const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/LeadSiteHome-D1Ps7r6E.js","assets/useLeadSiteSearchSuggestions-FtGtATcB.js","assets/CityPagesModule-DxGxdk7g.js","assets/ListingCarouselModule-Dna-qZ94.js","assets/imageOptimization-Csrlnz8M.js","assets/ExchangeListingsSection-BwYSBDbZ.js","assets/LeadSiteLuxuryHome-DiYdO3Un.js","assets/LeadSiteExchangeListings-mhjTuEDU.js","assets/LeadSiteLuxuryHome-DKt_VWIz.css","assets/LeadSiteLandRanchHome-BF86E2tB.js","assets/LeadSiteSearch-CItmwr1a.js","assets/LeadSiteListingCardImage-DH7CT-bc.js","assets/LeadSiteMap-Bef_MY_x.js","assets/LeadSiteLuxurySearch-GycJcAWg.js","assets/LeadSiteListingDetail-03jUD4Zz.js","assets/ListingVideoTour-Dkb9_t81.js","assets/useListingVideos-CwHgqTyb.js","assets/LeadSiteLuxuryListingDetail-CBr1v-j5.js","assets/LeadSiteCityPage-C5zFJDh0.js","assets/CityFaqSection-Dow2aDiV.js","assets/LeadSiteSubdivisionPage-Ab0LmhJH.js","assets/LeadSiteFocusPage-m8m5Ijxc.js","assets/OrgSiteAgents-BIaL63kf.js","assets/OrgSiteHome-C73w6xbd.js","assets/OrgSitePages-Cbr99MEL.js","assets/OrgSiteListings-laCxPlL0.js","assets/PublicLiveEvent-DDOjpQq_.js","assets/useLiveEngagement-BNdj9T_i.js","assets/LiveEventConsole-CJ83vGz0.js","assets/StagingStudio-UhlNOX7K.js","assets/presets-CVb6w-fA.js","assets/download-BqCckdNk.js","assets/BeforeAfterSlider-DWenl47Y.js","assets/BuyCreditsDialog-CnkAGEAX.js","assets/StagingLibrary-B0O8ALvq.js","assets/StagingCredits-qOjKWzxN.js","assets/StagingSharePage-DijPtdlH.js","assets/StagingStudioAdmin-Gd6Ix9Sd.js","assets/PostcardManager-BPcnvaGr.js","assets/usePostcardZones-roDs89vr.js","assets/DirectMail-dtSpGSCU.js","assets/LeadSiteEditor-Cu_FAIBr.js","assets/ImageUrlField-CYAlSExH.js","assets/HomepageModuleManager-C1rPMCwy.js","assets/LeadSiteEditor-BzY4kI8E.css","assets/AdminLeadSiteThemes-DxfBo2ia.js","assets/AdminFreeWebsiteOfferStudio-ahQGHPJY.js","assets/MLSListingDetail-BV18eD_6.js","assets/EmailCampaigns-B5KtB4Ng.js","assets/sesRequest-CPfuxEe-.js","assets/EmailCampaignComposer-DRaLekoo.js","assets/EditorModeSelector-CJls5e3f.js","assets/SharedCampaignTemplates-Cu9fwZkD.js","assets/TemplateEditorDialog-B7YLH1Bf.js","assets/AgentTemplates-Cr22xsEA.js","assets/TheLocalMoveHome-CEwrIj0I.js","assets/tlm-hero-bg-BbD3acLf.js","assets/TheLocalMoveGetStarted-DGLWVpgm.js"])))=>i.map(i=>d[i]); var Nhs=Object.defineProperty;var but=s=>{throw TypeError(s)};var khs=(s,t,n)=>t in s?Nhs(s,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):s[t]=n;var Pr=(s,t,n)=>khs(s,typeof t!="symbol"?t+"":t,n),lFe=(s,t,n)=>t.has(s)||but("Cannot "+n);var ye=(s,t,n)=>(lFe(s,t,"read from private field"),n?n.call(s):t.get(s)),us=(s,t,n)=>t.has(s)?but("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(s):t.set(s,n),Ut=(s,t,n,r)=>(lFe(s,t,"write to private field"),r?r.call(s,n):t.set(s,n),n),ts=(s,t,n)=>(lFe(s,t,"access private method"),n);var X0=(s,t,n,r)=>({set _(a){Ut(s,t,a,n)},get _(){return ye(s,t,r)}});function Shs(s,t){for(var n=0;nr[a]})}}}return Object.freeze(Object.defineProperty(s,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))r(a);new MutationObserver(a=>{for(const i of a)if(i.type==="childList")for(const l of i.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&r(l)}).observe(document,{childList:!0,subtree:!0});function n(a){const i={};return a.integrity&&(i.integrity=a.integrity),a.referrerPolicy&&(i.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?i.credentials="include":a.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(a){if(a.ep)return;a.ep=!0;const i=n(a);fetch(a.href,i)}})();var Cp=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function _d(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}function Chs(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 gEt={exports:{}},aMe={},yEt={exports:{}},zd={};/** * @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 fre=Symbol.for("react.element"),Ahs=Symbol.for("react.portal"),Ehs=Symbol.for("react.fragment"),Ths=Symbol.for("react.strict_mode"),Mhs=Symbol.for("react.profiler"),Phs=Symbol.for("react.provider"),Lhs=Symbol.for("react.context"),Ihs=Symbol.for("react.forward_ref"),Dhs=Symbol.for("react.suspense"),Rhs=Symbol.for("react.memo"),Fhs=Symbol.for("react.lazy"),_ut=Symbol.iterator;function Ohs(s){return s===null||typeof s!="object"?null:(s=_ut&&s[_ut]||s["@@iterator"],typeof s=="function"?s:null)}var vEt={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},bEt=Object.assign,_Et={};function HG(s,t,n){this.props=s,this.context=t,this.refs=_Et,this.updater=n||vEt}HG.prototype.isReactComponent={};HG.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")};HG.prototype.forceUpdate=function(s){this.updater.enqueueForceUpdate(this,s,"forceUpdate")};function wEt(){}wEt.prototype=HG.prototype;function FZe(s,t,n){this.props=s,this.context=t,this.refs=_Et,this.updater=n||vEt}var OZe=FZe.prototype=new wEt;OZe.constructor=FZe;bEt(OZe,HG.prototype);OZe.isPureReactComponent=!0;var wut=Array.isArray,jEt=Object.prototype.hasOwnProperty,zZe={current:null},NEt={key:!0,ref:!0,__self:!0,__source:!0};function kEt(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)jEt.call(t,r)&&!NEt.hasOwnProperty(r)&&(a[r]=t[r]);var o=arguments.length-2;if(o===1)a.children=n;else if(1>>1,ae=ne[te];if(0>>1;tea(me,ie))hea(pe,me)?(ne[te]=pe,ne[he]=ie,te=he):(ne[te]=me,ne[be]=ie,te=be);else if(hea(pe,ie))ne[te]=pe,ne[he]=ie,te=he;else break e}}return ce}function a(ne,ce){var ie=ne.sortIndex-ce.sortIndex;return ie!==0?ie:ne.id-ce.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;s.unstable_now=function(){return i.now()}}else{var l=Date,o=l.now();s.unstable_now=function(){return l.now()-o}}var c=[],d=[],u=1,h=null,m=3,p=!1,f=!1,y=!1,v=typeof setTimeout=="function"?setTimeout:null,g=typeof clearTimeout=="function"?clearTimeout:null,b=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function j(ne){for(var ce=n(d);ce!==null;){if(ce.callback===null)r(d);else if(ce.startTime<=ne)r(d),ce.sortIndex=ce.expirationTime,t(c,ce);else break;ce=n(d)}}function S(ne){if(y=!1,j(ne),!f)if(n(c)!==null)f=!0,Y(C);else{var ce=n(d);ce!==null&&Z(S,ce.startTime-ne)}}function C(ne,ce){f=!1,y&&(y=!1,g(M),M=-1),p=!0;var ie=m;try{for(j(ce),h=n(c);h!==null&&(!(h.expirationTime>ce)||ne&&!O());){var te=h.callback;if(typeof te=="function"){h.callback=null,m=h.priorityLevel;var ae=te(h.expirationTime<=ce);ce=s.unstable_now(),typeof ae=="function"?h.callback=ae:h===n(c)&&r(c),j(ce)}else r(c);h=n(c)}if(h!==null)var le=!0;else{var be=n(d);be!==null&&Z(S,be.startTime-ce),le=!1}return le}finally{h=null,m=ie,p=!1}}var E=!1,P=null,M=-1,I=5,D=-1;function O(){return!(s.unstable_now()-Dne||125te?(ne.sortIndex=ie,t(d,ne),n(c)===null&&ne===n(d)&&(y?(g(M),M=-1):y=!0,Z(S,ie-te))):(ne.sortIndex=ae,t(c,ne),f||p||(f=!0,Y(C))),ne},s.unstable_shouldYield=O,s.unstable_wrapCallback=function(ne){var ce=m;return function(){var ie=m;m=ce;try{return ne.apply(this,arguments)}finally{m=ie}}}})(TEt);EEt.exports=TEt;var iQ=EEt.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 Yhs=_,Cj=iQ;function ti(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"),BUe=Object.prototype.hasOwnProperty,Zhs=/^[: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]*$/,Nut={},kut={};function Xhs(s){return BUe.call(kut,s)?!0:BUe.call(Nut,s)?!1:Zhs.test(s)?kut[s]=!0:(Nut[s]=!0,!1)}function Qhs(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 Jhs(s,t,n,r){if(t===null||typeof t>"u"||Qhs(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 Lb(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 Av={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(s){Av[s]=new Lb(s,0,!1,s,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(s){var t=s[0];Av[t]=new Lb(t,1,!1,s[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(s){Av[s]=new Lb(s,2,!1,s.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(s){Av[s]=new Lb(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){Av[s]=new Lb(s,3,!1,s.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(s){Av[s]=new Lb(s,3,!0,s,null,!1,!1)});["capture","download"].forEach(function(s){Av[s]=new Lb(s,4,!1,s,null,!1,!1)});["cols","rows","size","span"].forEach(function(s){Av[s]=new Lb(s,6,!1,s,null,!1,!1)});["rowSpan","start"].forEach(function(s){Av[s]=new Lb(s,5,!1,s.toLowerCase(),null,!1,!1)});var qZe=/[\-:]([a-z])/g;function $Ze(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(qZe,$Ze);Av[t]=new Lb(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(qZe,$Ze);Av[t]=new Lb(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(qZe,$Ze);Av[t]=new Lb(t,1,!1,s,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(s){Av[s]=new Lb(s,1,!1,s.toLowerCase(),null,!1,!1)});Av.xlinkHref=new Lb("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(s){Av[s]=new Lb(s,1,!1,s.toLowerCase(),null,!0,!0)});function VZe(s,t,n,r){var a=Av.hasOwnProperty(t)?Av[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{uFe=!1,Error.prepareStackTrace=n}return(s=s?s.displayName||s.name:"")?nX(s):""}function ems(s){switch(s.tag){case 5:return nX(s.type);case 16:return nX("Lazy");case 13:return nX("Suspense");case 19:return nX("SuspenseList");case 0:case 2:case 15:return s=hFe(s.type,!1),s;case 11:return s=hFe(s.type.render,!1),s;case 1:return s=hFe(s.type,!0),s;default:return""}}function VUe(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 FU:return"Fragment";case RU:return"Portal";case UUe:return"Profiler";case HZe:return"StrictMode";case qUe:return"Suspense";case $Ue:return"SuspenseList"}if(typeof s=="object")switch(s.$$typeof){case LEt:return(s.displayName||"Context")+".Consumer";case PEt:return(s._context.displayName||"Context")+".Provider";case GZe:var t=s.render;return s=s.displayName,s||(s=t.displayName||t.name||"",s=s!==""?"ForwardRef("+s+")":"ForwardRef"),s;case WZe:return t=s.displayName||null,t!==null?t:VUe(s.type)||"Memo";case s6:t=s._payload,s=s._init;try{return VUe(s(t))}catch{}}return null}function tms(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 VUe(t);case 8:return t===HZe?"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 kP(s){switch(typeof s){case"boolean":case"number":case"string":case"undefined":return s;case"object":return s;default:return""}}function DEt(s){var t=s.type;return(s=s.nodeName)&&s.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function sms(s){var t=DEt(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 Ioe(s){s._valueTracker||(s._valueTracker=sms(s))}function REt(s){if(!s)return!1;var t=s._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return s&&(r=DEt(s)?s.checked?"true":"false":s.value),s=r,s!==n?(t.setValue(s),!0):!1}function h3e(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 HUe(s,t){var n=t.checked;return Kf({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??s._wrapperState.initialChecked})}function Cut(s,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=kP(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 FEt(s,t){t=t.checked,t!=null&&VZe(s,"checked",t,!1)}function GUe(s,t){FEt(s,t);var n=kP(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")?WUe(s,t.type,n):t.hasOwnProperty("defaultValue")&&WUe(s,t.type,kP(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(s.defaultChecked=!!t.defaultChecked)}function Aut(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 WUe(s,t,n){(t!=="number"||h3e(s.ownerDocument)!==s)&&(n==null?s.defaultValue=""+s._wrapperState.initialValue:s.defaultValue!==""+n&&(s.defaultValue=""+n))}var rX=Array.isArray;function wq(s,t,n,r){if(s=s.options,t){t={};for(var a=0;a"+t.valueOf().toString()+"",t=Doe.firstChild;s.firstChild;)s.removeChild(s.firstChild);for(;t.firstChild;)s.appendChild(t.firstChild)}});function Eee(s,t){if(t){var n=s.firstChild;if(n&&n===s.lastChild&&n.nodeType===3){n.nodeValue=t;return}}s.textContent=t}var oQ={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},nms=["Webkit","ms","Moz","O"];Object.keys(oQ).forEach(function(s){nms.forEach(function(t){t=t+s.charAt(0).toUpperCase()+s.substring(1),oQ[t]=oQ[s]})});function UEt(s,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||oQ.hasOwnProperty(s)&&oQ[s]?(""+t).trim():t+"px"}function qEt(s,t){s=s.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,a=UEt(n,t[n],r);n==="float"&&(n="cssFloat"),r?s.setProperty(n,a):s[n]=a}}var rms=Kf({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 ZUe(s,t){if(t){if(rms[s]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(ti(137,s));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(ti(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(ti(61))}if(t.style!=null&&typeof t.style!="object")throw Error(ti(62))}}function XUe(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 QUe=null;function KZe(s){return s=s.target||s.srcElement||window,s.correspondingUseElement&&(s=s.correspondingUseElement),s.nodeType===3?s.parentNode:s}var JUe=null,jq=null,Nq=null;function Mut(s){if(s=yre(s)){if(typeof JUe!="function")throw Error(ti(280));var t=s.stateNode;t&&(t=dMe(t),JUe(s.stateNode,s.type,t))}}function $Et(s){jq?Nq?Nq.push(s):Nq=[s]:jq=s}function VEt(){if(jq){var s=jq,t=Nq;if(Nq=jq=null,Mut(s),t)for(s=0;s>>=0,s===0?32:31-(fms(s)/xms|0)|0}var Roe=64,Foe=4194304;function aX(s){switch(s&-s){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return s&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return s&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return s}}function x3e(s,t){var n=s.pendingLanes;if(n===0)return 0;var r=0,a=s.suspendedLanes,i=s.pingedLanes,l=n&268435455;if(l!==0){var o=l&~a;o!==0?r=aX(o):(i&=l,i!==0&&(r=aX(i)))}else l=n&~a,l!==0?r=aX(l):i!==0&&(r=aX(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 xre(s,t,n){s.pendingLanes|=t,t!==536870912&&(s.suspendedLanes=0,s.pingedLanes=0),s=s.eventTimes,t=31-oS(t),s[t]=n}function bms(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=cQ),But=" ",Uut=!1;function dTt(s,t){switch(s){case"keyup":return Kms.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function uTt(s){return s=s.detail,typeof s=="object"&&"data"in s?s.data:null}var OU=!1;function Zms(s,t){switch(s){case"compositionend":return uTt(t);case"keypress":return t.which!==32?null:(Uut=!0,But);case"textInput":return s=t.data,s===But&&Uut?null:s;default:return null}}function Xms(s,t){if(OU)return s==="compositionend"||!sXe&&dTt(s,t)?(s=lTt(),Due=JZe=xM=null,OU=!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=Hut(n)}}function fTt(s,t){return s&&t?s===t?!0:s&&s.nodeType===3?!1:t&&t.nodeType===3?fTt(s,t.parentNode):"contains"in s?s.contains(t):s.compareDocumentPosition?!!(s.compareDocumentPosition(t)&16):!1:!1}function xTt(){for(var s=window,t=h3e();t instanceof s.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)s=t.contentWindow;else break;t=h3e(s.document)}return t}function nXe(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 ips(s){var t=xTt(),n=s.focusedElem,r=s.selectionRange;if(t!==n&&n&&n.ownerDocument&&fTt(n.ownerDocument.documentElement,n)){if(r!==null&&nXe(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=Gut(n,i);var l=Gut(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,zU=null,aqe=null,uQ=null,iqe=!1;function Wut(s,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;iqe||zU==null||zU!==h3e(r)||(r=zU,"selectionStart"in r&&nXe(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}),uQ&&Dee(uQ,r)||(uQ=r,r=v3e(aqe,"onSelect"),0qU||(s.current=hqe[qU],hqe[qU]=null,qU--)}function Jm(s,t){qU++,hqe[qU]=s.current,s.current=t}var SP={},y1=sL(SP),M_=sL(!1),O7=SP;function mH(s,t){var n=s.type.contextTypes;if(!n)return SP;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 P_(s){return s=s.childContextTypes,s!=null}function _3e(){Ap(M_),Ap(y1)}function eht(s,t,n){if(y1.current!==SP)throw Error(ti(168));Jm(y1,t),Jm(M_,n)}function kTt(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(ti(108,tms(s)||"Unknown",a));return Kf({},n,r)}function w3e(s){return s=(s=s.stateNode)&&s.__reactInternalMemoizedMergedChildContext||SP,O7=y1.current,Jm(y1,s),Jm(M_,M_.current),!0}function tht(s,t,n){var r=s.stateNode;if(!r)throw Error(ti(169));n?(s=kTt(s,t,O7),r.__reactInternalMemoizedMergedChildContext=s,Ap(M_),Ap(y1),Jm(y1,s)):Ap(M_),Jm(M_,n)}var W3=null,uMe=!1,SFe=!1;function STt(s){W3===null?W3=[s]:W3.push(s)}function yps(s){uMe=!0,STt(s)}function nL(){if(!SFe&&W3!==null){SFe=!0;var s=0,t=Gh;try{var n=W3;for(Gh=1;s>=l,a-=l,TA=1<<32-oS(t)+a|n<M?(I=P,P=null):I=P.sibling;var D=m(g,P,j[M],S);if(D===null){P===null&&(P=I);break}s&&P&&D.alternate===null&&t(g,P),b=i(D,b,M),E===null?C=D:E.sibling=D,E=D,P=I}if(M===j.length)return n(g,P),Jp&&II(g,M),C;if(P===null){for(;MM?(I=P,P=null):I=P.sibling;var O=m(g,P,D.value,S);if(O===null){P===null&&(P=I);break}s&&P&&O.alternate===null&&t(g,P),b=i(O,b,M),E===null?C=O:E.sibling=O,E=O,P=I}if(D.done)return n(g,P),Jp&&II(g,M),C;if(P===null){for(;!D.done;M++,D=j.next())D=h(g,D.value,S),D!==null&&(b=i(D,b,M),E===null?C=D:E.sibling=D,E=D);return Jp&&II(g,M),C}for(P=r(g,P);!D.done;M++,D=j.next())D=p(P,g,M,D.value,S),D!==null&&(s&&D.alternate!==null&&P.delete(D.key===null?M:D.key),b=i(D,b,M),E===null?C=D:E.sibling=D,E=D);return s&&P.forEach(function(V){return t(g,V)}),Jp&&II(g,M),C}function v(g,b,j,S){if(typeof j=="object"&&j!==null&&j.type===FU&&j.key===null&&(j=j.props.children),typeof j=="object"&&j!==null){switch(j.$$typeof){case Loe:e:{for(var C=j.key,E=b;E!==null;){if(E.key===C){if(C=j.type,C===FU){if(E.tag===7){n(g,E.sibling),b=a(E,j.props.children),b.return=g,g=b;break e}}else if(E.elementType===C||typeof C=="object"&&C!==null&&C.$$typeof===s6&&rht(C)===E.type){n(g,E.sibling),b=a(E,j.props),b.ref=kY(g,E,j),b.return=g,g=b;break e}n(g,E);break}else t(g,E);E=E.sibling}j.type===FU?(b=qO(j.props.children,g.mode,S,j.key),b.return=g,g=b):(S=$ue(j.type,j.key,j.props,null,g.mode,S),S.ref=kY(g,b,j),S.return=g,g=S)}return l(g);case RU:e:{for(E=j.key;b!==null;){if(b.key===E)if(b.tag===4&&b.stateNode.containerInfo===j.containerInfo&&b.stateNode.implementation===j.implementation){n(g,b.sibling),b=a(b,j.children||[]),b.return=g,g=b;break e}else{n(g,b);break}else t(g,b);b=b.sibling}b=IFe(j,g.mode,S),b.return=g,g=b}return l(g);case s6:return E=j._init,v(g,b,E(j._payload),S)}if(rX(j))return f(g,b,j,S);if(bY(j))return y(g,b,j,S);Voe(g,j)}return typeof j=="string"&&j!==""||typeof j=="number"?(j=""+j,b!==null&&b.tag===6?(n(g,b.sibling),b=a(b,j),b.return=g,g=b):(n(g,b),b=LFe(j,g.mode,S),b.return=g,g=b),l(g)):n(g,b)}return v}var fH=TTt(!0),MTt=TTt(!1),k3e=sL(null),S3e=null,HU=null,oXe=null;function lXe(){oXe=HU=S3e=null}function cXe(s){var t=k3e.current;Ap(k3e),s._currentValue=t}function fqe(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 Sq(s,t){S3e=s,oXe=HU=null,s=s.dependencies,s!==null&&s.firstContext!==null&&(s.lanes&t&&(N_=!0),s.firstContext=null)}function kN(s){var t=s._currentValue;if(oXe!==s)if(s={context:s,memoizedValue:t,next:null},HU===null){if(S3e===null)throw Error(ti(308));HU=s,S3e.dependencies={lanes:0,firstContext:s}}else HU=HU.next=s;return t}var lF=null;function dXe(s){lF===null?lF=[s]:lF.push(s)}function PTt(s,t,n,r){var a=t.interleaved;return a===null?(n.next=n,dXe(t)):(n.next=a.next,a.next=n),t.interleaved=n,xE(s,r)}function xE(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 n6=!1;function uXe(s){s.updateQueue={baseState:s.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function LTt(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 zA(s,t){return{eventTime:s,lane:t,tag:0,payload:null,callback:null,next:null}}function FM(s,t,n){var r=s.updateQueue;if(r===null)return null;if(r=r.shared,Du&2){var a=r.pending;return a===null?t.next=t:(t.next=a.next,a.next=t),r.pending=t,xE(s,n)}return a=r.interleaved,a===null?(t.next=t,dXe(r)):(t.next=a.next,a.next=t),r.interleaved=t,xE(s,n)}function Fue(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,ZZe(s,n)}}function aht(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 C3e(s,t,n,r){var a=s.updateQueue;n6=!1;var i=a.firstBaseUpdate,l=a.lastBaseUpdate,o=a.shared.pending;if(o!==null){a.shared.pending=null;var c=o,d=c.next;c.next=null,l===null?i=d:l.next=d,l=c;var u=s.alternate;u!==null&&(u=u.updateQueue,o=u.lastBaseUpdate,o!==l&&(o===null?u.firstBaseUpdate=d:o.next=d,u.lastBaseUpdate=c))}if(i!==null){var h=a.baseState;l=0,u=d=c=null,o=i;do{var m=o.lane,p=o.eventTime;if((r&m)===m){u!==null&&(u=u.next={eventTime:p,lane:0,tag:o.tag,payload:o.payload,callback:o.callback,next:null});e:{var f=s,y=o;switch(m=t,p=n,y.tag){case 1:if(f=y.payload,typeof f=="function"){h=f.call(p,h,m);break e}h=f;break e;case 3:f.flags=f.flags&-65537|128;case 0:if(f=y.payload,m=typeof f=="function"?f.call(p,h,m):f,m==null)break e;h=Kf({},h,m);break e;case 2:n6=!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);U7|=l,s.lanes=l,s.memoizedState=h}}function iht(s,t,n){if(s=t.effects,t.effects=null,s!==null)for(t=0;tn?n:4,s(!0);var r=AFe.transition;AFe.transition={};try{s(!1),t()}finally{Gh=n,AFe.transition=r}}function ZTt(){return SN().memoizedState}function wps(s,t,n){var r=zM(s);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},XTt(s))QTt(t,n);else if(n=PTt(s,t,n,r),n!==null){var a=bb();lS(n,s,r,a),JTt(n,t,r)}}function jps(s,t,n){var r=zM(s),a={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(XTt(s))QTt(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,kS(o,l)){var c=t.interleaved;c===null?(a.next=a,dXe(t)):(a.next=c.next,c.next=a),t.interleaved=a;return}}catch{}finally{}n=PTt(s,t,a,r),n!==null&&(a=bb(),lS(n,s,r,a),JTt(n,t,r))}}function XTt(s){var t=s.alternate;return s===Of||t!==null&&t===Of}function QTt(s,t){hQ=E3e=!0;var n=s.pending;n===null?t.next=t:(t.next=n.next,n.next=t),s.pending=t}function JTt(s,t,n){if(n&4194240){var r=t.lanes;r&=s.pendingLanes,n|=r,t.lanes=n,ZZe(s,n)}}var T3e={readContext:kN,useCallback:Hv,useContext:Hv,useEffect:Hv,useImperativeHandle:Hv,useInsertionEffect:Hv,useLayoutEffect:Hv,useMemo:Hv,useReducer:Hv,useRef:Hv,useState:Hv,useDebugValue:Hv,useDeferredValue:Hv,useTransition:Hv,useMutableSource:Hv,useSyncExternalStore:Hv,useId:Hv,unstable_isNewReconciler:!1},Nps={readContext:kN,useCallback:function(s,t){return z5().memoizedState=[s,t===void 0?null:t],s},useContext:kN,useEffect:lht,useImperativeHandle:function(s,t,n){return n=n!=null?n.concat([s]):null,zue(4194308,4,HTt.bind(null,t,s),n)},useLayoutEffect:function(s,t){return zue(4194308,4,s,t)},useInsertionEffect:function(s,t){return zue(4,2,s,t)},useMemo:function(s,t){var n=z5();return t=t===void 0?null:t,s=s(),n.memoizedState=[s,t],s},useReducer:function(s,t,n){var r=z5();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=wps.bind(null,Of,s),[r.memoizedState,s]},useRef:function(s){var t=z5();return s={current:s},t.memoizedState=s},useState:oht,useDebugValue:vXe,useDeferredValue:function(s){return z5().memoizedState=s},useTransition:function(){var s=oht(!1),t=s[0];return s=_ps.bind(null,s[1]),z5().memoizedState=s,[t,s]},useMutableSource:function(){},useSyncExternalStore:function(s,t,n){var r=Of,a=z5();if(Jp){if(n===void 0)throw Error(ti(407));n=n()}else{if(n=t(),vy===null)throw Error(ti(349));B7&30||FTt(r,t,n)}a.memoizedState=n;var i={value:n,getSnapshot:t};return a.queue=i,lht(zTt.bind(null,r,i,s),[s]),r.flags|=2048,$ee(9,OTt.bind(null,r,i,n,t),void 0,null),n},useId:function(){var s=z5(),t=vy.identifierPrefix;if(Jp){var n=MA,r=TA;n=(r&~(1<<32-oS(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=Uee++,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[b4]=t,s[Oee]=r,c6t(s,t,!1,!1),t.stateNode=s;e:{switch(l=XUe(n,r),n){case"dialog":vp("cancel",s),vp("close",s),a=r;break;case"iframe":case"object":case"embed":vp("load",s),a=r;break;case"video":case"audio":for(a=0;ayH&&(t.flags|=128,r=!0,SY(i,!1),t.lanes=4194304)}else{if(!r)if(s=A3e(l),s!==null){if(t.flags|=128,r=!0,n=s.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),SY(i,!0),i.tail===null&&i.tailMode==="hidden"&&!l.alternate&&!Jp)return Gv(t),null}else 2*Zx()-i.renderingStartTime>yH&&n!==1073741824&&(t.flags|=128,r=!0,SY(i,!1),t.lanes=4194304);i.isBackwards?(l.sibling=t.child,t.child=l):(n=i.last,n!==null?n.sibling=l:t.child=l,i.last=l)}return i.tail!==null?(t=i.tail,i.rendering=t,i.tail=t.sibling,i.renderingStartTime=Zx(),t.sibling=null,n=Ef.current,Jm(Ef,r?n&1|2:n&1),t):(Gv(t),null);case 22:case 23:return kXe(),r=t.memoizedState!==null,s!==null&&s.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?Vw&1073741824&&(Gv(t),t.subtreeFlags&6&&(t.flags|=8192)):Gv(t),null;case 24:return null;case 25:return null}throw Error(ti(156,t.tag))}function Pps(s,t){switch(aXe(t),t.tag){case 1:return P_(t.type)&&_3e(),s=t.flags,s&65536?(t.flags=s&-65537|128,t):null;case 3:return xH(),Ap(M_),Ap(y1),pXe(),s=t.flags,s&65536&&!(s&128)?(t.flags=s&-65537|128,t):null;case 5:return mXe(t),null;case 13:if(Ap(Ef),s=t.memoizedState,s!==null&&s.dehydrated!==null){if(t.alternate===null)throw Error(ti(340));pH()}return s=t.flags,s&65536?(t.flags=s&-65537|128,t):null;case 19:return Ap(Ef),null;case 4:return xH(),null;case 10:return cXe(t.type._context),null;case 22:case 23:return kXe(),null;case 24:return null;default:return null}}var Goe=!1,l1=!1,Lps=typeof WeakSet=="function"?WeakSet:Set,xo=null;function GU(s,t){var n=s.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){fx(s,t,r)}else n.current=null}function Nqe(s,t,n){try{n()}catch(r){fx(s,t,r)}}var vht=!1;function Ips(s,t){if(oqe=g3e,s=xTt(),nXe(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(lqe={focusedElem:s,selectionRange:n},g3e=!1,xo=t;xo!==null;)if(t=xo,s=t.child,(t.subtreeFlags&1028)!==0&&s!==null)s.return=t,xo=s;else for(;xo!==null;){t=xo;try{var f=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(f!==null){var y=f.memoizedProps,v=f.memoizedState,g=t.stateNode,b=g.getSnapshotBeforeUpdate(t.elementType===t.type?y:Ak(t.type,y),v);g.__reactInternalSnapshotBeforeUpdate=b}break;case 3:var j=t.stateNode.containerInfo;j.nodeType===1?j.textContent="":j.nodeType===9&&j.documentElement&&j.removeChild(j.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(ti(163))}}catch(S){fx(t,t.return,S)}if(s=t.sibling,s!==null){s.return=t.return,xo=s;break}xo=t.return}return f=vht,vht=!1,f}function mQ(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&&Nqe(t,n,i)}a=a.next}while(a!==r)}}function pMe(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 kqe(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 h6t(s){var t=s.alternate;t!==null&&(s.alternate=null,h6t(t)),s.child=null,s.deletions=null,s.sibling=null,s.tag===5&&(t=s.stateNode,t!==null&&(delete t[b4],delete t[Oee],delete t[uqe],delete t[xps],delete t[gps])),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 m6t(s){return s.tag===5||s.tag===3||s.tag===4}function bht(s){e:for(;;){for(;s.sibling===null;){if(s.return===null||m6t(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 Sqe(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=b3e));else if(r!==4&&(s=s.child,s!==null))for(Sqe(s,t,n),s=s.sibling;s!==null;)Sqe(s,t,n),s=s.sibling}function Cqe(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(Cqe(s,t,n),s=s.sibling;s!==null;)Cqe(s,t,n),s=s.sibling}var nv=null,Hk=!1;function xT(s,t,n){for(n=n.child;n!==null;)p6t(s,t,n),n=n.sibling}function p6t(s,t,n){if(z4&&typeof z4.onCommitFiberUnmount=="function")try{z4.onCommitFiberUnmount(iMe,n)}catch{}switch(n.tag){case 5:l1||GU(n,t);case 6:var r=nv,a=Hk;nv=null,xT(s,t,n),nv=r,Hk=a,nv!==null&&(Hk?(s=nv,n=n.stateNode,s.nodeType===8?s.parentNode.removeChild(n):s.removeChild(n)):nv.removeChild(n.stateNode));break;case 18:nv!==null&&(Hk?(s=nv,n=n.stateNode,s.nodeType===8?kFe(s.parentNode,n):s.nodeType===1&&kFe(s,n),Lee(s)):kFe(nv,n.stateNode));break;case 4:r=nv,a=Hk,nv=n.stateNode.containerInfo,Hk=!0,xT(s,t,n),nv=r,Hk=a;break;case 0:case 11:case 14:case 15:if(!l1&&(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)&&Nqe(n,t,l),a=a.next}while(a!==r)}xT(s,t,n);break;case 1:if(!l1&&(GU(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(o){fx(n,t,o)}xT(s,t,n);break;case 21:xT(s,t,n);break;case 22:n.mode&1?(l1=(r=l1)||n.memoizedState!==null,xT(s,t,n),l1=r):xT(s,t,n);break;default:xT(s,t,n)}}function _ht(s){var t=s.updateQueue;if(t!==null){s.updateQueue=null;var n=s.stateNode;n===null&&(n=s.stateNode=new Lps),t.forEach(function(r){var a=$ps.bind(null,s,r);n.has(r)||(n.add(r),r.then(a,a))})}}function mk(s,t){var n=t.deletions;if(n!==null)for(var r=0;ra&&(a=l),r&=~i}if(r=a,r=Zx()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*Rps(r/1960))-r,10s?16:s,gM===null)var r=!1;else{if(s=gM,gM=null,L3e=0,Du&6)throw Error(ti(331));var a=Du;for(Du|=4,xo=s.current;xo!==null;){var i=xo,l=i.child;if(xo.flags&16){var o=i.deletions;if(o!==null){for(var c=0;cZx()-jXe?UO(s,0):wXe|=n),L_(s,t)}function w6t(s,t){t===0&&(s.mode&1?(t=Foe,Foe<<=1,!(Foe&130023424)&&(Foe=4194304)):t=1);var n=bb();s=xE(s,t),s!==null&&(xre(s,t,n),L_(s,n))}function qps(s){var t=s.memoizedState,n=0;t!==null&&(n=t.retryLane),w6t(s,n)}function $ps(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(ti(314))}r!==null&&r.delete(t),w6t(s,n)}var j6t;j6t=function(s,t,n){if(s!==null)if(s.memoizedProps!==t.pendingProps||M_.current)N_=!0;else{if(!(s.lanes&n)&&!(t.flags&128))return N_=!1,Tps(s,t,n);N_=!!(s.flags&131072)}else N_=!1,Jp&&t.flags&1048576&&CTt(t,N3e,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;Bue(s,t),s=t.pendingProps;var a=mH(t,y1.current);Sq(t,n),a=xXe(null,t,r,s,a,n);var i=gXe();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,P_(r)?(i=!0,w3e(t)):i=!1,t.memoizedState=a.state!==null&&a.state!==void 0?a.state:null,uXe(t),a.updater=mMe,t.stateNode=a,a._reactInternals=t,gqe(t,r,s,n),t=bqe(null,t,r,!0,i,n)):(t.tag=0,Jp&&i&&rXe(t),nb(null,t,a,n),t=t.child),t;case 16:r=t.elementType;e:{switch(Bue(s,t),s=t.pendingProps,a=r._init,r=a(r._payload),t.type=r,a=t.tag=Hps(r),s=Ak(r,s),a){case 0:t=vqe(null,t,r,s,n);break e;case 1:t=xht(null,t,r,s,n);break e;case 11:t=pht(null,t,r,s,n);break e;case 14:t=fht(null,t,r,Ak(r.type,s),n);break e}throw Error(ti(306,r,""))}return t;case 0:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:Ak(r,a),vqe(s,t,r,a,n);case 1:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:Ak(r,a),xht(s,t,r,a,n);case 3:e:{if(i6t(t),s===null)throw Error(ti(387));r=t.pendingProps,i=t.memoizedState,a=i.element,LTt(s,t),C3e(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=gH(Error(ti(423)),t),t=ght(s,t,r,n,a);break e}else if(r!==a){a=gH(Error(ti(424)),t),t=ght(s,t,r,n,a);break e}else for(tj=RM(t.stateNode.containerInfo.firstChild),cj=t,Jp=!0,Xk=null,n=MTt(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(pH(),r===a){t=gE(s,t,n);break e}nb(s,t,r,n)}t=t.child}return t;case 5:return ITt(t),s===null&&pqe(t),r=t.type,a=t.pendingProps,i=s!==null?s.memoizedProps:null,l=a.children,cqe(r,a)?l=null:i!==null&&cqe(r,i)&&(t.flags|=32),a6t(s,t),nb(s,t,l,n),t.child;case 6:return s===null&&pqe(t),null;case 13:return o6t(s,t,n);case 4:return hXe(t,t.stateNode.containerInfo),r=t.pendingProps,s===null?t.child=fH(t,null,r,n):nb(s,t,r,n),t.child;case 11:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:Ak(r,a),pht(s,t,r,a,n);case 7:return nb(s,t,t.pendingProps,n),t.child;case 8:return nb(s,t,t.pendingProps.children,n),t.child;case 12:return nb(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,Jm(k3e,r._currentValue),r._currentValue=l,i!==null)if(kS(i.value,l)){if(i.children===a.children&&!M_.current){t=gE(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=zA(-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),fqe(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(ti(341));l.lanes|=n,o=l.alternate,o!==null&&(o.lanes|=n),fqe(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}nb(s,t,a.children,n),t=t.child}return t;case 9:return a=t.type,r=t.pendingProps.children,Sq(t,n),a=kN(a),r=r(a),t.flags|=1,nb(s,t,r,n),t.child;case 14:return r=t.type,a=Ak(r,t.pendingProps),a=Ak(r.type,a),fht(s,t,r,a,n);case 15:return n6t(s,t,t.type,t.pendingProps,n);case 17:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:Ak(r,a),Bue(s,t),t.tag=1,P_(r)?(s=!0,w3e(t)):s=!1,Sq(t,n),e6t(t,r,a),gqe(t,r,a,n),bqe(null,t,r,!0,s,n);case 19:return l6t(s,t,n);case 22:return r6t(s,t,n)}throw Error(ti(156,t.tag))};function N6t(s,t){return XEt(s,t)}function Vps(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 sN(s,t,n,r){return new Vps(s,t,n,r)}function CXe(s){return s=s.prototype,!(!s||!s.isReactComponent)}function Hps(s){if(typeof s=="function")return CXe(s)?1:0;if(s!=null){if(s=s.$$typeof,s===GZe)return 11;if(s===WZe)return 14}return 2}function BM(s,t){var n=s.alternate;return n===null?(n=sN(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 $ue(s,t,n,r,a,i){var l=2;if(r=s,typeof s=="function")CXe(s)&&(l=1);else if(typeof s=="string")l=5;else e:switch(s){case FU:return qO(n.children,a,i,t);case HZe:l=8,a|=8;break;case UUe:return s=sN(12,n,t,a|2),s.elementType=UUe,s.lanes=i,s;case qUe:return s=sN(13,n,t,a),s.elementType=qUe,s.lanes=i,s;case $Ue:return s=sN(19,n,t,a),s.elementType=$Ue,s.lanes=i,s;case IEt:return xMe(n,a,i,t);default:if(typeof s=="object"&&s!==null)switch(s.$$typeof){case PEt:l=10;break e;case LEt:l=9;break e;case GZe:l=11;break e;case WZe:l=14;break e;case s6:l=16,r=null;break e}throw Error(ti(130,s==null?s:typeof s,""))}return t=sN(l,n,t,a),t.elementType=s,t.type=r,t.lanes=i,t}function qO(s,t,n,r){return s=sN(7,s,r,t),s.lanes=n,s}function xMe(s,t,n,r){return s=sN(22,s,r,t),s.elementType=IEt,s.lanes=n,s.stateNode={isHidden:!1},s}function LFe(s,t,n){return s=sN(6,s,null,t),s.lanes=n,s}function IFe(s,t,n){return t=sN(4,s.children!==null?s.children:[],s.key,t),t.lanes=n,t.stateNode={containerInfo:s.containerInfo,pendingChildren:null,implementation:s.implementation},t}function Gps(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=pFe(0),this.expirationTimes=pFe(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=pFe(0),this.identifierPrefix=r,this.onRecoverableError=a,this.mutableSourceEagerHydrationData=null}function AXe(s,t,n,r,a,i,l,o,c){return s=new Gps(s,t,n,o,c),t===1?(t=1,i===!0&&(t|=8)):t=0,i=sN(3,null,null,t),s.current=i,i.stateNode=s,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},uXe(i),s}function Wps(s,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(A6t)}catch(s){console.error(s)}}A6t(),AEt.exports=Oj;var mv=AEt.exports;const PXe=_d(mv);var E6t,Eht=mv;E6t=Eht.createRoot,Eht.hydrateRoot;const Qps="modulepreload",Jps=function(s){return"/"+s},Tht={},za=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=Jps(c),c in Tht)return;Tht[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":Qps,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)})},efs=new Set(["localhost","relevelup.com","thelocalmove.com","www.thelocalmove.com"]),tfs=s=>s.toLowerCase().replace(/:\d+$/,"").replace(/^www\./,"");function sfs(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")||efs.has(s))}function T6t(s){return M6t(s)!==null}function M6t(s){const t=tfs(s);return sfs(t)?null:t}const nfs=1,rfs=1e6;let DFe=0;function afs(){return DFe=(DFe+1)%Number.MAX_SAFE_INTEGER,DFe.toString()}const RFe=new Map,Mht=s=>{if(RFe.has(s))return;const t=setTimeout(()=>{RFe.delete(s),xQ({type:"REMOVE_TOAST",toastId:s})},rfs);RFe.set(s,t)},ifs=(s,t)=>{switch(t.type){case"ADD_TOAST":return{...s,toasts:[t.toast,...s.toasts].slice(0,nfs)};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?Mht(n):s.toasts.forEach(r=>{Mht(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)}}},Vue=[];let Hue={toasts:[]};function xQ(s){Hue=ifs(Hue,s),Vue.forEach(t=>{t(Hue)})}function ia({...s}){const t=afs(),n=a=>xQ({type:"UPDATE_TOAST",toast:{...a,id:t}}),r=()=>xQ({type:"DISMISS_TOAST",toastId:t});return xQ({type:"ADD_TOAST",toast:{...s,id:t,open:!0,onOpenChange:a=>{a||r()}}}),{id:t,dismiss:r,update:n}}function vi(){const[s,t]=_.useState(Hue);return _.useEffect(()=>(Vue.push(t),()=>{const n=Vue.indexOf(t);n>-1&&Vue.splice(n,1)}),[s]),{...s,toast:ia,dismiss:n=>xQ({type:"DISMISS_TOAST",toastId:n})}}function wa(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 Pht(s,t){if(typeof s=="function")return s(t);s!=null&&(s.current=t)}function yE(...s){return t=>{let n=!1;const r=s.map(a=>{const i=Pht(a,t);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let a=0;a{const{children:l,...o}=i,c=_.useMemo(()=>o,Object.values(o));return e.jsx(n.Provider,{value:c,children:l})};r.displayName=s+"Provider";function a(i){const l=_.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 af(s,t=[]){let n=[];function r(i,l){const o=_.createContext(l),c=n.length;n=[...n,l];const d=h=>{var g;const{scope:m,children:p,...f}=h,y=((g=m==null?void 0:m[s])==null?void 0:g[c])||o,v=_.useMemo(()=>f,Object.values(f));return e.jsx(y.Provider,{value:v,children:p})};d.displayName=i+"Provider";function u(h,m){var y;const p=((y=m==null?void 0:m[s])==null?void 0:y[c])||o,f=_.useContext(p);if(f)return f;if(l!==void 0)return l;throw new Error(`\`${h}\` must be used within \`${i}\``)}return[d,u]}const a=()=>{const i=n.map(l=>_.createContext(l));return function(o){const c=(o==null?void 0:o[s])||i;return _.useMemo(()=>({[`__scope${s}`]:{...o,[s]:c}}),[o,c])}};return a.scopeName=s,[r,lfs(a,...t)]}function lfs(...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 _.useMemo(()=>({[`__scope${t.scopeName}`]:l}),[l])}};return n.scopeName=t.scopeName,n}function CP(s){const t=cfs(s),n=_.forwardRef((r,a)=>{const{children:i,...l}=r,o=_.Children.toArray(i),c=o.find(dfs);if(c){const d=c.props.children,u=o.map(h=>h===c?_.Children.count(d)>1?_.Children.only(null):_.isValidElement(d)?d.props.children:null:h);return e.jsx(t,{...l,ref:a,children:_.isValidElement(d)?_.cloneElement(d,void 0,u):null})}return e.jsx(t,{...l,ref:a,children:i})});return n.displayName=`${s}.Slot`,n}var LXe=CP("Slot");function cfs(s){const t=_.forwardRef((n,r)=>{const{children:a,...i}=n;if(_.isValidElement(a)){const l=hfs(a),o=ufs(i,a.props);return a.type!==_.Fragment&&(o.ref=r?yE(r,l):l),_.cloneElement(a,o)}return _.Children.count(a)>1?_.Children.only(null):null});return t.displayName=`${s}.SlotClone`,t}var P6t=Symbol("radix.slottable");function L6t(s){const t=({children:n})=>e.jsx(e.Fragment,{children:n});return t.displayName=`${s}.Slottable`,t.__radixId=P6t,t}function dfs(s){return _.isValidElement(s)&&typeof s.type=="function"&&"__radixId"in s.type&&s.type.__radixId===P6t}function ufs(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 hfs(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 KG(s){const t=s+"CollectionProvider",[n,r]=af(t),[a,i]=n(t,{collectionRef:{current:null},itemMap:new Map}),l=y=>{const{scope:v,children:g}=y,b=Dt.useRef(null),j=Dt.useRef(new Map).current;return e.jsx(a,{scope:v,itemMap:j,collectionRef:b,children:g})};l.displayName=t;const o=s+"CollectionSlot",c=CP(o),d=Dt.forwardRef((y,v)=>{const{scope:g,children:b}=y,j=i(o,g),S=Qo(v,j.collectionRef);return e.jsx(c,{ref:S,children:b})});d.displayName=o;const u=s+"CollectionItemSlot",h="data-radix-collection-item",m=CP(u),p=Dt.forwardRef((y,v)=>{const{scope:g,children:b,...j}=y,S=Dt.useRef(null),C=Qo(v,S),E=i(u,g);return Dt.useEffect(()=>(E.itemMap.set(S,{ref:S,...j}),()=>void E.itemMap.delete(S))),e.jsx(m,{[h]:"",ref:C,children:b})});p.displayName=u;function f(y){const v=i(s+"CollectionConsumer",y);return Dt.useCallback(()=>{const b=v.collectionRef.current;if(!b)return[];const j=Array.from(b.querySelectorAll(`[${h}]`));return Array.from(v.itemMap.values()).sort((E,P)=>j.indexOf(E.ref.current)-j.indexOf(P.ref.current))},[v.collectionRef,v.itemMap])}return[{Provider:l,Slot:d,ItemSlot:p},f,r]}var mfs=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],ii=mfs.reduce((s,t)=>{const n=CP(`Primitive.${t}`),r=_.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 IXe(s,t){s&&mv.flushSync(()=>s.dispatchEvent(t))}function wx(s){const t=_.useRef(s);return _.useEffect(()=>{t.current=s}),_.useMemo(()=>(...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)},[])}function pfs(s,t=globalThis==null?void 0:globalThis.document){const n=wx(s);_.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 ffs="DismissableLayer",Pqe="dismissableLayer.update",xfs="dismissableLayer.pointerDownOutside",gfs="dismissableLayer.focusOutside",Lht,I6t=_.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),rL=_.forwardRef((s,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:a,onFocusOutside:i,onInteractOutside:l,onDismiss:o,...c}=s,d=_.useContext(I6t),[u,h]=_.useState(null),m=(u==null?void 0:u.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,p]=_.useState({}),f=Qo(t,P=>h(P)),y=Array.from(d.layers),[v]=[...d.layersWithOutsidePointerEventsDisabled].slice(-1),g=y.indexOf(v),b=u?y.indexOf(u):-1,j=d.layersWithOutsidePointerEventsDisabled.size>0,S=b>=g,C=vfs(P=>{const M=P.target,I=[...d.branches].some(D=>D.contains(M));!S||I||(a==null||a(P),l==null||l(P),P.defaultPrevented||o==null||o())},m),E=bfs(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 pfs(P=>{b===d.layers.size-1&&(r==null||r(P),!P.defaultPrevented&&o&&(P.preventDefault(),o()))},m),_.useEffect(()=>{if(u)return n&&(d.layersWithOutsidePointerEventsDisabled.size===0&&(Lht=m.body.style.pointerEvents,m.body.style.pointerEvents="none"),d.layersWithOutsidePointerEventsDisabled.add(u)),d.layers.add(u),Iht(),()=>{n&&d.layersWithOutsidePointerEventsDisabled.size===1&&(m.body.style.pointerEvents=Lht)}},[u,m,n,d]),_.useEffect(()=>()=>{u&&(d.layers.delete(u),d.layersWithOutsidePointerEventsDisabled.delete(u),Iht())},[u,d]),_.useEffect(()=>{const P=()=>p({});return document.addEventListener(Pqe,P),()=>document.removeEventListener(Pqe,P)},[]),e.jsx(ii.div,{...c,ref:f,style:{pointerEvents:j?S?"auto":"none":void 0,...s.style},onFocusCapture:wa(s.onFocusCapture,E.onFocusCapture),onBlurCapture:wa(s.onBlurCapture,E.onBlurCapture),onPointerDownCapture:wa(s.onPointerDownCapture,C.onPointerDownCapture)})});rL.displayName=ffs;var yfs="DismissableLayerBranch",D6t=_.forwardRef((s,t)=>{const n=_.useContext(I6t),r=_.useRef(null),a=Qo(t,r);return _.useEffect(()=>{const i=r.current;if(i)return n.branches.add(i),()=>{n.branches.delete(i)}},[n.branches]),e.jsx(ii.div,{...s,ref:a})});D6t.displayName=yfs;function vfs(s,t=globalThis==null?void 0:globalThis.document){const n=wx(s),r=_.useRef(!1),a=_.useRef(()=>{});return _.useEffect(()=>{const i=o=>{if(o.target&&!r.current){let c=function(){R6t(xfs,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 bfs(s,t=globalThis==null?void 0:globalThis.document){const n=wx(s),r=_.useRef(!1);return _.useEffect(()=>{const a=i=>{i.target&&!r.current&&R6t(gfs,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 Iht(){const s=new CustomEvent(Pqe);document.dispatchEvent(s)}function R6t(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?IXe(a,i):a.dispatchEvent(i)}var _fs=rL,wfs=D6t,Mx=globalThis!=null&&globalThis.document?_.useLayoutEffect:()=>{},jfs="Portal",YG=_.forwardRef((s,t)=>{var o;const{container:n,...r}=s,[a,i]=_.useState(!1);Mx(()=>i(!0),[]);const l=n||a&&((o=globalThis==null?void 0:globalThis.document)==null?void 0:o.body);return l?PXe.createPortal(e.jsx(ii.div,{...r,ref:t}),l):null});YG.displayName=jfs;function Nfs(s,t){return _.useReducer((n,r)=>t[n][r]??n,s)}var pg=s=>{const{present:t,children:n}=s,r=kfs(t),a=typeof n=="function"?n({present:r.isPresent}):_.Children.only(n),i=Qo(r.ref,Sfs(a));return typeof n=="function"||r.isPresent?_.cloneElement(a,{ref:i}):null};pg.displayName="Presence";function kfs(s){const[t,n]=_.useState(),r=_.useRef(null),a=_.useRef(s),i=_.useRef("none"),l=s?"mounted":"unmounted",[o,c]=Nfs(l,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return _.useEffect(()=>{const d=Yoe(r.current);i.current=o==="mounted"?d:"none"},[o]),Mx(()=>{const d=r.current,u=a.current;if(u!==s){const m=i.current,p=Yoe(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]),Mx(()=>{if(t){let d;const u=t.ownerDocument.defaultView??window,h=p=>{const y=Yoe(r.current).includes(p.animationName);if(p.target===t&&y&&(c("ANIMATION_END"),!a.current)){const v=t.style.animationFillMode;t.style.animationFillMode="forwards",d=u.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=v)})}},m=p=>{p.target===t&&(i.current=Yoe(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:_.useCallback(d=>{r.current=d?getComputedStyle(d):null,n(d)},[])}}function Yoe(s){return(s==null?void 0:s.animationName)||"none"}function Sfs(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 Cfs=UZe[" useInsertionEffect ".trim().toString()]||Mx;function Ug({prop:s,defaultProp:t,onChange:n=()=>{},caller:r}){const[a,i,l]=Afs({defaultProp:t,onChange:n}),o=s!==void 0,c=o?s:a;{const u=_.useRef(s!==void 0);_.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=_.useCallback(u=>{var h;if(o){const m=Efs(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 Afs({defaultProp:s,onChange:t}){const[n,r]=_.useState(s),a=_.useRef(n),i=_.useRef(t);return Cfs(()=>{i.current=t},[t]),_.useEffect(()=>{var l;a.current!==n&&((l=i.current)==null||l.call(i,n),a.current=n)},[n,a]),[n,r,i]}function Efs(s){return typeof s=="function"}var F6t=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"}),Tfs="VisuallyHidden",_Me=_.forwardRef((s,t)=>e.jsx(ii.span,{...s,ref:t,style:{...F6t,...s.style}}));_Me.displayName=Tfs;var Mfs=_Me,DXe="ToastProvider",[RXe,Pfs,Lfs]=KG("Toast"),[O6t,nbr]=af("Toast",[Lfs]),[Ifs,wMe]=O6t(DXe),z6t=s=>{const{__scopeToast:t,label:n="Notification",duration:r=5e3,swipeDirection:a="right",swipeThreshold:i=50,children:l}=s,[o,c]=_.useState(null),[d,u]=_.useState(0),h=_.useRef(!1),m=_.useRef(!1);return n.trim()||console.error(`Invalid prop \`label\` supplied to \`${DXe}\`. Expected non-empty \`string\`.`),e.jsx(RXe.Provider,{scope:t,children:e.jsx(Ifs,{scope:t,label:n,duration:r,swipeDirection:a,swipeThreshold:i,toastCount:d,viewport:o,onViewportChange:c,onToastAdd:_.useCallback(()=>u(p=>p+1),[]),onToastRemove:_.useCallback(()=>u(p=>p-1),[]),isFocusedToastEscapeKeyDownRef:h,isClosePausedRef:m,children:l})})};z6t.displayName=DXe;var B6t="ToastViewport",Dfs=["F8"],Lqe="toast.viewportPause",Iqe="toast.viewportResume",U6t=_.forwardRef((s,t)=>{const{__scopeToast:n,hotkey:r=Dfs,label:a="Notifications ({hotkey})",...i}=s,l=wMe(B6t,n),o=Pfs(n),c=_.useRef(null),d=_.useRef(null),u=_.useRef(null),h=_.useRef(null),m=Qo(t,h,l.onViewportChange),p=r.join("+").replace(/Key/g,"").replace(/Digit/g,""),f=l.toastCount>0;_.useEffect(()=>{const v=g=>{var j;r.length!==0&&r.every(S=>g[S]||g.code===S)&&((j=h.current)==null||j.focus())};return document.addEventListener("keydown",v),()=>document.removeEventListener("keydown",v)},[r]),_.useEffect(()=>{const v=c.current,g=h.current;if(f&&v&&g){const b=()=>{if(!l.isClosePausedRef.current){const E=new CustomEvent(Lqe);g.dispatchEvent(E),l.isClosePausedRef.current=!0}},j=()=>{if(l.isClosePausedRef.current){const E=new CustomEvent(Iqe);g.dispatchEvent(E),l.isClosePausedRef.current=!1}},S=E=>{!v.contains(E.relatedTarget)&&j()},C=()=>{v.contains(document.activeElement)||j()};return v.addEventListener("focusin",b),v.addEventListener("focusout",S),v.addEventListener("pointermove",b),v.addEventListener("pointerleave",C),window.addEventListener("blur",b),window.addEventListener("focus",j),()=>{v.removeEventListener("focusin",b),v.removeEventListener("focusout",S),v.removeEventListener("pointermove",b),v.removeEventListener("pointerleave",C),window.removeEventListener("blur",b),window.removeEventListener("focus",j)}}},[f,l.isClosePausedRef]);const y=_.useCallback(({tabbingDirection:v})=>{const b=o().map(j=>{const S=j.ref.current,C=[S,...Kfs(S)];return v==="forwards"?C:C.reverse()});return(v==="forwards"?b.reverse():b).flat()},[o]);return _.useEffect(()=>{const v=h.current;if(v){const g=b=>{var C,E,P;const j=b.altKey||b.ctrlKey||b.metaKey;if(b.key==="Tab"&&!j){const M=document.activeElement,I=b.shiftKey;if(b.target===v&&I){(C=d.current)==null||C.focus();return}const V=y({tabbingDirection:I?"backwards":"forwards"}),G=V.findIndex($=>$===M);FFe(V.slice(G+1))?b.preventDefault():I?(E=d.current)==null||E.focus():(P=u.current)==null||P.focus()}};return v.addEventListener("keydown",g),()=>v.removeEventListener("keydown",g)}},[o,y]),e.jsxs(wfs,{ref:c,role:"region","aria-label":a.replace("{hotkey}",p),tabIndex:-1,style:{pointerEvents:f?void 0:"none"},children:[f&&e.jsx(Dqe,{ref:d,onFocusFromOutsideViewport:()=>{const v=y({tabbingDirection:"forwards"});FFe(v)}}),e.jsx(RXe.Slot,{scope:n,children:e.jsx(ii.ol,{tabIndex:-1,...i,ref:m})}),f&&e.jsx(Dqe,{ref:u,onFocusFromOutsideViewport:()=>{const v=y({tabbingDirection:"backwards"});FFe(v)}})]})});U6t.displayName=B6t;var q6t="ToastFocusProxy",Dqe=_.forwardRef((s,t)=>{const{__scopeToast:n,onFocusFromOutsideViewport:r,...a}=s,i=wMe(q6t,n);return e.jsx(_Me,{"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()}})});Dqe.displayName=q6t;var bre="Toast",Rfs="toast.swipeStart",Ffs="toast.swipeMove",Ofs="toast.swipeCancel",zfs="toast.swipeEnd",$6t=_.forwardRef((s,t)=>{const{forceMount:n,open:r,defaultOpen:a,onOpenChange:i,...l}=s,[o,c]=Ug({prop:r,defaultProp:a??!0,onChange:i,caller:bre});return e.jsx(pg,{present:n||o,children:e.jsx(qfs,{open:o,...l,ref:t,onClose:()=>c(!1),onPause:wx(s.onPause),onResume:wx(s.onResume),onSwipeStart:wa(s.onSwipeStart,d=>{d.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:wa(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:wa(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:wa(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)})})})});$6t.displayName=bre;var[Bfs,Ufs]=O6t(bre,{onClose(){}}),qfs=_.forwardRef((s,t)=>{const{__scopeToast:n,type:r="foreground",duration:a,open:i,onClose:l,onEscapeKeyDown:o,onPause:c,onResume:d,onSwipeStart:u,onSwipeMove:h,onSwipeCancel:m,onSwipeEnd:p,...f}=s,y=wMe(bre,n),[v,g]=_.useState(null),b=Qo(t,$=>g($)),j=_.useRef(null),S=_.useRef(null),C=a||y.duration,E=_.useRef(0),P=_.useRef(C),M=_.useRef(0),{onToastAdd:I,onToastRemove:D}=y,O=wx(()=>{var H;(v==null?void 0:v.contains(document.activeElement))&&((H=y.viewport)==null||H.focus()),l()}),V=_.useCallback($=>{!$||$===1/0||(window.clearTimeout(M.current),E.current=new Date().getTime(),M.current=window.setTimeout(O,$))},[O]);_.useEffect(()=>{const $=y.viewport;if($){const H=()=>{V(P.current),d==null||d()},Y=()=>{const Z=new Date().getTime()-E.current;P.current=P.current-Z,window.clearTimeout(M.current),c==null||c()};return $.addEventListener(Lqe,Y),$.addEventListener(Iqe,H),()=>{$.removeEventListener(Lqe,Y),$.removeEventListener(Iqe,H)}}},[y.viewport,C,c,d,V]),_.useEffect(()=>{i&&!y.isClosePausedRef.current&&V(C)},[i,C,y.isClosePausedRef,V]),_.useEffect(()=>(I(),()=>D()),[I,D]);const G=_.useMemo(()=>v?Z6t(v):null,[v]);return y.viewport?e.jsxs(e.Fragment,{children:[G&&e.jsx($fs,{__scopeToast:n,role:"status","aria-live":r==="foreground"?"assertive":"polite","aria-atomic":!0,children:G}),e.jsx(Bfs,{scope:n,onClose:O,children:mv.createPortal(e.jsx(RXe.ItemSlot,{scope:n,children:e.jsx(_fs,{asChild:!0,onEscapeKeyDown:wa(o,()=>{y.isFocusedToastEscapeKeyDownRef.current||O(),y.isFocusedToastEscapeKeyDownRef.current=!1}),children:e.jsx(ii.li,{role:"status","aria-live":"off","aria-atomic":!0,tabIndex:0,"data-state":i?"open":"closed","data-swipe-direction":y.swipeDirection,...f,ref:b,style:{userSelect:"none",touchAction:"none",...s.style},onKeyDown:wa(s.onKeyDown,$=>{$.key==="Escape"&&(o==null||o($.nativeEvent),$.nativeEvent.defaultPrevented||(y.isFocusedToastEscapeKeyDownRef.current=!0,O()))}),onPointerDown:wa(s.onPointerDown,$=>{$.button===0&&(j.current={x:$.clientX,y:$.clientY})}),onPointerMove:wa(s.onPointerMove,$=>{if(!j.current)return;const H=$.clientX-j.current.x,Y=$.clientY-j.current.y,Z=!!S.current,ne=["left","right"].includes(y.swipeDirection),ce=["left","up"].includes(y.swipeDirection)?Math.min:Math.max,ie=ne?ce(0,H):0,te=ne?0:ce(0,Y),ae=$.pointerType==="touch"?10:2,le={x:ie,y:te},be={originalEvent:$,delta:le};Z?(S.current=le,Zoe(Ffs,h,be,{discrete:!1})):Dht(le,y.swipeDirection,ae)?(S.current=le,Zoe(Rfs,u,be,{discrete:!1}),$.target.setPointerCapture($.pointerId)):(Math.abs(H)>ae||Math.abs(Y)>ae)&&(j.current=null)}),onPointerUp:wa(s.onPointerUp,$=>{const H=S.current,Y=$.target;if(Y.hasPointerCapture($.pointerId)&&Y.releasePointerCapture($.pointerId),S.current=null,j.current=null,H){const Z=$.currentTarget,ne={originalEvent:$,delta:H};Dht(H,y.swipeDirection,y.swipeThreshold)?Zoe(zfs,p,ne,{discrete:!0}):Zoe(Ofs,m,ne,{discrete:!0}),Z.addEventListener("click",ce=>ce.preventDefault(),{once:!0})}})})})}),y.viewport)})]}):null}),$fs=s=>{const{__scopeToast:t,children:n,...r}=s,a=wMe(bre,t),[i,l]=_.useState(!1),[o,c]=_.useState(!1);return Gfs(()=>l(!0)),_.useEffect(()=>{const d=window.setTimeout(()=>c(!0),1e3);return()=>window.clearTimeout(d)},[]),o?null:e.jsx(YG,{asChild:!0,children:e.jsx(_Me,{...r,children:i&&e.jsxs(e.Fragment,{children:[a.label," ",n]})})})},Vfs="ToastTitle",V6t=_.forwardRef((s,t)=>{const{__scopeToast:n,...r}=s;return e.jsx(ii.div,{...r,ref:t})});V6t.displayName=Vfs;var Hfs="ToastDescription",H6t=_.forwardRef((s,t)=>{const{__scopeToast:n,...r}=s;return e.jsx(ii.div,{...r,ref:t})});H6t.displayName=Hfs;var G6t="ToastAction",W6t=_.forwardRef((s,t)=>{const{altText:n,...r}=s;return n.trim()?e.jsx(Y6t,{altText:n,asChild:!0,children:e.jsx(FXe,{...r,ref:t})}):(console.error(`Invalid prop \`altText\` supplied to \`${G6t}\`. Expected non-empty \`string\`.`),null)});W6t.displayName=G6t;var K6t="ToastClose",FXe=_.forwardRef((s,t)=>{const{__scopeToast:n,...r}=s,a=Ufs(K6t,n);return e.jsx(Y6t,{asChild:!0,children:e.jsx(ii.button,{type:"button",...r,ref:t,onClick:wa(s.onClick,a.onClose)})})});FXe.displayName=K6t;var Y6t=_.forwardRef((s,t)=>{const{__scopeToast:n,altText:r,...a}=s;return e.jsx(ii.div,{"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":r||void 0,...a,ref:t})});function Z6t(s){const t=[];return Array.from(s.childNodes).forEach(r=>{if(r.nodeType===r.TEXT_NODE&&r.textContent&&t.push(r.textContent),Wfs(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(...Z6t(r))}}),t}function Zoe(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?IXe(a,i):a.dispatchEvent(i)}var Dht=(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 Gfs(s=()=>{}){const t=wx(s);Mx(()=>{let n=0,r=0;return n=window.requestAnimationFrame(()=>r=window.requestAnimationFrame(t)),()=>{window.cancelAnimationFrame(n),window.cancelAnimationFrame(r)}},[t])}function Wfs(s){return s.nodeType===s.ELEMENT_NODE}function Kfs(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 FFe(s){const t=document.activeElement;return s.some(n=>n===t?!0:(n.focus(),document.activeElement!==t))}var Yfs=z6t,X6t=U6t,Q6t=$6t,J6t=V6t,eMt=H6t,tMt=W6t,sMt=FXe;function nMt(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,Fht=jc,F9=(s,t)=>n=>{var r;if((t==null?void 0:t.variants)==null)return Fht(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=Rht(u)||Rht(h);return a[d][m]}),o=n&&Object.entries(n).reduce((d,u)=>{let[h,m]=u;return m===void 0||(d[h]=m),d},{}),c=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((d,u)=>{let{class:h,className:m,...p}=u;return Object.entries(p).every(f=>{let[y,v]=f;return Array.isArray(v)?v.includes({...i,...o}[y]):{...i,...o}[y]===v})?[...d,h,m]:d},[]);return Fht(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 Zfs=s=>s.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),rMt=(...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 Xfs={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 aMt=_.forwardRef(({color:s="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:a="",children:i,iconNode:l,...o},c)=>_.createElement("svg",{ref:c,...Xfs,width:t,height:t,stroke:s,strokeWidth:r?Number(n)*24/Number(t):n,className:rMt("lucide",a),...o},[...l.map(([d,u])=>_.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 fe=(s,t)=>{const n=_.forwardRef(({className:r,...a},i)=>_.createElement(aMt,{ref:i,iconNode:t,className:rMt(`lucide-${Zfs(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 Gue=fe("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 Wue=fe("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 Kue=fe("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 Yue=fe("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 hm=fe("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 Zue=fe("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 Xue=fe("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 RI=fe("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 FI=fe("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 Que=fe("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 OI=fe("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 Jue=fe("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 ehe=fe("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 the=fe("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 she=fe("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 nhe=fe("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 UM=fe("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 rhe=fe("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 ahe=fe("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 ihe=fe("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 ohe=fe("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 lhe=fe("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 che=fe("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 dhe=fe("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 uhe=fe("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 hhe=fe("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 mhe=fe("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 phe=fe("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 qM=fe("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 $M=fe("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 fhe=fe("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 xhe=fe("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 ghe=fe("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 yhe=fe("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 vhe=fe("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 bhe=fe("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 _he=fe("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 whe=fe("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 jhe=fe("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 Nhe=fe("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 khe=fe("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 She=fe("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 Che=fe("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 Ahe=fe("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 Ehe=fe("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 The=fe("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 Mhe=fe("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 Phe=fe("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 Lhe=fe("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 Ihe=fe("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 Dhe=fe("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 Rhe=fe("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 Fhe=fe("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 VM=fe("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 Ohe=fe("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 by=fe("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 zhe=fe("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 Bhe=fe("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 Uhe=fe("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 qhe=fe("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 $he=fe("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 Vhe=fe("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 Hhe=fe("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 Ghe=fe("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 Whe=fe("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 Khe=fe("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 Yhe=fe("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 zI=fe("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 Zhe=fe("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 Xhe=fe("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 Qhe=fe("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 gQ=fe("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 Jhe=fe("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 eme=fe("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 tme=fe("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 BI=fe("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 UI=fe("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 zf=fe("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 sme=fe("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 yQ=fe("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 nme=fe("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=fe("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 rme=fe("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 U4=fe("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 ame=fe("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 La=fe("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 ime=fe("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 ome=fe("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 qI=fe("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 Lg=fe("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 lme=fe("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 cme=fe("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 dme=fe("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 $I=fe("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 $O=fe("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 ume=fe("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 hme=fe("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 VI=fe("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=fe("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 mme=fe("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 pme=fe("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 fme=fe("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 xme=fe("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 gme=fe("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 yme=fe("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 Hh=fe("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 vme=fe("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 HI=fe("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 bme=fe("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 _me=fe("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 wme=fe("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 jme=fe("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 K3=fe("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 Nme=fe("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 kme=fe("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 Sme=fe("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 Cme=fe("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 Ame=fe("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 Eme=fe("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 Tme=fe("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 Mme=fe("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 Pme=fe("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 Lme=fe("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 Ime=fe("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 Dme=fe("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 Rme=fe("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 Fme=fe("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 Ome=fe("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 VO=fe("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 zme=fe("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 Bme=fe("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 Ume=fe("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 qme=fe("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 $me=fe("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 S0=fe("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 Vme=fe("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 Hme=fe("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 Gme=fe("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 Wme=fe("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 Kme=fe("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 Yme=fe("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 vQ=fe("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 Zme=fe("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 Xme=fe("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 q4=fe("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 Qme=fe("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 dj=fe("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 Jme=fe("Beef",[["circle",{cx:"12.5",cy:"8.5",r:"2.5",key:"9738u8"}],["path",{d:"M12.5 2a6.5 6.5 0 0 0-6.22 4.6c-1.1 3.13-.78 3.9-3.18 6.08A3 3 0 0 0 5 18c4 0 8.4-1.8 11.4-4.3A6.5 6.5 0 0 0 12.5 2Z",key:"o0f6za"}],["path",{d:"m18.5 6 2.19 4.5a6.48 6.48 0 0 1 .31 2 6.49 6.49 0 0 1-2.6 5.2C15.4 20.2 11 22 7 22a3 3 0 0 1-2.68-1.66L2.4 16.5",key:"k7p6i0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const epe=fe("BeerOff",[["path",{d:"M13 13v5",key:"igwfh0"}],["path",{d:"M17 11.47V8",key:"16yw0g"}],["path",{d:"M17 11h1a3 3 0 0 1 2.745 4.211",key:"1xbt65"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M5 8v12a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2v-3",key:"c55o3e"}],["path",{d:"M7.536 7.535C6.766 7.649 6.154 8 5.5 8a2.5 2.5 0 0 1-1.768-4.268",key:"1ydug7"}],["path",{d:"M8.727 3.204C9.306 2.767 9.885 2 11 2c1.56 0 2 1.5 3 1.5s1.72-.5 2.5-.5a1 1 0 1 1 0 5c-.78 0-1.5-.5-2.5-.5a3.149 3.149 0 0 0-.842.12",key:"q81o7q"}],["path",{d:"M9 14.6V18",key:"20ek98"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tpe=fe("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 spe=fe("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 npe=fe("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 rpe=fe("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 cS=fe("BellOff",[["path",{d:"M8.7 3A6 6 0 0 1 18 8a21.3 21.3 0 0 0 .6 5",key:"o7mx20"}],["path",{d:"M17 17H3s3-2 3-9a4.67 4.67 0 0 1 .3-1.7",key:"16f1lm"}],["path",{d:"M10.3 21a1.94 1.94 0 0 0 3.4 0",key:"qgo35s"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ape=fe("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 $4=fe("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 Rg=fe("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 GI=fe("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 WI=fe("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 ipe=fe("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 ope=fe("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 lpe=fe("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 cpe=fe("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 dpe=fe("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 upe=fe("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 hpe=fe("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 mpe=fe("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 ppe=fe("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 fpe=fe("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 xpe=fe("Blinds",[["path",{d:"M3 3h18",key:"o7r712"}],["path",{d:"M20 7H8",key:"gd2fo2"}],["path",{d:"M20 11H8",key:"1ynp89"}],["path",{d:"M10 19h10",key:"19hjk5"}],["path",{d:"M8 15h12",key:"1yqzne"}],["path",{d:"M4 3v14",key:"fggqzn"}],["circle",{cx:"4",cy:"19",r:"2",key:"p3m9r0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gpe=fe("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 ype=fe("BluetoothConnected",[["path",{d:"m7 7 10 10-5 5V2l5 5L7 17",key:"1q5490"}],["line",{x1:"18",x2:"21",y1:"12",y2:"12",key:"1rsjjs"}],["line",{x1:"3",x2:"6",y1:"12",y2:"12",key:"11yl8c"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vpe=fe("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 bpe=fe("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 _pe=fe("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 BA=fe("Bold",[["path",{d:"M6 12h9a4 4 0 0 1 0 8H7a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1h7a4 4 0 0 1 0 8",key:"mg9rjx"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wpe=fe("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 jpe=fe("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 Npe=fe("Bone",[["path",{d:"M17 10c.7-.7 1.69 0 2.5 0a2.5 2.5 0 1 0 0-5 .5.5 0 0 1-.5-.5 2.5 2.5 0 1 0-5 0c0 .81.7 1.8 0 2.5l-7 7c-.7.7-1.69 0-2.5 0a2.5 2.5 0 0 0 0 5c.28 0 .5.22.5.5a2.5 2.5 0 1 0 5 0c0-.81-.7-1.8 0-2.5Z",key:"w610uw"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const kpe=fe("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 Spe=fe("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 Cpe=fe("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 Ape=fe("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 KI=fe("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 Epe=fe("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 Tpe=fe("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 Mpe=fe("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 Ppe=fe("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 Lpe=fe("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 Ipe=fe("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 Dpe=fe("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 Rpe=fe("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 Fpe=fe("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 Ope=fe("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 Sx=fe("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 zpe=fe("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 Bpe=fe("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 Upe=fe("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 qpe=fe("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 $pe=fe("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 Vpe=fe("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 Hpe=fe("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 Gpe=fe("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 Wpe=fe("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 Kpe=fe("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 HM=fe("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 Ype=fe("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 C0=fe("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 Zpe=fe("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 Xpe=fe("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 Qpe=fe("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 V4=fe("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 bQ=fe("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 Jpe=fe("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 r6=fe("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 efe=fe("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 tfe=fe("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 sfe=fe("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 _Q=fe("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 nfe=fe("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 rfe=fe("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 afe=fe("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 ife=fe("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 Cx=fe("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 ofe=fe("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 lfe=fe("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 cfe=fe("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 dfe=fe("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 ufe=fe("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=fe("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 GM=fe("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 hfe=fe("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 mfe=fe("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 pfe=fe("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 ffe=fe("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 xfe=fe("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 Bf=fe("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 uj=fe("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 gfe=fe("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 yfe=fe("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 vfe=fe("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 bfe=fe("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 bv=fe("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 Qd=fe("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 _fe=fe("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 pc=fe("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 wfe=fe("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 dS=fe("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 jfe=fe("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 Nfe=fe("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 Aq=fe("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 kfe=fe("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 gy=fe("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 Sfe=fe("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 Cfe=fe("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 Afe=fe("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 Efe=fe("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 wQ=fe("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 ga=fe("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 Tfe=fe("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 cg=fe("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 Mfe=fe("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 Pfe=fe("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 Lfe=fe("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 Ife=fe("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 Dfe=fe("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 YI=fe("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 Rfe=fe("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 Ffe=fe("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 Ofe=fe("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 zfe=fe("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 Bfe=fe("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 Ufe=fe("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 qfe=fe("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 $fe=fe("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 Vfe=fe("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 Hfe=fe("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 Gfe=fe("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 Wfe=fe("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 Kfe=fe("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 ZI=fe("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 XI=fe("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 Yfe=fe("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 Zfe=fe("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 Xfe=fe("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 QI=fe("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 JI=fe("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 e8=fe("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 Qfe=fe("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 t8=fe("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 Jfe=fe("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 bl=fe("ChartColumn",[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"M18 17V9",key:"2bz60n"}],["path",{d:"M13 17V5",key:"1frdt8"}],["path",{d:"M8 17v-3",key:"17ska0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const exe=fe("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 s8=fe("ChartLine",[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"m19 9-5 5-4-4-3 3",key:"2osh9i"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const txe=fe("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 sxe=fe("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 n8=fe("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 r8=fe("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 nxe=fe("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 a8=fe("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 i8=fe("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 o8=fe("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 rxe=fe("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 HO=fe("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 ea=fe("Check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const axe=fe("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 ixe=fe("Cherry",[["path",{d:"M2 17a5 5 0 0 0 10 0c0-2.76-2.5-5-5-3-2.5-2-5 .24-5 3Z",key:"cvxqlc"}],["path",{d:"M12 17a5 5 0 0 0 10 0c0-2.76-2.5-5-5-3-2.5-2-5 .24-5 3Z",key:"1ostrc"}],["path",{d:"M7 14c3.22-2.91 4.29-8.75 5-12 1.66 2.38 4.94 9 5 12",key:"hqx58h"}],["path",{d:"M22 9c-4.29 0-7.14-2.33-10-7 5.71 0 10 4.67 10 7Z",key:"eykp1o"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tl=fe("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 oxe=fe("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 lxe=fe("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 $c=fe("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 xi=fe("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 _v=fe("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 cxe=fe("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 dxe=fe("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 uxe=fe("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 hxe=fe("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 mxe=fe("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 pxe=fe("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 fxe=fe("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 I_=fe("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 xxe=fe("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 GO=fe("Chrome",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["line",{x1:"21.17",x2:"12",y1:"8",y2:"8",key:"a0cw5f"}],["line",{x1:"3.95",x2:"8.54",y1:"6.06",y2:"14",key:"1kftof"}],["line",{x1:"10.88",x2:"15.46",y1:"21.94",y2:"14",key:"1ymyh8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gxe=fe("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 yxe=fe("CigaretteOff",[["path",{d:"M12 12H3a1 1 0 0 0-1 1v2a1 1 0 0 0 1 1h13",key:"1gdiyg"}],["path",{d:"M18 8c0-2.5-2-2.5-2-5",key:"1il607"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M21 12a1 1 0 0 1 1 1v2a1 1 0 0 1-.5.866",key:"166zjj"}],["path",{d:"M22 8c0-2.5-2-2.5-2-5",key:"1gah44"}],["path",{d:"M7 12v4",key:"jqww69"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vxe=fe("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=fe("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 l8=fe("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 c8=fe("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 d8=fe("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 u8=fe("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 h8=fe("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 m8=fe("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 p8=fe("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 f8=fe("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 _l=fe("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 Er=fe("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 x8=fe("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 g8=fe("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 y8=fe("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 v8=fe("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 bxe=fe("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 b8=fe("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 _xe=fe("CircleDollarSign",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M16 8h-6a2 2 0 1 0 0 4h4a2 2 0 1 1 0 4H8",key:"1h4pet"}],["path",{d:"M12 18V6",key:"zqpxq5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wxe=fe("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 jxe=fe("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 Nxe=fe("CircleEllipsis",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M17 12h.01",key:"1m0b6t"}],["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M7 12h.01",key:"eqddd0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const kxe=fe("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 Sxe=fe("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 Cxe=fe("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 _8=fe("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 f4=fe("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 w8=fe("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 Axe=fe("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 j8=fe("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 N8=fe("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 k8=fe("CirclePause",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"10",x2:"10",y1:"15",y2:"9",key:"c1nkhi"}],["line",{x1:"14",x2:"14",y1:"15",y2:"9",key:"h65svq"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const S8=fe("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 om=fe("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 C8=fe("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 A8=fe("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 E8=fe("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 Exe=fe("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 T8=fe("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 M8=fe("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 P8=fe("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 Rd=fe("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 Uf=fe("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 Txe=fe("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 Mxe=fe("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 Eq=fe("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 cN=fe("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 Pxe=fe("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 qf=fe("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 Lxe=fe("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 Ixe=fe("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 L8=fe("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 I8=fe("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 Dxe=fe("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 Rxe=fe("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 Fxe=fe("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 Oxe=fe("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 zxe=fe("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 Bxe=fe("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 Uxe=fe("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 qxe=fe("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 $xe=fe("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 Tq=fe("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 Vxe=fe("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 Hxe=fe("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 Gxe=fe("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 Wxe=fe("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 Kxe=fe("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 Yxe=fe("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 Zxe=fe("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 Xxe=fe("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 Qxe=fe("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 Gr=fe("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 Jxe=fe("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 ege=fe("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 D8=fe("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 tge=fe("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 sge=fe("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 nge=fe("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 rge=fe("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 age=fe("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 ige=fe("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 oge=fe("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 lge=fe("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 cge=fe("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 dge=fe("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 uge=fe("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 hge=fe("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 R8=fe("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 mge=fe("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 pge=fe("Cloudy",[["path",{d:"M17.5 21H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z",key:"gqqjvc"}],["path",{d:"M22 10a3 3 0 0 0-3-3h-2.207a5.502 5.502 0 0 0-10.702.5",key:"1p2s76"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const PA=fe("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 fge=fe("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 Y3=fe("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 UA=fe("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 xge=fe("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 gge=fe("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 H4=fe("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 yge=fe("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 jQ=fe("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 F8=fe("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 a6=fe("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 vge=fe("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 bge=fe("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 _ge=fe("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 WO=fe("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 wge=fe("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 jge=fe("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 Nge=fe("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 kge=fe("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 Sge=fe("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 O8=fe("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 WM=fe("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 Cge=fe("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 Age=fe("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 Ege=fe("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 Tge=fe("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 Mge=fe("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 Pge=fe("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 Lge=fe("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 Ige=fe("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 Dge=fe("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 Ia=fe("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 Rge=fe("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 Fge=fe("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 Oge=fe("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 NQ=fe("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 zge=fe("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 Bge=fe("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 Uge=fe("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 qge=fe("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 $ge=fe("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 Vge=fe("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 Hge=fe("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 Gge=fe("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 _y=fe("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 Wge=fe("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 Kge=fe("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 Yge=fe("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 Zge=fe("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 $f=fe("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 Xge=fe("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 Qge=fe("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 Jge=fe("Currency",[["circle",{cx:"12",cy:"12",r:"8",key:"46899m"}],["line",{x1:"3",x2:"6",y1:"3",y2:"6",key:"1jkytn"}],["line",{x1:"21",x2:"18",y1:"3",y2:"6",key:"14zfjt"}],["line",{x1:"3",x2:"6",y1:"21",y2:"18",key:"iusuec"}],["line",{x1:"21",x2:"18",y1:"21",y2:"18",key:"yj2dd7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const e0e=fe("Cylinder",[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5v14a9 3 0 0 0 18 0V5",key:"aqi0yr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const t0e=fe("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 s0e=fe("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 n0e=fe("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 Mq=fe("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 r0e=fe("Delete",[["path",{d:"M10 5a2 2 0 0 0-1.344.519l-6.328 5.74a1 1 0 0 0 0 1.481l6.328 5.741A2 2 0 0 0 10 19h10a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2z",key:"1yo7s0"}],["path",{d:"m12 9 6 6",key:"anjzzh"}],["path",{d:"m18 9-6 6",key:"1fp51s"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const a0e=fe("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 i0e=fe("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 o0e=fe("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 z8=fe("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 l0e=fe("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 c0e=fe("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 d0e=fe("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 u0e=fe("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 h0e=fe("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 m0e=fe("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 p0e=fe("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 f0e=fe("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 x0e=fe("Dices",[["rect",{width:"12",height:"12",x:"2",y:"10",rx:"2",ry:"2",key:"6agr2n"}],["path",{d:"m17.92 14 3.5-3.5a2.24 2.24 0 0 0 0-3l-5-4.92a2.24 2.24 0 0 0-3 0L10 6",key:"1o487t"}],["path",{d:"M6 18h.01",key:"uhywen"}],["path",{d:"M10 14h.01",key:"ssrbsk"}],["path",{d:"M15 6h.01",key:"cblpky"}],["path",{d:"M18 9h.01",key:"2061c0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const g0e=fe("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 y0e=fe("Disc2",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 12h.01",key:"1mp3jc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const v0e=fe("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 b0e=fe("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 _0e=fe("Disc",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const w0e=fe("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 j0e=fe("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 N0e=fe("Dna",[["path",{d:"m10 16 1.5 1.5",key:"11lckj"}],["path",{d:"m14 8-1.5-1.5",key:"1ohn8i"}],["path",{d:"M15 2c-1.798 1.998-2.518 3.995-2.807 5.993",key:"80uv8i"}],["path",{d:"m16.5 10.5 1 1",key:"696xn5"}],["path",{d:"m17 6-2.891-2.891",key:"xu6p2f"}],["path",{d:"M2 15c6.667-6 13.333 0 20-6",key:"1pyr53"}],["path",{d:"m20 9 .891.891",key:"3xwk7g"}],["path",{d:"M3.109 14.109 4 15",key:"q76aoh"}],["path",{d:"m6.5 12.5 1 1",key:"cs35ky"}],["path",{d:"m7 18 2.891 2.891",key:"1sisit"}],["path",{d:"M9 22c1.798-1.998 2.518-3.995 2.807-5.993",key:"q3hbxp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const k0e=fe("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 S0e=fe("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 yd=fe("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 C0e=fe("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 A0e=fe("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 dN=fe("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 E0e=fe("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 li=fe("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 T0e=fe("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 M0e=fe("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 P0e=fe("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 L0e=fe("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 I0e=fe("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 m1=fe("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 D0e=fe("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 R0e=fe("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 F0e=fe("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 O0e=fe("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 z0e=fe("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 B0e=fe("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 $2=fe("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 U0e=fe("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 q0e=fe("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 $0e=fe("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 Pq=fe("Egg",[["path",{d:"M12 22c6.23-.05 7.87-5.57 7.5-10-.36-4.34-3.95-9.96-7.5-10-3.55.04-7.14 5.66-7.5 10-.37 4.43 1.27 9.95 7.5 10z",key:"1c39pg"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Xx=fe("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 ob=fe("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 V0e=fe("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 H0e=fe("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 G0e=fe("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 Lq=fe("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 W0e=fe("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 K0e=fe("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 Y0e=fe("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 wr=fe("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 Z0e=fe("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 Ax=fe("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 ya=fe("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 tf=fe("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 X0e=fe("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 Q0e=fe("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 J0e=fe("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 eye=fe("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 tye=fe("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 sye=fe("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 nye=fe("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 rye=fe("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 aye=fe("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 iye=fe("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 B8=fe("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 oye=fe("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 lye=fe("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 cye=fe("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 U8=fe("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 q8=fe("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 $8=fe("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 V8=fe("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 KO=fe("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 kQ=fe("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 dye=fe("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 uye=fe("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 hye=fe("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 H8=fe("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 mye=fe("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 pye=fe("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 hj=fe("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 fye=fe("FileHeart",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v2",key:"17k7jt"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M10.29 10.7a2.43 2.43 0 0 0-2.66-.52c-.29.12-.56.3-.78.53l-.35.34-.35-.34a2.43 2.43 0 0 0-2.65-.53c-.3.12-.56.3-.79.53-.95.94-1 2.53.2 3.74L6.5 18l3.6-3.55c1.2-1.21 1.14-2.8.19-3.74Z",key:"1c1fso"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const KM=fe("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 xye=fe("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 gye=fe("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 yye=fe("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 vye=fe("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 bye=fe("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 _ye=fe("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 wye=fe("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 jye=fe("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 Nye=fe("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 kye=fe("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 Sye=fe("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 lb=fe("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 G8=fe("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 Iq=fe("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 Cye=fe("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 Aye=fe("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 Eye=fe("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 Tye=fe("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 SQ=fe("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 Mye=fe("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 uS=fe("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 CQ=fe("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 Pye=fe("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 Lye=fe("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 Fr=fe("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 Iye=fe("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 Dye=fe("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 AQ=fe("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 Rye=fe("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 Fye=fe("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 EQ=fe("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 Oye=fe("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 zye=fe("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 Bye=fe("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 Uye=fe("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 qye=fe("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 Dq=fe("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 $ye=fe("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 dm=fe("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 Vye=fe("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 D_=fe("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 Hye=fe("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 Gye=fe("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 Wye=fe("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 Kye=fe("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 Yye=fe("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 Zye=fe("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 Xye=fe("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 Qye=fe("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 qA=fe("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 Jye=fe("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 gu=fe("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 eve=fe("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 tve=fe("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 sve=fe("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 YM=fe("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 nve=fe("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 rve=fe("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 TQ=fe("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 ave=fe("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 ive=fe("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 rS=fe("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 ove=fe("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 lve=fe("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 cve=fe("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 dve=fe("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 uve=fe("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 hve=fe("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 mve=fe("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 pve=fe("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 fve=fe("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 W8=fe("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 xve=fe("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 gve=fe("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 yve=fe("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 vve=fe("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 bve=fe("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 _ve=fe("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 wve=fe("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 jve=fe("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 Nve=fe("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 kve=fe("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 Sve=fe("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 wy=fe("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 Cve=fe("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 K8=fe("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 MQ=fe("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 Ave=fe("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 Eve=fe("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 Tve=fe("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 Mve=fe("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 Pve=fe("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 Lve=fe("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 Ive=fe("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 Dve=fe("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 Rq=fe("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 Rve=fe("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 Fve=fe("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 Ove=fe("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 zve=fe("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 Bve=fe("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 Uve=fe("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 qve=fe("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 $ve=fe("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 Vve=fe("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 Hve=fe("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 Gve=fe("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 Wve=fe("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 Kve=fe("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 Yve=fe("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 Zve=fe("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 Xve=fe("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 Qve=fe("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 Jve=fe("Gavel",[["path",{d:"m14.5 12.5-8 8a2.119 2.119 0 1 1-3-3l8-8",key:"15492f"}],["path",{d:"m16 16 6-6",key:"vzrcl6"}],["path",{d:"m8 8 6-6",key:"18bi4p"}],["path",{d:"m9 7 8 8",key:"5jnvq1"}],["path",{d:"m21 11-8-8",key:"z4y7zo"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const e1e=fe("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 YO=fe("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 Vo=fe("Gift",[["rect",{x:"3",y:"8",width:"18",height:"4",rx:"1",key:"bkv52"}],["path",{d:"M12 8v13",key:"1c76mn"}],["path",{d:"M19 12v7a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2v-7",key:"6wjy6b"}],["path",{d:"M7.5 8a2.5 2.5 0 0 1 0-5A4.8 8 0 0 1 12 8a4.8 8 0 0 1 4.5-5 2.5 2.5 0 0 1 0 5",key:"1ihvrl"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const t1e=fe("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 s1e=fe("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 Y8=fe("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 n1e=fe("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 r1e=fe("GitCompareArrows",[["circle",{cx:"5",cy:"6",r:"3",key:"1qnov2"}],["path",{d:"M12 6h5a2 2 0 0 1 2 2v7",key:"1yj91y"}],["path",{d:"m15 9-3-3 3-3",key:"1lwv8l"}],["circle",{cx:"19",cy:"18",r:"3",key:"1qljk2"}],["path",{d:"M12 18H7a2 2 0 0 1-2-2V9",key:"16sdep"}],["path",{d:"m9 15 3 3-3 3",key:"1m3kbl"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const a1e=fe("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 i1e=fe("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 o1e=fe("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 l1e=fe("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 c1e=fe("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 d1e=fe("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 u1e=fe("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 h1e=fe("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 m1e=fe("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 p1e=fe("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 f1e=fe("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 x1e=fe("Gitlab",[["path",{d:"m22 13.29-3.33-10a.42.42 0 0 0-.14-.18.38.38 0 0 0-.22-.11.39.39 0 0 0-.23.07.42.42 0 0 0-.14.18l-2.26 6.67H8.32L6.1 3.26a.42.42 0 0 0-.1-.18.38.38 0 0 0-.26-.08.39.39 0 0 0-.23.07.42.42 0 0 0-.14.18L2 13.29a.74.74 0 0 0 .27.83L12 21l9.69-6.88a.71.71 0 0 0 .31-.83Z",key:"148pdi"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const g1e=fe("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 y1e=fe("Glasses",[["circle",{cx:"6",cy:"15",r:"4",key:"vux9w4"}],["circle",{cx:"18",cy:"15",r:"4",key:"18o8ve"}],["path",{d:"M14 15a2 2 0 0 0-2-2 2 2 0 0 0-2 2",key:"1ag4bs"}],["path",{d:"M2.5 13 5 7c.7-1.3 1.4-2 3-2",key:"1hm1gs"}],["path",{d:"M21.5 13 19 7c-.7-1.3-1.5-2-3-2",key:"1r31ai"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const v1e=fe("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 sl=fe("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 b1e=fe("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 _1e=fe("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 mm=fe("GraduationCap",[["path",{d:"M21.42 10.922a1 1 0 0 0-.019-1.838L12.83 5.18a2 2 0 0 0-1.66 0L2.6 9.08a1 1 0 0 0 0 1.832l8.57 3.908a2 2 0 0 0 1.66 0z",key:"j76jl0"}],["path",{d:"M22 10v6",key:"1lu8f3"}],["path",{d:"M6 12.5V16a6 3 0 0 0 12 0v-3.5",key:"1r8lef"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const w1e=fe("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 j1e=fe("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 Z8=fe("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 N1e=fe("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 X8=fe("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 Uw=fe("Grid3x3",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}],["path",{d:"M3 15h18",key:"5xshup"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const k1e=fe("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 Vf=fe("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 S1e=fe("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 C1e=fe("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 A1e=fe("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 E1e=fe("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 PQ=fe("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 T1e=fe("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 LQ=fe("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 x4=fe("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 M1e=fe("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 P1e=fe("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 Fq=fe("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 wv=fe("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 L1e=fe("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 I1e=fe("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 IQ=fe("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 D1e=fe("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 ZM=fe("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 R1e=fe("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 F1e=fe("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 Oq=fe("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 ZO=fe("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 zq=fe("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 O1e=fe("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 z1e=fe("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 B1e=fe("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 U1e=fe("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 q1e=fe("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 $1e=fe("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 V1e=fe("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 H1e=fe("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 DQ=fe("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 G1e=fe("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 W1e=fe("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 Do=fe("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 K1e=fe("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 Y1e=fe("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 Z1e=fe("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 R_=fe("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 X1e=fe("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 Q1e=fe("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 J1e=fe("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 ebe=fe("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 RQ=fe("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 tbe=fe("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 sbe=fe("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 Jr=fe("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 Q8=fe("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 J8=fe("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 FQ=fe("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 nbe=fe("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 rbe=fe("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 abe=fe("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 ibe=fe("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 jy=fe("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 obe=fe("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 lbe=fe("ImageUpscale",[["path",{d:"M16 3h5v5",key:"1806ms"}],["path",{d:"M17 21h2a2 2 0 0 0 2-2",key:"130fy9"}],["path",{d:"M21 12v3",key:"1wzk3p"}],["path",{d:"m21 3-5 5",key:"1g5oa7"}],["path",{d:"M3 7V5a2 2 0 0 1 2-2",key:"kk3yz1"}],["path",{d:"m5 21 4.144-4.144a1.21 1.21 0 0 1 1.712 0L13 19",key:"fyekpt"}],["path",{d:"M9 3h3",key:"d52fa"}],["rect",{x:"3",y:"11",width:"10",height:"10",rx:"1",key:"1wpmix"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hc=fe("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 cbe=fe("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 dbe=fe("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 XO=fe("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 eD=fe("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 tD=fe("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 ube=fe("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 Bq=fe("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 hS=fe("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 hbe=fe("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 Im=fe("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 $A=fe("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 mbe=fe("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 pbe=fe("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 fbe=fe("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 xbe=fe("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 mj=fe("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 VA=fe("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 gbe=fe("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 _b=fe("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 ybe=fe("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 vbe=fe("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 bbe=fe("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 _be=fe("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 wbe=fe("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 jbe=fe("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 Nbe=fe("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 kbe=fe("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 Sbe=fe("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 Cbe=fe("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 Uq=fe("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 Abe=fe("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 Ebe=fe("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 sD=fe("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 Tbe=fe("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 Mbe=fe("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 Pbe=fe("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 Lbe=fe("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 Ibe=fe("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 Dbe=fe("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 G4=fe("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 XM=fe("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 sf=fe("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 Rbe=fe("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 Fbe=fe("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 Obe=fe("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 pj=fe("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 zbe=fe("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 Bbe=fe("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 Ube=fe("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 qbe=fe("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 $be=fe("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 fj=fe("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 qq=fe("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 Vbe=fe("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 Hbe=fe("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 mS=fe("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 Gbe=fe("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 vd=fe("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 Vc=fe("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 dg=fe("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 Wbe=fe("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 Ny=fe("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 Kbe=fe("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 Ybe=fe("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 OQ=fe("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 Zbe=fe("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 Xbe=fe("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 xj=fe("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 zQ=fe("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 Qbe=fe("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 Jbe=fe("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 e_e=fe("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 t_e=fe("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 s_e=fe("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 n_e=fe("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 A0=fe("List",[["path",{d:"M3 12h.01",key:"nlz23k"}],["path",{d:"M3 18h.01",key:"1tta3j"}],["path",{d:"M3 6h.01",key:"1rqtza"}],["path",{d:"M8 12h13",key:"1za7za"}],["path",{d:"M8 18h13",key:"1lx6n3"}],["path",{d:"M8 6h13",key:"ik3vkj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ct=fe("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 r_e=fe("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 a_e=fe("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 i_e=fe("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 o_e=fe("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 $q=fe("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 nD=fe("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 BQ=fe("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 rD=fe("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 ec=fe("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 QM=fe("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 QO=fe("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 l_e=fe("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 c_e=fe("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 d_e=fe("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 u_e=fe("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 JO=fe("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 h_e=fe("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 Vq=fe("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 Hq=fe("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 m_e=fe("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 p_e=fe("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 f_e=fe("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 JM=fe("MailX",[["path",{d:"M22 13V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v12c0 1.1.9 2 2 2h9",key:"1j9vog"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}],["path",{d:"m17 17 4 4",key:"1b3523"}],["path",{d:"m21 17-4 4",key:"uinynz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ln=fe("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 x_e=fe("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 g_e=fe("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 y_e=fe("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 v_e=fe("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 b_e=fe("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 __e=fe("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 w_e=fe("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 j_e=fe("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 N_e=fe("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 k_e=fe("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 S_e=fe("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 C_e=fe("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 Xa=fe("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 UQ=fe("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 e7=fe("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 A_e=fe("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 qQ=fe("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 t7=fe("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 HA=fe("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 E_e=fe("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 wh=fe("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 T_e=fe("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 M_e=fe("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 GA=fe("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 s7=fe("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 P_e=fe("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 L_e=fe("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 Gq=fe("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 I_e=fe("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 D_e=fe("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 R_e=fe("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 $Q=fe("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 F_e=fe("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 O_e=fe("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 z_e=fe("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 Ou=fe("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 B_e=fe("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 U_e=fe("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 q_e=fe("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 $_e=fe("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 V_e=fe("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 H_e=fe("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 VQ=fe("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 G_e=fe("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 E4=fe("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 WA=fe("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 HQ=fe("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 W_e=fe("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 K_e=fe("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 GQ=fe("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 Y_e=fe("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 Hi=fe("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 WQ=fe("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 Z_e=fe("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 aD=fe("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 n7=fe("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 X_e=fe("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 Q_e=fe("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 J_e=fe("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 ewe=fe("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 twe=fe("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 swe=fe("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 nwe=fe("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 rwe=fe("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 uN=fe("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 awe=fe("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 iwe=fe("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 owe=fe("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 lwe=fe("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 cwe=fe("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 dwe=fe("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 Wq=fe("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 uwe=fe("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 hwe=fe("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 mwe=fe("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 r7=fe("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 pwe=fe("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 hN=fe("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 fwe=fe("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 xwe=fe("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 gwe=fe("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 ywe=fe("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 vwe=fe("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 KQ=fe("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 bwe=fe("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 $h=fe("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 v0=fe("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 _we=fe("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 iD=fe("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 wwe=fe("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 jwe=fe("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 Nwe=fe("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 kwe=fe("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 Swe=fe("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 Cwe=fe("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 Awe=fe("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 Ewe=fe("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 Twe=fe("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 Mwe=fe("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 Pwe=fe("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 Lwe=fe("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 YQ=fe("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 Iwe=fe("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 Dwe=fe("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 Rwe=fe("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 Kq=fe("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 Fwe=fe("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 Owe=fe("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 zwe=fe("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 ZQ=fe("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 Bwe=fe("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 mN=fe("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 Uwe=fe("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 qwe=fe("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 $we=fe("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 Vwe=fe("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 Hwe=fe("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 Gwe=fe("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 Wwe=fe("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 Kwe=fe("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 Ywe=fe("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 Qk=fe("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 Zwe=fe("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 oD=fe("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 lD=fe("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 Xwe=fe("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 Qwe=fe("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 Jwe=fe("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 eje=fe("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 tje=fe("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 sje=fe("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 nje=fe("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 rje=fe("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 aje=fe("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 ije=fe("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 oje=fe("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 lje=fe("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 Nh=fe("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 cje=fe("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 dje=fe("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 cD=fe("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 uje=fe("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 Xc=fe("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 hje=fe("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 dD=fe("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 mje=fe("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 pje=fe("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 uD=fe("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 hD=fe("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 mD=fe("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 pD=fe("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 fje=fe("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 fD=fe("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 xje=fe("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 gje=fe("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 yje=fe("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 xD=fe("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 vje=fe("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 bje=fe("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 _je=fe("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 wje=fe("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 Z3=fe("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 eP=fe("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 jje=fe("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 Nje=fe("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 Ex=fe("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 ky=fe("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 kje=fe("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 Sje=fe("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 Qm=fe("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 Cje=fe("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 KA=fe("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 V2=fe("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 Yq=fe("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 Aje=fe("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 Eje=fe("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=fe("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 Tje=fe("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 F_=fe("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 Mje=fe("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 Pje=fe("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 XQ=fe("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 Lje=fe("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 Ije=fe("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 Dje=fe("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 Rje=fe("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 Fje=fe("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 _a=fe("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 Oje=fe("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 zje=fe("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 Bje=fe("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 Uje=fe("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 qje=fe("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 QQ=fe("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 $je=fe("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 Vje=fe("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 Hje=fe("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 Gje=fe("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 Wje=fe("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 JQ=fe("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 YA=fe("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 Kje=fe("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 Yje=fe("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 Zje=fe("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 Xje=fe("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 eJ=fe("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 Jd=fe("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 Qje=fe("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 gD=fe("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 pN=fe("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 rn=fe("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 Jje=fe("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 e2e=fe("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 t2e=fe("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 s2e=fe("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 n2e=fe("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 r2e=fe("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 a2e=fe("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 i2e=fe("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 o2e=fe("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 tJ=fe("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 jv=fe("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 l2e=fe("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 ZA=fe("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 c2e=fe("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 d2e=fe("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 u2e=fe("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 h2e=fe("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 Hf=fe("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 pS=fe("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 m2e=fe("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 Zq=fe("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 p2e=fe("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 f2e=fe("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 x2e=fe("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 g2e=fe("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 Nv=fe("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 y2e=fe("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 v2e=fe("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 b2e=fe("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 _2e=fe("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 w2e=fe("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 j2e=fe("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 N2e=fe("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 k2e=fe("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 S2e=fe("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 C2e=fe("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 A2e=fe("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 E2e=fe("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 T2e=fe("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 sJ=fe("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 yD=fe("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 M2e=fe("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 P2e=fe("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 L2e=fe("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 I2e=fe("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 D2e=fe("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 XA=fe("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 R2e=fe("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 Xq=fe("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 F2e=fe("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 uo=fe("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 O2e=fe("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 z2e=fe("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 B2e=fe("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 U2e=fe("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 nJ=fe("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 QA=fe("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 q2e=fe("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 $2e=fe("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 V2e=fe("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 Qq=fe("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 H2e=fe("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 G2e=fe("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 Sy=fe("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 W2e=fe("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 K2e=fe("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 vD=fe("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 Y2e=fe("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 Tx=fe("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 Z2e=fe("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 a7=fe("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 X2e=fe("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 Jq=fe("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 Q2e=fe("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 bD=fe("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 _D=fe("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 J2e=fe("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 eNe=fe("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 W4=fe("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 tNe=fe("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 sNe=fe("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 nNe=fe("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 rNe=fe("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 aNe=fe("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 iNe=fe("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 oNe=fe("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 lNe=fe("SaveOff",[["path",{d:"M13 13H8a1 1 0 0 0-1 1v7",key:"h8g396"}],["path",{d:"M14 8h1",key:"1lfen6"}],["path",{d:"M17 21v-4",key:"1yknxs"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M20.41 20.41A2 2 0 0 1 19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 .59-1.41",key:"1t4vdl"}],["path",{d:"M29.5 11.5s5 5 4 5",key:"zzn4i6"}],["path",{d:"M9 3h6.2a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V15",key:"24cby9"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ho=fe("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 wD=fe("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 cNe=fe("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 dNe=fe("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 uNe=fe("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 hNe=fe("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 mNe=fe("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 pNe=fe("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 fNe=fe("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 xNe=fe("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 gNe=fe("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 yNe=fe("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 vNe=fe("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 bNe=fe("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 _Ne=fe("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 wNe=fe("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 jNe=fe("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 e$=fe("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 NNe=fe("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 kNe=fe("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 SNe=fe("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 CNe=fe("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 t$=fe("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 Lr=fe("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 ANe=fe("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 jD=fe("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 ENe=fe("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 Or=fe("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 TNe=fe("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 MNe=fe("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 PNe=fe("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 LNe=fe("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 INe=fe("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 DNe=fe("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 fS=fe("Settings2",[["path",{d:"M20 7h-9",key:"3s1dr2"}],["path",{d:"M14 17H5",key:"gfn3mx"}],["circle",{cx:"17",cy:"17",r:"3",key:"18b49y"}],["circle",{cx:"7",cy:"7",r:"3",key:"dfmy0x"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const qc=fe("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 RNe=fe("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 bd=fe("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 rJ=fe("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 FNe=fe("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 ONe=fe("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 s$=fe("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 zNe=fe("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 Dm=fe("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 BNe=fe("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 UNe=fe("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 qNe=fe("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 i7=fe("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 $Ne=fe("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 o7=fe("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 ND=fe("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 Rm=fe("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 VNe=fe("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 HNe=fe("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 GNe=fe("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 K4=fe("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 WNe=fe("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 xS=fe("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 KNe=fe("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 YNe=fe("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 ZNe=fe("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 XNe=fe("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 l7=fe("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 QNe=fe("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 JNe=fe("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 eke=fe("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 tke=fe("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 ske=fe("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 nke=fe("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 rke=fe("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 ake=fe("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 aJ=fe("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 ike=fe("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 oke=fe("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 iJ=fe("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 lke=fe("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 cke=fe("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 dke=fe("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 uke=fe("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 tP=fe("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 kD=fe("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 hke=fe("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 mke=fe("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 p1=fe("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 pke=fe("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 fke=fe("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 xke=fe("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 sj=fe("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 n$=fe("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 gke=fe("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 yke=fe("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 vke=fe("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 sP=fe("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 un=fe("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 bke=fe("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 _ke=fe("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 wke=fe("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 jke=fe("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 Nke=fe("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 kke=fe("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 Ske=fe("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 nP=fe("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 SD=fe("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 CD=fe("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 AD=fe("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 ED=fe("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 TD=fe("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 MD=fe("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 PD=fe("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 LD=fe("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 ID=fe("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 DD=fe("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 RD=fe("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 FD=fe("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 OD=fe("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 zD=fe("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 BD=fe("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 I5=fe("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 Ww=fe("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 UD=fe("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 qD=fe("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 $D=fe("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 VD=fe("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 HD=fe("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 GD=fe("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 Cke=fe("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 Ake=fe("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 WD=fe("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 KD=fe("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 YD=fe("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 ZD=fe("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 XD=fe("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 QD=fe("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 JD=fe("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 eR=fe("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 tR=fe("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 sR=fe("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 nR=fe("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 rR=fe("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 aR=fe("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 iR=fe("SquareParkingOff",[["path",{d:"M3.6 3.6A2 2 0 0 1 5 3h14a2 2 0 0 1 2 2v14a2 2 0 0 1-.59 1.41",key:"9l1ft6"}],["path",{d:"M3 8.7V19a2 2 0 0 0 2 2h10.3",key:"17knke"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M13 13a3 3 0 1 0 0-6H9v2",key:"uoagbd"}],["path",{d:"M9 17v-2.3",key:"1jxgo2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const oR=fe("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 wp=fe("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 lR=fe("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 cR=fe("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 dR=fe("SquarePilcrow",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M12 12H9.5a2.5 2.5 0 0 1 0-5H17",key:"1l9586"}],["path",{d:"M12 7v10",key:"jspqdw"}],["path",{d:"M16 7v10",key:"lavkr4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const uR=fe("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 hR=fe("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 mR=fe("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 Eke=fe("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 pR=fe("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 fR=fe("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 xR=fe("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 gR=fe("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 yR=fe("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 Tke=fe("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 Mke=fe("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 vR=fe("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 bR=fe("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 _R=fe("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 wR=fe("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 wb=fe("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 Pke=fe("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 Lke=fe("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 Ike=fe("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 Dke=fe("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 Rke=fe("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 Da=fe("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 Fke=fe("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 Oke=fe("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 zke=fe("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 Bke=fe("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 c7=fe("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 r$=fe("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 Uke=fe("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 qke=fe("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 oJ=fe("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 $ke=fe("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 Vke=fe("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 Hke=fe("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 Gke=fe("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 Wke=fe("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 fN=fe("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 Kke=fe("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 Yke=fe("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 Zke=fe("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 Xke=fe("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 Qke=fe("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 Jke=fe("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 eSe=fe("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 tSe=fe("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 sSe=fe("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 a$=fe("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 nSe=fe("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 rSe=fe("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 aSe=fe("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 iSe=fe("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 oSe=fe("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 lSe=fe("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 i$=fe("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 cSe=fe("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 o$=fe("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 dSe=fe("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 Ep=fe("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 lJ=fe("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 uSe=fe("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 hSe=fe("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 mSe=fe("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 pSe=fe("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 fSe=fe("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 xSe=fe("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 ku=fe("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 gSe=fe("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 ySe=fe("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 vSe=fe("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 bSe=fe("Terminal",[["polyline",{points:"4 17 10 11 4 5",key:"akl6gq"}],["line",{x1:"12",x2:"20",y1:"19",y2:"19",key:"q2wloq"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const jR=fe("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 _Se=fe("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 wSe=fe("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 l$=fe("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 jSe=fe("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 NSe=fe("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 kSe=fe("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 NR=fe("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 SSe=fe("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 CSe=fe("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 ASe=fe("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 ESe=fe("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 TSe=fe("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 cJ=fe("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 Fg=fe("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 MSe=fe("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 PSe=fe("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 LSe=fe("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 ISe=fe("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 DSe=fe("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 RSe=fe("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 d7=fe("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 FSe=fe("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 OSe=fe("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 zSe=fe("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 BSe=fe("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 USe=fe("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 qSe=fe("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 $Se=fe("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 VSe=fe("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 HSe=fe("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 GSe=fe("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 WSe=fe("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 KSe=fe("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 YSe=fe("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 ZSe=fe("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 XSe=fe("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 QSe=fe("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 JSe=fe("TrainFrontTunnel",[["path",{d:"M2 22V12a10 10 0 1 1 20 0v10",key:"o0fyp0"}],["path",{d:"M15 6.8v1.4a3 2.8 0 1 1-6 0V6.8",key:"m8q3n9"}],["path",{d:"M10 15h.01",key:"44in9x"}],["path",{d:"M14 15h.01",key:"5mohn5"}],["path",{d:"M10 19a4 4 0 0 1-4-4v-3a6 6 0 1 1 12 0v3a4 4 0 0 1-4 4Z",key:"hckbmu"}],["path",{d:"m9 19-2 3",key:"iij7hm"}],["path",{d:"m15 19 2 3",key:"npx8sa"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const e5e=fe("TrainFront",[["path",{d:"M8 3.1V7a4 4 0 0 0 8 0V3.1",key:"1v71zp"}],["path",{d:"m9 15-1-1",key:"1yrq24"}],["path",{d:"m15 15 1-1",key:"1t0d6s"}],["path",{d:"M9 19c-2.8 0-5-2.2-5-5v-4a8 8 0 0 1 16 0v4c0 2.8-2.2 5-5 5Z",key:"1p0hjs"}],["path",{d:"m8 19-2 3",key:"13i0xs"}],["path",{d:"m16 19 2 3",key:"xo31yx"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const t5e=fe("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 kR=fe("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 Sn=fe("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 s5e=fe("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 n5e=fe("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 SR=fe("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 rP=fe("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 r5e=fe("Trees",[["path",{d:"M10 10v.2A3 3 0 0 1 8.9 16H5a3 3 0 0 1-1-5.8V10a3 3 0 0 1 6 0Z",key:"1l6gj6"}],["path",{d:"M7 16v6",key:"1a82de"}],["path",{d:"M13 19v3",key:"13sx9i"}],["path",{d:"M12 19h8.3a1 1 0 0 0 .7-1.7L18 14h.3a1 1 0 0 0 .7-1.7L16 9h.2a1 1 0 0 0 .8-1.7L13 3l-1.4 1.5",key:"1sj9kv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const a5e=fe("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 gS=fe("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 i5e=fe("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 Nl=fe("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 xl=fe("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 o5e=fe("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 l5e=fe("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 wl=fe("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 dJ=fe("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 c5e=fe("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 d5e=fe("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 CR=fe("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 u5e=fe("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 h5e=fe("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 uJ=fe("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 m5e=fe("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 c$=fe("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 p5e=fe("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 f5e=fe("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 u7=fe("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 hJ=fe("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 x5e=fe("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 JA=fe("Undo",[["path",{d:"M3 7v6h6",key:"1v2h90"}],["path",{d:"M21 17a9 9 0 0 0-9-9 9 9 0 0 0-6 2.3L3 13",key:"1r6uu6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const g5e=fe("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 y5e=fe("UnfoldVertical",[["path",{d:"M12 22v-6",key:"6o8u61"}],["path",{d:"M12 8V2",key:"1wkif3"}],["path",{d:"M4 12H2",key:"rhcxmi"}],["path",{d:"M10 12H8",key:"s88cx1"}],["path",{d:"M16 12h-2",key:"10asgb"}],["path",{d:"M22 12h-2",key:"14jgyd"}],["path",{d:"m15 19-3 3-3-3",key:"11eu04"}],["path",{d:"m15 5-3-3-3 3",key:"itvq4r"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const v5e=fe("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 AR=fe("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 b5e=fe("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 h7=fe("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 d$=fe("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 Oa=fe("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 _5e=fe("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 gj=fe("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 mJ=fe("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 u$=fe("UserMinus",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["line",{x1:"22",x2:"16",y1:"11",y2:"11",key:"1shjgl"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const w5e=fe("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 Pl=fe("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 i6=fe("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 ER=fe("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 TR=fe("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 j5e=fe("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 MR=fe("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 h$=fe("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 PR=fe("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 LR=fe("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 N5e=fe("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 m$=fe("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 Fo=fe("User",[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const x0=fe("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 In=fe("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 IR=fe("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 DR=fe("Utensils",[["path",{d:"M3 2v7c0 1.1.9 2 2 2h4a2 2 0 0 0 2-2V2",key:"cjf0a3"}],["path",{d:"M7 2v20",key:"1473qp"}],["path",{d:"M21 15V2a5 5 0 0 0-5 5v6c0 1.1.9 2 2 2h3Zm0 0v7",key:"j28e5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const k5e=fe("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 p$=fe("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 S5e=fe("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 C5e=fe("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 A5e=fe("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 E5e=fe("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 T5e=fe("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 M5e=fe("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 Kr=fe("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 P5e=fe("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 L5e=fe("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 I5e=fe("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 D5e=fe("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 R5e=fe("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 pJ=fe("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 F5e=fe("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 fJ=fe("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 O5e=fe("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 z5e=fe("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 B5e=fe("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 RR=fe("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 m7=fe("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 U5e=fe("Wallpaper",[["circle",{cx:"8",cy:"9",r:"2",key:"gjzl9d"}],["path",{d:"m9 17 6.1-6.1a2 2 0 0 1 2.81.01L22 15V5a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2",key:"69xh40"}],["path",{d:"M8 21h8",key:"1ev6f3"}],["path",{d:"M12 17v4",key:"1riwvh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Qx=fe("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 q5e=fe("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 $5e=fe("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 V5e=fe("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 H5e=fe("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 G5e=fe("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 W5e=fe("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 K5e=fe("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 Y5e=fe("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 Z5e=fe("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 X5e=fe("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 Q5e=fe("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 J5e=fe("Wheat",[["path",{d:"M2 22 16 8",key:"60hf96"}],["path",{d:"M3.47 12.53 5 11l1.53 1.53a3.5 3.5 0 0 1 0 4.94L5 19l-1.53-1.53a3.5 3.5 0 0 1 0-4.94Z",key:"1rdhi6"}],["path",{d:"M7.47 8.53 9 7l1.53 1.53a3.5 3.5 0 0 1 0 4.94L9 15l-1.53-1.53a3.5 3.5 0 0 1 0-4.94Z",key:"1sdzmb"}],["path",{d:"M11.47 4.53 13 3l1.53 1.53a3.5 3.5 0 0 1 0 4.94L13 11l-1.53-1.53a3.5 3.5 0 0 1 0-4.94Z",key:"eoatbi"}],["path",{d:"M20 2h2v2a4 4 0 0 1-4 4h-2V6a4 4 0 0 1 4-4Z",key:"19rau1"}],["path",{d:"M11.47 17.47 13 19l-1.53 1.53a3.5 3.5 0 0 1-4.94 0L5 19l1.53-1.53a3.5 3.5 0 0 1 4.94 0Z",key:"tc8ph9"}],["path",{d:"M15.47 13.47 17 15l-1.53 1.53a3.5 3.5 0 0 1-4.94 0L9 15l1.53-1.53a3.5 3.5 0 0 1 4.94 0Z",key:"2m8kc5"}],["path",{d:"M19.47 9.47 21 11l-1.53 1.53a3.5 3.5 0 0 1-4.94 0L13 11l1.53-1.53a3.5 3.5 0 0 1 4.94 0Z",key:"vex3ng"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const e4e=fe("WholeWord",[["circle",{cx:"7",cy:"12",r:"3",key:"12clwm"}],["path",{d:"M10 9v6",key:"17i7lo"}],["circle",{cx:"17",cy:"12",r:"3",key:"gl7c2s"}],["path",{d:"M14 7v8",key:"dl84cr"}],["path",{d:"M22 17v1c0 .5-.5 1-1 1H3c-.5 0-1-.5-1-1v-1",key:"lt2kga"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const t4e=fe("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 s4e=fe("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 n4e=fe("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 r4e=fe("WifiZero",[["path",{d:"M12 20h.01",key:"zekei9"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const a4e=fe("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 i4e=fe("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 o4e=fe("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 l4e=fe("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 c4e=fe("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 p7=fe("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 d4e=fe("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 u4e=fe("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 Y4=fe("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 Qn=fe("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 f$=fe("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 h4e=fe("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 nf=fe("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 aP=fe("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 x$=fe("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 Qfs=Object.freeze(Object.defineProperty({__proto__:null,AArrowDown:Gue,AArrowUp:Wue,ALargeSmall:Kue,Accessibility:Yue,Activity:hm,AirVent:Zue,Airplay:Xue,AlarmClock:Jue,AlarmClockCheck:RI,AlarmClockMinus:FI,AlarmClockOff:Que,AlarmClockPlus:OI,AlarmSmoke:ehe,Album:the,AlignCenter:UM,AlignCenterHorizontal:she,AlignCenterVertical:nhe,AlignEndHorizontal:rhe,AlignEndVertical:ahe,AlignHorizontalDistributeCenter:ihe,AlignHorizontalDistributeEnd:ohe,AlignHorizontalDistributeStart:lhe,AlignHorizontalJustifyCenter:che,AlignHorizontalJustifyEnd:dhe,AlignHorizontalJustifyStart:uhe,AlignHorizontalSpaceAround:hhe,AlignHorizontalSpaceBetween:mhe,AlignJustify:phe,AlignLeft:qM,AlignRight:$M,AlignStartHorizontal:fhe,AlignStartVertical:xhe,AlignVerticalDistributeCenter:ghe,AlignVerticalDistributeEnd:yhe,AlignVerticalDistributeStart:vhe,AlignVerticalJustifyCenter:bhe,AlignVerticalJustifyEnd:_he,AlignVerticalJustifyStart:whe,AlignVerticalSpaceAround:jhe,AlignVerticalSpaceBetween:Nhe,Ambulance:khe,Ampersand:She,Ampersands:Che,Amphora:Ahe,Anchor:Ehe,Angry:The,Annoyed:Mhe,Antenna:Phe,Anvil:Lhe,Aperture:Ihe,AppWindow:Rhe,AppWindowMac:Dhe,Apple:Fhe,Archive:by,ArchiveRestore:VM,ArchiveX:Ohe,Armchair:zhe,ArrowBigDown:Uhe,ArrowBigDownDash:Bhe,ArrowBigLeft:$he,ArrowBigLeftDash:qhe,ArrowBigRight:Hhe,ArrowBigRightDash:Vhe,ArrowBigUp:Whe,ArrowBigUpDash:Ghe,ArrowDown:zf,ArrowDown01:Khe,ArrowDown10:Yhe,ArrowDownAZ:zI,ArrowDownFromLine:Zhe,ArrowDownLeft:Xhe,ArrowDownNarrowWide:Qhe,ArrowDownRight:gQ,ArrowDownToDot:Jhe,ArrowDownToLine:eme,ArrowDownUp:tme,ArrowDownWideNarrow:BI,ArrowDownZA:UI,ArrowLeft:ka,ArrowLeftFromLine:sme,ArrowLeftRight:yQ,ArrowLeftToLine:nme,ArrowRight:La,ArrowRightFromLine:rme,ArrowRightLeft:U4,ArrowRightToLine:ame,ArrowUp:sp,ArrowUp01:ime,ArrowUp10:ome,ArrowUpAZ:qI,ArrowUpDown:Lg,ArrowUpFromDot:lme,ArrowUpFromLine:cme,ArrowUpLeft:dme,ArrowUpNarrowWide:$I,ArrowUpRight:$O,ArrowUpToLine:ume,ArrowUpWideNarrow:hme,ArrowUpZA:VI,ArrowsUpFromLine:mme,Asterisk:pme,AtSign:fme,Atom:xme,AudioLines:gme,AudioWaveform:yme,Award:Hh,Axe:vme,Axis3d:HI,Baby:bme,Backpack:_me,Badge:Fme,BadgeAlert:wme,BadgeCent:jme,BadgeCheck:K3,BadgeDollarSign:Nme,BadgeEuro:kme,BadgeHelp:Sme,BadgeIndianRupee:Cme,BadgeInfo:Ame,BadgeJapaneseYen:Eme,BadgeMinus:Tme,BadgePercent:Mme,BadgePlus:Pme,BadgePoundSterling:Lme,BadgeRussianRuble:Ime,BadgeSwissFranc:Dme,BadgeX:Rme,BaggageClaim:Ome,Ban:VO,Banana:zme,Bandage:Bme,Banknote:Ume,Barcode:qme,Baseline:$me,Bath:S0,Battery:Yme,BatteryCharging:Vme,BatteryFull:Hme,BatteryLow:Gme,BatteryMedium:Wme,BatteryWarning:Kme,Beaker:vQ,Bean:Xme,BeanOff:Zme,Bed:dj,BedDouble:q4,BedSingle:Qme,Beef:Jme,Beer:tpe,BeerOff:epe,Bell:Rg,BellDot:spe,BellElectric:npe,BellMinus:rpe,BellOff:cS,BellPlus:ape,BellRing:$4,BetweenHorizontalEnd:GI,BetweenHorizontalStart:WI,BetweenVerticalEnd:ipe,BetweenVerticalStart:ope,BicepsFlexed:lpe,Bike:cpe,Binary:dpe,Binoculars:upe,Biohazard:hpe,Bird:mpe,Bitcoin:ppe,Blend:fpe,Blinds:xpe,Blocks:gpe,Bluetooth:_pe,BluetoothConnected:ype,BluetoothOff:vpe,BluetoothSearching:bpe,Bold:BA,Bolt:wpe,Bomb:jpe,Bone:Npe,Book:Gpe,BookA:kpe,BookAudio:Spe,BookCheck:Cpe,BookCopy:Ape,BookDashed:KI,BookDown:Epe,BookHeadphones:Tpe,BookHeart:Mpe,BookImage:Ppe,BookKey:Lpe,BookLock:Ipe,BookMarked:Dpe,BookMinus:Rpe,BookOpen:Sx,BookOpenCheck:Fpe,BookOpenText:Ope,BookPlus:zpe,BookText:Bpe,BookType:Upe,BookUp:$pe,BookUp2:qpe,BookUser:Vpe,BookX:Hpe,Bookmark:C0,BookmarkCheck:Wpe,BookmarkMinus:Kpe,BookmarkPlus:HM,BookmarkX:Ype,BoomBox:Zpe,Bot:V4,BotMessageSquare:Xpe,BotOff:Qpe,Box:bQ,Boxes:Jpe,Braces:r6,Brackets:efe,Brain:_Q,BrainCircuit:tfe,BrainCog:sfe,BrickWall:nfe,Briefcase:Cx,BriefcaseBusiness:rfe,BriefcaseConveyorBelt:afe,BriefcaseMedical:ife,BringToFront:ofe,Brush:lfe,Bug:ufe,BugOff:cfe,BugPlay:dfe,Building:GM,Building2:ai,Bus:mfe,BusFront:hfe,Cable:ffe,CableCar:pfe,Cake:Bf,CakeSlice:xfe,Calculator:uj,Calendar:ga,Calendar1:gfe,CalendarArrowDown:yfe,CalendarArrowUp:vfe,CalendarCheck:bv,CalendarCheck2:bfe,CalendarClock:Qd,CalendarCog:_fe,CalendarDays:pc,CalendarFold:wfe,CalendarHeart:dS,CalendarMinus:Nfe,CalendarMinus2:jfe,CalendarOff:Aq,CalendarPlus:gy,CalendarPlus2:kfe,CalendarRange:Sfe,CalendarSearch:Cfe,CalendarSync:Afe,CalendarX:wQ,CalendarX2:Efe,Camera:cg,CameraOff:Tfe,Candy:Lfe,CandyCane:Mfe,CandyOff:Pfe,Cannabis:Ife,Captions:YI,CaptionsOff:Dfe,Car:Ofe,CarFront:Rfe,CarTaxiFront:Ffe,Caravan:zfe,Carrot:Bfe,CaseLower:Ufe,CaseSensitive:qfe,CaseUpper:$fe,CassetteTape:Vfe,Cast:Hfe,Castle:Gfe,Cat:Wfe,Cctv:Kfe,ChartArea:ZI,ChartBar:QI,ChartBarBig:XI,ChartBarDecreasing:Yfe,ChartBarIncreasing:Zfe,ChartBarStacked:Xfe,ChartCandlestick:JI,ChartColumn:bl,ChartColumnBig:e8,ChartColumnDecreasing:Qfe,ChartColumnIncreasing:t8,ChartColumnStacked:Jfe,ChartGantt:exe,ChartLine:s8,ChartNetwork:txe,ChartNoAxesColumn:r8,ChartNoAxesColumnDecreasing:sxe,ChartNoAxesColumnIncreasing:n8,ChartNoAxesCombined:nxe,ChartNoAxesGantt:a8,ChartPie:i8,ChartScatter:o8,ChartSpline:rxe,Check:ea,CheckCheck:HO,ChefHat:axe,Cherry:ixe,ChevronDown:tl,ChevronFirst:oxe,ChevronLast:lxe,ChevronLeft:$c,ChevronRight:xi,ChevronUp:_v,ChevronsDown:dxe,ChevronsDownUp:cxe,ChevronsLeft:mxe,ChevronsLeftRight:hxe,ChevronsLeftRightEllipsis:uxe,ChevronsRight:fxe,ChevronsRightLeft:pxe,ChevronsUp:xxe,ChevronsUpDown:I_,Chrome:GO,Church:gxe,Cigarette:vxe,CigaretteOff:yxe,Circle:Uf,CircleAlert:Xo,CircleArrowDown:l8,CircleArrowLeft:c8,CircleArrowOutDownLeft:d8,CircleArrowOutDownRight:u8,CircleArrowOutUpLeft:h8,CircleArrowOutUpRight:m8,CircleArrowRight:p8,CircleArrowUp:f8,CircleCheck:Er,CircleCheckBig:_l,CircleChevronDown:x8,CircleChevronLeft:g8,CircleChevronRight:y8,CircleChevronUp:v8,CircleDashed:bxe,CircleDivide:b8,CircleDollarSign:_xe,CircleDot:jxe,CircleDotDashed:wxe,CircleEllipsis:Nxe,CircleEqual:kxe,CircleFadingArrowUp:Sxe,CircleFadingPlus:Cxe,CircleGauge:_8,CircleHelp:f4,CircleMinus:w8,CircleOff:Axe,CircleParking:N8,CircleParkingOff:j8,CirclePause:k8,CirclePercent:S8,CirclePlay:om,CirclePlus:C8,CirclePower:A8,CircleSlash:Exe,CircleSlash2:E8,CircleStop:T8,CircleUser:P8,CircleUserRound:M8,CircleX:Rd,CircuitBoard:Txe,Citrus:Mxe,Clapperboard:Eq,Clipboard:Oxe,ClipboardCheck:cN,ClipboardCopy:Pxe,ClipboardList:qf,ClipboardMinus:Lxe,ClipboardPaste:Ixe,ClipboardPen:I8,ClipboardPenLine:L8,ClipboardPlus:Dxe,ClipboardType:Rxe,ClipboardX:Fxe,Clock:Gr,Clock1:zxe,Clock10:Bxe,Clock11:Uxe,Clock12:qxe,Clock2:$xe,Clock3:Tq,Clock4:Vxe,Clock5:Hxe,Clock6:Gxe,Clock7:Wxe,Clock8:Kxe,Clock9:Yxe,ClockAlert:Zxe,ClockArrowDown:Xxe,ClockArrowUp:Qxe,Cloud:mge,CloudAlert:Jxe,CloudCog:ege,CloudDownload:D8,CloudDrizzle:tge,CloudFog:sge,CloudHail:nge,CloudLightning:rge,CloudMoon:ige,CloudMoonRain:age,CloudOff:oge,CloudRain:cge,CloudRainWind:lge,CloudSnow:dge,CloudSun:hge,CloudSunRain:uge,CloudUpload:R8,Cloudy:pge,Clover:PA,Club:fge,Code:UA,CodeXml:Y3,Codepen:xge,Codesandbox:gge,Coffee:H4,Cog:yge,Coins:jQ,Columns2:F8,Columns3:a6,Columns4:vge,Combine:bge,Command:_ge,Compass:WO,Component:wge,Computer:jge,ConciergeBell:Nge,Cone:kge,Construction:Sge,Contact:WM,ContactRound:O8,Container:Cge,Contrast:Age,Cookie:Ege,CookingPot:Tge,Copy:Ia,CopyCheck:Mge,CopyMinus:Pge,CopyPlus:Lge,CopySlash:Ige,CopyX:Dge,Copyleft:Rge,Copyright:Fge,CornerDownLeft:Oge,CornerDownRight:NQ,CornerLeftDown:zge,CornerLeftUp:Bge,CornerRightDown:Uge,CornerRightUp:qge,CornerUpLeft:$ge,CornerUpRight:Vge,Cpu:Hge,CreativeCommons:Gge,CreditCard:_y,Croissant:Wge,Crop:Kge,Cross:Yge,Crosshair:Zge,Crown:$f,Cuboid:Xge,CupSoda:Qge,Currency:Jge,Cylinder:e0e,Dam:t0e,Database:Mq,DatabaseBackup:s0e,DatabaseZap:n0e,Delete:r0e,Dessert:a0e,Diameter:i0e,Diamond:c0e,DiamondMinus:o0e,DiamondPercent:z8,DiamondPlus:l0e,Dice1:d0e,Dice2:u0e,Dice3:h0e,Dice4:m0e,Dice5:p0e,Dice6:f0e,Dices:x0e,Diff:g0e,Disc:_0e,Disc2:y0e,Disc3:v0e,DiscAlbum:b0e,Divide:w0e,Dna:N0e,DnaOff:j0e,Dock:k0e,Dog:S0e,DollarSign:yd,Donut:C0e,DoorClosed:A0e,DoorOpen:dN,Dot:E0e,Download:li,DraftingCompass:T0e,Drama:M0e,Dribbble:P0e,Drill:L0e,Droplet:I0e,Droplets:m1,Drum:D0e,Drumstick:R0e,Dumbbell:F0e,Ear:z0e,EarOff:O0e,Earth:$2,EarthLock:B0e,Eclipse:U0e,Egg:Pq,EggFried:q0e,EggOff:$0e,Ellipsis:ob,EllipsisVertical:Xx,Equal:G0e,EqualApproximately:V0e,EqualNot:H0e,Eraser:Lq,EthernetPort:W0e,Euro:K0e,Expand:Y0e,ExternalLink:wr,Eye:ya,EyeClosed:Z0e,EyeOff:Ax,Facebook:tf,Factory:X0e,Fan:Q0e,FastForward:J0e,Feather:eye,Fence:tye,FerrisWheel:sye,Figma:nye,File:Dq,FileArchive:rye,FileAudio:iye,FileAudio2:aye,FileAxis3d:B8,FileBadge:lye,FileBadge2:oye,FileBox:cye,FileChartColumn:q8,FileChartColumnIncreasing:U8,FileChartLine:$8,FileChartPie:V8,FileCheck:kQ,FileCheck2:KO,FileClock:dye,FileCode:hye,FileCode2:uye,FileCog:H8,FileDiff:mye,FileDigit:pye,FileDown:hj,FileHeart:fye,FileImage:KM,FileInput:xye,FileJson:yye,FileJson2:gye,FileKey:bye,FileKey2:vye,FileLock:wye,FileLock2:_ye,FileMinus:Nye,FileMinus2:jye,FileMusic:kye,FileOutput:Sye,FilePen:G8,FilePenLine:lb,FilePlus:Cye,FilePlus2:Iq,FileQuestion:Aye,FileScan:Eye,FileSearch:SQ,FileSearch2:Tye,FileSliders:Mye,FileSpreadsheet:uS,FileStack:CQ,FileSymlink:Pye,FileTerminal:Lye,FileText:Fr,FileType:Dye,FileType2:Iye,FileUp:AQ,FileUser:Rye,FileVideo:EQ,FileVideo2:Fye,FileVolume:zye,FileVolume2:Oye,FileWarning:Bye,FileX:qye,FileX2:Uye,Files:$ye,Film:dm,Filter:D_,FilterX:Vye,Fingerprint:Hye,FireExtinguisher:Gye,Fish:Yye,FishOff:Wye,FishSymbol:Kye,Flag:qA,FlagOff:Zye,FlagTriangleLeft:Xye,FlagTriangleRight:Qye,Flame:gu,FlameKindling:Jye,Flashlight:tve,FlashlightOff:eve,FlaskConical:YM,FlaskConicalOff:sve,FlaskRound:nve,FlipHorizontal:TQ,FlipHorizontal2:rve,FlipVertical:ive,FlipVertical2:ave,Flower:ove,Flower2:rS,Focus:lve,FoldHorizontal:cve,FoldVertical:dve,Folder:Rq,FolderArchive:uve,FolderCheck:hve,FolderClock:mve,FolderClosed:pve,FolderCode:fve,FolderCog:W8,FolderDot:xve,FolderDown:gve,FolderGit:vve,FolderGit2:yve,FolderHeart:bve,FolderInput:_ve,FolderKanban:wve,FolderKey:jve,FolderLock:Nve,FolderMinus:kve,FolderOpen:wy,FolderOpenDot:Sve,FolderOutput:Cve,FolderPen:K8,FolderPlus:MQ,FolderRoot:Ave,FolderSearch:Tve,FolderSearch2:Eve,FolderSymlink:Mve,FolderSync:Pve,FolderTree:Lve,FolderUp:Ive,FolderX:Dve,Folders:Rve,Footprints:Fve,Forklift:Ove,Forward:zve,Frame:Bve,Framer:Uve,Frown:qve,Fuel:$ve,Fullscreen:Vve,GalleryHorizontal:Gve,GalleryHorizontalEnd:Hve,GalleryThumbnails:Wve,GalleryVertical:Yve,GalleryVerticalEnd:Kve,Gamepad:Xve,Gamepad2:Zve,Gauge:Qve,Gavel:Jve,Gem:e1e,Ghost:YO,Gift:Vo,GitBranch:s1e,GitBranchPlus:t1e,GitCommitHorizontal:Y8,GitCommitVertical:n1e,GitCompare:a1e,GitCompareArrows:r1e,GitFork:i1e,GitGraph:o1e,GitMerge:l1e,GitPullRequest:p1e,GitPullRequestArrow:c1e,GitPullRequestClosed:d1e,GitPullRequestCreate:h1e,GitPullRequestCreateArrow:u1e,GitPullRequestDraft:m1e,Github:f1e,Gitlab:x1e,GlassWater:g1e,Glasses:y1e,Globe:sl,GlobeLock:v1e,Goal:b1e,Grab:_1e,GraduationCap:mm,Grape:w1e,Grid2x2:X8,Grid2x2Check:j1e,Grid2x2Plus:Z8,Grid2x2X:N1e,Grid3x3:Uw,Grip:S1e,GripHorizontal:k1e,GripVertical:Vf,Group:C1e,Guitar:A1e,Ham:E1e,Hammer:PQ,Hand:Fq,HandCoins:T1e,HandHeart:LQ,HandHelping:x4,HandMetal:M1e,HandPlatter:P1e,Handshake:wv,HardDrive:IQ,HardDriveDownload:L1e,HardDriveUpload:I1e,HardHat:D1e,Hash:ZM,Haze:R1e,HdmiPort:F1e,Heading:U1e,Heading1:Oq,Heading2:ZO,Heading3:zq,Heading4:O1e,Heading5:z1e,Heading6:B1e,HeadphoneOff:q1e,Headphones:$1e,Headset:V1e,Heart:Do,HeartCrack:H1e,HeartHandshake:DQ,HeartOff:G1e,HeartPulse:W1e,Heater:K1e,Hexagon:Y1e,Highlighter:Z1e,History:R_,Hop:Q1e,HopOff:X1e,Hospital:J1e,Hotel:ebe,Hourglass:RQ,House:Jr,HousePlug:tbe,HousePlus:sbe,IceCreamBowl:Q8,IceCreamCone:J8,IdCard:FQ,Image:hc,ImageDown:nbe,ImageMinus:rbe,ImageOff:abe,ImagePlay:ibe,ImagePlus:jy,ImageUp:obe,ImageUpscale:lbe,Images:cbe,Import:dbe,Inbox:XO,IndentDecrease:eD,IndentIncrease:tD,IndianRupee:ube,Infinity:Bq,Info:hS,InspectionPanel:hbe,Instagram:Im,Italic:$A,IterationCcw:mbe,IterationCw:pbe,JapaneseYen:fbe,Joystick:xbe,Kanban:mj,Key:_b,KeyRound:VA,KeySquare:gbe,Keyboard:bbe,KeyboardMusic:ybe,KeyboardOff:vbe,Lamp:Sbe,LampCeiling:_be,LampDesk:wbe,LampFloor:jbe,LampWallDown:Nbe,LampWallUp:kbe,LandPlot:Cbe,Landmark:Uq,Languages:Abe,Laptop:Tbe,LaptopMinimal:sD,LaptopMinimalCheck:Ebe,Lasso:Pbe,LassoSelect:Mbe,Laugh:Lbe,Layers:G4,Layers2:Ibe,Layers3:Dbe,LayoutDashboard:XM,LayoutGrid:sf,LayoutList:Rbe,LayoutPanelLeft:Fbe,LayoutPanelTop:Obe,LayoutTemplate:pj,Leaf:zbe,LeafyGreen:Bbe,Lectern:Ube,LetterText:qbe,Library:fj,LibraryBig:$be,LifeBuoy:qq,Ligature:Vbe,Lightbulb:mS,LightbulbOff:Hbe,Link:Vc,Link2:vd,Link2Off:Gbe,Linkedin:dg,List:A0,ListCheck:Wbe,ListChecks:Ny,ListCollapse:Kbe,ListEnd:Ybe,ListFilter:OQ,ListMinus:Zbe,ListMusic:Xbe,ListOrdered:xj,ListPlus:zQ,ListRestart:Qbe,ListStart:Jbe,ListTodo:e_e,ListTree:t_e,ListVideo:s_e,ListX:n_e,Loader:a_e,LoaderCircle:Ct,LoaderPinwheel:r_e,Locate:$q,LocateFixed:i_e,LocateOff:o_e,Lock:ec,LockKeyhole:BQ,LockKeyholeOpen:nD,LockOpen:rD,LogIn:QM,LogOut:QO,Logs:l_e,Lollipop:c_e,Luggage:d_e,Magnet:u_e,Mail:ln,MailCheck:JO,MailMinus:h_e,MailOpen:Vq,MailPlus:Hq,MailQuestion:m_e,MailSearch:p_e,MailWarning:f_e,MailX:JM,Mailbox:x_e,Mails:g_e,Map:e7,MapPin:Xa,MapPinCheck:v_e,MapPinCheckInside:y_e,MapPinHouse:b_e,MapPinMinus:w_e,MapPinMinusInside:__e,MapPinOff:j_e,MapPinPlus:k_e,MapPinPlusInside:N_e,MapPinX:C_e,MapPinXInside:S_e,MapPinned:UQ,Martini:A_e,Maximize:t7,Maximize2:qQ,Medal:HA,Megaphone:wh,MegaphoneOff:E_e,Meh:T_e,MemoryStick:M_e,Menu:GA,Merge:s7,MessageCircle:Ou,MessageCircleCode:P_e,MessageCircleDashed:L_e,MessageCircleHeart:Gq,MessageCircleMore:I_e,MessageCircleOff:D_e,MessageCirclePlus:R_e,MessageCircleQuestion:$Q,MessageCircleReply:F_e,MessageCircleWarning:O_e,MessageCircleX:z_e,MessageSquare:Hi,MessageSquareCode:B_e,MessageSquareDashed:U_e,MessageSquareDiff:q_e,MessageSquareDot:$_e,MessageSquareHeart:V_e,MessageSquareLock:H_e,MessageSquareMore:VQ,MessageSquareOff:G_e,MessageSquarePlus:E4,MessageSquareQuote:WA,MessageSquareReply:HQ,MessageSquareShare:W_e,MessageSquareText:K_e,MessageSquareWarning:GQ,MessageSquareX:Y_e,MessagesSquare:WQ,Mic:n7,MicOff:Z_e,MicVocal:aD,Microchip:X_e,Microscope:Q_e,Microwave:J_e,Milestone:ewe,Milk:swe,MilkOff:twe,Minimize:rwe,Minimize2:nwe,Minus:uN,Monitor:hN,MonitorCheck:awe,MonitorCog:iwe,MonitorDot:owe,MonitorDown:lwe,MonitorOff:cwe,MonitorPause:dwe,MonitorPlay:Wq,MonitorSmartphone:uwe,MonitorSpeaker:hwe,MonitorStop:mwe,MonitorUp:r7,MonitorX:pwe,Moon:xwe,MoonStar:fwe,Mountain:ywe,MountainSnow:gwe,Mouse:_we,MouseOff:vwe,MousePointer:v0,MousePointer2:KQ,MousePointerBan:bwe,MousePointerClick:$h,Move:YQ,Move3d:iD,MoveDiagonal:jwe,MoveDiagonal2:wwe,MoveDown:Swe,MoveDownLeft:Nwe,MoveDownRight:kwe,MoveHorizontal:Cwe,MoveLeft:Awe,MoveRight:Ewe,MoveUp:Pwe,MoveUpLeft:Twe,MoveUpRight:Mwe,MoveVertical:Lwe,Music:Kq,Music2:Iwe,Music3:Dwe,Music4:Rwe,Navigation:ZQ,Navigation2:Owe,Navigation2Off:Fwe,NavigationOff:zwe,Network:Bwe,Newspaper:mN,Nfc:Uwe,Notebook:Hwe,NotebookPen:qwe,NotebookTabs:$we,NotebookText:Vwe,NotepadText:Wwe,NotepadTextDashed:Gwe,Nut:Ywe,NutOff:Kwe,Octagon:Xwe,OctagonAlert:Qk,OctagonMinus:Zwe,OctagonPause:oD,OctagonX:lD,Omega:Qwe,Option:Jwe,Orbit:eje,Origami:tje,Package:Nh,Package2:sje,PackageCheck:nje,PackageMinus:rje,PackageOpen:aje,PackagePlus:ije,PackageSearch:oje,PackageX:lje,PaintBucket:cje,PaintRoller:dje,Paintbrush:uje,PaintbrushVertical:cD,Palette:Xc,PanelBottom:pje,PanelBottomClose:hje,PanelBottomDashed:dD,PanelBottomOpen:mje,PanelLeft:pD,PanelLeftClose:uD,PanelLeftDashed:hD,PanelLeftOpen:mD,PanelRight:gje,PanelRightClose:fje,PanelRightDashed:fD,PanelRightOpen:xje,PanelTop:bje,PanelTopClose:yje,PanelTopDashed:xD,PanelTopOpen:vje,PanelsLeftBottom:_je,PanelsRightBottom:wje,PanelsTopLeft:Z3,Paperclip:eP,Parentheses:jje,ParkingMeter:Nje,PartyPopper:Ex,Pause:ky,PawPrint:kje,PcCase:Sje,Pen:V2,PenLine:Qm,PenOff:Cje,PenTool:KA,Pencil:Ya,PencilLine:Yq,PencilOff:Aje,PencilRuler:Eje,Pentagon:Tje,Percent:F_,PersonStanding:Mje,PhilippinePeso:Pje,Phone:_a,PhoneCall:XQ,PhoneForwarded:Lje,PhoneIncoming:Ije,PhoneMissed:Dje,PhoneOff:Rje,PhoneOutgoing:Fje,Pi:Oje,Piano:zje,Pickaxe:Bje,PictureInPicture:qje,PictureInPicture2:Uje,PiggyBank:QQ,Pilcrow:Hje,PilcrowLeft:$je,PilcrowRight:Vje,Pill:Wje,PillBottle:Gje,Pin:YA,PinOff:JQ,Pipette:Kje,Pizza:Yje,Plane:eJ,PlaneLanding:Zje,PlaneTakeoff:Xje,Play:Jd,Plug:pN,Plug2:Qje,PlugZap:gD,Plus:rn,Pocket:e2e,PocketKnife:Jje,Podcast:t2e,Pointer:n2e,PointerOff:s2e,Popcorn:r2e,Popsicle:a2e,PoundSterling:i2e,Power:tJ,PowerOff:o2e,Presentation:jv,Printer:ZA,PrinterCheck:l2e,Projector:c2e,Proportions:d2e,Puzzle:u2e,Pyramid:h2e,QrCode:Hf,Quote:pS,Rabbit:m2e,Radar:Zq,Radiation:p2e,Radical:f2e,Radio:Nv,RadioReceiver:x2e,RadioTower:g2e,Radius:y2e,RailSymbol:v2e,Rainbow:b2e,Rat:_2e,Ratio:w2e,Receipt:sJ,ReceiptCent:j2e,ReceiptEuro:N2e,ReceiptIndianRupee:k2e,ReceiptJapaneseYen:S2e,ReceiptPoundSterling:C2e,ReceiptRussianRuble:A2e,ReceiptSwissFranc:E2e,ReceiptText:T2e,RectangleEllipsis:yD,RectangleHorizontal:M2e,RectangleVertical:P2e,Recycle:L2e,Redo:XA,Redo2:I2e,RedoDot:D2e,RefreshCcw:Xq,RefreshCcwDot:R2e,RefreshCw:uo,RefreshCwOff:F2e,Refrigerator:O2e,Regex:z2e,RemoveFormatting:B2e,Repeat:QA,Repeat1:U2e,Repeat2:nJ,Replace:$2e,ReplaceAll:q2e,Reply:Qq,ReplyAll:V2e,Rewind:H2e,Ribbon:G2e,Rocket:Sy,RockingChair:W2e,RollerCoaster:K2e,Rotate3d:vD,RotateCcw:Tx,RotateCcwSquare:Y2e,RotateCw:a7,RotateCwSquare:Z2e,Route:Jq,RouteOff:X2e,Router:Q2e,Rows2:bD,Rows3:_D,Rows4:J2e,Rss:eNe,Ruler:W4,RussianRuble:tNe,Sailboat:sNe,Salad:nNe,Sandwich:rNe,Satellite:iNe,SatelliteDish:aNe,Save:Ho,SaveAll:oNe,SaveOff:lNe,Scale:cNe,Scale3d:wD,Scaling:dNe,Scan:yNe,ScanBarcode:uNe,ScanEye:hNe,ScanFace:mNe,ScanLine:pNe,ScanQrCode:fNe,ScanSearch:xNe,ScanText:gNe,School:vNe,Scissors:_Ne,ScissorsLineDashed:bNe,ScreenShare:jNe,ScreenShareOff:wNe,Scroll:NNe,ScrollText:e$,Search:Lr,SearchCheck:kNe,SearchCode:SNe,SearchSlash:CNe,SearchX:t$,Section:ANe,Send:Or,SendHorizontal:jD,SendToBack:ENe,SeparatorHorizontal:TNe,SeparatorVertical:MNe,Server:DNe,ServerCog:PNe,ServerCrash:LNe,ServerOff:INe,Settings:qc,Settings2:fS,Shapes:RNe,Share:rJ,Share2:bd,Sheet:FNe,Shell:ONe,Shield:Rm,ShieldAlert:s$,ShieldBan:zNe,ShieldCheck:Dm,ShieldEllipsis:BNe,ShieldHalf:UNe,ShieldMinus:qNe,ShieldOff:i7,ShieldPlus:$Ne,ShieldQuestion:o7,ShieldX:ND,Ship:HNe,ShipWheel:VNe,Shirt:GNe,ShoppingBag:K4,ShoppingBasket:WNe,ShoppingCart:xS,Shovel:KNe,ShowerHead:YNe,Shrink:ZNe,Shrub:XNe,Shuffle:l7,Sigma:QNe,Signal:nke,SignalHigh:JNe,SignalLow:eke,SignalMedium:tke,SignalZero:ske,Signature:rke,Signpost:aJ,SignpostBig:ake,Siren:ike,SkipBack:oke,SkipForward:iJ,Skull:lke,Slack:cke,Slash:dke,Slice:uke,SlidersHorizontal:tP,SlidersVertical:kD,Smartphone:p1,SmartphoneCharging:hke,SmartphoneNfc:mke,Smile:fke,SmilePlus:pke,Snail:xke,Snowflake:sj,Sofa:n$,Soup:gke,Space:yke,Spade:vke,Sparkle:sP,Sparkles:un,Speaker:bke,Speech:_ke,SpellCheck:jke,SpellCheck2:wke,Spline:Nke,Split:kke,SprayCan:Ske,Sprout:nP,Square:wb,SquareActivity:SD,SquareArrowDown:ED,SquareArrowDownLeft:CD,SquareArrowDownRight:AD,SquareArrowLeft:TD,SquareArrowOutDownLeft:MD,SquareArrowOutDownRight:PD,SquareArrowOutUpLeft:LD,SquareArrowOutUpRight:ID,SquareArrowRight:DD,SquareArrowUp:OD,SquareArrowUpLeft:RD,SquareArrowUpRight:FD,SquareAsterisk:zD,SquareBottomDashedScissors:BD,SquareChartGantt:I5,SquareCheck:UD,SquareCheckBig:Ww,SquareChevronDown:qD,SquareChevronLeft:$D,SquareChevronRight:VD,SquareChevronUp:HD,SquareCode:GD,SquareDashed:YD,SquareDashedBottom:Ake,SquareDashedBottomCode:Cke,SquareDashedKanban:WD,SquareDashedMousePointer:KD,SquareDivide:ZD,SquareDot:XD,SquareEqual:QD,SquareFunction:JD,SquareKanban:eR,SquareLibrary:tR,SquareM:sR,SquareMenu:nR,SquareMinus:rR,SquareMousePointer:aR,SquareParking:oR,SquareParkingOff:iR,SquarePen:wp,SquarePercent:lR,SquarePi:cR,SquarePilcrow:dR,SquarePlay:uR,SquarePlus:hR,SquarePower:mR,SquareRadical:Eke,SquareScissors:pR,SquareSigma:fR,SquareSlash:xR,SquareSplitHorizontal:gR,SquareSplitVertical:yR,SquareSquare:Tke,SquareStack:Mke,SquareTerminal:vR,SquareUser:_R,SquareUserRound:bR,SquareX:wR,Squircle:Pke,Squirrel:Lke,Stamp:Ike,Star:Da,StarHalf:Dke,StarOff:Rke,StepBack:Fke,StepForward:Oke,Stethoscope:zke,Sticker:Bke,StickyNote:c7,Store:r$,StretchHorizontal:Uke,StretchVertical:qke,Strikethrough:oJ,Subscript:$ke,Sun:fN,SunDim:Vke,SunMedium:Hke,SunMoon:Gke,SunSnow:Wke,Sunrise:Kke,Sunset:Yke,Superscript:Zke,SwatchBook:Xke,SwissFranc:Qke,SwitchCamera:Jke,Sword:eSe,Swords:tSe,Syringe:sSe,Table:i$,Table2:a$,TableCellsMerge:nSe,TableCellsSplit:rSe,TableColumnsSplit:aSe,TableOfContents:iSe,TableProperties:oSe,TableRowsSplit:lSe,Tablet:o$,TabletSmartphone:cSe,Tablets:dSe,Tag:Ep,Tags:lJ,Tally1:uSe,Tally2:hSe,Tally3:mSe,Tally4:pSe,Tally5:fSe,Tangent:xSe,Target:ku,Telescope:gSe,Tent:vSe,TentTree:ySe,Terminal:bSe,TestTube:_Se,TestTubeDiagonal:jR,TestTubes:wSe,Text:SSe,TextCursor:jSe,TextCursorInput:l$,TextQuote:NSe,TextSearch:kSe,TextSelect:NR,Theater:CSe,Thermometer:TSe,ThermometerSnowflake:ASe,ThermometerSun:ESe,ThumbsDown:cJ,ThumbsUp:Fg,Ticket:d7,TicketCheck:MSe,TicketMinus:PSe,TicketPercent:LSe,TicketPlus:ISe,TicketSlash:DSe,TicketX:RSe,Tickets:OSe,TicketsPlane:FSe,Timer:USe,TimerOff:zSe,TimerReset:BSe,ToggleLeft:qSe,ToggleRight:$Se,Toilet:VSe,Tornado:HSe,Torus:GSe,Touchpad:KSe,TouchpadOff:WSe,TowerControl:YSe,ToyBrick:ZSe,Tractor:XSe,TrafficCone:QSe,TrainFront:e5e,TrainFrontTunnel:JSe,TrainTrack:t5e,TramFront:kR,Trash:s5e,Trash2:Sn,TreeDeciduous:n5e,TreePalm:SR,TreePine:rP,Trees:r5e,Trello:a5e,TrendingDown:gS,TrendingUp:Nl,TrendingUpDown:i5e,Triangle:l5e,TriangleAlert:xl,TriangleRight:o5e,Trophy:wl,Truck:dJ,Turtle:c5e,Tv:u5e,TvMinimal:CR,TvMinimalPlay:d5e,Twitch:h5e,Twitter:uJ,Type:c$,TypeOutline:m5e,Umbrella:f5e,UmbrellaOff:p5e,Underline:u7,Undo:JA,Undo2:hJ,UndoDot:x5e,UnfoldHorizontal:g5e,UnfoldVertical:y5e,Ungroup:v5e,University:AR,Unlink:h7,Unlink2:b5e,Unplug:d$,Upload:Oa,Usb:_5e,User:Fo,UserCheck:gj,UserCog:mJ,UserMinus:u$,UserPen:w5e,UserPlus:Pl,UserRound:LR,UserRoundCheck:i6,UserRoundCog:ER,UserRoundMinus:TR,UserRoundPen:j5e,UserRoundPlus:MR,UserRoundSearch:h$,UserRoundX:PR,UserSearch:N5e,UserX:m$,Users:In,UsersRound:x0,Utensils:DR,UtensilsCrossed:IR,UtilityPole:k5e,Variable:p$,Vault:S5e,Vegan:C5e,VenetianMask:A5e,Vibrate:T5e,VibrateOff:E5e,Video:Kr,VideoOff:M5e,Videotape:P5e,View:L5e,Voicemail:I5e,Volleyball:D5e,Volume:O5e,Volume1:R5e,Volume2:pJ,VolumeOff:F5e,VolumeX:fJ,Vote:z5e,Wallet:m7,WalletCards:B5e,WalletMinimal:RR,Wallpaper:U5e,Wand:q5e,WandSparkles:Qx,Warehouse:$5e,WashingMachine:V5e,Watch:H5e,Waves:G5e,Waypoints:W5e,Webcam:K5e,Webhook:Z5e,WebhookOff:Y5e,Weight:X5e,Wheat:J5e,WheatOff:Q5e,WholeWord:e4e,Wifi:a4e,WifiHigh:t4e,WifiLow:s4e,WifiOff:n4e,WifiZero:r4e,Wind:o4e,WindArrowDown:i4e,Wine:c4e,WineOff:l4e,Workflow:p7,Worm:d4e,WrapText:u4e,Wrench:Y4,X:Qn,Youtube:f$,Zap:nf,ZapOff:h4e,ZoomIn:aP,ZoomOut:x$},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 jMe=Object.freeze(Object.defineProperty({__proto__:null,AArrowDown:Gue,AArrowDownIcon:Gue,AArrowUp:Wue,AArrowUpIcon:Wue,ALargeSmall:Kue,ALargeSmallIcon:Kue,Accessibility:Yue,AccessibilityIcon:Yue,Activity:hm,ActivityIcon:hm,ActivitySquare:SD,ActivitySquareIcon:SD,AirVent:Zue,AirVentIcon:Zue,Airplay:Xue,AirplayIcon:Xue,AlarmCheck:RI,AlarmCheckIcon:RI,AlarmClock:Jue,AlarmClockCheck:RI,AlarmClockCheckIcon:RI,AlarmClockIcon:Jue,AlarmClockMinus:FI,AlarmClockMinusIcon:FI,AlarmClockOff:Que,AlarmClockOffIcon:Que,AlarmClockPlus:OI,AlarmClockPlusIcon:OI,AlarmMinus:FI,AlarmMinusIcon:FI,AlarmPlus:OI,AlarmPlusIcon:OI,AlarmSmoke:ehe,AlarmSmokeIcon:ehe,Album:the,AlbumIcon:the,AlertCircle:Xo,AlertCircleIcon:Xo,AlertOctagon:Qk,AlertOctagonIcon:Qk,AlertTriangle:xl,AlertTriangleIcon:xl,AlignCenter:UM,AlignCenterHorizontal:she,AlignCenterHorizontalIcon:she,AlignCenterIcon:UM,AlignCenterVertical:nhe,AlignCenterVerticalIcon:nhe,AlignEndHorizontal:rhe,AlignEndHorizontalIcon:rhe,AlignEndVertical:ahe,AlignEndVerticalIcon:ahe,AlignHorizontalDistributeCenter:ihe,AlignHorizontalDistributeCenterIcon:ihe,AlignHorizontalDistributeEnd:ohe,AlignHorizontalDistributeEndIcon:ohe,AlignHorizontalDistributeStart:lhe,AlignHorizontalDistributeStartIcon:lhe,AlignHorizontalJustifyCenter:che,AlignHorizontalJustifyCenterIcon:che,AlignHorizontalJustifyEnd:dhe,AlignHorizontalJustifyEndIcon:dhe,AlignHorizontalJustifyStart:uhe,AlignHorizontalJustifyStartIcon:uhe,AlignHorizontalSpaceAround:hhe,AlignHorizontalSpaceAroundIcon:hhe,AlignHorizontalSpaceBetween:mhe,AlignHorizontalSpaceBetweenIcon:mhe,AlignJustify:phe,AlignJustifyIcon:phe,AlignLeft:qM,AlignLeftIcon:qM,AlignRight:$M,AlignRightIcon:$M,AlignStartHorizontal:fhe,AlignStartHorizontalIcon:fhe,AlignStartVertical:xhe,AlignStartVerticalIcon:xhe,AlignVerticalDistributeCenter:ghe,AlignVerticalDistributeCenterIcon:ghe,AlignVerticalDistributeEnd:yhe,AlignVerticalDistributeEndIcon:yhe,AlignVerticalDistributeStart:vhe,AlignVerticalDistributeStartIcon:vhe,AlignVerticalJustifyCenter:bhe,AlignVerticalJustifyCenterIcon:bhe,AlignVerticalJustifyEnd:_he,AlignVerticalJustifyEndIcon:_he,AlignVerticalJustifyStart:whe,AlignVerticalJustifyStartIcon:whe,AlignVerticalSpaceAround:jhe,AlignVerticalSpaceAroundIcon:jhe,AlignVerticalSpaceBetween:Nhe,AlignVerticalSpaceBetweenIcon:Nhe,Ambulance:khe,AmbulanceIcon:khe,Ampersand:She,AmpersandIcon:She,Ampersands:Che,AmpersandsIcon:Che,Amphora:Ahe,AmphoraIcon:Ahe,Anchor:Ehe,AnchorIcon:Ehe,Angry:The,AngryIcon:The,Annoyed:Mhe,AnnoyedIcon:Mhe,Antenna:Phe,AntennaIcon:Phe,Anvil:Lhe,AnvilIcon:Lhe,Aperture:Ihe,ApertureIcon:Ihe,AppWindow:Rhe,AppWindowIcon:Rhe,AppWindowMac:Dhe,AppWindowMacIcon:Dhe,Apple:Fhe,AppleIcon:Fhe,Archive:by,ArchiveIcon:by,ArchiveRestore:VM,ArchiveRestoreIcon:VM,ArchiveX:Ohe,ArchiveXIcon:Ohe,AreaChart:ZI,AreaChartIcon:ZI,Armchair:zhe,ArmchairIcon:zhe,ArrowBigDown:Uhe,ArrowBigDownDash:Bhe,ArrowBigDownDashIcon:Bhe,ArrowBigDownIcon:Uhe,ArrowBigLeft:$he,ArrowBigLeftDash:qhe,ArrowBigLeftDashIcon:qhe,ArrowBigLeftIcon:$he,ArrowBigRight:Hhe,ArrowBigRightDash:Vhe,ArrowBigRightDashIcon:Vhe,ArrowBigRightIcon:Hhe,ArrowBigUp:Whe,ArrowBigUpDash:Ghe,ArrowBigUpDashIcon:Ghe,ArrowBigUpIcon:Whe,ArrowDown:zf,ArrowDown01:Khe,ArrowDown01Icon:Khe,ArrowDown10:Yhe,ArrowDown10Icon:Yhe,ArrowDownAZ:zI,ArrowDownAZIcon:zI,ArrowDownAz:zI,ArrowDownAzIcon:zI,ArrowDownCircle:l8,ArrowDownCircleIcon:l8,ArrowDownFromLine:Zhe,ArrowDownFromLineIcon:Zhe,ArrowDownIcon:zf,ArrowDownLeft:Xhe,ArrowDownLeftFromCircle:d8,ArrowDownLeftFromCircleIcon:d8,ArrowDownLeftFromSquare:MD,ArrowDownLeftFromSquareIcon:MD,ArrowDownLeftIcon:Xhe,ArrowDownLeftSquare:CD,ArrowDownLeftSquareIcon:CD,ArrowDownNarrowWide:Qhe,ArrowDownNarrowWideIcon:Qhe,ArrowDownRight:gQ,ArrowDownRightFromCircle:u8,ArrowDownRightFromCircleIcon:u8,ArrowDownRightFromSquare:PD,ArrowDownRightFromSquareIcon:PD,ArrowDownRightIcon:gQ,ArrowDownRightSquare:AD,ArrowDownRightSquareIcon:AD,ArrowDownSquare:ED,ArrowDownSquareIcon:ED,ArrowDownToDot:Jhe,ArrowDownToDotIcon:Jhe,ArrowDownToLine:eme,ArrowDownToLineIcon:eme,ArrowDownUp:tme,ArrowDownUpIcon:tme,ArrowDownWideNarrow:BI,ArrowDownWideNarrowIcon:BI,ArrowDownZA:UI,ArrowDownZAIcon:UI,ArrowDownZa:UI,ArrowDownZaIcon:UI,ArrowLeft:ka,ArrowLeftCircle:c8,ArrowLeftCircleIcon:c8,ArrowLeftFromLine:sme,ArrowLeftFromLineIcon:sme,ArrowLeftIcon:ka,ArrowLeftRight:yQ,ArrowLeftRightIcon:yQ,ArrowLeftSquare:TD,ArrowLeftSquareIcon:TD,ArrowLeftToLine:nme,ArrowLeftToLineIcon:nme,ArrowRight:La,ArrowRightCircle:p8,ArrowRightCircleIcon:p8,ArrowRightFromLine:rme,ArrowRightFromLineIcon:rme,ArrowRightIcon:La,ArrowRightLeft:U4,ArrowRightLeftIcon:U4,ArrowRightSquare:DD,ArrowRightSquareIcon:DD,ArrowRightToLine:ame,ArrowRightToLineIcon:ame,ArrowUp:sp,ArrowUp01:ime,ArrowUp01Icon:ime,ArrowUp10:ome,ArrowUp10Icon:ome,ArrowUpAZ:qI,ArrowUpAZIcon:qI,ArrowUpAz:qI,ArrowUpAzIcon:qI,ArrowUpCircle:f8,ArrowUpCircleIcon:f8,ArrowUpDown:Lg,ArrowUpDownIcon:Lg,ArrowUpFromDot:lme,ArrowUpFromDotIcon:lme,ArrowUpFromLine:cme,ArrowUpFromLineIcon:cme,ArrowUpIcon:sp,ArrowUpLeft:dme,ArrowUpLeftFromCircle:h8,ArrowUpLeftFromCircleIcon:h8,ArrowUpLeftFromSquare:LD,ArrowUpLeftFromSquareIcon:LD,ArrowUpLeftIcon:dme,ArrowUpLeftSquare:RD,ArrowUpLeftSquareIcon:RD,ArrowUpNarrowWide:$I,ArrowUpNarrowWideIcon:$I,ArrowUpRight:$O,ArrowUpRightFromCircle:m8,ArrowUpRightFromCircleIcon:m8,ArrowUpRightFromSquare:ID,ArrowUpRightFromSquareIcon:ID,ArrowUpRightIcon:$O,ArrowUpRightSquare:FD,ArrowUpRightSquareIcon:FD,ArrowUpSquare:OD,ArrowUpSquareIcon:OD,ArrowUpToLine:ume,ArrowUpToLineIcon:ume,ArrowUpWideNarrow:hme,ArrowUpWideNarrowIcon:hme,ArrowUpZA:VI,ArrowUpZAIcon:VI,ArrowUpZa:VI,ArrowUpZaIcon:VI,ArrowsUpFromLine:mme,ArrowsUpFromLineIcon:mme,Asterisk:pme,AsteriskIcon:pme,AsteriskSquare:zD,AsteriskSquareIcon:zD,AtSign:fme,AtSignIcon:fme,Atom:xme,AtomIcon:xme,AudioLines:gme,AudioLinesIcon:gme,AudioWaveform:yme,AudioWaveformIcon:yme,Award:Hh,AwardIcon:Hh,Axe:vme,AxeIcon:vme,Axis3D:HI,Axis3DIcon:HI,Axis3d:HI,Axis3dIcon:HI,Baby:bme,BabyIcon:bme,Backpack:_me,BackpackIcon:_me,Badge:Fme,BadgeAlert:wme,BadgeAlertIcon:wme,BadgeCent:jme,BadgeCentIcon:jme,BadgeCheck:K3,BadgeCheckIcon:K3,BadgeDollarSign:Nme,BadgeDollarSignIcon:Nme,BadgeEuro:kme,BadgeEuroIcon:kme,BadgeHelp:Sme,BadgeHelpIcon:Sme,BadgeIcon:Fme,BadgeIndianRupee:Cme,BadgeIndianRupeeIcon:Cme,BadgeInfo:Ame,BadgeInfoIcon:Ame,BadgeJapaneseYen:Eme,BadgeJapaneseYenIcon:Eme,BadgeMinus:Tme,BadgeMinusIcon:Tme,BadgePercent:Mme,BadgePercentIcon:Mme,BadgePlus:Pme,BadgePlusIcon:Pme,BadgePoundSterling:Lme,BadgePoundSterlingIcon:Lme,BadgeRussianRuble:Ime,BadgeRussianRubleIcon:Ime,BadgeSwissFranc:Dme,BadgeSwissFrancIcon:Dme,BadgeX:Rme,BadgeXIcon:Rme,BaggageClaim:Ome,BaggageClaimIcon:Ome,Ban:VO,BanIcon:VO,Banana:zme,BananaIcon:zme,Bandage:Bme,BandageIcon:Bme,Banknote:Ume,BanknoteIcon:Ume,BarChart:n8,BarChart2:r8,BarChart2Icon:r8,BarChart3:bl,BarChart3Icon:bl,BarChart4:t8,BarChart4Icon:t8,BarChartBig:e8,BarChartBigIcon:e8,BarChartHorizontal:QI,BarChartHorizontalBig:XI,BarChartHorizontalBigIcon:XI,BarChartHorizontalIcon:QI,BarChartIcon:n8,Barcode:qme,BarcodeIcon:qme,Baseline:$me,BaselineIcon:$me,Bath:S0,BathIcon:S0,Battery:Yme,BatteryCharging:Vme,BatteryChargingIcon:Vme,BatteryFull:Hme,BatteryFullIcon:Hme,BatteryIcon:Yme,BatteryLow:Gme,BatteryLowIcon:Gme,BatteryMedium:Wme,BatteryMediumIcon:Wme,BatteryWarning:Kme,BatteryWarningIcon:Kme,Beaker:vQ,BeakerIcon:vQ,Bean:Xme,BeanIcon:Xme,BeanOff:Zme,BeanOffIcon:Zme,Bed:dj,BedDouble:q4,BedDoubleIcon:q4,BedIcon:dj,BedSingle:Qme,BedSingleIcon:Qme,Beef:Jme,BeefIcon:Jme,Beer:tpe,BeerIcon:tpe,BeerOff:epe,BeerOffIcon:epe,Bell:Rg,BellDot:spe,BellDotIcon:spe,BellElectric:npe,BellElectricIcon:npe,BellIcon:Rg,BellMinus:rpe,BellMinusIcon:rpe,BellOff:cS,BellOffIcon:cS,BellPlus:ape,BellPlusIcon:ape,BellRing:$4,BellRingIcon:$4,BetweenHorizonalEnd:GI,BetweenHorizonalEndIcon:GI,BetweenHorizonalStart:WI,BetweenHorizonalStartIcon:WI,BetweenHorizontalEnd:GI,BetweenHorizontalEndIcon:GI,BetweenHorizontalStart:WI,BetweenHorizontalStartIcon:WI,BetweenVerticalEnd:ipe,BetweenVerticalEndIcon:ipe,BetweenVerticalStart:ope,BetweenVerticalStartIcon:ope,BicepsFlexed:lpe,BicepsFlexedIcon:lpe,Bike:cpe,BikeIcon:cpe,Binary:dpe,BinaryIcon:dpe,Binoculars:upe,BinocularsIcon:upe,Biohazard:hpe,BiohazardIcon:hpe,Bird:mpe,BirdIcon:mpe,Bitcoin:ppe,BitcoinIcon:ppe,Blend:fpe,BlendIcon:fpe,Blinds:xpe,BlindsIcon:xpe,Blocks:gpe,BlocksIcon:gpe,Bluetooth:_pe,BluetoothConnected:ype,BluetoothConnectedIcon:ype,BluetoothIcon:_pe,BluetoothOff:vpe,BluetoothOffIcon:vpe,BluetoothSearching:bpe,BluetoothSearchingIcon:bpe,Bold:BA,BoldIcon:BA,Bolt:wpe,BoltIcon:wpe,Bomb:jpe,BombIcon:jpe,Bone:Npe,BoneIcon:Npe,Book:Gpe,BookA:kpe,BookAIcon:kpe,BookAudio:Spe,BookAudioIcon:Spe,BookCheck:Cpe,BookCheckIcon:Cpe,BookCopy:Ape,BookCopyIcon:Ape,BookDashed:KI,BookDashedIcon:KI,BookDown:Epe,BookDownIcon:Epe,BookHeadphones:Tpe,BookHeadphonesIcon:Tpe,BookHeart:Mpe,BookHeartIcon:Mpe,BookIcon:Gpe,BookImage:Ppe,BookImageIcon:Ppe,BookKey:Lpe,BookKeyIcon:Lpe,BookLock:Ipe,BookLockIcon:Ipe,BookMarked:Dpe,BookMarkedIcon:Dpe,BookMinus:Rpe,BookMinusIcon:Rpe,BookOpen:Sx,BookOpenCheck:Fpe,BookOpenCheckIcon:Fpe,BookOpenIcon:Sx,BookOpenText:Ope,BookOpenTextIcon:Ope,BookPlus:zpe,BookPlusIcon:zpe,BookTemplate:KI,BookTemplateIcon:KI,BookText:Bpe,BookTextIcon:Bpe,BookType:Upe,BookTypeIcon:Upe,BookUp:$pe,BookUp2:qpe,BookUp2Icon:qpe,BookUpIcon:$pe,BookUser:Vpe,BookUserIcon:Vpe,BookX:Hpe,BookXIcon:Hpe,Bookmark:C0,BookmarkCheck:Wpe,BookmarkCheckIcon:Wpe,BookmarkIcon:C0,BookmarkMinus:Kpe,BookmarkMinusIcon:Kpe,BookmarkPlus:HM,BookmarkPlusIcon:HM,BookmarkX:Ype,BookmarkXIcon:Ype,BoomBox:Zpe,BoomBoxIcon:Zpe,Bot:V4,BotIcon:V4,BotMessageSquare:Xpe,BotMessageSquareIcon:Xpe,BotOff:Qpe,BotOffIcon:Qpe,Box:bQ,BoxIcon:bQ,BoxSelect:YD,BoxSelectIcon:YD,Boxes:Jpe,BoxesIcon:Jpe,Braces:r6,BracesIcon:r6,Brackets:efe,BracketsIcon:efe,Brain:_Q,BrainCircuit:tfe,BrainCircuitIcon:tfe,BrainCog:sfe,BrainCogIcon:sfe,BrainIcon:_Q,BrickWall:nfe,BrickWallIcon:nfe,Briefcase:Cx,BriefcaseBusiness:rfe,BriefcaseBusinessIcon:rfe,BriefcaseConveyorBelt:afe,BriefcaseConveyorBeltIcon:afe,BriefcaseIcon:Cx,BriefcaseMedical:ife,BriefcaseMedicalIcon:ife,BringToFront:ofe,BringToFrontIcon:ofe,Brush:lfe,BrushIcon:lfe,Bug:ufe,BugIcon:ufe,BugOff:cfe,BugOffIcon:cfe,BugPlay:dfe,BugPlayIcon:dfe,Building:GM,Building2:ai,Building2Icon:ai,BuildingIcon:GM,Bus:mfe,BusFront:hfe,BusFrontIcon:hfe,BusIcon:mfe,Cable:ffe,CableCar:pfe,CableCarIcon:pfe,CableIcon:ffe,Cake:Bf,CakeIcon:Bf,CakeSlice:xfe,CakeSliceIcon:xfe,Calculator:uj,CalculatorIcon:uj,Calendar:ga,Calendar1:gfe,Calendar1Icon:gfe,CalendarArrowDown:yfe,CalendarArrowDownIcon:yfe,CalendarArrowUp:vfe,CalendarArrowUpIcon:vfe,CalendarCheck:bv,CalendarCheck2:bfe,CalendarCheck2Icon:bfe,CalendarCheckIcon:bv,CalendarClock:Qd,CalendarClockIcon:Qd,CalendarCog:_fe,CalendarCogIcon:_fe,CalendarDays:pc,CalendarDaysIcon:pc,CalendarFold:wfe,CalendarFoldIcon:wfe,CalendarHeart:dS,CalendarHeartIcon:dS,CalendarIcon:ga,CalendarMinus:Nfe,CalendarMinus2:jfe,CalendarMinus2Icon:jfe,CalendarMinusIcon:Nfe,CalendarOff:Aq,CalendarOffIcon:Aq,CalendarPlus:gy,CalendarPlus2:kfe,CalendarPlus2Icon:kfe,CalendarPlusIcon:gy,CalendarRange:Sfe,CalendarRangeIcon:Sfe,CalendarSearch:Cfe,CalendarSearchIcon:Cfe,CalendarSync:Afe,CalendarSyncIcon:Afe,CalendarX:wQ,CalendarX2:Efe,CalendarX2Icon:Efe,CalendarXIcon:wQ,Camera:cg,CameraIcon:cg,CameraOff:Tfe,CameraOffIcon:Tfe,CandlestickChart:JI,CandlestickChartIcon:JI,Candy:Lfe,CandyCane:Mfe,CandyCaneIcon:Mfe,CandyIcon:Lfe,CandyOff:Pfe,CandyOffIcon:Pfe,Cannabis:Ife,CannabisIcon:Ife,Captions:YI,CaptionsIcon:YI,CaptionsOff:Dfe,CaptionsOffIcon:Dfe,Car:Ofe,CarFront:Rfe,CarFrontIcon:Rfe,CarIcon:Ofe,CarTaxiFront:Ffe,CarTaxiFrontIcon:Ffe,Caravan:zfe,CaravanIcon:zfe,Carrot:Bfe,CarrotIcon:Bfe,CaseLower:Ufe,CaseLowerIcon:Ufe,CaseSensitive:qfe,CaseSensitiveIcon:qfe,CaseUpper:$fe,CaseUpperIcon:$fe,CassetteTape:Vfe,CassetteTapeIcon:Vfe,Cast:Hfe,CastIcon:Hfe,Castle:Gfe,CastleIcon:Gfe,Cat:Wfe,CatIcon:Wfe,Cctv:Kfe,CctvIcon:Kfe,ChartArea:ZI,ChartAreaIcon:ZI,ChartBar:QI,ChartBarBig:XI,ChartBarBigIcon:XI,ChartBarDecreasing:Yfe,ChartBarDecreasingIcon:Yfe,ChartBarIcon:QI,ChartBarIncreasing:Zfe,ChartBarIncreasingIcon:Zfe,ChartBarStacked:Xfe,ChartBarStackedIcon:Xfe,ChartCandlestick:JI,ChartCandlestickIcon:JI,ChartColumn:bl,ChartColumnBig:e8,ChartColumnBigIcon:e8,ChartColumnDecreasing:Qfe,ChartColumnDecreasingIcon:Qfe,ChartColumnIcon:bl,ChartColumnIncreasing:t8,ChartColumnIncreasingIcon:t8,ChartColumnStacked:Jfe,ChartColumnStackedIcon:Jfe,ChartGantt:exe,ChartGanttIcon:exe,ChartLine:s8,ChartLineIcon:s8,ChartNetwork:txe,ChartNetworkIcon:txe,ChartNoAxesColumn:r8,ChartNoAxesColumnDecreasing:sxe,ChartNoAxesColumnDecreasingIcon:sxe,ChartNoAxesColumnIcon:r8,ChartNoAxesColumnIncreasing:n8,ChartNoAxesColumnIncreasingIcon:n8,ChartNoAxesCombined:nxe,ChartNoAxesCombinedIcon:nxe,ChartNoAxesGantt:a8,ChartNoAxesGanttIcon:a8,ChartPie:i8,ChartPieIcon:i8,ChartScatter:o8,ChartScatterIcon:o8,ChartSpline:rxe,ChartSplineIcon:rxe,Check:ea,CheckCheck:HO,CheckCheckIcon:HO,CheckCircle:_l,CheckCircle2:Er,CheckCircle2Icon:Er,CheckCircleIcon:_l,CheckIcon:ea,CheckSquare:Ww,CheckSquare2:UD,CheckSquare2Icon:UD,CheckSquareIcon:Ww,ChefHat:axe,ChefHatIcon:axe,Cherry:ixe,CherryIcon:ixe,ChevronDown:tl,ChevronDownCircle:x8,ChevronDownCircleIcon:x8,ChevronDownIcon:tl,ChevronDownSquare:qD,ChevronDownSquareIcon:qD,ChevronFirst:oxe,ChevronFirstIcon:oxe,ChevronLast:lxe,ChevronLastIcon:lxe,ChevronLeft:$c,ChevronLeftCircle:g8,ChevronLeftCircleIcon:g8,ChevronLeftIcon:$c,ChevronLeftSquare:$D,ChevronLeftSquareIcon:$D,ChevronRight:xi,ChevronRightCircle:y8,ChevronRightCircleIcon:y8,ChevronRightIcon:xi,ChevronRightSquare:VD,ChevronRightSquareIcon:VD,ChevronUp:_v,ChevronUpCircle:v8,ChevronUpCircleIcon:v8,ChevronUpIcon:_v,ChevronUpSquare:HD,ChevronUpSquareIcon:HD,ChevronsDown:dxe,ChevronsDownIcon:dxe,ChevronsDownUp:cxe,ChevronsDownUpIcon:cxe,ChevronsLeft:mxe,ChevronsLeftIcon:mxe,ChevronsLeftRight:hxe,ChevronsLeftRightEllipsis:uxe,ChevronsLeftRightEllipsisIcon:uxe,ChevronsLeftRightIcon:hxe,ChevronsRight:fxe,ChevronsRightIcon:fxe,ChevronsRightLeft:pxe,ChevronsRightLeftIcon:pxe,ChevronsUp:xxe,ChevronsUpDown:I_,ChevronsUpDownIcon:I_,ChevronsUpIcon:xxe,Chrome:GO,ChromeIcon:GO,Church:gxe,ChurchIcon:gxe,Cigarette:vxe,CigaretteIcon:vxe,CigaretteOff:yxe,CigaretteOffIcon:yxe,Circle:Uf,CircleAlert:Xo,CircleAlertIcon:Xo,CircleArrowDown:l8,CircleArrowDownIcon:l8,CircleArrowLeft:c8,CircleArrowLeftIcon:c8,CircleArrowOutDownLeft:d8,CircleArrowOutDownLeftIcon:d8,CircleArrowOutDownRight:u8,CircleArrowOutDownRightIcon:u8,CircleArrowOutUpLeft:h8,CircleArrowOutUpLeftIcon:h8,CircleArrowOutUpRight:m8,CircleArrowOutUpRightIcon:m8,CircleArrowRight:p8,CircleArrowRightIcon:p8,CircleArrowUp:f8,CircleArrowUpIcon:f8,CircleCheck:Er,CircleCheckBig:_l,CircleCheckBigIcon:_l,CircleCheckIcon:Er,CircleChevronDown:x8,CircleChevronDownIcon:x8,CircleChevronLeft:g8,CircleChevronLeftIcon:g8,CircleChevronRight:y8,CircleChevronRightIcon:y8,CircleChevronUp:v8,CircleChevronUpIcon:v8,CircleDashed:bxe,CircleDashedIcon:bxe,CircleDivide:b8,CircleDivideIcon:b8,CircleDollarSign:_xe,CircleDollarSignIcon:_xe,CircleDot:jxe,CircleDotDashed:wxe,CircleDotDashedIcon:wxe,CircleDotIcon:jxe,CircleEllipsis:Nxe,CircleEllipsisIcon:Nxe,CircleEqual:kxe,CircleEqualIcon:kxe,CircleFadingArrowUp:Sxe,CircleFadingArrowUpIcon:Sxe,CircleFadingPlus:Cxe,CircleFadingPlusIcon:Cxe,CircleGauge:_8,CircleGaugeIcon:_8,CircleHelp:f4,CircleHelpIcon:f4,CircleIcon:Uf,CircleMinus:w8,CircleMinusIcon:w8,CircleOff:Axe,CircleOffIcon:Axe,CircleParking:N8,CircleParkingIcon:N8,CircleParkingOff:j8,CircleParkingOffIcon:j8,CirclePause:k8,CirclePauseIcon:k8,CirclePercent:S8,CirclePercentIcon:S8,CirclePlay:om,CirclePlayIcon:om,CirclePlus:C8,CirclePlusIcon:C8,CirclePower:A8,CirclePowerIcon:A8,CircleSlash:Exe,CircleSlash2:E8,CircleSlash2Icon:E8,CircleSlashIcon:Exe,CircleSlashed:E8,CircleSlashedIcon:E8,CircleStop:T8,CircleStopIcon:T8,CircleUser:P8,CircleUserIcon:P8,CircleUserRound:M8,CircleUserRoundIcon:M8,CircleX:Rd,CircleXIcon:Rd,CircuitBoard:Txe,CircuitBoardIcon:Txe,Citrus:Mxe,CitrusIcon:Mxe,Clapperboard:Eq,ClapperboardIcon:Eq,Clipboard:Oxe,ClipboardCheck:cN,ClipboardCheckIcon:cN,ClipboardCopy:Pxe,ClipboardCopyIcon:Pxe,ClipboardEdit:I8,ClipboardEditIcon:I8,ClipboardIcon:Oxe,ClipboardList:qf,ClipboardListIcon:qf,ClipboardMinus:Lxe,ClipboardMinusIcon:Lxe,ClipboardPaste:Ixe,ClipboardPasteIcon:Ixe,ClipboardPen:I8,ClipboardPenIcon:I8,ClipboardPenLine:L8,ClipboardPenLineIcon:L8,ClipboardPlus:Dxe,ClipboardPlusIcon:Dxe,ClipboardSignature:L8,ClipboardSignatureIcon:L8,ClipboardType:Rxe,ClipboardTypeIcon:Rxe,ClipboardX:Fxe,ClipboardXIcon:Fxe,Clock:Gr,Clock1:zxe,Clock10:Bxe,Clock10Icon:Bxe,Clock11:Uxe,Clock11Icon:Uxe,Clock12:qxe,Clock12Icon:qxe,Clock1Icon:zxe,Clock2:$xe,Clock2Icon:$xe,Clock3:Tq,Clock3Icon:Tq,Clock4:Vxe,Clock4Icon:Vxe,Clock5:Hxe,Clock5Icon:Hxe,Clock6:Gxe,Clock6Icon:Gxe,Clock7:Wxe,Clock7Icon:Wxe,Clock8:Kxe,Clock8Icon:Kxe,Clock9:Yxe,Clock9Icon:Yxe,ClockAlert:Zxe,ClockAlertIcon:Zxe,ClockArrowDown:Xxe,ClockArrowDownIcon:Xxe,ClockArrowUp:Qxe,ClockArrowUpIcon:Qxe,ClockIcon:Gr,Cloud:mge,CloudAlert:Jxe,CloudAlertIcon:Jxe,CloudCog:ege,CloudCogIcon:ege,CloudDownload:D8,CloudDownloadIcon:D8,CloudDrizzle:tge,CloudDrizzleIcon:tge,CloudFog:sge,CloudFogIcon:sge,CloudHail:nge,CloudHailIcon:nge,CloudIcon:mge,CloudLightning:rge,CloudLightningIcon:rge,CloudMoon:ige,CloudMoonIcon:ige,CloudMoonRain:age,CloudMoonRainIcon:age,CloudOff:oge,CloudOffIcon:oge,CloudRain:cge,CloudRainIcon:cge,CloudRainWind:lge,CloudRainWindIcon:lge,CloudSnow:dge,CloudSnowIcon:dge,CloudSun:hge,CloudSunIcon:hge,CloudSunRain:uge,CloudSunRainIcon:uge,CloudUpload:R8,CloudUploadIcon:R8,Cloudy:pge,CloudyIcon:pge,Clover:PA,CloverIcon:PA,Club:fge,ClubIcon:fge,Code:UA,Code2:Y3,Code2Icon:Y3,CodeIcon:UA,CodeSquare:GD,CodeSquareIcon:GD,CodeXml:Y3,CodeXmlIcon:Y3,Codepen:xge,CodepenIcon:xge,Codesandbox:gge,CodesandboxIcon:gge,Coffee:H4,CoffeeIcon:H4,Cog:yge,CogIcon:yge,Coins:jQ,CoinsIcon:jQ,Columns:F8,Columns2:F8,Columns2Icon:F8,Columns3:a6,Columns3Icon:a6,Columns4:vge,Columns4Icon:vge,ColumnsIcon:F8,Combine:bge,CombineIcon:bge,Command:_ge,CommandIcon:_ge,Compass:WO,CompassIcon:WO,Component:wge,ComponentIcon:wge,Computer:jge,ComputerIcon:jge,ConciergeBell:Nge,ConciergeBellIcon:Nge,Cone:kge,ConeIcon:kge,Construction:Sge,ConstructionIcon:Sge,Contact:WM,Contact2:O8,Contact2Icon:O8,ContactIcon:WM,ContactRound:O8,ContactRoundIcon:O8,Container:Cge,ContainerIcon:Cge,Contrast:Age,ContrastIcon:Age,Cookie:Ege,CookieIcon:Ege,CookingPot:Tge,CookingPotIcon:Tge,Copy:Ia,CopyCheck:Mge,CopyCheckIcon:Mge,CopyIcon:Ia,CopyMinus:Pge,CopyMinusIcon:Pge,CopyPlus:Lge,CopyPlusIcon:Lge,CopySlash:Ige,CopySlashIcon:Ige,CopyX:Dge,CopyXIcon:Dge,Copyleft:Rge,CopyleftIcon:Rge,Copyright:Fge,CopyrightIcon:Fge,CornerDownLeft:Oge,CornerDownLeftIcon:Oge,CornerDownRight:NQ,CornerDownRightIcon:NQ,CornerLeftDown:zge,CornerLeftDownIcon:zge,CornerLeftUp:Bge,CornerLeftUpIcon:Bge,CornerRightDown:Uge,CornerRightDownIcon:Uge,CornerRightUp:qge,CornerRightUpIcon:qge,CornerUpLeft:$ge,CornerUpLeftIcon:$ge,CornerUpRight:Vge,CornerUpRightIcon:Vge,Cpu:Hge,CpuIcon:Hge,CreativeCommons:Gge,CreativeCommonsIcon:Gge,CreditCard:_y,CreditCardIcon:_y,Croissant:Wge,CroissantIcon:Wge,Crop:Kge,CropIcon:Kge,Cross:Yge,CrossIcon:Yge,Crosshair:Zge,CrosshairIcon:Zge,Crown:$f,CrownIcon:$f,Cuboid:Xge,CuboidIcon:Xge,CupSoda:Qge,CupSodaIcon:Qge,CurlyBraces:r6,CurlyBracesIcon:r6,Currency:Jge,CurrencyIcon:Jge,Cylinder:e0e,CylinderIcon:e0e,Dam:t0e,DamIcon:t0e,Database:Mq,DatabaseBackup:s0e,DatabaseBackupIcon:s0e,DatabaseIcon:Mq,DatabaseZap:n0e,DatabaseZapIcon:n0e,Delete:r0e,DeleteIcon:r0e,Dessert:a0e,DessertIcon:a0e,Diameter:i0e,DiameterIcon:i0e,Diamond:c0e,DiamondIcon:c0e,DiamondMinus:o0e,DiamondMinusIcon:o0e,DiamondPercent:z8,DiamondPercentIcon:z8,DiamondPlus:l0e,DiamondPlusIcon:l0e,Dice1:d0e,Dice1Icon:d0e,Dice2:u0e,Dice2Icon:u0e,Dice3:h0e,Dice3Icon:h0e,Dice4:m0e,Dice4Icon:m0e,Dice5:p0e,Dice5Icon:p0e,Dice6:f0e,Dice6Icon:f0e,Dices:x0e,DicesIcon:x0e,Diff:g0e,DiffIcon:g0e,Disc:_0e,Disc2:y0e,Disc2Icon:y0e,Disc3:v0e,Disc3Icon:v0e,DiscAlbum:b0e,DiscAlbumIcon:b0e,DiscIcon:_0e,Divide:w0e,DivideCircle:b8,DivideCircleIcon:b8,DivideIcon:w0e,DivideSquare:ZD,DivideSquareIcon:ZD,Dna:N0e,DnaIcon:N0e,DnaOff:j0e,DnaOffIcon:j0e,Dock:k0e,DockIcon:k0e,Dog:S0e,DogIcon:S0e,DollarSign:yd,DollarSignIcon:yd,Donut:C0e,DonutIcon:C0e,DoorClosed:A0e,DoorClosedIcon:A0e,DoorOpen:dN,DoorOpenIcon:dN,Dot:E0e,DotIcon:E0e,DotSquare:XD,DotSquareIcon:XD,Download:li,DownloadCloud:D8,DownloadCloudIcon:D8,DownloadIcon:li,DraftingCompass:T0e,DraftingCompassIcon:T0e,Drama:M0e,DramaIcon:M0e,Dribbble:P0e,DribbbleIcon:P0e,Drill:L0e,DrillIcon:L0e,Droplet:I0e,DropletIcon:I0e,Droplets:m1,DropletsIcon:m1,Drum:D0e,DrumIcon:D0e,Drumstick:R0e,DrumstickIcon:R0e,Dumbbell:F0e,DumbbellIcon:F0e,Ear:z0e,EarIcon:z0e,EarOff:O0e,EarOffIcon:O0e,Earth:$2,EarthIcon:$2,EarthLock:B0e,EarthLockIcon:B0e,Eclipse:U0e,EclipseIcon:U0e,Edit:wp,Edit2:V2,Edit2Icon:V2,Edit3:Qm,Edit3Icon:Qm,EditIcon:wp,Egg:Pq,EggFried:q0e,EggFriedIcon:q0e,EggIcon:Pq,EggOff:$0e,EggOffIcon:$0e,Ellipsis:ob,EllipsisIcon:ob,EllipsisVertical:Xx,EllipsisVerticalIcon:Xx,Equal:G0e,EqualApproximately:V0e,EqualApproximatelyIcon:V0e,EqualIcon:G0e,EqualNot:H0e,EqualNotIcon:H0e,EqualSquare:QD,EqualSquareIcon:QD,Eraser:Lq,EraserIcon:Lq,EthernetPort:W0e,EthernetPortIcon:W0e,Euro:K0e,EuroIcon:K0e,Expand:Y0e,ExpandIcon:Y0e,ExternalLink:wr,ExternalLinkIcon:wr,Eye:ya,EyeClosed:Z0e,EyeClosedIcon:Z0e,EyeIcon:ya,EyeOff:Ax,EyeOffIcon:Ax,Facebook:tf,FacebookIcon:tf,Factory:X0e,FactoryIcon:X0e,Fan:Q0e,FanIcon:Q0e,FastForward:J0e,FastForwardIcon:J0e,Feather:eye,FeatherIcon:eye,Fence:tye,FenceIcon:tye,FerrisWheel:sye,FerrisWheelIcon:sye,Figma:nye,FigmaIcon:nye,File:Dq,FileArchive:rye,FileArchiveIcon:rye,FileAudio:iye,FileAudio2:aye,FileAudio2Icon:aye,FileAudioIcon:iye,FileAxis3D:B8,FileAxis3DIcon:B8,FileAxis3d:B8,FileAxis3dIcon:B8,FileBadge:lye,FileBadge2:oye,FileBadge2Icon:oye,FileBadgeIcon:lye,FileBarChart:U8,FileBarChart2:q8,FileBarChart2Icon:q8,FileBarChartIcon:U8,FileBox:cye,FileBoxIcon:cye,FileChartColumn:q8,FileChartColumnIcon:q8,FileChartColumnIncreasing:U8,FileChartColumnIncreasingIcon:U8,FileChartLine:$8,FileChartLineIcon:$8,FileChartPie:V8,FileChartPieIcon:V8,FileCheck:kQ,FileCheck2:KO,FileCheck2Icon:KO,FileCheckIcon:kQ,FileClock:dye,FileClockIcon:dye,FileCode:hye,FileCode2:uye,FileCode2Icon:uye,FileCodeIcon:hye,FileCog:H8,FileCog2:H8,FileCog2Icon:H8,FileCogIcon:H8,FileDiff:mye,FileDiffIcon:mye,FileDigit:pye,FileDigitIcon:pye,FileDown:hj,FileDownIcon:hj,FileEdit:G8,FileEditIcon:G8,FileHeart:fye,FileHeartIcon:fye,FileIcon:Dq,FileImage:KM,FileImageIcon:KM,FileInput:xye,FileInputIcon:xye,FileJson:yye,FileJson2:gye,FileJson2Icon:gye,FileJsonIcon:yye,FileKey:bye,FileKey2:vye,FileKey2Icon:vye,FileKeyIcon:bye,FileLineChart:$8,FileLineChartIcon:$8,FileLock:wye,FileLock2:_ye,FileLock2Icon:_ye,FileLockIcon:wye,FileMinus:Nye,FileMinus2:jye,FileMinus2Icon:jye,FileMinusIcon:Nye,FileMusic:kye,FileMusicIcon:kye,FileOutput:Sye,FileOutputIcon:Sye,FilePen:G8,FilePenIcon:G8,FilePenLine:lb,FilePenLineIcon:lb,FilePieChart:V8,FilePieChartIcon:V8,FilePlus:Cye,FilePlus2:Iq,FilePlus2Icon:Iq,FilePlusIcon:Cye,FileQuestion:Aye,FileQuestionIcon:Aye,FileScan:Eye,FileScanIcon:Eye,FileSearch:SQ,FileSearch2:Tye,FileSearch2Icon:Tye,FileSearchIcon:SQ,FileSignature:lb,FileSignatureIcon:lb,FileSliders:Mye,FileSlidersIcon:Mye,FileSpreadsheet:uS,FileSpreadsheetIcon:uS,FileStack:CQ,FileStackIcon:CQ,FileSymlink:Pye,FileSymlinkIcon:Pye,FileTerminal:Lye,FileTerminalIcon:Lye,FileText:Fr,FileTextIcon:Fr,FileType:Dye,FileType2:Iye,FileType2Icon:Iye,FileTypeIcon:Dye,FileUp:AQ,FileUpIcon:AQ,FileUser:Rye,FileUserIcon:Rye,FileVideo:EQ,FileVideo2:Fye,FileVideo2Icon:Fye,FileVideoIcon:EQ,FileVolume:zye,FileVolume2:Oye,FileVolume2Icon:Oye,FileVolumeIcon:zye,FileWarning:Bye,FileWarningIcon:Bye,FileX:qye,FileX2:Uye,FileX2Icon:Uye,FileXIcon:qye,Files:$ye,FilesIcon:$ye,Film:dm,FilmIcon:dm,Filter:D_,FilterIcon:D_,FilterX:Vye,FilterXIcon:Vye,Fingerprint:Hye,FingerprintIcon:Hye,FireExtinguisher:Gye,FireExtinguisherIcon:Gye,Fish:Yye,FishIcon:Yye,FishOff:Wye,FishOffIcon:Wye,FishSymbol:Kye,FishSymbolIcon:Kye,Flag:qA,FlagIcon:qA,FlagOff:Zye,FlagOffIcon:Zye,FlagTriangleLeft:Xye,FlagTriangleLeftIcon:Xye,FlagTriangleRight:Qye,FlagTriangleRightIcon:Qye,Flame:gu,FlameIcon:gu,FlameKindling:Jye,FlameKindlingIcon:Jye,Flashlight:tve,FlashlightIcon:tve,FlashlightOff:eve,FlashlightOffIcon:eve,FlaskConical:YM,FlaskConicalIcon:YM,FlaskConicalOff:sve,FlaskConicalOffIcon:sve,FlaskRound:nve,FlaskRoundIcon:nve,FlipHorizontal:TQ,FlipHorizontal2:rve,FlipHorizontal2Icon:rve,FlipHorizontalIcon:TQ,FlipVertical:ive,FlipVertical2:ave,FlipVertical2Icon:ave,FlipVerticalIcon:ive,Flower:ove,Flower2:rS,Flower2Icon:rS,FlowerIcon:ove,Focus:lve,FocusIcon:lve,FoldHorizontal:cve,FoldHorizontalIcon:cve,FoldVertical:dve,FoldVerticalIcon:dve,Folder:Rq,FolderArchive:uve,FolderArchiveIcon:uve,FolderCheck:hve,FolderCheckIcon:hve,FolderClock:mve,FolderClockIcon:mve,FolderClosed:pve,FolderClosedIcon:pve,FolderCode:fve,FolderCodeIcon:fve,FolderCog:W8,FolderCog2:W8,FolderCog2Icon:W8,FolderCogIcon:W8,FolderDot:xve,FolderDotIcon:xve,FolderDown:gve,FolderDownIcon:gve,FolderEdit:K8,FolderEditIcon:K8,FolderGit:vve,FolderGit2:yve,FolderGit2Icon:yve,FolderGitIcon:vve,FolderHeart:bve,FolderHeartIcon:bve,FolderIcon:Rq,FolderInput:_ve,FolderInputIcon:_ve,FolderKanban:wve,FolderKanbanIcon:wve,FolderKey:jve,FolderKeyIcon:jve,FolderLock:Nve,FolderLockIcon:Nve,FolderMinus:kve,FolderMinusIcon:kve,FolderOpen:wy,FolderOpenDot:Sve,FolderOpenDotIcon:Sve,FolderOpenIcon:wy,FolderOutput:Cve,FolderOutputIcon:Cve,FolderPen:K8,FolderPenIcon:K8,FolderPlus:MQ,FolderPlusIcon:MQ,FolderRoot:Ave,FolderRootIcon:Ave,FolderSearch:Tve,FolderSearch2:Eve,FolderSearch2Icon:Eve,FolderSearchIcon:Tve,FolderSymlink:Mve,FolderSymlinkIcon:Mve,FolderSync:Pve,FolderSyncIcon:Pve,FolderTree:Lve,FolderTreeIcon:Lve,FolderUp:Ive,FolderUpIcon:Ive,FolderX:Dve,FolderXIcon:Dve,Folders:Rve,FoldersIcon:Rve,Footprints:Fve,FootprintsIcon:Fve,ForkKnife:DR,ForkKnifeCrossed:IR,ForkKnifeCrossedIcon:IR,ForkKnifeIcon:DR,Forklift:Ove,ForkliftIcon:Ove,FormInput:yD,FormInputIcon:yD,Forward:zve,ForwardIcon:zve,Frame:Bve,FrameIcon:Bve,Framer:Uve,FramerIcon:Uve,Frown:qve,FrownIcon:qve,Fuel:$ve,FuelIcon:$ve,Fullscreen:Vve,FullscreenIcon:Vve,FunctionSquare:JD,FunctionSquareIcon:JD,GalleryHorizontal:Gve,GalleryHorizontalEnd:Hve,GalleryHorizontalEndIcon:Hve,GalleryHorizontalIcon:Gve,GalleryThumbnails:Wve,GalleryThumbnailsIcon:Wve,GalleryVertical:Yve,GalleryVerticalEnd:Kve,GalleryVerticalEndIcon:Kve,GalleryVerticalIcon:Yve,Gamepad:Xve,Gamepad2:Zve,Gamepad2Icon:Zve,GamepadIcon:Xve,GanttChart:a8,GanttChartIcon:a8,GanttChartSquare:I5,GanttChartSquareIcon:I5,Gauge:Qve,GaugeCircle:_8,GaugeCircleIcon:_8,GaugeIcon:Qve,Gavel:Jve,GavelIcon:Jve,Gem:e1e,GemIcon:e1e,Ghost:YO,GhostIcon:YO,Gift:Vo,GiftIcon:Vo,GitBranch:s1e,GitBranchIcon:s1e,GitBranchPlus:t1e,GitBranchPlusIcon:t1e,GitCommit:Y8,GitCommitHorizontal:Y8,GitCommitHorizontalIcon:Y8,GitCommitIcon:Y8,GitCommitVertical:n1e,GitCommitVerticalIcon:n1e,GitCompare:a1e,GitCompareArrows:r1e,GitCompareArrowsIcon:r1e,GitCompareIcon:a1e,GitFork:i1e,GitForkIcon:i1e,GitGraph:o1e,GitGraphIcon:o1e,GitMerge:l1e,GitMergeIcon:l1e,GitPullRequest:p1e,GitPullRequestArrow:c1e,GitPullRequestArrowIcon:c1e,GitPullRequestClosed:d1e,GitPullRequestClosedIcon:d1e,GitPullRequestCreate:h1e,GitPullRequestCreateArrow:u1e,GitPullRequestCreateArrowIcon:u1e,GitPullRequestCreateIcon:h1e,GitPullRequestDraft:m1e,GitPullRequestDraftIcon:m1e,GitPullRequestIcon:p1e,Github:f1e,GithubIcon:f1e,Gitlab:x1e,GitlabIcon:x1e,GlassWater:g1e,GlassWaterIcon:g1e,Glasses:y1e,GlassesIcon:y1e,Globe:sl,Globe2:$2,Globe2Icon:$2,GlobeIcon:sl,GlobeLock:v1e,GlobeLockIcon:v1e,Goal:b1e,GoalIcon:b1e,Grab:_1e,GrabIcon:_1e,GraduationCap:mm,GraduationCapIcon:mm,Grape:w1e,GrapeIcon:w1e,Grid:Uw,Grid2X2:X8,Grid2X2Icon:X8,Grid2X2Plus:Z8,Grid2X2PlusIcon:Z8,Grid2x2:X8,Grid2x2Check:j1e,Grid2x2CheckIcon:j1e,Grid2x2Icon:X8,Grid2x2Plus:Z8,Grid2x2PlusIcon:Z8,Grid2x2X:N1e,Grid2x2XIcon:N1e,Grid3X3:Uw,Grid3X3Icon:Uw,Grid3x3:Uw,Grid3x3Icon:Uw,GridIcon:Uw,Grip:S1e,GripHorizontal:k1e,GripHorizontalIcon:k1e,GripIcon:S1e,GripVertical:Vf,GripVerticalIcon:Vf,Group:C1e,GroupIcon:C1e,Guitar:A1e,GuitarIcon:A1e,Ham:E1e,HamIcon:E1e,Hammer:PQ,HammerIcon:PQ,Hand:Fq,HandCoins:T1e,HandCoinsIcon:T1e,HandHeart:LQ,HandHeartIcon:LQ,HandHelping:x4,HandHelpingIcon:x4,HandIcon:Fq,HandMetal:M1e,HandMetalIcon:M1e,HandPlatter:P1e,HandPlatterIcon:P1e,Handshake:wv,HandshakeIcon:wv,HardDrive:IQ,HardDriveDownload:L1e,HardDriveDownloadIcon:L1e,HardDriveIcon:IQ,HardDriveUpload:I1e,HardDriveUploadIcon:I1e,HardHat:D1e,HardHatIcon:D1e,Hash:ZM,HashIcon:ZM,Haze:R1e,HazeIcon:R1e,HdmiPort:F1e,HdmiPortIcon:F1e,Heading:U1e,Heading1:Oq,Heading1Icon:Oq,Heading2:ZO,Heading2Icon:ZO,Heading3:zq,Heading3Icon:zq,Heading4:O1e,Heading4Icon:O1e,Heading5:z1e,Heading5Icon:z1e,Heading6:B1e,Heading6Icon:B1e,HeadingIcon:U1e,HeadphoneOff:q1e,HeadphoneOffIcon:q1e,Headphones:$1e,HeadphonesIcon:$1e,Headset:V1e,HeadsetIcon:V1e,Heart:Do,HeartCrack:H1e,HeartCrackIcon:H1e,HeartHandshake:DQ,HeartHandshakeIcon:DQ,HeartIcon:Do,HeartOff:G1e,HeartOffIcon:G1e,HeartPulse:W1e,HeartPulseIcon:W1e,Heater:K1e,HeaterIcon:K1e,HelpCircle:f4,HelpCircleIcon:f4,HelpingHand:x4,HelpingHandIcon:x4,Hexagon:Y1e,HexagonIcon:Y1e,Highlighter:Z1e,HighlighterIcon:Z1e,History:R_,HistoryIcon:R_,Home:Jr,HomeIcon:Jr,Hop:Q1e,HopIcon:Q1e,HopOff:X1e,HopOffIcon:X1e,Hospital:J1e,HospitalIcon:J1e,Hotel:ebe,HotelIcon:ebe,Hourglass:RQ,HourglassIcon:RQ,House:Jr,HouseIcon:Jr,HousePlug:tbe,HousePlugIcon:tbe,HousePlus:sbe,HousePlusIcon:sbe,IceCream:J8,IceCream2:Q8,IceCream2Icon:Q8,IceCreamBowl:Q8,IceCreamBowlIcon:Q8,IceCreamCone:J8,IceCreamConeIcon:J8,IceCreamIcon:J8,Icon:aMt,IdCard:FQ,IdCardIcon:FQ,Image:hc,ImageDown:nbe,ImageDownIcon:nbe,ImageIcon:hc,ImageMinus:rbe,ImageMinusIcon:rbe,ImageOff:abe,ImageOffIcon:abe,ImagePlay:ibe,ImagePlayIcon:ibe,ImagePlus:jy,ImagePlusIcon:jy,ImageUp:obe,ImageUpIcon:obe,ImageUpscale:lbe,ImageUpscaleIcon:lbe,Images:cbe,ImagesIcon:cbe,Import:dbe,ImportIcon:dbe,Inbox:XO,InboxIcon:XO,Indent:tD,IndentDecrease:eD,IndentDecreaseIcon:eD,IndentIcon:tD,IndentIncrease:tD,IndentIncreaseIcon:tD,IndianRupee:ube,IndianRupeeIcon:ube,Infinity:Bq,InfinityIcon:Bq,Info:hS,InfoIcon:hS,Inspect:aR,InspectIcon:aR,InspectionPanel:hbe,InspectionPanelIcon:hbe,Instagram:Im,InstagramIcon:Im,Italic:$A,ItalicIcon:$A,IterationCcw:mbe,IterationCcwIcon:mbe,IterationCw:pbe,IterationCwIcon:pbe,JapaneseYen:fbe,JapaneseYenIcon:fbe,Joystick:xbe,JoystickIcon:xbe,Kanban:mj,KanbanIcon:mj,KanbanSquare:eR,KanbanSquareDashed:WD,KanbanSquareDashedIcon:WD,KanbanSquareIcon:eR,Key:_b,KeyIcon:_b,KeyRound:VA,KeyRoundIcon:VA,KeySquare:gbe,KeySquareIcon:gbe,Keyboard:bbe,KeyboardIcon:bbe,KeyboardMusic:ybe,KeyboardMusicIcon:ybe,KeyboardOff:vbe,KeyboardOffIcon:vbe,Lamp:Sbe,LampCeiling:_be,LampCeilingIcon:_be,LampDesk:wbe,LampDeskIcon:wbe,LampFloor:jbe,LampFloorIcon:jbe,LampIcon:Sbe,LampWallDown:Nbe,LampWallDownIcon:Nbe,LampWallUp:kbe,LampWallUpIcon:kbe,LandPlot:Cbe,LandPlotIcon:Cbe,Landmark:Uq,LandmarkIcon:Uq,Languages:Abe,LanguagesIcon:Abe,Laptop:Tbe,Laptop2:sD,Laptop2Icon:sD,LaptopIcon:Tbe,LaptopMinimal:sD,LaptopMinimalCheck:Ebe,LaptopMinimalCheckIcon:Ebe,LaptopMinimalIcon:sD,Lasso:Pbe,LassoIcon:Pbe,LassoSelect:Mbe,LassoSelectIcon:Mbe,Laugh:Lbe,LaughIcon:Lbe,Layers:G4,Layers2:Ibe,Layers2Icon:Ibe,Layers3:Dbe,Layers3Icon:Dbe,LayersIcon:G4,Layout:Z3,LayoutDashboard:XM,LayoutDashboardIcon:XM,LayoutGrid:sf,LayoutGridIcon:sf,LayoutIcon:Z3,LayoutList:Rbe,LayoutListIcon:Rbe,LayoutPanelLeft:Fbe,LayoutPanelLeftIcon:Fbe,LayoutPanelTop:Obe,LayoutPanelTopIcon:Obe,LayoutTemplate:pj,LayoutTemplateIcon:pj,Leaf:zbe,LeafIcon:zbe,LeafyGreen:Bbe,LeafyGreenIcon:Bbe,Lectern:Ube,LecternIcon:Ube,LetterText:qbe,LetterTextIcon:qbe,Library:fj,LibraryBig:$be,LibraryBigIcon:$be,LibraryIcon:fj,LibrarySquare:tR,LibrarySquareIcon:tR,LifeBuoy:qq,LifeBuoyIcon:qq,Ligature:Vbe,LigatureIcon:Vbe,Lightbulb:mS,LightbulbIcon:mS,LightbulbOff:Hbe,LightbulbOffIcon:Hbe,LineChart:s8,LineChartIcon:s8,Link:Vc,Link2:vd,Link2Icon:vd,Link2Off:Gbe,Link2OffIcon:Gbe,LinkIcon:Vc,Linkedin:dg,LinkedinIcon:dg,List:A0,ListCheck:Wbe,ListCheckIcon:Wbe,ListChecks:Ny,ListChecksIcon:Ny,ListCollapse:Kbe,ListCollapseIcon:Kbe,ListEnd:Ybe,ListEndIcon:Ybe,ListFilter:OQ,ListFilterIcon:OQ,ListIcon:A0,ListMinus:Zbe,ListMinusIcon:Zbe,ListMusic:Xbe,ListMusicIcon:Xbe,ListOrdered:xj,ListOrderedIcon:xj,ListPlus:zQ,ListPlusIcon:zQ,ListRestart:Qbe,ListRestartIcon:Qbe,ListStart:Jbe,ListStartIcon:Jbe,ListTodo:e_e,ListTodoIcon:e_e,ListTree:t_e,ListTreeIcon:t_e,ListVideo:s_e,ListVideoIcon:s_e,ListX:n_e,ListXIcon:n_e,Loader:a_e,Loader2:Ct,Loader2Icon:Ct,LoaderCircle:Ct,LoaderCircleIcon:Ct,LoaderIcon:a_e,LoaderPinwheel:r_e,LoaderPinwheelIcon:r_e,Locate:$q,LocateFixed:i_e,LocateFixedIcon:i_e,LocateIcon:$q,LocateOff:o_e,LocateOffIcon:o_e,Lock:ec,LockIcon:ec,LockKeyhole:BQ,LockKeyholeIcon:BQ,LockKeyholeOpen:nD,LockKeyholeOpenIcon:nD,LockOpen:rD,LockOpenIcon:rD,LogIn:QM,LogInIcon:QM,LogOut:QO,LogOutIcon:QO,Logs:l_e,LogsIcon:l_e,Lollipop:c_e,LollipopIcon:c_e,LucideAArrowDown:Gue,LucideAArrowUp:Wue,LucideALargeSmall:Kue,LucideAccessibility:Yue,LucideActivity:hm,LucideActivitySquare:SD,LucideAirVent:Zue,LucideAirplay:Xue,LucideAlarmCheck:RI,LucideAlarmClock:Jue,LucideAlarmClockCheck:RI,LucideAlarmClockMinus:FI,LucideAlarmClockOff:Que,LucideAlarmClockPlus:OI,LucideAlarmMinus:FI,LucideAlarmPlus:OI,LucideAlarmSmoke:ehe,LucideAlbum:the,LucideAlertCircle:Xo,LucideAlertOctagon:Qk,LucideAlertTriangle:xl,LucideAlignCenter:UM,LucideAlignCenterHorizontal:she,LucideAlignCenterVertical:nhe,LucideAlignEndHorizontal:rhe,LucideAlignEndVertical:ahe,LucideAlignHorizontalDistributeCenter:ihe,LucideAlignHorizontalDistributeEnd:ohe,LucideAlignHorizontalDistributeStart:lhe,LucideAlignHorizontalJustifyCenter:che,LucideAlignHorizontalJustifyEnd:dhe,LucideAlignHorizontalJustifyStart:uhe,LucideAlignHorizontalSpaceAround:hhe,LucideAlignHorizontalSpaceBetween:mhe,LucideAlignJustify:phe,LucideAlignLeft:qM,LucideAlignRight:$M,LucideAlignStartHorizontal:fhe,LucideAlignStartVertical:xhe,LucideAlignVerticalDistributeCenter:ghe,LucideAlignVerticalDistributeEnd:yhe,LucideAlignVerticalDistributeStart:vhe,LucideAlignVerticalJustifyCenter:bhe,LucideAlignVerticalJustifyEnd:_he,LucideAlignVerticalJustifyStart:whe,LucideAlignVerticalSpaceAround:jhe,LucideAlignVerticalSpaceBetween:Nhe,LucideAmbulance:khe,LucideAmpersand:She,LucideAmpersands:Che,LucideAmphora:Ahe,LucideAnchor:Ehe,LucideAngry:The,LucideAnnoyed:Mhe,LucideAntenna:Phe,LucideAnvil:Lhe,LucideAperture:Ihe,LucideAppWindow:Rhe,LucideAppWindowMac:Dhe,LucideApple:Fhe,LucideArchive:by,LucideArchiveRestore:VM,LucideArchiveX:Ohe,LucideAreaChart:ZI,LucideArmchair:zhe,LucideArrowBigDown:Uhe,LucideArrowBigDownDash:Bhe,LucideArrowBigLeft:$he,LucideArrowBigLeftDash:qhe,LucideArrowBigRight:Hhe,LucideArrowBigRightDash:Vhe,LucideArrowBigUp:Whe,LucideArrowBigUpDash:Ghe,LucideArrowDown:zf,LucideArrowDown01:Khe,LucideArrowDown10:Yhe,LucideArrowDownAZ:zI,LucideArrowDownAz:zI,LucideArrowDownCircle:l8,LucideArrowDownFromLine:Zhe,LucideArrowDownLeft:Xhe,LucideArrowDownLeftFromCircle:d8,LucideArrowDownLeftFromSquare:MD,LucideArrowDownLeftSquare:CD,LucideArrowDownNarrowWide:Qhe,LucideArrowDownRight:gQ,LucideArrowDownRightFromCircle:u8,LucideArrowDownRightFromSquare:PD,LucideArrowDownRightSquare:AD,LucideArrowDownSquare:ED,LucideArrowDownToDot:Jhe,LucideArrowDownToLine:eme,LucideArrowDownUp:tme,LucideArrowDownWideNarrow:BI,LucideArrowDownZA:UI,LucideArrowDownZa:UI,LucideArrowLeft:ka,LucideArrowLeftCircle:c8,LucideArrowLeftFromLine:sme,LucideArrowLeftRight:yQ,LucideArrowLeftSquare:TD,LucideArrowLeftToLine:nme,LucideArrowRight:La,LucideArrowRightCircle:p8,LucideArrowRightFromLine:rme,LucideArrowRightLeft:U4,LucideArrowRightSquare:DD,LucideArrowRightToLine:ame,LucideArrowUp:sp,LucideArrowUp01:ime,LucideArrowUp10:ome,LucideArrowUpAZ:qI,LucideArrowUpAz:qI,LucideArrowUpCircle:f8,LucideArrowUpDown:Lg,LucideArrowUpFromDot:lme,LucideArrowUpFromLine:cme,LucideArrowUpLeft:dme,LucideArrowUpLeftFromCircle:h8,LucideArrowUpLeftFromSquare:LD,LucideArrowUpLeftSquare:RD,LucideArrowUpNarrowWide:$I,LucideArrowUpRight:$O,LucideArrowUpRightFromCircle:m8,LucideArrowUpRightFromSquare:ID,LucideArrowUpRightSquare:FD,LucideArrowUpSquare:OD,LucideArrowUpToLine:ume,LucideArrowUpWideNarrow:hme,LucideArrowUpZA:VI,LucideArrowUpZa:VI,LucideArrowsUpFromLine:mme,LucideAsterisk:pme,LucideAsteriskSquare:zD,LucideAtSign:fme,LucideAtom:xme,LucideAudioLines:gme,LucideAudioWaveform:yme,LucideAward:Hh,LucideAxe:vme,LucideAxis3D:HI,LucideAxis3d:HI,LucideBaby:bme,LucideBackpack:_me,LucideBadge:Fme,LucideBadgeAlert:wme,LucideBadgeCent:jme,LucideBadgeCheck:K3,LucideBadgeDollarSign:Nme,LucideBadgeEuro:kme,LucideBadgeHelp:Sme,LucideBadgeIndianRupee:Cme,LucideBadgeInfo:Ame,LucideBadgeJapaneseYen:Eme,LucideBadgeMinus:Tme,LucideBadgePercent:Mme,LucideBadgePlus:Pme,LucideBadgePoundSterling:Lme,LucideBadgeRussianRuble:Ime,LucideBadgeSwissFranc:Dme,LucideBadgeX:Rme,LucideBaggageClaim:Ome,LucideBan:VO,LucideBanana:zme,LucideBandage:Bme,LucideBanknote:Ume,LucideBarChart:n8,LucideBarChart2:r8,LucideBarChart3:bl,LucideBarChart4:t8,LucideBarChartBig:e8,LucideBarChartHorizontal:QI,LucideBarChartHorizontalBig:XI,LucideBarcode:qme,LucideBaseline:$me,LucideBath:S0,LucideBattery:Yme,LucideBatteryCharging:Vme,LucideBatteryFull:Hme,LucideBatteryLow:Gme,LucideBatteryMedium:Wme,LucideBatteryWarning:Kme,LucideBeaker:vQ,LucideBean:Xme,LucideBeanOff:Zme,LucideBed:dj,LucideBedDouble:q4,LucideBedSingle:Qme,LucideBeef:Jme,LucideBeer:tpe,LucideBeerOff:epe,LucideBell:Rg,LucideBellDot:spe,LucideBellElectric:npe,LucideBellMinus:rpe,LucideBellOff:cS,LucideBellPlus:ape,LucideBellRing:$4,LucideBetweenHorizonalEnd:GI,LucideBetweenHorizonalStart:WI,LucideBetweenHorizontalEnd:GI,LucideBetweenHorizontalStart:WI,LucideBetweenVerticalEnd:ipe,LucideBetweenVerticalStart:ope,LucideBicepsFlexed:lpe,LucideBike:cpe,LucideBinary:dpe,LucideBinoculars:upe,LucideBiohazard:hpe,LucideBird:mpe,LucideBitcoin:ppe,LucideBlend:fpe,LucideBlinds:xpe,LucideBlocks:gpe,LucideBluetooth:_pe,LucideBluetoothConnected:ype,LucideBluetoothOff:vpe,LucideBluetoothSearching:bpe,LucideBold:BA,LucideBolt:wpe,LucideBomb:jpe,LucideBone:Npe,LucideBook:Gpe,LucideBookA:kpe,LucideBookAudio:Spe,LucideBookCheck:Cpe,LucideBookCopy:Ape,LucideBookDashed:KI,LucideBookDown:Epe,LucideBookHeadphones:Tpe,LucideBookHeart:Mpe,LucideBookImage:Ppe,LucideBookKey:Lpe,LucideBookLock:Ipe,LucideBookMarked:Dpe,LucideBookMinus:Rpe,LucideBookOpen:Sx,LucideBookOpenCheck:Fpe,LucideBookOpenText:Ope,LucideBookPlus:zpe,LucideBookTemplate:KI,LucideBookText:Bpe,LucideBookType:Upe,LucideBookUp:$pe,LucideBookUp2:qpe,LucideBookUser:Vpe,LucideBookX:Hpe,LucideBookmark:C0,LucideBookmarkCheck:Wpe,LucideBookmarkMinus:Kpe,LucideBookmarkPlus:HM,LucideBookmarkX:Ype,LucideBoomBox:Zpe,LucideBot:V4,LucideBotMessageSquare:Xpe,LucideBotOff:Qpe,LucideBox:bQ,LucideBoxSelect:YD,LucideBoxes:Jpe,LucideBraces:r6,LucideBrackets:efe,LucideBrain:_Q,LucideBrainCircuit:tfe,LucideBrainCog:sfe,LucideBrickWall:nfe,LucideBriefcase:Cx,LucideBriefcaseBusiness:rfe,LucideBriefcaseConveyorBelt:afe,LucideBriefcaseMedical:ife,LucideBringToFront:ofe,LucideBrush:lfe,LucideBug:ufe,LucideBugOff:cfe,LucideBugPlay:dfe,LucideBuilding:GM,LucideBuilding2:ai,LucideBus:mfe,LucideBusFront:hfe,LucideCable:ffe,LucideCableCar:pfe,LucideCake:Bf,LucideCakeSlice:xfe,LucideCalculator:uj,LucideCalendar:ga,LucideCalendar1:gfe,LucideCalendarArrowDown:yfe,LucideCalendarArrowUp:vfe,LucideCalendarCheck:bv,LucideCalendarCheck2:bfe,LucideCalendarClock:Qd,LucideCalendarCog:_fe,LucideCalendarDays:pc,LucideCalendarFold:wfe,LucideCalendarHeart:dS,LucideCalendarMinus:Nfe,LucideCalendarMinus2:jfe,LucideCalendarOff:Aq,LucideCalendarPlus:gy,LucideCalendarPlus2:kfe,LucideCalendarRange:Sfe,LucideCalendarSearch:Cfe,LucideCalendarSync:Afe,LucideCalendarX:wQ,LucideCalendarX2:Efe,LucideCamera:cg,LucideCameraOff:Tfe,LucideCandlestickChart:JI,LucideCandy:Lfe,LucideCandyCane:Mfe,LucideCandyOff:Pfe,LucideCannabis:Ife,LucideCaptions:YI,LucideCaptionsOff:Dfe,LucideCar:Ofe,LucideCarFront:Rfe,LucideCarTaxiFront:Ffe,LucideCaravan:zfe,LucideCarrot:Bfe,LucideCaseLower:Ufe,LucideCaseSensitive:qfe,LucideCaseUpper:$fe,LucideCassetteTape:Vfe,LucideCast:Hfe,LucideCastle:Gfe,LucideCat:Wfe,LucideCctv:Kfe,LucideChartArea:ZI,LucideChartBar:QI,LucideChartBarBig:XI,LucideChartBarDecreasing:Yfe,LucideChartBarIncreasing:Zfe,LucideChartBarStacked:Xfe,LucideChartCandlestick:JI,LucideChartColumn:bl,LucideChartColumnBig:e8,LucideChartColumnDecreasing:Qfe,LucideChartColumnIncreasing:t8,LucideChartColumnStacked:Jfe,LucideChartGantt:exe,LucideChartLine:s8,LucideChartNetwork:txe,LucideChartNoAxesColumn:r8,LucideChartNoAxesColumnDecreasing:sxe,LucideChartNoAxesColumnIncreasing:n8,LucideChartNoAxesCombined:nxe,LucideChartNoAxesGantt:a8,LucideChartPie:i8,LucideChartScatter:o8,LucideChartSpline:rxe,LucideCheck:ea,LucideCheckCheck:HO,LucideCheckCircle:_l,LucideCheckCircle2:Er,LucideCheckSquare:Ww,LucideCheckSquare2:UD,LucideChefHat:axe,LucideCherry:ixe,LucideChevronDown:tl,LucideChevronDownCircle:x8,LucideChevronDownSquare:qD,LucideChevronFirst:oxe,LucideChevronLast:lxe,LucideChevronLeft:$c,LucideChevronLeftCircle:g8,LucideChevronLeftSquare:$D,LucideChevronRight:xi,LucideChevronRightCircle:y8,LucideChevronRightSquare:VD,LucideChevronUp:_v,LucideChevronUpCircle:v8,LucideChevronUpSquare:HD,LucideChevronsDown:dxe,LucideChevronsDownUp:cxe,LucideChevronsLeft:mxe,LucideChevronsLeftRight:hxe,LucideChevronsLeftRightEllipsis:uxe,LucideChevronsRight:fxe,LucideChevronsRightLeft:pxe,LucideChevronsUp:xxe,LucideChevronsUpDown:I_,LucideChrome:GO,LucideChurch:gxe,LucideCigarette:vxe,LucideCigaretteOff:yxe,LucideCircle:Uf,LucideCircleAlert:Xo,LucideCircleArrowDown:l8,LucideCircleArrowLeft:c8,LucideCircleArrowOutDownLeft:d8,LucideCircleArrowOutDownRight:u8,LucideCircleArrowOutUpLeft:h8,LucideCircleArrowOutUpRight:m8,LucideCircleArrowRight:p8,LucideCircleArrowUp:f8,LucideCircleCheck:Er,LucideCircleCheckBig:_l,LucideCircleChevronDown:x8,LucideCircleChevronLeft:g8,LucideCircleChevronRight:y8,LucideCircleChevronUp:v8,LucideCircleDashed:bxe,LucideCircleDivide:b8,LucideCircleDollarSign:_xe,LucideCircleDot:jxe,LucideCircleDotDashed:wxe,LucideCircleEllipsis:Nxe,LucideCircleEqual:kxe,LucideCircleFadingArrowUp:Sxe,LucideCircleFadingPlus:Cxe,LucideCircleGauge:_8,LucideCircleHelp:f4,LucideCircleMinus:w8,LucideCircleOff:Axe,LucideCircleParking:N8,LucideCircleParkingOff:j8,LucideCirclePause:k8,LucideCirclePercent:S8,LucideCirclePlay:om,LucideCirclePlus:C8,LucideCirclePower:A8,LucideCircleSlash:Exe,LucideCircleSlash2:E8,LucideCircleSlashed:E8,LucideCircleStop:T8,LucideCircleUser:P8,LucideCircleUserRound:M8,LucideCircleX:Rd,LucideCircuitBoard:Txe,LucideCitrus:Mxe,LucideClapperboard:Eq,LucideClipboard:Oxe,LucideClipboardCheck:cN,LucideClipboardCopy:Pxe,LucideClipboardEdit:I8,LucideClipboardList:qf,LucideClipboardMinus:Lxe,LucideClipboardPaste:Ixe,LucideClipboardPen:I8,LucideClipboardPenLine:L8,LucideClipboardPlus:Dxe,LucideClipboardSignature:L8,LucideClipboardType:Rxe,LucideClipboardX:Fxe,LucideClock:Gr,LucideClock1:zxe,LucideClock10:Bxe,LucideClock11:Uxe,LucideClock12:qxe,LucideClock2:$xe,LucideClock3:Tq,LucideClock4:Vxe,LucideClock5:Hxe,LucideClock6:Gxe,LucideClock7:Wxe,LucideClock8:Kxe,LucideClock9:Yxe,LucideClockAlert:Zxe,LucideClockArrowDown:Xxe,LucideClockArrowUp:Qxe,LucideCloud:mge,LucideCloudAlert:Jxe,LucideCloudCog:ege,LucideCloudDownload:D8,LucideCloudDrizzle:tge,LucideCloudFog:sge,LucideCloudHail:nge,LucideCloudLightning:rge,LucideCloudMoon:ige,LucideCloudMoonRain:age,LucideCloudOff:oge,LucideCloudRain:cge,LucideCloudRainWind:lge,LucideCloudSnow:dge,LucideCloudSun:hge,LucideCloudSunRain:uge,LucideCloudUpload:R8,LucideCloudy:pge,LucideClover:PA,LucideClub:fge,LucideCode:UA,LucideCode2:Y3,LucideCodeSquare:GD,LucideCodeXml:Y3,LucideCodepen:xge,LucideCodesandbox:gge,LucideCoffee:H4,LucideCog:yge,LucideCoins:jQ,LucideColumns:F8,LucideColumns2:F8,LucideColumns3:a6,LucideColumns4:vge,LucideCombine:bge,LucideCommand:_ge,LucideCompass:WO,LucideComponent:wge,LucideComputer:jge,LucideConciergeBell:Nge,LucideCone:kge,LucideConstruction:Sge,LucideContact:WM,LucideContact2:O8,LucideContactRound:O8,LucideContainer:Cge,LucideContrast:Age,LucideCookie:Ege,LucideCookingPot:Tge,LucideCopy:Ia,LucideCopyCheck:Mge,LucideCopyMinus:Pge,LucideCopyPlus:Lge,LucideCopySlash:Ige,LucideCopyX:Dge,LucideCopyleft:Rge,LucideCopyright:Fge,LucideCornerDownLeft:Oge,LucideCornerDownRight:NQ,LucideCornerLeftDown:zge,LucideCornerLeftUp:Bge,LucideCornerRightDown:Uge,LucideCornerRightUp:qge,LucideCornerUpLeft:$ge,LucideCornerUpRight:Vge,LucideCpu:Hge,LucideCreativeCommons:Gge,LucideCreditCard:_y,LucideCroissant:Wge,LucideCrop:Kge,LucideCross:Yge,LucideCrosshair:Zge,LucideCrown:$f,LucideCuboid:Xge,LucideCupSoda:Qge,LucideCurlyBraces:r6,LucideCurrency:Jge,LucideCylinder:e0e,LucideDam:t0e,LucideDatabase:Mq,LucideDatabaseBackup:s0e,LucideDatabaseZap:n0e,LucideDelete:r0e,LucideDessert:a0e,LucideDiameter:i0e,LucideDiamond:c0e,LucideDiamondMinus:o0e,LucideDiamondPercent:z8,LucideDiamondPlus:l0e,LucideDice1:d0e,LucideDice2:u0e,LucideDice3:h0e,LucideDice4:m0e,LucideDice5:p0e,LucideDice6:f0e,LucideDices:x0e,LucideDiff:g0e,LucideDisc:_0e,LucideDisc2:y0e,LucideDisc3:v0e,LucideDiscAlbum:b0e,LucideDivide:w0e,LucideDivideCircle:b8,LucideDivideSquare:ZD,LucideDna:N0e,LucideDnaOff:j0e,LucideDock:k0e,LucideDog:S0e,LucideDollarSign:yd,LucideDonut:C0e,LucideDoorClosed:A0e,LucideDoorOpen:dN,LucideDot:E0e,LucideDotSquare:XD,LucideDownload:li,LucideDownloadCloud:D8,LucideDraftingCompass:T0e,LucideDrama:M0e,LucideDribbble:P0e,LucideDrill:L0e,LucideDroplet:I0e,LucideDroplets:m1,LucideDrum:D0e,LucideDrumstick:R0e,LucideDumbbell:F0e,LucideEar:z0e,LucideEarOff:O0e,LucideEarth:$2,LucideEarthLock:B0e,LucideEclipse:U0e,LucideEdit:wp,LucideEdit2:V2,LucideEdit3:Qm,LucideEgg:Pq,LucideEggFried:q0e,LucideEggOff:$0e,LucideEllipsis:ob,LucideEllipsisVertical:Xx,LucideEqual:G0e,LucideEqualApproximately:V0e,LucideEqualNot:H0e,LucideEqualSquare:QD,LucideEraser:Lq,LucideEthernetPort:W0e,LucideEuro:K0e,LucideExpand:Y0e,LucideExternalLink:wr,LucideEye:ya,LucideEyeClosed:Z0e,LucideEyeOff:Ax,LucideFacebook:tf,LucideFactory:X0e,LucideFan:Q0e,LucideFastForward:J0e,LucideFeather:eye,LucideFence:tye,LucideFerrisWheel:sye,LucideFigma:nye,LucideFile:Dq,LucideFileArchive:rye,LucideFileAudio:iye,LucideFileAudio2:aye,LucideFileAxis3D:B8,LucideFileAxis3d:B8,LucideFileBadge:lye,LucideFileBadge2:oye,LucideFileBarChart:U8,LucideFileBarChart2:q8,LucideFileBox:cye,LucideFileChartColumn:q8,LucideFileChartColumnIncreasing:U8,LucideFileChartLine:$8,LucideFileChartPie:V8,LucideFileCheck:kQ,LucideFileCheck2:KO,LucideFileClock:dye,LucideFileCode:hye,LucideFileCode2:uye,LucideFileCog:H8,LucideFileCog2:H8,LucideFileDiff:mye,LucideFileDigit:pye,LucideFileDown:hj,LucideFileEdit:G8,LucideFileHeart:fye,LucideFileImage:KM,LucideFileInput:xye,LucideFileJson:yye,LucideFileJson2:gye,LucideFileKey:bye,LucideFileKey2:vye,LucideFileLineChart:$8,LucideFileLock:wye,LucideFileLock2:_ye,LucideFileMinus:Nye,LucideFileMinus2:jye,LucideFileMusic:kye,LucideFileOutput:Sye,LucideFilePen:G8,LucideFilePenLine:lb,LucideFilePieChart:V8,LucideFilePlus:Cye,LucideFilePlus2:Iq,LucideFileQuestion:Aye,LucideFileScan:Eye,LucideFileSearch:SQ,LucideFileSearch2:Tye,LucideFileSignature:lb,LucideFileSliders:Mye,LucideFileSpreadsheet:uS,LucideFileStack:CQ,LucideFileSymlink:Pye,LucideFileTerminal:Lye,LucideFileText:Fr,LucideFileType:Dye,LucideFileType2:Iye,LucideFileUp:AQ,LucideFileUser:Rye,LucideFileVideo:EQ,LucideFileVideo2:Fye,LucideFileVolume:zye,LucideFileVolume2:Oye,LucideFileWarning:Bye,LucideFileX:qye,LucideFileX2:Uye,LucideFiles:$ye,LucideFilm:dm,LucideFilter:D_,LucideFilterX:Vye,LucideFingerprint:Hye,LucideFireExtinguisher:Gye,LucideFish:Yye,LucideFishOff:Wye,LucideFishSymbol:Kye,LucideFlag:qA,LucideFlagOff:Zye,LucideFlagTriangleLeft:Xye,LucideFlagTriangleRight:Qye,LucideFlame:gu,LucideFlameKindling:Jye,LucideFlashlight:tve,LucideFlashlightOff:eve,LucideFlaskConical:YM,LucideFlaskConicalOff:sve,LucideFlaskRound:nve,LucideFlipHorizontal:TQ,LucideFlipHorizontal2:rve,LucideFlipVertical:ive,LucideFlipVertical2:ave,LucideFlower:ove,LucideFlower2:rS,LucideFocus:lve,LucideFoldHorizontal:cve,LucideFoldVertical:dve,LucideFolder:Rq,LucideFolderArchive:uve,LucideFolderCheck:hve,LucideFolderClock:mve,LucideFolderClosed:pve,LucideFolderCode:fve,LucideFolderCog:W8,LucideFolderCog2:W8,LucideFolderDot:xve,LucideFolderDown:gve,LucideFolderEdit:K8,LucideFolderGit:vve,LucideFolderGit2:yve,LucideFolderHeart:bve,LucideFolderInput:_ve,LucideFolderKanban:wve,LucideFolderKey:jve,LucideFolderLock:Nve,LucideFolderMinus:kve,LucideFolderOpen:wy,LucideFolderOpenDot:Sve,LucideFolderOutput:Cve,LucideFolderPen:K8,LucideFolderPlus:MQ,LucideFolderRoot:Ave,LucideFolderSearch:Tve,LucideFolderSearch2:Eve,LucideFolderSymlink:Mve,LucideFolderSync:Pve,LucideFolderTree:Lve,LucideFolderUp:Ive,LucideFolderX:Dve,LucideFolders:Rve,LucideFootprints:Fve,LucideForkKnife:DR,LucideForkKnifeCrossed:IR,LucideForklift:Ove,LucideFormInput:yD,LucideForward:zve,LucideFrame:Bve,LucideFramer:Uve,LucideFrown:qve,LucideFuel:$ve,LucideFullscreen:Vve,LucideFunctionSquare:JD,LucideGalleryHorizontal:Gve,LucideGalleryHorizontalEnd:Hve,LucideGalleryThumbnails:Wve,LucideGalleryVertical:Yve,LucideGalleryVerticalEnd:Kve,LucideGamepad:Xve,LucideGamepad2:Zve,LucideGanttChart:a8,LucideGanttChartSquare:I5,LucideGauge:Qve,LucideGaugeCircle:_8,LucideGavel:Jve,LucideGem:e1e,LucideGhost:YO,LucideGift:Vo,LucideGitBranch:s1e,LucideGitBranchPlus:t1e,LucideGitCommit:Y8,LucideGitCommitHorizontal:Y8,LucideGitCommitVertical:n1e,LucideGitCompare:a1e,LucideGitCompareArrows:r1e,LucideGitFork:i1e,LucideGitGraph:o1e,LucideGitMerge:l1e,LucideGitPullRequest:p1e,LucideGitPullRequestArrow:c1e,LucideGitPullRequestClosed:d1e,LucideGitPullRequestCreate:h1e,LucideGitPullRequestCreateArrow:u1e,LucideGitPullRequestDraft:m1e,LucideGithub:f1e,LucideGitlab:x1e,LucideGlassWater:g1e,LucideGlasses:y1e,LucideGlobe:sl,LucideGlobe2:$2,LucideGlobeLock:v1e,LucideGoal:b1e,LucideGrab:_1e,LucideGraduationCap:mm,LucideGrape:w1e,LucideGrid:Uw,LucideGrid2X2:X8,LucideGrid2X2Plus:Z8,LucideGrid2x2:X8,LucideGrid2x2Check:j1e,LucideGrid2x2Plus:Z8,LucideGrid2x2X:N1e,LucideGrid3X3:Uw,LucideGrid3x3:Uw,LucideGrip:S1e,LucideGripHorizontal:k1e,LucideGripVertical:Vf,LucideGroup:C1e,LucideGuitar:A1e,LucideHam:E1e,LucideHammer:PQ,LucideHand:Fq,LucideHandCoins:T1e,LucideHandHeart:LQ,LucideHandHelping:x4,LucideHandMetal:M1e,LucideHandPlatter:P1e,LucideHandshake:wv,LucideHardDrive:IQ,LucideHardDriveDownload:L1e,LucideHardDriveUpload:I1e,LucideHardHat:D1e,LucideHash:ZM,LucideHaze:R1e,LucideHdmiPort:F1e,LucideHeading:U1e,LucideHeading1:Oq,LucideHeading2:ZO,LucideHeading3:zq,LucideHeading4:O1e,LucideHeading5:z1e,LucideHeading6:B1e,LucideHeadphoneOff:q1e,LucideHeadphones:$1e,LucideHeadset:V1e,LucideHeart:Do,LucideHeartCrack:H1e,LucideHeartHandshake:DQ,LucideHeartOff:G1e,LucideHeartPulse:W1e,LucideHeater:K1e,LucideHelpCircle:f4,LucideHelpingHand:x4,LucideHexagon:Y1e,LucideHighlighter:Z1e,LucideHistory:R_,LucideHome:Jr,LucideHop:Q1e,LucideHopOff:X1e,LucideHospital:J1e,LucideHotel:ebe,LucideHourglass:RQ,LucideHouse:Jr,LucideHousePlug:tbe,LucideHousePlus:sbe,LucideIceCream:J8,LucideIceCream2:Q8,LucideIceCreamBowl:Q8,LucideIceCreamCone:J8,LucideIdCard:FQ,LucideImage:hc,LucideImageDown:nbe,LucideImageMinus:rbe,LucideImageOff:abe,LucideImagePlay:ibe,LucideImagePlus:jy,LucideImageUp:obe,LucideImageUpscale:lbe,LucideImages:cbe,LucideImport:dbe,LucideInbox:XO,LucideIndent:tD,LucideIndentDecrease:eD,LucideIndentIncrease:tD,LucideIndianRupee:ube,LucideInfinity:Bq,LucideInfo:hS,LucideInspect:aR,LucideInspectionPanel:hbe,LucideInstagram:Im,LucideItalic:$A,LucideIterationCcw:mbe,LucideIterationCw:pbe,LucideJapaneseYen:fbe,LucideJoystick:xbe,LucideKanban:mj,LucideKanbanSquare:eR,LucideKanbanSquareDashed:WD,LucideKey:_b,LucideKeyRound:VA,LucideKeySquare:gbe,LucideKeyboard:bbe,LucideKeyboardMusic:ybe,LucideKeyboardOff:vbe,LucideLamp:Sbe,LucideLampCeiling:_be,LucideLampDesk:wbe,LucideLampFloor:jbe,LucideLampWallDown:Nbe,LucideLampWallUp:kbe,LucideLandPlot:Cbe,LucideLandmark:Uq,LucideLanguages:Abe,LucideLaptop:Tbe,LucideLaptop2:sD,LucideLaptopMinimal:sD,LucideLaptopMinimalCheck:Ebe,LucideLasso:Pbe,LucideLassoSelect:Mbe,LucideLaugh:Lbe,LucideLayers:G4,LucideLayers2:Ibe,LucideLayers3:Dbe,LucideLayout:Z3,LucideLayoutDashboard:XM,LucideLayoutGrid:sf,LucideLayoutList:Rbe,LucideLayoutPanelLeft:Fbe,LucideLayoutPanelTop:Obe,LucideLayoutTemplate:pj,LucideLeaf:zbe,LucideLeafyGreen:Bbe,LucideLectern:Ube,LucideLetterText:qbe,LucideLibrary:fj,LucideLibraryBig:$be,LucideLibrarySquare:tR,LucideLifeBuoy:qq,LucideLigature:Vbe,LucideLightbulb:mS,LucideLightbulbOff:Hbe,LucideLineChart:s8,LucideLink:Vc,LucideLink2:vd,LucideLink2Off:Gbe,LucideLinkedin:dg,LucideList:A0,LucideListCheck:Wbe,LucideListChecks:Ny,LucideListCollapse:Kbe,LucideListEnd:Ybe,LucideListFilter:OQ,LucideListMinus:Zbe,LucideListMusic:Xbe,LucideListOrdered:xj,LucideListPlus:zQ,LucideListRestart:Qbe,LucideListStart:Jbe,LucideListTodo:e_e,LucideListTree:t_e,LucideListVideo:s_e,LucideListX:n_e,LucideLoader:a_e,LucideLoader2:Ct,LucideLoaderCircle:Ct,LucideLoaderPinwheel:r_e,LucideLocate:$q,LucideLocateFixed:i_e,LucideLocateOff:o_e,LucideLock:ec,LucideLockKeyhole:BQ,LucideLockKeyholeOpen:nD,LucideLockOpen:rD,LucideLogIn:QM,LucideLogOut:QO,LucideLogs:l_e,LucideLollipop:c_e,LucideLuggage:d_e,LucideMSquare:sR,LucideMagnet:u_e,LucideMail:ln,LucideMailCheck:JO,LucideMailMinus:h_e,LucideMailOpen:Vq,LucideMailPlus:Hq,LucideMailQuestion:m_e,LucideMailSearch:p_e,LucideMailWarning:f_e,LucideMailX:JM,LucideMailbox:x_e,LucideMails:g_e,LucideMap:e7,LucideMapPin:Xa,LucideMapPinCheck:v_e,LucideMapPinCheckInside:y_e,LucideMapPinHouse:b_e,LucideMapPinMinus:w_e,LucideMapPinMinusInside:__e,LucideMapPinOff:j_e,LucideMapPinPlus:k_e,LucideMapPinPlusInside:N_e,LucideMapPinX:C_e,LucideMapPinXInside:S_e,LucideMapPinned:UQ,LucideMartini:A_e,LucideMaximize:t7,LucideMaximize2:qQ,LucideMedal:HA,LucideMegaphone:wh,LucideMegaphoneOff:E_e,LucideMeh:T_e,LucideMemoryStick:M_e,LucideMenu:GA,LucideMenuSquare:nR,LucideMerge:s7,LucideMessageCircle:Ou,LucideMessageCircleCode:P_e,LucideMessageCircleDashed:L_e,LucideMessageCircleHeart:Gq,LucideMessageCircleMore:I_e,LucideMessageCircleOff:D_e,LucideMessageCirclePlus:R_e,LucideMessageCircleQuestion:$Q,LucideMessageCircleReply:F_e,LucideMessageCircleWarning:O_e,LucideMessageCircleX:z_e,LucideMessageSquare:Hi,LucideMessageSquareCode:B_e,LucideMessageSquareDashed:U_e,LucideMessageSquareDiff:q_e,LucideMessageSquareDot:$_e,LucideMessageSquareHeart:V_e,LucideMessageSquareLock:H_e,LucideMessageSquareMore:VQ,LucideMessageSquareOff:G_e,LucideMessageSquarePlus:E4,LucideMessageSquareQuote:WA,LucideMessageSquareReply:HQ,LucideMessageSquareShare:W_e,LucideMessageSquareText:K_e,LucideMessageSquareWarning:GQ,LucideMessageSquareX:Y_e,LucideMessagesSquare:WQ,LucideMic:n7,LucideMic2:aD,LucideMicOff:Z_e,LucideMicVocal:aD,LucideMicrochip:X_e,LucideMicroscope:Q_e,LucideMicrowave:J_e,LucideMilestone:ewe,LucideMilk:swe,LucideMilkOff:twe,LucideMinimize:rwe,LucideMinimize2:nwe,LucideMinus:uN,LucideMinusCircle:w8,LucideMinusSquare:rR,LucideMonitor:hN,LucideMonitorCheck:awe,LucideMonitorCog:iwe,LucideMonitorDot:owe,LucideMonitorDown:lwe,LucideMonitorOff:cwe,LucideMonitorPause:dwe,LucideMonitorPlay:Wq,LucideMonitorSmartphone:uwe,LucideMonitorSpeaker:hwe,LucideMonitorStop:mwe,LucideMonitorUp:r7,LucideMonitorX:pwe,LucideMoon:xwe,LucideMoonStar:fwe,LucideMoreHorizontal:ob,LucideMoreVertical:Xx,LucideMountain:ywe,LucideMountainSnow:gwe,LucideMouse:_we,LucideMouseOff:vwe,LucideMousePointer:v0,LucideMousePointer2:KQ,LucideMousePointerBan:bwe,LucideMousePointerClick:$h,LucideMousePointerSquareDashed:KD,LucideMove:YQ,LucideMove3D:iD,LucideMove3d:iD,LucideMoveDiagonal:jwe,LucideMoveDiagonal2:wwe,LucideMoveDown:Swe,LucideMoveDownLeft:Nwe,LucideMoveDownRight:kwe,LucideMoveHorizontal:Cwe,LucideMoveLeft:Awe,LucideMoveRight:Ewe,LucideMoveUp:Pwe,LucideMoveUpLeft:Twe,LucideMoveUpRight:Mwe,LucideMoveVertical:Lwe,LucideMusic:Kq,LucideMusic2:Iwe,LucideMusic3:Dwe,LucideMusic4:Rwe,LucideNavigation:ZQ,LucideNavigation2:Owe,LucideNavigation2Off:Fwe,LucideNavigationOff:zwe,LucideNetwork:Bwe,LucideNewspaper:mN,LucideNfc:Uwe,LucideNotebook:Hwe,LucideNotebookPen:qwe,LucideNotebookTabs:$we,LucideNotebookText:Vwe,LucideNotepadText:Wwe,LucideNotepadTextDashed:Gwe,LucideNut:Ywe,LucideNutOff:Kwe,LucideOctagon:Xwe,LucideOctagonAlert:Qk,LucideOctagonMinus:Zwe,LucideOctagonPause:oD,LucideOctagonX:lD,LucideOmega:Qwe,LucideOption:Jwe,LucideOrbit:eje,LucideOrigami:tje,LucideOutdent:eD,LucidePackage:Nh,LucidePackage2:sje,LucidePackageCheck:nje,LucidePackageMinus:rje,LucidePackageOpen:aje,LucidePackagePlus:ije,LucidePackageSearch:oje,LucidePackageX:lje,LucidePaintBucket:cje,LucidePaintRoller:dje,LucidePaintbrush:uje,LucidePaintbrush2:cD,LucidePaintbrushVertical:cD,LucidePalette:Xc,LucidePalmtree:SR,LucidePanelBottom:pje,LucidePanelBottomClose:hje,LucidePanelBottomDashed:dD,LucidePanelBottomInactive:dD,LucidePanelBottomOpen:mje,LucidePanelLeft:pD,LucidePanelLeftClose:uD,LucidePanelLeftDashed:hD,LucidePanelLeftInactive:hD,LucidePanelLeftOpen:mD,LucidePanelRight:gje,LucidePanelRightClose:fje,LucidePanelRightDashed:fD,LucidePanelRightInactive:fD,LucidePanelRightOpen:xje,LucidePanelTop:bje,LucidePanelTopClose:yje,LucidePanelTopDashed:xD,LucidePanelTopInactive:xD,LucidePanelTopOpen:vje,LucidePanelsLeftBottom:_je,LucidePanelsLeftRight:a6,LucidePanelsRightBottom:wje,LucidePanelsTopBottom:_D,LucidePanelsTopLeft:Z3,LucidePaperclip:eP,LucideParentheses:jje,LucideParkingCircle:N8,LucideParkingCircleOff:j8,LucideParkingMeter:Nje,LucideParkingSquare:oR,LucideParkingSquareOff:iR,LucidePartyPopper:Ex,LucidePause:ky,LucidePauseCircle:k8,LucidePauseOctagon:oD,LucidePawPrint:kje,LucidePcCase:Sje,LucidePen:V2,LucidePenBox:wp,LucidePenLine:Qm,LucidePenOff:Cje,LucidePenSquare:wp,LucidePenTool:KA,LucidePencil:Ya,LucidePencilLine:Yq,LucidePencilOff:Aje,LucidePencilRuler:Eje,LucidePentagon:Tje,LucidePercent:F_,LucidePercentCircle:S8,LucidePercentDiamond:z8,LucidePercentSquare:lR,LucidePersonStanding:Mje,LucidePhilippinePeso:Pje,LucidePhone:_a,LucidePhoneCall:XQ,LucidePhoneForwarded:Lje,LucidePhoneIncoming:Ije,LucidePhoneMissed:Dje,LucidePhoneOff:Rje,LucidePhoneOutgoing:Fje,LucidePi:Oje,LucidePiSquare:cR,LucidePiano:zje,LucidePickaxe:Bje,LucidePictureInPicture:qje,LucidePictureInPicture2:Uje,LucidePieChart:i8,LucidePiggyBank:QQ,LucidePilcrow:Hje,LucidePilcrowLeft:$je,LucidePilcrowRight:Vje,LucidePilcrowSquare:dR,LucidePill:Wje,LucidePillBottle:Gje,LucidePin:YA,LucidePinOff:JQ,LucidePipette:Kje,LucidePizza:Yje,LucidePlane:eJ,LucidePlaneLanding:Zje,LucidePlaneTakeoff:Xje,LucidePlay:Jd,LucidePlayCircle:om,LucidePlaySquare:uR,LucidePlug:pN,LucidePlug2:Qje,LucidePlugZap:gD,LucidePlugZap2:gD,LucidePlus:rn,LucidePlusCircle:C8,LucidePlusSquare:hR,LucidePocket:e2e,LucidePocketKnife:Jje,LucidePodcast:t2e,LucidePointer:n2e,LucidePointerOff:s2e,LucidePopcorn:r2e,LucidePopsicle:a2e,LucidePoundSterling:i2e,LucidePower:tJ,LucidePowerCircle:A8,LucidePowerOff:o2e,LucidePowerSquare:mR,LucidePresentation:jv,LucidePrinter:ZA,LucidePrinterCheck:l2e,LucideProjector:c2e,LucideProportions:d2e,LucidePuzzle:u2e,LucidePyramid:h2e,LucideQrCode:Hf,LucideQuote:pS,LucideRabbit:m2e,LucideRadar:Zq,LucideRadiation:p2e,LucideRadical:f2e,LucideRadio:Nv,LucideRadioReceiver:x2e,LucideRadioTower:g2e,LucideRadius:y2e,LucideRailSymbol:v2e,LucideRainbow:b2e,LucideRat:_2e,LucideRatio:w2e,LucideReceipt:sJ,LucideReceiptCent:j2e,LucideReceiptEuro:N2e,LucideReceiptIndianRupee:k2e,LucideReceiptJapaneseYen:S2e,LucideReceiptPoundSterling:C2e,LucideReceiptRussianRuble:A2e,LucideReceiptSwissFranc:E2e,LucideReceiptText:T2e,LucideRectangleEllipsis:yD,LucideRectangleHorizontal:M2e,LucideRectangleVertical:P2e,LucideRecycle:L2e,LucideRedo:XA,LucideRedo2:I2e,LucideRedoDot:D2e,LucideRefreshCcw:Xq,LucideRefreshCcwDot:R2e,LucideRefreshCw:uo,LucideRefreshCwOff:F2e,LucideRefrigerator:O2e,LucideRegex:z2e,LucideRemoveFormatting:B2e,LucideRepeat:QA,LucideRepeat1:U2e,LucideRepeat2:nJ,LucideReplace:$2e,LucideReplaceAll:q2e,LucideReply:Qq,LucideReplyAll:V2e,LucideRewind:H2e,LucideRibbon:G2e,LucideRocket:Sy,LucideRockingChair:W2e,LucideRollerCoaster:K2e,LucideRotate3D:vD,LucideRotate3d:vD,LucideRotateCcw:Tx,LucideRotateCcwSquare:Y2e,LucideRotateCw:a7,LucideRotateCwSquare:Z2e,LucideRoute:Jq,LucideRouteOff:X2e,LucideRouter:Q2e,LucideRows:bD,LucideRows2:bD,LucideRows3:_D,LucideRows4:J2e,LucideRss:eNe,LucideRuler:W4,LucideRussianRuble:tNe,LucideSailboat:sNe,LucideSalad:nNe,LucideSandwich:rNe,LucideSatellite:iNe,LucideSatelliteDish:aNe,LucideSave:Ho,LucideSaveAll:oNe,LucideSaveOff:lNe,LucideScale:cNe,LucideScale3D:wD,LucideScale3d:wD,LucideScaling:dNe,LucideScan:yNe,LucideScanBarcode:uNe,LucideScanEye:hNe,LucideScanFace:mNe,LucideScanLine:pNe,LucideScanQrCode:fNe,LucideScanSearch:xNe,LucideScanText:gNe,LucideScatterChart:o8,LucideSchool:vNe,LucideSchool2:AR,LucideScissors:_Ne,LucideScissorsLineDashed:bNe,LucideScissorsSquare:pR,LucideScissorsSquareDashedBottom:BD,LucideScreenShare:jNe,LucideScreenShareOff:wNe,LucideScroll:NNe,LucideScrollText:e$,LucideSearch:Lr,LucideSearchCheck:kNe,LucideSearchCode:SNe,LucideSearchSlash:CNe,LucideSearchX:t$,LucideSection:ANe,LucideSend:Or,LucideSendHorizonal:jD,LucideSendHorizontal:jD,LucideSendToBack:ENe,LucideSeparatorHorizontal:TNe,LucideSeparatorVertical:MNe,LucideServer:DNe,LucideServerCog:PNe,LucideServerCrash:LNe,LucideServerOff:INe,LucideSettings:qc,LucideSettings2:fS,LucideShapes:RNe,LucideShare:rJ,LucideShare2:bd,LucideSheet:FNe,LucideShell:ONe,LucideShield:Rm,LucideShieldAlert:s$,LucideShieldBan:zNe,LucideShieldCheck:Dm,LucideShieldClose:ND,LucideShieldEllipsis:BNe,LucideShieldHalf:UNe,LucideShieldMinus:qNe,LucideShieldOff:i7,LucideShieldPlus:$Ne,LucideShieldQuestion:o7,LucideShieldX:ND,LucideShip:HNe,LucideShipWheel:VNe,LucideShirt:GNe,LucideShoppingBag:K4,LucideShoppingBasket:WNe,LucideShoppingCart:xS,LucideShovel:KNe,LucideShowerHead:YNe,LucideShrink:ZNe,LucideShrub:XNe,LucideShuffle:l7,LucideSidebar:pD,LucideSidebarClose:uD,LucideSidebarOpen:mD,LucideSigma:QNe,LucideSigmaSquare:fR,LucideSignal:nke,LucideSignalHigh:JNe,LucideSignalLow:eke,LucideSignalMedium:tke,LucideSignalZero:ske,LucideSignature:rke,LucideSignpost:aJ,LucideSignpostBig:ake,LucideSiren:ike,LucideSkipBack:oke,LucideSkipForward:iJ,LucideSkull:lke,LucideSlack:cke,LucideSlash:dke,LucideSlashSquare:xR,LucideSlice:uke,LucideSliders:kD,LucideSlidersHorizontal:tP,LucideSlidersVertical:kD,LucideSmartphone:p1,LucideSmartphoneCharging:hke,LucideSmartphoneNfc:mke,LucideSmile:fke,LucideSmilePlus:pke,LucideSnail:xke,LucideSnowflake:sj,LucideSofa:n$,LucideSortAsc:$I,LucideSortDesc:BI,LucideSoup:gke,LucideSpace:yke,LucideSpade:vke,LucideSparkle:sP,LucideSparkles:un,LucideSpeaker:bke,LucideSpeech:_ke,LucideSpellCheck:jke,LucideSpellCheck2:wke,LucideSpline:Nke,LucideSplit:kke,LucideSplitSquareHorizontal:gR,LucideSplitSquareVertical:yR,LucideSprayCan:Ske,LucideSprout:nP,LucideSquare:wb,LucideSquareActivity:SD,LucideSquareArrowDown:ED,LucideSquareArrowDownLeft:CD,LucideSquareArrowDownRight:AD,LucideSquareArrowLeft:TD,LucideSquareArrowOutDownLeft:MD,LucideSquareArrowOutDownRight:PD,LucideSquareArrowOutUpLeft:LD,LucideSquareArrowOutUpRight:ID,LucideSquareArrowRight:DD,LucideSquareArrowUp:OD,LucideSquareArrowUpLeft:RD,LucideSquareArrowUpRight:FD,LucideSquareAsterisk:zD,LucideSquareBottomDashedScissors:BD,LucideSquareChartGantt:I5,LucideSquareCheck:UD,LucideSquareCheckBig:Ww,LucideSquareChevronDown:qD,LucideSquareChevronLeft:$D,LucideSquareChevronRight:VD,LucideSquareChevronUp:HD,LucideSquareCode:GD,LucideSquareDashed:YD,LucideSquareDashedBottom:Ake,LucideSquareDashedBottomCode:Cke,LucideSquareDashedKanban:WD,LucideSquareDashedMousePointer:KD,LucideSquareDivide:ZD,LucideSquareDot:XD,LucideSquareEqual:QD,LucideSquareFunction:JD,LucideSquareGanttChart:I5,LucideSquareKanban:eR,LucideSquareLibrary:tR,LucideSquareM:sR,LucideSquareMenu:nR,LucideSquareMinus:rR,LucideSquareMousePointer:aR,LucideSquareParking:oR,LucideSquareParkingOff:iR,LucideSquarePen:wp,LucideSquarePercent:lR,LucideSquarePi:cR,LucideSquarePilcrow:dR,LucideSquarePlay:uR,LucideSquarePlus:hR,LucideSquarePower:mR,LucideSquareRadical:Eke,LucideSquareScissors:pR,LucideSquareSigma:fR,LucideSquareSlash:xR,LucideSquareSplitHorizontal:gR,LucideSquareSplitVertical:yR,LucideSquareSquare:Tke,LucideSquareStack:Mke,LucideSquareTerminal:vR,LucideSquareUser:_R,LucideSquareUserRound:bR,LucideSquareX:wR,LucideSquircle:Pke,LucideSquirrel:Lke,LucideStamp:Ike,LucideStar:Da,LucideStarHalf:Dke,LucideStarOff:Rke,LucideStars:un,LucideStepBack:Fke,LucideStepForward:Oke,LucideStethoscope:zke,LucideSticker:Bke,LucideStickyNote:c7,LucideStopCircle:T8,LucideStore:r$,LucideStretchHorizontal:Uke,LucideStretchVertical:qke,LucideStrikethrough:oJ,LucideSubscript:$ke,LucideSubtitles:YI,LucideSun:fN,LucideSunDim:Vke,LucideSunMedium:Hke,LucideSunMoon:Gke,LucideSunSnow:Wke,LucideSunrise:Kke,LucideSunset:Yke,LucideSuperscript:Zke,LucideSwatchBook:Xke,LucideSwissFranc:Qke,LucideSwitchCamera:Jke,LucideSword:eSe,LucideSwords:tSe,LucideSyringe:sSe,LucideTable:i$,LucideTable2:a$,LucideTableCellsMerge:nSe,LucideTableCellsSplit:rSe,LucideTableColumnsSplit:aSe,LucideTableOfContents:iSe,LucideTableProperties:oSe,LucideTableRowsSplit:lSe,LucideTablet:o$,LucideTabletSmartphone:cSe,LucideTablets:dSe,LucideTag:Ep,LucideTags:lJ,LucideTally1:uSe,LucideTally2:hSe,LucideTally3:mSe,LucideTally4:pSe,LucideTally5:fSe,LucideTangent:xSe,LucideTarget:ku,LucideTelescope:gSe,LucideTent:vSe,LucideTentTree:ySe,LucideTerminal:bSe,LucideTerminalSquare:vR,LucideTestTube:_Se,LucideTestTube2:jR,LucideTestTubeDiagonal:jR,LucideTestTubes:wSe,LucideText:SSe,LucideTextCursor:jSe,LucideTextCursorInput:l$,LucideTextQuote:NSe,LucideTextSearch:kSe,LucideTextSelect:NR,LucideTextSelection:NR,LucideTheater:CSe,LucideThermometer:TSe,LucideThermometerSnowflake:ASe,LucideThermometerSun:ESe,LucideThumbsDown:cJ,LucideThumbsUp:Fg,LucideTicket:d7,LucideTicketCheck:MSe,LucideTicketMinus:PSe,LucideTicketPercent:LSe,LucideTicketPlus:ISe,LucideTicketSlash:DSe,LucideTicketX:RSe,LucideTickets:OSe,LucideTicketsPlane:FSe,LucideTimer:USe,LucideTimerOff:zSe,LucideTimerReset:BSe,LucideToggleLeft:qSe,LucideToggleRight:$Se,LucideToilet:VSe,LucideTornado:HSe,LucideTorus:GSe,LucideTouchpad:KSe,LucideTouchpadOff:WSe,LucideTowerControl:YSe,LucideToyBrick:ZSe,LucideTractor:XSe,LucideTrafficCone:QSe,LucideTrain:kR,LucideTrainFront:e5e,LucideTrainFrontTunnel:JSe,LucideTrainTrack:t5e,LucideTramFront:kR,LucideTrash:s5e,LucideTrash2:Sn,LucideTreeDeciduous:n5e,LucideTreePalm:SR,LucideTreePine:rP,LucideTrees:r5e,LucideTrello:a5e,LucideTrendingDown:gS,LucideTrendingUp:Nl,LucideTrendingUpDown:i5e,LucideTriangle:l5e,LucideTriangleAlert:xl,LucideTriangleRight:o5e,LucideTrophy:wl,LucideTruck:dJ,LucideTurtle:c5e,LucideTv:u5e,LucideTv2:CR,LucideTvMinimal:CR,LucideTvMinimalPlay:d5e,LucideTwitch:h5e,LucideTwitter:uJ,LucideType:c$,LucideTypeOutline:m5e,LucideUmbrella:f5e,LucideUmbrellaOff:p5e,LucideUnderline:u7,LucideUndo:JA,LucideUndo2:hJ,LucideUndoDot:x5e,LucideUnfoldHorizontal:g5e,LucideUnfoldVertical:y5e,LucideUngroup:v5e,LucideUniversity:AR,LucideUnlink:h7,LucideUnlink2:b5e,LucideUnlock:rD,LucideUnlockKeyhole:nD,LucideUnplug:d$,LucideUpload:Oa,LucideUploadCloud:R8,LucideUsb:_5e,LucideUser:Fo,LucideUser2:LR,LucideUserCheck:gj,LucideUserCheck2:i6,LucideUserCircle:P8,LucideUserCircle2:M8,LucideUserCog:mJ,LucideUserCog2:ER,LucideUserMinus:u$,LucideUserMinus2:TR,LucideUserPen:w5e,LucideUserPlus:Pl,LucideUserPlus2:MR,LucideUserRound:LR,LucideUserRoundCheck:i6,LucideUserRoundCog:ER,LucideUserRoundMinus:TR,LucideUserRoundPen:j5e,LucideUserRoundPlus:MR,LucideUserRoundSearch:h$,LucideUserRoundX:PR,LucideUserSearch:N5e,LucideUserSquare:_R,LucideUserSquare2:bR,LucideUserX:m$,LucideUserX2:PR,LucideUsers:In,LucideUsers2:x0,LucideUsersRound:x0,LucideUtensils:DR,LucideUtensilsCrossed:IR,LucideUtilityPole:k5e,LucideVariable:p$,LucideVault:S5e,LucideVegan:C5e,LucideVenetianMask:A5e,LucideVerified:K3,LucideVibrate:T5e,LucideVibrateOff:E5e,LucideVideo:Kr,LucideVideoOff:M5e,LucideVideotape:P5e,LucideView:L5e,LucideVoicemail:I5e,LucideVolleyball:D5e,LucideVolume:O5e,LucideVolume1:R5e,LucideVolume2:pJ,LucideVolumeOff:F5e,LucideVolumeX:fJ,LucideVote:z5e,LucideWallet:m7,LucideWallet2:RR,LucideWalletCards:B5e,LucideWalletMinimal:RR,LucideWallpaper:U5e,LucideWand:q5e,LucideWand2:Qx,LucideWandSparkles:Qx,LucideWarehouse:$5e,LucideWashingMachine:V5e,LucideWatch:H5e,LucideWaves:G5e,LucideWaypoints:W5e,LucideWebcam:K5e,LucideWebhook:Z5e,LucideWebhookOff:Y5e,LucideWeight:X5e,LucideWheat:J5e,LucideWheatOff:Q5e,LucideWholeWord:e4e,LucideWifi:a4e,LucideWifiHigh:t4e,LucideWifiLow:s4e,LucideWifiOff:n4e,LucideWifiZero:r4e,LucideWind:o4e,LucideWindArrowDown:i4e,LucideWine:c4e,LucideWineOff:l4e,LucideWorkflow:p7,LucideWorm:d4e,LucideWrapText:u4e,LucideWrench:Y4,LucideX:Qn,LucideXCircle:Rd,LucideXOctagon:lD,LucideXSquare:wR,LucideYoutube:f$,LucideZap:nf,LucideZapOff:h4e,LucideZoomIn:aP,LucideZoomOut:x$,Luggage:d_e,LuggageIcon:d_e,MSquare:sR,MSquareIcon:sR,Magnet:u_e,MagnetIcon:u_e,Mail:ln,MailCheck:JO,MailCheckIcon:JO,MailIcon:ln,MailMinus:h_e,MailMinusIcon:h_e,MailOpen:Vq,MailOpenIcon:Vq,MailPlus:Hq,MailPlusIcon:Hq,MailQuestion:m_e,MailQuestionIcon:m_e,MailSearch:p_e,MailSearchIcon:p_e,MailWarning:f_e,MailWarningIcon:f_e,MailX:JM,MailXIcon:JM,Mailbox:x_e,MailboxIcon:x_e,Mails:g_e,MailsIcon:g_e,Map:e7,MapIcon:e7,MapPin:Xa,MapPinCheck:v_e,MapPinCheckIcon:v_e,MapPinCheckInside:y_e,MapPinCheckInsideIcon:y_e,MapPinHouse:b_e,MapPinHouseIcon:b_e,MapPinIcon:Xa,MapPinMinus:w_e,MapPinMinusIcon:w_e,MapPinMinusInside:__e,MapPinMinusInsideIcon:__e,MapPinOff:j_e,MapPinOffIcon:j_e,MapPinPlus:k_e,MapPinPlusIcon:k_e,MapPinPlusInside:N_e,MapPinPlusInsideIcon:N_e,MapPinX:C_e,MapPinXIcon:C_e,MapPinXInside:S_e,MapPinXInsideIcon:S_e,MapPinned:UQ,MapPinnedIcon:UQ,Martini:A_e,MartiniIcon:A_e,Maximize:t7,Maximize2:qQ,Maximize2Icon:qQ,MaximizeIcon:t7,Medal:HA,MedalIcon:HA,Megaphone:wh,MegaphoneIcon:wh,MegaphoneOff:E_e,MegaphoneOffIcon:E_e,Meh:T_e,MehIcon:T_e,MemoryStick:M_e,MemoryStickIcon:M_e,Menu:GA,MenuIcon:GA,MenuSquare:nR,MenuSquareIcon:nR,Merge:s7,MergeIcon:s7,MessageCircle:Ou,MessageCircleCode:P_e,MessageCircleCodeIcon:P_e,MessageCircleDashed:L_e,MessageCircleDashedIcon:L_e,MessageCircleHeart:Gq,MessageCircleHeartIcon:Gq,MessageCircleIcon:Ou,MessageCircleMore:I_e,MessageCircleMoreIcon:I_e,MessageCircleOff:D_e,MessageCircleOffIcon:D_e,MessageCirclePlus:R_e,MessageCirclePlusIcon:R_e,MessageCircleQuestion:$Q,MessageCircleQuestionIcon:$Q,MessageCircleReply:F_e,MessageCircleReplyIcon:F_e,MessageCircleWarning:O_e,MessageCircleWarningIcon:O_e,MessageCircleX:z_e,MessageCircleXIcon:z_e,MessageSquare:Hi,MessageSquareCode:B_e,MessageSquareCodeIcon:B_e,MessageSquareDashed:U_e,MessageSquareDashedIcon:U_e,MessageSquareDiff:q_e,MessageSquareDiffIcon:q_e,MessageSquareDot:$_e,MessageSquareDotIcon:$_e,MessageSquareHeart:V_e,MessageSquareHeartIcon:V_e,MessageSquareIcon:Hi,MessageSquareLock:H_e,MessageSquareLockIcon:H_e,MessageSquareMore:VQ,MessageSquareMoreIcon:VQ,MessageSquareOff:G_e,MessageSquareOffIcon:G_e,MessageSquarePlus:E4,MessageSquarePlusIcon:E4,MessageSquareQuote:WA,MessageSquareQuoteIcon:WA,MessageSquareReply:HQ,MessageSquareReplyIcon:HQ,MessageSquareShare:W_e,MessageSquareShareIcon:W_e,MessageSquareText:K_e,MessageSquareTextIcon:K_e,MessageSquareWarning:GQ,MessageSquareWarningIcon:GQ,MessageSquareX:Y_e,MessageSquareXIcon:Y_e,MessagesSquare:WQ,MessagesSquareIcon:WQ,Mic:n7,Mic2:aD,Mic2Icon:aD,MicIcon:n7,MicOff:Z_e,MicOffIcon:Z_e,MicVocal:aD,MicVocalIcon:aD,Microchip:X_e,MicrochipIcon:X_e,Microscope:Q_e,MicroscopeIcon:Q_e,Microwave:J_e,MicrowaveIcon:J_e,Milestone:ewe,MilestoneIcon:ewe,Milk:swe,MilkIcon:swe,MilkOff:twe,MilkOffIcon:twe,Minimize:rwe,Minimize2:nwe,Minimize2Icon:nwe,MinimizeIcon:rwe,Minus:uN,MinusCircle:w8,MinusCircleIcon:w8,MinusIcon:uN,MinusSquare:rR,MinusSquareIcon:rR,Monitor:hN,MonitorCheck:awe,MonitorCheckIcon:awe,MonitorCog:iwe,MonitorCogIcon:iwe,MonitorDot:owe,MonitorDotIcon:owe,MonitorDown:lwe,MonitorDownIcon:lwe,MonitorIcon:hN,MonitorOff:cwe,MonitorOffIcon:cwe,MonitorPause:dwe,MonitorPauseIcon:dwe,MonitorPlay:Wq,MonitorPlayIcon:Wq,MonitorSmartphone:uwe,MonitorSmartphoneIcon:uwe,MonitorSpeaker:hwe,MonitorSpeakerIcon:hwe,MonitorStop:mwe,MonitorStopIcon:mwe,MonitorUp:r7,MonitorUpIcon:r7,MonitorX:pwe,MonitorXIcon:pwe,Moon:xwe,MoonIcon:xwe,MoonStar:fwe,MoonStarIcon:fwe,MoreHorizontal:ob,MoreHorizontalIcon:ob,MoreVertical:Xx,MoreVerticalIcon:Xx,Mountain:ywe,MountainIcon:ywe,MountainSnow:gwe,MountainSnowIcon:gwe,Mouse:_we,MouseIcon:_we,MouseOff:vwe,MouseOffIcon:vwe,MousePointer:v0,MousePointer2:KQ,MousePointer2Icon:KQ,MousePointerBan:bwe,MousePointerBanIcon:bwe,MousePointerClick:$h,MousePointerClickIcon:$h,MousePointerIcon:v0,MousePointerSquareDashed:KD,MousePointerSquareDashedIcon:KD,Move:YQ,Move3D:iD,Move3DIcon:iD,Move3d:iD,Move3dIcon:iD,MoveDiagonal:jwe,MoveDiagonal2:wwe,MoveDiagonal2Icon:wwe,MoveDiagonalIcon:jwe,MoveDown:Swe,MoveDownIcon:Swe,MoveDownLeft:Nwe,MoveDownLeftIcon:Nwe,MoveDownRight:kwe,MoveDownRightIcon:kwe,MoveHorizontal:Cwe,MoveHorizontalIcon:Cwe,MoveIcon:YQ,MoveLeft:Awe,MoveLeftIcon:Awe,MoveRight:Ewe,MoveRightIcon:Ewe,MoveUp:Pwe,MoveUpIcon:Pwe,MoveUpLeft:Twe,MoveUpLeftIcon:Twe,MoveUpRight:Mwe,MoveUpRightIcon:Mwe,MoveVertical:Lwe,MoveVerticalIcon:Lwe,Music:Kq,Music2:Iwe,Music2Icon:Iwe,Music3:Dwe,Music3Icon:Dwe,Music4:Rwe,Music4Icon:Rwe,MusicIcon:Kq,Navigation:ZQ,Navigation2:Owe,Navigation2Icon:Owe,Navigation2Off:Fwe,Navigation2OffIcon:Fwe,NavigationIcon:ZQ,NavigationOff:zwe,NavigationOffIcon:zwe,Network:Bwe,NetworkIcon:Bwe,Newspaper:mN,NewspaperIcon:mN,Nfc:Uwe,NfcIcon:Uwe,Notebook:Hwe,NotebookIcon:Hwe,NotebookPen:qwe,NotebookPenIcon:qwe,NotebookTabs:$we,NotebookTabsIcon:$we,NotebookText:Vwe,NotebookTextIcon:Vwe,NotepadText:Wwe,NotepadTextDashed:Gwe,NotepadTextDashedIcon:Gwe,NotepadTextIcon:Wwe,Nut:Ywe,NutIcon:Ywe,NutOff:Kwe,NutOffIcon:Kwe,Octagon:Xwe,OctagonAlert:Qk,OctagonAlertIcon:Qk,OctagonIcon:Xwe,OctagonMinus:Zwe,OctagonMinusIcon:Zwe,OctagonPause:oD,OctagonPauseIcon:oD,OctagonX:lD,OctagonXIcon:lD,Omega:Qwe,OmegaIcon:Qwe,Option:Jwe,OptionIcon:Jwe,Orbit:eje,OrbitIcon:eje,Origami:tje,OrigamiIcon:tje,Outdent:eD,OutdentIcon:eD,Package:Nh,Package2:sje,Package2Icon:sje,PackageCheck:nje,PackageCheckIcon:nje,PackageIcon:Nh,PackageMinus:rje,PackageMinusIcon:rje,PackageOpen:aje,PackageOpenIcon:aje,PackagePlus:ije,PackagePlusIcon:ije,PackageSearch:oje,PackageSearchIcon:oje,PackageX:lje,PackageXIcon:lje,PaintBucket:cje,PaintBucketIcon:cje,PaintRoller:dje,PaintRollerIcon:dje,Paintbrush:uje,Paintbrush2:cD,Paintbrush2Icon:cD,PaintbrushIcon:uje,PaintbrushVertical:cD,PaintbrushVerticalIcon:cD,Palette:Xc,PaletteIcon:Xc,Palmtree:SR,PalmtreeIcon:SR,PanelBottom:pje,PanelBottomClose:hje,PanelBottomCloseIcon:hje,PanelBottomDashed:dD,PanelBottomDashedIcon:dD,PanelBottomIcon:pje,PanelBottomInactive:dD,PanelBottomInactiveIcon:dD,PanelBottomOpen:mje,PanelBottomOpenIcon:mje,PanelLeft:pD,PanelLeftClose:uD,PanelLeftCloseIcon:uD,PanelLeftDashed:hD,PanelLeftDashedIcon:hD,PanelLeftIcon:pD,PanelLeftInactive:hD,PanelLeftInactiveIcon:hD,PanelLeftOpen:mD,PanelLeftOpenIcon:mD,PanelRight:gje,PanelRightClose:fje,PanelRightCloseIcon:fje,PanelRightDashed:fD,PanelRightDashedIcon:fD,PanelRightIcon:gje,PanelRightInactive:fD,PanelRightInactiveIcon:fD,PanelRightOpen:xje,PanelRightOpenIcon:xje,PanelTop:bje,PanelTopClose:yje,PanelTopCloseIcon:yje,PanelTopDashed:xD,PanelTopDashedIcon:xD,PanelTopIcon:bje,PanelTopInactive:xD,PanelTopInactiveIcon:xD,PanelTopOpen:vje,PanelTopOpenIcon:vje,PanelsLeftBottom:_je,PanelsLeftBottomIcon:_je,PanelsLeftRight:a6,PanelsLeftRightIcon:a6,PanelsRightBottom:wje,PanelsRightBottomIcon:wje,PanelsTopBottom:_D,PanelsTopBottomIcon:_D,PanelsTopLeft:Z3,PanelsTopLeftIcon:Z3,Paperclip:eP,PaperclipIcon:eP,Parentheses:jje,ParenthesesIcon:jje,ParkingCircle:N8,ParkingCircleIcon:N8,ParkingCircleOff:j8,ParkingCircleOffIcon:j8,ParkingMeter:Nje,ParkingMeterIcon:Nje,ParkingSquare:oR,ParkingSquareIcon:oR,ParkingSquareOff:iR,ParkingSquareOffIcon:iR,PartyPopper:Ex,PartyPopperIcon:Ex,Pause:ky,PauseCircle:k8,PauseCircleIcon:k8,PauseIcon:ky,PauseOctagon:oD,PauseOctagonIcon:oD,PawPrint:kje,PawPrintIcon:kje,PcCase:Sje,PcCaseIcon:Sje,Pen:V2,PenBox:wp,PenBoxIcon:wp,PenIcon:V2,PenLine:Qm,PenLineIcon:Qm,PenOff:Cje,PenOffIcon:Cje,PenSquare:wp,PenSquareIcon:wp,PenTool:KA,PenToolIcon:KA,Pencil:Ya,PencilIcon:Ya,PencilLine:Yq,PencilLineIcon:Yq,PencilOff:Aje,PencilOffIcon:Aje,PencilRuler:Eje,PencilRulerIcon:Eje,Pentagon:Tje,PentagonIcon:Tje,Percent:F_,PercentCircle:S8,PercentCircleIcon:S8,PercentDiamond:z8,PercentDiamondIcon:z8,PercentIcon:F_,PercentSquare:lR,PercentSquareIcon:lR,PersonStanding:Mje,PersonStandingIcon:Mje,PhilippinePeso:Pje,PhilippinePesoIcon:Pje,Phone:_a,PhoneCall:XQ,PhoneCallIcon:XQ,PhoneForwarded:Lje,PhoneForwardedIcon:Lje,PhoneIcon:_a,PhoneIncoming:Ije,PhoneIncomingIcon:Ije,PhoneMissed:Dje,PhoneMissedIcon:Dje,PhoneOff:Rje,PhoneOffIcon:Rje,PhoneOutgoing:Fje,PhoneOutgoingIcon:Fje,Pi:Oje,PiIcon:Oje,PiSquare:cR,PiSquareIcon:cR,Piano:zje,PianoIcon:zje,Pickaxe:Bje,PickaxeIcon:Bje,PictureInPicture:qje,PictureInPicture2:Uje,PictureInPicture2Icon:Uje,PictureInPictureIcon:qje,PieChart:i8,PieChartIcon:i8,PiggyBank:QQ,PiggyBankIcon:QQ,Pilcrow:Hje,PilcrowIcon:Hje,PilcrowLeft:$je,PilcrowLeftIcon:$je,PilcrowRight:Vje,PilcrowRightIcon:Vje,PilcrowSquare:dR,PilcrowSquareIcon:dR,Pill:Wje,PillBottle:Gje,PillBottleIcon:Gje,PillIcon:Wje,Pin:YA,PinIcon:YA,PinOff:JQ,PinOffIcon:JQ,Pipette:Kje,PipetteIcon:Kje,Pizza:Yje,PizzaIcon:Yje,Plane:eJ,PlaneIcon:eJ,PlaneLanding:Zje,PlaneLandingIcon:Zje,PlaneTakeoff:Xje,PlaneTakeoffIcon:Xje,Play:Jd,PlayCircle:om,PlayCircleIcon:om,PlayIcon:Jd,PlaySquare:uR,PlaySquareIcon:uR,Plug:pN,Plug2:Qje,Plug2Icon:Qje,PlugIcon:pN,PlugZap:gD,PlugZap2:gD,PlugZap2Icon:gD,PlugZapIcon:gD,Plus:rn,PlusCircle:C8,PlusCircleIcon:C8,PlusIcon:rn,PlusSquare:hR,PlusSquareIcon:hR,Pocket:e2e,PocketIcon:e2e,PocketKnife:Jje,PocketKnifeIcon:Jje,Podcast:t2e,PodcastIcon:t2e,Pointer:n2e,PointerIcon:n2e,PointerOff:s2e,PointerOffIcon:s2e,Popcorn:r2e,PopcornIcon:r2e,Popsicle:a2e,PopsicleIcon:a2e,PoundSterling:i2e,PoundSterlingIcon:i2e,Power:tJ,PowerCircle:A8,PowerCircleIcon:A8,PowerIcon:tJ,PowerOff:o2e,PowerOffIcon:o2e,PowerSquare:mR,PowerSquareIcon:mR,Presentation:jv,PresentationIcon:jv,Printer:ZA,PrinterCheck:l2e,PrinterCheckIcon:l2e,PrinterIcon:ZA,Projector:c2e,ProjectorIcon:c2e,Proportions:d2e,ProportionsIcon:d2e,Puzzle:u2e,PuzzleIcon:u2e,Pyramid:h2e,PyramidIcon:h2e,QrCode:Hf,QrCodeIcon:Hf,Quote:pS,QuoteIcon:pS,Rabbit:m2e,RabbitIcon:m2e,Radar:Zq,RadarIcon:Zq,Radiation:p2e,RadiationIcon:p2e,Radical:f2e,RadicalIcon:f2e,Radio:Nv,RadioIcon:Nv,RadioReceiver:x2e,RadioReceiverIcon:x2e,RadioTower:g2e,RadioTowerIcon:g2e,Radius:y2e,RadiusIcon:y2e,RailSymbol:v2e,RailSymbolIcon:v2e,Rainbow:b2e,RainbowIcon:b2e,Rat:_2e,RatIcon:_2e,Ratio:w2e,RatioIcon:w2e,Receipt:sJ,ReceiptCent:j2e,ReceiptCentIcon:j2e,ReceiptEuro:N2e,ReceiptEuroIcon:N2e,ReceiptIcon:sJ,ReceiptIndianRupee:k2e,ReceiptIndianRupeeIcon:k2e,ReceiptJapaneseYen:S2e,ReceiptJapaneseYenIcon:S2e,ReceiptPoundSterling:C2e,ReceiptPoundSterlingIcon:C2e,ReceiptRussianRuble:A2e,ReceiptRussianRubleIcon:A2e,ReceiptSwissFranc:E2e,ReceiptSwissFrancIcon:E2e,ReceiptText:T2e,ReceiptTextIcon:T2e,RectangleEllipsis:yD,RectangleEllipsisIcon:yD,RectangleHorizontal:M2e,RectangleHorizontalIcon:M2e,RectangleVertical:P2e,RectangleVerticalIcon:P2e,Recycle:L2e,RecycleIcon:L2e,Redo:XA,Redo2:I2e,Redo2Icon:I2e,RedoDot:D2e,RedoDotIcon:D2e,RedoIcon:XA,RefreshCcw:Xq,RefreshCcwDot:R2e,RefreshCcwDotIcon:R2e,RefreshCcwIcon:Xq,RefreshCw:uo,RefreshCwIcon:uo,RefreshCwOff:F2e,RefreshCwOffIcon:F2e,Refrigerator:O2e,RefrigeratorIcon:O2e,Regex:z2e,RegexIcon:z2e,RemoveFormatting:B2e,RemoveFormattingIcon:B2e,Repeat:QA,Repeat1:U2e,Repeat1Icon:U2e,Repeat2:nJ,Repeat2Icon:nJ,RepeatIcon:QA,Replace:$2e,ReplaceAll:q2e,ReplaceAllIcon:q2e,ReplaceIcon:$2e,Reply:Qq,ReplyAll:V2e,ReplyAllIcon:V2e,ReplyIcon:Qq,Rewind:H2e,RewindIcon:H2e,Ribbon:G2e,RibbonIcon:G2e,Rocket:Sy,RocketIcon:Sy,RockingChair:W2e,RockingChairIcon:W2e,RollerCoaster:K2e,RollerCoasterIcon:K2e,Rotate3D:vD,Rotate3DIcon:vD,Rotate3d:vD,Rotate3dIcon:vD,RotateCcw:Tx,RotateCcwIcon:Tx,RotateCcwSquare:Y2e,RotateCcwSquareIcon:Y2e,RotateCw:a7,RotateCwIcon:a7,RotateCwSquare:Z2e,RotateCwSquareIcon:Z2e,Route:Jq,RouteIcon:Jq,RouteOff:X2e,RouteOffIcon:X2e,Router:Q2e,RouterIcon:Q2e,Rows:bD,Rows2:bD,Rows2Icon:bD,Rows3:_D,Rows3Icon:_D,Rows4:J2e,Rows4Icon:J2e,RowsIcon:bD,Rss:eNe,RssIcon:eNe,Ruler:W4,RulerIcon:W4,RussianRuble:tNe,RussianRubleIcon:tNe,Sailboat:sNe,SailboatIcon:sNe,Salad:nNe,SaladIcon:nNe,Sandwich:rNe,SandwichIcon:rNe,Satellite:iNe,SatelliteDish:aNe,SatelliteDishIcon:aNe,SatelliteIcon:iNe,Save:Ho,SaveAll:oNe,SaveAllIcon:oNe,SaveIcon:Ho,SaveOff:lNe,SaveOffIcon:lNe,Scale:cNe,Scale3D:wD,Scale3DIcon:wD,Scale3d:wD,Scale3dIcon:wD,ScaleIcon:cNe,Scaling:dNe,ScalingIcon:dNe,Scan:yNe,ScanBarcode:uNe,ScanBarcodeIcon:uNe,ScanEye:hNe,ScanEyeIcon:hNe,ScanFace:mNe,ScanFaceIcon:mNe,ScanIcon:yNe,ScanLine:pNe,ScanLineIcon:pNe,ScanQrCode:fNe,ScanQrCodeIcon:fNe,ScanSearch:xNe,ScanSearchIcon:xNe,ScanText:gNe,ScanTextIcon:gNe,ScatterChart:o8,ScatterChartIcon:o8,School:vNe,School2:AR,School2Icon:AR,SchoolIcon:vNe,Scissors:_Ne,ScissorsIcon:_Ne,ScissorsLineDashed:bNe,ScissorsLineDashedIcon:bNe,ScissorsSquare:pR,ScissorsSquareDashedBottom:BD,ScissorsSquareDashedBottomIcon:BD,ScissorsSquareIcon:pR,ScreenShare:jNe,ScreenShareIcon:jNe,ScreenShareOff:wNe,ScreenShareOffIcon:wNe,Scroll:NNe,ScrollIcon:NNe,ScrollText:e$,ScrollTextIcon:e$,Search:Lr,SearchCheck:kNe,SearchCheckIcon:kNe,SearchCode:SNe,SearchCodeIcon:SNe,SearchIcon:Lr,SearchSlash:CNe,SearchSlashIcon:CNe,SearchX:t$,SearchXIcon:t$,Section:ANe,SectionIcon:ANe,Send:Or,SendHorizonal:jD,SendHorizonalIcon:jD,SendHorizontal:jD,SendHorizontalIcon:jD,SendIcon:Or,SendToBack:ENe,SendToBackIcon:ENe,SeparatorHorizontal:TNe,SeparatorHorizontalIcon:TNe,SeparatorVertical:MNe,SeparatorVerticalIcon:MNe,Server:DNe,ServerCog:PNe,ServerCogIcon:PNe,ServerCrash:LNe,ServerCrashIcon:LNe,ServerIcon:DNe,ServerOff:INe,ServerOffIcon:INe,Settings:qc,Settings2:fS,Settings2Icon:fS,SettingsIcon:qc,Shapes:RNe,ShapesIcon:RNe,Share:rJ,Share2:bd,Share2Icon:bd,ShareIcon:rJ,Sheet:FNe,SheetIcon:FNe,Shell:ONe,ShellIcon:ONe,Shield:Rm,ShieldAlert:s$,ShieldAlertIcon:s$,ShieldBan:zNe,ShieldBanIcon:zNe,ShieldCheck:Dm,ShieldCheckIcon:Dm,ShieldClose:ND,ShieldCloseIcon:ND,ShieldEllipsis:BNe,ShieldEllipsisIcon:BNe,ShieldHalf:UNe,ShieldHalfIcon:UNe,ShieldIcon:Rm,ShieldMinus:qNe,ShieldMinusIcon:qNe,ShieldOff:i7,ShieldOffIcon:i7,ShieldPlus:$Ne,ShieldPlusIcon:$Ne,ShieldQuestion:o7,ShieldQuestionIcon:o7,ShieldX:ND,ShieldXIcon:ND,Ship:HNe,ShipIcon:HNe,ShipWheel:VNe,ShipWheelIcon:VNe,Shirt:GNe,ShirtIcon:GNe,ShoppingBag:K4,ShoppingBagIcon:K4,ShoppingBasket:WNe,ShoppingBasketIcon:WNe,ShoppingCart:xS,ShoppingCartIcon:xS,Shovel:KNe,ShovelIcon:KNe,ShowerHead:YNe,ShowerHeadIcon:YNe,Shrink:ZNe,ShrinkIcon:ZNe,Shrub:XNe,ShrubIcon:XNe,Shuffle:l7,ShuffleIcon:l7,Sidebar:pD,SidebarClose:uD,SidebarCloseIcon:uD,SidebarIcon:pD,SidebarOpen:mD,SidebarOpenIcon:mD,Sigma:QNe,SigmaIcon:QNe,SigmaSquare:fR,SigmaSquareIcon:fR,Signal:nke,SignalHigh:JNe,SignalHighIcon:JNe,SignalIcon:nke,SignalLow:eke,SignalLowIcon:eke,SignalMedium:tke,SignalMediumIcon:tke,SignalZero:ske,SignalZeroIcon:ske,Signature:rke,SignatureIcon:rke,Signpost:aJ,SignpostBig:ake,SignpostBigIcon:ake,SignpostIcon:aJ,Siren:ike,SirenIcon:ike,SkipBack:oke,SkipBackIcon:oke,SkipForward:iJ,SkipForwardIcon:iJ,Skull:lke,SkullIcon:lke,Slack:cke,SlackIcon:cke,Slash:dke,SlashIcon:dke,SlashSquare:xR,SlashSquareIcon:xR,Slice:uke,SliceIcon:uke,Sliders:kD,SlidersHorizontal:tP,SlidersHorizontalIcon:tP,SlidersIcon:kD,SlidersVertical:kD,SlidersVerticalIcon:kD,Smartphone:p1,SmartphoneCharging:hke,SmartphoneChargingIcon:hke,SmartphoneIcon:p1,SmartphoneNfc:mke,SmartphoneNfcIcon:mke,Smile:fke,SmileIcon:fke,SmilePlus:pke,SmilePlusIcon:pke,Snail:xke,SnailIcon:xke,Snowflake:sj,SnowflakeIcon:sj,Sofa:n$,SofaIcon:n$,SortAsc:$I,SortAscIcon:$I,SortDesc:BI,SortDescIcon:BI,Soup:gke,SoupIcon:gke,Space:yke,SpaceIcon:yke,Spade:vke,SpadeIcon:vke,Sparkle:sP,SparkleIcon:sP,Sparkles:un,SparklesIcon:un,Speaker:bke,SpeakerIcon:bke,Speech:_ke,SpeechIcon:_ke,SpellCheck:jke,SpellCheck2:wke,SpellCheck2Icon:wke,SpellCheckIcon:jke,Spline:Nke,SplineIcon:Nke,Split:kke,SplitIcon:kke,SplitSquareHorizontal:gR,SplitSquareHorizontalIcon:gR,SplitSquareVertical:yR,SplitSquareVerticalIcon:yR,SprayCan:Ske,SprayCanIcon:Ske,Sprout:nP,SproutIcon:nP,Square:wb,SquareActivity:SD,SquareActivityIcon:SD,SquareArrowDown:ED,SquareArrowDownIcon:ED,SquareArrowDownLeft:CD,SquareArrowDownLeftIcon:CD,SquareArrowDownRight:AD,SquareArrowDownRightIcon:AD,SquareArrowLeft:TD,SquareArrowLeftIcon:TD,SquareArrowOutDownLeft:MD,SquareArrowOutDownLeftIcon:MD,SquareArrowOutDownRight:PD,SquareArrowOutDownRightIcon:PD,SquareArrowOutUpLeft:LD,SquareArrowOutUpLeftIcon:LD,SquareArrowOutUpRight:ID,SquareArrowOutUpRightIcon:ID,SquareArrowRight:DD,SquareArrowRightIcon:DD,SquareArrowUp:OD,SquareArrowUpIcon:OD,SquareArrowUpLeft:RD,SquareArrowUpLeftIcon:RD,SquareArrowUpRight:FD,SquareArrowUpRightIcon:FD,SquareAsterisk:zD,SquareAsteriskIcon:zD,SquareBottomDashedScissors:BD,SquareBottomDashedScissorsIcon:BD,SquareChartGantt:I5,SquareChartGanttIcon:I5,SquareCheck:UD,SquareCheckBig:Ww,SquareCheckBigIcon:Ww,SquareCheckIcon:UD,SquareChevronDown:qD,SquareChevronDownIcon:qD,SquareChevronLeft:$D,SquareChevronLeftIcon:$D,SquareChevronRight:VD,SquareChevronRightIcon:VD,SquareChevronUp:HD,SquareChevronUpIcon:HD,SquareCode:GD,SquareCodeIcon:GD,SquareDashed:YD,SquareDashedBottom:Ake,SquareDashedBottomCode:Cke,SquareDashedBottomCodeIcon:Cke,SquareDashedBottomIcon:Ake,SquareDashedIcon:YD,SquareDashedKanban:WD,SquareDashedKanbanIcon:WD,SquareDashedMousePointer:KD,SquareDashedMousePointerIcon:KD,SquareDivide:ZD,SquareDivideIcon:ZD,SquareDot:XD,SquareDotIcon:XD,SquareEqual:QD,SquareEqualIcon:QD,SquareFunction:JD,SquareFunctionIcon:JD,SquareGanttChart:I5,SquareGanttChartIcon:I5,SquareIcon:wb,SquareKanban:eR,SquareKanbanIcon:eR,SquareLibrary:tR,SquareLibraryIcon:tR,SquareM:sR,SquareMIcon:sR,SquareMenu:nR,SquareMenuIcon:nR,SquareMinus:rR,SquareMinusIcon:rR,SquareMousePointer:aR,SquareMousePointerIcon:aR,SquareParking:oR,SquareParkingIcon:oR,SquareParkingOff:iR,SquareParkingOffIcon:iR,SquarePen:wp,SquarePenIcon:wp,SquarePercent:lR,SquarePercentIcon:lR,SquarePi:cR,SquarePiIcon:cR,SquarePilcrow:dR,SquarePilcrowIcon:dR,SquarePlay:uR,SquarePlayIcon:uR,SquarePlus:hR,SquarePlusIcon:hR,SquarePower:mR,SquarePowerIcon:mR,SquareRadical:Eke,SquareRadicalIcon:Eke,SquareScissors:pR,SquareScissorsIcon:pR,SquareSigma:fR,SquareSigmaIcon:fR,SquareSlash:xR,SquareSlashIcon:xR,SquareSplitHorizontal:gR,SquareSplitHorizontalIcon:gR,SquareSplitVertical:yR,SquareSplitVerticalIcon:yR,SquareSquare:Tke,SquareSquareIcon:Tke,SquareStack:Mke,SquareStackIcon:Mke,SquareTerminal:vR,SquareTerminalIcon:vR,SquareUser:_R,SquareUserIcon:_R,SquareUserRound:bR,SquareUserRoundIcon:bR,SquareX:wR,SquareXIcon:wR,Squircle:Pke,SquircleIcon:Pke,Squirrel:Lke,SquirrelIcon:Lke,Stamp:Ike,StampIcon:Ike,Star:Da,StarHalf:Dke,StarHalfIcon:Dke,StarIcon:Da,StarOff:Rke,StarOffIcon:Rke,Stars:un,StarsIcon:un,StepBack:Fke,StepBackIcon:Fke,StepForward:Oke,StepForwardIcon:Oke,Stethoscope:zke,StethoscopeIcon:zke,Sticker:Bke,StickerIcon:Bke,StickyNote:c7,StickyNoteIcon:c7,StopCircle:T8,StopCircleIcon:T8,Store:r$,StoreIcon:r$,StretchHorizontal:Uke,StretchHorizontalIcon:Uke,StretchVertical:qke,StretchVerticalIcon:qke,Strikethrough:oJ,StrikethroughIcon:oJ,Subscript:$ke,SubscriptIcon:$ke,Subtitles:YI,SubtitlesIcon:YI,Sun:fN,SunDim:Vke,SunDimIcon:Vke,SunIcon:fN,SunMedium:Hke,SunMediumIcon:Hke,SunMoon:Gke,SunMoonIcon:Gke,SunSnow:Wke,SunSnowIcon:Wke,Sunrise:Kke,SunriseIcon:Kke,Sunset:Yke,SunsetIcon:Yke,Superscript:Zke,SuperscriptIcon:Zke,SwatchBook:Xke,SwatchBookIcon:Xke,SwissFranc:Qke,SwissFrancIcon:Qke,SwitchCamera:Jke,SwitchCameraIcon:Jke,Sword:eSe,SwordIcon:eSe,Swords:tSe,SwordsIcon:tSe,Syringe:sSe,SyringeIcon:sSe,Table:i$,Table2:a$,Table2Icon:a$,TableCellsMerge:nSe,TableCellsMergeIcon:nSe,TableCellsSplit:rSe,TableCellsSplitIcon:rSe,TableColumnsSplit:aSe,TableColumnsSplitIcon:aSe,TableIcon:i$,TableOfContents:iSe,TableOfContentsIcon:iSe,TableProperties:oSe,TablePropertiesIcon:oSe,TableRowsSplit:lSe,TableRowsSplitIcon:lSe,Tablet:o$,TabletIcon:o$,TabletSmartphone:cSe,TabletSmartphoneIcon:cSe,Tablets:dSe,TabletsIcon:dSe,Tag:Ep,TagIcon:Ep,Tags:lJ,TagsIcon:lJ,Tally1:uSe,Tally1Icon:uSe,Tally2:hSe,Tally2Icon:hSe,Tally3:mSe,Tally3Icon:mSe,Tally4:pSe,Tally4Icon:pSe,Tally5:fSe,Tally5Icon:fSe,Tangent:xSe,TangentIcon:xSe,Target:ku,TargetIcon:ku,Telescope:gSe,TelescopeIcon:gSe,Tent:vSe,TentIcon:vSe,TentTree:ySe,TentTreeIcon:ySe,Terminal:bSe,TerminalIcon:bSe,TerminalSquare:vR,TerminalSquareIcon:vR,TestTube:_Se,TestTube2:jR,TestTube2Icon:jR,TestTubeDiagonal:jR,TestTubeDiagonalIcon:jR,TestTubeIcon:_Se,TestTubes:wSe,TestTubesIcon:wSe,Text:SSe,TextCursor:jSe,TextCursorIcon:jSe,TextCursorInput:l$,TextCursorInputIcon:l$,TextIcon:SSe,TextQuote:NSe,TextQuoteIcon:NSe,TextSearch:kSe,TextSearchIcon:kSe,TextSelect:NR,TextSelectIcon:NR,TextSelection:NR,TextSelectionIcon:NR,Theater:CSe,TheaterIcon:CSe,Thermometer:TSe,ThermometerIcon:TSe,ThermometerSnowflake:ASe,ThermometerSnowflakeIcon:ASe,ThermometerSun:ESe,ThermometerSunIcon:ESe,ThumbsDown:cJ,ThumbsDownIcon:cJ,ThumbsUp:Fg,ThumbsUpIcon:Fg,Ticket:d7,TicketCheck:MSe,TicketCheckIcon:MSe,TicketIcon:d7,TicketMinus:PSe,TicketMinusIcon:PSe,TicketPercent:LSe,TicketPercentIcon:LSe,TicketPlus:ISe,TicketPlusIcon:ISe,TicketSlash:DSe,TicketSlashIcon:DSe,TicketX:RSe,TicketXIcon:RSe,Tickets:OSe,TicketsIcon:OSe,TicketsPlane:FSe,TicketsPlaneIcon:FSe,Timer:USe,TimerIcon:USe,TimerOff:zSe,TimerOffIcon:zSe,TimerReset:BSe,TimerResetIcon:BSe,ToggleLeft:qSe,ToggleLeftIcon:qSe,ToggleRight:$Se,ToggleRightIcon:$Se,Toilet:VSe,ToiletIcon:VSe,Tornado:HSe,TornadoIcon:HSe,Torus:GSe,TorusIcon:GSe,Touchpad:KSe,TouchpadIcon:KSe,TouchpadOff:WSe,TouchpadOffIcon:WSe,TowerControl:YSe,TowerControlIcon:YSe,ToyBrick:ZSe,ToyBrickIcon:ZSe,Tractor:XSe,TractorIcon:XSe,TrafficCone:QSe,TrafficConeIcon:QSe,Train:kR,TrainFront:e5e,TrainFrontIcon:e5e,TrainFrontTunnel:JSe,TrainFrontTunnelIcon:JSe,TrainIcon:kR,TrainTrack:t5e,TrainTrackIcon:t5e,TramFront:kR,TramFrontIcon:kR,Trash:s5e,Trash2:Sn,Trash2Icon:Sn,TrashIcon:s5e,TreeDeciduous:n5e,TreeDeciduousIcon:n5e,TreePalm:SR,TreePalmIcon:SR,TreePine:rP,TreePineIcon:rP,Trees:r5e,TreesIcon:r5e,Trello:a5e,TrelloIcon:a5e,TrendingDown:gS,TrendingDownIcon:gS,TrendingUp:Nl,TrendingUpDown:i5e,TrendingUpDownIcon:i5e,TrendingUpIcon:Nl,Triangle:l5e,TriangleAlert:xl,TriangleAlertIcon:xl,TriangleIcon:l5e,TriangleRight:o5e,TriangleRightIcon:o5e,Trophy:wl,TrophyIcon:wl,Truck:dJ,TruckIcon:dJ,Turtle:c5e,TurtleIcon:c5e,Tv:u5e,Tv2:CR,Tv2Icon:CR,TvIcon:u5e,TvMinimal:CR,TvMinimalIcon:CR,TvMinimalPlay:d5e,TvMinimalPlayIcon:d5e,Twitch:h5e,TwitchIcon:h5e,Twitter:uJ,TwitterIcon:uJ,Type:c$,TypeIcon:c$,TypeOutline:m5e,TypeOutlineIcon:m5e,Umbrella:f5e,UmbrellaIcon:f5e,UmbrellaOff:p5e,UmbrellaOffIcon:p5e,Underline:u7,UnderlineIcon:u7,Undo:JA,Undo2:hJ,Undo2Icon:hJ,UndoDot:x5e,UndoDotIcon:x5e,UndoIcon:JA,UnfoldHorizontal:g5e,UnfoldHorizontalIcon:g5e,UnfoldVertical:y5e,UnfoldVerticalIcon:y5e,Ungroup:v5e,UngroupIcon:v5e,University:AR,UniversityIcon:AR,Unlink:h7,Unlink2:b5e,Unlink2Icon:b5e,UnlinkIcon:h7,Unlock:rD,UnlockIcon:rD,UnlockKeyhole:nD,UnlockKeyholeIcon:nD,Unplug:d$,UnplugIcon:d$,Upload:Oa,UploadCloud:R8,UploadCloudIcon:R8,UploadIcon:Oa,Usb:_5e,UsbIcon:_5e,User:Fo,User2:LR,User2Icon:LR,UserCheck:gj,UserCheck2:i6,UserCheck2Icon:i6,UserCheckIcon:gj,UserCircle:P8,UserCircle2:M8,UserCircle2Icon:M8,UserCircleIcon:P8,UserCog:mJ,UserCog2:ER,UserCog2Icon:ER,UserCogIcon:mJ,UserIcon:Fo,UserMinus:u$,UserMinus2:TR,UserMinus2Icon:TR,UserMinusIcon:u$,UserPen:w5e,UserPenIcon:w5e,UserPlus:Pl,UserPlus2:MR,UserPlus2Icon:MR,UserPlusIcon:Pl,UserRound:LR,UserRoundCheck:i6,UserRoundCheckIcon:i6,UserRoundCog:ER,UserRoundCogIcon:ER,UserRoundIcon:LR,UserRoundMinus:TR,UserRoundMinusIcon:TR,UserRoundPen:j5e,UserRoundPenIcon:j5e,UserRoundPlus:MR,UserRoundPlusIcon:MR,UserRoundSearch:h$,UserRoundSearchIcon:h$,UserRoundX:PR,UserRoundXIcon:PR,UserSearch:N5e,UserSearchIcon:N5e,UserSquare:_R,UserSquare2:bR,UserSquare2Icon:bR,UserSquareIcon:_R,UserX:m$,UserX2:PR,UserX2Icon:PR,UserXIcon:m$,Users:In,Users2:x0,Users2Icon:x0,UsersIcon:In,UsersRound:x0,UsersRoundIcon:x0,Utensils:DR,UtensilsCrossed:IR,UtensilsCrossedIcon:IR,UtensilsIcon:DR,UtilityPole:k5e,UtilityPoleIcon:k5e,Variable:p$,VariableIcon:p$,Vault:S5e,VaultIcon:S5e,Vegan:C5e,VeganIcon:C5e,VenetianMask:A5e,VenetianMaskIcon:A5e,Verified:K3,VerifiedIcon:K3,Vibrate:T5e,VibrateIcon:T5e,VibrateOff:E5e,VibrateOffIcon:E5e,Video:Kr,VideoIcon:Kr,VideoOff:M5e,VideoOffIcon:M5e,Videotape:P5e,VideotapeIcon:P5e,View:L5e,ViewIcon:L5e,Voicemail:I5e,VoicemailIcon:I5e,Volleyball:D5e,VolleyballIcon:D5e,Volume:O5e,Volume1:R5e,Volume1Icon:R5e,Volume2:pJ,Volume2Icon:pJ,VolumeIcon:O5e,VolumeOff:F5e,VolumeOffIcon:F5e,VolumeX:fJ,VolumeXIcon:fJ,Vote:z5e,VoteIcon:z5e,Wallet:m7,Wallet2:RR,Wallet2Icon:RR,WalletCards:B5e,WalletCardsIcon:B5e,WalletIcon:m7,WalletMinimal:RR,WalletMinimalIcon:RR,Wallpaper:U5e,WallpaperIcon:U5e,Wand:q5e,Wand2:Qx,Wand2Icon:Qx,WandIcon:q5e,WandSparkles:Qx,WandSparklesIcon:Qx,Warehouse:$5e,WarehouseIcon:$5e,WashingMachine:V5e,WashingMachineIcon:V5e,Watch:H5e,WatchIcon:H5e,Waves:G5e,WavesIcon:G5e,Waypoints:W5e,WaypointsIcon:W5e,Webcam:K5e,WebcamIcon:K5e,Webhook:Z5e,WebhookIcon:Z5e,WebhookOff:Y5e,WebhookOffIcon:Y5e,Weight:X5e,WeightIcon:X5e,Wheat:J5e,WheatIcon:J5e,WheatOff:Q5e,WheatOffIcon:Q5e,WholeWord:e4e,WholeWordIcon:e4e,Wifi:a4e,WifiHigh:t4e,WifiHighIcon:t4e,WifiIcon:a4e,WifiLow:s4e,WifiLowIcon:s4e,WifiOff:n4e,WifiOffIcon:n4e,WifiZero:r4e,WifiZeroIcon:r4e,Wind:o4e,WindArrowDown:i4e,WindArrowDownIcon:i4e,WindIcon:o4e,Wine:c4e,WineIcon:c4e,WineOff:l4e,WineOffIcon:l4e,Workflow:p7,WorkflowIcon:p7,Worm:d4e,WormIcon:d4e,WrapText:u4e,WrapTextIcon:u4e,Wrench:Y4,WrenchIcon:Y4,X:Qn,XCircle:Rd,XCircleIcon:Rd,XIcon:Qn,XOctagon:lD,XOctagonIcon:lD,XSquare:wR,XSquareIcon:wR,Youtube:f$,YoutubeIcon:f$,Zap:nf,ZapIcon:nf,ZapOff:h4e,ZapOffIcon:h4e,ZoomIn:aP,ZoomInIcon:aP,ZoomOut:x$,ZoomOutIcon:x$,createLucideIcon:fe,icons:Qfs},Symbol.toStringTag,{value:"Module"})),OXe="-",Jfs=s=>{const t=txs(s),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=s;return{getClassGroupId:l=>{const o=l.split(OXe);return o[0]===""&&o.length!==1&&o.shift(),iMt(o,t)||exs(l)},getConflictingClassGroupIds:(l,o)=>{const c=n[l]||[];return o&&r[l]?[...c,...r[l]]:c}}},iMt=(s,t)=>{var l;if(s.length===0)return t.classGroupId;const n=s[0],r=t.nextPart.get(n),a=r?iMt(s.slice(1),r):void 0;if(a)return a;if(t.validators.length===0)return;const i=s.join(OXe);return(l=t.validators.find(({validator:o})=>o(i)))==null?void 0:l.classGroupId},Oht=/^\[(.+)\]$/,exs=s=>{if(Oht.test(s)){const t=Oht.exec(s)[1],n=t==null?void 0:t.substring(0,t.indexOf(":"));if(n)return"arbitrary.."+n}},txs=s=>{const{theme:t,prefix:n}=s,r={nextPart:new Map,validators:[]};return nxs(Object.entries(s.classGroups),n).forEach(([i,l])=>{Rqe(l,r,i,t)}),r},Rqe=(s,t,n,r)=>{s.forEach(a=>{if(typeof a=="string"){const i=a===""?t:zht(t,a);i.classGroupId=n;return}if(typeof a=="function"){if(sxs(a)){Rqe(a(r),t,n,r);return}t.validators.push({validator:a,classGroupId:n});return}Object.entries(a).forEach(([i,l])=>{Rqe(l,zht(t,i),n,r)})})},zht=(s,t)=>{let n=s;return t.split(OXe).forEach(r=>{n.nextPart.has(r)||n.nextPart.set(r,{nextPart:new Map,validators:[]}),n=n.nextPart.get(r)}),n},sxs=s=>s.isThemeGetter,nxs=(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,rxs=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)}}},oMt="!",axs=s=>{const{separator:t,experimentalParseClassName:n}=s,r=t.length===1,a=t[0],i=t.length,l=o=>{const c=[];let d=0,u=0,h;for(let v=0;vu?h-u:void 0;return{modifiers:c,hasImportantModifier:p,baseClassName:f,maybePostfixModifierPosition:y}};return n?o=>n({className:o,parseClassName:l}):l},ixs=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},oxs=s=>({cache:rxs(s.cacheSize),parseClassName:axs(s),...Jfs(s)}),lxs=/\s+/,cxs=(s,t)=>{const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:a}=t,i=[],l=s.trim().split(lxs);let o="";for(let c=l.length-1;c>=0;c-=1){const d=l[c],{modifiers:u,hasImportantModifier:h,baseClassName:m,maybePostfixModifierPosition:p}=n(d);let f=!!p,y=r(f?m.substring(0,p):m);if(!y){if(!f){o=d+(o.length>0?" "+o:o);continue}if(y=r(m),!y){o=d+(o.length>0?" "+o:o);continue}f=!1}const v=ixs(u).join(":"),g=h?v+oMt:v,b=g+y;if(i.includes(b))continue;i.push(b);const j=a(y,f);for(let S=0;S0?" "+o:o)}return o};function dxs(){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=oxs(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=cxs(c,n);return a(c,u),u}return function(){return i(dxs.apply(null,arguments))}}const xp=s=>{const t=n=>n[s]||[];return t.isThemeGetter=!0,t},cMt=/^\[(?:([a-z-]+):)?(.+)\]$/i,hxs=/^\d+\/\d+$/,mxs=new Set(["px","full","screen"]),pxs=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,fxs=/\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$/,xxs=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,gxs=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,yxs=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,u3=s=>g$(s)||mxs.has(s)||hxs.test(s),gT=s=>ZG(s,"length",Sxs),g$=s=>!!s&&!Number.isNaN(Number(s)),OFe=s=>ZG(s,"number",g$),AY=s=>!!s&&Number.isInteger(Number(s)),vxs=s=>s.endsWith("%")&&g$(s.slice(0,-1)),Kc=s=>cMt.test(s),yT=s=>pxs.test(s),bxs=new Set(["length","size","percentage"]),_xs=s=>ZG(s,bxs,dMt),wxs=s=>ZG(s,"position",dMt),jxs=new Set(["image","url"]),Nxs=s=>ZG(s,jxs,Axs),kxs=s=>ZG(s,"",Cxs),EY=()=>!0,ZG=(s,t,n)=>{const r=cMt.exec(s);return r?r[1]?typeof t=="string"?r[1]===t:t.has(r[1]):n(r[2]):!1},Sxs=s=>fxs.test(s)&&!xxs.test(s),dMt=()=>!1,Cxs=s=>gxs.test(s),Axs=s=>yxs.test(s),Exs=()=>{const s=xp("colors"),t=xp("spacing"),n=xp("blur"),r=xp("brightness"),a=xp("borderColor"),i=xp("borderRadius"),l=xp("borderSpacing"),o=xp("borderWidth"),c=xp("contrast"),d=xp("grayscale"),u=xp("hueRotate"),h=xp("invert"),m=xp("gap"),p=xp("gradientColorStops"),f=xp("gradientColorStopPositions"),y=xp("inset"),v=xp("margin"),g=xp("opacity"),b=xp("padding"),j=xp("saturate"),S=xp("scale"),C=xp("sepia"),E=xp("skew"),P=xp("space"),M=xp("translate"),I=()=>["auto","contain","none"],D=()=>["auto","hidden","clip","visible","scroll"],O=()=>["auto",Kc,t],V=()=>[Kc,t],G=()=>["",u3,gT],$=()=>["auto",g$,Kc],H=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],Y=()=>["solid","dashed","dotted","double","none"],Z=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],ne=()=>["start","end","center","between","around","evenly","stretch"],ce=()=>["","0",Kc],ie=()=>["auto","avoid","all","avoid-page","page","left","right","column"],te=()=>[g$,Kc];return{cacheSize:500,separator:":",theme:{colors:[EY],spacing:[u3,gT],blur:["none","",yT,Kc],brightness:te(),borderColor:[s],borderRadius:["none","","full",yT,Kc],borderSpacing:V(),borderWidth:G(),contrast:te(),grayscale:ce(),hueRotate:te(),invert:ce(),gap:V(),gradientColorStops:[s],gradientColorStopPositions:[vxs,gT],inset:O(),margin:O(),opacity:te(),padding:V(),saturate:te(),scale:te(),sepia:ce(),skew:te(),space:V(),translate:V()},classGroups:{aspect:[{aspect:["auto","square","video",Kc]}],container:["container"],columns:[{columns:[yT]}],"break-after":[{"break-after":ie()}],"break-before":[{"break-before":ie()}],"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:[...H(),Kc]}],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:[y]}],"inset-x":[{"inset-x":[y]}],"inset-y":[{"inset-y":[y]}],start:[{start:[y]}],end:[{end:[y]}],top:[{top:[y]}],right:[{right:[y]}],bottom:[{bottom:[y]}],left:[{left:[y]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",AY,Kc]}],basis:[{basis:O()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",Kc]}],grow:[{grow:ce()}],shrink:[{shrink:ce()}],order:[{order:["first","last","none",AY,Kc]}],"grid-cols":[{"grid-cols":[EY]}],"col-start-end":[{col:["auto",{span:["full",AY,Kc]},Kc]}],"col-start":[{"col-start":$()}],"col-end":[{"col-end":$()}],"grid-rows":[{"grid-rows":[EY]}],"row-start-end":[{row:["auto",{span:[AY,Kc]},Kc]}],"row-start":[{"row-start":$()}],"row-end":[{"row-end":$()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",Kc]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",Kc]}],gap:[{gap:[m]}],"gap-x":[{"gap-x":[m]}],"gap-y":[{"gap-y":[m]}],"justify-content":[{justify:["normal",...ne()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...ne(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...ne(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[b]}],px:[{px:[b]}],py:[{py:[b]}],ps:[{ps:[b]}],pe:[{pe:[b]}],pt:[{pt:[b]}],pr:[{pr:[b]}],pb:[{pb:[b]}],pl:[{pl:[b]}],m:[{m:[v]}],mx:[{mx:[v]}],my:[{my:[v]}],ms:[{ms:[v]}],me:[{me:[v]}],mt:[{mt:[v]}],mr:[{mr:[v]}],mb:[{mb:[v]}],ml:[{ml:[v]}],"space-x":[{"space-x":[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",Kc,t]}],"min-w":[{"min-w":[Kc,t,"min","max","fit"]}],"max-w":[{"max-w":[Kc,t,"none","full","min","max","fit","prose",{screen:[yT]},yT]}],h:[{h:[Kc,t,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[Kc,t,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[Kc,t,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[Kc,t,"auto","min","max","fit"]}],"font-size":[{text:["base",yT,gT]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",OFe]}],"font-family":[{font:[EY]}],"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",Kc]}],"line-clamp":[{"line-clamp":["none",g$,OFe]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",u3,Kc]}],"list-image":[{"list-image":["none",Kc]}],"list-style-type":[{list:["none","disc","decimal",Kc]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[s]}],"placeholder-opacity":[{"placeholder-opacity":[g]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[s]}],"text-opacity":[{"text-opacity":[g]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...Y(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",u3,gT]}],"underline-offset":[{"underline-offset":["auto",u3,Kc]}],"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:V()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Kc]}],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",Kc]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[g]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...H(),wxs]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",_xs]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},Nxs]}],"bg-color":[{bg:[s]}],"gradient-from-pos":[{from:[f]}],"gradient-via-pos":[{via:[f]}],"gradient-to-pos":[{to:[f]}],"gradient-from":[{from:[p]}],"gradient-via":[{via:[p]}],"gradient-to":[{to:[p]}],rounded:[{rounded:[i]}],"rounded-s":[{"rounded-s":[i]}],"rounded-e":[{"rounded-e":[i]}],"rounded-t":[{"rounded-t":[i]}],"rounded-r":[{"rounded-r":[i]}],"rounded-b":[{"rounded-b":[i]}],"rounded-l":[{"rounded-l":[i]}],"rounded-ss":[{"rounded-ss":[i]}],"rounded-se":[{"rounded-se":[i]}],"rounded-ee":[{"rounded-ee":[i]}],"rounded-es":[{"rounded-es":[i]}],"rounded-tl":[{"rounded-tl":[i]}],"rounded-tr":[{"rounded-tr":[i]}],"rounded-br":[{"rounded-br":[i]}],"rounded-bl":[{"rounded-bl":[i]}],"border-w":[{border:[o]}],"border-w-x":[{"border-x":[o]}],"border-w-y":[{"border-y":[o]}],"border-w-s":[{"border-s":[o]}],"border-w-e":[{"border-e":[o]}],"border-w-t":[{"border-t":[o]}],"border-w-r":[{"border-r":[o]}],"border-w-b":[{"border-b":[o]}],"border-w-l":[{"border-l":[o]}],"border-opacity":[{"border-opacity":[g]}],"border-style":[{border:[...Y(),"hidden"]}],"divide-x":[{"divide-x":[o]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[o]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[g]}],"divide-style":[{divide:Y()}],"border-color":[{border:[a]}],"border-color-x":[{"border-x":[a]}],"border-color-y":[{"border-y":[a]}],"border-color-s":[{"border-s":[a]}],"border-color-e":[{"border-e":[a]}],"border-color-t":[{"border-t":[a]}],"border-color-r":[{"border-r":[a]}],"border-color-b":[{"border-b":[a]}],"border-color-l":[{"border-l":[a]}],"divide-color":[{divide:[a]}],"outline-style":[{outline:["",...Y()]}],"outline-offset":[{"outline-offset":[u3,Kc]}],"outline-w":[{outline:[u3,gT]}],"outline-color":[{outline:[s]}],"ring-w":[{ring:G()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[s]}],"ring-opacity":[{"ring-opacity":[g]}],"ring-offset-w":[{"ring-offset":[u3,gT]}],"ring-offset-color":[{"ring-offset":[s]}],shadow:[{shadow:["","inner","none",yT,kxs]}],"shadow-color":[{shadow:[EY]}],opacity:[{opacity:[g]}],"mix-blend":[{"mix-blend":[...Z(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":Z()}],filter:[{filter:["","none"]}],blur:[{blur:[n]}],brightness:[{brightness:[r]}],contrast:[{contrast:[c]}],"drop-shadow":[{"drop-shadow":["","none",yT,Kc]}],grayscale:[{grayscale:[d]}],"hue-rotate":[{"hue-rotate":[u]}],invert:[{invert:[h]}],saturate:[{saturate:[j]}],sepia:[{sepia:[C]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[n]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[c]}],"backdrop-grayscale":[{"backdrop-grayscale":[d]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[u]}],"backdrop-invert":[{"backdrop-invert":[h]}],"backdrop-opacity":[{"backdrop-opacity":[g]}],"backdrop-saturate":[{"backdrop-saturate":[j]}],"backdrop-sepia":[{"backdrop-sepia":[C]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[l]}],"border-spacing-x":[{"border-spacing-x":[l]}],"border-spacing-y":[{"border-spacing-y":[l]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",Kc]}],duration:[{duration:te()}],ease:[{ease:["linear","in","out","in-out",Kc]}],delay:[{delay:te()}],animate:[{animate:["none","spin","ping","pulse","bounce",Kc]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[S]}],"scale-x":[{"scale-x":[S]}],"scale-y":[{"scale-y":[S]}],rotate:[{rotate:[AY,Kc]}],"translate-x":[{"translate-x":[M]}],"translate-y":[{"translate-y":[M]}],"skew-x":[{"skew-x":[E]}],"skew-y":[{"skew-y":[E]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",Kc]}],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",Kc]}],"caret-color":[{caret:[s]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":V()}],"scroll-mx":[{"scroll-mx":V()}],"scroll-my":[{"scroll-my":V()}],"scroll-ms":[{"scroll-ms":V()}],"scroll-me":[{"scroll-me":V()}],"scroll-mt":[{"scroll-mt":V()}],"scroll-mr":[{"scroll-mr":V()}],"scroll-mb":[{"scroll-mb":V()}],"scroll-ml":[{"scroll-ml":V()}],"scroll-p":[{"scroll-p":V()}],"scroll-px":[{"scroll-px":V()}],"scroll-py":[{"scroll-py":V()}],"scroll-ps":[{"scroll-ps":V()}],"scroll-pe":[{"scroll-pe":V()}],"scroll-pt":[{"scroll-pt":V()}],"scroll-pr":[{"scroll-pr":V()}],"scroll-pb":[{"scroll-pb":V()}],"scroll-pl":[{"scroll-pl":V()}],"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",Kc]}],fill:[{fill:[s,"none"]}],"stroke-w":[{stroke:[u3,gT,OFe]}],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"]}}},Txs=uxs(Exs);function At(...s){return Txs(jc(s))}function am(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 Bht(s){const t=new Date(s);return new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric"}).format(t)}function Hee(s){return s?s.replace(/<[^>]*>/g,""):""}const Mxs=Yfs,uMt=_.forwardRef(({className:s,...t},n)=>e.jsx(X6t,{ref:n,className:At("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}));uMt.displayName=X6t.displayName;const Pxs=F9("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"}}),hMt=_.forwardRef(({className:s,variant:t,...n},r)=>e.jsx(Q6t,{ref:r,className:At(Pxs({variant:t}),s),...n}));hMt.displayName=Q6t.displayName;const Lxs=_.forwardRef(({className:s,...t},n)=>e.jsx(tMt,{ref:n,className:At("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}));Lxs.displayName=tMt.displayName;const mMt=_.forwardRef(({className:s,...t},n)=>e.jsx(sMt,{ref:n,className:At("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(Qn,{className:"h-4 w-4"})}));mMt.displayName=sMt.displayName;const pMt=_.forwardRef(({className:s,...t},n)=>e.jsx(J6t,{ref:n,className:At("text-sm font-semibold",s),...t}));pMt.displayName=J6t.displayName;const fMt=_.forwardRef(({className:s,...t},n)=>e.jsx(eMt,{ref:n,className:At("text-sm opacity-90",s),...t}));fMt.displayName=eMt.displayName;function Ixs(){const{toasts:s}=vi();return e.jsxs(Mxs,{children:[s.map(function({id:t,title:n,description:r,action:a,...i}){return e.jsxs(hMt,{...i,children:[e.jsxs("div",{className:"grid gap-1",children:[n&&e.jsx(pMt,{children:n}),r&&e.jsx(fMt,{children:r})]}),a,e.jsx(mMt,{})]},t)}),e.jsx(uMt,{})]})}var Uht=["light","dark"],Dxs="(prefers-color-scheme: dark)",Rxs=_.createContext(void 0),Fxs={setTheme:s=>{},themes:[]},Oxs=()=>{var s;return(s=_.useContext(Rxs))!=null?s:Fxs};_.memo(({forcedTheme:s,storageKey:t,attribute:n,enableSystem:r,enableColorScheme:a,defaultTheme:i,value:l,attrs:o,nonce:c})=>{let d=i==="system",u=n==="class"?`var d=document.documentElement,c=d.classList;${`c.remove(${o.map(f=>`'${f}'`).join(",")})`};`:`var d=document.documentElement,n='${n}',s='setAttribute';`,h=a?Uht.includes(i)&&i?`if(e==='light'||e==='dark'||!e)d.style.colorScheme=e||'${i}'`:"if(e==='light'||e==='dark')d.style.colorScheme=e":"",m=(f,y=!1,v=!0)=>{let g=l?l[f]:f,b=y?f+"|| ''":`'${g}'`,j="";return a&&v&&!y&&Uht.includes(f)&&(j+=`d.style.colorScheme = '${f}';`),n==="class"?y||g?j+=`c.add(${b})`:j+="null":g&&(j+=`d[s](n,${b})`),j},p=s?`!function(){${u}${m(s)}}()`:r?`!function(){try{${u}var e=localStorage.getItem('${t}');if('system'===e||(!e&&${d})){var t='${Dxs}',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 _.createElement("script",{nonce:c,dangerouslySetInnerHTML:{__html:p}})});var zxs=s=>{switch(s){case"success":return qxs;case"info":return Vxs;case"warning":return $xs;case"error":return Hxs;default:return null}},Bxs=Array(12).fill(0),Uxs=({visible:s,className:t})=>Dt.createElement("div",{className:["sonner-loading-wrapper",t].filter(Boolean).join(" "),"data-visible":s},Dt.createElement("div",{className:"sonner-spinner"},Bxs.map((n,r)=>Dt.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${r}`})))),qxs=Dt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Dt.createElement("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z",clipRule:"evenodd"})),$xs=Dt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},Dt.createElement("path",{fillRule:"evenodd",d:"M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z",clipRule:"evenodd"})),Vxs=Dt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Dt.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z",clipRule:"evenodd"})),Hxs=Dt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Dt.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})),Gxs=Dt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},Dt.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),Dt.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),Wxs=()=>{let[s,t]=Dt.useState(document.hidden);return Dt.useEffect(()=>{let n=()=>{t(document.hidden)};return document.addEventListener("visibilitychange",n),()=>window.removeEventListener("visibilitychange",n)},[]),s},Fqe=1,Kxs=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:Fqe++,l=this.toasts.find(c=>c.id===i),o=t.dismissible===void 0?!0:t.dismissible;return this.dismissedToasts.has(i)&&this.dismissedToasts.delete(i),l?this.toasts=this.toasts.map(c=>c.id===i?(this.publish({...c,...t,id:i,title:r}),{...c,...t,id:i,dismissible:o,title:r}):c):this.addToast({title:r,...a,dismissible:o,id:i}),i},this.dismiss=t=>(this.dismissedToasts.add(t),t||this.toasts.forEach(n=>{this.subscribers.forEach(r=>r({id:n.id,dismiss:!0}))}),this.subscribers.forEach(n=>n({id:t,dismiss:!0})),t),this.message=(t,n)=>this.create({...n,message:t}),this.error=(t,n)=>this.create({...n,message:t,type:"error"}),this.success=(t,n)=>this.create({...n,type:"success",message:t}),this.info=(t,n)=>this.create({...n,type:"info",message:t}),this.warning=(t,n)=>this.create({...n,type:"warning",message:t}),this.loading=(t,n)=>this.create({...n,type:"loading",message:t}),this.promise=(t,n)=>{if(!n)return;let r;n.loading!==void 0&&(r=this.create({...n,promise:t,type:"loading",message:n.loading,description:typeof n.description!="function"?n.description:void 0}));let a=t instanceof Promise?t:t(),i=r!==void 0,l,o=a.then(async d=>{if(l=["resolve",d],Dt.isValidElement(d))i=!1,this.create({id:r,type:"default",message:d});else if(Zxs(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)||Fqe++;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}},f_=new Kxs,Yxs=(s,t)=>{let n=(t==null?void 0:t.id)||Fqe++;return f_.addToast({title:s,...t,id:n}),n},Zxs=s=>s&&typeof s=="object"&&"ok"in s&&typeof s.ok=="boolean"&&"status"in s&&typeof s.status=="number",Xxs=Yxs,Qxs=()=>f_.toasts,Jxs=()=>f_.getActiveToasts(),se=Object.assign(Xxs,{success:f_.success,info:f_.info,warning:f_.warning,error:f_.error,custom:f_.custom,message:f_.message,promise:f_.promise,dismiss:f_.dismiss,loading:f_.loading},{getHistory:Qxs,getToasts:Jxs});function egs(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))}egs(`: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 Xoe(s){return s.label!==void 0}var tgs=3,sgs="32px",ngs="16px",qht=4e3,rgs=356,ags=14,igs=20,ogs=200;function pk(...s){return s.filter(Boolean).join(" ")}function lgs(s){let[t,n]=s.split("-"),r=[];return t&&r.push(t),n&&r.push(n),r}var cgs=s=>{var t,n,r,a,i,l,o,c,d,u,h;let{invert:m,toast:p,unstyled:f,interacting:y,setHeights:v,visibleToasts:g,heights:b,index:j,toasts:S,expanded:C,removeToast:E,defaultRichColors:P,closeButton:M,style:I,cancelButtonStyle:D,actionButtonStyle:O,className:V="",descriptionClassName:G="",duration:$,position:H,gap:Y,loadingIcon:Z,expandByDefault:ne,classNames:ce,icons:ie,closeButtonAriaLabel:te="Close toast",pauseWhenPageIsHidden:ae}=s,[le,be]=Dt.useState(null),[me,he]=Dt.useState(null),[pe,Ce]=Dt.useState(!1),[Ae,Pe]=Dt.useState(!1),[ze,ke]=Dt.useState(!1),[Ze,Se]=Dt.useState(!1),[Fe,Ne]=Dt.useState(!1),[Ye,Ve]=Dt.useState(0),[qe,Qe]=Dt.useState(0),Ue=Dt.useRef(p.duration||$||qht),Xe=Dt.useRef(null),nt=Dt.useRef(null),$e=j===0,Ge=j+1<=g,ct=p.type,xt=p.dismissible!==!1,qt=p.className||"",Vt=p.descriptionClassName||"",Xt=Dt.useMemo(()=>b.findIndex(Cn=>Cn.toastId===p.id)||0,[b,p.id]),fs=Dt.useMemo(()=>{var Cn;return(Cn=p.closeButton)!=null?Cn:M},[p.closeButton,M]),Ft=Dt.useMemo(()=>p.duration||$||qht,[p.duration,$]),wt=Dt.useRef(0),Ts=Dt.useRef(0),vt=Dt.useRef(0),$s=Dt.useRef(null),[As,jn]=H.split("-"),ar=Dt.useMemo(()=>b.reduce((Cn,Yn,on)=>on>=Xt?Cn:Cn+Yn.height,0),[b,Xt]),Dn=Wxs(),Ur=p.invert||m,Vs=ct==="loading";Ts.current=Dt.useMemo(()=>Xt*Y+ar,[Xt,ar]),Dt.useEffect(()=>{Ue.current=Ft},[Ft]),Dt.useEffect(()=>{Ce(!0)},[]),Dt.useEffect(()=>{let Cn=nt.current;if(Cn){let Yn=Cn.getBoundingClientRect().height;return Qe(Yn),v(on=>[{toastId:p.id,height:Yn,position:p.position},...on]),()=>v(on=>on.filter(Ir=>Ir.toastId!==p.id))}},[v,p.id]),Dt.useLayoutEffect(()=>{if(!pe)return;let Cn=nt.current,Yn=Cn.style.height;Cn.style.height="auto";let on=Cn.getBoundingClientRect().height;Cn.style.height=Yn,Qe(on),v(Ir=>Ir.find(Wn=>Wn.toastId===p.id)?Ir.map(Wn=>Wn.toastId===p.id?{...Wn,height:on}:Wn):[{toastId:p.id,height:on,position:p.position},...Ir])},[pe,p.title,p.description,v,p.id]);let hn=Dt.useCallback(()=>{Pe(!0),Ve(Ts.current),v(Cn=>Cn.filter(Yn=>Yn.toastId!==p.id)),setTimeout(()=>{E(p)},ogs)},[p,E,v,Ts]);Dt.useEffect(()=>{if(p.promise&&ct==="loading"||p.duration===1/0||p.type==="loading")return;let Cn;return C||y||ae&&Dn?(()=>{if(vt.current{var Yn;(Yn=p.onAutoClose)==null||Yn.call(p,p),hn()},Ue.current)),()=>clearTimeout(Cn)},[C,y,p,ct,ae,Dn,hn]),Dt.useEffect(()=>{p.delete&&hn()},[hn,p.delete]);function dr(){var Cn,Yn,on;return ie!=null&&ie.loading?Dt.createElement("div",{className:pk(ce==null?void 0:ce.loader,(Cn=p==null?void 0:p.classNames)==null?void 0:Cn.loader,"sonner-loader"),"data-visible":ct==="loading"},ie.loading):Z?Dt.createElement("div",{className:pk(ce==null?void 0:ce.loader,(Yn=p==null?void 0:p.classNames)==null?void 0:Yn.loader,"sonner-loader"),"data-visible":ct==="loading"},Z):Dt.createElement(Uxs,{className:pk(ce==null?void 0:ce.loader,(on=p==null?void 0:p.classNames)==null?void 0:on.loader),visible:ct==="loading"})}return Dt.createElement("li",{tabIndex:0,ref:nt,className:pk(V,qt,ce==null?void 0:ce.toast,(t=p==null?void 0:p.classNames)==null?void 0:t.toast,ce==null?void 0:ce.default,ce==null?void 0:ce[ct],(n=p==null?void 0:p.classNames)==null?void 0:n[ct]),"data-sonner-toast":"","data-rich-colors":(r=p.richColors)!=null?r:P,"data-styled":!(p.jsx||p.unstyled||f),"data-mounted":pe,"data-promise":!!p.promise,"data-swiped":Fe,"data-removed":Ae,"data-visible":Ge,"data-y-position":As,"data-x-position":jn,"data-index":j,"data-front":$e,"data-swiping":ze,"data-dismissible":xt,"data-type":ct,"data-invert":Ur,"data-swipe-out":Ze,"data-swipe-direction":me,"data-expanded":!!(C||ne&&pe),style:{"--index":j,"--toasts-before":j,"--z-index":S.length-j,"--offset":`${Ae?Ye:Ts.current}px`,"--initial-height":ne?"auto":`${qe}px`,...I,...p.style},onDragEnd:()=>{ke(!1),be(null),$s.current=null},onPointerDown:Cn=>{Vs||!xt||(Xe.current=new Date,Ve(Ts.current),Cn.target.setPointerCapture(Cn.pointerId),Cn.target.tagName!=="BUTTON"&&(ke(!0),$s.current={x:Cn.clientX,y:Cn.clientY}))},onPointerUp:()=>{var Cn,Yn,on,Ir;if(Ze||!xt)return;$s.current=null;let Wn=Number(((Cn=nt.current)==null?void 0:Cn.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),Js=Number(((Yn=nt.current)==null?void 0:Yn.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),Fa=new Date().getTime()-((on=Xe.current)==null?void 0:on.getTime()),ks=le==="x"?Wn:Js,Gs=Math.abs(ks)/Fa;if(Math.abs(ks)>=igs||Gs>.11){Ve(Ts.current),(Ir=p.onDismiss)==null||Ir.call(p,p),he(le==="x"?Wn>0?"right":"left":Js>0?"down":"up"),hn(),Se(!0),Ne(!1);return}ke(!1),be(null)},onPointerMove:Cn=>{var Yn,on,Ir,Wn;if(!$s.current||!xt||((Yn=window.getSelection())==null?void 0:Yn.toString().length)>0)return;let Js=Cn.clientY-$s.current.y,Fa=Cn.clientX-$s.current.x,ks=(on=s.swipeDirections)!=null?on:lgs(H);!le&&(Math.abs(Fa)>1||Math.abs(Js)>1)&&be(Math.abs(Fa)>Math.abs(Js)?"x":"y");let Gs={x:0,y:0};le==="y"?(ks.includes("top")||ks.includes("bottom"))&&(ks.includes("top")&&Js<0||ks.includes("bottom")&&Js>0)&&(Gs.y=Js):le==="x"&&(ks.includes("left")||ks.includes("right"))&&(ks.includes("left")&&Fa<0||ks.includes("right")&&Fa>0)&&(Gs.x=Fa),(Math.abs(Gs.x)>0||Math.abs(Gs.y)>0)&&Ne(!0),(Ir=nt.current)==null||Ir.style.setProperty("--swipe-amount-x",`${Gs.x}px`),(Wn=nt.current)==null||Wn.style.setProperty("--swipe-amount-y",`${Gs.y}px`)}},fs&&!p.jsx?Dt.createElement("button",{"aria-label":te,"data-disabled":Vs,"data-close-button":!0,onClick:Vs||!xt?()=>{}:()=>{var Cn;hn(),(Cn=p.onDismiss)==null||Cn.call(p,p)},className:pk(ce==null?void 0:ce.closeButton,(a=p==null?void 0:p.classNames)==null?void 0:a.closeButton)},(i=ie==null?void 0:ie.close)!=null?i:Gxs):null,p.jsx||_.isValidElement(p.title)?p.jsx?p.jsx:typeof p.title=="function"?p.title():p.title:Dt.createElement(Dt.Fragment,null,ct||p.icon||p.promise?Dt.createElement("div",{"data-icon":"",className:pk(ce==null?void 0:ce.icon,(l=p==null?void 0:p.classNames)==null?void 0:l.icon)},p.promise||p.type==="loading"&&!p.icon?p.icon||dr():null,p.type!=="loading"?p.icon||(ie==null?void 0:ie[ct])||zxs(ct):null):null,Dt.createElement("div",{"data-content":"",className:pk(ce==null?void 0:ce.content,(o=p==null?void 0:p.classNames)==null?void 0:o.content)},Dt.createElement("div",{"data-title":"",className:pk(ce==null?void 0:ce.title,(c=p==null?void 0:p.classNames)==null?void 0:c.title)},typeof p.title=="function"?p.title():p.title),p.description?Dt.createElement("div",{"data-description":"",className:pk(G,Vt,ce==null?void 0:ce.description,(d=p==null?void 0:p.classNames)==null?void 0:d.description)},typeof p.description=="function"?p.description():p.description):null),_.isValidElement(p.cancel)?p.cancel:p.cancel&&Xoe(p.cancel)?Dt.createElement("button",{"data-button":!0,"data-cancel":!0,style:p.cancelButtonStyle||D,onClick:Cn=>{var Yn,on;Xoe(p.cancel)&&xt&&((on=(Yn=p.cancel).onClick)==null||on.call(Yn,Cn),hn())},className:pk(ce==null?void 0:ce.cancelButton,(u=p==null?void 0:p.classNames)==null?void 0:u.cancelButton)},p.cancel.label):null,_.isValidElement(p.action)?p.action:p.action&&Xoe(p.action)?Dt.createElement("button",{"data-button":!0,"data-action":!0,style:p.actionButtonStyle||O,onClick:Cn=>{var Yn,on;Xoe(p.action)&&((on=(Yn=p.action).onClick)==null||on.call(Yn,Cn),!Cn.defaultPrevented&&hn())},className:pk(ce==null?void 0:ce.actionButton,(h=p==null?void 0:p.classNames)==null?void 0:h.actionButton)},p.action.label):null))};function $ht(){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 dgs(s,t){let n={};return[s,t].forEach((r,a)=>{let i=a===1,l=i?"--mobile-offset":"--offset",o=i?ngs:sgs;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 ugs=_.forwardRef(function(s,t){let{invert:n,position:r="bottom-right",hotkey:a=["altKey","KeyT"],expand:i,closeButton:l,className:o,offset:c,mobileOffset:d,theme:u="light",richColors:h,duration:m,style:p,visibleToasts:f=tgs,toastOptions:y,dir:v=$ht(),gap:g=ags,loadingIcon:b,icons:j,containerAriaLabel:S="Notifications",pauseWhenPageIsHidden:C}=s,[E,P]=Dt.useState([]),M=Dt.useMemo(()=>Array.from(new Set([r].concat(E.filter(ae=>ae.position).map(ae=>ae.position)))),[E,r]),[I,D]=Dt.useState([]),[O,V]=Dt.useState(!1),[G,$]=Dt.useState(!1),[H,Y]=Dt.useState(u!=="system"?u:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),Z=Dt.useRef(null),ne=a.join("+").replace(/Key/g,"").replace(/Digit/g,""),ce=Dt.useRef(null),ie=Dt.useRef(!1),te=Dt.useCallback(ae=>{P(le=>{var be;return(be=le.find(me=>me.id===ae.id))!=null&&be.delete||f_.dismiss(ae.id),le.filter(({id:me})=>me!==ae.id)})},[]);return Dt.useEffect(()=>f_.subscribe(ae=>{if(ae.dismiss){P(le=>le.map(be=>be.id===ae.id?{...be,delete:!0}:be));return}setTimeout(()=>{PXe.flushSync(()=>{P(le=>{let be=le.findIndex(me=>me.id===ae.id);return be!==-1?[...le.slice(0,be),{...le[be],...ae},...le.slice(be+1)]:[ae,...le]})})})}),[]),Dt.useEffect(()=>{if(u!=="system"){Y(u);return}if(u==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?Y("dark"):Y("light")),typeof window>"u")return;let ae=window.matchMedia("(prefers-color-scheme: dark)");try{ae.addEventListener("change",({matches:le})=>{Y(le?"dark":"light")})}catch{ae.addListener(({matches:be})=>{try{Y(be?"dark":"light")}catch(me){console.error(me)}})}},[u]),Dt.useEffect(()=>{E.length<=1&&V(!1)},[E]),Dt.useEffect(()=>{let ae=le=>{var be,me;a.every(he=>le[he]||le.code===he)&&(V(!0),(be=Z.current)==null||be.focus()),le.code==="Escape"&&(document.activeElement===Z.current||(me=Z.current)!=null&&me.contains(document.activeElement))&&V(!1)};return document.addEventListener("keydown",ae),()=>document.removeEventListener("keydown",ae)},[a]),Dt.useEffect(()=>{if(Z.current)return()=>{ce.current&&(ce.current.focus({preventScroll:!0}),ce.current=null,ie.current=!1)}},[Z.current]),Dt.createElement("section",{ref:t,"aria-label":`${S} ${ne}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},M.map((ae,le)=>{var be;let[me,he]=ae.split("-");return E.length?Dt.createElement("ol",{key:ae,dir:v==="auto"?$ht():v,tabIndex:-1,ref:Z,className:o,"data-sonner-toaster":!0,"data-theme":H,"data-y-position":me,"data-lifted":O&&E.length>1&&!i,"data-x-position":he,style:{"--front-toast-height":`${((be=I[0])==null?void 0:be.height)||0}px`,"--width":`${rgs}px`,"--gap":`${g}px`,...p,...dgs(c,d)},onBlur:pe=>{ie.current&&!pe.currentTarget.contains(pe.relatedTarget)&&(ie.current=!1,ce.current&&(ce.current.focus({preventScroll:!0}),ce.current=null))},onFocus:pe=>{pe.target instanceof HTMLElement&&pe.target.dataset.dismissible==="false"||ie.current||(ie.current=!0,ce.current=pe.relatedTarget)},onMouseEnter:()=>V(!0),onMouseMove:()=>V(!0),onMouseLeave:()=>{G||V(!1)},onDragEnd:()=>V(!1),onPointerDown:pe=>{pe.target instanceof HTMLElement&&pe.target.dataset.dismissible==="false"||$(!0)},onPointerUp:()=>$(!1)},E.filter(pe=>!pe.position&&le===0||pe.position===ae).map((pe,Ce)=>{var Ae,Pe;return Dt.createElement(cgs,{key:pe.id,icons:j,index:Ce,toast:pe,defaultRichColors:h,duration:(Ae=y==null?void 0:y.duration)!=null?Ae:m,className:y==null?void 0:y.className,descriptionClassName:y==null?void 0:y.descriptionClassName,invert:n,visibleToasts:f,closeButton:(Pe=y==null?void 0:y.closeButton)!=null?Pe:l,interacting:G,position:ae,style:y==null?void 0:y.style,unstyled:y==null?void 0:y.unstyled,classNames:y==null?void 0:y.classNames,cancelButtonStyle:y==null?void 0:y.cancelButtonStyle,actionButtonStyle:y==null?void 0:y.actionButtonStyle,removeToast:te,toasts:E.filter(ze=>ze.position==pe.position),heights:I.filter(ze=>ze.position==pe.position),setHeights:D,expandByDefault:i,gap:g,loadingIcon:b,expanded:O,pauseWhenPageIsHidden:C,swipeDirections:s.swipeDirections})})):null}))});const hgs=({...s})=>{const{theme:t="system"}=Oxs();return e.jsx(ugs,{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 mgs=UZe[" useId ".trim().toString()]||(()=>{}),pgs=0;function Og(s){const[t,n]=_.useState(mgs());return Mx(()=>{n(r=>r??String(pgs++))},[s]),t?`radix-${t}`:""}var zFe="focusScope.autoFocusOnMount",BFe="focusScope.autoFocusOnUnmount",Vht={bubbles:!1,cancelable:!0},fgs="FocusScope",_re=_.forwardRef((s,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:a,onUnmountAutoFocus:i,...l}=s,[o,c]=_.useState(null),d=wx(a),u=wx(i),h=_.useRef(null),m=Qo(t,y=>c(y)),p=_.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;_.useEffect(()=>{if(r){let y=function(j){if(p.paused||!o)return;const S=j.target;o.contains(S)?h.current=S:UT(h.current,{select:!0})},v=function(j){if(p.paused||!o)return;const S=j.relatedTarget;S!==null&&(o.contains(S)||UT(h.current,{select:!0}))},g=function(j){if(document.activeElement===document.body)for(const C of j)C.removedNodes.length>0&&UT(o)};document.addEventListener("focusin",y),document.addEventListener("focusout",v);const b=new MutationObserver(g);return o&&b.observe(o,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",y),document.removeEventListener("focusout",v),b.disconnect()}}},[r,o,p.paused]),_.useEffect(()=>{if(o){Ght.add(p);const y=document.activeElement;if(!o.contains(y)){const g=new CustomEvent(zFe,Vht);o.addEventListener(zFe,d),o.dispatchEvent(g),g.defaultPrevented||(xgs(_gs(xMt(o)),{select:!0}),document.activeElement===y&&UT(o))}return()=>{o.removeEventListener(zFe,d),setTimeout(()=>{const g=new CustomEvent(BFe,Vht);o.addEventListener(BFe,u),o.dispatchEvent(g),g.defaultPrevented||UT(y??document.body,{select:!0}),o.removeEventListener(BFe,u),Ght.remove(p)},0)}}},[o,d,u,p]);const f=_.useCallback(y=>{if(!n&&!r||p.paused)return;const v=y.key==="Tab"&&!y.altKey&&!y.ctrlKey&&!y.metaKey,g=document.activeElement;if(v&&g){const b=y.currentTarget,[j,S]=ggs(b);j&&S?!y.shiftKey&&g===S?(y.preventDefault(),n&&UT(j,{select:!0})):y.shiftKey&&g===j&&(y.preventDefault(),n&&UT(S,{select:!0})):g===b&&y.preventDefault()}},[n,r,p.paused]);return e.jsx(ii.div,{tabIndex:-1,...l,ref:m,onKeyDown:f})});_re.displayName=fgs;function xgs(s,{select:t=!1}={}){const n=document.activeElement;for(const r of s)if(UT(r,{select:t}),document.activeElement!==n)return}function ggs(s){const t=xMt(s),n=Hht(t,s),r=Hht(t.reverse(),s);return[n,r]}function xMt(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 Hht(s,t){for(const n of s)if(!ygs(n,{upTo:t}))return n}function ygs(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 vgs(s){return s instanceof HTMLInputElement&&"select"in s}function UT(s,{select:t=!1}={}){if(s&&s.focus){const n=document.activeElement;s.focus({preventScroll:!0}),s!==n&&vgs(s)&&t&&s.select()}}var Ght=bgs();function bgs(){let s=[];return{add(t){const n=s[0];t!==n&&(n==null||n.pause()),s=Wht(s,t),s.unshift(t)},remove(t){var n;s=Wht(s,t),(n=s[0])==null||n.resume()}}}function Wht(s,t){const n=[...s],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function _gs(s){return s.filter(t=>t.tagName!=="A")}var UFe=0;function NMe(){_.useEffect(()=>{const s=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",s[0]??Kht()),document.body.insertAdjacentElement("beforeend",s[1]??Kht()),UFe++,()=>{UFe===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),UFe--}},[])}function Kht(){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 _4=function(){return _4=Object.assign||function(t){for(var n,r=1,a=arguments.length;r"u")return Ogs;var t=zgs(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])}},Ugs=bMt(),y$="data-scroll-locked",qgs=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(jgs,` { overflow: hidden `).concat(r,`; padding-right: `).concat(o,"px ").concat(r,`; } body[`).concat(y$,`] { 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(m4e,` { right: `).concat(o,"px ").concat(r,`; } .`).concat(p4e,` { margin-right: `).concat(o,"px ").concat(r,`; } .`).concat(m4e," .").concat(m4e,` { right: 0 `).concat(r,`; } .`).concat(p4e," .").concat(p4e,` { margin-right: 0 `).concat(r,`; } body[`).concat(y$,`] { `).concat(Ngs,": ").concat(o,`px; } `)},Zht=function(){var s=parseInt(document.body.getAttribute(y$)||"0",10);return isFinite(s)?s:0},$gs=function(){_.useEffect(function(){return document.body.setAttribute(y$,(Zht()+1).toString()),function(){var s=Zht()-1;s<=0?document.body.removeAttribute(y$):document.body.setAttribute(y$,s.toString())}},[])},Vgs=function(s){var t=s.noRelative,n=s.noImportant,r=s.gapMode,a=r===void 0?"margin":r;$gs();var i=_.useMemo(function(){return Bgs(a)},[a]);return _.createElement(Ugs,{styles:qgs(i,!t,a,n?"":"!important")})},Oqe=!1;if(typeof window<"u")try{var Qoe=Object.defineProperty({},"passive",{get:function(){return Oqe=!0,!0}});window.addEventListener("test",Qoe,Qoe),window.removeEventListener("test",Qoe,Qoe)}catch{Oqe=!1}var dB=Oqe?{passive:!1}:!1,Hgs=function(s){return s.tagName==="TEXTAREA"},_Mt=function(s,t){if(!(s instanceof Element))return!1;var n=window.getComputedStyle(s);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!Hgs(s)&&n[t]==="visible")},Ggs=function(s){return _Mt(s,"overflowY")},Wgs=function(s){return _Mt(s,"overflowX")},Xht=function(s,t){var n=t.ownerDocument,r=t;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var a=wMt(s,r);if(a){var i=jMt(s,r),l=i[1],o=i[2];if(l>o)return!0}r=r.parentNode}while(r&&r!==n.body);return!1},Kgs=function(s){var t=s.scrollTop,n=s.scrollHeight,r=s.clientHeight;return[t,n,r]},Ygs=function(s){var t=s.scrollLeft,n=s.scrollWidth,r=s.clientWidth;return[t,n,r]},wMt=function(s,t){return s==="v"?Ggs(t):Wgs(t)},jMt=function(s,t){return s==="v"?Kgs(t):Ygs(t)},Zgs=function(s,t){return s==="h"&&t==="rtl"?-1:1},Xgs=function(s,t,n,r,a){var i=Zgs(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=jMt(s,o),f=p[0],y=p[1],v=p[2],g=y-v-i*f;(f||g)&&wMt(s,o)&&(h+=g,m+=f);var b=o.parentNode;o=b&&b.nodeType===Node.DOCUMENT_FRAGMENT_NODE?b.host:b}while(!c&&o!==document.body||c&&(t.contains(o)||t===o));return(u&&(Math.abs(h)<1||!a)||!u&&(Math.abs(m)<1||!a))&&(d=!0),d},Joe=function(s){return"changedTouches"in s?[s.changedTouches[0].clientX,s.changedTouches[0].clientY]:[0,0]},Qht=function(s){return[s.deltaX,s.deltaY]},Jht=function(s){return s&&"current"in s?s.current:s},Qgs=function(s,t){return s[0]===t[0]&&s[1]===t[1]},Jgs=function(s){return` .block-interactivity-`.concat(s,` {pointer-events: none;} .allow-interactivity-`).concat(s,` {pointer-events: all;} `)},e0s=0,uB=[];function t0s(s){var t=_.useRef([]),n=_.useRef([0,0]),r=_.useRef(),a=_.useState(e0s++)[0],i=_.useState(bMt)[0],l=_.useRef(s);_.useEffect(function(){l.current=s},[s]),_.useEffect(function(){if(s.inert){document.body.classList.add("block-interactivity-".concat(a));var y=wgs([s.lockRef.current],(s.shards||[]).map(Jht),!0).filter(Boolean);return y.forEach(function(v){return v.classList.add("allow-interactivity-".concat(a))}),function(){document.body.classList.remove("block-interactivity-".concat(a)),y.forEach(function(v){return v.classList.remove("allow-interactivity-".concat(a))})}}},[s.inert,s.lockRef.current,s.shards]);var o=_.useCallback(function(y,v){if("touches"in y&&y.touches.length===2||y.type==="wheel"&&y.ctrlKey)return!l.current.allowPinchZoom;var g=Joe(y),b=n.current,j="deltaX"in y?y.deltaX:b[0]-g[0],S="deltaY"in y?y.deltaY:b[1]-g[1],C,E=y.target,P=Math.abs(j)>Math.abs(S)?"h":"v";if("touches"in y&&P==="h"&&E.type==="range")return!1;var M=Xht(P,E);if(!M)return!0;if(M?C=P:(C=P==="v"?"h":"v",M=Xht(P,E)),!M)return!1;if(!r.current&&"changedTouches"in y&&(j||S)&&(r.current=C),!C)return!0;var I=r.current||C;return Xgs(I,v,y,I==="h"?j:S,!0)},[]),c=_.useCallback(function(y){var v=y;if(!(!uB.length||uB[uB.length-1]!==i)){var g="deltaY"in v?Qht(v):Joe(v),b=t.current.filter(function(C){return C.name===v.type&&(C.target===v.target||v.target===C.shadowParent)&&Qgs(C.delta,g)})[0];if(b&&b.should){v.cancelable&&v.preventDefault();return}if(!b){var j=(l.current.shards||[]).map(Jht).filter(Boolean).filter(function(C){return C.contains(v.target)}),S=j.length>0?o(v,j[0]):!l.current.noIsolation;S&&v.cancelable&&v.preventDefault()}}},[]),d=_.useCallback(function(y,v,g,b){var j={name:y,delta:v,target:g,should:b,shadowParent:s0s(g)};t.current.push(j),setTimeout(function(){t.current=t.current.filter(function(S){return S!==j})},1)},[]),u=_.useCallback(function(y){n.current=Joe(y),r.current=void 0},[]),h=_.useCallback(function(y){d(y.type,Qht(y),y.target,o(y,s.lockRef.current))},[]),m=_.useCallback(function(y){d(y.type,Joe(y),y.target,o(y,s.lockRef.current))},[]);_.useEffect(function(){return uB.push(i),s.setCallbacks({onScrollCapture:h,onWheelCapture:h,onTouchMoveCapture:m}),document.addEventListener("wheel",c,dB),document.addEventListener("touchmove",c,dB),document.addEventListener("touchstart",u,dB),function(){uB=uB.filter(function(y){return y!==i}),document.removeEventListener("wheel",c,dB),document.removeEventListener("touchmove",c,dB),document.removeEventListener("touchstart",u,dB)}},[]);var p=s.removeScrollBar,f=s.inert;return _.createElement(_.Fragment,null,f?_.createElement(i,{styles:Jgs(a)}):null,p?_.createElement(Vgs,{noRelative:s.noRelative,gapMode:s.gapMode}):null)}function s0s(s){for(var t=null;s!==null;)s instanceof ShadowRoot&&(t=s.host,s=s.host),s=s.parentNode;return t}const n0s=Mgs(vMt,t0s);var wre=_.forwardRef(function(s,t){return _.createElement(kMe,_4({},s,{ref:t,sideCar:n0s}))});wre.classNames=kMe.classNames;var r0s=function(s){if(typeof document>"u")return null;var t=Array.isArray(s)?s[0]:s;return t.ownerDocument.body},hB=new WeakMap,ele=new WeakMap,tle={},HFe=0,NMt=function(s){return s&&(s.host||NMt(s.parentNode))},a0s=function(s,t){return t.map(function(n){if(s.contains(n))return n;var r=NMt(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})},i0s=function(s,t,n,r){var a=a0s(t,Array.isArray(s)?s:[s]);tle[n]||(tle[n]=new WeakMap);var i=tle[n],l=[],o=new Set,c=new Set(a),d=function(h){!h||o.has(h)||(o.add(h),d(h.parentNode))};a.forEach(d);var u=function(h){!h||c.has(h)||Array.prototype.forEach.call(h.children,function(m){if(o.has(m))u(m);else try{var p=m.getAttribute(r),f=p!==null&&p!=="false",y=(hB.get(m)||0)+1,v=(i.get(m)||0)+1;hB.set(m,y),i.set(m,v),l.push(m),y===1&&f&&ele.set(m,!0),v===1&&m.setAttribute(n,"true"),f||m.setAttribute(r,"true")}catch(g){console.error("aria-hidden: cannot operate on ",m,g)}})};return u(t),o.clear(),HFe++,function(){l.forEach(function(h){var m=hB.get(h)-1,p=i.get(h)-1;hB.set(h,m),i.set(h,p),m||(ele.has(h)||h.removeAttribute(r),ele.delete(h)),p||h.removeAttribute(n)}),HFe--,HFe||(hB=new WeakMap,hB=new WeakMap,ele=new WeakMap,tle={})}},SMe=function(s,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(s)?s:[s]),a=r0s(s);return a?(r.push.apply(r,Array.from(a.querySelectorAll("[aria-live]"))),i0s(r,a,n,"aria-hidden")):function(){return null}},CMe="Dialog",[kMt,SMt]=af(CMe),[o0s,LS]=kMt(CMe),CMt=s=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:a,onOpenChange:i,modal:l=!0}=s,o=_.useRef(null),c=_.useRef(null),[d,u]=Ug({prop:r,defaultProp:a??!1,onChange:i,caller:CMe});return e.jsx(o0s,{scope:t,triggerRef:o,contentRef:c,contentId:Og(),titleId:Og(),descriptionId:Og(),open:d,onOpenChange:u,onOpenToggle:_.useCallback(()=>u(h=>!h),[u]),modal:l,children:n})};CMt.displayName=CMe;var AMt="DialogTrigger",EMt=_.forwardRef((s,t)=>{const{__scopeDialog:n,...r}=s,a=LS(AMt,n),i=Qo(t,a.triggerRef);return e.jsx(ii.button,{type:"button","aria-haspopup":"dialog","aria-expanded":a.open,"aria-controls":a.contentId,"data-state":UXe(a.open),...r,ref:i,onClick:wa(s.onClick,a.onOpenToggle)})});EMt.displayName=AMt;var zXe="DialogPortal",[l0s,TMt]=kMt(zXe,{forceMount:void 0}),MMt=s=>{const{__scopeDialog:t,forceMount:n,children:r,container:a}=s,i=LS(zXe,t);return e.jsx(l0s,{scope:t,forceMount:n,children:_.Children.map(r,l=>e.jsx(pg,{present:n||i.open,children:e.jsx(YG,{asChild:!0,container:a,children:l})}))})};MMt.displayName=zXe;var R3e="DialogOverlay",PMt=_.forwardRef((s,t)=>{const n=TMt(R3e,s.__scopeDialog),{forceMount:r=n.forceMount,...a}=s,i=LS(R3e,s.__scopeDialog);return i.modal?e.jsx(pg,{present:r||i.open,children:e.jsx(d0s,{...a,ref:t})}):null});PMt.displayName=R3e;var c0s=CP("DialogOverlay.RemoveScroll"),d0s=_.forwardRef((s,t)=>{const{__scopeDialog:n,...r}=s,a=LS(R3e,n);return e.jsx(wre,{as:c0s,allowPinchZoom:!0,shards:[a.contentRef],children:e.jsx(ii.div,{"data-state":UXe(a.open),...r,ref:t,style:{pointerEvents:"auto",...r.style}})})}),$7="DialogContent",LMt=_.forwardRef((s,t)=>{const n=TMt($7,s.__scopeDialog),{forceMount:r=n.forceMount,...a}=s,i=LS($7,s.__scopeDialog);return e.jsx(pg,{present:r||i.open,children:i.modal?e.jsx(u0s,{...a,ref:t}):e.jsx(h0s,{...a,ref:t})})});LMt.displayName=$7;var u0s=_.forwardRef((s,t)=>{const n=LS($7,s.__scopeDialog),r=_.useRef(null),a=Qo(t,n.contentRef,r);return _.useEffect(()=>{const i=r.current;if(i)return SMe(i)},[]),e.jsx(IMt,{...s,ref:a,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:wa(s.onCloseAutoFocus,i=>{var l;i.preventDefault(),(l=n.triggerRef.current)==null||l.focus()}),onPointerDownOutside:wa(s.onPointerDownOutside,i=>{const l=i.detail.originalEvent,o=l.button===0&&l.ctrlKey===!0;(l.button===2||o)&&i.preventDefault()}),onFocusOutside:wa(s.onFocusOutside,i=>i.preventDefault())})}),h0s=_.forwardRef((s,t)=>{const n=LS($7,s.__scopeDialog),r=_.useRef(!1),a=_.useRef(!1);return e.jsx(IMt,{...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()}})}),IMt=_.forwardRef((s,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:a,onCloseAutoFocus:i,...l}=s,o=LS($7,n),c=_.useRef(null),d=Qo(t,c);return NMe(),e.jsxs(e.Fragment,{children:[e.jsx(_re,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:a,onUnmountAutoFocus:i,children:e.jsx(rL,{role:"dialog",id:o.contentId,"aria-describedby":o.descriptionId,"aria-labelledby":o.titleId,"data-state":UXe(o.open),...l,ref:d,onDismiss:()=>o.onOpenChange(!1)})}),e.jsxs(e.Fragment,{children:[e.jsx(p0s,{titleId:o.titleId}),e.jsx(x0s,{contentRef:c,descriptionId:o.descriptionId})]})]})}),BXe="DialogTitle",DMt=_.forwardRef((s,t)=>{const{__scopeDialog:n,...r}=s,a=LS(BXe,n);return e.jsx(ii.h2,{id:a.titleId,...r,ref:t})});DMt.displayName=BXe;var RMt="DialogDescription",FMt=_.forwardRef((s,t)=>{const{__scopeDialog:n,...r}=s,a=LS(RMt,n);return e.jsx(ii.p,{id:a.descriptionId,...r,ref:t})});FMt.displayName=RMt;var OMt="DialogClose",zMt=_.forwardRef((s,t)=>{const{__scopeDialog:n,...r}=s,a=LS(OMt,n);return e.jsx(ii.button,{type:"button",...r,ref:t,onClick:wa(s.onClick,()=>a.onOpenChange(!1))})});zMt.displayName=OMt;function UXe(s){return s?"open":"closed"}var BMt="DialogTitleWarning",[m0s,UMt]=ofs(BMt,{contentName:$7,titleName:BXe,docsSlug:"dialog"}),p0s=({titleId:s})=>{const t=UMt(BMt),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 _.useEffect(()=>{s&&(document.getElementById(s)||console.error(n))},[n,s]),null},f0s="DialogDescriptionWarning",x0s=({contentRef:s,descriptionId:t})=>{const r=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${UMt(f0s).contentName}}.`;return _.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},AMe=CMt,qXe=EMt,EMe=MMt,XG=PMt,QG=LMt,jre=DMt,Nre=FMt,kre=zMt,qMt="AlertDialog",[g0s,abr]=af(qMt,[SMt]),LE=SMt(),$Mt=s=>{const{__scopeAlertDialog:t,...n}=s,r=LE(t);return e.jsx(AMe,{...r,...n,modal:!0})};$Mt.displayName=qMt;var y0s="AlertDialogTrigger",VMt=_.forwardRef((s,t)=>{const{__scopeAlertDialog:n,...r}=s,a=LE(n);return e.jsx(qXe,{...a,...r,ref:t})});VMt.displayName=y0s;var v0s="AlertDialogPortal",HMt=s=>{const{__scopeAlertDialog:t,...n}=s,r=LE(t);return e.jsx(EMe,{...r,...n})};HMt.displayName=v0s;var b0s="AlertDialogOverlay",GMt=_.forwardRef((s,t)=>{const{__scopeAlertDialog:n,...r}=s,a=LE(n);return e.jsx(XG,{...a,...r,ref:t})});GMt.displayName=b0s;var v$="AlertDialogContent",[_0s,w0s]=g0s(v$),j0s=L6t("AlertDialogContent"),WMt=_.forwardRef((s,t)=>{const{__scopeAlertDialog:n,children:r,...a}=s,i=LE(n),l=_.useRef(null),o=Qo(t,l),c=_.useRef(null);return e.jsx(m0s,{contentName:v$,titleName:KMt,docsSlug:"alert-dialog",children:e.jsx(_0s,{scope:n,cancelRef:c,children:e.jsxs(QG,{role:"alertdialog",...i,...a,ref:o,onOpenAutoFocus:wa(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(j0s,{children:r}),e.jsx(k0s,{contentRef:l})]})})})});WMt.displayName=v$;var KMt="AlertDialogTitle",YMt=_.forwardRef((s,t)=>{const{__scopeAlertDialog:n,...r}=s,a=LE(n);return e.jsx(jre,{...a,...r,ref:t})});YMt.displayName=KMt;var ZMt="AlertDialogDescription",XMt=_.forwardRef((s,t)=>{const{__scopeAlertDialog:n,...r}=s,a=LE(n);return e.jsx(Nre,{...a,...r,ref:t})});XMt.displayName=ZMt;var N0s="AlertDialogAction",QMt=_.forwardRef((s,t)=>{const{__scopeAlertDialog:n,...r}=s,a=LE(n);return e.jsx(kre,{...a,...r,ref:t})});QMt.displayName=N0s;var JMt="AlertDialogCancel",ePt=_.forwardRef((s,t)=>{const{__scopeAlertDialog:n,...r}=s,{cancelRef:a}=w0s(JMt,n),i=LE(n),l=Qo(t,a);return e.jsx(kre,{...i,...r,ref:l})});ePt.displayName=JMt;var k0s=({contentRef:s})=>{const t=`\`${v$}\` requires a description for the component to be accessible for screen reader users. You can add a description to the \`${v$}\` by passing a \`${ZMt}\` 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 \`${v$}\`. 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 _.useEffect(()=>{var r;document.getElementById((r=s.current)==null?void 0:r.getAttribute("aria-describedby"))||console.warn(t)},[t,s]),null},S0s=$Mt,C0s=VMt,A0s=HMt,tPt=GMt,sPt=WMt,nPt=QMt,rPt=ePt,aPt=YMt,iPt=XMt;const vH=F9("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"}}),B=_.forwardRef(({className:s,variant:t,size:n,asChild:r=!1,...a},i)=>{const l=r?LXe:"button";return e.jsx(l,{className:At(vH({variant:t,size:n,className:s})),ref:i,...a})});B.displayName="Button";const Kl=S0s,jx=C0s,E0s=A0s,oPt=_.forwardRef(({className:s,...t},n)=>e.jsx(tPt,{className:At("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}));oPt.displayName=tPt.displayName;const Ol=_.forwardRef(({className:s,...t},n)=>e.jsxs(E0s,{children:[e.jsx(oPt,{}),e.jsx(sPt,{ref:n,className:At("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})]}));Ol.displayName=sPt.displayName;const zl=({className:s,...t})=>e.jsx("div",{className:At("flex flex-col space-y-2 text-center sm:text-left",s),...t});zl.displayName="AlertDialogHeader";const Bl=({className:s,...t})=>e.jsx("div",{className:At("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",s),...t});Bl.displayName="AlertDialogFooter";const Ul=_.forwardRef(({className:s,...t},n)=>e.jsx(aPt,{ref:n,className:At("text-lg font-semibold",s),...t}));Ul.displayName=aPt.displayName;const ql=_.forwardRef(({className:s,...t},n)=>e.jsx(iPt,{ref:n,className:At("text-sm text-muted-foreground",s),...t}));ql.displayName=iPt.displayName;const Ml=_.forwardRef(({className:s,...t},n)=>e.jsx(nPt,{ref:n,className:At(vH(),s),...t}));Ml.displayName=nPt.displayName;const $l=_.forwardRef(({className:s,...t},n)=>e.jsx(rPt,{ref:n,className:At(vH({variant:"outline"}),"mt-2 sm:mt-0",s),...t}));$l.displayName=rPt.displayName;let F3e=null;const T0s=["delete","remove","revoke","cannot be undone","permanently"];function Xi(s,t={}){const n=typeof s=="string"?{description:s,...t}:s,r=`${n.title??""} ${n.description??""}`.toLowerCase(),a=n.destructive??T0s.some(i=>r.includes(i));return new Promise(i=>{if(!F3e){i(window.confirm(n.description??n.title??"Are you sure?"));return}F3e({...n,destructive:a,resolve:i})})}function M0s(){const[s,t]=_.useState(null);_.useEffect(()=>(F3e=a=>t(a),()=>{F3e=null}),[]);const n=a=>{s==null||s.resolve(a),t(null)},r=!!(s!=null&&s.destructive);return e.jsx(Kl,{open:!!s,onOpenChange:a=>!a&&n(!1),children:e.jsxs(Ol,{className:"sm:max-w-md",children:[e.jsx(zl,{children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:At("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(xl,{className:"h-5 w-5"})}),e.jsxs("div",{className:"space-y-1.5 text-left",children:[e.jsx(Ul,{children:(s==null?void 0:s.title)??(r?"Are you sure?":"Please confirm")}),(s==null?void 0:s.description)&&e.jsx(ql,{className:"leading-relaxed",children:s.description})]})]})}),e.jsxs(Bl,{className:"gap-2 sm:gap-2",children:[e.jsx($l,{onClick:()=>n(!1),children:(s==null?void 0:s.cancelText)??"Cancel"}),e.jsx(Ml,{onClick:()=>n(!0),className:At(r&&"bg-destructive text-destructive-foreground hover:bg-destructive/90"),children:(s==null?void 0:s.confirmText)??(r?"Delete":"Continue")})]})]})})}const P0s=["top","right","bottom","left"],AP=Math.min,Kw=Math.max,O3e=Math.round,sle=Math.floor,EP=s=>({x:s,y:s}),L0s={left:"right",right:"left",bottom:"top",top:"bottom"},I0s={start:"end",end:"start"};function zqe(s,t,n){return Kw(s,AP(t,n))}function vE(s,t){return typeof s=="function"?s(t):s}function bE(s){return s.split("-")[0]}function JG(s){return s.split("-")[1]}function $Xe(s){return s==="x"?"y":"x"}function VXe(s){return s==="y"?"height":"width"}function TP(s){return["top","bottom"].includes(bE(s))?"y":"x"}function HXe(s){return $Xe(TP(s))}function D0s(s,t,n){n===void 0&&(n=!1);const r=JG(s),a=HXe(s),i=VXe(a);let l=a==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[i]>t.floating[i]&&(l=z3e(l)),[l,z3e(l)]}function R0s(s){const t=z3e(s);return[Bqe(s),t,Bqe(t)]}function Bqe(s){return s.replace(/start|end/g,t=>I0s[t])}function F0s(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 O0s(s,t,n,r){const a=JG(s);let i=F0s(bE(s),n==="start",r);return a&&(i=i.map(l=>l+"-"+a),t&&(i=i.concat(i.map(Bqe)))),i}function z3e(s){return s.replace(/left|right|bottom|top/g,t=>L0s[t])}function z0s(s){return{top:0,right:0,bottom:0,left:0,...s}}function lPt(s){return typeof s!="number"?z0s(s):{top:s,right:s,bottom:s,left:s}}function B3e(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 emt(s,t,n){let{reference:r,floating:a}=s;const i=TP(t),l=HXe(t),o=VXe(l),c=bE(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(JG(t)){case"start":p[l]-=m*(n&&d?-1:1);break;case"end":p[l]+=m*(n&&d?-1:1);break}return p}const B0s=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}=emt(d,r,c),m=r,p={},f=0;for(let y=0;y({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}=vE(s,t)||{};if(d==null)return{};const h=lPt(u),m={x:n,y:r},p=HXe(a),f=VXe(p),y=await l.getDimensions(d),v=p==="y",g=v?"top":"left",b=v?"bottom":"right",j=v?"clientHeight":"clientWidth",S=i.reference[f]+i.reference[p]-m[p]-i.floating[f],C=m[p]-i.reference[p],E=await(l.getOffsetParent==null?void 0:l.getOffsetParent(d));let P=E?E[j]:0;(!P||!await(l.isElement==null?void 0:l.isElement(E)))&&(P=o.floating[j]||i.floating[f]);const M=S/2-C/2,I=P/2-y[f]/2-1,D=AP(h[g],I),O=AP(h[b],I),V=D,G=P-y[f]-O,$=P/2-y[f]/2+M,H=zqe(V,$,G),Y=!c.arrow&&JG(a)!=null&&$!==H&&i.reference[f]/2-($$<=0)){var O,V;const $=(((O=i.flip)==null?void 0:O.index)||0)+1,H=P[$];if(H)return{data:{index:$,overflows:D},reset:{placement:H}};let Y=(V=D.filter(Z=>Z.overflows[0]<=0).sort((Z,ne)=>Z.overflows[1]-ne.overflows[1])[0])==null?void 0:V.placement;if(!Y)switch(p){case"bestFit":{var G;const Z=(G=D.filter(ne=>{if(E){const ce=TP(ne.placement);return ce===b||ce==="y"}return!0}).map(ne=>[ne.placement,ne.overflows.filter(ce=>ce>0).reduce((ce,ie)=>ce+ie,0)]).sort((ne,ce)=>ne[1]-ce[1])[0])==null?void 0:G[0];Z&&(Y=Z);break}case"initialPlacement":Y=o;break}if(a!==Y)return{reset:{placement:Y}}}return{}}}};function tmt(s,t){return{top:s.top-t.height,right:s.right-t.width,bottom:s.bottom-t.height,left:s.left-t.width}}function smt(s){return P0s.some(t=>s[t]>=0)}const $0s=function(s){return s===void 0&&(s={}),{name:"hide",options:s,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...a}=vE(s,t);switch(r){case"referenceHidden":{const i=await Gee(t,{...a,elementContext:"reference"}),l=tmt(i,n.reference);return{data:{referenceHiddenOffsets:l,referenceHidden:smt(l)}}}case"escaped":{const i=await Gee(t,{...a,altBoundary:!0}),l=tmt(i,n.floating);return{data:{escapedOffsets:l,escaped:smt(l)}}}default:return{}}}}};async function V0s(s,t){const{placement:n,platform:r,elements:a}=s,i=await(r.isRTL==null?void 0:r.isRTL(a.floating)),l=bE(n),o=JG(n),c=TP(n)==="y",d=["left","top"].includes(l)?-1:1,u=i&&c?-1:1,h=vE(t,s);let{mainAxis:m,crossAxis:p,alignmentAxis:f}=typeof h=="number"?{mainAxis:h,crossAxis:0,alignmentAxis:null}:{mainAxis:h.mainAxis||0,crossAxis:h.crossAxis||0,alignmentAxis:h.alignmentAxis};return o&&typeof f=="number"&&(p=o==="end"?f*-1:f),c?{x:p*u,y:m*d}:{x:m*d,y:p*u}}const H0s=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 V0s(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}}}}},G0s=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:v=>{let{x:g,y:b}=v;return{x:g,y:b}}},...c}=vE(s,t),d={x:n,y:r},u=await Gee(t,c),h=TP(bE(a)),m=$Xe(h);let p=d[m],f=d[h];if(i){const v=m==="y"?"top":"left",g=m==="y"?"bottom":"right",b=p+u[v],j=p-u[g];p=zqe(b,p,j)}if(l){const v=h==="y"?"top":"left",g=h==="y"?"bottom":"right",b=f+u[v],j=f-u[g];f=zqe(b,f,j)}const y=o.fn({...t,[m]:p,[h]:f});return{...y,data:{x:y.x-n,y:y.y-r,enabled:{[m]:i,[h]:l}}}}}},W0s=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}=vE(s,t),u={x:n,y:r},h=TP(a),m=$Xe(h);let p=u[m],f=u[h];const y=vE(o,t),v=typeof y=="number"?{mainAxis:y,crossAxis:0}:{mainAxis:0,crossAxis:0,...y};if(c){const j=m==="y"?"height":"width",S=i.reference[m]-i.floating[j]+v.mainAxis,C=i.reference[m]+i.reference[j]-v.mainAxis;pC&&(p=C)}if(d){var g,b;const j=m==="y"?"width":"height",S=["top","left"].includes(bE(a)),C=i.reference[h]-i.floating[j]+(S&&((g=l.offset)==null?void 0:g[h])||0)+(S?0:v.crossAxis),E=i.reference[h]+i.reference[j]+(S?0:((b=l.offset)==null?void 0:b[h])||0)-(S?v.crossAxis:0);fE&&(f=E)}return{[m]:p,[h]:f}}}},K0s=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}=vE(s,t),u=await Gee(t,d),h=bE(a),m=JG(a),p=TP(a)==="y",{width:f,height:y}=i.floating;let v,g;h==="top"||h==="bottom"?(v=h,g=m===(await(l.isRTL==null?void 0:l.isRTL(o.floating))?"start":"end")?"left":"right"):(g=h,v=m==="end"?"top":"bottom");const b=y-u.top-u.bottom,j=f-u.left-u.right,S=AP(y-u[v],b),C=AP(f-u[g],j),E=!t.middlewareData.shift;let P=S,M=C;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(M=j),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(P=b),E&&!m){const D=Kw(u.left,0),O=Kw(u.right,0),V=Kw(u.top,0),G=Kw(u.bottom,0);p?M=f-2*(D!==0||O!==0?D+O:Kw(u.left,u.right)):P=y-2*(V!==0||G!==0?V+G:Kw(u.top,u.bottom))}await c({...t,availableWidth:M,availableHeight:P});const I=await l.getDimensions(o.floating);return f!==I.width||y!==I.height?{reset:{rects:!0}}:{}}}};function TMe(){return typeof window<"u"}function eW(s){return cPt(s)?(s.nodeName||"").toLowerCase():"#document"}function yj(s){var t;return(s==null||(t=s.ownerDocument)==null?void 0:t.defaultView)||window}function bC(s){var t;return(t=(cPt(s)?s.ownerDocument:s.document)||window.document)==null?void 0:t.documentElement}function cPt(s){return TMe()?s instanceof Node||s instanceof yj(s).Node:!1}function SS(s){return TMe()?s instanceof Element||s instanceof yj(s).Element:!1}function aC(s){return TMe()?s instanceof HTMLElement||s instanceof yj(s).HTMLElement:!1}function nmt(s){return!TMe()||typeof ShadowRoot>"u"?!1:s instanceof ShadowRoot||s instanceof yj(s).ShadowRoot}function Sre(s){const{overflow:t,overflowX:n,overflowY:r,display:a}=CS(s);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!["inline","contents"].includes(a)}function Y0s(s){return["table","td","th"].includes(eW(s))}function MMe(s){return[":popover-open",":modal"].some(t=>{try{return s.matches(t)}catch{return!1}})}function GXe(s){const t=WXe(),n=SS(s)?CS(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 Z0s(s){let t=MP(s);for(;aC(t)&&!bH(t);){if(GXe(t))return t;if(MMe(t))return null;t=MP(t)}return null}function WXe(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function bH(s){return["html","body","#document"].includes(eW(s))}function CS(s){return yj(s).getComputedStyle(s)}function PMe(s){return SS(s)?{scrollLeft:s.scrollLeft,scrollTop:s.scrollTop}:{scrollLeft:s.scrollX,scrollTop:s.scrollY}}function MP(s){if(eW(s)==="html")return s;const t=s.assignedSlot||s.parentNode||nmt(s)&&s.host||bC(s);return nmt(t)?t.host:t}function dPt(s){const t=MP(s);return bH(t)?s.ownerDocument?s.ownerDocument.body:s.body:aC(t)&&Sre(t)?t:dPt(t)}function Wee(s,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const a=dPt(s),i=a===((r=s.ownerDocument)==null?void 0:r.body),l=yj(a);if(i){const o=Uqe(l);return t.concat(l,l.visualViewport||[],Sre(a)?a:[],o&&n?Wee(o):[])}return t.concat(a,Wee(a,[],n))}function Uqe(s){return s.parent&&Object.getPrototypeOf(s.parent)?s.frameElement:null}function uPt(s){const t=CS(s);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const a=aC(s),i=a?s.offsetWidth:n,l=a?s.offsetHeight:r,o=O3e(n)!==i||O3e(r)!==l;return o&&(n=i,r=l),{width:n,height:r,$:o}}function KXe(s){return SS(s)?s:s.contextElement}function b$(s){const t=KXe(s);if(!aC(t))return EP(1);const n=t.getBoundingClientRect(),{width:r,height:a,$:i}=uPt(t);let l=(i?O3e(n.width):n.width)/r,o=(i?O3e(n.height):n.height)/a;return(!l||!Number.isFinite(l))&&(l=1),(!o||!Number.isFinite(o))&&(o=1),{x:l,y:o}}const X0s=EP(0);function hPt(s){const t=yj(s);return!WXe()||!t.visualViewport?X0s:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function Q0s(s,t,n){return t===void 0&&(t=!1),!n||t&&n!==yj(s)?!1:t}function V7(s,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const a=s.getBoundingClientRect(),i=KXe(s);let l=EP(1);t&&(r?SS(r)&&(l=b$(r)):l=b$(s));const o=Q0s(i,n,r)?hPt(i):EP(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=yj(i),p=r&&SS(r)?yj(r):r;let f=m,y=Uqe(f);for(;y&&r&&p!==f;){const v=b$(y),g=y.getBoundingClientRect(),b=CS(y),j=g.left+(y.clientLeft+parseFloat(b.paddingLeft))*v.x,S=g.top+(y.clientTop+parseFloat(b.paddingTop))*v.y;c*=v.x,d*=v.y,u*=v.x,h*=v.y,c+=j,d+=S,f=yj(y),y=Uqe(f)}}return B3e({width:u,height:h,x:c,y:d})}function J0s(s){let{elements:t,rect:n,offsetParent:r,strategy:a}=s;const i=a==="fixed",l=bC(r),o=t?MMe(t.floating):!1;if(r===l||o&&i)return n;let c={scrollLeft:0,scrollTop:0},d=EP(1);const u=EP(0),h=aC(r);if((h||!h&&!i)&&((eW(r)!=="body"||Sre(l))&&(c=PMe(r)),aC(r))){const m=V7(r);d=b$(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 eys(s){return Array.from(s.getClientRects())}function qqe(s,t){const n=PMe(s).scrollLeft;return t?t.left+n:V7(bC(s)).left+n}function tys(s){const t=bC(s),n=PMe(s),r=s.ownerDocument.body,a=Kw(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),i=Kw(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let l=-n.scrollLeft+qqe(s);const o=-n.scrollTop;return CS(r).direction==="rtl"&&(l+=Kw(t.clientWidth,r.clientWidth)-a),{width:a,height:i,x:l,y:o}}function sys(s,t){const n=yj(s),r=bC(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=WXe();(!d||d&&t==="fixed")&&(o=a.offsetLeft,c=a.offsetTop)}return{width:i,height:l,x:o,y:c}}function nys(s,t){const n=V7(s,!0,t==="fixed"),r=n.top+s.clientTop,a=n.left+s.clientLeft,i=aC(s)?b$(s):EP(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 rmt(s,t,n){let r;if(t==="viewport")r=sys(s,n);else if(t==="document")r=tys(bC(s));else if(SS(t))r=nys(t,n);else{const a=hPt(s);r={...t,x:t.x-a.x,y:t.y-a.y}}return B3e(r)}function mPt(s,t){const n=MP(s);return n===t||!SS(n)||bH(n)?!1:CS(n).position==="fixed"||mPt(n,t)}function rys(s,t){const n=t.get(s);if(n)return n;let r=Wee(s,[],!1).filter(o=>SS(o)&&eW(o)!=="body"),a=null;const i=CS(s).position==="fixed";let l=i?MP(s):s;for(;SS(l)&&!bH(l);){const o=CS(l),c=GXe(l);!c&&o.position==="fixed"&&(a=null),(i?!c&&!a:!c&&o.position==="static"&&!!a&&["absolute","fixed"].includes(a.position)||Sre(l)&&!c&&mPt(s,l))?r=r.filter(u=>u!==l):a=o,l=MP(l)}return t.set(s,r),r}function ays(s){let{element:t,boundary:n,rootBoundary:r,strategy:a}=s;const l=[...n==="clippingAncestors"?MMe(t)?[]:rys(t,this._c):[].concat(n),r],o=l[0],c=l.reduce((d,u)=>{const h=rmt(t,u,a);return d.top=Kw(h.top,d.top),d.right=AP(h.right,d.right),d.bottom=AP(h.bottom,d.bottom),d.left=Kw(h.left,d.left),d},rmt(t,o,a));return{width:c.right-c.left,height:c.bottom-c.top,x:c.left,y:c.top}}function iys(s){const{width:t,height:n}=uPt(s);return{width:t,height:n}}function oys(s,t,n){const r=aC(t),a=bC(t),i=n==="fixed",l=V7(s,!0,i,t);let o={scrollLeft:0,scrollTop:0};const c=EP(0);if(r||!r&&!i)if((eW(t)!=="body"||Sre(a))&&(o=PMe(t)),r){const p=V7(t,!0,i,t);c.x=p.x+t.clientLeft,c.y=p.y+t.clientTop}else a&&(c.x=qqe(a));let d=0,u=0;if(a&&!r&&!i){const p=a.getBoundingClientRect();u=p.top+o.scrollTop,d=p.left+o.scrollLeft-qqe(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 GFe(s){return CS(s).position==="static"}function amt(s,t){if(!aC(s)||CS(s).position==="fixed")return null;if(t)return t(s);let n=s.offsetParent;return bC(s)===n&&(n=n.ownerDocument.body),n}function pPt(s,t){const n=yj(s);if(MMe(s))return n;if(!aC(s)){let a=MP(s);for(;a&&!bH(a);){if(SS(a)&&!GFe(a))return a;a=MP(a)}return n}let r=amt(s,t);for(;r&&Y0s(r)&&GFe(r);)r=amt(r,t);return r&&bH(r)&&GFe(r)&&!GXe(r)?n:r||Z0s(s)||n}const lys=async function(s){const t=this.getOffsetParent||pPt,n=this.getDimensions,r=await n(s.floating);return{reference:oys(s.reference,await t(s.floating),s.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function cys(s){return CS(s).direction==="rtl"}const dys={convertOffsetParentRelativeRectToViewportRelativeRect:J0s,getDocumentElement:bC,getClippingRect:ays,getOffsetParent:pPt,getElementRects:lys,getClientRects:eys,getDimensions:iys,getScale:b$,isElement:SS,isRTL:cys};function uys(s,t){let n=null,r;const a=bC(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=sle(u),f=sle(a.clientWidth-(d+h)),y=sle(a.clientHeight-(u+m)),v=sle(d),b={rootMargin:-p+"px "+-f+"px "+-y+"px "+-v+"px",threshold:Kw(0,AP(1,c))||1};let j=!0;function S(C){const E=C[0].intersectionRatio;if(E!==c){if(!j)return l();E?l(!1,E):r=setTimeout(()=>{l(!1,1e-7)},1e3)}j=!1}try{n=new IntersectionObserver(S,{...b,root:a.ownerDocument})}catch{n=new IntersectionObserver(S,b)}n.observe(s)}return l(!0),i}function hys(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=KXe(s),u=a||i?[...d?Wee(d):[],...Wee(t)]:[];u.forEach(g=>{a&&g.addEventListener("scroll",n,{passive:!0}),i&&g.addEventListener("resize",n)});const h=d&&o?uys(d,n):null;let m=-1,p=null;l&&(p=new ResizeObserver(g=>{let[b]=g;b&&b.target===d&&p&&(p.unobserve(t),cancelAnimationFrame(m),m=requestAnimationFrame(()=>{var j;(j=p)==null||j.observe(t)})),n()}),d&&!c&&p.observe(d),p.observe(t));let f,y=c?V7(s):null;c&&v();function v(){const g=V7(s);y&&(g.x!==y.x||g.y!==y.y||g.width!==y.width||g.height!==y.height)&&n(),y=g,f=requestAnimationFrame(v)}return n(),()=>{var g;u.forEach(b=>{a&&b.removeEventListener("scroll",n),i&&b.removeEventListener("resize",n)}),h==null||h(),(g=p)==null||g.disconnect(),p=null,c&&cancelAnimationFrame(f)}}const mys=H0s,pys=G0s,fys=q0s,xys=K0s,gys=$0s,imt=U0s,yys=W0s,vys=(s,t,n)=>{const r=new Map,a={platform:dys,...n},i={...a.platform,_c:r};return B0s(s,t,{...a,platform:i})};var f4e=typeof document<"u"?_.useLayoutEffect:_.useEffect;function U3e(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(!U3e(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)&&!U3e(s[i],t[i]))return!1}return!0}return s!==s&&t!==t}function fPt(s){return typeof window>"u"?1:(s.ownerDocument.defaultView||window).devicePixelRatio||1}function omt(s,t){const n=fPt(s);return Math.round(t*n)/n}function WFe(s){const t=_.useRef(s);return f4e(()=>{t.current=s}),t}function bys(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]=_.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[m,p]=_.useState(r);U3e(m,r)||p(r);const[f,y]=_.useState(null),[v,g]=_.useState(null),b=_.useCallback(ne=>{ne!==E.current&&(E.current=ne,y(ne))},[]),j=_.useCallback(ne=>{ne!==P.current&&(P.current=ne,g(ne))},[]),S=i||f,C=l||v,E=_.useRef(null),P=_.useRef(null),M=_.useRef(u),I=c!=null,D=WFe(c),O=WFe(a),V=WFe(d),G=_.useCallback(()=>{if(!E.current||!P.current)return;const ne={placement:t,strategy:n,middleware:m};O.current&&(ne.platform=O.current),vys(E.current,P.current,ne).then(ce=>{const ie={...ce,isPositioned:V.current!==!1};$.current&&!U3e(M.current,ie)&&(M.current=ie,mv.flushSync(()=>{h(ie)}))})},[m,t,n,O,V]);f4e(()=>{d===!1&&M.current.isPositioned&&(M.current.isPositioned=!1,h(ne=>({...ne,isPositioned:!1})))},[d]);const $=_.useRef(!1);f4e(()=>($.current=!0,()=>{$.current=!1}),[]),f4e(()=>{if(S&&(E.current=S),C&&(P.current=C),S&&C){if(D.current)return D.current(S,C,G);G()}},[S,C,G,D,I]);const H=_.useMemo(()=>({reference:E,floating:P,setReference:b,setFloating:j}),[b,j]),Y=_.useMemo(()=>({reference:S,floating:C}),[S,C]),Z=_.useMemo(()=>{const ne={position:n,left:0,top:0};if(!Y.floating)return ne;const ce=omt(Y.floating,u.x),ie=omt(Y.floating,u.y);return o?{...ne,transform:"translate("+ce+"px, "+ie+"px)",...fPt(Y.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:ce,top:ie}},[n,o,Y.floating,u.x,u.y]);return _.useMemo(()=>({...u,update:G,refs:H,elements:Y,floatingStyles:Z}),[u,G,H,Y,Z])}const _ys=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?imt({element:r.current,padding:a}).fn(n):{}:r?imt({element:r,padding:a}).fn(n):{}}}},wys=(s,t)=>({...mys(s),options:[s,t]}),jys=(s,t)=>({...pys(s),options:[s,t]}),Nys=(s,t)=>({...yys(s),options:[s,t]}),kys=(s,t)=>({...fys(s),options:[s,t]}),Sys=(s,t)=>({...xys(s),options:[s,t]}),Cys=(s,t)=>({...gys(s),options:[s,t]}),Ays=(s,t)=>({..._ys(s),options:[s,t]});var Eys="Arrow",xPt=_.forwardRef((s,t)=>{const{children:n,width:r=10,height:a=5,...i}=s;return e.jsx(ii.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"})})});xPt.displayName=Eys;var Tys=xPt;function Cre(s){const[t,n]=_.useState(void 0);return Mx(()=>{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 YXe="Popper",[gPt,_C]=af(YXe),[Mys,yPt]=gPt(YXe),vPt=s=>{const{__scopePopper:t,children:n}=s,[r,a]=_.useState(null);return e.jsx(Mys,{scope:t,anchor:r,onAnchorChange:a,children:n})};vPt.displayName=YXe;var bPt="PopperAnchor",_Pt=_.forwardRef((s,t)=>{const{__scopePopper:n,virtualRef:r,...a}=s,i=yPt(bPt,n),l=_.useRef(null),o=Qo(t,l);return _.useEffect(()=>{i.onAnchorChange((r==null?void 0:r.current)||l.current)}),r?null:e.jsx(ii.div,{...a,ref:o})});_Pt.displayName=bPt;var ZXe="PopperContent",[Pys,Lys]=gPt(ZXe),wPt=_.forwardRef((s,t)=>{var pe,Ce,Ae,Pe,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:f,...y}=s,v=yPt(ZXe,n),[g,b]=_.useState(null),j=Qo(t,Ze=>b(Ze)),[S,C]=_.useState(null),E=Cre(S),P=(E==null?void 0:E.width)??0,M=(E==null?void 0:E.height)??0,I=r+(i!=="center"?"-"+i:""),D=typeof u=="number"?u:{top:0,right:0,bottom:0,left:0,...u},O=Array.isArray(d)?d:[d],V=O.length>0,G={padding:D,boundary:O.filter(Dys),altBoundary:V},{refs:$,floatingStyles:H,placement:Y,isPositioned:Z,middlewareData:ne}=bys({strategy:"fixed",placement:I,whileElementsMounted:(...Ze)=>hys(...Ze,{animationFrame:p==="always"}),elements:{reference:v.anchor},middleware:[wys({mainAxis:a+M,alignmentAxis:l}),c&&jys({mainAxis:!0,crossAxis:!1,limiter:h==="partial"?Nys():void 0,...G}),c&&kys({...G}),Sys({...G,apply:({elements:Ze,rects:Se,availableWidth:Fe,availableHeight:Ne})=>{const{width:Ye,height:Ve}=Se.reference,qe=Ze.floating.style;qe.setProperty("--radix-popper-available-width",`${Fe}px`),qe.setProperty("--radix-popper-available-height",`${Ne}px`),qe.setProperty("--radix-popper-anchor-width",`${Ye}px`),qe.setProperty("--radix-popper-anchor-height",`${Ve}px`)}}),S&&Ays({element:S,padding:o}),Rys({arrowWidth:P,arrowHeight:M}),m&&Cys({strategy:"referenceHidden",...G})]}),[ce,ie]=kPt(Y),te=wx(f);Mx(()=>{Z&&(te==null||te())},[Z,te]);const ae=(pe=ne.arrow)==null?void 0:pe.x,le=(Ce=ne.arrow)==null?void 0:Ce.y,be=((Ae=ne.arrow)==null?void 0:Ae.centerOffset)!==0,[me,he]=_.useState();return Mx(()=>{g&&he(window.getComputedStyle(g).zIndex)},[g]),e.jsx("div",{ref:$.setFloating,"data-radix-popper-content-wrapper":"",style:{...H,transform:Z?H.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:me,"--radix-popper-transform-origin":[(Pe=ne.transformOrigin)==null?void 0:Pe.x,(ze=ne.transformOrigin)==null?void 0:ze.y].join(" "),...((ke=ne.hide)==null?void 0:ke.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:s.dir,children:e.jsx(Pys,{scope:n,placedSide:ce,onArrowChange:C,arrowX:ae,arrowY:le,shouldHideArrow:be,children:e.jsx(ii.div,{"data-side":ce,"data-align":ie,...y,ref:j,style:{...y.style,animation:Z?void 0:"none"}})})})});wPt.displayName=ZXe;var jPt="PopperArrow",Iys={top:"bottom",right:"left",bottom:"top",left:"right"},NPt=_.forwardRef(function(t,n){const{__scopePopper:r,...a}=t,i=Lys(jPt,r),l=Iys[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(Tys,{...a,ref:n,style:{...a.style,display:"block"}})})});NPt.displayName=jPt;function Dys(s){return s!==null}var Rys=s=>({name:"transformOrigin",options:s,fn(t){var v,g,b;const{placement:n,rects:r,middlewareData:a}=t,l=((v=a.arrow)==null?void 0:v.centerOffset)!==0,o=l?0:s.arrowWidth,c=l?0:s.arrowHeight,[d,u]=kPt(n),h={start:"0%",center:"50%",end:"100%"}[u],m=(((g=a.arrow)==null?void 0:g.x)??0)+o/2,p=(((b=a.arrow)==null?void 0:b.y)??0)+c/2;let f="",y="";return d==="bottom"?(f=l?h:`${m}px`,y=`${-c}px`):d==="top"?(f=l?h:`${m}px`,y=`${r.floating.height+c}px`):d==="right"?(f=`${-c}px`,y=l?h:`${p}px`):d==="left"&&(f=`${r.floating.width+c}px`,y=l?h:`${p}px`),{data:{x:f,y}}}});function kPt(s){const[t,n="center"]=s.split("-");return[t,n]}var Are=vPt,tW=_Pt,Ere=wPt,Tre=NPt,[LMe,ibr]=af("Tooltip",[_C]),IMe=_C(),SPt="TooltipProvider",Fys=700,$qe="tooltip.open",[Oys,XXe]=LMe(SPt),CPt=s=>{const{__scopeTooltip:t,delayDuration:n=Fys,skipDelayDuration:r=300,disableHoverableContent:a=!1,children:i}=s,l=_.useRef(!0),o=_.useRef(!1),c=_.useRef(0);return _.useEffect(()=>{const d=c.current;return()=>window.clearTimeout(d)},[]),e.jsx(Oys,{scope:t,isOpenDelayedRef:l,delayDuration:n,onOpen:_.useCallback(()=>{window.clearTimeout(c.current),l.current=!1},[]),onClose:_.useCallback(()=>{window.clearTimeout(c.current),c.current=window.setTimeout(()=>l.current=!0,r)},[r]),isPointerInTransitRef:o,onPointerInTransitChange:_.useCallback(d=>{o.current=d},[]),disableHoverableContent:a,children:i})};CPt.displayName=SPt;var Kee="Tooltip",[zys,DMe]=LMe(Kee),APt=s=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:a,onOpenChange:i,disableHoverableContent:l,delayDuration:o}=s,c=XXe(Kee,s.__scopeTooltip),d=IMe(t),[u,h]=_.useState(null),m=Og(),p=_.useRef(0),f=l??c.disableHoverableContent,y=o??c.delayDuration,v=_.useRef(!1),[g,b]=Ug({prop:r,defaultProp:a??!1,onChange:P=>{P?(c.onOpen(),document.dispatchEvent(new CustomEvent($qe))):c.onClose(),i==null||i(P)},caller:Kee}),j=_.useMemo(()=>g?v.current?"delayed-open":"instant-open":"closed",[g]),S=_.useCallback(()=>{window.clearTimeout(p.current),p.current=0,v.current=!1,b(!0)},[b]),C=_.useCallback(()=>{window.clearTimeout(p.current),p.current=0,b(!1)},[b]),E=_.useCallback(()=>{window.clearTimeout(p.current),p.current=window.setTimeout(()=>{v.current=!0,b(!0),p.current=0},y)},[y,b]);return _.useEffect(()=>()=>{p.current&&(window.clearTimeout(p.current),p.current=0)},[]),e.jsx(Are,{...d,children:e.jsx(zys,{scope:t,contentId:m,open:g,stateAttribute:j,trigger:u,onTriggerChange:h,onTriggerEnter:_.useCallback(()=>{c.isOpenDelayedRef.current?E():S()},[c.isOpenDelayedRef,E,S]),onTriggerLeave:_.useCallback(()=>{f?C():(window.clearTimeout(p.current),p.current=0)},[C,f]),onOpen:S,onClose:C,disableHoverableContent:f,children:n})})};APt.displayName=Kee;var Vqe="TooltipTrigger",EPt=_.forwardRef((s,t)=>{const{__scopeTooltip:n,...r}=s,a=DMe(Vqe,n),i=XXe(Vqe,n),l=IMe(n),o=_.useRef(null),c=Qo(t,o,a.onTriggerChange),d=_.useRef(!1),u=_.useRef(!1),h=_.useCallback(()=>d.current=!1,[]);return _.useEffect(()=>()=>document.removeEventListener("pointerup",h),[h]),e.jsx(tW,{asChild:!0,...l,children:e.jsx(ii.button,{"aria-describedby":a.open?a.contentId:void 0,"data-state":a.stateAttribute,...r,ref:c,onPointerMove:wa(s.onPointerMove,m=>{m.pointerType!=="touch"&&!u.current&&!i.isPointerInTransitRef.current&&(a.onTriggerEnter(),u.current=!0)}),onPointerLeave:wa(s.onPointerLeave,()=>{a.onTriggerLeave(),u.current=!1}),onPointerDown:wa(s.onPointerDown,()=>{a.open&&a.onClose(),d.current=!0,document.addEventListener("pointerup",h,{once:!0})}),onFocus:wa(s.onFocus,()=>{d.current||a.onOpen()}),onBlur:wa(s.onBlur,a.onClose),onClick:wa(s.onClick,a.onClose)})})});EPt.displayName=Vqe;var Bys="TooltipPortal",[obr,Uys]=LMe(Bys,{forceMount:void 0}),_H="TooltipContent",TPt=_.forwardRef((s,t)=>{const n=Uys(_H,s.__scopeTooltip),{forceMount:r=n.forceMount,side:a="top",...i}=s,l=DMe(_H,s.__scopeTooltip);return e.jsx(pg,{present:r||l.open,children:l.disableHoverableContent?e.jsx(MPt,{side:a,...i,ref:t}):e.jsx(qys,{side:a,...i,ref:t})})}),qys=_.forwardRef((s,t)=>{const n=DMe(_H,s.__scopeTooltip),r=XXe(_H,s.__scopeTooltip),a=_.useRef(null),i=Qo(t,a),[l,o]=_.useState(null),{trigger:c,onClose:d}=n,u=a.current,{onPointerInTransitChange:h}=r,m=_.useCallback(()=>{o(null),h(!1)},[h]),p=_.useCallback((f,y)=>{const v=f.currentTarget,g={x:f.clientX,y:f.clientY},b=Wys(g,v.getBoundingClientRect()),j=Kys(g,b),S=Yys(y.getBoundingClientRect()),C=Xys([...j,...S]);o(C),h(!0)},[h]);return _.useEffect(()=>()=>m(),[m]),_.useEffect(()=>{if(c&&u){const f=v=>p(v,u),y=v=>p(v,c);return c.addEventListener("pointerleave",f),u.addEventListener("pointerleave",y),()=>{c.removeEventListener("pointerleave",f),u.removeEventListener("pointerleave",y)}}},[c,u,p,m]),_.useEffect(()=>{if(l){const f=y=>{const v=y.target,g={x:y.clientX,y:y.clientY},b=(c==null?void 0:c.contains(v))||(u==null?void 0:u.contains(v)),j=!Zys(g,l);b?m():j&&(m(),d())};return document.addEventListener("pointermove",f),()=>document.removeEventListener("pointermove",f)}},[c,u,l,d,m]),e.jsx(MPt,{...s,ref:i})}),[$ys,Vys]=LMe(Kee,{isInside:!1}),Hys=L6t("TooltipContent"),MPt=_.forwardRef((s,t)=>{const{__scopeTooltip:n,children:r,"aria-label":a,onEscapeKeyDown:i,onPointerDownOutside:l,...o}=s,c=DMe(_H,n),d=IMe(n),{onClose:u}=c;return _.useEffect(()=>(document.addEventListener($qe,u),()=>document.removeEventListener($qe,u)),[u]),_.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(rL,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:i,onPointerDownOutside:l,onFocusOutside:h=>h.preventDefault(),onDismiss:u,children:e.jsxs(Ere,{"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(Hys,{children:r}),e.jsx($ys,{scope:n,isInside:!0,children:e.jsx(Mfs,{id:c.contentId,role:"tooltip",children:a||r})})]})})});TPt.displayName=_H;var PPt="TooltipArrow",Gys=_.forwardRef((s,t)=>{const{__scopeTooltip:n,...r}=s,a=IMe(n);return Vys(PPt,n).isInside?null:e.jsx(Tre,{...a,...r,ref:t})});Gys.displayName=PPt;function Wys(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 Kys(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 Yys(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 Zys(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 Xys(s){const t=s.slice();return t.sort((n,r)=>n.xr.x?1:n.yr.y?1:0),Qys(t)}function Qys(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 Jys=CPt,evs=APt,tvs=EPt,LPt=TPt;const FN=Jys,ag=evs,ig=tvs,Nx=_.forwardRef(({className:s,sideOffset:t=4,...n},r)=>e.jsx(LPt,{ref:r,sideOffset:t,className:At("z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",s),...n}));Nx.displayName=LPt.displayName;var sW=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(){}},H7=typeof window>"u"||"Deno"in globalThis;function rb(){}function svs(s,t){return typeof s=="function"?s(t):s}function Hqe(s){return typeof s=="number"&&s>=0&&s!==1/0}function IPt(s,t){return Math.max(s+(t||0)-Date.now(),0)}function iP(s,t){return typeof s=="function"?s(t):s}function O2(s,t){return typeof s=="function"?s(t):s}function lmt(s,t){const{type:n="all",exact:r,fetchStatus:a,predicate:i,queryKey:l,stale:o}=s;if(l){if(r){if(t.queryHash!==QXe(l,t.options))return!1}else if(!Yee(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 cmt(s,t){const{exact:n,status:r,predicate:a,mutationKey:i}=s;if(i){if(!t.options.mutationKey)return!1;if(n){if(G7(t.options.mutationKey)!==G7(i))return!1}else if(!Yee(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||a&&!a(t))}function QXe(s,t){return((t==null?void 0:t.queryKeyHashFn)||G7)(s)}function G7(s){return JSON.stringify(s,(t,n)=>Gqe(n)?Object.keys(n).sort().reduce((r,a)=>(r[a]=n[a],r),{}):n)}function Yee(s,t){return s===t?!0:typeof s!=typeof t?!1:s&&t&&typeof s=="object"&&typeof t=="object"?Object.keys(t).every(n=>Yee(s[n],t[n])):!1}function DPt(s,t){if(s===t)return s;const n=dmt(s)&&dmt(t);if(n||Gqe(s)&&Gqe(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 Wqe(s,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(s,t):n.structuralSharing!==!1?DPt(s,t):t}function rvs(s,t,n=0){const r=[...s,t];return n&&r.length>n?r.slice(1):r}function avs(s,t,n=0){const r=[t,...s];return n&&r.length>n?r.slice(0,-1):r}var JXe=Symbol();function RPt(s,t){return!s.queryFn&&(t!=null&&t.initialPromise)?()=>t.initialPromise:!s.queryFn||s.queryFn===JXe?()=>Promise.reject(new Error(`Missing queryFn: '${s.queryHash}'`)):s.queryFn}function FPt(s,t){return typeof s=="function"?s(...t):!!s}var DF,L6,sV,iEt,ivs=(iEt=class extends sW{constructor(){super();us(this,DF);us(this,L6);us(this,sV);Ut(this,sV,t=>{if(!H7&&window.addEventListener){const n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){ye(this,L6)||this.setEventListener(ye(this,sV))}onUnsubscribe(){var t;this.hasListeners()||((t=ye(this,L6))==null||t.call(this),Ut(this,L6,void 0))}setEventListener(t){var n;Ut(this,sV,t),(n=ye(this,L6))==null||n.call(this),Ut(this,L6,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){ye(this,DF)!==t&&(Ut(this,DF,t),this.onFocus())}onFocus(){const t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){var t;return typeof ye(this,DF)=="boolean"?ye(this,DF):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},DF=new WeakMap,L6=new WeakMap,sV=new WeakMap,iEt),eQe=new ivs,nV,I6,rV,oEt,ovs=(oEt=class extends sW{constructor(){super();us(this,nV,!0);us(this,I6);us(this,rV);Ut(this,rV,t=>{if(!H7&&window.addEventListener){const n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){ye(this,I6)||this.setEventListener(ye(this,rV))}onUnsubscribe(){var t;this.hasListeners()||((t=ye(this,I6))==null||t.call(this),Ut(this,I6,void 0))}setEventListener(t){var n;Ut(this,rV,t),(n=ye(this,I6))==null||n.call(this),Ut(this,I6,t(this.setOnline.bind(this)))}setOnline(t){ye(this,nV)!==t&&(Ut(this,nV,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return ye(this,nV)}},nV=new WeakMap,I6=new WeakMap,rV=new WeakMap,oEt),$3e=new ovs;function Kqe(){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 lvs(s){return Math.min(1e3*2**s,3e4)}function OPt(s){return(s??"online")==="online"?$3e.isOnline():!0}var zPt=class extends Error{constructor(s){super("CancelledError"),this.revert=s==null?void 0:s.revert,this.silent=s==null?void 0:s.silent}};function KFe(s){return s instanceof zPt}function BPt(s){let t=!1,n=0,r=!1,a;const i=Kqe(),l=y=>{var v;r||(m(new zPt(y)),(v=s.abort)==null||v.call(s))},o=()=>{t=!0},c=()=>{t=!1},d=()=>eQe.isFocused()&&(s.networkMode==="always"||$3e.isOnline())&&s.canRun(),u=()=>OPt(s.networkMode)&&s.canRun(),h=y=>{var v;r||(r=!0,(v=s.onSuccess)==null||v.call(s,y),a==null||a(),i.resolve(y))},m=y=>{var v;r||(r=!0,(v=s.onError)==null||v.call(s,y),a==null||a(),i.reject(y))},p=()=>new Promise(y=>{var v;a=g=>{(r||d())&&y(g)},(v=s.onPause)==null||v.call(s)}).then(()=>{var y;a=void 0,r||(y=s.onContinue)==null||y.call(s)}),f=()=>{if(r)return;let y;const v=n===0?s.initialPromise:void 0;try{y=v??s.fn()}catch(g){y=Promise.reject(g)}Promise.resolve(y).then(h).catch(g=>{var E;if(r)return;const b=s.retry??(H7?0:3),j=s.retryDelay??lvs,S=typeof j=="function"?j(n,g):j,C=b===!0||typeof b=="number"&&nd()?void 0:p()).then(()=>{t?m(g):f()})})};return{promise:i,cancel:l,continue:()=>(a==null||a(),i),cancelRetry:o,continueRetry:c,canStart:u,start:()=>(u()?f():p().then(f),i)}}var cvs=s=>setTimeout(s,0);function dvs(){let s=[],t=0,n=o=>{o()},r=o=>{o()},a=cvs;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 g0=dvs(),RF,lEt,UPt=(lEt=class{constructor(){us(this,RF)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Hqe(this.gcTime)&&Ut(this,RF,setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(s){this.gcTime=Math.max(this.gcTime||0,s??(H7?1/0:5*60*1e3))}clearGcTimeout(){ye(this,RF)&&(clearTimeout(ye(this,RF)),Ut(this,RF,void 0))}},RF=new WeakMap,lEt),aV,FF,P2,OF,e1,Zse,zF,Tk,M3,cEt,uvs=(cEt=class extends UPt{constructor(t){super();us(this,Tk);us(this,aV);us(this,FF);us(this,P2);us(this,OF);us(this,e1);us(this,Zse);us(this,zF);Ut(this,zF,!1),Ut(this,Zse,t.defaultOptions),this.setOptions(t.options),this.observers=[],Ut(this,OF,t.client),Ut(this,P2,ye(this,OF).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,Ut(this,aV,hvs(this.options)),this.state=t.state??ye(this,aV),this.scheduleGc()}get meta(){return this.options.meta}get promise(){var t;return(t=ye(this,e1))==null?void 0:t.promise}setOptions(t){this.options={...ye(this,Zse),...t},this.updateGcTime(this.options.gcTime)}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&ye(this,P2).remove(this)}setData(t,n){const r=Wqe(this.state.data,t,this.options);return ts(this,Tk,M3).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(t,n){ts(this,Tk,M3).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){var r,a;const n=(r=ye(this,e1))==null?void 0:r.promise;return(a=ye(this,e1))==null||a.cancel(t),n?n.then(rb).catch(rb):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(ye(this,aV))}isActive(){return this.observers.some(t=>O2(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===JXe||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>iP(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:!IPt(this.state.dataUpdatedAt,t)}onFocus(){var n;const t=this.observers.find(r=>r.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(n=ye(this,e1))==null||n.continue()}onOnline(){var n;const t=this.observers.find(r=>r.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(n=ye(this,e1))==null||n.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),ye(this,P2).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(n=>n!==t),this.observers.length||(ye(this,e1)&&(ye(this,zF)?ye(this,e1).cancel({revert:!0}):ye(this,e1).cancelRetry()),this.scheduleGc()),ye(this,P2).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||ts(this,Tk,M3).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(ye(this,e1))return ye(this,e1).continueRetry(),ye(this,e1).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:()=>(Ut(this,zF,!0),r.signal)})},i=()=>{const m=RPt(this.options,n),f=(()=>{const y={client:ye(this,OF),queryKey:this.queryKey,meta:this.meta};return a(y),y})();return Ut(this,zF,!1),this.options.persister?this.options.persister(m,f,this):m(f)},o=(()=>{const m={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:ye(this,OF),state:this.state,fetchFn:i};return a(m),m})();(d=this.options.behavior)==null||d.onFetch(o,this),Ut(this,FF,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((u=o.fetchOptions)==null?void 0:u.meta))&&ts(this,Tk,M3).call(this,{type:"fetch",meta:(h=o.fetchOptions)==null?void 0:h.meta});const c=m=>{var p,f,y,v;KFe(m)&&m.silent||ts(this,Tk,M3).call(this,{type:"error",error:m}),KFe(m)||((f=(p=ye(this,P2).config).onError)==null||f.call(p,m,this),(v=(y=ye(this,P2).config).onSettled)==null||v.call(y,this.state.data,m,this)),this.scheduleGc()};return Ut(this,e1,BPt({initialPromise:n==null?void 0:n.initialPromise,fn:o.fetchFn,abort:r.abort.bind(r),onSuccess:m=>{var p,f,y,v;if(m===void 0){c(new Error(`${this.queryHash} data is undefined`));return}try{this.setData(m)}catch(g){c(g);return}(f=(p=ye(this,P2).config).onSuccess)==null||f.call(p,m,this),(v=(y=ye(this,P2).config).onSettled)==null||v.call(y,m,this.state.error,this),this.scheduleGc()},onError:c,onFail:(m,p)=>{ts(this,Tk,M3).call(this,{type:"failed",failureCount:m,error:p})},onPause:()=>{ts(this,Tk,M3).call(this,{type:"pause"})},onContinue:()=>{ts(this,Tk,M3).call(this,{type:"continue"})},retry:o.options.retry,retryDelay:o.options.retryDelay,networkMode:o.options.networkMode,canRun:()=>!0})),ye(this,e1).start()}},aV=new WeakMap,FF=new WeakMap,P2=new WeakMap,OF=new WeakMap,e1=new WeakMap,Zse=new WeakMap,zF=new WeakMap,Tk=new WeakSet,M3=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,...qPt(r.data,this.options),fetchMeta:t.meta??null};case"success":return Ut(this,FF,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 KFe(a)&&a.revert&&ye(this,FF)?{...ye(this,FF),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),g0.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),ye(this,P2).notify({query:this,type:"updated",action:t})})},cEt);function qPt(s,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:OPt(t.networkMode)?"fetching":"paused",...s===void 0&&{error:null,status:"pending"}}}function hvs(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 K5,dEt,mvs=(dEt=class extends sW{constructor(t={}){super();us(this,K5);this.config=t,Ut(this,K5,new Map)}build(t,n,r){const a=n.queryKey,i=n.queryHash??QXe(a,n);let l=this.get(i);return l||(l=new uvs({client:t,queryKey:a,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(a)}),this.add(l)),l}add(t){ye(this,K5).has(t.queryHash)||(ye(this,K5).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const n=ye(this,K5).get(t.queryHash);n&&(t.destroy(),n===t&&ye(this,K5).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){g0.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return ye(this,K5).get(t)}getAll(){return[...ye(this,K5).values()]}find(t){const n={exact:!0,...t};return this.getAll().find(r=>lmt(n,r))}findAll(t={}){const n=this.getAll();return Object.keys(t).length>0?n.filter(r=>lmt(t,r)):n}notify(t){g0.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){g0.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){g0.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},K5=new WeakMap,dEt),Y5,tb,BF,Z5,qT,uEt,pvs=(uEt=class extends UPt{constructor(t){super();us(this,Z5);us(this,Y5);us(this,tb);us(this,BF);this.mutationId=t.mutationId,Ut(this,tb,t.mutationCache),Ut(this,Y5,[]),this.state=t.state||$Pt(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){ye(this,Y5).includes(t)||(ye(this,Y5).push(t),this.clearGcTimeout(),ye(this,tb).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){Ut(this,Y5,ye(this,Y5).filter(n=>n!==t)),this.scheduleGc(),ye(this,tb).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){ye(this,Y5).length||(this.state.status==="pending"?this.scheduleGc():ye(this,tb).remove(this))}continue(){var t;return((t=ye(this,BF))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var i,l,o,c,d,u,h,m,p,f,y,v,g,b,j,S,C,E,P,M;const n=()=>{ts(this,Z5,qT).call(this,{type:"continue"})};Ut(this,BF,BPt({fn:()=>this.options.mutationFn?this.options.mutationFn(t):Promise.reject(new Error("No mutationFn found")),onFail:(I,D)=>{ts(this,Z5,qT).call(this,{type:"failed",failureCount:I,error:D})},onPause:()=>{ts(this,Z5,qT).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>ye(this,tb).canRun(this)}));const r=this.state.status==="pending",a=!ye(this,BF).canStart();try{if(r)n();else{ts(this,Z5,qT).call(this,{type:"pending",variables:t,isPaused:a}),await((l=(i=ye(this,tb).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&&ts(this,Z5,qT).call(this,{type:"pending",context:D,variables:t,isPaused:a})}const I=await ye(this,BF).start();return await((u=(d=ye(this,tb).config).onSuccess)==null?void 0:u.call(d,I,t,this.state.context,this)),await((m=(h=this.options).onSuccess)==null?void 0:m.call(h,I,t,this.state.context)),await((f=(p=ye(this,tb).config).onSettled)==null?void 0:f.call(p,I,null,this.state.variables,this.state.context,this)),await((v=(y=this.options).onSettled)==null?void 0:v.call(y,I,null,t,this.state.context)),ts(this,Z5,qT).call(this,{type:"success",data:I}),I}catch(I){try{throw await((b=(g=ye(this,tb).config).onError)==null?void 0:b.call(g,I,t,this.state.context,this)),await((S=(j=this.options).onError)==null?void 0:S.call(j,I,t,this.state.context)),await((E=(C=ye(this,tb).config).onSettled)==null?void 0:E.call(C,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{ts(this,Z5,qT).call(this,{type:"error",error:I})}}finally{ye(this,tb).runNext(this)}}},Y5=new WeakMap,tb=new WeakMap,BF=new WeakMap,Z5=new WeakSet,qT=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),g0.batch(()=>{ye(this,Y5).forEach(r=>{r.onMutationUpdate(t)}),ye(this,tb).notify({mutation:this,type:"updated",action:t})})},uEt);function $Pt(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var eA,Mk,Xse,hEt,fvs=(hEt=class extends sW{constructor(t={}){super();us(this,eA);us(this,Mk);us(this,Xse);this.config=t,Ut(this,eA,new Set),Ut(this,Mk,new Map),Ut(this,Xse,0)}build(t,n,r){const a=new pvs({mutationCache:this,mutationId:++X0(this,Xse)._,options:t.defaultMutationOptions(n),state:r});return this.add(a),a}add(t){ye(this,eA).add(t);const n=nle(t);if(typeof n=="string"){const r=ye(this,Mk).get(n);r?r.push(t):ye(this,Mk).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(ye(this,eA).delete(t)){const n=nle(t);if(typeof n=="string"){const r=ye(this,Mk).get(n);if(r)if(r.length>1){const a=r.indexOf(t);a!==-1&&r.splice(a,1)}else r[0]===t&&ye(this,Mk).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){const n=nle(t);if(typeof n=="string"){const r=ye(this,Mk).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=nle(t);if(typeof n=="string"){const a=(r=ye(this,Mk).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(){g0.batch(()=>{ye(this,eA).forEach(t=>{this.notify({type:"removed",mutation:t})}),ye(this,eA).clear(),ye(this,Mk).clear()})}getAll(){return Array.from(ye(this,eA))}find(t){const n={exact:!0,...t};return this.getAll().find(r=>cmt(n,r))}findAll(t={}){return this.getAll().filter(n=>cmt(t,n))}notify(t){g0.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){const t=this.getAll().filter(n=>n.state.isPaused);return g0.batch(()=>Promise.all(t.map(n=>n.continue().catch(rb))))}},eA=new WeakMap,Mk=new WeakMap,Xse=new WeakMap,hEt);function nle(s){var t;return(t=s.options.scope)==null?void 0:t.id}function V3e(s){return{onFetch:(t,n)=>{var u,h,m,p,f;const r=t.options,a=(m=(h=(u=t.fetchOptions)==null?void 0:u.meta)==null?void 0:h.fetchMore)==null?void 0:m.direction,i=((p=t.state.data)==null?void 0:p.pages)||[],l=((f=t.state.data)==null?void 0:f.pageParams)||[];let o={pages:[],pageParams:[]},c=0;const d=async()=>{let y=!1;const v=j=>{Object.defineProperty(j,"signal",{enumerable:!0,get:()=>(t.signal.aborted?y=!0:t.signal.addEventListener("abort",()=>{y=!0}),t.signal)})},g=RPt(t.options,t.fetchOptions),b=async(j,S,C)=>{if(y)return Promise.reject();if(S==null&&j.pages.length)return Promise.resolve(j);const P=(()=>{const O={client:t.client,queryKey:t.queryKey,pageParam:S,direction:C?"backward":"forward",meta:t.options.meta};return v(O),O})(),M=await g(P),{maxPages:I}=t.options,D=C?avs:rvs;return{pages:D(j.pages,M,I),pageParams:D(j.pageParams,S,I)}};if(a&&i.length){const j=a==="backward",S=j?VPt:Yqe,C={pages:i,pageParams:l},E=S(r,C);o=await b(C,E,j)}else{const j=s??i.length;do{const S=c===0?l[0]??r.initialPageParam:Yqe(r,o);if(c>0&&S==null)break;o=await b(o,S),c++}while(c{var y,v;return(v=(y=t.options).persister)==null?void 0:v.call(y,d,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n)}:t.fetchFn=d}}}function Yqe(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 VPt(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 xvs(s,t){return t?Yqe(s,t)!=null:!1}function gvs(s,t){return!t||!s.getPreviousPageParam?!1:VPt(s,t)!=null}var hx,D6,R6,iV,oV,F6,lV,cV,mEt,yvs=(mEt=class{constructor(s={}){us(this,hx);us(this,D6);us(this,R6);us(this,iV);us(this,oV);us(this,F6);us(this,lV);us(this,cV);Ut(this,hx,s.queryCache||new mvs),Ut(this,D6,s.mutationCache||new fvs),Ut(this,R6,s.defaultOptions||{}),Ut(this,iV,new Map),Ut(this,oV,new Map),Ut(this,F6,0)}mount(){X0(this,F6)._++,ye(this,F6)===1&&(Ut(this,lV,eQe.subscribe(async s=>{s&&(await this.resumePausedMutations(),ye(this,hx).onFocus())})),Ut(this,cV,$3e.subscribe(async s=>{s&&(await this.resumePausedMutations(),ye(this,hx).onOnline())})))}unmount(){var s,t;X0(this,F6)._--,ye(this,F6)===0&&((s=ye(this,lV))==null||s.call(this),Ut(this,lV,void 0),(t=ye(this,cV))==null||t.call(this),Ut(this,cV,void 0))}isFetching(s){return ye(this,hx).findAll({...s,fetchStatus:"fetching"}).length}isMutating(s){return ye(this,D6).findAll({...s,status:"pending"}).length}getQueryData(s){var n;const t=this.defaultQueryOptions({queryKey:s});return(n=ye(this,hx).get(t.queryHash))==null?void 0:n.state.data}ensureQueryData(s){const t=this.defaultQueryOptions(s),n=ye(this,hx).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(s):(s.revalidateIfStale&&n.isStaleByTime(iP(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(s){return ye(this,hx).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=ye(this,hx).get(r.queryHash),i=a==null?void 0:a.state.data,l=svs(t,i);if(l!==void 0)return ye(this,hx).build(this,r).setData(l,{...n,manual:!0})}setQueriesData(s,t,n){return g0.batch(()=>ye(this,hx).findAll(s).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(s){var n;const t=this.defaultQueryOptions({queryKey:s});return(n=ye(this,hx).get(t.queryHash))==null?void 0:n.state}removeQueries(s){const t=ye(this,hx);g0.batch(()=>{t.findAll(s).forEach(n=>{t.remove(n)})})}resetQueries(s,t){const n=ye(this,hx);return g0.batch(()=>(n.findAll(s).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...s},t)))}cancelQueries(s,t={}){const n={revert:!0,...t},r=g0.batch(()=>ye(this,hx).findAll(s).map(a=>a.cancel(n)));return Promise.all(r).then(rb).catch(rb)}invalidateQueries(s,t={}){return g0.batch(()=>(ye(this,hx).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=g0.batch(()=>ye(this,hx).findAll(s).filter(a=>!a.isDisabled()&&!a.isStatic()).map(a=>{let i=a.fetch(void 0,n);return n.throwOnError||(i=i.catch(rb)),a.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(rb)}fetchQuery(s){const t=this.defaultQueryOptions(s);t.retry===void 0&&(t.retry=!1);const n=ye(this,hx).build(this,t);return n.isStaleByTime(iP(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(s){return this.fetchQuery(s).then(rb).catch(rb)}fetchInfiniteQuery(s){return s.behavior=V3e(s.pages),this.fetchQuery(s)}prefetchInfiniteQuery(s){return this.fetchInfiniteQuery(s).then(rb).catch(rb)}ensureInfiniteQueryData(s){return s.behavior=V3e(s.pages),this.ensureQueryData(s)}resumePausedMutations(){return $3e.isOnline()?ye(this,D6).resumePausedMutations():Promise.resolve()}getQueryCache(){return ye(this,hx)}getMutationCache(){return ye(this,D6)}getDefaultOptions(){return ye(this,R6)}setDefaultOptions(s){Ut(this,R6,s)}setQueryDefaults(s,t){ye(this,iV).set(G7(s),{queryKey:s,defaultOptions:t})}getQueryDefaults(s){const t=[...ye(this,iV).values()],n={};return t.forEach(r=>{Yee(s,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(s,t){ye(this,oV).set(G7(s),{mutationKey:s,defaultOptions:t})}getMutationDefaults(s){const t=[...ye(this,oV).values()],n={};return t.forEach(r=>{Yee(s,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(s){if(s._defaulted)return s;const t={...ye(this,R6).queries,...this.getQueryDefaults(s.queryKey),...s,_defaulted:!0};return t.queryHash||(t.queryHash=QXe(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===JXe&&(t.enabled=!1),t}defaultMutationOptions(s){return s!=null&&s._defaulted?s:{...ye(this,R6).mutations,...(s==null?void 0:s.mutationKey)&&this.getMutationDefaults(s.mutationKey),...s,_defaulted:!0}}clear(){ye(this,hx).clear(),ye(this,D6).clear()}},hx=new WeakMap,D6=new WeakMap,R6=new WeakMap,iV=new WeakMap,oV=new WeakMap,F6=new WeakMap,lV=new WeakMap,cV=new WeakMap,mEt),c_,du,Qse,sb,UF,dV,O6,z6,Jse,uV,hV,qF,$F,B6,mV,jh,oX,Zqe,Xqe,Qqe,Jqe,e$e,t$e,s$e,GPt,pEt,HPt=(pEt=class extends sW{constructor(t,n){super();us(this,jh);us(this,c_);us(this,du);us(this,Qse);us(this,sb);us(this,UF);us(this,dV);us(this,O6);us(this,z6);us(this,Jse);us(this,uV);us(this,hV);us(this,qF);us(this,$F);us(this,B6);us(this,mV,new Set);this.options=n,Ut(this,c_,t),Ut(this,z6,null),Ut(this,O6,Kqe()),this.options.experimental_prefetchInRender||ye(this,O6).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&&(ye(this,du).addObserver(this),hmt(ye(this,du),this.options)?ts(this,jh,oX).call(this):this.updateResult(),ts(this,jh,Jqe).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return n$e(ye(this,du),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return n$e(ye(this,du),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,ts(this,jh,e$e).call(this),ts(this,jh,t$e).call(this),ye(this,du).removeObserver(this)}setOptions(t){const n=this.options,r=ye(this,du);if(this.options=ye(this,c_).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof O2(this.options.enabled,ye(this,du))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");ts(this,jh,s$e).call(this),ye(this,du).setOptions(this.options),n._defaulted&&!q3e(this.options,n)&&ye(this,c_).getQueryCache().notify({type:"observerOptionsUpdated",query:ye(this,du),observer:this});const a=this.hasListeners();a&&mmt(ye(this,du),r,this.options,n)&&ts(this,jh,oX).call(this),this.updateResult(),a&&(ye(this,du)!==r||O2(this.options.enabled,ye(this,du))!==O2(n.enabled,ye(this,du))||iP(this.options.staleTime,ye(this,du))!==iP(n.staleTime,ye(this,du)))&&ts(this,jh,Zqe).call(this);const i=ts(this,jh,Xqe).call(this);a&&(ye(this,du)!==r||O2(this.options.enabled,ye(this,du))!==O2(n.enabled,ye(this,du))||i!==ye(this,B6))&&ts(this,jh,Qqe).call(this,i)}getOptimisticResult(t){const n=ye(this,c_).getQueryCache().build(ye(this,c_),t),r=this.createResult(n,t);return bvs(this,r)&&(Ut(this,sb,r),Ut(this,dV,this.options),Ut(this,UF,ye(this,du).state)),r}getCurrentResult(){return ye(this,sb)}trackResult(t,n){return new Proxy(t,{get:(r,a)=>(this.trackProp(a),n==null||n(a),Reflect.get(r,a))})}trackProp(t){ye(this,mV).add(t)}getCurrentQuery(){return ye(this,du)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const n=ye(this,c_).defaultQueryOptions(t),r=ye(this,c_).getQueryCache().build(ye(this,c_),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(t){return ts(this,jh,oX).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),ye(this,sb)))}createResult(t,n){var I;const r=ye(this,du),a=this.options,i=ye(this,sb),l=ye(this,UF),o=ye(this,dV),d=t!==r?t.state:ye(this,Qse),{state:u}=t;let h={...u},m=!1,p;if(n._optimisticResults){const D=this.hasListeners(),O=!D&&hmt(t,n),V=D&&mmt(t,r,n,a);(O||V)&&(h={...h,...qPt(u.data,t.options)}),n._optimisticResults==="isRestoring"&&(h.fetchStatus="idle")}let{error:f,errorUpdatedAt:y,status:v}=h;p=h.data;let g=!1;if(n.placeholderData!==void 0&&p===void 0&&v==="pending"){let D;i!=null&&i.isPlaceholderData&&n.placeholderData===(o==null?void 0:o.placeholderData)?(D=i.data,g=!0):D=typeof n.placeholderData=="function"?n.placeholderData((I=ye(this,hV))==null?void 0:I.state.data,ye(this,hV)):n.placeholderData,D!==void 0&&(v="success",p=Wqe(i==null?void 0:i.data,D,n),m=!0)}if(n.select&&p!==void 0&&!g)if(i&&p===(l==null?void 0:l.data)&&n.select===ye(this,Jse))p=ye(this,uV);else try{Ut(this,Jse,n.select),p=n.select(p),p=Wqe(i==null?void 0:i.data,p,n),Ut(this,uV,p),Ut(this,z6,null)}catch(D){Ut(this,z6,D)}ye(this,z6)&&(f=ye(this,z6),p=ye(this,uV),y=Date.now(),v="error");const b=h.fetchStatus==="fetching",j=v==="pending",S=v==="error",C=j&&b,E=p!==void 0,M={status:v,fetchStatus:h.fetchStatus,isPending:j,isSuccess:v==="success",isError:S,isInitialLoading:C,isLoading:C,data:p,dataUpdatedAt:h.dataUpdatedAt,error:f,errorUpdatedAt:y,failureCount:h.fetchFailureCount,failureReason:h.fetchFailureReason,errorUpdateCount:h.errorUpdateCount,isFetched:h.dataUpdateCount>0||h.errorUpdateCount>0,isFetchedAfterMount:h.dataUpdateCount>d.dataUpdateCount||h.errorUpdateCount>d.errorUpdateCount,isFetching:b,isRefetching:b&&!j,isLoadingError:S&&!E,isPaused:h.fetchStatus==="paused",isPlaceholderData:m,isRefetchError:S&&E,isStale:tQe(t,n),refetch:this.refetch,promise:ye(this,O6),isEnabled:O2(n.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){const D=G=>{M.status==="error"?G.reject(M.error):M.data!==void 0&&G.resolve(M.data)},O=()=>{const G=Ut(this,O6,M.promise=Kqe());D(G)},V=ye(this,O6);switch(V.status){case"pending":t.queryHash===r.queryHash&&D(V);break;case"fulfilled":(M.status==="error"||M.data!==V.value)&&O();break;case"rejected":(M.status!=="error"||M.error!==V.reason)&&O();break}}return M}updateResult(){const t=ye(this,sb),n=this.createResult(ye(this,du),this.options);if(Ut(this,UF,ye(this,du).state),Ut(this,dV,this.options),ye(this,UF).data!==void 0&&Ut(this,hV,ye(this,du)),q3e(n,t))return;Ut(this,sb,n);const r=()=>{if(!t)return!0;const{notifyOnChangeProps:a}=this.options,i=typeof a=="function"?a():a;if(i==="all"||!i&&!ye(this,mV).size)return!0;const l=new Set(i??ye(this,mV));return this.options.throwOnError&&l.add("error"),Object.keys(ye(this,sb)).some(o=>{const c=o;return ye(this,sb)[c]!==t[c]&&l.has(c)})};ts(this,jh,GPt).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&ts(this,jh,Jqe).call(this)}},c_=new WeakMap,du=new WeakMap,Qse=new WeakMap,sb=new WeakMap,UF=new WeakMap,dV=new WeakMap,O6=new WeakMap,z6=new WeakMap,Jse=new WeakMap,uV=new WeakMap,hV=new WeakMap,qF=new WeakMap,$F=new WeakMap,B6=new WeakMap,mV=new WeakMap,jh=new WeakSet,oX=function(t){ts(this,jh,s$e).call(this);let n=ye(this,du).fetch(this.options,t);return t!=null&&t.throwOnError||(n=n.catch(rb)),n},Zqe=function(){ts(this,jh,e$e).call(this);const t=iP(this.options.staleTime,ye(this,du));if(H7||ye(this,sb).isStale||!Hqe(t))return;const r=IPt(ye(this,sb).dataUpdatedAt,t)+1;Ut(this,qF,setTimeout(()=>{ye(this,sb).isStale||this.updateResult()},r))},Xqe=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(ye(this,du)):this.options.refetchInterval)??!1},Qqe=function(t){ts(this,jh,t$e).call(this),Ut(this,B6,t),!(H7||O2(this.options.enabled,ye(this,du))===!1||!Hqe(ye(this,B6))||ye(this,B6)===0)&&Ut(this,$F,setInterval(()=>{(this.options.refetchIntervalInBackground||eQe.isFocused())&&ts(this,jh,oX).call(this)},ye(this,B6)))},Jqe=function(){ts(this,jh,Zqe).call(this),ts(this,jh,Qqe).call(this,ts(this,jh,Xqe).call(this))},e$e=function(){ye(this,qF)&&(clearTimeout(ye(this,qF)),Ut(this,qF,void 0))},t$e=function(){ye(this,$F)&&(clearInterval(ye(this,$F)),Ut(this,$F,void 0))},s$e=function(){const t=ye(this,c_).getQueryCache().build(ye(this,c_),this.options);if(t===ye(this,du))return;const n=ye(this,du);Ut(this,du,t),Ut(this,Qse,t.state),this.hasListeners()&&(n==null||n.removeObserver(this),t.addObserver(this))},GPt=function(t){g0.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(ye(this,sb))}),ye(this,c_).getQueryCache().notify({query:ye(this,du),type:"observerResultsUpdated"})})},pEt);function vvs(s,t){return O2(t.enabled,s)!==!1&&s.state.data===void 0&&!(s.state.status==="error"&&t.retryOnMount===!1)}function hmt(s,t){return vvs(s,t)||s.state.data!==void 0&&n$e(s,t,t.refetchOnMount)}function n$e(s,t,n){if(O2(t.enabled,s)!==!1&&iP(t.staleTime,s)!=="static"){const r=typeof n=="function"?n(s):n;return r==="always"||r!==!1&&tQe(s,t)}return!1}function mmt(s,t,n,r){return(s!==t||O2(r.enabled,s)===!1)&&(!n.suspense||s.state.status!=="error")&&tQe(s,n)}function tQe(s,t){return O2(t.enabled,s)!==!1&&s.isStaleByTime(iP(t.staleTime,s))}function bvs(s,t){return!q3e(s.getCurrentResult(),t)}var _vs=class extends HPt{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:V3e()})}getOptimisticResult(s){return s.behavior=V3e(),super.getOptimisticResult(s)}fetchNextPage(s){return this.fetch({...s,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(s){return this.fetch({...s,meta:{fetchMore:{direction:"backward"}}})}createResult(s,t){var f,y;const{state:n}=s,r=super.createResult(s,t),{isFetching:a,isRefetching:i,isError:l,isRefetchError:o}=r,c=(y=(f=n.fetchMeta)==null?void 0:f.fetchMore)==null?void 0:y.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:xvs(t,n.data),hasPreviousPage:gvs(t,n.data),isFetchNextPageError:d,isFetchingNextPage:u,isFetchPreviousPageError:h,isFetchingPreviousPage:m,isRefetchError:o&&!d&&!h,isRefetching:i&&!u&&!m}}},U6,q6,d_,tA,uE,x4e,r$e,fEt,wvs=(fEt=class extends sW{constructor(n,r){super();us(this,uE);us(this,U6);us(this,q6);us(this,d_);us(this,tA);Ut(this,U6,n),this.setOptions(r),this.bindMethods(),ts(this,uE,x4e).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(n){var a;const r=this.options;this.options=ye(this,U6).defaultMutationOptions(n),q3e(this.options,r)||ye(this,U6).getMutationCache().notify({type:"observerOptionsUpdated",mutation:ye(this,d_),observer:this}),r!=null&&r.mutationKey&&this.options.mutationKey&&G7(r.mutationKey)!==G7(this.options.mutationKey)?this.reset():((a=ye(this,d_))==null?void 0:a.state.status)==="pending"&&ye(this,d_).setOptions(this.options)}onUnsubscribe(){var n;this.hasListeners()||(n=ye(this,d_))==null||n.removeObserver(this)}onMutationUpdate(n){ts(this,uE,x4e).call(this),ts(this,uE,r$e).call(this,n)}getCurrentResult(){return ye(this,q6)}reset(){var n;(n=ye(this,d_))==null||n.removeObserver(this),Ut(this,d_,void 0),ts(this,uE,x4e).call(this),ts(this,uE,r$e).call(this)}mutate(n,r){var a;return Ut(this,tA,r),(a=ye(this,d_))==null||a.removeObserver(this),Ut(this,d_,ye(this,U6).getMutationCache().build(ye(this,U6),this.options)),ye(this,d_).addObserver(this),ye(this,d_).execute(n)}},U6=new WeakMap,q6=new WeakMap,d_=new WeakMap,tA=new WeakMap,uE=new WeakSet,x4e=function(){var r;const n=((r=ye(this,d_))==null?void 0:r.state)??$Pt();Ut(this,q6,{...n,isPending:n.status==="pending",isSuccess:n.status==="success",isError:n.status==="error",isIdle:n.status==="idle",mutate:this.mutate,reset:this.reset})},r$e=function(n){g0.batch(()=>{var r,a,i,l,o,c,d,u;if(ye(this,tA)&&this.hasListeners()){const h=ye(this,q6).variables,m=ye(this,q6).context;(n==null?void 0:n.type)==="success"?((a=(r=ye(this,tA)).onSuccess)==null||a.call(r,n.data,h,m),(l=(i=ye(this,tA)).onSettled)==null||l.call(i,n.data,null,h,m)):(n==null?void 0:n.type)==="error"&&((c=(o=ye(this,tA)).onError)==null||c.call(o,n.error,h,m),(u=(d=ye(this,tA)).onSettled)==null||u.call(d,void 0,n.error,h,m))}this.listeners.forEach(h=>{h(ye(this,q6))})})},fEt),WPt=_.createContext(void 0),Bt=s=>{const t=_.useContext(WPt);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},jvs=({client:s,children:t})=>(_.useEffect(()=>(s.mount(),()=>{s.unmount()}),[s]),e.jsx(WPt.Provider,{value:s,children:t})),KPt=_.createContext(!1),Nvs=()=>_.useContext(KPt);KPt.Provider;function kvs(){let s=!1;return{clearReset:()=>{s=!1},reset:()=>{s=!0},isReset:()=>s}}var Svs=_.createContext(kvs()),Cvs=()=>_.useContext(Svs),Avs=(s,t)=>{(s.suspense||s.throwOnError||s.experimental_prefetchInRender)&&(t.isReset()||(s.retryOnMount=!1))},Evs=s=>{_.useEffect(()=>{s.clearReset()},[s])},Tvs=({result:s,errorResetBoundary:t,throwOnError:n,query:r,suspense:a})=>s.isError&&!t.isReset()&&!s.isFetching&&r&&(a&&s.data===void 0||FPt(n,[s.error,r])),Mvs=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))}},Pvs=(s,t)=>s.isLoading&&s.isFetching&&!t,Lvs=(s,t)=>(s==null?void 0:s.suspense)&&t.isPending,pmt=(s,t,n)=>t.fetchOptimistic(s).catch(()=>{n.clearReset()});function YPt(s,t,n){var h,m,p,f,y;const r=Nvs(),a=Cvs(),i=Bt(),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",Mvs(l),Avs(l,a),Evs(a);const o=!i.getQueryCache().get(l.queryHash),[c]=_.useState(()=>new t(i,l)),d=c.getOptimisticResult(l),u=!r&&s.subscribed!==!1;if(_.useSyncExternalStore(_.useCallback(v=>{const g=u?c.subscribe(g0.batchCalls(v)):rb;return c.updateResult(),g},[c,u]),()=>c.getCurrentResult(),()=>c.getCurrentResult()),_.useEffect(()=>{c.setOptions(l)},[l,c]),Lvs(l,d))throw pmt(l,c,a);if(Tvs({result:d,errorResetBoundary:a,throwOnError:l.throwOnError,query:i.getQueryCache().get(l.queryHash),suspense:l.suspense}))throw d.error;if((f=(p=i.getDefaultOptions().queries)==null?void 0:p._experimental_afterQuery)==null||f.call(p,l,d),l.experimental_prefetchInRender&&!H7&&Pvs(d,r)){const v=o?pmt(l,c,a):(y=i.getQueryCache().get(l.queryHash))==null?void 0:y.promise;v==null||v.catch(rb).finally(()=>{c.updateResult()})}return l.notifyOnChangeProps?d:c.trackResult(d)}function at(s,t){return YPt(s,HPt)}function mt(s,t){const n=Bt(),[r]=_.useState(()=>new wvs(n,s));_.useEffect(()=>{r.setOptions(s)},[r,s]);const a=_.useSyncExternalStore(_.useCallback(l=>r.subscribe(g0.batchCalls(l)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),i=_.useCallback((l,o)=>{r.mutate(l,o).catch(rb)},[r]);if(a.error&&FPt(r.options.throwOnError,[a.error]))throw a.error;return{...a,mutate:i,mutateAsync:a.mutate}}function Ivs(s,t){return YPt(s,_vs)}/** * @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 Zee(){return Zee=Object.assign?Object.assign.bind():function(s){for(var t=1;t"u")throw new Error(t)}function ZPt(s,t){if(!s){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function Rvs(){return Math.random().toString(36).substr(2,8)}function xmt(s,t){return{usr:s.state,key:s.key,idx:t}}function a$e(s,t,n,r){return n===void 0&&(n=null),Zee({pathname:typeof s=="string"?s:s.pathname,search:"",hash:""},typeof t=="string"?nW(t):t,{state:n,key:t&&t.key||r||Rvs()})}function H3e(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 nW(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 Fvs(s,t,n,r){r===void 0&&(r={});let{window:a=document.defaultView,v5Compat:i=!1}=r,l=a.history,o=yM.Pop,c=null,d=u();d==null&&(d=0,l.replaceState(Zee({},l.state,{idx:d}),""));function u(){return(l.state||{idx:null}).idx}function h(){o=yM.Pop;let v=u(),g=v==null?null:v-d;d=v,c&&c({action:o,location:y.location,delta:g})}function m(v,g){o=yM.Push;let b=a$e(y.location,v,g);d=u()+1;let j=xmt(b,d),S=y.createHref(b);try{l.pushState(j,"",S)}catch(C){if(C instanceof DOMException&&C.name==="DataCloneError")throw C;a.location.assign(S)}i&&c&&c({action:o,location:y.location,delta:1})}function p(v,g){o=yM.Replace;let b=a$e(y.location,v,g);d=u();let j=xmt(b,d),S=y.createHref(b);l.replaceState(j,"",S),i&&c&&c({action:o,location:y.location,delta:0})}function f(v){let g=a.location.origin!=="null"?a.location.origin:a.location.href,b=typeof v=="string"?v:H3e(v);return b=b.replace(/ $/,"%20"),Gf(g,"No window.location.(origin|href) available to create URL for href: "+b),new URL(b,g)}let y={get action(){return o},get location(){return s(a,l)},listen(v){if(c)throw new Error("A history only accepts one active listener");return a.addEventListener(fmt,h),c=v,()=>{a.removeEventListener(fmt,h),c=null}},createHref(v){return t(a,v)},createURL:f,encodeLocation(v){let g=f(v);return{pathname:g.pathname,search:g.search,hash:g.hash}},push:m,replace:p,go(v){return l.go(v)}};return y}var gmt;(function(s){s.data="data",s.deferred="deferred",s.redirect="redirect",s.error="error"})(gmt||(gmt={}));function Ovs(s,t,n){return n===void 0&&(n="/"),zvs(s,t,n,!1)}function zvs(s,t,n,r){let a=typeof t=="string"?nW(t):t,i=wH(a.pathname||"/",n);if(i==null)return null;let l=XPt(s);Bvs(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("/")&&(Gf(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=oP([r,c.relativePath]),u=n.concat(c);i.children&&i.children.length>0&&(Gf(i.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+d+'".')),XPt(i.children,t,u,d)),!(i.path==null&&!i.index)&&t.push({path:d,score:Wvs(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 QPt(i.path))a(i,l,c)}),t}function QPt(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=QPt(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 Bvs(s){s.sort((t,n)=>t.score!==n.score?n.score-t.score:Kvs(t.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}const Uvs=/^:[\w-]+$/,qvs=3,$vs=2,Vvs=1,Hvs=10,Gvs=-2,ymt=s=>s==="*";function Wvs(s,t){let n=s.split("/"),r=n.length;return n.some(ymt)&&(r+=Gvs),t&&(r+=$vs),n.filter(a=>!ymt(a)).reduce((a,i)=>a+(Uvs.test(i)?qvs:i===""?Vvs:Hvs),r)}function Kvs(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 Yvs(s,t,n){let{routesMeta:r}=s,a={},i="/",l=[];for(let o=0;o{let{paramName:m,isOptional:p}=u;if(m==="*"){let y=o[h]||"";l=i.slice(0,i.length-y.length).replace(/(.)\/+$/,"$1")}const f=o[h];return p&&!f?d[m]=void 0:d[m]=(f||"").replace(/%2F/g,"/"),d},{}),pathname:i,pathnameBase:l,pattern:s}}function Zvs(s,t,n){t===void 0&&(t=!1),n===void 0&&(n=!0),ZPt(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 Xvs(s){try{return s.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return ZPt(!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 wH(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 Qvs(s,t){t===void 0&&(t="/");let{pathname:n,search:r="",hash:a=""}=typeof s=="string"?nW(s):s;return{pathname:n?n.startsWith("/")?n:Jvs(n,t):t,search:s1s(r),hash:n1s(a)}}function Jvs(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 YFe(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 e1s(s){return s.filter((t,n)=>n===0||t.route.path&&t.route.path.length>0)}function sQe(s,t){let n=e1s(s);return t?n.map((r,a)=>a===n.length-1?r.pathname:r.pathnameBase):n.map(r=>r.pathnameBase)}function nQe(s,t,n,r){r===void 0&&(r=!1);let a;typeof s=="string"?a=nW(s):(a=Zee({},s),Gf(!a.pathname||!a.pathname.includes("?"),YFe("?","pathname","search",a)),Gf(!a.pathname||!a.pathname.includes("#"),YFe("#","pathname","hash",a)),Gf(!a.search||!a.search.includes("#"),YFe("#","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=Qvs(a,o),d=l&&l!=="/"&&l.endsWith("/"),u=(i||l===".")&&n.endsWith("/");return!c.pathname.endsWith("/")&&(d||u)&&(c.pathname+="/"),c}const oP=s=>s.join("/").replace(/\/\/+/g,"/"),t1s=s=>s.replace(/\/+$/,"").replace(/^\/*/,"/"),s1s=s=>!s||s==="?"?"":s.startsWith("?")?s:"?"+s,n1s=s=>!s||s==="#"?"":s.startsWith("#")?s:"#"+s;function r1s(s){return s!=null&&typeof s.status=="number"&&typeof s.statusText=="string"&&typeof s.internal=="boolean"&&"data"in s}const JPt=["post","put","patch","delete"];new Set(JPt);const a1s=["get",...JPt];new Set(a1s);/** * 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 Xee(){return Xee=Object.assign?Object.assign.bind():function(s){for(var t=1;t{o.current=!0}),_.useCallback(function(d,u){if(u===void 0&&(u={}),!o.current)return;if(typeof d=="number"){r.go(d);return}let h=nQe(d,JSON.parse(l),i,u.relative==="path");s==null&&t!=="/"&&(h.pathname=h.pathname==="/"?t:oP([t,h.pathname])),(u.replace?r.replace:r.push)(h,u.state,u)},[t,r,l,i,s])}const l1s=_.createContext(null);function c1s(s){let t=_.useContext(wC).outlet;return t&&_.createElement(l1s.Provider,{value:s},t)}function Li(){let{matches:s}=_.useContext(wC),t=s[s.length-1];return t?t.params:{}}function OMe(s,t){let{relative:n}=t===void 0?{}:t,{future:r}=_.useContext(IE),{matches:a}=_.useContext(wC),{pathname:i}=ru(),l=JSON.stringify(sQe(a,r.v7_relativeSplatPath));return _.useMemo(()=>nQe(s,JSON.parse(l),i,n==="path"),[s,l,i,n])}function d1s(s,t){return u1s(s,t)}function u1s(s,t,n,r){rW()||Gf(!1);let{navigator:a}=_.useContext(IE),{matches:i}=_.useContext(wC),l=i[i.length-1],o=l?l.params:{};l&&l.pathname;let c=l?l.pathnameBase:"/";l&&l.route;let d=ru(),u;if(t){var h;let v=typeof t=="string"?nW(t):t;c==="/"||(h=v.pathname)!=null&&h.startsWith(c)||Gf(!1),u=v}else u=d;let m=u.pathname||"/",p=m;if(c!=="/"){let v=c.replace(/^\//,"").split("/");p="/"+m.replace(/^\//,"").split("/").slice(v.length).join("/")}let f=Ovs(s,{pathname:p}),y=x1s(f&&f.map(v=>Object.assign({},v,{params:Object.assign({},o,v.params),pathname:oP([c,a.encodeLocation?a.encodeLocation(v.pathname).pathname:v.pathname]),pathnameBase:v.pathnameBase==="/"?c:oP([c,a.encodeLocation?a.encodeLocation(v.pathnameBase).pathname:v.pathnameBase])})),i,n,r);return t&&y?_.createElement(FMe.Provider,{value:{location:Xee({pathname:"/",search:"",hash:"",state:null,key:"default"},u),navigationType:yM.Pop}},y):y}function h1s(){let s=b1s(),t=r1s(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 _.createElement(_.Fragment,null,_.createElement("h2",null,"Unexpected Application Error!"),_.createElement("h3",{style:{fontStyle:"italic"}},t),n?_.createElement("pre",{style:a},n):null,null)}const m1s=_.createElement(h1s,null);class p1s extends _.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?_.createElement(wC.Provider,{value:this.props.routeContext},_.createElement(tLt.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function f1s(s){let{routeContext:t,match:n,children:r}=s,a=_.useContext(RMe);return a&&a.static&&a.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(a.staticContext._deepestRenderedBoundaryId=n.route.id),_.createElement(wC.Provider,{value:t},r)}function x1s(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||Gf(!1),l=l.slice(0,Math.min(l.length,u+1))}let c=!1,d=-1;if(n&&r&&r.v7_partialHydration)for(let u=0;u=0?l=l.slice(0,d+1):l=[l[0]];break}}}return l.reduceRight((u,h,m)=>{let p,f=!1,y=null,v=null;n&&(p=o&&h.route.id?o[h.route.id]:void 0,y=h.route.errorElement||m1s,c&&(d<0&&m===0?(f=!0,v=null):d===m&&(f=!0,v=h.route.hydrateFallbackElement||null)));let g=t.concat(l.slice(0,m+1)),b=()=>{let j;return p?j=y:f?j=v:h.route.Component?j=_.createElement(h.route.Component,null):h.route.element?j=h.route.element:j=u,_.createElement(f1s,{match:h,routeContext:{outlet:u,matches:g,isDataRoute:n!=null},children:j})};return n&&(h.route.ErrorBoundary||h.route.errorElement||m===0)?_.createElement(p1s,{location:n.location,revalidation:n.revalidation,component:y,error:p,children:b(),routeContext:{outlet:null,matches:g,isDataRoute:!0}}):b()},null)}var nLt=function(s){return s.UseBlocker="useBlocker",s.UseRevalidator="useRevalidator",s.UseNavigateStable="useNavigate",s}(nLt||{}),W3e=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}(W3e||{});function g1s(s){let t=_.useContext(RMe);return t||Gf(!1),t}function y1s(s){let t=_.useContext(eLt);return t||Gf(!1),t}function v1s(s){let t=_.useContext(wC);return t||Gf(!1),t}function rLt(s){let t=v1s(),n=t.matches[t.matches.length-1];return n.route.id||Gf(!1),n.route.id}function b1s(){var s;let t=_.useContext(tLt),n=y1s(W3e.UseRouteError),r=rLt(W3e.UseRouteError);return t!==void 0?t:(s=n.errors)==null?void 0:s[r]}function _1s(){let{router:s}=g1s(nLt.UseNavigateStable),t=rLt(W3e.UseNavigateStable),n=_.useRef(!1);return sLt(()=>{n.current=!0}),_.useCallback(function(a,i){i===void 0&&(i={}),n.current&&(typeof a=="number"?s.navigate(a):s.navigate(a,Xee({fromRouteId:t},i)))},[s,t])}function w1s(s,t){s==null||s.v7_startTransition,s==null||s.v7_relativeSplatPath}function fd(s){let{to:t,replace:n,state:r,relative:a}=s;rW()||Gf(!1);let{future:i,static:l}=_.useContext(IE),{matches:o}=_.useContext(wC),{pathname:c}=ru(),d=Fn(),u=nQe(t,sQe(o,i.v7_relativeSplatPath),c,a==="path"),h=JSON.stringify(u);return _.useEffect(()=>d(JSON.parse(h),{replace:n,state:r,relative:a}),[d,h,a,n,r]),null}function rQe(s){return c1s(s.context)}function Qt(s){Gf(!1)}function j1s(s){let{basename:t="/",children:n=null,location:r,navigationType:a=yM.Pop,navigator:i,static:l=!1,future:o}=s;rW()&&Gf(!1);let c=t.replace(/^\/*/,"/"),d=_.useMemo(()=>({basename:c,navigator:i,static:l,future:Xee({v7_relativeSplatPath:!1},o)}),[c,o,i,l]);typeof r=="string"&&(r=nW(r));let{pathname:u="/",search:h="",hash:m="",state:p=null,key:f="default"}=r,y=_.useMemo(()=>{let v=wH(u,c);return v==null?null:{location:{pathname:v,search:h,hash:m,state:p,key:f},navigationType:a}},[c,u,h,m,p,f,a]);return y==null?null:_.createElement(IE.Provider,{value:d},_.createElement(FMe.Provider,{children:n,value:y}))}function jH(s){let{children:t,location:n}=s;return d1s(i$e(t),n)}new Promise(()=>{});function i$e(s,t){t===void 0&&(t=[]);let n=[];return _.Children.forEach(s,(r,a)=>{if(!_.isValidElement(r))return;let i=[...t,a];if(r.type===_.Fragment){n.push.apply(n,i$e(r.props.children,i));return}r.type!==Qt&&Gf(!1),!r.props.index||!r.props.children||Gf(!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=i$e(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 K3e(){return K3e=Object.assign?Object.assign.bind():function(s){for(var t=1;t=0)&&(n[a]=s[a]);return n}function N1s(s){return!!(s.metaKey||s.altKey||s.ctrlKey||s.shiftKey)}function k1s(s,t){return s.button===0&&(!t||t==="_self")&&!N1s(s)}function o$e(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 S1s(s,t){let n=o$e(s);return t&&t.forEach((r,a)=>{n.has(a)||t.getAll(a).forEach(i=>{n.append(a,i)})}),n}const C1s=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","viewTransition"],A1s=["aria-current","caseSensitive","className","end","style","to","viewTransition","children"],E1s="6";try{window.__reactRouterVersion=E1s}catch{}const T1s=_.createContext({isTransitioning:!1}),M1s="startTransition",vmt=UZe[M1s];function P1s(s){let{basename:t,children:n,future:r,window:a}=s,i=_.useRef();i.current==null&&(i.current=Dvs({window:a,v5Compat:!0}));let l=i.current,[o,c]=_.useState({action:l.action,location:l.location}),{v7_startTransition:d}=r||{},u=_.useCallback(h=>{d&&vmt?vmt(()=>c(h)):c(h)},[c,d]);return _.useLayoutEffect(()=>l.listen(u),[l,u]),_.useEffect(()=>w1s(r),[r]),_.createElement(j1s,{basename:t,children:n,location:o.location,navigationType:o.action,navigator:l,future:r})}const L1s=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",I1s=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,ir=_.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=aLt(t,C1s),{basename:p}=_.useContext(IE),f,y=!1;if(typeof d=="string"&&I1s.test(d)&&(f=d,L1s))try{let j=new URL(window.location.href),S=d.startsWith("//")?new URL(j.protocol+d):new URL(d),C=wH(S.pathname,p);S.origin===j.origin&&C!=null?d=C+S.search+S.hash:y=!0}catch{}let v=i1s(d,{relative:a}),g=R1s(d,{replace:l,state:o,target:c,preventScrollReset:u,relative:a,viewTransition:h});function b(j){r&&r(j),j.defaultPrevented||g(j)}return _.createElement("a",K3e({},m,{href:f||v,onClick:y||i?r:b,ref:n,target:c}))}),o6=_.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=aLt(t,A1s),m=OMe(c,{relative:h.relative}),p=ru(),f=_.useContext(eLt),{navigator:y,basename:v}=_.useContext(IE),g=f!=null&&F1s(m)&&d===!0,b=y.encodeLocation?y.encodeLocation(m).pathname:m.pathname,j=p.pathname,S=f&&f.navigation&&f.navigation.location?f.navigation.location.pathname:null;a||(j=j.toLowerCase(),S=S?S.toLowerCase():null,b=b.toLowerCase()),S&&v&&(S=wH(S,v)||S);const C=b!=="/"&&b.endsWith("/")?b.length-1:b.length;let E=j===b||!l&&j.startsWith(b)&&j.charAt(C)==="/",P=S!=null&&(S===b||!l&&S.startsWith(b)&&S.charAt(b.length)==="/"),M={isActive:E,isPending:P,isTransitioning:g},I=E?r:void 0,D;typeof i=="function"?D=i(M):D=[i,E?"active":null,P?"pending":null,g?"transitioning":null].filter(Boolean).join(" ");let O=typeof o=="function"?o(M):o;return _.createElement(ir,K3e({},h,{"aria-current":I,className:D,ref:n,style:O,to:c,viewTransition:d}),typeof u=="function"?u(M):u)});var l$e;(function(s){s.UseScrollRestoration="useScrollRestoration",s.UseSubmit="useSubmit",s.UseSubmitFetcher="useSubmitFetcher",s.UseFetcher="useFetcher",s.useViewTransitionState="useViewTransitionState"})(l$e||(l$e={}));var bmt;(function(s){s.UseFetcher="useFetcher",s.UseFetchers="useFetchers",s.UseScrollRestoration="useScrollRestoration"})(bmt||(bmt={}));function D1s(s){let t=_.useContext(RMe);return t||Gf(!1),t}function R1s(s,t){let{target:n,replace:r,state:a,preventScrollReset:i,relative:l,viewTransition:o}=t===void 0?{}:t,c=Fn(),d=ru(),u=OMe(s,{relative:l});return _.useCallback(h=>{if(k1s(h,n)){h.preventDefault();let m=r!==void 0?r:H3e(d)===H3e(u);c(s,{replace:m,state:a,preventScrollReset:i,relative:l,viewTransition:o})}},[d,c,u,r,a,n,s,i,l,o])}function Yl(s){let t=_.useRef(o$e(s)),n=_.useRef(!1),r=ru(),a=_.useMemo(()=>S1s(r.search,n.current?null:t.current),[r.search]),i=Fn(),l=_.useCallback((o,c)=>{const d=o$e(typeof o=="function"?o(a):o);n.current=!0,i("?"+d,c)},[i,a]);return[a,l]}function F1s(s,t){t===void 0&&(t={});let n=_.useContext(T1s);n==null&&Gf(!1);let{basename:r}=D1s(l$e.useViewTransitionState),a=OMe(s,{relative:t.relative});if(!n.isTransitioning)return!1;let i=wH(n.currentLocation.pathname,r)||n.currentLocation.pathname,l=wH(n.nextLocation.pathname,r)||n.nextLocation.pathname;return G3e(a.pathname,l)!=null||G3e(a.pathname,i)!=null}var O1s=typeof Element<"u",z1s=typeof Map=="function",B1s=typeof Set=="function",U1s=typeof ArrayBuffer=="function"&&!!ArrayBuffer.isView;function g4e(s,t){if(s===t)return!0;if(s&&t&&typeof s=="object"&&typeof t=="object"){if(s.constructor!==t.constructor)return!1;var n,r,a;if(Array.isArray(s)){if(n=s.length,n!=t.length)return!1;for(r=n;r--!==0;)if(!g4e(s[r],t[r]))return!1;return!0}var i;if(z1s&&s instanceof Map&&t instanceof Map){if(s.size!==t.size)return!1;for(i=s.entries();!(r=i.next()).done;)if(!t.has(r.value[0]))return!1;for(i=s.entries();!(r=i.next()).done;)if(!g4e(r.value[1],t.get(r.value[0])))return!1;return!0}if(B1s&&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(U1s&&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(O1s&&s instanceof Element)return!1;for(r=n;r--!==0;)if(!((a[r]==="_owner"||a[r]==="__v"||a[r]==="__o")&&s.$$typeof)&&!g4e(s[a[r]],t[a[r]]))return!1;return!0}return s!==s&&t!==t}var q1s=function(t,n){try{return g4e(t,n)}catch(r){if((r.message||"").match(/stack|recursion/i))return console.warn("react-fast-compare cannot handle circular refs"),!1;throw r}};const $1s=_d(q1s);var V1s=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}},H1s=V1s;const _mt=_d(H1s);var G1s=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))(iLt||{}),ZFe={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"]}},wmt=Object.values(iLt),aQe={accesskey:"accessKey",charset:"charSet",class:"className",contenteditable:"contentEditable",contextmenu:"contextMenu","http-equiv":"httpEquiv",itemprop:"itemProp",tabindex:"tabIndex"},K1s=Object.entries(aQe).reduce((s,[t,n])=>(s[n]=t,s),{}),aS="data-rh",_$={DEFAULT_TITLE:"defaultTitle",DEFER:"defer",ENCODE_SPECIAL_CHARACTERS:"encodeSpecialCharacters",ON_CHANGE_CLIENT_STATE:"onChangeClientState",TITLE_TEMPLATE:"titleTemplate",PRIORITIZE_SEO_TAGS:"prioritizeSeoTags"},w$=(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},Y1s=s=>{let t=w$(s,"title");const n=w$(s,_$.TITLE_TEMPLATE);if(Array.isArray(t)&&(t=t.join("")),n&&t)return n.replace(/%s/g,()=>t);const r=w$(s,_$.DEFAULT_TITLE);return t||r||void 0},Z1s=s=>w$(s,_$.ON_CHANGE_CLIENT_STATE)||(()=>{}),XFe=(s,t)=>t.filter(n=>typeof n[s]<"u").map(n=>n[s]).reduce((n,r)=>({...n,...r}),{}),X1s=(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),TY=(s,t,n)=>{const r={};return n.filter(a=>Array.isArray(a[s])?!0:(typeof a[s]<"u"&&Q1s(`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:X1s(["href"],s),bodyAttributes:XFe("bodyAttributes",s),defer:w$(s,_$.DEFER),encode:w$(s,_$.ENCODE_SPECIAL_CHARACTERS),htmlAttributes:XFe("htmlAttributes",s),linkTags:TY("link",["rel","href"],s),metaTags:TY("meta",["name","charset","http-equiv","property","itemprop"],s),noscriptTags:TY("noscript",["innerHTML"],s),onChangeClientState:Z1s(s),scriptTags:TY("script",["src","innerHTML"],s),styleTags:TY("style",["cssText"],s),title:Y1s(s),titleAttributes:XFe("titleAttributes",s),prioritizeSeoTags:J1s(s,_$.PRIORITIZE_SEO_TAGS)}),oLt=s=>Array.isArray(s)?s.join(""):s,tbs=(s,t)=>{const n=Object.keys(s);for(let r=0;rArray.isArray(s)?s.reduce((n,r)=>(tbs(r,t)?n.priority.push(r):n.default.push(r),n),{priority:[],default:[]}):{default:s,priority:[]},jmt=(s,t)=>({...s,[t]:void 0}),sbs=["noscript","script","style"],c$e=(s,t=!0)=>t===!1?String(s):String(s).replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'"),lLt=s=>Object.keys(s).reduce((t,n)=>{const r=typeof s[n]<"u"?`${n}="${s[n]}"`:`${n}`;return t?`${t} ${r}`:r},""),nbs=(s,t,n,r)=>{const a=lLt(n),i=oLt(t);return a?`<${s} ${aS}="true" ${a}>${c$e(i,r)}`:`<${s} ${aS}="true">${c$e(i,r)}`},rbs=(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}="${c$e(i[u],n)}"`;return d?`${d} ${h}`:h},""),o=i.innerHTML||i.cssText||"",c=sbs.indexOf(s)===-1;return`${r}<${s} ${aS}="true" ${l}${c?"/>":`>${o}`}`},""),cLt=(s,t={})=>Object.keys(s).reduce((n,r)=>{const a=aQe[r];return n[a||r]=s[r],n},t),abs=(s,t,n)=>{const r={key:t,[aS]:!0},a=cLt(n,r);return[Dt.createElement("title",a,t)]},y4e=(s,t)=>t.map((n,r)=>{const a={key:r,[aS]:!0};return Object.keys(n).forEach(i=>{const o=aQe[i]||i;if(o==="innerHTML"||o==="cssText"){const c=n.innerHTML||n.cssText;a.dangerouslySetInnerHTML={__html:c}}else a[o]=n[i]}),Dt.createElement(s,a)}),M2=(s,t,n=!0)=>{switch(s){case"title":return{toComponent:()=>abs(s,t.title,t.titleAttributes),toString:()=>nbs(s,t.title,t.titleAttributes,n)};case"bodyAttributes":case"htmlAttributes":return{toComponent:()=>cLt(t),toString:()=>lLt(t)};default:return{toComponent:()=>y4e(s,t),toString:()=>rbs(s,t,n)}}},ibs=({metaTags:s,linkTags:t,scriptTags:n,encode:r})=>{const a=QFe(s,ZFe.meta),i=QFe(t,ZFe.link),l=QFe(n,ZFe.script);return{priorityMethods:{toComponent:()=>[...y4e("meta",a.priority),...y4e("link",i.priority),...y4e("script",l.priority)],toString:()=>`${M2("meta",a.priority,r)} ${M2("link",i.priority,r)} ${M2("script",l.priority,r)}`},metaTags:a.default,linkTags:i.default,scriptTags:l.default}},obs=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}=ibs(s)),{priority:p,base:M2("base",t,r),bodyAttributes:M2("bodyAttributes",n,r),htmlAttributes:M2("htmlAttributes",a,r),link:M2("link",u,r),meta:M2("meta",h,r),noscript:M2("noscript",i,r),script:M2("script",m,r),style:M2("style",l,r),title:M2("title",{title:o,titleAttributes:c},r)}},d$e=obs,rle=[],dLt=!!(typeof window<"u"&&window.document&&window.document.createElement),u$e=class{constructor(s,t){Pr(this,"instances",[]);Pr(this,"canUseDOM",dLt);Pr(this,"context");Pr(this,"value",{setHelmet:s=>{this.context.helmet=s},helmetInstances:{get:()=>this.canUseDOM?rle:this.instances,add:s=>{(this.canUseDOM?rle:this.instances).push(s)},remove:s=>{const t=(this.canUseDOM?rle:this.instances).indexOf(s);(this.canUseDOM?rle:this.instances).splice(t,1)}}});this.context=s,this.canUseDOM=t||!1,t||(s.helmet=d$e({baseTag:[],bodyAttributes:{},encodeSpecialCharacters:!0,htmlAttributes:{},linkTags:[],metaTags:[],noscriptTags:[],scriptTags:[],styleTags:[],title:"",titleAttributes:{}}))}},lbs={},uLt=Dt.createContext(lbs),VF,hLt=(VF=class extends _.Component{constructor(n){super(n);Pr(this,"helmetData");this.helmetData=new u$e(this.props.context||{},VF.canUseDOM)}render(){return Dt.createElement(uLt.Provider,{value:this.helmetData.value},this.props.children)}},Pr(VF,"canUseDOM",dLt),VF),mB=(s,t)=>{const n=document.head||document.querySelector("head"),r=n.querySelectorAll(`${s}[${aS}]`),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(aS,"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}},h$e=(s,t)=>{const n=document.getElementsByTagName(s)[0];if(!n)return;const r=n.getAttribute(aS),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(aS):n.getAttribute(aS)!==l.join(",")&&n.setAttribute(aS,l.join(","))},cbs=(s,t)=>{typeof s<"u"&&document.title!==s&&(document.title=oLt(s)),h$e("title",t)},Nmt=(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;h$e("body",r),h$e("html",a),cbs(h,m);const p={baseTag:mB("base",n),linkTags:mB("link",i),metaTags:mB("meta",l),noscriptTags:mB("noscript",o),scriptTags:mB("script",d),styleTags:mB("style",u)},f={},y={};Object.keys(p).forEach(v=>{const{newTags:g,oldTags:b}=p[v];g.length&&(f[v]=g),b.length&&(y[v]=p[v].oldTags)}),t&&t(),c(s,f,y)},MY=null,dbs=s=>{MY&&cancelAnimationFrame(MY),s.defer?MY=requestAnimationFrame(()=>{Nmt(s,()=>{MY=null})}):(Nmt(s),MY=null)},ubs=dbs,kmt=class extends _.Component{constructor(){super(...arguments);Pr(this,"rendered",!1)}shouldComponentUpdate(t){return!W1s(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=ebs(t.get().map(i=>{const l={...i.props};return delete l.context,l}));hLt.canUseDOM?ubs(a):d$e&&(r=d$e(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}},zUe,ul=(zUe=class extends _.Component{shouldComponentUpdate(s){return!$1s(jmt(this.props,"helmetData"),jmt(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 _mt(wmt.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 ${wmt.join(", ")} are allowed. Helmet does not support rendering <${s.type}> elements. Refer to our API for more information.`),_mt(!t||typeof t=="string"||Array.isArray(t)&&!t.some(n=>typeof n!="string"),`Helmet expects a string as a child of <${s.type}>. Did you forget to wrap your children in braces? ( <${s.type}>{\`\`} ) Refer to our API for more information.`),!0}mapChildrenToProps(s,t){let n={};return Dt.Children.forEach(s,r=>{if(!r||!r.props)return;const{children:a,...i}=r.props,l=Object.keys(i).reduce((c,d)=>(c[K1s[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 u$e)){const a=r;r=new u$e(a.context,!0),delete n.helmetData}return r?Dt.createElement(kmt,{...n,context:r.value}):Dt.createElement(uLt.Consumer,null,a=>Dt.createElement(kmt,{...n,context:a}))}},Pr(zUe,"defaultProps",{defer:!0,encodeSpecialCharacters:!0,prioritizeSeoTags:!1}),zUe);const hbs=s=>{let t;return s?t=s:typeof fetch>"u"?t=(...n)=>za(async()=>{const{default:r}=await Promise.resolve().then(()=>aW);return{default:r}},void 0).then(({default:r})=>r(...n)):t=fetch,(...n)=>t(...n)};class iQe extends Error{constructor(t,n="FunctionsError",r){super(t),this.name=n,this.context=r}}class mbs extends iQe{constructor(t){super("Failed to send a request to the Edge Function","FunctionsFetchError",t)}}class pbs extends iQe{constructor(t){super("Relay Error invoking the Edge Function","FunctionsRelayError",t)}}class Mre extends iQe{constructor(t){super("Edge Function returned a non-2xx status code","FunctionsHttpError",t)}}var m$e;(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"})(m$e||(m$e={}));var fbs=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 xbs{constructor(t,{headers:n={},customFetch:r,region:a=m$e.Any}={}){this.url=t,this.headers=n,this.region=a,this.fetch=hbs(r)}setAuth(t){this.headers.Authorization=`Bearer ${t}`}invoke(t,n={}){var r;return fbs(this,void 0,void 0,function*(){try{const{headers:a,method:i,body:l}=n;let o={},{region:c}=n;c||(c=this.region),c&&c!=="any"&&(o["x-region"]=c);let d;l&&(a&&!Object.prototype.hasOwnProperty.call(a,"Content-Type")||!a)&&(typeof Blob<"u"&&l instanceof Blob||l instanceof ArrayBuffer?(o["Content-Type"]="application/octet-stream",d=l):typeof l=="string"?(o["Content-Type"]="text/plain",d=l):typeof FormData<"u"&&l instanceof FormData?d=l:(o["Content-Type"]="application/json",d=JSON.stringify(l)));const u=yield this.fetch(`${this.url}/${t}`,{method:i||"POST",headers:Object.assign(Object.assign(Object.assign({},o),this.headers),a),body:d}).catch(f=>{throw new mbs(f)}),h=u.headers.get("x-relay-error");if(h&&h==="true")throw new pbs(u);if(!u.ok)throw new Mre(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 __={},oQe={},zMe={},Pre={},BMe={},UMe={},gbs=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")},NH=gbs();const ybs=NH.fetch,mLt=NH.fetch.bind(NH),pLt=NH.Headers,vbs=NH.Request,bbs=NH.Response,aW=Object.freeze(Object.defineProperty({__proto__:null,Headers:pLt,Request:vbs,Response:bbs,default:mLt,fetch:ybs},Symbol.toStringTag,{value:"Module"})),_bs=Chs(aW);var qMe={};Object.defineProperty(qMe,"__esModule",{value:!0});let wbs=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}};qMe.default=wbs;var fLt=Cp&&Cp.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(UMe,"__esModule",{value:!0});const jbs=fLt(_bs),Nbs=fLt(qMe);let kbs=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=jbs.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 g=await i.text();g===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?u=g:u=JSON.parse(g))}const y=(l=this.headers.Prefer)===null||l===void 0?void 0:l.match(/count=(exact|planned|estimated)/),v=(o=i.headers.get("content-range"))===null||o===void 0?void 0:o.split("/");y&&v&&v.length>1&&(h=parseInt(v[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(u)&&(u.length>1?(d={code:"PGRST116",details:`Results contain ${u.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},u=null,h=null,m=406,p="Not Acceptable"):u.length===1?u=u[0]:u=null)}else{const y=await i.text();try{d=JSON.parse(y),Array.isArray(d)&&i.status===404&&(u=[],d=null,m=200,p="OK")}catch{i.status===404&&y===""?(m=204,p="No Content"):d={message:y}}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 Nbs.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}};UMe.default=kbs;var Sbs=Cp&&Cp.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(BMe,"__esModule",{value:!0});const Cbs=Sbs(UMe);let Abs=class extends Cbs.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}};BMe.default=Abs;var Ebs=Cp&&Cp.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Pre,"__esModule",{value:!0});const Tbs=Ebs(BMe);let Mbs=class extends Tbs.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}};Pre.default=Mbs;var Pbs=Cp&&Cp.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(zMe,"__esModule",{value:!0});const PY=Pbs(Pre);let Lbs=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 PY.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 PY.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 PY.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 PY.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 PY.default({method:n,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};zMe.default=Lbs;var $Me={},VMe={};Object.defineProperty(VMe,"__esModule",{value:!0});VMe.version=void 0;VMe.version="0.0.0-automated";Object.defineProperty($Me,"__esModule",{value:!0});$Me.DEFAULT_HEADERS=void 0;const Ibs=VMe;$Me.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${Ibs.version}`};var xLt=Cp&&Cp.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(oQe,"__esModule",{value:!0});const Dbs=xLt(zMe),Rbs=xLt(Pre),Fbs=$Me;let Obs=class gLt{constructor(t,{headers:n={},schema:r,fetch:a}={}){this.url=t,this.headers=Object.assign(Object.assign({},Fbs.DEFAULT_HEADERS),n),this.schemaName=r,this.fetch=a}from(t){const n=new URL(`${this.url}/${t}`);return new Dbs.default(n,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(t){return new gLt(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 Rbs.default({method:l,url:o,headers:d,schema:this.schemaName,body:c,fetch:this.fetch,allowEmpty:!1})}};oQe.default=Obs;var iW=Cp&&Cp.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(__,"__esModule",{value:!0});__.PostgrestError=__.PostgrestBuilder=__.PostgrestTransformBuilder=__.PostgrestFilterBuilder=__.PostgrestQueryBuilder=__.PostgrestClient=void 0;const yLt=iW(oQe);__.PostgrestClient=yLt.default;const vLt=iW(zMe);__.PostgrestQueryBuilder=vLt.default;const bLt=iW(Pre);__.PostgrestFilterBuilder=bLt.default;const _Lt=iW(BMe);__.PostgrestTransformBuilder=_Lt.default;const wLt=iW(UMe);__.PostgrestBuilder=wLt.default;const jLt=iW(qMe);__.PostgrestError=jLt.default;var zbs=__.default={PostgrestClient:yLt.default,PostgrestQueryBuilder:vLt.default,PostgrestFilterBuilder:bLt.default,PostgrestTransformBuilder:_Lt.default,PostgrestBuilder:wLt.default,PostgrestError:jLt.default};const{PostgrestClient:Bbs,PostgrestQueryBuilder:pbr,PostgrestFilterBuilder:fbr,PostgrestTransformBuilder:xbr,PostgrestBuilder:gbr,PostgrestError:ybr}=zbs;let p$e;typeof window>"u"?p$e=require("ws"):p$e=window.WebSocket;const Ubs=p$e,qbs="2.11.10",$bs={"X-Client-Info":`realtime-js/${qbs}`},Vbs="1.0.0",NLt=1e4,Hbs=1e3;var j$;(function(s){s[s.connecting=0]="connecting",s[s.open=1]="open",s[s.closing=2]="closing",s[s.closed=3]="closed"})(j$||(j$={}));var J1;(function(s){s.closed="closed",s.errored="errored",s.joined="joined",s.joining="joining",s.leaving="leaving"})(J1||(J1={}));var Gk;(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"})(Gk||(Gk={}));var f$e;(function(s){s.websocket="websocket"})(f$e||(f$e={}));var QR;(function(s){s.Connecting="connecting",s.Open="open",s.Closing="closing",s.Closed="closed"})(QR||(QR={}));class Gbs{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 kLt{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 Hm;(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"})(Hm||(Hm={}));const Smt=(s,t,n={})=>{var r;const a=(r=n.skipTypes)!==null&&r!==void 0?r:[];return Object.keys(t).reduce((i,l)=>(i[l]=Wbs(l,s,t,a),i),{})},Wbs=(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)?SLt(i,l):x$e(l)},SLt=(s,t)=>{if(s.charAt(0)==="_"){const n=s.slice(1,s.length);return Xbs(t,n)}switch(s){case Hm.bool:return Kbs(t);case Hm.float4:case Hm.float8:case Hm.int2:case Hm.int4:case Hm.int8:case Hm.numeric:case Hm.oid:return Ybs(t);case Hm.json:case Hm.jsonb:return Zbs(t);case Hm.timestamp:return Qbs(t);case Hm.abstime:case Hm.date:case Hm.daterange:case Hm.int4range:case Hm.int8range:case Hm.money:case Hm.reltime:case Hm.text:case Hm.time:case Hm.timestamptz:case Hm.timetz:case Hm.tsrange:case Hm.tstzrange:return x$e(t);default:return x$e(t)}},x$e=s=>s,Kbs=s=>{switch(s){case"t":return!0;case"f":return!1;default:return s}},Ybs=s=>{if(typeof s=="string"){const t=parseFloat(s);if(!Number.isNaN(t))return t}return s},Zbs=s=>{if(typeof s=="string")try{return JSON.parse(s)}catch(t){return console.log(`JSON parse error: ${t}`),s}return s},Xbs=(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=>SLt(t,o))}return s},Qbs=s=>typeof s=="string"?s.replace(" ","T"):s,CLt=s=>{let t=s;return t=t.replace(/^ws/i,"http"),t=t.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),t.replace(/\/+$/,"")};class JFe{constructor(t,n,r={},a=NLt){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 Cmt;(function(s){s.SYNC="sync",s.JOIN="join",s.LEAVE="leave"})(Cmt||(Cmt={}));class xJ{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=xJ.syncState(this.state,a,i,l),this.pendingDiffs.forEach(c=>{this.state=xJ.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=xJ.syncDiff(this.state,a,i,l),o())}),this.onJoin((a,i,l)=>{this.channel._trigger("presence",{event:"join",key:a,currentPresences:i,newPresences:l})}),this.onLeave((a,i,l)=>{this.channel._trigger("presence",{event:"leave",key:a,currentPresences:i,leftPresences:l})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(t,n,r,a){const i=this.cloneDeep(t),l=this.transformState(n),o={},c={};return this.map(i,(d,u)=>{l[d]||(c[d]=u)}),this.map(l,(d,u)=>{const h=i[d];if(h){const m=u.map(v=>v.presence_ref),p=h.map(v=>v.presence_ref),f=u.filter(v=>p.indexOf(v.presence_ref)<0),y=h.filter(v=>m.indexOf(v.presence_ref)<0);f.length>0&&(o[d]=f),y.length>0&&(c[d]=y)}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 Amt;(function(s){s.ALL="*",s.INSERT="INSERT",s.UPDATE="UPDATE",s.DELETE="DELETE"})(Amt||(Amt={}));var Emt;(function(s){s.BROADCAST="broadcast",s.PRESENCE="presence",s.POSTGRES_CHANGES="postgres_changes",s.SYSTEM="system"})(Emt||(Emt={}));var z3;(function(s){s.SUBSCRIBED="SUBSCRIBED",s.TIMED_OUT="TIMED_OUT",s.CLOSED="CLOSED",s.CHANNEL_ERROR="CHANNEL_ERROR"})(z3||(z3={}));class lQe{constructor(t,n={config:{}},r){this.topic=t,this.params=n,this.socket=r,this.bindings={},this.state=J1.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 JFe(this,Gk.join,this.params,this.timeout),this.rejoinTimer=new kLt(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=J1.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=J1.closed,this.socket._remove(this)}),this._onError(a=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,a),this.state=J1.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=J1.errored,this.rejoinTimer.scheduleTimeout())}),this._on(Gk.reply,{},(a,i)=>{this._trigger(this._replyEventName(i),a)}),this.presence=new xJ(this),this.broadcastEndpointURL=CLt(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(z3.CHANNEL_ERROR,u)),this._onClose(()=>t==null?void 0:t(z3.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(z3.SUBSCRIBED);return}else{const m=this.bindings.postgres_changes,p=(h=m==null?void 0:m.length)!==null&&h!==void 0?h:0,f=[];for(let y=0;y{this.state=J1.errored,t==null||t(z3.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(u).join(", ")||"error")))}).receive("timeout",()=>{t==null||t(z3.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=J1.leaving;const n=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(Gk.close,"leave",this._joinRef())};return this.joinPush.destroy(),new Promise(r=>{const a=new JFe(this,Gk.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 JFe(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}=Gk;if(r&&[o,c,d,u].indexOf(l)>=0&&r!==this._joinRef())return;let m=this._onMessage(l,n,r);if(n&&!m)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(l)?(a=this.bindings.postgres_changes)===null||a===void 0||a.filter(p=>{var f,y,v;return((f=p.filter)===null||f===void 0?void 0:f.event)==="*"||((v=(y=p.filter)===null||y===void 0?void 0:y.event)===null||v===void 0?void 0:v.toLocaleLowerCase())===l}).map(p=>p.callback(m,r)):(i=this.bindings[l])===null||i===void 0||i.filter(p=>{var f,y,v,g,b,j;if(["broadcast","presence","postgres_changes"].includes(l))if("id"in p){const S=p.id,C=(f=p.filter)===null||f===void 0?void 0:f.event;return S&&((y=n.ids)===null||y===void 0?void 0:y.includes(S))&&(C==="*"||(C==null?void 0:C.toLocaleLowerCase())===((v=n.data)===null||v===void 0?void 0:v.type.toLocaleLowerCase()))}else{const S=(b=(g=p==null?void 0:p.filter)===null||g===void 0?void 0:g.event)===null||b===void 0?void 0:b.toLocaleLowerCase();return S==="*"||S===((j=n==null?void 0:n.event)===null||j===void 0?void 0:j.toLocaleLowerCase())}else return p.type.toLocaleLowerCase()===l}).map(p=>{if(typeof m=="object"&&"ids"in m){const f=m.data,{schema:y,table:v,commit_timestamp:g,type:b,errors:j}=f;m=Object.assign(Object.assign({},{schema:y,table:v,commit_timestamp:g,eventType:b,new:{},old:{},errors:j}),this._getPayloadRecords(f))}p.callback(m,r)})}_isClosed(){return this.state===J1.closed}_isJoined(){return this.state===J1.joined}_isJoining(){return this.state===J1.joining}_isLeaving(){return this.state===J1.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&&lQe.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(Gk.close,{},t)}_onError(t){this._on(Gk.error,{},n=>t(n))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(t=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=J1.joining,this.joinPush.resend(t))}_getPayloadRecords(t){const n={new:{},old:{}};return(t.type==="INSERT"||t.type==="UPDATE")&&(n.new=Smt(t.columns,t.record)),(t.type==="UPDATE"||t.type==="DELETE")&&(n.old=Smt(t.columns,t.old_record)),n}}const Tmt=()=>{},Jbs=` addEventListener("message", (e) => { if (e.data.event === "start") { setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); } });`;class e_s{constructor(t,n){var r;this.accessTokenValue=null,this.apiKey=null,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers=$bs,this.params={},this.timeout=NLt,this.heartbeatIntervalMs=25e3,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=Tmt,this.ref=0,this.logger=Tmt,this.conn=null,this.sendBuffer=[],this.serializer=new Gbs,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._resolveFetch=i=>{let l;return i?l=i:typeof fetch>"u"?l=(...o)=>za(async()=>{const{default:c}=await Promise.resolve().then(()=>aW);return{default:c}},void 0).then(({default:c})=>c(...o)):l=fetch,(...o)=>l(...o)},this.endPoint=`${t}/${f$e.websocket}`,this.httpEndpoint=CLt(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 kLt(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=Ubs),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 t_s(this.endpointURL(),void 0,{close:()=>{this.conn=null}})}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:Vbs}))}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 j$.connecting:return QR.Connecting;case j$.open:return QR.Open;case j$.closing:return QR.Closing;default:return QR.Closed}}isConnected(){return this.connectionState()===QR.Open}channel(t,n={config:{}}){const r=`realtime:${t}`,a=this.getChannels().find(i=>i.topic===r);if(a)return a;{const i=new lQe(`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(Gk.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(Hbs,"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(Gk.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([Jbs],{type:"application/javascript"});n=URL.createObjectURL(r)}return n}}class t_s{constructor(t,n,r){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=j$.connecting,this.send=()=>{},this.url=null,this.url=t,this.close=r.close}}class cQe extends Error{constructor(t){super(t),this.__isStorageError=!0,this.name="StorageError"}}function oy(s){return typeof s=="object"&&s!==null&&"__isStorageError"in s}class s_s extends cQe{constructor(t,n){super(t),this.name="StorageApiError",this.status=n}toJSON(){return{name:this.name,message:this.message,status:this.status}}}class g$e extends cQe{constructor(t,n){super(t),this.name="StorageUnknownError",this.originalError=n}}var n_s=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 ALt=s=>{let t;return s?t=s:typeof fetch>"u"?t=(...n)=>za(async()=>{const{default:r}=await Promise.resolve().then(()=>aW);return{default:r}},void 0).then(({default:r})=>r(...n)):t=fetch,(...n)=>t(...n)},r_s=()=>n_s(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield za(()=>Promise.resolve().then(()=>aW),void 0)).Response:Response}),y$e=s=>{if(Array.isArray(s))return s.map(n=>y$e(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]=y$e(r)}),t};var O9=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 eOe=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),a_s=(s,t,n)=>O9(void 0,void 0,void 0,function*(){const r=yield r_s();s instanceof r&&!(n!=null&&n.noResolveJson)?s.json().then(a=>{t(new s_s(eOe(a),s.status||500))}).catch(a=>{t(new g$e(eOe(a),a))}):t(new g$e(eOe(s),s))}),i_s=(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 Lre(s,t,n,r,a,i){return O9(this,void 0,void 0,function*(){return new Promise((l,o)=>{s(n,i_s(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=>a_s(c,o,r))})})}function Y3e(s,t,n,r){return O9(this,void 0,void 0,function*(){return Lre(s,"GET",t,n,r)})}function l6(s,t,n,r,a){return O9(this,void 0,void 0,function*(){return Lre(s,"POST",t,r,a,n)})}function o_s(s,t,n,r,a){return O9(this,void 0,void 0,function*(){return Lre(s,"PUT",t,r,a,n)})}function l_s(s,t,n,r){return O9(this,void 0,void 0,function*(){return Lre(s,"HEAD",t,Object.assign(Object.assign({},n),{noResolveJson:!0}),r)})}function ELt(s,t,n,r,a){return O9(this,void 0,void 0,function*(){return Lre(s,"DELETE",t,r,a,n)})}var e_=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 c_s={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},Mmt={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class d_s{constructor(t,n={},r,a){this.url=t,this.headers=n,this.bucketId=r,this.fetch=ALt(a)}uploadOrUpdate(t,n,r,a){return e_(this,void 0,void 0,function*(){try{let i;const l=Object.assign(Object.assign({},Mmt),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(oy(i))return{data:null,error:i};throw i}})}upload(t,n,r){return e_(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",t,n,r)})}uploadToSignedUrl(t,n,r,a){return e_(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:Mmt.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(oy(c))return{data:null,error:c};throw c}})}createSignedUploadUrl(t,n){return e_(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 l6(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 cQe("No token returned by API");return{data:{signedUrl:l.toString(),path:t,token:o},error:null}}catch(r){if(oy(r))return{data:null,error:r};throw r}})}update(t,n,r){return e_(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",t,n,r)})}move(t,n,r){return e_(this,void 0,void 0,function*(){try{return{data:yield l6(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(oy(a))return{data:null,error:a};throw a}})}copy(t,n,r){return e_(this,void 0,void 0,function*(){try{return{data:{path:(yield l6(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(oy(a))return{data:null,error:a};throw a}})}createSignedUrl(t,n,r){return e_(this,void 0,void 0,function*(){try{let a=this._getFinalPath(t),i=yield l6(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(oy(a))return{data:null,error:a};throw a}})}createSignedUrls(t,n,r){return e_(this,void 0,void 0,function*(){try{const a=yield l6(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(oy(a))return{data:null,error:a};throw a}})}download(t,n){return e_(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 Y3e(this.fetch,`${this.url}/${a}/${o}${l}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(o){if(oy(o))return{data:null,error:o};throw o}})}info(t){return e_(this,void 0,void 0,function*(){const n=this._getFinalPath(t);try{const r=yield Y3e(this.fetch,`${this.url}/object/info/${n}`,{headers:this.headers});return{data:y$e(r),error:null}}catch(r){if(oy(r))return{data:null,error:r};throw r}})}exists(t){return e_(this,void 0,void 0,function*(){const n=this._getFinalPath(t);try{return yield l_s(this.fetch,`${this.url}/object/${n}`,{headers:this.headers}),{data:!0,error:null}}catch(r){if(oy(r)&&r instanceof g$e){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 e_(this,void 0,void 0,function*(){try{return{data:yield ELt(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:t},{headers:this.headers}),error:null}}catch(n){if(oy(n))return{data:null,error:n};throw n}})}list(t,n,r){return e_(this,void 0,void 0,function*(){try{const a=Object.assign(Object.assign(Object.assign({},c_s),n),{prefix:t||""});return{data:yield l6(this.fetch,`${this.url}/object/list/${this.bucketId}`,a,{headers:this.headers},r),error:null}}catch(a){if(oy(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 u_s="2.7.1",h_s={"X-Client-Info":`storage-js/${u_s}`};var pB=function(s,t,n,r){function a(i){return i instanceof n?i:new n(function(l){l(i)})}return new(n||(n=Promise))(function(i,l){function o(u){try{d(r.next(u))}catch(h){l(h)}}function c(u){try{d(r.throw(u))}catch(h){l(h)}}function d(u){u.done?i(u.value):a(u.value).then(o,c)}d((r=r.apply(s,t||[])).next())})};class m_s{constructor(t,n={},r){this.url=t,this.headers=Object.assign(Object.assign({},h_s),n),this.fetch=ALt(r)}listBuckets(){return pB(this,void 0,void 0,function*(){try{return{data:yield Y3e(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(t){if(oy(t))return{data:null,error:t};throw t}})}getBucket(t){return pB(this,void 0,void 0,function*(){try{return{data:yield Y3e(this.fetch,`${this.url}/bucket/${t}`,{headers:this.headers}),error:null}}catch(n){if(oy(n))return{data:null,error:n};throw n}})}createBucket(t,n={public:!1}){return pB(this,void 0,void 0,function*(){try{return{data:yield l6(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(oy(r))return{data:null,error:r};throw r}})}updateBucket(t,n){return pB(this,void 0,void 0,function*(){try{return{data:yield o_s(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(oy(r))return{data:null,error:r};throw r}})}emptyBucket(t){return pB(this,void 0,void 0,function*(){try{return{data:yield l6(this.fetch,`${this.url}/bucket/${t}/empty`,{},{headers:this.headers}),error:null}}catch(n){if(oy(n))return{data:null,error:n};throw n}})}deleteBucket(t){return pB(this,void 0,void 0,function*(){try{return{data:yield ELt(this.fetch,`${this.url}/bucket/${t}`,{},{headers:this.headers}),error:null}}catch(n){if(oy(n))return{data:null,error:n};throw n}})}}class p_s extends m_s{constructor(t,n={},r){super(t,n,r)}from(t){return new d_s(this.url,this.headers,t,this.fetch)}}const f_s="2.49.10";let lX="";typeof Deno<"u"?lX="deno":typeof document<"u"?lX="web":typeof navigator<"u"&&navigator.product==="ReactNative"?lX="react-native":lX="node";const x_s={"X-Client-Info":`supabase-js-${lX}/${f_s}`},g_s={headers:x_s},y_s={schema:"public"},v_s={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},b_s={};var __s=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 w_s=s=>{let t;return s?t=s:typeof fetch>"u"?t=mLt:t=fetch,(...n)=>t(...n)},j_s=()=>typeof Headers>"u"?pLt:Headers,N_s=(s,t,n)=>{const r=w_s(n),a=j_s();return(i,l)=>__s(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 k_s=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 S_s(s){return s.endsWith("/")?s:s+"/"}function C_s(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:()=>k_s(this,void 0,void 0,function*(){return""})};return s.accessToken?m.accessToken=s.accessToken:delete m.accessToken,m}const TLt="2.69.1",pU=30*1e3,v$e=3,tOe=v$e*pU,A_s="http://localhost:9999",E_s="supabase.auth.token",T_s={"X-Client-Info":`gotrue-js/${TLt}`},b$e="X-Supabase-Api-Version",MLt={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},M_s=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,P_s=6e5;class dQe extends Error{constructor(t,n,r){super(t),this.__isAuthError=!0,this.name="AuthError",this.status=n,this.code=r}}function Yc(s){return typeof s=="object"&&s!==null&&"__isAuthError"in s}class L_s extends dQe{constructor(t,n,r){super(t,n,r),this.name="AuthApiError",this.status=n,this.code=r}}function I_s(s){return Yc(s)&&s.name==="AuthApiError"}class PLt extends dQe{constructor(t,n){super(t),this.name="AuthUnknownError",this.originalError=n}}class aL extends dQe{constructor(t,n,r,a){super(t,r,a),this.name=n,this.status=r}}class $T extends aL{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function D_s(s){return Yc(s)&&s.name==="AuthSessionMissingError"}class sOe extends aL{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class ale extends aL{constructor(t){super(t,"AuthInvalidCredentialsError",400,void 0)}}class ile extends aL{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 R_s(s){return Yc(s)&&s.name==="AuthImplicitGrantRedirectError"}class Pmt extends aL{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 _$e extends aL{constructor(t,n){super(t,"AuthRetryableFetchError",n,void 0)}}function nOe(s){return Yc(s)&&s.name==="AuthRetryableFetchError"}class Lmt extends aL{constructor(t,n,r){super(t,"AuthWeakPasswordError",n,"weak_password"),this.reasons=r}}class gJ extends aL{constructor(t){super(t,"AuthInvalidJwtError",400,"invalid_jwt")}}const Imt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),Dmt=` \r=`.split(""),F_s=(()=>{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 Rmt(s){const t=[],n=l=>{t.push(String.fromCodePoint(l))},r={utf8seq:0,codepoint:0},a={queue:0,queuedBits:0},i=l=>{B_s(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 z_s(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}O_s(r,t)}}function B_s(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 U_s(s){const t=[],n={queue:0,queuedBits:0},r=a=>{t.push(a)};for(let a=0;at.push(n)),new Uint8Array(t)}function $_s(s){return Math.round(Date.now()/1e3)+s}function V_s(){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 D5=()=>typeof window<"u"&&typeof document<"u",xI={tested:!1,writable:!1},yJ=()=>{if(!D5())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(xI.tested)return xI.writable;const s=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(s,s),globalThis.localStorage.removeItem(s),xI.tested=!0,xI.writable=!0}catch{xI.tested=!0,xI.writable=!1}return xI.writable};function H_s(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 ILt=s=>{let t;return s?t=s:typeof fetch>"u"?t=(...n)=>za(async()=>{const{default:r}=await Promise.resolve().then(()=>aW);return{default:r}},void 0).then(({default:r})=>r(...n)):t=fetch,(...n)=>t(...n)},G_s=s=>typeof s=="object"&&s!==null&&"status"in s&&"ok"in s&&"json"in s&&typeof s.json=="function",DLt=async(s,t,n)=>{await s.setItem(t,JSON.stringify(n))},ole=async(s,t)=>{const n=await s.getItem(t);if(!n)return null;try{return JSON.parse(n)}catch{return n}},lle=async(s,t)=>{await s.removeItem(t)};class HMe{constructor(){this.promise=new HMe.promiseConstructor((t,n)=>{this.resolve=t,this.reject=n})}}HMe.promiseConstructor=Promise;function rOe(s){const t=s.split(".");if(t.length!==3)throw new gJ("Invalid JWT structure");for(let r=0;r{setTimeout(()=>t(null),s)})}function K_s(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 Y_s(s){return("0"+s.toString(16)).substr(-2)}function Z_s(){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,Y_s).join("")}async function X_s(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 Q_s(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 X_s(s);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function fB(s,t,n=!1){const r=Z_s();let a=r;n&&(a+="/PASSWORD_RECOVERY"),await DLt(s,`${t}-code-verifier`,a);const i=await Q_s(r);return[i,r===i?"plain":"s256"]}const J_s=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function ews(s){const t=s.headers.get(b$e);if(!t||!t.match(J_s))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch{return null}}function tws(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 sws(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 nws=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),rws=[502,503,504];async function Fmt(s){var t;if(!G_s(s))throw new _$e(FR(s),0);if(rws.includes(s.status))throw new _$e(FR(s),s.status);let n;try{n=await s.json()}catch(i){throw new PLt(FR(i),i)}let r;const a=ews(s);if(a&&a.getTime()>=MLt["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 Lmt(FR(n),s.status,((t=n.weak_password)===null||t===void 0?void 0:t.reasons)||[]);if(r==="session_not_found")throw new $T}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 Lmt(FR(n),s.status,n.weak_password.reasons);throw new L_s(FR(n),s.status||500,r)}const aws=(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 Yd(s,t,n,r){var a;const i=Object.assign({},r==null?void 0:r.headers);i[b$e]||(i[b$e]=MLt["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 iws(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 iws(s,t,n,r,a,i){const l=aws(t,r,a,i);let o;try{o=await s(n,Object.assign({},l))}catch(c){throw console.error(c),new _$e(FR(c),0)}if(o.ok||await Fmt(o),r!=null&&r.noResolveJson)return o;try{return await o.json()}catch(c){await Fmt(c)}}function VT(s){var t;let n=null;dws(s)&&(n=Object.assign({},s),s.expires_at||(n.expires_at=$_s(s.expires_in)));const r=(t=s.user)!==null&&t!==void 0?t:s;return{data:{session:n,user:r},error:null}}function Omt(s){const t=VT(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 j6(s){var t;return{data:{user:(t=s.user)!==null&&t!==void 0?t:s},error:null}}function ows(s){return{data:s,error:null}}function lws(s){const{action_link:t,email_otp:n,hashed_token:r,redirect_to:a,verification_type:i}=s,l=nws(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 cws(s){return s}function dws(s){return s.access_token&&s.refresh_token&&s.expires_in}var uws=function(s,t){var n={};for(var r in s)Object.prototype.hasOwnProperty.call(s,r)&&t.indexOf(r)<0&&(n[r]=s[r]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var a=0,r=Object.getOwnPropertySymbols(s);a0&&(p.forEach(f=>{const y=parseInt(f.split(";")[0].split("=")[1].substring(0,1)),v=JSON.parse(f.split(";")[1].split("=")[1]);d[`${v}Page`]=y}),d.total=parseInt(m)),{data:Object.assign(Object.assign({},h),d),error:null}}catch(d){if(Yc(d))return{data:{users:[]},error:d};throw d}}async getUserById(t){try{return await Yd(this.fetch,"GET",`${this.url}/admin/users/${t}`,{headers:this.headers,xform:j6})}catch(n){if(Yc(n))return{data:{user:null},error:n};throw n}}async updateUserById(t,n){try{return await Yd(this.fetch,"PUT",`${this.url}/admin/users/${t}`,{body:n,headers:this.headers,xform:j6})}catch(r){if(Yc(r))return{data:{user:null},error:r};throw r}}async deleteUser(t,n=!1){try{return await Yd(this.fetch,"DELETE",`${this.url}/admin/users/${t}`,{headers:this.headers,body:{should_soft_delete:n},xform:j6})}catch(r){if(Yc(r))return{data:{user:null},error:r};throw r}}async _listFactors(t){try{const{data:n,error:r}=await Yd(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(Yc(n))return{data:null,error:n};throw n}}async _deleteFactor(t){try{return{data:await Yd(this.fetch,"DELETE",`${this.url}/admin/users/${t.userId}/factors/${t.id}`,{headers:this.headers}),error:null}}catch(n){if(Yc(n))return{data:null,error:n};throw n}}}const mws={getItem:s=>yJ()?globalThis.localStorage.getItem(s):null,setItem:(s,t)=>{yJ()&&globalThis.localStorage.setItem(s,t)},removeItem:s=>{yJ()&&globalThis.localStorage.removeItem(s)}};function zmt(s={}){return{getItem:t=>s[t]||null,setItem:(t,n)=>{s[t]=n},removeItem:t=>{delete s[t]}}}function pws(){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 xB={debug:!!(globalThis&&yJ()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class RLt extends Error{constructor(t){super(t),this.isAcquireTimeout=!0}}class fws extends RLt{}async function xws(s,t,n){xB.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",s,t);const r=new globalThis.AbortController;return t>0&&setTimeout(()=>{r.abort(),xB.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){xB.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",s,a.name);try{return await n()}finally{xB.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",s,a.name)}}else{if(t===0)throw xB.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",s),new fws(`Acquiring an exclusive Navigator LockManager lock "${s}" immediately failed`);if(xB.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()}}))}pws();const gws={url:A_s,storageKey:E_s,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:T_s,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1};async function Bmt(s,t,n){return await n()}class Qee{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=Qee.nextInstanceID,Qee.nextInstanceID+=1,this.instanceID>0&&D5()&&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({},gws),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 hws({url:a.url,headers:a.headers,fetch:a.fetch}),this.url=a.url,this.headers=a.headers,this.fetch=ILt(a.fetch),this.lock=a.lock||Bmt,this.detectSessionInUrl=a.detectSessionInUrl,this.flowType=a.flowType,this.hasCustomAuthorizationHeader=a.hasCustomAuthorizationHeader,a.lock?this.lock=a.lock:D5()&&(!((n=globalThis==null?void 0:globalThis.navigator)===null||n===void 0)&&n.locks)?this.lock=xws:this.lock=Bmt,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:yJ()?this.storage=mws:(this.memoryStorage={},this.storage=zmt(this.memoryStorage)):(this.memoryStorage={},this.storage=zmt(this.memoryStorage)),D5()&&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} (${TLt}) ${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=H_s(window.location.href);let r="none";if(this._isImplicitGrantCallback(n)?r="implicit":await this._isPKCECallback(n)&&(r="pkce"),D5()&&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),R_s(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 Yc(n)?{error:n}:{error:new PLt("Unexpected error during initialization",n)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(t){var n,r,a;try{const i=await Yd(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:VT}),{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(Yc(i))return{data:{user:null,session:null},error:i};throw i}}async signUp(t){var n,r,a;try{let i;if("email"in t){const{email:u,password:h,options:m}=t;let p=null,f=null;this.flowType==="pkce"&&([p,f]=await fB(this.storage,this.storageKey)),i=await Yd(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:m==null?void 0:m.emailRedirectTo,body:{email:u,password:h,data:(n=m==null?void 0:m.data)!==null&&n!==void 0?n:{},gotrue_meta_security:{captcha_token:m==null?void 0:m.captchaToken},code_challenge:p,code_challenge_method:f},xform:VT})}else if("phone"in t){const{phone:u,password:h,options:m}=t;i=await Yd(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:VT})}else throw new ale("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(Yc(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 Yd(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:Omt})}else if("phone"in t){const{phone:i,password:l,options:o}=t;n=await Yd(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:Omt})}else throw new ale("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 sOe}:(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(Yc(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 ole(this.storage,`${this.storageKey}-code-verifier`),[r,a]=(n??"").split("/");try{const{data:i,error:l}=await Yd(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:t,code_verifier:r},xform:VT});if(await lle(this.storage,`${this.storageKey}-code-verifier`),l)throw l;return!i||!i.session||!i.user?{data:{user:null,session:null,redirectType:null},error:new sOe}:(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(Yc(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 Yd(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:VT}),{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 sOe}:(c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),{data:c,error:d})}catch(n){if(Yc(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 fB(this.storage,this.storageKey));const{error:h}=await Yd(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 Yd(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 ale("You must provide either an email or phone number.")}catch(o){if(Yc(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 Yd(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},t),{gotrue_meta_security:{captcha_token:i}}),redirectTo:a,xform:VT});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(Yc(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 fB(this.storage,this.storageKey)),await Yd(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:ows})}catch(i){if(Yc(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 $T;const{error:a}=await Yd(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:n.access_token});return{data:{user:null,session:null},error:a}})}catch(t){if(Yc(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 Yd(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 Yd(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 ale("You must provide either an email or phone number and a type")}catch(n){if(Yc(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 ole(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 Yd(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:t,xform:j6}):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 $T}:await Yd(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:j6})})}catch(n){if(Yc(n))return D_s(n)&&(await this._removeSession(),await lle(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 $T;const l=a.session;let o=null,c=null;this.flowType==="pkce"&&t.email!=null&&([o,c]=await fB(this.storage,this.storageKey));const{data:d,error:u}=await Yd(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:j6});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(Yc(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 $T;const n=Date.now()/1e3;let r=n,a=!0,i=null;const{payload:l}=rOe(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(Yc(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 $T;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(Yc(n))return{data:{user:null,session:null},error:n};throw n}}async _getSessionFromURL(t,n){try{if(!D5())throw new ile("No browser detected.");if(t.error||t.error_description||t.error_code)throw new ile(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 Pmt("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new ile("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 Pmt("No code detected.");const{data:b,error:j}=await this._exchangeCodeForSession(t.code);if(j)throw j;const S=new URL(window.location.href);return S.searchParams.delete("code"),window.history.replaceState(window.history.state,"",S.toString()),{data:{session:b.session,redirectType:null},error:null}}const{provider_token:r,provider_refresh_token:a,access_token:i,refresh_token:l,expires_in:o,expires_at:c,token_type:d}=t;if(!i||!o||!l||!d)throw new ile("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<=pU&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${p}s, should have been closer to ${h}s`);const f=m-h;u-f>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",f,m,u):u-f<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",f,m,u);const{data:y,error:v}=await this._getUser(i);if(v)throw v;const g={provider_token:r,provider_refresh_token:a,access_token:i,expires_in:h,expires_at:m,refresh_token:l,token_type:d,user:y.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:g,redirectType:t.type},error:null}}catch(r){if(Yc(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 ole(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&&!(I_s(o)&&(o.status===404||o.status===401||o.status===403)))return{error:o}}return t!=="others"&&(await this._removeSession(),await lle(this.storage,`${this.storageKey}-code-verifier`)),{error:null}})}onAuthStateChange(t){const n=V_s(),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 fB(this.storage,this.storageKey,!0));try{return await Yd(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(Yc(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(Yc(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 Yd(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 D5()&&!(!((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(Yc(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 Yd(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(Yc(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 K_s(async a=>(a>0&&await W_s(200*Math.pow(2,a-1)),this._debug(n,"refreshing attempt",a),await Yd(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:t},headers:this.headers,xform:VT})),(a,i)=>{const l=200*Math.pow(2,a);return i&&nOe(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(),pU);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)/pU);this._debug("#_autoRefreshTokenTick()",`access token expires in ${a} ticks, a tick lasts ${pU}ms, refresh threshold is ${v$e} ticks`),a<=v$e&&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 RLt)this._debug("auto refresh token tick lock not available");else throw t}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!D5()||!(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 fB(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 Yd(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(Yc(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 Yd(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(Yc(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 Yd(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(Yc(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 Yd(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(Yc(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}=rOe(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+P_s>Date.now()))return r;const{data:a,error:i}=await Yd(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 gJ("JWKS is empty");if(this.jwks=a,this.jwks_cached_at=Date.now(),r=a.keys.find(l=>l.kid===t),!r)throw new gJ("No matching signing key found in JWKS");return r}async getClaims(t,n={keys:[]}){try{let r=t;if(!r){const{data:p,error:f}=await this.getSession();if(f||!p.session)return{data:null,error:f};r=p.session.access_token}const{header:a,payload:i,signature:l,raw:{header:o,payload:c}}=rOe(r);if(tws(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=sws(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,q_s(`${o}.${c}`)))throw new gJ("Invalid JWT signature");return{data:{claims:i,header:a,signature:l},error:null}}catch(r){if(Yc(r))return{data:null,error:r};throw r}}}Qee.nextInstanceID=0;const yws=Qee;class vws extends yws{constructor(t){super(t)}}var bws=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 _ws{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=S_s(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:y_s,realtime:b_s,auth:Object.assign(Object.assign({},v_s),{storageKey:d}),global:g_s},h=C_s(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=N_s(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 Bbs(new URL("rest/v1",c).href,{headers:this.headers,schema:h.db.schema,fetch:this.fetch}),h.accessToken||this._listenForAuthEvents()}get functions(){return new xbs(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}get storage(){return new p_s(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 bws(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 vws({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 e_s(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 wws=(s,t,n)=>new _ws(s,t,n);function jws(){var v,g;if(typeof window>"u")return;const s=location.hostname,n=["lovableproject.com","lovableproject-dev.com","lovable.app","gpt-eng.com","gptengineer.run"].some(b=>s===b||s.endsWith("."+b)),r="[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}",a=n?((v=s.match(new RegExp("^(?:id-preview(?:-[a-z0-9]+)?|project)--("+r+")(?:-dev)?(?=\\.|$)","i")))==null?void 0:v[1])??((g=s.match(new RegExp("^("+r+")(?=[.-])","i")))==null?void 0:g[1]):void 0,i=window.parent&&window.parent!==window;if(!a||!i)return localStorage;const l=s.endsWith(".lovableproject-dev.com")||s.endsWith(".gpt-eng.com"),o=l?/^https:\/\/([a-z0-9-]+\.)*(lovable\.dev|gptengineer\.app)$|^http:\/\/localhost:3000$/:/^https:\/\/([a-z0-9-]+\.)*(lovable\.dev|gptengineer\.app)$/,c=location.ancestorOrigins&&location.ancestorOrigins[0]||(document.referrer?new URL(document.referrer).origin:""),d=c&&o.test(c)?[c]:l?["https://lovable.dev","http://localhost:3000"]:["https://lovable.dev"],u="lovable-preview-auth:result",h=2e3,m=()=>Math.random().toString(36).slice(2)+Date.now().toString(36),p=(b,j,S)=>new Promise(C=>{const E=m();let P=!1,M;const I=V=>{P||(P=!0,clearTimeout(M),window.removeEventListener("message",D),C(V))},D=V=>{if(d.indexOf(V.origin)<0)return;const G=V.data;G&&G.type===u&&G.requestId===E&&I(G)};window.addEventListener("message",D);const O={type:b,requestId:E,projectId:a,key:j};S!==void 0&&(O.value=S);for(const V of d)window.parent.postMessage(O,V);M=setTimeout(()=>I(null),h)});let f=!0;const y=250;return{getItem:async b=>{let j=await p("lovable-preview-auth:get",b);return!j&&f&&(await new Promise(S=>setTimeout(S,y)),j=await p("lovable-preview-auth:get",b)),f=!1,j&&j.ok&&typeof j.value=="string"?j.value===""?(localStorage.removeItem(b),null):j.value:localStorage.getItem(b)},setItem:(b,j)=>(localStorage.setItem(b,j),p("lovable-preview-auth:set",b,j).then(()=>{})),removeItem:b=>(localStorage.removeItem(b),p("lovable-preview-auth:remove",b).then(()=>{}))}}const Nws="https://relzejiswnotikjgvjhz.supabase.co",kws="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM",q=wws(Nws,kws,{auth:{storage:jws(),persistSession:!0,autoRefreshToken:!0}}),Sws=Object.freeze(Object.defineProperty({__proto__:null,supabase:q},Symbol.toStringTag,{value:"Module"})),FLt=_.createContext(void 0),Cws=({children:s})=>{const[t,n]=_.useState(null),[r,a]=_.useState(null),[i,l]=_.useState(!0),[o,c]=_.useState(!0),[d,u]=_.useState(!1),[h,m]=_.useState(!1),[p,f]=_.useState(!1),[y,v]=_.useState(null),[g,b]=_.useState([]),[j,S]=_.useState(null),C=_.useRef(null),E=_.useRef(!1),P=_.useRef(!1),M=Fn(),I=()=>{u(!1),m(!1),f(!1),v(null),b([]),S(null),C.current=null,E.current=!1},D=async $=>{if(E.current&&C.current===$||P.current)return;P.current=!0,c(!0);const H=window.setTimeout(()=>{console.warn("Role check timeout reached — unblocking UI."),P.current=!1,c(!1)},8e3);try{console.log("Checking roles via RPC for user:",$);const[{data:Y,error:Z},{data:ne,error:ce},{data:ie,error:te}]=await Promise.all([q.rpc("has_role",{_user_id:$,_role:"admin"}),q.rpc("has_role",{_user_id:$,_role:"brokerage_manager"}),q.rpc("has_role",{_user_id:$,_role:"coach"})]);if(Z||ce)console.error("Role RPC errors:",{isAdminError:Z,isBrokerError:ce,isCoachError:te}),u(!1),m(!1),f(!1);else{const be=!!Y,me=!!ne,he=!!ie;console.log("RPC roles result:",{adminValue:be,brokerValue:me,coachValue:he}),u(be),m(me),f(he)}C.current=$,E.current=!0,window.clearTimeout(H),c(!1);const{data:ae,error:le}=await q.from("profiles").select("brokerage_id, is_paused, paused_reason").eq("id",$).single();if(!le&&(ae!=null&&ae.is_paused)){const be=ae.paused_reason;try{sessionStorage.setItem("accountPausedReason",be||"")}catch{}await q.auth.signOut(),I(),M("/auth?paused=1",{replace:!0});return}if(v(!le&&ae?ae.brokerage_id:null),ne){console.log("Fetching managed brokerages for user:",$);const{data:be,error:me}=await q.from("brokerage_manager_assignments").select("brokerage_id").eq("user_id",$);if(console.log("Managed brokerage assignments result:",{assignments:be,assignmentsError:me}),me||!be){console.error("Error fetching managed brokerage assignments:",me),b([]);return}const he=Array.from(new Set(be.map(Pe=>Pe.brokerage_id).filter(Boolean)));if(he.length===0){b([]);return}const{data:pe,error:Ce}=await q.from("brokerages").select("id, name").in("id",he);if(console.log("Managed brokerages details result:",{brokeragesData:pe,brokeragesError:Ce}),Ce||!pe){console.error("Error fetching managed brokerages details:",Ce),b([]);return}const Ae=pe.map(Pe=>({id:Pe.id,name:Pe.name})).sort((Pe,ze)=>he.indexOf(Pe.id)-he.indexOf(ze.id));console.log("Parsed managed brokerages:",Ae),b(Ae),Ae.length>0&&S(Pe=>Pe??Ae[0].id)}else console.log("User is not a brokerage manager, skipping managed brokerages fetch"),b([]);C.current=$,E.current=!0}catch(Y){console.error("Unexpected error in checkRoles:",Y),I()}finally{window.clearTimeout(H),P.current=!1,c(!1)}};_.useEffect(()=>{let $=!0,H=!1;const Y=()=>{!$||H||(H=!0,l(!1))},{data:{subscription:Z}}=q.auth.onAuthStateChange((ce,ie)=>{console.log("Auth event:",ce),$&&(a(ie),n((ie==null?void 0:ie.user)??null),Y(),ce==="PASSWORD_RECOVERY"&&(console.log("Password recovery detected, redirecting to profile"),setTimeout(()=>{M("/profile?reset=true")},100)),ie!=null&&ie.user?(!E.current||C.current!==ie.user.id)&&setTimeout(()=>{D(ie.user.id)},0):(I(),c(!1)))}),ne=window.setTimeout(()=>{console.warn("Auth initialization timeout reached. Continuing without blocking UI."),Y()},8e3);return()=>{$=!1,window.clearTimeout(ne),Z.unsubscribe()}},[]);const O=async($,H)=>{var ce;const Y=($||"").trim().toLowerCase(),{data:Z,error:ne}=await q.auth.signInWithPassword({email:Y,password:H});if(ne)throw se.error(/invalid login credentials/i.test(ne.message)?`That email and password don't match an account. Check the email address, or use "Forgot password" to set a new password.`:ne.message),ne;if((ce=Z.user)!=null&&ce.id){const{data:ie}=await q.from("profiles").select("is_paused, paused_reason").eq("id",Z.user.id).maybeSingle();if(ie!=null&&ie.is_paused){const te=ie.paused_reason||"";try{sessionStorage.setItem("accountPausedReason",te)}catch{}await q.auth.signOut(),I(),n(null),a(null);const ae=new Error(te?`Your account is paused. ${te}`:"Your account is paused. Please contact LevelUp support to reactivate it.");throw ae.name="AccountPaused",se.error(ae.message),ae}}se.success("Welcome back!")},V=async($,H,Y)=>{var te;const Z="https://dashboard.relevelup.com/dashboard",ne=localStorage.getItem("levelup_referral_code")||null,{data:ce,error:ie}=await q.auth.signUp({email:$,password:H,options:{emailRedirectTo:Z,data:{name:Y,referred_by_code:ne}}});if(ie)throw se.error(ie.message),ie;if(ne&&((te=ce.user)!=null&&te.id))try{await q.from("profiles").update({referred_by_code:ne}).eq("id",ce.user.id),localStorage.removeItem("levelup_referral_code")}catch(ae){console.warn("Failed to attach referral code to profile",ae)}se.success("Account created! Welcome to LevelUp."),M("/dashboard")},G=async()=>{try{const{data:{session:$}}=await q.auth.getSession();if($){const{error:H}=await q.auth.signOut();H?H.message==="Auth session missing!"?console.warn("Sign out warning (ignored):",H.message):(console.error("Sign out error:",H),se.error(H.message)):se.success("Signed out successfully")}else console.log("No active session found, redirecting to auth");n(null),a(null),u(!1),m(!1),v(null),b([]),S(null),M("/auth")}catch($){console.error("Unexpected sign out error:",$),M("/auth")}};return e.jsx(FLt.Provider,{value:{user:t,session:r,loading:i,rolesLoading:o,signIn:O,signUp:V,signOut:G,isAdmin:d,isBrokerageManager:h,isCoach:p,brokerageId:y,managedBrokerages:g,selectedBrokerageId:j,setSelectedBrokerageId:S},children:s})},hs=()=>{const s=_.useContext(FLt);if(s===void 0)throw new Error("useAuth must be used within an AuthProvider");return s},OLt=_.createContext({onlineUsers:[],totalOnline:0}),Aws=3*60*1e3,Ews=45*1e3,Tws=30*1e3,Mws=({children:s})=>{const{user:t,brokerageId:n,isAdmin:r}=hs(),[a,i]=_.useState([]),l=_.useRef(new Date().toISOString()),o=_.useCallback(async()=>{t&&await q.from("user_presence").upsert({user_id:t.id,last_seen_at:new Date().toISOString(),online_since:l.current,current_path:window.location.pathname},{onConflict:"user_id"})},[t==null?void 0:t.id]),c=_.useCallback(async()=>{if(!t)return;const u=new Date(Date.now()-Aws).toISOString(),{data:h}=await q.from("user_presence").select("user_id, last_seen_at, online_since").gte("last_seen_at",u).order("last_seen_at",{ascending:!1}).limit(200);if(!(h!=null&&h.length)){i([]);return}const m=h.map(y=>y.user_id),{data:p}=await q.from("profiles").select("id, name, email, avatar_url, brokerage_id").in("id",m),f=new Map((p||[]).map(y=>[y.id,y]));i(h.map(y=>{var g;const v=f.get(y.user_id);return{id:y.user_id,name:(v==null?void 0:v.name)||((g=v==null?void 0:v.email)==null?void 0:g.split("@")[0])||"Member",avatarUrl:(v==null?void 0:v.avatar_url)||void 0,brokerageId:(v==null?void 0:v.brokerage_id)||void 0,onlineSince:y.online_since||y.last_seen_at}}))},[t==null?void 0:t.id]);_.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()},Ews),p=window.setInterval(()=>{c()},Tws),f=()=>{document.visibilityState==="visible"&&h()};return document.addEventListener("visibilitychange",f),()=>{u=!0,window.clearInterval(m),window.clearInterval(p),document.removeEventListener("visibilitychange",f)}},[t==null?void 0:t.id,o,c]);const d=a.filter(u=>!!(u.id===(t==null?void 0:t.id)||r||n&&u.brokerageId===n||!n&&!u.brokerageId));return e.jsx(OLt.Provider,{value:{onlineUsers:d,totalOnline:d.length},children:s})},zLt=()=>_.useContext(OLt),BLt=_.createContext(void 0),gI="levelup_admin_session",vT="levelup_impersonation",aOe="levelup_impersonation_return",Pws=({children:s})=>{const[t,n]=_.useState(!1),[r,a]=_.useState(null),[i,l]=_.useState(!1);_.useEffect(()=>{const d=sessionStorage.getItem(vT);if(d)try{const u=JSON.parse(d);n(!0),a(u)}catch{sessionStorage.removeItem(vT)}},[]);const o=async(d,u)=>{l(!0);try{const{data:{session:h}}=await q.auth.getSession();if(!h)return se.error("No active session found"),!1;const m={access_token:h.access_token,refresh_token:h.refresh_token};sessionStorage.setItem(gI,JSON.stringify(m)),u&&sessionStorage.setItem(aOe,u);const p=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/impersonate-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${h.access_token}`},body:JSON.stringify({targetUserId:d})}),f=await p.json();if(!p.ok)throw new Error(f.error||"Failed to impersonate user");const y={id:f.targetUser.id,name:f.targetUser.name,email:f.targetUser.email};if(sessionStorage.setItem(vT,JSON.stringify(y)),f.method==="session"){const{error:v}=await q.auth.setSession({access_token:f.access_token,refresh_token:f.refresh_token});if(v)throw console.error("Set session error:",v),sessionStorage.removeItem(gI),sessionStorage.removeItem(vT),new Error("Failed to establish impersonation session")}else{const v=f.type||"recovery",{error:g}=await q.auth.verifyOtp({token_hash:f.token_hash,type:v});if(g)throw console.error("Verify OTP error:",g),sessionStorage.removeItem(gI),sessionStorage.removeItem(vT),new Error("Failed to establish impersonation session")}return n(!0),a(y),se.success(`Now viewing as ${y.name}`),window.location.href="/dashboard",!0}catch(h){return console.error("Impersonation error:",h),se.error(h.message||"Failed to impersonate user"),sessionStorage.removeItem(gI),sessionStorage.removeItem(vT),!1}finally{l(!1)}},c=async()=>{l(!0);try{const d=sessionStorage.getItem(gI);if(!d){await q.auth.signOut(),window.location.href="/auth";return}const u=JSON.parse(d);await q.auth.signOut();const{error:h}=await q.auth.setSession({access_token:u.access_token,refresh_token:u.refresh_token});if(sessionStorage.removeItem(gI),sessionStorage.removeItem(vT),h){console.error("Failed to restore admin session:",h),se.error("Admin session expired, please sign in again"),window.location.href="/auth";return}n(!1),a(null),se.success("Returned to your account");const m=sessionStorage.getItem(aOe)||"/admin/members";sessionStorage.removeItem(aOe),window.location.href=m}catch(d){console.error("Stop impersonation error:",d),se.error("Failed to restore admin session"),sessionStorage.removeItem(gI),sessionStorage.removeItem(vT),window.location.href="/auth"}finally{l(!1)}};return e.jsx(BLt.Provider,{value:{isImpersonating:t,impersonatedUser:r,startImpersonation:o,stopImpersonation:c,isLoading:i},children:s})},GMe=()=>{const s=_.useContext(BLt);if(s===void 0)throw new Error("useImpersonation must be used within an ImpersonationProvider");return s},Lws=()=>{const{isImpersonating:s,impersonatedUser:t,stopImpersonation:n,isLoading:r}=GMe();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(xl,{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(B,{size:"sm",variant:"secondary",onClick:n,disabled:r,className:"bg-amber-100 hover:bg-amber-200 text-amber-950 border-0",children:r?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Qn,{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"})]})})]})})},ULt=_.createContext(void 0),gB="levelup_acting_as",cle="levelup_acting_as_self",Iws=({children:s})=>{const{user:t}=hs(),[n,r]=_.useState(!1),[a,i]=_.useState([]),[l,o]=_.useState(null),[c,d]=_.useState({}),[u,h]=_.useState(!0),[m,p]=_.useState(()=>sessionStorage.getItem(cle)==="true");_.useEffect(()=>{if(!(t!=null&&t.id)){r(!1),i([]),o(null),d({}),h(!1);return}(async()=>{h(!0);try{const{data:j}=await q.rpc("has_role",{_user_id:t.id,_role:"assistant"});if(!j){r(!1),i([]),o(null),d({}),h(!1);return}r(!0);const{data:S,error:C}=await q.from("agent_assistant_assignments").select("agent_id, permissions").eq("assistant_id",t.id);if(C||!S||S.length===0){i([]),h(!1);return}const E=S.map(I=>I.agent_id),{data:P}=await q.from("profiles").select("id, name, email, avatar_url").in("id",E),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(cle)==="true")p(!0),o(null),d({});else{const I=sessionStorage.getItem(gB);if(I){const D=M.find(O=>O.id===I);if(D){o(D);const O=S.find(V=>V.agent_id===I);d((O==null?void 0:O.permissions)||{})}else if(M.length>0){o(M[0]);const O=S.find(V=>V.agent_id===M[0].id);d((O==null?void 0:O.permissions)||{}),sessionStorage.setItem(gB,M[0].id)}}else if(M.length>0){o(M[0]);const D=S.find(O=>O.agent_id===M[0].id);d((D==null?void 0:D.permissions)||{}),sessionStorage.setItem(gB,M[0].id)}}}catch(j){console.error("Error loading assistant data:",j)}finally{h(!1)}})()},[t==null?void 0:t.id]);const f=b=>{o(b),p(!1),sessionStorage.removeItem(cle),b?(sessionStorage.setItem(gB,b.id),q.from("agent_assistant_assignments").select("permissions").eq("assistant_id",(t==null?void 0:t.id)||"").eq("agent_id",b.id).single().then(({data:j})=>{d((j==null?void 0:j.permissions)||{})})):(sessionStorage.removeItem(gB),d({}))},y=()=>{p(!0),o(null),d({}),sessionStorage.setItem(cle,"true"),sessionStorage.removeItem(gB)},v=b=>!n||m?!0:c[b]===!0,g=n&&l&&!m?l.id:(t==null?void 0:t.id)||null;return e.jsx(ULt.Provider,{value:{isAssistant:n,assignedAgents:a,actingAsAgent:l,setActingAsAgent:f,effectiveUserId:g,permissions:c,hasPermission:v,isLoading:u,isActingAsSelf:m,setActingAsSelf:y},children:s})},Ire=()=>{const s=_.useContext(ULt);if(s===void 0)throw new Error("useActingAs must be used within an ActingAsProvider");return s},ha=()=>{const{effectiveUserId:s}=Ire();return s};var qLt={exports:{}},$Lt={};/** * @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 kH=_;function Dws(s,t){return s===t&&(s!==0||1/s===1/t)||s!==s&&t!==t}var Rws=typeof Object.is=="function"?Object.is:Dws,Fws=kH.useState,Ows=kH.useEffect,zws=kH.useLayoutEffect,Bws=kH.useDebugValue;function Uws(s,t){var n=t(),r=Fws({inst:{value:n,getSnapshot:t}}),a=r[0].inst,i=r[1];return zws(function(){a.value=n,a.getSnapshot=t,iOe(a)&&i({inst:a})},[s,n,t]),Ows(function(){return iOe(a)&&i({inst:a}),s(function(){iOe(a)&&i({inst:a})})},[s]),Bws(n),n}function iOe(s){var t=s.getSnapshot;s=s.value;try{var n=t();return!Rws(s,n)}catch{return!0}}function qws(s,t){return t()}var $ws=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?qws:Uws;$Lt.useSyncExternalStore=kH.useSyncExternalStore!==void 0?kH.useSyncExternalStore:$ws;qLt.exports=$Lt;var Vws=qLt.exports;function Hws(){return Vws.useSyncExternalStore(Gws,()=>!0,()=>!1)}function Gws(){return()=>{}}var uQe="Avatar",[Wws,vbr]=af(uQe),[Kws,VLt]=Wws(uQe),HLt=_.forwardRef((s,t)=>{const{__scopeAvatar:n,...r}=s,[a,i]=_.useState("idle");return e.jsx(Kws,{scope:n,imageLoadingStatus:a,onImageLoadingStatusChange:i,children:e.jsx(ii.span,{...r,ref:t})})});HLt.displayName=uQe;var GLt="AvatarImage",WLt=_.forwardRef((s,t)=>{const{__scopeAvatar:n,src:r,onLoadingStatusChange:a=()=>{},...i}=s,l=VLt(GLt,n),o=Yws(r,i),c=wx(d=>{a(d),l.onImageLoadingStatusChange(d)});return Mx(()=>{o!=="idle"&&c(o)},[o,c]),o==="loaded"?e.jsx(ii.img,{...i,ref:t,src:r}):null});WLt.displayName=GLt;var KLt="AvatarFallback",YLt=_.forwardRef((s,t)=>{const{__scopeAvatar:n,delayMs:r,...a}=s,i=VLt(KLt,n),[l,o]=_.useState(r===void 0);return _.useEffect(()=>{if(r!==void 0){const c=window.setTimeout(()=>o(!0),r);return()=>window.clearTimeout(c)}},[r]),l&&i.imageLoadingStatus!=="loaded"?e.jsx(ii.span,{...a,ref:t}):null});YLt.displayName=KLt;function Umt(s,t){return s?t?(s.src!==t&&(s.src=t),s.complete&&s.naturalWidth>0?"loaded":"loading"):"error":"idle"}function Yws(s,{referrerPolicy:t,crossOrigin:n}){const r=Hws(),a=_.useRef(null),i=r?(a.current||(a.current=new window.Image),a.current):null,[l,o]=_.useState(()=>Umt(i,s));return Mx(()=>{o(Umt(i,s))},[i,s]),Mx(()=>{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 ZLt=HLt,XLt=WLt,QLt=YLt;const ja=_.forwardRef(({className:s,...t},n)=>e.jsx(ZLt,{ref:n,className:At("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",s),...t}));ja.displayName=ZLt.displayName;const pi=_.forwardRef(({className:s,...t},n)=>e.jsx(XLt,{ref:n,className:At("aspect-square h-full w-full",s),...t}));pi.displayName=XLt.displayName;const Na=_.forwardRef(({className:s,...t},n)=>e.jsx(QLt,{ref:n,className:At("flex h-full w-full items-center justify-center rounded-full bg-muted",s),...t}));Na.displayName=QLt.displayName;const Zws=F9("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 Oe({className:s,variant:t,...n}){return e.jsx("div",{className:At(Zws({variant:t}),s),...n})}var Xws=_.createContext(void 0);function DE(s){const t=_.useContext(Xws);return s||t||"ltr"}var oOe="rovingFocusGroup.onEntryFocus",Qws={bubbles:!1,cancelable:!0},Dre="RovingFocusGroup",[w$e,JLt,Jws]=KG(Dre),[ejs,iL]=af(Dre,[Jws]),[tjs,sjs]=ejs(Dre),eIt=_.forwardRef((s,t)=>e.jsx(w$e.Provider,{scope:s.__scopeRovingFocusGroup,children:e.jsx(w$e.Slot,{scope:s.__scopeRovingFocusGroup,children:e.jsx(njs,{...s,ref:t})})}));eIt.displayName=Dre;var njs=_.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=_.useRef(null),p=Qo(t,m),f=DE(i),[y,v]=Ug({prop:l,defaultProp:o??null,onChange:c,caller:Dre}),[g,b]=_.useState(!1),j=wx(d),S=JLt(n),C=_.useRef(!1),[E,P]=_.useState(0);return _.useEffect(()=>{const M=m.current;if(M)return M.addEventListener(oOe,j),()=>M.removeEventListener(oOe,j)},[j]),e.jsx(tjs,{scope:n,orientation:r,dir:f,loop:a,currentTabStopId:y,onItemFocus:_.useCallback(M=>v(M),[v]),onItemShiftTab:_.useCallback(()=>b(!0),[]),onFocusableItemAdd:_.useCallback(()=>P(M=>M+1),[]),onFocusableItemRemove:_.useCallback(()=>P(M=>M-1),[]),children:e.jsx(ii.div,{tabIndex:g||E===0?-1:0,"data-orientation":r,...h,ref:p,style:{outline:"none",...s.style},onMouseDown:wa(s.onMouseDown,()=>{C.current=!0}),onFocus:wa(s.onFocus,M=>{const I=!C.current;if(M.target===M.currentTarget&&I&&!g){const D=new CustomEvent(oOe,Qws);if(M.currentTarget.dispatchEvent(D),!D.defaultPrevented){const O=S().filter(Y=>Y.focusable),V=O.find(Y=>Y.active),G=O.find(Y=>Y.id===y),H=[V,G,...O].filter(Boolean).map(Y=>Y.ref.current);nIt(H,u)}}C.current=!1}),onBlur:wa(s.onBlur,()=>b(!1))})})}),tIt="RovingFocusGroupItem",sIt=_.forwardRef((s,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:a=!1,tabStopId:i,children:l,...o}=s,c=Og(),d=i||c,u=sjs(tIt,n),h=u.currentTabStopId===d,m=JLt(n),{onFocusableItemAdd:p,onFocusableItemRemove:f,currentTabStopId:y}=u;return _.useEffect(()=>{if(r)return p(),()=>f()},[r,p,f]),e.jsx(w$e.ItemSlot,{scope:n,id:d,focusable:r,active:a,children:e.jsx(ii.span,{tabIndex:h?0:-1,"data-orientation":u.orientation,...o,ref:t,onMouseDown:wa(s.onMouseDown,v=>{r?u.onItemFocus(d):v.preventDefault()}),onFocus:wa(s.onFocus,()=>u.onItemFocus(d)),onKeyDown:wa(s.onKeyDown,v=>{if(v.key==="Tab"&&v.shiftKey){u.onItemShiftTab();return}if(v.target!==v.currentTarget)return;const g=ijs(v,u.orientation,u.dir);if(g!==void 0){if(v.metaKey||v.ctrlKey||v.altKey||v.shiftKey)return;v.preventDefault();let j=m().filter(S=>S.focusable).map(S=>S.ref.current);if(g==="last")j.reverse();else if(g==="prev"||g==="next"){g==="prev"&&j.reverse();const S=j.indexOf(v.currentTarget);j=u.loop?ojs(j,S+1):j.slice(S+1)}setTimeout(()=>nIt(j))}}),children:typeof l=="function"?l({isCurrentTabStop:h,hasTabStop:y!=null}):l})})});sIt.displayName=tIt;var rjs={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function ajs(s,t){return t!=="rtl"?s:s==="ArrowLeft"?"ArrowRight":s==="ArrowRight"?"ArrowLeft":s}function ijs(s,t,n){const r=ajs(s.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return rjs[r]}function nIt(s,t=!1){const n=document.activeElement;for(const r of s)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function ojs(s,t){return s.map((n,r)=>s[(t+r)%s.length])}var WMe=eIt,KMe=sIt,j$e=["Enter"," "],ljs=["ArrowDown","PageUp","Home"],rIt=["ArrowUp","PageDown","End"],cjs=[...ljs,...rIt],djs={ltr:[...j$e,"ArrowRight"],rtl:[...j$e,"ArrowLeft"]},ujs={ltr:["ArrowLeft"],rtl:["ArrowRight"]},Rre="Menu",[Jee,hjs,mjs]=KG(Rre),[z9,aIt]=af(Rre,[mjs,_C,iL]),YMe=_C(),iIt=iL(),[pjs,B9]=z9(Rre),[fjs,Fre]=z9(Rre),oIt=s=>{const{__scopeMenu:t,open:n=!1,children:r,dir:a,onOpenChange:i,modal:l=!0}=s,o=YMe(t),[c,d]=_.useState(null),u=_.useRef(!1),h=wx(i),m=DE(a);return _.useEffect(()=>{const p=()=>{u.current=!0,document.addEventListener("pointerdown",f,{capture:!0,once:!0}),document.addEventListener("pointermove",f,{capture:!0,once:!0})},f=()=>u.current=!1;return document.addEventListener("keydown",p,{capture:!0}),()=>{document.removeEventListener("keydown",p,{capture:!0}),document.removeEventListener("pointerdown",f,{capture:!0}),document.removeEventListener("pointermove",f,{capture:!0})}},[]),e.jsx(Are,{...o,children:e.jsx(pjs,{scope:t,open:n,onOpenChange:h,content:c,onContentChange:d,children:e.jsx(fjs,{scope:t,onClose:_.useCallback(()=>h(!1),[h]),isUsingKeyboardRef:u,dir:m,modal:l,children:r})})})};oIt.displayName=Rre;var xjs="MenuAnchor",hQe=_.forwardRef((s,t)=>{const{__scopeMenu:n,...r}=s,a=YMe(n);return e.jsx(tW,{...a,...r,ref:t})});hQe.displayName=xjs;var mQe="MenuPortal",[gjs,lIt]=z9(mQe,{forceMount:void 0}),cIt=s=>{const{__scopeMenu:t,forceMount:n,children:r,container:a}=s,i=B9(mQe,t);return e.jsx(gjs,{scope:t,forceMount:n,children:e.jsx(pg,{present:n||i.open,children:e.jsx(YG,{asChild:!0,container:a,children:r})})})};cIt.displayName=mQe;var xN="MenuContent",[yjs,pQe]=z9(xN),dIt=_.forwardRef((s,t)=>{const n=lIt(xN,s.__scopeMenu),{forceMount:r=n.forceMount,...a}=s,i=B9(xN,s.__scopeMenu),l=Fre(xN,s.__scopeMenu);return e.jsx(Jee.Provider,{scope:s.__scopeMenu,children:e.jsx(pg,{present:r||i.open,children:e.jsx(Jee.Slot,{scope:s.__scopeMenu,children:l.modal?e.jsx(vjs,{...a,ref:t}):e.jsx(bjs,{...a,ref:t})})})})}),vjs=_.forwardRef((s,t)=>{const n=B9(xN,s.__scopeMenu),r=_.useRef(null),a=Qo(t,r);return _.useEffect(()=>{const i=r.current;if(i)return SMe(i)},[]),e.jsx(fQe,{...s,ref:a,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:wa(s.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),bjs=_.forwardRef((s,t)=>{const n=B9(xN,s.__scopeMenu);return e.jsx(fQe,{...s,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),_js=CP("MenuContent.ScrollLock"),fQe=_.forwardRef((s,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:a,onOpenAutoFocus:i,onCloseAutoFocus:l,disableOutsidePointerEvents:o,onEntryFocus:c,onEscapeKeyDown:d,onPointerDownOutside:u,onFocusOutside:h,onInteractOutside:m,onDismiss:p,disableOutsideScroll:f,...y}=s,v=B9(xN,n),g=Fre(xN,n),b=YMe(n),j=iIt(n),S=hjs(n),[C,E]=_.useState(null),P=_.useRef(null),M=Qo(t,P,v.onContentChange),I=_.useRef(0),D=_.useRef(""),O=_.useRef(0),V=_.useRef(null),G=_.useRef("right"),$=_.useRef(0),H=f?wre:_.Fragment,Y=f?{as:_js,allowPinchZoom:!0}:void 0,Z=ce=>{var pe,Ce;const ie=D.current+ce,te=S().filter(Ae=>!Ae.disabled),ae=document.activeElement,le=(pe=te.find(Ae=>Ae.ref.current===ae))==null?void 0:pe.textValue,be=te.map(Ae=>Ae.textValue),me=Ljs(be,ie,le),he=(Ce=te.find(Ae=>Ae.textValue===me))==null?void 0:Ce.ref.current;(function Ae(Pe){D.current=Pe,window.clearTimeout(I.current),Pe!==""&&(I.current=window.setTimeout(()=>Ae(""),1e3))})(ie),he&&setTimeout(()=>he.focus())};_.useEffect(()=>()=>window.clearTimeout(I.current),[]),NMe();const ne=_.useCallback(ce=>{var te,ae;return G.current===((te=V.current)==null?void 0:te.side)&&Djs(ce,(ae=V.current)==null?void 0:ae.area)},[]);return e.jsx(yjs,{scope:n,searchRef:D,onItemEnter:_.useCallback(ce=>{ne(ce)&&ce.preventDefault()},[ne]),onItemLeave:_.useCallback(ce=>{var ie;ne(ce)||((ie=P.current)==null||ie.focus(),E(null))},[ne]),onTriggerLeave:_.useCallback(ce=>{ne(ce)&&ce.preventDefault()},[ne]),pointerGraceTimerRef:O,onPointerGraceIntentChange:_.useCallback(ce=>{V.current=ce},[]),children:e.jsx(H,{...Y,children:e.jsx(_re,{asChild:!0,trapped:a,onMountAutoFocus:wa(i,ce=>{var ie;ce.preventDefault(),(ie=P.current)==null||ie.focus({preventScroll:!0})}),onUnmountAutoFocus:l,children:e.jsx(rL,{asChild:!0,disableOutsidePointerEvents:o,onEscapeKeyDown:d,onPointerDownOutside:u,onFocusOutside:h,onInteractOutside:m,onDismiss:p,children:e.jsx(WMe,{asChild:!0,...j,dir:g.dir,orientation:"vertical",loop:r,currentTabStopId:C,onCurrentTabStopIdChange:E,onEntryFocus:wa(c,ce=>{g.isUsingKeyboardRef.current||ce.preventDefault()}),preventScrollOnEntryFocus:!0,children:e.jsx(Ere,{role:"menu","aria-orientation":"vertical","data-state":SIt(v.open),"data-radix-menu-content":"",dir:g.dir,...b,...y,ref:M,style:{outline:"none",...y.style},onKeyDown:wa(y.onKeyDown,ce=>{const te=ce.target.closest("[data-radix-menu-content]")===ce.currentTarget,ae=ce.ctrlKey||ce.altKey||ce.metaKey,le=ce.key.length===1;te&&(ce.key==="Tab"&&ce.preventDefault(),!ae&&le&&Z(ce.key));const be=P.current;if(ce.target!==be||!cjs.includes(ce.key))return;ce.preventDefault();const he=S().filter(pe=>!pe.disabled).map(pe=>pe.ref.current);rIt.includes(ce.key)&&he.reverse(),Mjs(he)}),onBlur:wa(s.onBlur,ce=>{ce.currentTarget.contains(ce.target)||(window.clearTimeout(I.current),D.current="")}),onPointerMove:wa(s.onPointerMove,ete(ce=>{const ie=ce.target,te=$.current!==ce.clientX;if(ce.currentTarget.contains(ie)&&te){const ae=ce.clientX>$.current?"right":"left";G.current=ae,$.current=ce.clientX}}))})})})})})})});dIt.displayName=xN;var wjs="MenuGroup",xQe=_.forwardRef((s,t)=>{const{__scopeMenu:n,...r}=s;return e.jsx(ii.div,{role:"group",...r,ref:t})});xQe.displayName=wjs;var jjs="MenuLabel",uIt=_.forwardRef((s,t)=>{const{__scopeMenu:n,...r}=s;return e.jsx(ii.div,{...r,ref:t})});uIt.displayName=jjs;var Z3e="MenuItem",qmt="menu.itemSelect",ZMe=_.forwardRef((s,t)=>{const{disabled:n=!1,onSelect:r,...a}=s,i=_.useRef(null),l=Fre(Z3e,s.__scopeMenu),o=pQe(Z3e,s.__scopeMenu),c=Qo(t,i),d=_.useRef(!1),u=()=>{const h=i.current;if(!n&&h){const m=new CustomEvent(qmt,{bubbles:!0,cancelable:!0});h.addEventListener(qmt,p=>r==null?void 0:r(p),{once:!0}),IXe(h,m),m.defaultPrevented?d.current=!1:l.onClose()}};return e.jsx(hIt,{...a,ref:c,disabled:n,onClick:wa(s.onClick,u),onPointerDown:h=>{var m;(m=s.onPointerDown)==null||m.call(s,h),d.current=!0},onPointerUp:wa(s.onPointerUp,h=>{var m;d.current||(m=h.currentTarget)==null||m.click()}),onKeyDown:wa(s.onKeyDown,h=>{const m=o.searchRef.current!=="";n||m&&h.key===" "||j$e.includes(h.key)&&(h.currentTarget.click(),h.preventDefault())})})});ZMe.displayName=Z3e;var hIt=_.forwardRef((s,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:a,...i}=s,l=pQe(Z3e,n),o=iIt(n),c=_.useRef(null),d=Qo(t,c),[u,h]=_.useState(!1),[m,p]=_.useState("");return _.useEffect(()=>{const f=c.current;f&&p((f.textContent??"").trim())},[i.children]),e.jsx(Jee.ItemSlot,{scope:n,disabled:r,textValue:a??m,children:e.jsx(KMe,{asChild:!0,...o,focusable:!r,children:e.jsx(ii.div,{role:"menuitem","data-highlighted":u?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...i,ref:d,onPointerMove:wa(s.onPointerMove,ete(f=>{r?l.onItemLeave(f):(l.onItemEnter(f),f.defaultPrevented||f.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:wa(s.onPointerLeave,ete(f=>l.onItemLeave(f))),onFocus:wa(s.onFocus,()=>h(!0)),onBlur:wa(s.onBlur,()=>h(!1))})})})}),Njs="MenuCheckboxItem",mIt=_.forwardRef((s,t)=>{const{checked:n=!1,onCheckedChange:r,...a}=s;return e.jsx(yIt,{scope:s.__scopeMenu,checked:n,children:e.jsx(ZMe,{role:"menuitemcheckbox","aria-checked":X3e(n)?"mixed":n,...a,ref:t,"data-state":yQe(n),onSelect:wa(a.onSelect,()=>r==null?void 0:r(X3e(n)?!0:!n),{checkForDefaultPrevented:!1})})})});mIt.displayName=Njs;var pIt="MenuRadioGroup",[kjs,Sjs]=z9(pIt,{value:void 0,onValueChange:()=>{}}),fIt=_.forwardRef((s,t)=>{const{value:n,onValueChange:r,...a}=s,i=wx(r);return e.jsx(kjs,{scope:s.__scopeMenu,value:n,onValueChange:i,children:e.jsx(xQe,{...a,ref:t})})});fIt.displayName=pIt;var xIt="MenuRadioItem",gIt=_.forwardRef((s,t)=>{const{value:n,...r}=s,a=Sjs(xIt,s.__scopeMenu),i=n===a.value;return e.jsx(yIt,{scope:s.__scopeMenu,checked:i,children:e.jsx(ZMe,{role:"menuitemradio","aria-checked":i,...r,ref:t,"data-state":yQe(i),onSelect:wa(r.onSelect,()=>{var l;return(l=a.onValueChange)==null?void 0:l.call(a,n)},{checkForDefaultPrevented:!1})})})});gIt.displayName=xIt;var gQe="MenuItemIndicator",[yIt,Cjs]=z9(gQe,{checked:!1}),vIt=_.forwardRef((s,t)=>{const{__scopeMenu:n,forceMount:r,...a}=s,i=Cjs(gQe,n);return e.jsx(pg,{present:r||X3e(i.checked)||i.checked===!0,children:e.jsx(ii.span,{...a,ref:t,"data-state":yQe(i.checked)})})});vIt.displayName=gQe;var Ajs="MenuSeparator",bIt=_.forwardRef((s,t)=>{const{__scopeMenu:n,...r}=s;return e.jsx(ii.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});bIt.displayName=Ajs;var Ejs="MenuArrow",_It=_.forwardRef((s,t)=>{const{__scopeMenu:n,...r}=s,a=YMe(n);return e.jsx(Tre,{...a,...r,ref:t})});_It.displayName=Ejs;var Tjs="MenuSub",[bbr,wIt]=z9(Tjs),cX="MenuSubTrigger",jIt=_.forwardRef((s,t)=>{const n=B9(cX,s.__scopeMenu),r=Fre(cX,s.__scopeMenu),a=wIt(cX,s.__scopeMenu),i=pQe(cX,s.__scopeMenu),l=_.useRef(null),{pointerGraceTimerRef:o,onPointerGraceIntentChange:c}=i,d={__scopeMenu:s.__scopeMenu},u=_.useCallback(()=>{l.current&&window.clearTimeout(l.current),l.current=null},[]);return _.useEffect(()=>u,[u]),_.useEffect(()=>{const h=o.current;return()=>{window.clearTimeout(h),c(null)}},[o,c]),e.jsx(hQe,{asChild:!0,...d,children:e.jsx(hIt,{id:a.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":a.contentId,"data-state":SIt(n.open),...s,ref:yE(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:wa(s.onPointerMove,ete(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:wa(s.onPointerLeave,ete(h=>{var p,f;u();const m=(p=n.content)==null?void 0:p.getBoundingClientRect();if(m){const y=(f=n.content)==null?void 0:f.dataset.side,v=y==="right",g=v?-5:5,b=m[v?"left":"right"],j=m[v?"right":"left"];i.onPointerGraceIntentChange({area:[{x:h.clientX+g,y:h.clientY},{x:b,y:m.top},{x:j,y:m.top},{x:j,y:m.bottom},{x:b,y:m.bottom}],side:y}),window.clearTimeout(o.current),o.current=window.setTimeout(()=>i.onPointerGraceIntentChange(null),300)}else{if(i.onTriggerLeave(h),h.defaultPrevented)return;i.onPointerGraceIntentChange(null)}})),onKeyDown:wa(s.onKeyDown,h=>{var p;const m=i.searchRef.current!=="";s.disabled||m&&h.key===" "||djs[r.dir].includes(h.key)&&(n.onOpenChange(!0),(p=n.content)==null||p.focus(),h.preventDefault())})})})});jIt.displayName=cX;var NIt="MenuSubContent",kIt=_.forwardRef((s,t)=>{const n=lIt(xN,s.__scopeMenu),{forceMount:r=n.forceMount,...a}=s,i=B9(xN,s.__scopeMenu),l=Fre(xN,s.__scopeMenu),o=wIt(NIt,s.__scopeMenu),c=_.useRef(null),d=Qo(t,c);return e.jsx(Jee.Provider,{scope:s.__scopeMenu,children:e.jsx(pg,{present:r||i.open,children:e.jsx(Jee.Slot,{scope:s.__scopeMenu,children:e.jsx(fQe,{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:wa(s.onFocusOutside,u=>{u.target!==o.trigger&&i.onOpenChange(!1)}),onEscapeKeyDown:wa(s.onEscapeKeyDown,u=>{l.onClose(),u.preventDefault()}),onKeyDown:wa(s.onKeyDown,u=>{var p;const h=u.currentTarget.contains(u.target),m=ujs[l.dir].includes(u.key);h&&m&&(i.onOpenChange(!1),(p=o.trigger)==null||p.focus(),u.preventDefault())})})})})})});kIt.displayName=NIt;function SIt(s){return s?"open":"closed"}function X3e(s){return s==="indeterminate"}function yQe(s){return X3e(s)?"indeterminate":s?"checked":"unchecked"}function Mjs(s){const t=document.activeElement;for(const n of s)if(n===t||(n.focus(),document.activeElement!==t))return}function Pjs(s,t){return s.map((n,r)=>s[(t+r)%s.length])}function Ljs(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=Pjs(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 Ijs(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 Djs(s,t){if(!t)return!1;const n={x:s.clientX,y:s.clientY};return Ijs(n,t)}function ete(s){return t=>t.pointerType==="mouse"?s(t):void 0}var Rjs=oIt,Fjs=hQe,Ojs=cIt,zjs=dIt,Bjs=xQe,Ujs=uIt,qjs=ZMe,$js=mIt,Vjs=fIt,Hjs=gIt,Gjs=vIt,Wjs=bIt,Kjs=_It,Yjs=jIt,Zjs=kIt,XMe="DropdownMenu",[Xjs,_br]=af(XMe,[aIt]),Ib=aIt(),[Qjs,CIt]=Xjs(XMe),AIt=s=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:a,defaultOpen:i,onOpenChange:l,modal:o=!0}=s,c=Ib(t),d=_.useRef(null),[u,h]=Ug({prop:a,defaultProp:i??!1,onChange:l,caller:XMe});return e.jsx(Qjs,{scope:t,triggerId:Og(),triggerRef:d,contentId:Og(),open:u,onOpenChange:h,onOpenToggle:_.useCallback(()=>h(m=>!m),[h]),modal:o,children:e.jsx(Rjs,{...c,open:u,onOpenChange:h,dir:r,modal:o,children:n})})};AIt.displayName=XMe;var EIt="DropdownMenuTrigger",TIt=_.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...a}=s,i=CIt(EIt,n),l=Ib(n);return e.jsx(Fjs,{asChild:!0,...l,children:e.jsx(ii.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:yE(t,i.triggerRef),onPointerDown:wa(s.onPointerDown,o=>{!r&&o.button===0&&o.ctrlKey===!1&&(i.onOpenToggle(),i.open||o.preventDefault())}),onKeyDown:wa(s.onKeyDown,o=>{r||(["Enter"," "].includes(o.key)&&i.onOpenToggle(),o.key==="ArrowDown"&&i.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(o.key)&&o.preventDefault())})})})});TIt.displayName=EIt;var Jjs="DropdownMenuPortal",MIt=s=>{const{__scopeDropdownMenu:t,...n}=s,r=Ib(t);return e.jsx(Ojs,{...r,...n})};MIt.displayName=Jjs;var PIt="DropdownMenuContent",LIt=_.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=CIt(PIt,n),i=Ib(n),l=_.useRef(!1);return e.jsx(zjs,{id:a.contentId,"aria-labelledby":a.triggerId,...i,...r,ref:t,onCloseAutoFocus:wa(s.onCloseAutoFocus,o=>{var c;l.current||(c=a.triggerRef.current)==null||c.focus(),l.current=!1,o.preventDefault()}),onInteractOutside:wa(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)"}})});LIt.displayName=PIt;var e2s="DropdownMenuGroup",t2s=_.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=Ib(n);return e.jsx(Bjs,{...a,...r,ref:t})});t2s.displayName=e2s;var s2s="DropdownMenuLabel",IIt=_.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=Ib(n);return e.jsx(Ujs,{...a,...r,ref:t})});IIt.displayName=s2s;var n2s="DropdownMenuItem",DIt=_.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=Ib(n);return e.jsx(qjs,{...a,...r,ref:t})});DIt.displayName=n2s;var r2s="DropdownMenuCheckboxItem",RIt=_.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=Ib(n);return e.jsx($js,{...a,...r,ref:t})});RIt.displayName=r2s;var a2s="DropdownMenuRadioGroup",i2s=_.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=Ib(n);return e.jsx(Vjs,{...a,...r,ref:t})});i2s.displayName=a2s;var o2s="DropdownMenuRadioItem",FIt=_.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=Ib(n);return e.jsx(Hjs,{...a,...r,ref:t})});FIt.displayName=o2s;var l2s="DropdownMenuItemIndicator",OIt=_.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=Ib(n);return e.jsx(Gjs,{...a,...r,ref:t})});OIt.displayName=l2s;var c2s="DropdownMenuSeparator",zIt=_.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=Ib(n);return e.jsx(Wjs,{...a,...r,ref:t})});zIt.displayName=c2s;var d2s="DropdownMenuArrow",u2s=_.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=Ib(n);return e.jsx(Kjs,{...a,...r,ref:t})});u2s.displayName=d2s;var h2s="DropdownMenuSubTrigger",BIt=_.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=Ib(n);return e.jsx(Yjs,{...a,...r,ref:t})});BIt.displayName=h2s;var m2s="DropdownMenuSubContent",UIt=_.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=Ib(n);return e.jsx(Zjs,{...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)"}})});UIt.displayName=m2s;var p2s=AIt,f2s=TIt,x2s=MIt,qIt=LIt,$It=IIt,VIt=DIt,HIt=RIt,GIt=FIt,WIt=OIt,KIt=zIt,YIt=BIt,ZIt=UIt;const tu=p2s,su=f2s,g2s=_.forwardRef(({className:s,inset:t,children:n,...r},a)=>e.jsxs(YIt,{ref:a,className:At("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(xi,{className:"ml-auto h-4 w-4"})]}));g2s.displayName=YIt.displayName;const y2s=_.forwardRef(({className:s,...t},n)=>e.jsx(ZIt,{ref:n,className:At("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}));y2s.displayName=ZIt.displayName;const Od=_.forwardRef(({className:s,sideOffset:t=4,...n},r)=>e.jsx(x2s,{children:e.jsx(qIt,{ref:r,sideOffset:t,className:At("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})}));Od.displayName=qIt.displayName;const ca=_.forwardRef(({className:s,inset:t,...n},r)=>e.jsx(VIt,{ref:r,className:At("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}));ca.displayName=VIt.displayName;const v2s=_.forwardRef(({className:s,children:t,checked:n,...r},a)=>e.jsxs(HIt,{ref:a,className:At("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(WIt,{children:e.jsx(ea,{className:"h-4 w-4"})})}),t]}));v2s.displayName=HIt.displayName;const b2s=_.forwardRef(({className:s,children:t,...n},r)=>e.jsxs(GIt,{ref:r,className:At("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(WIt,{children:e.jsx(Uf,{className:"h-2 w-2 fill-current"})})}),t]}));b2s.displayName=GIt.displayName;const PP=_.forwardRef(({className:s,inset:t,...n},r)=>e.jsx($It,{ref:r,className:At("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",s),...n}));PP.displayName=$It.displayName;const M0=_.forwardRef(({className:s,...t},n)=>e.jsx(KIt,{ref:n,className:At("-mx-1 my-1 h-px bg-muted",s),...t}));M0.displayName=KIt.displayName;const _2s=()=>{const{isAssistant:s,actingAsAgent:t,assignedAgents:n,setActingAsAgent:r,isActingAsSelf:a,setActingAsSelf:i}=Ire();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(Fo,{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(In,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"font-medium text-sm",children:"Acting as"})]}),e.jsxs(tu,{children:[e.jsx(su,{asChild:!0,children:e.jsxs(B,{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(Fo,{className:"h-4 w-4"}),e.jsx("strong",{children:"My Account"})]}):t?e.jsxs(e.Fragment,{children:[e.jsxs(ja,{className:"h-5 w-5",children:[e.jsx(pi,{src:t.avatar_url||void 0}),e.jsx(Na,{className:"text-[10px] bg-primary-foreground/30",children:l(t.name)})]}),e.jsx("strong",{children:t.name})]}):e.jsx("strong",{children:"Select..."}),e.jsx(tl,{className:"h-3 w-3"})]})}),e.jsxs(Od,{align:"start",className:"z-[2147483647]",children:[e.jsxs(ca,{onClick:i,className:"gap-2",children:[e.jsx(Fo,{className:"h-4 w-4"}),e.jsx("span",{children:"My Account"}),a&&e.jsx(Oe,{variant:"secondary",className:"ml-auto text-[10px]",children:"Current"})]}),e.jsx(M0,{}),n.map(o=>e.jsxs(ca,{onClick:()=>r(o),className:"gap-2",children:[e.jsxs(ja,{className:"h-6 w-6",children:[e.jsx(pi,{src:o.avatar_url||void 0}),e.jsx(Na,{className:"text-[10px]",children:l(o.name)})]}),e.jsx("span",{children:o.name}),!a&&o.id===(t==null?void 0:t.id)&&e.jsx(Oe,{variant:"secondary",className:"ml-auto text-[10px]",children:"Current"})]},o.id))]})]})]}),e.jsx(Oe,{variant:"secondary",className:"bg-primary-foreground/20 text-primary-foreground border-0 text-xs",children:a?"Personal Mode":"Assistant Mode"})]})})};function IS(){var c,d;const{user:s,isAdmin:t}=hs(),{data:n,isLoading:r}=at({queryKey:["partnership-membership",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),staleTime:5*60*1e3,queryFn:async()=>{const{data:u}=await q.from("partnership_memberships").select("id, status, package_id, program_id").eq("user_id",s.id).eq("status","active").maybeSingle();if(!u)return null;const[{data:h},{data:m}]=await Promise.all([q.from("partnership_packages").select("*").eq("id",u.package_id).maybeSingle(),q.from("partnership_programs").select("id, name, enabled, brokerage_id").eq("id",u.program_id).maybeSingle()]);return!h||!(m!=null&&m.enabled)?null:{membership:u,pkg:h,program:m}}}),a=_.useMemo(()=>{var u;return new Set(((u=n==null?void 0:n.pkg)==null?void 0:u.included_features)||[])},[n]),i=!!n,l=u=>t||!i?!0:a.has(u),o=u=>{var p,f;const h=((p=n==null?void 0:n.pkg)==null?void 0:p.feature_limits)||{},m=(f=h==null?void 0:h[u])==null?void 0:f.monthly_limit;return typeof m=="number"?m:null};return{isLoading:r,isMember:i,membership:(n==null?void 0:n.membership)??null,pkg:(n==null?void 0:n.pkg)??null,program:(n==null?void 0:n.program)??null,packageKey:((c=n==null?void 0:n.pkg)==null?void 0:c.key)??null,packageName:((d=n==null?void 0:n.pkg)==null?void 0:d.name)??null,features:a,hasFeature:l,limitFor:o,isRestricted:i&&!t}}const vQe={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"},wbr=Object.keys(vQe),w2s={home:null,crm:"crm",deals:"deals",listings:"listing_exchange",marketing:"marketing_studio",websites:"website",academy:"learn",events:"learn",apps:null,brokerage:"community",more:null},$mt={"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"},j2s={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 N2s(s){return s.id in $mt?$mt[s.id]:w2s[s.primaryCategory]??null}function k2s(s){return j2s[s]??null}const S2s=[["/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 XIt(s){let t=null;for(const n of S2s){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 ve=_.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:At("rounded-lg border bg-card text-card-foreground shadow-sm",s),...t}));ve.displayName="Card";const bt=_.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:At("flex flex-col space-y-1.5 p-6",s),...t}));bt.displayName="CardHeader";const St=_.forwardRef(({className:s,...t},n)=>e.jsx("h3",{ref:n,className:At("text-2xl font-semibold leading-none tracking-tight",s),...t}));St.displayName="CardTitle";const kn=_.forwardRef(({className:s,...t},n)=>e.jsx("p",{ref:n,className:At("text-sm text-muted-foreground",s),...t}));kn.displayName="CardDescription";const Me=_.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:At("p-6 pt-0",s),...t}));Me.displayName="CardContent";const Q3e=_.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:At("flex items-center p-6 pt-0",s),...t}));Q3e.displayName="CardFooter";const Ms=_.forwardRef(({className:s,...t},n)=>e.jsx("textarea",{className:At("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}));Ms.displayName="Textarea";const Ls=AMe,nl=qXe,C2s=EMe,jbr=kre,QIt=_.forwardRef(({className:s,...t},n)=>e.jsx(XG,{ref:n,className:At("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}));QIt.displayName=XG.displayName;const Ps=_.forwardRef(({className:s,children:t,overlayClassName:n,...r},a)=>e.jsxs(C2s,{children:[e.jsx(QIt,{className:n}),e.jsxs(QG,{ref:a,className:At("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(kre,{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(Qn,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Ps.displayName=QG.displayName;const Os=({className:s,...t})=>e.jsx("div",{className:At("flex flex-col space-y-1.5 text-center sm:text-left",s),...t});Os.displayName="DialogHeader";const yr=({className:s,...t})=>e.jsx("div",{className:At("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",s),...t});yr.displayName="DialogFooter";const Ds=_.forwardRef(({className:s,...t},n)=>e.jsx(jre,{ref:n,className:At("text-lg font-semibold leading-none tracking-tight",s),...t}));Ds.displayName=jre.displayName;const _r=_.forwardRef(({className:s,...t},n)=>e.jsx(Nre,{ref:n,className:At("text-sm text-muted-foreground",s),...t}));_r.displayName=Nre.displayName;function A2s({featureKey:s,open:t,onOpenChange:n}){const{user:r}=hs(),a=Bt(),[i,l]=_.useState(""),{data:o}=at({queryKey:["partnership-upgrade-requests",r==null?void 0:r.id],enabled:!!(r!=null&&r.id)&&t,queryFn:async()=>{const{data:h}=await q.from("lead_site_upgrade_requests").select("id, feature_key, status").eq("user_id",r.id);return h||[]}}),c=!!(o!=null&&o.some(h=>h.feature_key===s&&h.status!=="declined")),d=mt({mutationFn:async()=>{const{error:h}=await q.from("lead_site_upgrade_requests").insert({user_id:r.id,feature_key:s,notes:i||null});if(h)throw h},onSuccess:()=>{a.invalidateQueries({queryKey:["partnership-upgrade-requests"]}),se.success("Request sent — we'll be in touch shortly."),l(""),n(!1)},onError:h=>se.error((h==null?void 0:h.message)||"Could not send your request")}),u=vQe[s]||s;return e.jsx(Ls,{open:t,onOpenChange:n,children:e.jsxs(Ps,{className:"sm:max-w-md",children:[e.jsxs(Os,{children:[e.jsxs(Ds,{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-5 w-5 text-primary"}),"Request ",u]}),e.jsxs(_r,{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(ea,{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(Ms,{placeholder:"Anything we should know? (optional)",value:i,onChange:h=>l(h.target.value),rows:4}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>n(!1),children:"Close"}),!c&&e.jsx(B,{onClick:()=>d.mutate(),disabled:d.isPending,children:d.isPending?"Sending…":"Send request"})]})]})})}function E2s({featureKey:s}){const[t,n]=_.useState(!1),r=vQe[s]||s;return e.jsxs("div",{className:"flex items-center justify-center py-16 px-4",children:[e.jsx(ve,{className:"max-w-lg w-full border-border/60",children:e.jsxs(Me,{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(ec,{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(B,{onClick:()=>n(!0),className:"gap-2",children:[e.jsx(un,{className:"h-4 w-4"})," Request access"]})]})}),e.jsx(A2s,{featureKey:s,open:t,onOpenChange:n})]})}const JIt=s=>{const[t,n]=_.useState(null),[r,a]=_.useState(!0);return _.useEffect(()=>{if(!s){a(!1);return}(async()=>{try{const{data:o}=await q.storage.from("avatars").list(`${s}`);if(o&&o.length>0){const{data:c}=q.storage.from("avatars").getPublicUrl(`${s}/${o[0].name}`);n(`${c.publicUrl}?t=${Date.now()}`)}else n(null)}catch(o){console.error("Error fetching avatar:",o),n(null)}finally{a(!1)}})()},[s]),{avatarUrl:t,loading:r,refreshAvatar:async()=>{if(s)try{const{data:l}=await q.storage.from("avatars").list(`${s}`);if(l&&l.length>0){const{data:o}=q.storage.from("avatars").getPublicUrl(`${s}/${l[0].name}`);n(`${o.publicUrl}?t=${Date.now()}`)}}catch(l){console.error("Error refreshing avatar:",l)}}}},e8t=async s=>{const t=new Map;return await Promise.all(s.map(async n=>{try{const{data:r}=await q.storage.from("avatars").list(`${n}`);if(r&&r.length>0){const{data:a}=q.storage.from("avatars").getPublicUrl(`${n}/${r[0].name}`);t.set(n,a.publicUrl)}}catch{}})),t},T2s=s=>{const[t,n]=_.useState({isTrial:!1,isExpired:!1,expiresAt:null,daysLeft:null,loading:!0});return _.useEffect(()=>{if(!s){n(a=>({...a,loading:!1}));return}(async()=>{try{const{data:a,error:i}=await q.from("profiles").select("is_trial, trial_expires_at, subscription_status, subscription_end_date").eq("id",s).single();if(i){console.error("Error fetching trial status:",i),n(h=>({...h,loading:!1}));return}const l=(a==null?void 0:a.subscription_status)==="trialing",o=!!(a!=null&&a.is_trial),c=!!(a!=null&&a.trial_expires_at)&&new Date(a.trial_expires_at).getTime()>Date.now()&&(a==null?void 0:a.subscription_status)!=="active",d=l&&(a==null?void 0:a.subscription_end_date)||(a==null?void 0:a.trial_expires_at)||(a==null?void 0:a.subscription_end_date)||null;if((l||o||c)&&!!d&&d){const h=new Date().getTime(),m=new Date(d).getTime(),p=Math.ceil((m-h)/(1e3*60*60*24)),f=p<=0;n({isTrial:!0,isExpired:f,expiresAt:d,daysLeft:f?0:p,loading:!1})}else n({isTrial:!1,isExpired:!1,expiresAt:null,daysLeft:null,loading:!1})}catch(a){console.error("Error in useTrialStatus:",a),n(i=>({...i,loading:!1}))}})()},[s]),t},Ore=()=>{const{data:s,isLoading:t}=at({queryKey:["feature-flags"],queryFn:async()=>{const{data:r,error:a}=await q.from("feature_flags").select("*");if(a)throw a;return r}}),n=r=>{if(!s)return!1;const a=s.find(i=>i.key===r);return(a==null?void 0:a.enabled)??!1};return{flags:s,isLoading:t,isFeatureEnabled:n,isAgentOSEnabled:n("agent_os_enabled"),isInnerCircleEnabled:n("innercircle_enabled"),isMarketplaceEnabled:n("marketplace")}},Vmt="community_last_seen_post_at";function M2s(){const{user:s}=hs(),t=ru(),[n,r]=_.useState(0),[a,i]=_.useState(null);_.useEffect(()=>{if(!s)return;const o=localStorage.getItem(`${Vmt}_${s.id}`);i(o)},[s]),_.useEffect(()=>{if(!s)return;const o=`community_unread_count_${s.id}`,c=2*60*1e3;(async()=>{try{const p=sessionStorage.getItem(o);if(p){const f=JSON.parse(p);if(f.ts&&Date.now()-f.ts{if(!s)return;const o=q.channel("community-new-posts").on("postgres_changes",{event:"INSERT",schema:"public",table:"community_posts"},async c=>{const d=c.new;if(d.user_id===s.id)return;const u=t.pathname==="/community";u||r(y=>y+1);const{data:h}=await q.from("profiles").select("name").eq("id",d.user_id).single(),m=(h==null?void 0:h.name)||"Someone",p=d.content.replace(/@\[([^\]]+)\]\([^)]+\)/g,"@$1"),f=p.length>50?p.substring(0,50)+"...":p;u||se("New Community Post",{description:`${m}: ${f}`,action:{label:"View",onClick:()=>{window.location.href="/community"}}})}).subscribe();return()=>{q.removeChannel(o)}},[s,t.pathname]);const l=_.useCallback(()=>{if(!s)return;const o=new Date().toISOString();localStorage.setItem(`${Vmt}_${s.id}`,o),i(o),r(0)},[s]);return _.useEffect(()=>{t.pathname==="/community"&&n>0&&l()},[t.pathname,n,l]),{unreadCount:n,markAsRead:l}}function P2s(){const{isAdmin:s}=hs(),{data:t=0}=at({queryKey:["wishlist-open-count"],queryFn:async()=>{const{count:n,error:r}=await q.from("wishlist_items").select("*",{count:"exact",head:!0}).eq("status","open");if(r)throw r;return n||0},enabled:s,staleTime:6e4});return{openCount:s?t:0}}const lOe=s=>`levelup:activeTeam:${s}`,QMe=()=>{const s=ha();return at({queryKey:["user-teams",s],queryFn:async()=>{const{data:t,error:n}=await q.from("team_members").select("id, team_id, role").eq("user_id",s);if(n)throw n;if(!(t!=null&&t.length))return[];const{data:r,error:a}=await q.from("teams").select("*").in("id",t.map(l=>l.team_id));if(a)throw a;const i=new Map((r||[]).map(l=>[l.id,l]));return t.filter(l=>i.has(l.team_id)).map(l=>({membershipId:l.id,teamId:l.team_id,role:l.role,team:i.get(l.team_id)})).sort((l,o)=>{var c,d;return l.role!==o.role?l.role==="team_leader"?-1:1:(((c=l.team)==null?void 0:c.name)||"").localeCompare(((d=o.team)==null?void 0:d.name)||"")})},enabled:!!s,staleTime:5*60*1e3})},G_=()=>{const s=ha(),t=QMe(),n=_.useMemo(()=>t.data||[],[t.data]),[r,a]=_.useState(()=>!s||typeof window>"u"?null:window.localStorage.getItem(lOe(s)));_.useEffect(()=>{!s||typeof window>"u"||a(window.localStorage.getItem(lOe(s)))},[s]);const i=_.useCallback(o=>{a(o),s&&typeof window<"u"&&window.localStorage.setItem(lOe(s),o)},[s]),l=_.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}},KU="weekly_reels";function JMe(){const{user:s,loading:t,isAdmin:n}=hs(),{data:r,isLoading:a}=at({queryKey:["feature-entitlement",KU,s==null?void 0:s.id],enabled:!!s&&!n,staleTime:5*60*1e3,queryFn:async()=>{const{data:i,error:l}=await q.from("feature_entitlements").select("enabled, expires_at, tier").eq("user_id",s.id).eq("feature_key",KU).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 qg=AMe,zre=qXe,L2s=EMe,t8t=_.forwardRef(({className:s,...t},n)=>e.jsx(XG,{className:At("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}));t8t.displayName=XG.displayName;const I2s=F9("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"}}),hg=_.forwardRef(({side:s="right",className:t,children:n,...r},a)=>e.jsxs(L2s,{children:[e.jsx(t8t,{}),e.jsxs(QG,{ref:a,className:At(I2s({side:s}),t),...r,children:[n,e.jsxs(kre,{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(Qn,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));hg.displayName=QG.displayName;const P0=({className:s,...t})=>e.jsx("div",{className:At("flex flex-col space-y-2 text-center sm:text-left",s),...t});P0.displayName="SheetHeader";const s8t=({className:s,...t})=>e.jsx("div",{className:At("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",s),...t});s8t.displayName="SheetFooter";const L0=_.forwardRef(({className:s,...t},n)=>e.jsx(jre,{ref:n,className:At("text-lg font-semibold text-foreground",s),...t}));L0.displayName=jre.displayName;const U9=_.forwardRef(({className:s,...t},n)=>e.jsx(Nre,{ref:n,className:At("text-sm text-muted-foreground",s),...t}));U9.displayName=Nre.displayName;function tte(s,[t,n]){return Math.min(n,Math.max(t,s))}function D2s(s,t){return _.useReducer((n,r)=>t[n][r]??n,s)}var bQe="ScrollArea",[n8t,Nbr]=af(bQe),[R2s,ON]=n8t(bQe),r8t=_.forwardRef((s,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:a,scrollHideDelay:i=600,...l}=s,[o,c]=_.useState(null),[d,u]=_.useState(null),[h,m]=_.useState(null),[p,f]=_.useState(null),[y,v]=_.useState(null),[g,b]=_.useState(0),[j,S]=_.useState(0),[C,E]=_.useState(!1),[P,M]=_.useState(!1),I=Qo(t,O=>c(O)),D=DE(a);return e.jsx(R2s,{scope:n,type:r,dir:D,scrollHideDelay:i,scrollArea:o,viewport:d,onViewportChange:u,content:h,onContentChange:m,scrollbarX:p,onScrollbarXChange:f,scrollbarXEnabled:C,onScrollbarXEnabledChange:E,scrollbarY:y,onScrollbarYChange:v,scrollbarYEnabled:P,onScrollbarYEnabledChange:M,onCornerWidthChange:b,onCornerHeightChange:S,children:e.jsx(ii.div,{dir:D,...l,ref:I,style:{position:"relative","--radix-scroll-area-corner-width":g+"px","--radix-scroll-area-corner-height":j+"px",...s.style}})})});r8t.displayName=bQe;var a8t="ScrollAreaViewport",i8t=_.forwardRef((s,t)=>{const{__scopeScrollArea:n,children:r,nonce:a,...i}=s,l=ON(a8t,n),o=_.useRef(null),c=Qo(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(ii.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})})]})});i8t.displayName=a8t;var jC="ScrollAreaScrollbar",_Qe=_.forwardRef((s,t)=>{const{forceMount:n,...r}=s,a=ON(jC,s.__scopeScrollArea),{onScrollbarXEnabledChange:i,onScrollbarYEnabledChange:l}=a,o=s.orientation==="horizontal";return _.useEffect(()=>(o?i(!0):l(!0),()=>{o?i(!1):l(!1)}),[o,i,l]),a.type==="hover"?e.jsx(F2s,{...r,ref:t,forceMount:n}):a.type==="scroll"?e.jsx(O2s,{...r,ref:t,forceMount:n}):a.type==="auto"?e.jsx(o8t,{...r,ref:t,forceMount:n}):a.type==="always"?e.jsx(wQe,{...r,ref:t}):null});_Qe.displayName=jC;var F2s=_.forwardRef((s,t)=>{const{forceMount:n,...r}=s,a=ON(jC,s.__scopeScrollArea),[i,l]=_.useState(!1);return _.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(pg,{present:n||i,children:e.jsx(o8t,{"data-state":i?"visible":"hidden",...r,ref:t})})}),O2s=_.forwardRef((s,t)=>{const{forceMount:n,...r}=s,a=ON(jC,s.__scopeScrollArea),i=s.orientation==="horizontal",l=tPe(()=>c("SCROLL_END"),100),[o,c]=D2s("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 _.useEffect(()=>{if(o==="idle"){const d=window.setTimeout(()=>c("HIDE"),a.scrollHideDelay);return()=>window.clearTimeout(d)}},[o,a.scrollHideDelay,c]),_.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(pg,{present:n||o!=="hidden",children:e.jsx(wQe,{"data-state":o==="hidden"?"hidden":"visible",...r,ref:t,onPointerEnter:wa(s.onPointerEnter,()=>c("POINTER_ENTER")),onPointerLeave:wa(s.onPointerLeave,()=>c("POINTER_LEAVE"))})})}),o8t=_.forwardRef((s,t)=>{const n=ON(jC,s.__scopeScrollArea),{forceMount:r,...a}=s,[i,l]=_.useState(!1),o=s.orientation==="horizontal",c=tPe(()=>{if(n.viewport){const d=n.viewport.offsetWidth{const{orientation:n="vertical",...r}=s,a=ON(jC,s.__scopeScrollArea),i=_.useRef(null),l=_.useRef(0),[o,c]=_.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),d=h8t(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 V2s(m,l.current,o,p)}return n==="horizontal"?e.jsx(z2s,{...u,ref:t,onThumbPositionChange:()=>{if(a.viewport&&i.current){const m=a.viewport.scrollLeft,p=Hmt(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(B2s,{...u,ref:t,onThumbPositionChange:()=>{if(a.viewport&&i.current){const m=a.viewport.scrollTop,p=Hmt(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}),z2s=_.forwardRef((s,t)=>{const{sizes:n,onSizesChange:r,...a}=s,i=ON(jC,s.__scopeScrollArea),[l,o]=_.useState(),c=_.useRef(null),d=Qo(t,c,i.onScrollbarXChange);return _.useEffect(()=>{c.current&&o(getComputedStyle(c.current))},[c]),e.jsx(c8t,{"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":ePe(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),p8t(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:eAe(l.paddingLeft),paddingEnd:eAe(l.paddingRight)}})}})}),B2s=_.forwardRef((s,t)=>{const{sizes:n,onSizesChange:r,...a}=s,i=ON(jC,s.__scopeScrollArea),[l,o]=_.useState(),c=_.useRef(null),d=Qo(t,c,i.onScrollbarYChange);return _.useEffect(()=>{c.current&&o(getComputedStyle(c.current))},[c]),e.jsx(c8t,{"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":ePe(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),p8t(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:eAe(l.paddingTop),paddingEnd:eAe(l.paddingBottom)}})}})}),[U2s,l8t]=n8t(jC),c8t=_.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=ON(jC,n),[f,y]=_.useState(null),v=Qo(t,I=>y(I)),g=_.useRef(null),b=_.useRef(""),j=p.viewport,S=r.content-r.viewport,C=wx(u),E=wx(c),P=tPe(h,10);function M(I){if(g.current){const D=I.clientX-g.current.left,O=I.clientY-g.current.top;d({x:D,y:O})}}return _.useEffect(()=>{const I=D=>{const O=D.target;(f==null?void 0:f.contains(O))&&C(D,S)};return document.addEventListener("wheel",I,{passive:!1}),()=>document.removeEventListener("wheel",I,{passive:!1})},[j,f,S,C]),_.useEffect(E,[r,E]),SH(f,P),SH(p.content,P),e.jsx(U2s,{scope:n,scrollbar:f,hasThumb:a,onThumbChange:wx(i),onThumbPointerUp:wx(l),onThumbPositionChange:E,onThumbPointerDown:wx(o),children:e.jsx(ii.div,{...m,ref:v,style:{position:"absolute",...m.style},onPointerDown:wa(s.onPointerDown,I=>{I.button===0&&(I.target.setPointerCapture(I.pointerId),g.current=f.getBoundingClientRect(),b.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",p.viewport&&(p.viewport.style.scrollBehavior="auto"),M(I))}),onPointerMove:wa(s.onPointerMove,M),onPointerUp:wa(s.onPointerUp,I=>{const D=I.target;D.hasPointerCapture(I.pointerId)&&D.releasePointerCapture(I.pointerId),document.body.style.webkitUserSelect=b.current,p.viewport&&(p.viewport.style.scrollBehavior=""),g.current=null})})})}),J3e="ScrollAreaThumb",d8t=_.forwardRef((s,t)=>{const{forceMount:n,...r}=s,a=l8t(J3e,s.__scopeScrollArea);return e.jsx(pg,{present:n||a.hasThumb,children:e.jsx(q2s,{ref:t,...r})})}),q2s=_.forwardRef((s,t)=>{const{__scopeScrollArea:n,style:r,...a}=s,i=ON(J3e,n),l=l8t(J3e,n),{onThumbPositionChange:o}=l,c=Qo(t,h=>l.onThumbChange(h)),d=_.useRef(void 0),u=tPe(()=>{d.current&&(d.current(),d.current=void 0)},100);return _.useEffect(()=>{const h=i.viewport;if(h){const m=()=>{if(u(),!d.current){const p=H2s(h,o);d.current=p,o()}};return o(),h.addEventListener("scroll",m),()=>h.removeEventListener("scroll",m)}},[i.viewport,u,o]),e.jsx(ii.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:wa(s.onPointerDownCapture,h=>{const p=h.target.getBoundingClientRect(),f=h.clientX-p.left,y=h.clientY-p.top;l.onThumbPointerDown({x:f,y})}),onPointerUp:wa(s.onPointerUp,l.onThumbPointerUp)})});d8t.displayName=J3e;var jQe="ScrollAreaCorner",u8t=_.forwardRef((s,t)=>{const n=ON(jQe,s.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?e.jsx($2s,{...s,ref:t}):null});u8t.displayName=jQe;var $2s=_.forwardRef((s,t)=>{const{__scopeScrollArea:n,...r}=s,a=ON(jQe,n),[i,l]=_.useState(0),[o,c]=_.useState(0),d=!!(i&&o);return SH(a.scrollbarX,()=>{var h;const u=((h=a.scrollbarX)==null?void 0:h.offsetHeight)||0;a.onCornerHeightChange(u),c(u)}),SH(a.scrollbarY,()=>{var h;const u=((h=a.scrollbarY)==null?void 0:h.offsetWidth)||0;a.onCornerWidthChange(u),l(u)}),d?e.jsx(ii.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 eAe(s){return s?parseInt(s,10):0}function h8t(s,t){const n=s/t;return isNaN(n)?0:n}function ePe(s){const t=h8t(s.viewport,s.content),n=s.scrollbar.paddingStart+s.scrollbar.paddingEnd,r=(s.scrollbar.size-n)*t;return Math.max(r,18)}function V2s(s,t,n,r="ltr"){const a=ePe(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 m8t([c,d],h)(s)}function Hmt(s,t,n="ltr"){const r=ePe(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=tte(s,c);return m8t([0,l],[0,o])(d)}function m8t(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 p8t(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 tPe(s,t){const n=wx(s),r=_.useRef(0);return _.useEffect(()=>()=>window.clearTimeout(r.current),[]),_.useCallback(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}function SH(s,t){const n=wx(t);Mx(()=>{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 f8t=r8t,G2s=i8t,W2s=u8t;const Ji=_.forwardRef(({className:s,children:t,...n},r)=>e.jsxs(f8t,{ref:r,className:At("relative overflow-hidden",s),...n,children:[e.jsx(G2s,{className:"h-full w-full rounded-[inherit]",children:t}),e.jsx(Bre,{}),e.jsx(W2s,{})]}));Ji.displayName=f8t.displayName;const Bre=_.forwardRef(({className:s,orientation:t="vertical",...n},r)=>e.jsx(_Qe,{ref:r,orientation:t,className:At("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(d8t,{className:"relative flex-1 rounded-full bg-border"})}));Bre.displayName=_Qe.displayName;const K2s="/assets/levelup-logo-Eif24dqY.png",Y2s="/assets/levelup-logo-icon-C-7iromj.png",Z2s="/assets/levelup-logo-mobile-B9skSjUG.png";var Ure=s=>s.type==="checkbox",dF=s=>s instanceof Date,ab=s=>s==null;const x8t=s=>typeof s=="object";var ug=s=>!ab(s)&&!Array.isArray(s)&&x8t(s)&&!dF(s),g8t=s=>ug(s)&&s.target?Ure(s.target)?s.target.checked:s.target.value:s,X2s=s=>s.substring(0,s.search(/\.\d+(\.|$)/))||s,y8t=(s,t)=>s.has(X2s(t)),Q2s=s=>{const t=s.constructor&&s.constructor.prototype;return ug(t)&&t.hasOwnProperty("isPrototypeOf")},NQe=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function n0(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(!(NQe&&(s instanceof Blob||r))&&(n||ug(s)))if(t=n?[]:{},!n&&!Q2s(s))t=s;else for(const a in s)s.hasOwnProperty(a)&&(t[a]=n0(s[a]));else return s;return t}var sPe=s=>/^\w*$/.test(s),Kx=s=>s===void 0,kQe=s=>Array.isArray(s)?s.filter(Boolean):[],SQe=s=>kQe(s.replace(/["|']|\]/g,"").split(/\.|\[/)),Ui=(s,t,n)=>{if(!t||!ug(s))return n;const r=(sPe(t)?[t]:SQe(t)).reduce((a,i)=>ab(a)?a:a[i],s);return Kx(r)||r===s?Kx(s[t])?n:s[t]:r},Gw=s=>typeof s=="boolean",Dh=(s,t,n)=>{let r=-1;const a=sPe(t)?[t]:SQe(t),i=a.length,l=i-1;for(;++rDt.useContext(CQe),J2s=s=>{const{children:t,...n}=s;return Dt.createElement(CQe.Provider,{value:n},t)};var v8t=(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]!==eS.all&&(t._proxyFormState[l]=!r||eS.all),n&&(n[l]=!0),s[l]}});return a};const AQe=typeof window<"u"?Dt.useLayoutEffect:Dt.useEffect;function eNs(s){const t=nPe(),{control:n=t.control,disabled:r,name:a,exact:i}=s||{},[l,o]=Dt.useState(n._formState),c=Dt.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,validatingFields:!1,isValidating:!1,isValid:!1,errors:!1});return AQe(()=>n._subscribe({name:a,formState:c.current,exact:i,callback:d=>{!r&&o({...n._formState,...d})}}),[a,r,i]),Dt.useEffect(()=>{c.current.isValid&&n._setValid(!0)},[n]),Dt.useMemo(()=>v8t(l,n,c.current,!1),[l,n])}var T4=s=>typeof s=="string",b8t=(s,t,n,r,a)=>T4(s)?(r&&t.watch.add(s),Ui(n,s,a)):Array.isArray(s)?s.map(i=>(r&&t.watch.add(i),Ui(n,i))):(r&&(t.watchAll=!0),n),N$e=s=>ab(s)||!x8t(s);function SA(s,t,n=new WeakSet){if(N$e(s)||N$e(t))return s===t;if(dF(s)&&dF(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(dF(l)&&dF(o)||ug(l)&&ug(o)||Array.isArray(l)&&Array.isArray(o)?!SA(l,o,n):l!==o)return!1}}return!0}function tNs(s){const t=nPe(),{control:n=t.control,name:r,defaultValue:a,disabled:i,exact:l,compute:o}=s||{},c=Dt.useRef(a),d=Dt.useRef(o),u=Dt.useRef(void 0);d.current=o;const h=Dt.useMemo(()=>n._getWatch(r,c.current),[n,r]),[m,p]=Dt.useState(d.current?d.current(h):h);return AQe(()=>n._subscribe({name:r,formState:{values:!0},exact:l,callback:f=>{if(!i){const y=b8t(r,n._names,f.values||n._formValues,!1,c.current);if(d.current){const v=d.current(y);SA(v,u.current)||(p(v),u.current=v)}else p(y)}}}),[n,i,r,l]),Dt.useEffect(()=>n._removeUnmounted()),m}function sNs(s){const t=nPe(),{name:n,disabled:r,control:a=t.control,shouldUnregister:i,defaultValue:l}=s,o=y8t(a._names.array,n),c=Dt.useMemo(()=>Ui(a._formValues,n,Ui(a._defaultValues,n,l)),[a,n,l]),d=tNs({control:a,name:n,defaultValue:c,exact:!0}),u=eNs({control:a,name:n,exact:!0}),h=Dt.useRef(s),m=Dt.useRef(a.register(n,{...s.rules,value:d,...Gw(s.disabled)?{disabled:s.disabled}:{}}));h.current=s;const p=Dt.useMemo(()=>Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!Ui(u.errors,n)},isDirty:{enumerable:!0,get:()=>!!Ui(u.dirtyFields,n)},isTouched:{enumerable:!0,get:()=>!!Ui(u.touchedFields,n)},isValidating:{enumerable:!0,get:()=>!!Ui(u.validatingFields,n)},error:{enumerable:!0,get:()=>Ui(u.errors,n)}}),[u,n]),f=Dt.useCallback(b=>m.current.onChange({target:{value:g8t(b),name:n},type:tAe.CHANGE}),[n]),y=Dt.useCallback(()=>m.current.onBlur({target:{value:Ui(a._formValues,n),name:n},type:tAe.BLUR}),[n,a._formValues]),v=Dt.useCallback(b=>{const j=Ui(a._fields,n);j&&b&&(j._f.ref={focus:()=>b.focus&&b.focus(),select:()=>b.select&&b.select(),setCustomValidity:S=>b.setCustomValidity(S),reportValidity:()=>b.reportValidity()})},[a._fields,n]),g=Dt.useMemo(()=>({name:n,value:d,...Gw(r)||u.disabled?{disabled:u.disabled||r}:{},onChange:f,onBlur:y,ref:v}),[n,r,u.disabled,f,y,v,d]);return Dt.useEffect(()=>{const b=a._options.shouldUnregister||i;a.register(n,{...h.current.rules,...Gw(h.current.disabled)?{disabled:h.current.disabled}:{}});const j=(S,C)=>{const E=Ui(a._fields,S);E&&E._f&&(E._f.mount=C)};if(j(n,!0),b){const S=n0(Ui(a._options.defaultValues,n));Dh(a._defaultValues,n,S),Kx(Ui(a._formValues,n))&&Dh(a._formValues,n,S)}return!o&&a.register(n),()=>{(o?b&&!a._state.action:b)?a.unregister(n):j(n,!1)}},[n,a,o,i]),Dt.useEffect(()=>{a._setDisabledField({disabled:r,name:n})},[r,n,a]),Dt.useMemo(()=>({field:g,formState:u,fieldState:p}),[g,u,p])}const nNs=s=>s.render(sNs(s));var _8t=(s,t,n,r,a)=>t?{...n[s],types:{...n[s]&&n[s].types?n[s].types:{},[r]:a||!0}}:{},vJ=s=>Array.isArray(s)?s:[s],Gmt=()=>{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=[]}}},p_=s=>ug(s)&&!Object.keys(s).length,EQe=s=>s.type==="file",tS=s=>typeof s=="function",sAe=s=>{if(!NQe)return!1;const t=s?s.ownerDocument:0;return s instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},w8t=s=>s.type==="select-multiple",TQe=s=>s.type==="radio",rNs=s=>TQe(s)||Ure(s),cOe=s=>sAe(s)&&s.isConnected;function aNs(s,t){const n=t.slice(0,-1).length;let r=0;for(;r{for(const t in s)if(tS(s[t]))return!0;return!1};function nAe(s,t={}){const n=Array.isArray(s);if(ug(s)||n)for(const r in s)Array.isArray(s[r])||ug(s[r])&&!j8t(s[r])?(t[r]=Array.isArray(s[r])?[]:{},nAe(s[r],t[r])):ab(s[r])||(t[r]=!0);return t}function N8t(s,t,n){const r=Array.isArray(s);if(ug(s)||r)for(const a in s)Array.isArray(s[a])||ug(s[a])&&!j8t(s[a])?Kx(t)||N$e(n[a])?n[a]=Array.isArray(s[a])?nAe(s[a],[]):{...nAe(s[a])}:N8t(s[a],ab(t)?{}:t[a],n[a]):n[a]=!SA(s[a],t[a]);return n}var LY=(s,t)=>N8t(s,t,nAe(t));const Wmt={value:!1,isValid:!1},Kmt={value:!0,isValid:!0};var k8t=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&&!Kx(s[0].attributes.value)?Kx(s[0].value)||s[0].value===""?Kmt:{value:s[0].value,isValid:!0}:Kmt:Wmt}return Wmt},S8t=(s,{valueAsNumber:t,valueAsDate:n,setValueAs:r})=>Kx(s)?s:t?s===""?NaN:s&&+s:n&&T4(s)?new Date(s):r?r(s):s;const Ymt={isValid:!1,value:null};var C8t=s=>Array.isArray(s)?s.reduce((t,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:t,Ymt):Ymt;function Zmt(s){const t=s.ref;return EQe(t)?t.files:TQe(t)?C8t(s.refs).value:w8t(t)?[...t.selectedOptions].map(({value:n})=>n):Ure(t)?k8t(s.refs).value:S8t(Kx(t.value)?s.ref.value:t.value,s)}var oNs=(s,t,n,r)=>{const a={};for(const i of s){const l=Ui(t,i);l&&Dh(a,i,l._f)}return{criteriaMode:n,names:[...s],fields:a,shouldUseNativeValidation:r}},rAe=s=>s instanceof RegExp,IY=s=>Kx(s)?s:rAe(s)?s.source:ug(s)?rAe(s.value)?s.value.source:s.value:s,Xmt=s=>({isOnSubmit:!s||s===eS.onSubmit,isOnBlur:s===eS.onBlur,isOnChange:s===eS.onChange,isOnAll:s===eS.all,isOnTouch:s===eS.onTouched});const Qmt="AsyncFunction";var lNs=s=>!!s&&!!s.validate&&!!(tS(s.validate)&&s.validate.constructor.name===Qmt||ug(s.validate)&&Object.values(s.validate).find(t=>t.constructor.name===Qmt)),cNs=s=>s.mount&&(s.required||s.min||s.max||s.maxLength||s.minLength||s.pattern||s.validate),Jmt=(s,t,n)=>!n&&(t.watchAll||t.watch.has(s)||[...t.watch].some(r=>s.startsWith(r)&&/^\.\w+/.test(s.slice(r.length))));const bJ=(s,t,n,r)=>{for(const a of n||Object.keys(s)){const i=Ui(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(bJ(o,t))break}else if(ug(o)&&bJ(o,t))break}}};function ept(s,t,n){const r=Ui(s,n);if(r||sPe(n))return{error:r,name:n};const a=n.split(".");for(;a.length;){const i=a.join("."),l=Ui(t,i),o=Ui(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 dNs=(s,t,n,r)=>{n(s);const{name:a,...i}=s;return p_(i)||Object.keys(i).length>=Object.keys(t).length||Object.keys(i).find(l=>t[l]===(!r||eS.all))},uNs=(s,t,n)=>!s||!t||s===t||vJ(s).some(r=>r&&(n?r===t:r.startsWith(t)||t.startsWith(r))),hNs=(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,mNs=(s,t)=>!kQe(Ui(s,t)).length&&Ng(s,t),pNs=(s,t,n)=>{const r=vJ(Ui(s,n));return Dh(r,"root",t[n]),Dh(s,n,r),s},v4e=s=>T4(s);function tpt(s,t,n="validate"){if(v4e(s)||Array.isArray(s)&&s.every(v4e)||Gw(s)&&!s)return{type:n,message:v4e(s)?s:"",ref:t}}var yB=s=>ug(s)&&!rAe(s)?s:{value:s,message:""},spt=async(s,t,n,r,a,i)=>{const{ref:l,refs:o,required:c,maxLength:d,minLength:u,min:h,max:m,pattern:p,validate:f,name:y,valueAsNumber:v,mount:g}=s._f,b=Ui(n,y);if(!g||t.has(y))return{};const j=o?o[0]:l,S=V=>{a&&j.reportValidity&&(j.setCustomValidity(Gw(V)?"":V||""),j.reportValidity())},C={},E=TQe(l),P=Ure(l),M=E||P,I=(v||EQe(l))&&Kx(l.value)&&Kx(b)||sAe(l)&&l.value===""||b===""||Array.isArray(b)&&!b.length,D=_8t.bind(null,y,r,C),O=(V,G,$,H=h3.maxLength,Y=h3.minLength)=>{const Z=V?G:$;C[y]={type:V?H:Y,message:Z,ref:l,...D(V?H:Y,Z)}};if(i?!Array.isArray(b)||!b.length:c&&(!M&&(I||ab(b))||Gw(b)&&!b||P&&!k8t(o).isValid||E&&!C8t(o).isValid)){const{value:V,message:G}=v4e(c)?{value:!!c,message:c}:yB(c);if(V&&(C[y]={type:h3.required,message:G,ref:j,...D(h3.required,G)},!r))return S(G),C}if(!I&&(!ab(h)||!ab(m))){let V,G;const $=yB(m),H=yB(h);if(!ab(b)&&!isNaN(b)){const Y=l.valueAsNumber||b&&+b;ab($.value)||(V=Y>$.value),ab(H.value)||(G=Ynew Date(new Date().toDateString()+" "+ie),ne=l.type=="time",ce=l.type=="week";T4($.value)&&b&&(V=ne?Z(b)>Z($.value):ce?b>$.value:Y>new Date($.value)),T4(H.value)&&b&&(G=ne?Z(b)+V.value,H=!ab(G.value)&&b.length<+G.value;if(($||H)&&(O($,V.message,G.message),!r))return S(C[y].message),C}if(p&&!I&&T4(b)){const{value:V,message:G}=yB(p);if(rAe(V)&&!b.match(V)&&(C[y]={type:h3.pattern,message:G,ref:l,...D(h3.pattern,G)},!r))return S(G),C}if(f){if(tS(f)){const V=await f(b,n),G=tpt(V,j);if(G&&(C[y]={...G,...D(h3.validate,G.message)},!r))return S(G.message),C}else if(ug(f)){let V={};for(const G in f){if(!p_(V)&&!r)break;const $=tpt(await f[G](b,n),j,G);$&&(V={...$,...D(G,$.message)},S($.message),r&&(C[y]=V))}if(!p_(V)&&(C[y]={ref:j,...V},!r))return C}}return S(!0),C};const fNs={mode:eS.onSubmit,reValidateMode:eS.onChange,shouldFocusError:!0};function xNs(s={}){let t={...fNs,...s},n={submitCount:0,isDirty:!1,isReady:!1,isLoading:tS(t.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{},errors:t.errors||{},disabled:t.disabled||!1},r={},a=ug(t.defaultValues)||ug(t.values)?n0(t.defaultValues||t.values)||{}:{},i=t.shouldUnregister?{}:n0(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:Gmt(),state:Gmt()},p=t.criteriaMode===eS.all,f=Qe=>Ue=>{clearTimeout(d),d=setTimeout(Qe,Ue)},y=async Qe=>{if(!t.disabled&&(u.isValid||h.isValid||Qe)){const Ue=t.resolver?p_((await P()).errors):await I(r,!0);Ue!==n.isValid&&m.state.next({isValid:Ue})}},v=(Qe,Ue)=>{!t.disabled&&(u.isValidating||u.validatingFields||h.isValidating||h.validatingFields)&&((Qe||Array.from(o.mount)).forEach(Xe=>{Xe&&(Ue?Dh(n.validatingFields,Xe,Ue):Ng(n.validatingFields,Xe))}),m.state.next({validatingFields:n.validatingFields,isValidating:!p_(n.validatingFields)}))},g=(Qe,Ue=[],Xe,nt,$e=!0,Ge=!0)=>{if(nt&&Xe&&!t.disabled){if(l.action=!0,Ge&&Array.isArray(Ui(r,Qe))){const ct=Xe(Ui(r,Qe),nt.argA,nt.argB);$e&&Dh(r,Qe,ct)}if(Ge&&Array.isArray(Ui(n.errors,Qe))){const ct=Xe(Ui(n.errors,Qe),nt.argA,nt.argB);$e&&Dh(n.errors,Qe,ct),mNs(n.errors,Qe)}if((u.touchedFields||h.touchedFields)&&Ge&&Array.isArray(Ui(n.touchedFields,Qe))){const ct=Xe(Ui(n.touchedFields,Qe),nt.argA,nt.argB);$e&&Dh(n.touchedFields,Qe,ct)}(u.dirtyFields||h.dirtyFields)&&(n.dirtyFields=LY(a,i)),m.state.next({name:Qe,isDirty:O(Qe,Ue),dirtyFields:n.dirtyFields,errors:n.errors,isValid:n.isValid})}else Dh(i,Qe,Ue)},b=(Qe,Ue)=>{Dh(n.errors,Qe,Ue),m.state.next({errors:n.errors})},j=Qe=>{n.errors=Qe,m.state.next({errors:n.errors,isValid:!1})},S=(Qe,Ue,Xe,nt)=>{const $e=Ui(r,Qe);if($e){const Ge=Ui(i,Qe,Kx(Xe)?Ui(a,Qe):Xe);Kx(Ge)||nt&&nt.defaultChecked||Ue?Dh(i,Qe,Ue?Ge:Zmt($e._f)):$(Qe,Ge),l.mount&&y()}},C=(Qe,Ue,Xe,nt,$e)=>{let Ge=!1,ct=!1;const xt={name:Qe};if(!t.disabled){if(!Xe||nt){(u.isDirty||h.isDirty)&&(ct=n.isDirty,n.isDirty=xt.isDirty=O(),Ge=ct!==xt.isDirty);const qt=SA(Ui(a,Qe),Ue);ct=!!Ui(n.dirtyFields,Qe),qt?Ng(n.dirtyFields,Qe):Dh(n.dirtyFields,Qe,!0),xt.dirtyFields=n.dirtyFields,Ge=Ge||(u.dirtyFields||h.dirtyFields)&&ct!==!qt}if(Xe){const qt=Ui(n.touchedFields,Qe);qt||(Dh(n.touchedFields,Qe,Xe),xt.touchedFields=n.touchedFields,Ge=Ge||(u.touchedFields||h.touchedFields)&&qt!==Xe)}Ge&&$e&&m.state.next(xt)}return Ge?xt:{}},E=(Qe,Ue,Xe,nt)=>{const $e=Ui(n.errors,Qe),Ge=(u.isValid||h.isValid)&&Gw(Ue)&&n.isValid!==Ue;if(t.delayError&&Xe?(c=f(()=>b(Qe,Xe)),c(t.delayError)):(clearTimeout(d),c=null,Xe?Dh(n.errors,Qe,Xe):Ng(n.errors,Qe)),(Xe?!SA($e,Xe):$e)||!p_(nt)||Ge){const ct={...nt,...Ge&&Gw(Ue)?{isValid:Ue}:{},errors:n.errors,name:Qe};n={...n,...ct},m.state.next(ct)}},P=async Qe=>{v(Qe,!0);const Ue=await t.resolver(i,t.context,oNs(Qe||o.mount,r,t.criteriaMode,t.shouldUseNativeValidation));return v(Qe),Ue},M=async Qe=>{const{errors:Ue}=await P(Qe);if(Qe)for(const Xe of Qe){const nt=Ui(Ue,Xe);nt?Dh(n.errors,Xe,nt):Ng(n.errors,Xe)}else n.errors=Ue;return Ue},I=async(Qe,Ue,Xe={valid:!0})=>{for(const nt in Qe){const $e=Qe[nt];if($e){const{_f:Ge,...ct}=$e;if(Ge){const xt=o.array.has(Ge.name),qt=$e._f&&lNs($e._f);qt&&u.validatingFields&&v([nt],!0);const Vt=await spt($e,o.disabled,i,p,t.shouldUseNativeValidation&&!Ue,xt);if(qt&&u.validatingFields&&v([nt]),Vt[Ge.name]&&(Xe.valid=!1,Ue))break;!Ue&&(Ui(Vt,Ge.name)?xt?pNs(n.errors,Vt,Ge.name):Dh(n.errors,Ge.name,Vt[Ge.name]):Ng(n.errors,Ge.name))}!p_(ct)&&await I(ct,Ue,Xe)}}return Xe.valid},D=()=>{for(const Qe of o.unMount){const Ue=Ui(r,Qe);Ue&&(Ue._f.refs?Ue._f.refs.every(Xe=>!cOe(Xe)):!cOe(Ue._f.ref))&&pe(Qe)}o.unMount=new Set},O=(Qe,Ue)=>!t.disabled&&(Qe&&Ue&&Dh(i,Qe,Ue),!SA(ie(),a)),V=(Qe,Ue,Xe)=>b8t(Qe,o,{...l.mount?i:Kx(Ue)?a:T4(Qe)?{[Qe]:Ue}:Ue},Xe,Ue),G=Qe=>kQe(Ui(l.mount?i:a,Qe,t.shouldUnregister?Ui(a,Qe,[]):[])),$=(Qe,Ue,Xe={})=>{const nt=Ui(r,Qe);let $e=Ue;if(nt){const Ge=nt._f;Ge&&(!Ge.disabled&&Dh(i,Qe,S8t(Ue,Ge)),$e=sAe(Ge.ref)&&ab(Ue)?"":Ue,w8t(Ge.ref)?[...Ge.ref.options].forEach(ct=>ct.selected=$e.includes(ct.value)):Ge.refs?Ure(Ge.ref)?Ge.refs.forEach(ct=>{(!ct.defaultChecked||!ct.disabled)&&(Array.isArray($e)?ct.checked=!!$e.find(xt=>xt===ct.value):ct.checked=$e===ct.value||!!$e)}):Ge.refs.forEach(ct=>ct.checked=ct.value===$e):EQe(Ge.ref)?Ge.ref.value="":(Ge.ref.value=$e,Ge.ref.type||m.state.next({name:Qe,values:n0(i)})))}(Xe.shouldDirty||Xe.shouldTouch)&&C(Qe,$e,Xe.shouldTouch,Xe.shouldDirty,!0),Xe.shouldValidate&&ce(Qe)},H=(Qe,Ue,Xe)=>{for(const nt in Ue){if(!Ue.hasOwnProperty(nt))return;const $e=Ue[nt],Ge=Qe+"."+nt,ct=Ui(r,Ge);(o.array.has(Qe)||ug($e)||ct&&!ct._f)&&!dF($e)?H(Ge,$e,Xe):$(Ge,$e,Xe)}},Y=(Qe,Ue,Xe={})=>{const nt=Ui(r,Qe),$e=o.array.has(Qe),Ge=n0(Ue);Dh(i,Qe,Ge),$e?(m.array.next({name:Qe,values:n0(i)}),(u.isDirty||u.dirtyFields||h.isDirty||h.dirtyFields)&&Xe.shouldDirty&&m.state.next({name:Qe,dirtyFields:LY(a,i),isDirty:O(Qe,Ge)})):nt&&!nt._f&&!ab(Ge)?H(Qe,Ge,Xe):$(Qe,Ge,Xe),Jmt(Qe,o)&&m.state.next({...n,name:Qe}),m.state.next({name:l.mount?Qe:void 0,values:n0(i)})},Z=async Qe=>{l.mount=!0;const Ue=Qe.target;let Xe=Ue.name,nt=!0;const $e=Ui(r,Xe),Ge=qt=>{nt=Number.isNaN(qt)||dF(qt)&&isNaN(qt.getTime())||SA(qt,Ui(i,Xe,qt))},ct=Xmt(t.mode),xt=Xmt(t.reValidateMode);if($e){let qt,Vt;const Xt=Ue.type?Zmt($e._f):g8t(Qe),fs=Qe.type===tAe.BLUR||Qe.type===tAe.FOCUS_OUT,Ft=!cNs($e._f)&&!t.resolver&&!Ui(n.errors,Xe)&&!$e._f.deps||hNs(fs,Ui(n.touchedFields,Xe),n.isSubmitted,xt,ct),wt=Jmt(Xe,o,fs);Dh(i,Xe,Xt),fs?($e._f.onBlur&&$e._f.onBlur(Qe),c&&c(0)):$e._f.onChange&&$e._f.onChange(Qe);const Ts=C(Xe,Xt,fs),vt=!p_(Ts)||wt;if(!fs&&m.state.next({name:Xe,type:Qe.type,values:n0(i)}),Ft)return(u.isValid||h.isValid)&&(t.mode==="onBlur"?fs&&y():fs||y()),vt&&m.state.next({name:Xe,...wt?{}:Ts});if(!fs&&wt&&m.state.next({...n}),t.resolver){const{errors:$s}=await P([Xe]);if(Ge(Xt),nt){const As=ept(n.errors,r,Xe),jn=ept($s,r,As.name||Xe);qt=jn.error,Xe=jn.name,Vt=p_($s)}}else v([Xe],!0),qt=(await spt($e,o.disabled,i,p,t.shouldUseNativeValidation))[Xe],v([Xe]),Ge(Xt),nt&&(qt?Vt=!1:(u.isValid||h.isValid)&&(Vt=await I(r,!0)));nt&&($e._f.deps&&ce($e._f.deps),E(Xe,Vt,qt,Ts))}},ne=(Qe,Ue)=>{if(Ui(n.errors,Ue)&&Qe.focus)return Qe.focus(),1},ce=async(Qe,Ue={})=>{let Xe,nt;const $e=vJ(Qe);if(t.resolver){const Ge=await M(Kx(Qe)?Qe:$e);Xe=p_(Ge),nt=Qe?!$e.some(ct=>Ui(Ge,ct)):Xe}else Qe?(nt=(await Promise.all($e.map(async Ge=>{const ct=Ui(r,Ge);return await I(ct&&ct._f?{[Ge]:ct}:ct)}))).every(Boolean),!(!nt&&!n.isValid)&&y()):nt=Xe=await I(r);return m.state.next({...!T4(Qe)||(u.isValid||h.isValid)&&Xe!==n.isValid?{}:{name:Qe},...t.resolver||!Qe?{isValid:Xe}:{},errors:n.errors}),Ue.shouldFocus&&!nt&&bJ(r,ne,Qe?$e:o.mount),nt},ie=Qe=>{const Ue={...l.mount?i:a};return Kx(Qe)?Ue:T4(Qe)?Ui(Ue,Qe):Qe.map(Xe=>Ui(Ue,Xe))},te=(Qe,Ue)=>({invalid:!!Ui((Ue||n).errors,Qe),isDirty:!!Ui((Ue||n).dirtyFields,Qe),error:Ui((Ue||n).errors,Qe),isValidating:!!Ui(n.validatingFields,Qe),isTouched:!!Ui((Ue||n).touchedFields,Qe)}),ae=Qe=>{Qe&&vJ(Qe).forEach(Ue=>Ng(n.errors,Ue)),m.state.next({errors:Qe?n.errors:{}})},le=(Qe,Ue,Xe)=>{const nt=(Ui(r,Qe,{_f:{}})._f||{}).ref,$e=Ui(n.errors,Qe)||{},{ref:Ge,message:ct,type:xt,...qt}=$e;Dh(n.errors,Qe,{...qt,...Ue,ref:nt}),m.state.next({name:Qe,errors:n.errors,isValid:!1}),Xe&&Xe.shouldFocus&&nt&&nt.focus&&nt.focus()},be=(Qe,Ue)=>tS(Qe)?m.state.subscribe({next:Xe=>"values"in Xe&&Qe(V(void 0,Ue),Xe)}):V(Qe,Ue,!0),me=Qe=>m.state.subscribe({next:Ue=>{uNs(Qe.name,Ue.name,Qe.exact)&&dNs(Ue,Qe.formState||u,Ye,Qe.reRenderRoot)&&Qe.callback({values:{...i},...n,...Ue,defaultValues:a})}}).unsubscribe,he=Qe=>(l.mount=!0,h={...h,...Qe.formState},me({...Qe,formState:h})),pe=(Qe,Ue={})=>{for(const Xe of Qe?vJ(Qe):o.mount)o.mount.delete(Xe),o.array.delete(Xe),Ue.keepValue||(Ng(r,Xe),Ng(i,Xe)),!Ue.keepError&&Ng(n.errors,Xe),!Ue.keepDirty&&Ng(n.dirtyFields,Xe),!Ue.keepTouched&&Ng(n.touchedFields,Xe),!Ue.keepIsValidating&&Ng(n.validatingFields,Xe),!t.shouldUnregister&&!Ue.keepDefaultValue&&Ng(a,Xe);m.state.next({values:n0(i)}),m.state.next({...n,...Ue.keepDirty?{isDirty:O()}:{}}),!Ue.keepIsValid&&y()},Ce=({disabled:Qe,name:Ue})=>{(Gw(Qe)&&l.mount||Qe||o.disabled.has(Ue))&&(Qe?o.disabled.add(Ue):o.disabled.delete(Ue))},Ae=(Qe,Ue={})=>{let Xe=Ui(r,Qe);const nt=Gw(Ue.disabled)||Gw(t.disabled);return Dh(r,Qe,{...Xe||{},_f:{...Xe&&Xe._f?Xe._f:{ref:{name:Qe}},name:Qe,mount:!0,...Ue}}),o.mount.add(Qe),Xe?Ce({disabled:Gw(Ue.disabled)?Ue.disabled:t.disabled,name:Qe}):S(Qe,!0,Ue.value),{...nt?{disabled:Ue.disabled||t.disabled}:{},...t.progressive?{required:!!Ue.required,min:IY(Ue.min),max:IY(Ue.max),minLength:IY(Ue.minLength),maxLength:IY(Ue.maxLength),pattern:IY(Ue.pattern)}:{},name:Qe,onChange:Z,onBlur:Z,ref:$e=>{if($e){Ae(Qe,Ue),Xe=Ui(r,Qe);const Ge=Kx($e.value)&&$e.querySelectorAll&&$e.querySelectorAll("input,select,textarea")[0]||$e,ct=rNs(Ge),xt=Xe._f.refs||[];if(ct?xt.find(qt=>qt===Ge):Ge===Xe._f.ref)return;Dh(r,Qe,{_f:{...Xe._f,...ct?{refs:[...xt.filter(cOe),Ge,...Array.isArray(Ui(a,Qe))?[{}]:[]],ref:{type:Ge.type,name:Qe}}:{ref:Ge}}}),S(Qe,!1,void 0,Ge)}else Xe=Ui(r,Qe,{}),Xe._f&&(Xe._f.mount=!1),(t.shouldUnregister||Ue.shouldUnregister)&&!(y8t(o.array,Qe)&&l.action)&&o.unMount.add(Qe)}}},Pe=()=>t.shouldFocusError&&bJ(r,ne,o.mount),ze=Qe=>{Gw(Qe)&&(m.state.next({disabled:Qe}),bJ(r,(Ue,Xe)=>{const nt=Ui(r,Xe);nt&&(Ue.disabled=nt._f.disabled||Qe,Array.isArray(nt._f.refs)&&nt._f.refs.forEach($e=>{$e.disabled=nt._f.disabled||Qe}))},0,!1))},ke=(Qe,Ue)=>async Xe=>{let nt;Xe&&(Xe.preventDefault&&Xe.preventDefault(),Xe.persist&&Xe.persist());let $e=n0(i);if(m.state.next({isSubmitting:!0}),t.resolver){const{errors:Ge,values:ct}=await P();n.errors=Ge,$e=n0(ct)}else await I(r);if(o.disabled.size)for(const Ge of o.disabled)Ng($e,Ge);if(Ng(n.errors,"root"),p_(n.errors)){m.state.next({errors:{}});try{await Qe($e,Xe)}catch(Ge){nt=Ge}}else Ue&&await Ue({...n.errors},Xe),Pe(),setTimeout(Pe);if(m.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:p_(n.errors)&&!nt,submitCount:n.submitCount+1,errors:n.errors}),nt)throw nt},Ze=(Qe,Ue={})=>{Ui(r,Qe)&&(Kx(Ue.defaultValue)?Y(Qe,n0(Ui(a,Qe))):(Y(Qe,Ue.defaultValue),Dh(a,Qe,n0(Ue.defaultValue))),Ue.keepTouched||Ng(n.touchedFields,Qe),Ue.keepDirty||(Ng(n.dirtyFields,Qe),n.isDirty=Ue.defaultValue?O(Qe,n0(Ui(a,Qe))):O()),Ue.keepError||(Ng(n.errors,Qe),u.isValid&&y()),m.state.next({...n}))},Se=(Qe,Ue={})=>{const Xe=Qe?n0(Qe):a,nt=n0(Xe),$e=p_(Qe),Ge=$e?a:nt;if(Ue.keepDefaultValues||(a=Xe),!Ue.keepValues){if(Ue.keepDirtyValues){const ct=new Set([...o.mount,...Object.keys(LY(a,i))]);for(const xt of Array.from(ct))Ui(n.dirtyFields,xt)?Dh(Ge,xt,Ui(i,xt)):Y(xt,Ui(Ge,xt))}else{if(NQe&&Kx(Qe))for(const ct of o.mount){const xt=Ui(r,ct);if(xt&&xt._f){const qt=Array.isArray(xt._f.refs)?xt._f.refs[0]:xt._f.ref;if(sAe(qt)){const Vt=qt.closest("form");if(Vt){Vt.reset();break}}}}if(Ue.keepFieldsRef)for(const ct of o.mount)Y(ct,Ui(Ge,ct));else r={}}i=t.shouldUnregister?Ue.keepDefaultValues?n0(a):{}:n0(Ge),m.array.next({values:{...Ge}}),m.state.next({values:{...Ge}})}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:$e?!1:Ue.keepDirty?n.isDirty:!!(Ue.keepDefaultValues&&!SA(Qe,a)),isSubmitted:Ue.keepIsSubmitted?n.isSubmitted:!1,dirtyFields:$e?{}:Ue.keepDirtyValues?Ue.keepDefaultValues&&i?LY(a,i):n.dirtyFields:Ue.keepDefaultValues&&Qe?LY(a,Qe):Ue.keepDirty?n.dirtyFields:{},touchedFields:Ue.keepTouched?n.touchedFields:{},errors:Ue.keepErrors?n.errors:{},isSubmitSuccessful:Ue.keepIsSubmitSuccessful?n.isSubmitSuccessful:!1,isSubmitting:!1})},Fe=(Qe,Ue)=>Se(tS(Qe)?Qe(i):Qe,Ue),Ne=(Qe,Ue={})=>{const Xe=Ui(r,Qe),nt=Xe&&Xe._f;if(nt){const $e=nt.refs?nt.refs[0]:nt.ref;$e.focus&&($e.focus(),Ue.shouldSelect&&tS($e.select)&&$e.select())}},Ye=Qe=>{n={...n,...Qe}},qe={control:{register:Ae,unregister:pe,getFieldState:te,handleSubmit:ke,setError:le,_subscribe:me,_runSchema:P,_focusError:Pe,_getWatch:V,_getDirty:O,_setValid:y,_setFieldArray:g,_setDisabledField:Ce,_setErrors:j,_getFieldArray:G,_reset:Se,_resetDefaultValues:()=>tS(t.defaultValues)&&t.defaultValues().then(Qe=>{Fe(Qe,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(Qe){l=Qe},get _defaultValues(){return a},get _names(){return o},set _names(Qe){o=Qe},get _formState(){return n},get _options(){return t},set _options(Qe){t={...t,...Qe}}},subscribe:he,trigger:ce,register:Ae,handleSubmit:ke,watch:be,setValue:Y,getValues:ie,reset:Fe,resetField:Ze,clearErrors:ae,unregister:pe,setError:le,setFocus:Ne,getFieldState:te};return{...qe,formControl:qe}}function rPe(s={}){const t=Dt.useRef(void 0),n=Dt.useRef(void 0),[r,a]=Dt.useState({isDirty:!1,isValidating:!1,isLoading:tS(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:tS(s.defaultValues)?void 0:s.defaultValues});if(!t.current)if(s.formControl)t.current={...s.formControl,formState:r},s.defaultValues&&!tS(s.defaultValues)&&s.formControl.reset(s.defaultValues,s.resetOptions);else{const{formControl:l,...o}=xNs(s);t.current={...o,formState:r}}const i=t.current.control;return i._options=s,AQe(()=>{const l=i._subscribe({formState:i._proxyFormState,callback:()=>a({...i._formState}),reRenderRoot:!0});return a(o=>({...o,isReady:!0})),i._formState.isReady=!0,l},[i]),Dt.useEffect(()=>i._disableForm(s.disabled),[i,s.disabled]),Dt.useEffect(()=>{s.mode&&(i._options.mode=s.mode),s.reValidateMode&&(i._options.reValidateMode=s.reValidateMode)},[i,s.mode,s.reValidateMode]),Dt.useEffect(()=>{s.errors&&(i._setErrors(s.errors),i._focusError())},[i,s.errors]),Dt.useEffect(()=>{s.shouldUnregister&&i._subjects.state.next({values:i._getWatch()})},[i,s.shouldUnregister]),Dt.useEffect(()=>{if(i._proxyFormState.isDirty){const l=i._getDirty();l!==r.isDirty&&i._subjects.state.next({isDirty:l})}},[i,r.isDirty]),Dt.useEffect(()=>{s.values&&!SA(s.values,n.current)?(i._reset(s.values,{keepFieldsRef:!0,...i._options.resetOptions}),n.current=s.values,a(l=>({...l}))):i._resetDefaultValues()},[i,s.values]),Dt.useEffect(()=>{i._state.mount||(i._setValid(),i._state.mount=!0),i._state.watch&&(i._state.watch=!1,i._subjects.state.next({...i._formState})),i._removeUnmounted()}),t.current.formState=v8t(r,i),t.current}const npt=(s,t,n)=>{if(s&&"reportValidity"in s){const r=Ui(n,t);s.setCustomValidity(r&&r.message||""),s.reportValidity()}},A8t=(s,t)=>{for(const n in t.fields){const r=t.fields[n];r&&r.ref&&"reportValidity"in r.ref?npt(r.ref,n,s):r.refs&&r.refs.forEach(a=>npt(a,n,s))}},gNs=(s,t)=>{t.shouldUseNativeValidation&&A8t(s,t);const n={};for(const r in s){const a=Ui(t.fields,r),i=Object.assign(s[r]||{},{ref:a&&a.ref});if(yNs(t.names||Object.keys(s),r)){const l=Object.assign({},Ui(n,r));Dh(l,"root",i),Dh(n,r,l)}else Dh(n,r,i)}return n},yNs=(s,t)=>s.some(n=>n.startsWith(t+"."));var vNs=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]=_8t(l,t,n,a,d?[].concat(d,r.message):r.message)}s.shift()}return n},aPe=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&&A8t({},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:gNs(vNs(l.errors,!i.shouldUseNativeValidation&&i.criteriaMode==="all"),i)};throw l}))}catch(l){return Promise.reject(l)}}},rpt;function xa(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 N$ extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class E8t extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(rpt=globalThis).__zod_globalConfig??(rpt.__zod_globalConfig={});const MQe=globalThis.__zod_globalConfig;function W7(s){return MQe}function T8t(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 k$e(s,t){return typeof t=="bigint"?t.toString():t}function PQe(s){return{get value(){{const t=s();return Object.defineProperty(this,"value",{value:t}),t}}}}function LQe(s){return s==null}function IQe(s){const t=s.startsWith("^")?1:0,n=s.endsWith("$")?s.length-1:s.length;return s.slice(t,n)}function bNs(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 aAe(s){return typeof s=="object"&&s!==null&&!Array.isArray(s)}const wNs=PQe(()=>{var s;if(MQe.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 ste(s){if(aAe(s)===!1)return!1;const t=s.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(aAe(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function P8t(s){return ste(s)?{...s}:Array.isArray(s)?[...s]:s instanceof Map?new Map(s):s instanceof Set?new Set(s):s}const jNs=new Set(["string","number","symbol"]);function CH(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function lL(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 ol(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 NNs(s){return Object.keys(s).filter(t=>s[t]._zod.optin==="optional"&&s[t]._zod.optout==="optional")}const kNs={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 SNs(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=oL(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 q9(this,"shape",l),l},checks:[]});return lL(s,i)}function CNs(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=oL(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 q9(this,"shape",l),l},checks:[]});return lL(s,i)}function ANs(s,t){if(!ste(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=oL(s._zod.def,{get shape(){const i={...s._zod.def.shape,...t};return q9(this,"shape",i),i}});return lL(s,a)}function ENs(s,t){if(!ste(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=oL(s._zod.def,{get shape(){const r={...s._zod.def.shape,...t};return q9(this,"shape",r),r}});return lL(s,n)}function TNs(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=oL(s._zod.def,{get shape(){const a={...s._zod.def.shape,...t._zod.def.shape};return q9(this,"shape",a),a},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return lL(s,n)}function MNs(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=oL(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 q9(this,"shape",c),c},checks:[]});return lL(t,l)}function PNs(s,t,n){const r=oL(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 q9(this,"shape",i),i}});return lL(t,r)}function YU(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 dle(s){return typeof s=="string"?s:s==null?void 0:s.message}function K7(s,t,n){var c,d,u,h,m,p;const r=s.message?s.message:dle((u=(d=(c=s.inst)==null?void 0:c._zod.def)==null?void 0:d.error)==null?void 0:u.call(d,s))??dle((h=t==null?void 0:t.error)==null?void 0:h.call(t,s))??dle((m=n.customError)==null?void 0:m.call(n,s))??dle((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 DQe(s){return Array.isArray(s)?"array":typeof s=="string"?"string":"unknown"}function nte(...s){const[t,n,r]=s;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}const I8t=(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,k$e,2),Object.defineProperty(s,"toString",{value:()=>s.message,enumerable:!1})},D8t=xa("$ZodError",I8t),R8t=xa("$ZodError",I8t,{Parent:Error});function INs(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 DNs(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 N$;if(l.issues.length){const o=new((a==null?void 0:a.Err)??s)(l.issues.map(c=>K7(c,i,W7())));throw M8t(o,a==null?void 0:a.callee),o}return l.value},FQe=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=>K7(c,i,W7())));throw M8t(o,a==null?void 0:a.callee),o}return l.value},iPe=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 N$;return i.issues.length?{success:!1,error:new(s??D8t)(i.issues.map(l=>K7(l,a,W7())))}:{success:!0,data:i.value}},RNs=iPe(R8t),oPe=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=>K7(l,a,W7())))}:{success:!0,data:i.value}},FNs=oPe(R8t),ONs=s=>(t,n,r)=>{const a=r?{...r,direction:"backward"}:{direction:"backward"};return RQe(s)(t,n,a)},zNs=s=>(t,n,r)=>RQe(s)(t,n,r),BNs=s=>async(t,n,r)=>{const a=r?{...r,direction:"backward"}:{direction:"backward"};return FQe(s)(t,n,a)},UNs=s=>async(t,n,r)=>FQe(s)(t,n,r),qNs=s=>(t,n,r)=>{const a=r?{...r,direction:"backward"}:{direction:"backward"};return iPe(s)(t,n,a)},$Ns=s=>(t,n,r)=>iPe(s)(t,n,r),VNs=s=>async(t,n,r)=>{const a=r?{...r,direction:"backward"}:{direction:"backward"};return oPe(s)(t,n,a)},HNs=s=>async(t,n,r)=>oPe(s)(t,n,r),GNs=/^[cC][0-9a-z]{6,}$/,WNs=/^[0-9a-z]+$/,KNs=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,YNs=/^[0-9a-vA-V]{20}$/,ZNs=/^[A-Za-z0-9]{27}$/,XNs=/^[a-zA-Z0-9_-]{21}$/,QNs=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,JNs=/^([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})$/,opt=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)$/,eks=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,tks="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function sks(){return new RegExp(tks,"u")}const nks=/^(?:(?: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])$/,rks=/^(([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}|:))$/,aks=/^((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])$/,iks=/^(([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])$/,oks=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,F8t=/^[A-Za-z0-9_-]*$/,lks=/^https?$/,cks=/^\+[1-9]\d{6,14}$/,O8t="(?:(?:\\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])))",dks=new RegExp(`^${O8t}$`);function z8t(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 uks(s){return new RegExp(`^${z8t(s)}$`)}function hks(s){const t=z8t({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(`^${O8t}T(?:${r})$`)}const mks=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}$`)},pks=/^-?\d+$/,fks=/^-?\d+(?:\.\d+)?$/,xks=/^(?:true|false)$/i,gks=/^[^A-Z]*$/,yks=/^[^a-z]*$/,W_=xa("$ZodCheck",(s,t)=>{var n;s._zod??(s._zod={}),s._zod.def=t,(n=s._zod).onattach??(n.onattach=[])}),B8t={number:"number",bigint:"bigint",object:"date"},U8t=xa("$ZodCheckLessThan",(s,t)=>{W_.init(s,t);const n=B8t[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{W_.init(s,t);const n=B8t[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})}}),vks=xa("$ZodCheckMultipleOf",(s,t)=>{W_.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):bNs(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})}}),bks=xa("$ZodCheckNumberFormat",(s,t)=>{var l;W_.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]=kNs[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=pks)}),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})}}),_ks=xa("$ZodCheckMaxLength",(s,t)=>{var n;W_.init(s,t),(n=s._zod.def).when??(n.when=r=>{const a=r.value;return!LQe(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=DQe(a);r.issues.push({origin:l,code:"too_big",maximum:t.maximum,inclusive:!0,input:a,inst:s,continue:!t.abort})}}),wks=xa("$ZodCheckMinLength",(s,t)=>{var n;W_.init(s,t),(n=s._zod.def).when??(n.when=r=>{const a=r.value;return!LQe(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=DQe(a);r.issues.push({origin:l,code:"too_small",minimum:t.minimum,inclusive:!0,input:a,inst:s,continue:!t.abort})}}),jks=xa("$ZodCheckLengthEquals",(s,t)=>{var n;W_.init(s,t),(n=s._zod.def).when??(n.when=r=>{const a=r.value;return!LQe(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=DQe(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})}}),lPe=xa("$ZodCheckStringFormat",(s,t)=>{var n,r;W_.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=()=>{})}),Nks=xa("$ZodCheckRegex",(s,t)=>{lPe.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})}}),kks=xa("$ZodCheckLowerCase",(s,t)=>{t.pattern??(t.pattern=gks),lPe.init(s,t)}),Sks=xa("$ZodCheckUpperCase",(s,t)=>{t.pattern??(t.pattern=yks),lPe.init(s,t)}),Cks=xa("$ZodCheckIncludes",(s,t)=>{W_.init(s,t);const n=CH(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})}}),Aks=xa("$ZodCheckStartsWith",(s,t)=>{W_.init(s,t);const n=new RegExp(`^${CH(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})}}),Eks=xa("$ZodCheckEndsWith",(s,t)=>{W_.init(s,t);const n=new RegExp(`.*${CH(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})}}),Tks=xa("$ZodCheckOverwrite",(s,t)=>{W_.init(s,t),s._zod.check=n=>{n.value=t.tx(n.value)}});class Mks{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 Pks={major:4,minor:4,patch:3},Ix=xa("$ZodType",(s,t)=>{var a;var n;s??(s={}),s._zod.def=t,s._zod.bag=s._zod.bag||{},s._zod.version=Pks;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=YU(o),h;for(const m of c){if(m._zod.def.when){if(LNs(o)||!m._zod.def.when(o))continue}else if(u)continue;const p=o.issues.length,f=m._zod.check(o);if(f instanceof Promise&&(d==null?void 0:d.async)===!1)throw new N$;if(h||f instanceof Promise)h=(h??Promise.resolve()).then(async()=>{await f,o.issues.length!==p&&(u||(u=YU(o,p)))});else{if(o.issues.length===p)continue;u||(u=YU(o,p))}}return h?h.then(()=>o):o},l=(o,c,d)=>{if(YU(o))return o.aborted=!0,o;const u=i(c,r,d);if(u instanceof Promise){if(d.async===!1)throw new N$;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 N$;return d.then(u=>i(u,r,c))}return i(d,r,c)}}um(s,"~standard",()=>({validate:i=>{var l;try{const o=RNs(s,i);return o.success?{value:o.data}:{issues:(l=o.error)==null?void 0:l.issues}}catch{return FNs(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}))}),OQe=xa("$ZodString",(s,t)=>{var n;Ix.init(s,t),s._zod.pattern=[...((n=s==null?void 0:s._zod.bag)==null?void 0:n.patterns)??[]].pop()??mks(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}}),of=xa("$ZodStringFormat",(s,t)=>{lPe.init(s,t),OQe.init(s,t)}),Lks=xa("$ZodGUID",(s,t)=>{t.pattern??(t.pattern=JNs),of.init(s,t)}),Iks=xa("$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=opt(r))}else t.pattern??(t.pattern=opt());of.init(s,t)}),Dks=xa("$ZodEmail",(s,t)=>{t.pattern??(t.pattern=eks),of.init(s,t)}),Rks=xa("$ZodURL",(s,t)=>{of.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)===lks.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})}}}),Fks=xa("$ZodEmoji",(s,t)=>{t.pattern??(t.pattern=sks()),of.init(s,t)}),Oks=xa("$ZodNanoID",(s,t)=>{t.pattern??(t.pattern=XNs),of.init(s,t)}),zks=xa("$ZodCUID",(s,t)=>{t.pattern??(t.pattern=GNs),of.init(s,t)}),Bks=xa("$ZodCUID2",(s,t)=>{t.pattern??(t.pattern=WNs),of.init(s,t)}),Uks=xa("$ZodULID",(s,t)=>{t.pattern??(t.pattern=KNs),of.init(s,t)}),qks=xa("$ZodXID",(s,t)=>{t.pattern??(t.pattern=YNs),of.init(s,t)}),$ks=xa("$ZodKSUID",(s,t)=>{t.pattern??(t.pattern=ZNs),of.init(s,t)}),Vks=xa("$ZodISODateTime",(s,t)=>{t.pattern??(t.pattern=hks(t)),of.init(s,t)}),Hks=xa("$ZodISODate",(s,t)=>{t.pattern??(t.pattern=dks),of.init(s,t)}),Gks=xa("$ZodISOTime",(s,t)=>{t.pattern??(t.pattern=uks(t)),of.init(s,t)}),Wks=xa("$ZodISODuration",(s,t)=>{t.pattern??(t.pattern=QNs),of.init(s,t)}),Kks=xa("$ZodIPv4",(s,t)=>{t.pattern??(t.pattern=nks),of.init(s,t),s._zod.bag.format="ipv4"}),Yks=xa("$ZodIPv6",(s,t)=>{t.pattern??(t.pattern=rks),of.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})}}}),Zks=xa("$ZodCIDRv4",(s,t)=>{t.pattern??(t.pattern=aks),of.init(s,t)}),Xks=xa("$ZodCIDRv6",(s,t)=>{t.pattern??(t.pattern=iks),of.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 $8t(s){if(s==="")return!0;if(/\s/.test(s)||s.length%4!==0)return!1;try{return atob(s),!0}catch{return!1}}const Qks=xa("$ZodBase64",(s,t)=>{t.pattern??(t.pattern=oks),of.init(s,t),s._zod.bag.contentEncoding="base64",s._zod.check=n=>{$8t(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:s,continue:!t.abort})}});function Jks(s){if(!F8t.test(s))return!1;const t=s.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return $8t(n)}const eSs=xa("$ZodBase64URL",(s,t)=>{t.pattern??(t.pattern=F8t),of.init(s,t),s._zod.bag.contentEncoding="base64url",s._zod.check=n=>{Jks(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:s,continue:!t.abort})}}),tSs=xa("$ZodE164",(s,t)=>{t.pattern??(t.pattern=cks),of.init(s,t)});function sSs(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 nSs=xa("$ZodJWT",(s,t)=>{of.init(s,t),s._zod.check=n=>{sSs(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:s,continue:!t.abort})}}),V8t=xa("$ZodNumber",(s,t)=>{Ix.init(s,t),s._zod.pattern=s._zod.bag.pattern??fks,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}}),rSs=xa("$ZodNumberFormat",(s,t)=>{bks.init(s,t),V8t.init(s,t)}),aSs=xa("$ZodBoolean",(s,t)=>{Ix.init(s,t),s._zod.pattern=xks,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}}),iSs=xa("$ZodUnknown",(s,t)=>{Ix.init(s,t),s._zod.parse=n=>n}),oSs=xa("$ZodNever",(s,t)=>{Ix.init(s,t),s._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:s}),n)});function lpt(s,t,n){s.issues.length&&t.issues.push(...L8t(n,s.issues)),t.value[n]=s.value}const lSs=xa("$ZodArray",(s,t)=>{Ix.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;llpt(d,n,l))):lpt(c,n,l)}return i.length?Promise.all(i).then(()=>n):n}});function iAe(s,t,n,r,a,i){const l=n in r;if(s.issues.length){if(a&&i&&!l)return;t.issues.push(...L8t(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 H8t(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=NNs(s.shape);return{...s,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function G8t(s,t,n,r,a,i){const l=[],o=a.keySet,c=a.catchall._zod,d=c.def.type,u=c.optin==="optional",h=c.optout==="optional";for(const m in t){if(m==="__proto__"||o.has(m))continue;if(d==="never"){l.push(m);continue}const p=c.run({value:t[m],issues:[]},r);p instanceof Promise?s.push(p.then(f=>iAe(f,n,m,t,u,h))):iAe(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 cSs=xa("$ZodObject",(s,t)=>{Ix.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=PQe(()=>H8t(t));um(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=aAe,i=t.catchall;let l;s._zod.parse=(o,c)=>{l??(l=r.value);const d=o.value;if(!a(d))return o.issues.push({expected:"object",code:"invalid_type",input:d,inst:s}),o;o.value={};const u=[],h=l.shape;for(const m of l.keys){const p=h[m],f=p._zod.optin==="optional",y=p._zod.optout==="optional",v=p._zod.run({value:d[m],issues:[]},c);v instanceof Promise?u.push(v.then(g=>iAe(g,o,m,d,f,y))):iAe(v,o,m,d,f,y)}return i?G8t(u,d,o,c,r.value,s):u.length?Promise.all(u).then(()=>o):o}}),dSs=xa("$ZodObjectJIT",(s,t)=>{cSs.init(s,t);const n=s._zod.parse,r=PQe(()=>H8t(t)),a=m=>{var j,S;const p=new Mks(["shape","payload","ctx"]),f=r.value,y=C=>{const E=ipt(C);return`shape[${E}]._zod.run({ value: input[${E}], issues: [] }, ctx)`};p.write("const input = payload.value;");const v=Object.create(null);let g=0;for(const C of f.keys)v[C]=`key_${g++}`;p.write("const newResult = {};");for(const C of f.keys){const E=v[C],P=ipt(C),M=m[C],I=((j=M==null?void 0:M._zod)==null?void 0:j.optin)==="optional",D=((S=M==null?void 0:M._zod)==null?void 0:S.optout)==="optional";p.write(`const ${E} = ${y(C)};`),I&&D?p.write(` if (${E}.issues.length) { if (${P} in input) { payload.issues = payload.issues.concat(${E}.issues.map(iss => ({ ...iss, path: iss.path ? [${P}, ...iss.path] : [${P}] }))); } } if (${E}.value === undefined) { if (${P} in input) { newResult[${P}] = undefined; } } else { newResult[${P}] = ${E}.value; } `):I?p.write(` if (${E}.issues.length) { payload.issues = payload.issues.concat(${E}.issues.map(iss => ({ ...iss, path: iss.path ? [${P}, ...iss.path] : [${P}] }))); } if (${E}.value === undefined) { if (${P} in input) { newResult[${P}] = undefined; } } else { newResult[${P}] = ${E}.value; } `):p.write(` const ${E}_present = ${P} in input; if (${E}.issues.length) { payload.issues = payload.issues.concat(${E}.issues.map(iss => ({ ...iss, path: iss.path ? [${P}, ...iss.path] : [${P}] }))); } if (!${E}_present && !${E}.issues.length) { payload.issues.push({ code: "invalid_type", expected: "nonoptional", input: undefined, path: [${P}] }); } if (${E}_present) { if (${E}.value === undefined) { newResult[${P}] = undefined; } else { newResult[${P}] = ${E}.value; } } `)}p.write("payload.value = newResult;"),p.write("return payload;");const b=p.compile();return(C,E)=>b(m,C,E)};let i;const l=aAe,o=!MQe.jitless,d=o&&wNs.value,u=t.catchall;let h;s._zod.parse=(m,p)=>{h??(h=r.value);const f=m.value;return l(f)?o&&d&&(p==null?void 0:p.async)===!1&&p.jitless!==!0?(i||(i=a(t.shape)),m=i(m,p),u?G8t([],f,m,p,h,s):m):n(m,p):(m.issues.push({expected:"object",code:"invalid_type",input:f,inst:s}),m)}});function cpt(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=>!YU(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=>K7(l,r,W7())))}),t)}const uSs=xa("$ZodUnion",(s,t)=>{Ix.init(s,t),um(s._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),um(s._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),um(s._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),um(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=>IQe(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=>cpt(o,r,s,a)):cpt(l,r,s,a)}}),hSs=xa("$ZodIntersection",(s,t)=>{Ix.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])=>dpt(n,c,d)):dpt(n,i,l)}});function S$e(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(ste(s)&&ste(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=S$e(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}),YU(s))return s;const l=S$e(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 mSs=xa("$ZodEnum",(s,t)=>{Ix.init(s,t);const n=T8t(t.entries),r=new Set(n);s._zod.values=r,s._zod.pattern=new RegExp(`^(${n.filter(a=>jNs.has(typeof a)).map(a=>typeof a=="string"?CH(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}}),pSs=xa("$ZodLiteral",(s,t)=>{if(Ix.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"?CH(r):r?CH(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}}),fSs=xa("$ZodTransform",(s,t)=>{Ix.init(s,t),s._zod.optin="optional",s._zod.parse=(n,r)=>{if(r.direction==="backward")throw new E8t(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 N$;return n.value=a,n.fallback=!0,n}});function upt(s,t){return t===void 0&&(s.issues.length||s.fallback)?{issues:[],value:void 0}:s}const W8t=xa("$ZodOptional",(s,t)=>{Ix.init(s,t),s._zod.optin="optional",s._zod.optout="optional",um(s._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),um(s._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${IQe(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=>upt(l,a)):upt(i,a)}return n.value===void 0?n:t.innerType._zod.run(n,r)}}),xSs=xa("$ZodExactOptional",(s,t)=>{W8t.init(s,t),um(s._zod,"values",()=>t.innerType._zod.values),um(s._zod,"pattern",()=>t.innerType._zod.pattern),s._zod.parse=(n,r)=>t.innerType._zod.run(n,r)}),gSs=xa("$ZodNullable",(s,t)=>{Ix.init(s,t),um(s._zod,"optin",()=>t.innerType._zod.optin),um(s._zod,"optout",()=>t.innerType._zod.optout),um(s._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${IQe(n.source)}|null)$`):void 0}),um(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)}),ySs=xa("$ZodDefault",(s,t)=>{Ix.init(s,t),s._zod.optin="optional",um(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=>hpt(i,t)):hpt(a,t)}});function hpt(s,t){return s.value===void 0&&(s.value=t.defaultValue),s}const vSs=xa("$ZodPrefault",(s,t)=>{Ix.init(s,t),s._zod.optin="optional",um(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))}),bSs=xa("$ZodNonOptional",(s,t)=>{Ix.init(s,t),um(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=>mpt(i,s)):mpt(a,s)}});function mpt(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 _Ss=xa("$ZodCatch",(s,t)=>{Ix.init(s,t),s._zod.optin="optional",um(s._zod,"optout",()=>t.innerType._zod.optout),um(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=>K7(l,r,W7()))},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=>K7(i,r,W7()))},input:n.value}),n.issues=[],n.fallback=!0),n)}}),wSs=xa("$ZodPipe",(s,t)=>{Ix.init(s,t),um(s._zod,"values",()=>t.in._zod.values),um(s._zod,"optin",()=>t.in._zod.optin),um(s._zod,"optout",()=>t.out._zod.optout),um(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=>ule(l,t.in,r)):ule(i,t.in,r)}const a=t.in._zod.run(n,r);return a instanceof Promise?a.then(i=>ule(i,t.out,r)):ule(a,t.out,r)}});function ule(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 jSs=xa("$ZodReadonly",(s,t)=>{Ix.init(s,t),um(s._zod,"propValues",()=>t.innerType._zod.propValues),um(s._zod,"values",()=>t.innerType._zod.values),um(s._zod,"optin",()=>{var n,r;return(r=(n=t.innerType)==null?void 0:n._zod)==null?void 0:r.optin}),um(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(ppt):ppt(a)}});function ppt(s){return s.value=Object.freeze(s.value),s}const NSs=xa("$ZodCustom",(s,t)=>{W_.init(s,t),Ix.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=>fpt(i,n,r,s));fpt(a,n,r,s)}});function fpt(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(nte(a))}}var xpt;class kSs{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 SSs(){return new kSs}(xpt=globalThis).__zod_globalRegistry??(xpt.__zod_globalRegistry=SSs());const dX=globalThis.__zod_globalRegistry;function CSs(s,t){return new s({type:"string",...ol(t)})}function ASs(s,t){return new s({type:"string",format:"email",check:"string_format",abort:!1,...ol(t)})}function gpt(s,t){return new s({type:"string",format:"guid",check:"string_format",abort:!1,...ol(t)})}function ESs(s,t){return new s({type:"string",format:"uuid",check:"string_format",abort:!1,...ol(t)})}function TSs(s,t){return new s({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...ol(t)})}function MSs(s,t){return new s({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...ol(t)})}function PSs(s,t){return new s({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...ol(t)})}function LSs(s,t){return new s({type:"string",format:"url",check:"string_format",abort:!1,...ol(t)})}function ISs(s,t){return new s({type:"string",format:"emoji",check:"string_format",abort:!1,...ol(t)})}function DSs(s,t){return new s({type:"string",format:"nanoid",check:"string_format",abort:!1,...ol(t)})}function RSs(s,t){return new s({type:"string",format:"cuid",check:"string_format",abort:!1,...ol(t)})}function FSs(s,t){return new s({type:"string",format:"cuid2",check:"string_format",abort:!1,...ol(t)})}function OSs(s,t){return new s({type:"string",format:"ulid",check:"string_format",abort:!1,...ol(t)})}function zSs(s,t){return new s({type:"string",format:"xid",check:"string_format",abort:!1,...ol(t)})}function BSs(s,t){return new s({type:"string",format:"ksuid",check:"string_format",abort:!1,...ol(t)})}function USs(s,t){return new s({type:"string",format:"ipv4",check:"string_format",abort:!1,...ol(t)})}function qSs(s,t){return new s({type:"string",format:"ipv6",check:"string_format",abort:!1,...ol(t)})}function $Ss(s,t){return new s({type:"string",format:"cidrv4",check:"string_format",abort:!1,...ol(t)})}function VSs(s,t){return new s({type:"string",format:"cidrv6",check:"string_format",abort:!1,...ol(t)})}function HSs(s,t){return new s({type:"string",format:"base64",check:"string_format",abort:!1,...ol(t)})}function GSs(s,t){return new s({type:"string",format:"base64url",check:"string_format",abort:!1,...ol(t)})}function WSs(s,t){return new s({type:"string",format:"e164",check:"string_format",abort:!1,...ol(t)})}function KSs(s,t){return new s({type:"string",format:"jwt",check:"string_format",abort:!1,...ol(t)})}function YSs(s,t){return new s({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...ol(t)})}function ZSs(s,t){return new s({type:"string",format:"date",check:"string_format",...ol(t)})}function XSs(s,t){return new s({type:"string",format:"time",check:"string_format",precision:null,...ol(t)})}function QSs(s,t){return new s({type:"string",format:"duration",check:"string_format",...ol(t)})}function JSs(s,t){return new s({type:"number",checks:[],...ol(t)})}function e5s(s,t){return new s({type:"number",check:"number_format",abort:!1,format:"safeint",...ol(t)})}function t5s(s,t){return new s({type:"boolean",...ol(t)})}function s5s(s){return new s({type:"unknown"})}function n5s(s,t){return new s({type:"never",...ol(t)})}function ypt(s,t){return new U8t({check:"less_than",...ol(t),value:s,inclusive:!1})}function dOe(s,t){return new U8t({check:"less_than",...ol(t),value:s,inclusive:!0})}function vpt(s,t){return new q8t({check:"greater_than",...ol(t),value:s,inclusive:!1})}function uOe(s,t){return new q8t({check:"greater_than",...ol(t),value:s,inclusive:!0})}function bpt(s,t){return new vks({check:"multiple_of",...ol(t),value:s})}function K8t(s,t){return new _ks({check:"max_length",...ol(t),maximum:s})}function oAe(s,t){return new wks({check:"min_length",...ol(t),minimum:s})}function Y8t(s,t){return new jks({check:"length_equals",...ol(t),length:s})}function r5s(s,t){return new Nks({check:"string_format",format:"regex",...ol(t),pattern:s})}function a5s(s){return new kks({check:"string_format",format:"lowercase",...ol(s)})}function i5s(s){return new Sks({check:"string_format",format:"uppercase",...ol(s)})}function o5s(s,t){return new Cks({check:"string_format",format:"includes",...ol(t),includes:s})}function l5s(s,t){return new Aks({check:"string_format",format:"starts_with",...ol(t),prefix:s})}function c5s(s,t){return new Eks({check:"string_format",format:"ends_with",...ol(t),suffix:s})}function oW(s){return new Tks({check:"overwrite",tx:s})}function d5s(s){return oW(t=>t.normalize(s))}function u5s(){return oW(s=>s.trim())}function h5s(){return oW(s=>s.toLowerCase())}function m5s(){return oW(s=>s.toUpperCase())}function p5s(){return oW(s=>_Ns(s))}function f5s(s,t,n){return new s({type:"array",element:t,...ol(n)})}function x5s(s,t,n){return new s({type:"custom",check:"custom",fn:t,...ol(n)})}function g5s(s,t){const n=y5s(r=>(r.addIssue=a=>{if(typeof a=="string")r.issues.push(nte(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(nte(i))}},s(r.value,r)),t);return n}function y5s(s,t){const n=new W_({check:"custom",...ol(t)});return n._zod.check=s,n}function Z8t(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)??dX,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 Ev(s,t,n={path:[],schemaPath:[]}){var u,h;var r;const a=s._zod.def,i=t.seen.get(s);if(i)return i.count++,n.schemaPath.includes(s)&&(i.cycle=n.path),i.schema;const l={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(s,l);const o=(h=(u=s._zod).toJSONSchema)==null?void 0:h.call(u);if(o)l.schema=o;else{const m={...n,schemaPath:[...n.schemaPath,s],path:n.path};if(s._zod.processJSONSchema)s._zod.processJSONSchema(t,l.schema,m);else{const f=l.schema,y=t.processors[a.type];if(!y)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${a.type}`);y(s,t,f,m)}const p=s._zod.parent;p&&(l.ref||(l.ref=p),Ev(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"&&Y1(s)&&(delete l.schema.examples,delete l.schema.default),t.io==="input"&&"_prefault"in l.schema&&((r=l.schema).default??(r.default=l.schema._prefault)),delete l.schema._prefault,t.seen.get(s).schema}function X8t(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 y;const h=s.target==="draft-2020-12"?"$defs":"definitions";if(s.external){const v=(y=s.external.registry.get(u[0]))==null?void 0:y.id,g=s.external.uri??(j=>j);if(v)return{ref:g(v)};const b=u[1].defId??u[1].schema.id??`schema${s.counter++}`;return u[1].defId=b,{defId:b,ref:`${g("__shared")}#/${h}/${b}`}}if(u[1]===n)return{ref:"#"};const p=`#/${h}/`,f=u[1].schema.id??`__schema${s.counter++}`;return{defId:f,ref:p+f}},i=u=>{if(u[1].schema.$ref)return;const h=u[1],{ref:m,defId:p}=a(u);h.def={...h.schema},p&&(h.defId=p);const f=h.schema;for(const y in f)delete f[y];f.$ref=m};if(s.cycles==="throw")for(const u of s.seen.entries()){const h=u[1];if(h.cycle)throw new Error(`Cycle detected: #/${(o=h.cycle)==null?void 0:o.join("/")}/ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const u of s.seen.entries()){const h=u[1];if(t===u[0]){i(u);continue}if(s.external){const p=(c=s.external.registry.get(u[0]))==null?void 0:c.id;if(t!==u[0]&&p){i(u);continue}}if((d=s.metadataRegistry.get(u[0]))==null?void 0:d.id){i(u);continue}if(h.cycle){i(u);continue}if(h.count>1&&s.reused==="ref"){i(u);continue}}}function Q8t(s,t){var o,c,d,u;const n=s.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=h=>{const m=s.seen.get(h);if(m.ref===null)return;const p=m.def??m.schema,f={...p},y=m.ref;if(m.ref=null,y){r(y);const g=s.seen.get(y),b=g.schema;if(b.$ref&&(s.target==="draft-07"||s.target==="draft-04"||s.target==="openapi-3.0")?(p.allOf=p.allOf??[],p.allOf.push(b)):Object.assign(p,b),Object.assign(p,f),h._zod.parent===y)for(const S in p)S==="$ref"||S==="allOf"||S in f||delete p[S];if(b.$ref&&g.def)for(const S in p)S==="$ref"||S==="allOf"||S in g.def&&JSON.stringify(p[S])===JSON.stringify(g.def[S])&&delete p[S]}const v=h._zod.parent;if(v&&v!==y){r(v);const g=s.seen.get(v);if(g!=null&&g.schema.$ref&&(p.$ref=g.schema.$ref,g.def))for(const b in p)b==="$ref"||b==="allOf"||b in g.def&&JSON.stringify(p[b])===JSON.stringify(g.def[b])&&delete p[b]}s.override({zodSchema:h,jsonSchema:p,path:m.path??[]})};for(const h of[...s.seen.entries()].reverse())r(h[0]);const a={};if(s.target==="draft-2020-12"?a.$schema="https://json-schema.org/draft/2020-12/schema":s.target==="draft-07"?a.$schema="http://json-schema.org/draft-07/schema#":s.target==="draft-04"?a.$schema="http://json-schema.org/draft-04/schema#":s.target,(o=s.external)!=null&&o.uri){const h=(c=s.external.registry.get(t))==null?void 0:c.id;if(!h)throw new Error("Schema is missing an `id` property");a.$id=s.external.uri(h)}Object.assign(a,n.def??n.schema);const i=(d=s.metadataRegistry.get(t))==null?void 0:d.id;i!==void 0&&a.id===i&&delete a.id;const l=((u=s.external)==null?void 0:u.defs)??{};for(const h of s.seen.entries()){const m=h[1];m.def&&m.defId&&(m.def.id===m.defId&&delete m.def.id,l[m.defId]=m.def)}s.external||Object.keys(l).length>0&&(s.target==="draft-2020-12"?a.$defs=l:a.definitions=l);try{const h=JSON.parse(JSON.stringify(a));return Object.defineProperty(h,"~standard",{value:{...t["~standard"],jsonSchema:{input:lAe(t,"input",s.processors),output:lAe(t,"output",s.processors)}},enumerable:!1,writable:!1}),h}catch{throw new Error("Error converting schema to JSON.")}}function Y1(s,t){const n=t??{seen:new Set};if(n.seen.has(s))return!1;n.seen.add(s);const r=s._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return Y1(r.element,n);if(r.type==="set")return Y1(r.valueType,n);if(r.type==="lazy")return Y1(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault")return Y1(r.innerType,n);if(r.type==="intersection")return Y1(r.left,n)||Y1(r.right,n);if(r.type==="record"||r.type==="map")return Y1(r.keyType,n)||Y1(r.valueType,n);if(r.type==="pipe")return s._zod.traits.has("$ZodCodec")?!0:Y1(r.in,n)||Y1(r.out,n);if(r.type==="object"){for(const a in r.shape)if(Y1(r.shape[a],n))return!0;return!1}if(r.type==="union"){for(const a of r.options)if(Y1(a,n))return!0;return!1}if(r.type==="tuple"){for(const a of r.items)if(Y1(a,n))return!0;return!!(r.rest&&Y1(r.rest,n))}return!1}const v5s=(s,t={})=>n=>{const r=Z8t({...n,processors:t});return Ev(s,r),X8t(r,s),Q8t(r,s)},lAe=(s,t,n={})=>r=>{const{libraryOptions:a,target:i}=r??{},l=Z8t({...a??{},target:i,io:t,processors:n});return Ev(s,l),X8t(l,s),Q8t(l,s)},b5s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},_5s=(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=b5s[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}))])}},w5s=(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)},j5s=(s,t,n,r)=>{n.type="boolean"},N5s=(s,t,n,r)=>{n.not={}},k5s=(s,t,n,r)=>{},S5s=(s,t,n,r)=>{const a=s._zod.def,i=T8t(a.entries);i.every(l=>typeof l=="number")&&(n.type="number"),i.every(l=>typeof l=="string")&&(n.type="string"),n.enum=i},C5s=(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},A5s=(s,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},E5s=(s,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},T5s=(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=Ev(i.element,t,{...r,path:[...r.path,"items"]})},M5s=(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]=Ev(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=Ev(i.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):t.io==="output"&&(a.additionalProperties=!1)},P5s=(s,t,n,r)=>{const a=s._zod.def,i=a.inclusive===!1,l=a.options.map((o,c)=>Ev(o,t,{...r,path:[...r.path,i?"oneOf":"anyOf",c]}));i?n.oneOf=l:n.anyOf=l},L5s=(s,t,n,r)=>{const a=s._zod.def,i=Ev(a.left,t,{...r,path:[...r.path,"allOf",0]}),l=Ev(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},I5s=(s,t,n,r)=>{const a=s._zod.def,i=Ev(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"}]},D5s=(s,t,n,r)=>{const a=s._zod.def;Ev(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType},R5s=(s,t,n,r)=>{const a=s._zod.def;Ev(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType,n.default=JSON.parse(JSON.stringify(a.defaultValue))},F5s=(s,t,n,r)=>{const a=s._zod.def;Ev(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)))},O5s=(s,t,n,r)=>{const a=s._zod.def;Ev(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},z5s=(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;Ev(l,t,r);const o=t.seen.get(s);o.ref=l},B5s=(s,t,n,r)=>{const a=s._zod.def;Ev(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType,n.readOnly=!0},J8t=(s,t,n,r)=>{const a=s._zod.def;Ev(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType},U5s=xa("ZodISODateTime",(s,t)=>{Vks.init(s,t),Yf.init(s,t)});function q5s(s){return YSs(U5s,s)}const $5s=xa("ZodISODate",(s,t)=>{Hks.init(s,t),Yf.init(s,t)});function V5s(s){return ZSs($5s,s)}const H5s=xa("ZodISOTime",(s,t)=>{Gks.init(s,t),Yf.init(s,t)});function G5s(s){return XSs(H5s,s)}const W5s=xa("ZodISODuration",(s,t)=>{Wks.init(s,t),Yf.init(s,t)});function K5s(s){return QSs(W5s,s)}const eDt=(s,t)=>{D8t.init(s,t),s.name="ZodError",Object.defineProperties(s,{format:{value:n=>DNs(s,n)},flatten:{value:n=>INs(s,n)},addIssue:{value:n=>{s.issues.push(n),s.message=JSON.stringify(s.issues,k$e,2)}},addIssues:{value:n=>{s.issues.push(...n),s.message=JSON.stringify(s.issues,k$e,2)}},isEmpty:{get(){return s.issues.length===0}}})},Y5s=xa("ZodError",eDt),zN=xa("ZodError",eDt,{Parent:Error}),Z5s=RQe(zN),X5s=FQe(zN),Q5s=iPe(zN),J5s=oPe(zN),e4s=ONs(zN),t4s=zNs(zN),s4s=BNs(zN),n4s=UNs(zN),r4s=qNs(zN),a4s=$Ns(zN),i4s=VNs(zN),o4s=HNs(zN),_pt=new WeakMap;function qre(s,t,n){const r=Object.getPrototypeOf(s);let a=_pt.get(r);if(a||(a=new Set,_pt.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 Dx=xa("ZodType",(s,t)=>(Ix.init(s,t),Object.assign(s["~standard"],{jsonSchema:{input:lAe(s,"input"),output:lAe(s,"output")}}),s.toJSONSchema=v5s(s,{}),s.def=t,s.type=t.type,Object.defineProperty(s,"_def",{value:t}),s.parse=(n,r)=>Z5s(s,n,r,{callee:s.parse}),s.safeParse=(n,r)=>Q5s(s,n,r),s.parseAsync=async(n,r)=>X5s(s,n,r,{callee:s.parseAsync}),s.safeParseAsync=async(n,r)=>J5s(s,n,r),s.spa=s.safeParseAsync,s.encode=(n,r)=>e4s(s,n,r),s.decode=(n,r)=>t4s(s,n,r),s.encodeAsync=async(n,r)=>s4s(s,n,r),s.decodeAsync=async(n,r)=>n4s(s,n,r),s.safeEncode=(n,r)=>r4s(s,n,r),s.safeDecode=(n,r)=>a4s(s,n,r),s.safeEncodeAsync=async(n,r)=>i4s(s,n,r),s.safeDecodeAsync=async(n,r)=>o4s(s,n,r),qre(s,"ZodType",{check(...n){const r=this.def;return this.clone(oL(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 lL(this,n,r)},brand(){return this},register(n,r){return n.add(this,r),this},refine(n,r){return this.check(sCs(n,r))},superRefine(n,r){return this.check(nCs(n,r))},overwrite(n){return this.check(oW(n))},optional(){return kpt(this)},exactOptional(){return $4s(this)},nullable(){return Spt(this)},nullish(){return kpt(Spt(this))},nonoptional(n){return Y4s(this,n)},array(){return L4s(this)},or(n){return R4s([this,n])},and(n){return O4s(this,n)},transform(n){return Cpt(this,U4s(n))},default(n){return G4s(this,n)},prefault(n){return K4s(this,n)},catch(n){return X4s(this,n)},pipe(n){return Cpt(this,n)},readonly(){return eCs(this)},describe(n){const r=this.clone();return dX.add(r,{description:n}),r},meta(...n){if(n.length===0)return dX.get(this);const r=this.clone();return dX.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=dX.get(s))==null?void 0:n.description},configurable:!0}),s)),tDt=xa("_ZodString",(s,t)=>{OQe.init(s,t),Dx.init(s,t),s._zod.processJSONSchema=(r,a,i)=>_5s(s,r,a);const n=s._zod.bag;s.format=n.format??null,s.minLength=n.minimum??null,s.maxLength=n.maximum??null,qre(s,"_ZodString",{regex(...r){return this.check(r5s(...r))},includes(...r){return this.check(o5s(...r))},startsWith(...r){return this.check(l5s(...r))},endsWith(...r){return this.check(c5s(...r))},min(...r){return this.check(oAe(...r))},max(...r){return this.check(K8t(...r))},length(...r){return this.check(Y8t(...r))},nonempty(...r){return this.check(oAe(1,...r))},lowercase(r){return this.check(a5s(r))},uppercase(r){return this.check(i5s(r))},trim(){return this.check(u5s())},normalize(...r){return this.check(d5s(...r))},toLowerCase(){return this.check(h5s())},toUpperCase(){return this.check(m5s())},slugify(){return this.check(p5s())}})}),l4s=xa("ZodString",(s,t)=>{OQe.init(s,t),tDt.init(s,t),s.email=n=>s.check(ASs(c4s,n)),s.url=n=>s.check(LSs(d4s,n)),s.jwt=n=>s.check(KSs(k4s,n)),s.emoji=n=>s.check(ISs(u4s,n)),s.guid=n=>s.check(gpt(wpt,n)),s.uuid=n=>s.check(ESs(hle,n)),s.uuidv4=n=>s.check(TSs(hle,n)),s.uuidv6=n=>s.check(MSs(hle,n)),s.uuidv7=n=>s.check(PSs(hle,n)),s.nanoid=n=>s.check(DSs(h4s,n)),s.guid=n=>s.check(gpt(wpt,n)),s.cuid=n=>s.check(RSs(m4s,n)),s.cuid2=n=>s.check(FSs(p4s,n)),s.ulid=n=>s.check(OSs(f4s,n)),s.base64=n=>s.check(HSs(w4s,n)),s.base64url=n=>s.check(GSs(j4s,n)),s.xid=n=>s.check(zSs(x4s,n)),s.ksuid=n=>s.check(BSs(g4s,n)),s.ipv4=n=>s.check(USs(y4s,n)),s.ipv6=n=>s.check(qSs(v4s,n)),s.cidrv4=n=>s.check($Ss(b4s,n)),s.cidrv6=n=>s.check(VSs(_4s,n)),s.e164=n=>s.check(WSs(N4s,n)),s.datetime=n=>s.check(q5s(n)),s.date=n=>s.check(V5s(n)),s.time=n=>s.check(G5s(n)),s.duration=n=>s.check(K5s(n))});function Zo(s){return CSs(l4s,s)}const Yf=xa("ZodStringFormat",(s,t)=>{of.init(s,t),tDt.init(s,t)}),c4s=xa("ZodEmail",(s,t)=>{Dks.init(s,t),Yf.init(s,t)}),wpt=xa("ZodGUID",(s,t)=>{Lks.init(s,t),Yf.init(s,t)}),hle=xa("ZodUUID",(s,t)=>{Iks.init(s,t),Yf.init(s,t)}),d4s=xa("ZodURL",(s,t)=>{Rks.init(s,t),Yf.init(s,t)}),u4s=xa("ZodEmoji",(s,t)=>{Fks.init(s,t),Yf.init(s,t)}),h4s=xa("ZodNanoID",(s,t)=>{Oks.init(s,t),Yf.init(s,t)}),m4s=xa("ZodCUID",(s,t)=>{zks.init(s,t),Yf.init(s,t)}),p4s=xa("ZodCUID2",(s,t)=>{Bks.init(s,t),Yf.init(s,t)}),f4s=xa("ZodULID",(s,t)=>{Uks.init(s,t),Yf.init(s,t)}),x4s=xa("ZodXID",(s,t)=>{qks.init(s,t),Yf.init(s,t)}),g4s=xa("ZodKSUID",(s,t)=>{$ks.init(s,t),Yf.init(s,t)}),y4s=xa("ZodIPv4",(s,t)=>{Kks.init(s,t),Yf.init(s,t)}),v4s=xa("ZodIPv6",(s,t)=>{Yks.init(s,t),Yf.init(s,t)}),b4s=xa("ZodCIDRv4",(s,t)=>{Zks.init(s,t),Yf.init(s,t)}),_4s=xa("ZodCIDRv6",(s,t)=>{Xks.init(s,t),Yf.init(s,t)}),w4s=xa("ZodBase64",(s,t)=>{Qks.init(s,t),Yf.init(s,t)}),j4s=xa("ZodBase64URL",(s,t)=>{eSs.init(s,t),Yf.init(s,t)}),N4s=xa("ZodE164",(s,t)=>{tSs.init(s,t),Yf.init(s,t)}),k4s=xa("ZodJWT",(s,t)=>{nSs.init(s,t),Yf.init(s,t)}),sDt=xa("ZodNumber",(s,t)=>{V8t.init(s,t),Dx.init(s,t),s._zod.processJSONSchema=(r,a,i)=>w5s(s,r,a),qre(s,"ZodNumber",{gt(r,a){return this.check(vpt(r,a))},gte(r,a){return this.check(uOe(r,a))},min(r,a){return this.check(uOe(r,a))},lt(r,a){return this.check(ypt(r,a))},lte(r,a){return this.check(dOe(r,a))},max(r,a){return this.check(dOe(r,a))},int(r){return this.check(jpt(r))},safe(r){return this.check(jpt(r))},positive(r){return this.check(vpt(0,r))},nonnegative(r){return this.check(uOe(0,r))},negative(r){return this.check(ypt(0,r))},nonpositive(r){return this.check(dOe(0,r))},multipleOf(r,a){return this.check(bpt(r,a))},step(r,a){return this.check(bpt(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 _J(s){return JSs(sDt,s)}const S4s=xa("ZodNumberFormat",(s,t)=>{rSs.init(s,t),sDt.init(s,t)});function jpt(s){return e5s(S4s,s)}const C4s=xa("ZodBoolean",(s,t)=>{aSs.init(s,t),Dx.init(s,t),s._zod.processJSONSchema=(n,r,a)=>j5s(s,n,r)});function A4s(s){return t5s(C4s,s)}const E4s=xa("ZodUnknown",(s,t)=>{iSs.init(s,t),Dx.init(s,t),s._zod.processJSONSchema=(n,r,a)=>k5s()});function Npt(){return s5s(E4s)}const T4s=xa("ZodNever",(s,t)=>{oSs.init(s,t),Dx.init(s,t),s._zod.processJSONSchema=(n,r,a)=>N5s(s,n,r)});function M4s(s){return n5s(T4s,s)}const P4s=xa("ZodArray",(s,t)=>{lSs.init(s,t),Dx.init(s,t),s._zod.processJSONSchema=(n,r,a)=>T5s(s,n,r,a),s.element=t.element,qre(s,"ZodArray",{min(n,r){return this.check(oAe(n,r))},nonempty(n){return this.check(oAe(1,n))},max(n,r){return this.check(K8t(n,r))},length(n,r){return this.check(Y8t(n,r))},unwrap(){return this.element}})});function L4s(s,t){return f5s(P4s,s,t)}const I4s=xa("ZodObject",(s,t)=>{dSs.init(s,t),Dx.init(s,t),s._zod.processJSONSchema=(n,r,a)=>M5s(s,n,r,a),um(s,"shape",()=>t.shape),qre(s,"ZodObject",{keyof(){return zQe(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:Npt()})},loose(){return this.clone({...this._zod.def,catchall:Npt()})},strict(){return this.clone({...this._zod.def,catchall:M4s()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return ANs(this,n)},safeExtend(n){return ENs(this,n)},merge(n){return TNs(this,n)},pick(n){return SNs(this,n)},omit(n){return CNs(this,n)},partial(...n){return MNs(nDt,this,n[0])},required(...n){return PNs(rDt,this,n[0])}})});function Bj(s,t){const n={type:"object",shape:s??{},...ol(t)};return new I4s(n)}const D4s=xa("ZodUnion",(s,t)=>{uSs.init(s,t),Dx.init(s,t),s._zod.processJSONSchema=(n,r,a)=>P5s(s,n,r,a),s.options=t.options});function R4s(s,t){return new D4s({type:"union",options:s,...ol(t)})}const F4s=xa("ZodIntersection",(s,t)=>{hSs.init(s,t),Dx.init(s,t),s._zod.processJSONSchema=(n,r,a)=>L5s(s,n,r,a)});function O4s(s,t){return new F4s({type:"intersection",left:s,right:t})}const C$e=xa("ZodEnum",(s,t)=>{mSs.init(s,t),Dx.init(s,t),s._zod.processJSONSchema=(r,a,i)=>S5s(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 C$e({...t,checks:[],...ol(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 C$e({...t,checks:[],...ol(a),entries:i})}});function zQe(s,t){const n=Array.isArray(s)?Object.fromEntries(s.map(r=>[r,r])):s;return new C$e({type:"enum",entries:n,...ol(t)})}const z4s=xa("ZodLiteral",(s,t)=>{pSs.init(s,t),Dx.init(s,t),s._zod.processJSONSchema=(n,r,a)=>C5s(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 gx(s,t){return new z4s({type:"literal",values:Array.isArray(s)?s:[s],...ol(t)})}const B4s=xa("ZodTransform",(s,t)=>{fSs.init(s,t),Dx.init(s,t),s._zod.processJSONSchema=(n,r,a)=>E5s(s,n),s._zod.parse=(n,r)=>{if(r.direction==="backward")throw new E8t(s.constructor.name);n.addIssue=i=>{if(typeof i=="string")n.issues.push(nte(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(nte(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 U4s(s){return new B4s({type:"transform",transform:s})}const nDt=xa("ZodOptional",(s,t)=>{W8t.init(s,t),Dx.init(s,t),s._zod.processJSONSchema=(n,r,a)=>J8t(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function kpt(s){return new nDt({type:"optional",innerType:s})}const q4s=xa("ZodExactOptional",(s,t)=>{xSs.init(s,t),Dx.init(s,t),s._zod.processJSONSchema=(n,r,a)=>J8t(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function $4s(s){return new q4s({type:"optional",innerType:s})}const V4s=xa("ZodNullable",(s,t)=>{gSs.init(s,t),Dx.init(s,t),s._zod.processJSONSchema=(n,r,a)=>I5s(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function Spt(s){return new V4s({type:"nullable",innerType:s})}const H4s=xa("ZodDefault",(s,t)=>{ySs.init(s,t),Dx.init(s,t),s._zod.processJSONSchema=(n,r,a)=>R5s(s,n,r,a),s.unwrap=()=>s._zod.def.innerType,s.removeDefault=s.unwrap});function G4s(s,t){return new H4s({type:"default",innerType:s,get defaultValue(){return typeof t=="function"?t():P8t(t)}})}const W4s=xa("ZodPrefault",(s,t)=>{vSs.init(s,t),Dx.init(s,t),s._zod.processJSONSchema=(n,r,a)=>F5s(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function K4s(s,t){return new W4s({type:"prefault",innerType:s,get defaultValue(){return typeof t=="function"?t():P8t(t)}})}const rDt=xa("ZodNonOptional",(s,t)=>{bSs.init(s,t),Dx.init(s,t),s._zod.processJSONSchema=(n,r,a)=>D5s(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function Y4s(s,t){return new rDt({type:"nonoptional",innerType:s,...ol(t)})}const Z4s=xa("ZodCatch",(s,t)=>{_Ss.init(s,t),Dx.init(s,t),s._zod.processJSONSchema=(n,r,a)=>O5s(s,n,r,a),s.unwrap=()=>s._zod.def.innerType,s.removeCatch=s.unwrap});function X4s(s,t){return new Z4s({type:"catch",innerType:s,catchValue:typeof t=="function"?t:()=>t})}const Q4s=xa("ZodPipe",(s,t)=>{wSs.init(s,t),Dx.init(s,t),s._zod.processJSONSchema=(n,r,a)=>z5s(s,n,r,a),s.in=t.in,s.out=t.out});function Cpt(s,t){return new Q4s({type:"pipe",in:s,out:t})}const J4s=xa("ZodReadonly",(s,t)=>{jSs.init(s,t),Dx.init(s,t),s._zod.processJSONSchema=(n,r,a)=>B5s(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function eCs(s){return new J4s({type:"readonly",innerType:s})}const tCs=xa("ZodCustom",(s,t)=>{NSs.init(s,t),Dx.init(s,t),s._zod.processJSONSchema=(n,r,a)=>A5s(s,n)});function sCs(s,t={}){return x5s(tCs,s,t)}function nCs(s,t){return g5s(s,t)}var rCs="Label",aDt=_.forwardRef((s,t)=>e.jsx(ii.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())}}));aDt.displayName=rCs;var iDt=aDt;const aCs=F9("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),J=_.forwardRef(({className:s,...t},n)=>e.jsx(iDt,{ref:n,className:At(aCs(),s),...t}));J.displayName=iDt.displayName;const cPe=J2s,oDt=_.createContext({}),Sf=({...s})=>e.jsx(oDt.Provider,{value:{name:s.name},children:e.jsx(nNs,{...s})}),dPe=()=>{const s=_.useContext(oDt),t=_.useContext(lDt),{getFieldState:n,formState:r}=nPe(),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}},lDt=_.createContext({}),Yp=_.forwardRef(({className:s,...t},n)=>{const r=_.useId();return e.jsx(lDt.Provider,{value:{id:r},children:e.jsx("div",{ref:n,className:At("space-y-2",s),...t})})});Yp.displayName="FormItem";const Zp=_.forwardRef(({className:s,...t},n)=>{const{error:r,formItemId:a}=dPe();return e.jsx(J,{ref:n,className:At(r&&"text-destructive",s),htmlFor:a,...t})});Zp.displayName="FormLabel";const Xp=_.forwardRef(({...s},t)=>{const{error:n,formItemId:r,formDescriptionId:a,formMessageId:i}=dPe();return e.jsx(LXe,{ref:t,id:r,"aria-describedby":n?`${a} ${i}`:`${a}`,"aria-invalid":!!n,...s})});Xp.displayName="FormControl";const b4e=_.forwardRef(({className:s,...t},n)=>{const{formDescriptionId:r}=dPe();return e.jsx("p",{ref:n,id:r,className:At("text-sm text-muted-foreground",s),...t})});b4e.displayName="FormDescription";const ub=_.forwardRef(({className:s,children:t,...n},r)=>{const{error:a,formMessageId:i}=dPe(),l=a?String(a==null?void 0:a.message):t;return l?e.jsx("p",{ref:r,id:i,className:At("text-sm font-medium text-destructive",s),...n,children:l}):null});ub.displayName="FormMessage";const xe=_.forwardRef(({className:s,type:t,...n},r)=>e.jsx("input",{type:t,className:At("flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",s),ref:r,...n}));xe.displayName="Input";function $re(s){const t=_.useRef({value:s,previous:s});return _.useMemo(()=>(t.current.value!==s&&(t.current.previous=t.current.value,t.current.value=s),t.current.previous),[s])}var iCs=[" ","Enter","ArrowUp","ArrowDown"],oCs=[" ","Enter"],Y7="Select",[uPe,hPe,lCs]=KG(Y7),[lW,kbr]=af(Y7,[lCs,_C]),mPe=_C(),[cCs,cL]=lW(Y7),[dCs,uCs]=lW(Y7),cDt=s=>{const{__scopeSelect:t,children:n,open:r,defaultOpen:a,onOpenChange:i,value:l,defaultValue:o,onValueChange:c,dir:d,name:u,autoComplete:h,disabled:m,required:p,form:f}=s,y=mPe(t),[v,g]=_.useState(null),[b,j]=_.useState(null),[S,C]=_.useState(!1),E=DE(d),[P,M]=Ug({prop:r,defaultProp:a??!1,onChange:i,caller:Y7}),[I,D]=Ug({prop:l,defaultProp:o,onChange:c,caller:Y7}),O=_.useRef(null),V=v?f||!!v.closest("form"):!0,[G,$]=_.useState(new Set),H=Array.from(G).map(Y=>Y.props.value).join(";");return e.jsx(Are,{...y,children:e.jsxs(cCs,{required:p,scope:t,trigger:v,onTriggerChange:g,valueNode:b,onValueNodeChange:j,valueNodeHasChildren:S,onValueNodeHasChildrenChange:C,contentId:Og(),value:I,onValueChange:D,open:P,onOpenChange:M,dir:E,triggerPointerDownPosRef:O,disabled:m,children:[e.jsx(uPe.Provider,{scope:t,children:e.jsx(dCs,{scope:s.__scopeSelect,onNativeOptionAdd:_.useCallback(Y=>{$(Z=>new Set(Z).add(Y))},[]),onNativeOptionRemove:_.useCallback(Y=>{$(Z=>{const ne=new Set(Z);return ne.delete(Y),ne})},[]),children:n})}),V?e.jsxs(IDt,{"aria-hidden":!0,required:p,tabIndex:-1,name:u,autoComplete:h,value:I,onChange:Y=>D(Y.target.value),disabled:m,form:f,children:[I===void 0?e.jsx("option",{value:""}):null,Array.from(G)]},H):null]})})};cDt.displayName=Y7;var dDt="SelectTrigger",uDt=_.forwardRef((s,t)=>{const{__scopeSelect:n,disabled:r=!1,...a}=s,i=mPe(n),l=cL(dDt,n),o=l.disabled||r,c=Qo(t,l.onTriggerChange),d=hPe(n),u=_.useRef("touch"),[h,m,p]=RDt(y=>{const v=d().filter(j=>!j.disabled),g=v.find(j=>j.value===l.value),b=FDt(v,y,g);b!==void 0&&l.onValueChange(b.value)}),f=y=>{o||(l.onOpenChange(!0),p()),y&&(l.triggerPointerDownPosRef.current={x:Math.round(y.pageX),y:Math.round(y.pageY)})};return e.jsx(tW,{asChild:!0,...i,children:e.jsx(ii.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":DDt(l.value)?"":void 0,...a,ref:c,onClick:wa(a.onClick,y=>{y.currentTarget.focus(),u.current!=="mouse"&&f(y)}),onPointerDown:wa(a.onPointerDown,y=>{u.current=y.pointerType;const v=y.target;v.hasPointerCapture(y.pointerId)&&v.releasePointerCapture(y.pointerId),y.button===0&&y.ctrlKey===!1&&y.pointerType==="mouse"&&(f(y),y.preventDefault())}),onKeyDown:wa(a.onKeyDown,y=>{const v=h.current!=="";!(y.ctrlKey||y.altKey||y.metaKey)&&y.key.length===1&&m(y.key),!(v&&y.key===" ")&&iCs.includes(y.key)&&(f(),y.preventDefault())})})})});uDt.displayName=dDt;var hDt="SelectValue",mDt=_.forwardRef((s,t)=>{const{__scopeSelect:n,className:r,style:a,children:i,placeholder:l="",...o}=s,c=cL(hDt,n),{onValueNodeHasChildrenChange:d}=c,u=i!==void 0,h=Qo(t,c.onValueNodeChange);return Mx(()=>{d(u)},[d,u]),e.jsx(ii.span,{...o,ref:h,style:{pointerEvents:"none"},children:DDt(c.value)?e.jsx(e.Fragment,{children:l}):i})});mDt.displayName=hDt;var hCs="SelectIcon",pDt=_.forwardRef((s,t)=>{const{__scopeSelect:n,children:r,...a}=s;return e.jsx(ii.span,{"aria-hidden":!0,...a,ref:t,children:r||"▼"})});pDt.displayName=hCs;var mCs="SelectPortal",fDt=s=>e.jsx(YG,{asChild:!0,...s});fDt.displayName=mCs;var Z7="SelectContent",xDt=_.forwardRef((s,t)=>{const n=cL(Z7,s.__scopeSelect),[r,a]=_.useState();if(Mx(()=>{a(new DocumentFragment)},[]),!n.open){const i=r;return i?mv.createPortal(e.jsx(gDt,{scope:s.__scopeSelect,children:e.jsx(uPe.Slot,{scope:s.__scopeSelect,children:e.jsx("div",{children:s.children})})}),i):null}return e.jsx(yDt,{...s,ref:t})});xDt.displayName=Z7;var jk=10,[gDt,dL]=lW(Z7),pCs="SelectContentImpl",fCs=CP("SelectContent.RemoveScroll"),yDt=_.forwardRef((s,t)=>{const{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:a,onEscapeKeyDown:i,onPointerDownOutside:l,side:o,sideOffset:c,align:d,alignOffset:u,arrowPadding:h,collisionBoundary:m,collisionPadding:p,sticky:f,hideWhenDetached:y,avoidCollisions:v,...g}=s,b=cL(Z7,n),[j,S]=_.useState(null),[C,E]=_.useState(null),P=Qo(t,pe=>S(pe)),[M,I]=_.useState(null),[D,O]=_.useState(null),V=hPe(n),[G,$]=_.useState(!1),H=_.useRef(!1);_.useEffect(()=>{if(j)return SMe(j)},[j]),NMe();const Y=_.useCallback(pe=>{const[Ce,...Ae]=V().map(ke=>ke.ref.current),[Pe]=Ae.slice(-1),ze=document.activeElement;for(const ke of pe)if(ke===ze||(ke==null||ke.scrollIntoView({block:"nearest"}),ke===Ce&&C&&(C.scrollTop=0),ke===Pe&&C&&(C.scrollTop=C.scrollHeight),ke==null||ke.focus(),document.activeElement!==ze))return},[V,C]),Z=_.useCallback(()=>Y([M,j]),[Y,M,j]);_.useEffect(()=>{G&&Z()},[G,Z]);const{onOpenChange:ne,triggerPointerDownPosRef:ce}=b;_.useEffect(()=>{if(j){let pe={x:0,y:0};const Ce=Pe=>{var ze,ke;pe={x:Math.abs(Math.round(Pe.pageX)-(((ze=ce.current)==null?void 0:ze.x)??0)),y:Math.abs(Math.round(Pe.pageY)-(((ke=ce.current)==null?void 0:ke.y)??0))}},Ae=Pe=>{pe.x<=10&&pe.y<=10?Pe.preventDefault():j.contains(Pe.target)||ne(!1),document.removeEventListener("pointermove",Ce),ce.current=null};return ce.current!==null&&(document.addEventListener("pointermove",Ce),document.addEventListener("pointerup",Ae,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",Ce),document.removeEventListener("pointerup",Ae,{capture:!0})}}},[j,ne,ce]),_.useEffect(()=>{const pe=()=>ne(!1);return window.addEventListener("blur",pe),window.addEventListener("resize",pe),()=>{window.removeEventListener("blur",pe),window.removeEventListener("resize",pe)}},[ne]);const[ie,te]=RDt(pe=>{const Ce=V().filter(ze=>!ze.disabled),Ae=Ce.find(ze=>ze.ref.current===document.activeElement),Pe=FDt(Ce,pe,Ae);Pe&&setTimeout(()=>Pe.ref.current.focus())}),ae=_.useCallback((pe,Ce,Ae)=>{const Pe=!H.current&&!Ae;(b.value!==void 0&&b.value===Ce||Pe)&&(I(pe),Pe&&(H.current=!0))},[b.value]),le=_.useCallback(()=>j==null?void 0:j.focus(),[j]),be=_.useCallback((pe,Ce,Ae)=>{const Pe=!H.current&&!Ae;(b.value!==void 0&&b.value===Ce||Pe)&&O(pe)},[b.value]),me=r==="popper"?A$e:vDt,he=me===A$e?{side:o,sideOffset:c,align:d,alignOffset:u,arrowPadding:h,collisionBoundary:m,collisionPadding:p,sticky:f,hideWhenDetached:y,avoidCollisions:v}:{};return e.jsx(gDt,{scope:n,content:j,viewport:C,onViewportChange:E,itemRefCallback:ae,selectedItem:M,onItemLeave:le,itemTextRefCallback:be,focusSelectedItem:Z,selectedItemText:D,position:r,isPositioned:G,searchRef:ie,children:e.jsx(wre,{as:fCs,allowPinchZoom:!0,children:e.jsx(_re,{asChild:!0,trapped:b.open,onMountAutoFocus:pe=>{pe.preventDefault()},onUnmountAutoFocus:wa(a,pe=>{var Ce;(Ce=b.trigger)==null||Ce.focus({preventScroll:!0}),pe.preventDefault()}),children:e.jsx(rL,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:i,onPointerDownOutside:l,onFocusOutside:pe=>pe.preventDefault(),onDismiss:()=>b.onOpenChange(!1),children:e.jsx(me,{role:"listbox",id:b.contentId,"data-state":b.open?"open":"closed",dir:b.dir,onContextMenu:pe=>pe.preventDefault(),...g,...he,onPlaced:()=>$(!0),ref:P,style:{display:"flex",flexDirection:"column",outline:"none",...g.style},onKeyDown:wa(g.onKeyDown,pe=>{const Ce=pe.ctrlKey||pe.altKey||pe.metaKey;if(pe.key==="Tab"&&pe.preventDefault(),!Ce&&pe.key.length===1&&te(pe.key),["ArrowUp","ArrowDown","Home","End"].includes(pe.key)){let Pe=V().filter(ze=>!ze.disabled).map(ze=>ze.ref.current);if(["ArrowUp","End"].includes(pe.key)&&(Pe=Pe.slice().reverse()),["ArrowUp","ArrowDown"].includes(pe.key)){const ze=pe.target,ke=Pe.indexOf(ze);Pe=Pe.slice(ke+1)}setTimeout(()=>Y(Pe)),pe.preventDefault()}})})})})})})});yDt.displayName=pCs;var xCs="SelectItemAlignedPosition",vDt=_.forwardRef((s,t)=>{const{__scopeSelect:n,onPlaced:r,...a}=s,i=cL(Z7,n),l=dL(Z7,n),[o,c]=_.useState(null),[d,u]=_.useState(null),h=Qo(t,P=>u(P)),m=hPe(n),p=_.useRef(!1),f=_.useRef(!0),{viewport:y,selectedItem:v,selectedItemText:g,focusSelectedItem:b}=l,j=_.useCallback(()=>{if(i.trigger&&i.valueNode&&o&&d&&y&&v&&g){const P=i.trigger.getBoundingClientRect(),M=d.getBoundingClientRect(),I=i.valueNode.getBoundingClientRect(),D=g.getBoundingClientRect();if(i.dir!=="rtl"){const ze=D.left-M.left,ke=I.left-ze,Ze=P.left-ke,Se=P.width+Ze,Fe=Math.max(Se,M.width),Ne=window.innerWidth-jk,Ye=tte(ke,[jk,Math.max(jk,Ne-Fe)]);o.style.minWidth=Se+"px",o.style.left=Ye+"px"}else{const ze=M.right-D.right,ke=window.innerWidth-I.right-ze,Ze=window.innerWidth-P.right-ke,Se=P.width+Ze,Fe=Math.max(Se,M.width),Ne=window.innerWidth-jk,Ye=tte(ke,[jk,Math.max(jk,Ne-Fe)]);o.style.minWidth=Se+"px",o.style.right=Ye+"px"}const O=m(),V=window.innerHeight-jk*2,G=y.scrollHeight,$=window.getComputedStyle(d),H=parseInt($.borderTopWidth,10),Y=parseInt($.paddingTop,10),Z=parseInt($.borderBottomWidth,10),ne=parseInt($.paddingBottom,10),ce=H+Y+G+ne+Z,ie=Math.min(v.offsetHeight*5,ce),te=window.getComputedStyle(y),ae=parseInt(te.paddingTop,10),le=parseInt(te.paddingBottom,10),be=P.top+P.height/2-jk,me=V-be,he=v.offsetHeight/2,pe=v.offsetTop+he,Ce=H+Y+pe,Ae=ce-Ce;if(Ce<=be){const ze=O.length>0&&v===O[O.length-1].ref.current;o.style.bottom="0px";const ke=d.clientHeight-y.offsetTop-y.offsetHeight,Ze=Math.max(me,he+(ze?le:0)+ke+Z),Se=Ce+Ze;o.style.height=Se+"px"}else{const ze=O.length>0&&v===O[0].ref.current;o.style.top="0px";const Ze=Math.max(be,H+y.offsetTop+(ze?ae:0)+he)+Ae;o.style.height=Ze+"px",y.scrollTop=Ce-be+y.offsetTop}o.style.margin=`${jk}px 0`,o.style.minHeight=ie+"px",o.style.maxHeight=V+"px",r==null||r(),requestAnimationFrame(()=>p.current=!0)}},[m,i.trigger,i.valueNode,o,d,y,v,g,i.dir,r]);Mx(()=>j(),[j]);const[S,C]=_.useState();Mx(()=>{d&&C(window.getComputedStyle(d).zIndex)},[d]);const E=_.useCallback(P=>{P&&f.current===!0&&(j(),b==null||b(),f.current=!1)},[j,b]);return e.jsx(yCs,{scope:n,contentWrapper:o,shouldExpandOnScrollRef:p,onScrollButtonChange:E,children:e.jsx("div",{ref:c,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:S},children:e.jsx(ii.div,{...a,ref:h,style:{boxSizing:"border-box",maxHeight:"100%",...a.style}})})})});vDt.displayName=xCs;var gCs="SelectPopperPosition",A$e=_.forwardRef((s,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:a=jk,...i}=s,l=mPe(n);return e.jsx(Ere,{...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)"}})});A$e.displayName=gCs;var[yCs,BQe]=lW(Z7,{}),E$e="SelectViewport",bDt=_.forwardRef((s,t)=>{const{__scopeSelect:n,nonce:r,...a}=s,i=dL(E$e,n),l=BQe(E$e,n),o=Qo(t,i.onViewportChange),c=_.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(uPe.Slot,{scope:n,children:e.jsx(ii.div,{"data-radix-select-viewport":"",role:"presentation",...a,ref:o,style:{position:"relative",flex:1,overflow:"hidden auto",...a.style},onScroll:wa(a.onScroll,d=>{const u=d.currentTarget,{contentWrapper:h,shouldExpandOnScrollRef:m}=l;if(m!=null&&m.current&&h){const p=Math.abs(c.current-u.scrollTop);if(p>0){const f=window.innerHeight-jk*2,y=parseFloat(h.style.minHeight),v=parseFloat(h.style.height),g=Math.max(y,v);if(g0?S:0,h.style.justifyContent="flex-end")}}}c.current=u.scrollTop})})})]})});bDt.displayName=E$e;var _Dt="SelectGroup",[vCs,bCs]=lW(_Dt),wDt=_.forwardRef((s,t)=>{const{__scopeSelect:n,...r}=s,a=Og();return e.jsx(vCs,{scope:n,id:a,children:e.jsx(ii.div,{role:"group","aria-labelledby":a,...r,ref:t})})});wDt.displayName=_Dt;var jDt="SelectLabel",NDt=_.forwardRef((s,t)=>{const{__scopeSelect:n,...r}=s,a=bCs(jDt,n);return e.jsx(ii.div,{id:a.id,...r,ref:t})});NDt.displayName=jDt;var cAe="SelectItem",[_Cs,kDt]=lW(cAe),SDt=_.forwardRef((s,t)=>{const{__scopeSelect:n,value:r,disabled:a=!1,textValue:i,...l}=s,o=cL(cAe,n),c=dL(cAe,n),d=o.value===r,[u,h]=_.useState(i??""),[m,p]=_.useState(!1),f=Qo(t,b=>{var j;return(j=c.itemRefCallback)==null?void 0:j.call(c,b,r,a)}),y=Og(),v=_.useRef("touch"),g=()=>{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(_Cs,{scope:n,value:r,disabled:a,textId:y,isSelected:d,onItemTextChange:_.useCallback(b=>{h(j=>j||((b==null?void 0:b.textContent)??"").trim())},[]),children:e.jsx(uPe.ItemSlot,{scope:n,value:r,disabled:a,textValue:u,children:e.jsx(ii.div,{role:"option","aria-labelledby":y,"data-highlighted":m?"":void 0,"aria-selected":d&&m,"data-state":d?"checked":"unchecked","aria-disabled":a||void 0,"data-disabled":a?"":void 0,tabIndex:a?void 0:-1,...l,ref:f,onFocus:wa(l.onFocus,()=>p(!0)),onBlur:wa(l.onBlur,()=>p(!1)),onClick:wa(l.onClick,()=>{v.current!=="mouse"&&g()}),onPointerUp:wa(l.onPointerUp,()=>{v.current==="mouse"&&g()}),onPointerDown:wa(l.onPointerDown,b=>{v.current=b.pointerType}),onPointerMove:wa(l.onPointerMove,b=>{var j;v.current=b.pointerType,a?(j=c.onItemLeave)==null||j.call(c):v.current==="mouse"&&b.currentTarget.focus({preventScroll:!0})}),onPointerLeave:wa(l.onPointerLeave,b=>{var j;b.currentTarget===document.activeElement&&((j=c.onItemLeave)==null||j.call(c))}),onKeyDown:wa(l.onKeyDown,b=>{var S;((S=c.searchRef)==null?void 0:S.current)!==""&&b.key===" "||(oCs.includes(b.key)&&g(),b.key===" "&&b.preventDefault())})})})})});SDt.displayName=cAe;var uX="SelectItemText",CDt=_.forwardRef((s,t)=>{const{__scopeSelect:n,className:r,style:a,...i}=s,l=cL(uX,n),o=dL(uX,n),c=kDt(uX,n),d=uCs(uX,n),[u,h]=_.useState(null),m=Qo(t,g=>h(g),c.onItemTextChange,g=>{var b;return(b=o.itemTextRefCallback)==null?void 0:b.call(o,g,c.value,c.disabled)}),p=u==null?void 0:u.textContent,f=_.useMemo(()=>e.jsx("option",{value:c.value,disabled:c.disabled,children:p},c.value),[c.disabled,c.value,p]),{onNativeOptionAdd:y,onNativeOptionRemove:v}=d;return Mx(()=>(y(f),()=>v(f)),[y,v,f]),e.jsxs(e.Fragment,{children:[e.jsx(ii.span,{id:c.textId,...i,ref:m}),c.isSelected&&l.valueNode&&!l.valueNodeHasChildren?mv.createPortal(i.children,l.valueNode):null]})});CDt.displayName=uX;var ADt="SelectItemIndicator",EDt=_.forwardRef((s,t)=>{const{__scopeSelect:n,...r}=s;return kDt(ADt,n).isSelected?e.jsx(ii.span,{"aria-hidden":!0,...r,ref:t}):null});EDt.displayName=ADt;var T$e="SelectScrollUpButton",TDt=_.forwardRef((s,t)=>{const n=dL(T$e,s.__scopeSelect),r=BQe(T$e,s.__scopeSelect),[a,i]=_.useState(!1),l=Qo(t,r.onScrollButtonChange);return Mx(()=>{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(PDt,{...s,ref:l,onAutoScroll:()=>{const{viewport:o,selectedItem:c}=n;o&&c&&(o.scrollTop=o.scrollTop-c.offsetHeight)}}):null});TDt.displayName=T$e;var M$e="SelectScrollDownButton",MDt=_.forwardRef((s,t)=>{const n=dL(M$e,s.__scopeSelect),r=BQe(M$e,s.__scopeSelect),[a,i]=_.useState(!1),l=Qo(t,r.onScrollButtonChange);return Mx(()=>{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(PDt,{...s,ref:l,onAutoScroll:()=>{const{viewport:o,selectedItem:c}=n;o&&c&&(o.scrollTop=o.scrollTop+c.offsetHeight)}}):null});MDt.displayName=M$e;var PDt=_.forwardRef((s,t)=>{const{__scopeSelect:n,onAutoScroll:r,...a}=s,i=dL("SelectScrollButton",n),l=_.useRef(null),o=hPe(n),c=_.useCallback(()=>{l.current!==null&&(window.clearInterval(l.current),l.current=null)},[]);return _.useEffect(()=>()=>c(),[c]),Mx(()=>{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(ii.div,{"aria-hidden":!0,...a,ref:t,style:{flexShrink:0,...a.style},onPointerDown:wa(a.onPointerDown,()=>{l.current===null&&(l.current=window.setInterval(r,50))}),onPointerMove:wa(a.onPointerMove,()=>{var d;(d=i.onItemLeave)==null||d.call(i),l.current===null&&(l.current=window.setInterval(r,50))}),onPointerLeave:wa(a.onPointerLeave,()=>{c()})})}),wCs="SelectSeparator",LDt=_.forwardRef((s,t)=>{const{__scopeSelect:n,...r}=s;return e.jsx(ii.div,{"aria-hidden":!0,...r,ref:t})});LDt.displayName=wCs;var P$e="SelectArrow",jCs=_.forwardRef((s,t)=>{const{__scopeSelect:n,...r}=s,a=mPe(n),i=cL(P$e,n),l=dL(P$e,n);return i.open&&l.position==="popper"?e.jsx(Tre,{...a,...r,ref:t}):null});jCs.displayName=P$e;var NCs="SelectBubbleInput",IDt=_.forwardRef(({__scopeSelect:s,value:t,...n},r)=>{const a=_.useRef(null),i=Qo(r,a),l=$re(t);return _.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(ii.select,{...n,style:{...F6t,...n.style},ref:i,defaultValue:t})});IDt.displayName=NCs;function DDt(s){return s===""||s===void 0}function RDt(s){const t=wx(s),n=_.useRef(""),r=_.useRef(0),a=_.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=_.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return _.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,a,i]}function FDt(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=kCs(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 kCs(s,t){return s.map((n,r)=>s[(t+r)%s.length])}var SCs=cDt,ODt=uDt,CCs=mDt,ACs=pDt,ECs=fDt,zDt=xDt,TCs=bDt,MCs=wDt,BDt=NDt,UDt=SDt,PCs=CDt,LCs=EDt,qDt=TDt,$Dt=MDt,VDt=LDt;const is=SCs,ICs=MCs,ls=CCs,rs=_.forwardRef(({className:s,children:t,...n},r)=>e.jsxs(ODt,{ref:r,className:At("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(ACs,{asChild:!0,children:e.jsx(tl,{className:"h-4 w-4 opacity-50"})})]}));rs.displayName=ODt.displayName;const HDt=_.forwardRef(({className:s,...t},n)=>e.jsx(qDt,{ref:n,className:At("flex cursor-default items-center justify-center py-1",s),...t,children:e.jsx(_v,{className:"h-4 w-4"})}));HDt.displayName=qDt.displayName;const GDt=_.forwardRef(({className:s,...t},n)=>e.jsx($Dt,{ref:n,className:At("flex cursor-default items-center justify-center py-1",s),...t,children:e.jsx(tl,{className:"h-4 w-4"})}));GDt.displayName=$Dt.displayName;const as=_.forwardRef(({className:s,children:t,position:n="popper",...r},a)=>e.jsx(ECs,{children:e.jsxs(zDt,{ref:a,className:At("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(HDt,{}),e.jsx(TCs,{className:At("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),e.jsx(GDt,{})]})}));as.displayName=zDt.displayName;const WDt=_.forwardRef(({className:s,...t},n)=>e.jsx(BDt,{ref:n,className:At("py-1.5 pl-8 pr-2 text-sm font-semibold",s),...t}));WDt.displayName=BDt.displayName;const He=_.forwardRef(({className:s,children:t,...n},r)=>e.jsxs(UDt,{ref:r,className:At("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(LCs,{children:e.jsx(ea,{className:"h-4 w-4"})})}),e.jsx(PCs,{children:t})]}));He.displayName=UDt.displayName;const DCs=_.forwardRef(({className:s,...t},n)=>e.jsx(VDt,{ref:n,className:At("-mx-1 my-1 h-px bg-muted",s),...t}));DCs.displayName=VDt.displayName;const RCs=Bj({category:zQe(["general","technology","crm","marketing"]),subject:Zo().min(5,"Subject must be at least 5 characters").max(200),description:Zo().min(20,"Please provide more details (at least 20 characters)").max(2e3)}),FCs={general:"General Support",technology:"Technology Support",crm:"CRM Support",marketing:"Marketing Support"};function L$e({trigger:s}){const[t,n]=_.useState(!1),[r,a]=_.useState(!1),{user:i}=hs(),l=rPe({resolver:aPe(RCs),defaultValues:{category:"general",subject:"",description:""}}),o=async c=>{if(!i){se.error("You must be logged in to submit a ticket");return}a(!0);try{const{error:d}=await q.from("support_tickets").insert({user_id:i.id,category:c.category,subject:c.subject,description:c.description});if(d)throw d;try{await q.functions.invoke("support-ticket-notify",{body:{category:FCs[c.category],subject:c.subject}})}catch(u){console.log("Notification send attempted:",u)}se.success("Support ticket submitted successfully!"),l.reset(),n(!1)}catch(d){console.error("Error submitting ticket:",d),se.error("Failed to submit ticket. Please try again.")}finally{a(!1)}};return e.jsxs(Ls,{open:t,onOpenChange:n,children:[e.jsx(nl,{asChild:!0,children:s||e.jsxs(B,{variant:"ghost",size:"icon",className:"relative",children:[e.jsx($Q,{className:"h-5 w-5"}),e.jsx("span",{className:"sr-only",children:"Support"})]})}),e.jsxs(Ps,{className:"sm:max-w-[500px]",children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Need Help?"}),e.jsx(_r,{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(_a,{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(cPe,{...l,children:e.jsxs("form",{onSubmit:l.handleSubmit(o),className:"space-y-4",children:[e.jsx(Sf,{control:l.control,name:"category",render:({field:c})=>e.jsxs(Yp,{children:[e.jsx(Zp,{children:"Category"}),e.jsxs(is,{onValueChange:c.onChange,defaultValue:c.value,children:[e.jsx(Xp,{children:e.jsx(rs,{children:e.jsx(ls,{placeholder:"Select a category"})})}),e.jsxs(as,{children:[e.jsx(He,{value:"general",children:"General Support"}),e.jsx(He,{value:"technology",children:"Technology Support"}),e.jsx(He,{value:"crm",children:"CRM Support"}),e.jsx(He,{value:"marketing",children:"Marketing Support"})]})]}),e.jsx(ub,{})]})}),e.jsx(Sf,{control:l.control,name:"subject",render:({field:c})=>e.jsxs(Yp,{children:[e.jsx(Zp,{children:"Subject"}),e.jsx(Xp,{children:e.jsx(xe,{placeholder:"Brief description of your issue",...c})}),e.jsx(ub,{})]})}),e.jsx(Sf,{control:l.control,name:"description",render:({field:c})=>e.jsxs(Yp,{children:[e.jsx(Zp,{children:"Description"}),e.jsx(Xp,{children:e.jsx(Ms,{placeholder:"Please describe your issue in detail...",className:"min-h-[120px]",...c})}),e.jsx(ub,{})]})}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(B,{type:"submit",disabled:r,children:r?"Submitting...":"Submit Ticket"})]})]})})]})]})}function po(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 Bh(s,t){return s instanceof Date?new s.constructor(t):new Date(t)}function zh(s,t){const n=po(s);return isNaN(t)?Bh(s,NaN):(t&&n.setDate(n.getDate()+t),n)}function Cy(s,t){const n=po(s);if(isNaN(t))return Bh(s,NaN);if(!t)return n;const r=n.getDate(),a=Bh(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 KDt(s,t){const n=+po(s);return Bh(s,n+t)}const UQe=6048e5,OCs=864e5,pPe=6e4,fPe=36e5,zCs=1e3,mle=43200,Apt=1440;function Ept(s,t){return KDt(s,t*fPe)}let BCs={};function uL(){return BCs}function v1(s,t){var o,c,d,u;const n=uL(),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=po(s),i=a.getDay(),l=(i=a.getTime()?n+1:t.getTime()>=l.getTime()?n:n-1}function If(s){const t=po(s);return t.setHours(0,0,0,0),t}function LP(s){const t=po(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 pv(s,t){const n=If(s),r=If(t),a=+n-LP(n),i=+r-LP(r);return Math.round((a-i)/OCs)}function UCs(s){const t=YDt(s),n=Bh(s,0);return n.setFullYear(t,0,4),n.setHours(0,0,0,0),_E(n)}function Tpt(s,t){return KDt(s,t*pPe)}function uF(s,t){const n=t*7;return zh(s,n)}function qCs(s,t){return Cy(s,t*12)}function $Cs(s){let t;return s.forEach(function(n){const r=po(n);(t===void 0||t{const r=po(n);(!t||t>r||isNaN(+r))&&(t=r)}),t||new Date(NaN)}function _4e(s,t){const n=po(s),r=po(t),a=n.getTime()-r.getTime();return a<0?-1:a>0?1:a}function xPe(s){return Bh(s,Date.now())}function cm(s,t){const n=If(s),r=If(t);return+n==+r}function qQe(s){return s instanceof Date||typeof s=="object"&&Object.prototype.toString.call(s)==="[object Date]"}function I$e(s){if(!qQe(s)&&typeof s!="number")return!1;const t=po(s);return!isNaN(Number(t))}function AH(s,t){const n=po(s),r=po(t),a=n.getFullYear()-r.getFullYear(),i=n.getMonth()-r.getMonth();return a*12+i}function HCs(s,t,n){const r=v1(s,n),a=v1(t,n),i=+r-LP(r),l=+a-LP(a);return Math.round((i-l)/UQe)}function CN(s,t){const n=po(s),r=po(t),a=Mpt(n,r),i=Math.abs(pv(n,r));n.setDate(n.getDate()-a*i);const l=+(Mpt(n,r)===-a),o=a*(i-l);return o===0?0:o}function Mpt(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 GCs(s){return t=>{const r=(s?Math[s]:Math.trunc)(t);return r===0?0:r}}function WCs(s,t){return+po(s)-+po(t)}function KCs(s){const t=po(s);return t.setHours(23,59,59,999),t}function y_(s){const t=po(s),n=t.getMonth();return t.setFullYear(t.getFullYear(),n+1,0),t.setHours(23,59,59,999),t}function YCs(s){const t=po(s);return+KCs(t)==+y_(t)}function ZCs(s,t){const n=po(s),r=po(t),a=_4e(n,r),i=Math.abs(AH(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=_4e(n,r)===-a;YCs(po(s))&&i===1&&_4e(s,r)===1&&(o=!1),l=a*(i-Number(o))}return l===0?0:l}function XCs(s,t,n){const r=WCs(s,t)/1e3;return GCs(n==null?void 0:n.roundingMethod)(r)}function QCs(s,t){const n=po(s.start),r=po(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(po(l)),l.setDate(l.getDate()+o),l.setHours(0,0,0,0);return a?c.reverse():c}function JCs(s){const t=po(s),n=t.getMonth(),r=n-n%3;return t.setMonth(r,1),t.setHours(0,0,0,0),t}function rm(s){const t=po(s);return t.setDate(1),t.setHours(0,0,0,0),t}function $Qe(s){const t=po(s),n=Bh(s,0);return n.setFullYear(t.getFullYear(),0,1),n.setHours(0,0,0,0),n}function gPe(s,t){var o,c,d,u;const n=uL(),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=po(s),i=a.getDay(),l=(i{let r;const a=e3s[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 hOe(s){return(t={})=>{const n=t.width?String(t.width):s.defaultWidth;return s.formats[n]||s.formats[s.defaultWidth]}}const s3s={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},n3s={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},r3s={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},a3s={date:hOe({formats:s3s,defaultWidth:"full"}),time:hOe({formats:n3s,defaultWidth:"full"}),dateTime:hOe({formats:r3s,defaultWidth:"full"})},i3s={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},o3s=(s,t,n,r)=>i3s[s];function DY(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 l3s={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},c3s={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},d3s={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"]},u3s={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"]},h3s={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"}},m3s={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"}},p3s=(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"},f3s={ordinalNumber:p3s,era:DY({values:l3s,defaultWidth:"wide"}),quarter:DY({values:c3s,defaultWidth:"wide",argumentCallback:s=>s-1}),month:DY({values:d3s,defaultWidth:"wide"}),day:DY({values:u3s,defaultWidth:"wide"}),dayPeriod:DY({values:h3s,defaultWidth:"wide",formattingValues:m3s,defaultFormattingWidth:"wide"})};function RY(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)?g3s(o,h=>h.test(l)):x3s(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 x3s(s,t){for(const n in s)if(Object.prototype.hasOwnProperty.call(s,n)&&t(s[n]))return n}function g3s(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 v3s=/^(\d+)(th|st|nd|rd)?/i,b3s=/\d+/i,_3s={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},w3s={any:[/^b/i,/^(a|c)/i]},j3s={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},N3s={any:[/1/i,/2/i,/3/i,/4/i]},k3s={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},S3s={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]},C3s={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},A3s={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]},E3s={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},T3s={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}},M3s={ordinalNumber:y3s({matchPattern:v3s,parsePattern:b3s,valueCallback:s=>parseInt(s,10)}),era:RY({matchPatterns:_3s,defaultMatchWidth:"wide",parsePatterns:w3s,defaultParseWidth:"any"}),quarter:RY({matchPatterns:j3s,defaultMatchWidth:"wide",parsePatterns:N3s,defaultParseWidth:"any",valueCallback:s=>s+1}),month:RY({matchPatterns:k3s,defaultMatchWidth:"wide",parsePatterns:S3s,defaultParseWidth:"any"}),day:RY({matchPatterns:C3s,defaultMatchWidth:"wide",parsePatterns:A3s,defaultParseWidth:"any"}),dayPeriod:RY({matchPatterns:E3s,defaultMatchWidth:"any",parsePatterns:T3s,defaultParseWidth:"any"})},yPe={code:"en-US",formatDistance:t3s,formatLong:a3s,formatRelative:o3s,localize:f3s,match:M3s,options:{weekStartsOn:0,firstWeekContainsDate:1}};function P3s(s){const t=po(s);return pv(t,$Qe(t))+1}function VQe(s){const t=po(s),n=+_E(t)-+UCs(t);return Math.round(n/UQe)+1}function HQe(s,t){var u,h,m,p;const n=po(s),r=n.getFullYear(),a=uL(),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=Bh(s,0);l.setFullYear(r+1,0,i),l.setHours(0,0,0,0);const o=v1(l,t),c=Bh(s,0);c.setFullYear(r,0,i),c.setHours(0,0,0,0);const d=v1(c,t);return n.getTime()>=o.getTime()?r+1:n.getTime()>=d.getTime()?r:r-1}function L3s(s,t){var o,c,d,u;const n=uL(),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=HQe(s,t),i=Bh(s,0);return i.setFullYear(a,0,r),i.setHours(0,0,0,0),v1(i,t)}function GQe(s,t){const n=po(s),r=+v1(n,t)-+L3s(n,t);return Math.round(r/UQe)+1}function Rh(s,t){const n=s<0?"-":"",r=Math.abs(s).toString().padStart(t,"0");return n+r}const bT={y(s,t){const n=s.getFullYear(),r=n>0?n:1-n;return Rh(t==="yy"?r%100:r,t.length)},M(s,t){const n=s.getMonth();return t==="M"?String(n+1):Rh(n+1,2)},d(s,t){return Rh(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 Rh(s.getHours()%12||12,t.length)},H(s,t){return Rh(s.getHours(),t.length)},m(s,t){return Rh(s.getMinutes(),t.length)},s(s,t){return Rh(s.getSeconds(),t.length)},S(s,t){const n=t.length,r=s.getMilliseconds(),a=Math.trunc(r*Math.pow(10,n-3));return Rh(a,t.length)}},vB={am:"am",pm:"pm",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},Ppt={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 bT.y(s,t)},Y:function(s,t,n,r){const a=HQe(s,r),i=a>0?a:1-a;if(t==="YY"){const l=i%100;return Rh(l,2)}return t==="Yo"?n.ordinalNumber(i,{unit:"year"}):Rh(i,t.length)},R:function(s,t){const n=YDt(s);return Rh(n,t.length)},u:function(s,t){const n=s.getFullYear();return Rh(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 Rh(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 Rh(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 bT.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 Rh(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=GQe(s,r);return t==="wo"?n.ordinalNumber(a,{unit:"week"}):Rh(a,t.length)},I:function(s,t,n){const r=VQe(s);return t==="Io"?n.ordinalNumber(r,{unit:"week"}):Rh(r,t.length)},d:function(s,t,n){return t==="do"?n.ordinalNumber(s.getDate(),{unit:"date"}):bT.d(s,t)},D:function(s,t,n){const r=P3s(s);return t==="Do"?n.ordinalNumber(r,{unit:"dayOfYear"}):Rh(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 Rh(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 Rh(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 Rh(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=vB.noon:r===0?a=vB.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=vB.evening:r>=12?a=vB.afternoon:r>=4?a=vB.morning:a=vB.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 bT.h(s,t)},H:function(s,t,n){return t==="Ho"?n.ordinalNumber(s.getHours(),{unit:"hour"}):bT.H(s,t)},K:function(s,t,n){const r=s.getHours()%12;return t==="Ko"?n.ordinalNumber(r,{unit:"hour"}):Rh(r,t.length)},k:function(s,t,n){let r=s.getHours();return r===0&&(r=24),t==="ko"?n.ordinalNumber(r,{unit:"hour"}):Rh(r,t.length)},m:function(s,t,n){return t==="mo"?n.ordinalNumber(s.getMinutes(),{unit:"minute"}):bT.m(s,t)},s:function(s,t,n){return t==="so"?n.ordinalNumber(s.getSeconds(),{unit:"second"}):bT.s(s,t)},S:function(s,t){return bT.S(s,t)},X:function(s,t,n){const r=s.getTimezoneOffset();if(r===0)return"Z";switch(t){case"X":return Ipt(r);case"XXXX":case"XX":return OR(r);case"XXXXX":case"XXX":default:return OR(r,":")}},x:function(s,t,n){const r=s.getTimezoneOffset();switch(t){case"x":return Ipt(r);case"xxxx":case"xx":return OR(r);case"xxxxx":case"xxx":default:return OR(r,":")}},O:function(s,t,n){const r=s.getTimezoneOffset();switch(t){case"O":case"OO":case"OOO":return"GMT"+Lpt(r,":");case"OOOO":default:return"GMT"+OR(r,":")}},z:function(s,t,n){const r=s.getTimezoneOffset();switch(t){case"z":case"zz":case"zzz":return"GMT"+Lpt(r,":");case"zzzz":default:return"GMT"+OR(r,":")}},t:function(s,t,n){const r=Math.trunc(s.getTime()/1e3);return Rh(r,t.length)},T:function(s,t,n){const r=s.getTime();return Rh(r,t.length)}};function Lpt(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+Rh(i,2)}function Ipt(s,t){return s%60===0?(s>0?"-":"+")+Rh(Math.abs(s)/60,2):OR(s,t)}function OR(s,t=""){const n=s>0?"-":"+",r=Math.abs(s),a=Rh(Math.trunc(r/60),2),i=Rh(r%60,2);return n+a+t+i}const Dpt=(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"})}},XDt=(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"})}},I3s=(s,t)=>{const n=s.match(/(P+)(p+)?/)||[],r=n[1],a=n[2];if(!a)return Dpt(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}}",Dpt(r,t)).replace("{{time}}",XDt(a,t))},D$e={p:XDt,P:I3s},D3s=/^D+$/,R3s=/^Y+$/,F3s=["D","DD","YY","YYYY"];function QDt(s){return D3s.test(s)}function JDt(s){return R3s.test(s)}function R$e(s,t,n){const r=O3s(s,t,n);if(console.warn(r),F3s.includes(s))throw new RangeError(r)}function O3s(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 z3s=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,B3s=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,U3s=/^'([^]*?)'?$/,q3s=/''/g,$3s=/[a-zA-Z]/;function Hs(s,t,n){var u,h,m,p,f,y,v,g;const r=uL(),a=(n==null?void 0:n.locale)??r.locale??yPe,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)??((y=(f=n==null?void 0:n.locale)==null?void 0:f.options)==null?void 0:y.weekStartsOn)??r.weekStartsOn??((g=(v=r.locale)==null?void 0:v.options)==null?void 0:g.weekStartsOn)??0,o=po(s);if(!I$e(o))throw new RangeError("Invalid time value");let c=t.match(B3s).map(b=>{const j=b[0];if(j==="p"||j==="P"){const S=D$e[j];return S(b,a.formatLong)}return b}).join("").match(z3s).map(b=>{if(b==="''")return{isToken:!1,value:"'"};const j=b[0];if(j==="'")return{isToken:!1,value:V3s(b)};if(Ppt[j])return{isToken:!0,value:b};if(j.match($3s))throw new RangeError("Format string contains an unescaped latin alphabet character `"+j+"`");return{isToken:!1,value:b}});a.localize.preprocessor&&(c=a.localize.preprocessor(o,c));const d={firstWeekContainsDate:i,weekStartsOn:l,locale:a};return c.map(b=>{if(!b.isToken)return b.value;const j=b.value;(!(n!=null&&n.useAdditionalWeekYearTokens)&&JDt(j)||!(n!=null&&n.useAdditionalDayOfYearTokens)&&QDt(j))&&R$e(j,t,String(s));const S=Ppt[j[0]];return S(o,j,a.localize,d)}).join("")}function V3s(s){const t=s.match(U3s);return t?t[1].replace(q3s,"'"):s}function H3s(s,t,n){const r=uL(),a=(n==null?void 0:n.locale)??r.locale??yPe,i=2520,l=_4e(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=po(t),d=po(s)):(c=po(s),d=po(t));const u=XCs(d,c),h=(LP(d)-LP(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 yS(s,t){const n=po(s),r=po(t);return+n<+r}function Q3s(s){return+po(s)>Date.now()}function J3s(s,t){const n=t instanceof Date?Bh(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 eAs=10;class eRt{constructor(){Pr(this,"subPriority",0)}validate(t,n){return!0}}class tAs extends eRt{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 sAs extends eRt{constructor(){super(...arguments);Pr(this,"priority",eAs);Pr(this,"subPriority",-1)}set(n,r){return r.timestampIsSet?n:Bh(n,J3s(n,Date))}}class uh{run(t,n,r,a){const i=this.parse(t,n,r,a);return i?{setter:new tAs(i.value,this.validate,this.set,this.priority,this.subPriority),rest:i.rest}:null}validate(t,n,r){return!0}}class nAs extends uh{constructor(){super(...arguments);Pr(this,"priority",140);Pr(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 og={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}/},w4={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 lg(s,t){return s&&{value:t(s.value),rest:s.rest}}function Lf(s,t){const n=t.match(s);return n?{value:parseInt(n[0],10),rest:t.slice(n[0].length)}:null}function j4(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*fPe+i*pPe+l*zCs),rest:t.slice(n[0].length)}}function tRt(s){return Lf(og.anyDigitsSigned,s)}function Px(s,t){switch(s){case 1:return Lf(og.singleDigit,t);case 2:return Lf(og.twoDigits,t);case 3:return Lf(og.threeDigits,t);case 4:return Lf(og.fourDigits,t);default:return Lf(new RegExp("^\\d{1,"+s+"}"),t)}}function dAe(s,t){switch(s){case 1:return Lf(og.singleDigitSigned,t);case 2:return Lf(og.twoDigitsSigned,t);case 3:return Lf(og.threeDigitsSigned,t);case 4:return Lf(og.fourDigitsSigned,t);default:return Lf(new RegExp("^-?\\d{1,"+s+"}"),t)}}function WQe(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 sRt(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 nRt(s){return s%400===0||s%4===0&&s%100!==0}class rAs extends uh{constructor(){super(...arguments);Pr(this,"priority",130);Pr(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 lg(Px(4,n),i);case"yo":return lg(a.ordinalNumber(n,{unit:"year"}),i);default:return lg(Px(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=sRt(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 aAs extends uh{constructor(){super(...arguments);Pr(this,"priority",130);Pr(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 lg(Px(4,n),i);case"Yo":return lg(a.ordinalNumber(n,{unit:"year"}),i);default:return lg(Px(r.length,n),i)}}validate(n,r){return r.isTwoDigitYear||r.year>0}set(n,r,a,i){const l=HQe(n,i);if(a.isTwoDigitYear){const c=sRt(a.year,l);return n.setFullYear(c,0,i.firstWeekContainsDate),n.setHours(0,0,0,0),v1(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),v1(n,i)}}class iAs extends uh{constructor(){super(...arguments);Pr(this,"priority",130);Pr(this,"incompatibleTokens",["G","y","Y","u","Q","q","M","L","w","d","D","e","c","t","T"])}parse(n,r){return dAe(r==="R"?4:r.length,n)}set(n,r,a){const i=Bh(n,0);return i.setFullYear(a,0,4),i.setHours(0,0,0,0),_E(i)}}class oAs extends uh{constructor(){super(...arguments);Pr(this,"priority",130);Pr(this,"incompatibleTokens",["G","y","Y","R","w","I","i","e","c","t","T"])}parse(n,r){return dAe(r==="u"?4:r.length,n)}set(n,r,a){return n.setFullYear(a,0,1),n.setHours(0,0,0,0),n}}class lAs extends uh{constructor(){super(...arguments);Pr(this,"priority",120);Pr(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 Px(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 cAs extends uh{constructor(){super(...arguments);Pr(this,"priority",120);Pr(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 Px(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 dAs extends uh{constructor(){super(...arguments);Pr(this,"incompatibleTokens",["Y","R","q","Q","L","w","I","D","i","e","c","t","T"]);Pr(this,"priority",110)}parse(n,r,a){const i=l=>l-1;switch(r){case"M":return lg(Lf(og.month,n),i);case"MM":return lg(Px(2,n),i);case"Mo":return lg(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 uAs extends uh{constructor(){super(...arguments);Pr(this,"priority",110);Pr(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 lg(Lf(og.month,n),i);case"LL":return lg(Px(2,n),i);case"Lo":return lg(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 hAs(s,t,n){const r=po(s),a=GQe(r,n)-t;return r.setDate(r.getDate()-a*7),r}class mAs extends uh{constructor(){super(...arguments);Pr(this,"priority",100);Pr(this,"incompatibleTokens",["y","R","u","q","Q","M","L","I","d","D","i","t","T"])}parse(n,r,a){switch(r){case"w":return Lf(og.week,n);case"wo":return a.ordinalNumber(n,{unit:"week"});default:return Px(r.length,n)}}validate(n,r){return r>=1&&r<=53}set(n,r,a,i){return v1(hAs(n,a,i),i)}}function pAs(s,t){const n=po(s),r=VQe(n)-t;return n.setDate(n.getDate()-r*7),n}class fAs extends uh{constructor(){super(...arguments);Pr(this,"priority",100);Pr(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 Lf(og.week,n);case"Io":return a.ordinalNumber(n,{unit:"week"});default:return Px(r.length,n)}}validate(n,r){return r>=1&&r<=53}set(n,r,a){return _E(pAs(n,a))}}const xAs=[31,28,31,30,31,30,31,31,30,31,30,31],gAs=[31,29,31,30,31,30,31,31,30,31,30,31];class yAs extends uh{constructor(){super(...arguments);Pr(this,"priority",90);Pr(this,"subPriority",1);Pr(this,"incompatibleTokens",["Y","R","q","Q","w","I","D","i","e","c","t","T"])}parse(n,r,a){switch(r){case"d":return Lf(og.date,n);case"do":return a.ordinalNumber(n,{unit:"date"});default:return Px(r.length,n)}}validate(n,r){const a=n.getFullYear(),i=nRt(a),l=n.getMonth();return i?r>=1&&r<=gAs[l]:r>=1&&r<=xAs[l]}set(n,r,a){return n.setDate(a),n.setHours(0,0,0,0),n}}class vAs extends uh{constructor(){super(...arguments);Pr(this,"priority",90);Pr(this,"subpriority",1);Pr(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 Lf(og.dayOfYear,n);case"Do":return a.ordinalNumber(n,{unit:"date"});default:return Px(r.length,n)}}validate(n,r){const a=n.getFullYear();return nRt(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 KQe(s,t,n){var h,m,p,f;const r=uL(),a=(n==null?void 0:n.weekStartsOn)??((m=(h=n==null?void 0:n.locale)==null?void 0:h.options)==null?void 0:m.weekStartsOn)??r.weekStartsOn??((f=(p=r.locale)==null?void 0:p.options)==null?void 0:f.weekStartsOn)??0,i=po(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 zh(i,u)}class bAs extends uh{constructor(){super(...arguments);Pr(this,"priority",90);Pr(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=KQe(n,a,i),n.setHours(0,0,0,0),n}}class _As extends uh{constructor(){super(...arguments);Pr(this,"priority",90);Pr(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 lg(Px(r.length,n),l);case"eo":return lg(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=KQe(n,a,i),n.setHours(0,0,0,0),n}}class wAs extends uh{constructor(){super(...arguments);Pr(this,"priority",90);Pr(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 lg(Px(r.length,n),l);case"co":return lg(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=KQe(n,a,i),n.setHours(0,0,0,0),n}}function jAs(s,t){const n=po(s),r=K3s(n),a=t-r;return zh(n,a)}class NAs extends uh{constructor(){super(...arguments);Pr(this,"priority",90);Pr(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 Px(r.length,n);case"io":return a.ordinalNumber(n,{unit:"day"});case"iii":return lg(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 lg(a.day(n,{width:"narrow",context:"formatting"}),i);case"iiiiii":return lg(a.day(n,{width:"short",context:"formatting"})||a.day(n,{width:"narrow",context:"formatting"}),i);case"iiii":default:return lg(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=jAs(n,a),n.setHours(0,0,0,0),n}}class kAs extends uh{constructor(){super(...arguments);Pr(this,"priority",80);Pr(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(WQe(a),0,0,0),n}}class SAs extends uh{constructor(){super(...arguments);Pr(this,"priority",80);Pr(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(WQe(a),0,0,0),n}}class CAs extends uh{constructor(){super(...arguments);Pr(this,"priority",80);Pr(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(WQe(a),0,0,0),n}}class AAs extends uh{constructor(){super(...arguments);Pr(this,"priority",70);Pr(this,"incompatibleTokens",["H","K","k","t","T"])}parse(n,r,a){switch(r){case"h":return Lf(og.hour12h,n);case"ho":return a.ordinalNumber(n,{unit:"hour"});default:return Px(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 EAs extends uh{constructor(){super(...arguments);Pr(this,"priority",70);Pr(this,"incompatibleTokens",["a","b","h","K","k","t","T"])}parse(n,r,a){switch(r){case"H":return Lf(og.hour23h,n);case"Ho":return a.ordinalNumber(n,{unit:"hour"});default:return Px(r.length,n)}}validate(n,r){return r>=0&&r<=23}set(n,r,a){return n.setHours(a,0,0,0),n}}class TAs extends uh{constructor(){super(...arguments);Pr(this,"priority",70);Pr(this,"incompatibleTokens",["h","H","k","t","T"])}parse(n,r,a){switch(r){case"K":return Lf(og.hour11h,n);case"Ko":return a.ordinalNumber(n,{unit:"hour"});default:return Px(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 MAs extends uh{constructor(){super(...arguments);Pr(this,"priority",70);Pr(this,"incompatibleTokens",["a","b","h","H","K","t","T"])}parse(n,r,a){switch(r){case"k":return Lf(og.hour24h,n);case"ko":return a.ordinalNumber(n,{unit:"hour"});default:return Px(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 PAs extends uh{constructor(){super(...arguments);Pr(this,"priority",60);Pr(this,"incompatibleTokens",["t","T"])}parse(n,r,a){switch(r){case"m":return Lf(og.minute,n);case"mo":return a.ordinalNumber(n,{unit:"minute"});default:return Px(r.length,n)}}validate(n,r){return r>=0&&r<=59}set(n,r,a){return n.setMinutes(a,0,0),n}}class LAs extends uh{constructor(){super(...arguments);Pr(this,"priority",50);Pr(this,"incompatibleTokens",["t","T"])}parse(n,r,a){switch(r){case"s":return Lf(og.second,n);case"so":return a.ordinalNumber(n,{unit:"second"});default:return Px(r.length,n)}}validate(n,r){return r>=0&&r<=59}set(n,r,a){return n.setSeconds(a,0),n}}class IAs extends uh{constructor(){super(...arguments);Pr(this,"priority",30);Pr(this,"incompatibleTokens",["t","T"])}parse(n,r){const a=i=>Math.trunc(i*Math.pow(10,-r.length+3));return lg(Px(r.length,n),a)}set(n,r,a){return n.setMilliseconds(a),n}}class DAs extends uh{constructor(){super(...arguments);Pr(this,"priority",10);Pr(this,"incompatibleTokens",["t","T","x"])}parse(n,r){switch(r){case"X":return j4(w4.basicOptionalMinutes,n);case"XX":return j4(w4.basic,n);case"XXXX":return j4(w4.basicOptionalSeconds,n);case"XXXXX":return j4(w4.extendedOptionalSeconds,n);case"XXX":default:return j4(w4.extended,n)}}set(n,r,a){return r.timestampIsSet?n:Bh(n,n.getTime()-LP(n)-a)}}class RAs extends uh{constructor(){super(...arguments);Pr(this,"priority",10);Pr(this,"incompatibleTokens",["t","T","X"])}parse(n,r){switch(r){case"x":return j4(w4.basicOptionalMinutes,n);case"xx":return j4(w4.basic,n);case"xxxx":return j4(w4.basicOptionalSeconds,n);case"xxxxx":return j4(w4.extendedOptionalSeconds,n);case"xxx":default:return j4(w4.extended,n)}}set(n,r,a){return r.timestampIsSet?n:Bh(n,n.getTime()-LP(n)-a)}}class FAs extends uh{constructor(){super(...arguments);Pr(this,"priority",40);Pr(this,"incompatibleTokens","*")}parse(n){return tRt(n)}set(n,r,a){return[Bh(n,a*1e3),{timestampIsSet:!0}]}}class OAs extends uh{constructor(){super(...arguments);Pr(this,"priority",20);Pr(this,"incompatibleTokens","*")}parse(n){return tRt(n)}set(n,r,a){return[Bh(n,a),{timestampIsSet:!0}]}}const zAs={G:new nAs,y:new rAs,Y:new aAs,R:new iAs,u:new oAs,Q:new lAs,q:new cAs,M:new dAs,L:new uAs,w:new mAs,I:new fAs,d:new yAs,D:new vAs,E:new bAs,e:new _As,c:new wAs,i:new NAs,a:new kAs,b:new SAs,B:new CAs,h:new AAs,H:new EAs,K:new TAs,k:new MAs,m:new PAs,s:new LAs,S:new IAs,X:new DAs,x:new RAs,t:new FAs,T:new OAs},BAs=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,UAs=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,qAs=/^'([^]*?)'?$/,$As=/''/g,VAs=/\S/,HAs=/[a-zA-Z]/;function YQe(s,t,n,r){var y,v,g,b;const a=W3s(),i=a.locale??yPe,l=a.firstWeekContainsDate??((v=(y=a.locale)==null?void 0:y.options)==null?void 0:v.firstWeekContainsDate)??1,o=a.weekStartsOn??((b=(g=a.locale)==null?void 0:g.options)==null?void 0:b.weekStartsOn)??0;if(t==="")return s===""?po(n):Bh(n,NaN);const c={firstWeekContainsDate:l,weekStartsOn:o,locale:i},d=[new sAs],u=t.match(UAs).map(j=>{const S=j[0];if(S in D$e){const C=D$e[S];return C(j,i.formatLong)}return j}).join("").match(BAs),h=[];for(let j of u){JDt(j)&&R$e(j,t,s),QDt(j)&&R$e(j,t,s);const S=j[0],C=zAs[S];if(C){const{incompatibleTokens:E}=C;if(Array.isArray(E)){const M=h.find(I=>E.includes(I.token)||I.token===S);if(M)throw new RangeError(`The format string mustn't contain \`${M.fullToken}\` and \`${j}\` at the same time`)}else if(C.incompatibleTokens==="*"&&h.length>0)throw new RangeError(`The format string mustn't contain \`${j}\` and any other token at the same time`);h.push({token:S,fullToken:j});const P=C.run(s,j,i.match,c);if(!P)return Bh(n,NaN);d.push(P.setter),s=P.rest}else{if(S.match(HAs))throw new RangeError("Format string contains an unescaped latin alphabet character `"+S+"`");if(j==="''"?j="'":S==="'"&&(j=GAs(j)),s.indexOf(j)===0)s=s.slice(j.length);else return Bh(n,NaN)}}if(s.length>0&&VAs.test(s))return Bh(n,NaN);const m=d.map(j=>j.priority).sort((j,S)=>S-j).filter((j,S,C)=>C.indexOf(j)===S).map(j=>d.filter(S=>S.priority===j).sort((S,C)=>C.subPriority-S.subPriority)).map(j=>j[0]);let p=po(n);if(isNaN(p.getTime()))return Bh(n,NaN);const f={};for(const j of m){if(!j.validate(p,c))return Bh(n,NaN);const S=j.set(p,f,c);Array.isArray(S)?(p=S[0],Object.assign(f,S[1])):p=S}return Bh(n,p)}function GAs(s){return s.match(qAs)[1].replace($As,"'")}function X4(s){return+po(s)i-l);return n>=r&&n<=a}function w4e(s,t){return zh(s,-t)}function py(s,t){const r=eEs(s);let a;if(r.date){const c=tEs(r.date,2);a=sEs(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=nEs(r.time),isNaN(l)))return new Date(NaN);if(r.timezone){if(o=rEs(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 ple={dateTimeDelimiter:/[T ]/,timeZoneDelimiter:/[Z ]/i,timezone:/([Z+-].*)$/},XAs=/^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/,QAs=/^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/,JAs=/^([+-])(\d{2})(?::?(\d{2}))?$/;function eEs(s){const t={},n=s.split(ple.dateTimeDelimiter);let r;if(n.length>2)return t;if(/:/.test(n[0])?r=n[0]:(t.date=n[0],r=n[1],ple.timeZoneDelimiter.test(t.date)&&(t.date=s.split(ple.timeZoneDelimiter)[0],r=s.substr(t.date.length,s.length))),r){const a=ple.timezone.exec(r);a?(t.time=r.replace(a[1],""),t.timezone=a[1]):t.time=r}return t}function tEs(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 sEs(s,t){if(t===null)return new Date(NaN);const n=s.match(XAs);if(!n)return new Date(NaN);const r=!!n[4],a=FY(n[1]),i=FY(n[2])-1,l=FY(n[3]),o=FY(n[4]),c=FY(n[5])-1;if(r)return cEs(t,o,c)?aEs(t,o,c):new Date(NaN);{const d=new Date(0);return!oEs(t,i,l)||!lEs(t,a)?new Date(NaN):(d.setUTCFullYear(t,i,Math.max(a,l)),d)}}function FY(s){return s?parseInt(s):1}function nEs(s){const t=s.match(QAs);if(!t)return NaN;const n=mOe(t[1]),r=mOe(t[2]),a=mOe(t[3]);return dEs(n,r,a)?n*fPe+r*pPe+a*1e3:NaN}function mOe(s){return s&&parseFloat(s.replace(",","."))||0}function rEs(s){if(s==="Z")return 0;const t=s.match(JAs);if(!t)return 0;const n=t[1]==="+"?-1:1,r=parseInt(t[2]),a=t[3]&&parseInt(t[3])||0;return uEs(r,a)?n*(r*fPe+a*pPe):NaN}function aEs(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 iEs=[31,null,31,30,31,30,31,31,30,31,30,31];function rRt(s){return s%400===0||s%4===0&&s%100!==0}function oEs(s,t,n){return t>=0&&t<=11&&n>=1&&n<=(iEs[t]||(rRt(s)?29:28))}function lEs(s,t){return t>=1&&t<=(rRt(s)?366:365)}function cEs(s,t,n){return t>=1&&t<=53&&n>=0&&n<=6}function dEs(s,t,n){return s===24?t===0&&n===0:n>=0&&n<60&&t>=0&&t<60&&s>=0&&s<25}function uEs(s,t){return t>=0&&t<=59}function pOe(s,t){const n=po(s),r=n.getFullYear(),a=n.getDate(),i=Bh(s,0);i.setFullYear(r,t,15),i.setHours(0,0,0,0);const l=G3s(i);return n.setMonth(t,Math.min(a,l)),n}function aRt(s,t){const n=po(s);return n.setHours(t),n}function iRt(s,t){const n=po(s);return n.setMinutes(t),n}function Fpt(s,t){const n=po(s);return isNaN(+n)?Bh(s,NaN):(n.setFullYear(t),n)}function hF(s,t){return Cy(s,-t)}const hEs=()=>{const{user:s}=hs(),t=Fn(),[n,r]=_.useState([]),[a,i]=_.useState(0),[l,o]=_.useState(!1),[c,d]=_.useState(null),u=_.useRef(null);_.useEffect(()=>{u.current=c},[c]),_.useEffect(()=>{if(!s)return;const y=`notification_last_read_${s.id}`,v=localStorage.getItem(y);v&&!u.current&&(u.current=v,d(v));const g=`nb_cache_${s.id}`,b=60*1e3,j=async()=>{try{const M=sessionStorage.getItem(g);if(M){const I=JSON.parse(M);if(I.ts&&Date.now()-I.ts{r(E);const P=u.current?new Date(u.current):null,M=E.filter(I=>P?new Date(I.created_at)>P:!0);i(M.length)};j();const C=q.channel("push-notifications").on("postgres_changes",{event:"INSERT",schema:"public",table:"push_notifications"},E=>{const P=E.new;r(I=>{const D=[P,...I].slice(0,20);try{sessionStorage.setItem(g,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()=>{q.removeChannel(C)}},[s]);const h=y=>{const v=y.toLowerCase();return v.includes("community")||v.includes("post")?Hi:v.includes("academy")||v.includes("video")?Kr:v.includes("template")?Xc:v.includes("event")?ga:v.includes("newsletter")?mN:v.includes("brokerage")?Cx:v.includes("swag")||v.includes("social")?Vo:v.includes("toolbox")||v.includes("tool")?Y4:v.includes("brief")?un:Hi},m=y=>{o(!1),y.url&&y.url!=="/"&&t(y.url)},p=()=>{if(!s)return;const y=new Date().toISOString(),v=`notification_last_read_${s.id}`;localStorage.setItem(v,y),d(y),i(0)},f=y=>{o(y),y&&a>0&&p()};return e.jsxs(tu,{open:l,onOpenChange:f,children:[e.jsx(su,{asChild:!0,children:e.jsxs(B,{variant:"ghost",size:"icon",className:"relative",children:[e.jsx(Rg,{className:"h-5 w-5"}),a>0&&e.jsx(Oe,{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(Od,{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(B,{variant:"ghost",size:"sm",className:"text-xs h-6",onClick:p,children:"Mark all read"})]}),e.jsx(Ji,{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(y=>{const v=h(y.title);return e.jsxs(ca,{className:"group flex items-start gap-3 p-3 cursor-pointer data-[highlighted]:bg-accent data-[highlighted]:text-accent-foreground",onClick:()=>m(y),children:[e.jsx("div",{className:"flex-shrink-0 mt-0.5",children:e.jsx(v,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"flex flex-col gap-1 min-w-0",children:[e.jsx("span",{className:"font-medium text-sm",children:y.title}),e.jsx("span",{className:"text-xs text-muted-foreground line-clamp-2 group-data-[highlighted]:text-accent-foreground/80",children:y.body}),e.jsx("span",{className:"text-xs text-muted-foreground group-data-[highlighted]:text-accent-foreground/80",children:Ed(new Date(y.created_at),{addSuffix:!0})})]})]},y.id)})})]})]})};function mEs(s){return s!=null&&s.length?s.find(t=>t.is_active&&t.mls_provider_id&&!t.no_mls_mode)||s[0]:null}function lf(){const{user:s}=hs(),{data:t,isLoading:n}=at({queryKey:["agent-lead-site",s==null?void 0:s.id],queryFn:async()=>{const{data:r,error:a}=await q.from("lead_sites").select("id, subdomain_slug, custom_domain, site_title, is_active, plan_tier, mls_provider_id, no_mls_mode, mls_agent_id, mls_agent_key, mls_office_id, mls_service_cities, mls_disclaimer_text, brokerage_legal_name").eq("agent_id",s.id).eq("is_active",!0).order("created_at",{ascending:!0}).limit(10);if(a)throw a;return mEs(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 vPe(s=!0){const{user:t}=hs(),{data:n,isLoading:r}=at({queryKey:["free-lead-site-offer",t==null?void 0:t.id],enabled:!!t&&s,staleTime:5*60*1e3,queryFn:async()=>{const{data:a}=await q.from("profiles").select("brokerage_id").eq("id",t.id).maybeSingle();if(!(a!=null&&a.brokerage_id))return null;const{data:i}=await q.from("lead_site_brokerage_offers").select("*").eq("brokerage_id",a.brokerage_id).eq("enabled",!0).maybeSingle();return i??null}});return{offer:n??null,hasOffer:!!n,isLoading:r}}const pEs="coaching_access";function oRt(){const{user:s,loading:t,isAdmin:n,isCoach:r}=hs(),{data:a,isLoading:i}=at({queryKey:["coaching-access",s==null?void 0:s.id],enabled:!!s,staleTime:5*60*1e3,queryFn:async()=>{const[l,o]=await Promise.all([q.from("coaching_assignments").select("id").eq("agent_id",s.id).eq("status","active").limit(1),q.from("feature_entitlements").select("enabled, expires_at").eq("user_id",s.id).eq("feature_key",pEs).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 Zd=q,uAe=[{value:"contract",label:"Under contract"},{value:"inspection",label:"Inspection / due diligence"},{value:"closing",label:"Closing"},{value:"closed",label:"Closed"}];function F$e(s){return s.total_items===0?"not_started":s.rejected_items>0?"changes_requested":s.approved_items>=s.total_items?"compliant":"in_review"}const lRt={not_started:"Not started",in_review:"In review",changes_requested:"Changes requested",compliant:"Compliant"};function ZQe(){return at({queryKey:["transaction-admin-seats"],queryFn:async()=>{const{data:s}=await q.auth.getUser();if(!s.user)return[];const{data:t,error:n}=await Zd.from("brokerage_transaction_admins").select("brokerage_id").eq("user_id",s.user.id);if(n)throw n;return t||[]}})}function fEs(s){return at({queryKey:["transaction-admins",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await Zd.from("brokerage_transaction_admins").select("id, user_id, created_at").eq("brokerage_id",s);if(n)throw n;const r=t||[];if(r.length===0)return[];const{data:a}=await Zd.from("profiles").select("id, name, email").in("id",r.map(l=>l.user_id)),i=new Map((a||[]).map(l=>[l.id,{name:l.name??null,email:l.email??null}]));return r.map(l=>{var o,c;return{...l,name:((o=i.get(l.user_id))==null?void 0:o.name)??null,email:((c=i.get(l.user_id))==null?void 0:c.email)??null}})}})}function xEs(){const s=Bt();return mt({mutationFn:async({brokerageId:t,userId:n})=>{const{error:r}=await Zd.from("brokerage_transaction_admins").insert({brokerage_id:t,user_id:n});if(r)throw r},onSuccess:(t,n)=>s.invalidateQueries({queryKey:["transaction-admins",n.brokerageId]})})}function gEs(){const s=Bt();return mt({mutationFn:async({id:t})=>{const{error:n}=await Zd.from("brokerage_transaction_admins").delete().eq("id",t);if(n)throw n},onSuccess:(t,n)=>s.invalidateQueries({queryKey:["transaction-admins",n.brokerageId]})})}function yEs(s){return at({queryKey:["compliance-settings",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await Zd.from("brokerage_compliance_settings").select("*").eq("brokerage_id",s).maybeSingle();if(n)throw n;return t}})}function vEs(){const s=Bt();return mt({mutationFn:async t=>{const{error:n}=await Zd.from("brokerage_compliance_settings").upsert(t,{onConflict:"brokerage_id"});if(n)throw n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["compliance-settings",n.brokerage_id]}),s.invalidateQueries({queryKey:["compliance-deals"]})}})}function cRt(s){return at({queryKey:["compliance-templates",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await Zd.from("brokerage_checklist_templates").select("*").eq("brokerage_id",s).order("created_at",{ascending:!0});if(n)throw n;return t||[]}})}function bEs(s){return at({queryKey:["compliance-template-items",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await Zd.from("brokerage_checklist_template_items").select("*").eq("template_id",s).order("sort_order",{ascending:!0});if(n)throw n;return t||[]}})}function _Es(){const s=Bt();return mt({mutationFn:async t=>{if(t.id){const{error:a}=await Zd.from("brokerage_checklist_templates").update(t).eq("id",t.id);if(a)throw a;return t.id}const{data:n,error:r}=await Zd.from("brokerage_checklist_templates").insert(t).select("id").single();if(r)throw r;return n.id},onSuccess:(t,n)=>s.invalidateQueries({queryKey:["compliance-templates",n.brokerage_id]})})}function wEs(){const s=Bt();return mt({mutationFn:async({id:t})=>{const{error:n}=await Zd.from("brokerage_checklist_templates").delete().eq("id",t);if(n)throw n},onSuccess:(t,n)=>s.invalidateQueries({queryKey:["compliance-templates",n.brokerageId]})})}function jEs(){const s=Bt();return mt({mutationFn:async t=>{if(t.id){const{error:r}=await Zd.from("brokerage_checklist_template_items").update(t).eq("id",t.id);if(r)throw r;return}const{error:n}=await Zd.from("brokerage_checklist_template_items").insert(t);if(n)throw n},onSuccess:(t,n)=>s.invalidateQueries({queryKey:["compliance-template-items",n.template_id]})})}function NEs(){const s=Bt();return mt({mutationFn:async({id:t})=>{const{error:n}=await Zd.from("brokerage_checklist_template_items").delete().eq("id",t);if(n)throw n},onSuccess:(t,n)=>s.invalidateQueries({queryKey:["compliance-template-items",n.templateId]})})}function XQe(s){return at({queryKey:["compliance-deals",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await Zd.rpc("get_brokerage_compliance_deals",{_brokerage_id:s});if(n)throw n;return t||[]}})}function dRt(s){return at({queryKey:["deal-compliance-items",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await Zd.from("deal_compliance_items").select("*").eq("deal_id",s).order("sort_order",{ascending:!0});if(n)throw n;return t||[]}})}function kEs(s){return at({queryKey:["deal-compliance-events",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await Zd.from("deal_compliance_events").select("*").eq("deal_id",s).order("created_at",{ascending:!1}).limit(200);if(n)throw n;return t||[]}})}async function bPe(s){var n;const{data:t}=await q.auth.getUser();await Zd.from("deal_compliance_events").insert({deal_id:s.dealId,brokerage_id:s.brokerageId??null,item_id:s.itemId??null,actor_user_id:((n=t.user)==null?void 0:n.id)??null,event_type:s.eventType,detail:s.detail??null})}function SEs(){const s=Bt();return mt({mutationFn:async({item:t,status:n,note:r})=>{var l;const{data:a}=await q.auth.getUser(),{error:i}=await Zd.from("deal_compliance_items").update({status:n,review_note:r??null,reviewed_by:((l=a.user)==null?void 0:l.id)??null,reviewed_at:new Date().toISOString()}).eq("id",t.id);if(i)throw i;await bPe({dealId:t.deal_id,brokerageId:t.brokerage_id,itemId:t.id,eventType:n==="approved"?"item_approved":n==="rejected"?"item_rejected":"item_updated",detail:r?`${t.title}: ${r}`:t.title})},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["deal-compliance-items",n.item.deal_id]}),s.invalidateQueries({queryKey:["deal-compliance-events",n.item.deal_id]}),s.invalidateQueries({queryKey:["compliance-deals"]})}})}function CEs(){const s=Bt();return mt({mutationFn:async({dealId:t,brokerageId:n,templateId:r,deal:a})=>{const{data:i,error:l}=await Zd.from("brokerage_checklist_template_items").select("*").eq("template_id",r).order("sort_order",{ascending:!0});if(l)throw l;const o=(u,h)=>{if(!u)return null;const[m,p,f]=u.split(/[-/T]/).map(Number);return new Date(Date.UTC(m,p-1,f+(h||0))).toISOString().slice(0,10)},c=(i||[]).map(u=>({deal_id:t,brokerage_id:n,template_item_id:u.id,title:u.title,description:u.description,phase:u.phase,requires_document:u.requires_document,required_for_closing:u.required_for_closing,due_date:u.due_anchor==="contract_date"?o(a==null?void 0:a.contract_date,u.due_offset_days):u.due_anchor==="target_close_date"?o(a==null?void 0:a.target_close_date,u.due_offset_days):null,sort_order:u.sort_order}));if(c.length===0)return;const{error:d}=await Zd.from("deal_compliance_items").insert(c);if(d)throw d;await bPe({dealId:t,brokerageId:n,eventType:"checklist_applied",detail:`${c.length} items added`})},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["deal-compliance-items",n.dealId]}),s.invalidateQueries({queryKey:["deal-compliance-events",n.dealId]}),s.invalidateQueries({queryKey:["compliance-deals"]})}})}function AEs(s){return at({queryKey:["deal-compliance-files",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await Zd.from("deal_files").select("id, deal_id, compliance_item_id, file_name, file_size, storage_path, version_no, is_current, created_at, owner_user_id").eq("deal_id",s).not("compliance_item_id","is",null).order("version_no",{ascending:!1});if(n)throw n;return t||[]}})}function EEs(){const s=Bt();return mt({mutationFn:async({item:t,file:n})=>{var h,m;const{data:r}=await q.auth.getUser(),a=(h=r.user)==null?void 0:h.id;if(!a)throw new Error("Not signed in");const{data:i}=await Zd.from("deal_files").select("id, version_no").eq("compliance_item_id",t.id).order("version_no",{ascending:!1}).limit(1),l=(((m=i==null?void 0:i[0])==null?void 0:m.version_no)||0)+1,o=n.name.split(".").pop(),c=`${a}/${t.deal_id}/${crypto.randomUUID()}.${o}`,{error:d}=await q.storage.from("deal-files").upload(c,n);if(d)throw d;i!=null&&i.length&&await Zd.from("deal_files").update({is_current:!1}).eq("compliance_item_id",t.id);const{error:u}=await Zd.from("deal_files").insert({deal_id:t.deal_id,owner_user_id:a,file_name:n.name,file_size:n.size,file_type:n.type||null,storage_path:c,compliance_item_id:t.id,version_no:l,is_current:!0});if(u)throw u;await Zd.from("deal_compliance_items").update({status:"submitted",review_note:null,reviewed_at:null,reviewed_by:null}).eq("id",t.id),await bPe({dealId:t.deal_id,brokerageId:t.brokerage_id,itemId:t.id,eventType:"document_uploaded",detail:`${t.title} — ${n.name} (v${l})`})},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["deal-compliance-files",n.item.deal_id]}),s.invalidateQueries({queryKey:["deal-compliance-items",n.item.deal_id]}),s.invalidateQueries({queryKey:["deal-compliance-events",n.item.deal_id]}),s.invalidateQueries({queryKey:["deal-files",n.item.deal_id]}),s.invalidateQueries({queryKey:["compliance-deals"]})}})}async function Opt(s){const{data:t,error:n}=await q.storage.from("deal-files").createSignedUrl(s,3600);if(n)throw n;window.open(t.signedUrl,"_blank","noopener,noreferrer")}function TEs(s){return at({queryKey:["deal-compliance-messages",s],enabled:!!s,refetchInterval:3e4,queryFn:async()=>{const{data:t,error:n}=await Zd.from("deal_compliance_messages").select("*").eq("deal_id",s).order("created_at",{ascending:!0});if(n)throw n;const r=t||[],a=Array.from(new Set(r.map(o=>o.sender_user_id)));if(a.length===0)return r;const{data:i}=await Zd.from("profiles").select("id, name").in("id",a),l=new Map((i||[]).map(o=>[o.id,o.name??null]));return r.map(o=>({...o,sender_name:l.get(o.sender_user_id)??null}))}})}function MEs(){const s=Bt();return mt({mutationFn:async({dealId:t,brokerageId:n,body:r,senderRole:a,itemId:i})=>{var u;const{data:l}=await q.auth.getUser(),o=(u=l.user)==null?void 0:u.id;if(!o)throw new Error("Not signed in");const{data:c,error:d}=await Zd.from("deal_compliance_messages").insert({deal_id:t,brokerage_id:n,sender_user_id:o,sender_role:a,item_id:i??null,body:r.trim()}).select("id").single();if(d)throw d;try{await q.functions.invoke("compliance-message-notify",{body:{messageId:c.id}})}catch(h){console.error("compliance message notify failed",h)}return c.id},onSuccess:(t,n)=>s.invalidateQueries({queryKey:["deal-compliance-messages",n.dealId]})})}function PEs(){const s=Bt();return mt({mutationFn:async({dealId:t,senderRole:n})=>{const{error:r}=await Zd.from("deal_compliance_messages").update({read_at:new Date().toISOString()}).eq("deal_id",t).neq("sender_role",n).is("read_at",null);if(r)throw r},onSuccess:(t,n)=>s.invalidateQueries({queryKey:["deal-compliance-messages",n.dealId]})})}function LEs(s){return at({queryKey:["brokerage-agent-roster",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await Zd.from("profiles").select("id, name, email, avatar_url").eq("brokerage_id",s).order("name",{ascending:!0});if(n)throw n;return t||[]}})}function IEs(s){return at({queryKey:["agent-pipeline-stages",s],enabled:!!s,queryFn:async()=>{const t=async()=>{const{data:r,error:a}=await Zd.from("deal_pipeline_stages").select("id, name, sort_order, default_probability").eq("owner_user_id",s).order("sort_order",{ascending:!0});if(a)throw a;return r||[]};let n=await t();if(n.length===0){const{error:r}=await Zd.rpc("initialize_deal_pipeline_stages",{p_user_id:s});r||(n=await t())}return n}})}function DEs(){const s=Bt();return mt({mutationFn:async t=>{const n=t.price!=null&&t.commissionPercentage!=null?Math.round(t.price*(t.commissionPercentage/100)*100)/100:null,{data:r,error:a}=await Zd.from("deal_pipeline").insert({owner_user_id:t.ownerUserId,deal_name:t.dealName.trim(),deal_type:t.dealType,stage_id:t.stageId,property_address:t.propertyAddress||null,city:t.city||null,state:t.state||null,zip_code:t.zipCode||null,contract_date:t.contractDate||null,target_close_date:t.targetCloseDate||null,actual_close_date:t.actualCloseDate||null,expected_price:t.price??null,sale_price:t.actualCloseDate?t.price??null:null,commission_percentage:t.commissionPercentage??null,expected_commission:n,notes:t.notes||null}).select("id").single();if(a)throw a;const i=r.id;try{await Zd.rpc("ensure_deal_compliance",{_deal_id:i})}catch(l){console.error("ensure_deal_compliance failed",l)}return await bPe({dealId:i,brokerageId:t.brokerageId,eventType:"deal_added_by_staff",detail:"Deal added by brokerage staff for the agent's pipeline"}),i},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["compliance-deals",n.brokerageId]}),s.invalidateQueries({queryKey:["deal-pipeline"]})}})}const _Pe=[{id:"home",label:"Home",icon:XM,route:"/dashboard",accent:"nav-home"},{id:"crm",label:"CRM",icon:Do,description:"Contacts and follow-up",accent:"nav-crm"},{id:"deals",label:"Deals",icon:mj,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:wh,description:"Content, email and video",accent:"nav-marketing"},{id:"websites",label:"Websites",icon:sl,description:"Your site and add-ons",accent:"nav-websites"},{id:"academy",label:"Learn",icon:mm,description:"Training, programs and coaching",accent:"nav-academy"},{id:"events",label:"Events",icon:d7,route:"/events",accent:"nav-events"},{id:"apps",label:"Apps",icon:Uw,route:"/apps",accent:"nav-apps"},{id:"team",label:"Team",icon:In,route:"/team",description:"Your team hub — production, pond and resources",accent:"nav-team",visible:s=>s.isOnTeam&&!s.isAdmin&&!s.isBrokerageManager},{id:"brokerage",label:"Brokerage",icon:Uq,description:"Your brokerage, teams and recruiting",accent:"nav-brokerage",visible:s=>!s.isAdmin&&(!!s.brokerageId||s.isBrokerageManager||s.isOnTeam)},{id:"more",label:"More",icon:ob,description:"Community, marketplace and help",accent:"nav-more"}],W1=s=>t=>t.hasPermission(s),REs=[{id:"mission-control",label:"Mission Control",route:"/mission-control",icon:V4,description:"Your daily relationship command center",primaryCategory:"crm",section:"Overview",visible:W1("contacts"),searchKeywords:["agent os","mission control","dashboard"],displayOrder:10},{id:"client-portals",label:"Client Portals",route:"/mission-control/client-portals",icon:un,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:In,description:"Every contact in your database",primaryCategory:"crm",section:"Contacts",visible:W1("contacts"),searchKeywords:["contacts","database","sphere","people"],displayOrder:30},{id:"relationship-report",label:"Relationship Report",route:"/mission-control/relationship-scorecard",icon:hm,description:"See who needs attention next",primaryCategory:"crm",section:"Contacts",visible:W1("contacts"),searchKeywords:["relationship","scorecard","report"],displayOrder:40},{id:"sphere-gaps",label:"Sphere Gaps",route:"/mission-control/sphere-gaps",icon:t$,description:"Find missing info across your sphere",primaryCategory:"crm",section:"Contacts",visible:W1("contacts"),searchKeywords:["gaps","missing data"],displayOrder:50},{id:"sent-emails",label:"Sent Emails",route:"/mission-control/sent-emails",icon:Or,description:"History of everything you have sent",primaryCategory:"crm",section:"Contacts",visible:W1("contacts"),searchKeywords:["sent","email history"],displayOrder:60},{id:"connect-page",label:"Connect Page",route:"/mission-control/connect-page",icon:vd,description:"Your shareable intake and link page",primaryCategory:"crm",section:"Contacts",visible:W1("contacts"),searchKeywords:["connect","link in bio","intake"],displayOrder:70},{id:"property-intelligence",label:"Property Intelligence",route:"/mission-control/property-intelligence",icon:ai,description:"Enrich property data for your contacts",primaryCategory:"crm",section:"Contacts",visible:s=>s.isAdmin,searchKeywords:["property","zillow","enrichment","intelligence","home value"],displayOrder:75},{id:"touchplans",label:"TouchPlans",route:"/mission-control/plans",icon:pc,description:"Structured touch plans for your people",primaryCategory:"crm",section:"Follow-Up",visible:W1("contacts"),searchKeywords:["touch plan","follow up plan"],displayOrder:80},{id:"smart-drips",label:"Smart Drips",route:"/mission-control/smart-drips",icon:nf,description:"Automated drip campaigns that pause when they reply",primaryCategory:"crm",section:"Follow-Up",badge:"beta",searchKeywords:["drip","automation","campaign"],displayOrder:90},{id:"email-templates",label:"Email Templates",route:"/email-campaigns/templates",icon:ln,description:"Reusable email templates",primaryCategory:"crm",section:"Follow-Up",searchKeywords:["email template"],displayOrder:100},{id:"signals",label:"Signals",route:"/mission-control/signals",icon:Zq,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:Vo,description:"Plan and log in-person pop-bys",primaryCategory:"crm",section:"Follow-Up",visible:W1("popbys"),searchKeywords:["pop by","gifts","drop off"],displayOrder:120},{id:"pipeline",label:"Deal Pipeline",route:"/mission-control/pipeline",icon:mj,description:"Track every deal from lead to close",primaryCategory:"deals",section:"Pipeline",visible:W1("pipeline"),searchKeywords:["pipeline","deals","kanban"],displayOrder:130},{id:"transactions",label:"Transactions",route:"/mission-control/transactions",icon:cN,description:"Closed and in-progress transactions",primaryCategory:"deals",section:"Pipeline",visible:W1("pipeline"),searchKeywords:["transactions","closings"],displayOrder:140},{id:"forms",label:"Forms Library",route:"/mission-control/forms",icon:lb,description:"Your PDF form templates, filled from any deal",primaryCategory:"deals",section:"Pipeline",visible:W1("pipeline"),searchKeywords:["forms","pdf","templates","contracts","documents"],displayOrder:145},{id:"tasks",label:"Tasks",route:"/mission-control/tasks",icon:Ww,description:"Everything on your plate today",primaryCategory:"deals",section:"Pipeline",visible:W1("pipeline"),searchKeywords:["tasks","to do"],displayOrder:150},{id:"scorecard",label:"Scorecard",route:"/mission-control/scorecard",icon:bl,description:"Your production numbers at a glance",primaryCategory:"deals",section:"Pipeline",visible:W1("scorecard"),searchKeywords:["scorecard","production","goals"],displayOrder:160},{id:"my-calendar",label:"My Calendar",route:"/mission-control/calendar",icon:pc,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:pc,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:W1("listings"),searchKeywords:["listings","exchange","my listings"],displayOrder:10},{id:"listing-presentation-studio",label:"Listing Presentation Studio",route:"/apps/listing-presentation-studio",icon:jv,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:gu,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:Jr,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:uj,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:cN,description:"Digital open house sign-in",primaryCategory:"listings",section:"Open Houses",toolId:"guest-book",searchKeywords:["open house","sign in","guest book"],displayOrder:60},{id:"listing-studio",label:"Listing Studio",route:"/mission-control/listing-studio",icon:hc,description:"Marketing assets for a listing",primaryCategory:"listings",section:"Market the Listing",toolId:"listing-studio",searchKeywords:["listing marketing","flyer","just listed"],displayOrder:70},{id:"templates",label:"Templates",route:"/templates",icon:Xc,description:"Ready-to-edit Canva templates",primaryCategory:"marketing",section:"Create",searchKeywords:["templates","canva","graphics"],displayOrder:10},{id:"staging-studio",label:"Staging Studio",route:"/apps/staging-studio",icon:n$,description:"Virtually stage, declutter and brighten listing photos",primaryCategory:"marketing",section:"Create",toolId:"staging-studio",visible:s=>s.isAdmin||s.stagingStudioEnabled,searchKeywords:["staging","virtual staging","twilight","declutter","sky replacement","photo"],displayOrder:11},{id:"marketing-studio",label:"Marketing Studio",route:"/marketing-studio",icon:hc,description:"Create branded marketing assets",primaryCategory:"marketing",section:"Create",searchKeywords:["marketing studio","design","brand kit"],displayOrder:20},{id:"social-studio",label:"Social Studio",route:"/social-studio",icon:p1,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:p1,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:dm,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:mN,description:"Send a branded monthly newsletter",primaryCategory:"marketing",section:"Email & Mail",badge:"new",toolId:"newsletter-pro",searchKeywords:["newsletter","email marketing"],displayOrder:50},{id:"mass-emails",label:"Mass Emails",route:"/admin/email-campaigns",icon:ln,description:"Email your whole database at once",primaryCategory:"marketing",section:"Email & Mail",toolId:"mass-emails",searchKeywords:["mass email","campaign","blast"],displayOrder:60},{id:"direct-mail",label:"Direct Mail",route:"/mission-control/direct-mail",icon:Or,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:Vo,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:Kr,description:"All of your recorded videos",primaryCategory:"marketing",section:"Video",visible:W1("videos"),searchKeywords:["videos","library"],displayOrder:90},{id:"quickvid",label:"QuickVid",route:"/mission-control/video/record",icon:Kr,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:dm,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:Sy,description:"Capture leads with focused landing pages",primaryCategory:"marketing",section:"Lead Capture",toolId:"landing-pages",searchKeywords:["landing page","lead capture","funnel"],displayOrder:120},{id:"buyer-match",label:"Buyer Match",route:"/mission-control/buyer-match",icon:wv,description:"Turn a buyer's wish list into seller conversations",primaryCategory:"marketing",section:"Lead Capture",searchKeywords:["buyer match","buyer needs","seller leads","wish list"],displayOrder:125},{id:"smart-card",label:"Smart Card",route:"/mission-control/my-card",icon:vd,description:"Your digital business card",primaryCategory:"marketing",section:"Lead Capture",toolId:"smart-card",searchKeywords:["digital card","business card","qr"],displayOrder:130},{id:"my-websites",label:"My Websites",route:"/websites",icon:sf,description:"Every site you can edit: yours, your company and your team",primaryCategory:"websites",section:"My Website",visible:s=>s.hasLeadSite||s.isBrokerageManager||s.isTeamLeader||s.isAdmin,searchKeywords:["websites","my sites","edit website","company site","team site"],displayOrder:1},{id:"get-my-website",label:"Get My Website",route:"/get-my-website",icon:sl,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:sl,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:ya,description:"Open your live website",primaryCategory:"websites",section:"My Website",external:!0,openInNewTab:!0,visible:s=>s.hasLeadSite&&!!s.siteUrl,searchKeywords:["view site","live site"],displayOrder:10},{id:"edit-website",label:"Edit My Site",route:s=>`/my-website/${s.leadSiteId}/edit`,icon: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:"brokerage-website",label:"Edit Company Site",route:"/brokerage/website",icon:ai,description:"Your company site: agents, listings, recruiting and leads",primaryCategory:"websites",section:"My Website",badge:"new",visible:s=>s.isBrokerageManager||s.isAdmin,searchKeywords:["website","company site","brokerage site","agents","roster"],displayOrder:24},{id:"team-website",label:"Edit Team Site",route:"/team/website",icon:In,description:"Your team site: members, listings and leads",primaryCategory:"websites",section:"My Website",badge:"new",visible:s=>s.isTeamLeader||s.isAdmin,searchKeywords:["team website","team site","team page"],displayOrder:26},{id:"mls-listings",label:"MLS Listings",route:"/my-website/mls-listings",icon:Jr,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:bl,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:hm,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:p1,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:un,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:mm,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:Sx,description:"On-demand training videos",primaryCategory:"academy",section:"Learn",searchKeywords:["academy","videos","training"],displayOrder:20},{id:"toolbox",label:"Toolbox",route:"/toolbox",icon:Y4,description:"Scripts, checklists and downloads",primaryCategory:"academy",section:"Learn",searchKeywords:["toolbox","scripts","downloads"],displayOrder:30},{id:"events",label:"Events",route:"/events",icon:d7,description:"Live trainings and member events",primaryCategory:"events",section:"Events",searchKeywords:["events","live","webinar"],displayOrder:10},{id:"programs",label:"Programs",route:"/programs",icon:Sy,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:mm,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:Do,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:Hi,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:mS,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:wr,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:r$,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:wl,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:Vo,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:qq,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:un,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:pN,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:pN,description:"Install the LevelUp Chrome extension",primaryCategory:"more",section:"Help & Services",searchKeywords:["extension","chrome"],displayOrder:100},{id:"attract",label:"LevelUp Attract",route:"/attract",icon:un,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:ec,description:"Manage members, content and settings",primaryCategory:"more",section:"Admin",visible:s=>s.isAdmin,searchKeywords:["admin"],displayOrder:120},{id:"agent-activation",label:"Agent Activation",route:"/admin/agent-activation",icon:nf,description:"Wake up dormant agents with branded email sequences",primaryCategory:"more",section:"Admin",visible:s=>s.isAdmin,searchKeywords:["activation","dormant","adoption","agents"],displayOrder:121},{id:"my-brokerage",label:"My Brokerage",route:"/my-brokerage",icon: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:x4,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:Sx,description:"Content shared by your brokerage",primaryCategory:"brokerage",section:"My Brokerage",visible:s=>!!s.brokerageId&&!s.isAdmin,searchKeywords:["brokerage content"],displayOrder:150},{id:"team-hub",label:"Team Hub",route:"/team",icon:In,description:"Production, leaderboard, pond and resources for your team",primaryCategory:"team",section:"My Team",searchKeywords:["team","leaderboard","production","team hub","standing"],displayOrder:155},{id:"my-team",label:"My Team",route:"/my-team",icon:In,description:"Your team roster and lead pond",primaryCategory:"brokerage",section:"My Team",visible:s=>s.isOnTeam&&!s.isBrokerageManager&&!s.isAdmin,searchKeywords:["team","lead pond"],displayOrder:160},{id:"manage-brokerages",label:"Manage Brokerages",route:"/brokerage/dashboard",icon:qc,description:"Brokerage manager dashboard",primaryCategory:"brokerage",section:"Manage Brokerage",visible:s=>s.isBrokerageManager&&!s.isAdmin,searchKeywords:["manage brokerage"],displayOrder:170},{id:"brokerage-teams",label:"Teams",route:"/brokerage/teams",icon:In,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:wh,description:"Recruit and nurture agents",primaryCategory:"brokerage",section:"Manage Brokerage",visible:s=>s.isBrokerageManager&&!s.isAdmin,searchKeywords:["recruiting"],displayOrder:190},{id:"brokerage-onboarding",label:"Agent Onboarding",route:"/brokerage/onboarding",icon:qf,description:"Onboarding checklists, documents and agent notes",primaryCategory:"brokerage",section:"Manage Brokerage",badge:"new",visible:s=>s.isBrokerageManager&&!s.isAdmin,searchKeywords:["onboarding","checklist","documents","new agent"],displayOrder:195},{id:"brokerage-operations",label:"Operations",route:"/brokerage/operations",icon:XM,description:"Daily action feed, office task board and brokerage calendar",primaryCategory:"brokerage",section:"Manage Brokerage",badge:"new",visible:s=>(s.isBrokerageManager||s.isTransactionAdmin)&&!s.isAdmin,searchKeywords:["operations","tasks","today","calendar","action items"],displayOrder:188},{id:"brokerage-commission-plans",label:"Financials",route:"/brokerage/commission-plans",icon:F_,description:"Commission plans, company dollar and fee statements",primaryCategory:"brokerage",section:"Manage Brokerage",badge:"new",visible:s=>(s.isBrokerageManager||s.isTransactionAdmin)&&!s.isAdmin,searchKeywords:["commission","split","cap","fees","agent plans"],displayOrder:195},{id:"brokerage-transactions",label:"Transactions & Compliance",route:"/brokerage/transactions",icon:qf,description:"Review agent files, required documents and closing compliance",primaryCategory:"brokerage",section:"Manage Brokerage",badge:"new",visible:s=>(s.isBrokerageManager||s.isTransactionAdmin)&&!s.isAdmin,searchKeywords:["compliance","transactions","documents","closing","paperless"],displayOrder:196},{id:"brokerage-vendors",label:"Vendors",route:"/brokerage/vendors",icon:wv,description:"Preferred vendor directory",primaryCategory:"brokerage",section:"Manage Brokerage",visible:s=>s.isBrokerageManager&&!s.isAdmin,searchKeywords:["vendors"],displayOrder:200},{id:"brokerage-forms",label:"Brokerage Forms",route:"/brokerage/forms",icon:Fr,description:"Official forms your agents can use",primaryCategory:"brokerage",section:"Manage Brokerage",badge:"new",visible:s=>s.isBrokerageManager&&!s.isAdmin,searchKeywords:["forms","pdf","documents"],displayOrder:205},{id:"brokerage-resources",label:"Brokerage Resources",route:"/brokerage-resources",icon:Cx,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:un,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:qf,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 uRt(s,t){return typeof s.route=="function"?s.route(t):s.route}function hRt(){const{user:s,isAdmin:t,isBrokerageManager:n,isCoach:r,brokerageId:a}=hs(),{hasPermission:i}=Ire(),{isInnerCircleEnabled:l,isMarketplaceEnabled:o,isFeatureEnabled:c}=Ore(),{hasAccess:d}=JMe(),{data:u,teams:h}=G_(),{leadSite:m,hasLeadSite:p,siteUrl:f}=lf(),{hasOffer:y}=vPe(!p),v=IS(),{hasAccess:g}=oRt(),{data:b}=ZQe(),j=Bt(),{data:S}=at({queryKey:["my-coach-nav",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),staleTime:5*60*1e3,queryFn:async()=>{const{data:Z}=await q.from("coaching_assignments").select("id").eq("agent_id",s.id).eq("status","active").limit(1);return(Z||[]).length>0}}),{data:C}=at({queryKey:["user-tool-favorites",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),staleTime:60*1e3,queryFn:async()=>{const{data:Z}=await q.from("user_tool_favorites").select("tool_id").eq("user_id",s.id);return(Z||[]).map(ne=>ne.tool_id)}}),E=_.useMemo(()=>new Set(C||[]),[C]),P=mt({mutationFn:async Z=>{s!=null&&s.id&&(E.has(Z)?await q.from("user_tool_favorites").delete().eq("user_id",s.id).eq("tool_id",Z):await q.from("user_tool_favorites").insert({user_id:s.id,tool_id:Z}))},onSuccess:()=>{j.invalidateQueries({queryKey:["user-tool-favorites"]}),j.invalidateQueries({queryKey:["app-catalog"]})}}),M=_.useMemo(()=>{var Z,ne;return{isAdmin:!!t,isBrokerageManager:!!n,isTransactionAdmin:((b==null?void 0:b.length)||0)>0,isCoach:!!r,isOnTeam:!!u,isTeamLeader:(h||[]).some(ce=>ce.role==="team_leader"),hasCoach:!!S,brokerageId:a??null,hasPermission:i,isInnerCircleEnabled:!!l,stagingStudioEnabled:c("staging_studio_enabled"),isMarketplaceEnabled:!!o,hasWeeklyReels:!!d,hasLeadSite:!!p,hasLeadSiteMLS:!!(m!=null&&m.mls_provider_id),hasFreeSiteOffer:!!y,leadSiteId:(m==null?void 0:m.id)??null,siteUrl:f??null,email:(s==null?void 0:s.email)??null,isPartnershipMember:v.isMember,hasCoachingOnboarding:v.isMember&&!!((Z=v.pkg)!=null&&Z.includes_coaching),hasCoachingAccess:!!g||v.isMember&&!!((ne=v.pkg)!=null&&ne.includes_coaching)}},[t,n,b,r,u,h,S,a,i,l,o,c,d,p,m,y,f,s==null?void 0:s.email,v.isMember,v.pkg,g]),I=_.useMemo(()=>REs.filter(Z=>Z.visible?Z.visible(M):!0).map(Z=>{if(!v.isRestricted)return Z;const ne=N2s(Z);return!ne||v.hasFeature(ne)?Z:{...Z,locked:!0,route:`/upgrade/${ne}`}}).sort((Z,ne)=>Z.displayOrder-ne.displayOrder),[M,v.isRestricted,v.features]),D=_.useMemo(()=>_Pe.filter(Z=>Z.visible?Z.visible(M):!0),[M]),O=_.useMemo(()=>D.filter(Z=>!Z.route).map(Z=>{const ne=I.filter(te=>te.primaryCategory===Z.id),ce=[],ie=new Map;for(const te of ne)ie.has(te.section)||(ie.set(te.section,[]),ce.push(te.section)),ie.get(te.section).push(te);return{id:Z.id,label:Z.label,sections:ce.map(te=>({title:te,items:ie.get(te)}))}}),[I,D]),V=_.useMemo(()=>new Map(O.map(Z=>[Z.id,Z])),[O]),G=Z=>Z.toolId||`nav:${Z.id}`,$=Z=>E.has(G(Z));return{ctx:M,categories:O,railCategories:D,categoryMap:V,destinations:I,favorites:E,isFavorite:$,favoritesFor:Z=>I.filter(ne=>ne.primaryCategory===Z&&$(ne)),favoriteKey:G,toggleFavorite:Z=>P.mutate(Z),searchDestinations:Z=>{const ne=Z.trim().toLowerCase();return ne?I.map(ie=>{const te=ie.label.toLowerCase(),ae=(ie.description||"").toLowerCase(),le=(ie.searchKeywords||[]).join(" ").toLowerCase();let be=0;return te===ne?be=100:te.startsWith(ne)?be=80:te.includes(ne)?be=60:le.includes(ne)?be=40:ae.includes(ne)?be=20:ie.section.toLowerCase().includes(ne)&&(be=10),be&&$(ie)&&(be+=5),{d:ie,score:be}}).filter(ie=>ie.score>0).sort((ie,te)=>te.score-ie.score).map(ie=>ie.d):[]},routeFor:Z=>uRt(Z,M)}}var zpt=1,FEs=.9,OEs=.8,zEs=.17,fOe=.1,xOe=.999,BEs=.9999,UEs=.99,qEs=/[\\\/_+.#"@\[\(\{&]/,$Es=/[\\\/_+.#"@\[\(\{&]/g,VEs=/[\s-]/,mRt=/[\s-]/g;function O$e(s,t,n,r,a,i,l){if(i===t.length)return a===s.length?zpt:UEs;var o=`${a},${i}`;if(l[o]!==void 0)return l[o];for(var c=r.charAt(i),d=n.indexOf(c,a),u=0,h,m,p,f;d>=0;)h=O$e(s,t,n,r,d+1,i+1,l),h>u&&(d===a?h*=zpt:qEs.test(s.charAt(d-1))?(h*=OEs,p=s.slice(a,d-1).match($Es),p&&a>0&&(h*=Math.pow(xOe,p.length))):VEs.test(s.charAt(d-1))?(h*=FEs,f=s.slice(a,d-1).match(mRt),f&&a>0&&(h*=Math.pow(xOe,f.length))):(h*=zEs,a>0&&(h*=Math.pow(xOe,d-a))),s.charAt(d)!==t.charAt(i)&&(h*=BEs)),(hh&&(h=m*fOe)),h>u&&(u=h),d=n.indexOf(c,d+1);return l[o]=u,u}function Bpt(s){return s.toLowerCase().replace(mRt," ")}function HEs(s,t,n){return s=n&&n.length>0?`${s+" "+n.join(" ")}`:s,O$e(s,t,Bpt(s),Bpt(t),0,0,{})}var OY='[cmdk-group=""]',gOe='[cmdk-group-items=""]',GEs='[cmdk-group-heading=""]',pRt='[cmdk-item=""]',Upt=`${pRt}:not([aria-disabled="true"])`,z$e="cmdk-item-select",fU="data-value",WEs=(s,t,n)=>HEs(s,t,n),fRt=_.createContext(void 0),Hre=()=>_.useContext(fRt),xRt=_.createContext(void 0),QQe=()=>_.useContext(xRt),gRt=_.createContext(void 0),yRt=_.forwardRef((s,t)=>{let n=xU(()=>{var ae,le;return{search:"",value:(le=(ae=s.value)!=null?ae:s.defaultValue)!=null?le:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=xU(()=>new Set),a=xU(()=>new Map),i=xU(()=>new Map),l=xU(()=>new Set),o=vRt(s),{label:c,children:d,value:u,onValueChange:h,filter:m,shouldFilter:p,loop:f,disablePointerSelection:y=!1,vimBindings:v=!0,...g}=s,b=Og(),j=Og(),S=Og(),C=_.useRef(null),E=rTs();X7(()=>{if(u!==void 0){let ae=u.trim();n.current.value=ae,P.emit()}},[u]),X7(()=>{E(6,G)},[]);let P=_.useMemo(()=>({subscribe:ae=>(l.current.add(ae),()=>l.current.delete(ae)),snapshot:()=>n.current,setState:(ae,le,be)=>{var me,he,pe,Ce;if(!Object.is(n.current[ae],le)){if(n.current[ae]=le,ae==="search")V(),D(),E(1,O);else if(ae==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let Ae=document.getElementById(S);Ae?Ae.focus():(me=document.getElementById(b))==null||me.focus()}if(E(7,()=>{var Ae;n.current.selectedItemId=(Ae=$())==null?void 0:Ae.id,P.emit()}),be||E(5,G),((he=o.current)==null?void 0:he.value)!==void 0){let Ae=le??"";(Ce=(pe=o.current).onValueChange)==null||Ce.call(pe,Ae);return}}P.emit()}},emit:()=>{l.current.forEach(ae=>ae())}}),[]),M=_.useMemo(()=>({value:(ae,le,be)=>{var me;le!==((me=i.current.get(ae))==null?void 0:me.value)&&(i.current.set(ae,{value:le,keywords:be}),n.current.filtered.items.set(ae,I(le,be)),E(2,()=>{D(),P.emit()}))},item:(ae,le)=>(r.current.add(ae),le&&(a.current.has(le)?a.current.get(le).add(ae):a.current.set(le,new Set([ae]))),E(3,()=>{V(),D(),n.current.value||O(),P.emit()}),()=>{i.current.delete(ae),r.current.delete(ae),n.current.filtered.items.delete(ae);let be=$();E(4,()=>{V(),(be==null?void 0:be.getAttribute("id"))===ae&&O(),P.emit()})}),group:ae=>(a.current.has(ae)||a.current.set(ae,new Set),()=>{i.current.delete(ae),a.current.delete(ae)}),filter:()=>o.current.shouldFilter,label:c||s["aria-label"],getDisablePointerSelection:()=>o.current.disablePointerSelection,listId:b,inputId:S,labelId:j,listInnerRef:C}),[]);function I(ae,le){var be,me;let he=(me=(be=o.current)==null?void 0:be.filter)!=null?me:WEs;return ae?he(ae,n.current.search,le):0}function D(){if(!n.current.search||o.current.shouldFilter===!1)return;let ae=n.current.filtered.items,le=[];n.current.filtered.groups.forEach(me=>{let he=a.current.get(me),pe=0;he.forEach(Ce=>{let Ae=ae.get(Ce);pe=Math.max(Ae,pe)}),le.push([me,pe])});let be=C.current;H().sort((me,he)=>{var pe,Ce;let Ae=me.getAttribute("id"),Pe=he.getAttribute("id");return((pe=ae.get(Pe))!=null?pe:0)-((Ce=ae.get(Ae))!=null?Ce:0)}).forEach(me=>{let he=me.closest(gOe);he?he.appendChild(me.parentElement===he?me:me.closest(`${gOe} > *`)):be.appendChild(me.parentElement===be?me:me.closest(`${gOe} > *`))}),le.sort((me,he)=>he[1]-me[1]).forEach(me=>{var he;let pe=(he=C.current)==null?void 0:he.querySelector(`${OY}[${fU}="${encodeURIComponent(me[0])}"]`);pe==null||pe.parentElement.appendChild(pe)})}function O(){let ae=H().find(be=>be.getAttribute("aria-disabled")!=="true"),le=ae==null?void 0:ae.getAttribute(fU);P.setState("value",le||void 0)}function V(){var ae,le,be,me;if(!n.current.search||o.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let he=0;for(let pe of r.current){let Ce=(le=(ae=i.current.get(pe))==null?void 0:ae.value)!=null?le:"",Ae=(me=(be=i.current.get(pe))==null?void 0:be.keywords)!=null?me:[],Pe=I(Ce,Ae);n.current.filtered.items.set(pe,Pe),Pe>0&&he++}for(let[pe,Ce]of a.current)for(let Ae of Ce)if(n.current.filtered.items.get(Ae)>0){n.current.filtered.groups.add(pe);break}n.current.filtered.count=he}function G(){var ae,le,be;let me=$();me&&(((ae=me.parentElement)==null?void 0:ae.firstChild)===me&&((be=(le=me.closest(OY))==null?void 0:le.querySelector(GEs))==null||be.scrollIntoView({block:"nearest"})),me.scrollIntoView({block:"nearest"}))}function $(){var ae;return(ae=C.current)==null?void 0:ae.querySelector(`${pRt}[aria-selected="true"]`)}function H(){var ae;return Array.from(((ae=C.current)==null?void 0:ae.querySelectorAll(Upt))||[])}function Y(ae){let le=H()[ae];le&&P.setState("value",le.getAttribute(fU))}function Z(ae){var le;let be=$(),me=H(),he=me.findIndex(Ce=>Ce===be),pe=me[he+ae];(le=o.current)!=null&&le.loop&&(pe=he+ae<0?me[me.length-1]:he+ae===me.length?me[0]:me[he+ae]),pe&&P.setState("value",pe.getAttribute(fU))}function ne(ae){let le=$(),be=le==null?void 0:le.closest(OY),me;for(;be&&!me;)be=ae>0?sTs(be,OY):nTs(be,OY),me=be==null?void 0:be.querySelector(Upt);me?P.setState("value",me.getAttribute(fU)):Z(ae)}let ce=()=>Y(H().length-1),ie=ae=>{ae.preventDefault(),ae.metaKey?ce():ae.altKey?ne(1):Z(1)},te=ae=>{ae.preventDefault(),ae.metaKey?Y(0):ae.altKey?ne(-1):Z(-1)};return _.createElement(ii.div,{ref:t,tabIndex:-1,...g,"cmdk-root":"",onKeyDown:ae=>{var le;(le=g.onKeyDown)==null||le.call(g,ae);let be=ae.nativeEvent.isComposing||ae.keyCode===229;if(!(ae.defaultPrevented||be))switch(ae.key){case"n":case"j":{v&&ae.ctrlKey&&ie(ae);break}case"ArrowDown":{ie(ae);break}case"p":case"k":{v&&ae.ctrlKey&&te(ae);break}case"ArrowUp":{te(ae);break}case"Home":{ae.preventDefault(),Y(0);break}case"End":{ae.preventDefault(),ce();break}case"Enter":{ae.preventDefault();let me=$();if(me){let he=new Event(z$e);me.dispatchEvent(he)}}}}},_.createElement("label",{"cmdk-label":"",htmlFor:M.inputId,id:M.labelId,style:iTs},c),wPe(s,ae=>_.createElement(xRt.Provider,{value:P},_.createElement(fRt.Provider,{value:M},ae))))}),KEs=_.forwardRef((s,t)=>{var n,r;let a=Og(),i=_.useRef(null),l=_.useContext(gRt),o=Hre(),c=vRt(s),d=(r=(n=c.current)==null?void 0:n.forceMount)!=null?r:l==null?void 0:l.forceMount;X7(()=>{if(!d)return o.item(a,l==null?void 0:l.id)},[d]);let u=bRt(a,i,[s.value,s.children,i],s.keywords),h=QQe(),m=IP(E=>E.value&&E.value===u.current),p=IP(E=>d||o.filter()===!1?!0:E.search?E.filtered.items.get(a)>0:!0);_.useEffect(()=>{let E=i.current;if(!(!E||s.disabled))return E.addEventListener(z$e,f),()=>E.removeEventListener(z$e,f)},[p,s.onSelect,s.disabled]);function f(){var E,P;y(),(P=(E=c.current).onSelect)==null||P.call(E,u.current)}function y(){h.setState("value",u.current,!0)}if(!p)return null;let{disabled:v,value:g,onSelect:b,forceMount:j,keywords:S,...C}=s;return _.createElement(ii.div,{ref:yE(i,t),...C,id:a,"cmdk-item":"",role:"option","aria-disabled":!!v,"aria-selected":!!m,"data-disabled":!!v,"data-selected":!!m,onPointerMove:v||o.getDisablePointerSelection()?void 0:y,onClick:v?void 0:f},s.children)}),YEs=_.forwardRef((s,t)=>{let{heading:n,children:r,forceMount:a,...i}=s,l=Og(),o=_.useRef(null),c=_.useRef(null),d=Og(),u=Hre(),h=IP(p=>a||u.filter()===!1?!0:p.search?p.filtered.groups.has(l):!0);X7(()=>u.group(l),[]),bRt(l,o,[s.value,s.heading,c]);let m=_.useMemo(()=>({id:l,forceMount:a}),[a]);return _.createElement(ii.div,{ref:yE(o,t),...i,"cmdk-group":"",role:"presentation",hidden:h?void 0:!0},n&&_.createElement("div",{ref:c,"cmdk-group-heading":"","aria-hidden":!0,id:d},n),wPe(s,p=>_.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?d:void 0},_.createElement(gRt.Provider,{value:m},p))))}),ZEs=_.forwardRef((s,t)=>{let{alwaysRender:n,...r}=s,a=_.useRef(null),i=IP(l=>!l.search);return!n&&!i?null:_.createElement(ii.div,{ref:yE(a,t),...r,"cmdk-separator":"",role:"separator"})}),XEs=_.forwardRef((s,t)=>{let{onValueChange:n,...r}=s,a=s.value!=null,i=QQe(),l=IP(d=>d.search),o=IP(d=>d.selectedItemId),c=Hre();return _.useEffect(()=>{s.value!=null&&i.setState("search",s.value)},[s.value]),_.createElement(ii.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)}})}),QEs=_.forwardRef((s,t)=>{let{children:n,label:r="Suggestions",...a}=s,i=_.useRef(null),l=_.useRef(null),o=IP(d=>d.selectedItemId),c=Hre();return _.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)}}},[]),_.createElement(ii.div,{ref:yE(i,t),...a,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":o,"aria-label":r,id:c.listId},wPe(s,d=>_.createElement("div",{ref:yE(l,c.listInnerRef),"cmdk-list-sizer":""},d)))}),JEs=_.forwardRef((s,t)=>{let{open:n,onOpenChange:r,overlayClassName:a,contentClassName:i,container:l,...o}=s;return _.createElement(AMe,{open:n,onOpenChange:r},_.createElement(EMe,{container:l},_.createElement(XG,{"cmdk-overlay":"",className:a}),_.createElement(QG,{"aria-label":s.label,"cmdk-dialog":"",className:i},_.createElement(yRt,{ref:t,...o}))))}),eTs=_.forwardRef((s,t)=>IP(n=>n.filtered.count===0)?_.createElement(ii.div,{ref:t,...s,"cmdk-empty":"",role:"presentation"}):null),tTs=_.forwardRef((s,t)=>{let{progress:n,children:r,label:a="Loading...",...i}=s;return _.createElement(ii.div,{ref:t,...i,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":a},wPe(s,l=>_.createElement("div",{"aria-hidden":!0},l)))}),K_=Object.assign(yRt,{List:QEs,Item:KEs,Input:XEs,Group:YEs,Separator:ZEs,Dialog:JEs,Empty:eTs,Loading:tTs});function sTs(s,t){let n=s.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function nTs(s,t){let n=s.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function vRt(s){let t=_.useRef(s);return X7(()=>{t.current=s}),t}var X7=typeof window>"u"?_.useEffect:_.useLayoutEffect;function xU(s){let t=_.useRef();return t.current===void 0&&(t.current=s()),t}function IP(s){let t=QQe(),n=()=>s(t.snapshot());return _.useSyncExternalStore(t.subscribe,n,n)}function bRt(s,t,n,r=[]){let a=_.useRef(),i=Hre();return X7(()=>{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(fU,o),a.current=o}),a}var rTs=()=>{let[s,t]=_.useState(),n=xU(()=>new Map);return X7(()=>{n.current.forEach(r=>r()),n.current=new Map},[s]),(r,a)=>{n.current.set(r,a),t({})}};function aTs(s){let t=s.type;return typeof t=="function"?t(s.props):"render"in t?t.render(s.props):s}function wPe({asChild:s,children:t},n){return s&&_.isValidElement(t)?_.cloneElement(aTs(t),{ref:t.ref},n(t.props.children)):n(t)}var iTs={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};const Aj=_.forwardRef(({className:s,...t},n)=>e.jsx(K_,{ref:n,className:At("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",s),...t}));Aj.displayName=K_.displayName;const oTs=({children:s,...t})=>e.jsx(Ls,{...t,children:e.jsx(Ps,{className:"overflow-hidden p-0 shadow-lg",children:e.jsx(Aj,{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})})}),Ej=_.forwardRef(({className:s,...t},n)=>e.jsxs("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:[e.jsx(Lr,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),e.jsx(K_.Input,{ref:n,className:At("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})]}));Ej.displayName=K_.Input.displayName;const Tj=_.forwardRef(({className:s,...t},n)=>e.jsx(K_.List,{ref:n,className:At("max-h-[300px] overflow-y-auto overflow-x-hidden",s),...t}));Tj.displayName=K_.List.displayName;const Mj=_.forwardRef((s,t)=>e.jsx(K_.Empty,{ref:t,className:"py-6 text-center text-sm",...s}));Mj.displayName=K_.Empty.displayName;const V_=_.forwardRef(({className:s,...t},n)=>e.jsx(K_.Group,{ref:n,className:At("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}));V_.displayName=K_.Group.displayName;const lTs=_.forwardRef(({className:s,...t},n)=>e.jsx(K_.Separator,{ref:n,className:At("-mx-1 h-px bg-border",s),...t}));lTs.displayName=K_.Separator.displayName;const d1=_.forwardRef(({className:s,...t},n)=>e.jsx(K_.Item,{ref:n,className:At("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}));d1.displayName=K_.Item.displayName;const cTs={event:{label:"Events",icon:pc,color:"bg-blue-500/10 text-blue-600"},template:{label:"Templates",icon:Xc,color:"bg-purple-500/10 text-purple-600"},academy:{label:"Academy",icon:mm,color:"bg-amber-500/10 text-amber-600"},toolbox:{label:"Toolbox",icon:Y4,color:"bg-green-500/10 text-green-600"},"social-swag":{label:"Social Swag",icon:un,color:"bg-fuchsia-500/10 text-fuchsia-600"}},qpt=()=>{const[s,t]=_.useState(!1),[n,r]=_.useState(""),[a,i]=_.useState([]),[l,o]=_.useState(!1),c=Fn(),{searchDestinations:d,isFavorite:u,routeFor:h}=hRt(),m=n.trim()?d(n).slice(0,6):[];_.useEffect(()=>{const v=g=>{g.key==="k"&&(g.metaKey||g.ctrlKey)&&(g.preventDefault(),t(b=>!b))};return document.addEventListener("keydown",v),()=>document.removeEventListener("keydown",v)},[]);const p=_.useCallback(async v=>{if(!v.trim()){i([]);return}o(!0);const g=`%${v}%`;try{const[b,j,S,C,E]=await Promise.all([q.from("events").select("id, title, description, event_date").eq("is_published",!0).or(`title.ilike.${g},description.ilike.${g}`).limit(5),q.from("canva_templates").select("id, name, description, publish_date").or(`name.ilike.${g},description.ilike.${g}`).limit(5),q.from("academy_videos").select("id, title, description, publish_date").eq("is_published",!0).or(`title.ilike.${g},description.ilike.${g}`).limit(5),q.from("resource_kits").select("id, name, description, publish_date").eq("is_published",!0).or(`name.ilike.${g},description.ilike.${g}`).limit(5),q.from("social_swag").select("id, title, description, publish_date").eq("is_published",!0).or(`title.ilike.${g},description.ilike.${g}`).limit(5)]),P=[];b.data&&b.data.forEach(M=>{P.push({id:M.id,title:M.title,description:M.description,type:"event",date:M.event_date,path:`/event/${M.id}`})}),j.data&&j.data.forEach(M=>{P.push({id:M.id,title:M.name,description:M.description,type:"template",date:M.publish_date,path:`/templates/${M.id}`})}),S.data&&S.data.forEach(M=>{P.push({id:M.id,title:M.title,description:M.description,type:"academy",date:M.publish_date,path:`/academy/${M.id}`})}),C.data&&C.data.forEach(M=>{P.push({id:M.id,title:M.name,description:M.description,type:"toolbox",date:M.publish_date,path:`/toolbox/${M.id}`})}),E.data&&E.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(b){console.error("Search error:",b)}finally{o(!1)}},[]);_.useEffect(()=>{const v=setTimeout(()=>{p(n)},300);return()=>clearTimeout(v)},[n,p]);const f=v=>{t(!1),r(""),c(v)},y=a.reduce((v,g)=>(v[g.type]||(v[g.type]=[]),v[g.type].push(g),v),{});return e.jsxs(e.Fragment,{children:[e.jsxs(B,{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(Lr,{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(oTs,{open:s,onOpenChange:t,children:[e.jsx(Ej,{placeholder:"Search events, templates, academy, toolbox, social swag...",value:n,onValueChange:r}),e.jsxs(Tj,{children:[m.length>0&&e.jsx(V_,{heading:"Go to",children:m.map(v=>{const g=v.icon;return e.jsxs(d1,{value:`nav-${v.id}-${v.label}`,onSelect:()=>{const b=h(v);v.external||v.openInNewTab?(t(!1),r(""),window.open(b,"_blank","noopener,noreferrer")):f(b)},className:"flex items-start gap-3 py-3 cursor-pointer",children:[e.jsx("div",{className:"p-2 rounded-md bg-primary/10 text-primary",children:e.jsx(g,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium truncate flex items-center gap-1.5",children:[v.label,u(v)&&e.jsx(C0,{className:"h-3 w-3 fill-current text-primary"})]}),v.description&&e.jsx("div",{className:"text-sm text-muted-foreground truncate",children:v.description})]}),e.jsx(Oe,{variant:"secondary",className:"text-xs shrink-0",children:v.section})]},`nav-${v.id}`)})}),l&&e.jsx("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"Searching..."}),!l&&n&&a.length===0&&m.length===0&&e.jsxs(Mj,{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(y).map(([v,g])=>{const b=cTs[v],j=b.icon;return e.jsx(V_,{heading:b.label,children:g.map(S=>e.jsxs(d1,{value:`${S.type}-${S.id}-${S.title}`,onSelect:()=>f(S.path),className:"flex items-start gap-3 py-3 cursor-pointer",children:[e.jsx("div",{className:`p-2 rounded-md ${b.color}`,children:e.jsx(j,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium truncate",children:S.title}),S.description&&e.jsx("div",{className:"text-sm text-muted-foreground truncate group-data-[selected=true]:text-primary-foreground/80",children:S.description})]}),e.jsxs("div",{className:"flex flex-col items-end gap-1 shrink-0",children:[e.jsx(Oe,{variant:"secondary",className:"text-xs",children:b.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Ed(new Date(S.date),{addSuffix:!0})})]})]},`${S.type}-${S.id}`))},v)})]})]})]})},dTs=({expiresAt:s,className:t,showUpgradeButton:n=!0})=>{const[r,a]=_.useState(null),i=Fn();if(_.useEffect(()=>{const d=()=>{const h=new Date().getTime(),p=new Date(s).getTime()-h;if(p<=0){a({days:0,hours:0,minutes:0});return}const f=Math.floor(p/(1e3*60*60*24)),y=Math.floor(p%(1e3*60*60*24)/(1e3*60*60)),v=Math.floor(p%(1e3*60*60)/(1e3*60));a({days:f,hours:y,minutes:v})};d();const u=setInterval(d,6e4);return()=>clearInterval(u)},[s]),!r)return null;const l=r.days===0&&r.hours===0&&r.minutes===0,o=r.days<=1,c=r.days<=3&&!o;return l?e.jsxs("div",{className:At("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(xl,{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(B,{size:"sm",onClick:()=>i("/subscription"),className:"bg-primary hover:bg-primary/90 text-xs h-7 px-3",children:[e.jsx(un,{className:"h-3 w-3 mr-1"}),"Upgrade Now"]})]}):e.jsxs("div",{className:At("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(Gr,{className:At("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:At("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:At("text-sm font-bold",o?"text-destructive":c?"text-amber-600":"text-primary"),children:[r.days,"d"]}),e.jsxs("span",{className:At("text-sm font-bold",o?"text-destructive":c?"text-amber-600":"text-primary"),children:[r.hours,"h"]}),e.jsxs("span",{className:At("text-sm font-bold",o?"text-destructive":c?"text-amber-600":"text-primary"),children:[r.minutes,"m"]}),e.jsx("span",{className:At("text-xs",o?"text-destructive/70":c?"text-amber-600/70":"text-primary/70"),children:"remaining"})]})]})]}),n&&e.jsxs(B,{size:"sm",onClick:()=>i("/subscription"),variant:o?"destructive":c?"default":"outline",className:At("text-xs h-7 px-3",c&&"bg-amber-500 hover:bg-amber-600 text-white"),children:[e.jsx(un,{className:"h-3 w-3 mr-1"}),"Upgrade"]})]})},uTs=()=>{const s=Fn();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(ve,{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(xl,{className:"h-8 w-8 text-destructive"})}),e.jsx(St,{className:"text-2xl",children:"Your Free Trial Has Ended"}),e.jsx(kn,{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(Me,{className:"space-y-6",children:[e.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[e.jsx(ve,{className:"border-2 border-primary/20 hover:border-primary/50 transition-colors cursor-pointer",onClick:()=>s("/subscription"),children:e.jsxs(Me,{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(In,{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(B,{className:"w-full",onClick:t=>{t.stopPropagation(),s("/subscription")},children:[e.jsx(un,{className:"h-4 w-4 mr-2"}),"Choose Individual"]})]})}),e.jsx(ve,{className:"border-2 border-amber-500/20 hover:border-amber-500/50 transition-colors cursor-pointer",onClick:()=>s("/subscription"),children:e.jsxs(Me,{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(B,{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(_a,{className:"h-4 w-4"}),e.jsx("span",{children:"1-866-527-8668"})]}),e.jsxs("a",{href:"mailto:support@relevelup.com",className:"flex items-center justify-center gap-2 text-primary hover:underline",children:[e.jsx(ln,{className:"h-4 w-4"}),e.jsx("span",{children:"support@relevelup.com"})]})]})]})]})]})})},hTs=({hasUnseenBrief:s,onClick:t,className:n})=>e.jsxs(ag,{children:[e.jsx(ig,{asChild:!0,children:e.jsxs(B,{variant:"ghost",size:"icon",onClick:t,className:At("relative transition-colors",s&&"text-primary hover:text-primary",n),children:[e.jsx(wh,{className:"h-5 w-5"}),s&&e.jsx("span",{className:"absolute top-1 right-1 h-2 w-2 rounded-full bg-primary animate-pulse"})]})}),e.jsx(Nx,{children:e.jsx("p",{children:"The LevelUp Brief"})})]});var jPe="Checkbox",[mTs,Sbr]=af(jPe),[pTs,JQe]=mTs(jPe);function fTs(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]=Ug({prop:n,defaultProp:a??!1,onChange:c,caller:jPe}),[f,y]=_.useState(null),[v,g]=_.useState(null),b=_.useRef(!1),j=f?!!l||!!f.closest("form"):!0,S={checked:m,disabled:i,setChecked:p,control:f,setControl:y,name:o,form:l,value:u,hasConsumerStoppedPropagationRef:b,required:d,defaultChecked:lP(a)?!1:a,isFormControl:j,bubbleInput:v,setBubbleInput:g};return e.jsx(pTs,{scope:t,...S,children:xTs(h)?h(S):r})}var _Rt="CheckboxTrigger",wRt=_.forwardRef(({__scopeCheckbox:s,onKeyDown:t,onClick:n,...r},a)=>{const{control:i,value:l,disabled:o,checked:c,required:d,setControl:u,setChecked:h,hasConsumerStoppedPropagationRef:m,isFormControl:p,bubbleInput:f}=JQe(_Rt,s),y=Qo(a,u),v=_.useRef(c);return _.useEffect(()=>{const g=i==null?void 0:i.form;if(g){const b=()=>h(v.current);return g.addEventListener("reset",b),()=>g.removeEventListener("reset",b)}},[i,h]),e.jsx(ii.button,{type:"button",role:"checkbox","aria-checked":lP(c)?"mixed":c,"aria-required":d,"data-state":CRt(c),"data-disabled":o?"":void 0,disabled:o,value:l,...r,ref:y,onKeyDown:wa(t,g=>{g.key==="Enter"&&g.preventDefault()}),onClick:wa(n,g=>{h(b=>lP(b)?!0:!b),f&&p&&(m.current=g.isPropagationStopped(),m.current||g.stopPropagation())})})});wRt.displayName=_Rt;var eJe=_.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(fTs,{__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(wRt,{...h,ref:t,__scopeCheckbox:n}),m&&e.jsx(SRt,{__scopeCheckbox:n})]})})});eJe.displayName=jPe;var jRt="CheckboxIndicator",NRt=_.forwardRef((s,t)=>{const{__scopeCheckbox:n,forceMount:r,...a}=s,i=JQe(jRt,n);return e.jsx(pg,{present:r||lP(i.checked)||i.checked===!0,children:e.jsx(ii.span,{"data-state":CRt(i.checked),"data-disabled":i.disabled?"":void 0,...a,ref:t,style:{pointerEvents:"none",...s.style}})})});NRt.displayName=jRt;var kRt="CheckboxBubbleInput",SRt=_.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}=JQe(kRt,s),f=Qo(n,p),y=$re(i),v=Cre(r);_.useEffect(()=>{const b=m;if(!b)return;const j=window.HTMLInputElement.prototype,C=Object.getOwnPropertyDescriptor(j,"checked").set,E=!a.current;if(y!==i&&C){const P=new Event("click",{bubbles:E});b.indeterminate=lP(i),C.call(b,lP(i)?!1:i),b.dispatchEvent(P)}},[m,y,i,a]);const g=_.useRef(lP(i)?!1:i);return e.jsx(ii.input,{type:"checkbox","aria-hidden":!0,defaultChecked:l??g.current,required:o,disabled:c,name:d,value:u,form:h,...t,tabIndex:-1,ref:f,style:{...t.style,...v,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})});SRt.displayName=kRt;function xTs(s){return typeof s=="function"}function lP(s){return s==="indeterminate"}function CRt(s){return lP(s)?"indeterminate":s?"checked":"unchecked"}const $a=_.forwardRef(({className:s,...t},n)=>e.jsx(eJe,{ref:n,className:At("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(NRt,{className:At("flex items-center justify-center text-current"),children:e.jsx(ea,{className:"h-4 w-4"})})}));$a.displayName=eJe.displayName;var tJe="Radio",[gTs,ARt]=af(tJe),[yTs,vTs]=gTs(tJe),ERt=_.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]=_.useState(null),p=Qo(t,v=>m(v)),f=_.useRef(!1),y=h?d||!!h.closest("form"):!0;return e.jsxs(yTs,{scope:n,checked:a,disabled:l,children:[e.jsx(ii.button,{type:"button",role:"radio","aria-checked":a,"data-state":LRt(a),"data-disabled":l?"":void 0,disabled:l,value:o,...u,ref:p,onClick:wa(s.onClick,v=>{a||c==null||c(),y&&(f.current=v.isPropagationStopped(),f.current||v.stopPropagation())})}),y&&e.jsx(PRt,{control:h,bubbles:!f.current,name:r,value:o,checked:a,required:i,disabled:l,form:d,style:{transform:"translateX(-100%)"}})]})});ERt.displayName=tJe;var TRt="RadioIndicator",MRt=_.forwardRef((s,t)=>{const{__scopeRadio:n,forceMount:r,...a}=s,i=vTs(TRt,n);return e.jsx(pg,{present:r||i.checked,children:e.jsx(ii.span,{"data-state":LRt(i.checked),"data-disabled":i.disabled?"":void 0,...a,ref:t})})});MRt.displayName=TRt;var bTs="RadioBubbleInput",PRt=_.forwardRef(({__scopeRadio:s,control:t,checked:n,bubbles:r=!0,...a},i)=>{const l=_.useRef(null),o=Qo(l,i),c=$re(n),d=Cre(t);return _.useEffect(()=>{const u=l.current;if(!u)return;const h=window.HTMLInputElement.prototype,p=Object.getOwnPropertyDescriptor(h,"checked").set;if(c!==n&&p){const f=new Event("click",{bubbles:r});p.call(u,n),u.dispatchEvent(f)}},[c,n,r]),e.jsx(ii.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}})});PRt.displayName=bTs;function LRt(s){return s?"checked":"unchecked"}var _Ts=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],NPe="RadioGroup",[wTs,Cbr]=af(NPe,[iL,ARt]),IRt=iL(),DRt=ARt(),[jTs,NTs]=wTs(NPe),RRt=_.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=IRt(n),f=DE(d),[y,v]=Ug({prop:i,defaultProp:a??null,onChange:h,caller:NPe});return e.jsx(jTs,{scope:n,name:r,required:l,disabled:o,value:y,onValueChange:v,children:e.jsx(WMe,{asChild:!0,...p,orientation:c,dir:f,loop:u,children:e.jsx(ii.div,{role:"radiogroup","aria-required":l,"aria-orientation":c,"data-disabled":o?"":void 0,dir:f,...m,ref:t})})})});RRt.displayName=NPe;var FRt="RadioGroupItem",ORt=_.forwardRef((s,t)=>{const{__scopeRadioGroup:n,disabled:r,...a}=s,i=NTs(FRt,n),l=i.disabled||r,o=IRt(n),c=DRt(n),d=_.useRef(null),u=Qo(t,d),h=i.value===a.value,m=_.useRef(!1);return _.useEffect(()=>{const p=y=>{_Ts.includes(y.key)&&(m.current=!0)},f=()=>m.current=!1;return document.addEventListener("keydown",p),document.addEventListener("keyup",f),()=>{document.removeEventListener("keydown",p),document.removeEventListener("keyup",f)}},[]),e.jsx(KMe,{asChild:!0,...o,focusable:!l,active:h,children:e.jsx(ERt,{disabled:l,required:i.required,checked:h,...c,...a,name:i.name,ref:u,onCheck:()=>i.onValueChange(a.value),onKeyDown:wa(p=>{p.key==="Enter"&&p.preventDefault()}),onFocus:wa(a.onFocus,()=>{var p;m.current&&((p=d.current)==null||p.click())})})})});ORt.displayName=FRt;var kTs="RadioGroupIndicator",zRt=_.forwardRef((s,t)=>{const{__scopeRadioGroup:n,...r}=s,a=DRt(n);return e.jsx(MRt,{...a,...r,ref:t})});zRt.displayName=kTs;var BRt=RRt,URt=ORt,STs=zRt;const k_=_.forwardRef(({className:s,...t},n)=>e.jsx(BRt,{className:At("grid gap-2",s),...t,ref:n}));k_.displayName=BRt.displayName;const sm=_.forwardRef(({className:s,...t},n)=>e.jsx(URt,{ref:n,className:At("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(STs,{className:"flex items-center justify-center",children:e.jsx(Uf,{className:"h-2.5 w-2.5 fill-current text-current"})})}));sm.displayName=URt.displayName;const CTs=({brief:s,open:t,onClose:n,onDismiss:r})=>{const{user:a}=hs(),[i,l]=_.useState({}),[o,c]=_.useState({}),[d,u]=_.useState([]);_.useEffect(()=>{t&&a&&s.polls.length>0&&h()},[t,a,s.polls]);const h=async()=>{if(!a)return;const v=s.polls.map(b=>b.id),{data:g}=await q.from("levelup_brief_poll_responses").select("poll_id, option_id").eq("user_id",a.id).in("poll_id",v);if(g){const b={};g.forEach(j=>{b[j.poll_id]||(b[j.poll_id]=[]),b[j.poll_id].push(j.option_id)}),c(b)}},m=(v,g)=>{l(b=>({...b,[v]:g}))},p=(v,g,b)=>{l(j=>{const S=j[v]||[];return b?{...j,[v]:[...S,g]}:{...j,[v]:S.filter(C=>C!==g)}})},f=async v=>{if(!a)return;const g=i[v];if(!g||Array.isArray(g)&&g.length===0){se.error("Please select an option");return}u(b=>[...b,v]);try{await q.from("levelup_brief_poll_responses").delete().eq("poll_id",v).eq("user_id",a.id);const b=Array.isArray(g)?g:[g],j=b.map(C=>({poll_id:v,option_id:C,user_id:a.id})),{error:S}=await q.from("levelup_brief_poll_responses").insert(j);if(S)throw S;c(C=>({...C,[v]:b})),se.success("Response submitted!")}catch(b){console.error("Error submitting poll response:",b),se.error("Failed to submit response")}finally{u(b=>b.filter(j=>j!==v))}},y=v=>(v.includes("mediadelivery.net")||v.includes("bunny"),v);return e.jsx(Ls,{open:t,onOpenChange:v=>!v&&n(),children:e.jsxs(Ps,{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(Qn,{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(wh,{className:"h-6 w-6"})}),e.jsxs("div",{children:[e.jsx(Oe,{variant:"secondary",className:"mb-1 bg-white/20 text-white border-0",children:"The LevelUp Brief"}),e.jsx(Ds,{className:"text-xl font-bold text-white",children:s.brief.title})]})]})]}),e.jsx(Ji,{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:y(s.brief.video_url),className:"absolute inset-0 w-full h-full",allow:"autoplay; fullscreen; picture-in-picture",allowFullScreen:!0})}),s.brief.graphic_url&&!s.brief.video_url&&e.jsx("div",{className:"rounded-lg overflow-hidden bg-muted",children:s.brief.graphic_link_url?e.jsx("a",{href:s.brief.graphic_link_url,target:"_blank",rel:"noopener noreferrer",className:"block",children:e.jsx("img",{src:s.brief.graphic_url,alt:"Brief graphic",className:"w-full object-contain cursor-pointer hover:opacity-90 transition-opacity"})}):e.jsx("img",{src:s.brief.graphic_url,alt:"Brief graphic",className:"w-full object-contain"})}),s.links.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("h4",{className:"font-semibold text-foreground",children:"Quick Links"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:s.links.map(v=>e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>window.open(v.url,"_blank"),className:"gap-2",children:[e.jsx(wr,{className:"h-4 w-4"}),v.title]},v.id))})]}),s.polls.map(v=>{var j,S;const g=((j=o[v.id])==null?void 0:j.length)>0,b=d.includes(v.id);return e.jsxs("div",{className:"space-y-3 p-4 bg-muted/50 rounded-lg border",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h4",{className:"font-semibold text-foreground",children:v.question}),g&&e.jsxs(Oe,{variant:"secondary",className:"gap-1",children:[e.jsx(Er,{className:"h-3 w-3"}),"Responded"]})]}),v.poll_type==="single"?e.jsx(k_,{value:i[v.id]||((S=o[v.id])==null?void 0:S[0])||"",onValueChange:C=>m(v.id,C),className:"space-y-2",children:v.options.map(C=>e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(sm,{value:C.id,id:C.id}),e.jsx(J,{htmlFor:C.id,className:"cursor-pointer",children:C.option_text})]},C.id))}):e.jsx("div",{className:"space-y-2",children:v.options.map(C=>{const P=(i[v.id]||o[v.id]||[]).includes(C.id);return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx($a,{id:C.id,checked:P,onCheckedChange:M=>p(v.id,C.id,M)}),e.jsx(J,{htmlFor:C.id,className:"cursor-pointer",children:C.option_text})]},C.id)})}),e.jsx(B,{size:"sm",onClick:()=>f(v.id),disabled:b,children:b?"Submitting...":g?"Update Response":"Submit"})]},v.id)})]})}),e.jsxs("div",{className:"p-4 pb-[calc(1rem+env(safe-area-inset-bottom))] border-t bg-muted/30 flex flex-col items-center gap-2 sticky bottom-0 z-10",children:[e.jsx(B,{onClick:n,className:"w-full max-w-xs",children:"Got it!"}),e.jsx(B,{variant:"ghost",size:"sm",onClick:r,children:"Don't show again"})]})]})})},ATs=()=>{const{user:s}=hs(),[t,n]=_.useState(null),[r,a]=_.useState(!1),[i,l]=_.useState(!0),[o,c]=_.useState(!1),d=_.useCallback(async()=>{if(!s){l(!1);return}try{const{data:f,error:y}=await q.from("levelup_briefs").select("*").eq("is_published",!0).lte("publish_date",new Date().toISOString()).order("publish_date",{ascending:!1}).limit(1).single();if(y||!f){l(!1);return}const{data:v}=await q.from("levelup_brief_views").select("*").eq("brief_id",f.id).eq("user_id",s.id).maybeSingle(),[g,b]=await Promise.all([q.from("levelup_brief_links").select("*").eq("brief_id",f.id).order("sort_order"),q.from("levelup_brief_polls").select("*").eq("brief_id",f.id).order("sort_order")]),j=[];if(b.data)for(const M of b.data){const{data:I}=await q.from("levelup_brief_poll_options").select("*").eq("poll_id",M.id).order("sort_order");j.push({...M,options:I||[]})}const S={brief:f,links:g.data||[],polls:j};n(S);const C=!!v,E=(v==null?void 0:v.dismissed_at)!=null,P=localStorage.getItem(`brief-dismissed-${f.id}`)==="true";if(E||P)c(!1),a(!1);else if(!C)a(!0),c(!0);else if(f.show_frequency==="every_login")a(!0),c(!0);else if(f.show_frequency==="daily"){const M=new Date(v.viewed_at);(new Date().getTime()-M.getTime())/(1e3*60*60)>=24&&(a(!0),c(!0))}else c(!1)}catch(f){console.error("Error fetching brief:",f)}finally{l(!1)}},[s]);_.useEffect(()=>{d()},[d]);const u=async()=>{if(!(!s||!t))try{const{data:f}=await q.from("levelup_brief_views").select("id").eq("brief_id",t.brief.id).eq("user_id",s.id).maybeSingle();f?await q.from("levelup_brief_views").update({viewed_at:new Date().toISOString()}).eq("id",f.id):await q.from("levelup_brief_views").insert({brief_id:t.brief.id,user_id:s.id})}catch(f){console.error("Error marking brief as viewed:",f)}};return{currentBrief:t,shouldShowPopup:r,hasUnseenBrief:o,loading:i,openBrief:()=>{a(!0)},closeBrief:()=>{a(!1),u()},dismissBrief:async()=>{if(!(!s||!t)){a(!1),c(!1);try{const{data:f,error:y}=await q.from("levelup_brief_views").select("id").eq("brief_id",t.brief.id).eq("user_id",s.id).maybeSingle();if(y&&console.error("Error checking existing brief view:",y),f){const{error:v}=await q.from("levelup_brief_views").update({dismissed_at:new Date().toISOString()}).eq("id",f.id).eq("user_id",s.id);v&&console.error("Error updating brief dismiss:",v)}else{const{error:v}=await q.from("levelup_brief_views").insert({brief_id:t.brief.id,user_id:s.id,dismissed_at:new Date().toISOString()});v&&console.error("Error inserting brief dismiss:",v)}localStorage.setItem(`brief-dismissed-${t.brief.id}`,"true")}catch(f){console.error("Error dismissing brief:",f),t&&localStorage.setItem(`brief-dismissed-${t.brief.id}`,"true")}}},refetch:d}};function ETs(){const[s,t]=_.useState(!1),[n,r]=_.useState(!1),[a,i]=_.useState(null);_.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(li,{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(rJ,{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(B,{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(Qn,{className:"h-4 w-4"})})]})]})}):null}const TTs=({children:s,onRefresh:t})=>{const[n,r]=_.useState(!1),[a,i]=_.useState(0),[l,o]=_.useState(!1),c=_.useRef(null),d=_.useRef(0),u=Bt(),h=80,m=120,p=_.useCallback(b=>{const j=c.current;j&&j.scrollTop<=0&&(d.current=b.touches[0].clientY,r(!0))},[]),f=_.useCallback(b=>{if(!n||l)return;const j=c.current;if(!j||j.scrollTop>0){r(!1),i(0);return}const C=b.touches[0].clientY-d.current;if(C>0){const P=Math.min(C*.5,m);i(P),P>10&&b.preventDefault()}},[n,l]),y=_.useCallback(async()=>{if(n)if(r(!1),a>=h&&!l){o(!0),i(h);try{t?await t():await u.invalidateQueries()}catch(b){console.error("Refresh failed:",b)}finally{o(!1),i(0)}}else i(0)},[n,a,l,t,u]),v=Math.min(a/h,1),g=v*180;return e.jsxs("div",{ref:c,className:"h-full overflow-auto",onTouchStart:p,onTouchMove:f,onTouchEnd:y,children:[e.jsx("div",{className:"flex justify-center items-center overflow-hidden transition-all duration-200 ease-out",style:{height:a>0?a:0,opacity:v},children:e.jsx("div",{className:`p-2 rounded-full bg-primary/10 ${l?"animate-spin":""}`,style:{transform:l?void 0:`rotate(${g}deg)`,transition:l?void 0:"transform 0.1s ease-out"},children:e.jsx(uo,{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})]})},qRt=()=>{const{user:s}=hs(),[t,n]=_.useState(!1),[r,a]=_.useState(!1),[i,l]=_.useState(0),[o,c]=_.useState(!0);_.useEffect(()=>{(async()=>{if(!s){c(!1);return}try{const{data:p}=await q.from("membership_reviews").select("id").eq("user_id",s.id).maybeSingle();if(p){a(!0),n(!1),c(!1);return}const{data:f}=await q.from("profiles").select("login_count").eq("id",s.id).single(),y=(f==null?void 0:f.login_count)||0;l(y);const v=sessionStorage.getItem("review-prompt-dismissed");n(y>=4&&!v)}catch(p){console.error("Error checking review eligibility:",p)}finally{c(!1)}})()},[s]);const d=_.useCallback(()=>{sessionStorage.setItem("review-prompt-dismissed","true"),n(!1)},[]),u=_.useCallback(async(m,p)=>{if(!s)return{success:!1,error:"Not authenticated"};try{const{error:f}=await q.from("membership_reviews").insert({user_id:s.id,rating:m,review_text:p});if(f)throw f;return a(!0),n(!1),{success:!0,pointsAwarded:25}}catch(f){return console.error("Error submitting review:",f),{success:!1,error:f.message}}},[s]),h=_.useCallback(async()=>{if(s)try{await q.from("membership_reviews").update({posted_to_google:!0}).eq("user_id",s.id)}catch(m){console.error("Error updating Google review status:",m)}},[s]);return{shouldShowPrompt:t,hasSubmittedReview:r,loginCount:i,isLoading:o,dismissPrompt:d,submitReview:u,markPostedToGoogle:h}},MTs="https://search.google.com/local/writereview?placeid=ChIJM73ERQD1QogRPxupMFObuck&source=g.page.m.ia._&laa=nmx-review-solicitation-ia2",PTs=()=>{const{shouldShowPrompt:s,isLoading:t,dismissPrompt:n,submitReview:r,markPostedToGoogle:a}=qRt(),[i,l]=_.useState(!1),[o,c]=_.useState("review"),[d,u]=_.useState(0),[h,m]=_.useState(0),[p,f]=_.useState(""),[y,v]=_.useState(!1),[g,b]=_.useState(!1);if(t||!s&&!g)return null;const j=async()=>{if(d===0){ia({title:"Please select a rating",variant:"destructive"});return}v(!0);const E=await r(d,p);v(!1),E.success?(b(!0),ia({title:"Thank you for your feedback!",description:"Your review helps us improve."}),c("google")):ia({title:"Error submitting review",description:E.error,variant:"destructive"})},S=async E=>{E&&(await navigator.clipboard.writeText(p||`${d} star rating for LevelUp!`),ia({title:"Review copied!",description:"Paste it on Google Reviews."}),await a(),window.open(MTs,"_blank")),l(!1),n()},C=()=>{l(!1),n()};return e.jsxs(e.Fragment,{children:[e.jsxs("button",{onClick:()=>l(!0),className:"fixed bottom-20 left-1/2 -translate-x-1/2 z-40 flex items-center gap-2 rounded-full bg-primary/90 px-3 py-2 text-xs text-primary-foreground shadow-lg backdrop-blur-sm transition-all hover:bg-primary hover:scale-105 md:bottom-6",children:[e.jsx(Da,{className:"h-3.5 w-3.5 fill-current"}),e.jsx("span",{className:"hidden sm:inline",children:"Leave a Review"})]}),e.jsx(Ls,{open:i,onOpenChange:C,children:e.jsx(Ps,{className:"sm:max-w-md",children:o==="review"?e.jsxs(e.Fragment,{children:[e.jsxs(Os,{children:[e.jsx(Ds,{className:"text-center",children:"How are you enjoying LevelUp?"}),e.jsx(_r,{className:"text-center",children:"Your feedback helps us improve the experience for all members."})]}),e.jsxs("div",{className:"space-y-6 py-4",children:[e.jsx("div",{className:"flex justify-center gap-1",children:[1,2,3,4,5].map(E=>e.jsx("button",{type:"button",onClick:()=>u(E),onMouseEnter:()=>m(E),onMouseLeave:()=>m(0),className:"p-1 transition-transform hover:scale-110",children:e.jsx(Da,{className:At("h-8 w-8 transition-colors",(h||d)>=E?"fill-yellow-400 text-yellow-400":"text-muted-foreground")})},E))}),e.jsx(Ms,{placeholder:"Tell us about your experience (optional)",value:p,onChange:E=>f(E.target.value),rows:4,className:"resize-none"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",onClick:C,className:"flex-1",children:"Maybe Later"}),e.jsx(B,{onClick:j,disabled:y||d===0,className:"flex-1",children:y?"Submitting...":"Submit Review"})]})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(Os,{children:[e.jsx(Ds,{className:"text-center",children:"🎉 Thank you!"}),e.jsx(_r,{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(B,{variant:"outline",onClick:()=>S(!1),className:"flex-1",children:"No Thanks"}),e.jsx(B,{onClick:()=>S(!0),className:"flex-1",children:"Yes, Open Google"})]})]})]})})})]})};function LTs(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 y="vapid_public_key";let v=localStorage.getItem(y);if(!v){const{data:j,error:S}=await q.functions.invoke("get-vapid-public-key",{body:{}});if(S)throw S;if(v=(j==null?void 0:j.vapidPublicKey)??null,!v)throw new Error("Missing VAPID public key");localStorage.setItem(y,v)}u(v);const g=await navigator.serviceWorker.register("/push-sw.js",{scope:"/push-notifications/"});c(g),n(Notification.permission);const b=await g.pushManager.getSubscription();a(!!b)}catch(y){console.error("Error initializing push notifications:",y)}finally{l(!1)}})()},[h]);const m=_.useCallback(async()=>{if(!h||!o||!s)return console.error("Push notifications not supported or user not logged in"),!1;if(!d)return se.error("Push notifications are not ready yet. Please try again in a moment."),!1;try{l(!0);const f=await o.pushManager.getSubscription();if(f){try{await f.unsubscribe()}catch(S){console.warn("Failed to unsubscribe existing push subscription:",S)}const{error:j}=await q.from("push_subscriptions").delete().eq("user_id",s.id);j&&console.warn("Failed to cleanup push_subscriptions rows:",j)}if(Notification.permission!=="granted"){const j=await Notification.requestPermission();if(n(j),j!=="granted")return j==="denied"?se.error("Notifications blocked. Please enable them in your browser settings (click the lock icon in the address bar)."):se.error("Notification permission was dismissed. Please try again."),!1}const y=LTs(d);let v;try{v=await o.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:y})}catch(j){console.error("PushManager.subscribe() failed:",j);const S=(j==null?void 0:j.message)||String(j);return S.includes("permission")?se.error("Push permission denied. Check your browser notification settings."):S.includes("key")||S.includes("VAPID")?se.error("Push configuration error. Please contact support."):S.includes("AbortError")?se.error("Push subscription was cancelled. Please try again."):se.error(`Failed to subscribe: ${S}`),!1}const g=v.toJSON(),{error:b}=await q.from("push_subscriptions").upsert({user_id:s.id,endpoint:g.endpoint,p256dh_key:g.keys.p256dh,auth_key:g.keys.auth},{onConflict:"user_id,endpoint"});if(b)throw console.error("Error saving subscription:",b),se.error("Failed to save notification preferences. Please try again."),b;return a(!0),se.success("Push notifications enabled!"),!0}catch(f){if(console.error("Error subscribing to push notifications:",f),!(f instanceof Error&&f.message.includes("toast"))){const y=f instanceof Error?f.message:"Unknown error";se.error("Failed to enable push notifications: "+y)}return!1}finally{l(!1)}},[h,o,s,d]),p=_.useCallback(async()=>{if(!o||!s)return!1;try{l(!0);const f=await o.pushManager.getSubscription();return f&&await f.unsubscribe(),await q.from("push_subscriptions").delete().eq("user_id",s.id),a(!1),se.success("Push notifications disabled"),!0}catch(f){console.error("Error unsubscribing:",f);const y=f instanceof Error?f.message:"Unknown error";return se.error("Failed to disable push notifications: "+y),!1}finally{l(!1)}},[o,s]);return{isSupported:h,permission:t,isSubscribed:r,isLoading:i,vapidPublicKey:d,subscribe:m,unsubscribe:p}}const yOe="push_notification_prompt_dismissed",ITs=["/dashboard","/admin"],DTs=()=>{const{user:s}=hs(),{isSupported:t,isSubscribed:n,isLoading:r,subscribe:a}=$Rt(),i=ru(),[l,o]=_.useState(!1),[c,d]=_.useState(!1),u=ITs.some(p=>i.pathname===p||i.pathname.startsWith(`${p}/`));_.useEffect(()=>{if(u){o(!1);return}if(!s||!t||n||r||localStorage.getItem(`${yOe}_${s.id}`))return;const f=setTimeout(()=>{o(!0)},2e3);return()=>clearTimeout(f)},[s,t,n,r,u]);const h=async()=>{d(!0);const p=await a();d(!1),p&&(s&&localStorage.setItem(`${yOe}_${s.id}`,"true"),o(!1))},m=()=>{s&&localStorage.setItem(`${yOe}_${s.id}`,"true"),o(!1)};return!t||n||u?null:e.jsx(Ls,{open:l,onOpenChange:p=>!p&&m(),children:e.jsxs(Ps,{className:"sm:max-w-md",children:[e.jsxs(Os,{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(Rg,{className:"h-6 w-6 text-primary"})}),e.jsx(Ds,{className:"text-center",children:"Stay in the Loop!"}),e.jsx(_r,{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(B,{onClick:h,disabled:c,className:"w-full",children:c?"Enabling...":"Enable Notifications"}),e.jsx(B,{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."})]})})},$pt=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},RTs=s=>s?$pt(s):$pt,FTs=s=>s;function OTs(s,t=FTs){const n=Dt.useSyncExternalStore(s.subscribe,Dt.useCallback(()=>t(s.getState()),[s,t]),Dt.useCallback(()=>t(s.getInitialState()),[s,t]));return Dt.useDebugValue(n),n}const Vpt=s=>{const t=RTs(s),n=r=>OTs(t,r);return Object.assign(n,t),n},zTs=s=>s?Vpt(s):Vpt;function BTs(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 B$e=s=>t=>{try{const n=s(t);return n instanceof Promise?n:{then(r){return B$e(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return B$e(r)(n)}}}},UTs=(s,t)=>(n,r,a)=>{let i={storage:BTs(()=>window.localStorage),partialize:v=>v,version:0,merge:(v,g)=>({...g,...v}),...t},l=!1,o=0;const c=new Set,d=new Set;let u=i.storage;if(!u)return s((...v)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...v)},r,a);const h=()=>{const v=i.partialize({...r()});return u.setItem(i.name,{state:v,version:i.version})},m=a.setState;a.setState=(v,g)=>(m(v,g),h());const p=s((...v)=>(n(...v),h()),r,a);a.getInitialState=()=>p;let f;const y=()=>{var v,g;if(!u)return;const b=++o;l=!1,c.forEach(S=>{var C;return S((C=r())!=null?C:p)});const j=((g=i.onRehydrateStorage)==null?void 0:g.call(i,(v=r())!=null?v:p))||void 0;return B$e(u.getItem.bind(u))(i.name).then(S=>{if(S)if(typeof S.version=="number"&&S.version!==i.version){if(i.migrate){const C=i.migrate(S.state,S.version);return C instanceof Promise?C.then(E=>[!0,E]):[!0,C]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,S.state];return[!1,void 0]}).then(S=>{var C;if(b!==o)return;const[E,P]=S;if(f=i.merge(P,(C=r())!=null?C:p),n(f,!0),E)return h()}).then(()=>{b===o&&(j==null||j(r(),void 0),f=r(),l=!0,d.forEach(S=>S(f)))}).catch(S=>{b===o&&(j==null||j(void 0,S))})};return a.persist={setOptions:v=>{i={...i,...v},v.storage&&(u=v.storage)},clearStorage:()=>{u==null||u.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>y(),hasHydrated:()=>l,onHydrate:v=>(c.add(v),()=>{c.delete(v)}),onFinishHydration:v=>(d.add(v),()=>{d.delete(v)})},i.skipHydration||y(),f||p},qTs=UTs,kPe=zTs()(qTs((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 $Ts({activeCategory:s,currentCategory:t,onSelect:n,onHover:r,badgeCounts:a,categories:i=_Pe}){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:At("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 VTs({category:s,top:t,left:n,onClose:r,onNavigate:a,isFavorite:i,favorites:l,onToggleFavorite:o,isCurrent:c,badgeCounts:d}){const u=_.useRef(null);_.useEffect(()=>{const m=f=>{f.key==="Escape"&&r()},p=f=>{var v;if(!u.current)return;const y=f.target;!u.current.contains(y)&&!((v=y==null?void 0:y.closest)!=null&&v.call(y,"[data-nav-rail]"))&&r()};return document.addEventListener("keydown",m),document.addEventListener("mousedown",p),()=>{document.removeEventListener("keydown",m),document.removeEventListener("mousedown",p)}},[r]);const h=m=>{const p=m.icon,f=m.badgeKey?(d==null?void 0:d[m.badgeKey])??0:0;return e.jsxs("div",{className:At("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(ec,{className:"h-3 w-3 text-muted-foreground","aria-label":"Upgrade required"}),f>0&&e.jsx("span",{className:"flex h-4 min-w-4 items-center justify-center rounded-full bg-muted-foreground/15 px-1 text-[10px] font-medium text-muted-foreground",children:f>9?"9+":f})]}),m.description&&e.jsx("span",{className:"mt-0.5 block text-xs leading-snug text-muted-foreground line-clamp-2",children:m.description})]})]}),e.jsx("button",{type:"button","aria-label":i(m)?`Remove ${m.label} from favorites`:`Add ${m.label} to favorites`,onClick:y=>{y.stopPropagation(),o(m)},className:At("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(C0,{className:At("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(C0,{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 HTs({categories:s,railCategories:t=_Pe,currentCategory:n,onNavigate:r,onNavigateRoute:a,isCurrent:i,badgeCounts:l,isFavorite:o,onToggleFavorite:c}){const[d,u]=_.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:At("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(y=>y.id===h.id),f=d===h.id;return e.jsxs("div",{children:[e.jsxs("button",{type:"button","aria-expanded":f,onClick:()=>u(f?null:h.id),className:At("flex w-full items-center gap-3 rounded-lg px-3 py-3 text-sm font-medium text-sidebar-foreground hover:bg-sidebar-accent",n===h.id&&"text-primary"),children:[e.jsx(m,{className:"h-4 w-4",style:{color:`hsl(var(--${h.accent}))`}}),h.label,e.jsx(tl,{className:At("ml-auto h-4 w-4 transition-transform",f&&"rotate-180")})]}),f&&p&&e.jsx("div",{className:"space-y-3 pb-3 pl-4 pr-1",children:p.sections.map(y=>e.jsxs("div",{children:[e.jsx("p",{className:"px-2 py-1 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground",children:y.title}),y.items.map(v=>{const g=v.icon,b=v.badgeKey?(l==null?void 0:l[v.badgeKey])??0:0,j=(o==null?void 0:o(v))??!1;return e.jsxs("div",{className:At("flex w-full items-center gap-2 rounded-md pr-1 hover:bg-sidebar-accent",i(v)&&"bg-sidebar-accent"),children:[e.jsxs("button",{type:"button",onClick:()=>r(v),className:"flex flex-1 items-center gap-2 px-2 py-2 text-left text-sm text-sidebar-foreground",children:[e.jsx(g,{className:"h-4 w-4 shrink-0"}),e.jsx("span",{className:"truncate",children:v.label}),b>0&&e.jsx("span",{className:"ml-auto flex h-5 w-5 items-center justify-center rounded-full bg-muted text-xs text-muted-foreground",children:b>9?"9+":b})]}),c&&e.jsx("button",{type:"button","aria-label":j?`Remove ${v.label} from favorites`:`Add ${v.label} to favorites`,onClick:()=>c(v),className:At("rounded p-2",j?"text-primary":"text-muted-foreground/60"),children:e.jsx(C0,{className:At("h-4 w-4",j&&"fill-current")})})]},v.id)})]},y.title))})]},h.id)})})}function VRt(){const s=Fn(),t=ru(),n=hRt(),r=_.useCallback(o=>uRt(o,n.ctx),[n.ctx]),a=_.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=_.useCallback(o=>!o.external&&t.pathname===r(o),[t.pathname,r]),l=_.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 GTs({communityUnreadCount:s=0,wishlistOpenCount:t=0,flyoutTop:n=64,flyoutLeft:r=80}){const{nav:a,navigate:i,currentCategory:l,isCurrent:o,go:c}=VRt(),[d,u]=_.useState(null),h=_.useRef(null),m=y=>{const v=_Pe.find(g=>g.id===y);if(v!=null&&v.route){u(null),i(v.route);return}u(g=>g===y?null:y)},p=d?a.categoryMap.get(d):void 0,f={more:s+t};return e.jsxs("div",{"data-nav-rail":!0,className:"flex h-full flex-col",onMouseLeave:()=>{h.current&&window.clearTimeout(h.current),h.current=window.setTimeout(()=>u(null),250)},onMouseEnter:()=>{h.current&&window.clearTimeout(h.current)},children:[e.jsx($Ts,{activeCategory:d,currentCategory:l,onSelect:m,categories:a.railCategories,badgeCounts:f}),p&&e.jsx(VTs,{category:p,top:n,left:r,onClose:()=>u(null),onNavigate:y=>{u(null),c(y)},isFavorite:a.isFavorite,favorites:a.favoritesFor(p.id),onToggleFavorite:y=>a.toggleFavorite(a.favoriteKey(y)),isCurrent:o,badgeCounts:{community:s,wishlist:t}})]})}function WTs({communityUnreadCount:s=0,wishlistOpenCount:t=0,onNavigated:n}){const{nav:r,navigate:a,currentCategory:i,isCurrent:l,go:o}=VRt();return e.jsx(HTs,{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 KTs=({bannerHeight:s,communityUnreadCount:t,wishlistOpenCount:n,isTrial:r,isExpired:a})=>{const i=Fn();return e.jsxs("div",{className:"flex h-full flex-col",children:[e.jsx("div",{className:"flex h-16 shrink-0 items-center justify-center border-b border-sidebar-border",children:e.jsx("button",{type:"button",onClick:()=>i("/dashboard"),"aria-label":"LevelUp home",children:e.jsx("img",{src:Y2s,alt:"LevelUp",className:"h-8 w-auto"})})}),e.jsxs(Ji,{className:"flex-1 [&_[data-radix-scroll-area-scrollbar]]:w-1.5",children:[e.jsx(GTs,{communityUnreadCount:t,wishlistOpenCount:n,flyoutTop:s+64,flyoutLeft:80}),r&&!a&&e.jsx("div",{className:"p-2",children:e.jsxs("button",{type:"button",onClick:()=>i("/subscription"),className:"flex w-full flex-col items-center gap-1 rounded-xl border border-amber-500/30 bg-amber-500/10 px-1 py-2 text-[10px] font-semibold text-amber-600 dark:text-amber-400",children:[e.jsx(un,{className:"h-4 w-4"}),"Upgrade"]})})]})]})},YTs=({isTrial:s,isExpired:t,expiresAt:n,communityUnreadCount:r,wishlistOpenCount:a,pathname:i,onSignOut:l,onNavigated:o})=>{const c=Fn();return e.jsxs("div",{className:"flex h-full flex-col",children:[e.jsx("div",{className:"flex items-center gap-2 border-b border-sidebar-border p-3",children:e.jsx("img",{src:K2s,alt:"LevelUp",className:"h-8 w-auto"})}),e.jsxs(Ji,{className:"flex-1",children:[s&&!t&&e.jsx("div",{className:"p-2",children:e.jsx("button",{type:"button",onClick:()=>{c("/subscription"),o==null||o()},className:At("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(un,{className:"h-4 w-4 text-amber-500"}),e.jsx("span",{className:"flex-1 text-left",children:"Ready to Upgrade?"}),n&&e.jsxs("span",{className:"rounded border border-amber-500/30 bg-amber-500/15 px-1.5 py-0.5 text-[10px] font-bold uppercase tracking-wide text-amber-600 dark:text-amber-400",children:[Math.max(0,Math.ceil((Date.parse(n)-Date.now())/864e5)),"d left"]})]})})}),e.jsx(WTs,{communityUnreadCount:r,wishlistOpenCount:a,onNavigated:o})]}),e.jsxs("div",{className:"border-t border-sidebar-border p-3",children:[e.jsxs(B,{variant:"ghost",size:"sm",className:At("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",i==="/profile"&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>{c("/profile"),o==null||o()},children:[e.jsx(Fo,{className:"h-4 w-4"}),"Profile"]}),e.jsxs(B,{variant:"ghost",size:"sm",className:"w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",onClick:l,children:[e.jsx(QO,{className:"h-4 w-4"}),"Sign Out"]})]})]})},zs=({children:s,title:t})=>{var me;const{user:n,signOut:r,isAdmin:a,isBrokerageManager:i,isCoach:l,brokerageId:o}=hs(),{isAssistant:c,actingAsAgent:d,hasPermission:u}=Ire();JMe();const{isImpersonating:h}=GMe(),p=(c&&!!d?40:0)+(h?40:0),{avatarUrl:f}=JIt(n==null?void 0:n.id),{isTrial:y,isExpired:v,expiresAt:g}=T2s(n==null?void 0:n.id),{isInnerCircleEnabled:b,isMarketplaceEnabled:j}=Ore(),{currentBrief:S,shouldShowPopup:C,hasUnseenBrief:E,openBrief:P,closeBrief:M,dismissBrief:I}=ATs(),{unreadCount:D}=M2s(),{openCount:O}=P2s();G_();const G=kPe(he=>he.cartItems).reduce((he,pe)=>he+pe.quantity,0),{leadSite:$,hasLeadSite:H,siteUrl:Y}=lf();vPe(!H);const Z=Fn(),ne=ru(),[ce,ie]=_.useState(null);_.useEffect(()=>{n!=null&&n.id&&q.from("profiles").select("name").eq("id",n.id).single().then(({data:he})=>{he!=null&&he.name&&ie(he.name)})},[n==null?void 0:n.id]);const te=ce||((me=n==null?void 0:n.user_metadata)==null?void 0:me.name)||(n==null?void 0:n.email)||"User",[ae,le]=_.useState(!1),be=he=>he.split(" ").map(pe=>pe[0]).join("").toUpperCase().slice(0,2);return e.jsx(FN,{children:e.jsxs("div",{className:"min-h-screen bg-background flex",children:[y&&v&&ne.pathname!=="/subscription"&&e.jsx(uTs,{}),typeof document<"u"&&mv.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(KTs,{bannerHeight:p,communityUnreadCount:D,wishlistOpenCount:O,isTrial:y,isExpired:v})}),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(qg,{open:ae,onOpenChange:le,children:[e.jsx(zre,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"md:hidden",children:e.jsx(GA,{className:"h-5 w-5"})})}),e.jsx(hg,{side:"left",className:"w-72 p-0 bg-card",children:e.jsx(YTs,{isTrial:y,isExpired:v,expiresAt:g,communityUnreadCount:D,wishlistOpenCount:O,pathname:ne.pathname,onSignOut:r,onNavigated:()=>le(!1)})})]}),e.jsx("div",{className:"flex-1 md:hidden",children:e.jsx("img",{src:Z2s,alt:"LevelUp",className:"h-8 w-auto"})}),e.jsx("div",{className:"hidden md:flex flex-1 justify-center",children:e.jsx(qpt,{})}),e.jsxs("div",{className:"flex items-center gap-3 ml-auto",children:[y&&!v&&g&&e.jsx(dTs,{expiresAt:g,className:"hidden lg:flex"}),e.jsx("div",{className:"md:hidden",children:e.jsx(qpt,{})}),S&&e.jsx(hTs,{hasUnseenBrief:E,onClick:P}),j&&e.jsxs(B,{variant:"ghost",size:"icon",className:"relative",onClick:()=>Z("/marketplace/cart"),children:[e.jsx(xS,{className:"h-5 w-5"}),G>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:G>99?"99+":G})]}),e.jsx(B,{variant:"ghost",size:"icon","aria-label":"My Calendar",title:"My Calendar",onClick:()=>Z("/mission-control/calendar"),children:e.jsx(pc,{className:"h-5 w-5"})}),e.jsx(hEs,{}),e.jsx(L$e,{}),e.jsxs("span",{className:"hidden sm:block text-sm font-medium text-foreground",children:["Hello, ",te.split(" ")[0],"!"]}),e.jsxs(tu,{children:[e.jsx(su,{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(ja,{className:"h-9 w-9 cursor-pointer hover:opacity-80 transition-opacity",children:[e.jsx(pi,{src:f||void 0}),e.jsx(Na,{className:"bg-primary text-primary-foreground font-medium text-sm",children:be(te)})]})})}),e.jsxs(Od,{align:"end",className:"w-48",children:[e.jsxs(ca,{onClick:()=>Z("/profile"),className:"cursor-pointer",children:[e.jsx(Fo,{className:"h-4 w-4 mr-2"}),"Profile"]}),e.jsxs(ca,{onClick:()=>Z("/mission-control/integrations"),className:"cursor-pointer",children:[e.jsx(pN,{className:"h-4 w-4 mr-2"}),"Integrations"]}),e.jsxs(ca,{onClick:()=>Z("/mission-control/browser-extension"),className:"cursor-pointer",children:[e.jsx(pN,{className:"h-4 w-4 mr-2"}),"Browser Extension"]}),e.jsx(M0,{}),e.jsxs(ca,{onClick:r,className:"cursor-pointer text-destructive focus:text-destructive",children:[e.jsx(QO,{className:"h-4 w-4 mr-2"}),"Sign Out"]})]})]})]})]})}),e.jsx(TTs,{children:e.jsx("main",{className:"p-4 sm:p-6 lg:p-8 overflow-x-hidden",children:s})}),S&&e.jsx(CTs,{brief:S,open:C,onClose:M,onDismiss:I}),e.jsx(ETs,{}),e.jsx(PTs,{}),e.jsx(DTs,{})]})]})})},dn=({children:s,requireAdmin:t=!1,requireBrokerageManager:n=!1})=>{const{user:r,loading:a,rolesLoading:i,isAdmin:l,isBrokerageManager:o}=hs(),c=ru(),d=IS();if(a||(t||n)&&i)return e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"Loading..."})]})});if(!r){const u=c.pathname+c.search+c.hash;return u&&u!=="/auth"&&sessionStorage.setItem("redirectAfterLogin",u),e.jsx(fd,{to:"/auth",replace:!0})}if(t&&!l)return e.jsx(fd,{to:"/dashboard",replace:!0});if(n&&!o&&!l)return e.jsx(fd,{to:"/dashboard",replace:!0});if(d.isRestricted&&!d.isLoading){const u=XIt(c.pathname);if(u&&!d.hasFeature(u))return e.jsx(zs,{title:"Upgrade required",children:e.jsx(E2s,{featureKey:u})})}return e.jsx(e.Fragment,{children:s})};function vOe({children:s}){const{isAdmin:t,loading:n,rolesLoading:r}=hs(),{isFeatureEnabled:a,isLoading:i}=Ore();return n||r||i?e.jsx("div",{className:"flex min-h-[50vh] items-center justify-center",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):!t&&!a("staging_studio_enabled")?e.jsx(fd,{to:"/apps",replace:!0}):e.jsx(zs,{title:"Staging Studio",children:e.jsx(_.Suspense,{fallback:e.jsx("div",{className:"flex min-h-[50vh] items-center justify-center",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:s})})}var sJe={};(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 ie=new OffscreenCanvas(1,1),te=ie.getContext("2d");te.fillRect(0,0,1,1);var ae=ie.transferToImageBitmap();te.createPattern(ae,"no-repeat")}catch{return!1}return!0}();function c(){}function d(ie){var te=n.exports.Promise,ae=te!==void 0?te:t.Promise;return typeof ae=="function"?new ae(ie):(ie(c,c),null)}var u=function(ie,te){return{transform:function(ae){if(ie)return ae;if(te.has(ae))return te.get(ae);var le=new OffscreenCanvas(ae.width,ae.height),be=le.getContext("2d");return be.drawImage(ae,0,0),te.set(ae,le),le},clear:function(){te.clear()}}}(o,new Map),h=function(){var ie=Math.floor(16.666666666666668),te,ae,le={},be=0;return typeof requestAnimationFrame=="function"&&typeof cancelAnimationFrame=="function"?(te=function(me){var he=Math.random();return le[he]=requestAnimationFrame(function pe(Ce){be===Ce||be+ie-1{const{data:t,error:n}=await q.from("celebration_queue").select("*").eq("user_id",s.id).is("seen_at",null).order("created_at",{ascending:!0});if(n)throw n;return t},enabled:!!(s!=null&&s.id),refetchOnWindowFocus:!0,staleTime:0})}function XTs(){const s=Bt();return mt({mutationFn:async t=>{const{error:n}=await q.from("celebration_queue").update({seen_at:new Date().toISOString()}).eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["celebrations"]})}})}function QTs(){const s=Bt(),{user:t}=hs();return mt({mutationFn:async n=>{const{error:r}=await q.from("celebration_queue").insert({user_id:n.user_id,celebration_type:n.celebration_type,title:n.title,message:n.message||null,points_amount:n.points_amount||null,created_by:t==null?void 0:t.id});if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["celebrations"]})}})}const JTs={points_earned:wl,listing_created:Jr,deal_closed:yd,custom:Da},Gpt={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"},Wpt=()=>{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 e6s(){const{user:s}=hs(),t=Bt(),{data:n}=ZTs(),r=XTs(),[a,i]=_.useState(null),[l,o]=_.useState(!1),c=_.useCallback(()=>{const p=Date.now()+3e3,f={startVelocity:30,spread:360,ticks:60,zIndex:9999},y=(g,b)=>Math.random()*(b-g)+g,v=setInterval(()=>{const g=p-Date.now();if(g<=0){clearInterval(v);return}const b=50*(g/3e3);Hpt({...f,particleCount:b,origin:{x:y(.1,.3),y:Math.random()-.2},colors:["#ff6b6b","#feca57","#48dbfb","#ff9ff3","#54a0ff","#5f27cd"]}),Hpt({...f,particleCount:b,origin:{x:y(.7,.9),y:Math.random()-.2},colors:["#ff6b6b","#feca57","#48dbfb","#ff9ff3","#54a0ff","#5f27cd"]})},250)},[]);_.useEffect(()=>{Wpt()||n&&n.length>0&&!a&&(i(n[0]),o(!0),setTimeout(c,100))},[n,a,c]);const d=async()=>{if(a){const m=a.id;o(!1),i(null),t.setQueryData(["celebrations","pending",s==null?void 0:s.id],p=>(p==null?void 0:p.filter(f=>f.id!==m))??[]),await r.mutateAsync(m)}};if(Wpt()||!a)return null;const u=JTs[a.celebration_type]||Da,h=Gpt[a.celebration_type]||Gpt.custom;return e.jsx(Ls,{open:l,onOpenChange:m=>!m&&d(),children:e.jsxs(Ps,{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(un,{className:"w-5 h-5 text-yellow-500 animate-pulse"}),e.jsx(un,{className:"w-5 h-5 text-yellow-500 animate-pulse delay-75"}),e.jsx(un,{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(B,{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 cn({className:s,...t}){return e.jsx("div",{className:At("animate-pulse rounded-md bg-muted",s),...t})}var SPe="Tabs",[t6s,Abr]=af(SPe,[iL]),HRt=iL(),[s6s,nJe]=t6s(SPe),GRt=_.forwardRef((s,t)=>{const{__scopeTabs:n,value:r,onValueChange:a,defaultValue:i,orientation:l="horizontal",dir:o,activationMode:c="automatic",...d}=s,u=DE(o),[h,m]=Ug({prop:r,onChange:a,defaultProp:i??"",caller:SPe});return e.jsx(s6s,{scope:n,baseId:Og(),value:h,onValueChange:m,orientation:l,dir:u,activationMode:c,children:e.jsx(ii.div,{dir:u,"data-orientation":l,...d,ref:t})})});GRt.displayName=SPe;var WRt="TabsList",KRt=_.forwardRef((s,t)=>{const{__scopeTabs:n,loop:r=!0,...a}=s,i=nJe(WRt,n),l=HRt(n);return e.jsx(WMe,{asChild:!0,...l,orientation:i.orientation,dir:i.dir,loop:r,children:e.jsx(ii.div,{role:"tablist","aria-orientation":i.orientation,...a,ref:t})})});KRt.displayName=WRt;var YRt="TabsTrigger",ZRt=_.forwardRef((s,t)=>{const{__scopeTabs:n,value:r,disabled:a=!1,...i}=s,l=nJe(YRt,n),o=HRt(n),c=JRt(l.baseId,r),d=eFt(l.baseId,r),u=r===l.value;return e.jsx(KMe,{asChild:!0,...o,focusable:!a,active:u,children:e.jsx(ii.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:wa(s.onMouseDown,h=>{!a&&h.button===0&&h.ctrlKey===!1?l.onValueChange(r):h.preventDefault()}),onKeyDown:wa(s.onKeyDown,h=>{[" ","Enter"].includes(h.key)&&l.onValueChange(r)}),onFocus:wa(s.onFocus,()=>{const h=l.activationMode!=="manual";!u&&!a&&h&&l.onValueChange(r)})})})});ZRt.displayName=YRt;var XRt="TabsContent",QRt=_.forwardRef((s,t)=>{const{__scopeTabs:n,value:r,forceMount:a,children:i,...l}=s,o=nJe(XRt,n),c=JRt(o.baseId,r),d=eFt(o.baseId,r),u=r===o.value,h=_.useRef(u);return _.useEffect(()=>{const m=requestAnimationFrame(()=>h.current=!1);return()=>cancelAnimationFrame(m)},[]),e.jsx(pg,{present:a||u,children:({present:m})=>e.jsx(ii.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})})});QRt.displayName=XRt;function JRt(s,t){return`${s}-trigger-${t}`}function eFt(s,t){return`${s}-content-${t}`}var n6s=GRt,tFt=KRt,sFt=ZRt,nFt=QRt;const Yr=n6s,Zr=_.forwardRef(({className:s,...t},n)=>e.jsx(tFt,{ref:n,className:At("inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",s),...t}));Zr.displayName=tFt.displayName;const Ht=_.forwardRef(({className:s,...t},n)=>e.jsx(sFt,{ref:n,className:At("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}));Ht.displayName=sFt.displayName;const Gt=_.forwardRef(({className:s,...t},n)=>e.jsx(nFt,{ref:n,className:At("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",s),...t}));Gt.displayName=nFt.displayName;const rte="#0d0d0d",hAe="#1a1a1a",hv="#c9a84c",Gre="#f0d78c",iC={captured:"lup_lead_captured_v1",stickyDismissed:"lup_sticky_dismissed_v1",exitShown:"lup_exit_shown_v1",savedListings:"lup_saved_listings_v1"};async function CPe(s){const t={...s,source_page:typeof window<"u"?window.location.pathname:null,user_agent:typeof navigator<"u"?navigator.userAgent:null,referrer:typeof document<"u"?document.referrer:null},{data:n,error:r}=await q.functions.invoke("public-site-lead",{body:t});if(r)throw r;try{localStorage.setItem(iC.captured,JSON.stringify({email:s.email,ts:Date.now()}))}catch{}return n}function rJe(){try{return!!localStorage.getItem(iC.captured)}catch{return!1}}function r6s(){try{const s=localStorage.getItem(iC.captured);return s?JSON.parse(s).email??null:null}catch{return null}}function aJe({open:s,onClose:t,children:n}){return _.useEffect(()=>{if(!s)return;const r=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=r}},[s]),s?mv.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, ${hAe} 0%, ${rte} 100%)`,border:`1px solid ${hv}33`,boxShadow:`0 30px 80px rgba(0,0,0,0.6), 0 0 0 1px ${hv}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(Qn,{className:"h-4 w-4"})}),n]})}),document.body):null}function iJe(){const[s,t]=_.useState({first_name:"",email:"",phone:"",area:""}),[n,r]=_.useState(!1),[a,i]=_.useState("");return{values:s,setValues:t,loading:n,setLoading:r,honeypot:a,setHoneypot:i}}function oJe({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(Fo,{className:"absolute left-3.5 top-1/2 -translate-y-1/2 h-4 w-4 text-white/40"}),e.jsx("input",{type:"text",placeholder:"First name",value:s.first_name,onChange:d=>t({...s,first_name:d.target.value}),className:o,style:c})]}),e.jsxs("div",{className:"relative",children:[e.jsx(ln,{className:"absolute left-3.5 top-1/2 -translate-y-1/2 h-4 w-4 text-white/40"}),e.jsx("input",{type:"email",required:!0,placeholder:"Email address",value:s.email,onChange:d=>t({...s,email:d.target.value}),className:o,style:c})]}),a&&e.jsxs("div",{className:"relative",children:[e.jsx(_a,{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(Xa,{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 lJe({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, ${Gre} 0%, ${hv} 100%)`,color:rte,boxShadow:`0 8px 24px ${hv}55`},children:s})}function Kpt({open:s,onClose:t,initialCriteria:n}){const{values:r,setValues:a,loading:i,setLoading:l,honeypot:o,setHoneypot:c}=iJe(),[d,u]=_.useState(!1),h=async m=>{if(m.preventDefault(),!!r.email){l(!0);try{await CPe({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(iC.stickyDismissed,"1")}catch{}setTimeout(t,2200)}catch{se.error("Something went wrong. Please try again.")}finally{l(!1)}}};return e.jsx(aJe,{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(Rg,{className:"h-4 w-4",style:{color:hv}}),e.jsx("span",{className:"text-xs uppercase tracking-[0.2em]",style:{color:Gre},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:`${hv}22`,border:`1px solid ${hv}55`},children:e.jsx(un,{className:"h-5 w-5",style:{color:hv}})}),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(oJe,{values:r,setValues:a,honeypot:o,setHoneypot:c}),e.jsx(lJe,{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 a6s(){const[s,t]=_.useState(!0),[n,r]=_.useState(!1);_.useEffect(()=>{try{const i=!!localStorage.getItem(iC.stickyDismissed)||rJe();t(i)}catch{t(!1)}},[]);const a=()=>{t(!0);try{localStorage.setItem(iC.stickyDismissed,"1")}catch{}};return s?e.jsx(Kpt,{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, ${hAe} 0%, ${rte} 100%)`,borderTop:`1px solid ${hv}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:`${hv}22`,border:`1px solid ${hv}55`},children:e.jsx(Rg,{className:"h-4 w-4",style:{color:hv}})}),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, ${Gre} 0%, ${hv} 100%)`,color:rte},children:"Get Alerts"}),e.jsx("button",{onClick:a,className:"p-2 text-white/50 hover:text-white transition","aria-label":"Dismiss",children:e.jsx(Qn,{className:"h-4 w-4"})})]})}),e.jsx(Kpt,{open:n,onClose:()=>r(!1)})]})}function i6s(){const[s,t]=_.useState(!1),n=_.useRef(!1);_.useEffect(()=>{try{if(sessionStorage.getItem(iC.exitShown)||rJe())return}catch{}const m=setTimeout(()=>{n.current=!0},8e3),p=f=>{if(n.current&&!(f.clientY>0)){t(!0);try{sessionStorage.setItem(iC.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}=iJe(),[d,u]=_.useState(!1),h=async m=>{if(m.preventDefault(),!!r.email){l(!0);try{await CPe({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{se.error("Something went wrong. Please try again.")}finally{l(!1)}}};return e.jsx(aJe,{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, ${rte} 0%, ${hAe} 60%, ${hv} 130%)`},children:e.jsx("div",{className:"absolute top-4 left-6",children:e.jsx("span",{className:"text-[10px] uppercase tracking-[0.25em]",style:{color:Gre},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:hAe,border:`1px solid ${hv}55`,boxShadow:"0 8px 24px rgba(0,0,0,0.5)"},children:e.jsx(un,{className:"h-6 w-6",style:{color:hv}})}),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(oJe,{values:r,setValues:a,honeypot:o,setHoneypot:c,showPhone:!1}),e.jsx(lJe,{type:"submit",disabled:i||!r.email,children:i?"Sending…":"Send My List"})]})]})]})})}function o6s(){const[s,t]=_.useState([]);_.useEffect(()=>{try{const o=localStorage.getItem(iC.savedListings);o&&t(JSON.parse(o))}catch{}},[]);const n=o=>{t(o);try{localStorage.setItem(iC.savedListings,JSON.stringify(o))}catch{}},r=_.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 l6s({listingId:s,listingAddress:t,className:n}){const{has:r,add:a,remove:i}=o6s(),l=r(s),[o,c]=_.useState(!1),d=()=>{if(l){i(s);return}if(rJe()){a(s),se.success("Saved to your favorites"),CPe({lead_type:"saved_listing",email:r6s()||"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(Do,{className:`h-5 w-5 ${l?"fill-current":""}`})}),e.jsx(c6s,{open:o,onClose:()=>c(!1),listingId:s,listingAddress:t,onSaved:()=>a(s)})]})}function c6s({open:s,onClose:t,listingId:n,listingAddress:r,onSaved:a}){const{values:i,setValues:l,loading:o,setLoading:c,honeypot:d,setHoneypot:u}=iJe(),h=async m=>{if(m.preventDefault(),!!i.email){c(!0);try{await CPe({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(),se.success("Saved to your favorites"),t()}catch{se.error("Something went wrong. Please try again.")}finally{c(!1)}}};return e.jsx(aJe,{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(Do,{className:"h-4 w-4",style:{color:hv}}),e.jsx("span",{className:"text-xs uppercase tracking-[0.2em]",style:{color:Gre},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(oJe,{values:i,setValues:l,honeypot:d,setHoneypot:u}),e.jsx(lJe,{type:"submit",disabled:o||!i.email,children:o?"Saving…":"Save Home"})]})]})})}var rFt=["PageUp","PageDown"],aFt=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],iFt={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},cW="Slider",[U$e,d6s,u6s]=KG(cW),[oFt,Ebr]=af(cW,[u6s]),[h6s,APe]=oFt(cW),lFt=_.forwardRef((s,t)=>{const{name:n,min:r=0,max:a=100,step:i=1,orientation:l="horizontal",disabled:o=!1,minStepsBetweenThumbs:c=0,defaultValue:d=[r],value:u,onValueChange:h=()=>{},onValueCommit:m=()=>{},inverted:p=!1,form:f,...y}=s,v=_.useRef(new Set),g=_.useRef(0),j=l==="horizontal"?m6s:p6s,[S=[],C]=Ug({prop:u,defaultProp:d,onChange:O=>{var G;(G=[...v.current][g.current])==null||G.focus(),h(O)}}),E=_.useRef(S);function P(O){const V=v6s(S,O);D(O,V)}function M(O){D(O,g.current)}function I(){const O=E.current[g.current];S[g.current]!==O&&m(S)}function D(O,V,{commit:G}={commit:!1}){const $=j6s(i),H=N6s(Math.round((O-r)/i)*i+r,$),Y=tte(H,[r,a]);C((Z=[])=>{const ne=g6s(Z,Y,V);if(w6s(ne,c*i)){g.current=ne.indexOf(Y);const ce=String(ne)!==String(Z);return ce&&G&&m(ne),ce?ne:Z}else return Z})}return e.jsx(h6s,{scope:s.__scopeSlider,name:n,disabled:o,min:r,max:a,valueIndexToChangeRef:g,thumbs:v.current,values:S,orientation:l,form:f,children:e.jsx(U$e.Provider,{scope:s.__scopeSlider,children:e.jsx(U$e.Slot,{scope:s.__scopeSlider,children:e.jsx(j,{"aria-disabled":o,"data-disabled":o?"":void 0,...y,ref:t,onPointerDown:wa(y.onPointerDown,()=>{o||(E.current=S)}),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,S.length-1,{commit:!0}),onStepKeyDown:({event:O,direction:V})=>{if(!o){const H=rFt.includes(O.key)||O.shiftKey&&aFt.includes(O.key)?10:1,Y=g.current,Z=S[Y],ne=i*H*V;D(Z+ne,Y,{commit:!0})}}})})})})});lFt.displayName=cW;var[cFt,dFt]=oFt(cW,{startEdge:"left",endEdge:"right",size:"width",direction:1}),m6s=_.forwardRef((s,t)=>{const{min:n,max:r,dir:a,inverted:i,onSlideStart:l,onSlideMove:o,onSlideEnd:c,onStepKeyDown:d,...u}=s,[h,m]=_.useState(null),p=Qo(t,j=>m(j)),f=_.useRef(void 0),y=DE(a),v=y==="ltr",g=v&&!i||!v&&i;function b(j){const S=f.current||h.getBoundingClientRect(),C=[0,S.width],P=cJe(C,g?[n,r]:[r,n]);return f.current=S,P(j-S.left)}return e.jsx(cFt,{scope:s.__scopeSlider,startEdge:g?"left":"right",endEdge:g?"right":"left",direction:g?1:-1,size:"width",children:e.jsx(uFt,{dir:y,"data-orientation":"horizontal",...u,ref:p,style:{...u.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:j=>{const S=b(j.clientX);l==null||l(S)},onSlideMove:j=>{const S=b(j.clientX);o==null||o(S)},onSlideEnd:()=>{f.current=void 0,c==null||c()},onStepKeyDown:j=>{const C=iFt[g?"from-left":"from-right"].includes(j.key);d==null||d({event:j,direction:C?-1:1})}})})}),p6s=_.forwardRef((s,t)=>{const{min:n,max:r,inverted:a,onSlideStart:i,onSlideMove:l,onSlideEnd:o,onStepKeyDown:c,...d}=s,u=_.useRef(null),h=Qo(t,u),m=_.useRef(void 0),p=!a;function f(y){const v=m.current||u.current.getBoundingClientRect(),g=[0,v.height],j=cJe(g,p?[r,n]:[n,r]);return m.current=v,j(y-v.top)}return e.jsx(cFt,{scope:s.__scopeSlider,startEdge:p?"bottom":"top",endEdge:p?"top":"bottom",size:"height",direction:p?1:-1,children:e.jsx(uFt,{"data-orientation":"vertical",...d,ref:h,style:{...d.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:y=>{const v=f(y.clientY);i==null||i(v)},onSlideMove:y=>{const v=f(y.clientY);l==null||l(v)},onSlideEnd:()=>{m.current=void 0,o==null||o()},onStepKeyDown:y=>{const g=iFt[p?"from-bottom":"from-top"].includes(y.key);c==null||c({event:y,direction:g?-1:1})}})})}),uFt=_.forwardRef((s,t)=>{const{__scopeSlider:n,onSlideStart:r,onSlideMove:a,onSlideEnd:i,onHomeKeyDown:l,onEndKeyDown:o,onStepKeyDown:c,...d}=s,u=APe(cW,n);return e.jsx(ii.span,{...d,ref:t,onKeyDown:wa(s.onKeyDown,h=>{h.key==="Home"?(l(h),h.preventDefault()):h.key==="End"?(o(h),h.preventDefault()):rFt.concat(aFt).includes(h.key)&&(c(h),h.preventDefault())}),onPointerDown:wa(s.onPointerDown,h=>{const m=h.target;m.setPointerCapture(h.pointerId),h.preventDefault(),u.thumbs.has(m)?m.focus():r(h)}),onPointerMove:wa(s.onPointerMove,h=>{h.target.hasPointerCapture(h.pointerId)&&a(h)}),onPointerUp:wa(s.onPointerUp,h=>{const m=h.target;m.hasPointerCapture(h.pointerId)&&(m.releasePointerCapture(h.pointerId),i(h))})})}),hFt="SliderTrack",mFt=_.forwardRef((s,t)=>{const{__scopeSlider:n,...r}=s,a=APe(hFt,n);return e.jsx(ii.span,{"data-disabled":a.disabled?"":void 0,"data-orientation":a.orientation,...r,ref:t})});mFt.displayName=hFt;var q$e="SliderRange",pFt=_.forwardRef((s,t)=>{const{__scopeSlider:n,...r}=s,a=APe(q$e,n),i=dFt(q$e,n),l=_.useRef(null),o=Qo(t,l),c=a.values.length,d=a.values.map(m=>gFt(m,a.min,a.max)),u=c>1?Math.min(...d):0,h=100-Math.max(...d);return e.jsx(ii.span,{"data-orientation":a.orientation,"data-disabled":a.disabled?"":void 0,...r,ref:o,style:{...s.style,[i.startEdge]:u+"%",[i.endEdge]:h+"%"}})});pFt.displayName=q$e;var $$e="SliderThumb",fFt=_.forwardRef((s,t)=>{const n=d6s(s.__scopeSlider),[r,a]=_.useState(null),i=Qo(t,o=>a(o)),l=_.useMemo(()=>r?n().findIndex(o=>o.ref.current===r):-1,[n,r]);return e.jsx(f6s,{...s,ref:i,index:l})}),f6s=_.forwardRef((s,t)=>{const{__scopeSlider:n,index:r,name:a,...i}=s,l=APe($$e,n),o=dFt($$e,n),[c,d]=_.useState(null),u=Qo(t,b=>d(b)),h=c?l.form||!!c.closest("form"):!0,m=Cre(c),p=l.values[r],f=p===void 0?0:gFt(p,l.min,l.max),y=y6s(r,l.values.length),v=m==null?void 0:m[o.size],g=v?b6s(v,f,o.direction):0;return _.useEffect(()=>{if(c)return l.thumbs.add(c),()=>{l.thumbs.delete(c)}},[c,l.thumbs]),e.jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[o.startEdge]:`calc(${f}% + ${g}px)`},children:[e.jsx(U$e.ItemSlot,{scope:s.__scopeSlider,children:e.jsx(ii.span,{role:"slider","aria-label":s["aria-label"]||y,"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:wa(s.onFocus,()=>{l.valueIndexToChangeRef.current=r})})}),h&&e.jsx(xFt,{name:a??(l.name?l.name+(l.values.length>1?"[]":""):void 0),form:l.form,value:p},r)]})});fFt.displayName=$$e;var x6s="RadioBubbleInput",xFt=_.forwardRef(({__scopeSlider:s,value:t,...n},r)=>{const a=_.useRef(null),i=Qo(a,r),l=$re(t);return _.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(ii.input,{style:{display:"none"},...n,ref:i,defaultValue:t})});xFt.displayName=x6s;function g6s(s=[],t,n){const r=[...s];return r[n]=t,r.sort((a,i)=>a-i)}function gFt(s,t,n){const i=100/(n-t)*(s-t);return tte(i,[0,100])}function y6s(s,t){return t>2?`Value ${s+1} of ${t}`:t===2?["Minimum","Maximum"][s]:void 0}function v6s(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 b6s(s,t,n){const r=s/2,i=cJe([0,50],[0,r]);return(r-i(t)*n)*n}function _6s(s){return s.slice(0,-1).map((t,n)=>s[n+1]-t)}function w6s(s,t){if(t>0){const n=_6s(s);return Math.min(...n)>=t}return!0}function cJe(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 j6s(s){return(String(s).split(".")[1]||"").length}function N6s(s,t){const n=Math.pow(10,t);return Math.round(s*n)/n}var yFt=lFt,k6s=mFt,S6s=pFt,C6s=fFt;const kx=_.forwardRef(({className:s,...t},n)=>e.jsxs(yFt,{ref:n,className:At("relative flex w-full touch-none select-none items-center",s),...t,children:[e.jsx(k6s,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:e.jsx(S6s,{className:"absolute h-full bg-primary"})}),e.jsx(C6s,{className:"block h-5 w-5 rounded-full border-2 border-primary bg-background ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50"})]}));kx.displayName=yFt.displayName;const A6s=s=>at({queryKey:["public-listings",s],queryFn:async()=>{let t=q.from("listings").select(` id, slug, agent_id, property_address, city, state, neighborhood, price, property_type, listing_class, status, bedrooms, bathrooms, square_footage, lot_size, year_built, has_hoa, description, latitude, longitude, created_at, updated_at, photos:listing_photos(id, photo_url, is_primary), agent:profiles!listings_agent_id_fkey(id, name, email, phone, avatar_url, brokerage_name, brokerage:brokerages(name)) `).eq("is_approved",!0).eq("is_public",!0).or("lifecycle_stage.is.null,lifecycle_stage.neq.pitch").or("listing_class.is.null,listing_class.neq.commercial").order("created_at",{ascending:!1});if(s!=null&&s.status?t=t.eq("status",s.status):t=t.neq("status","sold"),s!=null&&s.propertyType&&(t=t.eq("property_type",s.propertyType)),s!=null&&s.city){const a=s.city.replace(/[%,()]/g," ").trim();if(a){const i=`%${a}%`;t=t.or(`city.ilike.${i},neighborhood.ilike.${i},property_address.ilike.${i}`)}}s!=null&&s.minPrice&&(t=t.gte("price",s.minPrice)),s!=null&&s.maxPrice&&(t=t.lte("price",s.maxPrice));const{data:n,error:r}=await t;if(r)throw r;return n}}),E6s=()=>at({queryKey:["public-listings-search-index"],staleTime:5*60*1e3,queryFn:async()=>{const{data:s,error:t}=await q.from("listings").select("city, state, neighborhood, property_address").eq("is_approved",!0).eq("is_public",!0);if(t)throw t;const n=new Map,r=new Map,a=new Map;return(s||[]).forEach(i=>{if(i.city){const l=`${i.city}|${i.state||""}`.toLowerCase(),o=i.state?`${i.city}, ${i.state}`:i.city,c=n.get(l);c?c.count++:n.set(l,{label:o,city:i.city,state:i.state,count:1})}if(i.neighborhood){const l=`${i.neighborhood}|${i.city||""}`.toLowerCase(),o=i.city?`${i.neighborhood} — ${i.city}`:i.neighborhood,c=r.get(l);c?c.count++:r.set(l,{label:o,city:i.city||"",neighborhood:i.neighborhood,count:1})}if(i.property_address){const l=String(i.property_address).match(/\b(\d{5})(?:-\d{4})?\b/);if(l){const o=l[1],c=a.get(o);c?c.count++:a.set(o,{label:o,zip:o,count:1})}}}),{cities:Array.from(n.values()).sort((i,l)=>l.count-i.count),neighborhoods:Array.from(r.values()).sort((i,l)=>l.count-i.count),zips:Array.from(a.values()).sort((i,l)=>l.count-i.count)}}}),T6s=s=>at({queryKey:["public-listing",s],queryFn:async()=>{const t=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(s);let n=q.from("listings").select(` id, slug, agent_id, property_address, city, state, neighborhood, price, property_type, listing_class, status, bedrooms, bathrooms, square_footage, lot_size, year_built, has_hoa, description, agent_notes, agent_notes_public, mls_link, video_link, video_id, latitude, longitude, page_config, page_theme, created_at, updated_at, co_agent_name, co_agent_email, co_agent_phone, co_agent_brokerage, co_agent_photo_url, photos:listing_photos(id, photo_url, is_primary, sort_order), agent:profiles!listings_agent_id_fkey(id, name, email, phone, avatar_url, brokerage_name, brokerage:brokerages(name)), video:agent_videos!listings_video_id_fkey(id, playback_url, thumbnail_url, title, duration_seconds, bunny_video_id) `).eq("is_approved",!0).eq("is_public",!0);t?n=n.eq("id",s):n=n.eq("slug",s);const{data:r,error:a}=await n.single();if(a)throw a;const i=r;return Array.isArray(i==null?void 0:i.photos)&&(i.photos=[...i.photos].sort((l,o)=>(l.sort_order??0)-(o.sort_order??0)||(o.is_primary?1:0)-(l.is_primary?1:0))),i},enabled:!!s}),M6s=()=>mt({mutationFn:async({listingId:s,agentId:t,firstName:n,lastName:r,email:a,phone:i,shareToken:l,leadType:o="info_request",preferredDate:c,preferredTime:d,showingMode:u,message:h})=>{let m=null,p=null;if(l){const{data:b}=await q.from("listing_shares").select("id, sharing_agent_id").eq("share_token",l).eq("listing_id",s).maybeSingle();b&&(m=b.id,p=b.sharing_agent_id)}const f=crypto.randomUUID(),y={id:f},{error:v}=await q.from("listing_leads").insert({id:f,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});if(v)throw v;const{error:g}=await q.functions.invoke("process-listing-lead",{body:{leadId:y.id}});return g&&console.error("Error processing lead:",g),y}}),P6s=()=>mt({mutationFn:async s=>{const{error:t}=await q.rpc("increment_listing_share_click",{p_share_token:s});if(t)throw t}}),DP={sale:"For Sale",lease:"For Lease",sale_or_lease:"For Sale or Lease",investment:"Investment Offering"},hL={office:"Office",retail:"Retail",industrial:"Industrial",flex:"Flex / R&D",multifamily:"Multifamily",land:"Land",medical:"Medical",hospitality:"Hospitality",self_storage:"Self Storage",mixed_use:"Mixed Use",special_purpose:"Special Purpose"},L6s=["NNN","Modified Gross","Full Service","Gross","Absolute Net","Ground Lease"],I6s={sf_year:"/SF/YR",sf_month:"/SF/MO",month:"/MO"},V$e={om:"Offering Memorandum",flyer:"Flyer",rent_roll:"Rent Roll",financials:"Financials",survey:"Survey",site_plan:"Site Plan",lease:"Lease Documents",other:"Other"},Ypt={public:"Open download",email:"Email required",nda:"NDA required"},H$e={principal:"Principal / Investor",broker:"Broker",tenant:"Tenant / User",lender:"Lender",other:"Other"},bOe=[{key:"pitch",label:"Pitch",blurb:"Competing for the assignment"},{key:"won",label:"Won",blurb:"Assignment secured"},{key:"launched",label:"Launch",blurb:"Microsite & materials live"},{key:"marketing",label:"Market",blurb:"Campaign in market"},{key:"under_contract",label:"Under Contract",blurb:"Deal in escrow"},{key:"closed",label:"Closed",blurb:"Transaction complete"}],j4e=[{key:"photos",label:"Professional photography uploaded",detail:"At least 6 images for the microsite hero and gallery"},{key:"financials",label:"Financial snapshot completed",detail:"NOI, cap rate, occupancy or lease rate entered"},{key:"highlights",label:"Investment highlights written",detail:"3–6 reasons this opportunity matters"},{key:"om",label:"Offering Memorandum uploaded",detail:"Gated OM available for qualified prospects"},{key:"microsite",label:"Microsite published",detail:"Public commercial microsite is live"},{key:"email",label:"Broker & investor email sent",detail:"First distribution to your database"},{key:"social",label:"Social / LinkedIn announcement",detail:"Launch post published"},{key:"signage",label:"Signage & QR deployed",detail:"On-site QR code linking to the microsite"}],vFt=[{label:"Day 1 — Positioning & pricing",detail:"Finalize the pricing strategy, opportunity narrative and target buyer/tenant profile."},{label:"Day 2–4 — Institutional-grade materials",detail:"Photography, Offering Memorandum, investor teaser and branded flyer produced."},{label:"Day 5 — Property microsite goes live",detail:"Dedicated commercial microsite with gated OM, tour requests and full analytics."},{label:"Week 1 — Targeted broker & investor outreach",detail:"Direct email to qualified buyers, brokers and 1031 investors in the LevelUp database."},{label:"Week 2 — Digital & social distribution",detail:"LinkedIn campaign, syndication and QR-coded on-site signage."},{label:"Weekly — Owner activity reporting",detail:"Every week you receive views, OM requests, downloads, tours and prospect-level interest."}];function K2(s,t=0){return s==null||Number.isNaN(Number(s))?null:new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:t}).format(Number(s))}function Zpt(s){if(s==null)return null;const t=Number(s);return Number.isNaN(t)?null:t>=1e6?`$${(t/1e6).toFixed(t>=1e7?1:2).replace(/\.0+$/,"")}M`:t>=1e3?`$${Math.round(t/1e3)}K`:K2(t)}function LA(s){return s==null?null:`${new Intl.NumberFormat("en-US").format(Number(s))} SF`}function mAe(s,t=2){return s==null?null:`${Number(s).toFixed(t).replace(/\.?0+$/,"")}%`}function G$e(s){if(!(s!=null&&s.lease_rate))return null;const t=I6s[s.lease_rate_unit||"sf_year"]??"";return`${s.lease_rate_unit==="month"?K2(s.lease_rate):`$${Number(s.lease_rate).toFixed(2).replace(/\.00$/,"")}`}${t}${s.lease_type?` ${s.lease_type}`:""}`}function EH(s,t){if(!s)return K2(t)??"Price on request";if(s.deal_type==="lease")return G$e(s)??"Rate on request";const n=s.asking_price??t;if(s.deal_type==="sale_or_lease"){const r=[K2(n),G$e(s)].filter(Boolean);return r.length?r.join(" · "):"Price on request"}return K2(n)??"Price on request"}function cP(s,t){return t!=null&&t.opportunity_title?t.opportunity_title:t!=null&&t.hide_address||t!=null&&t.is_confidential?`Confidential ${t!=null&&t.commercial_type?hL[t.commercial_type]:"Commercial"} Opportunity`:s.property_address||`${s.city??""}, ${s.state??""}`}function Wre(s,t){const n=(t==null?void 0:t.submarket)||s.neighborhood,r=[s.city,s.state].filter(Boolean).join(", ");return n?`${n} · ${r}`:r}function D6s(s,t){var i;const n=(s==null?void 0:s.launch_checklist)??{},r=[],a={photos:t.photoCount>=6,financials:!!(s!=null&&s.noi||s!=null&&s.cap_rate||s!=null&&s.lease_rate||s!=null&&s.occupancy_pct),highlights:(((i=s==null?void 0:s.investment_highlights)==null?void 0:i.length)??0)>=3,om:t.hasOm,microsite:t.isPublic};for(const l of j4e)(a[l.key]||n[l.key])&&r.push(l.key);return{done:r,total:j4e.length,score:Math.round(r.length/j4e.length*100)}}const Xpt={om_download:10,om_request:9,tour_request:15,inquiry:12,doc_download:8,om_view:5,gallery_view:2,page_view:1,contact_click:4,share_click:2,email_click:3,email_open:1,map_view:1};function Qpt(s){return s>=30?{label:"Hot",tone:"bg-amber-500/15 text-amber-600 border-amber-500/30"}:s>=12?{label:"Warm",tone:"bg-orange-500/10 text-orange-600 border-orange-500/20"}:{label:"Tracking",tone:"bg-muted text-muted-foreground border-border"}}const R6s="https://commercial.relevelup.com",oC=q;function bFt(s){return at({queryKey:["commercial-details",s],queryFn:async()=>{const{data:t,error:n}=await oC.from("commercial_listing_details").select("*").eq("listing_id",s).maybeSingle();if(n)throw n;return t??null},enabled:!!s})}function _Ft(){const s=Bt(),{user:t}=hs();return mt({mutationFn:async({listingId:n,values:r})=>{const{data:a,error:i}=await oC.from("commercial_listing_details").upsert({listing_id:n,agent_id:t==null?void 0:t.id,...r},{onConflict:"listing_id"}).select().single();if(i)throw i;return a},onSuccess:(n,r)=>{s.invalidateQueries({queryKey:["commercial-details",r.listingId]}),s.invalidateQueries({queryKey:["listing",r.listingId]})}})}function F6s(s){return at({queryKey:["commercial-pitch",s],queryFn:async()=>{const{data:t,error:n}=await oC.from("commercial_pitch_details").select("*").eq("listing_id",s).maybeSingle();if(n)throw n;return t??null},enabled:!!s})}function wFt(){const s=Bt(),{user:t}=hs();return mt({mutationFn:async({listingId:n,values:r})=>{const{data:a,error:i}=await oC.from("commercial_pitch_details").upsert({listing_id:n,agent_id:t==null?void 0:t.id,...r},{onConflict:"listing_id"}).select().single();if(i)throw i;return a},onSuccess:(n,r)=>s.invalidateQueries({queryKey:["commercial-pitch",r.listingId]})})}function jFt(){const s=Bt();return mt({mutationFn:async({listingId:t,stage:n,lostReason:r})=>{const a=n==="won",i=n==="lost",l={lifecycle_stage:n};a&&(l.status="coming_soon"),i&&(l.is_public=!1,l.allow_sharing=!1);const{error:o}=await oC.from("listings").update(l).eq("id",t);if(o)throw o;return(a||i)&&await oC.from("commercial_pitch_details").update({outcome:a?"won":"lost",won_at:a?new Date().toISOString():null,lost_at:i?new Date().toISOString():null,lost_reason:i?r??null:null}).eq("listing_id",t),n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["listing",n.listingId]}),s.invalidateQueries({queryKey:["commercial-pitch",n.listingId]}),s.invalidateQueries({queryKey:["my-listings"]}),s.invalidateQueries({queryKey:["listings"]})}})}function O6s(){const s=Bt();return mt({mutationFn:async({listingId:t,values:n})=>{const{error:r}=await oC.from("listings").update(n).eq("id",t);if(r)throw r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["listing",n.listingId]}),s.invalidateQueries({queryKey:["my-listings"]})}})}function dJe(s,t=90){return at({queryKey:["commercial-engagement",s,t],queryFn:async()=>{const n=new Date(Date.now()-t*864e5).toISOString(),{data:r,error:a}=await oC.from("commercial_engagement_events").select("*").eq("listing_id",s).gte("created_at",n).order("created_at",{ascending:!1}).limit(1e3);if(a)throw a;return r??[]},enabled:!!s})}function uJe(s){return at({queryKey:["commercial-leads",s],queryFn:async()=>{const{data:t,error:n}=await oC.from("listing_leads").select("*").eq("listing_id",s).order("created_at",{ascending:!1});if(n)throw n;return t??[]},enabled:!!s})}const Jpt="lu_commercial_session";function NFt(){try{let s=localStorage.getItem(Jpt);return s||(s=crypto.randomUUID(),localStorage.setItem(Jpt,s)),s}catch{return"anonymous"}}async function bB(s,t,n={}){try{await oC.from("commercial_engagement_events").insert({listing_id:s,event_type:t,session_id:NFt(),source:typeof document<"u"&&document.referrer||null,metadata:n})}catch{}}const z6s={om_request:{eyebrow:"Confidential materials",title:"Request the Offering Memorandum",blurb:"Complete the form below and the offering package will be released to you immediately.",cta:"Request access"},tour_request:{eyebrow:"Property tour",title:"Schedule a tour",blurb:"Tell us who you represent and preferred timing — the listing broker will confirm directly.",cta:"Request tour"},investor_inquiry:{eyebrow:"Investment inquiry",title:"Request information",blurb:"Send a note to the listing broker about this opportunity.",cta:"Send inquiry"}};function B6s({open:s,onOpenChange:t,listingId:n,kind:r,documentId:a,requiresNda:i,brokerName:l}){const o=z6s[r],[c,d]=_.useState({firstName:"",lastName:"",email:"",phone:"",company:"",role:"principal",message:""}),[u,h]=_.useState(!1),[m,p]=_.useState(!1),[f,y]=_.useState(null),v=async()=>{if(!c.firstName.trim()||!c.email.trim()){se.error("Name and email are required");return}if(i&&r==="om_request"&&!u){se.error("Please acknowledge the confidentiality terms");return}p(!0);try{const{data:g,error:b}=await q.functions.invoke("commercial-lead",{body:{listingId:n,documentId:a??null,leadType:r,firstName:c.firstName,lastName:c.lastName,email:c.email,phone:c.phone||null,company:c.company||null,role:c.role,message:c.message||null,ndaAccepted:u,sessionId:NFt()}});if(b)throw b;if(g!=null&&g.error)throw new Error(g.error);y({signedUrl:(g==null?void 0:g.signedUrl)??null,fileName:(g==null?void 0:g.fileName)??null}),g!=null&&g.signedUrl&&window.open(g.signedUrl,"_blank")}catch(g){se.error(g.message||"Something went wrong. Please try again.")}finally{p(!1)}};return e.jsx(Ls,{open:s,onOpenChange:g=>{t(g),g||y(null)},children:e.jsxs(Ps,{className:"max-w-lg overflow-hidden border-white/10 bg-[#0b0f14] p-0 text-white",children:[e.jsxs("div",{className:"border-b border-white/10 bg-gradient-to-b from-white/[0.06] to-transparent px-7 py-6",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.24em] text-white/45",children:o.eyebrow}),e.jsx("h2",{className:"mt-2 font-serif text-2xl",children:f?"Access granted":o.title}),e.jsx("p",{className:"mt-1.5 text-sm text-white/60",children:f?f.signedUrl?"Your download has opened in a new tab. The secure link expires in 30 minutes.":`Your request has been sent${l?` to ${l}`:""}. You'll hear back shortly.`:o.blurb})]}),f?e.jsxs("div",{className:"space-y-4 px-7 py-7",children:[e.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-emerald-400/20 bg-emerald-400/10 px-4 py-3",children:[e.jsx(Er,{className:"h-5 w-5 text-emerald-400"}),e.jsx("p",{className:"text-sm text-white/80",children:f.fileName??"Request received"})]}),f.signedUrl&&e.jsx(B,{className:"w-full",onClick:()=>window.open(f.signedUrl,"_blank"),children:"Download again"}),e.jsx(B,{variant:"ghost",className:"w-full text-white/60 hover:text-white",onClick:()=>t(!1),children:"Close"})]}):e.jsxs("div",{className:"space-y-4 px-7 py-6",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsx(yI,{label:"First name *",children:e.jsx(xe,{value:c.firstName,onChange:g=>d({...c,firstName:g.target.value}),className:"border-white/15 bg-white/5 text-white"})}),e.jsx(yI,{label:"Last name",children:e.jsx(xe,{value:c.lastName,onChange:g=>d({...c,lastName:g.target.value}),className:"border-white/15 bg-white/5 text-white"})})]}),e.jsx(yI,{label:"Email *",children:e.jsx(xe,{type:"email",value:c.email,onChange:g=>d({...c,email:g.target.value}),className:"border-white/15 bg-white/5 text-white"})}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsx(yI,{label:"Company",children:e.jsx(xe,{value:c.company,onChange:g=>d({...c,company:g.target.value}),className:"border-white/15 bg-white/5 text-white"})}),e.jsx(yI,{label:"Phone",children:e.jsx(xe,{value:c.phone,onChange:g=>d({...c,phone:g.target.value}),className:"border-white/15 bg-white/5 text-white"})})]}),e.jsx(yI,{label:"I am a *",children:e.jsxs(is,{value:c.role,onValueChange:g=>d({...c,role:g}),children:[e.jsx(rs,{className:"border-white/15 bg-white/5 text-white",children:e.jsx(ls,{})}),e.jsx(as,{children:Object.entries(H$e).map(([g,b])=>e.jsx(He,{value:g,children:b},g))})]})}),r!=="om_request"&&e.jsx(yI,{label:"Message",children:e.jsx(Ms,{rows:3,value:c.message,onChange:g=>d({...c,message:g.target.value}),className:"border-white/15 bg-white/5 text-white",placeholder:r==="tour_request"?"Preferred dates and times…":"Your question…"})}),i&&r==="om_request"&&e.jsxs("label",{className:"flex cursor-pointer items-start gap-3 rounded-xl border border-white/10 bg-white/[0.04] p-3",children:[e.jsx($a,{checked:u,onCheckedChange:g=>h(!!g),className:"mt-0.5 border-white/30"}),e.jsxs("span",{className:"text-xs leading-relaxed text-white/65",children:[e.jsx(Dm,{className:"mr-1 inline h-3.5 w-3.5"}),"I acknowledge these materials are confidential and agree not to distribute them without the listing broker's written consent."]})]}),e.jsxs(B,{className:"w-full",size:"lg",onClick:v,disabled:m,children:[m?e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(ec,{className:"mr-2 h-4 w-4"}),o.cta]}),e.jsx("p",{className:"text-center text-[11px] text-white/40",children:"Your information is shared only with the listing broker."})]})]})})}function yI({label:s,children:t}){return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-[11px] font-medium uppercase tracking-wider text-white/50",children:s}),t]})}function hJe(s){if(!s)return[];const t=[],n=(r,a)=>{a&&t.push({label:r,value:a})};return n("Cap Rate",mAe(s.cap_rate)),n("NOI",Zpt(s.noi)),n("Occupancy",s.occupancy_pct!=null?`${Math.round(Number(s.occupancy_pct))}%`:null),n("Building SF",LA(s.building_sf)),n("Available SF",LA(s.available_sf)),n("Lot Size",s.lot_acres!=null?`${Number(s.lot_acres)} AC`:null),n("Units",s.units!=null?String(s.units):null),n("Price / SF",s.price_per_sf!=null?K2(s.price_per_sf,2):null),n("Price / Unit",Zpt(s.price_per_unit)),n("Lease Rate",s.deal_type!=="sale"?G$e(s):null),n("Year Built",null),n("Zoning",s.zoning??null),t}function kFt({details:s,className:t="",tone:n="light"}){const r=hJe(s).slice(0,8);if(!r.length)return null;const a=n==="dark";return e.jsx("div",{className:`grid gap-px overflow-hidden rounded-xl border ${a?"border-white/10 bg-white/10":"bg-border"} sm:grid-cols-2 lg:grid-cols-4 ${t}`,children:r.map(i=>e.jsxs("div",{className:`${a?"bg-[#0b0f14]":"bg-card"} px-5 py-4`,children:[e.jsx("p",{className:`text-[10px] font-semibold uppercase tracking-[0.18em] ${a?"text-white/45":"text-muted-foreground"}`,children:i.label}),e.jsx("p",{className:`mt-1.5 text-xl font-semibold tabular-nums ${a?"text-white":""}`,children:i.value})]},i.label))})}function U6s(s){return at({queryKey:["commercial-microsite",s],queryFn:async()=>{const{data:t,error:n}=await q.functions.invoke("commercial-public",{body:{slug:s}});if(n)throw n;if(t!=null&&t.error)throw new Error(t.error);return t},enabled:!!s})}function q6s({slug:s}){var O,V;const{data:t,isLoading:n,error:r}=U6s(s),[a,i]=_.useState(null),[l,o]=_.useState(null),c=t==null?void 0:t.listing,d=(t==null?void 0:t.details)??void 0,u=(t==null?void 0:t.documents)??[],h=(c==null?void 0:c.photos)??[],m=c==null?void 0:c.agent,p=!!(d!=null&&d.is_confidential||d!=null&&d.hide_address),f=_.useMemo(()=>hJe(d).slice(0,8),[d]);if(_.useEffect(()=>{c!=null&&c.id&&bB(c.id,"page_view",{slug:s})},[c==null?void 0:c.id,s]),_.useEffect(()=>{if(a===null)return;const G=$=>{$.key==="Escape"&&i(null),$.key==="ArrowRight"&&i(H=>H===null?H:(H+1)%h.length),$.key==="ArrowLeft"&&i(H=>H===null?H:(H-1+h.length)%h.length)};return window.addEventListener("keydown",G),()=>window.removeEventListener("keydown",G)},[a,h.length]),n)return e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-[#0b0f14]",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-2 border-white/20 border-t-white/70"})});if(r||!c)return e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-[#0b0f14] px-6 text-center text-white/60",children:"This offering is no longer available."});const y=cP(c,d),v=Wre(c,d),g=c.latitude&&c.longitude?`${c.latitude},${c.longitude}`:p?[d==null?void 0:d.submarket,c.city,c.state].filter(Boolean).join(", ")||null:[c.property_address,c.city,c.state].filter(Boolean).join(", ")||null,b=(O=h[0])==null?void 0:O.photo_url,j=(d==null?void 0:d.tenants)??[],S=(d==null?void 0:d.spaces)??[],C=(d==null?void 0:d.demographics)??{},E=(d==null?void 0:d.traffic_counts)??[],P=(d==null?void 0:d.investment_highlights)??[],M=(d==null?void 0:d.property_highlights)??[],I=["radius_1","radius_3","radius_5"].some(G=>(C==null?void 0:C[G])&&Object.values(C[G]).some(Boolean)),D=(G,$)=>{o({kind:G,documentId:$}),bB(c.id,G==="om_request"?"om_request":G,{})};return e.jsxs("div",{className:"min-h-screen bg-[#0b0f14] text-white antialiased",children:[e.jsxs(ul,{children:[e.jsx("title",{children:`${y} | ${v}`}),e.jsx("meta",{name:"description",content:(c.description??"").slice(0,155)||`${DP[(d==null?void 0:d.deal_type)??"sale"]} — ${v}`}),p&&e.jsx("meta",{name:"robots",content:"noindex,nofollow"}),e.jsx("meta",{property:"og:title",content:y}),e.jsx("meta",{property:"og:type",content:"website"})]}),e.jsx("header",{className:"fixed inset-x-0 top-0 z-40 border-b border-white/10 bg-[#0b0f14]/80 backdrop-blur",children:e.jsxs("div",{className:"mx-auto flex max-w-7xl items-center justify-between px-6 py-3.5 md:px-10",children:[e.jsxs("a",{href:typeof window<"u"&&window.location.hostname.startsWith("commercial.")?"/":"/public/commercial",className:"flex items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.22em] text-white/70 transition-colors hover:text-white",children:[e.jsx("span",{"aria-hidden":!0,children:"←"})," All opportunities"]}),e.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-[0.22em] text-white/45",children:"LevelUp Commercial"})]})}),e.jsxs("section",{className:"relative min-h-[86vh] w-full overflow-hidden",children:[b?e.jsx("img",{src:b,alt:y,className:"absolute inset-0 h-full w-full object-cover"}):e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-[#12202b] to-[#0b0f14]"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-[#0b0f14] via-[#0b0f14]/60 to-[#0b0f14]/30"}),e.jsxs("div",{className:"relative mx-auto flex min-h-[86vh] max-w-7xl flex-col justify-end px-6 pb-16 pt-24 md:px-10",children:[e.jsxs("div",{className:"mb-5 flex flex-wrap items-center gap-2.5",children:[e.jsx("span",{className:"rounded-full border border-white/25 px-3.5 py-1 text-[10px] font-semibold uppercase tracking-[0.22em]",children:DP[(d==null?void 0:d.deal_type)??"sale"]}),(d==null?void 0:d.commercial_type)&&e.jsx("span",{className:"rounded-full border border-white/15 bg-white/5 px-3.5 py-1 text-[10px] font-semibold uppercase tracking-[0.22em] text-white/70",children:hL[d.commercial_type]}),p&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full border border-amber-300/30 bg-amber-300/10 px-3.5 py-1 text-[10px] font-semibold uppercase tracking-[0.22em] text-amber-200",children:[e.jsx(ec,{className:"h-3 w-3"})," Confidential offering"]})]}),e.jsx("h1",{className:"max-w-4xl font-serif text-4xl leading-[1.05] tracking-tight md:text-6xl lg:text-7xl",children:y}),e.jsxs("p",{className:"mt-4 flex items-center gap-2 text-sm uppercase tracking-[0.2em] text-white/60",children:[e.jsx(Xa,{className:"h-4 w-4"})," ",v]}),e.jsxs("div",{className:"mt-8 flex flex-wrap items-end gap-x-10 gap-y-5",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.24em] text-white/45",children:(d==null?void 0:d.deal_type)==="lease"?"Lease rate":"Asking price"}),e.jsx("p",{className:"mt-1 text-3xl font-semibold tabular-nums md:text-4xl",children:EH(d,c.price)})]}),(d==null?void 0:d.cap_rate)!=null&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.24em] text-white/45",children:"Cap rate"}),e.jsx("p",{className:"mt-1 text-3xl font-semibold tabular-nums md:text-4xl",children:mAe(d.cap_rate)})]})]}),e.jsxs("div",{className:"mt-9 flex flex-wrap gap-3",children:[e.jsxs(B,{size:"lg",className:"rounded-full px-7",onClick:()=>{var G;return D("om_request",((G=u.find($=>$.doc_kind==="om"))==null?void 0:G.id)??null)},children:["Request Offering Memorandum ",e.jsx(La,{className:"ml-2 h-4 w-4"})]}),e.jsx(B,{size:"lg",variant:"outline",className:"rounded-full border-white/25 bg-white/5 px-7 text-white hover:bg-white/10 hover:text-white",onClick:()=>D("tour_request"),children:"Schedule a tour"})]})]})]}),f.length>0&&e.jsx("section",{className:"border-y border-white/10 bg-white/[0.02]",children:e.jsx("div",{className:"mx-auto grid max-w-7xl gap-px bg-white/10",style:{gridTemplateColumns:`repeat(${Math.min(f.length,4)}, minmax(0, 1fr))`},children:f.map(G=>e.jsxs("div",{className:"bg-[#0b0f14] px-6 py-8",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.2em] text-white/40",children:G.label}),e.jsx("p",{className:"mt-2 text-2xl font-semibold tabular-nums md:text-3xl",children:G.value})]},G.label))})}),P.length>0&&e.jsx(_T,{eyebrow:"The opportunity",title:"Investment highlights",children:e.jsx("div",{className:"grid gap-x-12 gap-y-8 md:grid-cols-2",children:P.map((G,$)=>e.jsxs("div",{className:"flex gap-5 border-t border-white/10 pt-6",children:[e.jsx("span",{className:"font-serif text-2xl text-white/25 tabular-nums",children:String($+1).padStart(2,"0")}),e.jsx("p",{className:"text-lg leading-relaxed text-white/85",children:G})]},$))})}),(c.description||M.length>0)&&e.jsx(_T,{eyebrow:"Property",title:"The asset",children:e.jsxs("div",{className:"grid gap-12 lg:grid-cols-[1.4fr_1fr]",children:[c.description&&e.jsx("div",{className:"space-y-5 text-lg leading-relaxed text-white/70",children:String(c.description).split(/\n{2,}/).map((G,$)=>e.jsx("p",{children:G},$))}),M.length>0&&e.jsx("ul",{className:"space-y-3 self-start rounded-2xl border border-white/10 bg-white/[0.03] p-7",children:M.map((G,$)=>e.jsxs("li",{className:"flex gap-3 text-sm text-white/75",children:[e.jsx("span",{className:"mt-2 h-1 w-1 shrink-0 rounded-full bg-white/50"})," ",G]},$))})]})}),h.length>1&&e.jsx(_T,{eyebrow:"Gallery",title:"Property imagery",children:e.jsx("div",{className:"grid gap-3 md:grid-cols-3",children:h.slice(1,10).map((G,$)=>e.jsx("button",{onClick:()=>{i($+1),bB(c.id,"gallery_view",{})},className:`group relative overflow-hidden rounded-xl ${$===0?"md:col-span-2 md:row-span-2":""}`,children:e.jsx("img",{src:G.photo_url,alt:`${y} — image ${$+2}`,loading:"lazy",className:`w-full object-cover transition-transform duration-700 group-hover:scale-[1.04] ${$===0?"h-full min-h-[280px] md:min-h-[560px]":"h-[180px] md:h-[275px]"}`})},G.id))})}),((d==null?void 0:d.noi)||(d==null?void 0:d.gross_income)||(d==null?void 0:d.operating_expenses)||(d==null?void 0:d.occupancy_pct)!=null)&&e.jsxs(_T,{eyebrow:"Financials",title:"Offering snapshot",children:[e.jsx("div",{className:"grid gap-px overflow-hidden rounded-2xl border border-white/10 bg-white/10 sm:grid-cols-2 lg:grid-cols-4",children:[{l:"Net operating income",v:K2(d==null?void 0:d.noi)},{l:"Gross income",v:K2(d==null?void 0:d.gross_income)},{l:"Operating expenses",v:K2(d==null?void 0:d.operating_expenses)},{l:"Occupancy",v:(d==null?void 0:d.occupancy_pct)!=null?`${Math.round(Number(d.occupancy_pct))}%`:null},{l:"Price per SF",v:(d==null?void 0:d.price_per_sf)!=null?K2(d.price_per_sf,2):null},{l:"Price per unit",v:K2(d==null?void 0:d.price_per_unit)},{l:"Tenancy",v:d!=null&&d.tenancy?`${d.tenancy[0].toUpperCase()}${d.tenancy.slice(1)} tenant`:null},{l:"Broker co-op",v:(d==null?void 0:d.broker_coop_pct)!=null?`${d.broker_coop_pct}%`:null}].filter(G=>G.v).map(G=>e.jsxs("div",{className:"bg-[#0b0f14] px-6 py-7",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.2em] text-white/40",children:G.l}),e.jsx("p",{className:"mt-2 text-xl font-semibold tabular-nums",children:G.v})]},G.l))}),(d==null?void 0:d.call_for_offers_at)&&e.jsxs("p",{className:"mt-6 inline-flex items-center gap-2 rounded-full border border-amber-300/25 bg-amber-300/10 px-5 py-2 text-sm text-amber-100",children:["Call for offers · ",new Date(d.call_for_offers_at).toLocaleDateString(void 0,{month:"long",day:"numeric",year:"numeric"})]})]}),(j.length>0||S.length>0)&&e.jsx(_T,{eyebrow:"Occupancy",title:S.length?"Space availability":"Tenant roster",children:e.jsx("div",{className:"overflow-hidden rounded-2xl border border-white/10",children:e.jsxs("table",{className:"w-full text-left text-sm",children:[e.jsx("thead",{className:"bg-white/[0.04] text-[10px] uppercase tracking-[0.18em] text-white/45",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-6 py-4",children:S.length?"Suite":"Tenant"}),e.jsx("th",{className:"px-6 py-4",children:"SF"}),e.jsx("th",{className:"px-6 py-4",children:S.length?"Rate":"Rent"}),e.jsx("th",{className:"px-6 py-4",children:S.length?"Availability":"Lease expiry"})]})}),e.jsx("tbody",{className:"divide-y divide-white/5",children:(S.length?S:j).map((G,$)=>e.jsxs("tr",{className:"text-white/80",children:[e.jsx("td",{className:"px-6 py-4 font-medium text-white",children:G.suite??G.name??"—"}),e.jsx("td",{className:"px-6 py-4 tabular-nums",children:G.sf?LA(Number(G.sf)):"—"}),e.jsx("td",{className:"px-6 py-4",children:G.rate??G.rent??"—"}),e.jsx("td",{className:"px-6 py-4",children:G.availability??G.lease_expiry??"—"})]},$))})]})})}),e.jsx(_T,{eyebrow:"Location",title:d!=null&&d.submarket?`${d.submarket} submarket`:v,children:e.jsxs("div",{className:"grid gap-8 lg:grid-cols-[1.2fr_1fr]",children:[g?e.jsx("div",{className:"overflow-hidden rounded-2xl border border-white/10",children:e.jsx("iframe",{title:"Property location",className:"h-[420px] w-full",loading:"lazy",src:`https://www.google.com/maps?q=${encodeURIComponent(g)}&z=${c.latitude&&c.longitude?15:12}&output=embed`,onLoad:()=>bB(c.id,"map_view",{})})}):e.jsx("div",{className:"flex h-[420px] items-center justify-center rounded-2xl border border-white/10 bg-white/[0.03] text-center text-sm text-white/50",children:p?"Exact location released with the Offering Memorandum.":v}),e.jsxs("div",{className:"space-y-5",children:[(d==null?void 0:d.zoning)&&e.jsx(_B,{label:"Zoning",value:d.zoning}),(d==null?void 0:d.lot_acres)!=null&&e.jsx(_B,{label:"Site size",value:`${d.lot_acres} acres`}),(d==null?void 0:d.parking_spaces)!=null&&e.jsx(_B,{label:"Parking",value:`${d.parking_spaces} spaces`}),(d==null?void 0:d.opportunity_zone)&&e.jsx(_B,{label:"Opportunity Zone",value:"Qualified"}),E.filter(G=>G.road||G.count).map((G,$)=>e.jsx(_B,{label:`Traffic count — ${G.road??"Adjacent road"}`,value:`${G.count??"—"} VPD`},$)),!(d!=null&&d.zoning)&&(d==null?void 0:d.lot_acres)==null&&(d==null?void 0:d.parking_spaces)==null&&!(d!=null&&d.opportunity_zone)&&e.jsx(_B,{label:"Submarket",value:(d==null?void 0:d.submarket)||v})]})]})}),I&&e.jsx(_T,{eyebrow:"Market",title:"Demographics",children:e.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[["radius_1","1 mile"],["radius_3","3 miles"],["radius_5","5 miles"]].map(([G,$])=>{const H=C==null?void 0:C[G];return!H||!Object.values(H).some(Boolean)?null:e.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/[0.03] p-7",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.2em] text-white/40",children:$}),e.jsx("dl",{className:"mt-5 space-y-3 text-sm",children:[["Population",H.population],["Households",H.households],["Avg. income",H.avg_income],["Daytime pop.",H.daytime_pop]].filter(([,Y])=>Y).map(([Y,Z])=>e.jsxs("div",{className:"flex justify-between gap-4",children:[e.jsx("dt",{className:"text-white/50",children:Y}),e.jsx("dd",{className:"font-medium tabular-nums",children:Z})]},Y))})]},G)})})}),u.length>0&&e.jsx(_T,{eyebrow:"Deal room",title:"Offering documents",children:e.jsx("div",{className:"grid gap-4 md:grid-cols-2",children:u.map(G=>{const $=G.gate_level==="public";return e.jsxs("div",{className:"flex items-center gap-4 rounded-2xl border border-white/10 bg-white/[0.03] p-5 transition-colors hover:border-white/20",children:[e.jsx("div",{className:"flex h-11 w-11 shrink-0 items-center justify-center rounded-xl border border-white/10 bg-white/5",children:$?e.jsx(li,{className:"h-5 w-5"}):G.gate_level==="nda"?e.jsx(Dm,{className:"h-5 w-5"}):e.jsx(ec,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate font-medium",children:G.title||V$e[G.doc_kind||"other"]}),e.jsx("p",{className:"text-xs text-white/45",children:$?"Available to download":G.gate_level==="nda"?"Confidentiality acknowledgement required":"Registration required"})]}),e.jsx(B,{size:"sm",variant:"outline",className:"border-white/20 bg-transparent text-white hover:bg-white/10 hover:text-white",onClick:()=>D("om_request",G.id),children:$?"Download":"Request"})]},G.id)})})}),m&&e.jsx("section",{className:"border-t border-white/10 bg-white/[0.02]",children:e.jsx("div",{className:"mx-auto max-w-7xl px-6 py-20 md:px-10",children:e.jsxs("div",{className:"flex flex-col items-start gap-8 md:flex-row md:items-center md:justify-between",children:[e.jsxs("div",{className:"flex items-center gap-6",children:[m.avatar_url&&e.jsx("img",{src:m.avatar_url,alt:m.name,className:"h-24 w-24 rounded-full object-cover ring-1 ring-white/15"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.22em] text-white/40",children:"Exclusively listed by"}),e.jsx("p",{className:"mt-2 font-serif text-2xl",children:m.name}),e.jsx("p",{className:"text-sm text-white/55",children:((V=m.brokerage)==null?void 0:V.name)||m.brokerage_name})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[m.email&&e.jsxs(B,{variant:"outline",className:"rounded-full border-white/20 bg-transparent text-white hover:bg-white/10 hover:text-white",onClick:()=>{bB(c.id,"contact_click",{}),window.location.href=`mailto:${m.email}`},children:[e.jsx(ln,{className:"mr-2 h-4 w-4"})," Email"]}),m.phone&&e.jsxs(B,{variant:"outline",className:"rounded-full border-white/20 bg-transparent text-white hover:bg-white/10 hover:text-white",onClick:()=>{bB(c.id,"contact_click",{}),window.location.href=`tel:${m.phone}`},children:[e.jsx(_a,{className:"mr-2 h-4 w-4"})," Call"]}),e.jsx(B,{className:"rounded-full",onClick:()=>D("investor_inquiry"),children:"Request information"})]})]})})}),e.jsx("footer",{className:"border-t border-white/10 py-10 text-center text-xs text-white/35",children:e.jsx("p",{children:"The information contained herein has been obtained from sources believed reliable but is not guaranteed. Prospective purchasers and tenants should conduct their own independent investigation."})}),e.jsx("div",{className:"sticky bottom-0 z-30 border-t border-white/10 bg-[#0b0f14]/90 backdrop-blur-xl",children:e.jsxs("div",{className:"mx-auto flex max-w-7xl flex-wrap items-center justify-between gap-3 px-6 py-3.5 md:px-10",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:y}),e.jsxs("p",{className:"truncate text-xs text-white/50",children:[EH(d,c.price)," · ",v]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{size:"sm",variant:"outline",className:"rounded-full border-white/20 bg-transparent text-white hover:bg-white/10 hover:text-white",onClick:()=>D("tour_request"),children:"Tour"}),e.jsx(B,{size:"sm",className:"rounded-full",onClick:()=>{var G;return D("om_request",((G=u.find($=>$.doc_kind==="om"))==null?void 0:G.id)??null)},children:"Request OM"})]})]})}),e.jsx(Ls,{open:a!==null,onOpenChange:G=>!G&&i(null),children:e.jsx(Ps,{className:"max-w-[96vw] border-none bg-transparent p-0 shadow-none",children:a!==null&&h[a]&&e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:h[a].photo_url,alt:"",className:"max-h-[88vh] w-full rounded-xl object-contain"}),e.jsx("button",{className:"absolute right-3 top-3 rounded-full bg-black/60 p-2",onClick:()=>i(null),children:e.jsx(Qn,{className:"h-5 w-5"})}),e.jsx("button",{className:"absolute left-3 top-1/2 -translate-y-1/2 rounded-full bg-black/60 p-2",onClick:()=>i(G=>(G-1+h.length)%h.length),children:e.jsx($c,{className:"h-6 w-6"})}),e.jsx("button",{className:"absolute right-3 top-1/2 -translate-y-1/2 rounded-full bg-black/60 p-2",onClick:()=>i(G=>(G+1)%h.length),children:e.jsx(xi,{className:"h-6 w-6"})})]})})}),l&&e.jsx(B6s,{open:!0,onOpenChange:G=>!G&&o(null),listingId:c.id,kind:l.kind,documentId:l.documentId,requiresNda:!!(d!=null&&d.requires_nda)||(d==null?void 0:d.om_gate_mode)==="nda",brokerName:m==null?void 0:m.name})]})}function _T({eyebrow:s,title:t,children:n}){return e.jsx("section",{className:"border-t border-white/10",children:e.jsxs("div",{className:"mx-auto max-w-7xl px-6 py-20 md:px-10 md:py-24",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.24em] text-white/40",children:s}),e.jsx("h2",{className:"mt-3 font-serif text-3xl tracking-tight md:text-4xl",children:t}),e.jsx("div",{className:"mt-12",children:n})]})})}function _B({label:s,value:t}){return e.jsxs("div",{className:"border-t border-white/10 pt-4",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.2em] text-white/40",children:s}),e.jsx("p",{className:"mt-1 text-lg",children:t})]})}const eft="/assets/levelup-logo-color-BeKd2k_g.png",$6s={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"},V6s={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"},tft={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"},fle=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),zY=s=>new Intl.NumberFormat("en-US").format(s);function mJe({slugOverride:s}={}){var qt,Vt,Xt,fs,Ft;const t=Li(),n=s||t.slugOrId,[r]=Yl(),{data:a,isLoading:i}=T6s(n||""),l=M6s(),o=P6s(),c=r.get("ref"),[d,u]=_.useState(""),[h,m]=_.useState(""),[p,f]=_.useState(""),[y,v]=_.useState(""),[g,b]=_.useState(""),[j,S]=_.useState(""),[C,E]=_.useState(""),[P,M]=_.useState("in_person"),[I,D]=_.useState("info"),[O,V]=_.useState(!1),[G,$]=_.useState(!1),[H,Y]=_.useState(null),[Z,ne]=_.useState(!1);_.useState(!1);const[ce,ie]=_.useState(!1),[te,ae]=_.useState(20),[le,be]=_.useState(6.5),[me,he]=_.useState(30),pe=_.useRef(null),[Ce,Ae]=_.useState(!1);_.useEffect(()=>{const wt=()=>Ae(window.scrollY>300);return window.addEventListener("scroll",wt,{passive:!0}),()=>window.removeEventListener("scroll",wt)},[]),_.useEffect(()=>{c&&o.mutate(c)},[c]),_.useEffect(()=>{window.scrollTo({top:0,left:0,behavior:"auto"})},[n]);const Pe=(a==null?void 0:a.photos)||[],ze=Pe.find(wt=>wt.is_primary)||Pe[0],ke=_.useMemo(()=>{if(!(a!=null&&a.price))return 0;const wt=a.price*(1-te/100),Ts=le/100/12,vt=me*12;return Ts===0?wt/vt:wt*Ts/(1-Math.pow(1+Ts,-vt))},[a==null?void 0:a.price,te,le,me]),Ze=async()=>{const wt=window.location.href;if(navigator.share)try{await navigator.share({title:document.title,url:wt})}catch{}else await navigator.clipboard.writeText(wt),se.success("Link copied to clipboard")},Se=async wt=>{if(wt.preventDefault(),!d.trim()||!p.trim()||!a)return;const Ts=I==="showing";if(Ts&&!j){se.error("Please pick a preferred date for your showing");return}V(!0);try{await l.mutateAsync({listingId:a.id,agentId:a.agent_id,firstName:d.trim(),lastName:h.trim(),email:p.trim(),phone:y.trim(),shareToken:c,leadType:Ts?"showing_request":"info_request",preferredDate:Ts?j:null,preferredTime:Ts&&C||null,showingMode:Ts?P:null,message:g.trim()||null}),$(!0),se.success(Ts?"Showing request sent! The agent will confirm details shortly.":"Thanks! The agent will be in touch soon.")}catch(vt){console.error("Lead submission error:",vt),se.error(`Failed to submit: ${vt.message||"Please try again"}`)}finally{V(!1)}},Fe=()=>{H!==null&&Y(H===0?Pe.length-1:H-1)},Ne=()=>{H!==null&&Y(H===Pe.length-1?0:H+1)};if((a==null?void 0:a.listing_class)==="commercial")return e.jsx(q6s,{slug:n});if(i)return e.jsx("div",{className:"min-h-screen bg-neutral-950",children:e.jsx(cn,{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(ir,{to:"/public/listings",className:"flex items-center gap-2",children:e.jsx("img",{src:eft,alt:"LevelUp",className:"h-8"})})})}),e.jsxs("div",{className:"container mx-auto px-4 py-24 text-center",children:[e.jsx(Jr,{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(B,{asChild:!0,children:e.jsx(ir,{to:typeof window<"u"&&window.location.host==="listings.relevelup.com"?"/":"/public/listings",children:"Browse All Listings"})})]})]});const Ye=a.property_address?`${a.property_address} — ${a.city}, ${a.state}`:`${a.city}, ${a.state} Home for Sale`,Ve=((Vt=(qt=a.agent)==null?void 0:qt.brokerage)==null?void 0:Vt.name)||((Xt=a.agent)==null?void 0:Xt.brokerage_name),qe=a.latitude&&a.longitude?`https://maps.google.com/maps?q=${a.latitude},${a.longitude}&z=15&output=embed`:a.property_address?`https://maps.google.com/maps?q=${encodeURIComponent(`${a.property_address}, ${a.city}, ${a.state}`)}&z=15&output=embed`:null,Qe=a.description||"",Ue=Qe.length>420,Xe=ce||!Ue?Qe:Qe.slice(0,420).trimEnd()+"…",nt=a.page_config||{},$e=wt=>{var Ts;return(((Ts=nt.sections)==null?void 0:Ts[wt])??!0)!==!1},Ge=Array.isArray(nt.addons)?nt.addons:[],ct=nt.custom_note||"",xt=nt.accent_color||null;return e.jsxs(e.Fragment,{children:[e.jsxs(ul,{children:[e.jsxs("title",{children:[Ye," | LevelUp Listings"]}),e.jsx("meta",{name:"description",content:`${fle(a.price)} · ${a.bedrooms||""}BD ${a.bathrooms||""}BA ${a.square_footage?a.square_footage.toLocaleString()+" sqft · ":""}${tft[a.property_type]} in ${a.city}, ${a.state}. ${Qe.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:Ye}),e.jsx("meta",{property:"og:description",content:`${fle(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:Ye}),e.jsx("meta",{name:"twitter:description",content:`${fle(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:Qe,url:`https://listings.relevelup.com/${a.slug||a.id}`,datePosted:a.created_at,image:Pe.map(wt=>wt.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 ${Ce?"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(ir,{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"})]}),Ce&&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(([wt,Ts])=>e.jsx("a",{href:`#${wt}`,className:"px-3 py-1.5 rounded-full text-white/70 hover:text-white hover:bg-white/10 transition",children:Ts},wt))}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(l6s,{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:Ze,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(bd,{className:"h-4 w-4 text-white"})}),e.jsx(B,{size:"sm",onClick:()=>ne(!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:pe,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(Oe,{className:`${$6s[a.status]} text-white border-0 uppercase tracking-widest text-[10px] px-3 py-1 rounded-full shadow-lg`,children:V6s[a.status]}),Pe.length>0&&e.jsxs("button",{onClick:()=>Y(0),className:"flex items-center gap-1.5 text-xs text-white/90 bg-black/40 backdrop-blur border border-white/20 rounded-full px-3 py-1.5 hover:bg-black/60 transition",children:[e.jsx(cg,{className:"h-3.5 w-3.5"}),Pe.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:fle(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:zY(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(Fo,{className:"h-6 w-6 text-white"})}),e.jsxs("div",{className:"pr-2",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-widest text-white/60",children:"Listing Agent"}),e.jsx("p",{className:"text-white font-medium leading-tight",children:a.agent.name}),Ve&&e.jsx("p",{className:"text-xs text-white/60",children:Ve})]}),e.jsx(B,{size:"sm",onClick:()=>ne(!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"]})]})})]}),$e("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:dj,label:"Bedrooms",value:a.bedrooms},a.bathrooms&&{icon:S0,label:"Bathrooms",value:a.bathrooms},a.square_footage&&{icon:wb,label:"Interior",value:`${zY(a.square_footage)} sqft`},a.lot_size&&{icon:W4,label:"Lot Size",value:a.lot_size},a.year_built&&{icon:ga,label:"Year Built",value:a.year_built},!a.year_built&&a.square_footage&&{icon:uj,label:"Price / sqft",value:`$${zY(Math.round(a.price/a.square_footage))}`}].filter(Boolean).slice(0,5).map((wt,Ts)=>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(wt.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:wt.label}),e.jsx("p",{className:"font-display text-2xl text-white font-light",children:wt.value})]})]},Ts))})}),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:[$e("story")&&Qe&&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:Xe})}),Ue&&e.jsx("button",{onClick:()=>ie(!ce),className:"mt-4 text-sm text-white/60 hover:text-white underline underline-offset-4",children:ce?"Show less":"Read more"}),e.jsxs("div",{className:"mt-8 flex flex-wrap gap-2",children:[e.jsxs(Oe,{variant:"outline",className:"border-white/20 text-white/80 bg-white/5",children:[e.jsx(ai,{className:"h-3 w-3 mr-1.5"}),tft[a.property_type]]}),a.has_hoa&&e.jsx(Oe,{variant:"outline",className:"border-white/20 text-white/80 bg-white/5",children:"HOA"}),a.mls_link&&e.jsx(B,{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(wr,{className:"h-3.5 w-3.5 mr-1.5"})," MLS"]})})]}),(ct||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(un,{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:['"',ct||a.agent_notes,'"']})]})]}),$e("gallery")&&Pe.length>1&&e.jsxs("section",{id:"gallery",children:[e.jsxs("div",{className:"flex items-end justify-between mb-6",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"Gallery"}),e.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white",children:"Every angle, every detail"})]}),e.jsxs("button",{onClick:()=>Y(0),className:"text-sm text-white/60 hover:text-white underline underline-offset-4 hidden sm:inline",children:["View all ",Pe.length]})]}),e.jsx("div",{className:"grid grid-cols-4 gap-2 sm:gap-3",children:Pe.slice(0,7).map((wt,Ts)=>{const vt=["col-span-4 sm:col-span-2 sm:row-span-2 aspect-square sm:aspect-auto","col-span-2 sm:col-span-2 aspect-[4/3]","col-span-2 sm:col-span-2 aspect-[4/3]","col-span-2 sm:col-span-1 aspect-square","col-span-2 sm:col-span-1 aspect-square","col-span-2 sm:col-span-1 aspect-square","col-span-2 sm:col-span-1 aspect-square"],$s=Ts===6&&Pe.length>7;return e.jsxs("button",{onClick:()=>Y(Ts),className:`${vt[Ts]} relative rounded-xl overflow-hidden group bg-neutral-900`,children:[e.jsx("img",{src:wt.photo_url,alt:`Photo ${Ts+1}`,className:"absolute inset-0 h-full w-full object-cover group-hover:scale-[1.04] transition-transform duration-500"}),$s&&e.jsxs("div",{className:"absolute inset-0 bg-black/60 flex flex-col items-center justify-center text-white",children:[e.jsx(cg,{className:"h-6 w-6 mb-1"}),e.jsxs("span",{className:"font-medium",children:["+",Pe.length-7," more"]})]})]},wt.id)})})]}),$e("video")&&((fs=a.video)==null?void 0:fs.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"})})]}),$e("map")&&qe&&e.jsxs("section",{id:"map",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"Location"}),e.jsxs("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:[a.neighborhood?a.neighborhood:a.city,", ",a.state]}),e.jsx("div",{className:"rounded-2xl overflow-hidden border border-white/10 shadow-2xl aspect-[16/10]",children:e.jsx("iframe",{src:qe,className:"w-full h-full grayscale-[.2] contrast-[1.05]",loading:"lazy",title:"Map"})}),e.jsxs("div",{className:"mt-4 flex items-center gap-2 text-white/60 text-sm",children:[e.jsx(Xa,{className:"h-4 w-4"}),a.property_address?`${a.property_address}, `:"",a.city,", ",a.state]})]}),$e("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:["$",zY(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(J,{className:"text-white/70 text-xs uppercase tracking-widest",children:"Down Payment"}),e.jsxs("span",{className:"text-white font-medium",children:[te,"%"]})]}),e.jsx(kx,{value:[te],onValueChange:wt=>ae(wt[0]),min:0,max:50,step:1}),e.jsxs("p",{className:"text-xs text-white/50 mt-2",children:["$",zY(Math.round(a.price*te/100))," down"]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(J,{className:"text-white/70 text-xs uppercase tracking-widest",children:"Interest Rate"}),e.jsxs("span",{className:"text-white font-medium",children:[le.toFixed(2),"%"]})]}),e.jsx(kx,{value:[le],onValueChange:wt=>be(wt[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(J,{className:"text-white/70 text-xs uppercase tracking-widest",children:"Loan Term"}),e.jsxs("span",{className:"text-white font-medium",children:[me," yr"]})]}),e.jsx(kx,{value:[me],onValueChange:wt=>he(wt[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."})]})]}),Ge.map(wt=>{const Ts=wt.type,vt=wt.data||{};if(Ts==="extra_video"&&vt.url){const $s=String(vt.url).includes("youtu")?`https://www.youtube.com/embed/${String(vt.url).split(/[/=]/).pop()}`:vt.url;return e.jsxs("section",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:vt.eyebrow||"Featured Video"}),e.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:vt.title||"Watch"}),e.jsx("div",{className:"relative rounded-2xl overflow-hidden bg-black shadow-2xl aspect-video",children:e.jsx("iframe",{src:$s,className:"absolute inset-0 h-full w-full",allowFullScreen:!0,title:vt.title||"Video"})})]},wt.id)}return Ts==="3d_tour"&&vt.url?e.jsxs("section",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"3D Tour"}),e.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:vt.title||"Step inside"}),e.jsx("div",{className:"relative rounded-2xl overflow-hidden bg-black shadow-2xl aspect-video",children:e.jsx("iframe",{src:vt.url,className:"absolute inset-0 h-full w-full",allowFullScreen:!0,title:"3D Tour"})})]},wt.id):Ts==="floor_plan"&&vt.image_url?e.jsxs("section",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"Floor Plan"}),e.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:vt.title||"Layout"}),e.jsx("img",{src:vt.image_url,alt:"Floor plan",className:"w-full rounded-2xl border border-white/10"})]},wt.id):Ts==="testimonial"&&vt.quote?e.jsxs("section",{className:"rounded-2xl border border-white/10 bg-white/[0.03] p-8",children:[e.jsxs("p",{className:"font-display italic text-2xl text-white/90 leading-relaxed",children:['"',vt.quote,'"']}),vt.author&&e.jsxs("p",{className:"mt-4 text-sm text-white/60",children:["— ",vt.author]})]},wt.id):Ts==="custom_cta"&&vt.label?e.jsxs("section",{className:"rounded-2xl p-8 text-center",style:{background:xt?`${xt}22`:"rgba(255,255,255,0.05)",border:`1px solid ${xt||"rgba(255,255,255,0.1)"}`},children:[vt.title&&e.jsx("h3",{className:"font-display text-3xl text-white mb-4",children:vt.title}),e.jsx(B,{asChild:!0,size:"lg",style:xt?{background:xt}:void 0,children:e.jsx("a",{href:vt.url||"#agent",children:vt.label})})]},wt.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(Fo,{className:"h-7 w-7 text-white/70"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-widest text-white/50",children:"Listing Agent"}),e.jsx("p",{className:"font-display text-xl text-white font-medium leading-tight",children:a.agent.name}),Ve&&e.jsx("p",{className:"text-sm text-white/60 mt-0.5",children:Ve})]})]}),e.jsxs("div",{className:"mt-4 grid grid-cols-2 gap-2",children:[a.agent.phone&&e.jsx(B,{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(_a,{className:"h-3.5 w-3.5 mr-1.5"}),"Call"]})}),a.agent.email&&e.jsx(B,{asChild:!0,variant:"outline",size:"sm",className:"border-white/20 bg-white/5 text-white hover:bg-white/15",children:e.jsxs("a",{href:`mailto:${a.agent.email}`,children:[e.jsx(ln,{className:"h-3.5 w-3.5 mr-1.5"}),"Email"]})})]})]}),a.co_agent_name&&e.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/[0.03] p-6 backdrop-blur",children:[e.jsxs("div",{className:"flex items-start gap-4",children:[a.co_agent_photo_url?e.jsx("img",{src:a.co_agent_photo_url,alt:a.co_agent_name,className:"h-16 w-16 rounded-full object-cover border-2 border-white/20"}):e.jsx("div",{className:"h-16 w-16 rounded-full bg-white/10 flex items-center justify-center border-2 border-white/20",children:e.jsx(Fo,{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(B,{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(_a,{className:"h-3.5 w-3.5 mr-1.5"}),"Call"]})}),a.co_agent_email&&e.jsx(B,{asChild:!0,variant:"outline",size:"sm",className:"border-white/20 bg-white/5 text-white hover:bg-white/15",children:e.jsxs("a",{href:`mailto:${a.co_agent_email}`,children:[e.jsx(ln,{className:"h-3.5 w-3.5 mr-1.5"}),"Email"]})})]})]}),e.jsx("div",{id:"contact",className:"rounded-2xl border border-white/10 bg-white text-neutral-900 p-6 shadow-2xl",children:e.jsx(sft,{submitted:G,activeTab:I,setActiveTab:D,firstName:d,setFirstName:u,lastName:h,setLastName:m,email:p,setEmail:f,phone:y,setPhone:v,message:g,setMessage:b,preferredDate:j,setPreferredDate:S,preferredTime:C,setPreferredTime:E,showingMode:P,setShowingMode:M,isSubmitting:O,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:[((Ft=a.agent)==null?void 0:Ft.phone)&&e.jsx(B,{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(_a,{className:"h-4 w-4 mr-1.5"}),"Call"]})}),e.jsxs(B,{onClick:()=>ne(!0),className:"bg-white text-neutral-900 hover:bg-white/90 flex-[2] font-medium",children:[e.jsx(Qd,{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:eft,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(Ls,{open:H!==null,onOpenChange:()=>Y(null),children:e.jsxs(Ps,{className:"max-w-6xl p-0 bg-black/95 border-0",children:[e.jsx(Os,{className:"sr-only",children:e.jsx(Ds,{children:"Photo Gallery"})}),e.jsx("button",{onClick:()=>Y(null),className:"absolute right-4 top-4 z-50 rounded-full bg-white/10 hover:bg-white/20 p-2 text-white",children:e.jsx(Qn,{className:"h-5 w-5"})}),H!==null&&Pe[H]&&e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:Pe[H].photo_url,alt:`Photo ${H+1}`,className:"w-full max-h-[85vh] object-contain"}),Pe.length>1&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:Fe,className:"absolute left-4 top-1/2 -translate-y-1/2 rounded-full bg-white/10 hover:bg-white/20 p-3 text-white",children:e.jsx($c,{className:"h-6 w-6"})}),e.jsx("button",{onClick:Ne,className:"absolute right-4 top-1/2 -translate-y-1/2 rounded-full bg-white/10 hover:bg-white/20 p-3 text-white",children:e.jsx(xi,{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:[H+1," / ",Pe.length]})]})]})]})}),e.jsx(Ls,{open:Z,onOpenChange:ne,children:e.jsxs(Ps,{className:"max-w-md p-0 bg-white text-neutral-900",children:[e.jsx(Os,{className:"sr-only",children:e.jsx(Ds,{children:"Contact the agent"})}),e.jsx("div",{className:"p-6",children:e.jsx(sft,{submitted:G,activeTab:I,setActiveTab:D,firstName:d,setFirstName:u,lastName:h,setLastName:m,email:p,setEmail:f,phone:y,setPhone:v,message:g,setMessage:b,preferredDate:j,setPreferredDate:S,preferredTime:C,setPreferredTime:E,showingMode:P,setShowingMode:M,isSubmitting:O,onSubmit:Se})})]})})]})]})}function sft(s){const{submitted:t,activeTab:n,setActiveTab:r,firstName:a,setFirstName:i,lastName:l,setLastName:o,email:c,setEmail:d,phone:u,setPhone:h,message:m,setMessage:p,preferredDate:f,setPreferredDate:y,preferredTime:v,setPreferredTime:g,showingMode:b,setShowingMode:j,isSubmitting:S,onSubmit:C}=s;return t?e.jsxs("div",{className:"text-center py-6",children:[e.jsx("div",{className:"h-14 w-14 rounded-full bg-emerald-100 flex items-center justify-center mx-auto mb-3",children:e.jsx(ea,{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(Yr,{value:n,onValueChange:E=>r(E),children:[e.jsxs(Zr,{className:"grid w-full grid-cols-2 mb-4",children:[e.jsxs(Ht,{value:"info",className:"gap-1.5",children:[e.jsx(Hi,{className:"h-3.5 w-3.5"})," Get Info"]}),e.jsxs(Ht,{value:"showing",className:"gap-1.5",children:[e.jsx(Qd,{className:"h-3.5 w-3.5"})," Request Tour"]})]}),e.jsxs("form",{onSubmit:C,className:"space-y-3",children:[e.jsxs(Gt,{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(J,{htmlFor:"preferredDate",children:"Preferred Date *"}),e.jsx(xe,{id:"preferredDate",type:"date",value:f,onChange:E=>y(E.target.value),min:new Date().toISOString().split("T")[0],required:n==="showing"})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"preferredTime",children:"Preferred Time"}),e.jsxs(is,{value:v,onValueChange:g,children:[e.jsx(rs,{id:"preferredTime",children:e.jsx(ls,{placeholder:"Any time"})}),e.jsxs(as,{children:[e.jsx(He,{value:"morning",children:"Morning (9am–12pm)"}),e.jsx(He,{value:"afternoon",children:"Afternoon (12pm–5pm)"}),e.jsx(He,{value:"evening",children:"Evening (5pm–8pm)"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"showingMode",children:"Tour Type"}),e.jsxs(is,{value:b,onValueChange:E=>j(E),children:[e.jsx(rs,{id:"showingMode",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"in_person",children:"🏡 In-person showing"}),e.jsx(He,{value:"video",children:"📱 Video tour (FaceTime/Zoom)"}),e.jsx(He,{value:"either",children:"Either works for me"})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(J,{htmlFor:"firstName",children:"First Name *"}),e.jsx(xe,{id:"firstName",value:a,onChange:E=>i(E.target.value),required:!0})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"lastName",children:"Last Name"}),e.jsx(xe,{id:"lastName",value:l,onChange:E=>o(E.target.value)})]})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"email",children:"Email *"}),e.jsx(xe,{id:"email",type:"email",value:c,onChange:E=>d(E.target.value),required:!0})]}),e.jsxs("div",{children:[e.jsxs(J,{htmlFor:"phone",children:["Phone ",n==="showing"&&"*"]}),e.jsx(xe,{id:"phone",type:"tel",value:u,onChange:E=>h(E.target.value),required:n==="showing"})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"message",children:n==="showing"?"Anything else?":"Message (optional)"}),e.jsx(Ms,{id:"message",value:m,onChange:E=>p(E.target.value),rows:2})]}),e.jsx(B,{type:"submit",disabled:S,className:"w-full bg-neutral-900 hover:bg-neutral-800 text-white h-11",children:S?"Sending…":n==="showing"?"Request Showing":"Get More Info"}),e.jsx("p",{className:"text-[11px] text-neutral-500 text-center",children:"The listing agent will contact you directly. No spam."})]})]})]})}const TH="/assets/levelup-logo-white-C2RAgAoG.png",H6s="/assets/listings-hero-noir-BHCJrhvU.jpg";var SFt={exports:{}};(function(s,t){(function(n,r){s.exports=r()})(Cp,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,x){var w=x[0],A=x[1],L=x[2],F=x[3],U=w*F-L*A;return U?(k[0]=F*(U=1/U),k[1]=-A*U,k[2]=-L*U,k[3]=w*U,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,x){var w=x[0],A=x[1],L=x[2],F=x[3],U=x[4],K=x[5],X=x[6],oe=x[7],ge=x[8];return k[0]=U*ge-K*oe,k[1]=L*oe-A*ge,k[2]=A*K-L*U,k[3]=K*X-F*ge,k[4]=w*ge-L*X,k[5]=L*F-w*K,k[6]=F*oe-U*X,k[7]=A*X-w*oe,k[8]=w*U-A*F,k}function p(k,x,w){var A=x[0],L=x[1],F=x[2],U=x[3],K=x[4],X=x[5],oe=x[6],ge=x[7],we=x[8],je=w[0],Le=w[1],Re=w[2],We=w[3],et=w[4],it=w[5],yt=w[6],ht=w[7],Et=w[8];return k[0]=je*A+Le*U+Re*oe,k[1]=je*L+Le*K+Re*ge,k[2]=je*F+Le*X+Re*we,k[3]=We*A+et*U+it*oe,k[4]=We*L+et*K+it*ge,k[5]=We*F+et*X+it*we,k[6]=yt*A+ht*U+Et*oe,k[7]=yt*L+ht*K+Et*ge,k[8]=yt*F+ht*X+Et*we,k}function f(){var k=new d(16);return d!=Float32Array&&(k[1]=0,k[2]=0,k[3]=0,k[4]=0,k[6]=0,k[7]=0,k[8]=0,k[9]=0,k[11]=0,k[12]=0,k[13]=0,k[14]=0),k[0]=1,k[5]=1,k[10]=1,k[15]=1,k}function y(k){var x=new d(16);return x[0]=k[0],x[1]=k[1],x[2]=k[2],x[3]=k[3],x[4]=k[4],x[5]=k[5],x[6]=k[6],x[7]=k[7],x[8]=k[8],x[9]=k[9],x[10]=k[10],x[11]=k[11],x[12]=k[12],x[13]=k[13],x[14]=k[14],x[15]=k[15],x}function v(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 g(k,x){var w=x[0],A=x[1],L=x[2],F=x[3],U=x[4],K=x[5],X=x[6],oe=x[7],ge=x[8],we=x[9],je=x[10],Le=x[11],Re=x[12],We=x[13],et=x[14],it=x[15],yt=w*K-A*U,ht=w*X-L*U,Et=w*oe-F*U,It=A*X-L*K,Ot=A*oe-F*K,ws=L*oe-F*X,ds=ge*We-we*Re,_s=ge*et-je*Re,gs=ge*it-Le*Re,ys=we*et-je*We,vn=we*it-Le*We,wn=je*it-Le*et,Pn=yt*wn-ht*vn+Et*ys+It*gs-Ot*_s+ws*ds;return Pn?(k[0]=(K*wn-X*vn+oe*ys)*(Pn=1/Pn),k[1]=(L*vn-A*wn-F*ys)*Pn,k[2]=(We*ws-et*Ot+it*It)*Pn,k[3]=(je*Ot-we*ws-Le*It)*Pn,k[4]=(X*gs-U*wn-oe*_s)*Pn,k[5]=(w*wn-L*gs+F*_s)*Pn,k[6]=(et*Et-Re*ws-it*ht)*Pn,k[7]=(ge*ws-je*Et+Le*ht)*Pn,k[8]=(U*vn-K*gs+oe*ds)*Pn,k[9]=(A*gs-w*vn-F*ds)*Pn,k[10]=(Re*Ot-We*Et+it*yt)*Pn,k[11]=(we*Et-ge*Ot-Le*yt)*Pn,k[12]=(K*_s-U*ys-X*ds)*Pn,k[13]=(w*ys-A*_s+L*ds)*Pn,k[14]=(We*ht-Re*It-et*yt)*Pn,k[15]=(ge*It-we*ht+je*yt)*Pn,k):null}function b(k,x,w){var A=x[0],L=x[1],F=x[2],U=x[3],K=x[4],X=x[5],oe=x[6],ge=x[7],we=x[8],je=x[9],Le=x[10],Re=x[11],We=x[12],et=x[13],it=x[14],yt=x[15],ht=w[0],Et=w[1],It=w[2],Ot=w[3];return k[0]=ht*A+Et*K+It*we+Ot*We,k[1]=ht*L+Et*X+It*je+Ot*et,k[2]=ht*F+Et*oe+It*Le+Ot*it,k[3]=ht*U+Et*ge+It*Re+Ot*yt,k[4]=(ht=w[4])*A+(Et=w[5])*K+(It=w[6])*we+(Ot=w[7])*We,k[5]=ht*L+Et*X+It*je+Ot*et,k[6]=ht*F+Et*oe+It*Le+Ot*it,k[7]=ht*U+Et*ge+It*Re+Ot*yt,k[8]=(ht=w[8])*A+(Et=w[9])*K+(It=w[10])*we+(Ot=w[11])*We,k[9]=ht*L+Et*X+It*je+Ot*et,k[10]=ht*F+Et*oe+It*Le+Ot*it,k[11]=ht*U+Et*ge+It*Re+Ot*yt,k[12]=(ht=w[12])*A+(Et=w[13])*K+(It=w[14])*we+(Ot=w[15])*We,k[13]=ht*L+Et*X+It*je+Ot*et,k[14]=ht*F+Et*oe+It*Le+Ot*it,k[15]=ht*U+Et*ge+It*Re+Ot*yt,k}function j(k,x,w){var A,L,F,U,K,X,oe,ge,we,je,Le,Re,We=w[0],et=w[1],it=w[2];return x===k?(k[12]=x[0]*We+x[4]*et+x[8]*it+x[12],k[13]=x[1]*We+x[5]*et+x[9]*it+x[13],k[14]=x[2]*We+x[6]*et+x[10]*it+x[14],k[15]=x[3]*We+x[7]*et+x[11]*it+x[15]):(L=x[1],F=x[2],U=x[3],K=x[4],X=x[5],oe=x[6],ge=x[7],we=x[8],je=x[9],Le=x[10],Re=x[11],k[0]=A=x[0],k[1]=L,k[2]=F,k[3]=U,k[4]=K,k[5]=X,k[6]=oe,k[7]=ge,k[8]=we,k[9]=je,k[10]=Le,k[11]=Re,k[12]=A*We+K*et+we*it+x[12],k[13]=L*We+X*et+je*it+x[13],k[14]=F*We+oe*et+Le*it+x[14],k[15]=U*We+ge*et+Re*it+x[15]),k}function S(k,x,w){var A=w[0],L=w[1],F=w[2];return k[0]=x[0]*A,k[1]=x[1]*A,k[2]=x[2]*A,k[3]=x[3]*A,k[4]=x[4]*L,k[5]=x[5]*L,k[6]=x[6]*L,k[7]=x[7]*L,k[8]=x[8]*F,k[9]=x[9]*F,k[10]=x[10]*F,k[11]=x[11]*F,k[12]=x[12],k[13]=x[13],k[14]=x[14],k[15]=x[15],k}function C(k,x,w){var A=Math.sin(w),L=Math.cos(w),F=x[4],U=x[5],K=x[6],X=x[7],oe=x[8],ge=x[9],we=x[10],je=x[11];return x!==k&&(k[0]=x[0],k[1]=x[1],k[2]=x[2],k[3]=x[3],k[12]=x[12],k[13]=x[13],k[14]=x[14],k[15]=x[15]),k[4]=F*L+oe*A,k[5]=U*L+ge*A,k[6]=K*L+we*A,k[7]=X*L+je*A,k[8]=oe*L-F*A,k[9]=ge*L-U*A,k[10]=we*L-K*A,k[11]=je*L-X*A,k}function E(k,x,w){var A=Math.sin(w),L=Math.cos(w),F=x[0],U=x[1],K=x[2],X=x[3],oe=x[8],ge=x[9],we=x[10],je=x[11];return x!==k&&(k[4]=x[4],k[5]=x[5],k[6]=x[6],k[7]=x[7],k[12]=x[12],k[13]=x[13],k[14]=x[14],k[15]=x[15]),k[0]=F*L-oe*A,k[1]=U*L-ge*A,k[2]=K*L-we*A,k[3]=X*L-je*A,k[8]=F*A+oe*L,k[9]=U*A+ge*L,k[10]=K*A+we*L,k[11]=X*A+je*L,k}function P(k,x,w){var A=Math.sin(w),L=Math.cos(w),F=x[0],U=x[1],K=x[2],X=x[3],oe=x[4],ge=x[5],we=x[6],je=x[7];return x!==k&&(k[8]=x[8],k[9]=x[9],k[10]=x[10],k[11]=x[11],k[12]=x[12],k[13]=x[13],k[14]=x[14],k[15]=x[15]),k[0]=F*L+oe*A,k[1]=U*L+ge*A,k[2]=K*L+we*A,k[3]=X*L+je*A,k[4]=oe*L-F*A,k[5]=ge*L-U*A,k[6]=we*L-K*A,k[7]=je*L-X*A,k}function M(k,x){return k[0]=x[0],k[1]=0,k[2]=0,k[3]=0,k[4]=0,k[5]=x[1],k[6]=0,k[7]=0,k[8]=0,k[9]=0,k[10]=x[2],k[11]=0,k[12]=0,k[13]=0,k[14]=0,k[15]=1,k}function I(k,x,w){var A,L,F,U=w[0],K=w[1],X=w[2],oe=Math.sqrt(U*U+K*K+X*X);return oe0&&(F=1/Math.sqrt(F)),k[0]=x[0]*F,k[1]=x[1]*F,k[2]=x[2]*F,k}function Pe(k,x){return k[0]*x[0]+k[1]*x[1]+k[2]*x[2]}function ze(k,x,w){var A=x[0],L=x[1],F=x[2],U=w[0],K=w[1],X=w[2];return k[0]=L*X-F*K,k[1]=F*U-A*X,k[2]=A*K-L*U,k}function ke(k,x,w,A){var L=x[0],F=x[1],U=x[2];return k[0]=L+A*(w[0]-L),k[1]=F+A*(w[1]-F),k[2]=U+A*(w[2]-U),k}function Ze(k,x,w){var A=x[0],L=x[1],F=x[2],U=w[3]*A+w[7]*L+w[11]*F+w[15];return k[0]=(w[0]*A+w[4]*L+w[8]*F+w[12])/(U=U||1),k[1]=(w[1]*A+w[5]*L+w[9]*F+w[13])/U,k[2]=(w[2]*A+w[6]*L+w[10]*F+w[14])/U,k}function Se(k,x,w){var A=x[0],L=x[1],F=x[2];return k[0]=A*w[0]+L*w[3]+F*w[6],k[1]=A*w[1]+L*w[4]+F*w[7],k[2]=A*w[2]+L*w[5]+F*w[8],k}function Fe(k,x,w){var A=w[0],L=w[1],F=w[2],U=w[3],K=x[0],X=x[1],oe=x[2],ge=L*oe-F*X,we=F*K-A*oe,je=A*X-L*K;return k[0]=K+U*(ge+=ge)+L*(je+=je)-F*(we+=we),k[1]=X+U*we+F*ge-A*je,k[2]=oe+U*je+A*we-L*ge,k}function Ne(k){return k[0]=0,k[1]=0,k[2]=0,k}function Ye(k,x){return k[0]===x[0]&&k[1]===x[1]&&k[2]===x[2]}var Ve=ce,qe=ie,Qe=H;function Ue(){var k=new d(4);return d!=Float32Array&&(k[0]=0,k[1]=0,k[2]=0,k[3]=0),k}function Xe(k,x,w){return k[0]=x[0]*w,k[1]=x[1]*w,k[2]=x[2]*w,k[3]=x[3]*w,k}function nt(k,x){var w=x[0],A=x[1],L=x[2],F=x[3],U=w*w+A*A+L*L+F*F;return U>0&&(U=1/Math.sqrt(U)),k[0]=w*U,k[1]=A*U,k[2]=L*U,k[3]=F*U,k}function $e(k,x){return k[0]*x[0]+k[1]*x[1]+k[2]*x[2]+k[3]*x[3]}function Ge(k,x,w){var A=x[0],L=x[1],F=x[2],U=x[3];return k[0]=w[0]*A+w[4]*L+w[8]*F+w[12]*U,k[1]=w[1]*A+w[5]*L+w[9]*F+w[13]*U,k[2]=w[2]*A+w[6]*L+w[10]*F+w[14]*U,k[3]=w[3]*A+w[7]*L+w[11]*F+w[15]*U,k}function ct(){var k=new d(4);return d!=Float32Array&&(k[0]=0,k[1]=0,k[2]=0),k[3]=1,k}function xt(k){return k[0]=0,k[1]=0,k[2]=0,k[3]=1,k}function qt(k,x,w){w*=.5;var A=x[0],L=x[1],F=x[2],U=x[3],K=Math.sin(w),X=Math.cos(w);return k[0]=A*X+U*K,k[1]=L*X+F*K,k[2]=F*X-L*K,k[3]=U*X-A*K,k}function Vt(k,x,w){w*=.5;var A=x[0],L=x[1],F=x[2],U=x[3],K=Math.sin(w),X=Math.cos(w);return k[0]=A*X-F*K,k[1]=L*X+U*K,k[2]=F*X+A*K,k[3]=U*X-L*K,k}G(),Ue();var Xt,fs,Ft,wt=nt,Ts=(Xt=G(),fs=Y(1,0,0),Ft=Y(0,1,0),function(k,x,w){var A=Pe(x,w);return A<-.999999?(ze(Xt,fs,x),Qe(Xt)<1e-6&&ze(Xt,Ft,x),Ae(Xt,Xt),function(L,F,U){U*=.5;var K=Math.sin(U);L[0]=K*F[0],L[1]=K*F[1],L[2]=K*F[2],L[3]=Math.cos(U)}(k,Xt,Math.PI),k):A>.999999?(k[0]=0,k[1]=0,k[2]=0,k[3]=1,k):(ze(Xt,x,w),k[0]=Xt[0],k[1]=Xt[1],k[2]=Xt[2],k[3]=1+A,wt(k,k))});function vt(){var k=new d(2);return d!=Float32Array&&(k[0]=0,k[1]=0),k}function $s(k,x){var w=new d(2);return w[0]=k,w[1]=x,w}function As(k,x,w){return k[0]=x,k[1]=w,k}function jn(k,x,w){return k[0]=x[0]+w[0],k[1]=x[1]+w[1],k}function ar(k,x,w){return k[0]=x[0]-w[0],k[1]=x[1]-w[1],k}function Dn(k,x,w){return k[0]=x[0]*w,k[1]=x[1]*w,k}function Ur(k){var x=k[0],w=k[1];return Math.sqrt(x*x+w*w)}function Vs(k,x){var w=x[0],A=x[1],L=w*w+A*A;return L>0&&(L=1/Math.sqrt(L)),k[0]=x[0]*L,k[1]=x[1]*L,k}function hn(k,x){return k[0]*x[0]+k[1]*x[1]}ct(),ct(),h();var dr,Cn,Yn=ar;function on(k){return k&&k.__esModule&&Object.prototype.hasOwnProperty.call(k,"default")?k.default:k}vt();var Ir=function(){if(Cn)return dr;function k(x,w,A,L){this.cx=3*x,this.bx=3*(A-x)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*w,this.by=3*(L-w)-this.cy,this.ay=1-this.cy-this.by,this.p1x=x,this.p1y=w,this.p2x=A,this.p2y=L}return Cn=1,dr=k,k.prototype={sampleCurveX:function(x){return((this.ax*x+this.bx)*x+this.cx)*x},sampleCurveY:function(x){return((this.ay*x+this.by)*x+this.cy)*x},sampleCurveDerivativeX:function(x){return(3*this.ax*x+2*this.bx)*x+this.cx},solveCurveX:function(x,w){if(w===void 0&&(w=1e-6),x<0)return 0;if(x>1)return 1;for(var A=x,L=0;L<8;L++){var F=this.sampleCurveX(A)-x;if(Math.abs(F)F?K=A:X=A,A=.5*(X-K)+K;return A},solve:function(x,w){return this.sampleCurveY(this.solveCurveX(x,w))}},dr}(),Wn=on(Ir);function Js(k,x){this.x=k,this.y=x}function Fa(k,x){if(Array.isArray(k)){if(!Array.isArray(x)||k.length!==x.length)return!1;for(let w=0;w=1)return 1;const x=k*k,w=x*k;return 4*(k<.5?w:3*(k-x)+w-.75)}function Wt(k,x,w,A){const L=new Wn(k,x,w,A);return function(F){return L.solve(F)}}const rt=Wt(.25,.1,.25,1);function pt(k,x,w){return Math.min(w,Math.max(x,k))}function jt(k,x,w){return(w=pt((w-k)/(x-k),0,1))*w*(3-2*w)}function Mt(k,x,w){const A=w-x,L=((k-x)%A+A)%A+x;return L===x?w:L}function es(k,x,w){if(!k.length)return w(null,[]);let A=k.length;const L=new Array(k.length);let F=null;k.forEach((U,K)=>{x(U,(X,oe)=>{X&&(F=X),L[K]=oe,--A===0&&w(F,L)})})}let ps=1;function Is(){return ps++}function js(k){return k<=1?1:Math.pow(2,Math.ceil(Math.log2(k)))}function Kt(k,x){k.forEach(w=>{x[w]&&(x[w]=x[w].bind(x))})}function Qs(k,x,w){const A={};for(const L in k)A[L]=x.call(this,k[L],L,k);return A}function an(k,x,w){const A={};for(const L in k)x.call(this,k[L],L,k)&&(A[L]=k[L]);return A}function er(k){return Array.isArray(k)?k.map(er):typeof k=="object"&&k?Qs(k,er):k}function Xr(k,x){for(let w=0;w=0)return!0;return!1}const ma={};function Br(k){ma[k]||(typeof console<"u"&&console.warn(k),ma[k]=!0)}function sa(k,x,w){return(w.y-k.y)*(x.x-k.x)>(x.y-k.y)*(w.x-k.x)}function Rr(k){let x=0;for(let w,A,L=0,F=k.length,U=F-1;L@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g,(w,A,L,F)=>{const U=L||F;return x[A]=!U||U.toLowerCase(),""}),x["max-age"]){const w=parseInt(x["max-age"],10);isNaN(w)?delete x["max-age"]:x["max-age"]=w}return x}let rl,Ii=null;function Ta(k,x){return[k[4*x],k[4*x+1],k[4*x+2],k[4*x+3]]}function eo(k,x,w,A){for(;x>1;k[L]>1;k[L]<=A?x=L+1:w=L}return x}function Ra(k){return k>0?1/(1.001-k):1+k}function Eo(k){return k>0?1-1/(1.001-k):-k}function Ro(k,x,w){return(k-x.min)*(w.max-w.min)/(x.max-x.min)+w.min}const di={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(!di.API_URL)return null;try{const k=new URL(di.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 rr(){return new URL(di.DRACO_URL,di.API_URL).href}function oi(){if(typeof WebAssembly!="object")throw new Error("WebAssembly not supported, cannot instantiate meshoptimizer");return new URL(function(){if(rl===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]);rl=WebAssembly.validate(k)}return rl}()?di.MESHOPT_SIMD_URL:di.MESHOPT_URL,di.API_URL).href}function Oo(){return new URL(di.BUILDING_GEN_URL,di.API_URL).href}function kl(k){return di.API_URL_REGEX.test(k)}function Jo(k){return di.API_SPRITE_REGEX.test(k)}let Sl,vu,Ku,Tp,Bd,xm;function xs(){return Sl==null&&(Sl=self.OffscreenCanvas&&new OffscreenCanvas(1,1).getContext("2d")&&typeof self.createImageBitmap=="function"),Sl}const da={now:()=>Tp!==void 0?Tp:performance.now(),setNow(k){Tp=k},restoreNow(){Tp=void 0},frame(k){const x=requestAnimationFrame(k);return{cancel:()=>cancelAnimationFrame(x)}},getImageData(k,x=0){const{width:w,height:A}=k;Bd||(Bd=document.createElement("canvas"));const L=Bd.getContext("2d",{willReadFrequently:!0});if(!L)throw new Error("failed to create canvas 2d context");return(w>Bd.width||A>Bd.height)&&(Bd.width=w,Bd.height=A),L.clearRect(-x,-x,w+2*x,A+2*x),L.drawImage(k,0,0,w,A),L.getImageData(-x,-x,w+2*x,A+2*x)},resolveURL:k=>(vu||(vu=document.createElement("a")),vu.href=k,vu.href),get devicePixelRatio(){return window.devicePixelRatio},get prefersReducedMotion(){return!!window.matchMedia&&(Ku==null&&(Ku=window.matchMedia("(prefers-reduced-motion: reduce)")),Ku.matches)},hasCanvasFingerprintNoise(){if(xm!==void 0)return xm;if(!xs())return xm=!1,!1;const k=new OffscreenCanvas(85,1),x=k.getContext("2d",{willReadFrequently:!0});let w=0;for(let L=0;L0?`?${F}`:""}`}const no="mapbox-tiles";let Co=500,bi=50;const Bu=["language","worldview","jobid"];let Uu;function Rx(){try{return caches}catch{}}function hl(){const k=Rx();k&&Uu==null&&(Uu=k.open(no))}let Ua=1/0;const ml={supported:!1,testSupport:function(k){!Dv&&Hg&&(Dc?op(k):fg=k)}};let fg,Hg,Dv=!1,Dc=!1;const Mp=typeof self<"u"?self:{};function op(k){const x=k.createTexture();k.bindTexture(k.TEXTURE_2D,x);try{if(k.texImage2D(k.TEXTURE_2D,0,k.RGBA,k.RGBA,k.UNSIGNED_BYTE,Hg),k.isContextLost())return;ml.supported=!0}catch{}k.deleteTexture(x),Dv=!0}Mp.document&&(Hg=Mp.document.createElement("img"),Hg.onload=function(){fg&&op(fg),fg=null,Dc=!0},Hg.onerror=function(){Dv=!0,fg=null},Hg.src="data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAQAAAAfQ//73v/+BiOh/AAA=");const xg={Unknown:"Unknown",Style:"Style",Source:"Source",Tile:"Tile",Glyphs:"Glyphs",SpriteImage:"SpriteImage",SpriteJSON:"SpriteJSON",Iconset:"Iconset",Image:"Image",Model:"Model"};Object.freeze(xg);class Rv extends Error{constructor(x,w,A){w===401&&kl(A)&&(x+=": you may have provided an invalid Mapbox access token. See https://docs.mapbox.com/api/overview/#access-tokens-and-token-scopes"),super(x),this.status=w,this.url=A}toString(){return`${this.name}: ${this.message} (${this.status}): ${this.url}`}}function Xf(k){return typeof k=="object"&&k!==null&&"status"in k&&k.status===404}const Ti=Si()?()=>self.worker.referrer:()=>(location.protocol==="blob:"?parent:self).location.href,gm=function(k,x){return/^file:/.test(w=k.url)||/^file:/.test(Ti())&&!/^\w+:/.test(w)?function(A,L){const F=new XMLHttpRequest;F.open(A.method||"GET",A.url,!0),A.type==="arrayBuffer"&&(F.responseType="arraybuffer");for(const U in A.headers)F.setRequestHeader(U,A.headers[U]);return A.type==="json"&&(F.responseType="text",F.setRequestHeader("Accept","application/json")),F.withCredentials=A.credentials==="include",F.onerror=()=>{L(new Error(F.statusText))},F.onload=()=>{if((F.status>=200&&F.status<300||F.status===0)&&F.response!==null){let U=F.response;if(A.type==="json")try{U=JSON.parse(F.response)}catch(X){return L(X)}const K=new Headers;F.getAllResponseHeaders().trim().split(/[\r\n]+/).forEach(X=>{const oe=X.split(": "),ge=oe.shift(),we=oe.join(": ");K.append(ge,we)}),L(null,U,K)}else L(new Rv(F.statusText,F.status,A.url))},F.send(A.body),{cancel:()=>F.abort()}}(k,x):function(A,L){const F=new AbortController,U=new Request(A.url,{method:A.method||"GET",body:A.body,credentials:A.credentials,headers:A.headers,referrer:Ti(),referrerPolicy:A.referrerPolicy,signal:F.signal});let K=!1,X=!1;const oe=(ge=U.url).indexOf("sku=")>0&&kl(ge);var ge;A.type==="json"&&U.headers.set("Accept","application/json");const we=(Le,Re,We)=>{if(X)return;if(Le&&Le.message!=="SecurityError"&&Br(Le.toString()),Re&&We)return je(Re);const et=Date.now();fetch(U).then(it=>{if(it.ok){const yt=oe?it.clone():null;return je(it,yt,et)}return L(new Rv(it.statusText,it.status,A.url))}).catch(it=>{it.name!=="AbortError"&&L(new Error(`${it.message} ${A.url}`))})},je=(Le,Re,We)=>{(A.type==="arrayBuffer"?Le.arrayBuffer():A.type==="json"?Le.json():Le.text()).then(et=>{X||(Re&&We&&function(it,yt,ht){if(hl(),Uu==null)return;const Et=Gi(yt.headers.get("cache-control")||"");if(Et["no-store"])return;const It={status:yt.status,statusText:yt.statusText,headers:new Headers};yt.headers.forEach((gs,ys)=>It.headers.set(ys,gs)),Et["max-age"]&&It.headers.set("Expires",new Date(ht+1e3*Et["max-age"]).toUTCString());const Ot=It.headers.get("expires");if(!Ot||new Date(Ot).getTime()-ht<42e4)return;let ws=Ma(it.url,{persistentParams:Bu});if(yt.status===206){const gs=it.headers.get("Range");if(!gs)return;It.status=200,ws=so(ws,{range:gs})}const ds=new Response((_s=yt.status)!==200&&_s!==404&&[101,103,204,205,304].includes(_s)?null:yt.body,It);var _s;hl(),Uu!=null&&Uu.then(gs=>gs.put(ws,ds)).catch(gs=>Br(gs.message))}(U,Re,We),K=!0,L(null,et,Le.headers))}).catch(et=>{X||L(new Error(et.message))})};return oe?function(Le,Re){if(hl(),Uu==null)return Re(null);Uu.then(We=>{let et=Ma(Le.url,{persistentParams:Bu});const it=Le.headers.get("Range");it&&(et=so(et,{range:it})),We.match(et).then(yt=>{const ht=function(Et){if(!Et)return!1;const It=new Date(Et.headers.get("expires")||0),Ot=Gi(Et.headers.get("cache-control")||"");return Number(It)>Date.now()&&!Ot["no-cache"]}(yt);We.delete(et).catch(Re),ht&&We.put(et,yt.clone()).catch(Re),Re(null,yt,ht)}).catch(Re)}).catch(Re)}(U,we):we(null,null),{cancel:()=>{X=!0,K||F.abort()}}}(k,x);var w},Gg=function(k,x){return gm(Object.assign(k,{type:"arrayBuffer"}),x)};function wd(k){const x=document.createElement("a");return x.href=k,x.protocol===location.protocol&&x.host===location.host}let jd,Yu;jd=[],Yu=0;const Yh=function(k,x){if(ml.supported&&(k.headers||(k.headers={}),k.headers.accept="image/webp,*/*"),Yu>=di.MAX_PARALLEL_IMAGE_REQUESTS){const F={requestParameters:k,callback:x,cancelled:!1,cancel(){this.cancelled=!0}};return jd.push(F),F}Yu++;let w=!1;const A=()=>{if(!w)for(w=!0,Yu--;jd.length&&Yu{A(),F?x(F):U&&function(X,oe){const ge=new Blob([new Uint8Array(X)],{type:"image/png"});createImageBitmap(ge).then(we=>{oe(null,we)}).catch(we=>{oe(new Error(`Could not load image because of ${we.message}. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported.`))})}(U,(X,oe)=>x(X,oe,K))});return{cancel:()=>{L.cancel(),A()}}};var B0,kh,Sh,Zh={exports:{}},qu={exports:{}},Qf={exports:{}},Dy=function(){if(Sh)return Zh.exports;Sh=1;var k=(B0||(B0=1,qu.exports=function(w,A){var L,F,U,K,X,oe,ge,we;for(F=w.length-(L=3&w.length),U=A,X=3432918353,oe=461845907,we=0;we>>16)*X&65535)<<16)&4294967295)<<15|ge>>>17))*oe+(((ge>>>16)*oe&65535)<<16)&4294967295)<<13|U>>>19))+((5*(U>>>16)&65535)<<16)&4294967295))+(((K>>>16)+58964&65535)<<16);switch(ge=0,L){case 3:ge^=(255&w.charCodeAt(we+2))<<16;case 2:ge^=(255&w.charCodeAt(we+1))<<8;case 1:U^=ge=(65535&(ge=(ge=(65535&(ge^=255&w.charCodeAt(we)))*X+(((ge>>>16)*X&65535)<<16)&4294967295)<<15|ge>>>17))*oe+(((ge>>>16)*oe&65535)<<16)&4294967295}return U^=w.length,U=2246822507*(65535&(U^=U>>>16))+((2246822507*(U>>>16)&65535)<<16)&4294967295,U=3266489909*(65535&(U^=U>>>13))+((3266489909*(U>>>16)&65535)<<16)&4294967295,(U^=U>>>16)>>>0}),qu.exports),x=(kh||(kh=1,Qf.exports=function(w,A){for(var L,F=w.length,U=A^F,K=0;F>=4;)L=1540483477*(65535&(L=255&w.charCodeAt(K)|(255&w.charCodeAt(++K))<<8|(255&w.charCodeAt(++K))<<16|(255&w.charCodeAt(++K))<<24))+((1540483477*(L>>>16)&65535)<<16),U=1540483477*(65535&U)+((1540483477*(U>>>16)&65535)<<16)^(L=1540483477*(65535&(L^=L>>>24))+((1540483477*(L>>>16)&65535)<<16)),F-=4,++K;switch(F){case 3:U^=(255&w.charCodeAt(K+2))<<16;case 2:U^=(255&w.charCodeAt(K+1))<<8;case 1:U=1540483477*(65535&(U^=255&w.charCodeAt(K)))+((1540483477*(U>>>16)&65535)<<16)}return U=1540483477*(65535&(U^=U>>>13))+((1540483477*(U>>>16)&65535)<<16),(U^=U>>>15)>>>0}),Qf.exports);return Zh.exports=k,Zh.exports.murmur3=k,Zh.exports.murmur2=x,Zh.exports}(),dc=on(Dy);class Nd{constructor(x,...w){Object.assign(this,w[0]||{}),this.type=x}}class cf extends Nd{constructor(x,w={}){super("error",Object.assign({error:x},w))}}function iu(k,x,w){w[k]&&w[k].indexOf(x)!==-1||(w[k]=w[k]||[],w[k].push(x))}function lp(k,x,w){if(w&&w[k]){const A=w[k].indexOf(x);A!==-1&&w[k].splice(A,1)}}class Om{on(x,w){return this._listeners=this._listeners||{},iu(x,w,this._listeners),this}off(x,w){return lp(x,w,this._listeners),lp(x,w,this._oneTimeListeners),this}once(x,w){return w?(this._oneTimeListeners=this._oneTimeListeners||{},iu(x,w,this._oneTimeListeners),this):new Promise(A=>{this.once(x,A)})}fire(x,w){const A=typeof x=="string"?new Nd(x,w):x,L=A.type;if(this.listens(L)){A.target=this;const F=this._listeners&&this._listeners[L]?this._listeners[L].slice():[];for(const X of F)X.call(this,A);const U=this._oneTimeListeners&&this._oneTimeListeners[L]?this._oneTimeListeners[L].slice():[];for(const X of U)lp(L,X,this._oneTimeListeners),X.call(this,A);const K=this._eventedParent;if(K){const X=typeof this._eventedParentData=="function"?this._eventedParentData():this._eventedParentData;Object.assign(A,X),K.fire(A)}}else A instanceof cf&&console.error(A.error);return this}listens(x){return!!(this._listeners&&this._listeners[x]&&this._listeners[x].length>0||this._oneTimeListeners&&this._oneTimeListeners[x]&&this._oneTimeListeners[x].length>0||this._eventedParent&&this._eventedParent.listens(x))}setEventedParent(x,w){return this._eventedParent=x,this._eventedParentData=w,this}}class zm{constructor(x){typeof x=="string"?this.name=x:(this.name=x.name,this.iconsetId=x.iconsetId)}static from(x){return new zm(x)}static toString(x){return x.iconsetId?`${x.name}${x.iconsetId}`:x.name}static parse(x){const[w,A]=x.split("");return new zm({name:w,iconsetId:A})}static isEqual(x,w){return x.name===w.name&&x.iconsetId===w.iconsetId}toString(){return zm.toString(this)}serialize(){return{name:this.name,iconsetId:this.iconsetId}}}var ot,Jt={},qs=function(){if(ot)return Jt;ot=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 x(F){return(F=Math.round(F))<0?0:F>255?255:F}function w(F){return x(F[F.length-1]==="%"?parseFloat(F)/100*255:parseInt(F))}function A(F){return(U=F[F.length-1]==="%"?parseFloat(F)/100:parseFloat(F))<0?0:U>1?1:U;var U}function L(F,U,K){return K<0?K+=1:K>1&&(K-=1),6*K<1?F+(U-F)*K*6:2*K<1?U:3*K<2?F+(U-F)*(2/3-K)*6:F}try{Jt.parseCSSColor=function(F){var U,K=F.replace(/ /g,"").toLowerCase();if(K in k)return k[K].slice();if(K[0]==="#")return K.length===4?(U=parseInt(K.substr(1),16))>=0&&U<=4095?[(3840&U)>>4|(3840&U)>>8,240&U|(240&U)>>4,15&U|(15&U)<<4,1]:null:K.length===7&&(U=parseInt(K.substr(1),16))>=0&&U<=16777215?[(16711680&U)>>16,(65280&U)>>8,255&U,1]:null;var X=K.indexOf("("),oe=K.indexOf(")");if(X!==-1&&oe+1===K.length){var ge=K.substr(0,X),we=K.substr(X+1,oe-(X+1)).split(","),je=1;switch(ge){case"rgba":if(we.length!==4)return null;je=A(we.pop());case"rgb":return we.length!==3?null:[w(we[0]),w(we[1]),w(we[2]),je];case"hsla":if(we.length!==4)return null;je=A(we.pop());case"hsl":if(we.length!==3)return null;var Le=(parseFloat(we[0])%360+360)%360/360,Re=A(we[1]),We=A(we[2]),et=We<=.5?We*(Re+1):We+Re-We*Re,it=2*We-et;return[x(255*L(it,et,Le+1/3)),x(255*L(it,et,Le)),x(255*L(it,et,Le-1/3)),je];default:return null}}return null}}catch{}return Jt}();class Xs{constructor(x,w,A,L=1){this.r=x,this.g=w,this.b=A,this.a=L}static parse(x){if(!x)return;if(x instanceof Xs)return x;if(typeof x!="string")return;const w=qs.parseCSSColor(x);return w?new Xs(w[0]/255,w[1]/255,w[2]/255,w[3]):void 0}toString(){const[x,w,A,L]=[this.r,this.g,this.b,this.a];return`rgba(${Math.round(255*x)},${Math.round(255*w)},${Math.round(255*A)},${L})`}toNonPremultipliedRenderColor(x){const{r:w,g:A,b:L,a:F}=this;return new zr(x,w,A,L,F)}toPremultipliedRenderColor(x){const{r:w,g:A,b:L,a:F}=this;return new Wr(x,w*F,A*F,L*F,F)}clone(){return new Xs(this.r,this.g,this.b,this.a)}}class An{constructor(x,w,A,L,F,U=!1){if(this.premultiplied=!1,this.premultiplied=U,x){const K=x.image.height,X=K*K;this.premultiplied?(w=F===0?0:w/F*(K-1),A=F===0?0:A/F*(K-1),L=F===0?0:L/F*(K-1)):(w*=K-1,A*=K-1,L*=K-1),w=Math.max(0,Math.min(K-1,w)),A=Math.max(0,Math.min(K-1,A)),L=Math.max(0,Math.min(K-1,L));const oe=Math.floor(w),ge=Math.floor(A),we=Math.floor(L),je=Math.ceil(w),Le=Math.ceil(A),Re=Math.ceil(L),We=w-oe,et=A-ge,it=L-we,yt=x.image.data,ht=4*(oe+ge*X+we*K),Et=4*(oe+ge*X+Re*K),It=4*(oe+Le*X+we*K),Ot=4*(oe+Le*X+Re*K),ws=4*(je+ge*X+we*K),ds=4*(je+ge*X+Re*K),_s=4*(je+Le*X+we*K),gs=4*(je+Le*X+Re*K);this.r=Ar(Ar(Ar(yt[ht],yt[Et],it),Ar(yt[It],yt[Ot],it),et),Ar(Ar(yt[ws],yt[ds],it),Ar(yt[_s],yt[gs],it),et),We)/255*(this.premultiplied?F:1),this.g=Ar(Ar(Ar(yt[ht+1],yt[Et+1],it),Ar(yt[It+1],yt[Ot+1],it),et),Ar(Ar(yt[ws+1],yt[ds+1],it),Ar(yt[_s+1],yt[gs+1],it),et),We)/255*(this.premultiplied?F:1),this.b=Ar(Ar(Ar(yt[ht+2],yt[Et+2],it),Ar(yt[It+2],yt[Ot+2],it),et),Ar(Ar(yt[ws+2],yt[ds+2],it),Ar(yt[_s+2],yt[gs+2],it),et),We)/255*(this.premultiplied?F:1),this.a=F}else this.r=w,this.g=A,this.b=L,this.a=F}toArray(){const{r:x,g:w,b:A,a:L}=this;return[255*x,255*w,255*A,L]}toHslaArray(){let{r:x,g:w,b:A,a:L}=this;if(this.premultiplied){if(L===0)return[0,0,0,0];const Re=1/L;x*=Re,w*=Re,A*=Re}const F=Math.min(Math.max(x,0),1),U=Math.min(Math.max(w,0),1),K=Math.min(Math.max(A,0),1),X=Math.min(F,U,K),oe=Math.max(F,U,K),ge=oe-X,we=.5*(X+oe);if(ge===0)return[0,0,100*we,L];const je=we>.5?ge/(2-oe-X):ge/(oe+X);let Le;switch(oe){case F:Le=60*((U-K)/ge+(UAr(A,x[L],w))}Xs.black=new Xs(0,0,0,1),Xs.white=new Xs(1,1,1,1),Xs.transparent=new Xs(0,0,0,0),Xs.red=new Xs(1,0,0,1),Xs.blue=new Xs(0,0,1,1);var Po=Object.freeze({__proto__:null,array:wi,color:function(k,x,w){return new Xs(Ar(k.r,x.r,w),Ar(k.g,x.g,w),Ar(k.b,x.b,w),Ar(k.a,x.a,w))},number:Ar});class bo extends Error{constructor(x,w){super(w),this.message=w,this.key=x}}class Vl{constructor(x,w=[]){this.parent=x,this.bindings={};for(const[A,L]of w)this.bindings[A]=L}concat(x){return new Vl(this,x)}get(x){if(this.bindings[x])return this.bindings[x];if(this.parent)return this.parent.get(x);throw new Error(`${x} not found in scope.`)}has(x){return!!this.bindings[x]||!!this.parent&&this.parent.has(x)}}const cd={kind:"null"},$r={kind:"number"},fi={kind:"string"},Ci={kind:"boolean"},tc={kind:"color"},Hc={kind:"object"},ho={kind:"value"},Xh={kind:"collator"},$t={kind:"formatted"},Nn={kind:"resolvedImage"};function Un(k,x){return{kind:"array",itemType:k,N:x}}function qr(k){if(k.kind==="array"){const x=qr(k.itemType);return typeof k.N=="number"?`array<${x}, ${k.N}>`:k.itemType.kind==="value"?"array":`array<${x}>`}return k.kind}const Ea=[cd,$r,fi,Ci,tc,$t,Hc,Un(ho),Nn];function gi(k,x){if(x.kind==="error")return null;if(k.kind==="array"){if(x.kind==="array"&&(x.N===0&&x.itemType.kind==="value"||!gi(k.itemType,x.itemType))&&(typeof k.N!="number"||k.N===x.N))return null}else{if(k.kind===x.kind)return null;if(k.kind==="value"){for(const w of Ea)if(!gi(w,x))return null}}return`Expected ${qr(k)} but found ${qr(x)} instead.`}function Mi(k,x){return x.some(w=>w.kind===k.kind)}function _i(k,x){return x.some(w=>w==="null"?k===null:w==="array"?Array.isArray(k):w==="object"?k&&!Array.isArray(k)&&typeof k=="object":w===typeof k)}function Jc(k,x){return k.kind==="array"&&x.kind==="array"?k.N===x.N&&Jc(k.itemType,x.itemType):k.kind===x.kind}class Su{constructor(x,w,A){this.sensitivity=x?w?"variant":"case":w?"accent":"base",this.locale=A,this.collator=new Intl.Collator(this.locale?this.locale:[],{sensitivity:this.sensitivity,usage:"search"})}compare(x,w){return this.collator.compare(x,w)}resolvedLocale(){return new Intl.Collator(this.locale?this.locale:[]).resolvedOptions().locale}}class cp{constructor(x,w,A,L,F){this.text=x.normalize?x.normalize():x,this.image=w,this.scale=A,this.fontStack=L,this.textColor=F}}class dd{constructor(x){this.sections=x}static fromString(x){return new dd([new cp(x,null,null,null,null)])}isEmpty(){return this.sections.length===0||!this.sections.some(x=>x.text.length!==0||!!x.image&&x.image.hasPrimary())}static factory(x){return x instanceof dd?x:dd.fromString(x)}toString(){return this.sections.length===0?"":this.sections.map(x=>x.text).join("")}serialize(){const x=["format"];for(const w of this.sections){if(w.image){const L=w.image.getPrimary().id.toString();x.push(["image",L]);continue}x.push(w.text);const A={};w.fontStack&&(A["text-font"]=["literal",w.fontStack.split(",")]),w.scale&&(A["font-scale"]=w.scale),w.textColor&&(A["text-color"]=["rgba"].concat(w.textColor.toNonPremultipliedRenderColor(null).toArray())),x.push(A)}return x}}class Ud{constructor(x,w={}){this.id=zm.from(x),this.params=w.params,this.sx=w.sx||1,this.sy=w.sy||1}toString(){return JSON.stringify(this)}static parse(x){let w,A,L,F;try{({id:w,params:A,sx:L,sy:F}=JSON.parse(x)||{})}catch{return null}return w?new Ud(w,{params:A,sx:L,sy:F}):null}scaleSelf(x,w=x){return this.sx*=x,this.sy*=w,this}}class Ch{constructor(x,w,A,L,F=!1){this.primaryId=zm.from(x),this.primaryOptions=w,A&&(this.secondaryId=zm.from(A)),this.secondaryOptions=L,this.available=F}toString(){return this.primaryId&&this.secondaryId?`[${this.primaryId.name},${this.secondaryId.name}]`:this.primaryId.name}hasPrimary(){return!!this.primaryId}getPrimary(){return new Ud(this.primaryId,this.primaryOptions)}hasSecondary(){return!!this.secondaryId}getSecondary(){return this.secondaryId?new Ud(this.secondaryId,this.secondaryOptions):null}static from(x){return typeof x=="string"?Ch.build({name:x}):x}static build(x,w,A,L){return!x||typeof x=="object"&&!("name"in x)?null:new Ch(x,A,w,L)}}function Pp(k,x,w,A){return typeof k=="number"&&k>=0&&k<=255&&typeof x=="number"&&x>=0&&x<=255&&typeof w=="number"&&w>=0&&w<=255?A===void 0||typeof A=="number"&&A>=0&&A<=1?null:`Invalid rgba value [${[k,x,w,A].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid rgba value [${(typeof A=="number"?[k,x,w,A]:[k,x,w]).join(", ")}]: 'r', 'g', and 'b' must be between 0 and 255.`}function Fx(k){if(k===null||typeof k=="string"||typeof k=="boolean"||typeof k=="number"||k instanceof Xs||k instanceof Su||k instanceof dd||k instanceof Ch)return!0;if(Array.isArray(k)){for(const x of k)if(!Fx(x))return!1;return!0}if(typeof k=="object"){for(const x in k)if(!Fx(k[x]))return!1;return!0}return!1}function sc(k){if(k===null)return cd;if(typeof k=="string")return fi;if(typeof k=="boolean")return Ci;if(typeof k=="number")return $r;if(k instanceof Xs)return tc;if(k instanceof Su)return Xh;if(k instanceof dd)return $t;if(k instanceof Ch)return Nn;if(Array.isArray(k)){const x=k.length;let w;for(const A of k){const L=sc(A);if(w){if(w===L)continue;w=ho;break}w=L}return Un(w||ho,x)}return Hc}function Ba(k){const x=typeof k;return k===null?"":x==="string"||x==="number"||x==="boolean"?String(k):k instanceof dd||k instanceof Ch||k instanceof Xs?k.toString():JSON.stringify(k)}class Hr{constructor(x,w){this.type=x,this.value=w}static parse(x,w){if(x.length!==2)return w.error(`'literal' expression requires exactly one argument, but found ${x.length-1} instead.`);if(!Fx(x[1]))return w.error("invalid value");const A=x[1];let L=sc(A);const F=w.expectedType;return L.kind!=="array"||L.N!==0||!F||F.kind!=="array"||typeof F.N=="number"&&F.N!==0||(L=F),new Hr(L,A)}evaluate(){return this.value}eachChild(){}outputDefined(){return!0}serialize(){return this.type.kind==="array"||this.type.kind==="object"?["literal",this.value]:this.value instanceof Xs?["rgba"].concat(this.value.toNonPremultipliedRenderColor(null).toArray()):this.value instanceof dd?this.value.serialize():this.value}}class Cc{constructor(x){this.name="ExpressionEvaluationError",this.message=x}toJSON(){return this.message}}const qa={string:fi,number:$r,boolean:Ci,object:Hc};class Lp{constructor(x,w){this.type=x,this.args=w}static parse(x,w){if(x.length<2)return w.error("Expected at least one argument.");let A,L=1;const F=x[0];if(F==="array"){let K,X;if(x.length>2){const oe=x[1];if(typeof oe!="string"||!(oe in qa)||oe==="object")return w.error('The item type argument of "array" must be one of string, number, boolean',1);K=qa[oe],L++}else K=ho;if(x.length>3){if(x[2]!==null&&(typeof x[2]!="number"||x[2]<0||x[2]!==Math.floor(x[2])))return w.error('The length argument to "array" must be a positive integer literal',2);X=x[2],L++}A=Un(K,X)}else A=qa[F];const U=[];for(;Lx.outputDefined())}serialize(){const x=this.type,w=[x.kind];if(x.kind==="array"){const A=x.itemType;if(A.kind==="string"||A.kind==="number"||A.kind==="boolean"){w.push(A.kind);const L=x.N;(typeof L=="number"||this.args.length>1)&&w.push(L)}}return w.concat(this.args.map(A=>A.serialize()))}}class ou{constructor(x){this.type=$t,this.sections=x}static parse(x,w){if(x.length<2)return w.error("Expected at least one argument.");const A=x[1];if(!Array.isArray(A)&&typeof A=="object")return w.error("First argument must be an image or text section.");const L=[];let F=!1;for(let U=1;U<=x.length-1;++U){const K=x[U];if(F&&typeof K=="object"&&!Array.isArray(K)){F=!1;let X=null;if(K["font-scale"]&&(X=w.parseObjectValue(K["font-scale"],U,"font-scale",$r),!X))return null;let oe=null;if(K["text-font"]&&(oe=w.parseObjectValue(K["text-font"],U,"text-font",Un(fi)),!oe))return null;let ge=null;if(K["text-color"]&&(ge=w.parseObjectValue(K["text-color"],U,"text-color",tc),!ge))return null;const we=L[L.length-1];we.scale=X,we.font=oe,we.textColor=ge}else{const X=w.parse(x[U],U,ho);if(!X)return null;const oe=X.type.kind;if(oe!=="string"&&oe!=="value"&&oe!=="null"&&oe!=="resolvedImage")return w.error("Formatted text type must be 'string', 'value', 'image' or 'null'.");F=!0,L.push({content:X,scale:null,font:null,textColor:null})}}return new ou(L)}evaluate(x){return new dd(this.sections.map(w=>{const A=w.content.evaluate(x);return Jc(sc(A),Nn)?new cp("",A,null,null,null):new cp(Ba(A),null,w.scale?w.scale.evaluate(x):null,w.font?w.font.evaluate(x).join(","):null,w.textColor?w.textColor.evaluate(x):null)}))}eachChild(x){for(const w of this.sections)x(w.content),w.scale&&x(w.scale),w.font&&x(w.font),w.textColor&&x(w.textColor)}outputDefined(){return!1}serialize(){const x=["format"];for(const w of this.sections){x.push(w.content.serialize());const A={};w.scale&&(A["font-scale"]=w.scale.serialize()),w.font&&(A["text-font"]=w.font.serialize()),w.textColor&&(A["text-color"]=w.textColor.serialize()),x.push(A)}return x}}class va{constructor(x,w,A,L){this._imageWarnHistory={},this.type=Nn,this.namePrimary=x,this.nameSecondary=w,A&&(this.paramsPrimary=A.params,this.iconsetIdPrimary=A.iconset?A.iconset.id:void 0),L&&(this.paramsSecondary=L.params,this.iconsetIdSecondary=L.iconset?L.iconset.id:void 0)}static parse(x,w){if(x.length<2)return w.error("Expected two or more arguments.");let A=1;const L=[];function F(){if(Azm.isEqual(U,F)),L.available){const U=L.getSecondary()?L.getSecondary().id:null;U&&(L.available=x.availableImages.some(K=>zm.isEqual(K,U)))}}return L}eachChild(x){if(x(this.namePrimary),this.paramsPrimary)for(const w in this.paramsPrimary)this.paramsPrimary[w]&&x(this.paramsPrimary[w]);if(this.nameSecondary&&(x(this.nameSecondary),this.paramsSecondary))for(const w in this.paramsSecondary)this.paramsSecondary[w]&&x(this.paramsSecondary[w])}outputDefined(){return!1}serializeOptions(x,w){const A={};if(w&&(A.iconset={id:w}),x){A.params={};for(const L in x)x[L]&&(A.params[L]=x[L].serialize())}return Object.keys(A).length>0?A:void 0}serialize(){const x=["image",this.namePrimary.serialize()];if(this.paramsPrimary||this.iconsetIdPrimary){const w=this.serializeOptions(this.paramsPrimary,this.iconsetIdPrimary);w&&x.push(w)}if(this.nameSecondary&&(x.push(this.nameSecondary.serialize()),this.paramsSecondary||this.iconsetIdSecondary)){const w=this.serializeOptions(this.paramsSecondary,this.iconsetIdSecondary);w&&x.push(w)}return x}}function Wg(k){return gg(k)?"string":Ry(k)?"number":Ox(k)?"boolean":Array.isArray(k)?"array":k===null?"null":U0(k)?"object":typeof k}function U0(k){return k!=null&&!Array.isArray(k)&&typeof k!="function"&&!(k instanceof String||k instanceof Number||k instanceof Boolean)&&typeof k=="object"}function gg(k){return typeof k=="string"||k instanceof String}function Ry(k){return typeof k=="number"||k instanceof Number}function Ox(k){return typeof k=="boolean"||k instanceof Boolean}const Td={"to-boolean":Ci,"to-color":tc,"to-number":$r,"to-string":fi};class df{constructor(x,w){this.type=x,this.args=w}static parse(x,w){if(x.length<2)return w.error("Expected at least one argument.");const A=x[0],L=[];let F=cd;if(A==="to-array"){if(!Array.isArray(x[1]))return null;const U=x[1].length;if(w.expectedType){if(w.expectedType.kind!=="array")return w.error(`Expected ${w.expectedType.kind} but found array.`);F=Un(w.expectedType.itemType,U)}else{if(!(U>0&&Fx(x[1][0])))return null;F=Un(sc(x[1][0]),U)}for(let K=0;K4?`Invalid rbga value ${JSON.stringify(w)}: expected an array containing either three or four numeric values.`:Pp(w[0],w[1],w[2],w[3]),!A))return new Xs(w[0]/255,w[1]/255,w[2]/255,w[3])}throw new Cc(A||`Could not parse color from value '${typeof w=="string"?w:String(JSON.stringify(w))}'`)}if(this.type.kind==="number"){let w=null;for(const A of this.args){if(w=A.evaluate(x),w===null)return 0;const L=Number(w);if(!isNaN(L))return L}throw new Cc(`Could not convert ${JSON.stringify(w)} to number.`)}return this.type.kind==="formatted"?dd.fromString(Ba(this.args[0].evaluate(x))):this.type.kind==="resolvedImage"?Ch.build(Ba(this.args[0].evaluate(x))):this.type.kind==="array"?this.args.map(w=>w.evaluate(x)):Ba(this.args[0].evaluate(x))}eachChild(x){this.args.forEach(x)}outputDefined(){return this.args.every(x=>x.outputDefined())}serialize(){if(this.type.kind==="formatted")return new ou([{content:this.args[0],scale:null,font:null,textColor:null}]).serialize();if(this.type.kind==="resolvedImage")return new va(this.args[0]).serialize();const x=this.type.kind==="array"?[]:[`to-${this.type.kind}`];return this.eachChild(w=>{x.push(w.serialize())}),x}}const ym=["Unknown","Point","LineString","Polygon"];class hh{constructor(x,w,A){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=x,this.options=w,this.iconImageUseTheme=A}id(){return this.feature&&this.feature.id!==void 0?this.feature.id:null}geometryType(){return this.feature?typeof this.feature.type=="number"?ym[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(x){return this.globals.brightness||0}distanceFromCenter(){if(this.featureTileCoord&&this.featureDistanceData){const x=this.featureDistanceData.center,w=this.featureDistanceData.scale,{x:A,y:L}=this.featureTileCoord;return this.featureDistanceData.bearing[0]*(A*w-x[0])+this.featureDistanceData.bearing[1]*(L*w-x[1])}return 0}parseColor(x){let w=this._parseColorCache[x];return w||(w=this._parseColorCache[x]=Xs.parse(x)),w}getConfig(x){return this.options?this.options.get(x):null}}class qd{constructor(x,w,A,L,F){this.name=x,this.type=w,this._evaluate=A,this.args=L,this._overloadIndex=F}evaluate(x){if(!this._evaluate){const w=qd.definitions[this.name];this._evaluate=Array.isArray(w)?w[2]:w.overloads[this._overloadIndex][1]}return this._evaluate(x,this.args)}eachChild(x){this.args.forEach(x)}outputDefined(){return!1}serialize(){return[this.name].concat(this.args.map(x=>x.serialize()))}static parse(x,w){const A=x[0],L=qd.definitions[A];if(!L)return w.error(`Unknown expression "${A}". If you wanted a literal array, use ["literal", [...]].`,0);const F=Array.isArray(L)?L[0]:L.type,U=Array.isArray(L)?[[L[1],L[2]]]:L.overloads,K=[];let X=null,oe=-1;for(const[ge,we]of U){if(Array.isArray(ge)&&ge.length!==x.length-1)continue;K.push(ge),oe++,X=new QN(w.registry,w.path,null,w.scope,void 0,w._scope,w.options,w.iconImageUseTheme);const je=[];let Le=!1;for(let Re=1;Reje)).map(uf).join(" | "),we=[];for(let je=1;jew;){if(A-w>600){const X=A-w+1,oe=x-w+1,ge=Math.log(X),we=.5*Math.exp(2*ge/3),je=.5*Math.sqrt(ge*we*(X-we)/X)*(oe-X/2<0?-1:1);T1(k,x,Math.max(w,Math.floor(x-oe*we/X+je)),Math.min(A,Math.floor(x+(X-oe)*we/X+je)),L)}const F=k[x];let U=w,K=A;for(ud(k,w,x),L(k[A],F)>0&&ud(k,w,A);U0;)K--}L(k[w],F)===0?ud(k,w,K):(K++,ud(k,K,A)),K<=x&&(w=K+1),x<=K&&(A=K-1)}}function ud(k,x,w){const A=k[x];k[x]=k[w],k[w]=A}function Kg(k,x){return kx?1:0}function Fy(k){let x=0;for(let w,A,L=0,F=k.length,U=F-1;L=x[2]||k[1]<=x[1]||k[3]>=x[3])}function Rb(k,x,w){const A=k[0]-x[0],L=k[1]-x[1],F=k[0]-w[0],U=k[1]-w[1];return A*U-F*L===0&&A*F<=0&&L*U<=0}function mh(k,x,w){return x[1]>k[1]!=w[1]>k[1]&&k[0]<(w[0]-x[0])*(k[1]-x[1])/(w[1]-x[1])+x[0]}function Ac(k,x,w=!1){let A=!1;for(let L=0,F=x.length;L0&&K<0||U<0&&K>0}function pl(k,x,w,A){return(L=[A[0]-w[0],A[1]-w[1]])[0]*(F=[x[0]-k[0],x[1]-k[1]])[1]-L[1]*F[0]!==0&&!(!Cl(k,x,w,A)||!Cl(w,A,k,x));var L,F}function $u(k){const x=new Js(Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY),w=new Js(Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY);for(const A of k[0])x.x>A.x&&(x.x=A.x),x.y>A.y&&(x.y=A.y),w.xw[2]){const L=.5*A;let F=k[0]-w[0]>L?-A:w[0]-k[0]>L?A:0;F===0&&(F=k[0]-w[2]>L?-A:w[2]-k[0]>L?A:0),k[0]+=F}vm(x,k)}function zy(k,x,w,A){const L=Math.pow(2,A.z)*$d,F=[A.x*$d,A.y*$d],U=[];if(!k)return U;for(const K of k)for(const X of K){const oe=[X.x+F[0],X.y+F[1]];ph(oe,x,w,L),U.push(oe)}return U}function Hj(k,x,w,A){const L=Math.pow(2,A.z)*$d,F=[A.x*$d,A.y*$d],U=[];if(!k)return U;for(const X of k){const oe=[];for(const ge of X){const we=[ge.x+F[0],ge.y+F[1]];vm(x,we),oe.push(we)}U.push(oe)}if(x[2]-x[0]<=L/2){(K=x)[0]=K[1]=1/0,K[2]=K[3]=-1/0;for(const X of U)for(const oe of X)ph(oe,x,w,L)}var K;return U}class By{constructor(x,w){this.type=Ci,this.geojson=x,this.geometries=w}static parse(x,w){if(x.length!==2)return w.error(`'within' expression requires exactly one argument, but found ${x.length-1} instead.`);if(Fx(x[1])){const A=x[1];if(A.type==="FeatureCollection")for(let L=0;Lw)return rw(F,U,(w-(A-K))/K)}return x[x.length-1]}pointToSegmentDistance(x,w,A){let[L,F]=w,U=hf(A[0]-L)*this.kx,K=(A[1]-F)*this.ky;if(U!==0||K!==0){const X=(hf(x[0]-L)*this.kx*U+(x[1]-F)*this.ky*K)/(U*U+K*K);X>1?(L=A[0],F=A[1]):X>0&&(L+=U/this.kx*X,F+=K/this.ky*X)}return U=hf(x[0]-L)*this.kx,K=(x[1]-F)*this.ky,Math.sqrt(U*U+K*K)}pointOnLine(x,w){let A=1/0,L=x[0][0],F=x[0][1],U=0,K=0;for(let X=0;X1?(oe=x[X+1][0],ge=x[X+1][1]):Le>0&&(oe+=we/this.kx*Le,ge+=je/this.ky*Le)),we=hf(w[0]-oe)*this.kx,je=(w[1]-ge)*this.ky;const Re=we*we+je*je;ReF.index||L.index===F.index&&L.t>F.t){const oe=L;L=F,F=oe}const U=[L.point],K=L.index+1,X=F.index;!YN(A[K],U[0])&&K<=X&&U.push(A[K]);for(let oe=K+1;oe<=X;oe++)U.push(A[oe]);return YN(A[X],F.point)||U.push(F.point),U}lineSliceAlong(x,w,A){let L=0;const F=[];for(let U=0;Ux&&F.length===0&&F.push(rw(K,X,(x-(L-oe))/oe)),L>=w)return F.push(rw(K,X,(w-(L-oe))/oe)),F;L>x&&F.push(X)}return F}bufferPoint(x,w){const A=w/this.ky,L=w/this.kx;return[x[0]-L,x[1]-A,x[0]+L,x[1]+A]}bufferBBox(x,w){const A=w/this.ky,L=w/this.kx;return[x[0]-L,x[1]-A,x[2]+L,x[3]+A]}insideBBox(x,w){return hf(x[0]-w[0])>=0&&hf(x[0]-w[2])<=0&&x[1]>=w[1]&&x[1]<=w[3]}}function YN(k,x){return k[0]===x[0]&&k[1]===x[1]}function rw(k,x,w){const A=hf(x[0]-k[0]);return[k[0]+A*w,k[1]+(x[1]-k[1])*w]}function hf(k){for(;k<-180;)k+=360;for(;k>180;)k-=360;return k}class _m{constructor(x=[],w=(A,L)=>AL?1:0){if(this.data=x,this.length=this.data.length,this.compare=w,this.length>0)for(let A=(this.length>>1)-1;A>=0;A--)this._down(A)}push(x){this.data.push(x),this._up(this.length++)}pop(){if(this.length===0)return;const x=this.data[0],w=this.data.pop();return--this.length>0&&(this.data[0]=w,this._down(0)),x}peek(){return this.data[0]}_up(x){const{data:w,compare:A}=this,L=w[x];for(;x>0;){const F=x-1>>1,U=w[F];if(A(L,U)>=0)break;w[x]=U,x=F}w[x]=L}_down(x){const{data:w,compare:A}=this,L=this.length>>1,F=w[x];for(;x=0)break;w[x]=w[U],x=U}w[x]=F}}var ur=8192;function zb(k,x){return x.dist-k.dist}function Bb(k){const x=[1/0,1/0,-1/0,-1/0];if(x.length!==k.length)return!1;for(let w=0;w=k[0]&&k[1]k[1])return[null,null];const w=M1(k);if(x){if(w===2)return[k,null];const A=Math.floor(w/2);return[[k[0],k[0]+A],[k[0]+A,k[1]]]}{if(w===1)return[k,null];const A=Math.floor(w/2)-1;return[[k[0],k[0]+A],[k[0]+A+1,k[1]]]}}function Uy(k,x){const w=[1/0,1/0,-1/0,-1/0];if(!Jf(x,k.length))return w;for(let A=x[0];A<=x[1];++A)vm(w,k[A]);return w}function aw(k){const x=[1/0,1/0,-1/0,-1/0];for(let w=0;wx[2]&&(A=k[0]-x[2]),k[1]>x[3]&&(L=k[1]-x[3]),k[3]=A)return A;if(zx(L,F)){if(iw(k,x))return 0}else if(iw(x,k))return 0;let U=A;for(const K of k)for(let X=0,oe=K.length,ge=oe-1;X=F)continue;const ge=oe.range1;if(M1(ge)<=K){if(!Jf(ge,k.length))return NaN;if(x){const we=hd(k,ge,w,A);if((F=Math.min(F,we))===0)return F}else for(let we=ge[0];we<=ge[1];++we){const je=YE(k[we],w,A);if((F=Math.min(F,je))===0)return F}}else{const we=Fv(ge,x);if(we[0]!==null){const je=P1(Uy(k,we[0]),X,A);je=U)continue;const we=ge.range1,je=ge.range2;if(M1(we)<=X&&M1(je)<=oe){if(!Jf(we,k.length)||!Jf(je,w.length))return NaN;if(x&&A?U=Math.min(U,BL(k,we,w,je,L)):x||A?x&&!A?U=Math.min(U,KS(w,je,k,we,L)):!x&&A&&(U=Math.min(U,KS(k,we,w,je,L))):U=Math.min(U,qC(k,we,w,je,L)),U===0)return U}else{const Le=Fv(we,x),Re=Fv(je,A);Ub(K,U,L,k,w,Le[0],Re[0]),Ub(K,U,L,k,w,Le[0],Re[1]),Ub(K,U,L,k,w,Le[1],Re[0]),Ub(K,U,L,k,w,Le[1],Re[1])}}return U}function Wj(k,x,w,A,L=1/0){let F=L;const U=Uy(k,[0,k.length-1]);for(const K of w)if(!(F!==1/0&&P1(U,Uy(K,[0,K.length-1]),A)>=F)&&(F=Math.min(F,$0(k,x,K,!0,A,F)),F===0))return F;return F}function ow(k,x,w,A,L=1/0){let F=L;const U=Uy(k,[0,k.length-1]);for(const K of w){if(F!==1/0&&P1(U,aw(K),A)>=F)continue;const X=UL(k,x,K,A,F);if(isNaN(X))return X;if((F=Math.min(F,X))===0)return F}return F}function YS(k){return k==="Point"||k==="MultiPoint"||k==="LineString"||k==="MultiLineString"||k==="Polygon"||k==="MultiPolygon"}class qb{constructor(x,w){this.type=$r,this.geojson=x,this.geometries=w}static parse(x,w){if(x.length!==2)return w.error(`'distance' expression requires either one argument, but found ' ${x.length-1} instead.`);if(Fx(x[1])){const A=x[1];if(A.type==="FeatureCollection"){for(let L=0;L{x&&!$b(w)&&(x=!1)}),x}function Bx(k){if(k instanceof qd&&k.name==="feature-state")return!1;let x=!0;return k.eachChild(w=>{x&&!Bx(w)&&(x=!1)}),x}function Zu(k,x){if(k instanceof qd&&x.indexOf(k.name)>=0)return!1;let w=!0;return k.eachChild(A=>{w&&!Zu(A,x)&&(w=!1)}),w}function V0(k,x,w){return[k,x,w].filter(Boolean).join("")}function XN(k,x){switch(k){case"string":return Ba(x);case"number":return+x;case"boolean":return!!x;case"color":return Xs.parse(x);case"formatted":return dd.fromString(Ba(x));case"resolvedImage":return Ch.build(Ba(x))}return x}function VC(k,x,w,A){return A!==void 0&&(k=A*Math.round(k/A)),x!==void 0&&kw&&(k=w),k}class yg{constructor(x,w,A,L=!1){this.type=x,this.key=w,this.scope=A,this.featureConstant=L}static parse(x,w){let A=w.expectedType;if(A==null&&(A=ho),x.length<2||x.length>3)return w.error("Invalid number of arguments for 'config' expression.");const L=w.parse(x[1],1);if(!(L instanceof Hr))return w.error("Key name of 'config' expression must be a string literal.");let F,U=!0;const K=Ba(L.value);if(x.length>=3){const X=w.parse(x[2],2);if(!(X instanceof Hr))return w.error("Scope of 'config' expression must be a string literal.");F=Ba(X.value)}if(w.options){const X=V0(K,F,w._scope),oe=w.options.get(X);oe&&(U=$b(oe.value||oe.default))}return new yg(A,K,F,U)}evaluate(x){const w=V0(this.key,this.scope,x.scope),A=x.getConfig(w);if(!A)return null;const{type:L,value:F,values:U,minValue:K,maxValue:X,stepValue:oe}=A,ge=A.default.evaluate(x);let we=ge;if(F){const je=x.scope;x.scope=(je||"").split("").slice(1).join(""),we=F.evaluate(x),x.scope=je}return L&&(we=XN(L,we)),we===void 0||K===void 0&&X===void 0&&oe===void 0||(typeof we=="number"?we=VC(we,K,X,oe):Array.isArray(we)&&(we=we.map(je=>typeof je=="number"?VC(je,K,X,oe):je))),F!==void 0&&we!==void 0&&U&&!U.includes(we)&&(we=ge,L&&(we=XN(L,we))),(L&&L!==this.type||we!==void 0&&!Jc(sc(we),this.type))&&(we=XN(this.type.kind,we)),we}eachChild(){}outputDefined(){return!1}serialize(){const x=["config",this.key];return this.scope&&x.concat(this.scope),x}}class ex{constructor(x,w){this.type=w.type,this.name=x,this.boundExpression=w}static parse(x,w){if(x.length!==2||typeof x[1]!="string")return w.error("'var' expression requires exactly one string literal argument.");const A=x[1];return w.scope.has(A)?new ex(A,w.scope.get(A)):w.error(`Unknown variable "${A}". Make sure "${A}" has been bound in an enclosing "let" expression before using it.`,1)}evaluate(x){return this.boundExpression.evaluate(x)}eachChild(){}outputDefined(){return!1}serialize(){return["var",this.name]}}class QN{constructor(x,w=[],A,L=new Vl,F=[],U,K,X){this.registry=x,this.path=w,this.key=w.map(oe=>typeof oe=="string"?`['${oe}']`:`[${oe}]`).join(""),this.scope=L,this.errors=F,this.expectedType=A,this._scope=U,this.options=K,this.iconImageUseTheme=X}parse(x,w,A,L,F={}){return w||A?this.concat(w,null,A,L)._parse(x,F):this._parse(x,F)}parseObjectValue(x,w,A,L,F,U={}){return this.concat(w,A,L,F)._parse(x,U)}_parse(x,w){function A(L,F,U){return U==="assert"?new Lp(F,[L]):U==="coerce"?new df(F,[L]):L}if(x!==null&&typeof x!="string"&&typeof x!="boolean"&&typeof x!="number"||(x=["literal",x]),Array.isArray(x)){if(x.length===0)return this.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].');const L=typeof x[0]=="string"?this.registry[x[0]]:void 0;if(L){let F=L.parse(x,this);if(!F)return null;if(this.expectedType){const U=this.expectedType,K=F.type;if(U.kind!=="string"&&U.kind!=="number"&&U.kind!=="boolean"&&U.kind!=="object"&&U.kind!=="array"||K.kind!=="value")if(U.kind!=="color"&&U.kind!=="formatted"&&U.kind!=="resolvedImage"||K.kind!=="value"&&K.kind!=="string"){if(this.checkSubtype(U,K))return null}else F=A(F,U,w.typeAnnotation||"coerce");else F=A(F,U,w.typeAnnotation||"assert")}if(!(F instanceof Hr)&&F.type.kind!=="resolvedImage"&&ZS(F)){const U=new hh(this._scope,this.options,this.iconImageUseTheme);try{F=new Hr(F.type,F.evaluate(U))}catch(K){return this.error(K.message),null}}return F}return df.parse(["to-array",x],this)}return this.error(x===void 0?"'undefined' value invalid. Use null instead.":typeof x=="object"?'Bare objects invalid. Use ["literal", {...}] instead.':`Expected an array, but found ${typeof x} instead.`)}concat(x,w,A,L){let F=typeof x=="number"?this.path.concat(x):this.path;F=typeof w=="string"?F.concat(w):F;const U=L?this.scope.concat(L):this.scope;return new QN(this.registry,F,A||null,U,this.errors,this._scope,this.options,this.iconImageUseTheme)}error(x,...w){const A=`${this.key}${w.map(L=>`[${L}]`).join("")}`;this.errors.push(new bo(A,x))}checkSubtype(x,w){const A=gi(x,w);return A&&this.error(A),A}}function ZS(k){if(k instanceof ex)return ZS(k.boundExpression);if(k instanceof qd&&k.name==="error"||k instanceof E1||k instanceof By||k instanceof qb||k instanceof yg)return!1;const x=k instanceof df||k instanceof Lp;let w=!0;return k.eachChild(A=>{w=x?w&&ZS(A):w&&A instanceof Hr}),!!w&&$b(k)&&Zu(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 Kj(k,x){const w=k.length-1;let A,L,F=0,U=w,K=0;for(;F<=U;)if(K=Math.floor((F+U)/2),A=k[K],L=k[K+1],A<=x){if(K===w||xx))throw new Cc("Input is not a number.");U=K-1}return 0}class Yj{constructor(x,w,A){this.type=x,this.input=w,this.labels=[],this.outputs=[];for(const[L,F]of A)this.labels.push(L),this.outputs.push(F)}static parse(x,w){if(x.length-1<4)return w.error(`Expected at least 4 arguments, but found only ${x.length-1}.`);if((x.length-1)%2!=0)return w.error("Expected an even number of arguments.");const A=w.parse(x[1],1,$r);if(!A)return null;const L=[];let F=null;w.expectedType&&w.expectedType.kind!=="value"&&(F=w.expectedType);for(let U=1;U=K)return w.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.',oe);const we=w.parse(X,ge,F);if(!we)return null;F=F||we.type,L.push([K,we])}return new Yj(F,A,L)}evaluate(x){const w=this.labels,A=this.outputs;if(w.length===1)return A[0].evaluate(x);const L=this.input.evaluate(x);if(L<=w[0])return A[0].evaluate(x);const F=w.length;return L>=w[F-1]?A[F-1].evaluate(x):A[Kj(w,L)].evaluate(x)}eachChild(x){x(this.input);for(const w of this.outputs)x(w)}outputDefined(){return this.outputs.every(x=>x.outputDefined())}serialize(){const x=["step",this.input.serialize()];for(let w=0;w0&&x.push(this.labels[w]),x.push(this.outputs[w].serialize());return x}}const tx=.95047,mf=1.08883,HC=4/29,Ov=6/29,Zj=3*Ov*Ov,Xj=Ov*Ov*Ov,XS=Math.PI/180,QS=180/Math.PI;function JS(k){return k>Xj?Math.pow(k,1/3):k/Zj+HC}function Qj(k){return k>Ov?k*k*k:Zj*(k-HC)}function Jj(k){return 255*(k<=.0031308?12.92*k:1.055*Math.pow(k,1/2.4)-.055)}function lw(k){return(k/=255)<=.04045?k/12.92:Math.pow((k+.055)/1.055,2.4)}function JN(k){const x=lw(k.r),w=lw(k.g),A=lw(k.b),L=JS((.4124564*x+.3575761*w+.1804375*A)/tx),F=JS((.2126729*x+.7151522*w+.072175*A)/1);return{l:116*F-16,a:500*(L-F),b:200*(F-JS((.0193339*x+.119192*w+.9503041*A)/mf)),alpha:k.a}}function e5(k){let x=(k.l+16)/116,w=isNaN(k.a)?x:x+k.a/500,A=isNaN(k.b)?x:x-k.b/200;return x=1*Qj(x),w=tx*Qj(w),A=mf*Qj(A),new Xs(Jj(3.2404542*w-1.5371385*x-.4985314*A),Jj(-.969266*w+1.8760108*x+.041556*A),Jj(.0556434*w-.2040259*x+1.0572252*A),k.alpha)}function ZE(k,x,w){const A=x-k;return k+w*(A>180||A<-180?A-360*Math.round(A/360):A)}const cw={forward:JN,reverse:e5,interpolate:function(k,x,w){return{l:Ar(k.l,x.l,w),a:Ar(k.a,x.a,w),b:Ar(k.b,x.b,w),alpha:Ar(k.alpha,x.alpha,w)}}},zv={forward:function(k){const{l:x,a:w,b:A}=JN(k),L=Math.atan2(A,w)*QS;return{h:L<0?L+360:L,c:Math.sqrt(w*w+A*A),l:x,alpha:k.a}},reverse:function(k){const x=k.h*XS,w=k.c;return e5({l:k.l,a:Math.cos(x)*w,b:Math.sin(x)*w,alpha:k.alpha})},interpolate:function(k,x,w){return{h:ZE(k.h,x.h,w),c:Ar(k.c,x.c,w),l:Ar(k.l,x.l,w),alpha:Ar(k.alpha,x.alpha,w)}}};var e2=Object.freeze({__proto__:null,hcl:zv,lab:cw});class dp{constructor(x,w,A,L,F){this.type=x,this.operator=w,this.interpolation=A,this.input=L,this.labels=[],this.outputs=[];for(const[U,K]of F)this.labels.push(U),this.outputs.push(K)}static interpolationFactor(x,w,A,L){let F=0;if(x.name==="exponential")F=t2(w,x.base,A,L);else if(x.name==="linear")F=t2(w,1,A,L);else if(x.name==="cubic-bezier"){const U=x.controlPoints;F=new Wn(U[0],U[1],U[2],U[3]).solve(t2(w,1,A,L))}return F}static parse(x,w){let[A,L,F,...U]=x;if(!Array.isArray(L)||L.length===0)return w.error("Expected an interpolation type expression.",1);if(L[0]==="linear")L={name:"linear"};else if(L[0]==="exponential"){const oe=L[1];if(typeof oe!="number")return w.error("Exponential interpolation requires a numeric base.",1,1);L={name:"exponential",base:oe}}else{if(L[0]!=="cubic-bezier")return w.error(`Unknown interpolation type ${String(L[0])}`,1,0);{const oe=L.slice(1);if(oe.length!==4||oe.some(ge=>typeof ge!="number"||ge<0||ge>1))return w.error("Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.",1);L={name:"cubic-bezier",controlPoints:oe}}}if(x.length-1<4)return w.error(`Expected at least 4 arguments, but found only ${x.length-1}.`);if(x.length-1>3&&(x.length-1)%2!=0)return w.error("Expected an even number of arguments.");if(F=w.parse(F,2,$r),!F)return null;const K=[];let X=null;A==="interpolate-hcl"||A==="interpolate-lab"?X=tc:w.expectedType&&w.expectedType.kind!=="value"&&(X=w.expectedType);for(let oe=0;oe=ge)return w.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.',je);const Re=w.parse(we,Le,X);if(!Re)return null;X=X||Re.type,K.push([ge,Re])}return X.kind==="number"||X.kind==="color"||X.kind==="array"&&X.itemType.kind==="number"&&typeof X.N=="number"?new dp(X,A,L,F,K):w.error(`Type ${qr(X)} is not interpolatable.`)}evaluate(x){const w=this.labels,A=this.outputs;if(w.length===1)return A[0].evaluate(x);const L=this.input.evaluate(x);if(L<=w[0])return A[0].evaluate(x);const F=w.length;if(L>=w[F-1])return A[F-1].evaluate(x);const U=Kj(w,L),K=dp.interpolationFactor(this.interpolation,L,w[U],w[U+1]),X=A[U].evaluate(x),oe=A[U+1].evaluate(x);return this.operator==="interpolate"?Po[this.type.kind.toLowerCase()](X,oe,K):this.operator==="interpolate-hcl"?zv.reverse(zv.interpolate(zv.forward(X),zv.forward(oe),K)):cw.reverse(cw.interpolate(cw.forward(X),cw.forward(oe),K))}eachChild(x){x(this.input);for(const w of this.outputs)x(w)}outputDefined(){return this.outputs.every(x=>x.outputDefined())}serialize(){let x;x=this.interpolation.name==="linear"?["linear"]:this.interpolation.name==="exponential"?this.interpolation.base===1?["linear"]:["exponential",this.interpolation.base]:["cubic-bezier",...this.interpolation.controlPoints];const w=[this.operator,x,this.input.serialize()];for(let A=0;Agi(L,K.type));return new dw(U?ho:A,F)}evaluate(x){let w,A=null,L=0;for(const F of this.args){if(L++,A=F.evaluate(x),A&&A instanceof Ch&&!A.available&&(w||(w=A),A=null,L===this.args.length))return w;if(A!==null)break}return A}eachChild(x){this.args.forEach(x)}outputDefined(){return this.args.every(x=>x.outputDefined())}serialize(){const x=["coalesce"];return this.eachChild(w=>{x.push(w.serialize())}),x}}class Te{constructor(x,w){this.type=w.type,this.bindings=[].concat(x),this.result=w}evaluate(x){return this.result.evaluate(x)}eachChild(x){for(const w of this.bindings)x(w[1]);x(this.result)}static parse(x,w){if(x.length<4)return w.error(`Expected at least 3 arguments, but found ${x.length-1} instead.`);const A=[];for(let F=1;F=A.length)throw new Cc("Array index out of bounds: index exceeds array size");if(w!==Math.floor(w))throw new Cc("Array index must be an integer. Use at-interpolated for fractional indices");return A[w]}eachChild(x){x(this.index),x(this.input)}outputDefined(){return!1}serialize(){return["at",this.index.serialize(),this.input.serialize()]}}class ft{constructor(x,w,A){this.type=x,this.index=w,this.input=A}static parse(x,w){if(x.length!==3)return w.error(`Expected 2 arguments, but found ${x.length-1} instead.`);const A=w.parse(x[1],1,$r),L=w.parse(x[2],2,Un(w.expectedType||ho));return A&&L?new ft(L.type.itemType,A,L):null}evaluate(x){const w=this.index.evaluate(x),A=this.input.evaluate(x);if(w<0)throw new Cc(`Array index out of bounds: ${w} < 0.`);if(w>A.length-1)throw new Cc(`Array index out of bounds: ${w} > ${A.length-1}.`);if(w===Math.floor(w))return A[w];const L=Math.floor(w),F=Math.ceil(w),U=A[L],K=A[F];if(typeof U!="number"||typeof K!="number")throw new Cc(`Cannot interpolate between non-number values at index ${w}.`);const X=w-L;return U*(1-X)+K*X}eachChild(x){x(this.index),x(this.input)}outputDefined(){return!1}serialize(){return["at-interpolated",this.index.serialize(),this.input.serialize()]}}class _t{constructor(x,w){this.type=Ci,this.needle=x,this.haystack=w}static parse(x,w){if(x.length!==3)return w.error(`Expected 2 arguments, but found ${x.length-1} instead.`),null;const A=w.parse(x[1],1,ho),L=w.parse(x[2],2,ho);return A&&L?Mi(A.type,[Ci,fi,$r,cd,ho])?new _t(A,L):(w.error(`Expected first argument to be of type boolean, string, number or null, but found ${qr(A.type)} instead`),null):null}evaluate(x){const w=this.needle.evaluate(x),A=this.haystack.evaluate(x);if(A==null)return!1;if(!_i(w,["boolean","string","number","null"]))throw new Cc(`Expected first argument to be of type boolean, string, number or null, but found ${qr(sc(w))} instead.`);if(!_i(A,["string","array"]))throw new Cc(`Expected second argument to be of type array or string, but found ${qr(sc(A))} instead.`);return A.indexOf(w)>=0}eachChild(x){x(this.needle),x(this.haystack)}outputDefined(){return!0}serialize(){return["in",this.needle.serialize(),this.haystack.serialize()]}}class ss{constructor(x,w,A){this.type=$r,this.needle=x,this.haystack=w,this.fromIndex=A}static parse(x,w){if(x.length<=2||x.length>=5)return w.error(`Expected 3 or 4 arguments, but found ${x.length-1} instead.`),null;const A=w.parse(x[1],1,ho),L=w.parse(x[2],2,ho);if(!A||!L)return null;if(!Mi(A.type,[Ci,fi,$r,cd,ho]))return w.error(`Expected first argument to be of type boolean, string, number or null, but found ${qr(A.type)} instead`),null;if(x.length===4){const F=w.parse(x[3],3,$r);return F?new ss(A,L,F):null}return new ss(A,L)}evaluate(x){const w=this.needle.evaluate(x),A=this.haystack.evaluate(x);if(!_i(w,["boolean","string","number","null"]))throw new Cc(`Expected first argument to be of type boolean, string, number or null, but found ${qr(sc(w))} instead.`);if(!_i(A,["string","array"]))throw new Cc(`Expected second argument to be of type array or string, but found ${qr(sc(A))} instead.`);if(this.fromIndex){const L=this.fromIndex.evaluate(x);return A.indexOf(w,L)}return A.indexOf(w)}eachChild(x){x(this.needle),x(this.haystack),this.fromIndex&&x(this.fromIndex)}outputDefined(){return!1}serialize(){if(this.fromIndex!=null&&this.fromIndex!==void 0){const x=this.fromIndex.serialize();return["index-of",this.needle.serialize(),this.haystack.serialize(),x]}return["index-of",this.needle.serialize(),this.haystack.serialize()]}}class ms{constructor(x,w,A,L,F,U){this.inputType=x,this.type=w,this.input=A,this.cases=L,this.outputs=F,this.otherwise=U}static parse(x,w){if(x.length<5)return w.error(`Expected at least 4 arguments, but found only ${x.length-1}.`);if(x.length%2!=1)return w.error("Expected an even number of arguments.");let A,L;w.expectedType&&w.expectedType.kind!=="value"&&(L=w.expectedType);const F={},U=[];for(let oe=2;oeNumber.MAX_SAFE_INTEGER)return je.error(`Branch labels must be integers no larger than ${Number.MAX_SAFE_INTEGER}.`);if(typeof Re=="number"&&Math.floor(Re)!==Re)return je.error("Numeric branch labels must be integer values.");if(A){if(je.checkSubtype(A,sc(Re)))return null}else A=sc(Re);if(F[String(Re)]!==void 0)return je.error("Branch labels must be unique.");F[String(Re)]=U.length}const Le=w.parse(we,oe,L);if(!Le)return null;L=L||Le.type,U.push(Le)}const K=w.parse(x[1],1,ho);if(!K)return null;const X=w.parse(x[x.length-1],x.length-1,L);return X?K.type.kind!=="value"&&w.concat(1).checkSubtype(A,K.type)?null:new ms(A,L,K,F,U,X):null}evaluate(x){const w=this.input.evaluate(x);return(Jc(sc(w),this.inputType)&&this.outputs[this.cases[w]]||this.otherwise).evaluate(x)}eachChild(x){x(this.input),this.outputs.forEach(x),x(this.otherwise)}outputDefined(){return this.outputs.every(x=>x.outputDefined())&&this.otherwise.outputDefined()}serialize(){const x=["match",this.input.serialize()],w=Object.keys(this.cases).sort(),A=[],L={};for(const U of w){const K=L[this.cases[U]];K===void 0?(L[this.cases[U]]=A.length,A.push([this.cases[U],[U]])):A[K][1].push(U)}const F=U=>this.inputType.kind==="number"?Number(U):U;for(const[U,K]of A)x.push(K.length===1?F(K[0]):K.map(F)),x.push(this.outputs[U].serialize());return x.push(this.otherwise.serialize()),x}}class vs{constructor(x,w,A){this.type=x,this.branches=w,this.otherwise=A}static parse(x,w){if(x.length<4)return w.error(`Expected at least 3 arguments, but found only ${x.length-1}.`),null;if(x.length%2!=0)return w.error("Expected an odd number of arguments."),null;let A;w.expectedType&&w.expectedType.kind!=="value"&&(A=w.expectedType);const L=[];for(let U=1;Uw.outputDefined())&&this.otherwise.outputDefined()}serialize(){const x=["case"];return this.eachChild(w=>{x.push(w.serialize())}),x}}class Cs{constructor(x,w,A,L){this.type=x,this.input=w,this.beginIndex=A,this.endIndex=L}static parse(x,w){if(x.length<=2||x.length>=5)return w.error(`Expected 3 or 4 arguments, but found ${x.length-1} instead.`),null;const A=w.parse(x[1],1,ho),L=w.parse(x[2],2,$r);if(!A||!L)return null;if(!Mi(A.type,[Un(ho),fi,ho]))return w.error(`Expected first argument to be of type array or string, but found ${qr(A.type)} instead`),null;if(x.length===4){const F=w.parse(x[3],3,$r);return F?new Cs(A.type,A,L,F):null}return new Cs(A.type,A,L)}evaluate(x){const w=this.input.evaluate(x),A=this.beginIndex.evaluate(x);if(!_i(w,["string","array"]))throw new Cc(`Expected first argument to be of type array or string, but found ${qr(sc(w))} instead.`);if(this.endIndex){const L=this.endIndex.evaluate(x);return w.slice(A,L)}return w.slice(A)}eachChild(x){x(this.input),x(this.beginIndex),this.endIndex&&x(this.endIndex)}outputDefined(){return!1}serialize(){if(this.endIndex!=null&&this.endIndex!==void 0){const x=this.endIndex.serialize();return["slice",this.input.serialize(),this.beginIndex.serialize(),x]}return["slice",this.input.serialize(),this.beginIndex.serialize()]}}class Rs{constructor(x,w){this.type=Un(fi),this.str=x,this.delimiter=w}static parse(x,w){if(x.length!==3)return w.error(`Expected 2 arguments, but found ${x.length-1} instead.`);const A=w.parse(x[1],1,fi),L=w.parse(x[2],2,fi);return A&&L?new Rs(A,L):void 0}evaluate(x){const w=this.str.evaluate(x),A=this.delimiter.evaluate(x);return w.split(A)}eachChild(x){x(this.str),x(this.delimiter)}outputDefined(){return!1}serialize(){return["split",this.str.serialize(),this.delimiter.serialize()]}}function en(k,x){return k==="=="||k==="!="?x.kind==="boolean"||x.kind==="string"||x.kind==="number"||x.kind==="null"||x.kind==="value":x.kind==="string"||x.kind==="number"||x.kind==="value"}function Mn(k,x,w,A){return A.compare(x,w)===0}function Xn(k,x,w){const A=k!=="=="&&k!=="!=";return class CFt{constructor(F,U,K){this.type=Ci,this.lhs=F,this.rhs=U,this.collator=K,this.hasUntypedArgument=F.type.kind==="value"||U.type.kind==="value"}static parse(F,U){if(F.length!==3&&F.length!==4)return U.error("Expected two or three arguments.");const K=F[0];let X=U.parse(F[1],1,ho);if(!X)return null;if(!en(K,X.type))return U.concat(1).error(`"${K}" comparisons are not supported for type '${qr(X.type)}'.`);let oe=U.parse(F[2],2,ho);if(!oe)return null;if(!en(K,oe.type))return U.concat(2).error(`"${K}" comparisons are not supported for type '${qr(oe.type)}'.`);if(X.type.kind!==oe.type.kind&&X.type.kind!=="value"&&oe.type.kind!=="value")return U.error(`Cannot compare types '${qr(X.type)}' and '${qr(oe.type)}'.`);A&&(X.type.kind==="value"&&oe.type.kind!=="value"?X=new Lp(oe.type,[X]):X.type.kind!=="value"&&oe.type.kind==="value"&&(oe=new Lp(X.type,[oe])));let ge=null;if(F.length===4){if(X.type.kind!=="string"&&oe.type.kind!=="string"&&X.type.kind!=="value"&&oe.type.kind!=="value")return U.error("Cannot use collator to compare non-string types.");if(ge=U.parse(F[3],3,Xh),!ge)return null}return new CFt(X,oe,ge)}evaluate(F){const U=this.lhs.evaluate(F),K=this.rhs.evaluate(F);if(A&&this.hasUntypedArgument){const X=sc(U),oe=sc(K);if(X.kind!==oe.kind||X.kind!=="string"&&X.kind!=="number")throw new Cc(`Expected arguments for "${k}" to be (string, string) or (number, number), but found (${X.kind}, ${oe.kind}) instead.`)}if(this.collator&&!A&&this.hasUntypedArgument){const X=sc(U),oe=sc(K);if(X.kind!=="string"||oe.kind!=="string")return x(F,U,K)}return this.collator?w(F,U,K,this.collator.evaluate(F)):x(F,U,K)}eachChild(F){F(this.lhs),F(this.rhs),this.collator&&F(this.collator)}outputDefined(){return!0}serialize(){const F=[k];return this.eachChild(U=>{F.push(U.serialize())}),F}}}const tn=Xn("==",function(k,x,w){return x===w},Mn),$n=Xn("!=",function(k,x,w){return x!==w},function(k,x,w,A){return!Mn(0,x,w,A)}),nr=Xn("<",function(k,x,w){return x",function(k,x,w){return x>w},function(k,x,w,A){return A.compare(x,w)>0}),br=Xn("<=",function(k,x,w){return x<=w},function(k,x,w,A){return A.compare(x,w)<=0}),Vn=Xn(">=",function(k,x,w){return x>=w},function(k,x,w,A){return A.compare(x,w)>=0});class Vr{constructor(x,w,A,L,F,U){this.type=fi,this.number=x,this.locale=w,this.currency=A,this.unit=L,this.minFractionDigits=F,this.maxFractionDigits=U}static parse(x,w){if(x.length!==3)return w.error("Expected two arguments.");const A=w.parse(x[1],1,$r);if(!A)return null;const L=x[2];if(typeof L!="object"||Array.isArray(L))return w.error("NumberFormat options argument must be an object.");let F=null;if(L.locale&&(F=w.parseObjectValue(L.locale,2,"locale",fi),!F))return null;let U=null;if(L.currency&&(U=w.parseObjectValue(L.currency,2,"currency",fi),!U))return null;let K=null;if(L.unit&&(K=w.parseObjectValue(L.unit,2,"unit",fi),!K))return null;let X=null;if(L["min-fraction-digits"]&&(X=w.parseObjectValue(L["min-fraction-digits"],2,"min-fraction-digits",$r),!X))return null;let oe=null;return L["max-fraction-digits"]&&(oe=w.parseObjectValue(L["max-fraction-digits"],2,"max-fraction-digits",$r),!oe)?null:new Vr(A,F,U,K,X,oe)}evaluate(x){return new Intl.NumberFormat(this.locale?this.locale.evaluate(x):[],{style:(this.currency?"currency":this.unit&&"unit")||"decimal",currency:this.currency?this.currency.evaluate(x):void 0,unit:this.unit?this.unit.evaluate(x):void 0,minimumFractionDigits:this.minFractionDigits?this.minFractionDigits.evaluate(x):void 0,maximumFractionDigits:this.maxFractionDigits?this.maxFractionDigits.evaluate(x):void 0}).format(this.number.evaluate(x))}eachChild(x){x(this.number),this.locale&&x(this.locale),this.currency&&x(this.currency),this.unit&&x(this.unit),this.minFractionDigits&&x(this.minFractionDigits),this.maxFractionDigits&&x(this.maxFractionDigits)}outputDefined(){return!1}serialize(){const x={};return this.locale&&(x.locale=this.locale.serialize()),this.currency&&(x.currency=this.currency.serialize()),this.unit&&(x.unit=this.unit.serialize()),this.minFractionDigits&&(x["min-fraction-digits"]=this.minFractionDigits.serialize()),this.maxFractionDigits&&(x["max-fraction-digits"]=this.maxFractionDigits.serialize()),["number-format",this.number.serialize(),x]}}class Sa{constructor(x){this.type=$r,this.input=x}static parse(x,w){if(x.length!==2)return w.error(`Expected 1 argument, but found ${x.length-1} instead.`),null;const A=w.parse(x[1],1);return A?A.type.kind!=="array"&&A.type.kind!=="string"&&A.type.kind!=="value"?(w.error(`Expected argument of type string or array, but found ${qr(A.type)} instead.`),null):new Sa(A):null}evaluate(x){const w=this.input.evaluate(x);if(typeof w=="string"||Array.isArray(w))return w.length;throw new Cc(`Expected value to be of type string or array, but found ${qr(sc(w))} instead.`)}eachChild(x){x(this.input)}outputDefined(){return!1}serialize(){const x=["length"];return this.eachChild(w=>{x.push(w.serialize())}),x}}function ba(k){return function(){k=1831565813+(k|=0)|0;let x=Math.imul(k^k>>>15,1|k);return x=x+Math.imul(x^x>>>7,61|x)^x,((x^x>>>14)>>>0)/4294967296}}const ro={"==":tn,"!=":$n,">":Mr,"<":nr,">=":Vn,"<=":br,array:Lp,at:Be,"at-interpolated":ft,boolean:Lp,case:vs,coalesce:dw,collator:E1,format:ou,image:va,in:_t,"index-of":ss,interpolate:dp,"interpolate-hcl":dp,"interpolate-lab":dp,length:Sa,let:Te,literal:Hr,match:ms,number:Lp,"number-format":Vr,object:Lp,slice:Cs,step:Yj,string:Lp,"to-boolean":df,"to-color":df,"to-number":df,"to-string":df,var:ex,within:By,distance:qb,config:yg,split:Rs};function Oi(k,[x,w,A,L]){x=x.evaluate(k),w=w.evaluate(k),A=A.evaluate(k);const F=L?L.evaluate(k):1,U=Pp(x,w,A,F);if(U)throw new Cc(U);return new Xs(x/255,w/255,A/255,F)}function Al(k,[x,w,A,L]){x=x.evaluate(k),w=w.evaluate(k),A=A.evaluate(k);const F=L?L.evaluate(k):1,U=function(oe,ge,we,je){return typeof oe=="number"&&oe>=0&&oe<=360?typeof ge=="number"&&ge>=0&&ge<=100&&typeof we=="number"&&we>=0&&we<=100?je===void 0||typeof je=="number"&&je>=0&&je<=1?null:`Invalid hsla value [${[oe,ge,we,je].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid hsla value [${(typeof je=="number"?[oe,ge,we,je]:[oe,ge,we]).join(", ")}]: 's', and 'l' must be between 0 and 100.`:`Invalid hsla value [${(typeof je=="number"?[oe,ge,we,je]:[oe,ge,we]).join(", ")}]: 'h' must be between 0 and 360.`}(x,w,A,F);if(U)throw new Cc(U);const K=`hsla(${x}, ${w}%, ${A}%, ${F})`,X=Xs.parse(K);if(!X)throw new Cc(`Failed to parse HSLA color: ${K}`);return X}function Ki(k,x){return k in x}function xc(k,x){const w=x[k];return w===void 0?null:w}function Cu(k){return{type:k}}function El(k){if(k instanceof yg)return new Set([k.key]);let x=new Set;return k.eachChild(w=>{x=new Set([...x,...El(w)])}),x}function Qi(k){if(k instanceof qd&&k.name==="is-active-floor")return!0;let x=!1;return k.eachChild(w=>{!x&&Qi(w)&&(x=!0)}),x}function mi(k){return{result:"success",value:k}}function Ll(k){return{result:"error",value:k}}function Ao(k,x){return!!k&&!!k.parameters&&k.parameters.indexOf(x)>-1}function gl(k){return k["property-type"]==="data-driven"}function bu(k){return Ao(k.expression,"measure-light")}function Bm(k){return Ao(k.expression,"zoom")}function _u(k){return!!k.expression&&k.expression.interpolated}function Xu(k){return typeof k=="object"&&k!==null&&!Array.isArray(k)}function Vu(k){return k}function sx(k,x){const w=x.type==="color",A=k.stops&&typeof k.stops[0][0]=="object",L=A||!(A||k.property!==void 0),F=k.type||(_u(x)?"exponential":"interval");if(w&&((k=Object.assign({},k)).stops&&(k.stops=k.stops.map(oe=>[oe[0],Xs.parse(oe[1])])),k.default=Xs.parse(k.default?k.default:x.default)),k.colorSpace&&k.colorSpace!=="rgb"&&!e2[k.colorSpace])throw new Error(`Unknown color space: ${k.colorSpace}`);let U,K,X;if(F==="exponential")U=fh;else if(F==="interval")U=Vd;else if(F==="categorical"){U=ed,K=Object.create(null);for(const oe of k.stops)K[oe[0]]=oe[1];X=typeof k.stops[0][0]}else{if(F!=="identity")throw new Error(`Unknown function type "${F}"`);U=md}if(A){const oe={},ge=[];for(let Le=0;LeLe[0]),evaluate:({zoom:Le},Re)=>fh({stops:we,base:k.base},x,Le).evaluate(Le,Re)}}if(L){const oe=F==="exponential"?{name:"exponential",base:k.base!==void 0?k.base:1}:null;return{kind:"camera",interpolationType:oe,interpolationFactor:dp.interpolationFactor.bind(void 0,oe),zoomStops:k.stops.map(ge=>ge[0]),evaluate:({zoom:ge})=>U(k,x,ge,K,X)}}return{kind:"source",evaluate(oe,ge){const we=ge&&ge.properties?ge.properties[k.property]:void 0;return we===void 0?lu(k.default,x.default):U(k,x,we,K,X)}}}function lu(k,x,w){return k!==void 0?k:x!==void 0?x:w!==void 0?w:void 0}function ed(k,x,w,A,L){return lu(typeof w===L?A[w]:void 0,k.default,x.default)}function Vd(k,x,w){if(!Ry(w))return lu(k.default,x.default);const A=k.stops.length;if(A===1||w<=k.stops[0][0])return k.stops[0][1];if(w>=k.stops[A-1][0])return k.stops[A-1][1];const L=Kj(k.stops.map(F=>F[0]),w);return k.stops[L][1]}function fh(k,x,w){const A=k.base!==void 0?k.base:1;if(!Ry(w))return lu(k.default,x.default);const L=k.stops.length;if(L===1||w<=k.stops[0][0])return k.stops[0][1];if(w>=k.stops[L-1][0])return k.stops[L-1][1];const F=Kj(k.stops.map(ge=>ge[0]),w),U=function(ge,we,je,Le){const Re=Le-je,We=ge-je;return Re===0?0:we===1?We/Re:(Math.pow(we,We)-1)/(Math.pow(we,Re)-1)}(w,A,k.stops[F][0],k.stops[F+1][0]),K=k.stops[F][1],X=k.stops[F+1][1];let oe=Po[x.type]||Vu;if(k.colorSpace&&k.colorSpace!=="rgb"){const ge=e2[k.colorSpace];oe=(we,je)=>ge.reverse(ge.interpolate(ge.forward(we),ge.forward(je),U))}return typeof K.evaluate=="function"?{evaluate(...ge){const we=K.evaluate.apply(void 0,ge),je=X.evaluate.apply(void 0,ge);if(we!==void 0&&je!==void 0)return oe(we,je,U)}}:oe(K,X,U)}function md(k,x,w){return x.type==="color"?w=Xs.parse(w):x.type==="formatted"?w=dd.fromString(w.toString()):x.type==="resolvedImage"?w=Ch.build(w.toString()):Wg(w)===x.type||x.type==="enum"&&x.values[w]||(w=void 0),lu(w,k.default,x.default)}qd.register(ro,{error:[{kind:"error"},[fi],(k,[x])=>{throw new Cc(x.evaluate(k))}],typeof:[fi,[ho],(k,[x])=>qr(sc(x.evaluate(k)))],"to-rgba":[Un($r,4),[tc],(k,[x])=>x.evaluate(k).toNonPremultipliedRenderColor(null).toArray()],"to-hsla":[Un($r,4),[tc],(k,[x])=>x.evaluate(k).toNonPremultipliedRenderColor(null).toHslaArray()],rgb:[tc,[$r,$r,$r],Oi],rgba:[tc,[$r,$r,$r,$r],Oi],hsl:[tc,[$r,$r,$r],Al],hsla:[tc,[$r,$r,$r,$r],Al],has:{type:Ci,overloads:[[[fi],(k,[x])=>Ki(x.evaluate(k),k.properties())],[[fi,Hc],(k,[x,w])=>Ki(x.evaluate(k),w.evaluate(k))]]},get:{type:ho,overloads:[[[fi],(k,[x])=>xc(x.evaluate(k),k.properties())],[[fi,Hc],(k,[x,w])=>xc(x.evaluate(k),w.evaluate(k))]]},"feature-state":[ho,[fi],(k,[x])=>xc(x.evaluate(k),k.featureState||{})],properties:[Hc,[],k=>k.properties()],"geometry-type":[fi,[],k=>k.geometryType()],worldview:[fi,[],k=>k.globals.worldview||""],"is-active-floor":[Ci,Cu(fi),(k,x)=>{if(!(k.globals&&k.globals.activeFloors&&k.globals.activeFloors.size>0))return!1;if(x.length===0)return!0;const w=k.globals.activeFloors;return x.some(A=>{const L=A.evaluate(k);return w.has(L)})}],id:[ho,[],k=>k.id()],zoom:[$r,[],k=>k.globals.zoom],pitch:[$r,[],k=>k.globals.pitch||0],"distance-from-center":[$r,[],k=>k.distanceFromCenter()],"measure-light":[$r,[fi],(k,[x])=>k.measureLight(x.evaluate(k))],"heatmap-density":[$r,[],k=>k.globals.heatmapDensity||0],"line-progress":[$r,[],k=>k.globals.lineProgress||0],"raster-value":[$r,[],k=>k.globals.rasterValue||0],"raster-particle-speed":[$r,[],k=>k.globals.rasterParticleSpeed||0],"sky-radial-progress":[$r,[],k=>k.globals.skyRadialProgress||0],accumulated:[ho,[],k=>k.globals.accumulated===void 0?null:k.globals.accumulated],"+":[$r,Cu($r),(k,x)=>{let w=0;for(const A of x)w+=A.evaluate(k);return w}],"*":[$r,Cu($r),(k,x)=>{let w=1;for(const A of x)w*=A.evaluate(k);return w}],"-":{type:$r,overloads:[[[$r,$r],(k,[x,w])=>x.evaluate(k)-w.evaluate(k)],[[$r],(k,[x])=>-x.evaluate(k)]]},"/":[$r,[$r,$r],(k,[x,w])=>x.evaluate(k)/w.evaluate(k)],"%":[$r,[$r,$r],(k,[x,w])=>x.evaluate(k)%w.evaluate(k)],ln2:[$r,[],()=>Math.LN2],pi:[$r,[],()=>Math.PI],e:[$r,[],()=>Math.E],"^":[$r,[$r,$r],(k,[x,w])=>Math.pow(x.evaluate(k),w.evaluate(k))],sqrt:[$r,[$r],(k,[x])=>Math.sqrt(x.evaluate(k))],log10:[$r,[$r],(k,[x])=>Math.log(x.evaluate(k))/Math.LN10],ln:[$r,[$r],(k,[x])=>Math.log(x.evaluate(k))],log2:[$r,[$r],(k,[x])=>Math.log2(x.evaluate(k))],sin:[$r,[$r],(k,[x])=>Math.sin(x.evaluate(k))],cos:[$r,[$r],(k,[x])=>Math.cos(x.evaluate(k))],tan:[$r,[$r],(k,[x])=>Math.tan(x.evaluate(k))],asin:[$r,[$r],(k,[x])=>Math.asin(x.evaluate(k))],acos:[$r,[$r],(k,[x])=>Math.acos(x.evaluate(k))],atan:[$r,[$r],(k,[x])=>Math.atan(x.evaluate(k))],min:[$r,Cu($r),(k,x)=>Math.min(...x.map(w=>w.evaluate(k)))],max:[$r,Cu($r),(k,x)=>Math.max(...x.map(w=>w.evaluate(k)))],abs:[$r,[$r],(k,[x])=>Math.abs(x.evaluate(k))],round:[$r,[$r],(k,[x])=>{const w=x.evaluate(k);return w<0?-Math.round(-w):Math.round(w)}],floor:[$r,[$r],(k,[x])=>Math.floor(x.evaluate(k))],ceil:[$r,[$r],(k,[x])=>Math.ceil(x.evaluate(k))],"filter-==":[Ci,[fi,ho],(k,[x,w])=>k.properties()[x.value]===w.value],"filter-id-==":[Ci,[ho],(k,[x])=>k.id()===x.value],"filter-type-==":[Ci,[fi],(k,[x])=>k.geometryType()===x.value],"filter-<":[Ci,[fi,ho],(k,[x,w])=>{const A=k.properties()[x.value],L=w.value;return typeof A==typeof L&&A{const w=k.id(),A=x.value;return typeof w==typeof A&&w":[Ci,[fi,ho],(k,[x,w])=>{const A=k.properties()[x.value],L=w.value;return typeof A==typeof L&&A>L}],"filter-id->":[Ci,[ho],(k,[x])=>{const w=k.id(),A=x.value;return typeof w==typeof A&&w>A}],"filter-<=":[Ci,[fi,ho],(k,[x,w])=>{const A=k.properties()[x.value],L=w.value;return typeof A==typeof L&&A<=L}],"filter-id-<=":[Ci,[ho],(k,[x])=>{const w=k.id(),A=x.value;return typeof w==typeof A&&w<=A}],"filter->=":[Ci,[fi,ho],(k,[x,w])=>{const A=k.properties()[x.value],L=w.value;return typeof A==typeof L&&A>=L}],"filter-id->=":[Ci,[ho],(k,[x])=>{const w=k.id(),A=x.value;return typeof w==typeof A&&w>=A}],"filter-has":[Ci,[ho],(k,[x])=>x.value in k.properties()],"filter-has-id":[Ci,[],k=>k.id()!==null&&k.id()!==void 0],"filter-type-in":[Ci,[Un(fi)],(k,[x])=>x.value.indexOf(k.geometryType())>=0],"filter-id-in":[Ci,[Un(ho)],(k,[x])=>x.value.indexOf(k.id())>=0],"filter-in-small":[Ci,[fi,Un(ho)],(k,[x,w])=>w.value.indexOf(k.properties()[x.value])>=0],"filter-in-large":[Ci,[fi,Un(ho)],(k,[x,w])=>function(A,L,F,U){for(;F<=U;){const K=F+U>>1;if(L[K]===A)return!0;L[K]>A?U=K-1:F=K+1}return!1}(k.properties()[x.value],w.value,0,w.value.length-1)],all:{type:Ci,overloads:[[[Ci,Ci],(k,[x,w])=>x.evaluate(k)&&w.evaluate(k)],[Cu(Ci),(k,x)=>{for(const w of x)if(!w.evaluate(k))return!1;return!0}]]},any:{type:Ci,overloads:[[[Ci,Ci],(k,[x,w])=>x.evaluate(k)||w.evaluate(k)],[Cu(Ci),(k,x)=>{for(const w of x)if(w.evaluate(k))return!0;return!1}]]},"!":[Ci,[Ci],(k,[x])=>!x.evaluate(k)],"is-supported-script":[Ci,[fi],(k,[x])=>{const w=k.globals&&k.globals.isSupportedScript;return!w||w(x.evaluate(k))}],upcase:[fi,[fi],(k,[x])=>x.evaluate(k).toUpperCase()],downcase:[fi,[fi],(k,[x])=>x.evaluate(k).toLowerCase()],concat:[fi,Cu(ho),(k,x)=>x.map(w=>Ba(w.evaluate(k))).join("")],"resolved-locale":[fi,[Xh],(k,[x])=>x.evaluate(k).resolvedLocale()],random:[$r,[$r,$r,ho],(k,x)=>{const[w,A,L]=x.map(U=>U.evaluate(k));if(w>A||w===A)return w;let F;if(typeof L=="string")F=function(U){let K=0;if(U.length===0)return K;for(let X=0;XJSON.stringify(we)).join(", ")}, but found ${JSON.stringify(ge)} instead.`);return ge}catch(ge){const we=ge;return this._warningHistory[we.message]||(this._warningHistory[we.message]=!0,typeof console<"u"&&console.warn(`Failed to evaluate expression "${JSON.stringify(this.expression.serialize())}". ${we.message}`)),this._defaultValue}}}function Ip(k){return Array.isArray(k)&&k.length>0&&typeof k[0]=="string"&&k[0]in ro}function Md(k,x,w,A,L){const F=new QN(ro,[],x?function(K){const X={color:tc,string:fi,number:$r,enum:fi,boolean:Ci,formatted:$t,resolvedImage:Nn};return K.type==="array"?Un(X[K.value]||ho,K.length):X[K.type]}(x):void 0,void 0,void 0,w,A,L),U=F.parse(k,void 0,void 0,void 0,x&&x.type==="string"?{typeAnnotation:"coerce"}:void 0);return U?mi(new Ah(U,x,w,A,L)):Ll(F.errors)}class Qh{constructor(x,w,A,L){this.kind=x,this._styleExpression=w,this.isLightConstant=A,this.isLineProgressConstant=L,this.isStateDependent=x!=="constant"&&!Bx(w.expression),this.configDependencies=El(w.expression),this.isIndoorDependent=Qi(w.expression)}evaluateWithoutErrorHandling(x,w,A,L,F,U){return this._styleExpression.evaluateWithoutErrorHandling(x,w,A,L,F,U)}evaluate(x,w,A,L,F,U,K){return this._styleExpression.evaluate(x,w,A,L,F,U,void 0,void 0,K)}}class Ec{constructor(x,w,A,L,F,U){this.kind=x,this.zoomStops=A,this._styleExpression=w,this.isStateDependent=x!=="camera"&&!Bx(w.expression),this.isIndoorDependent=Qi(w.expression),this.isLightConstant=F,this.isLineProgressConstant=U,this.configDependencies=El(w.expression),this.interpolationType=L}evaluateWithoutErrorHandling(x,w,A,L,F,U){return this._styleExpression.evaluateWithoutErrorHandling(x,w,A,L,F,U)}evaluate(x,w,A,L,F,U){return this._styleExpression.evaluate(x,w,A,L,F,U)}interpolationFactor(x,w,A){return this.interpolationType?dp.interpolationFactor(this.interpolationType,x,w,A):0}}function Eh(k,x,w,A,L){if((k=Md(k,x,w,A,L)).result==="error")return k;const F=k.value.expression,U=$b(F);if(!U&&!gl(x))return Ll([new bo("","data expressions not supported")]);const K=Zu(F,["zoom","pitch","distance-from-center"]);if(!K&&!Bm(x))return Ll([new bo("","zoom expressions not supported")]);const X=Zu(F,["measure-light"]);if(!X&&!bu(x))return Ll([new bo("","measure-light expression not supported")]);const oe=Zu(F,["line-progress"]);if(!oe&&!function(je){return Ao(je.expression,"line-progress")}(x))return Ll([new bo("","line-progress expression not supported")]);const ge=x.expression&&x.expression.relaxZoomRestriction,we=Au(F);return we||K||ge?we instanceof bo?Ll([we]):we instanceof dp&&!_u(x)?Ll([new bo("",'"interpolate" expressions cannot be used with this property')]):mi(we?new Ec(U&&oe?"camera":"composite",k.value,we.labels,we instanceof dp?we.interpolation:void 0,X,oe):new Qh(U&&oe?"constant":"source",k.value,X,oe)):Ll([new bo("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression, or in the properties of atmosphere.')])}class Dp{constructor(x,w){this._parameters=x,this._specification=w,Object.assign(this,sx(this._parameters,this._specification))}static deserialize(x){return new Dp(x._parameters,x._specification)}static serialize(x){return{_parameters:x._parameters,_specification:x._specification}}}function Au(k){let x=null;if(k instanceof Te)x=Au(k.result);else if(k instanceof dw){for(const w of k.args)if(x=Au(w),x)break}else(k instanceof Yj||k instanceof dp)&&k.input instanceof qd&&k.input.name==="zoom"&&(x=k);return x instanceof bo||k.eachChild(w=>{const A=Au(w);A instanceof bo?x=A:x&&A&&x!==A&&(x=new bo("",'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'))}),x}var nx,rx,Rp=function(){if(rx)return nx;rx=1,nx=x;var k=3;function x(w,A,L){var F=this.cells=[];if(w instanceof ArrayBuffer){this.arrayBuffer=w;var U=new Int32Array(this.arrayBuffer);w=U[0],this.d=(A=U[1])+2*(L=U[2]);for(var K=0;K=je[We+0]&&F>=je[We+1])?(X[Re]=!0,K.push(we[Re])):X[Re]=!1}}},x.prototype._forEachCell=function(w,A,L,F,U,K,X,oe){for(var ge=this._convertToCellCoord(w),we=this._convertToCellCoord(A),je=this._convertToCellCoord(L),Le=this._convertToCellCoord(F),Re=ge;Re<=je;Re++)for(var We=we;We<=Le;We++){var et=this.d*We+Re;if((!oe||oe(this._convertFromCellCoord(Re),this._convertFromCellCoord(We),this._convertFromCellCoord(Re+1),this._convertFromCellCoord(We+1)))&&U.call(this,w,A,L,F,et,K,X,oe))return}},x.prototype._convertFromCellCoord=function(w){return(w-this.padding)/this.scale},x.prototype._convertToCellCoord=function(w){return Math.max(0,Math.min(this.d-1,Math.floor(w*this.scale)+this.padding))},x.prototype.toArrayBuffer=function(){if(this.arrayBuffer)return this.arrayBuffer;for(var w=this.cells,A=k+this.cells.length+1+1,L=0,F=0;F=0||(L[F]=kd(k[F],x)));k instanceof Error&&(L.message=k.message)}if(L.$name)throw new Error("$name property is reserved for worker serialization logic.");return A!=="Object"&&(L.$name=A),L}throw new Error("can't serialize object of type "+typeof k)}function Gc(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||zo(k)||k instanceof ImageBitmap||ArrayBuffer.isView(k)||k instanceof ImageData)return k;if(Array.isArray(k))return k.map(Gc);if(typeof k=="object"){const x=k.$name||"Object";if(x==="Map"){const L=k.entries||[],F=new Map;for(let U=0;Uk>=1536&&k<=1791,up=k=>k>=1872&&k<=1919,qy=k=>k>=2208&&k<=2303,Qu=k=>k>=11904&&k<=12031,pf=k=>k>=12032&&k<=12255,L1=k=>k>=12272&&k<=12287,Vb=k=>k>=12288&&k<=12351,I1=k=>k>=12352&&k<=12447,Fp=k=>k>=12448&&k<=12543,ax=k=>k>=12544&&k<=12591,s2=k=>k>=12704&&k<=12735,H0=k=>k>=12736&&k<=12783,$y=k=>k>=12784&&k<=12799,Bv=k=>k>=12800&&k<=13055,n2=k=>k>=13056&&k<=13311,r2=k=>k>=13312&&k<=19903,vg=k=>k>=19968&&k<=40959,Uv=k=>k>=40960&&k<=42127,bg=k=>k>=42128&&k<=42191,uw=k=>k>=44032&&k<=55215,Hb=k=>k>=63744&&k<=64255,Gb=k=>k>=64336&&k<=65023,a2=k=>k>=65040&&k<=65055,Wb=k=>k>=65072&&k<=65103,xh=k=>k>=65104&&k<=65135,Vy=k=>k>=65136&&k<=65279,Ux=k=>k>=65280&&k<=65519;function ix(k){for(const x of k)if(t5(x.charCodeAt(0)))return!0;return!1}function GC(k){for(const x of k)if(!Kb(x.charCodeAt(0)))return!1;return!0}function Kb(k){return!(sd(k)||up(k)||qy(k)||Gb(k)||Vy(k))}function WC(k){return!(k<11904||!(s2(k)||ax(k)||Wb(k)||Hb(k)||n2(k)||Qu(k)||H0(k)||Vb(k)||r2(k)||vg(k)||Bv(k)||Ux(k)||I1(k)||L1(k)||pf(k)||$y(k)||Fp(k)||a2(k)||bg(k)||Uv(k)))}function t5(k){return!(k!==746&&k!==747&&(k<4352||!(s2(k)||ax(k)||Wb(k)&&!(k>=65097&&k<=65103)||Hb(k)||n2(k)||Qu(k)||H0(k)||!(!Vb(k)||k>=12296&&k<=12305||k>=12308&&k<=12319||k===12336)||r2(k)||vg(k)||Bv(k)||(x=>x>=12592&&x<=12687)(k)||(x=>x>=43360&&x<=43391)(k)||(x=>x>=55216&&x<=55295)(k)||(x=>x>=4352&&x<=4607)(k)||uw(k)||I1(k)||L1(k)||(x=>x>=12688&&x<=12703)(k)||pf(k)||$y(k)||Fp(k)&&k!==12540||!(!Ux(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)||!(!xh(k)||k>=65112&&k<=65118||k>=65123&&k<=65126)||(x=>x>=5120&&x<=5759)(k)||(x=>x>=6320&&x<=6399)(k)||a2(k)||(x=>x>=19904&&x<=19967)(k)||Uv(k)||bg(k))))}function D1(k){return k===12312||k===12313||k===12316||k===12540||k===12448}function R1(k){return!(t5(k)||function(x){return!!((w=>w>=128&&w<=255)(x)&&(x===167||x===169||x===174||x===177||x===188||x===189||x===190||x===215||x===247)||(w=>w>=8192&&w<=8303)(x)&&(x===8214||x===8224||x===8225||x===8240||x===8241||x===8251||x===8252||x===8258||x===8263||x===8264||x===8265||x===8273)||(w=>w>=8448&&w<=8527)(x)||(w=>w>=8528&&w<=8591)(x)||(w=>w>=8960&&w<=9215)(x)&&(x>=8960&&x<=8967||x>=8972&&x<=8991||x>=8996&&x<=9e3||x===9003||x>=9085&&x<=9114||x>=9150&&x<=9165||x===9167||x>=9169&&x<=9179||x>=9186&&x<=9215)||(w=>w>=9216&&w<=9279)(x)&&x!==9251||(w=>w>=9280&&w<=9311)(x)||(w=>w>=9312&&w<=9471)(x)||(w=>w>=9632&&w<=9727)(x)||(w=>w>=9728&&w<=9983)(x)&&!(x>=9754&&x<=9759)||(w=>w>=11008&&w<=11263)(x)&&(x>=11026&&x<=11055||x>=11088&&x<=11097||x>=11192&&x<=11243)||Vb(x)||Fp(x)||(w=>w>=57344&&w<=63743)(x)||Wb(x)||xh(x)||Ux(x)||x===8734||x===8756||x===8757||x>=9984&&x<=10087||x>=10102&&x<=10131||x===65532||x===65533)}(k))}function KC(k){return sd(k)||up(k)||qy(k)||Gb(k)||Vy(k)}function F1(k){return k>=1424&&k<=2303||Gb(k)||Vy(k)}function G0(k,x){return!(!x&&F1(k)||k>=2304&&k<=3583||k>=3840&&k<=4255||(w=>w>=6016&&w<=6143)(k))}function ek(k){for(const x of k)if(F1(x.charCodeAt(0)))return!0;return!1}const Th={unavailable:"unavailable",deferred:"deferred",loading:"loading",parsing:"parsing",parsed:"parsed",loaded:"loaded",error:"error"};let hp=null,Eu=Th.unavailable,ox=null;const s5=function(k){k&&typeof k=="string"&&k.indexOf("NetworkError")>-1&&(Eu=Th.error),hp&&hp(k)};function tk(){n5.fire(new Nd("pluginStateChange",{pluginStatus:Eu,pluginURL:ox}))}const n5=new Om,Hy=function(){return Eu},r5=function(){if(Eu!==Th.deferred||!ox)throw new Error("rtl-text-plugin cannot be downloaded unless a pluginURL is specified");Eu=Th.loading,tk(),ox&&Gg({url:ox},k=>{k?s5(k):(Eu=Th.loaded,tk())})},Xg={applyArabicShaping:null,processBidirectionalText:null,processStyledBidirectionalText:null,isLoaded:()=>Eu===Th.loaded||Xg.applyArabicShaping!=null,isLoading:()=>Eu===Th.loading,setState(k){Eu=k.pluginStatus,ox=k.pluginURL},isParsing:()=>Eu===Th.parsing,isParsed:()=>Eu===Th.parsed,getPluginURL:()=>ox},qL=function(){Xg.isLoading()||Xg.isLoaded()||Hy()!=="deferred"||r5()};class $i{constructor(x,w){this.zoom=x,w?(this.now=w.now,this.fadeDuration=w.fadeDuration,this.transition=w.transition,this.pitch=w.pitch,this.brightness=w.brightness,this.worldview=w.worldview,this.activeFloors=w.activeFloors):(this.now=0,this.fadeDuration=0,this.transition={},this.pitch=0,this.brightness=0)}isSupportedScript(x){return function(w,A){for(const L of w)if(!G0(L.charCodeAt(0),A))return!1;return!0}(x,Xg.isLoaded())}}class a5{constructor(x,w,A,L,F){this.property=x,this.value=w,this.expression=function(U,K,X,oe,ge){if(Xu(U))return new Dp(U,K);if(Ip(U)||Array.isArray(U)&&U.length>0){const we=Eh(U,K,X,oe,ge);if(we.result==="error")throw new Error(we.value.map(je=>`${je.key}: ${je.message}`).join(", "));return we.value}{let we=U;return typeof U=="string"&&K.type==="color"&&(we=Xs.parse(U)),{kind:"constant",configDependencies:new Set,isIndoorDependent:!1,evaluate:()=>we}}}(w===void 0?x.specification.default:w,x.specification,A,L,F)}isIndoorDependent(){return this.expression.isIndoorDependent}isDataDriven(){return this.expression.kind==="source"||this.expression.kind==="composite"}possiblyEvaluate(x,w,A,L){return this.property.possiblyEvaluate(this,x,w,A,L)}}class YC{constructor(x,w,A,L){this.property=x,this.value=new a5(x,void 0,w,A,L)}transitioned(x,w){return new i5(this.property,this.value,w,Object.assign({},x.transition,this.transition),x.now)}untransitioned(){return new i5(this.property,this.value,null,{},0)}}class XE{constructor(x,w,A,L){this._properties=x,this._values=Object.create(x.defaultTransitionablePropertyValues),this._scope=w,this._options=A,this._iconImageUseTheme=L,this._isIndoorDependent=!1,this.configDependencies=new Set}getValue(x){return er(this._values[x].value.value)}setValue(x,w){this._values.hasOwnProperty(x)||(this._values[x]=new YC(this._values[x].property,this._scope,this._options,this._iconImageUseTheme)),this._values[x].value=new a5(this._values[x].property,w===null?void 0:er(w),this._scope,this._options,this._iconImageUseTheme),this._values[x].value.expression.configDependencies&&(this.configDependencies=new Set([...this.configDependencies,...this._values[x].value.expression.configDependencies]),this._isIndoorDependent=this._isIndoorDependent||this._values[x].value.isIndoorDependent())}setTransitionOrValue(x,w){w&&(this._options=w);const A=this._properties.properties;if(x)for(const L in x){const F=x[L];if(L.endsWith("-transition")){const U=L.slice(0,-11);A[U]&&this.setTransition(U,F)}else A.hasOwnProperty(L)&&this.setValue(L,F)}}getTransition(x){return er(this._values[x].transition)}setTransition(x,w){this._values.hasOwnProperty(x)||(this._values[x]=new YC(this._values[x].property)),this._values[x].transition=er(w)||void 0}serialize(){const x={};for(const w of Object.keys(this._values)){const A=this.getValue(w);A!==void 0&&(x[w]=A);const L=this.getTransition(w);L!==void 0&&(x[`${w}-transition`]=L)}return x}transitioned(x,w){const A=new QE(this._properties);for(const L of Object.keys(this._values))A._values[L]=this._values[L].transitioned(x,w._values[L]);return A}untransitioned(){const x=new QE(this._properties);for(const w of Object.keys(this._values))x._values[w]=this._values[w].untransitioned();return x}isIndoorDependent(){return this._isIndoorDependent}}class i5{constructor(x,w,A,L,F){const U=L.delay||0,K=L.duration||0;F=F||0,this.property=x,this.value=w,this.begin=F+U,this.end=this.begin+K,x.specification.transition&&(L.delay||L.duration)&&(this.prior=A)}possiblyEvaluate(x,w,A){const L=x.now||0,F=this.value.possiblyEvaluate(x,w,A),U=this.prior;if(U){if(L>this.end)return this.prior=null,F;if(this.value.isDataDriven())return this.prior=null,F;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 ZC(k){return k instanceof Number||k instanceof String||k instanceof Boolean?k.valueOf():k}function o5(k){if(Array.isArray(k))return k.map(o5);if(k instanceof Object&&!(k instanceof Number||k instanceof String||k instanceof Boolean)){const x={};for(const w in k)x[w]=o5(k[w]);return x}return ZC(k)}function XC(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 x of k.slice(1))if(!XC(x)&&typeof x!="boolean")return!1;return!0;default:return!0}}function eT(k,x="",w=null,A="fill"){if(k==null)return{filter:()=>!0,needGeometry:!1,needFeature:!1};XC(k)||(k=sT(k));const L=k;let F=!0;try{F=function(ge){if(!nk(ge))return ge;let we=o5(ge);return VL(we),we=$L(we),we}(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 U=null,K=null;if(A!=="background"&&A!=="sky"&&A!=="slot"){K=Us[`filter_${A}`];const ge=Md(F,K,x,w);if(ge.result==="error")throw new Error(ge.value.map(we=>`${we.key}: ${we.message}`).join(", "));U=(we,je,Le)=>ge.value.evaluate(we,je,{},Le)}let X=null,oe=null;if(F!==L){const ge=Md(L,K,x,w);if(ge.result==="error")throw new Error(ge.value.map(we=>`${we.key}: ${we.message}`).join(", "));X=(we,je,Le,Re,We)=>ge.value.evaluate(we,je,{},Le,void 0,void 0,Re,We),oe=!$b(ge.value.expression)}return{filter:U,dynamicFilter:X||void 0,needGeometry:Cz(F),needFeature:!!oe}}function $L(k){if(!Array.isArray(k))return k;const x=function(w){if(HL.has(w[0])){for(let A=1;A$L(w))}function VL(k){let x=!1;const w=[];if(k[0]==="case"){for(let A=1;A",">=","<","<=","to-boolean"]);function tT(k,x){return kx?1:0}function Cz(k){if(!Array.isArray(k))return!1;if(k[0]==="within"||k[0]==="distance")return!0;for(let x=1;x"||x==="<="||x===">="?re(k[1],k[2],x):x==="any"?(w=k.slice(1),["any"].concat(w.map(sT))):x==="all"?["all"].concat(k.slice(1).map(sT)):x==="none"?["all"].concat(k.slice(1).map(sT).map(st)):x==="in"?de(k[1],k.slice(2)):x==="!in"?st(de(k[1],k.slice(2))):x==="has"?De(k[1]):x!=="!has"||st(De(k[1]));var w}function re(k,x,w){switch(k){case"$type":return[`filter-type-${w}`,x];case"$id":return[`filter-id-${w}`,x];default:return[`filter-${w}`,k,x]}}function de(k,x){if(x.length===0)return!1;switch(k){case"$type":return["filter-type-in",["literal",x]];case"$id":return["filter-id-in",["literal",x]];default:return x.length>200&&!x.some(w=>typeof w!=typeof x[0])?["filter-in-large",k,["literal",x.sort(tT)]]:["filter-in-small",k,["literal",x]]}}function De(k){switch(k){case"$type":return!0;case"$id":return["filter-has-id"];default:return["filter-has",k]}}function st(k){return["!",k]}const dt="";function Lt(k,x){return x?`${k}${dt}${x}`:k}function Bs(k){const x=k.indexOf(dt);return x>=0?k.slice(x+1):""}let Zn;const Dr=()=>Zn||(Zn=new nd({"icon-size":new lr(Us.layout_symbol["icon-size"]),"icon-image":new lr(Us.layout_symbol["icon-image"]),"icon-rotate":new lr(Us.layout_symbol["icon-rotate"]),"icon-offset":new lr(Us.layout_symbol["icon-offset"]),"text-size":new lr(Us.layout_symbol["text-size"]),"text-rotate":new lr(Us.layout_symbol["text-rotate"]),"text-offset":new lr(Us.layout_symbol["text-offset"])}));let Va;const to=()=>Va||(Va=new nd({"icon-opacity":new lr(Us.paint_symbol["icon-opacity"]),"icon-occlusion-opacity":new lr(Us.paint_symbol["icon-occlusion-opacity"]),"icon-emissive-strength":new lr(Us.paint_symbol["icon-emissive-strength"]),"text-emissive-strength":new lr(Us.paint_symbol["text-emissive-strength"]),"icon-color":new lr(Us.paint_symbol["icon-color"]),"icon-halo-color":new lr(Us.paint_symbol["icon-halo-color"]),"icon-halo-width":new lr(Us.paint_symbol["icon-halo-width"]),"icon-halo-blur":new lr(Us.paint_symbol["icon-halo-blur"]),"icon-translate":new lr(Us.paint_symbol["icon-translate"]),"text-opacity":new lr(Us.paint_symbol["text-opacity"]),"text-occlusion-opacity":new lr(Us.paint_symbol["text-occlusion-opacity"]),"text-color":new lr(Us.paint_symbol["text-color"],{runtimeType:tc,getOverride:k=>k.textColor,hasOverride:k=>!!k.textColor}),"text-halo-color":new lr(Us.paint_symbol["text-halo-color"]),"text-halo-width":new lr(Us.paint_symbol["text-halo-width"]),"text-halo-blur":new lr(Us.paint_symbol["text-halo-blur"]),"text-translate":new lr(Us.paint_symbol["text-translate"]),"symbol-z-offset":new lr(Us.paint_symbol["symbol-z-offset"]),"icon-color-use-theme":new lr({type:"string",default:"default","property-type":"data-driven"}),"icon-halo-color-use-theme":new lr({type:"string",default:"default","property-type":"data-driven"}),"text-color-use-theme":new lr({type:"string",default:"default","property-type":"data-driven"}),"text-halo-color-use-theme":new lr({type:"string",default:"default","property-type":"data-driven"})}));class nc{constructor(x,w,A,L,F,U){this._conditionSpec=x,this._propertiesSpec=A;const K=Md(x,Us.appearance.condition);if(K.result==="success"&&(this.condition=K.value),this.name=w,A){this.layoutProperties=new Op(Dr()),this.unevaluatedLayout=new JE(Dr(),L,F,U),this.paintProperties=new Op(to()),this.unevaluatedPaint=new JE(to(),L,F,"");for(const X in A)X in this.unevaluatedLayout._values?this.unevaluatedLayout.setValue(X,A[X]):X in this.unevaluatedPaint._values&&this.unevaluatedPaint.setValue(X,A[X])}}isActive(x){return!(this.condition||!x.isHidden||this.name!=="hidden")||this.condition.evaluate(x.globals,x.feature,x.featureState,x.canonical)}getCondition(){return this.condition}getName(){return this.name}getLayoutProperty(x){return this.layoutProperties.get(x)}getPaintProperty(x){return this.paintProperties.get(x)}getUnevaluatedLayoutProperties(){return this.unevaluatedLayout}getUnevaluatedLayoutProperty(x){return this.unevaluatedLayout._values[x]}getUnevaluatedPaintProperty(x){return this.unevaluatedPaint._values[x]}recalculate(x,w,A){this.unevaluatedLayout&&(this.layoutProperties=this.unevaluatedLayout.possiblyEvaluate(x,void 0,w,A)),this.unevaluatedPaint&&(this.paintProperties=this.unevaluatedPaint.possiblyEvaluate(x,void 0,w,""))}serialize(){const x={};x.condition=this.condition.expression.serialize(),this.name&&(x.name=this.name);const w=this.unevaluatedLayout?this.unevaluatedLayout.serialize():{},A=this.unevaluatedPaint?this.unevaluatedPaint.serialize():{},L=Object.assign({},w,A);return Object.keys(L).length>0&&(x.properties=L),x}hasIconLayoutProperties(){const x=this.hasLayoutProperty("icon-image"),w=this.hasLayoutProperty("icon-size"),A=this.hasLayoutProperty("icon-offset"),L=this.hasLayoutProperty("icon-rotate");return x||w||A||L}hasTextLayoutProperties(){const x=this.hasLayoutProperty("text-size"),w=this.hasLayoutProperty("text-offset"),A=this.hasLayoutProperty("text-rotate");return x||w||A}hasIconPaintProperties(){return!!this.unevaluatedPaint&&Object.keys(this.unevaluatedPaint._values).filter(x=>!x.endsWith("-use-theme")).some(x=>(x.startsWith("icon-")||x==="symbol-z-offset")&&this.hasPaintProperty(x))}hasTextPaintProperties(){return!!this.unevaluatedPaint&&Object.keys(this.unevaluatedPaint._values).filter(x=>!x.endsWith("-use-theme")).some(x=>(x.startsWith("text-")||x==="symbol-z-offset")&&this.hasPaintProperty(x))}hasLayoutProperty(x){return this.unevaluatedLayout&&this.unevaluatedLayout._values[x].value!==void 0}hasPaintProperty(x){return this.unevaluatedPaint&&this.unevaluatedPaint._values[x].value!==void 0}}const Di="-transition",Mh=new Set(["fill","line","background","hillshade","raster"]);class rc extends Om{constructor(x,w,A,L,F,U){if(super(),this.id=x.id,this.fqid=Lt(this.id,A),this.type=x.type,this.scope=A,this.lut=L,this.options=F,this.iconImageUseTheme=U,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},x.type!=="custom"){if(this.metadata=x.metadata,this.minzoom=x.minzoom,this.maxzoom=x.maxzoom,x.type&&x.type!=="background"&&x.type!=="sky"&&x.type!=="slot"){this.source=x.source,this.sourceLayer=x["source-layer"],this.filter=x.filter;const K=Md(this.filter,Us[`filter_${x.type}`]);K.result!=="error"&&(this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...K.value.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||K.value.isIndoorDependent)}if(x.slot&&(this.slot=x.slot),x.appearances&&this.setAppearances(x.appearances),w.layout&&(this._unevaluatedLayout=new JE(w.layout,this.scope,F,this.iconImageUseTheme),this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...this._unevaluatedLayout.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||this._unevaluatedLayout.isIndoorDependent()),w.paint){this._transitionablePaint=new XE(w.paint,this.scope,F);for(const K in x.paint)this.setPaintProperty(K,x.paint[K]);for(const K in x.layout)this.setLayoutProperty(K,x.layout[K]);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 Op(w.paint)}}}onAdd(x){}onRemove(x){}isDraped(x){return!this.is3D(!0)&&Mh.has(this.type)}getLayoutProperty(x){return x==="visibility"?this.visibility:this._unevaluatedLayout.getValue(x)}setLayoutProperty(x,w){if(this.type==="custom"&&x==="visibility")return void(this.visibility=w);const A=this._unevaluatedLayout;A._properties.properties[x]&&(A.setValue(x,w),this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...A.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||A.isIndoorDependent(),x==="visibility"&&this.possiblyEvaluateVisibility())}setAppearances(x){this.appearances=[],x.forEach(w=>{this.appearances.push(new nc(w.condition,w.name,w.properties,this.scope,this.options,this.iconImageUseTheme))}),this.appearancesVersion++}possiblyEvaluateVisibility(){this._unevaluatedLayout._values.visibility&&(this.visibility=this._unevaluatedLayout._values.visibility.possiblyEvaluate({zoom:0}))}getPaintProperty(x){return x.endsWith(Di)?this._transitionablePaint.getTransition(x.slice(0,-11)):this._transitionablePaint.getValue(x)}isPaintProperty(x){return!!this._transitionablePaint._properties.properties[x]}setPaintProperty(x,w){const A=this._transitionablePaint,L=A._properties.properties;if(x.endsWith(Di)){const we=x.slice(0,-11);return L[we]&&A.setTransition(we,w||void 0),!1}if(!L[x])return!1;const F=A._values[x],U=F.value.isDataDriven(),K=F.value;A.setValue(x,w),this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...A.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||A.isIndoorDependent(),this._handleSpecialPaintPropertyUpdate(x);const X=A._values[x].value,oe=X.isDataDriven(),ge=x.endsWith("pattern")||x==="line-dasharray";return oe||U||ge||this._handleOverridablePaintPropertyUpdate(x,K,X)}_handleSpecialPaintPropertyUpdate(x){}getProgramIds(){return null}getDefaultProgramParams(x,w,A){return null}_handleOverridablePaintPropertyUpdate(x,w,A){return!1}isHidden(x){return!!(this.minzoom&&x=this.maxzoom)||this.visibility==="none"}updateTransitions(x){this._transitioningPaint=this._transitionablePaint.transitioned(x,this._transitioningPaint)}hasTransition(){return this._transitioningPaint.hasTransition()}recalculate(x,w){this._unevaluatedLayout&&(this.layout=this._unevaluatedLayout.possiblyEvaluate(x,void 0,w,this.iconImageUseTheme)),this.paint=this._transitioningPaint.possiblyEvaluate(x,void 0,w)}serialize(){const x={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&&(x.appearances=this.appearances.map(w=>w.serialize())),an(x,(w,A)=>!(w===void 0||A==="layout"&&!Object.keys(w).length||A==="paint"&&!Object.keys(w).length))}is3D(x){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 x in this.paint._values){const w=this.paint.get(x);if(w instanceof sk&&gl(w.property.specification)&&(w.value.kind==="source"||w.value.kind==="composite")&&w.value.isStateDependent)return!0}for(const x of this.appearances)if(!Bx(x.condition.expression))return!0;return!1}compileFilter(x){this._filterCompiled||(this._featureFilter=eT(this.filter,this.scope,x),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(x){this._stats&&(x.renderPass==="shadow"?this._stats.numRenderedVerticesInShadowPass=0:this._stats.numRenderedVerticesInTransparentPass=0)}getAppearances(){return this.appearances}queryRenderedFeatures(x,w,A){return{}}queryRadius(x){}queryIntersectsFeature(x,w,A,L,F,U,K,X,oe,ge){}}const qx={Int8:Int8Array,Uint8:Uint8Array,Int16:Int16Array,Uint16:Uint16Array,Int32:Int32Array,Uint32:Uint32Array,Float32:Float32Array};class Wy{constructor(x,w){this._structArray=x,this._pos1=w*this.size,this._pos2=this._pos1/2,this._pos4=this._pos1/4,this._pos8=this._pos1/8}}const Tr=new ArrayBuffer(0);class En{constructor(){this._reallocCount=0,this.capacity=0,this.length=0}static serialize(x,w){return x._trim(),w&&x.arrayBuffer&&w.add(x.arrayBuffer),{length:x.length,arrayBuffer:x.arrayBuffer}}static deserialize(x){const w=Object.create(this.prototype);return w.arrayBuffer=x.arrayBuffer,w.length=x.length,x.arrayBuffer?w.capacity=x.arrayBuffer.byteLength/w.bytesPerElement:(w.capacity=0,w.arrayBuffer=Tr),w._refreshViews(),w}_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(x){this.reserve(x),this.length=x}reserve(x){if(x>this.capacity){this._reallocCount++,this.capacity=Math.max(x,Math.floor(5*this.capacity),128),this.arrayBuffer=new ArrayBuffer(this.capacity*this.bytesPerElement);const w=this.uint8;this._refreshViews(),w&&this.uint8.set(w)}}reserveForAdditional(x){this.reserve(this.length+x)}_refreshViews(){throw new Error("StructArray#_refreshViews() must be implemented by each concrete StructArray layout")}emplace(...x){throw new Error("StructArray#emplace() must be implemented by each concrete StructArray layout")}emplaceBack(...x){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 Hn(k,x=1){let w=0,A=0;return{members:k.map(L=>{const F=qx[L.type].BYTES_PER_ELEMENT,U=w=Vi(w,Math.max(x,F)),K=L.components||1;return A=Math.max(A,F),w+=F*K,{name:L.name,type:L.type,components:K,offset:U}}),size:Vi(w,Math.max(A,x)),alignment:x}}function Vi(k,x){return Math.ceil(k/x)*x}class ao extends En{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(x,w){const A=this.length;return this.resize(A+1),this.emplace(A,x,w)}emplace(x,w,A){const L=2*x;return this.int16[L+0]=w,this.int16[L+1]=A,x}}ao.prototype.bytesPerElement=4,jr(ao,"StructArrayLayout2i4");class fl extends En{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(x,w,A){const L=this.length;return this.resize(L+1),this.emplace(L,x,w,A)}emplace(x,w,A,L){const F=3*x;return this.int16[F+0]=w,this.int16[F+1]=A,this.int16[F+2]=L,x}}fl.prototype.bytesPerElement=6,jr(fl,"StructArrayLayout3i6");class yo extends En{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(x,w,A,L){const F=this.length;return this.resize(F+1),this.emplace(F,x,w,A,L)}emplace(x,w,A,L,F){const U=4*x;return this.int16[U+0]=w,this.int16[U+1]=A,this.uint16[U+2]=L,this.uint16[U+3]=F,x}}yo.prototype.bytesPerElement=8,jr(yo,"StructArrayLayout2i2ui8");class Zl extends En{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(x){const w=this.length;return this.resize(w+1),this.emplace(w,x)}emplace(x,w){return this.float32[1*x+0]=w,x}}Zl.prototype.bytesPerElement=4,jr(Zl,"StructArrayLayout1f4");class zp extends En{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(x,w,A){const L=this.length;return this.resize(L+1),this.emplace(L,x,w,A)}emplace(x,w,A,L){const F=4*x,U=2*x;return this.int16[F+0]=w,this.int16[F+1]=A,this.float32[U+1]=L,x}}zp.prototype.bytesPerElement=8,jr(zp,"StructArrayLayout2i1f8");class Sd extends En{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(x,w,A){const L=this.length;return this.resize(L+1),this.emplace(L,x,w,A)}emplace(x,w,A,L){const F=4*x;return this.int16[F+0]=w,this.int16[F+1]=A,this.int16[F+2]=L,x}}Sd.prototype.bytesPerElement=8,jr(Sd,"StructArrayLayout3i8");class Yb extends En{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(x,w,A,L){const F=this.length;return this.resize(F+1),this.emplace(F,x,w,A,L)}emplace(x,w,A,L,F){const U=4*x;return this.int16[U+0]=w,this.int16[U+1]=A,this.int16[U+2]=L,this.int16[U+3]=F,x}}Yb.prototype.bytesPerElement=8,jr(Yb,"StructArrayLayout4i8");class GL extends En{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(x,w,A,L,F){const U=this.length;return this.resize(U+1),this.emplace(U,x,w,A,L,F)}emplace(x,w,A,L,F,U){const K=5*x;return this.int16[K+0]=w,this.int16[K+1]=A,this.int16[K+2]=L,this.int16[K+3]=F,this.int16[K+4]=U,x}}GL.prototype.bytesPerElement=10,jr(GL,"StructArrayLayout5i10");class WL extends En{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(x,w,A,L,F,U,K){const X=this.length;return this.resize(X+1),this.emplace(X,x,w,A,L,F,U,K)}emplace(x,w,A,L,F,U,K,X){const oe=6*x,ge=12*x,we=3*x;return this.int16[oe+0]=w,this.int16[oe+1]=A,this.uint8[ge+4]=L,this.uint8[ge+5]=F,this.uint8[ge+6]=U,this.uint8[ge+7]=K,this.float32[we+2]=X,x}}WL.prototype.bytesPerElement=12,jr(WL,"StructArrayLayout2i4ub1f12");class Zb extends En{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(x,w,A){const L=this.length;return this.resize(L+1),this.emplace(L,x,w,A)}emplace(x,w,A,L){const F=3*x;return this.float32[F+0]=w,this.float32[F+1]=A,this.float32[F+2]=L,x}}Zb.prototype.bytesPerElement=12,jr(Zb,"StructArrayLayout3f12");class i2 extends En{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(x,w,A,L,F){const U=this.length;return this.resize(U+1),this.emplace(U,x,w,A,L,F)}emplace(x,w,A,L,F,U){const K=6*x,X=3*x;return this.uint16[K+0]=w,this.uint16[K+1]=A,this.uint16[K+2]=L,this.uint16[K+3]=F,this.float32[X+2]=U,x}}i2.prototype.bytesPerElement=12,jr(i2,"StructArrayLayout4ui1f12");class nT extends En{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(x,w,A,L){const F=this.length;return this.resize(F+1),this.emplace(F,x,w,A,L)}emplace(x,w,A,L,F){const U=4*x;return this.uint16[U+0]=w,this.uint16[U+1]=A,this.uint16[U+2]=L,this.uint16[U+3]=F,x}}nT.prototype.bytesPerElement=8,jr(nT,"StructArrayLayout4ui8");class Az extends En{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(x,w,A,L,F,U){const K=this.length;return this.resize(K+1),this.emplace(K,x,w,A,L,F,U)}emplace(x,w,A,L,F,U,K){const X=6*x;return this.int16[X+0]=w,this.int16[X+1]=A,this.int16[X+2]=L,this.int16[X+3]=F,this.int16[X+4]=U,this.int16[X+5]=K,x}}Az.prototype.bytesPerElement=12,jr(Az,"StructArrayLayout6i12");class vK extends En{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(x,w,A,L,F,U,K,X,oe,ge,we,je){const Le=this.length;return this.resize(Le+1),this.emplace(Le,x,w,A,L,F,U,K,X,oe,ge,we,je)}emplace(x,w,A,L,F,U,K,X,oe,ge,we,je,Le){const Re=12*x;return this.int16[Re+0]=w,this.int16[Re+1]=A,this.int16[Re+2]=L,this.int16[Re+3]=F,this.uint16[Re+4]=U,this.uint16[Re+5]=K,this.uint16[Re+6]=X,this.uint16[Re+7]=oe,this.int16[Re+8]=ge,this.int16[Re+9]=we,this.int16[Re+10]=je,this.int16[Re+11]=Le,x}}vK.prototype.bytesPerElement=24,jr(vK,"StructArrayLayout4i4ui4i24");class bK extends En{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(x,w,A,L,F,U){const K=this.length;return this.resize(K+1),this.emplace(K,x,w,A,L,F,U)}emplace(x,w,A,L,F,U,K){const X=10*x,oe=5*x;return this.int16[X+0]=w,this.int16[X+1]=A,this.int16[X+2]=L,this.float32[oe+2]=F,this.float32[oe+3]=U,this.float32[oe+4]=K,x}}bK.prototype.bytesPerElement=20,jr(bK,"StructArrayLayout3i3f20");class rk extends En{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(x,w,A,L){const F=this.length;return this.resize(F+1),this.emplace(F,x,w,A,L)}emplace(x,w,A,L,F){const U=4*x;return this.float32[U+0]=w,this.float32[U+1]=A,this.float32[U+2]=L,this.float32[U+3]=F,x}}rk.prototype.bytesPerElement=16,jr(rk,"StructArrayLayout4f16");class KL extends En{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer)}emplaceBack(x){const w=this.length;return this.resize(w+1),this.emplace(w,x)}emplace(x,w){return this.uint32[1*x+0]=w,x}}KL.prototype.bytesPerElement=4,jr(KL,"StructArrayLayout1ul4");class Xb extends En{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(x,w){const A=this.length;return this.resize(A+1),this.emplace(A,x,w)}emplace(x,w,A){const L=2*x;return this.uint16[L+0]=w,this.uint16[L+1]=A,x}}Xb.prototype.bytesPerElement=4,jr(Xb,"StructArrayLayout2ui4");class Ez extends En{_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(x,w,A,L,F,U,K,X,oe,ge,we,je,Le){const Re=this.length;return this.resize(Re+1),this.emplace(Re,x,w,A,L,F,U,K,X,oe,ge,we,je,Le)}emplace(x,w,A,L,F,U,K,X,oe,ge,we,je,Le,Re){const We=20*x,et=10*x;return this.int16[We+0]=w,this.int16[We+1]=A,this.int16[We+2]=L,this.int16[We+3]=F,this.int16[We+4]=U,this.float32[et+3]=K,this.float32[et+4]=X,this.float32[et+5]=oe,this.float32[et+6]=ge,this.int16[We+14]=we,this.uint32[et+8]=je,this.uint16[We+18]=Le,this.uint16[We+19]=Re,x}}Ez.prototype.bytesPerElement=40,jr(Ez,"StructArrayLayout5i4f1i1ul2ui40");class YL extends En{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(x,w,A,L,F,U,K){const X=this.length;return this.resize(X+1),this.emplace(X,x,w,A,L,F,U,K)}emplace(x,w,A,L,F,U,K,X){const oe=8*x;return this.int16[oe+0]=w,this.int16[oe+1]=A,this.int16[oe+2]=L,this.int16[oe+4]=F,this.int16[oe+5]=U,this.int16[oe+6]=K,this.int16[oe+7]=X,x}}YL.prototype.bytesPerElement=16,jr(YL,"StructArrayLayout3i2i2i16");class _K extends En{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(x,w,A,L,F){const U=this.length;return this.resize(U+1),this.emplace(U,x,w,A,L,F)}emplace(x,w,A,L,F,U){const K=4*x,X=8*x;return this.float32[K+0]=w,this.float32[K+1]=A,this.float32[K+2]=L,this.int16[X+6]=F,this.int16[X+7]=U,x}}_K.prototype.bytesPerElement=16,jr(_K,"StructArrayLayout2f1f2i16");class ZL extends En{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(x,w,A,L,F,U){const K=this.length;return this.resize(K+1),this.emplace(K,x,w,A,L,F,U)}emplace(x,w,A,L,F,U,K){const X=20*x,oe=5*x;return this.uint8[X+0]=w,this.uint8[X+1]=A,this.float32[oe+1]=L,this.float32[oe+2]=F,this.float32[oe+3]=U,this.float32[oe+4]=K,x}}ZL.prototype.bytesPerElement=20,jr(ZL,"StructArrayLayout2ub4f20");class Ju extends En{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(x,w,A){const L=this.length;return this.resize(L+1),this.emplace(L,x,w,A)}emplace(x,w,A,L){const F=3*x;return this.uint16[F+0]=w,this.uint16[F+1]=A,this.uint16[F+2]=L,x}}Ju.prototype.bytesPerElement=6,jr(Ju,"StructArrayLayout3ui6");class Tz extends En{_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(x,w,A,L,F,U,K,X,oe,ge,we,je,Le,Re,We,et,it,yt,ht,Et,It){const Ot=this.length;return this.resize(Ot+1),this.emplace(Ot,x,w,A,L,F,U,K,X,oe,ge,we,je,Le,Re,We,et,it,yt,ht,Et,It)}emplace(x,w,A,L,F,U,K,X,oe,ge,we,je,Le,Re,We,et,it,yt,ht,Et,It,Ot){const ws=30*x,ds=15*x,_s=60*x;return this.int16[ws+0]=w,this.int16[ws+1]=A,this.int16[ws+2]=L,this.float32[ds+2]=F,this.float32[ds+3]=U,this.uint16[ws+8]=K,this.uint16[ws+9]=X,this.uint32[ds+5]=oe,this.uint32[ds+6]=ge,this.uint32[ds+7]=we,this.uint16[ws+16]=je,this.uint16[ws+17]=Le,this.uint16[ws+18]=Re,this.float32[ds+10]=We,this.float32[ds+11]=et,this.uint8[_s+48]=it,this.uint8[_s+49]=yt,this.uint8[_s+50]=ht,this.uint32[ds+13]=Et,this.int16[ws+28]=It,this.uint8[_s+58]=Ot,x}}Tz.prototype.bytesPerElement=60,jr(Tz,"StructArrayLayout3i2f2ui3ul3ui2f3ub1ul1i1ub60");class wK extends En{_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(x,w,A,L,F,U,K,X,oe,ge,we,je,Le,Re,We,et,it,yt,ht,Et,It,Ot,ws,ds,_s,gs,ys,vn,wn,Pn,On,Ln,Jn){const gn=this.length;return this.resize(gn+1),this.emplace(gn,x,w,A,L,F,U,K,X,oe,ge,we,je,Le,Re,We,et,it,yt,ht,Et,It,Ot,ws,ds,_s,gs,ys,vn,wn,Pn,On,Ln,Jn)}emplace(x,w,A,L,F,U,K,X,oe,ge,we,je,Le,Re,We,et,it,yt,ht,Et,It,Ot,ws,ds,_s,gs,ys,vn,wn,Pn,On,Ln,Jn,gn){const Rn=20*x,qn=40*x,tr=80*x;return this.float32[Rn+0]=w,this.float32[Rn+1]=A,this.int16[qn+4]=L,this.int16[qn+5]=F,this.int16[qn+6]=U,this.int16[qn+7]=K,this.int16[qn+8]=X,this.int16[qn+9]=oe,this.int16[qn+10]=ge,this.int16[qn+11]=we,this.int16[qn+12]=je,this.uint16[qn+13]=Le,this.uint16[qn+14]=Re,this.uint16[qn+15]=We,this.uint16[qn+16]=et,this.uint16[qn+17]=it,this.uint16[qn+18]=yt,this.uint16[qn+19]=ht,this.uint16[qn+20]=Et,this.uint16[qn+21]=It,this.uint16[qn+22]=Ot,this.uint16[qn+23]=ws,this.uint16[qn+24]=ds,this.uint16[qn+25]=_s,this.uint16[qn+26]=gs,this.uint16[qn+27]=ys,this.uint32[Rn+14]=vn,this.float32[Rn+15]=wn,this.float32[Rn+16]=Pn,this.float32[Rn+17]=On,this.float32[Rn+18]=Ln,this.uint8[tr+76]=Jn,this.uint16[qn+39]=gn,x}}wK.prototype.bytesPerElement=80,jr(wK,"StructArrayLayout2f9i15ui1ul4f1ub1ui80");class Mz extends En{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(x,w,A,L,F,U){const K=this.length;return this.resize(K+1),this.emplace(K,x,w,A,L,F,U)}emplace(x,w,A,L,F,U,K){const X=6*x;return this.float32[X+0]=w,this.float32[X+1]=A,this.float32[X+2]=L,this.float32[X+3]=F,this.float32[X+4]=U,this.float32[X+5]=K,x}}Mz.prototype.bytesPerElement=24,jr(Mz,"StructArrayLayout6f24");class QC extends En{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(x,w,A,L,F){const U=this.length;return this.resize(U+1),this.emplace(U,x,w,A,L,F)}emplace(x,w,A,L,F,U){const K=5*x;return this.float32[K+0]=w,this.float32[K+1]=A,this.float32[K+2]=L,this.float32[K+3]=F,this.float32[K+4]=U,x}}QC.prototype.bytesPerElement=20,jr(QC,"StructArrayLayout5f20");class XL extends En{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(x,w,A,L,F,U,K){const X=this.length;return this.resize(X+1),this.emplace(X,x,w,A,L,F,U,K)}emplace(x,w,A,L,F,U,K,X){const oe=7*x;return this.float32[oe+0]=w,this.float32[oe+1]=A,this.float32[oe+2]=L,this.float32[oe+3]=F,this.float32[oe+4]=U,this.float32[oe+5]=K,this.float32[oe+6]=X,x}}XL.prototype.bytesPerElement=28,jr(XL,"StructArrayLayout7f28");class jK extends En{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(x,w,A,L,F,U,K,X,oe,ge,we){const je=this.length;return this.resize(je+1),this.emplace(je,x,w,A,L,F,U,K,X,oe,ge,we)}emplace(x,w,A,L,F,U,K,X,oe,ge,we,je){const Le=11*x;return this.float32[Le+0]=w,this.float32[Le+1]=A,this.float32[Le+2]=L,this.float32[Le+3]=F,this.float32[Le+4]=U,this.float32[Le+5]=K,this.float32[Le+6]=X,this.float32[Le+7]=oe,this.float32[Le+8]=ge,this.float32[Le+9]=we,this.float32[Le+10]=je,x}}jK.prototype.bytesPerElement=44,jr(jK,"StructArrayLayout11f44");class NK extends En{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(x,w,A,L,F,U,K,X,oe){const ge=this.length;return this.resize(ge+1),this.emplace(ge,x,w,A,L,F,U,K,X,oe)}emplace(x,w,A,L,F,U,K,X,oe,ge){const we=9*x;return this.float32[we+0]=w,this.float32[we+1]=A,this.float32[we+2]=L,this.float32[we+3]=F,this.float32[we+4]=U,this.float32[we+5]=K,this.float32[we+6]=X,this.float32[we+7]=oe,this.float32[we+8]=ge,x}}NK.prototype.bytesPerElement=36,jr(NK,"StructArrayLayout9f36");class JC extends En{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(x,w){const A=this.length;return this.resize(A+1),this.emplace(A,x,w)}emplace(x,w,A){const L=2*x;return this.float32[L+0]=w,this.float32[L+1]=A,x}}JC.prototype.bytesPerElement=8,jr(JC,"StructArrayLayout2f8");class kK extends En{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(x,w,A,L){const F=this.length;return this.resize(F+1),this.emplace(F,x,w,A,L)}emplace(x,w,A,L,F){const U=6*x;return this.uint32[3*x+0]=w,this.uint16[U+2]=A,this.uint16[U+3]=L,this.uint16[U+4]=F,x}}kK.prototype.bytesPerElement=12,jr(kK,"StructArrayLayout1ul3ui12");class e3 extends En{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(x){const w=this.length;return this.resize(w+1),this.emplace(w,x)}emplace(x,w){return this.uint16[1*x+0]=w,x}}e3.prototype.bytesPerElement=2,jr(e3,"StructArrayLayout1ui2");class SK extends En{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(x,w,A,L,F,U,K,X,oe,ge,we,je,Le,Re,We,et){const it=this.length;return this.resize(it+1),this.emplace(it,x,w,A,L,F,U,K,X,oe,ge,we,je,Le,Re,We,et)}emplace(x,w,A,L,F,U,K,X,oe,ge,we,je,Le,Re,We,et,it){const yt=16*x;return this.float32[yt+0]=w,this.float32[yt+1]=A,this.float32[yt+2]=L,this.float32[yt+3]=F,this.float32[yt+4]=U,this.float32[yt+5]=K,this.float32[yt+6]=X,this.float32[yt+7]=oe,this.float32[yt+8]=ge,this.float32[yt+9]=we,this.float32[yt+10]=je,this.float32[yt+11]=Le,this.float32[yt+12]=Re,this.float32[yt+13]=We,this.float32[yt+14]=et,this.float32[yt+15]=it,x}}SK.prototype.bytesPerElement=64,jr(SK,"StructArrayLayout16f64");class Pz extends En{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(x,w,A,L,F,U,K){const X=this.length;return this.resize(X+1),this.emplace(X,x,w,A,L,F,U,K)}emplace(x,w,A,L,F,U,K,X){const oe=10*x,ge=5*x;return this.uint16[oe+0]=w,this.uint16[oe+1]=A,this.uint16[oe+2]=L,this.uint16[oe+3]=F,this.float32[ge+2]=U,this.float32[ge+3]=K,this.float32[ge+4]=X,x}}Pz.prototype.bytesPerElement=20,jr(Pz,"StructArrayLayout4ui3f20");class Lz extends En{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(x){const w=this.length;return this.resize(w+1),this.emplace(w,x)}emplace(x,w){return this.int16[1*x+0]=w,x}}Lz.prototype.bytesPerElement=2,jr(Lz,"StructArrayLayout1i2");class Iz extends En{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer)}emplaceBack(x){const w=this.length;return this.resize(w+1),this.emplace(w,x)}emplace(x,w){return this.uint8[1*x+0]=w,x}}Iz.prototype.bytesPerElement=1,jr(Iz,"StructArrayLayout1ub1");class pie extends Wy{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]}}pie.prototype.size=40;class CK extends Ez{get(x){return new pie(this,x)}}jr(CK,"CollisionBoxArray");class fie extends Wy{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(x){this._structArray.uint8[this._pos1+49]=x}get hidden(){return this._structArray.uint8[this._pos1+50]}set hidden(x){this._structArray.uint8[this._pos1+50]=x}get crossTileID(){return this._structArray.uint32[this._pos4+13]}set crossTileID(x){this._structArray.uint32[this._pos4+13]=x}get associatedIconIndex(){return this._structArray.int16[this._pos2+28]}get flipState(){return this._structArray.uint8[this._pos1+58]}set flipState(x){this._structArray.uint8[this._pos1+58]=x}}fie.prototype.size=60;class xie extends Tz{get(x){return new fie(this,x)}}jr(xie,"PlacedSymbolArray");class QL extends Wy{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(x){this._structArray.uint32[this._pos4+14]=x}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(x){this._structArray.float32[this._pos4+18]=x}get hasIconTextFit(){return this._structArray.uint8[this._pos1+76]}get elevationFeatureIndex(){return this._structArray.uint16[this._pos2+39]}}QL.prototype.size=80;class gie extends wK{get(x){return new QL(this,x)}}jr(gie,"SymbolInstanceArray");class yie extends Zl{getoffsetX(x){return this.float32[1*x+0]}}jr(yie,"GlyphOffsetArray");class JL extends ao{getx(x){return this.int16[2*x+0]}gety(x){return this.int16[2*x+1]}}jr(JL,"SymbolLineVertexArray");class vie extends Wy{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]}}vie.prototype.size=12;class AK extends kK{get(x){return new vie(this,x)}}jr(AK,"FeatureIndexArray");class bie extends Xb{geta_centroid_pos0(x){return this.uint16[2*x+0]}geta_centroid_pos1(x){return this.uint16[2*x+1]}}jr(bie,"FillExtrusionCentroidArray");class EK extends Wy{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]}}EK.prototype.size=6;class TK extends fl{get(x){return new EK(this,x)}}jr(TK,"FillExtrusionWallArray");const _ie=Hn([{name:"a_pos",components:2,type:"Int16"}],4),jDe=Hn([{name:"a_circle_z_offset",components:1,type:"Float32"}],4),NDe=Hn([{name:"a_pos_3",components:3,type:"Int16"},{name:"a_pos_normal_3",components:3,type:"Int16"}]);class Rc{constructor(x=[]){this.segments=x}_prepareSegment(x,w,A,L,F){let U=this.segments[this.segments.length-1];return x>Rc.MAX_VERTEX_ARRAY_LENGTH&&Br(`Max vertices per segment is ${Rc.MAX_VERTEX_ARRAY_LENGTH}: bucket requested ${x}`),(!U||U.vertexLength+x>Rc.MAX_VERTEX_ARRAY_LENGTH||U.sortKey!==L||F!==void 0&&U&&U.batchIndex!==void 0&&U.batchIndex!==F)&&(U={vertexOffset:w,primitiveOffset:A,vertexLength:0,primitiveLength:0},L!==void 0&&(U.sortKey=L),F!==void 0&&(U.batchIndex=F),this.segments.push(U)),U}prepareSegment(x,w,A,L,F){return this._prepareSegment(x,w.length,A.length,L,F)}get(){return this.segments}destroy(){for(const x of this.segments)for(const w in x.vaos)x.vaos[w].destroy()}static simpleSegment(x,w,A,L){return new Rc([{vertexOffset:x,primitiveOffset:w,vertexLength:A,primitiveLength:L,vaos:{},sortKey:0}])}}function Dz(k,x){return 256*(k=pt(Math.floor(k),0,255))+pt(Math.floor(x),0,255)}Rc.MAX_VERTEX_ARRAY_LENGTH=Math.pow(2,16)-1,jr(Rc,"SegmentVector");const kDe=Hn([{name:"a_pattern",components:4,type:"Uint16"},{name:"a_pixel_ratio",components:1,type:"Float32"}]),SDe=Hn([{name:"a_pattern_b",components:4,type:"Uint16"}]),CDe=Hn([{name:"a_dash",components:4,type:"Uint16"}]);class eI{constructor(){this.ids=[],this.uniqueIds=[],this.positions=[],this.indexed=!1}add(x,w,A,L){this.ids.push(MK(x)),this.positions.push(w,A,L)}eachPosition(x,w){const A=MK(x);let L=0,F=this.ids.length-1;for(;L>1;this.ids[U]>=A?F=U:L=U+1}for(;this.ids[L]===A;)w(this.positions[3*L],this.positions[3*L+1],this.positions[3*L+2]),L++}static serialize(x,w){const A=new Float64Array(x.ids),L=new Uint32Array(x.positions);return tI(A,L,0,A.length-1),w&&(w.add(A.buffer),w.add(L.buffer)),{ids:A,positions:L}}static deserialize(x){const w=new eI;let A;w.ids=x.ids,w.positions=x.positions;for(const L of w.ids)L!==A&&w.uniqueIds.push(L),A=L;return w.indexed=!0,w}}function MK(k){const x=+k;return Number.isSafeInteger(x)?x:dc(String(k))}function tI(k,x,w,A){for(;w>1];let F=w-1,U=A+1;for(;;){do F++;while(k[F]L);if(F>=U)break;O1(k,F,U),O1(x,3*F,3*U),O1(x,3*F+1,3*U+1),O1(x,3*F+2,3*U+2)}U-w`u_${F}`),this.type=A,this.context=L}setUniform(x,w,A,L,F){const U=L.constantOr(this.value);w.set(x,F,U instanceof Xs?U.toPremultipliedRenderColor(this.lutExpression&&this.lutExpression.kind==="constant"&&this.lutExpression.value==="none"?null:this.context.lut):U)}getBinding(x,w){return this.type==="color"?new EDe(x):new Um(x)}}class _e{constructor(x,w){this.uniformNames=w.map(A=>`u_${A}`),this.pattern=null,this.patternTransition=null,this.pixelRatio=1}setConstantPatternPositions(x,w){this.pixelRatio=x.pixelRatio||1,this.pattern=x.tl.concat(x.br),this.patternTransition=w?w.tl.concat(w.br):this.pattern}setUniform(x,w,A,L,F){let U=null;F!=="u_pattern"&&F!=="u_dash"||(U=this.pattern),F==="u_pattern_b"&&(U=this.patternTransition),F==="u_pixel_ratio"&&(U=this.pixelRatio),U&&w.set(x,F,U)}getBinding(x,w){return w==="u_pattern"||w==="u_pattern_b"||w==="u_dash"?new ADe(x):new Um(x)}}class Ee{constructor(x,w,A,L){this.expression=x,this.type=A,this.maxValue=0,this.paintVertexAttributes=w.map(F=>({name:`a_${F}`,type:"Float32",components:A==="color"?2:1,offset:0})),this.paintVertexArray=new L}populatePaintArray(x,w,A,L,F,U,K,X){const oe=this.paintVertexArray.length,ge=this.expression.kind==="composite"||this.expression.kind==="source"?this.expression.evaluate(new $i(0,{brightness:U,worldview:X}),w,{},F,L,K):this.expression.kind==="constant"&&this.expression.value,we=ee(this.lutExpression,w,{},L,F,U,K,X);this.paintVertexArray.resize(x),this._setPaintValue(oe,x,ge,we?null:this.context.lut)}updatePaintArray(x,w,A,L,F,U,K,X){const oe=this.expression.kind==="composite"||this.expression.kind==="source"?this.expression.evaluate({zoom:0,brightness:K,worldview:X},A,L,void 0,F):this.expression.kind==="constant"&&this.expression.value,ge=ee(this.lutExpression,A,L,F,void 0,K,void 0,X);this._setPaintValue(x,w,oe,ge?null:this.context.lut)}_setPaintValue(x,w,A,L){if(this.type==="color"){const F=Q(A.toPremultipliedRenderColor(L));for(let U=x;U`u_${K}_t`),this.type=A,this.useIntegerZoom=L,this.context=F,this.maxValue=0,this.paintVertexAttributes=w.map(K=>({name:`a_${K}`,type:"Float32",components:A==="color"?4:2,offset:0})),this.paintVertexArray=new U}populatePaintArray(x,w,A,L,F,U,K,X){const oe=this.expression.evaluate(new $i(this.context.zoom,{brightness:U,worldview:X}),w,{},F,L,K),ge=this.expression.evaluate(new $i(this.context.zoom+1,{brightness:U,worldview:X}),w,{},F,L,K),we=ee(this.lutExpression,w,{},L,F,U,K,X),je=this.paintVertexArray.length;this.paintVertexArray.resize(x),this._setPaintValue(je,x,oe,ge,we?null:this.context.lut)}updatePaintArray(x,w,A,L,F,U,K,X){const oe=this.expression.evaluate({zoom:this.context.zoom,brightness:K,worldview:X},A,L,void 0,F),ge=this.expression.evaluate({zoom:this.context.zoom+1,brightness:K,worldview:X},A,L,void 0,F),we=ee(this.lutExpression,A,L,F,void 0,K,void 0,X);this._setPaintValue(x,w,oe,ge,we?null:this.context.lut)}_setPaintValue(x,w,A,L,F){if(this.type==="color"){const U=Q(A.toPremultipliedRenderColor(F)),K=Q(L.toPremultipliedRenderColor(F));for(let X=x;X!0){this.binders={},this._buffers=[],this.context=w;const L=[],F=x;for(const U in x.paint._values){const K=F.paint.get(U);if(U.endsWith("-use-theme")||!A(U)||!(K instanceof sk&&gl(K.property.specification)))continue;const X=lt(U,x.type),oe=K.value,ge=K.property.specification.type,we=!!K.property.useIntegerZoom,je=U==="line-dasharray"||U.endsWith("pattern"),Le=F.paint.get(`${U}-use-theme`),Re=U==="line-dasharray"&&F.layout.get("line-cap").value.kind!=="constant"||Le&&Le.value.kind!=="constant";if(oe.kind!=="constant"||Re)if(oe.kind==="source"||Re||je){const We=zt(U,ge,"source");this.binders[U]=je?new Je(oe,X,ge,We,x.id):new Ee(oe,X,ge,We),L.push(`/a_${U}`)}else{const We=zt(U,ge,"composite");this.binders[U]=new Ie(oe,X,ge,we,w,We),L.push(`/z_${U}`)}else this.binders[U]=je?new _e(oe.value,X):new ue(oe.value,X,ge,w),L.push(`/u_${U}`);Le&&(this.binders[U].lutExpression=Le.value)}this.cacheKey=L.sort().join("")}getMaxValue(x){const w=this.binders[x];return w instanceof Ee||w instanceof Ie?w.maxValue:0}populatePaintArrays(x,w,A,L,F,U,K,X){for(const oe in this.binders){const ge=this.binders[oe];ge.context=this.context,(ge instanceof Ee||ge instanceof Ie||ge instanceof Je)&&ge.populatePaintArray(x,w,A,L,F,U,K,X)}}setConstantPatternPositions(x,w){for(const A in this.binders){const L=this.binders[A];L instanceof _e&&L.setConstantPatternPositions(x,w)}}getPatternTransitionVertexBuffer(x){const w=this.binders[x];return w instanceof Je?w.paintTransitionVertexBuffer:null}updatePaintArrays(x,w,A,L,F,U,K,X,oe,ge){let we=!1;const je=Object.keys(x),Le=je.length!==0&&!X,Re=Le?je:w.uniqueIds;this.context.lut=F.lut;for(const We in this.binders){const et=this.binders[We];if(et.context=this.context,(et instanceof Ee||et instanceof Ie||et instanceof Je)&&et.expression&&et.expression.kind&&et.expression.kind!=="constant"&&(et.expression.isStateDependent===!0||et.expression.isLightConstant===!1)){const it=F.paint.get(We);et.expression=it.value;for(const yt of Re){const ht=x[yt.toString()];w.eachPosition(yt,(Et,It,Ot)=>{const ws=L.feature(Et);et.updatePaintArray(It,Ot,ws,ht,U,K,oe,ge)})}if(!Le)for(const yt of A.uniqueIds){const ht=x[yt.toString()];A.eachPosition(yt,(Et,It,Ot)=>{const ws=L.feature(Et);et.updatePaintArray(It,Ot,ws,ht,U,K,oe,ge)})}we=!0}}return we}defines(){const x=[];for(const w in this.binders){const A=this.binders[w];(A instanceof ue||A instanceof _e)&&x.push(...A.uniformNames.map(L=>`#define HAS_UNIFORM_${L}`))}return x}getPaintVertexBuffers(){return this._buffers}getUniforms(x){const w=[];for(const A in this.binders){const L=this.binders[A];if(L instanceof ue||L instanceof _e||L instanceof Ie)for(const F of L.uniformNames)w.push({name:F,property:A,binding:L.getBinding(x,F)})}return w}setUniforms(x,w,A,L,F){for(const{name:U,property:K,binding:X}of A)this.binders[K].setUniform(x,X,F,L.get(K),U)}updatePaintBuffers(){this._buffers=[];for(const x in this.binders){const w=this.binders[x];(w instanceof Ee||w instanceof Ie||w instanceof Je)&&w.paintVertexBuffer&&this._buffers.push(w.paintVertexBuffer),w instanceof Je&&w.paintTransitionVertexBuffer&&this._buffers.push(w.paintTransitionVertexBuffer)}}upload(x){for(const w in this.binders){const A=this.binders[w];(A instanceof Ee||A instanceof Ie||A instanceof Je)&&A.upload(x)}this.updatePaintBuffers()}destroy(){for(const x in this.binders){const w=this.binders[x];(w instanceof Ee||w instanceof Ie||w instanceof Je)&&w.destroy()}}}class tt{constructor(x,w,A=()=>!0){this.programConfigurations={};for(const L of x)this.programConfigurations[L.id]=new Ke(L,w,A);this.needsUpload=!1,this._featureMap=new eI,this._featureMapWithoutIds=new eI,this._bufferOffset=0,this._idlessCounter=0}populatePaintArrays(x,w,A,L,F,U,K,X,oe){for(const ge in this.programConfigurations)this.programConfigurations[ge].populatePaintArrays(x,w,L,F,U,K,X,oe);w.id!==void 0?this._featureMap.add(w.id,A,this._bufferOffset,x):(this._featureMapWithoutIds.add(this._idlessCounter,A,this._bufferOffset,x),this._idlessCounter+=1),this._bufferOffset=x,this.needsUpload=!0}updatePaintArrays(x,w,A,L,F,U,K,X){for(const oe of A)this.needsUpload=this.programConfigurations[oe.id].updatePaintArrays(x,this._featureMap,this._featureMapWithoutIds,w,oe,L,F,U,K||0,X)||this.needsUpload}get(x){return this.programConfigurations[x]}upload(x){if(this.needsUpload){for(const w in this.programConfigurations)this.programConfigurations[w].upload(x);this.needsUpload=!1}}destroy(){for(const x in this.programConfigurations)this.programConfigurations[x].destroy()}}const ut={"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 lt(k,x){return ut[k]||[k.replace(`${x}-`,"").replace(/-/g,"_")]}const kt={"line-pattern":{source:i2,composite:i2},"fill-pattern":{source:i2,composite:i2},"fill-extrusion-pattern":{source:i2,composite:i2},"line-dasharray":{source:nT,composite:nT}},Nt={color:{source:JC,composite:rk},number:{source:Zl,composite:JC}};function zt(k,x,w){const A=kt[k];return A&&A[w]||Nt[x][w]}jr(ue,"ConstantBinder"),jr(_e,"PatternConstantBinder"),jr(Ee,"SourceExpressionBinder"),jr(Je,"PatternCompositeBinder"),jr(Ie,"CompositeExpressionBinder"),jr(Ke,"ProgramConfiguration",{omit:["_buffers"]}),jr(tt,"ProgramConfigurationSet");const Yt=ur/Math.PI/2,Tt=64,Ss=[Tt,32,16],cs=-Yt,Ns=Yt;function Zt(k,x,w,A=Yt){return w=Ws(w),[k*Math.sin(w)*A,-x*A,k*Math.cos(w)*A]}function ns(k,x,w){return Zt(Math.cos(Ws(k)),Math.sin(Ws(k)),x,w)}const bs=63710088e-1,Ks=2*Math.PI*bs;class Es{constructor(x,w){if(isNaN(x)||isNaN(w))throw new Error(`Invalid LngLat object: (${x}, ${w})`);if(this.lng=+x,this.lat=+w,this.lat>90||this.lat<-90)throw new Error("Invalid LngLat latitude value: must be between -90 and 90")}wrap(){return new Es(Mt(this.lng,-180,180),this.lat)}toArray(){return[this.lng,this.lat]}toString(){return`LngLat(${this.lng}, ${this.lat})`}distanceTo(x){const w=Math.PI/180,A=this.lat*w,L=x.lat*w,F=Math.sin(A)*Math.sin(L)+Math.cos(A)*Math.cos(L)*Math.cos((x.lng-this.lng)*w);return bs*Math.acos(Math.min(F,1))}toBounds(x=0){const w=360*x/40075017,A=w/Math.cos(Math.PI/180*this.lat);return new bn({lng:this.lng-A,lat:this.lat-w},{lng:this.lng+A,lat:this.lat+w})}toEcef(x){return ns(this.lat,this.lng,Yt+x*Yt/bs)}static convert(x){if(x instanceof Es)return x;if(Array.isArray(x)&&(x.length===2||x.length===3))return new Es(Number(x[0]),Number(x[1]));if(!Array.isArray(x)&&typeof x=="object"&&x!==null)return new Es(Number("lng"in x?x.lng:x.lon),Number(x.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 bn{constructor(x,w){x&&(w?this.setSouthWest(x).setNorthEast(w):Array.isArray(x)&&x.length===4?this.setSouthWest([x[0],x[1]]).setNorthEast([x[2],x[3]]):this.setSouthWest(x[0]).setNorthEast(x[1]))}setNorthEast(x){return this._ne=x instanceof Es?new Es(x.lng,x.lat):Es.convert(x),this}setSouthWest(x){return this._sw=x instanceof Es?new Es(x.lng,x.lat):Es.convert(x),this}extend(x){const w=this._sw,A=this._ne;let L,F;if(x instanceof Es)L=x,F=x;else{if(!(x instanceof bn))return Array.isArray(x)?x.length===4||x.every(Array.isArray)?this.extend(bn.convert(x)):this.extend(Es.convert(x)):typeof x=="object"&&x!==null&&x.hasOwnProperty("lat")&&(x.hasOwnProperty("lon")||x.hasOwnProperty("lng"))?this.extend(Es.convert(x)):this;if(L=x._sw,F=x._ne,!L||!F)return this}return w||A?(w.lng=Math.min(L.lng,w.lng),w.lat=Math.min(L.lat,w.lat),A.lng=Math.max(F.lng,A.lng),A.lat=Math.max(F.lat,A.lat)):(this._sw=new Es(L.lng,L.lat),this._ne=new Es(F.lng,F.lat)),this}getCenter(){return new Es((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 Es(this.getWest(),this.getNorth())}getSouthEast(){return new Es(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(x){const{lng:w,lat:A}=Es.convert(x);let L=this._sw.lng<=w&&w<=this._ne.lng;return this._sw.lng>this._ne.lng&&(L=this._sw.lng>=w&&w>=this._ne.lng),this._sw.lat<=A&&A<=this._ne.lat&&L}static convert(x){if(x)return x instanceof bn?x:new bn(x)}}function mn(k){return Ks*Math.cos(k*Math.PI/180)}function zn(k){return(180+k)/360}function Kn(k){return(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+k*Math.PI/360)))/360}function sn(k,x){return k/mn(x)}function Fs(k){return 360*k-180}function yn(k){return 360/Math.PI*Math.atan(Math.exp((180-360*k)*Math.PI/180))-90}function _n(k,x){return k*mn(yn(x))}const Tn=85.051129;function Nr(k){return Math.cos(Ws(pt(k,-85.051129,Tn)))}function hr(k,x){const w=pt(x,0,25.5),A=Math.pow(2,w);return Nr(k)*Ks/(512*A)}function mr(k){return 1/Math.cos(k*Math.PI/180)}function Gn(k,x=0){const w=Math.exp(Math.PI*(1-(k.y+x/ur)/(1<=X?(Aa(k,x,w,oe,ge,F,we,K,X),Aa(k,oe,ge,A,L,we,U,K,X)):k.push(U)}function ta(k,x,w){let A=k[0],L=A.x,F=A.y;x(A);const U=[A];for(let K=1;Kk.x+1||Ak.y+1)&&Br("Geometry exceeds allowed extent, reduce your vector tile buffer size"),k}function Qa(k,x,w){const A=k.loadGeometry(),L=k.extent,F=ur/L;if(x&&w&&w.projection.isReprojectedInTileSpace){const U=1<{const Le=Fs((x.x+je.x/L)/U),Re=yn((x.y+je.y/L)/U),We=ge.project(Le,Re);je.x=(We.x*K-X)*L,je.y=(We.y*K-oe)*L};for(let je=0;je=L||Re.y<0||Re.y>=L||(we(Re),Le.push(Re));A[je]=Le}}for(const U of A)for(const K of U)io(K,F);return A}function oo(k,x){return{type:k.type,id:k.id,properties:k.properties,geometry:x?Qa(k):[]}}class Ni{constructor(x,w,A,L,F){this.properties={},this.extent=A,this.type=0,this.id=void 0,this._pbf=x,this._geometry=-1,this._keys=L,this._values=F,x.readFields(al,this,w)}loadGeometry(){const x=this._pbf;x.pos=this._geometry;const w=x.readVarint()+x.pos,A=[];let L,F=1,U=0,K=0,X=0;for(;x.pos>3}if(U--,F===1||F===2)K+=x.readSVarint(),X+=x.readSVarint(),F===1&&(L&&A.push(L),L=[]),L&&L.push(new Js(K,X));else{if(F!==7)throw new Error(`unknown command ${F}`);L&&L.push(L[0].clone())}}return L&&A.push(L),A}bbox(){const x=this._pbf;x.pos=this._geometry;const w=x.readVarint()+x.pos;let A=1,L=0,F=0,U=0,K=1/0,X=-1/0,oe=1/0,ge=-1/0;for(;x.pos>3}if(L--,A===1||A===2)F+=x.readSVarint(),U+=x.readSVarint(),FX&&(X=F),Uge&&(ge=U);else if(A!==7)throw new Error(`unknown command ${A}`)}return[K,oe,X,ge]}toGeoJSON(x,w,A){const L=this.extent*Math.pow(2,A),F=this.extent*x,U=this.extent*w,K=this.loadGeometry();function X(je){return[360*(je.x+F)/L-180,360/Math.PI*Math.atan(Math.exp((1-2*(je.y+U)/L)*Math.PI))-90]}function oe(je){return je.map(X)}let ge;if(this.type===1){const je=[];for(const Re of K)je.push(Re[0]);const Le=oe(je);ge=je.length===1?{type:"Point",coordinates:Le[0]}:{type:"MultiPoint",coordinates:Le}}else if(this.type===2){const je=K.map(oe);ge=je.length===1?{type:"LineString",coordinates:je[0]}:{type:"MultiLineString",coordinates:je}}else{if(this.type!==3)throw new Error("unknown feature type");{const je=function(Re){const We=Re.length;if(We<=1)return[Re];const et=[];let it,yt;for(let ht=0;ht=this._features.length)throw new Error("feature index out of bounds");this._pbf.pos=this._features[x];const w=this._pbf.readVarint()+this._pbf.pos;return new Ni(this._pbf,w,this.extent,this._keys,this._values)}}function Fc(k,x,w){k===15?x.version=w.readVarint():k===1?x.name=w.readString():k===5?x.extent=w.readVarint():k===2?x._features.push(w.pos):k===3?x._keys.push(w.readString()):k===4&&x._values.push(function(A){let L=null;const F=A.readVarint()+A.pos;for(;A.pos>3;L=U===1?A.readString():U===2?A.readFloat():U===3?A.readDouble():U===4?A.readVarint64():U===5?A.readVarint():U===6?A.readSVarint():U===7?A.readBoolean():null}if(L==null)throw new Error("unknown feature value");return L}(w))}class yl{constructor(x,w){this.layers=x.readFields(Yi,{},w)}}function Yi(k,x,w){if(k===3){const A=new Hd(w,w.readVarint()+w.pos);A.length&&(x[A.name]=A)}}const Zi="3d_elevation_id",Oc="level";class cu{constructor(){this._valid=!1}reset(x){return this.feature=x,this._valid=!0,this._geometry=x.loadGeometry(),this._geometry.length!==0&&this._geometry[0].length!==0||(this._valid=!1),this}geometry(x,w){return this._valid&&x(w(this._geometry)),this}require(x,w,A){return this.get(x,!0,w,A)}optional(x,w,A){return this.get(x,!1,w,A)}success(){return this._valid}get(x,w,A,L){const F=this.feature.properties.hasOwnProperty(x)?+this.feature.properties[x]:void 0;return this._valid&&F!==void 0&&!Number.isNaN(F)?A(L?L(F):F):w&&(this._valid=!1),this}}class vl{constructor(x,w){this.featureFunc=x,this.vertexFunc=w}parseFeature(x,w,A){return this.featureFunc(x,w,A)}parseVertex(x,w,A){return this.vertexFunc(x,w,A)}}const Ri=new vl((k,x,w)=>k.reset(x).require(Zi,A=>{w.id=A}).optional("fixed_height_relative",A=>{w.constantHeight=A},yc.decodeRelativeHeight).geometry(A=>{w.bounds=A},$u).success(),(k,x,w)=>k.reset(x).require(Zi,A=>{w.id=A}).require("elevation_idx",A=>{w.idx=A}).require("extent",A=>{w.extent=A}).require("height_relative",A=>{w.height=A},yc.decodeRelativeHeight).geometry(A=>{w.position=A},yc.getPoint).success()),Pd=new vl((k,x,w)=>k.reset(x).require(Zi,A=>{w.id=A}).optional("fixed_height",A=>{w.constantHeight=A},yc.decodeMetricHeight).geometry(A=>{w.bounds=A},$u).success(),(k,x,w)=>k.reset(x).require(Zi,A=>{w.id=A}).require("elevation_idx",A=>{w.idx=A}).require("extent",A=>{w.extent=A}).require("height",A=>{w.height=A},yc.decodeMetricHeight).geometry(A=>{w.position=A},yc.getPoint).success());class yc{static getPoint(x){return $s(x[0][0].x,x[0][0].y)}static decodeRelativeHeight(x){return 1e-4*x*5}static decodeMetricHeight(x){return 1e-4*x}static getVersionSchema(x){return x?x==="1.0.1"?Pd:void 0:Ri}static parse(x){const w=[],A=[],L=x.length,F=new cu;for(let U=0;U=0);if(F===0)return 0;F!==x.length&&(w=!1)}return w?2:1}function qm(k,x){for(const w of k.projections){const A=jm(x,k.points[0],w.axis);if(w.projection[1]A[1])return 0}return 1}function ff(k,x){let w=0;const A=[0,0,0,0];for(let L=0;L=0&&w++;return w}class qv{constructor(x,w){this.points=x||new Array(8).fill([0,0,0]),this.planes=w||new Array(6).fill([0,0,0,0]),this.bounds=Hl.fromPoints(this.points),this.projections=[],this.frustumEdges=[Ve([],this.points[2],this.points[3]),Ve([],this.points[0],this.points[3]),Ve([],this.points[4],this.points[0]),Ve([],this.points[5],this.points[1]),Ve([],this.points[6],this.points[2]),Ve([],this.points[7],this.points[3])];for(const A of this.frustumEdges){const L=[0,-A[2],A[1]],F=[A[2],0,-A[0]];this.projections.push({axis:L,projection:jm(this.points,this.points[0],L)}),this.projections.push({axis:F,projection:jm(this.points,this.points[0],F)})}}static fromInvProjectionMatrix(x,w,A,L){const F=Math.pow(2,A),U=[[-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(oe=>{const ge=Ge([],oe,x),we=1/ge[3]/w*F;return(je=ge)[0]=(Le=ge)[0]*(Re=[we,we,L?1/ge[3]:we,we])[0],je[1]=Le[1]*Re[1],je[2]=Le[2]*Re[2],je[3]=Le[3]*Re[3],je;var je,Le,Re}),K=[[0,1,2],[6,5,4],[0,3,7],[2,1,5],[3,2,6],[0,4,5]].map(oe=>{const ge=Ae([],ze([],Ve([],U[oe[0]],U[oe[1]]),Ve([],U[oe[2]],U[oe[1]]))),we=-Pe(ge,U[oe[1]]);return ge.concat(we)}),X=[];for(let oe=0;oeoe[1]||oe[0]>X[1])return 0}return 1}containsPoint(x){for(const w of this.planes){const A=w[3];if(Pe([w[0],w[1],w[2]],x)+A<0)return!1}return!0}}class Hl{static fromPoints(x){const w=[1/0,1/0,1/0],A=[-1/0,-1/0,-1/0];for(const L of x)te(w,w,L),ae(A,A,L);return new Hl(w,A)}static fromTileIdAndHeight(x,w,A){const L=1<x.max[w]||x.min[w]>this.max[w])return!1;return!0}intersectsAabbXY(x){return!(this.min[0]>x.max[0]||x.min[0]>this.max[0]||this.min[1]>x.max[1]||x.min[1]>this.max[1])}encapsulate(x){for(let w=0;w<3;w++)this.min[w]=Math.min(this.min[w],x.min[w]),this.max[w]=Math.max(this.max[w],x.max[w])}encapsulatePoint(x){for(let w=0;w<3;w++)this.min[w]=Math.min(this.min[w],x[w]),this.max[w]=Math.max(this.max[w],x[w])}closestPoint(x){return[Math.max(Math.min(this.max[0],x[0]),this.min[0]),Math.max(Math.min(this.max[1],x[1]),this.min[1]),Math.max(Math.min(this.max[2],x[2]),this.min[2])]}}jr(Hl,"Aabb");class z1{constructor(x,w){this.feature=x,this.metersToTile=w,this.index=0}get(){const x=this.feature.vertices[this.index],w=this.feature.vertexProps[this.index].dir,A=w[1],L=-w[0],F=(x.extent+1)*this.metersToTile;return[new Js(Math.trunc(x.position[0]+A*F),Math.trunc(x.position[1]+L*F)),new Js(Math.trunc(x.position[0]-A*F),Math.trunc(x.position[1]-L*F))]}next(){this.index++}valid(){return this.index{return K.a0?le(X,X,1/oe):Z(X,0,0,1)}getSafeArea(){return this.safeArea}isTunnel(){return this.heightRange.max<=-5}getClosestEdge(x){if(this.edges.length===0)return;let w=0,A=Number.POSITIVE_INFINITY,L=0;const[F,U,K,X,oe,ge,we]=this._tmpVec2;As(we,x.x,x.y);const je=new Ph(we,null);for(let Le=0;Le0?hn(X,K)/Et:0,Ot=pt(It,0,1),ws=Math.abs((It-Ot)*this.edgeProps[Le].len);ar(oe,we,et),As(ge,We[1],-We[0]);const ds=ws+Math.abs(hn(oe,ge));ds=0;--U){const K=this.edges[U].a,X=this.edges[U].b,{position:oe,height:ge,extent:we}=this.vertices[K],{position:je,height:Le,extent:Re}=this.vertices[X],We=this.vertexProps[K].dir,et=this.vertexProps[X].dir;if(Z(w,oe[0]/x,oe[1]/x,ge),Z(A,je[0]/x,je[1]/x,Le),Z(L,We[1],-We[0],0),le(L,L,we),Z(F,et[1],-et[0],0),le(F,F,Re),this.distSqLines(Y(w[0]+.5*L[0],w[1]+.5*L[1],w[2]+.5*L[2]),Y(A[0]-.5*F[0],A[1]-.5*F[1],A[2]-.5*F[2]),Y(w[0]-.5*L[0],w[1]-.5*L[1],w[2]-.5*L[2]),Y(A[0]+.5*F[0],A[1]+.5*F[1],A[2]+.5*F[2]))<=.0025000000000000005)continue;const it=this.vertices.length,yt=jn(vt(),oe,je);this.vertices.push({position:Dn(yt,yt,.5),height:.5*(ge+Le),extent:.5*(we+Re)});const ht=jn(vt(),We,et);this.vertexProps.push({dir:Vs(ht,ht)}),this.edges.splice(U,1),this.edgeProps.splice(U,1),this.edges.push({a:K,b:it}),this.edges.push({a:it,b:X});const Et=ar(vt(),this.vertices[it].position,oe),It=Ur(Et),Ot={vec:Et,dir:Dn(vt(),Et,1/It),len:It};this.edgeProps.push(Ot),this.edgeProps.push(Ot)}}distSqLines(x,w,A,L){const F=ce(G(),w,x),U=ce(G(),L,A),K=ce(G(),x,A),X=Pe(F,F),oe=Pe(F,U),ge=Pe(F,K),we=Pe(U,U),je=Pe(U,K),Le=X*we-oe*oe;if(Le===0)return he(ke(F,A,L,Pe(K,U)/Pe(U,U)),x);const Re=(X*je-oe*ge)/Le;return he(ke(F,x,w,(oe*je-ge*we)/Le),ke(U,A,L,Re))}}class Wc{static parseFrom(x,w){const A=yc.parse(x);if(!A)return[];let{vertices:L,features:F}=A;const U=1/Gn(w);F.sort((ge,we)=>ge.id-we.id),L.sort((ge,we)=>ge.id-we.id||ge.idx-we.idx),L=L.filter((ge,we,je)=>we===je.findIndex(Le=>Le.id===ge.id&&Le.idx===ge.idx));const K=new Array;let X=0;const oe=L.length;for(const ge of F){if(ge.constantHeight){K.push(new B1(ge.id,ge.bounds,ge.constantHeight));continue}for(;X!==oe&&L[X].idL.id===A)}}class rd{constructor(x,w){this.zScale=1,this.xOffset=0,this.yOffset=0,x.equals(w)||(this.zScale=Math.pow(2,w.z-x.z),this.xOffset=(x.x*this.zScale-w.x)*ur,this.yOffset=(x.y*this.zScale-w.y)*ur)}constantElevation(x,w){if(x.constantHeight!=null)return this.computeBiasedHeight(x.constantHeight,w)}pointElevation(x,w,A){const L=this.constantElevation(w,A);return L??(x.x=x.x*this.zScale+this.xOffset,x.y=x.y*this.zScale+this.yOffset,this.computeBiasedHeight(w.pointElevation(x),A))}computeBiasedHeight(x,w){return w<=0?x:x+w*jt(0,w,x>=0?x:Math.abs(.5*x))}}jr(B1,"ElevationFeature");class ac{constructor(x){this.zoom=x.zoom,this.overscaling=x.overscaling,this.layers=x.layers,this.layerIds=this.layers.map(w=>w.fqid),this.index=x.index,this.hasPattern=!1,this.projection=x.projection,this.layoutVertexArray=new ao,this.indexArray=new Ju,this.segments=new Rc,this.programConfigurations=new tt(x.layers,{zoom:x.zoom,lut:x.lut}),this.stateDependentLayerIds=this.layers.filter(w=>w.isStateDependent()).map(w=>w.id),this.elevationMode=this.layers[0].layout.get("circle-elevation-reference"),this.hasElevation=!1,this.elevationMode!=="none"&&(this.elevatedLayoutVertexArray=new Zl),this.worldview=x.worldview,this.hasAppearances=null}updateFootprints(x,w){}updateAppearances(x,w,A,L){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(x,w,A,L){const F=this.layers[0],U=[];let K=null;F.type==="circle"&&(K=F.layout.get("circle-sort-key"));for(const{feature:oe,id:ge,index:we,sourceLayerIndex:je}of x){const Le=this.layers[0]._featureFilter.needGeometry,Re=oo(oe,Le);if(!this.layers[0]._featureFilter.filter(new $i(this.zoom,{worldview:this.worldview,activeFloors:w.activeFloors}),Re,A))continue;const We=K?K.evaluate(Re,{},A):void 0,et={id:ge,properties:oe.properties,type:oe.type,sourceLayerIndex:je,index:we,geometry:Le?Re.geometry:Qa(oe,A,L),patterns:{},sortKey:We};U.push(et)}K&&U.sort((oe,ge)=>oe.sortKey-ge.sortKey);let X=null;L.projection.name==="globe"&&(this.globeExtVertexArray=new Az,X=L.projection);for(const oe of U){const{geometry:ge,index:we,sourceLayerIndex:je}=oe,Le=x[we].feature;this.addFeature(oe,ge,we,w.availableImages,A,X,w.brightness,w.elevationFeatures),w.featureIndex.insert(Le,ge,we,je,this.index)}this.hasElevation||(this.elevatedLayoutVertexArray=void 0)}update(x,w,A,L,F,U,K){this.programConfigurations.updatePaintArrays(x,w,F,A,L,U,K,this.worldview)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(x){this.uploaded||(this.layoutVertexBuffer=x.createVertexBuffer(this.layoutVertexArray,_ie.members),this.indexBuffer=x.createIndexBuffer(this.indexArray),this.globeExtVertexArray&&(this.globeExtVertexBuffer=x.createVertexBuffer(this.globeExtVertexArray,NDe.members)),this.elevatedLayoutVertexArray&&(this.elevatedLayoutVertexBuffer=x.createVertexBuffer(this.elevatedLayoutVertexArray,jDe.members))),this.programConfigurations.upload(x),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(x,w,A,L,F,U,K,X){let oe;this.elevationMode!=="none"&&(oe=Wc.getElevationFeature(x,X));for(const ge of w)for(const we of ge){const je=we.x,Le=we.y;if(je<0||je>=ur||Le<0||Le>=ur)continue;if(U){const et=U.projectTilePoint(je,Le,F),it=U.upVector(F,je,Le);this.addGlobeExtVertex(et,it),this.addGlobeExtVertex(et,it),this.addGlobeExtVertex(et,it),this.addGlobeExtVertex(et,it)}const Re=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray,x.sortKey),We=Re.vertexLength;if(this.addCircleVertex(je,Le,-1,-1),this.addCircleVertex(je,Le,1,-1),this.addCircleVertex(je,Le,1,1),this.addCircleVertex(je,Le,-1,1),this.elevationMode!=="none"){const et=oe?oe.pointElevation(new Js(je,Le)):0;this.hasElevation=this.hasElevation||et!==0;for(let it=0;it<4;it++)this.elevatedLayoutVertexArray.emplaceBack(et)}this.indexArray.emplaceBack(We,We+1,We+2),this.indexArray.emplaceBack(We,We+2,We+3),Re.vertexLength+=4,Re.primitiveLength+=2}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,x,A,{},L,F,K,void 0,this.worldview)}addCircleVertex(x,w,A,L){this.layoutVertexArray.emplaceBack(2*x+(A+1)/2,2*w+(L+1)/2)}addGlobeExtVertex(x,w){this.globeExtVertexArray.emplaceBack(x.x,x.y,x.z,w[0]*16384,w[1]*16384,w[2]*16384)}}function gh(k,x){for(let w=0;w1){if(l5(k,x))return!0;for(let A=0;A1?w:w.sub(x)._mult(L)._add(x))}function aT(k,x){let w,A,L,F=!1;for(let U=0;Ux.y!=L.y>x.y&&x.x<(L.x-A.x)*(x.y-A.y)/(L.y-A.y)+A.x&&(F=!F)}return F}function Ky(k,x){let w=!1;for(let A=0,L=k.length-1;Ax.y!=U.y>x.y&&x.x<(U.x-F.x)*(x.y-F.y)/(U.y-F.y)+F.x&&(w=!w)}return w}function c5(k,x,w,A,L){for(const U of k)if(x<=U.x&&w<=U.y&&A>=U.x&&L>=U.y)return!0;const F=[new Js(x,w),new Js(x,L),new Js(A,L),new Js(A,w)];if(k.length>2){for(const U of F)if(Ky(k,U))return!0}for(let U=0;UL.x&&x.x>L.x||k.yL.y&&x.y>L.y)return!1;const F=sa(k,x,w[0]);return F!==sa(k,x,w[1])||F!==sa(k,x,w[2])||F!==sa(k,x,w[3])}function u5(k,x,w,A,L,F){let U=x.y-k.y,K=k.x-x.x;if(F=F||0){const X=U*U+K*K;if(X===0)return!0;const oe=Math.sqrt(X);U/=oe,K/=oe}return!((w.x-k.x)*U+(w.y-k.y)*K-F<0||(A.x-k.x)*U+(A.y-k.y)*K-F<0||(L.x-k.x)*U+(L.y-k.y)*K-F<0)}function Fz(k,x,w,A,L,F,U){return!(u5(k,x,A,L,F,U)||u5(x,w,A,L,F,U)||u5(w,k,A,L,F,U)||u5(A,L,k,x,w,U)||u5(L,F,k,x,w,U)||u5(F,A,k,x,w,U))}function iT(k,x,w){const A=x.paint.get(k).value;return A.kind==="constant"?A.value:w.programConfigurations.get(x.id).getMaxValue(k)}function wie(k){return Math.sqrt(k[0]*k[0]+k[1]*k[1])}function lot(k,x,w,A,L){if(!x[0]&&!x[1])return k;const F=Js.convert(x)._mult(L);w==="viewport"&&F._rotate(-A);const U=[];for(let K=0;K>w&&x.y===this.y>>w}url(x,w){const A=function(F,U,K){const X=2**K,oe=2*Math.PI*6378137,ge=oe*(F/X-.5),we=oe*(.5-(U+1)/X);return`${ge},${we},${ge+oe/X},${we+oe/X}`}(this.x,this.y,this.z),L=function(F,U,K){let X,oe="";for(let ge=F;ge>0;ge--)X=1<this.canonical.z?new W0(x,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y):new W0(x,this.wrap,x,this.canonical.x>>w,this.canonical.y>>w)}calculateScaledKey(x,w=!0){if(this.overscaledZ===x&&w)return this.key;if(x>this.canonical.z)return Oz(this.wrap*+w,x,this.canonical.z,this.canonical.x,this.canonical.y);{const A=this.canonical.z-x;return Oz(this.wrap*+w,x,x,this.canonical.x>>A,this.canonical.y>>A)}}isChildOf(x){if(x.wrap!==this.wrap)return!1;const w=this.canonical.z-x.canonical.z;return x.overscaledZ===0||x.overscaledZ>w&&x.canonical.y===this.canonical.y>>w}children(x){if(this.overscaledZ>=x)return[new W0(this.overscaledZ+1,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)];const w=this.canonical.z+1,A=2*this.canonical.x,L=2*this.canonical.y;return[new W0(w,this.wrap,w,A,L),new W0(w,this.wrap,w,A+1,L),new W0(w,this.wrap,w,A,L+1),new W0(w,this.wrap,w,A+1,L+1)]}isLessThan(x){return this.wrapx.wrap)&&(this.overscaledZx.overscaledZ)&&(this.canonical.xx.canonical.x)&&this.canonical.y{let x=k.canonical.x-1,w=k.wrap;return x<0&&(x=(1<{let x=k.canonical.x+1,w=k.wrap;return x===1<new W0(k.overscaledZ,k.wrap,k.canonical.z,k.canonical.x,(k.canonical.y===0?1<new W0(k.overscaledZ,k.wrap,k.canonical.z,k.canonical.x,k.canonical.y===(1<1?null:function(A,L,F,U){const K=Math.sin(F);return A*(Math.sin((1-U)*F)/K)+L*(Math.sin(U*F)/K)}(k.a[x],k.b[x],k.angle,pt(w,0,1))+k.center[x]}function h5(k){if(k.z<=1)return Cls[k.z+2*k.y+k.x];const x=MDe(kie(k));return Hl.fromPoints(x)}function n3(k,x,w){return le(k,k,1-w),be(k,k,x,w)}function fot(k,x){const w=r3(x.zoom);if(w===0)return h5(k);const A=kie(k),L=MDe(A),F=zn(A.getWest())*x.worldSize,U=zn(A.getEast())*x.worldSize,K=Kn(A.getNorth())*x.worldSize,X=Kn(A.getSouth())*x.worldSize,oe=[F,K,0],ge=[U,K,0],we=[F,X,0],je=[U,X,0],Le=g([],x.globeMatrix);return Ze(oe,oe,Le),Ze(ge,ge,Le),Ze(we,we,Le),Ze(je,je,Le),L[0]=n3(L[0],we,w),L[1]=n3(L[1],je,w),L[2]=n3(L[2],ge,w),L[3]=n3(L[3],oe,w),Hl.fromPoints(L)}function xot(k,x,w){for(const A of k)Ze(A,A,x),le(A,A,w)}function got(k,x,w,A){const L=x/k.worldSize,F=k.globeMatrix;if(w.z<=1){const _s=h5(w).getCorners();return xot(_s,F,L),Hl.fromPoints(_s)}const U=kie(w,A),K=MDe(U,Yt+Nie(k._tileCoverLift));xot(K,F,L);const X=Number.MAX_VALUE,oe=[-X,-X,-X],ge=[X,X,X];if(U.contains(k.center)){for(const ys of K)te(ge,ge,ys),ae(oe,oe,ys);oe[2]=0;const _s=k.point,gs=[_s.x*L,_s.y*L,0];return te(ge,ge,gs),ae(oe,oe,gs),new Hl(ge,oe)}if(k._tileCoverLift>0){for(const _s of K)te(ge,ge,_s),ae(oe,oe,_s);return new Hl(ge,oe)}const we=[F[12]*L,F[13]*L,F[14]*L],je=U.getCenter(),Le=pt(k.center.lat,-85.051129,Tn),Re=pt(je.lat,-85.051129,Tn),We=zn(k.center.lng),et=Kn(Le);let it=We-zn(je.lng);const yt=et-Kn(Re);it>.5?it-=1:it<-.5&&(it+=1);let ht=0;Math.abs(it)>Math.abs(yt)?ht=it>=0?1:3:(ht=yt>=0?0:2,be(we,we,[F[4]*L,F[5]*L,F[6]*L],-Math.sin(Ws(yt>=0?U.getSouth():U.getNorth()))*Yt));const Et=K[ht],It=K[(ht+1)%4],Ot=new Als(Et,It,we),ws=[TDe(Ot,0)||Et[0],TDe(Ot,1)||Et[1],TDe(Ot,2)||Et[2]],ds=r3(k.zoom);if(ds>0){const _s=function({x:ys,y:vn,z:wn},Pn,On,Ln,Jn){const gn=1/(1<.5?na=-1:Cr<-.5&&(na=1),Rn=((Rn+na)*Pn-(Ln*=Pn))*On+Ln,qn=((qn+na)*Pn-Ln)*On+Ln,tr=(tr*Pn-(Jn*=Pn))*On+Jn,pr=(pr*Pn-Jn)*On+Jn,[[Rn,pr,0],[qn,pr,0],[qn,tr,0],[Rn,tr,0]]}(w,x,k._pixelsPerMercatorPixel,We,et);for(let ys=0;ysMath.PI/2*1.01}const wot=Ws(85),Els=Math.cos(wot),Tls=Math.sin(wot),Mls=f(),jot=k=>{const x=[];return k.paint.get("circle-pitch-alignment")==="map"&&x.push("PITCH_WITH_MAP"),k.paint.get("circle-pitch-scale")==="map"&&x.push("SCALE_WITH_MAP"),x};function Not(k,x,w,A,L,F,U,K,X){if(F&&k.queryGeometry.isAboveHorizon)return!1;F&&(X*=k.pixelToTileUnitsFactor);const oe=k.tileID.canonical,ge=w.projection.upVectorScale(oe,w.center.lat,w.worldSize).metersToTile;for(const we of x)for(const je of we){const Le=je.add(K),Re=L&&w.elevation?w.elevation.exaggeration()*L.getElevationAt(Le.x,Le.y,!0):0,We=w.projection.projectTilePoint(Le.x,Le.y,oe);if(Re>0){const ht=w.projection.upVector(oe,Le.x,Le.y);We.x+=ht[0]*ge*Re,We.y+=ht[1]*ge*Re,We.z+=ht[2]*ge*Re}const et=F?Le:Pls(We.x,We.y,We.z,A),it=F?k.tilespaceRays.map(ht=>Ils(ht,Re)):k.queryGeometry.screenGeometry,yt=Ge([],[We.x,We.y,We.z,1],A);if(!U&&F?X*=yt[3]/w.cameraToCenterDistance:U&&!F&&(X*=w.cameraToCenterDistance/yt[3]),F){const ht=yn((je.y/ur+oe.y)/(1<k.width||L.height>k.height||w.x>k.width-L.width||w.y>k.height-L.height)throw new RangeError("out of range source coordinates for image copy");if(L.width>x.width||L.height>x.height||A.x>x.width-L.width||A.y>x.height-L.height)throw new RangeError("out of range destination coordinates for image copy");const X=k.data,oe=x.data,ge=F===4&&K;for(let we=0;we{x[k.evaluationKey]=X;const oe=k.expression.evaluate(x),ge=oe?oe.toNonPremultipliedRenderColor(null):null;ge&&(L.data[U+K+0]=Math.floor(255*ge.r),L.data[U+K+1]=Math.floor(255*ge.g),L.data[U+K+2]=Math.floor(255*ge.b),L.data[U+K+3]=Math.floor(255*ge.a))};if(k.clips)for(let U=0,K=0;U80*w){K=k[0],X=k[1];let ge=K,we=X;for(let je=w;jege&&(ge=Le),Re>we&&(we=Re)}oe=Math.max(ge-K,we-X),oe=oe!==0?32767/oe:0}return RK(F,U,w,K,X,oe,0),U}function Iot(k,x,w,A,L){let F;if(L===function(U,K,X,oe){let ge=0;for(let we=K,je=X-oe;we0)for(let U=x;U=x;U-=A)F=Oot(U/A|0,k[U],k[U+1],F);return F&&Bz(F,F.next)&&(zK(F),F=F.next),F}function aI(k,x){if(!k)return k;x||(x=k);let w,A=k;do if(w=!1,A.steiner||!Bz(A,A.next)&&xf(A.prev,A,A.next)!==0)A=A.next;else{if(zK(A),A=x=A.prev,A===A.next)break;w=!0}while(w||A!==x);return x}function RK(k,x,w,A,L,F,U){if(!k)return;!U&&F&&function(X,oe,ge,we){let je=X;do je.z===0&&(je.z=RDe(je.x,je.y,oe,ge,we)),je.prevZ=je.prev,je.nextZ=je.next,je=je.next;while(je!==X);je.prevZ.nextZ=null,je.prevZ=null,function(Le){let Re,We=1;do{let et,it=Le;Le=null;let yt=null;for(Re=0;it;){Re++;let ht=it,Et=0;for(let Ot=0;Ot0||It>0&&ht;)Et!==0&&(It===0||!ht||it.z<=ht.z)?(et=it,it=it.nextZ,Et--):(et=ht,ht=ht.nextZ,It--),yt?yt.nextZ=et:Le=et,et.prevZ=yt,yt=et;it=ht}yt.nextZ=null,We*=2}while(Re>1)}(je)}(k,A,L,F);let K=k;for(;k.prev!==k.next;){const X=k.prev,oe=k.next;if(F?Bls(k,A,L,F):zls(k))x.push(X.i,k.i,oe.i),zK(k),k=oe.next,K=oe.next;else if((k=oe)===K){U?U===1?RK(k=Uls(aI(k),x),x,w,A,L,F,2):U===2&&qls(k,x,w,A,L,F):RK(aI(k),x,w,A,L,F,1);break}}}function zls(k){const x=k.prev,w=k,A=k.next;if(xf(x,w,A)>=0)return!1;const L=x.x,F=w.x,U=A.x,K=x.y,X=w.y,oe=A.y,ge=Math.min(L,F,U),we=Math.min(K,X,oe),je=Math.max(L,F,U),Le=Math.max(K,X,oe);let Re=A.next;for(;Re!==x;){if(Re.x>=ge&&Re.x<=je&&Re.y>=we&&Re.y<=Le&&FK(L,K,F,X,U,oe,Re.x,Re.y)&&xf(Re.prev,Re,Re.next)>=0)return!1;Re=Re.next}return!0}function Bls(k,x,w,A){const L=k.prev,F=k,U=k.next;if(xf(L,F,U)>=0)return!1;const K=L.x,X=F.x,oe=U.x,ge=L.y,we=F.y,je=U.y,Le=Math.min(K,X,oe),Re=Math.min(ge,we,je),We=Math.max(K,X,oe),et=Math.max(ge,we,je),it=RDe(Le,Re,x,w,A),yt=RDe(We,et,x,w,A);let ht=k.prevZ,Et=k.nextZ;for(;ht&&ht.z>=it&&Et&&Et.z<=yt;){if(ht.x>=Le&&ht.x<=We&&ht.y>=Re&&ht.y<=et&&ht!==L&&ht!==U&&FK(K,ge,X,we,oe,je,ht.x,ht.y)&&xf(ht.prev,ht,ht.next)>=0||(ht=ht.prevZ,Et.x>=Le&&Et.x<=We&&Et.y>=Re&&Et.y<=et&&Et!==L&&Et!==U&&FK(K,ge,X,we,oe,je,Et.x,Et.y)&&xf(Et.prev,Et,Et.next)>=0))return!1;Et=Et.nextZ}for(;ht&&ht.z>=it;){if(ht.x>=Le&&ht.x<=We&&ht.y>=Re&&ht.y<=et&&ht!==L&&ht!==U&&FK(K,ge,X,we,oe,je,ht.x,ht.y)&&xf(ht.prev,ht,ht.next)>=0)return!1;ht=ht.prevZ}for(;Et&&Et.z<=yt;){if(Et.x>=Le&&Et.x<=We&&Et.y>=Re&&Et.y<=et&&Et!==L&&Et!==U&&FK(K,ge,X,we,oe,je,Et.x,Et.y)&&xf(Et.prev,Et,Et.next)>=0)return!1;Et=Et.nextZ}return!0}function Uls(k,x){let w=k;do{const A=w.prev,L=w.next.next;!Bz(A,L)&&Rot(A,w,w.next,L)&&OK(A,L)&&OK(L,A)&&(x.push(A.i,w.i,L.i),zK(w),zK(w.next),w=k=L),w=w.next}while(w!==k);return aI(w)}function qls(k,x,w,A,L,F){let U=k;do{let K=U.next.next;for(;K!==U.prev;){if(U.i!==K.i&&Wls(U,K)){let X=Fot(U,K);return U=aI(U,U.next),X=aI(X,X.next),RK(U,x,w,A,L,F,0),void RK(X,x,w,A,L,F,0)}K=K.next}U=U.next}while(U!==k)}function $ls(k,x){let w=k.x-x.x;return w===0&&(w=k.y-x.y,w===0)&&(w=(k.next.y-k.y)/(k.next.x-k.x)-(x.next.y-x.y)/(x.next.x-x.x)),w}function Vls(k,x){const w=function(L,F){let U=F;const K=L.x,X=L.y;let oe,ge=-1/0;if(Bz(L,U))return U;do{if(Bz(L,U.next))return U.next;if(X<=U.y&&X>=U.next.y&&U.next.y!==U.y){const We=U.x+(X-U.y)*(U.next.x-U.x)/(U.next.y-U.y);if(We<=K&&We>ge&&(ge=We,oe=U.x=U.x&&U.x>=je&&K!==U.x&&Dot(Xoe.x||U.x===oe.x&&Hls(oe,U)))&&(oe=U,Re=We)}U=U.next}while(U!==we);return oe}(k,x);if(!w)return x;const A=Fot(w,k);return aI(A,A.next),aI(w,w.next)}function Hls(k,x){return xf(k.prev,k,x.prev)<0&&xf(x.next,k,k.next)<0}function RDe(k,x,w,A,L){return(k=1431655765&((k=858993459&((k=252645135&((k=16711935&((k=(k-w)*L|0)|k<<8))|k<<4))|k<<2))|k<<1))|(x=1431655765&((x=858993459&((x=252645135&((x=16711935&((x=(x-A)*L|0)|x<<8))|x<<4))|x<<2))|x<<1))<<1}function Gls(k){let x=k,w=k;do(x.x=(k-U)*(F-K)&&(k-U)*(A-K)>=(w-U)*(x-K)&&(w-U)*(F-K)>=(L-U)*(A-K)}function FK(k,x,w,A,L,F,U,K){return!(k===U&&x===K)&&Dot(k,x,w,A,L,F,U,K)}function Wls(k,x){return k.next.i!==x.i&&k.prev.i!==x.i&&!function(w,A){let L=w;do{if(L.i!==w.i&&L.next.i!==w.i&&L.i!==A.i&&L.next.i!==A.i&&Rot(L,L.next,w,A))return!0;L=L.next}while(L!==w);return!1}(k,x)&&(OK(k,x)&&OK(x,k)&&function(w,A){let L=w,F=!1;const U=(w.x+A.x)/2,K=(w.y+A.y)/2;do L.y>K!=L.next.y>K&&L.next.y!==L.y&&U<(L.next.x-L.x)*(K-L.y)/(L.next.y-L.y)+L.x&&(F=!F),L=L.next;while(L!==w);return F}(k,x)&&(xf(k.prev,k,x.prev)||xf(k,x.prev,x))||Bz(k,x)&&xf(k.prev,k,k.next)>0&&xf(x.prev,x,x.next)>0)}function xf(k,x,w){return(x.y-k.y)*(w.x-x.x)-(x.x-k.x)*(w.y-x.y)}function Bz(k,x){return k.x===x.x&&k.y===x.y}function Rot(k,x,w,A){const L=Aie(xf(k,x,w)),F=Aie(xf(k,x,A)),U=Aie(xf(w,A,k)),K=Aie(xf(w,A,x));return L!==F&&U!==K||!(L!==0||!Cie(k,w,x))||!(F!==0||!Cie(k,A,x))||!(U!==0||!Cie(w,k,A))||!(K!==0||!Cie(w,x,A))}function Cie(k,x,w){return x.x<=Math.max(k.x,w.x)&&x.x>=Math.min(k.x,w.x)&&x.y<=Math.max(k.y,w.y)&&x.y>=Math.min(k.y,w.y)}function Aie(k){return k>0?1:k<0?-1:0}function OK(k,x){return xf(k.prev,k,k.next)<0?xf(k,x,k.next)>=0&&xf(k,k.prev,x)>=0:xf(k,x,k.prev)<0||xf(k,k.next,x)<0}function Fot(k,x){const w=FDe(k.i,k.x,k.y),A=FDe(x.i,x.x,x.y),L=k.next,F=x.prev;return k.next=x,x.prev=k,w.next=L,L.prev=w,A.next=w,w.prev=A,F.next=A,A.prev=F,A}function Oot(k,x,w,A){const L=FDe(k,x,w);return A?(L.next=A.next,L.prev=A,A.next.prev=L,A.next=L):(L.prev=L,L.next=L),L}function zK(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 FDe(k,x,w){return{i:k,x,y:w,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function BK(k,x){const w=k.length;if(w<=1)return[k];const A=[];let L,F;for(let U=0;U1)for(let U=0;U=ur&&w>=ur}static evaluate(x){if(x.length===0)return new a3;let w=[];for(const X of x)w.push(...X.portals);if(w.length===0)return new a3;for(const X of w){const oe=X.va,ge=X.vb;(a3.isOnBorder(oe.x,ge.x)||a3.isOnBorder(oe.y,ge.y))&&(X.type="border")}const A=w.filter(X=>X.type!=="unevaluated"),L=w.filter(X=>X.type==="unevaluated");if(L.length===0)return new a3;L.sort((X,oe)=>X.hash===oe.hash?X.isTunnel===oe.isTunnel?0:X.isTunnel?-1:1:X.hashX.hashF!=="fill-tunnel-structure-color"),this.tunnelProgramConfigurations=new tt(w,{zoom:A,lut:L},F=>F!=="fill-bridge-guard-rail-color")}addVertices(x,w){const A=this.unevalVertices.length;for(let L=0;L=F.min.x&&we.x<=F.max.x&&we.y>=F.min.y&&we.y<=F.max.y||je.x>=F.min.x&&je.x<=F.max.x&&je.y>=F.min.y&&je.y<=F.max.y||d5(we,je,K))||this.isOnBorder(we.x,je.x)||this.isOnBorder(we.y,je.y))continue;const Le=U1.computeEdgeHash(this.unevalVertices[oe],this.unevalVertices[ge]);let Re,We=this.vertexHashLookup.get(U1.computePosHash(we));We!=null?Re=We.next:(We=this.vertexHashLookup.get(U1.computePosHash(je)),Re=We!=null?We.prev:Le),this.unevalEdges.push({polygonIdx:x,a:oe,b:ge,hash:Le,portalHash:Re,isTunnel:L,type:"unevaluated",featureInfo:U})}}addPortalCandidates(x,w,A,L,F){if(w.length!==0){this.vertexHashLookup.clear();for(const U of w){if(U.length===0)continue;const K=U[0];let X=U1.computeEdgeHash(K[K.length-2],K[K.length-1]);for(let oe=0;oe({vertexOffset:0,primitiveOffset:this.indexArray.length}),A=je=>{je.primitiveLength=this.indexArray.length-je.primitiveOffset},L=new Yls(this.vertexPositions,this.vertexNormals,this.indexArray);this.prepareEdges(x.portals,this.unevalEdges);const F=w(),U=w(),K=w(),X=(je,Le)=>{je.sort((We,et)=>We.type===Le&&et.type!==Le?-1:We.type!==Le&&et.type===Le?1:0);const Re=je.findIndex(We=>We.type!==Le);return Re>=0?Re:je.length};let oe=0;this.unevalEdges.length>0&&(oe=X(this.unevalEdges,"none"),this.constructBridgeStructures(L,this.unevalVertices,this.unevalHeights,this.unevalEdges,{min:0,max:oe},this.tileToMeters)),A(K);const ge=w(),we=w();if(this.unevalEdges.length>0){const je=this.unevalEdges.splice(oe),Le=X(je,"tunnel")+oe;this.unevalEdges.push(...je),this.constructTunnelStructures(L,this.unevalVertices,this.unevalHeights,this.unevalEdges,{min:0,max:oe},{min:oe,max:Le})}A(ge),L.addTriangles(this.unevalTriangles,this.unevalVertices,this.unevalHeights),A(we),L.addTriangles(this.unevalTunnelTriangles,this.unevalVertices,this.unevalHeights),A(U),L.addTriangles(this.unevalTunnelTriangles,this.unevalVertices,[-.1]),A(F),this.maskSegments=Rc.simpleSegment(0,we.primitiveOffset,0,we.primitiveLength),this.depthSegments=Rc.simpleSegment(0,U.primitiveOffset,0,U.primitiveLength),this.renderableBridgeSegments=Rc.simpleSegment(0,K.primitiveOffset,0,K.primitiveLength),this.renderableTunnelSegments=Rc.simpleSegment(0,ge.primitiveOffset,0,ge.primitiveLength),this.shadowCasterSegments=Rc.simpleSegment(0,F.primitiveOffset,0,F.primitiveLength)}update(x,w,A,L,F,U,K,X){this.bridgeProgramConfigurations.updatePaintArrays(x,w,F,A,L,U,K,X),this.tunnelProgramConfigurations.updatePaintArrays(x,w,F,A,L,U,K,X)}upload(x){this.vertexBuffer||this.vertexPositions.length===0||this.vertexNormals.length===0||this.indexArray.length===0||(this.vertexBuffer=x.createVertexBuffer(this.vertexPositions,Fls.members),this.vertexBufferNormal=x.createVertexBuffer(this.vertexNormals,Ols.members),this.indexBuffer=x.createIndexBuffer(this.indexArray),this.bridgeProgramConfigurations.upload(x),this.tunnelProgramConfigurations.upload(x))}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(x,w,A,L,F){const U=(K,X)=>{for(let oe=0;oeZ(On,w[Ln].x,w[Ln].y,A[Ln]*X),we=G(),je=G(),Le=G(),Re=G(),We=G(),et=(On,Ln)=>{const Jn=K.get(U1.computePosHash(w[Ln])),gn=Jn.from,Rn=Jn.to;if(!gn||!Rn)return;ge(we,gn),ge(je,Ln),ge(Le,Rn),Ne(Re),Ye(we,je)||(Ve(We,je,we),Ae(Re,We)),Ye(Le,je)||(Ve(We,Le,je),ne(Re,Re,Ae(We,We)));const qn=Qe(Re);return qn>0?le(On,Re,1/qn):void 0};let it=Number.POSITIVE_INFINITY;this.sortSubarray(L,F.min,F.max,(On,Ln)=>On.featureInfo.featureIndex-Ln.featureInfo.featureIndex);const yt=G(),ht=G(),Et=G(),It=G(),Ot=G(),ws=G(),ds=G(),_s=G(),gs=G(),ys=[G(),G(),G(),G()],vn=[G(),G(),G(),G()],wn=[{coord:new Js(0,0),height:0},{coord:new Js(0,0),height:0}],Pn=(On,Ln)=>On>Ln;for(let On=F.min;Onit.featureInfo.featureIndex-yt.featureInfo.featureIndex;this.sortSubarray(L,F.min,F.max,X),this.sortSubarray(L,U.min,U.max,X);const oe=it=>Ae(it,it),ge=[{coord:new Js(0,0),height:0},{coord:new Js(0,0),height:0}],we=(it,yt)=>itK.hash===X.hash?X.polygonIdx-K.polygonIdx:X.hash>K.hash?1:-1);let A=0,L=0,F=0,U=w[A].polygonIdx;do L++,(L===w.length||w[A].hash!==w[L].hash)&&((L-A===1||w[L-1].polygonIdx!==U)&&(Foe.portalHashge.hash?K++:ge.hash>oe.portalHash?X++:(oe.type=ge.type,K++)}}}isOnBorder(x,w){return x<=0&&w<=0||x>=ur&&w>=ur}addFeatureSection(x,w,A,L){return x!==w&&(w=x,A.push({featureIndex:x,vertexStart:L.getVertexCount()}),L.clearVertexLookup()),w}sortSubarray(x,w,A,L){const F=x.slice(w,A);F.sort(L),x.splice(w,F.length,...F)}static computeEdgeHash(x,w){return(x.y===w.y&&x.x>w.x||x.y>w.y)&&([x,w]=[w,x]),BigInt(U1.computePosHash(x))<<32n|BigInt(U1.computePosHash(w))}static computePosHash(x){return((65535&x.x)<<16|65535&x.y)>>>0}}function Zls(k,x){return k>x?1:k0))return w;w=w.left}}return null}contains(x){for(var w=this._root,A=this._compare;w;){var L=A(x,w.key);if(L===0)return!0;w=L<0?w.left:w.right}return!1}remove(x){var w=this.find(x);if(!w)return!1;if(this.splay(w),w.left)if(w.right){var A=this.minNode(w.right);A.parent!==w&&(this.replace(A,A.right),A.right=w.right,A.right.parent=A),this.replace(w,A),A.left=w.left,A.left.parent=A}else this.replace(w,w.left);else this.replace(w,w.right);return this._size--,!0}removeNode(x){if(!x)return!1;if(this.splay(x),x.left)if(x.right){var w=this.minNode(x.right);w.parent!==x&&(this.replace(w,w.right),w.right=x.right,w.right.parent=w),this.replace(x,w),w.left=x.left,w.left.parent=w}else this.replace(x,x.left);else this.replace(x,x.right);return this._size--,!0}erase(x){var w=this.find(x);if(w){this.splay(w);var A=w.left,L=w.right,F=null;A&&(A.parent=null,F=this.maxNode(A),this.splay(F),this._root=F),L&&(A?F.right=L:this._root=L,L.parent=F),this._size--}}pop(){var x=this._root,w=null;if(x){for(;x.left;)x=x.left;w={key:x.key,data:x.data},this.remove(x.key)}return w}next(x){var w=x;if(w)if(w.right)for(w=w.right;w&&w.left;)w=w.left;else for(w=x.parent;w&&w.right===x;)x=w,w=w.parent;return w}prev(x){var w=x;if(w)if(w.left)for(w=w.left;w&&w.right;)w=w.right;else for(w=x.parent;w&&w.left===x;)x=w,w=w.parent;return w}forEach(x){for(var w=this._root,A=[],L=!1,F=0;!L;)w?(A.push(w),w=w.left):A.length>0?(x(w=A.pop(),F++),w=w.right):L=!0;return this}range(x,w,A,L){const F=[],U=this._compare;let K,X=this._root;for(;F.length!==0||X;)if(X)F.push(X),X=X.left;else{if(X=F.pop(),K=U(X.key,w),K>0)break;if(U(X.key,x)>=0&&A.call(L,X))return this;X=X.right}return this}keys(){for(var x=this._root,w=[],A=[],L=!1;!L;)x?(w.push(x),x=x.left):w.length>0?(x=w.pop(),A.push(x.key),x=x.right):L=!0;return A}values(){for(var x=this._root,w=[],A=[],L=!1;!L;)x?(w.push(x),x=x.left):w.length>0?(x=w.pop(),A.push(x.data),x=x.right):L=!0;return A}at(x){for(var w=this._root,A=[],L=!1,F=0;!L;)if(w)A.push(w),w=w.left;else if(A.length>0){if(w=A.pop(),F===x)return w;F++,w=w.right}else L=!0;return null}load(x=[],w=[],A=!1){if(this._size!==0)throw new Error("bulk-load: tree is not empty");const L=x.length;return A&&qDe(x,w,0,L-1,this._compare),this._root=UDe(null,x,w,0,L),this._size=L,this}min(){var x=this.minNode(this._root);return x?x.key:null}max(){var x=this.maxNode(this._root);return x?x.key:null}isEmpty(){return this._root===null}get size(){return this._size}static createTree(x,w,A,L,F){return new BDe(A,F).load(x,w,L)}}function UDe(k,x,w,A,L){const F=L-A;if(F>0){const U=A+Math.floor(F/2),K={key:x[U],data:w[U],parent:k};return K.left=UDe(K,x,w,A,U),K.right=UDe(K,x,w,U+1,L),K}return null}function qDe(k,x,w,A,L){if(w>=A)return;const F=k[w+A>>1];let U=w-1,K=A+1;for(;;){do U++;while(L(k[U],F)<0);do K--;while(L(k[K],F)>0);if(U>=K)break;let X=k[U];k[U]=k[K],k[K]=X,X=x[U],x[U]=x[K],x[K]=X}qDe(k,x,w,K,L),qDe(k,x,K+1,A,L)}const Bot=11102230246251565e-32,Vv=134217729,Xls=(3+8*Bot)*Bot;function $De(k,x,w,A,L){let F,U,K,X,oe=x[0],ge=A[0],we=0,je=0;ge>oe==ge>-oe?(F=oe,oe=x[++we]):(F=ge,ge=A[++je]);let Le=0;if(weoe==ge>-oe?(U=oe+F,K=F-(U-oe),oe=x[++we]):(U=ge+F,K=F-(U-ge),ge=A[++je]),F=U,K!==0&&(L[Le++]=K);weoe==ge>-oe?(U=F+oe,X=U-F,K=F-(U-X)+(oe-X),oe=x[++we]):(U=F+ge,X=U-F,K=F-(U-X)+(ge-X),ge=A[++je]),F=U,K!==0&&(L[Le++]=K);for(;we0:(A[0]-x[0])*(w[1]-x[1])-(w[0]-x[0])*(A[1]-x[1])>0}isAbove(x){return!this.isBelow(x)}isVertical(){return this.point[0]===this.otherEvent.point[0]}get inResult(){return this.resultTransition!==0}clone(){const x=new qz(this.point,this.left,this.otherEvent,this.isSubject,this.type);return x.contourId=this.contourId,x.resultTransition=this.resultTransition,x.prevInResult=this.prevInResult,x.isExteriorRing=this.isExteriorRing,x.inOut=this.inOut,x.otherInOut=this.otherInOut,x}}function m5(k,x){return k[0]===x[0]&&k[1]===x[1]}function VDe(k,x,w){const A=function(L,F,U,K,X,oe){const ge=(F-oe)*(U-X),we=(L-X)*(K-oe),je=ge-we;if(ge===0||we===0||ge>0!=we>0)return je;const Le=Math.abs(ge+we);return Math.abs(je)>=33306690738754716e-32*Le?je:-function(Re,We,et,it,yt,ht,Et){let It,Ot,ws,ds,_s,gs,ys,vn,wn,Pn,On,Ln,Jn,gn,Rn,qn,tr,pr;const na=Re-yt,Cr=et-yt,kr=We-ht,fr=it-ht;gn=na*fr,gs=Vv*na,ys=gs-(gs-na),vn=na-ys,gs=Vv*fr,wn=gs-(gs-fr),Pn=fr-wn,Rn=vn*Pn-(gn-ys*wn-vn*wn-ys*Pn),qn=kr*Cr,gs=Vv*kr,ys=gs-(gs-kr),vn=kr-ys,gs=Vv*Cr,wn=gs-(gs-Cr),Pn=Cr-wn,tr=vn*Pn-(qn-ys*wn-vn*wn-ys*Pn),On=Rn-tr,_s=Rn-On,Uz[0]=Rn-(On+_s)+(_s-tr),Ln=gn+On,_s=Ln-gn,Jn=gn-(Ln-_s)+(On-_s),On=Jn-qn,_s=Jn-On,Uz[1]=Jn-(On+_s)+(_s-qn),pr=Ln+On,_s=pr-Ln,Uz[2]=Ln-(pr-_s)+(On-_s),Uz[3]=pr;let Qr=function(Ko,Bi){let el=Bi[0];for(let lo=1;lo<4;lo++)el+=Bi[lo];return el}(0,Uz),fa=22204460492503146e-32*Et;if(Qr>=fa||-Qr>=fa||(_s=Re-na,It=Re-(na+_s)+(_s-yt),_s=et-Cr,ws=et-(Cr+_s)+(_s-yt),_s=We-kr,Ot=We-(kr+_s)+(_s-ht),_s=it-fr,ds=it-(fr+_s)+(_s-ht),It===0&&Ot===0&&ws===0&&ds===0)||(fa=11093356479670487e-47*Et+Xls*Math.abs(Qr),Qr+=na*ds+fr*It-(kr*ws+Cr*Ot),Qr>=fa||-Qr>=fa))return Qr;gn=It*fr,gs=Vv*It,ys=gs-(gs-It),vn=It-ys,gs=Vv*fr,wn=gs-(gs-fr),Pn=fr-wn,Rn=vn*Pn-(gn-ys*wn-vn*wn-ys*Pn),qn=Ot*Cr,gs=Vv*Ot,ys=gs-(gs-Ot),vn=Ot-ys,gs=Vv*Cr,wn=gs-(gs-Cr),Pn=Cr-wn,tr=vn*Pn-(qn-ys*wn-vn*wn-ys*Pn),On=Rn-tr,_s=Rn-On,q1[0]=Rn-(On+_s)+(_s-tr),Ln=gn+On,_s=Ln-gn,Jn=gn-(Ln-_s)+(On-_s),On=Jn-qn,_s=Jn-On,q1[1]=Jn-(On+_s)+(_s-qn),pr=Ln+On,_s=pr-Ln,q1[2]=Ln-(pr-_s)+(On-_s),q1[3]=pr;const Za=$De(4,Uz,4,q1,Uot);gn=na*ds,gs=Vv*na,ys=gs-(gs-na),vn=na-ys,gs=Vv*ds,wn=gs-(gs-ds),Pn=ds-wn,Rn=vn*Pn-(gn-ys*wn-vn*wn-ys*Pn),qn=kr*ws,gs=Vv*kr,ys=gs-(gs-kr),vn=kr-ys,gs=Vv*ws,wn=gs-(gs-ws),Pn=ws-wn,tr=vn*Pn-(qn-ys*wn-vn*wn-ys*Pn),On=Rn-tr,_s=Rn-On,q1[0]=Rn-(On+_s)+(_s-tr),Ln=gn+On,_s=Ln-gn,Jn=gn-(Ln-_s)+(On-_s),On=Jn-qn,_s=Jn-On,q1[1]=Jn-(On+_s)+(_s-qn),pr=Ln+On,_s=pr-Ln,q1[2]=Ln-(pr-_s)+(On-_s),q1[3]=pr;const Ca=$De(Za,Uot,4,q1,qot);gn=It*ds,gs=Vv*It,ys=gs-(gs-It),vn=It-ys,gs=Vv*ds,wn=gs-(gs-ds),Pn=ds-wn,Rn=vn*Pn-(gn-ys*wn-vn*wn-ys*Pn),qn=Ot*ws,gs=Vv*Ot,ys=gs-(gs-Ot),vn=Ot-ys,gs=Vv*ws,wn=gs-(gs-ws),Pn=ws-wn,tr=vn*Pn-(qn-ys*wn-vn*wn-ys*Pn),On=Rn-tr,_s=Rn-On,q1[0]=Rn-(On+_s)+(_s-tr),Ln=gn+On,_s=Ln-gn,Jn=gn-(Ln-_s)+(On-_s),On=Jn-qn,_s=Jn-On,q1[1]=Jn-(On+_s)+(_s-qn),pr=Ln+On,_s=pr-Ln,q1[2]=Ln-(pr-_s)+(On-_s),q1[3]=pr;const zi=$De(Ca,qot,4,q1,$ot);return $ot[zi-1]}(L,F,U,K,X,oe,Le)}(k[0],k[1],x[0],x[1],w[0],w[1]);return A>0?-1:A<0?1:0}function lT(k,x){const w=k.point,A=x.point;return w[0]>A[0]?1:w[0]A[1]?1:-1:function(L,F,U){return L.left!==F.left?L.left?1:-1:VDe(U,L.otherEvent.point,F.otherEvent.point)!==0?L.isBelow(F.otherEvent.point)?-1:1:!L.isSubject&&F.isSubject?1:-1}(k,x,w)}function cT(k,x,w){const A=new qz(x,!1,k,k.isSubject),L=new qz(x,!0,k.otherEvent,k.isSubject);return m5(k.point,k.otherEvent.point)&&console.warn("what is that, a collapsed segment?",k),A.contourId=L.contourId=k.contourId,lT(L,k.otherEvent)>0&&(k.otherEvent.left=!0,L.left=!1),k.otherEvent.otherEvent=L,k.otherEvent=A,w.push(L),w.push(A),w}function Eie(k,x){return k[0]*x[1]-k[1]*x[0]}function HDe(k,x){return k[0]*x[0]+k[1]*x[1]}function GDe(k,x,w){const A=function(X,oe,ge,we){const je=[oe[0]-X[0],oe[1]-X[1]],Le=[we[0]-ge[0],we[1]-ge[1]];function Re(ws,ds,_s){return[ws[0]+ds*_s[0],ws[1]+ds*_s[1]]}const We=[ge[0]-X[0],ge[1]-X[1]];let et=Eie(je,Le),it=et*et;const yt=HDe(je,je);if(it>0){const ws=Eie(We,Le)/et;if(ws<0||ws>1)return null;const ds=Eie(We,je)/et;return ds<0||ds>1?null:ws===0||ws===1?[Re(X,ws,je)]:ds===0||ds===1?[Re(ge,ds,Le)]:[Re(X,ws,je)]}if(et=Eie(We,je),it=et*et,it>0)return null;const ht=HDe(je,We)/yt,Et=ht+HDe(je,Le)/yt,It=Math.min(ht,Et),Ot=Math.max(ht,Et);return It<=1&&Ot>=0?It===1?[Re(X,It>0?It:0,je)]:Ot===0?[Re(X,Ot<1?Ot:1,je)]:[Re(X,It>0?It:0,je),Re(X,Ot<1?Ot:1,je)]:null}(k.point,k.otherEvent.point,x.point,x.otherEvent.point),L=A?A.length:0;if(L===0||L===1&&(m5(k.point,x.point)||m5(k.otherEvent.point,x.otherEvent.point))||L===2&&k.isSubject===x.isSubject)return 0;if(L===1)return!m5(k.point,A[0])&&!m5(k.otherEvent.point,A[0])&&cT(k,A[0],w),!m5(x.point,A[0])&&!m5(x.otherEvent.point,A[0])&&cT(x,A[0],w),1;const F=[];let U=!1,K=!1;return m5(k.point,x.point)?U=!0:lT(k,x)===1?F.push(x,k):F.push(k,x),m5(k.otherEvent.point,x.otherEvent.point)?K=!0:lT(k.otherEvent,x.otherEvent)===1?F.push(x.otherEvent,k.otherEvent):F.push(k.otherEvent,x.otherEvent),U&&K||U?(x.type=1,k.type=x.inOut===k.inOut?2:3,U&&!K&&cT(F[1].otherEvent,F[0].point,w),2):K?(cT(F[0],F[1].point,w),3):F[0]!==F[3].otherEvent?(cT(F[0],F[1].point,w),cT(F[1],F[2].point,w),3):(cT(F[0],F[1].point,w),cT(F[3].otherEvent,F[2].point,w),3)}function Qls(k,x){if(k===x)return 0;if(VDe(k.point,k.otherEvent.point,x.point)!==0||VDe(k.point,k.otherEvent.point,x.otherEvent.point)!==0)return m5(k.point,x.point)?k.isBelow(x.otherEvent.point)?-1:1:k.point[0]===x.point[0]?k.point[1](x.contourId??0)?1:-1}return lT(k,x)===1?1:-1}class Jls{constructor(){this.points=[],this.holeIds=[],this.holeOf=null,this.depth=null}isExterior(){return this.holeOf==null}}function ecs(k,x,w,A){let L,F=k+1,U=x[k].point;const K=x.length;for(FA;)F--;return F}function tcs(k,x,w){const A=new Jls;if(k.prevInResult!=null){const L=k.prevInResult,F=L.outputContourId;if(L.resultTransition>0){const U=x[F];if(U.holeOf!=null){const K=U.holeOf;x[K].holeIds.push(w),A.holeOf=K,A.depth=x[F].depth}else x[F].holeIds.push(w),A.holeOf=F,A.depth=x[F].depth+1}else A.holeOf=null,A.depth=x[F].depth}else A.holeOf=null,A.depth=0;return A}const Hot=Math.max,Got=Math.min;let Tie=0;function Wot(k,x,w,A,L,F){let U,K,X,oe,ge,we;for(U=0,K=k.length-1;U0?we.left=!0:ge.left=!0;const je=X[0],Le=X[1];L[0]=Got(L[0],je),L[1]=Got(L[1],Le),L[2]=Hot(L[2],je),L[3]=Hot(L[3],Le),A.push(ge),A.push(we)}}const Mie=[];function Kot(k,x,w){let A=k,L=x;typeof k[0][0][0]=="number"&&(A=[k]),typeof x[0][0][0]=="number"&&(L=[x]);let F=function(je,Le,Re){let We=null;return je.length*Le.length===0&&(Re===0?We=Mie:Re===2?We=je:(Re===1||Re===3)&&(We=je.length===0?Le:je)),We}(A,L,w);if(F)return F===Mie?null:F;const U=[1/0,1/0,-1/0,-1/0],K=[1/0,1/0,-1/0,-1/0],X=function(je,Le,Re,We,et){const it=new _m(void 0,lT);let yt,ht,Et,It,Ot,ws;for(Et=0,It=je.length;EtWe[2]||We[0]>Re[2]||Re[1]>We[3]||We[1]>Re[3])&&(et===0?it=Mie:et===2?it=je:(et===1||et===3)&&(it=je.concat(Le))),it}(A,L,U,K,w),F)return F===Mie?null:F;const oe=function(je,Le,Re,We,et,it){const yt=new BDe(Qls),ht=[],Et=Math.min(We[2],et[2]);let It,Ot,ws;for(;je.length!==0;){let ds=je.pop();if(ht.push(ds),it===0&&ds.point[0]>Et||it===2&&ds.point[0]>We[2])break;if(ds.left){Ot=It=yt.insert(ds),ws=yt.minNode(),It=It!==ws?yt.prev(It):null,Ot=yt.next(Ot);const _s=It?It.key:null;let gs;if(qK(ds,_s,it),Ot&&GDe(ds,Ot.key,je)===2&&(qK(ds,_s,it),qK(Ot.key,ds,it)),It&&GDe(It.key,ds,je)===2){let ys=It;ys=ys!==ws?yt.prev(ys):null,gs=ys?ys.key:null,qK(_s,gs,it),qK(ds,_s,it)}}else ds=ds.otherEvent,Ot=It=yt.find(ds),It&&Ot&&(It=It!==ws?yt.prev(It):null,Ot=yt.next(Ot),yt.remove(ds),Ot&&It&&GDe(It.key,Ot.key,je))}return ht}(X,0,0,U,K,w),ge=function(je){let Le,Re;const We=function(yt){let ht,Et,It,Ot,ws;const ds=[];for(Et=0,It=yt.length;Et{et[ws]=!0,ws=We.length)&&We[It];);it.push(ht)}return it}(oe),we=[];for(let je=0;je{U.push(new Js(we,X+(we-K)/(oe-K)*(ge-X)))}:(U,K,X,oe,ge,we)=>{U.push(new Js(K+(we-X)/(ge-X)*(oe-K),we))};for(const U of k){const K=[];for(const X of U){if(X.length<=2)continue;const oe=[];for(let je=0;jex&&F(oe,Le,Re,We,et,x):it>w?yt=x&&F(oe,Le,Re,We,et,x),yt>w&&it<=w&&F(oe,Le,Re,We,et,w)}let ge=X[X.length-1];const we=A===0?ge.x:ge.y;we>=x&&we<=w&&oe.push(ge),oe.length&&(ge=oe[oe.length-1],oe[0].x===ge.x&&oe[0].y===ge.y||oe.push(oe[0]),K.push(oe))}K.length&&L.push(K)}return L}function scs(k,x){const w=Kot(WDe(k),WDe([x]),0);return w==null?[]:Yot(w)}function ncs(k,x,w=0){let L=WDe(k,65536);const F=[];for(;x.valid();x.next()){const[U,K]=x.get();let X=U.x*65536,oe=U.y*65536,ge=K.x*65536,we=K.y*65536;const je=ge-X,Le=we-oe,Re=Math.hypot(je,Le);if(Re===0)continue;X-=je*w,oe-=Le*w,ge+=je*w,we+=Le*w;const We=Math.trunc(Le/Re*3),et=-Math.trunc(je/Re*3);F.push([[[X,oe],[ge,we],[ge+We,we+et],[X+We,oe+et],[X,oe]]])}return F.length>0&&(L=Kot(L,F,2)),Yot(L,1/65536,128)}function WDe(k,x=1){return[k.map(w=>w.map(A=>[A.x*x,A.y*x]))]}function Yot(k,x=1,w){return k.map(A=>A.map((L,F)=>{const U=L.map(K=>{let X=K[0],oe=K[1];return w&&(X=Math.round(X/w)*w,oe=Math.round(oe/w)*w),new Js(X*x,oe*x)._round()});return F>0&&U.reverse(),U}))}class KDe{constructor(x,w){this.layoutVertexArray=new ao,this.indexArray=new Ju,this.lineIndexArray=new Xb,this.triangleSegments=new Rc,this.lineSegments=new Rc,this.programConfigurations=new tt(x.layers,{zoom:x.zoom,lut:x.lut}),this.uploaded=!1,w&&(this.elevatedLayoutVertexArray=new Zl)}update(x,w,A,L,F,U,K,X){this.programConfigurations.updatePaintArrays(x,w,F,A,L,U,K,X)}isEmpty(){return this.layoutVertexArray.length===0}needsUpload(){return this.programConfigurations.needsUpload}upload(x){this.uploaded||(this.layoutVertexBuffer=x.createVertexBuffer(this.layoutVertexArray,Dls.members),this.indexBuffer=x.createIndexBuffer(this.indexArray),this.lineIndexBuffer=x.createIndexBuffer(this.lineIndexArray),this.elevatedLayoutVertexArray&&this.elevatedLayoutVertexArray.length>0&&(this.elevatedLayoutVertexBuffer=x.createVertexBuffer(this.elevatedLayoutVertexArray,Rls.members))),this.programConfigurations.upload(x),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(x,w,A,L,F,U,K){this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,x,w,A,L,F,U,void 0,K)}}class Lie{constructor(x){this.zoom=x.zoom,this.pixelRatio=x.pixelRatio,this.overscaling=x.overscaling,this.layers=x.layers,this.layerIds=this.layers.map(w=>w.fqid),this.index=x.index,this.hasPattern=!1,this.patternFeatures=[],this.lut=x.lut,this.bufferData=new KDe(x,!1),this.elevationBufferData=new KDe(x,!0),this.stateDependentLayerIds=this.layers.filter(w=>w.isStateDependent()).map(w=>w.id),this.projection=x.projection,this.elevationMode=this.layers[0].layout.get("fill-elevation-reference"),this.sourceLayerIndex=x.sourceLayerIndex,this.worldview=x.worldview,this.hasAppearances=null}updateFootprints(x,w){}updateAppearances(x,w,A,L){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(x,w,A,L){this.hasPattern=ODe("fill",this.layers,this.pixelRatio,w);const F=this.layers[0].layout.get("fill-sort-key"),U=[];for(const{feature:K,id:X,index:oe,sourceLayerIndex:ge}of x){const we=this.layers[0]._featureFilter.needGeometry,je=oo(K,we);if(!this.layers[0]._featureFilter.filter(new $i(this.zoom,{worldview:this.worldview,activeFloors:w.activeFloors}),je,A))continue;const Le=F?F.evaluate(je,{},A,w.availableImages):void 0,Re={id:X,properties:K.properties,type:K.type,sourceLayerIndex:ge,index:oe,geometry:we?je.geometry:Qa(K,A,L),patterns:{},sortKey:Le};U.push(Re)}F&&U.sort((K,X)=>K.sortKey-X.sortKey);for(const K of U){const{geometry:X,index:oe,sourceLayerIndex:ge}=K;if(this.hasPattern){const we=zDe("fill",this.layers,K,this.zoom,this.pixelRatio,w);this.patternFeatures.push(we)}else this.addFeature(K,X,oe,A,{},w.availableImages,w.brightness,w.elevationFeatures);w.featureIndex.insert(x[oe].feature,X,oe,ge,this.index)}}update(x,w,A,L,F,U,K){this.bufferData.update(x,w,A,L,F,U,K,this.worldview),this.elevationBufferData.update(x,w,A,L,F,U,K,this.worldview),this.elevatedStructures&&this.elevatedStructures.update(x,w,A,L,F,U,K,this.worldview)}addFeatures(x,w,A,L,F,U){for(const K of this.patternFeatures)this.addFeature(K,K.geometry,K.index,w,A,L,U,x.elevationFeatures)}isEmpty(){return this.bufferData.isEmpty()&&this.elevationBufferData.isEmpty()}uploadPending(){return!this.uploaded||this.bufferData.needsUpload()||this.elevationBufferData.needsUpload()}upload(x){this.bufferData.upload(x),this.elevationBufferData.upload(x),this.elevatedStructures&&this.elevatedStructures.upload(x)}destroy(){this.bufferData.destroy(),this.elevationBufferData.destroy(),this.elevatedStructures&&this.elevatedStructures.destroy()}addFeature(x,w,A,L,F,U=[],K,X){const oe=BK(w,500);this.elevationMode!=="none"?this.addElevatedRoadFeature(x,oe,L,A,X):this.addGeometry(oe,this.bufferData),this.bufferData.populatePaintArrays(x,A,F,U,L,K,this.worldview),this.elevationBufferData.populatePaintArrays(x,A,F,U,L,K,this.worldview)}getUnevaluatedPortalGraph(){return this.elevatedStructures?this.elevatedStructures.unevaluatedPortals:void 0}setEvaluatedPortalGraph(x,w,A,L,F){this.elevatedStructures&&(this.elevatedStructures.construct(x),this.elevatedStructures.populatePaintArrays(w,A,L,F,this.worldview))}addElevatedRoadFeature(x,w,A,L,F){const U=new Array,K=Wc.getElevationFeature(x,F);if(!K)return void this.addGeometry(w,this.bufferData);{const oe=this.clipPolygonsToTile(w,1);oe.length>0&&U.push({polygons:oe,elevationFeature:K,elevationTileID:A})}const X={guardRailEnabled:this.layers[0].layout.get("fill-construct-bridge-guard-rail").evaluate(x,{},A),featureIndex:L};for(const oe of U)if(oe.elevationFeature){if(this.elevationMode==="hd-road-base"){this.elevatedStructures||(this.elevatedStructures=new U1(oe.elevationTileID,this.layers,this.zoom,this.lut));const we=oe.elevationFeature.isTunnel();let je=0;x.properties.hasOwnProperty(Oc)&&(je=+x.properties[Oc]),this.elevatedStructures.addPortalCandidates(oe.elevationFeature.id,oe.polygons,we,oe.elevationFeature,je)}oe.elevationFeature.constantHeight==null&&(oe.polygons=this.prepareElevatedPolygons(oe.polygons,oe.elevationFeature,oe.elevationTileID));const ge=new rd(A,oe.elevationTileID);this.addElevatedGeometry(oe.polygons,ge,oe.elevationFeature,this.elevationMode==="hd-road-base"?0:.05,L,X)}}addElevatedGeometry(x,w,A,L,F,U){const K={elevation:A,elevationSampler:w,bias:L,index:F,featureInfo:U},[X,oe]=this.addGeometry(x,this.elevationBufferData,K);this.elevationBufferData.heightRange==null?this.elevationBufferData.heightRange={min:X,max:oe}:(this.elevationBufferData.heightRange.min=Math.min(this.elevationBufferData.heightRange.min,X),this.elevationBufferData.heightRange.max=Math.max(this.elevationBufferData.heightRange.max,oe))}addGeometry(x,w,A){let L=Number.POSITIVE_INFINITY,F=Number.NEGATIVE_INFINITY,U=null;A&&(U=A.elevationSampler.constantElevation(A.elevation,A.bias),U!=null&&(L=U,F=U));const K=(X,oe,ge)=>{if(A!=null)if(oe.push(X),U!=null)w.elevatedLayoutVertexArray.emplaceBack(U),ge.push(U);else{const we=A.elevationSampler.pointElevation(X,A.elevation,A.bias);w.elevatedLayoutVertexArray.emplaceBack(we),ge.push(we),L=Math.min(L,we),F=Math.max(F,we)}};for(const X of x){let oe=0;for(const ht of X)oe+=ht.length;const ge=w.triangleSegments.prepareSegment(oe,w.layoutVertexArray,w.indexArray),we=ge.vertexLength,je=[],Le=[],Re=[],We=[],et=[],it=w.layoutVertexArray.length;for(const ht of X){if(ht.length===0)continue;ht!==X[0]&&Le.push(je.length/2);const Et=w.lineSegments.prepareSegment(ht.length,w.layoutVertexArray,w.lineIndexArray),It=Et.vertexLength;A&&et.push(w.layoutVertexArray.length-it),K(ht[0],Re,We),w.layoutVertexArray.emplaceBack(ht[0].x,ht[0].y),w.lineIndexArray.emplaceBack(It+ht.length-1,It),je.push(ht[0].x),je.push(ht[0].y);for(let Ot=1;Ot0&&A&&this.elevationMode==="hd-road-base"){const ht=A.elevation.isTunnel(),Et=A.elevation.safeArea,It=this.elevatedStructures.addVertices(Re,We);this.elevatedStructures.addTriangles(yt,It,ht);const Ot=et.length;if(Ot>0){for(let ws=0;ws=A&&Le.max.x<=F&&Le.min.y>=L&&Le.max.y<=U?X:oe).push(je)}if(X.length===x.length)return x;const ge=[new Js(A,L),new Js(F,L),new Js(F,U),new Js(A,U),new Js(A,L)],we=X;for(const je of oe)we.push(...scs(je,ge));return we}}let Zot,Xot,Qot,Jot;jr(Lie,"FillBucket",{omit:["layers","patternFeatures"]}),jr(KDe,"FillBufferData"),jr(U1,"ElevatedStructures");class Iie{constructor(x,w,A,L){if(this.triangleCount=w.length/3,this.min=new Js(0,0),this.max=new Js(0,0),this.xScale=0,this.yScale=0,this.cellsX=0,this.cellsY=0,this.cells=[],this.payload=[],this.triangleCount===0||x.length===0)return;const[F,U]=[x[0].clone(),x[0].clone()];for(let we=1;wewe.cellIdx-je.cellIdx||we.triIdx-je.triIdx);let ge=0;for(;gethis.max.x||this.min.x>x.x||x.y>this.max.y||this.min.y>x.y)return;const A=p5(x.x-this.min.x,this.xScale,this.cellsX),L=p5(x.y-this.min.y,this.yScale,this.cellsY),F=this.cells[L*this.cellsX+A];if(F){this._lazyInitLookup();for(let U=0;Uthis.max.x||this.min.x>w.x||x.y>this.max.y||this.min.y>w.y)return;this._lazyInitLookup();const L=p5(x.x-this.min.x,this.xScale,this.cellsX),F=p5(w.x-this.min.x,this.xScale,this.cellsX),U=p5(x.y-this.min.y,this.yScale,this.cellsY),K=p5(w.y-this.min.y,this.yScale,this.cellsY);for(let X=U;X<=K;X++)for(let oe=L;oe<=F;oe++){const ge=this.cells[X*this.cellsX+oe];if(ge)for(let we=0;wew.fqid),this.index=x.index,this.hasPattern=!1,this.stateDependentLayerIds=this.layers.filter(w=>w.isStateDependent()).map(w=>w.id),this.footprints=[],this.worldview=x.worldview,this.hasAppearances=null}updateFootprints(x,w){for(const A of this.footprints)w.push({footprint:A,id:x})}updateAppearances(x,w,A,L){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(x,w,A,L){const F=[];for(const{feature:U,id:K,index:X,sourceLayerIndex:oe}of x){const ge=this.layers[0]._featureFilter.needGeometry,we=oo(U,ge);if(!this.layers[0]._featureFilter.filter(new $i(this.zoom,{worldview:this.worldview,activeFloors:w.activeFloors}),we,A))continue;const je={id:K,properties:U.properties,type:U.type,sourceLayerIndex:oe,index:X,geometry:ge?we.geometry:Qa(U,A,L),patterns:{}};F.push(je)}for(const U of F){const{geometry:K,index:X,sourceLayerIndex:oe}=U;this.addFeature(U,K,X,A,{},w.availableImages,w.brightness),w.featureIndex.insert(x[X].feature,K,X,oe,this.index)}}isEmpty(){return this.footprints.length===0}uploadPending(){return!1}upload(x){}update(x,w,A,L,F,U,K){}destroy(){}addFeature(x,w,A,L,F,U=[],K){for(const X of BK(w,2)){const oe=[],ge=[],we=[],je=new Js(1/0,1/0),Le=new Js(-1/0,-1/0);for(const et of X)if(et.length!==0){et!==X[0]&&we.push(ge.length/2);for(let it=0;itx.max.x||k.max.xx.max.y||k.max.ynew Js((X.x+F.x*ur)*K-U.x*ur,(X.y+F.y*ur)*K-U.y*ur))}return ZDe(w,L,k.indices,0,k.indices.length,0,0)}function alt(k,x,w,A){const L=Math.pow(2,A.z-w.z);return new Js((k+w.x*ur)*L-A.x*ur,(x+w.y*ur)*L-A.y*ur)}function ilt(k,x){const w=[];x.grid.queryPoint(k,w);const A=x.indices,L=x.vertices;for(let F=0;F0&&(A.length>1&&w.push(A),A=[])}return A.length>1&&w.push(A),w}const QDe=Ni.types,pcs=["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"],fcs=["fill-extrusion-flood-light-ground-radius"],xcs=Math.pow(2,13),gcs=Math.pow(2,15)-1,Oie=new Js(0,1),i3=2147483648,zie=1073741824;function VK(k,x,w,A,L,F,U,K){k.emplaceBack((x<<1)+U,(w<<1)+F,(Math.floor(A*xcs)<<1)+L,Math.round(K))}function HK(k,x,w){k.emplaceBack(x.x*ur,x.y*ur,w?1:0)}function Bie(k,x,w,A,L,F){k.emplaceBack(x.x,x.y,(w.x<<1)+A,(w.y<<1)+L,F)}function GK(k,x,w){k.emplaceBack(x.x,x.y,x.z,w[0]*16384,w[1]*16384,w[2]*16384)}class llt{constructor(){this.vertexOffset=0,this.vertexCount=0,this.indexOffset=0,this.indexCount=0}}class JDe{constructor(){this.centroidXY=new Js(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 Js(Number.MAX_VALUE,Number.MAX_VALUE),this.max=new Js(-Number.MAX_VALUE,-Number.MAX_VALUE),this.height=0,this.buildingId=0,this.groupCentroidPos=new Js(0,0)}span(){return new Js(this.max.x-this.min.x,this.max.y-this.min.y)}}class eRe{constructor(){this.acc=new Js(0,0),this.accCount=0,this.centroidDataIndex=0}startRing(x,w){x.min.x===Number.MAX_VALUE&&(x.min.x=x.max.x=w.x,x.min.y=x.max.y=w.y)}appendEdge(x,w,A){this.accCount++,this.acc._add(w);let L=!!this.borders;w.xx.max.x&&(x.max.x=w.x,L=!0),w.yx.max.y&&(x.max.y=w.y,L=!0),((w.x===0||w.x===ur)&&w.x===A.x)!=((w.y===0||w.y===ur)&&w.y===A.y)&&this.processBorderOverlap(w,A),L&&this.checkBorderIntersection(w,A)}checkBorderIntersection(x,w){w.x<0!=x.x<0&&this.addBorderIntersection(0,Ar(w.y,x.y,(0-w.x)/(x.x-w.x))),w.x>ur!=x.x>ur&&this.addBorderIntersection(1,Ar(w.y,x.y,(ur-w.x)/(x.x-w.x))),w.y<0!=x.y<0&&this.addBorderIntersection(2,Ar(w.x,x.x,(0-w.y)/(x.y-w.y))),w.y>ur!=x.y>ur&&this.addBorderIntersection(3,Ar(w.x,x.x,(ur-w.y)/(x.y-w.y)))}addBorderIntersection(x,w){this.borders||(this.borders=[[Number.MAX_VALUE,-Number.MAX_VALUE],[Number.MAX_VALUE,-Number.MAX_VALUE],[Number.MAX_VALUE,-Number.MAX_VALUE],[Number.MAX_VALUE,-Number.MAX_VALUE]]);const A=this.borders[x];wA[1]&&(A[1]=w)}processBorderOverlap(x,w){if(x.x===w.x){if(x.y===w.y)return;const A=x.x===0?0:1;this.addBorderIntersection(A,w.y),this.addBorderIntersection(A,x.y)}else{const A=x.y===0?2:3;this.addBorderIntersection(A,w.x),this.addBorderIntersection(A,x.x)}}centroid(){return this.accCount===0?new Js(0,0):new Js(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((x,w)=>x+ +(w[0]!==Number.MAX_VALUE),0):0}}function clt(k,x){const w=k.add(x)._unit(),A=pt(k.x*w.x+k.y*w.y,-1,1);var L,F,U;return U=Math.acos(A),Math.min(4,Math.max(-4,Math.tan(U)))/4*gcs*((L=k).x*(F=x).y-L.y*F.x<0?-1:1)}const ycs=[k=>k.x<0,k=>k.x>ur,k=>k.y<0,k=>k.y>ur];function vcs(k,x,w,A){const L=[4];if(A===0)return L;w._mult(A);const F=k.sub(w),U=x.sub(w),K=[k,x,F,U];for(let X=0;X<4;X++)for(const oe of K)if(ycs[X](oe)){L.push(X);break}return L}class tRe{constructor(x){this.groundRadiusArray=null,this.groundRadiusBuffer=null,this.vertexArray=new GL,this.indexArray=new Ju,this.programConfigurations=new tt(x.layers,{zoom:x.zoom,lut:x.lut},w=>fcs.includes(w)),this._segments=new Rc,this.hiddenByLandmarkVertexArray=new Iz,this._segmentToGroundQuads={},this._segmentToGroundQuads[0]=[],this._segmentToRegionTriCounts={},this._segmentToRegionTriCounts[0]=[0,0,0,0,0],this.regionSegments={},this.regionSegments[4]=new Rc}getDefaultSegment(){return this.regionSegments[4]}hasData(){return this.vertexArray.length!==0}addData(x,w,A,L=!1){const F=x.length;if(F>2){let U=Math.max(0,this._segments.get().length-1);const K=this._segments._prepareSegment(4*F,this.vertexArray.length,2*this._segmentToGroundQuads[U].length);let X;U!==this._segments.get().length-1&&(U++,this._segmentToGroundQuads[U]=[],this._segmentToRegionTriCounts[U]=[0,0,0,0,0]);{const oe=x[0],ge=x[1];X=clt(oe.sub(x[F-1])._perp()._unit(),ge.sub(oe)._perp()._unit())}for(let oe=0;oeL.region-F.region);for(let A=0;AX+oe,0);let K=0;for(let X=0;X<=4;X++){const oe=U[X];if(oe!==0){let ge=this.regionSegments[X];ge||(ge=this.regionSegments[X]=new Rc);const we={vertexOffset:F.vertexOffset,primitiveOffset:F.primitiveOffset+K,vertexLength:F.vertexLength,primitiveLength:oe};ge.get().push(we)}K+=oe}for(let X=0;X0?this.hiddenByLandmarkVertexBuffer=x.createVertexBuffer(this.hiddenByLandmarkVertexArray,ccs.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 x=0;x<=4;x++){const w=this.regionSegments[x];w&&w.destroy()}}}}class Uie{constructor(x){this.zoom=x.zoom,this.canonical=x.canonical,this.overscaling=x.overscaling,this.layers=x.layers,this.pixelRatio=x.pixelRatio,this.layerIds=this.layers.map(w=>w.fqid),this.index=x.index,this.hasPattern=!1,this.edgeRadius=0,this.projection=x.projection,this.activeReplacements=[],this.replacementUpdateTime=0,this.centroidData=[],this.footprintIndices=new Ju,this.footprintVertices=new ao,this.footprintSegments=[],this.layoutVertexArray=new Yb,this.centroidVertexArray=new bie,this.wallVertexArray=new TK,this.indexArray=new Ju,this.programConfigurations=new tt(x.layers,{zoom:x.zoom,lut:x.lut},w=>pcs.includes(w)),this.segments=new Rc,this.stateDependentLayerIds=this.layers.filter(w=>w.isStateDependent()).map(w=>w.id),this.groundEffect=new tRe(x),this.maxHeight=0,this.partLookup={},this.triangleSubSegments=[],this.polygonSegments=[],this.buildingGroups=new Map,this.worldview=x.worldview,this.hasAppearances=null}updateFootprints(x,w){}updateAppearances(x,w,A,L){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(x,w,A,L){this.features=[],this.hasPattern=ODe("fill-extrusion",this.layers,this.pixelRatio,w),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=Gn(A),this.edgeRadius=this.layers[0].layout.get("fill-extrusion-edge-radius")/this.tileToMeter,this.wallMode=this.layers[0].paint.get("fill-extrusion-line-width").constantOr(1)!==0;for(const{feature:F,id:U,index:K,sourceLayerIndex:X}of x){const oe=this.layers[0]._featureFilter.needGeometry,ge=oo(F,oe);if(!this.layers[0]._featureFilter.filter(new $i(this.zoom,{worldview:this.worldview,activeFloors:w.activeFloors}),ge,A))continue;const we={id:U,sourceLayerIndex:X,index:K,geometry:oe?ge.geometry:Qa(F,A,L),properties:F.properties,type:F.type,patterns:{}},je=this.layoutVertexArray.length,Le=QDe[we.type]==="Polygon";if(this.hasPattern)this.features.push({featureId:F.id,feature:zDe("fill-extrusion",this.layers,we,this.zoom,this.pixelRatio,w)});else if(this.wallMode)for(const Re of we.geometry)for(const We of olt(Re,Le))this.addFeature(F.id,we,[We],K,A,{},w.availableImages,L,w.brightness);else this.addFeature(F.id,we,we.geometry,K,A,{},w.availableImages,L,w.brightness);w.featureIndex.insert(F,we.geometry,K,X,this.index,je)}this._finalizeBuildingGroups(),this.sortBorders(),this.projection.name==="mercator"&&this.splitToSubtiles(),this.groundEffect.prepareBorderSegments(),this.polygonSegments.length=0}addFeatures(x,w,A,L,F,U){for(const{featureId:K,feature:X}of this.features){const oe=QDe[X.type]==="Polygon",{geometry:ge}=X;if(this.wallMode)for(const we of ge)for(const je of olt(we,oe))this.addFeature(K,X,[je],X.index,w,A,L,F,U);else this.addFeature(K,X,ge,X.index,w,A,L,F,U)}this._finalizeBuildingGroups(),this.sortBorders(),this.projection.name==="mercator"&&this.splitToSubtiles()}update(x,w,A,L,F,U,K){this.programConfigurations.updatePaintArrays(x,w,F,A,L,U,K,this.worldview),this.groundEffect.update(x,w,F,A,L,U,K,this.worldview)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload||this.groundEffect.programConfigurations.needsUpload}upload(x){this.uploaded||(this.layoutVertexBuffer=x.createVertexBuffer(this.layoutVertexArray,ucs),this.indexBuffer=x.createIndexBuffer(this.indexArray),this.wallVertexBuffer=x.createVertexBuffer(this.wallVertexArray,lcs.members),this.layoutVertexExtArray&&(this.layoutVertexExtBuffer=x.createVertexBuffer(this.layoutVertexExtArray,dcs.members,!0)),this.groundEffect.upload(x)),this.groundEffect.uploadPaintProperties(x),this.programConfigurations.upload(x),this.uploaded=!0}uploadCentroid(x){this.groundEffect.uploadHiddenByLandmark(x),this.needsCentroidUpdate&&(!this.centroidVertexBuffer&&this.centroidVertexArray.length>0?this.centroidVertexBuffer=x.createVertexBuffer(this.centroidVertexArray,ocs.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(x,w,A,L,F,U,K,X,oe){const ge=this.layers[0].paint.get("fill-extrusion-flood-light-ground-radius").evaluate(w,{})/this.tileToMeter,we=[new Js(0,0),new Js(ur,ur)],je=X.projection,Le=je.name==="globe",Re=this.wallMode||QDe[w.type]==="Polygon",We=new eRe;We.centroidDataIndex=this.centroidData.length;const et=new JDe;et.buildingId=x,w.properties&&w.properties.hasOwnProperty("building_id")&&(et.buildingId=Number(w.properties.building_id)),We.buildingId=et.buildingId;const it=this.layers[0].paint.get("fill-extrusion-base").evaluate(w,{},F)<=0,yt=this.layers[0].paint.get("fill-extrusion-height").evaluate(w,{},F);let ht;if(et.height=yt,et.vertexArrayOffset=this.layoutVertexArray.length,et.groundVertexArrayOffset=this.groundEffect.vertexArray.length,Le&&!this.layoutVertexExtArray&&(this.layoutVertexExtArray=new Az),this.wallMode){if(Le)return void Br("Non zero fill-extrusion-line-width is not yet supported on globe.");if(A.length!==1)return;ht=function(gs){const ys=gs[0].x===gs[gs.length-1].x&&gs[0].y===gs[gs.length-1].y;(function(kr){let fr=0;const Qr=kr.length;for(let fa=0;fa=0})(gs)||(gs=gs.reverse());const wn={geometry:[],joinNormals:[],indices:[]},Pn=[],On=[],Ln=[];let Jn=gs.length;for(;Jn>=2&&gs[Jn-1].equals(gs[Jn-2]);)Jn--;if(Jn<(ys?3:2))return wn;let gn,Rn,qn,tr,pr,na=0;for(;na0;let Ca="miter";const zi=2;Ca==="miter"&&fa>zi&&(Ca="bevel"),Ca==="bevel"&&(fa>100&&(Ca="flipbevel"),fa{const Il=new Js(Bi.x,Bi.y),ll=new Js(Bi.x,Bi.y);Il.x+=el.x*Mu,Il.y+=el.y*Mu,ll.x-=el.x*Math.max(lo,1),ll.y-=el.y*Math.max(lo,1),Ln.push(el),Pn.push(Il),On.push(ll)};if(Ca==="miter")fr._mult(fa),Ko(gn,fr,0,0);else if(Ca==="flipbevel")fr=pr.mult(-1),Ko(gn,fr,0,0),Ko(gn,fr.mult(-1),0,0);else{const Bi=-Math.sqrt(fa*fa-1),el=Za?Bi:0,lo=Za?0:Bi;Rn&&Ko(gn,tr,el,lo),qn&&Ko(gn,pr,el,lo)}}wn.geometry=[...Pn,...On.reverse(),Pn[0]],wn.joinNormals=[...Ln,...Ln.reverse(),Ln[Ln.length-1]];const Cr=wn.geometry.length-1;for(let kr=0;krgs<(ys.length-1)/2||gs===ys.length-1,It=this.wallMode?[A]:BK(A,500);for(let gs=It.length-1;gs>=0;gs--){const ys=It[gs];(ys.length===0||_cs(ys[0]))&&It.splice(gs,1)}let Ot;if(Le)Ot=xlt(It,we,F);else{Ot=[];for(const gs of It)Ot.push({polygon:gs,bounds:we})}const ws=Re?this.edgeRadius:0,ds=ws>0&&this.zoom<17,_s=(gs,ys)=>{if(gs.length===0)return!1;const vn=gs[gs.length-1];return ys.x===vn.x&&ys.y===vn.y};for(const{polygon:gs,bounds:ys}of Ot){let vn=0,wn=0;for(const Jn of gs)Re&&!Jn[0].equals(Jn[Jn.length-1])&&Jn.push(Jn[0]),wn+=Re?Jn.length-1:Jn.length;const Pn=this.segments.prepareSegment((Re?5:4)*wn,this.layoutVertexArray,this.indexArray);et.footprintSegIdx<0&&(et.footprintSegIdx=this.footprintSegments.length),et.polygonSegIdx<0&&(et.polygonSegIdx=this.polygonSegments.length);const On={triangleArrayOffset:this.indexArray.length,triangleCount:0,triangleSegIdx:this.segments.segments.length-1},Ln=new llt;if(Ln.vertexOffset=this.footprintVertices.length,Ln.indexOffset=3*this.footprintIndices.length,Ln.ringIndices=[],Re){const Jn=[],gn=[];vn=Pn.vertexLength;for(let qn=0;qn4&&mlt(gn[gn.length-2],gn[0],gn[1]),qn=ws?bcs(gn[gn.length-2],gn[0],gn[1],ws):0;const tr=[];let pr,na,Cr;na=gn[1].sub(gn[0])._perp()._unit();let kr=!0;for(let fr=1,Qr=0;fr0?1:0,el=fa.dist(Za);if(Qr+el>32768&&(Qr=0),ws){Cr=Ca.sub(Za)._perp()._unit();let ll=ult(fa,Za,Ca,dlt(na,Cr),ws);isNaN(ll)&&(ll=0);const zc=Za.sub(fa)._unit();fa=fa.add(zc.mult(qn))._round(),Za=Za.add(zc.mult(-ll))._round(),qn=ll,na=Cr,it&&this.zoom>=17&&(_s(tr,fa)||tr.push(fa),_s(tr,Za)||tr.push(Za))}const lo=Pn.vertexLength,Mu=gn.length>4&&mlt(fa,Za,Ca);let Il=plt(Qr,Rn,kr);if(VK(this.layoutVertexArray,fa.x,fa.y,Ko,Bi,0,0,Il),VK(this.layoutVertexArray,fa.x,fa.y,Ko,Bi,0,1,Il),this.wallMode){const ll=Et(fr-1,gn),zc=ht.joinNormals[fr-1];HK(this.wallVertexArray,zc,ll),HK(this.wallVertexArray,zc,ll)}if(Qr+=el,Il=plt(Qr,Mu,!kr),Rn=Mu,VK(this.layoutVertexArray,Za.x,Za.y,Ko,Bi,0,0,Il),VK(this.layoutVertexArray,Za.x,Za.y,Ko,Bi,0,1,Il),this.wallMode){const ll=Et(fr,gn),zc=ht.joinNormals[fr];HK(this.wallVertexArray,zc,ll),HK(this.wallVertexArray,zc,ll)}if(Pn.vertexLength+=4,this.indexArray.emplaceBack(lo+0,lo+1,lo+2),this.indexArray.emplaceBack(lo+1,lo+3,lo+2),Pn.primitiveLength+=2,ws){const ll=vn+(fr===1?gn.length-2:fr-2),zc=fr===1?vn:ll+1;if(this.indexArray.emplaceBack(lo+1,ll,lo+3),this.indexArray.emplaceBack(ll,zc,lo+3),Pn.primitiveLength+=2,pr===void 0&&(pr=lo),!sRe(Ca,gn[fr],ys)){const wu=fr===gn.length-1?pr:Pn.vertexLength;this.indexArray.emplaceBack(lo+2,lo+3,wu),this.indexArray.emplaceBack(lo+3,wu+1,wu),this.indexArray.emplaceBack(lo+3,zc,wu+1),Pn.primitiveLength+=3}kr=!kr}if(Le){const ll=this.layoutVertexExtArray,zc=je.projectTilePoint(fa.x,fa.y,F),wu=je.projectTilePoint(Za.x,Za.y,F),Up=je.upVector(F,fa.x,fa.y),ju=je.upVector(F,Za.x,Za.y);GK(ll,zc,Up),GK(ll,zc,Up),GK(ll,wu,ju),GK(ll,wu,ju)}}Re&&(vn+=gn.length-1),it&&ws&&this.zoom>=17&&(tr.length!==0&&_s(tr,tr[0])&&tr.pop(),this.groundEffect.addData(tr,ys,ge,ws>0))}this.footprintSegments.push(Ln),On.triangleCount=this.indexArray.length-On.triangleArrayOffset,this.polygonSegments.push(On),++et.footprintSegLen,++et.polygonSegLen}if(et.vertexCount=this.layoutVertexArray.length-et.vertexArrayOffset,et.groundVertexCount=this.groundEffect.vertexArray.length-et.groundVertexArrayOffset,et.vertexCount!==0){if(et.centroidXY=We.borders?Oie:this.encodeCentroid(We,et),w.properties&&w.properties.hasOwnProperty("building_id")){const gs=et.buildingId;let ys=this.buildingGroups.get(gs);ys||(ys={accX:0,accY:0,accCount:0,mergedMin:new Js(Number.MAX_VALUE,Number.MAX_VALUE),mergedMax:new Js(-Number.MAX_VALUE,-Number.MAX_VALUE),partIndices:[]},this.buildingGroups.set(gs,ys)),ys.accX+=We.acc.x,ys.accY+=We.acc.y,ys.accCount+=We.accCount,ys.mergedMin.x=Math.min(ys.mergedMin.x,et.min.x),ys.mergedMin.y=Math.min(ys.mergedMin.y,et.min.y),ys.mergedMax.x=Math.max(ys.mergedMax.x,et.max.x),ys.mergedMax.y=Math.max(ys.mergedMax.y,et.max.y),ys.partIndices.push(this.centroidData.length)}if(this.centroidData.push(et),We.borders){this.featuresOnBorder.push(We);const gs=this.featuresOnBorder.length-1;for(let ys=0;ysthis.featuresOnBorder[w].borders[x][0]-this.featuresOnBorder[A].borders[x][0])}splitToSubtiles(){const x=[];for(let K=0;Kur),ge=2*oe+(+(X.min.x+X.max.x>ur)^oe);for(let we=0;weK.triangleSegmentIdx===X.triangleSegmentIdx?K.subtile-X.subtile:K.triangleSegmentIdx-X.triangleSegmentIdx);let A=0,L=0,F=0;for(const K of x){if(K.triangleSegmentIdx!==A)break;F++}const U=x.length;for(;L!==x.length;){A=x[L].triangleSegmentIdx;let K=0,X=L,oe=L;for(let ge=X;ge0&&this.triangleSubSegments.push({segment:Le,min:we,max:je}),X=oe;for(let Re=X;Re[We[0]*(1-it[0])+et[0]*it[0],We[1]*(1-it[1])+et[1]*it[1]],Le=[],Re=[];for(const We of this.triangleSubSegments){Le[0]=We.min.x/ur,Le[1]=We.min.y/ur,Re[0]=We.max.x/ur,Re[1]=We.max.y/ur;const et=je(ge,we,Le),it=je(ge,we,Re);if(new Hl([et[0],et[1],F],[it[0],it[1],U]).intersectsPrecise(A)===0){oe&&(L.segments.push(oe),oe=void 0);continue}const yt=We.segment;oe&&oe.vertexOffset!==yt.vertexOffset&&(L.segments.push(oe),oe=void 0),oe?(oe.vertexLength+=yt.vertexLength,oe.primitiveLength+=yt.primitiveLength):oe={vertexOffset:yt.vertexOffset,primitiveLength:yt.primitiveLength,vertexLength:yt.vertexLength,primitiveOffset:yt.primitiveOffset,sortKey:void 0,vaos:{}}}return oe&&L.segments.push(oe),L}encodeCentroid(x,w){const A=x.centroid(),L=w.span(),F=Math.min(7,Math.round(L.x*this.tileToMeter/10)),U=Math.min(6,Math.round(L.y*this.tileToMeter/10));return new Js(pt(A.x,1,8191)<<3|F,pt(A.y,1,8191)<<3|U)}encodeBorderCentroid(x){if(!x.borders)return new Js(0,0);const w=x.borders,A=Number.MAX_VALUE;if(w[0][0]!==A||w[1][0]!==A){const L=w[0][0]!==A?0:1;return new Js(6|(w[0][0]!==A?0:65528),(w[L][0]+w[L][1])/2<<3|6)}{const L=w[2][0]!==A?2:3;return new Js((w[L][0]+w[L][1])/2<<3|6,6|(w[2][0]!==A?0:65528))}}showCentroid(x){const w=this.centroidData[x.centroidDataIndex];if(w.flags&=i3,w.groupCentroidPos.x!==0||w.groupCentroidPos.y!==0){const A=w.span(),L=Math.min(7,Math.round(A.x*this.tileToMeter/10)),F=Math.min(6,Math.round(A.y*this.tileToMeter/10));w.centroidXY=new Js(pt(w.groupCentroidPos.x,1,8191)<<3|L,pt(w.groupCentroidPos.y,1,8191)<<3|F)}else w.centroidXY=new Js(0,0);this.writeCentroidToBuffer(w)}writeCentroidToBuffer(x){this.groundEffect.updateHiddenByLandmark(x);const w=x.vertexArrayOffset,A=x.vertexCount+x.vertexArrayOffset,L=-1073741824&x.flags?Oie:x.centroidXY,F=this.centroidVertexArray.geta_centroid_pos0(w);if(this.centroidVertexArray.geta_centroid_pos1(w)!==L.y||F!==L.x){for(let U=w;UX.max.x||X.min.x>U.max.x||U.min.y>X.max.y||X.min.y>U.max.y||U.footprint.buildingIds.has(X.buildingId)&&(X.flags|=U.clipMask!==Fie.None?-1073741824:i3);else for(const X of this.centroidData)if(!(X.flags&i3||X.flags&zie||U.min.x>X.max.x||X.min.x>U.max.x||U.min.y>X.max.y||X.min.y>U.max.y))for(let oe=0;oew!=Le>w&&x<(this.footprintVertices.int16[2*(ge+U.vertexOffset)+0]-we)*(w-je)/(Le-je)+we&&(L=!L)}K=X}}return L}getHeightAtTileCoord(x,w){let A=Number.NEGATIVE_INFINITY,L=!0;const F=4*(x+ur)*ur+(w+ur);if(this.partLookup.hasOwnProperty(F)){const U=this.partLookup[F];return U?{height:U.height,hidden:!!(U.flags&i3)}:void 0}for(const U of this.centroidData)x>U.max.x||U.min.x>x||w>U.max.y||U.min.y>w||U.height<=A||this.footprintContainsPoint(x,w,U)&&(A=U.height,this.partLookup[F]=U,L=!!(U.flags&i3));if(A!==Number.NEGATIVE_INFINITY)return{height:A,hidden:L};this.partLookup[F]=void 0}}function dlt(k,x){const w=k.add(x)._unit();return k.x*w.x+k.y*w.y}function bcs(k,x,w,A){const L=x.sub(k)._perp()._unit(),F=w.sub(x)._perp()._unit();return ult(k,x,w,dlt(L,F),A)}function ult(k,x,w,A,L){const F=Math.sqrt(1-A*A);return Math.min(k.dist(x)/3,x.dist(w)/3,L*F/A)}function sRe(k,x,w){return k.xw[1].x&&x.x>w[1].x||k.yw[1].y&&x.y>w[1].y}function hlt(k,x){return k.xx[1].x||k.yx[1].y}function _cs(k){return k.every(x=>x.x<=0)||k.every(x=>x.x>=ur)||k.every(x=>x.y<=0)||k.every(x=>x.y>=ur)}function mlt(k,x,w){if(k.x<0||k.x>=ur||x.x<0||x.x>=ur||w.x<0||w.x>=ur)return!1;const A=w.sub(x),L=A.perp(),F=k.sub(x);return(A.x*F.x+A.y*F.y)/Math.sqrt((A.x*A.x+A.y*A.y)*(F.x*F.x+F.y*F.y))>-.866&&L.x*F.x+L.y*F.y<0}function plt(k,x,w){const A=x?2|k:-3&k;return w?1|A:-2&A}function flt(){const k=Math.PI/32,x=Math.tan(k),w=bs;return w*Math.sqrt(1+2*x*x)-w}function xlt(k,x,w){const A=1<{for(const ds of Ot)Re.push({polygon:ds,bounds:ws})},et=Math.ceil(Math.log2(ge)),it=Math.ceil(Math.log2(we)),yt=et-it,ht=[];for(let Ot=0;Ot0?0:1);for(let Ot=0;Otws+1?It.push({polygons:Pn,bounds:Ln,depth:ws+1}):We(Pn,Ln)}if(On.length){const Ln=[new Js(ds===0?wn:_s.x,ds===1?wn:_s.y),gs];ht.length>ws+1?It.push({polygons:On,bounds:Ln,depth:ws+1}):We(On,Ln)}}return Re}(k,x,Math.ceil((F-L)/11.25),Math.ceil((U-K)/11.25),1,(X,oe,ge)=>{if(X===0)return .5*(oe+ge);{const we=yn((w.y+oe/ur)/A);return(Kn(.5*(yn((w.y+ge/ur)/A)+we))*A-w.y)*ur}})}function wcs(k,x,w,A,L,F){const U=Math.pow(2,A.z-L.z);for(let K=0;K=X[U]&&(K=x,X=k),K[U]L&&blt(K,X,U,L),K[U]F&&blt(X,K,U,F)}}function qie(k,x,w,A,L,F){const U=[];for(let K=0;K=A&&Re.x>=A||(Le.x>=A?Le=new Js(A,Le.y+(A-Le.x)/(Re.x-Le.x)*(Re.y-Le.y))._round():Re.x>=A&&(Re=new Js(A,Le.y+(A-Le.x)/(Re.x-Le.x)*(Re.y-Le.y))._round()),Le.y>=L&&Re.y>=L||(Le.y>=L?Le=new Js(Le.x+(L-Le.y)/(Re.y-Le.y)*(Re.x-Le.x),L)._round():Re.y>=L&&(Re=new Js(Le.x+(L-Le.y)/(Re.y-Le.y)*(Re.x-Le.x),L)._round()),oe&&Le.equals(oe[oe.length-1])||(oe=[Le],U.push(oe),F&&F.push({progress:{min:et+wlt(it,yt,Le)*We,max:1},parentIndex:K,prevPoint:it,nextPoint:yt})),oe.push(Re),F&&(F[F.length-1].progress.max=et+wlt(it,yt,Re)*We,F[F.length-1].nextPoint=yt)))))}if(F&&we>0)for(let je=ge;jeoe.t-ge.t);let U=0,K=0,X=[];for(A.push(X);U!==k.length;){if(K===F.length){for(;U!==k.length;)X.length!==0&&X[X.length-1].equals(k[U])||X.push(k[U]),U++;break}F[K].t<=U?(X.length!==0&&X[X.length-1].equals(F[K].point)||X.push(F[K].point),Math.trunc(F[K].t),K++):(X.length!==0&&X[X.length-1].equals(k[U])||X.push(k[U]),U++)}}function wlt(k,x,w){return k.x!==x.x?(w.x-k.x)/(x.x-k.x):k.y!==x.y?(w.y-k.y)/(x.y-k.y):0}function WK(k,x){return k.x*x.x+k.y*x.y}function jlt(k,x){if(k.length===1){let w=0;const A=x[w++];let L;for(;!L||A.equals(L);)if(L=x[w++],!L)return 1/0;for(;w{wn[0]=Pn,wn[1]=On,wn[2]=Ln,wn[3]=1},vn=flt();Le>0&&(Le+=vn),Re+=vn;for(const wn of je){const Pn=[],On=[];for(const Ln of wn){const Jn=Ln.x+We.x,gn=Ln.y+We.y,Rn=we.projection.projectTilePoint(Jn,gn,It),qn=we.projection.upVector(It,Ln.x,Ln.y);let tr=Le,pr=Re;if(it){const na=Slt(Jn,gn,Le,Re,it,yt,ht,Et);tr+=na.base,pr+=na.top}Le!==0?ys(_s,Rn.x+qn[0]*ds*tr,Rn.y+qn[1]*ds*tr,Rn.z+qn[2]*ds*tr):ys(_s,Rn.x,Rn.y,Rn.z),ys(gs,Rn.x+qn[0]*ds*pr,Rn.y+qn[1]*ds*pr,Rn.z+qn[2]*ds*pr),Ze(_s,_s,et),Ze(gs,gs,et),Pn.push(new iI(_s[0],_s[1],_s[2])),On.push(new iI(gs[0],gs[1],gs[2]))}Ot.push(Pn),ws.push(On)}return[Ot,ws]}(k,x,w,A,L,F,U,K,X,oe,ge):U?function(we,je,Le,Re,We,et,it,yt,ht){const Et=[],It=[],Ot=[0,0,0,1];for(const ws of we){const ds=[],_s=[];for(const gs of ws){const ys=gs.x+Re.x,vn=gs.y+Re.y,wn=Slt(ys,vn,je,Le,et,it,yt,ht);Ot[0]=ys,Ot[1]=vn,Ot[2]=wn.base,Ot[3]=1,Ge(Ot,Ot,We),Ot[3]=Math.max(Ot[3],1e-5);const Pn=new iI(Ot[0]/Ot[3],Ot[1]/Ot[3],Ot[2]/Ot[3]);Ot[0]=ys,Ot[1]=vn,Ot[2]=wn.top,Ot[3]=1,Ge(Ot,Ot,We),Ot[3]=Math.max(Ot[3],1e-5);const On=new iI(Ot[0]/Ot[3],Ot[1]/Ot[3],Ot[2]/Ot[3]);ds.push(Pn),_s.push(On)}Et.push(ds),It.push(_s)}return[Et,It]}(x,w,A,L,F,U,K,X,oe):function(we,je,Le,Re,We){const et=[],it=[],yt=We[8]*je,ht=We[9]*je,Et=We[10]*je,It=We[11]*je,Ot=We[8]*Le,ws=We[9]*Le,ds=We[10]*Le,_s=We[11]*Le;for(const gs of we){const ys=[],vn=[];for(const wn of gs){const Pn=wn.x+Re.x,On=wn.y+Re.y,Ln=We[0]*Pn+We[4]*On+We[12],Jn=We[1]*Pn+We[5]*On+We[13],gn=We[2]*Pn+We[6]*On+We[14],Rn=We[3]*Pn+We[7]*On+We[15],qn=Ln+yt,tr=Jn+ht,pr=gn+Et,na=Math.max(Rn+It,1e-5),Cr=Ln+Ot,kr=Jn+ws,fr=gn+ds,Qr=Math.max(Rn+_s,1e-5);ys.push(new iI(qn/na,tr/na,pr/na)),vn.push(new iI(Cr/Qr,kr/Qr,fr/Qr))}et.push(ys),it.push(vn)}return[et,it]}(x,w,A,L,F)}function Slt(k,x,w,A,L,F,U,K){const X=U*L.getElevationAt(k,x,!0,!0),oe=F[0]!==0,ge=oe?F[1]===0?U*(F[0]/7-450):U*function(we,je,Le){const Re=Math.floor(je[0]/8),We=Math.floor(je[1]/8),et=10*(je[0]-8*Re),it=10*(je[1]-8*We),yt=we.getElevationAt(Re,We,!0,!0),ht=we.getMeterToDEM(Le),Et=Math.floor(.5*(et*ht-1)),It=Math.floor(.5*(it*ht-1)),Ot=we.tileCoordToPixel(Re,We),ws=2*Et+1,ds=2*It+1,_s=function(On,Ln,Jn,gn,Rn){return[On.getElevationAtPixel(Ln,Jn,!0),On.getElevationAtPixel(Ln+Rn,Jn,!0),On.getElevationAtPixel(Ln,Jn+Rn,!0),On.getElevationAtPixel(Ln+gn,Jn+Rn,!0)]}(we,Ot.x-Et,Ot.y-It,ws,ds),gs=Math.abs(_s[0]-_s[1]),ys=Math.abs(_s[2]-_s[3]),vn=Math.abs(_s[0]-_s[2])+Math.abs(_s[1]-_s[3]),wn=Math.min(.25,.5*ht*(gs+ys)/ws),Pn=Math.min(.25,.5*ht*vn/ds);return yt+Math.max(wn*et,Pn*it)}(L,F,K):X;return{base:X+(w===0?-1:w),top:oe?Math.max(ge+A,X+w+2):X+A}}const nRe=4096;class Ncs{constructor(x){this.module=x,this.memoryStack=this.module.malloc(nRe),this.memoryStackNextFree=this.memoryStack}createIntArray(x){const w=this.memoryStackNextFree;return this.memoryStackNextFree+=x.length*Int32Array.BYTES_PER_ELEMENT,this.memoryStackNextFree-this.memoryStack>nRe?-1:(new Int32Array(this.module.heap32.buffer,w,x.length).set(x),w)}createFloatArray(x){const w=this.memoryStackNextFree;return this.memoryStackNextFree+=x.length*Float32Array.BYTES_PER_ELEMENT,this.memoryStackNextFree-this.memoryStack>nRe?-1:(new Float32Array(this.module.heapF32.buffer,w,x.length).set(x),w)}readStringBuffer(x){let w="";for(;this.module.heapU8[x]!==0;)w+=String.fromCharCode(this.module.heapU8[x]),++x;return w}setStyle(x){const w=x.normalScale;this.module.setStyle(w[0],w[1],w[2],x.tileToMeters)}setAOOptions(x,w){this.module.setAOOptions(x?1:0,w)}setMetricOptions(x,w){this.module.setMetricOptions(x?1:0,w)}setStructuralOptions(x){this.module.setStructuralOptions(x?1:0)}setFacadeOptions(x,w){this.module.setFacadeOptions(x,w?1:0)}setFauxFacadeOptions(x,w,A){this.module.setFauxFacadeOptions(x?1:0,w?1:0,A)}setFacadeClassifierOptions(x){this.module.setFacadeClassifierOptions(x)}generateMesh(x,w){this.memoryStackNextFree=this.memoryStack;for(const K of x){const X=this.createIntArray(K.ringIndices),oe=this.createFloatArray(K.coordinates);if(X===-1||oe===-1)return`building_gen: Out of stack memory: ${this.memoryStackNextFree-this.memoryStack}/4096`;this.module.addFeature(K.id,K.sourceId,K.minHeight,K.height,K.roofType,oe,X,K.ringIndices.length-1)}for(const K of w){let X;X=K.entrances?JSON.parse(K.entrances):[];const oe=this.createFloatArray(X),ge=this.createFloatArray(K.coordinates);if(oe===-1||ge===-1)return`building_gen: Out of stack memory: ${this.memoryStackNextFree-this.memoryStack}/4096`;this.module.addFacade(K.sourceId,K.crossPerc,K.distanceToRoad,oe,X.length,ge,K.coordinates.length)}if(!this.module.generateMesh()){const K=this.module.getLastError();return this.readStringBuffer(K)}const A=this.module.getMeshCount(),L=new Array(A);for(let K=0;K>2)-3,et=Le[Re++]>>2;if(Re++,L.json=JSON.parse(Rlt.decode(Le.subarray(Re,Re+et))),Re+=et,Re>>0,Math.ceil(1.2*Et)),Ot=Math.ceil((It-Et)/65536);try{return We.grow(Ot),et(),!0}catch{return!1}},b:it}};return(WebAssembly.instantiateStreaming?WebAssembly.instantiateStreaming(Le,yt):Le.then(ht=>ht.arrayBuffer()).then(ht=>WebAssembly.instantiate(ht,yt))).then(ht=>{const{Rb:Et,Qb:It,P:Ot,T:ws,X:ds,Ja:_s,La:gs,Qa:ys,Va:vn,Wa:wn,eb:Pn,jb:On,f:Ln,e:Jn,yb:gn,zb:Rn,Ab:qn,Bb:tr,Db:pr,Gb:na}=ht.instance.exports;We=Jn;const Cr=(()=>{let kr=0,fr=0,Qr=0,fa=0;return Za=>{Qr&&(Et(fa),Et(kr),fr+=Qr,Qr=kr=0),kr||(fr+=128,kr=It(fr));const Ca=Za.length+7&-8;let zi=kr;Ca>=fr&&(Qr=Ca,zi=fa=It(Ca));for(let Ko=0;Ko{ik=Le,KK=void 0}))}()),je&&ge.push(function(){if(rRe)return;const Le=function(Re){let We;const et=WebAssembly.instantiateStreaming(Re,{}).then(ht=>{We=ht.instance,We.exports.__wasm_call_ctors()}),it={NONE:"",OCTAHEDRAL:"meshopt_decodeFilterOct",QUATERNION:"meshopt_decodeFilterQuat",EXPONENTIAL:"meshopt_decodeFilterExp"},yt={ATTRIBUTES:"meshopt_decodeVertexBuffer",TRIANGLES:"meshopt_decodeIndexBuffer",INDICES:"meshopt_decodeIndexSequence"};return{ready:et,supported:!0,decodeGltfBuffer(ht,Et,It,Ot,ws,ds){(function(_s,gs,ys,vn,wn,Pn,On){const Ln=_s.exports.sbrk,Jn=vn+3&-4,gn=Ln(Jn*wn),Rn=Ln(Pn.length),qn=new Uint8Array(_s.exports.memory.buffer);qn.set(Pn,Rn);const tr=gs(gn,vn,wn,Rn,Pn.length);if(tr===0&&On&&On(gn,Jn,wn),ys.set(qn.subarray(gn,gn+vn*wn)),Ln(gn-Ln(0)),tr!==0)throw new Error(`Malformed buffer data: ${tr}`)})(We,We.exports[yt[ws]],ht,Et,It,Ot,We.exports[it[ds]])}}}(fetch(oi()));return Le.ready.then(()=>{rRe=Le})}()),U)for(let Le=0;Le{const K=gm(A,(X,oe)=>{X?U(X):F(oe)});L&&L.addEventListener("abort",()=>{K.cancel(),U(new DOMException("Aborted","AbortError"))},{once:!0})})}({url:k,type:"arrayBuffer"},x);return zlt(w,0,k,x)}function iRe(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 oRe(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 f5{constructor(x,w,A,L){this.context=x,this.format=A,this.useMipmap=L&&L.useMipmap,this.texture=x.gl.createTexture(),this.update(w,{premultiply:L&&L.premultiply})}update(x,w){const A=x&&x instanceof HTMLVideoElement&&x.width===0?x.videoWidth:x.width,L=x&&x instanceof HTMLVideoElement&&x.height===0?x.videoHeight:x.height,{context:F}=this,{gl:U}=F,{x:K,y:X}=w&&w.position?w.position:{x:0,y:0},oe=K+A,ge=X+L;this.size&&(this.size[0]!==oe||this.size[1]!==ge)&&(!w||w.recreateWhenResize===void 0||w.recreateWhenResize)&&(U.bindTexture(U.TEXTURE_2D,null),U.deleteTexture(this.texture),this.texture=U.createTexture(),this.size=null),U.bindTexture(U.TEXTURE_2D,this.texture),F.pixelStoreUnpackFlipY.set(!1),F.pixelStoreUnpack.set(1),F.pixelStoreUnpackPremultiplyAlpha.set(this.format===U.RGBA8&&(!w||w.premultiply!==!1));const we=x instanceof HTMLImageElement||x instanceof HTMLCanvasElement||x instanceof HTMLVideoElement||x instanceof ImageData||ImageBitmap&&x instanceof ImageBitmap;if(!this.size&&oe>0&&ge>0){const je=this.useMipmap?Math.floor(Math.log2(Math.max(oe,ge)))+1:1;U.texStorage2D(U.TEXTURE_2D,je,this.format,oe,ge),this.size=[oe,ge]}this.size&&(we?U.texSubImage2D(U.TEXTURE_2D,0,K,X,iRe(this.format),oRe(this.format),x):"data"in x&&x.data&&U.texSubImage2D(U.TEXTURE_2D,0,K,X,A,L,iRe(this.format),oRe(this.format),x.data)),this.useMipmap&&U.generateMipmap(U.TEXTURE_2D)}bind(x,w,A=!1){const{context:L}=this,{gl:F}=L;F.bindTexture(F.TEXTURE_2D,this.texture),x!==this.minFilter&&(F.texParameteri(F.TEXTURE_2D,F.TEXTURE_MAG_FILTER,x),F.texParameteri(F.TEXTURE_2D,F.TEXTURE_MIN_FILTER,this.useMipmap&&!A?x===F.NEAREST?F.NEAREST_MIPMAP_NEAREST:F.LINEAR_MIPMAP_LINEAR:x),this.minFilter=x),w!==this.wrapS&&(F.texParameteri(F.TEXTURE_2D,F.TEXTURE_WRAP_S,w),F.texParameteri(F.TEXTURE_2D,F.TEXTURE_WRAP_T,w),this.wrapS=w)}bindExtraParam(x,w,A,L,F){const{context:U}=this,{gl:K}=U;K.bindTexture(K.TEXTURE_2D,this.texture),w!==this.magFilter&&(K.texParameteri(K.TEXTURE_2D,K.TEXTURE_MAG_FILTER,w),this.magFilter=w),x!==this.minFilter&&(K.texParameteri(K.TEXTURE_2D,K.TEXTURE_MIN_FILTER,this.useMipmap?x===K.NEAREST?K.NEAREST_MIPMAP_NEAREST:K.LINEAR_MIPMAP_LINEAR:x),this.minFilter=x),A!==this.wrapS&&(K.texParameteri(K.TEXTURE_2D,K.TEXTURE_WRAP_S,A),this.wrapS=A),L!==this.wrapT&&(K.texParameteri(K.TEXTURE_2D,K.TEXTURE_WRAP_T,L),this.wrapT=L),F!==this.compareMode&&(F?(K.texParameteri(K.TEXTURE_2D,K.TEXTURE_COMPARE_MODE,K.COMPARE_REF_TO_TEXTURE),K.texParameteri(K.TEXTURE_2D,K.TEXTURE_COMPARE_FUNC,F)):K.texParameteri(K.TEXTURE_2D,K.TEXTURE_COMPARE_MODE,K.NONE),this.compareMode=F)}destroy(){const{gl:x}=this.context;x.deleteTexture(this.texture),this.texture=null}}class ZK{constructor(x,w){this.context=x,this.texture=w}bind(x,w){const{context:A}=this,{gl:L}=A;L.bindTexture(L.TEXTURE_2D,this.texture),x!==this.minFilter&&(L.texParameteri(L.TEXTURE_2D,L.TEXTURE_MAG_FILTER,x),L.texParameteri(L.TEXTURE_2D,L.TEXTURE_MIN_FILTER,x),this.minFilter=x),w!==this.wrapS&&(L.texParameteri(L.TEXTURE_2D,L.TEXTURE_WRAP_S,w),L.texParameteri(L.TEXTURE_2D,L.TEXTURE_WRAP_T,w),this.wrapS=w)}}const Mcs=Hn([{name:"a_pos_3f",components:3,type:"Float32"}]),Pcs=Hn([{name:"a_color_3f",components:3,type:"Float32"}]),Lcs=Hn([{name:"a_color_4f",components:4,type:"Float32"}]),Ics=Hn([{name:"a_uv_2f",components:2,type:"Float32"}]),Dcs=Hn([{name:"a_normal_3f",components:3,type:"Float32"}]),Rcs=Hn([{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"}]),Fcs=Hn([{name:"a_pbr",components:4,type:"Uint16"},{name:"a_heightBasedEmissiveStrength",components:3,type:"Float32"}]);function Ult(k,x){const w=Gie(k.projection,k.zoom,k.width,k.height),A=function(F,U,K,X,oe){const ge=new Es(K.lng-180*dT,K.lat),we=new Es(K.lng+180*dT,K.lat),je=F.project(ge.lng,ge.lat),Le=F.project(we.lng,we.lat),Re=-Math.atan2(Le.y-je.y,Le.x-je.x),We=pa.fromLngLat(K);We.y=pt(We.y,-1+dT,1-dT);const et=We.toLngLat(),it=F.project(et.lng,et.lat),yt=pa.fromLngLat(et);yt.x+=dT;const ht=yt.toLngLat(),Et=F.project(ht.lng,ht.lat),It=$lt(Et.x-it.x,Et.y-it.y,Re),Ot=pa.fromLngLat(et);Ot.y+=dT;const ws=Ot.toLngLat(),ds=F.project(ws.lng,ws.lat),_s=$lt(ds.x-it.x,ds.y-it.y,Re),gs=Math.abs(It.x)/Math.abs(_s.y),ys=v([]);P(ys,ys,-Re*(1-(oe?0:X)));const vn=v([]);return S(vn,vn,[1,1-(1-gs)*X,1]),vn[4]=-_s.x/_s.y*X,P(vn,vn,Re),b(vn,ys,vn),vn}(k.projection,0,k.center,w,x),L=qlt(k);return S(A,A,[L,L,1]),A}function qlt(k){const x=k.projection,w=Gie(k.projection,k.zoom,k.width,k.height),A=lRe(x,k.center),L=lRe(x,Es.convert(x.center));return Math.pow(2,A*w+(1-w)*L)}function Gie(k,x,w,A,L=1/0){const F=k.range;if(!F)return 0;const U=Math.min(L,Math.max(w,A)),K=Math.log2(U/1024);return jt(F[0]+K,F[1]+K,x)}const dT=1/4e4;function lRe(k,x){const w=pt(x.lat,-85.051129,Tn),A=new Es(x.lng-180*dT,w),L=new Es(x.lng+180*dT,w),F=k.project(A.lng,w),U=k.project(L.lng,w),K=pa.fromLngLat(A),X=pa.fromLngLat(L),oe=U.x-F.x,ge=U.y-F.y,we=X.x-K.x,je=X.y-K.y,Le=Math.sqrt((we*we+je*je)/(oe*oe+ge*ge));return Math.log2(Le)}function $lt(k,x,w){const A=Math.cos(w),L=Math.sin(w);return{x:k*A-x*L,y:k*L+x*A}}function Vlt(k,x,w){v(k),P(k,k,Ws(x[2])),C(k,k,Ws(x[0])),E(k,k,Ws(x[1])),S(k,k,w),b(k,k,[1,0,0,0,0,0,1,0,0,1,0,0,0,0,0,1])}function Wie(k,x,w,A,L,F,U,K){const X=[w[0]-x[0],w[1]-x[1],0],oe=[A[0]-x[0],A[1]-x[1],0];if(H(X)<1e-12||H(oe)<1e-12)return xt(k);const ge=ze([],X,oe);Ae(ge,ge),ce(oe,A,x),X[2]=(F-L)*K,oe[2]=(U-L)*K;const we=X;return ze(we,X,oe),Ae(we,we),Ts(k,ge,we)}function Kie(k,x,w=!1){const A=r3(x.zoom),L=function(F,U,K){const X=U.worldSize,oe=[F[12],F[13],F[14]],ge=yn(oe[1]/X),we=Fs(oe[0]/X),je=v([]),Le=sn(1,ge)*X,Re=sn(1,0)*X*hr(ge,U.zoom),We=1/LDe(X);let et=Re*We;if(K){const Et=Gie(U.projection,U.zoom,U.width,U.height,1024);et=We*U.projection.pixelSpaceConversion(U.center.lat,X,Et)}const it=ns(ge,we);ne(it,it,le([],Ae([],it),Le*et*oe[2]));const yt=function(Et){const It=[Et[0],Et[1],Et[2]];let Ot=[0,1,0];const ws=ze([],Ot,It);return ze(Ot,It,ws),pe(Ot)===0&&(Ot=[0,1,0],ze(ws,It,Ot)),Ae(ws,ws),Ae(Ot,Ot),Ae(It,It),[ws[0],ws[1],ws[2],0,Ot[0],Ot[1],Ot[2],0,It[0],It[1],It[2],0,Et[0],Et[1],Et[2],1]}(it);S(je,je,[et,et,et*Le]),j(je,je,[-oe[0],-oe[1],-oe[2]]);const ht=b([],U.globeMatrix,yt);return b(ht,ht,je),b(ht,ht,F),ht}(k,x,w);if(A>0){const F=function(U,K){const X=K.worldSize,oe=sn(1,0)*X*hr(K.center.lat,K.zoom)/LDe(X),ge=sn(1,K.center.lat)*X,we=v([]);E(we,we,Ws(K.center.lng)),C(we,we,Ws(K.center.lat)),j(we,we,[0,0,Yt]),S(we,we,[oe,oe,oe*ge]);const je=K.point;return j(we,we,[-je.x,-je.y,0]),b(we,we,U),b(we,K.globeMatrix,we)}(k,x);return function(U,K,X){const oe=(Re,We,et)=>{const it=H(Re),yt=H(We),ht=n3(Re,We,et);return le(ht,ht,1/H(ht)*Ar(it,yt,et))},ge=oe([U[0],U[1],U[2]],[K[0],K[1],K[2]],X),we=oe([U[4],U[5],U[6]],[K[4],K[5],K[6]],X),je=oe([U[8],U[9],U[10]],[K[8],K[9],K[10]],X),Le=n3([U[12],U[13],U[14]],[K[12],K[13],K[14]],X);return[ge[0],ge[1],ge[2],0,we[0],we[1],we[2],0,je[0],je[1],je[2],0,Le[0],Le[1],Le[2],1]}(L,F,A)}return L}function cRe(k,x,w,A){const L=Hl.projectAabbCorners(A,w);let F=Number.MAX_VALUE;for(let K=0;K0||et===0&&Re[0]*We[0]+Re[1]*We[1]>=0&&Re[0]*Re[0]+Re[1]*Re[1]>We[0]*We[0]+We[1]*We[1])&&(ge=Le)}we=ge}while(we!==oe);return X.length>0&&X.push(X[0]),X}(L);if(gh(k,U))return F}const oI=64,Vz={CoordinateSpaceTile:1,HasMapboxMeshFeatures:4,HasMeshoptCompression:8};function Yie(k,x,w,A,L,F,U,K,X,oe=!1){const ge=w.zoom,we=w.project(A),je=hr(A.lat,ge),Le=1/je;v(k),j(k,k,[we.x+U[0]*Le,we.y+U[1]*Le,U[2]]);let Re=1,We=1;const et=w.worldSize;if(oe){if(w.projection.name==="mercator"){let Et=0;w.elevation&&(Et=w.elevation.getAtPointOrZero(new pa(we.x/et,we.y/et),0));const It=Ge([],[we.x,we.y,Et,1],w.projMatrix)[3]/w.cameraToCenterDistance;Re=It,We=It*hr(w.center.lat,ge)}else if(w.projection.name==="globe"){const Et=Kie(k,w),It=[0,0,0,1];Ge(It,It,b([],w.projMatrix,Et));const Ot=It[3]/w.cameraToCenterDistance,ws=r3(ge),ds=w.projection.pixelsPerMeter(A.lat,et)*hr(A.lat,ge),_s=w.projection.pixelsPerMeter(w.center.lat,et)*hr(w.center.lat,ge);Re=Ot/Ar(ds,Nr(w.center.lat),ws),We=Ot*je/ds,Re*=_s,We*=_s}}else Re=Le;S(k,k,[Re,Re,We]);const it=[...k],yt=x.orientation,ht=[];if(Vlt(ht,[yt[0]+(L?L[0]:0),yt[1]+(L?L[1]:0),yt[2]+(L?L[2]:0)],F),b(k,it,ht),K&&w.elevation){let Et=0;const It=[];if(X&&w.elevation){Et=function(ws,ds,_s,gs,ys){const vn=ds.elevation;if(!vn)return 0;const wn=Hl.projectAabbCorners(_s,gs),Pn=sn(1,ys.lat)*ds.worldSize,On=function(fr,Qr){const fa=[0,0,1],Za=[{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 Ca of Za){const zi=fr[Ca.corners[0]],Ko=fr[Ca.corners[1]],Bi=fr[Ca.corners[2]],el=[Ko[0]-zi[0],Ko[1]-zi[1],Qr*(Ko[2]-zi[2])],lo=ze(el,el,[Bi[0]-zi[0],Bi[1]-zi[1],Qr*(Bi[2]-zi[2])]);Ae(lo,lo),Ca.dotProductWithUp=Pe(lo,fa)}return Za.sort((Ca,zi)=>Ca.dotProductWithUp-zi.dotProductWithUp),Za[0].corners}(wn,Pn),Ln=wn[On[0]],Jn=wn[On[1]],gn=wn[On[2]],Rn=wn[On[3]],qn=vn.getAtPointOrZero(new pa(Ln[0]/ds.worldSize,Ln[1]/ds.worldSize),0),tr=vn.getAtPointOrZero(new pa(Jn[0]/ds.worldSize,Jn[1]/ds.worldSize),0),pr=vn.getAtPointOrZero(new pa(gn[0]/ds.worldSize,gn[1]/ds.worldSize),0),na=vn.getAtPointOrZero(new pa(Rn[0]/ds.worldSize,Rn[1]/ds.worldSize),0),Cr=(qn+na)/2,kr=(tr+pr)/2;return Cr>kr?tr=x.gl.NEAREST_MIPMAP_NEAREST}),k.uploaded=!0,k.image=null)}function Ocs(k,x,w){k.indexBuffer=x.createIndexBuffer(k.indexArray,!1,!0),k.vertexBuffer=x.createVertexBuffer(k.vertexArray,Mcs.members,!1,!0),k.normalArray&&(k.normalBuffer=x.createVertexBuffer(k.normalArray,Dcs.members,!1,!0)),k.texcoordArray&&(k.texcoordBuffer=x.createVertexBuffer(k.texcoordArray,Ics.members,!1,!0)),k.colorArray&&(k.colorBuffer=x.createVertexBuffer(k.colorArray,(k.colorArray.bytesPerElement===12?Pcs:Lcs).members,!1,!0)),k.featureArray&&(k.pbrBuffer=x.createVertexBuffer(k.featureArray,Fcs.members,!0)),k.segments=Rc.simpleSegment(0,0,k.vertexArray.length,k.indexArray.length);const A=k.material;A.pbrMetallicRoughness.baseColorTexture&&XK(A.pbrMetallicRoughness.baseColorTexture,x),A.pbrMetallicRoughness.metallicRoughnessTexture&&XK(A.pbrMetallicRoughness.metallicRoughnessTexture,x),A.normalTexture&&XK(A.normalTexture,x),A.occlusionTexture&&XK(A.occlusionTexture,x,w),A.emissionTexture&&XK(A.emissionTexture,x)}function dRe(k,x,w){if(k.meshes)for(const A of k.meshes)Ocs(A,x,w);if(k.children)for(const A of k.children)dRe(A,x,w)}function Zie(k){if(k.meshes)for(const x of k.meshes)x.indexArray.destroy(),x.vertexArray.destroy(),x.colorArray&&x.colorArray.destroy(),x.normalArray&&x.normalArray.destroy(),x.texcoordArray&&x.texcoordArray.destroy(),x.featureArray&&x.featureArray.destroy();if(k.children)for(const x of k.children)Zie(x)}function zcs(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 uRe(k){if(k.meshes)for(const x of k.meshes)x.vertexBuffer&&(x.vertexBuffer.destroy(),x.indexBuffer.destroy(),x.normalBuffer&&x.normalBuffer.destroy(),x.texcoordBuffer&&x.texcoordBuffer.destroy(),x.colorBuffer&&x.colorBuffer.destroy(),x.pbrBuffer&&x.pbrBuffer.destroy(),x.segments.destroy(),x.material&&zcs(x.material));if(k.footprintDebugMesh&&(k.footprintDebugMesh.vertexBuffer.destroy(),k.footprintDebugMesh.indexBuffer.destroy(),k.footprintDebugMesh.segments.destroy()),k.children)for(const x of k.children)uRe(x)}function lI(k,x){const w=k.json.bufferViews[x.bufferView],A=Vie[x.componentType];return new A(k.buffers[w.buffer],(x.byteOffset||0)+(w.byteOffset||0),x.count*(w.byteStride&&w.byteStride!==YK[x.type]*A.BYTES_PER_ELEMENT?w.byteStride/A.BYTES_PER_ELEMENT:YK[x.type]))}function hRe(k,x,w,A){const L=Vie[x.componentType],F=function(ge){switch(ge){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:return 1}}(L),U=k.json.bufferViews[x.bufferView],K=U.byteStride?U.byteStride/L.BYTES_PER_ELEMENT:YK[x.type],X=w.float32,oe=X.length/w.capacity;for(let ge=0,we=0;ge0){for(let et=0;et0){F.texcoordArray=new JC;const je=x.json.accessors[L.TEXCOORD_0];F.texcoordArray.resize(je.count);const Le=lI(x,je);hRe(x,je,F.texcoordArray,Le)}if(L._FEATURE_ID_RGBA4444!==void 0){const je=x.json.accessors[L._FEATURE_ID_RGBA4444];x.json.extensionsUsed&&x.json.extensionsUsed.includes("EXT_meshopt_compression")&&(F.featureData=lI(x,je))}L._FEATURE_RGBA4444!==void 0&&(F.featureData=new Uint32Array(lI(x,x.json.accessors[L._FEATURE_RGBA4444]).buffer));const we=k.material;return F.material=function(je,Le){const{emissiveFactor:Re=[0,0,0],alphaMode:We="OPAQUE",alphaCutoff:et=.5,normalTexture:it,occlusionTexture:yt,emissiveTexture:ht,doubleSided:Et,name:It}=je,{baseColorFactor:Ot=[1,1,1,1],metallicFactor:ws=1,roughnessFactor:ds=1,baseColorTexture:_s,metallicRoughnessTexture:gs}=je.pbrMetallicRoughness||{},ys=yt?Le[yt.index]:void 0;if(yt&&yt.extensions&&yt.extensions.KHR_texture_transform&&ys){const vn=yt.extensions.KHR_texture_transform;ys.offsetScale=[vn.offset[0],vn.offset[1],vn.scale[0],vn.scale[1]]}return{name:It,pbrMetallicRoughness:{baseColorFactor:new Xs(...Ot),metallicFactor:ws,roughnessFactor:ds,baseColorTexture:_s?Le[_s.index]:void 0,metallicRoughnessTexture:gs?Le[gs.index]:void 0},doubleSided:Et,emissiveFactor:new Xs(...Re),alphaMode:We,alphaCutoff:et,normalTexture:it?Le[it.index]:void 0,occlusionTexture:ys,emissionTexture:ht?Le[ht.index]:void 0,defined:je.defined===void 0}}(we!==void 0?x.json.materials[we]:{defined:!1},w),F}function Glt(k,x,w){const{matrix:A,rotation:L,translation:F,scale:U,mesh:K,extras:X,children:oe,name:ge}=k,we={};if(we.name=ge,we.localMatrix=A||function(je,Le,Re,We){var et=Le[0],it=Le[1],yt=Le[2],ht=Le[3],Et=et+et,It=it+it,Ot=yt+yt,ws=et*Et,ds=et*It,_s=et*Ot,gs=it*It,ys=it*Ot,vn=yt*Ot,wn=ht*Et,Pn=ht*It,On=ht*Ot,Ln=We[0],Jn=We[1],gn=We[2];return je[0]=(1-(gs+vn))*Ln,je[1]=(ds+On)*Ln,je[2]=(_s-Pn)*Ln,je[3]=0,je[4]=(ds-On)*Jn,je[5]=(1-(ws+vn))*Jn,je[6]=(ys+wn)*Jn,je[7]=0,je[8]=(_s+Pn)*gn,je[9]=(ys-wn)*gn,je[10]=(1-(ws+gs))*gn,je[11]=0,je[12]=Re[0],je[13]=Re[1],je[14]=Re[2],je[15]=1,je}([],L||[0,0,0,1],F||[0,0,0],U||[1,1,1]),we.globalMatrix=y(we.localMatrix),K!==void 0){we.meshes=w[K];const je=we.anchor=[0,0];for(const Le of we.meshes){const{min:Re,max:We}=Le.aabb;je[0]+=Re[0]+We[0],je[1]+=Re[1]+We[1]}je[0]=Math.floor(je[0]/we.meshes.length/2),je[1]=Math.floor(je[1]/we.meshes.length/2)}if(X&&(X.id&&(we.id=X.id),X.lights&&(we.lights=function(je){if(!je.length)return[];const Le=function(yt){const ht=atob(yt),Et=new Uint8Array(ht.length);for(let It=0;It1&&A[A.length-1].equals(A[0])&&A.pop();let L=0;for(let U=0;U0&&A.reverse();const F=zz(A.flatMap(U=>[U.x,U.y]),[]);return F.length===0?null:{vertices:A,indices:F}}function $cs(k,x){const w=[],A=[];let L=0;const F=[];for(const U of k){L=w.length;const K=U.vertexArray.float32,X=U.indexArray.uint16;for(let oe=0;oe0&&([A[U+1],A[U+2]]=[A[U+2],A[U+1]])}return{vertices:w,indices:A}}function mRe(k){const x=function(X,oe){const ge=[],we=WebGL2RenderingContext;if(X.json.textures)for(const je of X.json.textures){const Le={magFilter:we.LINEAR,minFilter:we.NEAREST,wrapS:we.REPEAT,wrapT:we.REPEAT};je.sampler!==void 0&&Object.assign(Le,X.json.samplers[je.sampler]),ge.push({image:oe[je.source],sampler:Le,uploaded:!1})}return ge}(k,k.images),w=function(X,oe){const ge=[];for(const we of X.json.meshes){const je=[];for(const Le of we.primitives)je.push(Bcs(Le,X,oe));ge.push(je)}return ge}(k,x),{scenes:A,scene:L,nodes:F}=k.json,U=A?A[L||0].nodes:[...F.keys()],K=[];for(const X of U)K.push(Glt(F[X],k,w));return function(X,oe,ge){const we={},je=new Set;for(let Le=0;Le0){const Le=Array.from(je.values()).sort((Re,We)=>Re-We);for(let Re=Le.length-1;Re>=0;Re--)X.splice(Le[Re],1)}}(K,U,k.json.nodes),K}function Vcs(k){k.heightmap=new Float32Array(4096),k.heightmap.fill(-1);const x=k.vertexArray.float32,w=k.aabb.min[0]-1,A=k.aabb.min[1]-1,L=oI/(k.aabb.max[0]-w+2),F=oI/(k.aabb.max[1]-A+2);for(let U=0;Uk.heightmap[oe*oI+X]&&(k.heightmap[oe*oI+X]=K)}}function Wlt(k,x,w,A,L){w.reserve(w.length+4*k.length),A.reserve(A.length+10*k.length),L.reserve(L.length+10*k.length);let F=A.length;for(const U of k){const K=Math.min(10,Math.max(4,1.3*U.height))*x,X=[-U.normal[1],U.normal[0],0],oe=Math.min(.29,.1*U.width/U.depth),ge=U.width-2*U.depth*x*(oe+.01),we=be([],U.pos,X,ge/2),je=be([],U.pos,X,-ge/2),Le=[we[0],we[1],we[2]+U.height],Re=[je[0],je[1],je[2]+U.height],We=be([],U.normal,X,oe);le(We,We,K);const et=be([],U.normal,X,-oe);le(et,et,K),ne(We,we,We),ne(et,je,et),we[2]+=.1,je[2]+=.1,A.emplaceBack(We[0],We[1],We[2]),A.emplaceBack(et[0],et[1],et[2]),A.emplaceBack(we[0],we[1],we[2]),A.emplaceBack(je[0],je[1],je[2]),A.emplaceBack(Le[0],Le[1],Le[2]),A.emplaceBack(Re[0],Re[1],Re[2]),A.emplaceBack(we[0],we[1],we[2]),A.emplaceBack(je[0],je[1],je[2]),A.emplaceBack(We[0],We[1],We[2]),A.emplaceBack(et[0],et[1],et[2]);const it=ge/K/2;L.emplaceBack(-it-oe,-1,it,.8),L.emplaceBack(it+oe,-1,it,.8),L.emplaceBack(-it,0,it,1.3),L.emplaceBack(it,0,it,1.3),L.emplaceBack(it+oe,-.8,it,.7),L.emplaceBack(it+oe,-.8,it,.7),L.emplaceBack(0,0,it,1.3),L.emplaceBack(0,0,it,1.3),L.emplaceBack(it+oe,-1.2,it,.8),L.emplaceBack(it+oe,-1.2,it,.8),w.emplaceBack(6+F,4+F,8+F),w.emplaceBack(7+F,9+F,5+F),w.emplaceBack(0+F,1+F,2+F),w.emplaceBack(1+F,3+F,2+F),F+=10}}function Hcs(k,x){const w={};w.indexArray=new Ju,w.vertexArray=new Zb,w.colorArray=new rk,Wlt(k,x,w.indexArray,w.vertexArray,w.colorArray);const A={defined:!0};A.emissiveFactor=Xs.black;const L={};return L.baseColorFactor=Xs.white,A.pbrMetallicRoughness=L,w.material=A,w.aabb=new Hl([1/0,1/0,1/0],[-1/0,-1/0,-1/0]),w}const Klt=Hn([{name:"a_pos_3f",components:3,type:"Float32"}]),Gcs=Hn([{name:"a_normal_3",components:3,type:"Int16"}]),Wcs=Hn([{name:"a_centroid_3",components:3,type:"Int16"}]),Ylt=Hn([{name:"a_part_color_emissive",components:2,type:"Uint16"}]),Kcs=Hn([{name:"a_faux_facade_color_emissive",components:2,type:"Uint16"}]),Ycs=Hn([{name:"a_faux_facade_data",components:4,type:"Uint16"}]),Zcs=Hn([{name:"a_faux_facade_vertical_range",components:2,type:"Uint16"}]),Xcs=Hn([{name:"a_bloom_attenuation",components:4,type:"Float32"}]),Qcs=Hn([{name:"a_flood_light_wall_radius_1i16",components:1,type:"Int16"}]),Zlt=Ni.types,Xie=32767;function Jcs(k,x){const w=ur+x;for(const A of k)for(const L of A)if(L.x<-x||L.x>w||L.y<-x||L.y>w)return!1;return!0}function eds(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 pRe{constructor(){this.layoutVertexArray=new Zb,this.layoutAttenuationArray=new rk,this.layoutColorArray=new Xb,this.indexArray=new Ju,this.indexArrayForConflation=new Ju,this.segmentsBucket=new Rc}}class fRe{constructor(x){this.layoutFacadePaintArray=null,this.layoutFacadeDataArray=null,this.layoutFacadeVerticalRangeArray=null,this.segmentsBucket=new Rc,this.entranceBloom=new pRe;const w=66560;this.layoutVertexArray=new Zb,this.layoutVertexArray.reserve(w),this.layoutNormalArray=new fl,this.layoutNormalArray.reserve(w),this.layoutCentroidArray=new fl,this.layoutCentroidArray.reserve(w),this.layoutColorArray=new Xb,this.layoutColorArray.reserve(w),this.layoutFloodLightDataArray=new Lz,this.layoutFloodLightDataArray.reserve(w),this.layoutAOArray=new Iz,this.layoutAOArray.reserve(w),this.indexArray=new Ju,this.indexArray.reserve(66560),this.indexArrayForConflation=new Ju,this.segmentsBucket=new Rc,this.entranceBloom=new pRe,x&&(this.layoutFacadePaintArray=new Xb,this.layoutFacadeDataArray=new nT,this.layoutFacadeVerticalRangeArray=new Xb)}reserve(x,w,A){this.layoutVertexArray.reserveForAdditional(x),this.layoutCentroidArray.reserveForAdditional(x),this.layoutFloodLightDataArray.reserveForAdditional(x),this.layoutNormalArray.reserveForAdditional(x),this.layoutAOArray.reserveForAdditional(x),this.layoutColorArray.reserveForAdditional(x),this.indexArray.reserveForAdditional(w),A&&(this.layoutFacadePaintArray.reserveForAdditional(x),this.layoutFacadeDataArray.reserveForAdditional(x),this.layoutFacadeVerticalRangeArray.reserveForAdditional(x))}}class Xlt{constructor(x){this.colorBufferUploaded=!1,this.maxHeight=0,this.replacementUpdateTime=0,this.activeReplacements=[],this.footprints=[],this.footprintsVertices=new JC,this.footprintsIndices=new e3,this.footprintsMin=new Js(1/0,1/0),this.footprintsMax=new Js(-1/0,-1/0),this.featuresOnBorder=[],this.buildingWithoutFacade=new fRe(!1),this.buildingWithFacade=new fRe(!0),this.indexArrayForConflationUploaded=!1,this.featureFootprintLookup=new Map,this.buildingIds=new Set,this.footprintLookup={},this.zoom=x.zoom,this.canonical=x.canonical,this.layers=x.layers,this.layerIds=this.layers.map(w=>w.fqid),this.index=x.index,this.hasPattern=!1,this.worldview=x.worldview,this.lut=x.lut,this.programConfigurations=new tt(x.layers,{zoom:x.zoom,lut:x.lut}),this.stateDependentLayerIds=this.layers.filter(w=>w.isStateDependent()).map(w=>w.id),this.projection=x.projection,this.groundEffect=new tRe(x),this.groundEffect.groundRadiusArray=new Zl,this.hasAppearances=null}updateFootprints(x,w){const A=new Iie([],[],1),L={vertices:[],indices:new Uint32Array(0),grid:A,min:this.footprintsMin,max:this.footprintsMax,buildingIds:this.buildingIds};w.push({footprint:L,id:x})}updateAppearances(x,w,A,L){return{hasLayoutChanges:!1,hasUboChanges:!1}}prepare(){return function(){if($ie!=null||Clt!=null)return null;if($z!=null)return $z;const x=fetch(Oo());return $z=function(w){let A,L,F,U,K;function X(){A=new Uint8Array(K.buffer),L=new Int16Array(K.buffer),F=new Int32Array(K.buffer),U=new Float32Array(K.buffer)}function oe(){throw new Error("Unexpected BuildingGen error.")}const ge=()=>{},we={a:{a:oe,f:function(je){const Le=A.length,Re=Math.max(je>>>0,Math.ceil(1.2*Le)),We=Math.ceil((Re-Le)/65536);try{return K.grow(We),X(),!0}catch{return!1}},g:oe,b:ge,c:ge,d:ge,e:ge}};return(WebAssembly.instantiateStreaming?WebAssembly.instantiateStreaming(w,we):w.then(je=>je.arrayBuffer()).then(je=>WebAssembly.instantiate(je,we))).then(je=>{const Le=je.instance.exports;return(0,Le.g)(),K=Le.f,X(),new Ncs({setStyle:Le.h,setAOOptions:Le.i,setMetricOptions:Le.j,setStructuralOptions:Le.k,setFacadeOptions:Le.l,setFauxFacadeOptions:Le.m,setFacadeClassifierOptions:Le.n,addFeature:Le.o,addFacade:Le.p,generateMesh:Le.q,getLastError:Le.r,getOuterRingLength:Le.s,getMeshCount:Le.t,getPositionsPtr:Le.u,getPositionsLength:Le.v,getNormalsPtr:Le.w,getNormalsLength:Le.x,getAOPtr:Le.y,getAOLength:Le.z,getUVPtr:Le.A,getUVLength:Le.B,getFauxFacadePtr:Le.C,getFauxFacadeLength:Le.D,getIndicesPtr:Le.E,getIndicesLength:Le.F,getBuildingPart:Le.G,getRingCount:Le.H,getRingPtr:Le.I,getRingLength:Le.J,malloc:Le.K,free:Le.L,heapU8:A,heap16:L,heap32:F,heapF32:U})})}(x).then(w=>($z=null,$ie=w,$ie)).catch(w=>{Br("Could not load building-gen"),$z=null,Clt=w instanceof Error?w:new Error("Unknown error")}),$z}()}populate(x,w,A,L){const F=kcs();if(!F)return;const U=Gn(A);this.tileToMeter=U,this.brightness=w.brightness,F.setStyle({normalScale:[1,-1,U],tileToMeters:U}),F.setAOOptions(!1,.3),F.setMetricOptions(!1,16),F.setStructuralOptions(!0),F.setFacadeClassifierOptions(3);const K=new Map,X=new Map;let oe=0;for(const{feature:it}of x){if(Zlt[it.type]!=="LineString"){K.set(it.id,it.properties.source_id);continue}const yt=this.layers[0]._featureFilter.needGeometry;if(yt&&!this.layers[0]._featureFilter.filter(new $i(this.zoom),it,A))continue;const ht=oo(it,yt);if(!yt&&!this.layers[0]._featureFilter.filter(new $i(this.zoom),ht,A))continue;const Et=yt?ht.geometry:Qa(it,A,L),It=[];for(const _s of Et)for(const gs of _s)It.push(gs.x),It.push(gs.y);const Ot={coordinates:It,crossPerc:it.properties.cross_perc,distanceToRoad:it.properties.distance_to_road,entrances:it.properties.entrances,sourceId:0},ws=it.properties.source_id;let ds=X.get(ws);ds||(ds=[],X.set(ws,ds)),ds.push(Ot),++oe}this.maxHeight=0;const ge=new Array,we=new Set,je=it=>{it!=null&&we.add(it)},Le=(it,yt)=>{it!=null&&ge.push({buildingId:it,footprintIndex:yt})},Re=64*(x.length-oe),We=Re/2;this.buildingWithFacade.reserve(Re,We,!0),this.buildingWithoutFacade.reserve(2*Re,2*We,!1),this.footprintsIndices.reserve(16*(x.length-oe)),this.footprintsVertices.reserve(8*(x.length-oe));for(const{feature:it,id:yt,index:ht,sourceLayerIndex:Et}of x){if(Zlt[it.type]==="LineString")continue;const It=this.layers[0]._featureFilter.needGeometry;if(It&&!this.layers[0]._featureFilter.filter(new $i(this.zoom),it,A))continue;let Ot=null;if(it.properties&&it.properties.hasOwnProperty("building_id")&&(Ot=Number(it.properties.building_id),we.has(Ot)))continue;const ws=oo(it,It);if(!It&&!this.layers[0]._featureFilter.filter(new $i(this.zoom),ws,A))continue;const ds=It?ws.geometry:Qa(it,A,L),_s=BK(ds,500);let gs=!1;for(const vo of _s)if(vo.length!==1){gs=!0;break}if(gs){je(Ot);continue}if(!Jcs(ds,163)){je(Ot);continue}const ys=this.layers[0],vn=eds(ys.layout.get("building-roof-shape").evaluate(it,{},A)),wn=ys.layout.get("building-base").evaluate(it,{},A),Pn=ys.layout.get("building-height").evaluate(it,{},A),On=ys.layout.get("building-flood-light-ground-radius").evaluate(it,{},A),Ln=ys.paint.get("building-ambient-occlusion-intensity"),Jn=On/this.tileToMeter;it.properties["building-part"]="roof";const gn=ys.paint.get("building-color").evaluate(it,{},this.canonical).toPremultipliedRenderColor(this.lut),Rn=ys.paint.get("building-emissive-strength").evaluate(it,{},this.canonical);it.properties["building-part"]="wall";const qn=ys.paint.get("building-color").evaluate(it,{},this.canonical).toPremultipliedRenderColor(this.lut),tr=ys.paint.get("building-emissive-strength").evaluate(it,{},this.canonical);it.properties["building-part"]="window";const pr=ys.paint.get("building-color").evaluate(it,{},this.canonical).toPremultipliedRenderColor(this.lut),na=ys.paint.get("building-emissive-strength").evaluate(it,{},this.canonical);it.properties["building-part"]="door";const Cr=ys.paint.get("building-color").evaluate(it,{},this.canonical).toPremultipliedRenderColor(this.lut),kr=ys.paint.get("building-emissive-strength").evaluate(it,{},this.canonical);let fr=ys.layout.get("building-flood-light-wall-radius").evaluate(it,{},A);fr=pt(fr,0,2048);const Qr=fr/2048*Xie,fa=K.get(yt),Za=X.get(fa)||[],Ca=Za.length!==0&&ys.layout.get("building-facade").evaluate(it,{},A);F.setFacadeOptions(4,!0),F.setFauxFacadeOptions(Ca,!1,1);let zi=0,Ko=0,Bi=0,el=0,lo=0,Mu=0,Il=0,ll=0,zc=0,wu=0,Up=0;if(Ca){let vo=Math.round(ys.layout.get("building-facade-floors").evaluate(it,{},A));if(wn===0){vo=Math.max(1,vo-(Za.length>0?1:0));let sh=4;if(Pn>100){const pp=[10,13,15];sh=pp[it.id?it.id%pp.length:0]}else Pn<=10&&(sh=3);F.setFacadeOptions(sh,!0),lo=(Pn<15?1.3:1.61803)*sh/U}else lo=wn/U;Mu=Pn/U,lo=Math.min(lo,Mu),Bi=ys.layout.get("building-facade-unit-width").evaluate(it,{},A)/U,el=(Mu-lo)/vo,F.setFauxFacadeOptions(!0,!0,Bi);const vf=ys.layout.get("building-facade-window").evaluate(it,{},A);zi=vf[0],Ko=vf[1],Il=Math.floor(65535*Math.min(1,lo/ur)),ll=Math.floor(65535*Math.min(1,Mu/ur)),zc=Math.floor(255*zi)<<8|Math.floor(255*Ko),wu=Math.floor(65535*Math.min(1,Bi/ur)),Up=Math.floor(65535*Math.min(1,el/ur))}const ju=Array(_s.length),eh={x:1/0,y:1/0},Jh={x:-1/0,y:-1/0},th={x:0,y:0};let Vx=0;for(let vo=0;vo<_s.length;vo++){const vf=_s[vo];if(vf.length>0){const sh=[],pp=Array(vf.length+1);pp[0]=0;for(let fw=0;fwur||eh.y<0||Jh.y>ur)&&this.featuresOnBorder.push({featureId:it.id,footprintIndex:this.footprints.length});{const vo=zz(d3,null,2);this.footprintsIndices.resize(this.footprintsIndices.length+vo.length),this.footprintsIndices.uint16.set(vo,nB),this.buildingIds.add(Ot??it.id),this.footprintsMin.x=Math.min(this.footprintsMin.x,mw.x),this.footprintsMin.y=Math.min(this.footprintsMin.y,mw.y),this.footprintsMax.x=Math.max(this.footprintsMax.x,pw.x),this.footprintsMax.y=Math.max(this.footprintsMax.y,pw.y);const vf={footprintVertexOffset:c3,footprintVertexLength:this.footprintsVertices.length-c3,footprintIndexOffset:nB,footprintIndexLength:this.footprintsIndices.length-nB,min:mw,max:pw,hiddenFlags:0,indicesOffset:Soe,indicesLength:aFe,bloomIndicesOffset:Hx,bloomIndicesLength:Pu,groundEffectVertexOffset:fI,groundEffectVertexLength:rB,hasFauxFacade:Ca,height:sB,promoteId:yt,feature:ws,parts:gf,buildingBloom:Y0},sh=this.footprints.length;it.id!==void 0&&this.featureFootprintLookup.set(it.id,sh),Le(Ot,sh),this.footprints.push(vf)}this.programConfigurations.populatePaintArrays(fo.layoutVertexArray.length,it,ht,{},w.availableImages,A,w.brightness),this.groundEffect.addPaintPropertiesData(it,ht,{},w.availableImages,A,w.brightness),w.featureIndex.insert(it,ds,ht,Et,this.index,Qg)}ge.forEach(({buildingId:it,footprintIndex:yt})=>{we.has(it)&&(this.footprints[yt].hiddenFlags|=4)});const et=new Set;this.buildingIds.forEach((it,yt,ht)=>{we.has(it)||et.add(it)}),this.buildingIds=et,this.groundEffect.prepareBorderSegments()}update(x,w,A,L,F,U,K){this.programConfigurations.updatePaintArrays(x,w,F,A,L,U,K),this.groundEffect.update(x,w,F,A,L,U,K),this.evaluate(this.layers[0],x),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(x){const w=A=>{A.layoutVertexBuffer=x.createVertexBuffer(A.layoutVertexArray,Klt.members),A.layoutNormalBuffer=x.createVertexBuffer(A.layoutNormalArray,Gcs.members),A.layoutCentroidBuffer=x.createVertexBuffer(A.layoutCentroidArray,Wcs.members),A.layoutFloodLightDataBuffer=x.createVertexBuffer(A.layoutFloodLightDataArray,Qcs.members),A.layoutFacadeDataArray&&A.layoutFacadeDataArray.length&&(A.layoutFacadeDataBuffer=x.createVertexBuffer(A.layoutFacadeDataArray,Ycs.members)),A.layoutFacadeVerticalRangeArray&&A.layoutFacadeVerticalRangeArray.length&&(A.layoutFacadeVerticalRangeBuffer=x.createVertexBuffer(A.layoutFacadeVerticalRangeArray,Zcs.members)),A.entranceBloom.layoutVertexArray.length&&(A.entranceBloom.layoutVertexBuffer=x.createVertexBuffer(A.entranceBloom.layoutVertexArray,Klt.members),A.entranceBloom.layoutAttenuationBuffer=x.createVertexBuffer(A.entranceBloom.layoutAttenuationArray,Xcs.members)),this.uploadUpdatedColorBuffer(x),this.uploadUpdatedIndexBuffer(x)};this.uploaded||(w(this.buildingWithoutFacade),w(this.buildingWithFacade),this.groundEffect.upload(x)),this.groundEffect.uploadPaintProperties(x),this.programConfigurations.upload(x),this.uploaded=!0}destroy(){const x=w=>{w.layoutVertexBuffer&&(w.layoutVertexBuffer.destroy(),w.layoutNormalBuffer.destroy(),w.layoutColorBuffer.destroy(),w.segmentsBucket.destroy(),w.indexBuffer&&w.indexBuffer.destroy(),w.entranceBloom.layoutVertexBuffer&&(w.entranceBloom.layoutVertexBuffer.destroy(),w.entranceBloom.layoutColorBuffer.destroy(),w.entranceBloom.layoutAttenuationBuffer.destroy(),w.entranceBloom.indexBuffer.destroy(),w.entranceBloom.segmentsBucket.destroy()))};x(this.buildingWithoutFacade),x(this.buildingWithFacade),this.groundEffect.destroy(),this.programConfigurations.destroy()}updateFootprintHiddenFlags(x,w,A=!0){let L=!1;const F=A?w:0,U=0|(A?-1:~w);this.groundEffect.hiddenByLandmarkVertexArray.length===0&&this.groundEffect.hiddenByLandmarkVertexArray.resize(this.groundEffect.vertexArray.length);for(const K of x){const X=this.footprints[K],oe=X.hiddenFlags&U|F;X.hiddenFlags!==oe&&(X.hiddenFlags=oe,L=!0,this.groundEffect.updateHiddenByLandmarkRange(X.groundEffectVertexOffset,X.groundEffectVertexLength,X.hiddenFlags!==0))}return L&&(this.indexArrayForConflationUploaded=!1),L}uploadUpdatedIndexBuffer(x){if(this.groundEffect.uploadHiddenByLandmark(x),this.indexArrayForConflationUploaded)return;const w=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))};w(this.buildingWithoutFacade),w(this.buildingWithFacade);for(const L of this.footprints){const F=L.hasFauxFacade?this.buildingWithFacade:this.buildingWithoutFacade,U=L.indicesOffset+L.indicesLength;if(L.hiddenFlags!==0){for(let X=L.indicesOffset;X{L.indexArray.length!==0&&(L.indexBuffer?L.indexBuffer.updateData(L.indexArrayForConflation):L.indexBuffer=x.createIndexBuffer(L.indexArrayForConflation,!0),L.entranceBloom.indexBuffer?L.entranceBloom.indexBuffer.updateData(L.entranceBloom.indexArrayForConflation):L.entranceBloom.indexBuffer=x.createIndexBuffer(L.entranceBloom.indexArrayForConflation,!0))};A(this.buildingWithoutFacade),A(this.buildingWithFacade),this.indexArrayForConflationUploaded=!0}uploadUpdatedColorBuffer(x){const w=A=>{A.layoutColorBuffer?A.layoutColorBuffer.updateData(A.layoutColorArray):A.layoutColorBuffer=x.createVertexBuffer(A.layoutColorArray,Ylt.members,!0),A.layoutFacadePaintArray&&(A.layoutFacadePaintBuffer?A.layoutFacadePaintBuffer.updateData(A.layoutFacadePaintArray):A.layoutFacadePaintBuffer=x.createVertexBuffer(A.layoutFacadePaintArray,Kcs.members,!0)),A.entranceBloom.layoutColorBuffer?A.entranceBloom.layoutColorBuffer.updateData(A.entranceBloom.layoutColorArray):A.entranceBloom.layoutColorBuffer=x.createVertexBuffer(A.entranceBloom.layoutColorArray,Ylt.members,!0)};w(this.buildingWithoutFacade),w(this.buildingWithFacade),this.colorBufferUploaded=!0}evaluate(x,w){const A=x.paint.get("building-ambient-occlusion-intensity");for(const L of this.footprints){if(4&L.hiddenFlags)continue;const F=w[L.promoteId],U=L.feature;U.properties["building-part"]="roof";const K=x.paint.get("building-color").evaluate(U,F,this.canonical).toPremultipliedRenderColor(this.lut),X=x.paint.get("building-emissive-strength").evaluate(U,F,this.canonical);U.properties["building-part"]="wall";const oe=x.paint.get("building-color").evaluate(U,F,this.canonical).toPremultipliedRenderColor(this.lut),ge=x.paint.get("building-emissive-strength").evaluate(U,F,this.canonical);U.properties["building-part"]="window";const we=x.paint.get("building-color").evaluate(U,F,this.canonical).toPremultipliedRenderColor(this.lut),je=x.paint.get("building-emissive-strength").evaluate(U,F,this.canonical);U.properties["building-part"]="door";const Le=x.paint.get("building-color").evaluate(U,F,this.canonical).toPremultipliedRenderColor(this.lut),Re=x.paint.get("building-emissive-strength").evaluate(U,F,this.canonical),We=L.hasFauxFacade?this.buildingWithFacade:this.buildingWithoutFacade;for(const it of L.parts){let yt,ht=K;it.part===1?(ht=K,yt=X):it.part===0?(ht=oe,yt=ge):it.part===2?(ht=we,yt=je):it.part===3&&(ht=Le,yt=Re),yt=pt(yt,0,1);for(let Et=0;EtU.max.x||X.max.xU.max.y||X.max.yK.max.x||K.min.x>x||w>K.max.y||K.min.y>w||K.height<=A||tds(U,this.footprintsVertices.float32.subarray(2*K.footprintVertexOffset,2*(K.footprintVertexOffset+K.footprintVertexLength)),this.footprintsIndices.uint16.subarray(K.footprintIndexOffset,K.footprintIndexOffset+K.footprintIndexLength))&&(A=K.height,this.footprintLookup[F]=K,L=K.hiddenFlags!==0);if(A!==Number.NEGATIVE_INFINITY)return{height:A,hidden:L};this.footprintLookup[F]=void 0}}function tds(k,x,w){for(let A=0;A1&&(X=x[++K]);const ge=Math.abs(oe-X.left),we=Math.abs(oe-X.right),je=Math.min(ge,we);let Le;const Re=F/A*(L+1);if(X.isDash){const We=L-Math.abs(Re);Le=Math.sqrt(je*je+We*We)}else Le=L-Math.sqrt(je*je+Re*Re);this.image.data[U+oe]=Math.max(0,Math.min(255,Le+128))}}}addRegularDash(x,w){for(let X=x.length-1;X>=0;--X){const oe=x[X],ge=x[X+1];oe.zeroLength?x.splice(X,1):ge&&ge.isDash===oe.isDash&&(ge.left=oe.left,x.splice(X,1))}const A=x[0],L=x[x.length-1];A.isDash===L.isDash&&(A.left=L.left-this.width,L.right=A.right+this.width);const F=this.width*this.nextRow;let U=0,K=x[U];for(let X=0;X1&&(K=x[++U]);const oe=Math.abs(X-K.left),ge=Math.abs(X-K.right),we=Math.min(oe,ge);this.image.data[F+X]=Math.max(0,Math.min(255,(K.isDash?we:-we)+w+128))}}addDash(x,w){const A=this.getKey(x,w);if(this.positions[A])return this.positions[A];const L=w==="round",F=L?7:0,U=2*F+1;if(this.nextRow+U>this.height)return Br("LineAtlas out of space"),null;x.length===0&&x.push(1);let K=0;for(let we=0;wew.fqid),this.index=x.index,this.projection=x.projection,this.hasPattern=!1,this.hasCrossSlope=!1,this.patternFeatures=[],this.lineClipsArray=[],this.gradients={},this.layers.forEach(w=>{this.gradients[w.id]={}}),this.layoutVertexArray=new WL,this.layoutVertexArray2=new Zb,this.patternVertexArray=new Zb,this.indexArray=new Ju,this.programConfigurations=new tt(x.layers,{zoom:x.zoom,lut:x.lut}),this.segments=new Rc,this.maxLineLength=0,this.zOffsetVertexArray=new Zb,this.elevationGroundScaleVertexArray=new Zl,this.stateDependentLayerIds=this.layers.filter(w=>w.isStateDependent()).map(w=>w.id),this.tessellationStep=x.tessellationStep?x.tessellationStep:128,this.worldview=x.worldview,this.hasAppearances=null}updateFootprints(x,w){}updateAppearances(x,w,A,L){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(x,w,A,L){this.hasPattern=ODe("line",this.layers,this.pixelRatio,w);const F=this.layers[0].layout.get("line-sort-key");this.tileToMeter=Gn(A);const U=this.layers[0].layout.get("line-elevation-reference");if(U==="hd-road-markup")this.elevationType="road";else{const je=this.layers[0].layout.get("line-z-offset"),Le=je.isConstant()&&!je.constantOr(0);this.elevationType=U!=="sea"&&U!=="ground"&&Le?"none":"offset",this.elevationType==="offset"&&U==="none"&&Br(`line-elevation-reference: ground is used for the layer ${this.layerIds[0]} because non-zero line-z-offset value was found.`),this.isSeaLevelReference=U==="sea"}const K=this.layers[0].layout.get("line-cross-slope");this.hasCrossSlope=this.elevationType==="offset"&&K!==void 0;const X=[];for(const{feature:je,id:Le,index:Re,sourceLayerIndex:We}of x){const et=this.layers[0]._featureFilter.needGeometry,it=oo(je,et);if(!this.layers[0]._featureFilter.filter(new $i(this.zoom,{worldview:this.worldview,activeFloors:w.activeFloors}),it,A))continue;const yt=F?F.evaluate(it,{},A):void 0,ht={id:Le,properties:je.properties,type:je.type,sourceLayerIndex:We,index:Re,geometry:et?it.geometry:Qa(je,A,L),patterns:{},sortKey:yt};X.push(ht)}F&&X.sort((je,Le)=>je.sortKey-Le.sortKey);const{lineAtlas:oe,featureIndex:ge}=w,we=this.addConstantDashes(oe);for(const je of X){const{geometry:Le,index:Re,sourceLayerIndex:We}=je;if(we&&this.addFeatureDashes(je,oe),this.hasPattern){const et=zDe("line",this.layers,je,this.zoom,this.pixelRatio,w);this.patternFeatures.push(et)}else this.addFeature(je,Le,Re,A,oe.positions,w.availableImages,w.brightness,w.elevationFeatures);ge.insert(x[Re].feature,Le,Re,We,this.index)}}addConstantDashes(x){let w=!1;for(const A of this.layers){const L=A.paint.get("line-dasharray").value,F=A.layout.get("line-cap").value;if(L.kind!=="constant"||F.kind!=="constant")w=!0;else{const U=F.value,K=L.value;if(!K)continue;x.addDash(K,U)}}return w}addFeatureDashes(x,w){const A=this.zoom;for(const L of this.layers){const F=L.paint.get("line-dasharray").value,U=L.layout.get("line-cap").value;if(F.kind==="constant"&&U.kind==="constant")continue;let K,X;if(F.kind==="constant"){if(K=F.value,!K)continue}else K=F.evaluate({zoom:A},x);X=U.kind==="constant"?U.value:U.evaluate({zoom:A},x),w.addDash(K,X),x.patterns[L.id]=[w.getKey(K,X)]}}update(x,w,A,L,F,U,K,X,oe){this.programConfigurations.updatePaintArrays(x,w,F,A,L,U,K,oe)}addFeatures(x,w,A,L,F,U){for(const K of this.patternFeatures)this.addFeature(K,K.geometry,K.index,w,A,L,U,x.elevationFeatures)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(x){this.uploaded||(this.layoutVertexArray2.length!==0&&(this.layoutVertexBuffer2=x.createVertexBuffer(this.layoutVertexArray2,lds)),this.patternVertexArray.length!==0&&(this.patternVertexBuffer=x.createVertexBuffer(this.patternVertexArray,dds)),!this.zOffsetVertexBuffer&&this.zOffsetVertexArray.length>0&&(this.zOffsetVertexBuffer=x.createVertexBuffer(this.zOffsetVertexArray,rds.members,!0)),!this.elevationGroundScaleVertexBuffer&&this.elevationGroundScaleVertexArray.length>0&&(this.elevationGroundScaleVertexBuffer=x.createVertexBuffer(this.elevationGroundScaleVertexArray,ads.members,!0)),this.layoutVertexBuffer=x.createVertexBuffer(this.layoutVertexArray,ids),this.indexBuffer=x.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(x),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(x,w){let A,L;if(w&&w>0?(A=`mapbox_clip_start_${w}`,L=`mapbox_clip_end_${w}`):(A="mapbox_clip_start",L="mapbox_clip_end"),x.properties&&x.properties.hasOwnProperty(A)&&x.properties.hasOwnProperty(L))return{start:+x.properties[A],end:+x.properties[L]}}addFeature(x,w,A,L,F,U,K,X){const oe=this.layers[0].layout,ge=oe.get("line-join").evaluate(x,{}),we=oe.get("line-cap").evaluate(x,{}),je=oe.get("line-miter-limit"),Le=oe.get("line-round-limit");this.lineClips=this.lineFeatureClips(x),this.lineFeature=x;const Re=!(!x.properties||!x.properties.hasOwnProperty("mapbox_line_metrics"))&&x.properties.mapbox_line_metrics;this.zOffsetValue=oe.get("line-z-offset").value;const We=this.layers[0].paint.get("line-width").value;if(We.kind!=="constant"&&We.isLineProgressConstant===!1&&(this.variableWidthValue=We),this.isSeaLevelReference){const et=oe.get("line-elevation-ground-scale").value;et.kind==="constant"&&et.value===0||(this.elevationGroundScaleValue=et)}if(this.elevationType==="road"){const et=this.layoutVertexArray.length;if(!this.addElevatedRoadFeature(x,w,L,X,ge,we,je,Le)){const[it,yt]=this.clipRuntimeLinesToTile(w,1);for(let ht=0;ht0?It.parentIndex:null)}this.fillNonElevatedRoadSegment(et)}}else for(let et=0;et0?et:null);this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,x,A,F,U,L,K,void 0,this.worldview)}computeSegNextDir(x,w){return x.nextPoint.sub(w.at(-2)).unit()}computeSegPrevDir(x,w){return w[1].sub(x.prevPoint).unit()}clipLinesToTile(x,w){return qie(x,-w,-w,ur+w,ur+w)}clipRuntimeLinesToTile(x,w){const A=[];return[qie(x,-w,-w,ur+w,ur+w,A),A]}addElevatedRoadFeature(x,w,A,L,F,U,K,X){const oe=[],ge=Wc.getElevationFeature(x,L);if(ge){const we=this.clipLinesToTile(w,1),je=this.prepareElevatedLines(we,ge,A);for(const Le of je)oe.push({geometry:Le,elevation:ge,elevationTileID:A,segment:{progress:{min:0,max:1},nextDir:void 0,prevDir:void 0}})}if(oe.length===0)return!1;for(const we of oe){const je=this.layoutVertexArray.length;this.addLine(we.geometry,x,A,F,U,K,X);const Le=new rd(A,we.elevationTileID);if(we.elevation)for(let Re=je;Re>1,this.layoutVertexArray.int16[6*Re+1]>>1),et=Le.pointElevation(We,we.elevation,.05);this.updateHeightRange(et),this.zOffsetVertexArray.emplaceBack(et,0,0)}else this.fillNonElevatedRoadSegment(je)}return!0}prepareElevatedLines(x,w,A){if(w.constantHeight!=null)return x;const L=[],F=1/Gn(A);for(const U of x)jcs(U,new z1(w,F),0,L);return L}fillNonElevatedRoadSegment(x){for(let w=x;w0,je=X&&X.progress.max<1;if(this.lineClips){let _s={min:this.lineClips.start,max:this.lineClips.end},gs=1;if(X){const wn=this.lineClips.end-this.lineClips.start;_s=function(Pn,On,Ln){return{min:Ro(Pn.min,On,Ln),max:Ro(Pn.max,On,Ln)}}(X.progress,{min:0,max:1},_s),wn>0&&(gs=(_s.max-_s.min)/wn)}const ys=+w.properties.mapbox_clip_feature_len,vn=+w.properties.mapbox_clip_seg_len;if(Number.isNaN(ys)||Number.isNaN(vn)){for(let Pn=0;Pn=2&&x[Re-1].equals(x[Re-2]);)Re--;let We=0;for(;We0,Rn=this.overscaling<=16?122880/(512*this.overscaling):0;if(gs&&ys==="round"){if(OnU&&(ys="bevel"),ys==="bevel"&&(On>2&&(ys="flipbevel"),On2*Rn){const pr=it.sub(it.sub(yt)._mult(Rn/qn)._round());this.updateDistance(yt,pr),this.addCurrentVertex(pr,Et,0,0,et,ds),yt=pr}this.updateDistance(yt,it),wn._mult(On),this.addCurrentVertex(it,wn,0,0,et,ds);const tr=it.dist(ht);if(tr>2*Rn){const pr=it.add(ht.sub(it)._mult(Rn/tr)._round());this.updateDistance(it,pr),this.addCurrentVertex(pr,It,0,0,et,ds),it=pr}}else wn._mult(On),this.addCurrentVertex(it,wn,0,0,et,ds);else if(ys==="flipbevel"){if(On>100)wn=It.mult(-1);else{const qn=On*Et.add(It).mag()/Et.sub(It).mag();wn._perp()._mult(qn*(gn?-1:1))}this.addCurrentVertex(it,wn,0,0,et,ds),this.addCurrentVertex(it,wn.mult(-1),0,0,et,ds)}else if(ys==="bevel"||ys==="fakeround"){const qn=it.dist(yt);let tr=1;if(this.elevationType==="offset"&&ys==="bevel"&&this.currentLineJoinType!=="round"&&!this.patternJoinNone&&ds!=null&&yt&&ht){const Qr=4*Rn;qn1){this.lineSoFar=x.w;const We=(w.x-x.x)/we,et=(w.y-x.y)/we,it=(w.z-x.z)/we,yt=(w.w-x.w)/we,ht=w.x-x.x,Et=w.y-x.y,It=Math.sqrt(ht*ht+Et*Et);if(It===0)return;const Ot=-Et/It,ws=ht/It,ds=Ot,_s=ws,gs=-Ot,ys=-ws;for(let vn=1;vn=0&&this.e2>=0&&(this.indexArray.emplaceBack(this.e1,this.e2,ge),X.primitiveLength++),U?this.e2=ge:this.e1=ge,oe!=null&&this.zOffsetVertexArray.emplaceBack(oe.zOffset,oe.variableWidth,oe.variableWidth),this.elevationGroundScaleValue){const we=oe?oe.elevationGroundScale:this.evaluateElevationGroundScale();this.elevationGroundScaleVertexArray.emplaceBack(we)}}updateScaledDistance(){this.lineClips?(this.scaledDistance=this.distance/this.totalDistance,this.lineSoFar=this.totalFeatureLength*this.lineClips.start+this.distance):this.lineSoFar=this.distance}updateDistance(x,w){this.prevDistance=this.distance,this.distance+=x.dist(w),this.updateScaledDistance()}}function xRe(k,x,w){return k.xw||k.yw}let tct,sct;function nct(k,x,w){return x*(ur/(k.tileSize*Math.pow(2,w-k.tileID.overscaledZ)))}jr(Qie,"LineBucket",{omit:["layers","patternFeatures","currentVertex","currentVertexIsOutside"]});const rct=(k,x,w)=>(1-w)*k+w*x;function act(k,x){return 1/nct(k,1,x.tileZoom)}function ict(k,x,w,A){return k.translatePosMatrix(A||x.tileID.projMatrix,x,w.paint.get("line-translate"),w.paint.get("line-translate-anchor"))}const oct=k=>{const x=[];lct(k)&&x.push("RENDER_LINE_DASH"),k.paint.get("line-gradient")&&x.push("RENDER_LINE_GRADIENT"),k.paint.get("line-blend-mode")==="multiply"&&x.push("LINE_BLEND_MULTIPLY");const w=k.paint.get("line-trim-offset");w[0]===0&&w[1]===0||x.push("RENDER_LINE_TRIM_OFFSET"),k.paint.get("line-border-width").constantOr(1)!==0&&x.push("RENDER_LINE_BORDER");const A=k.layout.get("line-join").constantOr("miter")==="none",L=!!k.paint.get("line-pattern").constantOr(1);return A&&L&&x.push("LINE_JOIN_NONE"),x};function lct(k){const x=k.paint.get("line-dasharray").value;return x.kind!=="constant"||x.value}let gRe;const cct=()=>gRe||(gRe={layout:tct||(tct=new nd({"line-cap":new lr(Us.layout_line["line-cap"]),"line-join":new lr(Us.layout_line["line-join"]),"line-miter-limit":new cr(Us.layout_line["line-miter-limit"]),"line-round-limit":new cr(Us.layout_line["line-round-limit"]),"line-sort-key":new lr(Us.layout_line["line-sort-key"]),"line-z-offset":new lr(Us.layout_line["line-z-offset"]),"line-elevation-reference":new cr(Us.layout_line["line-elevation-reference"]),"line-cross-slope":new cr(Us.layout_line["line-cross-slope"]),visibility:new cr(Us.layout_line.visibility),"line-width-unit":new cr(Us.layout_line["line-width-unit"]),"line-elevation-ground-scale":new lr(Us.layout_line["line-elevation-ground-scale"])})),paint:sct||(sct=new nd({"line-opacity":new lr(Us.paint_line["line-opacity"]),"line-color":new lr(Us.paint_line["line-color"]),"line-translate":new cr(Us.paint_line["line-translate"]),"line-translate-anchor":new cr(Us.paint_line["line-translate-anchor"]),"line-width":new lr(Us.paint_line["line-width"]),"line-gap-width":new lr(Us.paint_line["line-gap-width"]),"line-offset":new lr(Us.paint_line["line-offset"]),"line-blur":new lr(Us.paint_line["line-blur"]),"line-dasharray":new lr(Us.paint_line["line-dasharray"]),"line-pattern":new lr(Us.paint_line["line-pattern"]),"line-pattern-cross-fade":new cr(Us.paint_line["line-pattern-cross-fade"]),"line-gradient":new Gy(Us.paint_line["line-gradient"]),"line-trim-offset":new cr(Us.paint_line["line-trim-offset"]),"line-trim-fade-range":new cr(Us.paint_line["line-trim-fade-range"]),"line-trim-color":new cr(Us.paint_line["line-trim-color"]),"line-emissive-strength":new lr(Us.paint_line["line-emissive-strength"]),"line-border-width":new lr(Us.paint_line["line-border-width"]),"line-border-color":new lr(Us.paint_line["line-border-color"]),"line-occlusion-opacity":new cr(Us.paint_line["line-occlusion-opacity"]),"line-blend-mode":new cr(Us.paint_line["line-blend-mode"]),"line-color-use-theme":new lr({type:"string",default:"default","property-type":"data-driven"}),"line-gradient-use-theme":new lr({type:"string",default:"default","property-type":"data-driven"}),"line-trim-color-use-theme":new lr({type:"string",default:"default","property-type":"data-driven"}),"line-border-color-use-theme":new lr({type:"string",default:"default","property-type":"data-driven"})}))},gRe);class pds extends lr{possiblyEvaluate(x,w){return w=new $i(Math.floor(w.zoom),{now:w.now,fadeDuration:w.fadeDuration,transition:w.transition,worldview:w.worldview}),super.possiblyEvaluate(x,w)}evaluate(x,w,A,L){return w=Object.assign({},w,{zoom:Math.floor(w.zoom)}),super.evaluate(x,w,A,L)}}let QK;function dct(k,x){return x>0?x+2*k:k}const fds=Hn([{name:"a_pos_offset",components:4,type:"Int16"},{name:"a_tex_size",components:4,type:"Uint16"},{name:"a_pixeloffset",components:4,type:"Int16"}],4),xds=Hn([{name:"a_globe_anchor",components:3,type:"Int16"},{name:"a_globe_normal",components:3,type:"Float32"}],4),gds=Hn([{name:"a_projected_pos",components:4,type:"Float32"}],4);Hn([{name:"a_fade_opacity",components:1,type:"Uint32"}],4);const yds=Hn([{name:"a_auto_z_offset",components:1,type:"Float32"}],4),vds=Hn([{name:"a_feature_index",components:1,type:"Float32"}],4),bds=Hn([{name:"a_x_axis",components:3,type:"Float32"},{name:"a_y_axis",components:3,type:"Float32"}]),_ds=Hn([{name:"a_texb",components:2,type:"Uint16"}]),wds=Hn([{name:"a_placed",components:2,type:"Uint8"},{name:"a_shift",components:2,type:"Float32"},{name:"a_elevation_from_sea",components:2,type:"Float32"}]),jds=Hn([{name:"a_size_scale",components:1,type:"Float32"},{name:"a_padding",components:2,type:"Float32"},{name:"a_auto_z_offset",components:1,type:"Float32"}]);Hn([{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 uct=Hn([{name:"a_pos",components:3,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4),Nds=Hn([{name:"a_pos_2f",components:2,type:"Float32"},{name:"a_radius",components:1,type:"Float32"},{name:"a_flags",components:2,type:"Int16"}],4);Hn([{name:"triangle",components:3,type:"Uint16"}]),Hn([{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"}]),Hn([{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"}]),Hn([{type:"Float32",name:"offsetX"}]),Hn([{type:"Int16",name:"x"},{type:"Int16",name:"y"}]);const yRe=class N4e{constructor(x=null,w=0,A=4096){this.batchIndex=w,this.headerBuffer=null,this.propertiesBuffer=null,this.blockIndicesBuffer=null,this.context=x||null,this.propsDwords=A,this.totalBytes=4*this.propsDwords,this.headerData=new Uint32Array(N4e.HEADER_DWORDS),this.propertiesData=new Float32Array(this.propsDwords),this.blockIndicesData=new Uint32Array(this.propsDwords);for(let L=0;Lx.maxUniformBlockSize)throw new Error(`UBO size ${this.totalBytes} exceeds device limit ${x.maxUniformBlockSize}`);if(this.headerBuffer=w.createBuffer(),!this.headerBuffer)throw new Error("Failed to create header UBO buffer");if(w.bindBuffer(w.UNIFORM_BUFFER,this.headerBuffer),w.bufferData(w.UNIFORM_BUFFER,N4e.HEADER_BYTES,w.DYNAMIC_DRAW),this.propertiesBuffer=w.createBuffer(),!this.propertiesBuffer)throw new Error("Failed to create properties UBO buffer");if(w.bindBuffer(w.UNIFORM_BUFFER,this.propertiesBuffer),w.bufferData(w.UNIFORM_BUFFER,this.totalBytes,w.DYNAMIC_DRAW),this.blockIndicesBuffer=w.createBuffer(),!this.blockIndicesBuffer)throw new Error("Failed to create block-indices UBO buffer");w.bindBuffer(w.UNIFORM_BUFFER,this.blockIndicesBuffer),w.bufferData(w.UNIFORM_BUFFER,this.totalBytes,w.DYNAMIC_DRAW),w.bindBuffer(w.UNIFORM_BUFFER,null)}writeHeader(x){const w=this.headerData;w[0]=x.dataDrivenMask,w[1]=x.zoomDependentMask,w[2]=x.dataDrivenBlockSizeVec4,w[3]=x.offsets[0],w[4]=x.offsets[1],w[5]=x.offsets[2],w[6]=x.offsets[3],w[7]=x.offsets[4],w[8]=x.offsets[5],w[9]=x.offsets[6],w[10]=x.offsets[7],w[11]=x.offsets[8]}writeDataDrivenBlock(x,w,A){const L=4*A.dataDrivenBlockSizeVec4;if(L===0)return;const F=w*L;if(F+L>this.propertiesData.length)throw new Error(`UBO write out of bounds: feature index ${w} exceeds propertiesData capacity`);for(let U=0;U<9;U++)A.dataDrivenMask&1<{if(!K)return;const oe=A.getUniformBlockIndex(w,U);oe!==A.INVALID_INDEX&&(A.uniformBlockBinding(w,oe,X),A.bindBufferBase(A.UNIFORM_BUFFER,X,K))},F=3*this.batchIndex;L("SymbolPaintPropertiesHeaderUniform",this.headerBuffer,F),L("SymbolPaintPropertiesUniform",this.propertiesBuffer,F+1),L("SymbolPaintPropertiesIndexUniform",this.blockIndicesBuffer,F+2)}destroy(){if(this.context){const x=this.context.gl;this.headerBuffer&&(x.deleteBuffer(this.headerBuffer),this.headerBuffer=null),this.propertiesBuffer&&(x.deleteBuffer(this.propertiesBuffer),this.propertiesBuffer=null),this.blockIndicesBuffer&&(x.deleteBuffer(this.blockIndicesBuffer),this.blockIndicesBuffer=null)}}};yRe.HEADER_DWORDS=12,yRe.HEADER_BYTES=48;let vRe=yRe;function bRe(k,x,w,A){return[Dz(255*k,255*x),Dz(255*w,255*A)]}function hct(k,x,w,A,L,F,U,K){return!!k&&(k.kind==="constant"?k.value==="none":k.kind==="composite"||k.kind==="source"?k.evaluate({zoom:0,brightness:F,worldview:K},x,w,L,A,U)==="none":typeof k=="string"&&k==="none")}jr(vRe,"SymbolPropertiesUBO",{omit:["headerBuffer","propertiesBuffer","blockIndicesBuffer"]});class _Re{constructor(x,w,A,L,F="",U,K){this.layer=x,this.zoom=w,this.lut=A,this.isText=L,this.propDefs=this._getPropDefs(),this.worldview=F,this.maxUniformBufferBindings=U||24,this.uboSizeDwords=K||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(x,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 x=this.isText?"text":"icon";return[{name:`${x}-color`,useThemeName:`${x}-color-use-theme`,isColor:!0},{name:`${x}-halo-color`,useThemeName:`${x}-halo-color-use-theme`,isColor:!0},{name:`${x}-opacity`,useThemeName:null,isColor:!1},{name:`${x}-halo-width`,useThemeName:null,isColor:!1},{name:`${x}-halo-blur`,useThemeName:null,isColor:!1},{name:`${x}-emissive-strength`,useThemeName:null,isColor:!1},{name:`${x}-occlusion-opacity`,useThemeName:null,isColor:!1},{name:"symbol-z-offset",useThemeName:null,isColor:!1},{name:`${x}-translate`,useThemeName:null,isColor:!1,isVec2:!0}]}buildHeader(){const x=this.layer.paint,w=this.propDefs;let A=0,L=0,F=0,U=0;const K=[0,0,0,0,0,0,0,0,0];for(let X=0;X<9;X++){const{name:oe,isColor:ge,isVec2:we}=w[X],je=x.get(oe),Le=!(!je||typeof je.isConstant!="function"||je.isConstant()),Re=this._appearancesHavePaintProperties(oe),We=Le||Re,et=!(!je||!je.value||je.value.kind!=="composite"),it=this.layer._transitionablePaint._values[oe],yt=!We&&(it&&it.value&&it.value.expression&&it.value.expression.kind)==="camera";We?(A|=1<w.hasPaintProperty(x):this.isText?w=>w.hasTextPaintProperties():w=>w.hasIconPaintProperties())}_checkIfAllPropertiesAreConstant(x,w){const A=x.paint,L=w?"text":"icon",F=[`${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 U of F){const K=A.get(U);if(K&&typeof K=="object"&&"isConstant"in K&&!K.isConstant())return!1}return!this._appearancesHavePaintProperties()}_hashDataDrivenValues(x,w){if(w.dataDrivenMask===0)return"";const A=[];for(let L=0;L<9;L++){if(!(w.dataDrivenMask&1<=Re){Br(`Too many symbol features: batch ${je} requires binding points up to ${3*je+2}, device limit ${Re}. Some features will render incorrectly.`);const et={batchIndex:0,localFeatureIndex:0,vtFeatureIndex:w,featureId:X};return this.allFeatures.push(et),X!=null&&(this.featureVertexRangesFromId.has(X)||this.featureVertexRangesFromId.set(X,[]),this.featureVertexRangesFromId.get(X).push(et)),0}this.ubos[je]||(this.ubos[je]=new vRe(K,je,this.uboSizeDwords),this.ubos[je].writeHeader(oe)),this.ubos[je].writeDataDrivenBlock(ge,Le,oe);const We={batchIndex:je,localFeatureIndex:Le,vtFeatureIndex:w,featureId:X};return this.allFeatures.push(We),X!=null&&(this.featureVertexRangesFromId.has(X)||this.featureVertexRangesFromId.set(X,[]),this.featureVertexRangesFromId.get(X).push(We)),Le}updateFeatures(x,w,A,L,F,U,K){if(this.layer=w,this.cachedConstantUniforms=null,!this.cachedHeader)return;const X=this.cachedHeader;for(const oe of x){const ge=this.featureVertexRangesFromId.get(oe);if(!ge)continue;const we=U[oe]||{};for(const je of ge){if(!A)continue;const Le=A.feature(je.vtFeatureIndex);if(!Le)continue;const Re={type:Le.type,id:oe,properties:Le.properties||{},geometry:[]},We=this.activeAppearanceByVtIndex?this.activeAppearanceByVtIndex.get(je.vtFeatureIndex):void 0,et=this.evaluateAllProperties(Re,we,L,F,K,void 0,We);this.ubos[je.batchIndex]&&this.ubos[je.batchIndex].writeDataDrivenBlock(et,je.localFeatureIndex,X)}}}updateDynamicExpressions(x,w,A,L,F,U){if(this.layer=x,this.cachedConstantUniforms=null,!this.cachedHeader)return;const K=this.cachedHeader;for(const X of this.allFeatures){if(!w)continue;const oe=w.feature(X.vtFeatureIndex);if(!oe)continue;const ge=X.featureId!=null&&F[X.featureId]||{},we={type:oe.type,id:X.featureId,properties:oe.properties||{},geometry:[]},je=this.activeAppearanceByVtIndex?this.activeAppearanceByVtIndex.get(X.vtFeatureIndex):void 0,Le=this.evaluateAllProperties(we,ge,A,L,U,void 0,je);this.ubos[X.batchIndex]&&this.ubos[X.batchIndex].writeDataDrivenBlock(Le,X.localFeatureIndex,K)}}updateFeaturePaintForAppearance(x,w,A,L,F,U,K){if(!this.layer||(this.activeAppearanceByVtIndex||(this.activeAppearanceByVtIndex=new Map),this.activeAppearanceByVtIndex.set(x,K||null),!this.cachedHeader))return!1;const X=this.cachedHeader;if(X.dataDrivenMask===0)return!1;let oe=!1;for(const ge of this.allFeatures){if(ge.vtFeatureIndex!==x)continue;const we=this.evaluateAllProperties(w,A,L,F,U,void 0,K);this.ubos[ge.batchIndex]&&(this.ubos[ge.batchIndex].writeDataDrivenBlock(we,ge.localFeatureIndex,X),oe=!0)}return oe}getConstantUniformValues(x,w){const A=this.cachedHeader,L=!(!A||!A.cameraMask);if(this.cachedConstantUniforms&&this.cachedConstantBrightness===w&&(!L||this.cachedConstantRenderZoom===x))return this.cachedConstantUniforms;const F=this.layer.paint,U=this.propDefs,K=L?new $i(x,{brightness:w,worldview:this.worldview}):null,X={type:1,id:void 0,properties:{},geometry:[]},oe=je=>{const Le=U[je],Re=F.get(Le.name);if(!Re)return[0,0,0,1];const We=Le.useThemeName?F.get(Le.useThemeName):void 0,et=hct(We&&typeof We!="string"?We.value:void 0,X,{},[],void 0,w,void 0,this.worldview)?null:this.lut;let it;it=A&&A.cameraMask&1<{const Re=F.get(U[je].name);if(!Re)return Le;if(A&&A.cameraMask&1<{A.text=function(L,F,U){const K=F.layout.get("text-transform").evaluate(U,{});return K==="uppercase"?L=L.toLocaleUpperCase():K==="lowercase"&&(L=L.toLocaleLowerCase()),Xg.applyArabicShaping&&(L=Xg.applyArabicShaping(L)),L}(A.text,x,w)}),k}const JK={"!":"︕","#":"#",$:"$","%":"%","&":"&","(":"︵",")":"︶","*":"*","+":"+",",":"︐","-":"︲",".":"・","/":"/",":":"︓",";":"︔","<":"︿","=":"=",">":"﹀","?":"︖","@":"@","[":"﹇","\\":"\","]":"﹈","^":"^",_:"︳","`":"`","{":"︷","|":"―","}":"︸","~":"~","¢":"¢","£":"£","¥":"¥","¦":"¦","¬":"¬","¯":" ̄","–":"︲","—":"︱","‘":"﹃","’":"﹄","“":"﹁","”":"﹂","…":"︙","‧":"・","₩":"₩","、":"︑","。":"︒","〈":"︿","〉":"﹀","《":"︽","》":"︾","「":"﹁","」":"﹂","『":"﹃","』":"﹄","【":"︻","】":"︼","〔":"︹","〕":"︺","〖":"︗","〗":"︘","!":"︕","(":"︵",")":"︶",",":"︐","-":"︲",".":"・",":":"︓",";":"︔","<":"︿",">":"﹀","?":"︖","[":"﹇","]":"﹈","_":"︳","{":"︷","|":"―","}":"︸","⦅":"︵","⦆":"︶","。":"︒","「":"﹁","」":"﹂","←":"↑","→":"↓"};function Sds(k){return k==="︶"||k==="﹈"||k==="︸"||k==="﹄"||k==="﹂"||k==="︾"||k==="︼"||k==="︺"||k==="︘"||k==="﹀"||k==="︐"||k==="︓"||k==="︔"||k==="`"||k===" ̄"||k==="︑"||k==="︒"}function Cds(k){return k==="︵"||k==="﹇"||k==="︷"||k==="﹃"||k==="﹁"||k==="︽"||k==="︻"||k==="︹"||k==="︗"||k==="︿"}const wRe=4294967296,mct=1/wRe,pct=typeof TextDecoder>"u"?null:new TextDecoder("utf-8");let Jie=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,x,w=this.length){for(;this.pos>3,F=this.pos;this.type=7&A,k(L,x,this),this.pos===F&&this.skip(A)}return x}readMessage(k,x){return this.readFields(k,x,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)*wRe;return this.pos+=8,k}readSFixed64(){const k=this.dataView.getUint32(this.pos,!0)+this.dataView.getInt32(this.pos+4,!0)*wRe;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 x=this.buf;let w,A;return A=x[this.pos++],w=127&A,A<128?w:(A=x[this.pos++],w|=(127&A)<<7,A<128?w:(A=x[this.pos++],w|=(127&A)<<14,A<128?w:(A=x[this.pos++],w|=(127&A)<<21,A<128?w:(A=x[this.pos],w|=(15&A)<<28,function(L,F,U){const K=U.buf;let X,oe;if(oe=K[U.pos++],X=(112&oe)>>4,oe<128||(oe=K[U.pos++],X|=(127&oe)<<3,oe<128)||(oe=K[U.pos++],X|=(127&oe)<<10,oe<128)||(oe=K[U.pos++],X|=(127&oe)<<17,oe<128)||(oe=K[U.pos++],X|=(127&oe)<<24,oe<128)||(oe=K[U.pos++],X|=(1&oe)<<31,oe<128))return Hz(L,X,F);throw new Error("Expected varint not more than 10 bytes")}(w,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,x=this.pos;return this.pos=k,k-x>=12&&pct?pct.decode(this.buf.subarray(x,k)):function(w,A,L){let F="",U=A;for(;U239?4:K>223?3:K>191?2:1;if(U+je>L)break;je===1?K<128&&(we=K):je===2?(X=w[U+1],(192&X)==128&&(we=(31&K)<<6|63&X,we<=127&&(we=null))):je===3?(X=w[U+1],oe=w[U+2],(192&X)==128&&(192&oe)==128&&(we=(15&K)<<12|(63&X)<<6|63&oe,(we<=2047||we>=55296&&we<=57343)&&(we=null))):je===4&&(X=w[U+1],oe=w[U+2],ge=w[U+3],(192&X)==128&&(192&oe)==128&&(192&ge)==128&&(we=(15&K)<<18|(63&X)<<12|(63&oe)<<6|63&ge,(we<=65535||we>=1114112)&&(we=null))),we===null?(we=65533,je=1):we>65535&&(we-=65536,F+=String.fromCharCode(we>>>10&1023|55296),we=56320|1023&we),F+=String.fromCharCode(we),U+=je}return F}(this.buf,x,k)}readBytes(){const k=this.readVarint()+this.pos,x=this.buf.subarray(this.pos,k);return this.pos=k,x}readPackedVarint(k=[],x){const w=this.readPackedEnd();for(;this.pos127;);else if(x===2)this.pos=this.readVarint()+this.pos;else if(x===5)this.pos+=4;else{if(x!==1)throw new Error(`Unimplemented type: ${x}`);this.pos+=8}}writeTag(k,x){this.writeVarint(k<<3|x)}realloc(k){let x=this.length||16;for(;x268435455||k<0?function(x,w){let A,L;if(x>=0?(A=x%4294967296|0,L=x/4294967296|0):(A=~(-x%4294967296),L=~(-x/4294967296),4294967295^A?A=A+1|0:(A=0,L=L+1|0)),x>=18446744073709552e3||x<-18446744073709552e3)throw new Error("Given varint doesn't fit into 10 bytes");w.realloc(10),function(F,U,K){K.buf[K.pos++]=127&F|128,F>>>=7,K.buf[K.pos++]=127&F|128,F>>>=7,K.buf[K.pos++]=127&F|128,F>>>=7,K.buf[K.pos++]=127&F|128,K.buf[K.pos]=127&(F>>>=7)}(A,0,w),function(F,U){const K=(7&F)<<4;U.buf[U.pos++]|=K|((F>>>=3)?128:0),F&&(U.buf[U.pos++]=127&F|((F>>>=7)?128:0),F&&(U.buf[U.pos++]=127&F|((F>>>=7)?128:0),F&&(U.buf[U.pos++]=127&F|((F>>>=7)?128:0),F&&(U.buf[U.pos++]=127&F|((F>>>=7)?128:0),F&&(U.buf[U.pos++]=127&F)))))}(L,w)}(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 x=this.pos;this.pos=function(A,L,F){for(let U,K,X=0;X55295&&U<57344){if(!K){U>56319||X+1===L.length?(A[F++]=239,A[F++]=191,A[F++]=189):K=U;continue}if(U<56320){A[F++]=239,A[F++]=191,A[F++]=189,K=U;continue}U=K-55296<<10|U-56320|65536,K=null}else K&&(A[F++]=239,A[F++]=191,A[F++]=189,K=null);U<128?A[F++]=U:(U<2048?A[F++]=U>>6|192:(U<65536?A[F++]=U>>12|224:(A[F++]=U>>18|240,A[F++]=U>>12&63|128),A[F++]=U>>6&63|128),A[F++]=63&U|128)}return F}(this.buf,k,this.pos);const w=this.pos-x;w>=128&&fct(x,w,this),this.pos=x-1,this.writeVarint(w),this.pos+=w}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 x=k.length;this.writeVarint(x),this.realloc(x);for(let w=0;w=128&&fct(w,A,this),this.pos=w-1,this.writeVarint(A),this.pos+=A}writeMessage(k,x,w){this.writeTag(k,2),this.writeRawMessage(x,w)}writePackedVarint(k,x){x.length&&this.writeMessage(k,Ads,x)}writePackedSVarint(k,x){x.length&&this.writeMessage(k,Eds,x)}writePackedBoolean(k,x){x.length&&this.writeMessage(k,Pds,x)}writePackedFloat(k,x){x.length&&this.writeMessage(k,Tds,x)}writePackedDouble(k,x){x.length&&this.writeMessage(k,Mds,x)}writePackedFixed32(k,x){x.length&&this.writeMessage(k,Lds,x)}writePackedSFixed32(k,x){x.length&&this.writeMessage(k,Ids,x)}writePackedFixed64(k,x){x.length&&this.writeMessage(k,Dds,x)}writePackedSFixed64(k,x){x.length&&this.writeMessage(k,Rds,x)}writeBytesField(k,x){this.writeTag(k,2),this.writeBytes(x)}writeFixed32Field(k,x){this.writeTag(k,5),this.writeFixed32(x)}writeSFixed32Field(k,x){this.writeTag(k,5),this.writeSFixed32(x)}writeFixed64Field(k,x){this.writeTag(k,1),this.writeFixed64(x)}writeSFixed64Field(k,x){this.writeTag(k,1),this.writeSFixed64(x)}writeVarintField(k,x){this.writeTag(k,0),this.writeVarint(x)}writeSVarintField(k,x){this.writeTag(k,0),this.writeSVarint(x)}writeStringField(k,x){this.writeTag(k,2),this.writeString(x)}writeFloatField(k,x){this.writeTag(k,5),this.writeFloat(x)}writeDoubleField(k,x){this.writeTag(k,1),this.writeDouble(x)}writeBooleanField(k,x){this.writeVarintField(k,+x)}};function Hz(k,x,w){return w?4294967296*x+(k>>>0):4294967296*(x>>>0)+(k>>>0)}function fct(k,x,w){const A=x<=16383?1:x<=2097151?2:x<=268435455?3:Math.floor(Math.log(x)/(7*Math.LN2));w.realloc(A);for(let L=w.pos-1;L>=k;L--)w.buf[L+A]=w.buf[L]}function Ads(k,x){for(let w=0;w=0&&A>=x&&eoe[this.text.charCodeAt(A)];A--)w--;this.text=this.text.substring(x,w),this.sectionIndex=this.sectionIndex.slice(x,w)}substring(x,w){const A=new Gz;return A.text=this.text.substring(x,w),A.sectionIndex=this.sectionIndex.slice(x,w),A.sections=this.sections,A}toString(){return this.text}getMaxScale(){return this.sectionIndex.reduce((x,w)=>Math.max(x,this.sections[w].scale),0)}addTextSection(x,w){this.text+=x.text,this.sections.push(eY.forText(x.scale,x.fontStack||w));const A=this.sections.length-1;for(let L=0;L=63743?null:++this.imageSectionID:(this.imageSectionID=57344,this.imageSectionID)}}function jRe(k,x,w,A,L,F,U,K,X,oe,ge,we,je,Le,Re,We=1,et=1){const it=Gz.fromFeature(k,L,We,et);we===$1.vertical&&it.verticalizePunctuation(je);let yt=[];const ht=function(ds,_s,gs,ys,vn,wn,Pn=1){if(!ds)return[];const On=[],Ln=function(Rn,qn,tr,pr,na,Cr,kr=1){let fr=0;for(let Qr=0;Qr=0;let gn=0;for(let Rn=0;Rn0&&Qg>lo&&(lo=Qg)}else{const gf=gs[wu.fontStack];if(!gf)continue;gf[ju]&&(th=gf[ju]);const Y0=_s[wu.fontStack];if(!Y0)continue;const Hx=Y0.glyphs[ju];if(!Hx)continue;if(Jh=Hx.metrics,qp=ju!==8203?Bp:0,kr){const Pu=Y0.ascender!==void 0?Math.abs(Y0.ascender):0,Qg=Y0.descender!==void 0?Math.abs(Y0.descender):0,yf=(Pu+Qg)*eh;Mu-w/2;){if(U--,U<0)return!1;K-=k[U].dist(F),F=k[U]}K+=k[U].dist(k[U+1]),U++;const X=[];let oe=0;for(;KA;)oe-=X.shift().angleDelta;if(oe>L)return!1;U++,K+=ge.dist(we)}return!0}function kct(k){let x=0;for(let w=0;woe){const Re=(oe-X)/Le,We=Ar(we.x,je.x,Re),et=Ar(we.y,je.y,Re),it=new l3(We,et,0,je.angleTo(we),ge);return!U||Nct(k,it,K,U,x)?it:void 0}X+=Le}}function $ds(k,x,w,A,L,F,U,K,X){const oe=Sct(A,F,U),ge=Cct(A,L),we=ge*U,je=k[0].x===0||k[0].x===X||k[0].y===0||k[0].y===X;return x-we=0&&Et=0&&It=0&&je+oe<=ge){const Ot=new l3(Et,It,0,yt,Re);A&&!Nct(k,Ot,F,A,L)||Le.push(Ot)}}we+=it}return K||Le.length||U||(Le=Act(k,we/2,w,A,L,F,U,!0,X)),Le}function Ect(k){let x=0,w=0;for(const U of k)x+=U.w*U.h,w=Math.max(w,U.w);k.sort((U,K)=>K.h-U.h);const A=[{x:0,y:0,w:Math.max(Math.ceil(Math.sqrt(x/.95)),w),h:1/0}];let L=0,F=0;for(const U of k)for(let K=A.length-1;K>=0;K--){const X=A[K];if(!(U.w>X.w||U.h>X.h)){if(U.x=X.x,U.y=X.y,F=Math.max(F,U.y+U.h),L=Math.max(L,U.x+U.w),U.w===X.w&&U.h===X.h){const oe=A.pop();oe&&Kx.id?1:k.versionx.version?1:k.sxx.sx?1:k.syx.sy?1:0}function ARe(k){let x=0;for(let w=0;w0,Tct(x,A,this.iconDescriptors,F),Tct(w,A,this.patternDescriptors,F),this.iconDescriptors.sort(soe),this.patternDescriptors.sort(soe);let U=0;const K=L?L.data:"";K&&(U=ok(U,ARe(K))),U=ok(U,1);for(const X of this.iconDescriptors)U=ok(U,ARe(X.id)),U=ok(U,X.version),U=ok(U,X.sx),U=ok(U,X.sy);U=ok(U,1);for(const X of this.patternDescriptors)U=ok(U,ARe(X.id)),U=ok(U,X.version),U=ok(U,X.sx),U=ok(U,X.sy);this.hash=U}subsetOf(x){return this.isSubsetArray(this.iconDescriptors,x.iconDescriptors,soe)&&this.isSubsetArray(this.patternDescriptors,x.patternDescriptors,soe)}isSubsetArray(x,w,A){let L=0,F=0;if(x.length>w.length)return!1;for(;L{const U=L.variant.id.toString().localeCompare(F.variant.id.toString());return U!==0?U:L.variant.sx!==F.variant.sx?L.variant.sx-F.variant.sx:L.variant.sy!==F.variant.sy?L.variant.sy-F.variant.sy:0});const A=new Map;for(const L of w)A.set(L.key,L.value);return A}class Mct{constructor(x){this.sourceAtlasHash=x}}class Pct{constructor(x,w,A,L){const F=new Map,U=new Map;this.haveRenderCallbacks=[];const K=[],X=L!==void 0,oe=X?new Map:void 0,ge=X?MRe(x,oe):x,we=X?MRe(w,oe):w;this.addImages(ge,F,1,K),this.addImages(we,U,2,K);const{w:je,h:Le}=Ect(K),Re=new wg({width:je||1,height:Le||1});for(const[We,et]of ge.entries()){const it=F.get(We).paddedRect;wg.copy(et.data,Re,{x:0,y:0},{x:it.x+1,y:it.y+1},et.data,null,et.sdf)}for(const[We,et]of we.entries()){const it=U.get(We),yt=it.paddedRect;let ht=it.padding;const Et=yt.x+ht,It=yt.y+ht,Ot=et.data.width,ws=et.data.height;ht=ht>1?ht-1:ht,wg.copy(et.data,Re,{x:0,y:0},{x:Et,y:It},et.data,A),wg.copy(et.data,Re,{x:0,y:ws-ht},{x:Et,y:It-ht},{width:Ot,height:ht},A),wg.copy(et.data,Re,{x:0,y:0},{x:Et,y:It+ws},{width:Ot,height:ht},A),wg.copy(et.data,Re,{x:Ot-ht,y:0},{x:Et-ht,y:It},{width:ht,height:ws},A),wg.copy(et.data,Re,{x:0,y:0},{x:Et+Ot,y:It},{width:ht,height:ws},A),wg.copy(et.data,Re,{x:Ot-ht,y:ws-ht},{x:Et-ht,y:It-ht},{width:ht,height:ht},A),wg.copy(et.data,Re,{x:0,y:ws-ht},{x:Et+Ot,y:It-ht},{width:ht,height:ht},A),wg.copy(et.data,Re,{x:0,y:0},{x:Et+Ot,y:It+ws},{width:ht,height:ht},A),wg.copy(et.data,Re,{x:Ot-ht,y:0},{x:Et-ht,y:It+ws},{width:ht,height:ht},A)}this.lut=A,this.image=Re,this.iconPositions=F,this.patternPositions=U,X&&(this.contentDescriptor=new ERe(ge,we,L,A,oe))}addImages(x,w,A,L){for(const[F,U]of x.entries()){const{bin:K,imagePosition:X,imageVariant:oe}=TRe(F,U,A);w.set(F,X),L.push(K),U.hasRenderCallback&&this.haveRenderCallbacks.push(oe.id)}}patchUpdatedImages(x,w,A,L){this.haveRenderCallbacks=this.haveRenderCallbacks.filter(F=>x.hasImage(F,A)),x.dispatchRenderCallbacks(this.haveRenderCallbacks,A);for(const F of x.getUpdatedImages(A)){for(const U of this.iconPositions.keys()){const K=Ud.parse(U);if(zm.isEqual(K.id,F)){const X=x.getImage(F,A);this.patchUpdatedImage(this.iconPositions.get(U),X,w,null)}}for(const U of this.patternPositions.keys()){const K=Ud.parse(U);if(zm.isEqual(K.id,F)){const X=x.getImage(F,A);this.patchUpdatedImage(this.patternPositions.get(U),X,w,L||this.lut)}}}}patchUpdatedImage(x,w,A,L=null){if(!x||!w||x.version===w.version)return;x.version=w.version;const[F,U]=x.tl,K=x.sdf;if(this.lut||K){const X={width:w.data.width,height:w.data.height},oe=new wg(X);wg.copy(w.data,oe,{x:0,y:0},{x:0,y:0},X,L,K),A.update(oe,{position:{x:F,y:U},recreateWhenResize:!1})}else A.update(w.data,{position:{x:F,y:U},recreateWhenResize:!1})}}jr(tY,"ImagePosition"),jr(Pct,"ImageAtlas",{omit:["lut"]}),jr(Mct,"ImageAtlasReference");class sY{constructor(x){this.pendingRequests=new Map,this.cachedRanges=new Map,this.useServerFontComposition=!x||x.useServerFontComposition===void 0||x.useServerFontComposition}loadGlyphRange(x,w,A,L,F){if(this.useServerFontComposition)return void sY.loadGlyphRange(x,w,A,L,F);const U=x.split(",").map(K=>K.trim()).filter(K=>K.length>0);U.length!==0?U.length!==1?this._loadMultipleFonts(U,w,A,L,F):this._loadFont(U[0],w,A,L,F):F(new Error("Empty fontstack"))}_loadMultipleFonts(x,w,A,L,F){const U=x.map(()=>null),K={completed:0,firstError:null,callbackCalled:!1},X=(oe,ge,we)=>{if(!K.callbackCalled&&(ge&&!K.firstError&&(K.firstError=ge),we&&(U[oe]=we),K.completed++,K.completed===x.length)){K.callbackCalled=!0;const je=U.filter(Re=>Re!==null);if(je.length===0)return void F(K.firstError||new Error("All fonts failed to load"));const Le=this._composeGlyphs(je);F(null,Le)}};for(let oe=0;oe{X(oe,ge,we)})}_loadFont(x,w,A,L,F){const U=`${x}:${w}`;if(this.cachedRanges.has(U)){const X=this.cachedRanges.get(U);return void da.frame(()=>F(null,X))}const K=this.pendingRequests.get(U);K?K.push(F):(this.pendingRequests.set(U,[F]),sY.loadGlyphRange(x,w,A,L,(X,oe)=>{X||this.cachedRanges.set(U,oe||null);const ge=this.pendingRequests.get(U);if(this.pendingRequests.delete(U),ge)for(const we of ge)we(X,oe)}))}_composeGlyphs(x){const w={};let A,L;for(const F of x)if(A===void 0&&F.ascender!==void 0&&(A=F.ascender),L===void 0&&F.descender!==void 0&&(L=F.descender),F.glyphs)for(const U in F.glyphs)w[U]===void 0&&(w[U]=F.glyphs[U]);return{glyphs:w,ascender:A,descender:L}}}sY.loadGlyphRange=function(k,x,w,A,L){const F=256*x,U=F+255,K=A.transformRequest(A.normalizeGlyphsURL(w).replace("{fontstack}",k).replace("{range}",`${F}-${U}`),xg.Glyphs);Gg(K,(X,oe)=>{if(X)L(X);else if(oe){const ge={},we=function(je){return new Jie(je).readFields(Fds,{})}(oe);for(const je of we.glyphs)ge[je.id]=je;L(null,{glyphs:ge,ascender:we.ascender,descender:we.descender})}})};const nY=1e20;function Lct(k,x,w,A,L,F,U,K,X){for(let oe=x;oe-1);X++,F[X]=K,U[X]=oe,U[X+1]=nY}for(let K=0,X=0;K{if(U){L.ascender=U.ascender,L.descender=U.descender;for(const K in U.glyphs)this._doesCharSupportLocalGlyph(+K)||(L.glyphs[+K]=U.glyphs[+K]);L.ranges[w]=!0}for(const K of L.requests[w]||[])K(F,U);delete L.requests[w]}))}getGlyphs(x,w){const A=[],L=this.url||di.GLYPHS_URL;for(const F in x)for(const U of x[F])A.push({stack:F,id:U});es(A,({stack:F,id:U},K)=>{let X=this.entries[F];X||(X=this.entries[F]={glyphs:{},requests:{},ranges:{},ascender:void 0,descender:void 0});let oe=X.glyphs[U];if(oe!==void 0)return void K(null,{stack:F,id:U,glyph:oe});if(oe=this._tinySDF(X,F,U),oe)return X.glyphs[U]=oe,void K(null,{stack:F,id:U,glyph:oe});const ge=Math.floor(U/256);if(256*ge>65535)return Br("glyphs > 65535 not supported"),void K(null,{stack:F,id:U,glyph:oe});if(X.ranges[ge])return void K(null,{stack:F,id:U,glyph:oe});let we=X.requests[ge];we||(we=X.requests[ge]=[],this.glyphLoader.loadGlyphRange(F,ge,L,this.requestManager,(je,Le)=>{if(Le){X.ascender=Le.ascender,X.descender=Le.descender;for(const Re in Le.glyphs)this._doesCharSupportLocalGlyph(+Re)||(X.glyphs[+Re]=Le.glyphs[+Re]);X.ranges[ge]=!0}for(const Re of we)Re(je,Le);delete X.requests[ge]})),we.push((je,Le)=>{je?K(je):Le&&K(null,{stack:F,id:U,glyph:Le.glyphs[U]||null})})},(F,U)=>{if(F)w(F);else if(U){const K={};for(const{stack:X,id:oe,glyph:ge}of U)K[X]===void 0&&(K[X]={}),K[X].glyphs===void 0&&(K[X].glyphs={}),K[X].glyphs[oe]=ge&&{id:ge.id,bitmap:ge.bitmap.clone(),metrics:ge.metrics},K[X].ascender=this.entries[X].ascender,K[X].descender=this.entries[X].descender;w(null,K)}})}_doesCharSupportLocalGlyph(x){return this.localGlyphMode!==PRe.none&&(this.localGlyphMode===PRe.all?!!this.localFontFamily:!!this.localFontFamily&&(vg(x)||uw(x)||I1(x)||Fp(x)||Vb(x)||r2(x)||(w=x)>=131072&&w<=173791||(A=>A>=66736&&A<=66815)(x)));var w}_tinySDF(x,w,A){const L=this.localFontFamily;if(!L||!this._doesCharSupportLocalGlyph(A))return;let F=x.tinySDF;if(!F){let et="400";/bold/i.test(w)?et="900":/medium/i.test(w)?et="500":/light/i.test(w)&&(et="200"),F=x.tinySDF=new noe.TinySDF({fontFamily:L,fontWeight:et,fontSize:48,buffer:6,radius:16}),F.fontWeight=et}const U=F.fontWeight;if(this.localGlyphs[U][A])return this.localGlyphs[U][A];const K=String.fromCodePoint(A),{data:X,width:oe,height:ge,glyphWidth:we,glyphHeight:je,glyphLeft:Le,glyphTop:Re,glyphAdvance:We}=F.draw(K);return this.localGlyphs[U][A]={id:A,bitmap:new oT({width:oe,height:ge},X),metrics:{width:we/2,height:je/2,left:Le/2,top:Re/2-27,advance:We/2,localGlyph:!0}}}}function Dct(k,x){return k+x[1]-x[0]}function LRe(k,x,w,A,L=1){const F=[],U=k.imagePrimary,K=U.pixelRatio,X=U.paddedRect.w-2,oe=U.paddedRect.h-2,ge=(k.right-k.left)*L,we=(k.bottom-k.top)*L,je=U.stretchX||[[0,X]],Le=U.stretchY||[[0,oe]],Re=je.reduce(Dct,0),We=Le.reduce(Dct,0),et=X-Re,it=oe-We;let yt=0,ht=Re,Et=0,It=We,Ot=0,ws=et,ds=0,_s=it;if(U.content&&A){const ys=U.content;yt=roe(je,0,ys[0]),Et=roe(Le,0,ys[1]),ht=roe(je,ys[0],ys[2]),It=roe(Le,ys[1],ys[3]),Ot=ys[0]-yt,ds=ys[1]-Et,ws=ys[2]-ys[0]-ht,_s=ys[3]-ys[1]-It}const gs=(ys,vn,wn,Pn)=>{const On=aoe(ys.stretch-yt,ht,ge,k.left*L),Ln=ioe(ys.fixed-Ot,ws,ys.stretch,Re),Jn=aoe(vn.stretch-Et,It,we,k.top*L),gn=ioe(vn.fixed-ds,_s,vn.stretch,We),Rn=aoe(wn.stretch-yt,ht,ge,k.left*L),qn=ioe(wn.fixed-Ot,ws,wn.stretch,Re),tr=aoe(Pn.stretch-Et,It,we,k.top*L),pr=ioe(Pn.fixed-ds,_s,Pn.stretch,We),na=new Js(On,Jn),Cr=new Js(Rn,Jn),kr=new Js(Rn,tr),fr=new Js(On,tr),Qr=new Js(Ln/K,gn/K),fa=new Js(qn/K,pr/K),Za=x*Math.PI/180;if(Za){const lo=Math.sin(Za),Mu=Math.cos(Za),Il=[Mu,-lo,lo,Mu];na._matMult(Il),Cr._matMult(Il),fr._matMult(Il),kr._matMult(Il)}const Ca=ys.stretch+ys.fixed,zi=wn.stretch+wn.fixed,Ko=vn.stretch+vn.fixed,Bi=Pn.stretch+Pn.fixed,el=k.imageSecondary;return{tl:na,tr:Cr,bl:fr,br:kr,texPrimary:{x:U.paddedRect.x+1+Ca,y:U.paddedRect.y+1+Ko,w:zi-Ca,h:Bi-Ko},texSecondary:el?{x:el.paddedRect.x+1+Ca,y:el.paddedRect.y+1+Ko,w:zi-Ca,h:Bi-Ko}:void 0,writingMode:void 0,glyphOffset:[0,0],sectionIndex:0,pixelOffsetTL:Qr,pixelOffsetBR:fa,minFontScaleX:ws/K/ge,minFontScaleY:_s/K/we,isSDF:w}};if(U.stretchX||U.stretchY){const ys=Rct(je,et,Re),vn=Rct(Le,it,We);for(let wn=0;wn0?[yt,-ht]:Et<0?[-yt,ht]:yt===0?[ht,yt]:[ht,-yt]}(w);let Le=Math.abs(x.top-x.bottom);for(const it of x.positionedLines)Le-=it.lineOffset;const Re=x.positionedLines.length,We=Le/Re;let et=x.top-w[1];for(let it=0;itF)&&(F=Re.x),(!Le||Re.y>U)&&(U=Re.y)}const X=Math.min(F-A,U-L);let oe=X/2;const ge=new _m([],Wds);if(X===0)return new Js(A,L);for(let Le=A;Lewe.d||!we.d)&&(we=Le,w&&console.log("found best %d after %d probes",Math.round(1e4*Le.d)/1e4,je)),Le.max-we.d<=x||(oe=Le.h/2,ge.push(new Kz(Le.p.x-oe,Le.p.y-oe,oe,k)),ge.push(new Kz(Le.p.x+oe,Le.p.y-oe,oe,k)),ge.push(new Kz(Le.p.x-oe,Le.p.y+oe,oe,k)),ge.push(new Kz(Le.p.x+oe,Le.p.y+oe,oe,k)),je+=4)}return w&&(console.log(`num probes: ${je}`),console.log(`best distance: ${we.d}`)),we.p}function Wds(k,x){return x.max-k.max}noe.TinySDF=class{constructor({fontSize:k=24,buffer:x=3,radius:w=8,cutoff:A=.25,fontFamily:L="sans-serif",fontWeight:F="normal",fontStyle:U="normal",lang:K=null}={}){this.buffer=x,this.cutoff=A,this.radius=w,this.lang=K;const X=this.size=k+4*x,oe=this._createCanvas(X),ge=this.ctx=oe.getContext("2d",{willReadFrequently:!0});ge.font=`${U} ${F} ${k}px ${L}`,ge.textBaseline="alphabetic",ge.textAlign="left",ge.fillStyle="black",this.gridOuter=new Float64Array(X*X),this.gridInner=new Float64Array(X*X),this.f=new Float64Array(X),this.z=new Float64Array(X+1),this.v=new Uint16Array(X)}_createCanvas(k){const x=document.createElement("canvas");return x.width=x.height=k,x}draw(k){const{width:x,actualBoundingBoxAscent:w,actualBoundingBoxDescent:A,actualBoundingBoxLeft:L,actualBoundingBoxRight:F}=this.ctx.measureText(k),U=Math.ceil(w),K=Math.max(0,Math.min(this.size-this.buffer,Math.ceil(F-L))),X=Math.min(this.size-this.buffer,U+Math.ceil(A)),oe=K+2*this.buffer,ge=X+2*this.buffer,we=Math.max(oe*ge,0),je=new Uint8ClampedArray(we),Le={data:je,width:oe,height:ge,glyphWidth:K,glyphHeight:X,glyphTop:U,glyphLeft:0,glyphAdvance:x};if(K===0||X===0)return Le;const{ctx:Re,buffer:We,gridInner:et,gridOuter:it}=this;this.lang&&(Re.lang=this.lang),Re.clearRect(We,We,K,X),Re.fillText(k,We,We+U);const yt=Re.getImageData(We,We,K,X);it.fill(nY,0,we),et.fill(0,0,we);for(let ht=0;ht0?ws*ws:0,et[Ot]=ws<0?ws*ws:0}}Lct(it,0,0,oe,ge,oe,this.f,this.v,this.z),Lct(et,We,We,K,X,oe,this.f,this.v,this.z);for(let ht=0;htF.y!=We.y>F.y&&F.x<(We.x-Re.x)*(F.y-Re.y)/(We.y-Re.y)+Re.x&&(K=!K),X=Math.min(X,o2(F,Re,We))}}return(K?1:-1)*Math.sqrt(X)}(this.p,L),this.max=this.d+this.h*Math.SQRT2}}const Kds=Object.keys,IRe=Number.POSITIVE_INFINITY,Yds=Math.sqrt(2);function uT(k,x,w,A,L,F){const U=kRe(k)&&k.collisionPadding?k.collisionPadding:[0,0,0,0],K={top:k.top-U[1],bottom:k.bottom+U[3],left:k.left-U[0],right:k.right+U[2],scaled:!1};return A!==void 0&&function(X,oe){X.top*=oe,X.bottom*=oe,X.left*=oe,X.right*=oe,X.scaled=!0}(K,A),F&&(K.left+=F[0],K.right+=F[0],K.top+=F[1],K.bottom+=F[1]),w&&function(X,oe,ge){if(!oe)return;const we=Ws(oe),je=new Js(ge?ge[0]:0,ge?ge[1]:0),Le=new Js(X.left,X.top),Re=new Js(X.right,X.top),We=new Js(X.left,X.bottom),et=new Js(X.right,X.bottom);Le._rotateAround(we,je),Re._rotateAround(we,je),We._rotateAround(we,je),et._rotateAround(we,je),X.left=Math.min(Le.x,Re.x,We.x,et.x),X.right=Math.max(Le.x,Re.x,We.x,et.x),X.top=Math.min(Le.y,Re.y,We.y,et.y),X.bottom=Math.max(Le.y,Re.y,We.y,et.y)}(K,w,L),x?{top:Math.min(x.top,K.top),bottom:Math.max(x.bottom,K.bottom),left:Math.min(x.left,K.left),right:Math.max(x.right,K.right),scaled:x.scaled||K.scaled}:K}function zct(k,[x,w]){let A=0,L=0;if(w===IRe){x<0&&(x=0);const F=x/Yds;switch(k){case"top-right":case"top-left":L=F-7;break;case"bottom-right":case"bottom-left":L=7-F;break;case"bottom":L=7-x;break;case"top":L=x-7}switch(k){case"top-right":case"bottom-right":A=-F;break;case"top-left":case"bottom-left":A=F;break;case"left":A=x;break;case"right":A=-x}}else{switch(x=Math.abs(x),w=Math.abs(w),k){case"top-right":case"top-left":case"top":L=w-7;break;case"bottom-right":case"bottom-left":case"bottom":L=7-w}switch(k){case"top-right":case"bottom-right":case"right":A=-x;break;case"top-left":case"bottom-left":case"left":A=x}}return[A,L]}function Zds(k,x,w,A,L,F,U,K,X,oe,ge,we,je,Le,Re){const We=k.layers[0],et=We.appearances;if(et.length===0)return{iconBBox:null,iconVerticalBBox:null,textBBox:null,textVerticalBBox:null};const it={iconBBox:null,iconVerticalBBox:null},yt={textBBox:null,textVerticalBBox:null},{baseIconRotate:ht,baseTextRotate:Et,iconScaleFactor:It}=function(ws,ds,_s){const gs=ws.get("icon-rotate").evaluate(ds,{},_s),ys=ws.get("text-rotate").evaluate(ds,{},_s),[vn,wn]=ws.get("icon-size-scale-range");return{baseIconRotate:gs,baseTextRotate:ys,iconScaleFactor:pt(1,vn,wn)}}(A,L,F);x&&(it.iconBBox=uT(x,it.iconBBox,ht),w)&&(it.iconVerticalBBox=uT(w,it.iconVerticalBBox,ht+90));const Ot=loe(we.horizontal);Ot&&(yt.textBBox=uT(Ot,yt.textBBox,Et,1,Le)),we.vertical&&(yt.textVerticalBBox=uT(we.vertical,yt.textVerticalBBox,Et+90,1,Le));for(const ws of et)ws.hasIconLayoutProperties()&&Xds(it,k,We,ws,L,F,K,ht,U,X,x,oe,It,ge,Re),ws.hasTextLayoutProperties()&&Qds(yt,We,ws,L,F,Le,Et,je,Ot,we.vertical);return{iconBBox:it.iconBBox,iconVerticalBBox:it.iconVerticalBBox,textBBox:yt.textBBox,textVerticalBBox:yt.textVerticalBBox}}function Xds(k,x,w,A,L,F,U,K,X,oe,ge,we,je,Le,Re){const{appearanceIconOffset:We,appearanceIconRotate:et,appearanceIconSize:it}=Bct(A,w,L,F,U,K,X,oe.iconScaleFactor);let yt=null,ht=null,Et=null;A.hasLayoutProperty("icon-image")?Et=function(Ot,ws,ds,_s,gs,ys,vn,wn){let Pn=null;const On=ws.getAppearanceValueAndResolveTokens(ds,"icon-image",_s,gs,wn);if(On){const Ln=Ot.getResolvedImageFromTokens(On),Jn=ds.hasLayoutProperty("icon-size")?ds.getUnevaluatedLayoutProperty("icon-size"):ws._unevaluatedLayout._values["icon-size"],gn=rY(Ln,cI(Ot.zoom,Jn,Ot.worldview,wn),Jn,gs,Ot.zoom,_s,Ot.pixelRatio,vn,Ot.worldview,wn);Pn=ys.get(gn.iconPrimary.toString())}return Pn}(x,w,A,L,F,we,je,Re):ge&&(Et=ge.imagePrimary),Et&&(yt=toe(Et,null,We,Le),x.allowVerticalPlacement&&(ht=toe(Et,null,We,Le)));const It=X>0?it/X:1;yt&&(k.iconBBox=uT(yt,k.iconBBox,et,It!==1?It:void 0)),ht&&(k.iconVerticalBBox=uT(ht,k.iconVerticalBBox,et+90,It!==1?It:void 0))}function Bct(k,x,w,A,L,F,U,K){const X=k.hasLayoutProperty("icon-offset")?x.getAppearanceValueAndResolveTokens(k,"icon-offset",w,A,[]):null,oe=X&&Array.isArray(X)?X:L,ge=k.hasLayoutProperty("icon-rotate")?x.getAppearanceValueAndResolveTokens(k,"icon-rotate",w,A,[]):null,we=typeof ge=="number"?ge:F,je=k.hasLayoutProperty("icon-size")?x.getAppearanceValueAndResolveTokens(k,"icon-size",w,A,[]):null;return{appearanceIconOffset:oe,appearanceIconRotate:we,appearanceIconSize:typeof je=="number"?je*K:U}}function Qds(k,x,w,A,L,F,U,K,X,oe){const{appearanceTextOffset:ge,appearanceTextRotate:we,appearanceTextSize:je}=Uct(w,x,A,L,F,U,K),Le=je/K,Re=[(ge[0]-F[0])*Le,(ge[1]-F[1])*Le],We=Re[0]!==0||Re[1]!==0;X&&(k.textBBox=uT(X,k.textBBox,we,Le,ge,We?Re:void 0)),oe&&(k.textVerticalBBox=uT(oe,k.textVerticalBBox,we+90,Le,ge,We?Re:void 0))}function Uct(k,x,w,A,L,F,U){const K=k.hasLayoutProperty("text-offset")?x.getAppearanceValueAndResolveTokens(k,"text-offset",w,A,[]):null,X=K&&Array.isArray(K)?[K[0]*Bp,K[1]*Bp]:L,oe=k.hasLayoutProperty("text-rotate")?x.getAppearanceValueAndResolveTokens(k,"text-rotate",w,A,[]):null,ge=typeof oe=="number"?oe:F,we=k.hasLayoutProperty("text-size")?x.getAppearanceValueAndResolveTokens(k,"text-size",w,A,[]):null;return{appearanceTextOffset:X,appearanceTextRotate:ge,appearanceTextSize:typeof we=="number"?we:U}}function ooe(k,x,w,A,L,F,U,K,X){if(!x||!x.usvg)return;const oe=jct(A),ge=jct(L),we=F!=="both"&&F!=="width"||!_ct(A)?1:ge.width/oe.width,je=F!=="both"&&F!=="height"||!wct(A)?1:ge.height/oe.height;w.scaleSelf(we,je);const Le=w.toString();U.set(Le,w),K.set(Le,x);const{imagePosition:Re}=TRe(Le,x,1);X.set(Le,Re)}function qct(k,x,w,A,L,F,U,K,X,oe){if(!k)return;const ge=function(we,je,Le,Re,We,et,it){if(we.kind==="camera")return we.maxSize;if(we.kind==="composite"){const yt=je.possiblyEvaluate(new $i(we.maxZoom,{worldview:et}),Le,it).evaluate(We,{},Le,it),ht=je.possiblyEvaluate(new $i(we.minZoom,{worldview:et}),Le,it).evaluate(We,{},Le,it);return Math.max(yt,ht)}return je.possiblyEvaluate(new $i(Re,{worldview:et}),Le,it).evaluate(We,{},Le,it)}(x,w,A,L,F,X,oe);return k.scaleSelf(ge*K*U)}function rY(k,x,w,A,L,F,U,K,X,oe){return{iconPrimary:qct(k.getPrimary(),x,w,A,L,F,U,K,X,oe),iconSecondary:qct(k.getSecondary(),x,w,A,L,F,U,K,X,oe)}}function Jds(k,x,w){if(!x)return;const A=w.get(k.toString()),L=w.get(x.toString());A&&L&&(A.paddedRect.w===L.paddedRect.w&&A.paddedRect.h===L.paddedRect.h||Br(`Mismatch in icon variant sizes: ${k.toString()} and ${x.toString()}`),A.usvg!==L.usvg&&Br(`Mismatch in icon variant image types: ${k.id} and ${x.id}`))}function $ct(k,x,w,A){if(!k)return;const L=x.get(w.toString());if(L&&(k.imagePrimary=L),A){const F=x.get(A.toString());k.imageSecondary=F}}function eus(k,x){for(const w in k.horizontal)Vct(k.horizontal[w],x);Vct(k.vertical,x)}function Vct(k,x){if(k){for(const w of k.positionedLines)for(const A of w.positionedGlyphs)if(A.image!==null){const L=A.image.toString();A.rect=x.get(L).paddedRect}}}function DRe(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 tus(k,x,w,A,L,F,U,K,X){const oe=loe(F.horizontal)||F.vertical,ge=w.get("icon-text-fit-padding").evaluate(A,{},L);let we,je=x;return x&&X!=="none"&&(k.allowVerticalPlacement&&F.vertical&&(we=SRe(x,F.vertical,X,ge,K,U)),oe&&(je=SRe(x,oe,X,ge,K,U))),{defaultShapedIcon:je,verticallyShapedIcon:we}}function Hct(k,x){return k*x/24}function sus(k,x,w,A,L,F,U,K,X,oe,ge,we,je,Le,Re,We,et,it,yt,ht,Et,It,Ot,ws){let ds=U.textMaxSize.evaluate(x,{},je);ds===void 0?ds=K*U.textScaleFactor:ds*=U.textScaleFactor;const _s=k.layers[0].layout,gs=Hct(K,U.textScaleFactor),ys=loe(w.horizontal)||w.vertical,vn=k.hasAnyAppearanceLayoutProperty(["text-size","text-offset","text-rotate"]),wn=k.getAppearanceFeatureData(x.index);(et!=="none"||vn)&&wn&&(wn.textShaping=ys,wn.iconTextFitPadding=_s.get("icon-text-fit-padding").evaluate(x,{},je),wn.fontScale=gs,wn.textScaleFactor=U.textScaleFactor);const Pn=Le.name==="globe",On=k.tilePixelRatio*ds/24,Ln=(pr=k.overscaling,k.zoom>18&&pr>2&&(pr>>=1),Math.max(ur/(512*pr),1)*_s.get("symbol-spacing")),Jn=_s.get("text-padding")*k.tilePixelRatio,gn=_s.get("icon-padding")*k.tilePixelRatio,Rn=Ws(_s.get("text-max-angle")),qn=_s.get("icon-rotation-alignment")==="map"&&ht!=="point",tr=Ln/2;var pr;k.hasAnyIconTextFit===!1&&et!=="none"&&(k.hasAnyIconTextFit=!0);const na=x.properties?+x.properties[Zi]:null,Cr=na&&k.elevationFeatureIdToIndex?k.elevationFeatureIdToIndex.get(na):65535,kr=(fr,Qr,fa)=>{if(Qr.x<0||Qr.x>=ur||Qr.y<0||Qr.y>=ur)return;let Za=null;if(Pn){const{x:Ca,y:zi,z:Ko}=Le.projectTilePoint(Qr.x,Qr.y,fa);Za={anchor:new l3(Ca,zi,Ko,0,void 0),up:Le.upVector(fa,Qr.x,Qr.y)}}(function(Ca,zi,Ko,Bi,el,lo,Mu,Il,ll,zc,wu,Up,ju,eh,Jh,th,Vx,qp,fo,K0,yh,gf,Y0,Hx,Pu,Qg,yf,Soe,sB,Yy,aFe,nB){const c3=Ca.addToLineVertexArray(zi,Bi);let d3,mw,pw,fI,rB,vo,vf,sh=0,pp=0,fw=0,V1=0,H1=-1,G1=-1;const d2={};let Coe=dc("");const uk=Ko?Ko.anchor:zi,aB=Soe!=="none";let iB=0,$m=0;if(ll._unevaluatedLayout.getValue("text-radial-offset")===void 0){const vh=ll.layout.get("text-offset").evaluate(yh,{},Pu);iB=vh[0]*Bp,$m=vh[1]*Bp}else iB=ll.layout.get("text-radial-offset").evaluate(yh,{},Pu)*Bp,$m=IRe;if(Ca.allowVerticalPlacement&&el.vertical){const vh=el.vertical;if(Jh)vo=ORe(vh),Il&&(vf=ORe(Il));else{const Z0=ll.layout.get("text-rotate").evaluate(yh,{},Pu)+90;pw=coe(zc,uk,zi,wu,Up,ju,vh,eh,Z0,th,nB),Il&&(fI=coe(zc,uk,zi,wu,Up,ju,Il,qp,Z0,null,aFe))}}if(lo){const vh=ll.layout.get("icon-rotate").evaluate(yh,{},Pu),Z0=LRe(lo,vh,Y0,aB,gf.iconScaleFactor),Zy=Il?LRe(Il,vh,Y0,aB,gf.iconScaleFactor):void 0;mw=coe(zc,uk,zi,wu,Up,ju,lo,qp,vh,null,Yy);const h2=function(hk,vY,oB,ghs,yhs,hut,mut,vhs,tbr,oFe){const put=hk.layers[0],fut=put.appearances;let lB=vY.length;if(oB&&(lB=Math.max(lB,oB.length)),fut.length===0)return lB;const[bhs,_hs]=ghs.get("icon-size-scale-range"),whs=pt(1,bhs,_hs);for(const Moe of fut)if(Moe.hasLayoutProperty("icon-image")){const xut=put.getAppearanceValueAndResolveTokens(Moe,"icon-image",hut,mut,oFe);if(xut){const gut=hk.getResolvedImageFromTokens(xut);if(gut){const yut=Moe.hasLayoutProperty("icon-size")?Moe.getUnevaluatedLayoutProperty("icon-size"):yhs._values["icon-size"],jhs=rY(gut,cI(hk.zoom,yut,hk.worldview,oFe),yut,mut,hk.zoom,hut,hk.pixelRatio,whs,hk.worldview,oFe),vut=vhs.get(jhs.iconPrimary.toString());vut&&(lB=Math.max(lB,Vds(vut)))}}}return lB}(Ca,Z0,Zy,ll.layout,ll._unevaluatedLayout,yh,Pu,Ca.iconAtlasPositions,0,Hx);sh=4*h2;const Aoe=ll.layout.get("icon-size").evaluate(yh,{},Pu,Hx),Eoe=gf.compositeIconSizes?gf.compositeIconSizes[0].evaluate(yh,{},Pu,Hx):0,iFe=gf.compositeIconSizes?gf.compositeIconSizes[1].evaluate(yh,{},Pu,Hx):0,Toe=FRe(Ca.layerIds[0],Ca.iconSizeData,Aoe,gf.iconScaleFactor,Eoe,iFe);Ca.addSymbols(Ca.icon,Z0,Toe,K0,fo,yh,void 0,Ko,zi,c3.lineStartIndex,c3.lineLength,-1,Hx,Pu,Qg,yf,Ca.symbolInstances.length,h2),H1=Ca.icon.placedSymbolArray.length-1,Zy&&(pp=4*h2,Ca.addSymbols(Ca.icon,Zy,Toe,K0,fo,yh,$1.vertical,Ko,zi,c3.lineStartIndex,c3.lineLength,-1,Hx,Pu,Qg,yf,Ca.symbolInstances.length,h2),G1=Ca.icon.placedSymbolArray.length-1)}for(const vh in el.horizontal){const Z0=vh,Zy=el.horizontal[Z0];d3||(Coe=dc(Zy.text),Jh?rB=ORe(Zy):d3=coe(zc,uk,zi,wu,Up,ju,Zy,eh,ll.layout.get("text-rotate").evaluate(yh,{},Pu),th,nB));const h2=Zy.positionedLines.length===1;if(fw+=Gct(Ca,Ko,zi,Zy,Mu,ll,Jh,yh,th,c3,el.vertical?$1.horizontal:$1.horizontalOnly,h2?Kds(el.horizontal):[Z0],d2,H1,gf,Hx,Pu,Ca.symbolInstances.length,Qg),h2)break}el.vertical&&(V1+=Gct(Ca,Ko,zi,el.vertical,Mu,ll,Jh,yh,th,c3,$1.vertical,["vertical"],d2,G1,gf,Hx,Pu,Ca.symbolInstances.length,Qg));let Nm=-1;const fp=(vh,Z0)=>vh?Math.max(vh,Z0):Z0;Nm=fp(rB,Nm),Nm=fp(vo,Nm),Nm=fp(vf,Nm);const u2=Nm>-1?1:0;Ca.glyphOffsetArray.length>=65535&&Br("Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907"),yh.sortKey!==void 0&&Ca.addToSortKeyRanges(Ca.symbolInstances.length,yh.sortKey),Ca.symbolInstances.emplaceBack(zi.x,zi.y,uk.x,uk.y,uk.z,d2.right>=0?d2.right:-1,d2.center>=0?d2.center:-1,d2.left>=0?d2.left:-1,d2.vertical>=0?d2.vertical:-1,H1,G1,Coe,d3!==void 0?d3:Ca.collisionBoxArray.length,d3!==void 0?d3+1:Ca.collisionBoxArray.length,pw!==void 0?pw:Ca.collisionBoxArray.length,pw!==void 0?pw+1:Ca.collisionBoxArray.length,mw!==void 0?mw:Ca.collisionBoxArray.length,mw!==void 0?mw+1:Ca.collisionBoxArray.length,fI||Ca.collisionBoxArray.length,fI?fI+1:Ca.collisionBoxArray.length,wu,fw,V1,sh,pp,u2,0,iB,$m,Nm,0,aB?1:0,sB)})(k,Qr,Za,fr,w,A,F,L,k.layers[0],k.collisionBoxArray,x.index,x.sourceLayerIndex,k.index,Jn,yt,oe,0,gn,qn,it,x,U,ge,we,je,Re,We,et,Cr,Et,It,Ot)};if(ht==="line")for(const fr of qie(x.geometry,0,0,ur,ur)){const Qr=$ds(fr,Ln,Rn,w.vertical||ys,A,24,On,k.overscaling,ur);for(const fa of Qr)ys&&nus(k,ys.text,tr,fa)||kr(fr,fa,je)}else if(ht==="line-center"){for(const fr of x.geometry)if(fr.length>1){const Qr=qds(fr,Rn,w.vertical||ys,A,24,On);Qr&&kr(fr,Qr,je)}}else if(x.type==="Polygon")for(const fr of BK(x.geometry,0)){const Qr=Gds(fr,16);kr(fr[0],new l3(Qr.x,Qr.y,0,0,void 0),je)}else if(x.type==="LineString")for(const fr of x.geometry)kr(fr,new l3(fr[0].x,fr[0].y,0,0,void 0),je);else if(x.type==="Point")for(const fr of x.geometry)for(const Qr of fr)kr([Qr],new l3(Qr.x,Qr.y,0,0,void 0),je)}const RRe=255,dI=RRe*o3;function Gct(k,x,w,A,L,F,U,K,X,oe,ge,we,je,Le,Re,We,et,it,yt){const ht=Oct(0,A,X,F,U,K,L,k.allowVerticalPlacement,void 0,Re.textScaleFactor),Et=F.layout.get("text-size").evaluate(K,{},et),It=Re.compositeTextSizes?Re.compositeTextSizes[0].evaluate(K,{},et):0,Ot=Re.compositeTextSizes?Re.compositeTextSizes[1].evaluate(K,{},et):0,ws=FRe(k.layerIds[0],k.textSizeData,Et,Re.textScaleFactor,It,Ot);k.addSymbols(k.text,ht,ws,X,U,K,ge,x,w,oe.lineStartIndex,oe.lineLength,Le,We,et,yt,!1,it,ht.length);for(const ds of we)je[ds]=k.text.placedSymbolArray.length-1;return 4*ht.length}function FRe(k,x,w,A,L,F){const U=x;let K=null;return U.kind==="source"?(K=[o3*w*A],K[0]>dI&&Br(`${k}: Value for "text-size" is >= ${RRe}. Reduce your "text-size".`)):U.kind==="composite"&&(K=[o3*L*A,o3*F*A],(K[0]>dI||K[1]>dI)&&Br(`${k}: Value for "text-size" is >= ${RRe}. Reduce your "text-size".`)),K}function loe(k){for(const x in k)return k[x];return null}function coe(k,x,w,A,L,F,U,K,X,oe,ge){let we,je,Le,Re;if(we=ge?ge.top:U.top,je=ge?ge.bottom:U.bottom,Le=ge?ge.left:U.left,Re=ge?ge.right:U.right,kRe(U)&&U.collisionPadding){const We=U.collisionPadding;Le-=We[0],we-=We[1],Re+=We[2],je+=We[3]}if(X){const We=new Js(Le,we),et=new Js(Re,we),it=new Js(Le,je),yt=new Js(Re,je),ht=Ws(X);let Et=new Js(0,0);oe&&(Et=new Js(oe[0],oe[1])),We._rotateAround(ht,Et),et._rotateAround(ht,Et),it._rotateAround(ht,Et),yt._rotateAround(ht,Et),Le=Math.min(We.x,et.x,it.x,yt.x),Re=Math.max(We.x,et.x,it.x,yt.x),we=Math.min(We.y,et.y,it.y,yt.y),je=Math.max(We.y,et.y,it.y,yt.y)}return k.emplaceBack(x.x,x.y,x.z,w.x,w.y,Le,we,Re,je,K,A,L,F),k.length-1}function ORe(k){kRe(k)&&k.collisionPadding&&(k.top-=k.collisionPadding[1],k.bottom+=k.collisionPadding[3]);const x=k.bottom-k.top;return x>0?Math.max(10,x):null}function nus(k,x,w,A){const L=k.compareText;if(x in L){const F=L[x];for(let U=F.length-1;U>=0;U--)if(A.dist(F[U])ht&&(Et(Ot,Pn,ds,_s,vn,wn),Et(Pn,ws,vn,wn,gs,ys))}Et(we,je,A,F,L,F),Et(je,Le,L,F,L,U),Et(Le,Re,L,U,A,U),Et(Re,we,A,U,A,F),We-=ht,et-=ht,it+=ht,yt+=ht;const It=1/Math.max(it-We,yt-et);return{scale:It,x:We*It,y:et*It,x2:it*It,y2:yt*It,projection:x}}function Kct(k,{x,y:w},A=0){return new Js(((x-A)*k.scale-k.x)*ur,(w*k.scale-k.y)*ur)}const rus=v(new Float32Array(16));class hT{constructor(x){this.spec=x,this.name=x.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(x,w){return{x:0,y:0,z:0}}unproject(x,w){return new Es(0,0)}projectTilePoint(x,w,A){return{x,y:w,z:0}}locationPoint(x,w,A,L=!0){return x._coordinatePoint(x.locationCoordinate(w,A),L)}pixelsPerMeter(x,w){return sn(1,x)*w}pixelSpaceConversion(x,w,A){return 1}farthestPixelDistance(x){return Wct(x,x.pixelsPerMeter)}pointCoordinate(x,w,A,L){const F=x.horizonLineFromTop(!1),U=new Js(w,Math.max(F,A));return x.rayIntersectionCoordinate(x.pointRayIntersection(U,L))}pointCoordinate3D(x,w,A){const L=new Js(w,A);if(x.elevation)return x.elevation.pointCoordinate(L);{const F=this.pointCoordinate(x,L.x,L.y,0);return[F.x,F.y,F.z]}}isPointAboveHorizon(x,w){if(x.elevation&&x.elevation.visibleDemTiles.length)return!this.pointCoordinate3D(x,w.x,w.y);const A=x.horizonLineFromTop();return w.y0?w<-Yz+A&&(w=-Yz+A):w>Yz-A&&(w=Yz-A);const U=F/Math.pow(uoe(w),L);let K=U*Math.sin(L*x),X=F-U*Math.cos(L*x);return K=.5*(K/Math.PI+.5),X=.5*(X/Math.PI+.5),{x:K,y:this.southernCenter?X:1-X,z:0}}unproject(x,w){x=(2*x-.5)*Math.PI,this.southernCenter&&(w=1-w),w=(2*(1-w)-.5)*Math.PI;const{n:A,f:L}=this,F=L-w,U=Math.sign(F),K=Math.sign(A)*Math.sqrt(x*x+F*F);let X=Math.atan2(x,Math.abs(F))*U;F*A<0&&(X-=Math.PI*Math.sign(x)*U);const oe=pt(Ys(X/A)+this.center[0],-180,180),ge=pt(Ys(2*Math.atan(Math.pow(L/K,1/A))-Yz),-85.051129,Tn);return new Es(oe,this.southernCenter?-ge:ge)}}class Yct extends hT{constructor(x){super(x),this.wrap=!0,this.supportsWorldCopies=!0,this.supportsTerrain=!0,this.supportsFog=!0,this.supportsFreeCamera=!0,this.isReprojectedInTileSpace=!1,this.unsupportedLayers=[],this.range=null}project(x,w){return{x:zn(x),y:Kn(w),z:0}}unproject(x,w){const A=Fs(x),L=yn(w);return new Es(A,L)}}const Zct=Ws(Tn);class cus extends hT{project(x,w){const A=(w=Ws(w))*w,L=A*A;return{x:.5*((x=Ws(x))*(.8707-.131979*A+L*(L*(.003971*A-.001529*L)-.013791))/Math.PI+.5),y:1-.5*(w*(1.007226+A*(.015085+L*(.028874*A-.044475-.005916*L)))/Math.PI+1),z:0}}unproject(x,w){x=(2*x-.5)*Math.PI;let A=w=(2*(1-w)-1)*Math.PI,L=25,F=0,U=A*A;do{U=A*A;const oe=U*U;F=(A*(1.007226+U*(.015085+oe*(.028874*U-.044475-.005916*oe)))-w)/(1.007226+U*(.045255+oe*(.259866*U-.311325-.005916*11*oe))),A=pt(A-F,-Zct,Zct)}while(Math.abs(F)>1e-6&&--L>0);U=A*A;const K=pt(Ys(x/(.8707+U*(U*(U*U*U*(.003971-.001529*U)-.013791)-.131979))),-180,180),X=Ys(A);return new Es(K,X)}}const Xct=Ws(Tn);class dus extends hT{project(x,w){w=Ws(w),x=Ws(x);const A=Math.cos(w),L=2/Math.PI,F=Math.acos(A*Math.cos(x/2)),U=Math.sin(F)/F,K=.5*(x*L+2*A*Math.sin(x/2)/U)||0,X=.5*(w+Math.sin(w)/U)||0;return{x:.5*(K/Math.PI+.5),y:1-.5*(X/Math.PI+1),z:0}}unproject(x,w){let A=x=(2*x-.5)*Math.PI,L=w=(2*(1-w)-1)*Math.PI,F=25;const U=1e-6;let K=0,X=0;do{const oe=Math.cos(L),ge=Math.sin(L),we=2*ge*oe,je=ge*ge,Le=oe*oe,Re=Math.cos(A/2),We=Math.sin(A/2),et=2*Re*We,it=We*We,yt=1-Le*Re*Re,ht=yt?1/yt:0,Et=yt?Math.acos(oe*Re)*Math.sqrt(1/yt):0,It=.5*(2*Et*oe*We+2*A/Math.PI)-x,Ot=.5*(Et*ge+L)-w,ws=.5*ht*(Le*it+Et*oe*Re*je)+1/Math.PI,ds=ht*(et*we/4-Et*ge*We),_s=.125*ht*(we*We-Et*ge*Le*et),gs=.5*ht*(je*Re+Et*it*oe)+.5,ys=ds*_s-gs*ws;K=(Ot*ds-It*gs)/ys,X=(It*_s-Ot*ws)/ys,A=pt(A-K,-Math.PI,Math.PI),L=pt(L-X,-Xct,Xct)}while((Math.abs(K)>U||Math.abs(X)>U)&&--F>0);return new Es(Ys(A),Ys(L))}}class Qct extends hT{constructor(x){super(x),this.center=x.center||[0,0],this.parallels=x.parallels||[0,0],this.cosPhi=Math.max(.01,Math.cos(Ws(this.parallels[0]))),this.scale=1/(2*Math.max(Math.PI*this.cosPhi,1/this.cosPhi)),this.wrap=!0,this.supportsWorldCopies=!0}project(x,w){const{scale:A,cosPhi:L}=this;return{x:Ws(x)*L*A+.5,y:-Math.sin(Ws(w))/L*A+.5,z:0}}unproject(x,w){const{scale:A,cosPhi:L}=this,F=-(w-.5)/A,U=pt(Ys((x-.5)/A)/L,-180,180),K=Math.asin(pt(F*L,-1,1)),X=pt(Ys(K),-85.051129,Tn);return new Es(U,X)}}class uus extends Yct{constructor(x){super(x),this.requiresDraping=!0,this.supportsWorldCopies=!1,this.supportsFog=!0,this.zAxisUnit="pixels",this.unsupportedLayers=["debug"],this.range=[3,5]}projectTilePoint(x,w,A){const L=LK(x,w,A);return Ze(L,L,IK(h5(A))),{x:L[0],y:L[1],z:L[2]}}locationPoint(x,w,A){const L=ns(w.lat,w.lng),F=Ae([],L),U=A?x._centerAltitude+A:x.elevation?x.elevation.getAtPointOrZero(x.locationCoordinate(w),x._centerAltitude):x._centerAltitude;be(L,L,F,sn(1,0)*ur*U);const K=v(new Float64Array(16));return b(K,x.pixelMatrix,x.globeMatrix),Ze(L,L,K),new Js(L[0],L[1])}pixelsPerMeter(x,w){return sn(1,0)*w}pixelSpaceConversion(x,w,A){const L=sn(1,x)*w,F=Ar(sn(1,45)*w,L,A);return this.pixelsPerMeter(x,w)/F}createTileMatrix(x,w,A){const L=PDe(h5(A.canonical));return b(new Float64Array(16),x.globeMatrix,L)}createInversionMatrix(x,w){const{center:A}=x,L=IK(h5(w));return E(L,L,Ws(A.lng)),C(L,L,Ws(A.lat)),S(L,L,[x._pixelsPerMercatorPixel,x._pixelsPerMercatorPixel,1]),Float32Array.from(L)}pointCoordinate(x,w,A,L){return pot(x,w,A,!0)||new pa(0,0)}pointCoordinate3D(x,w,A){const L=this.pointCoordinate(x,w,A,0);return[L.x,L.y,L.z]}isPointAboveHorizon(x,w){return!pot(x,w.x,w.y,!1)}farthestPixelDistance(x){const w=function(L,F){const U=L.cameraToCenterDistance,K=L._centerAltitude*F,X=L._camera,oe=L._camera.forward(),ge=ne([],le([],oe,-U),[0,0,K]),we=L.worldSize/(2*Math.PI),je=[0,0,-we],Le=L.width/L.height,Re=Math.tan(L.fovAboveCenter),We=le([],X.up(),Re),et=le([],X.right(),Re*Le),it=Ae([],ne([],ne([],oe,We),et)),yt=[];let ht;if(new _o(ge,it).closestPointOnSphere(je,we,yt)){const Et=ne([],yt,je),It=Ve([],Et,ge);ht=Math.cos(L.fovAboveCenter)*H(It)}else{const Et=Ve([],ge,je),It=Ve([],je,ge);Ae(It,It);const Ot=H(Et)-we;ht=Math.sqrt(Ot*(Ot+2*we));const ws=Math.acos(ht/(we+Ot))-Math.acos(Pe(oe,It));ht*=Math.cos(ws)}return 1.01*ht}(x,this.pixelsPerMeter(x.center.lat,x.worldSize)),A=r3(x.zoom);if(A>0){const L=Wct(x,sn(1,x.center.lat)*x.worldSize),F=x.worldSize/(2*Math.PI),U=Math.max(x.width,x.height)/x.worldSize*Math.PI;return Ar(w,L+F*(1-Math.cos(U)),Math.pow(A,10))}return w}upVector(x,w,A){return LK(w,A,x,1)}upVectorScale(x){return{metersToTile:Nie(Sie(h5(x)))}}}function Jct(k){const x=k.parallels,w=!!x&&Math.abs(x[0]+x[1])<.01;switch(k.name){case"mercator":return new Yct(k);case"equirectangular":return new ous(k);case"naturalEarth":return new cus(k);case"equalEarth":return new ius(k);case"winkelTripel":return new dus(k);case"albers":return w?new Qct(k):new aus(k);case"lambertConformalConic":return w?new Qct(k):new lus(k);case"globe":return new uus(k)}throw new Error(`Invalid projection name: ${k.name}`)}class hus{constructor(x,w){this.lastParams=null,this.lastAllFeaturesIndex=-2,this.appearancesVersion=w,this.appearances=x;const A=x.map(L=>function(F){if(!F.condition)return{featureDependent:!1,stateDependent:!1,zoomDependent:!1,pitchDependent:!1,brightnessDependent:!1,worldviewDependent:!1};const U=F.condition.expression;return{featureDependent:!$b(U),stateDependent:!Bx(U),zoomDependent:!Zu(U,["zoom"]),pitchDependent:!Zu(U,["pitch"]),brightnessDependent:!Zu(U,["brightness","measure-light"]),worldviewDependent:!Zu(U,["worldview"])}}(L));this.anyFeatureDependent=A.some(L=>L.featureDependent),this.anyStateDependent=A.some(L=>L.stateDependent)}update(x,w){const A=this.lastParams,L=!A||A.zoom!==x.zoom||A.pitch!==(x.pitch||0)||A.brightness!==(x.brightness||0)||A.worldview!==x.worldview;this.lastParams={zoom:x.zoom,pitch:x.pitch||0,brightness:x.brightness||0,worldview:x.worldview};const F=w&&this.anyStateDependent;if(!L&&!F&&this.lastAllFeaturesIndex!==-2)return{kind:"no-changes"};if(!this.anyFeatureDependent&&!F){const U=this.evaluateAllFeatures(x);return U===this.lastAllFeaturesIndex?{kind:"no-changes"}:(this.lastAllFeaturesIndex=U,{kind:"all-features",appearanceIndex:U})}return{kind:"per-feature"}}evaluateAllFeatures(x){for(let w=0;w{for(let L=0;LU-K),F=new Map;for(const U of L){const K=A.get(U);F.set(U,new Rc(K))}return w&&(this.cachedBatchIndices=L,this.cachedBatchSegments=F),{batchIndices:L,batchSegments:F}}snapshotSymbolVertexData(x,w){const A=x*Xz;return this.layoutVertexArray.uint16.slice(A,A+w*Xz)}restoreSymbolVertexData(x,w){this.layoutVertexArray.uint16.set(w,x*Xz)}updateSymbolVertexData(x,w,A,L,F,U,K,X,oe,ge,we,je,Le){const Re=this.layoutVertexArray.uint16,We=x*Xz;Re[We]=w,Re[We+1]=A,Re[We+2]=L,Re[We+3]=F,Re[We+4]=U,Re[We+5]=K,Re[We+6]=X,Re[We+7]=oe,Re[We+8]=ge,Re[We+9]=we,Re[We+10]=je,Re[We+11]=Le}upload(x,w,A,L,F,U){this.isEmpty()||(A&&(this.cachedBatchIndices=null,this.cachedBatchSegments=null,this.layoutVertexBuffer=x.createVertexBuffer(this.layoutVertexArray,fds.members,!!U),this.indexBuffer=x.createIndexBuffer(this.indexArray,w),this.dynamicLayoutVertexBuffer=x.createVertexBuffer(this.dynamicLayoutVertexArray,gds.members,!0),this.opacityVertexBuffer=x.createVertexBuffer(this.opacityVertexArray,pus,!0),this.iconTransitioningVertexArray.length>0&&(this.iconTransitioningVertexBuffer=x.createVertexBuffer(this.iconTransitioningVertexArray,_ds.members,!0)),this.globeExtVertexArray.length>0&&(this.globeExtVertexBuffer=x.createVertexBuffer(this.globeExtVertexArray,xds.members,!0)),!this.zOffsetVertexBuffer&&(this.zOffsetVertexArray.length>0||F)&&(this.zOffsetVertexBuffer=x.createVertexBuffer(this.zOffsetVertexArray,yds.members,!0)),!this.orientationVertexBuffer&&this.orientationVertexArray&&this.orientationVertexArray.length>0&&(this.orientationVertexBuffer=x.createVertexBuffer(this.orientationVertexArray,bds.members,!0)),this.opacityVertexBuffer.itemSize=1,this.featureIdArray&&this.featureIdArray.length>0&&(this.featureIdBuffer=x.createVertexBuffer(this.featureIdArray,vds.members,!1))),(A||L)&&(this.programConfigurations.upload(x),this.uboBinder&&this.uboBinder.upload(x)))}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())}}jr(zRe,"SymbolBuffers",{omit:["cachedBatchIndices","cachedBatchSegments"]});class BRe{constructor(x,w,A){this.layoutVertexArray=new x,this.layoutAttributes=w,this.indexArray=new A,this.segments=new Rc,this.collisionVertexArray=new ZL,this.collisionVertexArrayExt=new rk}upload(x){this.layoutVertexBuffer=x.createVertexBuffer(this.layoutVertexArray,this.layoutAttributes),this.indexBuffer=x.createIndexBuffer(this.indexArray),this.collisionVertexBuffer=x.createVertexBuffer(this.collisionVertexArray,wds.members,!0),this.collisionVertexBufferExt=x.createVertexBuffer(this.collisionVertexArrayExt,jds.members,!0)}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy(),this.collisionVertexBuffer.destroy(),this.collisionVertexBufferExt.destroy())}}jr(BRe,"CollisionBuffers");class lk{constructor(x){this.collisionBoxArray=x.collisionBoxArray,this.zoom=x.zoom,this.overscaling=x.overscaling,this.layers=x.layers,this.layerIds=this.layers.map(U=>U.fqid),this.index=x.index,this.pixelRatio=x.pixelRatio,this.sourceLayerIndex=x.sourceLayerIndex,this.hasPattern=!1,this.hasRTLText=!1,this.fullyClipped=!1,this.hasAnyIconTextFit=!1,this.sortKeyRanges=[],this.collisionCircleArray=[],this.placementInvProjMatrix=v([]),this.placementViewportMatrix=v([]);const w=this.layers[0]._unevaluatedLayout._values;this.worldview=x.worldview,this.localizable=x.localizable,this.maxUniformBufferBindings=x.maxUniformBufferBindings,this.maxUniformBlockSizeDwords=x.maxUniformBlockSizeDwords,this.disableSymbolUBO=x.disableSymbolUBO,this.textSizeData=cI(this.zoom,w["text-size"],this.worldview,x.availableImages),this.iconSizeData=cI(this.zoom,w["icon-size"],this.worldview,x.availableImages);const A=this.layers[0].layout,L=A.get("symbol-sort-key"),F=A.get("symbol-z-order");this.lut=x.lut,this.canOverlap=A.get("text-allow-overlap")||A.get("icon-allow-overlap")||A.get("text-ignore-placement")||A.get("icon-ignore-placement"),this.sortFeaturesByKey=F!=="viewport-y"&&L.constantOr(1)!==void 0,this.sortFeaturesByY=(F==="viewport-y"||F==="auto"&&!this.sortFeaturesByKey)&&this.canOverlap,this.writingModes=A.get("text-writing-mode").map(U=>$1[U]),this.stateDependentLayerIds=this.layers.filter(U=>U.isStateDependent()).map(U=>U.id),this.sourceID=x.sourceID,this.projection=x.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(x){const w=this.layers[0].getAppearances();if(!w||w.length===0)return!1;const A=Array.isArray(x)?x:[x];return w.some(L=>A.some(F=>L.hasLayoutProperty(F)))}getAppearanceFeatureData(x){return this.featureAppearanceData.get(x)}createArrays(){this.text=new zRe(new tt(this.layers,{zoom:this.zoom,lut:this.lut},x=>x.startsWith("text")||x.startsWith("symbol"))),this.icon=new zRe(new tt(this.layers,{zoom:this.zoom,lut:this.lut},x=>x.startsWith("icon")||x.startsWith("symbol"))),this.disableSymbolUBO||(this.text.uboBinder=new _Re(this.layers[0],this.zoom,this.lut,!0,"",this.maxUniformBufferBindings,this.maxUniformBlockSizeDwords),this.icon.uboBinder=new _Re(this.layers[0],this.zoom,this.lut,!1,"",this.maxUniformBufferBindings,this.maxUniformBlockSizeDwords)),this.glyphOffsetArray=new yie,this.lineVertexArray=new JL,this.symbolInstances=new gie}calculateGlyphDependencies(x,w,A,L,F){for(const U of x){const K=U.codePointAt(0);if(K===void 0)break;if(w[K]=!0,L&&F&&K<=65535){const X=JK[U];X&&(w[X.charCodeAt(0)]=!0)}}}calculateEffectiveAppearanceIconSize(x,w,A,L,F,U,K){if(!x.hasLayoutProperty("icon-size"))return K*U;let X=1;const oe=x.getUnevaluatedLayoutProperty("icon-size"),ge=cI(this.zoom,oe,this.worldview,F),we=Wz(ge,w);if(ge.kind!=="constant"&&ge.kind!=="camera"||(X=we.uSize),ge.kind==="composite"){const{minZoom:je,maxZoom:Le}=ge,Re=oe.possiblyEvaluate(new $i(je,{worldview:this.worldview}),L),We=oe.possiblyEvaluate(new $i(Le,{worldview:this.worldview}),L),et=Re.evaluate(A,{},L,F);X=et+(We.evaluate(A,{},L,F)-et)*we.uSizeT}return ge.kind==="source"&&(X=oe.possiblyEvaluate(new $i(this.zoom,{worldview:this.worldview}),L).evaluate(A,{},L,F)),X*U}updateFootprints(x,w){}updateReplacement(x,w){if(w.updateTime===this.replacementUpdateTime)return!1;this.replacementUpdateTime=w.updateTime;const A=w.getReplacementRegionsForTile(x.toUnwrapped(),!0);return!Rie(this.activeReplacements,A)&&(this.activeReplacements=A,!0)}getResolvedImageFromTokens(x){return typeof x=="string"?Ch.build(x):x}populate(x,w,A,L){const F=this.layers[0],U=F.layout,K=this.projection.name==="globe",X=U.get("text-font"),oe=U.get("text-field"),ge=U.get("icon-image"),[we,je]=U.get("icon-size-scale-range"),Le=pt(w.scaleFactor||1,we,je),[Re,We]=U.get("text-size-scale-range"),et=pt(w.scaleFactor||1,Re,We),it=(oe.value.kind!=="constant"||oe.value.value instanceof dd&&!oe.value.value.isEmpty()||oe.value.value.toString().length>0)&&(X.value.kind!=="constant"||X.value.value.length>0),yt=ge.value.kind!=="constant"||!!ge.value.value||Object.keys(ge.parameters).length>0,ht=this.hasAnyAppearanceLayoutProperty("icon-image"),Et=U.get("symbol-sort-key");if(this.features=[],this.featureAppearanceData=new Map,!it&&!yt&&!ht)return;const It=w.iconDependencies,Ot=w.glyphDependencies,ws=w.availableImages,ds=new $i(this.zoom,{worldview:this.worldview,activeFloors:w.activeFloors}),_s=gs=>{const ys=gs.id.toString();It.has(ys)?It.get(ys).push(gs):It.set(ys,[gs])};for(const gs of x){const{feature:ys,id:vn,index:wn,sourceLayerIndex:Pn}=gs,On=F._featureFilter.needGeometry,Ln=oo(ys,On);if(!F._featureFilter.filter(ds,Ln,A))continue;if(On||(Ln.geometry=Qa(ys,A,L)),K&&ys.type!==1&&A.z<=5){const Cr=Ln.geometry,kr=.98078528056,fr=(Qr,fa)=>Pe(LK(Qr.x,Qr.y,A,1),LK(fa.x,fa.y,A,1)){if(!Cr.getLayoutProperty("icon-image"))return;const kr=this.getCombinedIconPrimary(Cr,Rn,Ln,A,ws,pr,Le);kr&&_s(kr)}),Jn){const Cr=X.evaluate(Ln,{},A).join(","),kr=U.get("text-rotation-alignment")==="map"&&U.get("symbol-placement")!=="point";this.allowVerticalPlacement=this.writingModes&&this.writingModes.indexOf($1.vertical)>=0;for(const fr of Jn.sections)if(fr.image){const Qr=fr.image.getPrimary().scaleSelf(this.pixelRatio*et),fa=Qr.id.toString(),Za=It.get(fa)||[];Za.push(Qr),It.set(fa,Za)}else{const Qr=ix(Jn.toString()),fa=fr.fontStack||Cr,Za=Ot[fa]=Ot[fa]||{};this.calculateGlyphDependencies(fr.text,Za,kr,this.allowVerticalPlacement,Qr)}}}if(U.get("symbol-placement")==="line"&&(this.features=function(gs){const ys={},vn={},wn=[];let Pn=0;function On(Rn){wn.push(gs[Rn]),Pn++}function Ln(Rn,qn,tr){const pr=vn[Rn];return delete vn[Rn],vn[qn]=pr,wn[pr].geometry[0].pop(),wn[pr].geometry[0]=wn[pr].geometry[0].concat(tr[0]),pr}function Jn(Rn,qn,tr){const pr=ys[qn];return delete ys[qn],ys[Rn]=pr,wn[pr].geometry[0].shift(),wn[pr].geometry[0]=tr[0].concat(wn[pr].geometry[0]),pr}function gn(Rn,qn,tr){const pr=tr?qn[0][qn[0].length-1]:qn[0][0];return`${Rn}:${pr.x}:${pr.y}`}for(let Rn=0;RnRn.geometry)}(this.features)),U.get("symbol-elevation-reference")==="hd-road-markup"){if(this.elevationType="road",w.elevationFeatures){!this.elevationFeatures&&w.elevationFeatures.length>0&&(this.elevationFeatures=[],this.elevationFeatureIdToIndex=new Map);for(const gs of w.elevationFeatures)this.elevationFeatureIdToIndex.set(gs.id,this.elevationFeatures.length),this.elevationFeatures.push(gs)}}else U.get("symbol-z-elevate")&&(this.elevationType="offset");this.elevationType!=="none"&&(this.zOffsetBuffersNeedUpload=!0),this.sortFeaturesByKey&&this.features.sort((gs,ys)=>gs.sortKey-ys.sortKey)}getCombinedIconPrimary(x,w,A,L,F,U,K){let X,oe;if(x.hasLayoutProperty("icon-image")){const ge=w.getAppearanceValueAndResolveTokens(x,"icon-image",A,L,F);X=this.getResolvedImageFromTokens(ge)}else{const ge=w.getValueAndResolveTokens("icon-image",A,L,F);X=this.getResolvedImageFromTokens(ge)}if(X){const ge=x.hasLayoutProperty("icon-size")?x.getUnevaluatedLayoutProperty("icon-size"):w._unevaluatedLayout._values["icon-size"];oe=rY(X,cI(this.zoom,ge,this.worldview,F),ge,L,this.zoom,U,this.pixelRatio,K,this.worldview,F).iconPrimary}return oe}updateSymbolInstanceIconVertices(x,w,A,L,F,U){const{canonical:K,availableImages:X,globalProperties:oe,layer:ge,iconScaleFactor:we,featureState:je,layoutIconOffset:Le,layoutIconSize:Re,layoutIconRotate:We}=U;if(x.placedIconSymbolIndex<0)return{vertexOffsetDelta:0,hasChanges:!1};if(w.activeAppearanceIndex===A)return{vertexOffsetDelta:x.numIconVertices,hasChanges:!1};const et=A>=0?ge.appearances[A]:null;if(et){const it=this.getCombinedIconPrimary(et,ge,L,K,X,{sortKey:void 0,text:void 0,icon:null,index:x.featureIndex,sourceLayerIndex:x.featureIndex,geometry:[],properties:w.properties,type:"Point",id:w.id},we);if(!it)return{vertexOffsetDelta:0,hasChanges:!1};const yt=it.toString(),ht=this.iconAtlasPositions&&this.iconAtlasPositions.get(yt);if(ht){const{appearanceIconOffset:Et,appearanceIconRotate:It}=Bct(et,ge,L,K,Le,We,Re,we);let Ot=toe(ht,void 0,Et,ge.layout.get("icon-anchor").evaluate(L,je,K));const ws=ht.sdf,ds=ge.layout.get("icon-text-fit").constantOr("none");ds!=="none"&&w.textShaping&&w.iconTextFitPadding&&w.fontScale&&(Ot=SRe(Ot,w.textShaping,ds,w.iconTextFitPadding,Et,w.fontScale));const _s=this.calculateEffectiveAppearanceIconSize(et,oe.zoom,L,K,X,we,Re),gs=0,ys=1+(Math.min(dI,Math.round(_s*o3))<<1),vn=LRe(Ot,It,ws,ds!=="none",we);w.isUsingAppearanceIconVertexData||(w.isUsingAppearanceIconVertexData=!0,w.layoutBasedIconVertexData=this.icon.snapshotSymbolVertexData(F,x.numIconVertices));const wn=Math.floor(x.numIconVertices/4),Pn=Math.min(vn.length,wn);let On=F;for(let Jn=0;Jn0||x.numVerticalGlyphVertices>0;if(!Et)return{vertexOffsetDelta:Et?x.numHorizontalGlyphVertices+x.numVerticalGlyphVertices:0,hasChanges:!1};if(w.activeAppearanceIndex===A)return{vertexOffsetDelta:x.numHorizontalGlyphVertices+x.numVerticalGlyphVertices,hasChanges:!1};const It=A>=0?X.appearances[A]:null;if(It&&w.textShaping){const{appearanceTextOffset:Ot,appearanceTextRotate:ws,appearanceTextSize:ds}=Uct(It,X,L,K,je,Re,Le);w.fontScale=Hct(ds,w.textScaleFactor);const _s=It.getUnevaluatedLayoutProperty("text-size");let gs=this.textSizeData,ys=it,vn=yt;It.hasLayoutProperty("text-size")&&(gs=cI(this.zoom,_s,this.worldview,ht),ys=this.textSizeData.kind==="composite"?this.textSizeData.minZoom:0,vn=this.textSizeData.kind==="composite"?this.textSizeData.maxZoom:0);const wn=w.textShaping.bottom-je[1],Pn=w.textShaping.left-je[0],On=w.textShaping.right-je[0];w.textShaping.top=Ot[1]+(w.textShaping.top-je[1]),w.textShaping.bottom=Ot[1]+wn,w.textShaping.left=Ot[0]+Pn,w.textShaping.right=Ot[0]+On;const Ln=Oct(0,w.textShaping,Ot,X,!1,L,ge,this.allowVerticalPlacement,ws),Jn=ds&&gs.kind==="composite"?_s.possiblyEvaluate(new $i(ys,{}),K).evaluate(L,we,K):We,gn=ds&&gs.kind==="composite"?_s.possiblyEvaluate(new $i(vn,{}),K).evaluate(L,we,K):et,Rn=FRe(It.name,gs,ds,oe,Jn,gn),qn=Array.isArray(Rn)?Rn[1]:ds,tr=0,pr=1+(Math.min(dI,Math.round(qn*o3))<<1);w.isUsingAppearanceTextVertexData||(w.isUsingAppearanceTextVertexData=!0,w.layoutBasedTextVertexData=this.text.snapshotSymbolVertexData(F,x.numHorizontalGlyphVertices+x.numVerticalGlyphVertices));for(let na=0;na0){const oe=new Set(Object.keys(x).map(ge=>{const we=Number(ge);return!isNaN(we)&&Number.isSafeInteger(we)&&String(we)===ge?we:ge}));this.text.uboBinder&&this.text.uboBinder.updateFeatures(oe,F[0],w,X,A,x,K),this.icon.uboBinder&&this.icon.uboBinder.updateFeatures(oe,F[0],w,X,A,x,K)}}}updateRoadElevation(x){if(this.elevationType!=="road"||!this.elevationFeatures||this.elevationStateComplete)return;this.elevationStateComplete=!0,this.hasAnyZOffset=!1;let w=!1;const A=Gn(x),L=1/A;let F=!1,U=!1;for(let K=0;K0||je>0,et=Le>0,it=this.elevationFeatures[X.elevationFeatureIndex];if(it){const yt=new Js(X.tileAnchorX,X.tileAnchorY),ht=.075+it.pointElevation(yt);X.zOffset!==ht&&(w=!0,X.zOffset=ht),ht!==0&&(this.hasAnyZOffset=!0);const Et=it.computeSlopeNormal(yt,L),It=Ts(ct(),Y(0,0,1),Et);Fe(oe,oe,It),Fe(ge,ge,It),oe[2]*=A,ge[2]*=A,oe[0]===1&&oe[1]===0&&oe[2]===0&&ge[0]===0&&ge[1]===1&&ge[2]===0||(F=F||We,U=U||et)}if(We&&(hoe(this.text.orientationVertexArray,we,oe,ge),hoe(this.text.orientationVertexArray,je,oe,ge)),et){const{placedIconSymbolIndex:yt,verticalPlacedIconSymbolIndex:ht}=X;yt>=0&&hoe(this.icon.orientationVertexArray,Le,oe,ge),ht>=0&&hoe(this.icon.orientationVertexArray,Re,oe,ge)}}F||(this.text.orientationVertexArray=void 0),U||(this.icon.orientationVertexArray=void 0),w&&(this.zOffsetBuffersNeedUpload=!0,this.zOffsetSortDirty=!0)}updateZOffset(){const x=(F,U,K)=>{A+=U,A>F.length&&F.resize(A);for(let X=-U;X<0;X++)F.emplace(X+A,K)},w=(F,U,K)=>{L+=U,L>F.length&&F.resize(L);for(let X=-U;X<0;X++)F.emplace(X+L,K)};if(!this.zOffsetBuffersNeedUpload)return;this.zOffsetBuffersNeedUpload=!1;let A=0,L=0;for(let F=0;F0;if((K>0||X>0)&&(x(this.text.zOffsetVertexArray,K,ge),x(this.text.zOffsetVertexArray,X,ge)),we){const{placedIconSymbolIndex:je,verticalPlacedIconSymbolIndex:Le}=U;je>=0&&w(this.icon.zOffsetVertexArray,oe,ge),Le>=0&&w(this.icon.zOffsetVertexArray,U.numVerticalIconVertices,ge)}}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(x,w,A,L,F){!this.uploaded&&this.hasDebugData()&&(this.textCollisionBox.upload(x),this.iconCollisionBox.upload(x)),this.text.upload(x,this.sortFeaturesByY,!this.uploaded,this.text.programConfigurations.needsUpload,this.zOffsetBuffersNeedUpload,this.hasAppearances),this.hasAppearances===null&&(this.hasAppearances=this.layers.some(U=>U.appearances&&U.appearances.length>0)),this.icon.upload(x,this.sortFeaturesByY,!this.uploaded,this.icon.programConfigurations.needsUpload,this.zOffsetBuffersNeedUpload,this.hasAppearances),this.uploaded=!0}updateAppearances(x,w,A,L,F,U=!1){const K={hasLayoutChanges:!1,hasUboChanges:!1};if(!x||!A||!this.featureAppearanceData)return K;const X=w||{},oe=this.icon.layoutVertexArray&&this.icon.layoutVertexArray.length>0&&this.icon.layoutVertexArray.arrayBuffer,ge=this.text.layoutVertexArray&&this.text.layoutVertexArray.length>0&&this.text.layoutVertexArray.arrayBuffer;if(!oe&&!ge)return K;const we=this.layers[0],je=we.layout;this.featureAppearances&&this.featureAppearances.appearancesVersion===we.appearancesVersion||(this.featureAppearances=new hus(we.appearances,we.appearancesVersion));const Le=this.featureAppearances.update(L,U);if(Le.kind==="no-changes")return K;let Re=1,We=0,et=!1,it=!1;if(oe){const[Ot,ws]=je.get("icon-size-scale-range");Re=pt(1,Ot,ws)}let yt=1,ht=0,Et=!1;if(ge){const[Ot,ws]=je.get("text-size-scale-range");yt=pt(1,Ot,ws)}const It=new Map;if(F&&A)for(const Ot of A){const ws=F.getImage(Ot,we.scope);if(ws){const ds=new Ud(Ot.toString());It.set(ds.toString(),ws)}}for(let Ot=0;OtOn.isActive({globals:L,feature:ys,canonical:x,featureState:gs})):-1;vn=Pn>=0?Pn:-1}const wn=ds.activeAppearanceIndex!==vn;if(ge){const Pn=je.get("text-size"),On=this.textSizeData.kind==="composite"?this.textSizeData.minZoom:0,Ln=this.textSizeData.kind==="composite"?this.textSizeData.maxZoom:0,Jn={canonical:x,layer:we,featureState:gs,availableImages:A,textScaleFactor:yt,imageMap:It,layoutTextOffset:je.get("text-offset").evaluate(ys,gs,x).map(Rn=>Rn*Bp),layoutTextSize:Pn.evaluate(ys,gs,x),layoutTextRotate:je.get("text-rotate").evaluate(ys,gs,x),layoutMinZoomSize:Pn.evaluate(ys,{zoom:On},x),layoutMaxZoomSize:Pn.evaluate(ys,{zoom:Ln},x),layoutTextSizeMinZoom:On,layoutTextSizeMaxZoom:Ln},gn=this.updateSymbolInstanceTextVertices(ws,ds,vn,ys,ht,Jn);ht+=gn.vertexOffsetDelta,Et=Et||gn.hasChanges}if(oe){const Pn={canonical:x,layer:we,featureState:gs,availableImages:A,globalProperties:L,iconScaleFactor:Re,layoutIconOffset:je.get("icon-offset").evaluate(ys,gs,x),layoutIconSize:je.get("icon-size").evaluate(ys,gs,x,A),layoutIconRotate:je.get("icon-rotate").evaluate(ys,gs,x)},On=this.updateSymbolInstanceIconVertices(ws,ds,vn,ys,We,Pn);We+=On.vertexOffsetDelta,et=et||On.hasChanges}if(wn){const Pn=ws.featureIndex,On=L?L.brightness:null,Ln=gs||{},Jn=vn>=0?we.appearances[vn]:null;this.text.uboBinder&&(this.text.uboBinder.layer=we,it=this.text.uboBinder.updateFeaturePaintForAppearance(Pn,ys,Ln,x,A,On,Jn)||it),this.icon.uboBinder&&(this.icon.uboBinder.layer=we,it=this.icon.uboBinder.updateFeaturePaintForAppearance(Pn,ys,Ln,x,A,On,Jn)||it)}ds.activeAppearanceIndex=vn}return et&&this.icon.layoutVertexBuffer&&this.icon.layoutVertexArray.arrayBuffer!==null&&this.icon.layoutVertexArray.length===this.icon.layoutVertexBuffer.length&&this.icon.layoutVertexBuffer.updateData(this.icon.layoutVertexArray),Et&&this.text.layoutVertexBuffer&&this.text.layoutVertexArray.arrayBuffer!==null&&this.text.layoutVertexArray.length===this.text.layoutVertexBuffer.length&&this.text.layoutVertexBuffer.updateData(this.text.layoutVertexArray),{hasLayoutChanges:et||Et,hasUboChanges:it}}destroyDebugData(){this.textCollisionBox.destroy(),this.iconCollisionBox.destroy()}getProjection(){return this.projectionInstance||(this.projectionInstance=Jct(this.projection)),this.projectionInstance}destroy(){this.text.destroy(),this.icon.destroy(),this.hasDebugData()&&this.destroyDebugData()}addToLineVertexArray(x,w){const A=this.lineVertexArray.length;if(x.segment!==void 0)for(const{x:L,y:F}of w)this.lineVertexArray.emplaceBack(L,F);return{lineStartIndex:A,lineLength:this.lineVertexArray.length-A}}addSymbols(x,w,A,L,F,U,K,X,oe,ge,we,je,Le,Re,We,et,it,yt){const ht=x.indexArray,Et=x.layoutVertexArray,It=x.globeExtVertexArray,Ot=yt,ws=x.uboBinder?x.uboBinder.getCurrentBatchIndex():void 0,ds=x.segments.prepareSegment(4*Ot,Et,ht,this.canOverlap?U.sortKey:void 0,ws),_s=this.glyphOffsetArray.length,gs=ds.vertexLength,ys=this.allowVerticalPlacement&&K===$1.vertical?Math.PI/2:0,vn=U.text&&U.text.sections;let wn=Et.length,Pn=-1;for(let Jn=0;Jn=0)){const Jn=4*On;for(let gn=0;gn=0?w.rightJustifiedTextSymbolIndex:w.centerJustifiedTextSymbolIndex>=0?w.centerJustifiedTextSymbolIndex:w.leftJustifiedTextSymbolIndex>=0?w.leftJustifiedTextSymbolIndex:w.verticalPlacedTextSymbolIndex>=0?w.verticalPlacedTextSymbolIndex:L),U=CRe(this.textSizeData,x,F)/Bp;return this.tilePixelRatio*U}getSymbolInstanceIconSize(x,w,A){const L=this.icon.placedSymbolArray.get(A),F=CRe(this.iconSizeData,x,L);return this.tilePixelRatio*F}_commitDebugCollisionVertexUpdate(x,w,A,L){x.emplaceBack(w,-A,-A,L),x.emplaceBack(w,A,-A,L),x.emplaceBack(w,A,A,L),x.emplaceBack(w,-A,A,L)}_updateTextDebugCollisionBoxes(x,w,A,L,F,U,K){for(let X=L;X0}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(x,w){const A=x.placedSymbolArray.get(w),L=A.vertexStartIndex+4*A.numGlyphs;for(let F=A.vertexStartIndex;FL[K]-L[X]||F[X]-F[K]),U}getSortedIndexesByZOffset(){if(!this.zOffsetSortDirty)return this.symbolInstanceIndexesSortedZOffset;if(!this.symbolInstanceIndexesSortedZOffset){this.symbolInstanceIndexesSortedZOffset=[];for(let x=0;xthis.symbolInstances.get(w).zOffset-this.symbolInstances.get(x).zOffset)}addToSortKeyRanges(x,w){const A=this.sortKeyRanges[this.sortKeyRanges.length-1];A&&A.sortKey===w?A.symbolInstanceEnd=x+1:this.sortKeyRanges.push({sortKey:w,symbolInstanceStart:x,symbolInstanceEnd:x+1})}sortFeatures(x){if(this.sortFeaturesByY&&this.sortedAngle!==x)if(this.text.segments.get().length>1||this.icon.segments.get().length>1)this.sortFeaturesWithinSegments();else{this.symbolInstanceIndexes=this.getSortedSymbolIndexes(x),this.sortedAngle=x,this.text.indexArray.clear(),this.icon.indexArray.clear(),this.featureSortOrder=[];for(const w of this.symbolInstanceIndexes){const A=this.symbolInstances.get(w);this.featureSortOrder.push(A.featureIndex);const{rightJustifiedTextSymbolIndex:L,centerJustifiedTextSymbolIndex:F,leftJustifiedTextSymbolIndex:U,verticalPlacedTextSymbolIndex:K,placedIconSymbolIndex:X,verticalPlacedIconSymbolIndex:oe}=A;L>=0&&this.addIndicesForPlacedSymbol(this.text,L),F>=0&&F!==L&&this.addIndicesForPlacedSymbol(this.text,F),U>=0&&U!==F&&U!==L&&this.addIndicesForPlacedSymbol(this.text,U),K>=0&&this.addIndicesForPlacedSymbol(this.text,K),X>=0&&this.addIndicesForPlacedSymbol(this.icon,X),oe>=0&&this.addIndicesForPlacedSymbol(this.icon,oe)}this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray)}}getOrCreateSortedSymbolsByBatch(x,w){const A=(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 F of L){const U=this.symbolInstances.get(F.index);F.rotatedY=0|Math.round(x*U.tileAnchorX+w*U.tileAnchorY)}else{this.symbolsByBatch=new Map;for(let L=0;LF.rotatedY-U.rotatedY||U.featureIndex-F.featureIndex);return this.symbolsByBatch}rebuildTextSegmentIndices(x,w){for(const A of x){const L=A.batchIndex;if(L===void 0)continue;const F=w.get(L);if(!F){A.primitiveOffset=this.text.indexArray.length,A.primitiveLength=0;continue}A.primitiveOffset=this.text.indexArray.length;const U=this.text.indexArray.length;for(const{index:K}of F){const X=this.symbolInstances.get(K),{rightJustifiedTextSymbolIndex:oe,centerJustifiedTextSymbolIndex:ge,leftJustifiedTextSymbolIndex:we,verticalPlacedTextSymbolIndex:je}=X;oe>=0&&this.addIndicesForPlacedSymbol(this.text,oe),ge>=0&&ge!==oe&&this.addIndicesForPlacedSymbol(this.text,ge),we>=0&&we!==ge&&we!==oe&&this.addIndicesForPlacedSymbol(this.text,we),je>=0&&this.addIndicesForPlacedSymbol(this.text,je)}A.primitiveLength=this.text.indexArray.length-U}}rebuildIconSegmentIndices(x,w){for(const A of x){const L=A.batchIndex;if(L===void 0)continue;const F=w.get(L);if(!F){A.primitiveOffset=this.icon.indexArray.length,A.primitiveLength=0;continue}A.primitiveOffset=this.icon.indexArray.length;const U=this.icon.indexArray.length;for(const{index:K}of F){const X=this.symbolInstances.get(K),{placedIconSymbolIndex:oe,verticalPlacedIconSymbolIndex:ge}=X;oe>=0&&this.addIndicesForPlacedSymbol(this.icon,oe),ge>=0&&this.addIndicesForPlacedSymbol(this.icon,ge)}A.primitiveLength=this.icon.indexArray.length-U}}sortFeaturesWithinSegments(){this.featureSortOrder=[];const x=Math.sin(this.sortedAngle),w=Math.cos(this.sortedAngle),A=this.getOrCreateSortedSymbolsByBatch(x,w),L=Array.from(A.keys()).sort((F,U)=>F-U);for(const F of L){const U=A.get(F);for(const{index:K}of U){const X=this.symbolInstances.get(K);this.featureSortOrder.push(X.featureIndex)}}this.text.indexArray.clear(),this.icon.indexArray.clear(),this.rebuildTextSegmentIndices(this.text.segments.get(),A),this.rebuildIconSegmentIndices(this.icon.segments.get(),A),this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray)}getElevationFeatureForText(x){const w=this.symbolInstances.get(this.text.symbolInstanceIndices[x]).elevationFeatureIndex;let A;return this.elevationFeatures&&wA in k?String(k[A]):"")}let tdt,sdt,URe;jr(lk,"SymbolBucket",{omit:["layers","collisionBoxArray","compareText","features"]}),lk.addDynamicAttributes=Zz;class ndt{constructor(x){this.type=x.property.overrides?x.property.overrides.runtimeType:cd,this.defaultValue=x}evaluate(x){if(x.formattedSection){const w=this.defaultValue.property.overrides;if(w&&w.hasOverride(x.formattedSection))return w.getOverride(x.formattedSection)}return x.feature&&x.featureState?this.defaultValue.evaluate(x.feature,x.featureState):this.defaultValue.property.specification.default}eachChild(x){this.defaultValue.isConstant()||x(this.defaultValue.value._styleExpression.expression)}outputDefined(){return!1}serialize(){return null}}jr(ndt,"FormatSectionOverride",{omit:["defaultValue"]});const qRe=()=>URe||(URe={layout:tdt||(tdt=new nd({"symbol-placement":new cr(Us.layout_symbol["symbol-placement"]),"symbol-spacing":new cr(Us.layout_symbol["symbol-spacing"]),"symbol-avoid-edges":new cr(Us.layout_symbol["symbol-avoid-edges"]),"symbol-sort-key":new lr(Us.layout_symbol["symbol-sort-key"]),"symbol-z-order":new cr(Us.layout_symbol["symbol-z-order"]),"symbol-z-elevate":new cr(Us.layout_symbol["symbol-z-elevate"]),"symbol-elevation-reference":new cr(Us.layout_symbol["symbol-elevation-reference"]),"icon-allow-overlap":new cr(Us.layout_symbol["icon-allow-overlap"]),"icon-ignore-placement":new cr(Us.layout_symbol["icon-ignore-placement"]),"icon-optional":new cr(Us.layout_symbol["icon-optional"]),"icon-rotation-alignment":new cr(Us.layout_symbol["icon-rotation-alignment"]),"icon-size":new lr(Us.layout_symbol["icon-size"]),"icon-size-scale-range":new cr(Us.layout_symbol["icon-size-scale-range"]),"icon-text-fit":new lr(Us.layout_symbol["icon-text-fit"]),"icon-text-fit-padding":new lr(Us.layout_symbol["icon-text-fit-padding"]),"icon-image":new lr(Us.layout_symbol["icon-image"]),"icon-image-use-theme":new cr({type:"string",default:"default","property-type":"data-constant"}),"icon-rotate":new lr(Us.layout_symbol["icon-rotate"]),"icon-padding":new cr(Us.layout_symbol["icon-padding"]),"icon-keep-upright":new cr(Us.layout_symbol["icon-keep-upright"]),"icon-offset":new lr(Us.layout_symbol["icon-offset"]),"icon-anchor":new lr(Us.layout_symbol["icon-anchor"]),"icon-pitch-alignment":new cr(Us.layout_symbol["icon-pitch-alignment"]),"text-pitch-alignment":new cr(Us.layout_symbol["text-pitch-alignment"]),"text-rotation-alignment":new cr(Us.layout_symbol["text-rotation-alignment"]),"text-field":new lr(Us.layout_symbol["text-field"]),"text-font":new lr(Us.layout_symbol["text-font"]),"text-size":new lr(Us.layout_symbol["text-size"]),"text-size-scale-range":new cr(Us.layout_symbol["text-size-scale-range"]),"text-max-width":new lr(Us.layout_symbol["text-max-width"]),"text-line-height":new lr(Us.layout_symbol["text-line-height"]),"text-letter-spacing":new lr(Us.layout_symbol["text-letter-spacing"]),"text-justify":new lr(Us.layout_symbol["text-justify"]),"text-radial-offset":new lr(Us.layout_symbol["text-radial-offset"]),"text-variable-anchor":new cr(Us.layout_symbol["text-variable-anchor"]),"text-anchor":new lr(Us.layout_symbol["text-anchor"]),"text-max-angle":new cr(Us.layout_symbol["text-max-angle"]),"text-writing-mode":new cr(Us.layout_symbol["text-writing-mode"]),"text-rotate":new lr(Us.layout_symbol["text-rotate"]),"text-padding":new cr(Us.layout_symbol["text-padding"]),"text-keep-upright":new cr(Us.layout_symbol["text-keep-upright"]),"text-transform":new lr(Us.layout_symbol["text-transform"]),"text-offset":new lr(Us.layout_symbol["text-offset"]),"text-allow-overlap":new cr(Us.layout_symbol["text-allow-overlap"]),"text-ignore-placement":new cr(Us.layout_symbol["text-ignore-placement"]),"text-optional":new cr(Us.layout_symbol["text-optional"]),visibility:new cr(Us.layout_symbol.visibility)})),paint:sdt||(sdt=new nd({"icon-opacity":new lr(Us.paint_symbol["icon-opacity"]),"icon-occlusion-opacity":new lr(Us.paint_symbol["icon-occlusion-opacity"]),"icon-emissive-strength":new lr(Us.paint_symbol["icon-emissive-strength"]),"text-emissive-strength":new lr(Us.paint_symbol["text-emissive-strength"]),"icon-color":new lr(Us.paint_symbol["icon-color"]),"icon-halo-color":new lr(Us.paint_symbol["icon-halo-color"]),"icon-halo-width":new lr(Us.paint_symbol["icon-halo-width"]),"icon-halo-blur":new lr(Us.paint_symbol["icon-halo-blur"]),"icon-translate":new cr(Us.paint_symbol["icon-translate"]),"icon-translate-anchor":new cr(Us.paint_symbol["icon-translate-anchor"]),"icon-image-cross-fade":new cr(Us.paint_symbol["icon-image-cross-fade"]),"text-opacity":new lr(Us.paint_symbol["text-opacity"]),"text-occlusion-opacity":new lr(Us.paint_symbol["text-occlusion-opacity"]),"text-color":new lr(Us.paint_symbol["text-color"],{runtimeType:tc,getOverride:k=>k.textColor,hasOverride:k=>!!k.textColor}),"text-halo-color":new lr(Us.paint_symbol["text-halo-color"]),"text-halo-width":new lr(Us.paint_symbol["text-halo-width"]),"text-halo-blur":new lr(Us.paint_symbol["text-halo-blur"]),"text-translate":new cr(Us.paint_symbol["text-translate"]),"text-translate-anchor":new cr(Us.paint_symbol["text-translate-anchor"]),"icon-color-saturation":new cr(Us.paint_symbol["icon-color-saturation"]),"icon-color-contrast":new cr(Us.paint_symbol["icon-color-contrast"]),"icon-color-brightness-min":new cr(Us.paint_symbol["icon-color-brightness-min"]),"icon-color-brightness-max":new cr(Us.paint_symbol["icon-color-brightness-max"]),"symbol-z-offset":new lr(Us.paint_symbol["symbol-z-offset"]),"icon-color-use-theme":new lr({type:"string",default:"default","property-type":"data-driven"}),"icon-halo-color-use-theme":new lr({type:"string",default:"default","property-type":"data-driven"}),"text-color-use-theme":new lr({type:"string",default:"default","property-type":"data-driven"}),"text-halo-color-use-theme":new lr({type:"string",default:"default","property-type":"data-driven"})}))},URe);class moe extends rc{constructor(x,w,A,L){super(x,qRe(),w,A,L,x.layout?x.layout["icon-image-use-theme"]:null),this._colorAdjustmentMatrix=v([]),this.hasOcclusionOpacityProperties=x.paint!==void 0&&("icon-occlusion-opacity"in x.paint||"text-occlusion-opacity"in x.paint)}_handleSpecialPaintPropertyUpdate(x){x!=="icon-occlusion-opacity"&&x!=="text-occlusion-opacity"||(this.hasOcclusionOpacityProperties=!0)}recalculate(x,w){super.recalculate(x,w),this.appearances&&this.appearances.forEach(L=>{L.recalculate(x,w,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 A=this.layout.get("text-writing-mode");if(A){const L=[];for(const F of A)L.indexOf(F)<0&&L.push(F);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(x,w,A,L){return this._saturation===x&&this._contrast===w&&this._brightnessMin===A&&this._brightnessMax===L||(this._colorAdjustmentMatrix=function(F,U,K,X){F=Eo(F),U=Ra(U);const oe=f(),ge=F/3,we=1-2*ge,je=[we,ge,ge,0,ge,we,ge,0,ge,ge,we,0,0,0,0,1],Le=.5-.5*U,Re=X-K;return b(oe,[Re,0,0,0,0,Re,0,0,0,0,Re,0,K,K,K,1],[U,0,0,0,0,U,0,0,0,0,U,0,Le,Le,Le,1]),b(oe,oe,je),oe}(x,w,A,L),this._saturation=x,this._contrast=w,this._brightnessMin=A,this._brightnessMax=L),this._colorAdjustmentMatrix}getValueAndResolveTokens(x,w,A,L){const F=this.layout.get(x).evaluate(w,{},A,L),U=this._unevaluatedLayout._values[x];return U.isDataDriven()||Ip(U.value)||!F?F:edt(w.properties,F)}getAppearanceValueAndResolveTokens(x,w,A,L,F){const U=x.getLayoutProperty(w);if(!U)return;const K=U.evaluate(A,{},L,F),X=x.getUnevaluatedLayoutProperties()._values[w];return X.isDataDriven()||Ip(X.value)||!K||typeof K!="string"?K:edt(A.properties,K)}createBucket(x){return new lk(x)}queryRadius(){return 0}queryIntersectsFeature(){return!1}_setPaintOverrides(){for(const x of qRe().paint.overridableProperties){if(!moe.hasPaintOverride(this.layout,x))continue;const w=this.paint.get(x),A=new ndt(w),L=new Ah(A,w.property.specification,this.scope,this.options,this.layout.get("icon-image-use-theme"));let F=null;F=w.value.kind==="constant"||w.value.kind==="source"?new Qh("source",L):new Ec("composite",L,w.value.zoomStops,w.value.interpolationType),this.paint._values[x]=new sk(w.property,F,w.parameters)}}_handleOverridablePaintPropertyUpdate(x,w,A){return!(!this.layout||w.isDataDriven()||A.isDataDriven())&&moe.hasPaintOverride(this.layout,x)}static hasPaintOverride(x,w){const A=x.get("text-field"),L=qRe().paint.properties[w];let F=!1;const U=K=>{for(const X of K)if(L.overrides&&L.overrides.hasOverride(X))return void(F=!0)};if(A.value.kind==="constant"&&A.value.value instanceof dd)U(A.value.value.sections);else if(A.value.kind==="source"){const K=oe=>{F||(oe instanceof Hr&&sc(oe.value)===$t?U(oe.value.sections):oe instanceof ou?U(oe.sections):oe.eachChild(K))},X=A.value;X._styleExpression&&K(X._styleExpression.expression)}return F}getProgramIds(){return["symbol"]}getDefaultProgramParams(x,w,A){return{config:new Ke(this,{zoom:w,lut:A}),overrideFog:!1}}hasElevation(){return this.layout&&this.layout.get("symbol-elevation-reference")==="hd-road-markup"}}let rdt,adt,idt,odt;var poe=Hn([{name:"a_pos",type:"Int16",components:2},{name:"a_texture_pos",type:"Uint16",components:2}]);function foe(k,x,w,A,L,F,U,K){const X=[k,x,1,w,A,1,L,F,1],oe=[U,K,1],ge=m([],X),[we,je,Le]=Se(oe,oe,ge);return p(X,X,[we,0,0,0,je,0,0,0,Le])}function ldt(k,x,w,A,L,F,U,K){const X=function(oe,ge,we,je,Le,Re,We,et){const it=foe(0,0,1,0,1,1,0,1),yt=foe(oe,ge,we,je,Le,Re,We,et);return p(yt,yt,m([],it))}(k,x,w,A,L,F,U,K);return[X[2]/X[8]/ur,X[5]/X[8]/ur]}function xoe(k){return[k[0],Math.min(Math.max(k[1],-85.051129),Tn)]}class cdt extends Om{constructor(x,w,A,L){super(),this.id=x,this.dispatcher=A,this.coordinates=w.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=w,this._dirty=!1}load(x,w){if(this._loaded=w||!1,this.fire(new Nd("dataloading",{dataType:"source"})),this.url=this.options.url,!this.url)return x&&(this.coordinates=x),this._loaded=!0,void this._finishLoading();this._imageRequest=Yh(this.map._requestManager.transformRequest(this.url,xg.Image),(A,L)=>{this._imageRequest=null,this._loaded=!0,A?this.fire(new cf(A)):L&&(this.image=L,this._dirty=!0,this.width=this.image.width,this.height=this.image.height,x&&(this.coordinates=x),this._finishLoading())})}loaded(){return this._loaded}updateImage(x){return x.url?(this._imageRequest&&x.url!==this.options.url&&(this._imageRequest.cancel(),this._imageRequest=null),this.options.url=x.url,this.load(x.coordinates,this._loaded),this):this}setTexture(x){if(!(x.handle instanceof WebGLTexture))throw new Error("The provided handle is not a WebGLTexture instance");return this.texture=new ZK(this.map.painter.context,x.handle),this.width=x.dimensions[0],this.height=x.dimensions[1],this._dirty=!1,this._loaded=!0,this._finishLoading(),this}_finishLoading(){this.map&&(this.setCoordinates(this.coordinates),this.fire(new Nd("data",{dataType:"source",sourceDataType:"metadata"})))}onAdd(x){this.map=x,this.load()}onRemove(x){this._imageRequest&&(this._imageRequest.cancel(),this._imageRequest=null),!this.texture||this.texture instanceof ZK||this.texture.destroy(),this.boundsBuffer&&(this.boundsBuffer.destroy(),this.elevatedGlobeVertexBuffer&&this.elevatedGlobeVertexBuffer.destroy(),this.elevatedGlobeIndexBuffer&&this.elevatedGlobeIndexBuffer.destroy())}setCoordinates(x){if(this.coordinates=x,this._boundsArray=void 0,this._unsupportedCoords=!1,!x.length)return this;this.onNorthPole=!1,this.onSouthPole=!1;let w=x[0][1],A=x[0][1];for(const F of x)F[1]>A&&(A=F[1]),F[1]Tn?this.onNorthPole=!0:L<-85.051129&&(this.onSouthPole=!0),!this.onNorthPole&&!this.onSouthPole){const F=x.map(pa.fromLngLat);this.tileID=function(U){let K=1/0,X=1/0,oe=-1/0,ge=-1/0;for(const We of U)K=Math.min(K,We.x),X=Math.min(X,We.y),oe=Math.max(oe,We.x),ge=Math.max(ge,We.y);const we=Math.max(oe-K,ge-X),je=Math.max(0,Math.floor(-Math.log2(we))),Le=Math.pow(2,je);let Re=Math.floor((K+oe)/2*Le);return Re>1&&(Re-=1),new rI(je,Re,Math.floor((X+ge)/2*Le))}(F),this.minzoom=this.maxzoom=this.tileID.z}return this.fire(new Nd("data",{dataType:"source",sourceDataType:"content"})),this}_clear(){!this.texture||this.texture instanceof ZK||(this.texture.destroy(),this._dirty=!0),this.texture=null,this._boundsArray=void 0,this._unsupportedCoords=!1}_prepareData(x){for(const et in this.tiles){const it=this.tiles[et];it.state!=="loaded"&&(it.state="loaded",it.texture=this.texture)}if(this._boundsArray||this.onNorthPole||this.onSouthPole||this._unsupportedCoords)return;const w=uI(new rI(0,0,0),this.map.transform.projection),A=[w.projection.project(this.coordinates[0][0],this.coordinates[0][1]),w.projection.project(this.coordinates[1][0],this.coordinates[1][1]),w.projection.project(this.coordinates[2][0],this.coordinates[2][1]),w.projection.project(this.coordinates[3][0],this.coordinates[3][1])];if(!function(et){const it=et[1].x-et[0].x,yt=et[1].y-et[0].y,ht=et[2].x-et[1].x,Et=et[2].y-et[1].y,It=et[3].x-et[2].x,Ot=et[3].y-et[2].y,ws=et[0].x-et[3].x,ds=et[0].y-et[3].y,_s=it*Et-ht*yt,gs=ht*Ot-It*Et,ys=It*ds-ws*Ot,vn=ws*yt-it*ds;return _s>0&&gs>0&&ys>0&&vn>0||_s<0&&gs<0&&ys<0&&vn<0}(A))return console.warn("Image source coordinates are defining non-convex area in the Mercator projection"),void(this._unsupportedCoords=!0);const L=uI(this.tileID,this.map.transform.projection),[F,U,K,X]=this.coordinates.map(et=>{const it=L.projection.project(et[0],et[1]);return Kct(L,it)._round()});this.perspectiveTransform=ldt(F.x,F.y,U.x,U.y,K.x,K.y,X.x,X.y);const oe=this._boundsArray=new yo;oe.emplaceBack(F.x,F.y,0,0),oe.emplaceBack(U.x,U.y,ur,0),oe.emplaceBack(X.x,X.y,0,ur),oe.emplaceBack(K.x,K.y,ur,ur),this.boundsBuffer&&(this.boundsBuffer.destroy(),this.elevatedGlobeVertexBuffer&&this.elevatedGlobeVertexBuffer.destroy(),this.elevatedGlobeIndexBuffer&&this.elevatedGlobeIndexBuffer.destroy()),this.boundsBuffer=x.createVertexBuffer(oe,poe.members),this.boundsSegments=Rc.simpleSegment(0,0,4,2);const ge=[],we=function(et){return[xoe(et[0]),xoe(et[1]),xoe(et[2]),xoe(et[3])]}(this.coordinates),[je,Le,Re,We]=function(et){let it=et[0][0],yt=it,ht=et[0][1],Et=ht;for(let It=1;Ityt&&(yt=et[It][0]),et[It][1]Et&&(Et=et[It][1]);return[it,ht,yt-it,Et-ht]}(we);{const et=new yo,[it,yt,ht,Et]=function(Ln){let Jn=Ln[0].x,gn=Jn,Rn=Ln[0].y,qn=Rn;for(let tr=1;trgn&&(gn=Ln[tr].x),Ln[tr].yqn&&(qn=Ln[tr].y);return[Jn,Rn,gn-Jn,qn-Rn]}(A),It=Ln=>[(Ln.x-it)/ht,(Ln.y-yt)/Et],[Ot,ws,ds,_s]=A.map(It),gs=function(Ln,Jn,gn,Rn,qn,tr,pr,na){const Cr=foe(0,0,1,0,1,1,0,1);return p(Cr,Cr,m([],foe(Ln,Jn,gn,Rn,qn,tr,pr,na)))}(Ot[0],Ot[1],ws[0],ws[1],ds[0],ds[1],_s[0],_s[1]);this.elevatedGlobePerspectiveTransform=ldt(Ot[0],Ot[1],ws[0],ws[1],ds[0],ds[1],_s[0],_s[1]);const ys=(Ln,Jn)=>{ge.push(Ln.lng);const gn=Math.round((Ln.lng-je)/Re*ur),Rn=Math.round((Ln.lat-Le)/We*ur),qn=It(Jn),tr=Se([],[qn[0],qn[1],1],gs),pr=Math.round(tr[0]/tr[2]*ur),na=Math.round(tr[1]/tr[2]*ur);et.emplaceBack(gn,Rn,pr,na)},vn=A[3].x-A[0].x,wn=A[3].y-A[0].y,Pn=A[2].x-A[1].x,On=A[2].y-A[1].y;for(let Ln=0;Ln<65;Ln++){const Jn=Ln/64,gn=[A[0].x+Jn*vn,A[0].y+Jn*wn],Rn=[A[1].x+Jn*Pn,A[1].y+Jn*On],qn=Rn[0]-gn[0],tr=Rn[1]-gn[1];for(let pr=0;pr<65;pr++){const na=pr/64,Cr={x:gn[0]+qn*na,y:gn[1]+tr*na};ys(w.projection.unproject(Cr.x,Cr.y),Cr)}}this.elevatedGlobeVertexBuffer=x.createVertexBuffer(et,poe.members)}{this.maxLongitudeTriangleSize=0;let et=[],it=new Ju;const yt=(ht,Et,It)=>{it.emplaceBack(ht,Et,It);const Ot=ge[ht],ws=ge[Et],ds=ge[It],_s=Math.min(Math.min(Ot,ws),ds),gs=Math.max(Math.max(Ot,ws),ds)-_s;gs>this.maxLongitudeTriangleSize&&(this.maxLongitudeTriangleSize=gs),et.push(_s+gs/2)};for(let ht=0;ht<64;ht++)for(let Et=0;Et<64;Et++){const It=65*ht+Et,Ot=It+1,ws=It+65,ds=ws+1;yt(It,ws,Ot),yt(Ot,ws,ds)}[et,it]=function(ht,Et){const It=Array.from({length:ht.length},(ds,_s)=>_s);It.sort((ds,_s)=>ht[ds]-ht[_s]);const Ot=[],ws=new Ju;for(let ds=0;ds{U.segments.push({vertexOffset:0,primitiveOffset:we,vertexLength:w.segments[0].vertexLength,primitiveLength:je,sortKey:void 0,vaos:{}})},X=.51*this.maxLongitudeTriangleSize;if(Math.abs(A[0]-L)<=X){const we=So(A,0,A.length,L+X);return we===A.length||K(we,eo(A,we+1,A.length,L+360-X)-we),U}L0}}let udt,hdt,mdt,pdt,fdt,xdt,gdt;class ydt extends rc{constructor(x,w,A,L){super(x,{layout:udt||(udt=new nd({visibility:new cr(Us["layout_raster-particle"].visibility)})),paint:hdt||(hdt=new nd({"raster-particle-array-band":new cr(Us["paint_raster-particle"]["raster-particle-array-band"]),"raster-particle-count":new cr(Us["paint_raster-particle"]["raster-particle-count"]),"raster-particle-color":new Gy(Us["paint_raster-particle"]["raster-particle-color"]),"raster-particle-max-speed":new cr(Us["paint_raster-particle"]["raster-particle-max-speed"]),"raster-particle-speed-factor":new cr(Us["paint_raster-particle"]["raster-particle-speed-factor"]),"raster-particle-fade-opacity-factor":new cr(Us["paint_raster-particle"]["raster-particle-fade-opacity-factor"]),"raster-particle-reset-rate-factor":new cr(Us["paint_raster-particle"]["raster-particle-reset-rate-factor"]),"raster-particle-elevation":new cr(Us["paint_raster-particle"]["raster-particle-elevation"]),"raster-particle-color-use-theme":new lr({type:"string",default:"default","property-type":"data-driven"})}))},w,A,L),this._updateColorRamp(),this.lastInvalidatedAt=da.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(x){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(x){return!1}_handleSpecialPaintPropertyUpdate(x){x!=="raster-particle-color"&&x!=="raster-particle-max-speed"||(this._updateColorRamp(),this._invalidateAnimationState()),x==="raster-particle-count"&&this._invalidateAnimationState()}_updateColorRamp(){if(!this.hasColorMap())return;const x=this._transitionablePaint._values["raster-particle-color"].value.expression,w=this._transitionablePaint._values["raster-particle-max-speed"].value.expression.evaluate({zoom:0});this.colorRamp=DK({expression:x,evaluationKey:"rasterParticleSpeed",image:this.colorRamp,clips:[{start:0,end:w}],resolution:256}),this.colorRampTexture=null}_invalidateAnimationState(){this.lastInvalidatedAt=da.now()}tileCoverLift(){return this.paint.get("raster-particle-elevation")}}class gus extends rc{constructor(x,w){super(x,{},w,null),this.implementation=x,x.slot&&(this.slot=x.slot)}is3D(x){return this.implementation.renderingMode==="3d"}hasOffscreenPass(){return this.implementation.prerender!==void 0}isDraped(x){return this.implementation.renderToTile!==void 0}shouldRedrape(){return!!this.implementation.shouldRerenderTiles&&this.implementation.shouldRerenderTiles()}recalculate(){}updateTransitions(){}hasTransition(){return!1}serialize(){}onAdd(x){this.implementation.onAdd&&this.implementation.onAdd(x,x.painter.context.gl)}onRemove(x){this.implementation.onRemove&&this.implementation.onRemove(x,x.painter.context.gl)}}function VRe(k,x,w){const A=[0,0,1],L=xt([]);return Vt(L,L,w?-Ws(k)+Math.PI:Ws(k)),qt(L,L,-Ws(x)),Fe(A,A,L),Ae(A,A)}class goe{constructor(x,w,A,L){this.message=(x?`${x}: `:"")+A,L&&(this.identifier=L),w!=null&&w.__line__&&(this.line=w.__line__)}}function HRe(k,x){const w=k.indexOf("://")===-1;try{return new URL(k,w&&x?"http://example.com":void 0),!0}catch{return!1}}class vdt{constructor(x,w){this.feature=x,this.instancedDataOffset=w,this.instancedDataCount=0,this.rotation=[0,0,0],this.scale=[1,1,1],this.translation=[0,0,0]}}class bdt{constructor(){this.maxScale=1,this.maxXYTranslationDistance=0,this.instancedDataArray=new SK,this.instancesEvaluatedElevation=[],this.features=[],this.idToFeaturesIndex={}}colorForInstance(x){const w=16*x,A=this.instancedDataArray.float32;let L=Math.floor(A[w+2]);const F=1.05*(A[w+2]-L);return L/=100,[A[w]%1*1.05,A[w+1]%1*1.05,F,L]}tileCoordinatesForInstance(x){const w=16*x,A=this.instancedDataArray.float32;let L=A[w+0];return L=L>ur?L-ur:L,new Js(Math.trunc(L),Math.trunc(A[w+1]))}translationForInstance(x){const w=16*x,A=this.instancedDataArray.float32;return[A[w+4],A[w+5],A[w+6]]}rotationScaleForInstance(x){const w=16*x,A=this.instancedDataArray.float32;return[A[w+7],A[w+8],A[w+9],A[w+10],A[w+11],A[w+12],A[w+13],A[w+14],A[w+15]]}transformForInstance(x){const w=16*x,A=this.instancedDataArray.float32;return[A[w+7],A[w+8],A[w+9],A[w+4],A[w+10],A[w+11],A[w+12],A[w+5],A[w+13],A[w+14],A[w+15],A[w+6],0,0,0,1]}}class GRe{constructor(x){this.zoom=x.zoom,this.canonical=x.canonical,this.overscaledZ=this.canonical.z+Math.log2(x.overscaling),this.layers=x.layers,this.layerIds=this.layers.map(w=>w.fqid),this.projection=x.projection,this.index=x.index,this.worldview=x.worldview,this.hasZoomDependentProperties=this.layers[0].isZoomDependent(),this.stateDependentLayerIds=this.layers.filter(w=>w.isStateDependent()).map(w=>w.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=x.styleDefinedModelURLs,this.hasAppearances=null}updateFootprints(x,w){}updateAppearances(x,w,A,L){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(x,w,A,L){this.tileToMeter=Gn(A);const F=this.layers[0]._featureFilter.needGeometry;this.lookup=new Uint8Array(this.lookupDim*this.lookupDim);const U=this.layers[0].paint.get("model-elevation-reference")==="hd-road-markup"?w.elevationFeatures:void 0;for(const{feature:K,id:X,index:oe,sourceLayerIndex:ge}of x){const we=X??(K.properties&&K.properties.hasOwnProperty("id")?K.properties.id:void 0),je=oo(K,F);if(!this.layers[0]._featureFilter.filter(new $i(this.zoom,{worldview:this.worldview,activeFloors:w.activeFloors}),je,A))continue;const Le={id:we,sourceLayerIndex:ge,index:oe,geometry:F?je.geometry:Qa(K,A,L),properties:K.properties,type:K.type,patterns:{}},Re=this.addFeature(Le,Le.geometry,je,U,A);Re&&w.featureIndex.insert(K,Le.geometry,oe,ge,this.index,this.instancesPerModel[Re].instancedDataArray.length,256)}this.lookup=null}evaluateQueryRenderedFeaturePadding(){const x=this.layers[0].modelManager,w=this.layers[0].scope;let A=0;for(const L of this.modelUris){const F=x.getModel(L,w);if(!F)continue;const U=this.instancesPerModel[L];if(U){const K=.5*me(F.aabb.max,F.aabb.min)*U.maxScale+U.maxXYTranslationDistance,X=Math.min(ur,Math.max(K/this.tileToMeter,256));A=Math.max(X,A)}}return A}update(x,w,A,L){for(const F in this.instancesPerModel){const U=this.instancesPerModel[F];for(const K in x)U.idToFeaturesIndex.hasOwnProperty(K)&&(this.evaluate(U.features[U.idToFeaturesIndex[K]],x[K],U,!0),this.uploaded=!1)}this.maxHeight=0}updateZoomBasedPaintProperties(){if(!this.hasZoomDependentProperties)return!1;let x=!1;for(const w in this.instancesPerModel){const A=this.instancesPerModel[w];for(const L of A.features){const F=this.layers[0],U=L.feature,K=this.canonical,X=F.paint.get("model-rotation").evaluate(U,{},K),oe=F.paint.get("model-scale").evaluate(U,{},K),ge=F.paint.get("model-translation").evaluate(U,{},K);Ye(L.rotation,X)&&Ye(L.scale,oe)&&Ye(L.translation,ge)||(this.evaluate(L,L.featureStates,A,!0),x=!0)}}return x}updateReplacement(x,w,A,L){if(w.updateTime===this.replacementUpdateTime)return!1;this.replacementUpdateTime=w.updateTime;const F=w.getReplacementRegionsForTile(x.toUnwrapped(),!0);if(Rie(this.activeReplacements,F))return!1;this.activeReplacements=F;let U=!1;for(const K in this.instancesPerModel){const X=this.instancesPerModel[K],oe=X.instancedDataArray;for(const ge of X.features){const we=ge.instancedDataOffset,je=ge.instancedDataCount;for(let Le=0;Leur;We=et?We-ur:We;const it=Math.floor(We),yt=Math.floor(oe.float32[Re+1]);let ht=!1;for(const Et of this.activeReplacements)if(!tlt(Et,A,Fie.Model,L)&&!(Et.min.x>it||it>Et.max.x||Et.min.y>yt||yt>Et.max.y)&&(ht=ilt(alt(it,yt,x.canonical,Et.footprintTileId.canonical),Et.footprint),ht))break;oe.float32[Re]=ht?We+ur:We,U=U||ht!==et}}}return U}isEmpty(){for(const x in this.instancesPerModel)if(this.instancesPerModel[x].instancedDataArray.length!==0)return!1;return!0}uploadPending(){return!this.uploaded}upload(x){if(!this.uploaded)for(const w in this.instancesPerModel){const A=this.instancesPerModel[w];A.instancedDataArray.length<0||A.instancedDataArray.length===0||(A.instancedDataBuffer?A.instancedDataBuffer.updateData(A.instancedDataArray):A.instancedDataBuffer=x.createVertexBuffer(A.instancedDataArray,Rcs.members,!0,void 0,this.instanceCount))}this.uploaded=!0}destroy(x){for(const A in this.instancesPerModel){const L=this.instancesPerModel[A];L.instancedDataArray.length!==0&&L.instancedDataBuffer&&L.instancedDataBuffer.destroy()}const w=this.layers[0].modelManager;if(x&&w&&this.modelUris&&this.modelsRequested)for(const A of this.modelUris)w.removeModel(A,"",!0)}addFeature(x,w,A,L,F){const U=this.layers[0],K=U.layout.get("model-id"),X=U.layout.get("model-allow-density-reduction"),oe=K.evaluate(A,{},this.canonical);if(!oe)return Br(`modelId is not evaluated for layer ${U.id} and it is not going to get rendered.`),oe;(HRe(oe,!1)||this.styleDefinedModelURLs[oe]!==void 0)&&(this.modelUris.includes(oe)||this.modelUris.push(oe)),this.instancesPerModel[oe]||(this.instancesPerModel[oe]=new bdt);const ge=this.instancesPerModel[oe],we=ge.instancedDataArray,je=new vdt(A,we.length);let Le;L&&(Le=Wc.getElevationFeature(x,L));for(const Re of w)for(const We of Re){if(We.x<0||We.x>=ur||We.y<0||We.y>=ur)continue;if(this.lookupDim!==0&&X){const it=(this.lookupDim-1)/ur,yt=this.lookupDim*(We.y*it|0)+We.x*it|0;if(this.lookup){if(this.lookup[yt]!==0)continue;this.lookup[yt]=1}}this.instanceCount++;const et=we.length;if(we.resize(et+1),L){ge.instancesRoadElevation||(ge.instancesRoadElevation=[]);const it=Le?Le.pointElevation(new Js(We.x,We.y)):0;ge.instancesRoadElevation.push(it)}ge.instancesEvaluatedElevation.push(0),we.float32[16*et]=We.x,we.float32[16*et+1]=We.y}return je.instancedDataCount=ge.instancedDataArray.length-je.instancedDataOffset,je.instancedDataCount>0&&(x.id&&(ge.idToFeaturesIndex[x.id]=ge.features.length),ge.features.push(je),this.evaluate(je,{},ge,!1)),oe}getModelUris(){return this.modelUris}evaluate(x,w,A,L){const F=this.layers[0],U=x.feature,K=this.canonical,X=x.rotation=F.paint.get("model-rotation").evaluate(U,w,K),oe=x.scale=F.paint.get("model-scale").evaluate(U,w,K),ge=x.translation=F.paint.get("model-translation").evaluate(U,w,K),we=Object.assign({},F.paint.get("model-color").evaluate(U,w,K));we.a=F.paint.get("model-color-mix-intensity").evaluate(U,w,K);const je=[];this.maxVerticalOffset0?Math.sqrt(Le):0;A.maxScale=Math.max(Math.max(A.maxScale,oe[0]),Math.max(oe[1],oe[2])),A.maxXYTranslationDistance=Math.max(A.maxXYTranslationDistance,Re),this.maxScale=Math.max(Math.max(this.maxScale,oe[0]),Math.max(oe[1],oe[2])),Vlt(je,X,oe);const We=Math.round(100*we.a)+we.b/1.05;for(let et=0;et10?this.tileToMeter:Gn(K,It)),ht[yt+4]=ge[0],ht[yt+5]=ge[1],ht[yt+6]=ge[2]+(A.instancesRoadElevation?A.instancesRoadElevation[it]:0)+Et,ht[yt+7]=je[0],ht[yt+8]=je[1],ht[yt+9]=je[2],ht[yt+10]=je[4],ht[yt+11]=je[5],ht[yt+12]=je[6],ht[yt+13]=je[8],ht[yt+14]=je[9],ht[yt+15]=je[10],A.instancesEvaluatedElevation[it]=ge[2]}}}jr(GRe,"ModelBucket",{omit:["layers"]}),jr(bdt,"PerModelAttributes"),jr(vdt,"ModelFeature");class Qz{constructor(x,w,A){this._demTile=x,this._dem=this._demTile.dem,this._scale=w,this._offset=A}static create(x,w,A){const L=A||x.findDEMTileFor(w);if(!L||!L.dem)return;const F=L.dem,U=L.tileID,K=1<oe.fqid),this.stateDependentLayerIds=this.layers.filter(oe=>oe.isStateDependent()).map(oe=>oe.id),this.modelTraits|=Vz.CoordinateSpaceTile,this.uploaded=!1,this.hasPattern=!1,L&&(this.modelTraits|=Vz.HasMapboxMeshFeatures),F&&(this.modelTraits|=Vz.HasMeshoptCompression),this.zoom=-1,this.terrainExaggeration=1,this.projection={name:"mercator"},this.replacementUpdateTime=0,this.elevationReadFromZ=255,this.brightness=U,this.worldview=X,this.dirty=!0,this.needsUpload=!1,this.filter=null,this.nodesInfo=[];for(const oe of w)this.nodesInfo.push(new Ndt(oe)),wdt(oe,K.featureIndexArray.length,K.grid),K.featureIndexArray.emplaceBack(this.nodesInfo.length-1,0,K.bucketLayerIDs.length-1,0);this.states={},this.hasAppearances=null}updateFootprints(x,w){for(const A of this.getNodesInfo()){const L=A.node;L.footprint&&w.push({footprint:L.footprint,id:x})}}updateAppearances(x,w,A,L){return{hasLayoutChanges:!1,hasUboChanges:!1}}update(x){const w=Object.keys(x).length!==0;if(w&&!this.stateDependentLayers.length)return;const A=w?this.stateDependentLayers:this.layers;if(!Fa(x,this.states))for(const L of A)this.evaluate(L,x);this.states=structuredClone(x)}populate(){console.log("populate 3D model bucket")}uploadPending(){return!this.uploaded||this.needsUpload}upload(x){if(!this.needsUpload)return;const w=this.getNodesInfo();for(const A of w){const L=A.node;this.uploaded?this.updatePbrBuffer(L):dRe(L,x,!0)}for(const A of w)Zie(A.node);this.uploaded=!0,this.needsUpload=!1}updatePbrBuffer(x){let w=!1;if(!x.meshes)return w;for(const A of x.meshes)A.pbrBuffer&&(A.pbrBuffer.updateData(A.featureArray),w=!0);return w}needsReEvaluation(x,w,A){const L=x.transform.projectionOptions,F=x.style.getBrightness(),U=this.brightness!==F;if(!this.uploaded||this.dirty||L.name!==this.projection.name||hY(A.paint.get("model-color").value,U)||hY(A.paint.get("model-color-mix-intensity").value,U)||hY(A.paint.get("model-roughness").value,U)||hY(A.paint.get("model-emissive-strength").value,U)||hY(A.paint.get("model-height-based-emissive-strength-multiplier").value,U)){this.projection=L,this.brightness=F;const K=this.getNodesInfo();for(const X of K)X.state=null;return!0}return!1}evaluateTransform(x,w){if(x.transform.zoom===this.zoom)return;this.zoom=x.transform.zoom;const A=this.getNodesInfo(),L=this.id.canonical;for(const F of A){const U=F.feature;F.evaluatedTranslation=w.paint.get("model-translation").evaluate(U,{},L),F.evaluatedScale=w.paint.get("model-scale").evaluate(U,{},L)}}evaluate(x,w){const A=this.getNodesInfo();for(const L of A){if(!L.node.meshes)continue;const F=L.feature,U=w&&w[F.id];if(Fa(U,L.state))continue;L.state=structuredClone(U);const K=L.node.meshes&&L.node.meshes[0].featureData,X=L.evaluatedColor[2],oe=L.evaluatedRMEA[2],ge=this.id.canonical;if(L.hasTranslucentParts=!1,K){for(let we=0;we=Ot)continue;const Jn=WRe[Ln],gn=Math.abs(Jn);gn>ys&&(gs=Jn,ys=gn,vn=On,wn=Pn)}if(ys>.1){const Pn=1-(Ot+.5*Math.abs(vn*wn))/Re;let On=w._dem.get(ds,ws)+gs*Pn;const Ln=w._dem.get(ds+vn,ws+wn),Jn=w._dem.get(ds-vn,ws-wn,!0);(On-Ln)*(On-Jn)>0&&(On=(Ln+Jn)/2),WRe[_s]=w._dem.set(ds,ws,On),hI[_s]=Ot}}}}}K&&(w._demTile.needsDEMTextureUpload=!0,w._dem._timestamp=da.now())}setFilter(x){this.filter=x?eT(x):null}getNodesInfo(){return this.filter?this.nodesInfo.filter(x=>this.filter.filter(new $i(this.id.overscaledZ,{worldview:this.worldview}),x.feature,this.id.canonical)):this.nodesInfo}destroy(){const x=this.getNodesInfo();for(const w of x)Zie(w.node),uRe(w.node)}isEmpty(){return!this.nodesInfo.length}updateReplacement(x,w){if(w.updateTime===this.replacementUpdateTime)return;this.replacementUpdateTime=w.updateTime;const A=w.getReplacementRegionsForTile(x.toUnwrapped());for(const L of this.getNodesInfo()){const F=L.node.footprint;L.hiddenByReplacement=!!F&&!A.find(U=>U.footprint===F)}}getHeightAtTileCoord(x,w){const A=[],L=[0,0,0],F=v([]);for(const U of this.getNodesInfo()){const K=U.node.meshes[0],X=K.transformedAabb;if(xX.max[0]||w>X.max[1])continue;if(U.node.hidden===!0)return{height:1/0,maxHeight:U.feature.properties.height,hidden:!1,verticalScale:U.evaluatedScale[2]};g(F,U.node.globalMatrix),L[0]=x,L[1]=w,Ze(L,L,F);const oe=(L[0]-K.aabb.min[0])/(K.aabb.max[0]-K.aabb.min[0])*oI|0,ge=Math.min(63,(L[1]-K.aabb.min[1])/(K.aabb.max[1]-K.aabb.min[1])*oI|0)*oI+Math.min(63,oe),we=K.heightmap[ge];if(!(we<0&&U.node.footprint))return U.hiddenByReplacement?void 0:{height:we,maxHeight:U.feature.properties.height,hidden:!1,verticalScale:U.evaluatedScale[2]};if(U.node.footprint.grid.query(new Js(x,w),new Js(x,w),A),A.length>0)return{height:void 0,maxHeight:U.feature.properties.height,hidden:U.hiddenByReplacement,verticalScale:U.evaluatedScale[2]}}}}function hY(k,x){return k instanceof Qh&&!k.isLightConstant&&x}function yus(k,x,w,A,L,F,U,K){let X=(61440&x|(61440&x)>>4)>>8,oe=(3840&x|(3840&x)>>4)>>4,ge=240&x|(240&x)>>4;w[3]>0&&(X=Ar(X,255*w[0],w[3]),oe=Ar(oe,255*w[1],w[3]),ge=Ar(ge,255*w[2],w[3]));const we=X<<8|oe,je=ge<<8|Math.floor(255*A[3]),Le=function(Ot){const ws=pt(Ot,0,2);return Math.min(Math.round(.5*ws*255),255)}(A[2])<<8|15*A[0]<<4|15*A[1],Re=pt(L[0],0,1),We=pt(L[1],0,1),et=pt(L[2],0,1),it=pt(L[3],0,1);let yt,ht,Et,It;if(Re!==We&&U!==F&&We!==Re){const Ot=U-F;ht=1/(Ot*(We-Re)),Et=-(F+Ot*Re)/(Ot*(We-Re));const ws=pt(L[4],-1,1);It=Math.pow(10,ws),yt=255*et<<8|255*it}else yt=65535,ht=0,Et=1,It=1;if(k.emplaceBack(we,je,Le,yt,ht,Et,It),K){const Ot=K.length;K.clear();for(let ws=0;ws>16&65535,ge=F?X>>16&65535:65535&X,we=(15&ge)<8?15&ge:0,je=k.evaluatedRMEA[we],Le=k.evaluatedColor[we],Re=k.emissionHeightBasedParams[we];let We;if(K&&we===2&&A.lights&&(We=new Pz,We.resize(10*A.lights.length)),yus(U.featureArray,oe,Le,je,Re,U.aabb.min[2],U.aabb.max[2],We),We&&K){K=!1;const et=A.meshes[A.lightMeshIndex];et.featureArray=We,et.featureArray._trim()}}U.featureArray._trim(),L++}}jr(yoe,"Tiled3dModelBucket",{omit:["layers"]}),jr(Ndt,"Tiled3dModelFeature");const bus=["id","tile","layer","source","sourceLayer","state"];class mI{constructor(x,w,A,L,F){this.type="Feature",this._vectorTileFeature=x,this._z=w,this._x=A,this._y=L,this.properties=x?x.properties:{},this.id=F}clone(){const x=new mI(this._vectorTileFeature,this._z,this._x,this._y,this.id);return this.state&&(x.state=Object.assign({},this.state)),this.layer&&(x.layer=Object.assign({},this.layer)),this.source&&(x.source=this.source),this.sourceLayer&&(x.sourceLayer=this.sourceLayer),x}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(x){this._geometry=x}toJSON(){const x={type:"Feature",state:void 0,geometry:this.geometry,properties:this.properties};for(const w of bus)this[w]!==void 0&&(x[w]=this[w]);return x}}class pI extends Om{constructor(x,w,A,L){super(),this.id=x,this.type="model",this.models=[],this._options=w,this._modelsInfo=new Map,this._abortController=null}cancelModelRequests(){this._abortController&&(this._abortController.abort(),this._abortController=null)}loadGLTFFromURI(x,w){return Blt(this.map._requestManager.transformRequest(x,xg.Model).url,w)}async loadModel(x,w,A){try{const L=await this.loadGLTFFromURI(w.uri,A);if(A.aborted)return;const F=this._modelsInfo.get(x);if(!F)return;const U=mRe(L),K=F.modelSpec,X=new Hlt(x,K.uri,K.position,K.orientation,U);pI.applyModelSpecification(X,K),X.computeBoundsAndApplyParent(),this.models.push(X),F.model=X}catch(L){if(L instanceof Error&&L.name==="AbortError")return;const F=L instanceof Error?L.message:"Unknown error";this.fire(new cf(new Error(`Could not load model ${x} from ${w.uri}: ${F}`)))}}async load(){this._abortController||(this._abortController=new AbortController);const x=this._abortController.signal,w=[];for(const A in this._options.models){const L=this._options.models[A],F=this._modelsInfo.get(A);if(F&&F.model){F.modelSpec=L;const U=F.model;U.position=L.position!=null?new Es(L.position[0],L.position[1]):new Es(0,0),U.orientation=L.orientation!=null?L.orientation:[0,0,0],pI.applyModelSpecification(U,L),U.computeBoundsAndApplyParent(),this.models.push(U)}else F?F.modelSpec=L:(this._modelsInfo.set(A,{modelSpec:L,model:null}),w.push(this.loadModel(A,L,x)))}w.length!==0?(await Promise.allSettled(w),x.aborted||this.fire(new Nd("data",{dataType:"source",sourceDataType:"metadata"}))):this.loaded()&&this.fire(new Nd("data",{dataType:"source",sourceDataType:"metadata"}))}static applyModelSpecification(x,w){w.nodeOverrides&&pI.convertNodeOverrides(x,w.nodeOverrides),w.materialOverrides&&pI.convertMaterialOverrides(x,w.materialOverrides),w.nodeOverrideNames&&(x.nodeOverrideNames=[...w.nodeOverrideNames]),w.materialOverrideNames&&(x.materialOverrideNames=[...w.materialOverrideNames]),w.featureProperties&&(x.featureProperties=w.featureProperties)}static convertNodeOverrides(x,w){if(Array.isArray(w)&&w.every(A=>typeof A=="string")){x.nodeOverrideNames=[];for(const A of w)x.nodeOverrideNames.push(A)}else Object.entries(w).forEach(([A,L])=>{const F={orientation:[0,0,0]};if(L.hasOwnProperty("orientation")){const U=L.orientation;U&&(F.orientation=U)}x.nodeOverrides.set(A,F)})}static convertMaterialOverrides(x,w){if(Array.isArray(w)&&w.every(A=>typeof A=="string")){x.materialOverrideNames=[];for(const A of w)x.materialOverrideNames.push(A)}else Object.entries(w).forEach(([A,L])=>{const F={color:new Xs(1,1,1),colorMix:0,emissionStrength:0,opacity:1},U=L["model-color"];U!==void 0&&(F.color.r=U[0],F.color.g=U[1],F.color.b=U[2]);const K=L["model-color-mix-intensity"];K!==void 0&&(F.colorMix=K);const X=L["model-emissive-strength"];X!==void 0&&(F.emissionStrength=X);const oe=L["model-opacity"];oe!==void 0&&(F.opacity=oe),x.materialOverrides.set(A,F)})}onAdd(x){this.map=x,this.load()}hasTransition(){return!1}loaded(){if(this._modelsInfo.size===0)return!0;for(const x of this._modelsInfo.values())if(x.model==null)return!1;return!0}getModels(){return this.models}loadTile(x,w){}serialize(){return this._options}setProperty(x,w){return!1}reload(){this.cancelModelRequests();const x=Lt(this.id,this.scope);this.map.style.clearSource(x),this.models=[],this._modelsInfo.clear(),this.load()}onRemove(x){this.cancelModelRequests()}setModels(x){this.models=[];const w=new Map;for(const A in x){const L=x[A],F=this._modelsInfo.get(A);F&&F.modelSpec.uri===L.uri&&w.set(A,F)}if(this._modelsInfo.size!==w.size){this.cancelModelRequests();for(const[A,L]of w)L.model||w.delete(A)}this._modelsInfo=w,this._options.models=x,this.load()}}function KRe(k,x,w,A){const L=1<X>=It.vertexArrayOffset&&XEt.polygon).flat());const et=Le?K:null,[it,yt]=klt(F,A,we,ge,oe,U,et,je,Re,F.center.lat,k.tileID.canonical),ht=k.queryGeometry;return Nlt(it,yt,ht.isPointQuery()?ht.screenBounds:ht.screenGeometry)}},building:class extends rc{constructor(k,x,w,A){super(k,{layout:Qlt||(Qlt=new nd({visibility:new cr(Us.layout_building.visibility),"building-facade":new lr(Us.layout_building["building-facade"]),"building-facade-floors":new lr(Us.layout_building["building-facade-floors"]),"building-facade-unit-width":new lr(Us.layout_building["building-facade-unit-width"]),"building-facade-window":new lr(Us.layout_building["building-facade-window"]),"building-roof-shape":new lr(Us.layout_building["building-roof-shape"]),"building-height":new lr(Us.layout_building["building-height"]),"building-base":new lr(Us.layout_building["building-base"]),"building-flood-light-wall-radius":new lr(Us.layout_building["building-flood-light-wall-radius"]),"building-flood-light-ground-radius":new lr(Us.layout_building["building-flood-light-ground-radius"]),"building-flip-roof-orientation":new lr(Us.layout_building["building-flip-roof-orientation"])})),paint:Jlt||(Jlt=new nd({"building-opacity":new cr(Us.paint_building["building-opacity"]),"building-ambient-occlusion-intensity":new cr(Us.paint_building["building-ambient-occlusion-intensity"]),"building-ambient-occlusion-ground-intensity":new cr(Us.paint_building["building-ambient-occlusion-ground-intensity"]),"building-ambient-occlusion-ground-radius":new cr(Us.paint_building["building-ambient-occlusion-ground-radius"]),"building-ambient-occlusion-ground-attenuation":new cr(Us.paint_building["building-ambient-occlusion-ground-attenuation"]),"building-vertical-scale":new cr(Us.paint_building["building-vertical-scale"]),"building-cast-shadows":new cr(Us.paint_building["building-cast-shadows"]),"building-color":new lr(Us.paint_building["building-color"]),"building-emissive-strength":new lr(Us.paint_building["building-emissive-strength"]),"building-facade-emissive-chance":new cr(Us.paint_building["building-facade-emissive-chance"]),"building-cutoff-fade-range":new cr(Us.paint_building["building-cutoff-fade-range"]),"building-front-cutoff":new cr(Us.paint_building["building-front-cutoff"]),"building-flood-light-color":new cr(Us.paint_building["building-flood-light-color"]),"building-flood-light-intensity":new cr(Us.paint_building["building-flood-light-intensity"]),"building-flood-light-ground-attenuation":new cr(Us.paint_building["building-flood-light-ground-attenuation"]),"building-color-use-theme":new lr({type:"string",default:"default","property-type":"data-driven"}),"building-flood-light-color-use-theme":new lr({type:"string",default:"default","property-type":"data-driven"})}))},x,w,A),this._stats={numRenderedVerticesInShadowPass:0,numRenderedVerticesInTransparentPass:0}}createBucket(k){return new Xlt(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,x,w,A,L,F,U,K,X,oe){let ge=this.layout.get("building-height").evaluate(x,w);const we=this.layout.get("building-base").evaluate(x,w),je=k.tile.getBucket(this).getFootprint(x);if(je){if(je.hiddenFlags!==0)return!1;ge=je.height}const[Le,Re]=klt(F,A,we,ge,new Js(0,0),U,null,[0,0],1,F.center.lat,k.tileID.canonical),We=k.queryGeometry;return Nlt(Le,Re,We.isPointQuery()?We.screenBounds:We.screenGeometry)}},line:class extends rc{constructor(k,x,w,A){const L=cct();super(k,L,x,w,A),L.layout&&(this.layout=new Op(L.layout)),this.gradientVersion=0,this.hasElevatedBuckets=!1,this.hasNonElevatedBuckets=!1}_handleSpecialPaintPropertyUpdate(k){if(k==="line-gradient"){const x=this._transitionablePaint._values["line-gradient"].value.expression;this.stepInterpolant=x._styleExpression&&x._styleExpression.expression instanceof Yj,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,x){super.recalculate(k,x),this.paint._values["line-floorwidth"]=(()=>{if(QK)return QK;const w=cct();return QK=new pds(w.paint.properties["line-width"].specification),QK.useIntegerZoom=!0,QK})().possiblyEvaluate(this._transitioningPaint._values["line-width"].value,k)}createBucket(k){return new Qie(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,x,w){if(k==="lineBlendComposite")return{};const A=oct(this);return{config:new Ke(this,{zoom:x,lut:w}),defines:A,overrideFog:!1}}queryRadius(k){const x=k,w=dct(iT("line-width",this,x),iT("line-gap-width",this,x)),A=iT("line-offset",this,x);return w/2+Math.abs(A)+wie(this.paint.get("line-translate"))}queryIntersectsFeature(k,x,w,A,L,F){if(k.queryGeometry.isAboveHorizon)return!1;const U=lot(k.tilespaceGeometry,this.paint.get("line-translate"),this.paint.get("line-translate-anchor"),F.angle,k.pixelToTileUnitsFactor),K=k.pixelToTileUnitsFactor/2*dct(this.paint.get("line-width").evaluate(x,w),this.paint.get("line-gap-width").evaluate(x,w)),X=this.paint.get("line-offset").evaluate(x,w);return X&&(A=function(oe,ge){const we=[],je=new Js(0,0);for(let Le=0;Le=3){for(let Re=0;Re{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 kdt{constructor(x){this._stringToNumber={},this._numberToString=[];for(let w=0;w=0&&je[3]>=0&&oe.insert(X,je[0],je[1],je[2],je[3])}}loadVTLayers(){if(!this.vtLayers){this.vtLayers=new yl(new Jie(this.rawTileData)).layers,this.sourceLayerCoder=new kdt(this.vtLayers?Object.keys(this.vtLayers).sort():["_geojsonTileLayer"]),this.vtFeatures={};for(const x in this.vtLayers)this.vtFeatures[x]=[]}return this.vtLayers}query(x,w){const{tilespaceGeometry:A,transform:L,tileTransform:F,pixelPosMatrix:U,availableImages:K,worldview:X}=w;this.loadVTLayers(),this.serializedLayersCache.clear();const oe=w.queryRadius?w.queryRadius:0,ge=A.bufferedTilespaceBounds,we=this.grid.query(ge.min.x,ge.min.y,ge.max.x,ge.max.y,(We,et,it,yt)=>c5(A.bufferedTilespaceGeometry,We-oe,et-oe,it+oe,yt+oe));we.sort(Nus);let je=null;L.elevation&&we.length>0&&(je=Qz.create(L.elevation,this.tileID));const Le={};let Re;for(let We=0;We(yt||(yt=Qa(ht,this.tileID.canonical,F)),Et.queryIntersectsFeature(A,ht,It,yt,this.z,L,U,je,Ot,w.scope)))}return Le}loadMatchingFeature(x,w,A,L,F,U){const{featureIndex:K,bucketIndex:X,sourceLayerIndex:oe,layoutVertexArrayOffset:ge}=w,we=this.bucketLayerIDs[X],je=A.layers,Le=Object.keys(je);if(Le.length&&!Xr(Le,we))return;const Re=A.sourceCache,We=this.sourceLayerCoder.decode(oe),et=this.vtLayers[We].feature(K),it=this.getId(et,We);for(let yt=0;yt`${K.key}: ${K.message}`).join(", ");return void Br(`Failed to create expression for promoteId: ${U}`)}this.promoteIdExpression=F.value}A=this.promoteIdExpression.evaluate({zoom:0},x)}else A=x.properties[L];typeof A=="boolean"&&(A=Number(A))}return A}}function Cdt(k,x,w,A,L){return Qs(k,(F,U)=>{const K=x instanceof Op?x.get(U):null;return K&&K.evaluate?K.evaluate(w,A,void 0,L):K})}function Nus(k,x){return x-k}function Adt(k,x){const w={};if(!x)return w;for(const A of k){const L=A.layerIds.map(F=>x.getLayer(F)).filter(Boolean);if(L.length!==0){A.layers=L,A.stateDependentLayerIds&&(A.stateDependentLayers=A.stateDependentLayerIds.map(F=>L.filter(U=>U.id===F)[0]));for(const F of L)w[F.fqid]=A}}return w}jr(Sdt,"FeatureIndex",{omit:["rawTileData","sourceLayerCoder"]});const l2=32,x5=33,mT=new Uint16Array(8184);for(let k=0;k<2046;k++){let x=k+2,w=0,A=0,L=0,F=0,U=0,K=0;for(1&x?L=F=U=l2:w=A=K=l2;(x>>=1)>1;){const oe=w+L>>1,ge=A+F>>1;1&x?(L=w,F=A,w=U,A=K):(w=L,A=F,L=U,F=K),U=oe,K=ge}const X=4*k;mT[X+0]=w,mT[X+1]=A,mT[X+2]=L,mT[X+3]=F}const g5=new Uint16Array(2178),pT=new Uint8Array(1089),voe=new Uint16Array(1089);function Edt(k){return k===0?-.03125:k===32?.03125:0}const Tdt={Other:0,Symbol:1,FillExtrusion:2},Mdt={type:2,extent:ur,loadGeometry:()=>[[new Js(0,0),new Js(8193,0),new Js(8193,8193),new Js(0,8193),new Js(0,0)]]};class kus{constructor(){this.tasks={},this.taskQueue=[],Kt(["process"],this),this.invoker=new jus(this.process),this.nextId=0}add(x,w){const A=this.nextId++,L=function({type:F,renderSourceType:U,zoom:K}){K=K||0;const X=U===Tdt.Symbol;return F==="message"?0:F!=="maybePrepare"||X?F!=="parseTile"||X?F==="parseTile"&&X?300-K:F==="maybePrepare"&&X?400-K:500:200-K:100-K}(w);if(L===0){try{x()}finally{}return null}return this.tasks[A]={fn:x,metadata:w,priority:L,id:A},this.taskQueue.push(A),this.invoker.trigger(),{cancel:()=>{delete this.tasks[A]}}}process(){try{if(this.taskQueue=this.taskQueue.filter(A=>!!this.tasks[A]),!this.taskQueue.length)return;const x=this.pick();if(x===null)return;const w=this.tasks[x];if(delete this.tasks[x],this.taskQueue.length&&this.invoker.trigger(),!w)return;w.fn()}finally{}}pick(){let x=null,w=1/0;for(let L=0;L>16&255)/255,(k>>8&255)/255,(255&k)/255,1)}function Fus(k,x,w){k===1?(x.rgb_color=woe(w.readVarint()),x.paint="rgb_color"):k===2?(x.linear_gradient_idx=w.readVarint(),x.paint="linear_gradient_idx"):k===3?(x.radial_gradient_idx=w.readVarint(),x.paint="radial_gradient_idx"):k===5?w.readPackedFloat(x.dasharray):k===6?x.dashoffset=w.readFloat():k===7?x.miterlimit=w.readFloat():k===8?x.opacity=w.readVarint():k===9?x.width=w.readFloat():k===10?x.linecap=w.readVarint():k===11&&(x.linejoin=w.readVarint())}function Ous(k,x,w){k===1?x.transform=_oe(w,w.readVarint()+w.pos):k===2?x.spread_method=w.readVarint():k===3?x.stops.push(Idt(w,w.readVarint()+w.pos)):k===4?x.x1=w.readFloat():k===5?x.y1=w.readFloat():k===6?x.x2=w.readFloat():k===7&&(x.y2=w.readFloat())}function Idt(k,x){return k.readFields(zus,{offset:0,opacity:255,rgb_color:YRe},x)}function zus(k,x,w){k===1?x.offset=w.readFloat():k===2?x.opacity=w.readVarint():k===3&&(x.rgb_color=woe(w.readVarint()))}function Bus(k,x,w){k===1?x.transform=_oe(w,w.readVarint()+w.pos):k===2?x.spread_method=w.readVarint():k===3?x.stops.push(Idt(w,w.readVarint()+w.pos)):k===4?x.cx=w.readFloat():k===5?x.cy=w.readFloat():k===6?x.r=w.readFloat():k===7?x.fx=w.readFloat():k===8?x.fy=w.readFloat():k===9&&(x.fr=w.readFloat())}function Uus(k,x,w){k===1?x.transform=_oe(w,w.readVarint()+w.pos):k===2?x.clip_path_idx=w.readVarint():k===3&&x.children.push(boe(w,w.readVarint()+w.pos))}function qus(k,x,w){k===1?x.left=x.top=w.readFloat():k===2?x.width=x.height=w.readFloat():k===3?x.top=w.readFloat():k===4?x.height=w.readFloat():k===5?x.mask_type=w.readVarint():k===6?x.mask_idx=w.readVarint():k===7&&x.children.push(boe(w,w.readVarint()+w.pos))}class $us{static calculate(x={},w=[]){const A=new Map,L=new Map;if(Object.keys(x).length===0)return A;w.forEach(F=>{L.set(F.name,F.rgb_color||new Xs(0,0,0))});for(const[F,U]of Object.entries(x))L.has(F)?A.set(L.get(F).toString(),U):console.warn(`Ignoring unknown image variable "${F}"`);return A}}function Jz(k,x=255,w){const A=x/255,L=k.toString(),F=w.has(L)?w.get(L).clone():k.clone();return F.a*=A,F.toString()}function mY(k,x){if(!xs()){const w=document.createElement("canvas");return w.width=k,w.height=x,w}return new OffscreenCanvas(k,x)}let ZRe,pY=null;function XRe(k,x,w,A,L){for(const F of A.children)Ddt(k,x,w,F,L)}function Ddt(k,x,w,A,L){A.group?(k.save(),function(F,U,K,X,oe){const ge=X.mask_idx!=null?K.masks[X.mask_idx]:null,we=X.clip_path_idx!=null?K.clip_paths[X.clip_path_idx]:null;if(X.transform&&(U=eB(X.transform).preMultiplySelf(U)),!function(Re,We,et){return Re.opacity!==255||We||et}(X,we!=null,ge!=null))return void XRe(F,U,K,X,oe);const je=mY(F.canvas.width,F.canvas.height),Le=je.getContext("2d");XRe(Le,U,K,X,oe),we&&qdt(Le,U,K,we),ge&&$dt(Le,U,K,ge,oe),F.globalAlpha=X.opacity/255,F.drawImage(je,0,0)}(k,x,w,A.group,L),k.restore()):A.path&&(k.save(),function(F,U,K,X,oe){F.setTransform(U),X.paint_order===1?(Rdt(F,K,X,oe),Odt(F,K,X,oe)):(Odt(F,K,X,oe),Rdt(F,K,X,oe))}(k,x,w,A.path,L),k.restore())}function Rdt(k,x,w,A){const L=w.fill;if(!L)return;const F=L.opacity/255;switch(k.save(),k.beginPath(),Vdt(w,k),L.paint){case"rgb_color":k.fillStyle=Jz(L.rgb_color,L.opacity,A);break;case"linear_gradient_idx":{const U=x.linear_gradients[L.linear_gradient_idx];U.transform&&k.setTransform(eB(U.transform).preMultiplySelf(k.getTransform())),k.fillStyle=zdt(k,U,F,A);break}case"radial_gradient_idx":{const U=x.radial_gradients[L.radial_gradient_idx];U.transform&&k.setTransform(eB(U.transform).preMultiplySelf(k.getTransform())),k.fillStyle=Bdt(k,U,F,A)}}k.fill(Fdt(w)),k.restore()}function Fdt(k){return k.rule===1?"nonzero":k.rule===2?"evenodd":void 0}function Odt(k,x,w,A){const L=w.stroke;if(!L)return;const F=Hdt(w);k.lineWidth=L.width,k.miterLimit=L.miterlimit,k.setLineDash(L.dasharray),k.lineDashOffset=L.dashoffset;const U=L.opacity/255;switch(L.paint){case"rgb_color":k.strokeStyle=Jz(L.rgb_color,L.opacity,A);break;case"linear_gradient_idx":k.strokeStyle=zdt(k,x.linear_gradients[L.linear_gradient_idx],U,A,!0);break;case"radial_gradient_idx":k.strokeStyle=Bdt(k,x.radial_gradients[L.radial_gradient_idx],U,A,!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(F)}function zdt(k,x,w,A,L=!1){if(x.stops.length===1){const je=x.stops[0];return Jz(je.rgb_color,je.opacity*w,A)}const{x1:F,y1:U,x2:K,y2:X}=x;let oe=new DOMPoint(F,U),ge=new DOMPoint(K,X);if(L){const je=eB(x.transform);oe=je.transformPoint(oe),ge=je.transformPoint(ge)}const we=k.createLinearGradient(oe.x,oe.y,ge.x,ge.y);for(const je of x.stops)we.addColorStop(je.offset,Jz(je.rgb_color,je.opacity*w,A));return we}function Bdt(k,x,w,A,L=!1){if(x.stops.length===1){const it=x.stops[0];return Jz(it.rgb_color,it.opacity*w,A)}const F=eB(x.transform),{fx:U,fy:K,fr:X,cx:oe,cy:ge,r:we}=x;let je=new DOMPoint(U,K),Le=new DOMPoint(oe,ge),Re=X,We=we;if(L){je=F.transformPoint(je),Le=F.transformPoint(Le);const it=(F.a+F.d)/2;Re=X*it,We=x.r*it}const et=k.createRadialGradient(je.x,je.y,Re,Le.x,Le.y,We);for(const it of x.stops)et.addColorStop(it.offset,Jz(it.rgb_color,it.opacity*w,A));return et}function Udt(k,x,w,A){const L=A.transform?eB(A.transform).preMultiplySelf(x):x,F=mY(k.canvas.width,k.canvas.height),U=F.getContext("2d");for(const X of A.children)if(X.group)Udt(U,L,w,X.group);else if(X.path){const oe=X.path,ge=new Path2D;ge.addPath(Hdt(oe),L),U.fill(ge,Fdt(oe))}const K=A.clip_path_idx!=null?w.clip_paths[A.clip_path_idx]:null;K&&qdt(U,L,w,K),k.globalCompositeOperation="source-over",k.drawImage(F,0,0)}function qdt(k,x,w,A){const L=mY(k.canvas.width,k.canvas.height);Udt(L.getContext("2d"),x,w,A),k.globalCompositeOperation="destination-in",k.drawImage(L,0,0)}function $dt(k,x,w,A,L){if(A.children.length===0)return;const F=A.mask_idx!=null?w.masks[A.mask_idx]:null;F&&$dt(k,x,w,F,L);const U=k.canvas.width,K=k.canvas.height,X=mY(U,K),oe=X.getContext("2d"),ge=A.width,we=A.height,je=A.left,Le=A.top,Re=new Path2D,We=new Path2D;We.rect(je,Le,ge,we),Re.addPath(We,x),oe.clip(Re);for(const yt of A.children)Ddt(oe,x,w,yt,L);const et=oe.getImageData(0,0,U,K),it=et.data;if(A.mask_type===1)for(let yt=0;ytx[U])return null}else{const K=1/A[U];let X=(k[U]-w[U])*K,oe=(x[U]-w[U])*K;if(X>oe){const ge=X;X=oe,oe=ge}if(X>L&&(L=X),oeF)return null}return L}function Kdt(k,x,w,A,L,F,U,K,X,oe,ge){const we=A-k,je=L-x,Le=F-w,Re=U-k,We=K-x,et=X-w,it=ge[1]*et-ge[2]*We,yt=ge[2]*Re-ge[0]*et,ht=ge[0]*We-ge[1]*Re,Et=we*it+je*yt+Le*ht;if(Math.abs(Et)<1e-15)return null;const It=1/Et,Ot=oe[0]-k,ws=oe[1]-x,ds=oe[2]-w,_s=(Ot*it+ws*yt+ds*ht)*It;if(_s<0||_s>1)return null;const gs=ws*Le-ds*je,ys=ds*we-Ot*Le,vn=Ot*je-ws*we,wn=(ge[0]*gs+ge[1]*ys+ge[2]*vn)*It;return wn<0||_s+wn>1?null:(Re*gs+We*ys+et*vn)*It}function Ydt(k,x,w){return(k-x)/(w-x)}function Zdt(k,x,w,A,L,F,U,K,X){const oe=1<{const yt=et?1:0,ht=(Le+1)*We-yt,Et=Re*We,It=(Re+1)*We-yt;it[0]=Le*We,it[1]=Et,it[2]=ht,it[3]=It};let we=new Gdt(X);const je=[];for(let Le=0;Le=1;X/=2){const Le=K[K.length-1];we=new Gdt(X);for(let Re=0;Re0;){const{idx:Re,t:We,nodex:et,nodey:it,depth:yt}=Le.pop();if(this.leaves[Re]){Zdt(et,it,yt,x,w,A,L,we,je);const Et=1<=Ln[2])return We}continue}let ht=0;for(let Et=0;Et=oe[ge[ds]]&&(ge.splice(ds,0,Et),ws=!0);ws||(ge[ht]=Et),ht++}}for(let Et=0;Et=this.dim+1||w<-1||w>=this.dim+1)throw new RangeError("out of range source coordinates for DEM data");return(w+1)*this.stride+(x+1)}static pack(x,w){const A=[0,0,0,0],L=Noe.getUnpackVector(w);let F=Math.floor((x+L[3])/L[2]);return A[2]=F%256,F=Math.floor(F/256),A[1]=F%256,F=Math.floor(F/256),A[0]=F,A}getPixels(){return new Lot({width:this.stride,height:this.stride},this.pixels)}backfillBorder(x,w,A){if(this.dim!==x.dim)throw new Error("dem dimension mismatch");let L=w*this.dim,F=w*this.dim+this.dim,U=A*this.dim,K=A*this.dim+this.dim;switch(w){case-1:L=F-1;break;case 1:F=L+1}switch(A){case-1:U=K-1;break;case 1:K=U+1}const X=-w*this.dim,oe=-A*this.dim;for(let ge=U;ge=1;A--){const L=A===1?1:0,F=A===2?1:0;for(let U=0;U>>1^-(1&k[x]);return k}function nhs(k,x){switch(x){case"uint32":return k;case"uint16":for(let w=0;w>4|(61440&A)>>8|(240&L)<<4|61440&L,k[w+1]=15&A|(3840&A)>>4|(15&L)<<8|(3840&L)<<4}return k;case"uint8":for(let w=0;w>6|(192&L)>>4|(192&F)>>2|192&U,k[w+1]=(48&A)>>4|(48&L)>>2|48&F|(48&U)<<2,k[w+2]=(12&A)>>2|12&L|(12&F)<<2|(12&U)<<4,k[w+3]=3&A|(3&L)<<2|(3&F)<<4|(3&U)<<6}return k;default:throw new Error(`Invalid pixel format, "${x}"`)}}jr(Noe,"DEMData"),jr(Xdt,"DemMinMaxQuadTree",{omit:["dem"]});var hw=Uint8Array,fY=Uint16Array,rhs=Int32Array,Jdt=new hw([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]),eut=new hw([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]),ahs=new hw([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),tut=function(k,x){for(var w=new fY(31),A=0;A<31;++A)w[A]=x+=1<>1|(21845&mp)<<1;rut[mp]=((65280&(tB=(61680&(tB=(52428&tB)>>2|(13107&tB)<<2))>>4|(3855&tB)<<4))>>8|(255&tB)<<8)>>1}var xY=function(k,x,w){for(var A=k.length,L=0,F=new fY(x);L>X]=oe;return U},gY=new hw(288);for(mp=0;mp<144;++mp)gY[mp]=8;for(mp=144;mp<256;++mp)gY[mp]=9;for(mp=256;mp<280;++mp)gY[mp]=7;for(mp=280;mp<288;++mp)gY[mp]=8;var aut=new hw(32);for(mp=0;mp<32;++mp)aut[mp]=5;var lhs=xY(gY,9),chs=xY(aut,5),JRe=function(k){for(var x=k[0],w=1;wx&&(x=k[w]);return x},ck=function(k,x,w){var A=x/8|0;return(k[A]|k[A+1]<<8)>>(7&x)&w},eFe=function(k,x){var w=x/8|0;return(k[w]|k[w+1]<<8|k[w+2]<<16)>>(7&x)},dhs=function(k){return(k+7)/8|0},uhs=["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"],dk=function(k,x,w){var A=new Error(x||uhs[k]);if(A.code=k,Error.captureStackTrace&&Error.captureStackTrace(A,dk),!w)throw A;return A},hhs=new hw(0),mhs=typeof TextDecoder<"u"&&new TextDecoder;try{mhs.decode(hhs,{stream:!0})}catch{}const phs={gzip_data:"gzip"};class c2 extends Error{constructor(x){super(x),this.name="MRTError"}}const fhs={0:"uint32",1:"uint32",2:"uint16",3:"uint8"},iut={uint32:1,uint16:2,uint8:4},xhs={uint32:Uint32Array,uint16:Uint16Array,uint8:Uint8Array};let tFe;class koe{constructor(x=5){this.x=NaN,this.y=NaN,this.z=NaN,this.layers={},this._cacheSize=x}getLayer(x){const w=this.layers[x];if(!w)throw new c2(`Layer '${x}' not found`);return w}getHeaderLength(x){const w=new Uint8Array(x),A=new DataView(x);if(w[0]!==13)throw new c2("File is not a valid MRT.");return A.getUint32(1,!0)}parseHeader(x){const w=new Uint8Array(x),A=this.getHeaderLength(x);if(w.length= ${A} but got buffer of length ${w.length}`);const L=new tFe(w.subarray(0,A)).readFields(Wus,{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 c2(`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 F of L.layers)this.layers[F.name]=new out(F,{cacheSize:this._cacheSize});return this}createDecodingTask(x){const w=[],A=this.getLayer(x.layerName);for(let L of x.blockIndices){const F=A.dataIndex[L],U=F.firstByte-x.firstByte,K=F.lastByte-x.firstByte;if(A._blocksInProgress.has(L))continue;const X={layerName:A.name,firstByte:U,lastByte:K,pixelFormat:A.pixelFormat,blockIndex:L,blockShape:[F.bands.length].concat(A.bandShape),buffer:A.buffer,codec:F.codec.codec,filters:F.filters.map(oe=>oe.filter)};A._blocksInProgress.add(L),w.push(X)}return new lut(w,()=>{w.forEach(L=>A._blocksInProgress.delete(L.blockIndex))},(L,F)=>{if(w.forEach(U=>A._blocksInProgress.delete(U.blockIndex)),L)throw L;F.forEach(U=>{this.getLayer(U.layerName).processDecodedData(U)})})}}class out{constructor({version:x,name:w,units:A,tileSize:L,pixelFormat:F,buffer:U,dataIndex:K},X){if(this.version=x,this.version!==1)throw new c2(`Cannot parse raster layer encoded with MRT version ${x}`);this.name=w,this.units=A,this.tileSize=L,this.buffer=U,this.pixelFormat=fhs[F],this.dataIndex=K,this.bandShape=[L+2*U,L+2*U,iut[this.pixelFormat]],this._decodedBlocks=new joe(X?X.cacheSize:5),this._blocksInProgress=new Set}get dimension(){return iut[this.pixelFormat]}get cacheSize(){return this._decodedBlocks.capacity}getBandList(){return this.dataIndex.map(({bands:x})=>x).flat()}processDecodedData(x){const w=x.blockIndex.toString();this._decodedBlocks.get(w)||this._decodedBlocks.put(w,x.data)}getBlockForBand(x){let w=0;switch(typeof x){case"string":for(const[A,L]of this.dataIndex.entries()){for(const[F,U]of L.bands.entries())if(U===x)return{bandIndex:w+F,blockIndex:A,blockBandIndex:F};w+=L.bands.length}break;case"number":for(const[A,L]of this.dataIndex.entries()){if(x>=w&&xthis.cacheSize)throw new c2(`Number of blocks to decode (${F.size}) exceeds cache size (${this.cacheSize}).`);return{layerName:this.name,firstByte:w,lastByte:A,blockIndices:L}}hasBand(x){const{blockIndex:w}=this.getBlockForBand(x);return w>=0}hasDataForBand(x){const{blockIndex:w}=this.getBlockForBand(x);return w>=0&&!!this._decodedBlocks.get(w.toString())}getBandView(x){const{blockIndex:w,blockBandIndex:A}=this.getBlockForBand(x);if(w<0)throw new c2(`Band not found: ${JSON.stringify(x)}`);const L=this._decodedBlocks.get(w.toString());if(!L)throw new c2(`Data for band ${JSON.stringify(x)} of layer "${this.name}" not decoded.`);const F=this.dataIndex[w],U=this.bandShape.reduce((oe,ge)=>oe*ge,1),K=A*U,X=L.subarray(K,K+U);return{data:X,bytes:new Uint8Array(X.buffer).subarray(X.byteOffset,X.byteOffset+X.byteLength),tileSize:this.tileSize,buffer:this.buffer,pixelFormat:this.pixelFormat,dimension:this.dimension,offset:F.offset,scale:F.scale}}}koe.setPbf=function(k){tFe=k};class lut{constructor(x,w,A){this.tasks=x,this._onCancel=w,this._onComplete=A,this._finalized=!1}cancel(){this._finalized||(this._onCancel(),this._finalized=!0)}complete(x,w){this._finalized||(this._onComplete(x,w),this._finalized=!0)}}koe.performDecoding=function(k,x){const w=new Uint8Array(k);return Promise.all(x.tasks.map(A=>{const{layerName:L,firstByte:F,lastByte:U,pixelFormat:K,blockShape:X,blockIndex:oe,filters:ge,codec:we}=A,je=w.subarray(F,U+1),Le=new Uint32Array(X[0]*X[1]*X[2]);let Re;if(we!=="gzip_data")throw new c2(`Unhandled codec: ${we}`);return Re=function(We,et){if(!globalThis.DecompressionStream&&et==="gzip_data")return Promise.resolve((It=function(ds){ds[0]==31&&ds[1]==139&&ds[2]==8||dk(6,"invalid gzip data");var _s=ds[3],gs=10;4&_s&&(gs+=2+(ds[10]|ds[11]<<8));for(var ys=(_s>>3&1)+(_s>>4&1);ys>0;ys-=!ds[gs++]);return gs+(2&_s)}(it=We),It+8>it.length&&dk(6,"invalid gzip data"),function(ds,_s,gs,ys){var vn=ds.length;if(!vn||_s.f&&!_s.l)return gs||new hw(0);var wn=!gs,Pn=wn||_s.i!=2,On=_s.i;wn&&(gs=new hw(3*vn));var Ln=function(Pu){var Qg=gs.length;if(Pu>Qg){var yf=new hw(Math.max(2*Qg,Pu));yf.set(gs),gs=yf}},Jn=_s.f||0,gn=_s.p||0,Rn=_s.b||0,qn=_s.l,tr=_s.d,pr=_s.m,na=_s.n,Cr=8*vn;do{if(!qn){Jn=ck(ds,gn,1);var kr=ck(ds,gn+1,3);if(gn+=3,!kr){var fr=ds[(Il=dhs(gn)+4)-4]|ds[Il-3]<<8,Qr=Il+fr;if(Qr>vn){On&&dk(0);break}Pn&&Ln(Rn+fr),gs.set(ds.subarray(Il,Qr),Rn),_s.b=Rn+=fr,_s.p=gn=8*Qr,_s.f=Jn;continue}if(kr==1)qn=lhs,tr=chs,pr=9,na=5;else if(kr==2){var fa=ck(ds,gn,31)+257,Za=ck(ds,gn+10,15)+4,Ca=fa+ck(ds,gn+5,31)+1;gn+=14;for(var zi=new hw(Ca),Ko=new hw(19),Bi=0;Bi>4)<16)zi[Bi++]=Il;else{var zc=0,wu=0;for(Il==16?(wu=3+ck(ds,gn,3),gn+=2,zc=zi[Bi-1]):Il==17?(wu=3+ck(ds,gn,7),gn+=3):Il==18&&(wu=11+ck(ds,gn,127),gn+=7);wu--;)zi[Bi++]=zc}}var Up=zi.subarray(0,fa),ju=zi.subarray(fa);pr=JRe(Up),na=JRe(ju),qn=xY(Up,pr),tr=xY(ju,na)}else dk(1);if(gn>Cr){On&&dk(0);break}}Pn&&Ln(Rn+131072);for(var eh=(1<>4;if((gn+=15&zc)>Cr){On&&dk(0);break}if(zc||dk(2),Vx<256)gs[Rn++]=Vx;else{if(Vx==256){th=gn,qn=null;break}var qp=Vx-254;Vx>264&&(qp=ck(ds,gn,(1<<(yh=Jdt[Bi=Vx-257]))-1)+nut[Bi],gn+=yh);var fo=tr[eFe(ds,gn)&Jh],K0=fo>>4;if(fo||dk(3),gn+=15&fo,ju=ohs[K0],K0>3){var yh=eut[K0];ju+=eFe(ds,gn)&(1<Cr){On&&dk(0);break}Pn&&Ln(Rn+131072);var gf=Rn+qp;if(RnPu.length)&&(yf=Pu.length),new hw(Pu.subarray(0,yf))}(gs,0,Rn):gs.subarray(0,Rn)}(it.subarray(It,-8),{i:2},new hw(((ht=it)[(Et=ht.length)-4]|ht[Et-3]<<8|ht[Et-2]<<16|ht[Et-1]<<24)>>>0),yt)));var it,yt,ht,Et,It;const Ot=phs[et];if(!Ot)throw new Error(`Unhandled codec: ${et}`);const ws=new globalThis.DecompressionStream(Ot);return new Response(new Blob([We]).stream().pipeThrough(ws)).arrayBuffer().then(ds=>new Uint8Array(ds))}(je,we).then(We=>(function(et,it){et.readFields(Jus,it)}(new tFe(We),Le),new xhs[K](Le.buffer))),Re.then(We=>{for(let et=ge.length-1;et>=0;et--)switch(ge[et]){case"delta_filter":ths(We,X);break;case"zigzag_filter":shs(We);break;case"bitshuffle_filter":nhs(We,K);break;default:throw new c2(`Unhandled filter "${ge[et]}"`)}return{layerName:L,blockIndex:oe,data:We}}).catch(We=>{throw We})}))},jr(lut,"MRTDecodingBatch",{omit:["_onCancel","_onComplete"]}),jr(koe,"MapboxRasterTile"),jr(out,"MapboxRasterLayer",{omit:["_blocksInProgress"]});const cut=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array];class sFe{static from(x){if(!(x instanceof ArrayBuffer))throw new Error("Data must be an instance of ArrayBuffer.");const[w,A]=new Uint8Array(x,0,2);if(w!==219)throw new Error("Data does not appear to be in a KDBush format.");const L=A>>4;if(L!==1)throw new Error(`Got v${L} data when expected v1.`);const F=cut[15&A];if(!F)throw new Error("Unrecognized array type.");const[U]=new Uint16Array(x,2,1),[K]=new Uint32Array(x,4,1);return new sFe(K,U,F,x)}constructor(x,w=64,A=Float64Array,L){if(isNaN(x)||x<0)throw new Error(`Unpexpected numItems value: ${x}.`);this.numItems=+x,this.nodeSize=Math.min(Math.max(+w,2),65535),this.ArrayType=A,this.IndexArrayType=x<65536?Uint16Array:Uint32Array;const F=cut.indexOf(this.ArrayType),U=2*x*this.ArrayType.BYTES_PER_ELEMENT,K=x*this.IndexArrayType.BYTES_PER_ELEMENT,X=(8-K%8)%8;if(F<0)throw new Error(`Unexpected typed array class: ${A}.`);L&&L instanceof ArrayBuffer?(this.data=L,this.ids=new this.IndexArrayType(this.data,8,x),this.coords=new this.ArrayType(this.data,8+K+X,2*x),this._pos=2*x,this._finished=!0):(this.data=new ArrayBuffer(8+U+K+X),this.ids=new this.IndexArrayType(this.data,8,x),this.coords=new this.ArrayType(this.data,8+K+X,2*x),this._pos=0,this._finished=!1,new Uint8Array(this.data,0,2).set([219,16+F]),new Uint16Array(this.data,2,1)[0]=w,new Uint32Array(this.data,4,1)[0]=x)}add(x,w){const A=this._pos>>1;return this.ids[A]=A,this.coords[this._pos++]=x,this.coords[this._pos++]=w,A}finish(){const x=this._pos>>1;if(x!==this.numItems)throw new Error(`Added ${x} items when expected ${this.numItems}.`);return nFe(this.ids,this.coords,this.nodeSize,0,this.numItems-1,0),this._finished=!0,this}range(x,w,A,L){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:F,coords:U,nodeSize:K}=this,X=[0,F.length-1,0],oe=[];for(;X.length;){const ge=X.pop()||0,we=X.pop()||0,je=X.pop()||0;if(we-je<=K){for(let et=je;et<=we;et++){const it=U[2*et],yt=U[2*et+1];it>=x&&it<=A&&yt>=w&&yt<=L&&oe.push(F[et])}continue}const Le=je+we>>1,Re=U[2*Le],We=U[2*Le+1];Re>=x&&Re<=A&&We>=w&&We<=L&&oe.push(F[Le]),(ge===0?x<=Re:w<=We)&&(X.push(je),X.push(Le-1),X.push(1-ge)),(ge===0?A>=Re:L>=We)&&(X.push(Le+1),X.push(we),X.push(1-ge))}return oe}within(x,w,A){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:L,coords:F,nodeSize:U}=this,K=[0,L.length-1,0],X=[],oe=A*A;for(;K.length;){const ge=K.pop()||0,we=K.pop()||0,je=K.pop()||0;if(we-je<=U){for(let et=je;et<=we;et++)uut(F[2*et],F[2*et+1],x,w)<=oe&&X.push(L[et]);continue}const Le=je+we>>1,Re=F[2*Le],We=F[2*Le+1];uut(Re,We,x,w)<=oe&&X.push(L[Le]),(ge===0?x-A<=Re:w-A<=We)&&(K.push(je),K.push(Le-1),K.push(1-ge)),(ge===0?x+A>=Re:w+A>=We)&&(K.push(Le+1),K.push(we),K.push(1-ge))}return X}}function nFe(k,x,w,A,L,F){if(L-A<=w)return;const U=A+L>>1;dut(k,x,U,A,L,F),nFe(k,x,w,A,U-1,1-F),nFe(k,x,w,U+1,L,1-F)}function dut(k,x,w,A,L,F){for(;L>A;){if(L-A>600){const oe=L-A+1,ge=w-A+1,we=Math.log(oe),je=.5*Math.exp(2*we/3),Le=.5*Math.sqrt(we*je*(oe-je)/oe)*(ge-oe/2<0?-1:1);dut(k,x,w,Math.max(A,Math.floor(w-ge*je/oe+Le)),Math.min(L,Math.floor(w+(oe-ge)*je/oe+Le)),F)}const U=x[2*w+F];let K=A,X=L;for(yY(k,x,A,w),x[2*L+F]>U&&yY(k,x,A,L);KU;)X--}x[2*A+F]===U?yY(k,x,A,X):(X++,yY(k,x,X,L)),X<=w&&(A=X+1),w<=X&&(L=X-1)}}function yY(k,x,w,A){rFe(k,w,A),rFe(x,2*w,2*A),rFe(x,2*w+1,2*A+1)}function rFe(k,x,w){const A=k[x];k[x]=k[w],k[w]=A}function uut(k,x,w,A){const L=k-w,F=x-A;return L*L+F*F}o.$=Bx,o.A=class{constructor(k,x,w){this.target=k,this.parent=x,this.mapId=w,this.callbacks={},this.cancelCallbacks={},Kt(["receive"],this),this.target.addEventListener("message",this.receive,!1),this.scheduler=new kus}send(k,x,w,A,L=!1,F){const U=Math.round(1e18*Math.random()).toString(36).substring(0,10);w&&(w.metadata=F,this.callbacks[U]=w);const K=new Set;return this.target.postMessage({id:U,type:k,hasCallback:!!w,targetMapId:A,mustQueue:L,sourceMapId:this.mapId,data:kd(x,K)},K),{cancel:()=>{w&&delete this.callbacks[U],this.target.postMessage({id:U,type:"",targetMapId:A,sourceMapId:this.mapId})}}}receive(k){const x=k.data;if(!x)return;const w=x.id;if(w&&(!x.targetMapId||this.mapId===x.targetMapId))if(x.type===""){const A=this.cancelCallbacks[w];delete this.cancelCallbacks[w],A&&A.cancel()}else if(x.mustQueue||Si(self)){const A=this.callbacks[w],L=this.scheduler.add(()=>this.processTask(w,x),A&&A.metadata||{type:"message"});L&&(this.cancelCallbacks[w]=L)}else this.processTask(w,x)}processTask(k,x){if(delete this.cancelCallbacks[k],x.type===""){const w=this.callbacks[k];delete this.callbacks[k],w&&(x.error?w(Gc(x.error)):w(null,Gc(x.data)))}else{const w=new Set,A=x.hasCallback?(F,U)=>{this.target.postMessage({id:k,type:"",sourceMapId:this.mapId,error:F?kd(F):null,data:kd(U,w)},w)}:()=>{},L=Gc(x.data);if(this.parent[x.type])this.parent[x.type](x.sourceMapId,L,A);else if(this.parent.getWorkerSource){const F=x.type.split("."),{source:U,scope:K}=L;this.parent.getWorkerSource(x.sourceMapId,{type:F[0],source:U,scope:K,uid:0})[F[1]](L,A)}else A(new Error(`Could not find function ${x.type}`))}}remove(){this.scheduler.remove(),this.target.removeEventListener("message",this.receive,!1)}},o.B=cf,o.C=Nd,o.D=Ud,o.E=Om,o.F=Lt,o.G=2,o.H=tY,o.I=zm,o.J=Ect,o.K=U0,o.L=ZC,o.M=Wg,o.N=Ry,o.O=_u,o.P=Js,o.Q=gl,o.R=xg,o.S=Bm,o.T=f5,o.U=Ip,o.V=goe,o.W=o5,o.X=Md,o.Y=Eh,o.Z=Zu,o._=$b,o.a=function(k){return di.API_CDN_URL_REGEX.test(k)},o.a$=Jie,o.a0=qd,o.a1=Ox,o.a2=gg,o.a3=qs,o.a4=XC,o.a5=class extends goe{},o.a6=Xu,o.a7=bu,o.a8=Us,o.a9=function(k){const x=k.value;return x?gg(x)?HRe(x,!0)?[]:[new goe(k.key,x,`invalid url "${x}"`)]:[new goe(k.key,x,`string expected, "${Wg(x)}" found`)]:[]},o.aA=nct,o.aB=function(k){let x=1/0,w=1/0,A=-1/0,L=-1/0;for(const F of k)x=Math.min(x,F.x),w=Math.min(w,F.y),A=Math.max(A,F.x),L=Math.max(L,F.y);return{min:new Js(x,w),max:new Js(A,L)}},o.aC=pt,o.aD=b,o.aE=Ge,o.aF=Yt,o.aG=Ky,o.aH=zn,o.aI=ta,o.aJ=function(k,x){const w={};for(let A=0;A=0?x.slice(w+1):""}catch{return""}},o.aN=class{constructor(k){this.entries={},this.scheduler=k}request(k,x,w,A){const L=this.entries[k]=this.entries[k]||{callbacks:[]};if(L.result){const[F,U]=L.result;return this.scheduler?this.scheduler.add(()=>{A(F,U)},x):A(F,U),()=>{}}return L.callbacks.push(A),L.cancel||(L.cancel=w((F,U)=>{L.result=[F,U];for(const K of L.callbacks)this.scheduler?this.scheduler.add(()=>{K(F,U)},x):K(F,U);setTimeout(()=>delete this.entries[k],3e3)})),()=>{L.result||(L.callbacks=L.callbacks.filter(F=>F!==A),L.callbacks.length||(L.cancel(),delete this.entries[k]))}}},o.aO=function(k,x,w){const A=JSON.stringify(k.request);return k.data&&(this.deduped.entries[A]={result:[null,k.data]}),this.deduped.request(A,{type:"parseTile",renderSourceType:k.renderSourceType,zoom:k.tileZoom},L=>{const F=Gg(k.request,(U,K,X)=>{U?Xf(U)?L(null,null):L(U):K&&L(null,{rawData:K,vectorTile:w?void 0:new yl(new Jie(K)),responseHeaders:new Map(X.entries())})});return()=>{F.cancel(),L(null,null)}},x)},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){Ua++,Ua>bi&&(k.getActor().send("enforceCacheSizeLimit",Co),Ua=0)},o.aR=W0,o.aS=ddt,o.aT=ydt,o.aU=Es,o.aV=cdt,o.aW=function(k,x){const w=document.createElement("video");w.muted=!0,w.onloadstart=function(){x(null,w)};for(let A=0;A{}}},o.aX=ZK,o.aY=pI,o.aZ=Kt,o.a_=koe,o.aa=XE,o.ab=nd,o.ac=cr,o.ad=class{constructor(k){this.specification=k}possiblyEvaluate(k,x){return ra(k.expression.evaluate(x))}interpolate(k,x,w){return{x:Ar(k.x,x.x,w),y:Ar(k.y,x.y,w),z:Ar(k.z,x.z,w),azimuthal:Ar(k.azimuthal,x.azimuthal,w),polar:Ar(k.polar,x.polar,w)}}},o.ae=$i,o.af=Ec,o.ag=pa,o.ah=Ze,o.ai=H,o.aj=jt,o.ak=Op,o.al=r3,o.am=Ar,o.an=ur,o.ao=wi,o.ap=Ws,o.aq=Xs,o.ar=class{constructor(k){this.specification=k}possiblyEvaluate(k,x){return function([w,A]){const L=ra([1,w,A]);return{x:L.x,y:L.y,z:L.z}}(k.expression.evaluate(x))}interpolate(k,x,w){return{x:Ar(k.x,x.x,w),y:Ar(k.y,x.y,w),z:Ar(k.z,x.z,w)}}},o.as=function(k,x,w=0,A=!0){const L=new Js(w,w),F=k.sub(L),U=x.add(L),K=[F,new Js(U.x,F.y),U,new Js(F.x,U.y)];return A&&K.push(F.clone()),K},o.at=function(k,x){const w=[];for(let A=0;Athis.buckets[we].layers.some(je=>U.has(je.fqid))),X=Object.keys(this.buckets).some(we=>this.buckets[we].layers.some(je=>je.hasTransition&&je.hasTransition())),oe=this._firstPrepareComplete&&F!==this._lastAvailableImagesCount;this._hasAppearances===null&&(this._hasAppearances=this.hasAppearances(x));const ge=this._lastUpdatedBrightness!==A;this._lastAvailableImagesCount=F,this._firstPrepareComplete=!0,(this._lastUpdatedBrightness||A||this._hasAppearances||K||X||oe)&&(!(this._hasAppearances||K||X||oe)&&this._lastUpdatedBrightness&&A&&Math.abs(this._lastUpdatedBrightness-A)<.001||(this.updateBuckets(x,ge,void 0,oe||K||X,U,L),this._lastUpdatedBrightness=A))}evaluateQueryRenderedFeaturePadding(){let k=0;for(const x in this.buckets){const w=this.buckets[x];w.evaluateQueryRenderedFeaturePadding&&(k=Math.max(k,w.evaluateQueryRenderedFeaturePadding()))}return k}queryRenderedFeatures(k,x,w,A,L,F,U){if(!this.latestFeatureIndex||!this.latestFeatureIndex.rawTileData&&!this.latestFeatureIndex.is3DTile)return{};const K=this.evaluateQueryRenderedFeaturePadding(),X=function(oe,ge){const we=M([],[.5*oe.width,.5*-oe.height,1]);return j(we,we,[1,-1,0]),b(we,we,oe.calculateProjMatrix(ge.toUnwrapped())),Float32Array.from(we)}(L,this.tileID);return this.latestFeatureIndex.query(k,{tilespaceGeometry:x,pixelPosMatrix:X,transform:A,availableImages:w,tileTransform:this.tileTransform,worldview:this.worldview,queryRadius:K,scope:U})}querySourceFeatures(k,x){const w=this.latestFeatureIndex;if(!w||!w.rawTileData)return;const A=w.loadVTLayers(),L=x?x.sourceLayer:"",F=A._geojsonTileLayer||A[L];if(!F)return;const U=eT(x&&x.filter),{z:K,x:X,y:oe}=this.tileID.canonical,ge={z:K,x:X,y:oe};for(let we=0;wew)A=!1;else if(x)if(this.expirationTimew.appearances&&w.appearances.length>0))return!0;return!1}updateBuckets(k,x,w,A,L,F){if(!this.latestFeatureIndex||!k.style)return;const U=F||k.style.listImages(),K=k.style.getBrightness(),X=L||new Set;for(const oe in this.buckets){if(!k.style.hasLayer(oe))continue;const ge=this.buckets[oe],we=ge.layers[0],je=we.sourceLayer||"_geojsonTileLayer",Le=k.style.getLayerSourceCache(we),Re=ge.layers.some(It=>X.has(It.fqid)),We=(A||Re)&&ge instanceof lk?k.style.getOwnLayer(oe):void 0;let et=w&&w[je]||{};Le&&!w&&(et=Le._state.getState(je,void 0));const it=this.imageAtlas?Object.fromEntries(this.imageAtlas.patternPositions):{},yt=Object.keys(et).length>0&&!x;ge.hasAppearances=ge.layers.some(It=>It.appearances&&It.appearances.length>0);const ht=yt?ge.stateDependentLayers:ge.layers;if(yt&&ge.stateDependentLayers.length!==0||x||Re||A){const It=this.latestFeatureIndex.loadVTLayers()[je];if(ge.update(et,It,U,it,ht,x,K,this.tileID.canonical),(A||Re)&&!x&&ge instanceof lk&&We&&We.type==="symbol"){const Ot=ge;Ot.text&&Ot.text.uboBinder&&Ot.text.uboBinder.updateDynamicExpressions(We,It,this.tileID.canonical,U,et,K),Ot.icon&&Ot.icon.uboBinder&&Ot.icon.uboBinder.updateDynamicExpressions(We,It,this.tileID.canonical,U,et,K)}if(ge instanceof lk){const Ot=ge,ws=k.context;Ot.text&&Ot.text.uboBinder&&Ot.text.uboBinder.upload(ws),Ot.icon&&Ot.icon.uboBinder&&Ot.icon.uboBinder.upload(ws)}}if(yt&&ge.stateDependentLayers.length!==0||x||ge.hasAppearances){const It={zoom:k.transform.zoom,pitch:k.transform.pitch,brightness:k.style.getBrightness()||0,worldview:k.worldview},Ot=ge.updateAppearances(this.tileID.canonical,et,U,It,k.imageManager,yt&&ge.stateDependentLayers.length!==0);if(Ot&&Ot.hasUboChanges){const ws=k.context;ge instanceof lk&&ge.text&&ge.text.uboBinder&&ge.text.uboBinder.upload(ws),ge instanceof lk&&ge.icon&&ge.icon.uboBinder&&ge.icon.uboBinder.upload(ws)}}(ge instanceof Qie||ge instanceof Lie)&&k._terrain&&k._terrain.enabled&&Le&&ge.uploadPending()&&k._terrain._clearRenderCacheForTile(Le.id,this.tileID);const Et=k&&k.style&&k.style.getOwnLayer(oe);Et&&(this.queryPadding=Math.max(this.queryPadding,Et.queryRadius(ge)||0))}}holdingForFade(){return this.symbolFadeHoldUntil!==void 0}symbolFadeFinished(){return!this.symbolFadeHoldUntil||this.symbolFadeHoldUntil=0;We--){const et=4*We,it=mT[et+0],yt=mT[et+1],ht=mT[et+2],Et=mT[et+3],It=it+ht>>1,Ot=yt+Et>>1,ws=It+Ot-yt,ds=Ot+it-It,_s=yt*x5+it,gs=Et*x5+ht,ys=Ot*x5+It,vn=Math.hypot((g5[2*_s+0]+g5[2*gs+0])/2-g5[2*ys+0],(g5[2*_s+1]+g5[2*gs+1])/2-g5[2*ys+1])>=16;pT[ys]=pT[ys]||(vn?1:0),We<1022&&(pT[ys]=pT[ys]||pT[(yt+ds>>1)*x5+(it+ws>>1)]||pT[(Et+ds>>1)*x5+(ht+ws>>1)])}const ge=new yo,we=new Ju;let je=0;function Le(We,et){const it=et*x5+We;return voe[it]===0&&(ge.emplaceBack(g5[2*it+0],g5[2*it+1],We*ur/l2,et*ur/l2),voe[it]=++je),voe[it]-1}function Re(We,et,it,yt,ht,Et){const It=We+it>>1,Ot=et+yt>>1;if(Math.abs(We-ht)+Math.abs(et-Et)>1&&pT[Ot*x5+It])Re(ht,Et,We,et,It,Ot),Re(it,yt,ht,Et,It,Ot);else{const ws=Le(We,et),ds=Le(it,yt),_s=Le(ht,Et);we.emplaceBack(ws,ds,_s)}}return Re(0,0,l2,l2,l2,0),Re(l2,l2,0,0,0,l2),{vertices:ge,indices:we}}(this.tileID.canonical,x);A=F.vertices,L=F.indices}else{A=new yo,L=new Ju;for(const{x:U,y:K}of w)A.emplaceBack(U,K,0,0);const F=zz(A.int16.subarray(0,4*A.length),void 0,4);for(let U=0;U0&&(U=g(new Float64Array(16),x.globeMatrix)),this._makeGlobeTileDebugBorderBuffer(k,A,x,L,U,F),this._makeGlobeTileDebugTextBuffer(k,A,x,L,U,F)}_globePoint(k,x,w,A,L,F,U){let K=LK(k,x,w);if(F){const X=1<.5?je=-1:we<-.5&&(je=1);let Le=(k/ur+w.x)/X+je,Re=(x/ur+w.y)/X;Le=(Le-oe)*A._pixelsPerMercatorPixel+oe,Re=(Re-ge)*A._pixelsPerMercatorPixel+ge;const We=[Le*A.worldSize,Re*A.worldSize,0];Ze(We,We,F),K=n3(K,We,U)}return Ze(K,K,L)}_makeGlobeTileDebugBorderBuffer(k,x,w,A,L,F){const U=new ao,K=new e3,X=new fl,oe=(we,je,Le,Re,We)=>{const et=(Le-we)/(We-1),it=(Re-je)/(We-1),yt=U.length;for(let ht=0;htoe*we+je;for(let we=0;we1)return!1;const w=x.getSource().maxzoom,A=1<1)return x;const L=A.getSource().maxzoom,F=1<{const K=this.getAtTileOffset(k,L,F,U),X=A.upVector(k.canonical,L.x,L.y);return le(X,X,K*A.upVectorScale(k.canonical,x,w).metersToTile),X}}getForTilePoints(k,x,w,A){if(this.isUsingMockSource())return!1;const L=Qz.create(this,k,A);return!!L&&(x.forEach(F=>{F[2]=this.exaggeration()*L.getElevationAt(F[0],F[1],w)}),!0)}getMinMaxForTile(k){if(this.isUsingMockSource())return null;const x=this.findDEMTileFor(k);if(!x||!x.dem)return null;const w=x.dem.tree,A=x.tileID,L=1<0&&(A+=(k[L]-0)*(k[L]-0)),x[L]<0&&(A+=(0-x[L])*(0-x[L]));return A},o.cL=function(k){return k*k*k*k*k},o.cM=mn,o.cN=45,o.cO=Rz,o.cP=function(k,x,w){const A=Math.sqrt(k*k+x*x+w*w),L=A>0?Math.acos(w/A)*Gs:0;let F=k!==0||x!==0?Math.atan2(-x,-k)*Gs+90:0;return F<0&&(F+=360),[A,F,L]},o.cQ=Y,o.cR=ra,o.cS=Gn,o.cT=ne,o.cU=Hl,o.cV=ce,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=Blt,o.cY=mRe,o.cZ=Hlt,o.c_=HRe,o.ca=2,o.cb=7,o.cc=6,o.cd=ke,o.ce=G,o.cf=$,o.cg=0,o.ch=1,o.ci=4,o.cj=5,o.ck=Oz,o.cl=qv,o.cm=qlt,o.cn=rI,o.co=got,o.cp=function(k,x,w,A,L,F,U,K,X){if(X.name==="globe")return got(k,x,new rI(w,A,L),!1);const oe=uI({z:w,x:A,y:L},X);return new Hl([(F+oe.x/oe.scale)*x,x*(oe.y/oe.scale),U],[(F+oe.x2/oe.scale)*x,x*(oe.y2/oe.scale),K])},o.cq=function(k,x,w){return k[0]=Math.min(x[0],w[0]),k[1]=Math.min(x[1],w[1]),k[2]=Math.min(x[2],w[2]),k[3]=Math.min(x[3],w[3]),k},o.cr=function(k,x,w){return k[0]=Math.max(x[0],w[0]),k[1]=Math.max(x[1],w[1]),k[2]=Math.max(x[2],w[2]),k[3]=Math.max(x[3],w[3]),k},o.cs=function(k){const x=Math.round((k+45+360)%360/90)%4;return Bn[x]},o.ct=Tn,o.cu=Xe,o.cv=6,o.cw=function(k){const x=v(new Float64Array(16));b(x,k.pixelMatrix,k.globeMatrix);const w=[0,cs,0],A=[0,Ns,0];return Ze(w,w,x),Ze(A,A,x),[w[0]>0&&w[0]<=k.width&&w[1]>0&&w[1]<=k.height&&!IDe(k,new Es(k.center.lat,90)),A[0]>0&&A[0]<=k.width&&A[1]>0&&A[1]<=k.height&&!IDe(k,new Es(k.center.lat,-90))]},o.cx=function(k,x){const{scale:w}=k.tileTransform,A=w*ur/(k.tileSize*Math.pow(2,x.zoom-k.tileID.overscaledZ+k.tileID.canonical.z));return function(L,F,U){var K=F[1],X=F[2],oe=F[3],ge=U[0],we=U[1];return L[0]=F[0]*ge,L[1]=K*ge,L[2]=X*we,L[3]=oe*we,L}(new Float32Array(4),x.inverseAdjustmentMatrix,[A,A])},o.cy=Gie,o.cz=V,o.d=function(k){return di.API_TILEJSON_REGEX.test(k)},o.d$=kls,o.d0=Tu,o.d1=class{static calculate(k,x,w){const A=new Set,L=new Map,F=new Set,U=new Set;for(const X of Object.values(k))for(const[oe,ge]of Object.entries(X.floors)){F.add(oe),ge.isDefault&&U.add(oe),ge.conflicts&&L.set(oe,ge.conflicts);const we=oe===x,je=ge.connections&&x&&ge.connections.has(x);(we||je)&&A.add(oe)}const K=X=>{const oe=L.get(X)||new Set;for(const ge of A)if((L.get(ge)||new Set).has(X)||oe.has(ge))return!0;return!1};if(w)for(const X of w)F.has(X)&&(K(X)||A.add(X));for(const X of U)A.has(X)||K(X)||A.add(X);return A}},o.d2=noe,o.d3=PRe,o.d4=Ti,o.d5=function(){return{API_URL:di.API_URL,DRACO_URL:di.DRACO_URL,MESHOPT_URL:di.MESHOPT_URL,MESHOPT_SIMD_URL:di.MESHOPT_SIMD_URL,BUILDING_GEN_URL:di.BUILDING_GEN_URL}},o.d6=s5,o.d7=Ma,o.d8=dc,o.d9=er,o.dA=Nie,o.dB=ao,o.dC=Ju,o.dD=function(k,x){return[Math.pow(k[0],2.2)*x,Math.pow(k[1],2.2)*x,Math.pow(k[2],2.2)*x]},o.dE=h,o.dF=function(k,x){var w=Math.sin(x),A=Math.cos(x);return k[0]=A,k[1]=w,k[2]=0,k[3]=-w,k[4]=A,k[5]=0,k[6]=0,k[7]=0,k[8]=1,k},o.dG=Se,o.dH=vot,o.dI=Ra,o.dJ=Eo,o.dK=$Re,o.dL=function(k,x){const w=[0,0,0];return Ze(w,w,IK(h5(x.canonical))),Ze(w,w,k),w},o.dM=k=>({u_matrix:new N(k),u_texsize:new Jb(k),u_pixels_to_tile_units:new W(k),u_device_pixel_ratio:new Um(k),u_width_scale:new Um(k),u_floor_width_scale:new Um(k),u_image:new sI(k),u_units_to_pixels:new Jb(k),u_tile_units_to_pixels:new Um(k),u_alpha_discard_threshold:new Um(k),u_trim_offset:new Jb(k),u_trim_fade_range:new Jb(k),u_trim_gradient_mix_range:new Jb(k),u_trim_color:new Rz(k),u_zbias_factor:new Um(k),u_tile_to_meter:new Um(k),u_ground_shadow_factor:new nI(k),u_pattern_transition:new Um(k)}),o.dN=k=>({u_matrix:new N(k),u_pixels_to_tile_units:new W(k),u_device_pixel_ratio:new Um(k),u_width_scale:new Um(k),u_floor_width_scale:new Um(k),u_units_to_pixels:new Jb(k),u_dash_image:new sI(k),u_gradient_image:new sI(k),u_image_height:new Um(k),u_texsize:new Jb(k),u_tile_units_to_pixels:new Um(k),u_alpha_discard_threshold:new Um(k),u_trim_offset:new Jb(k),u_trim_fade_range:new Jb(k),u_trim_gradient_mix_range:new Jb(k),u_trim_color:new Rz(k),u_zbias_factor:new Um(k),u_tile_to_meter:new Um(k),u_ground_shadow_factor:new nI(k)}),o.dO=k=>({u_camera_to_center_distance:new Um(k),u_extrude_scale:new W(k),u_device_pixel_ratio:new Um(k),u_matrix:new N(k),u_inv_rot_matrix:new N(k),u_merc_center:new Jb(k),u_tile_id:new nI(k),u_zoom_transition:new Um(k),u_up_dir:new nI(k),u_emissive_strength:new Um(k)}),o.dP=_K,o.dQ=Nds,o.dR=class{constructor(k,x,w,A){this.context=k,this.format=A,this.size=w,this.texture=k.gl.createTexture();const[L,F,U]=this.size,{gl:K}=k;K.bindTexture(K.TEXTURE_3D,this.texture),k.pixelStoreUnpackFlipY.set(!1),k.pixelStoreUnpack.set(1),k.pixelStoreUnpackPremultiplyAlpha.set(!1),"data"in x&&x.data&&K.texImage3D(K.TEXTURE_3D,0,this.format,L,F,U,0,iRe(this.format),oRe(this.format),x.data)}bind(k,x){const{context:w}=this,{gl:A}=w;A.bindTexture(A.TEXTURE_3D,this.texture),k!==this.minFilter&&(A.texParameteri(A.TEXTURE_3D,A.TEXTURE_MAG_FILTER,k),A.texParameteri(A.TEXTURE_3D,A.TEXTURE_MIN_FILTER,k),this.minFilter=k),x!==this.wrapS&&(A.texParameteri(A.TEXTURE_3D,A.TEXTURE_WRAP_S,x),A.texParameteri(A.TEXTURE_3D,A.TEXTURE_WRAP_T,x),this.wrapS=x)}destroy(){const{gl:k}=this.context;k.deleteTexture(this.texture),this.texture=null}},o.dS=jot,o.dT=(k,x,w,A,L,F)=>{const U=k.transform,K=U.projection.name==="globe";let X;if(F.paint.get("circle-pitch-alignment")==="map")if(K){const ge=vot(U.zoom,x.canonical)*U._pixelsPerMercatorPixel;X=Float32Array.from([ge,0,0,ge])}else X=U.calculatePixelsToTileUnitsMatrix(w);else X=new Float32Array([U.pixelsToGLUnits[0],0,0,U.pixelsToGLUnits[1]]);const oe={u_camera_to_center_distance:k.transform.getCameraToCenterDistance(U.projection),u_matrix:k.translatePosMatrix(x.projMatrix,w,F.paint.get("circle-translate"),F.paint.get("circle-translate-anchor")),u_device_pixel_ratio:da.devicePixelRatio,u_extrude_scale:X,u_inv_rot_matrix:Mls,u_merc_center:[0,0],u_tile_id:[0,0,0],u_zoom_transition:0,u_up_dir:[0,0,0],u_emissive_strength:F.paint.get("circle-emissive-strength")};if(K){oe.u_inv_rot_matrix=A,oe.u_merc_center=L,oe.u_tile_id=[x.canonical.x,x.canonical.y,1<{const ge=k.transform,we=ge.pitch<15?rct(.07,.7,pt((14-ge.zoom)/5,0,1)):.07,je=w.paint.get("line-trim-color-use-theme").constantOr("default")==="none";return{u_matrix:ict(k,x,w,A),u_texsize:x.imageAtlasTexture?x.imageAtlasTexture.size:[0,0],u_pixels_to_tile_units:ge.calculatePixelsToTileUnitsMatrix(x),u_device_pixel_ratio:L,u_width_scale:F,u_floor_width_scale:U,u_image:0,u_tile_units_to_pixels:act(x,ge),u_units_to_pixels:[1/ge.pixelsToGLUnits[0],1/ge.pixelsToGLUnits[1]],u_alpha_discard_threshold:0,u_trim_offset:K,u_trim_fade_range:w.paint.get("line-trim-fade-range"),u_trim_gradient_mix_range:[1,1],u_trim_color:w.paint.get("line-trim-color").toPremultipliedRenderColor(je?null:w.lut).toArray01(),u_zbias_factor:we,u_tile_to_meter:Gn(x.tileID.canonical,0),u_ground_shadow_factor:X,u_pattern_transition:oe}},o.dX=(k,x,w,A,L,F,U,K,X,oe)=>{const ge=k.transform,we=ge.calculatePixelsToTileUnitsMatrix(x),je=w.paint.get("line-trim-color-use-theme").constantOr("default")==="none",Le=ge.pitch<15?rct(.07,.7,pt((14-ge.zoom)/5,0,1)):.07;return{u_matrix:ict(k,x,w,A),u_pixels_to_tile_units:we,u_device_pixel_ratio:F,u_width_scale:U,u_floor_width_scale:K,u_units_to_pixels:[1/ge.pixelsToGLUnits[0],1/ge.pixelsToGLUnits[1]],u_dash_image:0,u_gradient_image:1,u_image_height:L,u_texsize:lct(w)&&x.lineAtlasTexture?x.lineAtlasTexture.size:[0,0],u_tile_units_to_pixels:act(x,k.transform),u_alpha_discard_threshold:0,u_trim_offset:X,u_trim_fade_range:w.paint.get("line-trim-fade-range"),u_trim_gradient_mix_range:[1,1],u_trim_color:w.paint.get("line-trim-color").toPremultipliedRenderColor(je?null:w.lut).toArray01(),u_zbias_factor:Le,u_tile_to_meter:Gn(x.tileID.canonical,0),u_ground_shadow_factor:oe}},o.dY=js,o.dZ=DK,o.d_=_n,o.da=function(k){const x=k.indexOf(dt);return x>=0?k.slice(0,x):k},o.db=function(k){return k.indexOf(dt)>=0},o.dc=function(k){const x=k.lastIndexOf(dt);return x>=0?k.slice(x+1):""},o.dd=function(k){const x=[],w=k.id;return w===void 0&&x.push({message:`layers.${w}: missing required property "id"`}),k.render===void 0&&x.push({message:`layers.${w}: missing required method "render"`}),k.renderingMode&&k.renderingMode!=="2d"&&k.renderingMode!=="3d"&&x.push({message:`layers.${w}: property "renderingMode" must be either "2d" or "3d"`}),x},o.de=function(k,x,w,A){return k.type==="custom"?new gus(k,x):new wus[k.type](k,x,w,A)},o.df=an,o.dg=eT,o.dh=Bs,o.di=class extends mI{constructor(k,x){super(k._vectorTileFeature,k._z,k._x,k._y,k.id),k.state&&(this.state=Object.assign({},k.state)),this.target=x.target,this.namespace=x.namespace,x.properties&&(this.properties=x.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=n5,o.dk=function(k){return k({pluginStatus:Eu,pluginURL:ox}),n5.on("pluginStateChange",k),k},o.dl=EDe,o.dm=class extends Qb{constructor(k){super(k),this.current=T}set(k,x,w){if(this.fetchUniformLocation(k,x)){for(let A=0;A<9;A++)if(w[A]!==this.current[A]){this.current=w,this.gl.uniformMatrix3fv(this.location,!1,w);break}}}},o.dn=or,o.dp=function(k,x,w){const A=r3(w.zoom),L=k.style.map._antialias,F=k.terrain&&k.terrain.exaggeration()>0;return A===0&&!L&&!F},o.dq=function(k){const x=k.pixelsPerMeter,w=x/sn(1,k.center.lat),A=v(new Float64Array(16));return j(A,A,[k.point.x,k.point.y,0]),S(A,A,[w,w,x]),Float32Array.from(A)},o.dr=kie,o.ds=function(k){const x=80.051129;k=pt(k,-80.051129,x)/x*90;const w=Math.pow(Math.abs(Math.sin(Ws(k))),3);return Math.round(w*(Ss.length-1))},o.dt=function(k,x,w,A){const L=x.getNorth(),F=x.getSouth(),U=x.getWest(),K=x.getEast(),X=1<0){const Re=180/A;p(Le,Le,[Re/oe+1,0,0,0,Re/ge+1,0,-.5*Re/we,.5*Re/je,1])}return Le[2]=X,Le[5]=k.x,Le[8]=k.y,Le},o.du=IK,o.dv=h5,o.dw=function(k,x,w){const A=v(new Float64Array(16)),L=(x/(1<0&&++this._updateTime,this._activeRegions=[],this._prevRegions=[]}get updateTime(){return this._updateTime}getReplacementRegionsForTile(k,x=!1){const w=nlt(new Js(0,0),new Js(ur,ur),k),A=[];if(x&&!YDe(w,this._globalClipBounds))return A;for(const L of this._activeRegions){if(L.hiddenByOverlap||!YDe(w,L))continue;const F=mcs(L.min,L.max,k);A.push({min:F.min,max:F.max,sourceId:this._sourceIds[L.priority],footprint:L.footprint,footprintTileId:L.tileId,order:L.order,clipMask:L.clipMask,clipScope:L.clipScope})}return A}setSources(k){this._setSources(k.map(x=>({getSourceId:()=>x.cache.id,getFootprints:()=>{const w=[];for(const A of x.cache.getVisibleCoordinates()){const L=x.cache.getTile(A).buckets[x.layer];L&&L.updateFootprints(A.toUnwrapped(),w)}return w},getOrder:()=>x.order,getClipMask:()=>x.clipMask,getClipScope:()=>x.clipScope})))}_addSource(k){const x=k.getFootprints();if(x.length===0)return;const w=k.getOrder(),A=k.getClipMask(),L=k.getClipScope();for(const F of x){if(!F.footprint)continue;const U=nlt(F.footprint.min,F.footprint.max,F.id);this._activeRegions.push({min:U.min,max:U.max,hiddenByOverlap:!1,priority:this._sourceIds.length,tileId:F.id,footprint:F.footprint,order:w,clipMask:A,clipScope:L})}this._sourceIds.push(k.getSourceId())}_computeReplacement(){this._activeRegions.sort((x,w)=>x.priority-w.priority||Die(x.min,w.min)||Die(x.max,w.max)||x.order-w.order||x.clipMask-w.clipMask||function(A,L){const F=(U,K)=>U+K;return A.length-L.length||A.reduce(F,"").localeCompare(L.reduce(F,""))}(x.clipScope,w.clipScope));let k=this._activeRegions.length!==this._prevRegions.length;if(!k){let x=0;for(;!k&&x!==this._activeRegions.length;){const w=this._activeRegions[x],A=this._prevRegions[x];k=w.priority!==A.priority||!slt(w,A)||w.order!==A.order||w.clipMask!==A.clipMask||!Fa(w.clipScope,A.clipScope),this._activeRegions[x].hiddenByOverlap=A.hiddenByOverlap,++x}}if(k){++this._updateTime;for(const w of this._activeRegions)w.order!==$K&&(this._globalClipBounds.min.x=Math.min(this._globalClipBounds.min.x,w.min.x),this._globalClipBounds.min.y=Math.min(this._globalClipBounds.min.y,w.min.y),this._globalClipBounds.max.x=Math.max(this._globalClipBounds.max.x,w.max.x),this._globalClipBounds.max.y=Math.max(this._globalClipBounds.max.y,w.max.y));const x=w=>{const A=this._activeRegions;if(w>=A.length)return w;const L=A[w].priority;for(;w1){let w=0,A=x(w);for(;w!==A;){let L=w;const F=w;for(;L!==A;){const U=this._activeRegions[L];U.hiddenByOverlap=!1;for(let K=0;K=0;x--)this._addSource(k[x]);this._computeReplacement()}},o.eH=yo,o.eI=poe,o.eJ=e3,o.eK=$K,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,x){const w=new ao,A=new Ju,L=[],F=k+1+2,U=x[0]+1,K=x[0]+1+(1+x.length),X=(oe,ge,we)=>{let je=oe===F-1?oe-2:oe===0?oe:oe-1;return je+=we?24575:0,[je,ge]};for(let oe=0;oe>>=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=fot,o.ed=PDe,o.ee=Zb,o.ef=E,o.eg=function(k,x){return k[0]=x[0],k[1]=x[1],k[2]=x[2],k[3]=x[4],k[4]=x[5],k[5]=x[6],k[6]=x[8],k[7]=x[9],k[8]=x[10],k},o.eh=QC,o.ei=XL,o.ej=function(k,x,w,A,L){return pt((k-x)/(w-x)*(L-A)+A,A,L)},o.ek=Vt,o.el=function(k,x){var w=x[0],A=x[1],L=x[2],F=x[3],U=x[4],K=x[5],X=x[6],oe=x[7],ge=x[8],we=ge*U-K*oe,je=-ge*F+K*X,Le=oe*F-U*X,Re=w*we+A*je+L*Le;return Re?(k[0]=we*(Re=1/Re),k[1]=(-ge*A+L*oe)*Re,k[2]=(K*A-L*U)*Re,k[3]=je*Re,k[4]=(ge*w-L*X)*Re,k[5]=(-K*w+L*F)*Re,k[6]=Le*Re,k[7]=(-oe*w+A*X)*Re,k[8]=(U*w-A*F)*Re,k):null},o.em=ba,o.en=2,o.eo=Ce,o.ep=ct,o.eq=D,o.er=function(k,x){var w=new d(3);D(w,x);var A=1/w[0],L=1/w[1],F=1/w[2],U=x[0]*A,K=x[1]*L,X=x[2]*F,oe=x[4]*A,ge=x[5]*L,we=x[6]*F,je=x[8]*A,Le=x[9]*L,Re=x[10]*F,We=U+ge+Re,et=0;return We>0?(et=2*Math.sqrt(We+1),k[3]=.25*et,k[0]=(we-Le)/et,k[1]=(je-X)/et,k[2]=(K-oe)/et):U>ge&&U>Re?(et=2*Math.sqrt(1+U-ge-Re),k[3]=(we-Le)/et,k[0]=.25*et,k[1]=(K+oe)/et,k[2]=(je+X)/et):ge>Re?(et=2*Math.sqrt(1+ge-U-Re),k[3]=(je-X)/et,k[0]=(K+oe)/et,k[1]=.25*et,k[2]=(we+Le)/et):(et=2*Math.sqrt(1+Re-U-ge),k[3]=(K-oe)/et,k[0]=(je+X)/et,k[1]=(we+Le)/et,k[2]=.25*et),k},o.es=function(k,x){var w=2*Math.acos(x[3]),A=Math.sin(w/2);return A>c?(k[0]=x[0]/A,k[1]=x[1]/A,k[2]=x[2]/A):(k[0]=1,k[1]=0,k[2]=0),w},o.et=KRe,o.eu=Yie,o.ev=Kie,o.ew=[1,1,1],o.ex=Qz,o.ey=function(k,x,w,A){var L=x[0],F=x[1],U=x[2],K=x[3];return k[0]=L+A*(w[0]-L),k[1]=F+A*(w[1]-F),k[2]=U+A*(w[2]-U),k[3]=K+A*(w[3]-K),k},o.ez=Vz,o.f=kl,o.f0=_ot,o.f1=function(k){const x=[0,0,0],w=v(new Float64Array(16));return b(w,k.pixelMatrix,k.globeMatrix),Ze(x,x,w),new Js(x[0],x[1])},o.f2=Hy,o.f3=function(k,x,w=!1){if(Eu===Th.deferred||Eu===Th.loading||Eu===Th.loaded)throw new Error("setRTLTextPlugin cannot be called multiple times.");ox=da.resolveURL(k),Eu=Th.deferred,hp=x,tk(),w||r5()},o.f4=Oo,o.f5=oi,o.f6=rr,o.f7=function(k){const x=Rx();if(!x)return;const w=x.delete(no);k&&w.then(()=>k()).catch(k)},o.f8=jr,o.f9=oT,o.fA=Ni,o.fB=function(k){let x=0;if(new Uint32Array(k,0,1)[0]!==Dlt){const w=new Uint32Array(k,0,7),[,,A,L,F,U]=w;x=w.byteLength+L+F+U+F,(A!==k.byteLength||x>=k.byteLength)&&Br("Invalid b3dm header information.")}return zlt(k,x)},o.fC=function(k,x){const w=mRe(k);for(const A of w){for(const L of A.meshes)Vcs(L);A.lights&&(A.lightMeshIndex=A.meshes.length,A.meshes.push(Hcs(A.lights,x)))}return w},o.fD=yoe,o.fE=Si,o.fF=Xg,o.fG=Th,o.fH=function(k){hl(),Uu!=null&&Uu.then(x=>{x.keys().then(w=>{for(let A=0;ABr(L.message))}).catch(w=>Br(w.message))}).catch(x=>Br(x.message))},o.fa=2,o.fb=q0,o.fc=uI,o.fd=CK,o.fe=kdt,o.ff=Sdt,o.fg=ect,o.fh=Zi,o.fi="hd_road_elevation",o.fj=Wc,o.fk=Qs,o.fl=Lie,o.fm=a3,o.fn=TRe,o.fo=1,o.fp=lk,o.fq=function(k,x,w,A,L,F,U,K=1,X,oe,ge,we){k.createArrays(),k.tilePixelRatio=ur/(512*k.overscaling),k.compareText={},k.iconsNeedLinear=!1;const je=k.layers[0].layout,Le=k.layers[0]._unevaluatedLayout._values,Re={};Re.scaleFactor=K,Re.textSizeScaleRange=je.get("text-size-scale-range"),Re.iconSizeScaleRange=je.get("icon-size-scale-range");const[We,et]=Re.textSizeScaleRange,[it,yt]=Re.iconSizeScaleRange;Re.textScaleFactor=pt(Re.scaleFactor,We,et),Re.iconScaleFactor=pt(Re.scaleFactor,it,yt);const ht=Le["text-size"],Et=Le["icon-size"];if(k.textSizeData.kind==="composite"){const{minZoom:gs,maxZoom:ys}=k.textSizeData;Re.compositeTextSizes=[ht.possiblyEvaluate(new $i(gs,{worldview:ge}),F),ht.possiblyEvaluate(new $i(ys,{worldview:ge}),F)]}if(k.iconSizeData.kind==="composite"){const{minZoom:gs,maxZoom:ys}=k.iconSizeData;Re.compositeIconSizes=[Et.possiblyEvaluate(new $i(gs,{worldview:ge}),F,we),Et.possiblyEvaluate(new $i(ys,{worldview:ge}),F,we)]}Re.layoutTextSize=ht.possiblyEvaluate(new $i(U+1,{worldview:ge}),F),Re.layoutIconSize=Et.possiblyEvaluate(new $i(U+1,{worldview:ge}),F,we),Re.textMaxSize=ht.possiblyEvaluate(new $i(18,{worldview:ge}),F);const It=je.get("symbol-placement"),Ot=je.get("text-rotation-alignment")==="map"&&It!=="point",ws=je.get("text-size");let ds=!1;const _s=[];for(const gs of k.features){const ys=je.get("text-font").evaluate(gs,{},F).join(","),vn=ws.evaluate(gs,{},F)*Re.textScaleFactor,wn=Re.layoutTextSize.evaluate(gs,{},F)*Re.textScaleFactor,Pn=Re.layoutIconSize.evaluate(gs,{},F,we)*Re.iconScaleFactor,On={horizontal:{},vertical:void 0},Ln=gs.text;let Jn,gn=[0,0];if(Ln){const lo=Ln.toString(),Mu=je.get("text-letter-spacing").evaluate(gs,{},F)*Bp,Il=je.get("text-line-height").evaluate(gs,{},F)*Bp,ll=GC(lo)?Mu:0,zc=je.get("text-anchor").evaluate(gs,{},F),wu=je.get("text-variable-anchor");if(!wu){const th=je.get("text-radial-offset").evaluate(gs,{},F);if(th)gn=zct(zc,[th*Bp,IRe]);else{const Vx=je.get("text-offset").evaluate(gs,{},F);gn=[Vx[0]*Bp,Vx[1]*Bp]}}let Up=Ot?"center":je.get("text-justify").evaluate(gs,{},F);const ju=It==="point",eh=ju?je.get("text-max-width").evaluate(gs,{},F)*Bp:1/0,Jh=th=>{k.allowVerticalPlacement&&ix(lo)&&(On.vertical=jRe(Ln,x,w,L,ys,eh,Il,zc,th,ll,gn,$1.vertical,!0,wn,vn,X,Re.textScaleFactor))};if(!Ot&&wu){const th=Up==="auto"?wu.map(qp=>DRe(qp)):[Up];let Vx=!1;for(let qp=0;qp=0||!ix(lo)){const th=jRe(Ln,x,w,L,ys,eh,Il,zc,Up,ll,gn,$1.horizontal,!1,wn,vn,X,Re.textScaleFactor);th&&(On.horizontal[Up]=th)}Jh(ju?"left":Up)}}let Rn,qn,tr,pr,na,Cr,kr=!1;const fr=je.get("icon-text-fit").evaluate(gs,{},F);if(gs.icon&&gs.icon.hasPrimary()){const lo=rY(gs.icon,k.iconSizeData,Le["icon-size"],F,k.zoom,gs,X,Re.iconScaleFactor,ge,we);Rn=lo.iconPrimary,tr=lo.iconSecondary;const Mu=Rn.toString();if(qn=A.get(Mu),qn&&(na=je.get("icon-offset").evaluate(gs,{},F),Cr=je.get("icon-anchor").evaluate(gs,{},F),Jn=toe(L.get(Mu),tr?L.get(tr.toString()):void 0,na,Cr),kr=qn.sdf,k.sdfIcons===void 0?k.sdfIcons=qn.sdf:k.sdfIcons!==qn.sdf&&Br("Style sheet warning: Cannot mix SDF and non-SDF icons in one buffer"),(qn.pixelRatio!==k.pixelRatio||je.get("icon-rotate").constantOr(1)!==0)&&(k.iconsNeedLinear=!0)),tr){const Il=tr.toString();pr=A.get(Il)}}ds=ds||!(!gs.icon||!gs.icon.hasSecondary());const Qr=loe(On.horizontal)||On.vertical;k.iconsInText||(k.iconsInText=!!Qr&&Qr.iconsInText);const fa=wn*Re.textScaleFactor/Bp,{defaultShapedIcon:Za,verticallyShapedIcon:Ca}=tus(k,Jn,je,gs,F,On,fa,na,fr);fr!=="none"&&Jn&&(_ct(Jn)||wct(Jn))&&(ooe(0,qn,Rn,Jn,Za,fr,oe,A,L),ooe(0,pr,tr,Jn,Za,fr,oe,A,L),Ca&&(ooe(0,qn,Rn,Jn,Ca,fr,oe,A,L),ooe(0,pr,tr,Jn,Ca,fr,oe,A,L))),Jn=Za;const{iconBBox:zi,iconVerticalBBox:Ko,textBBox:Bi,textVerticalBBox:el}=Zds(k,Jn,Ca,je,gs,F,Pn,na,Re,L,Cr,On,wn,gn,we);_s.push({feature:gs,shapedTextOrientations:On,shapedText:Qr,shapedIcon:Jn,iconPrimary:Rn,iconSecondary:tr,iconOffset:na,iconAnchor:Cr,verticallyShapedIcon:Ca,layoutTextSize:wn,layoutIconSize:Pn,textOffset:gn,isSDFIcon:kr,iconTextFit:fr,iconCollisionBounds:zi,iconVerticalCollisionBounds:Ko,textCollisionBounds:Bi,textVerticalCollisionBounds:el})}return{featureData:_s,sizes:Re,hasAnySecondaryIcon:ds,textAlongLine:Ot,symbolPlacement:It}},o.fr=MRe,o.fs=ERe,o.ft=Mct,o.fu=Pct,o.fv=function(k,x,w,A,L,F,U,K,X,oe){k.iconAtlasPositions=oe.iconPositions;const{featureData:ge,hasAnySecondaryIcon:we,sizes:je,textAlongLine:Le,symbolPlacement:Re}=x;for(const We of ge){const{shapedIcon:et,verticallyShapedIcon:it,feature:yt,shapedTextOrientations:ht,shapedText:Et,layoutTextSize:It,textOffset:Ot,isSDFIcon:ws,iconPrimary:ds,iconSecondary:_s,iconTextFit:gs,iconOffset:ys,iconCollisionBounds:vn,iconVerticalCollisionBounds:wn,textCollisionBounds:Pn}=We;$ct(et,oe.iconPositions,ds,_s),$ct(it,oe.iconPositions,ds,_s),eus(ht,oe.iconPositions),Jds(ds,_s,oe.iconPositions),(Et||et)&&sus(k,yt,ht,et,it,X,je,It,0,Ot,ws,A,L,U,K,we,gs,ys,Le,Re,vn,wn,Pn)}w&&k.generateCollisionDebugBuffers(F,k.collisionBoxArray,je.textScaleFactor)},o.fw=Qie,o.fx=yl,o.fy=function(k){return k<=1?1:Math.pow(2,Math.floor(Math.log2(k)))},o.fz=Noe,o.g=di,o.h=function(k,x){return gm(Object.assign(k,{method:"GET"}),x)},o.i=function(k){return di.API_STYLE_REGEX.test(k)&&!Jo(k)},o.j=function(k){return btoa(encodeURIComponent(k).replace(/%([0-9A-F]{2})/g,(x,w)=>String.fromCharCode(+("0x"+w))))},o.k=ml,o.l=function(k){return decodeURIComponent(atob(k).split("").map(x=>"%"+("00"+x.charCodeAt(0).toString(16)).slice(-2)).join(""))},o.m=function(k,x){return gm(Object.assign(k,{type:"json"}),x)},o.n=Yh,o.o=da,o.p=function(k,x){return gm(Object.assign(k,{method:"POST"}),x)},o.q=wg,o.r=Is,o.s=function(k){try{const x=self[k];return x.setItem("_mapbox_test_",1),x.removeItem("_mapbox_test_"),!0}catch{return!1}},o.t=es,o.u=function(){return function k(x){return x?(x^Math.random()*(16>>x/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=Br,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(x=>{this.cache.delete(x),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 x=this.textures.get(k);if(x){const w=this.calculateTextureMemory(k);x.destroy(),this.textures.delete(k),this.textureAccessTimes.delete(k),this.textureMemoryUsed-=w}}evictTexturesIfNeeded(k){for(;this.textureMemoryUsed+k>this.maxTextureMemory&&this.textures.size>0;){let x=null,w=1/0;for(const[A]of this.textures.entries()){const L=this.textureAccessTimes.get(A)||0;Lthis._layers[er.id]),Is=ps[0];if(Is.visibility==="none")continue;const js=Is.source||"";let Kt=this.familiesBySource[js];Kt||(Kt=this.familiesBySource[js]=Object.create(null));const Qs=Is.sourceLayer||"_geojsonTileLayer";let an=Kt[Qs];an||(an=Kt[Qs]=[]),an.push(ps)}}}const f=1*c.fa;class y{constructor(rt){const pt={},jt=[];for(const Is in rt){const js=rt[Is],Kt=pt[Is]={};for(const Qs in js.glyphs){const an=js.glyphs[+Qs];if(!an||an.bitmap.width===0||an.bitmap.height===0)continue;const er=an.metrics.localGlyph?f:1,Xr={x:0,y:0,w:an.bitmap.width+2*er,h:an.bitmap.height+2*er};jt.push(Xr),Kt[Qs]=Xr}}const{w:Mt,h:es}=c.J(jt),ps=new c.f9({width:Mt||1,height:es||1});for(const Is in rt){const js=rt[Is];for(const Kt in js.glyphs){const Qs=js.glyphs[+Kt];if(!Qs||Qs.bitmap.width===0||Qs.bitmap.height===0)continue;const an=pt[Is][Kt],er=Qs.metrics.localGlyph?f:1;c.f9.copy(Qs.bitmap,ps,{x:0,y:0},{x:an.x+er,y:an.y+er},Qs.bitmap)}}this.image=ps,this.positions=pt}}function v(Wt,rt,pt){Wt[rt]?pt&&(Wt[rt].center=pt):Wt[rt]={floorIds:new Set,center:pt||[0,0],floors:{}}}function g(Wt,rt,pt,jt){for(const Mt of rt)v(Wt,Mt),Wt[Mt].floors[pt]=jt,Wt[Mt].floorIds.add(pt)}function b(Wt){return{id:Wt.properties.id.toString(),center:[Wt.properties.center_lon||0,Wt.properties.center_lat||0]}}function j(Wt,rt){const pt=Wt.properties.id.toString(),jt=!!Wt.properties.is_default&&Wt.properties.is_default,Mt=Wt.properties.connected_floor_ids?new Set(Wt.properties.connected_floor_ids.toString().split(";")):new Set,es=Wt.properties.conflicted_floor_ids?new Set(Wt.properties.conflicted_floor_ids.toString().split(";")):new Set,ps=Wt.properties.structure_ids?new Set(Wt.properties.structure_ids.toString().split(";")):new Set,Is=Wt.properties.name.toString(),js=Wt.properties.z_index,Kt=function(Qs,an){const er=Qs.loadGeometry();if(!er||er.length===0)return;const Xr=er.map(ma=>ma.map(Br=>c.fb(Br,an,Qs.extent)));return Xr.length===0?void 0:{type:"Polygon",coordinates:[Xr[0]]}}(Wt,rt);return{id:pt,isDefault:jt,connections:Mt,conflicts:es,buildings:ps,name:Is,zIndex:js,geometry:Kt}}function S(Wt,rt){return rt.every(pt=>Wt.properties&&Wt.properties[pt]!=null)}function C(Wt){return S(Wt,["type","id","name"])&&Wt.properties.type==="structure"}function E(Wt){return S(Wt,["type","id","name","z_index"])&&Wt.properties.type==="floor"}c.f8(y,"GlyphAtlas");class P{constructor(rt){this.tileID=new c.aR(rt.tileID.overscaledZ,rt.tileID.wrap,rt.tileID.canonical.z,rt.tileID.canonical.x,rt.tileID.canonical.y),this.tileZoom=rt.tileZoom,this.uid=rt.uid,this.zoom=rt.zoom,this.lut=rt.lut,this.canonical=rt.tileID.canonical,this.pixelRatio=rt.pixelRatio,this.tileSize=rt.tileSize,this.source=rt.source,this.scope=rt.scope,this.overscaling=this.tileID.overscaleFactor(),this.showCollisionBoxes=rt.showCollisionBoxes,this.collectResourceTiming=!!rt.request&&rt.request.collectResourceTiming,this.promoteId=rt.promoteId,this.renderSourceType=rt.renderSourceType,this.tileTransform=c.fc(rt.tileID.canonical,rt.projection),this.projection=rt.projection,this.worldview=rt.worldview,this.localizableLayerIds=rt.localizableLayerIds,this.brightness=rt.brightness,this.extraShadowCaster=!!rt.extraShadowCaster,this.tessellationStep=rt.tessellationStep,this.scaleFactor=rt.scaleFactor,this.worldview=rt.worldview,this.indoor=rt.indoor}parse(rt,pt,jt,Mt,es,ps){this.status="parsing",this.data=rt,this.collisionBoxArray=new c.fd;const Is=new c.fe(Object.keys(rt.layers).sort()),js=new c.ff(this.tileID,this.promoteId);js.bucketLayerIDs=[];const Kt={},Qs=new c.fg(256,256),an={featureIndex:js,iconDependencies:new Map,patternDependencies:new Map,glyphDependencies:{},lineAtlas:Qs,availableImages:jt,brightness:this.brightness,scaleFactor:this.scaleFactor,elevationFeatures:void 0,activeFloors:void 0};this.indoor&&(an.activeFloors=function(Br,sa,Rr,ra){const Si=sa.indoorState.activeFloorsVisible;if(!sa.sourceLayers)return Si?sa.indoorState.activeFloors:void 0;const Gi=function(Ta,eo){if(!Ta)return c.w("No source layers defined in indoor specification"),eo;if(Ta.size===0)return eo;const So=Ta.difference(eo);for(const Ra of So)c.w(`Missing source layer required in indoor specification: ${Ra}`);return eo.intersection(eo)}(sa.sourceLayers,new Set(Object.keys(Br.layers))),rl=sa.indoorState,Ii=function(Ta,eo,So,Ra,Eo){const Ro={};for(const di of eo){const rr=Ta.layers[di];if(rr)for(let oi=0;oi=Ra.maxzoom||Ra.visibility==="none")continue;M(So,this.zoom,an.brightness,jt,this.worldview,an.activeFloors);const Eo=Kt[Ra.id]=Ra.createBucket({index:js.bucketLayerIDs.length,layers:So,zoom:this.zoom,lut:this.lut,canonical:this.canonical,pixelRatio:this.pixelRatio,overscaling:this.overscaling,collisionBoxArray:this.collisionBoxArray,sourceLayerIndex:rl,sourceID:this.source,projection:this.projection.spec,tessellationStep:this.tessellationStep,styleDefinedModelURLs:Mt,worldview:this.worldview,localizable:Ta,availableImages:jt,maxUniformBufferBindings:this.maxUniformBufferBindings,maxUniformBlockSizeDwords:this.maxUniformBlockSizeDwords,disableSymbolUBO:this.disableSymbolUBO});js.bucketLayerIDs.push(So.map(di=>c.F(di.id,di.scope)));let Ro=Eo.prepare?Eo.prepare():null;Ro!=null?(Ro=Ro.then(()=>Eo.populate(Ii,an,this.tileID.canonical,this.tileTransform)),er.push(Ro)):Eo.populate(Ii,an,this.tileID.canonical,this.tileTransform)}}const ma=()=>{Qs.trim();const Br=!(!an.elevationFeatures||!an.elevationFeatures.some(Ra=>Ra.heightRange.min<0));let sa,Rr,ra,Si,Gi,rl,Ii;const Ta={type:"maybePrepare",renderSourceType:this.renderSourceType,zoom:this.zoom},eo=()=>{if(sa)return this.status="done",ps(sa);if(this.extraShadowCaster)this.status="done",ps(null,{buckets:Object.values(Kt).filter(Ra=>!Ra.isEmpty()),featureIndex:js,collisionBoxArray:null,hasTunnelGeometry:Br,glyphAtlasImage:null,lineAtlas:null,imageAtlas:null,brightness:an.brightness,glyphMap:null,iconMap:null,glyphPositions:null});else if(Rr&&ra&&Si&&Ii){const Eo=new y(Rr),Ro=new Map;for(const[oi,Oo]of ra.entries()){const{imagePosition:kl}=c.fn(oi,Oo,c.fo);Ro.set(oi,kl)}const di={};for(const oi in Kt){const Oo=Kt[oi];Oo instanceof c.fp&&(M(Oo.layers,this.zoom,an.brightness,jt,this.worldview,an.activeFloors),di[oi]=c.fq(Oo,Rr,Eo.positions,ra,Ro,this.tileID.canonical,this.tileZoom,this.scaleFactor,this.pixelRatio,Gi,this.worldview,jt))}const rr={iconsPending:!0,patternsPending:!0};this.rasterizeIfNeeded(es,ra,Gi,()=>{rr.iconsPending=!1,So(di,Eo,rr,void 0,Ii)}),this.rasterizeIfNeeded(es,Si,rl,()=>{rr.patternsPending=!1,So(di,Eo,rr,void 0,Ii)})}},So=(Ra,Eo,Ro,di,rr)=>{if(Ro.iconsPending||Ro.patternsPending)return;const oi=ra.size>0||Si.size>0,Oo=Object.keys(Ra).length>0;if(!oi&&!Oo)return this.status="done",void ps(null,{buckets:Object.values(Kt).filter(Jo=>!Jo.isEmpty()),featureIndex:js,collisionBoxArray:this.collisionBoxArray,hasTunnelGeometry:Br,glyphAtlasImage:Eo.image,lineAtlas:Qs,imageAtlas:null,brightness:an.brightness});const kl=(Jo,Sl)=>{for(const vu in Kt){const Ku=Kt[vu];if(vu in Ra)c.fv(Ku,Ra[vu],this.showCollisionBoxes,jt,this.tileID.canonical,this.tileZoom,this.projection,this.brightness,ra,Sl);else if(Ku.hasPattern&&(Ku instanceof c.fw||Ku instanceof c.fl||Ku instanceof c.e0)){M(Ku.layers,this.zoom,an.brightness,jt,this.worldview,an.activeFloors);const Tp=Object.fromEntries(Sl.patternPositions);Ku.addFeatures(an,this.tileID.canonical,Tp,jt,this.tileTransform,this.brightness)}}this.status="done",ps(null,{buckets:Object.values(Kt).filter(vu=>!vu.isEmpty()),featureIndex:js,collisionBoxArray:this.collisionBoxArray,hasTunnelGeometry:Br,glyphAtlasImage:Eo.image,lineAtlas:Qs,imageAtlas:Jo,brightness:an.brightness})};if(oi){const Jo=new Map,Sl=c.fr(ra,Jo),vu=c.fr(Si,Jo),Ku=new c.fs(Sl,vu,rr,this.lut,Jo);es.send("checkAtlasCache",{descriptor:Ku,scope:this.scope},(Tp,Bd)=>{let xm,xs;if(Tp&&c.w(`[Worker] Error checking atlas cache: ${Tp.message}`),Bd)xm=new c.ft(Bd.sourceHash),xs=Bd;else{const da=new c.fu(ra,Si,this.lut,rr);xm=da,xs=da}kl(xm,xs)})}else kl(null,{iconPositions:new Map,patternPositions:new Map})};if(!this.extraShadowCaster){const Ra=c.fk(an.glyphDependencies,di=>Object.keys(di).map(Number));Object.keys(Ra).length?es.send("getGlyphs",{uid:this.uid,stacks:Ra},(di,rr)=>{sa||(sa=di,Rr=rr,eo())},void 0,!1,Ta):Rr={},Ii=new Map;const Eo=Array.from(an.iconDependencies.keys()).map(di=>c.I.parse(di));Eo.length?es.send("getImages",{images:Eo,source:this.source,scope:this.scope,tileID:this.tileID,type:"icons"},(di,rr)=>{if(!sa){sa=di,ra=new Map,Gi=this.updateImageMapAndGetImageTaskQueue(ra,rr.images,an.iconDependencies);for(const[oi,Oo]of rr.versions.entries())Ii.set(oi,Oo);eo()}},void 0,!1,Ta):(ra=new Map,Gi=new Map);const Ro=Array.from(an.patternDependencies.keys()).map(di=>c.I.parse(di));Ro.length?es.send("getImages",{images:Ro,source:this.source,scope:this.scope,tileID:this.tileID,type:"patterns"},(di,rr)=>{if(!sa){sa=di,Si=new Map,rl=this.updateImageMapAndGetImageTaskQueue(Si,rr.images,an.patternDependencies);for(const[oi,Oo]of rr.versions.entries())Ii.set(oi,Oo);eo()}},void 0,!1,Ta):(Si=new Map,rl=new Map)}if(an.elevationFeatures&&an.elevationFeatures.length>0){const Ra=[];for(const Ro of Object.values(Kt))if(Ro instanceof c.fl){const di=Ro.getUnevaluatedPortalGraph();di&&Ra.push(di)}const Eo=c.fm.evaluate(Ra);for(const Ro of Object.values(Kt))if(Ro instanceof c.fl){const di=rt.layers[Is.decode(Ro.sourceLayerIndex)];Ro.setEvaluatedPortalGraph(Eo,di,this.tileID.canonical,an.availableImages,an.brightness)}}eo()};er.length>0?Promise.allSettled(er).then(ma).catch(ps):ma()}updateParameters(rt){this.scaleFactor=rt.scaleFactor,this.showCollisionBoxes=rt.showCollisionBoxes,this.projection=rt.projection,this.brightness=rt.brightness,this.tileTransform=c.fc(rt.tileID.canonical,rt.projection),this.extraShadowCaster=rt.extraShadowCaster,this.lut=rt.lut,this.worldview=rt.worldview,this.indoor=rt.indoor}rasterizeIfNeeded(rt,pt,jt,Mt){Array.from(pt.values()).some(es=>es.usvg)?this.rasterize(rt,pt,jt,Mt):Mt()}updateImageMapAndGetImageTaskQueue(rt,pt,jt){const Mt=new Map;for(const es of pt.keys()){const ps=jt.get(es)||[];for(const Is of ps){const js=Is.toString(),Kt=pt.get(Is.id.toString());Kt.usvg?Mt.has(js)||(Mt.set(js,Is),rt.set(js,Object.assign({},Kt))):rt.set(js,Kt)}}return Mt}rasterize(rt,pt,jt,Mt){this.rasterizeTask=rt.send("rasterizeImages",{scope:this.scope,tasks:jt},(es,ps)=>{if(!es)for(const[Is,js]of ps.entries()){const Kt=Object.assign(pt.get(Is),{data:js});pt.set(Is,Kt)}Mt()})}cancelRasterize(){this.rasterizeTask&&this.rasterizeTask.cancel()}}function M(Wt,rt,pt,jt,Mt,es){const ps=new c.ae(rt,{brightness:pt,worldview:Mt,activeFloors:es});for(const Is of Wt)Is.recalculate(ps,jt)}class I extends c.E{constructor({actor:rt,layerIndex:pt,availableImages:jt,availableModels:Mt,isSpriteLoaded:es,tileProvider:ps,brightness:Is,maxUniformBufferBindings:js,maxUniformBlockSizeDwords:Kt,disableSymbolUBO:Qs}){super(),this.actor=rt,this.layerIndex=pt,this.availableImages=jt,this.availableModels=Mt,this.loadVectorData=c.aO,this.tileProvider=ps,this.loading={},this.loaded={},this.deduped=new c.aN(rt.scheduler),this.isSpriteLoaded=es,this.scheduler=rt.scheduler,this.brightness=Is,this.maxUniformBufferBindings=js,this.maxUniformBlockSizeDwords=Kt,this.disableSymbolUBO=Qs}loadTileData(rt,pt){if(!this.tileProvider)return this.loadVectorData(rt,pt);const jt=new AbortController,{z:Mt,x:es,y:ps}=rt.tileID.canonical;return this.tileProvider.loadTile({z:Mt,x:es,y:ps},{request:rt.request,signal:jt.signal}).then(Is=>{if(jt.signal.aborted)return;if(Is==null){const Kt=new Error("Tile not found");return Kt.status=404,pt(Kt)}if(Is.data===null)return pt(null,null);const js=new Map;Is.expires&&js.set("expires",Is.expires),Is.cacheControl&&js.set("cache-control",Is.cacheControl),pt(null,{rawData:Is.data,responseHeaders:js})}).catch(Is=>{jt.signal.aborted||pt(Is instanceof Error?Is:new Error(String(Is)))}),()=>jt.abort()}loadTile(rt,pt){const jt=rt.uid,Mt=rt&&rt.request,es=Mt&&Mt.collectResourceTiming,ps=this.loading[jt]=new P(rt);ps.maxUniformBufferBindings=this.maxUniformBufferBindings,ps.maxUniformBlockSizeDwords=this.maxUniformBlockSizeDwords,ps.disableSymbolUBO=this.disableSymbolUBO,ps.abort=this.loadTileData(rt,(Is,js)=>{const Kt=!this.loading[jt];if(delete this.loading[jt],ps.cancelRasterize(),Kt||Is||!js)return ps.status="done",Kt||(this.loaded[jt]=ps),pt(Is);const Qs=js.rawData,an={},er=c.aP(js.responseHeaders);er&&er.expires&&(an.expires=er.expires),er&&er.cacheControl&&(an.cacheControl=er.cacheControl),ps.vectorTile=js.vectorTile||new c.fx(new c.a$(Qs));const Xr=()=>{ps.parse(ps.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,(ma,Br)=>{if(ma||!Br)return pt(ma);const sa={};if(es){const Rr=d(Mt);Rr.length>0&&(sa.resourceTiming=JSON.parse(JSON.stringify(Rr)))}pt(null,Object.assign({rawTileData:Qs.slice(0),responseHeaders:js.responseHeaders},Br,an,sa))})};this.isSpriteLoaded?Xr():this.once("isSpriteLoaded",()=>{this.scheduler?this.scheduler.add(Xr,{type:"parseTile",renderSourceType:rt.renderSourceType,zoom:rt.tileZoom}):Xr()}),this.loaded=this.loaded||{},this.loaded[jt]=ps})}reloadTile(rt,pt){const jt=this.loaded,Mt=rt.uid;if(jt&&jt[Mt]){const es=jt[Mt];es.updateParameters(rt);const ps=(Is,js)=>{const Kt=es.reloadCallback;Kt&&(delete es.reloadCallback,es.parse(es.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,Kt)),pt(Is,js)};es.status==="parsing"?es.reloadCallback=ps:es.status==="done"&&(es.vectorTile?es.parse(es.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,ps):ps())}else pt(null,void 0)}abortTile(rt,pt){const jt=rt.uid,Mt=this.loading[jt];Mt&&(Mt.abort&&Mt.abort(),delete this.loading[jt]),pt()}removeTile(rt,pt){const jt=this.loaded,Mt=rt.uid;jt&&jt[Mt]&&delete jt[Mt],pt()}}class D{constructor(rt){this.loading={}}loadTile(rt,pt){const jt=rt.uid,{cancel:Mt}=c.b1(rt.request,(es,ps,Is)=>{const js=!this.loading[jt];if(delete this.loading[jt],js||es||!ps)return pt(es);this.decodeTile(jt,ps,rt.encoding).then(Kt=>{const{expires:Qs,cacheControl:an}=c.aP(Is);pt(null,Object.assign(Kt,{expires:Qs,cacheControl:an}))}).catch(Kt=>pt(Kt))});this.loading[jt]={cancel:Mt}}async decodeTile(rt,pt,jt){const Mt=await createImageBitmap(new Blob([new Uint8Array(pt)],{type:"image/png"})),es=1-(Mt.width-c.fy(Mt.width))/2,ps=es<1,Is=this.getImageData(Mt,es);return Mt.close(),{dem:new c.fz(rt,Is,jt,ps),borderReady:ps}}reloadTile(rt,pt){pt(null,null)}abortTile(rt,pt){const jt=rt.uid,Mt=this.loading[jt];Mt&&(Mt.cancel(),delete this.loading[jt]),pt()}removeTile(rt,pt){pt()}getImageData(rt,pt){this.offscreenCanvas&&this.offscreenCanvasContext||(this.offscreenCanvas=new OffscreenCanvas(rt.width,rt.height),this.offscreenCanvasContext=this.offscreenCanvas.getContext("2d",{willReadFrequently:!0})),this.offscreenCanvas.width=rt.width,this.offscreenCanvas.height=rt.height,this.offscreenCanvasContext.drawImage(rt,0,0,rt.width,rt.height);const jt=this.offscreenCanvasContext.getImageData(-pt,-pt,rt.width+2*pt,rt.height+2*pt);return this.offscreenCanvasContext.clearRect(0,0,this.offscreenCanvas.width,this.offscreenCanvas.height),jt}}c.a_.setPbf(c.a$);class O{constructor(rt){this._mrt=new c.a_(rt.partial?30:1/0),this._isHeaderLoaded=!1,this.uid=rt.uid,this.tileID=rt.tileID,this.source=rt.source}parse(rt,pt){const jt=this._mrt;this.status="parsing",this._entireBuffer=rt;try{jt.parseHeader(rt),this._isHeaderLoaded=!0;const Mt=[];for(const es in jt.layers){const ps=jt.getLayer(es),Is=ps.getDataRange(ps.getBandList()),js=jt.createDecodingTask(Is),Kt=rt.slice(Is.firstByte,Is.lastByte+1),Qs=c.a_.performDecoding(Kt,js).then(an=>js.complete(null,an)).catch(an=>js.complete(an,null));Mt.push(Qs)}Promise.allSettled(Mt).then(()=>pt(null,jt)).catch(es=>pt(es))}catch(Mt){pt(Mt)}}}class V{constructor({actor:rt}){this.actor=rt,this.loading={},this.loaded={}}loadTile(rt,pt){const jt=rt.uid,Mt=rt.request,es=this.loading[jt]=new O(rt),{cancel:ps}=c.b1(Mt,(Is,js,Kt)=>{const Qs=!this.loading[jt];if(delete this.loading[jt],Qs||Is||!js)return es.status="done",Qs||(this.loaded[jt]=es),pt(Is);es.parse(js,(an,er)=>{if(an||!er)return pt(an);pt(null,er,Kt)}),this.loaded[jt]=es});es.abort=ps}reloadTile(rt,pt){pt(null,void 0)}abortTile(rt,pt){const jt=rt.uid,Mt=this.loading[jt];Mt&&(Mt.abort&&Mt.abort(),delete this.loading[jt]),pt()}removeTile(rt,pt){const jt=rt.uid;this.loaded[jt]&&delete this.loaded[jt],pt()}decodeRasterArray(rt,pt){c.a_.performDecoding(rt.buffer,rt.task).then(jt=>pt(null,jt)).catch(jt=>pt(jt))}}const G=c.fA.prototype.toGeoJSON;class ${constructor(rt){this._feature=rt,this.extent=c.an,this.type=rt.type,this.properties=rt.tags,"id"in rt&&!isNaN(rt.id)&&(this.id=parseInt(rt.id,10))}loadGeometry(){if(this._feature.type===1){const rt=[];for(const pt of this._feature.geometry)rt.push([new c.P(pt[0],pt[1])]);return rt}{const rt=[];for(const pt of this._feature.geometry){const jt=[];for(const Mt of pt)jt.push(new c.P(Mt[0],Mt[1]));rt.push(jt)}return rt}}toGeoJSON(rt,pt,jt){return G.call(this,rt,pt,jt)}}class H{constructor(rt,pt){this.name=rt,this.extent=c.an,this.length=pt.length,this._jsonFeatures=pt}feature(rt){return new $(this._jsonFeatures[rt])}}class Y{constructor(rt){this.layers={},this.extent=c.an;for(const pt of Object.keys(rt))this.layers[pt]=new H(pt,rt[pt])}}const Z=64/4096;class ne{constructor(){this.features=new Map}clear(){this.features.clear()}load(rt=[],pt){for(const jt of rt){const Mt=jt.id;if(Mt==null)continue;let es=this.features.get(Mt);es&&this.updateCache(es,pt),jt.geometry?(es=ie(jt),this.updateCache(es,pt),this.features.set(Mt,es)):this.features.delete(Mt),this.updateCache(es,pt)}}updateCache(rt,pt){for(const{canonical:jt,uid:Mt}of Object.values(pt)){const{z:es,x:ps,y:Is}=jt;ce(rt,Math.pow(2,es),ps,Is)&&delete pt[Mt]}}getTile(rt,pt,jt){const Mt=Math.pow(2,rt),es=[];for(const ps of this.features.values())ce(ps,Mt,pt,jt)&&es.push(be(ps,Mt,pt,jt));return{features:es}}getFeatures(){return[...this.features.values()]}}function ce({minX:Wt,minY:rt,maxX:pt,maxY:jt},Mt,es,ps){return Wt<(es+1+Z)/Mt&&rt<(ps+1+Z)/Mt&&pt>(es-Z)/Mt&&jt>(ps-Z)/Mt}function ie(Wt){const{id:rt,geometry:pt,properties:jt}=Wt;if(!pt)return;if(pt.type==="GeometryCollection")throw new Error("GeometryCollection not supported in dynamic mode.");const{type:Mt,coordinates:es}=pt,ps={id:rt,type:1,geometry:[],tags:jt,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0},Is=ps.geometry;if(Mt==="Point")te(es,Is,ps);else if(Mt==="MultiPoint")for(const js of es)te(js,Is,ps);else if(Mt==="LineString")ps.type=2,ae(es,Is,ps);else if(Mt==="MultiLineString")ps.type=2,le(es,Is,ps);else if(Mt==="Polygon")ps.type=3,le(es,Is,ps,!0);else{if(Mt!=="MultiPolygon")throw new Error("Input data is not a valid GeoJSON object.");ps.type=3;for(const js of es)le(js,Is,ps,!0)}return ps}function te([Wt,rt],pt,jt){const Mt=c.aH(Wt);let es=c.aL(rt);es=es<0?0:es>1?1:es,pt.push(Mt,es),jt.minX=Math.min(jt.minX,Mt),jt.minY=Math.min(jt.minY,es),jt.maxX=Math.max(jt.maxX,Mt),jt.maxY=Math.max(jt.maxY,es)}function ae(Wt,rt,pt,jt=!1,Mt=!1){const es=[];for(const ps of Wt)te(ps,es,pt);rt.push(es),jt&&function(ps,Is){let js=0;for(let Kt=0,Qs=ps.length,an=Qs-2;Kt0===Is)for(let Kt=0,Qs=ps.length;Kt=ps&&an>=ps||(Kt>=ps?(Qs+=Math.round(ma*((ps-Kt)/Xr)),Kt=ps):an>=ps&&(er=Qs+Math.round(ma*((ps-Kt)/Xr)),an=ps),Qs>=ps&&er>=ps||(Qs>=ps?(Kt+=Math.round(Xr*((ps-Qs)/ma)),Qs=ps):er>=ps&&(an=Kt+Math.round(Xr*((ps-Qs)/ma)),er=ps),Is&&Kt===Is[Is.length-1][0]&&Qs===Is[Is.length-1][1]||(Is=[[Kt,Qs]],Mt.push(Is)),Is.push([an,er])))))}}function he(Wt,rt,pt,jt,Mt){const es=(pt-Z)/rt,ps=(jt-Z)/rt,Is=(pt+1+Z)/rt,js=(jt+1+Z)/rt;function Kt(er,Xr){let ma=0;return erIs&&(ma|=2),Xrjs&&(ma|=8),ma}let Qs=[];for(let er=1;er<=8;er*=2){let Xr=Wt[Wt.length-2],ma=Wt[Wt.length-1],Br=!(Kt(Xr,ma)&er);for(let sa=0;sa>31}function ke(Wt,rt){const{geometry:pt,type:jt}=Wt;let Mt=0,es=0;if(jt===1){rt.writeVarint(Pe(1,pt.length));for(const ps of pt){const Is=ps[0]-Mt,js=ps[1]-es;rt.writeVarint(ze(Is)),rt.writeVarint(ze(js)),Mt+=Is,es+=js}}else for(const ps of pt){if(ps.length===0)continue;rt.writeVarint(Pe(1,1));const Is=ps.length-(jt===3?1:0);for(let js=0;jsWt},Fe=Math.fround||(Ne=new Float32Array(1),Wt=>(Ne[0]=+Wt,Ne[0]));var Ne;class Ye{constructor(rt){this.options=Object.assign(Object.create(Se),rt),this.trees=new Array(this.options.maxZoom+1),this.stride=this.options.reduce?7:6,this.clusterProps=[]}load(rt){const{log:pt,minZoom:jt,maxZoom:Mt}=this.options;pt&&console.time("total time");const es=`prepare ${rt.length} points`;pt&&console.time(es),this.points=rt;const ps=[];for(let js=0;js=jt;js--){const Kt=+Date.now();Is=this.trees[js]=this._createTree(this._cluster(Is,js)),pt&&console.log("z%d: %d clusters in %dms",js,Is.numItems,+Date.now()-Kt)}return pt&&console.timeEnd("total time"),this}getClusters(rt,pt){let jt=((rt[0]+180)%360+360)%360-180;const Mt=Math.max(-90,Math.min(90,rt[1]));let es=rt[2]===180?180:((rt[2]+180)%360+360)%360-180;const ps=Math.max(-90,Math.min(90,rt[3]));if(rt[2]-rt[0]>=360)jt=-180,es=180;else if(jt>es){const an=this.getClusters([jt,Mt,180,ps],pt),er=this.getClusters([-180,Mt,es,ps],pt);return an.concat(er)}const Is=this.trees[this._limitZoom(pt)],js=Is.range(Qe(jt),Ue(ps),Qe(es),Ue(Mt)),Kt=Is.data,Qs=[];for(const an of js){const er=this.stride*an;Qs.push(Kt[er+5]>1?Ve(Kt,er,this.clusterProps):this.points[Kt[er+3]])}return Qs}getChildren(rt){const pt=this._getOriginId(rt),jt=this._getOriginZoom(rt),Mt="No cluster with the specified id.",es=this.trees[jt];if(!es)throw new Error(Mt);const ps=es.data;if(pt*this.stride>=ps.length)throw new Error(Mt);const Is=this.options.radius/(this.options.extent*Math.pow(2,jt-1)),js=es.within(ps[pt*this.stride],ps[pt*this.stride+1],Is),Kt=[];for(const Qs of js){const an=Qs*this.stride;ps[an+4]===rt&&Kt.push(ps[an+5]>1?Ve(ps,an,this.clusterProps):this.points[ps[an+3]])}if(Kt.length===0)throw new Error(Mt);return Kt}getLeaves(rt,pt,jt){const Mt=[];return this._appendLeaves(Mt,rt,pt=pt||10,jt=jt||0,0),Mt}getTile(rt,pt,jt){const Mt=this.trees[this._limitZoom(rt)],es=Math.pow(2,rt),{extent:ps,radius:Is}=this.options,js=Is/ps,Kt=(jt-js)/es,Qs=(jt+1+js)/es,an={features:[]};return this._addTileFeatures(Mt.range((pt-js)/es,Kt,(pt+1+js)/es,Qs),Mt.data,pt,jt,es,an),pt===0&&this._addTileFeatures(Mt.range(1-js/es,Kt,1,Qs),Mt.data,es,jt,es,an),pt===es-1&&this._addTileFeatures(Mt.range(0,Kt,js/es,Qs),Mt.data,-1,jt,es,an),an.features.length?an:null}getClusterExpansionZoom(rt){let pt=this._getOriginZoom(rt)-1;for(;pt<=this.options.maxZoom;){const jt=this.getChildren(rt);if(pt++,jt.length!==1)break;rt=jt[0].properties.cluster_id}return pt}_appendLeaves(rt,pt,jt,Mt,es){const ps=this.getChildren(pt);for(const Is of ps){const js=Is.properties;if(js&&js.cluster?es+js.point_count<=Mt?es+=js.point_count:es=this._appendLeaves(rt,js.cluster_id,jt,Mt,es):es1;let Qs,an,er;if(Kt)Qs=qe(pt,js,this.clusterProps),an=pt[js],er=pt[js+1];else{const Br=this.points[pt[js+3]];Qs=Br.properties;const[sa,Rr]=Br.geometry.coordinates;an=Qe(sa),er=Ue(Rr)}const Xr={type:1,geometry:[[Math.round(this.options.extent*(an*es-jt)),Math.round(this.options.extent*(er*es-Mt))]],tags:Qs};let ma;ma=Kt||this.options.generateId?pt[js+3]:this.points[pt[js+3]].id,ma!==void 0&&(Xr.id=ma),ps.features.push(Xr)}}_limitZoom(rt){return Math.max(this.options.minZoom,Math.min(Math.floor(+rt),this.options.maxZoom+1))}_cluster(rt,pt){const{radius:jt,extent:Mt,reduce:es,minPoints:ps}=this.options,Is=jt/(Mt*Math.pow(2,pt)),js=rt.data,Kt=[],Qs=this.stride;for(let an=0;anpt&&(sa+=js[ra+5])}if(sa>Br&&sa>=ps){let Rr,ra=er*Br,Si=Xr*Br,Gi=-1;const rl=(an/Qs<<5)+(pt+1)+this.points.length;for(const Ii of ma){const Ta=Ii*Qs;if(js[Ta+2]<=pt)continue;js[Ta+2]=pt;const eo=js[Ta+5];ra+=js[Ta]*eo,Si+=js[Ta+1]*eo,js[Ta+4]=rl,es&&(Rr||(Rr=this._map(js,an,!0),Gi=this.clusterProps.length,this.clusterProps.push(Rr)),es(Rr,this._map(js,Ta)))}js[an+4]=rl,Kt.push(ra/sa,Si/sa,1/0,rl,-1,sa),es&&Kt.push(Gi)}else{for(let Rr=0;Rr1)for(const Rr of ma){const ra=Rr*Qs;if(!(js[ra+2]<=pt)){js[ra+2]=pt;for(let Si=0;Si>5}_getOriginZoom(rt){return(rt-this.points.length)%32}_map(rt,pt,jt){if(rt[pt+5]>1){const ps=this.clusterProps[rt[pt+6]];return jt?Object.assign({},ps):ps}const Mt=this.points[rt[pt+3]].properties,es=this.options.map(Mt);return jt&&es===Mt?Object.assign({},es):es}}function Ve(Wt,rt,pt){return{type:"Feature",id:Wt[rt+3],properties:qe(Wt,rt,pt),geometry:{type:"Point",coordinates:[(jt=Wt[rt],360*(jt-.5)),Xe(Wt[rt+1])]}};var jt}function qe(Wt,rt,pt){const jt=Wt[rt+5],Mt=jt>=1e4?`${Math.round(jt/1e3)}k`:jt>=1e3?Math.round(jt/100)/10+"k":jt,es=Wt[rt+6],ps=es===-1?{}:Object.assign({},pt[es]);return Object.assign(ps,{cluster:!0,cluster_id:Wt[rt+3],point_count:jt,point_count_abbreviated:Mt})}function Qe(Wt){return Wt/360+.5}function Ue(Wt){const rt=Math.sin(Wt*Math.PI/180),pt=.5-.25*Math.log((1+rt)/(1-rt))/Math.PI;return pt<0?0:pt>1?1:pt}function Xe(Wt){const rt=(180-360*Wt)*Math.PI/180;return 360*Math.atan(Math.exp(rt))/Math.PI-90}function nt(Wt,rt,pt,jt){let Mt=jt;const es=rt+(pt-rt>>1);let ps,Is=pt-rt;const js=Wt[rt],Kt=Wt[rt+1],Qs=Wt[pt],an=Wt[pt+1];for(let er=rt+3;erMt)ps=er,Mt=Xr;else if(Xr===Mt){const ma=Math.abs(er-es);majt&&(ps-rt>3&&nt(Wt,rt,ps,jt),Wt[ps+2]=Mt,pt-ps>3&&nt(Wt,ps,pt,jt))}function $e(Wt,rt,pt,jt,Mt,es){let ps=Mt-pt,Is=es-jt;if(ps!==0||Is!==0){const js=((Wt-pt)*ps+(rt-jt)*Is)/(ps*ps+Is*Is);js>1?(pt=Mt,jt=es):js>0&&(pt+=ps*js,jt+=Is*js)}return ps=Wt-pt,Is=rt-jt,ps*ps+Is*Is}function Ge(Wt,rt,pt,jt){const Mt={id:Wt??null,type:rt,geometry:pt,tags:jt,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};if(rt==="Point"||rt==="MultiPoint"||rt==="LineString")ct(Mt,pt);else if(rt==="Polygon")ct(Mt,pt[0]);else if(rt==="MultiLineString")for(const es of pt)ct(Mt,es);else if(rt==="MultiPolygon")for(const es of pt)ct(Mt,es[0]);return Mt}function ct(Wt,rt){for(let pt=0;pt0&&(ps+=jt?(Mt*Qs-Kt*es)/2:Math.sqrt(Math.pow(Kt-Mt,2)+Math.pow(Qs-es,2))),Mt=Kt,es=Qs}const Is=rt.length-3;rt[2]=1,nt(rt,0,Is,pt),rt[Is+2]=1,rt.size=Math.abs(ps),rt.start=0,rt.end=rt.size}function Xt(Wt,rt,pt,jt){for(let Mt=0;Mt1?1:pt}function wt(Wt,rt,pt,jt,Mt,es,ps,Is){if(jt/=rt,es>=(pt/=rt)&&ps=jt)return null;const js=[];for(const Kt of Wt){const Qs=Kt.geometry;let an=Kt.type;const er=Mt===0?Kt.minX:Kt.minY,Xr=Mt===0?Kt.maxX:Kt.maxY;if(er>=pt&&Xr=jt)continue;let ma=[];if(an==="Point"||an==="MultiPoint")Ts(Qs,ma,pt,jt,Mt);else if(an==="LineString")vt(Qs,ma,pt,jt,Mt,!1,Is.lineMetrics);else if(an==="MultiLineString")As(Qs,ma,pt,jt,Mt,!1);else if(an==="Polygon")As(Qs,ma,pt,jt,Mt,!0);else if(an==="MultiPolygon")for(const Br of Qs){const sa=[];As(Br,sa,pt,jt,Mt,!0),sa.length&&ma.push(sa)}if(ma.length){if(Is.lineMetrics&&an==="LineString"){for(const Br of ma)js.push(Ge(Kt.id,an,Br,Kt.tags));continue}an!=="LineString"&&an!=="MultiLineString"||(ma.length===1?(an="LineString",ma=ma[0]):an="MultiLineString"),an!=="Point"&&an!=="MultiPoint"||(an=ma.length===3?"Point":"MultiPoint"),js.push(Ge(Kt.id,an,ma,Kt.tags))}}return js.length?js:null}function Ts(Wt,rt,pt,jt,Mt){for(let es=0;es=pt&&ps<=jt&&jn(rt,Wt[es],Wt[es+1],Wt[es+2])}}function vt(Wt,rt,pt,jt,Mt,es,ps){let Is=$s(Wt);const js=Mt===0?ar:Dn;let Kt,Qs,an=Wt.start;for(let sa=0;sapt&&(Qs=js(Is,Rr,ra,Gi,rl,pt),ps&&(Is.start=an+Kt*Qs)):Ii>jt?Ta=pt&&(Qs=js(Is,Rr,ra,Gi,rl,pt),eo=!0),Ta>jt&&Ii<=jt&&(Qs=js(Is,Rr,ra,Gi,rl,jt),eo=!0),!es&&eo&&(ps&&(Is.end=an+Kt*Qs),rt.push(Is),Is=$s(Wt)),ps&&(an+=Kt)}let er=Wt.length-3;const Xr=Wt[er],ma=Wt[er+1],Br=Mt===0?Xr:ma;Br>=pt&&Br<=jt&&jn(Is,Xr,ma,Wt[er+2]),er=Is.length-3,es&&er>=3&&(Is[er]!==Is[0]||Is[er+1]!==Is[1])&&jn(Is,Is[0],Is[1],Is[2]),Is.length&&rt.push(Is)}function $s(Wt){const rt=[];return rt.size=Wt.size,rt.start=Wt.start,rt.end=Wt.end,rt}function As(Wt,rt,pt,jt,Mt,es){for(const ps of Wt)vt(ps,rt,pt,jt,Mt,es,!1)}function jn(Wt,rt,pt,jt){Wt.push(rt,pt,jt)}function ar(Wt,rt,pt,jt,Mt,es){const ps=(es-rt)/(jt-rt);return jn(Wt,es,pt+(Mt-pt)*ps,1),ps}function Dn(Wt,rt,pt,jt,Mt,es){const ps=(es-pt)/(Mt-pt);return jn(Wt,rt+(jt-rt)*ps,es,1),ps}function Ur(Wt,rt){const pt=[];for(let jt=0;jt0&&rt.size<(Mt?ps:jt))return void(pt.numPoints+=rt.length/3);const Is=[];for(let js=0;jsps)&&(pt.numSimplified++,Is.push(rt[js],rt[js+1])),pt.numPoints++;Mt&&function(js,Kt){let Qs=0;for(let an=0,er=js.length,Xr=er-2;an0===Kt)for(let an=0,er=js.length;an24)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 Mt=function(es,ps){const Is=[];if(es.type==="FeatureCollection")for(let js=0;js1&&console.time("creation"),Xr=this.tiles[er]=Cn(rt,pt,jt,Mt,Kt),this.tileCoords.push({z:pt,x:jt,y:Mt}),Qs)){Qs>1&&(console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",pt,jt,Mt,Xr.numFeatures,Xr.numPoints,Xr.numSimplified),console.timeEnd("creation"));const eo=`z${pt}`;this.stats[eo]=(this.stats[eo]||0)+1,this.total++}if(Xr.source=rt,es==null){if(pt===Kt.indexMaxZoom||Xr.numPoints<=Kt.indexMaxPoints)continue}else{if(pt===Kt.maxZoom||pt===es)continue;if(es!=null){const eo=es-pt;if(jt!==ps>>eo||Mt!==Is>>eo)continue}}if(Xr.source=null,rt.length===0)continue;Qs>1&&console.time("clipping");const ma=.5*Kt.buffer/Kt.extent,Br=.5-ma,sa=.5+ma,Rr=1+ma;let ra=null,Si=null,Gi=null,rl=null,Ii=wt(rt,an,jt-ma,jt+sa,0,Xr.minX,Xr.maxX,Kt),Ta=wt(rt,an,jt+Br,jt+Rr,0,Xr.minX,Xr.maxX,Kt);rt=null,Ii&&(ra=wt(Ii,an,Mt-ma,Mt+sa,1,Xr.minY,Xr.maxY,Kt),Si=wt(Ii,an,Mt+Br,Mt+Rr,1,Xr.minY,Xr.maxY,Kt),Ii=null),Ta&&(Gi=wt(Ta,an,Mt-ma,Mt+sa,1,Xr.minY,Xr.maxY,Kt),rl=wt(Ta,an,Mt+Br,Mt+Rr,1,Xr.minY,Xr.maxY,Kt),Ta=null),Qs>1&&console.timeEnd("clipping"),js.push(ra||[],pt+1,2*jt,2*Mt),js.push(Si||[],pt+1,2*jt,2*Mt+1),js.push(Gi||[],pt+1,2*jt+1,2*Mt),js.push(rl||[],pt+1,2*jt+1,2*Mt+1)}}getTile(rt,pt,jt){rt=+rt,pt=+pt,jt=+jt;const Mt=this.options,{extent:es,debug:ps}=Mt;if(rt<0||rt>24)return null;const Is=1<1&&console.log("drilling down to z%d-%d-%d",rt,pt,jt);let Kt,Qs=rt,an=pt,er=jt;for(;!Kt&&Qs>0;)Qs--,an>>=1,er>>=1,Kt=this.tiles[Js(Qs,an,er)];return Kt&&Kt.source?(ps>1&&(console.log("found parent tile z%d-%d-%d",Qs,an,er),console.time("drilling down")),this.splitTile(Kt.source,Qs,an,er,rt,pt,jt),ps>1&&console.timeEnd("drilling down"),this.tiles[js]?hn(this.tiles[js],es):null):null}}function Js(Wt,rt,pt){return 32*((1<Kt.tags&&"3d_elevation_id"in Kt.tags&&"source"in Kt.tags&&Kt.tags.source==="elevation",es=jt.features.filter(Kt=>Mt(Kt));let ps={_geojsonTileLayer:jt.features};es.length>0&&(ps={_geojsonTileLayer:jt.features.filter(Kt=>!Mt(Kt)),hd_road_elevation:es});const Is=new Y(ps),js=function(Kt){const Qs=new c.a$;for(const an of Object.keys(Kt))Qs.writeMessage(3,pe,{name:an,features:Kt[an]});return Qs.finish()}(ps).buffer;rt(null,{vectorTile:Is,rawData:js})}class ks extends I{constructor(rt){super(rt),this.loadVectorData=Fa,this._dynamicIndex=new ne}loadData(rt,pt){const jt=rt&&rt.request,Mt=jt&&jt.collectResourceTiming;this._geoJSONIndex=null,this.loadGeoJSON(rt,(es,ps)=>{if(es||!ps)return pt(es);if(typeof ps!="object")return pt(new Error(`Input data given to '${rt.source}' is not a valid GeoJSON object.`));{try{if(rt.filter){const js=c.X(rt.filter,{type:"boolean","property-type":"data-driven",overridable:!1,transition:!1});if(js.result==="error")throw new Error(js.value.map(Kt=>`${Kt.key}: ${Kt.message}`).join(", "));ps.features=ps.features.filter(Kt=>js.value.evaluate({zoom:0},Kt))}rt.dynamic?(ps.type==="Feature"&&(ps={type:"FeatureCollection",features:[ps]}),rt.append||(this._dynamicIndex.clear(),this.loaded={}),this._dynamicIndex.load(ps.features,this.loaded),rt.cluster&&(ps.features=this._dynamicIndex.getFeatures())):this.loaded={},this._geoJSONIndex=rt.cluster?new Ye(function({superclusterOptions:js,clusterProperties:Kt}){if(!Kt||!js)return js;const Qs={},an={},er={accumulated:null,zoom:0},Xr={properties:null},ma=Object.keys(Kt);for(const Br of ma){const[sa,Rr]=Kt[Br],ra=c.X(Rr),Si=c.X(typeof sa=="string"?[sa,["accumulated"],["get",Br]]:sa);Qs[Br]=ra.value,an[Br]=Si.value}return js.map=Br=>{Xr.properties=Br;const sa={};for(const Rr of ma)sa[Rr]=Qs[Rr].evaluate(er,Xr);return sa},js.reduce=(Br,sa)=>{Xr.properties=sa;for(const Rr of ma)er.accumulated=Br[Rr],Br[Rr]=an[Rr].evaluate(er,Xr)},js}(rt)).load(ps.features):rt.dynamic?this._dynamicIndex:function(js,Kt){return new Wn(js,Kt)}(ps,rt.geojsonVtOptions)}catch(js){return pt(js)}const Is={};if(Mt){const js=d(jt);js&&(Is.resourceTiming={},Is.resourceTiming[rt.source]=JSON.parse(JSON.stringify(js)))}pt(null,Is)}})}reloadTile(rt,pt){const jt=this.loaded;return jt&&jt[rt.uid]?rt.partial?pt(null,void 0):super.reloadTile(rt,pt):this.loadTile(rt,pt)}loadGeoJSON(rt,pt){if(rt.request)c.m(rt.request,pt);else{if(typeof rt.data!="string")return pt(new Error(`Input data given to '${rt.source}' is not a valid GeoJSON object.`));setTimeout(()=>{try{return pt(null,JSON.parse(rt.data))}catch{return pt(new Error(`Input data given to '${rt.source}' is not a valid GeoJSON object.`))}},0)}}getClusterExpansionZoom(rt,pt){try{pt(null,this._geoJSONIndex.getClusterExpansionZoom(rt.clusterId))}catch(jt){pt(jt)}}getClusterChildren(rt,pt){try{pt(null,this._geoJSONIndex.getChildren(rt.clusterId))}catch(jt){pt(jt)}}getClusterLeaves(rt,pt){try{pt(null,this._geoJSONIndex.getLeaves(rt.clusterId,rt.limit,rt.offset))}catch(jt){pt(jt)}}}class Gs{constructor(rt,pt,jt){this.tileID=new c.aR(rt.tileID.overscaledZ,rt.tileID.wrap,rt.tileID.canonical.z,rt.tileID.canonical.x,rt.tileID.canonical.y),this.tileZoom=rt.tileZoom,this.uid=rt.uid,this.zoom=rt.zoom,this.canonical=rt.tileID.canonical,this.pixelRatio=rt.pixelRatio,this.tileSize=rt.tileSize,this.source=rt.source,this.overscaling=this.tileID.overscaleFactor(),this.projection=rt.projection,this.brightness=pt,this.worldview=jt}parse(rt,pt,jt,Mt){this.status="parsing";const es=new c.aR(jt.tileID.overscaledZ,jt.tileID.wrap,jt.tileID.canonical.z,jt.tileID.canonical.x,jt.tileID.canonical.y),ps=[],Is=pt.familiesBySource[jt.source],js=new c.ff(es,jt.promoteId);js.bucketLayerIDs=[],js.is3DTile=!0,c.fB(rt).then(Kt=>{const Qs=Kt.json.extensionsUsed&&Kt.json.extensionsUsed.includes("MAPBOX_mesh_features")||Kt.json.asset.extras&&Kt.json.asset.extras.MAPBOX_mesh_features,an=Kt.json.extensionsUsed&&Kt.json.extensionsUsed.includes("EXT_meshopt_compression"),er=new c.ae(this.zoom,{brightness:this.brightness,worldview:this.worldview});for(const Xr in Is)for(const ma of Is[Xr]){const Br=ma[0];js.bucketLayerIDs.push(ma.map(ra=>c.F(ra.id,ra.scope))),Br.recalculate(er,[]);const sa=c.fC(Kt,1/c.cS(jt.tileID.canonical)),Rr=new c.fD(ma,sa,es,Qs,an,this.brightness,js,this.worldview);Qs||(Rr.needsUpload=!0),ps.push(Rr),Rr.evaluate(Br)}this.status="done",Mt(null,{buckets:ps,featureIndex:js,collisionBoxArray:null,glyphAtlasImage:null,lineAtlas:null,imageAtlas:null,brightness:null})}).catch(Kt=>Mt(new Error(Kt.message)))}}class Ws{constructor({actor:rt,layerIndex:pt,availableImages:jt,availableModels:Mt,brightness:es,worldview:ps}){this.actor=rt,this.layerIndex=pt,this.availableImages=jt,this.availableModels=Mt,this.brightness=es,this.loading={},this.loaded={},this.worldview=ps}loadTile(rt,pt){const jt=rt.uid,Mt=this.loading[jt]=new Gs(rt,this.brightness,this.worldview);c.b1(rt.request,(es,ps)=>{const Is=!this.loading[jt];return delete this.loading[jt],Is||es?(Mt.status="done",Is||(this.loaded[jt]=Mt),pt(es)):ps&&ps.byteLength!==0?void Mt.parse(ps,this.layerIndex,rt,(js,Kt)=>{Mt.status="done",this.loaded=this.loaded||{},this.loaded[jt]=Mt,js||!Kt?pt(js):pt(null,Kt)}):(Mt.status="done",this.loaded[jt]=Mt,pt())})}reloadTile(rt,pt){const jt=this.loaded,Mt=rt.uid;if(jt&&jt[Mt]){const es=jt[Mt];es.projection=rt.projection,es.brightness=rt.brightness;const ps=(Is,js)=>{es.reloadCallback&&(delete es.reloadCallback,this.loadTile(rt,pt)),pt(Is,js)};es.status==="parsing"?es.reloadCallback=ps:es.status==="done"&&this.loadTile(rt,pt)}}abortTile(rt,pt){const jt=rt.uid;this.loading[jt]&&delete this.loading[jt],pt()}removeTile(rt,pt){const jt=this.loaded,Mt=rt.uid;jt&&jt[Mt]&&delete jt[Mt],pt()}}const Ys=new Map,Bn=new Map;class or{constructor(rt){this.self=rt,this.actor=new c.A(rt,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:ks,"raster-dem":D,"raster-array":V,"batched-model":Ws},this.workerSources={},this.self.registerWorkerSource=(pt,jt)=>{if(this.workerSourceTypes[pt])throw new Error(`Worker source with name "${pt}" already registered.`);this.workerSourceTypes[pt]=jt},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 jt of this.rtlPluginParsingListeners)jt(null,!0);this.rtlPluginParsingListeners=[]}}clearCaches(rt,pt,jt){delete this.layerIndexes[rt],delete this.availableImages[rt],delete this.availableModels[rt],delete this.workerSources[rt],jt()}checkIfReady(rt,pt,jt){jt()}setReferrer(rt,pt){this.referrer=pt}spriteLoaded(rt,pt){this.isSpriteLoaded[rt]||(this.isSpriteLoaded[rt]={});const{scope:jt,isLoaded:Mt}=pt;if(this.isSpriteLoaded[rt][jt]=Mt,this.workerSources[rt]&&this.workerSources[rt][jt])for(const es in this.workerSources[rt][jt]){const ps=this.workerSources[rt][jt][es];for(const Is in ps){const js=ps[Is];js instanceof I&&(js.isSpriteLoaded=Mt,js.fire(new c.C("isSpriteLoaded")))}}}setImages(rt,pt,jt){this.availableImages[rt]||(this.availableImages[rt]={});const{scope:Mt,images:es}=pt;if(this.availableImages[rt][Mt]=es,this.workerSources[rt]&&this.workerSources[rt][Mt]){for(const ps in this.workerSources[rt][Mt]){const Is=this.workerSources[rt][Mt][ps];for(const js in Is)Is[js].availableImages=es}jt()}else jt()}setModels(rt,{scope:pt,models:jt},Mt){if(this.availableModels[rt]||(this.availableModels[rt]={}),this.availableModels[rt][pt]=jt,this.workerSources[rt]&&this.workerSources[rt][pt]){for(const es in this.workerSources[rt][pt]){const ps=this.workerSources[rt][pt][es];for(const Is in ps)ps[Is].availableModels=jt}Mt()}else Mt()}setProjection(rt,pt){this.projections[rt]=c.c0(pt)}setBrightness(rt,pt,jt){this.brightness=pt,jt()}setContextParams(rt,pt,jt){this.maxUniformBufferBindings=pt.maxBindingPoints,this.maxUniformBlockSizeDwords=pt.maxUniformBlockSizeDwords,this.disableSymbolUBO=pt.disableSymbolUBO,jt()}setWorldview(rt,pt,jt){this.worldview=pt,jt()}setLayers(rt,pt,jt){this.getLayerIndex(rt,pt.scope).replace(pt.layers,pt.options),jt()}updateLayers(rt,pt,jt){this.getLayerIndex(rt,pt.scope).update(pt.layers,pt.removedIds,pt.options),jt()}loadTile(rt,pt,jt){pt.projection=this.projections[rt]||this.defaultProjection,this.getWorkerSource(rt,pt).loadTile(pt,jt)}decodeRasterArray(rt,pt,jt){this.getWorkerSource(rt,pt).decodeRasterArray(pt,jt)}reloadTile(rt,pt,jt){pt.projection=this.projections[rt]||this.defaultProjection,this.getWorkerSource(rt,pt).reloadTile(pt,jt)}abortTile(rt,pt,jt){this.getWorkerSource(rt,pt).abortTile(pt,jt)}removeTile(rt,pt,jt){this.getWorkerSource(rt,pt).removeTile(pt,jt)}removeSource(rt,pt,jt){if(!(this.workerSources[rt]&&this.workerSources[rt][pt.scope]&&this.workerSources[rt][pt.scope][pt.type]&&this.workerSources[rt][pt.scope][pt.type][pt.source]))return;const Mt=this.workerSources[rt][pt.scope][pt.type][pt.source];delete this.workerSources[rt][pt.scope][pt.type][pt.source],Mt.removeSource!==void 0?Mt.removeSource(pt,jt):jt()}loadTileProvider(rt,pt,jt){(async function(Mt,es){const ps=Bn.get(Mt);if(ps)return ps;const Is=Ys.get(Mt);if(Is!==void 0)return Is;const js=import(es).then(Kt=>{const Qs=Kt.default;if(typeof Qs!="function")throw new Error(`TileProvider "${Mt}" module must default-export a class`);if(typeof Qs.prototype.loadTile!="function")throw new Error(`TileProvider "${Mt}" class must have a loadTile method`);return Bn.set(Mt,Qs),Qs}).finally(()=>{Ys.delete(Mt)});return Ys.set(Mt,js),js})(pt.name,pt.url).then(Mt=>{const es=new Mt(pt.options);return this.getWorkerSource(rt,{type:pt.type,source:pt.source,scope:pt.scope},es),es.load&&pt.request?es.load({request:pt.request}):null}).then(Mt=>jt(null,Mt)).catch(Mt=>jt(Mt instanceof Error?Mt:new Error(typeof Mt=="string"?Mt:"Unknown error")))}loadWorkerSource(rt,pt,jt){try{this.self.importScripts(pt.url),jt()}catch(Mt){jt(Mt)}}syncRTLPluginState(rt,pt,jt){if(c.fF.isParsed())jt(null,!0);else if(c.fF.isParsing())this.rtlPluginParsingListeners.push(jt);else try{c.fF.setState(pt);const Mt=c.fF.getPluginURL();!c.fF.isLoaded()||c.fF.isParsed()||c.fF.isParsing()||Mt==null||(c.fF.setState({pluginStatus:c.fG.parsing,pluginURL:c.fF.getPluginURL()}),this.self.importScripts(Mt),c.fF.isParsed()?jt(null,!0):this.rtlPluginParsingListeners.push(jt))}catch(Mt){jt(Mt)}}setConfig(rt,pt){Object.assign(c.g,pt)}getAvailableImages(rt,pt){this.availableImages[rt]||(this.availableImages[rt]={});let jt=this.availableImages[rt][pt];return jt||(jt=[]),jt}getAvailableModels(rt,pt){this.availableModels[rt]||(this.availableModels[rt]={});let jt=this.availableModels[rt][pt];return jt||(jt={}),jt}getLayerIndex(rt,pt){this.layerIndexes[rt]||(this.layerIndexes[rt]={});let jt=this.layerIndexes[rt][pt];return jt||(jt=this.layerIndexes[rt][pt]=new p,jt.scope=pt),jt}getWorkerSource(rt,pt,jt){const{type:Mt,source:es,scope:ps}=pt,Is=this.workerSources;if(Is[rt]||(Is[rt]={}),Is[rt][ps]||(Is[rt][ps]={}),Is[rt][ps][Mt]||(Is[rt][ps][Mt]={}),this.isSpriteLoaded[rt]||(this.isSpriteLoaded[rt]={}),!Is[rt][ps][Mt][es]){const js={send:(Qs,an,er,Xr,ma,Br)=>this.actor.send(Qs,an,er,rt,ma,Br),scheduler:this.actor.scheduler},Kt=this.workerSourceTypes[Mt];if(!Kt)throw new Error(`Unknown worker source type "${Mt}".`);Is[rt][ps][Mt][es]=new Kt({actor:js,layerIndex:this.getLayerIndex(rt,ps),availableImages:this.getAvailableImages(rt,ps),availableModels:this.getAvailableModels(rt,ps),isSpriteLoaded:this.isSpriteLoaded[rt][ps],tileProvider:jt,brightness:this.brightness,worldview:this.worldview,maxUniformBufferBindings:this.maxUniformBufferBindings,maxUniformBlockSizeDwords:this.maxUniformBlockSizeDwords,disableSymbolUBO:this.disableSymbolUBO})}return Is[rt][ps][Mt][es]}rasterizeImagesWorker(rt,pt,jt){const Mt=new Map;for(const[es,{image:ps,imageVariant:Is}]of pt.tasks.entries()){const js=this.imageRasterizer.rasterize(Is,ps,pt.scope,rt);Mt.set(es,js)}jt(void 0,Mt)}removeRasterizedImages(rt,pt,jt){this.imageRasterizer.removeImagesFromCacheByIds(pt.imageIds,pt.scope,rt),jt()}enforceCacheSizeLimit(rt,pt){c.fH(pt)}getWorkerPerformanceMetrics(rt,pt,jt){jt(void 0,void 0)}}return c.fE(self)&&(self.worker=new or(self)),or}),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,N,T){performance.measure(R,N,T)}};function h(R){const N=R.name.split("?")[0];return o.a(N)&&N.includes("mapbox-gl.js")?"javascript":o.a(N)&&N.includes("mapbox-gl.css")?"css":o.b(N)?"fontRange":o.c(N)?"sprite":o.i(N)?"style":o.d(N)?"tilejson":"other"}var m,p={},f=function(){if(m)return p;function R(z){return!N(z)}function N(z){return typeof window>"u"||typeof document>"u"?"not a browser":function(){if(!("Worker"in window&&"Blob"in window&&"URL"in window))return!1;var Q,ee,ue=new Blob([""],{type:"text/javascript"}),_e=URL.createObjectURL(ue);try{ee=new Worker(_e),Q=!0}catch{Q=!1}return ee&&ee.terminate(),URL.revokeObjectURL(_e),Q}()?function(){var Q=document.createElement("canvas");Q.width=Q.height=1;var ee=Q.getContext("2d");if(!ee)return!1;var ue=ee.getImageData(0,0,1,1);return ue&&ue.width===Q.width}()?(T[W=z&&z.failIfMajorPerformanceCaveat]===void 0&&(T[W]=function(Q){var ee,ue=function(_e){var Ee=document.createElement("canvas"),Ie=Object.create(R.webGLContextAttributes);return Ie.failIfMajorPerformanceCaveat=_e,Ee.getContext("webgl2",Ie)}(Q);if(!ue)return!1;try{ee=ue.createShader(ue.VERTEX_SHADER)}catch{return!1}return!(!ee||ue.isContextLost())&&(ue.shaderSource(ee,"void main() {}"),ue.compileShader(ee),ue.getShaderParameter(ee,ue.COMPILE_STATUS)===!0)}(W)),T[W]?document.documentMode?"insufficient ECMAScript 6 support":void 0:"insufficient WebGL2 support"):"insufficient Canvas/getImageData support":"insufficient worker support";var W}m=1,p.supported=R,p.notSupportedReason=N;var T={};return R.webGLContextAttributes={antialias:!1,alpha:!0,stencil:!0,depth:!0},p}();function y(R,N,T){const z=document.createElement(R);return N!=null&&(z.className=N),T&&T.appendChild(z),z}function v(R,N,T){const z=document.createElementNS("http://www.w3.org/2000/svg",R);for(const W of Object.keys(N))z.setAttributeNS(null,W,String(N[W]));return T&&T.appendChild(z),z}const g=typeof document<"u"?document.documentElement&&document.documentElement.style:null,b=g&&g.userSelect!==void 0?"userSelect":"WebkitUserSelect";let j;function S(){g&&b&&(j=g[b],g[b]="none")}function C(){g&&b&&(g[b]=j)}function E(R){R.preventDefault(),R.stopPropagation(),window.removeEventListener("click",E,!0)}function P(){window.addEventListener("click",E,!0),window.setTimeout(()=>{window.removeEventListener("click",E,!0)},0)}function M(R,N){const T=R.getBoundingClientRect();return O(R,T,N)}function I(R,N){const T=R.getBoundingClientRect(),z=[];for(let W=0;Wthis._skuTokenExpiresAt}transformRequest(N,T){return this._transformRequestFn&&this._transformRequestFn(N,T)||{url:N}}normalizeStyleURL(N,T){if(!o.e(N))return N;const z=Y(N);return z.params.push(`sdk=js-${c}`),z.path=`/styles/v1${z.path}`,this._makeAPIURL(z,this._customAccessToken||T)}normalizeGlyphsURL(N,T){if(!o.e(N))return N;const z=Y(N);return z.path=`/fonts/v1${z.path}`,this._makeAPIURL(z,this._customAccessToken||T)}normalizeModelURL(N,T){if(!o.e(N))return N;const z=Y(N);return z.path=`/models/v1${z.path}`,this._makeAPIURL(z,this._customAccessToken||T)}normalizeSourceURL(N,T,z,W){if(!o.e(N))return N;const Q=Y(N);return Q.path=`/v4/${Q.authority}.json`,Q.params.push("secure"),z&&Q.params.push(`language=${z}`),W&&Q.params.push(`worldview=${W}`),this._makeAPIURL(Q,this._customAccessToken||T)}normalizeIconsetURL(N,T){const z=Y(N);return o.e(N)?(z.path=`/styles/v1${z.path}/iconset.pbf`,this._makeAPIURL(z,this._customAccessToken||T)):Z(z)}normalizeSpriteURL(N,T,z,W){const Q=Y(N);return o.e(N)?(Q.path=`/styles/v1${Q.path}/sprite${T}${z}`,this._makeAPIURL(Q,this._customAccessToken||W)):(Q.path+=`${T}${z}`,Z(Q))}normalizeTileURL(N,T,z){if(this._isSkuTokenExpired()&&this._createSkuToken(),N&&!o.e(N))return N;const W=Y(N);W.path=W.path.replace(/(\.(png|jpg)\d*)(?=$)/,`${T||z&&W.authority!=="raster"&&z===512?"@2x":""}${o.k.supported?".webp":"$1"}`),W.authority==="raster"?W.path=`/${o.g.RASTER_URL_PREFIX}${W.path}`:W.authority==="rasterarrays"?W.path=`/${o.g.RASTERARRAYS_URL_PREFIX}${W.path}`:W.authority==="3dtiles"?W.path=`/${o.g.TILES3D_URL_PREFIX}${W.path}`:(W.path=W.path.replace(/^.+\/v4\//,"/"),W.path=`/${o.g.TILE_URL_VERSION}${W.path}`);const Q=this._customAccessToken||function(ee){for(const ue of ee){const _e=ue.match(/^access_token=(.*)$/);if(_e)return _e[1]}return null}(W.params)||o.g.ACCESS_TOKEN;return o.g.REQUIRE_ACCESS_TOKEN&&Q&&this._skuToken&&W.params.push(`sku=${this._skuToken}`),this._makeAPIURL(W,Q)}canonicalizeTileURL(N,T){const z=Y(N);if(!z.path.match(/^(\/v4\/|\/(raster|rasterarrays)\/v1\/)/)||!z.path.match(/\.[\w]+$/))return N;let W="mapbox://";z.path.match(/^\/raster\/v1\//)?W+=`raster/${z.path.replace(`/${o.g.RASTER_URL_PREFIX}/`,"")}`:z.path.match(/^\/rasterarrays\/v1\//)?W+=`rasterarrays/${z.path.replace(`/${o.g.RASTERARRAYS_URL_PREFIX}/`,"")}`:W+=`tiles/${z.path.replace(`/${o.g.TILE_URL_VERSION}/`,"")}`;let Q=z.params;return T&&(Q=Q.filter(ee=>!ee.match(/^access_token=/))),Q.length&&(W+=`?${Q.join("&")}`),W}canonicalizeTileset(N,T){const z=!!T&&o.e(T),W=[];for(const Q of N.tiles||[])o.f(Q)?W.push(this.canonicalizeTileURL(Q,z)):W.push(Q);return W}_makeAPIURL(N,T){const z="See https://docs.mapbox.com/api/overview/#access-tokens-and-token-scopes",W=Y(o.g.API_URL);if(N.protocol=W.protocol,N.authority=W.authority,N.protocol==="http"){const Q=N.params.indexOf("secure");Q>=0&&N.params.splice(Q,1)}if(W.path!=="/"&&(N.path=`${W.path}${N.path}`),!o.g.REQUIRE_ACCESS_TOKEN)return Z(N);if(T=T||o.g.ACCESS_TOKEN,!this._silenceAuthErrors){if(!T)throw new Error(`An API access token is required to use Mapbox GL. ${z}`);if(T[0]==="s")throw new Error(`Use a public access token (pk.*) with Mapbox GL, not a secret access token (sk.*). ${z}`)}return N.params=N.params.filter(Q=>Q.indexOf("access_token")===-1),N.params.push(`access_token=${T||""}`),Z(N)}}const H=/^(\w+):\/\/([^/?]*)(\/[^?]+)?\??(.+)?/;function Y(R){const N=R.match(H);if(!N)throw new Error("Unable to parse URL object");return{protocol:N[1],authority:N[2],path:N[3]||"/",params:N[4]?N[4].split("&"):[]}}function Z(R){const N=R.params.length?`?${R.params.join("&")}`:"";return`${R.protocol}://${R.authority}${R.path}${N}`}const ne="mapbox.eventData";function ce(R){if(!R)return null;const N=R.split(".");if(!N||N.length!==3)return null;try{return JSON.parse(o.l(N[1]))}catch{return null}}function ie(R){return!(!o.g.EVENTS_URL||!R&&!o.g.ACCESS_TOKEN)}class te{constructor(N){this.type=N,this.anonId=null,this.anonIdTimestamp=null,this.eventData={},this.queue=[],this.pendingRequest=null}getStorageKey(N){const T=ce(o.g.ACCESS_TOKEN);let z="";return z=T&&T.u?o.j(T.u):o.g.ACCESS_TOKEN||"",N?`${ne}.${N}:${z}`:`${ne}:${z}`}fetchEventData(){const N=o.s("localStorage"),T=this.getStorageKey(),z=this.getStorageKey("uuid"),W=this.getStorageKey("uuidTimestamp");if(N)try{const Q=localStorage.getItem(T);Q&&(this.eventData=JSON.parse(Q));const ee=localStorage.getItem(z);ee&&(this.anonId=ee);const ue=localStorage.getItem(W);ue&&(this.anonIdTimestamp=Number(ue));const _e=Date.now()-864e5;(!this.anonIdTimestamp||this.anonIdTimestamp<_e)&&this.refreshUUID()}catch{o.w("Unable to read from LocalStorage")}}refreshUUID(){this.anonId=o.u(),this.anonIdTimestamp=Date.now()}saveEventData(){const N=o.s("localStorage"),T=this.getStorageKey(),z=this.getStorageKey("uuid"),W=this.getStorageKey("uuidTimestamp"),Q=this.anonId,ee=this.anonIdTimestamp;if(N&&Q)try{localStorage.setItem(z,Q),Object.keys(this.eventData).length>=1&&localStorage.setItem(T,JSON.stringify(this.eventData)),ee&&localStorage.setItem(W,ee.toString())}catch{o.w("Unable to write to LocalStorage")}}processRequests(N){}postEvent(N,T,z,W){if(!o.g.EVENTS_URL)return;const Q=Y(o.g.EVENTS_URL);Q.params.push(`access_token=${W||o.g.ACCESS_TOKEN||""}`);const ee={event:this.type,created:new Date(N).toISOString()},ue=T?Object.assign(ee,T):ee,_e={url:Z(Q),headers:{"Content-Type":"text/plain"},body:JSON.stringify([ue])};this.pendingRequest=o.p(_e,Ee=>{this.pendingRequest=null,z(Ee),this.saveEventData(),this.processRequests(W)})}queueRequest(N,T){this.queue.push(N),this.processRequests(T)}}class ae extends te{constructor(N){super("metrics"),N&&(this.data=N)}postMetricsEvent(N){if(!ie(N))return;this.anonId||this.fetchEventData(),o.v(this.anonId)||this.refreshUUID();const T=Object.assign({},this.data,{sessionId:this.anonId});this.queueRequest({timestamp:Date.now(),payload:T},N)}processRequests(N){if(this.pendingRequest||this.queue.length===0)return;const{timestamp:T,payload:z}=this.queue.shift();this.postEvent(T,z,()=>{},N)}}const le=new class extends te{constructor(R){super("appUserTurnstile"),this._customAccessToken=R}postTurnstileEvent(R,N){ie(N)&&Array.isArray(R)&&R.some(T=>o.e(T)||o.f(T))&&this.queueRequest(Date.now(),N)}processRequests(R){if(this.pendingRequest||this.queue.length===0)return;this.anonId&&this.anonIdTimestamp&&this.eventData.lastSuccess&&this.eventData.tokenU||this.fetchEventData();const N=ce(o.g.ACCESS_TOKEN),T=N?N.u:o.g.ACCESS_TOKEN;let z=T!==this.eventData.tokenU;o.v(this.anonId)||(this.refreshUUID(),z=!0);const W=this.queue.shift();if(this.eventData.lastSuccess){const Q=new Date(this.eventData.lastSuccess),ee=new Date(W),ue=(W-this.eventData.lastSuccess)/864e5;z=z||ue>=1||ue<-1||Q.getDate()!==ee.getDate()}else z=!0;z?this.postEvent(W,{sdkIdentifier:"mapbox-gl-js",sdkVersion:c,skuId:V,"enabled.telemetry":!1,userId:this.anonId},Q=>{Q||(this.eventData.lastSuccess=W,this.eventData.tokenU=T)},R):this.processRequests()}},be=le.postTurnstileEvent.bind(le),me=new class extends te{constructor(){super("map.load"),this.success={},this.skuToken=""}postMapLoadEvent(R,N,T,z){this.skuToken=N,this.errorCb=z,o.g.EVENTS_URL&&(T||o.g.ACCESS_TOKEN?this.queueRequest({id:R,timestamp:Date.now()},T):this.errorCb(new Error(G)))}processRequests(R){if(this.pendingRequest||this.queue.length===0)return;const{id:N,timestamp:T}=this.queue.shift();N&&this.success[N]||(this.anonId&&this.anonIdTimestamp||this.fetchEventData(),o.v(this.anonId)||this.refreshUUID(),this.postEvent(T,{sdkIdentifier:"mapbox-gl-js",sdkVersion:c,skuId:V,skuToken:this.skuToken,userId:this.anonId},z=>{z?this.errorCb(z):N&&(this.success[N]=!0)},R))}remove(){this.errorCb=null}},he=me.postMapLoadEvent.bind(me),pe=new class extends te{constructor(){super("style.load"),this.eventIdPerMapInstanceMap=new Map,this.mapInstanceIdMap=new WeakMap}getMapInstanceId(R){let N=this.mapInstanceIdMap.get(R);return N||(N=o.u(),this.mapInstanceIdMap.set(R,N)),N}getEventId(R){const N=this.eventIdPerMapInstanceMap.get(R)||0;return this.eventIdPerMapInstanceMap.set(R,N+1),N}postStyleLoadEvent(R,N){const{map:T,style:z,importedStyles:W}=N;if(!ie(R))return;const Q=this.getMapInstanceId(T),ee={mapInstanceId:Q,eventId:this.getEventId(Q),style:z};W.length&&(ee.importedStyles=W),this.queueRequest({timestamp:Date.now(),payload:ee},R)}processRequests(R){if(this.pendingRequest||this.queue.length===0)return;const{timestamp:N,payload:T}=this.queue.shift();this.postEvent(N,T,()=>{},R)}},Ce=pe.postStyleLoadEvent.bind(pe),Ae=new ae({attributes:[{name:"maps/js/layer-animations/style-with-appearances"}]}),Pe=Ae.postMetricsEvent.bind(Ae),ze=new ae({attributes:[{name:"maps/js/layer-animations/runtime-appearances"}]}),ke=ze.postMetricsEvent.bind(ze),Ze=new class extends te{constructor(){super("gljs.performance")}postPerformanceEvent(R,N){ie(R)&&this.queueRequest({timestamp:Date.now(),performanceData:N},R)}processRequests(R){if(this.pendingRequest||this.queue.length===0)return;const{timestamp:N,performanceData:T}=this.queue.shift(),z=function(W){const Q=performance.getEntriesByType("resource"),ee=performance.getEntriesByType("mark"),ue=function(tt){const ut={};if(tt){for(const lt in tt)if(lt!=="other")for(const kt of tt[lt]){const Nt=`${lt}ResolveRangeMin`,zt=`${lt}ResolveRangeMax`,Yt=`${lt}RequestCount`,Tt=`${lt}RequestCachedCount`;ut[Nt]=Math.min(ut[Nt]||1/0,kt.startTime),ut[zt]=Math.max(ut[zt]||-1/0,kt.responseEnd);const Ss=cs=>{ut[cs]===void 0&&(ut[cs]=0),++ut[cs]};kt.transferSize!==void 0&&kt.transferSize===0&&Ss(Tt),Ss(Yt)}}return ut}(function(tt,ut){const lt={};if(tt)for(const kt of tt){const Nt=ut(kt);lt[Nt]===void 0&&(lt[Nt]=[]),lt[Nt].push(kt)}return lt}(Q,h)),_e=window.devicePixelRatio,Ee=navigator.connection||navigator.mozConnection||navigator.webkitConnection,Ie=Ee?Ee.effectiveType:void 0,Je={counters:[],metadata:[],attributes:[]},Ke=(tt,ut,lt)=>{lt!=null&&tt.push({name:ut,value:lt.toString()})};for(const tt in ue)Ke(Je.counters,tt,ue[tt]);if(W.interactionRange[0]!==1/0&&W.interactionRange[1]!==-1/0&&(Ke(Je.counters,"interactionRangeMin",W.interactionRange[0]),Ke(Je.counters,"interactionRangeMax",W.interactionRange[1])),ee)for(const tt of Object.values(d)){const ut=ee.find(lt=>lt.name===tt);ut&&Ke(Je.counters,tt,ut.startTime)}return Ke(Je.counters,"visibilityHidden",W.visibilityHidden),Ke(Je.attributes,"style",function(tt){if(tt)for(const ut of tt){const lt=ut.name.split("?")[0];if(o.i(lt)){const kt=lt.split("/").slice(-2);if(kt.length===2)return`mapbox://styles/${kt[0]}/${kt[1]}`}}}(Q)),Ke(Je.attributes,"terrainEnabled",W.terrainEnabled?"true":"false"),Ke(Je.attributes,"fogEnabled",W.fogEnabled?"true":"false"),Ke(Je.attributes,"projection",W.projection),Ke(Je.attributes,"zoom",W.zoom),Ke(Je.metadata,"devicePixelRatio",_e),Ke(Je.metadata,"connectionEffectiveType",Ie),Ke(Je.metadata,"navigatorUserAgent",navigator.userAgent),Ke(Je.metadata,"screenWidth",window.screen.width),Ke(Je.metadata,"screenHeight",window.screen.height),Ke(Je.metadata,"windowWidth",window.innerWidth),Ke(Je.metadata,"windowHeight",window.innerHeight),Ke(Je.metadata,"mapWidth",W.width/_e),Ke(Je.metadata,"mapHeight",W.height/_e),Ke(Je.metadata,"webglRenderer",W.renderer),Ke(Je.metadata,"webglVendor",W.vendor),Ke(Je.metadata,"sdkVersion",c),Ke(Je.metadata,"sdkIdentifier","mapbox-gl-js"),Je}(T);for(const W of z.metadata);for(const W of z.counters);for(const W of z.attributes);this.postEvent(N,z,()=>{},R)}},Se=Ze.postPerformanceEvent.bind(Ze),Fe=new class extends te{constructor(){super("map.auth"),this.success={},this.skuToken=""}getSession(R,N,T,z){if(!o.g.API_URL||!o.g.SESSION_PATH)return;const W=Y(o.g.API_URL+o.g.SESSION_PATH);W.params.push(`sku=${N||""}`),W.params.push(`access_token=${z||o.g.ACCESS_TOKEN||""}`);const Q={url:Z(W),headers:{"Content-Type":"text/plain"}};this.pendingRequest=o.h(Q,ee=>{this.pendingRequest=null,T(ee),this.saveEventData(),this.processRequests(z)})}getSessionAPI(R,N,T,z){this.skuToken=N,this.errorCb=z,o.g.EVENTS_URL&&o.g.SESSION_PATH&&o.g.API_URL&&(T||o.g.ACCESS_TOKEN?this.queueRequest({id:R,timestamp:Date.now()},T):this.errorCb(new Error(G)))}processRequests(R){if(this.pendingRequest||this.queue.length===0)return;const{id:N,timestamp:T}=this.queue.shift();N&&this.success[N]||this.getSession(T,this.skuToken,z=>{z?this.errorCb(z):N&&(this.success[N]=!0)},R)}remove(){this.errorCb=null}},Ne=Fe.getSessionAPI.bind(Fe),Ye=new Set;function Ve(R,N){N?Ye.add(R):Ye.delete(R)}class qe{constructor(){this._changed=!1,this._updatedLayers={},this._removedLayers={},this._updatedSourceCaches={},this._updatedPaintProps=new Set,this._updatedImages={}}isDirty(){return this._changed}setDirty(){this._changed=!0}getUpdatedSourceCaches(){return this._updatedSourceCaches}updateSourceCache(N,T){this._updatedSourceCaches[N]=T,this.setDirty()}discardSourceCacheUpdate(N){delete this._updatedSourceCaches[N]}updateLayer(N){const T=N.scope;this._updatedLayers[T]=this._updatedLayers[T]||new Set,this._updatedLayers[T].add(N.id),this.setDirty()}removeLayer(N){const T=N.scope;this._removedLayers[T]=this._removedLayers[T]||{},this._updatedLayers[T]=this._updatedLayers[T]||new Set,this._removedLayers[T][N.id]=N,this._updatedLayers[T].delete(N.id),this._updatedPaintProps.delete(N.fqid),this.setDirty()}getRemovedLayer(N){return this._removedLayers[N.scope]?this._removedLayers[N.scope][N.id]:null}discardLayerRemoval(N){this._removedLayers[N.scope]&&delete this._removedLayers[N.scope][N.id]}getLayerUpdatesByScope(){const N={};for(const T in this._updatedLayers)N[T]=N[T]||{},N[T].updatedIds=Array.from(this._updatedLayers[T].values());for(const T in this._removedLayers)N[T]=N[T]||{},N[T].removedIds=Object.keys(this._removedLayers[T]);return N}getUpdatedPaintProperties(){return this._updatedPaintProps}updatePaintProperties(N){this._updatedPaintProps.add(N.fqid),this.setDirty()}getUpdatedImages(N){return this._updatedImages[N]?Array.from(this._updatedImages[N].values()):[]}updateImage(N,T){this._updatedImages[T]=this._updatedImages[T]||new Set,this._updatedImages[T].add(o.I.toString(N)),this.setDirty()}resetUpdatedImages(N){this._updatedImages[N]&&this._updatedImages[N].clear()}reset(){this._changed=!1,this._updatedLayers={},this._removedLayers={},this._updatedSourceCaches={},this._updatedPaintProps.clear(),this._updatedImages={}}}function Qe(R){const{userImage:N}=R;return!!(N&&N.render&&N.render())&&(R.data.replace(new Uint8Array(N.data.buffer)),!0)}const Ue={workerUrl:"",workerClass:null,workerParams:void 0};function Xe(R){return Ue.workerClass!=null?new Ue.workerClass:new self.Worker(Ue.workerUrl,Object.assign({name:R},Ue.workerParams))}const nt="mapboxgl_preloaded_worker_pool";class $e{constructor(N){this.active={},this.name=N}acquire(N,T=$e.workerCount){if(!this.workers)for(this.workers=[];this.workers.length{T.terminate()}),this.workers=null)}isPreloaded(){return!!this.active[nt]}numActive(){return Object.keys(this.active).length}}$e.workerCount=2;class Ge{constructor(N,T,z="Worker",W=$e.workerCount){this.workerPool=N,this.actors=[],this.currentActor=0,this.id=o.r();const Q=this.workerPool.acquire(this.id,W);for(let ee=0;ee{this.ready=!0})}broadcast(N,T,z){o.t(this.actors,(W,Q)=>{W.send(N,T,Q)},z=z||function(){})}getActor(){return this.currentActor=(this.currentActor+1)%this.actors.length,this.actors[this.currentActor]}remove(){this.actors.forEach(N=>{N.remove()}),this.actors=[],this.workerPool.release(this.id)}}let ct,xt;function qt(){return ct||(ct=new $e),ct}Ge.Actor=o.A;class Vt extends o.E{constructor(N){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=N,N!=="raster"&&o.y()&&(this.imageRasterizerDispatcher=new Ge((xt||(xt=new $e("ImageRasterizer")),xt),this,"Image Rasterizer Worker",1))}addScope(N){this.loaded.set(N,!1),this.imageProviders.set(N,new Map),this.images.set(N,new Map),this.updatedImages.set(N,new Set),this.callbackDispatchedThisFrame.set(N,new Set),this.imageVersions.set(N,new Map),this.patterns.set(N,new Map),this.atlasImage.set(N,new o.q({width:1,height:1}))}removeScope(N){this.loaded.delete(N),this.imageProviders.delete(N),this.images.delete(N),this.updatedImages.delete(N),this.callbackDispatchedThisFrame.delete(N),this.imageVersions.delete(N),this.patterns.delete(N),this.atlasImage.delete(N);const T=this.atlasTexture.get(N);T&&(T.destroy(),this.atlasTexture.delete(N))}addImageProvider(N,T){this.imageProviders.has(T)||this.imageProviders.set(T,new Map),this.imageProviders.get(T).set(N.id,N)}removeImageProvider(N,T){this.imageProviders.has(T)&&this.imageProviders.get(T).delete(N)}getPendingImageProviders(){const N=[];for(const T of this.imageProviders.values())for(const z of T.values())z.hasPendingRequests()&&N.push(z);return N}get imageRasterizer(){return this._imageRasterizer||(this._imageRasterizer=new o.z),this._imageRasterizer}isLoaded(){for(const N of this.loaded.keys())if(!this.loaded.get(N))return!1;return!0}setLoaded(N,T){if(this.loaded.get(T)!==N&&(this.loaded.set(T,N),N)){for(const{ids:z,callback:W}of this.requestors)this._notify(z,T,W);this.requestors=[]}}hasImage(N,T){return!!this.getImage(N,T)}getImage(N,T){return this.images.get(T).get(N.toString())}addImage(N,T,z){if(this._validate(N,z)){this.images.get(T).set(N.toString(),z);const W=this.imageVersions.get(T),Q=W.get(N.toString())||0;W.set(N.toString(),Q+1)}}_validate(N,T){let z=!0;return this._validateStretch(T.stretchX,T.data&&T.data.width)||(this.fire(new o.B(new Error(`Image "${N.name}" has invalid "stretchX" value`))),z=!1),this._validateStretch(T.stretchY,T.data&&T.data.height)||(this.fire(new o.B(new Error(`Image "${N.name}" has invalid "stretchY" value`))),z=!1),this._validateContent(T.content,T)||(this.fire(new o.B(new Error(`Image "${N.name}" has invalid "content" value`))),z=!1),z}_validateStretch(N,T){if(!N)return!0;let z=0;for(const W of N){if(W[0]o.I.from(T))}getImageVersions(N){const T=this.imageVersions.get(N);if(T)return T}getImages(N,T,z){const W=[],Q=[],ee=this.imageProviders.get(T);for(const Ie of N){if(!Ie.iconsetId){W.push(Ie);continue}const Je=ee.get(Ie.iconsetId);Je&&(this.getImage(Ie,T)?Q.push(Ie):Je.addPendingRequest(Ie))}if(W.length===0)return void this._notify(Q,T,z);let ue=!0;const _e=!!this.loaded.get(T),Ee=this.images.get(T);if(!_e)for(const Ie of W)Ee.has(Ie.toString())||(ue=!1);_e||ue?this._notify(W,T,z):this.requestors.push({ids:W,scope:T,callback:z})}rasterizeImages(N,T){const z=new Map,{tasks:W,scope:Q}=N;for(const[ee,ue]of W.entries()){const _e=this.getImage(ue.id,Q);_e&&z.set(ee,{image:_e,imageVariant:ue})}this._rasterizeImages(Q,z,T)}_rasterizeImages(N,T,z){if(o.y())this.imageRasterizerDispatcher.getActor().send("rasterizeImagesWorker",{tasks:T,scope:N},z);else{const W=new Map;for(const[Q,{image:ee,imageVariant:ue}]of T.entries())W.set(Q,this.imageRasterizer.rasterize(ue,ee,N,0));z(void 0,W)}}getUpdatedImages(N){return this.updatedImages.get(N)||new Set}_notify(N,T,z){const W=this.images.get(T),Q=new Map;for(const ee of N){if(!W.get(ee.toString())){if(ee.iconsetId)continue;this.fire(new o.C("styleimagemissing",{id:ee.name}))}const ue=W.get(ee.toString());if(!ue){o.w(`Image "${ee.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 _e={data:ue.usvg?null:ue.data.clone(),pixelRatio:ue.pixelRatio,sdf:ue.sdf,usvg:ue.usvg,stretchX:ue.stretchX,stretchY:ue.stretchY,content:ue.content,hasRenderCallback:!!(ue.userImage&&ue.userImage.render)};ue.usvg&&Object.assign(_e,{width:ue.icon.usvg_tree.width,height:ue.icon.usvg_tree.height}),Q.set(o.I.toString(ee),_e)}z(null,{images:Q,versions:this.getImageVersions(T)})}getPixelSize(N){const{width:T,height:z}=this.atlasImage.get(N);return{width:T,height:z}}getPattern(N,T,z){const W=N.toString(),Q=this.patterns.get(T),ee=Q.get(W),ue=this.getImage(N,T);if(!ue)return null;if(ee){if(ee.position.version===ue.version)return ee.position;ee.position.version=ue.version}else{if(ue.usvg&&!ue.data){const _e=this.getPatternInFlightId(W,T);if(this.patternsInFlight.has(_e))return null;this.patternsInFlight.add(_e);const Ee=new o.D(N).scaleSelf(o.o.devicePixelRatio),Ie=new Map([[Ee.toString(),{image:ue,imageVariant:Ee}]]);return this._rasterizeImages(T,Ie,(Je,Ke)=>this.storePatternImage(Ee,T,ue,z,Ke)),null}this.storePattern(N,T,ue)}return this._updatePatternAtlas(T,z),Q.get(W).position}getPatternInFlightId(N,T){return o.F(N,T)}hasPatternsInFlight(){return this.patternsInFlight.size!==0}storePatternImage(N,T,z,W,Q){const ee=N.toString(),ue=Q?Q.get(ee):void 0;ue&&(z.data=ue,this.storePattern(N.id,T,z),this._updatePatternAtlas(T,W),this.patternsInFlight.delete(this.getPatternInFlightId(N.id.toString(),T)))}storePattern(N,T,z){const W={w:z.data.width+2*o.G,h:z.data.height+2*o.G,x:0,y:0},Q=new o.H(W,z,o.G);this.patterns.get(T).set(N.toString(),{bin:W,position:Q})}destroyAtlasTextures(){for(const N of this.atlasTexture.values())N&&N.destroy();this.atlasTexture.clear()}bind(N,T){const z=N.gl;let W=this.atlasTexture.get(T);W?this.dirty&&(W.update(this.atlasImage.get(T)),this.dirty=!1):(W=new o.T(N,this.atlasImage.get(T),z.RGBA8),this.atlasTexture.set(T,W)),W.bind(z.LINEAR,z.CLAMP_TO_EDGE)}_updatePatternAtlas(N,T){const z=this.patterns.get(N),W=Array.from(z.values()).map(({bin:Ee})=>Ee),{w:Q,h:ee}=o.J(W),ue=this.atlasImage.get(N);ue.resize({width:Q||1,height:ee||1});const _e=this.images.get(N);for(const[Ee,{bin:Ie,position:Je}]of z.entries()){let Ke=Je.padding;const tt=Ie.x+Ke,ut=Ie.y+Ke,lt=_e.get(Ee).data,kt=lt.width,Nt=lt.height;Ke=Ke>1?Ke-1:Ke,o.q.copy(lt,ue,{x:0,y:0},{x:tt,y:ut},{width:kt,height:Nt},T),o.q.copy(lt,ue,{x:0,y:Nt-Ke},{x:tt,y:ut-Ke},{width:kt,height:Ke},T),o.q.copy(lt,ue,{x:0,y:0},{x:tt,y:ut+Nt},{width:kt,height:Ke},T),o.q.copy(lt,ue,{x:kt-Ke,y:0},{x:tt-Ke,y:ut},{width:Ke,height:Nt},T),o.q.copy(lt,ue,{x:0,y:0},{x:tt+kt,y:ut},{width:Ke,height:Nt},T),o.q.copy(lt,ue,{x:kt-Ke,y:Nt-Ke},{x:tt-Ke,y:ut-Ke},{width:Ke,height:Ke},T),o.q.copy(lt,ue,{x:0,y:Nt-Ke},{x:tt+kt,y:ut-Ke},{width:Ke,height:Ke},T),o.q.copy(lt,ue,{x:0,y:0},{x:tt+kt,y:ut+Nt},{width:Ke,height:Ke},T),o.q.copy(lt,ue,{x:kt-Ke,y:0},{x:tt-Ke,y:ut+Nt},{width:Ke,height:Ke},T)}this.dirty=!0}beginFrame(){for(const N of this.images.keys())this.callbackDispatchedThisFrame.set(N,new Set)}dispatchRenderCallbacks(N,T){const z=this.images.get(T);for(const W of N){if(this.callbackDispatchedThisFrame.get(T).has(W.toString()))continue;this.callbackDispatchedThisFrame.get(T).add(W.toString());const Q=z.get(W.toString());Qe(Q)&&this.updateImage(W,T,Q)}}destroy(){this.imageRasterizerDispatcher&&this.imageRasterizerDispatcher.remove()}}function Xt(R){const N=R.value,T=R.valueSpec,z=R.style,W=R.styleSpec,Q=R.key,ee=R.arrayElementValidator||ks;if(!Array.isArray(N))return[new o.V(Q,N,`array expected, ${o.M(N)} found`)];if(T.length&&N.length!==T.length)return[new o.V(Q,N,`array length ${T.length} expected, length ${N.length} found`)];if(T["min-length"]&&N.lengthW)return[new o.V(N,T,`${T} is greater than the maximum value ${W}`)]}return[]}function Ft(R){const N=R.key,T=R.value;if(!o.K(T))return[new o.V(N,T,`object expected, ${o.M(T)} found`)];const z=R.valueSpec,W=o.L(T.type);let Q,ee,ue,_e={};const Ee=W!=="categorical"&&T.property===void 0,Ie=!Ee,Je=function(lt){const kt=lt.stops;return Array.isArray(kt)&&Array.isArray(kt[0])&&o.K(kt[0][0])}(T),Ke=Gs({key:R.key,value:R.value,valueSpec:R.styleSpec.function,style:R.style,styleSpec:R.styleSpec,objectElementValidators:{stops:function(lt){if(W==="identity")return[new o.V(lt.key,lt.value,'identity function may not have a "stops" property')];let kt=[];const Nt=lt.value;return kt=kt.concat(Xt({key:lt.key,value:Nt,valueSpec:lt.valueSpec,style:lt.style,styleSpec:lt.styleSpec,arrayElementValidator:tt})),Array.isArray(Nt)&&Nt.length===0&&kt.push(new o.V(lt.key,Nt,"array must have at least one stop")),kt},default:function(lt){return ks({key:lt.key,value:lt.value,valueSpec:z,style:lt.style,styleSpec:lt.styleSpec})}}});return W==="identity"&&Ee&&Ke.push(new o.V(R.key,R.value,'missing required property "property"')),W==="identity"||T.stops||Ke.push(new o.V(R.key,R.value,'missing required property "stops"')),W==="exponential"&&z.expression&&!o.O(z)&&Ke.push(new o.V(R.key,R.value,"exponential functions not supported")),R.styleSpec.$version>=8&&(Ie&&!o.Q(z)?Ke.push(new o.V(R.key,R.value,"property functions not supported")):Ee&&!o.S(z)&&Ke.push(new o.V(R.key,R.value,"zoom functions not supported"))),W!=="categorical"&&!Je||T.property!==void 0||Ke.push(new o.V(R.key,R.value,'"property" property is required')),Ke;function tt(lt){let kt=[];const Nt=lt.value,zt=lt.key;if(!Array.isArray(Nt))return[new o.V(zt,Nt,`array expected, ${o.M(Nt)} found`)];if(Nt.length!==2)return[new o.V(zt,Nt,`array length 2 expected, length ${Nt.length} found`)];if(Je){if(!o.K(Nt[0]))return[new o.V(zt,Nt,`object expected, ${o.M(Nt[0])} found`)];const Yt=Nt[0];if(Yt.zoom===void 0)return[new o.V(zt,Nt,"object stop key must have zoom")];if(Yt.value===void 0)return[new o.V(zt,Nt,"object stop key must have value")];const Tt=o.L(Yt.zoom);if(typeof Tt!="number")return[new o.V(zt,Yt.zoom,"stop zoom values must be numbers")];if(ue&&ue>Tt)return[new o.V(zt,Yt.zoom,"stop zoom values must appear in ascending order")];Tt!==ue&&(ue=Tt,ee=void 0,_e={}),kt=kt.concat(Gs({key:`${zt}[0]`,value:Nt[0],valueSpec:{zoom:{}},style:lt.style,styleSpec:lt.styleSpec,objectElementValidators:{zoom:fs,value:ut}}))}else kt=kt.concat(ut({key:`${zt}[0]`,value:Nt[0],style:lt.style,styleSpec:lt.styleSpec},Nt));return o.U(o.W(Nt[1]))?kt.concat([new o.V(`${zt}[1]`,Nt[1],"expressions are not allowed in function stops.")]):kt.concat(ks({key:`${zt}[1]`,value:Nt[1],valueSpec:z,style:lt.style,styleSpec:lt.styleSpec}))}function ut(lt,kt){const Nt=o.M(lt.value),zt=o.L(lt.value),Yt=lt.value!==null?lt.value:kt;if(Q){if(Nt!==Q)return[new o.V(lt.key,Yt,`${Nt} stop domain type must match previous stop domain type ${Q}`)]}else Q=Nt;if(Nt!=="number"&&Nt!=="string"&&Nt!=="boolean"&&typeof zt!="number"&&typeof zt!="string"&&typeof zt!="boolean")return[new o.V(lt.key,Yt,"stop domain value must be a number, string, or boolean")];if(Nt!=="number"&&W!=="categorical"){let Tt=`number expected, ${Nt} found`;return o.Q(z)&&W===void 0&&(Tt+='\nIf you intended to use a categorical function, specify `"type": "categorical"`.'),[new o.V(lt.key,Yt,Tt)]}return W!=="categorical"||Nt!=="number"||typeof zt=="number"&&isFinite(zt)&&Math.floor(zt)===zt?W!=="categorical"&&Nt==="number"&&typeof zt=="number"&&typeof ee=="number"&&ee!==void 0&&ztnew o.V(`${R.key}${z.key}`,R.value,z.message));const T=N.value.expression||N.value._styleExpression.expression;if(R.expressionContext==="property"&&R.propertyKey==="text-font"&&!T.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.$(T))return[new o.V(R.key,R.value,'"feature-state" data expressions are not supported with layout properties.')];if(R.expressionContext==="filter")return Ts(T,R);if(R.expressionContext==="appearance")return vt(T,R);if(R.expressionContext&&R.expressionContext.indexOf("cluster")===0){if(!o.Z(T,["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._(T))return[new o.V(R.key,R.value,"Feature data expressions are not supported with initial expression part of cluster properties.")]}return[]}function Ts(R,N){const T=new Set(["zoom","feature-state","pitch","distance-from-center"]);if(N.valueSpec&&N.valueSpec.expression)for(const W of N.valueSpec.expression.parameters)T.delete(W);if(T.size===0)return[];const z=[];return R instanceof o.a0&&T.has(R.name)?[new o.V(N.key,N.value,`["${R.name}"] expression is not supported in a filter for a ${N.object.type} layer with id: ${N.object.id}`)]:(R.eachChild(W=>{z.push(...Ts(W,N))}),z)}function vt(R,N){const T=new Set;if(N.valueSpec&&N.valueSpec.expression)for(const W of N.valueSpec.expression.parameters)T.add(W);if(T.size===0)return[];const z=[];return R instanceof o.a0&&!T.has(R.name)?[new o.V(N.key,N.value,`["${R.name}"] is not an allowed parameter`)]:(R.eachChild(W=>{z.push(...vt(W,N))}),z)}function $s(R){const N=R.key,T=R.value,z=R.valueSpec,W=[];return Array.isArray(z.values)?z.values.indexOf(o.L(T))===-1&&W.push(new o.V(N,T,`expected one of [${z.values.join(", ")}], ${JSON.stringify(T)} found`)):Object.keys(z.values).indexOf(o.L(T))===-1&&W.push(new o.V(N,T,`expected one of [${Object.keys(z.values).join(", ")}], ${JSON.stringify(T)} found`)),W}function As(R){return o.a4(o.W(R.value))?wt(Object.assign({},R,{expressionContext:"filter",valueSpec:R.styleSpec[`filter_${R.layerType||"fill"}`]})):jn(R)}function jn(R){const N=R.value,T=R.key;if(!Array.isArray(N))return[new o.V(T,N,`array expected, ${o.M(N)} found`)];if(N.length<1)return[new o.V(T,N,"filter array must have at least 1 element")];const z=R.styleSpec;let W=$s({key:`${T}[0]`,value:N[0],valueSpec:z.filter_operator});const Q=()=>{N.length>=2&&(o.a2(N[1])||W.push(new o.V(`${T}[1]`,N[1],`string expected, ${o.M(N[1])} found`)));for(let ee=2;ee":case">=":N.length>=2&&o.L(N[1])==="$type"&&W.push(new o.V(T,N,`"$type" cannot be use with operator "${N[0]}"`)),N.length!==3&&W.push(new o.V(T,N,`filter array for operator "${N[0]}" must have 3 elements`)),Q();break;case"==":case"!=":N.length!==3&&W.push(new o.V(T,N,`filter array for operator "${N[0]}" must have 3 elements`)),Q();break;case"in":case"!in":Q();break;case"any":case"all":case"none":for(let ee=1;ee{Ee in T&&N.push(new o.V(z,T[Ee],`"${Ee}" is prohibited for ref layers`))}),W.layers.forEach(Ee=>{o.L(Ee.id)===ue&&(_e=Ee)}),_e?_e.ref?N.push(new o.V(z,T.ref,"ref cannot reference another ref layer")):ee=o.L(_e.type):typeof ue=="string"&&N.push(new o.V(z,T.ref,`ref layer "${ue}" not found`))}else if(ee!=="background"&&ee!=="sky"&&ee!=="slot")if(T.source)if(o.a2(T.source)){const _e=W.sources&&W.sources[T.source],Ee=_e&&o.L(_e.type);_e?Ee==="vector"&&ee==="raster"?N.push(new o.V(z,T.source,`layer "${T.id}" requires a raster source`)):Ee==="raster"&&ee!=="raster"?N.push(new o.V(z,T.source,`layer "${T.id}" requires a vector source`)):Ee!=="vector"||T["source-layer"]?Ee==="raster-dem"&&ee!=="hillshade"?N.push(new o.V(z,T.source,"raster-dem source can only be used with layer type 'hillshade'.")):Ee!=="raster-array"||["raster","raster-particle"].includes(ee)?ee==="line"&&T.paint&&(T.paint["line-gradient"]||T.paint["line-trim-offset"])&&Ee==="geojson"&&!_e.lineMetrics?N.push(new o.V(z,T,`layer "${T.id}" specifies a line-gradient, which requires the GeoJSON source to have \`lineMetrics\` enabled.`)):ee==="raster-particle"&&Ee!=="raster-array"&&N.push(new o.V(z,T.source,`layer "${T.id}" requires a 'raster-array' source.`)):N.push(new o.V(z,T.source,"raster-array source can only be used with layer type 'raster'.")):N.push(new o.V(z,T,`layer "${T.id}" must specify a "source-layer"`)):N.push(new o.V(z,T.source,`source "${T.source}" not found`))}else N.push(new o.V(`${z}.source`,T.source,'"source" must be a string'));else N.push(new o.V(z,T,'missing required property "source"'));return N=N.concat(Gs({key:z,value:T,valueSpec:Q.layer,style:R.style,styleSpec:R.styleSpec,objectElementValidators:{"*":()=>[],type:()=>ks({key:`${z}.type`,value:T.type,valueSpec:Q.layer.type,style:R.style,styleSpec:R.styleSpec,object:T,objectKey:"type"}),filter:_e=>As(Object.assign({layerType:ee},_e)),layout:_e=>Gs({layer:T,key:_e.key,value:_e.value,valueSpec:{},style:_e.style,styleSpec:_e.styleSpec,objectElementValidators:{"*":Ee=>Ur(Object.assign({layerType:ee},Ee))}}),paint:_e=>Gs({layer:T,key:_e.key,value:_e.value,valueSpec:{},style:_e.style,styleSpec:_e.styleSpec,objectElementValidators:{"*":Ee=>Dn(Object.assign({layerType:ee,layer:T},Ee))}}),appearances(_e){const Ee=Xt({key:_e.key,value:_e.value,valueSpec:_e.valueSpec,style:_e.style,styleSpec:_e.styleSpec,arrayElementValidator:Ke=>function(tt){const{key:ut,layer:lt,layerType:kt}=tt,Nt=o.L(tt.value),zt=o.L(Nt.name),Yt=o.L(Nt.condition),Tt=Gs({key:ut,value:Nt,valueSpec:tt.styleSpec.appearance,style:tt.style,styleSpec:tt.styleSpec,objectElementValidators:{condition:Ss=>function(cs){const Ns=[];return Ns.push(...wt({key:cs.key,value:cs.object.condition,valueSpec:o.a8.appearance.condition,expressionContext:"appearance"})),Ns}(Object.assign({layer:lt,layerType:kt},Ss)),properties:Ss=>function(cs){const Ns=[],{styleSpec:Zt,layer:ns,layerType:bs}=cs,Ks=Zt[`paint_${bs}`],Es=Zt[`layout_${bs}`],bn=cs.object[cs.objectKey];for(const mn in bn){const zn=mn in Ks?"paint":mn in Es?"layout":void 0;if(!zn){Ns.push(new o.V(cs.key,mn,`unknown property "${mn}" for layer type "${bs}"`));continue}const Kn=Object.assign({},cs,{key:`${cs.key}.${mn}`,object:bn,objectKey:mn,layer:ns,layerType:bs,value:bn[mn],valueSpec:zn==="paint"?Ks[mn]:Es[mn]});Ns.push(...ar(Kn,zn))}return Ns}(Object.assign({layer:lt,layerType:kt},Ss))}});return zt!=="hidden"&&Yt===void 0&&Tt.push(new o.V(tt.key,"name",'Appearance with name different than "hidden" must have a condition')),Tt}(Object.assign({layerType:ee,layer:T},Ke))}),Ie=Array.isArray(_e.value)?_e.value:[],Je=new Set;return Ie.forEach((Ke,tt)=>{const ut=o.L(Ke.name);if(ut)if(Je.has(ut)){const lt=o.L(T.id);Ee.push(new o.V(_e.key,ut,`Duplicated appearance name "${ut}" for layer "${lt}"`))}else Je.add(ut)}),Ee}}})),N}function hn({key:R,value:N}){return o.a2(N)?[]:[new o.V(R,N,`string expected, ${o.M(N)} found`)]}const dr={promoteId:function R({key:N,value:T}){if(o.a2(T))return hn({key:N,value:T});if(Array.isArray(T)){const W=[],Q=o.W(T),ee=o.X(Q);return ee.result==="error"?(ee.value.forEach(ue=>{W.push(new o.V(`${N}${ue.key}`,null,`${ue.message}`))}),W):(o.Z(ee.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"])||W.push(new o.V(`${N}`,null,"promoteId expression should be only feature dependent")),W)}if(!o.K(T))return[new o.V(N,T,`string, expression or object expected, "${o.M(T)}" found`)];const z=[];for(const W in T)z.push(...R({key:`${N}.${W}`,value:T[W]}));return z}};function Cn(R){const N=R.value,T=R.key,z=R.styleSpec,W=R.style;if(!o.K(N))return[new o.V(T,N,`object expected, ${o.M(N)} found`)];if(!("type"in N))return[new o.V(T,N,'"type" is required')];const Q=o.L(N.type);let ee=[];switch(["vector","raster","raster-dem","raster-array"].includes(Q)&&("url"in N||"tiles"in N||ee.push(new o.a5(T,N,'Either "url" or "tiles" is required.'))),Q){case"vector":case"raster":case"raster-dem":case"raster-array":return ee=ee.concat(Gs({key:T,value:N,valueSpec:z[`source_${Q.replace("-","_")}`],style:R.style,styleSpec:z,objectElementValidators:dr})),ee;case"geojson":if(ee=Gs({key:T,value:N,valueSpec:z.source_geojson,style:W,styleSpec:z,objectElementValidators:dr}),"cluster"in N&&"clusterProperties"in N){if(!o.K(N.clusterProperties))return[new o.V(`${T}.clusterProperties`,N,`object expected, ${o.M(N)} found`)];for(const ue in N.clusterProperties){const _e=N.clusterProperties[ue];if(!Array.isArray(_e))return[new o.V(`${T}.clusterProperties.${ue}`,_e,"array expected")];const[Ee,Ie]=_e,Je=typeof Ee=="string"?[Ee,["accumulated"],["get",ue]]:Ee;ee.push(...wt({key:`${T}.${ue}.map`,value:Ie,expressionContext:"cluster-map"})),ee.push(...wt({key:`${T}.${ue}.reduce`,value:Je,expressionContext:"cluster-reduce"}))}}return ee;case"video":return Gs({key:T,value:N,valueSpec:z.source_video,style:W,styleSpec:z});case"image":return Gs({key:T,value:N,valueSpec:z.source_image,style:W,styleSpec:z});case"canvas":return[new o.V(T,null,"Please use runtime APIs to add canvas sources, rather than including them in stylesheets.","source.canvas")];default:return $s({key:`${T}.type`,value:N.type,valueSpec:{values:Yn(z)}})}}function Yn(R){return R.source.reduce((N,T)=>{const z=R[T];return z.type.type==="enum"&&(N=N.concat(Object.keys(z.type.values||{}))),N},[])}function on(R){const N=R.value,T=R.styleSpec,z=T.light,W=R.style;if(N===void 0)return[];if(!o.K(N))return[new o.V("light",N,`object expected, ${o.M(N)} found`)];let Q=[];for(const ee in N){const ue=ee.match(/^(.*)-transition$/),_e=ee.match(/^(.*)-use-theme$/);Q=Q.concat(_e&&z[_e[1]]?ks({key:ee,value:N[ee],valueSpec:{type:"string"},style:W,styleSpec:T}):ue&&z[ue[1]]&&z[ue[1]].transition?ks({key:ee,value:N[ee],valueSpec:T.transition,style:W,styleSpec:T}):z[ee]?ks({key:ee,value:N[ee],valueSpec:z[ee],style:W,styleSpec:T}):[new o.V(ee,N[ee],`unknown property "${ee}"`)])}return Q}function Ir(R){const N=R.value;if(!N)return[];const T=R.key;if(!o.K(N))return[new o.V(T,N,`object expected, ${o.M(N)} found`)];let z=[];const W=R.styleSpec,Q=W["light-3d"],ee=R.style,ue=R.style.lights;for(const Ie of["type","id"])if(!(Ie in N))return z=z.concat([new o.V(T,N,`missing property "${Ie}"`)]),z;if(!o.a2(N.type))return z=z.concat([new o.V(`${T}.type`,N.type,"string expected")]),z;if(ue)for(let Ie=0;Ie[],array:Xt,boolean:function(R){const N=R.value,T=R.key;return o.a1(N)?[]:[new o.V(T,N,`boolean expected, ${o.M(N)} found`)]},number:fs,color:function({key:R,value:N}){return o.a2(N)?o.a3.parseCSSColor(N)===null?[new o.V(R,N,`color expected, "${N}" found`)]:[]:[new o.V(R,N,`color expected, ${o.M(N)} found`)]},enum:$s,filter:As,function:Ft,layer:Vs,object:Gs,source:Cn,model:o.a9,light:on,"light-3d":Ir,terrain:Wn,fog:Js,string:hn,formatted:function(R){return hn(R).length===0?[]:wt(R)},resolvedImage:function(R){return hn(R).length===0?[]:wt(R)},projection:function(R){const N=R.value,T=R.styleSpec,z=T.projection,W=R.style;if(o.K(N)){let Q=[];for(const ee in N)Q=Q.concat(ks({key:ee,value:N[ee],valueSpec:z[ee],style:W,styleSpec:T}));return Q}return o.a2(N)?[]:[new o.V("projection",N,`object or string expected, ${o.M(N)} found`)]},import:function(R){const N=R.key,{value:T,styleSpec:z}=R;if(!o.K(T))return[new o.V(N,T,"import must be an object")];const{data:W,...Q}=T;Object.defineProperty(Q,"__line__",{value:T.__line__,enumerable:!1});let ee=Gs(Object.assign({},R,{value:Q,valueSpec:z.import}));return o.L(Q.id)===""&&ee.push(new o.V(`${R.key}.id`,Q,"import id can't be an empty string")),W&&(ee=ee.concat(Ys(W,z,{key:`${R.key}.data`}))),ee},iconset:function(R){const N=R.value,T=R.key,z=R.styleSpec,W=R.style;if(!o.K(N))return[new o.V(T,N,"object expected")];if(!N.type)return[new o.V(T,N,'"type" is required')];const Q=o.L(N.type);let ee=[];if(ee=ee.concat(Gs({key:T,value:N,valueSpec:z[`iconset_${Q}`],style:W,styleSpec:z})),function(ue,_e){return!(ue!=="source"||!_e.source)}(Q,N)){const ue=W.sources&&W.sources[N.source],_e=ue&&o.L(ue.type);ue?_e!=="raster-array"&&ee.push(new o.V(T,N.source,`iconset cannot be used with a source of type ${String(_e)}, it only be used with a "raster-array" source type`)):ee.push(new o.V(T,N.source,`source "${N.source}" not found`))}return ee}};function ks(R,N=!1){const T=R.value,z=R.valueSpec,W=R.styleSpec;if(z.expression){if(o.a6(o.L(T)))return Ft(R);if(o.U(o.W(T)))return wt(R)}if(z.type&&Fa[z.type]){const Q=Fa[z.type](R);return N===!0&&Q.length>0&&Array.isArray(R.value)?wt(R):Q}return Gs(Object.assign({},R,{valueSpec:z.type?W[z.type]:z}))}function Gs(R){const N=R.key,T=R.value,z=R.valueSpec||{},W=R.objectElementValidators||{},Q=R.style,ee=R.styleSpec;if(!o.K(T))return[new o.V(N,T,`object expected, ${o.M(T)} found`)];let ue=[];for(const _e in T){const Ee=_e.split(".")[0];let Ie;W[Ee]?Ie=W[Ee]:z[Ee]?Ie=ks:W["*"]?Ie=W["*"]:z["*"]&&(Ie=ks),Ie?ue=ue.concat(Ie({key:(N&&`${N}.`)+_e,value:T[_e],valueSpec:z[Ee]||z["*"],style:Q,styleSpec:ee,object:T,objectKey:_e},T)):ue.push(new o.a5(N,T[_e],`unknown property "${_e}"`))}for(const _e in z){if(W[_e])continue;const Ee=z[_e];Ee.required&&Ee.default===void 0&&T[_e]===void 0&&ue.push(new o.V(N,T,`missing required property "${_e}"`))}return ue}function Ws({key:R,value:N}){const T=hn({key:R,value:N});if(T.length)return T;const z=N;return z.indexOf("{fontstack}")===-1&&T.push(new o.V(R,N,'"glyphs" url must include a "{fontstack}" token')),z.indexOf("{range}")===-1&&T.push(new o.V(R,N,'"glyphs" url must include a "{range}" token')),T}function Ys(R,N=o.a8,T={}){return Gs({key:T.key||"",value:R,valueSpec:Object.assign(N.$root,{"*":{type:"*"}}),styleSpec:N,style:R,objectElementValidators:{glyphs:Ws}})}function Bn(R,N=o.a8){return an(Ys(R,N))}const or=R=>an(Cn(R)),Wt=R=>an(on(R)),rt=R=>an(Ir(R)),pt=R=>an(Wn(R)),jt=R=>an(Js(R)),Mt=R=>an(function(N){const T=N.value,z=N.style,W=N.styleSpec,Q=W.snow;if(T===void 0)return[];if(!o.K(T))return[new o.V("snow",T,`object expected, ${o.M(T)} found`)];let ee=[];for(const ue in T){const _e=ue.match(/^(.*)-transition$/);ee=ee.concat(_e&&Q[_e[1]]&&Q[_e[1]].transition?ks({key:ue,value:T[ue],valueSpec:W.transition,style:z,styleSpec:W}):Q[ue]?ks({key:ue,value:T[ue],valueSpec:Q[ue],style:z,styleSpec:W}):[new o.a5(ue,T[ue],`unknown property "${ue}"`)])}return ee}(R)),es=R=>an(function(N){const T=N.value,z=N.style,W=N.styleSpec,Q=W.rain;if(T===void 0)return[];if(!o.K(T))return[new o.V("rain",T,`object expected, ${o.M(T)} found`)];let ee=[];for(const ue in T){const _e=ue.match(/^(.*)-transition$/);ee=ee.concat(_e&&Q[_e[1]]&&Q[_e[1]].transition?ks({key:ue,value:T[ue],valueSpec:W.transition,style:z,styleSpec:W}):Q[ue]?ks({key:ue,value:T[ue],valueSpec:Q[ue],style:z,styleSpec:W}):[new o.a5(ue,T[ue],`unknown property "${ue}"`)])}return ee}(R)),ps=R=>an(Vs(R)),Is=R=>an(As(R)),js=R=>an(Dn(R)),Kt=R=>an(Ur(R)),Qs=R=>an(o.a9(R));function an(R){return R.slice().sort((N,T)=>N.line&&T.line?N.line-T.line:0)}function er(R,N){let T=!1;if(N&&N.length)for(const z of N)z instanceof o.a5?o.w(z.message):(R.fire(new o.B(new Error(z.message))),T=!0);return T}const Xr=o.a8.light;let ma;class Br extends o.E{constructor(N,T="flat"){super(),this._transitionable=new o.aa(ma||(ma=new o.ab({anchor:new o.ac(Xr.anchor),position:new o.ad(Xr.position),color:new o.ac(Xr.color),intensity:new o.ac(Xr.intensity)}))),this.setLight(N,T),this._transitioning=this._transitionable.untransitioned()}getLight(){return this._transitionable.serialize()}setLight(N,T,z={}){this._validate(Wt,N,z)||(this._transitionable.setTransitionOrValue(N),this.id=T)}updateTransitions(N){this._transitioning=this._transitionable.transitioned(N,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(N){this.properties=this._transitioning.possiblyEvaluate(N)}_validate(N,T,z){return(!z||z.validate!==!1)&&er(this,N.call(Bn,Object.assign({value:T,style:{glyphs:!0,sprite:!0},styleSpec:o.a8})))}}const sa=o.a8.terrain;let Rr=class extends o.E{constructor(R,N,T,z,W){super(),this.scope=T,this._transitionable=new o.aa(new o.ab({source:new o.ac(sa.source),exaggeration:new o.ac(sa.exaggeration)}),T,z),this._transitionable.setTransitionOrValue(R,z),this._transitioning=this._transitionable.untransitioned(),this.drapeRenderMode=N,this.worldview=W}get(){return this._transitionable.serialize()}set(R,N){this._transitionable.setTransitionOrValue(R,N)}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 N=R.value.expression;if(!N)return null;let T=-1,z=-1,W=1;for(const Q of N.zoomStops)W=N.evaluate(new o.ae(Q,{worldview:this.worldview})),W>.01?(T=Q,z=-1):z=Q;return W<.01&&T>0&&z>T?[T,z]: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 ra=.05;function Si(R,N,T,z){const W=o.aj(45,65,T),[Q,ee]=Gi(R,z);let ue=1-Math.min(1,Math.exp((N-Q)/(ee-Q)*-6));return ue*=ue*ue,ue=Math.min(1,1.00747*ue),ue*W*R.alpha}function Gi(R,N){const T=.5/Math.tan(.5*N);return[R.range[0]+T,R.range[1]+T]}function rl(R,N,T,z,W){const Q=o.ah([],[N,T,z],W.mercatorFogMatrix);return Si(R,o.ai(Q),W.pitch,W._fov)}function Ii(R,N,T,z,W,Q,ee){const ue=[[T,z,0],[W,z,0],[W,Q,0],[T,Q,0]];let _e=Number.MAX_VALUE,Ee=-Number.MAX_VALUE;for(const Ie of ue){const Je=o.ah([],Ie,N),Ke=o.ai(Je);_e=Math.min(_e,Ke),Ee=Math.max(Ee,Ke)}return[Si(R,_e,ee.pitch,ee._fov),Si(R,Ee,ee.pitch,ee._fov)]}const Ta=o.a8.fog;class eo extends o.E{constructor(N,T,z,W){super();const Q=new o.ab({range:new o.ac(Ta.range),color:new o.ac(Ta.color),"color-use-theme":new o.ac({type:"string","property-type":"data-constant",default:"default"}),"high-color":new o.ac(Ta["high-color"]),"high-color-use-theme":new o.ac({type:"string","property-type":"data-constant",default:"default"}),"space-color":new o.ac(Ta["space-color"]),"space-color-use-theme":new o.ac({type:"string","property-type":"data-constant",default:"default"}),"horizon-blend":new o.ac(Ta["horizon-blend"]),"star-intensity":new o.ac(Ta["star-intensity"]),"vertical-range":new o.ac(Ta["vertical-range"])});this._transitionable=new o.aa(Q,z,new Map(W)),this.set(N,W),this._transitioning=this._transitionable.untransitioned(),this._transform=T,this.properties=new o.ak(Q),this.scope=z}get state(){const N=this._transform,T=N.projection.name==="globe",z=o.al(N.zoom),W=this.properties.get("range"),Q=[.5,3];return{range:T?[o.am(Q[0],W[0],z),o.am(Q[1],W[1],z)]:W,horizonBlend:this.properties.get("horizon-blend"),alpha:this.properties.get("color").a}}get(){return this._transitionable.serialize()}set(N,T,z={}){if(this._validate(jt,N,z))return;const W=Object.assign({},N);for(const Q of Object.keys(Ta))W[Q]===void 0&&(W[Q]=Ta[Q].default);this._options=W,this._transitionable.setTransitionOrValue(this._options,T)}getOpacity(N){if(!this._transform.projection.supportsFog)return 0;const T=this.properties&&this.properties.get("color")||1;return(this._transform.projection.name==="globe"?1:o.aj(45,65,N))*T.a}getOpacityAtLatLng(N,T){return this._transform.projection.supportsFog?function(z,W,Q){const ee=o.ag.fromLngLat(W),ue=Q.elevation?Q.elevation.getAtPointOrZero(ee):0;return rl(z,ee.x,ee.y,ue,Q)}(this.state,N,T):0}getOpacityForTile(N){if(!this._transform.projection.supportsFog)return[1,1];const T=this._transform.calculateFogTileMatrix(N.toUnwrapped());return Ii(this.state,T,0,0,o.an,o.an,this._transform)}getOpacityForBounds(N,T,z,W,Q){return this._transform.projection.supportsFog?Ii(this.state,N,T,z,W,Q,this._transform):[1,1]}getFovAdjustedRange(N){return this._transform.projection.supportsFog?Gi(this.state,N):[0,1]}isVisibleOnFrustum(N){if(!this._transform.projection.supportsFog)return!1;const T=[4,5,6,7];for(const z of T){const W=N.points[z];let Q;if(W[2]>=0)Q=W;else{const ee=N.points[z-4];Q=o.ao(ee,W,ee[2]/(ee[2]-W[2]))}if(rl(this.state,Q[0],Q[1],0,this._transform)>=ra)return!0}return!1}updateConfig(N){this._transitionable.setTransitionOrValue(this._options,new Map(N))}updateTransitions(N){this._transitioning=this._transitionable.transitioned(N,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(N){this.properties=this._transitioning.possiblyEvaluate(N)}_validate(N,T,z){return(!z||z.validate!==!1)&&er(this,N.call(Bn,Object.assign({value:T,style:{glyphs:!0,sprite:!0},styleSpec:o.a8})))}}let So,Ra,Eo,Ro=class extends o.E{constructor(R,N,T,z){super();const W=So||(So=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(W,T,new Map(z)),this.set(R,z),this._transitioning=this._transitionable.untransitioned(),this.properties=new o.ak(W),this.scope=T}get state(){const R=this.properties.get("opacity"),N=this.properties.get("color"),T=this.properties.get("direction"),z=o.ap(T[0]),W=-Math.max(o.ap(T[1]),.01),Q=[Math.cos(z)*Math.cos(W),Math.sin(z)*Math.cos(W),Math.sin(W)],ee=this.properties.get("vignette"),ue=this.properties.get("vignette-color");return ue.a=ee,{density:this.properties.get("density"),intensity:this.properties.get("intensity"),color:new o.aq(N.r,N.g,N.b,N.a*R),direction:Q,centerThinning:this.properties.get("center-thinning"),flakeSize:this.properties.get("flake-size"),vignetteColor:ue}}get(){return this._transitionable.serialize()}set(R,N,T={}){if(this._validate(Mt,R,T))return;const z=Object.assign({},R),W=o.a8.snow;for(const Q of Object.keys(W))z[Q]===void 0&&(z[Q]=W[Q].default);this._options=z,this._transitionable.setTransitionOrValue(this._options,N)}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,N,T){return(!T||T.validate!==!1)&&er(this,R.call(Bn,Object.assign({value:N,style:{glyphs:!0,sprite:!0},styleSpec:o.a8})))}},di=class extends o.E{constructor(R,N,T,z){super();const W=Ra||(Ra=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(W,T,new Map(z)),this.set(R,z),this._transitioning=this._transitionable.untransitioned(),this.properties=new o.ak(W),this.scope=T}get state(){const R=this.properties.get("opacity"),N=this.properties.get("color"),T=this.properties.get("direction"),z=o.ap(T[0]),W=-Math.max(o.ap(T[1]),.01),Q=[Math.cos(z)*Math.cos(W),Math.sin(z)*Math.cos(W),Math.sin(W)],ee=this.properties.get("vignette-color");return ee.a=this.properties.get("vignette"),{density:this.properties.get("density"),intensity:this.properties.get("intensity"),color:new o.aq(N.r,N.g,N.b,N.a*R),direction:Q,centerThinning:this.properties.get("center-thinning"),dropletSize:this.properties.get("droplet-size"),distortionStrength:this.properties.get("distortion-strength"),vignetteColor:ee}}get(){return this._transitionable.serialize()}set(R,N,T={}){if(this._validate(es,R,T))return;const z=Object.assign({},R),W=o.a8.rain;for(const Q of Object.keys(W))z[Q]===void 0&&(z[Q]=W[Q].default);this._options=z,this._transitionable.setTransitionOrValue(this._options,N)}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,N,T){return(!T||T.validate!==!1)&&er(this,R.call(Bn,Object.assign({value:N,style:{glyphs:!0,sprite:!0},styleSpec:o.a8})))}};class rr extends o.E{constructor(N,T,z,W){super(),this.scope=z,this._options=N,this.properties=new o.ak(T),this._transitionable=new o.aa(T,z,new Map(W)),this._transitionable.setTransitionOrValue(N.properties),this._transitioning=this._transitionable.untransitioned()}updateConfig(N){this._transitionable.setTransitionOrValue(this._options.properties,new Map(N))}updateTransitions(N){this._transitioning=this._transitionable.transitioned(N,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(N){this.properties=this._transitioning.possiblyEvaluate(N)}get(){return this._options.properties=this._transitionable.serialize(),this._options}set(N,T){this._options=N,this._transitionable.setTransitionOrValue(N.properties,T)}shadowsEnabled(){return!!this.properties&&this.properties.get("cast-shadows")===!0}}const oi=()=>Eo||(Eo=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 Oo;const kl=()=>Oo||(Oo=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 Jo{constructor(N,T,z){this.screenBounds=N,this.cameraPoint=z.getCameraPoint(),this._screenRaycastCache={},this._cameraRaycastCache={},this.isAboveHorizon=T,this.screenGeometry=this.bufferedScreenGeometry(0),this.screenGeometryMercator=this._bufferedScreenMercator(0,z)}static createFromScreenPoints(N,T){let z,W;if(N instanceof o.P||typeof N[0]=="number"){const Q=o.P.convert(N);z=[Q],W=T.isPointAboveHorizon(Q)}else{const Q=o.P.convert(N[0]),ee=o.P.convert(N[1]),ue=Q.add(ee)._div(2);z=[Q,ee],W=o.as(Q,ee).every(_e=>T.isPointAboveHorizon(_e))&&T.isPointAboveHorizon(ue)}return new Jo(z,W,T)}isPointQuery(){return this.screenBounds.length===1}bufferedScreenGeometry(N){return o.as(this.screenBounds[0],this.screenBounds.length===1?this.screenBounds[0]:this.screenBounds[1],N)}bufferedCameraGeometry(N){const T=this.screenBounds[0],z=this.screenBounds.length===1?this.screenBounds[0].add(new o.P(1,1)):this.screenBounds[1],W=o.as(T,z,0,!1);return this.cameraPoint.y>z.y&&(this.cameraPoint.x>T.x&&this.cameraPoint.x=z.x?W[2]=this.cameraPoint:this.cameraPoint.x<=T.x&&(W[3]=this.cameraPoint)),o.at(W,N)}bufferedCameraGeometryGlobe(N){const T=this.screenBounds[0],z=this.screenBounds.length===1?this.screenBounds[0].add(new o.P(1,1)):this.screenBounds[1],W=o.as(T,z,N),Q=this.cameraPoint.clone(),ee=+(Q.x>T.x)+ +(Q.x>z.x);switch(3*(+(Q.y>T.y)+ +(Q.y>z.y))+ee){case 0:W[0]=Q,W[4]=Q.clone();break;case 1:W.splice(1,0,Q);break;case 2:W[1]=Q;break;case 3:W.splice(4,0,Q);break;case 5:W.splice(2,0,Q);break;case 6:W[3]=Q;break;case 7:W.splice(3,0,Q);break;case 8:W[2]=Q}return W}containsTile(N,T,z,W=0){const Q=Math.max(N.queryPadding,N.evaluateQueryRenderedFeaturePadding())/T._pixelsPerMercatorPixel+1,ee=z?this._bufferedCameraMercator(Q,T):this._bufferedScreenMercator(Q,T);let ue=N.tileID.wrap+(ee.unwrapped?W:0);const _e=ee.polygon.map(kt=>o.au(N.tileTransform,kt,ue));if(!o.av(_e,0,0,o.an,o.an))return;ue=N.tileID.wrap+(this.screenGeometryMercator.unwrapped?W:0);const Ee=this.screenGeometryMercator.polygon.map(kt=>o.aw(N.tileTransform,kt,ue)),Ie=Ee.map(kt=>new o.P(kt[0],kt[1])),Je=T.getFreeCameraOptions().position||new o.ag(0,0,0),Ke=o.aw(N.tileTransform,Je,ue),tt=Ee.map(kt=>{const Nt=o.ax(kt,kt,Ke);return o.ay(Nt,Nt),new o.az(Ke,Nt)}),ut=o.aA(N,1,T.zoom)*T._pixelsPerMercatorPixel;return{queryGeometry:this,tilespaceGeometry:Ie,tilespaceRays:tt,bufferedTilespaceGeometry:_e,bufferedTilespaceBounds:(lt=o.aB(_e),lt.min.x=o.aC(lt.min.x,0,o.an),lt.min.y=o.aC(lt.min.y,0,o.an),lt.max.x=o.aC(lt.max.x,0,o.an),lt.max.y=o.aC(lt.max.y,0,o.an),lt),tile:N,tileID:N.tileID,pixelToTileUnitsFactor:ut};var lt}_bufferedScreenMercator(N,T){const z=Ku(N);if(this._screenRaycastCache[z])return this._screenRaycastCache[z];{let W;return W=T.projection.name==="globe"?this._projectAndResample(this.bufferedScreenGeometry(N),T):{polygon:this.bufferedScreenGeometry(N).map(Q=>T.pointCoordinate3D(Q)),unwrapped:!0},this._screenRaycastCache[z]=W,W}}_bufferedCameraMercator(N,T){const z=Ku(N);if(this._cameraRaycastCache[z])return this._cameraRaycastCache[z];{let W;return W=T.projection.name==="globe"?this._projectAndResample(this.bufferedCameraGeometryGlobe(N),T):{polygon:this.bufferedCameraGeometry(N).map(Q=>T.pointCoordinate3D(Q)),unwrapped:!0},this._cameraRaycastCache[z]=W,W}}_projectAndResample(N,T){const z=function(Q,ee){const ue=o.aD([],ee.pixelMatrix,ee.globeMatrix),_e=[0,-o.aF,0,1],Ee=[0,o.aF,0,1],Ie=[0,0,0,1];o.aE(_e,_e,ue),o.aE(Ee,Ee,ue),o.aE(Ie,Ie,ue);const Je=new o.P(_e[0]/_e[3],_e[1]/_e[3]),Ke=new o.P(Ee[0]/Ee[3],Ee[1]/Ee[3]),tt=o.aG(Q,Je)&&_e[3]1?Sl(Q.slice(0,kt),ee):[],Yt=ktnew o.P(vu(Ns.x),Ns.y)),Yt=Yt.map(Ns=>new o.P(vu(Ns.x),Ns.y));const Tt=[...zt];Tt.length===0&&Tt.push(Yt[Yt.length-1]);const Ss=o.am(Tt[Tt.length-1].y,(Yt.length===0?zt[0]:Yt[0]).y,Nt);let cs;return cs=tt?[new o.P(0,Ss),new o.P(0,0),new o.P(1,0),new o.P(1,Ss)]:[new o.P(1,Ss),new o.P(1,1),new o.P(0,1),new o.P(0,Ss)],Tt.push(...cs),Yt.length===0?Tt.push(zt[0]):Tt.push(...Yt),{polygon:Tt.map(Ns=>new o.ag(Ns.x,Ns.y)),unwrapped:!1}}(N,T);if(z)return z;const W=function(Q,ee){let ue=!1,_e=-1/0,Ee=0;for(let Je=0;Je_e&&(_e=Q[Je].x,Ee=Je);for(let Je=0;Je.5&&(tt.x{Je.x-=1}),{polygon:Q,unwrapped:ue}}(Sl(N,T).map(Q=>new o.P(vu(Q.x),Q.y)),T);return{polygon:W.polygon.map(Q=>new o.ag(Q.x,Q.y)),unwrapped:W.unwrapped}}}function Sl(R,N){return o.aI(R,T=>{const z=N.pointCoordinate3D(T);T.x=z.x,T.y=z.y},1/256)}function vu(R){return R<0?1+R%1:R%1}function Ku(R){return 100*R|0}function Tp(R,N,T){try{N=function(W){if(!W.variants)return W;if(!Array.isArray(W.variants))throw new Error("variants must be an array");for(const Q of W.variants){if(Q==null||typeof Q!="object"||Q.constructor!==Object)throw new Error("variant must be an object");if(!Array.isArray(Q.capabilities))throw new Error("capabilities must be an array");if(Q.capabilities.length===1&&Q.capabilities[0]==="meshopt")return Object.assign(W,Q)}return W}(N)}catch(W){return new Error("Failed to process TileJSON variants",{cause:W})}const z=o.aJ(Object.assign({},N,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&&N.tiles&&R.tiles&&(z.tiles=N.tiles),z.tiles=T.canonicalizeTileset(z,R.url),z}function Bd(R,N,T,z,W){const Q=function(ue,_e){if(ue)return W(ue);if(_e){R.url&&_e.tiles&&R.tiles&&delete R.tiles;const Ee=Tp(R,_e,N);if(Ee instanceof Error)return W(Ee);W(null,Ee)}},ee=function(ue,_e,Ee){if(!ue)return null;if(!_e&&!Ee)return ue;Ee=Ee||ue.worldview_default;const Ie=Object.values(ue.language||{});if(Ie.length===0)return null;const Je=Object.values(ue.worldview||{});if(Je.length===0)return null;const Ke=Ie.every(ut=>ut===_e),tt=Je.every(ut=>ut===Ee);return Ke&&tt?ue:_e in(ue.language_options||{})||Ee in(ue.worldview_options||{})?null:ue.language_options&&ue.worldview_options?ue:null}(R.data,T,z);return ee?o.o.frame(()=>Q(null,ee)):R.url?o.m(N.transformRequest(N.normalizeSourceURL(R.url,null,T,z),o.R.Source),Q):o.o.frame(()=>{const{data:ue,..._e}=R;Q(null,_e)})}function xm(R,N){const T=Math.pow(2,N.z),z=Math.floor(o.aH(R.getWest())*T),W=Math.floor(o.aL(R.getNorth())*T),Q=Math.ceil(o.aH(R.getEast())*T),ee=Math.ceil(o.aL(R.getSouth())*T);return N.x>=z&&N.x=W&&N.ythis.maxzoom||N.z{this._tileJSONRequest=null,this._loaded=!0,ee?(T&&console.warn(`Ensure that your requested language string is a valid BCP-47 code or list of codes. Found: ${T}`),z&&console.warn(`Requested worldview strings must be a valid ISO alpha-2 code. Found: ${z}`),this.fire(new o.B(ee))):ue&&(this._setTileJSON(ue),be(ue.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"}))),N&&N(ee)};this.provider=this._options.provider;const Q=function(ee){if("provider"in ee&&!ee.provider)return null;let ue=ee.provider;if(!ue&&"url"in ee&&ee.url&&(ue=o.aM(ee.url)),!ue)return null;const _e=o.g.TILE_PROVIDER_URLS[ue];if(!_e)return null;let Ee;try{Ee=new URL(_e,o.g.API_URL).href}catch{return o.w(`TileProvider "${ue}" has an invalid URL: "${_e}"`),null}return{name:ue,url:Ee}}(this._options);if(this.provider&&!Q)return this._loaded=!0,this.fire(new o.B(new Error(`TileProvider "${this.provider}" is not registered`))),void(N&&N());this._tileJSONRequest=Q?this._loadWithProvider(Q,W):Bd(this._options,this.map._requestManager,T,z,W)}_loadWithProvider(N,T){this.provider=N.name;const z=new AbortController,W=this._options.url&&!this._options.tiles?this.map._requestManager.transformRequest(this._options.url,o.R.Source):void 0,Q=W?Object.assign({},this._options,{url:W.url}):this._options;return this.dispatcher.broadcast("loadTileProvider",{name:N.name,url:N.url,source:this.id,scope:this.scope,type:this.type,options:Q,request:W},(ee,ue)=>{if(z.signal.aborted)return;if(ee)return void T(ee);const _e=ue?ue.find(Ee=>Ee!=null):null;if(_e){const Ee=Tp(this._options,_e,this.map._requestManager);Ee instanceof Error?T(Ee):T(null,Ee)}else T(null,{tiles:this._options.tiles})}),{cancel:()=>{z.abort()}}}_setTileJSON(N){if(Object.assign(this,N),this.hasWorldviews=!!N.worldview_options,N.worldview_default&&(this.worldviewDefault=N.worldview_default),N.vector_layers){this.vectorLayers=N.vector_layers,this.vectorLayerIds=[],this.localizableLayerIds=new Set;for(const T of N.vector_layers)this.vectorLayerIds.push(T.id),N.worldview&&N.worldview[T.source]&&this.localizableLayerIds.add(T.id)}this.tileBounds=xs.fromTileJSON(N)}loaded(){return this._loaded}hasTile(N){return!this.tileBounds||this.tileBounds.contains(N.canonical)}onAdd(N){this.map=N,this.load()}reload(){this.cancelTileJSONRequest();const N=o.F(this.id,this.scope);this.load(()=>this.map.style.clearSource(N))}setTiles(N){return this._options.tiles=N,this.reload(),this}setUrl(N){return this.url=N,this._options.url=N,this.reload(),this}onRemove(N){this.cancelTileJSONRequest()}serialize(){return Object.assign({},this._options)}loadTile(N,T){const z=N.tileID.canonical.url(this.tiles,this.scheme),W=this.map._requestManager.normalizeTileURL(z),Q=this.map._requestManager.transformRequest(W,o.R.Tile),ee=this.map.style?this.map.style.getLut(this.scope):null,ue=ee?{image:ee.image.clone()}:null,_e={request:Q,data:void 0,uid:N.uid,tileID:N.tileID,tileZoom:N.tileZoom,zoom:N.tileID.overscaledZ,maxZoom:this.maxzoom,lut:ue,tileSize:this.tileSize*N.tileID.overscaleFactor(),type:this.type,source:this.id,scope:this.scope,pixelRatio:o.o.devicePixelRatio,showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,renderSourceType:N.renderSourceType,brightness:this.map.style&&this.map.style.getBrightness()||0,extraShadowCaster:N.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(z)&&(_e.localizableLayerIds=this.localizableLayerIds),_e.request.collectResourceTiming=this._collectResourceTiming,N.actor&&N.state!=="expired")N.state==="loading"?N.reloadCallback=T:N.request=N.actor.send("reloadTile",_e,Ee.bind(this));else if(N.actor=this._tileWorkers[W]=this._tileWorkers[W]||this.dispatcher.getActor(),this.dispatcher.ready||this.provider)N.request=N.actor.send("loadTile",_e,Ee.bind(this),void 0,!0);else{const Ie=o.aO.call({deduped:this._deduped},_e,(Je,Ke)=>{if(Je||!Ke)Ee.call(this,Je);else{const tt=o.aP(Ke.responseHeaders);_e.data={rawData:Ke.rawData.slice(0),expires:tt.expires,cacheControl:tt.cacheControl},N.actor&&N.actor.send("loadTile",_e,Ee.bind(this),void 0,!0)}},!0);N.request={cancel:Ie}}function Ee(Ie,Je){return delete N.request,N.aborted?T(null):Ie?T(Ie):(Je&&Je.resourceTiming&&(N.resourceTiming=Je.resourceTiming),this.map._refreshExpiredTiles&&Je&&N.setExpiryData(Je),N.loadVectorData(Je,this.map.painter),o.aQ(this.dispatcher),T(null,Je),void(N.reloadCallback&&(this.loadTile(N,N.reloadCallback),N.reloadCallback=null)))}}abortTile(N){N.request&&(N.request.cancel(),delete N.request),N.actor&&N.actor.send("abortTile",{uid:N.uid,type:this.type,source:this.id,scope:this.scope})}unloadTile(N,T){N.actor&&N.actor.send("removeTile",{uid:N.uid,type:this.type,source:this.id,scope:this.scope}),N.destroy()}hasTransition(){return!1}afterUpdate(){this._tileWorkers={}}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null)}}class so extends o.E{constructor(N,T,z,W){super(),this.id=N,this.dispatcher=z,this.setEventedParent(W),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"},T),Object.assign(this,o.aJ(T,["url","scheme","tileSize"]))}load(N){this._loaded=!1,this.fire(new o.C("dataloading",{dataType:"source"}));const T=this.map.getWorldview();this._tileJSONRequest=Bd(this._options,this.map._requestManager,null,T,(z,W)=>{this._tileJSONRequest=null,this._loaded=!0,z?this.fire(new o.B(z)):W&&(Object.assign(this,W),W.raster_layers&&(this.rasterLayers=W.raster_layers,this.rasterLayerIds=this.rasterLayers.map(Q=>Q.id)),this.tileBounds=xs.fromTileJSON(W),be(W.tiles),this.fire(new o.C("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new o.C("data",{dataType:"source",sourceDataType:"content"}))),N&&N(z)})}loaded(){return this._loaded}onAdd(N){this.map=N,this.load()}reload(){this.cancelTileJSONRequest();const N=o.F(this.id,this.scope);this.load(()=>this.map.style.clearSource(N))}setTiles(N){return this._options.tiles=N,this.reload(),this}setUrl(N){return this.url=N,this._options.url=N,this.reload(),this}onRemove(N){this.cancelTileJSONRequest()}serialize(){return Object.assign({},this._options)}hasTile(N){return!this.tileBounds||this.tileBounds.contains(N.canonical)}loadTile(N,T){const z=o.o.devicePixelRatio>=2,W=this.map._requestManager.normalizeTileURL(N.tileID.canonical.url(this.tiles,this.scheme),z,this.tileSize);N.request=o.n(this.map._requestManager.transformRequest(W,o.R.Tile),(Q,ee,ue)=>{if(delete N.request,N.aborted)return N.state="unloaded",T(null);if(Q)return N.state="errored",T(Q);if(!ee)return T(null);const _e=o.aP(ue);this.map._refreshExpiredTiles&&N.setExpiryData(_e),N.setTexture(ee,this.map.painter),N.state="loaded",o.aQ(this.dispatcher),T(null)})}abortTile(N,T){N.request&&(N.request.cancel(),delete N.request),T&&T()}unloadTile(N,T){N.texture&&N.texture instanceof o.T?(N.destroy(!1),N.texture&&N.texture instanceof o.T&&this.map.painter.saveTileTexture(N.texture)):N.destroy(),T&&T()}hasTransition(){return!1}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null)}}function Ma([R,N],T,z,{scaled:W=!0}={}){const{tileSize:Q,buffer:ee}=z,{x:ue,y:_e,z:Ee}=T;if(!isFinite(ue)||!isFinite(_e)||!isFinite(Ee))throw new Error("Invalid MRT header");const Ie=2**Ee,Je=Ie*o.aH(R),Ke=Ie*o.aL(N);return function([tt,ut],lt,{scaled:kt=!0}={}){if(!lt)throw new Error("bandView is undefined");const{data:Nt,tileSize:zt,buffer:Yt,offset:Tt,scale:Ss,dimension:cs}=lt;if(tt<-Yt||tt>zt+Yt||ut<-Yt||ut>zt+Yt)throw new Error(`Point (${tt}, ${ut}) out of bounds for tileSize=${zt}, buffer=${Yt}`);const Ns=(ut+Yt)*(zt+2*Yt)+(tt+Yt);if(new Uint32Array(Nt.buffer)[Ns]===4294967295)return null;let Zt=[];Zt=kt?[]:new lt.data.constructor(cs);for(let ns=0;ns{if(delete N.request,N.aborted)return N.state="unloaded",T(null);if(ue)return ue.name==="AbortError"?void 0:(N.state="errored",T(ue));if(this.map._refreshExpiredTiles&&_e){const Ie=o.aP(Ee);N.setExpiryData(Ie)}if(this.partial&&N.state!=="expired")N.state="empty";else if(!this.partial){if(!_e)return T(null);N.state="loaded",N._isHeaderLoaded=!0,N._mrt=_e}T(null)};N.request=this.partial?N.fetchHeader(void 0,ee.bind(this)):N.actor.send("loadTile",Q,ee.bind(this),void 0,!0)}abortTile(N){N.request&&(N.request.cancel(),delete N.request),N.actor&&N.actor.send("abortTile",{uid:N.uid,type:this.type,source:this.id,scope:this.scope})}unloadTile(N,T){const z=N.texturePerLayer;if(N.flushAllQueues(),z.size){N.destroy(!1);for(const W of z.values())this.map.painter.saveTileTexture(W)}else N.destroy()}prepareTile(N,T,z,W){N._isHeaderLoaded&&(N.state!=="empty"&&(N.state="reloading"),N.fetchBandForRender(T,z,W,(Q,ee)=>{Q?(N.state="errored",this.fire(new o.B(Q))):ee&&(N._isHeaderLoaded=!0,N.setTexturePerLayer(z,ee,this.map.painter),N.state="loaded"),this.triggerRepaint(N)}))}getInitialBand(N){if(!this.rasterLayers)return 0;const T=this.rasterLayers.find(({id:Q})=>Q===N),z=T&&T.fields,W=z&&z.bands&&z.bands;return W?W[0]:0}getTextureDescriptor(N,T,z){if(!N)return;const W=T.sourceLayer||this.rasterLayerIds&&this.rasterLayerIds[0];if(!W)return;let Q=null;T instanceof o.aS?Q=T.paint.get("raster-array-band"):T instanceof o.aT&&(Q=T.paint.get("raster-particle-array-band"));const ee=Q||this.getInitialBand(W);if(ee==null)return;if(!N.textureDescriptorPerLayer.get(T.id))return void this.prepareTile(N,W,T.id,ee);if(N.updateNeeded(T.id,ee)&&!z)return;const ue=N.textureDescriptorPerLayer.get(T.id);return Object.assign({},ue,{texture:N.texturePerLayer.get(T.id)})}getImages(N,T){const z=new Map;for(const W of N)for(const Q of T){const[ee,ue]=Q.split("/"),_e=W.getLayer(ee);if(!_e||!_e.hasBand(ue)||!_e.hasDataForBand(ue))continue;const{bytes:Ee,tileSize:Ie,buffer:Je}=_e.getBandView(ue),Ke=Ie+2*Je,tt={data:new o.q({width:Ke,height:Ke},Ee),pixelRatio:2,sdf:!1,usvg:!1,version:0};z.set(Q,tt)}return z}queryRasterArrayValueByBandId(N,T,z){const W=T._mrt;return new Promise(Q=>{const ee={},ue=new Set;for(const[_e,Ee]of Object.entries(W.layers)){if(z.layerName&&_e!==z.layerName)continue;const Ie={};ee[_e]=Ie;for(const{bands:Je}of Ee.dataIndex)for(const Ke of Je)z.bands&&!z.bands.includes(Ke)||(ue.add(o.F(_e,Ke)),T.fetchBand(_e,null,Ke,tt=>{o.o.frame(()=>{Ie[Ke]=tt?null:Ma([N.lng,N.lat],W,Ee.getBandView(Ke)),ue.delete(o.F(_e,Ke)),ue.size===0&&Q(ee)})},!1))}ue.size===0&&Q(ee)})}_loadTileForQuery(N,T){if(this._loadTileLoaded[N.uid])return void T(null,N._mrt);if(this._loadTilePending[N.uid])return void this._loadTilePending[N.uid].push(T);this._loadTilePending[N.uid]=[T];const z=this.map._requestManager.normalizeTileURL(N.tileID.canonical.url(this.tiles,this.scheme),!1,this.tileSize),W=this.map._requestManager.transformRequest(z,o.R.Tile);N.actor.send("loadTile",{request:W,uid:N.uid,tileID:N.tileID,type:this.type,source:this.id,scope:this.scope,partial:!1},(Q,ee,ue)=>{if(Q)return this._loadTilePending[N.uid].forEach(_e=>_e(Q,null)),void delete this._loadTilePending[N.uid];if(!ee)return this._loadTilePending[N.uid].forEach(_e=>_e(null,null)),void delete this._loadTilePending[N.uid];if(this.map._refreshExpiredTiles&&ee){const _e=o.aP(ue);N.setExpiryData(_e)}N._mrt=ee,N._isHeaderLoaded=!0,N.state="loaded",this._loadTilePending[N.uid].forEach(_e=>_e(null,ee)),this._loadTileLoaded[N.uid]=!0,delete this._loadTilePending[N.uid]},void 0,!0)}queryRasterArrayValueByAllBands(N,T,z){return new Promise((W,Q)=>{this._loadTileForQuery(T,(ee,ue)=>{ee?Q(ee):W(ue?this.queryRasterArrayValueByBandId(N,T,z):null)})})}queryRasterArrayValue(N,T){const z=o.aU.convert(N),W=this.findLoadedParent(z);return W&&W._mrt?T.bands||!this.partial?this.queryRasterArrayValueByBandId(z,W,T):this.queryRasterArrayValueByAllBands(z,W,T):Promise.resolve(null)}findLoadedParent(N){const T=o.ag.fromLngLat(N,this.map.transform.tileSize),z=this.maxzoom+1,W=1<0&&(ue[new o.aR(R.overscaledZ,W,N.z,z,N.y-1).key]={backfilled:!1},ue[new o.aR(R.overscaledZ,R.wrap,N.z,N.x,N.y-1).key]={backfilled:!1},ue[new o.aR(R.overscaledZ,ee,N.z,Q,N.y-1).key]={backfilled:!1}),N.y+1{if(this._loaded=!0,this._pendingLoad=null,z)this.fire(new o.B(z));else{const Q={dataType:"source",sourceDataType:this._metadataFired?"content":"metadata"};this._collectResourceTiming&&W&&W.resourceTiming&&W.resourceTiming[this.id]&&(Q.resourceTiming=W.resourceTiming[this.id]),R&&(this._partialReload=!0),this.fire(new o.C("data",Q)),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,N){const T=R.actor?"reloadTile":"loadTile";R.actor=this.actor;const z=this.map.style?this.map.style.getLut(this.scope):null,W=z?{image:z.image.clone()}:null,Q=this._partialReload,ee={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:W,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:Q,worldview:this.map.getWorldview(),indoor:this.map.getIndoorTileOptions(this.id,this.scope)};R.request=this.actor.send(T,ee,(ue,_e)=>Q&&!_e?(R.state="loaded",N(null)):(delete R.request,R.destroy(!1),R.aborted?N(null):ue?N(ue):(R.loadVectorData(_e,this.map.painter,T==="reloadTile"),N(null))),void 0,T==="loadTile")}abortTile(R){R.request&&(R.request.cancel(),delete R.request),R.aborted=!0}unloadTile(R,N){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,N,T,z){super(R,N,T,z),this.roundZoom=!0,this.type="video",this.options=N}load(){this._loaded=!1;const R=this.options;this.urls=[];for(const N of R.urls)this.urls.push(this.map._requestManager.transformRequest(N,o.R.Source).url);o.aW(this.urls,(N,T)=>{this._loaded=!0,N?this.fire(new o.B(N)):T&&(this.video=T,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 N=this.video.seekable;RN.end(0)?this.fire(new o.B(new o.V(`sources.${this.id}`,null,`Playback for this video can be set only between the ${N.start(0)} and ${N.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,N=R.gl;this.texture?this.video.paused||(this.texture.bind(N.LINEAR,N.CLAMP_TO_EDGE),N.texSubImage2D(N.TEXTURE_2D,0,0,0,N.RGBA,N.UNSIGNED_BYTE,this.video)):(this.texture=new o.T(R,this.video,N.RGBA8),this.texture.bind(N.LINEAR,N.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,N,T,z){super(),this.type="batched-model",this.id=R,this.tileSize=512,this._options=N,this.tiles=this._options.tiles,this.maxzoom=N.maxzoom||19,this.minzoom=N.minzoom||0,this.roundZoom=!0,this.usedInConflation=!0,this.dispatcher=T,this.reparseOverscaled=!1,this.scheme="xyz",this._loaded=!1,this.setEventedParent(z)}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 N=Array.isArray(this.map._language)?this.map._language.join():this.map._language,T=this.map.getWorldview();this._tileJSONRequest=Bd(this._options,this.map._requestManager,N,T,(z,W)=>{this._tileJSONRequest=null,this._loaded=!0,z?(N&&console.warn(`Ensure that your requested language string is a valid BCP-47 code or list of codes. Found: ${N}`),T&&T.length!==2&&console.warn(`Requested worldview strings must be a valid ISO alpha-2 code. Found: ${T}`),this.fire(new o.B(z))):W&&(Object.assign(this,W),W.bounds&&(this.tileBounds=new xs(W.bounds,this.minzoom,this.maxzoom)),be(W.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(z)})}hasTransition(){return!1}hasTile(R){return!this.tileBounds||this.tileBounds.contains(R.canonical)}loaded(){return this._loaded}loadTile(R,N){const T=this.map._requestManager.normalizeTileURL(R.tileID.canonical.url(this.tiles,this.scheme)),z={request:this.map._requestManager.transformRequest(T,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=N;else{if(R.buckets){const Q=Object.values(R.buckets);for(const ee of Q)ee.dirty=!0;return void(R.state="loaded")}R.request=R.actor.send("reloadTile",z,W.bind(this))}else R.actor=this.dispatcher.getActor(),R.request=R.actor.send("loadTile",z,W.bind(this),void 0,!0);function W(Q,ee){return R.aborted?N(null):Q&&Q.status!==404?N(Q):(this.map._refreshExpiredTiles&&ee&&R.setExpiryData(ee),R.loadModelData(ee,this.map.painter),R.state="loaded",void N(null))}}serialize(){return Object.assign({},this._options)}},canvas:class extends o.aV{constructor(R,N,T,z){super(R,N,T,z),N.coordinates?Array.isArray(N.coordinates)&&N.coordinates.length===4&&!N.coordinates.some(W=>!Array.isArray(W)||W.length!==2||W.some(Q=>typeof Q!="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"'))),N.animate&&typeof N.animate!="boolean"&&this.fire(new o.B(new o.V(`sources.${R}`,null,'optional "animate" property must be a boolean value'))),N.canvas?typeof N.canvas=="string"||N.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=N,this.animate=N.animate===void 0||N.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 N=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(N,this.canvas,N.gl.RGBA8,{premultiply:!0}),this._prepareData(N)}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,N,T,z){super(),this.id=R,this.type="custom",this._dataType="raster",this._dispatcher=T,this._implementation=N,this.setEventedParent(z),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 xs(this._implementation.bounds,this.minzoom,this.maxzoom));const W=N;W.update=this._update.bind(this),W.clearTiles=this._clearTiles.bind(this),W.coveringTiles=this._coveringTiles.bind(this),Object.assign(this,o.aJ(N,["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:N,y:T,z}=R.canonical;return this._implementation.hasTile({x:N,y:T,z})}return!this.tileBounds||this.tileBounds.contains(R.canonical)}loadTile(R,N){const{x:T,y:z,z:W}=R.tileID.canonical,Q=new AbortController,ee=Promise.resolve(this._implementation.loadTile({x:T,y:z,z:W},{signal:Q.signal})).then((function(ue){return delete R.request,R.aborted?(R.state="unloaded",N(null)):ue===void 0?(R.state="errored",N(null)):ue===null?(this.loadTileData(R,{width:this.tileSize,height:this.tileSize,data:null}),R.state="loaded",N(null)):function(_e){return _e instanceof ImageData||_e instanceof HTMLCanvasElement||_e instanceof ImageBitmap||_e instanceof HTMLImageElement}(ue)?(this.loadTileData(R,ue),R.state="loaded",void N(null)):(R.state="errored",N(new Error(`Can't infer data type for ${this.id}, only raster data supported at the moment`)))}).bind(this)).catch(ue=>{ue.name!=="AbortError"&&(R.state="errored",N(ue))});ee.cancel=()=>Q.abort(),R.request=ee}loadTileData(R,N){R.setTexture(N,this.map.painter)}unloadTile(R,N){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:T,y:z,z:W}=R.tileID.canonical;this._implementation.unloadTile({x:T,y:z,z:W})}N&&N()}abortTile(R,N){R.request&&R.request.cancel&&(R.request.cancel(),delete R.request),N&&N()}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"}))}}},bi=function(R,N,T,z){const W=new Co[N.type](R,N,T,z);if(W.id!==R)throw new Error(`Expected Source id to be ${R} instead of ${W.id}`);return o.aZ(["load","abort","unload","serialize","prepare"],W),W};function Bu(R,N,T=""){return`${T}:${N.id||""}:${N.layer.id}:${function(z){if("layerId"in z)return`layer:${z.layerId}`;{const{featuresetId:W,importId:Q}=z;return`featureset:${W}${Q?`:import:${Q}`:""}`}}(R.target)}`}function Uu(R,N,T,z=""){if(R.uniqueFeatureID){const W=Bu(R,N,z);if(T.has(W))return!0;T.add(W)}return!1}function Rx(R,N,T,z,W=!1,Q=void 0){const ee=N.sourceCache.transform,ue=N.sourceCache.tilesIn(R,N.has3DLayers,W);ue.sort(ml);const _e=[];for(const Ee of ue){const Ie=Ee.tile.queryRenderedFeatures(N,Ee,T,z,ee,W,Q);Object.keys(Ie).length&&_e.push({wrappedTileID:Ee.tile.tileID.wrapped().key,queryResults:Ie})}for(const Ee in N.layers){const Ie=N.layers[Ee];if(Ie.styleLayer){const Je=Ie.styleLayer.queryRenderedFeatures(R,N.sourceCache,z);Object.keys(Je).length&&_e.push({wrappedTileID:0,queryResults:Je})}}return _e.length===0?{}:function(Ee){const Ie={},Je={};for(const Ke of Ee){const tt=Ke.queryResults,ut=Ke.wrappedTileID,lt=Je[ut]=Je[ut]||{};for(const kt in tt){const Nt=tt[kt],zt=lt[kt]=lt[kt]||{},Yt=Ie[kt]=Ie[kt]||[];for(const Tt of Nt)zt[Tt.featureIndex]||(zt[Tt.featureIndex]=!0,Yt.push(Tt))}}return Ie}(_e)}function hl(R,N,T,z,W,Q){const ee={},ue=z.queryRenderedSymbols(R),_e=[];for(const Ee of Object.keys(ue).map(Number))_e.push(W[Ee]);_e.sort(ml);for(const Ee of _e){const Ie=Ee.featureIndex.lookupSymbolFeatures(ue[Ee.bucketInstanceId],Ee.bucketIndex,Ee.sourceLayerIndex,N,T,Q);for(const Je in Ie){const Ke=ee[Je]=ee[Je]||[],tt=Ie[Je];tt.sort((ut,lt)=>{const kt=Ee.featureSortOrder;if(kt){const Nt=kt.indexOf(ut.featureIndex);return kt.indexOf(lt.featureIndex)-Nt}return lt.featureIndex-ut.featureIndex});for(const ut of tt)Ke.push(ut)}}return ee}function Ua(R,N){const T=R.getRenderableIds().map(Q=>R.getTileByID(Q)),z=[],W={};for(let Q=0;Q{if(Q)T(Q);else try{const _e=z.getHeaderLength(ee);if(_e>N)return void(this.request=this.fetchHeader(_e,T));z.parseHeader(ee),this._isHeaderLoaded=!0;let Ee=0;for(const Ie of Object.values(z.layers))Ee=Math.max(Ee,Ie.dataIndex[Ie.dataIndex.length-1].lastByte);ee.byteLength>=Ee&&(this.entireBuffer=ee),T(null,this.entireBuffer||ee,ue)}catch(_e){T(_e)}}),this.request}fetchBandForRender(N,T,z,W){this.fetchBand(N,T,z,Q=>{if(Q)return void W(Q);this.updateTextureDescriptor(N,T,z);const ee=this.textureDescriptorPerLayer.get(T);W(null,ee?ee.img:null)})}fetchBand(N,T,z,W,Q=!0){const ee=this._mrt;if(!this._isHeaderLoaded||!ee)return void W(new Error("Tile header is not ready"));const ue=this.actor;if(!ue)return void W(new Error("Can't fetch tile band without an actor"));let _e;const Ee=o.F(String(z),o.F(this.tileID.key,N));let Ie=this._taskQueue.get(Ee);Ie?Ie.add(W):(Ie=new Set,Ie.add(W),this._taskQueue.set(Ee,Ie));const Je=(lt,kt)=>{_e.complete(lt,kt),lt?W(lt):(Ie.forEach(Nt=>Nt(null,kt)),this._taskQueue.delete(Ee))},Ke=(lt,kt)=>{if(lt)return W(lt);const Nt=ue.send("decodeRasterArray",{type:"raster-array",source:this.source,scope:this.scope,tileID:this.tileID,uid:this.uid,buffer:kt,task:_e},Je,void 0,!0);if(T!==null){const zt=this._workQueuePerLayer.get(T)||[];zt.push(()=>{Nt&&Nt.cancel(),_e.cancel()}),this._workQueuePerLayer.has(T)||this._workQueuePerLayer.set(T,zt)}};let tt;try{tt=ee.getLayer(N)}catch(lt){if(this.state==="reloading")return;throw lt}if(!tt)return void W(new Error(`Unknown sourceLayer "${N}"`));if(tt.hasDataForBand(z))return Ie.forEach(lt=>lt(null,null)),void this._taskQueue.delete(Ee);const ut=tt.getDataRange([z]);if(_e=ee.createDecodingTask(ut),!_e||_e.tasks.length)if(T!==null&&this.flushQueues(T),this.entireBuffer)Ke(null,this.entireBuffer.slice(ut.firstByte,ut.lastByte+1));else{const lt=Object.assign({},this.requestParams,{headers:{Range:`bytes=${ut.firstByte}-${ut.lastByte}`}}),kt=o.b1(lt,Ke);if(T!==null){const Nt=this._fetchQueuePerLayer.get(T)||[];Nt.push(()=>{kt.cancel(),_e.cancel()}),this._fetchQueuePerLayer.has(T)||this._fetchQueuePerLayer.set(T,Nt)}}}updateNeeded(N,T){return(!this.textureDescriptorPerLayer.get(N)||this.textureDescriptorPerLayer.get(N).band!==T||this.refreshedUponExpiration)&&this.state!=="errored"}updateTextureDescriptor(N,T,z){if(!this._mrt)return;const W=this._mrt.getLayer(N);if(!W||!W.hasBand(z)||!W.hasDataForBand(z))return;const{bytes:Q,tileSize:ee,buffer:ue,offset:_e,scale:Ee}=W.getBandView(z),Ie=ee+2*ue,Je=new o.q({width:Ie,height:Ie},Q),Ke=this.texturePerLayer.get(T);Ke&&Ke instanceof o.T&&Ke.update(Je,{premultiply:!1}),this.textureDescriptorPerLayer.set(T,{layer:N,band:z,img:Je,buffer:ue,offset:_e,tileSize:ee,format:W.pixelFormat,mix:[Ee,256*Ee,65536*Ee,16777216*Ee]})}destroy(N=!1){if(super.destroy(N),delete this._mrt,!N)for(const T of this.texturePerLayer.values())T&&T instanceof o.T&&T.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 Hg{constructor(N,T){this.max=N,this.onRemove=T,this.reset()}reset(){for(const N in this.data)for(const T of this.data[N])T.timeout&&clearTimeout(T.timeout),this.onRemove(T.value);return this.data={},this.order=[],this}add(N,T,z){const W=N.wrapped().key;this.data[W]===void 0&&(this.data[W]=[]);const Q={value:T,timeout:void 0};if(z!==void 0&&(Q.timeout=setTimeout(()=>{this.remove(N,Q)},z)),this.data[W].push(Q),this.order.push(W),this.order.length>this.max){const ee=this._getAndRemoveByKey(this.order[0]);ee&&this.onRemove(ee)}return this}has(N){return N.wrapped().key in this.data}getAndRemove(N){return this.has(N)?this._getAndRemoveByKey(N.wrapped().key):null}_getAndRemoveByKey(N){const T=this.data[N].shift();return T.timeout&&clearTimeout(T.timeout),this.data[N].length===0&&delete this.data[N],this.order.splice(this.order.indexOf(N),1),T.value}getByKey(N){const T=this.data[N];return T?T[0].value:null}get(N){return this.has(N)?this.data[N.wrapped().key][0].value:null}remove(N,T){if(!this.has(N))return this;const z=N.wrapped().key,W=T===void 0?0:this.data[z].indexOf(T),Q=this.data[z][W];return this.data[z].splice(W,1),Q.timeout&&clearTimeout(Q.timeout),this.data[z].length===0&&delete this.data[z],this.onRemove(Q.value),this.order.splice(this.order.indexOf(z),1),this}setMaxSize(N){for(this.max=N;this.order.length>this.max;){const T=this._getAndRemoveByKey(this.order[0]);T&&this.onRemove(T)}return this}filter(N){const T=[];for(const z in this.data)for(const W of this.data[z])N(W.value)||T.push(W);for(const z of T)this.remove(z.value.tileID,z)}}class Dv{constructor(){this.state={},this.stateChanges={},this.deletedStates={}}updateState(N,T,z){const W=String(T);if(this.stateChanges[N]=this.stateChanges[N]||{},this.stateChanges[N][W]=this.stateChanges[N][W]||{},Object.assign(this.stateChanges[N][W],z),this.deletedStates[N]===null){this.deletedStates[N]={};for(const Q in this.state[N])Q!==W&&(this.deletedStates[N][Q]=null)}else if(this.deletedStates[N]&&this.deletedStates[N][W]===null){this.deletedStates[N][W]={};for(const Q in this.state[N][W])z[Q]||(this.deletedStates[N][W][Q]=null)}else for(const Q in z)this.deletedStates[N]&&this.deletedStates[N][W]&&this.deletedStates[N][W][Q]===null&&delete this.deletedStates[N][W][Q]}removeFeatureState(N,T,z){if(this.deletedStates[N]===null)return;const W=String(T);if(this.deletedStates[N]=this.deletedStates[N]||{},z&&T!==void 0)this.deletedStates[N][W]!==null&&(this.deletedStates[N][W]=this.deletedStates[N][W]||{},this.deletedStates[N][W][z]=null);else if(T!==void 0)if(this.stateChanges[N]&&this.stateChanges[N][W])for(z in this.deletedStates[N][W]={},this.stateChanges[N][W])this.deletedStates[N][W][z]=null;else this.deletedStates[N][W]=null;else this.deletedStates[N]=null}getState(N,T){const z=this.state[N]||{},W=this.stateChanges[N]||{},Q=this.deletedStates[N];if(Q===null)return{};if(T!==void 0){const ue=String(T),_e=Object.assign({},z[ue],W[ue]);if(Q){const Ee=Q[T];if(Ee===null)return{};for(const Ie in Ee)delete _e[Ie]}return _e}const ee=Object.assign({},z,W);if(Q)for(const ue in Q)delete ee[ue];return ee}initializeTileState(N,T){N.refreshFeatureState(T)}coalesceChanges(N,T){const z={};for(const W in this.stateChanges){this.state[W]=this.state[W]||{};const Q={};for(const ee in this.stateChanges[W])this.state[W][ee]||(this.state[W][ee]={}),Object.assign(this.state[W][ee],this.stateChanges[W][ee]),Q[ee]=this.state[W][ee];z[W]=Q}for(const W in this.deletedStates){this.state[W]=this.state[W]||{};const Q={};if(this.deletedStates[W]===null)for(const ee in this.state[W])Q[ee]={},this.state[W][ee]={};else for(const ee in this.deletedStates[W]){if(this.deletedStates[W][ee]===null)this.state[W][ee]={};else if(this.state[W][ee])for(const ue of Object.keys(this.deletedStates[W][ee]))delete this.state[W][ee][ue];Q[ee]=this.state[W][ee]}z[W]=z[W]||{},Object.assign(z[W],Q)}if(this.stateChanges={},this.deletedStates={},Object.keys(z).length!==0)for(const W in N)N[W].refreshFeatureState(T,z)}}class Dc extends o.E{constructor(N,T,z){super(),this.id=N,this._renderSourceType=z,this._maxzoomOverride=null,T.on("data",W=>{W.dataType==="source"&&W.sourceDataType==="metadata"&&(this._sourceLoaded=!0),this._sourceLoaded&&!this._paused&&W.dataType==="source"&&W.sourceDataType==="content"&&(this.reload(),this.transform&&this.update(this.transform))}),T.on("error",()=>{this._sourceErrored=!0}),this._source=T,this._tiles={},this._cache=new Hg(0,this._unloadTile.bind(this)),this._timers={},this._cacheTimers={},this._minTileCacheSize=T.minTileCacheSize,this._maxTileCacheSize=T.maxTileCacheSize,this._loadedParentTiles={},this.castsShadows=!1,this.tileCoverLift=0,this._coveredTiles={},this._shadowCasterTiles={},this._state=new Dv,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(N){this.map=N,this._minTileCacheSize=this._minTileCacheSize===void 0&&N?N._minTileCacheSize:this._minTileCacheSize,this._maxTileCacheSize=this._maxTileCacheSize===void 0&&N?N._maxTileCacheSize:this._maxTileCacheSize}loaded(){if(this._sourceErrored)return!0;if(!this._sourceLoaded||!this._source.loaded())return!1;for(const N in this._tiles)if(!this._tiles[N].loaded())return!1;return!0}getSource(){return this._source}pause(){this._paused=!0}resume(){if(!this._paused)return;const N=this._shouldReloadOnResume;this._paused=!1,this._shouldReloadOnResume=!1,N&&this.reload(),this.transform&&this.update(this.transform)}setMaxzoomOverride(N){this._maxzoomOverride=N}_loadTile(N,T){return N.renderSourceType=this._renderSourceType,N.isExtraShadowCaster=this._shadowCasterTiles[N.tileID.key],this._source.loadTile(N,T)}_unloadTile(N){if(this._source.unloadTile)return this._source.unloadTile(N)}_abortTile(N){if(this._source.abortTile)return this._source.abortTile(N)}serialize(){return this._source.serialize()}prepare(N){this._source.prepare&&this._source.prepare(),this._state.coalesceChanges(this._tiles,this.map?this.map.painter:null);for(const T in this._tiles){const z=this._tiles[T];z.upload(N,this.map?this.map.painter:void 0),z.prepare(this.map.style.imageManager,this.map?this.map.painter:null,this._source.scope)}}getIds(){return Object.values(this._tiles).map(N=>N.tileID).sort(Mp).map(N=>N.key)}getRenderableIds(N,T){const z=[];for(const W in this._tiles)this._isIdRenderable(+W,N,T)&&z.push(this._tiles[W]);return N?z.sort((W,Q)=>{const ee=W.tileID,ue=Q.tileID,_e=new o.P(ee.canonical.x,ee.canonical.y)._rotate(this.transform.angle),Ee=new o.P(ue.canonical.x,ue.canonical.y)._rotate(this.transform.angle);return ee.overscaledZ-ue.overscaledZ||Ee.y-_e.y||Ee.x-_e.x}).map(W=>W.tileID.key):z.map(W=>W.tileID).sort(Mp).map(W=>W.key)}hasRenderableParent(N){const T=this.findLoadedParent(N,0);return!!T&&this._isIdRenderable(T.tileID.key)}_isIdRenderable(N,T,z){return this._tiles[N]&&this._tiles[N].hasData()&&!this._coveredTiles[N]&&(T||!this._tiles[N].holdingForFade())&&(z||!this._shadowCasterTiles[N])}reload(){if(this._paused)this._shouldReloadOnResume=!0;else{this._cache.reset();for(const N in this._tiles)this._tiles[N].state!=="errored"&&this._reloadTile(+N,"reloading")}}_reloadTile(N,T){const z=this._tiles[N];z&&(z.state!=="loading"&&(z.state=T),this._loadTile(z,this._tileLoaded.bind(this,z,N,T)))}_tileLoaded(N,T,z,W,Q){if(W){if(N.state="errored",o.b2(W)){if(this._source.fire(new o.C("data",{dataType:"source",sourceDataType:"error",sourceId:this._source.id,tile:N})),!(N.tileID.key in this._loadedParentTiles))return;if(this._source.type==="raster-dem"&&this.usedForTerrain&&this.map.painter.terrain){const ue=this.map.painter.terrain;this.update(this.transform,ue.getScaledDemTileSize(),!0),ue.resetTileLookupCache(this.id)}else this.update(this.transform)}else this._source.fire(new o.B(W,{tile:N}));return}N.timeAdded=o.o.now(),z==="expired"&&(N.refreshedUponExpiration=!0),this._setTileReloadTimer(T,N),this._source.type==="raster-dem"&&N.dem&&this._backfillDEM(N),this._state.initializeTileState(N,this.map?this.map.painter:null);let ee=new Map;Q&&Q.responseHeaders&&(ee=Q.responseHeaders),this._source.fire(new o.C("data",{dataType:"source",tile:N,coord:N.tileID,sourceCacheId:this.id,responseHeaders:ee}))}_hasTunnelGeometry(){for(const N in this._tiles){const T=this._tiles[N];if(T&&T.hasTunnelGeometry)return!0}return!1}_backfillDEM(N){const T=this.getRenderableIds();for(let W=0;W1||(Math.abs(ee)>1&&(Math.abs(ee+_e)===1?ee+=_e:Math.abs(ee-_e)===1&&(ee-=_e)),Q.dem&&W.dem&&(W.dem.backfillBorder(Q.dem,ee,ue),W.neighboringTiles&&W.neighboringTiles[Ee]&&(W.neighboringTiles[Ee].backfilled=!0)))}}getTile(N){return this.getTileByID(N.key)}getTileByID(N){return this._tiles[N]}_retainLoadedChildren(N,T,z,W){for(const Q in this._tiles){let ee=this._tiles[Q];if(W[Q]||!ee.hasData()||ee.tileID.overscaledZ<=T||ee.tileID.overscaledZ>z)continue;let ue=ee.tileID;for(;ee&&ee.tileID.overscaledZ>T+1;){const Ee=ee.tileID.scaledTo(ee.tileID.overscaledZ-1);ee=this._tiles[Ee.key],ee&&ee.hasData()&&(ue=Ee)}let _e=ue;for(;_e.overscaledZ>T;)if(_e=_e.scaledTo(_e.overscaledZ-1),N[_e.key]){W[ue.key]=ue;break}}}findLoadedParent(N,T){if(N.key in this._loadedParentTiles){const z=this._loadedParentTiles[N.key];return z&&z.tileID.overscaledZ>=T?z:null}for(let z=N.overscaledZ-1;z>=T;z--){const W=N.scaledTo(z),Q=this._getLoadedTile(W);if(Q)return Q}}_getLoadedTile(N){const T=this._tiles[N.key];return T&&T.hasData()?T:this._cache.getByKey(this._source.reparseOverscaled?N.wrapped().key:N.canonical.key)}updateCacheSize(N,T){T=T||this._source.tileSize;const z=Math.ceil(N.width/T)+1,W=Math.ceil(N.height/T)+1,Q=Math.floor(z*W*5),ee=typeof this._minTileCacheSize=="number"?Math.max(this._minTileCacheSize,Q):Q,ue=typeof this._maxTileCacheSize=="number"?Math.min(this._maxTileCacheSize,ee):ee;this._cache.setMaxSize(ue)}handleWrapJump(N){const T=Math.round((N-(this._prevLng===void 0?N:this._prevLng))/360);if(this._prevLng=N,T){const z={};for(const W in this._tiles){const Q=this._tiles[W];Q.tileID=Q.tileID.unwrapTo(Q.tileID.wrap+T),z[Q.tileID.key]=Q}this._tiles=z;for(const W in this._timers)clearTimeout(this._timers[W]),delete this._timers[W];for(const W in this._tiles)this._setTileReloadTimer(+W,this._tiles[W])}}update(N,T,z,W,Q){if(this.transform=N,!this._sourceLoaded||this._paused||this.transform.freezeTileCoverage||this.usedForTerrain&&!z)return;this.updateCacheSize(N,T),this.transform.projection.name!=="globe"&&this.handleWrapJump(this.transform.center.lng),this._shadowCasterTiles={},this._coveredTiles={};const ee=this._source.type==="batched-model";let ue,_e=this._source.maxzoom;this._maxzoomOverride!==null&&(_e=Math.min(_e,this._maxzoomOverride));const Ee=this.map&&this.map.painter?this.map.painter._terrain:null;if(Ee&&Ee.sourceCache===this&&Ee.attenuationRange()){const tt=Ee.attenuationRange()[0],ut=Math.floor(tt)-Math.log2(Ee.getDemUpscale());_e>ut&&(_e=ut)}const Ie=this._maxzoomOverride===null&&this._source.reparseOverscaled;if(this.used||this.usedForTerrain){if(this._source.tileID)ue=N.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=N.clone();tt.tileCoverLift=this.tileCoverLift,ue=tt.coveringTiles({tileSize:T||this._source.tileSize,minzoom:this._source.minzoom,maxzoom:_e,roundZoom:this._source.roundZoom&&!z,reparseOverscaled:Ie,isTerrainDEM:this.usedForTerrain,calculateQuadrantVisibility:ee}),this._source.minzoom<=1&&N.projection.name==="globe"&&(ue.push(new o.aR(1,0,1,0,0)),ue.push(new o.aR(1,0,1,1,0)),ue.push(new o.aR(1,0,1,0,1)),ue.push(new o.aR(1,0,1,1,1)))}else if(ue=N.coveringTiles({tileSize:T||this._source.tileSize,minzoom:this._source.minzoom,maxzoom:_e,roundZoom:this._source.roundZoom&&!z,reparseOverscaled:Ie,isTerrainDEM:this.usedForTerrain,calculateQuadrantVisibility:ee}),this._source.hasTile){const tt=this._source.hasTile.bind(this._source);ue=ue.filter(ut=>tt(ut))}}else ue=[];if(ue.length>0&&this.transform.projection.name!=="globe"&&!this.usedForTerrain&&!this._supportsFading){const tt=N.coveringZoomLevel({tileSize:T||this._source.tileSize,roundZoom:this._source.roundZoom&&!z}),ut=Math.min(tt,_e);if(ee){const lt=N.extendTileCover(ue,ut);for(const kt of lt)ue.push(kt)}else if(Q){const lt=this.transform.getFrustum(ut),kt=N.extendTileCoverToNearPlane(ue,lt,ut);for(const Nt of kt)ue.push(Nt);if(ut>=18&&this._hasTunnelGeometry()){const Nt=N.extendTileCoverForTunnels(ue,lt,ut,20);for(const zt of Nt)ue.push(zt)}}else if(this.castsShadows&&W){const lt=N.extendTileCover(ue,ut,W,16);for(const kt of lt)this._shadowCasterTiles[kt.key]=!0,ue.push(kt)}}const Je=this._updateRetainedTiles(ue);if(this._supportsFading&&ue.length!==0){const tt={},ut={},lt=o.o.now(),kt=Object.keys(Je);for(const zt of kt){const Yt=Je[zt],Tt=this._tiles[zt];if(!Tt||Tt.fadeEndTime!==void 0&&Tt.fadeEndTime<=lt)continue;const Ss=this.findLoadedParent(Yt,Math.max(Yt.overscaledZ-Dc.maxOverzooming,this._source.minzoom));Ss&&(this._addTile(Ss.tileID),tt[Ss.tileID.key]=Ss.tileID),ut[zt]=Yt}const Nt=ue[ue.length-1].overscaledZ;for(const zt in this._tiles){const Yt=this._tiles[zt];if(Je[zt]||!Yt.hasData())continue;let Tt=Yt.tileID;for(;Tt.overscaledZ>Nt;){Tt=Tt.scaledTo(Tt.overscaledZ-1);const Ss=this._tiles[Tt.key];if(Ss&&Ss.hasData()&&ut[Tt.key]){Je[zt]=Yt.tileID;break}}}for(const zt in tt)Je[zt]||(this._coveredTiles[zt]=!0,Je[zt]=tt[zt])}for(const tt in Je)this._tiles[tt].clearFadeHold();const Ke=o.b3(this._tiles,Je);for(const tt of Ke){const ut=this._tiles[tt];ut.hasSymbolBuckets&&!ut.holdingForFade()?ut.setHoldDuration(this.map._fadeDuration):ut.hasSymbolBuckets&&!ut.symbolFadeFinished()||this._removeTile(+tt)}this._updateLoadedParentTileCache(),this._renderSourceType===o.b4.Symbol&&this._source.afterUpdate&&this._source.afterUpdate()}releaseSymbolFadeTiles(){for(const N in this._tiles)this._tiles[N].holdingForFade()&&this._removeTile(+N)}_updateRetainedTiles(N){const T={};if(N.length===0)return T;const z={},W=N.reduce((Ee,Ie)=>Math.min(Ee,Ie.overscaledZ),1/0),Q=N[0].overscaledZ,ee=Math.max(Q-Dc.maxOverzooming,this._source.minzoom),ue=Math.max(Q+Dc.maxUnderzooming,this._source.minzoom),_e={};for(const Ee of N){const Ie=this._addTile(Ee);T[Ee.key]=Ee,Ie.hasData()||W=this._source.maxzoom){const Ke=Ee.children(this._source.maxzoom)[0],tt=this.getTile(Ke);if(tt&&tt.hasData()){T[Ke.key]=Ke;continue}}else{const Ke=Ee.children(this._source.maxzoom);if(T[Ke[0].key]&&T[Ke[1].key]&&T[Ke[2].key]&&T[Ke[3].key])continue}let Je=Ie.wasRequested();for(let Ke=Ee.overscaledZ-1;Ke>=ee;--Ke){const tt=Ee.scaledTo(Ke);if(z[tt.key]||(z[tt.key]=!0,Ie=this.getTile(tt),!Ie&&Je&&(Ie=this._addTile(tt)),Ie&&(T[tt.key]=tt,Je=Ie.wasRequested(),Ie.hasData())))break}}return T}_updateLoadedParentTileCache(){this._loadedParentTiles={};for(const N in this._tiles){const T=[];let z,W=this._tiles[N].tileID;for(;W.overscaledZ>0;){if(W.key in this._loadedParentTiles){z=this._loadedParentTiles[W.key];break}T.push(W.key);const Q=W.scaledTo(W.overscaledZ-1);if(z=this._getLoadedTile(Q),z)break;W=Q}for(const Q of T)this._loadedParentTiles[Q]=z}}_addTile(N){let T=this._tiles[N.key];if(T)return T.isExtraShadowCaster!==!0||this._shadowCasterTiles[N.key]||this._reloadTile(N.key,"reloading"),T;T=this._cache.getAndRemove(N),T&&(this._setTileReloadTimer(N.key,T),T.tileID=N,this._state.initializeTileState(T,this.map?this.map.painter:null),this._cacheTimers[N.key]&&(clearTimeout(this._cacheTimers[N.key]),delete this._cacheTimers[N.key],this._setTileReloadTimer(N.key,T)));const z=!!T;if(!z){const W=this.map?this.map.painter:null,Q=this._source.tileSize*N.overscaleFactor();T=this._source.type==="raster-array"?new fg(N,Q,this.transform.tileZoom,W,this._isRaster):new o.b0(N,Q,this.transform.tileZoom,W,this._isRaster,this._source.worldview),this._loadTile(T,this._tileLoaded.bind(this,T,N.key,T.state))}return T.uses++,this._tiles[N.key]=T,z||this._source.fire(new o.C("dataloading",{tile:T,coord:T.tileID,dataType:"source"})),T}_setTileReloadTimer(N,T){N in this._timers&&(clearTimeout(this._timers[N]),delete this._timers[N]);const z=T.getExpiryTimeout();z&&(this._timers[N]=setTimeout(()=>{this._reloadTile(N,"expired"),delete this._timers[N]},z))}_removeTile(N){const T=this._tiles[N];T&&(T.uses--,delete this._tiles[N],this._timers[N]&&(clearTimeout(this._timers[N]),delete this._timers[N]),T.uses>0||(T.hasData()&&T.state!=="reloading"||T.state==="empty"?this._cache.add(T.tileID,T,T.getExpiryTimeout()):(T.aborted=!0,this._abortTile(T),this._unloadTile(T))))}clearTiles(){this._shouldReloadOnResume=!1,this._paused=!1;for(const N in this._tiles)this._removeTile(+N);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(N,T,z){const W=[],Q=this.transform;if(!Q)return W;const ee=Q.projection.name==="globe",ue=o.aH(Q.center.lng);for(const _e in this._tiles){const Ee=this._tiles[_e];if(z&&Ee.clearQueryDebugViz(),Ee.holdingForFade())continue;let Ie;if(ee){const Je=Ee.tileID.canonical;if(Je.z===0){const Ke=[Math.abs(o.aC(ue,...op(Je,-1))-ue),Math.abs(o.aC(ue,...op(Je,1))-ue)];Ie=[0,2*Ke.indexOf(Math.min(...Ke))-1]}else{const Ke=[Math.abs(o.aC(ue,...op(Je,-1))-ue),Math.abs(o.aC(ue,...op(Je,0))-ue),Math.abs(o.aC(ue,...op(Je,1))-ue)];Ie=[Ke.indexOf(Math.min(...Ke))-1]}}else Ie=[0];for(const Je of Ie){const Ke=N.containsTile(Ee,Q,T,Je);Ke&&W.push(Ke)}}return W}getShadowCasterCoordinates(){return this._getRenderableCoordinates(!1,!0)}getVisibleCoordinates(N){return this._getRenderableCoordinates(N)}_getRenderableCoordinates(N,T){const z=this.getRenderableIds(N,T).map(Q=>this._tiles[Q].tileID),W=this.transform.projection.name==="globe";for(const Q of z)Q.projMatrix=this.transform.calculateProjMatrix(Q.toUnwrapped()),Q.expandedProjMatrix=W?this.transform.calculateProjMatrix(Q.toUnwrapped(),!1,!0):Q.projMatrix;return z}sortCoordinatesByDistance(N){const T=N.slice(),z=this.transform._camera.position,W=this.transform._camera.forward(),Q={};for(const ee of T){const ue=1/(1<Q[ee.key]-Q[ue.key]),T}hasTransition(){if(this._source.hasTransition())return!0;if(this._supportsFading){const N=o.o.now();for(const T in this._tiles){const z=this._tiles[T];if(z.fadeEndTime!==void 0&&z.fadeEndTime>=N)return!0}}return!1}setFeatureState(N,T,z){this._state.updateState(N=N||"_geojsonTileLayer",T,z)}removeFeatureState(N,T,z){this._state.removeFeatureState(N=N||"_geojsonTileLayer",T,z)}getFeatureState(N,T){return this._state.getState(N=N||"_geojsonTileLayer",T)}setDependencies(N,T,z){const W=this._tiles[N];W&&W.setDependencies(T,z)}reloadTilesForDependencies(N,T){for(const z in this._tiles)this._tiles[z].hasDependency(N,T)&&this._reloadTile(+z,"reloading");this._cache.filter(z=>!z.hasDependency(N,T))}_preloadTiles(N,T){if(!this._sourceLoaded){const _e=()=>{this._sourceLoaded&&(this._source.off("data",_e),this._preloadTiles(N,T))};return void this._source.on("data",_e)}const z=new Map,W=Array.isArray(N)?N:[N],Q=this.map.painter.terrain,ee=this.usedForTerrain&&Q?Q.getScaledDemTileSize():this._source.tileSize;for(const _e of W){const Ee=_e.coveringTiles({tileSize:ee,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:this._source.roundZoom&&!this.usedForTerrain,reparseOverscaled:this._source.reparseOverscaled,isTerrainDEM:this.usedForTerrain});for(const Ie of Ee)z.set(Ie.key,Ie);this.usedForTerrain&&_e.updateElevation(!1)}const ue=Array.from(z.values());o.t(ue,(_e,Ee)=>{const Ie=new o.b0(_e,this._source.tileSize*_e.overscaleFactor(),this.transform.tileZoom,this.map.painter,this._isRaster,this._source.worldview);this._loadTile(Ie,Je=>{this._source.type==="raster-dem"&&Ie.dem&&this._backfillDEM(Ie),Ee(Je,Ie)})},T)}}function Mp(R,N){const T=Math.abs(2*R.wrap)-+(R.wrap<0),z=Math.abs(2*N.wrap)-+(N.wrap<0);return R.overscaledZ-N.overscaledZ||z-T||N.canonical.y-R.canonical.y||N.canonical.x-R.canonical.x}function op(R,N){const T=1<0:z.type==="building"?W=!z.isHidden(N)&&z.paint.get("building-opacity")>0:z.type==="model"&&(W=!z.isHidden(N)&&z.paint.get("model-opacity").constantOr(1)>0),this.layersGotHidden=this.layersGotHidden||!W&&T.visible,T.visible=W}}updateZOffset(N,T){this.currentBuildingBuckets=[];for(const W of this.layers){const Q=W.layer,ee=this.style.getLayerSourceCache(Q);let ue=1;Q.type==="fill-extrusion"?ue=W.visible?Q.paint.get("fill-extrusion-vertical-scale"):0:Q.type==="building"&&(ue=W.visible?Q.paint.get("building-vertical-scale"):0);let _e=ee?ee.getTile(T):null;if(!_e&&ee)for(const Ee in ee._tiles){const Ie=ee._tiles[Ee];if(T.canonical.isChildOf(Ie.tileID.canonical)){_e=Ie;break}}this.currentBuildingBuckets.push({bucket:_e?_e.getBucket(Q):null,tileID:_e?_e.tileID:T,verticalScale:ue})}N.hasAnyZOffset=!1;let z=!1;for(let W=0;W{z in N&&(T[z]=N[z])}),T}function Xf(R){R=R.slice();const N=Object.create(null);for(const T of R)N[T.id]=T;for(let T=0;T0?(W-ee)/ue:0;return this.points[Q].mult(1-_e).add(this.points[T].mult(_e))}}class Qf{constructor(N,T,z){const W=this.boxCells=[],Q=this.circleCells=[];this.xCellCount=Math.ceil(N/z),this.yCellCount=Math.ceil(T/z);for(let ee=0;eethis.width||W<0||T>this.height)return!Q&&[];const ue=[];if(N<=0&&T<=0&&this.width<=z&&this.height<=W){if(Q)return!0;for(let _e=0;_e0:ue}_queryCircle(N,T,z,W,Q){const ee=N-z,ue=N+z,_e=T-z,Ee=T+z;if(ue<0||ee>this.width||Ee<0||_e>this.height)return!W&&[];const Ie=[];return this._forEachCell(ee,_e,ue,Ee,this._queryCellCircle,Ie,{hitTest:W,circle:{x:N,y:T,radius:z},seenUids:{box:{},circle:{}}},Q),W?Ie.length>0:Ie}query(N,T,z,W,Q){return this._query(N,T,z,W,!1,Q)}hitTest(N,T,z,W,Q){return this._query(N,T,z,W,!0,Q)}hitTestCircle(N,T,z,W){return this._queryCircle(N,T,z,!0,W)}_queryCell(N,T,z,W,Q,ee,ue,_e){const Ee=ue.seenUids,Ie=this.boxCells[Q];if(Ie!==null){const Ke=this.bboxes;for(const tt of Ie)if(!Ee.box[tt]){Ee.box[tt]=!0;const ut=4*tt;if(N<=Ke[ut+2]&&T<=Ke[ut+3]&&z>=Ke[ut+0]&&W>=Ke[ut+1]&&(!_e||_e(this.boxKeys[tt]))){if(ue.hitTest)return ee.push(!0),!0;ee.push({key:this.boxKeys[tt],x1:Ke[ut],y1:Ke[ut+1],x2:Ke[ut+2],y2:Ke[ut+3]})}}}const Je=this.circleCells[Q];if(Je!==null){const Ke=this.circles;for(const tt of Je)if(!Ee.circle[tt]){Ee.circle[tt]=!0;const ut=3*tt;if(this._circleAndRectCollide(Ke[ut],Ke[ut+1],Ke[ut+2],N,T,z,W)&&(!_e||_e(this.circleKeys[tt]))){if(ue.hitTest)return ee.push(!0),!0;{const lt=Ke[ut],kt=Ke[ut+1],Nt=Ke[ut+2];ee.push({key:this.circleKeys[tt],x1:lt-Nt,y1:kt-Nt,x2:lt+Nt,y2:kt+Nt})}}}}}_queryCellCircle(N,T,z,W,Q,ee,ue,_e){const Ee=ue.circle,Ie=ue.seenUids,Je=this.boxCells[Q];if(Je!==null){const tt=this.bboxes;for(const ut of Je)if(!Ie.box[ut]){Ie.box[ut]=!0;const lt=4*ut;if(this._circleAndRectCollide(Ee.x,Ee.y,Ee.radius,tt[lt+0],tt[lt+1],tt[lt+2],tt[lt+3])&&(!_e||_e(this.boxKeys[ut])))return ee.push(!0),!0}}const Ke=this.circleCells[Q];if(Ke!==null){const tt=this.circles;for(const ut of Ke)if(!Ie.circle[ut]){Ie.circle[ut]=!0;const lt=3*ut;if(this._circlesCollide(tt[lt],tt[lt+1],tt[lt+2],Ee.x,Ee.y,Ee.radius)&&(!_e||_e(this.circleKeys[ut])))return ee.push(!0),!0}}}_forEachCell(N,T,z,W,Q,ee,ue,_e){const Ee=this._convertToXCellCoord(N),Ie=this._convertToYCellCoord(T),Je=this._convertToXCellCoord(z),Ke=this._convertToYCellCoord(W);for(let tt=Ee;tt<=Je;tt++)for(let ut=Ie;ut<=Ke;ut++)if(Q.call(this,N,T,z,W,this.xCellCount*ut+tt,ee,ue,_e))return}_convertToXCellCoord(N){return Math.max(0,Math.min(this.xCellCount-1,Math.floor(N*this.xScale)))}_convertToYCellCoord(N){return Math.max(0,Math.min(this.yCellCount-1,Math.floor(N*this.yScale)))}_circlesCollide(N,T,z,W,Q,ee){const ue=W-N,_e=Q-T,Ee=z+ee;return Ee*Ee>ue*ue+_e*_e}_circleAndRectCollide(N,T,z,W,Q,ee,ue){const _e=(ee-W)/2,Ee=Math.abs(N-(W+_e));if(Ee>_e+z)return!1;const Ie=(ue-Q)/2,Je=Math.abs(T-(Q+Ie));if(Je>Ie+z)return!1;if(Ee<=_e||Je<=Ie)return!0;const Ke=Ee-_e,tt=Je-Ie;return Ke*Ke+tt*tt<=z*z}}const Dy=Math.tan(85*Math.PI/180);function dc(R,N,T,z,W,Q,ee){const ue=o.bb();if(T)if(Q.name==="globe"){const _e=o.bc(W,N);o.aD(ue,ue,_e)}else{const _e=o.bd([],ee);ue[0]=_e[0],ue[1]=_e[1],ue[4]=_e[2],ue[5]=_e[3],z||o.ba(ue,ue,W.angle)}else o.aD(ue,W.labelPlaneMatrix,R);return ue}function Nd(R,N,T,z,W,Q,ee){const ue=dc(R,N,T,z,W,Q,ee);return Q.name==="globe"&&T||(ue[2]=ue[6]=ue[10]=ue[14]=0),ue}function cf(R,N,T,z,W,Q,ee){if(T){if(Q.name==="globe"){const ue=dc(R,N,T,z,W,Q,ee);return o.b7(ue,ue),o.aD(ue,R,ue),ue}{const ue=o.b8(R),_e=o.b9([]);return _e[0]=ee[0],_e[1]=ee[1],_e[4]=ee[2],_e[5]=ee[3],o.aD(ue,ue,_e),z||o.ba(ue,ue,-W.angle),ue}}return W.glCoordMatrix}function iu(R,N,T,z){const W=[R,N,T,1];T?o.aE(W,W,z):Ar(W,W,z);const Q=W[3];return W[0]/=Q,W[1]/=Q,W[2]/=Q,W}function lp(R,N){return Math.min(.5+R/N*.5,1.5)}function Om(R,N){const T=R[0]/R[3],z=R[1]/R[3];return T>=-N[0]&&T<=N[0]&&z>=-N[1]&&z<=N[1]}function zm(R,N,T,z,W,Q,ee,ue,_e,Ee,Ie=1){const Je=T.transform,Ke=z?R.textSizeData:R.iconSizeData,tt=o.bj(Ke,T.transform.zoom,Ie),ut=Je.projection.name==="globe",lt=[256/T.width*2+1,256/T.height*2+1],kt=z?R.text.dynamicLayoutVertexArray:R.icon.dynamicLayoutVertexArray;kt.clear();let Nt=null;ut&&(Nt=z?R.text.globeExtVertexArray:R.icon.globeExtVertexArray);const zt=R.lineVertexArray,Yt=z?R.text.placedSymbolArray:R.icon.placedSymbolArray,Tt=T.transform.width/T.transform.height;let Ss,cs=!1;for(let Ns=0;NsMath.abs(T)?{useVertical:!0}:R===o.bk.vertical?z>0?{needsFlipping:!0}:null:N!==0&&function(W,Q){return W===0||Math.abs(Q/W)>Dy}(T,z)?N===1?{needsFlipping:!0}:null:T<0?{needsFlipping:!0}:null}function qs(R,N,T,z,W,Q,ee,ue,_e,Ee,Ie,Je,Ke,tt,ut,lt,kt,Nt,zt,Yt){const Tt=N/24,Ss=R.lineOffsetX*Tt,cs=R.lineOffsetY*Tt,{lineStartIndex:Ns,glyphStartIndex:Zt,numGlyphs:ns,segment:bs,writingMode:Ks,flipState:Es}=R,bn=Ns+R.lineLength,mn=zn=>{if(Ie){const[yn,_n,Tn]=zn.up,Nr=Ee.length;o.bm(Ie,Nr+0,yn,_n,Tn),o.bm(Ie,Nr+1,yn,_n,Tn),o.bm(Ie,Nr+2,yn,_n,Tn),o.bm(Ie,Nr+3,yn,_n,Tn)}const[Kn,sn,Fs]=zn.point;o.bn(Ee,Kn,sn,Fs,zn.angle)};if(ns>1){const zn=ot(Tt,ue,Ss,cs,T,Je,Ke,R,_e,Q,tt,lt,!1,kt,Nt,zt,Yt);if(!zn)return{notEnoughRoom:!0};if(z&&!T){let[Kn,sn,Fs]=zn.first.point,[yn,_n,Tn]=zn.last.point;[Kn,sn]=iu(Kn,sn,Fs,ee),[yn,_n]=iu(yn,_n,Tn,ee);const Nr=Jt(Ks,Es,(yn-Kn)*ut,_n-sn);if(R.flipState=Nr&&Nr.needsFlipping?1:2,Nr)return Nr}mn(zn.first);for(let Kn=Zt+1;Kn0?yn:An(Ke,Fs,Kn,1,W,void 0,kt,Nt.canonical),Tn=Jt(Ks,Es,(_n[0]-Kn[0])*ut,_n[1]-Kn[1]);if(R.flipState=Tn&&Tn.needsFlipping?1:2,Tn)return Tn}const zn=zr(Tt*ue.getoffsetX(Zt),Ss,cs,T,Je,Ke,bs,Ns,bn,_e,Q,tt,lt,!1,!1,kt,Nt,zt,Yt);if(!zn)return{notEnoughRoom:!0};mn(zn)}return{}}function Xs(R,N,T,z,W){const{x:Q,y:ee,z:ue}=z.projectTilePoint(R.x,R.y,N);if(!W)return iu(Q,ee,ue,T);const[_e,Ee,Ie]=W.getElevation(R,W.elevation,W.elevationFeature);return iu(Q+_e,ee+Ee,ue+Ie,T)}function An(R,N,T,z,W,Q,ee,ue){const _e=Xs(R.sub(N)._unit()._add(R),ue,W,ee,Q);return o.ax(_e,T,_e),o.ay(_e,_e),o.bg(_e,T,_e,z)}function zr(R,N,T,z,W,Q,ee,ue,_e,Ee,Ie,Je,Ke,tt,ut,lt,kt,Nt,zt){const Yt=z?R-N:R+N;let Tt=Yt>0?1:-1,Ss=0;z&&(Tt*=-1,Ss=Math.PI),Tt<0&&(Ss+=Math.PI);let cs=ue+ee+(Tt>0?0:1)|0,Ns=W,Zt=W,ns=0,bs=0;const Ks=Math.abs(Yt),Es=[],bn=[];let mn=Q,zn=mn,Kn=o.be([]);const sn=()=>An(zn,mn,Zt,Ks-ns+1,Ie,Ke,lt,kt.canonical);for(;ns+bs<=Ks;){if(cs+=Tt,cs=_e)return null;if(Zt=Ns,zn=mn,Es.push(Zt),tt&&bn.push(zn),mn=new o.P(Ee.getx(cs),Ee.gety(cs)),Ns=Je[cs],!Ns){const Aa=Xs(mn,kt.canonical,Ie,lt,Ke);Ns=Aa[3]>0?Je[cs]=Aa:sn()}ns+=bs;const Gn=o.ax([],Ns,Zt),pa=o.bf(Zt,Ns);if(T&&pa>0&&bs>0&&o.bi(Kn,Gn)/(bs*pa)0,Yt),Ns=Ee*cs.perspectiveRatio,Zt=(z.x1*T+ue.x-z.padding)*Ns+cs.point.x,ns=(z.y1*T+ue.y-z.padding)*Ns+cs.point.y,bs=(z.x2*T+ue.x+z.padding)*Ns+cs.point.x,Ks=(z.y2*T+ue.y+z.padding)*Ns+cs.point.y,Es=cs.perspectiveRatio<=.55||cs.occluded;return!this.isInsideGrid(Zt,ns,bs,Ks)||!_e&&this.grid.hitTest(Zt,ns,bs,Ks,Je)||Es?{box:[],offscreen:!1,occluded:cs.occluded}:{box:[Zt,ns,bs,Ks],offscreen:this.isOffscreen(Zt,ns,bs,Ks),occluded:!1}}placeCollisionCircles(N,T,z,W,Q,ee,ue,_e,Ee,Ie,Je,Ke,tt,ut,lt,kt){const Nt=[],zt=this.transform.elevation,Yt=N.getProjection(),Tt=N.elevationType==="road",Ss=!!zt||Tt,cs=o.bu.getAtTileOffsetFunc(kt,this.transform.center.lat,this.transform.worldSize,Yt),Ns=new o.P(z.tileAnchorX,z.tileAnchorY),Zt=new o.P(z.tileAnchorX,z.tileAnchorY);let{x:ns,y:bs,z:Ks}=Yt.projectTilePoint(Zt.x,Zt.y,kt.canonical),Es=null;if(Ss){const pa=Tt?N.getElevationFeatureForText(W):null;Es={getElevation:cs,elevation:zt,elevationFeature:pa};const[Aa,ta,ua]=cs(Ns,zt,pa);ns+=Aa,bs+=ta,Ks+=ua}const bn=Yt.name==="globe",mn=this.projectAndGetPerspectiveRatio(_e,ns,bs,Ks,kt,bn||!!zt||this.transform.pitch>0,Yt),{perspectiveRatio:zn}=mn,Kn=(Ke?ue/zn:ue*zn)/o.by,sn=iu(ns,bs,Ks,Ee),Fs=z.lineOffsetX*Kn,yn=z.lineOffsetY*Kn,_n=o.ap(N.layers[0].layout.get("text-max-angle")),Tn=Math.cos(_n),Nr=mn.signedDistanceFromCamera>0?ot(Kn,ee,Fs,yn,Tt&&z.flipState===1,sn,Zt,z,Q,Ee,{},Ss&&!Ke?Es:null,Ke&&Ss,Yt,kt,Ke,Tn):null;let hr=!1,mr=!1,Gn=!0;if(Nr&&!mn.occluded){const pa=.5*ut*zn+lt,Aa=new o.P(-100,-100),ta=new o.P(this.screenRightBoundary,this.screenBottomBoundary),ua=new qu,{first:ui,last:Ai}=Nr,ji=ui.path.length;let io=[];for(let Ni=ji-1;Ni>=1;Ni--)io.push(ui.path[Ni]);for(let Ni=1;Ni(Ss&&!bn&&(gc=cs(HdNi[3]<=0)&&(io=[]));let oo=[];if(io.length>0){let Ni=1/0,al=-1/0,gc=1/0,Hd=-1/0;for(const Fc of io)Ni=Math.min(Ni,Fc[0]),gc=Math.min(gc,Fc[1]),al=Math.max(al,Fc[0]),Hd=Math.max(Hd,Fc[1]);al>=Aa.x&&Ni<=ta.x&&Hd>=Aa.y&&gc<=ta.y&&(oo=[io.map(Fc=>new o.P(Fc[0],Fc[1]))],(Nita.x||gcta.y)&&(oo=o.bv(oo,Aa.x,Aa.y,ta.x,ta.y)))}for(const Ni of oo){ua.reset(Ni,.25*pa);let al=0;al=ua.length<=.5*pa?1:Math.ceil(ua.paddedLength/Qa)+1;for(let gc=0;gc0?(o.aE(_e,_e,N),this.fogState&&Q&&ue.name!=="globe"&&(Ee=function(Ke,tt,ut,lt,kt,Nt){const zt=Nt.calculateFogTileMatrix(kt),Yt=[tt,ut,lt];return o.ah(Yt,Yt,zt),Si(Ke,o.ai(Yt),Nt.pitch,Nt._fov)}(this.fogState,T,z,W,Q.toUnwrapped(),this.transform)>.9)):Ar(_e,_e,N);const Ie=_e[3];return{point:new o.P((_e[0]/Ie+1)/2*this.transform.width+wi,(-_e[1]/Ie+1)/2*this.transform.height+wi),perspectiveRatio:Math.min(.5+this.transform.getCameraToCenterDistance(ue)/Ie*.5,1.5),signedDistanceFromCamera:Ie,occluded:ee&&_e[2]>Ie||Ee}}isOffscreen(N,T,z,W){return z=this.screenRightBoundary||Wthis.screenBottomBoundary}isInsideGrid(N,T,z,W){return z>=0&&N=0&&Tz.collisionGroupID===T}}return this.collisionGroups[N]}}function tc(R,N,T,z,W){const{horizontalAlign:Q,verticalAlign:ee}=o.bF(R),ue=-(Q-.5)*N,_e=-(ee-.5)*T,Ee=o.bG(R,z);return new o.P(ue+Ee[0]*W,_e+Ee[1]*W)}function Hc(R,N,T,z,W){const Q=new o.P(R,N);return T&&Q._rotate(z?W:-W),Q}class ho{constructor(N,T,z,W,Q,ee){this.transform=N.clone(),this.projection=N.projection.name,this.collisionIndex=new Po(this.transform,Q),this.buildingIndex=ee,this.frontCutoffStart=0,this.placements={},this.opacities={},this.variableOffsets={},this.stale=!1,this.commitTime=0,this.fadeDuration=T,this.retainedQueryData={},this.collisionGroups=new Ci(z),this.collisionCircleArrays={},this.prevPlacement=W,W&&(W.prevPlacement=void 0),this.placedOrientations={},this.lastReplacementSourceUpdateTime=0}getBucketParts(N,T,z,W,Q=1){const ee=z.getBucket(T),ue=z.latestFeatureIndex;if(!ee||!ue||T.fqid!==ee.layerIds[0])return;const _e=ee.layers[0].layout,Ee=ee.layers[0].paint,Ie=z.collisionBoxArray,Je=Math.pow(2,this.transform.zoom-z.tileID.overscaledZ),Ke=z.tileSize/o.an,tt=z.tileID.toUnwrapped();this.transform.setProjection(ee.projection);const ut=(lt=z.tileID,kt=ee.getProjection(),Nt=this.transform,kt.name===this.projection?Nt.calculateProjMatrix(lt.toUnwrapped()):kh(Nt,kt,lt));var lt,kt,Nt;const zt=_e.get("text-pitch-alignment")==="map",Yt=_e.get("text-rotation-alignment")==="map";T.compileFilter(T.options);const Tt=T.dynamicFilter(),Ss=T.dynamicFilterNeedsFeature(),cs=T.dynamicFilterNeedsGeometry(),Ns=this.transform.calculatePixelsToTileUnitsMatrix(z),Zt=Nd(ut,z.tileID.canonical,zt,Yt,this.transform,ee.getProjection(),Ns);let ns=null;const bs=ee.getProjection().createInversionMatrix(this.transform,z.tileID.canonical);if(zt){const yn=cf(ut,z.tileID.canonical,zt,Yt,this.transform,ee.getProjection(),Ns);ns=o.aD([],this.transform.labelPlaneMatrix,yn)}let Ks=null;Tt&&z.latestFeatureIndex&&(Ks={unwrappedTileID:tt,dynamicFilter:Tt,dynamicFilterNeedsFeature:Ss,needGeometry:cs}),this.retainedQueryData[ee.bucketInstanceId]=new fi(ee.bucketInstanceId,ue,ee.sourceLayerIndex,ee.index,z.tileID);const[Es,bn]=ee.layers[0].layout.get("text-size-scale-range"),mn=o.aC(Q,Es,bn),[zn,Kn]=_e.get("icon-size-scale-range"),sn=o.aC(Q,zn,Kn),Fs={bucket:ee,layout:_e,paint:Ee,posMatrix:ut,invMatrix:bs,mercatorCenter:[o.aH(this.transform.center.lng),o.aL(this.transform.center.lat)],textLabelPlaneMatrix:Zt,labelToScreenMatrix:ns,clippingData:Ks,scale:Je,textPixelRatio:Ke,holdingForFade:z.holdingForFade(),collisionBoxArray:Ie,partiallyEvaluatedTextSize:o.bj(ee.textSizeData,this.transform.zoom,mn),partiallyEvaluatedIconSize:o.bj(ee.iconSizeData,this.transform.zoom,sn),collisionGroup:this.collisionGroups.get(ee.sourceID),latestFeatureIndex:z.latestFeatureIndex};if(W)for(const yn of ee.sortKeyRanges){const{sortKey:_n,symbolInstanceStart:Tn,symbolInstanceEnd:Nr}=yn;N.push({sortKey:_n,symbolInstanceStart:Tn,symbolInstanceEnd:Nr,parameters:Fs})}else N.push({symbolInstanceStart:0,symbolInstanceEnd:ee.symbolInstances.length,parameters:Fs})}attemptAnchorPlacement(N,T,z,W,Q,ee,ue,_e,Ee,Ie,Je,Ke,tt,ut,lt,kt,Nt,zt,Yt,Tt,Ss){const{textOffset0:cs,textOffset1:Ns,crossTileID:Zt}=lt,ns=[cs,Ns],bs=tc(N,ee,ue,ns,_e),Ks=this.collisionIndex.placeCollisionBox(Nt,_e,T,z,W,Q,Hc(bs.x,bs.y,Ee,Ie,this.transform.angle),ut,Je,Ke,tt.predicate);if(Yt){const Es=Nt.getSymbolInstanceIconSize(Ss,this.transform.zoom,lt.placedIconSymbolIndex);if(this.collisionIndex.placeCollisionBox(Nt,Es,Yt,z,W,Q,Hc(bs.x,bs.y,Ee,Ie,this.transform.angle),ut,Je,Ke,tt.predicate).box.length===0)return}if(Ks.box.length>0){let Es;return this.prevPlacement&&this.prevPlacement.variableOffsets[Zt]&&this.prevPlacement.placements[Zt]&&this.prevPlacement.placements[Zt].text&&(Es=this.prevPlacement.variableOffsets[Zt].anchor),this.variableOffsets[Zt]={textOffset:ns,width:ee,height:ue,anchor:N,textScale:_e,prevAnchor:Es},this.markUsedJustification(Nt,N,lt,zt),Nt.allowVerticalPlacement&&(this.markUsedOrientation(Nt,zt,lt),this.placedOrientations[Zt]=zt),{shift:bs,placedGlyphBoxes:Ks}}}placeLayerBucketPart(N,T,z,W,Q=1){const{bucket:ee,layout:ue,paint:_e,posMatrix:Ee,textLabelPlaneMatrix:Ie,labelToScreenMatrix:Je,clippingData:Ke,textPixelRatio:tt,mercatorCenter:ut,invMatrix:lt,holdingForFade:kt,collisionBoxArray:Nt,partiallyEvaluatedTextSize:zt,partiallyEvaluatedIconSize:Yt,collisionGroup:Tt,latestFeatureIndex:Ss}=N.parameters,cs=ue.get("text-optional"),Ns=ue.get("icon-optional"),Zt=ue.get("text-allow-overlap"),ns=ue.get("icon-allow-overlap"),bs=ue.get("text-rotation-alignment")==="map",Ks=ue.get("icon-rotation-alignment")==="map",Es=ue.get("text-pitch-alignment")==="map",bn=_e.get("symbol-z-offset"),mn=ue.get("symbol-elevation-reference")==="sea",zn=ue.get("symbol-placement"),[Kn,sn]=ue.get("text-size-scale-range"),[Fs,yn]=ue.get("icon-size-scale-range"),_n=o.aC(Q,Kn,sn),Tn=o.aC(Q,Fs,yn),Nr=ue.get("text-variable-anchor"),hr=bs&&zn!=="point",mr=Ks&&zn!=="point",Gn=Nr&&ee.hasTextData(),pa=ee.hasIconTextFit()&&Gn&&ee.hasIconData();this.transform.setProjection(ee.projection);const Aa=Gn||hr,ta=mr||pa;let ua=Zt&&(ns||!ee.hasIconData()||Ns),ui=ns&&(Zt||!ee.hasTextData()||cs);const Ai=!bn.isConstant();!ee.collisionArrays&&Nt&&ee.deserializeCollisionBoxes(Nt),z&&W&&ee.updateCollisionDebugBuffers(this.transform.zoom,Nt,_n,Tn);const ji=(Qa,oo,Ni)=>{const{crossTileID:al,numVerticalGlyphVertices:gc}=Qa;let Hd=null;if(Ke&&Ke.dynamicFilterNeedsFeature||Ai){const Wc=this.retainedQueryData[ee.bucketInstanceId],rd=Ss.loadFeature({featureIndex:Qa.featureIndex,bucketIndex:Wc.bucketIndex,sourceLayerIndex:Wc.sourceLayerIndex,layoutVertexArrayOffset:0}),ac=rd.properties?rd.properties.worldview:null;if(ee.localizable&&ee.worldview&&typeof ac=="string")if(ac==="all")rd.properties.$localized=!0;else{if(!ac.split(",").includes(ee.worldview))return;rd.properties.$localized=!0,rd.properties.worldview=ee.worldview}Hd=Ke&&Ke.needGeometry?o.bD(rd,!0):rd}if(Ke&&!(0,Ke.dynamicFilter)({zoom:this.transform.zoom,pitch:this.transform.pitch,worldview:ee.worldview},Hd,this.retainedQueryData[ee.bucketInstanceId].tileID.canonical,new o.P(Qa.tileAnchorX,Qa.tileAnchorY),this.transform.calculateDistanceTileData(Ke.unwrappedTileID)))return this.placements[al]=new cd(!1,!1,!1,!0),void T.add(al);const Fc=bn.evaluate(Hd,{});if((Qa.zOffset||0)+(Fc||0)>0&&this.frontCutoffStart>0){const Wc=2*this.frontCutoffStart-1,rd=[Qa.tileAnchorX,Qa.tileAnchorY,0,1],ac=o.aE(o.bE(),rd,Ee);if(ac[1]/ac[3]{Wc.tileID=this.retainedQueryData[ee.bucketInstanceId].tileID;const rd=this.transform.elevation;Wc.elevation=mn?Fc:Fc+o.bu.getAtTileOffset(Wc.tileID,new o.P(Wc.tileAnchorX,Wc.tileAnchorY),rd,qm),Wc.elevation+=Qa.zOffset},qv=Ni.textBox;if(qv){ff(qv);const Wc=ac=>{let gh=o.bk.horizontal;if(ee.allowVerticalPlacement&&!ac&&this.prevPlacement){const _g=this.prevPlacement.placedOrientations[al];_g&&(this.placedOrientations[al]=_g,gh=_g,this.markUsedOrientation(ee,gh,Qa))}return gh},rd=(ac,gh)=>{if(ee.allowVerticalPlacement&&gc>0&&Ni.verticalTextBox){for(const _g of ee.writingModes)if(_g===o.bk.vertical?(Ri=gh(),Pd=Ri):Ri=ac(),Ri&&Ri.box&&Ri.box.length)break}else Ri=ac()};if(Nr){let ac=Nr;if(this.prevPlacement&&this.prevPlacement.variableOffsets[al]){const Tu=this.prevPlacement.variableOffsets[al];ac.indexOf(Tu.anchor)>0&&(ac=ac.filter($v=>$v!==Tu.anchor),ac.unshift(Tu.anchor))}const gh=(Tu,$v,l5)=>{const t3=ee.getSymbolInstanceTextSize(zt,Qa,this.transform.zoom,oo),s3=(Tu.x2-Tu.x1)*t3+2*Tu.padding,rT=(Tu.y2-Tu.y1)*t3+2*Tu.padding,ak=Qa.hasIconTextFit&&!ns?$v:null;ak&&ff(ak);let o2={box:[],offscreen:!1,occluded:!1};const aT=Zt?2*ac.length:ac.length;for(let Ky=0;Ky=ac.length,Qa,oo,ee,l5,ak,zt,Yt);if(c5&&(o2=c5.placedGlyphBoxes,o2&&o2.box&&o2.box.length)){yl=!0,vl=c5.shift;break}}return o2};rd(()=>gh(qv,Ni.iconBox,o.bk.horizontal),()=>{const Tu=Ni.verticalTextBox;return Tu&&ff(Tu),ee.allowVerticalPlacement&&!(Ri&&Ri.box&&Ri.box.length)&&gc>0&&Tu?gh(Tu,Ni.verticalIconBox,o.bk.vertical):{box:null,offscreen:null,occluded:null}}),Ri&&(yl=Ri.box,Zi=Ri.offscreen,Oc=Ri.occluded);const _g=Wc(!(!Ri||!Ri.box));if(!yl&&this.prevPlacement){const Tu=this.prevPlacement.variableOffsets[al];Tu&&(this.variableOffsets[al]=Tu,this.markUsedJustification(ee,Tu.anchor,Qa,_g))}}else{const ac=(gh,_g)=>{const Tu=ee.getSymbolInstanceTextSize(zt,Qa,this.transform.zoom,oo),$v=this.collisionIndex.placeCollisionBox(ee,Tu,gh,ut,lt,Aa,new o.P(0,0),Zt,tt,Ee,Tt.predicate);return $v&&$v.box&&$v.box.length&&(this.markUsedOrientation(ee,_g,Qa),this.placedOrientations[al]=_g),$v};rd(()=>ac(qv,o.bk.horizontal),()=>{const gh=Ni.verticalTextBox;return ee.allowVerticalPlacement&&gc>0&&gh?(ff(gh),ac(gh,o.bk.vertical)):{box:null,offscreen:null,occluded:null}}),Wc(!!(Ri&&Ri.box&&Ri.box.length))}}if(yc=Ri,yl=yc&&yc.box&&yc.box.length>0,Zi=yc&&yc.offscreen,Oc=yc&&yc.occluded,Qa.useRuntimeCollisionCircles){const Wc=Qa.centerJustifiedTextSymbolIndex>=0?Qa.centerJustifiedTextSymbolIndex:Qa.verticalPlacedTextSymbolIndex,rd=ee.text.placedSymbolArray.get(Wc),ac=o.bl(ee.textSizeData,zt,rd),gh=ue.get("text-padding");Ph=this.collisionIndex.placeCollisionCircles(ee,Zt,rd,Wc,ee.lineVertexArray,ee.glyphOffsetArray,ac,Ee,Ie,Je,z,Es,Tt.predicate,Qa.collisionCircleDiameter*ac/o.by,gh,this.retainedQueryData[ee.bucketInstanceId].tileID),yl=Zt||Ph.circles.length>0&&!Ph.collisionDetected,Zi=Zi&&Ph.offscreen,Oc=Ph.occluded}if(Ni.iconFeatureIndex&&($x=Ni.iconFeatureIndex),Ni.iconBox){const Wc=rd=>{ff(rd);const ac=Qa.hasIconTextFit&&vl?Hc(vl.x,vl.y,bs,Es,this.transform.angle):new o.P(0,0),gh=ee.getSymbolInstanceIconSize(Yt,this.transform.zoom,Qa.placedIconSymbolIndex);return this.collisionIndex.placeCollisionBox(ee,gh,rd,ut,lt,ta,ac,ns,tt,Ee,Tt.predicate)};Pd&&Pd.box&&Pd.box.length&&Ni.verticalIconBox?(_o=Wc(Ni.verticalIconBox),Yi=_o.box.length>0):(_o=Wc(Ni.iconBox),Yi=_o.box.length>0),Zi=Zi&&_o.offscreen,cu=_o.occluded}const Hl=cs||Qa.numHorizontalGlyphVertices===0&&gc===0,z1=Ns||Qa.numIconVertices===0;if(Hl||z1?z1?Hl||(Yi=Yi&&yl):yl=Yi&&yl:Yi=yl=Yi&&yl,yl&&yc&&yc.box&&this.collisionIndex.insertCollisionBox(yc.box,ue.get("text-ignore-placement"),ee.bucketInstanceId,Pd&&Pd.box&&jm?jm:Tc,Tt.ID),Yi&&_o&&this.collisionIndex.insertCollisionBox(_o.box,ue.get("icon-ignore-placement"),ee.bucketInstanceId,$x,Tt.ID),Ph&&(yl&&this.collisionIndex.insertCollisionCircles(Ph.circles,ue.get("text-ignore-placement"),ee.bucketInstanceId,Tc,Tt.ID),z)){const Wc=ee.bucketInstanceId;let rd=this.collisionCircleArrays[Wc];rd===void 0&&(rd=this.collisionCircleArrays[Wc]=new $r);for(let ac=0;ac=0;--oo){const Ni=Qa[oo];ji(ee.symbolInstances.get(Ni),Ni,ee.collisionArrays[Ni])}ee.hasAnyZOffset&&o.w(`${ee.layerIds[0]} layer symbol-z-elevate: symbols are not sorted by elevation if symbol-z-order is evaluated to viewport-y`)}else if(ee.hasAnyZOffset){const Qa=ee.getSortedIndexesByZOffset();for(let oo=0;oo=0&&(N.text.placedSymbolArray.get(Q).crossTileID=Je>=0&&Q!==Je?0:Ee),ee>=0&&(N.text.placedSymbolArray.get(ee).crossTileID=Je>=0&&ee!==Je?0:Ee),ue>=0&&(N.text.placedSymbolArray.get(ue).crossTileID=Je>=0&&ue!==Je?0:Ee),_e>=0&&(N.text.placedSymbolArray.get(_e).crossTileID=Je>=0&&_e!==Je?0:Ee)}markUsedOrientation(N,T,z){const W=T===o.bk.horizontal||T===o.bk.horizontalOnly?T:0,Q=T===o.bk.vertical?T:0,{leftJustifiedTextSymbolIndex:ee,centerJustifiedTextSymbolIndex:ue,rightJustifiedTextSymbolIndex:_e,verticalPlacedTextSymbolIndex:Ee}=z,Ie=N.text.placedSymbolArray;ee>=0&&(Ie.get(ee).placedOrientation=W),ue>=0&&(Ie.get(ue).placedOrientation=W),_e>=0&&(Ie.get(_e).placedOrientation=W),Ee>=0&&(Ie.get(Ee).placedOrientation=Q)}commit(N){this.commitTime=N,this.zoomAtLastRecencyCheck=this.transform.zoom;const T=this.prevPlacement;let z=!1;this.prevZoomAdjustment=T?T.zoomAdjustment(this.transform.zoom):0;const W=T?T.symbolFadeChange(N):1,Q=T?T.opacities:{},ee=T?T.variableOffsets:{},ue=T?T.placedOrientations:{};for(const _e in this.placements){const Ee=this.placements[_e],Ie=Q[_e];Ie?(this.opacities[_e]=new Vl(Ie,W,Ee.text,Ee.icon,null,Ee.clipped),z=z||Ee.text!==Ie.text.placed||Ee.icon!==Ie.icon.placed):(this.opacities[_e]=new Vl(null,W,Ee.text,Ee.icon,Ee.skipFade,Ee.clipped),z=z||Ee.text||Ee.icon)}for(const _e in Q){const Ee=Q[_e];if(!this.opacities[_e]){const Ie=new Vl(Ee,W,!1,!1);Ie.isHidden()||(this.opacities[_e]=Ie,z=z||Ee.text.placed||Ee.icon.placed)}}for(const _e in ee)this.variableOffsets[_e]||!this.opacities[_e]||this.opacities[_e].isHidden()||(this.variableOffsets[_e]=ee[_e]);for(const _e in ue)this.placedOrientations[_e]||!this.opacities[_e]||this.opacities[_e].isHidden()||(this.placedOrientations[_e]=ue[_e]);z?this.lastPlacementChangeTime=N:typeof this.lastPlacementChangeTime!="number"&&(this.lastPlacementChangeTime=T?T.lastPlacementChangeTime:N)}updateLayerOpacities(N,T,z,W){W&&(this.lastReplacementSourceUpdateTime=W.updateTime);const Q=new Set;for(const ee of T){const ue=ee.getBucket(N);ue&&ee.latestFeatureIndex&&N.fqid===ue.layerIds[0]&&(this.updateBucketOpacities(ue,Q,ee,ee.collisionBoxArray,z,W,ee.tileID,N.scope),ue.elevationType==="offset"&&this.buildingIndex&&this.buildingIndex.updateZOffset(ue,ee.tileID),ue.elevationType==="road"&&ue.updateRoadElevation(ee.tileID.canonical),ue.updateZOffset())}}updateBucketOpacities(N,T,z,W,Q,ee,ue,_e){N.hasTextData()&&N.text.opacityVertexArray.clear(),N.hasIconData()&&N.icon.opacityVertexArray.clear(),N.hasIconCollisionBoxData()&&N.iconCollisionBox.collisionVertexArray.clear(),N.hasTextCollisionBoxData()&&N.textCollisionBox.collisionVertexArray.clear();const Ee=N.layers[0].layout,Ie=N.layers[0].paint,Je=!!N.layers[0].dynamicFilter(),Ke=new Vl(null,0,!1,!1,!0),tt=Ee.get("text-allow-overlap"),ut=Ee.get("icon-allow-overlap"),lt=Ee.get("text-variable-anchor"),kt=Ee.get("text-rotation-alignment")==="map",Nt=Ee.get("text-pitch-alignment")==="map",zt=Ie.get("symbol-z-offset"),Yt=Ee.get("symbol-elevation-reference")==="sea",Tt=!zt.isConstant(),Ss=new Vl(null,0,tt&&(ut||!N.hasIconData()||Ee.get("icon-optional")),ut&&(tt||!N.hasTextData()||Ee.get("text-optional")),!0);!N.collisionArrays&&W&&(N.hasIconCollisionBoxData()||N.hasTextCollisionBoxData())&&N.deserializeCollisionBoxes(W);const cs=(Zt,ns,bs)=>{for(let Ks=0;Ks0||Ks>0,Nr=bn>0,hr=this.placedOrientations[Es],mr=hr===o.bk.vertical,Gn=hr===o.bk.horizontal||hr===o.bk.horizontalOnly;!Tn&&!Nr||_n.isHidden()||Ns++;let pa=!1;if((Tn||Nr)&&ee)for(const Aa of N.activeReplacements){if(o.bz(Aa,Q,o.bA.Symbol,_e)||Aa.min.x>mn||mn>Aa.max.x||Aa.min.y>zn||zn>Aa.max.y)continue;const ta=o.bB(mn,zn,ue.canonical,Aa.footprintTileId.canonical);if(pa=o.bC(ta,Aa.footprint),pa)break}if(pa&&this.collisionIndex.markSymbolAsClipped(N.bucketInstanceId,ns.featureIndex),Tn){const Aa=pa?Jc:_i(_n.text);cs(N.text,bs,mr?Jc:Aa),cs(N.text,Ks,Gn?Jc:Aa);const ta=_n.text.isHidden(),{leftJustifiedTextSymbolIndex:ua,centerJustifiedTextSymbolIndex:ui,rightJustifiedTextSymbolIndex:Ai,verticalPlacedTextSymbolIndex:ji}=ns,io=N.text.placedSymbolArray,Qa=ta||mr?1:0;ua>=0&&(io.get(ua).hidden=Qa),ui>=0&&(io.get(ui).hidden=Qa),Ai>=0&&(io.get(Ai).hidden=Qa),ji>=0&&(io.get(ji).hidden=ta||Gn?1:0);const oo=this.variableOffsets[Es];oo&&this.markUsedJustification(N,oo.anchor,ns,hr);const Ni=this.placedOrientations[Es];Ni&&(this.markUsedJustification(N,"left",ns,Ni),this.markUsedOrientation(N,Ni,ns))}if(Nr){const Aa=pa?Jc:_i(_n.icon),{placedIconSymbolIndex:ta,verticalPlacedIconSymbolIndex:ua}=ns,ui=N.icon.placedSymbolArray,Ai=_n.icon.isHidden()?1:0;ta>=0&&(cs(N.icon,bn,mr?Jc:Aa),ui.get(ta).hidden=Ai),ua>=0&&(cs(N.icon,ns.numVerticalIconVertices,Gn?Jc:Aa),ui.get(ua).hidden=Ai)}if(N.hasIconCollisionBoxData()||N.hasTextCollisionBoxData()){const Aa=N.collisionArrays[Zt];if(Aa){let ta=new o.P(0,0),ua=!0;if(Aa.textBox||Aa.verticalTextBox){if(lt){const Ai=this.variableOffsets[Es];Ai?(ta=tc(Ai.anchor,Ai.width,Ai.height,Ai.textOffset,Ai.textScale),kt&&ta._rotate(Nt?this.transform.angle:-this.transform.angle)):ua=!1}Je&&(ua=!_n.clipped),Aa.textBox&&Xh(N.textCollisionBox.collisionVertexArray,_n.text.placed,!ua||mr,Fs,Yt,ta.x,ta.y),Aa.verticalTextBox&&Xh(N.textCollisionBox.collisionVertexArray,_n.text.placed,!ua||Gn,Fs,Yt,ta.x,ta.y)}const ui=ua&&!!(!Gn&&Aa.verticalIconBox);Aa.iconBox&&Xh(N.iconCollisionBox.collisionVertexArray,_n.icon.placed,ui,Fs,Yt,ns.hasIconTextFit?ta.x:0,ns.hasIconTextFit?ta.y:0),Aa.verticalIconBox&&Xh(N.iconCollisionBox.collisionVertexArray,_n.icon.placed,!ui,Fs,Yt,ns.hasIconTextFit?ta.x:0,ns.hasIconTextFit?ta.y:0)}}}if(N.fullyClipped=Ns===0,N.sortFeatures(this.transform.angle),this.retainedQueryData[N.bucketInstanceId]&&(this.retainedQueryData[N.bucketInstanceId].featureSortOrder=N.featureSortOrder),N.hasTextData()&&N.text.opacityVertexBuffer&&N.text.opacityVertexBuffer.updateData(N.text.opacityVertexArray),N.hasIconData()&&N.icon.opacityVertexBuffer&&N.icon.opacityVertexBuffer.updateData(N.icon.opacityVertexArray),N.hasIconCollisionBoxData()&&N.iconCollisionBox.collisionVertexBuffer&&N.iconCollisionBox.collisionVertexBuffer.updateData(N.iconCollisionBox.collisionVertexArray),N.hasTextCollisionBoxData()&&N.textCollisionBox.collisionVertexBuffer&&N.textCollisionBox.collisionVertexBuffer.updateData(N.textCollisionBox.collisionVertexArray),N.bucketInstanceId in this.collisionCircleArrays){const Zt=this.collisionCircleArrays[N.bucketInstanceId];N.placementInvProjMatrix=Zt.invProjMatrix,N.placementViewportMatrix=Zt.viewportMatrix,N.collisionCircleArray=Zt.circles,delete this.collisionCircleArrays[N.bucketInstanceId]}}symbolFadeChange(N){return this.fadeDuration===0?1:(N-this.commitTime)/this.fadeDuration+this.prevZoomAdjustment}zoomAdjustment(N){return Math.max(0,(this.transform.zoom-N)/1.5)}hasTransitions(N){return N-this.lastPlacementChangeTimeN}isStale(){return this.stale}setStale(){this.stale=!0}}function Xh(R,N,T,z,W,Q,ee){R.emplaceBack(N?1:0,T?1:0,Q||0,ee||0,z,W?1:0),R.emplaceBack(N?1:0,T?1:0,Q||0,ee||0,z,W?1:0),R.emplaceBack(N?1:0,T?1:0,Q||0,ee||0,z,W?1:0),R.emplaceBack(N?1:0,T?1:0,Q||0,ee||0,z,W?1:0)}const $t=Math.pow(2,25),Nn=Math.pow(2,24),Un=Math.pow(2,17),qr=Math.pow(2,16),Ea=Math.pow(2,9),gi=Math.pow(2,8),Mi=Math.pow(2,1);function _i(R){if(R.opacity===0&&!R.placed)return 0;if(R.opacity===1&&R.placed)return 4294967295;const N=R.placed?1:0,T=Math.floor(127*R.opacity);return T*$t+N*Nn+T*Un+N*qr+T*Ea+N*gi+T*Mi+N}const Jc=0;class Su{constructor(N){this._sortAcrossTiles=N.layout.get("symbol-z-order")!=="viewport-y"&&N.layout.get("symbol-sort-key").constantOr(1)!==void 0,this._currentTileIndex=0,this._currentPartIndex=0,this._seenCrossTileIDs=new Set,this._bucketParts=[]}continuePlacement(N,T,z,W,Q,ee){const ue=this._bucketParts;for(;this._currentTileIndex_e.sortKey-Ee.sortKey));this._currentPartIndex{const _e=o.o.now()-ee;return!this.isFullPlacementRequested()&&this._fadeDuration!==0&&_e>2};for(;this._currentPlacementIndex>=0;){const _e=T[N[this._currentPlacementIndex]],Ee=this.placement.collisionIndex.transform.zoom;if(_e.type==="symbol"&&_e.visibility!=="none"&&(!_e.minzoom||_e.minzoom<=Ee)&&(!_e.maxzoom||_e.maxzoom>Ee)){const Ie=_e,Je=Ie.layout.get("symbol-z-elevate"),Ke=Ie.layout.get("symbol-sort-key").constantOr(1)!==void 0,tt=Ie.layout.get("symbol-z-order"),ut=tt==="viewport-y"||tt==="auto"&&!(tt!=="viewport-y"&&Ke),lt=Ie.layout.get("text-allow-overlap")||Ie.layout.get("icon-allow-overlap")||Ie.layout.get("text-ignore-placement")||Ie.layout.get("icon-ignore-placement"),kt=ut&<,Nt=this._inProgressLayer=this._inProgressLayer||new Su(Ie),zt=o.F(_e.source,_e.scope);if(Nt.continuePlacement(Je||kt?W[zt]:z[zt],this.placement,this._showCollisionBoxes,_e,ue,Q))return;delete this._inProgressLayer}this._currentPlacementIndex--}this._forceFullPlacement=!1,this._done=!0}commit(N){return this.placement.commit(N),this.placement}}const dd=512/o.an/2;class Ud{constructor(N,T,z){this.tileID=N,this.bucketInstanceId=z,this.index=new o.bI(T.length,16,Int32Array),this.keys=[],this.crossTileIDs=[];const W=N.canonical.x*o.an,Q=N.canonical.y*o.an;for(let ee=0;eekt-Nt);for(const kt of lt){const Nt=this.crossTileIDs[kt];if(this.keys[kt]===Ie&&!z.has(Nt)){z.add(Nt),Ee.crossTileID=Nt;break}}}}}class Ch{constructor(){this.maxCrossTileID=0}generate(){return++this.maxCrossTileID}}class Pp{constructor(){this.indexes={},this.usedCrossTileIDs={},this.lng=0}handleWrapJump(N){const T=Math.round((N-this.lng)/360);if(T!==0)for(const z in this.indexes){const W=this.indexes[z],Q={};for(const ee in W){const ue=W[ee];ue.tileID=ue.tileID.unwrapTo(ue.tileID.wrap+T),Q[ue.tileID.key]=ue}this.indexes[z]=Q}this.lng=N}addBucket(N,T,z){if(this.indexes[N.overscaledZ]&&this.indexes[N.overscaledZ][N.key]){if(this.indexes[N.overscaledZ][N.key].bucketInstanceId===T.bucketInstanceId)return!1;this.removeBucketCrossTileIDs(N.overscaledZ,this.indexes[N.overscaledZ][N.key])}for(let Q=0;QN.overscaledZ)for(const ue in ee){const _e=ee[ue];_e.tileID.isChildOf(N)&&_e.findMatches(T.symbolInstances,N,W)}else{const ue=ee[N.scaledTo(Number(Q)).key];ue&&ue.findMatches(T.symbolInstances,N,W)}}for(let Q=0;Q{T[z]=!0});for(const z in this.layerIndexes)T[z]||delete this.layerIndexes[z]}}const sc=771;class Ba{constructor(N,T,z,W){this.blendFunction=N,this.blendColor=T.toNonPremultipliedRenderColor(null),this.mask=z,this.blendEquation=W}}Ba.Replace=[1,0,1,0],Ba.disabled=new Ba(Ba.Replace,o.aq.transparent,[!1,!1,!1,!1]),Ba.unblended=new Ba(Ba.Replace,o.aq.transparent,[!0,!0,!0,!0]),Ba.alphaBlended=new Ba([1,sc,1,sc],o.aq.transparent,[!0,!0,!0,!0]),Ba.alphaBlendedNonPremultiplied=new Ba([770,sc,770,sc],o.aq.transparent,[!0,!0,!0,!0]),Ba.multiply=new Ba([774,0,774,0],o.aq.transparent,[!0,!0,!0,!0]),Ba.multiplyAccumulateAlpha=new Ba([774,0,1,sc],o.aq.transparent,[!0,!0,!0,!0]),Ba.additive=new Ba([1,1,1,1],o.aq.transparent,[!0,!0,!0,!0]);class Hr{constructor(N,T,z){this.func=N,this.mask=T,this.range=z}}Hr.ReadOnly=!1,Hr.ReadWrite=!0,Hr.disabled=new Hr(519,Hr.ReadOnly,[0,1]);const Cc=7680;class qa{constructor(N,T,z,W,Q,ee){this.test=N,this.ref=T,this.mask=z,this.fail=W,this.depthFail=Q,this.pass=ee}}qa.disabled=new qa({func:519,mask:0},0,0,Cc,Cc,Cc);const Lp=1029,ou=2305;class va{constructor(N,T,z){this.enable=N,this.mode=T,this.frontFace=z}}function Wg(R,N){const T=o.bO(R,3);o.bR(R,N),o.bW(R,3,T)}function U0(R,N){const T=o.bL([]);return o.bM(T,T,-N),o.bN(T,T,-R),T}function gg(R,N){const T=[R[0],R[1],0],z=[N[0],N[1],0];if(o.ai(T)>=1e-15){const ee=o.ay([],T);o.bJ(z,ee,o.bi(z,ee)),N[0]=z[0],N[1]=z[1]}const W=o.bh([],N,R);if(o.bK(W)<1e-15)return null;const Q=Math.atan2(-W[1],W[0]);return U0(Math.atan2(Math.sqrt(R[0]*R[0]+R[1]*R[1]),-R[2]),Q)}va.disabled=new va(!1,Lp,ou),va.backCCW=new va(!0,Lp,ou),va.backCW=new va(!0,Lp,2304),va.frontCW=new va(!0,1028,2304),va.frontCCW=new va(!0,1028,ou);class Ry{constructor(N,T){this.position=N,this.orientation=T}get position(){return this._position}set position(N){if(N){const T=N instanceof o.ag?N:new o.ag(N[0],N[1],N[2]);this._renderWorldCopies&&(T.x=o.bs(T.x,0,1)),this._position=T}else this._position=null}lookAtPoint(N,T,z){if(this.orientation=null,!this.position)return;const W=this.position,Q=z||(this._elevation?this._elevation.getAtPointOrZero(o.ag.fromLngLat(N)):0),ee=o.ag.fromLngLat(N,Q),ue=[ee.x-W.x,ee.y-W.y,ee.z-W.z];T||(T=[0,0,1]),T[2]=Math.abs(T[2]),this.orientation=gg(ue,T)}setPitchBearing(N,T){this.orientation=U0(o.ap(N),o.ap(-T))}}class Ox{constructor(N,T){this._transform=o.b9([]),this.orientation=T,this.position=N}get mercatorPosition(){const N=this.position;return new o.ag(N[0],N[1],N[2])}get position(){const N=o.bO(this._transform,3);return[N[0],N[1],N[2]]}set position(N){var T;N&&o.bW(this._transform,3,[(T=N)[0],T[1],T[2],1])}get orientation(){return this._orientation}set orientation(N){this._orientation=N||o.bL([]),N&&Wg(this._transform,this._orientation)}getPitchBearing(){const N=this.forward(),T=this.right();return{bearing:Math.atan2(-T[1],T[0]),pitch:Math.atan2(Math.sqrt(N[0]*N[0]+N[1]*N[1]),-N[2])}}setPitchBearing(N,T){this._orientation=U0(N,T),Wg(this._transform,this._orientation)}forward(){const N=o.bO(this._transform,2);return[-N[0],-N[1],-N[2]]}up(){const N=o.bO(this._transform,1);return[-N[0],-N[1],-N[2]]}right(){const N=o.bO(this._transform,0);return[N[0],N[1],N[2]]}getCameraToWorld(N,T){const z=new Float64Array(16);return o.b7(z,this.getWorldToCamera(N,T)),z}getCameraToWorldMercator(){return this._transform}getWorldToCameraPosition(N,T,z){const W=this.position;o.bJ(W,W,-N);const Q=new Float64Array(16);return o.bP(Q,[z,z,z]),o.bx(Q,Q,W),Q[10]*=T,Q}getWorldToCamera(N,T){const z=new Float64Array(16),W=new Float64Array(4),Q=this.position;return o.bQ(W,this._orientation),o.bJ(Q,Q,-N),o.bR(z,W),o.bx(z,z,Q),z[1]*=-1,z[5]*=-1,z[9]*=-1,z[13]*=-1,z[8]*=T,z[9]*=T,z[10]*=T,z[11]*=T,z}getCameraToClipPerspective(N,T,z,W){const Q=new Float64Array(16);return o.bS(Q,N,T,z,W),Q}getCameraToClipOrthographic(N,T,z,W,Q,ee){const ue=new Float64Array(16);return o.bT(ue,N,T,z,W,Q,ee),ue}getDistanceToElevation(N,T=!1){const z=N===0?0:o.bU(N,T?o.bV(this.position[1]):this.position[1]),W=this.forward();return(z-this.position[2])/W[2]}clone(){return new Ox([...this.position],[...this.orientation])}}const Td=(R,N)=>({u_matrix:R,u_ground_shadow_factor:N});class df{constructor(N=0,T=0,z=0,W=0){if(isNaN(N)||N<0||isNaN(T)||T<0||isNaN(z)||z<0||isNaN(W)||W<0)throw new Error("Invalid value for edge-insets, top, bottom, left and right must all be numbers");this.top=N,this.bottom=T,this.left=z,this.right=W}interpolate(N,T,z){return T.top!=null&&N.top!=null&&(this.top=o.am(N.top,T.top,z)),T.bottom!=null&&N.bottom!=null&&(this.bottom=o.am(N.bottom,T.bottom,z)),T.left!=null&&N.left!=null&&(this.left=o.am(N.left,T.left,z)),T.right!=null&&N.right!=null&&(this.right=o.am(N.right,T.right,z)),this}getCenter(N,T){const z=o.aC((this.left+N-this.right)/2,0,N),W=o.aC((this.top+T-this.bottom)/2,0,T);return new o.P(z,W)}equals(N){return this.top===N.top&&this.bottom===N.bottom&&this.left===N.left&&this.right===N.right}clone(){return new df(this.top,this.bottom,this.left,this.right)}toJSON(){return{top:this.top,bottom:this.bottom,left:this.left,right:this.right}}}const ym=15;class hh{constructor(N,T,z,W,Q,ee,ue){this.tileSize=512,this._renderWorldCopies=Q===void 0||Q,this._minZoom=N||0,this._maxZoom=T||22,this._minPitch=z??0,this._maxPitch=W??60,this.setProjection(ee),this.setMaxBounds(ue),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 df,this._projMatrixCache={},this._alignedProjMatrixCache={},this._fogTileMatrixCache={},this._expandedProjMatrixCache={},this._distanceTileDataCache={},this._camera=new Ox,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 N=new hh(this._minZoom,this._maxZoom,this._minPitch,this.maxPitch,this._renderWorldCopies,this.getProjection(),this.maxBounds);return N._elevation=this._elevation,N._centerAltitude=this._centerAltitude,N._centerAltitudeValidForExaggeration=this._centerAltitudeValidForExaggeration,N.tileSize=this.tileSize,N.mercatorFromTransition=this.mercatorFromTransition,N.width=this.width,N.height=this.height,N.cameraElevationReference=this.cameraElevationReference,N._center=this._center,N._setZoom(this.zoom),N._seaLevelZoom=this._seaLevelZoom,N.angle=this.angle,N._fov=this._fov,N._pitch=this._pitch,N._nearZ=this._nearZ,N._farZ=this._farZ,N._nearClipOffset=this._nearClipOffset,N._averageElevation=this._averageElevation,N._orthographicProjectionAtLowPitch=this._orthographicProjectionAtLowPitch,N._unmodified=this._unmodified,N._edgeInsets=this._edgeInsets.clone(),N._camera=this._camera.clone(),N._calcMatrices(),N.freezeTileCoverage=this.freezeTileCoverage,N.frustumCorners=this.frustumCorners,N._allowWorldUnderZoom=this._allowWorldUnderZoom,N}get isOrthographic(){return this.projection.name!=="globe"&&this._orthographicProjectionAtLowPitch&&this.pitch0&&this.elevation.exaggeration()>0&&this._centerAltitudeValidForExaggeration;if(!this._elevation||N===Number.NEGATIVE_INFINITY&&(!T||!this._centerAltitude))return this._centerAltitude=0,this._seaLevelZoom=null,void(this._centerAltitudeValidForExaggeration=void 0);const z=this._elevation;T||this._centerAltitude&&this._centerAltitudeValidForExaggeration&&z.exaggeration()&&this._centerAltitudeValidForExaggeration!==z.exaggeration()?(this._centerAltitude=this._centerAltitude/this._centerAltitudeValidForExaggeration*z.exaggeration(),this._centerAltitudeValidForExaggeration=z.exaggeration()):(this._centerAltitude=N||0,this._centerAltitudeValidForExaggeration=z.exaggeration()),this._updateSeaLevelZoom()}_updateSeaLevelZoom(){if(this._centerAltitudeValidForExaggeration===void 0)return;const N=Math.max(0,(this.pixelsPerMeter*this._centerAltitude+this.cameraToCenterDistance)/this.worldSize);this._seaLevelZoom=this._zoomFromMercatorZ(N)}sampleAverageElevation(){if(!this._elevation)return 0;const N=this._elevation,T=[[.5,.2],[.3,.5],[.5,.5],[.7,.5],[.5,.8]],z=this.horizonLineFromTop();let W=0,Q=0;for(let ee=0;ee{const kt=o.ck(Ke,Je,tt,ut,lt);_e.has(kt)||(Q.push(new o.aR(Je,Ke,tt,ut,lt)),_e.add(kt))};for(let Je=0;JeKe.canonical.z)continue;const tt=Ke.canonical,ut=Ke.overscaledZ,lt=Ke.wrap,kt=1<0,Yt=tt.y+10,Ss=Ke.wrap-(zt?0:1),cs=Ke.wrap+(Nt?0:1),Ns=zt?tt.x-1:kt-1,Zt=Nt?tt.x+1:0;if(ee)z[0]<0?(Ee(ut,cs,tt.z,Zt,tt.y),z[1]<0&&Yt&&(Ee(ut,lt,tt.z,tt.x,tt.y+1),Ee(ut,cs,tt.z,Zt,tt.y+1)),z[1]>0&&Tt&&(Ee(ut,lt,tt.z,tt.x,tt.y-1),Ee(ut,cs,tt.z,Zt,tt.y-1))):z[0]>0?(Ee(ut,Ss,tt.z,Ns,tt.y),z[1]<0&&Yt&&(Ee(ut,lt,tt.z,tt.x,tt.y+1),Ee(ut,Ss,tt.z,Ns,tt.y+1)),z[1]>0&&Tt&&(Ee(ut,lt,tt.z,tt.x,tt.y-1),Ee(ut,Ss,tt.z,Ns,tt.y-1))):z[1]<0&&Yt?Ee(ut,lt,tt.z,tt.x,tt.y+1):Tt&&Ee(ut,lt,tt.z,tt.x,tt.y-1);else{const ns=Ke.visibleQuadrants;1&ns&&(Ee(ut,Ss,tt.z,Ns,tt.y),Tt&&(Ee(ut,lt,tt.z,tt.x,tt.y-1),Ee(ut,Ss,tt.z,Ns,tt.y-1))),2&ns&&(Ee(ut,cs,tt.z,Zt,tt.y),Tt&&(Ee(ut,lt,tt.z,tt.x,tt.y-1),Ee(ut,cs,tt.z,Zt,tt.y-1))),4&ns&&(Ee(ut,Ss,tt.z,Ns,tt.y),Yt&&(Ee(ut,lt,tt.z,tt.x,tt.y+1),Ee(ut,Ss,tt.z,Ns,tt.y+1))),8&ns&&(Ee(ut,cs,tt.z,Zt,tt.y),Yt&&(Ee(ut,lt,tt.z,tt.x,tt.y+1),Ee(ut,cs,tt.z,Zt,tt.y+1)))}}const Ie=[];for(const Je of Q)Q.some(Ke=>Je.isChildOf(Ke))||Ie.push(Je);if(Q=Ie.filter(Je=>!N.some(Ke=>!!(Je.overscaledZ{const Nt=kt.canonical.x+.5-tt[0],zt=kt.canonical.y+.5-tt[1];return Nt*Nt+zt*zt{const Ns=o.ck(Yt,zt,Tt,Ss,cs);Q.has(Ns)||(W.push(new o.aR(zt,Yt,Tt,Ss,cs)),Q.add(Ns))},ue=N.reduce((zt,Yt)=>Math.max(zt,Yt.overscaledZ),z),_e=1<{const Tt=Math.floor(zt[0]),Ss=Math.floor(zt[1]),cs=(zt[0]-Tt)*o.an,Ns=(zt[1]-Ss)*o.an,Zt=Math.floor(Yt[0]),ns=Math.floor(Yt[1]),bs=(Yt[0]-Zt)*o.an,Ks=(Yt[1]-ns)*o.an;for(let Es=-1;Es<=1;Es++){const bn=Tt+Es;if(!(bn<0||bn>=_e)){Ie.x=cs-Es*o.an,Je.x=bs-(bn-Zt)*o.an;for(let mn=-1;mn<=1;mn++){const zn=Ss+mn;Ie.y=Ns-mn*o.an,Je.y=Ks-(zn-ns)*o.an,o.cI(Ie,Je,Ee)&&ee(ue,0,z,bn,zn)}}}},tt=T.points,ut=tt[o.c9],lt=tt[o.ca],kt=this._projectToGround(ut,tt[o.cb]),Nt=this._projectToGround(lt,tt[o.cc]);return Ke(ut,kt),Ke(lt,Nt),W}_projectToGround(N,T){return o.cd(o.ce(),N,T,N[2]/(N[2]-T[2]))}_projectToZ(N,T,z){const W=N[2]-T[2];return Math.abs(W)<1e-6?o.cf(N):o.cd(o.ce(),N,T,(N[2]-z)/W)}extendTileCoverForTunnels(N,T,z,W){if(z<18)return[];const Q=T.points,ee=Q[o.cg],ue=Q[o.ch],_e=Q[o.ci],Ee=Q[o.cj];if(_e[2]>=0&&Ee[2]>=0||ee[2]<=0||ue[2]<=0)return[];const Ie=_e[2]<0?this._projectToZ(ee,_e,0):_e,Je=Ee[2]<0?this._projectToZ(ue,Ee,0):Ee,Ke=-W,tt=_e[2]3&&(lt.length=3),lt}_findExtensionTilesInQuad(N,T,z,W){const Q=[],ee=new Set;for(const Zt of N)ee.add(Zt.key);const ue=N.reduce((Zt,ns)=>Math.max(Zt,ns.overscaledZ),T),_e=1<{const bs=Zt.canonical.x+.5-cs,Ks=Zt.canonical.y+.5-Ns,Es=ns.canonical.x+.5-cs,bn=ns.canonical.y+.5-Ns;return bs*bs+Ks*Ks-(Es*Es+bn*bn)||Zt.canonical.x-ns.canonical.x||Zt.canonical.y-ns.canonical.y}),Q}coveringTiles(N){let T=this.coveringZoomLevel(N);const z=T,W=this.elevation&&this.elevation.exaggeration(),Q=W&&!N.isTerrainDEM,ee=this.projection.name==="mercator";if(N.minzoom!==void 0&&TN.maxzoom&&(T=N.maxzoom);const ue=this.locationCoordinate(this.center),_e=this.center.lat,Ee=1<{const _n=new o.ag(Fs.x+25e-6,Fs.y,Fs.z),Tn=new o.ag(Fs.x,Fs.y+25e-6,Fs.z),Nr=Fs.toLngLat(),hr=_n.toLngLat(),mr=Tn.toLngLat(),Gn=this.locationCoordinate(Nr),pa=this.locationCoordinate(hr),Aa=this.locationCoordinate(mr),ta=Math.hypot(pa.x-Gn.x,pa.y-Gn.y),ua=Math.hypot(Aa.x-Gn.x,Aa.y-Gn.y);return Math.sqrt(ta*ua)*Ns/25e-6},ns=Fs=>{const yn=Ss,_n=cs;return{aabb:o.cp(this,Ee,0,0,0,Fs,_n,yn,this.projection),zoom:0,x:0,y:0,minZ:_n,maxZ:yn,wrap:Fs,fullyVisible:!1}},bs=[];let Ks=[];const Es=T,bn=N.reparseOverscaled?z:T,mn=(kt-this._centerAltitude)*lt,zn=Fs=>{if(!this._elevation||!Fs.tileID||!ee)return;const yn=this._elevation.getMinMaxForTile(Fs.tileID),_n=Fs.aabb;yn?(_n.min[2]=yn.min,_n.max[2]=yn.max,_n.center[2]=(_n.min[2]+_n.max[2])/2):(Fs.shouldSplit=sn(Fs),Fs.shouldSplit||(_n.min[2]=_n.max[2]=_n.center[2]=this._centerAltitude))},Kn=(Fs,yn)=>{if(.707*yn{if(Fs.zoom=.9)return!0}else if(Q&&(Tn=Fs.aabb.distanceZ(Nt)*lt),this.projection.isReprojectedInTileSpace&&z<=5){const ua=Math.pow(2,Fs.zoom),ui=Zt(new o.ag((Fs.x+.5)/ua,(Fs.y+.5)/ua));Nr=ui>.85?1:ui}if(!ee&&!Je){const ua=Math.sqrt(yn*yn+_n*_n+Tn*Tn);let ui=(1<0;){const Fs=bs.pop(),yn=Fs.x,_n=Fs.y;let Tn=Fs.fullyVisible;const Nr=()=>this.projection.name==="globe"&&(Fs.y===0||Fs.y===(1<hr)continue;let mr=0;if(!Tn){let ta=zt?Fs.aabb.intersectsPrecise(tt):Fs.aabb.intersectsPreciseFlat(tt);if(ta===0&&Nr()){const ua=new o.cn(Fs.zoom,yn,_n);ta=o.co(this,Ee,ua,!0).intersectsPrecise(tt)}if(ta===0)continue;if(N.calculateQuadrantVisibility)if(tt.containsPoint(Fs.aabb.center))mr=15;else for(let ua=0;ua<4;ua++)Fs.aabb.quadrant(ua).intersects(tt)!==0&&(mr|=1<>1),pa={aabb:ee?Fs.aabb.quadrant(hr):o.cp(this,Ee,Fs.zoom+1,mr,Gn,Fs.wrap,Fs.minZ,Fs.maxZ,this.projection),zoom:Fs.zoom+1,x:mr,y:Gn,wrap:Fs.wrap,fullyVisible:Tn,tileID:void 0,shouldSplit:void 0,minZ:Fs.minZ,maxZ:Fs.maxZ};Q&&!Je&&(pa.tileID=new o.aR(Fs.zoom+1===Es?bn:Fs.zoom+1,Fs.wrap,Fs.zoom+1,mr,Gn),zn(pa)),bs.push(pa)}}if(this.fogCullDistSq){const Fs=this.fogCullDistSq,yn=this.horizonLineFromTop();Ks=Ks.filter(_n=>{const Tn=[0,0,0,1],Nr=[o.an,o.an,0,1],hr=this.calculateFogTileMatrix(_n.tileID.toUnwrapped());o.aE(Tn,Tn,hr),o.aE(Nr,Nr,hr);const mr=o.cq([],Tn,Nr),Gn=o.cr([],Tn,Nr),pa=o.cK(mr,Gn);if(pa===0)return!0;let Aa=!1;const ta=this._elevation;if(ta&&pa>Fs&&yn!==0){const ua=this.calculateProjMatrix(_n.tileID.toUnwrapped());let ui;N.isTerrainDEM||(ui=ta.getMinMaxForTile(_n.tileID)),ui||(ui={min:cs,max:Ss});const Ai=o.cs(this.rotation),ji=[Ai[0]*o.an,Ai[1]*o.an,ui.max];o.ah(ji,ji,ua),Aa=(1-ji[1])*this.height*.5Fs.distanceSq-yn.distanceSq).map(Fs=>Fs.tileID)}resize(N,T){this.width=N,this.height=T,this.pixelsToGLUnits=[2/N,-2/T],this._constrain(),this._calcMatrices()}get unmodified(){return this._unmodified}zoomScale(N){return Math.pow(2,N)}scaleZoom(N){return Math.log2(N)}project(N){const T=o.aC(N.lat,-o.ct,o.ct),z=this.projection.project(N.lng,T);return new o.P(z.x*this.worldSize,z.y*this.worldSize)}unproject(N){return this.projection.unproject(N.x/this.worldSize,N.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(N,T){let z,W;const Q=this.centerPoint;if(this.projection.name==="globe"){const ue=this.worldSize;z=(T.x-Q.x)/ue,W=(T.y-Q.y)/ue}else{const ue=this.pointCoordinate(T),_e=this.pointCoordinate(Q);z=ue.x-_e.x,W=ue.y-_e.y}const ee=this.locationCoordinate(N);this.setLocation(new o.ag(ee.x-z,ee.y-W))}setLocation(N){this.center=this.coordinateLocation(N),this.projection.wrap&&(this.center=this.center.wrap())}locationPoint(N,T){return this.projection.locationPoint(this,N,T)}locationPoint3D(N,T){return this.projection.locationPoint(this,N,T,!0)}pointLocation(N){return this.coordinateLocation(this.pointCoordinate(N))}pointLocation3D(N,T){return this.coordinateLocation(this.pointCoordinate3D(N,T))}locationCoordinate(N,T){const z=T?o.bU(T,N.lat):void 0,W=this.projection.project(N.lng,N.lat);return new o.ag(W.x,W.y,z)}coordinateLocation(N){return this.projection.unproject(N.x,N.y)}pointRayIntersection(N,T){const z=T??this._centerAltitude,W=[N.x,N.y,0,1],Q=[N.x,N.y,1,1];o.aE(W,W,this.pixelMatrixInverse),o.aE(Q,Q,this.pixelMatrixInverse);const ee=Q[3];o.cu(W,W,1/W[3]),o.cu(Q,Q,1/ee);const ue=W[2],_e=Q[2];return{p0:W,p1:Q,t:ue===_e?0:(z-ue)/(_e-ue)}}screenPointToMercatorRay(N){const T=[N.x,N.y,0,1],z=[N.x,N.y,1,1];return o.aE(T,T,this.pixelMatrixInverse),o.aE(z,z,this.pixelMatrixInverse),o.cu(T,T,1/T[3]),o.cu(z,z,1/z[3]),T[2]=o.bU(T[2],this._center.lat)*this.worldSize,z[2]=o.bU(z[2],this._center.lat)*this.worldSize,o.cu(T,T,1/this.worldSize),o.cu(z,z,1/this.worldSize),new o.az([T[0],T[1],T[2]],o.ay([],o.ax([],z,T)))}rayIntersectionCoordinate(N){const{p0:T,p1:z,t:W}=N,Q=o.bU(T[2],this._center.lat),ee=o.bU(z[2],this._center.lat);return new o.ag(o.am(T[0],z[0],W)/this.worldSize,o.am(T[1],z[1],W)/this.worldSize,o.am(Q,ee,W))}pointCoordinate(N,T=this._centerAltitude){return this.projection.pointCoordinate(this,N.x,N.y,T)}pointCoordinate3D(N,T){if(!this.elevation)return this.pointCoordinate(N,T);let z=this.projection.pointCoordinate3D(this,N.x,N.y);if(z)return new o.ag(z[0],z[1],z[2]);let W=0,Q=this.horizonLineFromTop();if(N.y>Q)return this.pointCoordinate(N,T);const ee=.02*Q,ue=N.clone();for(let _e=0;_e<10&&Q-W>ee;_e++){ue.y=o.am(W,Q,.66);const Ee=this.projection.pointCoordinate3D(this,ue.x,ue.y);Ee?(Q=ue.y,z=Ee):W=ue.y}return z?new o.ag(z[0],z[1],z[2]):this.pointCoordinate(N)}isPointAboveHorizon(N){return this.projection.isPointAboveHorizon(this,N)}isPointOnSurface(N){if(N.y<0||N.y>this.height||N.x<0||N.x>this.width)return!1;if(this.elevation||this.zoom>=o.cv)return!this.isPointAboveHorizon(N);const T=this.pointCoordinate(N);return T.y>=0&&T.y<=1}_coordinatePoint(N,T){const z=T&&this.elevation?this.elevation.getAtPointOrZero(N,this._centerAltitude):this._centerAltitude,W=[N.x*this.worldSize,N.y*this.worldSize,z+N.toAltitude(),1];return o.aE(W,W,this.pixelMatrix),W[3]>0?new o.P(W[0]/W[3],W[1]/W[3]):new o.P(Number.MAX_VALUE,Number.MAX_VALUE)}_getBoundsNonRectangular(){const{top:N,left:T}=this._edgeInsets,z=this.height-this._edgeInsets.bottom,W=this.width-this._edgeInsets.right,Q=this.pointLocation3D(new o.P(T,N)),ee=this.pointLocation3D(new o.P(W,N)),ue=this.pointLocation3D(new o.P(W,z)),_e=this.pointLocation3D(new o.P(T,z));let Ee=Math.min(Q.lng,ee.lng,ue.lng,_e.lng),Ie=Math.max(Q.lng,ee.lng,ue.lng,_e.lng),Je=Math.min(Q.lat,ee.lat,ue.lat,_e.lat),Ke=Math.max(Q.lat,ee.lat,ue.lat,_e.lat);const tt=Math.pow(2,-this.zoom)/16*270,ut=this.projection.name==="globe"?1:4,lt=(kt,Nt,zt,Yt,Tt)=>{const Ss=(kt+zt)/2,cs=(Nt+Yt)/2,Ns=new o.P(Ss,cs),{lng:Zt,lat:ns}=this.pointLocation3D(Ns),bs=Math.max(0,Ee-Zt,Je-ns,Zt-Ie,ns-Ke);Ee=Math.min(Ee,Zt),Ie=Math.max(Ie,Zt),Je=Math.min(Je,ns),Ke=Math.max(Ke,ns),(Tttt)&&(lt(kt,Nt,Ss,cs,Tt+1),lt(Ss,cs,zt,Yt,Tt+1))};if(lt(T,N,W,N,1),lt(W,N,W,z,1),lt(W,z,T,z,1),lt(T,z,T,N,1),this.projection.name==="globe"){const[kt,Nt]=o.cw(this);kt?(Ke=90,Ie=180,Ee=-180):Nt&&(Je=-90,Ie=180,Ee=-180)}return new o.aK(new o.aU(Ee,Je),new o.aU(Ie,Ke))}_getBoundsRectangular(N,T){const{top:z,left:W}=this._edgeInsets,Q=this.height-this._edgeInsets.bottom,ee=this.width-this._edgeInsets.right,ue=new o.P(W,z),_e=new o.P(ee,z),Ee=new o.P(ee,Q),Ie=new o.P(W,Q);let Je=this.pointCoordinate(ue,N),Ke=this.pointCoordinate(_e,N);const tt=this.pointCoordinate(Ee,T),ut=this.pointCoordinate(Ie,T),lt=(kt,Nt)=>(Nt.y-kt.y)/(Nt.x-kt.x);return Je.y>1&&Ke.y>=0?Je=new o.ag((1-ut.y)/lt(ut,Je)+ut.x,1):Je.y<0&&Ke.y<=1&&(Je=new o.ag(-ut.y/lt(ut,Je)+ut.x,0)),Ke.y>1&&Je.y>=0?Ke=new o.ag((1-tt.y)/lt(tt,Ke)+tt.x,1):Ke.y<0&&Je.y<=1&&(Ke=new o.ag(-tt.y/lt(tt,Ke)+tt.x,0)),new o.aK().extend(this.coordinateLocation(Je)).extend(this.coordinateLocation(Ke)).extend(this.coordinateLocation(ut)).extend(this.coordinateLocation(tt))}_getBoundsRectangularTerrain(){const N=this.elevation;if(!N.visibleDemTiles.length||N.isUsingMockSource())return this._getBoundsRectangular(0,0);const T=N.visibleDemTiles.reduce((z,W)=>{if(W.dem){const Q=W.dem.tree;z.min=Math.min(z.min,Q.minimums[0]),z.max=Math.max(z.max,Q.maximums[0])}return z},{min:Number.MAX_VALUE,max:0});return this._getBoundsRectangular(T.min*N.exaggeration(),T.max*N.exaggeration())}getBounds(){return this.projection.name==="mercator"||this.projection.name==="equirectangular"?this._terrainEnabled()?this._getBoundsRectangularTerrain():this._getBoundsRectangular(0,0):this._getBoundsNonRectangular()}horizonLineFromTop(N=!0){const T=this.height/2/Math.tan(this._fov/2)/Math.tan(Math.max(this._pitch,.1))-this.centerOffset.y,z=this.height/2-T*(1-this._horizonShift);return N?Math.max(0,z):z}getMaxBounds(){return this.maxBounds}setMaxBounds(N){this.maxBounds=N,this.minLat=-o.ct,this.maxLat=o.ct,this.minLng=-180,this.maxLng=180,N&&(this.minLat=N.getSouth(),this.maxLat=N.getNorth(),this.minLng=N.getWest(),this.maxLng=N.getEast(),this.maxLngJe&&(ue=Je-Ee),Je-Iett&&(ee=tt-_e),tt-Ke{for(let sn=0;sn<16;sn++)bn[sn]=o.am(mn[sn],zn[sn],Kn)})(ue,ue,_e,o.cL(this.pitch>=ym?1:this.pitch/ym))}else ue=_e;const Ee=o.cz([],_e,ee);let Ie=o.cz([],ue,ee);if(this.projection.isReprojectedInTileSpace){const ns=this.locationCoordinate(this.center),bs=o.b9([]);o.bx(bs,bs,[ns.x*this.worldSize,ns.y*this.worldSize,0]),o.aD(bs,bs,o.cA(this)),o.bx(bs,bs,[-ns.x*this.worldSize,-ns.y*this.worldSize,0]),o.aD(Ie,Ie,bs),o.aD(Ee,Ee,bs),this.inverseAdjustmentMatrix=o.cB(this)}else this.inverseAdjustmentMatrix=[1,0,0,1];if(this.mercatorMatrix=o.cC([],Ie,[this.worldSize,this.worldSize,this.worldSize/Q,1]),this.projMatrix=Ie,this.invProjMatrix=o.b7(new Float64Array(16),this.projMatrix),T){const ns=this._camera.getCameraToClipPerspective(this._fov,this.width/this.height,this._nearZ,1/0);ns[8]=2*-N.x/this.width,ns[9]=2*N.y/this.height,this.expandedFarZProjMatrix=o.cz([],ns,ee)}else this.expandedFarZProjMatrix=this.projMatrix;const Je=o.b7([],ue);this.frustumCorners=o.cD.fromInvProjectionMatrix(Je,this.horizonLineFromTop(),this.height),this.cameraFrustum=o.cl.fromInvProjectionMatrix(this.invProjMatrix,this.worldSize,0,!T);const Ke=new Float32Array(16);o.b9(Ke),o.cC(Ke,Ke,[1,-1,1]),o.cE(Ke,Ke,this._pitch),o.ba(Ke,Ke,this.angle);const tt=o.bS(new Float32Array(16),this._fov,this.width/this.height,this._nearZ,this._farZ);this.starsProjMatrix=o.b8(tt);const ut=(Math.PI/2-this._pitch)*(this.height/this._fov)*this._horizonShift;tt[8]=2*-N.x/this.width,tt[9]=2*(N.y+ut)/this.height,this.skyboxMatrix=o.aD(Ke,tt,Ke);const lt=this.point,kt=lt.x,Nt=lt.y,zt=this.width%2/2,Yt=this.height%2/2,Tt=Math.cos(this.angle),Ss=Math.sin(this.angle),cs=kt-Math.round(kt)+Tt*zt+Ss*Yt,Ns=Nt-Math.round(Nt)+Tt*Yt+Ss*zt,Zt=new Float64Array(Ie);if(o.bx(Zt,Zt,[cs>.5?cs-1:cs,Ns>.5?Ns-1:Ns,0]),this.alignedProjMatrix=Zt,Ie=o.bb(),o.cC(Ie,Ie,[this.width/2,-this.height/2,1]),o.bx(Ie,Ie,[1,-1,0]),this.labelPlaneMatrix=Ie,Ie=o.bb(),o.cC(Ie,Ie,[1,-1,1]),o.bx(Ie,Ie,[-1,-1,0]),o.cC(Ie,Ie,[2/this.width,2/this.height,1]),this.glCoordMatrix=Ie,this.pixelMatrix=o.aD(new Float64Array(16),this.labelPlaneMatrix,Ee),this._calcFogMatrices(),this._distanceTileDataCache={},Ie=o.b7(new Float64Array(16),this.pixelMatrix),!Ie)throw new Error("failed to invert matrix");if(this.pixelMatrixInverse=Ie,this.projection.name==="globe"||this.mercatorFromTransition){this.globeMatrix=o.cF(this);const ns=[this.globeMatrix[12],this.globeMatrix[13],this.globeMatrix[14]];this.globeCenterInViewSpace=o.ah(ns,ns,ee),this.globeRadius=this.worldSize/2/Math.PI-1}else this.globeMatrix=Ie;this._projMatrixCache={},this._alignedProjMatrixCache={},this._pixelsToTileUnitsCache={},this._expandedProjMatrixCache={}}_calcFogMatrices(){this._fogTileMatrixCache={};const N=this.cameraWorldSizeForFog,T=this.cameraPixelsPerMeter,z=this._camera.position,W=1/this.height/this._pixelsPerMercatorPixel,Q=[N,N,T];o.bJ(Q,Q,W),o.bJ(z,z,-1),o.cG(z,z,Q);const ee=o.bb();o.bx(ee,ee,z),o.cC(ee,ee,Q),this.mercatorFogMatrix=ee,this.worldToFogMatrix=this._camera.getWorldToCameraPosition(N,T,W)}_computeCameraPosition(N){const T=(N=N||this.pixelsPerMeter)/this.pixelsPerMeter,z=this._camera.forward(),W=this.point,Q=this._mercatorZfromZoom(this._seaLevelZoom?this._seaLevelZoom:this._zoom)*T-N/this.worldSize*this._centerAltitude;return[W.x/this.worldSize-z[0]*Q,W.y/this.worldSize-z[1]*Q,N/this.worldSize*this._centerAltitude-z[2]*Q]}_updateCameraState(){this.height&&(this._camera.setPitchBearing(this._pitch,this.angle),this._camera.position=this._computeCameraPosition())}_translateCameraConstrained(N){const T=this._maxCameraBoundsDistance()*Math.cos(this._pitch),z=this._camera.position[2],W=N[2];let Q=1;this.projection.wrap&&(this.center=this.center.wrap()),W>0&&(Q=Math.min((T-z)/W,1)),this._camera.position=o.bg([],this._camera.position,N,Q),this._updateStateFromCamera()}_updateStateFromCamera(){const N=this._camera.position,T=this._camera.forward(),{pitch:z,bearing:W}=this._camera.getPitchBearing(),Q=o.bU(this._centerAltitude,this.center.lat)*this._pixelsPerMercatorPixel,ee=this._mercatorZfromZoom(this._maxZoom)*Math.cos(o.ap(this._maxPitch)),ue=Math.max((N[2]-Q)/Math.cos(z),ee),_e=this._zoomFromMercatorZ(ue);o.bg(N,N,T,ue),this._pitch=o.aC(z,o.ap(this.minPitch),o.ap(this.maxPitch)),this.angle=o.bs(W,-Math.PI,Math.PI),this._setZoom(o.aC(_e,this._minZoom,this._maxZoom)),this._updateSeaLevelZoom(),this._center=this.coordinateLocation(new o.ag(N[0],N[1],N[2])),this._unmodified=!1,this._constrain(),this._calcMatrices()}_worldSizeFromZoom(N){return Math.pow(2,N)*this.tileSize}_mercatorZfromZoom(N){return this.cameraToCenterDistance/this._worldSizeFromZoom(N)}_minimumHeightOverTerrain(){const N=Math.min(this._seaLevelZoom!=null?this._seaLevelZoom:this._zoom,this._maxZoom)+4;return this._mercatorZfromZoom(N)}_zoomFromMercatorZ(N){return this.scaleZoom(this.cameraToCenterDistance/(Math.max(0,N)*this.tileSize))}zoomFromMercatorZAdjusted(N){let T=0,z=o.cv,W=0,Q=1/0;for(;z-T>1e-6&&z>T;){const ee=T+.5*(z-T),ue=this.tileSize*Math.pow(2,ee),_e=this.getCameraToCenterDistance(this.projection,ee,ue),Ee=this.scaleZoom(_e/(Math.max(0,N)*this.tileSize)),Ie=Math.abs(ee-Ee);IeEe||Ke.y>1)return!0}return!1}isHorizonVisible(){return this.pitch+o.cH(this.fovAboveCenter)>88||this.anyCornerOffEdge(new o.P(0,0),new o.P(this.width,this.height))}zoomDeltaToMovement(N,T){const z=o.ai(o.ax([],this._camera.position,N)),W=this._zoomFromMercatorZ(z)+T;return z-this._mercatorZfromZoom(W)}getCameraPoint(){if(this.projection.name==="globe"){const N=function([T,z,W],Q){const ee=[T,z,W,1];o.aE(ee,ee,Q);const ue=ee[3]=Math.max(ee[3],1e-6);return ee[0]/=ue,ee[1]/=ue,ee[2]/=ue,ee}([this.globeMatrix[12],this.globeMatrix[13],this.globeMatrix[14]],this.pixelMatrix);return new o.P(N[0],N[1])}{const N=Math.tan(this._pitch)*(this.cameraToCenterDistance||1);return this.centerPoint.add(new o.P(0,N))}}getCameraToCenterDistance(N,T=this.zoom,z=this.worldSize){const W=o.cy(N,T,this.width,this.height,1024),Q=N.pixelSpaceConversion(this.center.lat,z,W);let ee=.5/Math.tan(.5*this._fov)*this.height*Q;return this.isOrthographic&&(ee=o.am(1,ee,o.cL(this.pitch>=ym?1:this.pitch/ym))),ee}getWorldToCameraMatrix(){const N=this._camera.getWorldToCamera(this.worldSize,this.projection.zAxisUnit==="meters"?this.pixelsPerMeter:1);return this.projection.name==="globe"&&o.aD(N,N,this.globeMatrix),N}getFrustum(N){return o.cl.fromInvProjectionMatrix(this.invProjMatrix,this.worldSize,N,this.projection.zAxisUnit==="meters")}}const qd=(R,N)=>{if(N>0&&R.terrain&&o.w("Cutoff is currently disabled on terrain"),N<=0||R.terrain)return{shouldRenderCutoff:!1,uniformValues:{u_cutoff_params:[0,0,0,1]}};const T=R.transform,z=T.pitch,W=T.isLODDisabled(!1)?60:30;if(z0,uniformValues:{u_cutoff_params:[T._nearZ,T._farZ,(Ie-T._nearZ)/Q,(Ie-Ke-T._nearZ)/Q]}}},uf=2048;class E1{constructor(N,T){this.aabb=N,this.lastCascade=T}}class T1{add(N,T){const z=this.receivers[N.key];z!==void 0?(z.aabb.min[0]=Math.min(z.aabb.min[0],T.min[0]),z.aabb.min[1]=Math.min(z.aabb.min[1],T.min[1]),z.aabb.min[2]=Math.min(z.aabb.min[2],T.min[2]),z.aabb.max[0]=Math.max(z.aabb.max[0],T.max[0]),z.aabb.max[1]=Math.max(z.aabb.max[1],T.max[1]),z.aabb.max[2]=Math.max(z.aabb.max[2],T.max[2])):this.receivers[N.key]=new E1(T,null)}clear(){this.receivers={}}get(N){return this.receivers[N.key]}computeRequiredCascades(N,T,z){const W=o.cU.fromPoints(N.points);let Q=0;for(const ee in this.receivers){const ue=this.receivers[ee];if(!ue||!W.intersectsAabb(ue.aabb))continue;ue.aabb.min=W.closestPoint(ue.aabb.min),ue.aabb.max=W.closestPoint(ue.aabb.max);const _e=ue.aabb.getCorners();for(let Ee=0;Ee1||Ke[1]<-1||Ke[1]>1){Ie=!1;break}}if(ue.lastCascade=Ee,Q=Math.max(Q,Ee),Ie)break}}return Q+1}}class ud{constructor(N){this.painter=N,this._enabled=!1,this._drawShadowAfterLayer=-1,this._numCascadesToRender=0,this._cascades=[],this._groundShadowTiles=[],this._receivers=new T1,this._depthMode=new Hr(N.context.gl.LEQUAL,Hr.ReadWrite,[0,1]),this._uniformValues={u_light_matrix_0:new Float32Array(16),u_light_matrix_1:new Float32Array(16),u_shadow_intensity:0,u_fade_range:[0,0],u_shadow_normal_offset:[1,1,1],u_shadow_texel_size:1,u_shadow_map_resolution:1,u_shadow_direction:[0,0,1],u_shadow_bias:[36e-5,.0012,.012],u_shadowmap_0:0,u_shadowmap_1:0},this._forceDisable=!1,this.useNormalOffset=!1}destroy(){for(const N of this._cascades)N.texture.destroy(),N.framebuffer.destroy();this._cascades=[]}updateShadowParameters(N,T){const z=this.painter;if(this._enabled=!1,this._drawShadowAfterLayer=-1,this._receivers.clear(),!T||!T.properties)return;const W=T.properties.get("shadow-intensity"),Q=T.properties.get("shadow-draw-before-layer");if(!T.shadowsEnabled()||W<=0)return;let ee=-1,ue=0;for(const Nt of z.style.order){const zt=z.style._mergedLayers[Nt];zt.hasShadowPass()&&!zt.isHidden(N.zoom)&&(ee=ue),!Q||Q!==Nt&&Q!==zt.slot||(this._drawShadowAfterLayer=ue>0?ue-1:0),ue+=1}if(this._enabled=ee>=0,!this.enabled)return;this._drawShadowAfterLayer<0&&(this._drawShadowAfterLayer=ee);const _e=z.context,Ee=uf,Ie=uf;if(this._cascades.length===0||uf!==this._cascades[0].texture.size[0]){this._cascades=[];for(let Nt=0;Nt<2;++Nt){const zt=_e.gl,Yt=_e.createFramebuffer(Ee,Ie,0,"texture"),Tt=new o.T(_e,{width:Ee,height:Ie,data:null},zt.DEPTH_COMPONENT16);Yt.depthAttachment.set(Tt.texture),this._cascades.push({framebuffer:Yt,texture:Tt,matrix:[],far:0,boundingSphereRadius:0,frustum:new o.cl,scale:0})}}this.shadowDirection=Fy(T);let Je=0;if(N.elevation){const Nt=N.elevation,zt=[1e4,-1e4];Nt.visibleDemTiles.filter(Yt=>Yt.dem).forEach(Yt=>{const Tt=Yt.dem.tree;zt[0]=Math.min(zt[0],Tt.minimums[0]),zt[1]=Math.max(zt[1],Tt.maximums[0])}),zt[0]!==1e4&&(Je=(zt[1]-zt[0])*Nt.exaggeration())}const Ke=1.5*N.cameraToCenterDistance,tt=3*Ke,ut=new Float64Array(16);for(let Nt=0;Nt=0)return{};const Q=function(_e,Ee,Ie){const Je=Ie/(1<<_e.canonical.z);return new o.cU([_e.canonical.x*Je+_e.wrap*Ie,_e.canonical.y*Je+_e.wrap*Ie,0],[(_e.canonical.x+1)*Je+_e.wrap*Ie,(_e.canonical.y+1)*Je+_e.wrap*Ie,Ee])}(N,T,z).getCorners(),ee=T/-W[2];W[0]<0?(o.cT(Q[0],Q[0],[W[0]*ee,0,0]),o.cT(Q[3],Q[3],[W[0]*ee,0,0])):W[0]>0&&(o.cT(Q[1],Q[1],[W[0]*ee,0,0]),o.cT(Q[2],Q[2],[W[0]*ee,0,0])),W[1]<0?(o.cT(Q[0],Q[0],[0,W[1]*ee,0]),o.cT(Q[1],Q[1],[0,W[1]*ee,0])):W[1]>0&&(o.cT(Q[2],Q[2],[0,W[1]*ee,0]),o.cT(Q[3],Q[3],[0,W[1]*ee,0]));const ue={};return ue.vertices=Q,ue.planes=[Kg(Q[1],Q[0],Q[4]),Kg(Q[2],Q[1],Q[5]),Kg(Q[3],Q[2],Q[6]),Kg(Q[0],Q[3],Q[7])],ue}addShadowReceiver(N,T,z){this._receivers.add(N,o.cU.fromTileIdAndHeight(N,T,z))}getMaxCascadeForTile(N){const T=this._receivers.get(N);return T&&T.lastCascade?T.lastCascade:0}}function Kg(R,N,T){const z=o.ax([],T,N),W=o.ax([],R,N),Q=o.bh([],z,W),ee=o.ai(Q);return ee===0?[0,0,1,0]:(o.bJ(Q,Q,1/ee),[Q[0],Q[1],Q[2],-o.bi(Q,N)])}function Fy(R){const N=R.properties.get("direction"),T=o.cP(N.x,N.y,N.z);T[2]=o.aC(T[2],0,75);const z=o.cR([T[0],T[1],T[2]]);return o.cQ(z.x,z.y,z.z)}function vm(R,N,T){const z=N.properties.get("color-use-theme")==="none",W=N.properties.get("color"),Q=N.properties.get("intensity"),ee=N.properties.get("direction"),ue=[ee.x,ee.y,ee.z],_e=T.properties.get("color-use-theme")==="none",Ee=T.properties.get("color"),Ie=T.properties.get("intensity"),Je=Math.max(o.bi([0,0,1],ue),0),Ke=[0,0,0];o.bJ(Ke,Ee.toPremultipliedRenderColor(_e?null:R.getLut(N.scope)).toArray01Linear().slice(0,3),Ie);const tt=[0,0,0];return o.bJ(tt,W.toPremultipliedRenderColor(z?null:R.getLut(T.scope)).toArray01Linear().slice(0,3),Je*Q),o.cW([Ke[0]>0?Ke[0]/(Ke[0]+tt[0]):0,Ke[1]>0?Ke[1]/(Ke[1]+tt[1]):0,Ke[2]>0?Ke[2]/(Ke[2]+tt[2]):0])}function zx(R,N,T,z,W,Q){const ee=R.zoom,ue=R.scale,_e=R.worldSize,Ee=1/_e,Ie=R.aspect,Je=Math.sqrt(1+Ie*Ie)*Math.tan(.5*R.fovX),Ke=Je*Je,tt=z-T,ut=z+T;let lt,kt;Ke>tt/ut?(lt=z,kt=z*Je):(lt=.5*ut*(1+Ke),kt=.5*Math.sqrt(tt*tt+2*(z*z+T*T)*Ke+ut*ut*Ke*Ke));const Nt=R.projection.pixelsPerMeter(R.center.lat,_e),zt=R._camera.getCameraToWorldMercator(),Yt=[0,0,-lt*Ee];o.ah(Yt,Yt,zt);let Tt=kt*Ee;const Ss=function(Tn){return Tn[0]/=ue,Tn[1]/=ue,Tn[2]=o.bU(Tn[2],R._center.lat),Tn},cs=R._edgeInsets;if(!(cs.left===0&&cs.top===0&&cs.right===0&&cs.bottom===0||cs.left===cs.right&&cs.top===cs.bottom)){const Tn=R._camera.getWorldToCamera(R.worldSize,R.projection.zAxisUnit==="meters"?Nt:1),Nr=R._camera.getCameraToClipPerspective(R._fov,R.width/R.height,T,z);Nr[8]=2*-R.centerOffset.x/R.width,Nr[9]=2*R.centerOffset.y/R.height;const hr=new Float64Array(16);o.cz(hr,Nr,Tn);const mr=new Float64Array(16);o.b7(mr,hr);const Gn=o.cl.fromInvProjectionMatrix(mr,_e,ee,!0);for(const pa of Gn.points){const Aa=Ss(pa);Tt=Math.max(Tt,o.bK(o.cV([],Yt,Aa)))}}Tt*=W/(W-1);const Ns=Math.acos(N[2]),Zt=Math.atan2(-N[0],-N[1]),ns=new Ox;ns.position=Yt,ns.setPitchBearing(Ns,Zt);const bs=ns.getWorldToCamera(_e,Nt),Ks=Tt*_e,Es=Math.min(R._mercatorZfromZoom(17)*_e*-2,-2*Ks),bn=ns.getCameraToClipOrthographic(-Ks,Ks,-Ks,Ks,Es,(Ks+Q*Nt)/N[2]),mn=new Float64Array(16);o.aD(mn,bn,bs);const zn=o.cQ(Math.floor(1e6*Yt[0])/1e6*_e,Math.floor(1e6*Yt[1])/1e6*_e,0),Kn=.5*W,sn=[0,0,0];o.ah(sn,zn,mn),o.bJ(sn,sn,Kn);const Fs=[Math.floor(sn[0]),Math.floor(sn[1]),Math.floor(sn[2])],yn=[0,0,0];o.ax(yn,sn,Fs),o.bJ(yn,yn,-1/Kn);const _n=new Float64Array(16);return o.b9(_n),o.bx(_n,_n,yn),o.aD(mn,_n,mn),[mn,Ks]}class Rb extends o.E{constructor(N){super(),this.requestManager=N,this.models={"":{}},this.modelUris={"":{}},this.modelByURL={},this.numModelsLoading={}}loadModel(N,T){return o.cX(this.requestManager.transformRequest(T,o.R.Model).url).then(z=>{const W=o.cY(z),Q=new o.cZ(N,T,void 0,void 0,W);return Q.computeBoundsAndApplyParent(),Q}).catch(z=>{if(z&&z.status===404)return null;this.fire(new o.B(new Error(`Could not load model ${N} from ${T}: ${z.message}`)))})}load(N,T,z={forceReload:!1}){this.models[T]||(this.models[T]={});const W=Object.keys(N),Q=[],ee=[];for(const ue of W){const _e=N[ue];this.hasURLBeenRequested(_e)&&!z.forceReload||(this.modelByURL[_e]={modelId:ue,scope:T},Q.push(this.loadModel(ue,_e)),ee.push(ue)),this.models[T][ue]||(this.models[T][ue]={model:null,numReferences:1})}this.numModelsLoading[T]=(this.numModelsLoading[T]||0)+ee.length,Promise.allSettled(Q).then(ue=>{for(let _e=0;_e{this.fire(new o.B(new Error(`Could not load models: ${ue.message}`)))})}isLoaded(){for(const N in this.numModelsLoading)if(this.numModelsLoading[N]>0)return!1;return!0}hasModel(N,T,z={exactIdMatch:!1}){return!!(z.exactIdMatch?this.getModel(N,T):this.getModelByURL(this.modelUris[T][N]))}getModel(N,T){return this.models[T]||(this.models[T]={}),this.models[T][N]?this.models[T][N].model:void 0}getModelByURL(N){if(!N)return null;const T=this.modelByURL[N];return T?this.models[T.scope][T.modelId].model:null}hasModelBeenAdded(N,T){return this.models[T]&&this.models[T][N]!==void 0}getModelURIs(N){return this.modelUris[N]||{}}addModel(N,T,z){this.models[z]||(this.models[z]={}),this.modelUris[z]||(this.modelUris[z]={});const W=this.requestManager.normalizeModelURL(T);if((this.hasModel(N,z,{exactIdMatch:!0})||this.hasModelBeenAdded(N,z))&&this.modelUris[z][N]===W)this.models[z][N].numReferences++;else if(this.hasURLBeenRequested(W)){const{scope:Q,modelId:ee}=this.modelByURL[W];this.models[Q][ee].numReferences++}else this.modelUris[z][N]=W,this.load({[N]:this.modelUris[z][N]},z)}addModelURLs(N,T){this.models[T]||(this.models[T]={}),this.modelUris[T]||(this.modelUris[T]={});const z=this.modelUris[T];for(const W in N)z[W]=this.requestManager.normalizeModelURL(N[W])}reloadModels(N){this.load(this.modelUris[N],N,{forceReload:!0})}addModelsFromBucket(N,T){this.models[T]||(this.models[T]={}),this.modelUris[T]||(this.modelUris[T]={});const z={};for(const W of N)this.hasModel(W,T,{exactIdMatch:!0})||this.hasURLBeenRequested(W)?this.models[T][W].numReferences++:this.modelUris[T][W]&&!this.hasURLBeenRequested(W)?z[W]=this.modelUris[T][W]:!this.hasURLBeenRequested(W)&&o.c_(W,!1)&&(this.modelUris[T][W]=this.requestManager.normalizeModelURL(W),z[W]=this.modelUris[T][W]);this.load(z,T)}hasURLBeenRequested(N){return this.modelByURL[N]!==void 0}removeModel(N,T,z=!1,W=!1){if(this.models[T]&&this.models[T][N]&&(this.models[T][N].numReferences--,this.models[T][N].numReferences===0||W)){const Q=this.modelUris[T][N];z||delete this.modelUris[T][N],delete this.modelByURL[Q];const ee=this.models[T][N].model;if(!ee)return;delete this.models[T][N],ee.destroy()}}destroy(){for(const N of Object.keys(this.models))for(const T of Object.keys(this.models[N])){const z=this.models[N][T].model;delete this.models[N][T],z&&z.destroy()}this.models={"":{}},this.modelUris={"":{}},this.modelByURL={},this.numModelsLoading={}}listModels(N){return this.models[N]||(this.models[N]={}),Object.keys(this.models[N])}upload(N,T){this.models[T]||(this.models[T]={});for(const z in this.models[T])this.models[T][z].model&&this.models[T][z].model.upload(N.context)}}const mh=o.a8.colorTheme,Ac=new o.ab({data:new o.ac(mh.data)});function Cl(R){if(!R.metadata||!R.metadata.content_area)return;const N=o.o.devicePixelRatio,{left:T,top:z,width:W,height:Q}=R.metadata.content_area,ee=T*N,ue=z*N;return[ee,ue,ee+W*N,ue+Q*N]}function pl(R){if(R)return R.map(([N,T])=>[N*o.o.devicePixelRatio,T*o.o.devicePixelRatio])}class $u{constructor(N,T,z){this.id=N,this.scope=T,this.sourceCache=z,this.pendingRequests=new Set,this.missingRequests=new Set}addPendingRequest(N){this.missingRequests.has(N.name)||this.pendingRequests.has(N.name)||this.pendingRequests.add(N.name)}hasPendingRequests(){return this.pendingRequests.size>0}resolvePendingRequests(){const N=new Map;if(!this.sourceCache.loaded())return N;const T=this.sourceCache.getVisibleCoordinates();if(T.length===0)return N;const z=this.sourceCache.getSource();if(!(z instanceof no))return N;const W=T.map(ee=>this.sourceCache.getTile(ee)),Q=z.getImages(W,Array.from(this.pendingRequests));for(const[ee,ue]of Q)N.set(o.I.from({name:ee,iconsetId:this.id}),ue),this.pendingRequests.delete(ee);for(const ee of this.pendingRequests)this.missingRequests.add(ee);return this.pendingRequests.clear(),N}}class $d{constructor(){this._previousClosestBuildingId=null,this._hysteresisRatio=.8,this._indoorMinimumZoom=16}findClosestBuilding(N,T,z,W,Q){if(z_e*this._hysteresisRatio&&(ee=this._previousClosestBuildingId):Ee&&!ee&&(ee=this._previousClosestBuildingId),this._previousClosestBuildingId=ee,ee}_calculateDistance(N,T){if(!T.center)return Number.MAX_VALUE;const z=N.lat-T.center[1],W=N.lng-T.center[0];return z*z+W*W}_isBuildingVisible(N,T,z){if(!z)return!1;for(const W of N.floorIds){const Q=N.floors[W];if(!Q.geometry)continue;const ee=Q.geometry;if(ee.type==="Polygon"){const ue=this._convertRingToPoints(ee.coordinates[0]);if(o.bw(ue,z))return!0}else if(ee.type==="MultiPolygon"){const ue=this._convertMultiPolygonToPoints(ee.coordinates);if(o.d0(z,ue))return!0}}return!1}_convertRingToPoints(N){return N.map(T=>new o.P(T[0],T[1]))}_convertMultiPolygonToPoints(N){return N.map(T=>T.length===0?[]:T[0].map(z=>new o.P(z[0],z[1])))}}class Yg extends o.E{constructor(N){super(),this._style=N,this._buildings={},this._activeFloors=new Set,this._closestBuildingId=null,this._indoorState={selectedFloorId:null,activeFloorsVisible:!0,activeFloors:this._activeFloors},this._buildingDetectionStrategy=new $d,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(N){N===this._selectedFloorId&&this._indoorState&&this._indoorState.activeFloorsVisible||(this._selectedFloorId=N,this._recalculateActiveFloors())}setActiveFloorsVisibility(N){this._updateActiveFloors(N),this._updateIndoorSelector()}setIndoorData(N){let T=!1;for(const[z,W]of Object.entries(N.buildings))if(this._buildings[z])for(const Q of W.floorIds)this._buildings[z].floorIds.add(Q),this._buildings[z].floors[Q]?this._mergeFloors(this._buildings[z].floors[Q],W.floors[Q]):(this._buildings[z].floors[Q]=W.floors[Q],T=!0);else this._buildings[z]=W,T=!0;T&&this._recalculateActiveFloors()}getIndoorTileOptions(N,T){return this._indoorState?{sourceLayers:this._style.getIndoorSourceLayers(N,T),indoorState:this._indoorState}:null}getControlState(){const N=this._buildings,T=this._closestBuildingId,z=T&&N?N[T]:void 0;if(!z)return{selectedFloorId:null,activeFloorsVisible:!!this._indoorState&&this._indoorState.activeFloorsVisible,floors:[]};let W=null;for(const ee of z.floorIds)if(this._activeFloors&&this._activeFloors.has(ee)){W=ee;break}const Q=Array.from(z.floorIds).map(ee=>({id:ee,name:z.floors[ee].name,zIndex:z.floors[ee].zIndex})).sort((ee,ue)=>ue.zIndex-ee.zIndex).filter((ee,ue,_e)=>ue===0||ee.zIndex!==_e[ue-1].zIndex);return{selectedFloorId:W,activeFloorsVisible:!!this._indoorState&&this._indoorState.activeFloorsVisible,floors:Q}}_updateUI(){this._initialLoadDone=!0;const N=this._style.map.transform,T=this._buildingDetectionStrategy.findClosestBuilding(this._buildings,N.center,N.zoom,N.getBounds(),this._makeViewportPolygon());if(T!==this._closestBuildingId){const z=this._closestBuildingId;this._closestBuildingId=T,this._onBuildingTransition(z,T),this._updateIndoorSelector()}}_onBuildingTransition(N,T){if(!this._indoorState)return;!T&&N?(this._indoorState.activeFloors=new Set,this._indoorState.activeFloorsVisible=!1,this._style.updateIndoorDependentLayers()):!!T&&!N&&(this._recalculateActiveFloors(),this._updateActiveFloors(!0))}_updateIndoorSelector(){this.fire(new o.C("selector-update",this.getControlState()))}_updateActiveFloors(N){this._indoorState={selectedFloorId:this._selectedFloorId,activeFloorsVisible:N,activeFloors:this._activeFloors},this._initialLoadDone?this._style.updateIndoorDependentLayers():this._indoorState.needsUpdate=!0}_recalculateActiveFloors(){if(!this._buildings)return;const N=o.d1.calculate(this._buildings,this._selectedFloorId,this._activeFloors);(function(T,z){if(T===z)return!0;if(!T||!z||T.size!==z.size)return!1;for(const W of T)if(!z.has(W))return!1;return!0})(N,this._activeFloors)||(this._activeFloors=N,this._updateActiveFloors(!!this._indoorState&&this._indoorState.activeFloorsVisible),this._updateIndoorSelector())}_mergeFloors(N,T){T.geometry&&(N.geometry?(N.geometry.type==="Polygon"&&(N.geometry={type:"MultiPolygon",coordinates:[N.geometry.coordinates]}),T.geometry.type==="Polygon"?N.geometry.coordinates.push(T.geometry.coordinates):T.geometry.type==="MultiPolygon"&&N.geometry.coordinates.push(...T.geometry.coordinates)):N.geometry=T.geometry)}_makeViewportPolygon(){const N=this._style.map.transform,T=N.width,z=N.height;return[N.pointLocation(new o.P(0,0)),N.pointLocation(new o.P(T,0)),N.pointLocation(new o.P(T,z)),N.pointLocation(new o.P(0,z))].map(W=>new o.P(W.lng,W.lat))}}const Oy=(R,N)=>er(R,N&&N.filter(T=>T.identifier!=="source.canvas")),bm=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"]),tw=o.aJ(Ti,["setCenter","setZoom","setBearing","setPitch"]),Vj=new Set(["background","sky","slot","custom"]),sw={version:8,layers:[],sources:{}},Zg={duration:300,delay:0};class ph extends o.E{constructor(N,T={}){if(super(),this.map=N,this.scope=T.scope||"",this.globalId=null,this.fragments=[],this.importDepth=T.importDepth||0,this.importsCache=T.importsCache||new Map,this.resolvedImports=T.resolvedImports||new Set,this.transition=Object.assign({},Zg),this._buildingIndex=new xg(this),this.crossTileSymbolIndex=new Fx,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=T.styleChanges||new qe,this._hasDataDrivenEmissive=!1,this.indoorManager=new Yg(this),this.dispatcher=T.dispatcher?T.dispatcher:new Ge(qt(),this),this.map.painter&&this.map.painter.context){const W=this.map.painter.context.maxUniformBufferBindings,Q=Math.floor(this.map.painter.context.maxUniformBlockSize/4);this.dispatcher.broadcast("setContextParams",{maxBindingPoints:W,maxUniformBlockSizeDwords:Q,disableSymbolUBO:this.map.painter.context.disableSymbolUBO})}T.imageManager?this.imageManager=T.imageManager:(this.imageManager=new Vt(this.map._spriteFormat),this.imageManager.setEventedParent(this)),this.imageManager.addScope(this.scope),this.glyphManager=T.glyphManager?T.glyphManager:new o.d2(N._requestManager,T.localFontFamily?o.d3.all:T.localIdeographFontFamily?o.d3.ideographs:o.d3.none,T.localFontFamily||T.localIdeographFontFamily,T.useServerFontComposition),T.modelManager?this.modelManager=T.modelManager:(this.modelManager=new Rb(N._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=T.configOptions?T.configOptions:new Map,this._configDependentLayers=T.configDependentLayers?T.configDependentLayers:new Set,this._indoorDependentLayers=T.indoorDependentLayers?T.indoorDependentLayers:new Set,this._config=T.config,this._styleColorTheme={lut:null,lutLoading:!1,lutLoadingCorrelationID:0,colorTheme:null,colorThemeOverride:T.colorThemeOverride},this._styleColorThemeForScope={},this._initialConfig=T.initialConfig,this.dispatcher.broadcast("setReferrer",o.d4()),this.dispatcher.broadcast("setConfig",o.d5());const z=this;this._rtlTextPluginCallback=ph.registerForPluginStateChange(W=>{z.dispatcher.broadcast("syncRTLPluginState",{pluginStatus:W.pluginStatus,pluginURL:W.pluginURL},(Q,ee)=>{if(o.d6(Q),ee&&ee.every(ue=>ue))for(const ue in z._sourceCaches){const _e=z._sourceCaches[ue],Ee=_e.getSource().type;Ee!=="vector"&&Ee!=="geojson"||_e.reload()}})}),this.on("data",W=>{if(W.dataType!=="source"||W.sourceDataType!=="metadata")return;const Q=this.getOwnSource(W.sourceId);if(Q&&Q.vectorLayerIds)for(const ee in this._layers){const ue=this._layers[ee];ue.source===Q.id&&this._validateLayer(ue)}})}load(N){return N?(typeof N=="string"?this.loadURL(N):this.loadJSON(N),this):this}_getGlobalId(N){if(!N)return null;if(typeof N=="string"){if(o.e(N))return N;const T=o.d7(N);if(!T.startsWith("http"))try{return new URL(T,location.href).toString()}catch{return T}return T}return`json://${o.d8(JSON.stringify(N))}`}_diffStyle(N,T,z){this.globalId=this._getGlobalId(N);const W=(Q,ee)=>{try{ee(null,this.setState(Q,z))}catch(ue){ee(ue,!1)}};if(typeof N=="string"){const Q=this.map._requestManager.normalizeStyleURL(N),ee=this.map._requestManager.transformRequest(Q,o.R.Style);o.m(ee,(ue,_e)=>{ue?this.fire(new o.B(ue)):_e&&W(_e,T)})}else typeof N=="object"&&W(N,T)}loadURL(N,T={}){this.fire(new o.C("dataloading",{dataType:"style"}));const z=typeof T.validate=="boolean"?T.validate:!o.e(N);this.globalId=this._getGlobalId(N),N=this.map._requestManager.normalizeStyleURL(N,T.accessToken),this.resolvedImports.add(N);const W=this.importsCache.get(N);if(W)return this._load(W,z);const Q=this.map._requestManager.transformRequest(N,o.R.Style);this._request=o.m(Q,(ee,ue)=>{if(this._request=null,ee)this.fire(new o.B(ee));else if(ue)return this.importsCache.set(N,ue),this._load(ue,z)})}loadJSON(N,T={}){this.fire(new o.C("dataloading",{dataType:"style"})),this.globalId=this._getGlobalId(N),this._request=o.o.frame(()=>{this._request=null,this._load(N,T.validate!==!1)})}loadEmpty(){this.fire(new o.C("dataloading",{dataType:"style"})),this._load(sw,!1)}_loadImports(N,T,z){if(this.importDepth>=4)return o.w("Style doesn't support nesting deeper than 5"),Promise.resolve();const W=[];for(const Q of N){const ee=this._createFragmentStyle(Q),ue=new Promise(Ie=>{ee.once("style.import.load",Ie),ee.once("error",Ie)}).then(()=>{this.mergeAll(),this.fire(new o.C("data",{dataType:"style"}))});if(W.push(ue),this.resolvedImports.has(Q.url)){ee.loadEmpty();continue}const _e=Q.data||this.importsCache.get(Q.url);_e?(Q.data?(ee.fire(new o.C("dataloading",{dataType:"style"})),ee.globalId=ee._getGlobalId(_e),queueMicrotask(()=>ee._load(_e,T))):ee.loadJSON(_e,{validate:T}),this._isInternalStyle(_e)&&(ee.globalId=null)):Q.url?ee.loadURL(Q.url,{validate:T}):ee.loadEmpty();const Ee={style:ee,id:Q.id,config:Q.config};if(z){const Ie=this.fragments.findIndex(({id:Je})=>Je===z);this.fragments=this.fragments.slice(0,Ie).concat(Ee).concat(this.fragments.slice(Ie))}else this.fragments.push(Ee)}return Promise.allSettled(W)}getImportGlobalIds(N=this,T=new Set){for(const z of N.fragments)z.style.globalId&&T.add(z.style.globalId),this.getImportGlobalIds(z.style,T);return[...T.values()]}_createFragmentStyle(N){const T=this.scope?o.F(N.id,this.scope):N.id;let z;const W=this._initialConfig&&this._initialConfig[T];(N.config||W)&&(z=Object.assign({},N.config,W));const Q=new ph(this.map,{scope:T,styleChanges:this._changes,importDepth:this.importDepth+1,importsCache:this.importsCache,resolvedImports:new Set(this.resolvedImports),dispatcher:this.dispatcher,imageManager:this.imageManager,glyphManager:this.glyphManager,modelManager:this.modelManager,config:z,configOptions:this.options,colorThemeOverride:N["color-theme"],configDependentLayers:this._configDependentLayers,indoorDependentLayers:this._indoorDependentLayers});return Q.setEventedParent(this.map,{style:Q}),Q}_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(N){return this.isRootStyle()&&(N.fragment||!!N.schema&&N.fragment!==!1)}_load(N,T){if(this._isInternalStyle(N)){const Q=Object.assign({},sw,{imports:[{id:"basemap",data:N,url:""}]},N.center?{center:N.center}:{},N.bearing?{bearing:N.bearing}:{},N.pitch?{pitch:N.pitch}:{},N.zoom?{zoom:N.zoom}:{},N.light?{light:N.light}:{});return this._importedAsBasemap=!0,void this._load(Q,T)}if(this.updateConfig(this._config,N.schema),T&&Oy(this,Bn(N)))return;this._loaded=!0;for(const Q in N.sources)this.addSource(Q,N.sources[Q],{validate:!1,isInitialLoad:!0});this.stylesheet=o.d9(N);const z=()=>{if(N.iconsets)for(const _e in N.iconsets)this.addIconset(_e,N.iconsets[_e]);N.sprite?this._loadIconset(N.sprite):(this.imageManager.setLoaded(!0,this.scope),this.dispatcher.broadcast("spriteLoaded",{scope:this.scope,isLoaded:!0})),!this.glyphManager.url&&N.glyphs&&this.glyphManager.setURL(N.glyphs);const Q=Xf(this.stylesheet.layers);if(this._order=Q.map(_e=>_e.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 _e=this.stylesheet.lights[0];this.light=new Br(_e.properties,_e.id)}else this.setLights(this.stylesheet.lights);this.light||(this.light=new Br(this.stylesheet.light)),this._layers={};for(const _e of Q){const Ee=o.de(_e,this.scope,this._styleColorTheme.lut,this.options);Ee.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(Ee.fqid),Ee.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(Ee.fqid),this._hasAppearances=this._hasAppearances||Ee.getAppearances().length!==0,Ee.setEventedParent(this,{layer:{id:Ee.id}}),this._layers[Ee.id]=Ee;const Ie=this.getOwnLayerSourceCache(Ee),Je=!!this.directionalLight&&this.directionalLight.shadowsEnabled();Ie&&Ee.canCastShadows()&&Je&&(Ie.castsShadows=!0)}if(this.glyphManager.url){const _e=new Set;for(const Ee in this._layers){const Ie=this._layers[Ee];if(Ie.type==="symbol"&&Ie.layout){const Je=Ie.layout.get("text-font");Je&&Je.value&&Je.value.kind==="constant"&&_e.add(Je.value.value.join(","))}}for(const Ee of _e)this.glyphManager.prefetchRange(Ee,0)}this.stylesheet.featuresets&&this.setFeaturesetSelectors(this.stylesheet.featuresets),this.stylesheet.models&&this.addModelURLs(this.stylesheet.models);const ee=this.stylesheet.terrain;ee&&(this.checkCanvasFingerprintNoise(),this.disableElevatedTerrain||this.terrainSetForDrapingOnly()||this._createTerrain(ee,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 ue=this.isRootStyle();N.imports?this._loadImports(N.imports,T).then(()=>{this._reloadImports(),this.fire(new o.C(ue?"style.load":"style.import.load"))}).catch(_e=>{this.fire(new o.B(new Error("Failed to load imports",_e))),this.fire(new o.C(ue?"style.load":"style.import.load"))}):(this._reloadImports(),this.fire(new o.C(ue?"style.load":"style.import.load")))};this._styleColorTheme.colorTheme=this.stylesheet["color-theme"];const W=this._styleColorTheme.colorThemeOverride?this._styleColorTheme.colorThemeOverride:this._styleColorTheme.colorTheme;if(W){const Q=this._evaluateColorThemeData(W);this._loadColorTheme(Q).then(()=>{z()}).catch(ee=>{o.w(`Couldn't load color theme from the stylesheet: ${ee}`),z()})}else this._styleColorTheme.lut=null,z()}isRootStyle(){return this.importDepth===0}hasAppearances(){return this._hasAppearances||this.fragments.some(N=>N.style.hasAppearances())}mergeAll(){let N,T,z,W,Q,ee,ue,_e,Ee,Ie;const Je={};this.terrain&&this.terrain.scope!==this.scope&&delete this.terrain,this.forEachFragmentStyle(Ke=>{if(Ke.stylesheet){if(Ke.light!=null&&(N=Ke.light),Ke.stylesheet.lights)for(const tt of Ke.stylesheet.lights)tt.type==="ambient"&&Ke.ambientLight!=null&&(T=Ke.ambientLight),tt.type==="directional"&&Ke.directionalLight!=null&&(z=Ke.directionalLight);W=this._prioritizeTerrain(W,Ke.terrain,Ke.stylesheet.terrain),Ke.stylesheet.fog&&Ke.fog!=null&&(Q=Ke.fog),Ke.stylesheet.snow&&Ke.snow!=null&&(ee=Ke.snow),Ke.stylesheet.rain&&Ke.rain!=null&&(ue=Ke.rain),Ke.stylesheet.camera!=null&&(Ie=Ke.stylesheet.camera),Ke.stylesheet.projection!=null&&(_e=Ke.stylesheet.projection),Ke.stylesheet.transition!=null&&(Ee=Ke.stylesheet.transition),Je[Ke.scope]=Ke._styleColorTheme}}),this.light=N,this.ambientLight=T,this.directionalLight=z,this.fog=Q,this.snow=ee,this.rain=ue,this._styleColorThemeForScope=Je,W===null?delete this.terrain:this.terrain=W,this.camera=Ie||{"camera-projection":"perspective"},this.projection=_e||{name:"mercator"},this.transition=Object.assign({},Zg,Ee),this.mergeSources(),this.mergeLayers(),this.mergeIndoor()}forEachFragmentStyle(N){const T=z=>{for(const W of z.fragments)T(W.style);N(z)};T(this)}_prioritizeTerrain(N,T,z){const W=N&&N.drapeRenderMode===0;return z===null?T&&T.drapeRenderMode===0?T:W?N:null:T!=null&&(!N||W||T&&T.drapeRenderMode===1)?T:N}mergeTerrain(){let N;this.terrain&&this.terrain.scope!==this.scope&&delete this.terrain,this.forEachFragmentStyle(T=>{N=this._prioritizeTerrain(N,T.terrain,T.stylesheet.terrain)}),N===null?delete this.terrain:this.terrain=N}mergeProjection(){let N;this.forEachFragmentStyle(T=>{T.stylesheet.projection!=null&&(N=T.stylesheet.projection)}),this.projection=N||{name:"mercator"}}mergeSources(){const N={},T={},z={},W={};this.forEachFragmentStyle(Q=>{for(const ee in Q._sourceCaches){const ue=o.F(ee,Q.scope);N[ue]=Q._sourceCaches[ee]}for(const ee in Q._otherSourceCaches){const ue=o.F(ee,Q.scope);T[ue]=Q._otherSourceCaches[ee]}for(const ee in Q._symbolSourceCaches){const ue=o.F(ee,Q.scope);z[ue]=Q._symbolSourceCaches[ee]}for(const ee in Q._fillExtrusionSourceCaches){const ue=o.F(ee,Q.scope);W[ue]=Q._fillExtrusionSourceCaches[ee]}}),this._mergedSourceCaches=N,this._mergedOtherSourceCaches=T,this._mergedSymbolSourceCaches=z,this._mergedFillExtrusionSourceCaches=W}mergeIndoor(){this.forEachFragmentStyle(N=>{if(N.stylesheet&&N.stylesheet.indoor)for(const T of Object.values(N.stylesheet.indoor)){const z=T,W=o.F(z.sourceId,N.scope);this._mergedIndoor[W]=new Set(z.sourceLayers||[])}})}mergeLayers(){const N={},T=[],z={};this._mergedSlots=[],this._has3DLayers=!1,this._hasCircleLayers=!1,this._hasSymbolLayers=!1,this.forEachFragmentStyle(ee=>{for(const ue of ee._order){const _e=ee._layers[ue];if(_e.type==="slot"){const Ee=o.da(ue);if(N[Ee])continue;N[Ee]=[]}_e.slot&&N[_e.slot]?N[_e.slot].push(_e):T.push(_e)}}),this._mergedOrder=[];let W=-1;const Q=(ee=[])=>{for(const ue of ee)if(ue.type==="slot"){const _e=o.da(ue.id);N[_e]&&Q(N[_e]),this._mergedSlots.push(_e)}else{const _e=o.F(ue.id,ue.scope);this._mergedOrder.push(_e),z[_e]=ue,ue.is3D(!!this.terrain)&&(this._has3DLayers=!0,W=this._mergedOrder.length-1),ue.type==="circle"&&(this._hasCircleLayers=!0),ue.type==="symbol"&&(this._hasSymbolLayers=!0),ue.type==="clip"&&(this._clipLayerPresent=!0)}};if(Q(T),this._has3DLayers){const ee={};for(let ue=0;ueee[ue]-ee[_e])}this._mergedLayers=z,this.updateDrapeFirstLayers(),this._buildingIndex.processLayersChanged(),this._updateDataDrivenEmissiveStrength()}terrainSetForDrapingOnly(){return!!this.terrain&&this.terrain.drapeRenderMode===0}getCamera(){return this.stylesheet.camera}setCamera(N){return this.stylesheet.camera=Object.assign({},this.stylesheet.camera,N),this.camera=this.stylesheet.camera,this}_evaluateColorThemeData(N){return N.data?function(T,z,W){const Q=Object.assign({},z);for(const ue of Object.keys(mh))Q[ue]===void 0&&(Q[ue]=mh[ue].default);const ee=new o.aa(Ac,T,new Map(W));return ee.setTransitionOrValue(Q,W),ee.untransitioned().possiblyEvaluate(new o.ae(0,{worldview:void 0}))}(this.scope,N,this.options).get("data"):null}_loadColorTheme(N){this._styleColorTheme.lutLoading=!0,this._styleColorTheme.lutLoadingCorrelationID+=1;const T=this._styleColorTheme.lutLoadingCorrelationID;return new Promise((z,W)=>{const Q="data:image/png;base64,";if(!N||N.length===0)return this._styleColorTheme.lut=null,this._styleColorTheme.lutLoading=!1,void z();let ee=N;ee.startsWith(Q)||(ee=Q+ee);const ue=o.I.from("mapbox-reserved-lut"),_e=new Image;_e.src=ee,_e.onerror=()=>{this._styleColorTheme.lutLoading=!1,W(new Error("Failed to load image data"))},_e.onload=()=>{if(this._styleColorTheme.lutLoadingCorrelationID!==T)return void z();this._styleColorTheme.lutLoading=!1;const{width:Ee,height:Ie,data:Je}=o.o.getImageData(_e);if(Ie>32)return void W(new Error("The height of the image must be less than or equal to 32 pixels."));if(Ee!==Ie*Ie)return void W(new Error("The width of the image must be equal to the height squared."));this.getImage(ue)&&this.removeImage(ue),this.addImage(ue,{data:new o.q({width:Ee,height:Ie},Je),pixelRatio:1,sdf:!1,usvg:!1,version:0});const Ke=this.imageManager.getImage(ue,this.scope);Ke?(this._styleColorTheme.lut={image:Ke.data,data:N},z()):W(new Error("Missing LUT image."))}})}getLut(N){const T=this._styleColorThemeForScope[N];return T?T.lut:null}setProjection(N){N?this.stylesheet.projection=N: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(N){this._spriteRequest=function(T,z,W){let Q,ee,ue;const _e=o.o.devicePixelRatio>1?"@2x":"";let Ee=o.m(z.transformRequest(z.normalizeSpriteURL(T,_e,".json"),o.R.SpriteJSON),(Ke,tt)=>{Ee=null,ue||(ue=Ke,Q=tt,Je())}),Ie=o.n(z.transformRequest(z.normalizeSpriteURL(T,_e,".png"),o.R.SpriteImage),(Ke,tt)=>{Ie=null,ue||(ue=Ke,ee=tt,Je())});function Je(){if(ue)W(ue);else if(Q&&ee){const Ke=o.o.getImageData(ee),tt={};for(const ut in Q){const{width:lt,height:kt,x:Nt,y:zt,sdf:Yt,pixelRatio:Tt,stretchX:Ss,stretchY:cs,content:Ns}=Q[ut],Zt=new o.q({width:lt,height:kt});o.q.copy(Ke,Zt,{x:Nt,y:zt},{x:0,y:0},{width:lt,height:kt},null),tt[ut]={data:Zt,pixelRatio:Tt!==void 0?Tt:1,sdf:Yt!==void 0&&Yt,stretchX:Ss,stretchY:cs,content:Ns,usvg:!1,version:0}}W(null,tt)}}return{cancel(){Ee&&(Ee.cancel(),Ee=null),Ie&&(Ie.cancel(),Ie=null)}}}(N,this.map._requestManager,(T,z)=>{if(this._spriteRequest=null,T)this.fire(new o.B(T));else if(z){const W=new Map;for(const Q in z)W.set(o.I.from(Q),z[Q]);this.addImages(W)}this.imageManager.setLoaded(!0,this.scope),this.dispatcher.broadcast("spriteLoaded",{scope:this.scope,isLoaded:!0}),this.fire(new o.C("data",{dataType:"style"}))})}addIconset(N,T){if(T.type==="sprite")return void this._loadSprite(T.url);const z=this.getOwnSourceCache(T.source);if(!z)return void this.fire(new o.B(new Error(`Source "${T.source}" as specified by iconset "${N}" does not exist and cannot be used as an iconset source`)));const W=z.getSource();if(W.type!=="raster-array")return void this.fire(new o.B(new Error(`Source "${T.source}" as specified by iconset "${N}" is not a "raster-array" source and cannot be used as an iconset source`)));W.partial=!1;const Q=new $u(N,this.scope,z);this.imageManager.addImageProvider(Q,this.scope)}removeIconset(N){this.imageManager.removeImageProvider(N,this.scope)}_loadIconset(N){if(!o.e(N)&&this.map._spriteFormat!=="icon_set"||this.map._spriteFormat==="raster")return void this._loadSprite(N);const T=this.map._spriteFormat==="auto";var z,W;this._spriteRequest=(W=(Q,ee)=>{if(this._spriteRequest=null,Q)T?this._loadSprite(N):this.fire(new o.B(Q));else if(ee){const ue=new Map;for(const _e in ee)ue.set(o.I.from(_e),ee[_e]);this.addImages(ue)}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((z=this.map._requestManager).transformRequest(z.normalizeIconsetURL(N),o.R.Iconset),(Q,ee)=>{if(Q)return void W(Q);const ue={},_e=o.c$(new o.a$(ee));for(const Ee of _e.icons){const Ie={version:1,pixelRatio:o.o.devicePixelRatio,content:Cl(Ee),stretchX:Ee.metadata?pl(Ee.metadata.stretch_x_areas):void 0,stretchY:Ee.metadata?pl(Ee.metadata.stretch_y_areas):void 0,sdf:!1,usvg:!0,icon:Ee};ue[Ee.name]=Ie}W(null,ue)}))}_validateLayer(N){const T=this.getOwnSource(N.source);if(!T)return;const z=N.sourceLayer;z&&(T.type==="geojson"||T.vectorLayerIds&&T.vectorLayerIds.indexOf(z)===-1)&&this.fire(new o.B(new Error(`Source layer "${z}" does not exist on source "${T.id}" as specified by style layer "${N.id}"`)))}loaded(){if(!this._loaded||Object.keys(this._changes.getUpdatedSourceCaches()).length)return!1;for(const N in this._sourceCaches)if(!this._sourceCaches[N].loaded())return!1;if(!this.imageManager.isLoaded()||this.imageManager.hasPatternsInFlight()||!this.modelManager.isLoaded()||this._styleColorTheme.lutLoading)return!1;for(const{style:N}of this.fragments)if(!N.loaded())return!1;return!0}_serializeImports(){if(this.stylesheet.imports)return this.stylesheet.imports.map((N,T)=>{const z=this.fragments[T];return z&&z.style&&(N.data=z.style.serialize()),N})}_serializeSources(){const N={};for(const T in this._sourceCaches){const z=this._sourceCaches[T].getSource();N[z.id]||(N[z.id]=z.serialize())}return N}_serializeLayers(N){const T=[];for(const z of N){const W=this._layers[z];W&&W.type!=="custom"&&T.push(W.serialize())}return T}hasLightTransitions(){return!(!this.light||!this.light.hasTransition())||!(!this.ambientLight||!this.ambientLight.hasTransition())||!(!this.directionalLight||!this.directionalLight.hasTransition())}hasFogTransition(){return!!this.fog&&this.fog.hasTransition()}hasSnowTransition(){return!!this.snow&&this.snow.hasTransition()}hasRainTransition(){return!!this.rain&&this.rain.hasTransition()}hasTransitions(){if(this.hasLightTransitions()||this.hasFogTransition()||this.hasSnowTransition()||this.hasRainTransition())return!0;for(const N in this._sourceCaches)if(this._sourceCaches[N].hasTransition())return!0;for(const N in this._layers)if(this._layers[N].hasTransition())return!0;return!1}_updateDataDrivenEmissiveStrength(){for(const N in this._mergedLayers){const T=this._mergedLayers[N];if(T._transitionablePaint&&T._transitionablePaint._values){const z=T._transitionablePaint._values["line-emissive-strength"];if(z&&z.value&&z.value.isDataDriven())return void(this._hasDataDrivenEmissive=!0)}}this._hasDataDrivenEmissive=!1}hasDataDrivenEmissiveStrength(){return this._hasDataDrivenEmissive}get order(){return this.terrain?this._drapedFirstOrder:this._mergedOrder}_getOrder(N){return N?this.order:this._mergedOrder}isLayerDraped(N){return!!this.terrain&&N.isDraped(this.getLayerSourceCache(N))}_checkLoaded(){if(!this._loaded)throw new Error("Style is not done loading")}_checkLayer(N){const T=this.getOwnLayer(N);if(T)return T;this.fire(new o.B(new Error(`The layer '${N}' does not exist in the map's style.`)))}_checkSource(N){const T=this.getOwnSource(N);if(T)return T;this.fire(new o.B(new Error(`The source '${N}' does not exist in the map's style.`)))}precompilePrograms(N,T){const z=this.map.painter;if(z)for(let W=N.minzoom||0;W<(N.maxzoom||25.5);W++){const Q=N.getProgramIds();if(Q)for(const ee of Q){const ue=N.getDefaultProgramParams(ee,T.zoom,this._styleColorTheme.lut);ue&&(z.style=this,this.fog&&(z._fogVisible=!0,ue.overrideFog=!0,z.getOrCreateProgram(ee,ue)),z._fogVisible=!1,ue.overrideFog=!1,z.getOrCreateProgram(ee,ue),(this.stylesheet.terrain||this.stylesheet.projection&&this.stylesheet.projection.name==="globe")&&(ue.overrideRtt=!0,z.getOrCreateProgram(ee,ue)))}}}update(N){if(!this._loaded)return;this.ambientLight&&this.ambientLight.recalculate(N),this.directionalLight&&this.directionalLight.recalculate(N);const T=this.calculateLightsBrightness();N.brightness=T||0,T!==this._brightness&&(this._brightness=T,this.dispatcher.broadcast("setBrightness",T)),N.worldview!==this._worldview&&(this._worldview=N.worldview,this.dispatcher.broadcast("setWorldview",this._worldview));const z=this._changes.isDirty();let W=!1;if(this._changes.isDirty()){const _e=this._changes.getLayerUpdatesByScope();for(const Ee in _e){const{updatedIds:Ie,removedIds:Je}=_e[Ee];(Ie||Je)&&(this._updateWorkerLayers(Ee,Ie,Je),W=!0)}this.updateSourceCaches(),this._updateTilesForChangedImages(),this.updateLayers(N),this.light&&this.light.updateTransitions(N),this.ambientLight&&this.ambientLight.updateTransitions(N),this.directionalLight&&this.directionalLight.updateTransitions(N),this.fog&&this.fog.updateTransitions(N),this.snow&&this.snow.updateTransitions(N),this.rain&&this.rain.updateTransitions(N),this._changes.reset()}const Q={};for(const _e in this._mergedSourceCaches){const Ee=this._mergedSourceCaches[_e];Q[_e]=Ee.used,Ee.used=!1,Ee.tileCoverLift=0}const ee={};for(const _e of this._mergedOrder){const Ee=this._mergedLayers[_e];if((Ee.visibility!=="none"||Ee.hasTransition())&&Ee.recalculate(N,this._availableImages),!Ee.isHidden(N.zoom)){const Ie=this.getLayerSourceCache(Ee);Ie&&(Ie.used=!0,Ie.tileCoverLift=Math.max(Ie.tileCoverLift,Ee.tileCoverLift()))}if(Ee.type==="fill-extrusion"){const Ie=o.F(Ee.source,Ee.scope);if(Ie in this._mergedFillExtrusionSourceCaches){const Je=Ee.layout&&Ee.layout.get("source-max-zoom");if(Je!=null){const Ke=ee[Ie];ee[Ie]=Ke==null?Je:Math.min(Ke,Je)}}}!this._precompileDone&&this._shouldPrecompile&&("requestIdleCallback"in window?requestIdleCallback(()=>{this.precompilePrograms(Ee,N)}):this.precompilePrograms(Ee,N))}this._shouldPrecompile&&(this._precompileDone=!0);for(const _e in this._mergedFillExtrusionSourceCaches)this._mergedFillExtrusionSourceCaches[_e].setMaxzoomOverride(ee[_e]!=null?ee[_e]:null);this.terrain&&W&&this.mergeLayers();const ue=this.imageManager.getPendingImageProviders();for(const _e of ue)_e.sourceCache.used=!0;for(const _e in Q){const Ee=this._mergedSourceCaches[_e];Q[_e]!==Ee.used&&Ee.getSource().fire(new o.C("data",{sourceDataType:"visibility",dataType:"source",sourceId:Ee.getSource().id}))}this.light&&this.light.recalculate(N),this.terrain&&this.terrain.recalculate(N),this.fog&&this.fog.recalculate(N),this.snow&&this.snow.recalculate(N),this.rain&&this.rain.recalculate(N),this.z=N.zoom,this._markersNeedUpdate&&(this._updateMarkersOpacity(),this._markersNeedUpdate=!1),this.imageManager.clearUpdatedImages(this.scope),z&&this.fire(new o.C("data",{dataType:"style"}))}updateImageProviders(){const N=this.imageManager.getPendingImageProviders();for(const T of N){const z=T.resolvePendingRequests(),W=this.getFragmentStyle(T.scope);W&&W.addImages(z)}}_updateTilesForChangedImages(){const N={};for(const T in this._mergedSourceCaches){const z=this._mergedSourceCaches[T].getSource().scope;N[z]=N[z]||this._changes.getUpdatedImages(z),N[z].length!==0&&this._mergedSourceCaches[T].reloadTilesForDependencies(["icons","patterns"],N[z])}for(const T in N)this._changes.resetUpdatedImages(T)}_updateWorkerLayers(N,T,z){const W=this.getFragmentStyle(N);W&&this.dispatcher.broadcast("updateLayers",{layers:T?W._serializeLayers(T):[],scope:N,removedIds:z||[],options:W.options})}setState(N,T){if(this._checkLoaded(),Oy(this,Bn(N)))return!1;(N=o.d9(N)).layers=Xf(N.layers);const z=function(ee,ue){if(!ee)return[{command:Ti.setStyle,args:[ue]}];let _e=[];try{if(!o.b6(ee.version,ue.version))return[{command:Ti.setStyle,args:[ue]}];if(o.b6(ee.center,ue.center)||_e.push({command:Ti.setCenter,args:[ue.center]}),o.b6(ee.zoom,ue.zoom)||_e.push({command:Ti.setZoom,args:[ue.zoom]}),o.b6(ee.bearing,ue.bearing)||_e.push({command:Ti.setBearing,args:[ue.bearing]}),o.b6(ee.pitch,ue.pitch)||_e.push({command:Ti.setPitch,args:[ue.pitch]}),o.b6(ee.sprite,ue.sprite)||_e.push({command:Ti.setSprite,args:[ue.sprite]}),o.b6(ee.glyphs,ue.glyphs)||_e.push({command:Ti.setGlyphs,args:[ue.glyphs]}),o.b6(ee.imports,ue.imports)||function(tt=[],ut=[],lt){ut=ut||[];const kt=(tt=tt||[]).map(Yh),Nt=ut.map(Yh),zt=tt.reduce(B0,{}),Yt=ut.reduce(B0,{}),Tt=kt.slice();let Ss,cs,Ns,Zt;for(Ss=0,cs=0;Ss{tt.source&&Ee[tt.source]?_e.push({command:Ti.removeLayer,args:[tt.id]}):Je.push(tt)});let Ke=ee.terrain;Ke&&Ee[Ke.source]&&(_e.push({command:Ti.setTerrain,args:[void 0]}),Ke=void 0),_e=_e.concat(Ie),o.b6(Ke,ue.terrain)||_e.push({command:Ti.setTerrain,args:[ue.terrain]}),function(tt,ut,lt){ut=ut||[];const kt=(tt=tt||[]).map(Yh),Nt=ut.map(Yh),zt=tt.reduce(B0,{}),Yt=ut.reduce(B0,{}),Tt=kt.slice(),Ss=Object.create(null);let cs,Ns,Zt,ns,bs,Ks,Es;for(cs=0,Ns=0;cs!(ee.command in tw));if(z.length===0)return!1;const W=z.filter(ee=>!(ee.command in bm));if(W.length>0)throw new Error(`Unimplemented: ${W.map(ee=>ee.command).join(", ")}.`);const Q=[];return z.forEach(ee=>{Q.push(this[ee.command](...ee.args))}),T&&Promise.all(Q).then(T).catch(T),this.stylesheet=N,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(N){if(N.size===0)return this;for(const[T,z]of N.entries()){if(this.getImage(T))return this.fire(new o.B(new Error(`An image with the name "${T.name}" already exists.`)));this.imageManager.addImage(T,this.scope,z),this._changes.updateImage(T,this.scope)}return this._updateWorkerImages(),this.fire(new o.C("data",{dataType:"style"})),this}addImage(N,T){return this.getImage(N)?this.fire(new o.B(new Error(`An image with the name "${N.name}" already exists.`))):(this.imageManager.addImage(N,this.scope,T),this._changes.updateImage(N,this.scope),this._updateWorkerImages(),this.fire(new o.C("data",{dataType:"style"})),this)}updateImage(N,T,z=!1){this.imageManager.updateImage(N,this.scope,T),z&&(this._changes.updateImage(N,this.scope),this._updateWorkerImages(),this.fire(new o.C("data",{dataType:"style"})))}getImage(N){return this.imageManager.getImage(N,this.scope)}removeImage(N){return this.getImage(N)?(this.imageManager.removeImage(N,this.scope),this._changes.updateImage(N,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(N){return this.modelManager.addModelURLs(N,this.getActualScope()),this._updateWorkerModels(),this.fire(new o.C("data",{dataType:"style"})),this}addModel(N,T,z={}){return this._checkLoaded(),this._validate(Qs,`models.${N}`,T,null,z)||(this.modelManager.addModel(N,T,this.getActualScope()),this.fire(new o.C("data",{dataType:"style"}))),this}hasModel(N){return this.modelManager.hasModel(N,this.getActualScope())}removeModel(N){return this.hasModel(N)?(this.modelManager.removeModel(N,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(N,T,z={}){if(this._checkLoaded(),this.getOwnSource(N)!==void 0)throw new Error(`There is already a source with ID "${N}".`);if(!T.type)throw new Error(`The type property must be defined, but only the following properties were given: ${Object.keys(T).join(", ")}.`);if(["vector","raster","geojson","video","image"].indexOf(T.type)>=0&&this._validate(or,`sources.${N}`,T,null,z))return;this.map&&this.map._collectResourceTiming&&(T.collectResourceTiming=!0);const W=bi(N,T,this.dispatcher,this);W.scope=this.scope,W.setEventedParent(this,()=>({isSourceLoaded:this._isSourceCacheLoaded(W.id),source:W.serialize(),sourceId:W.id}));const Q=ee=>{const ue=(ee===o.b4.Symbol?"symbol:":ee===o.b4.FillExtrusion?"fill-extrusion:":"other:")+W.id,_e=o.F(ue,this.scope),Ee=this._sourceCaches[ue]=new Dc(_e,W,ee);ee===o.b4.Symbol?this._symbolSourceCaches[W.id]=Ee:ee===o.b4.FillExtrusion?this._fillExtrusionSourceCaches[W.id]=Ee:this._otherSourceCaches[W.id]=Ee,Ee.onAdd(this.map)};Q(o.b4.Other),T.type!=="vector"&&T.type!=="geojson"||(Q(o.b4.Symbol),T.type==="vector"&&Q(o.b4.FillExtrusion)),W.onAdd&&W.onAdd(this.map),z.isInitialLoad||(this.mergeSources(),this._changes.setDirty())}removeSource(N){this._checkLoaded();const T=this.getOwnSource(N);if(!T)throw new Error("There is no source with this ID");for(const W in this._layers)if(this._layers[W].source===N)return this.fire(new o.B(new Error(`Source "${N}" cannot be removed while layer "${W}" is using it.`)));if(this.terrain&&this.terrain.scope===this.scope&&this.terrain.get().source===N)return this.fire(new o.B(new Error(`Source "${N}" cannot be removed while terrain is using it.`)));if(this.stylesheet.iconsets){const W=Object.entries(this.stylesheet.iconsets).find(([Q,ee])=>ee.type==="source"&&ee.source===N);if(W)return this.fire(new o.B(new Error(`Source "${N}" cannot be removed while iconset "${W[0]}" is using it.`)))}const z=this.getOwnSourceCaches(N);for(const W of z){const Q=o.da(W.id);delete this._sourceCaches[Q],this._changes.discardSourceCacheUpdate(W.id),W.fire(new o.C("data",{sourceDataType:"metadata",dataType:"source",sourceId:W.getSource().id})),W.setEventedParent(null),W.clearTiles()}return delete this._otherSourceCaches[N],delete this._symbolSourceCaches[N],delete this._fillExtrusionSourceCaches[N],this.mergeSources(),T.setEventedParent(null),T.onRemove&&T.onRemove(this.map),this._changes.setDirty(),this}setGeoJSONSourceData(N,T){this._checkLoaded(),this.getOwnSource(N).setData(T),this._changes.setDirty()}getOwnSource(N){const T=this.getOwnSourceCache(N);return T&&T.getSource()}getOwnSources(){const N=[];for(const T in this._otherSourceCaches){const z=this.getOwnSourceCache(T);z&&N.push(z.getSource())}return N}areTilesLoaded(){const N=this._mergedSourceCaches;for(const T in N){const z=N[T]._tiles;for(const W in z){const Q=z[W];if(Q.state!=="loaded"&&Q.state!=="errored")return!1}}return!0}setLights(N){if(this._checkLoaded(),!N)return delete this.ambientLight,void delete this.directionalLight;const T=this._getTransitionParameters();for(const Q of N){if(this._validate(rt,"lights",Q))return;switch(Q.type){case"ambient":if(this.ambientLight){const ee=this.ambientLight;ee.set(Q),ee.updateTransitions(T)}else this.ambientLight=new rr(Q,oi(),this.scope,this.options);break;case"directional":if(this.directionalLight){const ee=this.directionalLight;ee.set(Q),ee.updateTransitions(T)}else this.directionalLight=new rr(Q,kl(),this.scope,this.options)}}const z=Object.assign(T,{worldview:this.map.getWorldview()}),W=new o.ae(this.z||0,z);this.ambientLight&&this.ambientLight.recalculate(W),this.directionalLight&&this.directionalLight.recalculate(W),this._brightness=this.calculateLightsBrightness(),this.dispatcher.broadcast("setBrightness",this._brightness)}calculateLightsBrightness(){const N=this.directionalLight,T=this.ambientLight;if(!N||!T)return;const z=Ke=>.2126*(Ke[0]<=.03928?Ke[0]/12.92:Math.pow((Ke[0]+.055)/1.055,2.4))+.7152*(Ke[1]<=.03928?Ke[1]/12.92:Math.pow((Ke[1]+.055)/1.055,2.4))+.0722*(Ke[2]<=.03928?Ke[2]/12.92:Math.pow((Ke[2]+.055)/1.055,2.4)),W=N.properties.get("color").toNonPremultipliedRenderColor(null).toArray01(),Q=N.properties.get("intensity"),ee=N.properties.get("direction"),ue=1-o.cP(ee.x,ee.y,ee.z)[2]/90,_e=z(W)*Q*ue,Ee=T.properties.get("color").toNonPremultipliedRenderColor(null).toArray01(),Ie=T.properties.get("intensity"),Je=z(Ee)*Ie;return Number(((_e+Je)/2).toFixed(6))}getBrightness(){return this._brightness}getLights(){if(!this.enable3dLights())return null;const N=[];return this.directionalLight&&N.push(this.directionalLight.get()),this.ambientLight&&N.push(this.ambientLight.get()),N}enable3dLights(){return!!this.ambientLight&&!!this.directionalLight}getFragmentStyle(N){if(N==null||N===""&&this.isRootStyle())return this;if(o.db(N)){const T=o.dc(N),z=this.fragments.find(({id:Q})=>Q===T);if(!z)return;const W=o.da(N);return z.style.getFragmentStyle(W)}{const T=this.fragments.find(({id:z})=>z===N);return T?T.style:void 0}}setFeaturesetSelectors(N){if(!N)return;const T=(z,W="")=>`${z}::${W}`;this._featuresetSelectors={};for(const z in N){const W={},Q=this._featuresetSelectors[z]=[];for(const ee of N[z].selectors){if(ee.featureNamespace){const _e=this.getOwnLayer(ee.layer);if(!_e){o.w(`Layer is undefined for selector: ${ee.layer}`);continue}const Ee=T(_e.source,_e.sourceLayer);if(Ee in W&&W[Ee]!==ee.featureNamespace){o.w(`"featureNamespace ${ee.featureNamespace} of featureset ${z}'s selector is not associated to the same source, skip this selector`);continue}W[Ee]=ee.featureNamespace}let ue;if(ee.properties)for(const _e in ee.properties){const Ee=o.X(ee.properties[_e]);Ee.result==="success"&&(ue=ue||{},ue[_e]=Ee.value)}Q.push({layerId:ee.layer,namespace:ee.featureNamespace,properties:ue,uniqueFeatureID:ee._uniqueFeatureID})}}}getFeaturesetDescriptors(N){const T=this.getFragmentStyle(N);if(!T||!T.stylesheet.featuresets)return[];const z=[];for(const W in T.stylesheet.featuresets)z.push({featuresetId:W,importId:T.scope?T.scope:void 0});return z}getFeaturesetLayers(N,T){const z=this.getFragmentStyle(T),W=z.stylesheet.featuresets;if(!W||!W[N])return this.fire(new o.B(new Error(`The featureset '${N}' does not exist in the map's style and cannot be queried.`))),[];const Q=[];for(const ee of W[N].selectors){const ue=z.getOwnLayer(ee.layer);ue&&Q.push(ue)}return Q}getConfigProperty(N,T){const z=this.getFragmentStyle(N);if(!z)return null;const W=o.F(T,z.scope),Q=z.options.get(W),ee=Q?Q.value||Q.default:null;return ee?ee.serialize():null}isIndoorEnabled(){return Object.keys(this._mergedIndoor).length>0}getIndoorSourceLayers(N,T){const z=o.F(N,T);return this._mergedIndoor[z]}setIndoorData(N,T){this.indoorManager.setIndoorData(T)}updateIndoorDependentLayers(){this._updateLayers(this._indoorDependentLayers),this.map._styleDirty=!0,this.map.triggerRepaint()}setConfigProperty(N,T,z){const W=this.getFragmentStyle(N);if(!W)return;const Q=W.stylesheet.schema;if(!Q||!Q[T])return;const ee=o.X(z);if(ee.result!=="success")return void Oy(this,ee.value);const ue=ee.value.expression,_e=o.F(T,W.scope),Ee=W.options.get(_e);if(!Ee)return;let Ie;const{minValue:Je,maxValue:Ke,stepValue:tt,type:ut,values:lt}=Q[T],kt=o.X(Q[T].default);kt.result==="success"&&(Ie=kt.value.expression),Ie?(this.options.set(_e,Object.assign({},Ee,{value:ue,default:Ie,minValue:Je,maxValue:Ke,stepValue:tt,type:ut,values:lt})),this.updateConfigDependencies(T)):this.fire(new o.B(new Error(`No schema defined for the config option "${T}" in the "${N}" fragment.`)))}getConfig(N){const T=this.getFragmentStyle(N);if(!T)return null;const z=T.stylesheet.schema;if(!z)return null;const W={};for(const Q in z){const ee=o.F(Q,T.scope),ue=T.options.get(ee),_e=ue?ue.value||ue.default:null;W[Q]=_e?_e.serialize():null}return W}setConfig(N,T){const z=this.getFragmentStyle(N);z&&(z.updateConfig(T,z.stylesheet.schema),this.updateConfigDependencies())}getSchema(N){const T=this.getFragmentStyle(N);return T?T.stylesheet.schema:null}setSchema(N,T){const z=this.getFragmentStyle(N);z&&(z.stylesheet.schema=T,z.updateConfig(z._config,T),this.updateConfigDependencies())}updateConfig(N,T){if(this._config=N,N||T)if(T)for(const z in T){let W,Q;const ee=o.X(T[z].default);if(ee.result==="success"&&(W=ee.value.expression),N&&N[z]!==void 0){const Ke=o.X(N[z]);Ke.result==="success"&&(Q=Ke.value.expression)}const{minValue:ue,maxValue:_e,stepValue:Ee,type:Ie,values:Je}=T[z];if(W){const Ke=o.F(z,this.scope);this.options.set(Ke,{default:W,value:Q,minValue:ue,maxValue:_e,stepValue:Ee,type:Ie,values:Je})}else this.fire(new o.B(new Error(`No schema defined for config option "${z}".`)))}else this.fire(new o.B(new Error("Attempting to set config for a style without schema.")))}_updateLayers(N,T=()=>!0){for(const z of N){const W=this.getLayer(z);W&&T(W)&&(W.possiblyEvaluateVisibility(),this._updateLayer(W),this._changes.setDirty())}}updateConfigDependencies(N){this._updateLayers(this._configDependentLayers,T=>!N||T.expressionDependencies.configDependencies.has(N)),this.ambientLight&&this.ambientLight.updateConfig(this.options),this.directionalLight&&this.directionalLight.updateConfig(this.options),this.fog&&this.fog.updateConfig(this.options),this.snow&&this.snow.updateConfig(this.options),this.rain&&this.rain.updateConfig(this.options),this.forEachFragmentStyle(T=>{const z=T._styleColorTheme.colorThemeOverride?T._styleColorTheme.colorThemeOverride:T._styleColorTheme.colorTheme;if(z){const W=T._evaluateColorThemeData(z);(!T._styleColorTheme.lut&&W!==""||T._styleColorTheme.lut&&W!==T._styleColorTheme.lut.data)&&T.setColorTheme(z)}}),this._changes.setDirty()}addLayer(N,T,z={}){this._checkLoaded();const W=N.id;if(this._layers[W])return void this.fire(new o.B(new Error(`Layer with id "${W}" already exists on this map`)));let Q;if(N.type==="custom"){if(Oy(this,o.dd(N)))return;Q=o.de(N,this.scope,this._styleColorTheme.lut,this.options)}else{if(typeof N.source=="object"&&(this.addSource(W,N.source),N=o.d9(N),N=Object.assign(N,{source:W})),this._validate(ps,`layers.${W}`,N,{arrayIndex:-1},z))return;Q=o.de(N,this.scope,this._styleColorTheme.lut,this.options),this._validateLayer(Q),Q.setEventedParent(this,{layer:{id:W}})}const ee=o.F(Q.source,Q.scope);Q.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(ee),Q.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(ee);let ue=this._order.length;if(T){const Je=this._order.indexOf(T);if(Je===-1)return void this.fire(new o.B(new Error(`Layer with id "${T}" does not exist on this map.`)));Q.slot&&Q.slot!==this._layers[T].slot?o.w(`Layer with id "${T}" has a different slot. Layers can only be rearranged within the same slot.`):ue=Je}this._order.splice(ue,0,W),this._handleLayerOrderChange(),this._layers[W]=Q;const _e=this.getOwnLayerSourceCache(Q),Ee=!!this.directionalLight&&this.directionalLight.shadowsEnabled();_e&&Q.canCastShadows()&&Ee&&(_e.castsShadows=!0);const Ie=this._changes.getRemovedLayer(Q);if(Ie&&Q.source&&_e&&Q.type!=="custom"){this._changes.discardLayerRemoval(Q);const Je=o.F(Q.source,Q.scope);Ie.type!==Q.type?this._changes.updateSourceCache(Je,"clear"):(this._changes.updateSourceCache(Je,"reload"),_e.pause())}this._updateLayer(Q),Q.onAdd&&Q.onAdd(this.map),Q.scope=this.scope,this.mergeLayers()}moveLayer(N,T){this._checkLoaded();const z=this._checkLayer(N);if(!z||N===T)return;const W=this._order.indexOf(N);this._order.splice(W,1);let Q=this._order.length;if(T){const ee=this._order.indexOf(T);if(ee===-1)return void this.fire(new o.B(new Error(`Layer with id "${T}" does not exist on this map.`)));z.slot&&z.slot!==this._layers[T].slot?o.w(`Layer with id "${T}" has a different slot. Layers can only be rearranged within the same slot.`):Q=ee}this._order.splice(Q,0,N),this._changes.setDirty(),this._handleLayerOrderChange(),this.mergeLayers()}removeLayer(N){this._checkLoaded();const T=this._checkLayer(N);if(!T)return;T.setEventedParent(null);const z=this._order.indexOf(N);this._order.splice(z,1),delete this._layers[N],this._changes.setDirty(),this._handleLayerOrderChange(),this._configDependentLayers.delete(T.fqid),this._indoorDependentLayers.delete(T.fqid),this._changes.removeLayer(T);const W=this.getOwnLayerSourceCache(T);if(W&&W.castsShadows){let Q=!1;for(const ee in this._layers)if(this._layers[ee].source===T.source&&this._layers[ee].canCastShadows()){Q=!0;break}W.castsShadows=Q}T.onRemove&&T.onRemove(this.map),this.mergeLayers()}getOwnLayer(N){return this._layers[N]}hasLayer(N){return N in this._mergedLayers}hasLayerType(N){for(const T in this._layers)if(this._layers[T].type===N)return!0;return!1}setLayerZoomRange(N,T,z){this._checkLoaded();const W=this._checkLayer(N);W&&(W.minzoom===T&&W.maxzoom===z||(T!=null&&(W.minzoom=T),z!=null&&(W.maxzoom=z),this._updateLayer(W)))}getSlots(){return this._checkLoaded(),this._mergedSlots}setSlot(N,T){this._checkLoaded();const z=this._checkLayer(N);z&&z.slot!==T&&(z.slot=T,this._updateLayer(z))}setFilter(N,T,z={}){this._checkLoaded();const W=this._checkLayer(N);if(W&&!o.b6(W.filter,T))return T==null?(W.filter=void 0,void this._updateLayer(W)):void(this._validate(Is,`layers.${W.id}.filter`,T,{layerType:W.type},z)||(W.filter=o.d9(T),this._updateLayer(W)))}getFilter(N){const T=this._checkLayer(N);if(T)return o.d9(T.filter)}setLayoutProperty(N,T,z,W={}){this._checkLoaded();const Q=this._checkLayer(N);if(Q&&!o.b6(Q.getLayoutProperty(T),z)){if(z!=null&&(!W||W.validate!==!1)&&Oy(Q,Kt.call(Bn,{key:`layers.${N}.layout.${T}`,layerType:Q.type,objectKey:T,value:z,styleSpec:o.a8,style:{glyphs:!0,sprite:!0}})))return;Q.setLayoutProperty(T,z),Q.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(Q.fqid),Q.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(Q.fqid),this._updateLayer(Q)}}setLayerProperty(N,T,z,W={}){this._checkLoaded();const Q=this._checkLayer(N);Q&&(T==="appearances"?(Q.setAppearances(z),this._updateLayer(Q)):Q.isPaintProperty(T)?this.setPaintProperty(N,T,z,W):this.setLayoutProperty(N,T,z,W))}getLayoutProperty(N,T){const z=this._checkLayer(N);if(z)return z.getLayoutProperty(T)}setPaintProperty(N,T,z,W={}){this._checkLoaded();const Q=this._checkLayer(N);if(!Q||o.b6(Q.getPaintProperty(T),z)||z!=null&&(!W||W.validate!==!1)&&Oy(Q,js.call(Bn,{key:`layers.${N}.paint.${T}`,layerType:Q.type,objectKey:T,value:z,styleSpec:o.a8})))return;const ee=Q.setPaintProperty(T,z);Q.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(Q.fqid),Q.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(Q.fqid),ee&&this._updateLayer(Q),this._changes.updatePaintProperties(Q)}getPaintProperty(N,T){const z=this._checkLayer(N);if(z)return z.getPaintProperty(T)}setFeatureState(N,T){if(this._checkLoaded(),"target"in N){if("featuresetId"in N.target){const{featuresetId:_e,importId:Ee}=N.target,Ie=this.getFragmentStyle(Ee),Je=Ie.getFeaturesetLayers(_e);for(const{source:Ke,sourceLayer:tt}of Je)Ie.setFeatureState({id:N.id,source:Ke,sourceLayer:tt},T)}else if("layerId"in N.target){const{layerId:_e}=N.target,Ee=this.getLayer(_e);this.setFeatureState({id:N.id,source:Ee.source,sourceLayer:Ee.sourceLayer},T)}return}const z=N.source,W=N.sourceLayer,Q=this._checkSource(z);if(!Q)return;const ee=Q.type;if(ee==="geojson"&&W)return void this.fire(new o.B(new Error("GeoJSON sources cannot have a sourceLayer parameter.")));if(ee==="vector"&&!W)return void this.fire(new o.B(new Error("The sourceLayer parameter must be provided for vector source types.")));N.id===void 0&&this.fire(new o.B(new Error("The feature id parameter must be provided.")));const ue=this.getOwnSourceCaches(z);for(const _e of ue)_e.setFeatureState(W,N.id,T)}removeFeatureState(N,T){if(this._checkLoaded(),"target"in N){if("featuresetId"in N.target){const{featuresetId:_e,importId:Ee}=N.target,Ie=this.getFragmentStyle(Ee),Je=Ie.getFeaturesetLayers(_e);for(const{source:Ke,sourceLayer:tt}of Je)Ie.removeFeatureState({id:N.id,source:Ke,sourceLayer:tt},T)}else if("layerId"in N.target){const{layerId:_e}=N.target,Ee=this.getLayer(_e);this.removeFeatureState({id:N.id,source:Ee.source,sourceLayer:Ee.sourceLayer},T)}return}const z=N.source,W=this._checkSource(z);if(!W)return;const Q=W.type,ee=Q==="vector"?N.sourceLayer:void 0;if(Q==="vector"&&!ee)return void this.fire(new o.B(new Error("The sourceLayer parameter must be provided for vector source types.")));if(T&&typeof N.id!="string"&&typeof N.id!="number")return void this.fire(new o.B(new Error("A feature id is required to remove its specific state property.")));const ue=this.getOwnSourceCaches(z);for(const _e of ue)_e.removeFeatureState(ee,N.id,T)}getFeatureState(N){if(this._checkLoaded(),"target"in N){let Q;if("featuresetId"in N.target){const{featuresetId:ee,importId:ue}=N.target,_e=this.getFragmentStyle(ue),Ee=_e.getFeaturesetLayers(ee);for(const{source:Ie,sourceLayer:Je}of Ee){const Ke=_e.getFeatureState({id:N.id,source:Ie,sourceLayer:Je});if(Ke&&!Q)Q=Ke;else if(!o.b6(Q,Ke))return void this.fire(new o.B(new Error("The same feature id exists in multiple sources in the featureset, but their feature states are not consistent through the sources.")))}}else if("layerId"in N.target){const{layerId:ee}=N.target,ue=this.getLayer(ee);Q=this.getFeatureState({id:N.id,source:ue.source,sourceLayer:ue.sourceLayer})}return Q}const T=N.source,z=N.sourceLayer,W=this._checkSource(T);if(W){if(W.type!=="vector"||z)return N.id===void 0&&this.fire(new o.B(new Error("The feature id parameter must be provided."))),this.getOwnSourceCaches(T)[0].getFeatureState(z,N.id);this.fire(new o.B(new Error("The sourceLayer parameter must be provided for vector source types.")))}}setTransition(N){return this.stylesheet.transition=Object.assign({},this.stylesheet.transition,N),this.transition=this.stylesheet.transition,this}getTransition(){return Object.assign({},this.stylesheet.transition)}setWorldview(N){N!==this._worldview&&(this._worldview=N,this.dispatcher.broadcast("setWorldview",this._worldview),this.reloadSources())}serialize(){this._checkLoaded();const N=this.getTerrain(),T=N&&this.terrain&&this.terrain.scope===this.scope?N: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:T,fog:this.stylesheet.fog,snow:this.stylesheet.snow,rain:this.stylesheet.rain,indoor:this.stylesheet.indoor,center:this.stylesheet.center,"color-theme":this.stylesheet["color-theme"],zoom:this.stylesheet.zoom,bearing:this.stylesheet.bearing,pitch:this.stylesheet.pitch,sprite:this.stylesheet.sprite,glyphs:this.stylesheet.glyphs,transition:this.stylesheet.transition,projection:this.stylesheet.projection,sources:this._serializeSources(),layers:this._serializeLayers(this._order)},z=>z!==void 0)}_updateFilteredLayers(N){for(const T of Object.values(this._mergedLayers))N(T)&&this._updateLayer(T)}_updateLayer(N){this._changes.updateLayer(N);const T=this.getLayerSourceCache(N),z=o.F(N.source,N.scope),W=this._changes.getUpdatedSourceCaches();N.source&&!W[z]&&T&&T.getSource().type!=="raster"&&(this._changes.updateSourceCache(z,"reload"),T.pause()),N.invalidateCompiledFilter()}_flattenAndSortRenderedFeatures(N){const T=ue=>this._mergedLayers[ue].is3D(!!this.terrain),z=this.order,W={},Q=[];for(let ue=z.length-1;ue>=0;ue--){const _e=z[ue];if(T(_e)){W[_e]=ue;for(const Ee of N){const Ie=Ee[_e];if(Ie)for(const Je of Ie)Q.push(Je)}}}Q.sort((ue,_e)=>_e.intersectionZ-ue.intersectionZ);const ee=[];for(let ue=z.length-1;ue>=0;ue--){const _e=z[ue];if(T(_e))for(let Ee=Q.length-1;Ee>=0;Ee--){const Ie=Q[Ee].feature;if(Ie.layer&&W[Ie.layer.id]{if(Vj.has(Ie.type))return;const Je=this.getOwnLayerSourceCache(Ie),Ke=Q[Je.id]=Q[Je.id]||{sourceCache:Je,layers:{},has3DLayers:!1};Ie.is3D(!!this.terrain)&&(Ke.has3DLayers=!0),Ke.layers[Ie.fqid]=Ke.layers[Ie.fqid]||{styleLayer:Ie,targets:[]},Ke.layers[Ie.fqid].targets.push({filter:W})};if(T&&T.layers){if(!Array.isArray(T.layers))return this.fire(new o.B(new Error("parameters.layers must be an Array."))),[];for(const Ie of T.layers){const Je=this._layers[Ie];if(!Je)return this.fire(new o.B(new Error(`The layer '${Ie}' does not exist in the map's style and cannot be queried for features.`))),[];ee(Je)}}else for(const Ie in this._layers)ee(this._layers[Ie]);const ue=this._queryRenderedFeatures(N,Q,z),_e=this._flattenAndSortRenderedFeatures(ue),Ee=[];for(const Ie of _e)o.dh(Ie.layer.id)===this.scope&&Ee.push(Ie);return Ee}queryRenderedFeatureset(N,T,z){let W;T&&!Array.isArray(T)&&T.filter&&(this._validate(Is,"queryRenderedFeatures.filter",T.filter,null,T),W=o.dg(T.filter));const Q="mock",ee=[];if(T&&T.target)ee.push(Object.assign({},T,{targetId:Q,filter:W}));else{const Ie=this.getFeaturesetDescriptors();for(const Je of Ie)ee.push({targetId:Q,filter:W,target:Je});for(const{style:Je}of this.fragments){const Ke=Je.getFeaturesetDescriptors();for(const tt of Ke)ee.push({targetId:Q,filter:W,target:tt})}}const ue=this.queryRenderedTargets(N,ee,z),_e=[],Ee=new Set;for(const Ie of ue)for(const Je of Ie.variants[Q])Uu(Je,Ie,Ee)||_e.push(new o.di(Ie,Je));return _e}queryRenderedTargets(N,T,z){const W={},Q=(ue,_e,Ee,Ie)=>{const Je=W[_e.id]=W[_e.id]||{sourceCache:_e,layers:{},has3DLayers:!1};if(Je.layers[ue.fqid]=Je.layers[ue.fqid]||{styleLayer:ue,targets:[]},ue.is3D(!!this.terrain)&&(Je.has3DLayers=!0),!Ie)return Ee.uniqueFeatureID=!1,void Je.layers[ue.fqid].targets.push(Ee);Je.layers[ue.fqid].targets.push(Object.assign({},Ee,{namespace:Ie.namespace,properties:Ie.properties,uniqueFeatureID:Ie.uniqueFeatureID}))};for(const ue of T)if("featuresetId"in ue.target){const{featuresetId:_e,importId:Ee}=ue.target,Ie=this.getFragmentStyle(Ee);if(!Ie||!Ie._featuresetSelectors)continue;const Je=Ie._featuresetSelectors[_e];if(!Je){this.fire(new o.B(new Error(`The featureset '${_e}' does not exist in the map's style and cannot be queried for features.`)));continue}for(const Ke of Je){const tt=Ie.getOwnLayer(Ke.layerId);tt&&!Vj.has(tt.type)&&Q(tt,Ie.getOwnLayerSourceCache(tt),ue,Ke)}}else if("layerId"in ue.target){const{layerId:_e}=ue.target,Ee=this.getLayer(_e);if(!Ee||Vj.has(Ee.type))continue;Q(Ee,this.getLayerSourceCache(Ee),ue)}const ee=this._queryRenderedFeatures(N,W,z);return this._flattenAndSortRenderedFeatures(ee)}_queryRenderedFeatures(N,T,z){const W=[],Q=!!this.map._showQueryGeometry,ee=Jo.createFromScreenPoints(N,z);for(const ue in T){const _e=Rx(ee,T[ue],this._availableImages,z,Q,this.getActualScope());Object.keys(_e).length&&W.push(_e)}if(this.placement)for(const ue in T){if(T[ue].sourceCache._renderSourceType!==o.b4.Symbol)continue;const _e=hl(ee.screenGeometry,T[ue],this._availableImages,this.placement.collisionIndex,this.placement.retainedQueryData,this.map.getWorldview());Object.keys(_e).length&&W.push(_e)}return W}querySourceFeatures(N,T){const z=T&&T.filter;z&&this._validate(Is,"querySourceFeatures.filter",z,null,T);let W=[];const Q=this.getOwnSourceCaches(N);for(const ee of Q)W=W.concat(Ua(ee,T));return W}addSourceType(N,T,z){return ph.getSourceType(N)?z(new Error(`A source type called "${N}" already exists.`)):(ph.setSourceType(N,T),T.workerSourceURL?void this.dispatcher.broadcast("loadWorkerSource",{name:N,url:T.workerSourceURL},z):z(null,null))}getFlatLight(){return this.light.getLight()}setFlatLight(N,T,z={}){this._checkLoaded();const W=this.light.getLight();let Q=!1;for(const ue in N)if(!o.b6(N[ue],W[ue])){Q=!0;break}if(!Q)return;const ee=this._getTransitionParameters();this.light.setLight(N,T,z),this.light.updateTransitions(ee)}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(N,T=1){if(this._checkLoaded(),!N)return this.terrainSetForDrapingOnly()||(delete this.terrain,this.map.transform.projection.requiresDraping&&this.setTerrainForDraping()),T===0&&delete this.terrain,N===null?this.stylesheet.terrain=null:delete this.stylesheet.terrain,this._force3DLayerUpdate(),void(this._markersNeedUpdate=!0);this.checkCanvasFingerprintNoise();let z=N;const W=!("source"in N)||N.source==null;if(T===1){if(this.disableElevatedTerrain)return;if("source"in z&&typeof z.source=="object"){const ue="terrain-dem-src";this.addSource(ue,z.source),z=o.d9(z),z=Object.assign(z,{source:ue})}const Q=Object.assign({},z),ee={};if(this.terrain&&W){Q.source=this.terrain.get().source;const ue=this.terrain?this.getFragmentStyle(this.terrain.scope):null;ue&&(ee.style=ue.serialize())}if(this._validate(pt,"terrain",Q,ee))return}if(!this.terrain||this.terrain.scope!==this.scope&&!W||this.terrain&&T!==this.terrain.drapeRenderMode){if(!z)return;this._createTerrain(z,T),this.fire(new o.C("data",{dataType:"style"}))}else{const Q=this.terrain,ee=Q.get();for(const ue of Object.keys(o.a8.terrain))!z.hasOwnProperty(ue)&&o.a8.terrain[ue].default&&(z[ue]=o.a8.terrain[ue].default);for(const ue in N)if(!o.b6(N[ue],ee[ue])){Q.set(N,this.options),this.stylesheet.terrain=N;const _e=this._getTransitionParameters({duration:0});Q.updateTransitions(_e),this.fire(new o.C("data",{dataType:"style"}));break}}this.mergeTerrain(),this.updateDrapeFirstLayers(),this._markersNeedUpdate=!0}_createFog(N){const T=this.fog=new eo(N,this.map.transform,this.scope,this.options);this.stylesheet.fog=T.get();const z=this._getTransitionParameters({duration:0});T.updateTransitions(z)}_createSnow(N){const T=this.snow=new Ro(N,this.map.transform,this.scope,this.options);this.stylesheet.snow=T.get();const z=this._getTransitionParameters({duration:0});T.updateTransitions(z)}_createRain(N){const T=this.rain=new di(N,this.map.transform,this.scope,this.options);this.stylesheet.rain=T.get();const z=this._getTransitionParameters({duration:0});T.updateTransitions(z)}_updateMarkersOpacity(){this.map._markers.length!==0&&this.map._requestDomTask(()=>{for(const N of this.map._markers)N._evaluateOpacity()})}getFog(){return this.fog?this.fog.get():null}setFog(N){if(this._checkLoaded(),!N)return delete this.fog,delete this.stylesheet.fog,void(this._markersNeedUpdate=!0);if(this.fog){const T=this.fog;if(!o.b6(T.get(),N)){T.set(N,this.options),this.stylesheet.fog=T.get();const z=this._getTransitionParameters({duration:0});T.updateTransitions(z)}}else this._createFog(N);this._markersNeedUpdate=!0}getSnow(){return this.snow?this.snow.get():null}setSnow(N){if(this._checkLoaded(),!N)return delete this.snow,void delete this.stylesheet.snow;if(this.snow){const T=this.snow;if(!o.b6(T.get(),N)){T.set(N,this.options),this.stylesheet.snow=T.get();const z=this._getTransitionParameters({duration:0});T.updateTransitions(z)}}else this._createSnow(N);this._markersNeedUpdate=!0}getRain(){return this.rain?this.rain.get():null}setRain(N){if(this._checkLoaded(),!N)return delete this.rain,void delete this.stylesheet.rain;if(this.rain){const T=this.rain;if(!o.b6(T.get(),N)){T.set(N,this.options),this.stylesheet.rain=T.get();const z=this._getTransitionParameters({duration:0});T.updateTransitions(z)}}else this._createRain(N);this._markersNeedUpdate=!0}_reloadColorTheme(){const N=()=>{for(const W in this._layers)this._layers[W].lut=this._styleColorTheme.lut;for(const W in this._sourceCaches)this._sourceCaches[W].clearTiles()},T=this._styleColorTheme.colorThemeOverride?this._styleColorTheme.colorThemeOverride:this._styleColorTheme.colorTheme;if(!T)return this._styleColorTheme.lut=null,void N();const z=this._evaluateColorThemeData(T);this._loadColorTheme(z).then(()=>{this.fire(new o.C("colorthemeset")),N()}).catch(W=>{o.w(`Couldn't set color theme: ${W}`)})}setColorTheme(N){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=N,this._reloadColorTheme()}setImportColorTheme(N,T){const z=this.getFragmentStyle(N);z&&(z._styleColorTheme.colorThemeOverride=T,z._reloadColorTheme())}_getTransitionParameters(N){return{now:o.o.now(),transition:Object.assign(this.transition,N)}}updateDrapeFirstLayers(){if(!this.terrain)return;const N=[],T=[];for(const z of this._mergedOrder)this.isLayerDraped(this._mergedLayers[z])?N.push(z):T.push(z);this._drapedFirstOrder=[],this._drapedFirstOrder.push(...N),this._drapedFirstOrder.push(...T)}_createTerrain(N,T){const z=this.terrain=new Rr(N,T,this.scope,this.options,this.map.getWorldview());T===1&&(this.stylesheet.terrain=N),this.mergeTerrain(),this.updateDrapeFirstLayers(),this._force3DLayerUpdate();const W=this._getTransitionParameters({duration:0});z.updateTransitions(W)}_force3DLayerUpdate(){for(const N in this._layers){const T=this._layers[N];T.type==="fill-extrusion"&&this._updateLayer(T)}}_forceSymbolLayerUpdate(){for(const N in this._layers){const T=this._layers[N];T.type==="symbol"&&this._updateLayer(T)}}_validate(N,T,z,W,Q={}){if(Q&&Q.validate===!1)return!1;const ee=Object.assign({},this.serialize());return Oy(this,N.call(Bn,Object.assign({key:T,style:ee,value:z,styleSpec:o.a8},W)))}_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 N in this._mergedLayers)this._mergedLayers[N].setEventedParent(null);for(const N in this._mergedSourceCaches)this._mergedSourceCaches[N].clearTiles(),this._mergedSourceCaches[N].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(N){const T=this.getSourceCaches(N);for(const z of T)z.clearTiles()}clearSources(){for(const N in this._mergedSourceCaches)this._mergedSourceCaches[N].clearTiles()}clearLayers(){for(const N in this._mergedLayers){const T=this._mergedLayers[N];T._clear&&T._clear()}}reloadSource(N){const T=this.getSourceCaches(N);for(const z of T)z.resume(),z.reload()}reloadSources(){for(const N of this.getSources())N.reload&&N.reload()}reloadModels(){this.modelManager.reloadModels(""),this.forEachFragmentStyle(N=>{N.modelManager.reloadModels(N.scope)})}updateSources(N){let T;this.directionalLight&&(T=Fy(this.directionalLight));const z=new Set,W=new Set,Q=new Set;for(const ee in this._mergedLayers){const ue=this._mergedLayers[ee];ue.type==="building"?z.add(ue.source):ue.type==="raster"&&ue.paint&&ue.paint.get("raster-elevation-reference")==="ground"&&Q.add(ue.source),ue.hasElevation()&&!W.has(ue.source)&&W.add(ue.source)}for(const ee in this._mergedSourceCaches){const ue=this._mergedSourceCaches[ee],_e=W.has(ue._source.id);ue._isRasterElevatedOverTerrain=Q.has(ue._source.id),z.has(ue._source.id)&&(ue._source.reparseOverscaled=!1),ue.update(N,void 0,void 0,T,_e)}}_generateCollisionBoxes(){for(const N in this._sourceCaches){const T=this._sourceCaches[N];T.resume(),T.reload()}}_handleLayerOrderChange(){this._requestFullLabelPlacement(),this.fire(new o.C("neworder"))}_requestFullLabelPlacement(){this.pauseablePlacement||(this.pauseablePlacement=new cp),this.pauseablePlacement.requestFullPlacement()}_setLabelPlacementStale(){this.placement&&this.placement.setStale()}_updatePlacement(N,T,z,W,Q){this.pauseablePlacement||(this.pauseablePlacement=new cp);let ee=!1,ue=!1;const _e={},Ee={};for(const lt of this._mergedOrder){const kt=this._mergedLayers[lt];if(kt.type!=="symbol")continue;const Nt=o.F(kt.source,kt.scope);let zt=_e[Nt];if(!zt){const Tt=this.getLayerSourceCache(kt);if(!Tt)continue;const Ss=Tt.getRenderableIds(!0).map(cs=>Tt.getTileByID(cs));Ee[Nt]=Ss.slice(),zt=_e[Nt]=Ss.sort((cs,Ns)=>Ns.tileID.overscaledZ-cs.tileID.overscaledZ||(cs.tileID.isLessThan(Ns.tileID)?-1:1))}const Yt=this.crossTileSymbolIndex.addLayer(kt,zt,N.center.lng,N.projection);ee=ee||Yt}this.crossTileSymbolIndex.pruneUnusedLayers(this._mergedOrder);const Ie=!!(this.placement&&!N.equals(this.placement.transform)),Je=!!(this.placement&&(this.placement.lastReplacementSourceUpdateTime!==0&&!Q||this.placement.lastReplacementSourceUpdateTime!==Q.updateTime)),Ke=Ie||Je||ee,tt=(Ke||this.pauseablePlacement.isStale())&&z===0,ut=this.pauseablePlacement.isDone()&&!this.placement.stillRecent(o.o.now(),N.zoom)&&z!==0;if((this.pauseablePlacement.isFullPlacementRequested()||!this.pauseablePlacement.placement||tt||ut)&&(this.pauseablePlacement=this.pauseablePlacement.startNewPlacement(N,this._mergedOrder,T,z,W,this.placement,this.fog&&N.projection.supportsFog?this.fog.state:null,this._buildingIndex),this.map.painter)){const lt=this.map.painter.maxFrontCutoffRawStart;if(lt>0){const kt=180*N.pitch/Math.PI;if(kt>=15){const Nt=Math.min(1,Math.max(0,(kt-15)/5)),zt=Nt*Nt*(3-2*Nt);this.pauseablePlacement.placement.frontCutoffStart=-.5*(1-zt)+lt*zt}}}if(this.pauseablePlacement.isDone()?Ke&&z!==0&&this.pauseablePlacement.setStale():(this.pauseablePlacement.continuePlacement(this._mergedOrder,this._mergedLayers,_e,Ee,this.map.painter.scaleFactor),this.pauseablePlacement.isDone()&&(this.placement=this.pauseablePlacement.commit(o.o.now()),ue=!0),ee&&this.pauseablePlacement.setStale()),ue||ee){this._buildingIndex.onNewFrame(N.zoom);for(let lt=0;ltQ===N.id)!==-1)return void this.fire(new o.B(new Error(`Import with id '${N.id}' already exists in the map's style.`)));if(!T)return z.push(N),this._loadImports([N],!0);const W=z.findIndex(({id:Q})=>Q===T);return W===-1&&this.fire(new o.B(new Error(`Import with id "${T}" does not exist on this map.`))),this.stylesheet.imports=z.slice(0,W).concat(N).concat(z.slice(W)),this._loadImports([N],!0,T)}updateImport(N,T){this._checkLoaded();const z=this.stylesheet.imports||[],W=this.getImportIndex(N);return W===-1?this:typeof T=="string"?(this.setImportUrl(N,T),this):(T.url&&T.url!==z[W].url&&this.setImportUrl(N,T.url),o.b6(T.config,z[W].config)||this.setImportConfig(N,T.config,T.data.schema),o.b6(T.data,z[W].data)||this.setImportData(N,T.data),this)}moveImport(N,T){this._checkLoaded();let z=this.stylesheet.imports||[];const W=this.getImportIndex(N);if(W===-1)return this;const Q=this.getImportIndex(T);if(Q===-1)return this;const ee=z[W],ue=this.fragments[W];return z=z.filter(({id:_e})=>_e!==N),this.fragments=this.fragments.filter(({id:_e})=>_e!==N),this.stylesheet.imports=z.slice(0,Q).concat(ee).concat(z.slice(Q)),this.fragments=this.fragments.slice(0,Q).concat(ue).concat(this.fragments.slice(Q)),this.mergeLayers(),this}setImportUrl(N,T){this._checkLoaded();const z=this.stylesheet.imports||[],W=this.getImportIndex(N);if(W===-1)return this;z[W].url=T;const Q=this.fragments[W];return Q.style=this._createFragmentStyle(z[W]),Q.style.on("style.import.load",()=>this.mergeAll()),Q.style.loadURL(T),this}setImportData(N,T){this._checkLoaded();const z=this.getImportIndex(N),W=this.stylesheet.imports||[];return z===-1?this:T?(this.fragments[z].style.setState(T),this._reloadImports(),this):(delete W[z].data,this.setImportUrl(N,W[z].url))}setImportConfig(N,T,z){this._checkLoaded();const W=this.getImportIndex(N),Q=this.stylesheet.imports||[];if(W===-1)return this;T?Q[W].config=T:delete Q[W].config;const ee=this.fragments[W];z&&ee.style.stylesheet&&(ee.style.stylesheet.schema=z);const ue=ee.style.stylesheet&&ee.style.stylesheet.schema;return ee.config=T,ee.style.updateConfig(T,ue),this.updateConfigDependencies(),this}removeImport(N){this._checkLoaded();const T=this.stylesheet.imports||[],z=this.getImportIndex(N);z!==-1&&(T.splice(z,1),this.fragments[z].style._remove(),this.fragments.splice(z,1),this._reloadImports())}getImportIndex(N){const T=(this.stylesheet.imports||[]).findIndex(z=>z.id===N);return T===-1&&this.fire(new o.B(new Error(`Import '${N}' does not exist in the map's style and cannot be updated.`))),T}getLayer(N){return this._mergedLayers[N]}getSources(){const N=[];for(const T in this._mergedOtherSourceCaches){const z=this._mergedOtherSourceCaches[T];z&&N.push(z.getSource())}return N}getSource(N,T){const z=this.getSourceCache(N,T);return z&&z.getSource()}getLayerSource(N){const T=this.getLayerSourceCache(N);return T&&T.getSource()}getSourceCache(N,T){const z=o.F(N,T);return this._mergedOtherSourceCaches[z]}getLayerSourceCache(N){const T=o.F(N.source,N.scope);return N.type==="symbol"?this._mergedSymbolSourceCaches[T]:N.type==="fill-extrusion"&&this._mergedFillExtrusionSourceCaches[T]||this._mergedOtherSourceCaches[T]}getSourceCaches(N){if(N==null)return Object.values(this._mergedSourceCaches);const T=[];return this._mergedOtherSourceCaches[N]&&T.push(this._mergedOtherSourceCaches[N]),this._mergedSymbolSourceCaches[N]&&T.push(this._mergedSymbolSourceCaches[N]),this._mergedFillExtrusionSourceCaches[N]&&T.push(this._mergedFillExtrusionSourceCaches[N]),T}updateSourceCaches(){const N=this._changes.getUpdatedSourceCaches();for(const T in N){const z=N[T];z==="reload"?this.reloadSource(T):z==="clear"&&this.clearSource(T)}}updateLayers(N){const T=this._changes.getUpdatedPaintProperties();for(const z of T){const W=this.getLayer(z);W&&W.updateTransitions(N)}}getGlyphsUrl(){return this.stylesheet.glyphs}setGlyphsUrl(N){this.stylesheet.glyphs=N,this.glyphManager.setURL(N)}getImages(N,T,z){this.imageManager.getImages(T.images,T.scope,z),this._updateTilesForChangedImages();const W=ee=>{if(ee){const ue=T.images.map(_e=>o.I.toString(_e));ee.setDependencies(T.tileID.key,T.type,ue)}},Q=o.F(T.source,T.scope);W(this._mergedOtherSourceCaches[Q]),W(this._mergedSymbolSourceCaches[Q]),T.images.some(ee=>ee.iconsetId)&&this.fire(new o.C("data",{dataType:"style"}))}rasterizeImages(N,T,z){this.imageManager.rasterizeImages(T,z)}checkAtlasCache(N,T,z){const W=this.imageManager.imageAtlasCache.findCachedAtlas(T.descriptor);z(null,W&&W.contentDescriptor?{iconPositions:W.iconPositions,patternPositions:W.patternPositions,sourceHash:W.contentDescriptor.hash}:null)}getGlyphs(N,T,z){this.glyphManager.getGlyphs(T.stacks,z)}getOwnSourceCache(N){return this._otherSourceCaches[N]}getOwnLayerSourceCache(N){return N.type==="symbol"?this._symbolSourceCaches[N.source]:N.type==="fill-extrusion"&&this._fillExtrusionSourceCaches[N.source]||this._otherSourceCaches[N.source]}getOwnSourceCaches(N){const T=[];return this._otherSourceCaches[N]&&T.push(this._otherSourceCaches[N]),this._symbolSourceCaches[N]&&T.push(this._symbolSourceCaches[N]),this._fillExtrusionSourceCaches[N]&&T.push(this._fillExtrusionSourceCaches[N]),T}_isSourceCacheLoaded(N){const T=this.getOwnSourceCaches(N);return T.length===0?(this.fire(new o.B(new Error(`There is no source with ID '${N}'`))),!1):T.every(z=>z.loaded())}has3DLayers(){return this._has3DLayers}hasSymbolLayers(){return this._hasSymbolLayers}hasCircleLayers(){return this._hasCircleLayers}isLayerClipped(N,T){if(!this._clipLayerPresent&&N.type!=="fill-extrusion"&&N.type!=="building")return!1;const z=N.type==="fill-extrusion"&&(N.sourceLayer==="building"||N.sourceLayer==="procedural_buildings"),W=N.type==="building";if(N.is3D(!!this.terrain)){if(z||W||T&&T.type==="batched-model"||N.type==="model")return!0}else if(N.type==="symbol")return!0;return!1}_clearWorkerCaches(){this.dispatcher.broadcast("clearCaches")}getBOMObject(){}destroy(){this._clearWorkerCaches(),this.imageManager.imageAtlasCache.clear(),this.fragments.forEach(N=>{N.style._remove()}),this.terrainSetForDrapingOnly()&&(delete this.terrain,delete this.stylesheet.terrain)}}ph.getSourceType=function(R){return Co[R]},ph.setSourceType=function(R,N){Co[R]=N},ph.registerForPluginStateChange=o.dk;var zy=` #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`,Hj=` #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;}`,By=` #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`,nw="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;}",WN=` #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`,KN=`#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`,Fb=`#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`,Ob=`#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`,YN=`#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;}`,rw=`#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`,hf=`#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 _m=/#include\s+"([^"]+)"/g,ur=/#pragma mapbox: ([\w\-]+) ([\w]+) ([\w]+) ([\w]+)/g,zb=/\b[A-Za-z_][A-Za-z0-9_]*\b/g,Bb=new Set(["ifdef","ifndef","elif","if","defined"]),M1=new Set;q0(zy,M1),q0(By,M1),q0(Hj,M1);const Jf={"_prelude_fog.vertex.glsl":KN,"_prelude_terrain.vertex.glsl":WN,"_prelude_shadow.vertex.glsl":rw,"_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":Fb,"_prelude_shadow.fragment.glsl":hf,"_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":Ob,"_prelude_raster_particle.glsl":YN},Fv={};To("",WN),To(Fb,KN),To(hf,rw),To(Ob,""),To(YN,"");const Uy=To(Hj,By),aw=zy,P1=[` #if defined(GL_EXT_blend_func_extended) && defined(DUAL_SOURCE_BLENDING) #extension GL_EXT_blend_func_extended : require #endif`,"precision mediump float;",aw,Uy.fragmentSource].join(` `),ZN=["precision highp float;",aw,Uy.vertexSource].join(` `);var Gj={background:To(`#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:To(`#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:To(`#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:To(`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:To("void main() {}","in vec3 a_pos_3f;uniform mat4 u_matrix;void main() {gl_Position=u_matrix*vec4(a_pos_3f,1.0);}"),circle:To(`#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:To("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:To(`#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:To(`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:To("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:To("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:To("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:To("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:To(`#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:To(`#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:To(`#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:To(`#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:To(`#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:To(`#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:To(`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:To(`#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:To("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:To(`#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:To(`#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:To(`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:To(`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:To(`#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:To(`#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:To(`#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:To(`#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:To(`#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:To("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:To("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:To(`#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:To(`#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:To(`#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:To("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:To(`#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 }`,nw),skyboxGradient:To(`#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 }`,nw),skyboxCapture:To(` 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:To(`#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:To(`#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:To(`#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:To("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:To(`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:To("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:To("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:To("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:To("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 q0(R,N){const T=R.split(` `);for(let z of T){if(z=z.trimStart(),z[0]!=="#"||!z.includes("if")||z.startsWith("#endif"))continue;const W=z.match(zb);if(W)for(const Q of W)Bb.has(Q)||N.add(Q)}}function BC(R){return new Set(["uint","int","uvec2","ivec2","uvec3","ivec3","uvec4","ivec4"]).has(R)}function To(R,N){const T=new Set,z=[],W=[];R=R.replace(_m,(ee,ue)=>(W.push(ue),"")),N=N.replace(_m,(ee,ue)=>(z.push(ue),""));let Q=new Set(M1);q0(R,Q),q0(N,Q);for(const ee of[...z,...W])Fv[ee]||(Fv[ee]=new Set,q0(Jf[ee],Fv[ee])),Q=new Set([...Q,...Fv[ee]]);return{fragmentSource:R=R.replace(ur,(ee,ue,_e,Ee,Ie)=>(T.add(Ie),ue==="define"?` #ifndef HAS_UNIFORM_u_${Ie} ${BC(Ee)?"flat ":""}in ${_e} ${Ee} ${Ie}; #else uniform ${_e} ${Ee} u_${Ie}; #endif `:ue==="initialize"?` #ifdef HAS_UNIFORM_u_${Ie} ${_e} ${Ee} ${Ie} = u_${Ie}; #endif `:ue==="define-attribute"?` #ifdef HAS_ATTRIBUTE_a_${Ie} in ${_e} ${Ee} ${Ie}; #endif `:ue==="initialize-attribute"?"":void 0)),vertexSource:N=N.replace(ur,(ee,ue,_e,Ee,Ie)=>{const Je=`MATERIAL_ATTRIBUTE_OFFSET_${Ie}`,Ke=Ee==="float"?"vec2":Ee,tt=`GET_ATTRIBUTE_${Ke}(a_${Ie}, materialInfo, ${Je})`,ut=Ie.match(/color/)?"color":Ke;return ue==="define-attribute-vertex-shader-only"?` #ifdef HAS_ATTRIBUTE_a_${Ie} in ${_e} ${Ee} a_${Ie}; #endif `:T.has(Ie)?ue==="define"?` #ifndef HAS_UNIFORM_u_${Ie} uniform lowp float u_${Ie}_t; #if !defined(${Je}) in ${_e} ${Ke} a_${Ie}; #endif ${BC(Ee)?"flat ":""}out ${_e} ${Ee} ${Ie}; #else uniform ${_e} ${Ee} u_${Ie}; #endif `:ue==="initialize"?ut==="vec4"||ut==="uvec4"?` #ifndef HAS_UNIFORM_u_${Ie} ${Ie} = a_${Ie}; #else ${_e} ${Ee} ${Ie} = u_${Ie}; #endif `:` #if !defined(HAS_UNIFORM_u_${Ie}) #ifdef ${Je} ${Ie} = unpack_mix_${ut}(${tt}, u_${Ie}_t); #else ${Ie} = unpack_mix_${ut}(a_${Ie}, u_${Ie}_t); #endif #else ${_e} ${Ee} ${Ie} = u_${Ie}; #endif `:ue==="define-attribute"?` #ifdef HAS_ATTRIBUTE_a_${Ie} in ${_e} ${Ee} a_${Ie}; out ${_e} ${Ee} ${Ie}; #endif `:ue==="initialize-attribute"?` #ifdef HAS_ATTRIBUTE_a_${Ie} ${Ie} = a_${Ie}; #endif `:void 0:ue==="define"?` #ifndef HAS_UNIFORM_u_${Ie} uniform lowp float u_${Ie}_t; #if !defined(${Je}) in ${_e} ${Ke} a_${Ie}; #endif #else uniform ${_e} ${Ee} u_${Ie}; #endif `:ue==="define-instanced"?ut==="mat4"?` #ifdef INSTANCED_ARRAYS in vec4 a_${Ie}0; in vec4 a_${Ie}1; in vec4 a_${Ie}2; in vec4 a_${Ie}3; #else uniform ${_e} ${Ee} u_${Ie}; #endif `:` #ifdef INSTANCED_ARRAYS in ${_e} ${Ke} a_${Ie}; #else uniform ${_e} ${Ee} u_${Ie}; #endif `:ue==="initialize-attribute-custom"?` #ifdef HAS_ATTRIBUTE_a_${Ie} ${_e} ${Ee} ${Ie} = a_${Ie}; #endif `:ut==="vec4"||ut==="uvec4"?` #ifndef HAS_UNIFORM_u_${Ie} #ifdef ${Je} ${_e} ${Ee} ${Ie} = ${tt}; #else ${_e} ${Ee} ${Ie} = a_${Ie}; #endif #else ${_e} ${Ee} ${Ie} = u_${Ie}; #endif `:` #ifndef HAS_UNIFORM_u_${Ie} #ifdef ${Je} ${_e} ${Ee} ${Ie} = unpack_mix_${ut}(${tt}, u_${Ie}_t); #else ${_e} ${Ee} ${Ie} = unpack_mix_${ut}(a_${Ie}, u_${Ie}_t); #endif #else ${_e} ${Ee} ${Ie} = u_${Ie}; #endif `}),usedDefines:Q,vertexIncludes:z,fragmentIncludes:W}}class KS{constructor(){this.boundProgram=null,this.boundLayoutVertexBuffer=null,this.boundPaintVertexBuffers=[],this.boundIndexBuffer=null,this.boundVertexOffset=null,this.boundDynamicVertexBuffers=[],this.vao=null}bind(N,T,z,W,Q,ee,ue,_e){this.context=N;let Ee=this.boundPaintVertexBuffers.length!==W.length;for(let Je=0;!Ee&&Je{const Ss=Yt.paint.get("hillshade-shadow-color"),cs=Yt.paint.get("hillshade-shadow-color-use-theme").constantOr("default")==="none",Ns=Yt.paint.get("hillshade-highlight-color"),Zt=Yt.paint.get("hillshade-highlight-color-use-theme").constantOr("default")==="none",ns=Yt.paint.get("hillshade-accent-color"),bs=Yt.paint.get("hillshade-accent-color-use-theme").constantOr("default")==="none",Ks=Yt.paint.get("hillshade-emissive-strength");let Es=o.ap(Yt.paint.get("hillshade-illumination-direction"));if(Yt.paint.get("hillshade-illumination-anchor")==="viewport")Es-=Nt.transform.angle;else if(Nt.style&&Nt.style.enable3dLights()&&Nt.style.directionalLight){const mn=Nt.style.directionalLight.properties.get("direction"),zn=o.cP(mn.x,mn.y,mn.z);Es=o.ap(zn[1])}const bn=!Nt.options.moving;return{u_matrix:Tt||Nt.transform.calculateProjMatrix(zt.tileID.toUnwrapped(),bn),u_image:0,u_latrange:UC(0,zt.tileID),u_light:[Yt.paint.get("hillshade-exaggeration"),Es],u_shadow:Ss.toPremultipliedRenderColor(cs?null:Yt.lut),u_highlight:Ns.toPremultipliedRenderColor(Zt?null:Yt.lut),u_emissive_strength:Ks,u_accent:ns.toPremultipliedRenderColor(bs?null:Yt.lut)}})(R,T,z,R.terrain?N.projMatrix:null);R.uploadCommonUniforms(ue,Ke,N.toUnwrapped());const{tileBoundsBuffer:ut,tileBoundsIndexBuffer:lt,tileBoundsSegments:kt}=R.getTileBoundsBuffers(T);Ke.draw(R,_e.TRIANGLES,W,Q,ee,va.disabled,tt,z.id,ut,lt,kt)}function qC(R,N,T){if(!N.needsDEMTextureUpload)return;const z=R.context,W=z.gl;z.pixelStoreUnpackPremultiplyAlpha.set(!1),N.demTexture=N.demTexture||R.getTileTexture(T.stride);const Q=T.getPixels();N.demTexture?N.demTexture.update(Q,{premultiply:!1}):N.demTexture=new o.T(z,Q,W.R32F,{premultiply:!1}),N.needsDEMTextureUpload=!1}function YE(R,N,T){const z=R.context,W=z.gl;if(!N.dem)return;const Q=N.dem;if(z.activeTexture.set(W.TEXTURE1),qC(R,N,Q),!N.demTexture)return;N.demTexture.bind(W.NEAREST,W.CLAMP_TO_EDGE);const ee=Q.dim;z.activeTexture.set(W.TEXTURE0);let ue=N.hillshadeFBO;if(!ue){const Ke=new o.T(z,{width:ee,height:ee,data:null},W.RGBA8);Ke.bind(W.LINEAR,W.CLAMP_TO_EDGE),ue=N.hillshadeFBO=z.createFramebuffer(ee,ee,1,"renderbuffer"),ue.colorAttachment0.set(Ke.texture)}z.bindFramebuffer.set(ue.framebuffer),z.viewport.set([0,0,ee,ee]);const{tileBoundsBuffer:_e,tileBoundsIndexBuffer:Ee,tileBoundsSegments:Ie}=R.getMercatorTileBoundsBuffers(),Je=[];R.linearFloatFilteringSupported()&&Je.push("TERRAIN_DEM_FLOAT_FORMAT"),R.terrain&&R.terrain.renderingToTexture&&R.emissiveMode==="mrt-fallback"&&Je.push("USE_MRT1"),R.getOrCreateProgram("hillshadePrepare",{defines:Je}).draw(R,W.TRIANGLES,Hr.disabled,qa.disabled,Ba.unblended,va.disabled,((Ke,tt)=>{const ut=tt.stride,lt=o.bb();return o.bT(lt,0,o.an,-o.an,0,0,1),o.bx(lt,lt,[0,-o.an,0]),{u_matrix:lt,u_image:1,u_dimension:[ut,ut],u_zoom:Ke.overscaledZ}})(N.tileID,Q),T.id,_e,Ee,Ie),N.needsHillshadePrepare=!1}class hd{constructor(N){this.gl=N.gl,this.default=this.getDefault(),this.current=this.default,this.dirty=!1}get(){return this.current}set(N){}getDefault(){return this.default}setDefault(){this.set(this.default)}}class iw extends hd{getDefault(){return o.aq.transparent.toNonPremultipliedRenderColor(null)}set(N){const T=this.current;(N.r!==T.r||N.g!==T.g||N.b!==T.b||N.a!==T.a||this.dirty)&&(this.gl.clearColor(N.r,N.g,N.b,N.a),this.current=N,this.dirty=!1)}}class $C extends hd{getDefault(){return 1}set(N){(N!==this.current||this.dirty)&&(this.gl.clearDepth(N),this.current=N,this.dirty=!1)}}class Ub extends hd{getDefault(){return 0}set(N){(N!==this.current||this.dirty)&&(this.gl.clearStencil(N),this.current=N,this.dirty=!1)}}class UL extends hd{getDefault(){return[!0,!0,!0,!0]}set(N){const T=this.current;(N[0]!==T[0]||N[1]!==T[1]||N[2]!==T[2]||N[3]!==T[3]||this.dirty)&&(this.gl.colorMask(N[0],N[1],N[2],N[3]),this.current=N,this.dirty=!1)}}class $0 extends hd{getDefault(){return!0}set(N){(N!==this.current||this.dirty)&&(this.gl.depthMask(N),this.current=N,this.dirty=!1)}}class Wj extends hd{getDefault(){return 255}set(N){(N!==this.current||this.dirty)&&(this.gl.stencilMask(N),this.current=N,this.dirty=!1)}}class ow extends hd{getDefault(){return{func:this.gl.ALWAYS,ref:0,mask:255}}set(N){const T=this.current;(N.func!==T.func||N.ref!==T.ref||N.mask!==T.mask||this.dirty)&&(this.gl.stencilFunc(N.func,N.ref,N.mask),this.current=N,this.dirty=!1)}}class YS extends hd{getDefault(){const N=this.gl;return[N.KEEP,N.KEEP,N.KEEP]}set(N){const T=this.current;(N[0]!==T[0]||N[1]!==T[1]||N[2]!==T[2]||this.dirty)&&(this.gl.stencilOp(N[0],N[1],N[2]),this.current=N,this.dirty=!1)}}class qb extends hd{getDefault(){return!1}set(N){if(N===this.current&&!this.dirty)return;const T=this.gl;N?T.enable(T.STENCIL_TEST):T.disable(T.STENCIL_TEST),this.current=N,this.dirty=!1}}class $b extends hd{getDefault(){return[0,1]}set(N){const T=this.current;(N[0]!==T[0]||N[1]!==T[1]||this.dirty)&&(this.gl.depthRange(N[0],N[1]),this.current=N,this.dirty=!1)}}class Bx extends hd{getDefault(){return!1}set(N){if(N===this.current&&!this.dirty)return;const T=this.gl;N?T.enable(T.DEPTH_TEST):T.disable(T.DEPTH_TEST),this.current=N,this.dirty=!1}}class Zu extends hd{getDefault(){return this.gl.LESS}set(N){(N!==this.current||this.dirty)&&(this.gl.depthFunc(N),this.current=N,this.dirty=!1)}}class V0 extends hd{getDefault(){return!1}set(N){if(N===this.current&&!this.dirty)return;const T=this.gl;N?T.enable(T.BLEND):T.disable(T.BLEND),this.current=N,this.dirty=!1}}class XN extends hd{getDefault(){const N=this.gl;return[N.ONE,N.ZERO,N.ONE,N.ZERO]}set(N){const T=this.current;(N[0]!==T[0]||N[1]!==T[1]||N[2]!==T[2]||N[3]!==T[3]||this.dirty)&&(this.gl.blendFuncSeparate(N[0],N[1],N[2],N[3]),this.current=N,this.dirty=!1)}}class VC extends hd{getDefault(){return o.aq.transparent.toNonPremultipliedRenderColor(null)}set(N){const T=this.current;(N.r!==T.r||N.g!==T.g||N.b!==T.b||N.a!==T.a||this.dirty)&&(this.gl.blendColor(N.r,N.g,N.b,N.a),this.current=N,this.dirty=!1)}}class yg extends hd{getDefault(){return this.gl.FUNC_ADD}set(N){(N!==this.current||this.dirty)&&(this.gl.blendEquationSeparate(N,N),this.current=N,this.dirty=!1)}}class ex extends hd{getDefault(){return!1}set(N){if(N===this.current&&!this.dirty)return;const T=this.gl;N?T.enable(T.CULL_FACE):T.disable(T.CULL_FACE),this.current=N,this.dirty=!1}}class QN extends hd{getDefault(){return this.gl.BACK}set(N){(N!==this.current||this.dirty)&&(this.gl.cullFace(N),this.current=N,this.dirty=!1)}}class ZS extends hd{getDefault(){return this.gl.CCW}set(N){(N!==this.current||this.dirty)&&(this.gl.frontFace(N),this.current=N,this.dirty=!1)}}let Kj=class extends hd{getDefault(){return null}set(R){(R!==this.current||this.dirty)&&(this.gl.useProgram(R),this.current=R,this.dirty=!1)}};class Yj extends hd{getDefault(){return this.gl.TEXTURE0}set(N){(N!==this.current||this.dirty)&&(this.gl.activeTexture(N),this.current=N,this.dirty=!1)}}class tx extends hd{getDefault(){const N=this.gl;return[0,0,N.drawingBufferWidth,N.drawingBufferHeight]}set(N){const T=this.current;(N[0]!==T[0]||N[1]!==T[1]||N[2]!==T[2]||N[3]!==T[3]||this.dirty)&&(this.gl.viewport(N[0],N[1],N[2],N[3]),this.current=N,this.dirty=!1)}}class mf extends hd{getDefault(){return null}set(N){if(N===this.current&&!this.dirty)return;const T=this.gl;T.bindFramebuffer(T.FRAMEBUFFER,N),this.current=N,this.dirty=!1}}class HC extends hd{getDefault(){return null}set(N){if(N===this.current&&!this.dirty)return;const T=this.gl;T.bindRenderbuffer(T.RENDERBUFFER,N),this.current=N,this.dirty=!1}}class Ov extends hd{getDefault(){return null}set(N){if(N===this.current&&!this.dirty)return;const T=this.gl;T.bindTexture(T.TEXTURE_2D,N),this.current=N,this.dirty=!1}}class Zj extends hd{getDefault(){return null}set(N){if(N===this.current&&!this.dirty)return;const T=this.gl;T.bindBuffer(T.ARRAY_BUFFER,N),this.current=N,this.dirty=!1}}class Xj extends hd{getDefault(){return null}set(N){const T=this.gl;T.bindBuffer(T.ELEMENT_ARRAY_BUFFER,N),this.current=N,this.dirty=!1}}class XS extends hd{getDefault(){return null}set(N){this.gl&&(N!==this.current||this.dirty)&&(this.gl.bindVertexArray(N),this.current=N,this.dirty=!1)}}class QS extends hd{getDefault(){return 4}set(N){if(N===this.current&&!this.dirty)return;const T=this.gl;T.pixelStorei(T.UNPACK_ALIGNMENT,N),this.current=N,this.dirty=!1}}class JS extends hd{getDefault(){return!1}set(N){if(N===this.current&&!this.dirty)return;const T=this.gl;T.pixelStorei(T.UNPACK_PREMULTIPLY_ALPHA_WEBGL,N),this.current=N,this.dirty=!1}}class Qj extends hd{getDefault(){return!1}set(N){if(N===this.current&&!this.dirty)return;const T=this.gl;T.pixelStorei(T.UNPACK_FLIP_Y_WEBGL,N),this.current=N,this.dirty=!1}}class Jj extends hd{constructor(N,T){super(N),this.context=N,this.parent=T}getDefault(){return null}}class lw extends Jj{constructor(N,T,z=0){super(N,T),this.attachmentPoint=N.gl.COLOR_ATTACHMENT0+z}setDirty(){this.dirty=!0}set(N){if(N===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const T=this.gl;T.framebufferTexture2D(T.FRAMEBUFFER,this.attachmentPoint,T.TEXTURE_2D,N,0),this.current=N,this.dirty=!1}}class JN extends Jj{attachment(){return this.gl.DEPTH_ATTACHMENT}set(N){if(N===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const T=this.gl;T.framebufferRenderbuffer(T.FRAMEBUFFER,this.attachment(),T.RENDERBUFFER,N),this.current=N,this.dirty=!1}}class e5 extends Jj{attachment(){return this.gl.DEPTH_ATTACHMENT}set(N){if(N===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const T=this.gl;T.framebufferTexture2D(T.FRAMEBUFFER,this.attachment(),T.TEXTURE_2D,N,0),this.current=N,this.dirty=!1}}class ZE extends JN{attachment(){return this.gl.DEPTH_STENCIL_ATTACHMENT}}const cw=(R,N,T,z)=>({u_matrix:R,u_image0:0,u_image1:1,u_skirt_height:N,u_ground_shadow_factor:T,u_emissive_texture_available:z}),zv=(R,N,T,z,W,Q,ee,ue,_e,Ee,Ie,Je,Ke,tt,ut,lt,kt)=>({u_proj_matrix:Float32Array.from(R),u_globe_matrix:N,u_normalize_matrix:Float32Array.from(z),u_merc_matrix:T,u_zoom_transition:W,u_merc_center:Q,u_image0:0,u_image1:1,u_frustum_tl:ee,u_frustum_tr:ue,u_frustum_br:_e,u_frustum_bl:Ee,u_globe_pos:Ie,u_globe_radius:Je,u_viewport:Ke,u_grid_matrix:kt?Float32Array.from(kt):new Float32Array(9),u_skirt_height:tt,u_far_z_cutoff:ut,u_emissive_texture_available:lt});function e2(R,N){return R!=null&&N!=null&&!(!R.hasData()||!N.hasData())&&R.demTexture!=null&&N.demTexture!=null&&R.tileID.key!==N.tileID.key}const dp=new class{constructor(){this.operations={}}newMorphing(R,N,T,z,W){if(R in this.operations){const Q=this.operations[R];Q.to.tileID.key!==T.tileID.key&&(Q.queued=T)}else this.operations[R]={startTime:z,phase:0,duration:W,from:N,to:T,queued:null}}getMorphValuesForProxy(R){if(!(R in this.operations))return null;const N=this.operations[R];return{from:N.from,to:N.to,phase:N.phase}}update(R){for(const N in this.operations){const T=this.operations[N];for(T.phase=(R-T.startTime)/T.duration;T.phase>=1||!this._validOp(T);)if(!this._nextOp(T,R)){delete this.operations[N];break}}}_nextOp(R,N){return!!R.queued&&(R.from=R.to,R.to=R.queued,R.queued=null,R.phase=0,R.startTime=N,!0)}_validOp(R){return R.from.hasData()&&R.to.hasData()}},t2={0:null,1:"TERRAIN_VERTEX_MORPHING"};function dw(R,N,T){if(N===0)return 0;const z=N<1&&T===514?.25/N:1;return 6*Math.pow(1.5,22-R)*Math.max(N,1)*z}function Te(R,N){const T=1<({u_matrix:R});function _t(R,N,T,z,W){if(W>0){const Q=o.o.now(),ee=(Q-R.timeAdded)/W,ue=N?(Q-N.timeAdded)/W:-1,_e=T.getSource(),Ee=z.coveringZoomLevel({tileSize:_e.tileSize,roundZoom:_e.roundZoom}),Ie=!N||Math.abs(N.tileID.overscaledZ-Ee)>Math.abs(R.tileID.overscaledZ-Ee),Je=Ie&&R.refreshedUponExpiration?1:o.aC(Ie?ee:1-ue,0,1);return N?{opacity:1,mix:1-Je,isFading:ee<1}:{opacity:Je,mix:0,isFading:ee<1}}return{opacity:1,mix:0,isFading:!1}}class ss extends Dc{constructor(N){const T={type:"raster-dem",maxzoom:Math.ceil(N.transform.maxZoom)},z=bi("mock-dem",T,N.style.dispatcher,N.style);super("mock-dem",z,null),z.setEventedParent(this),this._sourceLoaded=!0}_loadTile(N,T){N.state="loaded",T(null)}}class ms extends Dc{constructor(N){const T=bi("proxy",{type:"geojson",maxzoom:Math.ceil(N.transform.maxZoom)},N.style.dispatcher,N.style);super("proxy",T,null),T.setEventedParent(this),this.map=this.getSource().map=N,this.used=this._sourceLoaded=!0,this.renderCache=[],this.renderCachePool=[],this.proxyCachedFBO={}}update(N,T,z){if(N.freezeTileCoverage)return;this.transform=N;const W=N.coveringTiles({tileSize:this._source.tileSize,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:this._source.roundZoom,reparseOverscaled:this._source.reparseOverscaled}).reduce((Q,ee)=>{if(Q[ee.key]="",!this._tiles[ee.key]){const ue=new o.b0(ee,this._source.tileSize*ee.overscaleFactor(),N.tileZoom,void 0,void 0,this._source.worldview);ue.state="loaded",this._tiles[ee.key]=ue}return Q},{});for(const Q in this._tiles)Q in W||(this.freeFBO(Q),this._tiles[Q].unloadVectorData(),delete this._tiles[Q])}freeFBO(N){const T=this.proxyCachedFBO[N];if(T!==void 0){const z=Object.values(T);this.renderCachePool.push(...z),delete this.proxyCachedFBO[N]}}deallocRenderCache(){this.renderCache.forEach(N=>N.fb.destroy()),this.renderCache=[],this.renderCachePool=[],this.proxyCachedFBO={}}}class vs extends o.aR{constructor(N,T,z){super(N.overscaledZ,N.wrap,N.canonical.z,N.canonical.x,N.canonical.y),this.proxyTileKey=T,this.projMatrix=z}}class Cs extends o.bu{constructor(N,T){super(),this._debugParams={sortTilesHiZFirst:!0,disableRenderCache:!1},this.painter=N,this.terrainTileForTile={},this.prevTerrainTileForTile={};const[z,W,Q]=function(){const _e=new o.dB,Ee=new o.dC,Ie=131;_e.reserve(17161),Ee.reserve(33800);const Je=o.an/128,Ke=o.an+Je/2,tt=Ke+Je;for(let lt=-Je;ltKe||lt<0||lt>Ke?24575:0,zt=o.aC(Math.round(kt),0,o.an),Yt=o.aC(Math.round(lt),0,o.an);_e.emplaceBack(zt+Nt,Yt)}const ut=(lt,kt)=>{const Nt=kt*Ie+lt;Ee.emplaceBack(Nt+1,Nt,Nt+Ie),Ee.emplaceBack(Nt+Ie,Nt+Ie+1,Nt+1)};for(let lt=1;lt<129;lt++)for(let kt=1;kt<129;kt++)ut(kt,lt);return[0,129].forEach(lt=>{for(let kt=0;kt<130;kt++)ut(kt,lt),ut(lt,kt)}),[_e,Ee,32768]}(),ee=N.context;this.gridBuffer=ee.createVertexBuffer(z,o.dx.members),this.gridIndexBuffer=ee.createIndexBuffer(W),this.gridSegments=o.dy.simpleSegment(0,0,z.length,W.length),this.gridNoSkirtSegments=o.dy.simpleSegment(0,0,z.length,Q),this.proxyCoords=[],this.proxiedCoords={},this._visibleDemTiles=[],this._drapedRenderBatches=[],this._sourceTilesOverlap={},this.proxySourceCache=new ms(T.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 ue=ee.gl;this._overlapStencilMode=new qa({func:ue.GEQUAL,mask:255},0,255,ue.KEEP,ue.KEEP,ue.REPLACE),this._previousZoom=N.transform.zoom,this.pool=[],this._findCoveringTileCache={},this._tilesDirty={},this.style=T,this._useVertexMorphing=!0,this._exaggeration=1,this._mockSourceCache=new ss(T.map),this._pendingGroundEffectLayers=[],this._emissiveTexture=!1}set style(N){N.on("data",this._onStyleDataEvent.bind(this)),this._style=N,this._style.map.on("moveend",()=>{this._clearLineLayersFromRenderCache()})}update(N,T,z){if(N&&N.terrain){this._style!==N&&(this.style=N,this._evaluationZoom=void 0);const W=N.terrain.properties,Q=N.terrain.drapeRenderMode===0,ee=N.terrain.isZoomDependent();this._previousUpdateTimestamp=this.enabled?this._updateTimestamp:void 0,this._updateTimestamp=o.o.now();const ue=N.terrain&&N.terrain.scope,_e=W.get("source"),Ee=Q?this._mockSourceCache:N.getSourceCache(_e,ue);if(!Ee)return void o.w(`Couldn't find terrain source "${_e}".`);if(this.sourceCache=Ee,this._attenuationRange=N.terrain.getAttenuationRange(),this._exaggeration=ee?this.calculateExaggeration(T):W.get("exaggeration"),!T.projection.requiresDraping&&ee&&this._exaggeration===0)return void this._disable();this.enabled=!0;const Ie=()=>{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 Je=this.getScaledDemTileSize();this.sourceCache.update(T,Je,!0),this.resetTileLookupCache(this.sourceCache.id)};this.sourceCache.usedForTerrain||(this.resetTileLookupCache(this.sourceCache.id),this.sourceCache.usedForTerrain=!0,Ie(),this._initializing=!0),Ie(),T.updateElevation(!0,z),this.resetTileLookupCache(this.proxySourceCache.id),this.proxySourceCache.update(T),this._emptyDEMTextureDirty=!0,this._previousZoom=T.zoom}else this._disable()}calculateExaggeration(N){if(this._attenuationRange&&N.zoom>=Math.ceil(this._attenuationRange[1]))return this._style.terrain.getExaggeration(N.zoom);const T=this._previousCameraAltitude,z=N.getFreeCameraOptions().position.z/N.pixelsPerMeter*N.worldSize;this._previousCameraAltitude=z;const W=T!=null?z-T:Number.MAX_VALUE;if(Math.abs(W)<2)return this._exaggeration;const Q=N.zoom,ee=this._style.terrain;if(!this._previousUpdateTimestamp)return ee.getExaggeration(Q);let ue=Q-this._previousZoom;const _e=this._previousUpdateTimestamp;let Ee=Q;this._evaluationZoom!=null&&(Ee=this._evaluationZoom,Math.abs(Q-Ee)>.5&&(ue=.5*(Q-Ee+ue)),ue*W<0&&(Ee+=ue)),this._evaluationZoom=Ee;const Ie=ee.getExaggeration(Ee),Je=Ie===ee.getExaggeration(Math.max(0,Ee-.1));if(Je&&Math.abs(Ie-this._exaggeration)<.01)return Ie;let Ke=Math.min(.1,.00375*(this._updateTimestamp-_e));return(Je||Ie<.1||Math.abs(ue)<1e-4)&&(Ke=Math.min(.2,4*Ke)),o.am(this._exaggeration,Ie,Ke)}resetTileLookupCache(N){this._findCoveringTileCache[N]={}}attenuationRange(){return this._attenuationRange}getDemUpscale(){return this.proxySourceCache.getSource().tileSize/128}getScaledDemTileSize(){return this.sourceCache.getSource().tileSize/128*this.proxySourceCache.getSource().tileSize}_onStyleDataEvent(N){N.dataType==="source"&&N.coord?this._clearRenderCacheForTile(N.sourceCacheId,N.coord):N.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 N in this._style._mergedSourceCaches)this._style._mergedSourceCaches[N].usedForTerrain=!1}destroy(){this._disable(),this._emptyDEMTexture&&this._emptyDEMTexture.destroy(),this.pool.forEach(N=>N.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 N=2*this.proxySourceCache.getSource().tileSize;return[N,N]}set useVertexMorphing(N){this._useVertexMorphing=N}updateTileBinding(N){if(!this.enabled)return;this.prevTerrainTileForTile=this.terrainTileForTile;const T=this.proxySourceCache,z=this.painter.transform;this._initializing&&(this._initializing=z._centerAltitude===0&&this.getAtPointOrZero(o.ag.fromLngLat(z.center),-1)===-1,this._emptyDEMTextureDirty=!this._initializing);const W=this.proxyCoords=T.getIds().map(_e=>{const Ee=T.getTileByID(_e).tileID;return Ee.projMatrix=z.calculateProjMatrix(Ee.toUnwrapped()),Ee});(function(_e,Ee){const Ie=Ee.transform.pointCoordinate(Ee.transform.getCameraPoint()),Je=new o.P(Ie.x,Ie.y);_e.sort((Ke,tt)=>{if(tt.overscaledZ-Ke.overscaledZ)return tt.overscaledZ-Ke.overscaledZ;const ut=new o.P(Ke.canonical.x+(1<{this.proxyToSource[_e.key]={}}),this.terrainTileForTile={};const ee=this._style._mergedSourceCaches;for(const _e in ee){const Ee=ee[_e];if(!Ee.used||(Ee!==this.sourceCache&&this.resetTileLookupCache(Ee.id),this._setupProxiedCoordsForOrtho(Ee,N[_e],Q),Ee.usedForTerrain))continue;const Ie=N[_e];(Ee.getSource().reparseOverscaled||Ee._isRasterElevatedOverTerrain)&&this._assignTerrainTiles(Ie)}this.proxiedCoords[T.id]=W.map(_e=>new vs(_e,_e.key,this.orthoMatrix)),this._assignTerrainTiles(W),this._prepareDEMTextures(),this._setupDrapedRenderBatches(),this._initFBOPool(),this._setupRenderCache(Q),this.renderingToTexture=!1;const ue={};this._visibleDemTiles=[];for(const _e of this.proxyCoords){const Ee=this.terrainTileForTile[_e.key];if(!Ee)continue;const Ie=Ee.tileID.key;Ie in ue||(this._visibleDemTiles.push(Ee),ue[Ie]=Ie)}}_assignTerrainTiles(N){this._initializing||N.forEach(T=>{if(this.terrainTileForTile[T.key])return;const z=this._findTileCoveringTileID(T,this.sourceCache);z&&(this.terrainTileForTile[T.key]=z)})}_prepareDEMTextures(){const N=this.painter.context,T=N.gl;for(const z in this.terrainTileForTile){const W=this.terrainTileForTile[z],Q=W.dem;!Q||W.demTexture&&!W.needsDEMTextureUpload||(N.activeTexture.set(T.TEXTURE1),qC(this.painter,W,Q))}}_prepareDemTileUniforms(N,T,z,W){if(!T||T.demTexture==null)return!1;const Q=N.tileID.canonical,ee=Math.pow(2,T.tileID.canonical.z-Q.z),ue=W||"";return z[`u_dem_tl${ue}`]=[Q.x*ee%1,Q.y*ee%1],z[`u_dem_scale${ue}`]=ee,!0}get emptyDEMTexture(){return!this._emptyDEMTextureDirty&&this._emptyDEMTexture?this._emptyDEMTexture:this._updateEmptyDEMTexture()}_getLoadedAreaMinimum(){if(!this.enabled)return 0;let N=0;const T=this._visibleDemTiles.reduce((z,W)=>{if(!W.dem)return z;const Q=W.dem.tree.minimums[0];return Q>0&&N++,z+Q},0);return N?T/N:0}_updateEmptyDEMTexture(){const N=this.painter.context,T=N.gl;N.activeTexture.set(T.TEXTURE2);const z=this._getLoadedAreaMinimum(),W=new o.dz({width:1,height:1},new Float32Array([z]));this._emptyDEMTextureDirty=!1;let Q=this._emptyDEMTexture;return Q?Q.update(W,{premultiply:!1}):Q=this._emptyDEMTexture=new o.T(N,W,T.R32F,{premultiply:!1}),Q}setupElevationDraw(N,T,z){const W=this.painter.context,Q=W.gl,ee={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};ee.u_exaggeration=this.exaggeration();let ue=null,_e=null,Ee=1;if(z&&z.morphing&&this._useVertexMorphing){const tt=z.morphing.srcDemTile,ut=z.morphing.dstDemTile;Ee=z.morphing.phase,tt&&ut&&(this._prepareDemTileUniforms(N,tt,ee,"_prev")&&(_e=tt),this._prepareDemTileUniforms(N,ut,ee)&&(ue=ut))}const Ie=tt=>tt&&tt.demTexture&&this.painter.linearFloatFilteringSupported()?Q.LINEAR:Q.NEAREST;let Je=null;var Ke;if(this.enabled?_e&&ue?(Je=ue.demTexture,W.activeTexture.set(Q.TEXTURE4),_e.demTexture.bind(Ie(_e),Q.CLAMP_TO_EDGE),ee.u_dem_lerp=Ee):(ue=this.terrainTileForTile[N.tileID.key],Je=this._prepareDemTileUniforms(N,ue,ee)?ue.demTexture:this.emptyDEMTexture):Je=this.emptyDEMTexture,W.activeTexture.set(Q.TEXTURE2),Je&&(ee.u_dem_size=(Ke=Je).size[0]===1?1:Ke.size[0]-2,Je.bind(Ie(ue),Q.CLAMP_TO_EDGE)),this.painter.setupDepthForOcclusion(z&&z.useDepthForOcclusion,T,ee),z&&z.useMeterToDem&&ue){const tt=(1<{if(Nt===mn)return;const zn=[t2[mn],"PROJECTION_GLOBE_VIEW"];Yt&&zn.push("CUSTOM_ANTIALIASING");const Kn=Ee.isTileAffectedByFog(bn);kt=Ee.getOrCreateProgram("globeRaster",{defines:zn,overrideFog:Kn}),Nt=mn},Ss=Ee.colorModeForRenderPass(),cs=new Hr(lt.LEQUAL,Hr.ReadWrite,Ee.depthRangeFor3D);dp.update(tt);const Ns=o.dq(zt),Zt=[o.aH(zt.center.lng),o.aL(zt.center.lat)],ns=Ee.globeSharedBuffers,bs=[zt.width*o.o.devicePixelRatio,zt.height*o.o.devicePixelRatio],Ks=Float32Array.from(zt.globeMatrix),Es={useDenormalizedUpVectorScale:!0};{const bn=Ee.transform,mn=dw(bn.zoom,Ie.exaggeration(),Ie.sourceCache._source.tileSize);Nt=-1;const zn=lt.TRIANGLES;for(const Kn of Ke){const sn=Je.getTile(Kn),Fs=qa.disabled,yn=Ie.prevTerrainTileForTile[Kn.key],_n=Ie.terrainTileForTile[Kn.key];e2(yn,_n)&&dp.newMorphing(Kn.key,yn,_n,tt,250),Be(Ee,sn.emissiveTexture),ut.activeTexture.set(lt.TEXTURE0),sn.texture&&sn.texture.bind(lt.LINEAR,lt.CLAMP_TO_EDGE);const Tn=dp.getMorphValuesForProxy(Kn.key),Nr=Tn?1:0;Tn&&Object.assign(Es,{morphing:{srcDemTile:Tn.from,dstDemTile:Tn.to,phase:o.dn(Tn.phase)}});const hr=o.dr(Kn.canonical),mr=o.ds(hr.getCenter().lat),Gn=o.dt(Kn.canonical,hr,mr,bn.worldSize/bn._pixelsPerMercatorPixel),pa=o.du(o.dv(Kn.canonical)),Aa=Ee.emissiveMode==="mrt-fallback"?1:0,ta=zv(bn.expandedFarZProjMatrix,Ks,Ns,pa,o.al(bn.zoom),Zt,bn.frustumCorners.TL,bn.frustumCorners.TR,bn.frustumCorners.BR,bn.frustumCorners.BL,bn.globeCenterInViewSpace,bn.globeRadius,bs,mn,bn._farZ,Aa,Gn);if(Tt(Kn,Nr),kt&&(Ie.setupElevationDraw(sn,kt,Es),Ee.uploadCommonUniforms(ut,kt,Kn.toUnwrapped()),ns)){const[ua,ui,Ai]=ns.getGridBuffers(mr,mn!==0);kt.draw(Ee,zn,cs,Fs,Ss,va.backCCW,ta,"globe_raster",ua,ui,Ai)}}}if(ns&&(Ee.renderDefaultNorthPole||Ee.renderDefaultSouthPole)){const bn=["GLOBE_POLES","PROJECTION_GLOBE_VIEW"];Yt&&bn.push("CUSTOM_ANTIALIASING"),kt=Ee.getOrCreateProgram("globeRaster",{defines:bn});for(const mn of Ke){const{x:zn,y:Kn,z:sn}=mn.canonical,Fs=Kn===0,yn=Kn===(1<ua.draw(Ee,lt.TRIANGLES,cs,qa.disabled,Ss,va.disabled,zv(zt.expandedFarZProjMatrix,Gn,Gn,pa,0,Zt,zt.frustumCorners.TL,zt.frustumCorners.TR,zt.frustumCorners.BR,zt.frustumCorners.BL,zt.globeCenterInViewSpace,zt.globeRadius,bs,0,zt._farZ,Aa),"globe_pole_raster",ui,Nr,hr);Ie.setupElevationDraw(mr,kt,Es),Ee.uploadCommonUniforms(ut,kt,mn.toUnwrapped()),Fs&&Ee.renderDefaultNorthPole&&ta(kt,_n),yn&&Ee.renderDefaultSouthPole&&(Gn=o.cC(o.bb(),Gn,[1,-1,1]),ta(kt,Tn))}}}})(W,Q,ee,ue,_e);else{const Ee=W.context,Ie=Ee.gl;let Je,Ke;const tt=W.shadowRenderer,ut=qd(W,W.longestCutoffRange),lt=Ss=>{if(Ke===Ss)return;const cs=[];cs.push(t2[Ss]),ut.shouldRenderCutoff&&cs.push("RENDER_CUTOFF"),tt&&(cs.push("RENDER_SHADOWS"),tt.useNormalOffset&&cs.push("NORMAL_OFFSET")),Je=W.getOrCreateProgram("terrainRaster",{defines:cs}),Ke=Ss},kt=W.colorModeForRenderPass(),Nt=new Hr(Ie.LEQUAL,Hr.ReadWrite,W.depthRangeFor3D);dp.update(_e);const zt=W.transform,Yt=dw(zt.zoom,Q.exaggeration(),Q.sourceCache._source.tileSize);let Tt=[0,0,0];if(tt){const Ss=W.style.directionalLight,cs=W.style.ambientLight;Ss&&cs&&(Tt=vm(W.style,Ss,cs))}{Ke=-1;const Ss=Ie.TRIANGLES,[cs,Ns]=[Q.gridIndexBuffer,Q.gridSegments];for(const Zt of ue){const ns=ee.getTile(Zt),bs=qa.disabled,Ks=Q.prevTerrainTileForTile[Zt.key],Es=Q.terrainTileForTile[Zt.key];e2(Ks,Es)&&dp.newMorphing(Zt.key,Ks,Es,_e,250),Be(W,ns.emissiveTexture),Ee.activeTexture.set(Ie.TEXTURE0),ns.texture&&ns.texture.bind(Ie.LINEAR,Ie.CLAMP_TO_EDGE);const bn=dp.getMorphValuesForProxy(Zt.key),mn=bn?1:0;let zn;bn&&(zn={morphing:{srcDemTile:bn.from,dstDemTile:bn.to,phase:o.dn(bn.phase)}});const Kn=W.emissiveMode==="mrt-fallback"?1:0,sn=cw(Zt.projMatrix,Te(Zt.canonical,zt.renderWorldCopies)?Yt/10:Yt,Tt,Kn);if(lt(mn),!Je)continue;Q.setupElevationDraw(ns,Je,zn);const Fs=Zt.toUnwrapped();tt&&tt.setupShadows(Fs,Je),W.uploadCommonUniforms(Ee,Je,Fs,null,ut),Je.draw(W,Ss,Nt,bs,kt,va.backCCW,sn,"terrain_raster",Q.gridBuffer,cs,Ns)}}}}(T,this,this.proxySourceCache,N,this._updateTimestamp),this.renderingToTexture=!0,T.gpuTimingDeferredRenderEnd(),N.splice(0,N.length))}renderBatch(N){if(this._drapedRenderBatches.length===0)return N+1;this.renderingToTexture=!0;const T=this.painter,z=this.painter.context,W=this.proxySourceCache,Q=this.proxiedCoords[W.id],ee=this._drapedRenderBatches.shift(),ue=T.style.order,_e=[];this._updateFBOs(T.emissiveMode==="mrt-fallback");let Ee=0;for(const Ie of Q){const Je=W.getTileByID(Ie.proxyTileKey),Ke=W.proxyCachedFBO[Ie.key]?W.proxyCachedFBO[Ie.key][N]:void 0,tt=Ke!==void 0?W.renderCache[Ke]:this.pool[Ee++],ut=Ke!==void 0;if(Je.texture=tt.tex,Je.emissiveTexture=tt.emissiveTex,ut&&!tt.dirty){_e.push(Je.tileID);continue}z.bindFramebuffer.set(tt.fb.framebuffer);const lt=z.gl;let kt;lt.drawBuffers(T.emissiveMode==="mrt-fallback"?[lt.COLOR_ATTACHMENT0,lt.COLOR_ATTACHMENT1]:[lt.COLOR_ATTACHMENT0]),this.renderedToTile=!1,tt.dirty&&(z.clear({color:o.aq.transparent,stencil:0}),tt.dirty=!1);for(let Nt=ee.start;Nt<=ee.end;++Nt){const zt=T.style._mergedLayers[ue[Nt]];if(zt.isHidden(T.transform.zoom))continue;const Yt=T.style.getLayerSourceCache(zt),Tt=Yt?this.proxyToSource[Ie.key][Yt.id]:[Ie];if(!Tt)continue;const Ss=Tt;z.viewport.set([0,0,tt.fb.width,tt.fb.height]),kt!==(Yt?Yt.id:null)&&(this._setupStencil(tt,Tt,zt,Yt),kt=Yt?Yt.id:null),T.renderLayer(T,Yt,zt,Ss)}if(lt.drawBuffers([lt.COLOR_ATTACHMENT0]),this._drapedRenderBatches.length===0)for(const Nt of this._pendingGroundEffectLayers){const zt=T.style._mergedLayers[ue[Nt]];if(zt.isHidden(T.transform.zoom))continue;const Yt=T.style.getLayerSourceCache(zt),Tt=Yt?this.proxyToSource[Ie.key][Yt.id]:[Ie];if(!Tt)continue;const Ss=Tt;z.viewport.set([0,0,tt.fb.width,tt.fb.height]),kt!==(Yt?Yt.id:null)&&(this._setupStencil(tt,Tt,zt,Yt),kt=Yt?Yt.id:null),T.renderLayer(T,Yt,zt,Ss)}this.renderedToTile?(tt.dirty=!0,_e.push(Je.tileID)):ut||--Ee,Ee===5&&(Ee=0,this.renderToBackBuffer(_e))}return this.renderToBackBuffer(_e),this.renderingToTexture=!1,z.bindFramebuffer.set(null),z.viewport.set([0,0,T.width,T.height]),ee.end+1}postRender(){}isLayerOrderingCorrect(N){const T=N.order.length;let z=-1,W=T;for(let Q=0;Qz}getMinElevationBelowMSL(){let N=0;return this._visibleDemTiles.filter(T=>T.dem).forEach(T=>{N=Math.min(N,T.dem.tree.minimums[0])}),N===0?N:(N-30)*this._exaggeration}raycast(N,T,z){if(!this._visibleDemTiles)return null;const W=this._visibleDemTiles.filter(Q=>Q.dem).map(Q=>{const ee=Q.tileID,ue=1<(Q.t!==null?Q.t:Number.MAX_VALUE)-(ee.t!==null?ee.t:Number.MAX_VALUE));for(const Q of W){if(Q.t==null)return null;const ee=Q.tile.dem.tree.raycast(Q.minx,Q.miny,Q.maxx,Q.maxy,N,T,z);if(ee!=null)return ee}return null}_createFBO(){const N=this.painter.context,T=N.gl,z=this.drapeBufferSize;N.activeTexture.set(T.TEXTURE0);const W=new o.T(N,{width:z[0],height:z[1],data:null},T.RGBA8);W.bind(T.LINEAR,T.CLAMP_TO_EDGE);const Q=N.createFramebuffer(z[0],z[1],1,null);let ee;return Q.colorAttachment0.set(W.texture),this._emissiveTexture&&(ee=new o.T(N,{width:z[0],height:z[1],data:null},T.R8),ee.bind(T.LINEAR,T.CLAMP_TO_EDGE),Q.createColorAttachment(N,1),Q.colorAttachment1.set(ee.texture)),Q.depthAttachment=new ZE(N,Q.framebuffer),this._sharedDepthStencil===void 0?(this._sharedDepthStencil=N.createRenderbuffer(N.gl.DEPTH_STENCIL,z[0],z[1]),this._stencilRef=0,Q.depthAttachment.set(this._sharedDepthStencil),N.clear({stencil:0})):Q.depthAttachment.set(this._sharedDepthStencil),N.extTextureFilterAnisotropic&&T.texParameterf(T.TEXTURE_2D,N.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,N.extTextureFilterAnisotropicMax),{fb:Q,tex:W,emissiveTex:ee,dirty:!1}}_updateFBOs(N){if(this._emissiveTexture!==N){for(const T of this.pool)this._updateFBO(T,N);for(const T of this.proxySourceCache.renderCache)this._updateFBO(T,N);this._emissiveTexture=N}}_updateFBO(N,T){const z=N.fb,W=this.painter.context,Q=W.gl,ee=this.drapeBufferSize;if(T){const ue=new o.T(W,{width:ee[0],height:ee[1],data:null},Q.R8);ue.bind(Q.LINEAR,Q.CLAMP_TO_EDGE),N.emissiveTex=ue,z.createColorAttachment(W,1),z.colorAttachment1.set(ue.texture)}else N.emissiveTex=void 0,z.removeColorAttachment(W,1);N.dirty=!0}_initFBOPool(){for(;this.pool.length{const T=this._style._mergedLayers[N],z=T.isHidden(this.painter.transform.zoom);return T.type==="hillshade"||T.type==="custom"?!z&&T.shouldRedrape():!z&&T.hasTransition()})}_clearLineLayersFromRenderCache(){let N=!1;for(const z of this._style.getSources())if(z instanceof da){N=!0;break}if(!N)return;const T={};for(let z=0;z_e>ue.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=z}_setupRenderCache(N){const T=this.proxySourceCache;if(this._shouldDisableRenderCache()||this.invalidateRenderCache){if(this.invalidateRenderCache=!1,T.renderCache.length>T.renderCachePool.length){const ee=Object.values(T.proxyCachedFBO);T.proxyCachedFBO={};for(let ue=0;ue=0;ee--){const ue=z[ee];if(T.getTileByID(ue.key),T.proxyCachedFBO[ue.key]!==void 0){const _e=N[ue.key],Ee=this.proxyToSource[ue.key];let Ie=0;for(const Je in Ee){const Ke=Ee[Je],tt=_e[Je];if(!tt||tt.length!==Ke.length||Ke.some((ut,lt)=>ut!==tt[lt]||W[Je]&&W[Je].hasOwnProperty(ut.key))){Ie=-1;break}++Ie}for(const Je in T.proxyCachedFBO[ue.key])T.renderCache[T.proxyCachedFBO[ue.key][Je]].dirty=Ie<0||Ie!==Object.values(_e).length}}const Q=[...this._drapedRenderBatches];Q.sort((ee,ue)=>ue.end-ue.start-(ee.end-ee.start));for(const ee of Q)for(const ue of z){if(T.proxyCachedFBO[ue.key])continue;let _e=T.renderCachePool.pop();_e===void 0&&T.renderCache.length<50&&(_e=T.renderCache.length,T.renderCache.push(this._createFBO())),_e!==void 0&&(T.proxyCachedFBO[ue.key]={},T.proxyCachedFBO[ue.key][ee.start]=_e,T.renderCache[_e].dirty=!0)}this._tilesDirty={}}_setupStencil(N,T,z,W){if(!W||!this._sourceTilesOverlap[W.id])return void(this._overlapStencilType&&(this._overlapStencilType=!1));const Q=this.painter.context,ee=Q.gl;if(T.length<=1)return void(this._overlapStencilType=!1);let ue;if(z.isTileClipped())ue=T.length,this._overlapStencilMode.test={func:ee.EQUAL,mask:255},this._overlapStencilType="Clip";else{if(!(T[0].overscaledZ>T[T.length-1].overscaledZ))return void(this._overlapStencilType=!1);ue=1,this._overlapStencilMode.test={func:ee.GREATER,mask:255},this._overlapStencilType="Mask"}this._stencilRef+ue>255&&(Q.clear({stencil:0}),this._stencilRef=0),this._stencilRef+=ue,this._overlapStencilMode.ref=this._stencilRef,z.isTileClipped()&&this._renderTileClippingMasks(T,this._overlapStencilMode.ref)}clipOrMaskOverlapStencilType(){return this._overlapStencilType==="Clip"||this._overlapStencilType==="Mask"}stencilModeForRTTOverlap(N){return this.renderingToTexture&&this._overlapStencilType?(this._overlapStencilType==="Clip"&&(this._overlapStencilMode.ref=this.painter._tileClippingMaskIDs[N.key]),this._overlapStencilMode):qa.disabled}_renderTileClippingMasks(N,T){const z=this.painter,W=this.painter.context,Q=W.gl;z._tileClippingMaskIDs={},W.setColorMode(Ba.disabled),W.setDepthMode(Hr.disabled);const ee=z.getOrCreateProgram("clippingMask");for(const ue of N){const _e=z._tileClippingMaskIDs[ue.key]=--T;ee.draw(z,Q.TRIANGLES,Hr.disabled,new qa({func:Q.ALWAYS,mask:0},_e,255,Q.KEEP,Q.KEEP,Q.REPLACE),Ba.disabled,va.disabled,ft(ue.projMatrix),"$clipping",z.tileExtentBuffer,z.quadTriangleIndexBuffer,z.tileExtentSegments)}}pointCoordinate(N){const T=this.painter.transform;if(N.x<0||N.x>T.width||N.y<0||N.y>T.height)return null;const z=[N.x,N.y,1,1];o.aE(z,z,T.pixelMatrixInverse),o.cu(z,z,1/z[3]),z[0]/=T.worldSize,z[1]/=T.worldSize;const W=T._camera.position,Q=o.bU(1,T.center.lat),ee=[W[0],W[1],W[2]/Q,0],ue=o.cV([],z.slice(0,3),ee);o.ay(ue,ue);const _e=this.raycast(ee,ue,this._exaggeration);return _e!==null&&_e?(o.bg(ee,ee,ue,_e),ee[3]=ee[2],ee[2]*=Q,ee):null}_setupProxiedCoordsForOrtho(N,T,z){if(N.getSource()instanceof o.aV)return this._setupProxiedCoordsForImageSource(N,T,z);this._findCoveringTileCache[N.id]=this._findCoveringTileCache[N.id]||{};const W=this.proxiedCoords[N.id]=[],Q=this.proxyCoords;for(let _e=0;_eIe.overscaledZ-Ee.overscaledZ)}_setupProxiedCoordsForImageSource(N,T,z){if(!N.getSource().loaded())return;const W=this.proxiedCoords[N.id]=[],Q=this.proxyCoords,ee=N.getSource(),ue=ee.tileID;if(!ue)return;const _e=new o.P(ue.x,ue.y)._div(1<(Je.min.x=Math.min(Je.min.x,Ke.x-_e.x),Je.min.y=Math.min(Je.min.y,Ke.y-_e.y),Je.max.x=Math.max(Je.max.x,Ke.x-_e.x),Je.max.y=Math.max(Je.max.y,Ke.y-_e.y),Je),{min:new o.P(Number.MAX_VALUE,Number.MAX_VALUE),max:new o.P(-Number.MAX_VALUE,-Number.MAX_VALUE)}),Ie=(Je,Ke)=>{const tt=Je.wrap+Je.canonical.x/(1<kt+Ee.max.x||ut+ltNt+Ee.max.y};for(let Je=0;Jeee.key===T.tileID.key);if(Q)return Q}if(T.tileID.key!==N.key){const Q=N.canonical.z-T.tileID.canonical.z;let ee,ue,_e;W=o.bb();const Ee=T.tileID.wrap-N.wrap<0?(ee=o.an>>Q,ue=ee*((T.tileID.canonical.x<=Je){const Ke=N.canonical.z-Je;T.getSource().reparseOverscaled?(ue=Math.max(N.canonical.z+2,T.transform.tileZoom),ee=new o.aR(ue,N.wrap,Je,N.canonical.x>>Ke,N.canonical.y>>Ke)):Ke!==0&&(ue=Je,ee=new o.aR(ue,N.wrap,Je,N.canonical.x>>Ke,N.canonical.y>>Ke))}ee.key!==N.key&&(Ee.push(ee.key),z=T.getTile(ee))}const Ie=Je=>{Ee.forEach(Ke=>{W[Ke]=Je}),Ee.length=0};for(ue-=1;ue>=_e&&(!z||!z.hasData());ue--){z&&Ie(z.tileID.key);const Je=ee.calculateScaledKey(ue);if(z=T.getTileByID(Je),z&&z.hasData())break;const Ke=W[Je];if(Ke===null)break;Ke===void 0?Ee.push(Je):z=T.getTileByID(Ke)}return Ie(z?z.tileID.key:null),z&&z.hasData()?z:null}findDEMTileFor(N){return this.enabled?this._findTileCoveringTileID(N,this.sourceCache):null}prepareDrawTile(){this.renderedToTile=!0}_clearRenderCacheForTile(N,T){let z=this._tilesDirty[N];z||(z=this._tilesDirty[N]={}),z[T.key]=!0}}function Rs(R,N,T){const z=function(ue,_e,Ee){const Ie=o.bi(_e,ue),Je=o.bi(Ee,[.2126,.7152,.0722]),Ke=(ut,lt,kt)=>(1-kt)*ut+kt*lt,tt=Ke(1-.3*Math.min(Je,1),1,Math.min(Ie+1,1));return Ke(.92,1,Math.asin(o.aC(_e[2],-1,1))/Math.PI+.5)*tt}(R,[0,0,1],N),W=[0,0,0];o.bJ(W,T.slice(0,3),z);const Q=[0,0,0];o.bJ(Q,N.slice(0,3),R[2]);const ee=[0,0,0];return o.cT(ee,W,Q),o.cW(ee)}const en=["fill","fillOutline","fillPattern","line","linePattern","background","backgroundPattern","hillshade","raster"],Mn=["stars","rainParticle","snowParticle","fillExtrusion","fillExtrusionGroundEffect","building","buildingBloom","elevatedStructures","model","symbol"];class Xn{static cacheKey(N,T,z,W){const Q=[T];W&&Q.push(W.cacheKey);for(const ee of z)(typeof ee=="string"&&ee.includes(" ")||N.usedDefines.has(ee))&&Q.push(ee);return Q.join("/")}constructor(N,T,z,W,Q,ee){const ue=N.gl;this.program=ue.createProgram(),this.configuration=W,this.name=T,this.fixedDefines=[...ee];const _e=`#version 300 es ${(W?W.defines():[]).concat(ee.map(lt=>`#define ${lt}`)).join(` `)}`,Ee=[_e,P1];for(const lt of z.fragmentIncludes)Ee.push(Jf[lt]);Ee.push(z.fragmentSource);const Ie=Ee.join(` `),Je=[_e,ZN];for(const lt of z.vertexIncludes)Je.push(Jf[lt]);this.forceManualRenderingForInstanceIDShaders=N.forceManualRenderingForInstanceIDShaders&&z.vertexSource.includes("gl_InstanceID"),this.forceManualRenderingForInstanceIDShaders&&Je.push("uniform int u_instanceID;"),Je.push(z.vertexSource);let Ke=Je.join(` `);this.forceManualRenderingForInstanceIDShaders&&(Ke=Ke.replaceAll("gl_InstanceID","u_instanceID"));const tt=ue.createShader(ue.FRAGMENT_SHADER);if(ue.isContextLost())return void(this.failedToCreate=!0);ue.shaderSource(tt,Ie),ue.compileShader(tt),ue.attachShader(this.program,tt);const ut=ue.createShader(ue.VERTEX_SHADER);ue.isContextLost()?this.failedToCreate=!0:(ue.shaderSource(ut,Ke),ue.compileShader(ut),ue.attachShader(this.program,ut),this.attributes={},ue.linkProgram(this.program),ue.deleteShader(ut),ue.deleteShader(tt),this.fixedUniforms=Q(N),this.fixedUniformsEntries=Object.entries(this.fixedUniforms),this.binderUniforms=W?W.getUniforms(N):[],this.forceManualRenderingForInstanceIDShaders&&(this.instancingUniforms=(lt=>({u_instanceID:new o.bX(lt)}))(N)),(ee.includes("TERRAIN")||ee.includes("ELEVATED")||T.includes("symbol")||T.includes("circle"))&&(this.terrainUniforms=(lt=>({u_dem:new o.bX(lt),u_dem_prev:new o.bX(lt),u_dem_tl:new o.b_(lt),u_dem_scale:new o.bZ(lt),u_dem_tl_prev:new o.b_(lt),u_dem_scale_prev:new o.bZ(lt),u_dem_size:new o.bZ(lt),u_dem_lerp:new o.bZ(lt),u_exaggeration:new o.bZ(lt),u_depth:new o.bX(lt),u_depth_size_inv:new o.b_(lt),u_depth_range_unpack:new o.b_(lt),u_occluder_half_size:new o.bZ(lt),u_occlusion_depth_offset:new o.bZ(lt),u_meter_to_dem:new o.bZ(lt),u_label_plane_matrix_inv:new o.b$(lt)}))(N)),ee.includes("GLOBE")&&(this.globeUniforms=(lt=>({u_tile_tl_up:new o.bY(lt),u_tile_tr_up:new o.bY(lt),u_tile_br_up:new o.bY(lt),u_tile_bl_up:new o.bY(lt),u_tile_up_scale:new o.bZ(lt)}))(N)),ee.includes("FOG")&&(this.fogUniforms=(lt=>({u_fog_matrix:new o.b$(lt),u_fog_range:new o.b_(lt),u_fog_color:new o.cO(lt),u_fog_horizon_blend:new o.bZ(lt),u_fog_vertical_limit:new o.b_(lt),u_fog_temporal_offset:new o.bZ(lt),u_frustum_tl:new o.bY(lt),u_frustum_tr:new o.bY(lt),u_frustum_br:new o.bY(lt),u_frustum_bl:new o.bY(lt),u_globe_pos:new o.bY(lt),u_globe_radius:new o.bZ(lt),u_globe_transition:new o.bZ(lt),u_is_globe:new o.bX(lt),u_viewport:new o.b_(lt)}))(N)),ee.includes("RENDER_CUTOFF")&&(this.cutoffUniforms=(lt=>({u_cutoff_params:new o.cO(lt)}))(N)),ee.includes("LIGHTING_3D_MODE")&&(this.lightsUniforms=(lt=>({u_lighting_ambient_color:new o.bY(lt),u_lighting_directional_dir:new o.bY(lt),u_lighting_directional_color:new o.bY(lt),u_ground_radiance:new o.bY(lt)}))(N)),ee.includes("RENDER_SHADOWS")&&(this.shadowUniforms=(lt=>({u_light_matrix_0:new o.b$(lt),u_light_matrix_1:new o.b$(lt),u_fade_range:new o.b_(lt),u_shadow_normal_offset:new o.bY(lt),u_shadow_intensity:new o.bZ(lt),u_shadow_texel_size:new o.bZ(lt),u_shadow_map_resolution:new o.bZ(lt),u_shadow_direction:new o.bY(lt),u_shadow_bias:new o.bY(lt),u_shadowmap_0:new o.bX(lt),u_shadowmap_1:new o.bX(lt)}))(N)))}getAttributeLocation(N,T){let z=this.attributes[T];return z===void 0&&(z=this.attributes[T]=N.getAttribLocation(this.program,T)),z}setTerrainUniformValues(N,T){if(!this.terrainUniforms)return;const z=this.terrainUniforms;if(!this.failedToCreate){N.program.set(this.program);for(const W in T)z[W]&&z[W].set(this.program,W,T[W])}}setGlobeUniformValues(N,T){if(!this.globeUniforms)return;const z=this.globeUniforms;if(!this.failedToCreate){N.program.set(this.program);for(const W in T)z[W]&&z[W].set(this.program,W,T[W])}}setFogUniformValues(N,T){if(!this.fogUniforms)return;const z=this.fogUniforms;if(!this.failedToCreate){N.program.set(this.program);for(const W in T)z[W].set(this.program,W,T[W])}}setCutoffUniformValues(N,T){if(!this.cutoffUniforms)return;const z=this.cutoffUniforms;if(!this.failedToCreate){N.program.set(this.program);for(const W in T)z[W].set(this.program,W,T[W])}}setLightsUniformValues(N,T){if(!this.lightsUniforms)return;const z=this.lightsUniforms;if(!this.failedToCreate){N.program.set(this.program);for(const W in T)z[W].set(this.program,W,T[W])}}setShadowUniformValues(N,T){if(this.failedToCreate||!this.shadowUniforms)return;const z=this.shadowUniforms;N.program.set(this.program);for(const W in T)z[W].set(this.program,W,T[W])}_drawDebugWireframe(N,T,z,W,Q,ee,ue,_e,Ee,Ie){const Je=N.options.wireframe;if(Je.terrain===!1&&Je.layers2D===!1&&Je.layers3D===!1)return;const Ke=N.context;if(!(!(!Je.terrain||this.name!=="terrainRaster"&&this.name!=="globeRaster")||!(!Je.layers2D||N._terrain&&N._terrain.renderingToTexture||!en.includes(this.name))||!(!Je.layers3D||!Mn.includes(this.name))))return;const tt=Ke.gl,ut=N.wireframeDebugCache.getLinesFromTrianglesBuffer(N.frameCounter,Q,Ke);if(!ut)return;const lt=[...this.fixedDefines,"DEBUG_WIREFRAME"],kt=N.getOrCreateProgram(this.name,{config:this.configuration,defines:lt});Ke.program.set(kt.program);const Nt=(Tt,Ss,cs)=>{if(Ss[Tt]&&cs[Tt])for(const Ns in Ss[Tt])cs[Tt][Ns]&&cs[Tt][Ns].set(cs.program,Ns,Ss[Tt][Ns].current)};Ee&&Ee.setUniforms(kt.program,Ke,kt.binderUniforms,ue,{zoom:_e}),Nt("fixedUniforms",this,kt),Nt("terrainUniforms",this,kt),Nt("globeUniforms",this,kt),Nt("fogUniforms",this,kt),Nt("lightsUniforms",this,kt),Nt("shadowUniforms",this,kt),ut.bind(),Ke.setColorMode(new Ba([tt.ONE,tt.ONE_MINUS_SRC_ALPHA,tt.ZERO,tt.ONE],o.aq.transparent,[!0,!0,!0,!1])),Ke.setDepthMode(new Hr(T.func===tt.LESS?tt.LEQUAL:T.func,Hr.ReadOnly,T.range)),Ke.setStencilMode(qa.disabled);const zt=3*ee.primitiveLength*2,Yt=3*ee.primitiveOffset*2*2;if(this.forceManualRenderingForInstanceIDShaders){const Tt=Ie||1;for(let Ss=0;Ss1?tt.drawElementsInstanced(tt.LINES,zt,tt.UNSIGNED_SHORT,Yt,Ie):tt.drawElements(tt.LINES,zt,tt.UNSIGNED_SHORT,Yt);Q.bind(),Ke.program.set(this.program),Ke.setDepthMode(T),Ke.setStencilMode(z),Ke.setColorMode(W)}checkUniforms(N,T,z){if(this.fixedDefines.includes(T)){for(const W of Object.keys(z))if(!z[W].initialized)throw new Error(`Program '${this.name}', from draw '${N}': uniform ${W} not set but required by ${T} being defined`)}}draw(N,T,z,W,Q,ee,ue,_e,Ee,Ie,Je,Ke,tt,ut,lt,kt){const Nt=N.context,zt=Nt.gl;if(this.failedToCreate)return;Nt.program.set(this.program),Nt.setDepthMode(z),Nt.setStencilMode(W),Nt.setColorMode(Q),Nt.setCullFace(ee);for(const[Zt,ns]of this.fixedUniformsEntries)ns.set(this.program,Zt,ue[Zt]);ut&&ut.setUniforms(this.program,Nt,this.binderUniforms,Ke,{zoom:tt});const Yt={[zt.POINTS]:1,[zt.LINES]:2,[zt.TRIANGLES]:3,[zt.LINE_STRIP]:1}[T];this.checkUniforms(_e,"RENDER_SHADOWS",this.shadowUniforms);const Tt=lt||[],Ss=ut?ut.getPaintVertexBuffers():[],cs=T===zt.TRIANGLES&&Ie,Ns=kt&&kt>0?1:void 0;for(const Zt of Je.get()){const ns=Zt.vaos||(Zt.vaos={});if((ns[_e]||(ns[_e]=new KS)).bind(Nt,this,Ee,Ss,Ie,Zt.vertexOffset,Tt,Ns),this.forceManualRenderingForInstanceIDShaders){const bs=kt||1;for(let Ks=0;Ks1?zt.drawElementsInstanced(T,Zt.primitiveLength*Yt,zt.UNSIGNED_SHORT,Zt.primitiveOffset*Yt*2,kt):Ie?zt.drawElements(T,Zt.primitiveLength*Yt,zt.UNSIGNED_SHORT,Zt.primitiveOffset*Yt*2):zt.drawArrays(T,Zt.vertexOffset,Zt.vertexLength);cs&&this._drawDebugWireframe(N,z,W,Q,Ie,Zt,Ke,tt,ut,kt)}}}function tn(R,N,T=0){const z=Math.pow(2,N.tileID.overscaledZ),W=N.tileSize*Math.pow(2,R.transform.tileZoom)/z,Q=W*(N.tileID.canonical.x+N.tileID.wrap*z),ee=W*N.tileID.canonical.y;return{u_image:0,u_texsize:N.imageAtlasTexture?N.imageAtlasTexture.size:[0,0],u_tile_units_to_pixels:1/o.aA(N,1,R.transform.tileZoom),u_pixel_coord_upper:[Q>>16,ee>>16],u_pixel_coord_lower:[65535&Q,65535&ee],u_pattern_transition:T}}const $n={terrain:0,flat:1},nr=o.bb(),Mr=(R,N,T,z,W,Q,ee,ue,_e,Ee,Ie,Je,Ke,tt,ut,lt,kt,Nt,zt=[0,0,1])=>{const Yt=N.style.light,Tt=Yt.properties.get("position"),Ss=[Tt.x,Tt.y,Tt.z],cs=o.dE();Yt.properties.get("anchor")==="viewport"&&(o.dF(cs,-N.transform.angle),o.dG(Ss,Ss,cs));const Ns=Yt.properties.get("color").toPremultipliedRenderColor(null),Zt=N.transform,ns={u_matrix:R,u_lightpos:Ss,u_lightintensity:Yt.properties.get("intensity"),u_lightcolor:[Ns.r,Ns.g,Ns.b],u_vertical_gradient:+T,u_opacity:z,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:$n[Ee],u_base_type:$n[Ie],u_ao:W,u_edge_radius:Q,u_width_scale:ee,u_flood_light_color:ut,u_vertical_scale:lt,u_flood_light_intensity:kt,u_ground_shadow_factor:Nt,u_front_cutoff_params:zt};return Zt.projection.name==="globe"&&(ns.u_tile_id=[ue.canonical.x,ue.canonical.y,1<({u_matrix:R,u_edge_radius:N,u_width_scale:T,u_vertical_scale:z,u_height_type:$n[W],u_base_type:$n[Q]}),Vn=(R,N,T,z,W,Q,ee,ue,_e,Ee,Ie,Je,Ke,tt,ut,lt,kt,Nt)=>{const zt=Mr(R,N,T,z,W,Q,ee,ue,Ee,Ie,Je,Ke,tt,ut,lt,kt,1,[0,0,0]),Yt={u_height_factor:-Math.pow(2,ue.overscaledZ)/_e.tileSize/8};return Object.assign(zt,tn(N,_e,Nt),Yt)},Vr=(R,N,T)=>({u_matrix:R,u_emissive_strength:N,u_ground_shadow_factor:T}),Sa=(R,N,T,z,W,Q=0)=>Object.assign(Vr(R,N,W),tn(T,z,Q)),ba=(R,N,T,z)=>({u_matrix:R,u_world:T,u_emissive_strength:N,u_ground_shadow_factor:z}),ro=(R,N,T,z,W,Q,ee=0)=>Object.assign(Sa(R,N,T,z,Q,ee),{u_world:W}),Oi=(R,N)=>({u_matrix:R,u_depth_bias:N}),Al=(R,N)=>({u_matrix:R,u_ground_shadow_factor:N}),Ki=(R,N,T,z,W)=>({u_matrix:R,u_camera_pos:[N[0],N[1],N[2]],u_depth_bias:T,u_height_scale:z,u_reset_depth:W}),xc=(R,N,T)=>({u_image:R,u_opacity:N,u_blend_mode:T}),Cu=(R,N,T,z,W,Q,ee,ue,_e,Ee=[0,0,1])=>({u_matrix:R,u_normal_matrix:N,u_opacity:T,u_faux_facade_ao_intensity:z,u_camera_pos:W,u_tile_to_meter:Q,u_facade_emissive_chance:ee,u_flood_light_color:ue,u_flood_light_intensity:_e,u_front_cutoff_params:Ee}),El=R=>({u_matrix:R}),Qi=R=>({u_matrix:R}),mi=(R,N,T,z,W,Q,ee,ue)=>{const _e=o.an/Q.tileSize;return{u_matrix:R,u_inv_rot_matrix:N,u_camera_to_center_distance:T.getCameraToCenterDistance(ue),u_extrude_scale:[T.pixelsToGLUnits[0]/_e,T.pixelsToGLUnits[1]/_e],u_zoom_transition:z,u_tile_id:ee,u_merc_center:W}},Ll=(R,N,T,z)=>({u_matrix:R,u_inv_matrix:N,u_camera_to_center_distance:T.getCameraToCenterDistance(z),u_viewport_size:[T.width,T.height]}),Ao=(R,N,T=1)=>({u_matrix:R,u_color:N,u_overlay:0,u_overlay_scale:T}),gl=o.bb(),bu=(R,N,T,z,W,Q,ee)=>{const ue=R.transform,_e=ue.projection.name==="globe",Ee=_e?o.dH(ue.zoom,N.canonical)*ue._pixelsPerMercatorPixel:o.aA(T,1,Q),Ie={u_matrix:N.projMatrix,u_extrude_scale:Ee,u_intensity:ee,u_inv_rot_matrix:gl,u_merc_center:[0,0],u_tile_id:[0,0,0],u_zoom_transition:0,u_up_dir:[0,0,0]};if(_e){Ie.u_inv_rot_matrix=z,Ie.u_merc_center=W,Ie.u_tile_id=[N.canonical.x,N.canonical.y,1<({u_matrix:N,u_normalize_matrix:T,u_globe_matrix:z,u_merc_matrix:W,u_grid_matrix:Q,u_tl_parent:ee,u_scale_parent:Ie,u_fade_t:Je.mix,u_opacity:Je.opacity*Ke.paint.get("raster-opacity"),u_image0:0,u_image1:1,u_brightness_low:Ke.paint.get("raster-brightness-min"),u_brightness_high:Ke.paint.get("raster-brightness-max"),u_saturation_factor:o.dJ(Ke.paint.get("raster-saturation")),u_contrast_factor:o.dI(Ke.paint.get("raster-contrast")),u_spin_weights:sx(Ke.paint.get("raster-hue-rotate")),u_perspective_transform:tt,u_raster_elevation:ut,u_zoom_transition:ue,u_merc_center:_e,u_cutoff_params:Ee,u_colorization_mix:Bm(o.dK,kt,zt),u_colorization_offset:_u(o.dK,Nt,zt),u_color_ramp:lt,u_texture_offset:[Tt/(Yt+2*Tt),Yt/(Yt+2*Tt)],u_texture_res:[Yt+2*Tt,Yt+2*Tt],u_emissive_strength:Ss,u_zbias_factor:Xu(R)});function sx(R){R*=Math.PI/180;const N=Math.sin(R),T=Math.cos(R);return[(2*T+1)/3,(-Math.sqrt(3)*N-T+1)/3,(Math.sqrt(3)*N-T+1)/3]}const lu=.05,ed=(R,N,T,z,W,Q,ee,ue,_e,Ee,Ie,Je)=>({u_matrix:R,u_normalize_matrix:N,u_globe_matrix:T,u_merc_matrix:z,u_grid_matrix:W,u_tl_parent:Q,u_scale_parent:Ee,u_fade_t:Ie.mix,u_opacity:Ie.opacity,u_image0:0,u_image1:1,u_raster_elevation:Je,u_zoom_transition:ee,u_merc_center:ue,u_cutoff_params:_e}),Vd=(R,N,T,z,W,Q,ee,ue,_e,Ee)=>({u_particle_texture:R,u_particle_texture_side_len:N,u_tile_offset:T,u_velocity:z,u_color_ramp:Q,u_velocity_res:W,u_max_speed:ee,u_uv_offset:ue,u_data_scale:[255*_e[0],255*_e[1]],u_data_offset:Ee,u_particle_pos_scale:1.1,u_particle_pos_offset:[lu,lu]}),fh=(R,N,T,z,W,Q,ee,ue,_e,Ee)=>({u_particle_texture:R,u_particle_texture_side_len:N,u_velocity:T,u_velocity_res:z,u_max_speed:W,u_speed_factor:Q,u_reset_rate:ee,u_rand_seed:Math.random(),u_uv_offset:ue,u_data_scale:[255*_e[0],255*_e[1]],u_data_offset:Ee,u_particle_pos_scale:1.1,u_particle_pos_offset:[lu,lu]}),md=o.bb(),Ah=(R,N,T,z,W,Q,ee,ue,_e,Ee,Ie,Je,Ke,tt,ut,lt,kt,Nt,zt,Yt,Tt,Ss,cs,Ns)=>{const Zt=W.transform,ns={u_is_size_zoom_constant:+(R==="constant"||R==="source"),u_is_size_feature_constant:+(R==="constant"||R==="camera"),u_size_t:N?N.uSizeT:0,u_size:N?N.uSize:0,u_camera_to_center_distance:Zt.getCameraToCenterDistance(zt),u_rotate_symbol:+T,u_aspect_ratio:Zt.width/Zt.height,u_fade_change:W.options.fadeDuration?W.symbolFadeChange:1,u_matrix:Q,u_label_plane_matrix:ee,u_coord_matrix:ue,u_is_text:+Ee,u_elevation_from_sea:_e?1:0,u_pitch_with_map:+z,u_texsize:Ie,u_texsize_icon:Je,u_texture:0,u_texture_icon:1,u_tile_id:[0,0,0],u_zoom_transition:0,u_inv_rot_matrix:md,u_merc_center:[0,0],u_camera_forward:[0,0,0],u_ecef_origin:[0,0,0],u_tile_matrix:md,u_up_vector:[0,-1,0],u_color_adj_mat:Ss,u_icon_transition:cs||0,u_gamma_scale:z?W.transform.getCameraToCenterDistance(zt)*Math.cos(W.terrain?0:W.transform._pitch):1,u_device_pixel_ratio:o.o.devicePixelRatio,u_is_halo:1,u_scale_factor:Ns||1,u_ground_shadow_factor:Yt,u_inv_matrix:o.b7(o.bb(),ee),u_normal_scale:Tt,u_lutTexture:10,u_zoom:Zt.zoom-Math.floor(Zt.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 zt.name==="globe"&&(ns.u_tile_id=[tt.canonical.x,tt.canonical.y,1<({u_matrix:R,u_emissive_strength:N,u_opacity:T,u_color:z}),Md=(R,N,T,z,W,Q,ee,ue,_e)=>Object.assign(function(Ee,Ie,Je,Ke,tt,ut){const{width:lt,height:kt}=Ke.imageManager.getPixelSize(Ie),Nt=Math.pow(2,ut.tileID.overscaledZ),zt=ut.tileSize*Math.pow(2,Ke.transform.tileZoom)/Nt,Yt=zt*(ut.tileID.canonical.x+ut.tileID.wrap*Nt),Tt=zt*ut.tileID.canonical.y;return{u_image:0,u_pattern_tl:Je.tl,u_pattern_br:Je.br,u_texsize:[lt,kt],u_pattern_size:Je.displaySize,u_pattern_units_to_pixels:tt?[Ke.transform.width,-1*Ke.transform.height]:[1/o.aA(ut,1,Ke.transform.tileZoom),1/o.aA(ut,1,Ke.transform.tileZoom)],u_pixel_coord_upper:[Yt>>16,Tt>>16],u_pixel_coord_lower:[65535&Yt,65535&Tt]}}(0,Q,ee,z,ue,_e),{u_matrix:R,u_emissive_strength:N,u_opacity:T}),Qh=new Float32Array(o.b9([])),Ec=(R,N,T,z,W,Q,ee,ue,_e,Ee,Ie,Je,Ke,tt=[0,0,0],ut,lt,kt)=>{const Nt=W.style.light,zt=Nt.properties.get("position"),Yt=[-zt.x,-zt.y,zt.z],Tt=o.dE();Nt.properties.get("anchor")==="viewport"&&(o.dF(Tt,-W.transform.angle),o.dG(Yt,Yt,Tt));const Ss=Ie.alphaMode==="MASK",cs=Nt.properties.get("color").toNonPremultipliedRenderColor(null),Ns=Ke.paint.get("model-ambient-occlusion-intensity"),Zt=Ke.paint.get("model-color").constantOr(o.aq.white).toNonPremultipliedRenderColor(null);return Zt.a=Ke.paint.get("model-color-mix-intensity").constantOr(0),kt&&(Zt.r=kt[0],Zt.g=kt[1],Zt.b=kt[2],Zt.a=kt[3]),lt&&(Zt.r=lt.color.r,Zt.g=lt.color.g,Zt.b=lt.color.b,Zt.a=lt.colorMix,Je=lt.emissionStrength,Q*=lt.opacity),{u_matrix:R,u_lighting_matrix:N,u_normal_matrix:T,u_node_matrix:z||Qh,u_lightpos:Yt,u_lightintensity:Nt.properties.get("intensity"),u_lightcolor:[cs.r,cs.g,cs.b],u_camera_pos:tt,u_opacity:Q,u_baseTextureIsAlpha:0,u_alphaMask:+Ss,u_alphaCutoff:Ie.alphaCutoff,u_baseColorFactor:ee.toNonPremultipliedRenderColor(null).toArray01(),u_emissiveFactor:ue.toNonPremultipliedRenderColor(null).toArray01(),u_metallicFactor:_e,u_roughnessFactor:Ee,u_baseColorTexture:5,u_metallicRoughnessTexture:6,u_normalTexture:7,u_occlusionTexture:8,u_emissionTexture:9,u_lutTexture:10,u_color_mix:Zt.toArray01(),u_aoIntensity:Ns,u_emissive_strength:Je,u_occlusionTextureTransform:ut||[0,0,0,0]}},Eh=(R,N=Qh,T=Qh)=>({u_matrix:R,u_instance:N,u_node_matrix:T}),Dp={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 Au{constructor(N,T,z,W){this.id=Au.uniqueIdxCounter,Au.uniqueIdxCounter++,this.context=N;const Q=N.gl;this.buffer=Q.createBuffer(),this.dynamicDraw=!!z,this.context.unbindVAO(),N.bindElementBuffer.set(this.buffer),Q.bufferData(Q.ELEMENT_ARRAY_BUFFER,T.arrayBuffer,this.dynamicDraw?Q.DYNAMIC_DRAW:Q.STATIC_DRAW),this.dynamicDraw||W||T.destroy()}bind(){this.context.bindElementBuffer.set(this.buffer)}updateData(N){this.id=Au.uniqueIdxCounter,Au.uniqueIdxCounter++;const T=this.context.gl;this.context.unbindVAO(),this.bind(),T.bufferSubData(T.ELEMENT_ARRAY_BUFFER,0,N.arrayBuffer)}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer)}}Au.uniqueIdxCounter=0;const nx={Int8:"BYTE",Uint8:"UNSIGNED_BYTE",Int16:"SHORT",Uint16:"UNSIGNED_SHORT",Int32:"INT",Uint32:"UNSIGNED_INT",Float32:"FLOAT"};class rx{constructor(N,T,z,W,Q,ee){this.length=T.length,this.attributes=z,this.itemSize=T.bytesPerElement,this.dynamicDraw=W,this.instanceCount=ee,this.context=N;const ue=N.gl;this.buffer=ue.createBuffer(),N.bindVertexBuffer.set(this.buffer),ue.bufferData(ue.ARRAY_BUFFER,T.arrayBuffer,this.dynamicDraw?ue.DYNAMIC_DRAW:ue.STATIC_DRAW),this.dynamicDraw||Q||T.destroy()}bind(){this.context.bindVertexBuffer.set(this.buffer)}updateData(N){const T=this.context.gl;this.bind(),T.bufferSubData(T.ARRAY_BUFFER,0,N.arrayBuffer)}enableAttributes(N,T){for(const z of this.attributes){const W=T.getAttributeLocation(N,z.name);W!==-1&&N.enableVertexAttribArray(W)}}setVertexAttribPointers(N,T,z){for(const W of this.attributes){const Q=T.getAttributeLocation(N,W.name);if(Q!==-1){const ee=W.offset+this.itemSize*(z||0);W.type==="Float32"?N.vertexAttribPointer(Q,W.components,N.FLOAT,!1,this.itemSize,ee):N.vertexAttribIPointer(Q,W.components,N[nx[W.type]],this.itemSize,ee)}}}setVertexAttribDivisor(N,T,z){for(let W=0;W0&&N.vertexAttribDivisor(Q,z)}}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer)}}class Rp{constructor(N,T,z,W,Q){this.context=N,this.width=T,this.height=z;const ee=this.framebuffer=N.gl.createFramebuffer();W>0&&(this.colorAttachment0=new lw(N,ee,0)),W>1&&(this.colorAttachment1=new lw(N,ee,1)),Q&&(this.depthAttachmentType=Q,this.depthAttachment=Q==="renderbuffer"?new JN(N,ee):new e5(N,ee))}static createWithTexture(N,T,z,W,Q){const ee=N.gl;if(N.activeTexture.set(ee.TEXTURE1),N.viewport.set([0,0,z,W]),T&&T.width===z&&T.height===W)return ee.bindTexture(ee.TEXTURE_2D,T.colorAttachment0.get()),N.bindFramebuffer.set(T.framebuffer),T;T&&T.destroy();const ue=new o.T(N,{width:z,height:W,data:null},N.extRenderToTextureHalfFloat?N.gl.RGBA16F:N.gl.RGBA8);ue.bind(ee.LINEAR,ee.CLAMP_TO_EDGE);const _e=N.createFramebuffer(z,W,1,null);if(_e.colorAttachment0.set(ue.texture),Q){const Ee=N.createRenderbuffer(ee.DEPTH24_STENCIL8,z,W);N.bindFramebuffer.set(_e.framebuffer),ee.framebufferRenderbuffer(ee.FRAMEBUFFER,ee.DEPTH_STENCIL_ATTACHMENT,ee.RENDERBUFFER,Ee),_e._stencilRbo=Ee}return _e}createColorAttachment(N,T){T===0?this.colorAttachment0=new lw(N,this.framebuffer,0):T===1&&(this.colorAttachment1=new lw(N,this.framebuffer,1))}removeColorAttachment(N,T){const z=this.context.gl;let W;T===0?(W=this.colorAttachment0.get(),this.colorAttachment0=void 0):T===1&&(W=this.colorAttachment1.get(),this.colorAttachment1=void 0),W&&z.deleteTexture(W)}destroy(){const N=this.context.gl;if(this.colorAttachment0){const T=this.colorAttachment0.get();T&&N.deleteTexture(T)}if(this.colorAttachment1){const T=this.colorAttachment1.get();T&&N.deleteTexture(T)}if(this.depthAttachment&&this.depthAttachmentType)if(this.depthAttachmentType==="renderbuffer"){const T=this.depthAttachment.get();T&&N.deleteRenderbuffer(T)}else{const T=this.depthAttachment.get();T&&N.deleteTexture(T)}this._stencilRbo&&(N.deleteRenderbuffer(this._stencilRbo),this._stencilRbo=null),N.deleteFramebuffer(this.framebuffer)}}class wm{constructor(N,T){this.gl=N,this.clearColor=new iw(this),this.clearDepth=new $C(this),this.clearStencil=new Ub(this),this.colorMask=new UL(this),this.depthMask=new $0(this),this.stencilMask=new Wj(this),this.stencilFunc=new ow(this),this.stencilOp=new YS(this),this.stencilTest=new qb(this),this.depthRange=new $b(this),this.depthTest=new Bx(this),this.depthFunc=new Zu(this),this.blend=new V0(this),this.blendFunc=new XN(this),this.blendColor=new VC(this),this.blendEquation=new yg(this),this.cullFace=new ex(this),this.cullFaceSide=new QN(this),this.frontFace=new ZS(this),this.program=new Kj(this),this.activeTexture=new Yj(this),this.viewport=new tx(this),this.bindFramebuffer=new mf(this),this.bindRenderbuffer=new HC(this),this.bindTexture=new Ov(this),this.bindVertexBuffer=new Zj(this),this.bindElementBuffer=new Xj(this),this.bindVertexArrayOES=new XS(this),this.pixelStoreUnpack=new QS(this),this.pixelStoreUnpackPremultiplyAlpha=new JS(this),this.pixelStoreUnpackFlipY=new Qj(this),this.options=T?Object.assign({},T):{},this.options.extTextureFilterAnisotropicForceOff||(this.extTextureFilterAnisotropic=N.getExtension("EXT_texture_filter_anisotropic")||N.getExtension("MOZ_EXT_texture_filter_anisotropic")||N.getExtension("WEBKIT_EXT_texture_filter_anisotropic"),this.extTextureFilterAnisotropic&&(this.extTextureFilterAnisotropicMax=N.getParameter(this.extTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT))),this.extDebugRendererInfo=N.getExtension("WEBGL_debug_renderer_info"),this.extDebugRendererInfo&&(this.renderer=N.getParameter(this.extDebugRendererInfo.UNMASKED_RENDERER_WEBGL),this.vendor=N.getParameter(this.extDebugRendererInfo.UNMASKED_VENDOR_WEBGL)),this.forceManualRenderingForInstanceIDShaders=T&&!!T.forceManualRenderingForInstanceIDShaders||this.renderer&&this.renderer.indexOf("PowerVR")!==-1,this.disableSymbolUBO=T&&!!T.forceDisableSymbolUBO,this.options.extTextureFloatLinearForceOff||(this.extTextureFloatLinear=N.getExtension("OES_texture_float_linear")),this.extRenderToTextureHalfFloat=N.getExtension("EXT_color_buffer_half_float"),this.extTimerQuery=N.getExtension("EXT_disjoint_timer_query_webgl2"),this.maxTextureSize=N.getParameter(N.MAX_TEXTURE_SIZE),this.maxUniformBlockSize=Math.min(N.getParameter(N.MAX_UNIFORM_BLOCK_SIZE),32768),this.maxUniformBufferBindings=N.getParameter(N.MAX_UNIFORM_BUFFER_BINDINGS),this.extBlendFuncExtended=N.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(N,T,z){return new Au(this,N,T,z)}createVertexBuffer(N,T,z,W,Q){return new rx(this,N,T,z,W,Q)}createRenderbuffer(N,T,z){const W=this.gl,Q=W.createRenderbuffer();return this.bindRenderbuffer.set(Q),W.renderbufferStorage(W.RENDERBUFFER,N,T,z),this.bindRenderbuffer.set(null),Q}createFramebuffer(N,T,z,W){return new Rp(this,N,T,z,W)}clear({color:N,depth:T,stencil:z,colorMask:W}){const Q=this.gl;let ee=0;N&&(ee|=Q.COLOR_BUFFER_BIT,this.clearColor.set(N.toNonPremultipliedRenderColor(null)),this.colorMask.set(W||[!0,!0,!0,!0])),T!==void 0&&(ee|=Q.DEPTH_BUFFER_BIT,this.depthRange.set([0,1]),this.clearDepth.set(T),this.depthMask.set(!0)),z!==void 0&&(ee|=Q.STENCIL_BUFFER_BIT,this.clearStencil.set(z),this.stencilMask.set(255)),Q.clear(ee)}setCullFace(N){N.enable===!1?this.cullFace.set(!1):(this.cullFace.set(!0),this.cullFaceSide.set(N.mode),this.frontFace.set(N.frontFace))}setDepthMode(N){N.func!==this.gl.ALWAYS||N.mask?(this.depthTest.set(!0),this.depthFunc.set(N.func),this.depthMask.set(N.mask),this.depthRange.set(N.range)):this.depthTest.set(!1)}setStencilMode(N){N.test.func!==this.gl.ALWAYS||N.mask?(this.stencilTest.set(!0),this.stencilMask.set(N.mask),this.stencilOp.set([N.fail,N.depthFail,N.pass]),this.stencilFunc.set({func:N.test.func,ref:N.ref,mask:N.test.mask})):this.stencilTest.set(!1)}setColorMode(N){o.b6(N.blendFunction,Ba.Replace)?this.blend.set(!1):(this.blend.set(!0),this.blendFunc.set(N.blendFunction),this.blendColor.set(N.blendColor),N.blendEquation?this.blendEquation.set(N.blendEquation):this.blendEquation.setDefault()),this.colorMask.set(N.mask)}unbindVAO(){this.bindVertexArrayOES.set(null)}}let td;function jr(R,N,T,z,W,Q,ee){const ue=R.context,_e=ue.gl,Ee=R.transform,Ie=[o.aH(Ee.center.lng),o.aL(Ee.center.lat)],Je=T.layout.get("symbol-placement"),Ke=T.layout.get("text-variable-anchor"),tt=T.layout.get("icon-rotation-alignment")==="map",ut=T.layout.get("text-rotation-alignment")==="map",lt=Je!=="point",kt=[];let Nt=0,zt=0;for(let Zt=0;Zt0){const Aa=o.bb(),ta=hr;o.cz(Aa,Ks.placementInvProjMatrix,Ee.glCoordMatrix),o.cz(Aa,Aa,Ks.placementViewportMatrix),kt.push({circleArray:Gn,circleOffset:zt,transform:ta,invTransform:Aa,projection:Ks.getProjection()}),Nt+=Gn.length/4,zt=Nt}if(!mr)continue;R.terrain&&R.terrain.setupElevationDraw(bs,Nr);const pa=_n?[ns.canonical.x,ns.canonical.y,1<=0&&(tt[Yt.associatedIconIndex]={x:Es,y:bn,z:mn,angle:yn})}else Wr(cs,Je)}if(Ee){Ke.clear();const zt=R.icon.placedSymbolArray;for(let Yt=0;Yt{let Ri=[0,0,0];if(vl){const Pd=R.style.directionalLight,yc=R.style.ambientLight;Pd&&yc&&(Ri=vm(R.style,Pd,yc))}return Ri},oo=vl=>{if(R.context.disableSymbolUBO)return;vl.push("USE_PAINT_PROPERTIES_UBO");const Ri=Math.floor(R.context.maxUniformBlockSize/4),Pd=Math.floor(Ri/4);vl.push(`MAX_UBO_SIZE_VEC4 ${Pd}u`)},Ni=vl=>{ns.depthOcclusionForSymbolsAndCircles&&(T.hasOcclusionOpacityProperties||R.terrain)&&(vl.push("DEPTH_D24"),vl.push("DEPTH_OCCLUSION"))},al=vl=>{T.lut&&!cs&&(T.lut.texture||(T.lut.texture=new o.dR(R.context,T.lut.image,[T.lut.image.height,T.lut.image.height,T.lut.image.height],Ns.gl.RGBA8)),Ns.activeTexture.set(Ns.gl.TEXTURE0+10),T.lut.texture&&T.lut.texture.bind(Ns.gl.LINEAR,Ns.gl.CLAMP_TO_EDGE),vl.push("APPLY_LUT_ON_GPU"))},gc=()=>{const vl=bs&&T.layout.get("symbol-placement")!=="point",Ri=[];Ni(Ri),al(Ri);const Pd=vl||Ai,yc=Gn.elevationType==="road",Ph=R.shadowRenderer,_o=yc&&Es&&!!Ph&&Ph.enabled,Tc=Qa(_o),jm=yc&&Es&&!R.terrain?sn:Kn,$x=T.paint.get("icon-image-cross-fade");R.terrainRenderModeElevated()&&Es&&Ri.push("PITCH_WITH_MAP_TERRAIN"),pa&&(Ri.push("PROJECTION_GLOBE_VIEW"),Pd&&Ri.push("PROJECTED_POS_ON_VIEWPORT")),$x>0&&Gn.hasAnySecondaryIcon&&Ri.push("ICON_TRANSITION"),!Gn.icon.zOffsetVertexBuffer||yc&&R.terrain||Ri.push("Z_OFFSET"),Nt===0&&zt===0&&Yt===0&&Tt===1||Ri.push("COLOR_ADJUSTMENT"),Gn.sdfIcons&&Ri.push("RENDER_SDF"),_o&&Ri.push("RENDER_SHADOWS","NORMAL_OFFSET"),yc&&Es&&!R.terrain&&Gn.icon.orientationVertexBuffer&&Ri.push("ELEVATED_ROADS"),oo(Ri);const qm=Ns.disableSymbolUBO?Gn.icon.programConfigurations.get(T.id):null,ff=R.getOrCreateProgram("symbol",{config:qm,defines:Ri}),qv=mr.imageAtlasTexture?mr.imageAtlasTexture.size:[0,0],Hl=Gn.iconSizeData,z1=o.bj(Hl,ns.zoom),B1=Es||!ns.isOrthographic,Wc=dc(ta,mr.tileID.canonical,Es,bs,ns,Gn.getProjection(),ua),rd=cf(ta,mr.tileID.canonical,Es,bs,ns,Gn.getProjection(),ua),ac=Gn.icon.uboBinder&&Gn.icon.uboBinder.cachedHeader&&256&Gn.icon.uboBinder.cachedHeader.dataDrivenMask?[0,0]:ue,gh=R.translatePosMatrix(rd,mr,ac,Ee,!0),_g=R.translatePosMatrix(ta,mr,ac,Ee),Tu=Pd?zo:Wc,$v=bs&&!Es&&!vl;let l5=Nr;!_n&&!ns.mercatorFromTransition||bs||(l5=kd(ns));const t3=pa?l5:Nr,s3=T.getColorAdjustmentMatrix(Nt,zt,Yt,Tt),rT=Ah(Hl.kind,z1,$v,Es,R,_g,Tu,gh,Ss,!1,qv,[0,0],0,hr,Aa,Fs,ji,t3,Gn.getProjection(),Tc,io,s3,$x,null),ak=mr.imageAtlasTexture?mr.imageAtlasTexture:null,o2=T.layout.get("icon-size").constantOr(0)!==1||Gn.iconsNeedLinear,aT=Gn.sdfIcons||R.options.rotating||R.options.zooming||o2||B1?Zt.LINEAR:Zt.NEAREST,Ky=Gn.sdfIcons&&T.paint.get("icon-halo-width").constantOr(1)!==0,c5=R.terrain&&Es&&vl?o.b7(o.bb(),Wc):zo;if(vl&&Gn.icon){const d5=o.bu.getAtTileOffsetFunc(hr,ns.center.lat,ns.worldSize,Gn.getProjection()),u5=Nd(ta,mr.tileID.canonical,Es,bs,ns,Gn.getProjection(),ua),Fz=T.layout.get("icon-size-scale-range"),iT=o.aC(R.scaleFactor,Fz[0],Fz[1]);zm(Gn,ta,R,!1,u5,rd,Es,lt,d5,hr,iT)}return{program:ff,buffers:Gn.icon,uniformValues:rT,atlasTexture:ak,atlasTextureIcon:null,atlasInterpolation:aT,atlasInterpolationIcon:null,isSDF:Gn.sdfIcons,hasHalo:Ky,depthMode:jm,tile:mr,renderWithShadows:_o,labelPlaneMatrixInv:c5}},Hd=()=>{const vl=Ks&&T.layout.get("symbol-placement")!=="point",Ri=[],Pd=vl||yn||Ai,yc=Gn.elevationType==="road",Ph=R.shadowRenderer,_o=yc&&bn&&!!Ph&&Ph.enabled,Tc=Qa(_o),jm=yc&&bn&&!R.terrain?sn:Kn;R.terrainRenderModeElevated()&&bn&&Ri.push("PITCH_WITH_MAP_TERRAIN"),pa&&(Ri.push("PROJECTION_GLOBE_VIEW"),Pd&&Ri.push("PROJECTED_POS_ON_VIEWPORT")),!Gn.text.zOffsetVertexBuffer||yc&&R.terrain||Ri.push("Z_OFFSET"),Gn.iconsInText&&Ri.push("RENDER_TEXT_AND_SYMBOL"),Ri.push("RENDER_SDF"),_o&&Ri.push("RENDER_SHADOWS","NORMAL_OFFSET"),yc&&bn&&!R.terrain&&Gn.text.orientationVertexBuffer&&Ri.push("ELEVATED_ROADS"),Ni(Ri),oo(Ri);const $x=Ns.disableSymbolUBO?Gn.text.programConfigurations.get(T.id):null,qm=R.getOrCreateProgram("symbol",{config:$x,defines:Ri});let ff,qv=[0,0],Hl=null;const z1=Gn.textSizeData;Gn.iconsInText&&(qv=mr.imageAtlasTexture?mr.imageAtlasTexture.size:[0,0],Hl=mr.imageAtlasTexture?mr.imageAtlasTexture:null,ff=bn||!ns.isOrthographic||R.options.rotating||R.options.zooming||z1.kind==="composite"||z1.kind==="camera"?Zt.LINEAR:Zt.NEAREST);const B1=mr.glyphAtlasTexture?mr.glyphAtlasTexture.size:[0,0],Wc=T.layout.get("text-size-scale-range"),rd=o.aC(R.scaleFactor,Wc[0],Wc[1]),ac=o.bj(z1,ns.zoom,rd),gh=dc(ta,mr.tileID.canonical,bn,Ks,ns,Gn.getProjection(),ua),_g=cf(ta,mr.tileID.canonical,bn,Ks,ns,Gn.getProjection(),ua),Tu=Gn.text.uboBinder&&Gn.text.uboBinder.cachedHeader&&256&Gn.text.uboBinder.cachedHeader.dataDrivenMask?[0,0]:_e,$v=R.translatePosMatrix(_g,mr,Tu,Ie,!0),l5=R.translatePosMatrix(ta,mr,Tu,Ie),t3=Pd?zo:gh,s3=Ks&&!bn&&!vl;let rT=Nr;!_n&&!ns.mercatorFromTransition||Ks||(rT=kd(ns));const ak=Ah(z1.kind,ac,s3,bn,R,l5,t3,$v,Ss,!0,B1,qv,0,hr,Aa,Fs,ji,pa?rT:Nr,Gn.getProjection(),Tc,io,null,null,rd),o2=mr.glyphAtlasTexture?mr.glyphAtlasTexture:null,aT=Zt.LINEAR,Ky=T.paint.get("text-halo-width").constantOr(1)!==0,c5=R.terrain&&bn&&vl?o.b7(o.bb(),gh):zo;if(vl&&Gn.text){const d5=o.bu.getAtTileOffsetFunc(hr,ns.center.lat,ns.worldSize,Gn.getProjection()),u5=Nd(ta,mr.tileID.canonical,bn,Ks,ns,Gn.getProjection(),ua);zm(Gn,ta,R,!0,u5,_g,bn,kt,d5,hr,rd)}return{program:qm,buffers:Gn.text,uniformValues:ak,atlasTexture:o2,atlasTextureIcon:Hl,atlasInterpolation:aT,atlasInterpolationIcon:ff,isSDF:!0,hasHalo:Ky,depthMode:jm,tile:mr,renderWithShadows:_o,labelPlaneMatrixInv:c5}},Fc=Gn.icon.segments.get().length,yl=Gn.text.segments.get().length,Yi=Fc&&!ee.onlyText?gc():null,Zi=yl&&!ee.onlyIcons?Hd():null,Oc=T.paint.get("icon-opacity").constantOr(1),cu=T.paint.get("text-opacity").constantOr(1);if(mn&&Gn.canOverlap){zn=!0;const vl=Oc&&!ee.onlyText?Gn.icon.segments.get():[],Ri=cu&&!ee.onlyIcons?Gn.text.segments.get():[];for(const Pd of vl)Tn.push({segments:new o.dy([Pd]),sortKey:Pd.sortKey,state:Yi});for(const Pd of Ri)Tn.push({segments:new o.dy([Pd]),sortKey:Pd.sortKey,state:Zi})}else ee.onlyText||Tn.push({segments:Oc?Gn.icon.segments:new o.dy([]),sortKey:0,state:Yi}),ee.onlyIcons||Tn.push({segments:cu?Gn.text.segments:new o.dy([]),sortKey:0,state:Zi})}zn&&Tn.sort((hr,mr)=>hr.sortKey-mr.sortKey);for(const hr of Tn){const mr=hr.state;if(mr)if(R.terrain?R.terrain.setupElevationDraw(mr.tile,mr.program,{useDepthForOcclusion:ns.depthOcclusionForSymbolsAndCircles,labelPlaneMatrixInv:mr.labelPlaneMatrixInv}):R.setupDepthForOcclusion(ns.depthOcclusionForSymbolsAndCircles,mr.program),Ns.activeTexture.set(Zt.TEXTURE0),mr.atlasTexture&&mr.atlasTexture.bind(mr.atlasInterpolation,Zt.CLAMP_TO_EDGE,!0),mr.atlasTextureIcon&&(Ns.activeTexture.set(Zt.TEXTURE1),mr.atlasTextureIcon&&mr.atlasTextureIcon.bind(mr.atlasInterpolationIcon,Zt.CLAMP_TO_EDGE,!0)),mr.renderWithShadows&&R.shadowRenderer.setupShadows(mr.tile.tileID.toUnwrapped(),mr.program,"vector-tile"),R.uploadCommonLightUniforms(R.context,mr.program),mr.hasHalo){const Gn=mr.uniformValues;Gn.u_is_halo=1,qy(mr.buffers,hr.segments,T,R,mr.program,mr.depthMode,W,Q,Gn,2),Gn.u_is_halo=0}else{if(mr.isSDF){const Gn=mr.uniformValues;mr.hasHalo&&(Gn.u_is_halo=1,qy(mr.buffers,hr.segments,T,R,mr.program,mr.depthMode,W,Q,Gn,1)),Gn.u_is_halo=0}qy(mr.buffers,hr.segments,T,R,mr.program,mr.depthMode,W,Q,mr.uniformValues,1)}}}function qy(R,N,T,z,W,Q,ee,ue,_e,Ee){const Ie=z.context,Je=Ie.gl,Ke=[R.dynamicLayoutVertexBuffer,R.opacityVertexBuffer,R.iconTransitioningVertexBuffer,R.globeExtVertexBuffer,R.zOffsetVertexBuffer,R.orientationVertexBuffer];R.featureIdBuffer&&Ke.push(R.featureIdBuffer);const tt=R.uboBinder?null:R.programConfigurations.get(T.id);if(R.uboBinder){R.uboBinder.layer=T;const kt=z.transform.zoom,Nt=z.style.getBrightness?z.style.getBrightness():null,zt=R.uboBinder.getConstantUniformValues(kt,Nt);_e.u_spp_fill_np_color=zt.fill_np_color,_e.u_spp_halo_np_color=zt.halo_np_color,_e.u_spp_opacity=zt.opacity,_e.u_spp_halo_width=zt.halo_width,_e.u_spp_halo_blur=zt.halo_blur,_e.u_spp_emissive_strength=zt.emissive_strength,_e.u_spp_occlusion_opacity=zt.occlusion_opacity,_e.u_spp_z_offset=zt.z_offset;const Yt=T.paint.get(R.uboBinder.isText?"text-translate-anchor":"icon-translate-anchor"),Tt=R.uboBinder.cachedHeader&&256&R.uboBinder.cachedHeader.dataDrivenMask&&Yt==="map"?z.transform.angle:0;_e.u_spp_translate_rotation=[Math.cos(Tt),Math.sin(Tt)]}const{batchIndices:ut,batchSegments:lt}=R.getBatchGrouping(N);for(const kt of ut){const Nt=lt.get(kt);R.uboBinder&&R.uboBinder.bind(Ie,W.program,kt),W.draw(z,Je.TRIANGLES,Q,ee,ue,va.disabled,_e,T.id,R.layoutVertexBuffer,R.indexBuffer,Nt,T.paint,z.transform.zoom,tt,Ke,Ee)}}function Qu(R,N,T,z,W,Q){const ee=T.paint.get("line-width"),ue=T.paint.get("line-emissive-strength").isConstant(),_e=T.paint.get("line-emissive-strength").constantOr(0),Ee=T.paint.get("line-occlusion-opacity"),Ie=T.layout.get("line-elevation-reference"),Je=T.layout.get("line-width-unit")==="meters",Ke=Ie==="sea",tt=!(!R.terrain||!R.terrain.enabled),ut=R.context,lt=ut.gl;if(T.hasElevatedBuckets&&R.transform.projection.name==="globe")return;const kt=T.layout.get("line-cross-slope"),Nt=kt!==void 0,zt=kt<1,Yt=W||R.colorModeForDrapableLayerRenderPass(ue?_e:null),Tt=R.terrain&&R.terrain.renderingToTexture||Q,Ss=Tt?1:o.o.devicePixelRatio,cs=T.paint.get("line-dasharray"),Ns=cs.constantOr(1),Zt=T.layout.get("line-cap"),ns=cs.constantOr(null),bs=Zt.constantOr(null),Ks=T.paint.get("line-pattern"),Es=Ks.constantOr(1),bn=T.paint.get("line-pattern-cross-fade"),mn=Ks.constantOr(null),zn=T.paint.get("line-opacity").constantOr(1);let Kn=!Es&&zn!==1||R.depthOcclusion&&Ee>0&&Ee<1;const sn=T.paint.get("line-gradient"),Fs=Es?"linePattern":"line",yn=o.dU(T);let _n;if(Tt&&R.terrain&&R.terrain.clipOrMaskOverlapStencilType()&&(Kn=!1),Ee!==0&&R.depthOcclusion){const Gn=T.paint._values["line-opacity"];Gn&&Gn.value&&Gn.value.kind==="constant"?_n=Gn.value:o.w(`Occlusion opacity for layer ${T.id} is supported only when line-opacity isn't data-driven.`)}ee.value.kind!=="constant"&&ee.value.isLineProgressConstant===!1&&yn.push("VARIABLE_LINE_WIDTH"),Tt&&(R.emissiveMode!=="dual-source-blending"||ue?R.emissiveMode==="mrt-fallback"&&yn.push("USE_MRT1"):yn.push("DUAL_SOURCE_BLENDING"));const Tn={},Nr=(Gn,pa,Aa,ta,ua,ui)=>{for(const Ai of Gn){const ji=N.getTile(Ai);if(Es&&!ji.patternsLoaded())continue;const io=ji.getBucket(T);if(!io||io.elevationType!=="none"&&!ua||io.elevationType==="none"&&ua)continue;R.prepareDrawTile();const Qa=[...pa],oo=R.shadowRenderer,Ni=io.elevationType==="road"&&!!oo&&oo.enabled;let al=[0,0,0];if(Ni){const _o=R.style.directionalLight,Tc=R.style.ambientLight;_o&&Tc&&(al=vm(R.style,_o,Tc)),Qa.push("RENDER_SHADOWS","NORMAL_OFFSET")}const gc=io.programConfigurations.get(T.id);let Hd=!1;if(mn&&ji.imageAtlas){const _o=o.dV.from(mn),Tc=_o.getPrimary().scaleSelf(Ss).toString(),jm=ji.imageAtlas.patternPositions.get(Tc),$x=_o.getSecondary(),qm=$x?ji.imageAtlas.patternPositions.get($x.scaleSelf(Ss).toString()):null;Hd=!!jm&&!!qm,jm&&gc.setConstantPatternPositions(jm,qm)}bn>0&&(Hd||gc.getPatternTransitionVertexBuffer("line-pattern"))&&Qa.push("LINE_PATTERN_TRANSITION"),io.elevationGroundScaleVertexBuffer&&Qa.push("ELEVATION_GROUND_SCALE");const Fc=R.isTileAffectedByFog(Ai),yl=R.getOrCreateProgram(Fs,{config:gc,defines:Qa,overrideFog:Fc});if(!Es&&ns&&bs&&ji.lineAtlas){const _o=ji.lineAtlas.getDash(ns,bs);_o&&gc.setConstantPatternPositions(_o)}Ni&&oo.setupShadows(ji.tileID.toUnwrapped(),yl,"vector-tile");let[Yi,Zi]=T.paint.get("line-trim-offset");(bs==="round"||bs==="square")&&Yi!==Zi&&(Yi===0&&(Yi-=1),Zi===1&&(Zi+=1));const Oc=Tt?Ai.projMatrix:null,cu=Je?1/io.tileToMeter/o.aA(ji,1,R.transform.zoom):1,vl=Je?1/io.tileToMeter/o.aA(ji,1,Math.floor(R.transform.zoom)):1,Ri=Ns?T.paint._values["line-floorwidth"]:null;let Pd;if(Ri&&Ri.value.kind==="constant"){const _o=io.zoom;_o in Tn||(Tn[_o]=Math.max(.01,T.widthExpression().evaluate({zoom:_o}))),Pd=Ri.value.value;const Tc=Math.floor(R.transform.zoom);Ri.value.value=Tn[_o]*Math.pow(2,Tc-ji.tileID.overscaledZ)}const yc=Es?o.dW(R,ji,T,Oc,Ss,cu,vl,[Yi,Zi],al,bn):o.dX(R,ji,T,Oc,io.lineClipsArray.length,Ss,cu,vl,[Yi,Zi],al);if(sn){const _o=io.gradients[T.id];let Tc=_o.texture;if(T.gradientVersion!==_o.version){let jm=256;if(T.stepInterpolant){const $x=N.getSource().maxzoom,qm=Ai.canonical.z===$x?Math.ceil(1<{_n!=null&&(_n.value=zn*Ee),yl.draw(R,lt.TRIANGLES,Aa,_o,Yt,va.disabled,yc,T.id,io.layoutVertexBuffer,io.indexBuffer,io.segments,T.paint,R.transform.zoom,gc,[io.layoutVertexBuffer2,io.patternVertexBuffer,io.zOffsetVertexBuffer,io.elevationGroundScaleVertexBuffer]),_n!=null&&(_n.value=zn)};if(Kn&&!ua){const _o=R.stencilModeForClipping(Ai).ref;_o===0&&Tt&&ut.clear({stencil:0});const Tc={func:lt.EQUAL,mask:255};yc.u_alpha_discard_threshold=.8,Ph(new qa(Tc,_o,255,lt.KEEP,lt.KEEP,lt.INVERT)),yc.u_alpha_discard_threshold=0,Ph(new qa(Tc,_o,255,lt.KEEP,lt.KEEP,lt.KEEP))}else yc.u_alpha_discard_threshold=Kn&&ua&&ui?.8:0,Ph(ua?ta:R.stencilModeForClipping(Ai));Pd!==void 0&&(Ri.value.value=Pd)}};let hr=R.depthModeForSublayer(0,Hr.ReadOnly);const mr=new Hr(R.depthOcclusion?lt.GREATER:lt.LEQUAL,Hr.ReadOnly,R.depthRangeFor3D);if(T.hasNonElevatedBuckets){const Gn=!Tt&&R.terrain;Ee!==0&&Gn?o.w(`Occlusion opacity for layer ${T.id} is supported on terrain only if the layer has line-z-offset enabled.`):Gn?o.w(`Cannot render non-elevated lines in immediate mode when terrain is enabled. Layer: ${T.id}.`):Nr(z,yn,hr,qa.disabled,!1,!0)}if(T.hasElevatedBuckets){Ie==="hd-road-markup"?tt||(hr=mr,yn.push("ELEVATED_ROADS")):(yn.push("ELEVATED"),hr=mr,Nt&&yn.push(zt?"CROSS_SLOPE_HORIZONTAL":"CROSS_SLOPE_VERTICAL"),Ke&&yn.push("ELEVATION_REFERENCE_SEA"));const Gn=Kn?R.stencilModeFor3D():qa.disabled;R.forceTerrainMode=!0,Nr(z,yn,hr,Gn,!0,!0),Kn&&Nr(z,yn,hr,Gn,!0,!1),R.forceTerrainMode=!1}Kn&&(R.resetStencilClippingMasks(),Tt&&ut.clear({stencil:0})),Ee===0||R.depthOcclusion||Tt||R.layersWithOcclusionOpacity.push(R.currentLayer)}const pf={additive:{clearColor:new o.aq(0,0,0,0),colorMode:Ba.additive,compositeUniformValue:1},multiply:{clearColor:new o.aq(1,1,1,1),colorMode:Ba.multiply,compositeUniformValue:0}};function L1(R,N){const T=1<=ym?1:tt.pitch/ym))),2*ut}(R.transform),Ee=R.transform.getFreeCameraOptions().position,Ie="elevatedStructuresDepthReconstruct",Je=R.getOrCreateProgram(Ie,{defines:["DEPTH_RECONSTRUCTION"]}),Ke=R.getOrCreateProgram(Ie);for(const tt of z){const ut=N.getTile(tt),lt=ut.getBucket(T);if(!lt)continue;const kt=lt.elevatedStructures;if(!kt)continue;const Nt=lt.elevationBufferData.heightRange,zt=L1(tt.toUnwrapped(),Ee),Yt=R.translatePosMatrix(tt.projMatrix,ut,T.paint.get("fill-translate"),T.paint.get("fill-translate-anchor"));let Tt,Ss,cs,Ns;if(W==="initialize"){if(!Nt||Nt.min>=1||kt.depthSegments.segments[0].primitiveLength===0)continue;Tt=Ki(Yt,zt,_e,1,0),Ss=ee,cs=kt.depthSegments,Ns=Je}else if(W==="reset"){if(!Nt||Nt.min>=0||kt.maskSegments.segments[0].primitiveLength===0)continue;Tt=Ki(Yt,zt,0,0,1),Ss=ue,cs=kt.maskSegments,Ns=Je}else if(W==="geometry"){if(kt.depthSegments.segments[0].primitiveLength===0)continue;Tt=Ki(Yt,zt,_e,1,0),Ss=ee,cs=kt.depthSegments,Ns=Ke}Ns.draw(R,Q.TRIANGLES,Ss,qa.disabled,Ba.disabled,va.disabled,Tt,T.id,kt.vertexBuffer,kt.indexBuffer,cs,T.paint,R.transform.zoom)}}function I1(R,N,T,z){const{painter:W,sourceCache:Q,layer:ee,coords:ue,colorMode:_e,elevationType:Ee,terrainEnabled:Ie,pass:Je}=R,Ke=W.context.gl,tt=ee.paint.get("fill-pattern"),ut=ee.paint.get("fill-pattern-cross-fade"),lt=tt.constantOr(null);let kt=Ee;Ee!=="road"||N&&!Ie||(kt="none");const Nt=kt==="road",zt=R.painter.shadowRenderer,Yt=Nt&&!!zt&&zt.enabled,Tt=new Hr(W.context.gl.LEQUAL,Hr.ReadOnly,W.depthRangeFor3D);let Ss=[0,0,0];if(Yt){const ns=W.style.directionalLight,bs=W.style.ambientLight;ns&&bs&&(Ss=vm(W.style,ns,bs))}const cs=tt&&tt.constantOr(1),Ns=W.terrain&&W.terrain.renderingToTexture,Zt=(ns,bs)=>{let Ks,Es,bn,mn,zn;bs?(Ks=cs&&!ee.getPaintProperty("fill-outline-color")?"fillOutlinePattern":"fillOutline",bn=Ke.LINES):(Ks=cs?"fillPattern":"fill",bn=Ke.TRIANGLES);for(const Kn of ue){const sn=Q.getTile(Kn);if(cs&&!sn.patternsLoaded())continue;const Fs=sn.getBucket(ee);if(!Fs)continue;const yn=N?Fs.elevationBufferData:Fs.bufferData;if(yn.isEmpty())continue;W.prepareDrawTile();const _n=yn.programConfigurations.get(ee.id),Tn=W.isTileAffectedByFog(Kn),Nr=[],hr=[];Nt&&(Nr.push("ELEVATED_ROADS"),hr.push(yn.elevatedLayoutVertexBuffer)),Yt&&Nr.push("RENDER_SHADOWS","NORMAL_OFFSET"),Ns&&T&&Nr.push("USE_MRT1"),cs&&(W.context.activeTexture.set(Ke.TEXTURE0),sn.imageAtlasTexture&&sn.imageAtlasTexture.bind(Ke.LINEAR,Ke.CLAMP_TO_EDGE),_n.updatePaintBuffers());let mr=!1;if(lt&&sn.imageAtlas){const ua=sn.imageAtlas,ui=o.dV.from(lt),Ai=ui.getPrimary().scaleSelf(o.o.devicePixelRatio).toString(),ji=ui.getSecondary(),io=ua.patternPositions.get(Ai),Qa=ji?ua.patternPositions.get(ji.scaleSelf(o.o.devicePixelRatio).toString()):null;mr=!!io&&!!Qa,io&&_n.setConstantPatternPositions(io,Qa)}ut>0&&(mr||_n.getPatternTransitionVertexBuffer("fill-pattern"))&&Nr.push("FILL_PATTERN_TRANSITION");const Gn=W.getOrCreateProgram(Ks,{config:_n,overrideFog:Tn,defines:Nr}),pa=W.translatePosMatrix(Kn.projMatrix,sn,ee.paint.get("fill-translate"),ee.paint.get("fill-translate-anchor"));Yt&&zt.setupShadows(sn.tileID.toUnwrapped(),Gn,"vector-tile");const Aa=ee.paint.get("fill-emissive-strength");if(bs){mn=yn.lineIndexBuffer,zn=yn.lineSegments;const ua=W.terrain&&W.terrain.renderingToTexture?W.terrain.drapeBufferSize:[Ke.drawingBufferWidth,Ke.drawingBufferHeight];Es=Ks==="fillOutlinePattern"&&cs?ro(pa,Aa,W,sn,ua,Ss,ut):ba(pa,Aa,ua,Ss)}else mn=yn.indexBuffer,zn=yn.triangleSegments,Es=cs?Sa(pa,Aa,W,sn,Ss,ut):Vr(pa,Aa,Ss);W.uploadCommonUniforms(W.context,Gn,Kn.toUnwrapped());let ta=ns;(Ee==="road"&&!Ie||Ee==="offset")&&(ta=Tt),Gn.draw(W,bn,ta,z||W.stencilModeForClipping(Kn),_e,va.disabled,Es,ee.id,yn.layoutVertexBuffer,mn,zn,ee.paint,W.transform.zoom,_n,hr)}};W.renderPass===Je&&Zt(W.depthModeForSublayer(1,W.renderPass==="opaque"?Hr.ReadWrite:Hr.ReadOnly),!1),kt==="none"&&W.renderPass==="translucent"&&ee.paint.get("fill-antialias")&&Zt(W.depthModeForSublayer(ee.getPaintProperty("fill-outline-color")?2:0,Hr.ReadOnly),!0)}function Fp(R,N,T,z,W,Q,ee,ue){T.resetLayerRenderingStats(R);const _e=R.context,Ee=_e.gl,Ie=R.transform,Je=T.paint.get("fill-extrusion-pattern"),Ke=T.paint.get("fill-extrusion-pattern-cross-fade"),tt=Je.constantOr(null),ut=Je.constantOr(1),lt=T.paint.get("fill-extrusion-opacity"),kt=R.style.enable3dLights(),Nt=T.paint.get(kt&&!ut?"fill-extrusion-ambient-occlusion-wall-radius":"fill-extrusion-ambient-occlusion-radius"),zt=[T.paint.get("fill-extrusion-ambient-occlusion-intensity"),Nt],Yt=T.layout.get("fill-extrusion-edge-radius"),Tt=Yt>0&&!T.paint.get("fill-extrusion-rounded-roof"),Ss=Tt?0:Yt,cs=Ie.projection.name==="globe"?o.e1():0,Ns=Ie.projection.name==="globe",Zt=Ns?o.al(Ie.zoom):0,ns=[o.aH(Ie.center.lng),o.aL(Ie.center.lat)],bs=T.paint.get("fill-extrusion-flood-light-color-use-theme").constantOr("default")==="none",Ks=T.paint.get("fill-extrusion-flood-light-color").toNonPremultipliedRenderColor(bs?null:T.lut).toArray01().slice(0,3),Es=T.paint.get("fill-extrusion-flood-light-intensity"),bn=T.paint.get("fill-extrusion-vertical-scale"),mn=T.paint.get("fill-extrusion-line-width").constantOr(1)!==0,zn=T.paint.get("fill-extrusion-height-alignment"),Kn=T.paint.get("fill-extrusion-base-alignment"),sn=qd(R,T.paint.get("fill-extrusion-cutoff-fade-range")),Fs=T.paint.get("fill-extrusion-front-cutoff"),yn=s2(Ie.pitch,Fs,!!R.terrain),_n=yn[2]<1;_n&&(R.maxFrontCutoffRawStart=Math.max(R.maxFrontCutoffRawStart,Fs[0]));const Tn=[];let Nr;Ns&&Tn.push("PROJECTION_GLOBE_VIEW"),zt[0]>0&&Tn.push("FAUX_AO"),Tt&&Tn.push("ZERO_ROOF_RADIUS"),ue&&Tn.push("HAS_CENTROID"),Es>0&&Tn.push("FLOOD_LIGHT"),sn.shouldRenderCutoff&&Tn.push("RENDER_CUTOFF"),_n&&Tn.push("RENDER_FRONT_CUTOFF"),mn&&Tn.push("RENDER_WALL_MODE");const hr=R.renderPass==="shadow",mr=R.shadowRenderer,Gn=hr&&!!mr,pa=hr?va.disabled:va.backCCW;R.shadowRenderer&&(R.shadowRenderer.useNormalOffset=!0);let Aa=[0,0,0];if(mr){const ui=R.style.directionalLight,Ai=R.style.ambientLight;ui&&Ai&&(Aa=vm(R.style,ui,Ai)),hr||(Tn.push("RENDER_SHADOWS"),mr.useNormalOffset&&Tn.push("NORMAL_OFFSET")),Nr=Tn.concat(["SHADOWS_SINGLE_CASCADE"])}const ta=Gn?"fillExtrusionDepth":ut?"fillExtrusionPattern":"fillExtrusion",ua=T.getLayerRenderingStats();for(const ui of z){const Ai=N.getTile(ui),ji=Ai.getBucket(T);if(!ji||ji.projection.name!==Ie.projection.name)continue;let io=!1;mr&&(io=mr.getMaxCascadeForTile(ui.toUnwrapped())===0);const Qa=R.isTileAffectedByFog(ui),oo=ji.programConfigurations.get(T.id);let Ni=!1;if(tt&&Ai.imageAtlas){const Zi=Ai.imageAtlas,Oc=o.dV.from(tt),cu=Oc.getPrimary().scaleSelf(o.o.devicePixelRatio).toString(),vl=Oc.getSecondary(),Ri=Zi.patternPositions.get(cu),Pd=vl?Zi.patternPositions.get(vl.scaleSelf(o.o.devicePixelRatio).toString()):null;Ni=!!Ri&&!!Pd,Ri&&oo.setConstantPatternPositions(Ri,Pd)}Ke>0&&(Ni||oo.getPatternTransitionVertexBuffer("fill-extrusion-pattern"))&&Tn.push("FILL_EXTRUSION_PATTERN_TRANSITION");const al=R.getOrCreateProgram(ta,{config:oo,defines:io?Nr:Tn,overrideFog:Qa});if(R.terrain&&R.terrain.setupElevationDraw(Ai,al,{useMeterToDem:!0}),!ji.centroidVertexBuffer){const Zi=al.getAttributeLocation(Ee,"a_centroid_pos");Zi!==-1&&Ee.vertexAttribI4ui(Zi,0,0,0,0)}!hr&&mr&&mr.setupShadows(Ai.tileID.toUnwrapped(),al,"vector-tile"),ut&&(R.context.activeTexture.set(Ee.TEXTURE0),Ai.imageAtlasTexture&&Ai.imageAtlasTexture.bind(Ee.LINEAR,Ee.CLAMP_TO_EDGE),oo.updatePaintBuffers());const gc=T.paint.get("fill-extrusion-vertical-gradient"),Hd=1/ji.tileToMeter;let Fc;if(hr&&mr){if(vg(Ai.tileID,ji.maxHeight,R))continue;const Zi=mr.calculateShadowPassMatrixFromTile(Ai.tileID.toUnwrapped());Fc=br(Zi,Ss,Hd,bn,zn,Kn)}else{const Zi=R.translatePosMatrix(ui.expandedProjMatrix,Ai,T.paint.get("fill-extrusion-translate"),T.paint.get("fill-extrusion-translate-anchor")),Oc=Ie.projection.createInversionMatrix(Ie,ui.canonical);Fc=ut?Vn(Zi,R,gc,lt,zt,Ss,Hd,ui,Ai,cs,zn,Kn,Zt,ns,Oc,Ks,bn,Ke):Mr(Zi,R,gc,lt,zt,Ss,Hd,ui,cs,zn,Kn,Zt,ns,Oc,Ks,bn,Es,Aa,yn)}R.uploadCommonUniforms(_e,al,ui.toUnwrapped(),null,sn);let yl=ji.segments;if(Ie.projection.name==="mercator"&&!hr&&(yl=ji.getVisibleSegments(Ai.tileID,R.terrain,R.transform.getFrustum(0)),!yl.get().length))continue;if(ua)if(hr)for(const Zi of yl.get())ua.numRenderedVerticesInShadowPass+=Zi.primitiveLength;else for(const Zi of yl.get())ua.numRenderedVerticesInTransparentPass+=Zi.primitiveLength;const Yi=[];(R.terrain||ue)&&Yi.push(ji.centroidVertexBuffer),Ns&&Yi.push(ji.layoutVertexExtBuffer),mn&&Yi.push(ji.wallVertexBuffer),al.draw(R,_e.gl.TRIANGLES,W,Q,ee,pa,Fc,T.id,ji.layoutVertexBuffer,ji.indexBuffer,yl,T.paint,R.transform.zoom,oo,Yi)}R.shadowRenderer&&(R.shadowRenderer.useNormalOffset=!1)}class ax{constructor(){this.translate=[0,0],this.translateAnchor="map",this.edgeRadius=0,this.cutoffFadeRange=0}}function s2(R,N,T){if(!(N[2]<1)||T)return[0,0,1];const z=180*R/Math.PI;if(z<15)return[-.5,N[1],N[2]];const W=Math.min(1,Math.max(0,(z-15)/5)),Q=W*W*(3-2*W);return[-.5*(1-Q)+N[0]*Q,N[1],N[2]]}function H0(R,N,T,z,W,Q,ee,ue,_e,Ee,Ie,Je,Ke,tt,ut,lt,kt,Nt,zt,Yt,Tt){const Ss=N.context,cs=Ss.gl,Ns=N.transform,Zt=N.transform.zoom,ns=[],bs=R.translate,Ks=R.translateAnchor,Es=R.edgeRadius,bn=qd(N,R.cutoffFadeRange);Ie==="clear"?(ns.push("CLEAR_SUBPASS"),Yt&&(ns.push("CLEAR_FROM_TEXTURE"),Ss.activeTexture.set(cs.TEXTURE0),Yt.bind(cs.LINEAR,cs.CLAMP_TO_EDGE))):Ie==="sdf"?ns.push("SDF_SUBPASS"):Ie==="emissive"&&(ns.push("USE_MRT1"),Ss.activeTexture.set(cs.TEXTURE0),Yt.bind(cs.LINEAR,cs.CLAMP_TO_EDGE)),Nt&&ns.push("HAS_CENTROID"),bn.shouldRenderCutoff&&ns.push("RENDER_CUTOFF");const mn=(zn,Kn,sn,Fs,yn)=>{let _n=ns;Kn.groundRadiusBuffer!=null&&(_n=ns.concat("HAS_ATTRIBUTE_a_flood_light_ground_radius"));const Tn=Kn.programConfigurations.get(z.id),Nr=N.isTileAffectedByFog(zn),hr=N.getOrCreateProgram("fillExtrusionGroundEffect",{config:Tn,defines:_n,overrideFog:Nr}),mr=((pa,Aa,ta,ua,ui,Ai,ji,io,Qa,oo,Ni)=>({u_matrix:Aa,u_opacity:ta,u_ao_pass:ua?1:0,u_meter_to_tile:ui,u_ao:Ai,u_flood_light_intensity:ji,u_flood_light_color:io,u_attenuation:Qa,u_edge_radius:oo,u_fb:0,u_fb_size:Ni,u_dynamic_offset:1}))(0,Fs,Je,Ee,yn,[Ke,tt*yn],ut,lt,kt,Zt>=17?0:Es*yn,Yt?Yt.size[0]:0),Gn=[];Nt&&Gn.push(Kn.hiddenByLandmarkVertexBuffer),Kn.groundRadiusBuffer!=null&&Gn.push(Kn.groundRadiusBuffer),N.uploadCommonUniforms(Ss,hr,zn.toUnwrapped(),null,bn),hr.draw(N,Ss.gl.TRIANGLES,Q,ee,ue,_e,mr,z.id,Kn.vertexBuffer,Kn.indexBuffer,sn,z.paint,Zt,Tn,Gn)};for(const zn of W){const Kn=T.getTile(zn),sn=Kn.getBucket(z);if(!sn||sn.projection.name!==Ns.projection.name||!sn.groundEffect||sn.groundEffect&&!sn.groundEffect.hasData())continue;const Fs=sn.groundEffect,yn=1/sn.tileToMeter;{const _n=N.translatePosMatrix(zn.projMatrix,Kn,bs,Ks),Tn=Fs.getDefaultSegment();mn(zn,Fs,Tn,_n,yn)}if(zt)for(let _n=0;_n<4;_n++){const Tn=o.d$[_n](zn),Nr=T.getTile(Tn);if(!Nr)continue;const hr=Nr.getBucket(z);if(!hr||hr.projection.name!==Ns.projection.name||!hr.groundEffect||hr.groundEffect&&!hr.groundEffect.hasData())continue;const mr=hr.groundEffect;let Gn,pa;_n===0?(Gn=[-o.an,0,0],pa=1):_n===1?(Gn=[o.an,0,0],pa=0):_n===2?(Gn=[0,-o.an,0],pa=3):(Gn=[0,o.an,0],pa=2);const Aa=mr.regionSegments[pa];if(!Aa)continue;const ta=new Float32Array(16);o.bx(ta,zn.projMatrix,Gn),mn(zn,mr,Aa,N.translatePosMatrix(ta,Kn,bs,Ks),yn)}}}function $y(R,N,T,z,W,Q,ee){z.centroidVertexArray.length===0&&z.createCentroidsBuffer();const ue=Q?Q.findDEMTileFor(T):null;if(!(ue&&ue.dem||ee))return;Q&&ue&&ue.dem&&z.selfDEMTileTimestamp!==ue.dem._timestamp&&(z.borderDoneWithNeighborZ=[-1,-1,-1,-1],z.selfDEMTileTimestamp=ue.dem._timestamp);const _e=(Nt,zt)=>{(Nt.flags|zt.flags)&o.e3?(Nt.flags|=o.e3,zt.flags|=o.e3):(Nt.flags&=~o.e3,zt.flags&=~o.e3)},Ee=Nt=>new o.P(Math.ceil((Nt+o.e4)*o.e5),0),Ie=(Nt,zt,Yt)=>{const Tt=Math.ceil((Nt+o.e4)*o.e5),Ss=Math.floor(Math.max(0,Math.min(o.an-1,Yt))/4);return new o.P(Tt,Ss<<5|(3&zt)<<3|7)},Je=Nt=>{const zt=N.getSource().minzoom,Yt=Ss=>{const cs=N.getTileByID(Ss);if(cs&&cs.hasData())return cs.getBucket(W)},Tt=[0,-1,1];for(const Ss of Tt){if(Nt.overscaledZ+Ss(Ke[0]=Math.min(Nt.min.y,zt.min.y),Ke[1]=Math.max(Nt.max.y,zt.max.y),Ke[2]=o.an-zt.min.x>Nt.max.x?zt.min.x-o.an:Nt.max.x,Ke),ut=(Nt,zt)=>(Ke[0]=Math.min(Nt.min.x,zt.min.x),Ke[1]=Math.max(Nt.max.x,zt.max.x),Ke[2]=o.an-zt.min.y>Nt.max.y?zt.min.y-o.an:Nt.max.y,Ke),lt=[(Nt,zt)=>tt(Nt,zt),(Nt,zt)=>tt(zt,Nt),(Nt,zt)=>ut(Nt,zt),(Nt,zt)=>ut(zt,Nt)],kt=(Nt,zt,Yt,Tt,Ss,cs,Ns)=>{if(!Q)return 0;const Zt=[[cs?Yt:Nt,cs?Nt:Yt,0],[cs?Yt:zt,cs?zt:Yt,0]],ns=Ns<0?o.an+Ns:Ns,bs=[cs?ns:(Nt+zt)/2,cs?(Nt+zt)/2:ns,0];return Yt===0&&Ns<0||Yt!==0&&Ns>0?Q.getForTilePoints(Ss,[bs],!0,Tt):Zt.push(bs),Q.getForTilePoints(T,Zt,!0,ue),Math.max(Zt[0][2],Zt[1][2],bs[2])/Q.exaggeration()};for(let Nt=0;Nt<4;Nt++){const zt=z.borderFeatureIndices[Nt];if(zt.length===0)continue;const Yt=o.d$[Nt](T),Tt=Je(Yt);if(!(Tt&&Tt instanceof o.e0))continue;const Ss=Q?Q.findDEMTileFor(Yt):null;if(!(Ss&&Ss.dem||ee)||(Q&&Ss&&Ss.dem&&z.borderDEMTileTimestamp[Nt]!==Ss.dem._timestamp&&(z.borderDoneWithNeighborZ[Nt]=-1,z.borderDEMTileTimestamp[Nt]=Ss.dem._timestamp),z.borderDoneWithNeighborZ[Nt]===Tt.canonical.z))continue;Tt.centroidVertexArray.length===0&&Tt.createCentroidsBuffer();const cs=(Nt<2?1:5)-Nt,Ns=Tt.borderDoneWithNeighborZ[cs]!==z.canonical.z,Zt=Tt.borderFeatureIndices[cs];let ns=0;if(z.canonical.z!==Tt.canonical.z){for(const bn of zt)z.showCentroid(z.featuresOnBorder[bn]);if(Ns)for(const bn of Zt)Tt.showCentroid(Tt.featuresOnBorder[bn]);z.borderDoneWithNeighborZ[Nt]=Tt.canonical.z,Tt.borderDoneWithNeighborZ[cs]=z.canonical.z;continue}const bs=new Map,Ks=new Set,Es=new Set;for(let bn=0;bn1||sn.intersectsCount()>1;{let hr=0;if(Ss&&Ss.dem&&!Nr){const mr=lt[Nt](zn,Fs),Gn=Nt%2?o.an-1:0;hr=kt(mr[0],Math.min(o.an-1,mr[1]),Gn,Ss,Yt,Nt<2,mr[2])}zn.centroidXY=Ie(hr,Nt,Tn),Fs.centroidXY=Ie(hr,cs,Tn)}if(z.writeCentroidToBuffer(zn),Tt.writeCentroidToBuffer(Fs),mn.buildingId!==void 0){for(const hr of z.centroidData)hr.buildingId===mn.buildingId&&hr!==zn&&(hr.centroidXY=zn.centroidXY,z.writeCentroidToBuffer(hr));for(const hr of Tt.centroidData)hr.buildingId===mn.buildingId&&hr!==Fs&&(hr.centroidXY=Fs.centroidXY,Tt.writeCentroidToBuffer(hr))}}for(const bn of zt){if(Ks.has(bn))continue;const mn=z.featuresOnBorder[bn],zn=z.centroidData[mn.centroidDataIndex],Kn=mn.borders[Nt];let sn;for(;nsKn[0]+3||Fs[0]>Kn[0]-3)break;Tt.showCentroid(sn),ns++}if(sn&&nsKn[1]-3||(yn++,++ns===Zt.length))break;sn=Tt.featuresOnBorder[Zt[ns]]}for(;Fs=Zt.length){z.showCentroid(mn);continue}sn=Tt.featuresOnBorder[Zt[Fs]];let _n=!1;if(yn>=1){const hr=sn.borders[cs];Math.abs(Kn[0]-hr[0])<3&&Math.abs(Kn[1]-hr[1])<3&&(yn=1,_n=!0,ns=Fs+1)}else if(yn===0){z.showCentroid(mn);continue}const Tn=Tt.centroidData[sn.centroidDataIndex];ee&&_n&&_e(zn,Tn);const Nr=mn.intersectsCount()>1||sn.intersectsCount()>1;if(yn>1)ns=Fs,zn.centroidXY=Tn.centroidXY=new o.P(0,0);else if(Ss&&Ss.dem&&!Nr){const hr=lt[Nt](zn,Tn),mr=Nt%2?o.an-1:0,Gn=kt(hr[0],Math.min(o.an-1,hr[1]),mr,Ss,Yt,Nt<2,hr[2]);zn.centroidXY=Tn.centroidXY=Ee(Gn)}else Nr?zn.centroidXY=Tn.centroidXY=new o.P(0,0):(zn.centroidXY=z.encodeBorderCentroid(mn),Tn.centroidXY=Tt.encodeBorderCentroid(sn));z.writeCentroidToBuffer(zn),Tt.writeCentroidToBuffer(Tn)}else z.showCentroid(mn)}z.borderDoneWithNeighborZ[Nt]=Tt.canonical.z,Tt.borderDoneWithNeighborZ[cs]=z.canonical.z}(z.needsCentroidUpdate||!z.centroidVertexBuffer&&z.centroidVertexArray.length!==0)&&z.uploadCentroid(R)}const Bv=[1,0,0],n2=[0,1,0],r2=[0,0,1];function vg(R,N,T){const z=T.transform,W=T.shadowRenderer;if(!W)return!0;const Q=R.toUnwrapped(),ee=z.tileSize*W._cascades[T.currentShadowCascade].scale;let ue=N;if(z.elevation){const ut=z.elevation.getMinMaxForTile(R);ut&&(ue+=ut.max)}const _e=z.scaleZoom(ee);ue/=o.e2(z.center.lat,_e);const Ee=[...W.shadowDirection];Ee[2]=-Ee[2];const Ie=W.computeSimplifiedTileShadowVolume(Q,ue,ee,Ee);if(!Ie)return!1;const Je=[Bv,n2,r2,Ee,[Ee[0],0,Ee[2]],[0,Ee[1],Ee[2]]],Ke=o.cl.fromInvProjectionMatrix(z.invProjMatrix,z.worldSize,_e,z.projection.name!=="globe"),tt=W.getCurrentCascadeFrustum();return Ke.intersectsPrecise(Ie.vertices,Ie.planes,Je)===0||tt.intersectsPrecise(Ie.vertices,Ie.planes,Je)===0}function Uv(R){const{painter:N,source:T,layer:z,coords:W}=R;let Q=R.defines;const ee=N.context,ue=N.renderPass==="shadow",_e=N.renderPass==="light-beam",Ee=N.shadowRenderer,Ie=o.e2(N.transform.center.lat,N.transform.zoom),Je=qd(N,z.paint.get("building-cutoff-fade-range"));Je.shouldRenderCutoff&&(Q=Q.concat("RENDER_CUTOFF"));const Ke=z.paint.get("building-front-cutoff"),tt=Ke[2]<1&&!N.terrain,ut=s2(N.transform.pitch,Ke,!!N.terrain);tt&&(Q=Q.concat("RENDER_FRONT_CUTOFF"),N.maxFrontCutoffRawStart=Math.max(N.maxFrontCutoffRawStart,Ke[0])),R.floodLightIntensity>0&&(Q=Q.concat("FLOOD_LIGHT"));for(const lt of W){const kt=T.getTile(lt),Nt=kt.getBucket(z);if(!Nt)continue;Ee&&Ee.getMaxCascadeForTile(lt.toUnwrapped())===0&&(Q=Q.concat("SHADOWS_SINGLE_CASCADE"));const zt=Nt.programConfigurations.get(z.id);let Yt,Tt,Ss,cs=N.translatePosMatrix(lt.expandedProjMatrix,kt,[0,0],"map");if(cs=o.cC(o.bb(),cs,[1,1,R.verticalScale]),ue&&Ee){if(vg(kt.tileID,Nt.maxHeight*Ie,N))continue;let Zt=Ee.calculateShadowPassMatrixFromTile(kt.tileID.toUnwrapped());Zt=o.cC(o.bb(),Zt,[1,1,R.verticalScale]),Ss=Qi(Zt),Yt=Tt=N.getOrCreateProgram("buildingDepth",{config:zt,defines:Q,overrideFog:!1})}else if(_e)Yt=Tt=N.getOrCreateProgram("buildingBloom",{config:zt,defines:Q,overrideFog:!1}),Ss=El(cs);else{const Zt=N.transform.calculatePosMatrix(lt.toUnwrapped(),N.transform.worldSize);o.cC(Zt,Zt,[1,1,R.verticalScale]);const ns=o.bb();o.cC(ns,Zt,[1,-1,1/Ie]),o.b7(ns,ns),o.e6(ns,ns);const bs=N.transform.getFreeCameraOptions().position,Ks=1<{if(_e){const bs=Zt.entranceBloom;ns.draw(N,ee.gl.TRIANGLES,R.depthMode,qa.disabled,R.blendMode,va.disabled,Ss,z.id,bs.layoutVertexBuffer,bs.indexBuffer,bs.segmentsBucket,z.paint,N.transform.zoom,zt,[bs.layoutAttenuationBuffer,bs.layoutColorBuffer])}else{const bs=Zt.segmentsBucket;let Ks=[Zt.layoutNormalBuffer,Zt.layoutCentroidBuffer,Zt.layoutColorBuffer,Zt.layoutFloodLightDataBuffer];Zt.layoutFacadePaintBuffer&&(Ks=Ks.concat([Zt.layoutFacadeDataBuffer,Zt.layoutFacadeVerticalRangeBuffer,Zt.layoutFacadePaintBuffer])),ns.draw(N,ee.gl.TRIANGLES,R.depthMode,qa.disabled,R.blendMode,ue?va.disabled:va.backCW,Ss,z.id,Zt.layoutVertexBuffer,Zt.indexBuffer,bs,z.paint,N.transform.zoom,zt,Ks)}};N.uploadCommonUniforms(ee,Tt,lt.toUnwrapped(),null,Je),Nt.buildingWithoutFacade&&Ns(Nt.buildingWithoutFacade,Tt),Nt.buildingWithFacade&&(Yt!==Tt&&N.uploadCommonUniforms(ee,Yt,lt.toUnwrapped(),null,Je),Ns(Nt.buildingWithFacade,Yt))}}function bg(R,N,T,z,W,Q,ee,ue,_e,Ee,Ie,Je,Ke,tt){const ut=R.context.gl,lt=R.depthModeForSublayer(1,Hr.ReadOnly,ut.LEQUAL,!0),kt=.1*(1-(Nt=Ie))+3*Nt;var Nt;const zt=R._showOverdrawInspector,Yt=Je,Tt=new ax;zt||H0(Tt,R,N,T,z,lt,new qa({func:ut.ALWAYS,mask:255},255,255,ut.KEEP,ut.KEEP,ut.REPLACE),new Ba([ut.ONE,ut.ONE,ut.ONE,ut.ONE],o.aq.transparent,[!1,!1,!1,!0],ut.MIN),va.disabled,W,"sdf",Q,ee,ue,_e,Ee,kt,Yt,!1,void 0);{const Ss=zt?qa.disabled:new qa({func:ut.EQUAL,mask:255},255,255,ut.KEEP,ut.DECR,ut.DECR),cs=zt?R.colorModeForRenderPass():new Ba([ut.ONE_MINUS_DST_ALPHA,ut.DST_ALPHA,ut.ONE,ut.ONE],o.aq.transparent,[!0,!0,!0,!0]);H0(Tt,R,N,T,z,lt,Ss,cs,va.disabled,W,"color",Q,ee,ue,_e,Ee,kt,Yt,!1,void 0)}}function uw(R){return[R[0]*o.e7,R[1]*o.e7,R[2]*o.e7,0]}function Hb(R,N,T,z,W,Q,ee,ue,_e){const Ee=z.getSource(),Ie=T.globeSharedBuffers;if(!Ie)return;let Je,Ke,tt;if(N&&(Je=z.getTile(N)),Ee instanceof o.aV?(Ke=Ee.texture,tt=o.dw(0,0,T.transform)):Je&&N&&(Ke=Je.texture,tt=o.dw(N.canonical.z,N.canonical.x,T.transform)),!Ke||!tt)return;R||(tt=o.cC(o.bb(),tt,[1,-1,1]));const ut=T.context,lt=ut.gl,kt=W.paint.get("raster-resampling")==="nearest"?lt.NEAREST:lt.LINEAR,Nt=T.colorModeForDrapableLayerRenderPass(Q),zt=ee.defines;zt.push("GLOBE_POLES");const Yt=new Hr(lt.LEQUAL,Hr.ReadWrite,T.depthRangeFor3D),Tt=Float32Array.from(T.transform.expandedFarZProjMatrix),Ss=Float32Array.from(o.du(o.dv(new o.cn(0,0,0))));T.terrain&&T.terrain.prepareDrawTile(),ut.activeTexture.set(lt.TEXTURE0),Ke.bind(kt,lt.CLAMP_TO_EDGE),ut.activeTexture.set(lt.TEXTURE1),Ke.bind(kt,lt.CLAMP_TO_EDGE),"useMipmap"in Ke&&ut.extTextureFilterAnisotropic&&T.transform.pitch>20&<.texParameterf(lt.TEXTURE_2D,ut.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,ut.extTextureFilterAnisotropicMax);const[cs,Ns,Zt,ns]=N?Ie.getPoleBuffers(N.canonical.z,!1):Ie.getPoleBuffers(0,!0),bs=W.paint.get("raster-elevation");let Ks;R?(Ks=cs,T.renderDefaultNorthPole=bs!==0):(Ks=Ns,T.renderDefaultSouthPole=bs!==0);const Es=uw(ee.mix),bn=((zn,Kn,sn,Fs,yn,_n,Tn,Nr,hr,mr,Gn,pa,Aa,ta)=>Vu(zn,Kn,sn,Fs,new Float32Array(16),new Float32Array(9),[0,0],yn,[0,0],[0,0,0,0],1,{opacity:1,mix:0},Tn,[0,0],hr,2,Gn,pa,Aa,1,0,ta))(T,Tt,Ss,tt,o.al(T.transform.zoom),0,W,0,bs,0,Es,ee.offset,ee.range,Q),mn=T.getOrCreateProgram("raster",{defines:zt});T.uploadCommonUniforms(ut,mn,null),mn.draw(T,lt.TRIANGLES,Yt,_e,Nt,ue,bn,W.id,Ks,Zt,ns)}function Gb(R){if(R.isOrthographic)return[0,0,0,0];const N=R._nearZ,T=R.projection.farthestPixelDistance(R),z=T-N,W=.2*R.height,Q=N+W;return[N,T,(Q-W-N)/z,(Q-N)/z]}function a2(R,N,T,z){if(R)return N instanceof no&&R instanceof fg?N.getTextureDescriptor(R,T,!0):{texture:R.texture,mix:uw(z.mix),offset:z.offset,buffer:0,tileSize:1}}var Wb=o.e8([{name:"a_index",type:"Int16",components:1}]);class xh{constructor(N,T,z,W){const Q={width:z[0],height:z[1],data:null},ee=N.gl;this.targetColorTexture=new o.T(N,Q,ee.RGBA8,{useMipmap:!1}),this.backgroundColorTexture=new o.T(N,Q,ee.RGBA8,{useMipmap:!1}),this.context=N,this.updateParticleTexture(T,W),this.lastInvalidatedAt=0}updateParticleTexture(N,T){if(this.particleTextureDimension===T.width)return;(this.particleTexture0||this.particleTexture1||this.particleIndexBuffer||this.particleSegment)&&(this.particleTexture0.destroy(),this.particleTexture1.destroy(),this.particleIndexBuffer.destroy(),this.particleSegment.destroy());const z=this.context.gl,W=T.width*T.height;this.particleTexture0=new o.T(this.context,T,z.RGBA8,{premultiply:!1,useMipmap:!1}),this.particleTexture1=new o.T(this.context,T,z.RGBA8,{premultiply:!1,useMipmap:!1});const Q=new o.e9;Q.reserve(W);for(let ee=0;ee0){const Es=o.ec(T.canonical,_e),bn=o.ed(Es);Ke=o.aD(new Float32Array(16),_e.globeMatrix,bn),o.aD(Ke,_e.projMatrix,Ke)}const tt=o.bb();tt[12]+=2*W/(o.o.devicePixelRatio*_e.width),tt[13]+=2*Q/(o.o.devicePixelRatio*_e.height),o.aD(Ke,tt,Ke);const ut=R.getOrCreateProgram("debug",{defines:Je}),lt=N.getTileByID(T.key);R.terrain&&R.terrain.setupElevationDraw(lt,ut);const kt=Hr.disabled,Nt=qa.disabled,zt=R.colorModeForRenderPass(),Yt="$debug";ue.activeTexture.set(Ee.TEXTURE0),R.emptyTexture.bind(Ee.LINEAR,Ee.CLAMP_TO_EDGE),Ie?lt._makeGlobeTileDebugBuffers(R.context,_e):lt._makeDebugTileBoundsBuffers(R.context,_e.projection);const Tt=lt._tileDebugBuffer||R.debugBuffer,Ss=lt._tileDebugIndexBuffer||R.debugIndexBuffer,cs=lt._tileDebugSegments||R.debugSegments;if(ut.draw(R,Ee.LINE_STRIP,kt,Nt,zt,va.disabled,Ao(Ke,z.toPremultipliedRenderColor(null)),Yt,Tt,Ss,cs,null,null,null,[lt._globeTileDebugBorderBuffer]),ee){const Es=lt.latestRawTileData,bn=Math.floor((Es&&Es.byteLength||0)/1024);let mn=T.canonical.toString();T.overscaledZ!==T.canonical.z&&(mn+=` => ${T.overscaledZ}`),mn+=` ${lt.state}`,mn+=` ${bn}kb`,function(zn,Kn){zn.initDebugOverlayCanvas();const sn=zn.debugOverlayCanvas,Fs=zn.context.gl,yn=zn.debugOverlayCanvas.getContext("2d");yn.clearRect(0,0,sn.width,sn.height),yn.shadowColor="white",yn.shadowBlur=2,yn.lineWidth=1.5,yn.strokeStyle="white",yn.textBaseline="top",yn.font="bold 36px Open Sans, sans-serif",yn.fillText(Kn,5,5),yn.strokeText(Kn,5,5),zn.debugOverlayTexture.update(sn),zn.debugOverlayTexture.bind(Fs.LINEAR,Fs.CLAMP_TO_EDGE)}(R,mn)}const Ns=N.getTile(T).tileSize,Zt=512/Math.min(Ns,512)*(T.overscaledZ/_e.zoom)*.5,ns=lt._tileDebugTextBuffer||R.debugBuffer,bs=lt._tileDebugTextIndexBuffer||R.quadTriangleIndexBuffer,Ks=lt._tileDebugTextSegments||R.debugSegments;ut.draw(R,Ee.TRIANGLES,kt,Nt,Ba.alphaBlended,va.disabled,Ao(Ke,o.aq.transparent.toPremultipliedRenderColor(null),Zt),Yt,ns,bs,Ks,null,null,null,[lt._globeTileDebugTextBuffer])}function KC(R,N,T,z){G0(R,0,N+T/2,R.transform.width,T,z)}function F1(R,N,T,z){G0(R,N-T/2,0,T,R.transform.height,z)}function G0(R,N,T,z,W,Q){const ee=R.context,ue=ee.gl;ue.enable(ue.SCISSOR_TEST),ue.scissor(N*o.o.devicePixelRatio,T*o.o.devicePixelRatio,z*o.o.devicePixelRatio,W*o.o.devicePixelRatio),ee.clear({color:Q}),ue.disable(ue.SCISSOR_TEST)}const ek=o.e8([{name:"a_pos_3f",components:3,type:"Float32"}]),{members:Th}=ek;function hp(R,N,T,z){R.emplaceBack(N,T,z)}class Eu{constructor(N){this.vertexArray=new o.ee,this.indices=new o.dC,hp(this.vertexArray,-1,-1,1),hp(this.vertexArray,1,-1,1),hp(this.vertexArray,-1,1,1),hp(this.vertexArray,1,1,1),hp(this.vertexArray,-1,-1,-1),hp(this.vertexArray,1,-1,-1),hp(this.vertexArray,-1,1,-1),hp(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=N.createVertexBuffer(this.vertexArray,Th),this.indexBuffer=N.createIndexBuffer(this.indices),this.segment=o.dy.simpleSegment(0,0,36,12)}}function ox(R,N,T,z,W,Q){const ee=R.context.gl,ue=N.paint.get("sky-atmosphere-color"),_e=N.paint.get("sky-atmosphere-halo-color"),Ee=N.paint.get("sky-atmosphere-sun-intensity"),Ie=((Je,Ke,tt,ut,lt)=>({u_matrix_3f:Je,u_sun_direction:Ke,u_sun_intensity:tt,u_color_tint_r:[ut.r,ut.g,ut.b,ut.a],u_color_tint_m:[lt.r,lt.g,lt.b,lt.a],u_luminance:5e-5}))(o.eg(o.dE(),z),W,Ee,ue.toPremultipliedRenderColor(null),_e.toPremultipliedRenderColor(null));ee.framebufferTexture2D(ee.FRAMEBUFFER,ee.COLOR_ATTACHMENT0,ee.TEXTURE_CUBE_MAP_POSITIVE_X+Q,N.skyboxTexture,0),T.draw(R,ee.TRIANGLES,Hr.disabled,qa.disabled,Ba.unblended,va.frontCW,Ie,"skyboxCapture",N.skyboxGeometry.vertexBuffer,N.skyboxGeometry.indexBuffer,N.skyboxGeometry.segment)}const s5=o.e8([{type:"Float32",name:"a_pos",components:3},{type:"Float32",name:"a_uv",components:2}]);class tk{constructor(N){const T=new o.eh;T.emplaceBack(-1,1,1,0,0),T.emplaceBack(1,1,1,1,0),T.emplaceBack(1,-1,1,1,1),T.emplaceBack(-1,-1,1,0,1);const z=new o.dC;z.emplaceBack(0,1,2),z.emplaceBack(2,3,0),this.vertexBuffer=N.createVertexBuffer(T,s5.members),this.indexBuffer=N.createIndexBuffer(z),this.segments=o.dy.simpleSegment(0,0,4,2)}destroy(){this.vertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy()}}const n5=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 Hy{constructor(){this.starsCount=16e3,this.sizeMultiplier=.15,this.sizeRange=100,this.intensityRange=200}}class r5{constructor(N){this.colorModeAlphaBlendedWriteRGB=new Ba([1,sc,1,sc],o.aq.transparent,[!0,!0,!0,!1]),this.colorModeWriteAlpha=new Ba([1,0,1,0],o.aq.transparent,[!1,!1,!1,!0]),this.params=new Hy,this.updateNeeded=!0}update(N){const T=N.context;if(!this.atmosphereBuffer||this.updateNeeded){this.updateNeeded=!1,this.atmosphereBuffer=new tk(T);const z=this.params.sizeRange,W=this.params.intensityRange,Q=function(Ie){const Je=o.em(30),Ke=[];for(let tt=0;tt{const Zt=Q.projection.name==="globe"?["PROJECTION_GLOBE_VIEW","FOG"]:["FOG"];Ns&&Zt.push("ALPHA_PASS");const ns=N.getOrCreateProgram("globeAtmosphere",{defines:Zt}),bs=((Es,bn,mn,zn,Kn,sn,Fs,yn,_n,Tn,Nr,hr)=>({u_frustum_tl:Es,u_frustum_tr:bn,u_frustum_br:mn,u_frustum_bl:zn,u_horizon:Kn,u_transition:sn,u_fadeout_range:Fs,u_atmosphere_fog_color:yn.toArray01(),u_high_color:_n.toArray01(),u_space_color:Tn.toArray01(),u_temporal_offset:Nr,u_horizon_angle:hr}))(Q.frustumCorners.TL,Q.frustumCorners.TR,Q.frustumCorners.BR,Q.frustumCorners.BL,Q.frustumCorners.horizon,ue,kt,Ie,Ke,ut,zt,Ss);N.uploadCommonUniforms(z,ns);const Ks=this.atmosphereBuffer;Ks&&ns.draw(N,W.TRIANGLES,ee,qa.disabled,Ns?this.colorModeWriteAlpha:this.colorModeAlphaBlendedWriteRGB,va.backCW,bs,Ns?"atmosphere_glow_alpha":"atmosphere_glow",Ks.vertexBuffer,Ks.indexBuffer,Ks.segments)};cs(!1),cs(!0)}drawStars(N,T){const z=o.aC(T.properties.get("star-intensity"),0,1);if(z===0)return;const W=N.context,Q=W.gl,ee=N.transform,ue=N.getOrCreateProgram("stars"),_e=o.bL([]);o.bN(_e,_e,-ee._pitch),o.bM(_e,_e,-ee.angle),o.bN(_e,_e,o.ap(ee._center.lat)),o.ek(_e,_e,-o.ap(ee._center.lng));const Ee=o.bR(new Float32Array(16),_e),Ie=o.aD([],ee.starsProjMatrix,Ee),Je=o.eg([],Ee),Ke=o.el([],Je),tt=[0,1,0];o.dG(tt,tt,Ke),o.bJ(tt,tt,this.params.sizeMultiplier);const ut=[1,0,0];o.dG(ut,ut,Ke),o.bJ(ut,ut,this.params.sizeMultiplier);const lt=(kt=tt,Nt=ut,zt=z,{u_matrix:Float32Array.from(Ie),u_up:kt,u_right:Nt,u_intensity_multiplier:zt});var kt,Nt,zt;N.uploadCommonUniforms(W,ue),this.starsVx&&this.starsIdx&&ue.draw(N,Q.TRIANGLES,Hr.disabled,qa.disabled,this.colorModeAlphaBlendedWriteRGB,va.disabled,lt,"atmosphere_stars",this.starsVx,this.starsIdx,this.starsSegments)}}class Xg{constructor(){this.visibleTiles=[]}updateBorders(N,T){const z=[],W=[],Q=N._getRenderableCoordinates(!1,!0);for(const _e of Q){const Ee=N.getTile(_e);if(!Ee.hasData())continue;const Ie=Ee.getBucket(T);Ie&&(Ie.isEmpty()||(z.push(_e.key),W.push({bucket:Ie,tileID:_e.canonical})))}let ee=z.length!==this.visibleTiles.length;if(!ee){z.sort();for(let _e=0;_e_e.tileID.z-Ee.tileID.z||_e.tileID.x-Ee.tileID.x||_e.tileID.y-Ee.tileID.y);for(const _e of W){const Ee=new Array,Ie=new Array,Je=_e.bucket;for(const Ke of Je.featuresOnBorder)ue.has(Ke.featureId)?Ie.push(Ke.footprintIndex):(ue.add(Ke.featureId),Ee.push(Ke.footprintIndex));Je.updateFootprintHiddenFlags(Ee,o.en,!1),Je.updateFootprintHiddenFlags(Ie,o.en,!0)}}}function qL(R,N){const T=[...R],z=N.cameraWorldSizeForFog/N.worldSize,W=o.b9([]);return o.cC(W,W,[z,z,1]),o.aD(T,W,T),o.aD(T,N.worldToFogMatrix,T),T}function $i(R,N,T,z,W){const Q=T.material,ee=z.context,{baseColorTexture:ue,metallicRoughnessTexture:_e}=Q.pbrMetallicRoughness,{normalTexture:Ee,occlusionTexture:Ie,emissionTexture:Je}=Q;function Ke(ut,lt,kt){if(ut&&(R.push(lt),ee.activeTexture.set(ee.gl.TEXTURE0+kt),ut.gfxTexture)){const{minFilter:Nt,magFilter:zt,wrapS:Yt,wrapT:Tt}=ut.sampler;ut.gfxTexture.bindExtraParam(Nt,zt,Yt,Tt)}}Ke(ue,"HAS_TEXTURE_u_baseColorTexture",5),Ke(_e,"HAS_TEXTURE_u_metallicRoughnessTexture",6),Ke(Ee,"HAS_TEXTURE_u_normalTexture",7),Ke(Ie,"HAS_TEXTURE_u_occlusionTexture",8),Ke(Je,"HAS_TEXTURE_u_emissionTexture",9),W&&(W.texture||(W.texture=new o.dR(z.context,W.image,[W.image.height,W.image.height,W.image.height],ee.gl.RGBA8)),ee.activeTexture.set(ee.gl.TEXTURE0+10),W.texture&&W.texture.bind(ee.gl.LINEAR,ee.gl.CLAMP_TO_EDGE),R.push("APPLY_LUT_ON_GPU")),T.texcoordBuffer&&(R.push("HAS_ATTRIBUTE_a_uv_2f"),N.push(T.texcoordBuffer)),T.colorBuffer&&(R.push(T.colorBuffer.itemSize===12?"HAS_ATTRIBUTE_a_color_3f":"HAS_ATTRIBUTE_a_color_4f"),N.push(T.colorBuffer)),T.normalBuffer&&(R.push("HAS_ATTRIBUTE_a_normal_3f"),N.push(T.normalBuffer)),T.pbrBuffer&&(R.push("HAS_ATTRIBUTE_a_pbr"),R.push("HAS_ATTRIBUTE_a_heightBasedEmissiveStrength"),N.push(T.pbrBuffer)),Q.alphaMode!=="OPAQUE"&&Q.alphaMode!=="MASK"||R.push("UNPREMULT_TEXTURE_IN_SHADER"),Q.defined||R.push("DIFFUSE_SHADED");const tt=z.shadowRenderer;tt&&(R.push("RENDER_SHADOWS"),tt.useNormalOffset&&R.push("NORMAL_OFFSET"))}function a5(R,N,T,z,W,Q){const ee=R.modelOpacity,ue=N.context,_e=new Hr(N.context.gl.LEQUAL,R.isLightMesh?Hr.ReadOnly:Hr.ReadWrite,N.depthRangeFor3D),Ee=N.transform,Ie=R.mesh,Je=Ie.material,Ke=Je.pbrMetallicRoughness,tt=N.style.fog;let ut;ut=N.transform.projection.zAxisUnit==="pixels"?[...R.nodeModelMatrix]:o.aD([],z.zScaleMatrix,R.nodeModelMatrix),o.aD(ut,z.negCameraPosMatrix,ut);const lt=o.b7([],ut);o.e6(lt,lt);const kt=T.paint.get("model-color-use-theme").constantOr("default")==="none",Nt=T.paint.get("model-emissive-strength").constantOr(0),zt=Ec(new Float32Array(R.worldViewProjection),new Float32Array(ut),new Float32Array(lt),null,N,ee,Ke.baseColorFactor,Je.emissiveFactor,Ke.metallicFactor,Ke.roughnessFactor,Je,Nt,T,void 0,void 0,R.materialOverride,R.modelColor),Yt={defines:[]},Tt=[],Ss=N.shadowRenderer;Ss&&(Ss.useNormalOffset=!1),$i(Yt.defines,Tt,Ie,N,kt?null:T.lut);let cs=null;if(tt){const ns=qL(R.nodeModelMatrix,N.transform);if(cs=new Float32Array(ns),Ee.projection.name!=="globe"){const bs=Ie.aabb.min,Ks=Ie.aabb.max,[Es,bn]=tt.getOpacityForBounds(ns,bs[0],bs[1],Ks[0],Ks[1]);Yt.overrideFog=Es>=ra||bn>=ra}}const Ns=qd(N,T.paint.get("model-cutoff-fade-range"));Ns.shouldRenderCutoff&&Yt.defines.push("RENDER_CUTOFF");const Zt=N.getOrCreateProgram("model",Yt);N.uploadCommonUniforms(ue,Zt,null,cs,Ns),N.renderPass!=="shadow"&&Ss&&Ss.setupShadowsFromMatrix(R.nodeModelMatrix,Zt),Zt.draw(N,ue.gl.TRIANGLES,_e,W,Q,Ie.material.doubleSided?va.disabled:va.backCCW,zt,T.id,Ie.vertexBuffer,Ie.indexBuffer,Ie.segments,T.paint,N.transform.zoom,void 0,Tt)}function YC(R,N){return R.style._importedAsBasemap?"basemap":N.scope}function XE(R,N,T,z,W,Q,ee,ue,_e,Ee){const Ie=R.transform,Je=!!N.isGeometryBloom&&N.isGeometryBloom;if(Je&&R.renderPass==="shadow")return;const Ke=Ie.projection.name==="globe"?o.ev(T,Ie):[...T];o.aD(Ke,Ke,N.globalMatrix);const tt=o.aD([],z,Ke);if(N.meshes)for(const ut of N.meshes){const lt=ue.get(ut.material.name);if(lt&<.opacity<=0)continue;if(ut.material.alphaMode!=="BLEND"){ee.push({mesh:ut,depth:0,modelIndex:W,worldViewProjection:tt,nodeModelMatrix:Ke,isLightMesh:Je,materialOverride:lt,modelOpacity:_e,modelColor:Ee,node:N,modelMatrix:T});continue}const kt=o.ah([],ut.centroid,tt);!Ie.isOrthographic&&kt[2]<=0||Q.push({mesh:ut,depth:kt[2],modelIndex:W,worldViewProjection:tt,nodeModelMatrix:Ke,isLightMesh:Je,materialOverride:lt,modelOpacity:_e,modelColor:Ee,node:N,modelMatrix:T})}if(N.children)for(const ut of N.children)XE(R,ut,T,z,W,Q,ee,ue,_e,Ee)}function i5(R,N,T,z){const W=T.shadowRenderer;if(!W)return;const Q=W.getShadowPassDepthMode(),ee=W.calculateShadowPassMatrixFromMatrix(N),ue=Eh(ee);T.getOrCreateProgram("modelDepth").draw(T,T.context.gl.TRIANGLES,Q,qa.disabled,Ba.disabled,va.disabled,ue,z.id,R.vertexBuffer,R.indexBuffer,R.segments,z.paint,T.transform.zoom,void 0,void 0)}function QE(R,N,T,z){const W=function(Ie,Je){if(Je.footprintDebugMesh)return Je.footprintDebugMesh;if(!Je.footprint)return null;const Ke=Ie.context,tt=Je.footprint.vertices,ut=Je.footprint.indices,lt=new o.dB;lt.reserve(tt.length);for(const bs of tt)lt.emplaceBack(bs.x,bs.y);const kt=new o.dC;kt.reserve(ut.length);for(let bs=0;bs0){const Ke=Q.terrain,tt=Ke.findDEMTileFor(ue);tt&&tt.dem?_e=o.ex.create(Ke,ue,tt):Je=0}if(Je===0&&(ee.terrainElevationMin=0,ee.terrainElevationMax=0),Je===ee.validForExaggeration&&(Je===0||_e&&_e._demTile&&_e._demTile.tileID===ee.validForDEMTile.id&&_e._dem._timestamp===ee.validForDEMTile.timestamp))return!1;for(const Ke in ee.instancesPerModel){const tt=ee.instancesPerModel[Ke];for(let ut=0;utEe&&(Ee=tt.max)}const Ie=o.aC(z.x,Q,ee)-z.x,Je=o.aC(z.y,ue,_e)-z.y,Ke=o.bU(Ee,N.center.lat)-z.z;return N._zoomFromMercatorZ(Math.sqrt(Ie*Ie+Je*Je+Ke*Ke))}function nd(R,N,T,z,W,Q,ee){const ue=R.context,_e=R.renderPass==="shadow",Ee=R.shadowRenderer,Ie=_e&&Ee?Ee.getShadowPassDepthMode():new Hr(ue.gl.LEQUAL,Hr.ReadWrite,R.depthRangeFor3D),Je=R.isTileAffectedByFog(Q),Ke=R.transform.projection.name==="globe";if(T.meshes)for(const tt of T.meshes){const ut=Ke?[]:["MODEL_POSITION_ON_GPU"],lt=[];let kt,Nt,zt;const Yt=!Ke&&z.instancedDataArray.length>20;Yt&&ut.push("INSTANCED_ARRAYS");const Tt=qd(R,N.paint.get("model-cutoff-fade-range"));if(Tt.shouldRenderCutoff&&ut.push("RENDER_CUTOFF"),_e&&Ee)kt=R.getOrCreateProgram("modelDepth",{defines:ut}),Nt=Eh(ee.shadowTileMatrix,ee.shadowTileMatrix,Float32Array.from(T.globalMatrix)),zt=Ba.disabled;else{$i(ut,lt,tt,R,N.paint.get("model-color-use-theme").constantOr("default")==="none"?null:N.lut),kt=R.getOrCreateProgram("model",{defines:ut,overrideFog:Je});const cs=tt.material,Ns=cs.pbrMetallicRoughness,Zt=N.paint.get("model-opacity").constantOr(1),ns=N.paint.get("model-emissive-strength").constantOr(0);Nt=Ec(Q.expandedProjMatrix,Float32Array.from(T.globalMatrix),new Float32Array(16),null,R,Zt,Ns.baseColorFactor,cs.emissiveFactor,Ns.metallicFactor,Ns.roughnessFactor,cs,ns,N,W),Ee&&(ee.shadowUniformsInitialized?kt.setShadowUniformValues(ue,Ee.getShadowUniformValues()):(Ee.setupShadows(Q.toUnwrapped(),kt,"model-tile"),ee.shadowUniformsInitialized=!0)),zt=Tt.shouldRenderCutoff||Zt<1||cs.alphaMode!=="OPAQUE"?Ba.alphaBlended:Ba.unblended}R.uploadCommonUniforms(ue,kt,Q.toUnwrapped(),null,Tt);const Ss=tt.material.doubleSided?va.disabled:va.backCCW;if(Yt)lt.push(z.instancedDataBuffer),kt.draw(R,ue.gl.TRIANGLES,Ie,qa.disabled,zt,Ss,Nt,N.id,tt.vertexBuffer,tt.indexBuffer,tt.segments,N.paint,R.transform.zoom,void 0,lt,z.instancedDataArray.length);else{const cs=_e?"u_instance":"u_normal_matrix";for(let Ns=0;Ns_e[1]?ee:_e,Q[0]=T.max[0],ee=o.aE(o.bE(),Q,W),ue=ee[1]_e[1]?ee:_e,Q[1]=T.min[1],ee=o.aE(o.bE(),Q,W),ue=ee[1]_e[1]?ee:_e;const Ee=o.aC(z[0],0,1),Ie=100*N.pixelsPerMeter*o.aC(z[1],0,1),Je=o.aC(z[2],0,1),Ke=o.ey(o.bE(),ue,_e,Ee),tt=Math.tan(.5*N.fovX),ut=-Ke[2]*tt;if(Ie===0)return Ke[1]<-Math.abs(ut)?Je:1;const lt=(-Math.abs(ut)-Ke[1])/Ie,kt=(zt,Yt,Tt)=>(1-Tt)*zt+Tt*Yt,Nt=o.aC(kt(1,Je,lt),Je,1);return kt(1,Nt,o.aC((N.pitch-20)/20,0,1))}class eT{}class $L{constructor(){this._storage=new Map}getLinesFromTrianglesBuffer(N,T,z){{const Je=this._storage.get(T.id);if(Je)return Je.lastUsedFrameIdx=N,Je.buf}const W=z.gl,Q=W.getBufferParameter(W.ELEMENT_ARRAY_BUFFER,W.BUFFER_SIZE),ee=new ArrayBuffer(Q),ue=new Int16Array(ee);W.getBufferSubData(W.ELEMENT_ARRAY_BUFFER,0,new Int16Array(ee));const _e=new o.eA;for(let Je=0;Je30&&(z.buf.destroy(),this._storage.delete(T))}destroy(){for(const[N,T]of this._storage)T.buf.destroy(),this._storage.delete(N)}}class VL{constructor(){this.occluderSize=30,this.depthOffset=-1e-4}}const nk=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 HL{constructor(N){this.revealStart=11,this.revealRange=2}}const tT=o.e8([{type:"Float32",name:"a_pos_2f",components:2}]);class Cz{destroy(){this.vignetteVx&&this.vignetteVx.destroy(),this.vignetteIdx&&this.vignetteIdx.destroy()}draw(N,T){const z=N.getOrCreateProgram("vignette");if(!this.vignetteVx||!this.vignetteIdx){const ee=new o.eB,ue=new o.dC;ee.emplaceBack(-1,-1),ee.emplaceBack(1,-1),ee.emplaceBack(1,1),ee.emplaceBack(-1,1),ue.emplaceBack(0,1,2),ue.emplaceBack(0,2,3),this.vignetteVx=N.context.createVertexBuffer(ee,tT.members),this.vignetteIdx=N.context.createIndexBuffer(ue)}const W=o.dy.simpleSegment(0,0,4,6);if(this.vignetteVx&&this.vignetteIdx){N.uploadCommonUniforms(N.context,z);const ee={u_vignetteShape:(Q={vignetteShape:[T.start,T.range,Math.pow(10,T.fadePower)],vignetteColor:[T.color.r,T.color.g,T.color.b,T.color.a*T.strength]}).vignetteShape,u_vignetteColor:Q.vignetteColor};z.draw(N,N.context.gl.TRIANGLES,Hr.disabled,qa.disabled,Ba.alphaBlended,va.disabled,ee,"vignette",this.vignetteVx,this.vignetteIdx,W)}var Q}}class sT{constructor(){this._accumulatedOffsetX=0,this._accumulatedOffsetY=0,this._accumulatedElevation=0}update(N,T){const z=N.getFreeCameraOptions().position,W=z.toAltitude(),Q=z.toLngLat(),ee=o.ap(Q.lng),ue=o.ap(Q.lat),_e=N.pixelsPerMeter/T,Ee=ee*o.eD,Ie=o.eD*Math.log(Math.tan(Math.PI/4+ue/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 Je=-this._offsetYPrev+Ie,Ke=-this._elevationPrev+W;this._accumulatedOffsetX+=(-this._offsetXPrev+Ee)*_e,this._accumulatedOffsetY+=Je*_e,this._accumulatedElevation+=Ke*_e,this._offsetXPrev=Ee,this._offsetYPrev=Ie,this._elevationPrev=W}}getPosition(){return[this._accumulatedOffsetX,this._accumulatedOffsetY,this._accumulatedElevation]}}function re(R,N){return[-(R[0]-Math.floor(R[0]/N)*N),-(R[1]-Math.floor(R[1]/N)*N),-(R[2]-Math.floor(R[2]/N)*N)]}function de(R){const N=o.em(1323123451230),T=[];for(let z=0;z Rain"),this._vignetteParams={strength:1,start:.7,range:1,fadePower:.4,color:{r:.27,g:.27,b:.27,a:1}},this.particlesCount=16e3}update(N){const T=N.context;if(!this.particlesVx){const z=de(this.particlesCount),W=new o.eE,Q=new o.dC;let ee=0;const ue=o.em(1323123451230);for(let _e=0;_ez)return;const W=De(0,1,T.revealStart,T.revealStart+T.revealRange,z);if(!this.particlesVx||!this.particlesIdx)return;const Q=structuredClone(this._params);let ee=[-Q.direction.x,Q.direction.y,-100];o.ay(ee,ee);const ue=structuredClone(this._vignetteParams);ue.strength*=W,Q.overrideStyleParameters||(Q.intensity=N.style.rain.state.density,Q.timeFactor=N.style.rain.state.intensity,Q.color=structuredClone(N.style.rain.state.color),ee=structuredClone(N.style.rain.state.direction),Q.screenThinning.intensity=N.style.rain.state.centerThinning,Q.dropletSizeX=N.style.rain.state.dropletSize[0],Q.dropletSizeYScale=N.style.rain.state.dropletSize[1]/N.style.rain.state.dropletSize[0],Q.distortionStrength=100*N.style.rain.state.distortionStrength,ue.strength=1,ue.color=structuredClone(N.style.rain.state.vignetteColor));const _e=this.updateOnRender(N,Q.timeFactor),Ee=N.context,Ie=Ee.gl,Je=N.transform;this.screenTexture&&this.screenTexture.size[0]===N.width&&this.screenTexture.size[1]===N.height||(this.screenTexture=new o.T(Ee,{width:N.width,height:N.height,data:null},Ie.RGBA8)),Q.distortionStrength>0&&(Ee.activeTexture.set(Ie.TEXTURE0),this.screenTexture.bind(Ie.LINEAR,Ie.CLAMP_TO_EDGE),Ie.copyTexSubImage2D(Ie.TEXTURE_2D,0,0,0,0,0,N.width,N.height));const Ke=N.getOrCreateProgram("rainParticle");N.uploadCommonUniforms(Ee,Ke),Ee.activeTexture.set(Ie.TEXTURE0),this.screenTexture.bind(Ie.LINEAR,Ie.CLAMP_TO_EDGE);const tt=[Q.color.r,Q.color.g,Q.color.b,Q.color.a],ut=(lt,kt)=>{const Nt=re(this._movement.getPosition(),lt),zt=Q.dropletSizeX,Yt=Q.dropletSizeX*Q.dropletSizeYScale,Tt=N.width/2,Ss=N.height/2,cs=De(0,Q.screenThinning.start,0,1,Q.screenThinning.intensity),Ns=De(.001,Q.screenThinning.range,0,1,Q.screenThinning.intensity),Zt=De(0,Q.screenThinning.particleOffset,0,1,Q.screenThinning.intensity),ns=(bs={modelview:_e.modelviewMatrix,projection:_e.projectionMatrix,time:this._accumulatedTimeFromStart,camPos:Nt,velocityConeAperture:Q.velocityConeAperture,velocity:Q.velocity,boxSize:lt,rainDropletSize:[zt,Yt],distortionStrength:Q.distortionStrength,rainDirection:ee,color:tt,screenSize:[Je.width,Je.height],thinningCenterPos:[Tt,Ss],thinningShape:[cs,Ns,Math.pow(10,Q.screenThinning.fadePower)],thinningAffectedRatio:Q.screenThinning.affectedRatio,thinningParticleOffset:Zt,shapeDirectionalPower:Q.shapeDirPower,shapeNormalPower:Q.shapeNormalPower,mode:kt?0:1},{u_modelview:Float32Array.from(bs.modelview),u_projection:Float32Array.from(bs.projection),u_time:bs.time,u_cam_pos:bs.camPos,u_texScreen:0,u_velocityConeAperture:bs.velocityConeAperture,u_velocity:bs.velocity,u_boxSize:bs.boxSize,u_rainDropletSize:bs.rainDropletSize,u_distortionStrength:bs.distortionStrength,u_rainDirection:bs.rainDirection,u_color:bs.color,u_screenSize:bs.screenSize,u_thinningCenterPos:bs.thinningCenterPos,u_thinningShape:bs.thinningShape,u_thinningAffectedRatio:bs.thinningAffectedRatio,u_thinningParticleOffset:bs.thinningParticleOffset,u_shapeDirectionalPower:bs.shapeDirectionalPower,u_shapeNormalPower:bs.shapeNormalPower,u_mode:bs.mode});var bs;const Ks=Math.round(Q.intensity*this.particlesCount),Es=o.dy.simpleSegment(0,0,4*Ks,2*Ks);Ke.draw(N,Ie.TRIANGLES,Hr.disabled,qa.disabled,Ba.alphaBlended,va.disabled,ns,"rain_particles",this.particlesVx,this.particlesIdx,Es)};Q.distortionStrength>0&&ut(Q.boxSize,!0),ut(Q.boxSize,!1),this._vignette.draw(N,ue)}}const Lt=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 Bs extends st{constructor(N){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 HL("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(N){const T=N.context;if(!this.particlesVx){const z=de(this.particlesCount),W=new o.eF,Q=new o.dC;let ee=0;const ue=o.em(1323123451230);for(let _e=0;_eee)return;const ue=De(0,1,Q.revealStart,Q.revealStart+Q.revealRange,ee);W.strength*=ue,T.overrideStyleParameters||(T.intensity=N.style.snow.state.density,T.timeFactor=N.style.snow.state.intensity,T.color=structuredClone(N.style.snow.state.color),z=structuredClone(N.style.snow.state.direction),T.screenThinning.intensity=N.style.snow.state.centerThinning,T.billboardSize=2.79*N.style.snow.state.flakeSize,W.strength=1,W.color=structuredClone(N.style.snow.state.vignetteColor));const _e=this.updateOnRender(N,T.timeFactor);if(!this.particlesVx||!this.particlesIdx)return;const Ee=N.context,Ie=Ee.gl,Je=N.transform,Ke=N.getOrCreateProgram("snowParticle");N.uploadCommonUniforms(Ee,Ke),((tt,ut,lt)=>{const kt=re(this._movement.getPosition(),tt),Nt=Je.width/2,zt=Je.height/2,Yt=De(0,lt.screenThinning.start,0,1,lt.screenThinning.intensity),Tt=De(.001,lt.screenThinning.range,0,1,lt.screenThinning.intensity),Ss=De(0,lt.screenThinning.particleOffset,0,1,lt.screenThinning.intensity),cs=(Ns={modelview:_e.modelviewMatrix,projection:_e.projectionMatrix,time:this._accumulatedTimeFromStart,camPos:kt,velocityConeAperture:lt.velocityConeAperture,velocity:lt.velocity,horizontalOscillationRadius:lt.horizontalOscillationRadius,horizontalOscillationRate:lt.horizontalOscillationRate,boxSize:tt,billboardSize:1*lt.billboardSize,simpleShapeParameters:[lt.shapeFadeStart,lt.shapeFadePower],screenSize:[Je.width,Je.height],thinningCenterPos:[Nt,zt],thinningShape:[Yt,Tt,Math.pow(10,lt.screenThinning.fadePower)],thinningAffectedRatio:lt.screenThinning.affectedRatio,thinningParticleOffset:Ss,color:[lt.color.r,lt.color.g,lt.color.b,lt.color.a],direction:z},{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 Zt=Math.round(lt.intensity*this.particlesCount),ns=o.dy.simpleSegment(0,0,4*Zt,2*Zt);this.particlesVx&&this.particlesIdx&&Ke.draw(N,Ie.TRIANGLES,Hr.disabled,qa.disabled,Ba.alphaBlended,va.disabled,cs,"snow_particles",this.particlesVx,this.particlesIdx,ns)})(T.boxSize,0,T),this._vignette.draw(N,W)}}const Zn={symbol:function(R,N,T,z,W){if(R.renderPass!=="translucent")return;const Q=qa.disabled,ee=R.colorModeForRenderPass(),ue=T.layout.get("text-variable-anchor"),_e=T.layout.get("text-size-scale-range"),Ee=o.aC(R.scaleFactor,_e[0],_e[1]);ue&&function(Ke,tt,ut,lt,kt,Nt,zt,Yt){const Tt=tt.transform,Ss=kt==="map",cs=Nt==="map";for(const Ns of Ke){const Zt=lt.getTile(Ns),ns=Zt.getBucket(ut);if(!ns||!ns.text||!ns.text.segments.get().length)continue;const bs=o.bj(ns.textSizeData,Tt.zoom,Yt),Ks=Zh(Ns,ns.getProjection(),Tt),Es=Tt.calculatePixelsToTileUnitsMatrix(Zt),bn=dc(Ks,Zt.tileID.canonical,cs,Ss,Tt,ns.getProjection(),Es),mn=ns.hasIconTextFit()&&ns.hasIconData();bs&&sd(ns,Ss,cs,zt,Tt,bn,Ns,Math.pow(2,Tt.zoom-Zt.tileID.overscaledZ),bs,mn)}}(z,R,T,N,T.layout.get("text-rotation-alignment"),T.layout.get("text-pitch-alignment"),W,Ee);const Ie=T.paint.get("icon-opacity").constantOr(1)!==0,Je=T.paint.get("text-opacity").constantOr(1)!==0;T.layout.get("symbol-sort-key").constantOr(1)!==void 0&&(Ie||Je)?up(R,N,T,z,Q,ee):(Ie&&up(R,N,T,z,Q,ee,{onlyIcons:!0}),Je&&up(R,N,T,z,Q,ee,{onlyText:!0})),N.map.showCollisionBoxes&&(jr(R,N,T,z,T.paint.get("text-translate"),T.paint.get("text-translate-anchor"),!0),jr(R,N,T,z,T.paint.get("icon-translate"),T.paint.get("icon-translate-anchor"),!1))},circle:function(R,N,T,z){if(R.renderPass!=="translucent")return;const W=T.paint.get("circle-opacity"),Q=T.paint.get("circle-stroke-width"),ee=T.paint.get("circle-stroke-opacity"),ue=T.layout.get("circle-sort-key").constantOr(1)!==void 0,_e=T.paint.get("circle-emissive-strength");if(W.constantOr(1)===0&&(Q.constantOr(1)===0||ee.constantOr(1)===0))return;const Ee=R.context,Ie=Ee.gl,Je=R.transform,Ke=!(!R.terrain||!R.terrain.enabled),tt=T.layout.get("circle-elevation-reference"),ut=R.depthModeForSublayer(0,Hr.ReadOnly),lt=new Hr(R.context.gl.LEQUAL,Hr.ReadOnly,R.depthRangeFor3D),kt=tt==="none"||Ke?ut:lt,Nt=qa.disabled,zt=R.colorModeForDrapableLayerRenderPass(_e),Yt=Je.projection.name==="globe",Tt=[o.aH(Je.center.lng),o.aL(Je.center.lat)],Ss=[];for(let Ns=0;NsNs.sortKey-Zt.sortKey);const cs={useDepthForOcclusion:Je.depthOcclusionForSymbolsAndCircles};for(const Ns of Ss){const{programConfiguration:Zt,program:ns,layoutVertexBuffer:bs,dynamicBuffers:Ks,indexBuffer:Es,uniformValues:bn,tile:mn}=Ns.state,zn=Ns.segments;R.terrain&&R.terrain.setupElevationDraw(mn,ns,cs),R.uploadCommonUniforms(Ee,ns,mn.tileID.toUnwrapped()),ns.draw(R,Ie.TRIANGLES,kt,Nt,zt,va.disabled,bn,T.id,bs,Es,zn,T.paint,Je.zoom,Zt,Ks)}},heatmap:function(R,N,T,z){if(T.paint.get("heatmap-opacity")!==0)if(R.renderPass==="offscreen"){const W=R.context,Q=W.gl,ee=qa.disabled,ue=new Ba([Q.ONE,Q.ONE,Q.ONE,Q.ONE],o.aq.transparent,[!0,!0,!0,!0]),_e=R.transform.projection.name==="globe"?.5:.25;T.heatmapFbo=Rp.createWithTexture(W,T.heatmapFbo,R.width*_e,R.height*_e),W.clear({color:o.aq.transparent});const Ee=R.transform,Ie=Ee.projection.name==="globe",Je=Ie?["PROJECTION_GLOBE_VIEW"]:[],Ke=Ie?va.frontCCW:va.disabled,tt=[o.aH(Ee.center.lng),o.aL(Ee.center.lat)];for(let ut=0;ut({u_image:0,u_color_ramp:1,u_opacity:Je.paint.get("heatmap-opacity")}))(0,Q),Q.id,W.viewportBuffer,W.quadTriangleIndexBuffer,W.viewportSegments,Q.paint,W.transform.zoom)}(R,T))},line:function(R,N,T,z){const W=T.paint.get("line-opacity"),Q=T.paint.get("line-width");if(W.constantOr(1)===0||Q.constantOr(1)===0)return;const ee=T.paint.get("line-blend-mode");if(ee!=="default"&&R.transform.projection.name!=="globe")return R.terrain&&R.terrain.renderingToTexture?void function(ue,_e,Ee,Ie,Je){if(ue.renderPass!=="translucent")return;const Ke=ue.context,tt=Ke.gl,ut=ue.terrain;if(!ut)return;const lt=Ke.bindFramebuffer.current,kt=ue.emissiveMode==="mrt-fallback";Ee.lineBlendDrapeFbo=Rp.createWithTexture(Ke,Ee.lineBlendDrapeFbo,ut.drapeBufferSize[0],ut.drapeBufferSize[1],!0),Ee.lineBlendDrapeStencil=Ee.lineBlendDrapeFbo._stencilRbo,kt&&tt.drawBuffers([tt.COLOR_ATTACHMENT0]),Ke.clear({color:pf[Je].clearColor,depth:1,stencil:0});const Nt=ue.currentStencilSource,zt=ue._tileClippingMaskIDs,Yt=ue.nextStencilID;ue.currentStencilSource=void 0,ue._tileClippingMaskIDs={},ue.nextStencilID=1;const Tt=ue._terrain;ue._terrain=null,ue._renderTileClippingMasks(Ee,_e,Ie),Qu(ue,_e,Ee,Ie,pf[Je].colorMode,!0),ue._terrain=Tt,ue.currentStencilSource=Nt,ue._tileClippingMaskIDs=zt,ue.nextStencilID=Yt,Ke.bindFramebuffer.set(lt),kt&&tt.drawBuffers([tt.COLOR_ATTACHMENT0,tt.COLOR_ATTACHMENT1]);const Ss=ut.drapeBufferSize;Ke.viewport.set([0,0,Ss[0],Ss[1]]);const cs=Ee.lineBlendDrapeFbo;if(!cs)return;Ke.activeTexture.set(tt.TEXTURE0),tt.bindTexture(tt.TEXTURE_2D,cs.colorAttachment0.get());const Ns=Je==="additive"?1:Ee.paint.get("line-opacity").constantOr(1),Zt=Ee.paint.get("line-emissive-strength").constantOr(0),ns=Je==="additive"?ue.colorModeForDrapableLayerRenderPass(Zt):pf[Je].colorMode;ue.getOrCreateProgram("lineBlendComposite").draw(ue,tt.TRIANGLES,Hr.disabled,qa.disabled,ns,va.disabled,xc(0,Ns,pf[Je].compositeUniformValue),Ee.id,ue.viewportBuffer,ue.quadTriangleIndexBuffer,ue.viewportSegments,Ee.paint,ue.transform.zoom)}(R,N,T,z,ee):R.renderPass==="offscreen"?void function(ue,_e,Ee,Ie,Je){const Ke=ue.context,tt=Math.ceil(ue.width),ut=Math.ceil(ue.height);Ee.lineBlendFbo=Rp.createWithTexture(Ke,Ee.lineBlendFbo,tt,ut,!0),Ee.lineBlendStencil=Ee.lineBlendFbo._stencilRbo,Ke.clear({color:pf[Je].clearColor,depth:1,stencil:0});const lt=ue.currentStencilSource,kt=ue._tileClippingMaskIDs,Nt=ue.nextStencilID;ue.currentStencilSource=void 0,ue._tileClippingMaskIDs={},ue.nextStencilID=1,ue._renderTileClippingMasks(Ee,_e,Ie);const zt=ue.renderPass;ue.renderPass="translucent",Qu(ue,_e,Ee,Ie,pf[Je].colorMode),ue.renderPass=zt,ue.currentStencilSource=lt,ue._tileClippingMaskIDs=kt,ue.nextStencilID=Nt,Ke.viewport.set([0,0,ue.width,ue.height])}(R,N,T,z,ee):R.renderPass==="translucent"?void function(ue,_e,Ee){const Ie=ue.context,Je=Ie.gl,Ke=_e.lineBlendFbo;if(!Ke)return;Ie.activeTexture.set(Je.TEXTURE0),Je.bindTexture(Je.TEXTURE_2D,Ke.colorAttachment0.get());const tt=Ee==="additive"?1:_e.paint.get("line-opacity").constantOr(1),ut=Ee==="additive"?ue.colorModeForDrapableLayerRenderPass(_e.paint.get("line-emissive-strength").constantOr(0)):pf[Ee].colorMode;ue.getOrCreateProgram("lineBlendComposite").draw(ue,Je.TRIANGLES,Hr.disabled,qa.disabled,ut,va.disabled,xc(0,tt,pf[Ee].compositeUniformValue),_e.id,ue.viewportBuffer,ue.quadTriangleIndexBuffer,ue.viewportSegments,_e.paint,ue.transform.zoom)}(R,T,ee):void 0;R.renderPass==="translucent"&&Qu(R,N,T,z)},fill:function(R,N,T,z){const W=T.paint.get("fill-color"),Q=T.paint.get("fill-opacity");if(Q.constantOr(1)===0)return;const ee=T.paint.get("fill-emissive-strength"),ue=R.colorModeForDrapableLayerRenderPass(ee),_e=T.paint.get("fill-pattern"),Ee=R.opaquePassEnabledForLayer()&&!_e.constantOr(1)&&W.constantOr(o.aq.transparent).a===1&&Q.constantOr(0)===1?"opaque":"translucent";let Ie="none";T.layout.get("fill-elevation-reference")!=="none"?Ie="road":T.paint.get("fill-z-offset").constantOr(1)!==0&&(Ie="offset");const Je=!(!R.terrain||!R.terrain.enabled),Ke={painter:R,sourceCache:N,layer:T,coords:z,colorMode:ue,elevationType:Ie,terrainEnabled:Je,pass:Ee};if(R.renderPass==="shadow")return void(R.shadowRenderer&&Ie==="road"&&!Je&&function(ut){const{painter:lt,sourceCache:kt,layer:Nt,coords:zt}=ut,Yt=lt.context.gl,Tt=ut.painter.shadowRenderer;for(const Ss of zt){const cs=kt.getTile(Ss),Ns=cs.getBucket(Nt);if(!Ns)continue;const Zt=Ns.elevatedStructures;if(!Zt||!Zt.shadowCasterSegments||Zt.shadowCasterSegments.segments[0].primitiveLength===0)continue;lt.prepareDrawTile();const ns=Ns.bufferData.programConfigurations.get(Nt.id),bs=lt.isTileAffectedByFog(Ss),Ks=lt.getOrCreateProgram("elevatedStructuresDepth",{config:ns,overrideFog:bs}),Es=Tt.calculateShadowPassMatrixFromTile(cs.tileID.toUnwrapped());lt.uploadCommonUniforms(lt.context,Ks,Ss.toUnwrapped());const bn=Oi(Es,0);Ks.draw(lt,Yt.TRIANGLES,Tt.getShadowPassDepthMode(),qa.disabled,Ba.disabled,va.disabled,bn,Nt.id,Zt.vertexBuffer,Zt.indexBuffer,Zt.shadowCasterSegments,Nt.paint,lt.transform.zoom,ns)}}(Ke));const tt=R.emissiveMode==="mrt-fallback";if(Ie!=="offset"){if(I1(Ke,!1,tt),Ie==="road"){const ut=!Je&&R.renderPass==="translucent";ut&&Vb(R,N,T,z,"geometry"),I1(Ke,!0,tt,qa.disabled),ut&&function(lt){const{painter:kt,sourceCache:Nt,layer:zt,coords:Yt,colorMode:Tt}=lt,Ss=kt.context.gl,cs=lt.painter.shadowRenderer,Ns=!!cs&&cs.enabled,Zt=new Hr(kt.context.gl.LEQUAL,Hr.ReadOnly,kt.depthRangeFor3D);let ns=[0,0,0];if(Ns){const Ks=kt.style.directionalLight,Es=kt.style.ambientLight;Ks&&Es&&(ns=vm(kt.style,Ks,Es))}const bs=Ks=>{for(const Es of Yt){const bn=Nt.getTile(Es),mn=bn.getBucket(zt);if(!mn)continue;const zn=mn.elevatedStructures;if(!zn)continue;let Kn,sn;if(Ks?(Kn=zn.renderableBridgeSegments,sn=zn.bridgeProgramConfigurations.get(zt.id)):(Kn=zn.renderableTunnelSegments,sn=zn.tunnelProgramConfigurations.get(zt.id)),!Kn||Kn.segments[0].primitiveLength===0)continue;sn.updatePaintBuffers(),kt.prepareDrawTile();const Fs=kt.isTileAffectedByFog(Es),yn=[];Ns&&yn.push("RENDER_SHADOWS","NORMAL_OFFSET");const _n=kt.getOrCreateProgram("elevatedStructures",{config:sn,overrideFog:Fs,defines:yn}),Tn=kt.translatePosMatrix(Es.projMatrix,bn,zt.paint.get("fill-translate"),zt.paint.get("fill-translate-anchor"));Ns&&cs.setupShadows(bn.tileID.toUnwrapped(),_n,"vector-tile");const Nr=Al(Tn,ns);kt.uploadCommonUniforms(kt.context,_n,Es.toUnwrapped()),_n.draw(kt,Ss.TRIANGLES,Zt,qa.disabled,Tt,va.backCCW,Nr,zt.id,zn.vertexBuffer,zn.indexBuffer,Kn,zt.paint,kt.transform.zoom,sn,[zn.vertexBufferNormal])}};bs(!0),bs(!1)}(Ke)}}else I1(Ke,!1,tt,R.stencilModeFor3D())},"fill-extrusion":function(R,N,T,z){const W=T.paint.get("fill-extrusion-opacity"),Q=R.context,ee=Q.gl,ue=R.terrain,_e=ue&&ue.renderingToTexture;if(W===0)return;const Ee=R.emissiveMode==="mrt-fallback",Ie=R.conflationActive&&R.style.isLayerClipped(T,N.getSource()),Je=R.style.order.indexOf(T.fqid);if(Ie&&function(Ke,tt,ut,lt,kt){for(const Nt of lt){const zt=tt.getTile(Nt).getBucket(ut);zt&&(zt.updateReplacement(Nt,Ke.replacementSource,kt),zt.uploadCentroid(Ke.context))}}(R,N,T,z,Je),ue||Ie)for(const Ke of z){const tt=N.getTile(Ke).getBucket(T);tt&&$y(R.context,N,Ke,tt,T,ue,Ie)}if(R.renderPass==="shadow"&&R.shadowRenderer){if(ue&&W<.65&&T._transitionablePaint._values["fill-extrusion-opacity"].value.expression instanceof o.af)return;const Ke=R.shadowRenderer.getShadowPassDepthMode();Fp(R,N,T,z,Ke,qa.disabled,Ba.disabled,Ie)}else if(R.renderPass==="translucent"){const Ke=!T.paint.get("fill-extrusion-pattern").constantOr(1),tt=T.paint.get("fill-extrusion-color").constantOr(o.aq.white);if(!_e&&tt.a!==0){const ut=new Hr(R.context.gl.LEQUAL,Hr.ReadWrite,R.depthRangeFor3D);W===1&&Ke?Fp(R,N,T,z,ut,qa.disabled,Ba.unblended,Ie):(Fp(R,N,T,z,ut,qa.disabled,Ba.disabled,Ie),Fp(R,N,T,z,ut,R.stencilModeFor3D(),R.colorModeForRenderPass(),Ie),R.resetStencilClippingMasks())}if(R.style.enable3dLights()&&Ke&&(!ue&&R.transform.projection.name!=="globe"||_e)){const ut=T.paint.get("fill-extrusion-opacity"),lt=T.paint.get("fill-extrusion-ambient-occlusion-intensity"),kt=T.paint.get("fill-extrusion-ambient-occlusion-ground-radius"),Nt=T.paint.get("fill-extrusion-flood-light-intensity"),zt=T.paint.get("fill-extrusion-flood-light-color-use-theme").constantOr("default")==="none",Yt=T.paint.get("fill-extrusion-flood-light-color").toNonPremultipliedRenderColor(zt?null:T.lut).toArray01().slice(0,3),Tt=lt>0&&kt>0,Ss=Nt>0,cs=(ns,bs,Ks)=>(1-Ks)*ns+Ks*bs,Ns=new ax;Ns.translate=T.paint.get("fill-extrusion-translate"),Ns.translateAnchor=T.paint.get("fill-extrusion-translate-anchor"),Ns.edgeRadius=T.layout.get("fill-extrusion-edge-radius"),Ns.cutoffFadeRange=T.paint.get("fill-extrusion-cutoff-fade-range");const Zt=ns=>{const bs=R.depthModeForSublayer(1,Hr.ReadOnly,ee.LEQUAL,!0),Ks=T.paint.get(ns?"fill-extrusion-ambient-occlusion-ground-attenuation":"fill-extrusion-flood-light-ground-attenuation"),Es=cs(.1,3,Ks),bn=R._showOverdrawInspector;if(!bn){const mn=new qa({func:ee.ALWAYS,mask:255},255,255,ee.KEEP,ee.KEEP,ee.REPLACE),zn=new Ba([ee.ONE,ee.ONE,ee.ONE,ee.ONE],o.aq.transparent,[!1,!1,!1,!0],ee.MIN);H0(Ns,R,N,T,z,bs,mn,zn,va.disabled,ns,"sdf",ut,lt,kt,Nt,Yt,Es,Ie,!1)}{const mn=bn?qa.disabled:new qa({func:ee.EQUAL,mask:255},255,255,ee.KEEP,ee.DECR,ee.DECR),zn=bn?R.colorModeForRenderPass():new Ba([ee.ONE_MINUS_DST_ALPHA,ee.DST_ALPHA,ee.ONE,ee.ONE],o.aq.transparent,[!0,!0,!0,!0]);H0(Ns,R,N,T,z,bs,mn,zn,va.disabled,ns,"color",ut,lt,kt,Nt,Yt,Es,Ie,!1)}};if(_e){const ns=()=>{const Ks=ue.drapeBufferSize[0],Es=ue.drapeBufferSize[1];let bn=ue.framebufferCopyTexture;return bn&&(!bn||bn.size[0]===Ks&&bn.size[1]===Es)||(bn&&bn.destroy(),bn=ue.framebufferCopyTexture=new o.T(Q,new o.q({width:Ks,height:Es}),ee.RGBA8)),bn.bind(ee.LINEAR,ee.CLAMP_TO_EDGE),ee.copyTexSubImage2D(ee.TEXTURE_2D,0,0,0,0,0,Ks,Es),bn},bs=(Ks,Es,bn)=>{const mn=R.depthModeForSublayer(1,Hr.ReadOnly,ee.LEQUAL,!1),zn=T.paint.get(Ks?"fill-extrusion-ambient-occlusion-ground-attenuation":"fill-extrusion-flood-light-ground-attenuation"),Kn=cs(.1,3,zn);{const sn=new Ba([ee.ONE,ee.ONE,ee.ONE,ee.ONE],o.aq.transparent,[!1,!1,!1,!0]);H0(Ns,R,N,T,z,mn,qa.disabled,sn,va.disabled,Ks,"clear",ut,lt,kt,Nt,Yt,Kn,Ie,Es)}{const sn=new qa({func:ee.ALWAYS,mask:255},255,255,ee.KEEP,ee.KEEP,ee.REPLACE),Fs=new Ba([ee.ONE,ee.ONE,ee.ONE,ee.ONE],o.aq.transparent,[!1,!1,!1,!0],ee.MIN);H0(Ns,R,N,T,z,mn,sn,Fs,va.disabled,Ks,"sdf",ut,lt,kt,Nt,Yt,Kn,Ie,Es)}Ee&&!Ks&&(bn=ns());{const sn=Ks?ee.ZERO:ee.ONE_MINUS_DST_ALPHA,Fs=new qa({func:ee.EQUAL,mask:255},255,255,ee.KEEP,ee.DECR,ee.DECR),yn=new Ba([sn,ee.DST_ALPHA,ee.ONE_MINUS_DST_ALPHA,ee.ZERO],o.aq.transparent,[!0,!0,!0,!0]);H0(Ns,R,N,T,z,mn,Fs,yn,va.disabled,Ks,"color",ut,lt,kt,Nt,Yt,Kn,Ie,Es)}if(!Ee||Ks){const sn=new Ba([ee.ONE,ee.ONE,ee.ONE,Ks?ee.ZERO:ee.ONE],o.aq.transparent,[!1,!1,!1,!0],Ks?ee.FUNC_ADD:ee.MAX);H0(Ns,R,N,T,z,mn,qa.disabled,sn,va.disabled,Ks,"clear",ut,lt,kt,Nt,Yt,Kn,Ie,Es,bn)}else{ee.drawBuffers([ee.NONE,ee.COLOR_ATTACHMENT1]);const sn=new qa({func:ee.EQUAL,mask:255},254,255,ee.KEEP,ee.DECR,ee.DECR),Fs=new Ba([ee.ONE,ee.ONE,ee.ONE,ee.ONE],o.aq.transparent,[!0,!1,!1,!1],ee.MAX);H0(Ns,R,N,T,z,mn,sn,Fs,va.disabled,Ks,"emissive",ut,lt,kt,Nt,Yt,Kn,Ie,Es,bn),ee.drawBuffers([ee.COLOR_ATTACHMENT0])}};if(Tt||Ss){let Ks;R.prepareDrawTile(),Ee&&!Tt||(Ks=ns()),Tt&&bs(!0,!1,Ks),Ss&&bs(!1,!0,Ks)}}else Tt&&Zt(!0),Ss&&Zt(!1),(Tt||Ss)&&R.resetStencilClippingMasks()}}},building:function(R,N,T,z){R.currentLayer0&&Q>0,Ee=!0;const Ie=T.paint.get("building-vertical-scale");if(Ie<=0)return;R.shadowRenderer||(Ee=!1);const Je=R.conflationActive&&R.style.isLayerClipped(T,N.getSource()),Ke=R.style.order.indexOf(T.fqid);if(function(tt,ut,lt,kt,Nt,zt){for(const Yt of zt){const Tt=ut.getTile(Yt).getBucket(lt);Tt&&(Nt&&Tt.updateReplacement(Yt,tt.replacementSource,kt),Tt.uploadUpdatedIndexBuffer(tt.context))}}(R,N,T,Ke,Je,z),function(tt,ut,lt,kt){for(const Nt of kt){const zt=ut.getTile(Nt).getBucket(lt);zt&&zt.needsEvaluation()&&zt.uploadUpdatedColorBuffer(tt.context)}}(R,N,T,z),T.resetLayerRenderingStats(R),R.shadowRenderer&&(R.shadowRenderer.useNormalOffset=!0),R.renderPass==="shadow"&&R.shadowRenderer){const tt=[],ut=R.shadowRenderer.getShadowPassDepthMode();Uv({painter:R,source:N,layer:T,coords:z,defines:tt,blendMode:Ba.disabled,depthMode:ut,opacity:ue,verticalScale:Ie,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"];Ee&&(tt=tt.concat("RENDER_SHADOWS")),R.shadowRenderer&&R.shadowRenderer.useNormalOffset&&(tt=tt.concat("NORMAL_OFFSET"));const ut=T.paint.get("building-facade-emissive-chance"),lt=T.paint.get("building-ambient-occlusion-intensity"),kt=T.paint.get("building-flood-light-intensity"),Nt=T.paint.get("building-flood-light-color-use-theme").constantOr("default")==="none",zt=T.paint.get("building-flood-light-color").toNonPremultipliedRenderColor(Nt?null:T.lut).toArray01().slice(0,3),Yt=T.paint.get("building-flood-light-ground-attenuation"),Tt=kt>0,Ss=new Hr(R.context.gl.LEQUAL,Hr.ReadWrite,R.depthRangeFor3D);ue<1&&Uv({painter:R,source:N,layer:T,coords:z,defines:tt,blendMode:Ba.disabled,depthMode:Ss,opacity:ue,verticalScale:Ie,facadeEmissiveChance:ut,facadeAOIntensity:lt,floodLightIntensity:kt,floodLightColor:zt,depthOnly:!0});const cs=R.colorModeForRenderPass();Uv({painter:R,source:N,layer:T,coords:z,defines:tt,blendMode:cs,depthMode:Ss,opacity:ue,verticalScale:Ie,facadeEmissiveChance:ut,facadeAOIntensity:lt,floodLightIntensity:kt,floodLightColor:zt});const Ns=T.paint.get("building-front-cutoff");s2(R.transform.pitch,Ns,!!R.terrain),_e&&bg(R,N,T,z,!0,ue,W,Q,kt,zt,ee,Je),Tt&&bg(R,N,T,z,!1,ue,W,Q,kt,zt,Yt,Je)}else if(R.renderPass==="light-beam"){const tt=["HAS_ATTRIBUTE_a_part_color_emissive","HAS_ATTRIBUTE_a_bloom_attenuation"],ut=new Hr(R.context.gl.LEQUAL,Hr.ReadOnly,R.depthRangeFor3D);Uv({painter:R,source:N,layer:T,coords:z,defines:tt,blendMode:Ba.alphaBlended,depthMode:ut,opacity:ue,verticalScale:Ie,facadeEmissiveChance:0,facadeAOIntensity:0,floodLightIntensity:0,floodLightColor:[0,0,0]})}R.shadowRenderer&&(R.shadowRenderer.useNormalOffset=!1),R.resetStencilClippingMasks()},hillshade:function(R,N,T,z){if(R.renderPass!=="offscreen"&&R.renderPass!=="translucent"||R.style.disableElevatedTerrain)return;const W=R.context,Q=R.terrain&&R.terrain.renderingToTexture,[ee,ue]=R.renderPass!=="translucent"||Q?[{},z]:R.stencilConfigForOverlap(z);for(const _e of ue){const Ee=N.getTile(_e);if(Ee.needsHillshadePrepare&&R.renderPass==="offscreen")YE(R,Ee,T);else if(R.renderPass==="translucent"){const Ie=R.depthModeForSublayer(0,Hr.ReadOnly),Je=T.paint.get("hillshade-emissive-strength"),Ke=R.colorModeForDrapableLayerRenderPass(Je),tt=Q&&R.terrain?R.terrain.stencilModeForRTTOverlap(_e):ee[_e.overscaledZ];BL(R,_e,Ee,T,Ie,tt,Ke)}}W.viewport.set([0,0,R.width,R.height]),R.resetStencilClippingMasks()},raster:function(R,N,T,z,W,Q){if(R.renderPass!=="translucent")return;const ee=T.paint.get("raster-opacity");if(ee===0)return;const ue=R.transform.projection.name==="globe",_e=T.paint.get("raster-elevation")!==0,Ee=_e&&ue,Ie=R.terrain&&R.terrain.exaggeration()>0&&_e&&T.paint.get("raster-elevation-reference")==="ground",Je=!ue&&Ie;if(R.renderElevatedRasterBackface&&!Ee)return;const Ke=R.context,tt=Ke.gl,ut=N.getSource(),lt=function(ns,bs,Ks,Es,bn){const mn=bs.paint.get("raster-color"),zn=ns.type==="raster-array",Kn=[],sn=bs.paint.get("raster-resampling"),Fs=bs.paint.get("raster-color-mix");let yn=bs.paint.get("raster-color-range");const _n=[Fs[0],Fs[1],Fs[2],0],Tn=Fs[3];let Nr=sn==="nearest"?Es.NEAREST:Es.LINEAR;if(zn&&(Kn.push("RASTER_ARRAY"),mn||Kn.push("RASTER_COLOR"),sn==="linear"&&Kn.push("RASTER_ARRAY_LINEAR"),Nr=Es.NEAREST,!yn&&ns.rasterLayers)){const hr=ns.rasterLayers.find(({id:mr})=>mr===bs.sourceLayer);hr&&hr.fields&&hr.fields.range&&(yn=hr.fields.range)}if(yn=yn||[0,1],mn){Kn.push("RASTER_COLOR"),Ks.activeTexture.set(Es.TEXTURE2),bs.updateColorRamp(yn);let hr=bs.colorRampTexture;hr||(hr=bs.colorRampTexture=new o.T(Ks,bs.colorRamp,Es.RGBA8)),hr.bind(Nr,Es.CLAMP_TO_EDGE)}return bn&&Kn.push("USE_MRT1"),{mix:_n,range:yn,offset:Tn,defines:Kn,resampling:Nr}}(ut,T,Ke,tt,R.terrain&&R.terrain.renderingToTexture&&R.emissiveMode==="mrt-fallback");if(ut instanceof o.aV&&!z.length&&!ue)return;const kt=T.paint.get("raster-emissive-strength"),Nt=R.colorModeForDrapableLayerRenderPass(kt),zt=R.terrain&&R.terrain.renderingToTexture,Yt=!R.options.moving,Tt=T.paint.get("raster-resampling")==="nearest"?tt.NEAREST:tt.LINEAR;if(ut instanceof o.aV&&!z.length&&(ut.onNorthPole||ut.onSouthPole)){const ns=_e?R.stencilModeFor3D():qa.disabled;return void Hb(!!ut.onNorthPole,null,R,N,T,kt,lt,va.disabled,ns)}if(!z.length)return;const[Ss,cs]=ut instanceof o.aV||zt?[{},z]:R.stencilConfigForOverlap(z),Ns=cs[cs.length-1].overscaledZ;Ee&<.defines.push("PROJECTION_GLOBE_VIEW"),_e&<.defines.push("RENDER_CUTOFF","ELEVATED"),Ie&<.defines.push("ELEVATION_REFERENCE_GROUND");const Zt=(ns,bs,Ks)=>{for(const Es of ns){const bn=Es.toUnwrapped(),mn=N.getTile(Es);if(zt&&(!mn||!mn.hasData()))continue;Ke.activeTexture.set(tt.TEXTURE0);const zn=a2(mn,ut,T,lt);if(!zn||!zn.texture)continue;const{texture:Kn,mix:sn,offset:Fs,tileSize:yn,buffer:_n}=zn;let Tn,Nr;zt?(Tn=Hr.disabled,Nr=Es.projMatrix):_e?(Tn=new Hr(tt.LEQUAL,Hr.ReadWrite,R.depthRangeFor3D),Nr=ue?Float32Array.from(R.transform.expandedFarZProjMatrix):R.transform.calculateProjMatrix(bn,Yt)):(Tn=R.depthModeForSublayer(Es.overscaledZ-Ns,ee===1?Hr.ReadWrite:Hr.ReadOnly,tt.LESS),Nr=R.transform.calculateProjMatrix(bn,Yt));const hr=R.terrain&&zt?R.terrain.stencilModeForRTTOverlap(Es):Ss[Es.overscaledZ],mr=Q?0:T.paint.get("raster-fade-duration");mn.registerFadeDuration(mr);const Gn=N.findLoadedParent(Es,0),pa=_t(mn,Gn,N,R.transform,mr);let Aa,ta;!pa.isFading&&mn.refreshedUponExpiration&&(mn.refreshedUponExpiration=!1),R.terrain&&R.terrain.prepareDrawTile(),Ke.activeTexture.set(tt.TEXTURE0),Kn.bind(Tt,tt.CLAMP_TO_EDGE),Ke.activeTexture.set(tt.TEXTURE1),Gn?(Gn.texture&&Gn.texture.bind(Tt,tt.CLAMP_TO_EDGE),Aa=Math.pow(2,Gn.tileID.overscaledZ-mn.tileID.overscaledZ),ta=[mn.tileID.canonical.x*Aa%1,mn.tileID.canonical.y*Aa%1]):Kn.bind(Tt,tt.CLAMP_TO_EDGE),"useMipmap"in Kn&&Ke.extTextureFilterAnisotropic&&R.transform.pitch>20&&tt.texParameterf(tt.TEXTURE_2D,Ke.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,Ke.extTextureFilterAnisotropicMax);const ua=R.transform;let ui;const Ai=_e?Gb(ua):[0,0,0,0];let ji,io,Qa,oo,Ni,al=0;if(Ee&&ut instanceof o.aV&&ut.coordinates.length>3)ji=Float32Array.from(o.du(o.dv(new o.cn(0,0,0)))),io=Float32Array.from(ua.globeMatrix),Qa=Float32Array.from(o.dq(ua)),oo=[o.aH(ua.center.lng),o.aL(ua.center.lat)],ui=ut.elevatedGlobePerspectiveTransform,Ni=ut.elevatedGlobeGridMatrix||new Float32Array(9);else if(Ee){const yl=o.dr(Es.canonical);al=o.ds(yl.getCenter().lat),ji=Float32Array.from(o.du(o.dv(Es.canonical))),io=Float32Array.from(ua.globeMatrix),Qa=Float32Array.from(o.dq(ua)),oo=[o.aH(ua.center.lng),o.aL(ua.center.lat)],ui=[0,0],Ni=Float32Array.from(o.dt(Es.canonical,yl,al,ua.worldSize/ua._pixelsPerMercatorPixel))}else ui=ut instanceof o.aV?ut.perspectiveTransform:[0,0],ji=new Float32Array(16),io=new Float32Array(9),Qa=new Float32Array(16),oo=[0,0],Ni=new Float32Array(9);const gc=Vu(R,Nr,ji,io,Qa,Ni,ta||[0,0],o.al(R.transform.zoom),oo,Ai,Aa||1,pa,T,ui,_e?T.paint.get("raster-elevation"):0,2,sn,Fs,lt.range,yn,_n,kt),Hd=R.isTileAffectedByFog(Es),Fc=R.getOrCreateProgram("raster",{defines:lt.defines,overrideFog:Hd});if(R.uploadCommonUniforms(Ke,Fc,bn),ut instanceof o.aV){const yl=ut.elevatedGlobeVertexBuffer,Yi=ut.elevatedGlobeIndexBuffer;if(zt||!ue)ut.boundsBuffer&&ut.boundsSegments&&Fc.draw(R,tt.TRIANGLES,Tn,qa.disabled,Nt,va.disabled,gc,T.id,ut.boundsBuffer,R.quadTriangleIndexBuffer,ut.boundsSegments);else if(yl&&Yi){const Zi=ua.zoom<=o.cJ?ut.elevatedGlobeSegments:ut.getSegmentsForLongitude(ua.center.lng);Zi&&Fc.draw(R,tt.TRIANGLES,Tn,qa.disabled,Nt,bs,gc,T.id,yl,Yi,Zi)}}else if(Ee){Tn=new Hr(tt.LEQUAL,Hr.ReadOnly,R.depthRangeFor3D);const yl=R.globeSharedBuffers;if(yl){Ie&&(R.terrain.setupElevationDraw(mn,Fc),R.uploadCommonUniforms(Ke,Fc,mn.tileID.toUnwrapped()));const[Yi,Zi,Oc]=yl.getGridBuffers(al,!1),cu=Fc.getAttributeLocation(tt,"a_texture_pos");cu!==-1&&tt.vertexAttribI4ui(cu,0,0,0,0),Fc.draw(R,tt.TRIANGLES,Tn,Ks||hr,R.colorModeForRenderPass(),bs,gc,T.id,Yi,Zi,Oc)}}else if(Je)Tn=new Hr(tt.LEQUAL,Hr.ReadWrite,R.depthRangeFor3D),R.terrain.setupElevationDraw(mn,Fc),R.uploadCommonUniforms(Ke,Fc,mn.tileID.toUnwrapped()),ua.pitch>20&&Fc.draw(R,tt.TRIANGLES,Tn,qa.disabled,Ba.disabled,va.frontCCW,gc,T.id,R.terrain.gridBuffer,R.terrain.gridIndexBuffer,R.terrain.gridSegments),Fc.draw(R,tt.TRIANGLES,Tn,hr,Nt,va.backCCW,gc,T.id,R.terrain.gridBuffer,R.terrain.gridIndexBuffer,R.terrain.gridSegments);else{const{tileBoundsBuffer:yl,tileBoundsIndexBuffer:Yi,tileBoundsSegments:Zi}=R.getTileBoundsBuffers(mn);Fc.draw(R,tt.TRIANGLES,Tn,hr,Nt,va.disabled,gc,T.id,yl,Yi,Zi)}}if(!(ut instanceof o.aV)&&Ee)for(const Es of ns){const bn=Es.canonical.y===(1<o.d$[_n](bn));sn.push(bn);const Fs=bn.canonical.x,yn=bn.canonical.y;for(const _n of sn){const Tn=Tt.getTile(bs?_n.wrapped():_n);if(!Tn)continue;const Nr=Tn.rasterParticleState;if(!Nr)continue;const hr=_n.canonical.x+(1<<_n.canonical.z)*(_n.wrap-bn.wrap),mr=_n.canonical.y;Nr.particleTexture0.bind(Zt.NEAREST,Zt.CLAMP_TO_EDGE);const Gn=Vd(1,Nr.particleTexture0.size[0],[hr-Fs,mr-yn],0,mn.texture.size,2,Ks,mn.textureOffset,mn.scale,mn.offset);Kn.draw(Yt,Zt.POINTS,Hr.disabled,qa.disabled,Ba.alphaBlended,va.disabled,Gn,Ss.id,Nr.particleIndexBuffer,void 0,Nr.particleSegment)}}}(ee,ue,_e,kt),Ie.bindFramebuffer.set(_e.particleFramebuffer.framebuffer),function(Yt,Tt,Ss,cs){const Ns=Yt.context,Zt=Ns.gl,ns=Tt.paint.get("raster-particle-max-speed"),bs=cs*Tt.paint.get("raster-particle-speed-factor")*.15,Ks=function(bn){return Math.pow(bn,6)}(.01+1*Tt.paint.get("raster-particle-reset-rate-factor")),Es=Tt.particleFramebuffer;Ns.viewport.set([0,0,Es.width,Es.height]);for(const bn of Ss){const[,mn,zn]=bn;Ns.activeTexture.set(Zt.TEXTURE0+0),mn.texture.bind(Zt.LINEAR,Zt.CLAMP_TO_EDGE),Ns.activeTexture.set(Zt.TEXTURE0+1);const Kn=zn.particleTexture0;Kn.bind(Zt.NEAREST,Zt.CLAMP_TO_EDGE);const sn=fh(1,Kn.size[0],0,mn.texture.size,ns,bs,Ks,mn.textureOffset,mn.scale,mn.offset);Es.colorAttachment0.set(zn.particleTexture1.texture),Ns.clear({color:o.aq.transparent}),Yt.getOrCreateProgram("rasterParticleUpdate",{defines:mn.defines}).draw(Yt,Zt.TRIANGLES,Hr.disabled,qa.disabled,Ba.unblended,va.disabled,sn,Tt.id,Yt.viewportBuffer,Yt.quadTriangleIndexBuffer,Yt.viewportSegments)}}(ee,_e,kt,zt)}(R,N,T,z),R.renderPass==="translucent"&&(function(ee,ue,_e,Ee){const Ie=ee.context,Je=Ie.gl,Ke=ue.getSource().tileSize,tt=5*(1-o.aj(o.cv,o.cv+1,ee.transform.zoom))*Ke+_e.paint.get("raster-particle-elevation"),ut=!ee.options.moving,lt=ee.transform.projection.name==="globe";if(!Ee.length)return;const[kt,Nt]=ee.stencilConfigForOverlap(Ee),zt=[];lt&&zt.push("PROJECTION_GLOBE_VIEW");const Yt=ee.stencilModeFor3D();for(const Tt of Nt){const Ss=Tt.toUnwrapped(),cs=ue.getTile(Tt);if(!cs.rasterParticleState)continue;const Ns=cs.rasterParticleState,Zt=100;cs.registerFadeDuration(Zt);const ns=ue.findLoadedParent(Tt,0),bs=_t(cs,ns,ue,ee.transform,Zt);let Ks,Es;ee.terrain&&ee.terrain.prepareDrawTile(),Ie.activeTexture.set(Je.TEXTURE0),Ns.targetColorTexture.bind(Je.LINEAR,Je.CLAMP_TO_EDGE),Ie.activeTexture.set(Je.TEXTURE1),ns&&ns.rasterParticleState?(ns.rasterParticleState.targetColorTexture.bind(Je.LINEAR,Je.CLAMP_TO_EDGE),Ks=Math.pow(2,ns.tileID.overscaledZ-cs.tileID.overscaledZ),Es=[cs.tileID.canonical.x*Ks%1,cs.tileID.canonical.y*Ks%1]):Ns.targetColorTexture.bind(Je.LINEAR,Je.CLAMP_TO_EDGE);const bn=lt?Float32Array.from(ee.transform.expandedFarZProjMatrix):ee.transform.calculateProjMatrix(Ss,ut),mn=ee.transform,zn=Ux(mn),Kn=o.dr(Tt.canonical),sn=o.ds(Kn.getCenter().lat);let Fs,yn,_n,Tn,Nr;lt?(Fs=Float32Array.from(o.du(o.dv(Tt.canonical))),yn=Float32Array.from(mn.globeMatrix),_n=Float32Array.from(o.dq(mn)),Tn=[o.aH(mn.center.lng),o.aL(mn.center.lat)],Nr=Float32Array.from(o.dt(Tt.canonical,Kn,sn,mn.worldSize/mn._pixelsPerMercatorPixel))):(Fs=new Float32Array(16),yn=new Float32Array(9),_n=new Float32Array(16),Tn=[0,0],Nr=new Float32Array(9));const hr=ed(bn,Fs,yn,_n,Nr,Es||[0,0],o.al(ee.transform.zoom),Tn,zn,Ks||1,bs,tt),mr=ee.isTileAffectedByFog(Tt),Gn=ee.getOrCreateProgram("rasterParticle",{defines:zt,overrideFog:mr});if(ee.uploadCommonUniforms(Ie,Gn,Ss),lt){const pa=new Hr(Je.LEQUAL,Hr.ReadOnly,ee.depthRangeFor3D),Aa=0,ta=ee.globeSharedBuffers;if(ta){const[ua,ui,Ai]=ta.getGridBuffers(sn,Aa!==0);Gn.draw(ee,Je.TRIANGLES,pa,Yt,Ba.alphaBlended,ee.renderElevatedRasterBackface?va.frontCCW:va.backCCW,hr,_e.id,ua,ui,Ai)}}else{const pa=ee.depthModeForSublayer(0,Hr.ReadOnly),Aa=kt[Tt.overscaledZ],{tileBoundsBuffer:ta,tileBoundsIndexBuffer:ua,tileBoundsSegments:ui}=ee.getTileBoundsBuffers(cs);Gn.draw(ee,Je.TRIANGLES,pa,Aa,Ba.alphaBlended,va.disabled,hr,_e.id,ta,ua,ui)}}ee.resetStencilClippingMasks()}(R,N,T,z),R.style.map.triggerRepaint())},background:function(R,N,T,z){const W=T.paint.get("background-color"),Q=T.paint.get("background-color-use-theme").constantOr("default")==="none",ee=T.paint.get("background-opacity"),ue=T.paint.get("background-emissive-strength"),_e=T.paint.get("background-pitch-alignment")==="viewport";if(ee===0)return;const Ee=R.context,Ie=Ee.gl,Je=R.transform,Ke=Je.tileSize,tt=T.paint.get("background-pattern");let ut;if(tt!==void 0&&(tt===null||(ut=R.imageManager.getPattern(o.I.from(tt.toString()),T.scope,R.style.getLut(T.scope)),!ut)))return;const lt=!tt&&W.a===1&&ee===1&&R.opaquePassEnabledForLayer()?"opaque":"translucent";if(R.renderPass!==lt)return;const kt=qa.disabled,Nt=R.depthModeForSublayer(0,lt==="opaque"?Hr.ReadWrite:Hr.ReadOnly),zt=R.colorModeForDrapableLayerRenderPass(ue),Yt=tt?"backgroundPattern":"background";let Tt,Ss=z;Ss||(Tt=R.getBackgroundTiles(),Ss=Object.values(Tt).map(Ns=>Ns.tileID)),tt&&(Ee.activeTexture.set(Ie.TEXTURE0),R.imageManager.bind(R.context,T.scope));const cs=[];if(R.terrain&&R.terrain.renderingToTexture&&R.emissiveMode==="mrt-fallback"&&cs.push("USE_MRT1"),_e){const Ns=R.getOrCreateProgram(Yt,{overrideFog:!1,overrideRtt:!0,defines:cs}),Zt=new Float32Array(o.b9([])),ns=new o.aR(0,0,0,0,0),bs=tt?Md(Zt,ue,ee,R,0,T.scope,ut,_e,{tileID:ns,tileSize:Ke}):Ip(Zt,ue,ee,W.toPremultipliedRenderColor(Q?null:T.lut));return void Ns.draw(R,Ie.TRIANGLES,Nt,kt,zt,va.disabled,bs,T.id,R.viewportBuffer,R.quadTriangleIndexBuffer,R.viewportSegments)}for(const Ns of Ss){const Zt=R.isTileAffectedByFog(Ns),ns=R.getOrCreateProgram(Yt,{overrideFog:Zt,defines:cs}),bs=Ns.toUnwrapped(),Ks=z?Ns.projMatrix:R.transform.calculateProjMatrix(bs);R.prepareDrawTile();const Es=N?N.getTile(Ns):Tt?Tt[Ns.key]:new o.b0(Ns,Ke,Je.zoom,R),bn=tt?Md(Ks,ue,ee,R,0,T.scope,ut,_e,{tileID:Ns,tileSize:Ke}):Ip(Ks,ue,ee,W.toPremultipliedRenderColor(Q?null:T.lut));R.uploadCommonUniforms(Ee,ns,bs);const{tileBoundsBuffer:mn,tileBoundsIndexBuffer:zn,tileBoundsSegments:Kn}=R.getTileBoundsBuffers(Es);ns.draw(R,Ie.TRIANGLES,Nt,kt,zt,va.disabled,bn,T.id,mn,zn,Kn)}},sky:function(R,N,T){const z=R._atmosphere?o.al(R.transform.zoom):1,W=T.paint.get("sky-opacity")*z;if(W===0)return;const Q=R.context,ee=T.paint.get("sky-type"),ue=new Hr(Q.gl.LEQUAL,Hr.ReadOnly,[0,1]),_e=R.frameCounter/1e3%1;ee==="atmosphere"?R.renderPass==="offscreen"?T.needsSkyboxCapture(R)&&(function(Ee,Ie){const Je=Ee.context,Ke=Je.gl;let tt=Ie.skyboxFbo;if(!tt){tt=Ie.skyboxFbo=Je.createFramebuffer(32,32,1,null),Ie.skyboxGeometry=new Eu(Je),Ie.skyboxTexture=Je.gl.createTexture(),Ke.bindTexture(Ke.TEXTURE_CUBE_MAP,Ie.skyboxTexture),Ke.texParameteri(Ke.TEXTURE_CUBE_MAP,Ke.TEXTURE_WRAP_S,Ke.CLAMP_TO_EDGE),Ke.texParameteri(Ke.TEXTURE_CUBE_MAP,Ke.TEXTURE_WRAP_T,Ke.CLAMP_TO_EDGE),Ke.texParameteri(Ke.TEXTURE_CUBE_MAP,Ke.TEXTURE_MIN_FILTER,Ke.LINEAR),Ke.texParameteri(Ke.TEXTURE_CUBE_MAP,Ke.TEXTURE_MAG_FILTER,Ke.LINEAR);for(let Nt=0;Nt<6;++Nt)Ke.texImage2D(Ke.TEXTURE_CUBE_MAP_POSITIVE_X+Nt,0,Ke.RGBA,32,32,0,Ke.RGBA,Ke.UNSIGNED_BYTE,null)}Je.bindFramebuffer.set(tt.framebuffer),Je.viewport.set([0,0,32,32]);const ut=Ie.getCenter(Ee,!0),lt=Ee.getOrCreateProgram("skyboxCapture"),kt=new Float64Array(16);o.b9(kt),o.ef(kt,kt,.5*-Math.PI),ox(Ee,Ie,lt,kt,ut,0),o.b9(kt),o.ef(kt,kt,.5*Math.PI),ox(Ee,Ie,lt,kt,ut,1),o.b9(kt),o.cE(kt,kt,.5*-Math.PI),ox(Ee,Ie,lt,kt,ut,2),o.b9(kt),o.cE(kt,kt,.5*Math.PI),ox(Ee,Ie,lt,kt,ut,3),o.b9(kt),ox(Ee,Ie,lt,kt,ut,4),o.b9(kt),o.ef(kt,kt,Math.PI),ox(Ee,Ie,lt,kt,ut,5),Je.viewport.set([0,0,Ee.width,Ee.height])}(R,T),T.markSkyboxValid(R)):R.renderPass==="sky"&&function(Ee,Ie,Je,Ke,tt){const ut=Ee.context,lt=ut.gl,kt=Ee.transform,Nt=Ee.getOrCreateProgram("skybox");ut.activeTexture.set(lt.TEXTURE0),lt.bindTexture(lt.TEXTURE_CUBE_MAP,Ie.skyboxTexture);const zt=((Yt,Tt,Ss,cs,Ns)=>({u_matrix:Yt,u_sun_direction:Tt,u_cubemap:0,u_opacity:cs,u_temporal_offset:Ns}))(kt.skyboxMatrix,Ie.getCenter(Ee,!1),0,Ke,tt);Ee.uploadCommonUniforms(ut,Nt),Nt.draw(Ee,lt.TRIANGLES,Je,qa.disabled,Ee.colorModeForRenderPass(),va.backCW,zt,"skybox",Ie.skyboxGeometry.vertexBuffer,Ie.skyboxGeometry.indexBuffer,Ie.skyboxGeometry.segment)}(R,T,ue,W,_e):ee==="gradient"&&R.renderPass==="sky"&&function(Ee,Ie,Je,Ke,tt){const ut=Ee.context,lt=ut.gl,kt=Ee.transform,Nt=Ee.getOrCreateProgram("skyboxGradient");Ie.skyboxGeometry||(Ie.skyboxGeometry=new Eu(ut)),ut.activeTexture.set(lt.TEXTURE0);let zt=Ie.colorRampTexture;zt||(zt=Ie.colorRampTexture=new o.T(ut,Ie.colorRamp,lt.RGBA8)),zt.bind(lt.LINEAR,lt.CLAMP_TO_EDGE);const Yt=((Tt,Ss,cs,Ns,Zt)=>({u_matrix:Tt,u_color_ramp:0,u_center_direction:Ss,u_radius:o.ap(cs),u_opacity:Ns,u_temporal_offset:Zt}))(kt.skyboxMatrix,Ie.getCenter(Ee,!1),Ie.paint.get("sky-gradient-radius"),Ke,tt);Ee.uploadCommonUniforms(ut,Nt),Nt.draw(Ee,lt.TRIANGLES,Je,qa.disabled,Ee.colorModeForRenderPass(),va.backCW,Yt,"skyboxGradient",Ie.skyboxGeometry.vertexBuffer,Ie.skyboxGeometry.indexBuffer,Ie.skyboxGeometry.segment)}(R,T,ue,W,_e)},custom:function(R,N,T,z){const W=R.context,Q=T.implementation;if(!R.transform.projection.unsupportedLayers||!R.transform.projection.unsupportedLayers.includes("custom")||R.terrain&&(R.terrain.renderingToTexture||R.renderPass==="offscreen")&&T.isDraped(N)){if(R.renderPass==="offscreen"){const ee=Q.prerender;if(ee){if(R.setCustomLayerDefaults(),W.setColorMode(R.colorModeForRenderPass()),R.transform.projection.name==="globe"){const ue=R.transform.pointMerc;ee.call(Q,W.gl,R.transform.customLayerMatrix(),R.transform.getProjection(),R.transform.globeToMercatorMatrix(),o.al(R.transform.zoom),[ue.x,ue.y],R.transform.pixelsPerMeterRatio)}else ee.call(Q,W.gl,R.transform.customLayerMatrix());W.setDirty(),R.setBaseState()}}else if(R.renderPass==="translucent"){if(R.terrain&&R.terrain.renderingToTexture){const ue=Q.renderToTile;if(ue){const _e=z[0].canonical,Ee={x:_e.x+z[0].wrap*(Q.wrapTileId?0:1<<_e.z),y:_e.y,z:_e.z};W.setDepthMode(Hr.disabled),W.setStencilMode(qa.disabled),W.setColorMode(R.colorModeForRenderPass()),R.setCustomLayerDefaults(),ue.call(Q,W.gl,Ee),W.setDirty(),R.setBaseState()}return}R.setCustomLayerDefaults(),W.setColorMode(R.colorModeForRenderPass()),W.setStencilMode(qa.disabled);const ee=Q.renderingMode==="3d"?new Hr(R.context.gl.LEQUAL,Hr.ReadWrite,R.depthRangeFor3D):R.depthModeForSublayer(0,Hr.ReadOnly);if(W.setDepthMode(ee),R.transform.projection.name==="globe"){const ue=R.transform.pointMerc;Q.render(W.gl,R.transform.customLayerMatrix(),R.transform.getProjection(),R.transform.globeToMercatorMatrix(),o.al(R.transform.zoom),[ue.x,ue.y],R.transform.pixelsPerMeterRatio)}else Q.render(W.gl,R.transform.customLayerMatrix());W.setDirty(),R.setBaseState(),W.bindFramebuffer.set(null)}}else o.w("Custom layers are not yet supported with this projection. Use mercator or globe to enable usage of custom layers.")},model:function(R,N,T,z){if(R.renderPass==="opaque")return;const W=T.paint.get("model-opacity").constantOr(1),Q=T.paint.get("model-elevation-reference"),ee=Q==="ground",ue=Q==="ground";if(W===0)return;const _e=T.paint.get("model-cast-shadows");if(R.renderPass==="shadow"&&(!_e||R.terrain&&W<.65&&T._transitionablePaint._values["model-opacity"].value.expression instanceof o.af))return;const Ee=R.shadowRenderer,Ie=T.paint.get("model-receive-shadows");Ee&&(Ee.useNormalOffset=!0,Ie||(Ee.enabled=!1));const Je=()=>{Ee&&(Ee.useNormalOffset=!0,Ie||(Ee.enabled=!0))},Ke=N.getSource();if(R.renderPass==="light-beam"&&Ke.type!=="batched-model")return;if(Ke.type==="vector"||Ke.type==="geojson")return function(Tt,Ss,cs,Ns,Zt){const ns=Tt.transform,bs=ns.projection.name==="globe",Ks=ns.getFreeCameraOptions().position;if(!Tt.modelManager)return;const Es=Tt.modelManager;cs.modelManager=Es;const bn=Tt.shadowRenderer;if(!cs._unevaluatedLayout._values.hasOwnProperty("model-id"))return;const mn=cs._unevaluatedLayout._values["model-id"],zn=Object.assign({},cs.layout.get("model-id").parameters),Kn=Tt.style.order.indexOf(cs.fqid),sn=cs.paint.get("model-opacity").constantOr(1);for(const Fs of Ns){const yn=Ss.getTile(Fs).getBucket(cs);if(!yn||yn.projection.name!==ns.projection.name)continue;const _n=yn.getModelUris();if(_n&&!yn.modelsRequested&&(Es.addModelsFromBucket(_n,Zt),yn.modelsRequested=!0),bs)zn.zoom=Fs.overscaledZ;else{const ta=Gy(Fs,ns);zn.zoom=ta}const Tn=mn.possiblyEvaluate(zn);if(cr(Tt,yn,Fs),lr.shadowUniformsInitialized=!1,lr.useSingleShadowCascade=!!bn&&bn.getMaxCascadeForTile(Fs.toUnwrapped())===0,Tt.renderPass==="shadow"&&bn){if(Tt.currentShadowCascade===1&&yn.isInsideFirstShadowMapFrustum)continue;const ta=ns.calculatePosMatrix(Fs.toUnwrapped(),ns.worldSize);if(lr.tileMatrix.set(ta),lr.shadowTileMatrix=Float32Array.from(bn.calculateShadowPassMatrixFromMatrix(ta)),lr.aabb.min=[0,0,0],lr.aabb.max[0]=lr.aabb.max[1]=o.an,lr.aabb.max[2]=0,ZC(yn,lr,Tt,cs.scope))continue}const Nr=1<0&&Tt.style.isLayerClipped(cs,Ss.getSource())&&yn.updateReplacement(Fs,Tt.replacementSource,Kn,cs.scope)&&(yn.uploaded=!1,yn.upload(Tt.context));let mr=0;const Gn=new Array,pa=new Array,Aa=new Array;for(let ta in yn.instancesPerModel){const ua=yn.instancesPerModel[ta];ua.features.length>0&&!bs&&(ta=Tn.evaluate(ua.features[0].feature,{}));const ui=Es.getModel(ta,Zt);if(ui||Es.hasURLBeenRequested(ta)||yn.modelUris.includes(ta)||(yn.modelUris.push(ta),yn.modelsRequested=!1),ui&&ui.uploaded)if(bs){const Ai=o.bJ([],[Ks.x,Ks.y,Ks.z],Tt.transform.worldSize);o.eo(Ai,Ai);for(let ji=0;ji0&&oo.elevationUpdate(ta.terrain,ji,Qa,ui.source),oo.needsReEvaluation(ta,io,ui)&&oo.evaluate(ui))}})(Tt,Ss,cs,Ns),function(){const ta=new Map;let ua,ui,Ai;Gn?(ua=Ns.length-1,ui=-1,Ai=-1):(ua=0,ui=Ns.length,Ai=1);const ji=new Float64Array(16),io=o.ce(),Qa=new o.P(0,0);for(let oo=ua;oo!==ui;oo+=Ai){const Ni=Ns[oo],al=Ss.getTile(Ni).getBucket(cs);if(!al||!al.uploaded)continue;let gc=!1;Ks&&(gc=Ks.getMaxCascadeForTile(Ni.toUnwrapped())===0);const Hd=ns.calculatePosMatrix(Ni.toUnwrapped(),ns.worldSize),Fc=al.modelTraits;!Nr&&Gn&&(o.b7(ji,Hd),o.ah(io,bn,ji),Qa.x=io[0],Qa.y=io[1]);const yl=[];al.setFilter(cs.filter);for(const Yi of al.getNodesInfo()){if(Yi.hiddenByReplacement||!Yi.node.meshes)continue;const Zi=Yi.node;let Oc=0;Tt.terrain&&Zi.elevation&&(Oc=Zi.elevation*Tt.terrain.exaggeration());const cu=(()=>{const ff=Yi.aabb;return Tn.min=[...ff.min],Tn.max=[...ff.max],Tn.min[2]+=Oc,Tn.max[2]+=Oc,o.ah(Tn.min,Tn.min,Hd),o.ah(Tn.max,Tn.max,Hd),Tn})(),vl=Yi.evaluatedScale;if(vl[0]<=1&&vl[1]<=1&&vl[2]<=1&&cu.intersects(hr)===0)continue;if(!Nr&&Gn){const ff=.16666666666666666;Yi.cameraCollisionOpacity=bn[0]>cu.min[0]&&bn[0]cu.min[1]&&bn[1]!Gn||Yi.opacity===1&&Zi.opacity===1?Yi.depthZi.depth?-1:1);for(const Yi of yl){const Zi=Yi.nodeInfo,Oc=Zi.node;if(Tt._debugParams.show3DModelFootprints&&Oc.footprint){const _o=Oc.id||Oc.name||"footprint";ta.has(_o)||ta.set(_o,{node:Oc,mvp:Yi.wvpForTile})}let cu=o.aD([],sn,Yi.tileModelMatrix);o.aD(cu,zn,cu);const vl=o.b7([],cu);o.e6(vl,vl),o.cC(vl,vl,Us),cu=o.aD(cu,cu,Oc.globalMatrix);const Ri=Tt.renderPass==="light-beam",Pd=cs.paint.get("model-color-use-theme").constantOr("default")==="none",yc=Fc&o.ez.HasMapboxMeshFeatures,Ph=yc?0:Zi.evaluatedRMEA[0][2];for(let _o=0;_o=ra||$v>=ra}}const Hl=Tc.material;let z1;Hl.occlusionTexture&&Hl.occlusionTexture.offsetScale&&(z1=Hl.occlusionTexture.offsetScale,qm.defines.push("OCCLUSION_TEXTURE_TRANSFORM"));const B1=Tt.getOrCreateProgram("model",qm);!Nr&&Ks&&Ks.setupShadowsFromMatrix(Yi.tileModelMatrix,B1,Ks.useNormalOffset),Tt.uploadCommonUniforms(Zt,B1,null,qv);const Wc=Hl.pbrMetallicRoughness;Wc.metallicFactor=.9,Wc.roughnessFactor=.5;const rd=Ec(new Float32Array($x),new Float32Array(cu),new Float32Array(vl),new Float32Array(Oc.globalMatrix),Tt,Yi.opacity,Wc.baseColorFactor,Hl.emissiveFactor,Wc.metallicFactor,Wc.roughnessFactor,Hl,Ph,cs,[0,0,0],z1);!jm&&(Zi.hasTranslucentParts||Yi.opacity<1)&&B1.draw(Tt,Zt.gl.TRIANGLES,yn,qa.disabled,Ba.disabled,va.backCCW,rd,cs.id,Tc.vertexBuffer,Tc.indexBuffer,Tc.segments,cs.paint,Tt.transform.zoom,void 0,ff),B1.draw(Tt,Zt.gl.TRIANGLES,jm?_n:yn,qa.disabled,jm||Yi.opacity<1||Zi.hasTranslucentParts?Ba.alphaBlended:Ba.unblended,va.backCCW,rd,cs.id,Tc.vertexBuffer,Tc.indexBuffer,Tc.segments,cs.paint,Tt.transform.zoom,void 0,ff)}}}if(Tt._debugParams.show3DModelFootprints&&ta.size>0){const oo=Array.from(ta.keys()).sort();for(const Ni of oo){const{node:al,mvp:gc}=ta.get(Ni);QE(Tt,0,al,gc)}}}()}(R,N,T,z),void Je();if(Ke.type!=="model")return;const tt=Ke.getModels(),ut=[],lt=R.transform.getFreeCameraOptions().position,kt=o.bJ([],[lt.x,lt.y,lt.z],R.transform.worldSize);o.eo(kt,kt);const Nt=[],zt=[];let Yt=0;for(const Tt of tt){const Ss=N.getFeatureState("",Tt.id),cs={type:"Unknown",id:Tt.id,properties:Tt.featureProperties},Ns=T.paint.get("model-rotation").evaluate(cs,Ss),Zt=T.paint.get("model-scale").evaluate(cs,Ss),ns=T.paint.get("model-translation").evaluate(cs,Ss),bs=T.paint.get("model-opacity").evaluate(cs,Ss);JE(T,Tt.id,Ss,Tt.featureProperties,Tt.nodeOverrideNames,Tt.nodeOverrides),sk(T,Tt.id,Ss,Tt.featureProperties,Tt.materialOverrideNames,Tt.materialOverrides),Tt.nodeOverrides.size>0&&Tt.computeBoundsAndApplyParent(),Tt.computeModelMatrix(R,Ns,Zt,ns,ue,ee,!1);const Ks=o.b9([]),Es=o.e2(Tt.position.lat,R.transform.zoom),bn=o.bP([],[1,1,1/Es]);o.bx(Ks,Ks,kt),ut.push({zScaleMatrix:bn,negCameraPosMatrix:Ks});for(const mn of Tt.nodes)XE(R,mn,Tt.matrix,R.transform.expandedFarZProjMatrix,Yt,Nt,zt,Tt.materialOverrides,bs);Yt++}if(Nt.sort((Tt,Ss)=>Ss.depth-Tt.depth),R.renderPass!=="shadow"){if(R._debugParams.show3DModelFootprints){const Tt=R.transform.projMatrix,Ss=new Map,cs=(Zt,ns)=>{if(Zt.footprint){const bs=Zt.id||Zt.name||"footprint";if(!Ss.has(bs)){const Ks=o.aD([],Tt,ns);Ss.set(bs,{node:Zt,mvp:Ks})}}};for(const Zt of zt)cs(Zt.node,Zt.modelMatrix);for(const Zt of Nt)cs(Zt.node,Zt.modelMatrix);const Ns=Array.from(Ss.keys()).sort();for(const Zt of Ns){const{node:ns,mvp:bs}=Ss.get(Zt);QE(R,0,ns,bs)}}Op(R,T,Nt,zt,ut),Je()}else{for(const Tt of zt)i5(Tt.mesh,Tt.nodeModelMatrix,R,T);for(const Tt of Nt)i5(Tt.mesh,Tt.nodeModelMatrix,R,T);Je()}}},Dr={line:function(R,N,T){if(R.hasElevatedBuckets=!1,R.hasNonElevatedBuckets=!1,R._unevaluatedLayout.getValue("line-elevation-reference")!==void 0||R._unevaluatedLayout.getValue("line-z-offset")!==void 0){if(N){const z=N.getVisibleCoordinates();for(const W of z){const Q=N.getTile(W).getBucket(R);if(Q&&(Q.elevationType!=="none"?R.hasElevatedBuckets=!0:R.hasNonElevatedBuckets=!0,R.hasElevatedBuckets&&R.hasNonElevatedBuckets))break}}}else R.hasNonElevatedBuckets=!0},model:function(R,N,T){const z=N.getSource();if(!z.loaded())return;if(z.type==="vector"||z.type==="geojson")return void(T.modelManager&&T.modelManager.upload(T,YC(T,R)));if(z.type==="batched-model"||z.type!=="model")return;const W=z.getModels();for(const Q of W)Q.upload(T.context)},raster:function(R,N,T){const z=N.getSource();if(!(z instanceof no&&z.loaded()))return;const W=R.sourceLayer||z.rasterLayerIds&&z.rasterLayerIds[0];if(!W)return;const Q=R.paint.get("raster-array-band")||z.getInitialBand(W);if(Q==null)return;const ee=N.getIds().map(ue=>N.getTileByID(ue));for(const ue of ee)ue.updateNeeded(R.id,Q)&&z.prepareTile(ue,W,R.id,Q)},"raster-particle":function(R,N,T){const z=N.getSource();if(!(z instanceof no&&z.loaded()))return;const W=R.sourceLayer||z.rasterLayerIds&&z.rasterLayerIds[0];if(!W)return;const Q=R.paint.get("raster-particle-array-band")||z.getInitialBand(W);if(Q==null)return;const ee=N.getIds().map(ue=>N.getTileByID(ue));for(const ue of ee)ue.updateNeeded(R.id,Q)&&z.prepareTile(ue,W,R.id,Q)}},Va={fill:Vb},to={fill:function(R,N,T,z){if(!T.layout||T.layout.get("fill-elevation-reference")==="none"||T.paint.get("fill-opacity").constantOr(1)===0)return;const W=R.context.gl,Q=new Hr(W.LEQUAL,Hr.ReadOnly,R.depthRangeFor3D),ee=new qa({func:W.ALWAYS,mask:255},255,255,W.KEEP,W.KEEP,W.REPLACE),ue=R.transform.getFreeCameraOptions().position,_e=R.getOrCreateProgram("elevatedStructuresDepthReconstruct");for(const Ee of z){const Ie=N.getTile(Ee),Je=Ie.getBucket(T);if(!Je)continue;const Ke=Je.elevatedStructures;if(!Ke||Ke.depthSegments.segments[0].primitiveLength===0)continue;const tt=L1(Ee.toUnwrapped(),ue),ut=R.translatePosMatrix(Ee.projMatrix,Ie,T.paint.get("fill-translate"),T.paint.get("fill-translate-anchor")),lt=Ki(ut,tt,0,1,0);_e.draw(R,W.TRIANGLES,Q,ee,Ba.disabled,va.disabled,lt,T.id,Ke.vertexBuffer,Ke.indexBuffer,Ke.depthSegments,T.paint,R.transform.zoom)}}};class nc{constructor(N,T,z,W,Q){this.context=new wm(N,T),this.transform=z,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 ee=["fill","line","symbol","circle","heatmap","fill-extrusion","building","raster","raster-particle","hillshade","model","background","sky"];for(const _e of ee)this._debugParams.enabledLayers[_e]=!0;for(const _e of ee);this.occlusionParams=new VL,this.setup(),this.numSublayers=Dc.maxUnderzooming+Dc.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 ud(this),this._wireframeDebugCache=new $L,this.renderDefaultNorthPole=!0,this.renderDefaultSouthPole=!0,this.layersWithOcclusionOpacity=[];const ue=new o.q({width:1,height:1},Uint8Array.of(0,0,0,0));this.emptyDepthTexture=new o.T(this.context,ue,N.RGBA8),this._clippingActiveLastFrame=!1,this.scaleFactor=W,this.maxFrontCutoffRawStart=0,this.worldview=Q,this._forceEmissiveMode=!1,this.emissiveMode="constant"}updateTerrain(N,T){const z=!!N&&!!N.terrain&&this.transform.projection.supportsTerrain;if(!(z||this._terrain&&this._terrain.enabled))return;this._terrain||(this._terrain=new Cs(this,N));const W=this._terrain;this.transform.elevation=z?W:null,W.update(N,this.transform,T),this.transform.elevation&&!W.enabled&&(this.transform.elevation=null)}_updateFog(N){const T=N.fog;if(!T||this.transform.projection.name==="globe"||T.getOpacity(this.transform.pitch)<1||T.properties.get("horizon-blend")<.03)return void(this.transform.fogCullDistSq=null);const[z,W]=T.getFovAdjustedRange(this.transform._fov);if(z>W)return void(this.transform.fogCullDistSq=null);const Q=z+.78*(W-z);this.transform.fogCullDistSq=Q*Q}get terrain(){return this.transform._terrainEnabled()&&this._terrain&&this._terrain.enabled||this._forceTerrainMode?this._terrain:null}get forceTerrainMode(){return this._forceTerrainMode}set forceTerrainMode(N){N&&!this._terrain&&(this._terrain=new Cs(this,this.style)),this._forceTerrainMode=N}get shadowRenderer(){return this._shadowRenderer&&this._shadowRenderer.enabled?this._shadowRenderer:null}get wireframeDebugCache(){return this._wireframeDebugCache}resize(N,T){if(this.width=N*o.o.devicePixelRatio,this.height=T*o.o.devicePixelRatio,this.context.viewport.set([0,0,this.width,this.height]),this.style)for(const z of this.style.order)this.style._mergedLayers[z].resize()}setup(){const N=this.context,T=new o.dB;T.emplaceBack(0,0),T.emplaceBack(o.an,0),T.emplaceBack(0,o.an),T.emplaceBack(o.an,o.an),this.tileExtentBuffer=N.createVertexBuffer(T,o.dx.members),this.tileExtentSegments=o.dy.simpleSegment(0,0,4,2);const z=new o.dB;z.emplaceBack(0,0),z.emplaceBack(o.an,0),z.emplaceBack(0,o.an),z.emplaceBack(o.an,o.an),this.debugBuffer=N.createVertexBuffer(z,o.dx.members),this.debugSegments=o.dy.simpleSegment(0,0,4,5);const W=new o.dB;W.emplaceBack(-1,-1),W.emplaceBack(1,-1),W.emplaceBack(-1,1),W.emplaceBack(1,1),this.viewportBuffer=N.createVertexBuffer(W,o.dx.members),this.viewportSegments=o.dy.simpleSegment(0,0,4,2);const Q=new o.eH;Q.emplaceBack(0,0,0,0),Q.emplaceBack(o.an,0,o.an,0),Q.emplaceBack(0,o.an,0,o.an),Q.emplaceBack(o.an,o.an,o.an,o.an),this.mercatorBoundsBuffer=N.createVertexBuffer(Q,o.eI.members),this.mercatorBoundsSegments=o.dy.simpleSegment(0,0,4,2);const ee=new o.dC;ee.emplaceBack(0,1,2),ee.emplaceBack(2,1,3),this.quadTriangleIndexBuffer=N.createIndexBuffer(ee);const ue=new o.eJ;for(const Ee of[0,1,3,2,0])ue.emplaceBack(Ee);this.debugIndexBuffer=N.createIndexBuffer(ue),this.emptyTexture=new o.T(N,new o.q({width:1,height:1},Uint8Array.of(0,0,0,0)),N.gl.RGBA8),this.identityMat=o.bb();const _e=this.context.gl;this.stencilClearMode=new qa({func:_e.ALWAYS,mask:0},0,255,_e.ZERO,_e.ZERO,_e.ZERO),this.loadTimeStamps.push(performance.now())}getMercatorTileBoundsBuffers(){return{tileBoundsBuffer:this.mercatorBoundsBuffer,tileBoundsIndexBuffer:this.quadTriangleIndexBuffer,tileBoundsSegments:this.mercatorBoundsSegments}}getTileBoundsBuffers(N){return N._makeTileBoundsBuffers(this.context,this.transform.projection),N._tileBoundsBuffer?{tileBoundsBuffer:N._tileBoundsBuffer,tileBoundsIndexBuffer:N._tileBoundsIndexBuffer,tileBoundsSegments:N._tileBoundsSegments}:this.getMercatorTileBoundsBuffers()}clearStencil(){const N=this.context.gl;this.nextStencilID=1,this.currentStencilSource=void 0,this._tileClippingMaskIDs={},this.getOrCreateProgram("clippingMask").draw(this,N.TRIANGLES,Hr.disabled,this.stencilClearMode,Ba.disabled,va.disabled,ft(this.identityMat),"$clipping",this.viewportBuffer,this.quadTriangleIndexBuffer,this.viewportSegments)}resetStencilClippingMasks(){this.terrain||(this.currentStencilSource=void 0,this._tileClippingMaskIDs={})}_renderTileClippingMasks(N,T,z){if(!T||this.currentStencilSource===T.id||!N.isTileClipped()||!z||z.length===0)return;if(this._tileClippingMaskIDs&&!this.terrain){let ue=!1;for(const _e of z)if(this._tileClippingMaskIDs[_e.key]===void 0){ue=!0;break}if(!ue)return}this.currentStencilSource=T.id;const W=this.context,Q=W.gl;this.nextStencilID+z.length>256&&this.clearStencil(),W.setColorMode(Ba.disabled),W.setDepthMode(Hr.disabled);const ee=this.getOrCreateProgram("clippingMask");this._tileClippingMaskIDs={};for(const ue of z){const _e=T.getTile(ue),Ee=this._tileClippingMaskIDs[ue.key]=this.nextStencilID++,{tileBoundsBuffer:Ie,tileBoundsIndexBuffer:Je,tileBoundsSegments:Ke}=this.getTileBoundsBuffers(_e);ee.draw(this,Q.TRIANGLES,Hr.disabled,new qa({func:Q.ALWAYS,mask:0},Ee,255,Q.KEEP,Q.KEEP,Q.REPLACE),Ba.disabled,va.disabled,ft(ue.projMatrix),"$clipping",Ie,Je,Ke)}}stencilModeFor3D(){this.currentStencilSource=void 0,this.nextStencilID+1>256&&this.clearStencil();const N=this.nextStencilID++,T=this.context.gl;return new qa({func:T.NOTEQUAL,mask:255},N,255,T.KEEP,T.KEEP,T.REPLACE)}stencilModeForClipping(N){if(this.terrain)return this.terrain.stencilModeForRTTOverlap(N);const T=this.context.gl;return new qa({func:T.EQUAL,mask:255},this._tileClippingMaskIDs[N.key],0,T.KEEP,T.KEEP,T.REPLACE)}stencilConfigForOverlap(N){const T=this.context.gl,z=N.sort((ee,ue)=>ue.overscaledZ-ee.overscaledZ),W=z[z.length-1].overscaledZ,Q=z[0].overscaledZ-W+1;if(Q>1){this.currentStencilSource=void 0,this.nextStencilID+Q>256&&this.clearStencil();const ee={};for(let ue=0;uethis._debugParams.fpsWindow&&this._fpsHistory.splice(0,this._fpsHistory.length-this._debugParams.fpsWindow),this._averageFPS=Math.round(this._fpsHistory.reduce((N,T)=>N+T/this._fpsHistory.length,0))}render(N,T){const z=o.o.now();this._dt=z-this._timeStamp,this._timeStamp=z,this._wireframeDebugCache.update(this.frameCounter),this._debugParams.continousRedraw=N.map.repaint,this.style=N,this.options=T;const W=this.style._mergedLayers,Q=!(!this.terrain||!this.terrain.enabled),ee=()=>this.style._getOrder(Q).filter(sn=>{const Fs=W[sn];return!(Fs.type in this._debugParams.enabledLayers)||this._debugParams.enabledLayers[Fs.type]});let ue=ee(),_e=!1,Ee=!1,Ie=null,Je=0,Ke=!1;for(const sn of ue){const Fs=W[sn];Fs.visibility!=="none"&&(Fs.type==="circle"?_e=!0:Fs.type==="building"?(Ie=Fs,++Je):Fs.type==="symbol"&&(Fs.hasOcclusionOpacityProperties?Ee=!0:_e=!0))}this.updateEmissiveMode();let tt=ue.map(sn=>W[sn]);const ut=this.style._mergedSourceCaches;this.imageManager=N.imageManager,this.modelManager=N.modelManager,this.symbolFadeChange=N.placement.symbolFadeChange(o.o.now()),this.imageManager.beginFrame();for(const sn in ut){const Fs=ut[sn];Fs.used&&(Fs.prepare(this.context),Fs.getSource().usedInConflation&&++Je)}let lt=!1;for(const sn of tt)sn.isHidden(this.transform.zoom)||(sn.type==="clip"&&(lt=!0),this.prepareLayer(sn));const kt={},Nt={},zt={},Yt={},Tt={};for(const sn in ut){const Fs=ut[sn];kt[sn]=Fs.getVisibleCoordinates(),Nt[sn]=kt[sn].slice().reverse(),zt[sn]=Fs.getVisibleCoordinates(!0).reverse(),Yt[sn]=Fs.getShadowCasterCoordinates(),Tt[sn]=Fs.sortCoordinatesByDistance(kt[sn])}const Ss=sn=>{const Fs=this.style.getLayerSourceCache(sn);return Fs&&Fs.used?Fs.getSource():null};if(Je||lt||this._clippingActiveLastFrame){const sn=[],Fs=[];let yn=0;for(const _n of tt)this.isSourceForClippingOrConflation(_n,Ss(_n))&&(sn.push(_n),Fs.push(yn)),yn++;if(sn&&(lt||sn.length>1)||this._clippingActiveLastFrame){lt=!1;const _n=[];for(let Tn=0;Tn0){const _n=Ss(Fs);_n&&(this.minCutoffZoom=Math.max(_n.minzoom,this.minCutoffZoom)),Fs.minzoom&&(this.minCutoffZoom=Math.max(Fs.minzoom,this.minCutoffZoom))}Fs.is3D(Q)&&(this.opaquePassCutoff===1/0&&(this.opaquePassCutoff=sn),this._lastOcclusionLayer=sn)}const cs=this.style&&this.style.fog;cs?(this._fogVisible=cs.getOpacity(this.transform.pitch)!==0,this._fogVisible&&this.transform.projection.name!=="globe"&&(this._fogVisible=cs.isVisibleOnFrustum(this.transform.cameraFrustum))):this._fogVisible=!1,this._cachedTileFogOpacities={},this.terrain&&(this.terrain.updateTileBinding(zt),this.opaquePassCutoff=0,ue=ee(),tt=ue.map(sn=>W[sn]));const Ns=this._shadowRenderer;if(Ns){Ns.updateShadowParameters(this.transform,this.style.directionalLight);for(const sn in ut)for(const Fs of kt[sn]){let yn={min:0,max:0};this.terrain&&(yn=this.terrain.getMinMaxForTile(Fs)||yn),Ns.addShadowReceiver(Fs.toUnwrapped(),yn.min,yn.max)}}this.transform.projection.name!=="globe"||this.globeSharedBuffers||(this.globeSharedBuffers=new o.eL(this.context)),this.style.fog&&this.transform.projection.supportsFog?(this._atmosphere||(this._atmosphere=new r5(this)),this._atmosphere.update(this)):this._atmosphere&&(this._atmosphere.destroy(),this._atmosphere=void 0);const Zt=this._debugParams.forceEnablePrecipitation||!(!this.style||!this.style.snow),ns=this._debugParams.forceEnablePrecipitation||!(!this.style||!this.style.rain);if(Zt&&!this._snow&&(this._snow=new Bs(this)),!Zt&&this._snow&&(this._snow.destroy(),delete this._snow),ns&&!this._rain&&(this._rain=new dt(this)),!ns&&this._rain&&(this._rain.destroy(),delete this._rain),this._snow&&this._snow.update(this),this._rain&&this._rain.update(this),Ie){this.buildingTileBorderManager||(this.buildingTileBorderManager=new Xg);const sn=this.style.getLayerSourceCache(Ie);this.buildingTileBorderManager.updateBorders(sn,Ie)}if(!Ye.has(this.context.gl))return;this.renderPass="offscreen";for(const sn of tt){const Fs=N.getLayerSourceCache(sn);if(!sn.hasOffscreenPass()||sn.isHidden(this.transform.zoom))continue;const yn=Fs?Nt[Fs.id]:void 0;(sn.type==="custom"||sn.type==="raster"||sn.type==="raster-particle"||sn.isSky()||yn&&yn.length)&&this.renderLayer(this,Fs,sn,yn)}this.depthRangeFor3D=[0,1-(tt.length+2)*this.numSublayers*this.depthEpsilon],this._shadowRenderer&&(this.renderPass="shadow",this._shadowRenderer.drawShadowPass(this.style,Yt)),this.context.bindFramebuffer.set(null),this.context.viewport.set([0,0,this.width,this.height]);const bs=this.transform.projection.name==="globe"||this.transform.isHorizonVisible(),Ks=(()=>{if(T.showOverdrawInspector)return o.aq.black;const sn=this.style.fog;if(sn&&this.transform.projection.supportsFog){const Fs=this.style.getLut(sn.scope);if(!bs){const yn=sn.properties.get("color-use-theme")==="none",_n=sn.properties.get("color").toNonPremultipliedRenderColor(yn?null:Fs).toArray01();return new o.aq(..._n)}if(bs){const yn=sn.properties.get("space-color-use-theme")==="none",_n=sn.properties.get("space-color").toNonPremultipliedRenderColor(yn?null:Fs).toArray01();return new o.aq(..._n)}}return o.aq.transparent})();if(this.context.clear({color:Ks,depth:1}),this.clearStencil(),this._showOverdrawInspector=T.showOverdrawInspector,this.renderPass="opaque",this.style.fog&&this.transform.projection.supportsFog&&this._atmosphere&&!this._showOverdrawInspector&&bs&&this._atmosphere.drawStars(this,this.style.fog),!this.terrain)for(this.currentLayer=ue.length-1;this.currentLayer>=0;this.currentLayer--){const sn=tt[this.currentLayer],Fs=N.getLayerSourceCache(sn);if(sn.isSky())continue;const yn=Fs?(sn.is3D(Q)?Tt:Nt)[Fs.id]:void 0;this._renderTileClippingMasks(sn,Fs,yn),this.renderLayer(this,Fs,sn,yn)}if(this.style.fog&&this.transform.projection.supportsFog&&this._atmosphere&&!this._showOverdrawInspector&&bs&&this._atmosphere.drawAtmosphereGlow(this,this.style.fog),this.renderPass="sky",(!this._atmosphere||o.al(this.transform.zoom)>0)&&(this.transform.projection.name==="globe"||this.transform.isHorizonVisible()))for(this.currentLayer=0;this.currentLayer{for(this.currentLayer=0;this.currentLayer=this._lastOcclusionLayer&&this.layersWithOcclusionOpacity.length>0){const yn=this.currentLayer;this.depthOcclusion=!0;for(const _n of this.layersWithOcclusionOpacity){this.currentLayer=_n;const Tn=tt[this.currentLayer],Nr=N.getLayerSourceCache(Tn),hr=Nr?Nt[Nr.id]:void 0;this.terrain||this._renderTileClippingMasks(Tn,Nr,Nr?kt[Nr.id]:void 0),this.renderLayer(this,Nr,Tn,hr)}this.depthOcclusion=!1,this.currentLayer=yn,this.renderPass="translucent",this.layersWithOcclusionOpacity=[]}++this.currentLayer}}if(this.terrain&&this.terrain.postRender(),this._snow&&this._snow.draw(this),this._rain&&this._rain.draw(this),this.options.showTileBoundaries||this.options.showQueryGeometry||this.options.showTileAABBs){let sn=null;tt.forEach(Fs=>{const yn=N.getLayerSourceCache(Fs);yn&&!Fs.isHidden(this.transform.zoom)&&yn.getVisibleCoordinates().length&&(!sn||sn.getSource().maxzoom0?T.pop():null}terrainRenderModeElevated(){return this.style&&!!this.style.getTerrain()&&!!this.terrain&&!this.terrain.renderingToTexture||this.forceTerrainMode}linearFloatFilteringSupported(){return this.context.extTextureFloatLinear!=null}currentGlobalDefines(N,T,z){const W=z===void 0?this.terrain&&this.terrain.renderingToTexture:z,Q=[];return this.style&&this.style.enable3dLights()&&(N==="globeRaster"||N==="terrainRaster"?(Q.push("LIGHTING_3D_MODE"),Q.push("LIGHTING_3D_ALPHA_EMISSIVENESS")):W||Q.push("LIGHTING_3D_MODE")),this.terrainRenderModeElevated()&&(Q.push("TERRAIN"),this.linearFloatFilteringSupported()&&Q.push("TERRAIN_DEM_FLOAT_FORMAT")),this.transform.projection.name==="globe"&&Q.push("GLOBE"),!this._fogVisible||W||T!==void 0&&!T||Q.push("FOG"),W&&Q.push("RENDER_TO_TEXTURE"),this._showOverdrawInspector&&Q.push("OVERDRAW_INSPECTOR"),Q}getOrCreateProgram(N,T){this.cache=this.cache||{};const z=T&&T.defines||[],W=T&&T.config,Q=this.currentGlobalDefines(N,T&&T.overrideFog,T&&T.overrideRtt).concat(z),ee=Xn.cacheKey(Gj[N],N,Q,W);return this.cache[ee]||(this.cache[ee]=new Xn(this.context,N,Gj[N],W,Dp[N],Q)),this.cache[ee]}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 N=this.context.gl;this.context.cullFace.set(!1),this.context.viewport.set([0,0,this.width,this.height]),this.context.blendEquation.set(N.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(N,T){if(this.style.enable3dLights()){const z=this.style.directionalLight,W=this.style.ambientLight;if(z&&W){const Q=((ee,ue,_e)=>{const Ee=ee.properties.get("direction"),Ie=ee.properties.get("color-use-theme")==="none",Je=ee.properties.get("color").toNonPremultipliedRenderColor(Ie?null:_e.getLut(ee.scope)).toArray01(),Ke=ee.properties.get("intensity"),tt=ue.properties.get("color-use-theme")==="none",ut=ue.properties.get("color").toNonPremultipliedRenderColor(tt?null:_e.getLut(ue.scope)).toArray01(),lt=ue.properties.get("intensity"),kt=[Ee.x,Ee.y,Ee.z],Nt=o.dD(ut,lt),zt=o.dD(Je,Ke);return{u_lighting_ambient_color:Nt,u_lighting_directional_dir:kt,u_lighting_directional_color:zt,u_ground_radiance:Rs(kt,zt,Nt)}})(z,W,this.style);T.setLightsUniformValues(N,Q)}}}uploadCommonUniforms(N,T,z,W,Q){if(this.uploadCommonLightUniforms(N,T),this.terrain&&this.terrain.renderingToTexture)return;const ee=this.style.fog;if(ee){const ue=ee.getOpacity(this.transform.pitch),_e=((Ee,Ie,Je,Ke,tt,ut,lt,kt,Nt,zt,Yt,Tt)=>{const Ss=Ee.transform,cs=Ie.properties.get("color-use-theme")==="none",Ns=Ie.properties.get("color").toNonPremultipliedRenderColor(cs?null:Ee.style.getLut(Ie.scope)).toArray01();Ns[3]=Ke;const Zt=Ee.frameCounter/1e3%1,[ns,bs]=Ie.properties.get("vertical-range");return{u_fog_matrix:Je?Ss.calculateFogTileMatrix(Je):Tt||Ee.identityMat,u_fog_range:Ie.getFovAdjustedRange(Ss._fov),u_fog_color:Ns,u_fog_horizon_blend:Ie.properties.get("horizon-blend"),u_fog_vertical_limit:[Math.min(ns,bs),bs],u_fog_temporal_offset:Zt,u_frustum_tl:tt,u_frustum_tr:ut,u_frustum_br:lt,u_frustum_bl:kt,u_globe_pos:Nt,u_globe_radius:zt,u_viewport:Yt,u_globe_transition:o.al(Ss.zoom),u_is_globe:+(Ss.projection.name==="globe")}})(this,ee,z,ue,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],W);T.setFogUniformValues(N,_e)}Q&&T.setCutoffUniformValues(N,Q.uniformValues)}setTileLoadedFlag(N){this.tileLoaded=N}saveCanvasCopy(){const N=this.canvasCopy();N&&(this.frameCopies.push(N),this.tileLoaded=!1)}canvasCopy(){const N=this.context.gl,T=N.createTexture();return N.bindTexture(N.TEXTURE_2D,T),N.copyTexImage2D(N.TEXTURE_2D,0,N.RGBA,0,0,N.drawingBufferWidth,N.drawingBufferHeight,0),T}getCanvasCopiesAndTimestamps(){return{canvasCopies:this.frameCopies,timeStamps:this.loadTimeStamps}}averageElevationNeedsEasing(){if(!this.transform._elevation)return!1;const N=this.style&&this.style.fog;return!!N&&N.getOpacity(this.transform.pitch)!==0}getBackgroundTiles(){const N=this._backgroundTiles,T=this._backgroundTiles={},z=this.transform.coveringTiles({tileSize:512});for(const W of z)T[W.key]=N[W.key]||new o.b0(W,512,this.transform.tileZoom,this,void 0,this.worldview);return T}clearBackgroundTiles(){this._backgroundTiles={}}isSourceForClippingOrConflation(N,T){return!(!N.is3D(!(!this.terrain||!this.terrain.enabled))||N.type!=="clip"&&N.type!=="building"&&(N.minzoom&&N.minzoom>this.transform.zoom||(this.style._clipLayerPresent||N.sourceLayer!=="building"&&N.sourceLayer!=="procedural_buildings")&&(!T||T.type!=="batched-model")))}isTileAffectedByFog(N){if(!this.style||!this.style.fog)return!1;if(this.transform.projection.name==="globe")return!0;let T=this._cachedTileFogOpacities[N.key];return T||(this._cachedTileFogOpacities[N.key]=T=this.style.fog.getOpacityForTile(N)),T[0]>=ra||T[1]>=ra}setupDepthForOcclusion(N,T,z){const W=this.context,Q=W.gl,ee=!!z;var ue;z||(z={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}),W.activeTexture.set(Q.TEXTURE3),N&&this.depthFBO&&this.depthTexture?(this.depthTexture.bind(Q.NEAREST,Q.CLAMP_TO_EDGE),z.u_depth_size_inv=[1/this.depthFBO.width,1/this.depthFBO.height],z.u_depth_range_unpack=[2/((ue=this.depthRangeFor3D)[1]-ue[0]),-1-2*ue[0]/(ue[1]-ue[0])],z.u_occluder_half_size=.5*this.occlusionParams.occluderSize,z.u_occlusion_depth_offset=this.occlusionParams.depthOffset):this.emptyDepthTexture.bind(Q.NEAREST,Q.CLAMP_TO_EDGE),W.activeTexture.set(Q.TEXTURE0),ee||T.setTerrainUniformValues(W,z)}updateEmissiveMode(){if(this._forceEmissiveMode)return;const N=this.style.hasDataDrivenEmissiveStrength();this.emissiveMode=N?this.context.extBlendFuncExtended?"dual-source-blending":"mrt-fallback":"constant"}}function Di(R,N){let T=!1,z=null;const W=()=>{z=null,T&&(R(),z=setTimeout(W,N),T=!1)};return()=>(T=!0,z||W(),z)}class Mh{constructor(N){this._hashName=N&&encodeURIComponent(N),o.aZ(["_getCurrentHash","_onHashChange","_updateHash"],this),this._updateHash=Di(this._updateHashUnthrottled.bind(this),300)}addTo(N){return this._map=N,window.addEventListener("hashchange",this._onHashChange,!1),N.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 N=this._map;if(!N)return"";const T=rc(N);if(this._hashName){const z=this._hashName;let W=!1;const Q=location.hash.slice(1).split("&").map(ee=>{const ue=ee.split("=")[0];return ue===z?(W=!0,`${ue}=${T}`):ee}).filter(ee=>ee);return W||Q.push(`${z}=${T}`),`#${Q.join("&")}`}return`#${T}`}_getCurrentHash(){const N=location.hash.replace("#","");if(this._hashName){let T;return N.split("&").map(z=>z.split("=")).forEach(z=>{z[0]===this._hashName&&(T=z)}),(T&&T[1]||"").split("/")}return N.split("/")}_onHashChange(){const N=this._map;if(!N)return!1;const T=this._getCurrentHash();if(T.length>=3&&!T.some(z=>isNaN(Number(z)))){const z=N.dragRotate.isEnabled()&&N.touchZoomRotate.isEnabled()?+(T[3]||0):N.getBearing();return N.jumpTo({center:[+T[2],+T[1]],zoom:+T[0],bearing:z,pitch:+(T[4]||0)}),!0}return!1}_updateHashUnthrottled(){history.replaceState(history.state,"",location.href.replace(/(#.+)?$/,this.getHashString()))}}function rc(R,N){const T=R.getCenter(),z=Math.round(100*R.getZoom())/100,W=Math.ceil((z*Math.LN2+Math.log(512/360/.5))/Math.LN10),Q=Math.pow(10,W),ee=Math.round(T.lng*Q)/Q,ue=Math.round(T.lat*Q)/Q,_e=R.getBearing(),Ee=R.getPitch();let Ie=N?`/${ee}/${ue}/${z}`:`${z}/${ue}/${ee}`;return(_e||Ee)&&(Ie+="/"+Math.round(10*_e)/10),Ee&&(Ie+=`/${Math.round(Ee)}`),Ie}const qx={linearity:.3,easing:o.eN(0,0,.3,1)},Wy=Object.assign({deceleration:2500,maxSpeed:1400},qx),Tr=Object.assign({deceleration:20,maxSpeed:1400},qx),En=Object.assign({deceleration:1e3,maxSpeed:360},qx),Hn=Object.assign({deceleration:1e3,maxSpeed:90},qx);class Vi{constructor(N){this._map=N,this.clear()}clear(){this._inertiaBuffer=[]}record(N){this._drainInertiaBuffer(),this._inertiaBuffer.push({time:o.o.now(),settings:N})}_drainInertiaBuffer(){const N=this._inertiaBuffer,T=o.o.now();for(;N.length>0&&T-N[0].time>160;)N.shift()}_onMoveEnd(N){if(this._map._prefersReducedMotion()||(this._drainInertiaBuffer(),this._inertiaBuffer.length<2))return;const T={zoom:0,bearing:0,pitch:0,pan:new o.P(0,0),pinchAround:void 0,around:void 0};for(const{settings:Q}of this._inertiaBuffer)T.zoom+=Q.zoomDelta||0,T.bearing+=Q.bearingDelta||0,T.pitch+=Q.pitchDelta||0,Q.panDelta&&T.pan._add(Q.panDelta),Q.around&&(T.around=Q.around),Q.pinchAround&&(T.pinchAround=Q.pinchAround);const z=this._inertiaBuffer[this._inertiaBuffer.length-1].time-this._inertiaBuffer[0].time,W={};if(T.pan.mag()){const Q=fl(T.pan.mag(),z,Object.assign({},Wy,N||{}));W.offset=T.pan.mult(Q.amount/T.pan.mag()),W.center=this._map.transform.center,ao(W,Q)}if(T.zoom){const Q=fl(T.zoom,z,Tr);W.zoom=this._map.transform.zoom+Q.amount,ao(W,Q)}if(T.bearing){const Q=fl(T.bearing,z,En);W.bearing=this._map.transform.bearing+o.aC(Q.amount,-179,179),ao(W,Q)}if(T.pitch){const Q=fl(T.pitch,z,Hn);W.pitch=this._map.transform.pitch+Q.amount,ao(W,Q)}if(W.zoom||W.bearing){const Q=T.pinchAround===void 0?T.around:T.pinchAround;W.around=Q?this._map.unproject(Q):this._map.getCenter()}return this.clear(),W.noMoveStart=!0,W}}function ao(R,N){(!R.duration||R.durationT.unproject(_e)),ue=Q.reduce((_e,Ee,Ie,Je)=>_e.add(Ee.div(Je.length)),new o.P(0,0));super(N,{points:Q,point:ue,lngLats:ee,lngLat:T.unproject(ue),originalEvent:z}),this._defaultPrevented=!1}}class zp extends o.C{preventDefault(){this._defaultPrevented=!0}get defaultPrevented(){return this._defaultPrevented}constructor(N,T){super("wheel",{originalEvent:T}),this._defaultPrevented=!1}}class Sd{constructor(N,T){this._map=N,this._clickTolerance=T.clickTolerance}reset(){this._mousedownPos=void 0}wheel(N){return this._firePreventable(new zp(this._map,N))}mousedown(N,T){return this._mousedownPos=T,this._firePreventable(new yo(N.type,this._map,N))}mouseup(N){this._map.fire(new yo(N.type,this._map,N))}preclick(N){const T=new MouseEvent("preclick",N);this._map.fire(new yo(T.type,this._map,T))}click(N,T){this._mousedownPos&&this._mousedownPos.dist(T)>=this._clickTolerance||(this.preclick(N),this._map.fire(new yo(N.type,this._map,N)))}dblclick(N){return this._firePreventable(new yo(N.type,this._map,N))}mouseover(N){this._map.fire(new yo(N.type,this._map,N))}mouseout(N){this._map.fire(new yo(N.type,this._map,N))}touchstart(N){return this._firePreventable(new Zl(N.type,this._map,N))}touchmove(N){this._map.fire(new Zl(N.type,this._map,N))}touchend(N){this._map.fire(new Zl(N.type,this._map,N))}touchcancel(N){this._map.fire(new Zl(N.type,this._map,N))}_firePreventable(N){if(this._map.fire(N),N.defaultPrevented)return{}}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class Yb{constructor(N){this._map=N}reset(){this._delayContextMenu=!1,this._contextMenuEvent=void 0}mousemove(N){this._map.fire(new yo(N.type,this._map,N))}mousedown(){this._delayContextMenu=!0}mouseup(){this._delayContextMenu=!1,this._contextMenuEvent&&(this._map.fire(new yo("contextmenu",this._map,this._contextMenuEvent)),delete this._contextMenuEvent)}contextmenu(N){this._delayContextMenu?this._contextMenuEvent=N:this._map.fire(new yo(N.type,this._map,N)),this._map.listens("contextmenu")&&N.preventDefault()}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class GL{constructor(N,T){this._map=N,this._el=N.getCanvasContainer(),this._container=N.getContainer(),this._clickTolerance=T.clickTolerance||1}isEnabled(){return!!this._enabled}isActive(){return!!this._active}enable(){this.isEnabled()||(this._enabled=!0)}disable(){this.isEnabled()&&(this._enabled=!1)}mousedown(N,T){this.isEnabled()&&N.shiftKey&&N.button===0&&(S(),this._startPos=this._lastPos=T,this._active=!0)}mousemoveWindow(N,T){if(!this._active)return;const z=T,W=this._startPos,Q=this._lastPos;if(!W||!Q||Q.equals(z)||!this._box&&z.dist(W){this._box&&(this._box.style.transform=`translate(${ee}px,${_e}px)`,this._box.style.width=ue-ee+"px",this._box.style.height=Ee-_e+"px")})}mouseupWindow(N,T){if(!this._active)return;const z=this._startPos,W=T;if(z&&N.button===0){if(this.reset(),P(),z.x!==W.x||z.y!==W.y)return this._map.fire(new o.C("boxzoomend",{originalEvent:N})),{cameraAnimation:Q=>Q.fitScreenCoordinates(z,W,this._map.getBearing(),{linear:!1})};this._fireEvent("boxzoomcancel",N)}}keydown(N){this._active&&N.keyCode===27&&(this.reset(),this._fireEvent("boxzoomcancel",N))}blur(){this.reset()}reset(){this._active=!1,this._container.classList.remove("mapboxgl-crosshair"),this._box&&(this._box.remove(),this._box=null),C(),delete this._startPos,delete this._lastPos}_fireEvent(N,T){return this._map.fire(new o.C(N,{originalEvent:T}))}}function WL(R,N){const T={};for(let z=0;zthis.numTouches)&&(this.aborted=!0),this.aborted||(this.startTime===0&&(this.startTime=N.timeStamp),z.length===this.numTouches&&(this.centroid=function(W){const Q=new o.P(0,0);for(const ee of W)Q._add(ee);return Q.div(W.length)}(T),this.touches=WL(z,T)))}touchmove(N,T,z){if(this.aborted||!this.centroid)return;const W=WL(z,T);for(const Q in this.touches){const ee=W[Q];(!ee||ee.dist(this.touches[Q])>30)&&(this.aborted=!0)}}touchend(N,T,z){if((!this.centroid||N.timeStamp-this.startTime>500)&&(this.aborted=!0),z.length===0){const W=!this.aborted&&this.centroid;if(this.reset(),W)return W}}}class i2{constructor(N){this.singleTap=new Zb(N),this.numTaps=N.numTaps,this.reset()}reset(){this.lastTime=1/0,this.lastTap=void 0,this.count=0,this.singleTap.reset()}touchstart(N,T,z){this.singleTap.touchstart(N,T,z)}touchmove(N,T,z){this.singleTap.touchmove(N,T,z)}touchend(N,T,z){const W=this.singleTap.touchend(N,T,z);if(W){const Q=N.timeStamp-this.lastTime<500,ee=!this.lastTap||this.lastTap.dist(W)<30;if(Q&&ee||this.reset(),this.count++,this.lastTime=N.timeStamp,this.lastTap=W,this.count===this.numTaps)return this.reset(),W}}}class nT{constructor(){this._zoomIn=new i2({numTouches:1,numTaps:2}),this._zoomOut=new i2({numTouches:2,numTaps:1}),this.reset()}reset(){this._active=!1,this._zoomIn.reset(),this._zoomOut.reset()}touchstart(N,T,z){this._zoomIn.touchstart(N,T,z),this._zoomOut.touchstart(N,T,z)}touchmove(N,T,z){this._zoomIn.touchmove(N,T,z),this._zoomOut.touchmove(N,T,z)}touchend(N,T,z){const W=this._zoomIn.touchend(N,T,z),Q=this._zoomOut.touchend(N,T,z);return W?(this._active=!0,N.preventDefault(),setTimeout(()=>this.reset(),0),{cameraAnimation:ee=>ee.easeTo({duration:300,zoom:ee.getZoom()+1,around:ee.unproject(W)},{originalEvent:N})}):Q?(this._active=!0,N.preventDefault(),setTimeout(()=>this.reset(),0),{cameraAnimation:ee=>ee.easeTo({duration:300,zoom:ee.getZoom()-1,around:ee.unproject(Q)},{originalEvent:N})}):void 0}touchcancel(){this.reset()}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}const Az=0,vK=2,bK={[Az]:1,[vK]:2},rk={Control:"ctrlKey",Alt:"altKey",Shift:"shiftKey",Meta:"metaKey"};class KL{constructor(N){this.reset(),this._clickTolerance=N.clickTolerance||1}blur(){this.reset()}reset(){this._active=!1,this._moved=!1,this._lastPoint=void 0,this._eventButton=void 0}_correctButton(N,T){return!1}_move(N,T){return{}}mousedown(N,T){if(this._lastPoint)return;const z=D(N);this._correctButton(N,z)&&(this._lastPoint=T,this._eventButton=z)}mousemoveWindow(N,T){const z=this._lastPoint;if(z){if(N.preventDefault(),this._eventButton!=null&&function(W,Q){const ee=bK[Q];return W.buttons===void 0||(W.buttons&ee)!==ee}(N,this._eventButton))this.reset();else if(this._moved||!(T.dist(z)0&&(this._active=!0);const W=WL(z,T),Q=new o.P(0,0),ee=new o.P(0,0);let ue=0;for(const Ee in W){const Ie=W[Ee],Je=this._touches[Ee];Je&&(Q._add(Ie),ee._add(Ie.sub(Je)),ue++,W[Ee]=Ie)}if(this._touches=W,ue{this._alertContainer.classList.remove("mapboxgl-touch-pan-blocker-show"),this._alertContainer.removeAttribute("role")},500)}}class ZL{constructor(){this.reset()}reset(){this._active=!1,this._firstTwoTouches=void 0}_start(N){}_move(N,T,z){return{}}touchstart(N,T,z){this._firstTwoTouches||z.length<2||(this._firstTwoTouches=[z[0].identifier,z[1].identifier],this._start([T[0],T[1]]))}touchmove(N,T,z){const W=this._firstTwoTouches;if(!W)return;N.preventDefault();const[Q,ee]=W,ue=Ju(z,T,Q),_e=Ju(z,T,ee);if(!ue||!_e)return;const Ee=this._aroundCenter?null:ue.add(_e).div(2);return this._move([ue,_e],Ee,N)}touchend(N,T,z){if(!this._firstTwoTouches)return;const[W,Q]=this._firstTwoTouches,ee=Ju(z,T,W),ue=Ju(z,T,Q);ee&&ue||(this._active&&P(),this.reset())}touchcancel(){this.reset()}enable(N){this._enabled=!0,this._aroundCenter=!!N&&N.around==="center"}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}function Ju(R,N,T){for(let z=0;zMath.abs(R.x)}class jK extends ZL{constructor(N){super(),this._map=N}reset(){super.reset(),this._valid=void 0,this._firstMove=void 0,this._lastPoints=void 0}_start(N){this._lastPoints=N,XL(N[0].sub(N[1]))&&(this._valid=!1)}_move(N,T,z){const W=this._lastPoints;if(!W)return;const Q=N[0].sub(W[0]),ee=N[1].sub(W[1]);return this._map._cooperativeGestures&&!o.eO()&&z.touches.length<3||(this._valid=this.gestureBeginsVertically(Q,ee,z.timeStamp),!this._valid)?void 0:(this._lastPoints=N,this._active=!0,{pitchDelta:(Q.y+ee.y)/2*-.5})}gestureBeginsVertically(N,T,z){if(this._valid!==void 0)return this._valid;const W=N.mag()>=2,Q=T.mag()>=2;if(!W&&!Q)return;if(!W||!Q)return this._firstMove==null&&(this._firstMove=z),z-this._firstMove<100&&void 0;const ee=N.y>0==T.y>0;return XL(N)&&XL(T)&&ee}}const NK={panStep:100,bearingStep:15,pitchStep:10};class JC{constructor(){const N=NK;this._panStep=N.panStep,this._bearingStep=N.bearingStep,this._pitchStep=N.pitchStep,this._rotationDisabled=!1}blur(){this.reset()}reset(){this._active=!1}keydown(N){if(N.altKey||N.ctrlKey||N.metaKey)return;let T=0,z=0,W=0,Q=0,ee=0;switch(N.keyCode){case 61:case 107:case 171:case 187:T=1;break;case 189:case 109:case 173:T=-1;break;case 37:N.shiftKey?z=-1:(N.preventDefault(),Q=-1);break;case 39:N.shiftKey?z=1:(N.preventDefault(),Q=1);break;case 38:N.shiftKey?W=1:(N.preventDefault(),ee=-1);break;case 40:N.shiftKey?W=-1:(N.preventDefault(),ee=1);break;default:return}return this._rotationDisabled&&(z=0,W=0),{cameraAnimation:ue=>{const _e=ue.getZoom();ue.easeTo({duration:300,easeId:"keyboardHandler",easing:kK,zoom:T?Math.round(_e)+T*(N.shiftKey?2:1):_e,bearing:ue.getBearing()+z*this._bearingStep,pitch:ue.getPitch()+W*this._pitchStep,offset:[-Q*this._panStep,-ee*this._panStep],center:ue.getCenter()},{originalEvent:N})}}}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 kK(R){return R*(2-R)}const e3=4.000244140625,SK=1/450;class Pz{constructor(N,T){this._map=N,this._el=N.getCanvasContainer(),this._handler=T,this._delta=0,this._lastDelta=0,this._defaultZoomRate=.01,this._wheelZoomRate=SK,o.aZ(["_onTimeout","_addScrollZoomBlocker","_showBlockerAlert"],this)}setZoomRate(N){this._defaultZoomRate=N}setWheelZoomRate(N){this._wheelZoomRate=N}isEnabled(){return!!this._enabled}isActive(){return this._active||this._finishTimeout!==void 0}isZooming(){return!!this._zooming}enable(N){this.isEnabled()||(this._enabled=!0,this._aroundCenter=!!N&&N.around==="center",this._map._cooperativeGestures&&this._addScrollZoomBlocker())}disable(){this.isEnabled()&&(this._enabled=!1,this._map._cooperativeGestures&&(clearTimeout(this._alertTimer),this._alertContainer.remove()))}wheel(N){if(!this.isEnabled())return;if(this._map._cooperativeGestures){if(!(N.ctrlKey||N.metaKey||this.isZooming()||o.eO()))return void this._showBlockerAlert();this._alertContainer.style.visibility!=="hidden"&&(this._alertContainer.style.visibility="hidden",clearTimeout(this._alertTimer))}let T=N.deltaMode===WheelEvent.DOM_DELTA_LINE?40*N.deltaY:N.deltaY;const z=o.o.now(),W=z-(this._lastWheelEventTime||0);this._lastWheelEventTime=z,T!==0&&T%e3===0?this._type="wheel":T!==0&&Math.abs(T)<4?this._type="trackpad":W>400?(this._type=null,this._lastValue=T,this._timeout=window.setTimeout(this._onTimeout,40,N)):this._type||(this._type=Math.abs(W*T)<200?"trackpad":"wheel",this._timeout&&(clearTimeout(this._timeout),this._timeout=null,T+=this._lastValue)),N.shiftKey&&T&&(T/=4),this._type&&(this._lastWheelEvent=N,this._delta-=T,this._active||this._start(N)),N.preventDefault()}_onTimeout(N){this._type="wheel",this._delta-=this._lastValue,this._active||this._start(N)}_start(N){if(!this._delta)return;this._frameId&&(this._frameId=null),this._active=!0,this.isZooming()||(this._zooming=!0),this._finishTimeout&&(clearTimeout(this._finishTimeout),delete this._finishTimeout);const T=M(this._el,N);this._aroundPoint=this._aroundCenter?this._map.transform.centerPoint:T,this._aroundCoord=this._map.transform.pointCoordinate3D(this._aroundPoint),this._targetZoom=void 0,this._frameId||(this._frameId=!0,this._handler._triggerRenderFrame())}renderFrame(){if(!this._frameId||(this._frameId=null,!this.isActive()))return;const N=this._map.transform;this._type==="wheel"&&N.projection.wrap&&(N._center.lng>=180||N._center.lng<=-180)&&(this._prevEase=null,this._easing=null,this._lastWheelEvent=null,this._lastWheelEventTime=0);const T=()=>N._terrainEnabled()&&this._aroundCoord?N.computeZoomRelativeTo(this._aroundCoord):N.zoom;if(this._delta!==0){const Ee=this._type==="wheel"&&Math.abs(this._delta)>e3?this._wheelZoomRate:this._defaultZoomRate;let Ie=2/(1+Math.exp(-Math.abs(this._delta*Ee)));this._delta<0&&Ie!==0&&(Ie=1/Ie);const Je=T(),Ke=Math.pow(2,Je),tt=typeof this._targetZoom=="number"?N.zoomScale(this._targetZoom):Ke;this._targetZoom=Math.min(N.maxZoom,Math.max(N.minZoom,N.scaleZoom(tt*Ie))),this._type==="wheel"&&(this._startZoom=Je,this._easing=this._smoothOutEasing(200)),this._lastDelta=this._delta,this._delta=0}const z=typeof this._targetZoom=="number"?this._targetZoom:T(),W=this._startZoom,Q=this._easing;let ee,ue=!1;if(this._type==="wheel"&&W&&Q){const Ee=Math.min((o.o.now()-this._lastWheelEventTime)/200,1),Ie=Q(Ee);ee=o.am(W,z,Ie),Ee<1?this._frameId||(this._frameId=!0):ue=!0}else ee=z,ue=!0;this._active=!0,ue&&(this._active=!1,this._finishTimeout=window.setTimeout(()=>{this._zooming=!1,this._handler._triggerRenderFrame(),delete this._targetZoom,delete this._finishTimeout},200));let _e=ee-T();return _e*this._lastDelta<0&&(_e=0),{noInertia:!0,needsRenderFrame:!ue,zoomDelta:_e,around:this._aroundPoint,aroundCoord:this._aroundCoord,originalEvent:this._lastWheelEvent}}_smoothOutEasing(N){let T=o.eP;if(this._prevEase){const z=this._prevEase,W=(o.o.now()-z.start)/z.duration,Q=z.easing(W+.01)-z.easing(W),ee=.27/Math.sqrt(Q*Q+1e-4)*.01,ue=Math.sqrt(.0729-ee*ee);T=o.eN(ee,ue,.25,1)}return this._prevEase={start:o.o.now(),duration:N,easing:T},T}blur(){this.reset()}reset(){this._active=!1}_addScrollZoomBlocker(){this._map&&!this._alertContainer&&(this._alertContainer=y("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 Lz{constructor(N,T){this._clickZoom=N,this._tapZoom=T}enable(){this._clickZoom.enable(),this._tapZoom.enable()}disable(){this._clickZoom.disable(),this._tapZoom.disable()}isEnabled(){return this._clickZoom.isEnabled()&&this._tapZoom.isEnabled()}isActive(){return this._clickZoom.isActive()||this._tapZoom.isActive()}}class Iz{constructor(){this.reset()}reset(){this._active=!1}blur(){this.reset()}dblclick(N,T){return N.preventDefault(),{cameraAnimation:z=>{z.easeTo({duration:300,zoom:z.getZoom()+(N.shiftKey?-1:1),around:z.unproject(T)},{originalEvent:N})}}}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class pie{constructor(){this._tap=new i2({numTouches:1,numTaps:1}),this.reset()}reset(){this._active=!1,this._swipePoint=void 0,this._swipeTouch=0,this._tapTime=0,this._tap.reset()}touchstart(N,T,z){this._swipePoint||(this._tapTime&&N.timeStamp-this._tapTime>500&&this.reset(),this._tapTime?z.length>0&&(this._swipePoint=T[0],this._swipeTouch=z[0].identifier):this._tap.touchstart(N,T,z))}touchmove(N,T,z){if(this._tapTime){if(this._swipePoint){if(z[0].identifier!==this._swipeTouch)return;const W=T[0],Q=W.y-this._swipePoint.y;return this._swipePoint=W,N.preventDefault(),this._active=!0,{zoomDelta:Q/128}}}else this._tap.touchmove(N,T,z)}touchend(N,T,z){this._tapTime?this._swipePoint&&z.length===0&&this.reset():this._tap.touchend(N,T,z)&&(this._tapTime=N.timeStamp)}touchcancel(){this.reset()}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class CK{constructor(N,T,z){this._el=N,this._mousePan=T,this._touchPan=z}enable(N){this._inertiaOptions=N||{},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 fie{constructor(N,T,z){this._pitchWithRotate=N.pitchWithRotate,this._mouseRotate=T,this._mousePitch=z}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 xie{constructor(N,T,z,W){this._el=N,this._touchZoom=T,this._touchRotate=z,this._tapDragZoom=W,this._rotationDisabled=!1,this._enabled=!0}enable(N){this._touchZoom.enable(N),this._rotationDisabled||this._touchRotate.enable(N),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 QL=R=>R.zoom||R.drag||R.pitch||R.rotate;class gie extends o.C{}class yie{constructor(){this.constants=[1,1,.01],this.radius=0}setup(N,T){const z=o.ax([],T,N);this.radius=o.ai(z[2]<0?o.eR([],z,this.constants):[z[0],z[1],0])}projectRay(N){o.eR(N,N,this.constants),o.ay(N,N),o.eS(N,N,this.constants);const T=o.bJ([],N,this.radius);if(T[2]>0){const z=o.bJ([],[0,0,1],o.bi(T,[0,0,1])),W=o.bJ([],o.ay([],[T[0],T[1],0]),this.radius),Q=o.cT([],T,o.bJ([],o.ax([],o.cT([],W,z),T),2));T[0]=Q[0],T[1]=Q[1]}return T}}function JL(R){return R.panDelta&&R.panDelta.mag()||R.zoomDelta||R.bearingDelta||R.pitchDelta}class vie{constructor(N,T){this._map=N,this._el=this._map.getCanvasContainer(),this._handlers=[],this._handlersById={},this._changes=[],this._inertia=new Vi(N),this._bearingSnap=T.bearingSnap,this._previousActiveHandlers={},this._trackingEllipsoid=new yie,this._dragOrigin=null,this._eventsInProgress={},this._addDefaultHandlers(T),o.aZ(["handleEvent","handleWindowEvent"],this);const z=this._el;this._listeners=[[z,"touchstart",{passive:!0}],[z,"touchmove",{passive:!1}],[z,"touchend",void 0],[z,"touchcancel",void 0],[z,"mousedown",void 0],[z,"mousemove",void 0],[z,"mouseup",void 0],[document,"mousemove",{capture:!0}],[document,"mouseup",void 0],[z,"mouseover",void 0],[z,"mouseout",void 0],[z,"dblclick",void 0],[z,"click",void 0],[z,"keydown",{capture:!1}],[z,"keyup",void 0],[z,"wheel",{passive:!1}],[z,"contextmenu",void 0],[window,"blur",void 0]];for(const[W,Q,ee]of this._listeners){const ue=W===document?this.handleWindowEvent:this.handleEvent;W.addEventListener(Q,ue,ee)}}destroy(){for(const[N,T,z]of this._listeners){const W=N===document?this.handleWindowEvent:this.handleEvent;N.removeEventListener(T,W,z)}}_addDefaultHandlers(N){const T=this._map,z=T.getCanvasContainer();this._add("mapEvent",new Sd(T,N));const W=T.boxZoom=new GL(T,N);this._add("boxZoom",W);const Q=new nT,ee=new Iz;T.doubleClickZoom=new Lz(ee,Q),this._add("tapZoom",Q),this._add("clickZoom",ee);const ue=new pie;this._add("tapDragZoom",ue);const _e=T.touchPitch=new jK(T);this._add("touchPitch",_e);const Ee=new Ez(N),Ie=new YL(N);T.dragRotate=new fie(N,Ee,Ie),this._add("mouseRotate",Ee,["mousePitch"]),this._add("mousePitch",Ie,["mouseRotate"]);const Je=new Xb(N),Ke=new _K(T,N);T.dragPan=new CK(z,Je,Ke),this._add("mousePan",Je),this._add("touchPan",Ke,["touchZoom","touchRotate"]);const tt=new QC,ut=new wK;T.touchZoomRotate=new xie(z,ut,tt,ue),this._add("touchRotate",tt,["touchPan","touchZoom"]),this._add("touchZoom",ut,["touchPan","touchRotate"]),this._add("blockableMapEvent",new Yb(T));const lt=T.scrollZoom=new Pz(T,this);this._add("scrollZoom",lt,["mousePan"]);const kt=T.keyboard=new JC;this._add("keyboard",kt);for(const Nt of["boxZoom","doubleClickZoom","tapDragZoom","touchPitch","dragRotate","dragPan","touchZoomRotate","scrollZoom","keyboard"])N.interactive&&N[Nt]&&T[Nt].enable(N[Nt])}_add(N,T,z){this._handlers.push({handlerName:N,handler:T,allowed:z}),this._handlersById[N]=T}stop(N){if(!this._updatingCamera){for(const{handler:T}of this._handlers)T.reset();this._inertia.clear(),this._fireEvents({},{},N),this._changes=[],this._originalZoom=void 0}}isActive(){for(const{handler:N}of this._handlers)if(N.isActive())return!0;return!1}isZooming(){return!!this._eventsInProgress.zoom||this._map.scrollZoom.isZooming()}isRotating(){return!!this._eventsInProgress.rotate}isMoving(){return!!QL(this._eventsInProgress)||this.isZooming()}_isDragging(){return!!this._eventsInProgress.drag}_blockedByActive(N,T,z){for(const W in N)if(W!==z&&(!T||T.indexOf(W)<0))return!0;return!1}handleWindowEvent(N){this.handleEvent(N,`${N.type}Window`)}_getMapTouches(N){const T=[];for(const z of N)this._el.contains(z.target)&&T.push(z);return T}handleEvent(N,T){this._updatingCamera=!0;const z=N.type==="renderFrame",W=z?void 0:N,Q={needsRenderFrame:!1},ee={},ue={},_e=N.touches?this._getMapTouches(N.touches):void 0,Ee=_e?I(this._el,_e):z?void 0:M(this._el,N);for(const{handlerName:Ke,handler:tt,allowed:ut}of this._handlers){if(!tt.isEnabled())continue;let lt;this._blockedByActive(ue,ut,Ke)?tt.reset():tt[T||N.type]&&(lt=tt[T||N.type](N,Ee,_e),this.mergeHandlerResult(Q,ee,lt,Ke,W),lt&<.needsRenderFrame&&this._triggerRenderFrame()),(lt||tt.isActive())&&(ue[Ke]=tt)}const Ie={};for(const Ke in this._previousActiveHandlers)ue[Ke]||(Ie[Ke]=W);this._previousActiveHandlers=ue,(Object.keys(Ie).length||JL(Q))&&(this._changes.push([Q,ee,Ie]),this._triggerRenderFrame()),(Object.keys(ue).length||JL(Q))&&this._map._stop(!0),this._updatingCamera=!1;const{cameraAnimation:Je}=Q;Je&&(this._inertia.clear(),this._fireEvents({},{},!0),this._changes=[],Je(this._map))}mergeHandlerResult(N,T,z,W,Q){if(!z)return;Object.assign(N,z);const ee={handlerName:W,originalEvent:z.originalEvent||Q};z.zoomDelta!==void 0&&(T.zoom=ee),z.panDelta!==void 0&&(T.drag=ee),z.pitchDelta!==void 0&&(T.pitch=ee),z.bearingDelta!==void 0&&(T.rotate=ee)}_applyChanges(){const N={},T={},z={};for(const[W,Q,ee]of this._changes)W.panDelta&&(N.panDelta=(N.panDelta||new o.P(0,0))._add(W.panDelta)),W.zoomDelta&&(N.zoomDelta=(N.zoomDelta||0)+W.zoomDelta),W.bearingDelta&&(N.bearingDelta=(N.bearingDelta||0)+W.bearingDelta),W.pitchDelta&&(N.pitchDelta=(N.pitchDelta||0)+W.pitchDelta),W.around!==void 0&&(N.around=W.around),W.aroundCoord!==void 0&&(N.aroundCoord=W.aroundCoord),W.pinchAround!==void 0&&(N.pinchAround=W.pinchAround),W.noInertia&&(N.noInertia=W.noInertia),Object.assign(T,Q),Object.assign(z,ee);this._updateMapTransform(N,T,z),this._changes=[]}_updateMapTransform(N,T,z){const W=this._map,Q=W.transform,ee=zt=>[zt.x,zt.y,zt.z];if((()=>{const zt=this._eventsInProgress.drag;return zt&&!this._handlersById[zt.handlerName].isActive()})()&&!JL(N)){const zt=Q.zoom;Q.cameraElevationReference="sea",this._originalZoom!=null&&Q._orthographicProjectionAtLowPitch&&Q.projection.name!=="globe"&&Q.pitch===0?(Q.cameraElevationReference="ground",Q.zoom=this._originalZoom):(Q.recenterOnTerrain(),Q.cameraElevationReference="ground"),zt!==Q.zoom&&this._map._update(!0)}if(Q._isCameraConstrained&&W._stop(!0),!JL(N))return void this._fireEvents(T,z,!0);let{panDelta:ue,zoomDelta:_e,bearingDelta:Ee,pitchDelta:Ie,around:Je,aroundCoord:Ke,pinchAround:tt}=N;Q._isCameraConstrained&&(_e>0&&(_e=0),Q._isCameraConstrained=!1),tt!==void 0&&(Je=tt),(_e||(zt=>T[zt]&&!this._eventsInProgress[zt])("drag"))&&Je&&(this._dragOrigin=ee(Q.pointCoordinate3D(Je)),this._originalZoom=Q.zoom,this._trackingEllipsoid.setup(Q._camera.position,this._dragOrigin)),Q.cameraElevationReference="sea",W._stop(!0),Je=Je||W.transform.centerPoint,Ee&&(Q.bearing+=Ee),Ie&&(Q.pitch+=Ie),Q._updateCameraState();const ut=[0,0,0];if(ue)if(Q.projection.name==="mercator"){const zt=this._trackingEllipsoid.projectRay(Q.screenPointToMercatorRay(Je).dir),Yt=this._trackingEllipsoid.projectRay(Q.screenPointToMercatorRay(Je.sub(ue)).dir);ut[0]=Yt[0]-zt[0],ut[1]=Yt[1]-zt[1]}else{const zt=Q.pointCoordinate(Je);if(Q.projection.name==="globe"){ue=ue.rotate(-Q.angle);const Yt=Q._pixelsPerMercatorPixel/Q.worldSize;ut[0]=-ue.x*o.eQ(o.bV(zt.y))*Yt,ut[1]=-ue.y*o.eQ(Q.center.lat)*Yt}else{const Yt=Q.pointCoordinate(Je.sub(ue));zt&&Yt&&(ut[0]=Yt.x-zt.x,ut[1]=Yt.y-zt.y)}}const lt=Q.zoom,kt=[0,0,0];if(_e){const zt=ee(Ke||Q.pointCoordinate3D(Je)),Yt={dir:o.ay([],o.ax([],zt,Q._camera.position))};if(Yt.dir[2]<0){const Tt=Q.zoomDeltaToMovement(zt,_e);o.bJ(kt,Yt.dir,Tt)}}const Nt=o.cT(ut,ut,kt);Q._translateCameraConstrained(Nt),_e&&Math.abs(Q.zoom-lt)>1e-4&&Q.recenterOnTerrain(),Q.cameraElevationReference="ground",this._map._update(),N.noInertia||this._inertia.record(N),this._fireEvents(T,z,!0)}_fireEvents(N,T,z){const W=QL(this._eventsInProgress),Q=QL(N),ee={};for(const Ie in N){const{originalEvent:Je}=N[Ie];this._eventsInProgress[Ie]||(ee[`${Ie}start`]=Je),this._eventsInProgress[Ie]=N[Ie]}!W&&Q&&this._fireEvent("movestart",Q.originalEvent);for(const Ie in ee)this._fireEvent(Ie,ee[Ie]);Q&&this._fireEvent("move",Q.originalEvent);for(const Ie in N){const{originalEvent:Je}=N[Ie];this._fireEvent(Ie,Je)}const ue={};let _e;for(const Ie in this._eventsInProgress){const{handlerName:Je,originalEvent:Ke}=this._eventsInProgress[Ie];this._handlersById[Je].isActive()||(delete this._eventsInProgress[Ie],_e=T[Je]||Ke,ue[`${Ie}end`]=_e)}for(const Ie in ue)this._fireEvent(Ie,ue[Ie]);const Ee=QL(this._eventsInProgress);if(z&&(W||Q)&&!Ee){this._updatingCamera=!0;const Ie=this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions),Je=Ke=>Ke!==0&&-this._bearingSnap{this._frameId=void 0,this.handleEvent(new gie("renderFrame",{timeStamp:N})),this._applyChanges()})}_triggerRenderFrame(){this._frameId===void 0&&(this._frameId=this._requestFrame())}}const AK="map.setFreeCameraOptions(...) and map.getFreeCameraOptions() are not yet supported for non-mercator projections.";class bie extends o.E{constructor(N,T){super(),this._moving=!1,this._zooming=!1,this.transform=N,this._bearingSnap=T.bearingSnap,this._respectPrefersReducedMotion=T.respectPrefersReducedMotion!==!1,o.aZ(["_renderFrameCallback"],this)}getCenter(){return new o.aU(this.transform.center.lng,this.transform.center.lat)}setCenter(N,T){return this.jumpTo({center:N},T)}panBy(N,T,z){return N=o.P.convert(N).mult(-1),this.panTo(this.transform.center,Object.assign({offset:N},T),z)}panTo(N,T,z){return this.easeTo(Object.assign({center:N},T),z)}getZoom(){return this.transform.zoom}setZoom(N,T){return this.jumpTo({zoom:N},T),this}zoomTo(N,T,z){return this.easeTo(Object.assign({zoom:N},T),z)}zoomIn(N,T){return this.zoomTo(this.getZoom()+1,N,T),this}zoomOut(N,T){return this.zoomTo(this.getZoom()-1,N,T),this}getBearing(){return this.transform.bearing}setBearing(N,T){return this.jumpTo({bearing:N},T),this}getPadding(){return this.transform.padding}setPadding(N,T){return this.jumpTo({padding:N},T),this}rotateTo(N,T,z){return this.easeTo(Object.assign({bearing:N},T),z)}resetNorth(N,T){return this.rotateTo(0,Object.assign({duration:1e3},N),T),this}resetNorthPitch(N,T){return this.easeTo(Object.assign({bearing:0,pitch:0,duration:1e3},N),T),this}snapToNorth(N,T){return Math.abs(this.getBearing())N.aspect?z/(2*Math.tan(.5*N.fovX)*N.aspect):W/(2*Math.tan(.5*N.fovY)*N.aspect)}_cameraForBoundsOnGlobe(N,T,z,W,Q,ee){const ue=N.clone(),_e=this._extendCameraOptions(ee);ue.bearing=W,ue.pitch=Q;const Ee=o.aU.convert(T),Ie=o.aU.convert(z),Je=.5*(Ee.lat+Ie.lat),Ke=.5*(Ee.lng+Ie.lng),tt=o.eT(Je,Ke),ut=o.ay([],tt),lt=o.ay([],o.bh([],ut,[0,1,0])),kt=o.bh([],lt,ut),Nt=[lt[0],lt[1],lt[2],0,kt[0],kt[1],kt[2],0,ut[0],ut[1],ut[2],0,0,0,0,1],zt=[tt,o.eT(Ee.lat,Ee.lng),o.eT(Ie.lat,Ee.lng),o.eT(Ie.lat,Ie.lng),o.eT(Ee.lat,Ie.lng),o.eT(Je,Ee.lng),o.eT(Je,Ie.lng),o.eT(Ee.lat,Ke),o.eT(Ie.lat,Ke)];let Yt=o.cU.fromPoints(zt.map(_n=>[o.bi(lt,_n),o.bi(kt,_n),o.bi(ut,_n)]));const Tt=o.ah([],Yt.center,Nt);o.eU(Tt)===0&&o.eV(Tt,0,0,1),o.ay(Tt,Tt),o.bJ(Tt,Tt,o.aF),ue.center=o.eW(Tt);const Ss=ue.getWorldToCameraMatrix(),cs=o.b7(new Float64Array(16),Ss);Yt=o.cU.applyTransform(Yt,o.aD([],Ss,Nt));const Ns=this._extendAABB(Yt,ue,_e,W);if(!Ns)return void o.w("Map cannot fit within canvas with the given bounds, padding, and/or offset.");Yt=Ns,o.ah(Tt,Tt,Ss);const Zt=.5*(Yt.max[2]-Yt.min[2]),ns=this._minimumAABBFrustumDistance(ue,Yt),bs=o.bJ([],[0,0,1],Zt),Ks=o.cT(bs,Tt,bs),Es=ns+(ue.pitch===0?0:o.bf(Tt,Ks)),bn=ue.globeCenterInViewSpace,mn=o.ax([],Tt,[bn[0],bn[1],bn[2]]);o.ay(mn,mn),o.bJ(mn,mn,Es);const zn=o.cT([],Tt,mn);o.ah(zn,zn,cs);const Kn=o.eD/o.aF,sn=o.ai(zn),Fs=o.bU(Math.max(sn*Kn-o.eD,Number.EPSILON),0),yn=Math.min(ue.zoomFromMercatorZAdjusted(Fs),_e.maxZoom);return yn>.5*(o.cJ+o.cv)?(ue.setProjection({name:"mercator"}),ue.zoom=yn,this._cameraForBounds(ue,T,z,W,Q,ee)):{center:ue.center,zoom:yn,bearing:W,pitch:Q}}_extendAABB(N,T,z,W){const Q=.5*((z.padding.left||0)+(z.padding.right||0)),ee=.5*((z.padding.top||0)+(z.padding.bottom||0)),ue=ee,_e=Q,Ee=Q,Ie=ee,Je=T.width-(_e+Ee),Ke=T.height-(ue+Ie),tt=o.ax([],N.max,N.min),ut=Math.min(Je/tt[0],Ke/tt[1]),lt=Math.min(T.scaleZoom(T.scale*ut),z.maxZoom);if(isNaN(lt))return null;const kt=T.scale/T.zoomScale(lt),Nt=new o.cU([N.min[0]-_e*kt,N.min[1]-Ie*kt,N.min[2]],[N.max[0]+Ee*kt,N.max[1]+ue*kt,N.max[2]]),zt=(typeof z.offset.x=="number"&&typeof z.offset.y=="number"?new o.P(z.offset.x,z.offset.y):o.P.convert(z.offset)).rotate(-o.ap(W));return Nt.center[0]-=zt.x*kt,Nt.center[1]+=zt.y*kt,Nt}queryTerrainElevation(N,T){const z=this.transform.elevation;return z?(T=Object.assign({},{exaggerated:!0},T),z.getAtPoint(o.ag.fromLngLat(N),null,T.exaggerated)):null}_cameraForBounds(N,T,z,W,Q,ee){if(N.projection.name==="globe")return this._cameraForBoundsOnGlobe(N,T,z,W,Q,ee);const ue=N.clone(),_e=this._extendCameraOptions(ee);ue.bearing=W,ue.pitch=Q;const Ee=o.aU.convert(T),Ie=o.aU.convert(z),Je=new o.aU(Ee.lng,Ie.lat),Ke=new o.aU(Ie.lng,Ee.lat),tt=ue.project(Ee),ut=ue.project(Ie),lt=this.queryTerrainElevation(Ee),kt=this.queryTerrainElevation(Ie),Nt=this.queryTerrainElevation(Je),zt=this.queryTerrainElevation(Ke),Yt=[[tt.x,tt.y,Math.min(lt||0,kt||0,Nt||0,zt||0)],[ut.x,ut.y,Math.max(lt||0,kt||0,Nt||0,zt||0)]];let Tt=o.cU.fromPoints(Yt);const Ss=ue.getWorldToCameraMatrix(),cs=o.b7(new Float64Array(16),Ss);Tt=o.cU.applyTransform(Tt,Ss);const Ns=this._extendAABB(Tt,ue,_e,W);if(!Ns)return void o.w("Map cannot fit within canvas with the given bounds, padding, and/or offset.");Tt=Ns;const Zt=.5*o.ax([],Tt.max,Tt.min)[2],ns=this._minimumAABBFrustumDistance(ue,Tt),bs=[0,0,1,0];o.aE(bs,bs,Ss),o.eX(bs,bs);const Ks=o.bJ([],bs,ns+Zt),Es=o.cT([],Tt.center,Ks);o.ah(Tt.center,Tt.center,cs),o.ah(Es,Es,cs);const bn=ue.unproject(new o.P(Tt.center[0],Tt.center[1])),mn=o.eY(ue.projection,bn),zn=Math.pow(2,mn),Kn=Math.min(ue._zoomFromMercatorZ(Es[2]*ue.pixelsPerMeter*zn/ue.worldSize),_e.maxZoom);return ue.mercatorFromTransition&&Kn<.5*(o.cJ+o.cv)?(ue.setProjection({name:"globe"}),ue.zoom=Kn,this._cameraForBounds(ue,T,z,W,Q,ee)):{center:bn,zoom:Kn,bearing:W,pitch:Q}}fitBounds(N,T,z){const W=this.cameraForBounds(N,T);return this._fitInternal(W,T,z)}fitScreenCoordinates(N,T,z,W,Q){const ee=o.P.convert(N),ue=o.P.convert(T),_e=new o.P(Math.min(ee.x,ue.x),Math.min(ee.y,ue.y)),Ee=new o.P(Math.max(ee.x,ue.x),Math.max(ee.y,ue.y));if(this.transform.projection.name==="mercator"&&this.transform.anyCornerOffEdge(ee,ue))return this;const Ie=this.transform.pointLocation3D(_e),Je=this.transform.pointLocation3D(Ee),Ke=this.transform.pointLocation3D(new o.P(_e.x,Ee.y)),tt=this.transform.pointLocation3D(new o.P(Ee.x,_e.y)),ut=[Math.min(Ie.lng,Je.lng,Ke.lng,tt.lng),Math.min(Ie.lat,Je.lat,Ke.lat,tt.lat)],lt=[Math.max(Ie.lng,Je.lng,Ke.lng,tt.lng),Math.max(Ie.lat,Je.lat,Ke.lat,tt.lat)],kt=W&&W.pitch?W.pitch:this.getPitch(),Nt=this._cameraForBounds(this.transform,ut,lt,z,kt,W);return this._fitInternal(Nt,W,Q)}_fitInternal(N,T,z){return N?(T=Object.assign(N,T)).linear?this.easeTo(T,z):this.flyTo(T,z):this}jumpTo(N,T){this.stop();const z=N.preloadOnly?this.transform.clone():this.transform;let W=!1,Q=!1,ee=!1;"zoom"in N&&z.zoom!==+N.zoom&&(W=!0,z.zoom=+N.zoom),N.center!==void 0&&(z.center=o.aU.convert(N.center)),"bearing"in N&&z.bearing!==+N.bearing&&(Q=!0,z.bearing=+N.bearing),"pitch"in N&&z.pitch!==+N.pitch&&(ee=!0,z.pitch=+N.pitch);const ue=typeof N.padding=="number"?this._extendPadding(N.padding):N.padding;if(N.padding!=null&&!z.isPaddingEqual(ue))if(N.retainPadding===!1){const _e=z.clone();_e.padding=ue,z.setLocationAtPoint(z.center,_e.centerPoint)}else z.padding=ue;return N.preloadOnly?(this._preloadTiles(z),this):(this.fire(new o.C("movestart",T)).fire(new o.C("move",T)),W&&this.fire(new o.C("zoomstart",T)).fire(new o.C("zoom",T)).fire(new o.C("zoomend",T)),Q&&this.fire(new o.C("rotatestart",T)).fire(new o.C("rotate",T)).fire(new o.C("rotateend",T)),ee&&this.fire(new o.C("pitchstart",T)).fire(new o.C("pitch",T)).fire(new o.C("pitchend",T)),this.fire(new o.C("moveend",T)))}getFreeCameraOptions(){return this.transform.projection.supportsFreeCamera||o.w(AK),this.transform.getFreeCameraOptions()}setFreeCameraOptions(N,T){const z=this.transform;if(!z.projection.supportsFreeCamera)return o.w(AK),this;this.stop();const W=z.zoom,Q=z.pitch,ee=z.bearing;z.setFreeCameraOptions(N);const ue=W!==z.zoom,_e=Q!==z.pitch,Ee=ee!==z.bearing;return this.fire(new o.C("movestart",T)).fire(new o.C("move",T)),ue&&this.fire(new o.C("zoomstart",T)).fire(new o.C("zoom",T)).fire(new o.C("zoomend",T)),Ee&&this.fire(new o.C("rotatestart",T)).fire(new o.C("rotate",T)).fire(new o.C("rotateend",T)),_e&&this.fire(new o.C("pitchstart",T)).fire(new o.C("pitch",T)).fire(new o.C("pitchend",T)),this.fire(new o.C("moveend",T)),this}easeTo(N,T){this._stop(!1,N.easeId),((N=Object.assign({offset:[0,0],duration:500,easing:o.eP},N)).animate===!1||this._prefersReducedMotion(N))&&(N.duration=0);const z=this.transform,W=this.getZoom(),Q=this.getBearing(),ee=this.getPitch(),ue=this.getPadding(),_e="zoom"in N?+N.zoom:W,Ee="bearing"in N?this._normalizeBearing(N.bearing,Q):Q,Ie="pitch"in N?+N.pitch:ee,Je=this._extendPadding(N.padding),Ke=o.P.convert(N.offset);let tt,ut,lt;if(z.projection.name==="globe"){const bs=o.ag.fromLngLat(z.center),Ks=Ke.rotate(-z.angle);bs.x+=Ks.x/z.worldSize,bs.y+=Ks.y/z.worldSize;const Es=bs.toLngLat(),bn=o.aU.convert(N.center||Es);this._normalizeCenter(bn),tt=z.centerPoint.add(Ks),ut=new o.P(bs.x,bs.y).mult(z.worldSize),lt=new o.P(o.aH(bn.lng),o.aL(bn.lat)).mult(z.worldSize).sub(ut)}else{tt=z.centerPoint.add(Ke);const bs=z.pointLocation(tt),Ks=o.aU.convert(N.center||bs);this._normalizeCenter(Ks),ut=z.project(bs),lt=z.project(Ks).sub(ut)}const kt=z.zoomScale(_e-W);let Nt,zt;N.around&&(Nt=o.aU.convert(N.around),zt=z.locationPoint(Nt));const Yt=this._zooming||_e!==W,Tt=this._rotating||Q!==Ee,Ss=this._pitching||Ie!==ee,cs=!z.isPaddingEqual(Je),Ns=N.retainPadding===!1?z.clone():z,Zt=bs=>Ks=>{if(Yt&&(bs.zoom=o.am(W,_e,Ks)),Tt&&(bs.bearing=o.am(Q,Ee,Ks)),Ss&&(bs.pitch=o.am(ee,Ie,Ks)),cs&&(Ns.interpolatePadding(ue,Je,Ks),tt=Ns.centerPoint.add(Ke)),Nt)bs.setLocationAtPoint(Nt,zt);else{const Es=bs.zoomScale(bs.zoom-W),bn=_e>W?Math.min(2,kt):Math.max(.5,kt),mn=Math.pow(bn,1-Ks),zn=bs.unproject(ut.add(lt.mult(Ks*mn)).mult(Es));bs.setLocationAtPoint(bs.renderWorldCopies?zn.wrap():zn,tt)}return N.preloadOnly||this._fireMoveEvents(T),bs};if(N.preloadOnly){const bs=this._emulate(Zt,N.duration,z);return this._preloadTiles(bs),this}const ns={moving:this._moving,zooming:this._zooming,rotating:this._rotating,pitching:this._pitching};return this._zooming=Yt,this._rotating=Tt,this._pitching=Ss,this._padding=cs,this._easeId=N.easeId,this._prepareEase(T,N.noMoveStart,ns),this._ease(Zt(z),bs=>{z.cameraElevationReference==="sea"&&z.recenterOnTerrain(),this._afterEase(T,bs)},N),this}_prepareEase(N,T,z={}){this._moving=!0,this.transform.cameraElevationReference="sea",this.transform._orthographicProjectionAtLowPitch&&this.transform.pitch===0&&this.transform.projection.name!=="globe"&&(this.transform.cameraElevationReference="ground"),T||z.moving||this.fire(new o.C("movestart",N)),this._zooming&&!z.zooming&&this.fire(new o.C("zoomstart",N)),this._rotating&&!z.rotating&&this.fire(new o.C("rotatestart",N)),this._pitching&&!z.pitching&&this.fire(new o.C("pitchstart",N))}_fireMoveEvents(N){this.fire(new o.C("move",N)),this._zooming&&this.fire(new o.C("zoom",N)),this._rotating&&this.fire(new o.C("rotate",N)),this._pitching&&this.fire(new o.C("pitch",N))}_afterEase(N,T){if(this._easeId&&T&&this._easeId===T)return;this._easeId=void 0,this.transform.cameraElevationReference="ground";const z=this._zooming,W=this._rotating,Q=this._pitching;this._moving=!1,this._zooming=!1,this._rotating=!1,this._pitching=!1,this._padding=!1,z&&this.fire(new o.C("zoomend",N)),W&&this.fire(new o.C("rotateend",N)),Q&&this.fire(new o.C("pitchend",N)),this.fire(new o.C("moveend",N))}flyTo(N,T){if(this._prefersReducedMotion(N)){const _n=o.aJ(N,["center","zoom","bearing","pitch","around","padding","retainPadding"]);return this.jumpTo(_n,T)}this.stop(),N=Object.assign({offset:[0,0],speed:1.2,curve:1.42,easing:o.eP},N);const z=this.transform,W=this.getZoom(),Q=this.getBearing(),ee=this.getPitch(),ue=this.getPadding(),_e="zoom"in N?o.aC(+N.zoom,z.minZoom,z.maxZoom):W,Ee="bearing"in N?this._normalizeBearing(N.bearing,Q):Q,Ie="pitch"in N?+N.pitch:ee,Je=this._extendPadding(N.padding),Ke=z.zoomScale(_e-W),tt=o.P.convert(N.offset);let ut=z.centerPoint.add(tt);const lt=z.pointLocation(ut),kt=o.aU.convert(N.center||lt);this._normalizeCenter(kt);const Nt=z.project(lt),zt=z.project(kt).sub(Nt);let Yt=N.curve;const Tt=Math.max(z.width,z.height),Ss=Tt/Ke,cs=zt.mag();if("minZoom"in N){const _n=o.aC(Math.min(N.minZoom,W,_e),z.minZoom,z.maxZoom),Tn=Tt/z.zoomScale(_n-W);Yt=Math.sqrt(Tn/cs*2)}const Ns=Yt*Yt;function Zt(_n){const Tn=(Ss*Ss-Tt*Tt+(_n?-1:1)*Ns*Ns*cs*cs)/(2*(_n?Ss:Tt)*Ns*cs);return Math.log(Math.sqrt(Tn*Tn+1)-Tn)}function ns(_n){return(Math.exp(_n)-Math.exp(-_n))/2}function bs(_n){return(Math.exp(_n)+Math.exp(-_n))/2}const Ks=Zt(0);let Es=function(_n){return bs(Ks)/bs(Ks+Yt*_n)},bn=function(_n){return Tt*((bs(Ks)*(ns(Tn=Ks+Yt*_n)/bs(Tn))-ns(Ks))/Ns)/cs;var Tn},mn=(Zt(1)-Ks)/Yt;if(Math.abs(cs)<1e-6||!isFinite(mn)){if(Math.abs(Tt-Ss)<1e-6)return this.easeTo(N,T);const _n=SsN.maxDuration&&(N.duration=0);const zn=Q!==Ee,Kn=Ie!==ee,sn=!z.isPaddingEqual(Je),Fs=N.retainPadding===!1?z.clone():z,yn=_n=>Tn=>{const Nr=Tn*mn,hr=1/Es(Nr);_n.zoom=Tn===1?_e:W+_n.scaleZoom(hr),zn&&(_n.bearing=o.am(Q,Ee,Tn)),Kn&&(_n.pitch=o.am(ee,Ie,Tn)),sn&&(Fs.interpolatePadding(ue,Je,Tn),ut=Fs.centerPoint.add(tt));const mr=Tn===1?kt:_n.unproject(Nt.add(zt.mult(bn(Nr))).mult(hr));return _n.setLocationAtPoint(_n.renderWorldCopies?mr.wrap():mr,ut),_n._updateCameraOnTerrain(),N.preloadOnly||this._fireMoveEvents(T),_n};if(N.preloadOnly){const _n=this._emulate(yn,N.duration,z);return this._preloadTiles(_n),this}return this._zooming=!0,this._rotating=zn,this._pitching=Kn,this._padding=sn,this._prepareEase(T,!1),this._ease(yn(z),()=>this._afterEase(T),N),this}isEasing(){return!!this._easeFrameId}stop(){return this._stop()}_requestRenderFrame(N){}_cancelRenderFrame(N){}_stop(N,T){if(this._easeFrameId&&(this._cancelRenderFrame(this._easeFrameId),this._easeFrameId=void 0,this._onEaseFrame=void 0),this._onEaseEnd){const z=this._onEaseEnd;this._onEaseEnd=void 0,z.call(this,T)}if(!N){const z=this.handlers;z&&z.stop(!1)}return this}_ease(N,T,z){z.animate===!1||z.duration===0?(N(1),T()):(this._easeStart=o.o.now(),this._easeOptions=z,this._onEaseFrame=N,this._onEaseEnd=T,this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback))}_renderFrameCallback(){const N=Math.min((o.o.now()-this._easeStart)/this._easeOptions.duration,1),T=this._onEaseFrame;T&&T(this._easeOptions.easing(N)),N<1?this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback):this.stop()}_normalizeBearing(N,T){N=o.bs(N,-180,180);const z=Math.abs(N-T);return Math.abs(N-360-T)180?-360:z<-180?360:0}_prefersReducedMotion(N){return this._respectPrefersReducedMotion&&o.o.prefersReducedMotion&&!(N&&N.essential)}_emulate(N,T,z){const W=Math.ceil(15*T/1e3),Q=[],ee=N(z.clone());for(let ue=0;ue<=W;ue++){const _e=ee(ue/W);Q.push(_e.clone())}return Q}_preloadTiles(N,T){}}class EK{constructor(N={}){this.options=N,o.aZ(["_toggleAttribution","_updateEditLink","_updateData","_updateCompact"],this)}getDefaultPosition(){return"bottom-right"}onAdd(N){const T=this.options&&this.options.compact,z=N._getUIString("AttributionControl.ToggleAttribution");this._map=N,this._container=y("div","mapboxgl-ctrl mapboxgl-ctrl-attrib"),this._compactButton=y("button","mapboxgl-ctrl-attrib-button",this._container),this._compactButton.type="button",this._compactButton.addEventListener("click",this._toggleAttribution),this._compactButton.setAttribute("aria-label",z);const W=y("span","mapboxgl-ctrl-icon",this._compactButton);return W.setAttribute("aria-hidden","true"),W.setAttribute("title",z),this._innerContainer=y("div","mapboxgl-ctrl-attrib-inner",this._container),T&&this._container.classList.add("mapboxgl-compact"),this._updateAttributions(),this._updateEditLink(),this._map.on("styledata",this._updateData),this._map.on("sourcedata",this._updateData),this._map.on("moveend",this._updateEditLink),T===void 0&&(this._map.on("resize",this._updateCompact),this._updateCompact()),this._container}onRemove(){this._container.remove(),this._map.off("styledata",this._updateData),this._map.off("sourcedata",this._updateData),this._map.off("moveend",this._updateEditLink),this._map.off("resize",this._updateCompact),this._map=void 0,this._attribHTML=void 0}_toggleAttribution(){this._container.classList.contains("mapboxgl-compact-show")?(this._container.classList.remove("mapboxgl-compact-show"),this._compactButton.setAttribute("aria-expanded","false")):(this._container.classList.add("mapboxgl-compact-show"),this._compactButton.setAttribute("aria-expanded","true"))}_updateEditLink(){let N=this._editLink;N||(N=this._editLink=this._container.querySelector(".mapbox-improve-map"));const T=[{key:"owner",value:this.styleOwner},{key:"id",value:this.styleId},{key:"access_token",value:this._map._requestManager._customAccessToken||o.g.ACCESS_TOKEN}];if(N){const z=T.reduce((W,Q,ee)=>(Q.value&&(W+=`${Q.key}=${Q.value}${eeW.length-Q.length),N=N.filter((W,Q)=>{for(let ee=Q+1;ee=0)return!1;return!0}),this.options.customAttribution&&(Array.isArray(this.options.customAttribution)?N=[...this.options.customAttribution,...N]:N.unshift(this.options.customAttribution));const z=N.map(W=>function(Q){const ee=new DOMParser().parseFromString(Q,"text/html");return Array.from(ee.body.querySelectorAll("*")).reverse().forEach(ue=>{const _e=ue.textContent||"";if(ue.tagName!=="A")return void ue.replaceWith(...ue.childNodes);const Ee=ue.getAttribute("href");if(!Ee||!/^(https?:|mailto:)/i.test(Ee))return void ue.replaceWith(ee.createTextNode(_e));const Ie=ee.createElement("a");Ie.href=Ee,Ie.textContent=_e,Ie.rel="noopener nofollow";const Je=ue.getAttribute("class");Je&&(Ie.className=Je),ue.replaceWith(Ie)}),ee.body.innerHTML}(W)).join(" | ");z!==this._attribHTML&&(this._attribHTML=z,N.length?(this._innerContainer.innerHTML=z,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 TK{constructor(){o.aZ(["_updateLogo","_updateCompact"],this)}onAdd(N){this._map=N,this._container=y("div","mapboxgl-ctrl");const T=y("a","mapboxgl-ctrl-logo");return T.target="_blank",T.rel="noopener nofollow",T.href="https://www.mapbox.com/",T.setAttribute("aria-label",this._map._getUIString("LogoControl.Title")),T.setAttribute("rel","noopener nofollow"),this._container.appendChild(T),this._container.style.display="none",this._map.on("sourcedata",this._updateLogo),this._updateLogo(),this._map.on("resize",this._updateCompact),this._updateCompact(),this._container}onRemove(){this._container.remove(),this._map.off("sourcedata",this._updateLogo),this._map.off("resize",this._updateCompact)}getDefaultPosition(){return"bottom-left"}_updateLogo(N){N&&N.sourceDataType!=="metadata"||(this._container.style.display=this._logoRequired()?"block":"none")}_logoRequired(){if(!this._map.style)return!0;const N=this._map.style._sourceCaches;if(Object.entries(N).length===0)return!0;for(const T in N){const z=N[T].getSource();if(z.hasOwnProperty("mapbox_logo")&&!z.mapbox_logo)return!1}return!0}_updateCompact(){const N=this._container.children;if(N.length){const T=N[0];this._map.getCanvasContainer().offsetWidth<250?T.classList.add("mapboxgl-compact"):T.classList.remove("mapboxgl-compact")}}}class _ie{constructor(){this._queue=[],this._id=0,this._cleared=!1,this._currentlyRunning=!1}add(N){const T=++this._id;return this._queue.push({callback:N,id:T,cancelled:!1}),T}remove(N){const T=this._currentlyRunning,z=T?this._queue.concat(T):this._queue;for(const W of z)if(W.id===N)return void(W.cancelled=!0)}run(N=0){const T=this._currentlyRunning=this._queue;this._queue=[];for(const z of T)if(!z.cancelled&&(z.callback(N),this._cleared))break;this._cleared=!1,this._currentlyRunning=!1}clear(){this._currentlyRunning&&(this._cleared=!0),this._queue=[]}}class jDe{constructor(N){this.jumpTo(N)}getValue(N){if(N<=this._startTime)return this._start;if(N>=this._endTime)return this._end;const T=o.dn((N-this._startTime)/(this._endTime-this._startTime));return this._start*(1-T)+this._end*T}isEasing(N){return N>=this._startTime&&N<=this._endTime}jumpTo(N){this._startTime=-1/0,this._endTime=-1/0,this._start=N,this._end=N}easeTo(N,T,z){this._start=this.getValue(T),this._end=N,this._startTime=T,this._endTime=T+z}}const NDe={"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 Rc extends o.C{constructor(N,T,z,W){const{point:Q,lngLat:ee,originalEvent:ue,target:_e}=N;super(N.type,{point:Q,lngLat:ee,originalEvent:ue,target:_e}),this.preventDefault=()=>{N.preventDefault()},this.id=T,this.interaction=z,this.feature=W}}class Dz{constructor(N){this.map=N,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(N,T){if(this.typeById.has(N))throw new Error(`Interaction id "${N}" already exists.`);const z=T.filter;let W=T.type;z&&this.filters.set(N,o.dg(z)),W==="mouseover"&&(W="mouseenter"),W==="mouseout"&&(W="mouseleave");const Q=this.interactionsByType.get(W)||new Map;W==="mouseenter"||W==="mouseleave"?(this.delegatedInteractions.size===0&&(this.map.on("mousemove",this.handleMove),this.map.on("mouseout",this.handleOut)),this.delegatedInteractions.set(N,T)):Q.size===0&&this.map.on(W,this.handleType),Q.size===0&&this.interactionsByType.set(W,Q),Q.set(N,T),this.typeById.set(N,W)}get(N){const T=this.typeById.get(N);if(!T)return;const z=this.interactionsByType.get(T);return z?z.get(N):void 0}remove(N){const T=this.typeById.get(N);if(!T)return;this.typeById.delete(N),this.filters.delete(N);const z=this.interactionsByType.get(T);z&&(z.delete(N),T==="mouseenter"||T==="mouseleave"?(this.delegatedInteractions.delete(N),this.delegatedInteractions.size===0&&(this.map.off("mousemove",this.handleMove),this.map.off("mouseout",this.handleOut))):z.size===0&&this.map.off(T,this.handleType))}queryTargets(N,T){const z=[];for(const[W,Q]of T)Q.target&&z.push({targetId:W,target:Q.target,filter:this.filters.get(W)});return this.map.style.queryRenderedTargets(N,z,this.map.transform)}handleMove(N){this.prevHoveredFeatures=this.hoveredFeatures,this.hoveredFeatures=new Map;const T=this.queryTargets(N.point,Array.from(this.delegatedInteractions).reverse());T.length&&(N.type="mouseenter",this.handleType(N,T));const z=new Map;for(const[W,{feature:Q}]of this.prevHoveredFeatures)this.hoveredFeatures.has(W)||z.set(Q.id,Q);z.size&&(N.type="mouseleave",this.handleType(N,Array.from(z.values())))}handleOut(N){const T=Array.from(this.hoveredFeatures.values()).map(({feature:z})=>z);T.length&&(N.type="mouseleave",this.handleType(N,T)),this.hoveredFeatures.clear()}handleType(N,T){const z=N.type==="mouseenter";if(z&&!this.interactionsByType.has(N.type))return void o.w("mouseenter interaction required for mouseleave to work.");const W=Array.from(this.interactionsByType.get(N.type)).reverse(),Q=!!T;T=T||this.queryTargets(N.point,W);let ee=!1;const ue=new Set;for(const _e of T){for(const[Ee,Ie]of W){if(!Ie.target)continue;const Je=_e.variants?_e.variants[Ee]:null;if(Je){for(const Ke of Je){if(Uu(Ke,_e,ue,Ee))continue;const tt=new o.di(_e,Ke),ut=Bu(Ke,_e,Ee);Q&&tt.id!==void 0&&(tt.state=this.map.getFeatureState(tt));const lt=z?this.prevHoveredFeatures.get(ut):null,kt=new Rc(N,Ee,Ie,tt),Nt=lt?lt.stop:Ie.handler(kt);if(z&&this.hoveredFeatures.set(ut,{feature:_e,stop:Nt}),Nt!==!1){ee=!0;break}}if(ee)break}}if(ee)break}if(!ee)for(const[_e,Ee]of W){const{handler:Ie,target:Je}=Ee;if(!Je&&Ie(new Rc(N,_e,Ee,null))!==!1)break}}}function kDe(R,N){if(Array.isArray(R)&&Array.isArray(N)){const T=new Set(R),z=new Set(N);return T.size===z.size&&R.every(W=>z.has(W))}return o.b6(R,N)}const SDe={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},CDe={showCompass:!0,showZoom:!0,visualizePitch:!1};class eI{constructor(N,T,z=!1){this._clickTolerance=10,this.element=T,this.mouseRotate=new Ez({clickTolerance:N.dragRotate._mouseRotate._clickTolerance}),this.map=N,z&&(this.mousePitch=new YL({clickTolerance:N.dragRotate._mousePitch._clickTolerance})),o.aZ(["mousedown","mousemove","mouseup","touchstart","touchmove","touchend","reset"],this),T.addEventListener("mousedown",this.mousedown),T.addEventListener("touchstart",this.touchstart,{passive:!1}),T.addEventListener("touchmove",this.touchmove),T.addEventListener("touchend",this.touchend),T.addEventListener("touchcancel",this.reset)}down(N,T){this.mouseRotate.mousedown(N,T),this.mousePitch&&this.mousePitch.mousedown(N,T),S()}move(N,T){const z=this.map,W=this.mouseRotate.mousemoveWindow(N,T),Q=W&&W.bearingDelta;if(Q&&z.setBearing(z.getBearing()+Q),this.mousePitch){const ee=this.mousePitch.mousemoveWindow(N,T),ue=ee&&ee.pitchDelta;ue&&z.setPitch(z.getPitch()+ue)}}off(){const N=this.element;N.removeEventListener("mousedown",this.mousedown),N.removeEventListener("touchstart",this.touchstart),N.removeEventListener("touchmove",this.touchmove),N.removeEventListener("touchend",this.touchend),N.removeEventListener("touchcancel",this.reset),this.offTemp()}offTemp(){C(),window.removeEventListener("mousemove",this.mousemove),window.removeEventListener("mouseup",this.mouseup)}mousedown(N){this.down(Object.assign({},N,{button:N.button,type:N.type,ctrlKey:!0,preventDefault:()=>N.preventDefault()}),M(this.element,N)),window.addEventListener("mousemove",this.mousemove),window.addEventListener("mouseup",this.mouseup)}mousemove(N){this.move(N,M(this.element,N))}mouseup(N){this.mouseRotate.mouseupWindow(N),this.mousePitch&&this.mousePitch.mouseupWindow(N),this.offTemp()}touchstart(N){N.targetTouches.length!==1?this.reset():(this._startPos=this._lastPos=I(this.element,N.targetTouches)[0],this.down({type:"mousedown",button:0,ctrlKey:!0,preventDefault:()=>N.preventDefault()},this._startPos))}touchmove(N){N.targetTouches.length!==1?this.reset():(this._lastPos=I(this.element,N.targetTouches)[0],this.move({buttons:1,preventDefault:()=>N.preventDefault()},this._lastPos))}touchend(N){N.targetTouches.length===0&&this._startPos&&this._lastPos&&this._startPos.dist(this._lastPos)T.width||N.y>T.height;T.locationPoint3D(z).distSqr(N)180;){const z=T.locationPoint3D(R);if(z.x>=0&&z.y>=0&&z.x<=T.width&&z.y<=T.height)break;R.lng>T.center.lng?R.lng-=360:R.lng+=360}return R}const tI={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%)"},O1={rotation:0,rotationAlignment:"auto",pitchAlignment:"auto",occludedOpacity:.2,altitude:0};class Qb extends o.E{constructor(N,T){super(),(N instanceof HTMLElement||T)&&(N=Object.assign({element:N},T)),o.aZ(["_update","_onMove","_onUp","_addDragHandler","_onMapClick","_onKeyPress","_clearFadeTimer"],this);const{anchor:z="center",color:W="#3FB1CE",scale:Q=1,draggable:ee=!1,clickTolerance:ue=0,rotation:_e=O1.rotation,rotationAlignment:Ee=O1.rotationAlignment,pitchAlignment:Ie=O1.pitchAlignment,occludedOpacity:Je=O1.occludedOpacity,altitude:Ke=O1.altitude}=N||{};this._anchor=z,this._color=W,this._scale=Q,this._draggable=ee,this._clickTolerance=ue,this._rotation=_e,this._rotationAlignment=Ee,this._pitchAlignment=Ie,this._occludedOpacity=Je,this._altitude=Ke,this._state="inactive",this._isDragging=!1,this._updateMoving=()=>this._update(!0),N&&N.element?(this._element=N.element,this._offset=o.P.convert(N&&N.offset||[0,0])):(this._defaultMarker=!0,this._element=this._createDefaultMarker(),this._offset=o.P.convert(N&&N.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",lt=>{lt.preventDefault()}),this._element.addEventListener("mousedown",lt=>{lt.preventDefault()});const tt=this._element.classList;for(const lt in tI)tt.remove(`mapboxgl-marker-anchor-${lt}`);tt.add(`mapboxgl-marker-anchor-${this._anchor}`);const ut=N&&N.className?N.className.trim().split(/\s+/):[];tt.add(...ut),this._popup=null}_createDefaultMarker(){const N=y("div"),T=v("svg",{display:"block",height:41*this._scale+"px",width:27*this._scale+"px",viewBox:"0 0 27 41"},N);if(this._altitude===0){const z=v("radialGradient",{id:"shadowGradient"},v("defs",{},T));v("stop",{offset:"10%","stop-opacity":.4},z),v("stop",{offset:"100%","stop-opacity":.05},z),v("ellipse",{cx:13.5,cy:34.8,rx:10.5,ry:5.25,fill:"url(#shadowGradient)"},T)}return v("path",{fill:this._color,d:"M27,13.5C27,19.07 20.25,27 14.75,34.5C14.02,35.5 12.98,35.5 12.25,34.5C6.75,27 0,19.22 0,13.5C0,6.04 6.04,0 13.5,0C20.96,0 27,6.04 27,13.5Z"},T),v("path",{opacity:.25,d:"M13.5,0C6.04,0 0,6.04 0,13.5C0,19.22 6.75,27 12.25,34.5C13,35.52 14.02,35.5 14.75,34.5C20.25,27 27,19.07 27,13.5C27,6.04 20.96,0 13.5,0ZM13.5,1C20.42,1 26,6.58 26,13.5C26,15.9 24.5,19.18 22.22,22.74C19.95,26.3 16.71,30.14 13.94,33.91C13.74,34.18 13.61,34.32 13.5,34.44C13.39,34.32 13.26,34.18 13.06,33.91C10.28,30.13 7.41,26.31 5.02,22.77C2.62,19.23 1,15.95 1,13.5C1,6.58 6.58,1 13.5,1Z"},T),v("circle",{fill:"white",cx:13.5,cy:13.5,r:5.5},T),N}addTo(N){return N===this._map||(this.remove(),this._map=N,N.getCanvasContainer().appendChild(this._element),N.on("move",this._updateMoving),N.on("moveend",this._update),N.on("remove",this._clearFadeTimer),N._addMarker(this),this.setDraggable(this._draggable),this._update(),N.on("click",this._onMapClick)),this}remove(){const N=this._map;return N&&(N.off("click",this._onMapClick),N.off("move",this._updateMoving),N.off("moveend",this._update),N.off("mousedown",this._addDragHandler),N.off("touchstart",this._addDragHandler),N.off("mouseup",this._onUp),N.off("touchend",this._onUp),N.off("mousemove",this._onMove),N.off("touchmove",this._onMove),N.off("remove",this._clearFadeTimer),N._removeMarker(this),this._map=void 0),this._clearFadeTimer(),this._element.remove(),this._popup&&this._popup.remove(),this}getLngLat(){return this._lngLat}setLngLat(N){return this._lngLat=o.aU.convert(N),this._pos=null,this._popup&&this._popup.setLngLat(this._lngLat),this._update(!0),this}setAltitude(N){return N===this._altitude||(this._defaultMarker&&(this._altitude===0&&N!==0||this._altitude!==0&&N===0)&&(this._element=this._createDefaultMarker()),this._altitude=N||O1.altitude,this._update()),this}getAltitude(){return this._altitude}getElement(){return this._element}setPopup(N){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")),N){if(!("offset"in N.options)){const W=Math.sqrt(Math.pow(13.5,2)/2);N.options.offset=this._defaultMarker?{top:[0,0],"top-left":[0,0],"top-right":[0,0],bottom:[0,-38.1],"bottom-left":[W,-1*(38.1-13.5+W)],"bottom-right":[-W,-1*(38.1-13.5+W)],left:[13.5,-1*(38.1-13.5)],right:[-13.5,-1*(38.1-13.5)]}:this._offset}this._popup=N,N._marker=this,N._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(N){const T=N.code,z=N.charCode||N.keyCode;T!=="Space"&&T!=="Enter"&&z!==32&&z!==13||this.togglePopup()}_onMapClick(N){const T=N.originalEvent.target,z=this._element;this._popup&&(T===z||z.contains(T))&&this.togglePopup()}getPopup(){return this._popup}togglePopup(){const N=this._popup;return N?(N.isOpen()?(N.remove(),this._element.setAttribute("aria-expanded","false")):this._map&&(N.addTo(this._map),this._element.setAttribute("aria-expanded","true")),this):this}_behindTerrain(){const N=this._map,T=this._pos;if(!N||!T)return!1;const z=N.unproject(T,this._altitude),W=N.getFreeCameraOptions();if(!W.position)return!1;const Q=W.position.toLngLat();return Q.distanceTo(z)<.9*Q.distanceTo(this._lngLat)}_evaluateOpacity(){const N=this._map;if(!N)return;const T=this._pos;if(!T||T.x<0||T.x>N.transform.width||T.y<0||T.y>N.transform.height)return void this._clearFadeTimer();const z=N.unproject(T,this._altitude);let W;N._showingGlobe()&&o.e$(N.transform,this._lngLat)?W=0:(W=1-N._queryFogOpacity(z),N.transform._terrainEnabled()&&N.getTerrain()&&this._behindTerrain()&&(W*=this._occludedOpacity)),this._element.style.opacity=`${W}`,this._element.style.pointerEvents=W>0?"auto":"none",this._popup&&this._popup._setOpacity(W),this._fadeTimer=null}_clearFadeTimer(){this._fadeTimer&&(clearTimeout(this._fadeTimer),this._fadeTimer=null)}_updateDOM(){const N=this._pos;if(!N||!this._map)return;const T=this._offset.mult(this._scale);this._element.style.transform=` translate(${N.x}px,${N.y}px) ${tI[this._anchor]} ${this._calculateXYTransform()} ${this._calculateZTransform()} translate(${T.x}px,${T.y}px) `}_calculateXYTransform(){const N=this._pos,T=this._map,z=this.getPitchAlignment();if(!T||!N||z!=="map")return"";if(!T._showingGlobe()){const _e=T.getPitch();return _e?`rotateX(${_e}deg)`:""}const W=o.cH(o.f0(T.transform,this._lngLat)),Q=N.sub(o.f1(T.transform)),ee=Math.abs(Q.x)+Math.abs(Q.y);if(ee===0)return"";const ue=W/ee;return`rotateX(${-Q.y*ue}deg) rotateY(${Q.x*ue}deg)`}_calculateZTransform(){const N=this._pos,T=this._map;if(!T||!N)return"";let z=0;const W=this.getRotationAlignment();if(W==="map")if(T._showingGlobe()){const Q=T.project(new o.aU(this._lngLat.lng,this._lngLat.lat+.001),this._altitude),ee=T.project(new o.aU(this._lngLat.lng,this._lngLat.lat-.001),this._altitude).sub(Q);z=o.cH(Math.atan2(ee.y,ee.x))-90}else z=-T.getBearing();else if(W==="horizon"){const Q=o.aj(4,6,T.getZoom()),ee=o.f1(T.transform);ee.y+=Q*T.transform.height;const ue=N.sub(ee),_e=o.cH(Math.atan2(ue.y,ue.x));z=(_e>90?_e-270:_e+90)*(1-Q)}return z+=this._rotation,z?`rotateZ(${z}deg)`:""}_update(N){cancelAnimationFrame(this._updateFrameId);const T=this._map;T&&(T.transform.renderWorldCopies&&(this._lngLat=MK(this._lngLat,this._pos,T.transform)),this._pos=T.project(this._lngLat,this._altitude),N===!0?this._updateFrameId=requestAnimationFrame(()=>{this._element&&this._pos&&this._anchor&&(this._pos=this._pos.round(),this._updateDOM())}):this._pos=this._pos.round(),T._requestDomTask(()=>{this._map&&(this._element&&this._pos&&this._anchor&&this._updateDOM(),(T._showingGlobe()||T.getTerrain()||T.getFog())&&!this._fadeTimer&&(this._fadeTimer=window.setTimeout(this._evaluateOpacity.bind(this),60)))}))}getOffset(){return this._offset}setOffset(N){return this._offset=o.P.convert(N),this._update(),this}addClassName(N){return this._element.classList.add(N),this}removeClassName(N){return this._element.classList.remove(N),this}toggleClassName(N){return this._element.classList.toggle(N)}_onMove(N){const T=this._map;if(!T)return;const z=this._pointerdownPos,W=this._positionDelta;if(z&&W){if(!this._isDragging){const Q=this._clickTolerance||T._clickTolerance;if(N.point.dist(z)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 hh(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 _ie,this._domRenderTaskQueue=new _ie,this._controls=[],this._markers=[],this._popups=[],this._mapId=o.r(),this._locale=Object.assign({},NDe,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 jDe(0),this._interactionRange=[1/0,-1/0],this._visibilityHidden=0,this._useExplicitProjection=!1,this._frameId=0,this._scaleFactor=R.scaleFactor,this._requestManager=new $(R.transformRequest,R.accessToken,R.testMode);const T=ce(R.accessToken||o.g.ACCESS_TOKEN);if(T&&"atlas"in T&&typeof T.atlas=="number"&&(this._tokenExpiration=T.atlas),this._silenceAuthErrors=!!R.testMode,this._contextCreateOptions=R.contextCreateOptions?Object.assign({},R.contextCreateOptions):{},typeof R.container=="string"){const z=document.getElementById(R.container);if(!z)throw new Error(`Container '${R.container.toString()}' not found.`);this._container=z}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 vie(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 Mh(typeof R.hash=="string"&&R.hash||void 0).addTo(this)),!this._hash||!this._hash._onHashChange()){N.center==null&&N.zoom==null||(this.transform._unmodified=!1),this.jumpTo({center:R.center,zoom:R.zoom,bearing:R.bearing,pitch:R.pitch});const z=R.bounds;z&&(this.resize(),this.fitBounds(z,Object.assign({},R.fitBoundsOptions,{duration:0})))}this.resize(),R.attributionControl&&this.addControl(new EK({customAttribution:R.customAttribution})),this._logoControl=new TK,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",z=>{this._update(z.dataType==="style"),this.fire(new o.C(`${z.dataType}data`,z))}),this.on("dataloading",z=>{this.fire(new o.C(`${z.dataType}dataloading`,z))}),this._interactions=new Dz(this)}_getMapId(){return this._mapId}addControl(R,N){if(N===void 0&&(N=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 T=R.onAdd(this);this._controls.push(R);const z=this._controlPositions[N];return N.indexOf("bottom")!==-1?z.insertBefore(T,z.firstChild):z.appendChild(T),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 N=this._controls.indexOf(R);return N>-1&&this._controls.splice(N,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 N=!this._moving;return N&&this.fire(new o.C("movestart",R)).fire(new o.C("move",R)),this.fire(new o.C("resize",R)),N&&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(N=>N.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(N=>N==="auto"?navigator.language:N):R}setLanguage(R){const N=this._parseLanguage(R);if(!this.style||N===this._language)return this;this._language=N,this.style.reloadSources();for(const T of this._controls)T._setLanguage&&T._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,N=R.projection.name;let T;N==="globe"&&R.zoom>=o.cv?(R.setMercatorFromTransition(),T=!0):N==="mercator"&&R.zoom=o.cv?this.transform.setMercatorFromTransition():this.transform.setProjection(R),this.style.applyProjectionUpdate();const z=this.transform.getProjection().name==="mercator"&&T!==this.transform.mercatorFromTransition;return(N||z)&&(this.painter.clearBackgroundTiles(),this.style.clearSources(),this._update(!0),this._forceMarkerAndPopupUpdate(!0)),this}project(R,N){return this.transform.locationPoint3D(o.aU.convert(R),N)}unproject(R,N){return this.transform.pointLocation3D(o.P.convert(R),N)}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,N,T){const z=W=>{let Q=[];if(Array.isArray(N)){const ee=N.filter(ue=>this.getLayer(ue));Q=ee.length?this.queryRenderedFeatures(W,{layers:ee}):[]}else Q=this.queryRenderedFeatures(W,{target:N});return Q};if(R==="mouseenter"||R==="mouseover"){let W=!1;return{listener:T,targets:N,delegates:{mousemove:ee=>{const ue=z(ee.point);ue.length?W||(W=!0,T.call(this,new yo(R,this,ee.originalEvent,{features:ue}))):W=!1},mouseout:()=>{W=!1}}}}if(R==="mouseleave"||R==="mouseout"){let W=!1;return{listener:T,targets:N,delegates:{mousemove:ue=>{z(ue.point).length?W=!0:W&&(W=!1,T.call(this,new yo(R,this,ue.originalEvent)))},mouseout:ue=>{W&&(W=!1,T.call(this,new yo(R,this,ue.originalEvent)))}}}}{const W=Q=>{const ee=z(Q.point);ee.length&&(Q.features=ee,T.call(this,Q),delete Q.features)};return{listener:T,targets:N,delegates:{[R]:W}}}}on(R,N,T){if(typeof N=="function"||T===void 0)return super.on(R,N);if(typeof N=="string"&&(N=[N]),!this._areTargetsValid(N))return this;const z=this._createDelegatedListener(R,N,T);this._delegatedListeners=this._delegatedListeners||{},this._delegatedListeners[R]=this._delegatedListeners[R]||[],this._delegatedListeners[R].push(z);for(const W in z.delegates)this.on(W,z.delegates[W]);return this}once(R,N,T){if(typeof N=="function"||T===void 0)return super.once(R,N);if(typeof N=="string"&&(N=[N]),!this._areTargetsValid(N))return this;const z=this._createDelegatedListener(R,N,T);for(const W in z.delegates)this.once(W,z.delegates[W]);return this}off(R,N,T){if(typeof N=="function"||T===void 0)return super.off(R,N);if(typeof N=="string"&&(N=[N]),!this._areTargetsValid(N))return this;const z=this._delegatedListeners?this._delegatedListeners[R]:void 0;return z&&(W=>{for(let Q=0;Q{if(T){const W=typeof T=="string"?T:T instanceof Error?T.message:T.error;o.w(`Unable to perform style diff: ${W}. Rebuilding the style from scratch.`),this._updateStyle(R,N)}else z&&this._update(!0)},()=>this._postStyleLoadEvent()),this):(this._localIdeographFontFamily=N.localIdeographFontFamily,this._localFontFamily=N.localFontFamily,this._updateStyle(R,N))}_getUIString(R){const N=this._locale[R];if(N==null)throw new Error(`Missing UI string '${R}'`);return N}_updateStyle(R,N){if(this.style&&(this.style.setEventedParent(null),this.style._remove(),this.style=void 0),R){const T=Object.assign({},N);N&&N.config&&(T.initialConfig=N.config,delete T.config),this.style=new ph(this,T).load(R),this.style.setEventedParent(this,{style:this.style})}return this._updateTerrain(),this}_lazyInitEmptyStyle(){this.style||(this.style=new ph(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 N of R)if(!this._isValidId(N))return!1;return!0}return this._isTargetValid(R)}addSource(R,N){return this._isValidId(R)?(this._lazyInitEmptyStyle(),this.style.addSource(R,N),this._update(!0)):this}isSourceLoaded(R){return!!this._isValidId(R)&&!!this.style&&this.style._isSourceCacheLoaded(R)}areTilesLoaded(){return this.style.areTilesLoaded()}addSourceType(R,N,T){this._lazyInitEmptyStyle(),this.style.addSourceType(R,N,T)}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,N,{pixelRatio:T=1,sdf:z=!1,stretchX:W,stretchY:Q,content:ee}={}){this._lazyInitEmptyStyle();const ue=o.I.from(R);if(N instanceof HTMLImageElement||ImageBitmap&&N instanceof ImageBitmap){const{width:_e,height:Ee,data:Ie}=o.o.getImageData(N);this.style.addImage(ue,{data:new o.q({width:_e,height:Ee},Ie),pixelRatio:T,stretchX:W,stretchY:Q,content:ee,sdf:z,version:0,usvg:!1})}else if(N.width===void 0||N.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:_e,height:Ee}=N,Ie=N;this.style.addImage(ue,{data:new o.q({width:_e,height:Ee},new Uint8Array(Ie.data)),pixelRatio:T,stretchX:W,stretchY:Q,content:ee,sdf:z,usvg:!1,version:0,userImage:Ie}),Ie.onAdd&&Ie.onAdd(this,R)}}updateImage(R,N){this._lazyInitEmptyStyle();const T=o.I.from(R),z=this.style.getImage(T);if(!z)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 W=N instanceof HTMLImageElement||ImageBitmap&&N instanceof ImageBitmap?o.o.getImageData(N):N,{width:Q,height:ee,data:ue}=W;if(Q===void 0||ee===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(Q!==(z.usvg?z.icon.usvg_tree.width:z.data.width)||ee!==(z.usvg?z.icon.usvg_tree.height:z.data.height))return void this.fire(new o.B(new Error(`The width and height of the updated image (${Q}, ${ee}) must be that same as the previous version of the image (${z.data.width}, ${z.data.height})`)));const _e=!(N instanceof HTMLImageElement||ImageBitmap&&N instanceof ImageBitmap);let Ee=!1;z.usvg?(z.data=new o.q({width:Q,height:ee},new Uint8Array(ue)),z.usvg=!1,z.icon=void 0,Ee=!0):z.data.replace(ue,_e),this.style.updateImage(T,z,Ee)}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,N){o.n(this._requestManager.transformRequest(R,o.R.Image),(T,z)=>{N(T,z)})}listImages(){return this.style.listImages().map(R=>R.name)}addModel(R,N){this._lazyInitEmptyStyle(),this.style.addModel(R,N)}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,N){return this._isValidId(R.id)?(this._lazyInitEmptyStyle(),this.style.addLayer(R,N),this._update(!0)):this}getSlot(R){const N=this.getLayer(R);return N&&N.slot||null}setSlot(R,N){return this.style.setSlot(R,N),this.style.mergeLayers(),this._update(!0)}addImport(R,N){return this.style.addImport(R,N).catch(T=>this.fire(new o.B(new Error("Failed to add import",T)))),this}updateImport(R,N){return typeof N!="string"&&N.id!==R?(this.removeImport(R),this.addImport(N)):(this.style.updateImport(R,N),this._update(!0))}removeImport(R){return this.style.removeImport(R),this}moveImport(R,N){return this.style.moveImport(R,N),this._update(!0)}moveLayer(R,N){return this._isValidId(R)?(this.style.moveLayer(R,N),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 N=this.style.getOwnLayer(R);return N?N.type==="custom"?N.implementation:N.serialize():void 0}getSlots(){return this.style.getSlots()}setLayerZoomRange(R,N,T){return this._isValidId(R)?(this.style.setLayerZoomRange(R,N,T),this._update(!0)):this}setFilter(R,N,T={}){return this._isValidId(R)?(this.style.setFilter(R,N,T),this._update(!0)):this}getFilter(R){return this._isValidId(R)?this.style.getFilter(R):null}setPaintProperty(R,N,T,z={}){return this._isValidId(R)?(this.style.setPaintProperty(R,N,T,z),this._update(!0)):this}getPaintProperty(R,N){return this._isValidId(R)?this.style.getPaintProperty(R,N):null}setLayoutProperty(R,N,T,z={}){return this._isValidId(R)?(this.style.setLayoutProperty(R,N,T,z),this._update(!0)):this}getLayoutProperty(R,N){return this._isValidId(R)?this.style.getLayoutProperty(R,N):null}setLayerProperty(R,N,T,z={}){return this._isValidId(R)?(N==="appearances"&&this._postAddingAppearancesToStyleEvent(),this.style.setLayerProperty(R,N,T,z),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,N){return this.style.setSchema(R,N),this._update(!0)}getConfig(R){return this.style.getConfig(R)}setConfig(R,N){return this.style.setConfig(R,N),this._update(!0)}getConfigProperty(R,N){return this.style.getConfigProperty(R,N)}setConfigProperty(R,N,T){return this.style.setConfigProperty(R,N,T),this._update(!0)}getFeaturesetDescriptors(R){return this.style.getFeaturesetDescriptors(R)}setLights(R){if(this._lazyInitEmptyStyle(),R&&R.length===1&&R[0].type==="flat"){const N=R[0];N.properties?this.style.setFlatLight(N.properties,N.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,N={}){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,N){return this._lazyInitEmptyStyle(),this.style.setImportColorTheme(R,N),this._update(!0)}setCamera(R){return this.style.setCamera(R),this._triggerCameraUpdate(R)}getNearClipOffset(){return this.transform.nearClipOffset}setNearClipOffset(R){const N=this.transform.nearClipOffset!==R;return this.transform.nearClipOffset=R,this._update(N)}_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,N){return R.source&&!this._isValidId(R.source)?this:(this.style.setFeatureState(R,N),this._update())}removeFeatureState(R,N){return R.source&&!this._isValidId(R.source)?this:(this.style.removeFeatureState(R,N),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,N){return this.style.isIndoorEnabled()?this.style.indoorManager.getIndoorTileOptions(R,N):null}_updateContainerDimensions(){if(!this._container)return;const R=this._container.getBoundingClientRect().width||400,N=this._container.getBoundingClientRect().height||300;let T,z,W,Q=this._container;for(;Q&&(!z||!W);){const ee=window.getComputedStyle(Q).transform;ee&&ee!=="none"&&(T=ee.match(/matrix.*\((.+)\)/)[1].split(", "),T[0]&&T[0]!=="0"&&T[0]!=="1"&&(z=T[0]),T[3]&&T[3]!=="0"&&T[3]!=="1"&&(W=T[3])),Q=Q.parentElement}this._containerWidth=z?Math.abs(R/z):R,this._containerHeight=W?Math.abs(N/W):N}_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=y("div","mapboxgl-canary",R)).style.visibility="hidden",this._detectMissingCSS();const N=this._canvasContainer=y("div","mapboxgl-canvas-container",R);this._canvas=y("canvas","mapboxgl-canvas",N),this._interactive&&(N.classList.add("mapboxgl-interactive"),this._canvas.setAttribute("tabindex","0")),this._canvas.addEventListener("webglcontextlost",this._contextLost,!1),this._canvas.addEventListener("webglcontextrestored",this._contextRestored,!1),this._canvas.setAttribute("aria-label",this._getUIString("Map.Title")),this._canvas.setAttribute("role","region"),this._updateContainerDimensions(),this._resizeCanvas(this._containerWidth,this._containerHeight);const T=this._controlContainer=y("div","mapboxgl-control-container",R),z=this._controlPositions={};["top-left","top","top-right","right","bottom-right","bottom","bottom-left","left"].forEach(W=>{z[W]=y("div",`mapboxgl-ctrl-${W}`,T)}),this._container.addEventListener("scroll",this._onMapScroll,!1)}_resizeCanvas(R,N){const T=o.o.devicePixelRatio||1;this._canvas.width=T*Math.ceil(R),this._canvas.height=T*Math.ceil(N),this._canvas.style.width=`${R}px`,this._canvas.style.height=`${N}px`}_addMarker(R){this._markers.push(R)}_removeMarker(R){const N=this._markers.indexOf(R);N!==-1&&this._markers.splice(N,1)}_addPopup(R){this._popups.push(R)}_removePopup(R){const N=this._popups.indexOf(R);N!==-1&&this._popups.splice(N,1)}_setupPainter(){const R=Object.assign({},f.supported.webGLContextAttributes,{failIfMajorPerformanceCaveat:this._failIfMajorPerformanceCaveat,preserveDrawingBuffer:this._preserveDrawingBuffer,antialias:this._antialias||!1}),N=this._canvas.getContext("webgl2",R);N?(Ve(N,!0),this.painter=new nc(N,this._contextCreateOptions,this.transform,this._scaleFactor,this._worldview),this.on("data",T=>{if(T.dataType==="source"){const z=this.transform.elevation?this.transform.elevation._source():null;z&&T.sourceCacheId===z.id&&this.style&&this.style._setLabelPlacementStale(),this.painter.setTileLoadedFlag(!0)}}),o.k.testSupport(N)):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 N;this.fire(new o.C("renderstart")),++this._frameId;const T=this.painter.context.extTimerQuery,z=o.o.now(),W=this.painter.context.gl;if(this.listens("gpu-timing-frame")&&(N=W.createQuery(),W.beginQuery(T.TIME_ELAPSED_EXT,N)),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 Q=this._isInitialLoad?0:this._fadeDuration;if(this.style&&this._styleDirty){this._styleDirty=!1;const _e=this.transform.zoom,Ee=this.transform.pitch,Ie=o.o.now(),Je=new o.ae(_e,{now:Ie,fadeDuration:Q,pitch:Ee,transition:this.style.transition,worldview:this._worldview});this.style.update(Je)}this.style&&this.style.hasFogTransition()&&(this.style._markersNeedUpdate=!0,this._sourcesDirty=!0);let ee=!1;if(this.style&&this._sourcesDirty?(this._sourcesDirty=!1,this.painter._updateFog(this.style),this._updateTerrain(),ee=this._updateAverageElevation(z),this.style.updateSources(this.transform),this.style.updateImageProviders(),this.isMoving()||this._forceMarkerAndPopupUpdate()):ee=this._updateAverageElevation(z),this.style&&(this._placementDirty=this.style._updatePlacement(this.painter.transform,this.showCollisionBoxes,Q,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:Q,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(),N){const _e=o.o.now()-z;W.endQuery(T.TIME_ELAPSED_EXT),setTimeout(()=>{const Ee=W.getQueryParameter(N,W.QUERY_RESULT)/1e6;W.deleteQuery(N),this.fire(new o.C("gpu-timing-frame",{cpuTime:_e,gpuTime:Ee}))},50)}if(this.listens("gpu-timing-layer")){const _e=this.painter.collectGpuTimers();setTimeout(()=>{const Ee=this.painter.queryGpuTimers(_e);this.fire(new o.C("gpu-timing-layer",{layerTimes:Ee}))},50)}if(this.listens("gpu-timing-deferred-render")){const _e=this.painter.collectDeferredRenderGpuQueries();setTimeout(()=>{const Ee=this.painter.queryGpuTimeDeferredRender(_e);this.fire(new o.C("gpu-timing-deferred-render",{gpuTime:Ee}))},50)}const ue=this._sourcesDirty||this._styleDirty||this._placementDirty||ee;if(ue||this._repaint)this.triggerRepaint();else{const _e=this.idle();if(_e&&(ee=this._updateAverageElevation(z,!0)),ee)this.triggerRepaint();else if(this._triggerFrame(!1),_e&&(this.fire(new o.C("idle")),this._isInitialLoad=!1,this.speedIndexTiming)){const Ee=this._calculateSpeedIndex();this.fire(new o.C("speedindexcompleted",{speedIndex:Ee})),this.speedIndexTiming=!1}}!this._loaded||this._fullyLoaded||ue||(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 N of this._markers)R&&!this.getRenderWorldCopies()&&(N._lngLat=N._lngLat.wrap()),N._update();for(const N of this._popups)!R||this.getRenderWorldCopies()||N._trackPointer||(N._lngLat=N._lngLat.wrap()),N._update()}_updateAverageElevation(R,N=!1){const T=W=>(this.transform.averageElevation=W,this._update(!1),!0);if(!this.painter.averageElevationNeedsEasing())return this.transform.averageElevation!==0&&T(0);const z=this.transform.elevation&&this.transform.elevation.exaggeration()!==this._averageElevationExaggeration;if(z||(N||R-this._averageElevationLastSampledAt>500)&&!this._averageElevation.isEasing(R)){const W=this.transform.averageElevation;let Q=this.transform.sampleAverageElevation();this.transform.elevation!=null&&(this._averageElevationExaggeration=this.transform.elevation.exaggeration()),isNaN(Q)?Q=0:this._averageElevationLastSampledAt=R;const ee=Math.abs(W-Q);if(ee>1){if(this._isInitialLoad||z)return this._averageElevation.jumpTo(Q),T(Q);this._averageElevation.easeTo(Q,R,300)}else if(ee>1e-4)return this._averageElevation.jumpTo(Q),T(Q)}return!!this._averageElevation.isEasing(R)&&T(this._averageElevation.getValue(R))}_isTokenExpired(){return this._tokenExpiration!=null&&Date.now()>this._tokenExpiration}_revokeAuth(){const R=this.painter.context.gl;Ve(R,!1),this._logoControl instanceof TK&&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(){Ne(this._getMapId(),this._requestManager._skuToken,this._requestManager._customAccessToken,R=>{R&&(R.message!==G&&R.status!==401||this._revokeAuth())}),this._isTokenExpired()&&this._revokeAuth(),he(this._getMapId(),this._requestManager._skuToken,this._requestManager._customAccessToken,()=>{})}_postStyleLoadEvent(){this.style.globalId&&Ce(this._requestManager._customAccessToken,{map:this,style:this.style.globalId,importedStyles:this.style.getImportGlobalIds()})}_postStyleWithAppearanceEvent(){this.style.globalId&&this.style.hasAppearances()&&Pe(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(),N=this.painter.getCanvasCopiesAndTimestamps();N.timeStamps.push(performance.now());const T=this.painter.context.gl,z=T.createFramebuffer();function W(Q){T.framebufferTexture2D(T.FRAMEBUFFER,T.COLOR_ATTACHMENT0,T.TEXTURE_2D,Q,0);const ee=new Uint8Array(T.drawingBufferWidth*T.drawingBufferHeight*4);return T.readPixels(0,0,T.drawingBufferWidth,T.drawingBufferHeight,T.RGBA,T.UNSIGNED_BYTE,ee),ee}return T.bindFramebuffer(T.FRAMEBUFFER,z),this._canvasPixelComparison(W(R),N.canvasCopies.map(W),N.timeStamps)}_canvasPixelComparison(R,N,T){let z=T[1]-T[0];const W=R.length/4;for(let Q=0;Q{const T=!!this._renderNextFrame;this._frame=null,this._renderNextFrame=null,T&&this._render(N)}))}_preloadTiles(R){const N=this.style?this.style.getSourceCaches():[];return o.t(N,(T,z)=>T._preloadTiles(R,z),()=>{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,N){o.e_(R,N)}get version(){return c}},NavigationControl:class{constructor(R={}){this.options=Object.assign({},CDe,R),this._container=y("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._container.addEventListener("contextmenu",N=>N.preventDefault()),this.options.showZoom&&(o.aZ(["_setButtonTitle","_updateZoomButtons"],this),this._zoomInButton=this._createButton("mapboxgl-ctrl-zoom-in",N=>{this._map&&this._map.zoomIn({},{originalEvent:N})}),y("span","mapboxgl-ctrl-icon",this._zoomInButton).setAttribute("aria-hidden","true"),this._zoomOutButton=this._createButton("mapboxgl-ctrl-zoom-out",N=>{this._map&&this._map.zoomOut({},{originalEvent:N})}),y("span","mapboxgl-ctrl-icon",this._zoomOutButton).setAttribute("aria-hidden","true")),this.options.showCompass&&(o.aZ(["_rotateCompassArrow"],this),this._compass=this._createButton("mapboxgl-ctrl-compass",N=>{const T=this._map;T&&(this.options.visualizePitch?T.resetNorthPitch({},{originalEvent:N}):T.resetNorth({},{originalEvent:N}))}),this._compassIcon=y("span","mapboxgl-ctrl-icon",this._compass),this._compassIcon.setAttribute("aria-hidden","true"))}_updateZoomButtons(){const R=this._map;if(!R)return;const N=R.getZoom(),T=N===R.getMaxZoom(),z=N===R.getMinZoom();this._zoomInButton.disabled=T,this._zoomOutButton.disabled=z,this._zoomInButton.setAttribute("aria-disabled",T.toString()),this._zoomOutButton.setAttribute("aria-disabled",z.toString())}_rotateCompassArrow(){const R=this._map;if(!R)return;const N=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=N)})}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 eI(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,N){const T=y("button",R,this._container);return T.type="button",T.addEventListener("click",N),T}_setButtonTitle(R,N){if(!this._map)return;const T=this._map._getUIString(`NavigationControl.${N}`);R.setAttribute("aria-label",T),R.firstElementChild&&R.firstElementChild.setAttribute("title",T)}},GeolocateControl:class extends o.E{constructor(R={}){super();const N=navigator.geolocation;this.options=Object.assign({geolocation:N},sI,R),o.aZ(["_onSuccess","_onError","_onZoom","_finish","_setupUI","_updateCamera","_updateMarker","_updateMarkerRotation","_onDeviceOrientation"],this),this._updateMarkerRotationThrottled=Di(this._updateMarkerRotation,20),this._numberOfWatches=0}onAdd(R){return this._map=R,this._container=y("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 N=(T=!!this.options.geolocation)=>{this._supportsGeolocation=T,R(T)};this._supportsGeolocation!==void 0?R(this._supportsGeolocation):navigator.permissions!==void 0?navigator.permissions.query({name:"geolocation"}).then(T=>N(T.state!=="denied")).catch(()=>N()):N()}_isOutOfMapMaxBounds(R){const N=this._map.getMaxBounds(),T=R.coords;return!!N&&(T.longitudeN.getEast()||T.latitudeN.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 N=new o.aU(R.coords.longitude,R.coords.latitude),T=R.coords.accuracy,z=this._map.getBearing(),W=Object.assign({bearing:z},this.options.fitBoundsOptions);this._map.fitBounds(N.toBounds(T),W,{geolocateSource:!0})}_updateMarker(R){if(R){const N=new o.aU(R.coords.longitude,R.coords.latitude);this._accuracyCircleMarker.setLngLat(N).addTo(this._map),this._userLocationDotMarker.setLngLat(N).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,N=o.bU(1,R._center.lat)*R.worldSize,T=Math.ceil(2*this._accuracy*N);this._circleElement.style.width=`${T}px`,this._circleElement.style.height=`${T}px`}_onZoom(){this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius()}_updateMarkerRotation(){this._userLocationDotMarker&&typeof this._heading=="number"?(this._userLocationDotMarker.setRotation(this._heading),this._userLocationDotMarker.addClassName("mapboxgl-user-location-show-heading")):(this._userLocationDotMarker.removeClassName("mapboxgl-user-location-show-heading"),this._userLocationDotMarker.setRotation(0))}_onError(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 N=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.setAttribute("aria-label",N),this._geolocateButton.firstElementChild&&this._geolocateButton.firstElementChild.setAttribute("title",N),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",N=>N.preventDefault()),this._geolocateButton=y("button","mapboxgl-ctrl-geolocate",this._container),y("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 N=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.disabled=!0,this._geolocateButton.setAttribute("aria-label",N),this._geolocateButton.firstElementChild&&this._geolocateButton.firstElementChild.setAttribute("title",N)}else{const N=this._map._getUIString("GeolocateControl.FindMyLocation");this._geolocateButton.setAttribute("aria-label",N),this._geolocateButton.firstElementChild&&this._geolocateButton.firstElementChild.setAttribute("title",N)}this.options.trackUserLocation&&(this._geolocateButton.setAttribute("aria-pressed","false"),this._watchState="OFF"),this.options.showUserLocation&&(this._dotElement=y("div","mapboxgl-user-location"),this._dotElement.appendChild(y("div","mapboxgl-user-location-dot")),this._dotElement.appendChild(y("div","mapboxgl-user-location-heading")),this._userLocationDotMarker=new Qb({element:this._dotElement,rotationAlignment:"map",pitchAlignment:"map"}),this._circleElement=y("div","mapboxgl-user-location-accuracy-circle"),this._accuracyCircleMarker=new Qb({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",N=>{N.geolocateSource||this._watchState!=="ACTIVE_LOCK"||N.originalEvent&&N.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??sI.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 N="ondeviceorientationabsolute"in window?"deviceorientationabsolute":"deviceorientation";window.addEventListener(N,this._onDeviceOrientation)};typeof DeviceOrientationEvent.requestPermission=="function"?DeviceOrientationEvent.requestPermission().then(N=>{N==="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:EK,ScaleControl:class{constructor(R={}){this.options=Object.assign({},Um,R),o.aZ(["_update","_setScale","setUnit"],this)}getDefaultPosition(){return"bottom-left"}_update(){const R=this.options.maxWidth||100,N=this._map,T=N._containerHeight/2,z=N._containerWidth/2-R/2,W=N.unproject([z,T]),Q=N.unproject([z+R,T]),ee=W.distanceTo(Q);if(this.options.unit==="imperial"){const ue=3.2808*ee;ue>5280?this._setScale(R,ue/5280,"mile"):this._setScale(R,ue,"foot")}else this.options.unit==="nautical"?this._setScale(R,ee/1852,"nautical-mile"):ee>=1e3?this._setScale(R,ee/1e3,"kilometer"):this._setScale(R,ee,"meter")}_setScale(R,N,T){this._map._requestDomTask(()=>{const z=function(Q){const ee=Math.pow(10,`${Math.floor(Q)}`.length-1);let ue=Q/ee;return ue=ue>=10?10:ue>=5?5:ue>=3?3:ue>=2?2:ue>=1?1:function(_e){const Ee=Math.pow(10,Math.ceil(-Math.log(_e)/Math.LN10));return Math.round(_e*Ee)/Ee}(ue),ee*ue}(N),W=z/N;this._container.innerHTML=T!=="nautical-mile"?new Intl.NumberFormat(this._language,{style:"unit",unitDisplay:"short",unit:T}).format(z):`${z} ${Jb[T]}`,this._container.style.width=R*W+"px"})}onAdd(R){return this._map=R,this._language=R.getLanguage(),this._container=y("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=y("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=y("button","mapboxgl-ctrl-fullscreen",this._controlContainer);y("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=y("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,N){const T=y("button",R,this._container);return T.type="button",T.addEventListener("click",N),T}_setButtonTitle(R,N){R.setAttribute("aria-label",N),R.textContent=N}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 N=this._model;this._model=R,this._container.style.display="inline-block";const T=!N||N.floors.length!==R.floors.length||N.floors.some((z,W)=>z.id!==R.floors[W].id);if(T&&(this._visibleFloorStart=0,this._lastSelectedFloorId=null),R.selectedFloorId){if(R.selectedFloorId!==this._lastSelectedFloorId||T){const z=R.floors.findIndex(W=>W.id===R.selectedFloorId);if(z!==-1){const W=R.floors.length;let Q,ee;W<=5?(Q=0,ee=W-1):this._visibleFloorStart===0?(Q=0,ee=3):this._visibleFloorStart>=W-3?(Q=W-3-1,ee=W-1):(Q=this._visibleFloorStart,ee=this._visibleFloorStart+3-1),zee&&(this._visibleFloorStart=z-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);y("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 N=this._model.floors,T=N.length;if(T<=5)return void N.forEach(ee=>this._createFloorButton(ee));const z=this._visibleFloorStart===0,W=this._visibleFloorStart>=T-3;if(z)this._createFloorButton(N[0]);else{const ee=this._createButton("mapboxgl-ctrl-arrow-up",this._scrollUp);y("span","mapboxgl-ctrl-icon",ee).setAttribute("aria-hidden","true"),this._container.appendChild(ee)}let Q=[];if(Q=z?N.slice(1,4):W?N.slice(this._visibleFloorStart-1,this._visibleFloorStart+3-1):N.slice(this._visibleFloorStart,this._visibleFloorStart+3),Q.forEach(ee=>this._createFloorButton(ee)),W)this._createFloorButton(N[T-1]);else{const ee=this._createButton("mapboxgl-ctrl-arrow-down",this._scrollDown);y("span","mapboxgl-ctrl-icon",ee).setAttribute("aria-hidden","true"),this._container.appendChild(ee)}}_createFloorButton(R){const N=this._createButton("mapboxgl-ctrl-level-button",()=>{const Q=R.id;this._model&&this._model.selectedFloorId===Q&&this._model.activeFloorsVisible||this._map&&(this._model&&!this._model.activeFloorsVisible&&this._map.style&&this._map.style.indoorManager&&this._map.style.indoorManager.setActiveFloorsVisibility(!0),this._map._selectIndoorFloor(Q))}),T=(R.name||"").trim(),z=R.zIndex.toString(),W=T?Array.from(T).slice(0,3).join(""):z;this._setButtonTitle(N,W),this._model&&this._model.activeFloorsVisible&&R.id===this._model.selectedFloorId&&N.classList.add("mapboxgl-ctrl-level-button-selected"),this._container&&this._container.appendChild(N)}_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 N=R.length-3;this._visibleFloorStart===N-1&&(this._visibleFloorStart=N-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(nI),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 N=this._map;return N&&(N.on("move",this._update),N.off("mousemove",this._onMouseEvent),N._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 N=document.createDocumentFragment(),T=document.createElement("body");let z;for(T.innerHTML=R;z=T.firstChild,z;)N.appendChild(z);return this.setDOMContent(N)}getMaxWidth(){return this._container&&this._container.style.maxWidth}setMaxWidth(R){return this.options.maxWidth=R,this._update(),this}setDOMContent(R){let N=this._content;if(N)for(;N.hasChildNodes();)N.firstChild&&N.removeChild(N.firstChild);else N=this._content=y("div","mapboxgl-popup-content",this._container||void 0);if(N.appendChild(R),this.options.closeButton){const T=this._closeButton=y("button","mapboxgl-popup-close-button",N);T.type="button",T.setAttribute("aria-label","Close popup"),T.innerHTML='',T.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 N;return this._classList.delete(R)?N=!1:(this._classList.add(R),N=!0),this._updateClassList(),N}_onMouseEvent(R){this._update(R.point)}_getAnchor(R){if(this.options.anchor)return this.options.anchor;const N=this._map,T=this._container,z=this._pos;if(!N||!T||!z)return"bottom";const W=T.offsetWidth,Q=T.offsetHeight,ee=z.xN.transform.width-W/2;if(z.y+RN.transform.height-Q){if(ee)return"bottom-left";if(ue)return"bottom-right"}return ee?"left":ue?"right":"bottom"}_updateClassList(){const R=this._container;if(!R)return;const N=[...this._classList];N.push("mapboxgl-popup"),this._anchor&&N.push(`mapboxgl-popup-anchor-${this._anchor}`),this._trackPointer&&N.push("mapboxgl-popup-track-pointer"),R.className=N.join(" ")}_update(R){const N=this._map,T=this._content;if(!N||!this._lngLat&&!this._trackPointer||!T)return;let z=this._container;if(z||(z=this._container=y("div","mapboxgl-popup",N.getContainer()),this._tip=y("div","mapboxgl-popup-tip",z),z.appendChild(T)),this.options.maxWidth&&z.style.maxWidth!==this.options.maxWidth&&(z.style.maxWidth=this.options.maxWidth),N.transform.renderWorldCopies&&!this._trackPointer&&(this._lngLat=MK(this._lngLat,this._pos,N.transform)),!this._trackPointer||R){const W=this._pos=this._trackPointer&&R instanceof o.P?R:N.project(this._lngLat,this._altitude),Q=Rz(this.options.offset),ee=this._anchor=this._getAnchor(Q.y),ue=Rz(this.options.offset,ee),_e=W.add(ue).round();N._requestDomTask(()=>{this._container&&ee&&(this._container.style.transform=`${tI[ee]} translate(${_e.x}px,${_e.y}px)`)})}if(!this._marker&&N._showingGlobe()){const W=o.e$(N.transform,this._lngLat)?0:1;this._setOpacity(W)}this._updateClassList()}_focusFirstElement(){if(!this.options.focusAfterOpen||!this._container)return;const R=this._container.querySelector(ADe);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:Qb,Style:ph,LngLat:o.aU,LngLatBounds:o.aK,Point:o.P,MercatorCoordinate:o.ag,FreeCameraOptions:Ry,Evented:o.E,config:o.g,prewarm:function(){qt().acquire(nt)},clearPrewarmedResources:function(){const R=ct;R&&(R.isPreloaded()&&R.numActive()===1?(R.release(nt),ct=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 $e.workerCount},set workerCount(R){$e.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 N=o.o.resolveURL(R);o.g.MESHOPT_URL=N,o.g.MESHOPT_SIMD_URL=N},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})})(SFt);var G6s=SFt.exports;const Id=_d(G6s),nft={coming_soon:"#3B82F6",office_exclusive:"#6366F1",pre_market:"#06B6D4",active:"#10B981",price_improvement:"#F97316",under_contract:"#8B5CF6",sold:"#6B7280"},rft={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 W6s(s){return s>=1e6?`$${(s/1e6).toFixed(1)}M`:`$${(s/1e3).toFixed(0)}K`}function K6s({listings:s,isLoading:t}){const n=Fn(),r=_.useRef(null),a=_.useRef(null),i=_.useRef([]),[l,o]=_.useState(""),[c,d]=_.useState(!0);return _.useEffect(()=>{(async()=>{d(!0);try{const{data:m}=await q.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();m!=null&&m.value&&o(m.value)}catch(m){console.error("Error fetching mapbox token:",m)}d(!1)})()},[]),_.useEffect(()=>{if(!r.current||!l||a.current)return;Id.accessToken=l;const h=s.filter(f=>f.latitude!=null&&f.longitude!=null);let m=[-98.5795,39.8283],p=4;if(h.length>0){const f=h.reduce((v,g)=>v+g.longitude,0)/h.length,y=h.reduce((v,g)=>v+g.latitude,0)/h.length;m=[f,y],p=h.length===1?12:10}return a.current=new Id.Map({container:r.current,style:"mapbox://styles/mapbox/light-v11",zoom:p,center:m}),a.current.addControl(new Id.NavigationControl,"top-right"),()=>{var f;(f=a.current)==null||f.remove(),a.current=null}},[l]),_.useEffect(()=>{if(!a.current||!l)return;i.current.forEach(m=>m.remove()),i.current=[];const h=s.filter(m=>m.latitude!=null&&m.longitude!=null);if(h.forEach(m=>{var S,C,E;const p=nft[m.status]||"#10B981",f=((S=m.photos)==null?void 0:S.find(P=>P.is_primary))||((C=m.photos)==null?void 0:C[0]),v=window.location.hostname==="listings.relevelup.com"||window.location.hostname.startsWith("listings.")?`/${m.slug||m.id}`:`/public/listing/${m.slug||m.id}`,g=document.createElement("div");g.className="cursor-pointer",g.innerHTML=`
`;const b=new Id.Popup({offset:25,closeButton:!0,maxWidth:"280px"}).setHTML(`
${f!=null&&f.photo_url?``:""}
${W6s(m.price)}
${m.property_address||""}
${m.city}, ${m.state}
${rft[m.status]||m.status} ${m.bedrooms?`${m.bedrooms} bed`:""} ${m.bathrooms?`${m.bathrooms} bath`:""}
${(E=m.agent)!=null&&E.name?`
Listed by ${m.agent.name}
`:""}
Click to view details →
`),j=new Id.Marker(g).setLngLat([m.longitude,m.latitude]).setPopup(b).addTo(a.current);i.current.push(j)}),h.length>1){const m=new Id.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]),_.useEffect(()=>(window.__navigateToPublicListing__=h=>{n(h)},()=>{delete window.__navigateToPublicListing__}),[n]),c||t?e.jsx(cn,{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(nft).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:rft[h]})]},h))}),e.jsx("div",{ref:r,className:"w-full h-[500px] rounded-lg shadow-lg border border-gray-200"})]})}const _Oe={active:"Active",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},Y6s={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"},wB="#0d0d0d",aft="#1a1a1a",Gd="#c9a84c",wT="#f0d78c";function AFt(){const[s,t]=_.useState(""),[n,r]=_.useState(!1),[a,i]=_.useState(!1),[l,o]=_.useState(!1),[c,d]=_.useState(-1),u=_.useRef(null),[h,m]=_.useState({status:"",propertyType:"",minPrice:"",maxPrice:""}),{data:p}=E6s(),f=_.useMemo(()=>{if(!p)return[];const O=s.trim().toLowerCase(),V=[...p.cities.map($=>({label:$.label,value:$.city,type:"city",count:$.count})),...p.neighborhoods.map($=>({label:$.label,value:$.neighborhood,type:"neighborhood",count:$.count})),...p.zips.map($=>({label:`ZIP ${$.label}`,value:$.zip,type:"zip",count:$.count}))];return(O?V.filter($=>$.label.toLowerCase().includes(O)||$.value.toLowerCase().includes(O)):V).slice(0,8)},[p,s]);_.useEffect(()=>{const O=V=>{u.current&&!u.current.contains(V.target)&&o(!1)};return document.addEventListener("mousedown",O),()=>document.removeEventListener("mousedown",O)},[]);const{data:y,isLoading:v}=A6s({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}),g=O=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(O),b=()=>{m({status:"",propertyType:"",minPrice:"",maxPrice:""}),t("")},j=s||h.status||h.propertyType||h.minPrice||h.maxPrice,S=typeof window<"u"&&(window.location.hostname==="listings.relevelup.com"||window.location.hostname.startsWith("listings.")),C=O=>S?`/${O.slug||O.id}`:`/public/listing/${O.slug||O.id}`,{featured:E,restListings:P,luxeCount:M,cities:I,activeCount:D}=_.useMemo(()=>{const O=y||[],V=O.filter(be=>be.status==="active"),G=V.length>0?V:O,$=new Intl.DateTimeFormat("en-CA",{timeZone:"America/New_York",year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date),[H,Y,Z]=$.split("-").map(Number),ne=Math.floor(Date.UTC(H,Y-1,Z)/864e5),ce=G.length>0?G[ne%G.length]:void 0,ie=O.filter(be=>!ce||be.id!==ce.id),te=Array.from(new Set(O.map(be=>be.city).filter(Boolean))).slice(0,8),ae=O.filter(be=>(be.price||0)>=1e6).length,le=V.length;return{featured:ce,restListings:ie,luxeCount:ae,cities:te,activeCount:le}},[y]);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:wB,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: ${Gd}; } .lu-gold-line { background: linear-gradient(90deg, transparent, ${Gd}, 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(ir,{to:"/",className:"flex items-center gap-3",children:[e.jsx("img",{src:TH,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(ir,{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 ${Gd}`,color:Gd},children:"About LevelUp"})]}),e.jsx("button",{type:"button",onClick:()=>i(O=>!O),className:"md:hidden inline-flex items-center justify-center w-10 h-10 rounded-full",style:{border:`1px solid ${Gd}`,color:Gd},"aria-label":"Toggle menu","aria-expanded":a,children:a?e.jsx(Qn,{className:"w-5 h-5"}):e.jsx(GA,{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(ir,{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 ${Gd}`,color:Gd},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:H6s,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:Gd}}),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:wT},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 ${Gd}`,backdropFilter:"blur(12px)"},children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Lr,{className:"absolute left-6 top-1/2 -translate-y-1/2 h-5 w-5",style:{color:Gd}}),e.jsx(xe,{placeholder:"City, neighborhood, or ZIP",value:s,onChange:O=>{t(O.target.value),o(!0),d(-1)},onFocus:()=>o(!0),onKeyDown:O=>{if(!(!l||f.length===0))if(O.key==="ArrowDown")O.preventDefault(),d(V=>Math.min(V+1,f.length-1));else if(O.key==="ArrowUp")O.preventDefault(),d(V=>Math.max(V-1,0));else if(O.key==="Enter"&&c>=0){O.preventDefault();const V=f[c];t(V.value),o(!1)}else O.key==="Escape"&&o(!1)},className:"pl-16 h-16 text-base md:text-lg border-0 bg-transparent text-white placeholder:text-white/50 focus-visible:ring-0 rounded-none"})]}),e.jsxs("button",{onClick:()=>r(!n),className:"hidden sm:flex items-center gap-2 px-6 border-l text-sm text-white/80 hover:text-white transition",style:{borderColor:"rgba(201,168,76,0.3)"},children:[e.jsx(tP,{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:Gd,color:wB},onClick:()=>o(!1),children:[e.jsx(Lr,{className:"h-5 w-5"}),e.jsx("span",{className:"hidden md:inline",children:"Search"})]})]}),l&&f.length>0&&e.jsxs("div",{className:"mt-2 rounded-2xl overflow-hidden shadow-2xl animate-fade-in",style:{background:"rgba(13,13,13,0.96)",border:"1px solid rgba(201,168,76,0.35)",backdropFilter:"blur(12px)"},children:[e.jsx("div",{className:"px-5 pt-3 pb-2 text-[10px] tracking-[0.2em] uppercase",style:{color:Gd},children:"Suggestions"}),e.jsx("ul",{className:"max-h-80 overflow-y-auto",children:f.map((O,V)=>e.jsx("li",{children:e.jsxs("button",{type:"button",onMouseEnter:()=>d(V),onClick:()=>{t(O.value),o(!1)},className:"w-full flex items-center justify-between gap-3 px-5 py-3 text-left transition",style:{background:c===V?"rgba(201,168,76,0.12)":"transparent"},children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[O.type==="city"&&e.jsx(Xa,{className:"h-4 w-4 shrink-0",style:{color:Gd}}),O.type==="neighborhood"&&e.jsx(ai,{className:"h-4 w-4 shrink-0",style:{color:Gd}}),O.type==="zip"&&e.jsx(Jr,{className:"h-4 w-4 shrink-0",style:{color:Gd}}),e.jsx("span",{className:"text-white/90 truncate",children:O.label})]}),e.jsxs("span",{className:"text-xs text-white/50 shrink-0",children:[O.count," ",O.count===1?"listing":"listings"]})]})},`${O.type}-${O.value}-${V}`))})]}),l&&s.trim()&&f.length===0&&e.jsx("div",{className:"mt-2 rounded-2xl px-5 py-4 text-sm text-white/70",style:{background:"rgba(13,13,13,0.96)",border:"1px solid rgba(201,168,76,0.25)"},children:"No matches yet — try a nearby city or ZIP."}),n&&e.jsxs("div",{className:"mt-4 p-6 rounded-2xl grid sm:grid-cols-2 md:grid-cols-4 gap-4 animate-fade-in",style:{background:"rgba(26,26,26,0.9)",border:"1px solid rgba(201,168,76,0.25)"},children:[e.jsxs("div",{children:[e.jsx("label",{className:"lu-eyebrow text-white/60 mb-2 block",children:"Status"}),e.jsxs(is,{value:h.status||"all",onValueChange:O=>m({...h,status:O==="all"?"":O}),children:[e.jsx(rs,{className:"lu-input-dark",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"Any status"}),Object.entries(_Oe).map(([O,V])=>e.jsx(He,{value:O,children:V},O))]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"lu-eyebrow text-white/60 mb-2 block",children:"Type"}),e.jsxs(is,{value:h.propertyType||"all",onValueChange:O=>m({...h,propertyType:O==="all"?"":O}),children:[e.jsx(rs,{className:"lu-input-dark",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"Any type"}),Object.entries(Y6s).map(([O,V])=>e.jsx(He,{value:O,children:V},O))]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"lu-eyebrow text-white/60 mb-2 block",children:"Min Price"}),e.jsx(xe,{type:"number",placeholder:"No min",value:h.minPrice,onChange:O=>m({...h,minPrice:O.target.value}),className:"lu-input-dark"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"lu-eyebrow text-white/60 mb-2 block",children:"Max Price"}),e.jsx(xe,{type:"number",placeholder:"No max",value:h.maxPrice,onChange:O=>m({...h,maxPrice:O.target.value}),className:"lu-input-dark"})]}),j&&e.jsx("div",{className:"sm:col-span-2 md:col-span-4 flex justify-end",children:e.jsxs(B,{variant:"ghost",size:"sm",onClick:b,className:"text-white/70 hover:text-white gap-1",children:[e.jsx(Qn,{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:((y==null?void 0:y.length)??0).toString()},{label:"Active Now",value:D.toString()},{label:"Luxury $1M+",value:M.toString()}].map(O=>e.jsxs("div",{children:[e.jsx("div",{className:"lu-serif text-4xl md:text-5xl",style:{color:wT},children:O.value}),e.jsx("div",{className:"lu-eyebrow text-white/60 mt-1",children:O.label})]},O.label))})]}),e.jsxs("div",{className:"absolute bottom-6 left-1/2 -translate-x-1/2 flex flex-col items-center gap-2 text-white/60",children:[e.jsx("span",{className:"lu-eyebrow",children:"Scroll"}),e.jsx(tl,{className:"h-4 w-4 animate-bounce"})]})]})]}),I.length>0&&e.jsx("section",{className:"py-8 overflow-hidden",style:{background:aft,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((O,V)=>e.jsxs("span",{className:"flex items-center gap-3 lu-serif text-2xl md:text-3xl text-white/40",children:[O,e.jsx("span",{className:"h-1.5 w-1.5 rounded-full",style:{background:Gd}})]},V))})}),E&&e.jsx("section",{id:"featured",className:"py-20 md:py-28",children:e.jsxs("div",{className:"max-w-7xl mx-auto px-6",children:[e.jsxs("div",{className:"flex items-end justify-between mb-10 md:mb-14",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[e.jsx(un,{className:"h-4 w-4",style:{color:Gd}}),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:wT},children:"standout"}),"."]})]}),e.jsx("div",{className:"hidden md:block h-px flex-1 mx-8 lu-gold-line"})]}),e.jsx(ir,{to:C(E),className:"group block",children:e.jsxs("div",{className:"grid lg:grid-cols-5 gap-6 lg:gap-10 items-stretch",children:[e.jsxs("div",{className:"lg:col-span-3 relative overflow-hidden rounded-2xl aspect-[4/3] bg-black",children:[(()=>{var V,G;const O=((V=E.photos)==null?void 0:V.find($=>$.is_primary))||((G=E.photos)==null?void 0:G[0]);return O?e.jsx("img",{src:O.photo_url,alt:E.property_address||E.city,className:"w-full h-full object-cover lu-img-zoom"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(Jr,{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:Gd,color:wB},children:_Oe[E.status]||"Featured"})]}),e.jsxs("div",{className:"lg:col-span-2 flex flex-col justify-center",children:[e.jsxs("div",{className:"lu-eyebrow text-white/60 mb-4 flex items-center gap-2",children:[e.jsx(Xa,{className:"h-3.5 w-3.5",style:{color:Gd}}),E.city,E.state?`, ${E.state}`:""]}),E.property_address&&e.jsx("h3",{className:"lu-serif text-3xl md:text-4xl mb-4 leading-tight",children:E.property_address}),e.jsx("div",{className:"lu-serif text-5xl md:text-6xl mb-6",style:{color:wT},children:g(E.price)}),e.jsxs("div",{className:"flex items-center gap-6 text-white/70 mb-8",children:[E.bedrooms&&e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(dj,{className:"h-4 w-4",style:{color:Gd}}),E.bedrooms," bd"]}),E.bathrooms&&e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(S0,{className:"h-4 w-4",style:{color:Gd}}),E.bathrooms," ba"]}),E.square_footage&&e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(wb,{className:"h-4 w-4",style:{color:Gd}}),E.square_footage.toLocaleString()," sf"]})]}),E.description&&e.jsx("p",{className:"text-white/60 leading-relaxed mb-8 line-clamp-4",children:E.description}),e.jsxs("div",{className:"inline-flex items-center gap-3 lu-eyebrow group-hover:gap-5 transition-all",style:{color:Gd},children:["View Residence ",e.jsx(La,{className:"h-4 w-4"})]})]})]})})]})}),e.jsx("section",{id:"collection",className:"py-20 md:py-28",style:{background:aft},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:Gd}}),e.jsx("span",{className:"lu-eyebrow lu-gold",children:"The Collection"}),e.jsx("span",{className:"h-px w-10",style:{background:Gd}})]}),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:wT},children:"carefully considered"}),"."]}),e.jsx("p",{className:"text-white/60 max-w-2xl mx-auto",children:"Browse the full catalogue of LevelUp-represented properties. Filter, refine, and find the one that feels like yours."})]}),v?e.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 gap-8",children:[...Array(6)].map((O,V)=>e.jsxs("div",{className:"space-y-3",children:[e.jsx(cn,{className:"aspect-[4/5] bg-white/5"}),e.jsx(cn,{className:"h-6 w-32 bg-white/5"}),e.jsx(cn,{className:"h-4 w-full bg-white/5"})]},V))}):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(O=>{var G,$,H,Y,Z;const V=((G=O.photos)==null?void 0:G.find(ne=>ne.is_primary))||(($=O.photos)==null?void 0:$[0]);return e.jsxs(ir,{to:C(O),className:"group lu-card-hover block",children:[e.jsxs("div",{className:"relative aspect-[4/5] overflow-hidden bg-black mb-5 rounded-lg",children:[V?e.jsx("img",{src:V.photo_url,alt:O.property_address||O.city,className:"w-full h-full object-cover lu-img-zoom"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(Jr,{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:Gd,border:`1px solid ${Gd}`},children:_Oe[O.status]}),e.jsxs("div",{className:"absolute bottom-4 left-4 right-4 flex items-center gap-4 text-white/90 text-sm opacity-0 group-hover:opacity-100 translate-y-2 group-hover:translate-y-0 transition-all",children:[O.bedrooms&&e.jsxs("span",{children:[O.bedrooms," bd"]}),O.bathrooms&&e.jsxs("span",{children:[O.bathrooms," ba"]}),O.square_footage&&e.jsxs("span",{children:[O.square_footage.toLocaleString()," sf"]})]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"lu-eyebrow text-white/50 mb-2 flex items-center gap-2",children:[e.jsx(Xa,{className:"h-3 w-3",style:{color:Gd}}),O.city,O.state?`, ${O.state}`:""]}),e.jsx("div",{className:"lu-serif text-2xl md:text-3xl mb-1",style:{color:wT},children:g(O.price)}),O.property_address&&e.jsx("p",{className:"text-white/70 text-sm truncate",children:O.property_address}),((H=O.agent)==null?void 0:H.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"}),O.agent.name,(((Y=O.agent.brokerage)==null?void 0:Y.name)||O.agent.brokerage_name)&&e.jsxs("span",{className:"truncate",children:["· ",((Z=O.agent.brokerage)==null?void 0:Z.name)||O.agent.brokerage_name]})]})]})]},O.id)})}):e.jsxs("div",{className:"text-center py-20",children:[e.jsx("div",{className:"w-20 h-20 mx-auto mb-6 rounded-full flex items-center justify-center",style:{border:`1px solid ${Gd}`},children:e.jsx(Jr,{className:"h-8 w-8",style:{color:Gd}})}),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."}),j&&e.jsx(B,{onClick:b,style:{background:Gd,color:wB},className:"hover:brightness-110",children:"Clear filters"})]})]})}),y&&y.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:Gd}}),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:wT},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(K6s,{listings:y,isLoading:v})})]})}),e.jsxs("section",{className:"relative py-24 md:py-32 overflow-hidden lu-grain",children:[e.jsx("div",{className:"absolute inset-0",style:{background:`radial-gradient(ellipse at center, rgba(201,168,76,0.15) 0%, ${wB} 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:Gd}}),e.jsx("span",{className:"lu-eyebrow lu-gold",children:"For Agents"}),e.jsx("span",{className:"h-px w-10",style:{background:Gd}})]}),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:wT},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:Gd,color:wB},children:["Explore LevelUp",e.jsx(La,{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:TH,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(a6s,{}),e.jsx(i6s,{})]})}const Z6s=_.lazy(()=>za(()=>import("./PublicHomeValue-DVO7dbWP.js"),[]));function X6s(){const s=ru(),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(AFt,{}):r==="home-value"||r==="whats-my-home-worth"?e.jsx(_.Suspense,{fallback:e.jsx("div",{}),children:e.jsx(Z6s,{})}):r.startsWith("public/")?null:e.jsx(mJe,{slugOverride:r})}const Q6s=_.lazy(()=>za(()=>import("./CommercialMarketplace-DFGm_hyO.js"),[]));function J6s(){const t=ru().pathname.slice(1);return t?t.startsWith("public/")?null:e.jsx(mJe,{slugOverride:t}):e.jsx(_.Suspense,{fallback:e.jsx("div",{className:"min-h-screen bg-[#0a0d12]"}),children:e.jsx(Q6s,{})})}function EPe({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 EFt=s=>at({queryKey:["agent-card-public",s],queryFn:async()=>{if(!s)throw new Error("No slug provided");const{data:t,error:n}=await q.from("agent_cards").select("*").eq("slug",s).eq("is_published",!0).single();if(n)throw n;const{data:r}=await q.from("profiles").select("name, email, phone, brokerage_id").eq("id",t.user_id).single();let a=null;if(r!=null&&r.brokerage_id){const{data:o}=await q.from("brokerages").select("name").eq("id",r.brokerage_id).single();a=(o==null?void 0:o.name)||null}let i=null;try{const{data:o}=await q.from("profiles").select("avatar_url").eq("id",t.user_id).single();if(o!=null&&o.avatar_url)i=o.avatar_url;else{const{data:c}=await q.storage.from("avatars").list(`${t.user_id}`);if(c&&c.length>0){const{data:d}=q.storage.from("avatars").getPublicUrl(`${t.user_id}/${c[0].name}`);i=`${d.publicUrl}?t=${Date.now()}`}}}catch{}const l={...r||{name:null,email:null,phone:null,brokerage_id:null},email:t.display_email||(r==null?void 0:r.email)||null};return{...t,social_links:t.social_links||[],profile:l,brokerage_name:t.brokerage_display_name||a,avatar_url:i}},enabled:!!s}),eMs=()=>at({queryKey:["agent-cards-admin"],queryFn:async()=>{const{data:s,error:t}=await q.from("agent_cards").select("*").order("created_at",{ascending:!1});if(t)throw t;return s}}),tMs=s=>at({queryKey:["agent-card",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("agent_cards").select("*").eq("user_id",s).maybeSingle();if(n)throw n;return t},enabled:!!s}),TFt=()=>{const s=Bt();return mt({mutationFn:async t=>{const{data:n,error:r}=await q.from("agent_cards").insert(t).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-cards-admin"]}),s.invalidateQueries({queryKey:["agent-card"]}),se.success("Agent card created")},onError:t=>se.error(t.message)})},MFt=()=>{const s=Bt();return mt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("agent_cards").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["agent-cards-admin"]}),s.invalidateQueries({queryKey:["agent-card"]}),se.success("Agent card updated")},onError:t=>se.error(t.message)})},Dd=async(s,t,n,r)=>{const a=new URLSearchParams(window.location.search);await q.from("agent_card_interactions").insert({card_id:s,interaction_type:t,interaction_detail:n||null,referrer:document.referrer||null,user_agent:navigator.userAgent||null,utm_source:a.get("utm_source")||null,utm_medium:a.get("utm_medium")||null,utm_campaign:a.get("utm_campaign")||null,metadata:{}})},sMs=async(s,t)=>{const{error:n}=await q.from("agent_card_leads").insert({card_id:s,...t});if(n)throw n},PFt=s=>at({queryKey:["agent-card-analytics",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("agent_card_interactions").select("interaction_type, interaction_detail, created_at").eq("card_id",s).order("created_at",{ascending:!1}).limit(500);if(n)throw n;const{data:r,error:a}=await q.from("agent_card_leads").select("*").eq("card_id",s).order("created_at",{ascending:!1});if(a)throw a;const i=(t==null?void 0:t.filter(c=>c.interaction_type==="card_view").length)||0,l=(t==null?void 0:t.filter(c=>c.interaction_type==="button_click").length)||0,o=(t==null?void 0:t.filter(c=>c.interaction_type==="contact_saved").length)||0;return{views:i,clicks:l,saves:o,leads:r||[],interactions:t||[]}},enabled:!!s});function TPe({open:s,onOpenChange:t,cardId:n,type:r,agentName:a}){const[i,l]=_.useState(""),[o,c]=_.useState(""),[d,u]=_.useState(""),[h,m]=_.useState(""),[p,f]=_.useState(""),[y,v]=_.useState(!1),g=async b=>{if(b.preventDefault(),!i.trim()){se.error("Please enter your name");return}v(!0);try{await sMs(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}),Dd(n,"lead_submitted",r),q.functions.invoke("card-lead-notify",{body:{cardId:n,leadType:r,name:i.trim(),email:o.trim()||void 0,phone:d.trim()||void 0,message:p.trim()||void 0,intent:h||void 0}}).catch(j=>console.error("Card lead notify failed:",j)),se.success(r==="booking"?"Request sent! They'll be in touch soon.":r==="connect"?"Info shared! They'll be in touch soon.":"Referral submitted! Thank you."),t(!1),l(""),c(""),u(""),m(""),f("")}catch{se.error("Something went wrong. Please try again.")}finally{v(!1)}};return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"sm:max-w-md rounded-2xl",children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:r==="booking"?"Book a Call":r==="connect"?"Connect with Me":"Refer a Friend"}),e.jsx(_r,{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:g,className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(J,{htmlFor:"lead-name",children:"Name *"}),e.jsx(xe,{id:"lead-name",value:i,onChange:b=>l(b.target.value),placeholder:"Your name",required:!0})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"lead-phone",children:"Phone"}),e.jsx(xe,{id:"lead-phone",type:"tel",value:d,onChange:b=>u(b.target.value),placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"lead-email",children:"Email"}),e.jsx(xe,{id:"lead-email",type:"email",value:o,onChange:b=>c(b.target.value),placeholder:"you@example.com"})]}),r==="booking"&&e.jsxs("div",{children:[e.jsx(J,{htmlFor:"lead-intent",children:"I'm looking to..."}),e.jsxs(is,{value:h,onValueChange:m,children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Select one"})}),e.jsxs(as,{children:[e.jsx(He,{value:"buy",children:"Buy a home"}),e.jsx(He,{value:"sell",children:"Sell my home"}),e.jsx(He,{value:"both",children:"Buy & Sell"}),e.jsx(He,{value:"other",children:"Something else"})]})]})]}),r!=="connect"&&e.jsxs("div",{children:[e.jsx(J,{htmlFor:"lead-message",children:r==="referral"?"Tell us about them":"Message (optional)"}),e.jsx(xe,{id:"lead-message",value:p,onChange:b=>f(b.target.value),placeholder:r==="referral"?"Their name, phone, situation...":"Anything you'd like us to know"})]}),e.jsx(B,{type:"submit",className:"w-full rounded-2xl",disabled:y,children:y?"Sending...":"Submit"})]})]})})}const nMs=s=>at({queryKey:["card-blocks",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("card_blocks").select("*").eq("card_id",s).eq("is_visible",!0).order("sort_order",{ascending:!0});if(n)throw n;return t||[]},enabled:!!s}),rMs=s=>at({queryKey:["card-blocks-all",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("card_blocks").select("*").eq("card_id",s).order("sort_order",{ascending:!0});if(n)throw n;return t||[]},enabled:!!s}),aMs=()=>{const s=Bt();return mt({mutationFn:async t=>{const{data:n,error:r}=await q.from("card_blocks").insert(t).select().single();if(r)throw r;return n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["card-blocks",n.card_id]}),s.invalidateQueries({queryKey:["card-blocks-all",n.card_id]}),se.success("Block added")},onError:t=>se.error(t.message)})},iMs=()=>{const s=Bt();return mt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("card_blocks").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["card-blocks"]}),s.invalidateQueries({queryKey:["card-blocks-all"]}),se.success("Block updated")},onError:t=>se.error(t.message)})},oMs=()=>{const s=Bt();return mt({mutationFn:async t=>{const{error:n}=await q.from("card_blocks").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["card-blocks"]}),s.invalidateQueries({queryKey:["card-blocks-all"]}),se.success("Block removed")},onError:t=>se.error(t.message)})};function lMs(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 cMs(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 dMs={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 uMs({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=cMs(n.video_url),i=r||!!a,l=r?lMs(n.video_url):a||n.video_url;return e.jsx("div",{className:dMs[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 hMs={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 mMs({block:s,variant:t}){const r=s.config.testimonials||[],[a,i]=_.useState(0);if(r.length===0)return null;const l=hMs[t],o=r[a];return e.jsxs("div",{className:l.container,children:[e.jsxs("div",{className:l.card,children:[e.jsx(pS,{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($c,{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(xi,{className:"h-4 w-4"})})]})]})}const pMs={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 fMs({block:s,variant:t}){const r=s.config.tags||[];if(r.length===0)return null;const a=pMs[t];return e.jsx("div",{className:a.container,children:r.map((i,l)=>e.jsx("span",{className:a.tag,children:i},l))})}const xMs={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 gMs({block:s,cardId:t,variant:n}){const a=s.config.links||[];if(a.length===0)return null;const i=xMs[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:()=>Dd(t,"button_click",`custom_link_${l.label}`),className:i.link,children:[e.jsx("span",{children:l.label}),e.jsx(wr,{className:`h-4 w-4 ${i.icon}`})]},o))})}const W$e={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 yMs({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 vMs={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 bMs({block:s,cardId:t,variant:n}){const a=s.config.platforms||[],i=vMs[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=W$e[l.platform.toLowerCase()];return!c||!l.url?null:e.jsx("a",{href:l.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>Dd(t,"button_click",`social_${l.platform}`),className:i.linkClass,title:c.label,children:e.jsx(yMs,{path:c.icon,color:c.color})},o)})})]})}function MPe({cardId:s,variant:t}){const{data:n}=nMs(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(uMs,{block:l,variant:t},l.id);case"testimonials":return e.jsx(mMs,{block:l,variant:t},l.id);case"specialties":return e.jsx(fMs,{block:l,variant:t},l.id);case"custom_links":return e.jsx(gMs,{block:l,cardId:s,variant:t},l.id);default:return null}}),i&&e.jsx(bMs,{block:i,cardId:s,variant:t})]})}async function _Ms(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 wMs(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 PPe(s){const{first:t,last:n}=wMs(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 _Ms(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),se.success("Contact saved!")}function jMs({card:s}){var g;const[t,n]=_.useState(!1),[r,a]=_.useState("booking"),i=((g=s.profile)==null?void 0:g.name)||"Agent",l=i.split(" ").map(b=>b[0]).join("").toUpperCase().slice(0,2),o=(b,j)=>{Dd(s.id,"button_click",b),j()},c=()=>o("call",()=>{var b;(b=s.profile)!=null&&b.phone?window.location.href=`tel:${s.profile.phone}`:se.error("Phone number not available")}),d=()=>o("text",()=>{var b;(b=s.profile)!=null&&b.phone?window.location.href=`sms:${s.profile.phone}`:se.error("Phone number not available")}),u=()=>o("email",()=>{var b;(b=s.profile)!=null&&b.email?window.location.href=`mailto:${s.profile.email}`:se.error("Email not available")}),h=()=>{s.booking_url?o("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),n(!0),Dd(s.id,"button_click","book"))},m=()=>{var b,j;Dd(s.id,"contact_saved"),PPe({name:i,phone:(b=s.profile)==null?void 0:b.phone,email:(j=s.profile)==null?void 0:j.email,brokerage:s.brokerage_name,avatarUrl:s.avatar_url,cardUrl:window.location.href})},p=async()=>{Dd(s.id,"share_event");const b=`https://cards.relevelup.com/${s.slug}`,j="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${i}`,text:j,url:b})}catch{}else await navigator.clipboard.writeText(b),se.success("Link copied!")},f=()=>{a("referral"),n(!0),Dd(s.id,"button_click","refer")},y=()=>{a("connect"),n(!0),Dd(s.id,"button_click","connect")},v={instagram:"📸",facebook:"📘",linkedin:"💼",twitter:"🐦",youtube:"🎬",tiktok:"🎵"};return e.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 via-white to-slate-50",children:[e.jsxs("div",{className:"max-w-md mx-auto px-5 py-10",children:[e.jsxs("div",{className:"text-center mb-8",children:[s.show_photo&&e.jsxs(ja,{className:"h-28 w-28 mx-auto mb-4 ring-4 ring-white shadow-lg",children:[e.jsx(pi,{src:s.avatar_url||void 0,alt:i}),e.jsx(Na,{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(B,{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(_a,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs font-medium",children:"Call"})]}),e.jsxs(B,{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(Hi,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs font-medium",children:"Text"})]}),e.jsxs(B,{onClick:u,className:"flex flex-col items-center gap-1.5 h-auto py-4 bg-primary hover:bg-primary/90 text-primary-foreground rounded-2xl shadow-sm",children:[e.jsx(ln,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs font-medium",children:"Email"})]})]}),e.jsxs(B,{onClick:h,className:"w-full h-12 text-base font-semibold rounded-2xl shadow-sm mb-6",variant:"outline",children:[e.jsx(ga,{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(Da,{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(EPe,{card:s,variant:"standard"}),e.jsx(MPe,{cardId:s.id,variant:"standard"}),e.jsxs("div",{className:"space-y-2 mb-6",children:[s.show_save_contact&&e.jsxs(B,{variant:"ghost",onClick:m,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[e.jsx(li,{className:"h-4 w-4 mr-3 text-primary"}),"Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs(B,{variant:"ghost",onClick:()=>{Dd(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(Da,{className:"h-4 w-4 mr-3 text-amber-500"}),"Leave a Review"]}),s.show_refer_friend&&e.jsxs(B,{variant:"ghost",onClick:f,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[e.jsx(In,{className:"h-4 w-4 mr-3 text-primary"}),"Refer a Friend"]}),e.jsxs(B,{variant:"ghost",onClick:y,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[e.jsx(Pl,{className:"h-4 w-4 mr-3 text-primary"}),"Connect with Me"]}),e.jsxs(B,{variant:"ghost",onClick:p,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[e.jsx(bd,{className:"h-4 w-4 mr-3 text-primary"}),"Share My Card"]})]}),s.show_social_links&&s.social_links&&s.social_links.length>0&&e.jsx("div",{className:"flex justify-center gap-4 mb-8",children:s.social_links.slice(0,3).map((b,j)=>e.jsx("a",{href:b.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>Dd(s.id,"button_click",`social_${b.platform}`),className:"h-10 w-10 rounded-full bg-slate-100 hover:bg-slate-200 flex items-center justify-center text-lg transition-colors",children:v[b.platform.toLowerCase()]||"🔗"},j))}),e.jsx("div",{className:"text-center",children:e.jsx("p",{className:"text-xs text-slate-400",children:"Powered by LevelUp"})})]}),e.jsx(TPe,{open:t,onOpenChange:n,cardId:s.id,type:r,agentName:i})]})}function NMs({card:s}){var g;const[t,n]=_.useState(!1),[r,a]=_.useState("booking"),i=((g=s.profile)==null?void 0:g.name)||"Agent",l=i.split(" ").map(b=>b[0]).join("").toUpperCase().slice(0,2),o=(b,j)=>{Dd(s.id,"button_click",b),j()},c=()=>o("call",()=>{var b;(b=s.profile)!=null&&b.phone?window.location.href=`tel:${s.profile.phone}`:se.error("Phone number not available")}),d=()=>o("text",()=>{var b;(b=s.profile)!=null&&b.phone?window.location.href=`sms:${s.profile.phone}`:se.error("Phone number not available")}),u=()=>o("email",()=>{var b;(b=s.profile)!=null&&b.email?window.location.href=`mailto:${s.profile.email}`:se.error("Email not available")}),h=()=>{s.booking_url?o("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),n(!0),Dd(s.id,"button_click","book"))},m=()=>{var b,j;Dd(s.id,"contact_saved"),PPe({name:i,phone:(b=s.profile)==null?void 0:b.phone,email:(j=s.profile)==null?void 0:j.email,brokerage:s.brokerage_name,avatarUrl:s.avatar_url,cardUrl:window.location.href})},p=async()=>{Dd(s.id,"share_event");const b=`https://cards.relevelup.com/${s.slug}`,j="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${i}`,text:j,url:b})}catch{}else await navigator.clipboard.writeText(b),se.success("Link copied!")},f=()=>{a("referral"),n(!0),Dd(s.id,"button_click","refer")},y=()=>{a("connect"),n(!0),Dd(s.id,"button_click","connect")},v={instagram:"📸",facebook:"📘",linkedin:"💼",twitter:"🐦",youtube:"🎬",tiktok:"🎵"};return e.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-[#0f1419] via-[#1a1f2e] to-[#0f1419]",children:[e.jsxs("div",{className:"max-w-md mx-auto px-5 py-10",children:[e.jsx("div",{className:"w-16 h-0.5 bg-gradient-to-r from-[#c9a84c] to-[#e8d48b] mx-auto mb-8"}),e.jsxs("div",{className:"text-center mb-8",children:[s.show_photo&&e.jsxs(ja,{className:"h-32 w-32 mx-auto mb-5 ring-2 ring-[#c9a84c]/40 shadow-2xl",children:[e.jsx(pi,{src:s.avatar_url||void 0,alt:i}),e.jsx(Na,{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:_a,label:"Call",handler:c},{icon:Hi,label:"Text",handler:d},{icon:ln,label:"Email",handler:u}].map(({icon:b,label:j,handler:S})=>e.jsxs("button",{onClick:S,className:"flex flex-col items-center gap-1.5 py-4 bg-[#1e2636] hover:bg-[#252d3f] border border-[#c9a84c]/20 rounded-xl transition-colors",children:[e.jsx(b,{className:"h-5 w-5 text-[#c9a84c]"}),e.jsx("span",{className:"text-xs font-medium text-[#e2e8f0]",children:j})]},j))}),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(ga,{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(Da,{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(EPe,{card:s,variant:"luxury"}),e.jsx(MPe,{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(li,{className:"h-4 w-4 text-[#c9a84c]"})," Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs("button",{onClick:()=>{Dd(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(Da,{className:"h-4 w-4 text-[#c9a84c]"})," Leave a Review"]}),s.show_refer_friend&&e.jsxs("button",{onClick:f,className:"w-full flex items-center gap-3 h-12 px-4 rounded-xl text-[#e2e8f0] hover:bg-[#1e2636] transition-colors text-sm",children:[e.jsx(In,{className:"h-4 w-4 text-[#c9a84c]"})," Refer a Friend"]}),e.jsxs("button",{onClick:y,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(Pl,{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(bd,{className:"h-4 w-4 text-[#c9a84c]"})," Share My Card"]})]}),s.show_social_links&&s.social_links&&s.social_links.length>0&&e.jsx("div",{className:"flex justify-center gap-4 mb-8",children:s.social_links.slice(0,3).map((b,j)=>e.jsx("a",{href:b.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>Dd(s.id,"button_click",`social_${b.platform}`),className:"h-10 w-10 rounded-full bg-[#1e2636] border border-[#c9a84c]/20 hover:border-[#c9a84c]/50 flex items-center justify-center text-lg transition-colors",children:v[b.platform.toLowerCase()]||"🔗"},j))}),e.jsx("div",{className:"text-center",children:e.jsx("p",{className:"text-xs text-[#4a5568]",children:"Powered by LevelUp"})})]}),e.jsx(TPe,{open:t,onOpenChange:n,cardId:s.id,type:r,agentName:i})]})}function kMs({card:s}){var j,S,C,E;const[t,n]=_.useState(!1),[r,a]=_.useState("booking"),i=((j=s.profile)==null?void 0:j.name)||"Agent",l=i.split(" ").map(P=>P[0]).join("").toUpperCase().slice(0,2),o={accent:((S=s.bold_theme_colors)==null?void 0:S.accent)||"#ff5722",dark:((C=s.bold_theme_colors)==null?void 0:C.dark)||"#1a1a2e",button:((E=s.bold_theme_colors)==null?void 0:E.button)||"#ff5722"},c=(P,M)=>{const I=parseInt(P.replace("#",""),16),D=Math.max(0,(I>>16)-M),O=Math.max(0,(I>>8&255)-M),V=Math.max(0,(I&255)-M);return`#${(D<<16|O<<8|V).toString(16).padStart(6,"0")}`};c(o.accent,25),c(o.dark,-20),c(o.button,25);const d=(P,M)=>{Dd(s.id,"button_click",P),M()},u=()=>d("call",()=>{var P;(P=s.profile)!=null&&P.phone?window.location.href=`tel:${s.profile.phone}`:se.error("Phone number not available")}),h=()=>d("text",()=>{var P;(P=s.profile)!=null&&P.phone?window.location.href=`sms:${s.profile.phone}`:se.error("Phone number not available")}),m=()=>d("email",()=>{var P;(P=s.profile)!=null&&P.email?window.location.href=`mailto:${s.profile.email}`:se.error("Email not available")}),p=()=>{s.booking_url?d("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),n(!0),Dd(s.id,"button_click","book"))},f=()=>{var P,M;Dd(s.id,"contact_saved"),PPe({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})},y=async()=>{Dd(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),se.success("Link copied!")},v=()=>{a("referral"),n(!0),Dd(s.id,"button_click","refer")},g=()=>{a("connect"),n(!0),Dd(s.id,"button_click","connect")},b={instagram:"📸",facebook:"📘",linkedin:"💼",twitter:"🐦",youtube:"🎬",tiktok:"🎵"};return e.jsxs("div",{className:"min-h-screen",style:{backgroundColor:o.accent},children:[e.jsxs("div",{className:"px-5 pt-10 pb-14 text-center relative",style:{backgroundColor:o.dark},children:[s.show_photo&&e.jsxs(ja,{className:"h-28 w-28 mx-auto mb-4 shadow-2xl",style:{boxShadow:`0 0 0 4px ${o.accent}`},children:[e.jsx(pi,{src:s.avatar_url||void 0,alt:i}),e.jsx(Na,{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:_a,label:"Call",handler:u},{icon:Hi,label:"Text",handler:h},{icon:ln,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(ga,{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(Da,{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(EPe,{card:s,variant:"bold"}),e.jsx(MPe,{cardId:s.id,variant:"bold"}),e.jsxs("div",{className:"space-y-1 mb-6",children:[s.show_save_contact&&e.jsxs("button",{onClick:f,className:"w-full flex items-center gap-3 h-12 px-4 rounded-2xl hover:bg-gray-100 transition-colors text-sm font-bold",style:{color:o.dark},children:[e.jsx(li,{className:"h-4 w-4",style:{color:o.accent}})," Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs("button",{onClick:()=>{Dd(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(Da,{className:"h-4 w-4",style:{color:o.accent}})," Leave a Review"]}),s.show_refer_friend&&e.jsxs("button",{onClick:v,className:"w-full flex items-center gap-3 h-12 px-4 rounded-2xl hover:bg-gray-100 transition-colors text-sm font-bold",style:{color:o.dark},children:[e.jsx(In,{className:"h-4 w-4",style:{color:o.accent}})," Refer a Friend"]}),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(Pl,{className:"h-4 w-4",style:{color:o.accent}})," Connect with Me"]}),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(bd,{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:()=>Dd(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:b[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(TPe,{open:t,onOpenChange:n,cardId:s.id,type:r,agentName:i})]})}function SMs({card:s}){var g;const[t,n]=_.useState(!1),[r,a]=_.useState("booking"),i=((g=s.profile)==null?void 0:g.name)||"Agent",l=i.split(" ").map(b=>b[0]).join("").toUpperCase().slice(0,2),o=(b,j)=>{Dd(s.id,"button_click",b),j()},c=()=>o("call",()=>{var b;(b=s.profile)!=null&&b.phone?window.location.href=`tel:${s.profile.phone}`:se.error("Phone number not available")}),d=()=>o("text",()=>{var b;(b=s.profile)!=null&&b.phone?window.location.href=`sms:${s.profile.phone}`:se.error("Phone number not available")}),u=()=>o("email",()=>{var b;(b=s.profile)!=null&&b.email?window.location.href=`mailto:${s.profile.email}`:se.error("Email not available")}),h=()=>{s.booking_url?o("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),n(!0),Dd(s.id,"button_click","book"))},m=()=>{var b,j;Dd(s.id,"contact_saved"),PPe({name:i,phone:(b=s.profile)==null?void 0:b.phone,email:(j=s.profile)==null?void 0:j.email,brokerage:s.brokerage_name,avatarUrl:s.avatar_url,cardUrl:window.location.href})},p=async()=>{Dd(s.id,"share_event");const b=`https://cards.relevelup.com/${s.slug}`,j="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${i}`,text:j,url:b})}catch{}else await navigator.clipboard.writeText(b),se.success("Link copied!")},f=()=>{a("referral"),n(!0),Dd(s.id,"button_click","refer")},y=()=>{a("connect"),n(!0),Dd(s.id,"button_click","connect")},v={instagram:"📸",facebook:"📘",linkedin:"💼",twitter:"🐦",youtube:"🎬",tiktok:"🎵"};return e.jsxs("div",{className:"min-h-screen bg-[#f5f1eb]",children:[e.jsx("div",{className:"bg-[#1b3a4b] h-2"}),e.jsxs("div",{className:"max-w-md mx-auto px-5 py-10",children:[e.jsxs("div",{className:"text-center mb-8",children:[s.show_photo&&e.jsxs(ja,{className:"h-28 w-28 mx-auto mb-4 ring-4 ring-white shadow-lg",children:[e.jsx(pi,{src:s.avatar_url||void 0,alt:i}),e.jsx(Na,{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:_a,label:"Call",handler:c},{icon:Hi,label:"Text",handler:d},{icon:ln,label:"Email",handler:u}].map(({icon:b,label:j,handler:S})=>e.jsxs("button",{onClick:S,className:"flex flex-col items-center gap-1.5 py-4 bg-white hover:bg-[#e8e3db] border border-[#d4cfc5] rounded-lg transition-colors shadow-sm",children:[e.jsx(b,{className:"h-5 w-5 text-[#1b3a4b]"}),e.jsx("span",{className:"text-xs font-semibold text-[#1b3a4b]",children:j})]},j))}),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(ga,{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(Da,{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(EPe,{card:s,variant:"classic"}),e.jsx(MPe,{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(li,{className:"h-4 w-4 text-[#5a7a6f]"})," Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs("button",{onClick:()=>{Dd(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(Da,{className:"h-4 w-4 text-[#d4a843]"})," Leave a Review"]}),s.show_refer_friend&&e.jsxs("button",{onClick:f,className:"w-full flex items-center gap-3 h-12 px-4 text-[#1b3a4b] hover:bg-[#f5f1eb] transition-colors text-sm font-medium",children:[e.jsx(In,{className:"h-4 w-4 text-[#5a7a6f]"})," Refer a Friend"]}),e.jsxs("button",{onClick:y,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(Pl,{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(bd,{className:"h-4 w-4 text-[#5a7a6f]"})," Share My Card"]})]}),s.show_social_links&&s.social_links&&s.social_links.length>0&&e.jsx("div",{className:"flex justify-center gap-4 mb-8",children:s.social_links.slice(0,3).map((b,j)=>e.jsx("a",{href:b.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>Dd(s.id,"button_click",`social_${b.platform}`),className:"h-10 w-10 rounded-full bg-white border border-[#d4cfc5] hover:bg-[#e8e3db] flex items-center justify-center text-lg transition-colors shadow-sm",children:v[b.platform.toLowerCase()]||"🔗"},j))}),e.jsx("div",{className:"text-center",children:e.jsx("p",{className:"text-xs text-[#a0aec0]",children:"Powered by LevelUp"})})]}),e.jsx(TPe,{open:t,onOpenChange:n,cardId:s.id,type:r,agentName:i})]})}function pJe({card:s}){switch(s.theme){case"luxury":return e.jsx(NMs,{card:s});case"bold":return e.jsx(kMs,{card:s});case"classic":return e.jsx(SMs,{card:s});case"standard":default:return e.jsx(jMs,{card:s})}}function CMs(){const s=ru();_.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(AMs,{slug:t})}function AMs({slug:s}){return e.jsx(EMs,{slug:s})}function EMs({slug:s}){var i;const{data:t,isLoading:n,error:r}=EFt(s);if(_.useEffect(()=>{t!=null&&t.id&&Dd(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(cn,{className:"h-28 w-28 rounded-full"}),e.jsx(cn,{className:"h-6 w-48"}),e.jsx(cn,{className:"h-4 w-36"})]}),e.jsx(cn,{className:"h-12 w-full"}),e.jsx(cn,{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(pJe,{card:t})]})}function LFt({presentationId:s,ctaLabel:t,agentName:n,prefillName:r,prefillEmail:a,prefillPhone:i}){const[l,o]=_.useState(r||""),[c,d]=_.useState(a||""),[u,h]=_.useState(i||""),[m,p]=_.useState(""),[f,y]=_.useState(""),[v,g]=_.useState(!1),[b,j]=_.useState(!1),S=async C=>{if(C.preventDefault(),!l.trim()){se.error("Please enter your name");return}g(!0);try{const{error:E}=await q.from("smart_presentation_leads").insert({presentation_id:s,name:l.trim(),email:c.trim()||null,phone:u.trim()||null,intent:m||null,message:f.trim()||null});if(E)throw E;try{await q.rpc("log_presentation_view",{p_presentation_id:s,p_section_index:null,p_cta_clicked:!0,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:null})}catch{}q.functions.invoke("presentation-lead-notify",{body:{presentationId:s,name:l.trim(),email:c.trim()||void 0,phone:u.trim()||void 0,intent:m||void 0,message:f.trim()||void 0}}).catch(P=>console.error("Presentation lead notify failed:",P)),j(!0)}catch{se.error("Something went wrong. Please try again.")}finally{g(!1)}};return b?e.jsxs("div",{className:"text-center py-8",children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-emerald-100 flex items-center justify-center mx-auto mb-4",children:e.jsx(ea,{className:"h-8 w-8 text-emerald-600"})}),e.jsx("h3",{className:"text-xl font-semibold text-gray-900 mb-2",children:"Thank you!"}),e.jsx("p",{className:"text-gray-500",children:n?`${n} will be in touch soon.`:"We'll be in touch soon."})]}):e.jsxs("form",{onSubmit:S,className:"space-y-4 max-w-md mx-auto",children:[e.jsxs("div",{children:[e.jsx(J,{htmlFor:"pres-lead-name",children:"Name *"}),e.jsx(xe,{id:"pres-lead-name",value:l,onChange:C=>o(C.target.value),placeholder:"Your name",required:!0})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"pres-lead-phone",children:"Phone"}),e.jsx(xe,{id:"pres-lead-phone",type:"tel",value:u,onChange:C=>h(C.target.value),placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"pres-lead-email",children:"Email"}),e.jsx(xe,{id:"pres-lead-email",type:"email",value:c,onChange:C=>d(C.target.value),placeholder:"you@example.com"})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"pres-lead-intent",children:"I'm looking to..."}),e.jsxs(is,{value:m,onValueChange:p,children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Select one"})}),e.jsxs(as,{children:[e.jsx(He,{value:"buy",children:"Buy a home"}),e.jsx(He,{value:"sell",children:"Sell my home"}),e.jsx(He,{value:"both",children:"Buy & Sell"}),e.jsx(He,{value:"other",children:"Something else"})]})]})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"pres-lead-message",children:"Message (optional)"}),e.jsx(xe,{id:"pres-lead-message",value:f,onChange:C=>y(C.target.value),placeholder:"Anything you'd like us to know"})]}),e.jsx(B,{type:"submit",className:"w-full text-lg py-6 rounded-xl bg-blue-600 hover:bg-blue-700 text-white shadow-lg",disabled:v,children:v?"Sending...":t})]})}function TMs(){const s=ru();_.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(MMs,{shareToken:t})}function MMs({shareToken:s}){var f;const[t,n]=_.useState(null),[r,a]=_.useState(!0),[i,l]=_.useState(0),[o,c]=_.useState(!1);_.useEffect(()=>{d()},[s]);const d=async()=>{const{data:y,error:v}=await q.from("smart_presentations").select("*").eq("share_token",s).eq("status","published").single();if(v||!y){c(!0),a(!1);return}const{data:g}=await q.from("profiles").select("name, email, phone, avatar_url, title, brokerage_id").eq("id",y.owner_user_id).single();let b;if(g!=null&&g.brokerage_id){const{data:S}=await q.from("brokerages").select("name").eq("id",g.brokerage_id).single();b=(S==null?void 0:S.name)||void 0}let j=null;if(y.contact_id){const{data:S}=await q.from("innercircle_contacts").select("first_name, last_name, email, phone").eq("id",y.contact_id).single();j=S}n({...y,owner_name:g==null?void 0:g.name,owner_email:g==null?void 0:g.email,owner_phone:g==null?void 0:g.phone,owner_avatar:g==null?void 0:g.avatar_url,owner_title:(g==null?void 0:g.title)||void 0,brokerage_name:b,contact_name:j?[j.first_name,j.last_name].filter(Boolean).join(" "):void 0,contact_email:(j==null?void 0:j.email)||void 0,contact_phone:(j==null?void 0:j.phone)||void 0}),a(!1);try{await q.rpc("log_presentation_view",{p_presentation_id:y.id,p_section_index:0,p_cta_clicked:!1,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null})}catch{}},u=async()=>{if(t){try{await q.rpc("log_presentation_view",{p_presentation_id:t.id,p_section_index:null,p_cta_clicked:!0,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:null})}catch{}t.cta_url&&window.open(t.cta_url,"_blank")}},h=y=>{const v=y.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/)([a-zA-Z0-9_-]+)/);if(v)return`https://www.youtube.com/embed/${v[1]}?rel=0`;if(y.includes("iframe.mediadelivery.net/play/")){const j=y.replace("/play/","/embed/"),S=j.includes("?")?"&":"?";return`${j}${S}responsive=true`}if(y.includes("iframe.mediadelivery.net")){const j=y.includes("?")?"&":"?";return`${y}${j}responsive=true`}const g=y.match(/loom\.com\/share\/([a-zA-Z0-9]+)/);if(g)return`https://www.loom.com/embed/${g[1]}`;const b=y.match(/video\.bunnycdn\.com\/play\/(\d+)\/([a-f0-9-]+)/);return b?`https://iframe.mediadelivery.net/embed/${b[1]}/${b[2]}?responsive=true`:y};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(cn,{className:"h-12 w-3/4 mx-auto"}),e.jsx(cn,{className:"h-64 w-full"}),e.jsx(cn,{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(y=>y.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((y,v)=>e.jsx("button",{onClick:()=>l(v),className:At("w-full text-left p-4 rounded-xl border transition-all",i===v?"border-blue-500 bg-blue-50 shadow-sm":"border-gray-200 bg-white hover:border-blue-200 hover:bg-blue-50/50"),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs("span",{className:"text-blue-600 font-bold text-sm mt-0.5",children:[String(v+1).padStart(2,"0"),"."]}),e.jsxs("div",{children:[e.jsx("span",{className:"mr-2",children:y.icon}),e.jsx("span",{className:"font-semibold text-gray-900",children:y.title}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:y.description})]})]})},v))})]}),e.jsxs("div",{className:"mt-12 max-w-md mx-auto bg-white rounded-2xl border border-gray-200 shadow-sm p-6 text-center",children:[t.owner_avatar&&e.jsx("img",{src:t.owner_avatar,alt:t.owner_name||"Agent",className:"h-20 w-20 rounded-full object-cover mx-auto mb-3 border-2 border-gray-100"}),e.jsx("h3",{className:"text-lg font-bold text-gray-900",children:t.owner_name}),t.owner_title&&e.jsx("p",{className:"text-sm text-gray-500",children:t.owner_title}),t.brokerage_name&&e.jsx("p",{className:"text-sm text-gray-500",children:t.brokerage_name}),e.jsxs("div",{className:"mt-3 flex flex-col items-center gap-1 text-sm text-gray-600",children:[t.owner_phone&&e.jsx("a",{href:`tel:${t.owner_phone}`,className:"hover:text-blue-600 transition-colors",children:t.owner_phone}),t.owner_email&&e.jsx("a",{href:`mailto:${t.owner_email}`,className:"hover:text-blue-600 transition-colors",children:t.owner_email})]})]}),t.cta_label&&e.jsxs("div",{className:"text-center mt-8 py-8",children:[e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-4",children:"Ready to Get Started?"}),(f=t.cta_url)!=null&&f.trim()?e.jsxs(B,{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(wr,{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(LFt,{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 PMs(){const{user:s}=hs(),t=ha(),{data:n}=G_();return at({queryKey:["open-houses",t,n==null?void 0:n.teamId,n==null?void 0:n.role],queryFn:async()=>{const{data:r,error:a}=await q.from("open_houses").select("*").eq("agent_id",t).order("event_date",{ascending:!1});if(a)throw a;let i=r||[];if((n==null?void 0:n.role)==="team_leader"&&n.teamId){const{data:l,error:o}=await q.rpc("get_team_open_houses",{_user_id:t});if(!o&&l){const c=[...new Set(l.map(h=>h.agent_id))],d={};if(c.length>0){const{data:h}=await q.from("profiles").select("id, name").in("id",c);h==null||h.forEach(m=>{m.name&&(d[m.id]=m.name)})}const u=l.map(h=>({...h,agent_name:d[h.agent_id]||void 0}));i=[...i,...u]}}return i.sort((l,o)=>o.event_date.localeCompare(l.event_date)),i},enabled:!!s&&!!t})}function Tbr(s){const{user:t}=hs();return at({queryKey:["open-house",s],queryFn:async()=>{const{data:n,error:r}=await q.from("open_houses").select("*").eq("id",s).single();if(r)throw r;return n},enabled:!!t&&!!s})}function IFt(s){const{user:t}=hs(),n=Bt();return _.useEffect(()=>{if(!s)return;const r=`visitors-${s}-${Math.random().toString(36).slice(2,10)}`,a=q.channel(r).on("postgres_changes",{event:"*",schema:"public",table:"open_house_visitors",filter:`open_house_id=eq.${s}`},()=>{n.invalidateQueries({queryKey:["open-house-visitors",s]}),n.invalidateQueries({queryKey:["open-houses"]})}).subscribe();return()=>{q.removeChannel(a)}},[s,n]),at({queryKey:["open-house-visitors",s],queryFn:async()=>{const{data:r,error:a}=await q.from("open_house_visitors").select("*").eq("open_house_id",s).order("created_at",{ascending:!1});if(a)throw a;return r},enabled:!!t&&!!s})}function LMs(){const s=Bt(),t=ha();return mt({mutationFn:async n=>{const{data:r,error:a}=await q.from("open_houses").insert({...n,agent_id:t}).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["open-houses"]}),ia({title:"Open house created!"})},onError:n=>{ia({title:"Error",description:n.message,variant:"destructive"})}})}function DFt(){const s=Bt();return mt({mutationFn:async({id:t,...n})=>{const{error:r}=await q.from("open_houses").update(n).eq("id",t);if(r)throw r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["open-houses"]}),s.invalidateQueries({queryKey:["open-house",n.id]})}})}function IMs(){const s=Bt();return mt({mutationFn:async t=>{const{error:n}=await q.from("open_houses").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["open-houses"]}),ia({title:"Open house deleted"})}})}function RFt(s){return at({queryKey:["public-open-house",s],queryFn:async()=>{const{data:t,error:n}=await q.from("open_houses").select("*, profiles:agent_id(name, avatar_url, title, email, phone)").eq("slug",s).eq("is_active",!0).single();if(n)throw n;let r=null;if(t.agent_id){const{data:a}=await q.from("agent_cards").select("slug").eq("user_id",t.agent_id).eq("is_published",!0).maybeSingle();a&&(r=a.slug)}return{...t,agent_card_slug:r}},enabled:!!s})}function DMs(s){const{user:t}=hs();return at({queryKey:["survey-questions",s],queryFn:async()=>{const{data:n,error:r}=await q.from("open_house_survey_questions").select("*").eq("open_house_id",s).order("sort_order");if(r)throw r;return n},enabled:!!t&&!!s})}function RMs(s){return at({queryKey:["public-survey-questions",s],queryFn:async()=>{const{data:t,error:n}=await q.from("open_house_survey_questions").select("*").eq("open_house_id",s).eq("is_active",!0).order("sort_order");if(n)throw n;return t},enabled:!!s})}function FMs(){return mt({mutationFn:async s=>{const{error:t}=await q.from("open_house_survey_responses").insert(s);if(t)throw t}})}function OMs(s){const{user:t}=hs();return at({queryKey:["survey-responses",s],queryFn:async()=>{const{data:n,error:r}=await q.from("open_house_survey_questions").select("*").eq("open_house_id",s).order("sort_order");if(r)throw r;const a=(n||[]).map(o=>o.id);if(a.length===0)return{questions:[],responses:[]};const{data:i,error:l}=await q.from("open_house_survey_responses").select("*").in("question_id",a).order("created_at",{ascending:!1});if(l)throw l;return{questions:n,responses:i||[]}},enabled:!!t&&!!s})}function zMs(){const s=Bt();return mt({mutationFn:async t=>{const{data:n,error:r}=await q.from("open_house_survey_questions").insert(t).select().single();if(r)throw r;return n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["survey-questions",n.open_house_id]})}})}function BMs(){const s=Bt();return mt({mutationFn:async({id:t,open_house_id:n,...r})=>{const{error:a}=await q.from("open_house_survey_questions").update(r).eq("id",t);if(a)throw a},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["survey-questions",n.open_house_id]})}})}function UMs(){const s=Bt();return mt({mutationFn:async({id:t,open_house_id:n})=>{const{error:r}=await q.from("open_house_survey_questions").delete().eq("id",t);if(r)throw r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["survey-questions",n.open_house_id]})}})}function qMs(){const s=Bt();return mt({mutationFn:async t=>{const{error:n}=await q.rpc("seed_default_survey_questions",{_open_house_id:t});if(n)throw n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["survey-questions",n]})}})}function $Ms(){return mt({mutationFn:async s=>{const t=crypto.randomUUID(),{error:n}=await q.from("open_house_visitors").insert({...s,id:t});if(n)throw n;return{id:t}}})}function VMs(){return mt({mutationFn:async({visitor_id:s,...t})=>{const{error:n}=await q.from("open_house_visitors").update(t).eq("id",s);if(n)throw n}})}function HMs(){return mt({mutationFn:async s=>{await q.rpc("increment_open_house_scan",{_slug:s})}})}async function FFt(s){const{data:t,error:n}=await q.from("open_house_rooms").select("*").eq("open_house_id",s).order("sort_order");if(n)throw n;const r=t||[];if(r.length===0)return[];const a=r.map(c=>c.id),{data:i,error:l}=await q.from("open_house_room_media").select("*").in("room_id",a).order("sort_order");if(l)throw l;const o={};return(i||[]).forEach(c=>{var u;const d=c;(o[u=d.room_id]||(o[u]=[])).push(d)}),r.map(c=>({...c,media:o[c.id]||[]}))}function GMs(s){const{user:t}=hs();return at({queryKey:["open-house-rooms",s],queryFn:()=>FFt(s),enabled:!!t&&!!s})}function WMs(s){return at({queryKey:["public-open-house-rooms",s],queryFn:()=>FFt(s),enabled:!!s})}function KMs(){const s=Bt();return mt({mutationFn:async t=>{const{data:n,error:r}=await q.from("open_house_rooms").insert(t).select().single();if(r)throw r;return n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["open-house-rooms",n.open_house_id]})}})}function YMs(){const s=Bt();return mt({mutationFn:async({id:t,open_house_id:n,...r})=>{const{error:a}=await q.from("open_house_rooms").update(r).eq("id",t);if(a)throw a},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["open-house-rooms",n.open_house_id]})}})}function ZMs(){const s=Bt();return mt({mutationFn:async({id:t,open_house_id:n})=>{const{error:r}=await q.from("open_house_rooms").delete().eq("id",t);if(r)throw r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["open-house-rooms",n.open_house_id]})}})}function XMs(){const s=Bt();return mt({mutationFn:async({open_house_id:t,...n})=>{const{data:r,error:a}=await q.from("open_house_room_media").insert(n).select().single();if(a)throw a;return r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["open-house-rooms",n.open_house_id]})}})}function QMs(){const s=Bt();return mt({mutationFn:async({id:t,open_house_id:n})=>{const{error:r}=await q.from("open_house_room_media").delete().eq("id",t);if(r)throw r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["open-house-rooms",n.open_house_id]})}})}function JMs(){const s=Bt();return mt({mutationFn:async({open_house_id:t,orderedIds:n})=>{for(let r=0;r{const r=["open-house-rooms",t];await s.cancelQueries({queryKey:r});const a=s.getQueryData(r);if(a){const i=new Map(a.map(o=>[o.id,o])),l=n.map((o,c)=>({...i.get(o),sort_order:c})).filter(Boolean);s.setQueryData(r,l)}return{prev:a,key:r}},onError:(t,n,r)=>{r!=null&&r.prev&&s.setQueryData(r.key,r.prev)},onSettled:(t,n,r)=>{s.invalidateQueries({queryKey:["open-house-rooms",r.open_house_id]})}})}function ePs(){const s=Bt();return mt({mutationFn:async({open_house_id:t,room_id:n,orderedIds:r})=>{for(let a=0;a{const a=["open-house-rooms",t];await s.cancelQueries({queryKey:a});const i=s.getQueryData(a);return i&&s.setQueryData(a,i.map(l=>{if(l.id!==n)return l;const o=new Map(l.media.map(c=>[c.id,c]));return{...l,media:r.map((c,d)=>{const u=o.get(c);return u?{...u,sort_order:d}:null}).filter(Boolean)}})),{prev:i,key:a}},onError:(t,n,r)=>{r!=null&&r.prev&&s.setQueryData(r.key,r.prev)},onSettled:(t,n,r)=>{s.invalidateQueries({queryKey:["open-house-rooms",r.open_house_id]})}})}function tPs(s){const{user:t}=hs();return at({queryKey:["open-house-leads",s],queryFn:async()=>{const{data:n,error:r}=await q.from("open_house_leads").select("*").eq("open_house_id",s).order("created_at",{ascending:!1});if(r)throw r;return n||[]},enabled:!!t&&!!s})}function sPs(){const s=Bt();return mt({mutationFn:async({id:t,status:n,open_house_id:r})=>{const{error:a}=await q.from("open_house_leads").update({status:n}).eq("id",t);if(a)throw a;return{open_house_id:r}},onSuccess:t=>{s.invalidateQueries({queryKey:["open-house-leads",t.open_house_id]})}})}var LPe="Switch",[nPs,Mbr]=af(LPe),[rPs,aPs]=nPs(LPe),OFt=_.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]=_.useState(null),f=Qo(t,j=>p(j)),y=_.useRef(!1),v=m?u||!!m.closest("form"):!0,[g,b]=Ug({prop:a,defaultProp:i??!1,onChange:d,caller:LPe});return e.jsxs(rPs,{scope:n,checked:g,disabled:o,children:[e.jsx(ii.button,{type:"button",role:"switch","aria-checked":g,"aria-required":l,"data-state":qFt(g),"data-disabled":o?"":void 0,disabled:o,value:c,...h,ref:f,onClick:wa(s.onClick,j=>{b(S=>!S),v&&(y.current=j.isPropagationStopped(),y.current||j.stopPropagation())})}),v&&e.jsx(UFt,{control:m,bubbles:!y.current,name:r,value:c,checked:g,required:l,disabled:o,form:u,style:{transform:"translateX(-100%)"}})]})});OFt.displayName=LPe;var zFt="SwitchThumb",BFt=_.forwardRef((s,t)=>{const{__scopeSwitch:n,...r}=s,a=aPs(zFt,n);return e.jsx(ii.span,{"data-state":qFt(a.checked),"data-disabled":a.disabled?"":void 0,...r,ref:t})});BFt.displayName=zFt;var iPs="SwitchBubbleInput",UFt=_.forwardRef(({__scopeSwitch:s,control:t,checked:n,bubbles:r=!0,...a},i)=>{const l=_.useRef(null),o=Qo(l,i),c=$re(n),d=Cre(t);return _.useEffect(()=>{const u=l.current;if(!u)return;const h=window.HTMLInputElement.prototype,p=Object.getOwnPropertyDescriptor(h,"checked").set;if(c!==n&&p){const f=new Event("click",{bubbles:r});p.call(u,n),u.dispatchEvent(f)}},[c,n,r]),e.jsx("input",{type:"checkbox","aria-hidden":!0,defaultChecked:n,...a,tabIndex:-1,ref:o,style:{...a.style,...d,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});UFt.displayName=iPs;function qFt(s){return s?"checked":"unchecked"}var $Ft=OFt,oPs=BFt;const fn=_.forwardRef(({className:s,...t},n)=>e.jsx($Ft,{className:At("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(oPs,{className:At("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")})}));fn.displayName=$Ft.displayName;const lPs=["Excellent","Good","Neutral","Bad","Very Bad"],cPs=[5,4,3,2,1];function dPs({questions:s,visitorId:t,onComplete:n,onSkip:r}){const a=FMs(),[i,l]=_.useState({}),o=s.filter(m=>m.question_type==="rating"),c=s.filter(m=>m.question_type!=="rating"),d=(m,p)=>{l(f=>({...f,[m]:{rating_value:p}}))},u=(m,p)=>{l(f=>({...f,[m]:{text_value:p}}))},h=async()=>{const m=Object.entries(i).filter(([,p])=>p.rating_value!=null||p.text_value&&p.text_value.trim()).map(([p,f])=>{var y;return{visitor_id:t,question_id:p,rating_value:f.rating_value??null,text_value:((y=f.text_value)==null?void 0:y.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"}),lPs.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}),cPs.map(p=>{var f;return e.jsx("div",{className:"w-12 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>d(m.id,p),className:`w-6 h-6 rounded-full border-2 transition-all ${((f=i[m.id])==null?void 0:f.rating_value)===p?"bg-slate-900 border-slate-900":"border-slate-300 hover:border-slate-500"}`})},p)})]},m.id))]}),c.map(m=>{var p;return e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-slate-700 block mb-1",children:m.question_text}),e.jsx(Ms,{value:((p=i[m.id])==null?void 0:p.text_value)||"",onChange:f=>u(m.id,f.target.value),placeholder:"Your thoughts...",className:"h-16 text-sm resize-none rounded-xl border-slate-200"})]},m.id)}),e.jsx(B,{onClick:h,disabled:a.isPending,className:"w-full h-12 text-base bg-slate-900 hover:bg-slate-800 text-white rounded-xl",children:a.isPending?e.jsx(Ct,{className:"h-5 w-5 animate-spin"}):"Submit Feedback"})]})}function K$e(s){return/iframe\.mediadelivery\.net\/embed\//.test(s)}function uPs({rooms:s}){var h;const[t,n]=_.useState(((h=s[0])==null?void 0:h.id)||""),[r,a]=_.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 _.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:At("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:[K$e(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(Kr,{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($c,{className:"h-6 w-6"})}),l.kind==="video"?K$e(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(xi,{className:"h-6 w-6"})})]})]}):null}function hPs({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=_.useRef(null),[r,a]=_.useState(0);_.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:At("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"?K$e(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($c,{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(xi,{className:"h-4 w-4"})]})]})]})}const wOe={question:{label:"Ask a Question",title:"Ask the agent",placeholder:"What would you like to know about the home?",icon:Hi},showing:{label:"Schedule a Showing",title:"Request a private showing",placeholder:"Anything specific to focus on during the showing? (optional)",icon:ga},disclosure:{label:"Request Disclosures",title:"Request seller disclosures",placeholder:"Any specific documents? (optional)",icon:Fr},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:yd}},mPs=["Seller's Property Disclosure","HOA Documents & Bylaws","Inspection Reports","Title / CC&Rs","Utility & Tax History"];function pPs(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 fPs({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]=_.useState(null),[h,m]=_.useState(""),[p,f]=_.useState(r||""),[y,v]=_.useState(a||""),[g,b]=_.useState(!1),[j,S]=_.useState(null),[C,E]=_.useState(""),[P,M]=_.useState(""),[I,D]=_.useState(""),[O,V]=_.useState([]),[G,$]=_.useState(""),[H,Y]=_.useState(""),[Z,ne]=_.useState(""),[ce,ie]=_.useState(""),te=pPs(s.price),ae=s.tour_mode==="rooms",{data:le=[]}=WMs(ae?s.id:void 0),be=[s.enable_question&&"question",s.enable_showing&&"showing",s.enable_disclosures&&"disclosure",s.enable_offer&&"offer"].filter(Boolean),me=ke=>{u(ke),m(""),E(""),M(""),D(""),V([]),$(""),Y(""),ne(""),ie("")},he=()=>{u(null)},pe=ke=>{V(Ze=>Ze.includes(ke)?Ze.filter(Se=>Se!==ke):[...Ze,ke])},Ce=ke=>ke==="showing"?{preferred_date:C||null,preferred_time:P||null,alternate_date:I||null}:ke==="disclosure"?{requested_documents:O}:ke==="offer"?{offer_amount:G||null,financing:H||null,timeline:Z||null,pre_approved:ce||null}:{},Ae=d?d==="showing"?!!C:d==="question"?h.trim().length>0:!0:!1,Pe=async()=>{if(d){if(i){ia({title:"Preview mode",description:"Lead not sent — this is just a preview."}),S(d),setTimeout(()=>{u(null),S(null)},1500);return}b(!0);try{const ke=Ce(d),{error:Ze}=await q.from("open_house_leads").insert({open_house_id:s.id,visitor_id:t,action_type:d,payload:{message:h.trim()||null,email:p.trim()||null,phone:y.trim()||null,visitor_name:n,...ke}});if(Ze)throw Ze;q.functions.invoke("send-virtual-open-house-lead",{body:{open_house_id:s.id,visitor_id:t,action_type:d,message:h.trim()||null,visitor_name:n,visitor_email:p.trim()||null,visitor_phone:y.trim()||null,extras:ke}}).catch(()=>{}),S(d),ia({title:"Sent!",description:"The agent has been notified."}),setTimeout(()=>{he(),S(null)},1400)}catch(ke){ia({title:"Something went wrong",description:ke.message,variant:"destructive"})}finally{b(!1)}}};return e.jsxs("div",{className:"min-h-screen bg-slate-950 text-white",children:[e.jsxs("div",{className:"relative w-full aspect-video bg-slate-900 md:max-h-[70vh]",children:[s.hero_video_url?e.jsx("video",{src:s.hero_video_url,poster:s.hero_video_thumbnail_url||s.photo_url||void 0,controls:!0,playsInline:!0,className:"w-full h-full object-cover"}):s.photo_url?e.jsx("img",{src:s.photo_url,alt:s.property_address,className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-white/40",children:"No tour video yet"}),e.jsx("div",{className:"absolute inset-x-0 bottom-0 h-32 bg-gradient-to-t from-slate-950 to-transparent pointer-events-none"})]}),e.jsxs("div",{className:"max-w-3xl mx-auto px-5 pb-32 -mt-10 relative z-10",children:[e.jsxs("div",{className:"bg-slate-900/80 backdrop-blur-md border border-white/10 rounded-2xl p-6 shadow-2xl",children:[e.jsx("h1",{className:"text-2xl font-bold leading-tight",children:s.property_address}),s.city&&e.jsxs("p",{className:"text-sm text-white/60 mt-1 flex items-center gap-1",children:[e.jsx(Xa,{className:"h-3.5 w-3.5"}),s.city,s.state?`, ${s.state}`:""," ",s.zip]}),te&&e.jsx("p",{className:"text-3xl font-bold text-white mt-3",children:te}),e.jsxs("div",{className:"flex flex-wrap gap-4 mt-4 text-sm text-white/80",children:[s.beds!=null&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(dj,{className:"h-4 w-4"}),s.beds," bd"]}),s.baths!=null&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(S0,{className:"h-4 w-4"}),s.baths," ba"]}),s.sqft!=null&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(wb,{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(ja,{className:"h-12 w-12 ring-2 ring-white/20",style:c?{boxShadow:`0 0 0 2px ${c}`}:void 0,children:[e.jsx(pi,{src:l.avatar_url||"",alt:l.name||""}),e.jsx(Na,{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(_a,{className:"h-4 w-4"})}),l.email&&e.jsx("a",{href:`mailto:${l.email}`,"aria-label":`Email ${l.name}`,className:"h-10 w-10 rounded-full bg-white/10 hover:bg-white/20 transition-colors flex items-center justify-center text-white",style:c?{backgroundColor:`${c}33`,color:"white"}:void 0,children:e.jsx(ln,{className:"h-4 w-4"})})]})]}),ae&&le.length>0&&e.jsxs("div",{className:"mt-8",children:[e.jsx(uPs,{rooms:le}),e.jsx(hPs,{rooms:le})]}),be.length>0&&e.jsx("div",{className:"mt-5 grid grid-cols-1 sm:grid-cols-2 gap-3",children:be.map(ke=>{const Ze=wOe[ke],Se=Ze.icon;return e.jsxs("button",{onClick:()=>me(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:Ze.label})]},ke)})}),e.jsx("p",{className:"text-center text-white/30 text-xs mt-8",children:"Powered by LevelUp Virtual Open House"})]}),e.jsx(qg,{open:!!d,onOpenChange:ke=>!ke&&he(),children:e.jsx(hg,{side:"bottom",className:"rounded-t-2xl max-h-[92vh] overflow-y-auto",children:d&&e.jsxs(e.Fragment,{children:[e.jsxs(P0,{className:"text-left",children:[e.jsx(L0,{children:wOe[d].title}),e.jsxs(U9,{children:[(l==null?void 0:l.name)||"The agent"," will be notified by email."]})]}),j===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(Er,{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(J,{className:"text-xs",children:"Email"}),e.jsx(xe,{type:"email",value:p,onChange:ke=>f(ke.target.value),placeholder:"you@example.com",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Phone"}),e.jsx(xe,{type:"tel",value:y,onChange:ke=>v(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(J,{className:"text-xs",children:"Preferred date *"}),e.jsx(xe,{type:"date",value:C,onChange:ke=>E(ke.target.value),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Preferred time"}),e.jsx(xe,{type:"time",value:P,onChange:ke=>M(ke.target.value),className:"mt-1"})]})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Alternate date (optional)"}),e.jsx(xe,{type:"date",value:I,onChange:ke=>D(ke.target.value),className:"mt-1"})]})]}),d==="disclosure"&&e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Which documents? (select all that apply)"}),e.jsx("div",{className:"mt-2 space-y-2",children:mPs.map(ke=>e.jsxs("label",{className:"flex items-center gap-2 text-sm cursor-pointer",children:[e.jsx($a,{checked:O.includes(ke),onCheckedChange:()=>pe(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(J,{className:"text-xs",children:"Estimated offer"}),e.jsx(xe,{value:G,onChange:ke=>$(ke.target.value),placeholder:"$",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Financing"}),e.jsxs(is,{value:H,onValueChange:Y,children:[e.jsx(rs,{className:"mt-1",children:e.jsx(ls,{placeholder:"Select..."})}),e.jsxs(as,{children:[e.jsx(He,{value:"Cash",children:"Cash"}),e.jsx(He,{value:"Conventional",children:"Conventional"}),e.jsx(He,{value:"FHA",children:"FHA"}),e.jsx(He,{value:"VA",children:"VA"}),e.jsx(He,{value:"Other",children:"Other"})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Timeline"}),e.jsxs(is,{value:Z,onValueChange:ne,children:[e.jsx(rs,{className:"mt-1",children:e.jsx(ls,{placeholder:"Select..."})}),e.jsxs(as,{children:[e.jsx(He,{value:"ASAP",children:"ASAP"}),e.jsx(He,{value:"30 days",children:"30 days"}),e.jsx(He,{value:"60 days",children:"60 days"}),e.jsx(He,{value:"90+ days",children:"90+ days"})]})]})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Pre-approved?"}),e.jsxs(is,{value:ce,onValueChange:ie,children:[e.jsx(rs,{className:"mt-1",children:e.jsx(ls,{placeholder:"Select..."})}),e.jsxs(as,{children:[e.jsx(He,{value:"Yes",children:"Yes"}),e.jsx(He,{value:"No",children:"No"}),e.jsx(He,{value:"In progress",children:"In progress"})]})]})]})]})]}),e.jsxs("div",{children:[e.jsxs(J,{className:"text-xs",children:["Message",d==="question"?" *":" (optional)"]}),e.jsx(Ms,{value:h,onChange:ke=>m(ke.target.value),placeholder:wOe[d].placeholder,rows:4,className:"mt-1"})]}),e.jsx(B,{onClick:Pe,disabled:g||!Ae,className:"w-full h-12 text-white hover:opacity-90",style:c?{backgroundColor:c}:void 0,children:g?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):"Send to agent"})]})]})})})]})}const xPs=Bj({first_name:Zo().trim().min(1,"First name is required").max(50),last_name:Zo().trim().max(50).optional(),email:Zo().trim().email("Please enter a valid email").max(255).optional().or(gx("")),phone:Zo().trim().max(20).optional().or(gx(""))}),gPs=[{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 VFt({slug:s}={}){var Ve;const t=Li(),n=s||t.slug,[r]=Yl(),a=r.get("kiosk")==="1"||r.get("mode")==="kiosk",i=8,{data:l,isLoading:o,error:c}=RFt(n),d=$Ms(),u=VMs(),h=HMs(),m=_.useRef(!1),[p,f]=_.useState("welcome"),[y,v]=_.useState(null),[g,b]=_.useState({first_name:"",last_name:"",email:"",phone:"",visitor_address:""}),[j,S]=_.useState(""),[C,E]=_.useState(!1),[P,M]=_.useState(!1),[I,D]=_.useState(""),[O,V]=_.useState(""),[G,$]=_.useState(i),H=_.useCallback(()=>{v(null),b({first_name:"",last_name:"",email:"",phone:"",visitor_address:""}),S(""),E(!1),M(!1),D(""),V(""),$(i),f(a?"info":"welcome")},[a]),Y=_.useCallback((qe,Qe)=>{l!=null&&l.id&&q.functions.invoke("guestbook-lead-notify",{body:{open_house_id:l.id,visitor_id:qe,first_name:Qe.first_name??g.first_name,last_name:Qe.last_name??g.last_name,email:Qe.email??g.email,phone:Qe.phone??g.phone,visitor_intent:Qe.visitor_intent??j,message:Qe.message,wants_market_updates:Qe.wants_market_updates??C,has_agent:Qe.has_agent??P,working_with_agent_name:Qe.working_with_agent_name??I,visitor_address:Qe.visitor_address??g.visitor_address}}).catch(Ue=>console.error("Guest book lead notify failed:",Ue))},[l==null?void 0:l.id,g,j,C,P,I]);_.useEffect(()=>{if(!a||p!=="done")return;$(i);const qe=setInterval(()=>{$(Qe=>Qe<=1?(clearInterval(qe),H(),0):Qe-1)},1e3);return()=>clearInterval(qe)},[a,p,H]),_.useEffect(()=>{if(!a)return;f(Qe=>Qe==="welcome"?"info":Qe);let qe=null;return(async()=>{var Qe,Ue;try{qe=await((Ue=(Qe=navigator.wakeLock)==null?void 0:Qe.request)==null?void 0:Ue.call(Qe,"screen"))}catch{}})(),()=>{var Qe;try{(Qe=qe==null?void 0:qe.release)==null||Qe.call(qe)}catch{}}},[a]);const Z=_.useCallback(()=>{var Qe;const qe=document.documentElement;document.fullscreenElement||(Qe=qe.requestFullscreen||qe.webkitRequestFullscreen)==null||Qe.call(qe).catch(()=>{})},[]),{data:ne,isLoading:ce}=RMs(l==null?void 0:l.id),ie=!!(l!=null&&l.enable_survey),te=(l==null?void 0:l.ask_visitor_intent)!==!1,ae=(l==null?void 0:l.ask_visitor_address)===!0;_.useEffect(()=>{if(!n||!(l!=null&&l.id)||m.current)return;const qe=`oh_scan_${l.id}`;if(sessionStorage.getItem(qe)){m.current=!0;return}m.current=!0,sessionStorage.setItem(qe,"1"),h.mutate(n)},[n,l==null?void 0:l.id]),_.useEffect(()=>{p==="pending_survey"&&(ce||f(ie&&((ne==null?void 0:ne.length)??0)>0?"survey":"done"))},[p,ce,ie,ne]);const le=qe=>{if(!qe)return"";const[Qe,Ue]=qe.split(":"),Xe=parseInt(Qe),nt=Xe>=12?"PM":"AM";return`${Xe>12?Xe-12:Xe||12}:${Ue} ${nt}`},be=async()=>{V("");const qe=xPs.safeParse(g);if(!qe.success){V(qe.error.issues[0].message);return}if(!g.email&&!g.phone){V("Please provide either an email or phone number");return}const Qe=(l==null?void 0:l.kind)==="virtual";let Ue=null;if(!y&&(l!=null&&l.id))try{const Xe=await d.mutateAsync({open_house_id:l.id,first_name:g.first_name.trim(),last_name:g.last_name.trim()||void 0,email:g.email.trim()||void 0,phone:g.phone.trim()||void 0,visitor_address:ae&&g.visitor_address.trim()?g.visitor_address.trim():void 0,wants_market_updates:C,has_agent:P,working_with_agent_name:P&&I.trim()?I.trim():void 0,partial_signin:Qe?!1:te});Ue=Xe.id,v(Xe.id)}catch{if(Qe){V("We could not start the virtual tour. Please try again.");return}}if(Qe){te?f("intent"):(Ue&&Y(Ue,{}),f("done"));return}if(!te){Ue&&Y(Ue,{}),ie?!ce&&ne&&ne.length>0?f("survey"):f("pending_survey"):f("done");return}f("intent")},me=async qe=>{S(qe);try{let Qe=y;if(Qe?await u.mutateAsync({visitor_id:Qe,visitor_intent:qe,wants_market_updates:C,has_agent:P,working_with_agent_name:P&&I.trim()?I.trim():null,partial_signin:!1}):(Qe=(await d.mutateAsync({open_house_id:l.id,first_name:g.first_name.trim(),last_name:g.last_name.trim()||void 0,email:g.email.trim()||void 0,phone:g.phone.trim()||void 0,visitor_address:ae&&g.visitor_address.trim()?g.visitor_address.trim():void 0,visitor_intent:qe,wants_market_updates:C,has_agent:P,working_with_agent_name:P&&I.trim()?I.trim():void 0,partial_signin:!1})).id,v(Qe)),Qe&&Y(Qe,{visitor_intent:qe,wants_market_updates:C,has_agent:P,working_with_agent_name:P&&I.trim()?I.trim():null}),(l==null?void 0:l.kind)==="virtual"){f("done");return}ie?!ce&&ne&&ne.length>0?f("survey"):f("pending_survey"):f("done")}catch{V("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(Jr,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Open House Not Found"}),e.jsx("p",{className:"text-white/60",children:"This sign-in page doesn't exist or is no longer active."})]})});const he=l.profiles,pe=((Ve=he==null?void 0:he.name)==null?void 0:Ve.split(" ").map(qe=>qe[0]).join("").slice(0,2))||"?",Ce=l.event_type==="community",Ae=l.kind==="virtual",Pe=typeof window<"u"&&new URLSearchParams(window.location.search).get("preview")==="1";if(Ae&&(Pe||p==="done"))return!Pe&&!y?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"})]}),Pe&&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(fPs,{openHouse:l,visitorId:Pe?"preview":y,visitorName:Pe?"Preview Visitor":`${g.first_name} ${g.last_name}`.trim(),visitorEmail:Pe?"":g.email,visitorPhone:Pe?"":g.phone,previewMode:Pe})]});const ke=`${Ae?"Virtual Open House":Ce?"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,he!=null&&he.name?`Hosted by ${he.name}`:null].filter(Boolean).join(" · "),Fe=l.photo_url||"",Ne=Fe&&Fe.includes("/storage/v1/object/public/")?Fe.replace("/object/public/","/render/image/public/")+"?width=1200&height=630&resize=cover":Fe||"https://dashboard.relevelup.com/og-image.png",Ye=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:Ne}),e.jsx("meta",{property:"og:image:width",content:"1200"}),e.jsx("meta",{property:"og:image:height",content:"630"}),e.jsx("meta",{property:"og:url",content:Ye}),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:Ne}),e.jsx("meta",{name:"robots",content:"noindex, nofollow"})]}),e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 flex items-center justify-center p-4",children:e.jsxs("div",{className:"w-full max-w-md",children:[e.jsxs("div",{className:"text-center mb-6",children:[e.jsxs(ja,{className:"h-16 w-16 mx-auto mb-3 ring-2 ring-white/20",children:[e.jsx(pi,{src:(he==null?void 0:he.avatar_url)||"",alt:(he==null?void 0:he.name)||""}),e.jsx(Na,{className:"bg-white/10 text-white text-lg",children:pe})]}),e.jsx("p",{className:"text-white/60 text-sm",children:he==null?void 0:he.name}),(he==null?void 0:he.title)&&e.jsx("p",{className:"text-white/40 text-xs",children:he.title})]}),e.jsxs("div",{className:"bg-white rounded-2xl shadow-2xl overflow-hidden",children:[l.photo_url&&e.jsxs("div",{className:"relative h-44 sm:h-52 overflow-hidden",children:[e.jsx("img",{src:l.photo_url,alt:l.property_address,className:"w-full h-full object-cover"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-slate-900/80 via-slate-900/20 to-transparent"}),e.jsxs("div",{className:"absolute bottom-0 left-0 right-0 px-6 pb-4",children:[e.jsx("h1",{className:"text-white font-bold text-lg leading-tight drop-shadow-md",children:l.property_address}),e.jsxs("div",{className:"flex flex-wrap gap-3 mt-1.5 text-white/70 text-xs",children:[l.city&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Xa,{className:"h-3 w-3"}),l.city,l.state?`, ${l.state}`:""," ",l.zip]}),!Ae&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ga,{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(Gr,{className:"h-3 w-3"}),le(l.start_time),l.end_time?` – ${le(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:Ce?e.jsx(ai,{className:"h-5 w-5 text-white"}):e.jsx(Jr,{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(Xa,{className:"h-3 w-3"}),l.city,l.state?`, ${l.state}`:""," ",l.zip]}),!Ae&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ga,{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(Gr,{className:"h-3 w-3"}),le(l.start_time),l.end_time?` – ${le(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(B,{onClick:()=>f("info"),className:"w-full h-14 text-base bg-slate-900 hover:bg-slate-800 text-white rounded-xl",children:["Sign In ",e.jsx(La,{className:"h-5 w-5 ml-2"})]}),e.jsx("p",{className:"text-xs text-slate-400",children:"Quick & easy — takes 30 seconds"})]}),p==="info"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("button",{onClick:()=>f("welcome"),className:"text-slate-400 hover:text-slate-600",children:e.jsx(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(J,{className:"text-slate-600 text-xs",children:"First Name *"}),e.jsx(xe,{value:g.first_name,onChange:qe=>b(Qe=>({...Qe,first_name:qe.target.value})),placeholder:"First",className:"mt-1 h-12 rounded-xl border-slate-200 text-base",autoFocus:!0})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-slate-600 text-xs",children:"Last Name"}),e.jsx(xe,{value:g.last_name,onChange:qe=>b(Qe=>({...Qe,last_name:qe.target.value})),placeholder:"Last",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-slate-600 text-xs",children:"Email"}),e.jsx(xe,{type:"email",value:g.email,onChange:qe=>b(Qe=>({...Qe,email:qe.target.value})),placeholder:"your@email.com",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-slate-600 text-xs",children:"Phone"}),e.jsx(xe,{type:"tel",value:g.phone,onChange:qe=>b(Qe=>({...Qe,phone:qe.target.value})),placeholder:"(555) 123-4567",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]}),ae&&e.jsxs("div",{children:[e.jsx(J,{className:"text-slate-600 text-xs",children:"Your Home Address"}),e.jsx(xe,{value:g.visitor_address,onChange:qe=>b(Qe=>({...Qe,visitor_address:qe.target.value})),placeholder:"Street, City, State ZIP",className:"mt-1 h-12 rounded-xl border-slate-200 text-base",autoComplete:"street-address"})]}),e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer pt-1",children:[e.jsx("input",{type:"checkbox",checked:C,onChange:qe=>E(qe.target.checked),className:"rounded border-slate-300 text-slate-900 focus:ring-slate-500"}),e.jsx("span",{className:"text-sm text-slate-600",children:"Send me market updates for this area"})]}),e.jsxs("div",{className:"space-y-2 pt-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm text-slate-600",children:"Already working with an agent?"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs font-medium text-slate-400",children:P?"Yes":"No"}),e.jsx(fn,{checked:P,onCheckedChange:M})]})]}),P&&e.jsx(xe,{value:I,onChange:qe=>D(qe.target.value),placeholder:"Agent's name",className:"mt-1 h-10 rounded-xl border-slate-200 text-sm"})]}),O&&e.jsx("p",{className:"text-destructive text-sm",children:O}),e.jsxs(B,{onClick:be,className:"w-full h-14 text-base bg-slate-900 hover:bg-slate-800 text-white rounded-xl",children:["Continue ",e.jsx(La,{className:"h-5 w-5 ml-2"})]})]}),p==="intent"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("button",{onClick:()=>f("info"),className:"text-slate-400 hover:text-slate-600",children:e.jsx(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:gPs.map(qe=>e.jsxs("button",{onClick:()=>me(qe.value),disabled:d.isPending,className:"flex flex-col items-center gap-2 p-5 rounded-xl border-2 border-slate-200 hover:border-slate-900 hover:bg-slate-50 transition-all text-center group",children:[e.jsx("span",{className:"text-2xl",children:qe.emoji}),e.jsx("span",{className:"text-sm font-medium text-slate-700 group-hover:text-slate-900",children:qe.label})]},qe.value))}),O&&e.jsx("p",{className:"text-destructive text-sm text-center",children:O})]}),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"&&y&&ne&&e.jsx(dPs,{questions:ne,visitorId:y,onComplete:()=>f("done"),onSkip:()=>f("done")}),p==="done"&&e.jsxs("div",{className:"text-center space-y-4 py-4",children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-green-100 flex items-center justify-center mx-auto",children:e.jsx(Er,{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, ",g.first_name,". ",Ce?"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(Fr,{className:"h-4 w-4"}),"View Seller's Disclosures"]}),(he==null?void 0:he.name)&&e.jsxs("p",{className:"text-sm text-slate-400",children:["Your host today: ",e.jsx("strong",{className:"text-slate-600",children:he.name})]}),a&&e.jsxs("div",{className:"pt-4 space-y-3",children:[e.jsx(B,{onClick:H,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 ",G,"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(o$,{className:"h-3 w-3"})," Tablet Mode"]}),e.jsx("button",{onClick:Z,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(qQ,{className:"h-3 w-3"})})]})]})})]})}function yPs(s){return at({queryKey:["open-house-rsvps",s],queryFn:async()=>{const{data:t,error:n}=await q.from("open_house_rsvps").select("*").eq("open_house_id",s).order("created_at",{ascending:!1});if(n)throw n;return t||[]},enabled:!!s})}function vPs(){const s=Bt();return mt({mutationFn:async t=>{const{error:n}=await q.from("open_house_rsvps").insert({open_house_id:t.open_house_id,first_name:t.first_name,last_name:t.last_name||null,email:t.email||null,phone:t.phone||null,has_agent:t.has_agent??!1,working_with_agent_name:t.working_with_agent_name||null,message:t.message||null});if(n)throw n;return null},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["open-house-rsvps",n.open_house_id]})}})}function bPs(s){const t=Bt();return mt({mutationFn:async n=>{const{error:r}=await q.from("open_house_rsvps").delete().eq("id",n);if(r)throw r},onSuccess:()=>t.invalidateQueries({queryKey:["open-house-rsvps",s]})})}function _Ps(s){const t=Bt();return mt({mutationFn:async({id:n,checkedIn:r})=>{const{error:a}=await q.from("open_house_rsvps").update({checked_in_at:r?new Date().toISOString():null}).eq("id",n);if(a)throw a},onSuccess:()=>t.invalidateQueries({queryKey:["open-house-rsvps",s]})})}const wPs=Bj({first_name:Zo().trim().min(1,"First name is required").max(50),last_name:Zo().trim().max(50).optional(),email:Zo().trim().email("Please enter a valid email").max(255),phone:Zo().trim().max(20).optional().or(gx("")),message:Zo().trim().max(500).optional().or(gx(""))}),jOe=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}`},jPs=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 HFt({slug:s}={}){const t=Li(),n=s||t.slug,{data:r,isLoading:a,error:i}=RFt(n),l=vPs(),[o,c]=_.useState({first_name:"",last_name:"",email:"",phone:"",message:""}),[d,u]=_.useState(!1),[h,m]=_.useState(""),[p,f]=_.useState(""),[y,v]=_.useState(!1),g=_.useMemo(()=>jPs(r==null?void 0:r.event_date),[r==null?void 0:r.event_date]),b=_.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]),j=r==null?void 0:r.profiles,S=[r==null?void 0:r.city,r==null?void 0:r.state].filter(Boolean).join(", "),C=async()=>{f("");const M=wPs.safeParse(o);if(!M.success){f(M.error.issues[0].message);return}try{await l.mutateAsync({open_house_id:r.id,first_name:o.first_name.trim(),last_name:o.last_name.trim()||void 0,email:o.email.trim(),phone:o.phone.trim()||void 0,has_agent:d,working_with_agent_name:d&&h.trim()?h.trim():void 0,message:o.message.trim()||void 0}),v(!0)}catch(I){f((I==null?void 0:I.message)||"Something went wrong. Please try again.")}},E=_.useMemo(()=>{if(!r||!g)return"";const M=$=>String($).padStart(2,"0"),I=`${g.getFullYear()}${M(g.getMonth()+1)}${M(g.getDate())}`,D=(r.start_time||"12:00").slice(0,5).replace(":","")+"00",O=(r.end_time||"14:00").slice(0,5).replace(":","")+"00",V=encodeURIComponent(`Open House — ${r.property_address}`),G=encodeURIComponent([r.property_address,S,r.zip].filter(Boolean).join(", "));return`https://calendar.google.com/calendar/render?action=TEMPLATE&text=${V}&dates=${I}T${D}/${I}T${O}&location=${G}`},[r,g,S]);if(a)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-[#0f1c22]",children:e.jsx("div",{className:"h-10 w-10 rounded-full border-2 border-white/20 border-t-white animate-spin"})});if(i||!r)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-[#0f1c22] p-6 text-center",children:e.jsxs("div",{className:"text-white/80",children:[e.jsx(Jr,{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,S,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}${g?` on ${Hs(g,"EEEE, MMMM d")}`:""}.`})]}),e.jsxs("header",{className:"relative",children:[e.jsxs("div",{className:"relative h-[46vh] min-h-[320px] w-full overflow-hidden bg-[#1b3a4b]",children:[b&&e.jsx("img",{src:b,alt:r.property_address,className:"absolute inset-0 h-full w-full object-cover"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-[#0f1c22] via-[#0f1c22]/55 to-[#0f1c22]/25"}),e.jsx("div",{className:"absolute inset-x-0 bottom-0 p-6 sm:p-10",children:e.jsxs("div",{className:"mx-auto max-w-3xl",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.35em] text-[#d4b978] mb-3",children:"Open House"}),e.jsx("h1",{className:"font-serif text-3xl sm:text-4xl font-bold text-white leading-tight",children:r.property_address}),S&&e.jsxs("p",{className:"mt-1 text-white/70",children:[S," ",r.zip||""]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-x-5 gap-y-2 text-sm text-white/85",children:[g&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(ga,{className:"h-4 w-4 text-[#d4b978]"}),Hs(g,"EEEE, MMMM d, yyyy")]}),r.start_time&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Gr,{className:"h-4 w-4 text-[#d4b978]"}),jOe(r.start_time),r.end_time?` – ${jOe(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(xle,{icon:e.jsx(Jr,{className:"h-4 w-4"}),label:"Price",value:`$${Number(r.price).toLocaleString()}`}):null,r.beds?e.jsx(xle,{icon:e.jsx(q4,{className:"h-4 w-4"}),label:"Beds",value:String(r.beds)}):null,r.baths?e.jsx(xle,{icon:e.jsx(S0,{className:"h-4 w-4"}),label:"Baths",value:String(r.baths)}):null,r.sqft?e.jsx(xle,{icon:e.jsx(W4,{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:y?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(Er,{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 ",g?Hs(g,"EEEE, MMMM d"):"soon",r.start_time?` at ${jOe(r.start_time)}`:"",". A confirmation reminder will land in your inbox before the event."]}),e.jsxs("div",{className:"mt-6 flex flex-wrap justify-center gap-3",children:[E&&e.jsx(B,{asChild:!0,className:"bg-[#1b3a4b] hover:bg-[#25505f]",children:e.jsxs("a",{href:E,target:"_blank",rel:"noreferrer",children:[e.jsx(gy,{className:"mr-2 h-4 w-4"}),"Add to calendar"]})}),e.jsx(B,{asChild:!0,variant:"outline",children:e.jsxs("a",{href:P,target:"_blank",rel:"noreferrer",children:[e.jsx(Xa,{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(J,{htmlFor:"rsvp-first",children:"First name *"}),e.jsx(xe,{id:"rsvp-first",value:o.first_name,onChange:M=>c(I=>({...I,first_name:M.target.value})),className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{htmlFor:"rsvp-last",children:"Last name"}),e.jsx(xe,{id:"rsvp-last",value:o.last_name,onChange:M=>c(I=>({...I,last_name:M.target.value})),className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{htmlFor:"rsvp-email",children:"Email *"}),e.jsx(xe,{id:"rsvp-email",type:"email",value:o.email,onChange:M=>c(I=>({...I,email:M.target.value})),className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{htmlFor:"rsvp-phone",children:"Phone"}),e.jsx(xe,{id:"rsvp-phone",type:"tel",value:o.phone,onChange:M=>c(I=>({...I,phone:M.target.value})),className:"h-11"})]})]}),e.jsxs("div",{className:"mt-4 rounded-xl border border-[#e4dcd3] bg-[#faf7f4] p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-[#1b3a4b]",children:"Are you working with an agent?"}),e.jsx("p",{className:"text-xs text-[#7a888e]",children:"So we can respect your existing representation."})]}),e.jsx(fn,{checked:d,onCheckedChange:u})]}),d&&e.jsx(xe,{value:h,onChange:M=>m(M.target.value),placeholder:"Your agent's name (optional)",className:"mt-3 h-10 bg-white"})]}),e.jsxs("div",{className:"mt-4 space-y-1.5",children:[e.jsx(J,{htmlFor:"rsvp-msg",children:"Anything you'd like us to know?"}),e.jsx(Ms,{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(B,{onClick:C,disabled:l.isPending,className:"mt-6 h-12 w-full bg-gradient-to-r from-[#1b3a4b] to-[#406E71] text-base hover:opacity-95",children:l.isPending?"Reserving…":e.jsxs(e.Fragment,{children:["RSVP for this open house",e.jsx(La,{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."})]})}),(j==null?void 0:j.name)&&e.jsxs("section",{className:"rounded-2xl bg-white/70 border border-[#e4dcd3] p-5 flex items-center gap-4",children:[e.jsxs(ja,{className:"h-14 w-14",children:[e.jsx(pi,{src:j.avatar_url||void 0,alt:j.name}),e.jsx(Na,{children:j.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:j.name}),j.title&&e.jsx("p",{className:"text-sm text-[#5b6b72]",children:j.title}),e.jsxs("div",{className:"mt-1 flex flex-wrap gap-x-4 text-sm text-[#406E71]",children:[j.phone&&e.jsx("a",{href:`tel:${j.phone}`,children:j.phone}),j.email&&e.jsx("a",{href:`mailto:${j.email}`,className:"truncate",children:j.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(Xa,{className:"h-4 w-4"}),"Get directions to ",r.property_address]})})]})]})}function xle({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 Pbr(s){const{user:t}=hs();return at({queryKey:["cohost-tokens",s],queryFn:async()=>{const{data:n,error:r}=await q.from("open_house_cohost_tokens").select("*").eq("open_house_id",s).order("created_at",{ascending:!1});if(r)throw r;return n},enabled:!!t&&!!s})}function Lbr(){const s=Bt(),{user:t}=hs();return mt({mutationFn:async({openHouseId:n,label:r})=>{const{data:a,error:i}=await q.from("open_house_cohost_tokens").insert({open_house_id:n,label:r||null,created_by:t.id,expires_at:new Date(Date.now()+864e5).toISOString()}).select().single();if(i)throw i;return a},onSuccess:(n,r)=>{s.invalidateQueries({queryKey:["cohost-tokens",r.openHouseId]})}})}function Ibr(){const s=Bt();return mt({mutationFn:async({id:t,openHouseId:n})=>{const{error:r}=await q.from("open_house_cohost_tokens").update({is_active:!1}).eq("id",t);if(r)throw r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["cohost-tokens",n.openHouseId]})}})}function NPs(s){return at({queryKey:["cohost-validate",s],queryFn:async()=>{const{data:t,error:n}=await q.from("open_house_cohost_tokens").select("*, open_houses(*)").eq("token",s).eq("is_active",!0).single();if(n)throw n;if(t.expires_at&&new Date(t.expires_at)-1&&s.splice(n,1)}const lC=(s,t,n)=>n>t?t:n{},MH=()=>{};const RP={},WFt=s=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(s);function KFt(s){return typeof s=="object"&&s!==null}const YFt=s=>/^0[^.\s]+$/u.test(s);function ZFt(s){let t;return()=>(t===void 0&&(t=s()),t)}const gN=s=>s,SPs=(s,t)=>n=>t(s(n)),Kre=(...s)=>s.reduce(SPs),ate=(s,t,n)=>{const r=t-s;return r===0?1:(n-s)/r};class yJe{constructor(){this.subscriptions=[]}add(t){return gJe(this.subscriptions,t),()=>pAe(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,nN=s=>s/1e3;function XFt(s,t){return t?s*(1e3/t):0}const QFt=(s,t,n)=>(((1-3*n+3*t)*s+(3*n-6*t))*s+3*t)*s,CPs=1e-7,APs=12;function EPs(s,t,n,r,a){let i,l,o=0;do l=t+(n-t)/2,i=QFt(l,r,a)-s,i>0?n=l:t=l;while(Math.abs(i)>CPs&&++oEPs(i,0,1,s,n);return i=>i===0||i===1?i:QFt(a(i),t,r)}const JFt=s=>t=>t<=.5?s(2*t)/2:(2-s(2*(1-t)))/2,eOt=s=>t=>1-s(1-t),tOt=Yre(.33,1.53,.69,.99),vJe=eOt(tOt),sOt=JFt(vJe),nOt=s=>s>=1?1:(s*=2)<1?.5*vJe(s):.5*(2-Math.pow(2,-10*(s-1))),bJe=s=>1-Math.sin(Math.acos(s)),rOt=eOt(bJe),aOt=JFt(bJe),TPs=Yre(.42,0,1,1),MPs=Yre(0,0,.58,1),iOt=Yre(.42,0,.58,1),PPs=s=>Array.isArray(s)&&typeof s[0]!="number",oOt=s=>Array.isArray(s)&&typeof s[0]=="number",ift={linear:gN,easeIn:TPs,easeInOut:iOt,easeOut:MPs,circIn:bJe,circInOut:aOt,circOut:rOt,backIn:vJe,backInOut:sOt,backOut:tOt,anticipate:nOt},LPs=s=>typeof s=="string",oft=s=>{if(oOt(s)){MH(s.length===4,"Cubic bezier arrays must contain four numerical values.","cubic-bezier-length");const[t,n,r,a]=s;return Yre(t,n,r,a)}else if(LPs(s))return MH(ift[s]!==void 0,`Invalid easing type '${s}'`,"invalid-easing-type"),ift[s];return s},gle=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"],lft={value:null,addProjectionMetrics:null};function IPs(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 y=p&&a?n:r;return m&&l.add(h),y.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&&lft.value&&lft.value.frameloop[t].push(c),c=0,n.clear(),a=!1,i&&(i=!1,u.process(h))}};return u}const DPs=40;function lOt(s,t){let n=!1,r=!0;const a={delta:0,timestamp:0,isProcessing:!1},i=()=>n=!0,l=gle.reduce((j,S)=>(j[S]=IPs(i,t?S:void 0),j),{}),{setup:o,read:c,resolveKeyframes:d,preUpdate:u,update:h,preRender:m,render:p,postRender:f}=l,y=()=>{const j=RP.useManualTiming,S=j?a.timestamp:performance.now();n=!1,j||(a.delta=r?1e3/60:Math.max(Math.min(S-a.timestamp,DPs),1)),a.timestamp=S,a.isProcessing=!0,o.process(a),c.process(a),d.process(a),u.process(a),h.process(a),m.process(a),p.process(a),f.process(a),a.isProcessing=!1,n&&t&&(r=!1,s(y))},v=()=>{n=!0,r=!0,a.isProcessing||s(y)};return{schedule:gle.reduce((j,S)=>{const C=l[S];return j[S]=(E,P=!1,M=!1)=>(n||v(),C.schedule(E,P,M)),j},{}),cancel:j=>{for(let S=0;S(k4e===void 0&&hb.set(iv.isProcessing||RP.useManualTiming?iv.timestamp:performance.now()),k4e),set:s=>{k4e=s,queueMicrotask(RPs)}},cOt=s=>t=>typeof t=="string"&&t.startsWith(s),dOt=cOt("--"),FPs=cOt("var(--"),_Je=s=>FPs(s)?OPs.test(s.split("/*")[0].trim()):!1,OPs=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu;function cft(s){return typeof s!="string"?!1:s.split("/*")[0].includes("var(--")}const dW={test:s=>typeof s=="number",parse:parseFloat,transform:s=>s},ite={...dW,transform:s=>lC(0,1,s)},yle={...dW,default:1},wJ=s=>Math.round(s*1e5)/1e5,wJe=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function zPs(s){return s==null}const BPs=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,jJe=(s,t)=>n=>!!(typeof n=="string"&&BPs.test(n)&&n.startsWith(s)||t&&!zPs(n)&&Object.prototype.hasOwnProperty.call(n,t)),uOt=(s,t,n)=>r=>{if(typeof r!="string")return r;const[a,i,l,o]=r.match(wJe);return{[s]:parseFloat(a),[t]:parseFloat(i),[n]:parseFloat(l),alpha:o!==void 0?parseFloat(o):1}},UPs=s=>lC(0,255,s),kOe={...dW,transform:s=>Math.round(UPs(s))},mF={test:jJe("rgb","red"),parse:uOt("red","green","blue"),transform:({red:s,green:t,blue:n,alpha:r=1})=>"rgba("+kOe.transform(s)+", "+kOe.transform(t)+", "+kOe.transform(n)+", "+wJ(ite.transform(r))+")"};function qPs(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 Y$e={test:jJe("#"),parse:qPs,transform:mF.transform},Zre=s=>({test:t=>typeof t=="string"&&t.endsWith(s)&&t.split(" ").length===1,parse:parseFloat,transform:t=>`${t}${s}`}),HT=Zre("deg"),Q4=Zre("%"),wo=Zre("px"),$Ps=Zre("vh"),VPs=Zre("vw"),dft={...Q4,parse:s=>Q4.parse(s)/100,transform:s=>Q4.transform(s*100)},ZU={test:jJe("hsl","hue"),parse:uOt("hue","saturation","lightness"),transform:({hue:s,saturation:t,lightness:n,alpha:r=1})=>"hsla("+Math.round(s)+", "+Q4.transform(wJ(t))+", "+Q4.transform(wJ(n))+", "+wJ(ite.transform(r))+")"},Ag={test:s=>mF.test(s)||Y$e.test(s)||ZU.test(s),parse:s=>mF.test(s)?mF.parse(s):ZU.test(s)?ZU.parse(s):Y$e.parse(s),transform:s=>typeof s=="string"?s:s.hasOwnProperty("red")?mF.transform(s):ZU.transform(s),getAnimatableNone:s=>{const t=Ag.parse(s);return t.alpha=0,Ag.transform(t)}},HPs=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function GPs(s){var t,n;return isNaN(s)&&typeof s=="string"&&(((t=s.match(wJe))==null?void 0:t.length)||0)+(((n=s.match(HPs))==null?void 0:n.length)||0)>0}const hOt="number",mOt="color",WPs="var",KPs="var(",uft="${}",YPs=/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 PH(s){const t=s.toString(),n=[],r={color:[],number:[],var:[]},a=[];let i=0;const o=t.replace(YPs,c=>(Ag.test(c)?(r.color.push(i),a.push(mOt),n.push(Ag.parse(c))):c.startsWith(KPs)?(r.var.push(i),a.push(WPs),n.push(c)):(r.number.push(i),a.push(hOt),n.push(parseFloat(c))),++i,uft)).split(uft);return{values:n,split:o,indexes:r,types:a}}function ZPs(s){return PH(s).values}function pOt({split:s,types:t}){const n=s.length;return r=>{let a="";for(let i=0;itypeof s=="number"?0:Ag.test(s)?Ag.getAnimatableNone(s):s,JPs=(s,t)=>typeof s=="number"?t!=null&&t.trim().endsWith("/")?s:0:QPs(s);function eLs(s){const t=PH(s);return pOt(t)(t.values.map((r,a)=>JPs(r,t.split[a])))}const vS={test:GPs,parse:ZPs,createTransformer:XPs,getAnimatableNone:eLs};function SOe(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 tLs({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=SOe(c,o,s+1/3),i=SOe(c,o,s),l=SOe(c,o,s-1/3)}return{red:Math.round(a*255),green:Math.round(i*255),blue:Math.round(l*255),alpha:r}}function fAe(s,t){return n=>n>0?t:s}const Np=(s,t,n)=>s+(t-s)*n,COe=(s,t,n)=>{const r=s*s,a=n*(t*t-r)+r;return a<0?0:Math.sqrt(a)},sLs=[Y$e,mF,ZU],nLs=s=>sLs.find(t=>t.test(s));function hft(s){const t=nLs(s);if(DPe(!!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===ZU&&(n=tLs(n)),n}const mft=(s,t)=>{const n=hft(s),r=hft(t);if(!n||!r)return fAe(s,t);const a={...n};return i=>(a.red=COe(n.red,r.red,i),a.green=COe(n.green,r.green,i),a.blue=COe(n.blue,r.blue,i),a.alpha=Np(n.alpha,r.alpha,i),mF.transform(a))},Z$e=new Set(["none","hidden"]);function rLs(s,t){return Z$e.has(s)?n=>n<=0?s:t:n=>n>=1?t:s}function aLs(s,t){return n=>Np(s,t,n)}function NJe(s){return typeof s=="number"?aLs:typeof s=="string"?_Je(s)?fAe:Ag.test(s)?mft:lLs:Array.isArray(s)?fOt:typeof s=="object"?Ag.test(s)?mft:iLs:fAe}function fOt(s,t){const n=[...s],r=n.length,a=s.map((i,l)=>NJe(i)(i,t[l]));return i=>{for(let l=0;l{for(const i in r)n[i]=r[i](a);return n}}function oLs(s,t){const n=[],r={color:0,var:0,number:0};for(let a=0;a{const n=vS.createTransformer(t),r=PH(s),a=PH(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?Z$e.has(s)&&!a.values.length||Z$e.has(t)&&!r.values.length?rLs(s,t):Kre(fOt(oLs(r,a),a.values),n):(DPe(!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"),fAe(s,t))};function xOt(s,t,n){return typeof s=="number"&&typeof t=="number"&&typeof n=="number"?Np(s,t,n):NJe(s)(s,t)}const cLs=s=>{const t=({timestamp:n})=>s(n);return{start:(n=!0)=>Mm.update(t,n),stop:()=>FP(t),now:()=>iv.isProcessing?iv.timestamp:hb.now()}},gOt=(s,t,n=10)=>{let r="";const a=Math.max(Math.round(t/n),2);for(let i=0;i=xAe?1/0:t}function dLs(s,t=100,n){const r=n({...s,keyframes:[0,t]}),a=Math.min(kJe(r),xAe);return{type:"keyframes",ease:i=>r.next(a*i).value/t,duration:nN(a)}}const Cf={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 X$e(s,t){return s*Math.sqrt(1-t*t)}const uLs=12;function hLs(s,t,n){let r=n;for(let a=1;a{const u=d*l,h=u*s,m=u-n,p=X$e(d,l),f=Math.exp(-h);return AOe-m/p*f},i=d=>{const h=d*l*s,m=h*n+n,p=Math.pow(l,2)*Math.pow(d,2)*s,f=Math.exp(-h),y=X$e(Math.pow(d,2),l);return(-a(d)+AOe>0?-1:1)*((m-p)*f)/y}):(a=d=>{const u=Math.exp(-d*s),h=(d-n)*s+1;return-AOe+u*h},i=d=>{const u=Math.exp(-d*s),h=(n-d)*(s*s);return u*h});const o=5/s,c=hLs(a,i,o);if(s=O_(s),isNaN(c))return{stiffness:Cf.stiffness,damping:Cf.damping,duration:s};{const d=Math.pow(c,2)*r;return{stiffness:d,damping:l*2*Math.sqrt(r*d),duration:s}}}const pLs=["duration","bounce"],fLs=["stiffness","damping","mass"];function pft(s,t){return t.some(n=>s[n]!==void 0)}function xLs(s){let t={velocity:Cf.velocity,stiffness:Cf.stiffness,damping:Cf.damping,mass:Cf.mass,isResolvedFromDuration:!1,...s};if(!pft(s,fLs)&&pft(s,pLs))if(t.velocity=0,s.visualDuration){const n=s.visualDuration,r=2*Math.PI/(n*1.2),a=r*r,i=2*lC(.05,1,1-(s.bounce||0))*Math.sqrt(a);t={...t,mass:Cf.mass,stiffness:a,damping:i}}else{const n=mLs({...s,velocity:0});t={...t,...n,mass:Cf.mass},t.isResolvedFromDuration=!0}return t}function gAe(s=Cf.visualDuration,t=Cf.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}=xLs({...n,velocity:-nN(n.velocity||0)}),f=m||0,y=d/(2*Math.sqrt(c*u)),v=l-i,g=nN(Math.sqrt(c/u)),b=Math.abs(v)<5;r||(r=b?Cf.restSpeed.granular:Cf.restSpeed.default),a||(a=b?Cf.restDelta.granular:Cf.restDelta.default);let j,S,C,E,P,M;if(y<1)C=X$e(g,y),E=(f+y*g*v)/C,j=D=>{const O=Math.exp(-y*g*D);return l-O*(E*Math.sin(C*D)+v*Math.cos(C*D))},P=y*g*E+v*C,M=y*g*v-E*C,S=D=>Math.exp(-y*g*D)*(P*Math.sin(C*D)+M*Math.cos(C*D));else if(y===1){j=O=>l-Math.exp(-g*O)*(v+(f+g*v)*O);const D=f+g*v;S=O=>Math.exp(-g*O)*(g*D*O-f)}else{const D=g*Math.sqrt(y*y-1);j=$=>{const H=Math.exp(-y*g*$),Y=Math.min(D*$,300);return l-H*((f+y*g*v)*Math.sinh(Y)+D*v*Math.cosh(Y))/D};const O=(f+y*g*v)/D,V=y*g*O-v*D,G=y*g*v-O*D;S=$=>{const H=Math.exp(-y*g*$),Y=Math.min(D*$,300);return H*(V*Math.sinh(Y)+G*Math.cosh(Y))}}const I={calculatedDuration:p&&h||null,velocity:D=>O_(S(D)),next:D=>{if(!p&&y<1){const V=Math.exp(-y*g*D),G=Math.sin(C*D),$=Math.cos(C*D),H=l-V*(E*G+v*$),Y=O_(V*(P*G+M*$));return o.done=Math.abs(Y)<=r&&Math.abs(l-H)<=a,o.value=o.done?l:H,o}const O=j(D);if(p)o.done=D>=h;else{const V=O_(S(D));o.done=Math.abs(V)<=r&&Math.abs(l-O)<=a}return o.value=o.done?l:O,o},toString:()=>{const D=Math.min(kJe(I),xAe),O=gOt(V=>I.next(D*V).value,D,30);return D+"ms "+O},toTransition:()=>{}};return I}gAe.applyToOptions=s=>{const t=dLs(s,100,gAe);return s.ease=t.ease,s.duration=O_(t.duration),s.type="keyframes",s};const gLs=5;function yOt(s,t,n){const r=Math.max(t-gLs,0);return XFt(n-s(r),t-r)}function Q$e({keyframes:s,velocity:t=0,power:n=.8,timeConstant:r=325,bounceDamping:a=10,bounceStiffness:i=500,modifyTarget:l,min:o,max:c,restDelta:d=.5,restSpeed:u}){const h=s[0],m={done:!1,value:h},p=M=>o!==void 0&&Mc,f=M=>o===void 0?c:c===void 0||Math.abs(o-M)-y*Math.exp(-M/r),j=M=>g+b(M),S=M=>{const I=b(M),D=j(M);m.done=Math.abs(I)<=d,m.value=m.done?g:D};let C,E;const P=M=>{p(m.value)&&(C=M,E=gAe({keyframes:[m.value,f(m.value)],velocity:yOt(j,M,m.value),damping:a,stiffness:i,restDelta:d,restSpeed:u}))};return P(0),{calculatedDuration:null,next:M=>{let I=!1;return!E&&C===void 0&&(I=!0,S(M),P(M)),C!==void 0&&M>=C?E.next(M-C):(!I&&S(M),m)}}}function yLs(s,t,n){const r=[],a=n||RP.mix||xOt,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=yLs(t,r,a),c=o.length,d=u=>{if(l&&u1)for(;hd(lC(s[0],s[i-1],u)):d}function bLs(s,t){const n=s[s.length-1];for(let r=1;r<=t;r++){const a=ate(0,t,r);s.push(Np(n,1,a))}}function _Ls(s){const t=[0];return bLs(t,s.length-1),t}function wLs(s,t){return s.map(n=>n*t)}function jLs(s,t){return s.map(()=>t||iOt).splice(0,s.length-1)}function jJ({duration:s=300,keyframes:t,times:n,ease:r="easeInOut"}){const a=PPs(r)?r.map(oft):oft(r),i={done:!1,value:t[0]},l=wLs(n&&n.length===t.length?n:_Ls(t),s),o=vLs(l,t,{ease:Array.isArray(a)?a:jLs(t,a)});return{calculatedDuration:s,next:c=>(i.value=o(c),i.done=c>=s,i)}}const NLs=s=>s!==null;function RPe(s,{repeat:t,repeatType:n="loop"},r,a=1){const i=s.filter(NLs),o=a<0||t&&n!=="loop"&&t%2===1?0:i.length-1;return!o||r===void 0?i[o]:r}const kLs={decay:Q$e,inertia:Q$e,tween:jJ,keyframes:jJ,spring:gAe};function vOt(s){typeof s.type=="string"&&(s.type=kLs[s.type])}class SJe{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 SLs=s=>s/100;class yAe extends SJe{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!==hb.now()&&this.tick(hb.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;vOt(t);const{type:n=jJ,repeat:r=0,repeatDelay:a=0,repeatType:i,velocity:l=0}=t;let{keyframes:o}=t;const c=n||jJ;c!==jJ&&typeof o[0]!="number"&&(this.mixKeyframes=Kre(SLs,xOt(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=kJe(d));const{calculatedDuration:u}=d;this.calculatedDuration=u,this.resolvedDuration=u+a,this.totalDuration=this.resolvedDuration*(r+1)-a,this.generator=d}updateTime(t){const n=Math.round(t-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=n}tick(t,n=!1){const{generator:r,totalDuration:a,mixKeyframes:i,mirroredGenerator:l,resolvedDuration:o,calculatedDuration:c}=this;if(this.startTime===null)return r.next(0);const{delay:d=0,keyframes:u,repeat:h,repeatType:m,repeatDelay:p,type:f,onUpdate:y,finalKeyframe:v}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,t):this.speed<0&&(this.startTime=Math.min(t-a/this.speed,this.startTime)),n?this.currentTime=t:this.updateTime(t);const g=this.currentTime-d*(this.playbackSpeed>=0?1:-1),b=this.playbackSpeed>=0?g<0:g>a;this.currentTime=Math.max(g,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=a);let j=this.currentTime,S=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"&&(S=l)),j=lC(0,1,D)*o}let C;b?(this.delayState.value=u[0],C=this.delayState):C=S.next(j),i&&!b&&(C.value=i(C.value));let{done:E}=C;!b&&c!==null&&(E=this.playbackSpeed>=0?this.currentTime>=a:this.currentTime<=0);const P=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&E);return P&&f!==Q$e&&(C.value=RPe(u,this.options,v,this.speed)),y&&y(C.value),P&&this.finish(),C}then(t,n){return this.finished.then(t,n)}get duration(){return nN(this.calculatedDuration)}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+nN(t)}get time(){return nN(this.currentTime)}set time(t){t=O_(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 yOt(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(hb.now()),this.playbackSpeed=t,n&&this.driver&&(this.time=nN(this.currentTime))}play(){var a,i;if(this.isStopped)return;const{driver:t=cLs,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(hb.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 CLs(s){for(let t=1;ts*180/Math.PI,J$e=s=>{const t=pF(Math.atan2(s[1],s[0]));return eVe(t)},ALs={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:s=>(Math.abs(s[0])+Math.abs(s[3]))/2,rotate:J$e,rotateZ:J$e,skewX:s=>pF(Math.atan(s[1])),skewY:s=>pF(Math.atan(s[2])),skew:s=>(Math.abs(s[1])+Math.abs(s[2]))/2},eVe=s=>(s=s%360,s<0&&(s+=360),s),fft=J$e,xft=s=>Math.sqrt(s[0]*s[0]+s[1]*s[1]),gft=s=>Math.sqrt(s[4]*s[4]+s[5]*s[5]),ELs={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:xft,scaleY:gft,scale:s=>(xft(s)+gft(s))/2,rotateX:s=>eVe(pF(Math.atan2(s[6],s[5]))),rotateY:s=>eVe(pF(Math.atan2(-s[2],s[0]))),rotateZ:fft,rotate:fft,skewX:s=>pF(Math.atan(s[4])),skewY:s=>pF(Math.atan(s[1])),skew:s=>(Math.abs(s[1])+Math.abs(s[4]))/2};function tVe(s){return s.includes("scale")?1:0}function sVe(s,t){if(!s||s==="none")return tVe(t);const n=s.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let r,a;if(n)r=ELs,a=n;else{const o=s.match(/^matrix\(([-\d.e\s,]+)\)$/u);r=ALs,a=o}if(!a)return tVe(t);const i=r[t],l=a[1].split(",").map(MLs);return typeof i=="function"?i(l):l[i]}const TLs=(s,t)=>{const{transform:n="none"}=getComputedStyle(s);return sVe(n,t)};function MLs(s){return parseFloat(s.trim())}const uW=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],hW=new Set(uW),yft=s=>s===dW||s===wo,PLs=new Set(["x","y","z"]),LLs=uW.filter(s=>!PLs.has(s));function ILs(s){const t=[];return LLs.forEach(n=>{const r=s.getValue(n);r!==void 0&&(t.push([n,r.get()]),r.set(n.startsWith("scale")?1:0))}),t}const vM={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})=>sVe(t,"x"),y:(s,{transform:t})=>sVe(t,"y")};vM.translateX=vM.x;vM.translateY=vM.y;const f7=new Set;let nVe=!1,rVe=!1,aVe=!1;function bOt(){if(rVe){const s=Array.from(f7).filter(r=>r.needsMeasurement),t=new Set(s.map(r=>r.element)),n=new Map;t.forEach(r=>{const a=ILs(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)})}rVe=!1,nVe=!1,f7.forEach(s=>s.complete(aVe)),f7.clear()}function _Ot(){f7.forEach(s=>{s.readKeyframes(),s.needsMeasurement&&(rVe=!0)})}function DLs(){aVe=!0,_Ot(),bOt(),aVe=!1}class CJe{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?(f7.add(this),nVe||(nVe=!0,Mm.read(_Ot),Mm.resolveKeyframes(bOt))):(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])}CLs(t)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(t=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,t),f7.delete(this)}cancel(){this.state==="scheduled"&&(f7.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const RLs=s=>s.startsWith("--");function wOt(s,t,n){RLs(t)?s.style.setProperty(t,n):s.style[t]=n}const FLs={};function jOt(s,t){const n=ZFt(s);return()=>FLs[t]??n()}const OLs=jOt(()=>window.ScrollTimeline!==void 0,"scrollTimeline"),NOt=jOt(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),hX=([s,t,n,r])=>`cubic-bezier(${s}, ${t}, ${n}, ${r})`,vft={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:hX([0,.65,.55,1]),circOut:hX([.55,0,1,.45]),backIn:hX([.31,.01,.66,-.59]),backOut:hX([.33,1.53,.69,.99])};function kOt(s,t){if(s)return typeof s=="function"?NOt()?gOt(s,t):"ease-out":oOt(s)?hX(s):Array.isArray(s)?s.map(n=>kOt(n,t)||vft.easeOut):vft[s]}function zLs(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=kOt(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 SOt(s){return typeof s=="function"&&"applyToOptions"in s}function BLs({type:s,...t}){return SOt(s)&&NOt()?s.applyToOptions(t):(t.duration??(t.duration=300),t.ease??(t.ease="easeOut"),t)}class COt extends SJe{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,MH(typeof t.type!="string",`Mini animate() doesn't support "type" as a string.`,"mini-spring");const d=BLs(t);this.animation=zLs(n,r,a,d,i),d.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!i){const u=RPe(a,this.options,o,this.speed);this.updateMotionValue&&this.updateMotionValue(u),wOt(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 nN(Number(t))}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+nN(t)}get time(){return nN(Number(this.animation.currentTime)||0)}set time(t){const n=this.finishedTime!==null;this.manualStartTime=null,this.finishedTime=null,this.animation.currentTime=O_(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&&OLs()?(this.animation.timeline=t,n&&(this.animation.rangeStart=n),r&&(this.animation.rangeEnd=r),gN):a(this)}}const AOt={anticipate:nOt,backInOut:sOt,circInOut:aOt};function ULs(s){return s in AOt}function qLs(s){typeof s.ease=="string"&&ULs(s.ease)&&(s.ease=AOt[s.ease])}const EOe=10;class $Ls extends COt{constructor(t){qLs(t),vOt(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 yAe({...l,autoplay:!1}),c=Math.max(EOe,hb.now()-this.startTime),d=lC(0,EOe,c-EOe),u=o.sample(c).value,{name:h}=this.options;i&&h&&wOt(i,h,u),n.setWithVelocity(o.sample(Math.max(0,c-d)).value,u,d),o.stop()}}const bft=(s,t)=>t==="zIndex"?!1:!!(typeof s=="number"||Array.isArray(s)||typeof s=="string"&&(vS.test(s)||s==="0")&&!s.startsWith("url("));function VLs(s){const t=s[0];if(s.length===1)return!0;for(let n=0;nObject.hasOwnProperty.call(Element.prototype,"animate"));function ZLs(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 YLs()&&n&&(EOt.has(n)||KLs.has(n)&&WLs(o))&&(n!=="transform"||!u)&&!d&&!r&&a!=="mirror"&&i!==0&&l!=="inertia"}const XLs=40;class QLs extends SJe{constructor({autoplay:t=!0,delay:n=0,type:r="keyframes",repeat:a=0,repeatDelay:i=0,repeatType:l="loop",keyframes:o,name:c,motionValue:d,element:u,...h}){var f;super(),this.stop=()=>{var y,v;this._animation&&(this._animation.stop(),(y=this.stopTimeline)==null||y.call(this)),(v=this.keyframeResolver)==null||v.cancel()},this.createdAt=hb.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)||CJe;this.keyframeResolver=new p(o,(y,v,g)=>this.onKeyframesResolved(y,v,m,!g),c,d,u),(f=this.keyframeResolver)==null||f.scheduleResolve()}onKeyframesResolved(t,n,r,a){var g,b;this.keyframeResolver=void 0;const{name:i,type:l,velocity:o,delay:c,isHandoff:d,onUpdate:u}=r;this.resolvedAt=hb.now();let h=!0;HLs(t,i,l,o)||(h=!1,(RP.instantAnimations||!c)&&(u==null||u(RPe(t,r,n))),t[0]=t[t.length-1],iVe(r),r.repeat=0);const p={startTime:a?this.resolvedAt?this.resolvedAt-this.createdAt>XLs?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...r,keyframes:t},f=h&&!d&&ZLs(p),y=(b=(g=p.motionValue)==null?void 0:g.owner)==null?void 0:b.current;let v;if(f)try{v=new $Ls({...p,element:y})}catch{v=new yAe(p)}else v=new yAe(p);v.finished.then(()=>{this.notifyFinished()}).catch(gN),this.pendingTimeline&&(this.stopTimeline=v.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=v}get finished(){return this._animation?this.animation.finished:this._finished}then(t,n){return this.finished.finally(t).then(()=>{})}get animation(){var t;return this._animation||((t=this.keyframeResolver)==null||t.resume(),DLs()),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 TOt(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 JLs=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function eIs(s){const t=JLs.exec(s);if(!t)return[,];const[,n,r,a]=t;return[`--${n??r}`,a]}const tIs=4;function MOt(s,t,n=1){MH(n<=tIs,`Max CSS variable fallback depth detected in property "${s}". This may indicate a circular fallback dependency.`,"max-css-var-depth");const[r,a]=eIs(s);if(!r)return;const i=window.getComputedStyle(t).getPropertyValue(r);if(i){const l=i.trim();return WFt(l)?parseFloat(l):l}return _Je(a)?MOt(a,t,n+1):a}const sIs={type:"spring",stiffness:500,damping:25,restSpeed:10},nIs=s=>({type:"spring",stiffness:550,damping:s===0?2*Math.sqrt(550):30,restSpeed:10}),rIs={type:"keyframes",duration:.8},aIs={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},iIs=(s,{keyframes:t})=>t.length>2?rIs:hW.has(s)?s.startsWith("scale")?nIs(t[1]):sIs:aIs;function POt(s,t){if(s!=null&&s.inherit&&t){const{inherit:n,...r}=s;return{...t,...r}}return s}function AJe(s,t){const n=(s==null?void 0:s[t])??(s==null?void 0:s.default)??s;return n!==s?POt(n,s):n}const oIs=new Set(["when","delay","delayChildren","staggerChildren","staggerDirection","repeat","repeatType","repeatDelay","from","elapsed"]);function lIs(s){for(const t in s)if(!oIs.has(t))return!0;return!1}const EJe=(s,t,n,r={},a,i)=>l=>{const o=AJe(r,s)||{},c=o.delay||r.delay||0;let{elapsed:d=0}=r;d=d-O_(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};lIs(o)||Object.assign(u,iIs(s,u)),u.duration&&(u.duration=O_(u.duration)),u.repeatDelay&&(u.repeatDelay=O_(u.repeatDelay)),u.from!==void 0&&(u.keyframes[0]=u.from);let h=!1;if((u.type===!1||u.duration===0&&!u.repeatDelay)&&(iVe(u),u.delay===0&&(h=!0)),(RP.instantAnimations||RP.skipAnimations||a!=null&&a.shouldSkipAnimations)&&(h=!0,iVe(u),u.delay=0),u.allowFlatten=!o.type&&!o.ease,h&&!i&&t.get()!==void 0){const m=RPe(u.keyframes,o);if(m!==void 0){Mm.update(()=>{u.onUpdate(m),u.onComplete()});return}}return o.isSync?new yAe(u):new QLs(u)};function _ft(s){const t=[{},{}];return s==null||s.values.forEach((n,r)=>{t[0][r]=n.get(),t[1][r]=n.getVelocity()}),t}function TJe(s,t,n,r){if(typeof t=="function"){const[a,i]=_ft(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]=_ft(r);t=t(n!==void 0?n:s.custom,a,i)}return t}function x7(s,t,n){const r=s.getProps();return TJe(r,t,n!==void 0?n:r.custom,s)}const LOt=new Set(["width","height","top","left","right","bottom",...uW]),wft=30,cIs=s=>!isNaN(parseFloat(s));class dIs{constructor(t,n={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=r=>{var i;const a=hb.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=hb.now(),this.canTrackVelocity===null&&t!==void 0&&(this.canTrackVelocity=cIs(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 yJe);const r=this.events[t].add(n);return t==="change"?()=>{r(),Mm.read(()=>{this.events.change.getSize()||this.stop()})}:r}clearListeners(){for(const t in this.events)this.events[t].clear()}attach(t,n){this.passiveEffect=t,this.stopPassiveEffect=n}set(t){this.passiveEffect?this.passiveEffect(t,this.updateAndNotify):this.updateAndNotify(t)}setWithVelocity(t,n,r){this.set(n),this.prev=void 0,this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt-r}jump(t,n=!0){this.updateAndNotify(t),this.prev=t,this.prevUpdatedAt=this.prevFrameValue=void 0,n&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}dirty(){var t;(t=this.events.change)==null||t.notify(this.current)}addDependent(t){this.dependents||(this.dependents=new Set),this.dependents.add(t)}removeDependent(t){this.dependents&&this.dependents.delete(t)}get(){return this.current}getPrevious(){return this.prev}getVelocity(){const t=hb.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||t-this.updatedAt>wft)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,wft);return XFt(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 LH(s,t){return new dIs(s,t)}const oVe=s=>Array.isArray(s);function uIs(s,t,n){s.hasValue(t)?s.getValue(t).set(n):s.addValue(t,LH(n))}function hIs(s){return oVe(s)?s[s.length-1]||0:s}function mIs(s,t){const n=x7(s,t);let{transitionEnd:r={},transition:a={},...i}=n||{};i={...i,...r};for(const l in i){const o=hIs(i[l]);uIs(s,l,o)}}const fv=s=>!!(s&&s.getVelocity);function pIs(s){return!!(fv(s)&&s.add)}function lVe(s,t){const n=s.getValue("willChange");if(pIs(n))return n.add(t);if(!n&&RP.WillChange){const r=new RP.WillChange("auto");s.addValue("willChange",r),r.add(t)}}function MJe(s){return s.replace(/([A-Z])/g,t=>`-${t.toLowerCase()}`)}const fIs="framerAppearId",IOt="data-"+MJe(fIs);function DOt(s){return s.props[IOt]}function xIs({protectedKeys:s,needsAnimating:t},n){const r=s.hasOwnProperty(n)&&t[n]!==!0;return t[n]=!1,r}function ROt(s,t,{delay:n=0,transitionOverride:r,type:a}={}){let{transition:i,transitionEnd:l,...o}=t;const c=s.getDefaultTransition();i=i?POt(i,c):c;const d=i==null?void 0:i.reduceMotion;r&&(i=r);const u=[],h=a&&s.animationState&&s.animationState.getState()[a];for(const m in o){const p=s.getValue(m,s.latestValues[m]??null),f=o[m];if(f===void 0||h&&xIs(h,m))continue;const y={delay:n,...AJe(i||{},m)},v=p.get();if(v!==void 0&&!p.isAnimating()&&!Array.isArray(f)&&f===v&&!y.velocity){Mm.update(()=>p.set(f));continue}let g=!1;if(window.MotionHandoffAnimation){const S=DOt(s);if(S){const C=window.MotionHandoffAnimation(S,m,Mm);C!==null&&(y.startTime=C,g=!0)}}lVe(s,m);const b=d??s.shouldReduceMotion;p.start(EJe(m,p,f,b&&LOt.has(m)?{type:!1}:y,s,g));const j=p.animation;j&&u.push(j)}if(l){const m=()=>Mm.update(()=>{l&&mIs(s,l)});u.length?Promise.all(u).then(m):m()}return u}function cVe(s,t,n={}){var c;const r=x7(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(ROt(s,r,n)):()=>Promise.resolve(),l=s.variantChildren&&s.variantChildren.size?(d=0)=>{const{delayChildren:u=0,staggerChildren:h,staggerDirection:m}=a;return gIs(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 gIs(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(cVe(c,t,{...l,delay:n+(typeof r=="function"?0:r)+TOt(s.variantChildren,c,r,a,i)}).then(()=>c.notify("AnimationComplete",t)));return Promise.all(o)}function yIs(s,t,n={}){s.notify("AnimationStart",t);let r;if(Array.isArray(t)){const a=t.map(i=>cVe(s,i,n));r=Promise.all(a)}else if(typeof t=="string")r=cVe(s,t,n);else{const a=typeof t=="function"?x7(s,t,n.custom):t;r=Promise.all(ROt(s,a,n))}return r.then(()=>{s.notify("AnimationComplete",t)})}const vIs={test:s=>s==="auto",parse:s=>s},FOt=s=>t=>t.test(s),OOt=[dW,wo,Q4,HT,VPs,$Ps,vIs],jft=s=>OOt.find(FOt(s));function bIs(s){return typeof s=="number"?s===0:s!==null?s==="none"||s==="0"||YFt(s):!0}const _Is=new Set(["brightness","contrast","saturate","opacity"]);function wIs(s){const[t,n]=s.slice(0,-1).split("(");if(t==="drop-shadow")return s;const[r]=n.match(wJe)||[];if(!r)return s;const a=n.replace(r,"");let i=_Is.has(t)?1:0;return r!==n&&(i*=100),t+"("+i+a+")"}const jIs=/\b([a-z-]*)\(.*?\)/gu,dVe={...vS,getAnimatableNone:s=>{const t=s.match(jIs);return t?t.map(wIs).join(" "):s}},uVe={...vS,getAnimatableNone:s=>{const t=vS.parse(s);return vS.createTransformer(s)(t.map(r=>typeof r=="number"?0:typeof r=="object"?{...r,alpha:1}:r))}},Nft={...dW,transform:Math.round},NIs={rotate:HT,rotateX:HT,rotateY:HT,rotateZ:HT,scale:yle,scaleX:yle,scaleY:yle,scaleZ:yle,skew:HT,skewX:HT,skewY:HT,distance:wo,translateX:wo,translateY:wo,translateZ:wo,x:wo,y:wo,z:wo,perspective:wo,transformPerspective:wo,opacity:ite,originX:dft,originY:dft,originZ:wo},PJe={borderWidth:wo,borderTopWidth:wo,borderRightWidth:wo,borderBottomWidth:wo,borderLeftWidth:wo,borderRadius:wo,borderTopLeftRadius:wo,borderTopRightRadius:wo,borderBottomRightRadius:wo,borderBottomLeftRadius:wo,width:wo,maxWidth:wo,height:wo,maxHeight:wo,top:wo,right:wo,bottom:wo,left:wo,inset:wo,insetBlock:wo,insetBlockStart:wo,insetBlockEnd:wo,insetInline:wo,insetInlineStart:wo,insetInlineEnd:wo,padding:wo,paddingTop:wo,paddingRight:wo,paddingBottom:wo,paddingLeft:wo,paddingBlock:wo,paddingBlockStart:wo,paddingBlockEnd:wo,paddingInline:wo,paddingInlineStart:wo,paddingInlineEnd:wo,margin:wo,marginTop:wo,marginRight:wo,marginBottom:wo,marginLeft:wo,marginBlock:wo,marginBlockStart:wo,marginBlockEnd:wo,marginInline:wo,marginInlineStart:wo,marginInlineEnd:wo,fontSize:wo,backgroundPositionX:wo,backgroundPositionY:wo,...NIs,zIndex:Nft,fillOpacity:ite,strokeOpacity:ite,numOctaves:Nft},kIs={...PJe,color:Ag,backgroundColor:Ag,outlineColor:Ag,fill:Ag,stroke:Ag,borderColor:Ag,borderTopColor:Ag,borderRightColor:Ag,borderBottomColor:Ag,borderLeftColor:Ag,filter:dVe,WebkitFilter:dVe,mask:uVe,WebkitMask:uVe},zOt=s=>kIs[s],SIs=new Set([dVe,uVe]);function BOt(s,t){let n=zOt(s);return SIs.has(n)||(n=vS),n.getAnimatableNone?n.getAnimatableNone(t):void 0}const CIs=new Set(["auto","none","0"]);function AIs(s,t,n){let r=0,a;for(;r{t.getValue(c).set(d)}),this.resolveNoneKeyframes()}}function LJe(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 UOt=(s,t)=>t&&typeof s=="number"?t.transform(s):s;function S4e(s){return KFt(s)&&"offsetHeight"in s&&!("ownerSVGElement"in s)}const{schedule:IJe,cancel:Dbr}=lOt(queueMicrotask,!1),Nk={x:!1,y:!1};function qOt(){return Nk.x||Nk.y}function TIs(s){return s==="x"||s==="y"?Nk[s]?null:(Nk[s]=!0,()=>{Nk[s]=!1}):Nk.x||Nk.y?null:(Nk.x=Nk.y=!0,()=>{Nk.x=Nk.y=!1})}function $Ot(s,t){const n=LJe(s),r=new AbortController,a={passive:!0,...t,signal:r.signal};return[n,a,()=>r.abort()]}function MIs(s){return!(s.pointerType==="touch"||qOt())}function PIs(s,t,n={}){const[r,a,i]=$Ot(s,n);return r.forEach(l=>{let o=!1,c=!1,d;const u=()=>{l.removeEventListener("pointerleave",f)},h=v=>{d&&(d(v),d=void 0),u()},m=v=>{o=!1,window.removeEventListener("pointerup",m),window.removeEventListener("pointercancel",m),c&&(c=!1,h(v))},p=()=>{o=!0,window.addEventListener("pointerup",m,a),window.addEventListener("pointercancel",m,a)},f=v=>{if(v.pointerType!=="touch"){if(o){c=!0;return}h(v)}},y=v=>{if(!MIs(v))return;c=!1;const g=t(l,v);typeof g=="function"&&(d=g,l.addEventListener("pointerleave",f,a))};l.addEventListener("pointerenter",y,a),l.addEventListener("pointerdown",p,a)}),i}const VOt=(s,t)=>t?s===t?!0:VOt(s,t.parentElement):!1,DJe=s=>s.pointerType==="mouse"?typeof s.button!="number"||s.button<=0:s.isPrimary!==!1,LIs=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function IIs(s){return LIs.has(s.tagName)||s.isContentEditable===!0}const DIs=new Set(["INPUT","SELECT","TEXTAREA"]);function RIs(s){return DIs.has(s.tagName)||s.isContentEditable===!0}const C4e=new WeakSet;function kft(s){return t=>{t.key==="Enter"&&s(t)}}function TOe(s,t){s.dispatchEvent(new PointerEvent("pointer"+t,{isPrimary:!0,bubbles:!0}))}const FIs=(s,t)=>{const n=s.currentTarget;if(!n)return;const r=kft(()=>{if(C4e.has(n))return;TOe(n,"down");const a=kft(()=>{TOe(n,"up")}),i=()=>TOe(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 Sft(s){return DJe(s)&&!qOt()}const Cft=new WeakSet;function OIs(s,t,n={}){const[r,a,i]=$Ot(s,n),l=o=>{const c=o.currentTarget;if(!Sft(o)||Cft.has(o))return;C4e.add(c),n.stopPropagation&&Cft.add(o);const d=t(c,o),u=(p,f)=>{window.removeEventListener("pointerup",h),window.removeEventListener("pointercancel",m),C4e.has(c)&&C4e.delete(c),Sft(p)&&typeof d=="function"&&d(p,{success:f})},h=p=>{u(p,c===window||c===document||n.useGlobalTarget||VOt(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),S4e(o)&&(o.addEventListener("focus",d=>FIs(d,a)),!IIs(o)&&!o.hasAttribute("tabindex")&&(o.tabIndex=0))}),i}function RJe(s){return KFt(s)&&"ownerSVGElement"in s}const A4e=new WeakMap;let GT;const HOt=(s,t,n)=>(r,a)=>a&&a[0]?a[0][s+"Size"]:RJe(r)&&"getBBox"in r?r.getBBox()[t]:r[n],zIs=HOt("inline","width","offsetWidth"),BIs=HOt("block","height","offsetHeight");function UIs({target:s,borderBoxSize:t}){var n;(n=A4e.get(s))==null||n.forEach(r=>{r(s,{get width(){return zIs(s,t)},get height(){return BIs(s,t)}})})}function qIs(s){s.forEach(UIs)}function $Is(){typeof ResizeObserver>"u"||(GT=new ResizeObserver(qIs))}function VIs(s,t){GT||$Is();const n=LJe(s);return n.forEach(r=>{let a=A4e.get(r);a||(a=new Set,A4e.set(r,a)),a.add(t),GT==null||GT.observe(r)}),()=>{n.forEach(r=>{const a=A4e.get(r);a==null||a.delete(t),a!=null&&a.size||GT==null||GT.unobserve(r)})}}const E4e=new Set;let XU;function HIs(){XU=()=>{const s={get width(){return window.innerWidth},get height(){return window.innerHeight}};E4e.forEach(t=>t(s))},window.addEventListener("resize",XU)}function GIs(s){return E4e.add(s),XU||HIs(),()=>{E4e.delete(s),!E4e.size&&typeof XU=="function"&&(window.removeEventListener("resize",XU),XU=void 0)}}function Aft(s,t){return typeof s=="function"?GIs(s):VIs(s,t)}function WIs(s){return RJe(s)&&s.tagName==="svg"}const KIs=[...OOt,Ag,vS],YIs=s=>KIs.find(FOt(s)),Eft=()=>({translate:0,scale:1,origin:0,originPoint:0}),QU=()=>({x:Eft(),y:Eft()}),Tft=()=>({min:0,max:0}),l0=()=>({x:Tft(),y:Tft()}),ZIs=new WeakMap;function FPe(s){return s!==null&&typeof s=="object"&&typeof s.start=="function"}function ote(s){return typeof s=="string"||Array.isArray(s)}const FJe=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],OJe=["initial",...FJe];function OPe(s){return FPe(s.animate)||OJe.some(t=>ote(s[t]))}function GOt(s){return!!(OPe(s)||s.variants)}function XIs(s,t,n){for(const r in t){const a=t[r],i=n[r];if(fv(a))s.addValue(r,a);else if(fv(i))s.addValue(r,LH(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,LH(l!==void 0?l:a,{owner:s}))}}for(const r in n)t[r]===void 0&&s.removeValue(r);return t}const hVe={current:null},WOt={current:!1},QIs=typeof window<"u";function JIs(){if(WOt.current=!0,!!QIs)if(window.matchMedia){const s=window.matchMedia("(prefers-reduced-motion)"),t=()=>hVe.current=s.matches;s.addEventListener("change",t),t()}else hVe.current=!1}const Mft=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];let vAe={};function KOt(s){vAe=s}function e8s(){return vAe}class t8s{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=CJe,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=hb.now();this.renderScheduledAtthis.bindToMotionValue(i,a)),this.reducedMotionConfig==="never"?this.shouldReduceMotion=!1:this.reducedMotionConfig==="always"?this.shouldReduceMotion=!0:(WOt.current||JIs(),this.shouldReduceMotion=hVe.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(),FP(this.notifyUpdate),FP(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&&EOt.has(t)&&this.current instanceof HTMLElement){const{factory:l,keyframes:o,times:c,ease:d,duration:u}=n.accelerate,h=new COt({element:this.current,name:t,keyframes:o,times:c,ease:d,duration:O_(u)}),m=l(h);this.valueSubscriptions.set(t,()=>{m(),h.cancel()});return}const r=hW.has(t);r&&this.onBindTransform&&this.onBindTransform();const a=n.on("change",l=>{this.latestValues[t]=l,this.props.onUpdate&&Mm.preRender(this.notifyUpdate),r&&this.projection&&(this.projection.isTransformDirty=!0),this.scheduleRender()});let i;typeof window<"u"&&window.MotionCheckAppearSync&&(i=window.MotionCheckAppearSync(this,t,n)),this.valueSubscriptions.set(t,()=>{a(),i&&i(),n.owner&&n.stop()})}sortNodePosition(t){return!this.current||!this.sortInstanceNodePosition||this.type!==t.type?0:this.sortInstanceNodePosition(this.current,t.current)}updateFeatures(){let t="animation";for(t in vAe){const n=vAe[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):l0()}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=LH(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"&&(WFt(r)||YFt(r))?r=parseFloat(r):!YIs(r)&&vS.test(n)&&(r=BOt(t,n)),this.setBaseTarget(t,fv(r)?r.get():r)),fv(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=TJe(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&&!fv(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 yJe),this.events[t].add(n)}notify(t,...n){this.events[t]&&this.events[t].notify(...n)}scheduleRenderMicrotask(){IJe.render(this.render)}}class YOt extends t8s{constructor(){super(...arguments),this.KeyframeResolver=EIs}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;fv(t)&&(this.childSubscription=t.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}}class mL{constructor(t){this.isMounted=!1,this.node=t}update(){}}function ZOt({top:s,left:t,right:n,bottom:r}){return{x:{min:t,max:n},y:{min:s,max:r}}}function s8s({x:s,y:t}){return{top:t.min,right:s.max,bottom:t.max,left:s.min}}function n8s(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 MOe(s){return s===void 0||s===1}function mVe({scale:s,scaleX:t,scaleY:n}){return!MOe(s)||!MOe(t)||!MOe(n)}function zR(s){return mVe(s)||XOt(s)||s.z||s.rotate||s.rotateX||s.rotateY||s.skewX||s.skewY}function XOt(s){return Pft(s.x)||Pft(s.y)}function Pft(s){return s&&s!=="0%"}function bAe(s,t,n){const r=s-n,a=t*r;return n+a}function Lft(s,t,n,r,a){return a!==void 0&&(s=bAe(s,a,r)),bAe(s,n,r)+t}function pVe(s,t=0,n=1,r,a){s.min=Lft(s.min,t,n,r,a),s.max=Lft(s.max,t,n,r,a)}function QOt(s,{x:t,y:n}){pVe(s.x,t.translate,t.scale,t.originPoint),pVe(s.y,n.translate,n.scale,n.originPoint)}const Ift=.999999999999,Dft=1.0000000000001;function r8s(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;cIft&&(t.x=1),t.yIft&&(t.y=1)}function g4(s,t){s.min+=t,s.max+=t}function Rft(s,t,n,r,a=.5){const i=Np(s.min,s.max,a);pVe(s,t,n,i,r)}function Fft(s,t){return typeof s=="string"?parseFloat(s)/100*(t.max-t.min):s}function T4e(s,t,n){const r=n??s;Rft(s.x,Fft(t.x,r.x),t.scaleX,t.scale,t.originX),Rft(s.y,Fft(t.y,r.y),t.scaleY,t.scale,t.originY)}function JOt(s,t){return ZOt(n8s(s.getBoundingClientRect(),t))}function a8s(s,t,n){const r=JOt(s,n),{scroll:a}=t;return a&&(g4(r.x,a.offset.x),g4(r.y,a.offset.y)),r}const i8s={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},o8s=uW.length;function l8s(s,t,n){let r="",a=!0;for(let i=0;i{if(!t.target)return s;if(typeof s=="string")if(wo.test(s))s=parseFloat(s);else return s;const n=Oft(s,t.target.x),r=Oft(s,t.target.y);return`${n}% ${r}%`}},c8s={correct:(s,{treeScale:t,projectionDelta:n})=>{const r=s,a=vS.parse(s);if(a.length>5)return r;const i=vS.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=Np(o,c,.5);return typeof a[2+l]=="number"&&(a[2+l]/=d),typeof a[3+l]=="number"&&(a[3+l]/=d),i(a)}},fVe={borderRadius:{...BY,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:BY,borderTopRightRadius:BY,borderBottomLeftRadius:BY,borderBottomRightRadius:BY,boxShadow:c8s};function t7t(s,{layout:t,layoutId:n}){return hW.has(s)||s.startsWith("origin")||(t||n!==void 0)&&(!!fVe[s]||s==="opacity")}function BJe(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)(fv(r[o])||a&&fv(a[o])||t7t(o,s)||((l=n==null?void 0:n.getValue(o))==null?void 0:l.liveStyle)!==void 0)&&(i[o]=r[o]);return i}function d8s(s){return window.getComputedStyle(s)}class u8s extends YOt{constructor(){super(...arguments),this.type="html",this.renderInstance=e7t}readValueFromInstance(t,n){var r;if(hW.has(n))return(r=this.projection)!=null&&r.isProjecting?tVe(n):TLs(t,n);{const a=d8s(t),i=(dOt(n)?a.getPropertyValue(n):a[n])||0;return typeof i=="string"?i.trim():i}}measureInstanceViewportBox(t,{transformPagePoint:n}){return JOt(t,n)}build(t,n,r){zJe(t,n,r.transformTemplate)}scrapeMotionValuesFromProps(t,n,r){return BJe(t,n,r)}}const h8s={offset:"stroke-dashoffset",array:"stroke-dasharray"},m8s={offset:"strokeDashoffset",array:"strokeDasharray"};function p8s(s,t,n=1,r=0,a=!0){s.pathLength=1;const i=a?h8s:m8s;s[i.offset]=`${-r}`,s[i.array]=`${t} ${n}`}const f8s=["offsetDistance","offsetPath","offsetRotate","offsetAnchor"];function s7t(s,{attrX:t,attrY:n,attrScale:r,pathLength:a,pathSpacing:i=1,pathOffset:l=0,...o},c,d,u){if(zJe(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 f8s)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&&p8s(h,a,i,l,!1)}const n7t=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"]),r7t=s=>typeof s=="string"&&s.toLowerCase()==="svg";function x8s(s,t,n,r){e7t(s,t,void 0,r);for(const a in t.attrs)s.setAttribute(n7t.has(a)?a:MJe(a),t.attrs[a])}function a7t(s,t,n){const r=BJe(s,t,n);for(const a in s)if(fv(s[a])||fv(t[a])){const i=uW.indexOf(a)!==-1?"attr"+a.charAt(0).toUpperCase()+a.substring(1):a;r[i]=s[a]}return r}class g8s extends YOt{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=l0}getBaseTargetFromProps(t,n){return t[n]}readValueFromInstance(t,n){if(hW.has(n)){const r=zOt(n);return r&&r.default||0}return n=n7t.has(n)?n:MJe(n),t.getAttribute(n)}scrapeMotionValuesFromProps(t,n,r){return a7t(t,n,r)}build(t,n,r){s7t(t,n,this.isSVGTag,r.transformTemplate,r.style)}renderInstance(t,n,r,a){x8s(t,n,r,a)}mount(t){this.isSVGTag=r7t(t.tagName),super.mount(t)}}const y8s=OJe.length;function i7t(s){if(!s)return;if(!s.isControllingVariants){const n=s.parent?i7t(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})=>yIs(s,n,r)))}function w8s(s){let t=_8s(s),n=zft(),r=!0,a=!1;const i=d=>(u,h)=>{var p;const m=x7(s,h,d==="exit"?(p=s.presenceContext)==null?void 0:p.custom:void 0);if(m){const{transition:f,transitionEnd:y,...v}=m;u={...u,...v,...y}}return u};function l(d){t=d(s)}function o(d){const{props:u}=s,h=i7t(s.parent)||{},m=[],p=new Set;let f={},y=1/0;for(let g=0;gy&&C,D=!1;const O=Array.isArray(S)?S:[S];let V=O.reduce(i(b),{});E===!1&&(V={});const{prevResolvedValues:G={}}=j,$={...G,...V},H=ne=>{I=!0,p.has(ne)&&(D=!0,p.delete(ne)),j.needsAnimating[ne]=!0;const ce=s.getValue(ne);ce&&(ce.liveStyle=!1)};for(const ne in $){const ce=V[ne],ie=G[ne];if(f.hasOwnProperty(ne))continue;let te=!1;oVe(ce)&&oVe(ie)?te=!o7t(ce,ie):te=ce!==ie,te?ce!=null?H(ne):p.add(ne):ce!==void 0&&p.has(ne)?H(ne):j.protectedKeys[ne]=!0}j.prevProp=S,j.prevResolvedValues=V,j.isActive&&(f={...f,...V}),(r||a)&&s.blockInitialAnimation&&(I=!1);const Y=P&&M;I&&(!Y||D)&&m.push(...O.map(ne=>{const ce={type:b};if(typeof ne=="string"&&(r||a)&&!Y&&s.manuallyAnimateOnMount&&s.parent){const{parent:ie}=s,te=x7(ie,ne);if(ie.enteringChildren&&te){const{delayChildren:ae}=te.transition||{};ce.delay=TOt(ie.enteringChildren,s,ae)}}return{animation:ne,options:ce}}))}if(p.size){const g={};if(typeof u.initial!="boolean"){const b=x7(s,Array.isArray(u.initial)?u.initial[0]:u.initial);b&&b.transition&&(g.transition=b.transition)}p.forEach(b=>{const j=s.getBaseTarget(b),S=s.getValue(b);S&&(S.liveStyle=!0),g[b]=j??null}),m.push({animation:g})}let v=!!m.length;return r&&(u.initial===!1||u.initial===u.animate)&&!s.manuallyAnimateOnMount&&(v=!1),r=!1,a=!1,v?t(m):Promise.resolve()}function c(d,u){var m;if(n[d].isActive===u)return Promise.resolve();(m=s.variantChildren)==null||m.forEach(p=>{var f;return(f=p.animationState)==null?void 0:f.setActive(d,u)}),n[d].isActive=u;const h=o(d);for(const p in n)n[p].protectedKeys={};return h}return{animateChanges:o,setActive:c,setAnimateFunction:l,getState:()=>n,reset:()=>{n=zft(),a=!0}}}function j8s(s,t){return typeof t=="string"?t!==s:Array.isArray(t)?!o7t(t,s):!1}function vI(s=!1){return{isActive:s,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function zft(){return{animate:vI(!0),whileInView:vI(),whileHover:vI(),whileTap:vI(),whileDrag:vI(),whileFocus:vI(),exit:vI()}}function xVe(s,t){s.min=t.min,s.max=t.max}function fk(s,t){xVe(s.x,t.x),xVe(s.y,t.y)}function Bft(s,t){s.translate=t.translate,s.scale=t.scale,s.originPoint=t.originPoint,s.origin=t.origin}const l7t=1e-4,N8s=1-l7t,k8s=1+l7t,c7t=.01,S8s=0-c7t,C8s=0+c7t;function mb(s){return s.max-s.min}function A8s(s,t,n){return Math.abs(s-t)<=n}function Uft(s,t,n,r=.5){s.origin=r,s.originPoint=Np(t.min,t.max,s.origin),s.scale=mb(n)/mb(t),s.translate=Np(n.min,n.max,s.origin)-s.originPoint,(s.scale>=N8s&&s.scale<=k8s||isNaN(s.scale))&&(s.scale=1),(s.translate>=S8s&&s.translate<=C8s||isNaN(s.translate))&&(s.translate=0)}function NJ(s,t,n,r){Uft(s.x,t.x,n.x,r?r.originX:void 0),Uft(s.y,t.y,n.y,r?r.originY:void 0)}function qft(s,t,n,r=0){const a=r?Np(n.min,n.max,r):n.min;s.min=a+t.min,s.max=s.min+mb(t)}function E8s(s,t,n,r){qft(s.x,t.x,n.x,r==null?void 0:r.x),qft(s.y,t.y,n.y,r==null?void 0:r.y)}function $ft(s,t,n,r=0){const a=r?Np(n.min,n.max,r):n.min;s.min=t.min-a,s.max=s.min+mb(t)}function _Ae(s,t,n,r){$ft(s.x,t.x,n.x,r==null?void 0:r.x),$ft(s.y,t.y,n.y,r==null?void 0:r.y)}function Vft(s,t,n,r,a){return s-=t,s=bAe(s,1/n,r),a!==void 0&&(s=bAe(s,1/a,r)),s}function T8s(s,t=0,n=1,r=.5,a,i=s,l=s){if(Q4.test(t)&&(t=parseFloat(t),t=Np(l.min,l.max,t/100)-l.min),typeof t!="number")return;let o=Np(i.min,i.max,r);s===i&&(o-=t),s.min=Vft(s.min,t,n,o,a),s.max=Vft(s.max,t,n,o,a)}function Hft(s,t,[n,r,a],i,l){T8s(s,t[n],t[r],t[a],t.scale,i,l)}const M8s=["x","scaleX","originX"],P8s=["y","scaleY","originY"];function Gft(s,t,n,r){Hft(s.x,t,M8s,n?n.x:void 0,r?r.x:void 0),Hft(s.y,t,P8s,n?n.y:void 0,r?r.y:void 0)}function Wft(s){return s.translate===0&&s.scale===1}function d7t(s){return Wft(s.x)&&Wft(s.y)}function Kft(s,t){return s.min===t.min&&s.max===t.max}function L8s(s,t){return Kft(s.x,t.x)&&Kft(s.y,t.y)}function Yft(s,t){return Math.round(s.min)===Math.round(t.min)&&Math.round(s.max)===Math.round(t.max)}function u7t(s,t){return Yft(s.x,t.x)&&Yft(s.y,t.y)}function Zft(s){return mb(s.x)/mb(s.y)}function Xft(s,t){return s.translate===t.translate&&s.scale===t.scale&&s.originPoint===t.originPoint}function B5(s){return[s("x"),s("y")]}function I8s(s,t,n){let r="";const a=s.x.translate/t.x,i=s.y.translate/t.y,l=(n==null?void 0:n.z)||0;if((a||i||l)&&(r=`translate3d(${a}px, ${i}px, ${l}px) `),(t.x!==1||t.y!==1)&&(r+=`scale(${1/t.x}, ${1/t.y}) `),n){const{transformPerspective:d,rotate:u,rotateX:h,rotateY:m,skewX:p,skewY:f}=n;d&&(r=`perspective(${d}px) ${r}`),u&&(r+=`rotate(${u}deg) `),h&&(r+=`rotateX(${h}deg) `),m&&(r+=`rotateY(${m}deg) `),p&&(r+=`skewX(${p}deg) `),f&&(r+=`skewY(${f}deg) `)}const o=s.x.scale*t.x,c=s.y.scale*t.y;return(o!==1||c!==1)&&(r+=`scale(${o}, ${c})`),r||"none"}const h7t=["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"],D8s=h7t.length,Qft=s=>typeof s=="string"?parseFloat(s):s,Jft=s=>typeof s=="number"||wo.test(s);function R8s(s,t,n,r,a,i){a?(s.opacity=Np(0,n.opacity??1,F8s(r)),s.opacityExit=Np(t.opacity??1,0,O8s(r))):i&&(s.opacity=Np(t.opacity??1,n.opacity??1,r));for(let l=0;lrt?1:n(ate(s,t,r))}function z8s(s,t,n){const r=fv(s)?s:LH(s);return r.start(EJe("",r,t,n)),r.animation}function lte(s,t,n,r={passive:!0}){return s.addEventListener(t,n,r),()=>s.removeEventListener(t,n)}const B8s=(s,t)=>s.depth-t.depth;class U8s{constructor(){this.children=[],this.isDirty=!1}add(t){gJe(this.children,t),this.isDirty=!0}remove(t){pAe(this.children,t),this.isDirty=!0}forEach(t){this.isDirty&&this.children.sort(B8s),this.isDirty=!1,this.children.forEach(t)}}function q8s(s,t){const n=hb.now(),r=({timestamp:a})=>{const i=a-n;i>=t&&(FP(r),s(i-t))};return Mm.setup(r,!0),()=>FP(r)}function M4e(s){return fv(s)?s.get():s}class $8s{constructor(){this.members=[]}add(t){gJe(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&&(pAe(this.members,r),r.unmount())}t.scheduleRender()}remove(t){if(pAe(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 P4e={hasAnimatedSinceResize:!0,hasEverUpdated:!1},POe=["","X","Y","Z"],V8s=1e3;let H8s=0;function LOe(s,t,n,r){const{latestValues:a}=t;a[s]&&(n[s]=a[s],t.setStaticValue(s,0),r&&(r[s]=0))}function p7t(s){if(s.hasCheckedOptimisedAppear=!0,s.root===s)return;const{visualElement:t}=s.options;if(!t)return;const n=DOt(t);if(window.MotionHasOptimisedAnimation(n,"transform")){const{layout:a,layoutId:i}=s.options;window.MotionCancelOptimisedAnimation(n,"transform",Mm,!(a||i))}const{parent:r}=s;r&&!r.hasCheckedOptimisedAppear&&p7t(r)}function f7t({attachResizeListener:s,defaultParent:t,measureScroll:n,checkIsScrollRoot:r,resetTransform:a}){return class{constructor(l={},o=t==null?void 0:t()){this.id=H8s++,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(K8s),this.nodes.forEach(eDs),this.nodes.forEach(tDs),this.nodes.forEach(Y8s)},this.resolvedRelativeTargetAt=0,this.linkedParentVersion=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=l,this.root=o?o.root||o:this,this.path=o?[...o.path,o]:[],this.parent=o,this.depth=o?o.depth+1:0;for(let c=0;cthis.root.updateBlockedByResize=!1;Mm.read(()=>{h=window.innerWidth}),s(l,()=>{const p=window.innerWidth;p!==h&&(h=p,this.root.updateBlockedByResize=!0,u&&u(),u=q8s(m,250),P4e.hasAnimatedSinceResize&&(P4e.hasAnimatedSinceResize=!1,this.nodes.forEach(nxt)))})}o&&this.root.registerSharedNode(o,this),this.options.animate!==!1&&d&&(o||c)&&this.addEventListener("didUpdate",({delta:u,hasLayoutChanged:h,hasRelativeLayoutChanged:m,layout:p})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const f=this.options.transition||d.getDefaultTransition()||iDs,{onLayoutAnimationStart:y,onLayoutAnimationComplete:v}=d.getProps(),g=!this.targetLayout||!u7t(this.targetLayout,p),b=!h&&m;if(this.options.layoutRoot||this.resumeFrom||b||h&&(g||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const j={...AJe(f,"layout"),onPlay:y,onComplete:v};(d.shouldReduceMotion||this.options.layoutRoot)&&(j.delay=0,j.type=!1),this.startAnimation(j),this.setAnimationOrigin(u,b)}else h||nxt(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(),FP(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(sDs),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&&p7t(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&&!mb(this.snapshot.measuredBox.x)&&!mb(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 C=S/1e3;rxt(h.x,l.x,C),rxt(h.y,l.y,C),this.setTargetDelta(h),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(_Ae(m,this.layout.layoutBox,this.relativeParent.layout.layoutBox,this.options.layoutAnchor||void 0),rDs(this.relativeTarget,this.relativeTargetOrigin,m,C),j&&L8s(this.relativeTarget,j)&&(this.isProjectionDirty=!1),j||(j=l0()),fk(j,this.relativeTarget)),y&&(this.animationValues=u,R8s(u,d,this.latestValues,C,b,g)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=C},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&&(FP(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=Mm.update(()=>{P4e.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=LH(0)),this.motionValue.jump(0,!1),this.currentAnimation=z8s(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(V8s),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&&x7t(this.options.animationType,this.layout.layoutBox,d.layoutBox)){c=this.target||l0();const h=mb(this.layout.layoutBox.x);c.x.min=l.target.x.min,c.x.max=c.x.min+h;const m=mb(this.layout.layoutBox.y);c.y.min=l.target.y.min,c.y.max=c.y.min+m}fk(o,c),T4e(o,u),NJ(this.projectionDeltaWithTransform,this.layoutCorrected,o,u)}}registerSharedNode(l,o){this.sharedNodes.has(l)||this.sharedNodes.set(l,new $8s),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&&LOe("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(txt),this.root.sharedNodes.clear()}}}function G8s(s){s.updateLayout()}function W8s(s){var n;const t=((n=s.resumeFrom)==null?void 0:n.snapshot)||s.snapshot;if(s.isLead()&&s.layout&&t&&s.hasListeners("didUpdate")){const{layoutBox:r,measuredBox:a}=s.layout,{animationType:i}=s.options,l=t.source!==s.layout.source;if(i==="size")B5(h=>{const m=l?t.measuredBox[h]:t.layoutBox[h],p=mb(m);m.min=r[h].min,m.max=m.min+p});else if(i==="x"||i==="y"){const h=i==="x"?"y":"x";xVe(l?t.measuredBox[h]:t.layoutBox[h],r[h])}else x7t(i,t.layoutBox,r)&&B5(h=>{const m=l?t.measuredBox[h]:t.layoutBox[h],p=mb(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=QU();NJ(o,r,t.layoutBox);const c=QU();l?NJ(c,s.applyTransform(a,!0),t.measuredBox):NJ(c,r,t.layoutBox);const d=!d7t(o);let u=!1;if(!s.resumeFrom){const h=s.getClosestProjectingParent();if(h&&!h.resumeFrom){const{snapshot:m,layout:p}=h;if(m&&p){const f=s.options.layoutAnchor||void 0,y=l0();_Ae(y,t.layoutBox,m.layoutBox,f);const v=l0();_Ae(v,r,p.layoutBox,f),u7t(y,v)||(u=!0),h.options.layoutRoot&&(s.relativeTarget=v,s.relativeTargetOrigin=y,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 K8s(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 Y8s(s){s.isProjectionDirty=s.isSharedProjectionDirty=s.isTransformDirty=!1}function Z8s(s){s.clearSnapshot()}function txt(s){s.clearMeasurements()}function X8s(s){s.isLayoutDirty=!0,s.updateLayout()}function sxt(s){s.isLayoutDirty=!1}function Q8s(s){s.isAnimationBlocked&&s.layout&&!s.isLayoutDirty&&(s.snapshot=s.layout,s.isLayoutDirty=!0)}function J8s(s){const{visualElement:t}=s.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify("BeforeLayoutMeasure"),s.resetTransform()}function nxt(s){s.finishAnimation(),s.targetDelta=s.relativeTarget=s.target=void 0,s.isProjectionDirty=!0}function eDs(s){s.resolveTargetDelta()}function tDs(s){s.calcProjection()}function sDs(s){s.resetSkewAndRotation()}function nDs(s){s.removeLeadSnapshot()}function rxt(s,t,n){s.translate=Np(t.translate,0,n),s.scale=Np(t.scale,1,n),s.origin=t.origin,s.originPoint=t.originPoint}function axt(s,t,n,r){s.min=Np(t.min,n.min,r),s.max=Np(t.max,n.max,r)}function rDs(s,t,n,r){axt(s.x,t.x,n.x,r),axt(s.y,t.y,n.y,r)}function aDs(s){return s.animationValues&&s.animationValues.opacityExit!==void 0}const iDs={duration:.45,ease:[.4,0,.1,1]},ixt=s=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(s),oxt=ixt("applewebkit/")&&!ixt("chrome/")?Math.round:gN;function lxt(s){s.min=oxt(s.min),s.max=oxt(s.max)}function oDs(s){lxt(s.x),lxt(s.y)}function x7t(s,t,n){return s==="position"||s==="preserve-aspect"&&!A8s(Zft(t),Zft(n),.2)}function lDs(s){var t;return s!==s.root&&((t=s.scroll)==null?void 0:t.wasRoot)}const cDs=f7t({attachResizeListener:(s,t)=>lte(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}),IOe={current:void 0},g7t=f7t({measureScroll:s=>({x:s.scrollLeft,y:s.scrollTop}),defaultParent:()=>{if(!IOe.current){const s=new cDs({});s.mount(window),s.setOptions({layoutScroll:!0}),IOe.current=s}return IOe.current},resetTransform:(s,t)=>{s.style.transform=t!==void 0?t:"none"},checkIsScrollRoot:s=>window.getComputedStyle(s).position==="fixed"}),UJe=_.createContext({transformPagePoint:s=>s,isStatic:!1,reducedMotion:"never"});function cxt(s,t){if(typeof s=="function")return s(t);s!=null&&(s.current=t)}function dDs(...s){return t=>{let n=!1;const r=s.map(a=>{const i=cxt(a,t);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let a=0;a{const{width:p,height:f,top:y,left:v,right:g,bottom:b}=c.current;if(t||i===!1||!o.current||!p||!f)return;const j=n==="left"?`left: ${v}`:`right: ${g}`,S=r==="bottom"?`bottom: ${b}`:`top: ${y}`;o.current.dataset.motionPopId=l;const C=document.createElement("style");d&&(C.nonce=d);const E=a??document.head;return E.appendChild(C),C.sheet&&C.sheet.insertRule(` [data-motion-pop-id="${l}"] { position: absolute !important; width: ${p}px !important; height: ${f}px !important; ${j}px !important; ${S}px !important; } `),()=>{var P;(P=o.current)==null||P.removeAttribute("data-motion-pop-id"),E.contains(C)&&E.removeChild(C)}},[t]),e.jsx(hDs,{isPresent:t,childRef:o,sizeRef:c,pop:i,children:i===!1?s:_.cloneElement(s,{ref:h})})}const pDs=({children:s,initial:t,isPresent:n,onExitComplete:r,custom:a,presenceAffectsLayout:i,mode:l,anchorX:o,anchorY:c,root:d})=>{const u=xJe(fDs),h=_.useId();let m=!0,p=_.useMemo(()=>(m=!1,{id:h,initial:t,isPresent:n,custom:a,onExitComplete:f=>{u.set(f,!0);for(const y of u.values())if(!y)return;r&&r()},register:f=>(u.set(f,!1),()=>u.delete(f))}),[n,u,r]);return i&&m&&(p={...p}),_.useMemo(()=>{u.forEach((f,y)=>u.set(y,!1))},[n]),_.useEffect(()=>{!n&&!u.size&&r&&r()},[n]),s=e.jsx(mDs,{pop:l==="popLayout",isPresent:n,anchorX:o,anchorY:c,root:d,children:s}),e.jsx(IPe.Provider,{value:p,children:s})};function fDs(){return new Map}function y7t(s=!0){const t=_.useContext(IPe);if(t===null)return[!0,null];const{isPresent:n,onExitComplete:r,register:a}=t,i=_.useId();_.useEffect(()=>{if(s)return a(i)},[s]);const l=_.useCallback(()=>s&&r&&r(i),[i,r,s]);return!n&&r?[!1,l]:[!0]}const vle=s=>s.key||"";function dxt(s){const t=[];return _.Children.forEach(s,n=>{_.isValidElement(n)&&t.push(n)}),t}const mW=({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]=y7t(l),m=_.useMemo(()=>dxt(s),[s]),p=l&&!u?[]:m.map(vle),f=_.useRef(!0),y=_.useRef(m),v=xJe(()=>new Map),g=_.useRef(new Set),[b,j]=_.useState(m),[S,C]=_.useState(m);GFt(()=>{f.current=!1,y.current=m;for(let M=0;M{const I=vle(M),D=l&&!u?!1:m===S||p.includes(I),O=()=>{if(g.current.has(I))return;if(v.has(I))g.current.add(I),v.set(I,!0);else return;let V=!0;v.forEach(G=>{G||(V=!1)}),V&&(P==null||P(),C(y.current),l&&(h==null||h()),r&&r())};return e.jsx(pDs,{isPresent:D,initial:!f.current||n?void 0:!1,custom:t,presenceAffectsLayout:a,mode:i,root:d,onExitComplete:D?void 0:O,anchorX:o,anchorY:c,children:M},I)})})},v7t=_.createContext({strict:!1}),uxt={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 hxt=!1;function xDs(){if(hxt)return;const s={};for(const t in uxt)s[t]={isEnabled:n=>uxt[t].some(r=>!!n[r])};KOt(s),hxt=!0}function b7t(){return xDs(),e8s()}function gDs(s){const t=b7t();for(const n in s)t[n]={...t[n],...s[n]};KOt(t)}const yDs=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 wAe(s){return s.startsWith("while")||s.startsWith("drag")&&s!=="draggable"||s.startsWith("layout")||s.startsWith("onTap")||s.startsWith("onPan")||s.startsWith("onLayout")||yDs.has(s)}let _7t=s=>!wAe(s);function vDs(s){typeof s=="function"&&(_7t=t=>t.startsWith("on")?!wAe(t):s(t))}try{vDs(require("@emotion/is-prop-valid").default)}catch{}function bDs(s,t,n){const r={};for(const a in s)a==="values"&&typeof s.values=="object"||fv(s[a])||(_7t(a)||n===!0&&wAe(a)||!t&&!wAe(a)||s.draggable&&a.startsWith("onDrag"))&&(r[a]=s[a]);return r}const zPe=_.createContext({});function _Ds(s,t){if(OPe(s)){const{initial:n,animate:r}=s;return{initial:n===!1||ote(n)?n:void 0,animate:ote(r)?r:void 0}}return s.inherit!==!1?t:{}}function wDs(s){const{initial:t,animate:n}=_Ds(s,_.useContext(zPe));return _.useMemo(()=>({initial:t,animate:n}),[mxt(t),mxt(n)])}function mxt(s){return Array.isArray(s)?s.join(" "):s}const qJe=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function w7t(s,t,n){for(const r in t)!fv(t[r])&&!t7t(r,n)&&(s[r]=t[r])}function jDs({transformTemplate:s},t){return _.useMemo(()=>{const n=qJe();return zJe(n,t,s),Object.assign({},n.vars,n.style)},[t])}function NDs(s,t){const n=s.style||{},r={};return w7t(r,n,s),Object.assign(r,jDs(s,t)),r}function kDs(s,t){const n={},r=NDs(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 j7t=()=>({...qJe(),attrs:{}});function SDs(s,t,n,r){const a=_.useMemo(()=>{const i=j7t();return s7t(i,t,r7t(r),s.transformTemplate,s.style),{...i.attrs,style:{...i.style}}},[t]);if(s.style){const i={};w7t(i,s.style,s),a.style={...i,...a.style}}return a}const CDs=["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 $Je(s){return typeof s!="string"||s.includes("-")?!1:!!(CDs.indexOf(s)>-1||/[A-Z]/u.test(s))}function ADs(s,t,n,{latestValues:r},a,i=!1,l){const c=(l??$Je(s)?SDs:kDs)(t,r,a,s),d=bDs(t,typeof s=="string",i),u=s!==_.Fragment?{...d,...c,ref:n}:{},{children:h}=t,m=_.useMemo(()=>fv(h)?h.get():h,[h]);return _.createElement(s,{...u,children:m})}function EDs({scrapeMotionValuesFromProps:s,createRenderState:t},n,r,a){return{latestValues:TDs(n,r,a,s),renderState:t()}}function TDs(s,t,n,r){const a={},i=r(s,{});for(const m in i)a[m]=M4e(i[m]);let{initial:l,animate:o}=s;const c=OPe(s),d=GOt(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"&&!FPe(h)){const m=Array.isArray(h)?h:[h];for(let p=0;p(t,n)=>{const r=_.useContext(zPe),a=_.useContext(IPe),i=()=>EDs(s,t,r,a);return n?i():xJe(i)},MDs=N7t({scrapeMotionValuesFromProps:BJe,createRenderState:qJe}),PDs=N7t({scrapeMotionValuesFromProps:a7t,createRenderState:j7t}),LDs=Symbol.for("motionComponentSymbol");function IDs(s,t,n){const r=_.useRef(n);_.useInsertionEffect(()=>{r.current=n});const a=_.useRef(null);return _.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 k7t=_.createContext({});function gU(s){return s&&typeof s=="object"&&Object.prototype.hasOwnProperty.call(s,"current")}function DDs(s,t,n,r,a,i){var j,S;const{visualElement:l}=_.useContext(zPe),o=_.useContext(v7t),c=_.useContext(IPe),d=_.useContext(UJe),u=d.reducedMotion,h=d.skipAnimations,m=_.useRef(null),p=_.useRef(!1);r=r||o.renderer,!m.current&&r&&(m.current=r(s,{visualState:t,parent:l,props:n,presenceContext:c,blockInitialAnimation:c?c.initial===!1:!1,reducedMotionConfig:u,skipAnimations:h,isSVG:i}),p.current&&m.current&&(m.current.manuallyAnimateOnMount=!0));const f=m.current,y=_.useContext(k7t);f&&!f.projection&&a&&(f.type==="html"||f.type==="svg")&&RDs(m.current,n,a,y);const v=_.useRef(!1);_.useInsertionEffect(()=>{f&&v.current&&f.update(n,c)});const g=n[IOt],b=_.useRef(!!g&&typeof window<"u"&&!((j=window.MotionHandoffIsComplete)!=null&&j.call(window,g))&&((S=window.MotionHasOptimisedAnimation)==null?void 0:S.call(window,g)));return GFt(()=>{p.current=!0,f&&(v.current=!0,window.MotionIsMounted=!0,f.updateFeatures(),f.scheduleRenderMicrotask(),b.current&&f.animationState&&f.animationState.animateChanges())}),_.useEffect(()=>{f&&(!b.current&&f.animationState&&f.animationState.animateChanges(),b.current&&(queueMicrotask(()=>{var C;(C=window.MotionHandoffMarkAsComplete)==null||C.call(window,g)}),b.current=!1),f.enteringChildren=void 0)}),f}function RDs(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:S7t(s.parent)),s.projection.setOptions({layoutId:a,layout:i,alwaysMeasureLayout:!!l||o&&gU(o),visualElement:s,animationType:typeof i=="string"?i:"both",initialPromotionConfig:r,crossfade:h,layoutScroll:c,layoutRoot:d,layoutAnchor:u})}function S7t(s){if(s)return s.options.allowProjection!==!1?s.projection:S7t(s.parent)}function DOe(s,{forwardMotionProps:t=!1,type:n}={},r,a){r&&gDs(r);const i=n?n==="svg":$Je(s),l=i?PDs:MDs;function o(d,u){let h;const m={..._.useContext(UJe),...d,layoutId:FDs(d)},{isStatic:p}=m,f=wDs(d),y=l(d,p);if(!p&&typeof window<"u"){ODs();const v=zDs(m);h=v.MeasureLayout,f.visualElement=DDs(s,y,m,a,v.ProjectionNode,i)}return e.jsxs(zPe.Provider,{value:f,children:[h&&f.visualElement?e.jsx(h,{visualElement:f.visualElement,...m}):null,ADs(s,d,IDs(y,f.visualElement,u),y,p,t,i)]})}o.displayName=`motion.${typeof s=="string"?s:`create(${s.displayName??s.name??""})`}`;const c=_.forwardRef(o);return c[LDs]=s,c}function FDs({layoutId:s}){const t=_.useContext(fJe).id;return t&&s!==void 0?t+"-"+s:s}function ODs(s,t){_.useContext(v7t).strict}function zDs(s){const t=b7t(),{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 BDs(s,t){if(typeof Proxy>"u")return DOe;const n=new Map,r=(i,l)=>DOe(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,DOe(l,void 0,s,t)),n.get(l))})}const UDs=(s,t)=>t.isSVG??$Je(s)?new g8s(t):new u8s(t,{allowProjection:s!==_.Fragment});class qDs extends mL{constructor(t){super(t),t.animationState||(t.animationState=w8s(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();FPe(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 $Ds=0;class VDs extends mL{constructor(){super(...arguments),this.id=$Ds++,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=x7(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 HDs={animation:{Feature:qDs},exit:{Feature:VDs}};function Xre(s){return{point:{x:s.pageX,y:s.pageY}}}const GDs=s=>t=>DJe(t)&&s(t,Xre(t));function kJ(s,t,n,r){return lte(s,t,GDs(n),r)}const C7t=({current:s})=>s?s.ownerDocument.defaultView:null,pxt=(s,t)=>Math.abs(s-t);function WDs(s,t){const n=pxt(s.x,t.x),r=pxt(s.y,t.y);return Math.sqrt(n**2+r**2)}const fxt=new Set(["auto","scroll"]);class A7t{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=ble(this.lastRawMoveEventInfo,this.transformPagePoint));const p=ROe(this.lastMoveEventInfo,this.history),f=this.startEvent!==null,y=WDs(p.offset,{x:0,y:0})>=this.distanceThreshold;if(!f&&!y)return;const{point:v}=p,{timestamp:g}=iv;this.history.push({...v,timestamp:g});const{onStart:b,onMove:j}=this.handlers;f||(b&&b(this.lastMoveEvent,p),this.startEvent=this.lastMoveEvent),j&&j(this.lastMoveEvent,p)},this.handlePointerMove=(p,f)=>{this.lastMoveEvent=p,this.lastRawMoveEventInfo=f,this.lastMoveEventInfo=ble(f,this.transformPagePoint),Mm.update(this.updatePoint,!0)},this.handlePointerUp=(p,f)=>{this.end();const{onEnd:y,onSessionEnd:v,resumeAnimation:g}=this.handlers;if((this.dragSnapToOrigin||!this.startEvent)&&g&&g(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const b=ROe(p.type==="pointercancel"?this.lastMoveEventInfo:ble(f,this.transformPagePoint),this.history);this.startEvent&&y&&y(p,b),v&&v(p,b)},!DJe(t))return;this.dragSnapToOrigin=i,this.handlers=n,this.transformPagePoint=r,this.distanceThreshold=l,this.contextWindow=a||window;const c=Xre(t),d=ble(c,this.transformPagePoint),{point:u}=d,{timestamp:h}=iv;this.history=[{...u,timestamp:h}];const{onSessionStart:m}=n;m&&m(t,ROe(d,this.history)),this.removeListeners=Kre(kJ(this.contextWindow,"pointermove",this.handlePointerMove),kJ(this.contextWindow,"pointerup",this.handlePointerUp),kJ(this.contextWindow,"pointercancel",this.handlePointerUp)),o&&this.startScrollTracking(o)}startScrollTracking(t){let n=t.parentElement;for(;n;){const r=getComputedStyle(n);(fxt.has(r.overflowX)||fxt.has(r.overflowY))&&this.scrollPositions.set(n,{x:n.scrollLeft,y:n.scrollTop}),n=n.parentElement}this.scrollPositions.set(window,{x:window.scrollX,y:window.scrollY}),window.addEventListener("scroll",this.onElementScroll,{capture:!0}),window.addEventListener("scroll",this.onWindowScroll),this.removeScrollListeners=()=>{window.removeEventListener("scroll",this.onElementScroll,{capture:!0}),window.removeEventListener("scroll",this.onWindowScroll)}}handleScroll(t){const n=this.scrollPositions.get(t);if(!n)return;const r=t===window,a=r?{x:window.scrollX,y:window.scrollY}:{x:t.scrollLeft,y:t.scrollTop},i={x:a.x-n.x,y:a.y-n.y};i.x===0&&i.y===0||(r?this.lastMoveEventInfo&&(this.lastMoveEventInfo.point.x+=i.x,this.lastMoveEventInfo.point.y+=i.y):this.history.length>0&&(this.history[0].x-=i.x,this.history[0].y-=i.y),this.scrollPositions.set(t,a),Mm.update(this.updatePoint,!0))}updateHandlers(t){this.handlers=t}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),FP(this.updatePoint)}}function ble(s,t){return t?{point:t(s.point)}:s}function xxt(s,t){return{x:s.x-t.x,y:s.y-t.y}}function ROe({point:s},t){return{point:s,delta:xxt(s,E7t(t)),offset:xxt(s,KDs(t)),velocity:YDs(t,.1)}}function KDs(s){return s[0]}function E7t(s){return s[s.length-1]}function YDs(s,t){if(s.length<2)return{x:0,y:0};let n=s.length-1,r=null;const a=E7t(s);for(;n>=0&&(r=s[n],!(a.timestamp-r.timestamp>O_(t)));)n--;if(!r)return{x:0,y:0};r===s[0]&&s.length>2&&a.timestamp-r.timestamp>O_(t)*2&&(r=s[1]);const i=nN(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 ZDs(s,{min:t,max:n},r){return t!==void 0&&sn&&(s=r?Np(n,s,r.max):Math.min(s,n)),s}function gxt(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 XDs(s,{top:t,left:n,bottom:r,right:a}){return{x:gxt(s.x,n,a),y:gxt(s.y,t,r)}}function yxt(s,t){let n=t.min-s.min,r=t.max-s.max;return t.max-t.minr?n=ate(t.min,t.max-r,s.min):r>a&&(n=ate(s.min,s.max-a,t.min)),lC(0,1,n)}function eRs(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 gVe=.35;function tRs(s=gVe){return s===!1?s=0:s===!0&&(s=gVe),{x:vxt(s,"left","right"),y:vxt(s,"top","bottom")}}function vxt(s,t,n){return{min:bxt(s,t),max:bxt(s,n)}}function bxt(s,t){return typeof s=="number"?s:s[t]||0}const sRs=new WeakMap;class nRs{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=l0(),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(Xre(h).point),this.stopAnimation()},l=(h,m)=>{const{drag:p,dragPropagation:f,onDragStart:y}=this.getProps();if(p&&!f&&(this.openDragLock&&this.openDragLock(),this.openDragLock=TIs(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),B5(g=>{let b=this.getAxisMotionValue(g).get()||0;if(Q4.test(b)){const{projection:j}=this.visualElement;if(j&&j.layout){const S=j.layout.layoutBox[g];S&&(b=mb(S)*(parseFloat(b)/100))}}this.originPoint[g]=b}),y&&Mm.update(()=>y(h,m),!1,!0),lVe(this.visualElement,"transform");const{animationState:v}=this.visualElement;v&&v.setActive("whileDrag",!0)},o=(h,m)=>{this.latestPointerEvent=h,this.latestPanInfo=m;const{dragPropagation:p,dragDirectionLock:f,onDirectionLock:y,onDrag:v}=this.getProps();if(!p&&!this.openDragLock)return;const{offset:g}=m;if(f&&this.currentDirection===null){this.currentDirection=aRs(g),this.currentDirection!==null&&y&&y(this.currentDirection);return}this.updateAxis("x",m.point,g),this.updateAxis("y",m.point,g),this.visualElement.render(),v&&Mm.update(()=>v(h,m),!1,!0)},c=(h,m)=>{this.latestPointerEvent=h,this.latestPanInfo=m,this.stop(h,m),this.latestPointerEvent=null,this.latestPanInfo=null},d=()=>{const{dragSnapToOrigin:h}=this.getProps();(h||this.constraints)&&this.startAnimation({x:0,y:0})},{dragSnapToOrigin:u}=this.getProps();this.panSession=new A7t(t,{onSessionStart:i,onStart:l,onMove:o,onSessionEnd:c,resumeAnimation:d},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:u,distanceThreshold:r,contextWindow:C7t(this.visualElement),element:this.visualElement.current})}stop(t,n){const r=t||this.latestPointerEvent,a=n||this.latestPanInfo,i=this.isDragging;if(this.cancel(),!i||!a||!r)return;const{velocity:l}=a;this.startAnimation(l);const{onDragEnd:o}=this.getProps();o&&Mm.postRender(()=>o(r,a))}cancel(){this.isDragging=!1;const{projection:t,animationState:n}=this.visualElement;t&&(t.isAnimationBlocked=!1),this.endPanSession();const{dragPropagation:r}=this.getProps();!r&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),n&&n.setActive("whileDrag",!1)}endPanSession(){this.panSession&&this.panSession.end(),this.panSession=void 0}updateAxis(t,n,r){const{drag:a}=this.getProps();if(!r||!_le(t,a,this.currentDirection))return;const i=this.getAxisMotionValue(t);let l=this.originPoint[t]+r[t];this.constraints&&this.constraints[t]&&(l=ZDs(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&&gU(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):t&&r?this.constraints=XDs(r.layoutBox,t):this.constraints=!1,this.elastic=tRs(n),a!==this.constraints&&!gU(t)&&r&&this.constraints&&!this.hasMutatedConstraints&&B5(l=>{this.constraints!==!1&&this.getAxisMotionValue(l)&&(this.constraints[l]=eRs(r.layoutBox[l],this.constraints[l]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:n}=this.getProps();if(!t||!gU(t))return!1;const r=t.current;MH(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=a8s(r,a.root,this.visualElement.getTransformPagePoint());let l=QDs(a.layout.layoutBox,i);if(n){const o=n(s8s(l));this.hasMutatedConstraints=!!o,o&&(l=ZOt(o))}return l}startAnimation(t){const{drag:n,dragMomentum:r,dragElastic:a,dragTransition:i,dragSnapToOrigin:l,onDragTransitionEnd:o}=this.getProps(),c=this.constraints||{},d=B5(u=>{if(!_le(u,n,this.currentDirection))return;let h=c&&c[u]||{};(l===!0||l===u)&&(h={min:0,max:0});const m=a?200:1e6,p=a?40:1e7,f={type:"inertia",velocity:r?t[u]:0,bounceStiffness:m,bounceDamping:p,timeConstant:750,restDelta:1,restSpeed:10,...i,...h};return this.startAxisValueAnimation(u,f)});return Promise.all(d).then(o)}startAxisValueAnimation(t,n){const r=this.getAxisMotionValue(t);return lVe(this.visualElement,t),r.start(EJe(t,r,0,n,this.visualElement,!1))}stopAnimation(){B5(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){B5(n=>{const{drag:r}=this.getProps();if(!_le(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]-Np(l,o,.5)+c)}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:t,dragConstraints:n}=this.getProps(),{projection:r}=this.visualElement;if(!gU(n)||!r||!this.constraints)return;this.stopAnimation();const a={x:0,y:0};B5(l=>{const o=this.getAxisMotionValue(l);if(o&&this.constraints!==!1){const c=o.get();a[l]=JDs({min:c,max:c},this.constraints[l])}});const{transformTemplate:i}=this.visualElement.getProps();this.visualElement.current.style.transform=i?i({},""):"none",r.root&&r.root.updateScroll(),r.updateLayout(),this.constraints=!1,this.resolveConstraints(),B5(l=>{if(!_le(l,t,null))return;const o=this.getAxisMotionValue(l),{min:c,max:d}=this.constraints[l];o.set(Np(c,d,a[l]))}),this.visualElement.render()}addListeners(){if(!this.visualElement.current)return;sRs.set(this.visualElement,this);const t=this.visualElement.current,n=kJ(t,"pointerdown",d=>{const{drag:u,dragListener:h=!0}=this.getProps(),m=d.target,p=m!==t&&RIs(m);u&&h&&!p&&this.start(d)});let r;const a=()=>{const{dragConstraints:d}=this.getProps();gU(d)&&d.current&&(this.constraints=this.resolveRefConstraints(),r||(r=rRs(t,d.current,()=>this.scalePositionWithinConstraints())))},{projection:i}=this.visualElement,l=i.addEventListener("measure",a);i&&!i.layout&&(i.root&&i.root.updateScroll(),i.updateLayout()),Mm.read(a);const o=lte(window,"resize",()=>this.scalePositionWithinConstraints()),c=i.addEventListener("didUpdate",({delta:d,hasLayoutChanged:u})=>{this.isDragging&&u&&(B5(h=>{const m=this.getAxisMotionValue(h);m&&(this.originPoint[h]+=d[h].translate,m.set(m.get()+d[h].translate))}),this.visualElement.render())});return()=>{o(),n(),l(),c&&c(),r&&r()}}getProps(){const t=this.visualElement.getProps(),{drag:n=!1,dragDirectionLock:r=!1,dragPropagation:a=!1,dragConstraints:i=!1,dragElastic:l=gVe,dragMomentum:o=!0}=t;return{...t,drag:n,dragDirectionLock:r,dragPropagation:a,dragConstraints:i,dragElastic:l,dragMomentum:o}}}function _xt(s){let t=!0;return()=>{if(t){t=!1;return}s()}}function rRs(s,t,n){const r=Aft(s,_xt(n)),a=Aft(t,_xt(n));return()=>{r(),a()}}function _le(s,t,n){return(t===!0||t===s)&&(n===null||n===s)}function aRs(s,t=10){let n=null;return Math.abs(s.y)>t?n="y":Math.abs(s.x)>t&&(n="x"),n}class iRs extends mL{constructor(t){super(t),this.removeGroupControls=gN,this.removeListeners=gN,this.controls=new nRs(t)}mount(){const{dragControls:t}=this.node.getProps();t&&(this.removeGroupControls=t.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||gN}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 FOe=s=>(t,n)=>{s&&Mm.update(()=>s(t,n),!1,!0)};class oRs extends mL{constructor(){super(...arguments),this.removePointerDownListener=gN}onPointerDown(t){this.session=new A7t(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:C7t(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:n,onPan:r,onPanEnd:a}=this.node.getProps();return{onSessionStart:FOe(t),onStart:FOe(n),onMove:FOe(r),onEnd:(i,l)=>{delete this.session,a&&Mm.postRender(()=>a(i,l))}}}mount(){this.removePointerDownListener=kJ(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 OOe=!1;class lRs extends _.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),OOe&&i.root.didUpdate(),i.addEventListener("animationComplete",()=>{this.safeToRemove()}),i.setOptions({...i.options,layoutDependency:this.props.layoutDependency,onExitComplete:()=>this.safeToRemove()})),P4e.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}),OOe=!0,a||t.layoutDependency!==n||n===void 0||t.isPresent!==i?l.willUpdate():this.safeToRemove(),t.isPresent!==i&&(i?l.promote():l.relegate()||Mm.postRender(()=>{const o=l.getStack();(!o||!o.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{visualElement:t,layoutAnchor:n}=this.props,{projection:r}=t;r&&(r.options.layoutAnchor=n,r.root.didUpdate(),IJe.postRender(()=>{!r.currentAnimation&&r.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:r}=this.props,{projection:a}=t;OOe=!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 T7t(s){const[t,n]=y7t(),r=_.useContext(fJe);return e.jsx(lRs,{...s,layoutGroup:r,switchLayoutGroup:_.useContext(k7t),isPresent:t,safeToRemove:n})}const cRs={pan:{Feature:oRs},drag:{Feature:iRs,ProjectionNode:g7t,MeasureLayout:T7t}};function wxt(s,t,n){const{props:r}=s;s.animationState&&r.whileHover&&s.animationState.setActive("whileHover",n==="Start");const a="onHover"+n,i=r[a];i&&Mm.postRender(()=>i(t,Xre(t)))}class dRs extends mL{mount(){const{current:t}=this.node;t&&(this.unmount=PIs(t,(n,r)=>(wxt(this.node,r,"Start"),a=>wxt(this.node,a,"End"))))}unmount(){}}class uRs extends mL{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=Kre(lte(this.node.current,"focus",()=>this.onFocus()),lte(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function jxt(s,t,n){const{props:r}=s;if(s.current instanceof HTMLButtonElement&&s.current.disabled)return;s.animationState&&r.whileTap&&s.animationState.setActive("whileTap",n==="Start");const a="onTap"+(n==="End"?"":n),i=r[a];i&&Mm.postRender(()=>i(t,Xre(t)))}class hRs extends mL{mount(){const{current:t}=this.node;if(!t)return;const{globalTapTarget:n,propagate:r}=this.node.props;this.unmount=OIs(t,(a,i)=>(jxt(this.node,i,"Start"),(l,{success:o})=>jxt(this.node,l,o?"End":"Cancel")),{useGlobalTarget:n,stopPropagation:(r==null?void 0:r.tap)===!1})}unmount(){}}const yVe=new WeakMap,zOe=new WeakMap,mRs=s=>{const t=yVe.get(s.target);t&&t(s)},pRs=s=>{s.forEach(mRs)};function fRs({root:s,...t}){const n=s||document;zOe.has(n)||zOe.set(n,{});const r=zOe.get(n),a=JSON.stringify(t);return r[a]||(r[a]=new IntersectionObserver(pRs,{root:s,...t})),r[a]}function xRs(s,t,n){const r=fRs(t);return yVe.set(s,n),r.observe(s),()=>{yVe.delete(s),r.unobserve(s)}}const gRs={some:0,all:1};class yRs extends mL{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:gRs[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=xRs(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(vRs(t,n))&&this.startObserver()}unmount(){var t;(t=this.stopObserver)==null||t.call(this),this.hasEnteredView=!1,this.isInView=!1}}function vRs({viewport:s={}},{viewport:t={}}={}){return n=>s[n]!==t[n]}const bRs={inView:{Feature:yRs},tap:{Feature:hRs},focus:{Feature:uRs},hover:{Feature:dRs}},_Rs={layout:{ProjectionNode:g7t,MeasureLayout:T7t}},wRs={...HDs,...bRs,...cRs,..._Rs},Sr=BDs(wRs,UDs),jRs={some:0,all:1};function NRs(s,t,{root:n,margin:r,amount:a="some"}={}){const i=LJe(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:jRs[a]});return i.forEach(d=>c.observe(d)),()=>c.disconnect()}function kRs(s,{root:t,margin:n,amount:r,once:a=!1,initial:i=!1}={}){const[l,o]=_.useState(i);return _.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 NRs(s.current,c,d)},[t,s,n,a,r]),l}function SRs(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 Nxt(s){return s.visitor_intent==="buying"&&!s.has_agent}function CRs({token:s}={}){var p;const t=Li(),n=s||t.token,{data:r,isLoading:a,isError:i}=NPs(n);Bt();const l=(p=r==null?void 0:r.open_houses)==null?void 0:p.id,{data:o}=at({queryKey:["cohost-visitors",n,l],queryFn:async()=>{const{data:f,error:y}=await q.rpc("get_cohost_visitors",{_token:n});if(y)throw y;return f||[]},enabled:!!n&&!!l,refetchInterval:15e3});if(a)return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-950 via-slate-900 to-slate-950 flex items-center justify-center",children:e.jsx("div",{className:"animate-pulse text-white/40",children:"Validating access..."})});if(i||!r)return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-950 via-slate-900 to-slate-950 flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center text-white",children:[e.jsx("h1",{className:"text-xl font-bold mb-2",children:"Link Expired or Invalid"}),e.jsx("p",{className:"text-white/40 text-sm",children:"This co-host link is no longer active. Ask the host for a new one."})]})});const c=r.open_houses,d=(o==null?void 0:o.length)||0,u=(o==null?void 0:o.filter(f=>f.visitor_intent==="buying").length)||0,h=(o==null?void 0:o.filter(Nxt).length)||0,m=f=>{if(!f)return"";const[y,v]=f.split(":"),g=parseInt(y);return`${g>12?g-12:g||12}:${v} ${g>=12?"PM":"AM"}`};return e.jsxs("div",{className:"fixed inset-0 bg-gradient-to-br from-slate-950 via-slate-900 to-slate-950 flex flex-col",children:[e.jsxs("div",{className:"border-b border-white/10 px-4 sm:px-6 py-3 flex items-center justify-between bg-black/30 backdrop-blur-xl",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-emerald-400 animate-pulse"}),e.jsx("span",{className:"text-xs font-medium text-emerald-400 uppercase tracking-wider",children:"Live · Co-Host View"})]}),e.jsx("h1",{className:"text-white font-bold text-sm sm:text-base truncate",children:c.property_address})]}),e.jsxs("div",{className:"flex items-center gap-4 sm:gap-6 text-white/70",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(In,{className:"h-4 w-4"}),e.jsx("span",{className:"font-bold text-white",children:d})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-orange-400",children:[e.jsx(gu,{className:"h-4 w-4"}),e.jsx("span",{className:"font-bold text-white",children:h})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Jr,{className:"h-4 w-4"}),e.jsx("span",{className:"font-bold text-white",children:u})]})]})]}),e.jsxs("div",{className:"px-4 sm:px-6 py-2 flex items-center gap-4 text-xs text-white/40 border-b border-white/5",children:[e.jsx("span",{children:Hs(new Date(c.event_date+"T00:00:00"),"EEEE, MMMM d, yyyy")}),c.start_time&&e.jsxs("span",{children:[m(c.start_time),c.end_time?` – ${m(c.end_time)}`:""]})]}),e.jsx(Ji,{className:"flex-1 p-4 sm:p-6",children:o!=null&&o.length?e.jsx("div",{className:"space-y-2 max-w-3xl mx-auto",children:e.jsx(mW,{children:o.map((f,y)=>{var b;const v=SRs(f.visitor_intent),g=Nxt(f);return e.jsxs(Sr.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 ${g?"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 ${g?"bg-gradient-to-br from-orange-500 to-amber-500 text-white":"bg-white/10 text-white/80"}`,children:(b=f.first_name[0])==null?void 0:b.toUpperCase()}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("span",{className:"font-semibold text-white truncate",children:[f.first_name," ",f.last_name||""]}),g&&e.jsx(Oe,{className:"bg-orange-500/20 text-orange-300 border-orange-500/40 text-[10px] px-1.5 py-0",children:"🔥 HOT"}),f.has_agent&&e.jsx(Oe,{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(Oe,{variant:"outline",className:`text-[10px] px-1.5 py-0 ${v.color}`,children:[v.emoji," ",v.label]}),e.jsx("span",{className:"text-white/30 text-xs",children:Hs(new Date(f.created_at),"h:mm a")})]})]})]},f.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(Nv,{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 ARs(){const t=ru().pathname.slice(1);if(_.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(CRs,{token:n})}if(t.startsWith("rsvp/")){const n=t.slice(5);if(n)return e.jsx(HFt,{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(VFt,{slug:t})}function ERs({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(Sr.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(Sr.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(Sr.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(Jr,{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(Xa,{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(_a,{className:"w-4 h-4"}),e.jsx("span",{className:"text-sm font-medium",children:"Call"})]}),t.email&&e.jsxs("a",{href:`mailto:${t.email}`,className:"flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-xl transition-colors",style:{background:"hsl(var(--portal-gold) / 0.06)",color:"var(--portal-hero-accent)",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:[e.jsx(ln,{className:"w-4 h-4"}),e.jsx("span",{className:"text-sm font-medium",children:"Email"})]}),t.phone&&e.jsxs("a",{href:`sms:${t.phone}`,className:"flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-xl transition-colors",style:{background:"hsl(var(--portal-gold) / 0.06)",color:"var(--portal-hero-accent)",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:[e.jsx(Ou,{className:"w-4 h-4"}),e.jsx("span",{className:"text-sm font-medium",children:"Text"})]})]})})})]})}function M7t({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=CN(a,new Date);if(X4(a)&&!yy(a))return null;const o=yy(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(Sr.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(Sr.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 P7t({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(Sr.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 Ru(s){const t=s.split(/[-/T]/);if(t.length>=3){const n=Number(t[0]);return n>99?new Date(n,Number(t[1])-1,Number(t[2])):new Date(Number(t[2]),Number(t[0])-1,Number(t[1]))}return new Date(`${s}T12:00:00`)}function kxt(s){const t=s.trim();if(!t)return;const n=t.split(/[-/]/).filter(Boolean);if(n.length<3)return;const r=n.map(c=>Number(c));if(r.some(c=>Number.isNaN(c)))return;r[0];let a,i,l;if(n[0].length===4)[l,a,i]=r,a=a-1;else if([a,i,l]=r,a=a-1,n[2].length===2)l=l<=49?2e3+l:1900+l;else if(n[2].length!==4)return;const o=new Date(l,a,i);if(!(o.getFullYear()!==l||o.getMonth()!==a||o.getDate()!==i))return o}const TRs=[{key:"contract_date",label:"Contract Accepted",icon:cN},{key:"earnest_money_due_date",label:"Earnest Money",icon:yd},{key:"inspection_date",label:"Inspection",icon:Lr},{key:"inspection_contingency_date",label:"Inspection Deadline",icon:Fr},{key:"appraisal_date",label:"Appraisal",icon:Jr},{key:"loan_approval_date",label:"Loan Approval",icon:Uq},{key:"title_docs_due_date",label:"Title & Disclosures",icon:Fr},{key:"final_walkthrough_date",label:"Final Walkthrough",icon:VA},{key:"target_close_date",label:"Target Close",icon:ga}];function MRs(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 PRs(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 I7t({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=TRs.map(p=>p.key==="target_close_date"&&c?{...p,label:"Closed",date:c,done:!0}:{...p,date:o[p.key],done:d.includes(p.key)}).filter(p=>!!p.date);if(u.length===0)return null;const h=(p,f,y)=>{const v=Ru(f);if(y==="google")window.open(MRs(p,v),"_blank");else{const g=PRs(p,v),b=document.createElement("a");b.href=g,b.download=`${p.replace(/\s+/g,"-").toLowerCase()}.ics`,b.click()}},m=u.filter(p=>p.done).length;return e.jsxs("div",{children:[e.jsx("p",{className:"portal-eyebrow mb-2",children:"Milestones"}),e.jsxs("div",{className:"flex items-baseline justify-between gap-3 mb-5 flex-wrap",children:[e.jsx("h2",{className:"portal-serif text-2xl",style:{color:"hsl(var(--portal-ink))"},children:"Key dates"}),e.jsxs("span",{className:"text-[11px] tracking-[0.18em] uppercase",style:{color:"hsl(var(--portal-ink-dim))"},children:[m," of ",u.length," complete"]})]}),e.jsxs("div",{className:"space-y-4 relative",children:[e.jsx("div",{className:"absolute left-[10px] top-2 bottom-2 w-[1px]",style:{background:"hsl(var(--portal-gold) / 0.18)"}}),u.map(({label:p,date:f,done:y,icon:v})=>{const g=Ru(f),b=X4(g)&&!yy(g),j=yy(g),S=!b&&!j,C=y?"Completed":j?"Today":b?"In progress":"Upcoming";return e.jsxs("div",{className:"flex items-start gap-3 relative",children:[e.jsx("div",{className:"w-[21px] h-[21px] rounded-full mt-0.5 flex-shrink-0 relative z-10 flex items-center justify-center",style:{background:y?"hsl(var(--portal-gold))":j?"hsl(var(--portal-gold) / 0.25)":"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.7)",boxShadow:j?"0 0 12px hsl(var(--portal-gold) / 0.5)":"none"},children:y?e.jsx(ea,{className:"w-3 h-3",style:{color:"hsl(var(--portal-surface))"}}):e.jsx(v,{className:"w-3 h-3",style:{color:"hsl(var(--portal-gold))"}})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-[10px] tracking-[0.22em] uppercase",style:{color:"hsl(var(--portal-ink-dim))"},children:p}),e.jsx("p",{className:"portal-serif mt-0.5",style:{fontSize:"1.15rem",color:y?"hsl(var(--portal-ink-muted))":"hsl(var(--portal-ink))"},children:Hs(g,"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:y||j?"hsl(var(--portal-gold))":"hsl(var(--portal-ink-dim))",border:`1px solid hsl(var(--portal-gold) / ${y||j?.5:.18})`},children:C})]}),S&&e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[e.jsx("button",{onClick:()=>h(p,f,"google"),className:"p-1.5 rounded transition-colors",style:{color:"hsl(var(--portal-ink-dim))"},onMouseEnter:E=>{E.currentTarget.style.color="hsl(var(--portal-gold))"},onMouseLeave:E=>{E.currentTarget.style.color="hsl(var(--portal-ink-dim))"},title:"Add to Google Calendar",children:e.jsx(gy,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onClick:()=>h(p,f,"apple"),className:"text-[9px] tracking-widest px-1.5 py-1 rounded",style:{color:"hsl(var(--portal-ink-dim))"},title:"Download .ics",children:".ICS"})]})]},p)})]})]})}function D7t({documents:s}){const t=r=>r<1024?`${r} B`:r<1048576?`${(r/1024).toFixed(0)} KB`:`${(r/1048576).toFixed(1)} MB`,n=async r=>{const{data:a}=await q.storage.from("deal-files").createSignedUrl(r.storage_path,300);a!=null&&a.signedUrl&&window.open(a.signedUrl,"_blank")};return e.jsxs("div",{children:[e.jsx("p",{className:"portal-eyebrow mb-2",children:"Paperwork"}),e.jsx("h2",{className:"portal-serif text-2xl mb-5",style:{color:"hsl(var(--portal-ink))"},children:"Documents"}),e.jsx("div",{className:"space-y-2",children:s.map(r=>e.jsxs("button",{onClick:()=>n(r),className:"w-full flex items-center gap-3 p-3 rounded-xl transition-all text-left group",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.08)"},onMouseEnter:a=>{a.currentTarget.style.borderColor="hsl(var(--portal-gold) / 0.35)"},onMouseLeave:a=>{a.currentTarget.style.borderColor="hsl(var(--portal-gold) / 0.08)"},children:[e.jsx("div",{className:"w-10 h-10 rounded-lg flex items-center justify-center flex-shrink-0",style:{background:"hsl(var(--portal-gold) / 0.08)",border:"1px solid hsl(var(--portal-gold) / 0.2)"},children:e.jsx(Fr,{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(li,{className:"w-4 h-4 flex-shrink-0",style:{color:"hsl(var(--portal-gold) / 0.5)"}})]},r.id))})]})}function R7t({slug:s,wrapper:t}){const n=Fn(),[r,a]=_.useState(null),{data:i=[]}=at({queryKey:["portal-signature-requests",s],enabled:!!s,queryFn:async()=>{const{data:u,error:h}=await q.functions.invoke("forms-portal-public",{body:{action:"list",slug:s}});return h?[]:(u==null?void 0:u.envelopes)||[]}}),l=i.filter(u=>u.my_turn),o=i.filter(u=>!u.my_turn&&u.status!=="completed");if(!l.length&&!o.length)return null;const c=async u=>{a(u);try{const{data:h,error:m}=await q.functions.invoke("forms-portal-public",{body:{action:"sign_link",slug:s,envelope_id:u}});if(m||h!=null&&h.error)throw new Error((h==null?void 0:h.error)||"Could not open the document");n(h.path)}catch(h){se.error((h==null?void 0:h.message)||"Could not open the document")}finally{a(null)}},d=e.jsxs("div",{children:[e.jsx("p",{className:"portal-eyebrow mb-2",children:"Needs you"}),e.jsx("h2",{className:"portal-serif text-2xl mb-5",style:{color:"hsl(var(--portal-ink))"},children:"Documents to sign"}),e.jsxs("div",{className:"space-y-2",children:[l.map(u=>e.jsxs("button",{onClick:()=>c(u.id),disabled:r===u.id,className:"w-full flex items-center gap-3 p-3 rounded-xl transition-all text-left",style:{background:"hsl(var(--portal-gold) / 0.1)",border:"1px solid hsl(var(--portal-gold) / 0.4)"},children:[e.jsx("div",{className:"w-10 h-10 rounded-lg flex items-center justify-center flex-shrink-0",style:{background:"hsl(var(--portal-gold) / 0.14)",border:"1px solid hsl(var(--portal-gold) / 0.3)"},children:r===u.id?e.jsx(Ct,{className:"w-4 h-4 animate-spin",style:{color:"hsl(var(--portal-gold))"}}):e.jsx(Qm,{className:"w-4 h-4",style:{color:"hsl(var(--portal-gold))"}})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm portal-serif truncate",style:{color:"hsl(var(--portal-ink))",fontSize:"1rem"},children:u.title}),e.jsx("p",{className:"text-[10px] tracking-widest uppercase mt-0.5",style:{color:"hsl(var(--portal-gold))"},children:"Tap to review & sign"})]})]},u.id)),o.map(u=>e.jsxs("div",{className:"w-full flex items-center gap-3 p-3 rounded-xl",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.08)"},children:[e.jsx("div",{className:"w-10 h-10 rounded-lg flex items-center justify-center flex-shrink-0",style:{background:"hsl(var(--portal-gold) / 0.06)"},children:u.my_status==="signed"?e.jsx(Er,{className:"w-4 h-4",style:{color:"hsl(var(--portal-ink-muted))"}}):e.jsx(Gr,{className:"w-4 h-4",style:{color:"hsl(var(--portal-ink-muted))"}})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm portal-serif truncate",style:{color:"hsl(var(--portal-ink-muted))",fontSize:"1rem"},children:u.title}),e.jsx("p",{className:"text-[10px] tracking-widest uppercase mt-0.5",style:{color:"hsl(var(--portal-ink-dim))"},children:u.my_status==="signed"?"You signed — waiting on others":"Waiting on another signer"})]})]},u.id))]})]});return t?t(d):d}function F7t({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(Lg,{className:"w-3.5 h-3.5",style:{color:"hsl(var(--portal-gold))"}}):e.jsx(Rg,{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 pW=[{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"}],LRs=[{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 IRs(s){return at({queryKey:["vendors","brokerage",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("vendors").select("*").eq("owner_type","brokerage").eq("owner_brokerage_id",s).order("sort_order",{ascending:!0}).order("name",{ascending:!0});if(n)throw n;return t||[]},enabled:!!s})}function DRs(){const s=ha(),{brokerageId:t}=hs();return at({queryKey:["vendors","library",s,t],queryFn:async()=>{if(!s)return{vendors:[],selections:[]};let n=q.from("vendors").select("*");t?n=n.or(`and(owner_type.eq.agent,owner_user_id.eq.${s}),and(owner_type.eq.brokerage,owner_brokerage_id.eq.${t})`):n=n.eq("owner_type","agent").eq("owner_user_id",s);const[{data:r,error:a},{data:i,error:l}]=await Promise.all([n.order("sort_order",{ascending:!0}).order("name",{ascending:!0}),q.from("agent_vendor_selections").select("*").eq("agent_user_id",s)]);if(a)throw a;if(l)throw l;return{vendors:r||[],selections:i||[]}},enabled:!!s})}function RRs(){const s=Bt();return mt({mutationFn:async t=>{if(t.id){const{id:n,created_at:r,...a}=t,{data:i,error:l}=await q.from("vendors").update(a).eq("id",n).select().single();if(l)throw l;return i}else{const{data:n,error:r}=await q.from("vendors").insert(t).select().single();if(r)throw r;return n}},onSuccess:()=>s.invalidateQueries({queryKey:["vendors"]})})}function O7t(){const s=Bt();return mt({mutationFn:async t=>{const{error:n}=await q.from("vendors").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["vendors"]})})}function FRs(){const s=ha(),t=Bt();return mt({mutationFn:async({vendorId:n,isVisible:r})=>{if(!s)throw new Error("No user");const{data:a}=await q.from("agent_vendor_selections").select("id").eq("agent_user_id",s).eq("vendor_id",n).maybeSingle();if(a){const{error:i}=await q.from("agent_vendor_selections").update({is_visible:r}).eq("id",a.id);if(i)throw i}else{const{error:i}=await q.from("agent_vendor_selections").insert({agent_user_id:s,vendor_id:n,is_visible:r});if(i)throw i}},onSuccess:()=>t.invalidateQueries({queryKey:["vendors"]})})}function z7t(s){return at({queryKey:["portal-vendors",s==null?void 0:s.id,s==null?void 0:s.owner_user_id],queryFn:async()=>{if(!(s!=null&&s.id)||!(s!=null&&s.owner_user_id))return[];const t=s.owner_user_id,{data:n}=await q.from("profiles").select("brokerage_id").eq("id",t).maybeSingle(),r=n==null?void 0:n.brokerage_id,a=q.from("vendors").select("*").eq("is_active",!0),i=r?a.or(`and(owner_type.eq.agent,owner_user_id.eq.${t}),and(owner_type.eq.brokerage,owner_brokerage_id.eq.${r})`):a.eq("owner_type","agent").eq("owner_user_id",t),[{data:l,error:o},{data:c},{data:d}]=await Promise.all([i.order("sort_order",{ascending:!0}).order("name",{ascending:!0}),q.from("agent_vendor_selections").select("vendor_id, display_order, is_visible").eq("agent_user_id",t),q.from("portal_vendor_overrides").select("vendor_id, is_visible").eq("portal_id",s.id)]);if(o)throw o;const u=new Map;(c||[]).forEach(p=>u.set(p.vendor_id,{display_order:p.display_order,is_visible:p.is_visible}));const h=new Map;return(d||[]).forEach(p=>h.set(p.vendor_id,p.is_visible)),(l||[]).filter(p=>{if(h.get(p.id)===!1)return!1;const f=u.get(p.id);return!(f&&f.is_visible===!1&&!p.is_required)}).map(p=>{var f;return{...p,display_order:((f=u.get(p.id))==null?void 0:f.display_order)??p.sort_order??0}}).sort((p,f)=>(p.display_order||0)-(f.display_order||0))},enabled:!!(s!=null&&s.id)&&!!(s!=null&&s.owner_user_id)})}async function Sxt(s){try{await q.from("vendor_clicks").insert({vendor_id:s.vendorId,portal_id:s.portalId||null,agent_user_id:s.agentUserId||null,action_taken:s.actionTaken||null,user_agent:typeof navigator<"u"?navigator.userAgent.slice(0,500):null})}catch(t){console.warn("vendor click track failed",t)}}function B7t(s,t){return at({queryKey:["vendor-clicks",s,t],queryFn:async()=>{if(!t)return{};const{data:n}=await q.from("vendors").select("id").eq(s==="agent"?"owner_user_id":"owner_brokerage_id",t).eq("owner_type",s),r=(n||[]).map(l=>l.id);if(r.length===0)return{};const{data:a}=await q.from("vendor_clicks").select("vendor_id").in("vendor_id",r),i={};return(a||[]).forEach(l=>{i[l.vendor_id]=(i[l.vendor_id]||0)+1}),i},enabled:!!t})}function U7t({portalId:s,ownerUserId:t,currentStage:n,brandingColor:r,layout:a="list"}){const{data:i=[],isLoading:l}=z7t({id:s,owner_user_id:t});if(l||i.length===0)return null;const o=i.filter(b=>!b.stage_filter||b.stage_filter.length===0||!n?!0:b.stage_filter.includes(n));if(o.length===0)return null;const c=r||"#406E71",d=(b,j)=>{switch(j){case"book":return b.booking_url;case"website":return b.website;case"call":return b.phone?`tel:${b.phone.replace(/[^\d+]/g,"")}`:null;case"email":case"quote":return b.email?`mailto:${b.email}`:null}},u=b=>{const j=d(b,b.action_type);Sxt({vendorId:b.id,portalId:s,agentUserId:t,actionTaken:b.action_type}),j&&window.open(j,b.action_type==="call"||b.action_type==="email"||b.action_type==="quote"?"_self":"_blank")},h=b=>{const j=d(b,b.action_type);return[{action:"website",label:"Website",icon:e.jsx(sl,{className:"w-3.5 h-3.5"})},{action:"email",label:"Email",icon:e.jsx(ln,{className:"w-3.5 h-3.5"})},{action:"call",label:"Call",icon:e.jsx(_a,{className:"w-3.5 h-3.5"})},{action:"book",label:"Book",icon:e.jsx(ga,{className:"w-3.5 h-3.5"})}].filter(C=>C.action!==b.action_type).map(C=>{const E=d(b,C.action);return!E||E===j?null:e.jsxs("button",{onClick:()=>{Sxt({vendorId:b.id,portalId:s,agentUserId:t,actionTaken:C.action}),window.open(E,C.action==="call"||C.action==="email"?"_self":"_blank")},className:"inline-flex items-center gap-1 text-slate-500 hover:text-slate-700 hover:underline",title:C.label,children:[C.icon,e.jsx("span",{className:"text-xs",children:C.label})]},C.action)}).filter(Boolean)},m=b=>{switch(b.action_type){case"book":return"Book Now";case"quote":return"Request Quote";case"call":return"Call";case"email":return"Email";case"website":return"Visit Site"}},p=b=>{switch(b.action_type){case"book":return e.jsx(ga,{className:"w-3.5 h-3.5"});case"call":return e.jsx(_a,{className:"w-3.5 h-3.5"});case"email":case"quote":return e.jsx(ln,{className:"w-3.5 h-3.5"});case"website":return e.jsx(sl,{className:"w-3.5 h-3.5"})}},f=b=>{var j;return((j=pW.find(S=>S.value===b))==null?void 0:j.label)||b},y=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(un,{className:"w-4 h-4"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"font-semibold text-slate-800",children:"Trusted Partners"}),e.jsx("p",{className:"text-xs text-slate-500",children:"My personally-vetted recommendations for you"})]})]}),v=o.some(b=>b.disclosure_text)&&e.jsx("div",{className:"mt-4 pt-3 border-t border-slate-100 space-y-1",children:o.filter(b=>b.disclosure_text).map(b=>e.jsxs("p",{className:"text-[10px] text-slate-400",children:[e.jsxs("span",{className:"font-medium",children:[b.company||b.name,":"]})," ",b.disclosure_text]},b.id))});if(a==="grid")return e.jsxs(ve,{className:"p-5 sm:p-6 rounded-2xl border-slate-200/80 shadow-sm bg-white/70 backdrop-blur",children:[y,e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3",children:o.map(b=>e.jsxs("div",{className:"group flex flex-col p-4 rounded-xl border border-slate-200/70 bg-white hover:shadow-md hover:-translate-y-0.5 transition-all",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-lg bg-slate-50 border border-slate-200 flex items-center justify-center overflow-hidden shrink-0",children:b.logo_url?e.jsx("img",{src:b.logo_url,alt:b.name,className:"w-full h-full object-cover"}):e.jsx("span",{className:"text-base font-semibold text-slate-500",children:(b.company||b.name).charAt(0)})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-semibold text-sm text-slate-800 truncate",children:b.company||b.name}),b.company&&b.name&&e.jsx("p",{className:"text-xs text-slate-500 truncate",children:b.name}),e.jsx("span",{className:"inline-block mt-1 text-[10px] font-medium px-1.5 py-0.5 rounded",style:{backgroundColor:`${c}12`,color:c},children:f(b.category)})]})]}),b.description&&e.jsx("p",{className:"text-xs text-slate-500 mt-3 line-clamp-2",children:b.description}),e.jsxs("div",{className:"mt-auto pt-4 flex flex-col gap-2",children:[e.jsxs(B,{size:"sm",onClick:()=>u(b),style:{backgroundColor:c},className:"text-white hover:opacity-90 w-full",children:[p(b),e.jsx("span",{className:"ml-1.5 text-xs",children:m(b)})]}),h(b).length>0&&e.jsx("div",{className:"flex flex-wrap items-center justify-center gap-3",children:h(b)})]})]},b.id))}),v]});const g=o.reduce((b,j)=>((b[j.category]=b[j.category]||[]).push(j),b),{});return e.jsxs(ve,{className:"p-5 rounded-2xl border-slate-200/80 shadow-sm",children:[y,e.jsx("div",{className:"space-y-4",children:Object.entries(g).map(([b,j])=>e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-slate-400 font-medium mb-2",children:f(b)}),e.jsx("div",{className:"space-y-2",children:j.map(S=>e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-xl bg-slate-50 hover:bg-slate-100 transition-colors",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-white border border-slate-200 flex items-center justify-center overflow-hidden shrink-0",children:S.logo_url?e.jsx("img",{src:S.logo_url,alt:S.name,className:"w-full h-full object-cover"}):e.jsx("span",{className:"text-sm font-semibold text-slate-500",children:S.name.charAt(0)})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm text-slate-800 truncate",children:S.company||S.name}),S.company&&S.name&&e.jsx("p",{className:"text-xs text-slate-500 truncate",children:S.name}),S.description&&e.jsx("p",{className:"text-xs text-slate-500 truncate mt-0.5",children:S.description})]}),e.jsxs(B,{size:"sm",onClick:()=>u(S),style:{backgroundColor:c},className:"text-white hover:opacity-90 shrink-0",children:[p(S),e.jsx("span",{className:"ml-1.5 text-xs",children:m(S)})]})]},S.id))})]},b))}),v]})}function ORs(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 zRs(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 q7t({portalId:s,portalSlug:t,ownerUserId:n,rewardText:r,ctaHeadline:a,agentName:i,clientName:l,reviewUrl:o,hubVideoUrl:c}){const[d,u]=_.useState(!1),h=_.useRef(!1),m=ORs(t);_.useEffect(()=>{h.current||(h.current=!0,q.from("portal_referral_clicks").insert({portal_id:s,owner_user_id:n,click_type:"card_view",user_agent:navigator.userAgent.slice(0,500)}).then(()=>{}))},[s,n]);const p=async E=>{await q.from("portal_referral_clicks").insert({portal_id:s,owner_user_id:n,click_type:E,user_agent:navigator.userAgent.slice(0,500)})},f=()=>`${l?`Hey, it's ${l}!`:"Hey!"} I just had an amazing experience working with ${i||"my real estate agent"} on my home. If you or someone you know is thinking about buying or selling, here's their referral link: ${m}`,y=async()=>{await navigator.clipboard.writeText(m),u(!0),p("copy_link"),setTimeout(()=>u(!1),2e3)},v=()=>{p("share_sms");const E=encodeURIComponent(f());window.location.href=`sms:?&body=${E}`},g=()=>{p("share_email");const E=encodeURIComponent("A referral you'll thank me for"),P=encodeURIComponent(f());window.location.href=`mailto:?subject=${E}&body=${P}`},b=()=>{p("open_form"),window.open(m,"_blank")},j=a||"Know someone buying or selling?",S=c?zRs(c):null,C=S==null?void 0:S.match(/\.(mp4|webm|mov)(\?|$)/i);return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"bg-gradient-to-br from-emerald-50 via-teal-50 to-cyan-50 rounded-2xl p-6 border border-emerald-100 text-center",children:[e.jsx("div",{className:"text-5xl mb-2",children:"🎉"}),e.jsxs("h3",{className:"text-xl font-bold text-emerald-900 mb-1 font-serif",children:["Welcome Home",l?`, ${l.split(" ")[0]}`:"","!"]}),e.jsx("p",{className:"text-sm text-emerald-700/80",children:"Your transaction is complete. We're so proud to have been part of your journey."})]}),S&&e.jsxs("div",{className:"bg-white rounded-2xl border border-slate-100 shadow-sm overflow-hidden",children:[e.jsx("div",{className:"px-4 pt-4 pb-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(un,{className:"w-4 h-4 text-[#406E71]"}),e.jsxs("p",{className:"text-sm font-medium text-slate-700",children:["A message from ",i||"your agent"]})]})}),e.jsx("div",{className:"aspect-video bg-slate-900",children:C?e.jsx("video",{src:S,controls:!0,className:"w-full h-full",playsInline:!0}):e.jsx("iframe",{src:S,className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})]}),e.jsxs("div",{className:"relative overflow-hidden rounded-2xl bg-gradient-to-br from-[#2a4c64] via-[#345e7a] to-[#406E71] text-white shadow-xl",children:[e.jsx("div",{className:"absolute inset-0 opacity-[0.07]",style:{backgroundImage:"radial-gradient(circle at 25% 25%, white 1px, transparent 1px)",backgroundSize:"20px 20px"}}),e.jsxs("div",{className:"relative p-6",children:[e.jsxs("div",{className:"inline-flex items-center gap-1.5 bg-white/15 backdrop-blur-sm rounded-full px-3 py-1 text-xs font-medium mb-3",children:[e.jsx(Vo,{className:"w-3 h-3"}),"Referral Program"]}),e.jsx("h3",{className:"text-xl font-bold leading-tight mb-2 font-serif",children:j}),r&&e.jsxs("p",{className:"text-sm text-white/85 mb-1",children:[e.jsx("span",{className:"font-semibold text-white",children:"Your reward:"})," ",r]}),e.jsxs("p",{className:"text-sm text-white/70 mb-5 leading-relaxed",children:["The biggest compliment you can give ",i||"us"," is sending a friend or family member."]}),e.jsxs("button",{onClick:b,className:"w-full bg-white text-[#2a4c64] font-semibold rounded-xl py-3.5 px-4 flex items-center justify-center gap-2 shadow-md hover:bg-white/95 active:scale-[0.99] transition-all",children:["Refer a Friend",e.jsx(La,{className:"w-4 h-4"})]}),e.jsxs("div",{className:"mt-4 grid grid-cols-3 gap-2",children:[e.jsxs("button",{onClick:v,className:"flex items-center justify-center gap-1.5 bg-white/10 hover:bg-white/20 backdrop-blur-sm rounded-lg py-2.5 text-xs font-medium transition-colors",children:[e.jsx(Ou,{className:"w-3.5 h-3.5"}),"Text"]}),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:[e.jsx(ln,{className:"w-3.5 h-3.5"}),"Email"]}),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:[d?e.jsx(ea,{className:"w-3.5 h-3.5"}):e.jsx(Ia,{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(La,{className:"w-4 h-4 text-slate-400"})]})})]})}function $7t(s){return at({queryKey:["portal-messages",s],queryFn:async()=>{const{data:t,error:n}=await q.from("portal_messages").select("*").eq("portal_id",s).order("created_at",{ascending:!0});if(n)throw n;return t||[]},enabled:!!s,refetchInterval:3e4})}function V7t(){const s=Bt();return mt({mutationFn:async({portalId:t,senderType:n,senderName:r,body:a,deviceFingerprint:i,portalUrl:l})=>{const{data:o,error:c}=await q.from("portal_messages").insert({portal_id:t,sender_type:n,sender_name:r||null,body:a.trim(),device_fingerprint:i||null,...n==="agent"?{read_at:new Date().toISOString()}:{}}).select().single();if(c)throw c;try{await q.functions.invoke("portal-message-notify",{body:{message_id:o.id,portal_url:l}})}catch(d){console.error("portal-message-notify failed",d)}return o},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["portal-messages",n.portalId]}),s.invalidateQueries({queryKey:["portal-unread-messages"]}),s.invalidateQueries({queryKey:["portal-conversations"]})}})}function BRs(){const s=Bt();return mt({mutationFn:async t=>{const{error:n}=await q.from("portal_messages").update({read_at:new Date().toISOString()}).eq("portal_id",t).eq("sender_type","client").is("read_at",null);if(n)throw n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["portal-messages",n]}),s.invalidateQueries({queryKey:["portal-unread-messages"]}),s.invalidateQueries({queryKey:["portal-conversations"]})}})}function H7t(){const s=ha();return at({queryKey:["portal-conversations",s],queryFn:async()=>{const{data:t,error:n}=await q.from("client_portals").select("id, slug, client_name, client_email, archived_at").eq("owner_user_id",s).is("archived_at",null);if(n)throw n;if(!t||t.length===0)return[];const r=t.map(c=>c.id),a=[],i=100,l=1e3;for(let c=0;c{const d=o.get(c.id)||[];return{portalId:c.id,slug:c.slug,clientName:c.client_name,clientEmail:c.client_email,lastMessage:d.length?d[d.length-1]:null,unreadCount:d.filter(u=>u.sender_type==="client"&&!u.read_at).length,messageCount:d.length}}).sort((c,d)=>{var m,p;const u=((m=c.lastMessage)==null?void 0:m.created_at)||"",h=((p=d.lastMessage)==null?void 0:p.created_at)||"";return u===h?(c.clientName||"").localeCompare(d.clientName||""):h.localeCompare(u)})},enabled:!!s,refetchInterval:3e4})}function G7t({portalId:s,clientName:t,agentName:n,agentAvatar:r,deviceFingerprint:a}){const{data:i,isLoading:l}=$7t(s),o=V7t(),[c,d]=_.useState(""),u=`portal_msg_name_${s}`,[h,m]=_.useState(()=>localStorage.getItem(u)||t||""),p=_.useRef(null);_.useEffect(()=>{var v;(v=p.current)==null||v.scrollIntoView({block:"nearest"})},[i==null?void 0:i.length]);const f=async()=>{const v=c.trim();if(!v)return;const g=(h||t||"").trim();if(!g){se.error("Please add your name first");return}try{localStorage.setItem(u,g),await o.mutateAsync({portalId:s,senderType:"client",senderName:g,body:v,deviceFingerprint:a,portalUrl:window.location.href}),d(""),se.success("Message sent")}catch(b){se.error((b==null?void 0:b.message)||"Could not send your message")}},y="hsl(var(--portal-gold))";return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(Hi,{className:"w-4 h-4",style:{color:y}}),e.jsx("h2",{className:"portal-serif",style:{fontSize:"1.35rem",color:"hsl(var(--portal-ink))"},children:"Messages"})]}),e.jsx("div",{className:"portal-hairline mb-4"}),e.jsxs("div",{className:"space-y-3 max-h-[340px] overflow-y-auto pr-1",children:[l&&e.jsx("div",{className:"flex justify-center py-6",children:e.jsx(Ct,{className:"w-4 h-4 animate-spin",style:{color:y}})}),!l&&(!i||i.length===0)&&e.jsxs("p",{className:"text-sm",style:{color:"hsl(var(--portal-ink-muted))"},children:["Have a question for ",n||"your agent","? Send a message below — they'll be notified right away."]}),i==null?void 0:i.map(v=>{const g=v.sender_type==="agent";return e.jsx("div",{className:`flex ${g?"justify-start":"justify-end"}`,children:e.jsxs("div",{className:"max-w-[85%] rounded-2xl px-4 py-3",style:{background:g?"hsl(var(--portal-surface-2))":"hsl(var(--portal-gold) / 0.12)",border:`1px solid ${g?"hsl(var(--portal-gold) / 0.12)":"hsl(var(--portal-gold) / 0.28)"}`},children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[g&&r&&e.jsx("img",{src:r,alt:n||"Agent",className:"w-5 h-5 rounded-full object-cover"}),e.jsxs("span",{className:"text-[11px] uppercase tracking-[0.14em]",style:{color:"hsl(var(--portal-ink-dim))"},children:[g?n||"Your agent":v.sender_name||"You"," ·"," ",Hs(new Date(v.created_at),"MMM d, h:mm a")]})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap leading-relaxed",style:{color:"hsl(var(--portal-ink))"},children:v.body})]})},v.id)}),e.jsx("div",{ref:p})]}),e.jsxs("div",{className:"mt-4 space-y-2",children:[!t&&e.jsx("input",{value:h,onChange:v=>m(v.target.value),placeholder:"Your name",className:"w-full rounded-xl px-3 py-2 text-sm outline-none",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.18)",color:"hsl(var(--portal-ink))"}}),e.jsx("textarea",{value:c,onChange:v=>d(v.target.value),rows:3,placeholder:`Write a message to ${n||"your agent"}...`,className:"w-full rounded-xl px-3 py-2 text-sm outline-none resize-none",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.18)",color:"hsl(var(--portal-ink))"}}),e.jsxs("button",{onClick:f,disabled:o.isPending||!c.trim(),className:"w-full flex items-center justify-center gap-2 rounded-xl py-2.5 text-sm font-medium transition-opacity disabled:opacity-50",style:{background:"hsl(var(--portal-gold) / 0.16)",border:"1px solid hsl(var(--portal-gold) / 0.35)",color:y},children:[o.isPending?e.jsx(Ct,{className:"w-4 h-4 animate-spin"}):e.jsx(Or,{className:"w-4 h-4"}),"Send message"]})]})]})}function URs(s){return s==="buy-side"?"Home Search in Progress":s==="listing"?"Your Home Is On The Market":"Active Phase"}function qRs(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 $Rs={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. 🎉"}},W7t=["Lead","Consultation","Agreement Signed","Active","Under Contract","Closing","Closed Won"];function BPe(s){return W7t.map(t=>{if(t==="Active")return{key:"Active",label:URs(s),description:qRs(s)};const n=$Rs[t];return{key:t,label:n.label,description:n.description}})}function jAe(s){if(!s)return 0;const t=W7t.indexOf(s);return t>=0?t:0}function VRs({portal:s,linkedPortal:t,activePortal:n,activeTab:r,onTabChange:a,agentProfile:i,branding:l,updates:o,documents:c}){var H,Y,Z;const d=(l==null?void 0:l.cover_photo_url)||null,u=(l==null?void 0:l.logo_url)||null,h=(l==null?void 0:l.tagline)||"Your Real Estate Concierge",m=n==null?void 0:n.deal_pipeline,p=m==null?void 0:m.deal_pipeline_stages,f=p==null?void 0:p.is_won_stage,y=m==null?void 0:m.deal_type,v=n==null?void 0:n.stage_mapping;let g=BPe(y);v&&v.length>0&&(g=v.map((ne,ce)=>{var ie,te;return{key:`custom-${ce}`,label:ne.label||((ie=g[ce])==null?void 0:ie.label)||`Stage ${ce+1}`,description:ne.description||((te=g[ce])==null?void 0:te.description)||"",video_url:ne.video_url||void 0}}));const b=v&&v.length>0?Math.min(jAe(p==null?void 0:p.name),g.length-1):jAe(p==null?void 0:p.name),j=g[b],S=j==null?void 0:j.video_url,C=f&&n.show_post_close_tips!==!1&&n.referral_enabled!==!1,E=m!=null&&m.property_address?`${m.property_address}, ${m.city||""}, ${m.state||""}`.replace(/,\s*,/g,",").replace(/,\s*$/,""):null,P=!!t,M=(H=s==null?void 0:s.deal_pipeline)==null?void 0:H.deal_type,I=(Y=t==null?void 0:t.deal_pipeline)==null?void 0:Y.deal_type,D=ne=>ne==="listing"?"Your Sale":ne==="buy-side"?"Your Purchase":"Transaction",O=g.length>1?Math.round((b+1)/g.length*100):0,{data:V=[]}=z7t({id:n==null?void 0:n.id,owner_user_id:n==null?void 0:n.owner_user_id}),G=V.some(ne=>!ne.stage_filter||ne.stage_filter.length===0||!(p!=null&&p.name)?!0:ne.stage_filter.includes(p.name)),$=()=>{var ne;(ne=document.getElementById("trusted-vendors"))==null||ne.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(Sr.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(Rm,{className:"w-3 h-3",style:{color:"hsl(var(--portal-gold))"}}),"Secure & Encrypted"]})]}),e.jsxs(Sr.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(Jr,{className:"w-3 h-3"}),y==="listing"?"Sale":y==="buy-side"?"Purchase":"Transaction",f&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"opacity-50 mx-1",children:"·"}),"Complete"]})]}),e.jsx("h1",{className:"portal-serif leading-[0.95] mb-4",style:{fontSize:"4.5rem",color:"var(--portal-hero-ink)",textShadow:"var(--portal-hero-text-shadow)"},children:(m==null?void 0:m.deal_name)||"Your Transaction"}),e.jsx("div",{className:"portal-hairline w-32 mb-5"}),E&&e.jsxs("div",{className:"flex items-center gap-2",style:{color:"var(--portal-hero-ink-muted)",textShadow:"var(--portal-hero-text-shadow)"},children:[e.jsx(Xa,{className:"w-4 h-4",style:{color:"var(--portal-hero-accent)"}}),e.jsx("span",{className:"text-base",children:E})]}),(n==null?void 0:n.welcome_message)&&e.jsxs("p",{className:"mt-6 portal-serif italic leading-relaxed max-w-2xl",style:{color:"var(--portal-hero-ink-muted)",fontSize:"1.15rem",textShadow:"var(--portal-hero-text-shadow)"},children:["“",n.welcome_message,"”"]})]}),e.jsxs("div",{className:"flex flex-col items-center justify-center",children:[e.jsx(HRs,{pct:O}),e.jsx("p",{className:"portal-eyebrow mt-4",style:{color:"var(--portal-hero-accent)"},children:"Journey Progress"}),e.jsxs("p",{className:"portal-serif mt-1",style:{fontSize:"1.1rem",color:"var(--portal-hero-ink)",textShadow:"var(--portal-hero-text-shadow)"},children:["Stage ",b+1," of ",g.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(ne=>{const ce=ne==="primary"?M:I,ie=r===ne;return e.jsx("button",{onClick:()=>a(ne),className:"portal-serif px-5 py-2 rounded-lg transition-all",style:{fontSize:"1rem",background:ie?"hsl(var(--portal-surface-3))":"transparent",color:ie?"hsl(var(--portal-gold))":"hsl(var(--portal-ink-muted))",borderBottom:ie?"1px solid hsl(var(--portal-gold))":"1px solid transparent"},children:D(ce)},ne)})}),e.jsxs(Sr.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(v5,{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:((Z=i==null?void 0:i.name)==null?void 0:Z.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(BOe,{href:`tel:${i.phone}`,icon:_a,label:"Call",sub:i.phone}),(i==null?void 0:i.phone)&&e.jsx(BOe,{href:`sms:${i.phone}`,icon:Ou,label:"Text message"}),(i==null?void 0:i.email)&&e.jsx(BOe,{href:`mailto:${i.email}`,icon:ln,label:"Email",sub:i.email})]})]}),e.jsxs(v5,{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(UOe,{icon:ga,label:"Target close",value:Cxt(m.target_close_date)}),(m==null?void 0:m.contract_date)&&e.jsx(UOe,{icon:Gr,label:"Under contract",value:Cxt(m.contract_date)}),e.jsx(UOe,{icon:tl,label:"Progress",value:`${O}%`})]})]})]})}),e.jsxs("main",{className:"col-span-6 space-y-5",children:[C&&e.jsx(q7t,{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(M7t,{targetCloseDate:m==null?void 0:m.target_close_date,actualCloseDate:m==null?void 0:m.actual_close_date,clientName:n.client_name}),j&&e.jsx(v5,{children:e.jsx(L7t,{currentStage:j,nextStepText:n.next_step_text,nextStepVideoUrl:S||n.next_step_video_url})}),e.jsx(v5,{children:e.jsx(P7t,{journeyStages:g,currentIndex:b})}),o&&o.length>0&&e.jsx(v5,{children:e.jsx(F7t,{updates:o})}),(n==null?void 0:n.id)&&e.jsx(v5,{children:e.jsx(G7t,{portalId:n.id,clientName:n.client_name,agentName:i==null?void 0:i.name,agentAvatar:i==null?void 0:i.avatar_url})})]}),e.jsxs("aside",{className:"col-span-3 space-y-5",children:[e.jsx(v5,{children:e.jsx(I7t,{deal:m,portal:n})}),(n==null?void 0:n.slug)&&e.jsx(R7t,{slug:n.slug,wrapper:ne=>e.jsx(v5,{children:ne})}),c&&c.length>0&&e.jsx(v5,{children:e.jsx(D7t,{documents:c})}),G&&e.jsx(v5,{children:e.jsxs("button",{onClick:$,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:ne=>{ne.currentTarget.style.background="hsl(var(--portal-gold) / 0.12)"},onMouseLeave:ne=>{ne.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(r$,{className:"w-4 h-4"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"portal-serif",style:{fontSize:"1.05rem",color:"hsl(var(--portal-ink))"},children:"Trusted Vendors"}),e.jsx("p",{className:"text-[10px] tracking-[0.2em] uppercase mt-0.5",style:{color:"hsl(var(--portal-ink-dim))"},children:"My hand-picked network"})]}),e.jsx(tl,{className:"w-4 h-4",style:{color:"hsl(var(--portal-gold))"}})]})}),e.jsxs("div",{className:"text-center pt-2 space-y-2",children:[e.jsx("div",{className:"portal-hairline w-12 mx-auto"}),e.jsx("p",{className:"text-[10px] tracking-[0.25em] uppercase",style:{color:"hsl(var(--portal-ink-dim))"},children:"Powered by ReLevelUp"})]})]})]}),(n==null?void 0:n.id)&&(n==null?void 0:n.owner_user_id)&&e.jsx("div",{id:"trusted-vendors",className:"mt-8 scroll-mt-10",children:e.jsx(U7t,{portalId:n.id,ownerUserId:n.owner_user_id,currentStage:p==null?void 0:p.name,brandingColor:"hsl(var(--portal-gold))",layout:"grid"})})]})]})}function v5({children:s}){return e.jsx(Sr.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 BOe({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 UOe({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 HRs({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(Sr.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 Cxt(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 GRs({portal:s,dealData:t,agentProfile:n,customQuestions:r,deviceFingerprint:a,onComplete:i}){var v,g;const[l,o]=_.useState({first_name:((v=s.client_name)==null?void 0:v.split(" ")[0])||"",last_name:((g=s.client_name)==null?void 0:g.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]=_.useState({}),[u,h]=_.useState(!1),m=mt({mutationFn:async()=>{const{error:b}=await q.from("portal_onboarding_submissions").insert({portal_id:s.id,first_name:l.first_name,last_name:l.last_name||null,email:l.email||null,phone:l.phone||null,preferred_contact_method:l.preferred_contact_method,client_role:l.client_role,notes:l.notes||null,device_fingerprint:a,custom_answers:Object.keys(c).length>0?c:null,spouse_first_name:u&&l.spouse_first_name||null,spouse_last_name:u&&l.spouse_last_name||null,spouse_email:u&&l.spouse_email||null,spouse_phone:u&&l.spouse_phone||null});if(b)throw b},onSuccess:i,onError:b=>{console.error("[PortalOnboarding] Submit failed:",b),se.error("Something went wrong. Please try again.")}}),p=t!=null&&t.property_address?`${t.property_address}, ${t.city||""}, ${t.state||""}`:null,f="mt-1 rounded-xl bg-white text-slate-900 placeholder:text-slate-400 border-slate-200 focus-visible:ring-slate-400",y="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(Xa,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:p.replace(/,\s*,/g,",").replace(/,\s*$/,"")})]}),e.jsx("p",{className:"text-sm text-slate-600 mt-2",children:"Please fill in your details to access your transaction portal."})]}),e.jsxs("form",{onSubmit:b=>{b.preventDefault(),m.mutate()},className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(J,{className:"text-xs font-medium text-slate-700",children:"First Name *"}),e.jsx(xe,{required:!0,value:l.first_name,onChange:b=>o(j=>({...j,first_name:b.target.value})),className:f,placeholder:"John"})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs font-medium text-slate-700",children:"Last Name"}),e.jsx(xe,{value:l.last_name,onChange:b=>o(j=>({...j,last_name:b.target.value})),className:f,placeholder:"Doe"})]})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs font-medium text-slate-700",children:"Email"}),e.jsx(xe,{type:"email",value:l.email,onChange:b=>o(j=>({...j,email:b.target.value})),className:f,placeholder:"john@example.com"})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs font-medium text-slate-700",children:"Phone"}),e.jsx(xe,{type:"tel",value:l.phone,onChange:b=>o(j=>({...j,phone:b.target.value})),className:f,placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs font-medium text-slate-700",children:"Preferred Contact Method"}),e.jsx("div",{className:"flex gap-2 mt-1.5",children:[{value:"email",label:"Email"},{value:"call",label:"Phone"},{value:"text",label:"Text"}].map(b=>e.jsx("button",{type:"button",onClick:()=>o(j=>({...j,preferred_contact_method:b.value})),className:`px-3.5 py-1.5 rounded-full text-xs font-medium border transition-colors ${l.preferred_contact_method===b.value?"bg-slate-800 text-white border-slate-800":"bg-white text-slate-600 border-slate-200 hover:border-slate-300"}`,children:b.label},b.value))})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs font-medium text-slate-700",children:"Your Role"}),e.jsx("div",{className:"flex gap-2 mt-1.5",children:["buyer","seller","both"].map(b=>e.jsx("button",{type:"button",onClick:()=>o(j=>({...j,client_role:b})),className:`px-3.5 py-1.5 rounded-full text-xs font-medium border transition-colors ${l.client_role===b?"bg-slate-800 text-white border-slate-800":"bg-white text-slate-600 border-slate-200 hover:border-slate-300"}`,children:b.charAt(0).toUpperCase()+b.slice(1)},b))})]}),r.map(b=>e.jsxs("div",{children:[e.jsxs(J,{className:"text-xs font-medium text-slate-700",children:[b.question_text," ",b.is_required&&"*"]}),b.field_type==="text"&&e.jsx(xe,{required:b.is_required,value:c[b.id]||"",onChange:j=>d(S=>({...S,[b.id]:j.target.value})),className:f}),b.field_type==="textarea"&&e.jsx("textarea",{required:b.is_required,value:c[b.id]||"",onChange:j=>d(S=>({...S,[b.id]:j.target.value})),className:`${y} min-h-[80px]`}),b.field_type==="dropdown"&&e.jsxs("select",{required:b.is_required,value:c[b.id]||"",onChange:j=>d(S=>({...S,[b.id]:j.target.value})),className:`${y} h-10`,children:[e.jsx("option",{value:"",children:"Select..."}),(b.options||[]).map(j=>e.jsx("option",{value:j,children:j},j))]}),b.field_type==="toggle"&&e.jsx("div",{className:"mt-1.5 flex gap-2",children:["Yes","No"].map(j=>e.jsx("button",{type:"button",onClick:()=>d(S=>({...S,[b.id]:j})),className:`px-3.5 py-1.5 rounded-full text-xs font-medium border transition-colors ${c[b.id]===j?"bg-slate-800 text-white border-slate-800":"bg-white text-slate-600 border-slate-200"}`,children:j},j))})]},b.id)),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs font-medium text-slate-700",children:"Notes for your agent"}),e.jsx("textarea",{value:l.notes,onChange:b=>o(j=>({...j,notes:b.target.value})),className:`${y} 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(J,{className:"text-xs font-medium text-slate-700",children:"First Name"}),e.jsx(xe,{value:l.spouse_first_name,onChange:b=>o(j=>({...j,spouse_first_name:b.target.value})),className:f})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs font-medium text-slate-700",children:"Last Name"}),e.jsx(xe,{value:l.spouse_last_name,onChange:b=>o(j=>({...j,spouse_last_name:b.target.value})),className:f})]})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs font-medium text-slate-700",children:"Email"}),e.jsx(xe,{type:"email",value:l.spouse_email,onChange:b=>o(j=>({...j,spouse_email:b.target.value})),className:f})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs font-medium text-slate-700",children:"Phone"}),e.jsx(xe,{type:"tel",value:l.spouse_phone,onChange:b=>o(j=>({...j,spouse_phone:b.target.value})),className:f})]})]})]}),e.jsx(B,{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 WRs(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 K7t(){const s=ha();return at({queryKey:["agent-portal-branding",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("agent_portal_branding").select("*").eq("user_id",s).maybeSingle();if(n)throw n;return t},enabled:!!s})}function KRs(s){return at({queryKey:["agent-portal-branding-public",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("agent_portal_branding").select("logo_url, cover_photo_url, brand_color, accent_color, tagline, welcome_message, portal_theme").eq("user_id",s).maybeSingle();if(n)throw n;return t},enabled:!!s})}function YRs(){const s=ha(),t=Bt();return mt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("agent_portal_branding").upsert({user_id:s,...n},{onConflict:"user_id"}).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["agent-portal-branding",s]}),t.invalidateQueries({queryKey:["agent-portal-branding-public",s]})}})}async function Y7t(s,t,n){var o;const r=((o=t.name.split(".").pop())==null?void 0:o.toLowerCase())||"png",a=`${s}/${n}-${Date.now()}.${r}`,{error:i}=await q.storage.from("portal-branding").upload(a,t,{upsert:!0,cacheControl:"3600"});if(i)throw i;const{data:l}=q.storage.from("portal-branding").getPublicUrl(a);return l.publicUrl}function ZRs(s,t){return at({queryKey:["client-portal-public",s],queryFn:async()=>{if(!s)return null;const{data:n,error:r}=await q.from("client_portals").select(` *, deal_pipeline ( id, deal_name, property_address, city, state, deal_type, target_close_date, contract_date, expected_price, actual_close_date, earnest_money_due_date, inspection_date, inspection_contingency_date, appraisal_date, loan_approval_date, title_docs_due_date, final_walkthrough_date, completed_key_dates, stage_id, owner_user_id, deal_pipeline_stages (id, name, color, icon, sort_order, is_won_stage, is_lost_stage) ) `).eq("slug",s).eq("is_enabled",!0).maybeSingle();if(r)throw r;return n},enabled:t})}function XRs(s){return at({queryKey:["client-portal-by-id",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("client_portals").select(` *, deal_pipeline ( id, deal_name, property_address, city, state, deal_type, target_close_date, contract_date, expected_price, actual_close_date, earnest_money_due_date, inspection_date, inspection_contingency_date, appraisal_date, loan_approval_date, title_docs_due_date, final_walkthrough_date, completed_key_dates, stage_id, owner_user_id, deal_pipeline_stages (id, name, color, icon, sort_order, is_won_stage, is_lost_stage) ) `).eq("id",s).eq("is_enabled",!0).maybeSingle();if(n)throw n;return t},enabled:!!s})}function Z7t({slug:s}){var ne,ce,ie,te,ae,le;const[t,n]=_.useState(!1),[r,a]=_.useState("primary"),[i]=_.useState(()=>{const be=`portal_fp_${s}`;let me=localStorage.getItem(be);return me||(me=localStorage.getItem("portal_fp"),me?localStorage.setItem(be,me):(me=crypto.randomUUID(),localStorage.setItem(be,me),localStorage.setItem("portal_fp",me))),me});_.useEffect(()=>(document.body.classList.add("client-portal-page"),()=>document.body.classList.remove("client-portal-page")),[]);const{data:l,isLoading:o,error:c}=ZRs(s,!0),d=l==null?void 0:l.linked_portal_id,{data:u}=XRs(d),h=(ne=l==null?void 0:l.deal_pipeline)==null?void 0:ne.owner_user_id;at({queryKey:["portal-stages",h],queryFn:async()=>{const{data:be,error:me}=await q.from("deal_pipeline_stages").select("*").eq("owner_user_id",h).order("sort_order",{ascending:!0});if(me)throw me;return be},enabled:!!h});const{data:m}=at({queryKey:["portal-agent",h],queryFn:async()=>{const{data:be,error:me}=await q.from("profiles").select("id, name, avatar_url, phone, email").eq("id",h).single();if(me)throw me;return be},enabled:!!h}),{data:p}=KRs(h),f=r==="linked"&&u?u:l,y=f==null?void 0:f.id,v=WRs(p,f==null?void 0:f.branding_override),g=v.portal_theme==="azure"?"azure":"noir";_.useEffect(()=>{const be=`portal-theme-${g}`;return document.body.classList.add(be),()=>document.body.classList.remove(be)},[g]);const{data:b}=at({queryKey:["portal-updates-public",y],queryFn:async()=>{const{data:be,error:me}=await q.from("portal_updates").select("*").eq("portal_id",y).order("created_at",{ascending:!1});if(me)throw me;return be},enabled:!!y}),j=(ce=f==null?void 0:f.deal_pipeline)==null?void 0:ce.id,{data:S}=at({queryKey:["portal-documents",j],queryFn:async()=>{const{data:be,error:me}=await q.from("deal_files").select("*").eq("deal_id",j).eq("visible_on_portal",!0).order("created_at",{ascending:!1});if(me)throw me;return be},enabled:!!j}),C=l==null?void 0:l.id,E=C?`portal_onboarded_${C}_${i}`:null,P=E?localStorage.getItem(E)==="1":!1,{data:M,isLoading:I}=at({queryKey:["portal-onboarding-check",C,i],queryFn:async()=>{const{data:be,error:me}=await q.from("portal_onboarding_submissions").select("id").eq("portal_id",C).eq("device_fingerprint",i).maybeSingle();if(me)throw me;return be&&E&&localStorage.setItem(E,"1"),be},enabled:!!C&&!!(l!=null&&l.require_onboarding)&&!P,staleTime:5*60*1e3}),D=!!(l!=null&&l.require_onboarding)&&!P&&!M&&!t,{data:O}=at({queryKey:["portal-custom-questions-public",h],queryFn:async()=>{const{data:be,error:me}=await q.from("portal_custom_questions").select("*").eq("owner_user_id",h).eq("is_active",!0).order("sort_order",{ascending:!0});if(me)throw me;return be},enabled:!!h&&D}),V=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(Ct,{className:"w-6 h-6 animate-spin",style:{color:"hsl(var(--portal-gold))"}})});if(c||!l)return e.jsx("div",{className:"min-h-screen flex items-center justify-center p-6",style:{background:"var(--portal-gradient-noir)"},children:e.jsxs("div",{className:"text-center max-w-md",children:[e.jsx("div",{className:"w-16 h-16 rounded-full flex items-center justify-center mx-auto mb-6",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.3)"},children:e.jsx(Rm,{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(!V){const be=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(GRs,{portal:l,dealData:be,agentProfile:m,customQuestions:O||[],deviceFingerprint:i,onComplete:()=>{E&&localStorage.setItem(E,"1"),n(!0)}})})}const G=(ie=l==null?void 0:l.deal_pipeline)==null?void 0:ie.deal_type,$=(te=u==null?void 0:u.deal_pipeline)==null?void 0:te.deal_type,H=!!u,Y=be=>be==="listing"?"Your Sale":be==="buy-side"?"Your Purchase":"Transaction",Z=be=>be==="listing"?e.jsx(Jr,{className:"w-3.5 h-3.5"}):e.jsx(_b,{className:"w-3.5 h-3.5"});return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"hidden lg:block",children:e.jsx(VRs,{portal:l,linkedPortal:u,activePortal:f,activeTab:r,onTabChange:a,agentProfile:m,branding:v,updates:b,documents:S})}),e.jsxs("div",{className:"lg:hidden min-h-screen pb-16",style:{background:"var(--portal-gradient-noir)"},children:[e.jsx(ERs,{dealData:f==null?void 0:f.deal_pipeline,agentProfile:m,welcomeMessage:(f==null?void 0:f.welcome_message)||v.welcome_message,isWon:(le=(ae=f==null?void 0:f.deal_pipeline)==null?void 0:ae.deal_pipeline_stages)==null?void 0:le.is_won_stage,branding:v}),e.jsxs("div",{className:"max-w-lg mx-auto px-4 space-y-5 mt-8",children:[H&&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(be=>{const me=r===be,he=be==="primary"?G:$;return e.jsxs("button",{onClick:()=>a(be),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:me?"hsl(var(--portal-surface-3))":"transparent",color:me?"hsl(var(--portal-gold))":"hsl(var(--portal-ink-muted))",boxShadow:me?"0 1px 0 hsl(var(--portal-gold) / 0.3) inset":"none"},children:[Z(he),e.jsx("span",{style:{fontSize:"1rem"},children:Y(he)})]},be)})}),e.jsx(QRs,{portal:f,updates:b,documents:S,agentProfile:m}),y&&e.jsx("div",{className:"rounded-2xl p-5",style:{background:"hsl(var(--portal-surface))",border:"1px solid hsl(var(--portal-gold) / 0.14)"},children:e.jsx(G7t,{portalId:y,clientName:f==null?void 0:f.client_name,agentName:m==null?void 0:m.name,agentAvatar:m==null?void 0:m.avatar_url,deviceFingerprint:i})}),e.jsxs("div",{className:"text-center pt-8 pb-2 space-y-3",children:[e.jsx("div",{className:"portal-hairline w-16 mx-auto"}),e.jsxs("div",{className:"flex items-center justify-center gap-1.5",style:{color:"hsl(var(--portal-ink-dim))"},children:[e.jsx(Rm,{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 QRs({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=BPe(c);d&&d.length>0&&(u=d.map((y,v)=>{var g,b;return{key:`custom-${v}`,label:y.label||((g=u[v])==null?void 0:g.label)||`Stage ${v+1}`,description:y.description||((b=u[v])==null?void 0:b.description)||"",video_url:y.video_url||void 0}}));const h=d&&d.length>0?Math.min(jAe(l==null?void 0:l.name),u.length-1):jAe(l==null?void 0:l.name),m=u[h],p=m==null?void 0:m.video_url,f=o&&s.show_post_close_tips!==!1&&s.referral_enabled!==!1;return e.jsxs(e.Fragment,{children:[f&&e.jsx(q7t,{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(M7t,{targetCloseDate:i==null?void 0:i.target_close_date,actualCloseDate:i==null?void 0:i.actual_close_date,clientName:s.client_name}),e.jsx(P7t,{journeyStages:u,currentIndex:h}),m&&e.jsx(L7t,{currentStage:m,nextStepText:s.next_step_text,nextStepVideoUrl:p||s.next_step_video_url}),e.jsx(I7t,{deal:i,portal:s}),(s==null?void 0:s.slug)&&e.jsx(R7t,{slug:s.slug}),n&&n.length>0&&e.jsx(D7t,{documents:n}),(s==null?void 0:s.id)&&(s==null?void 0:s.owner_user_id)&&e.jsx(U7t,{portalId:s.id,ownerUserId:s.owner_user_id,currentStage:l==null?void 0:l.name}),t&&t.length>0&&e.jsx(F7t,{updates:t})]})}function X7t({slug:s}){const t=Li(),n=s||t.slug,[r,a]=_.useState(!1),[i,l]=_.useState(!1),[o,c]=_.useState(""),[d,u]=_.useState(""),[h,m]=_.useState(""),[p,f]=_.useState(""),[y,v]=_.useState(""),[g,b]=_.useState("buying"),[j,S]=_.useState("");_.useEffect(()=>(document.body.classList.add("client-portal-page"),()=>document.body.classList.remove("client-portal-page")),[]);const{data:C,isLoading:E,error:P}=at({queryKey:["portal-referral-target",n],queryFn:async()=>{if(!n)return null;const{data:D,error:O}=await q.from("client_portals").select(` id, slug, owner_user_id, client_name, referral_enabled, referral_reward_text, referral_cta_headline, is_enabled `).eq("slug",n).eq("is_enabled",!0).maybeSingle();if(O)throw O;return D},enabled:!!n}),{data:M}=at({queryKey:["portal-referral-agent",C==null?void 0:C.owner_user_id],queryFn:async()=>{const{data:D}=await q.from("profiles").select("id, name, avatar_url").eq("id",C.owner_user_id).single();return D},enabled:!!(C!=null&&C.owner_user_id)}),I=async D=>{if(D.preventDefault(),!C||!h.trim()){se.error("Please enter your friend's name");return}if(!p.trim()&&!y.trim()){se.error("Please add at least an email or phone for your friend");return}a(!0);try{const{error:O}=await q.from("portal_referrals").insert({portal_id:C.id,owner_user_id:C.owner_user_id,referrer_name:o.trim()||C.client_name||null,referrer_email:d.trim()||null,friend_name:h.trim(),friend_email:p.trim()||null,friend_phone:y.trim()||null,friend_interest:g,friend_message:j.trim()||null});if(O)throw O;l(!0)}catch(O){se.error(O.message||"Could not submit referral")}finally{a(!1)}};return E?e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center",children:e.jsx(cn,{className:"h-96 w-full max-w-lg rounded-2xl mx-4"})}):P||!C||!C.referral_enabled?e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-16 h-16 bg-slate-100 rounded-full flex items-center justify-center mx-auto mb-4",children:e.jsx("span",{className:"text-2xl",children:"🔒"})}),e.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Referral Page Unavailable"}),e.jsx("p",{className:"text-slate-500",children:"This referral link is no longer active."})]})}):i?e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-emerald-50 via-teal-50 to-white flex items-center justify-center p-6",children:e.jsxs("div",{className:"max-w-md w-full bg-white rounded-2xl shadow-xl p-8 text-center",children:[e.jsx("div",{className:"w-16 h-16 bg-emerald-100 rounded-full flex items-center justify-center mx-auto mb-4",children:e.jsx(ea,{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(Vo,{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(Vo,{className:"w-3 h-3"})," Referral"]}),e.jsx("h1",{className:"text-2xl font-bold tracking-tight mb-1 font-serif",children:C.referral_cta_headline||"Refer a Friend"}),e.jsxs("p",{className:"text-sm text-white/70",children:["Send ",(M==null?void 0:M.name)||"your agent"," someone you trust."]}),C.referral_reward_text&&e.jsxs("p",{className:"text-xs text-white/60 mt-2",children:["You'll get: ",e.jsx("span",{className:"text-white font-medium",children:C.referral_reward_text})," when they close."]})]})]}),e.jsx("div",{className:"max-w-lg mx-auto px-4 -mt-6 relative z-10",children:e.jsxs("form",{onSubmit: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(J,{htmlFor:"friend_name",className:"text-sm",children:["Their name ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(xe,{id:"friend_name",value:h,onChange: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(J,{htmlFor:"friend_email",className:"text-sm",children:"Email"}),e.jsx(xe,{id:"friend_email",type:"email",value:p,onChange:D=>f(D.target.value),placeholder:"jane@email.com",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"friend_phone",className:"text-sm",children:"Phone"}),e.jsx(xe,{id:"friend_phone",type:"tel",value:y,onChange:D=>v(D.target.value),placeholder:"(555) 123-4567",className:"mt-1"})]})]}),e.jsx("p",{className:"text-[11px] text-slate-400",children:"Add at least an email or phone so we can reach them."}),e.jsxs("div",{children:[e.jsx(J,{className:"text-sm",children:"They're interested in..."}),e.jsx("div",{className:"mt-2 grid grid-cols-2 gap-2",children:[{v:"buying",l:"Buying"},{v:"selling",l:"Selling"},{v:"both",l:"Both"},{v:"unsure",l:"Not sure"}].map(D=>e.jsx("button",{type:"button",onClick:()=>b(D.v),className:`rounded-lg border px-3 py-2 text-sm font-medium transition-colors ${g===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(J,{htmlFor:"friend_message",className:"text-sm",children:"A note (optional)"}),e.jsx("textarea",{id:"friend_message",value:j,onChange:D=>S(D.target.value),placeholder:"They're moving from Boston in the spring...",rows:3,className:"mt-1 w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"})]})]})]}),e.jsxs("div",{className:"border-t pt-4",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-slate-500 mb-3",children:"Your info"}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(J,{htmlFor:"referrer_name",className:"text-sm",children:"Your name"}),e.jsx(xe,{id:"referrer_name",value:o,onChange:D=>c(D.target.value),placeholder:C.client_name||"Your name",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"referrer_email",className:"text-sm",children:"Your email"}),e.jsx(xe,{id:"referrer_email",type:"email",value:d,onChange:D=>u(D.target.value),placeholder:"So we can thank you!",className:"mt-1"})]})]})]}),e.jsxs("button",{type:"submit",disabled:r,className:"w-full bg-[#406E71] hover:bg-[#345e7a] disabled:opacity-60 text-white font-semibold rounded-xl py-3.5 px-4 flex items-center justify-center gap-2 transition-colors",children:[r?e.jsx(Ct,{className:"w-4 h-4 animate-spin"}):e.jsx(Vo,{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 JRs(){const t=ru().pathname.slice(1).replace(/\/$/,"");if(_.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(X7t,{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(Z7t,{slug:t})}function eFs(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 NAe({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=_.useMemo(()=>eFs(Array.isArray(s)?s:[]),[s]),[l,o]=_.useState(0);return _.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(Jr,{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 Q7t({comp:s,open:t,onClose:n}){var d;const[r,a]=_.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(Ls,{open:t,onOpenChange:u=>{u||n()},children:e.jsxs(Ps,{className:"max-w-4xl max-h-[90vh] overflow-y-auto p-0",children:[e.jsxs(Os,{className:"px-6 pt-6 pb-2",children:[e.jsx(Ds,{className:"text-xl",children:s.address}),e.jsxs("div",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[e.jsx(Xa,{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(NAe,{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(NAe,{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(Jr,{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(yd,{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(Oe,{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(qOe,{label:"Active",date:c(s.listDate),active:!0}),e.jsx(qOe,{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(qOe,{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(wle,{icon:e.jsx(dj,{className:"w-4 h-4"}),label:"Beds",value:s.bedrooms??"—"}),e.jsx(wle,{icon:e.jsx(S0,{className:"w-4 h-4"}),label:"Baths",value:s.bathrooms??"—"}),e.jsx(wle,{icon:e.jsx(W4,{className:"w-4 h-4"}),label:"SqFt",value:((d=s.sqft)==null?void 0:d.toLocaleString())??"—"}),e.jsx(wle,{icon:e.jsx(ga,{className:"w-4 h-4"}),label:"Year Built",value:s.yearBuilt??"—"})]}),e.jsxs("div",{className:"px-6 pt-4 grid sm:grid-cols-2 gap-x-6 gap-y-2 text-sm",children:[e.jsx(K1,{label:"MLS #",value:s.mlsNumber}),e.jsx(K1,{label:"Property Type",value:s.propertySubType||s.propertyType}),e.jsx(K1,{label:"Lot Size",value:s.lotSize}),e.jsx(K1,{label:"Garage",value:s.garageSpaces}),e.jsx(K1,{label:"Stories",value:s.stories}),e.jsx(K1,{label:"HOA",value:s.hoaFee?`$${s.hoaFee}/${(s.hoaFrequency||"mo").toLowerCase()}`:null}),e.jsx(K1,{label:"Tax (annual)",value:s.taxAmount?`$${s.taxAmount.toLocaleString()}`:null}),e.jsx(K1,{label:"Heating",value:s.heating}),e.jsx(K1,{label:"Cooling",value:s.cooling}),e.jsx(K1,{label:"Parking",value:s.parking}),e.jsx(K1,{label:"Elementary",value:s.elementarySchool}),e.jsx(K1,{label:"Middle",value:s.middleSchool}),e.jsx(K1,{label:"High",value:s.highSchool}),e.jsx(K1,{label:"Listed By",value:s.listAgentFullName}),e.jsx(K1,{label:"Office",value:s.listOfficeName})]}),s.description&&e.jsxs("div",{className:"px-6 pt-4",children:[e.jsx("div",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground mb-1",children:"Description"}),e.jsx("p",{className:"text-sm leading-relaxed whitespace-pre-wrap",children:s.description})]}),e.jsx("div",{className:"px-6 py-4"})]})})}function wle({icon:s,label:t,value:n}){return e.jsxs("div",{className:"rounded-lg border bg-card p-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[s,t]}),e.jsx("div",{className:"text-lg font-semibold mt-0.5",children:n})]})}function K1({label:s,value:t}){return t==null||t===""||t===0?null:e.jsxs("div",{className:"flex justify-between border-b border-dashed py-1",children:[e.jsx("span",{className:"text-muted-foreground",children:s}),e.jsx("span",{className:"font-medium text-right ml-3 truncate",children:String(t)})]})}function qOe({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 jle({to:s,durationMs:t=1400,prefix:n="",suffix:r="",className:a,delayMs:i=0}){const[l,o]=_.useState(0),c=_.useRef(null);return _.useEffect(()=>{if(!Number.isFinite(s))return;let d=0;const u=0,h=p=>1-Math.pow(1-p,3),m=setTimeout(()=>{const p=f=>{d||(d=f);const y=f-d,v=Math.min(1,y/t);o(Math.round(u+(s-u)*h(v))),v<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 tFs({low:s,likely:t,high:n,defaultMortgage:r=0,defaultCommissionPct:a=6,defaultClosingPct:i=1}){const[l,o]=_.useState(t),[c,d]=_.useState(r),[u,h]=_.useState(a),[m,p]=_.useState(i),{commission:f,closing:y,net:v}=_.useMemo(()=>{const j=Math.round(l*u/100),S=Math.round(l*m/100);return{commission:j,closing:S,net:Math.max(0,l-j-S-(c||0))}},[l,u,m,c]),g=j=>`$${j.toLocaleString()}`,b=n>s?(l-s)/(n-s)*100:50;return e.jsxs(ve,{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(Nl,{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(Me,{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:g(l)})]}),e.jsxs("div",{className:"relative",children:[e.jsx(kx,{value:[l],min:s,max:n,step:1e3,onValueChange:([j])=>o(j)}),e.jsxs("div",{className:"flex justify-between text-[10px] text-muted-foreground mt-2",children:[e.jsx("span",{children:g(s)}),e.jsxs("span",{children:["Suggested ",g(t)]}),e.jsx("span",{children:g(n)})]})]}),e.jsx("div",{className:"mt-2 h-1.5 rounded-full bg-muted overflow-hidden",children:e.jsx("div",{className:"h-full bg-gradient-to-r from-emerald-500 via-primary to-amber-500 transition-all",style:{width:`${Math.min(100,Math.max(0,b))}%`}})})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Mortgage payoff"}),e.jsx(xe,{type:"number",inputMode:"numeric",value:c||"",placeholder:"$0",onChange:j=>d(Number(j.target.value)||0)})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Commission %"}),e.jsx(xe,{type:"number",step:"0.25",value:u,onChange:j=>h(Number(j.target.value)||0)})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Closing costs %"}),e.jsx(xe,{type:"number",step:"0.25",value:m,onChange:j=>p(Number(j.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:g(l)}),e.jsxs("span",{className:"text-muted-foreground",children:["Commission (",u,"%)"]}),e.jsxs("span",{className:"text-right tabular-nums text-rose-600",children:["−",g(f)]}),e.jsxs("span",{className:"text-muted-foreground",children:["Closing (",m,"%)"]}),e.jsxs("span",{className:"text-right tabular-nums text-rose-600",children:["−",g(y)]}),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:["−",g(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(m7,{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:g(v)})]})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground leading-relaxed",children:"This is a rough estimate to help you think through pricing. Actual proceeds depend on title fees, prorations, repairs, and other items your agent will walk through in detail."})]})]})}function J7t({tokenOverride:s}={}){var Pe,ze,ke,Ze,Se,Fe,Ne,Ye,Ve,qe,Qe,Ue;const t=Li(),n=s??t.token,[r,a]=_.useState(null),[i,l]=_.useState(null),[o,c]=_.useState([]),[d,u]=_.useState(!0),[h,m]=_.useState(""),[p,f]=_.useState(""),[y,v]=_.useState(""),[g,b]=_.useState(!1),[j,S]=_.useState(!1),[C,E]=_.useState(null),[P,M]=_.useState(null),[I,D]=_.useState(!1),{toast:O}=vi();_.useEffect(()=>{n&&(async()=>{const{data:Xe}=await q.from("cmas").select("*").eq("share_token",n).eq("status","shared").maybeSingle();if(!Xe){u(!1);return}a(Xe);const[{data:nt},{data:$e}]=await Promise.all([q.from("cma_comps").select("*").eq("cma_id",Xe.id).order("position"),q.from("profiles").select("id,name,email,phone,avatar_url,brokerage_name,website_url,title,bio").eq("id",Xe.agent_id).maybeSingle()]);c((nt||[]).filter(ct=>ct.selected)),l($e);const Ge=localStorage.getItem("cma_visitor_token")||crypto.randomUUID();localStorage.setItem("cma_visitor_token",Ge),await q.from("cma_views").insert({cma_id:Xe.id,visitor_token:Ge,user_agent:navigator.userAgent}),u(!1)})()},[n]);const V=async Xe=>{if(!r)return;const nt=localStorage.getItem("cma_visitor_token")||"";await q.from("cma_views").insert({cma_id:r.id,visitor_token:nt,reactions:{[Xe]:!0}}),q.functions.invoke("cma-reply-notify",{body:{shareToken:n,reaction:Xe,visitorToken:nt}}).catch(()=>{}),O({title:"Thanks — your agent just got notified ✨"})},G=!(r!=null&&r.contact_id),$=async()=>{if(!r||!h.trim())return;if(G&&(!p.trim()||!y.trim())){O({title:"Please add your name and email",variant:"destructive"});return}b(!0);const Xe=localStorage.getItem("cma_visitor_token")||"",{data:nt,error:$e}=await q.functions.invoke("cma-reply-notify",{body:{shareToken:n,message:h,visitorToken:Xe,viewerName:p.trim()||void 0,viewerEmail:y.trim()||void 0}});if(b(!1),$e||!(nt!=null&&nt.success)){O({title:"Could not send",description:($e==null?void 0:$e.message)||(nt==null?void 0:nt.error),variant:"destructive"});return}m(""),S(!0),O({title:"Message sent to your agent"})},H=_.useMemo(()=>{const Xe=o.map(nt=>{const $e=nt.snapshot,Ge=($e==null?void 0:$e.soldPrice)||($e==null?void 0:$e.price);return Ge&&($e!=null&&$e.sqft)?Ge/$e.sqft:null}).filter(nt=>!!nt).sort((nt,$e)=>nt-$e);return Xe.length?Math.round(Xe[Math.floor(Xe.length/2)]):null},[o]);if(d)return e.jsx("div",{className:"min-h-screen flex items-center justify-center",children:e.jsx(Ct,{className:"w-8 h-8 animate-spin"})});if(!r)return e.jsx("div",{className:"min-h-screen flex items-center justify-center text-center p-6",children:e.jsxs("div",{children:[e.jsx(Jr,{className:"w-12 h-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h1",{className:"text-xl font-semibold",children:"CMA not found"}),e.jsx("p",{className:"text-muted-foreground",children:"This report may have been removed or unpublished."})]})});const Y=r.subject||{},Z=(Pe=r.settings)==null?void 0:Pe.personalVideo,ne=(ze=Y.photos)==null?void 0:ze[0],ce=r.contact_first_name?r.contact_first_name:null,ie=((i==null?void 0:i.name)||"A").split(" ").map(Xe=>Xe[0]).slice(0,2).join("").toUpperCase(),te=i!=null&&i.phone?`tel:${String(i.phone).replace(/[^\d+]/g,"")}`:null,ae=i!=null&&i.email?`mailto:${i.email}`:null,le=i!=null&&i.phone?`sms:${String(i.phone).replace(/[^\d+]/g,"")}`:null,be=r.price_low??null,me=r.price_likely??null,he=r.price_high??null,pe=be&&me&&he,Ce=me&&Y.sqft?Math.round(me/Y.sqft):null,Ae=Ce&&H?Math.round((Ce-H)/H*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:ie}),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:[te&&e.jsx(B,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:te,children:[e.jsx(_a,{className:"w-4 h-4 mr-1"}),"Call"]})}),ae&&e.jsx(B,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:ae,children:[e.jsx(ln,{className:"w-4 h-4 mr-1"}),"Email"]})})]})]})}),e.jsxs("div",{className:"relative overflow-hidden",children:[ne?e.jsxs("div",{className:"absolute inset-0",children:[e.jsx("img",{src:ne,alt:Y.address,className:"w-full h-full object-cover scale-110 animate-[kenburns_18s_ease-out_infinite_alternate]",style:{animation:"kenburns 22s ease-in-out infinite alternate"}}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-slate-950/85 via-slate-900/75 to-primary/60"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-background via-background/20 to-transparent"})]}):e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-primary/30 via-primary/10 to-background"}),e.jsx("style",{children:` @keyframes kenburns { 0% { transform: scale(1.08) translate(0, 0); } 100% { transform: scale(1.18) translate(-1.5%, -1%); } } `}),e.jsx("div",{className:"relative container mx-auto max-w-6xl px-4 md:px-8 pt-12 md:pt-20 pb-16 md:pb-24",children:e.jsxs("div",{className:"grid md:grid-cols-5 gap-8 items-center",children:[e.jsxs("div",{className:`${Z!=null&&Z.url?"md:col-span-3":"md:col-span-5"} text-white animate-fade-in`,children:[e.jsxs(Oe,{className:"mb-4 bg-white/15 text-white border-white/20 backdrop-blur-sm hover:bg-white/20",children:[e.jsx(un,{className:"w-3 h-3 mr-1"}),ce?`Prepared for ${ce}`:r.buyer_mode?"Your Buyer Analysis":"Your Market Analysis"]}),e.jsx("h1",{className:"text-3xl md:text-5xl lg:text-6xl font-bold leading-[1.05] tracking-tight",children:Y.address}),e.jsxs("p",{className:"text-white/70 mt-2 text-base md:text-lg flex items-center gap-2",children:[e.jsx(Xa,{className:"w-4 h-4"}),Y.city,", ",Y.state," ",Y.zip]}),pe&&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(jle,{to:me,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(jle,{to:be,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(jle,{to:me,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(jle,{to:he,prefix:"$",delayMs:800})})]})]})]})]}),(Z==null?void 0:Z.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:[Z.thumb?e.jsx("img",{src:Z.thumb,alt:"",className:"w-full h-full object-cover"}):e.jsx("video",{src:Z.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(Jd,{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&&(Z==null?void 0:Z.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:Xe=>Xe.stopPropagation(),children:[e.jsx("video",{src:Z.url,controls:!0,autoPlay:!0,className:"w-full rounded-xl"}),e.jsx(B,{variant:"ghost",className:"absolute -top-12 right-0 text-white hover:bg-white/10",onClick:()=>D(!1),children:"Close"})]})}),e.jsxs("div",{className:"container mx-auto max-w-6xl px-4 md:px-8 py-10 md:py-16 space-y-10 md:space-y-14",children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 md:gap-4 -mt-20 md:-mt-24 relative z-10",children:[{label:"Beds",value:Y.bedrooms??"—"},{label:"Baths",value:Y.bathrooms??"—"},{label:"Sq Ft",value:((Ze=Y.sqft)==null?void 0:Ze.toLocaleString())??"—"},{label:"Year Built",value:Y.yearBuilt??"—"}].map((Xe,nt)=>e.jsx(ve,{className:"shadow-lg animate-fade-in",style:{animationDelay:`${nt*80}ms`},children:e.jsxs(Me,{className:"p-4 md:p-6 text-center",children:[e.jsx("div",{className:"text-2xl md:text-3xl font-bold",children:Xe.value}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1 uppercase tracking-wider",children:Xe.label})]})},nt))}),((Fe=(Se=r.settings)==null?void 0:Se.priceOverride)==null?void 0:Fe.enabled)&&((Ye=(Ne=r.settings)==null?void 0:Ne.priceOverride)==null?void 0:Ye.note)&&e.jsx(ve,{className:"border-primary/30 bg-gradient-to-br from-primary/5 to-transparent",children:e.jsxs(Me,{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})]})}),pe&&e.jsx(tFs,{low:be,likely:me,high:he}),H&&Ce&&e.jsxs("div",{className:"grid md:grid-cols-3 gap-4",children:[e.jsx(ve,{className:"md:col-span-2",children:e.jsxs(Me,{className:"p-6 md:p-8",children:[e.jsx("p",{className:"text-xs uppercase tracking-widest text-primary font-semibold mb-2",children:"Why this price"}),e.jsx("h2",{className:"text-2xl md:text-3xl font-bold mb-3",children:"The market is talking."}),e.jsxs("p",{className:"text-muted-foreground leading-relaxed",children:["Based on ",e.jsxs("strong",{className:"text-foreground",children:[o.length," comparable ",o.length===1?"home":"homes"]})," in ",Y.city,", the median sale rate is ",e.jsxs("strong",{className:"text-foreground",children:["$",H,"/sqft"]}),". Applied to your home's ",(Ve=Y.sqft)==null?void 0:Ve.toLocaleString()," sqft, the comps support a value near ",e.jsxs("strong",{className:"text-foreground",children:["$",(H*(Y.sqft||0)).toLocaleString()]}),". Your agent's suggested price reflects local nuance and condition."]})]})}),e.jsx(ve,{className:"bg-gradient-to-br from-primary/10 to-primary/5 border-primary/20",children:e.jsxs(Me,{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:["$",Ce,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:["$",H,"/sqft"]})]}),Ae!==null&&Ae!==0&&e.jsxs("p",{className:`text-sm font-medium mt-1 ${Ae>0?"text-emerald-600":"text-rose-600"}`,children:[Ae>0?"▲":"▼"," ",Math.abs(Ae),"% ",Ae>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(Oe,{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((Xe,nt)=>{var ct;const $e=Xe.snapshot,Ge=$e.soldPrice||$e.price;return e.jsxs(ve,{className:`overflow-hidden cursor-pointer transition-all duration-300 hover:shadow-xl hover:-translate-y-1 animate-fade-in ${P===nt?"ring-2 ring-primary":""}`,style:{animationDelay:`${nt*60}ms`},onClick:()=>E(nt),onMouseEnter:()=>M(nt),onMouseLeave:()=>M(null),children:[e.jsxs("div",{className:"relative",children:[e.jsx(NAe,{photos:$e.photos,className:"w-full h-44"}),e.jsxs(Oe,{className:"absolute top-2 left-2 bg-black/70 text-white border-0 backdrop-blur-sm",children:["#",nt+1]}),e.jsx(Oe,{variant:"outline",className:"absolute top-2 right-2 bg-white/95 border-0",children:$e.status})]}),e.jsxs(Me,{className:"p-4",children:[e.jsx("div",{className:"font-semibold leading-tight truncate",children:$e.address}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[$e.city,", ",$e.state]}),e.jsx("div",{className:"flex justify-between items-center mt-3 text-sm",children:e.jsxs("span",{className:"text-muted-foreground",children:[$e.bedrooms??"?","bd · ",$e.bathrooms??"?","ba · ",((ct=$e.sqft)==null?void 0:ct.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:["$",Ge==null?void 0:Ge.toLocaleString()]}),$e.sqft&&Ge?e.jsxs("span",{className:"text-xs text-muted-foreground tabular-nums",children:["$",Math.round(Ge/$e.sqft),"/sqft"]}):null]})]})]},nt)})})]}),e.jsx(Q7t,{comp:C!==null?(qe=o[C])==null?void 0:qe.snapshot:null,open:C!==null,onClose:()=>E(null)}),e.jsx(ve,{className:"border-primary/20 bg-gradient-to-br from-primary/5 via-background to-background overflow-hidden",children:e.jsxs(Me,{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",ce?`, ${ce}`:"","?"]}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:["One tap. ",((Qe=i==null?void 0:i.name)==null?void 0:Qe.split(" ")[0])||"Your agent"," hears you instantly."]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:[{kind:"love",icon:Do,label:"I love this price"},{kind:"fair",icon:Fg,label:"Seems fair"},{kind:"lower",icon:gS,label:"I'd price lower"},{kind:"higher",icon:Nl,label:"I'd price higher"},{kind:"ready_to_list",icon:wv,label:"Ready to list"},{kind:"want_walkthrough",icon:ya,label:"Want a walkthrough"},{kind:"need_time",icon:ga,label:"Need more time"},{kind:"have_questions",icon:f4,label:"I have questions"}].map(({kind:Xe,icon:nt,label:$e})=>e.jsxs(B,{variant:"outline",className:"bg-card hover:bg-primary hover:text-primary-foreground hover:scale-105 transition-all",onClick:()=>V(Xe),children:[e.jsx(nt,{className:"w-4 h-4 mr-2"}),$e]},Xe))}),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(Ou,{className:"w-4 h-4"}),"Ask your agent a question"]}),j?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:[G&&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:Xe=>f(Xe.target.value)}),e.jsx("input",{type:"email",className:"border rounded-md p-2 text-sm bg-background",placeholder:"Your email",value:y,onChange:Xe=>v(Xe.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:Xe=>m(Xe.target.value)}),e.jsx(B,{onClick:$,disabled:!h.trim()||g,className:"mt-2",children:g?"Sending…":"Send to agent"})]})]})]})}),i&&e.jsx(ve,{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:ie}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-xs uppercase tracking-widest text-muted-foreground",children:"Prepared by"}),e.jsx("h2",{className:"text-2xl md:text-3xl font-bold mt-1",children:i.name}),(i.title||i.brokerage_name)&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:[i.title,i.brokerage_name].filter(Boolean).join(" · ")}),i.bio&&e.jsx("p",{className:"text-sm text-muted-foreground mt-3 leading-relaxed",children:i.bio}),e.jsxs("div",{className:"flex flex-wrap gap-2 mt-4",children:[te&&e.jsx(B,{asChild:!0,children:e.jsxs("a",{href:te,children:[e.jsx(_a,{className:"w-4 h-4 mr-2"}),i.phone]})}),ae&&e.jsx(B,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:ae,children:[e.jsx(ln,{className:"w-4 h-4 mr-2"}),"Email"]})}),i.website_url&&e.jsx(B,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:i.website_url,target:"_blank",rel:"noreferrer",children:[e.jsx(sl,{className:"w-4 h-4 mr-2"}),"Website"]})})]})]})]})})})]}),i&&(te||le||ae)&&e.jsxs("div",{className:"md:hidden fixed bottom-0 left-0 right-0 bg-card/95 backdrop-blur border-t shadow-2xl z-50 px-3 py-3 flex gap-2",style:{paddingBottom:"calc(0.75rem + env(safe-area-inset-bottom))"},children:[te&&e.jsx(B,{className:"flex-1",asChild:!0,children:e.jsxs("a",{href:te,children:[e.jsx(_a,{className:"w-4 h-4 mr-1.5"}),"Call"]})}),le&&e.jsx(B,{variant:"outline",className:"flex-1",asChild:!0,children:e.jsxs("a",{href:le,children:[e.jsx(Ou,{className:"w-4 h-4 mr-1.5"}),"Text"]})}),ae&&e.jsx(B,{variant:"outline",className:"flex-1",asChild:!0,children:e.jsxs("a",{href:ae,children:[e.jsx(ln,{className:"w-4 h-4 mr-1.5"}),"Email"]})})]})]})}function sFs(){const t=ru().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(J7t,{tokenOverride:t})}const vVe="levelup_affiliate_ref",nFs=30,rFs=()=>{const[s]=Yl();_.useEffect(()=>{const t=s.get("ref");if(t){const n={code:t.toUpperCase(),timestamp:Date.now()};localStorage.setItem(vVe,JSON.stringify(n)),console.log("[Affiliate] Stored referral code:",t)}},[s])},aFs=()=>{try{const s=localStorage.getItem(vVe);if(!s)return null;const t=JSON.parse(s),n=nFs*24*60*60*1e3;return Date.now()-t.timestamp>n?(localStorage.removeItem(vVe),console.log("[Affiliate] Referral code expired"),null):t.code}catch{return null}},kAe="/assets/levelup-logo-header-_ZX7DvlA.png",iFs="/assets/scale-your-team-ku4MPatU.png";function oFs({open:s,onOpenChange:t}){return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"max-w-3xl max-h-[90vh] overflow-hidden",children:[e.jsx(Os,{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(Ds,{children:"Schedule a Brokerage Interest Meeting"}),e.jsx(_r,{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 Qre="/assets/mission_control-BJ-Kz8rX.png",UPe="/assets/crm-CsLftmB2.png",qPe="/assets/deal_pipeline-XYgypvwv.png",$Pe="/assets/staging_studio-5iLDjnv0.png",VPe="/assets/coaching-CSQEA81I.png",HPe="/assets/marketing_studio-Brx1ZOnN.png",lFs=[{key:"dashboard",label:"Agent Command Center",caption:"Your entire day — smart queue, calendar and pipeline in one view.",src:Qre},{key:"crm",label:"CRM & Contact Hub",caption:"Contacts, tags, follow-ups and deal history, always one click away.",src:UPe},{key:"pipeline",label:"Deal Pipeline",caption:"Every active deal with tasks, forms and commission tracking built in.",src:qPe},{key:"staging",label:"Staging Studio",caption:"AI photo staging — MLS-ready before/afters in minutes.",src:$Pe},{key:"coaching",label:"Coaching",caption:"Book live coaching sessions with Google Meet created automatically.",src:VPe},{key:"marketing",label:"Marketing Studio",caption:"Templates, social posts, reels and print — all branded to you.",src:HPe}];function cFs({slot:s}){return e.jsxs("figure",{className:"rounded-2xl overflow-hidden border border-white/10 bg-white/5 backdrop-blur-sm shadow-2xl",children:[e.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-2 border-b border-white/10",children:[e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-red-400/80"}),e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-amber-400/80"}),e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-green-400/80"}),e.jsx("span",{className:"ml-3 text-[11px] rounded px-2 py-0.5 bg-white/10 text-white/70",children:"dashboard.relevelup.com"})]}),s.src?e.jsx("img",{src:s.src,alt:`LevelUp ${s.label} screenshot`,className:"w-full h-auto block",loading:"lazy"}):e.jsxs("div",{className:"w-full aspect-[16/10] flex flex-col items-center justify-center gap-3 bg-white/5",children:[e.jsx(un,{className:"h-8 w-8 text-white/40"}),e.jsx("p",{className:"text-sm font-medium text-white/60",children:s.label}),e.jsx("p",{className:"text-xs px-6 text-center text-white/40",children:"Screenshot placeholder"})]}),e.jsxs("figcaption",{className:"px-4 py-3 text-sm text-white/80",children:[e.jsx("span",{className:"font-semibold text-white",children:s.label})," — ",s.caption]})]})}const m2={individual_agent:{name:"Individual Agent",price:"$39",period:"/month",description:"Perfect for independent agents ready to level up",features:["Full dashboard access","300+ professional templates","Academy training library","Community & networking","Live events & workshops","Social media content","Newsletter resources","Email support"],trial:"7-day free trial",popular:!1},brokerage_over_25:{name:"Brokerage",subtitle:"Unlimited Agents",price:"$499",period:"/month",description:"Scale your brokerage without limits",features:["Everything in Individual, plus:","Unlimited agents","Brokerage manager dashboard","Exclusive brokerage resources","Team performance analytics","Agent onboarding tools","Resource sharing","Priority support"],popular:!1}},dFs=[{icon:om,title:"Academy Training",description:"Access a library of on-demand video training covering lead generation, marketing, technology, and more."},{icon:Xc,title:"300+ Templates",description:"Professional Canva templates for social media, flyers, postcards, and marketing materials."},{icon:ga,title:"Live Events",description:"Weekly live training sessions, workshops, and Q&A events with industry experts."},{icon:Ou,title:"Agent Community",description:"Connect with fellow agents, share wins, ask questions, and network in our private community."},{icon:Fr,title:"Resource Kits",description:"Downloadable toolkits with scripts, checklists, guides, and everything you need to close more deals."},{icon:Vo,title:"Social Swag",description:"Fresh social media content and designs updated regularly to help you stand out online."}],uFs=[{category:"Marketing Studio",icon:wh,items:["Weekly Reels scripts","Social Post Generator","300+ Canva templates","Marketing Calendar","Postcard Direct Mail","Listing Music Videos","Social Swag drops"]},{category:"Lead Generation",icon:ku,items:["Custom lead websites","Open House Guest Book","RSVP pages","Resource landing pages","Listing Revival™","FSBO Breakthrough","Attract system"]},{category:"CRM & Deals",icon:Ny,items:["Agent OS CRM","Deal pipeline","Forms & e-signatures","Client portal","Smart follow-up queue","Lead ponds for teams","Google Business reviews"]},{category:"AI & Media",icon:Qx,items:["AI Staging Studio","Video library & sharing","Screen recording","Virtual backgrounds","AI blog writer","YouTube → Blog","Ask AI assistant"]},{category:"Growth & Coaching",icon:mm,items:["Academy courses","Live weekly coaching","Coaching programs","1:1 coaching booking","Private community","Live events & workshops"]},{category:"Brokerage Tools",icon:ai,items:["Manager dashboard","Team analytics","Agent onboarding","Office form libraries","Listing Exchange","Brand kits","Recruiting pipeline"]}],hFs=[{icon:In,title:"Contact Management",description:"Organize your sphere into relationship tiers—Top 25, Past Clients, Referral Partners, and more."},{icon:un,title:"Smart Touchpoint Plans",description:"Automated action plans that tell you exactly who to contact and how, based on relationship type."},{icon:_a,title:"One-Tap Actions",description:"Call, text, or email contacts directly with pre-written scripts tailored to each relationship."},{icon:Bf,title:"Birthday & Anniversary Alerts",description:"Never miss an important date—get reminders for birthdays and home anniversaries."},{icon:Xa,title:"Pop-by Map",description:"See all your contacts on a map and plan efficient pop-by routes in your area."},{icon:bl,title:"Momentum Tracking",description:"Track your touch streaks, weekly goals, and relationship health scores."},{icon:Do,title:"Relationship Health",description:"Visual dashboard showing which contacts need attention based on last touch date."},{icon:nf,title:"Daily Action Cards",description:"Wake up to a prioritized list of exactly who to reach out to today."}],mFs=[{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."}],pFs=()=>{const{user:s,loading:t}=hs(),n=Fn(),[r]=Yl();_.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]=_.useState(null),[l,o]=_.useState(null),[c,d]=_.useState(!1),[u,h]=_.useState(""),[m,p]=_.useState(""),[f,y]=_.useState(""),[v,g]=_.useState(!1),[b,j]=_.useState(!1),S=(P,M=!1)=>{o({tier:P,skipTrial:M}),d(!0)};rFs(),_.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]),_.useEffect(()=>{r.get("canceled")==="true"&&se.error("Checkout was canceled. Feel free to try again when you're ready!")},[r]);const C=async(P,M=!1)=>{if(!u){se.error("Please enter your email address");return}if(!m.trim()){se.error("Please enter your full name");return}g(!0),i(P+(M?"_direct":""));const I=aFs();try{const{data:D,error:O}=await q.functions.invoke("create-checkout",{body:{tier:P,email:u,name:m.trim(),couponCode:f.trim()||void 0,skipTrial:M,referralCode:I}});if(O)throw O;if(D!=null&&D.url)window.open(D.url,"_blank","noopener,noreferrer"),se.success("Checkout opened in a new tab");else throw new Error("No checkout URL returned")}catch(D){console.error("Checkout error:",D),se.error(D.message||"Failed to start checkout. Please try again.")}finally{g(!1),i(null),d(!1),o(null)}},E=()=>{l&&C(l.tier,l.skipTrial)};return t?e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-[#4a6b6d]",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-white border-t-transparent"})}):e.jsxs("div",{className:"min-h-screen bg-background overflow-hidden",children:[e.jsx("nav",{className:"fixed top-0 left-0 right-0 z-50 bg-[#4a6b6d] shadow-md",children:e.jsxs("div",{className:"container mx-auto px-4 py-3 flex items-center justify-between",children:[e.jsx("div",{className:"flex items-center",children:e.jsx("img",{src:kAe,alt:"LevelUp",className:"h-8 md:h-10"})}),e.jsxs("div",{className:"flex items-center gap-2 md:gap-4",children:[e.jsx(B,{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(B,{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(B,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>n("/blog"),children:"Blog"}),e.jsx(B,{onClick:()=>n("/auth"),className:"bg-white text-[#4a6b6d] hover:bg-gray-100 font-medium shadow-md",children:"Sign In"})]})]})}),e.jsxs("section",{className:"relative overflow-hidden bg-[#0f2530]",children:[e.jsx("style",{children:` @keyframes hero-float { 0%,100% { transform: translateY(0px); } 50% { transform: translateY(-12px); } } @keyframes hero-float-slow { 0%,100% { transform: translateY(0px); } 50% { transform: translateY(-8px); } } @keyframes hero-glow { 0%,100% { opacity: 0.55; } 50% { opacity: 0.9; } } `}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-b from-[#122c3a] via-[#16384a] to-[#0f2530]"}),e.jsx("div",{className:"absolute -top-40 left-1/2 -translate-x-1/2 h-[560px] w-[900px] rounded-full bg-[#4aa8a0]/25 blur-[140px] animate-[hero-glow_7s_ease-in-out_infinite]"}),e.jsx("div",{className:"absolute top-1/3 -left-40 h-[420px] w-[420px] rounded-full bg-[#2a6f8a]/20 blur-[120px]"}),e.jsx("div",{className:"absolute top-1/4 -right-40 h-[420px] w-[420px] rounded-full bg-[#c9a84c]/10 blur-[120px]"}),e.jsx("div",{className:"absolute inset-0 opacity-[0.12] bg-[linear-gradient(to_right,rgba(255,255,255,0.5)_1px,transparent_1px),linear-gradient(to_bottom,rgba(255,255,255,0.5)_1px,transparent_1px)] bg-[size:56px_56px] [mask-image:radial-gradient(ellipse_75%_65%_at_50%_35%,black,transparent)]"}),e.jsx("div",{className:"absolute inset-x-0 bottom-0 h-40 bg-gradient-to-t from-[#0f2530] to-transparent"}),e.jsxs("div",{className:"container mx-auto px-4 relative",children:[e.jsxs("div",{className:"max-w-5xl mx-auto text-center pt-20 md:pt-28 pb-10 space-y-8",children:[e.jsx("div",{className:"flex justify-center animate-fade-in",children:e.jsxs("span",{className:"inline-flex items-center gap-2 rounded-full border border-white/15 bg-white/5 backdrop-blur-sm px-4 py-1.5 text-xs md:text-sm font-semibold tracking-wide text-white/85 shadow-lg",children:[e.jsx(un,{className:"h-3.5 w-3.5 text-[#7fd4cc]"}),"The Agent Operating System — coaching, CRM & marketing in one"]})}),e.jsxs("h1",{className:"text-4xl sm:text-5xl md:text-7xl font-sans font-bold tracking-tight text-white leading-[1.05] animate-fade-in",children:["The tools you need",e.jsx("br",{className:"hidden sm:block"})," to get it done.",e.jsx("span",{className:"block mt-3 bg-gradient-to-r from-[#8fe0d6] via-[#5cc0b6] to-[#e6c878] bg-clip-text text-transparent",children:"The platform to keep it going."})]}),e.jsx("p",{className:"text-base md:text-xl text-white/65 max-w-2xl mx-auto leading-relaxed animate-fade-in",children:"Weekly coaching, a smart CRM, done-for-you marketing and AI tools — everything a modern agent runs on, in one login."}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center items-center pt-2 animate-fade-in",children:[e.jsxs(B,{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-[#122c3a] hover:bg-white/90 shadow-[0_0_40px_-8px_rgba(140,220,210,0.6)] transition-all hover:scale-105 group rounded-full",children:["Start Your Free Trial",e.jsx(La,{className:"ml-2 w-5 h-5 group-hover:translate-x-1 transition-transform"})]}),e.jsx(B,{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/40 text-white bg-white/5 backdrop-blur-sm hover:bg-white hover:text-[#122c3a] rounded-full",children:"See What's Included"})]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-x-8 gap-y-3 pt-2 text-sm text-white/55 animate-fade-in",children:[e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(Da,{className:"h-4 w-4 text-[#e6c878] fill-[#e6c878]"})," Built with agents' direct input"]}),e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(nf,{className:"h-4 w-4 text-[#7fd4cc]"})," New tools added every month"]}),e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(Rm,{className:"h-4 w-4 text-white/60"})," Cancel anytime"]})]})]}),e.jsxs("div",{className:"relative max-w-5xl mx-auto pb-20 md:pb-28 px-2",children:[e.jsx("div",{className:"absolute inset-x-8 top-10 bottom-0 rounded-[40px] bg-gradient-to-b from-[#4aa8a0]/30 to-transparent blur-2xl","aria-hidden":!0}),e.jsxs("div",{className:"relative animate-[hero-float-slow_8s_ease-in-out_infinite]",children:[e.jsxs("figure",{className:"rounded-2xl overflow-hidden border border-white/15 bg-[#0d1f29]/80 backdrop-blur-md shadow-[0_40px_80px_-20px_rgba(0,0,0,0.7)]",children:[e.jsxs("div",{className:"flex items-center gap-1.5 px-4 py-2.5 border-b border-white/10 bg-white/5",children:[e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-red-400/80"}),e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-amber-400/80"}),e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-green-400/80"}),e.jsx("span",{className:"ml-3 text-[11px] rounded px-2 py-0.5 bg-white/10 text-white/70",children:"dashboard.relevelup.com"})]}),e.jsx("img",{src:Qre,alt:"LevelUp Agent Command Center dashboard",className:"w-full h-auto block"})]}),e.jsxs("div",{className:"hidden md:flex absolute -left-10 top-24 items-center gap-3 rounded-2xl border border-white/15 bg-[#122c3a]/90 backdrop-blur-md px-4 py-3 shadow-2xl animate-[hero-float_6s_ease-in-out_infinite]",children:[e.jsx("span",{className:"flex h-9 w-9 items-center justify-center rounded-xl bg-[#4aa8a0]/20",children:e.jsx(Nl,{className:"h-5 w-5 text-[#7fd4cc]"})}),e.jsxs("span",{children:[e.jsx("span",{className:"block text-sm font-semibold text-white",children:"Smart Queue ready"}),e.jsx("span",{className:"block text-xs text-white/55",children:"5 follow-ups due today"})]})]}),e.jsxs("div",{className:"hidden md:flex absolute -right-10 top-1/2 items-center gap-3 rounded-2xl border border-white/15 bg-[#122c3a]/90 backdrop-blur-md px-4 py-3 shadow-2xl animate-[hero-float_7s_ease-in-out_infinite_1s]",children:[e.jsx("span",{className:"flex h-9 w-9 items-center justify-center rounded-xl bg-[#e6c878]/15",children:e.jsx(om,{className:"h-5 w-5 text-[#e6c878]"})}),e.jsxs("span",{children:[e.jsx("span",{className:"block text-sm font-semibold text-white",children:"Weekly Reels delivered"}),e.jsx("span",{className:"block text-xs text-white/55",children:"Fresh scripts every Monday"})]})]}),e.jsxs("div",{className:"hidden md:flex absolute left-8 -bottom-6 items-center gap-3 rounded-2xl border border-white/15 bg-[#122c3a]/90 backdrop-blur-md px-4 py-3 shadow-2xl animate-[hero-float_6.5s_ease-in-out_infinite_0.5s]",children:[e.jsx("span",{className:"flex h-9 w-9 items-center justify-center rounded-xl bg-white/10",children:e.jsx(ga,{className:"h-5 w-5 text-white/80"})}),e.jsxs("span",{children:[e.jsx("span",{className:"block text-sm font-semibold text-white",children:"Coaching booked"}),e.jsx("span",{className:"block text-xs text-white/55",children:"Meet link added automatically"})]})]})]})]})]})]}),e.jsx("section",{className:"py-20 bg-background",children:e.jsx("div",{className:"container mx-auto px-4",children:e.jsxs("div",{className:"max-w-4xl mx-auto text-center space-y-8",children:[e.jsx("h2",{className:"text-3xl md:text-5xl leading-tight font-sans font-semibold text-secondary",children:"We help brokerages and agents grow with training, tools, and built-in execution."}),e.jsxs("div",{className:"space-y-2 text-lg text-muted-foreground",children:[e.jsx("p",{children:"Agents get weekly coaching + plug-and-play marketing."}),e.jsx("p",{children:"Brokerages get higher adoption, consistency, and real engagement."})]}),e.jsx("p",{className:"text-2xl md:text-4xl text-[#4a6b6d] pt-4 font-sans font-bold",children:"LEVELUP EQUIPS BOTH TO THRIVE."}),e.jsx("p",{className:"text-lg text-muted-foreground",children:"Learn how we support agents and empower brokerages to grow—together."}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center pt-4",children:[e.jsxs(B,{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(B,{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(Fo,{className:"mr-2 h-5 w-5"}),"Individual Membership"]})]})]})})}),e.jsx("section",{id:"features",className:"py-20 bg-muted/30",children:e.jsxs("div",{className:"container mx-auto px-4",children:[e.jsxs("div",{className:"text-center max-w-3xl mx-auto mb-16",children:[e.jsxs("span",{className:"inline-flex items-center gap-2 px-4 py-1.5 rounded-full bg-[#4a6b6d]/10 text-[#4a6b6d] text-sm font-semibold mb-5",children:[e.jsx(G4,{className:"w-4 h-4"}),"40+ tools & counting"]}),e.jsx("h2",{className:"text-3xl md:text-4xl mb-6 font-sans font-bold",children:"What's inside our members only portal?"}),e.jsx("p",{className:"text-lg text-muted-foreground",children:"Everything you need to grow your business, all in one place."})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8 max-w-6xl mx-auto",children:dFs.map((P,M)=>e.jsxs(ve,{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(St,{className:"text-xl font-sans",children:P.title})]}),e.jsx(Me,{children:e.jsx("p",{className:"text-muted-foreground leading-relaxed",children:P.description})})]},M))}),e.jsxs("div",{className:"mt-14 max-w-6xl mx-auto rounded-3xl bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] p-8 md:p-12 relative overflow-hidden shadow-2xl",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"text-center mb-10",children:[e.jsx("h3",{className:"text-2xl md:text-3xl font-bold text-white font-sans",children:"...and that's just the beginning"}),e.jsx("p",{className:"text-white/60 mt-2",children:"Dozens of purpose-built tools, all included with membership."})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-x-10 gap-y-8",children:uFs.map(P=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2.5 mb-4",children:[e.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-white/10",children:e.jsx(P.icon,{className:"h-4 w-4 text-white"})}),e.jsx("span",{className:"text-sm font-bold uppercase tracking-wider text-white/90",children:P.category})]}),e.jsx("ul",{className:"space-y-2.5",children:P.items.map(M=>e.jsxs("li",{className:"flex items-center gap-2.5 text-white/70 text-sm",children:[e.jsx(ea,{className:"h-3.5 w-3.5 text-emerald-300 shrink-0"}),M]},M))})]},P.category))}),e.jsxs("p",{className:"text-center text-white/50 text-sm mt-10 flex items-center justify-center gap-2",children:[e.jsx(un,{className:"h-4 w-4"}),"New tools added every month — membership keeps getting more valuable."]})]})]})]})}),e.jsxs("section",{className:"py-20 bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),e.jsxs("div",{className:"container mx-auto px-4 relative",children:[e.jsxs("div",{className:"text-center max-w-3xl mx-auto mb-14",children:[e.jsx("span",{className:"text-sm font-semibold tracking-[0.15em] uppercase text-white/70",children:"See it in action"}),e.jsx("h2",{className:"text-3xl md:text-5xl font-bold text-white mt-4 tracking-tight font-sans",children:"A real platform, not another course"}),e.jsx("p",{className:"text-white/60 mt-4 max-w-2xl mx-auto text-lg",children:"This is what members open every morning."})]}),e.jsx("div",{className:"grid md:grid-cols-2 gap-8 md:gap-10 max-w-6xl mx-auto",children:lFs.map(P=>e.jsx(cFs,{slot:P},P.key))})]})]}),e.jsxs("section",{id:"agent-os",className:"py-20 bg-gradient-to-br from-[#4a6b6d] to-[#3d5a5c] relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),e.jsxs("div",{className:"container mx-auto px-4 relative",children:[e.jsxs("div",{className:"text-center max-w-3xl mx-auto mb-16",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-4 py-2 rounded-full bg-white/10 text-white text-sm font-medium mb-6",children:[e.jsx(un,{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:hFs.map((P,M)=>e.jsxs(ve,{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(St,{className:"text-lg font-semibold text-white",children:P.title})]}),e.jsx(Me,{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(B,{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(La,{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(ea,{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(B,{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(xi,{className:"ml-2 w-5 h-5"})]}),e.jsxs(B,{size:"lg",variant:"outline",onClick:()=>j(!0),className:"border-[#4a6b6d] text-[#4a6b6d] hover:bg-[#4a6b6d]/10",children:[e.jsx(ga,{className:"mr-2 w-5 h-5"}),"Schedule Info Session"]})]})]}),e.jsx("div",{className:"relative hidden md:block",children:e.jsx("img",{src:iFs,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:mFs.map((P,M)=>e.jsx(ve,{className:"bg-muted/30 border-0",children:e.jsxs(Me,{className:"pt-8",children:[e.jsx("div",{className:"flex gap-1 mb-4",children:[1,2,3,4,5].map(I=>e.jsx(Da,{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(B,{size:"lg",className:"px-12 py-7 text-lg font-semibold bg-white text-[#4a6b6d] hover:bg-white/90 shadow-2xl transition-all hover:scale-105 group rounded-full",onClick:()=>S("individual_agent"),children:["Start Free Trial",e.jsx(La,{className:"ml-2 w-5 h-5 group-hover:translate-x-1 transition-transform"})]})})]})})]}),e.jsx("section",{id:"pricing",className:"py-20 bg-muted/30",children:e.jsxs("div",{className:"container mx-auto px-4",children:[e.jsxs("div",{className:"text-center mb-16",children:[e.jsxs("h2",{className:"text-3xl mb-6 font-sans md:text-5xl font-bold",children:["Simple, Transparent ",e.jsx("span",{className:"italic text-[#4a6b6d]",children:"Pricing"})]}),e.jsx("p",{className:"text-lg text-muted-foreground max-w-2xl mx-auto",children:"Choose the plan that fits your needs. All plans include everything you need to succeed."})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8 max-w-4xl mx-auto",children:[e.jsxs(ve,{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(Fo,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsx(St,{className:"text-xl font-sans",children:m2.individual_agent.name})]}),e.jsxs("div",{className:"flex items-baseline gap-1 mt-4",children:[e.jsx("span",{className:"text-5xl font-bold",children:m2.individual_agent.price}),e.jsx("span",{className:"text-muted-foreground text-lg",children:m2.individual_agent.period})]}),e.jsx(kn,{className:"text-base mt-2",children:m2.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(Gr,{className:"w-4 h-4"}),m2.individual_agent.trial]})]}),e.jsx(Me,{className:"flex-1 pt-0",children:e.jsx("ul",{className:"space-y-3",children:m2.individual_agent.features.map((P,M)=>e.jsxs("li",{className:"flex items-center gap-3",children:[e.jsx(ea,{className:"w-5 h-5 text-[#4a6b6d] flex-shrink-0"}),e.jsx("span",{children:P})]},M))})}),e.jsxs(Q3e,{className:"flex flex-col gap-3 pt-4",children:[e.jsx(B,{className:"w-full py-6 text-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:()=>S("individual_agent"),children:"Start Free Trial"}),e.jsx(B,{variant:"outline",className:"w-full rounded-full border-2 border-[#4a6b6d] text-[#4a6b6d] bg-white hover:bg-[#4a6b6d]/5 uppercase text-sm font-medium tracking-wide",onClick:()=>S("individual_agent",!0),children:"Skip Trial, Subscribe Now"})]})]}),e.jsxs(ve,{className:"relative flex flex-col border-2 border-[#4a6b6d] shadow-2xl bg-background",children:[e.jsx("div",{className:"absolute -top-4 left-1/2 -translate-x-1/2 px-6 py-2 bg-[#4a6b6d] text-white text-sm font-semibold rounded-full shadow-lg",children:"Most Popular"}),e.jsxs(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(St,{className:"text-xl font-sans",children:m2.brokerage_over_25.name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:m2.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:m2.brokerage_over_25.price}),e.jsx("span",{className:"text-muted-foreground text-lg",children:m2.brokerage_over_25.period})]}),e.jsx(kn,{className:"text-base mt-2",children:m2.brokerage_over_25.description})]}),e.jsx(Me,{className:"flex-1 pt-0",children:e.jsx("ul",{className:"space-y-3",children:m2.brokerage_over_25.features.map((P,M)=>e.jsxs("li",{className:"flex items-center gap-3",children:[e.jsx(ea,{className:"w-5 h-5 text-[#4a6b6d] flex-shrink-0"}),e.jsx("span",{children:P})]},M))})}),e.jsx(Q3e,{className:"pt-4",children:e.jsx(B,{className:"w-full py-6 text-lg shadow-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:()=>S("brokerage_over_25"),children:"Get Started"})})]})]})]})}),e.jsx("section",{id:"neutrality",className:"py-20 bg-background",children:e.jsx("div",{className:"container mx-auto px-4",children:e.jsxs("div",{className:"max-w-4xl mx-auto",children:[e.jsxs("div",{className:"text-center mb-12",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-4 py-2 rounded-full bg-[#4a6b6d]/10 text-[#4a6b6d] text-sm font-medium mb-4",children:[e.jsx(Rm,{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(ve,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:e.jsxs(Me,{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(ve,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:e.jsxs(Me,{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(ec,{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(ve,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:e.jsxs(Me,{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(gj,{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(ve,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:e.jsxs(Me,{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(Fr,{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(B,{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(La,{className:"ml-2 w-5 h-5"})]}),e.jsx(B,{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:kAe,alt:"LevelUp",className:"h-8"}),e.jsxs("p",{className:"text-sm",children:["© ",new Date().getFullYear()," LevelUp. All rights reserved."]}),e.jsxs("div",{className:"flex items-center gap-6",children:[e.jsx("a",{href:"/blog",className:"text-white/60 hover:text-white transition-colors text-sm",children:"Blog"}),e.jsx("a",{href:"/privacy-policy",className:"text-white/60 hover:text-white transition-colors text-sm",children:"Privacy Policy"}),e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-white/60 hover:text-white transition-colors text-sm",children:"Contact Support"})]})]})})}),e.jsx(oFs,{open:b,onOpenChange:j}),e.jsx(Ls,{open:c,onOpenChange:d,children:e.jsxs(Ps,{className:"sm:max-w-md",children:[e.jsxs(Os,{children:[e.jsx(Ds,{className:"text-xl font-sans font-semibold",children:"Enter your details to get started"}),e.jsx(_r,{children:(l==null?void 0:l.tier)==="individual_agent"&&!(l!=null&&l.skipTrial)?"Start your 7-day free trial":(l==null?void 0:l.tier)==="individual_agent"?"Subscribe to Individual Agent":"Subscribe to Brokerage"})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{children:[e.jsxs(J,{htmlFor:"dialog-name",children:["Full Name ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(xe,{id:"dialog-name",type:"text",placeholder:"John Smith",value:m,onChange:P=>p(P.target.value),className:"mt-1",required:!0})]}),e.jsxs("div",{children:[e.jsxs(J,{htmlFor:"dialog-email",children:["Email Address ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(xe,{id:"dialog-email",type:"email",placeholder:"you@example.com",value:u,onChange:P=>h(P.target.value),className:"mt-1",required:!0})]}),e.jsxs("div",{children:[e.jsxs(J,{htmlFor:"dialog-coupon",children:["Discount Code ",e.jsx("span",{className:"text-muted-foreground",children:"(Optional)"})]}),e.jsx(xe,{id:"dialog-coupon",type:"text",placeholder:"Enter discount code",value:f,onChange:P=>y(P.target.value),className:"mt-1"})]})]}),e.jsx(B,{className:"w-full py-6 text-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:E,disabled:v,children:v?"Loading...":"Continue to Checkout"})]})})]})},Axt=()=>e.jsxs(e.Fragment,{children:[e.jsxs(ul,{children:[e.jsx("title",{children:"Privacy Policy | LevelUp"}),e.jsx("meta",{name:"description",content:"How LevelUp collects, uses, shares and retains data — including the LevelUp Hub MCP connector for ChatGPT."})]}),e.jsx("div",{className:"min-h-screen bg-background py-12 px-4 sm:px-6 lg:px-8",children:e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsx("h1",{className:"text-3xl font-bold text-foreground mb-8",children:"Privacy Policy"}),e.jsxs("div",{className:"prose prose-sm max-w-none text-muted-foreground space-y-6",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Last updated: September 16, 2026"}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"1. Introduction"}),e.jsx("p",{children:'LevelUp ("we," "our," or "us") provides a real estate business platform for agents, teams and brokerages. This policy explains what we collect, why, who receives it, how long we keep it and the controls you have. It covers the LevelUp web app, our public pages, our SMS program and the LevelUp Hub MCP connector that members can connect to ChatGPT and other AI clients.'}),e.jsx("p",{className:"mt-3",children:"Members store information about other people (their contacts, leads and open-house visitors) in LevelUp. For that information the member is the controller and LevelUp processes it on their behalf."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"2. Information We Collect"}),e.jsx("p",{children:"Depending on which features a member uses, we handle:"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Account and profile:"})," name, email, phone, password credentials, title, brokerage, license number and state, website, headshot and logo images, brand colors, taglines and any brokerage compliance line."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Billing:"})," subscription status, plan, and transaction records handled by our payment processor (we do not store full card numbers)."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Contacts and relationship data"})," a member enters or imports: names, emails, phones, mailing addresses, lead source, free-text notes, and optional personal fields such as birthday, home and wedding anniversary, spouse name, spouse email and spouse birthday, company and job title."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Deals, tasks and interaction history:"})," pipeline stage, prices, commissions, bonuses, key dates, tasks, and logged calls, texts, emails, pop-bys and notes."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Listings and media:"})," listing details, photos, videos and agent/brokerage attribution, including listings published to the shared Listing Exchange."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Guest Book visitors:"})," the name, contact details and any survey answers a visitor submits at an open house sign-in page."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Landing page and website leads:"})," the fields a visitor submits on a member's published landing page, property website or home-value page."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Generated marketing and campaign data:"})," drafts and records created by our marketing tools (email, social, print, FSBO and Listing Revival), plus the leads and engagement events those campaigns capture."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"MCP audit logs:"})," for each connector tool call we record the member id, tool name, a truncated snapshot of the tool inputs, the outcome, an error label, the duration and the calling client id."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Technical and usage data:"})," log data, device and browser information, and feature usage needed to run and secure the service."]})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"3. How We Use Information"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Provide, maintain and improve the platform and the features a member turns on."}),e.jsx("li",{children:"Perform the actions a member asks for, including through a connected AI client."}),e.jsx("li",{children:"Generate marketing copy and assets when a member explicitly requests generation."}),e.jsx("li",{children:"Process payments and send transactional and support messages."}),e.jsx("li",{children:"Secure the service: authentication, rate limiting, audit trails, abuse investigation and support."}),e.jsx("li",{children:"Meet legal, tax and record-keeping obligations."})]}),e.jsx("p",{className:"mt-3",children:"We do not sell personal information, and we do not use member contact data to train AI models."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"4. LevelUp Hub MCP Connector (ChatGPT and other AI clients)"}),e.jsxs("p",{children:["Members can optionally connect LevelUp Hub to an AI client such as ",e.jsx("strong",{children:"ChatGPT (OpenAI)"})," ","using the Model Context Protocol. The connector is off until a member connects it and signs in through OAuth, and it can be revoked at any time from the AI client."]}),e.jsxs("p",{className:"mt-3",children:["Once connected, the client can call LevelUp tools ",e.jsx("strong",{children:"as that member"})," and receives whatever a called tool returns — which may include profile and branding data, contacts and their relationship fields, deals and tasks, listings and photos, Guest Book visitors, landing-page leads, and campaign records. OpenAI's handling of that data is governed by OpenAI's own terms and privacy policy."]}),e.jsx("p",{className:"mt-3",children:'The connector does not send email, SMS, direct mail or social posts. Tools that "activate" a campaign only change its status inside LevelUp and publish its page; outbound delivery is always a separate action the member takes in the app. Publishing, activating, merging and deleting require an explicit confirmation step, and open houses, landing pages and property sites are created as unpublished drafts unless the member asks otherwise.'}),e.jsxs("p",{className:"mt-3",children:["Full details are on the"," ",e.jsx(ir,{to:"/mcp-data-use",className:"text-primary hover:underline",children:"MCP data use"})," ","page."]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"5. AI Content Generation"}),e.jsxs("p",{children:["When a member asks for generated copy (listing descriptions, emails, social posts, print collateral, campaign letters), the request is sent to the ",e.jsx("strong",{children:"Lovable AI Gateway"})," and the model provider behind it. That request contains the property details supplied for the task and a brand block with the agent's name, brokerage, phone, email, website, license and any compliance line. Contact records, visitor lists and lead lists are not sent for generation. Nothing is sent to a model provider for read-only tools or for ordinary use of the app."]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"6. Who Receives Information"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Infrastructure providers"})," that host our application, database, storage and email/SMS delivery."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Payment processor"})," for subscriptions and purchases."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"The AI client a member connects"})," (OpenAI/ChatGPT or another MCP client), as described in section 4."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"The Lovable AI Gateway and its model provider"}),", only for generation requests, as described in section 5."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Third-party services a member connects"})," — for example Google (calendar and sign-in), Gmail, Meta/Facebook and Instagram, YouTube, Canva, Stripe, and CRM imports such as BoldTrail or Lofty — and only when that integration is invoked. Each is governed by its own privacy policy."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"The public"}),", for pages a member publishes: open house sign-in pages, landing pages, property websites and public listing pages."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Other LevelUp members"}),", for listings a member publishes to the shared Listing Exchange (listing details, photos and agent/brokerage attribution). Contacts, leads and pipeline data are never shared this way."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Brokerage managers, team leaders, assigned assistants and coaches"}),", limited to the data their role is granted."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"LevelUp administrators"}),", who may act on behalf of a member for support and setup; those actions are recorded in the audit log with the target member."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Legal recipients"}),", where disclosure is required by law or needed to protect rights and safety."]})]}),e.jsx("p",{className:"mt-3",children:"We do not sell, rent or trade personal information."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"7. Retention"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Account, contact, deal, listing, campaign, visitor and lead records are kept for as long as the account is active, until the member deletes them, or until the account is deleted."}),e.jsx("li",{children:"MCP audit log entries are kept for security and support purposes. They are not purged automatically on a fixed schedule; they can be removed on request."}),e.jsx("li",{children:"Short-lived rate-limit counters expire within minutes."}),e.jsx("li",{children:"Billing and tax records are kept as long as the law requires."}),e.jsx("li",{children:"Backups are cycled on our provider's schedule, so deleted data can persist in backups for a limited period after deletion."})]}),e.jsxs("p",{className:"mt-3",children:["We do not promise an automatic timed purge that we do not operate; see"," ",e.jsx(ir,{to:"/data-deletion",className:"text-primary hover:underline",children:"Data Deletion"})," ","for how requests are handled."]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"8. Your Choices and Rights"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Access, correct or delete records from within the app."}),e.jsx("li",{children:"Connect or disconnect any integration, including the MCP connector, at any time."}),e.jsx("li",{children:"Review connector activity in the MCP activity log."}),e.jsx("li",{children:"Mark a contact as opted out of marketing email, and opt out of SMS by replying STOP."}),e.jsxs("li",{children:["Request access, correction, export or deletion by emailing ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"}),"."]})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"9. Data Security"}),e.jsx("p",{children:"We use access controls, row-level database security scoped to each member, OAuth-based authentication for connectors, per-member rate limiting and audit logging. No method of transmission or storage is completely secure."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"10. SMS / Text Messaging Program (LevelUp Account & Lead Alerts)"}),e.jsx("p",{children:"If you opt in, we use your mobile number to send SMS account notifications, real-time lead alerts, service updates and support messages related to your LevelUp account."}),e.jsx("p",{className:"mt-3",children:"No mobile information will be shared with third parties or affiliates for marketing or promotional purposes. Text messaging originator opt-in data and consent will not be shared with any third parties, except with the vendors and aggregators that deliver the messages on our behalf."}),e.jsx("p",{className:"mt-3",children:"Message frequency varies. Message and data rates may apply. Reply STOP to opt out and HELP for help."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"11. LevelUp SmartSign (Property Information by Text)"}),e.jsxs("p",{children:["LevelUp SmartSign is operated by ",e.jsx("strong",{children:"LevelUp Consulting Group"}),". Consumers text a property code displayed on a real estate sign to ",e.jsx("strong",{children:"859-413-5013"})," to request information about that property. LevelUp is the sender of these messages; independent real estate agents do not send messages through the SmartSign number. This program is separate from the LevelUp account and lead alert SMS program described in section 10, and consent to one is not consent to the other."]}),e.jsxs("p",{className:"mt-3",children:[e.jsx("strong",{className:"text-foreground",children:"What we collect:"})," your mobile phone number, the property code you text, the content of your messages, and the details of your inquiry (such as the property you asked about, your questions, and any name or showing preference you provide)."]}),e.jsxs("p",{className:"mt-3",children:[e.jsx("strong",{className:"text-foreground",children:"How we use it:"})," to respond to your inquiry with listing information, answer questions about the property, assist with showing requests, provide support, keep records of your messaging preferences and opt-outs, and meet legal and carrier requirements."]}),e.jsxs("p",{className:"mt-3",children:[e.jsx("strong",{className:"text-foreground",children:"Service providers:"})," messaging providers — including ",e.jsx("strong",{children:"Telnyx"})," — and our hosting and database providers process this information solely to deliver and operate the service on our behalf."]}),e.jsxs("p",{className:"mt-3",children:[e.jsx("strong",{className:"text-foreground",children:"Sharing with an agent:"})," we ask for your separate, specific permission before sharing your inquiry or contact details with a named agent. We identify the actual agent and brokerage first. If you agree, we share your name, phone number and property inquiry with that agent so they can respond to your request. This consumer-requested handoff is not a transfer of your SMS consent: the agent does not receive permission to send you marketing texts, and your LevelUp SmartSign consent does not carry over to them. Agreeing to an agent contacting you also does not enroll you in LevelUp marketing."]}),e.jsxs("p",{className:"mt-3",children:[e.jsx("strong",{className:"text-foreground",children:"Marketing is separate:"})," requesting property information does not enroll you in promotional or marketing texts. Marketing texts require a separate affirmative opt-in, and you can stop them at any time by replying STOP."]}),e.jsxs("p",{className:"mt-3",children:[e.jsx("strong",{className:"text-foreground",children:"No sale or sharing for third-party marketing:"})," we do not sell your information, and no mobile information, SMS opt-in data or consent is shared with third parties or affiliates for their own promotional or marketing purposes. The only recipients are the service providers that deliver the service on our behalf, and — with your separate permission — the specific agent you asked to hear from."]}),e.jsxs("p",{className:"mt-3",children:["Message frequency varies. Message and data rates may apply. Reply STOP to opt out or HELP for help. See the"," ",e.jsx(ir,{to:"/sms-opt-in",className:"text-primary hover:underline",children:"SMS opt-in page"})," ","and"," ",e.jsx(ir,{to:"/terms-of-service",className:"text-primary hover:underline",children:"Terms of Service"})," ","for program details."]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"12. Children"}),e.jsx("p",{children:"LevelUp is a business tool and is not directed to children under 16."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"13. Changes to This Policy"}),e.jsx("p",{children:'We will update this page when our practices change and revise the "Last updated" date above.'})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"14. Contact Us"}),e.jsxs("p",{children:["Questions about this policy:"," ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"}),"."]})]})]})]})})]}),Ext=()=>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: September 16, 2026"}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"1. Acceptance of Terms"}),e.jsx("p",{children:'By accessing or using the LevelUp platform ("Service"), you agree to be bound by these Terms of Service. If you do not agree to these terms, please do not use our Service.'})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"2. Description of Service"}),e.jsx("p",{children:"LevelUp provides a platform for real estate professionals to access training, resources, marketing tools, and community features. We reserve the right to modify or discontinue the Service at any time."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"3. User Accounts"}),e.jsx("p",{children:"To use certain features, you must create an account. You agree to:"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Provide accurate and complete information"}),e.jsx("li",{children:"Maintain the security of your account credentials"}),e.jsx("li",{children:"Notify us immediately of any unauthorized access"}),e.jsx("li",{children:"Accept responsibility for all activities under your account"})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"4. Acceptable Use"}),e.jsx("p",{children:"You agree not to:"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Violate any applicable laws or regulations"}),e.jsx("li",{children:"Infringe on the rights of others"}),e.jsx("li",{children:"Upload malicious code or interfere with the Service"}),e.jsx("li",{children:"Attempt to gain unauthorized access to any part of the Service"}),e.jsx("li",{children:"Use the Service for any unlawful purpose"})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"5. Intellectual Property"}),e.jsx("p",{children:"The Service and its original content, features, and functionality are owned by LevelUp and are protected by international copyright, trademark, and other intellectual property laws."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"6. Third-Party Integrations"}),e.jsx("p",{children:"Our Service may integrate with third-party platforms such as Facebook and Instagram. Your use of these integrations is subject to the terms and policies of those third parties. We are not responsible for the content or practices of any third-party services."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"7. Payment Terms"}),e.jsx("p",{children:"Certain features may require payment. By subscribing to paid features, you agree to pay all applicable fees. All payments are non-refundable unless otherwise specified."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"8. Limitation of Liability"}),e.jsx("p",{children:"To the maximum extent permitted by law, LevelUp shall not be liable for any indirect, incidental, special, consequential, or punitive damages resulting from your use of the Service."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"9. Termination"}),e.jsx("p",{children:"We may terminate or suspend your account at any time, without prior notice, for conduct that we believe violates these Terms or is harmful to other users, us, or third parties."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"10. Changes to Terms"}),e.jsx("p",{children:"We reserve the right to modify these Terms at any time. We will notify you of significant changes by posting a notice on our platform. Continued use of the Service constitutes acceptance of the modified terms."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"11. SMS / Text Messaging Terms (LevelUp Account & Lead Alerts)"}),e.jsxs("div",{className:"rounded-lg border border-primary/30 bg-primary/5 p-4 mb-4 text-sm",children:[e.jsx("strong",{children:"To opt in:"})," Submit our public SMS opt-in form at"," ",e.jsx("a",{href:"/sms-opt-in",className:"text-primary hover:underline font-medium",children:"/sms-opt-in"})," ","— consent is captured with timestamp and the exact disclosure text shown below."]}),e.jsx("p",{children:"By opting in to receive text messages from LevelUp, you agree to the following terms:"}),e.jsx("p",{className:"mt-2",children:"You consent to receive recurring SMS/MMS messages from LevelUp, including account notifications, real-time lead alerts, service updates, and customer support communications. Message frequency varies. Message and data rates may apply. Consent is not a condition of purchase."}),e.jsxs("p",{className:"mt-2",children:["You may opt out at any time by replying STOP to any message. After opting out, you will receive a confirmation message and no further messages will be sent. For assistance, reply HELP or contact us at"," ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"}),"."]}),e.jsxs("p",{className:"mt-2",children:["No mobile information will be shared with third parties or affiliates for marketing or promotional purposes. Text messaging originator opt-in data and consent will not be shared with any third parties. See our"," ",e.jsx("a",{href:"/privacy-policy",className:"text-primary hover:underline",children:"Privacy Policy"})," ","for full details."]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"12. LevelUp SmartSign SMS Terms"}),e.jsxs("p",{children:[e.jsx("strong",{children:"LevelUp SmartSign"})," is operated by ",e.jsx("strong",{children:"LevelUp Consulting Group"}),". Consumers text a property code displayed on a real estate sign to ",e.jsx("strong",{children:"859-413-5013"})," to request information about that property. LevelUp is the sender of these messages; independent real estate agents do not send messages through the SmartSign number. This program is separate from the LevelUp account and lead alert SMS program in section 11."]}),e.jsxs("ul",{className:"list-disc pl-6 mt-3 space-y-1",children:[e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Requested property responses:"})," texting a property code is a request for SMS responses about that property and your inquiry. LevelUp may reply with listing information, answers to your property questions, and help with showing requests."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Marketing is separate:"})," promotional texts about property updates and similar homes require a separate affirmative opt-in. Requesting property information does not subscribe you to marketing. ",e.jsx("strong",{children:"Consent is not a condition of purchase."})]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Agent contact is separate:"})," before sharing your contact details with a named agent and brokerage, LevelUp asks your permission separately. That permission does not enroll you in LevelUp marketing and does not transfer your LevelUp SMS consent to the agent."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Message frequency varies."})," Message and data rates may apply."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Opt out:"})," reply ",e.jsx("strong",{children:"STOP"})," to any message to stop further messages. Reply ",e.jsx("strong",{children:"HELP"})," for help."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Carrier liability:"})," carriers are not liable for delayed or undelivered messages."]})]}),e.jsxs("p",{className:"mt-3",children:["Support: ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"}),". How we handle SmartSign information is described in our"," ",e.jsx("a",{href:"/privacy-policy",className:"text-primary hover:underline",children:"Privacy Policy"}),". Program details and example disclosures are on the"," ",e.jsx("a",{href:"/sms-opt-in",className:"text-primary hover:underline",children:"SMS opt-in page"}),"."]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"13. Contact Us"}),e.jsxs("p",{children:["If you have questions about these Terms, please contact us at"," ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"})]})]})]})]})})]}),fFs=()=>e.jsxs(e.Fragment,{children:[e.jsxs(ul,{children:[e.jsx("title",{children:"Data Deletion | LevelUp"}),e.jsx("meta",{name:"description",content:"How to request deletion of your LevelUp data, and what is deleted or retained."})]}),e.jsx("div",{className:"min-h-screen bg-background py-12 px-4 sm:px-6 lg:px-8",children:e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsx("h1",{className:"text-3xl font-bold text-foreground mb-8",children:"Data Deletion Instructions"}),e.jsxs("div",{className:"prose prose-sm max-w-none text-muted-foreground space-y-6",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Last updated: August 25, 2026"}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"Delete records yourself"}),e.jsx("p",{children:"Most data can be removed directly in the app: contacts, deals, tasks, listings, open houses, landing pages, campaigns and uploaded media can each be deleted from their page. Disconnecting an integration (including the ChatGPT / MCP connector) immediately stops further access."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"Request account or bulk deletion"}),e.jsxs("p",{children:["Email"," ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"})," ",'with the subject "Data Deletion Request" and include your full name, the email address on the account and what you want deleted (the whole account, or specific categories such as MCP audit logs or Guest Book sign-ins). We verify the request against the account before acting on it.']})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"What account deletion removes"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Account and profile data, branding assets and connected-integration tokens."}),e.jsx("li",{children:"Contacts and their relationship fields, notes, tags and interaction logs."}),e.jsx("li",{children:"Deals, tasks, listings, uploaded media and generated marketing/campaign records."}),e.jsx("li",{children:"Guest Book open houses and the visitor sign-ins captured on them."}),e.jsx("li",{children:"Landing pages, property websites and the leads submitted through them, including FSBO and Listing Revival campaign leads."}),e.jsx("li",{children:"MCP audit log entries for your account."})]}),e.jsx("p",{className:"mt-3",children:"These records are deleted when we process the request. There is no automatic scheduled purge running in the background — deletion happens on account deletion or on a verified request."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"Category-specific notes"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"MCP audit logs"})," (member id, tool name, truncated tool inputs, outcome, duration, client id) are retained for security and support and are not purged on a timer. They are removed with the account, or earlier on request."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Campaign leads and Guest Book sign-ins"})," are records about other people that the member controls. A visitor or lead who wants their own record removed should ask the agent they signed in with, or email us and we will route it to that member and remove it."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Content already shared"})," — for example a listing published to the Listing Exchange and saved by another member, or a page a third party archived — may persist outside our control after deletion."]})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"What we retain"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Billing and transaction records required for financial and tax reporting."}),e.jsx("li",{children:"Records we must keep to comply with a legal obligation or to resolve a dispute."}),e.jsx("li",{children:"Anonymized or aggregated data that cannot identify you."}),e.jsx("li",{children:"Backup copies, until the backup cycle rotates them out after deletion."})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"Facebook / Instagram data"}),e.jsx("p",{children:"You can also revoke our access from Meta directly:"}),e.jsxs("ol",{className:"list-decimal pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Open Facebook Settings & Privacy → Settings"}),e.jsx("li",{children:'Click "Apps and Websites"'}),e.jsx("li",{children:'Find LevelUp and click "Remove"'})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"Timing"}),e.jsx("p",{children:"We aim to complete verified deletion requests within 30 days and will email you when it is done. If a request needs more time or is partly refused (for example where we must keep billing records), we will tell you why."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"Related"}),e.jsxs("p",{children:["See the ",e.jsx(ir,{to:"/privacy-policy",className:"text-primary hover:underline",children:"Privacy Policy"})," and the"," ",e.jsx(ir,{to:"/mcp-data-use",className:"text-primary hover:underline",children:"MCP data use"})," page, or contact"," ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"}),"."]})]})]})]})})]}),Txt=()=>e.jsxs(e.Fragment,{children:[e.jsxs(ul,{children:[e.jsx("title",{children:"MCP & ChatGPT Data Use | LevelUp"}),e.jsx("meta",{name:"description",content:"What the LevelUp Hub MCP connector shares with ChatGPT: data categories, purposes, recipients, retention and member controls."}),e.jsx("link",{rel:"canonical",href:"https://dashboard.relevelup.com/mcp-data-use"})]}),e.jsx("div",{className:"min-h-screen bg-background py-12 px-4 sm:px-6 lg:px-8",children:e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsx("h1",{className:"text-3xl font-bold text-foreground mb-2",children:"LevelUp Hub MCP — data use"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-8",children:"Last updated: August 25, 2026"}),e.jsxs("div",{className:"prose prose-sm max-w-none text-muted-foreground space-y-6",children:[e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"What this connector is"}),e.jsxs("p",{children:["LevelUp Hub publishes an MCP (Model Context Protocol) server. When a LevelUp member connects it to an AI client such as ChatGPT, that client can call LevelUp tools ",e.jsx("strong",{children:"as that member"}),", using an OAuth sign-in the member completes and can revoke. The connector is optional and off until the member connects it."]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"Data the tools can reach"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Profile and branding: name, email, phone, title, brokerage, license number and state, website, headshot and logo images, brand colors and any brokerage compliance line."}),e.jsx("li",{children:"Contacts (Agent OS / Inner Circle): names, emails, phones, addresses, lead source, notes, and the optional relationship fields a member chooses to store (birthday, home and wedding anniversary, spouse name/email/birthday, company, job title)."}),e.jsx("li",{children:"Deals, tasks and interaction logs: pipeline stage, prices, commissions, key dates, task text, and logged calls, texts, emails, pop-bys and notes."}),e.jsx("li",{children:"Listings and media: the member's listings plus listings other members published to the shared Listing Exchange, with photos, videos and agent/brokerage attribution."}),e.jsx("li",{children:"Guest Book open houses and their visitor sign-ins."}),e.jsx("li",{children:"Landing pages, property websites and the leads submitted through them."}),e.jsx("li",{children:"Marketing and campaign records generated through the tools (email, social, print, FSBO and Listing Revival drafts)."}),e.jsx("li",{children:"MCP audit logs: for every tool call we record the member id, tool name, a truncated snapshot of the tool inputs, the outcome, an error label, the duration and the calling client id."})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"Why"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"To answer the member's own questions about their business and to perform the actions they ask for."}),e.jsx("li",{children:"To draft marketing copy and assets when the member explicitly requests generation."}),e.jsx("li",{children:"To secure the connector: authentication, per-member rate limiting, abuse investigation and support."})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"Who receives data"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsxs("li",{children:[e.jsx("strong",{children:"LevelUp"})," and its hosting/database provider — where the data already lives."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"The connected AI client (OpenAI / ChatGPT, or another MCP client the member connects)"})," — it receives whatever a called tool returns, and it is governed by that client's own privacy terms."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"The Lovable AI Gateway and the model provider behind it"})," — only when a member requests copy generation, and only the property details and brand/contact block needed for that request. Nothing is sent there for read-only tools."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"The public"})," — only for pages the member publishes (open house sign-in pages, landing pages, property websites). Drafts are not published."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Other LevelUp members"})," — only for listings a member chose to publish to the Listing Exchange."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"LevelUp administrators"})," — an administrator may act on behalf of a member for support; those calls are recorded in the audit log with the target member."]})]}),e.jsx("p",{className:"mt-3",children:'The connector does not send email, SMS, direct mail or social posts. Tools that "activate" a campaign only change its status inside LevelUp and publish its page; outbound delivery is always a separate, member-initiated action in the app.'})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"Retention"}),e.jsx("p",{children:"Records created or edited through the connector follow the same retention as the rest of the member's LevelUp account: they are kept until the member deletes them or the account is deleted. MCP audit log entries are kept for security and support purposes and are not automatically purged on a fixed schedule; a member or administrator can ask us to remove them. Short-lived rate-limit counters expire on their own within minutes."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"Member controls"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Connect or disconnect the connector at any time from the AI client; revoking access stops all tool calls."}),e.jsx("li",{children:"Actions that publish, activate, merge or delete require an explicit confirmation step; without it the tool returns a preview and changes nothing."}),e.jsx("li",{children:"Open houses, landing pages and property sites are created as unpublished drafts unless the member asks for them to be published."}),e.jsx("li",{children:"Review every call in the member's MCP activity log, and edit or delete the underlying records in the app."}),e.jsxs("li",{children:["Request deletion or export by writing to ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"}),"."]})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"More"}),e.jsxs("p",{children:["See the ",e.jsx(ir,{to:"/privacy-policy",className:"text-primary hover:underline",children:"Privacy Policy"})," and"," ",e.jsx(ir,{to:"/data-deletion",className:"text-primary hover:underline",children:"Data Deletion"})," pages, or contact"," ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"}),"."]})]})]})]})})]}),Mxt="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.",xFs="I agree to receive recurring automated promotional texts from LevelUp SmartSign about property updates and similar homes. Consent is not a condition of purchase. Message frequency varies. Message and data rates may apply. Reply STOP to opt out or HELP for help.",gFs=Bj({name:Zo().trim().max(200).optional().or(gx("")),phone:Zo().trim().min(10,"Enter a valid mobile number").max(30).regex(/^[+\d\s()\-.]+$/,"Enter a valid mobile number"),email:Zo().trim().email("Enter a valid email").max(320).optional().or(gx(""))}),yFs=Bj({name:Zo().trim().min(1,"Name is required").max(200),phone:Zo().trim().min(10,"Enter a valid mobile number").max(30).regex(/^[+\d\s()\-.]+$/,"Enter a valid mobile number"),email:Zo().trim().email("Enter a valid email").max(320).optional().or(gx(""))});function vFs(){const[s,t]=_.useState(""),[n,r]=_.useState(""),[a,i]=_.useState(""),[l,o]=_.useState(!1),[c,d]=_.useState(!1),[u,h]=_.useState(!1),[m,p]=_.useState(!1),f=Fn(),[y,v]=_.useState(""),[g,b]=_.useState(""),[j,S]=_.useState(""),[C,E]=_.useState(!1),[P,M]=_.useState(!1),[I,D]=_.useState(!1),O=async G=>{var Z;if(G.preventDefault(),!C){se.error("Please check the marketing consent box to enroll.");return}const $=gFs.safeParse({name:y,phone:g,email:j});if(!$.success){se.error(((Z=$.error.issues[0])==null?void 0:Z.message)??"Please check your inputs.");return}M(!0);const{data:H,error:Y}=await q.functions.invoke("smartsign-marketing-optin",{body:{name:$.data.name||null,phone:$.data.phone,email:$.data.email||null,consent:!0,source_url:window.location.href}});if(M(!1),Y||!(H!=null&&H.ok)){se.error("We could not record your opt-in. Please try again.");return}D(!0),se.success("Your SmartSign marketing opt-in was recorded.")},V=async G=>{var Y;if(G.preventDefault(),!l){se.error("Please check the consent box to opt in.");return}const $=yFs.safeParse({name:s,phone:n,email:a});if(!$.success){se.error(((Y=$.error.issues[0])==null?void 0:Y.message)??"Please check your inputs.");return}d(!0);const{error:H}=await q.from("sms_opt_in_consents").insert({name:$.data.name,phone:$.data.phone,email:$.data.email||null,consent_text:Mxt,source:"web_form",user_agent:navigator.userAgent.slice(0,500)});if(d(!1),H){se.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 SmartSign | LevelUp"}),e.jsx("meta",{name:"description",content:"LevelUp SmartSign: text a property code to 859-413-5013 for property information. Also opt in to LevelUp account and lead alert texts. Message frequency varies, msg & data rates may apply, reply STOP to opt out or HELP for help."}),e.jsx("link",{rel:"canonical",href:"https://dashboard.relevelup.com/sms-opt-in"})]}),e.jsxs("div",{className:"max-w-2xl mx-auto",children:[e.jsxs("header",{className:"text-center mb-8",children:[e.jsx("div",{className:"inline-flex items-center justify-center w-14 h-14 rounded-2xl bg-primary/10 text-primary mb-4",children:e.jsx(Hi,{className:"w-7 h-7"})}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold tracking-tight",children:"LevelUp — SMS Programs"}),e.jsxs("p",{className:"text-muted-foreground mt-3 max-w-xl mx-auto",children:["LevelUp runs two separate text messaging programs. ",e.jsx("strong",{children:"LevelUp SmartSign"})," ","lets home shoppers text a property code from a real estate sign to get information about that property. ",e.jsx("strong",{children:"LevelUp Account & Lead Alerts"})," sends LevelUp members notifications about their own account. Each has its own number and its own consent."]})]}),e.jsxs(ve,{className:"p-6 md:p-8 mb-8",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[e.jsx("div",{className:"inline-flex items-center justify-center w-10 h-10 rounded-xl bg-primary/10 text-primary",children:e.jsx(aJ,{className:"w-5 h-5"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-semibold leading-tight",children:"LevelUp SmartSign"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Property information by text · Operated by LevelUp Consulting Group"})]})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"LevelUp SmartSign lets you request information about a home by texting the property code shown on the real estate sign. LevelUp responds with listing information, answers questions about the property, and can help with showing requests. LevelUp is the sender of these messages — independent real estate agents do not send messages through the LevelUp SmartSign number."}),e.jsxs("div",{className:"mt-5 rounded-lg border border-primary/30 bg-primary/5 p-4",children:[e.jsx("p",{className:"text-base font-semibold text-foreground",children:"Text the property code shown on the sign to 859-413-5013 to request information about that property from LevelUp SmartSign."}),e.jsxs("p",{className:"mt-3 text-xs leading-relaxed text-muted-foreground",children:["By texting a property code, you request SMS responses from LevelUp SmartSign about that property and your inquiry. Message frequency varies. Message and data rates may apply. Reply STOP to opt out or HELP for help. Requesting property information does not subscribe you to marketing updates. See our"," ",e.jsx(ir,{to:"/privacy-policy",className:"text-primary underline underline-offset-2",children:"Privacy Policy"})," ","and"," ",e.jsx(ir,{to:"/terms-of-service",className:"text-primary underline underline-offset-2",children:"Terms of Service"}),"."]})]}),e.jsxs("div",{className:"mt-6",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground mb-2",children:"Example sign — illustration only"}),e.jsxs("div",{className:"rounded-xl border-2 border-dashed border-primary/40 bg-background p-5 text-center",children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-[0.2em] text-primary",children:"LevelUp SmartSign"}),e.jsx("p",{className:"mt-3 text-sm font-medium text-foreground",children:"Text"}),e.jsx("p",{className:"text-3xl font-bold tracking-tight text-foreground",children:"1234"}),e.jsx("p",{className:"text-sm font-medium text-foreground",children:"to"}),e.jsx("p",{className:"text-2xl font-bold tracking-tight text-primary",children:"859-413-5013"}),e.jsx("p",{className:"mt-3 text-[11px] leading-relaxed text-muted-foreground",children:"Msg frequency varies. Msg & data rates may apply. Reply STOP to opt out, HELP for help. Requesting property info does not subscribe you to marketing."})]}),e.jsxs("p",{className:"mt-2 text-xs text-muted-foreground",children:[e.jsx("strong",{children:"1234 is an example property code used for illustration only."})," It is not an active listing and texting it will not return property information. Real property codes appear on the physical sign at the property."]})]}),e.jsxs("div",{className:"mt-8 space-y-4",children:[e.jsx("h3",{className:"text-base font-semibold text-foreground",children:"Three separate choices — each one is its own decision"}),e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-4",children:[e.jsx("p",{className:"text-sm font-semibold text-foreground",children:"1. Property information you requested"}),e.jsx("p",{className:"mt-1.5 text-sm text-muted-foreground",children:"When you text a property code, you are asking LevelUp SmartSign to reply about that property and your inquiry. That is all it does. It does not automatically enroll you in promotional or marketing updates. Reply STOP at any time to stop messages, or HELP for help."})]}),e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-4",children:[e.jsx("p",{className:"text-sm font-semibold text-foreground",children:"2. Optional LevelUp SmartSign marketing updates"}),e.jsx("p",{className:"mt-1.5 text-sm text-muted-foreground",children:"Marketing texts require a separate, affirmative choice that you make on purpose. They are never bundled with a property inquiry and are never combined with permission for an agent to contact you."}),I?e.jsxs("div",{className:"mt-4 rounded-md border border-primary/30 bg-primary/5 p-4",children:[e.jsx("p",{className:"text-sm font-semibold text-foreground",children:"Your marketing opt-in has been recorded."}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"We saved your number, the exact disclosure you agreed to, and the time of your consent. You can reply STOP to any message to opt out, or HELP for help."})]}):e.jsxs("form",{onSubmit:O,className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx(J,{htmlFor:"mkt-name",children:"Full name (optional)"}),e.jsx(xe,{id:"mkt-name",value:y,onChange:G=>v(G.target.value),maxLength:200,autoComplete:"name",className:"mt-1.5"})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"mkt-phone",children:"Mobile number"}),e.jsx(xe,{id:"mkt-phone",type:"tel",value:g,onChange:G=>b(G.target.value),maxLength:30,placeholder:"(555) 123-4567",autoComplete:"tel",className:"mt-1.5"})]})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"mkt-email",children:"Email (optional)"}),e.jsx(xe,{id:"mkt-email",type:"email",value:j,onChange:G=>S(G.target.value),maxLength:320,autoComplete:"email",className:"mt-1.5"})]}),e.jsx("div",{className:"rounded-md border bg-background p-3",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx($a,{id:"mkt-consent",checked:C,onCheckedChange:G=>E(G===!0),className:"mt-0.5"}),e.jsx(J,{htmlFor:"mkt-consent",className:"text-xs leading-relaxed font-normal cursor-pointer",children:xFs})]})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This box is optional and starts unchecked. Leaving it unchecked changes nothing. This consent is only for LevelUp SmartSign marketing texts — it is not account or lead alerts, and it is not permission for an agent to contact you."}),e.jsx(B,{type:"submit",disabled:!C||P,size:"sm",children:P?"Saving…":"Opt in to SmartSign marketing texts"})]})]}),e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-4",children:[e.jsx("p",{className:"text-sm font-semibold text-foreground",children:"3. Permission for an agent to contact you"}),e.jsx("p",{className:"mt-1.5 text-sm text-muted-foreground",children:"Before your contact details are shared with anyone, LevelUp identifies the actual agent and brokerage and asks you separately:"}),e.jsx("p",{className:"mt-2 rounded-md border bg-background p-3 text-xs leading-relaxed text-muted-foreground",children:'"Would you like [Agent Name] at [Brokerage] to contact you about [Property]? If you agree, LevelUp will share your name, phone number, and property inquiry with this agent to respond to your request."'}),e.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:'Agreeing to an agent contacting you does not enroll you in LevelUp marketing texts and does not transfer your LevelUp SMS consent to that agent. A single checkbox or an ambiguous "YES" is never used for both purposes.'})]})]})]}),e.jsxs("div",{className:"mb-6 rounded-lg border border-primary/30 bg-primary/5 p-4",children:[e.jsx("p",{className:"text-sm font-semibold text-foreground",children:"A separate program: LevelUp Account & Lead Alerts"}),e.jsx("p",{className:"text-sm mt-1 text-muted-foreground",children:"The form below is for LevelUp members (real estate agents) who want account notifications and lead alerts about their own LevelUp account. It is a different program from LevelUp SmartSign, uses a different number, and consent to one is never consent to the other. SMS notifications are optional — you may use LevelUp without providing a mobile number or consenting to text messages."})]}),m?e.jsxs(ve,{className:"p-8 text-center",children:[e.jsx(Er,{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(B,{className:"mt-6",onClick:()=>f("/auth"),children:"Continue to LevelUp"})]}):u?e.jsxs(ve,{className:"p-8 text-center",children:[e.jsx(Er,{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(ve,{className:"p-6 md:p-8",children:e.jsxs("form",{onSubmit:V,className:"space-y-5",children:[e.jsxs("div",{children:[e.jsx(J,{htmlFor:"name",children:"Full Name (only if you opt in to SMS)"}),e.jsx(xe,{id:"name",value:s,onChange:G=>t(G.target.value),maxLength:200,autoComplete:"name",className:"mt-1.5"})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"phone",children:"Mobile Number (only if you opt in to SMS)"}),e.jsx(xe,{id:"phone",type:"tel",value:n,onChange:G=>r(G.target.value),maxLength:30,placeholder:"(555) 123-4567",autoComplete:"tel",className:"mt-1.5"})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"email",children:"Email (optional)"}),e.jsx(xe,{id:"email",type:"email",value:a,onChange:G=>i(G.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($a,{id:"consent",checked:l,onCheckedChange:G=>o(G===!0),className:"mt-0.5"}),e.jsx(J,{htmlFor:"consent",className:"text-sm leading-relaxed font-normal cursor-pointer",children:Mxt})]})}),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(ir,{to:"/terms-of-service",className:"text-primary underline underline-offset-2",children:"SMS Terms & Conditions"})," ","and"," ",e.jsx(ir,{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(B,{type:"submit",disabled:!l||c,className:"w-full",size:"lg",children:c?"Submitting…":"Opt in to SMS"}),e.jsx(B,{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(Dm,{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 GPe="/assets/levelup-logo-horizontal-DEFNc0ms.png",bFs=Bj({email:Zo().email("Invalid email address"),password:Zo().min(6,"Password must be at least 6 characters")}),e9t="https://dashboard.relevelup.com",Nle="/oauth-connect",_Fs=`${e9t}/profile?reset=true`,L4e="levelupOAuthRouteHistory";function Pxt(s){return s.startsWith("/")&&!s.startsWith("//")&&!s.includes("://")}function wFs(s){const t=Date.now(),n=15e3;try{const i=[...JSON.parse(sessionStorage.getItem(L4e)??"[]").filter(o=>t-o.ato.route));return i.length>=6&&l.has("auth")&&l.has("consent")}catch{return sessionStorage.setItem(L4e,JSON.stringify([{route:s,at:t}])),!1}}function jFs(){sessionStorage.removeItem(L4e)}const NFs=()=>{const{signIn:s,user:t,loading:n}=hs(),r=(t==null?void 0:t.id)??null,a=Fn(),[i]=Yl(),l=i.get("authorization_id")??"",o=i.get("next")??"",[c,d]=_.useState(!1),[u,h]=_.useState({}),[m,p]=_.useState(""),[f,y]=_.useState(!1),[v,g]=_.useState(!1),[b,j]=_.useState(null),[S,C]=_.useState(null),[E,P]=_.useState(!1),[M,I]=_.useState(!1),[D,O]=_.useState(()=>{if(i.get("paused")!=="1")return null;let Y="";try{Y=sessionStorage.getItem("accountPausedReason")||""}catch{}return Y?`Your account is paused. ${Y}`:"Your account is paused. Please contact LevelUp support to reactivate it."}),V=_.useRef(!1);_.useEffect(()=>{if(l&&window.location.hostname==="tile-portal.lovable.app"){const Y=new URL("/auth",e9t);Y.searchParams.set("next",`${Nle}?authorization_id=${encodeURIComponent(l)}`),window.location.replace(Y.toString());return}if(l){const Y=`${Nle}?authorization_id=${encodeURIComponent(l)}`;sessionStorage.setItem("redirectAfterLogin",Y);return}o&&Pxt(o)&&sessionStorage.setItem("redirectAfterLogin",o)},[l,o]),_.useEffect(()=>{if(n||!r||V.current)return;const Y=l?`${Nle}?authorization_id=${encodeURIComponent(l)}`:sessionStorage.getItem("redirectAfterLogin")||"/dashboard";if(!Pxt(Y)){sessionStorage.removeItem("redirectAfterLogin"),V.current=!0,a("/dashboard",{replace:!0});return}const Z=Y.startsWith(Nle)||Y.startsWith("/oauth/consent")||Y.startsWith("/.lovable/oauth/consent");if(Z&&wFs("auth")){j("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}V.current=!0,Z||(jFs(),sessionStorage.removeItem("redirectAfterLogin")),a(Y,{replace:!0})},[l,n,a,r]);const G=async Y=>{Y.preventDefault(),h({}),O(null),C(null),P(!1),d(!0);const Z=new FormData(Y.currentTarget),ne=Z.get("email"),ce=Z.get("password");try{bFs.parse({email:ne,password:ce}),await s(ne,ce)}catch(ie){if(ie instanceof Y5s){const te={};ie.issues.forEach(ae=>{ae.path[0]&&(te[ae.path[0]]=ae.message)}),h(te)}else if(ie instanceof Error&&ie.name==="AccountPaused")O(ie.message);else if(ne)try{const{data:te}=await q.functions.invoke("account-activation-status",{body:{email:ne}});te!=null&&te.needsActivation&&C(ne)}catch{}}finally{d(!1)}},$=async()=>{if(S){I(!0);try{const{data:Y,error:Z}=await q.functions.invoke("send-password-reset",{body:{email:S,variant:"activation"}});if(Z)throw Z;if((Y==null?void 0:Y.sent)===!1)throw new Error("We couldn't send the activation email. Please try again in a moment or contact support.");P(!0),se.success("Activation email sent! Check your inbox.")}catch(Y){se.error(Y instanceof Error?Y.message:"Failed to send activation email")}finally{I(!1)}}},H=async()=>{if(!m){se.error("Please enter your email address");return}y(!0);try{const{data:Y,error:Z}=await q.functions.invoke("send-password-reset",{body:{email:m.trim().toLowerCase(),redirectTo:_Fs}});if(Z)throw Z;if((Y==null?void 0:Y.sent)===!1){se.error("We couldn't find a LevelUp account for that email. Double-check the address, or email hello@relevelup.com and we'll help.");return}se.success("Password reset email sent! Check your inbox."),g(!1),p("")}catch(Y){se.error(Y instanceof Error?Y.message:"Failed to send reset email")}finally{y(!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(ir,{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:GPe,alt:"LevelUp",className:"h-12 w-auto"})})}),e.jsxs(ve,{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(St,{className:"text-3xl font-bold text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:"Welcome Back"}),e.jsx(kn,{className:"text-gray-600",children:b||"Sign in to access your dashboard"})]}),e.jsxs(Me,{children:[D&&e.jsxs("div",{className:"mb-4 rounded-lg border border-amber-300 bg-amber-50 p-4 text-left",children:[e.jsx("p",{className:"text-sm font-semibold text-amber-900",children:"Account paused"}),e.jsx("p",{className:"mt-1 text-sm text-amber-800",children:D}),e.jsx("a",{href:"mailto:support@relevelup.com",className:"mt-2 inline-block text-sm font-medium text-amber-900 underline",children:"Contact support"})]}),S&&e.jsxs("div",{className:"mb-4 rounded-lg border border-[#4a6b6d]/30 bg-[#f2f7f7] p-4 text-left",children:[e.jsx("p",{className:"text-sm font-semibold text-[#2a4347]",children:"You haven't set a password yet"}),e.jsx("p",{className:"mt-1 text-sm text-gray-700",children:E?`We just emailed ${S} a link to set your password and sign in. Check your inbox (and spam folder).`:`Your LevelUp account for ${S} is ready — it just needs a password. We'll email you a link to set one.`}),!E&&e.jsx(B,{type:"button",onClick:$,disabled:M,className:"mt-3 bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white",children:M?"Sending...":"Email me a set-password link"})]}),e.jsxs("form",{onSubmit:G,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"signin-email",className:"text-gray-700",children:"Email"}),e.jsx(xe,{id:"signin-email",name:"email",type:"email",placeholder:"your@email.com",required:!0,className:"border-gray-300 focus:border-[#4a6b6d] focus:ring-[#4a6b6d]"}),u.email&&e.jsx("p",{className:"text-sm text-red-600",children:u.email})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"signin-password",className:"text-gray-700",children:"Password"}),e.jsx(xe,{id:"signin-password",name:"password",type:"password",required:!0,className:"border-gray-300 focus:border-[#4a6b6d] focus:ring-[#4a6b6d]"}),u.password&&e.jsx("p",{className:"text-sm text-red-600",children:u.password})]}),e.jsx(B,{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(Ls,{open:v,onOpenChange:g,children:[e.jsx(nl,{asChild:!0,children:e.jsx(B,{variant:"link",className:"w-full text-sm text-[#4a6b6d] hover:text-[#3d5a5c]",children:"Forgot password?"})}),e.jsxs(Ps,{className:"bg-white",children:[e.jsxs(Os,{children:[e.jsx(Ds,{className:"text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:"Reset Password"}),e.jsx(_r,{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(J,{htmlFor:"reset-email",className:"text-gray-700",children:"Email"}),e.jsx(xe,{id:"reset-email",type:"email",placeholder:"your@email.com",value:m,onChange:Y=>p(Y.target.value),className:"border-gray-300 focus:border-[#4a6b6d] focus:ring-[#4a6b6d]"})]}),e.jsx(B,{onClick:H,className:"w-full bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white",disabled:f,children:f?"Sending...":"Send Reset Link"})]})]})]})]})]})]}),e.jsxs("p",{className:"text-center text-white/70 text-sm mt-6",children:["Don't have an account?"," ",e.jsx(ir,{to:"/",className:"text-white hover:underline font-medium",children:"View Plans"})]})]})})]})]})},Lxt=()=>q.auth.oauth,kFs="https://dashboard.relevelup.com",SFs="/oauth-connect",I4e="levelupOAuthRouteHistory",CFs="https://relzejiswnotikjgvjhz.supabase.co/auth/v1",AFs="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM";function EFs(s){return s.startsWith("/")&&!s.startsWith("//")&&!s.includes("://")}function TFs(s){const t=Date.now(),n=15e3;try{const i=[...JSON.parse(sessionStorage.getItem(I4e)??"[]").filter(o=>t-o.ato.route));return i.length>=6&&l.has("auth")&&l.has("consent")}catch{return sessionStorage.setItem(I4e,JSON.stringify([{route:s,at:t}])),!1}}function MFs(){sessionStorage.removeItem(I4e)}async function Ixt(s,t,n){const r=await fetch(`${CFs}${s}`,{...n,headers:{Authorization:`Bearer ${t}`,apikey:AFs,"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 $Oe(){var y;const{user:s,session:t,loading:n}=hs(),r=(s==null?void 0:s.id)??null,a=(t==null?void 0:t.access_token)??null,[i]=Yl(),l=i.get("authorization_id")??"",[o,c]=_.useState(null),[d,u]=_.useState(null),[h,m]=_.useState(!1);_.useEffect(()=>{let v=!0;return(async()=>{if(!l){u("Missing authorization_id");return}const g=`${SFs}?authorization_id=${encodeURIComponent(l)}`;if(window.location.hostname==="tile-portal.lovable.app"){window.location.href=`${kFs}${g}`;return}if(n)return;if(!r){if(TFs("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}EFs(g)&&sessionStorage.setItem("redirectAfterLogin",g),window.location.replace(`/auth?next=${encodeURIComponent(g)}`);return}if(!a)return;MFs(),sessionStorage.removeItem("redirectAfterLogin");const b=Lxt(),{data:j,error:S}=b?await b.getAuthorizationDetails(l):await Ixt(`/oauth/authorizations/${encodeURIComponent(l)}`,a);if(!v)return;if(S){u(S.message);return}const C=(j==null?void 0:j.redirect_url)??(j==null?void 0:j.redirect_to);if(C&&!(j!=null&&j.client)){window.location.href=C;return}c(j)})(),()=>{v=!1}},[a,l,n,r]);async function p(v){if(!(t!=null&&t.access_token)){u("Your sign-in session is not ready yet. Please refresh and try again.");return}m(!0);const g=Lxt(),{data:b,error:j}=g?v?await g.approveAuthorization(l,{skipBrowserRedirect:!0}):await g.denyAuthorization(l,{skipBrowserRedirect:!0}):await Ixt(`/oauth/authorizations/${encodeURIComponent(l)}/consent`,t.access_token,{method:"POST",body:JSON.stringify({action:v?"approve":"deny"})});if(j){m(!1),u(j.message);return}const S=(b==null?void 0:b.redirect_url)??(b==null?void 0:b.redirect_to);if(!S){m(!1),u("No redirect returned by the authorization server.");return}window.location.href=S}if(d)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsx(ve,{className:"w-full max-w-md",children:e.jsxs(bt,{children:[e.jsx(St,{children:"Authorization error"}),e.jsx(kn,{children:d})]})})});if(!o)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsx(Ct,{className:"h-8 w-8 animate-spin text-primary"})});const f=((y=o.client)==null?void 0:y.name)??"An app";return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(ve,{className:"w-full max-w-md",children:[e.jsxs(bt,{children:[e.jsxs(St,{children:["Connect ",f," to LevelUp"]}),e.jsxs(kn,{children:[f," is requesting access to use LevelUp tools on your behalf. You can revoke access at any time."]})]}),e.jsxs(Me,{className:"flex gap-3 justify-end",children:[e.jsx(B,{variant:"outline",disabled:h,onClick:()=>p(!1),children:"Deny"}),e.jsx(B,{disabled:h,onClick:()=>p(!0),children:h?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):"Approve"})]})]})})}const PFs="https://chatgpt.com/plugins/plugin_asdk_app_6a7b9baf757081918ac4ab6fcbdb2639?q=levelup",Dxt="https://relzejiswnotikjgvjhz.supabase.co/functions/v1/mcp",LFs="https://tile-portal.lovable.app/mcp-oauth-bridge.html",IFs=[{label:"Open the ChatGPT Store",description:"Use the button below to open the LevelUp plugin page in the ChatGPT Store."},{label:"Install the plugin",description:"Tap Install. ChatGPT Plus, Pro, or Team is required to use plugins."},{label:"Sign in to LevelUp",description:"ChatGPT will open a LevelUp consent page. Sign in with your LevelUp account and tap Approve."},{label:"Start chatting",description:"Ask ChatGPT to 'list my upcoming LevelUp trainings' or 'summarize my contacts'."}],DFs=[{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 RFs(){const[s,t]=_.useState(!1),n=async()=>{try{await navigator.clipboard.writeText(Dxt),t(!0),se.success("MCP URL copied to clipboard"),setTimeout(()=>t(!1),2e3)}catch{se.error("Could not copy URL")}};return e.jsx(zs,{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(V4,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Connect ChatGPT to LevelUp"}),e.jsx("p",{className:"text-muted-foreground",children:"Install the official LevelUp plugin from the ChatGPT Store."})]})]}),e.jsxs(ve,{className:"border-primary/20 bg-primary/5",children:[e.jsxs(bt,{children:[e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-5 w-5 text-primary"}),"Install from the ChatGPT Store"]}),e.jsx(kn,{children:"The easiest way to connect. Tap the button below, then install the LevelUp plugin in ChatGPT."})]}),e.jsx(Me,{children:e.jsx(B,{asChild:!0,size:"lg",className:"w-full sm:w-auto",children:e.jsxs("a",{href:PFs,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(wr,{className:"h-4 w-4 mr-2"}),"Open LevelUp in the ChatGPT Store"]})})})]}),e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsx(St,{children:"Quick steps"}),e.jsx(kn,{children:"Share these steps with any agent who wants to connect via the plugin store."})]}),e.jsx(Me,{children:e.jsx("ol",{className:"space-y-4",children:IFs.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(ve,{children:[e.jsxs(bt,{children:[e.jsx(St,{children:"Manual MCP setup"}),e.jsx(kn,{children:"Only use this if you are adding LevelUp as a custom MCP server instead of installing the store plugin."})]}),e.jsxs(Me,{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("code",{className:"flex-1 block rounded-md bg-muted px-3 py-2 text-sm break-all",children:Dxt}),e.jsx(B,{variant:"outline",size:"icon",onClick:n,"aria-label":"Copy MCP URL",children:s?e.jsx(_l,{className:"h-4 w-4 text-green-600"}):e.jsx(Ia,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"rounded-lg border border-destructive/30 bg-destructive/5 p-4 text-sm",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(xl,{className:"h-5 w-5 text-destructive shrink-0 mt-0.5"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"font-semibold text-destructive",children:"Do not use the bridge URL as the Server URL."}),e.jsx("p",{className:"text-muted-foreground",children:"If ChatGPT shows “does not implement OAuth,” it means this wrong URL was pasted:"}),e.jsx("code",{className:"block rounded-md bg-background px-3 py-2 break-all text-xs",children:LFs}),e.jsx("p",{className:"text-muted-foreground",children:"Delete that plugin attempt and create a new one with the MCP server URL above."})]})]})}),e.jsx("ol",{className:"space-y-4",children:DFs.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(ve,{children:[e.jsxs(bt,{children:[e.jsx(St,{children:"What ChatGPT can see"}),e.jsx(kn,{children:"The connector acts as you. Before connecting, review exactly which data it can reach, who receives it, how long it is kept and how to disconnect."})]}),e.jsxs(Me,{className:"flex flex-wrap gap-4 text-sm",children:[e.jsx("a",{href:"/mcp-data-use",className:"text-primary underline underline-offset-4",children:"MCP data use"}),e.jsx("a",{href:"/privacy-policy",className:"text-primary underline underline-offset-4",children:"Privacy Policy"}),e.jsx("a",{href:"/data-deletion",className:"text-primary underline underline-offset-4",children:"Data deletion"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(wr,{className:"h-4 w-4"}),e.jsx("span",{children:"Publishing, activating, merging and deleting always ask you to confirm first, and new open houses and pages start as unpublished drafts."})]})]})})}const FFs=()=>{const[s]=Yl(),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(ve,{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(_l,{className:"w-10 h-10 text-green-500"})}),e.jsx(St,{className:"text-2xl",children:"Welcome to LevelUp!"}),e.jsx(kn,{className:"text-lg",children:"Your subscription has been activated successfully."})]}),e.jsxs(Me,{className:"space-y-6",children:[e.jsxs("div",{className:"p-4 rounded-lg bg-primary/10 border border-primary/20 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-primary",children:[e.jsx(ln,{className:"w-5 h-5"}),e.jsx("span",{className:"font-semibold",children:"Check your email to sign in"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"We've sent you an email with a secure link to access your account. Click the link in your email to get started."})]}),n?e.jsxs("div",{className:"space-y-3",children:[e.jsx("h3",{className:"font-semibold",children:"What's next?"}),e.jsxs("ul",{className:"space-y-2 text-sm text-muted-foreground",children:[e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"font-bold text-primary",children:"1."}),"Click the link in your email to sign in"]}),e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"font-bold text-primary",children:"2."}),"Create and name your brokerage"]}),e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"font-bold text-primary",children:"3."}),"Set your password and complete your profile"]}),e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"font-bold text-primary",children:"4."}),"Start inviting agents to join your team"]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsx("h3",{className:"font-semibold",children:"What's next?"}),e.jsxs("ul",{className:"space-y-2 text-sm text-muted-foreground",children:[e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"font-bold text-primary",children:"1."}),"Click the link in your email to sign in"]}),e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"font-bold text-primary",children:"2."}),"Set your password and complete your profile"]}),e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"font-bold text-primary",children:"3."}),"Start exploring templates, training videos, and more!"]})]}),e.jsx("p",{className:"text-sm text-green-600 font-medium mt-4",children:"🎉 Your 7-day free trial has started!"})]}),e.jsx("div",{className:"p-3 rounded-lg bg-muted/50 text-center",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Didn't receive the email? Check your spam folder or contact support."})})]})]})})},OFs=()=>{const{user:s}=hs(),[t,n]=_.useState(!1),[r,a]=_.useState(null),[i,l]=_.useState(""),o=async u=>{var h;if(!(s!=null&&s.email)){se.error("Please sign in to upgrade");return}n(!0),a(u);try{const{data:m,error:p}=await q.functions.invoke("create-checkout",{body:{tier:u,email:s.email,name:((h=s.user_metadata)==null?void 0:h.full_name)||s.email,userId:s.id,couponCode:i.trim()||void 0,skipTrial:!0}});if(p)throw p;if(m!=null&&m.url)window.open(m.url,"_blank","noopener,noreferrer"),se.success("Checkout opened in a new tab");else throw new Error("No checkout URL returned")}catch(m){console.error("Checkout error:",m),se.error(m.message||"Failed to start checkout. Please try again.")}finally{n(!1),a(null)}},c=["Unlimited access to all marketing templates","Complete Academy training library","AI-powered tools and resources","Community forums and support","Exclusive member events and workshops","Deal pipeline & scorecard tracking","Listing exchange access","Social media content library"],d=["Everything in Individual plan, plus:","Unlimited agent seats","Brokerage admin dashboard","Team performance analytics","Custom branding options","Priority support","Agent onboarding tools","Brokerage-wide announcements"];return e.jsx(zs,{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(J,{htmlFor:"coupon",className:"text-sm font-medium",children:"Have a discount code?"}),e.jsx(xe,{id:"coupon",placeholder:"Enter discount code",value:i,onChange:u=>l(u.target.value),className:"mt-1"})]}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-6 mb-8 max-w-4xl mx-auto",children:[e.jsxs(ve,{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(In,{className:"h-7 w-7 text-primary"})}),e.jsx(St,{className:"text-xl",children:"Individual Agent"}),e.jsx(kn,{children:"Perfect for solo agents ready to level up"})]}),e.jsxs(Me,{className:"space-y-6",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("span",{className:"text-4xl font-bold text-primary",children:"$39"}),e.jsx("span",{className:"text-muted-foreground",children:"/month"})]}),e.jsx("ul",{className:"space-y-2",children:c.map((u,h)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(ea,{className:"h-4 w-4 text-primary mt-0.5 shrink-0"}),e.jsx("span",{children:u})]},h))}),e.jsxs(B,{className:"w-full",size:"lg",onClick:()=>o("individual_agent"),disabled:t,children:[t&&r==="individual_agent"?e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(un,{className:"h-4 w-4 mr-2"}),"Get Started"]})]})]}),e.jsxs(ve,{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(St,{className:"text-xl",children:"Brokerage"}),e.jsx(kn,{children:"Unlimited agents — everything in Individual, plus brokerage tools"})]}),e.jsxs(Me,{className:"space-y-6",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("span",{className:"text-4xl font-bold text-purple-600",children:"$499"}),e.jsx("span",{className:"text-muted-foreground",children:"/month"})]}),e.jsx("ul",{className:"space-y-2",children:d.map((u,h)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(ea,{className:"h-4 w-4 text-purple-600 mt-0.5 shrink-0"}),e.jsx("span",{children:u})]},h))}),e.jsxs(B,{variant:"outline",className:"w-full border-purple-500 text-purple-600 hover:bg-purple-50",size:"lg",onClick:()=>o("brokerage_over_25"),disabled:t,children:[t&&r==="brokerage_over_25"?e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(ai,{className:"h-4 w-4 mr-2"}),"Get Started"]})]})]})]}),e.jsx(ve,{className:"bg-muted/50",children:e.jsxs(Me,{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(_a,{className:"h-4 w-4"}),e.jsx("span",{children:"1-866-527-8668"})]}),e.jsxs("a",{href:"mailto:support@relevelup.com",className:"flex items-center justify-center gap-2 text-primary hover:underline",children:[e.jsx(ln,{className:"h-4 w-4"}),e.jsx("span",{children:"support@relevelup.com"})]})]})]})})]})})},zFs=()=>{const{user:s,loading:t,isBrokerageManager:n,brokerageId:r}=hs(),a=Fn(),[i,l]=_.useState(""),[o,c]=_.useState(!1),[d,u]=_.useState(!1);_.useEffect(()=>{!t&&!s&&a("/auth")},[s,t,a]),_.useEffect(()=>{!t&&s&&r&&a("/profile?setup=true")},[s,t,r,a]);const h=async()=>{if(!i.trim()){se.error("Please enter a brokerage name");return}const{data:m}=await q.auth.getSession(),p=m.session;if(!s||!p){se.error("Please sign in again to create your brokerage."),a("/auth");return}c(!0);try{console.log("[SetupBrokerage] Creating brokerage…",{hasUser:!!s,hasSession:!!p,userId:s==null?void 0:s.id});const{data:f,error:y}=await q.functions.invoke("create-brokerage",{body:{name:i.trim()}});if(console.log("[SetupBrokerage] create-brokerage response",{data:f,error:y}),y)throw y;if(!(f!=null&&f.ok))throw new Error((f==null?void 0:f.error)||"Failed to create brokerage");c(!1),u(!0),se.success("Brokerage created! Setting up your account..."),setTimeout(()=>{a("/profile?setup=true")},2e3)}catch(f){console.error("Error creating brokerage:",f),se.error(f.message||"Failed to create brokerage"),c(!1)}};return t?e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):d?e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-background via-primary/5 to-secondary/10 flex items-center justify-center p-4",children:e.jsxs(ve,{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(Ct,{className:"w-10 h-10 text-primary animate-spin"})}),e.jsx(St,{className:"text-2xl",children:"Setting Up Your Brokerage"}),e.jsx(kn,{className:"text-lg",children:"We're assigning you as the brokerage manager and preparing your dashboard..."})]}),e.jsxs(Me,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-center gap-2 text-muted-foreground",children:[e.jsx(_l,{className:"w-5 h-5 text-green-500"}),e.jsx("span",{children:"Brokerage created"})]}),e.jsxs("div",{className:"flex items-center justify-center gap-2 text-muted-foreground",children:[e.jsx(Ct,{className:"w-5 h-5 animate-spin text-primary"}),e.jsx("span",{children:"Assigning you as manager..."})]}),e.jsx("p",{className:"text-center text-sm text-muted-foreground mt-4",children:"You'll be redirected to complete your profile setup in a moment."})]})]})}):e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-background via-primary/5 to-secondary/10 flex items-center justify-center p-4",children:e.jsxs(ve,{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(St,{className:"text-2xl",children:"Set Up Your Brokerage"}),e.jsx(kn,{className:"text-lg",children:"Create your brokerage to start managing your team"})]}),e.jsxs(Me,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"brokerage-name",children:"Brokerage Name"}),e.jsx(xe,{id:"brokerage-name",placeholder:"Enter your brokerage name",value:i,onChange:m=>l(m.target.value),onKeyDown:m=>m.key==="Enter"&&h()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This is how your brokerage will appear to your agents"})]}),e.jsxs("div",{className:"p-4 rounded-lg bg-muted/50 space-y-3",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2",children:[e.jsx(In,{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(_l,{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(_l,{className:"w-4 h-4 text-green-500"}),"Access exclusive brokerage resources"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx(_l,{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(_l,{className:"w-4 h-4 text-green-500"}),"Share resources with your agents"]})]})]}),e.jsxs(B,{onClick:h,className:"w-full",disabled:o||!i.trim(),children:[o?"Creating...":"Create Brokerage",e.jsx(La,{className:"w-4 h-4 ml-2"})]})]})]})})},Rxt=()=>{const s=Fn(),[t,n]=_.useState("verifying"),[r,a]=_.useState("");_.useEffect(()=>{(async()=>{try{const{data:{session:o},error:c}=await q.auth.getSession();if(c)throw c;if(o!=null&&o.user){const{data:d}=await q.from("profiles").select("login_count").eq("id",o.user.id).single();if(((d==null?void 0:d.login_count)||0)>1){console.log("Account already claimed, redirecting to dashboard"),n("already_claimed");return}console.log("User logged in successfully:",o.user.email),n("success");try{await q.functions.invoke("trial-claim-hook",{body:{userId:o.user.id}})}catch(u){console.log("Trial claim hook (non-critical):",u)}setTimeout(()=>{s("/profile?setup=true")},1500)}else setTimeout(()=>{n("already_claimed")},2e3)}catch(o){console.error("Claim error:",o),n("already_claimed")}})()},[s]);const i=()=>{window.location.href="https://dashboard.relevelup.com/auth"};return e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background p-4",children:e.jsxs(ve,{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(St,{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(kn,{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(Me,{children:e.jsx(B,{onClick:i,className:"w-full",children:"Go to Login"})})]})})},kle="https://dashboard.relevelup.com",Fxt=()=>{const[s,t]=_.useState(!1),n=_.useMemo(()=>new URLSearchParams(window.location.search),[]),r=_.useMemo(()=>n.get("link"),[n]),a=_.useMemo(()=>n.get("type")||"recovery",[n]),i=_.useMemo(()=>{switch(a){case"claim":return{title:"Claim Your Account",cta:"Continue to Claim Account",doc:"Claim Your LevelUp Account"};case"magiclink":return{title:"Sign In to LevelUp",cta:"Continue to Sign In",doc:"Sign In to LevelUp"};case"email_change":return{title:"Confirm Your Email",cta:"Continue to Confirm Email",doc:"Confirm Your Email"};default:return{title:"Reset Your Password",cta:"Continue to Reset Password",doc:"Reset Your Password"}}},[a]),l=_.useMemo(()=>{if(!r)return!1;try{const f=new URL(r);return f.hostname.endsWith(".supabase.co")&&f.pathname.startsWith("/auth/v1/verify")}catch{return!1}},[r]);_.useEffect(()=>{document.title=i.doc},[i]);const[o,c]=_.useState(null),[d,u]=_.useState("idle"),h=_.useMemo(()=>{if(!r)return null;try{return new URL(r).searchParams.get("email")}catch{return null}},[r]),m=async()=>{var f;u("sending");try{const y=h||((f=window.prompt("Enter the email address on your LevelUp account:"))==null?void 0:f.trim());if(!y){u("idle");return}const{error:v}=await q.functions.invoke("send-password-reset",{body:{email:y,variant:a==="recovery"?"reset":"activation"}});u(v?"failed":"sent")}catch{u("failed")}},p=async()=>{if(!(!l||!r)){if(t(!0),c(null),window.location.origin!==kle&&window.location.hostname!=="localhost"){window.location.href=`${kle}${window.location.pathname}${window.location.search}`;return}try{const f=new URL(r),y=f.searchParams.get("token")||f.searchParams.get("token_hash"),v=f.searchParams.get("type")||(a==="claim"?"invite":a);if(y){const{error:g}=await q.auth.verifyOtp({token_hash:y,type:v});if(!g){const b=f.searchParams.get("redirect_to");let j=v==="recovery"?"/profile?reset=true":"/dashboard";if(b)try{const S=new URL(b);j=`${S.pathname}${S.search}`}catch{}window.location.replace(`${kle}${j}`);return}t(!1),c("This link is invalid or has already been used. Please request a new email.");return}}catch{}window.location.href=r}};return e.jsxs("div",{className:"min-h-screen relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-[#4a6b6d] via-[#3d5a5c] to-[#2a4347]"}),e.jsx("div",{className:"relative z-10 flex flex-col min-h-screen items-center justify-center p-4",children:e.jsxs("div",{className:"w-full max-w-md",children:[e.jsx("div",{className:"flex justify-center mb-8",children:e.jsx("div",{className:"bg-white rounded-xl p-4 shadow-2xl",children:e.jsx("img",{src:GPe,alt:"LevelUp",className:"h-12 w-auto"})})}),e.jsxs(ve,{className:"border-0 shadow-2xl bg-white/95 backdrop-blur-sm",children:[e.jsxs(bt,{className:"text-center",children:[e.jsx(St,{className:"text-2xl font-bold text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:i.title}),e.jsx(kn,{className:"text-gray-600 pt-2",children:o||(l?"Click the button below to continue securely.":"This link is invalid or has expired. Please request a new email from the sign-in page.")})]}),e.jsxs(Me,{className:"space-y-4",children:[l&&!o?e.jsx(B,{onClick:p,disabled:s,className:"w-full bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white font-semibold py-6 text-lg shadow-lg hover:shadow-xl",children:s?"Continuing…":i.cta}):d==="sent"?e.jsx("div",{className:"rounded-lg bg-emerald-50 border border-emerald-200 p-4 text-center text-sm text-emerald-800",children:"A fresh link is on its way — check your inbox in the next minute or two."}):e.jsxs(e.Fragment,{children:[e.jsx(B,{onClick:m,disabled:d==="sending",className:"w-full bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white font-semibold py-6 text-lg shadow-lg hover:shadow-xl",children:d==="sending"?"Sending…":"Email me a fresh link"}),d==="failed"&&e.jsx("p",{className:"text-xs text-center text-red-600",children:"We couldn't send that just now. Please try again in a moment."}),e.jsx(B,{variant:"outline",onClick:()=>window.location.href=`${kle}/auth`,className:"w-full py-6 text-base",children:"Go to Sign In"})]}),e.jsx("p",{className:"text-xs text-center text-gray-500 pt-2",children:"For your security, these links expire and can only be used once."})]})]})]})})]})},Sle="https://dashboard.relevelup.com",BFs=()=>{const s=_.useMemo(()=>new URLSearchParams(window.location.search).get("a")||"",[]),[t,n]=_.useState(null),[r,a]=_.useState(!0),[i,l]=_.useState(!1),[o,c]=_.useState(null);_.useEffect(()=>{document.title="Activate Your LevelUp Account"},[]),_.useEffect(()=>{let h=!1;return(async()=>{if(!s){c("This link is missing information. Please use the button in your LevelUp email."),a(!1);return}const{data:p,error:f}=await q.functions.invoke("activation-link",{body:{action:"info",ref:s}});h||(f||!(p!=null&&p.ok)?c("We could not recognize this link. Please use the button in your latest LevelUp email."):n({email:p.email,name:p.name,brokerage_name:p.brokerage_name}),a(!1))})(),()=>{h=!0}},[s]);const d=async()=>{if(l(!0),c(null),window.location.origin!==Sle&&window.location.hostname!=="localhost"){window.location.href=`${Sle}${window.location.pathname}${window.location.search}`;return}try{const{data:h,error:m}=await q.functions.invoke("activation-link",{body:{action:"start",ref:s}});if(m||!(h!=null&&h.ok)||!h.token_hash)throw new Error("link_failed");const{error:p}=await q.auth.verifyOtp({token_hash:h.token_hash,type:h.type==="invite"?"invite":"recovery"});if(p)throw p;window.location.replace(`${Sle}/profile?reset=true&activation=1`)}catch{l(!1),c("Something went wrong signing you in. Please try again in a moment.")}},u=((t==null?void 0:t.name)||"").trim().split(/\s+/)[0];return e.jsxs("div",{className:"min-h-screen relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-[#4a6b6d] via-[#3d5a5c] to-[#2a4347]"}),e.jsx("div",{className:"relative z-10 flex flex-col min-h-screen items-center justify-center p-4",children:e.jsxs("div",{className:"w-full max-w-md",children:[e.jsx("div",{className:"flex justify-center mb-8",children:e.jsx("div",{className:"bg-white rounded-xl p-4 shadow-2xl",children:e.jsx("img",{src:GPe,alt:"LevelUp",className:"h-12 w-auto"})})}),e.jsxs(ve,{className:"border-0 shadow-2xl bg-white/95 backdrop-blur-sm",children:[e.jsxs(bt,{className:"text-center",children:[e.jsx(St,{className:"text-2xl font-bold text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:u?`Welcome, ${u}`:"Activate Your Account"}),e.jsx(kn,{className:"text-gray-600 pt-2",children:r?"Loading your account…":o||(t!=null&&t.brokerage_name?`${t.brokerage_name} provides LevelUp for you. Sign in below to set your password.`:"Sign in below to set your password and get started.")})]}),e.jsxs(Me,{className:"space-y-4",children:[t&&e.jsxs("div",{className:"rounded-lg bg-gray-50 border border-gray-200 p-4 text-center",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-gray-500",children:"Your login email"}),e.jsx("p",{className:"text-base font-semibold text-[#2a4347] break-all",children:t.email})]}),t?e.jsx(B,{onClick:d,disabled:i,className:"w-full bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white font-semibold py-6 text-lg shadow-lg hover:shadow-xl",children:i?"Signing you in…":"Sign me in"}):r?null:e.jsx(B,{onClick:()=>window.location.href=`${Sle}/auth`,className:"w-full bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white font-semibold py-6 text-lg",children:"Go to Sign In"}),e.jsx("p",{className:"text-xs text-center text-gray-500 pt-2",children:"No password needed — we'll sign you in and let you choose one."})]})]})]})})]})},UFs=()=>{const s=Fn(),[t]=Yl(),[n,r]=_.useState(t.get("code")||""),[a,i]=_.useState(""),[l,o]=_.useState(""),[c,d]=_.useState(""),[u,h]=_.useState(!1),[m,p]=_.useState(!1),[f,y]=_.useState(!1),[v,g]=_.useState(!1),[b,j]=_.useState(null),[S,C]=_.useState(null),[E,P]=_.useState(null),[M,I]=_.useState(null);_.useEffect(()=>{const G=t.get("code");G&&(r(G),D(G))},[t]);const D=async G=>{y(!0);const{data:$,error:H}=await q.from("invite_codes").select("id, code, max_uses, uses_count, expires_at, is_active, brokerage_id, trial_days").eq("code",G.toUpperCase().trim()).single();if(H||!$){se.error("Invalid invite code"),y(!1);return}if(!$.is_active){se.error("This invite code is no longer active"),y(!1);return}if($.max_uses&&$.uses_count>=$.max_uses){se.error("This invite code has reached its maximum uses"),y(!1);return}if($.expires_at&&new Date($.expires_at){G.preventDefault(),D(n)},V=async G=>{var $;if(G.preventDefault(),!c.trim()){se.error("Please enter your name");return}if(l.length<6){se.error("Password must be at least 6 characters");return}p(!0);try{const H="https://dashboard.relevelup.com/",{data:Y,error:Z}=await q.auth.signUp({email:a.trim(),password:l,options:{emailRedirectTo:H,data:{name:c.trim()}}});if(Z){Z.message.includes("already registered")?se.error("This email is already registered. Please sign in instead."):se.error(Z.message);return}if(Y.user){await q.rpc("add_default_signup_tag",{user_id:Y.user.id});const ne=n.toUpperCase().trim();S?await q.functions.invoke("assign-brokerage",{body:{userId:Y.user.id,brokerageId:S,inviteCode:ne}}):M?await q.functions.invoke("assign-brokerage",{body:{userId:Y.user.id,trialDays:M,inviteCode:ne}}):await q.functions.invoke("assign-brokerage",{body:{userId:Y.user.id,grandfathered:!0,inviteCode:ne}}),b&&await q.from("invite_codes").update({uses_count:(($=(await q.from("invite_codes").select("uses_count").eq("id",b).single()).data)==null?void 0:$.uses_count)+1}).eq("id",b),se.success("Account created! You can now access the dashboard."),s("/dashboard")}}catch(H){console.error("Signup error:",H),se.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(ve,{className:"w-full max-w-md",children:[e.jsxs(bt,{className:"text-center",children:[e.jsx(St,{className:"text-2xl font-bold text-primary",children:E?`Join ${E}`:"Join LevelUp"}),e.jsx(kn,{children:v?E?`Create your account to join ${E}`:"Create your account to get started":"Enter your invite code to continue"})]}),e.jsx(Me,{children:v?e.jsxs("form",{onSubmit:V,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"name",children:"Full Name"}),e.jsx(xe,{id:"name",type:"text",placeholder:"John Doe",value:c,onChange:G=>d(G.target.value),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"email",children:"Email"}),e.jsx(xe,{id:"email",type:"email",placeholder:"you@example.com",value:a,onChange:G=>i(G.target.value),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"password",children:"Password"}),e.jsxs("div",{className:"relative",children:[e.jsx(xe,{id:"password",type:u?"text":"password",placeholder:"••••••••",value:l,onChange:G=>o(G.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(Ax,{className:"h-4 w-4"}):e.jsx(ya,{className:"h-4 w-4"})})]})]}),e.jsx(B,{type:"submit",className:"w-full",disabled:m,children:m?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating Account..."]}):"Create Account"})]}):e.jsxs("form",{onSubmit:O,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"inviteCode",children:"Invite Code"}),e.jsx(xe,{id:"inviteCode",type:"text",placeholder:"Enter your invite code",value:n,onChange:G=>r(G.target.value),required:!0,autoFocus:!0})]}),e.jsx(B,{type:"submit",className:"w-full",disabled:f,children:f?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}),"Verifying..."]}):"Verify Code"})]})})]})})},Jre=()=>{const{user:s,isCoach:t}=hs();return at({queryKey:["my-coach-profile",s==null?void 0:s.id],enabled:!!s&&t,queryFn:async()=>{const{data:n,error:r}=await q.from("coaches").select("*").eq("user_id",s.id).maybeSingle();if(r)throw r;return n}})},qFs=()=>{const{data:s}=Jre();return at({queryKey:["coach-roster",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("coaching_assignments").select("*").eq("coach_id",s.id).order("started_at",{ascending:!1});if(n)throw n;const r=t||[];if(r.length===0)return[];const a=r.map(o=>o.agent_id),{data:i}=await q.from("profiles").select("id, name, email, avatar_url").in("id",a),l=new Map((i||[]).map(o=>[o.id,o]));return r.map(o=>({...o,agent:l.get(o.agent_id)||null}))}})},VJe=()=>{const{user:s}=hs();return at({queryKey:["my-coaching-assignment",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("coaching_assignments").select("*").eq("agent_id",s.id).eq("status","active").order("started_at",{ascending:!1}).limit(1);if(n)throw n;const r=(t||[])[0];if(!r)return null;const{data:a}=await q.from("coaches").select("*").eq("id",r.coach_id).maybeSingle();let i=null;if(a!=null&&a.user_id){const{data:l}=await q.from("profiles").select("id, name, email, avatar_url").eq("id",a.user_id).maybeSingle();i=l}return{...r,coach:a,coachProfile:i}}})},$Fs=s=>at({queryKey:["coaching-assignment",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("coaching_assignments").select("*").eq("id",s).maybeSingle();if(n)throw n;if(!t)return null;const{data:r}=await q.from("profiles").select("id, name, email, avatar_url").eq("id",t.agent_id).maybeSingle();return{...t,agent:r}}}),HJe=s=>at({queryKey:["coaching-sessions",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("coaching_sessions").select("*").eq("assignment_id",s).order("scheduled_at",{ascending:!1});if(n)throw n;return t||[]}}),GJe=s=>at({queryKey:["coaching-action-items",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("coaching_action_items").select("*").eq("assignment_id",s).order("due_date",{ascending:!0,nullsFirst:!1});if(n)throw n;return t||[]}}),VFs=[{key:"onboarding",label:"Onboarding"},{key:"active",label:"Active"},{key:"thriving",label:"Thriving"},{key:"at_risk",label:"At Risk"},{key:"graduated",label:"Graduated"}];function HFs(){const s=Fn(),{data:t,isLoading:n}=Jre(),{data:r=[],isLoading:a}=qFs();if(n)return e.jsx(zs,{title:"Coaching",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!t)return e.jsx(zs,{title:"Coaching",children:e.jsxs("div",{className:"max-w-2xl mx-auto p-8 text-center",children:[e.jsx(mm,{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."})]})});VFs.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(zs,{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(un,{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(VOe,{icon:mm,label:"Active agents",value:i}),e.jsx(VOe,{icon:pc,label:"This month",value:"—"}),e.jsx(VOe,{icon:gu,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(B,{size:"sm",variant:"outline",onClick:()=>s("/coaching/waitlist"),children:"Waitlist"}),e.jsx(B,{size:"sm",variant:"outline",onClick:()=>s("/coaching/settings"),children:"Profile Settings"}),e.jsx(B,{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(ve,{children:e.jsx(Me,{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(ve,{className:"cursor-pointer hover:shadow-lg transition-all hover:-translate-y-0.5",onClick:()=>s(`/coaching/agent/${l.id}`),children:e.jsx(Me,{className:"p-5",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsxs(ja,{className:"h-14 w-14",children:[e.jsx(pi,{src:((o=l.agent)==null?void 0:o.avatar_url)||void 0}),e.jsx(Na,{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(La,{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(Oe,{variant:"secondary",className:"capitalize",children:(l.pipeline_stage||"active").replace("_"," ")}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Started ",Ed(new Date(l.started_at),{addSuffix:!0})]})]})]})]})})},l.id)})})]})]})})}function VOe({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 t9t({assignmentId:s}){const{user:t}=hs(),n=Bt(),[r,a]=_.useState(""),[i,l]=_.useState(!1),o=_.useRef(null),{data:c=[]}=at({queryKey:["coaching-messages",s],enabled:!!s,queryFn:async()=>{const{data:u,error:h}=await q.from("coaching_messages").select("*").eq("assignment_id",s).order("created_at",{ascending:!0});if(h)throw h;return u||[]}});_.useEffect(()=>{if(!s)return;const u=q.channel(`coaching-messages-${s}`).on("postgres_changes",{event:"INSERT",schema:"public",table:"coaching_messages",filter:`assignment_id=eq.${s}`},()=>n.invalidateQueries({queryKey:["coaching-messages",s]})).subscribe();return()=>{q.removeChannel(u)}},[s,n]),_.useEffect(()=>{var u;(u=o.current)==null||u.scrollTo({top:o.current.scrollHeight,behavior:"smooth"})},[c]);const d=async()=>{const u=r.trim();if(!u||!t)return;l(!0);const{error:h}=await q.from("coaching_messages").insert({assignment_id:s,sender_id:t.id,body:u});l(!1),h||a("")};return e.jsxs(ve,{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:At("flex gap-2",h?"justify-end":"justify-start"),children:[!h&&e.jsx(ja,{className:"h-8 w-8 mt-1",children:e.jsx(Na,{className:"text-xs",children:(u.sender_id||"?").charAt(0).toUpperCase()})}),e.jsxs("div",{className:At("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:At("text-[10px] mt-1",h?"text-white/70":"text-muted-foreground"),children:Ed(new Date(u.created_at),{addSuffix:!0})})]})]},u.id)})}),e.jsx(Me,{className:"border-t p-3",children:e.jsxs("div",{className:"flex gap-2 items-end",children:[e.jsx(Ms,{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(B,{onClick:d,disabled:i||!r.trim(),size:"icon",className:"bg-[#406E71] hover:bg-[#2a4c64]",children:e.jsx(Or,{className:"h-4 w-4"})})]})})]})}var WJe="Progress",KJe=100,[GFs,Fbr]=af(WJe),[WFs,KFs]=GFs(WJe),s9t=_.forwardRef((s,t)=>{const{__scopeProgress:n,value:r=null,max:a,getValueLabel:i=YFs,...l}=s;(a||a===0)&&!Oxt(a)&&console.error(ZFs(`${a}`,"Progress"));const o=Oxt(a)?a:KJe;r!==null&&!zxt(r,o)&&console.error(XFs(`${r}`,"Progress"));const c=zxt(r,o)?r:null,d=SAe(c)?i(c,o):void 0;return e.jsx(WFs,{scope:n,value:c,max:o,children:e.jsx(ii.div,{"aria-valuemax":o,"aria-valuemin":0,"aria-valuenow":SAe(c)?c:void 0,"aria-valuetext":d,role:"progressbar","data-state":a9t(c,o),"data-value":c??void 0,"data-max":o,...l,ref:t})})});s9t.displayName=WJe;var n9t="ProgressIndicator",r9t=_.forwardRef((s,t)=>{const{__scopeProgress:n,...r}=s,a=KFs(n9t,n);return e.jsx(ii.div,{"data-state":a9t(a.value,a.max),"data-value":a.value??void 0,"data-max":a.max,...r,ref:t})});r9t.displayName=n9t;function YFs(s,t){return`${Math.round(s/t*100)}%`}function a9t(s,t){return s==null?"indeterminate":s===t?"complete":"loading"}function SAe(s){return typeof s=="number"}function Oxt(s){return SAe(s)&&!isNaN(s)&&s>0}function zxt(s,t){return SAe(s)&&!isNaN(s)&&s<=t&&s>=0}function ZFs(s,t){return`Invalid prop \`max\` of value \`${s}\` supplied to \`${t}\`. Only numbers greater than 0 are valid max values. Defaulting to \`${KJe}\`.`}function XFs(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 ${KJe} if no \`max\` prop is set) - \`null\` or \`undefined\` if the progress is indeterminate. Defaulting to \`null\`.`}var i9t=s9t,QFs=r9t;const Fi=_.forwardRef(({className:s,value:t,...n},r)=>e.jsx(i9t,{ref:r,className:At("relative h-4 w-full overflow-hidden rounded-full bg-secondary",s),...n,children:e.jsx(QFs,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));Fi.displayName=i9t.displayName;function o9t({agentUserId:s}){const t=new Date().getFullYear(),n=`${t}-01-01`,r=`${t}-12-31`,{data:a=[]}=at({queryKey:["coaching-kpi-txns",s,t],enabled:!!s,queryFn:async()=>{const{data:y,error:v}=await q.from("scorecard_transactions").select("id, sale_price, commission_amount, close_date, is_win").eq("owner_user_id",s).gte("close_date",n).lte("close_date",r);if(v)throw v;return y||[]}}),{data:i}=at({queryKey:["coaching-kpi-goal",s,t],enabled:!!s,queryFn:async()=>{const{data:y}=await q.from("scorecard_goals").select("*").eq("owner_user_id",s).eq("year",t).maybeSingle();return y}}),l=a.filter(y=>y.is_win),o=l.length,c=l.reduce((y,v)=>y+(Number(v.sale_price)||0),0),d=l.reduce((y,v)=>y+(Number(v.commission_amount)||0),0),u=i,h=(u==null?void 0:u.transactions_goal)||0,m=(u==null?void 0:u.volume_goal)||0,p=(u==null?void 0:u.gci_goal)||0,f=y=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(y);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(Nl,{className:"h-5 w-5"})," ",t," KPIs"]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:[e.jsx(HOe,{icon:Hh,label:"Transactions",value:o.toString(),goal:h,current:o,suffix:h?`/ ${h}`:""}),e.jsx(HOe,{icon:Nl,label:"Volume",value:f(c),goal:m,current:c,suffix:m?`of ${f(m)}`:""}),e.jsx(HOe,{icon:yd,label:"GCI",value:f(d),goal:p,current:d,suffix:p?`of ${f(p)}`:""})]}),o===0&&e.jsx(ve,{children:e.jsxs(Me,{className:"p-4 text-sm text-muted-foreground text-center",children:["No transactions logged for ",t," yet."]})})]})}function HOe({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(ve,{children:e.jsxs(Me,{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(Fi,{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 l9t({assignmentId:s,canEdit:t}){const n=Bt(),[r,a]=_.useState(!1),[i,l]=_.useState(null),{data:o=[]}=at({queryKey:["coaching-goals",s],enabled:!!s,queryFn:async()=>{const{data:d,error:u}=await q.from("coaching_goals").select("*").eq("assignment_id",s).order("created_at",{ascending:!1});if(u)throw u;return d||[]}}),c=()=>n.invalidateQueries({queryKey:["coaching-goals",s]});return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("h2",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx(ku,{className:"h-5 w-5"})," Goals"]}),t&&e.jsxs(B,{size:"sm",onClick:()=>{l(null),a(!0)},children:[e.jsx(rn,{className:"h-4 w-4 mr-1"})," New Goal"]})]}),o.length===0?e.jsx(ve,{children:e.jsx(Me,{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(ve,{children:e.jsxs(Me,{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(Oe,{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(B,{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(Fi,{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(JFs,{open:r,onOpenChange:a,assignmentId:s,goal:i,onSaved:c})]})}function JFs({open:s,onOpenChange:t,assignmentId:n,goal:r,onSaved:a}){var S,C;const[i,l]=_.useState((r==null?void 0:r.title)||""),[o,c]=_.useState((r==null?void 0:r.description)||""),[d,u]=_.useState((r==null?void 0:r.target_metric)||""),[h,m]=_.useState(((S=r==null?void 0:r.target_value)==null?void 0:S.toString())||""),[p,f]=_.useState(((C=r==null?void 0:r.current_value)==null?void 0:C.toString())||"0"),[y,v]=_.useState((r==null?void 0:r.due_date)||""),[g,b]=_.useState(!1);_.useState(()=>{var E,P;l((r==null?void 0:r.title)||""),c((r==null?void 0:r.description)||""),u((r==null?void 0:r.target_metric)||""),m(((E=r==null?void 0:r.target_value)==null?void 0:E.toString())||""),f(((P=r==null?void 0:r.current_value)==null?void 0:P.toString())||"0"),v((r==null?void 0:r.due_date)||"")});const j=async()=>{if(!i.trim())return;b(!0);const E={assignment_id:n,title:i,description:o||null,target_metric:d||null,target_value:h?Number(h):null,current_value:p?Number(p):0,due_date:y||null},{error:P}=r!=null&&r.id?await q.from("coaching_goals").update(E).eq("id",r.id):await q.from("coaching_goals").insert(E);if(b(!1),P)return se.error(P.message);se.success(r!=null&&r.id?"Goal updated":"Goal created"),a==null||a(),t(!1)};return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{children:[e.jsx(Os,{children:e.jsx(Ds,{children:r!=null&&r.id?"Edit Goal":"New Goal"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(xe,{placeholder:"Title",value:i,onChange:E=>l(E.target.value)}),e.jsx(Ms,{placeholder:"Description (optional)",rows:2,value:o,onChange:E=>c(E.target.value)}),e.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Metric"}),e.jsx(xe,{placeholder:"transactions",value:d,onChange:E=>u(E.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Target"}),e.jsx(xe,{type:"number",value:h,onChange:E=>m(E.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Current"}),e.jsx(xe,{type:"number",value:p,onChange:E=>f(E.target.value)})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Due date"}),e.jsx(xe,{type:"date",value:y,onChange:E=>v(E.target.value)})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(B,{onClick:j,disabled:g,children:r!=null&&r.id?"Save":"Create"})]})]})})}function c9t({assignmentId:s}){const t=Bt(),{user:n}=hs(),r=_.useRef(null),[a,i]=_.useState(!1),{data:l=[]}=at({queryKey:["coaching-files",s],enabled:!!s,queryFn:async()=>{const{data:h,error:m}=await q.from("coaching_shared_files").select("*").eq("assignment_id",s).order("created_at",{ascending:!1});if(m)throw m;return h||[]}}),o=()=>t.invalidateQueries({queryKey:["coaching-files",s]}),c=async h=>{var p;const m=(p=h.target.files)==null?void 0:p[0];if(!(!m||!n)){i(!0);try{const f=`${s}/${Date.now()}-${m.name}`,{error:y}=await q.storage.from("coaching-files").upload(f,m);if(y)throw y;const{error:v}=await q.from("coaching_shared_files").insert({assignment_id:s,uploaded_by:n.id,file_url:f,file_name:m.name,file_size_bytes:m.size,mime_type:m.type});if(v)throw v;se.success("File uploaded"),o()}catch(f){se.error(f.message||"Upload failed")}finally{i(!1),r.current&&(r.current.value="")}}},d=async h=>{const{data:m,error:p}=await q.storage.from("coaching-files").createSignedUrl(h.file_url,60);if(p||!m)return se.error("Could not get download link");window.open(m.signedUrl,"_blank")},u=async h=>{await Xi("Delete this file?")&&(await q.storage.from("coaching-files").remove([h.file_url]),await q.from("coaching_shared_files").delete().eq("id",h.id),o())};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Shared Files"}),e.jsxs(B,{size:"sm",onClick:()=>{var h;return(h=r.current)==null?void 0:h.click()},disabled:a,children:[e.jsx(Oa,{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(ve,{children:e.jsx(Me,{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(ve,{children:e.jsxs(Me,{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(Fr,{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(B,{variant:"ghost",size:"icon",onClick:()=>d(h),children:e.jsx(li,{className:"h-4 w-4"})}),h.uploaded_by===(n==null?void 0:n.id)&&e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>u(h),children:e.jsx(Sn,{className:"h-4 w-4"})})]})},h.id))})]})}function eOs(){var m,p,f,y;const{id:s}=Li(),t=Fn(),n=Bt(),{data:r,isLoading:a}=$Fs(s),{data:i=[]}=HJe(s),{data:l=[]}=GJe(s),[o,c]=_.useState(!1),[d,u]=_.useState(!1);if(a)return e.jsx(zs,{title:"Coaching",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!r)return e.jsx(zs,{title:"Coaching",children:e.jsx("div",{className:"p-8",children:"Assignment not found."})});const h=r;return e.jsxs(zs,{title:"Coaching",children:[e.jsxs("div",{className:"p-4 md:p-8 max-w-6xl mx-auto space-y-6",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>t("/coaching"),children:[e.jsx(ka,{className:"h-4 w-4 mr-2"})," Back to roster"]}),e.jsxs(ve,{className:"overflow-hidden",children:[e.jsx("div",{className:"h-24 bg-gradient-to-br from-[#2a4c64] to-[#406E71]"}),e.jsx(Me,{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(ja,{className:"h-24 w-24 ring-4 ring-background",children:[e.jsx(pi,{src:((m=h.agent)==null?void 0:m.avatar_url)||void 0}),e.jsx(Na,{className:"text-2xl",children:(((p=h.agent)==null?void 0:p.name)||"?").charAt(0)})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h1",{className:"text-2xl font-bold",children:((f=h.agent)==null?void 0:f.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(y=h.agent)==null?void 0:y.email}),e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[e.jsx(Oe,{variant:"secondary",className:"capitalize",children:(h.pipeline_stage||"active").replace("_"," ")}),e.jsx(Oe,{variant:"outline",className:"capitalize",children:h.status})]})]}),e.jsx("div",{className:"flex gap-2",children:e.jsx(sOs,{value:h.pipeline_stage||"active",onChange:async v=>{await q.from("coaching_assignments").update({pipeline_stage:v}).eq("id",h.id),n.invalidateQueries({queryKey:["coaching-assignment",h.id]}),n.invalidateQueries({queryKey:["coach-roster"]})}})})]})})]}),e.jsx(tOs,{assignment:h}),e.jsxs(Yr,{defaultValue:"sessions",children:[e.jsxs(Zr,{className:"w-full flex flex-wrap justify-start h-auto",children:[e.jsxs(Ht,{value:"sessions",children:[e.jsx(ga,{className:"h-4 w-4 mr-2"}),"Sessions"]}),e.jsxs(Ht,{value:"actions",children:[e.jsx(Ny,{className:"h-4 w-4 mr-2"}),"Actions"]}),e.jsxs(Ht,{value:"goals",children:[e.jsx(ku,{className:"h-4 w-4 mr-2"}),"Goals"]}),e.jsxs(Ht,{value:"kpis",children:[e.jsx(Nl,{className:"h-4 w-4 mr-2"}),"KPIs"]}),e.jsxs(Ht,{value:"messages",children:[e.jsx(Hi,{className:"h-4 w-4 mr-2"}),"Messages"]}),e.jsxs(Ht,{value:"files",children:[e.jsx(wy,{className:"h-4 w-4 mr-2"}),"Files"]}),e.jsxs(Ht,{value:"notes",children:[e.jsx(Fr,{className:"h-4 w-4 mr-2"}),"Private Notes"]})]}),e.jsxs(Gt,{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(B,{size:"sm",onClick:()=>c(!0),children:[e.jsx(rn,{className:"h-4 w-4 mr-1"})," New Session"]})]}),i.length===0?e.jsx(ve,{children:e.jsx(Me,{className:"p-6 text-muted-foreground text-center",children:"No sessions yet."})}):e.jsx("div",{className:"space-y-3",children:i.map(v=>e.jsx(ve,{children:e.jsx(Me,{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(v.scheduled_at),"PPp")}),e.jsx(Oe,{variant:"outline",className:"capitalize",children:v.status}),v.template&&e.jsx(Oe,{variant:"secondary",children:v.template}),v.zoom_join_url&&e.jsx("a",{href:v.zoom_join_url,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-primary underline",children:"Join Zoom"})]}),v.agenda&&e.jsxs("p",{className:"text-sm mb-1",children:[e.jsx("span",{className:"text-muted-foreground",children:"Agent's agenda:"})," ",v.agenda]}),v.summary&&e.jsx("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap",children:v.summary}),v.private_notes&&e.jsxs("div",{className:"mt-2 p-2 rounded bg-muted/50 text-xs",children:[e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground mb-1",children:[e.jsx(ec,{className:"h-3 w-3"})," Private"]}),e.jsx("p",{className:"whitespace-pre-wrap",children:v.private_notes})]})]})})})},v.id))})]}),e.jsxs(Gt,{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(B,{size:"sm",onClick:()=>u(!0),children:[e.jsx(rn,{className:"h-4 w-4 mr-1"})," Add"]})]}),l.length===0?e.jsx(ve,{children:e.jsx(Me,{className:"p-6 text-muted-foreground text-center",children:"No action items yet."})}):e.jsx("div",{className:"space-y-2",children:l.map(v=>e.jsx(ve,{children:e.jsxs(Me,{className:"p-3 flex items-center gap-3",children:[e.jsx($a,{checked:v.status==="done",onCheckedChange:async g=>{await q.from("coaching_action_items").update({status:g?"done":"open",completed_at:g?new Date().toISOString():null}).eq("id",v.id),n.invalidateQueries({queryKey:["coaching-action-items",h.id]})}}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:v.status==="done"?"line-through text-muted-foreground":"font-medium",children:v.title}),v.description&&e.jsx("div",{className:"text-xs text-muted-foreground",children:v.description})]}),v.due_date&&e.jsx(Oe,{variant:"outline",children:Hs(new Date(v.due_date),"MMM d")}),e.jsx(Oe,{variant:"secondary",className:"capitalize",children:v.priority})]})},v.id))})]}),e.jsx(Gt,{value:"goals",children:e.jsx(l9t,{assignmentId:h.id,canEdit:!0})}),e.jsx(Gt,{value:"kpis",children:h.agent_id&&e.jsx(o9t,{agentUserId:h.agent_id})}),e.jsx(Gt,{value:"messages",children:e.jsx(t9t,{assignmentId:h.id})}),e.jsx(Gt,{value:"files",children:e.jsx(c9t,{assignmentId:h.id})}),e.jsx(Gt,{value:"notes",className:"space-y-4",children:e.jsx(ve,{children:e.jsx(Me,{className:"p-6 text-muted-foreground",children:"Private notes per session live under the Sessions tab. General-relationship notes coming soon."})})})]})]}),e.jsx(nOs,{open:o,onOpenChange:c,assignmentId:h.id,onSaved:()=>n.invalidateQueries({queryKey:["coaching-sessions",h.id]})}),e.jsx(rOs,{open:d,onOpenChange:u,assignmentId:h.id,onSaved:()=>n.invalidateQueries({queryKey:["coaching-action-items",h.id]})})]})}function tOs({assignment:s}){const t=Bt(),[n,r]=_.useState(s.sessions_per_month==null?"":String(s.sessions_per_month)),[a,i]=_.useState(!1),l=async()=>{i(!0);const o=n.trim()===""?null:Math.max(1,parseInt(n,10)||1),{error:c}=await q.from("coaching_assignments").update({sessions_per_month:o}).eq("id",s.id);if(i(!1),c)return se.error(c.message);se.success("Session allowance updated"),t.invalidateQueries({queryKey:["coaching-assignment",s.id]})};return e.jsx(ve,{children:e.jsxs(Me,{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(ga,{className:"h-4 w-4"})," Monthly session allowance"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Leave blank to use your coach default. This agent books these on their My Coach page."})]}),e.jsx(xe,{type:"number",min:1,max:31,placeholder:"Default",value:n,onChange:o=>r(o.target.value),className:"w-28"}),e.jsxs(B,{size:"sm",variant:"outline",onClick:l,disabled:a,children:[e.jsx(Ho,{className:"h-4 w-4 mr-1"})," Save"]})]})})}function sOs({value:s,onChange:t}){return e.jsxs(is,{value:s,onValueChange:t,children:[e.jsx(rs,{className:"w-40",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"onboarding",children:"Onboarding"}),e.jsx(He,{value:"active",children:"Active"}),e.jsx(He,{value:"thriving",children:"Thriving"}),e.jsx(He,{value:"at_risk",children:"At Risk"}),e.jsx(He,{value:"graduated",children:"Graduated"})]})]})}function nOs({open:s,onOpenChange:t,assignmentId:n,onSaved:r}){const[a,i]=_.useState(()=>new Date().toISOString().slice(0,16)),[l,o]=_.useState(60),[c,d]=_.useState("weekly_1on1"),[u,h]=_.useState(""),[m,p]=_.useState(""),[f,y]=_.useState(!1),[v,g]=_.useState(!0),[b,j]=_.useState(null),[S,C]=_.useState(!1),E=async()=>{C(!0);const{data:M,error:I}=await q.functions.invoke("coaching-prep-brief",{body:{assignmentId:n}});if(C(!1),I||M!=null&&M.error)return se.error((M==null?void 0:M.error)||(I==null?void 0:I.message)||"Failed to generate brief");j(M.brief||"No brief returned.")},P=async()=>{y(!0);const{data:M,error:I}=await q.from("coaching_sessions").insert({assignment_id:n,scheduled_at:new Date(a).toISOString(),duration_minutes:l,template:c,summary:u,private_notes:m,status:"completed"}).select("id").maybeSingle();if(I)return y(!1),se.error(I.message);if(se.success("Session saved"),v&&u.trim()&&(M!=null&&M.id)){const{error:D}=await q.functions.invoke("coaching-send-recap",{body:{sessionId:M.id}});D?se.error("Saved, but recap email failed: "+D.message):se.success("Recap emailed to agent")}y(!1),r==null||r(),t(!1),h(""),p(""),j(null)};return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(Ds,{children:"New Session"}),e.jsxs(B,{size:"sm",variant:"outline",onClick:E,disabled:S,children:[S?e.jsx(Ct,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(un,{className:"h-4 w-4 mr-1"}),"Pre-session brief"]})]})}),e.jsxs("div",{className:"space-y-3",children:[b&&e.jsxs("div",{className:"rounded-lg border bg-gradient-to-br from-[#406E71]/5 to-[#2a4c64]/5 p-3 text-sm whitespace-pre-wrap max-h-60 overflow-y-auto",children:[e.jsxs("div",{className:"flex items-center gap-1 text-xs font-medium text-[#406E71] mb-2",children:[e.jsx(un,{className:"h-3 w-3"})," AI Brief"]}),b]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"When"}),e.jsx(xe,{type:"datetime-local",value:a,onChange:M=>i(M.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Duration (min)"}),e.jsx(xe,{type:"number",value:l,onChange:M=>o(Number(M.target.value))})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Template"}),e.jsxs(is,{value:c,onValueChange:d,children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"weekly_1on1",children:"Weekly 1:1"}),e.jsx(He,{value:"grow",children:"GROW Model"}),e.jsx(He,{value:"goal_review",children:"Goal Review"}),e.jsx(He,{value:"breakthrough",children:"Breakthrough Session"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Summary (agent sees this)"}),e.jsx(Ms,{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(ec,{className:"h-3 w-3"})," Private notes (only you)"]}),e.jsx(Ms,{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($a,{checked:v,onCheckedChange:M=>g(!!M)}),e.jsx(Or,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Email recap to agent on save"]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{onClick:P,disabled:f,children:[e.jsx(Ho,{className:"h-4 w-4 mr-1"})," Save Session"]})]})]})})}function rOs({open:s,onOpenChange:t,assignmentId:n,onSaved:r}){const[a,i]=_.useState(""),[l,o]=_.useState(""),[c,d]=_.useState(""),[u,h]=_.useState("medium"),[m,p]=_.useState(!1),f=async()=>{if(!a.trim())return;p(!0);const{error:y}=await q.from("coaching_action_items").insert({assignment_id:n,title:a,description:l||null,due_date:c||null,priority:u});if(p(!1),y)return se.error(y.message);se.success("Action item added"),r==null||r(),t(!1),i(""),o(""),d("")};return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{children:[e.jsx(Os,{children:e.jsx(Ds,{children:"New Action Item"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(xe,{placeholder:"Title",value:a,onChange:y=>i(y.target.value)}),e.jsx(Ms,{rows:3,placeholder:"Description (optional)",value:l,onChange:y=>o(y.target.value)}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Due date"}),e.jsx(xe,{type:"date",value:c,onChange:y=>d(y.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Priority"}),e.jsxs(is,{value:u,onValueChange:h,children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"low",children:"Low"}),e.jsx(He,{value:"medium",children:"Medium"}),e.jsx(He,{value:"high",children:"High"})]})]})]})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(B,{onClick:f,disabled:m,children:"Add"})]})]})})}function bVe({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(Da,{style:{width:t,height:t},className:r<=s?"fill-yellow-400 text-yellow-400":"text-muted-foreground/40"})},r))})}function aOs({coachId:s}){const[t,n]=_.useState([]),[r,a]=_.useState(!0);_.useEffect(()=>{(async()=>{const{data:l}=await q.from("coaching_reviews").select("*").eq("coach_id",s).eq("is_published",!0).order("created_at",{ascending:!1}),o=l||[];if(o.length){const c=o.map(h=>h.agent_id),{data:d}=await q.from("profiles").select("id, name, avatar_url").in("id",c),u=new Map((d||[]).map(h=>[h.id,h]));o.forEach(h=>h.profile=u.get(h.agent_id))}n(o),a(!1)})()},[s]);const i=t.length?t.reduce((l,o)=>l+o.rating,0)/t.length:0;return r||!t.length?null:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"Reviews"}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(bVe,{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(ve,{children:e.jsx(Me,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs(ja,{className:"h-9 w-9",children:[e.jsx(pi,{src:((o=l.profile)==null?void 0:o.avatar_url)||void 0}),e.jsx(Na,{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(bVe,{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 iOs({coachId:s,assignmentId:t}){const{user:n}=hs(),[r,a]=_.useState(null),[i,l]=_.useState(0),[o,c]=_.useState(""),[d,u]=_.useState(""),[h,m]=_.useState(!1);_.useEffect(()=>{n&&(async()=>{const{data:f}=await q.from("coaching_reviews").select("*").eq("coach_id",s).eq("agent_id",n.id).maybeSingle();f&&(a(f),l(f.rating),c(f.title||""),u(f.body||""))})()},[n,s]);const p=async()=>{if(!n)return;if(!i)return se.error("Pick a rating");m(!0);const f={coach_id:s,agent_id:n.id,assignment_id:t||null,rating:i,title:o||null,body:d||null},{error:y}=r?await q.from("coaching_reviews").update(f).eq("id",r.id):await q.from("coaching_reviews").insert(f);if(m(!1),y)return se.error(y.message);se.success("Thanks for your review!"),a({...f,id:r==null?void 0:r.id})};return e.jsx(ve,{children:e.jsxs(Me,{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(bVe,{value:i,size:28,onChange:l}),e.jsx(xe,{placeholder:"Title (optional)",value:o,onChange:f=>c(f.target.value)}),e.jsx(Ms,{rows:4,placeholder:"What was your experience like?",value:d,onChange:f=>u(f.target.value)}),e.jsx(B,{onClick:p,disabled:h,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:h?"Saving…":r?"Update review":"Submit review"})]})})}const Cle=async s=>{var r,a;const{data:t,error:n}=await q.functions.invoke("coaching-booking",{body:s});if(n){const i=(r=n==null?void 0:n.context)!=null&&r.text?await n.context.text():n.message;let l=i;try{l=((a=JSON.parse(i))==null?void 0:a.error)||i}catch{}throw new Error(l)}if(t!=null&&t.error)throw new Error(t.error);return t},GOe=s=>Hs(s,"yyyy-MM-dd"),Bxt=s=>{const[t,n]=s.split(":").map(Number),r=t>=12?"PM":"AM";return`${t%12||12}:${String(n).padStart(2,"0")} ${r}`};function oOs({assignmentId:s,upcoming:t=[]}){const n=Bt(),[r,a]=_.useState(null),[i,l]=_.useState(null),[o,c]=_.useState(null),[d,u]=_.useState(""),[h,m]=_.useState(!1),{data:p,isLoading:f}=at({queryKey:["coaching-booking-context",s],queryFn:()=>Cle({action:"context"})});_.useEffect(()=>{var ne;!r&&((ne=p==null?void 0:p.booking_types)!=null&&ne.length)&&a(p.booking_types[0].id)},[p,r]);const y=_.useMemo(()=>new Date,[]),[v,g]=_.useState(()=>rm(new Date)),b=(p==null?void 0:p.max_advance_days)||30,j=_.useMemo(()=>zh(If(y),b-1),[y,b]),S=_.useMemo(()=>{const ne=rm(v);return ne{const ne=y_(v);return ne>j?j:ne},[v,j]),E=Math.max(0,pv(C,S)+1),{data:P={},isFetching:M}=at({queryKey:["coaching-availability",r,GOe(S),E],enabled:!!r&&E>0,queryFn:async()=>(await Cle({action:"availability",booking_type_id:r,start:GOe(S),days:E})).availability||{}}),I=_.useMemo(()=>{const ne=rm(v),ce=y_(v).getDate(),ie=ne.getDay(),te=Array.from({length:ie},()=>null);for(let ae=0;aeObject.entries(P).filter(([,ne])=>ne.length>0),[P]),O=i?P[i]||[]:[],V=M,G=_.useMemo(()=>{const ne=[{label:"Morning",items:[]},{label:"Afternoon",items:[]},{label:"Evening",items:[]}];for(const ce of O){const ie=Number(ce.split(":")[0]);ie<12?ne[0].items.push(ce):ie<17?ne[1].items.push(ce):ne[2].items.push(ce)}return ne.filter(ce=>ce.items.length>0)},[O]),$=(p==null?void 0:p.booking_types.find(ne=>ne.id===r))||null,H=((p==null?void 0:p.sessions_remaining)??0)<=0,Y=async()=>{if(!(!r||!i||!o)){m(!0);try{await Cle({action:"book",booking_type_id:r,date:i,time:o,agenda:d||null}),se.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(ne){se.error(ne.message||"Could not book that session")}finally{m(!1)}}},Z=async ne=>{if(await Xi("Cancel this coaching session?"))try{await Cle({action:"cancel",session_id:ne}),se.success("Session cancelled"),n.invalidateQueries({queryKey:["coaching-booking-context",s]}),n.invalidateQueries({queryKey:["coaching-sessions",s]})}catch(ce){se.error(ce.message||"Could not cancel")}};return f?e.jsx(ve,{children:e.jsxs(Me,{className:"p-8 flex items-center justify-center text-muted-foreground gap-2",children:[e.jsx(Ct,{className:"h-4 w-4 animate-spin"})," Loading your coach's calendar…"]})}):p!=null&&p.scheduler_ready?e.jsxs("div",{className:"space-y-4",children:[e.jsx(ve,{children:e.jsxs(Me,{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(pc,{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."})]})]}),H&&e.jsx(Oe,{variant:"secondary",children:"All booked up"})]})}),t.length>0&&e.jsx(ve,{children:e.jsxs(Me,{className:"p-4 space-y-3",children:[e.jsx("h3",{className:"font-semibold",children:"Upcoming sessions"}),t.map(ne=>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(ne.scheduled_at),"EEE, MMM d · p")}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[ne.duration_minutes||30," minutes"]})]}),ne.zoom_join_url&&e.jsx(B,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:ne.zoom_join_url,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Kr,{className:"h-4 w-4 mr-1"})," Join"]})}),e.jsxs(B,{size:"sm",variant:"ghost",onClick:()=>Z(ne.id),children:[e.jsx(Rd,{className:"h-4 w-4 mr-1"})," Cancel"]})]},ne.id))]})}),e.jsx(ve,{children:e.jsxs(Me,{className:"p-4 md:p-6 space-y-5",children:[e.jsxs("div",{children:[e.jsx(J,{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(ne=>e.jsxs("button",{onClick:()=>{a(ne.id),c(null)},className:`text-left p-3 rounded-lg border transition-colors ${r===ne.id?"border-primary bg-primary/5":"hover:bg-muted/50"}`,children:[e.jsx("div",{className:"font-medium",children:ne.name}),e.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-1 mt-1",children:[e.jsx(Gr,{className:"h-3 w-3"})," ",ne.duration_minutes," min"]}),ne.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:ne.description})]},ne.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(J,{className:"block",children:"Pick a day"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(B,{size:"icon",variant:"ghost",className:"h-7 w-7",disabled:Vre(v,y),onClick:()=>g(Cy(v,-1)),"aria-label":"Previous month",children:e.jsx($c,{className:"h-4 w-4"})}),e.jsx("span",{className:"text-sm font-medium w-28 text-center",children:Hs(v,"MMMM yyyy")}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-7 w-7",disabled:rm(Cy(v,1))>j,onClick:()=>g(Cy(v,1)),"aria-label":"Next month",children:e.jsx(xi,{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((ne,ce)=>e.jsx("div",{className:"text-[11px] text-muted-foreground text-center py-1",children:ne},ce))}),e.jsx("div",{className:"grid grid-cols-7 gap-1",children:I.map((ne,ce)=>{if(!ne)return e.jsx("div",{},`b${ce}`);const ie=GOe(ne),te=(P[ie]||[]).length,le=ne>=If(y)&&ne<=j&&te>0,be=i===ie;return e.jsxs("button",{disabled:!le,onClick:()=>{l(ie),c(null)},className:`aspect-square rounded-lg border text-sm flex flex-col items-center justify-center gap-1 transition-colors ${be?"border-primary bg-primary text-primary-foreground":le?"border-primary/30 bg-primary/5 hover:bg-primary/10 font-medium":"border-transparent text-muted-foreground/50 cursor-not-allowed"}`,title:le?`${te} opening${te===1?"":"s"}`:"No openings",children:[e.jsx("span",{className:"leading-none",children:Hs(ne,"d")}),e.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${be?"bg-primary-foreground":le?"bg-primary":"bg-transparent"}`})]},ie)})}),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(Ct,{className:"h-3 w-3 animate-spin"})," Loading your coach's openings…"]}):e.jsxs(e.Fragment,{children:[e.jsx(un,{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(J,{className:"mb-2 block",children:i?`Available times · ${Hs(new Date(`${i}T12:00:00`),"EEE, MMM d")}`:"Available times"}),i?V?e.jsxs("div",{className:"text-sm text-muted-foreground flex items-center gap-2",children:[e.jsx(Ct,{className:"h-4 w-4 animate-spin"})," Checking availability…"]}):O.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No openings on this day — try another date."}):e.jsx("div",{className:"space-y-3 max-h-[320px] overflow-y-auto pr-1",children:G.map(ne=>e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wide text-muted-foreground mb-1",children:ne.label}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:ne.items.map(ce=>e.jsx("button",{onClick:()=>c(ce),className:`py-2 rounded-lg border text-sm transition-colors ${o===ce?"border-primary bg-primary/10 font-medium":"hover:bg-muted/50"}`,children:Bxt(ce)},ce))})]},ne.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(([ne,ce])=>e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>{l(ne),c(null)},children:[Hs(new Date(`${ne}T12:00:00`),"EEE MMM d")," · ",ce.length," open"]},ne))})]})]}),o&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(J,{htmlFor:"agenda",children:"What do you want to work on? (optional)"}),e.jsx(Ms,{id:"agenda",rows:3,value:d,onChange:ne=>u(ne.target.value),placeholder:"Share context so your coach can prep."})]}),e.jsxs(B,{onClick:Y,disabled:h||H,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[h?e.jsx(Ct,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Er,{className:"h-4 w-4 mr-1"}),"Book ",$==null?void 0:$.name," — ",i&&Hs(new Date(`${i}T12:00:00`),"MMM d")," at ",Bxt(o)]}),H&&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(ve,{children:e.jsx(Me,{className:"p-8 text-center text-muted-foreground",children:"Your coach hasn't opened their coaching calendar yet. Check back soon."})})}function lOs(){const{user:s}=hs(),{isMember:t,pkg:n}=IS(),{data:r}=at({queryKey:["coaching-prep-member",s==null?void 0:s.id,n==null?void 0:n.id],enabled:!!(s!=null&&s.id)&&!!(n!=null&&n.id),queryFn:async()=>{const[{data:l},{data:o},{data:c}]=await Promise.all([q.from("coaching_onboarding_forms").select("submitted_at").eq("user_id",s.id).maybeSingle(),q.from("coaching_prep_checklist_items").select("*").eq("package_id",n.id).eq("is_active",!0).order("sort_order"),q.from("coaching_prep_checklist_state").select("item_id").eq("user_id",s.id)]),d=new Set((c||[]).map(u=>u.item_id));return{submitted:!!(l!=null&&l.submitted_at),items:(o||[]).map(u=>({...u,done:d.has(u.id)}))}}});if(!t||!(n!=null&&n.includes_coaching))return null;const a=(r==null?void 0:r.items)||[],i=a.filter(l=>l.done).length;return e.jsxs(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between gap-2 space-y-0",children:[e.jsxs(St,{className:"text-base flex items-center gap-2",children:[e.jsx(qf,{className:"h-4 w-4 text-primary"})," Coaching prep"]}),a.length>0&&e.jsxs(Oe,{variant:"secondary",children:[i,"/",a.length," done"]})]}),e.jsxs(Me,{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(B,{asChild:!0,size:"sm",variant:r!=null&&r.submitted?"outline":"default",children:e.jsx(ir,{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(Er,{className:"h-4 w-4 mt-0.5 text-primary"}):e.jsx(Uf,{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 cOs(){var m,p,f,y,v,g;const{user:s}=hs(),{data:t,isLoading:n,refetch:r}=VJe(),a=Bt(),i=t==null?void 0:t.id,{data:l=[]}=HJe(i),{data:o=[]}=GJe(i);if(_.useEffect(()=>{new URLSearchParams(window.location.search).get("subscribed")==="1"&&q.functions.invoke("coaching-verify-checkout").then(()=>{r(),a.invalidateQueries({queryKey:["my-coaching-assignment"]})})},[r,a]),n)return e.jsx(zs,{title:"My Coach",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!t)return e.jsx(zs,{title:"My Coach",children:e.jsxs("div",{className:"max-w-2xl mx-auto p-8 text-center",children:[e.jsx(mm,{className:"h-12 w-12 mx-auto mb-4 text-muted-foreground"}),e.jsx("h2",{className:"text-2xl font-semibold mb-2",children:"You're not in a coaching program yet"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Browse LevelUp Certified Coaches to find a fit (coming soon)."})]})});const c=t,d=o.filter(b=>b.status!=="done"),u=o.length-d.length,h=l.filter(b=>b.status!=="cancelled"&&new Date(b.scheduled_at).getTime()>Date.now());return e.jsx(zs,{title:"My Coach",children:e.jsxs("div",{className:"p-4 md:p-8 max-w-5xl mx-auto space-y-6",children:[e.jsx(ve,{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(ja,{className:"h-24 w-24 ring-4 ring-white/20",children:[e.jsx(pi,{src:((m=c.coachProfile)==null?void 0:m.avatar_url)||void 0}),e.jsx(Na,{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(un,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm uppercase tracking-wider",children:"Your Coach"})]}),e.jsx("h1",{className:"text-3xl font-bold",children:((f=c.coachProfile)==null?void 0:f.name)||"Your Coach"}),((y=c.coach)==null?void 0:y.headline)&&e.jsx("p",{className:"text-white/80 mt-1",children:c.coach.headline}),e.jsxs("div",{className:"flex gap-2 mt-3",children:[((v=c.coach)==null?void 0:v.is_certified)&&e.jsx(Oe,{className:"bg-yellow-400/20 text-yellow-100 border-yellow-300/30",children:"LevelUp Certified"}),e.jsx(Oe,{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(WOe,{icon:Ny,label:"Open action items",value:d.length}),e.jsx(WOe,{icon:ku,label:"Completed",value:u}),e.jsx(WOe,{icon:ga,label:"Sessions",value:l.length})]}),e.jsx(lOs,{}),((g=c.coach)==null?void 0:g.id)&&e.jsx(iOs,{coachId:c.coach.id,assignmentId:i}),e.jsxs(Yr,{defaultValue:"book",children:[e.jsxs(Zr,{className:"flex flex-wrap h-auto w-full justify-start",children:[e.jsxs(Ht,{value:"book",children:[e.jsx(gy,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Book"})]}),e.jsxs(Ht,{value:"actions",children:[e.jsx(Ny,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Actions"})]}),e.jsxs(Ht,{value:"sessions",children:[e.jsx(ga,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Recaps"})]}),e.jsxs(Ht,{value:"goals",children:[e.jsx(ku,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Goals"})]}),e.jsxs(Ht,{value:"kpis",children:[e.jsx(Nl,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"KPIs"})]}),e.jsxs(Ht,{value:"messages",children:[e.jsx(Hi,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Messages"})]}),e.jsxs(Ht,{value:"files",children:[e.jsx(wy,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Files"})]})]}),e.jsx(Gt,{value:"book",children:e.jsx(oOs,{assignmentId:i,upcoming:h})}),e.jsx(Gt,{value:"actions",className:"space-y-2",children:o.length===0?e.jsx(ve,{children:e.jsx(Me,{className:"p-6 text-center text-muted-foreground",children:"Your coach hasn't assigned any action items yet."})}):o.map(b=>e.jsx(ve,{children:e.jsxs(Me,{className:"p-3 flex items-center gap-3",children:[e.jsx($a,{checked:b.status==="done",onCheckedChange:async j=>{await q.from("coaching_action_items").update({status:j?"done":"open",completed_at:j?new Date().toISOString():null}).eq("id",b.id),a.invalidateQueries({queryKey:["coaching-action-items",i]})}}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:b.status==="done"?"line-through text-muted-foreground":"font-medium",children:b.title}),b.description&&e.jsx("div",{className:"text-xs text-muted-foreground",children:b.description})]}),b.due_date&&e.jsx(Oe,{variant:"outline",children:Hs(new Date(b.due_date),"MMM d")}),e.jsx(Oe,{variant:"secondary",className:"capitalize",children:b.priority})]})},b.id))}),e.jsx(Gt,{value:"sessions",className:"space-y-3",children:l.length===0?e.jsx(ve,{children:e.jsx(Me,{className:"p-6 text-center text-muted-foreground",children:"No sessions logged yet."})}):l.map(b=>e.jsx(ve,{children:e.jsxs(Me,{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(b.scheduled_at),"PPp")}),e.jsx(Oe,{variant:"outline",className:"capitalize",children:b.status})]}),b.summary?e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:b.summary}):e.jsx("p",{className:"text-sm text-muted-foreground italic",children:"Recap coming soon."})]})},b.id))}),e.jsx(Gt,{value:"goals",children:e.jsx(l9t,{assignmentId:i,canEdit:!1})}),e.jsx(Gt,{value:"kpis",children:s&&e.jsx(o9t,{agentUserId:s.id})}),e.jsx(Gt,{value:"messages",children:e.jsx(t9t,{assignmentId:i})}),e.jsx(Gt,{value:"files",children:e.jsx(c9t,{assignmentId:i})})]})]})})}function WOe({icon:s,label:t,value:n}){return e.jsx(ve,{children:e.jsxs(Me,{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 Uxt="coaching_access",KOe=s=>((s==null?void 0:s.name)||(s==null?void 0:s.email)||"?").trim().slice(0,2).toUpperCase(),YOe=s=>!!s.expires_at&&new Date(s.expires_at).getTime()<=Date.now();function dOs(){const s=Bt(),[t,n]=_.useState(""),[r,a]=_.useState([]),[i,l]=_.useState(!1),[o,c]=_.useState(null),[d,u]=_.useState(""),{data:h=[],isLoading:m}=at({queryKey:["coaching-entitlements"],queryFn:async()=>{const{data:D,error:O}=await q.from("feature_entitlements").select("id, user_id, enabled, expires_at, tier, notes, enabled_at").eq("feature_key",Uxt).order("enabled_at",{ascending:!1});if(O)throw O;return D||[]}}),{data:p=[]}=at({queryKey:["coaching-assigned-agents"],queryFn:async()=>{const{data:D,error:O}=await q.from("coaching_assignments").select("agent_id, coach_id, status").eq("status","active");if(O)throw O;return D||[]}}),f=_.useMemo(()=>{const D=new Set;return h.forEach(O=>D.add(O.user_id)),p.forEach(O=>D.add(O.agent_id)),Array.from(D)},[h,p]),{data:y={}}=at({queryKey:["coaching-access-profiles",f.join(",")],enabled:f.length>0,queryFn:async()=>{const D={};for(let O=0;O{D[G.id]=G})}return D}});_.useEffect(()=>{const D=t.trim();if(D.length<2){a([]),l(!1);return}l(!0);const O=setTimeout(async()=>{const{data:V}=await q.from("profiles").select("id, name, email, avatar_url").or(`email.ilike.%${D}%,name.ilike.%${D}%`).limit(12);a(V||[]),l(!1)},250);return()=>clearTimeout(O)},[t]);const v=_.useMemo(()=>{const D=new Map;return h.forEach(O=>D.set(O.user_id,O)),D},[h]),g=_.useMemo(()=>new Set(p.map(D=>D.agent_id)),[p]),b=()=>{s.invalidateQueries({queryKey:["coaching-entitlements"]}),s.invalidateQueries({queryKey:["coaching-access-profiles"]}),s.invalidateQueries({queryKey:["coaching-access"]})},j=async(D,O={})=>{var $;const{data:V}=await q.auth.getUser(),{error:G}=await q.from("feature_entitlements").upsert({user_id:D,feature_key:Uxt,enabled:O.enabled??!0,expires_at:O.expires_at??null,notes:O.notes??null,tier:O.tier??null,enabled_by:(($=V==null?void 0:V.user)==null?void 0:$.id)??null,enabled_at:new Date().toISOString(),updated_at:new Date().toISOString()},{onConflict:"user_id,feature_key"});return G?(se.error(G.message),!1):(b(),!0)},S=async D=>{await j(D.id)&&se.success(`Coaching access granted to ${D.name||D.email}`),n(""),a([])},C=async(D,O)=>{const{error:V}=await q.from("feature_entitlements").update({enabled:O,updated_at:new Date().toISOString()}).eq("id",D.id);if(V)return se.error(V.message);se.success(O?"Access enabled":"Access paused"),b()},E=async D=>{if(!await Xi({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:V}=await q.from("feature_entitlements").delete().eq("id",D.entitlement.id);if(V)return se.error(V.message);se.success("Coaching access revoked"),b()},P=_.useMemo(()=>{const D=d.trim().toLowerCase(),O=h.map(V=>({entitlement:V,profile:y[V.user_id]}));return D?O.filter(({profile:V})=>`${(V==null?void 0:V.name)||""} ${(V==null?void 0:V.email)||""}`.toLowerCase().includes(D)):O},[h,y,d]),M=h.filter(D=>D.enabled&&!YOe(D)).length,I=p.filter(D=>!v.has(D.agent_id));return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3",children:[e.jsx(ZOe,{icon:Dm,label:"Granted access",value:M,hint:"Standalone entitlements"}),e.jsx(ZOe,{icon:In,label:"Coached members",value:g.size,hint:"Active coach assignments"}),e.jsx(ZOe,{icon:un,label:"Total with access",value:new Set([...h.filter(D=>D.enabled&&!YOe(D)).map(D=>D.user_id),...g]).size,hint:"Unique members"})]}),e.jsx(ve,{children:e.jsxs(Me,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(VA,{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(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{className:"pl-9",placeholder:"Search members by name or email…",value:t,onChange:D=>n(D.target.value)})]}),t.trim().length>=2&&e.jsx("div",{className:"border rounded-lg divide-y max-h-80 overflow-auto",children:i?e.jsxs("div",{className:"p-3 text-sm text-muted-foreground flex items-center gap-2",children:[e.jsx(Ct,{className:"h-4 w-4 animate-spin"})," Searching…"]}):r.length===0?e.jsx("div",{className:"p-3 text-sm text-muted-foreground",children:"No members found"}):r.map(D=>{const O=v.get(D.id),V=g.has(D.id);return e.jsxs("div",{className:"flex items-center gap-3 p-2.5 hover:bg-muted/40",children:[e.jsxs(ja,{className:"h-8 w-8",children:[e.jsx(pi,{src:D.avatar_url||void 0}),e.jsx(Na,{className:"text-xs",children:KOe(D)})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-medium truncate",children:D.name||D.email}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:D.email})]}),O?e.jsx(Oe,{variant:"outline",className:"shrink-0",children:"Already granted"}):V?e.jsxs(Oe,{variant:"outline",className:"shrink-0",children:[e.jsx(vd,{className:"h-3 w-3 mr-1"}),"Has coach"]}):e.jsxs("div",{className:"flex gap-1.5 shrink-0",children:[e.jsx(B,{size:"sm",variant:"outline",onClick:()=>c({profile:D}),children:"Options"}),e.jsxs(B,{size:"sm",className:"bg-[#406E71] hover:bg-[#2a4c64]",onClick:()=>S(D),children:[e.jsx(Pl,{className:"h-4 w-4 mr-1"})," Grant"]})]})]},D.id)})})]})}),e.jsx(ve,{children:e.jsxs(Me,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(Dm,{className:"h-5 w-5 text-primary"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Members with granted access"}),e.jsx(Oe,{variant:"outline",children:h.length}),e.jsx("div",{className:"ml-auto w-full sm:w-64",children:e.jsx(xe,{placeholder:"Filter list…",value:d,onChange:D=>u(D.target.value)})})]}),m?e.jsxs("div",{className:"p-6 text-sm text-muted-foreground flex items-center gap-2",children:[e.jsx(Ct,{className:"h-4 w-4 animate-spin"})," Loading…"]}):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:O})=>{const V=YOe(D);return e.jsxs("div",{className:"flex items-center gap-3 p-3 flex-wrap",children:[e.jsxs(ja,{className:"h-9 w-9",children:[e.jsx(pi,{src:(O==null?void 0:O.avatar_url)||void 0}),e.jsx(Na,{className:"text-xs",children:KOe(O)})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-medium truncate",children:(O==null?void 0:O.name)||(O==null?void 0:O.email)||D.user_id}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:O==null?void 0:O.email}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:[V?e.jsx(Oe,{className:"bg-rose-500/15 text-rose-700 border-rose-300/40",children:"Expired"}):D.enabled?e.jsx(Oe,{className:"bg-emerald-500/15 text-emerald-700 border-emerald-300/40",children:"Active"}):e.jsx(Oe,{variant:"outline",children:"Paused"}),g.has(D.user_id)&&e.jsxs(Oe,{variant:"outline",children:[e.jsx(vd,{className:"h-3 w-3 mr-1"}),"Has coach"]}),D.tier&&e.jsx(Oe,{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(Qd,{className:"h-3 w-3"}),V?"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(fn,{checked:D.enabled&&!V,onCheckedChange:G=>C(D,G)}),e.jsx(B,{size:"sm",variant:"outline",onClick:()=>c({profile:O||{id:D.user_id,name:null,email:null},entitlement:D}),children:"Edit"}),e.jsx(B,{size:"sm",variant:"ghost",className:"text-rose-600 hover:bg-rose-50",onClick:()=>E({profile:O||{id:D.user_id,name:null,email:null},entitlement:D}),children:e.jsx(Qn,{className:"h-4 w-4"})})]})]},D.id)})})]})}),e.jsx(ve,{children:e.jsxs(Me,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(In,{className:"h-5 w-5 text-primary"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Access through a coach assignment"}),e.jsx(Oe,{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 O=y[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(ja,{className:"h-6 w-6",children:[e.jsx(pi,{src:(O==null?void 0:O.avatar_url)||void 0}),e.jsx(Na,{className:"text-[10px]",children:KOe(O)})]}),e.jsx("span",{className:"text-sm",children:(O==null?void 0:O.name)||(O==null?void 0:O.email)||D.agent_id})]},D.agent_id)})})]})}),e.jsx(uOs,{state:o,onClose:()=>c(null),onSave:async D=>{if(!o)return;await j(o.profile.id,D)&&(se.success("Coaching access saved"),c(null))}})]})}function ZOe({icon:s,label:t,value:n,hint:r}){return e.jsx(ve,{children:e.jsxs(Me,{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 uOs({state:s,onClose:t,onSave:n}){const[r,a]=_.useState(""),[i,l]=_.useState(""),[o,c]=_.useState(""),[d,u]=_.useState(!0),[h,m]=_.useState(!1);_.useEffect(()=>{if(!s)return;const f=s.entitlement;a(f!=null&&f.expires_at?f.expires_at.slice(0,10):""),l((f==null?void 0:f.notes)||""),c((f==null?void 0:f.tier)||""),u(f?f.enabled:!0)},[s]);const p=async()=>{m(!0),await n({expires_at:r?new Date(`${r}T23:59:59`).toISOString():null,notes:i.trim()||null,tier:o.trim()||null,enabled:d}),m(!1)};return e.jsx(Ls,{open:!!s,onOpenChange:f=>!f&&t(),children:e.jsxs(Ps,{children:[e.jsx(Os,{children:e.jsx(Ds,{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(J,{children:"Access enabled"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Turn off to pause without removing the grant."})]}),e.jsx(fn,{checked:d,onCheckedChange:u})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Expires on (optional)"}),e.jsx(xe,{type:"date",value:r,onChange:f=>a(f.target.value)}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Leave blank for ongoing access."})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Tier / plan label (optional)"}),e.jsx(xe,{value:o,onChange:f=>c(f.target.value),placeholder:"e.g. Premium, Beta, Comp"})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Internal notes"}),e.jsx(Ms,{value:i,onChange:f=>l(f.target.value),rows:3,placeholder:"Why this member has access…"})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:t,children:"Cancel"}),e.jsx(B,{onClick:p,disabled:h,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:h?"Saving…":"Save access"})]})]})})}function hOs(){const s=Bt(),[t,n]=_.useState(""),[r,a]=_.useState("active"),{data:i=[]}=at({queryKey:["admin-coaches-lite"],queryFn:async()=>{const{data:p,error:f}=await q.from("coaches").select("id, user_id");if(f)throw f;const y=(p||[]).map(b=>b.user_id);if(!y.length)return[];const{data:v}=await q.from("profiles").select("id, name, email").in("id",y),g=new Map((v||[]).map(b=>[b.id,b]));return(p||[]).map(b=>{var j,S;return{id:b.id,label:((j=g.get(b.user_id))==null?void 0:j.name)||((S=g.get(b.user_id))==null?void 0:S.email)||b.user_id}})}}),{data:l=[],isLoading:o}=at({queryKey:["admin-coaching-assignments"],queryFn:async()=>{const{data:p,error:f}=await q.from("coaching_assignments").select("*").order("created_at",{ascending:!1});if(f)throw f;const y=[...new Set((p||[]).map(b=>b.agent_id))],{data:v}=y.length?await q.from("profiles").select("id, name, email").in("id",y):{data:[]},g=new Map((v||[]).map(b=>[b.id,b]));return(p||[]).map(b=>({...b,agent:g.get(b.agent_id)}))}}),c=p=>{var f;return((f=i.find(y=>y.id===p))==null?void 0:f.label)||"—"},d=_.useMemo(()=>{const p=t.trim().toLowerCase();return l.filter(f=>{var y,v;return r!=="all"&&f.status!==r?!1:p?(((y=f.agent)==null?void 0:y.name)||"").toLowerCase().includes(p)||(((v=f.agent)==null?void 0:v.email)||"").toLowerCase().includes(p)||c(f.coach_id).toLowerCase().includes(p):!0})},[l,t,r,i]),u=()=>{s.invalidateQueries({queryKey:["admin-coaching-assignments"]}),s.invalidateQueries({queryKey:["coach-roster"]})},h=async(p,f)=>{var g,b;if(f===p.coach_id||!await Xi({title:"Switch coach?",description:`${((g=p.agent)==null?void 0:g.name)||((b=p.agent)==null?void 0:b.email)} will move from ${c(p.coach_id)} to ${c(f)}. Session history stays with the assignment.`,confirmText:"Switch coach"}))return;const{error:v}=await q.from("coaching_assignments").update({coach_id:f}).eq("id",p.id);if(v)return se.error(v.message);se.success("Coach switched"),u()},m=async(p,f)=>{var v,g;if(f==="ended"&&!await Xi({title:"End assignment?",description:`${((v=p.agent)==null?void 0:v.name)||((g=p.agent)==null?void 0:g.email)} will lose access to the coaching workspace unless they have standalone access.`,confirmText:"End assignment",destructive:!0}))return;const{error:y}=await q.from("coaching_assignments").update({status:f,ended_at:f==="ended"?new Date().toISOString():null}).eq("id",p.id);if(y)return se.error(y.message);se.success(f==="ended"?"Assignment ended":"Assignment reactivated"),u()};return e.jsx(ve,{children:e.jsxs(Me,{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(In,{className:"h-5 w-5 text-primary"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Coach assignments"}),e.jsx(Oe,{variant:"secondary",className:"ml-auto",children:d.length})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Switch an agent to a different coach, end an assignment, or reactivate a past one."}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[e.jsx(xe,{placeholder:"Search by agent or coach…",value:t,onChange:p=>n(p.target.value)}),e.jsxs(is,{value:r,onValueChange:p=>a(p),children:[e.jsx(rs,{className:"sm:w-40",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"active",children:"Active"}),e.jsx(He,{value:"ended",children:"Ended"}),e.jsx(He,{value:"all",children:"All"})]})]})]}),o?e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading…"}):d.length===0?e.jsx("div",{className:"text-sm text-muted-foreground py-6 text-center",children:"No assignments found."}):e.jsx("div",{className:"divide-y border rounded-md",children:d.map(p=>{var f,y,v;return e.jsxs("div",{className:"p-3 flex flex-col md:flex-row md:items-center gap-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-medium truncate",children:((f=p.agent)==null?void 0:f.name)||((y=p.agent)==null?void 0:y.email)||p.agent_id}),e.jsxs("div",{className:"text-xs text-muted-foreground truncate",children:[(v=p.agent)==null?void 0:v.email," · ",p.pipeline_stage||"onboarding",p.status==="ended"&&" · ended"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(yQ,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs(is,{value:p.coach_id,onValueChange:g=>h(p,g),children:[e.jsx(rs,{className:"w-full md:w-56 h-9",children:e.jsx(ls,{})}),e.jsx(as,{children:i.map(g=>e.jsx(He,{value:g.id,children:g.label},g.id))})]}),p.status==="active"?e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>m(p,"ended"),children:[e.jsx(u$,{className:"h-4 w-4 mr-1"})," End"]}):e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>m(p,"active"),children:[e.jsx(Tx,{className:"h-4 w-4 mr-1"})," Reactivate"]})]})]},p.id)})})]})})}function mOs(){const s=Bt(),[t,n]=_.useState(""),[r,a]=_.useState([]),[i,l]=_.useState(null),{data:o=[],isLoading:c}=at({queryKey:["admin-coaches"],queryFn:async()=>{const{data:h,error:m}=await q.from("coaches").select("*").order("created_at",{ascending:!1});if(m)throw m;if(!(h!=null&&h.length))return[];const p=h.map(v=>v.user_id),{data:f}=await q.from("profiles").select("id, name, email, avatar_url").in("id",p),y=new Map((f||[]).map(v=>[v.id,v]));return h.map(v=>({...v,profile:y.get(v.user_id)}))}});_.useEffect(()=>{const h=t.trim();if(h.length<2){a([]);return}const m=setTimeout(async()=>{const{data:p}=await q.from("profiles").select("id, email, name, avatar_url").or(`email.ilike.%${h}%,name.ilike.%${h}%`).limit(10);a(p||[])},250);return()=>clearTimeout(m)},[t]);const d=async h=>{const{error:m}=await q.functions.invoke("manage-user-roles",{body:{userId:h.id,role:"coach",action:"add"}});if(m)return se.error(m.message);const{error:p}=await q.from("coaches").insert({user_id:h.id});if(p&&!String(p.message).includes("duplicate"))return se.error(p.message);se.success(`${h.name||h.email} is now a coach`),n(""),a([]),s.invalidateQueries({queryKey:["admin-coaches"]})},u=async(h,m)=>{const{error:p}=await q.from("coaches").update({is_certified:m}).eq("id",h);if(p)return se.error(p.message);se.success(m?"Marked Certified":"Removed certification"),s.invalidateQueries({queryKey:["admin-coaches"]})};return e.jsxs(zs,{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(mm,{className:"h-7 w-7 text-primary"}),e.jsx("h1",{className:"text-2xl font-bold",children:"LevelUp Coaching"})]}),e.jsxs(Yr,{defaultValue:"coaches",className:"space-y-6",children:[e.jsxs(Zr,{className:"flex-wrap h-auto",children:[e.jsx(Ht,{value:"coaches",children:"Coaches"}),e.jsx(Ht,{value:"assignments",children:"Assignments"}),e.jsx(Ht,{value:"access",children:"Coaching Access"}),e.jsx(Ht,{value:"applications",children:"Applications"}),e.jsx(Ht,{value:"settings",children:"Settings"})]}),e.jsx(Gt,{value:"assignments",className:"space-y-6",children:e.jsx(hOs,{})}),e.jsx(Gt,{value:"access",className:"space-y-6",children:e.jsx(dOs,{})}),e.jsx(Gt,{value:"applications",className:"space-y-6",children:e.jsx(xOs,{})}),e.jsx(Gt,{value:"settings",className:"space-y-6",children:e.jsx(pOs,{})}),e.jsxs(Gt,{value:"coaches",className:"space-y-6",children:[e.jsx(ve,{children:e.jsxs(Me,{className:"p-4 space-y-3",children:[e.jsx(xe,{placeholder:"Search by user email or name…",value:t,onChange:h=>n(h.target.value)}),t.trim().length>=2&&e.jsx("div",{className:"border rounded-md divide-y max-h-72 overflow-auto",children:r.length===0?e.jsx("div",{className:"p-3 text-sm text-muted-foreground",children:"No users found"}):r.map(h=>e.jsxs("div",{className:"flex items-center justify-between p-2 hover:bg-muted/40",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium truncate",children:h.name||h.email}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:h.email})]}),e.jsxs(B,{size:"sm",onClick:()=>d(h),children:[e.jsx(rn,{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(ve,{children:e.jsx(Me,{className:"p-6 text-center text-muted-foreground",children:"No coaches yet. Search for a user above to promote them."})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:o.map(h=>{var m,p,f;return e.jsx(ve,{children:e.jsxs(Me,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium",children:((m=h.profile)==null?void 0:m.name)||((p=h.profile)==null?void 0:p.email)||h.user_id}),e.jsx("div",{className:"text-xs text-muted-foreground",children:(f=h.profile)==null?void 0:f.email}),e.jsxs("div",{className:"flex gap-2 mt-2 flex-wrap",children:[h.is_certified&&e.jsxs(Oe,{className:"bg-yellow-500/15 text-yellow-700 border-yellow-300/40",children:[e.jsx(un,{className:"h-3 w-3 mr-1"}),"Certified"]}),h.accepting_clients&&e.jsx(Oe,{variant:"outline",children:"Accepting clients"})]})]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>l(h.id),children:[e.jsx(Pl,{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(fn,{checked:h.is_certified,onCheckedChange:y=>u(h.id,y)})]})]})},h.id)})})]})]})]})]}),e.jsx(fOs,{coachId:i,onClose:()=>l(null)})]})}function pOs(){const[s,t]=_.useState("1500"),[n,r]=_.useState(!1),[a,i]=_.useState(!1);_.useEffect(()=>{(async()=>{const{data:c}=await q.from("settings").select("value").eq("key","coaching_platform_fee_bps").maybeSingle();c!=null&&c.value&&t(String(c.value)),i(!0)})()},[]);const l=async()=>{const c=parseInt(s,10);if(isNaN(c)||c<0||c>5e3)return se.error("Enter a value between 0 and 5000 bps (0–50%)");r(!0);const{error:d}=await q.from("settings").upsert({key:"coaching_platform_fee_bps",value:String(c)});if(r(!1),d)return se.error(d.message);se.success("Platform fee updated")};if(!a)return null;const o=(parseInt(s,10)/100).toFixed(2);return e.jsx(ve,{children:e.jsxs(Me,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(F_,{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(J,{children:"Fee (bps)"}),e.jsx(xe,{type:"number",value:s,onChange:c=>t(c.target.value),min:0,max:5e3}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["= ",o,"%"]})]}),e.jsx(B,{onClick:l,disabled:n,className:"bg-[#406E71] hover:bg-[#2a4c64] self-end",children:n?"Saving…":"Save"})]})]})})}function fOs({coachId:s,onClose:t}){const[n,r]=_.useState(""),[a,i]=_.useState([]),[l,o]=_.useState(!1),c=Bt();_.useEffect(()=>{if(!s){r(""),i([]);return}},[s]),_.useEffect(()=>{const u=n.trim();if(u.length<2){i([]);return}o(!0);const h=setTimeout(async()=>{const{data:m}=await q.from("profiles").select("id, name, email").or(`email.ilike.%${u}%,name.ilike.%${u}%`).limit(15);i(m||[]),o(!1)},250);return()=>clearTimeout(h)},[n]);const d=async u=>{const{error:h}=await q.from("coaching_assignments").insert({coach_id:s,agent_id:u,status:"active",source:"admin",pipeline_stage:"onboarding"});if(h)return se.error(h.message);se.success("Agent assigned"),c.invalidateQueries({queryKey:["coach-roster"]}),t()};return e.jsx(Ls,{open:!!s,onOpenChange:u=>!u&&t(),children:e.jsxs(Ps,{children:[e.jsx(Os,{children:e.jsx(Ds,{children:"Assign Agent"})}),e.jsx(xe,{placeholder:"Search agents by name or email…",value:n,onChange:u=>r(u.target.value),autoFocus:!0}),e.jsx("div",{className:"space-y-1 max-h-72 overflow-auto border rounded-md",children:n.trim().length<2?e.jsx("div",{className:"p-3 text-sm text-muted-foreground",children:"Type at least 2 characters to search…"}):l?e.jsx("div",{className:"p-3 text-sm text-muted-foreground",children:"Searching…"}):a.length===0?e.jsx("div",{className:"p-3 text-sm text-muted-foreground",children:"No agents found"}):a.map(u=>e.jsxs("button",{onClick:()=>d(u.id),className:"w-full text-left p-2 hover:bg-muted",children:[e.jsx("div",{className:"font-medium",children:u.name||u.email}),e.jsx("div",{className:"text-xs text-muted-foreground",children:u.email})]},u.id))}),e.jsx(yr,{children:e.jsx(B,{variant:"outline",onClick:t,children:"Close"})})]})})}function xOs(){const s=Bt(),[t,n]=_.useState("pending"),[r,a]=_.useState(null),{data:i=[],isLoading:l}=at({queryKey:["coach-applications",t],queryFn:async()=>{let u=q.from("coach_applications").select("*").order("created_at",{ascending:!1});t!=="all"&&(u=u.eq("status",t));const{data:h,error:m}=await u;if(m)throw m;return h||[]}}),{data:o=0}=at({queryKey:["coach-applications-pending-count"],queryFn:async()=>{const{count:u}=await q.from("coach_applications").select("id",{count:"exact",head:!0}).eq("status","pending");return u||0}}),c=async(u,h)=>{const{error:m}=await q.from("coach_applications").update({status:h,reviewed_at:new Date().toISOString()}).eq("id",u);if(m)return se.error(m.message);se.success(`Marked ${h}`),s.invalidateQueries({queryKey:["coach-applications"]}),s.invalidateQueries({queryKey:["coach-applications-pending-count"]}),a(null)},d=u=>u==="approved"?e.jsxs(Oe,{className:"bg-emerald-500/15 text-emerald-700 border-emerald-300/40",children:[e.jsx(ea,{className:"h-3 w-3 mr-1"}),"Approved"]}):u==="rejected"?e.jsxs(Oe,{className:"bg-rose-500/15 text-rose-700 border-rose-300/40",children:[e.jsx(Qn,{className:"h-3 w-3 mr-1"}),"Rejected"]}):e.jsxs(Oe,{className:"bg-yellow-500/15 text-yellow-700 border-yellow-300/40",children:[e.jsx(Gr,{className:"h-3 w-3 mr-1"}),"Pending"]});return e.jsxs(ve,{children:[e.jsxs(Me,{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(XO,{className:"h-5 w-5 text-primary"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Coach Applications"}),o>0&&e.jsxs(Oe,{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(B,{size:"sm",variant:t===u?"default":"outline",onClick:()=>n(u),className:t===u?"bg-[#406E71] hover:bg-[#2a4c64]":"",children:u.charAt(0).toUpperCase()+u.slice(1)},u))})]}),l?e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading…"}):i.length===0?e.jsxs("div",{className:"text-sm text-muted-foreground p-6 text-center border rounded-md",children:["No applications ",t!=="all"?`with status "${t}"`:"yet","."]}):e.jsx("div",{className:"divide-y border rounded-md",children:i.map(u=>e.jsx("button",{onClick:()=>a(u),className:"w-full text-left p-3 hover:bg-muted/40 transition-colors",children:e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium",children:u.full_name}),e.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-3 mt-0.5",children:[e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(ln,{className:"h-3 w-3"}),u.email]}),u.brokerage&&e.jsxs("span",{children:["· ",u.brokerage]}),u.years_experience&&e.jsxs("span",{children:["· ",u.years_experience," yrs"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[d(u.status),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(u.created_at).toLocaleDateString()})]})]})},u.id))})]}),e.jsx(Ls,{open:!!r,onOpenChange:u=>!u&&a(null),children:e.jsx(Ps,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:r&&e.jsxs(e.Fragment,{children:[e.jsx(Os,{children:e.jsxs(Ds,{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(jB,{icon:ln,label:"Email",value:r.email,link:`mailto:${r.email}`}),r.phone&&e.jsx(jB,{icon:_a,label:"Phone",value:r.phone,link:`tel:${r.phone}`}),r.brokerage&&e.jsx(jB,{label:"Brokerage",value:r.brokerage}),r.years_experience&&e.jsx(jB,{label:"Years",value:r.years_experience}),r.website_url&&e.jsx(jB,{icon:wr,label:"Website",value:r.website_url,link:r.website_url}),r.linkedin_url&&e.jsx(jB,{icon:wr,label:"LinkedIn",value:r.linkedin_url,link:r.linkedin_url})]}),r.specialties&&e.jsx(XOe,{label:"Specialties",children:r.specialties}),e.jsx(XOe,{label:"Why they want to coach",children:r.why_coach}),r.results_story&&e.jsx(XOe,{label:"Results story",children:r.results_story}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs font-semibold uppercase text-muted-foreground",children:"Admin notes"}),e.jsx(Ms,{defaultValue:r.admin_notes||"",rows:3,onBlur:async u=>{const h=u.target.value;h!==(r.admin_notes||"")&&(await q.from("coach_applications").update({admin_notes:h}).eq("id",r.id),s.invalidateQueries({queryKey:["coach-applications"]}))},placeholder:"Internal notes (saved on blur)…"})]})]}),e.jsxs(yr,{className:"gap-2 flex-wrap",children:[r.status!=="rejected"&&e.jsxs(B,{variant:"outline",onClick:()=>c(r.id,"rejected"),className:"text-rose-600 border-rose-200 hover:bg-rose-50",children:[e.jsx(Qn,{className:"h-4 w-4 mr-1"})," Reject"]}),r.status!=="pending"&&e.jsxs(B,{variant:"outline",onClick:()=>c(r.id,"pending"),children:[e.jsx(Gr,{className:"h-4 w-4 mr-1"})," Move to pending"]}),r.status!=="approved"&&e.jsxs(B,{onClick:()=>c(r.id,"approved"),className:"bg-emerald-600 hover:bg-emerald-700",children:[e.jsx(ea,{className:"h-4 w-4 mr-1"})," Approve"]})]})]})})})]})}function jB({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 XOe({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 gOs(){const s=Fn(),{data:t}=Jre(),n=Bt(),[r,a]=_.useState(!1),[i,l]=_.useState(!1),[o,c]=_.useState(null),{data:d,refetch:u}=at({queryKey:["coach-stripe-status",t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{const{data:v}=await q.functions.invoke("coach-stripe-status");return v}}),{data:h=[]}=at({queryKey:["coach-packages",t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{const{data:v}=await q.from("coaching_packages").select("*").eq("coach_id",t.id).order("sort_order");return v||[]}});_.useEffect(()=>{const v=new URLSearchParams(window.location.search);(v.get("onboarded")||v.get("refresh"))&&u()},[u]);const m=async()=>{var j,S;a(!0);const{data:v,error:g}=await q.functions.invoke("coach-stripe-connect");a(!1);let b=v==null?void 0:v.error;if(!b&&g)try{const C=await((S=(j=g==null?void 0:g.context)==null?void 0:j.json)==null?void 0:S.call(j));b=(C==null?void 0:C.error)||g.message}catch{b=g.message}if(b)return se.error(b,{duration:1e4});v!=null&&v.url&&(window.location.href=v.url)},p=d||{},f=!!(t!=null&&t.use_platform_stripe),y=f||p.connected&&p.charges_enabled;return e.jsx(zs,{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(B,{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(ve,{children:e.jsxs(Me,{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(_y,{className:"h-5 w-5"})," Stripe Connect"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:f?"Your coaching sales are billed through the main LevelUp Stripe account.":"Payouts go directly to your bank. LevelUp takes a small platform fee from each charge."})]}),y?e.jsxs(Oe,{className:"bg-emerald-500/15 text-emerald-700 border-emerald-300/40 flex items-center gap-1",children:[e.jsx(Er,{className:"h-3 w-3"})," ",f?"Using LevelUp billing":"Connected"]}):p.connected?e.jsxs(Oe,{variant:"secondary",className:"flex items-center gap-1",children:[e.jsx(Xo,{className:"h-3 w-3"})," Setup incomplete"]}):e.jsx(Oe,{variant:"outline",children:"Not connected"})]}),!f&&e.jsxs(B,{onClick:m,disabled:r,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[y?"Update Stripe details":p.connected?"Finish Stripe setup":"Connect Stripe",e.jsx(wr,{className:"h-4 w-4 ml-1"})]})]})}),e.jsx(ve,{children:e.jsxs(Me,{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(B,{size:"sm",onClick:()=>{c(null),l(!0)},disabled:!y,children:[e.jsx(rn,{className:"h-4 w-4 mr-1"})," New Package"]})]}),!y&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Connect Stripe before creating packages."}),h.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No packages yet."}):e.jsx("div",{className:"space-y-2",children:h.map(v=>e.jsxs("div",{className:"flex items-center gap-3 p-3 border rounded-lg",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium flex items-center gap-2",children:[v.name,v.is_active&&v.accepting_clients===!1&&e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full bg-amber-100 text-amber-800 font-semibold",children:"Booked full"})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:["$",(v.price_cents/100).toFixed(0)," / ",v.billing_interval,!v.is_active&&" · Inactive"]})]}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{c(v),l(!0)},children:e.jsx(Ya,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:async()=>{await Xi("Delete this package?")&&(await q.from("coaching_packages").delete().eq("id",v.id),n.invalidateQueries({queryKey:["coach-packages",t==null?void 0:t.id]}))},children:e.jsx(Sn,{className:"h-4 w-4"})})]},v.id))})]})}),e.jsx(yOs,{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 yOs({open:s,onOpenChange:t,coachId:n,pkg:r,onSaved:a}){const[i,l]=_.useState(""),[o,c]=_.useState(""),[d,u]=_.useState(""),[h,m]=_.useState("month"),[p,f]=_.useState(!0),[y,v]=_.useState(!0),[g,b]=_.useState(!1);_.useEffect(()=>{s&&(l((r==null?void 0:r.name)||""),c((r==null?void 0:r.description)||""),u(r?(r.price_cents/100).toString():""),m((r==null?void 0:r.billing_interval)||"month"),f((r==null?void 0:r.is_active)??!0),v((r==null?void 0:r.accepting_clients)??!0))},[s,r]);const j=async()=>{if(!i.trim()||!d)return se.error("Name and price required");b(!0);const S={coach_id:n,name:i,description:o||null,price_cents:Math.round(Number(d)*100),billing_interval:h,is_active:p,accepting_clients:y},{error:C}=r!=null&&r.id?await q.from("coaching_packages").update(S).eq("id",r.id):await q.from("coaching_packages").insert(S);if(b(!1),C)return se.error(C.message);se.success("Saved"),a==null||a(),t(!1)};return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{children:[e.jsx(Os,{children:e.jsx(Ds,{children:r!=null&&r.id?"Edit Package":"New Package"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(xe,{placeholder:"Name (e.g. Accelerator)",value:i,onChange:S=>l(S.target.value)}),e.jsx(Ms,{rows:3,placeholder:"What's included",value:o,onChange:S=>c(S.target.value)}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Price (USD)"}),e.jsx(xe,{type:"number",value:d,onChange:S=>u(S.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Interval"}),e.jsxs(is,{value:h,onValueChange:m,children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"month",children:"Monthly"}),e.jsx(He,{value:"year",children:"Yearly"}),e.jsx(He,{value:"one_time",children:"One-time"})]})]})]})]}),e.jsxs("div",{className:"space-y-2 pt-1",children:[e.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[e.jsx("input",{type:"checkbox",checked:p,onChange:S=>f(S.target.checked)}),"Active (visible to agents)"]}),e.jsxs("label",{className:"flex items-start gap-2 text-sm",children:[e.jsx("input",{type:"checkbox",className:"mt-0.5",checked:y,onChange:S=>v(S.target.checked)}),e.jsxs("span",{children:[e.jsx("span",{className:"font-medium",children:"Accepting new clients"}),e.jsx("span",{className:"block text-xs text-muted-foreground",children:"Uncheck if you're booked full — visitors will still see the package but can't sign up."})]})]})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(B,{onClick:j,disabled:g,children:r!=null&&r.id?"Save":"Create"})]})]})})}function qxt({kind:s,value:t,onChange:n}){const r=_.useRef(null),[a,i]=_.useState(!1),[l,o]=_.useState(!1),[c,d]=_.useState(null),u=_.useRef(null),h=_.useRef(null),m=_.useRef(null),p=_.useRef([]),[f,y]=_.useState(!1),v=s==="photo"?"image/*":"video/*",g=s==="photo"?10*1024*1024:200*1024*1024,b=async(M,I)=>{var H;const{data:D}=await q.auth.getUser(),O=(H=D.user)==null?void 0:H.id;if(!O)return se.error("Not signed in");if(M.size>g)return se.error(`File too large. Max ${s==="photo"?"10MB":"200MB"}.`);i(!0);const V=`${O}/${s}-${Date.now()}.${I}`,{error:G}=await q.storage.from("coach-media").upload(V,M,{upsert:!0,contentType:M.type||(s==="photo"?"image/jpeg":"video/webm")});if(G)return i(!1),se.error(G.message);const{data:$}=await q.storage.from("coach-media").createSignedUrl(V,60*60*24*365*10);i(!1),$!=null&&$.signedUrl&&(n($.signedUrl),se.success("Uploaded"),d(null))},j=async M=>{const I=M.name.split(".").pop()||(s==="photo"?"jpg":"webm");await b(M,I)},S=async()=>{try{const M=await navigator.mediaDevices.getUserMedia({video:!0,audio:!0});h.current=M,y(!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(O=>O.stop())},m.current=I,I.start(),o(!0)}catch(M){se.error(M.message||"Could not access camera")}},C=()=>{var M;(M=m.current)==null||M.stop(),o(!1)},E=()=>{var M;(M=h.current)==null||M.getTracks().forEach(I=>I.stop()),y(!1),o(!1),d(null)},P=async()=>{c&&(await b(c,"webm"),E())};return _.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:v,className:"hidden",onChange:M=>{var D;const I=(D=M.target.files)==null?void 0:D[0];I&&j(I),M.target.value=""}}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",disabled:a,onClick:()=>{var M;return(M=r.current)==null?void 0:M.click()},children:[a?e.jsx(Ct,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Oa,{className:"h-4 w-4 mr-1"}),s==="photo"?"Upload photo":"Upload video"]}),s==="video"&&e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:S,disabled:a||f,children:[e.jsx(cg,{className:"h-4 w-4 mr-1"})," Record intro"]}),t&&e.jsxs(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>n(""),children:[e.jsx(Sn,{className:"h-4 w-4 mr-1"})," Remove"]})]}),f&&e.jsxs("div",{className:"rounded-lg border p-3 space-y-3 bg-background",children:[c?e.jsx("video",{src:URL.createObjectURL(c),controls:!0,className:"w-full max-h-64 rounded bg-black"}):e.jsx("video",{ref:u,muted:!0,playsInline:!0,className:"w-full max-h-64 rounded bg-black"}),e.jsxs("div",{className:"flex gap-2",children:[!c&&l&&e.jsxs(B,{type:"button",size:"sm",onClick:C,className:"bg-red-600 hover:bg-red-700",children:[e.jsx(wb,{className:"h-4 w-4 mr-1"})," Stop"]}),!c&&!l&&e.jsxs(B,{type:"button",size:"sm",onClick:()=>{var M;return(M=m.current)==null?void 0:M.start()},children:[e.jsx(Kr,{className:"h-4 w-4 mr-1"})," Start"]}),c&&e.jsxs(e.Fragment,{children:[e.jsxs(B,{type:"button",size:"sm",onClick:P,disabled:a,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[a?e.jsx(Ct,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Oa,{className:"h-4 w-4 mr-1"}),"Use this recording"]}),e.jsx(B,{type:"button",size:"sm",variant:"outline",onClick:()=>{d(null),S()},children:"Re-record"})]}),e.jsx(B,{type:"button",size:"sm",variant:"ghost",onClick:E,children:"Cancel"})]})]})]})}function d9t(){const{user:s}=hs(),t=Bt(),n=at({queryKey:["booking-settings",s==null?void 0:s.id],queryFn:async()=>{const{data:v,error:g}=await q.from("agent_booking_settings").select("*").eq("user_id",s.id).maybeSingle();if(g)throw g;return v},enabled:!!s}),r=at({queryKey:["booking-types",s==null?void 0:s.id],queryFn:async()=>{const{data:v,error:g}=await q.from("agent_booking_types").select("*").eq("user_id",s.id).order("sort_order");if(g)throw g;return v},enabled:!!s}),a=at({queryKey:["availability-slots",s==null?void 0:s.id],queryFn:async()=>{const{data:v,error:g}=await q.from("agent_availability_slots").select("*").eq("user_id",s.id).order("day_of_week").order("start_time");if(g)throw g;return v},enabled:!!s}),i=at({queryKey:["blocked-dates",s==null?void 0:s.id],queryFn:async()=>{const{data:v,error:g}=await q.from("agent_blocked_dates").select("*").eq("user_id",s.id).order("blocked_date");if(g)throw g;return v},enabled:!!s}),l=at({queryKey:["bookings",s==null?void 0:s.id],queryFn:async()=>{const{data:v,error:g}=await q.from("bookings").select("*, booking_type:agent_booking_types(*)").eq("agent_user_id",s.id).order("booking_date",{ascending:!1});if(g)throw g;return v},enabled:!!s}),o=mt({mutationFn:async()=>{const{data:v,error:g}=await q.from("agent_booking_settings").insert({user_id:s.id,slug:""}).select().single();if(g)throw g;const b=[{name:"Listing Consultation",description:"Get a comprehensive market analysis and listing strategy for your home",duration_minutes:60,color:"#10B981",icon:"Home",sort_order:0},{name:"Buyer Consultation",description:"Discuss your home search criteria, budget, and buying process",duration_minutes:45,color:"#3B82F6",icon:"Search",sort_order:1},{name:"Home Valuation",description:"Find out what your home is worth in today's market",duration_minutes:30,color:"#F59E0B",icon:"DollarSign",sort_order:2},{name:"General Meeting",description:"Coffee chat, check-in, or quick real estate question",duration_minutes:30,color:"#8B5CF6",icon:"Coffee",sort_order:3}],{error:j}=await q.from("agent_booking_types").insert(b.map(E=>({...E,user_id:s.id})));if(j)throw j;const S=[1,2,3,4,5].map(E=>({user_id:s.id,day_of_week:E,start_time:"09:00",end_time:"17:00"})),{error:C}=await q.from("agent_availability_slots").insert(S);if(C)throw C;return v},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-settings"]}),t.invalidateQueries({queryKey:["booking-types"]}),t.invalidateQueries({queryKey:["availability-slots"]}),se.success("Scheduler set up successfully!")},onError:v=>se.error(v.message)}),c=mt({mutationFn:async v=>{const{error:g}=await q.from("agent_booking_settings").update(v).eq("user_id",s.id);if(g)throw g},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-settings"]}),se.success("Settings updated")},onError:v=>se.error(v.message)}),d=mt({mutationFn:async v=>{const g={...v,user_id:s.id};if(v.id){const{error:b}=await q.from("agent_booking_types").update(g).eq("id",v.id);if(b)throw b}else{const{error:b}=await q.from("agent_booking_types").insert(g);if(b)throw b}},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-types"]}),se.success("Booking type saved")},onError:v=>se.error(v.message)}),u=mt({mutationFn:async v=>{const{error:g}=await q.from("agent_booking_types").delete().eq("id",v);if(g)throw g},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-types"]}),se.success("Booking type deleted")},onError:v=>se.error(v.message)}),h=mt({mutationFn:async v=>{const g={...v,user_id:s.id};if(v.id){const{error:b}=await q.from("agent_availability_slots").update(g).eq("id",v.id);if(b)throw b}else{const{error:b}=await q.from("agent_availability_slots").insert(g);if(b)throw b}},onSuccess:()=>{t.invalidateQueries({queryKey:["availability-slots"]})},onError:v=>se.error(v.message)}),m=mt({mutationFn:async v=>{const{error:g}=await q.from("agent_availability_slots").delete().eq("id",v);if(g)throw g},onSuccess:()=>{t.invalidateQueries({queryKey:["availability-slots"]})},onError:v=>se.error(v.message)}),p=mt({mutationFn:async v=>{const{blocked_date:g,end_date:b,reason:j}=v,S=D=>{const[O,V,G]=D.split("-").map(Number);return new Date(O,V-1,G)},C=D=>`${D.getFullYear()}-${String(D.getMonth()+1).padStart(2,"0")}-${String(D.getDate()).padStart(2,"0")}`,E=S(g),P=b?S(b):E;if(P366)throw new Error("Range too large (max 1 year)");const{error:I}=await q.from("agent_blocked_dates").upsert(M,{onConflict:"user_id,blocked_date",ignoreDuplicates:!0});if(I)throw I;return M.length},onSuccess:v=>{t.invalidateQueries({queryKey:["blocked-dates"]}),se.success(v&&v>1?`${v} dates blocked`:"Date blocked")},onError:v=>se.error(v.message)}),f=mt({mutationFn:async v=>{const{error:g}=await q.from("agent_blocked_dates").delete().eq("id",v);if(g)throw g},onSuccess:()=>{t.invalidateQueries({queryKey:["blocked-dates"]})},onError:v=>se.error(v.message)}),y=mt({mutationFn:async({id:v,reason:g})=>{const{error:b}=await q.from("bookings").update({status:"cancelled",cancelled_at:new Date().toISOString(),cancel_reason:g}).eq("id",v);if(b)throw b;await q.functions.invoke("agent-booking",{body:{action:"cancel",booking_id:v}}).catch(j=>console.error("Google calendar cleanup failed:",j))},onSuccess:()=>{t.invalidateQueries({queryKey:["bookings"]}),se.success("Booking cancelled")},onError:v=>se.error(v.message)});return{settings:n.data,bookingTypes:r.data??[],availability:a.data??[],blockedDates:i.data??[],bookings:l.data??[],isLoading:n.isLoading,initializeSettings:o,updateSettings:c,upsertBookingType:d,deleteBookingType:u,upsertAvailability:h,deleteAvailability:m,addBlockedDate:p,removeBlockedDate:f,cancelBooking:y}}const $xt=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];function u9t({slots:s,onSave:t,onDelete:n}){const[r,a]=_.useState(null),[i,l]=_.useState("09:00"),[o,c]=_.useState("17:00"),d=$xt.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(ve,{children:[e.jsxs(bt,{children:[e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(Gr,{className:"h-5 w-5"}),"Weekly Availability"]}),e.jsx(kn,{children:"Set your available hours for each day"})]}),e.jsx(Me,{className:"space-y-2",children:$xt.map((h,m)=>{const p=d[m];return e.jsxs("div",{className:"flex items-start gap-3 py-2 border-b last:border-0",children:[e.jsx("div",{className:"w-24 pt-1",children:e.jsx("p",{className:"text-sm font-medium",children:h})}),e.jsxs("div",{className:"flex-1 space-y-1",children:[p.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-1",children:"Unavailable"}):p.map(f=>{var y,v;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xe,{type:"time",className:"w-28 h-8 text-sm",defaultValue:(y=f.start_time)==null?void 0:y.slice(0,5),onBlur:g=>t({id:f.id,start_time:g.target.value})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"to"}),e.jsx(xe,{type:"time",className:"w-28 h-8 text-sm",defaultValue:(v=f.end_time)==null?void 0:v.slice(0,5),onBlur:g=>t({id:f.id,end_time:g.target.value})}),e.jsx(fn,{checked:f.is_active,onCheckedChange:g=>t({id:f.id,is_active:g})}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>n(f.id),children:e.jsx(Sn,{className:"h-3.5 w-3.5 text-muted-foreground"})})]},f.id)}),r===m?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xe,{type:"time",className:"w-28 h-8 text-sm",value:i,onChange:f=>l(f.target.value)}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"to"}),e.jsx(xe,{type:"time",className:"w-28 h-8 text-sm",value:o,onChange:f=>c(f.target.value)}),e.jsx(B,{size:"sm",className:"h-8",onClick:u,children:"Add"}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-8",onClick:()=>a(null),children:"Cancel"})]}):e.jsxs(B,{variant:"ghost",size:"sm",className:"h-7 text-xs text-muted-foreground",onClick:()=>a(m),children:[e.jsx(rn,{className:"h-3 w-3 mr-1"})," Add hours"]})]})]},h)})})]})}function Vxt(s){const[t,n,r]=s.split("-").map(Number);return Hs(new Date(t,n-1,r),"MMM d, yyyy")}function vOs(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 h9t({blockedDates:s,onAdd:t,onRemove:n}){const[r,a]=_.useState(!1),[i,l]=_.useState(""),[o,c]=_.useState(""),[d,u]=_.useState(""),h=()=>{i&&(t({blocked_date:i,end_date:o||void 0,reason:d||void 0}),a(!1),l(""),c(""),u(""))};return e.jsxs(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(Aq,{className:"h-5 w-5"}),"Blocked Dates"]}),e.jsx(kn,{children:"Block a single day or a full date range (vacations, holidays, etc.)"})]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>a(!0),children:[e.jsx(rn,{className:"h-4 w-4 mr-1"})," Block Dates"]})]}),e.jsxs(Me,{children:[r&&e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-3 p-3 rounded-lg border bg-muted/30",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xe,{type:"date",value:i,onChange:m=>l(m.target.value),className:"w-40"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"to"}),e.jsx(xe,{type:"date",value:o,min:i||void 0,onChange:m=>c(m.target.value),className:"w-40",placeholder:"Optional"})]}),e.jsx(xe,{placeholder:"Reason (optional)",value:d,onChange:m=>u(m.target.value),className:"flex-1 min-w-[180px]"}),e.jsx(B,{size:"sm",onClick:h,children:"Add"}),e.jsx(B,{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:vOs(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:[Vxt(m.start),m.end!==m.start&&` – ${Vxt(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(Qn,{className:"h-3.5 w-3.5"})})]},m.ids[0]))})]})]})}function bOs(){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}=d9t(),[p,f]=_.useState("1-on-1 Coaching Session"),[y,v]=_.useState(45),g=_.useMemo(()=>t.filter(j=>j.is_coaching_only),[t]);if(a)return e.jsx(ve,{children:e.jsxs(Me,{className:"p-6 flex items-center gap-2 text-muted-foreground",children:[e.jsx(Ct,{className:"h-4 w-4 animate-spin"})," Loading your calendar…"]})});if(!s)return e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(Qd,{className:"h-5 w-5"})," Coaching calendar"]}),e.jsx(kn,{children:"Set up your scheduler once, then open availability for the members assigned to you."})]}),e.jsx(Me,{children:e.jsxs(B,{onClick:()=>i.mutate(),disabled:i.isPending,children:[i.isPending&&e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),"Set up my calendar"]})})]});const b=()=>{p.trim()&&(o.mutate({name:p.trim(),description:"Private coaching session",duration_minutes:y,color:"#406E71",icon:"Video",is_active:!0,qualification_enabled:!1,is_coaching_only:!0,sort_order:99}),f("1-on-1 Coaching Session"),v(45))};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(Kr,{className:"h-5 w-5"})," Coaching session types"]}),e.jsx(kn,{children:"Only assigned members can book these. They stay hidden from your public booking page."})]}),e.jsxs(Me,{className:"space-y-3",children:[g.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."}):g.map(j=>e.jsxs("div",{className:"flex flex-wrap items-center gap-3 rounded-lg border p-3",children:[e.jsx(xe,{className:"h-9 max-w-[240px]",defaultValue:j.name,onBlur:S=>S.target.value!==j.name&&o.mutate({id:j.id,name:S.target.value})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xe,{type:"number",min:10,max:240,step:5,className:"h-9 w-20",defaultValue:j.duration_minutes,onBlur:S=>o.mutate({id:j.id,duration_minutes:parseInt(S.target.value)||30})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"min"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fn,{checked:j.is_active,onCheckedChange:S=>o.mutate({id:j.id,is_active:S})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:j.is_active?"Bookable":"Paused"})]}),e.jsx(Oe,{variant:"secondary",children:"Coaching only"}),e.jsx(B,{variant:"ghost",size:"sm",className:"ml-auto h-8 w-8 p-0",onClick:async()=>{await Xi({title:"Delete session type?",description:`"${j.name}" will no longer be bookable.`,confirmText:"Delete",destructive:!0})&&c.mutate(j.id)},children:e.jsx(Sn,{className:"h-3.5 w-3.5 text-muted-foreground"})})]},j.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(J,{className:"text-xs",children:"New session type"}),e.jsx(xe,{value:p,onChange:j=>f(j.target.value),className:"h-9"})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Minutes"}),e.jsx(xe,{type:"number",min:10,max:240,step:5,className:"h-9 w-24",value:y,onChange:j=>v(parseInt(j.target.value)||30)})]}),e.jsxs(B,{onClick:b,disabled:o.isPending,children:[e.jsx(rn,{className:"h-4 w-4 mr-1"})," Add"]})]})]})]}),e.jsx(u9t,{slots:n,onSave:j=>d.mutate(j),onDelete:j=>u.mutate(j)}),e.jsx(h9t,{blockedDates:r,onAdd:j=>h.mutate(j),onRemove:j=>m.mutate(j)}),e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsx(St,{children:"Scheduling rules"}),e.jsx(kn,{children:"Applies to coaching bookings on your calendar."})]}),e.jsxs(Me,{className:"grid gap-4 sm:grid-cols-3",children:[e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Buffer between sessions (min)"}),e.jsx(xe,{type:"number",min:0,max:120,step:5,className:"h-9",defaultValue:s.buffer_minutes,onBlur:j=>l.mutate({buffer_minutes:parseInt(j.target.value)||0})})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Minimum notice (hours)"}),e.jsx(xe,{type:"number",min:0,max:168,className:"h-9",defaultValue:s.min_notice_hours,onBlur:j=>l.mutate({min_notice_hours:parseInt(j.target.value)||0})})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Bookable up to (days out)"}),e.jsx(xe,{type:"number",min:1,max:365,className:"h-9",defaultValue:s.max_advance_days,onBlur:j=>l.mutate({max_advance_days:parseInt(j.target.value)||30})})]})]})]})]})}async function UY(s,t){const n=s==="agent"?"agent-google-calendar":"coach-google-calendar",{data:r,error:a}=await q.functions.invoke(n,{body:t});if(a){let i=a.message;try{const l=a.context;if(l!=null&&l.json){const o=await l.json();o!=null&&o.error&&(i=o.error)}}catch{}throw new Error(i)}if(r!=null&&r.error)throw new Error(r.error);return r}function m9t(s=!0,t="coach"){const n=Bt(),r=at({queryKey:["google-calendar-connection",t],enabled:s,queryFn:async()=>await UY(t,{action:"status"})}),a=()=>n.invalidateQueries({queryKey:["google-calendar-connection",t]}),i=mt({mutationFn:async()=>{const d=await UY(t,{action:"start",origin:window.location.origin}),u=d==null?void 0:d.authorizationUrl;if(!u)throw new Error("Google did not return an authorization link.");try{sessionStorage.setItem("googleCalendarReturnTo",window.location.pathname),sessionStorage.setItem("googleCalendarScope",t)}catch{}window.location.assign(u),await new Promise(h=>setTimeout(h,4e3))},onSuccess:a}),l=mt({mutationFn:()=>UY(t,{action:"disconnect"}),onSuccess:a}),o=mt({mutationFn:d=>UY(t,{action:"settings",...d}),onSuccess:a}),c=mt({mutationFn:()=>UY(t,{action:"refresh_calendars"}),onSuccess:a});return{status:r,connect:i,disconnect:l,updateSettings:o,refreshCalendars:c}}function p9t({scope:s="coach"}){const{status:t,connect:n,disconnect:r,updateSettings:a,refreshCalendars:i}=m9t(!0,s),l=s==="agent";_.useEffect(()=>{const d=new URLSearchParams(window.location.search),u=d.get("google_calendar");if(!u)return;u==="connected"?(se.success("Google Calendar connected"),t.refetch()):se.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(ve,{children:[e.jsx(bt,{children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(bv,{className:"h-5 w-5"})," Google Calendar"]}),e.jsx(kn,{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(Oe,{className:"bg-emerald-600 hover:bg-emerald-600 shrink-0",children:[e.jsx(Er,{className:"h-3.5 w-3.5 mr-1"})," Connected"]})]})}),e.jsxs(Me,{className:"space-y-4",children:[t.isLoading&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Ct,{className:"h-4 w-4 animate-spin"})," Checking your connection…"]}),c&&e.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-destructive/40 bg-destructive/5 p-3 text-sm",children:[e.jsx(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(B,{onClick:()=>n.mutate(void 0,{onSuccess:()=>se.success("Google Calendar connected"),onError:d=>se.error(d.message)}),disabled:n.isPending,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[n.isPending?e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(bv,{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(J,{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(fn,{checked:o.sync_enabled,onCheckedChange:d=>a.mutate({sync_enabled:d},{onError:u=>se.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(J,{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(fn,{checked:o.invite_guest!==!1,onCheckedChange:d=>a.mutate({invite_guest:d},{onError:u=>se.error(u.message)})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs",children:"Calendar to use"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(is,{value:o.selected_calendar_id||"primary",onValueChange:d=>a.mutate({calendar_id:d},{onError:u=>se.error(u.message)}),children:[e.jsx(rs,{className:"h-9",children:e.jsx(ls,{placeholder:"Primary calendar"})}),e.jsxs(as,{children:[e.jsx(He,{value:"primary",children:"Primary calendar"}),o.calendars.filter(d=>!d.primary).map(d=>e.jsx(He,{value:d.id,children:d.summary||d.id},d.id))]})]}),e.jsx(B,{variant:"outline",size:"icon",className:"h-9 w-9 shrink-0",onClick:()=>i.mutate(void 0,{onSuccess:()=>se.success("Calendars refreshed"),onError:d=>se.error(d.message)}),disabled:i.isPending,children:e.jsx(uo,{className:`h-4 w-4 ${i.isPending?"animate-spin":""}`})})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 pt-1",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>n.mutate(void 0,{onSuccess:()=>se.success("Google Calendar reconnected"),onError:d=>se.error(d.message)}),disabled:n.isPending,children:[n.isPending?e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(uo,{className:"h-4 w-4 mr-2"}),"Reconnect"]}),e.jsxs(B,{variant:"ghost",size:"sm",className:"text-destructive",disabled:r.isPending,onClick:async()=>{await Xi({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:()=>se.success("Google Calendar disconnected"),onError:u=>se.error(u.message)})},children:[e.jsx(d$,{className:"h-4 w-4 mr-2"})," Disconnect"]})]})]})]})]})}function _Os(){const s=Fn(),{data:t,isLoading:n}=Jre(),r=Bt(),[a,i]=_.useState(""),[l,o]=_.useState(""),[c,d]=_.useState(""),[u,h]=_.useState(""),[m,p]=_.useState(""),[f,y]=_.useState(!1),[v,g]=_.useState([]),[b,j]=_.useState(""),[S,C]=_.useState(2),[E,P]=_.useState(!1);_.useEffect(()=>{if(!t)return;const V=t;i(V.slug||""),o(V.headline||""),d(V.bio||""),h(V.photo_url||""),p(V.intro_video_url||""),y(!!V.accepting_clients),g(V.specialties||[]),C(V.default_sessions_per_month??2)},[t]);const M=async()=>{if(!t)return;P(!0);const{error:V}=await q.from("coaches").update({slug:a.trim()||null,headline:l||null,bio:c||null,photo_url:u||null,intro_video_url:m||null,accepting_clients:f,specialties:v,default_sessions_per_month:S}).eq("id",t.id);if(P(!1),V)return se.error(V.message);se.success("Profile saved"),r.invalidateQueries({queryKey:["my-coach-profile"]})},I=()=>{const V=b.trim();if(V){if(v.includes(V))return j("");g([...v,V]),j("")}};if(n)return e.jsx(zs,{title:"Coach Settings",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!t)return e.jsx(zs,{title:"Coach Settings",children:e.jsx("div",{className:"max-w-2xl mx-auto p-8 text-center text-muted-foreground",children:"You don't have a coach profile yet."})});const D=t,O=D.slug?`${window.location.origin}/coaches/${D.slug}`:null;return e.jsx(zs,{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(B,{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:[O&&e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>window.open(O,"_blank"),children:[e.jsx(wr,{className:"h-4 w-4 mr-1"})," View public"]}),e.jsxs(B,{onClick:M,disabled:E,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[e.jsx(Ho,{className:"h-4 w-4 mr-1"})," ",E?"Saving…":"Save"]})]})]}),D.is_certified&&e.jsxs("div",{className:"rounded-lg border border-yellow-300/50 bg-yellow-50 dark:bg-yellow-950/20 px-4 py-3 text-sm",children:["✨ ",e.jsx("strong",{children:"LevelUp Certified"})," — Your profile displays a verified badge."]}),e.jsx(ve,{children:e.jsxs(Me,{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(fn,{checked:f,onCheckedChange:y})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Public URL slug"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:"/coaches/"}),e.jsx(xe,{value:a,onChange:V=>i(V.target.value.toLowerCase().replace(/[^a-z0-9-]/g,"")),placeholder:"your-name"})]})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Headline"}),e.jsx(xe,{value:l,onChange:V=>o(V.target.value),placeholder:"e.g. Helping new agents close their first 10 deals",maxLength:140})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Bio"}),e.jsx(Ms,{rows:6,value:c,onChange:V=>d(V.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(J,{children:"Profile photo"}),e.jsx(qxt,{kind:"photo",value:u,onChange:h})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Intro video"}),e.jsx(qxt,{kind:"video",value:m,onChange:p})]})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Specialties"}),e.jsx("div",{className:"flex flex-wrap gap-2 mb-2",children:v.map(V=>e.jsxs(Oe,{variant:"secondary",className:"gap-1",children:[V,e.jsx("button",{onClick:()=>g(v.filter(G=>G!==V)),children:e.jsx(Qn,{className:"h-3 w-3"})})]},V))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{value:b,onChange:V=>j(V.target.value),placeholder:"Add a specialty…",onKeyDown:V=>{V.key==="Enter"&&(V.preventDefault(),I())}}),e.jsx(B,{type:"button",variant:"outline",onClick:I,children:e.jsx(rn,{className:"h-4 w-4"})})]})]})]})}),e.jsx(ve,{children:e.jsxs(Me,{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(J,{children:"Sessions each agent can book per month"}),e.jsx(xe,{type:"number",min:1,max:31,value:S,onChange:V=>C(Math.max(1,parseInt(V.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(B,{variant:"outline",onClick:()=>s("/mission-control/scheduler"),children:"Open full Scheduler"})]})]})}),e.jsx(p9t,{}),e.jsx(bOs,{}),e.jsx(ve,{children:e.jsx(Me,{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(B,{variant:"outline",onClick:()=>s("/coaching/billing"),children:"Go to Billing"})]})})}),e.jsx(wOs,{coachId:D.id})]})})}function wOs({coachId:s}){const[t,n]=_.useState("");Bt();const{data:r=[],refetch:a}=at({queryKey:["coach-invites",s],queryFn:async()=>{const{data:c}=await q.from("coaching_invites").select("*").eq("coach_id",s).order("created_at",{ascending:!1});return c||[]}}),i=async()=>{const c=t.trim().toLowerCase();if(!c)return se.error("Email required");const{error:d}=await q.from("coaching_invites").insert({coach_id:s,email:c});if(d)return se.error(d.message);n(""),se.success("Invite created"),a()},l=c=>{const d=`${window.location.origin}/auth?coach_invite=${c}`;navigator.clipboard.writeText(d),se.success("Link copied")},o=async c=>{await Xi("Revoke this invite?")&&(await q.from("coaching_invites").delete().eq("id",c),a())};return e.jsx(ve,{children:e.jsxs(Me,{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(Vc,{className:"h-5 w-5"})," Invite agents"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Generate a magic link to onboard agents directly."})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{placeholder:"agent@email.com",value:t,onChange:c=>n(c.target.value),onKeyDown:c=>c.key==="Enter"&&i()}),e.jsxs(B,{onClick:i,children:[e.jsx(rn,{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(B,{variant:"ghost",size:"icon",onClick:()=>l(c.token),children:e.jsx(Ia,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>o(c.id),children:e.jsx(Sn,{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 jOs="google_calendar";function NOs(){const[s,t]=_.useState("Finishing your Google Calendar connection…"),n=_.useRef(!1);return _.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:jOs,reason:h},window.location.origin),u==="appUserConnectorOAuthComplete"&&window.close();return}l(u==="appUserConnectorOAuthComplete"?"connected":"failed",h)};if(r.get("success")!=="true"){const u=r.get("error")||"Google did not complete the connection.";t(u),o("appUserConnectorOAuthFailed",u);return}const c=r.get("code");if(!c){const u=r.get("offline_access_allowed")==="false"?"This connection cannot be used yet: a workspace admin must enable offline access on the Google Calendar App User Connector client.":"Google finished, but no exchange code was returned.";t(u),o("appUserConnectorOAuthFailed",u);return}const d=(()=>{try{return sessionStorage.getItem("googleCalendarScope")==="agent"?"agent":"coach"}catch{return"coach"}})();q.functions.invoke(d==="agent"?"agent-google-calendar":"coach-google-calendar",{body:{action:"complete",code:c}}).then(({data:u,error:h})=>{if(h)throw h;if(u!=null&&u.error)throw new Error(u.error);t("Connected! You can close this window."),o("appUserConnectorOAuthComplete")}).catch(u=>{const h=(u==null?void 0:u.message)||"Could not finish the connection.";t(h),o("appUserConnectorOAuthFailed",h)})},[]),e.jsx("div",{className:"min-h-screen flex items-center justify-center p-8 text-center",children:e.jsxs("div",{className:"space-y-3 max-w-sm",children:[e.jsx(Ct,{className:"h-6 w-6 animate-spin mx-auto text-[#406E71]"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:s})]})})}const Ale=[{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 kOs(){const s=Fn(),t=Bt(),{data:n,isLoading:r}=Jre(),[a,i]=_.useState("pending"),[l,o]=_.useState(""),[c,d]=_.useState(null),[u,h]=_.useState(!1),[m,p]=_.useState(""),[f,y]=_.useState(!1),[v,g]=_.useState(""),{data:b=[],isLoading:j}=at({queryKey:["coaching-waitlist",n==null?void 0:n.id],enabled:!!(n!=null&&n.id),queryFn:async()=>{const{data:D,error:O}=await q.from("coaching_waitlist").select("*").eq("coach_id",n.id).order("created_at",{ascending:!1});if(O)throw O;return D||[]}}),S=_.useMemo(()=>b.filter(D=>{if(a!=="all"&&D.status!==a)return!1;if(l){const O=l.toLowerCase();return(D.name||"").toLowerCase().includes(O)||(D.email||"").toLowerCase().includes(O)||(D.brokerage||"").toLowerCase().includes(O)}return!0}),[b,a,l]),C=_.useMemo(()=>{const D={all:b.length};for(const O of Ale)D[O.value]=0;for(const O of b)D[O.status]=(D[O.status]||0)+1;return D},[b]),E=async(D,O)=>{const{error:V}=await q.from("coaching_waitlist").update(O).eq("id",D);if(V)return se.error(V.message);t.invalidateQueries({queryKey:["coaching-waitlist",n==null?void 0:n.id]}),(c==null?void 0:c.id)===D&&d(G=>({...G,...O}))},P=async D=>{if(!await Xi("Remove this person from the waitlist?"))return;const{error:O}=await q.from("coaching_waitlist").delete().eq("id",D);if(O)return se.error(O.message);se.success("Removed"),t.invalidateQueries({queryKey:["coaching-waitlist",n==null?void 0:n.id]}),d(null)},M=async()=>{if(!c)return;const{data:D,error:O}=await q.functions.invoke("coaching-waitlist-invite",{body:{waitlistId:c.id,message:m}});if(O||D!=null&&D.error)return se.error((D==null?void 0:D.error)||(O==null?void 0:O.message)||"Could not send invite");se.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:O}=await q.functions.invoke("coaching-waitlist-invite",{body:{coachId:n.id,notifyAll:!0,message:v}});if(O||D!=null&&D.error)return se.error((D==null?void 0:D.error)||(O==null?void 0:O.message)||"Could not notify");se.success(`Notified ${(D==null?void 0:D.count)||0} agents`),y(!1),g(""),t.invalidateQueries({queryKey:["coaching-waitlist",n==null?void 0:n.id]})};return r?e.jsx(zs,{title:"Waitlist",children:e.jsx("div",{className:"p-8",children:"Loading…"})}):n?e.jsxs(zs,{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(B,{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(qf,{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(B,{variant:"outline",onClick:()=>y(!0),disabled:!C.pending,title:C.pending?"":"No pending applicants",children:[e.jsx(JO,{className:"h-4 w-4 mr-2"}),"Notify all pending (",C.pending||0,")"]})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs("button",{onClick:()=>i("all"),className:`px-3 py-1.5 rounded-full text-sm border ${a==="all"?"bg-[#406E71] text-white border-[#406E71]":"bg-white hover:bg-muted"}`,children:["All (",C.all,")"]}),Ale.map(D=>e.jsxs("button",{onClick:()=>i(D.value),className:`px-3 py-1.5 rounded-full text-sm border ${a===D.value?"bg-[#406E71] text-white border-[#406E71]":"bg-white hover:bg-muted"}`,children:[D.label," (",C[D.value]||0,")"]},D.value))]}),e.jsx(xe,{placeholder:"Search by name, email, brokerage…",value:l,onChange:D=>o(D.target.value),className:"max-w-md"}),j?e.jsx("div",{className:"text-muted-foreground",children:"Loading…"}):S.length===0?e.jsx(ve,{children:e.jsx(Me,{className:"p-10 text-center text-muted-foreground",children:"No entries here yet."})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:S.map(D=>{const O=Ale.find(V=>V.value===D.status);return e.jsx(ve,{className:"cursor-pointer hover:shadow-md transition-shadow",onClick:()=>d(D),children:e.jsxs(Me,{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(Oe,{className:(O==null?void 0:O.tone)||"",children:(O==null?void 0:O.label)||D.status})]}),e.jsxs("div",{className:"flex items-center justify-between mt-3 text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Joined ",Ed(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(Ls,{open:!!c,onOpenChange:D=>!D&&d(null),children:e.jsx(Ps,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:c&&e.jsxs(e.Fragment,{children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:c.name}),e.jsxs(_r,{children:["Joined ",Ed(new Date(c.created_at),{addSuffix:!0})]})]}),e.jsxs("div",{className:"space-y-3 text-sm",children:[e.jsx(qY,{label:"Email",value:c.email}),e.jsx(qY,{label:"Phone",value:c.phone}),e.jsx(qY,{label:"Brokerage",value:c.brokerage}),e.jsx(qY,{label:"Years",value:c.years_in_business}),e.jsx(qY,{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 ",Ed(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(is,{value:c.status,onValueChange:D=>E(c.id,{status:D}),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsx(as,{children:Ale.map(D=>e.jsx(He,{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(Ms,{rows:3,defaultValue:c.coach_notes||"",onBlur:D=>{D.target.value!==(c.coach_notes||"")&&E(c.id,{coach_notes:D.target.value})}})]})]}),e.jsxs(yr,{className:"flex-wrap gap-2",children:[e.jsxs(B,{variant:"outline",className:"text-destructive",onClick:()=>P(c.id),children:[e.jsx(Sn,{className:"h-4 w-4 mr-1"})," Remove"]}),e.jsx(B,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:`mailto:${c.email}`,children:[e.jsx(ln,{className:"h-4 w-4 mr-1"})," Email directly"]})}),e.jsxs(B,{className:"bg-[#406E71] hover:bg-[#2a4c64]",onClick:()=>{p(""),h(!0)},children:[e.jsx(Or,{className:"h-4 w-4 mr-1"})," Invite to subscribe"]})]})]})})}),e.jsx(Ls,{open:u,onOpenChange:h,children:e.jsxs(Ps,{children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Invite to subscribe"}),e.jsxs(_r,{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(Ms,{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(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>h(!1),children:"Cancel"}),e.jsxs(B,{className:"bg-[#406E71] hover:bg-[#2a4c64]",onClick:M,children:[e.jsx(Or,{className:"h-4 w-4 mr-1"})," Send invite"]})]})]})}),e.jsx(Ls,{open:f,onOpenChange:y,children:e.jsxs(Ps,{children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Notify all pending applicants"}),e.jsx(_r,{children:"Send everyone with status “Pending” an email letting them know spots are opening up. They'll each be marked “Invited”."})]}),e.jsx(Ms,{rows:4,placeholder:"Good news — I just opened up new coaching spots…",value:v,onChange:D=>g(D.target.value)}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>y(!1),children:"Cancel"}),e.jsxs(B,{className:"bg-[#406E71] hover:bg-[#2a4c64]",onClick:I,children:[e.jsx(JO,{className:"h-4 w-4 mr-1"})," Send to ",C.pending||0," agents"]})]})]})})]}):e.jsx(zs,{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 qY({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 SOs(){const{data:s=[],isLoading:t}=at({queryKey:["coaches-directory"],queryFn:async()=>{const{data:n,error:r}=await q.from("coaches").select("id, slug, headline, bio, specialties, photo_url, is_certified, accepting_clients, user_id").not("slug","is",null);if(r)throw r;const a=(n||[]).map(o=>o.user_id);if(a.length===0)return[];const{data:i}=await q.from("profiles").select("id, name, avatar_url").in("id",a),l=new Map((i||[]).map(o=>[o.id,o]));return(n||[]).map(o=>({...o,profile:l.get(o.user_id)}))}});return e.jsxs("div",{className:"min-h-screen bg-white",children:[e.jsxs("section",{className:"relative overflow-hidden bg-gradient-to-br from-[#1c3447] via-[#2a4c64] to-[#406E71] text-white",children:[e.jsx("div",{className:"absolute -top-32 -left-24 h-96 w-96 rounded-full bg-[#5a9ea2]/20 blur-3xl"}),e.jsx("div",{className:"absolute -bottom-32 -right-24 h-96 w-96 rounded-full bg-yellow-400/10 blur-3xl"}),e.jsx("div",{className:"absolute inset-0 opacity-[0.04]",style:{backgroundImage:"radial-gradient(white 1px, transparent 1px)",backgroundSize:"22px 22px"}}),e.jsxs("div",{className:"relative max-w-6xl mx-auto px-4 py-20 md:py-28 text-center",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-3 py-1.5 rounded-full bg-white/10 backdrop-blur-sm border border-white/15 text-xs uppercase tracking-[0.18em] font-semibold mb-6",children:[e.jsx(un,{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(Er,{className:"h-4 w-4 text-yellow-300"})," Vetted by LevelUp"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(wl,{className:"h-4 w-4 text-yellow-300"})," Top-producer experience"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Da,{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(ir,{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(un,{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(La,{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(un,{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(Er,{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(Er,{className:"h-4 w-4 text-yellow-300"})," Recurring revenue"]}),e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(Er,{className:"h-4 w-4 text-yellow-300"})," Certified status"]})]})]}),e.jsxs("div",{className:"mt-8 md:mt-0",children:[e.jsxs(ir,{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(La,{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 COs=Bj({name:Zo().trim().min(1,"Name required").max(120),email:Zo().trim().email("Invalid email").max(255),phone:Zo().trim().max(40).optional().or(gx("")),brokerage:Zo().trim().max(160).optional().or(gx("")),years_in_business:Zo().max(40).optional().or(gx("")),biggest_challenge:Zo().trim().max(1e3).optional().or(gx("")),preferred_package:Zo().max(120).optional().or(gx("")),message:Zo().trim().max(1500).optional().or(gx(""))});function AOs({open:s,onOpenChange:t,coachId:n,coachName:r,packages:a=[]}){const{user:i}=hs(),[l,o]=_.useState(!1),[c,d]=_.useState({name:"",email:(i==null?void 0:i.email)||"",phone:"",brokerage:"",years_in_business:"",biggest_challenge:"",preferred_package:"",message:""}),u=(m,p)=>d(f=>({...f,[m]:p})),h=async()=>{var f;const m=COs.safeParse(c);if(!m.success){se.error(((f=m.error.issues[0])==null?void 0:f.message)||"Please check your entries");return}o(!0);const{error:p}=await q.from("coaching_waitlist").insert({coach_id:n,agent_user_id:(i==null?void 0:i.id)||null,name:c.name.trim(),email:c.email.trim().toLowerCase(),phone:c.phone||null,brokerage:c.brokerage||null,years_in_business:c.years_in_business||null,biggest_challenge:c.biggest_challenge||null,preferred_package:c.preferred_package||null,message:c.message||null,status:"pending"});if(o(!1),p){se.error(p.message||"Could not join waitlist");return}se.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(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsxs(Ds,{children:["Join the waitlist",r?` — ${r}`:""]}),e.jsx(_r,{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(J,{children:"Name *"}),e.jsx(xe,{value:c.name,onChange:m=>u("name",m.target.value)})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Email *"}),e.jsx(xe,{type:"email",value:c.email,onChange:m=>u("email",m.target.value)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Phone"}),e.jsx(xe,{value:c.phone,onChange:m=>u("phone",m.target.value)})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Brokerage"}),e.jsx(xe,{value:c.brokerage,onChange:m=>u("brokerage",m.target.value)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Years in business"}),e.jsxs(is,{value:c.years_in_business,onValueChange:m=>u("years_in_business",m),children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Select…"})}),e.jsxs(as,{children:[e.jsx(He,{value:"< 1 year",children:"Less than 1 year"}),e.jsx(He,{value:"1-3 years",children:"1-3 years"}),e.jsx(He,{value:"4-7 years",children:"4-7 years"}),e.jsx(He,{value:"8-15 years",children:"8-15 years"}),e.jsx(He,{value:"15+ years",children:"15+ years"})]})]})]}),a.length>0&&e.jsxs("div",{children:[e.jsx(J,{children:"Preferred package"}),e.jsxs(is,{value:c.preferred_package,onValueChange:m=>u("preferred_package",m),children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Any"})}),e.jsx(as,{children:a.map(m=>e.jsx(He,{value:m.name,children:m.name},m.id))})]})]})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Biggest challenge right now"}),e.jsx(Ms,{rows:2,value:c.biggest_challenge,onChange:m=>u("biggest_challenge",m.target.value)})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Anything else?"}),e.jsx(Ms,{rows:2,value:c.message,onChange:m=>u("message",m.target.value)})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),disabled:l,children:"Cancel"}),e.jsx(B,{className:"bg-[#406E71] hover:bg-[#2a4c64]",onClick:h,disabled:l,children:l?"Submitting…":"Join Waitlist"})]})]})})}function EOs(){var y;const{slug:s}=Li(),t=Fn(),{user:n}=hs(),[r,a]=_.useState(null),[i,l]=_.useState(!1),{data:o,isLoading:c}=at({queryKey:["coach-public",s],enabled:!!s,queryFn:async()=>{const v=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(s||""),g=q.from("coaches").select("*"),{data:b}=v?await g.eq("id",s).maybeSingle():await g.eq("slug",s).maybeSingle();if(!b)return null;const[{data:j},{data:S}]=await Promise.all([q.from("profiles").select("id, name, avatar_url").eq("id",b.user_id).maybeSingle(),q.from("coaching_packages").select("*").eq("coach_id",b.id).eq("is_active",!0).order("sort_order")]);return{coach:b,profile:j,packages:S||[]}}}),d=async v=>{if(!n){se.error("Please sign in to subscribe"),t(`/auth?redirect=/coaches/${s}`);return}a(v);const{data:g,error:b}=await q.functions.invoke("create-coaching-checkout",{body:{packageId:v}});if(a(null),b||g!=null&&g.error){se.error((g==null?void 0:g.error)||(b==null?void 0:b.message)||"Checkout failed");return}g!=null&&g.url&&(window.location.href=g.url)};if(c)return e.jsx("div",{className:"p-12 text-center",children:"Loading…"});if(!(o!=null&&o.coach))return e.jsx("div",{className:"p-12 text-center",children:"Coach not found."});const{coach:u,profile:h,packages:m}=o,p=u,f=(v,g)=>{const b=(v/100).toLocaleString("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0});return g==="one_time"?b:`${b} / ${g}`};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(B,{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(ja,{className:"h-28 w-28 ring-4 ring-white/20",children:[e.jsx(pi,{src:p.photo_url||(h==null?void 0:h.avatar_url)}),e.jsx(Na,{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(un,{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}),((y=p.specialties)==null?void 0:y.length)>0&&e.jsx("div",{className:"flex flex-wrap gap-2 mt-4",children:p.specialties.map(v=>e.jsx(Oe,{className:"bg-white/15 text-white border-white/20",children:v},v))})]})]})]})}),e.jsxs("div",{className:"max-w-5xl mx-auto px-4 py-12 grid grid-cols-1 md:grid-cols-3 gap-8",children:[e.jsxs("div",{className:"md:col-span-2 space-y-6",children:[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(aOs,{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(ve,{children:e.jsx(Me,{className:"p-6 text-sm text-muted-foreground text-center",children:"No packages available yet."})}):m.map(v=>{const g=v.accepting_clients===!1;return e.jsx(ve,{className:`border-2 transition-colors ${g?"border-amber-200 bg-amber-50/30":"hover:border-[#406E71]"}`,children:e.jsxs(Me,{className:"p-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("h3",{className:"font-semibold text-lg",children:v.name}),g&&e.jsx("span",{className:"text-[10px] uppercase tracking-wider font-bold px-2 py-1 rounded-full bg-amber-500 text-white shrink-0",children:"Booked Full"})]}),v.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:v.description}),e.jsx("div",{className:"text-2xl font-bold mt-3",children:f(v.price_cents,v.billing_interval)}),g?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(B,{variant:"outline",className:"w-full",onClick:()=>l(!0),children:[e.jsx(qf,{className:"h-4 w-4 mr-1"})," Join Waitlist"]})]}):e.jsxs(B,{className:"w-full mt-4 bg-[#406E71] hover:bg-[#2a4c64]",onClick:()=>d(v.id),disabled:r===v.id,children:[r===v.id?"Loading…":"Get Started",e.jsx(ea,{className:"h-4 w-4 ml-1"})]})]})},v.id)}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"Secure checkout powered by Stripe."}),e.jsxs(B,{variant:"ghost",size:"sm",className:"w-full text-muted-foreground",onClick:()=>l(!0),children:[e.jsx(qf,{className:"h-4 w-4 mr-1"})," Join the waitlist instead"]})]})]}),e.jsx(AOs,{open:i,onOpenChange:l,coachId:p.id,coachName:h==null?void 0:h.name,packages:m.map(v=>({id:v.id,name:v.name}))})]})}const TOs=Bj({full_name:Zo().trim().min(2,"Please enter your full name").max(100),email:Zo().trim().email("Enter a valid email").max(255),phone:Zo().trim().max(40).optional().or(gx("")),brokerage:Zo().trim().max(150).optional().or(gx("")),years_experience:Zo().trim().max(40).optional().or(gx("")),specialties:Zo().trim().max(500).optional().or(gx("")),why_coach:Zo().trim().min(20,"Tell us a bit more — at least 20 characters").max(2e3),results_story:Zo().trim().max(2e3).optional().or(gx("")),website_url:Zo().trim().max(300).optional().or(gx("")),linkedin_url:Zo().trim().max(300).optional().or(gx(""))});function MOs(){const s=Fn(),[t,n]=_.useState(!1),[r,a]=_.useState(!1),[i,l]=_.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=TOs.safeParse(i);if(!u.success){const p=(m=Object.values(u.error.flatten().fieldErrors)[0])==null?void 0:m[0];return se.error(p||"Please check the form and try again")}n(!0);const{error:h}=await q.from("coach_applications").insert(u.data);if(n(!1),h)return se.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(Er,{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(B,{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(ir,{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(un,{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(In,{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(Nl,{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(Hh,{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(Er,{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(wl,{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(Da,{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(b5,{label:"Full name *",children:e.jsx(xe,{value:i.full_name,onChange:d=>o("full_name",d.target.value),required:!0,maxLength:100})}),e.jsx(b5,{label:"Email *",children:e.jsx(xe,{type:"email",value:i.email,onChange:d=>o("email",d.target.value),required:!0,maxLength:255})}),e.jsx(b5,{label:"Phone",children:e.jsx(xe,{value:i.phone,onChange:d=>o("phone",d.target.value),maxLength:40})}),e.jsx(b5,{label:"Current brokerage",children:e.jsx(xe,{value:i.brokerage,onChange:d=>o("brokerage",d.target.value),maxLength:150})}),e.jsx(b5,{label:"Years in real estate",children:e.jsx(xe,{value:i.years_experience,onChange:d=>o("years_experience",d.target.value),placeholder:"e.g. 8",maxLength:40})}),e.jsx(b5,{label:"Coaching specialties",children:e.jsx(xe,{value:i.specialties,onChange:d=>o("specialties",d.target.value),placeholder:"Lead gen, listings, luxury, teams…",maxLength:500})}),e.jsx(b5,{label:"Website",children:e.jsx(xe,{value:i.website_url,onChange:d=>o("website_url",d.target.value),placeholder:"https://",maxLength:300})}),e.jsx(b5,{label:"LinkedIn",children:e.jsx(xe,{value:i.linkedin_url,onChange:d=>o("linkedin_url",d.target.value),placeholder:"https://linkedin.com/in/",maxLength:300})})]}),e.jsx(b5,{label:"Why do you want to coach with LevelUp? *",children:e.jsx(Ms,{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(b5,{label:"Tell us about results you've created — for yourself or other agents.",children:e.jsx(Ms,{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(B,{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 b5({label:s,children:t}){return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-sm font-semibold text-[#1c3447]",children:s}),t]})}const YJe="/assets/testimonial-avatar-1-BsCQFauB.jpg",ZJe="/assets/testimonial-avatar-2-B6VPVc2t.jpg",XJe="/assets/testimonial-avatar-3-GuEFwYUE.jpg",QJe="/assets/testimonial-avatar-4-98iKMtkB.jpg",JJe="/assets/testimonial-avatar-5-ZsZfyxMX.jpg",POs=[YJe,ZJe,XJe,QJe,JJe],LOs=[{key:"dashboard",label:"Agent Command Center",caption:"Your entire day — smart queue, calendar and pipeline in one view.",src:Qre},{key:"crm",label:"CRM & Contact Hub",caption:"Contacts, tags, follow-ups and deal history, always one click away.",src:UPe},{key:"pipeline",label:"Deal Pipeline",caption:"Every active deal with tasks, forms and commission tracking built in.",src:qPe},{key:"staging",label:"Staging Studio",caption:"AI photo staging — MLS-ready before/afters in minutes.",src:$Pe},{key:"coaching",label:"Coaching",caption:"Book live coaching sessions with Google Meet created automatically.",src:VPe},{key:"marketing",label:"Marketing Studio",caption:"Templates, social posts, reels and print — all branded to you.",src:HPe}];function IOs({slot:s}){return e.jsxs("figure",{className:"rounded-2xl overflow-hidden border border-white/10 bg-white/5 backdrop-blur-sm shadow-2xl",children:[e.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-2 border-b border-white/10",children:[e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-red-400/80"}),e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-amber-400/80"}),e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-green-400/80"}),e.jsx("span",{className:"ml-3 text-[11px] rounded px-2 py-0.5 bg-white/10 text-white/70",children:"dashboard.relevelup.com"})]}),s.src?e.jsx("img",{src:s.src,alt:`LevelUp ${s.label} screenshot`,className:"w-full h-auto block",loading:"lazy"}):e.jsxs("div",{className:"w-full aspect-[16/10] flex flex-col items-center justify-center gap-3 bg-white/5",children:[e.jsx(un,{className:"h-8 w-8 text-white/40"}),e.jsx("p",{className:"text-sm font-medium text-white/60",children:s.label})]}),e.jsxs("figcaption",{className:"px-4 py-3 text-sm text-white/80",children:[e.jsx("span",{className:"font-semibold text-white",children:s.label})," — ",s.caption]})]})}const DOs=Bj({name:Zo().trim().min(2,"Name must be at least 2 characters").max(100),email:Zo().trim().email("Please enter a valid email address").max(255),phone:Zo().trim().min(10,"Please enter a valid phone number").max(20).optional().or(gx("")),brokerage:Zo().trim().max(200).optional().or(gx(""))}),ROs=[{icon:om,title:"Academy Training",description:"Access a library of on-demand video training covering lead generation, marketing, technology, and more."},{icon:Xc,title:"300+ Templates",description:"Professional Canva templates for social media, flyers, postcards, and marketing materials."},{icon:ga,title:"Live Events",description:"Weekly live training sessions, workshops, and Q&A events with industry experts."},{icon:Ou,title:"Agent Community",description:"Connect with fellow agents, share wins, ask questions, and network in our private community."},{icon:Fr,title:"Resource Kits",description:"Downloadable toolkits with scripts, checklists, guides, and everything you need to close more deals."},{icon:Vo,title:"Social Swag",description:"Fresh social media content and designs updated regularly to help you stand out online."}],FOs=[{category:"Marketing Studio",icon:wh,items:["Weekly Reels scripts","Social Post Generator","300+ Canva templates","Marketing Calendar","Postcard Direct Mail","Listing Music Videos","Social Swag drops"]},{category:"Lead Generation",icon:ku,items:["Custom lead websites","Open House Guest Book","RSVP pages","Resource landing pages","Listing Revival™","FSBO Breakthrough","Attract system"]},{category:"CRM & Deals",icon:Ny,items:["Agent OS CRM","Deal pipeline","Forms & e-signatures","Client portal","Smart follow-up queue","Lead ponds for teams","Google Business reviews"]},{category:"AI & Media",icon:Qx,items:["AI Staging Studio","Video library & sharing","Screen recording","Virtual backgrounds","AI blog writer","YouTube → Blog","Ask AI assistant"]},{category:"Growth & Coaching",icon:mm,items:["Academy courses","Live weekly coaching","Coaching programs","1:1 coaching booking","Private community","Live events & workshops"]},{category:"Brokerage Tools",icon:ai,items:["Manager dashboard","Team analytics","Agent onboarding","Office form libraries","Listing Exchange","Brand kits","Recruiting pipeline"]}],OOs=[{icon:In,title:"Contact Management",description:"Organize your sphere into relationship tiers—Top 25, Past Clients, Referral Partners, and more."},{icon:un,title:"Smart TouchPlans",description:"Automated action plans that tell you exactly who to contact and how, based on relationship type."},{icon:_a,title:"One-Tap Actions",description:"Call, text, or email contacts directly with pre-written scripts tailored to each relationship."},{icon:Bf,title:"Birthday Alerts",description:"Never miss an important date—get reminders for birthdays and home anniversaries."},{icon:Xa,title:"Pop-by Map",description:"See all your contacts on a map and plan efficient pop-by routes in your area."},{icon:bl,title:"Momentum Tracking",description:"Track your touch streaks, weekly goals, and relationship health scores."},{icon:Do,title:"Relationship Health",description:"Visual dashboard showing which contacts need attention based on last touch date."},{icon:nf,title:"Daily Action Cards",description:"Wake up to a prioritized list of exactly who to reach out to today."}],zOs=[{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."}],Ele="bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]",BOs=()=>{const s=Fn(),[t,n]=_.useState(!1),[r,a]=_.useState({name:"",email:"",phone:"",brokerage:""}),[i,l]=_.useState({}),o=async d=>{var h,m;d.preventDefault(),l({});const u=DOs.safeParse(r);if(!u.success){const p={};u.error.issues.forEach(f=>{f.path[0]&&(p[f.path[0]]=f.message)}),l(p);return}n(!0);try{const p=typeof window<"u"&&localStorage.getItem("levelup_referral_code")||void 0,{data:f,error:y}=await q.functions.invoke("create-trial-signup",{body:{name:r.name.trim(),email:r.email.trim().toLowerCase(),phone:((h=r.phone)==null?void 0:h.trim())||void 0,brokerage:((m=r.brokerage)==null?void 0:m.trim())||void 0,referral_code:p}});if(y){console.error("Trial signup error:",y),se.error(y.message||"Something went wrong. Please try again.");return}if(f!=null&&f.error){se.error(f.error);return}se.success("🎉 Welcome aboard! Check your email to claim your account."),typeof window<"u"&&window.oaiq&&window.oaiq("measure","trial_started",{type:"plan_enrollment"}),typeof window<"u"&&window.fbq&&window.fbq("track","Lead",{content_name:"Trial Signup",value:0,currency:"USD"}),s("/trial/success")}catch(p){console.error("Trial signup error:",p),se.error("Something went wrong. Please try again.")}finally{n(!1)}},c=()=>{var d;(d=document.getElementById("trial-form"))==null||d.scrollIntoView({behavior:"smooth",block:"center"})};return e.jsxs(e.Fragment,{children:[e.jsxs(ul,{children:[e.jsx("title",{children:"LevelUp — Start Your Free Trial | Real Growth. Real Tools. Real Results."}),e.jsx("meta",{name:"description",content:"Try LevelUp free — the all-in-one platform for real estate agents: coaching, done-for-you marketing, CRM, lead sites, social studio, and 40+ tools built to help you scale."}),e.jsx("link",{rel:"canonical",href:"https://dashboard.relevelup.com/trial"}),e.jsx("meta",{property:"og:title",content:"LevelUp — Start Your Free Trial | Real Growth. Real Tools. Real Results."}),e.jsx("meta",{property:"og:description",content:"Try LevelUp free — coaching, done-for-you marketing, CRM, lead sites, social studio, and 40+ tools built to help you scale."}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:url",content:"https://dashboard.relevelup.com/trial"}),e.jsx("meta",{property:"og:image",content:"https://relzejiswnotikjgvjhz.supabase.co/storage/v1/object/public/email-assets/trial-og.png"}),e.jsx("meta",{property:"og:image:width",content:"1200"}),e.jsx("meta",{property:"og:image:height",content:"630"}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),e.jsx("meta",{name:"twitter:image",content:"https://relzejiswnotikjgvjhz.supabase.co/storage/v1/object/public/email-assets/trial-og.png"}),e.jsx("script",{children:"!function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod?n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0;t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window,document,'script','https://connect.facebook.net/en_US/fbevents.js'); fbq('init', '1388750291887997'); fbq('track', 'PageView');"})]}),e.jsx("noscript",{dangerouslySetInnerHTML:{__html:''}}),e.jsxs("div",{className:"min-h-screen bg-background overflow-hidden",children:[e.jsx("style",{children:` @keyframes hero-float { 0%,100% { transform: translateY(0px); } 50% { transform: translateY(-12px); } } @keyframes hero-glow { 0%,100% { opacity: 0.55; } 50% { opacity: 0.9; } } `}),e.jsx("nav",{className:"fixed top-0 left-0 right-0 z-50 bg-[#4a6b6d] shadow-md",children:e.jsxs("div",{className:"container mx-auto px-4 py-3 flex items-center justify-between",children:[e.jsx("div",{className:"flex items-center",children:e.jsx("img",{src:kAe,alt:"LevelUp",className:"h-8 md:h-10"})}),e.jsxs("div",{className:"flex items-center gap-2 md:gap-4",children:[e.jsx(B,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>{var d;return(d=document.getElementById("features"))==null?void 0:d.scrollIntoView({behavior:"smooth"})},children:"Features"}),e.jsx(B,{onClick:()=>s("/auth"),className:"bg-white text-[#4a6b6d] hover:bg-gray-100 font-medium shadow-md",children:"Sign In"})]})]})}),e.jsxs("section",{className:"relative overflow-hidden bg-[#0f2530]",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-b from-[#122c3a] via-[#16384a] to-[#0f2530]"}),e.jsx("div",{className:"absolute -top-40 left-1/2 -translate-x-1/2 h-[560px] w-[900px] rounded-full bg-[#4aa8a0]/25 blur-[140px] animate-[hero-glow_7s_ease-in-out_infinite]"}),e.jsx("div",{className:"absolute top-1/3 -left-40 h-[420px] w-[420px] rounded-full bg-[#2a6f8a]/20 blur-[120px]"}),e.jsx("div",{className:"absolute top-1/4 -right-40 h-[420px] w-[420px] rounded-full bg-[#c9a84c]/10 blur-[120px]"}),e.jsx("div",{className:"absolute inset-0 opacity-[0.12] bg-[linear-gradient(to_right,rgba(255,255,255,0.5)_1px,transparent_1px),linear-gradient(to_bottom,rgba(255,255,255,0.5)_1px,transparent_1px)] bg-[size:56px_56px] [mask-image:radial-gradient(ellipse_75%_65%_at_50%_35%,black,transparent)]"}),e.jsx("div",{className:"absolute inset-x-0 bottom-0 h-40 bg-gradient-to-t from-[#0f2530] to-transparent"}),e.jsx("div",{className:"container mx-auto px-4 relative",children:e.jsxs("div",{className:"grid lg:grid-cols-2 gap-12 items-center pt-28 md:pt-36 pb-20 md:pb-28",children:[e.jsxs("div",{className:"space-y-8 text-center lg:text-left",children:[e.jsx("div",{className:"flex justify-center lg:justify-start animate-fade-in",children:e.jsxs("span",{className:"inline-flex items-center gap-2 rounded-full border border-white/15 bg-white/5 backdrop-blur-sm px-4 py-1.5 text-xs md:text-sm font-semibold tracking-wide text-white/85 shadow-lg",children:[e.jsx(un,{className:"h-3.5 w-3.5 text-[#7fd4cc]"}),"7-Day Free Trial • No Credit Card Required"]})}),e.jsxs("h1",{className:"text-4xl sm:text-5xl md:text-6xl font-sans font-bold tracking-tight text-white leading-[1.05] animate-fade-in",children:["Take LevelUp for a"," ",e.jsx("span",{className:"bg-gradient-to-r from-[#8fe0d6] via-[#5cc0b6] to-[#e6c878] bg-clip-text text-transparent italic",children:"Free Test Drive"})]}),e.jsx("p",{className:"text-base md:text-xl text-white/65 max-w-xl mx-auto lg:mx-0 leading-relaxed animate-fade-in",children:"Weekly coaching, a smart CRM, done-for-you marketing and AI tools — everything a modern agent runs on, in one login."}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center lg:justify-start animate-fade-in",children:[e.jsxs("div",{className:"flex items-center gap-2 text-white/80",children:[e.jsx(Er,{className:"h-5 w-5 text-[#7fd4cc]"}),e.jsx("span",{children:"No credit card required"})]}),e.jsxs("div",{className:"flex items-center gap-2 text-white/80",children:[e.jsx(Er,{className:"h-5 w-5 text-[#7fd4cc]"}),e.jsx("span",{children:"Full access to all features"})]})]}),e.jsxs("div",{className:"flex items-center gap-4 justify-center lg:justify-start pt-2 animate-fade-in",children:[e.jsx("div",{className:"flex -space-x-3",children:POs.map((d,u)=>e.jsx("img",{src:d,alt:`Agent ${u+1}`,className:"w-10 h-10 rounded-full border-2 border-white/20 object-cover"},u))}),e.jsxs("div",{children:[e.jsx("div",{className:"flex gap-0.5",children:[1,2,3,4,5].map(d=>e.jsx(Da,{className:"h-4 w-4 fill-[#e6c878] text-[#e6c878]"},d))}),e.jsx("p",{className:"text-sm text-white/60",children:"Trusted by 3,000+ agents"})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-center lg:justify-start gap-x-6 gap-y-2 text-sm text-white/50 animate-fade-in",children:[e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(Rm,{className:"h-4 w-4 text-white/60"})," Cancel anytime"]}),e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(nf,{className:"h-4 w-4 text-[#7fd4cc]"})," Set up in 2 minutes"]})]})]}),e.jsxs("div",{id:"trial-form",className:"lg:pl-8 relative",children:[e.jsx("div",{className:"absolute -inset-6 rounded-[32px] bg-[#4aa8a0]/20 blur-2xl","aria-hidden":!0}),e.jsx(ve,{className:"relative bg-white shadow-[0_40px_80px_-20px_rgba(0,0,0,0.7)] border-0 animate-[hero-float_7s_ease-in-out_infinite]",children:e.jsxs(Me,{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(Sy,{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(J,{htmlFor:"name",children:"Full Name *"}),e.jsx(xe,{id:"name",type:"text",placeholder:"John Smith",value:r.name,onChange:d=>a({...r,name:d.target.value}),required:!0}),i.name&&e.jsx("p",{className:"text-sm text-destructive",children:i.name})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"email",children:"Email Address *"}),e.jsx(xe,{id:"email",type:"email",placeholder:"john@example.com",value:r.email,onChange:d=>a({...r,email:d.target.value}),required:!0}),i.email&&e.jsx("p",{className:"text-sm text-destructive",children:i.email})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"phone",children:"Phone Number"}),e.jsx(xe,{id:"phone",type:"tel",placeholder:"(555) 123-4567",value:r.phone,onChange:d=>a({...r,phone:d.target.value})}),i.phone&&e.jsx("p",{className:"text-sm text-destructive",children:i.phone})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"brokerage",children:"Brokerage Name"}),e.jsx(xe,{id:"brokerage",type:"text",placeholder:"Your brokerage or team name",value:r.brokerage,onChange:d=>a({...r,brokerage:d.target.value})}),i.brokerage&&e.jsx("p",{className:"text-sm text-destructive",children:i.brokerage})]}),e.jsx(B,{type:"submit",className:"w-full h-12 text-lg font-semibold bg-[#4a6b6d] hover:bg-[#3d5a5c]",disabled:t,children:t?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"mr-2 h-5 w-5 animate-spin"}),"Creating Your Account..."]}):e.jsxs(e.Fragment,{children:["Start My Free Trial",e.jsx(La,{className:"ml-2 h-5 w-5"})]})}),e.jsxs("p",{className:"text-center text-sm text-muted-foreground",children:["By signing up, you agree to our"," ",e.jsx("a",{href:"/terms-of-service",className:"text-[#4a6b6d] hover:underline",children:"Terms"})," ","and"," ",e.jsx("a",{href:"/privacy-policy",className:"text-[#4a6b6d] hover:underline",children:"Privacy Policy"})]})]})]})})]})]})})]}),e.jsx("section",{className:"py-20 bg-background",children:e.jsx("div",{className:"container mx-auto px-4",children:e.jsxs("div",{className:"max-w-4xl mx-auto text-center space-y-8",children:[e.jsx("h2",{className:"text-3xl md:text-5xl leading-tight font-sans font-semibold text-secondary",children:"We help brokerages and agents grow with training, tools, and built-in execution."}),e.jsxs("div",{className:"space-y-2 text-lg text-muted-foreground",children:[e.jsx("p",{children:"Agents get weekly coaching + plug-and-play marketing."}),e.jsx("p",{children:"Brokerages get higher adoption, consistency, and real engagement."})]}),e.jsx("p",{className:"text-2xl md:text-4xl text-[#4a6b6d] pt-4 font-sans font-bold",children:"LEVELUP EQUIPS BOTH TO THRIVE."})]})})}),e.jsxs("section",{className:"py-20 bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:`absolute inset-0 ${Ele}`})}),e.jsxs("div",{className:"container mx-auto px-4 relative",children:[e.jsxs("div",{className:"text-center max-w-3xl mx-auto mb-14",children:[e.jsx("span",{className:"text-sm font-semibold tracking-[0.15em] uppercase text-white/70",children:"See it in action"}),e.jsx("h2",{className:"text-3xl md:text-5xl font-bold text-white mt-4 tracking-tight font-sans",children:"A real platform, not another course"}),e.jsx("p",{className:"text-white/60 mt-4 max-w-2xl mx-auto text-lg",children:"This is what you'll open on day one of your trial."})]}),e.jsx("div",{className:"grid md:grid-cols-2 gap-8 md:gap-10 max-w-6xl mx-auto",children:LOs.map(d=>e.jsx(IOs,{slot:d},d.key))}),e.jsx("div",{className:"text-center mt-12",children:e.jsxs(B,{size:"lg",onClick:c,className:"px-8 py-7 text-lg font-semibold bg-white text-[#122c3a] hover:bg-white/90 shadow-2xl transition-all hover:scale-105 rounded-full",children:["Try It Free for 7 Days",e.jsx(La,{className:"ml-2 w-5 h-5"})]})})]})]}),e.jsx("section",{id:"features",className:"py-20 bg-muted/30",children:e.jsxs("div",{className:"container mx-auto px-4",children:[e.jsxs("div",{className:"text-center max-w-3xl mx-auto mb-16",children:[e.jsxs("span",{className:"inline-flex items-center gap-2 px-4 py-1.5 rounded-full bg-[#4a6b6d]/10 text-[#4a6b6d] text-sm font-semibold mb-5",children:[e.jsx(G4,{className:"w-4 h-4"}),"40+ tools & counting"]}),e.jsx("h2",{className:"text-3xl md:text-4xl mb-6 font-sans font-bold",children:"What's inside our members only portal?"}),e.jsx("p",{className:"text-lg text-muted-foreground",children:"Everything you need to grow your business, all in one place."})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8 max-w-6xl mx-auto",children:ROs.map((d,u)=>e.jsxs(ve,{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(d.icon,{className:"w-7 h-7 text-[#4a6b6d]"})}),e.jsx(St,{className:"text-xl font-sans",children:d.title})]}),e.jsx(Me,{children:e.jsx("p",{className:"text-muted-foreground leading-relaxed",children:d.description})})]},u))}),e.jsxs("div",{className:"mt-14 max-w-6xl mx-auto rounded-3xl bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] p-8 md:p-12 relative overflow-hidden shadow-2xl",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:`absolute inset-0 ${Ele}`})}),e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"text-center mb-10",children:[e.jsx("h3",{className:"text-2xl md:text-3xl font-bold text-white font-sans",children:"...and that's just the beginning"}),e.jsx("p",{className:"text-white/60 mt-2",children:"Dozens of purpose-built tools — all included in your free trial."})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-x-10 gap-y-8",children:FOs.map(d=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2.5 mb-4",children:[e.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-white/10",children:e.jsx(d.icon,{className:"h-4 w-4 text-white"})}),e.jsx("span",{className:"text-sm font-bold uppercase tracking-wider text-white/90",children:d.category})]}),e.jsx("ul",{className:"space-y-2.5",children:d.items.map(u=>e.jsxs("li",{className:"flex items-center gap-2.5 text-white/70 text-sm",children:[e.jsx(ea,{className:"h-3.5 w-3.5 text-emerald-300 shrink-0"}),u]},u))})]},d.category))}),e.jsxs("p",{className:"text-center text-white/50 text-sm mt-10 flex items-center justify-center gap-2",children:[e.jsx(un,{className:"h-4 w-4"}),"New tools added every month — membership keeps getting more valuable."]})]})]})]})}),e.jsxs("section",{className:"py-20 bg-gradient-to-br from-[#4a6b6d] to-[#3d5a5c] relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:`absolute inset-0 ${Ele}`})}),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(un,{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:OOs.map((d,u)=>e.jsxs(ve,{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(d.icon,{className:"w-6 h-6 text-white"})}),e.jsx(St,{className:"text-lg font-semibold text-white",children:d.title})]}),e.jsx(Me,{children:e.jsx("p",{className:"text-white/70 text-sm leading-relaxed",children:d.description})})]},u))})]})]}),e.jsx("section",{className:"py-20 bg-background",children:e.jsxs("div",{className:"container mx-auto px-4",children:[e.jsxs("div",{className:"text-center mb-16",children:[e.jsx("h2",{className:"text-3xl md:text-4xl font-bold mb-4 font-sans",children:"Loved by Top Producers"}),e.jsx("p",{className:"text-lg text-muted-foreground",children:"See what agents are saying about LevelUp"})]}),e.jsx("div",{className:"grid md:grid-cols-3 gap-8 max-w-5xl mx-auto",children:zOs.map((d,u)=>e.jsx(ve,{className:"border hover:shadow-lg transition-shadow",children:e.jsxs(Me,{className:"p-6",children:[e.jsx("div",{className:"flex gap-1 mb-4",children:[1,2,3,4,5].map(h=>e.jsx(Da,{className:"h-4 w-4 fill-yellow-400 text-yellow-400"},h))}),e.jsxs("p",{className:"text-muted-foreground mb-4 italic",children:['"',d.quote,'"']}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:d.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:d.role})]})]})},u))})]})}),e.jsx("section",{className:"py-16 bg-muted/30",children:e.jsx("div",{className:"container mx-auto px-4",children:e.jsxs("div",{className:"flex flex-wrap justify-center gap-8 md:gap-16",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-[#4a6b6d]/10 flex items-center justify-center",children:e.jsx(Rm,{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(nf,{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(In,{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(ve,{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 ${Ele}`})}),e.jsxs(Me,{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(B,{onClick:c,size:"lg",className:"h-14 px-8 text-lg font-semibold bg-white text-[#1e3a4c] hover:bg-white/90 shadow-2xl transition-all hover:scale-105 rounded-full",children:["Start Your Free Trial Now",e.jsx(La,{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:TH,alt:"LevelUp",className:"h-8"}),e.jsxs("div",{className:"flex gap-6 text-sm text-white/60",children:[e.jsx("a",{href:"/privacy-policy",className:"hover:text-white transition-colors",children:"Privacy Policy"}),e.jsx("a",{href:"/terms-of-service",className:"hover:text-white transition-colors",children:"Terms of Service"})]}),e.jsx("p",{className:"text-sm text-white/40",children:"© 2026 LevelUp Consulting Group. All rights reserved."})]})})})]})]})},UOs=()=>{const s=Fn();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:kAe,alt:"LevelUp",className:"h-8 md:h-10"})}),e.jsx(B,{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(ve,{className:"max-w-lg w-full bg-white shadow-2xl border-0",children:e.jsxs(Me,{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(Er,{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(Ex,{className:"h-5 w-5 text-white"})})]}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold text-foreground mb-4 font-sans",children:"You're In! 🎉"}),e.jsx("p",{className:"text-xl text-muted-foreground mb-8",children:"Your 7-day LevelUp adventure starts now!"}),e.jsxs("div",{className:"bg-[#4a6b6d]/10 rounded-xl p-6 mb-8",children:[e.jsxs("div",{className:"flex items-center justify-center gap-3 mb-4",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-[#4a6b6d]/20 flex items-center justify-center",children:e.jsx(ln,{className:"h-6 w-6 text-[#4a6b6d]"})}),e.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"Check Your Inbox"})]}),e.jsx("p",{className:"text-muted-foreground",children:"We just sent you a magic link to claim your account and set up your password. Click the link in your email to get started!"})]}),e.jsxs("div",{className:"text-left space-y-3 mb-8",children:[e.jsx("p",{className:"text-sm text-muted-foreground font-medium uppercase tracking-wide",children:"What happens next:"}),e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-[#4a6b6d] flex items-center justify-center flex-shrink-0 mt-0.5",children:e.jsx("span",{className:"text-xs font-bold text-white",children:"1"})}),e.jsx("p",{className:"text-foreground",children:"Check your email for the welcome message"})]}),e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-[#4a6b6d] flex items-center justify-center flex-shrink-0 mt-0.5",children:e.jsx("span",{className:"text-xs font-bold text-white",children:"2"})}),e.jsx("p",{className:"text-foreground",children:'Click "Claim Your Account" to set your password'})]}),e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-[#4a6b6d] flex items-center justify-center flex-shrink-0 mt-0.5",children:e.jsx("span",{className:"text-xs font-bold text-white",children:"3"})}),e.jsx("p",{className:"text-foreground",children:"Start exploring all the features!"})]})]}),e.jsxs("p",{className:"text-sm text-muted-foreground mb-6",children:["Didn't receive the email? Check your spam folder or"," ",e.jsx("button",{onClick:()=>s("/trial"),className:"text-[#4a6b6d] hover:underline font-medium",children:"try again"})]}),e.jsxs(B,{onClick:()=>s("/auth"),className:"bg-[#4a6b6d] hover:bg-[#3d5a5c]",children:["Go to Sign In",e.jsx(La,{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:TH,alt:"LevelUp",className:"h-8"}),e.jsxs("p",{className:"text-sm text-white/40",children:["© ",new Date().getFullYear()," LevelUp Consulting Group. All rights reserved."]})]})})})]})]})},qOs="https://us06web.zoom.us/meeting/register/7Ybq3ZIkRn2_RLkkv_uY8A",Tle="ld-open-house-invite-dismissed";function f9t({pageKey:s,headline:t="Not ready to join the LevelUp family yet?",delayMs:n=15e3}){const[r,a]=_.useState(!1);_.useEffect(()=>{if(localStorage.getItem(`${Tle}-${s}`))return;let o=null;const c=d=>{d.clientY<=0&&!localStorage.getItem(`${Tle}-${s}`)&&a(!0)};return o=setTimeout(()=>{localStorage.getItem(`${Tle}-${s}`)||a(!0)},n),document.addEventListener("mouseleave",c),()=>{o&&clearTimeout(o),document.removeEventListener("mouseleave",c)}},[s,n]);const i=()=>{a(!1),localStorage.setItem(`${Tle}-${s}`,"1")};return e.jsx(Ls,{open:r,onOpenChange:l=>!l&&i(),children:e.jsx(Ps,{className:"laborday-theme max-w-md border-0 p-0 overflow-hidden bg-transparent",overlayClassName:"bg-black/70 backdrop-blur-sm",children:e.jsxs("div",{className:"relative text-white",style:{background:"linear-gradient(150deg, hsl(var(--ld-navy)) 0%, hsl(var(--ld-navy-deep)) 100%)"},children:[e.jsx("div",{className:"h-2 w-full",style:{background:"repeating-linear-gradient(90deg, hsl(var(--ld-red)) 0px, hsl(var(--ld-red)) 24px, hsl(var(--ld-cream)) 24px, hsl(var(--ld-cream)) 48px, hsl(var(--ld-navy)) 48px, hsl(var(--ld-navy)) 72px)"}}),e.jsx("button",{onClick:i,className:"absolute right-3 top-5 rounded-full p-1.5 text-white/70 hover:bg-white/10 hover:text-white transition-colors","aria-label":"Close",children:e.jsx(Qn,{className:"h-4 w-4"})}),e.jsxs("div",{className:"p-6 pt-8 text-center",children:[e.jsx("div",{className:"mx-auto mb-4 flex h-14 w-14 items-center justify-center rounded-full bg-white/10 ring-1 ring-white/20",children:e.jsx(Kr,{className:"h-6 w-6 ld-gold-text"})}),e.jsxs(Os,{children:[e.jsx(Ds,{className:"text-xl font-bold leading-tight text-white",children:t}),e.jsxs(_r,{className:"text-white/80 mt-3 text-sm leading-relaxed",children:["Join us for our next"," ",e.jsx("span",{className:"font-semibold ld-gold-text",children:"LevelUp Live Open House"})," ","and get an inside look at our agent growth platform."]})]}),e.jsxs("div",{className:"mt-5 inline-flex items-center gap-2 rounded-full bg-white/10 px-4 py-2 text-sm font-medium text-white ring-1 ring-white/15",children:[e.jsx(ga,{className:"h-4 w-4 ld-gold-text"}),"Every Friday at 1:00 PM ET"]}),e.jsxs("div",{className:"mt-6 flex flex-col gap-3",children:[e.jsx(B,{asChild:!0,size:"lg",className:"w-full bg-accent text-accent-foreground hover:bg-accent/90 font-bold",children:e.jsxs("a",{href:qOs,target:"_blank",rel:"noreferrer",className:"gap-2",children:["Register for the Open House",e.jsx(wr,{className:"h-4 w-4"})]})}),e.jsx(B,{variant:"ghost",onClick:i,className:"w-full text-white/70 hover:bg-white/10 hover:text-white",children:"Maybe later"})]}),e.jsx("p",{className:"mt-4 text-xs text-white/50",children:"No pressure — you can always come back to this offer."})]})]})})})}const x9t=Date.UTC(2026,8,12,3,59,59),QOe="Friday, September 11 at 11:59 PM ET",JOe=300,Mle=39*12,$Os=[{key:"dashboard",label:"Agent Command Center",caption:"Your entire day — smart queue, calendar and pipeline in one view.",src:Qre},{key:"crm",label:"CRM & Contact Hub",caption:"Contacts, tags, follow-ups and deal history, always one click away.",src:UPe},{key:"pipeline",label:"Deal Pipeline",caption:"Every active deal with tasks, forms and commission tracking built in.",src:qPe},{key:"staging",label:"Staging Studio",caption:"AI photo staging — MLS-ready before/afters in minutes.",src:$Pe},{key:"coaching",label:"Coaching",caption:"Book live coaching sessions with Google Meet created automatically.",src:VPe},{key:"marketing",label:"Marketing Studio",caption:"Templates, social posts, reels and print — all branded to you.",src:HPe}],VOs=[{name:"Valerie Harp",meta:"Local Guide · Real Estate Agent",when:"4 months ago",text:"Level Up has been an absolute game changer for my real estate business. The platform is incredibly easy to use and by far one of the most user-friendly systems I've worked with. Everything is streamlined, intuitive, and designed with agents in mind."},{name:"Robert Larente",meta:"Real Estate Agent",when:"5 months ago",text:"I'm fortunate that my Broker started providing LevelUp membership a few years ago. Originally I used it for kvCore/Bold CRM training. But with the amazing amount of resources that Jeremy and his crew keep adding, I'm quickly canceling my subscriptions to other service providers."},{name:"Tom Lois",meta:"Real Estate Agent",when:"5 months ago",text:"Jeremy and his team at LevelUp continue to upgrade, update, and uplift agents with their meaningful content and insight. Whether you're a newbie or a seasoned agent, this program is for you! Try it — you'll REALLY like it!"},{name:"Michael Smith",meta:"Local Guide · Real Estate Agent",when:"7 months ago",text:"Great value in the material, ideas, etc. shared by the LevelUp team. They consistently provide implementable examples of ways to impact your real estate business. Not just theory, but real ideas/tasks that can be quickly implemented."},{name:"Pamela Nichols",meta:"Local Guide · Real Estate Agent",when:"4 months ago",text:"I'm loving this platform and all the excellent quick and easy information to use! It has been the easiest thing I've ever used to care for my database! I love the quick videos — quick and to the point!"},{name:"Tracy VanderWall",meta:"Local Guide · Broker/Owner",when:"7 months ago",text:"Best investment my brokerage has made! The value of this platform is AMAZING! The entire LEVELUP Team is wonderful!"},{name:"Bill Burns",meta:"Local Guide · Broker",when:"5 months ago",text:"Jeremy and his team are amazing! Level Up can next level your brokerage!"},{name:"Anissa, REMAX Executives",meta:"Real Estate Agent",when:"6 months ago",text:"So far this has helped me tremendously! Keeps me more organized and motivated to stay on top of these leads that get lost in the daily mix."}],HOs="https://www.google.com/search?q=levelup+consulting+group#lrd=0x8842f50045c4bd33:0xc9b99b5330a91b3f,1,,,,",g9t=[{icon:In,title:"1:1 & Group Coaching",desc:"Book live coaching sessions with Jeremy and the LevelUp team — Google Meet created automatically, tracked on your calendar.",value:1200},{icon:p7,title:"Full CRM & Contact Hub",desc:"Contacts, tags, smart follow-ups, lead ponds and team assignments — your database finally organized.",value:600},{icon:wv,title:"Deal Pipeline",desc:"Track every transaction from offer to closing with tasks, forms and commission math built in.",value:480},{icon:cg,title:"Staging Studio",desc:"AI virtual staging with MLS-ready before/after photos — no photographer or stager needed.",value:1200},{icon:Xc,title:"Marketing & Social Studio",desc:"300+ branded templates, social posts, postcards and the weekly Reels engine.",value:720},{icon:sl,title:"Lead Sites",desc:"SEO-optimized neighborhood and listing websites that rank on Google and capture leads 24/7.",value:960},{icon:mm,title:"Academy Training",desc:"On-demand video training on lead gen, marketing and tech — live weekly sessions too.",value:588},{icon:lb,title:"Forms & E-Signature",desc:"Upload any PDF, map fields, send for signature — done from one place.",value:300},{icon:Kr,title:"Weekly Reels & Video Tools",desc:"Personalized Instagram scripts delivered every Monday, plus screen recording and virtual backgrounds.",value:468},{icon:Hi,title:"Reviews Engine",desc:"Collect Google and video reviews with a single link — your reputation on autopilot.",value:240},{icon:un,title:"ChatGPT App + 30 AI Tools",desc:"Your entire business controllable from ChatGPT — create contacts, open houses, marketing assets and more.",value:500},{icon:ga,title:"My Calendar & Booking",desc:"Agent-first calendar with time zones, Google Calendar sync and self-serve booking links.",value:144}],Hxt=g9t.reduce((s,t)=>s+t.value,0),GOs=[{q:"What happens after the first year?",a:"Your rate is locked in. As long as your subscription stays active, you renew at $300/year — forever. No surprises, no bump to the regular price."},{q:"Is this the full platform or a stripped-down version?",a:"The full platform. Everything an Individual Agent member gets: coaching, CRM, deal pipeline, Staging Studio, Marketing Studio, lead sites, Academy, forms with e-signature, reviews, Weekly Reels, Listing Exchange and the ChatGPT app."},{q:"How do I manage or cancel my subscription?",a:"Right from your profile. Your billing lives in your LevelUp account settings with a Stripe customer portal — change cards, see invoices or cancel anytime without calling anyone."},{q:"Is there a free trial with this offer?",a:"No trial on this one — you're charged $300 today and get a full 12 months. That's how we're able to offer the lowest rate we've ever run."},{q:"I'm already a monthly member. Can I switch?",a:"Yes — use the button with the same email on your account and Stripe will match you. If anything looks off after checkout, reach out and we'll sort it immediately."},{q:"Who is LevelUp for?",a:"Solo agents and team agents who want one system for their database, marketing, deals and growth coaching — whether you're brand new or a seasoned producer."}];function y9t(s){const[t,n]=_.useState(()=>Date.now());_.useEffect(()=>{const i=setInterval(()=>n(Date.now()),1e3);return()=>clearInterval(i)},[]);const r=Math.max(0,s-t),a=Math.floor(r/1e3);return{expired:r<=0,d:Math.floor(a/86400),h:Math.floor(a%86400/3600),m:Math.floor(a%3600/60),sec:a%60}}function Gxt({dark:s=!1}){const{d:t,h:n,m:r,sec:a,expired:i}=y9t(x9t);if(i)return null;const l=[{v:t,l:"Days"},{v:n,l:"Hours"},{v:r,l:"Min"},{v:a,l:"Sec"}];return e.jsx("div",{className:"flex items-center gap-2 sm:gap-3",children:l.map(o=>e.jsxs("div",{className:`${s?"ld-glass":"bg-card border"} rounded-xl px-3 py-2 sm:px-4 sm:py-3 text-center min-w-[60px] sm:min-w-[72px]`,children:[e.jsx("div",{className:`text-2xl sm:text-3xl font-bold tabular-nums ${s?"text-white":"text-foreground"}`,children:String(o.v).padStart(2,"0")}),e.jsx("div",{className:`text-[10px] uppercase tracking-widest ${s?"text-white/60":"text-muted-foreground"}`,children:o.l})]},o.l))})}function Wxt(){return e.jsx("div",{className:"flex gap-0.5","aria-label":"5 out of 5 stars",children:Array.from({length:5}).map((s,t)=>e.jsx(Da,{className:"h-4 w-4 fill-accent text-accent"},t))})}function WOs({slot:s,dark:t=!0}){return e.jsxs("figure",{className:`ld-shot overflow-hidden border ${t?"ld-glass":"bg-card border-border"}`,children:[e.jsxs("div",{className:`flex items-center gap-1.5 px-3 py-2 border-b ${t?"border-white/10":"border-border"}`,children:[e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-red-400/80"}),e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-amber-400/80"}),e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-green-400/80"}),e.jsx("span",{className:`ml-3 text-[11px] rounded px-2 py-0.5 ${t?"bg-white/10 text-white/70":"bg-muted text-muted-foreground"}`,children:"dashboard.relevelup.com"})]}),s.src?e.jsx("img",{src:s.src,alt:`LevelUp ${s.label} screenshot`,className:"w-full h-auto block",loading:"lazy"}):e.jsxs("div",{className:`w-full aspect-[16/10] flex flex-col items-center justify-center gap-3 ${t?"bg-white/5":"bg-muted"}`,children:[e.jsx(un,{className:`h-8 w-8 ${t?"text-white/40":"text-muted-foreground/50"}`}),e.jsx("p",{className:`text-sm font-medium ${t?"text-white/60":"text-muted-foreground"}`,children:s.label}),e.jsx("p",{className:`text-xs px-6 text-center ${t?"text-white/40":"text-muted-foreground/70"}`,children:"Screenshot placeholder"})]}),e.jsxs("figcaption",{className:`px-4 py-3 text-sm ${t?"text-white/80":"text-muted-foreground"}`,children:[e.jsx("span",{className:`font-semibold ${t?"text-white":"text-foreground"}`,children:s.label})," — ",s.caption]})]})}function KOs(){const{expired:s}=y9t(x9t),[t,n]=_.useState(""),[r,a]=_.useState(""),[i,l]=_.useState(!1),[o,c]=_.useState(0),d=_.useMemo(()=>[YJe,ZJe,XJe,QJe,JJe],[]),u=Mle-JOe,h=async()=>{if(!r.trim()||!r.includes("@")){se.error("Enter your email to claim the offer.");return}l(!0);try{const{data:m,error:p}=await q.functions.invoke("create-checkout",{body:{tier:"individual_annual",email:r.trim(),name:t.trim()||void 0,skipTrial:!0}});if(p){const f=p instanceof Mre?await p.context.text():p.message;throw new Error(f||"Checkout failed to start")}if(m!=null&&m.url){window.location.href=m.url;return}throw new Error("No checkout URL returned")}catch(m){console.error("Labor Day checkout error:",m),se.error(m.message||"Could not start checkout. Please try again."),l(!1)}};return e.jsxs("div",{className:"laborday-theme min-h-screen bg-background",children:[e.jsxs(ul,{children:[e.jsx("title",{children:"Labor Day Sale — LevelUp for $300/Year (Save $168) | LevelUp Consulting Group"}),e.jsx("meta",{name:"description",content:`Labor Day only: get the full LevelUp agent growth platform — coaching, CRM, deal pipeline, Staging Studio, marketing and more — for $300/year instead of $39/month. Locked in for as long as you stay a member. Ends ${QOe}.`}),e.jsx("meta",{property:"og:title",content:"Labor Day Sale — LevelUp for $300/Year"}),e.jsx("meta",{property:"og:description",content:"Coaching, CRM, deal pipeline, Staging Studio, marketing studio and more. $300/year, locked in. Ends Sept 11 at midnight."}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),e.jsx("link",{rel:"preconnect",href:"https://fonts.googleapis.com"}),e.jsx("link",{rel:"preconnect",href:"https://fonts.gstatic.com",crossOrigin:"anonymous"}),e.jsx("link",{href:"https://fonts.googleapis.com/css2?family=Archivo+Black&display=swap",rel:"stylesheet"}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify({"@context":"https://schema.org","@type":"Offer",name:"LevelUp Individual Agent — Labor Day Annual",price:"300.00",priceCurrency:"USD",availabilityEnds:"2026-09-11T23:59:59-04:00",seller:{"@type":"Organization",name:"LevelUp Consulting Group"}})})]}),!s&&e.jsxs("div",{className:"fixed bottom-0 inset-x-0 z-50 md:hidden bg-foreground/95 backdrop-blur border-t border-white/10 px-4 py-3 flex items-center justify-between gap-3",style:{backgroundColor:"hsl(var(--ld-navy-deep) / 0.96)"},children:[e.jsxs("div",{className:"text-white",children:[e.jsx("div",{className:"text-xs text-white/60 uppercase tracking-wider",children:"Labor Day"}),e.jsxs("div",{className:"font-bold",children:["$300",e.jsx("span",{className:"text-sm font-normal text-white/70",children:"/year"})," ",e.jsxs("span",{className:"text-xs line-through text-white/50 ml-1",children:["$",Mle]})]})]}),e.jsx(B,{asChild:!0,className:"bg-accent text-accent-foreground hover:bg-accent/90 font-semibold",children:e.jsx("a",{href:"#claim",children:"Claim Offer"})})]}),e.jsxs("header",{className:"ld-dark relative overflow-hidden",children:[e.jsx("div",{className:"ld-flagbar absolute top-0 inset-x-0 z-10"}),e.jsx("div",{className:"ld-stars absolute inset-0 opacity-[0.10] pointer-events-none"}),e.jsxs("div",{className:"relative max-w-6xl mx-auto px-6 pt-12 pb-20 md:pb-28",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("img",{src:TH,alt:"LevelUp Consulting Group",className:"h-9 md:h-11 w-auto"}),e.jsxs("div",{className:"hidden sm:flex items-center gap-2 text-white/70 text-sm",children:[e.jsx("div",{className:"flex -space-x-2",children:d.map((m,p)=>e.jsx("img",{src:m,alt:"",className:"h-7 w-7 rounded-full border-2 border-white/20 object-cover"},p))}),e.jsx("span",{children:"3,000+ agents"})]})]}),e.jsxs("div",{className:"mt-16 md:mt-24 text-center max-w-4xl mx-auto",children:[e.jsxs("div",{className:"mb-10",children:[e.jsx("span",{className:"ld-stamp text-xs sm:text-sm",children:"★ Labor Day Sale ★"}),e.jsxs("p",{className:"mt-4 text-white/60 text-xs sm:text-sm uppercase tracking-[0.2em] font-semibold",children:["Ends ",QOe]})]}),e.jsxs("h1",{className:"ld-display text-4xl sm:text-6xl lg:text-7xl text-white leading-[1.05] uppercase",children:["Everything you need to grow your business.",e.jsx("span",{className:"block mt-4 ld-gold-text",children:"One payment of $300."})]}),e.jsx("div",{className:"mt-6 flex items-center justify-center gap-2 text-accent","aria-hidden":!0,children:Array.from({length:5}).map((m,p)=>e.jsx(Da,{className:"h-4 w-4 fill-accent text-accent"},p))}),e.jsxs("p",{className:"mt-6 text-lg md:text-xl text-white/75 max-w-2xl mx-auto leading-relaxed",children:["Coaching, a full agent growth platform, CRM, deal pipeline, Staging Studio, marketing studio and more —"," ",e.jsxs("span",{className:"text-white font-semibold",children:["normally $39/month ($",Mle,"/year)"]}),". This week only, get a full year for"," ",e.jsx("span",{className:"text-white font-semibold",children:"$300"}),", locked in for as long as you're a member."]}),e.jsxs("div",{className:"mt-10 flex flex-col items-center gap-4",children:[e.jsx(Gxt,{dark:!0}),e.jsx("p",{className:"text-xs uppercase tracking-widest text-white/50",children:"Offer disappears when the clock hits zero"})]}),e.jsxs("form",{id:"claim",onSubmit:m=>{m.preventDefault(),h()},className:"mt-8 mx-auto max-w-xl ld-glass rounded-2xl p-4 sm:p-5",children:[s?e.jsxs("div",{className:"text-center py-2",children:[e.jsx("p",{className:"text-white font-semibold text-lg",children:"This Labor Day offer has ended."}),e.jsx("p",{className:"text-white/60 text-sm mt-1 mb-4",children:"You can still join LevelUp with a free 7-day trial."}),e.jsx(B,{asChild:!0,size:"lg",className:"bg-accent text-accent-foreground hover:bg-accent/90 font-semibold w-full sm:w-auto",children:e.jsxs("a",{href:"/trial",children:["Start a Free Trial ",e.jsx(La,{className:"ml-2 h-4 w-4"})]})})]}):e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsx(xe,{value:t,onChange:m=>n(m.target.value),placeholder:"Your name",className:"bg-white/10 border-white/20 text-white placeholder:text-white/50 h-12",autoComplete:"name"}),e.jsx(xe,{value:r,onChange:m=>a(m.target.value),type:"email",placeholder:"Your email",className:"bg-white/10 border-white/20 text-white placeholder:text-white/50 h-12",autoComplete:"email",required:!0}),e.jsx(B,{type:"submit",disabled:i,size:"lg",className:"bg-accent text-accent-foreground hover:bg-accent/90 font-bold h-12 px-6 whitespace-nowrap",children:i?e.jsx(Ct,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:["Lock in $300/yr ",e.jsx(La,{className:"ml-2 h-5 w-5"})]})})]}),!s&&e.jsxs("p",{className:"text-white/50 text-xs mt-3 flex items-center justify-center gap-1.5",children:[e.jsx(ec,{className:"h-3 w-3"})," Secure Stripe checkout · Manage or cancel anytime from your profile"]})]}),e.jsxs("p",{className:"mt-6 text-white/70 text-sm",children:["Trusted by ",e.jsx("span",{className:"font-bold text-white",children:"3,000+ agents"})," to run and grow their business"]})]})]})]}),e.jsx("section",{className:"py-20 md:py-28 px-6",children:e.jsxs("div",{className:"max-w-6xl mx-auto",children:[e.jsxs("div",{className:"text-center mb-14",children:[e.jsx("span",{className:"text-sm font-semibold tracking-[0.15em] uppercase text-primary",children:"Everything included"}),e.jsx("h2",{className:"text-3xl md:text-5xl font-bold mt-4 tracking-tight",children:"One membership. The entire platform."}),e.jsxs("p",{className:"text-muted-foreground mt-4 max-w-2xl mx-auto",children:["This isn't a teaser tier. You get every tool LevelUp members use daily — worth $",Hxt.toLocaleString(),"/year at market rates."]})]}),e.jsxs("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 gap-5",children:[g9t.map(m=>e.jsxs("div",{className:"bg-card border rounded-2xl p-6 flex flex-col gap-3 hover:shadow-lg transition-shadow",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsx("div",{className:"h-11 w-11 rounded-xl bg-primary/10 flex items-center justify-center",children:e.jsx(m.icon,{className:"h-5 w-5 text-primary"})}),e.jsxs("span",{className:"text-xs font-semibold text-muted-foreground bg-muted rounded-full px-2.5 py-1",children:["$",m.value.toLocaleString(),"/yr value"]})]}),e.jsx("h3",{className:"font-bold text-lg",children:m.title}),e.jsx("p",{className:"text-sm text-muted-foreground leading-relaxed",children:m.desc})]},m.title)),e.jsxs("div",{className:"bg-foreground text-background rounded-2xl p-6 flex flex-col justify-center items-center text-center gap-2",style:{backgroundColor:"hsl(var(--ld-navy))",color:"white"},children:[e.jsx("div",{className:"text-sm uppercase tracking-widest text-white/60",children:"Total value"}),e.jsxs("div",{className:"text-4xl font-bold",children:["$",Hxt.toLocaleString(),e.jsx("span",{className:"text-lg font-normal text-white/60",children:"/yr"})]}),e.jsxs("div",{className:"text-white/70 text-sm",children:["Your Labor Day price: ",e.jsx("span",{className:"font-bold text-white",children:"$300/yr"})]})]})]})]})}),e.jsx("section",{className:"ld-dark py-20 md:py-28 px-6",children:e.jsxs("div",{className:"max-w-6xl mx-auto",children:[e.jsxs("div",{className:"text-center mb-14",children:[e.jsx("span",{className:"text-sm font-semibold tracking-[0.15em] uppercase text-accent",children:"See it in action"}),e.jsx("h2",{className:"text-3xl md:text-5xl font-bold text-white mt-4 tracking-tight",children:"A real platform, not another course"}),e.jsx("p",{className:"text-white/60 mt-4 max-w-2xl mx-auto",children:"This is what members open every morning."})]}),e.jsx("div",{className:"grid md:grid-cols-2 gap-8 md:gap-10",children:$Os.map(m=>e.jsx(WOs,{slot:m},m.key))})]})}),e.jsx("div",{className:"ld-divider pb-4","aria-hidden":!0,children:e.jsx("span",{children:"★★★"})}),e.jsx("section",{className:"py-20 md:py-28 px-6",children:e.jsxs("div",{className:"max-w-6xl mx-auto",children:[e.jsxs("div",{className:"text-center mb-12",children:[e.jsxs("div",{className:"inline-flex items-center gap-3 bg-card border rounded-full px-5 py-2.5 mb-6",children:[e.jsxs("svg",{viewBox:"0 0 24 24",className:"h-5 w-5","aria-hidden":!0,children:[e.jsx("path",{fill:"#4285F4",d:"M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92a5.06 5.06 0 0 1-2.2 3.32v2.77h3.57c2.08-1.92 3.27-4.74 3.27-8.1z"}),e.jsx("path",{fill:"#34A853",d:"M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"}),e.jsx("path",{fill:"#FBBC05",d:"M5.84 14.1a7.16 7.16 0 0 1 0-4.2V7.06H2.18a11 11 0 0 0 0 9.88l3.66-2.84z"}),e.jsx("path",{fill:"#EA4335",d:"M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.06l3.66 2.84c.87-2.6 3.3-4.52 6.16-4.52z"})]}),e.jsx("span",{className:"font-semibold",children:"5.0"}),e.jsx(Wxt,{}),e.jsx("span",{className:"text-muted-foreground text-sm",children:"on Google"})]}),e.jsx("h2",{className:"text-3xl md:text-5xl font-bold tracking-tight",children:"Why 3,000+ agents trust LevelUp"}),e.jsx("p",{className:"text-muted-foreground mt-4 max-w-2xl mx-auto",children:"Real reviews from real agents, pulled from our Google Business profile."})]}),e.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-4 gap-5",children:VOs.map(m=>e.jsxs("blockquote",{className:"bg-card border rounded-2xl p-5 flex flex-col gap-3",children:[e.jsx(Wxt,{}),e.jsxs("p",{className:"text-sm text-foreground/90 leading-relaxed flex-1",children:['"',m.text,'"']}),e.jsxs("footer",{children:[e.jsx("div",{className:"font-semibold text-sm",children:m.name}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[m.meta," · ",m.when]})]})]},m.name))}),e.jsx("div",{className:"text-center mt-8",children:e.jsx("a",{href:HOs,target:"_blank",rel:"noreferrer",className:"text-sm font-medium text-primary hover:underline",children:"Read all reviews on Google →"})})]})}),e.jsx("section",{className:"pb-20 md:pb-28 px-6",children:e.jsxs("div",{className:"max-w-4xl mx-auto",children:[e.jsx("div",{className:"text-center mb-12",children:e.jsx("h2",{className:"text-3xl md:text-5xl font-bold tracking-tight",children:"The math is simple"})}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-6",children:[e.jsxs("div",{className:"bg-card border rounded-3xl p-8",children:[e.jsx("h3",{className:"font-bold text-xl text-muted-foreground",children:"Regular Monthly"}),e.jsxs("div",{className:"mt-4 flex items-baseline gap-2",children:[e.jsx("span",{className:"text-5xl font-bold text-muted-foreground",children:"$39"}),e.jsx("span",{className:"text-muted-foreground",children:"/month"})]}),e.jsxs("ul",{className:"mt-6 space-y-3 text-sm text-muted-foreground",children:[e.jsxs("li",{className:"flex gap-2",children:[e.jsx(Qn,{className:"h-4 w-4 mt-0.5 shrink-0"})," $",Mle," per year"]}),e.jsxs("li",{className:"flex gap-2",children:[e.jsx(Qn,{className:"h-4 w-4 mt-0.5 shrink-0"})," Price can change at renewal"]}),e.jsxs("li",{className:"flex gap-2",children:[e.jsx(ea,{className:"h-4 w-4 mt-0.5 shrink-0 text-primary"})," Full platform access"]})]})]}),e.jsxs("div",{className:"relative rounded-3xl p-8 text-white overflow-hidden",style:{background:"linear-gradient(150deg, hsl(var(--ld-navy)), hsl(var(--ld-navy-deep)))"},children:[e.jsxs("div",{className:"absolute top-4 right-4 bg-accent text-accent-foreground text-xs font-bold uppercase tracking-wider rounded-full px-3 py-1",children:["Save $",u]}),e.jsx("h3",{className:"font-bold text-xl",children:"Labor Day Annual"}),e.jsxs("div",{className:"mt-4 flex items-baseline gap-2",children:[e.jsxs("span",{className:"text-5xl font-bold",children:["$",JOe]}),e.jsx("span",{className:"text-white/70",children:"/year"})]}),e.jsx("p",{className:"text-accent font-semibold text-sm mt-1",children:"That's just $25/month"}),e.jsxs("ul",{className:"mt-6 space-y-3 text-sm text-white/85",children:[e.jsxs("li",{className:"flex gap-2",children:[e.jsx(ea,{className:"h-4 w-4 mt-0.5 shrink-0 text-accent"})," $",JOe," per year — save $",u," vs monthly"]}),e.jsxs("li",{className:"flex gap-2",children:[e.jsx(Bq,{className:"h-4 w-4 mt-0.5 shrink-0 text-accent"})," Rate locked in for as long as you're a member"]}),e.jsxs("li",{className:"flex gap-2",children:[e.jsx(ea,{className:"h-4 w-4 mt-0.5 shrink-0 text-accent"})," Full platform access — everything included"]}),e.jsxs("li",{className:"flex gap-2",children:[e.jsx(Rm,{className:"h-4 w-4 mt-0.5 shrink-0 text-accent"})," Manage or cancel anytime from your profile"]})]}),e.jsx(B,{asChild:!0,size:"lg",className:"mt-8 w-full bg-accent text-accent-foreground hover:bg-accent/90 font-bold",children:e.jsx("a",{href:"#claim",children:"Claim the $300/yr rate"})})]})]})]})}),e.jsx("section",{className:"pb-20 md:pb-28 px-6",children:e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsx("h2",{className:"text-3xl md:text-4xl font-bold tracking-tight text-center mb-10",children:"Questions agents ask"}),e.jsx("div",{className:"space-y-3",children:GOs.map((m,p)=>e.jsxs("div",{className:"bg-card border rounded-2xl overflow-hidden",children:[e.jsxs("button",{onClick:()=>c(o===p?null:p),className:"w-full flex items-center justify-between gap-4 px-6 py-4 text-left font-semibold",children:[m.q,e.jsx("span",{className:`transition-transform ${o===p?"rotate-45":""} text-muted-foreground text-xl leading-none`,children:"+"})]}),o===p&&e.jsx("p",{className:"px-6 pb-5 text-sm text-muted-foreground leading-relaxed",children:m.a})]},p))})]})}),e.jsx("div",{className:"ld-divider pb-14","aria-hidden":!0,children:e.jsx("span",{children:"★★★"})}),e.jsxs("section",{className:"ld-dark relative overflow-hidden py-20 md:py-28 px-6",children:[e.jsx("div",{className:"ld-stars absolute inset-0 opacity-[0.08] pointer-events-none"}),e.jsx("div",{className:"ld-flagbar absolute bottom-0 inset-x-0"}),e.jsxs("div",{className:"relative max-w-3xl mx-auto text-center",children:[e.jsx("h2",{className:"ld-display text-3xl md:text-5xl text-white uppercase",children:"This is the lowest rate we've ever run."}),e.jsx("p",{className:"text-white/70 mt-5 text-lg",children:"When the timer hits zero, the $300/year rate is gone. Lock it in now and keep it for as long as you're a member."}),e.jsx("div",{className:"mt-8 flex justify-center",children:e.jsx(Gxt,{dark:!0})}),e.jsx(B,{asChild:!0,size:"lg",className:"mt-10 bg-accent text-accent-foreground hover:bg-accent/90 font-bold text-lg px-10 py-6",children:e.jsxs("a",{href:"#claim",children:["Get LevelUp for $300/year ",e.jsx(La,{className:"ml-2 h-5 w-5"})]})}),e.jsxs("p",{className:"text-white/40 text-xs mt-4 flex items-center justify-center gap-1.5",children:[e.jsx(ec,{className:"h-3 w-3"})," Secure Stripe checkout · Ends ",QOe]}),e.jsxs("p",{className:"text-white/50 text-sm mt-10",children:["© ",new Date().getFullYear()," LevelUp Consulting Group"]})]})]}),e.jsx(f9t,{pageKey:"individual-labor-day-2026",headline:"Not ready to join the LevelUp family yet?"})]})}const v9t=Date.UTC(2026,8,12,3,59,59),e7e="Friday, September 11 at 11:59 PM ET",mX=399,D4e=499,Kxt=(D4e-mX)*12,YOs=[{key:"dashboard",label:"Agent Command Center",caption:"Every agent's day — smart queue, calendar and pipeline in one view.",src:Qre},{key:"crm",label:"CRM & Contact Hub",caption:"Contacts, tags, follow-ups and deal history for every agent.",src:UPe},{key:"pipeline",label:"Deal Pipeline",caption:"Every transaction with tasks, forms and commission tracking built in.",src:qPe},{key:"staging",label:"Staging Studio",caption:"AI photo staging — MLS-ready before/afters in minutes.",src:$Pe},{key:"coaching",label:"Coaching",caption:"Live coaching sessions your agents book themselves.",src:VPe},{key:"marketing",label:"Marketing Studio",caption:"Templates, social posts, reels and print — all branded.",src:HPe}],ZOs=[{name:"Tracy VanderWall",meta:"Local Guide · Broker/Owner",when:"7 months ago",text:"Best investment my brokerage has made! The value of this platform is AMAZING! The entire LEVELUP Team is wonderful!"},{name:"Bill Burns",meta:"Local Guide · Broker",when:"5 months ago",text:"Jeremy and his team are amazing! Level Up can next level your brokerage!"},{name:"Robert Larente",meta:"Real Estate Agent",when:"5 months ago",text:"I'm fortunate that my Broker started providing LevelUp membership a few years ago. Originally I used it for kvCore/Bold CRM training. But with the amazing amount of resources that Jeremy and his crew keep adding, I'm quickly canceling my subscriptions to other service providers."},{name:"Valerie Harp",meta:"Local Guide · Real Estate Agent",when:"4 months ago",text:"Level Up has been an absolute game changer for my real estate business. The platform is incredibly easy to use and by far one of the most user-friendly systems I've worked with. Everything is streamlined, intuitive, and designed with agents in mind."},{name:"Tom Lois",meta:"Real Estate Agent",when:"5 months ago",text:"Jeremy and his team at LevelUp continue to upgrade, update, and uplift agents with their meaningful content and insight. Whether you're a newbie or a seasoned agent, this program is for you! Try it — you'll REALLY like it!"},{name:"Michael Smith",meta:"Local Guide · Real Estate Agent",when:"7 months ago",text:"Great value in the material, ideas, etc. shared by the LevelUp team. They consistently provide implementable examples of ways to impact your real estate business. Not just theory, but real ideas/tasks that can be quickly implemented."},{name:"Pamela Nichols",meta:"Local Guide · Real Estate Agent",when:"4 months ago",text:"I'm loving this platform and all the excellent quick and easy information to use! It has been the easiest thing I've ever used to care for my database! I love the quick videos — quick and to the point!"},{name:"Anissa, REMAX Executives",meta:"Real Estate Agent",when:"6 months ago",text:"So far this has helped me tremendously! Keeps me more organized and motivated to stay on top of these leads that get lost in the daily mix."}],XOs="https://www.google.com/search?q=levelup+consulting+group#lrd=0x8842f50045c4bd33:0xc9b99b5330a91b3f,1,,,,",QOs=[{icon:jv,title:"Live Weekly Trainings",desc:"Every agent joins live weekly training sessions with Jeremy and the LevelUp team — plus the full on-demand Academy."},{icon:p7,title:"Full CRM & Contact Hub",desc:"Contacts, tags, smart follow-ups, lead ponds and team assignments — every agent's database finally organized."},{icon:wv,title:"Deal Pipeline",desc:"Transactions from offer to closing with tasks, forms and commission math built in."},{icon:cg,title:"Staging Studio",desc:"AI virtual staging with MLS-ready before/after photos for every listing."},{icon:Xc,title:"Marketing & Social Studio",desc:"300+ branded templates, social posts, postcards and the weekly Reels engine."},{icon:sl,title:"Lead Sites",desc:"SEO-optimized websites that rank on Google and capture leads 24/7."},{icon:mm,title:"Academy Training",desc:"On-demand video training on lead gen, marketing and tech."},{icon:lb,title:"Forms & E-Signature",desc:"Upload any PDF, map fields, send for signature — done from one place."},{icon:Kr,title:"Weekly Reels & Video Tools",desc:"Personalized Instagram scripts every Monday, plus screen recording and virtual backgrounds."}],JOs=[{icon:ai,title:"Your Own Brokerage Hub",desc:"Brand profiles, announcements and resources pushed to every agent from one place."},{icon:lb,title:"Brokerage Form Library",desc:"Publish your official forms office-wide — agents use them read-only or copy to customize."},{icon:Pl,title:"Recruiting Pipeline",desc:"Customizable recruiting stages to attract and track your next agents."},{icon:wh,title:"Office-Wide Communication",desc:"Broadcasts, brokerage content and resource libraries your agents actually use."}],e7s=[{q:"What does 'unlimited agents' actually mean?",a:"Every agent in your brokerage gets a full LevelUp membership — coaching, CRM, deal pipeline, Staging Studio, Marketing Studio, lead sites, Academy, forms with e-signature, reviews, Weekly Reels and the ChatGPT app. No per-seat fees, no caps, no tiers to unlock."},{q:"Is the $399/mo rate really locked in?",a:"Yes. As long as your subscription stays active, you renew at $399/month — even when the standard brokerage rate goes back to $499/month. No surprises, no bump after year one."},{q:"What happens after I pay?",a:"You'll land on a setup screen where you name your brokerage, set your branding, and start inviting agents. Agents accept their invite and have full access within minutes."},{q:"What if we add or lose agents during the year?",a:"Nothing changes on your bill. The rate is flat $399/month for the whole brokerage whether you have 10 agents or 100. Add and remove agents freely from your brokerage dashboard."},{q:"Is there a contract or trial?",a:"No long-term contract and no trial on this one — you're charged $399 today and billed monthly. Manage or cancel anytime from your profile's Stripe customer portal."},{q:"Is this really the last brokerage offer this year?",a:"Yes. This is our final brokerage partnership promotion of 2026. When the clock hits zero on September 11, this rate is gone."}];function b9t(s){const[t,n]=_.useState(()=>Date.now());_.useEffect(()=>{const i=setInterval(()=>n(Date.now()),1e3);return()=>clearInterval(i)},[]);const r=Math.max(0,s-t),a=Math.floor(r/1e3);return{expired:r<=0,d:Math.floor(a/86400),h:Math.floor(a%86400/3600),m:Math.floor(a%3600/60),sec:a%60}}function Yxt({dark:s=!1}){const{d:t,h:n,m:r,sec:a,expired:i}=b9t(v9t);if(i)return null;const l=[{v:t,l:"Days"},{v:n,l:"Hours"},{v:r,l:"Min"},{v:a,l:"Sec"}];return e.jsx("div",{className:"flex items-center gap-2 sm:gap-3",children:l.map(o=>e.jsxs("div",{className:`${s?"ld-glass":"bg-card border"} rounded-xl px-3 py-2 sm:px-4 sm:py-3 text-center min-w-[60px] sm:min-w-[72px]`,children:[e.jsx("div",{className:`text-2xl sm:text-3xl font-bold tabular-nums ${s?"text-white":"text-foreground"}`,children:String(o.v).padStart(2,"0")}),e.jsx("div",{className:`text-[10px] uppercase tracking-widest ${s?"text-white/60":"text-muted-foreground"}`,children:o.l})]},o.l))})}function Zxt(){return e.jsx("div",{className:"flex gap-0.5","aria-label":"5 out of 5 stars",children:Array.from({length:5}).map((s,t)=>e.jsx(Da,{className:"h-4 w-4 fill-accent text-accent"},t))})}function t7s({slot:s,dark:t=!0}){return e.jsxs("figure",{className:`ld-shot overflow-hidden border ${t?"ld-glass":"bg-card border-border"}`,children:[e.jsxs("div",{className:`flex items-center gap-1.5 px-3 py-2 border-b ${t?"border-white/10":"border-border"}`,children:[e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-red-400/80"}),e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-amber-400/80"}),e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-green-400/80"}),e.jsx("span",{className:`ml-3 text-[11px] rounded px-2 py-0.5 ${t?"bg-white/10 text-white/70":"bg-muted text-muted-foreground"}`,children:"dashboard.relevelup.com"})]}),s.src?e.jsx("img",{src:s.src,alt:`LevelUp ${s.label} screenshot`,className:"w-full h-auto block",loading:"lazy"}):e.jsxs("div",{className:`w-full aspect-[16/10] flex flex-col items-center justify-center gap-3 ${t?"bg-white/5":"bg-muted"}`,children:[e.jsx(un,{className:`h-8 w-8 ${t?"text-white/40":"text-muted-foreground/50"}`}),e.jsx("p",{className:`text-sm font-medium ${t?"text-white/60":"text-muted-foreground"}`,children:s.label})]}),e.jsxs("figcaption",{className:`px-4 py-3 text-sm ${t?"text-white/80":"text-muted-foreground"}`,children:[e.jsx("span",{className:`font-semibold ${t?"text-white":"text-foreground"}`,children:s.label})," — ",s.caption]})]})}function s7s(){const{expired:s}=b9t(v9t),[t,n]=_.useState(""),[r,a]=_.useState(""),[i,l]=_.useState(!1),[o,c]=_.useState(0),d=_.useMemo(()=>[YJe,ZJe,XJe,QJe,JJe],[]),u=async()=>{if(!r.trim()||!r.includes("@")){se.error("Enter your email to claim the offer.");return}l(!0);try{const{data:h,error:m}=await q.functions.invoke("create-checkout",{body:{tier:"brokerage_labor_day",email:r.trim(),name:t.trim()||void 0,skipTrial:!0}});if(m){const p=m instanceof Mre?await m.context.text():m.message;throw new Error(p||"Checkout failed to start")}if(h!=null&&h.url){window.location.href=h.url;return}throw new Error("No checkout URL returned")}catch(h){console.error("Brokerage Labor Day checkout error:",h),se.error(h.message||"Could not start checkout. Please try again."),l(!1)}};return e.jsxs("div",{className:"laborday-theme min-h-screen bg-background",children:[e.jsxs(ul,{children:[e.jsx("title",{children:"Labor Day Brokerage Special — LevelUp for $399/mo, Unlimited Agents | LevelUp Consulting Group"}),e.jsx("meta",{name:"description",content:`Last brokerage offer of 2026: give every agent in your brokerage a full LevelUp membership — live weekly trainings, CRM, marketing and more — for $399/mo instead of $499/mo. Rate locked. Ends ${e7e}.`}),e.jsx("meta",{property:"og:title",content:"Labor Day Brokerage Special — $399/mo for Your Entire Brokerage"}),e.jsx("meta",{property:"og:description",content:"Unlimited agents, full memberships, live weekly trainings. $399/mo instead of $499/mo, locked in. Last brokerage offer of 2026 — ends Sept 11 at midnight."}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),e.jsx("link",{rel:"preconnect",href:"https://fonts.googleapis.com"}),e.jsx("link",{rel:"preconnect",href:"https://fonts.gstatic.com",crossOrigin:"anonymous"}),e.jsx("link",{href:"https://fonts.googleapis.com/css2?family=Archivo+Black&display=swap",rel:"stylesheet"}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify({"@context":"https://schema.org","@type":"Offer",name:"LevelUp Brokerage Partner — Labor Day Offer",price:"399.00",priceCurrency:"USD",availabilityEnds:"2026-09-11T23:59:59-04:00",seller:{"@type":"Organization",name:"LevelUp Consulting Group"}})})]}),!s&&e.jsxs("div",{className:"fixed bottom-0 inset-x-0 z-50 md:hidden bg-foreground/95 backdrop-blur border-t border-white/10 px-4 py-3 flex items-center justify-between gap-3",style:{backgroundColor:"hsl(var(--ld-navy-deep) / 0.96)"},children:[e.jsxs("div",{className:"text-white",children:[e.jsx("div",{className:"text-xs text-white/60 uppercase tracking-wider",children:"Brokerage Labor Day"}),e.jsxs("div",{className:"font-bold",children:["$",mX,e.jsx("span",{className:"text-sm font-normal text-white/70",children:"/mo"})," ",e.jsxs("span",{className:"text-xs line-through text-white/50 ml-1",children:["$",D4e]})]})]}),e.jsx(B,{asChild:!0,className:"bg-accent text-accent-foreground hover:bg-accent/90 font-semibold",children:e.jsx("a",{href:"#claim",children:"Claim Offer"})})]}),e.jsxs("header",{className:"ld-dark relative overflow-hidden",children:[e.jsx("div",{className:"ld-flagbar absolute top-0 inset-x-0 z-10"}),e.jsx("div",{className:"ld-stars absolute inset-0 opacity-[0.10] pointer-events-none"}),e.jsxs("div",{className:"relative max-w-6xl mx-auto px-6 pt-12 pb-20 md:pb-28",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("img",{src:TH,alt:"LevelUp Consulting Group",className:"h-9 md:h-11 w-auto"}),e.jsxs("div",{className:"hidden sm:flex items-center gap-2 text-white/70 text-sm",children:[e.jsx("div",{className:"flex -space-x-2",children:d.map((h,m)=>e.jsx("img",{src:h,alt:"",className:"h-7 w-7 rounded-full border-2 border-white/20 object-cover"},m))}),e.jsx("span",{children:"3,000+ agents"})]})]}),e.jsxs("div",{className:"mt-16 md:mt-24 text-center max-w-4xl mx-auto",children:[e.jsxs("div",{className:"mb-10",children:[e.jsx("span",{className:"ld-stamp text-xs sm:text-sm",children:"★ Labor Day Brokerage Special ★"}),e.jsxs("p",{className:"mt-4 text-white/60 text-xs sm:text-sm uppercase tracking-[0.2em] font-semibold",children:["Last brokerage offer of 2026 · Ends ",e7e]})]}),e.jsxs("h1",{className:"ld-display text-4xl sm:text-6xl lg:text-7xl text-white leading-[1.05] uppercase",children:["Every agent in your brokerage. Full membership.",e.jsx("span",{className:"block mt-4 ld-gold-text",children:"$399/mo — not $499."})]}),e.jsx("div",{className:"mt-6 flex items-center justify-center gap-2 text-accent","aria-hidden":!0,children:Array.from({length:5}).map((h,m)=>e.jsx(Da,{className:"h-4 w-4 fill-accent text-accent"},m))}),e.jsxs("p",{className:"mt-6 text-lg md:text-xl text-white/75 max-w-2xl mx-auto leading-relaxed",children:["Live weekly trainings, a full agent growth platform, CRM, marketing studio and more —"," ",e.jsx("span",{className:"text-white font-semibold",children:"for every agent in your brokerage"}),". Normally"," ",e.jsx("span",{className:"text-white font-semibold",children:"$499/month"}),". Partner this week for"," ",e.jsx("span",{className:"text-white font-semibold",children:"$399/month"}),", locked in for as long as you're a partner."]}),e.jsxs("div",{className:"mt-10 flex flex-col items-center gap-4",children:[e.jsx(Yxt,{dark:!0}),e.jsx("p",{className:"text-xs uppercase tracking-widest text-white/50",children:"Offer disappears when the clock hits zero"})]}),e.jsxs("form",{id:"claim",onSubmit:h=>{h.preventDefault(),u()},className:"mt-8 mx-auto max-w-xl ld-glass rounded-2xl p-4 sm:p-5",children:[s?e.jsxs("div",{className:"text-center py-2",children:[e.jsx("p",{className:"text-white font-semibold text-lg",children:"This Labor Day brokerage offer has ended."}),e.jsx("p",{className:"text-white/60 text-sm mt-1 mb-4",children:"You can still partner with LevelUp at the standard brokerage rate."}),e.jsx(B,{asChild:!0,size:"lg",className:"bg-accent text-accent-foreground hover:bg-accent/90 font-semibold w-full sm:w-auto",children:e.jsxs("a",{href:"/pricing",children:["See Brokerage Plans ",e.jsx(La,{className:"ml-2 h-4 w-4"})]})})]}):e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsx(xe,{value:t,onChange:h=>n(h.target.value),placeholder:"Your name",className:"bg-white/10 border-white/20 text-white placeholder:text-white/50 h-12",autoComplete:"name"}),e.jsx(xe,{value:r,onChange:h=>a(h.target.value),type:"email",placeholder:"Your email",className:"bg-white/10 border-white/20 text-white placeholder:text-white/50 h-12",autoComplete:"email",required:!0}),e.jsx(B,{type:"submit",disabled:i,size:"lg",className:"bg-accent text-accent-foreground hover:bg-accent/90 font-bold h-12 px-6 whitespace-nowrap",children:i?e.jsx(Ct,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:["Partner at $399/mo ",e.jsx(La,{className:"ml-2 h-5 w-5"})]})})]}),!s&&e.jsxs("p",{className:"text-white/50 text-xs mt-3 flex items-center justify-center gap-1.5",children:[e.jsx(ec,{className:"h-3 w-3"})," Secure Stripe checkout · Set up your brokerage right after payment"]})]}),e.jsxs("p",{className:"mt-6 text-white/70 text-sm",children:["Trusted by ",e.jsx("span",{className:"font-bold text-white",children:"3,000+ agents"})," and the brokerages they work for"]})]})]})]}),e.jsx("section",{className:"py-20 md:py-28 px-6",children:e.jsxs("div",{className:"max-w-6xl mx-auto",children:[e.jsxs("div",{className:"text-center mb-14",children:[e.jsx("span",{className:"text-sm font-semibold tracking-[0.15em] uppercase text-primary",children:"What your agents get"}),e.jsx("h2",{className:"text-3xl md:text-5xl font-bold mt-4 tracking-tight",children:"A full membership for every agent. No per-seat fees."}),e.jsx("p",{className:"text-muted-foreground mt-4 max-w-2xl mx-auto",children:"Individually, this membership costs $39/month per agent. As a brokerage partner, every agent gets it — all included in one flat rate."})]}),e.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 gap-5",children:QOs.map(h=>e.jsxs("div",{className:"bg-card border rounded-2xl p-6 flex flex-col gap-3 hover:shadow-lg transition-shadow",children:[e.jsx("div",{className:"h-11 w-11 rounded-xl bg-primary/10 flex items-center justify-center",children:e.jsx(h.icon,{className:"h-5 w-5 text-primary"})}),e.jsx("h3",{className:"font-bold text-lg",children:h.title}),e.jsx("p",{className:"text-sm text-muted-foreground leading-relaxed",children:h.desc})]},h.title))})]})}),e.jsx("section",{className:"ld-dark py-20 md:py-28 px-6",children:e.jsxs("div",{className:"max-w-6xl mx-auto",children:[e.jsxs("div",{className:"text-center mb-14",children:[e.jsx("span",{className:"text-sm font-semibold tracking-[0.15em] uppercase text-accent",children:"For the brokerage"}),e.jsx("h2",{className:"text-3xl md:text-5xl font-bold text-white mt-4 tracking-tight",children:"Tools that make your office run itself"}),e.jsx("p",{className:"text-white/60 mt-4 max-w-2xl mx-auto",children:"You get more than agent seats — you get brokerage-level controls."})]}),e.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-4 gap-5",children:JOs.map(h=>e.jsxs("div",{className:"ld-glass rounded-2xl p-6 flex flex-col gap-3",children:[e.jsx("div",{className:"h-11 w-11 rounded-xl bg-white/10 flex items-center justify-center",children:e.jsx(h.icon,{className:"h-5 w-5 text-accent"})}),e.jsx("h3",{className:"font-bold text-lg text-white",children:h.title}),e.jsx("p",{className:"text-sm text-white/70 leading-relaxed",children:h.desc})]},h.title))})]})}),e.jsx("section",{className:"py-20 md:py-28 px-6",children:e.jsxs("div",{className:"max-w-6xl mx-auto",children:[e.jsxs("div",{className:"text-center mb-14",children:[e.jsx("span",{className:"text-sm font-semibold tracking-[0.15em] uppercase text-primary",children:"See it in action"}),e.jsx("h2",{className:"text-3xl md:text-5xl font-bold mt-4 tracking-tight",children:"A real platform, not another training course"}),e.jsx("p",{className:"text-muted-foreground mt-4 max-w-2xl mx-auto",children:"This is what your agents open every morning."})]}),e.jsx("div",{className:"grid md:grid-cols-2 gap-8 md:gap-10",children:YOs.map(h=>e.jsx(t7s,{slot:h,dark:!1},h.key))})]})}),e.jsx("div",{className:"ld-divider pb-4","aria-hidden":!0,children:e.jsx("span",{children:"★★★"})}),e.jsx("section",{className:"py-20 md:py-28 px-6",children:e.jsxs("div",{className:"max-w-6xl mx-auto",children:[e.jsxs("div",{className:"text-center mb-12",children:[e.jsxs("div",{className:"inline-flex items-center gap-3 bg-card border rounded-full px-5 py-2.5 mb-6",children:[e.jsxs("svg",{viewBox:"0 0 24 24",className:"h-5 w-5","aria-hidden":!0,children:[e.jsx("path",{fill:"#4285F4",d:"M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92a5.06 5.06 0 0 1-2.2 3.32v2.77h3.57c2.08-1.92 3.27-4.74 3.27-8.1z"}),e.jsx("path",{fill:"#34A853",d:"M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"}),e.jsx("path",{fill:"#FBBC05",d:"M5.84 14.1a7.16 7.16 0 0 1 0-4.2V7.06H2.18a11 11 0 0 0 0 9.88l3.66-2.84z"}),e.jsx("path",{fill:"#EA4335",d:"M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.06l3.66 2.84c.87-2.6 3.3-4.52 6.16-4.52z"})]}),e.jsx("span",{className:"font-semibold",children:"5.0"}),e.jsx(Zxt,{}),e.jsx("span",{className:"text-muted-foreground text-sm",children:"on Google"})]}),e.jsx("h2",{className:"text-3xl md:text-5xl font-bold tracking-tight",children:"Brokers and agents agree"}),e.jsx("p",{className:"text-muted-foreground mt-4 max-w-2xl mx-auto",children:"Real reviews from our Google Business profile — including the brokers who made the call."})]}),e.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-4 gap-5",children:ZOs.map(h=>e.jsxs("blockquote",{className:"bg-card border rounded-2xl p-5 flex flex-col gap-3",children:[e.jsx(Zxt,{}),e.jsxs("p",{className:"text-sm text-foreground/90 leading-relaxed flex-1",children:['"',h.text,'"']}),e.jsxs("footer",{children:[e.jsx("div",{className:"font-semibold text-sm",children:h.name}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[h.meta," · ",h.when]})]})]},h.name))}),e.jsx("div",{className:"text-center mt-8",children:e.jsx("a",{href:XOs,target:"_blank",rel:"noreferrer",className:"text-sm font-medium text-primary hover:underline",children:"Read all reviews on Google →"})})]})}),e.jsx("section",{className:"pb-20 md:pb-28 px-6",children:e.jsxs("div",{className:"max-w-4xl mx-auto",children:[e.jsx("div",{className:"text-center mb-12",children:e.jsx("h2",{className:"text-3xl md:text-5xl font-bold tracking-tight",children:"Live in three steps"})}),e.jsx("div",{className:"grid md:grid-cols-3 gap-6",children:[{n:"1",title:"Partner & pay",desc:"Claim the $399/mo rate with secure Stripe checkout. Charged today, billed monthly."},{n:"2",title:"Set up your brokerage",desc:"Name your brokerage, add your branding and configure your office — minutes, not days."},{n:"3",title:"Invite your agents",desc:"Send invites and every agent gets their full membership. They can start this week."}].map(h=>e.jsxs("div",{className:"bg-card border rounded-2xl p-6 text-center",children:[e.jsx("div",{className:"mx-auto h-12 w-12 rounded-full bg-primary/10 flex items-center justify-center text-primary font-bold text-xl",children:h.n}),e.jsx("h3",{className:"font-bold text-lg mt-4",children:h.title}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2 leading-relaxed",children:h.desc})]},h.n))})]})}),e.jsx("section",{className:"pb-20 md:pb-28 px-6",children:e.jsxs("div",{className:"max-w-4xl mx-auto",children:[e.jsxs("div",{className:"text-center mb-12",children:[e.jsx("h2",{className:"text-3xl md:text-5xl font-bold tracking-tight",children:"Do the math"}),e.jsxs("p",{className:"text-muted-foreground mt-4 max-w-2xl mx-auto",children:["25 agents × $39/mo memberships = $975/mo of value. You pay a flat $",mX,"."]})]}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-6",children:[e.jsxs("div",{className:"bg-card border rounded-3xl p-8",children:[e.jsx("h3",{className:"font-bold text-xl text-muted-foreground",children:"Standard Brokerage Plan"}),e.jsxs("div",{className:"mt-4 flex items-baseline gap-2",children:[e.jsxs("span",{className:"text-5xl font-bold text-muted-foreground",children:["$",D4e]}),e.jsx("span",{className:"text-muted-foreground",children:"/month"})]}),e.jsxs("ul",{className:"mt-6 space-y-3 text-sm text-muted-foreground",children:[e.jsxs("li",{className:"flex gap-2",children:[e.jsx(Qn,{className:"h-4 w-4 mt-0.5 shrink-0"})," $",(D4e*12).toLocaleString()," per year"]}),e.jsxs("li",{className:"flex gap-2",children:[e.jsx(Qn,{className:"h-4 w-4 mt-0.5 shrink-0"})," Standard rate — no lock-in"]}),e.jsxs("li",{className:"flex gap-2",children:[e.jsx(ea,{className:"h-4 w-4 mt-0.5 shrink-0 text-primary"})," Unlimited agents, full memberships"]})]})]}),e.jsxs("div",{className:"relative rounded-3xl p-8 text-white overflow-hidden",style:{background:"linear-gradient(150deg, hsl(var(--ld-navy)), hsl(var(--ld-navy-deep)))"},children:[e.jsxs("div",{className:"absolute top-4 right-4 bg-accent text-accent-foreground text-xs font-bold uppercase tracking-wider rounded-full px-3 py-1",children:["Save $",Kxt.toLocaleString(),"/yr"]}),e.jsx("h3",{className:"font-bold text-xl",children:"Labor Day Partner Rate"}),e.jsxs("div",{className:"mt-4 flex items-baseline gap-2",children:[e.jsxs("span",{className:"text-5xl font-bold",children:["$",mX]}),e.jsx("span",{className:"text-white/70",children:"/month"})]}),e.jsx("p",{className:"text-accent font-semibold text-sm mt-1",children:"25 agents = under $16/agent/mo"}),e.jsxs("ul",{className:"mt-6 space-y-3 text-sm text-white/85",children:[e.jsxs("li",{className:"flex gap-2",children:[e.jsx(ea,{className:"h-4 w-4 mt-0.5 shrink-0 text-accent"})," $",(mX*12).toLocaleString()," per year — save $",Kxt.toLocaleString()," vs standard"]}),e.jsxs("li",{className:"flex gap-2",children:[e.jsx(Bq,{className:"h-4 w-4 mt-0.5 shrink-0 text-accent"})," Rate locked for as long as you're a partner"]}),e.jsxs("li",{className:"flex gap-2",children:[e.jsx(ea,{className:"h-4 w-4 mt-0.5 shrink-0 text-accent"})," Unlimited agents — every one gets a full membership"]}),e.jsxs("li",{className:"flex gap-2",children:[e.jsx(Rm,{className:"h-4 w-4 mt-0.5 shrink-0 text-accent"})," Manage or cancel anytime from your profile"]})]}),e.jsx(B,{asChild:!0,size:"lg",className:"mt-8 w-full bg-accent text-accent-foreground hover:bg-accent/90 font-bold",children:e.jsx("a",{href:"#claim",children:"Partner at $399/mo"})})]})]})]})}),e.jsx("section",{className:"pb-20 md:pb-28 px-6",children:e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsx("h2",{className:"text-3xl md:text-4xl font-bold tracking-tight text-center mb-10",children:"Questions brokers ask"}),e.jsx("div",{className:"space-y-3",children:e7s.map((h,m)=>e.jsxs("div",{className:"bg-card border rounded-2xl overflow-hidden",children:[e.jsxs("button",{onClick:()=>c(o===m?null:m),className:"w-full flex items-center justify-between gap-4 px-6 py-4 text-left font-semibold",children:[h.q,e.jsx("span",{className:`transition-transform ${o===m?"rotate-45":""} text-muted-foreground text-xl leading-none`,children:"+"})]}),o===m&&e.jsx("p",{className:"px-6 pb-5 text-sm text-muted-foreground leading-relaxed",children:h.a})]},m))})]})}),e.jsx("div",{className:"ld-divider pb-14","aria-hidden":!0,children:e.jsx("span",{children:"★★★"})}),e.jsxs("section",{className:"ld-dark relative overflow-hidden py-20 md:py-28 px-6",children:[e.jsx("div",{className:"ld-stars absolute inset-0 opacity-[0.08] pointer-events-none"}),e.jsx("div",{className:"ld-flagbar absolute bottom-0 inset-x-0"}),e.jsxs("div",{className:"relative max-w-3xl mx-auto text-center",children:[e.jsx("h2",{className:"ld-display text-3xl md:text-5xl text-white uppercase",children:"The last brokerage offer of 2026."}),e.jsx("p",{className:"text-white/70 mt-5 text-lg",children:"When the timer hits zero, the $399/mo partner rate is gone. Lock it in now and give every agent in your brokerage a full membership."}),e.jsx("div",{className:"mt-8 flex justify-center",children:e.jsx(Yxt,{dark:!0})}),e.jsx(B,{asChild:!0,size:"lg",className:"mt-10 bg-accent text-accent-foreground hover:bg-accent/90 font-bold text-lg px-10 py-6",children:e.jsxs("a",{href:"#claim",children:["Partner with LevelUp — $399/mo ",e.jsx(La,{className:"ml-2 h-5 w-5"})]})}),e.jsxs("p",{className:"text-white/40 text-xs mt-4 flex items-center justify-center gap-1.5",children:[e.jsx(ec,{className:"h-3 w-3"})," Secure Stripe checkout · Ends ",e7e]}),e.jsxs("p",{className:"text-white/50 text-sm mt-10",children:["© ",new Date().getFullYear()," LevelUp Consulting Group"]})]})]}),e.jsx(f9t,{pageKey:"brokerage-labor-day-2026",headline:"Not ready to partner with LevelUp yet?"})]})}const n7s=["Unlimited access to all marketing templates","Complete Academy training library","AI-powered tools and resources","Lead site & Listing Exchange access","Deal pipeline & scorecard tracking","Community forums and support"],r7s=["Everything in Individual, plus:","Unlimited agent seats","Brokerage admin dashboard","Team performance analytics","Agent onboarding tools","Priority support"],a7s=()=>{const{user:s,loading:t}=hs(),n=Fn(),[r]=Yl(),a=r.get("plan"),i=a==="individual"?"individual_agent":a==="brokerage"?"brokerage_over_25":a,[l,o]=_.useState(!1),[c,d]=_.useState(null),[u,h]=_.useState(""),m=y=>{const v=`/upgrade?plan=${y}`;n(`/auth?next=${encodeURIComponent(v)}`)},p=async y=>{var v;if(!(s!=null&&s.email)){m(y);return}o(!0),d(y);try{const{data:g,error:b}=await q.functions.invoke("create-checkout",{body:{tier:y,email:s.email,name:((v=s.user_metadata)==null?void 0:v.full_name)||s.email,userId:s.id,couponCode:u.trim()||void 0,skipTrial:!0}});if(b)throw b;if(g!=null&&g.url)window.location.href=g.url;else throw new Error("No checkout URL returned")}catch(g){console.error("Checkout error:",g),se.error(g.message||"Failed to start checkout. Please try again."),o(!1),d(null)}},f=(y,v,g,b,j,S,C)=>e.jsxs(ve,{className:`relative border-2 transition-colors ${C?"border-primary shadow-lg":"border-amber-500/30"} ${i===y?"ring-2 ring-primary ring-offset-2":""}`,children:[i===y&&e.jsx(Oe,{className:"absolute -top-3 left-1/2 -translate-x-1/2 bg-primary text-primary-foreground",children:"Recommended for you"}),e.jsxs(Me,{className:"p-6 text-center space-y-4",children:[e.jsx("div",{className:`mx-auto h-12 w-12 rounded-full flex items-center justify-center ${C?"bg-primary/10":"bg-amber-500/10"}`,children:S}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-xl",children:v}),e.jsxs("p",{className:`text-3xl font-bold mt-1 ${C?"text-primary":"text-amber-600"}`,children:[g,e.jsx("span",{className:"text-sm font-normal text-muted-foreground",children:"/mo"})]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:b})]}),e.jsx("ul",{className:"text-sm space-y-1.5 text-left text-muted-foreground",children:j.map(E=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx(ea,{className:`h-4 w-4 mt-0.5 shrink-0 ${C?"text-primary":"text-amber-600"}`}),e.jsx("span",{children:E})]},E))}),e.jsx(B,{className:"w-full",variant:C?"default":"outline",disabled:l||t,onClick:()=>p(y),children:l&&c===y?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),"Opening secure checkout…"]}):s?e.jsxs(e.Fragment,{children:[e.jsx(un,{className:"h-4 w-4 mr-2"}),"Upgrade to ",v]}):e.jsxs(e.Fragment,{children:[e.jsx(QM,{className:"h-4 w-4 mr-2"}),"Sign in & upgrade to ",v]})})]})]});return e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-[#f4f7fa] to-white",children:e.jsxs("div",{className:"container max-w-5xl py-10 px-4",children:[e.jsxs("div",{className:"text-center mb-10",children:[e.jsx("img",{src:GPe,alt:"LevelUp",className:"h-10 mx-auto mb-8"}),e.jsx(Oe,{variant:"outline",className:"mb-4 border-primary/40 text-primary",children:"Upgrade your membership"}),e.jsx("h1",{className:"text-3xl sm:text-4xl font-bold mb-3 text-[#2a4c64]",children:"Keep your momentum going"}),e.jsx("p",{className:"text-muted-foreground text-lg max-w-2xl mx-auto",children:s?"Choose your plan below — payment connects to your existing account and everything you set up stays right where you left it.":"Whether you're on a free trial or it just ended, sign in with your existing LevelUp account, choose your plan, and your payment connects right to it — nothing gets lost or duplicated."})]}),e.jsxs("div",{className:"max-w-md mx-auto mb-8",children:[e.jsx(J,{htmlFor:"upgrade-coupon",className:"text-sm font-medium",children:"Have a discount code?"}),e.jsx(xe,{id:"upgrade-coupon",placeholder:"Enter code (optional)",value:u,onChange:y=>h(y.target.value),className:"mt-1.5"})]}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-6 max-w-4xl mx-auto",children:[f("individual_agent","Individual Agent","$39","Perfect for solo agents ready to level up",n7s,e.jsx(In,{className:"h-6 w-6 text-primary"}),!0),f("brokerage_over_25","Brokerage","$499","For teams and brokerages",r7s,e.jsx(ai,{className:"h-6 w-6 text-amber-600"}),!1)]}),e.jsxs("div",{className:"mt-10 bg-white/70 border rounded-xl p-5 max-w-2xl mx-auto space-y-3",children:[e.jsx("p",{className:"text-sm font-medium text-center",children:"Questions before you upgrade? We're happy to help:"}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 justify-center",children:[e.jsxs("a",{href:"tel:1-866-527-8668",className:"flex items-center justify-center gap-2 text-primary hover:underline text-sm",children:[e.jsx(_a,{className:"h-4 w-4"}),e.jsx("span",{children:"1-866-527-8668"})]}),e.jsxs("a",{href:"mailto:support@relevelup.com",className:"flex items-center justify-center gap-2 text-primary hover:underline text-sm",children:[e.jsx(ln,{className:"h-4 w-4"}),e.jsx("span",{children:"support@relevelup.com"})]})]})]}),e.jsx("p",{className:"text-center text-xs text-muted-foreground mt-8",children:"Secure checkout powered by Stripe. Your existing account, listings, and settings are preserved."})]})})},i7s=Bj({viewerName:Zo().min(1,"Name is required").max(100,"Name must be less than 100 characters"),viewerEmail:Zo().email("Please enter a valid email").max(255,"Email must be less than 255 characters"),viewerPhone:Zo().max(20,"Phone must be less than 20 characters").optional(),message:Zo().min(1,"Message is required").max(1e3,"Message must be less than 1000 characters")});function o7s({shareToken:s,agentName:t,hasContact:n}){const[r,a]=_.useState(!1),[i,l]=_.useState(!1),[o,c]=_.useState(null),d=rPe({resolver:aPe(i7s),defaultValues:{viewerName:"",viewerEmail:"",viewerPhone:"",message:""}}),u=async h=>{a(!0),c(null);try{const{data:m,error:p}=await q.functions.invoke("video-reply-notify",{body:{shareToken:s,viewerName:h.viewerName,viewerEmail:h.viewerEmail,viewerPhone:h.viewerPhone||void 0,message:h.message}});if(p)throw new Error(p.message);if(!(m!=null&&m.success))throw new Error((m==null?void 0:m.error)||"Failed to send reply");l(!0)}catch(m){console.error("Failed to submit reply:",m),c(m.message||"Something went wrong. Please try again.")}finally{a(!1)}};return i?e.jsx(ve,{className:"border-2 border-primary/20 bg-gradient-to-br from-primary/5 to-primary/10",children:e.jsxs(Me,{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(Er,{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(ve,{children:[e.jsxs(bt,{className:"pb-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(Ou,{className:"h-5 w-5 text-primary"}),e.jsx(St,{className:"text-lg",children:"Reply to this video"})]}),e.jsx(kn,{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(Me,{children:e.jsx(cPe,{...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(Sf,{control:d.control,name:"viewerName",render:({field:h})=>e.jsxs(Yp,{children:[e.jsx(Zp,{children:"Your Name *"}),e.jsx(Xp,{children:e.jsx(xe,{placeholder:"John Smith",...h})}),e.jsx(ub,{})]})}),e.jsx(Sf,{control:d.control,name:"viewerEmail",render:({field:h})=>e.jsxs(Yp,{children:[e.jsx(Zp,{children:"Email *"}),e.jsx(Xp,{children:e.jsx(xe,{type:"email",placeholder:"john@example.com",...h})}),e.jsx(ub,{})]})})]}),!n&&e.jsx(Sf,{control:d.control,name:"viewerPhone",render:({field:h})=>e.jsxs(Yp,{children:[e.jsx(Zp,{children:"Phone (optional)"}),e.jsx(Xp,{children:e.jsx(xe,{type:"tel",placeholder:"(555) 123-4567",...h})}),e.jsx(ub,{})]})}),e.jsx(Sf,{control:d.control,name:"message",render:({field:h})=>e.jsxs(Yp,{children:[e.jsx(Zp,{children:"Message *"}),e.jsx(Xp,{children:e.jsx(Ms,{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(ub,{})]})}),o&&e.jsx("p",{className:"text-sm text-destructive",children:o}),e.jsx(B,{type:"submit",className:"w-full gap-2",disabled:r,children:r?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"h-4 w-4 animate-spin"}),"Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Or,{className:"h-4 w-4"}),"Send Message"]})})]})})})]})}const l7s=()=>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(Da,{className:"absolute top-[5%] left-[8%] w-6 h-6 text-blue-600/30 fill-blue-600/20"}),e.jsx(Da,{className:"absolute top-[15%] left-[20%] w-4 h-4 text-blue-600/25 fill-blue-600/15"}),e.jsx(Da,{className:"absolute top-[8%] left-[28%] w-5 h-5 text-blue-600/30 fill-blue-600/20"}),e.jsx(Da,{className:"absolute top-[25%] left-[12%] w-4 h-4 text-blue-600/20 fill-blue-600/10"}),e.jsx(Da,{className:"absolute top-[20%] right-[15%] w-5 h-5 text-red-500/25 fill-red-500/15 animate-pulse"}),e.jsx(qA,{className:"absolute bottom-[20%] right-[10%] w-12 h-12 text-blue-600/15 rotate-12"})]}),c7s=()=>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(un,{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(Da,{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(un,{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(Da,{className:"absolute bottom-[25%] left-[10%] w-6 h-6 text-blue-500/25 fill-blue-500/15 animate-pulse"}),e.jsx(Da,{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(qA,{className:"absolute top-[8%] left-[5%] w-10 h-10 text-red-500/20 rotate-12"})]}),d7s=()=>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(rS,{className:"w-20 h-20 text-pink-400 rotate-12"})}),e.jsx("div",{className:"absolute top-[2%] right-[8%] opacity-15",children:e.jsx(rS,{className:"w-16 h-16 text-rose-400 -rotate-12"})}),e.jsx("div",{className:"absolute bottom-[15%] left-[8%] opacity-15",children:e.jsx(rS,{className:"w-14 h-14 text-purple-400 rotate-45"})}),e.jsx("div",{className:"absolute bottom-[20%] right-[5%] opacity-20",children:e.jsx(rS,{className:"w-16 h-16 text-pink-300 -rotate-6"})}),e.jsx(Do,{className:"absolute top-[15%] left-[30%] w-5 h-5 text-rose-300/40 fill-rose-300/20 animate-pulse"}),e.jsx(Do,{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(Do,{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"})]}),u7s=()=>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(Hh,{className:"absolute top-[8%] left-[12%] w-12 h-12 text-blue-600/15"}),e.jsx(Da,{className:"absolute top-[15%] left-[22%] w-5 h-5 text-amber-500/25 fill-amber-500/15"}),e.jsx(Hh,{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(Da,{className:"absolute bottom-[25%] left-[15%] w-6 h-6 text-blue-500/20 fill-blue-500/10 animate-pulse"}),e.jsx(Da,{className:"absolute top-[20%] right-[22%] w-5 h-5 text-indigo-400/20 fill-indigo-400/10 animate-pulse",style:{animationDelay:"0.5s"}})]}),h7s=()=>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(rS,{className:"absolute top-[20%] left-[32%] w-7 h-7 text-purple-400/30"}),e.jsx(rS,{className:"absolute top-[12%] right-[28%] w-6 h-6 text-pink-400/30"}),e.jsx(Pq,{className:"absolute top-[18%] left-[52%] w-5 h-5 text-sky-400/35"})]}),m7s=()=>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(YO,{className:"absolute top-[5%] left-[10%] w-16 h-16 text-orange-400/25"}),e.jsx(YO,{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(un,{className:"absolute top-[8%] left-[55%] w-6 h-6 text-purple-400/35 animate-pulse"}),e.jsx(un,{className:"absolute bottom-[28%] right-[25%] w-5 h-5 text-orange-400/30 animate-pulse",style:{animationDelay:"0.5s"}})]}),p7s=()=>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(rP,{className:"absolute bottom-[8%] left-[5%] w-20 h-20 text-green-600/18"}),e.jsx(rP,{className:"absolute bottom-[12%] right-[8%] w-16 h-16 text-emerald-600/15"}),e.jsx(rP,{className:"absolute bottom-[10%] left-[28%] w-12 h-12 text-green-500/12"}),e.jsx(sj,{className:"absolute top-[5%] left-[15%] w-10 h-10 text-sky-300/30 animate-pulse"}),e.jsx(sj,{className:"absolute top-[10%] right-[20%] w-8 h-8 text-blue-300/25 animate-pulse",style:{animationDelay:"0.3s"}}),e.jsx(sj,{className:"absolute top-[18%] left-[45%] w-6 h-6 text-sky-200/25 animate-pulse",style:{animationDelay:"0.6s"}}),e.jsx(sj,{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(Da,{className:"absolute top-[3%] left-[50%] -translate-x-1/2 w-10 h-10 text-amber-400/35 fill-amber-400/25"})]}),f7s=()=>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(Do,{className:"absolute top-[8%] left-[55%] w-6 h-6 text-red-400/22 fill-red-400/12"}),e.jsx(Do,{className:"absolute top-[20%] right-[25%] w-5 h-5 text-orange-400/22 fill-orange-400/12"})]}),x7s=()=>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(Da,{className:"absolute top-[5%] left-[15%] w-12 h-12 text-yellow-400/35 fill-yellow-400/25 animate-pulse"}),e.jsx(Da,{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(Da,{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(Da,{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(un,{className:"absolute top-[3%] left-[50%] w-10 h-10 text-yellow-400/40"}),e.jsx(Ex,{className:"absolute bottom-[18%] left-[10%] w-12 h-12 text-purple-400/18 rotate-12"}),e.jsx(Ex,{className:"absolute bottom-[20%] right-[12%] w-10 h-10 text-amber-400/15 -rotate-12"})]}),g7s=()=>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(Da,{className:"absolute top-[8%] left-[50%] -translate-x-1/2 w-14 h-14 text-yellow-400/28 fill-yellow-400/18"}),e.jsx(un,{className:"absolute top-[5%] left-[20%] w-7 h-7 text-blue-400/35"}),e.jsx(un,{className:"absolute top-[10%] right-[18%] w-6 h-6 text-sky-400/30"})]}),y7s=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-green-900/12 via-emerald-900/6 to-teal-900/10"}),e.jsx(PA,{className:"absolute top-[5%] left-[10%] w-16 h-16 text-green-500/25"}),e.jsx(PA,{className:"absolute top-[8%] right-[12%] w-12 h-12 text-emerald-500/20"}),e.jsx(PA,{className:"absolute bottom-[18%] left-[12%] w-14 h-14 text-green-400/22"}),e.jsx(PA,{className:"absolute bottom-[22%] right-[10%] w-11 h-11 text-emerald-400/18"}),e.jsx("div",{className:"absolute top-[15%] left-[35%] w-6 h-6 rounded-full bg-yellow-500/30 border-2 border-yellow-600/25"}),e.jsx("div",{className:"absolute top-[20%] right-[28%] w-5 h-5 rounded-full bg-amber-500/25 border-2 border-amber-600/20"}),e.jsx("div",{className:"absolute bottom-[28%] left-[45%] w-5 h-5 rounded-full bg-yellow-400/25 border-2 border-yellow-500/20"}),e.jsx("div",{className:"absolute top-0 right-0 w-48 h-48 opacity-12 rounded-bl-full overflow-hidden",children:e.jsx("div",{className:"absolute inset-0 bg-gradient-to-bl from-red-400/60 via-yellow-400/60 to-green-400/60"})}),e.jsxs("div",{className:"absolute bottom-[10%] right-[5%] opacity-15",children:[e.jsx("div",{className:"w-12 h-8 bg-slate-700 rounded-b-full"}),e.jsx("div",{className:"absolute -top-1 left-1/2 -translate-x-1/2 w-10 h-3 bg-slate-600 rounded-full"}),e.jsxs("div",{className:"absolute top-0 left-1/2 -translate-x-1/2 flex gap-0.5",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-yellow-400"}),e.jsx("div",{className:"w-2 h-2 rounded-full bg-amber-400"}),e.jsx("div",{className:"w-2 h-2 rounded-full bg-yellow-400"})]})]})]}),v7s=()=>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(Da,{className:"absolute top-[5%] left-[42%] w-10 h-10 text-amber-400/30 fill-amber-400/20"}),e.jsx(Da,{className:"absolute top-[15%] right-[25%] w-7 h-7 text-yellow-400/25 fill-yellow-400/15"}),e.jsx(Hh,{className:"absolute bottom-[20%] right-[12%] w-12 h-12 text-blue-500/18"}),e.jsx(Hh,{className:"absolute top-[18%] left-[28%] w-8 h-8 text-indigo-400/15"}),e.jsx(qA,{className:"absolute top-[8%] left-[60%] w-10 h-10 text-indigo-400/18"})]}),b7s=()=>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(Bf,{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(Ex,{className:"absolute top-[8%] left-[45%] w-10 h-10 text-purple-400/22 rotate-12"}),e.jsx(Vo,{className:"absolute bottom-[18%] right-[15%] w-12 h-12 text-rose-400/18"})]}),_7s=()=>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(Do,{className:"absolute top-[5%] left-[10%] w-16 h-16 text-rose-400/28 fill-rose-400/18"}),e.jsx(Do,{className:"absolute top-[8%] right-[12%] w-14 h-14 text-pink-400/25 fill-pink-400/15"}),e.jsx(Do,{className:"absolute bottom-[15%] left-[12%] w-12 h-12 text-red-400/22 fill-red-400/12"}),e.jsx(Do,{className:"absolute bottom-[18%] right-[10%] w-13 h-13 text-rose-300/25 fill-rose-300/15"}),e.jsx(Do,{className:"absolute top-[15%] left-[30%] w-6 h-6 text-pink-300/35 fill-pink-300/20 animate-pulse"}),e.jsx(Do,{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(Do,{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(Do,{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"})]}),w7s=()=>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(fN,{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(fN,{className:"absolute top-[15%] left-[18%] w-10 h-10 text-yellow-400/30"}),e.jsx(un,{className:"absolute top-[10%] left-[42%] w-7 h-7 text-amber-400/35"}),e.jsx(fN,{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"})]}),j7s=()=>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(Jr,{className:"absolute top-[8%] left-[10%] w-14 h-14 text-teal-500/22"}),e.jsx(Jr,{className:"absolute bottom-[15%] right-[8%] w-16 h-16 text-emerald-500/18"}),e.jsx(_b,{className:"absolute top-[12%] right-[18%] w-10 h-10 text-amber-400/25"}),e.jsx(_b,{className:"absolute bottom-[22%] left-[22%] w-8 h-8 text-yellow-400/22"}),e.jsx(Do,{className:"absolute top-[18%] left-[40%] w-6 h-6 text-rose-400/22 fill-rose-400/12"}),e.jsx(Do,{className:"absolute top-[22%] right-[35%] w-5 h-5 text-teal-400/20 fill-teal-400/10"}),e.jsx(un,{className:"absolute top-[5%] left-[55%] w-8 h-8 text-teal-400/30"}),e.jsx(Ex,{className:"absolute bottom-[20%] left-[48%] w-10 h-10 text-cyan-400/18 rotate-12"})]}),N7s=()=>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(Ex,{className:"absolute top-[5%] left-[12%] w-14 h-14 text-emerald-400/25 rotate-12"}),e.jsx(Ex,{className:"absolute top-[8%] right-[10%] w-12 h-12 text-teal-400/22 -rotate-12"}),e.jsx(_b,{className:"absolute bottom-[18%] left-[18%] w-12 h-12 text-amber-400/25"}),e.jsx(Jr,{className:"absolute bottom-[15%] right-[12%] w-14 h-14 text-teal-500/18"}),e.jsx(un,{className:"absolute top-[15%] left-[42%] w-10 h-10 text-emerald-400/35"}),e.jsx(un,{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"})]}),k7s=()=>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(_b,{className:"absolute bottom-[12%] left-[50%] -translate-x-1/2 w-24 h-24 text-amber-400/25 rotate-45"}),e.jsx(_b,{className:"absolute top-[10%] left-[12%] w-10 h-10 text-yellow-400/30"}),e.jsx(_b,{className:"absolute top-[12%] right-[15%] w-9 h-9 text-amber-300/25"}),e.jsx(Jr,{className:"absolute top-[8%] left-[42%] w-12 h-12 text-teal-500/18"}),e.jsx(Ex,{className:"absolute bottom-[22%] right-[18%] w-12 h-12 text-orange-400/18 rotate-12"}),e.jsx(un,{className:"absolute top-[5%] right-[35%] w-8 h-8 text-yellow-400/35"}),e.jsx(Da,{className:"absolute top-[18%] left-[28%] w-6 h-6 text-amber-400/25 fill-amber-400/15"})]}),S7s=()=>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(Jr,{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(_b,{className:"absolute top-[10%] right-[12%] w-10 h-10 text-amber-400/28"}),e.jsx(Do,{className:"absolute top-[8%] left-[18%] w-8 h-8 text-rose-400/25 fill-rose-400/15"}),e.jsx(un,{className:"absolute top-[12%] left-[45%] w-8 h-8 text-teal-400/30"}),e.jsx(dN,{className:"absolute top-[15%] right-[28%] w-10 h-10 text-emerald-400/20"})]}),Xxt=()=>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"})]}),C7s=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(Do,{className:"absolute top-6 left-[12%] w-4 h-4 text-rose-300/50 fill-rose-300/30 animate-pulse"}),e.jsx(Do,{className:"absolute top-10 right-[18%] w-3 h-3 text-pink-300/50 fill-pink-300/30 animate-pulse delay-150"}),e.jsx(Do,{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(Do,{className:"absolute top-14 right-[35%] w-3.5 h-3.5 text-pink-300/40 fill-pink-300/20 animate-pulse delay-200"})]}),A7s=()=>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-blue-400/50 animate-pulse"}),e.jsx(un,{className:"absolute top-10 right-[15%] w-3 h-3 text-amber-400/50 animate-pulse delay-100"}),e.jsx(Jr,{className:"absolute top-8 left-[38%] w-3 h-3 text-teal-300/40 animate-pulse delay-200"})]}),E7s=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(H4,{className:"absolute top-5 left-[12%] w-4 h-4 text-amber-500/50 animate-pulse"}),e.jsx(Gq,{className:"absolute top-10 right-[15%] w-3 h-3 text-rose-400/50 animate-pulse delay-100"}),e.jsx(H4,{className:"absolute top-8 left-[40%] w-3 h-3 text-amber-400/40 animate-pulse delay-200"})]}),$Y=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(un,{className:"absolute top-5 left-[10%] w-4 h-4 text-emerald-400/50 animate-pulse"}),e.jsx(Ex,{className:"absolute top-10 right-[12%] w-5 h-5 text-amber-400/50 animate-pulse delay-150"}),e.jsx(un,{className:"absolute top-8 left-[45%] w-3 h-3 text-sky-400/40 animate-pulse delay-300"})]}),Qxt=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(Jr,{className:"absolute top-6 left-[12%] w-4 h-4 text-teal-400/40 animate-pulse"}),e.jsx(un,{className:"absolute top-10 right-[15%] w-3 h-3 text-emerald-400/50 animate-pulse delay-100"}),e.jsx(Jr,{className:"absolute top-4 right-[40%] w-3 h-3 text-cyan-400/30 animate-pulse delay-200"})]}),_Ve=[{id:"default",name:"Classic",description:"Clean, professional look for any occasion",icon:e.jsx(un,{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(Do,{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(C7s,{})},{id:"thinking_of_you",name:"Thinking of You",description:"Let them know they're on your mind",icon:e.jsx(_Q,{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($Y,{})},{id:"check_in",name:"Check-in",description:"Touch base with your contacts",icon:e.jsx(H4,{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(E7s,{})},{id:"market_update",name:"Market Update",description:"Share real estate market insights",icon:e.jsx(bl,{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(In,{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($Y,{})},{id:"congratulations",name:"Congratulations",description:"Celebrate their achievements",icon:e.jsx(Hh,{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(Xxt,{})},{id:"welcome_neighborhood",name:"Welcome to the Neighborhood",description:"Greet new neighbors",icon:e.jsx(Xa,{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(Qxt,{})},{id:"just_because",name:"Just Because",description:"No reason needed to connect",icon:e.jsx(Gq,{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($Y,{})},{id:"birthday",name:"Birthday",description:"Celebrate their special day",icon:e.jsx(Bf,{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(b7s,{})},{id:"valentines_day",name:"Valentine's Day",description:"Show appreciation on this special day",icon:e.jsx(Do,{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(_7s,{})},{id:"groundhog_day",name:"Groundhog Day",description:"A fun seasonal greeting",icon:e.jsx(fN,{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(w7s,{})},{id:"new_years",name:"New Year's Day",description:"Ring in the new year",icon:e.jsx(Da,{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(x7s,{})},{id:"easter",name:"Easter",description:"Celebrate the spring season",icon:e.jsx(Pq,{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(h7s,{})},{id:"mothers_day",name:"Mother's Day",description:"Celebrate the amazing moms",icon:e.jsx(rS,{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(d7s,{})},{id:"fathers_day",name:"Father's Day",description:"Celebrate the amazing dads",icon:e.jsx(Hh,{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(u7s,{})},{id:"memorial_day",name:"Memorial Day",description:"Honor those who served",icon:e.jsx(qA,{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(l7s,{})},{id:"independence_day",name:"4th of July",description:"Celebrate Independence Day",icon:e.jsx(gu,{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(c7s,{})},{id:"labor_day",name:"Labor Day",description:"Celebrate the workers",icon:e.jsx(Hh,{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(v7s,{})},{id:"halloween",name:"Halloween",description:"Spooky seasonal greetings",icon:e.jsx(YO,{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(m7s,{})},{id:"thanksgiving",name:"Thanksgiving",description:"Express gratitude this season",icon:e.jsx(Do,{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(f7s,{})},{id:"christmas",name:"Christmas",description:"Spread holiday cheer",icon:e.jsx(rP,{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(p7s,{})},{id:"hanukkah",name:"Hanukkah",description:"Celebrate the Festival of Lights",icon:e.jsx(un,{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(g7s,{})},{id:"st_patricks_day",name:"St. Patrick's Day",description:"Celebrate the luck of the Irish",icon:e.jsx(PA,{className:"h-5 w-5"}),category:"holidays",headerText:s=>s?`Happy St. Patrick's Day, ${s}!`:"Happy St. Patrick's Day!",subText:"Wishing you the luck of the Irish!",gradientClasses:"from-green-50/70 via-emerald-50/50 to-teal-50/40 dark:from-green-950/30 dark:via-emerald-950/20 dark:to-teal-950/20",accentColor:"green",decorativeElement:e.jsx(y7s,{})},{id:"home_anniversary",name:"Home Anniversary",description:"Celebrate their home ownership milestone",icon:e.jsx(Jr,{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(j7s,{})},{id:"under_contract",name:"Under Contract",description:"Celebrate this exciting milestone",icon:e.jsx(Ex,{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(N7s,{})},{id:"just_listed",name:"Just Listed",description:"Announce a new listing",icon:e.jsx(ga,{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(Qxt,{})},{id:"just_sold",name:"Just Sold",description:"Celebrate a successful sale",icon:e.jsx(yd,{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($Y,{})},{id:"price_reduction",name:"Price Reduction",description:"Notify about a price change",icon:e.jsx(gS,{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(dN,{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(A7s,{})},{id:"closing_day",name:"Closing Day",description:"Celebrate their closing day",icon:e.jsx(_b,{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(k7s,{})},{id:"move_in_day",name:"Move-in Day",description:"Welcome them to their new home",icon:e.jsx(Jr,{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(S7s,{})},{id:"offer_accepted",name:"Offer Accepted",description:"Celebrate their accepted offer",icon:e.jsx(Fg,{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($Y,{})},{id:"pre_approval",name:"Pre-Approval Congrats",description:"Congratulate on pre-approval",icon:e.jsx(Hh,{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(Xxt,{})}],T7s=[{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 M7s(s){return _Ve.filter(t=>t.category===s)}function k$(s){return _Ve.find(t=>t.id===s)||_Ve[0]}function Jxt(){const{shareToken:s,recipientToken:t}=Li(),[n,r]=_.useState(null),[a,i]=_.useState(null),[l,o]=_.useState(null),[c,d]=_.useState(!0),[u,h]=_.useState(null),[m,p]=_.useState(!0),f=_.useRef(null),y=_.useRef(0),v=_.useRef(0),g=(()=>{const V=new URLSearchParams(window.location.search);return t||V.get("rt")||null})(),b=_.useCallback((V,G=!1)=>{if(!g||V<=0)return;const $=Math.max(1,Math.round(V));if($<=v.current)return;const Y=`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/track-video-share?t=${encodeURIComponent(g)}&e=watch&ws=${$}`;G&&navigator.sendBeacon?navigator.sendBeacon(Y):fetch(Y,{method:"GET",keepalive:G}).catch(()=>{}),v.current=Math.max(v.current,$)},[g]);_.useEffect(()=>{var ne;if(!m||!(n!=null&&n.playback_url)||!g)return;let V=!1;const G=()=>{y.current>0&&b(y.current,!0)},$=()=>{document.visibilityState==="hidden"&&G()},H=()=>{G()},Y=()=>{var ie;if(V||!f.current||!((ie=window.playerjs)!=null&&ie.Player))return;const ce=new window.playerjs.Player(f.current);ce.on("timeupdate",te=>{const ae=Math.floor(Number((te==null?void 0:te.seconds)??0));!Number.isFinite(ae)||ae<=0||(y.current=Math.max(y.current,ae))}),ce.on("pause",()=>{y.current>0&&b(y.current)}),ce.on("ended",()=>{y.current>0&&b(y.current,!0)})},Z=document.querySelector('script[data-bunny-playerjs="true"]');if((ne=window.playerjs)!=null&&ne.Player)Y();else if(Z)Z.addEventListener("load",Y,{once:!0});else{const ce=document.createElement("script");ce.src="https://assets.mediadelivery.net/playerjs/playerjs-latest.min.js",ce.async=!0,ce.defer=!0,ce.dataset.bunnyPlayerjs="true",ce.onload=Y,document.body.appendChild(ce)}return document.addEventListener("visibilitychange",$),window.addEventListener("beforeunload",H),()=>{V=!0,document.removeEventListener("visibilitychange",$),window.removeEventListener("beforeunload",H),G()}},[m,n==null?void 0:n.playback_url,g,b]),_.useEffect(()=>{y.current=0,v.current=0},[g,s]),_.useEffect(()=>{const V=()=>{['[id*="lc_text_widget"]','[class*="lc-text-widget"]','[id*="chat-widget"]','[class*="chat-widget"]','iframe[src*="widgets.leadconnectorhq"]','iframe[src*="msgsndr"]',"[data-chat-widget]"].forEach(Y=>{document.querySelectorAll(Y).forEach(Z=>{Z.style.display="none"})})};V();const G=[setTimeout(V,500),setTimeout(V,1500),setTimeout(V,3e3)],$=new MutationObserver(V);return $.observe(document.body,{childList:!0,subtree:!0}),()=>{G.forEach(clearTimeout),$.disconnect()}},[]),_.useEffect(()=>{(async()=>{if(!s){h("Invalid share link"),d(!1);return}const{data:G,error:$}=await q.from("agent_videos").select("id, title, playback_url, thumbnail_url, preview_url, duration_seconds, share_token, owner_user_id, contact_id, page_template, recipient_name").eq("share_token",s).eq("is_deleted",!1).single();if($||!G){h("Video not found or has been removed"),d(!1);return}r(G);try{await q.rpc("log_video_view",{p_video_id:G.id,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null})}catch(H){console.warn("Failed to log video view:",H)}if(G.owner_user_id){const{data:H}=await q.from("profiles").select("id, name, email, phone").eq("id",G.owner_user_id).single();if(H){i(H);try{const{data:Y}=await q.storage.from("avatars").list(`${G.owner_user_id}`);if(Y&&Y.length>0){const{data:Z}=q.storage.from("avatars").getPublicUrl(`${G.owner_user_id}/${Y[0].name}`);o(Z.publicUrl)}}catch{}}}d(!1)})()},[s]);const j=V=>{if(!V)return"0:00";const G=Math.floor(V/60),$=V%60;return`${G}:${$.toString().padStart(2,"0")}`},S=V=>V.includes("iframe.mediadelivery.net/play/")?V.replace("/play/","/embed/")+"?autoplay=true&responsive=true":V,C=V=>{if(!V)return"?";const G=V.split(" ");return G.length>=2?`${G[0][0]}${G[1][0]}`.toUpperCase():V.substring(0,2).toUpperCase()},E=k$((n==null?void 0:n.page_template)||"default"),P=(n==null?void 0:n.recipient_name)||null,M=E.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(Ct,{className:"h-8 w-8 animate-spin text-primary"})});if(u||!n)return e.jsx("div",{className:"min-h-screen bg-background flex items-center justify-center p-4",children:e.jsx(ve,{className:"max-w-md w-full",children:e.jsxs(Me,{className:"py-12 text-center",children:[e.jsx(Kr,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"Video Not Found"}),e.jsx("p",{className:"text-muted-foreground",children:u||"This video is no longer available."})]})})});const O=E.id!=="default";return e.jsxs(e.Fragment,{children:[e.jsxs(ul,{children:[e.jsx("title",{children:M}),e.jsx("meta",{name:"description",content:E.subText}),e.jsx("meta",{property:"og:title",content:M}),e.jsx("meta",{property:"og:description",content:E.subText}),e.jsx("meta",{property:"og:type",content:"video.other"}),e.jsx("meta",{property:"og:url",content:D}),n.preview_url&&e.jsx("meta",{property:"og:image",content:n.preview_url}),!n.preview_url&&n.thumbnail_url&&e.jsx("meta",{property:"og:image",content:n.thumbnail_url}),n.playback_url&&e.jsxs(e.Fragment,{children:[e.jsx("meta",{property:"og:video",content:n.playback_url}),e.jsx("meta",{property:"og:video:type",content:"text/html"}),e.jsx("meta",{property:"og:video:width",content:"1280"}),e.jsx("meta",{property:"og:video:height",content:"720"})]}),e.jsx("meta",{name:"twitter:card",content:"player"}),e.jsx("meta",{name:"twitter:title",content:M}),e.jsx("meta",{name:"twitter:description",content:E.subText}),n.preview_url&&e.jsx("meta",{name:"twitter:image",content:n.preview_url}),n.playback_url&&e.jsxs(e.Fragment,{children:[e.jsx("meta",{name:"twitter:player",content:n.playback_url}),e.jsx("meta",{name:"twitter:player:width",content:"1280"}),e.jsx("meta",{name:"twitter:player:height",content:"720"})]})]}),e.jsxs("div",{className:At("min-h-screen flex items-center justify-center p-4 bg-gradient-to-b relative",E.gradientClasses),children:[O&&E.decorativeElement,e.jsxs("div",{className:"max-w-2xl w-full space-y-6 relative z-10",children:[O&&e.jsxs("div",{className:"text-center py-4 animate-fade-in",children:[e.jsx("div",{className:"flex justify-center mb-3",children:e.jsx("div",{className:At("w-14 h-14 rounded-full flex items-center justify-center shadow-sm",E.accentColor==="primary"&&"bg-primary/10 text-primary",E.accentColor==="amber"&&"bg-amber-100 text-amber-600 dark:bg-amber-900/50 dark:text-amber-400",E.accentColor==="teal"&&"bg-teal-100 text-teal-600 dark:bg-teal-900/50 dark:text-teal-400",E.accentColor==="rose"&&"bg-rose-100 text-rose-600 dark:bg-rose-900/50 dark:text-rose-400",E.accentColor==="emerald"&&"bg-emerald-100 text-emerald-600 dark:bg-emerald-900/50 dark:text-emerald-400",E.accentColor==="yellow"&&"bg-yellow-100 text-yellow-600 dark:bg-yellow-900/50 dark:text-yellow-400",E.accentColor==="pink"&&"bg-pink-100 text-pink-600 dark:bg-pink-900/50 dark:text-pink-400",E.accentColor==="blue"&&"bg-blue-100 text-blue-600 dark:bg-blue-900/50 dark:text-blue-400",E.accentColor==="red"&&"bg-red-100 text-red-600 dark:bg-red-900/50 dark:text-red-400",E.accentColor==="orange"&&"bg-orange-100 text-orange-600 dark:bg-orange-900/50 dark:text-orange-400",E.accentColor==="green"&&"bg-green-100 text-green-600 dark:bg-green-900/50 dark:text-green-400",E.accentColor==="violet"&&"bg-violet-100 text-violet-600 dark:bg-violet-900/50 dark:text-violet-400",E.accentColor==="sky"&&"bg-sky-100 text-sky-600 dark:bg-sky-900/50 dark:text-sky-400"),children:e.jsx("div",{className:"scale-150",children:E.icon})})}),e.jsx("h1",{className:"text-2xl sm:text-3xl font-bold mb-2",children:M}),e.jsx("p",{className:"text-muted-foreground",children:E.subText})]}),a&&e.jsxs("div",{className:"flex items-center gap-4 p-4 bg-card/90 backdrop-blur-sm rounded-lg border shadow-sm",children:[e.jsxs(ja,{className:"h-14 w-14 border-2 border-primary/20",children:[e.jsx(pi,{src:l||void 0,alt:a.name||"Agent"}),e.jsx(Na,{className:"bg-primary/10 text-primary font-semibold",children:C(a.name)})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:O?"A special video from":"A personal video from"}),e.jsx("h2",{className:"text-lg font-semibold truncate",children:a.name||"Your Agent"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Your Real Estate Professional"})]}),e.jsxs("div",{className:"flex gap-2 shrink-0",children:[a.phone&&e.jsx(B,{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(_a,{className:"h-4 w-4"})})}),a.email&&e.jsx(B,{variant:"outline",size:"icon",asChild:!0,className:"h-10 w-10",children:e.jsx("a",{href:`mailto:${a.email}`,"aria-label":"Email agent",children:e.jsx(ln,{className:"h-4 w-4"})})})]})]}),e.jsx(ve,{className:"overflow-hidden shadow-lg",children:m&&n.playback_url?e.jsx("div",{className:"relative w-full",style:{paddingBottom:"56.25%"},children:e.jsx("iframe",{ref:f,src:S(n.playback_url),title:n.title||"Video message",className:"absolute top-0 left-0 w-full h-full",style:{border:0},allow:"accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture",allowFullScreen:!0})}):e.jsxs("div",{className:"relative aspect-video bg-muted cursor-pointer group",onClick:()=>p(!0),children:[n.preview_url||n.thumbnail_url?e.jsx("img",{src:n.preview_url||n.thumbnail_url||"",alt:n.title?`${n.title} video preview`:"Video message preview",className:"w-full h-full object-cover",onError:V=>{var $;V.currentTarget.style.display="none";const G=($=V.currentTarget.parentElement)==null?void 0:$.querySelector(".video-fallback");G&&(G.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(Kr,{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(Jd,{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:j(n.duration_seconds)})]})}),!O&&e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold",children:n.title||"Video Message"}),e.jsx("p",{className:"text-muted-foreground mt-2",children:m?"Enjoy the video!":"Click to play the video"})]}),!m&&e.jsx("div",{className:"flex justify-center",children:e.jsxs(B,{size:"lg",onClick:()=>p(!0),className:"gap-2",children:[e.jsx(Jd,{className:"h-5 w-5"}),"Watch Video"]})}),e.jsx(o7s,{shareToken:s,agentName:(a==null?void 0:a.name)||null,hasContact:!!n.contact_id})]})]})]})}function P7s(){return _.useEffect(()=>(document.body.classList.add("video-landing-page"),()=>{document.body.classList.remove("video-landing-page")}),[]),e.jsx(rQe,{})}function L7s(){const{token:s}=Li();return _.useEffect(()=>{if(!s)return;const t=`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/video-og-image?token=${s}`;window.location.replace(t)},[s]),e.jsx("main",{className:"min-h-screen bg-background flex items-center justify-center",children:e.jsxs("div",{className:"flex items-center gap-3 text-muted-foreground",children:[e.jsx(Ct,{className:"h-5 w-5 animate-spin"}),e.jsx("span",{children:"Loading video preview…"})]})})}const I7s=[{key:"residential",title:"Residential",tagline:"Homes, condos, land & luxury",path:"/mission-control/listings/new/residential",icon:Jr,points:["Standard listing details","Listing Exchange & referrals","Single-property site & marketing"]},{key:"commercial",title:"Commercial",tagline:"Investment, office, retail, industrial & land",path:"/mission-control/listings/new/commercial",icon:ai,points:["Pitch Mode to win the assignment","Institutional-grade microsite","Gated OM & investor tracking"],featured:!0}];function D7s(){const s=Fn(),{search:t}=ru();return e.jsx("div",{className:"min-h-screen bg-background",children:e.jsxs("div",{className:"mx-auto max-w-5xl px-4 py-10",children:[e.jsxs(B,{variant:"ghost",size:"sm",className:"mb-6 -ml-2",onClick:()=>s("/mission-control/listings"),children:[e.jsx(ka,{className:"mr-2 h-4 w-4"})," Listing Exchange"]}),e.jsxs("div",{className:"mb-10",children:[e.jsx("p",{className:"text-xs font-medium uppercase tracking-[0.2em] text-muted-foreground",children:"New listing"}),e.jsx("h1",{className:"mt-2 text-3xl font-semibold tracking-tight md:text-4xl",children:"What are you marketing?"}),e.jsx("p",{className:"mt-2 max-w-xl text-muted-foreground",children:"Choose the workflow that fits. Commercial unlocks Pitch Mode, investment metrics and the Commercial Launch marketing workspace."})]}),e.jsx("div",{className:"grid gap-5 md:grid-cols-2",children:I7s.map(n=>{const r=n.icon;return e.jsxs("button",{onClick:()=>s(`${n.path}${t}`),className:`group relative overflow-hidden rounded-2xl border p-7 text-left transition-all hover:-translate-y-0.5 hover:shadow-xl ${n.featured?"border-primary/40 bg-gradient-to-br from-primary/[0.07] to-transparent":"bg-card"}`,children:[n.featured&&e.jsxs("span",{className:"absolute right-5 top-5 inline-flex items-center gap-1 rounded-full border border-primary/30 bg-primary/10 px-2.5 py-1 text-[10px] font-semibold uppercase tracking-wider text-primary",children:[e.jsx(un,{className:"h-3 w-3"})," Commercial Launch"]}),e.jsx("div",{className:"mb-5 flex h-12 w-12 items-center justify-center rounded-xl border bg-background",children:e.jsx(r,{className:"h-6 w-6"})}),e.jsx("h2",{className:"text-xl font-semibold",children:n.title}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:n.tagline}),e.jsx("ul",{className:"mt-5 space-y-2 text-sm text-muted-foreground",children:n.points.map(a=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"mt-[7px] h-1 w-1 shrink-0 rounded-full bg-foreground/40"}),a]},a))}),e.jsxs("span",{className:"mt-6 inline-flex items-center gap-1 text-sm font-medium text-primary",children:["Continue ",e.jsx(La,{className:"h-4 w-4 transition-transform group-hover:translate-x-0.5"})]})]},n.key)})})]})})}const _9t=()=>at({queryKey:["listing-exchange-enabled"],queryFn:async()=>{const{data:s,error:t}=await q.from("feature_flags").select("enabled").eq("key","listing_exchange_enabled").maybeSingle();if(t)throw t;return(s==null?void 0:s.enabled)??!1}}),w9t=s=>{const{user:t,brokerageId:n}=hs();return at({queryKey:["listings",s,n],queryFn:async()=>{let r=q.from("listings").select(` *, photos:listing_photos(*), commercial:commercial_listing_details(*), agent:profiles!listings_agent_id_fkey(id, name, email, brokerage_id, brokerage:brokerages(name)) `).eq("is_approved",!0).eq("is_public",!0).or("lifecycle_stage.is.null,lifecycle_stage.neq.pitch");s!=null&&s.listingClass&&(r=r.eq("listing_class",s.listingClass)),s!=null&&s.status?r=r.eq("status",s.status):r=r.neq("status","sold"),s!=null&&s.propertyType&&(r=r.eq("property_type",s.propertyType)),s!=null&&s.city&&(r=r.ilike("city",`%${s.city}%`)),s!=null&&s.minPrice&&(r=r.gte("price",s.minPrice)),s!=null&&s.maxPrice&&(r=r.lte("price",s.maxPrice)),s!=null&&s.openToReferrals&&(r=r.eq("open_to_referrals",!0));const{data:a,error:i}=await r;if(i)throw i;let l=a||[];if(n){const{data:o}=await q.from("profiles").select("id").eq("brokerage_id",n);if(o&&o.length>0){const c=o.map(h=>h.id);let d=q.from("listings").select(` *, photos:listing_photos(*), commercial:commercial_listing_details(*), agent:profiles!listings_agent_id_fkey(id, name, email, brokerage_id, brokerage:brokerages(name)) `).eq("is_approved",!0).eq("share_with_brokerage",!0).eq("is_public",!1).eq("site_only",!1).in("agent_id",c).or("lifecycle_stage.is.null,lifecycle_stage.neq.pitch");s!=null&&s.listingClass&&(d=d.eq("listing_class",s.listingClass)),s!=null&&s.status?d=d.eq("status",s.status):d=d.neq("status","sold"),s!=null&&s.propertyType&&(d=d.eq("property_type",s.propertyType)),s!=null&&s.city&&(d=d.ilike("city",`%${s.city}%`)),s!=null&&s.minPrice&&(d=d.gte("price",s.minPrice)),s!=null&&s.maxPrice&&(d=d.lte("price",s.maxPrice)),s!=null&&s.openToReferrals&&(d=d.eq("open_to_referrals",!0));const{data:u}=await d;if(u){const h=new Set(l.map(p=>p.id)),m=u.filter(p=>!h.has(p.id));l=[...l,...m]}}}switch(s==null?void 0:s.sortBy){case"updated":l.sort((o,c)=>new Date(c.updated_at).getTime()-new Date(o.updated_at).getTime());break;case"price_asc":l.sort((o,c)=>o.price-c.price);break;case"price_desc":l.sort((o,c)=>c.price-o.price);break;default:l.sort((o,c)=>new Date(c.created_at).getTime()-new Date(o.created_at).getTime())}return l.map(o=>tet(eet(o)))}})};function eet(s){return s&&Array.isArray(s.commercial)&&(s.commercial=s.commercial[0]??null),s}function tet(s){return Array.isArray(s==null?void 0:s.photos)&&(s.photos=[...s.photos].sort((t,n)=>(t.sort_order??0)-(n.sort_order??0)||(n.is_primary?1:0)-(t.is_primary?1:0))),s}const set=()=>{const{user:s}=hs();return at({queryKey:["my-listings",s==null?void 0:s.id],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("listings").select(` *, photos:listing_photos(*), commercial:commercial_listing_details(*) `).eq("agent_id",s.id).order("created_at",{ascending:!1});if(n)throw n;return t.map(r=>tet(eet(r)))},enabled:!!s})},eae=s=>{const{user:t}=hs();return at({queryKey:["listing",s],queryFn:async()=>{const{data:n,error:r}=await q.from("listings").select(` *, photos:listing_photos(*), commercial:commercial_listing_details(*), agent:profiles!listings_agent_id_fkey(id, name, email, brokerage_id, brokerage:brokerages(name)), video:agent_videos!listings_video_id_fkey(id, playback_url, thumbnail_url, title, duration_seconds) `).eq("id",s).single();if(r)throw r;return t&&await q.from("listing_views").insert({listing_id:s,viewer_id:t.id}),tet(eet(n))},enabled:!!s})},j9t=()=>{const s=Bt(),{user:t}=hs();return mt({mutationFn:async n=>{if(!t)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("listings").insert({...n,agent_id:t.id}).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["listings"]}),s.invalidateQueries({queryKey:["my-listings"]})}})},R7s=()=>{const s=Bt();return mt({mutationFn:async({agentId:t,...n})=>{const{data:r,error:a}=await q.from("listings").insert({...n,agent_id:t}).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["listings"]}),s.invalidateQueries({queryKey:["my-listings"]}),s.invalidateQueries({queryKey:["brokerage-listings"]})}})},N9t=()=>{const s=Bt();return mt({mutationFn:async({id:t,...n})=>{const r=n.is_public===!0?{...n,is_approved:!0}:{...n},{data:a,error:i}=await q.from("listings").update(r).eq("id",t).select().single();if(i)throw i;return a},onSuccess:t=>{s.invalidateQueries({queryKey:["listings"]}),s.invalidateQueries({queryKey:["my-listings"]}),s.invalidateQueries({queryKey:["listing",t.id]})}})},k9t=()=>{const s=Bt();return mt({mutationFn:async t=>{const{error:n}=await q.from("listings").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["listings"]}),s.invalidateQueries({queryKey:["my-listings"]})}})},S9t=()=>{const s=Bt();return mt({mutationFn:async({listingId:t,photoUrl:n,isPrimary:r=!1})=>{const{data:a,error:i}=await q.from("listing_photos").insert({listing_id:t,photo_url:n,is_primary:r}).select().single();if(i)throw i;return a},onSuccess:t=>{s.invalidateQueries({queryKey:["listing",t.listing_id]}),s.invalidateQueries({queryKey:["my-listings"]})}})},C9t=()=>{const s=Bt();return mt({mutationFn:async({photoId:t,listingId:n})=>{const{error:r}=await q.from("listing_photos").delete().eq("id",t);if(r)throw r;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["listing",t]}),s.invalidateQueries({queryKey:["my-listings"]})}})},A9t=()=>{const s=Bt();return mt({mutationFn:async({photos:t})=>{var i;const n=t.map(l=>q.from("listing_photos").update({sort_order:l.sort_order,is_primary:l.is_primary}).eq("id",l.id)),a=(i=(await Promise.all(n)).find(l=>l.error))==null?void 0:i.error;if(a)throw a;return t},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["listing"]}),s.invalidateQueries({queryKey:["my-listings"]})}})},E9t=()=>{const s=Bt();return mt({mutationFn:async({photoId:t,listingId:n})=>{const{error:r}=await q.from("listing_photos").update({is_primary:!1}).eq("listing_id",n);if(r)throw r;const{error:a}=await q.from("listing_photos").update({is_primary:!0}).eq("id",t);if(a)throw a;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["listing",t]}),s.invalidateQueries({queryKey:["my-listings"]})}})},F7s=()=>{const{user:s}=hs();return at({queryKey:["saved-listings",s==null?void 0:s.id],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("listing_saves").select(` *, listing:listings( *, photos:listing_photos(*), agent:profiles!listings_agent_id_fkey(id, name, email, brokerage_id) ) `).eq("agent_id",s.id);if(n)throw n;return t},enabled:!!s})},T9t=()=>{const s=Bt(),{user:t}=hs();return mt({mutationFn:async n=>{if(!t)throw new Error("Not authenticated");const{data:r}=await q.from("listing_saves").select("id").eq("listing_id",n).eq("agent_id",t.id).maybeSingle();return r?(await q.from("listing_saves").delete().eq("id",r.id),{saved:!1}):(await q.from("listing_saves").insert({listing_id:n,agent_id:t.id}),{saved:!0})},onSuccess:()=>{s.invalidateQueries({queryKey:["saved-listings"]}),s.invalidateQueries({queryKey:["listings"]})}})},M9t=s=>{const{user:t}=hs();return at({queryKey:["listing-saved",s,t==null?void 0:t.id],queryFn:async()=>{if(!t)return!1;const{data:n}=await q.from("listing_saves").select("id").eq("listing_id",s).eq("agent_id",t.id).maybeSingle();return!!n},enabled:!!t&&!!s})},O7s=()=>{const s=Bt(),{user:t}=hs();return mt({mutationFn:async n=>{if(!t)throw new Error("Not authenticated");const{data:r}=await q.from("listing_follows").select("id").eq("listing_id",n).eq("agent_id",t.id).maybeSingle();return r?(await q.from("listing_follows").delete().eq("id",r.id),{following:!1}):(await q.from("listing_follows").insert({listing_id:n,agent_id:t.id}),{following:!0})},onSuccess:()=>{s.invalidateQueries({queryKey:["listing-following"]})}})},z7s=s=>{const{user:t}=hs();return at({queryKey:["listing-following",s,t==null?void 0:t.id],queryFn:async()=>{if(!t)return!1;const{data:n}=await q.from("listing_follows").select("id").eq("listing_id",s).eq("agent_id",t.id).maybeSingle();return!!n},enabled:!!t&&!!s})},B7s=()=>{const{user:s}=hs();return mt({mutationFn:async({listingId:t,shareType:n})=>{if(!s)throw new Error("Not authenticated");const{error:r}=await q.from("listing_shares").insert({listing_id:t,sharing_agent_id:s.id,share_type:n});if(r)throw r}})},U7s=()=>{const{user:s}=hs();return at({queryKey:["my-referrals",s==null?void 0:s.id],queryFn:async()=>{if(!s)return{sent:[],received:[]};const[t,n]=await Promise.all([q.from("listing_referrals").select(` *, listing:listings(*,photos:listing_photos(*)) `).eq("sender_agent_id",s.id).order("created_at",{ascending:!1}),q.from("listing_referrals").select(` *, sender:profiles!listing_referrals_sender_agent_id_fkey(id, name, email), listing:listings(*,photos:listing_photos(*)) `).eq("listing_agent_id",s.id).order("created_at",{ascending:!1})]);return{sent:t.data||[],received:n.data||[]}},enabled:!!s})},q7s=()=>{const s=Bt(),{user:t}=hs();return mt({mutationFn:async({listingId:n,listingAgentId:r,buyerName:a,buyerType:i,notes:l})=>{if(!t)throw new Error("Not authenticated");const{data:o,error:c}=await q.from("listing_referrals").insert({listing_id:n,sender_agent_id:t.id,listing_agent_id:r,buyer_name:a,buyer_type:i,notes:l}).select().single();if(c)throw c;return o},onSuccess:()=>{s.invalidateQueries({queryKey:["my-referrals"]})}})},$7s=()=>at({queryKey:["listing-leaderboard"],queryFn:async()=>{const{data:s}=await q.from("listing_shares").select("sharing_agent_id, profiles!listing_shares_agent_id_fkey(name)").order("created_at",{ascending:!1}),t=new Map;s==null||s.forEach(l=>{var d;const o=l.sharing_agent_id;if(!o)return;const c=t.get(o);c?c.count++:t.set(o,{name:((d=l.profiles)==null?void 0:d.name)||"Unknown",count:1})});const n=Array.from(t.entries()).map(([l,o])=>({agentId:l,...o})).sort((l,o)=>o.count-l.count).slice(0,10),{data:r}=await q.from("listings").select("agent_id, agent:profiles!listings_agent_id_fkey(name)").eq("is_approved",!0),a=new Map;r==null||r.forEach(l=>{var c;const o=a.get(l.agent_id);o?o.count++:a.set(l.agent_id,{name:((c=l.agent)==null?void 0:c.name)||"Unknown",count:1})});const i=Array.from(a.entries()).map(([l,o])=>({agentId:l,...o})).sort((l,o)=>o.count-l.count).slice(0,10);return{topSharers:n,topListers:i}}}),V7s=()=>{const{user:s,brokerageId:t}=hs();return at({queryKey:["brokerage-listings",t],queryFn:async()=>{if(!s||!t)return[];const{data:n}=await q.from("profiles").select("id").eq("brokerage_id",t);if(!n||n.length===0)return[];const r=n.map(l=>l.id),{data:a,error:i}=await q.from("listings").select(` *, photos:listing_photos(*), commercial:commercial_listing_details(*), agent:profiles!listings_agent_id_fkey(id, name, email, brokerage_id, brokerage:brokerages(name)) `).in("agent_id",r).eq("is_approved",!0).order("created_at",{ascending:!1});if(i)throw i;return a},enabled:!!s&&!!t})},t7e=q,gp=s=>s===""||s==null?null:Number(String(s).replace(/[^0-9.\-]/g,"")),H7s={property_address:"",city:"",state:"",submarket:"",opportunity_title:"",description:"",deal_type:"sale",commercial_type:"office",asking_price:"",lease_rate:"",lease_rate_unit:"sf_year",lease_type:"",building_sf:"",available_sf:"",lot_acres:"",units:"",floors:"",year_built:"",parking_spaces:"",zoning:"",occupancy_pct:"",tenancy:"",noi:"",cap_rate:"",gross_income:"",operating_expenses:"",broker_coop_pct:"",call_for_offers_at:"",is_confidential:!1,hide_address:!1,requires_nda:!1,om_gate_mode:"email",opportunity_zone:!1,is_public:!1,allow_sharing:!0,share_with_brokerage:!1,open_to_referrals:!0,open_to_social_promotion:!0,show_on_lead_site:!0,site_only:!1};function egt({label:s,placeholder:t,items:n,onChange:r}){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:s}),n.map((a,i)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{value:a,placeholder:t,onChange:l=>r(n.map((o,c)=>c===i?l.target.value:o))}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>r(n.filter((l,o)=>o!==i)),children:e.jsx(Qn,{className:"h-4 w-4"})})]},i)),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:()=>r([...n,""]),children:[e.jsx(rn,{className:"mr-1.5 h-3.5 w-3.5"})," Add"]})]})}function s7e({label:s,description:t,columns:n,rows:r,onChange:a}){return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(J,{children:s}),t&&e.jsx("p",{className:"text-xs text-muted-foreground",children:t})]}),r.map((i,l)=>e.jsxs("div",{className:"flex flex-wrap items-end gap-2 rounded-lg border p-3",children:[n.map(o=>e.jsxs("div",{className:"min-w-[120px] flex-1 space-y-1",children:[e.jsx(J,{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:o.label}),e.jsx(xe,{value:i[o.key]??"",placeholder:o.placeholder,onChange:c=>a(r.map((d,u)=>u===l?{...d,[o.key]:c.target.value}:d))})]},o.key)),e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>a(r.filter((o,c)=>c!==l)),children:e.jsx(Qn,{className:"h-4 w-4"})})]},l)),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:()=>a([...r,{}]),children:[e.jsx(rn,{className:"mr-1.5 h-3.5 w-3.5"})," Add row"]})]})}const G7s=[{key:"radius_1",label:"1 mile"},{key:"radius_3",label:"3 miles"},{key:"radius_5",label:"5 miles"}],W7s=[{key:"population",label:"Population"},{key:"households",label:"Households"},{key:"avg_income",label:"Avg income"},{key:"daytime_pop",label:"Daytime pop."}];function tgt(){const{listingId:s}=Li(),t=Fn(),{user:n,loading:r}=hs(),a=!!s,{data:i,isLoading:l}=eae(s||""),{data:o}=bFt(s);j9t();const c=N9t(),d=_Ft(),u=wFt(),[h,m]=_.useState(null),[p,f]=_.useState(H7s),[y,v]=_.useState([""]),[g,b]=_.useState([]),[j,S]=_.useState([]),[C,E]=_.useState([]),[P,M]=_.useState([]),[I,D]=_.useState({}),[O,V]=_.useState(!1),[G,$]=_.useState([]),[H,Y]=_.useState([]),Z=!a||!!(n!=null&&n.id)&&(i==null?void 0:i.agent_id)===n.id;_.useEffect(()=>{!a||r||l||!i||Z||(se.error("Only the listing agent can edit this commercial listing"),t(`/mission-control/listings/${i.id}/commercial`,{replace:!0}))},[r,i,a,Z,l,t]);const ne=he=>{if(!(he!=null&&he.length))return;const pe=Array.from(he);$(Ce=>[...Ce,...pe]),Y(Ce=>[...Ce,...pe.map(Ae=>URL.createObjectURL(Ae))])},ce=he=>{URL.revokeObjectURL(H[he]),$(pe=>pe.filter((Ce,Ae)=>Ae!==he)),Y(pe=>pe.filter((Ce,Ae)=>Ae!==he))},ie=async he=>{if(!G.length)return;const{count:pe}=await t7e.from("listing_photos").select("id",{count:"exact",head:!0}).eq("listing_id",he),Ce=pe??0;for(let Ae=0;Aef(Ce=>({...Ce,[he]:pe}));_.useEffect(()=>{!a||!i||(m(i.lifecycle_stage==="pitch"?"pitch":"assignment"),f(he=>({...he,property_address:i.property_address??"",city:i.city??"",state:i.state??"",description:i.description??"",year_built:i.year_built?String(i.year_built):"",is_public:!!i.is_public,allow_sharing:i.allow_sharing??!0,share_with_brokerage:i.share_with_brokerage??!1,open_to_referrals:i.open_to_referrals??!0,open_to_social_promotion:i.open_to_social_promotion??!0,show_on_lead_site:i.show_on_lead_site??!0,site_only:!i.is_public&&(i.show_on_lead_site??!1)&&!i.allow_sharing})))},[a,i]),_.useEffect(()=>{var he;o&&(f(pe=>({...pe,submarket:o.submarket??"",opportunity_title:o.opportunity_title??"",deal_type:o.deal_type??"sale",commercial_type:o.commercial_type??"office",asking_price:o.asking_price!=null?String(o.asking_price):"",lease_rate:o.lease_rate!=null?String(o.lease_rate):"",lease_rate_unit:o.lease_rate_unit??"sf_year",lease_type:o.lease_type??"",building_sf:o.building_sf!=null?String(o.building_sf):"",available_sf:o.available_sf!=null?String(o.available_sf):"",lot_acres:o.lot_acres!=null?String(o.lot_acres):"",units:o.units!=null?String(o.units):"",floors:o.floors!=null?String(o.floors):"",parking_spaces:o.parking_spaces!=null?String(o.parking_spaces):"",zoning:o.zoning??"",occupancy_pct:o.occupancy_pct!=null?String(o.occupancy_pct):"",tenancy:o.tenancy??"",noi:o.noi!=null?String(o.noi):"",cap_rate:o.cap_rate!=null?String(o.cap_rate):"",gross_income:o.gross_income!=null?String(o.gross_income):"",operating_expenses:o.operating_expenses!=null?String(o.operating_expenses):"",broker_coop_pct:o.broker_coop_pct!=null?String(o.broker_coop_pct):"",call_for_offers_at:o.call_for_offers_at?o.call_for_offers_at.slice(0,10):"",is_confidential:!!o.is_confidential,hide_address:!!o.hide_address,requires_nda:!!o.requires_nda,om_gate_mode:o.om_gate_mode??"email",opportunity_zone:!!o.opportunity_zone})),v((he=o.investment_highlights)!=null&&he.length?o.investment_highlights:[""]),b(o.property_highlights??[]),S((o.spaces??[]).map(pe=>({...pe,sf:(pe==null?void 0:pe.sf)!=null?String(pe.sf):""}))),E((o.tenants??[]).map(pe=>({...pe,sf:(pe==null?void 0:pe.sf)!=null?String(pe.sf):""}))),M(o.traffic_counts??[]),D(o.demographics??{}))},[o]);const ae=p.deal_type==="lease"||p.deal_type==="sale_or_lease",le=p.deal_type!=="lease",be=_.useMemo(()=>({deal_type:p.deal_type,commercial_type:p.commercial_type,opportunity_title:p.opportunity_title||null,submarket:p.submarket||null,asking_price:gp(p.asking_price),lease_rate:gp(p.lease_rate),lease_rate_unit:p.lease_rate_unit,lease_type:p.lease_type||null,building_sf:gp(p.building_sf),available_sf:gp(p.available_sf),lot_acres:gp(p.lot_acres),units:gp(p.units),floors:gp(p.floors),parking_spaces:gp(p.parking_spaces),zoning:p.zoning||null,occupancy_pct:gp(p.occupancy_pct),tenancy:p.tenancy||null,noi:gp(p.noi),cap_rate:gp(p.cap_rate),gross_income:gp(p.gross_income),operating_expenses:gp(p.operating_expenses),broker_coop_pct:gp(p.broker_coop_pct),call_for_offers_at:p.call_for_offers_at?new Date(p.call_for_offers_at).toISOString():null,is_confidential:p.is_confidential,hide_address:p.hide_address,requires_nda:p.requires_nda,om_gate_mode:p.om_gate_mode,opportunity_zone:p.opportunity_zone,investment_highlights:y.map(he=>he.trim()).filter(Boolean),spaces:j.filter(he=>Object.values(he).some(pe=>String(pe??"").trim())),tenants:C.filter(he=>Object.values(he).some(pe=>String(pe??"").trim())),traffic_counts:P.filter(he=>String(he.road??"").trim()||String(he.count??"").trim()),demographics:Object.fromEntries(Object.entries(I).filter(([,he])=>Object.values(he??{}).some(pe=>String(pe??"").trim()))),property_highlights:g.map(he=>he.trim()).filter(Boolean),price_per_sf:gp(p.asking_price)&&gp(p.building_sf)?Math.round(gp(p.asking_price)/gp(p.building_sf)*100)/100:null,price_per_unit:gp(p.asking_price)&&gp(p.units)?Math.round(gp(p.asking_price)/gp(p.units)):null}),[p,y,g,j,C,P,I]),me=async()=>{if(a&&!Z){se.error("Only the listing agent can edit this commercial listing");return}if(!p.city||!p.state){se.error("City and state are required");return}if(!a&&!h){se.error("Choose whether you already have the assignment");return}V(!0);try{let he=s;const pe={property_address:p.property_address||null,city:p.city,state:p.state,neighborhood:p.submarket||null,price:gp(p.asking_price)??0,property_type:"commercial",description:p.description||null,year_built:gp(p.year_built),square_footage:gp(p.building_sf)},Ce=h==="pitch",Ae=Ce?{is_public:!1,allow_sharing:!1,share_with_brokerage:!1,open_to_referrals:!1,open_to_social_promotion:!1,show_on_lead_site:!1}:{is_public:p.site_only?!1:p.is_public,allow_sharing:p.site_only?!1:p.allow_sharing,share_with_brokerage:p.site_only?!1:p.share_with_brokerage,open_to_referrals:p.open_to_referrals,open_to_social_promotion:p.site_only?!1:p.open_to_social_promotion,show_on_lead_site:p.site_only?!0:p.show_on_lead_site},Pe=!Ce&&(Ae.is_public||Ae.show_on_lead_site||Ae.allow_sharing)?"active":"coming_soon";if(a&&he)await c.mutateAsync({id:he,...pe,...Ae,...Pe==="active"?{status:"active"}:{}});else{const ze=await t7e.from("listings").insert({...pe,...Ae,agent_id:n.id,listing_class:"commercial",lifecycle_stage:Ce?"pitch":"won",status:Pe}).select().single();if(ze.error)throw ze.error;he=ze.data.id,Ce&&await u.mutateAsync({listingId:he,values:{launch_plan:vFt}})}await d.mutateAsync({listingId:he,values:be}),await ie(he),se.success(a?"Commercial listing updated":"Commercial listing created"),t(`/mission-control/listings/${he}/commercial`)}catch(he){console.error(he),se.error(he.message||"Could not save listing")}finally{V(!1)}};return a&&(r||l||!i||!Z)?e.jsx("div",{className:"flex min-h-[50vh] items-center justify-center",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):!a&&!h?e.jsx("div",{className:"min-h-screen bg-background",children:e.jsxs("div",{className:"mx-auto max-w-4xl px-4 py-10",children:[e.jsxs(B,{variant:"ghost",size:"sm",className:"-ml-2 mb-6",onClick:()=>t("/mission-control/listings/new"),children:[e.jsx(ka,{className:"mr-2 h-4 w-4"})," Back"]}),e.jsx("p",{className:"text-xs font-medium uppercase tracking-[0.2em] text-muted-foreground",children:"Commercial Launch"}),e.jsx("h1",{className:"mt-2 text-3xl font-semibold tracking-tight md:text-4xl",children:"Where are you in the deal?"}),e.jsx("p",{className:"mt-2 max-w-xl text-muted-foreground",children:"Pitch Mode keeps everything private while you compete for the assignment. Win it and the same record becomes your live Commercial Launch — nothing gets re-entered."}),e.jsxs("div",{className:"mt-8 grid gap-5 md:grid-cols-2",children:[e.jsxs("button",{onClick:()=>m("assignment"),className:"group rounded-2xl border bg-card p-7 text-left transition-all hover:-translate-y-0.5 hover:shadow-xl",children:[e.jsx(wl,{className:"mb-4 h-6 w-6"}),e.jsx("h2",{className:"text-lg font-semibold",children:"I already have the assignment"}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Go straight to building the launch: microsite, OM gating, investor tracking and reporting."})]}),e.jsxs("button",{onClick:()=>m("pitch"),className:"group rounded-2xl border border-primary/40 bg-gradient-to-br from-primary/[0.07] to-transparent p-7 text-left transition-all hover:-translate-y-0.5 hover:shadow-xl",children:[e.jsx(ku,{className:"mb-4 h-6 w-6 text-primary"}),e.jsx("h2",{className:"text-lg font-semibold",children:"I'm pitching this property"}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Private Pitch Workspace with owner intel, positioning, a proposed launch plan and a seller-facing preview of exactly what happens the day they hire you."})]})]})]})}):e.jsxs("div",{className:"min-h-screen bg-background pb-28",children:[e.jsxs("div",{className:"mx-auto max-w-4xl px-4 py-8",children:[e.jsxs(B,{variant:"ghost",size:"sm",className:"-ml-2 mb-6",onClick:()=>t(a?`/mission-control/listings/${s}/commercial`:"/mission-control/listings"),children:[e.jsx(ka,{className:"mr-2 h-4 w-4"})," Back"]}),e.jsxs("div",{className:"mb-8 flex items-start gap-3",children:[e.jsx("div",{className:"flex h-11 w-11 items-center justify-center rounded-xl border bg-card",children:e.jsx(ai,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight md:text-3xl",children:a?"Edit commercial listing":h==="pitch"?"New pitch":"New commercial listing"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:h==="pitch"?"Private until you win it — never shown in the Exchange or on the public web.":"Only the fields that matter for this deal type are required."})]})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsx(St,{className:"text-base",children:"The opportunity"}),e.jsx(kn,{children:"How this deal is positioned to the market."})]}),e.jsxs(Me,{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Deal type"}),e.jsxs(is,{value:p.deal_type,onValueChange:he=>te("deal_type",he),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsx(as,{children:Object.entries(DP).map(([he,pe])=>e.jsx(He,{value:he,children:pe},he))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Property type"}),e.jsxs(is,{value:p.commercial_type,onValueChange:he=>te("commercial_type",he),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsx(as,{children:Object.entries(hL).map(([he,pe])=>e.jsx(He,{value:he,children:pe},he))})]})]}),e.jsxs("div",{className:"space-y-2 md:col-span-2",children:[e.jsxs(J,{children:["Opportunity name ",e.jsx("span",{className:"text-muted-foreground",children:"(optional)"})]}),e.jsx(xe,{value:p.opportunity_title,placeholder:"e.g. Gateway Logistics Center",onChange:he=>te("opportunity_title",he.target.value)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Used instead of the street address on confidential offerings."})]}),e.jsxs("div",{className:"space-y-2 md:col-span-2",children:[e.jsx(J,{children:"Property story"}),e.jsx(Ms,{rows:5,value:p.description,placeholder:"The narrative an investor, tenant or owner should read first.",onChange:he=>te("description",he.target.value)})]})]})]}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"Location"})}),e.jsxs(Me,{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2 md:col-span-2",children:[e.jsx(J,{children:"Street address"}),e.jsx(xe,{value:p.property_address,onChange:he=>te("property_address",he.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"City *"}),e.jsx(xe,{value:p.city,onChange:he=>te("city",he.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"State *"}),e.jsx(xe,{value:p.state,maxLength:2,onChange:he=>te("state",he.target.value.toUpperCase())})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Submarket"}),e.jsx(xe,{value:p.submarket,placeholder:"e.g. North Loop",onChange:he=>te("submarket",he.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Zoning"}),e.jsx(xe,{value:p.zoning,onChange:he=>te("zoning",he.target.value)})]})]})]}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"Pricing"})}),e.jsxs(Me,{className:"grid gap-4 md:grid-cols-2",children:[le&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Asking price"}),e.jsx(xe,{value:p.asking_price,placeholder:"4750000",onChange:he=>te("asking_price",he.target.value)})]}),ae&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Lease rate"}),e.jsx(xe,{value:p.lease_rate,placeholder:"24.50",onChange:he=>te("lease_rate",he.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Rate basis"}),e.jsxs(is,{value:p.lease_rate_unit,onValueChange:he=>te("lease_rate_unit",he),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"sf_year",children:"Per SF / year"}),e.jsx(He,{value:"sf_month",children:"Per SF / month"}),e.jsx(He,{value:"month",children:"Per month"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Lease structure"}),e.jsxs(is,{value:p.lease_type||"none",onValueChange:he=>te("lease_type",he==="none"?"":he),children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Select"})}),e.jsxs(as,{children:[e.jsx(He,{value:"none",children:"Not specified"}),L6s.map(he=>e.jsx(He,{value:he,children:he},he))]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Broker co-op (%)"}),e.jsx(xe,{value:p.broker_coop_pct,placeholder:"2.5",onChange:he=>te("broker_coop_pct",he.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Call for offers"}),e.jsx(xe,{type:"date",value:p.call_for_offers_at,onChange:he=>te("call_for_offers_at",he.target.value)})]})]})]}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"Building & site"})}),e.jsxs(Me,{className:"grid gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Building SF"}),e.jsx(xe,{value:p.building_sf,onChange:he=>te("building_sf",he.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Available SF"}),e.jsx(xe,{value:p.available_sf,onChange:he=>te("available_sf",he.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Lot acres"}),e.jsx(xe,{value:p.lot_acres,onChange:he=>te("lot_acres",he.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Units"}),e.jsx(xe,{value:p.units,onChange:he=>te("units",he.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Floors"}),e.jsx(xe,{value:p.floors,onChange:he=>te("floors",he.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Parking spaces"}),e.jsx(xe,{value:p.parking_spaces,onChange:he=>te("parking_spaces",he.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Year built"}),e.jsx(xe,{value:p.year_built,onChange:he=>te("year_built",he.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Tenancy"}),e.jsxs(is,{value:p.tenancy||"none",onValueChange:he=>te("tenancy",he==="none"?"":he),children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Select"})}),e.jsxs(as,{children:[e.jsx(He,{value:"none",children:"Not specified"}),e.jsx(He,{value:"single",children:"Single tenant"}),e.jsx(He,{value:"multi",children:"Multi-tenant"}),e.jsx(He,{value:"vacant",children:"Vacant"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Occupancy (%)"}),e.jsx(xe,{value:p.occupancy_pct,onChange:he=>te("occupancy_pct",he.target.value)})]})]})]}),e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsx(St,{className:"text-base",children:"Investment metrics"}),e.jsx(kn,{children:"Only what you enter is shown on the microsite."})]}),e.jsxs(Me,{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"NOI"}),e.jsx(xe,{value:p.noi,onChange:he=>te("noi",he.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Cap rate (%)"}),e.jsx(xe,{value:p.cap_rate,onChange:he=>te("cap_rate",he.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Gross income"}),e.jsx(xe,{value:p.gross_income,onChange:he=>te("gross_income",he.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Operating expenses"}),e.jsx(xe,{value:p.operating_expenses,onChange:he=>te("operating_expenses",he.target.value)})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3 md:col-span-2",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Opportunity Zone"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Highlight qualified OZ tax treatment."})]}),e.jsx(fn,{checked:p.opportunity_zone,onCheckedChange:he=>te("opportunity_zone",he)})]})]})]}),e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsx(St,{className:"text-base",children:"Highlights"}),e.jsx(kn,{children:"3–6 reasons this opportunity matters. These headline the microsite."})]}),e.jsxs(Me,{className:"space-y-6",children:[e.jsx(egt,{label:"Investment highlights",placeholder:"e.g. 12-year NNN lease to investment-grade tenant",items:y,onChange:v}),e.jsx(egt,{label:"Property highlights",placeholder:"e.g. 32' clear height, 14 dock doors",items:g,onChange:b})]})]}),e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsx(St,{className:"text-base",children:"Spaces, tenants & market data"}),e.jsx(kn,{children:"Everything here is optional — the microsite only renders the sections you fill in."})]}),e.jsxs(Me,{className:"space-y-8",children:[e.jsx(s7e,{label:"Available spaces",description:"Suites or spaces available for lease.",columns:[{key:"suite",label:"Suite",placeholder:"Suite 200"},{key:"sf",label:"SF",placeholder:"4,200"},{key:"rate",label:"Rate",placeholder:"$28.00 NNN"},{key:"availability",label:"Availability",placeholder:"Immediate"},{key:"use",label:"Use",placeholder:"Office"}],rows:j,onChange:S}),e.jsx(s7e,{label:"Rent roll / tenants",description:"Shown on investment offerings to demonstrate income stability.",columns:[{key:"name",label:"Tenant",placeholder:"Anchor tenant"},{key:"sf",label:"SF",placeholder:"12,000"},{key:"lease_expiry",label:"Lease expiry",placeholder:"2031"},{key:"rent",label:"Rent",placeholder:"$18.50/SF"},{key:"notes",label:"Notes",placeholder:"Two 5-yr options"}],rows:C,onChange:E}),e.jsx(s7e,{label:"Traffic counts",columns:[{key:"road",label:"Road",placeholder:"US-98"},{key:"count",label:"Vehicles / day",placeholder:"42,500 VPD"}],rows:P,onChange:M}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Demographics"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"1 / 3 / 5-mile radius cards on the microsite."})]}),G7s.map(he=>e.jsxs("div",{className:"flex flex-wrap items-end gap-2 rounded-lg border p-3",children:[e.jsx("p",{className:"w-16 text-sm font-medium",children:he.label}),W7s.map(pe=>{var Ce;return e.jsxs("div",{className:"min-w-[120px] flex-1 space-y-1",children:[e.jsx(J,{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:pe.label}),e.jsx(xe,{value:((Ce=I[he.key])==null?void 0:Ce[pe.key])??"",onChange:Ae=>D({...I,[he.key]:{...I[he.key]??{},[pe.key]:Ae.target.value}})})]},pe.key)})]},he.key))]})]})]}),e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsx(St,{className:"text-base",children:"Photography"}),e.jsx(kn,{children:"Cinematic exterior, aerial and interior imagery drives the microsite hero and gallery."})]}),e.jsxs(Me,{className:"space-y-3",children:[e.jsxs("label",{className:"flex cursor-pointer items-center justify-center rounded-lg border border-dashed px-4 py-8 text-sm text-muted-foreground hover:bg-muted/40",children:[e.jsx(rn,{className:"mr-2 h-4 w-4"}),"Add photos",e.jsx("input",{type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:he=>ne(he.target.files)})]}),H.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid grid-cols-3 gap-2 sm:grid-cols-4",children:H.map((he,pe)=>e.jsxs("div",{className:"group relative aspect-[4/3] overflow-hidden rounded-md border",children:[e.jsx("img",{src:he,alt:`Commercial photo ${pe+1}`,className:"h-full w-full object-cover"}),e.jsx("button",{type:"button",onClick:()=>ce(pe),className:"absolute right-1 top-1 rounded-full bg-background/90 p-1 opacity-0 transition group-hover:opacity-100","aria-label":"Remove photo",children:e.jsx(Qn,{className:"h-3 w-3"})})]},he))}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[H.length," photo",H.length===1?"":"s"," upload when you save."]})]})]})]}),h!=="pitch"&&e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsx(St,{className:"text-base",children:"Distribution & sharing"}),e.jsx(kn,{children:"Choose where this opportunity appears. You control the Listing Exchange, your own website, and the public commercial marketplace independently."})]}),e.jsxs(Me,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(J,{children:"My website only"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Hide from the Listing Exchange, other agents and the public marketplace."})]}),e.jsx(fn,{checked:p.site_only,onCheckedChange:he=>f(pe=>({...pe,site_only:he,is_public:he?!1:pe.is_public,show_on_lead_site:he?!0:pe.show_on_lead_site,share_with_brokerage:he?!1:pe.share_with_brokerage}))})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Publish publicly"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Go live on commercial.relevelup.com to capture leads."})]}),e.jsx(fn,{checked:p.is_public,disabled:p.site_only,onCheckedChange:he=>te("is_public",he)})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Show on my website"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Feature it on your own lead site."})]}),e.jsx(fn,{checked:p.show_on_lead_site,onCheckedChange:he=>te("show_on_lead_site",he)})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Allow sharing"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Other LevelUp agents can share it from the Exchange."})]}),e.jsx(fn,{checked:p.allow_sharing,disabled:p.site_only,onCheckedChange:he=>te("allow_sharing",he)})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Share with my brokerage"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Visible to agents inside your brokerage."})]}),e.jsx(fn,{checked:p.share_with_brokerage,disabled:p.site_only,onCheckedChange:he=>te("share_with_brokerage",he)})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Open to referrals"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Accept tenant / buyer referrals from other agents."})]}),e.jsx(fn,{checked:p.open_to_referrals,onCheckedChange:he=>te("open_to_referrals",he)})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Social promotion"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Other agents may promote it on social media."})]}),e.jsx(fn,{checked:p.open_to_social_promotion,disabled:p.site_only,onCheckedChange:he=>te("open_to_social_promotion",he)})]})]})]}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"Confidentiality & document gating"})}),e.jsxs(Me,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Confidential offering"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Teaser presentation, no address, search engines blocked."})]}),e.jsx(fn,{checked:p.is_confidential,onCheckedChange:he=>te("is_confidential",he)})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Hide street address"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show city / submarket only."})]}),e.jsx(fn,{checked:p.hide_address,onCheckedChange:he=>te("hide_address",he)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Offering Memorandum access"}),e.jsxs(is,{value:p.om_gate_mode,onValueChange:he=>te("om_gate_mode",he),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"open",children:"Open download"}),e.jsx(He,{value:"email",children:"Require name, email & company"}),e.jsx(He,{value:"nda",children:"Require confidentiality acknowledgement"})]})]})]})]})]})]})]}),e.jsx("div",{className:"fixed inset-x-0 bottom-0 border-t bg-background/95 backdrop-blur",children:e.jsxs("div",{className:"mx-auto flex max-w-4xl items-center justify-between gap-3 px-4 py-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:h==="pitch"?"Saved privately — nothing publishes until you win.":"Not published until you launch."}),e.jsxs(B,{onClick:me,disabled:O,children:[O&&e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}),a?"Save changes":"Create & continue"]})]})})]})}function WPe(s){return at({queryKey:["listing-documents",s],queryFn:async()=>{const{data:t,error:n}=await q.from("listing_documents").select("*").eq("listing_id",s).order("sort_order",{ascending:!0}).order("created_at",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function P9t(){const{user:s}=hs(),t=Bt();return mt({mutationFn:async({listingId:n,file:r,docKind:a,gateLevel:i,title:l})=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const o=r.name.split(".").pop(),c=`${s.id}/${n}/${crypto.randomUUID()}.${o}`,{error:d}=await q.storage.from("listing-documents").upload(c,r,{contentType:r.type||void 0});if(d)throw d;const{data:u,error:h}=await q.from("listing_documents").insert({listing_id:n,owner_user_id:s.id,file_name:r.name,file_size:r.size,file_type:r.type||null,storage_path:c,...a?{doc_kind:a}:{},...i?{gate_level:i}:{},...l?{title:l}:{}}).select().single();if(h)throw h;return u},onSuccess:(n,r)=>{t.invalidateQueries({queryKey:["listing-documents",r.listingId]})}})}function L9t(){const s=Bt();return mt({mutationFn:async({id:t,storage_path:n,listingId:r})=>{await q.storage.from("listing-documents").remove([n]);const{error:a}=await q.from("listing_documents").delete().eq("id",t);if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["listing-documents",t]})}})}function K7s(){const s=Bt();return mt({mutationFn:async({id:t,listingId:n,values:r})=>{const{error:a}=await q.from("listing_documents").update(r).eq("id",t);if(a)throw a;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["listing-documents",t]})}})}function Y7s(){const s=Bt();return mt({mutationFn:async({id:t,visible:n,listingId:r})=>{const{error:a}=await q.from("listing_documents").update({visible_on_exchange:n}).eq("id",t);if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["listing-documents",t]})}})}async function net(s){const{data:t,error:n}=await q.storage.from("listing-documents").createSignedUrl(s,3600);if(n)throw n;return t.signedUrl}function Z7s(){for(var s=arguments.length,t=new Array(s),n=0;nr=>{t.forEach(a=>a(r))},t)}const KPe=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function fW(s){const t=Object.prototype.toString.call(s);return t==="[object Window]"||t==="[object global]"}function ret(s){return"nodeType"in s}function Y_(s){var t,n;return s?fW(s)?s:ret(s)&&(t=(n=s.ownerDocument)==null?void 0:n.defaultView)!=null?t:window:window}function aet(s){const{Document:t}=Y_(s);return s instanceof t}function tae(s){return fW(s)?!1:s instanceof Y_(s).HTMLElement}function I9t(s){return s instanceof Y_(s).SVGElement}function xW(s){return s?fW(s)?s.document:ret(s)?aet(s)?s:tae(s)||I9t(s)?s.ownerDocument:document:document:document}const cC=KPe?_.useLayoutEffect:_.useEffect;function iet(s){const t=_.useRef(s);return cC(()=>{t.current=s}),_.useCallback(function(){for(var n=arguments.length,r=new Array(n),a=0;a{s.current=setInterval(r,a)},[]),n=_.useCallback(()=>{s.current!==null&&(clearInterval(s.current),s.current=null)},[]);return[t,n]}function cte(s,t){t===void 0&&(t=[s]);const n=_.useRef(s);return cC(()=>{n.current!==s&&(n.current=s)},t),n}function sae(s,t){const n=_.useRef();return _.useMemo(()=>{const r=s(n.current);return n.current=r,r},[...t])}function CAe(s){const t=iet(s),n=_.useRef(null),r=_.useCallback(a=>{a!==n.current&&(t==null||t(a,n.current)),n.current=a},[]);return[n,r]}function wVe(s){const t=_.useRef();return _.useEffect(()=>{t.current=s},[s]),t.current}let n7e={};function nae(s,t){return _.useMemo(()=>{if(t)return t;const n=n7e[s]==null?0:n7e[s]+1;return n7e[s]=n,s+"-"+n},[s,t])}function D9t(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 S$=D9t(1),dte=D9t(-1);function Q7s(s){return"clientX"in s&&"clientY"in s}function oet(s){if(!s)return!1;const{KeyboardEvent:t}=Y_(s.target);return t&&s instanceof t}function J7s(s){if(!s)return!1;const{TouchEvent:t}=Y_(s.target);return t&&s instanceof t}function jVe(s){if(J7s(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 Q7s(s)?{x:s.clientX,y:s.clientY}:null}const OP=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[OP.Translate.toString(s),OP.Scale.toString(s)].join(" ")}},Transition:{toString(s){let{property:t,duration:n,easing:r}=s;return t+" "+n+"ms "+r}}}),sgt="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function e9s(s){return s.matches(sgt)?s:s.querySelector(sgt)}const t9s={display:"none"};function s9s(s){let{id:t,value:n}=s;return Dt.createElement("div",{id:t,style:t9s},n)}function n9s(s){let{id:t,announcement:n,ariaLiveType:r="assertive"}=s;const a={position:"fixed",top:0,left:0,width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(100%)",whiteSpace:"nowrap"};return Dt.createElement("div",{id:t,style:a,role:"status","aria-live":r,"aria-atomic":!0},n)}function r9s(){const[s,t]=_.useState("");return{announce:_.useCallback(r=>{r!=null&&t(r)},[]),announcement:s}}const R9t=_.createContext(null);function a9s(s){const t=_.useContext(R9t);_.useEffect(()=>{if(!t)throw new Error("useDndMonitor must be used within a children of ");return t(s)},[s,t])}function i9s(){const[s]=_.useState(()=>new Set),t=_.useCallback(r=>(s.add(r),()=>s.delete(r)),[s]);return[_.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 o9s={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. `},l9s={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 c9s(s){let{announcements:t=l9s,container:n,hiddenTextDescribedById:r,screenReaderInstructions:a=o9s}=s;const{announce:i,announcement:l}=r9s(),o=nae("DndLiveRegion"),[c,d]=_.useState(!1);if(_.useEffect(()=>{d(!0)},[]),a9s(_.useMemo(()=>({onDragStart(h){let{active:m}=h;i(t.onDragStart({active:m}))},onDragMove(h){let{active:m,over:p}=h;t.onDragMove&&i(t.onDragMove({active:m,over:p}))},onDragOver(h){let{active:m,over:p}=h;i(t.onDragOver({active:m,over:p}))},onDragEnd(h){let{active:m,over:p}=h;i(t.onDragEnd({active:m,over:p}))},onDragCancel(h){let{active:m,over:p}=h;i(t.onDragCancel({active:m,over:p}))}}),[i,t])),!c)return null;const u=Dt.createElement(Dt.Fragment,null,Dt.createElement(s9s,{id:r,value:a.draggable}),Dt.createElement(n9s,{id:o,announcement:l}));return n?mv.createPortal(u,n):u}var m0;(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"})(m0||(m0={}));function AAe(){}function IH(s,t){return _.useMemo(()=>({sensor:s,options:t??{}}),[s,t])}function YPe(){for(var s=arguments.length,t=new Array(s),n=0;n[...t].filter(r=>r!=null),[...t])}const AS=Object.freeze({x:0,y:0});function F9t(s,t){return Math.sqrt(Math.pow(s.x-t.x,2)+Math.pow(s.y-t.y,2))}function O9t(s,t){let{data:{value:n}}=s,{data:{value:r}}=t;return n-r}function d9s(s,t){let{data:{value:n}}=s,{data:{value:r}}=t;return r-n}function ngt(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 z9t(s,t){if(!s||s.length===0)return null;const[n]=s;return n[t]}function rgt(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 ZPe=s=>{let{collisionRect:t,droppableRects:n,droppableContainers:r}=s;const a=rgt(t,t.left,t.top),i=[];for(const l of r){const{id:o}=l,c=n.get(o);if(c){const d=F9t(rgt(c),a);i.push({id:o,data:{droppableContainer:l,value:d}})}}return i.sort(O9t)},u9s=s=>{let{collisionRect:t,droppableRects:n,droppableContainers:r}=s;const a=ngt(t),i=[];for(const l of r){const{id:o}=l,c=n.get(o);if(c){const d=ngt(c),u=a.reduce((m,p,f)=>m+F9t(d[f],p),0),h=Number((u/4).toFixed(4));i.push({id:o,data:{droppableContainer:l,value:h}})}}return i.sort(O9t)};function h9s(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=h9s(o,t);c>0&&a.push({id:l,data:{droppableContainer:i,value:c}})}}return a.sort(d9s)};function p9s(s,t,n){return{...s,scaleX:t&&n?t.width/n.width:1,scaleY:t&&n?t.height/n.height:1}}function B9t(s,t){return s&&t?{x:s.left-t.left,y:s.top-t.top}:AS}function f9s(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 x9s=f9s(1);function g9s(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 y9s(s,t,n){const r=g9s(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 v9s={ignoreTransform:!1};function gW(s,t){t===void 0&&(t=v9s);let n=s.getBoundingClientRect();if(t.ignoreTransform){const{transform:d,transformOrigin:u}=Y_(s).getComputedStyle(s);d&&(n=y9s(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 agt(s){return gW(s,{ignoreTransform:!0})}function b9s(s){const t=s.innerWidth,n=s.innerHeight;return{top:0,left:0,right:t,bottom:n,width:t,height:n}}function _9s(s,t){return t===void 0&&(t=Y_(s).getComputedStyle(s)),t.position==="fixed"}function w9s(s,t){t===void 0&&(t=Y_(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 XPe(s,t){const n=[];function r(a){if(t!=null&&n.length>=t||!a)return n;if(aet(a)&&a.scrollingElement!=null&&!n.includes(a.scrollingElement))return n.push(a.scrollingElement),n;if(!tae(a)||I9t(a)||n.includes(a))return n;const i=Y_(s).getComputedStyle(a);return a!==s&&w9s(a,i)&&n.push(a),_9s(a,i)?n:r(a.parentNode)}return s?r(s):n}function U9t(s){const[t]=XPe(s,1);return t??null}function r7e(s){return!KPe||!s?null:fW(s)?s:ret(s)?aet(s)||s===xW(s).scrollingElement?window:tae(s)?s:null:null}function q9t(s){return fW(s)?s.scrollX:s.scrollLeft}function $9t(s){return fW(s)?s.scrollY:s.scrollTop}function NVe(s){return{x:q9t(s),y:$9t(s)}}var uy;(function(s){s[s.Forward=1]="Forward",s[s.Backward=-1]="Backward"})(uy||(uy={}));function V9t(s){return!KPe||!s?!1:s===document.scrollingElement}function H9t(s){const t={x:0,y:0},n=V9t(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 j9s={x:.2,y:.2};function N9s(s,t,n,r,a){let{top:i,left:l,right:o,bottom:c}=n;r===void 0&&(r=10),a===void 0&&(a=j9s);const{isTop:d,isBottom:u,isLeft:h,isRight:m}=H9t(s),p={x:0,y:0},f={x:0,y:0},y={height:t.height*a.y,width:t.width*a.x};return!d&&i<=t.top+y.height?(p.y=uy.Backward,f.y=r*Math.abs((t.top+y.height-i)/y.height)):!u&&c>=t.bottom-y.height&&(p.y=uy.Forward,f.y=r*Math.abs((t.bottom-y.height-c)/y.height)),!m&&o>=t.right-y.width?(p.x=uy.Forward,f.x=r*Math.abs((t.right-y.width-o)/y.width)):!h&&l<=t.left+y.width&&(p.x=uy.Backward,f.x=r*Math.abs((t.left+y.width-l)/y.width)),{direction:p,speed:f}}function k9s(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 G9t(s){return s.reduce((t,n)=>S$(t,NVe(n)),AS)}function S9s(s){return s.reduce((t,n)=>t+q9t(n),0)}function C9s(s){return s.reduce((t,n)=>t+$9t(n),0)}function A9s(s,t){if(t===void 0&&(t=gW),!s)return;const{top:n,left:r,bottom:a,right:i}=t(s);U9t(s)&&(a<=0||i<=0||n>=window.innerHeight||r>=window.innerWidth)&&s.scrollIntoView({block:"center",inline:"center"})}const E9s=[["x",["left","right"],S9s],["y",["top","bottom"],C9s]];let cet=class{constructor(t,n){this.rect=void 0,this.width=void 0,this.height=void 0,this.top=void 0,this.bottom=void 0,this.right=void 0,this.left=void 0;const r=XPe(n),a=G9t(r);this.rect={...t},this.width=t.width,this.height=t.height;for(const[i,l,o]of E9s)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 SJ{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 T9s(s){const{EventTarget:t}=Y_(s);return s instanceof t?s:xW(s)}function a7e(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 z2;(function(s){s.Click="click",s.DragStart="dragstart",s.Keydown="keydown",s.ContextMenu="contextmenu",s.Resize="resize",s.SelectionChange="selectionchange",s.VisibilityChange="visibilitychange"})(z2||(z2={}));function igt(s){s.preventDefault()}function M9s(s){s.stopPropagation()}var uu;(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"})(uu||(uu={}));const W9t={start:[uu.Space,uu.Enter],cancel:[uu.Esc],end:[uu.Space,uu.Enter,uu.Tab]},P9s=(s,t)=>{let{currentCoordinates:n}=t;switch(s.code){case uu.Right:return{...n,x:n.x+25};case uu.Left:return{...n,x:n.x-25};case uu.Down:return{...n,y:n.y+25};case uu.Up:return{...n,y:n.y-25}}};class QPe{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 SJ(xW(n)),this.windowListeners=new SJ(Y_(n)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(z2.Resize,this.handleCancel),this.windowListeners.add(z2.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(z2.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:t,onStart:n}=this.props,r=t.node.current;r&&A9s(r),n(AS)}handleKeyDown(t){if(oet(t)){const{active:n,context:r,options:a}=this.props,{keyboardCodes:i=W9t,coordinateGetter:l=P9s,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}:AS;this.referenceCoordinates||(this.referenceCoordinates=u);const h=l(t,{active:n,context:r.current,currentCoordinates:u});if(h){const m=dte(h,u),p={x:0,y:0},{scrollableAncestors:f}=r.current;for(const y of f){const v=t.code,{isTop:g,isRight:b,isLeft:j,isBottom:S,maxScroll:C,minScroll:E}=H9t(y),P=k9s(y),M={x:Math.min(v===uu.Right?P.right-P.width/2:P.right,Math.max(v===uu.Right?P.left:P.left+P.width/2,h.x)),y:Math.min(v===uu.Down?P.bottom-P.height/2:P.bottom,Math.max(v===uu.Down?P.top:P.top+P.height/2,h.y))},I=v===uu.Right&&!b||v===uu.Left&&!j,D=v===uu.Down&&!S||v===uu.Up&&!g;if(I&&M.x!==h.x){const O=y.scrollLeft+m.x,V=v===uu.Right&&O<=C.x||v===uu.Left&&O>=E.x;if(V&&!m.y){y.scrollTo({left:O,behavior:o});return}V?p.x=y.scrollLeft-O:p.x=v===uu.Right?y.scrollLeft-C.x:y.scrollLeft-E.x,p.x&&y.scrollBy({left:-p.x,behavior:o});break}else if(D&&M.y!==h.y){const O=y.scrollTop+m.y,V=v===uu.Down&&O<=C.y||v===uu.Up&&O>=E.y;if(V&&!m.x){y.scrollTo({top:O,behavior:o});return}V?p.y=y.scrollTop-O:p.y=v===uu.Down?y.scrollTop-C.y:y.scrollTop-E.y,p.y&&y.scrollBy({top:-p.y,behavior:o});break}}this.handleMove(t,S$(dte(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()}}QPe.activators=[{eventName:"onKeyDown",handler:(s,t,n)=>{let{keyboardCodes:r=W9t,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 ogt(s){return!!(s&&"distance"in s)}function lgt(s){return!!(s&&"delay"in s)}class det{constructor(t,n,r){var a;r===void 0&&(r=T9s(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=xW(l),this.documentListeners=new SJ(this.document),this.listeners=new SJ(r),this.windowListeners=new SJ(Y_(l)),this.initialCoordinates=(a=jVe(i))!=null?a:AS,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(z2.Resize,this.handleCancel),this.windowListeners.add(z2.DragStart,igt),this.windowListeners.add(z2.VisibilityChange,this.handleCancel),this.windowListeners.add(z2.ContextMenu,igt),this.documentListeners.add(z2.Keydown,this.handleKeydown),n){if(r!=null&&r({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(lgt(n)){this.timeoutId=setTimeout(this.handleStart,n.delay),this.handlePending(n);return}if(ogt(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(z2.Click,M9s,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(z2.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=jVe(t))!=null?n:AS,d=dte(a,c);if(!r&&o){if(ogt(o)){if(o.tolerance!=null&&a7e(d,o.tolerance))return this.handleCancel();if(a7e(d,o.distance))return this.handleStart()}if(lgt(o)&&a7e(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===uu.Esc&&this.handleCancel()}removeTextSelection(){var t;(t=this.document.getSelection())==null||t.removeAllRanges()}}const L9s={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class yW extends det{constructor(t){const{event:n}=t,r=xW(n.target);super(t,L9s,r)}}yW.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 I9s={move:{name:"mousemove"},end:{name:"mouseup"}};var kVe;(function(s){s[s.RightClick=2]="RightClick"})(kVe||(kVe={}));class D9s extends det{constructor(t){super(t,I9s,xW(t.event.target))}}D9s.activators=[{eventName:"onMouseDown",handler:(s,t)=>{let{nativeEvent:n}=s,{onActivation:r}=t;return n.button===kVe.RightClick?!1:(r==null||r({event:n}),!0)}}];const i7e={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class R9s extends det{constructor(t){super(t,i7e)}static setup(){return window.addEventListener(i7e.move.name,t,{capture:!1,passive:!1}),function(){window.removeEventListener(i7e.move.name,t)};function t(){}}}R9s.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 CJ;(function(s){s[s.Pointer=0]="Pointer",s[s.DraggableRect=1]="DraggableRect"})(CJ||(CJ={}));var EAe;(function(s){s[s.TreeOrder=0]="TreeOrder",s[s.ReversedTreeOrder=1]="ReversedTreeOrder"})(EAe||(EAe={}));function F9s(s){let{acceleration:t,activator:n=CJ.Pointer,canScroll:r,draggingRect:a,enabled:i,interval:l=5,order:o=EAe.TreeOrder,pointerCoordinates:c,scrollableAncestors:d,scrollableAncestorRects:u,delta:h,threshold:m}=s;const p=z9s({delta:h,disabled:!i}),[f,y]=X7s(),v=_.useRef({x:0,y:0}),g=_.useRef({x:0,y:0}),b=_.useMemo(()=>{switch(n){case CJ.Pointer:return c?{top:c.y,bottom:c.y,left:c.x,right:c.x}:null;case CJ.DraggableRect:return a}},[n,a,c]),j=_.useRef(null),S=_.useCallback(()=>{const E=j.current;if(!E)return;const P=v.current.x*g.current.x,M=v.current.y*g.current.y;E.scrollBy(P,M)},[]),C=_.useMemo(()=>o===EAe.TreeOrder?[...d].reverse():d,[o,d]);_.useEffect(()=>{if(!i||!d.length||!b){y();return}for(const E of C){if((r==null?void 0:r(E))===!1)continue;const P=d.indexOf(E),M=u[P];if(!M)continue;const{direction:I,speed:D}=N9s(E,M,b,t,m);for(const O of["x","y"])p[O][I[O]]||(D[O]=0,I[O]=0);if(D.x>0||D.y>0){y(),j.current=E,f(S,l),v.current=D,g.current=I;return}}v.current={x:0,y:0},g.current={x:0,y:0},y()},[t,S,r,y,i,l,JSON.stringify(b),JSON.stringify(p),f,d,C,u,JSON.stringify(m)])}const O9s={x:{[uy.Backward]:!1,[uy.Forward]:!1},y:{[uy.Backward]:!1,[uy.Forward]:!1}};function z9s(s){let{delta:t,disabled:n}=s;const r=wVe(t);return sae(a=>{if(n||!r||!a)return O9s;const i={x:Math.sign(t.x-r.x),y:Math.sign(t.y-r.y)};return{x:{[uy.Backward]:a.x[uy.Backward]||i.x===-1,[uy.Forward]:a.x[uy.Forward]||i.x===1},y:{[uy.Backward]:a.y[uy.Backward]||i.y===-1,[uy.Forward]:a.y[uy.Forward]||i.y===1}}},[n,t,r])}function B9s(s,t){const n=t!=null?s.get(t):void 0,r=n?n.node.current:null;return sae(a=>{var i;return t==null?null:(i=r??a)!=null?i:null},[r,t])}function U9s(s,t){return _.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 ute;(function(s){s[s.Always=0]="Always",s[s.BeforeDragging=1]="BeforeDragging",s[s.WhileDragging=2]="WhileDragging"})(ute||(ute={}));var SVe;(function(s){s.Optimized="optimized"})(SVe||(SVe={}));const cgt=new Map;function q9s(s,t){let{dragging:n,dependencies:r,config:a}=t;const[i,l]=_.useState(null),{frequency:o,measure:c,strategy:d}=a,u=_.useRef(s),h=v(),m=cte(h),p=_.useCallback(function(g){g===void 0&&(g=[]),!m.current&&l(b=>b===null?g:b.concat(g.filter(j=>!b.includes(j))))},[m]),f=_.useRef(null),y=sae(g=>{if(h&&!n)return cgt;if(!g||g===cgt||u.current!==s||i!=null){const b=new Map;for(let j of s){if(!j)continue;if(i&&i.length>0&&!i.includes(j.id)&&j.rect.current){b.set(j.id,j.rect.current);continue}const S=j.node.current,C=S?new cet(c(S),S):null;j.rect.current=C,C&&b.set(j.id,C)}return b}return g},[s,i,n,h,c]);return _.useEffect(()=>{u.current=s},[s]),_.useEffect(()=>{h||p()},[n,h]),_.useEffect(()=>{i&&i.length>0&&l(null)},[JSON.stringify(i)]),_.useEffect(()=>{h||typeof o!="number"||f.current!==null||(f.current=setTimeout(()=>{p(),f.current=null},o))},[o,h,p,...r]),{droppableRects:y,measureDroppableContainers:p,measuringScheduled:i!=null};function v(){switch(d){case ute.Always:return!1;case ute.BeforeDragging:return n;default:return!n}}}function K9t(s,t){return sae(n=>s?n||(typeof t=="function"?t(s):s):null,[t,s])}function $9s(s,t){return K9t(s,t)}function V9s(s){let{callback:t,disabled:n}=s;const r=iet(t),a=_.useMemo(()=>{if(n||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:i}=window;return new i(r)},[r,n]);return _.useEffect(()=>()=>a==null?void 0:a.disconnect(),[a]),a}function JPe(s){let{callback:t,disabled:n}=s;const r=iet(t),a=_.useMemo(()=>{if(n||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:i}=window;return new i(r)},[n]);return _.useEffect(()=>()=>a==null?void 0:a.disconnect(),[a]),a}function H9s(s){return new cet(gW(s),s)}function dgt(s,t,n){t===void 0&&(t=H9s);const[r,a]=_.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=V9s({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=JPe({callback:i});return cC(()=>{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 G9s(s){const t=K9t(s);return B9t(s,t)}const ugt=[];function W9s(s){const t=_.useRef(s),n=sae(r=>s?r&&r!==ugt&&s&&t.current&&s.parentNode===t.current.parentNode?r:XPe(s):ugt,[s]);return _.useEffect(()=>{t.current=s},[s]),n}function K9s(s){const[t,n]=_.useState(null),r=_.useRef(s),a=_.useCallback(i=>{const l=r7e(i.target);l&&n(o=>o?(o.set(l,NVe(l)),new Map(o)):null)},[]);return _.useEffect(()=>{const i=r.current;if(s!==i){l(i);const o=s.map(c=>{const d=r7e(c);return d?(d.addEventListener("scroll",a,{passive:!0}),[d,NVe(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=r7e(c);d==null||d.removeEventListener("scroll",a)})}},[a,s]),_.useMemo(()=>s.length?t?Array.from(t.values()).reduce((i,l)=>S$(i,l),AS):G9t(s):AS,[s,t])}function hgt(s,t){t===void 0&&(t=[]);const n=_.useRef(null);return _.useEffect(()=>{n.current=null},t),_.useEffect(()=>{const r=s!==AS;r&&!n.current&&(n.current=s),!r&&n.current&&(n.current=null)},[s]),n.current?dte(s,n.current):AS}function Y9s(s){_.useEffect(()=>{if(!KPe)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 Z9s(s,t){return _.useMemo(()=>s.reduce((n,r)=>{let{eventName:a,handler:i}=r;return n[a]=l=>{i(l,t)},n},{}),[s,t])}function Y9t(s){return _.useMemo(()=>s?b9s(s):null,[s])}const mgt=[];function X9s(s,t){t===void 0&&(t=gW);const[n]=s,r=Y9t(n?Y_(n):null),[a,i]=_.useState(mgt);function l(){i(()=>s.length?s.map(c=>V9t(c)?r:new cet(t(c),c)):mgt)}const o=JPe({callback:l});return cC(()=>{o==null||o.disconnect(),l(),s.forEach(c=>o==null?void 0:o.observe(c))},[s]),a}function Q9s(s){if(!s)return null;if(s.children.length>1)return s;const t=s.children[0];return tae(t)?t:s}function J9s(s){let{measure:t}=s;const[n,r]=_.useState(null),a=_.useCallback(d=>{for(const{target:u}of d)if(tae(u)){r(h=>{const m=t(u);return h?{...h,width:m.width,height:m.height}:m});break}},[t]),i=JPe({callback:a}),l=_.useCallback(d=>{const u=Q9s(d);i==null||i.disconnect(),u&&(i==null||i.observe(u)),r(u?t(u):null)},[t,i]),[o,c]=CAe(l);return _.useMemo(()=>({nodeRef:o,rect:n,setRef:c}),[n,o,c])}const ezs=[{sensor:yW,options:{}},{sensor:QPe,options:{}}],tzs={current:{}},R4e={draggable:{measure:agt},droppable:{measure:agt,strategy:ute.WhileDragging,frequency:SVe.Optimized},dragOverlay:{measure:gW}};class AJ 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 szs={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new AJ,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:AAe},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:R4e,measureDroppableContainers:AAe,windowRect:null,measuringScheduled:!1},nzs={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:AAe,draggableNodes:new Map,over:null,measureDroppableContainers:AAe},eLe=_.createContext(nzs),Z9t=_.createContext(szs);function rzs(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new AJ}}}function azs(s,t){switch(t.type){case m0.DragStart:return{...s,draggable:{...s.draggable,initialCoordinates:t.initialCoordinates,active:t.active}};case m0.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 m0.DragEnd:case m0.DragCancel:return{...s,draggable:{...s.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case m0.RegisterDroppable:{const{element:n}=t,{id:r}=n,a=new AJ(s.droppable.containers);return a.set(r,n),{...s,droppable:{...s.droppable,containers:a}}}case m0.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 AJ(s.droppable.containers);return l.set(n,{...i,disabled:a}),{...s,droppable:{...s.droppable,containers:l}}}case m0.UnregisterDroppable:{const{id:n,key:r}=t,a=s.droppable.containers.get(n);if(!a||r!==a.key)return s;const i=new AJ(s.droppable.containers);return i.delete(n),{...s,droppable:{...s.droppable,containers:i}}}default:return s}}function izs(s){let{disabled:t}=s;const{active:n,activatorEvent:r,draggableNodes:a}=_.useContext(eLe),i=wVe(r),l=wVe(n==null?void 0:n.id);return _.useEffect(()=>{if(!t&&!r&&i&&l!=null){if(!oet(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=e9s(u);if(h){h.focus();break}}})}},[r,t,a,l,i]),null}function ozs(s,t){let{transform:n,...r}=t;return s!=null&&s.length?s.reduce((a,i)=>i({transform:a,...r}),n):n}function lzs(s){return _.useMemo(()=>({draggable:{...R4e.draggable,...s==null?void 0:s.draggable},droppable:{...R4e.droppable,...s==null?void 0:s.droppable},dragOverlay:{...R4e.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 czs(s){let{activeNode:t,measure:n,initialRect:r,config:a=!0}=s;const i=_.useRef(!1),{x:l,y:o}=typeof a=="boolean"?{x:a,y:a}:a;cC(()=>{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=B9t(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=U9t(d);m&&m.scrollBy({top:h.y,left:h.x})}},[t,l,o,r,n])}const X9t=_.createContext({...AS,scaleX:1,scaleY:1});var c6;(function(s){s[s.Uninitialized=0]="Uninitialized",s[s.Initializing=1]="Initializing",s[s.Initialized=2]="Initialized"})(c6||(c6={}));const tLe=_.memo(function(t){var n,r,a,i;let{id:l,accessibility:o,autoScroll:c=!0,children:d,sensors:u=ezs,collisionDetection:h=m9s,measuring:m,modifiers:p,...f}=t;const y=_.useReducer(azs,void 0,rzs),[v,g]=y,[b,j]=i9s(),[S,C]=_.useState(c6.Uninitialized),E=S===c6.Initialized,{draggable:{active:P,nodes:M,translate:I},droppable:{containers:D}}=v,O=P!=null?M.get(P):null,V=_.useRef({initial:null,translated:null}),G=_.useMemo(()=>{var Vs;return P!=null?{id:P,data:(Vs=O==null?void 0:O.data)!=null?Vs:tzs,rect:V}:null},[P,O]),$=_.useRef(null),[H,Y]=_.useState(null),[Z,ne]=_.useState(null),ce=cte(f,Object.values(f)),ie=nae("DndDescribedBy",l),te=_.useMemo(()=>D.getEnabled(),[D]),ae=lzs(m),{droppableRects:le,measureDroppableContainers:be,measuringScheduled:me}=q9s(te,{dragging:E,dependencies:[I.x,I.y],config:ae.droppable}),he=B9s(M,P),pe=_.useMemo(()=>Z?jVe(Z):null,[Z]),Ce=Ur(),Ae=$9s(he,ae.draggable.measure);czs({activeNode:P!=null?M.get(P):null,config:Ce.layoutShiftCompensation,initialRect:Ae,measure:ae.draggable.measure});const Pe=dgt(he,ae.draggable.measure,Ae),ze=dgt(he?he.parentElement:null),ke=_.useRef({activatorEvent:null,active:null,activeNode:he,collisionRect:null,collisions:null,droppableRects:le,draggableNodes:M,draggingNode:null,draggingNodeRect:null,droppableContainers:D,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),Ze=D.getNodeFor((n=ke.current.over)==null?void 0:n.id),Se=J9s({measure:ae.dragOverlay.measure}),Fe=(r=Se.nodeRef.current)!=null?r:he,Ne=E?(a=Se.rect)!=null?a:Pe:null,Ye=!!(Se.nodeRef.current&&Se.rect),Ve=G9s(Ye?null:Pe),qe=Y9t(Fe?Y_(Fe):null),Qe=W9s(E?Ze??he:null),Ue=X9s(Qe),Xe=ozs(p,{transform:{x:I.x-Ve.x,y:I.y-Ve.y,scaleX:1,scaleY:1},activatorEvent:Z,active:G,activeNodeRect:Pe,containerNodeRect:ze,draggingNodeRect:Ne,over:ke.current.over,overlayNodeRect:Se.rect,scrollableAncestors:Qe,scrollableAncestorRects:Ue,windowRect:qe}),nt=pe?S$(pe,I):null,$e=K9s(Qe),Ge=hgt($e),ct=hgt($e,[Pe]),xt=S$(Xe,Ge),qt=Ne?x9s(Ne,Xe):null,Vt=G&&qt?h({active:G,collisionRect:qt,droppableRects:le,droppableContainers:te,pointerCoordinates:nt}):null,Xt=z9t(Vt,"id"),[fs,Ft]=_.useState(null),wt=Ye?Xe:S$(Xe,ct),Ts=p9s(wt,(i=fs==null?void 0:fs.rect)!=null?i:null,Pe),vt=_.useRef(null),$s=_.useCallback((Vs,hn)=>{let{sensor:dr,options:Cn}=hn;if($.current==null)return;const Yn=M.get($.current);if(!Yn)return;const on=Vs.nativeEvent,Ir=new dr({active:$.current,activeNode:Yn,event:on,options:Cn,context:ke,onAbort(Js){if(!M.get(Js))return;const{onDragAbort:ks}=ce.current,Gs={id:Js};ks==null||ks(Gs),b({type:"onDragAbort",event:Gs})},onPending(Js,Fa,ks,Gs){if(!M.get(Js))return;const{onDragPending:Ys}=ce.current,Bn={id:Js,constraint:Fa,initialCoordinates:ks,offset:Gs};Ys==null||Ys(Bn),b({type:"onDragPending",event:Bn})},onStart(Js){const Fa=$.current;if(Fa==null)return;const ks=M.get(Fa);if(!ks)return;const{onDragStart:Gs}=ce.current,Ws={activatorEvent:on,active:{id:Fa,data:ks.data,rect:V}};mv.unstable_batchedUpdates(()=>{Gs==null||Gs(Ws),C(c6.Initializing),g({type:m0.DragStart,initialCoordinates:Js,active:Fa}),b({type:"onDragStart",event:Ws}),Y(vt.current),ne(on)})},onMove(Js){g({type:m0.DragMove,coordinates:Js})},onEnd:Wn(m0.DragEnd),onCancel:Wn(m0.DragCancel)});vt.current=Ir;function Wn(Js){return async function(){const{active:ks,collisions:Gs,over:Ws,scrollAdjustedTranslate:Ys}=ke.current;let Bn=null;if(ks&&Ys){const{cancelDrop:or}=ce.current;Bn={activatorEvent:on,active:ks,collisions:Gs,delta:Ys,over:Ws},Js===m0.DragEnd&&typeof or=="function"&&await Promise.resolve(or(Bn))&&(Js=m0.DragCancel)}$.current=null,mv.unstable_batchedUpdates(()=>{g({type:Js}),C(c6.Uninitialized),Ft(null),Y(null),ne(null),vt.current=null;const or=Js===m0.DragEnd?"onDragEnd":"onDragCancel";if(Bn){const Wt=ce.current[or];Wt==null||Wt(Bn),b({type:or,event:Bn})}})}}},[M]),As=_.useCallback((Vs,hn)=>(dr,Cn)=>{const Yn=dr.nativeEvent,on=M.get(Cn);if($.current!==null||!on||Yn.dndKit||Yn.defaultPrevented)return;const Ir={active:on};Vs(dr,hn.options,Ir)===!0&&(Yn.dndKit={capturedBy:hn.sensor},$.current=Cn,$s(dr,hn))},[M,$s]),jn=U9s(u,As);Y9s(u),cC(()=>{Pe&&S===c6.Initializing&&C(c6.Initialized)},[Pe,S]),_.useEffect(()=>{const{onDragMove:Vs}=ce.current,{active:hn,activatorEvent:dr,collisions:Cn,over:Yn}=ke.current;if(!hn||!dr)return;const on={active:hn,activatorEvent:dr,collisions:Cn,delta:{x:xt.x,y:xt.y},over:Yn};mv.unstable_batchedUpdates(()=>{Vs==null||Vs(on),b({type:"onDragMove",event:on})})},[xt.x,xt.y]),_.useEffect(()=>{const{active:Vs,activatorEvent:hn,collisions:dr,droppableContainers:Cn,scrollAdjustedTranslate:Yn}=ke.current;if(!Vs||$.current==null||!hn||!Yn)return;const{onDragOver:on}=ce.current,Ir=Cn.get(Xt),Wn=Ir&&Ir.rect.current?{id:Ir.id,rect:Ir.rect.current,data:Ir.data,disabled:Ir.disabled}:null,Js={active:Vs,activatorEvent:hn,collisions:dr,delta:{x:Yn.x,y:Yn.y},over:Wn};mv.unstable_batchedUpdates(()=>{Ft(Wn),on==null||on(Js),b({type:"onDragOver",event:Js})})},[Xt]),cC(()=>{ke.current={activatorEvent:Z,active:G,activeNode:he,collisionRect:qt,collisions:Vt,droppableRects:le,draggableNodes:M,draggingNode:Fe,draggingNodeRect:Ne,droppableContainers:D,over:fs,scrollableAncestors:Qe,scrollAdjustedTranslate:xt},V.current={initial:Ne,translated:qt}},[G,he,Vt,qt,M,Fe,Ne,le,D,fs,Qe,xt]),F9s({...Ce,delta:I,draggingRect:qt,pointerCoordinates:nt,scrollableAncestors:Qe,scrollableAncestorRects:Ue});const ar=_.useMemo(()=>({active:G,activeNode:he,activeNodeRect:Pe,activatorEvent:Z,collisions:Vt,containerNodeRect:ze,dragOverlay:Se,draggableNodes:M,droppableContainers:D,droppableRects:le,over:fs,measureDroppableContainers:be,scrollableAncestors:Qe,scrollableAncestorRects:Ue,measuringConfiguration:ae,measuringScheduled:me,windowRect:qe}),[G,he,Pe,Z,Vt,ze,Se,M,D,le,fs,be,Qe,Ue,ae,me,qe]),Dn=_.useMemo(()=>({activatorEvent:Z,activators:jn,active:G,activeNodeRect:Pe,ariaDescribedById:{draggable:ie},dispatch:g,draggableNodes:M,over:fs,measureDroppableContainers:be}),[Z,jn,G,Pe,g,ie,M,fs,be]);return Dt.createElement(R9t.Provider,{value:j},Dt.createElement(eLe.Provider,{value:Dn},Dt.createElement(Z9t.Provider,{value:ar},Dt.createElement(X9t.Provider,{value:Ts},d)),Dt.createElement(izs,{disabled:(o==null?void 0:o.restoreFocus)===!1})),Dt.createElement(c9s,{...o,hiddenTextDescribedById:ie}));function Ur(){const Vs=(H==null?void 0:H.autoScrollEnabled)===!1,hn=typeof c=="object"?c.enabled===!1:c===!1,dr=E&&!Vs&&!hn;return typeof c=="object"?{...c,enabled:dr}:{enabled:dr}}}),dzs=_.createContext(null),pgt="button",uzs="Draggable";function hzs(s){let{id:t,data:n,disabled:r=!1,attributes:a}=s;const i=nae(uzs),{activators:l,activatorEvent:o,active:c,activeNodeRect:d,ariaDescribedById:u,draggableNodes:h,over:m}=_.useContext(eLe),{role:p=pgt,roleDescription:f="draggable",tabIndex:y=0}=a??{},v=(c==null?void 0:c.id)===t,g=_.useContext(v?X9t:dzs),[b,j]=CAe(),[S,C]=CAe(),E=Z9s(l,t),P=cte(n);cC(()=>(h.set(t,{id:t,key:i,node:b,activatorNode:S,data:P}),()=>{const I=h.get(t);I&&I.key===i&&h.delete(t)}),[h,t]);const M=_.useMemo(()=>({role:p,tabIndex:y,"aria-disabled":r,"aria-pressed":v&&p===pgt?!0:void 0,"aria-roledescription":f,"aria-describedby":u.draggable}),[r,p,y,v,f,u.draggable]);return{active:c,activatorEvent:o,activeNodeRect:d,attributes:M,isDragging:v,listeners:r?void 0:E,node:b,over:m,setNodeRef:j,setActivatorNodeRef:C,transform:g}}function mzs(){return _.useContext(Z9t)}const pzs="Droppable",fzs={timeout:25};function xzs(s){let{data:t,disabled:n=!1,id:r,resizeObserverConfig:a}=s;const i=nae(pzs),{active:l,dispatch:o,over:c,measureDroppableContainers:d}=_.useContext(eLe),u=_.useRef({disabled:n}),h=_.useRef(!1),m=_.useRef(null),p=_.useRef(null),{disabled:f,updateMeasurementsFor:y,timeout:v}={...fzs,...a},g=cte(y??r),b=_.useCallback(()=>{if(!h.current){h.current=!0;return}p.current!=null&&clearTimeout(p.current),p.current=setTimeout(()=>{d(Array.isArray(g.current)?g.current:[g.current]),p.current=null},v)},[v]),j=JPe({callback:b,disabled:f||!l}),S=_.useCallback((M,I)=>{j&&(I&&(j.unobserve(I),h.current=!1),M&&j.observe(M))},[j]),[C,E]=CAe(S),P=cte(t);return _.useEffect(()=>{!j||!C.current||(j.disconnect(),h.current=!1,j.observe(C.current))},[C,j]),_.useEffect(()=>(o({type:m0.RegisterDroppable,element:{id:r,key:i,disabled:n,node:C,rect:m,data:P}}),()=>o({type:m0.UnregisterDroppable,key:i,id:r})),[r]),_.useEffect(()=>{n!==u.current.disabled&&(o({type:m0.SetDroppableDisabled,id:r,key:i,disabled:n}),u.current.disabled=n)},[r,i,n,o]),{active:l,rect:m,isOver:(c==null?void 0:c.id)===r,node:C,over:c,setNodeRef:E}}function sLe(s,t,n){const r=s.slice();return r.splice(n<0?r.length+n:n,0,r.splice(t,1)[0]),r}function gzs(s,t){return s.reduce((n,r,a)=>{const i=t.get(r);return i&&(n[a]=i),n},Array(s.length))}function Ple(s){return s!==null&&s>=0}function yzs(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=bzs(n,l,a);if(l===a){const d=n[i];return d?{x:aa&&l<=i?{x:-o.width-c,y:0,...Lle}:l=i?{x:o.width+c,y:0,...Lle}:{x:0,y:0,...Lle}};function bzs(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=sLe(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}},Ile={scaleX:1,scaleY:1},_zs=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,...Ile}:a=l?{x:0,y:o.height+c,...Ile}:{x:0,y:0,...Ile}};function wzs(s,t,n){const r=s[t],a=s[t-1],i=s[t+1];return r?nr.map(E=>typeof E=="object"&&"id"in E?E.id:E),[r]),f=l!=null,y=l?p.indexOf(l.id):-1,v=d?p.indexOf(d.id):-1,g=_.useRef(p),b=!yzs(p,g.current),j=v!==-1&&y===-1||b,S=vzs(i);cC(()=>{b&&f&&u(p)},[b,p,f,u]),_.useEffect(()=>{g.current=p},[p]);const C=_.useMemo(()=>({activeIndex:y,containerId:h,disabled:S,disableTransforms:j,items:p,overIndex:v,useDragOverlay:m,sortedRects:gzs(p,c),strategy:a}),[y,h,S.draggable,S.droppable,j,p,v,c,m,a]);return Dt.createElement(J9t.Provider,{value:C},t)}const jzs=s=>{let{id:t,items:n,activeIndex:r,overIndex:a}=s;return sLe(n,r,a).indexOf(t)},Nzs=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},kzs={duration:200,easing:"ease"},ezt="transform",Szs=OP.Transition.toString({property:ezt,duration:0,easing:"linear"}),Czs={roleDescription:"sortable"};function Azs(s){let{disabled:t,index:n,node:r,rect:a}=s;const[i,l]=_.useState(null),o=_.useRef(n);return cC(()=>{if(!t&&n!==o.current&&r.current){const c=a.current;if(c){const d=gW(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]),_.useEffect(()=>{i&&l(null)},[i]),i}function rLe(s){let{animateLayoutChanges:t=Nzs,attributes:n,disabled:r,data:a,getNewIndex:i=jzs,id:l,strategy:o,resizeObserverConfig:c,transition:d=kzs}=s;const{items:u,containerId:h,activeIndex:m,disabled:p,disableTransforms:f,sortedRects:y,overIndex:v,useDragOverlay:g,strategy:b}=_.useContext(J9t),j=Ezs(r,p),S=u.indexOf(l),C=_.useMemo(()=>({sortable:{containerId:h,index:S,items:u},...a}),[h,a,S,u]),E=_.useMemo(()=>u.slice(u.indexOf(l)),[u,l]),{rect:P,node:M,isOver:I,setNodeRef:D}=xzs({id:l,data:C,disabled:j.droppable,resizeObserverConfig:{updateMeasurementsFor:E,...c}}),{active:O,activatorEvent:V,activeNodeRect:G,attributes:$,setNodeRef:H,listeners:Y,isDragging:Z,over:ne,setActivatorNodeRef:ce,transform:ie}=hzs({id:l,data:C,attributes:{...Czs,...n},disabled:j.draggable}),te=Z7s(D,H),ae=!!O,le=ae&&!f&&Ple(m)&&Ple(v),be=!g&&Z,me=be&&le?ie:null,pe=le?me??(o??b)({rects:y,activeNodeRect:G,activeIndex:m,overIndex:v,index:S}):null,Ce=Ple(m)&&Ple(v)?i({id:l,items:u,activeIndex:m,overIndex:v}):S,Ae=O==null?void 0:O.id,Pe=_.useRef({activeId:Ae,items:u,newIndex:Ce,containerId:h}),ze=u!==Pe.current.items,ke=t({active:O,containerId:h,isDragging:Z,isSorting:ae,id:l,index:S,items:u,newIndex:Pe.current.newIndex,previousItems:Pe.current.items,previousContainerId:Pe.current.containerId,transition:d,wasDragging:Pe.current.activeId!=null}),Ze=Azs({disabled:!ke,index:S,node:M,rect:P});return _.useEffect(()=>{ae&&Pe.current.newIndex!==Ce&&(Pe.current.newIndex=Ce),h!==Pe.current.containerId&&(Pe.current.containerId=h),u!==Pe.current.items&&(Pe.current.items=u)},[ae,Ce,h,u]),_.useEffect(()=>{if(Ae===Pe.current.activeId)return;if(Ae!=null&&Pe.current.activeId==null){Pe.current.activeId=Ae;return}const Fe=setTimeout(()=>{Pe.current.activeId=Ae},50);return()=>clearTimeout(Fe)},[Ae]),{active:O,activeIndex:m,attributes:$,data:C,rect:P,index:S,newIndex:Ce,items:u,isOver:I,isSorting:ae,isDragging:Z,listeners:Y,node:M,overIndex:v,over:ne,setNodeRef:te,setActivatorNodeRef:ce,setDroppableNodeRef:D,setDraggableNodeRef:H,transform:Ze??pe,transition:Se()};function Se(){if(Ze||ze&&Pe.current.newIndex===S)return Szs;if(!(be&&!oet(V)||!d)&&(ae||ke))return OP.Transition.toString({...d,property:ezt})}}function Ezs(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 TAe(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 Tzs=[uu.Down,uu.Right,uu.Up,uu.Left],tzt=(s,t)=>{let{context:{active:n,collisionRect:r,droppableRects:a,droppableContainers:i,over:l,scrollableAncestors:o}}=t;if(Tzs.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 uu.Down:r.topm.top&&c.push(h);break;case uu.Left:r.left>m.left&&c.push(h);break;case uu.Right:r.left1&&(u=d[1].id),u!=null){const h=i.get(n.id),m=i.get(u),p=m?a.get(m.id):null,f=m==null?void 0:m.node.current;if(f&&p&&h&&m){const v=XPe(f).some((E,P)=>o[P]!==E),g=szt(h,m),b=Mzs(h,m),j=v||!g?{x:0,y:0}:{x:b?r.width-p.width:0,y:b?r.height-p.height:0},S={x:p.left,y:p.top};return j.x&&j.y?S:dte(S,j)}}}};function szt(s,t){return!TAe(s)||!TAe(t)?!1:s.data.current.sortable.containerId===t.data.current.sortable.containerId}function Mzs(s,t){return!TAe(s)||!TAe(t)||!szt(s,t)?!1:s.data.current.sortable.indexn(s.id),className:"absolute top-1 right-1 p-1 bg-destructive text-destructive-foreground rounded-full hover:bg-destructive/90 opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx(Qn,{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(Da,{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 nzt({photos:s,uploading:t,onUpload:n,onRemove:r,onReorder:a,onSetPrimary:i}){var h,m;const l=YPe(IH(yW,{activationConstraint:{distance:5}})),o=[...s].sort((p,f)=>(p.sort_order??0)-(f.sort_order??0)),c=((h=o.find(p=>p.is_primary))==null?void 0:h.id)??null,d=c??((m=o[0])==null?void 0:m.id),u=p=>{var E;const{active:f,over:y}=p;if(!y||f.id===y.id)return;const v=o.findIndex(P=>P.id===f.id),g=o.findIndex(P=>P.id===y.id),b=[...o],[j]=b.splice(v,1);b.splice(g,0,j);const S=c??((E=b[0])==null?void 0:E.id),C=b.map((P,M)=>({...P,sort_order:M,is_primary:P.id===S}));a(C)};return e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Drag photos to reorder. Hover to set primary."}),e.jsx(tLe,{sensors:l,collisionDetection:ZPe,onDragEnd:u,children:e.jsx(nLe,{items:o.map(p=>p.id),strategy:rae,children:e.jsxs("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-4",children:[o.map(p=>e.jsx(Pzs,{photo:p,isPrimary:p.id===d,onRemove:r,onSetPrimary:i},p.id)),e.jsxs("label",{className:"aspect-square rounded-lg border-2 border-dashed border-muted-foreground/25 hover:border-muted-foreground/50 cursor-pointer flex flex-col items-center justify-center gap-2 text-muted-foreground",children:[t?e.jsx(Ct,{className:"h-8 w-8 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Oa,{className:"h-8 w-8"}),e.jsx("span",{className:"text-xs",children:"Upload"})]}),e.jsx("input",{type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:p=>n(p.target.files),disabled:t})]})]})})})]})}function aLe({open:s,onOpenChange:t,listingId:n,listingSlug:r,listingTitle:a,isCommercial:i=!1}){const{user:l}=hs(),[o,c]=_.useState(null),[d,u]=_.useState(!1),[h,m]=_.useState(!1);_.useEffect(()=>{(async()=>{if(!(!s||!l)){u(!0);try{const{data:g,error:b}=await q.from("listing_shares").select("id, share_token, click_count, lead_count").eq("listing_id",n).eq("sharing_agent_id",l.id).order("created_at",{ascending:!1}).limit(1).maybeSingle();if(b)throw b;if(g&&g.share_token)c(g);else if(g&&!g.share_token){const{data:j,error:S}=await q.from("listing_shares").update({share_type:"referral_link"}).eq("id",g.id).select("id, share_token, click_count, lead_count").single();if(S)throw S;c(j)}else{const{data:j,error:S}=await q.from("listing_shares").insert({listing_id:n,sharing_agent_id:l.id,share_type:"referral_link"}).select("id, share_token, click_count, lead_count").single();if(S)throw S;c(j)}}catch(g){console.error("Error creating share link:",g),se.error("Failed to generate share link")}finally{u(!1)}}})()},[s,l,n]);const p=o!=null&&o.share_token?`${i?R6s:"https://listings.relevelup.com"}/${r||n}?ref=${o.share_token}`:"",f=async()=>{try{await navigator.clipboard.writeText(p),m(!0),se.success("Link copied to clipboard!"),setTimeout(()=>m(!1),2e3)}catch{se.error("Failed to copy link")}},y=v=>{const g=encodeURIComponent(p),b=encodeURIComponent(`Check out this listing: ${a}`);switch(v){case"email":window.open(`mailto:?subject=${b}&body=${g}`);break;case"text":window.open(`sms:?body=${b}%20${g}`);break;case"facebook":window.open(`https://www.facebook.com/sharer/sharer.php?u=${g}`,"_blank");break}};return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"sm:max-w-md",children:[e.jsxs(Os,{children:[e.jsxs(Ds,{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-5 w-5 text-amber-500"}),"Share & Earn Leads"]}),e.jsx(_r,{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(J,{children:"Your Referral Link"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{value:d?"Generating...":p,readOnly:!0,className:"font-mono text-sm"}),e.jsx(B,{onClick:f,disabled:d||!p,variant:h?"default":"outline",children:h?e.jsx(ea,{className:"h-4 w-4"}):e.jsx(Ia,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Share via"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{variant:"outline",className:"flex-1",onClick:()=>y("email"),disabled:d,children:[e.jsx(ln,{className:"h-4 w-4 mr-2"}),"Email"]}),e.jsxs(B,{variant:"outline",className:"flex-1",onClick:()=>y("text"),disabled:d,children:[e.jsx(Hi,{className:"h-4 w-4 mr-2"}),"Text"]}),e.jsxs(B,{variant:"outline",className:"flex-1",onClick:()=>y("facebook"),disabled:d,children:[e.jsx(tf,{className:"h-4 w-4 mr-2"}),"Facebook"]})]})]}),o&&(o.click_count>0||o.lead_count>0)&&e.jsxs("div",{className:"pt-4 border-t",children:[e.jsx(J,{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(ya,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs",children:"Clicks"})]}),e.jsx("p",{className:"text-2xl font-bold",children:o.click_count})]}),e.jsxs("div",{className:"bg-primary/10 rounded-lg p-3 text-center",children:[e.jsxs("div",{className:"flex items-center justify-center gap-1 text-primary mb-1",children:[e.jsx(In,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs",children:"Leads"})]}),e.jsx("p",{className:"text-2xl font-bold text-primary",children:o.lead_count})]})]})]})]})]})})}var Lzs=Object.defineProperty,MAe=Object.getOwnPropertySymbols,rzt=Object.prototype.hasOwnProperty,azt=Object.prototype.propertyIsEnumerable,fgt=(s,t,n)=>t in s?Lzs(s,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):s[t]=n,CVe=(s,t)=>{for(var n in t||(t={}))rzt.call(t,n)&&fgt(s,n,t[n]);if(MAe)for(var n of MAe(t))azt.call(t,n)&&fgt(s,n,t[n]);return s},AVe=(s,t)=>{var n={};for(var r in s)rzt.call(s,r)&&t.indexOf(r)<0&&(n[r]=s[r]);if(s!=null&&MAe)for(var r of MAe(s))t.indexOf(r)<0&&azt.call(s,r)&&(n[r]=s[r]);return n};/** * @license QR Code generator library (TypeScript) * Copyright (c) Project Nayuki. * SPDX-License-Identifier: MIT */var Q7;(s=>{const t=class Ld{constructor(c,d,u,h){if(this.version=c,this.errorCorrectionLevel=d,this.modules=[],this.isFunction=[],cLd.MAX_VERSION)throw new RangeError("Version value out of range");if(h<-1||h>7)throw new RangeError("Mask value out of range");this.size=c*4+17;let m=[];for(let f=0;f7)throw new RangeError("Invalid value");let f,y;for(f=u;;f++){const j=Ld.getNumDataCodewords(f,d)*8,S=l.getTotalBits(c,f);if(S<=j){y=S;break}if(f>=h)throw new RangeError("Data too long")}for(const j of[Ld.Ecc.MEDIUM,Ld.Ecc.QUARTILE,Ld.Ecc.HIGH])p&&y<=Ld.getNumDataCodewords(f,j)*8&&(d=j);let v=[];for(const j of c){n(j.mode.modeBits,4,v),n(j.numChars,j.mode.numCharCountBits(f),v);for(const S of j.getData())v.push(S)}a(v.length==y);const g=Ld.getNumDataCodewords(f,d)*8;a(v.length<=g),n(0,Math.min(4,g-v.length),v),n(0,(8-v.length%8)%8,v),a(v.length%8==0);for(let j=236;v.lengthb[S>>>3]|=j<<7-(S&7)),new Ld(f,d,b,m)}getModule(c,d){return 0<=c&&c>>9)*1335;const h=(d<<10|u)^21522;a(h>>>15==0);for(let m=0;m<=5;m++)this.setFunctionModule(8,m,r(h,m));this.setFunctionModule(8,7,r(h,6)),this.setFunctionModule(8,8,r(h,7)),this.setFunctionModule(7,8,r(h,8));for(let m=9;m<15;m++)this.setFunctionModule(14-m,8,r(h,m));for(let m=0;m<8;m++)this.setFunctionModule(this.size-1-m,8,r(h,m));for(let m=8;m<15;m++)this.setFunctionModule(8,this.size-15+m,r(h,m));this.setFunctionModule(8,this.size-8,!0)}drawVersion(){if(this.version<7)return;let c=this.version;for(let u=0;u<12;u++)c=c<<1^(c>>>11)*7973;const d=this.version<<12|c;a(d>>>18==0);for(let u=0;u<18;u++){const h=r(d,u),m=this.size-11+u%3,p=Math.floor(u/3);this.setFunctionModule(m,p,h),this.setFunctionModule(p,m,h)}}drawFinderPattern(c,d){for(let u=-4;u<=4;u++)for(let h=-4;h<=4;h++){const m=Math.max(Math.abs(h),Math.abs(u)),p=c+h,f=d+u;0<=p&&p{(j!=y-m||C>=f)&&b.push(S[j])});return a(b.length==p),b}drawCodewords(c){if(c.length!=Math.floor(Ld.getNumRawDataModules(this.version)/8))throw new RangeError("Invalid argument");let d=0;for(let u=this.size-1;u>=1;u-=2){u==6&&(u=5);for(let h=0;h>>3],7-(d&7)),d++)}}a(d==c.length*8)}applyMask(c){if(c<0||c>7)throw new RangeError("Mask value out of range");for(let d=0;d5&&c++):(this.finderPenaltyAddHistory(f,y),p||(c+=this.finderPenaltyCountPatterns(y)*Ld.PENALTY_N3),p=this.modules[m][v],f=1);c+=this.finderPenaltyTerminateAndCount(p,f,y)*Ld.PENALTY_N3}for(let m=0;m5&&c++):(this.finderPenaltyAddHistory(f,y),p||(c+=this.finderPenaltyCountPatterns(y)*Ld.PENALTY_N3),p=this.modules[v][m],f=1);c+=this.finderPenaltyTerminateAndCount(p,f,y)*Ld.PENALTY_N3}for(let m=0;mp+(f?1:0),d);const u=this.size*this.size,h=Math.ceil(Math.abs(d*20-u*10)/u)-1;return a(0<=h&&h<=9),c+=h*Ld.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.lengthLd.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(Ld.getNumRawDataModules(c)/8)-Ld.ECC_CODEWORDS_PER_BLOCK[d.ordinal][c]*Ld.NUM_ERROR_CORRECTION_BLOCKS[d.ordinal][c]}static reedSolomonComputeDivisor(c){if(c<1||c>255)throw new RangeError("Degree out of range");let d=[];for(let h=0;h0);for(const h of c){const m=h^u.shift();u.push(0),d.forEach((p,f)=>u[f]^=Ld.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 dx{constructor(c,d,u){if(this.mode=c,this.numChars=d,this.bitData=u,d<0)throw new RangeError("Invalid argument");this.bitData=u.slice()}static makeBytes(c){let d=[];for(const u of c)n(u,8,d);return new dx(dx.Mode.BYTE,c.length,d)}static makeNumeric(c){if(!dx.isNumeric(c))throw new RangeError("String contains non-numeric characters");let d=[];for(let u=0;u=1<{(t=>{const n=class{constructor(a,i){this.ordinal=a,this.formatBits=i}};n.LOW=new n(0,1),n.MEDIUM=new n(1,0),n.QUARTILE=new n(2,3),n.HIGH=new n(3,2),t.Ecc=n})(s.QrCode||(s.QrCode={}))})(Q7||(Q7={}));(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={}))})(Q7||(Q7={}));var JU=Q7;/** * @license qrcode.react * Copyright (c) Paul O'Shannessy * SPDX-License-Identifier: ISC */var Izs={L:JU.QrCode.Ecc.LOW,M:JU.QrCode.Ecc.MEDIUM,Q:JU.QrCode.Ecc.QUARTILE,H:JU.QrCode.Ecc.HIGH},izt=128,ozt="L",lzt="#FFFFFF",czt="#000000",dzt=!1,uzt=1,Dzs=4,Rzs=0,Fzs=.1;function hzt(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 mzt(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 Ozs(s,t,n,r){if(r==null)return null;const a=s.length+n*2,i=Math.floor(t*Fzs),l=a/t,o=(r.width||i)*l,c=(r.height||i)*l,d=r.x==null?s.length/2-o/2:r.x*l,u=r.y==null?s.length/2-c/2:r.y*l,h=r.opacity==null?1:r.opacity;let m=null;if(r.excavate){let f=Math.floor(d),y=Math.floor(u),v=Math.ceil(o+d-f),g=Math.ceil(c+u-y);m={x:f,y,w:v,h:g}}const p=r.crossOrigin;return{x:d,y:u,h:c,w:o,excavation:m,opacity:h,crossOrigin:p}}function zzs(s,t){return t!=null?Math.max(Math.floor(t),0):s?Dzs:Rzs}function pzt({value:s,level:t,minVersion:n,includeMargin:r,marginSize:a,imageSettings:i,size:l,boostLevel:o}){let c=Dt.useMemo(()=>{const f=(Array.isArray(s)?s:[s]).reduce((y,v)=>(y.push(...JU.QrSegment.makeSegments(v)),y),[]);return JU.QrCode.encodeSegments(f,Izs[t],n,void 0,void 0,o)},[s,t,n,o]);const{cells:d,margin:u,numCells:h,calculatedImageSettings:m}=Dt.useMemo(()=>{let p=c.getModules();const f=zzs(r,a),y=p.length+f*2,v=Ozs(p,l,f,i);return{cells:p,margin:f,numCells:y,calculatedImageSettings:v}},[c,l,i,r,a]);return{qrcode:c,margin:u,cells:d,numCells:h,calculatedImageSettings:m}}var Bzs=function(){try{new Path2D().addPath(new Path2D)}catch{return!1}return!0}(),Uzs=Dt.forwardRef(function(t,n){const r=t,{value:a,size:i=izt,level:l=ozt,bgColor:o=lzt,fgColor:c=czt,includeMargin:d=dzt,minVersion:u=uzt,boostLevel:h,marginSize:m,imageSettings:p}=r,y=AVe(r,["value","size","level","bgColor","fgColor","includeMargin","minVersion","boostLevel","marginSize","imageSettings"]),{style:v}=y,g=AVe(y,["style"]),b=p==null?void 0:p.src,j=Dt.useRef(null),S=Dt.useRef(null),C=Dt.useCallback($=>{j.current=$,typeof n=="function"?n($):n&&(n.current=$)},[n]),[E,P]=Dt.useState(!1),{margin:M,cells:I,numCells:D,calculatedImageSettings:O}=pzt({value:a,level:l,minVersion:u,boostLevel:h,includeMargin:d,marginSize:m,imageSettings:p,size:i});Dt.useEffect(()=>{if(j.current!=null){const $=j.current,H=$.getContext("2d");if(!H)return;let Y=I;const Z=S.current,ne=O!=null&&Z!==null&&Z.complete&&Z.naturalHeight!==0&&Z.naturalWidth!==0;ne&&O.excavation!=null&&(Y=mzt(I,O.excavation));const ce=window.devicePixelRatio||1;$.height=$.width=i*ce;const ie=i/D*ce;H.scale(ie,ie),H.fillStyle=o,H.fillRect(0,0,D,D),H.fillStyle=c,Bzs?H.fill(new Path2D(hzt(Y,M))):I.forEach(function(te,ae){te.forEach(function(le,be){le&&H.fillRect(be+M,ae+M,1,1)})}),O&&(H.globalAlpha=O.opacity),ne&&H.drawImage(Z,O.x+M,O.y+M,O.w,O.h)}}),Dt.useEffect(()=>{P(!1)},[b]);const V=CVe({height:i,width:i},v);let G=null;return b!=null&&(G=Dt.createElement("img",{src:b,key:b,style:{display:"none"},onLoad:()=>{P(!0)},ref:S,crossOrigin:O==null?void 0:O.crossOrigin})),Dt.createElement(Dt.Fragment,null,Dt.createElement("canvas",CVe({style:V,height:i,width:i,ref:C,role:"img"},g)),G)});Uzs.displayName="QRCodeCanvas";var AN=Dt.forwardRef(function(t,n){const r=t,{value:a,size:i=izt,level:l=ozt,bgColor:o=lzt,fgColor:c=czt,includeMargin:d=dzt,minVersion:u=uzt,boostLevel:h,title:m,marginSize:p,imageSettings:f}=r,y=AVe(r,["value","size","level","bgColor","fgColor","includeMargin","minVersion","boostLevel","title","marginSize","imageSettings"]),{margin:v,cells:g,numCells:b,calculatedImageSettings:j}=pzt({value:a,level:l,minVersion:u,boostLevel:h,includeMargin:d,marginSize:p,imageSettings:f,size:i});let S=g,C=null;f!=null&&j!=null&&(j.excavation!=null&&(S=mzt(g,j.excavation)),C=Dt.createElement("image",{href:f.src,height:j.h,width:j.w,x:j.x+v,y:j.y+v,preserveAspectRatio:"none",opacity:j.opacity,crossOrigin:j.crossOrigin}));const E=hzt(S,v);return Dt.createElement("svg",CVe({height:i,width:i,viewBox:`0 0 ${b} ${b}`,ref:n,role:"img"},y),!!m&&Dt.createElement("title",null,m),Dt.createElement("path",{fill:o,d:`M0,0 h${b}v${b}H0z`,shapeRendering:"crispEdges"}),Dt.createElement("path",{fill:c,d:E,shapeRendering:"crispEdges"}),C)});AN.displayName="QRCodeSVG";function fzt({open:s,onOpenChange:t,url:n,title:r,fileBase:a}){const i=_.useRef(null),o=`${(h=>h.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||"listing")(a||r||"listing")}-qr`,c=()=>{var m;const h=(m=i.current)==null?void 0:m.querySelector("svg");return h?new XMLSerializer().serializeToString(h):null},d=()=>{const h=c();if(!h)return;const m=new Blob([h],{type:"image/svg+xml;charset=utf-8"}),p=document.createElement("a");p.href=URL.createObjectURL(m),p.download=`${o}.svg`,p.click(),URL.revokeObjectURL(p.href)},u=(h=1024)=>{const m=c();if(!m)return;const p=new Image,f=new Blob([m],{type:"image/svg+xml;charset=utf-8"}),y=URL.createObjectURL(f);p.onload=()=>{const v=document.createElement("canvas");v.width=h,v.height=h;const g=v.getContext("2d");g&&(g.fillStyle="#ffffff",g.fillRect(0,0,h,h),g.drawImage(p,0,0,h,h),URL.revokeObjectURL(y),v.toBlob(b=>{if(!b)return;const j=document.createElement("a");j.href=URL.createObjectURL(b),j.download=`${o}.png`,j.click(),URL.revokeObjectURL(j.href)},"image/png"))},p.src=y};return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"sm:max-w-md",children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Listing QR Code"}),e.jsx(_r,{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(AN,{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(B,{onClick:()=>u(),className:"gap-2",children:[e.jsx(li,{className:"h-4 w-4"}),"PNG"]}),e.jsxs(B,{variant:"outline",onClick:d,className:"gap-2",children:[e.jsx(li,{className:"h-4 w-4"}),"SVG"]}),e.jsxs(B,{variant:"outline",onClick:async()=>{await navigator.clipboard.writeText(n),se.success("Link copied")},className:"gap-2",children:[e.jsx(Ia,{className:"h-4 w-4"}),"Copy link"]})]})]})})}var qzs="Separator",xgt="horizontal",$zs=["horizontal","vertical"],xzt=_.forwardRef((s,t)=>{const{decorative:n,orientation:r=xgt,...a}=s,i=Vzs(r)?r:xgt,o=n?{role:"none"}:{"aria-orientation":i==="vertical"?i:void 0,role:"separator"};return e.jsx(ii.div,{"data-orientation":i,...o,...a,ref:t})});xzt.displayName=qzs;function Vzs(s){return $zs.includes(s)}var gzt=xzt;const wc=_.forwardRef(({className:s,orientation:t="horizontal",decorative:n=!0,...r},a)=>e.jsx(gzt,{ref:a,decorative:n,orientation:t,className:At("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",s),...r}));wc.displayName=gzt.displayName;const Z_=()=>at({queryKey:["relationship-types"],queryFn:async()=>{const{data:s,error:t}=await q.from("relationship_types").select("*").order("sort_order");if(t)throw t;return s}}),yzt=()=>{const s=ha(),t=1e3;return at({queryKey:["innercircle-contacts-lite",s],queryFn:async()=>{const n=[];let r=0;for(;;){const{data:a,error:i}=await q.from("innercircle_contacts").select("id, first_name, last_name, email, phone, address, city, state, zip, zip_code, birthday, home_anniversary, wedding_anniversary, created_at").eq("owner_user_id",s).order("created_at",{ascending:!1}).range(r,r+t-1);if(i)throw i;const l=a??[];if(n.push(...l),l.length{const t=ha(),n=1e3,r=async a=>{const i=[];let l=0;for(;;){const{data:o,error:c}=await a.range(l,l+n-1);if(c)throw c;const d=o??[];if(i.push(...d),d.length{let a=q.from("innercircle_contacts").select("*").eq("owner_user_id",t).order("created_at",{ascending:!1}).order("first_name");const i=await r(a);if(i.length===0)return i;const l=i.map(p=>p.id),o=Array.from(new Set(i.map(p=>p.lead_source_id).filter(p=>!!p))),c=(p,f=250)=>{const y=[];for(let v=0;v{const{data:f,error:y}=await q.from("innercircle_contact_tags").select("id, contact_id, relationship_type_id, relationship_type:relationship_types(*)").in("contact_id",p);if(y)throw y;return f??[]})),Promise.all(c(o).map(async p=>{const{data:f,error:y}=await q.from("lead_sources").select("id, name").in("id",p);if(y)throw y;return f??[]}))]),h=new Map;d.flat().forEach(p=>{const f=h.get(p.contact_id)??[];f.push(p),h.set(p.contact_id,f)});const m=new Map(u.flat().map(p=>[p.id,p]));return i.map(p=>({...p,lead_source_ref:p.lead_source_id?m.get(p.lead_source_id)??null:null,tags:h.get(p.id)??[]}))},enabled:!!t,staleTime:10*60*1e3})},Hzs=s=>at({queryKey:["innercircle-contact",s],queryFn:async()=>{const{data:t,error:n}=await q.from("innercircle_contacts").select(` *, lead_source_ref:lead_sources(id, name), tags:innercircle_contact_tags( id, contact_id, relationship_type_id, relationship_type:relationship_types(*) ) `).eq("id",s).maybeSingle();if(n)throw n;return t},enabled:!!s}),vzt=()=>{const s=ha();return at({queryKey:["innercircle-contact-counts",s],queryFn:async()=>{const{data:t,error:n}=await q.from("innercircle_contacts").select(` id, tags:innercircle_contact_tags(relationship_type_id) `);if(n)throw n;const r={};return t==null||t.forEach(a=>{var i;(i=a.tags)==null||i.forEach(l=>{r[l.relationship_type_id]=(r[l.relationship_type_id]||0)+1})}),r},enabled:!!s})},iLe=()=>{const s=Bt(),t=ha();return mt({mutationFn:async n=>{const{tagIds:r,...a}=n,i={...a,birthday:a.birthday||null,home_anniversary:a.home_anniversary||null,spouse_birthday:a.spouse_birthday||null,owner_user_id:t},{data:l,error:o}=await q.from("innercircle_contacts").insert(i).select().single();if(o)throw o;if(r&&r.length>0){const{error:c}=await q.from("innercircle_contact_tags").insert(r.map(d=>({contact_id:l.id,relationship_type_id:d})));if(c)throw c}return l},onSuccess:()=>{s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),ia({title:"Contact created successfully"})},onError:n=>{ia({title:"Error creating contact",description:n.message,variant:"destructive"})}})},uet=()=>{const s=Bt();return mt({mutationFn:async({id:t,...n})=>{const{tagIds:r,tags:a,...i}=n,l=["birthday","home_anniversary","spouse_birthday","wedding_anniversary","last_contacted_at","next_touch_date"],o={...i};for(const u of Object.keys(o)){const h=o[u];(h===""||typeof h=="string"&&l.includes(u)&&h.trim()==="")&&(o[u]=null)}const{data:c,error:d}=await q.from("innercircle_contacts").update(o).eq("id",t).select().single();if(d)throw d;if(r!==void 0&&(await q.from("innercircle_contact_tags").delete().eq("contact_id",t),r.length>0)){const{error:u}=await q.from("innercircle_contact_tags").insert(r.map(h=>({contact_id:t,relationship_type_id:h})));if(u)throw u}return c},onSuccess:()=>{s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),ia({title:"Contact updated successfully"})},onError:t=>{ia({title:"Error updating contact",description:t.message,variant:"destructive"})}})},bzt=()=>{const s=Bt();return mt({mutationFn:async({contactId:t,spouseContactId:n})=>{if(n){const{error:r}=await q.from("innercircle_contacts").update({spouse_contact_id:n}).eq("id",t);if(r)throw r;const{error:a}=await q.from("innercircle_contacts").update({spouse_contact_id:t}).eq("id",n);if(a)throw a}else{const{data:r}=await q.from("innercircle_contacts").select("spouse_contact_id").eq("id",t).single(),a=r==null?void 0:r.spouse_contact_id,{error:i}=await q.from("innercircle_contacts").update({spouse_contact_id:null}).eq("id",t);if(i)throw i;if(a){const{error:l}=await q.from("innercircle_contacts").update({spouse_contact_id:null}).eq("id",a);if(l)throw l}}},onSuccess:()=>{s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact"]}),s.invalidateQueries({queryKey:["innercircle-contact-spouse"]}),ia({title:"Spouse link updated"})},onError:t=>{ia({title:"Error linking spouse",description:t.message,variant:"destructive"})}})},_zt=()=>{const s=Bt();return mt({mutationFn:async t=>{const{error:n}=await q.from("innercircle_contacts").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),ia({title:"Contact deleted successfully"})},onError:t=>{ia({title:"Error deleting contact",description:t.message,variant:"destructive"})}})},Gzs=()=>{const s=Bt();return mt({mutationFn:async({ids:t,onProgress:n})=>{let a=0;for(let i=0;i{s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),s.invalidateQueries({queryKey:["all-contact-custom-tags"]})}})},aae=()=>at({queryKey:["action-types"],queryFn:async()=>{const{data:s,error:t}=await q.from("action_types").select("*").order("sort_order");if(t)throw t;return s}}),Wzs=s=>at({queryKey:["action-scripts",s],queryFn:async()=>{let t=q.from("action_scripts").select("*, action_type:action_types(*)");const{data:n,error:r}=await t;if(r)throw r;return n}}),Kzs=()=>at({queryKey:["touchpoint-plans"],queryFn:async()=>{const{data:s,error:t}=await q.from("touchpoint_plans").select(` *, items:touchpoint_plan_items( *, action_type:action_types(*), default_script:action_scripts(*) ) `).order("name");if(t)throw t;return s}}),Yzs=()=>{const s=Bt(),t=ha();return mt({mutationFn:async({name:n,description:r})=>{const{data:a,error:i}=await q.from("touchpoint_plans").insert({name:n,description:r,owner_user_id:t,active:!0,is_template:!1}).select().single();if(i)throw i;return a},onSuccess:()=>{s.invalidateQueries({queryKey:["touchpoint-plans"]}),ia({title:"Plan created successfully"})},onError:n=>{ia({title:"Error creating plan",description:n.message,variant:"destructive"})}})},Zzs=()=>{const s=Bt(),t=ha();return mt({mutationFn:async({sourcePlanId:n,newName:r})=>{const{data:a,error:i}=await q.from("touchpoint_plans").select(` *, items:touchpoint_plan_items(*) `).eq("id",n).single();if(i)throw i;if(!a)throw new Error("Source plan not found");const{data:l,error:o}=await q.from("touchpoint_plans").insert({name:r,description:a.description,owner_user_id:t,active:!0,is_template:!1}).select().single();if(o)throw o;if(a.items&&a.items.length>0){const c=a.items.map(u=>({plan_id:l.id,month_number:u.month_number,action_type_id:u.action_type_id,default_script_id:u.default_script_id,notes:u.notes})),{error:d}=await q.from("touchpoint_plan_items").insert(c);if(d)throw d}return l},onSuccess:()=>{s.invalidateQueries({queryKey:["touchpoint-plans"]}),ia({title:"Plan duplicated successfully",description:"You can now edit your copy of this plan."})},onError:n=>{ia({title:"Error duplicating plan",description:n.message,variant:"destructive"})}})},Xzs=()=>{const s=Bt();return mt({mutationFn:async({id:t,name:n,description:r})=>{const{data:a,error:i}=await q.from("touchpoint_plans").update({name:n,description:r}).eq("id",t).select().single();if(i)throw i;return a},onSuccess:()=>{s.invalidateQueries({queryKey:["touchpoint-plans"]}),ia({title:"Plan updated successfully"})}})},Qzs=()=>{const s=Bt();return mt({mutationFn:async t=>{const{error:n}=await q.from("touchpoint_plans").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["touchpoint-plans"]}),ia({title:"Plan deleted successfully"})}})},Jzs=()=>{const s=Bt();return mt({mutationFn:async({planId:t,items:n})=>{if(await q.from("touchpoint_plan_items").delete().eq("plan_id",t),n.length>0){const{error:r}=await q.from("touchpoint_plan_items").insert(n.map(a=>({plan_id:t,month_number:a.month_number,action_type_id:a.action_type_id,default_script_id:a.default_script_id||null,notes:a.notes})));if(r)throw r}},onSuccess:()=>{s.invalidateQueries({queryKey:["touchpoint-plans"]}),ia({title:"Plan schedule updated"})}})},eBs=()=>{const s=Bt();return mt({mutationFn:async({actionTypeId:t,title:n,scriptBody:r,emailSubject:a,tone:i})=>{const{data:{user:l}}=await q.auth.getUser(),{data:o,error:c}=await q.from("action_scripts").insert({action_type_id:t,title:n,script_body:r,email_subject:a||null,tone:i||null,active:!0,user_id:l==null?void 0:l.id}).select().single();if(c)throw c;return o},onSuccess:()=>{s.invalidateQueries({queryKey:["action-scripts"]}),ia({title:"Script created successfully"})},onError:t=>{ia({title:"Error creating script",description:t.message,variant:"destructive"})}})},tBs=()=>{const s=ha();return at({queryKey:["user-plan-enrollments",s],queryFn:async()=>{const{data:t,error:n}=await q.from("user_plan_enrollments").select(` *, plan:touchpoint_plans(*), relationship_type:relationship_types(*) `);if(n)throw n;return t},enabled:!!s})},sBs=()=>{const s=Bt(),t=ha();return mt({mutationFn:async({planId:n,relationshipTypeId:r,active:a})=>{const{data:i}=await q.from("user_plan_enrollments").select("id").eq("plan_id",n).eq("relationship_type_id",r).maybeSingle();if(i){const{error:l}=await q.from("user_plan_enrollments").update({active:a}).eq("id",i.id);if(l)throw l}else if(a){const{error:l}=await q.from("user_plan_enrollments").insert({owner_user_id:t,plan_id:n,relationship_type_id:r,active:!0,start_date:new Date().toISOString().split("T")[0]});if(l)throw l}},onSuccess:()=>{s.invalidateQueries({queryKey:["user-plan-enrollments"]}),ia({title:"Plan enrollment updated"})}})},vW=(s=7)=>{const t=ha();return at({queryKey:["contact-touch-logs",t,s],queryFn:async()=>{const n=new Date;n.setDate(n.getDate()-s);const{data:r,error:a}=await q.from("contact_touch_logs").select(` *, contact:innercircle_contacts(*), action_type:action_types(*) `).eq("owner_user_id",t).gte("completed_at",n.toISOString()).order("completed_at",{ascending:!1});if(a)throw a;return r},enabled:!!t})},wzt=()=>{const s=ha();return at({queryKey:["contacts-last-touch",s],queryFn:async()=>{const{data:t,error:n}=await q.from("contact_touch_logs").select("contact_id, completed_at").eq("owner_user_id",s).order("completed_at",{ascending:!1});if(n)throw n;const r={};return t==null||t.forEach(a=>{r[a.contact_id]||(r[a.contact_id]=a.completed_at)}),r},enabled:!!s})},nBs=(s=90)=>{const{data:t}=Db(),{data:n}=wzt();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=Bt(),t=ha();return mt({mutationFn:async({contactId:n,actionTypeId:r,scriptUsedId:a,notes:i,completedAt:l})=>{const{data:o,error:c}=await q.from("contact_touch_logs").insert({owner_user_id:t,contact_id:n,action_type_id:r,script_used_id:a,notes:i,completed_at:l||new Date().toISOString()}).select().single();if(c)throw c;return o},onSuccess:async(n,r)=>{var a,i;s.invalidateQueries({queryKey:["contact-touch-logs"]}),s.invalidateQueries({queryKey:["contacts-last-touch"]}),s.invalidateQueries({queryKey:["today-actions"]}),s.invalidateQueries({queryKey:["popby-logs"]}),ia({title:"Action completed!"});try{const[l,o]=await Promise.all([q.from("innercircle_contacts").select("email").eq("id",r.contactId).single(),q.from("action_types").select("name").eq("id",r.actionTypeId).single()]),c=(a=l.data)==null?void 0:a.email,d=((i=o.data)==null?void 0:i.name)||"Touch";/pop[\s-]?by/i.test(d)&&q.from("popby_logs").insert({owner_user_id:t,contact_id:r.contactId,notes:r.notes??null,completed_at:r.completedAt||n.completed_at}).then(()=>{s.invalidateQueries({queryKey:["popby-logs"]})}),c&&q.functions.invoke("boldtrail-sync",{body:{action:"push_touch",contact_email:c,touch_type:d,touch_notes:r.notes||null,touch_date:r.completedAt||n.completed_at}}).catch(()=>{})}catch{}}})},jzt="agentos_weekly_touch_goal",ggt=20,Nzt=()=>{if(typeof window>"u")return ggt;const s=localStorage.getItem(jzt);if(s){const t=parseInt(s,10);if(!isNaN(t)&&t>0)return t}return ggt},rBs=s=>{localStorage.setItem(jzt,s.toString())},lLe=()=>{const{data:s}=vW(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=Nzt();return{actionsThisWeek:r,weeklyGoal:i,streak:a,progress:Math.min(r/i*100,100)}},aBs=()=>{const s=ha();return at({queryKey:["contact-plan-cycles",s],queryFn:async()=>{const{data:t,error:n}=await q.from("contact_plan_cycles").select(` *, contact:innercircle_contacts(*), plan:touchpoint_plans( *, items:touchpoint_plan_items( *, action_type:action_types(*), default_script:action_scripts(*) ) ) `);if(n)throw n;return t},enabled:!!s})},iBs=()=>{const s=Bt();return ha(),mt({mutationFn:async()=>{var c;const{data:t}=await q.from("user_plan_enrollments").select("*").eq("active",!0);if(!t||t.length===0)return;const{data:n}=await q.auth.getUser(),r=(c=n==null?void 0:n.user)==null?void 0:c.id;if(!r)return;const{data:a}=await q.from("innercircle_contacts").select(` id, tags:innercircle_contact_tags(relationship_type_id) `).eq("owner_user_id",r);if(!a)return;const{data:i}=await q.from("contact_plan_cycles").select("contact_id, plan_id"),l=new Set((i==null?void 0:i.map(d=>`${d.contact_id}-${d.plan_id}`))||[]),o=[];for(const d of a)for(const u of d.tags||[]){const h=t.find(m=>m.relationship_type_id===u.relationship_type_id);h&&!l.has(`${d.id}-${h.plan_id}`)&&o.push({contact_id:d.id,plan_id:h.plan_id,relationship_type_id:u.relationship_type_id})}if(o.length>0){const{error:d}=await q.from("contact_plan_cycles").insert(o);if(d)throw d}return o.length},onSuccess:t=>{s.invalidateQueries({queryKey:["contact-plan-cycles"]}),t&&t>0&&ia({title:`${t} contact(s) enrolled in plans`})}})},het=()=>{const s=ha(),{data:t}=aBs(),{data:n}=vW(30);return at({queryKey:["today-actions",s,t==null?void 0:t.length,n==null?void 0:n.length],queryFn:async()=>{var f;if(!t||t.length===0)return[];const{data:r}=await q.from("contact_snoozes").select("contact_id").gte("snoozed_until",new Date().toISOString()),a=new Set((r==null?void 0:r.map(y=>y.contact_id))||[]),i=new Date,l=[],o=new Date(i.getFullYear(),i.getMonth(),1),c=new Set((n==null?void 0:n.filter(y=>new Date(y.completed_at)>=o).map(y=>`${y.contact_id}-${y.action_type_id}`))||[]);for(const y of t){if(!((f=y.plan)!=null&&f.items)||y.plan.items.length===0||!y.contact||a.has(y.contact_id))continue;const v=new Date(y.cycle_start_date),b=Math.floor((i.getTime()-v.getTime())/(30.44*24*60*60*1e3))%12+1,j=y.plan.items.find(S=>S.month_number===b);if(j&&j.action_type){const S=`${y.contact_id}-${j.action_type_id}`;if(!c.has(S)){const{data:C}=await q.from("relationship_types").select("name").eq("id",y.relationship_type_id).single();l.push({contact:y.contact,actionType:j.action_type,script:j.default_script||void 0,planName:y.plan.name,relationshipTypeName:(C==null?void 0:C.name)||"",monthNumber:b})}}}const d=5,u=i.getDate(),h=l.sort((y,v)=>y.contact.first_name.localeCompare(v.contact.first_name)),m=(u-1)%Math.max(1,h.length);return[...h.slice(m),...h.slice(0,m)].slice(0,d)},enabled:!!s&&!!t})};function oBs(){const{user:s}=hs(),{limitFor:t,isRestricted:n}=IS(),r=n?t("mass_email"):null,{data:a=0,refetch:i}=at({queryKey:["mass-email-usage",s==null?void 0:s.id],enabled:!!(s!=null&&s.id)&&!!r,staleTime:60*1e3,queryFn:async()=>{const o=new Date;o.setDate(1),o.setHours(0,0,0,0);const{count:c}=await q.from("bulk_email_sends").select("id",{count:"exact",head:!0}).eq("user_id",s.id).gte("sent_at",o.toISOString());return c||0}}),l=r===null?1/0:Math.max(0,r-a);return{limit:r,used:a,remaining:l,wouldExceed:o=>r!==null&&o>l,refetch:i}}function lBs({onSelect:s}){const{user:t}=hs(),[n,r]=_.useState("root"),[a,i]=_.useState(null),{data:l=[],isLoading:o}=at({queryKey:["agent-email-template-categories"],queryFn:async()=>{const{data:g,error:b}=await q.from("email_template_categories").select("*").order("sort_order");if(b)throw b;return g}}),{data:c=[],isLoading:d}=at({queryKey:["agent-email-templates",a],enabled:n==="category"&&!!a,queryFn:async()=>{const{data:g,error:b}=await q.from("agent_email_templates").select("*").eq("is_active",!0).eq("category_id",a).order("sort_order");if(b)throw b;return g}}),{data:u=[],isLoading:h}=at({queryKey:["picker-campaign-templates",t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{const{data:g,error:b}=await q.from("campaign_templates").select("id,name,subject,body_html,is_shared,user_id,updated_at").or(`user_id.eq.${t.id},is_shared.eq.true`).order("updated_at",{ascending:!1});if(b)throw b;return g}}),m=u.filter(g=>g.user_id===(t==null?void 0:t.id)&&!g.is_shared),p=u.filter(g=>g.is_shared),f=l.find(g=>g.id===a);if(o)return e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(Ct,{className:"h-5 w-5 animate-spin text-muted-foreground"})});const y=g=>{s({title:g.name,subject:g.subject,body:g.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(Fo,{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(xi,{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(sl,{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(xi,{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(g=>e.jsxs("button",{onClick:()=>{i(g.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:g.icon}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:g.name}),g.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1",children:g.description})]})]}),e.jsx(xi,{className:"h-4 w-4 text-muted-foreground shrink-0"})]},g.id))})]})]});const v=e.jsxs("button",{onClick:()=>{r("root"),i(null)},className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx($c,{className:"h-3.5 w-3.5"}),"Back"]});return n==="my"?e.jsxs("div",{className:"space-y-2",children:[v,e.jsxs("p",{className:"text-xs font-medium flex items-center gap-1.5",children:[e.jsx(Fo,{className:"h-3.5 w-3.5"})," My Saved Templates"]}),h?e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(Ct,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):m.length===0?e.jsxs("div",{className:"text-center py-6 space-y-2",children:[e.jsx(un,{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(Ji,{className:"max-h-[280px]",children:e.jsx("div",{className:"space-y-1",children:m.map(g=>e.jsxs("button",{onClick:()=>y(g),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:g.name}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:g.subject||"(no subject)"})]},g.id))})})]}):n==="shared"?e.jsxs("div",{className:"space-y-2",children:[v,e.jsxs("p",{className:"text-xs font-medium flex items-center gap-1.5",children:[e.jsx(sl,{className:"h-3.5 w-3.5"})," Shared Library"]}),h?e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(Ct,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):p.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No shared templates yet."}):e.jsx(Ji,{className:"max-h-[280px]",children:e.jsx("div",{className:"space-y-1",children:p.map(g=>e.jsxs("button",{onClick:()=>y(g),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:g.name}),e.jsx(Oe,{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:g.subject||"(no subject)"})]},g.id))})})]}):e.jsxs("div",{className:"space-y-2",children:[v,e.jsxs("p",{className:"text-xs font-medium flex items-center gap-1.5",children:[e.jsx("span",{children:f==null?void 0:f.icon})," ",f==null?void 0:f.name]}),d?e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(Ct,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):c.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No templates in this category"}):e.jsx(Ji,{className:"max-h-[280px]",children:e.jsx("div",{className:"space-y-1",children:c.map(g=>e.jsxs("button",{onClick:()=>s(g),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:g.title}),g.tone&&e.jsx(Oe,{variant:"secondary",className:"text-[10px] shrink-0",children:g.tone})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:g.subject})]},g.id))})})]})}function $9(){var a;const{user:s}=hs(),{data:t,isLoading:n}=at({queryKey:["mass-email-settings",s==null?void 0:s.id],enabled:!!s,staleTime:60*1e3,queryFn:async()=>{var d,u,h,m;const[i,l]=await Promise.all([q.from("mass_email_settings").select("reply_to_email, display_name").eq("user_id",s.id).maybeSingle(),q.from("profiles").select("email, name").eq("id",s.id).maybeSingle()]),o=i.data,c=l.data;return{reply_to_email:((d=o==null?void 0:o.reply_to_email)==null?void 0:d.trim())||((u=c==null?void 0:c.email)==null?void 0:u.trim())||s.email||null,display_name:((h=o==null?void 0:o.display_name)==null?void 0:h.trim())||((m=c==null?void 0:c.name)==null?void 0:m.trim())||null}}});return{isReady:!!((a=t==null?void 0:t.reply_to_email)!=null&&a.trim()),isLoading:n,settings:t}}function iae(){const{user:s}=hs();return at({queryKey:["verified-sender-check",s==null?void 0:s.id],enabled:!!s,staleTime:3e4,queryFn:async()=>{const[t,n]=await Promise.all([q.from("user_verified_senders").select("id, email, status").eq("user_id",s.id),q.from("gmail_integrations").select("gmail_email, is_active").eq("user_id",s.id).eq("is_active",!0).maybeSingle()]),r=t.data||[],a=r.filter(l=>l.status==="verified"),i=r.filter(l=>l.status==="pending");return{hasVerifiedSes:a.length>0,hasPendingSes:i.length>0,hasAnySender:r.length>0,hasGmail:!!n.data,verifiedEmails:a.map(l=>l.email),pendingEmails:i.map(l=>l.email)}}})}function cLe({open:s,onOpenChange:t,hasPending:n,pendingEmails:r}){const a=Fn();return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"sm:max-w-md",children:[e.jsxs(Os,{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(Ds,{children:"Verify your sending email first"})]}),e.jsx(_r,{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(Gr,{className:"h-4 w-4"})," Waiting for you to click Amazon's link"]}),r.map(i=>e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(ln,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:i})]},i)),e.jsx("p",{className:"text-xs text-muted-foreground pt-1",children:"Check that inbox (and your spam folder) for an email from Amazon Web Services and click the verification link."})]}):e.jsx("div",{className:"rounded-lg border bg-muted/40 p-3 text-sm text-muted-foreground",children:"It only takes a minute — add your email address on the Integrations page, then click the verification link Amazon sends you."}),e.jsxs(yr,{className:"gap-2 sm:gap-2",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Not now"}),e.jsxs(B,{onClick:()=>{t(!1),a("/mission-control/integrations")},children:[e.jsx(wr,{className:"h-4 w-4 mr-1"}),n?"Manage senders":"Verify my email"]})]})]})})}function dLe(){const{user:s}=hs(),t=Bt(),{data:n,isLoading:r}=at({queryKey:["contact-intake-page",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return null;const{data:d,error:u}=await q.from("contact_intake_pages").select("*").eq("user_id",s.id).maybeSingle();if(u)throw u;return d},enabled:!!(s!=null&&s.id)}),a=mt({mutationFn:async d=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:u,error:h}=await q.from("contact_intake_pages").insert({user_id:s.id,slug:d.toLowerCase().replace(/[^a-z0-9-]/g,"-")}).select().single();if(h)throw h;return u},onSuccess:()=>{t.invalidateQueries({queryKey:["contact-intake-page"]}),se.success("Connect page created!")},onError:d=>{var u;(u=d.message)!=null&&u.includes("duplicate")?se.error("That slug is already taken. Try another."):se.error("Failed to create page")}}),i=mt({mutationFn:async d=>{if(!(n!=null&&n.id))throw new Error("No intake page");const{error:u}=await q.from("contact_intake_pages").update({...d,updated_at:new Date().toISOString()}).eq("id",n.id);if(u)throw u},onSuccess:()=>{t.invalidateQueries({queryKey:["contact-intake-page"]}),se.success("Page updated!")},onError:()=>se.error("Failed to update page")}),{data:l=[],isLoading:o}=at({queryKey:["contact-intake-submissions",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return[];const{data:d,error:u}=await q.from("contact_intake_submissions").select("*").eq("agent_user_id",s.id).order("created_at",{ascending:!1}).limit(100);if(u)throw u;return d},enabled:!!(s!=null&&s.id)}),c=mt({mutationFn:async d=>{if(!(n!=null&&n.id))throw new Error("No intake page. Create your Connect page first.");const{data:u,error:h}=await q.from("contact_intake_tokens").insert({contact_id:d,intake_page_id:n.id}).select("token").single();if(h)throw h;return`${window.location.origin}/connect/${n.slug}?t=${u.token}`}});return{intakePage:n,isLoading:r,createPage:a,updatePage:i,submissions:l,loadingSubmissions:o,generateUpdateLink:c}}function kzt({value:s,onChange:t,userId:n,placeholder:r}){const[a,i]=_.useState(!1),[l,o]=_.useState([]),[c,d]=_.useState(!1),[u,h]=_.useState(0),m=_.useRef(null),p=_.useRef(null);_.useEffect(()=>{const y=v=>{m.current&&!m.current.contains(v.target)&&i(!1)};return document.addEventListener("mousedown",y),()=>document.removeEventListener("mousedown",y)},[]),_.useEffect(()=>{p.current&&clearTimeout(p.current);const y=s.trim();if(!n||y.length<1||y.includes("@")&&y.indexOf("@")>0&&/\S+@\S+\.\S+/.test(y)){o([]);return}return p.current=setTimeout(async()=>{d(!0);const v=`%${y}%`,g=q,{data:b,error:j}=await g.from("innercircle_contacts").select("id, first_name, last_name, email").eq("owner_user_id",n).not("email","is",null).or(`first_name.ilike.${v},last_name.ilike.${v},email.ilike.${v}`).order("first_name",{ascending:!0}).limit(8);d(!1),!j&&b&&(o(b),h(0),i(b.length>0))},180),()=>{p.current&&clearTimeout(p.current)}},[s,n]);const f=y=>{y.email&&(t(y.email),i(!1))};return e.jsxs("div",{ref:m,className:"relative",children:[e.jsx(xe,{id:"gmail-to",value:s,onChange:y=>t(y.target.value),onFocus:()=>l.length>0&&i(!0),onKeyDown:y=>{!a||l.length===0||(y.key==="ArrowDown"?(y.preventDefault(),h(v=>Math.min(v+1,l.length-1))):y.key==="ArrowUp"?(y.preventDefault(),h(v=>Math.max(v-1,0))):y.key==="Enter"?(y.preventDefault(),f(l[u])):y.key==="Escape"&&i(!1))},placeholder:r||"Start typing a name or email...",autoComplete:"off"}),a&&e.jsx("div",{className:"absolute z-50 mt-1 w-full rounded-md border bg-popover shadow-lg max-h-72 overflow-y-auto",children:c&&l.length===0?e.jsxs("div",{className:"px-3 py-2 text-sm text-muted-foreground flex items-center gap-2",children:[e.jsx(Ct,{className:"h-3 w-3 animate-spin"})," Searching..."]}):l.map((y,v)=>{const g=[y.first_name,y.last_name].filter(Boolean).join(" ")||"(No name)";return e.jsxs("button",{type:"button",onMouseEnter:()=>h(v),onClick:()=>f(y),className:`w-full flex items-center gap-2 px-3 py-2 text-left text-sm border-b last:border-b-0 ${v===u?"bg-accent":"bg-popover"}`,children:[e.jsx(Fo,{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:g}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:y.email})]})]},y.id)})})]})}function cBs(){const{user:s}=hs(),{data:t,isLoading:n}=at({queryKey:["email-signature",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),staleTime:5*60*1e3,queryFn:async()=>{const{data:a,error:i}=await q.from("profiles").select("email_signature, use_email_signature").eq("id",s.id).maybeSingle();if(i)throw i;return a}}),r=((t==null?void 0:t.email_signature)||"").trim();return{signatureHtml:r,hasSignature:r.length>0,signatureEnabledByDefault:!!(t!=null&&t.use_email_signature)&&r.length>0,isLoading:n}}function dBs(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 uBs(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 o7e=25*1024*1024,ygt=Math.floor(6.5*1024*1024),hBs=750*1024,p2=50,mBs=["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 Dle(s){return s<1024?s+" B":s<1024*1024?(s/1024).toFixed(1)+" KB":(s/(1024*1024)).toFixed(1)+" MB"}function pBs(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 fBs(s){if(!s)return"";const t=s.trim();return t.split(/\s+/)[0]||t}function xk(s,t){const n=fBs(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 DS({open:s,onOpenChange:t,contact:n,bulkContacts:r,defaultSubject:a="",defaultBody:i="",gmailEmail:l,onSendComplete:o,sendSource:c,logTouchpoint:d=!0}){const{user:u}=hs(),h=Bt(),{isReady:m,settings:p}=$9(),{data:f}=iae(),[y,v]=_.useState(!1),{intakePage:g}=dLe(),b=g?`https://contacts.relevelup.com/${g.slug}`:null,j=!!r&&r.length>0,S=oBs(),C=m,E=j?r:n?[n]:[],P=E[0],M=j?Math.ceil(E.length/p2):1,I=j&&E.length>p2,[D,O]=_.useState((P==null?void 0:P.email)||""),[V,G]=_.useState(a),[$,H]=_.useState(i),[Y,Z]=_.useState(!1),[ne,ce]=_.useState(!1),[ie,te]=_.useState([]),ae=_.useRef(new Map),[le,be]=_.useState(a),[me,he]=_.useState(i),[pe,Ce]=_.useState(!1),[Ae,Pe]=_.useState("composing"),[ze,ke]=_.useState(0),[Ze,Se]=_.useState(0),[Fe,Ne]=_.useState(0),[Ye,Ve]=_.useState(0),qe=_.useRef(!1),Qe=_.useRef(0),[Ue,Xe]=_.useState(!0),{signatureHtml:nt,hasSignature:$e,signatureEnabledByDefault:Ge}=cBs(),[ct,xt]=_.useState(!0),[qt,Vt]=_.useState(null);_.useEffect(()=>{s&&xt($e)},[s,$e]),_.useEffect(()=>{if(s){const ks=/<[a-z][\s\S]*>/i.test(i),Gs=ks?uBs(i):i;Ts.current=ks?{plain:Gs,html:i}:null,O((P==null?void 0:P.email)||""),be(a),he(Gs),G(xk(a,P||{first_name:""})),H(xk(Gs,P||{first_name:""})),ce(!a&&!i),Ce(!1),jn(Ws=>Ws+1),te([]),ae.current=new Map,Pe("composing"),ke(0),Se(0),Ne(0),Ve(0),qe.current=!1,Qe.current=0,Vt(null)}},[s,P,a,i]);const Xt=async ks=>{const Gs=ks.target.files;if(!Gs)return;const Ws=ie.reduce((or,Wt)=>or+Wt.size,0),Ys=[];let Bn=Ws;for(const or of Array.from(Gs)){if(!mBs.includes(or.type)){se.error(`${or.name}: Unsupported file type`);continue}if(Bn+or.size>o7e){se.error(`Total attachments exceed ${Dle(o7e)} limit`);break}try{const Wt=await pBs(or);Ys.push({name:or.name,type:or.type,size:or.size,data:Wt}),Bn+=or.size}catch{se.error(`Failed to read ${or.name}`)}}te(or=>[...or,...Ys]),ks.target.value=""},fs=ks=>{const Gs=ie[ks];Gs&&ae.current.delete(`${Gs.name}::${Gs.size}`),te(Ws=>Ws.filter((Ys,Bn)=>Bn!==ks))},Ft=async()=>{if(ie.length===0||!u)return{inline:[],paths:[]};const ks=[],Gs=[];for(const Ws of ie){const Ys=`${Ws.name}::${Ws.size}`,Bn=ae.current.get(Ys);if(Bn){Gs.push(Bn);continue}if(Ws.size<=hBs){ks.push(Ws);continue}const or=Ws.name.replace(/[^a-zA-Z0-9._-]/g,"_"),Wt=`${u.id}/${Date.now()}-${or}`,rt=atob(Ws.data),pt=new Uint8Array(rt.length);for(let Mt=0;Mt{if(!/<[a-z][\s\S]*>/i.test(ks)||typeof window>"u")return ks;const Gs=ks.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,""),Ws=document.createElement("div");return Ws.innerHTML=Gs,(Ws.textContent||Ws.innerText||"").replace(/\u00a0/g," ").replace(/\n{3,}/g,` `).trim()},Ts=_.useRef(null),vt=Ts.current&&me===Ts.current.plain?Ts.current.html:null,$s=_.useRef(null),[As,jn]=_.useState(0),ar=()=>{const ks=$s.current,Gs=Ts.current;!ks||!Gs||(Ts.current={plain:Gs.plain,html:ks.innerHTML})},Dn=ks=>{const Gs=/<[a-z][\s\S]*>/i.test(ks.body),Ws=Gs?wt(ks.body):ks.body;Ts.current=Gs?{plain:Ws,html:ks.body}:null,be(ks.subject),he(Ws),G(xk(ks.subject,P||{first_name:""})),H(xk(Ws,P||{first_name:""})),ce(!1),jn(Ys=>Ys+1)},Ur=ks=>/<\s*(p|div|span|table|tr|td|img|br|h[1-6]|a|body|html|section|article|ul|ol|li)\b/i.test(ks)?ks:ks.split(/\n\n+/).map(Gs=>`

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

`).join(""),Vs=(ks,Gs)=>{const Ws="https://relzejiswnotikjgvjhz.supabase.co/functions/v1/bulk-email-track";let Ys=ks.replace(/]*?)href=(["'])(.*?)\2([^>]*)>/gi,(or,Wt,rt,pt,jt)=>{if(!pt||/^(mailto:|tel:|#)/i.test(pt)||pt.includes("/bulk-email-track")||pt.includes("/ses-campaign-track"))return or;const Mt=`${Ws}?s=${Gs}&t=click&u=${encodeURIComponent(pt)}`;return``});const Bn=``;return/<\/body>/i.test(Ys)?Ys=Ys.replace(/<\/body>/i,`${Bn}`):Ys=`${Ys}${Bn}`,Ys},hn=async ks=>{if(!(ks!=null&&ks.email))return se.error("Please enter a recipient email"),!1;const Gs=ks||{first_name:""},Ws=xk(le,Gs),Ys=Ts.current,Bn=Ys&&me===Ys.plain,or=xk(Bn?Ys.html:me,Gs);let Wt=Bn?or:Ur(or);ct&&nt&&(Wt=dBs(Wt,xk(nt,Gs)));const rt=u&&ks.id?crypto.randomUUID():null;rt&&(Wt=Vs(Wt,rt));try{if(u&&ks.email){const Mt=new Date(Date.now()-6e5).toISOString(),{data:es}=await q.from("bulk_email_sends").select("id").eq("user_id",u.id).eq("contact_email",ks.email).eq("subject",Ws).gte("sent_at",Mt).limit(1);if(es&&es.length>0)return console.log(`Skipping duplicate send to ${ks.email} (same subject within 10 min)`),se.info(`Skipped ${ks.first_name||ks.email} — already sent this in the last 10 min`),!0}const{inline:pt,paths:jt}=await Ft();if(C){const Mt=(p==null?void 0:p.display_name)||"ReLevelUp",es=`${Mt.toLowerCase().replace(/[^a-z]/g,".")}@send.relevelup.com`,ps=`${Mt} <${es}>`;let Is=jt[0];if(!Is&&pt.length>0&&u){const Qs=pt[0],an=Qs.name.replace(/[^a-zA-Z0-9._-]/g,"_"),er=`${u.id}/${Date.now()}-${an}`,Xr=atob(Qs.data),ma=new Uint8Array(Xr.length);for(let sa=0;sa({name:ps,type:Is,data:js})),attachment_paths:jt,skip_signature:!0}});if(es)throw es;if(!(Mt!=null&&Mt.success))throw new Error((Mt==null?void 0:Mt.error)||"Failed to send")}if(u&&ks.id&&rt&&(await q.from("bulk_email_sends").insert({id:rt,user_id:u.id,contact_id:ks.id,contact_email:ks.email,subject:Ws,source:c||(C?"ses_bulk":"sphere_gaps")}),d))try{await q.from("contact_touch_logs").insert({owner_user_id:u.id,contact_id:ks.id,action_type_id:"9a88a47c-cb2a-4401-a2b5-111a76b19f9d",notes:`Mass Email: ${Ws}`,completed_at:new Date().toISOString()})}catch(Mt){console.warn("touch log insert failed",Mt)}return!0}catch(pt){return console.error("Send error:",pt),se.error("Failed to send to "+ks.first_name+": "+(pt instanceof Error?pt.message:"Unknown error")),!1}},dr=()=>{const ks=ze*p2;return E.slice(ks,ks+p2)},Cn=async(ks=0,Gs=Ue)=>{if(!V||!$){se.error("Please fill in subject and message");return}Z(!0),Pe("sending");let Ws=Math.max(0,Math.min(ks,E.length)),Ys=!1;for(;Wsjt+1):Ne(jt=>jt+1),rtsetTimeout(jt,150))}if(h.invalidateQueries({queryKey:["bulk-email-sends"]}),h.invalidateQueries({queryKey:["contact-touch-logs"]}),h.invalidateQueries({queryKey:["contacts-last-touch"]}),Ys||qe.current||Ws>=E.length)break;if(!Gs){Z(!1),Pe("batch_complete");return}if(Ve(0),await new Promise(rt=>setTimeout(rt,1500)),qe.current){Ys=!0;break}}Z(!1),Pe(Ys||qe.current?"batch_complete":"all_done")},Yn=async()=>{var Gs;if(!V||!$){se.error("Please fill in subject and message");return}const ks=j?(r==null?void 0:r.length)||0:1;if(S.wouldExceed(ks)){se.error(`Your package includes ${(Gs=S.limit)==null?void 0:Gs.toLocaleString()} emails per month. You have ${S.remaining.toLocaleString()} left — request an upgrade for unlimited sending.`);return}if(C&&f&&!f.hasVerifiedSes&&!f.hasGmail){v(!0);return}if(!j){const Ws=P||{id:"",first_name:"",last_name:"",email:D.trim()};if(!Ws.email){se.error("Please enter a recipient email");return}Z(!0);try{await hn(Ws)&&(h.invalidateQueries({queryKey:["bulk-email-sends"]}),se.success("Email sent successfully!"),t(!1),o==null||o())}finally{Z(!1)}return}qe.current=!1,Qe.current=0,await Cn(0)},on=async()=>{qe.current=!1,Ve(0),await Cn(Qe.current,!1)},Ir=async()=>{qe.current=!1,Xe(!0),Ve(0),await Cn(Qe.current,!0)},Wn=()=>{if(Y){qe.current=!0;return}t(!1),o==null||o()},Js=ze*p2;Math.min(Js+p2,E.length);const Fa=j&&E.length>0?Math.round((Ze+Fe)/E.length*100):0;return e.jsxs(Ls,{open:s,onOpenChange:Wn,children:[e.jsxs(Ps,{className:"sm:max-w-[600px] max-h-[90vh] overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsxs(Ds,{className:"flex items-center gap-2",children:[e.jsx(ln,{className:`h-5 w-5 ${C?"text-orange-500":"text-red-500"}`}),j?`Send to ${E.length} Contacts`:"Compose Email"]}),C?e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Sending via ",e.jsx("span",{className:"font-medium",children:"Mass Email"})," (reply-to: ",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,j&&Ae==="composing"&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Composing email for ",e.jsxs("span",{className:"font-medium",children:[E.length," contacts"]}),". You'll review each personalized email before sending."]})]}),Ae==="sending"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx(Ct,{className:"h-8 w-8 animate-spin mx-auto text-primary"}),e.jsxs("p",{className:"font-medium",children:["Sending batch ",ze+1," of ",M,"..."]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Ye," of ",dr().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(Fi,{value:Ye/Math.max(dr().length,1)*100,className:"h-2"}),e.jsxs("div",{className:"flex justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Overall: ",Ze+Fe," / ",E.length]}),e.jsxs("span",{children:[Ze," sent • ",Fe," failed"]})]}),e.jsx(B,{variant:"outline",size:"sm",className:"w-full",onClick:()=>{qe.current=!0},children:"Stop Sending"})]}),Ae==="batch_complete"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx(Er,{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:[Ze," sent, ",Fe," failed so far"]})]}),e.jsx(Fi,{value:Fa,className:"h-2"}),e.jsxs("p",{className:"text-xs text-center text-muted-foreground",children:[E.length-Ze-Fe," contacts remaining (",Math.max(M-ze-1,0)," batches left)"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",className:"flex-1",onClick:Wn,children:"Done for Now"}),e.jsxs(B,{className:"flex-1 gap-2",onClick:Ir,children:[e.jsx(Or,{className:"h-4 w-4"}),"Resume Sending"]})]}),e.jsxs(B,{variant:"ghost",size:"sm",className:"w-full",onClick:on,children:["Send just the next ",Math.min(p2,Math.max(E.length-(Ze+Fe),0))," contacts"]})]}),Ae==="all_done"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx(Er,{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:[Ze," emails sent successfully",Fe>0&&e.jsxs("span",{className:"text-destructive",children:[" • ",Fe," failed"]})]})]}),e.jsx(B,{className:"w-full",onClick:Wn,children:"Close"})]}),Ae==="composing"&&e.jsxs("div",{className:"space-y-4",children:[ne?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(Fr,{className:"h-4 w-4"})," Choose a Template"]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>ce(!1),className:"h-7 px-2 text-xs",children:[e.jsx(Qn,{className:"h-3 w-3 mr-1"})," Write from scratch"]})]}),e.jsx(lBs,{onSelect:Dn})]}):e.jsxs(B,{variant:"outline",size:"sm",className:"gap-2",onClick:()=>ce(!0),children:[e.jsx(Fr,{className:"h-4 w-4"}),"Browse Templates"]}),e.jsx(wc,{}),!j&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{htmlFor:"gmail-to",children:"To"}),e.jsx(kzt,{value:D,onChange:O,userId:u==null?void 0:u.id})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{htmlFor:"gmail-subject",children:"Subject"}),e.jsx(xe,{id:"gmail-subject",value:V,onChange:ks=>{G(ks.target.value),be(ks.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(J,{htmlFor:"gmail-body",children:"Message"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(Oe,{variant:"outline",className:"text-[10px] cursor-pointer hover:bg-accent",onClick:()=>{H(ks=>ks+"{{first_name}}"),he(ks=>ks+"{{first_name}}")},children:"{{first_name}}"}),e.jsx(Oe,{variant:"outline",className:"text-[10px] cursor-pointer hover:bg-accent",onClick:()=>{H(ks=>ks+"{{last_name}}"),he(ks=>ks+"{{last_name}}")},children:"{{last_name}}"}),b&&e.jsx(Oe,{variant:"outline",className:"text-[10px] cursor-pointer hover:bg-primary/10 border-primary/40 text-primary",onClick:()=>{const ks=` When you get a sec, can you share your latest contact info with me? It only takes about a minute: ${b} `;H(Gs=>Gs+ks),he(Gs=>Gs+ks)},title:"Insert your Connect Page link",children:"+ Connect Page"})]})]}),vt&&!pe?e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"overflow-hidden rounded-xl border bg-background",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 border-b bg-muted/40 px-3 py-2",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 font-bold",onMouseDown:ks=>ks.preventDefault(),onClick:()=>document.execCommand("bold"),title:"Bold",children:"B"}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 italic",onMouseDown:ks=>ks.preventDefault(),onClick:()=>document.execCommand("italic"),title:"Italic",children:"I"}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 underline",onMouseDown:ks=>ks.preventDefault(),onClick:()=>document.execCommand("underline"),title:"Underline",children:"U"}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 text-xs",onMouseDown:ks=>ks.preventDefault(),onClick:()=>{const ks=window.prompt("Link address (https://...)");ks&&document.execCommand("createLink",!1,ks)},title:"Add link",children:"Link"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"text-[11px] font-medium text-muted-foreground",children:"Click the email below to edit it"}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 text-[11px] text-muted-foreground",onClick:()=>Ce(!0),children:"Plain text"})]})]}),e.jsx("div",{ref:$s,contentEditable:!0,suppressContentEditableWarning:!0,onInput:ar,onBlur:ar,className:"max-h-[420px] overflow-y-auto p-1 outline-none focus-visible:ring-2 focus-visible:ring-ring/40 [&_img]:max-w-full",dangerouslySetInnerHTML:{__html:vt}},As)]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Edit any text right here — ","{{first_name}}"," and ","{{last_name}}"," are swapped in for each person when it sends."]})]}):e.jsx(Ms,{id:"gmail-body",value:$,onChange:ks=>{H(ks.target.value),he(ks.target.value)},placeholder:"Write your message...",rows:10,className:"resize-y"}),j&&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:$e?"Your saved signature is added to the bottom of this email.":"Add a signature in Profile settings to use this."})]}),e.jsx(fn,{checked:ct&&$e,onCheckedChange:xt,disabled:!$e})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{type:"button",variant:"outline",size:"sm",className:"gap-2",onClick:()=>{var ks;return(ks=document.getElementById("gmail-attachments"))==null?void 0:ks.click()},disabled:Y,children:[e.jsx(eP,{className:"h-4 w-4"}),"Attach Files"]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["PDF, images, Word, Excel (max ",Dle(o7e)," 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:Xt})]}),ie.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:ie.map((ks,Gs)=>e.jsxs(Oe,{variant:"secondary",className:"gap-1.5 pl-2 pr-1 py-1",children:[e.jsx(eP,{className:"h-3 w-3"}),e.jsx("span",{className:"max-w-[140px] truncate text-xs",children:ks.name}),e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["(",Dle(ks.size),")"]}),e.jsx("button",{type:"button",onClick:()=>fs(Gs),className:"ml-0.5 rounded-full p-0.5 hover:bg-muted",children:e.jsx(Qn,{className:"h-3 w-3"})})]},Gs))}),C&&ie.some(ks=>ks.size>ygt)&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Files over ",Dle(ygt)," will be sent as secure download links."]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),j?e.jsxs(B,{onClick:()=>{Vt(E[0]||null),Pe("reviewing")},disabled:!V||!$,className:"gap-2",children:["Review Emails",e.jsx(La,{className:"h-4 w-4"})]}):e.jsxs(B,{onClick:Yn,disabled:Y||!V||!$||!D.trim(),className:"gap-2",children:[Y?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Or,{className:"h-4 w-4"}),Y?"Sending...":"Send Email"]})]})]}),Ae==="reviewing"&&j&&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:["📦 ",E.length," contacts will be sent in ",M," batches of up to ",p2,"."]}),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:ks=>Xe(ks.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(J,{children:["Recipients (",E.length,")"]}),e.jsx("div",{className:"bg-muted p-1.5 rounded-md space-y-0.5 max-h-32 overflow-y-auto",children:E.map(ks=>e.jsxs("div",{className:`text-sm px-2 py-1 rounded cursor-pointer transition-colors ${(qt==null?void 0:qt.id)===ks.id?"bg-primary/10 text-primary font-medium":"text-muted-foreground hover:bg-accent hover:text-foreground"}`,onClick:()=>Vt(ks),children:[ks.first_name," ",ks.last_name," — ",ks.email]},ks.id))})]}),qt&&e.jsxs("div",{className:"border rounded-xl p-3 bg-muted/30 space-y-2 animate-in fade-in slide-in-from-top-1",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("p",{className:"text-xs font-semibold text-primary flex items-center gap-1.5",children:[e.jsx(ln,{className:"h-3.5 w-3.5"}),"Preview for ",qt.first_name," ",qt.last_name]})}),e.jsxs("div",{className:"space-y-1 text-sm",children:[e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground text-xs",children:"To:"})," ",qt.email]}),e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground text-xs",children:"Subject:"})," ",xk(le,qt)]})]}),e.jsx(wc,{}),vt?e.jsx("div",{className:"rounded-lg border bg-background max-h-72 overflow-y-auto [&_img]:max-w-full",dangerouslySetInnerHTML:{__html:xk(vt,qt)}}):e.jsx("div",{className:"text-sm whitespace-pre-wrap bg-background rounded p-2.5 max-h-40 overflow-y-auto border",children:xk(me,qt)})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsxs(B,{variant:"outline",onClick:()=>{Pe("composing"),Vt(null)},children:[e.jsx(ka,{className:"h-4 w-4 mr-1"}),"Back to Edit"]}),e.jsxs(B,{onClick:Yn,disabled:Y,className:"gap-2",children:[Y?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Or,{className:"h-4 w-4"}),I?`Send First ${p2}`:`Send to ${E.length}`]})]})]})]}),e.jsx(cLe,{open:y,onOpenChange:v,hasPending:!!(f!=null&&f.hasPendingSes),pendingEmails:f==null?void 0:f.pendingEmails})]})}function xBs(s){return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s)}const gBs={single_family:"Single Family Home",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury Home",commercial:"Commercial",other:"Property"};function Szt({open:s,onOpenChange:t,listing:n}){const{user:r}=hs(),{data:a=[],isLoading:i}=Db(),{data:l=[]}=Z_(),[o,c]=_.useState(""),[d,u]=_.useState("all"),[h,m]=_.useState(new Set),[p,f]=_.useState(!1),[y,v]=_.useState(null);_.useEffect(()=>{s||(c(""),u("all"),m(new Set),f(!1))},[s]),_.useEffect(()=>{!s||!r||(async()=>{const{data:M}=await q.from("gmail_integrations").select("gmail_email").eq("user_id",r.id).maybeSingle();v((M==null?void 0:M.gmail_email)||null)})()},[s,r]);const g=_.useMemo(()=>a.filter(M=>M.email),[a]),b=_.useMemo(()=>{let M=g;if(d!=="all"&&(M=M.filter(I=>{var D;return(D=I.tags)==null?void 0:D.some(O=>O.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},[g,o,d]),j=()=>{h.size===b.length?m(new Set):m(new Set(b.map(M=>M.id)))},S=M=>{const I=new Set(h);I.has(M)?I.delete(M):I.add(M),m(I)},C=_.useMemo(()=>g.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})),[g,h]),{defaultSubject:E,defaultBody:P}=_.useMemo(()=>{var te,ae,le,be;const M=n.property_address||`${n.city}, ${n.state}`,I=xBs(n.price),D=gBs[n.property_type]||"home",O=n.bedrooms?`${n.bedrooms} bed`:"",V=n.bathrooms?`${n.bathrooms} bath`:"",G=n.square_footage?`${n.square_footage.toLocaleString()} sqft`:"",$=[O,V,G].filter(Boolean).join(" • "),H=`https://listings.relevelup.com/${n.slug||n.id}`,Y=((ae=(te=n.photos)==null?void 0:te.find(me=>me.is_primary))==null?void 0:ae.photo_url)||((be=(le=n.photos)==null?void 0:le[0])==null?void 0:be.photo_url)||"",ne={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",ce=`${ne}: ${M} — ${I}`,ie=`

Hi {{first_name}},

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

${Y?` ${M} `:""}
${ne}

${I}

${M}

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

${$?`

${$} • ${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:ce,defaultBody:ie}},[n]);return p?e.jsx(DS,{open:p,onOpenChange:M=>{f(M),M||t(!1)},bulkContacts:C,defaultSubject:E,defaultBody:P,gmailEmail:y}):e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"sm:max-w-[640px] max-h-[90vh] flex flex-col",children:[e.jsxs(Os,{children:[e.jsxs(Ds,{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-5 w-5 text-amber-500"}),"Email this listing to your sphere"]}),e.jsx(_r,{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(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search contacts...",value:o,onChange:M=>c(M.target.value),className:"pl-9"})]}),e.jsxs(is,{value:d,onValueChange:u,children:[e.jsx(rs,{className:"sm:w-[180px]",children:e.jsx(ls,{placeholder:"Filter by tag"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All contacts"}),l.map(M=>e.jsx(He,{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:j,className:"flex items-center gap-2 text-primary hover:underline",children:[e.jsx($a,{checked:b.length>0&&h.size===b.length,className:"pointer-events-none"}),e.jsx("span",{children:h.size===b.length&&b.length>0?"Deselect all":`Select all (${b.length})`})]}),e.jsxs(Oe,{variant:"secondary",className:"gap-1",children:[e.jsx(In,{className:"h-3 w-3"}),h.size," selected"]})]}),e.jsx(Ji,{className:"flex-1 -mx-6 px-6",children:i?e.jsxs("div",{className:"flex items-center justify-center py-12 text-muted-foreground",children:[e.jsx(Ct,{className:"h-5 w-5 animate-spin mr-2"}),"Loading your contacts..."]}):b.length===0?e.jsx("div",{className:"text-center py-12 text-muted-foreground text-sm",children:g.length===0?"No contacts with email addresses yet.":"No contacts match your search."}):e.jsx("div",{className:"space-y-1 py-2",children:b.map(M=>e.jsxs("label",{className:"flex items-center gap-3 p-2 rounded-md hover:bg-muted/50 cursor-pointer",children:[e.jsx($a,{checked:h.has(M.id),onCheckedChange:()=>S(M.id)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:"text-sm font-medium truncate",children:[M.first_name," ",M.last_name]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:M.email})]}),M.tags&&M.tags.length>0&&e.jsx("div",{className:"flex gap-1 flex-wrap justify-end max-w-[40%]",children:M.tags.slice(0,2).map(I=>{var D;return e.jsx(Oe,{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(wc,{}),e.jsxs("div",{className:"flex justify-between items-center gap-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:y?`Sending from ${y}`:"Connect Gmail in Settings to send"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{onClick:()=>f(!0),disabled:h.size===0,className:"gap-2",children:[e.jsx(ln,{className:"h-4 w-4"}),"Compose Email (",h.size,")"]})]})]})]})})}const yBs=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)}`},vgt=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),bI="#D4AF37",bgt="#0F172A",_gt=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}),wgt=(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)},pX=(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()}…`},vBs=(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},_Bs=s=>s instanceof DOMException||s instanceof Error?s.name:null;function met({listingId:s,open:t,onOpenChange:n}){var C,E;const{data:r}=eae(s||""),[a,i]=_.useState(null),[l,o]=_.useState(!1),[c,d]=_.useState(null),[u,h]=_.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));_.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]),_.useEffect(()=>{let P=!1;if(!(!t||!(r!=null&&r.agent_id)))return(async()=>{var O,V,G,$;const{data:M}=await q.from("profiles").select("name, phone, phone_e164, avatar_url, brokerage:brokerages!profiles_brokerage_id_fkey(name)").eq("id",r.agent_id).maybeSingle();if(P)return;const I=M,D=((O=I==null?void 0:I.brokerage)==null?void 0:O.name)||((G=(V=r.agent)==null?void 0:V.brokerage)==null?void 0:G.name)||null;i({name:(I==null?void 0:I.name)||(($=r.agent)==null?void 0:$.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]),_.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=bgt,M.fillRect(0,0,1080,1080),b){const $=await _gt(b);wgt(M,$,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=bI,M.fillRect(56,62,72,2),M.font="600 22px Arial, sans-serif",bBs(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=vBs(M,r.property_address||`${r.city||""}, ${r.state||""}`.trim(),952,2);let O=D.length>1?590:654;D.forEach($=>{M.fillText($,64,O),O+=70}),M.restore();const V=[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(pX(M,V.toUpperCase(),952),64,O+8),M.fillStyle=bI,M.font="700 56px Arial, sans-serif",M.fillText(vgt(r.price),64,O+58),S.length>0&&(M.fillStyle="rgba(248,250,252,0.86)",M.font="600 22px Arial, sans-serif",M.fillText(pX(M,S.join(" · "),430),360,O+78));const G=M.createLinearGradient(0,880,0,1080);if(G.addColorStop(0,"rgba(15,23,42,0.96)"),G.addColorStop(1,"#0B1322"),M.fillStyle=G,M.fillRect(0,880,1080,200),M.fillStyle=bI,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=bI,M.stroke(),M.clip(),a.avatar_url)try{const $=await _gt(a.avatar_url);wgt(M,$,64,920,120,120)}catch{M.fillStyle=bI,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=bI,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(pX(M,a.name,j?430:820),212,970),a.brokerage&&(M.fillStyle=bI,M.font="600 20px Arial, sans-serif",M.fillText(pX(M,a.brokerage.toUpperCase(),j?430:820),212,1008)),j&&(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(j,1016,1008)),d(P.toDataURL("image/png"))}catch(P){console.error("Generate graphic error",P),se.error("Could not generate graphic")}finally{o(!1)}}},f=async P=>(await fetch(P)).blob(),y=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(),se.success("Downloaded!")},v=async()=>{if(c)try{const P=await f(c);await navigator.clipboard.write([new ClipboardItem({"image/png":P})]),se.success("Copied to clipboard")}catch{se.error("Copy not supported in this browser")}},g=async()=>{if(c)try{const P=await f(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"}):y()}catch(P){_Bs(P)!=="AbortError"&&se.error("Share failed")}},b=u||((C=m[0])==null?void 0:C.photo_url)||null,j=yBs(a==null?void 0:a.phone),S=[r!=null&&r.bedrooms?`${r.bedrooms} BD`:null,r!=null&&r.bathrooms?`${r.bathrooms} BA`:null,r!=null&&r.square_footage?`${r.square_footage.toLocaleString()} SF`:null].filter(Boolean);return e.jsx(Ls,{open:t,onOpenChange:n,children:e.jsx(Ps,{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(Os,{className:"px-5 pt-5 pb-3 shrink-0",children:[e.jsxs(Ds,{className:"flex items-center gap-2 pr-8",children:[e.jsx(un,{className:"h-5 w-5 text-amber-500 shrink-0"}),e.jsx("span",{className:"truncate",children:"Your Just Listed Graphic"})]}),e.jsx(_r,{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:bgt},children:[b&&e.jsx("img",{src:b,alt:"Selected property",className:"absolute inset-0 h-full w-full object-cover"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-b from-slate-950/65 via-slate-950/25 to-slate-950"}),e.jsxs("div",{className:"absolute left-4 right-4 top-4 flex items-center gap-2",children:[e.jsx("span",{className:"h-px w-6 bg-amber-400"}),e.jsx("span",{className:"text-[9px] font-semibold uppercase tracking-[0.28em] text-amber-300",children:"Just Listed"})]}),e.jsxs("div",{className:"absolute left-4 right-4 bottom-[64px] text-white",children:[e.jsx("div",{className:"line-clamp-2 font-serif text-[18px] font-semibold leading-[1.05] drop-shadow-lg",children:(r==null?void 0:r.property_address)||`${(r==null?void 0:r.city)||""}, ${(r==null?void 0:r.state)||""}`}),e.jsxs("div",{className:"mt-1 truncate text-[9px] font-semibold uppercase tracking-[0.18em] text-white/85",children:[[r==null?void 0:r.city,r==null?void 0:r.state].filter(Boolean).join(", "),r!=null&&r.neighborhood?` · ${r.neighborhood}`:""]}),e.jsxs("div",{className:"mt-1.5 flex items-center gap-2",children:[e.jsx("span",{className:"text-[16px] font-bold text-amber-300",children:r?vgt(r.price):""}),S.length>0&&e.jsx("span",{className:"truncate text-[8px] font-semibold uppercase tracking-[0.14em] text-white/80",children:S.join(" · ")})]})]}),e.jsxs("div",{className:"absolute inset-x-0 bottom-0 flex h-[52px] items-center border-t border-amber-400 bg-slate-950/95 px-4",children:[e.jsx("div",{className:"flex h-9 w-9 shrink-0 items-center justify-center overflow-hidden rounded-full border-2 border-amber-400 bg-slate-800 text-xs font-bold text-amber-300",children:a!=null&&a.avatar_url?e.jsx("img",{src:a.avatar_url,alt:"",className:"h-full w-full object-cover"}):(E=a==null?void 0:a.name)==null?void 0:E.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})]}),j&&e.jsx("div",{className:"ml-2 shrink-0 text-[9px] font-semibold text-white",children:j})]}),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(Ct,{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(B,{variant:"outline",size:"sm",onClick:()=>void p(),disabled:l||!r||!a,children:"Regenerate"}),e.jsxs(B,{variant:"outline",size:"sm",onClick:v,disabled:!c,className:"gap-1.5",children:[e.jsx(Ia,{className:"h-3.5 w-3.5"})," Copy"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:g,disabled:!c,className:"gap-1.5",children:[e.jsx(bd,{className:"h-3.5 w-3.5"})," Share"]}),e.jsxs(B,{size:"sm",onClick:y,disabled:!c,className:"gap-1.5",children:[e.jsx(li,{className:"h-3.5 w-3.5"})," Download"]})]})]})})})}function wBs({listing:s,canEdit:t}){const n=Fn(),{data:r,isLoading:a}=F6s(s.id),i=wFt(),l=jFt(),[o,c]=_.useState({owner_name:"",owner_company:"",owner_email:"",owner_phone:"",decision_maker_notes:"",pitch_date:"",positioning:"",pricing_strategy:"",pitch_notes:"",competitors:""}),[d,u]=_.useState(vFt),[h,m]=_.useState("");_.useEffect(()=>{r&&(c({owner_name:r.owner_name??"",owner_company:r.owner_company??"",owner_email:r.owner_email??"",owner_phone:r.owner_phone??"",decision_maker_notes:r.decision_maker_notes??"",pitch_date:r.pitch_date?String(r.pitch_date).slice(0,10):"",positioning:r.positioning??"",pricing_strategy:r.pricing_strategy??"",pitch_notes:r.pitch_notes??"",competitors:r.competitors??""}),Array.isArray(r.launch_plan)&&r.launch_plan.length&&u(r.launch_plan))},[r]);const p=r!=null&&r.preview_token?`${window.location.origin}/commercial-pitch/${r.preview_token}`:null,f=async()=>{await i.mutateAsync({listingId:s.id,values:{...o,pitch_date:o.pitch_date||null,launch_plan:d.filter(g=>{var b;return(b=g.label)==null?void 0:b.trim()})}}),se.success("Pitch saved")},y=async()=>{await l.mutateAsync({listingId:s.id,stage:"won"}),se.success("Assignment won — welcome to Launch"),n(`/mission-control/listings/${s.id}/commercial`)},v=async()=>{await l.mutateAsync({listingId:s.id,stage:"lost",lostReason:h}),se("Marked as lost opportunity"),n("/mission-control/listings")};return a?e.jsx("div",{className:"flex justify-center py-20",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):t?e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-6 lg:grid-cols-3",children:[e.jsxs("div",{className:"space-y-6 lg:col-span-2",children:[e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsx(St,{className:"text-base",children:"Owner & decision makers"}),e.jsx(kn,{children:"Who actually signs the listing agreement."})]}),e.jsxs(Me,{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Owner name"}),e.jsx(xe,{value:o.owner_name,onChange:g=>c({...o,owner_name:g.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Entity / company"}),e.jsx(xe,{value:o.owner_company,onChange:g=>c({...o,owner_company:g.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Email"}),e.jsx(xe,{type:"email",value:o.owner_email,onChange:g=>c({...o,owner_email:g.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Phone"}),e.jsx(xe,{value:o.owner_phone,onChange:g=>c({...o,owner_phone:g.target.value})})]}),e.jsxs("div",{className:"space-y-2 md:col-span-2",children:[e.jsx(J,{children:"Decision-maker intel"}),e.jsx(Ms,{rows:3,value:o.decision_maker_notes,onChange:g=>c({...o,decision_maker_notes:g.target.value}),placeholder:"Motivations, timing, partners, tax position, who influences the decision…"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Pitch date"}),e.jsx(xe,{type:"date",value:o.pitch_date,onChange:g=>c({...o,pitch_date:g.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Competing brokers"}),e.jsx(xe,{value:o.competitors,onChange:g=>c({...o,competitors:g.target.value})})]})]})]}),e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsx(St,{className:"text-base",children:"Positioning & pricing strategy"}),e.jsx(kn,{children:"The argument you're making for how this asset goes to market."})]}),e.jsxs(Me,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Proposed positioning"}),e.jsx(Ms,{rows:4,value:o.positioning,onChange:g=>c({...o,positioning:g.target.value}),placeholder:"Buyer profile, story, comparable trades, why this asset wins attention…"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Pricing strategy"}),e.jsx(Ms,{rows:4,value:o.pricing_strategy,onChange:g=>c({...o,pricing_strategy:g.target.value}),placeholder:"Recommended ask, cap-rate rationale, call-for-offers timing…"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Private pitch notes"}),e.jsx(Ms,{rows:3,value:o.pitch_notes,onChange:g=>c({...o,pitch_notes:g.target.value}),placeholder:"Never shown to the owner."})]})]})]}),e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsx(St,{className:"text-base",children:"Proposed launch plan"}),e.jsx(kn,{children:"Shown on the owner-facing preview — this is what they buy."})]}),e.jsxs(Me,{className:"space-y-3",children:[d.map((g,b)=>e.jsxs("div",{className:"rounded-lg border p-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{value:g.label,placeholder:"Milestone",onChange:j=>u(d.map((S,C)=>C===b?{...S,label:j.target.value}:S))}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>u(d.filter((j,S)=>S!==b)),children:e.jsx(Qn,{className:"h-4 w-4"})})]}),e.jsx(Ms,{className:"mt-2",rows:2,value:g.detail??"",placeholder:"What happens in this step",onChange:j=>u(d.map((S,C)=>C===b?{...S,detail:j.target.value}:S))})]},b)),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>u([...d,{label:"",detail:""}]),children:[e.jsx(rn,{className:"mr-1.5 h-3.5 w-3.5"})," Add step"]})]})]})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(ve,{className:"border-primary/30 bg-gradient-to-br from-primary/[0.06] to-transparent",children:[e.jsxs(bt,{children:[e.jsx(St,{className:"text-base",children:"Owner preview"}),e.jsx(kn,{children:"A private, seller-facing page showing exactly what happens the day they hire you."})]}),e.jsx(Me,{className:"space-y-3",children:p?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex items-center gap-2 rounded-lg border bg-background px-3 py-2",children:e.jsx("span",{className:"truncate text-xs text-muted-foreground",children:p})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",className:"flex-1",onClick:()=>{navigator.clipboard.writeText(p),se.success("Link copied")},children:[e.jsx(Ia,{className:"mr-1.5 h-3.5 w-3.5"})," Copy"]}),e.jsxs(B,{size:"sm",className:"flex-1",onClick:()=>window.open(p,"_blank"),children:[e.jsx(wr,{className:"mr-1.5 h-3.5 w-3.5"})," Open"]})]})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Save the pitch to generate the private preview link."})})]}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"Outcome"})}),e.jsxs(Me,{className:"space-y-3",children:[e.jsxs(Kl,{children:[e.jsx(jx,{asChild:!0,children:e.jsxs(B,{className:"w-full",children:[e.jsx(wl,{className:"mr-2 h-4 w-4"})," Won listing"]})}),e.jsxs(Ol,{children:[e.jsxs(zl,{children:[e.jsx(Ul,{children:"Convert this pitch into a Commercial Launch?"}),e.jsx(ql,{children:"Everything you've entered carries over. The listing moves into the Launch stage where you can publish the microsite, gate the OM and start tracking investor activity."})]}),e.jsxs(Bl,{children:[e.jsx($l,{children:"Cancel"}),e.jsx(Ml,{onClick:y,children:"Yes — we won it"})]})]})]}),e.jsxs(Kl,{children:[e.jsx(jx,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:"w-full",children:[e.jsx(Rd,{className:"mr-2 h-4 w-4"})," Lost opportunity"]})}),e.jsxs(Ol,{children:[e.jsxs(zl,{children:[e.jsx(Ul,{children:"Mark as lost?"}),e.jsx(ql,{children:"Kept private in your archive so you can learn from it."})]}),e.jsx(xe,{placeholder:"Reason (optional)",value:h,onChange:g=>m(g.target.value)}),e.jsxs(Bl,{children:[e.jsx($l,{children:"Cancel"}),e.jsx(Ml,{onClick:v,children:"Mark lost"})]})]})]})]})]})]})]}),e.jsx("div",{className:"sticky bottom-4 flex justify-end",children:e.jsxs(B,{onClick:f,disabled:i.isPending,size:"lg",className:"shadow-lg",children:[i.isPending?e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Ho,{className:"mr-2 h-4 w-4"}),"Save pitch"]})})]}):e.jsx(ve,{children:e.jsxs(bt,{children:[e.jsx(St,{className:"text-base",children:"Private pitch workspace"}),e.jsx(kn,{children:"Only the listing agent can view or update pitch strategy and owner information."})]})})}function jBs({listingId:s}){const{data:t=[],isLoading:n}=WPe(s),r=P9t(),a=L9t(),i=K7s(),l=_.useRef(null),[o,c]=_.useState("om"),[d,u]=_.useState("email"),h=async p=>{if(p!=null&&p.length)try{for(const f of Array.from(p))await r.mutateAsync({listingId:s,file:f,docKind:o,gateLevel:d});se.success("Document uploaded")}catch(f){se.error(f.message||"Upload failed")}finally{l.current&&(l.current.value="")}},m=async p=>{try{window.open(await net(p),"_blank")}catch{se.error("Could not open document")}};return e.jsx("div",{className:"space-y-6",children:e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsx(St,{className:"text-base",children:"Deal room"}),e.jsx(kn,{children:"Offering memorandum, financials and diligence files. Everything is stored privately and released through expiring secure links only."})]}),e.jsxs(Me,{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-muted-foreground",children:"Document type"}),e.jsxs(is,{value:o,onValueChange:p=>c(p),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsx(as,{children:Object.entries(V$e).map(([p,f])=>e.jsx(He,{value:p,children:f},p))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-muted-foreground",children:"Access"}),e.jsxs(is,{value:d,onValueChange:p=>u(p),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsx(as,{children:Object.entries(Ypt).map(([p,f])=>e.jsx(He,{value:p,children:f},p))})]})]}),e.jsxs("div",{className:"flex items-end",children:[e.jsxs(B,{className:"w-full",onClick:()=>{var p;return(p=l.current)==null?void 0:p.click()},disabled:r.isPending,children:[r.isPending?e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Oa,{className:"mr-2 h-4 w-4"}),"Upload"]}),e.jsx("input",{ref:l,type:"file",multiple:!0,className:"hidden",onChange:p=>h(p.target.files)})]})]}),n?e.jsx("div",{className:"flex justify-center py-10",children:e.jsx(Ct,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):t.length===0?e.jsxs("div",{className:"rounded-xl border border-dashed py-12 text-center",children:[e.jsx(Fr,{className:"mx-auto mb-3 h-7 w-7 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No documents yet. Upload the OM to activate gated requests."})]}):e.jsx("div",{className:"divide-y rounded-xl border",children:t.map(p=>e.jsxs("div",{className:"flex flex-wrap items-center gap-3 p-4",children:[e.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-lg border bg-muted/40",children:e.jsx(Fr,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:p.title||p.file_name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(p.file_size/1024/1024).toFixed(2)," MB · ",p.download_count??0," downloads"]})]}),e.jsx(Oe,{variant:"secondary",children:V$e[p.doc_kind||"other"]}),e.jsxs(is,{value:p.gate_level||"email",onValueChange:f=>i.mutate({id:p.id,listingId:s,values:{gate_level:f}}),children:[e.jsxs(rs,{className:"w-[190px]",children:[p.gate_level==="public"?e.jsx(li,{className:"mr-2 h-3.5 w-3.5"}):p.gate_level==="nda"?e.jsx(Dm,{className:"mr-2 h-3.5 w-3.5"}):e.jsx(ec,{className:"mr-2 h-3.5 w-3.5"}),e.jsx(ls,{})]}),e.jsx(as,{children:Object.entries(Ypt).map(([f,y])=>e.jsx(He,{value:f,children:y},f))})]}),e.jsx(B,{variant:"outline",size:"sm",onClick:()=>m(p.storage_path),children:"Preview"}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>a.mutate({id:p.id,storage_path:p.storage_path,listingId:s}),children:e.jsx(Sn,{className:"h-4 w-4"})})]},p.id))})]})]})})}const NBs={om_request:"OM request",tour_request:"Tour request",investor_inquiry:"Investor inquiry",loi_intent:"LOI intent",inquiry:"Inquiry",showing_request:"Tour request",general:"Inquiry"};function kBs({listingId:s}){const{data:t=[],isLoading:n}=uJe(s),{data:r=[]}=dJe(s),a=_.useMemo(()=>{const o={};for(const c of r)c.lead_id&&(o[c.lead_id]=(o[c.lead_id]??0)+(Xpt[c.event_type]??1));return o},[r]),i=_.useMemo(()=>[...t].map(o=>({...o,score:(a[o.id]??0)+(Xpt[o.lead_type]??5)})).sort((o,c)=>c.score-o.score),[t,a]),l=i.filter(o=>o.score>=12);return n?e.jsx("div",{className:"flex justify-center py-20",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-6",children:[l.length>0&&e.jsxs(ve,{className:"border-amber-500/30 bg-amber-500/[0.04]",children:[e.jsxs(bt,{children:[e.jsx(St,{className:"text-base",children:"High-interest prospects"}),e.jsx(kn,{children:"Ranked by document access, tour requests and repeat engagement."})]}),e.jsx(Me,{className:"grid gap-3 md:grid-cols-2",children:l.slice(0,6).map(o=>{const c=Qpt(o.score);return e.jsxs("div",{className:"rounded-xl border bg-background p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate font-medium",children:[o.first_name,o.last_name].filter(Boolean).join(" ")||o.email}),e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:o.company||H$e[o.investor_role||"other"]})]}),e.jsx(Oe,{variant:"outline",className:c.tone,children:c.label})]}),e.jsxs("div",{className:"mt-3 flex gap-2",children:[e.jsx(B,{asChild:!0,size:"sm",variant:"outline",children:e.jsxs("a",{href:`mailto:${o.email}`,children:[e.jsx(ln,{className:"mr-1.5 h-3.5 w-3.5"})," Email"]})}),o.phone&&e.jsx(B,{asChild:!0,size:"sm",variant:"ghost",children:e.jsxs("a",{href:`tel:${o.phone}`,children:[e.jsx(_a,{className:"mr-1.5 h-3.5 w-3.5"})," Call"]})})]})]},o.id)})})]}),e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsx(St,{className:"text-base",children:"Investors & inquiries"}),e.jsx(kn,{children:"Every prospect is written into your LevelUp CRM automatically."})]}),e.jsx(Me,{children:i.length===0?e.jsxs("div",{className:"rounded-xl border border-dashed py-14 text-center",children:[e.jsx(In,{className:"mx-auto mb-3 h-7 w-7 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No inquiries yet. Publish the microsite and start distribution."})]}):e.jsx("div",{className:"divide-y rounded-xl border",children:i.map(o=>{const c=Qpt(o.score);return e.jsxs("div",{className:"flex flex-wrap items-center gap-3 p-4",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"truncate text-sm font-medium",children:[[o.first_name,o.last_name].filter(Boolean).join(" ")||o.email,o.company&&e.jsxs("span",{className:"text-muted-foreground",children:[" · ",o.company]})]}),e.jsxs("p",{className:"truncate text-xs text-muted-foreground",children:[o.email,o.phone?` · ${o.phone}`:""," · ",new Date(o.created_at).toLocaleDateString()]}),o.message&&e.jsxs("p",{className:"mt-1 line-clamp-2 text-xs text-muted-foreground",children:['"',o.message,'"']})]}),o.investor_role&&e.jsx(Oe,{variant:"secondary",children:H$e[o.investor_role]??o.investor_role}),e.jsx(Oe,{variant:"outline",children:NBs[o.lead_type]??o.lead_type}),e.jsx(Oe,{variant:"outline",className:c.tone,children:c.label}),e.jsx(B,{asChild:!0,size:"sm",variant:"outline",children:e.jsx("a",{href:`mailto:${o.email}`,children:"Reply"})})]},o.id)})})})]})]})}const SBs={page_view:"Viewed the microsite",gallery_view:"Opened the gallery",om_request:"Requested the Offering Memorandum",om_download:"Downloaded the Offering Memorandum",doc_download:"Downloaded a document",tour_request:"Requested a tour",inquiry:"Submitted an inquiry",contact_click:"Clicked to contact the broker",share_click:"Opened a shared link",map_view:"Explored the location"};function CBs({listing:s}){const{data:t=[],isLoading:n}=dJe(s.id),{data:r=[]}=uJe(s.id),[a,i]=_.useState(""),[l,o]=_.useState(""),[c,d]=_.useState(!1),u=async p=>{d(!0);try{const{data:f,error:y}=await q.functions.invoke("commercial-seller-report",{body:{action:p?"send":"generate",listingId:s.id,days:7,narrative:l||null,recipients:a.split(/[,\s]+/).map(v=>v.trim()).filter(Boolean)}});if(y)throw y;if(f!=null&&f.error)throw new Error(f.error);se.success(p?"Activity report sent to your owner":"Weekly report generated")}catch(f){se.error(f.message||"Could not build the report")}finally{d(!1)}},h=_.useMemo(()=>{const p=v=>{const g=Array.isArray(v)?v:[v];return t.filter(b=>g.includes(b.event_type)).length},f=new Set(t.map(v=>v.session_id).filter(Boolean)),y=new Map;return t.forEach(v=>v.session_id&&y.set(v.session_id,(y.get(v.session_id)??0)+1)),{views:p("page_view")||s.view_count||0,unique:f.size,repeat:[...y.values()].filter(v=>v>3).length,omRequests:p(["om_request","om_download"]),downloads:p(["doc_download","om_download"]),tours:p("tour_request"),inquiries:r.length,shares:s.share_count??0}},[t,r,s]),m=[{label:"Microsite views",value:h.views,icon:ya},{label:"Unique visitors",value:h.unique,icon:In},{label:"Repeat visitors",value:h.repeat,icon:hm},{label:"OM requests",value:h.omRequests,icon:SQ},{label:"Document downloads",value:h.downloads,icon:li},{label:"Tour requests",value:h.tours,icon:hm},{label:"Total inquiries",value:h.inquiries,icon:In},{label:"Shares",value:h.shares,icon:bd}];return e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"grid gap-px overflow-hidden rounded-xl border bg-border sm:grid-cols-2 lg:grid-cols-4",children:m.map(p=>e.jsxs("div",{className:"bg-card px-5 py-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(p.icon,{className:"h-3.5 w-3.5"}),e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.16em]",children:p.label})]}),e.jsx("p",{className:"mt-1.5 text-2xl font-semibold tabular-nums",children:p.value})]},p.label))}),e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsx(St,{className:"text-base",children:"Send the weekly owner report"}),e.jsx(kn,{children:"Last 7 days of activity, packaged as a branded report the owner can read in their inbox."})]}),e.jsxs(Me,{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Owner email(s)"}),e.jsx(xe,{placeholder:"owner@example.com, asset.manager@example.com",value:a,onChange:p=>i(p.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Broker note (optional)"}),e.jsx(Ms,{rows:2,placeholder:"What you did this week and what happens next.",value:l,onChange:p=>o(p.target.value)})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(B,{onClick:()=>u(!0),disabled:c,children:[c?e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(ln,{className:"mr-2 h-4 w-4"}),"Send report"]}),e.jsx(B,{variant:"outline",onClick:()=>u(!1),disabled:c,children:"Save without sending"})]})]})]}),e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsx(St,{className:"text-base",children:"Owner activity report"}),e.jsx(kn,{children:"Everything below is what your owner sees in the weekly activity report — proof the asset is being worked."})]}),e.jsx(Me,{children:n?e.jsx("div",{className:"flex justify-center py-10",children:e.jsx(Ct,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):t.length===0?e.jsxs("div",{className:"rounded-xl border border-dashed py-14 text-center",children:[e.jsx(hm,{className:"mx-auto mb-3 h-7 w-7 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Activity appears here the moment the microsite goes live and prospects engage."})]}):e.jsx("div",{className:"space-y-1",children:t.slice(0,40).map(p=>e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg px-3 py-2 hover:bg-muted/50",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-primary/60"}),e.jsx("p",{className:"truncate text-sm",children:SBs[p.event_type]??p.event_type}),p.lead_id&&e.jsx(Oe,{variant:"secondary",className:"shrink-0",children:"Identified"})]}),e.jsx("p",{className:"shrink-0 text-xs text-muted-foreground",children:new Date(p.created_at).toLocaleString(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})})]},p.id))})})]})]})}function ABs({listing:s,details:t,publicUrl:n}){var f,y;const r=Fn(),[a,i]=_.useState(!1),l=s.photos??[],[o,c]=_.useState(0),d=(f=l[o])==null?void 0:f.photo_url,u=[...(t==null?void 0:t.investment_highlights)??[],...(t==null?void 0:t.property_highlights)??[]].filter(Boolean),h=(t==null?void 0:t.spaces)??[],m=(t==null?void 0:t.tenants)??[],p=s.agent;return e.jsxs(zs,{title:"Commercial Listing",children:[e.jsxs("div",{className:"mx-auto max-w-6xl px-4 py-6",children:[e.jsxs(B,{variant:"ghost",size:"sm",className:"-ml-2 mb-4",onClick:()=>r("/mission-control/listings"),children:[e.jsx(ka,{className:"mr-2 h-4 w-4"})," Listing Exchange"]}),e.jsx("div",{className:"overflow-hidden rounded-2xl border bg-muted",children:d?e.jsx("img",{src:d,alt:cP(s,t),className:"h-[300px] w-full object-cover md:h-[440px]"}):e.jsxs("div",{className:"flex h-[240px] w-full items-center justify-center text-muted-foreground",children:[e.jsx(hc,{className:"mr-2 h-5 w-5"})," No photos yet"]})}),l.length>1&&e.jsx("div",{className:"mt-3 flex gap-2 overflow-x-auto pb-1",children:l.map((v,g)=>e.jsx("button",{onClick:()=>c(g),className:`h-16 w-24 shrink-0 overflow-hidden rounded-lg border-2 ${g===o?"border-primary":"border-transparent"}`,children:e.jsx("img",{src:v.photo_url,alt:"",className:"h-full w-full object-cover"})},v.id??g))}),e.jsxs("div",{className:"mt-6 flex flex-wrap items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"mb-2 flex flex-wrap items-center gap-2",children:[e.jsxs(Oe,{variant:"outline",className:"border-primary/30 bg-primary/10 text-primary",children:[e.jsx(ai,{className:"mr-1 h-3 w-3"})," Commercial"]}),(t==null?void 0:t.deal_type)&&e.jsx(Oe,{variant:"secondary",children:DP[t.deal_type]}),(t==null?void 0:t.commercial_type)&&e.jsx(Oe,{variant:"secondary",children:hL[t.commercial_type]}),(t==null?void 0:t.is_confidential)&&e.jsxs(Oe,{variant:"outline",children:[e.jsx(ec,{className:"mr-1 h-3 w-3"})," Confidential"]})]}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight md:text-3xl",children:cP(s,t)}),e.jsxs("p",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(Xa,{className:"h-4 w-4"})," ",Wre(s,t)]}),e.jsx("p",{className:"mt-2 text-2xl font-semibold",children:EH(t,s.price)})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.is_public&&e.jsxs(B,{variant:"outline",onClick:()=>window.open(n,"_blank"),children:[e.jsx(wr,{className:"mr-2 h-4 w-4"})," View microsite"]}),s.allow_sharing&&e.jsxs(B,{onClick:()=>i(!0),children:[e.jsx(bd,{className:"mr-2 h-4 w-4"})," Share link"]})]})]}),e.jsx("div",{className:"mt-6",children:e.jsx(kFt,{details:t})}),e.jsxs("div",{className:"mt-6 grid gap-6 lg:grid-cols-3",children:[e.jsxs("div",{className:"space-y-6 lg:col-span-2",children:[s.description&&e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"About this property"})}),e.jsx(Me,{className:"whitespace-pre-line text-sm text-muted-foreground",children:s.description})]}),u.length>0&&e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"Highlights"})}),e.jsx(Me,{className:"space-y-2",children:u.map((v,g)=>e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(un,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),e.jsx("span",{children:v})]},g))})]}),h.length>0&&e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"Available spaces"})}),e.jsx(Me,{className:"space-y-2 text-sm",children:h.map((v,g)=>e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 border-b pb-2 last:border-0",children:[e.jsx("span",{className:"font-medium",children:v.suite||`Space ${g+1}`}),e.jsx("span",{className:"text-muted-foreground",children:[LA(v.sf),v.rate,v.use,v.availability].filter(Boolean).join(" · ")})]},g))})]}),m.length>0&&e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"Tenant roster"})}),e.jsx(Me,{className:"space-y-2 text-sm",children:m.map((v,g)=>e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 border-b pb-2 last:border-0",children:[e.jsx("span",{className:"font-medium",children:v.name||`Tenant ${g+1}`}),e.jsx("span",{className:"text-muted-foreground",children:[LA(v.sf),v.rent,v.lease_expiry].filter(Boolean).join(" · ")})]},g))})]})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"Listing agent"})}),e.jsxs(Me,{className:"space-y-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:(p==null?void 0:p.name)||"LevelUp Member"}),((y=p==null?void 0:p.brokerage)==null?void 0:y.name)&&e.jsx("p",{className:"text-muted-foreground",children:p.brokerage.name})]}),(p==null?void 0:p.email)&&e.jsxs(B,{variant:"outline",className:"w-full",onClick:()=>window.open(`mailto:${p.email}`),children:[e.jsx(ln,{className:"mr-2 h-4 w-4"})," Email agent"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Only the listing agent can update this listing."})]})]}),s.open_to_referrals&&e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"Open to referrals"})}),e.jsx(Me,{className:"text-sm text-muted-foreground",children:"The listing agent welcomes buyer or tenant referrals on this opportunity."})]})]})]})]}),e.jsx(aLe,{open:a,onOpenChange:i,listingId:s.id,listingSlug:s.slug??null,listingTitle:cP(s,t),isCommercial:!0})]})}function EBs(){const{listingId:s=""}=Li(),t=Fn(),{user:n}=hs(),[r,a]=Yl(),{data:i,isLoading:l}=eae(s),{data:o}=bFt(s),{data:c=[]}=WPe(s),{data:d=[]}=dJe(s),{data:u=[]}=uJe(s),h=_Ft(),m=jFt(),p=O6s(),f=S9t(),y=C9t(),v=A9t(),g=E9t(),[b,j]=_.useState(!1),[S,C]=_.useState(!1),[E,P]=_.useState(!1),[M,I]=_.useState(!1),[D,O]=_.useState(!1),V=r.get("tab")||"overview",G=ae=>a({tab:ae},{replace:!0}),$=i?`${window.location.origin}/public/listing/${i.slug||i.id}`:"",H=_.useMemo(()=>{var ae;return D6s(o,{photoCount:((ae=i==null?void 0:i.photos)==null?void 0:ae.length)??0,hasOm:c.some(le=>le.doc_kind==="om"),isPublic:!!(i!=null&&i.is_public)})},[o,i,c]),Y=async ae=>{var le;if(!(!ae||!i)){j(!0);try{for(const be of Array.from(ae)){const me=be.name.split(".").pop(),he=`${n==null?void 0:n.id}/${i.id}/${Date.now()}-${Math.random().toString(36).slice(2)}.${me}`,{error:pe}=await q.storage.from("listing-photos").upload(he,be);if(pe)throw pe;const{data:{publicUrl:Ce}}=q.storage.from("listing-photos").getPublicUrl(he);await f.mutateAsync({listingId:i.id,photoUrl:Ce,isPrimary:!((le=i.photos)!=null&&le.length)})}se.success("Photos uploaded")}catch(be){se.error(be.message||"Upload failed")}finally{j(!1)}}};if(l)return e.jsx(zs,{title:"Commercial Launch",children:e.jsx("div",{className:"flex min-h-[50vh] items-center justify-center",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})})});if(!i)return e.jsx(zs,{title:"Commercial Launch",children:e.jsx("div",{className:"flex min-h-[50vh] items-center justify-center text-muted-foreground",children:"Listing not found"})});const Z=i.lifecycle_stage==="pitch",ne=i.lifecycle_stage??"won",ce=bOe.findIndex(ae=>ae.key===ne),ie=cP(i,o),te=!!(n!=null&&n.id)&&i.agent_id===n.id;return te?e.jsx(zs,{title:"Commercial Launch",children:e.jsxs("div",{className:"bg-background",children:[e.jsx("div",{className:"border-b bg-gradient-to-b from-muted/40 to-background",children:e.jsxs("div",{className:"mx-auto max-w-7xl px-4 py-6",children:[e.jsxs(B,{variant:"ghost",size:"sm",className:"-ml-2 mb-4",onClick:()=>t("/mission-control/listings"),children:[e.jsx(ka,{className:"mr-2 h-4 w-4"})," Listing Exchange"]}),e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"mb-2 flex flex-wrap items-center gap-2",children:[e.jsxs(Oe,{variant:"outline",className:"border-primary/30 bg-primary/10 text-primary",children:[e.jsx(ai,{className:"mr-1 h-3 w-3"})," Commercial Launch"]}),(o==null?void 0:o.deal_type)&&e.jsx(Oe,{variant:"secondary",children:DP[o.deal_type]}),(o==null?void 0:o.commercial_type)&&e.jsx(Oe,{variant:"secondary",children:hL[o.commercial_type]}),Z&&e.jsxs(Oe,{className:"bg-amber-500/15 text-amber-600 hover:bg-amber-500/15",children:[e.jsx(ku,{className:"mr-1 h-3 w-3"})," Pitch — private"]}),(o==null?void 0:o.is_confidential)&&e.jsxs(Oe,{variant:"outline",children:[e.jsx(ec,{className:"mr-1 h-3 w-3"})," Confidential"]})]}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight md:text-3xl",children:ie}),e.jsx("p",{className:"text-muted-foreground",children:Wre(i,o)}),e.jsx("p",{className:"mt-2 text-xl font-semibold",children:EH(o,i.price)})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[!te&&e.jsxs(Oe,{variant:"outline",className:"self-center",children:[e.jsx(ec,{className:"mr-1 h-3 w-3"})," View only — listing agent controls updates"]}),te&&e.jsxs(B,{variant:"outline",onClick:()=>t(`/mission-control/listings/${i.id}/commercial/edit`),children:[e.jsx(Ya,{className:"mr-2 h-4 w-4"})," Edit details"]}),te&&!Z&&!i.is_public&&e.jsxs(B,{onClick:()=>{p.mutate({listingId:i.id,values:{is_public:!0,allow_sharing:!0,status:"active"}}),ne==="won"&&m.mutate({listingId:i.id,stage:"launched"})},children:[e.jsx(wr,{className:"mr-2 h-4 w-4"})," Publish & go live"]}),!Z&&i.is_public&&e.jsxs(B,{variant:"outline",onClick:()=>window.open($,"_blank"),children:[e.jsx(wr,{className:"mr-2 h-4 w-4"})," View microsite"]})]})]}),!Z&&e.jsx("div",{className:"mt-6 flex flex-wrap items-center gap-2",children:bOe.filter(ae=>ae.key!=="pitch").map((ae,le)=>{const be=bOe.findIndex(pe=>pe.key===ae.key),me=be===ce,he=bete&&m.mutate({listingId:i.id,stage:ae.key}),className:`flex items-center gap-2 rounded-full border px-3.5 py-1.5 text-xs font-medium transition-colors ${me?"border-primary bg-primary text-primary-foreground":he?"border-primary/30 bg-primary/10 text-primary":"text-muted-foreground hover:bg-muted"} ${te?"":"cursor-default"}`,children:[he&&e.jsx(ea,{className:"h-3 w-3"})," ",ae.label,le<4&&e.jsx("span",{className:"ml-1 opacity-40",children:"›"})]},ae.key)})})]})}),e.jsx("div",{className:"mx-auto max-w-7xl px-4 py-8",children:Z?e.jsx(wBs,{listing:i,canEdit:te}):e.jsxs(Yr,{value:te||["overview","marketing"].includes(V)?V:"overview",onValueChange:G,children:[e.jsxs(Zr,{className:"mb-6 flex w-full flex-wrap justify-start",children:[e.jsx(Ht,{value:"overview",children:"Overview"}),e.jsx(Ht,{value:"marketing",children:"Marketing"}),te&&e.jsx(Ht,{value:"investors",children:"Investors & Leads"}),te&&e.jsx(Ht,{value:"reporting",children:"Reporting"}),te&&e.jsx(Ht,{value:"documents",children:"Documents"}),te&&e.jsx(Ht,{value:"settings",children:"Settings"})]}),e.jsxs(Gt,{value:"overview",className:"space-y-6",children:[e.jsx(kFt,{details:o}),e.jsxs("div",{className:"grid gap-6 lg:grid-cols-3",children:[e.jsxs(ve,{className:"lg:col-span-2",children:[e.jsxs(bt,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(St,{className:"text-base",children:"Launch readiness"}),e.jsx(kn,{children:"Everything an institutional-quality launch needs."})]}),e.jsxs("span",{className:"text-2xl font-semibold tabular-nums",children:[H.score,"%"]})]}),e.jsx(Fi,{value:H.score,className:"mt-3"})]}),e.jsx(Me,{className:"space-y-2",children:j4e.map(ae=>{const le=H.done.includes(ae.key);return e.jsxs("button",{disabled:!te,onClick:()=>te&&h.mutate({listingId:i.id,values:{launch_checklist:{...(o==null?void 0:o.launch_checklist)??{},[ae.key]:!le}}}),className:"flex w-full items-start gap-3 rounded-lg px-3 py-2.5 text-left transition-colors hover:bg-muted/60",children:[e.jsx("span",{className:`mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded-full border ${le?"border-primary bg-primary text-primary-foreground":""}`,children:le&&e.jsx(ea,{className:"h-3 w-3"})}),e.jsxs("span",{children:[e.jsx("span",{className:`block text-sm font-medium ${le?"text-muted-foreground line-through":""}`,children:ae.label}),e.jsx("span",{className:"block text-xs text-muted-foreground",children:ae.detail})]})]},ae.key)})})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"Quick actions"})}),e.jsxs(Me,{className:"grid gap-2",children:[e.jsxs(B,{variant:"outline",className:"justify-start",onClick:()=>C(!0),children:[e.jsx(bd,{className:"mr-2 h-4 w-4"})," Share link"]}),e.jsxs(B,{variant:"outline",className:"justify-start",onClick:()=>P(!0),children:[e.jsx(Hf,{className:"mr-2 h-4 w-4"})," Signage QR code"]}),te&&e.jsxs(B,{variant:"outline",className:"justify-start",onClick:()=>I(!0),children:[e.jsx(ln,{className:"mr-2 h-4 w-4"})," Email brokers & investors"]}),te&&e.jsxs(B,{variant:"outline",className:"justify-start",onClick:()=>O(!0),children:[e.jsx(un,{className:"mr-2 h-4 w-4"})," Generate social post"]}),te&&e.jsxs(B,{variant:"outline",className:"justify-start",onClick:()=>G("documents"),children:[e.jsx(ec,{className:"mr-2 h-4 w-4"})," Manage gated OM"]})]})]}),(o==null?void 0:o.call_for_offers_at)&&e.jsxs(ve,{className:"border-amber-500/30 bg-amber-500/[0.05]",children:[e.jsx(bt,{className:"pb-2",children:e.jsx(St,{className:"text-sm",children:"Call for offers"})}),e.jsx(Me,{children:e.jsxs("p",{className:"flex items-center gap-2 text-lg font-semibold",children:[e.jsx(Qd,{className:"h-4 w-4"}),new Date(o.call_for_offers_at).toLocaleDateString(void 0,{month:"long",day:"numeric",year:"numeric"})]})})]}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"Recent engagement"})}),e.jsxs(Me,{className:"space-y-2",children:[d.slice(0,6).map(ae=>e.jsxs("div",{className:"flex items-center justify-between gap-2 text-sm",children:[e.jsx("span",{className:"truncate capitalize",children:ae.event_type.replace(/_/g," ")}),e.jsx("span",{className:"shrink-0 text-xs text-muted-foreground",children:new Date(ae.created_at).toLocaleDateString(void 0,{month:"short",day:"numeric"})})]},ae.id)),d.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No activity yet."}),e.jsxs("p",{className:"pt-2 text-xs text-muted-foreground",children:[u.length," inquiries captured"]})]})]})]})]})]}),e.jsxs(Gt,{value:"marketing",className:"space-y-6",children:[e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsx(St,{className:"text-base",children:"Photography"}),e.jsx(kn,{children:"The first image becomes the cinematic microsite hero."})]}),e.jsx(Me,{children:te?e.jsx(nzt,{photos:i.photos??[],uploading:b,onUpload:Y,onRemove:ae=>y.mutate({photoId:ae,listingId:i.id}),onReorder:ae=>v.mutate({photos:ae.map(le=>({id:le.id,sort_order:le.sort_order,is_primary:le.is_primary}))}),onSetPrimary:ae=>g.mutate({photoId:ae,listingId:i.id})}):e.jsxs("div",{className:"grid grid-cols-2 gap-3 md:grid-cols-4",children:[(i.photos??[]).map(ae=>e.jsx("img",{src:ae.photo_url,alt:ie,className:"aspect-[4/3] w-full rounded-lg object-cover",loading:"lazy"},ae.id)),!(i.photos??[]).length&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No photos yet."})]})})]}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-4",children:[{icon:sl,title:"Property microsite",body:"Institutional-grade public page with gated OM.",action:()=>window.open($,"_blank"),cta:"Preview"},{icon:Hf,title:"Signage QR",body:"On-site sign that routes to the microsite.",action:()=>P(!0),cta:"Create"},...te?[{icon:ln,title:"Broker & investor email",body:"Send to targeted segments of your database.",action:()=>I(!0),cta:"Compose"},{icon:un,title:"Social & LinkedIn",body:"Branded launch graphics and copy.",action:()=>O(!0),cta:"Generate"}]:[]].map(ae=>e.jsxs(ve,{className:"flex flex-col",children:[e.jsxs(bt,{className:"pb-3",children:[e.jsx(ae.icon,{className:"mb-2 h-5 w-5"}),e.jsx(St,{className:"text-sm",children:ae.title}),e.jsx(kn,{className:"text-xs",children:ae.body})]}),e.jsx(Me,{className:"mt-auto",children:e.jsx(B,{size:"sm",variant:"outline",className:"w-full",onClick:ae.action,children:ae.cta})})]},ae.title))})]}),te&&e.jsx(Gt,{value:"investors",children:e.jsx(kBs,{listingId:i.id})}),te&&e.jsx(Gt,{value:"reporting",children:e.jsx(CBs,{listing:i})}),te&&e.jsx(Gt,{value:"documents",children:e.jsx(jBs,{listingId:i.id})}),te&&e.jsx(Gt,{value:"settings",className:"space-y-6",children:e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsx(St,{className:"text-base",children:"Visibility"}),e.jsx(kn,{children:"Control who can see this offering."})]}),e.jsxs(Me,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Publish public microsite"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Makes the commercial microsite live at a shareable URL."})]}),e.jsx(fn,{checked:!!i.is_public,onCheckedChange:ae=>{p.mutate({listingId:i.id,values:{is_public:ae,allow_sharing:ae?!0:i.allow_sharing}}),ae&&ne==="won"&&m.mutate({listingId:i.id,stage:"launched"})}})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Share inside my brokerage"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Visible to agents in your brokerage on the Exchange."})]}),e.jsx(fn,{checked:!!i.share_with_brokerage,onCheckedChange:ae=>p.mutate({listingId:i.id,values:{share_with_brokerage:ae}})})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Confidential offering"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Teaser mode, address hidden, search engines blocked."})]}),e.jsx(fn,{checked:!!(o!=null&&o.is_confidential),onCheckedChange:ae=>h.mutate({listingId:i.id,values:{is_confidential:ae}})})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Hide street address"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show city / submarket only."})]}),e.jsx(fn,{checked:!!(o!=null&&o.hide_address),onCheckedChange:ae=>h.mutate({listingId:i.id,values:{hide_address:ae}})})]}),$&&e.jsxs("div",{className:"flex items-center gap-2 rounded-lg border bg-muted/40 px-3 py-2",children:[e.jsx("span",{className:"truncate text-xs text-muted-foreground",children:$}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{navigator.clipboard.writeText($),se.success("Copied")},children:e.jsx(Ia,{className:"h-3.5 w-3.5"})})]})]})]})})]})}),e.jsx(aLe,{open:S,onOpenChange:C,listingId:i.id,listingSlug:i.slug,listingTitle:ie,isCommercial:!0}),e.jsx(fzt,{open:E,onOpenChange:P,url:$,title:ie,fileBase:i.slug||i.id}),e.jsx(Szt,{open:M,onOpenChange:I,listing:i}),e.jsx(met,{open:D,onOpenChange:O,listingId:i.id})]})}):Z?e.jsx(zs,{title:"Commercial Launch",children:e.jsx("div",{className:"flex min-h-[50vh] items-center justify-center text-muted-foreground",children:"This opportunity is private to the listing agent."})}):e.jsx(ABs,{listing:i,details:o,publicUrl:$})}function TBs(){var m,p,f;const{token:s=""}=Li(),{data:t,isLoading:n,error:r}=at({queryKey:["commercial-pitch-preview",s],queryFn:async()=>{const{data:y,error:v}=await q.functions.invoke("commercial-pitch-preview",{body:{token:s}});if(v)throw v;if(y!=null&&y.error)throw new Error(y.error);return y},enabled:!!s});if(n)return e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-[#0b0f14]",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-2 border-white/20 border-t-white/70"})});if(r||!(t!=null&&t.listing))return e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-[#0b0f14] px-6 text-center text-white/60",children:"This preview link is no longer active."});const{listing:a,details:i,pitch:l}=t,o=a.agent,c=(p=(m=a.photos)==null?void 0:m[0])==null?void 0:p.photo_url,d=hJe(i).slice(0,4),u=l.launch_plan??[],h=[{icon:sl,label:"Dedicated property microsite",detail:"An institutional-grade page built for this asset alone."},{icon:Fr,label:"Offering Memorandum & teaser",detail:"Gated, tracked and released only to qualified prospects."},{icon:ln,label:"Targeted broker & investor email",detail:"Direct outreach to buyers, brokers and 1031 capital."},{icon:Hf,label:"Signage, QR & social distribution",detail:"On-site and digital presence working together."},{icon:bl,label:"Weekly owner activity reporting",detail:"Views, OM requests, downloads, tours and prospect interest."},{icon:Dm,label:"Confidentiality controls",detail:"Address, financials and documents released on your terms."}];return e.jsxs("div",{className:"min-h-screen bg-[#0b0f14] text-white antialiased",children:[e.jsxs(ul,{children:[e.jsxs("title",{children:["Marketing proposal — ",cP(a,i)]}),e.jsx("meta",{name:"robots",content:"noindex,nofollow"})]}),e.jsxs("section",{className:"relative min-h-[70vh] overflow-hidden",children:[c?e.jsx("img",{src:c,alt:"",className:"absolute inset-0 h-full w-full object-cover"}):e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-[#12202b] to-[#0b0f14]"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-[#0b0f14] via-[#0b0f14]/70 to-[#0b0f14]/40"}),e.jsxs("div",{className:"relative mx-auto flex min-h-[70vh] max-w-6xl flex-col justify-end px-6 pb-14 pt-24 md:px-10",children:[e.jsxs("p",{className:"text-[10px] font-semibold uppercase tracking-[0.24em] text-white/45",children:["Private marketing proposal",l.owner_name?` prepared for ${l.owner_name}`:""]}),e.jsx("h1",{className:"mt-4 max-w-3xl font-serif text-4xl leading-[1.05] md:text-6xl",children:cP(a,i)}),e.jsxs("p",{className:"mt-4 flex items-center gap-2 text-sm uppercase tracking-[0.2em] text-white/55",children:[e.jsx(Xa,{className:"h-4 w-4"})," ",Wre(a,i)]}),e.jsxs("div",{className:"mt-6 flex flex-wrap gap-2.5",children:[e.jsx("span",{className:"rounded-full border border-white/25 px-3.5 py-1 text-[10px] font-semibold uppercase tracking-[0.22em]",children:DP[(i==null?void 0:i.deal_type)??"sale"]}),(i==null?void 0:i.commercial_type)&&e.jsx("span",{className:"rounded-full border border-white/15 bg-white/5 px-3.5 py-1 text-[10px] font-semibold uppercase tracking-[0.22em] text-white/70",children:hL[i.commercial_type]})]})]})]}),d.length>0&&e.jsx("div",{className:"grid grid-cols-2 gap-px border-y border-white/10 bg-white/10 md:grid-cols-4",children:d.map(y=>e.jsxs("div",{className:"bg-[#0b0f14] px-6 py-7",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.2em] text-white/40",children:y.label}),e.jsx("p",{className:"mt-2 text-2xl font-semibold tabular-nums",children:y.value})]},y.label))}),(l.positioning||l.pricing_strategy)&&e.jsxs("section",{className:"mx-auto max-w-6xl px-6 py-20 md:px-10",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.24em] text-white/40",children:"Recommendation"}),e.jsx("h2",{className:"mt-3 font-serif text-3xl md:text-4xl",children:"How we take this asset to market"}),e.jsxs("div",{className:"mt-10 grid gap-10 md:grid-cols-2",children:[l.positioning&&e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold uppercase tracking-[0.16em] text-white/50",children:"Positioning"}),e.jsx("p",{className:"mt-4 whitespace-pre-line text-lg leading-relaxed text-white/75",children:l.positioning})]}),l.pricing_strategy&&e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold uppercase tracking-[0.16em] text-white/50",children:"Pricing strategy"}),e.jsx("p",{className:"mt-4 whitespace-pre-line text-lg leading-relaxed text-white/75",children:l.pricing_strategy}),e.jsx("p",{className:"mt-6 text-2xl font-semibold",children:EH(i,a.price)})]})]})]}),u.length>0&&e.jsx("section",{className:"border-t border-white/10",children:e.jsxs("div",{className:"mx-auto max-w-6xl px-6 py-20 md:px-10",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.24em] text-white/40",children:"The plan"}),e.jsx("h2",{className:"mt-3 font-serif text-3xl md:text-4xl",children:"What happens the day you hire us"}),e.jsx("div",{className:"mt-12 space-y-8",children:u.map((y,v)=>e.jsxs("div",{className:"flex gap-6 border-t border-white/10 pt-6",children:[e.jsx("span",{className:"font-serif text-2xl text-white/25 tabular-nums",children:String(v+1).padStart(2,"0")}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-medium",children:y.label}),y.detail&&e.jsx("p",{className:"mt-1.5 text-white/60",children:y.detail})]})]},v))})]})}),e.jsx("section",{className:"border-t border-white/10",children:e.jsxs("div",{className:"mx-auto max-w-6xl px-6 py-20 md:px-10",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.24em] text-white/40",children:"Distribution"}),e.jsx("h2",{className:"mt-3 font-serif text-3xl md:text-4xl",children:"Where your property shows up"}),e.jsx("div",{className:"mt-12 grid gap-4 md:grid-cols-3",children:h.map(y=>e.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/[0.03] p-7",children:[e.jsx(y.icon,{className:"mb-4 h-5 w-5 text-white/70"}),e.jsx("p",{className:"font-medium",children:y.label}),e.jsx("p",{className:"mt-1.5 text-sm text-white/55",children:y.detail})]},y.label))})]})}),o&&e.jsx("section",{className:"border-t border-white/10 bg-white/[0.02]",children:e.jsxs("div",{className:"mx-auto flex max-w-6xl flex-col items-start gap-6 px-6 py-16 md:flex-row md:items-center md:justify-between md:px-10",children:[e.jsxs("div",{className:"flex items-center gap-5",children:[o.avatar_url&&e.jsx("img",{src:o.avatar_url,alt:o.name,className:"h-20 w-20 rounded-full object-cover ring-1 ring-white/15"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.22em] text-white/40",children:"Prepared by"}),e.jsx("p",{className:"mt-2 font-serif text-2xl",children:o.name}),e.jsx("p",{className:"text-sm text-white/55",children:((f=o.brokerage)==null?void 0:f.name)||o.brokerage_name})]})]}),e.jsxs("div",{className:"flex gap-3 text-sm text-white/70",children:[o.email&&e.jsx("a",{className:"rounded-full border border-white/20 px-5 py-2 hover:bg-white/10",href:`mailto:${o.email}`,children:"Email"}),o.phone&&e.jsx("a",{className:"rounded-full border border-white/20 px-5 py-2 hover:bg-white/10",href:`tel:${o.phone}`,children:"Call"})]})]})}),e.jsx("footer",{className:"py-10 text-center text-xs text-white/35",children:"Confidential — prepared exclusively for the property owner."})]})}const MBs={office_exclusive:"Office Exclusive",coming_soon:"Coming Soon",pre_market:"Pre-Market",active:"Active"},PBs=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s||0);function LBs(){var ae;const[s]=Yl(),t=s.get("r"),n=s.get("m"),[r,a]=_.useState(null),[i,l]=_.useState(null),[o,c]=_.useState(!0),[d,u]=_.useState(0),[h,m]=_.useState(!1),[p,f]=_.useState(""),[y,v]=_.useState(""),[g,b]=_.useState(""),[j,S]=_.useState(""),[C,E]=_.useState("tour"),[P,M]=_.useState(!1),[I,D]=_.useState(!1),O=async()=>{if(!p.trim()||!y.trim()){se.error("Please enter your name and email");return}M(!0);try{const be=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:y.trim(),phone:g.trim()||null,message:j.trim()||null,intent:C})}),me=await be.json();if(!be.ok||!(me!=null&&me.success))throw new Error((me==null?void 0:me.error)||"Could not send");D(!0),se.success("Sent! The agent will be in touch shortly.")}catch(le){se.error((le==null?void 0:le.message)||"Could not send")}finally{M(!1)}};if(_.useEffect(()=>{if(!t||!n){l("Invalid link"),c(!1);return}const le=`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/private-listing-view?r=${encodeURIComponent(t)}&m=${encodeURIComponent(n)}`;fetch(le).then(be=>be.json()).then(be=>{be.error?l("This private listing link is no longer valid."):a({listing:be.listing,agent:be.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(ec,{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:V,agent:G}=r,$=(ae=V.photos)!=null&&ae.length?V.photos:[],H=$[0],Y=MBs[V.status]||V.status,Z=(G==null?void 0:G.sender_name)||(G==null?void 0:G.name)||"Your Agent",ne=(G==null?void 0:G.sender_email)||null,ce=encodeURIComponent(`Interested in ${V.address}`),ie=encodeURIComponent(`Hi ${Z}, I'd love to learn more about ${V.address}, ${V.city}. Thanks!`),te=G!=null&&G.booking_slug?`https://dashboard.relevelup.com/book/${G.booking_slug}`:null;return e.jsxs(e.Fragment,{children:[e.jsxs(ul,{children:[e.jsxs("title",{children:["Private Listing · ",V.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(ec,{className:"h-3.5 w-3.5"}),e.jsxs("span",{className:"font-medium tracking-wide uppercase",children:["Private listing · Shared by ",Z]})]}),e.jsxs("div",{className:"relative",children:[H?e.jsx("button",{type:"button",className:"block w-full",onClick:()=>{u(0),m(!0)},children:e.jsx("img",{src:H,alt:V.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(Oe,{className:"bg-indigo-600 text-white border-0 text-xs px-2.5 py-1 shadow",children:Y})}),$.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:[$.length," photos"]})]}),e.jsxs("div",{className:"max-w-5xl mx-auto px-4 sm:px-6 -mt-10 relative z-10",children:[e.jsx(ve,{className:"shadow-xl border-slate-200",children:e.jsxs(Me,{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:V.address}),e.jsxs("p",{className:"text-slate-600 mt-1 flex items-center gap-1.5",children:[e.jsx(Xa,{className:"h-4 w-4"}),V.city,", ",V.state," ",V.zip]})]}),e.jsx("div",{className:"text-right",children:e.jsx("p",{className:"text-3xl sm:text-4xl font-bold text-indigo-600",children:PBs(V.price)})})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3 mt-6",children:[V.bedrooms?e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3 text-center",children:[e.jsx(dj,{className:"h-5 w-5 mx-auto text-slate-500 mb-1"}),e.jsx("p",{className:"text-lg font-semibold text-slate-900",children:V.bedrooms}),e.jsx("p",{className:"text-xs text-slate-500",children:"Beds"})]}):null,V.bathrooms?e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3 text-center",children:[e.jsx(S0,{className:"h-5 w-5 mx-auto text-slate-500 mb-1"}),e.jsx("p",{className:"text-lg font-semibold text-slate-900",children:V.bathrooms}),e.jsx("p",{className:"text-xs text-slate-500",children:"Baths"})]}):null,V.sqft?e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3 text-center",children:[e.jsx(wb,{className:"h-5 w-5 mx-auto text-slate-500 mb-1"}),e.jsx("p",{className:"text-lg font-semibold text-slate-900",children:V.sqft.toLocaleString()}),e.jsx("p",{className:"text-xs text-slate-500",children:"Sq Ft"})]}):null]}),V.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:V.description})]}),$.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:$.slice(0,9).map((le,be)=>e.jsx("button",{type:"button",onClick:()=>{u(be),m(!0)},className:"aspect-[4/3] overflow-hidden rounded-lg bg-slate-100",children:e.jsx("img",{src:le,alt:"",className:"w-full h-full object-cover hover:scale-105 transition"})},be))})]})]})}),e.jsxs(ve,{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:[Z," will get back to you personally."]})]}),e.jsx(Me,{className:"p-6 sm:p-8",children:I?e.jsxs("div",{className:"flex flex-col items-center text-center py-6",children:[e.jsx(Er,{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:[Z," 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(le=>e.jsx("button",{type:"button",onClick:()=>E(le.id),className:`px-3 py-2 rounded-lg border text-sm font-medium transition ${C===le.id?"bg-indigo-600 text-white border-indigo-600":"bg-white text-slate-700 border-slate-200 hover:border-indigo-300"}`,children:le.label},le.id))}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(J,{htmlFor:"pl-name",children:"Your name *"}),e.jsx(xe,{id:"pl-name",value:p,onChange:le=>f(le.target.value),placeholder:"Jane Doe",maxLength:120})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"pl-email",children:"Email *"}),e.jsx(xe,{id:"pl-email",type:"email",value:y,onChange:le=>v(le.target.value),placeholder:"you@email.com",maxLength:255})]})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"pl-phone",children:"Phone (optional)"}),e.jsx(xe,{id:"pl-phone",value:g,onChange:le=>b(le.target.value),placeholder:"(555) 555-5555",maxLength:40})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"pl-msg",children:"Message (optional)"}),e.jsx(Ms,{id:"pl-msg",value:j,onChange:le=>S(le.target.value),placeholder:`I'd love to see ${V.address}…`,rows:4,maxLength:2e3})]}),e.jsx(B,{onClick:O,disabled:P,className:"w-full bg-indigo-600 hover:bg-indigo-700 h-11 text-base",children:P?"Sending…":"Send to "+Z.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(ve,{className:"mt-6 mb-12 shadow-lg border-slate-200",children:e.jsxs(Me,{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:[G!=null&&G.avatar_url?e.jsx("img",{src:G.avatar_url,alt:Z,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:Z.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:Z}),(G==null?void 0:G.brokerage_name)&&e.jsx("p",{className:"text-slate-600 text-sm",children:G.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:[ne&&e.jsx(B,{asChild:!0,className:"bg-indigo-600 hover:bg-indigo-700",children:e.jsxs("a",{href:`mailto:${ne}?subject=${ce}&body=${ie}`,children:[e.jsx(ln,{className:"h-4 w-4 mr-1.5"}),"Email"]})}),(G==null?void 0:G.phone)&&e.jsx(B,{asChild:!0,variant:"outline",children:e.jsxs("a",{href:`tel:${G.phone}`,children:[e.jsx(_a,{className:"h-4 w-4 mr-1.5"}),G.phone]})}),te&&e.jsx(B,{asChild:!0,variant:"outline",children:e.jsxs("a",{href:te,target:"_blank",rel:"noreferrer",children:[e.jsx(Qd,{className:"h-4 w-4 mr-1.5"}),"Book a tour"]})})]})]})})]}),h&&$.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(Qn,{className:"h-6 w-6"})}),e.jsx("button",{className:"absolute left-4 text-white p-2 hover:bg-white/10 rounded-full",onClick:()=>u(le=>(le-1+$.length)%$.length),"aria-label":"Previous",children:e.jsx($c,{className:"h-8 w-8"})}),e.jsx("img",{src:$[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(le=>(le+1)%$.length),"aria-label":"Next",children:e.jsx(xi,{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," / ",$.length]})]})]})]})}function IBs(){var i;const{slug:s}=Li(),{data:t,isLoading:n,error:r}=EFt(s);if(_.useEffect(()=>(document.body.classList.add("agent-card-page"),()=>{document.body.classList.remove("agent-card-page")}),[]),_.useEffect(()=>{t!=null&&t.id&&Dd(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(cn,{className:"h-28 w-28 rounded-full"}),e.jsx(cn,{className:"h-6 w-48"}),e.jsx(cn,{className:"h-4 w-36"})]}),e.jsx(cn,{className:"h-12 w-full"}),e.jsx(cn,{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(pJe,{card:t})]})}const DBs="https://images.unsplash.com/photo-1507525428034-b723cf961d3e?w=1600&q=80",RBs="https://images.unsplash.com/photo-1616486338812-3dadae4b4ace?w=1600&q=80",FBs="https://images.unsplash.com/photo-1500534314209-a25ddb2bd429?w=1600&q=80",OBs="https://images.unsplash.com/photo-1600585154340-be6161a56a0c?w=1600&q=80",zBs="https://images.unsplash.com/photo-1519741497674-611481863552?w=1600&q=80",BBs="https://images.unsplash.com/photo-1494526585095-c41746248156?w=1600&q=80",F4e={"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:BBs},"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:DBs},"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:RBs},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:FBs},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:OBs},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:zBs}},UBs=["#111111","#2f7a7d","#c9a84c","#d84a7a","#3b6fa0","#9b72cf","#e85d3a","#4a6741"];function Czt(s){return s&&s in F4e?F4e[s]:F4e["minimal-mono"]}function qBs(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 Azt({slugOverride:s}={}){var ar;const{slug:t}=Li(),n=s||t,[r]=Yl(),a=r.get("t"),[i,l]=_.useState(!0),[o,c]=_.useState(null),[d,u]=_.useState(null),h=_.useRef(null),m=_.useRef(null),[p,f]=_.useState(null),[y,v]=_.useState(null),[g,b]=_.useState(!1),[j,S]=_.useState(!1),[C,E]=_.useState(0),[P,M]=_.useState(!1),[I,D]=_.useState(""),[O,V]=_.useState(""),[G,$]=_.useState(""),[H,Y]=_.useState(""),[Z,ne]=_.useState(""),[ce,ie]=_.useState(""),[te,ae]=_.useState(""),[le,be]=_.useState(""),[me,he]=_.useState(""),[pe,Ce]=_.useState(""),[Ae,Pe]=_.useState(""),[ze,ke]=_.useState(""),[Ze,Se]=_.useState(""),[Fe,Ne]=_.useState([]),[Ye,Ve]=_.useState([]),[qe,Qe]=_.useState(""),[Ue,Xe]=_.useState(""),[nt,$e]=_.useState(""),[Ge,ct]=_.useState([]);_.useEffect(()=>{xt()},[n,a]);const xt=async()=>{if(!n)return;l(!0);const{data:Dn,error:Ur}=await q.from("contact_intake_pages").select("*").eq("slug",n).eq("is_active",!0).maybeSingle();if(Ur||!Dn){M(!0),l(!1);return}u(Dn),m.current=Dn;const{data:Vs}=await q.from("profiles").select("name, avatar_url, title, phone, email, brokerage_id").eq("id",Dn.user_id).single();if(Vs){let hn;if(Vs.brokerage_id){const{data:Yn}=await q.from("brokerages").select("name").eq("id",Vs.brokerage_id).single();hn=(Yn==null?void 0:Yn.name)||void 0}let dr=Vs.avatar_url||null;if(!dr){const{data:Yn}=q.storage.from("avatars").getPublicUrl(`${Dn.user_id}/avatar.jpg`);Yn!=null&&Yn.publicUrl&&(dr=`${Yn.publicUrl}?t=${Date.now()}`)}const Cn={...Vs,avatar_url:dr,brokerage_name:hn};c(Cn),h.current=Cn}if(a)try{console.log("[ConnectPage] Resolving token:",a,"for page:",Dn.id);const{data:hn,error:dr}=await q.functions.invoke("process-intake-submissions",{body:{action:"resolve_token",token:a,page_id:Dn.id}});if(console.log("[ConnectPage] Resolve result:",{resolved:hn,resolveErr:dr}),!dr&&(hn!=null&&hn.contact_id)){v(hn.contact_id);const Cn=hn.contact;Cn&&(f(Cn),D(Cn.first_name||""),V(Cn.last_name||""),$(Cn.email||""),Y(Cn.phone||""),ne(Cn.address||""),ie(Cn.city||""),ae(Cn.state||""),be(Cn.zip||""),he(Cn.birthday||""),Ce(Cn.home_anniversary||""))}}catch(hn){console.error("Failed to resolve token:",hn)}l(!1)},qt=async()=>{var Dn,Ur;if(!I.trim()){se.error("Please enter your first name");return}if(!n){se.error("Invalid page. Please refresh.");return}S(!0);try{let Vs=(Dn=m.current)==null?void 0:Dn.id,hn=(Ur=m.current)==null?void 0:Ur.user_id;if(!Vs||!hn){const{data:Yn}=await q.from("contact_intake_pages").select("id, user_id").eq("slug",n).eq("is_active",!0).maybeSingle();if(!Yn){se.error("This page is no longer active. Please contact the agent directly."),S(!1);return}Vs=Yn.id,hn=Yn.user_id}const dr={intake_page_id:Vs,agent_user_id:hn,existing_contact_id:y,first_name:I.trim(),last_name:O.trim()||null,email:G.trim()||null,phone:H.trim()||null,address:Z.trim()||null,city:ce.trim()||null,state:te.trim()||null,zip:le.trim()||null,birthday:me||null,home_anniversary:pe||null,real_estate_interest:Ae||null,message:ze.trim()||null,life_events:{spouse_name:Ze.trim()||null,kids:Fe.filter(Yn=>Yn.name.trim()),pets:Ye.filter(Yn=>Yn.name.trim()),favorite_spots:qe.trim()||null,dream_neighborhood:Ue.trim()||null,wedding_anniversary:nt||null},referrals:Ge.filter(Yn=>Yn.name.trim()&&Yn.contact.trim())},{error:Cn}=await q.from("contact_intake_submissions").insert(dr);if(console.log("[ConnectPage] Insert result:",{error:Cn}),Cn)throw Cn;a&&await q.from("contact_intake_tokens").update({used_at:new Date().toISOString()}).eq("token",a);try{const Yn=[I.trim(),O.trim()].filter(Boolean).join(" ");await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/connect-page-notify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agentUserId:hn,contactName:Yn,contactEmail:G.trim()||null,contactPhone:H.trim()||null,slug:n})})}catch(Yn){console.warn("Connect page notification failed (non-blocking):",Yn)}b(!0)}catch(Vs){console.error(Vs),se.error("Something went wrong. Please try again.")}finally{S(!1)}};if(i)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 via-white to-blue-50",children:e.jsx(Ct,{className:"h-8 w-8 animate-spin text-slate-400"})});if(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(g)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(Sr.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(Sr.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(Er,{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(Do,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Powered by ReLevelUp"})]})]})]});const Vt=!!a&&!!p,Xt=(d==null?void 0:d.show_little_things)??!0,fs=[{title:Vt?"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:Dn=>D(Dn.target.value),placeholder:"Jane",className:"connect-input",required:!0})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Last Name"}),e.jsx("input",{type:"text",value:O,onChange:Dn=>V(Dn.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:G,onChange:Dn=>$(Dn.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:H,onChange:Dn=>Y(Dn.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:Z,onChange:Dn=>ne(Dn.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:ce,onChange:Dn=>ie(Dn.target.value),placeholder:"Austin",className:"connect-input"})]}),e.jsxs("div",{className:"col-span-1",children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"State"}),e.jsx("input",{type:"text",value:te,onChange:Dn=>ae(Dn.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:le,onChange:Dn=>be(Dn.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:me,onChange:Dn=>he(Dn.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:pe,onChange:Dn=>Ce(Dn.target.value),className:"connect-input"})]})]})]})},...Xt?[{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:Ze,onChange:Dn=>Se(Dn.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:nt,onChange:Dn=>$e(Dn.target.value),className:"connect-input"})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[e.jsx("label",{className:"block text-sm font-medium",style:{color:"var(--c-text-muted)"},children:"Kids"}),e.jsxs("button",{type:"button",onClick:()=>Ne(Dn=>[...Dn,{name:"",age:""}]),className:"text-xs inline-flex items-center gap-1",style:{color:"var(--c-accent)"},children:[e.jsx(rn,{className:"h-3 w-3"})," Add"]})]}),e.jsxs("div",{className:"space-y-2",children:[Fe.length===0&&e.jsx("p",{className:"text-xs",style:{color:"var(--c-text-muted)"},children:"None to add? Skip this."}),Fe.map((Dn,Ur)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("input",{type:"text",value:Dn.name,onChange:Vs=>Ne(hn=>hn.map((dr,Cn)=>Cn===Ur?{...dr,name:Vs.target.value}:dr)),placeholder:"Child's name",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),e.jsx("input",{type:"text",value:Dn.age,onChange:Vs=>Ne(hn=>hn.map((dr,Cn)=>Cn===Ur?{...dr,age:Vs.target.value}:dr)),placeholder:"Age",className:"connect-input shrink-0",style:{width:"5rem"}}),e.jsx("button",{type:"button",onClick:()=>Ne(Vs=>Vs.filter((hn,dr)=>dr!==Ur)),className:"p-2 rounded-md hover:bg-black/5 shrink-0","aria-label":"Remove",children:e.jsx(Qn,{className:"h-3.5 w-3.5",style:{color:"var(--c-text-muted)"}})})]},Ur))]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[e.jsx("label",{className:"block text-sm font-medium",style:{color:"var(--c-text-muted)"},children:"Pets"}),e.jsxs("button",{type:"button",onClick:()=>Ve(Dn=>[...Dn,{name:"",kind:""}]),className:"text-xs inline-flex items-center gap-1",style:{color:"var(--c-accent)"},children:[e.jsx(rn,{className:"h-3 w-3"})," Add"]})]}),e.jsxs("div",{className:"space-y-2",children:[Ye.length===0&&e.jsx("p",{className:"text-xs",style:{color:"var(--c-text-muted)"},children:"None to add? Skip this."}),Ye.map((Dn,Ur)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("input",{type:"text",value:Dn.name,onChange:Vs=>Ve(hn=>hn.map((dr,Cn)=>Cn===Ur?{...dr,name:Vs.target.value}:dr)),placeholder:"Pet's name",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),e.jsx("input",{type:"text",value:Dn.kind,onChange:Vs=>Ve(hn=>hn.map((dr,Cn)=>Cn===Ur?{...dr,kind:Vs.target.value}:dr)),placeholder:"Dog, cat…",className:"connect-input shrink-0",style:{width:"7rem"}}),e.jsx("button",{type:"button",onClick:()=>Ve(Vs=>Vs.filter((hn,dr)=>dr!==Ur)),className:"p-2 rounded-md hover:bg-black/5 shrink-0","aria-label":"Remove",children:e.jsx(Qn,{className:"h-3.5 w-3.5",style:{color:"var(--c-text-muted)"}})})]},Ur))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Favorite local spots"}),e.jsx("input",{type:"text",value:qe,onChange:Dn=>Qe(Dn.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:Dn=>Xe(Dn.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."})]}),Ge.length<3&&e.jsxs("button",{type:"button",onClick:()=>ct(Dn=>[...Dn,{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(rn,{className:"h-3 w-3"})," Add"]})]}),e.jsx("div",{className:"space-y-2",children:Ge.map((Dn,Ur)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("input",{type:"text",value:Dn.name,onChange:Vs=>ct(hn=>hn.map((dr,Cn)=>Cn===Ur?{...dr,name:Vs.target.value}:dr)),placeholder:"Their name",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),e.jsx("input",{type:"text",value:Dn.contact,onChange:Vs=>ct(hn=>hn.map((dr,Cn)=>Cn===Ur?{...dr,contact:Vs.target.value}:dr)),placeholder:"Phone or email",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),e.jsx("button",{type:"button",onClick:()=>ct(Vs=>Vs.filter((hn,dr)=>dr!==Ur)),className:"p-2 rounded-md hover:bg-black/5","aria-label":"Remove",children:e.jsx(Qn,{className:"h-3.5 w-3.5",style:{color:"var(--c-text-muted)"}})})]},Ur))})]})]})}]:[],{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(Dn=>e.jsxs("button",{type:"button",onClick:()=>Pe(Ae===Dn.value?"":Dn.value),className:`p-3.5 rounded-xl border-2 text-left transition-all ${Ae===Dn.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:Dn.label}),e.jsx("span",{className:"block text-xs text-slate-500 mt-0.5",children:Dn.desc})]},Dn.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:Dn=>ke(Dn.target.value),placeholder:"Feel free to drop a note...",rows:3,className:"connect-input resize-none"})]})]})}],Ft=fs.length,wt=Czt(d==null?void 0:d.theme),Ts=qBs(wt,(d==null?void 0:d.accent_color)||null),vt=(d==null?void 0:d.cover_image_url)||wt.defaultCover,$s=(d==null?void 0:d.headline)||"Let's stay connected",As=(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)||""),jn=["deep-luxe"].includes((d==null?void 0:d.theme)||"");return e.jsxs("div",{className:"min-h-screen connect-shell",style:Ts,children:[e.jsxs(ul,{children:[e.jsxs("title",{children:["Connect with ",(o==null?void 0:o.name)||"Agent"]}),e.jsx("meta",{name:"description",content:`${$s} — ${(o==null?void 0:o.name)||"your agent"}`}),vt&&e.jsx("meta",{property:"og:image",content:vt}),e.jsx("meta",{property:"og:title",content:`Connect with ${(o==null?void 0:o.name)||"me"}`}),e.jsx("meta",{property:"og:description",content:$s}),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(Sr.img,{src:vt,alt:"",initial:{scale:1.08},animate:{scale:1},transition:{duration:1.4,ease:"easeOut"},className:"absolute inset-0 w-full h-full object-cover"}),e.jsx("div",{className:"absolute inset-0",style:{background:"linear-gradient(180deg, rgba(0,0,0,0) 20%, rgba(0,0,0,0.55) 100%)"}}),e.jsxs("div",{className:"absolute inset-x-0 bottom-0 p-6 pb-16 text-center",children:[e.jsx(Sr.h1,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{delay:.15,duration:.6},style:{color:"#fff",fontFamily:wt.headingFont,fontWeight:500,letterSpacing:"-0.01em"},className:"text-3xl sm:text-4xl leading-tight",children:$s}),As&&e.jsx(Sr.p,{initial:{opacity:0},animate:{opacity:.9},transition:{delay:.35,duration:.6},style:{color:"#fff"},className:"text-sm mt-2",children:As})]})]}),e.jsxs("div",{className:"max-w-lg mx-auto px-4 pb-12 -mt-12 relative",children:[e.jsxs(Sr.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:wt.accent,color:wt.accentText,border:"4px solid var(--c-surface)"},children:e.jsx("span",{className:"text-3xl font-bold",children:((ar=o==null?void 0:o.name)==null?void 0:ar.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(_a,{className:"h-4 w-4"})}),(o==null?void 0:o.email)&&e.jsx("a",{href:`mailto:${o.email}`,className:"flex items-center justify-center w-10 h-10 rounded-full transition-opacity hover:opacity-80",style:{background:"color-mix(in srgb, var(--c-accent) 12%, transparent)",color:"var(--c-accent)"},"aria-label":"Email agent",children:e.jsx(ln,{className:"h-4 w-4"})})]})]}),e.jsx(Sr.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:Ft}).map((Dn,Ur)=>e.jsx("div",{className:"h-1 flex-1 rounded-full transition-all duration-500",style:{background:Ur<=C?"var(--c-accent)":"color-mix(in srgb, var(--c-text) 12%, transparent)"}},Ur))}),e.jsxs(Sr.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:jn?"0 20px 40px -20px rgba(0,0,0,0.5)":"0 20px 40px -20px rgba(0,0,0,0.15)"},children:[e.jsx(mW,{mode:"wait",children:e.jsxs(Sr.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(un,{className:"h-4 w-4",style:{color:"var(--c-accent)"}}),e.jsx("h2",{className:"text-lg font-semibold",style:{color:"var(--c-text)"},children:fs[C].title})]}),fs[C].subtitle&&e.jsx("p",{className:"text-xs mt-1 ml-6",style:{color:"var(--c-text-muted)"},children:fs[C].subtitle})]}),fs[C].fields]},C)}),e.jsxs("div",{className:"flex justify-between mt-8",children:[C>0?e.jsx("button",{type:"button",onClick:()=>E(Dn=>Dn-1),className:"px-5 py-2.5 text-sm font-medium transition-opacity hover:opacity-70",style:{color:"var(--c-text-muted)"},children:"Back"}):e.jsx("div",{}),C{if(C===0&&!I.trim()){se.error("Please enter your first name");return}E(Dn=>Dn+1)},className:"px-6 py-2.5 text-sm font-medium rounded-xl transition-transform hover:scale-[1.02] shadow-sm",style:{background:"var(--c-accent)",color:"var(--c-accent-text)"},children:"Continue"}):e.jsx("button",{type:"button",onClick:()=>qt(),disabled:j,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:j?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"h-4 w-4 animate-spin"}),"Sending..."]}):"Submit"})]}),C>0&&CE(Dn=>Dn+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(Do,{className:"h-3 w-3"}),e.jsx("span",{children:"Powered by ReLevelUp"})]})})]})]})}const bW=()=>({trackEngagement:_.useCallback(async(t,n,r,a="view")=>{try{const{data:{user:i}}=await q.auth.getUser();if(!i)return;await q.from("content_engagement_logs").insert({user_id:i.id,resource_type:t,resource_id:n,resource_title:r,action_type:a})}catch(i){console.error("Error tracking engagement:",i)}},[])});function VY({banners:s,autoPlayInterval:t=5e3,className:n}){const[r,a]=_.useState(0),[i,l]=_.useState(!1),{trackEngagement:o}=bW(),c=_.useCallback(p=>{o("newsletter",p.id,p.title,"click_link")},[o]),d=_.useCallback(()=>{a(p=>(p+1)%s.length)},[s.length]),u=_.useCallback(()=>{a(p=>(p-1+s.length)%s.length)},[s.length]),h=_.useCallback(p=>{a(p)},[]);if(_.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:At("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(B,{variant:"ghost",size:"icon",className:At("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($c,{className:"h-6 w-6"})}),e.jsx(B,{variant:"ghost",size:"icon",className:At("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(xi,{className:"h-6 w-6"})})]}),s.length>1&&e.jsx("div",{className:"absolute bottom-3 left-1/2 -translate-x-1/2 flex gap-2",children:s.map((p,f)=>e.jsx("button",{onClick:()=>h(f),className:At("w-2 h-2 rounded-full transition-all duration-300",f===r?"bg-white w-6":"bg-white/50 hover:bg-white/70"),"aria-label":`Go to slide ${f+1}`},f))})]}),e.jsxs("div",{className:"bg-foreground rounded-b-xl px-5 py-3 flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{className:"text-sm md:text-base font-semibold text-background truncate",children:m.title}),m.description&&e.jsx("p",{className:"text-xs text-background/70 truncate",children:m.description})]}),m.link_url&&e.jsx("a",{href:m.link_url,target:"_blank",rel:"noopener noreferrer",className:"shrink-0",onClick:()=>c(m),children:e.jsx(B,{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 $Bs=["reserved","scheduled_for_charge","paid","payment_failed","completed"],DH=s=>!!s&&(s.access_override||$Bs.includes(s.status)),Tf=(s,t="usd")=>new Intl.NumberFormat("en-US",{style:"currency",currency:t.toUpperCase(),maximumFractionDigits:s%100===0?0:2}).format(s/100),hte=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`},EVe=(s,t="usd",n)=>`One-time payment: ${Tf(s,t)} for the ${hte(n)}`,pet=[{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}],mte=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:[]}},VBs=(s,t)=>!s.hidden.includes(t),jgt=(s,t)=>s.required.includes(t)&&!s.hidden.includes(t),xu=(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,uLe=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&&rat({queryKey:["programs"],queryFn:async()=>{const{data:s,error:t}=await q.from("programs").select("*").eq("status","published").order("is_featured",{ascending:!1}).order("sort_order",{ascending:!0});if(t)throw t;return s||[]}}),fet=s=>at({queryKey:["program",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("programs").select("*").eq("slug",s).maybeSingle();if(n)throw n;return t||null}}),Tzt=s=>at({queryKey:["program-seats",s],enabled:!!s,refetchInterval:6e4,queryFn:async()=>{const{data:t,error:n}=await q.rpc("program_seats_remaining",{_program_id:s});if(n)throw n;return t??0}}),xet=()=>{const{user:s}=hs();return at({queryKey:["program-enrollments",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),queryFn:async()=>{const{data:t,error:n}=await q.from("program_enrollments").select("*").eq("user_id",s.id);if(n)throw n;return t||[]}})},get=s=>{const{data:t=[],...n}=xet();return{...n,data:s&&t.find(r=>r.program_id===s)||null}},HBs=()=>{const{user:s}=hs(),t=Bt();return mt({mutationFn:async n=>{const{data:r,error:a}=await q.from("program_intake_responses").upsert({...n,user_id:s.id},{onConflict:"program_id,user_id"}).select("*").single();if(a)throw a;return r},onSuccess:()=>t.invalidateQueries({queryKey:["program-intake"]}),onError:n=>se.error(n.message||"Could not save your answers")})},Mzt=s=>{const{user:t}=hs();return at({queryKey:["program-intake",s,t==null?void 0:t.id],enabled:!!s&&!!(t!=null&&t.id),queryFn:async()=>{const{data:n,error:r}=await q.from("program_intake_responses").select("*").eq("program_id",s).eq("user_id",t.id).maybeSingle();if(r)throw r;return n}})},GBs=()=>{const s=Bt();return mt({mutationFn:async t=>{const{data:n,error:r}=await q.rpc("program_claim_seat",{_program_id:t});if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["program-enrollments"]}),s.invalidateQueries({queryKey:["program-seats"]})}})},WBs=(s,t)=>{const{user:n}=hs(),r=t||(n==null?void 0:n.id);return at({queryKey:["program-workspace",s,r],enabled:!!s&&!!r,queryFn:async()=>{const a=r,[i,l,o,c,d,u,h,m,p,f,y]=await Promise.all([q.from("program_weeks").select("*").eq("program_id",s).order("week_number"),q.from("program_lessons").select("*").eq("program_id",s).order("sort_order"),q.from("program_resources").select("*").eq("program_id",s).order("sort_order"),q.from("program_events").select("*").eq("program_id",s).order("starts_at"),q.from("program_announcements").select("*").eq("program_id",s).order("published_at",{ascending:!1}),q.from("program_lesson_completions").select("*").eq("program_id",s).eq("user_id",a),q.from("program_weekly_progress").select("*").eq("program_id",s).eq("user_id",a).order("week_number"),q.from("program_video_logs").select("*").eq("program_id",s).eq("user_id",a).order("posted_at",{ascending:!1}),q.from("program_badge_awards").select("*").eq("program_id",s).eq("user_id",a),q.from("program_profile_analyses").select("*").eq("program_id",s).eq("user_id",a).maybeSingle(),q.from("program_member_resources").select("*").eq("program_id",s).eq("user_id",a).order("sort_order")]);return{weeks:i.data||[],lessons:l.data||[],resources:o.data||[],myResources:y.data||[],events:c.data||[],announcements:d.data||[],completions:u.data||[],progress:h.data||[],videoLogs:m.data||[],badges:p.data||[],analysis:f.data||null}}})},KBs=s=>{const{user:t}=hs(),n=Bt();return mt({mutationFn:async({lessonId:r,done:a})=>{if(a){const{error:i}=await q.from("program_lesson_completions").insert({lesson_id:r,program_id:s,user_id:t.id});if(i&&!i.message.includes("duplicate"))throw i}else{const{error:i}=await q.from("program_lesson_completions").delete().eq("lesson_id",r).eq("user_id",t.id);if(i)throw i}},onSuccess:()=>n.invalidateQueries({queryKey:["program-workspace"]}),onError:r=>se.error(r.message||"Could not update progress")})},YBs=s=>{const{user:t}=hs(),n=Bt();return mt({mutationFn:async r=>{const{error:a}=await q.from("program_video_logs").insert({...r,program_id:s,user_id:t.id});if(a)throw a},onSuccess:()=>{se.success("Video logged — nice work"),n.invalidateQueries({queryKey:["program-workspace"]})},onError:r=>se.error(r.message||"Could not log the video")})},ZBs=s=>{const{user:t}=hs(),n=Bt();return mt({mutationFn:async r=>{const{error:a}=await q.from("program_weekly_progress").upsert({...r,program_id:s,user_id:t.id},{onConflict:"program_id,user_id,week_number"});if(a)throw a},onSuccess:()=>{se.success("Weekly check-in saved"),n.invalidateQueries({queryKey:["program-workspace"]})},onError:r=>se.error(r.message||"Could not save your check-in")})},XBs=s=>{const{user:t}=hs(),n=Bt();return mt({mutationFn:async({eventId:r,optIn:a})=>{const{error:i}=await q.from("program_event_attendance").upsert({event_id:r,program_id:s,user_id:t.id,reminder_opt_in:a},{onConflict:"event_id,user_id"});if(i)throw i},onSuccess:()=>n.invalidateQueries({queryKey:["program-workspace"]}),onError:r=>se.error(r.message||"Could not update your RSVP")})},QBs=s=>at({queryKey:["program-discount-codes",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("program_discount_codes").select("*").eq("program_id",s).order("created_at",{ascending:!1});if(n)throw n;return t||[]}}),JBs=s=>{const t=Bt();return mt({mutationFn:async n=>{const r={program_id:s,code:(n.code||"").trim().toUpperCase(),label:n.label||null,percent_off:n.percent_off??null,amount_off_cents:n.amount_off_cents??null,max_redemptions:n.max_redemptions??null,starts_at:n.starts_at||null,expires_at:n.expires_at||null,is_active:n.is_active??!0};if(n.id){const{error:a}=await q.from("program_discount_codes").update(r).eq("id",n.id);if(a)throw a}else{const{error:a}=await q.from("program_discount_codes").insert(r);if(a)throw a}},onSuccess:()=>{se.success("Discount code saved"),t.invalidateQueries({queryKey:["program-discount-codes"]})},onError:n=>{var r;return se.error((r=n.message)!=null&&r.includes("duplicate")?"That code already exists for this program":n.message||"Could not save the code")}})},eUs=()=>{const s=Bt();return mt({mutationFn:async t=>{const{error:n}=await q.from("program_discount_codes").delete().eq("id",t);if(n)throw n},onSuccess:()=>{se.success("Discount code deleted"),s.invalidateQueries({queryKey:["program-discount-codes"]})},onError:t=>se.error(t.message||"Could not delete the code")})},tUs=()=>mt({mutationFn:async({enrollmentId:s,code:t})=>{const{data:n,error:r}=await q.rpc("program_apply_discount",{_enrollment_id:s,_code:t});if(r)throw r;const a=n;if(!(a!=null&&a.ok))throw new Error((a==null?void 0:a.error)||"That code could not be applied");return a}}),sUs=()=>mt({mutationFn:async s=>{const{error:t}=await q.rpc("program_clear_discount",{_enrollment_id:s});if(t)throw t}}),nUs=s=>at({queryKey:["admin-program-events",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("program_events").select("*").eq("program_id",s).order("starts_at",{ascending:!0});if(n)throw n;return t||[]}}),rUs=s=>{const t=Bt();return mt({mutationFn:async n=>{const r={program_id:s,title:(n.title||"").trim(),description:n.description||null,event_kind:n.event_kind||"mastermind",starts_at:n.starts_at,duration_minutes:n.duration_minutes??60,speaker:n.speaker||null,meeting_link:n.meeting_link||null,replay_url:n.replay_url||null,is_published:n.is_published??!0};if(n.id){const{error:a}=await q.from("program_events").update(r).eq("id",n.id);if(a)throw a}else{const{error:a}=await q.from("program_events").insert(r);if(a)throw a}},onSuccess:()=>{se.success("Session saved"),t.invalidateQueries({queryKey:["admin-program-events"]}),t.invalidateQueries({queryKey:["program-workspace"]})},onError:n=>se.error(n.message||"Could not save the session")})},aUs=()=>{const s=Bt();return mt({mutationFn:async t=>{const{error:n}=await q.from("program_events").delete().eq("id",t);if(n)throw n},onSuccess:()=>{se.success("Session removed"),s.invalidateQueries({queryKey:["admin-program-events"]}),s.invalidateQueries({queryKey:["program-workspace"]})},onError:t=>se.error(t.message||"Could not remove the session")})},iUs=s=>at({queryKey:["admin-program-lessons",s],enabled:!!s,queryFn:async()=>{const[t,n]=await Promise.all([q.from("program_lessons").select("*").eq("program_id",s).order("sort_order"),q.from("program_weeks").select("id, week_number, title").eq("program_id",s).order("week_number")]);if(t.error)throw t.error;return{lessons:t.data||[],weeks:n.data||[]}}}),oUs=s=>{const t=Bt();return mt({mutationFn:async n=>{const r={program_id:s,week_id:n.week_id||null,title:(n.title||"").trim(),summary:n.summary||null,duration_minutes:n.duration_minutes??null,video_url:n.video_url||null,worksheet_url:n.worksheet_url||null,action_assignment:n.action_assignment||null,status:n.status||"published",publish_at:n.publish_at||null,sort_order:n.sort_order??0};if(n.id){const{error:a}=await q.from("program_lessons").update(r).eq("id",n.id);if(a)throw a}else{const{error:a}=await q.from("program_lessons").insert(r);if(a)throw a}},onSuccess:()=>{se.success("Video saved"),t.invalidateQueries({queryKey:["admin-program-lessons"]}),t.invalidateQueries({queryKey:["program-workspace"]})},onError:n=>se.error(n.message||"Could not save the video")})},lUs=()=>{const s=Bt();return mt({mutationFn:async t=>{const{error:n}=await q.from("program_lessons").delete().eq("id",t);if(n)throw n},onSuccess:()=>{se.success("Video removed"),s.invalidateQueries({queryKey:["admin-program-lessons"]}),s.invalidateQueries({queryKey:["program-workspace"]})},onError:t=>se.error(t.message||"Could not remove the video")})},Pzt=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},EJ=s=>!!s&&/\.(mp4|webm|mov|m4v)(\?|$)/i.test(s),Lzt=[{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"}],_W="event-images",oae=s=>{if(s.file_path){const{data:t}=q.storage.from(_W).getPublicUrl(s.file_path);return t.publicUrl}return s.url||null},TJ=async(s,t="open")=>{if(!s.file_path){const c=s.url;c&&window.open(c,"_blank","noopener,noreferrer");return}const{data:n,error:r}=await q.storage.from(_W).download(s.file_path);if(r||!n){const c=oae(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)},Izt=s=>at({queryKey:["admin-program-resources",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("program_resources").select("*").eq("program_id",s).order("sort_order");if(n)throw n;return t||[]}}),cUs=s=>{const t=Bt();return mt({mutationFn:async n=>{const r={program_id:s,title:(n.title||"").trim(),description:n.description||null,category:(n.category||"Resources").trim()||"Resources",resource_kind:n.resource_kind||"pdf",url:n.url||null,file_path:n.file_path||null,status:n.status||"published",sort_order:n.sort_order??0};if(n.id){const{error:a}=await q.from("program_resources").update(r).eq("id",n.id);if(a)throw a}else{const{error:a}=await q.from("program_resources").insert(r);if(a)throw a}},onSuccess:()=>{se.success("Resource saved"),t.invalidateQueries({queryKey:["admin-program-resources"]}),t.invalidateQueries({queryKey:["program-workspace"]})},onError:n=>se.error(n.message||"Could not save the resource")})},dUs=()=>{const s=Bt();return mt({mutationFn:async t=>{t.file_path&&await q.storage.from(_W).remove([t.file_path]);const{error:n}=await q.from("program_resources").delete().eq("id",t.id);if(n)throw n},onSuccess:()=>{se.success("Resource removed"),s.invalidateQueries({queryKey:["admin-program-resources"]}),s.invalidateQueries({queryKey:["program-workspace"]})},onError:t=>se.error(t.message||"Could not remove the resource")})},uUs=(s,t)=>at({queryKey:["admin-program-member-resources",s,t],enabled:!!s&&!!t,queryFn:async()=>{const{data:n,error:r}=await q.from("program_member_resources").select("*").eq("program_id",s).eq("user_id",t).order("sort_order");if(r)throw r;return n||[]}}),hUs=(s,t)=>{const n=Bt(),{user:r}=hs();return mt({mutationFn:async a=>{const i={program_id:s,user_id:t,uploaded_by:(r==null?void 0:r.id)??null,title:(a.title||"").trim(),description:a.description||null,category:(a.category||"Personal").trim()||"Personal",resource_kind:a.resource_kind||"pdf",url:a.url||null,file_path:a.file_path||null,status:a.status||"published",sort_order:a.sort_order??0};if(a.id){const{error:l}=await q.from("program_member_resources").update(i).eq("id",a.id);if(l)throw l}else{const{error:l}=await q.from("program_member_resources").insert(i);if(l)throw l}},onSuccess:()=>{se.success("Personal resource saved"),n.invalidateQueries({queryKey:["admin-program-member-resources"]}),n.invalidateQueries({queryKey:["program-workspace"]})},onError:a=>se.error(a.message||"Could not save the resource")})},mUs=()=>{const s=Bt();return mt({mutationFn:async t=>{t.file_path&&await q.storage.from(_W).remove([t.file_path]);const{error:n}=await q.from("program_member_resources").delete().eq("id",t.id);if(n)throw n},onSuccess:()=>{se.success("Personal resource removed"),s.invalidateQueries({queryKey:["admin-program-member-resources"]}),s.invalidateQueries({queryKey:["program-workspace"]})},onError:t=>se.error(t.message||"Could not remove the resource")})},pUs=s=>{const{user:t}=hs();return at({queryKey:["program-interest",s,t==null?void 0:t.id],enabled:!!s&&!!(t!=null&&t.id),queryFn:async()=>{const{data:n,error:r}=await q.from("program_interest").select("*").eq("program_id",s).eq("user_id",t.id).maybeSingle();if(r)throw r;return n||null}})},fUs=s=>{const t=Bt(),{user:n}=hs();return mt({mutationFn:async r=>{if(!(n!=null&&n.id)||!s)throw new Error("You need to be signed in.");if(r){const{error:a}=await q.from("program_interest").upsert({program_id:s,user_id:n.id,source:"program_detail"},{onConflict:"program_id,user_id"});if(a)throw a}else{const{error:a}=await q.from("program_interest").delete().eq("program_id",s).eq("user_id",n.id);if(a)throw a}return r},onSuccess:r=>{se.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=>se.error(r.message||"Could not update your notify preference")})},xUs=s=>at({queryKey:["admin-program-interest",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("program_interest").select("*").eq("program_id",s).order("created_at",{ascending:!1});if(n)throw n;const r=t||[];if(!r.length)return[];const a=Array.from(new Set(r.map(o=>o.user_id))),{data:i}=await q.from("profiles").select("id, name, email, phone, brokerage_name").in("id",a),l=new Map((i||[]).map(o=>[o.id,o]));return r.map(o=>{const c=l.get(o.user_id)||{};return{...o,full_name:c.name??null,email:c.email??null,phone:c.phone??null,brokerage:c.brokerage_name??null}})}}),gUs=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)},yUs=()=>{const{data:s=[]}=Ezt(),{data:t=[]}=xet(),n=new Set(t.filter(DH).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=gUs(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(Sy,{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(Oe,{variant:"secondary",children:l})]}),e.jsxs("p",{className:"mt-0.5 text-sm text-muted-foreground",children:[a.kickoff_at?`Starts ${xu(a.kickoff_at)} · `:"","Your program dashboard is live — lessons, resources and sessions inside."]})]})]}),e.jsx(B,{asChild:!0,size:"lg",className:"shrink-0",children:e.jsxs(ir,{to:`/programs/${a.slug}/workspace`,children:["Open program dashboard",e.jsx(La,{className:"ml-1.5 h-4 w-4"})]})})]},a.id)})})},vUs={url:"/exp-agent-advantage.webp"};function bUs({className:s}){const{isMember:t,program:n,packageName:r}=IS();return!t||!((n==null?void 0:n.name)||"").toLowerCase().includes("exp")?null:e.jsxs(ve,{className:At("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:vUs.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(un,{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 _Us({className:s}){var E,P,M;const{user:t}=hs(),{isMember:n,program:r,pkg:a,packageName:i}=IS(),l=_.useMemo(()=>!n||!(a!=null&&a.includes_coaching)?!1:((r==null?void 0:r.name)||"").toLowerCase().includes("exp"),[n,a,r]),{data:o}=VJe(),c=o==null?void 0:o.id,{data:d=[]}=HJe(c),{data:u=[]}=GJe(c),{data:h}=at({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:O}]=await Promise.all([q.from("coaching_onboarding_forms").select("submitted_at").eq("user_id",t.id).maybeSingle(),q.from("coaching_prep_checklist_items").select("id, title, sort_order").eq("package_id",a.id).eq("is_active",!0).order("sort_order"),q.from("coaching_prep_checklist_state").select("item_id").eq("user_id",t.id)]),V=new Set((O||[]).map(G=>G.item_id));return{submitted:!!(I!=null&&I.submitted_at),items:(D||[]).map(G=>({...G,done:V.has(G.id)}))}}});if(!l)return null;const m=((E=o==null?void 0:o.coachProfile)==null?void 0:E.name)||"Your LevelUp Coach",p=((P=o==null?void 0:o.coachProfile)==null?void 0:P.avatar_url)||void 0,f=(M=o==null?void 0:o.coach)==null?void 0:M.headline,v=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],g=u.filter(I=>I.status!=="done"),b=u.length-g.length,j=(h==null?void 0:h.items)||[],S=j.filter(I=>I.done).length,C=j.length?Math.round(S/j.length*100):0;return e.jsxs(ve,{className:At("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(ja,{className:"h-16 w-16 ring-4 ring-white/20 md:h-20 md:w-20",children:[e.jsx(pi,{src:p,alt:m}),e.jsx(Na,{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(un,{className:"h-4 w-4","aria-hidden":"true"}),e.jsx("span",{className:"text-xs font-semibold uppercase tracking-[0.18em]",children:i?`${i} Coaching`:"Included Coaching"})]}),e.jsx("h2",{className:"mt-1 text-2xl font-bold leading-tight",children:m}),e.jsx("p",{className:"mt-1 max-w-xl text-sm text-white/80",children:f||"1:1 accountability coaching included with your eXp Agent Advantage membership."})]}),e.jsxs("div",{className:"flex flex-col gap-2 md:items-end",children:[e.jsx(B,{asChild:!0,className:"bg-white text-[#2a4c64] hover:bg-white/90",children:e.jsxs(ir,{to:"/my-coach",children:[e.jsx(gy,{className:"mr-2 h-4 w-4"})," Book a session"]})}),e.jsx(B,{asChild:!0,variant:"outline",className:"border-white/40 bg-white/10 text-white hover:bg-white/20 hover:text-white",children:e.jsxs(ir,{to:"/my-coach",children:[e.jsx(Hi,{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(Kr,{className:"h-3.5 w-3.5"})," Next session"]}),v?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"mt-2 text-lg font-semibold text-foreground",children:Hs(new Date(v.scheduled_at),"EEE, MMM d")}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Hs(new Date(v.scheduled_at),"h:mm a"),v.title?` · ${v.title}`:""]}),v.meeting_url&&e.jsx(B,{asChild:!0,size:"sm",variant:"outline",className:"mt-3",children:e.jsx("a",{href:v.meeting_url,target:"_blank",rel:"noreferrer",children:"Join meeting"})})]}):e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"mt-2 text-sm text-muted-foreground",children:["Nothing on the calendar yet — grab a time with ",m.split(" ")[0],"."]}),e.jsx(B,{asChild:!0,size:"sm",className:"mt-3",children:e.jsx(ir,{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(Ny,{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:g.length}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"open"}),b>0&&e.jsxs(Oe,{variant:"secondary",className:"ml-auto",children:[b," done"]})]}),e.jsxs("ul",{className:"mt-2 space-y-1",children:[g.slice(0,3).map(I=>e.jsxs("li",{className:"flex items-start gap-2 text-sm text-muted-foreground",children:[e.jsx(Uf,{className:"mt-1 h-3 w-3 shrink-0"}),e.jsx("span",{className:"line-clamp-1",children:I.title||I.description})]},I.id)),g.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(qf,{className:"h-3.5 w-3.5"})," Coaching prep"]}),h!=null&&h.submitted?j.length>0?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mt-2 flex items-center justify-between text-sm",children:[e.jsxs("span",{className:"font-semibold text-foreground",children:[S,"/",j.length," complete"]}),e.jsxs("span",{className:"text-muted-foreground",children:[C,"%"]})]}),e.jsx(Fi,{value:C,className:"mt-2 h-2"}),e.jsx("ul",{className:"mt-3 space-y-1",children:j.slice(0,3).map(I=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[I.done?e.jsx(Er,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-primary"}):e.jsx(Uf,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground/50"}),e.jsx("span",{className:At("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(mm,{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(B,{asChild:!0,size:"sm",className:"mt-3",children:e.jsx(ir,{to:"/coaching/onboarding",children:"Start questionnaire"})})]})]})]})]})}function wUs(s){return"EST"}function pte(s){const n=new Intl.DateTimeFormat("en-US",{hour:"numeric",minute:"2-digit",hour12:!0,timeZone:"America/New_York"}).format(s),r=wUs();return`${n} ${r}`}function fF(s){const t=new Date,n=new Date(s),r=Tpt(n,-15),a=Tpt(n,30);return t>a?"ended":Wk(t,{start:n,end:a})?"live":Wk(t,{start:r,end:n})?"starting_soon":"upcoming"}function yet(s){const t=fF(s);return t==="starting_soon"||t==="live"}const jUs=yet,NUs=({events:s,registrations:t,onNavigateToEvents:n})=>{const[r,a]=_.useState(new Date);_.useEffect(()=>{const p=setInterval(()=>{a(new Date)},3e4);return()=>clearInterval(p)},[]);const i=s.filter(p=>yet(p.event_date));if(i.length===0)return null;const l=i[0],o=fF(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(Nv,{className:"h-4 w-4"}),"Live Now"]}):e.jsxs(e.Fragment,{children:[e.jsx(Gr,{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 ${pte(new Date(l.event_date))}`:`Starts at ${pte(new Date(l.event_date))}`})]}),e.jsx("div",{className:"flex items-center gap-2",children:u?e.jsxs(B,{onClick:()=>window.open(d,"_blank"),className:`${m.button} text-white gap-2`,children:[e.jsx(wr,{className:"h-4 w-4"}),h?"Join Now":"Join When Live"]}):e.jsxs(B,{variant:"outline",onClick:n,className:`${m.outlineButton} gap-2`,children:[e.jsx(In,{className:"h-4 w-4"}),"Register & Join"]})})]})})]})};function Vg(){const{user:s}=hs(),{data:t,isLoading:n}=at({queryKey:["gmail-integration",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),queryFn:async()=>{const{data:h,error:m}=await q.from("gmail_integrations").select("*").eq("user_id",s.id).maybeSingle();if(m)throw m;return h}}),{data:r,isLoading:a}=at({queryKey:["user-verified-ses-sender",s==null?void 0:s.id],enabled:!!s,staleTime:60*1e3,queryFn:async()=>{const{data:h}=await q.from("user_verified_senders").select("email, status").eq("user_id",s.id).eq("status","verified").order("verified_at",{ascending:!1}).limit(1).maybeSingle();return h}}),i=!!(t!=null&&t.is_active),l=(t==null?void 0:t.gmail_email)||null,o=!!(r!=null&&r.email),c=(r==null?void 0:r.email)||null;return{isGmailConnected:i,gmailEmail:l,hasVerifiedSes:o,sesEmail:c,canSendEmail:i||o,sendMethod:i?"gmail":o?"mass_email":"none",isLoading:n||a}}function kUs(){var C;const{user:s}=hs(),{isGmailConnected:t,hasVerifiedSes:n,isLoading:r}=Vg(),a=IS(),i=a.isMember&&!!((C=a.pkg)!=null&&C.includes_coaching),l=a.isMember&&!i,[o,c]=_.useState(!1),[d,u]=_.useState(!1);_.useEffect(()=>{s!=null&&s.id&&q.from("onboarding_checklist_dismissed").select("id").eq("user_id",s.id).maybeSingle().then(({data:E})=>{c(!!E),u(!0)})},[s==null?void 0:s.id]);const{data:h,isLoading:m}=at({queryKey:["new-agent-onboarding",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),staleTime:3e4,queryFn:async()=>{const[E,P,M,I,D,O]=await Promise.all([q.from("profiles").select("avatar_url, phone, bio, name").eq("id",s.id).maybeSingle(),q.from("innercircle_contacts").select("id",{count:"exact",head:!0}).eq("owner_user_id",s.id),q.from("event_registrations").select("id",{count:"exact",head:!0}).eq("user_id",s.id),q.from("community_posts").select("id",{count:"exact",head:!0}).eq("user_id",s.id),q.from("events").select("id, title, event_date, image_url").eq("is_published",!0).gte("event_date",new Date().toISOString()).or("title.ilike.%onboarding%,title.ilike.%new member%,title.ilike.%welcome%,description.ilike.%new member onboarding%").order("event_date",{ascending:!0}).limit(1).maybeSingle(),q.from("coaching_assignments").select("id").eq("agent_id",s.id).eq("status","active").limit(1)]),V=(O.data||[]).map(ce=>ce.id);let G=!1;if(V.length){const{count:ce}=await q.from("coaching_sessions").select("id",{count:"exact",head:!0}).in("assignment_id",V);G=(ce||0)>0}const $=E.data,H=!!($!=null&&$.avatar_url&&($!=null&&$.phone)&&($!=null&&$.bio)),Y=P.count||0,Z=(M.count||0)>0,ne=I.count||0;return{profile:$,profileComplete:H,contactsCount:Y,contactsComplete:Y>=5,eventsRegistered:Z,communityComplete:ne>0,nextOnboardingEvent:D.data||null,coachingBooked:G}}}),p=t||n,f=[{id:"profile",complete:!!(h!=null&&h.profileComplete)},{id:"email",complete:p},{id:"contacts",complete:!!(h!=null&&h.contactsComplete)},{id:"event",complete:!!(h!=null&&h.eventsRegistered)},{id:"community",complete:!!(h!=null&&h.communityComplete)}],y=l?f.filter(E=>E.id!=="community"&&E.id!=="event"):f;i&&y.push({id:"coaching",complete:!!(h!=null&&h.coachingBooked)});const v=y.filter(E=>E.complete).length,g=y.length;return{steps:y,completedCount:v,totalCount:g,allComplete:v===g,dismissed:o,dismiss:async()=>{s!=null&&s.id&&(c(!0),await q.from("onboarding_checklist_dismissed").insert({user_id:s.id}))},reopen:async()=>{s!=null&&s.id&&(c(!1),await q.from("onboarding_checklist_dismissed").delete().eq("user_id",s.id))},data:h,isGmailConnected:t,hasVerifiedSes:n,loading:m||r||!d||a.isLoading}}const SUs={profile:{title:"Complete Your Profile",description:"Add your headshot, phone, and short bio so contacts recognize you.",icon:Fo,accent:"from-[#2a4c64] to-[#406E71]",cta:"Edit Profile"},email:{title:"Set Up Email Sending",description:"Connect Gmail (recommended) or verify a Mass Email sender to send from your address.",icon:ln,accent:"from-[#406E71] to-[#5b9ea1]",cta:"Connect Email"},contacts:{title:"Add Your First Contacts",description:"Import your database or add contacts one at a time to start building your Inner Circle.",icon:In,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:ga,accent:"from-[#8b5cf6] to-[#a78bfa]",cta:"Register"},community:{title:"Say Hi in the Community",description:"Introduce yourself and connect with other LevelUp agents.",icon:Hi,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:mm,accent:"from-[#0ea5e9] to-[#38bdf8]",cta:"Book Session"}};function CUs(){var y,v;const s=Fn(),{user:t}=hs(),{steps:n,completedCount:r,totalCount:a,allComplete:i,dismissed:l,dismiss:o,data:c,loading:d}=kUs(),[u,h]=_.useState(!0);if(d||l||i)return null;const m=(((y=c==null?void 0:c.profile)==null?void 0:y.name)||((v=t==null?void 0:t.user_metadata)==null?void 0:v.name)||"there").split(" ")[0],p=r/a*100,f=async g=>{switch(g){case"profile":s("/profile");break;case"email":s("/mission-control/integrations");break;case"contacts":s("/mission-control/contacts");break;case"event":{const b=c==null?void 0:c.nextOnboardingEvent;if(!b){s("/events");return}if(!(t!=null&&t.id))return;const{error:j}=await q.from("event_registrations").insert({user_id:t.id,event_id:b.id});j&&!String(j.message).toLowerCase().includes("duplicate")?(se.error("Could not register — opening events page."),s("/events")):se.success(`You're registered for ${b.title}!`);break}case"community":s("/community");break;case"coaching":s("/my-coach");break}};return e.jsxs(ve,{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(Qn,{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(un,{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(Fi,{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(B,{onClick:()=>h(!0),className:"bg-[#f5f0e0] text-[#2a4c64] hover:bg-white font-semibold",children:["Continue Setup ",e.jsx(La,{className:"h-4 w-4 ml-1.5"})]}),e.jsx("button",{onClick:()=>h(g=>!g),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(_v,{className:"h-4 w-4"})]}):e.jsxs(e.Fragment,{children:["Show steps ",e.jsx(tl,{className:"h-4 w-4"})]})})]})]})]})]}),u&&e.jsx(Me,{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(g=>{const b=SUs[g.id],j=b.icon;return e.jsx("div",{className:At("relative rounded-xl border p-4 transition-all group",g.complete?"bg-muted/40 border-muted":"bg-card hover:shadow-md hover:border-primary/40 cursor-pointer"),onClick:()=>!g.complete&&f(g.id),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:At("h-10 w-10 rounded-lg flex items-center justify-center shrink-0 bg-gradient-to-br text-white",g.complete?"from-emerald-500 to-emerald-600":b.accent),children:g.complete?e.jsx(Er,{className:"h-5 w-5"}):e.jsx(j,{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:At("font-semibold text-sm",g.complete&&"text-muted-foreground line-through"),children:b.title})}),e.jsx("p",{className:At("text-xs text-muted-foreground mt-1 leading-relaxed",g.complete&&"line-through"),children:b.description}),g.id==="event"&&!g.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"]}),!g.complete&&e.jsxs(B,{size:"sm",variant:"ghost",className:"mt-2 h-7 px-2 -ml-2 text-primary hover:text-primary hover:bg-primary/10",onClick:S=>{S.stopPropagation(),f(g.id)},children:[b.cta," ",e.jsx(La,{className:"h-3 w-3 ml-1"})]})]}),g.complete&&e.jsx("span",{className:"text-xs font-medium text-emerald-600 shrink-0",children:"✓ Done"})]})},g.id)})})})]})}function AUs(s){return at({queryKey:["brokerage-content-categories",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("brokerage_content_categories").select("*").eq("brokerage_id",s).order("sort_order");if(n)throw n;return t},enabled:!!s})}function EUs(s,t){return at({queryKey:["brokerage-content",s,t],queryFn:async()=>{if(!s)return[];let n=q.from("brokerage_content").select("*, category:brokerage_content_categories(*)").eq("brokerage_id",s).order("created_at",{ascending:!1});t&&(n=n.eq("category_id",t));const{data:r,error:a}=await n;if(a)throw a;return r},enabled:!!s})}function TUs(s,t=4){return at({queryKey:["brokerage-content-recent",s,t],queryFn:async()=>{if(!s)return[];const{data:n,error:r}=await q.from("brokerage_content").select("*, category:brokerage_content_categories(*)").eq("brokerage_id",s).order("created_at",{ascending:!1}).limit(t);if(r)throw r;return n},enabled:!!s})}function MUs(s){const t=Bt();return mt({mutationFn:async n=>{const{data:r,error:a}=await q.from("brokerage_content").insert(n).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["brokerage-content"]}),t.invalidateQueries({queryKey:["brokerage-content-recent"]})}})}function PUs(){const s=Bt();return mt({mutationFn:async t=>{const{error:n}=await q.from("brokerage_content").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["brokerage-content"]}),s.invalidateQueries({queryKey:["brokerage-content-recent"]})}})}function LUs(s){const t=Bt();return mt({mutationFn:async n=>{const{data:r,error:a}=await q.from("brokerage_content_categories").insert({...n,brokerage_id:s}).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["brokerage-content-categories"]})}})}function IUs(){const s=Bt();return mt({mutationFn:async t=>{const{error:n}=await q.from("brokerage_content_categories").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["brokerage-content-categories"]})}})}function DUs(s){const t=Bt();return mt({mutationFn:async()=>{const n=[{name:"Events",icon:"📅",sort_order:0,is_default:!0,brokerage_id:s},{name:"Videos",icon:"🎥",sort_order:1,is_default:!0,brokerage_id:s},{name:"Documents",icon:"📄",sort_order:2,is_default:!0,brokerage_id:s},{name:"Resources",icon:"🔗",sort_order:3,is_default:!0,brokerage_id:s},{name:"Graphics",icon:"🎨",sort_order:4,is_default:!0,brokerage_id:s}],{error:r}=await q.from("brokerage_content_categories").upsert(n,{onConflict:"brokerage_id,name"});if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["brokerage-content-categories"]})}})}const RUs={video:Jd,pdf:Fr,link:vd,event:ga,graphic:Xc},FUs={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 OUs(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 zUs(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 BUs({item:s}){const t=Fn(),n=RUs[s.content_type]||vd,r=FUs[s.content_type]||"",[a,i]=_.useState(null),l=s.thumbnail_url||(s.content_type==="graphic"&&s.file_url?s.file_url:null)||(s.content_type==="video"?OUs(s.url):null);_.useEffect(()=>{l||!s.url||s.content_type!=="video"||!zUs(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(ve,{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(Me,{className:"p-3",children:[e.jsx("div",{className:"flex items-center gap-1.5 mb-1.5",children:e.jsxs(Oe,{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 UUs(){const{brokerageId:s}=hs(),t=Fn(),{data:n=[],isLoading:r}=TUs(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(B,{variant:"ghost",size:"sm",onClick:()=>t("/brokerage-content"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(La,{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(BUs,{item:a},a.id))})]})}const Dzt=({className:s,variant:t="default"})=>e.jsx(Oe,{variant:"outline",className:At("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"}),qUs={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"},$Us={coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",active:"Active",under_contract:"Under Contract",sold:"Sold",withdrawn:"Withdrawn"};function VUs(s){return s>=1e6?`$${(s/1e6).toFixed(1)}M`:`$${(s/1e3).toFixed(0)}K`}function HUs(){const s=Fn(),{data:t,isLoading:n}=_9t(),{data:r,isLoading:a}=w9t({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(ve,{className:"bg-gradient-to-br from-emerald-500/5 via-emerald-500/10 to-emerald-500/5 border-emerald-500/20",children:e.jsx(Me,{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(Dzt,{})]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>s("/mission-control/listings"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(La,{className:"h-4 w-4"})]})]}),c.length===0?e.jsx(ve,{className:"bg-muted/30 border-dashed",children:e.jsx(Me,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Jr,{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(B,{variant:"link",size:"sm",onClick:()=>s("/mission-control/listings/new"),className:"mt-2",children:"Add the first listing"})]})})}):e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3",children:c.map(u=>{var m,p;const h=((m=u.photos)==null?void 0:m.find(f=>f.is_primary))||((p=u.photos)==null?void 0:p[0]);return e.jsxs("div",{onClick:()=>s(`/mission-control/listings/${u.id}`),className:"group cursor-pointer bg-card rounded-xl border border-border overflow-hidden transition-all duration-200 hover:shadow-lg hover:border-primary/30",children:[e.jsxs("div",{className:"aspect-[4/3] bg-muted/50 overflow-hidden relative",children:[h!=null&&h.photo_url?e.jsx("img",{src:h.photo_url,alt:`${u.city}, ${u.state}`,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(Jr,{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(Oe,{className:"gap-1 bg-amber-500 text-white border-0 text-[10px] px-1.5 py-0.5",children:[e.jsx(Da,{className:"h-2.5 w-2.5 fill-current"}),"Featured"]})}),e.jsx("div",{className:"absolute top-1.5 right-1.5",children:e.jsx(Oe,{className:`text-[10px] px-1.5 py-0.5 ${qUs[u.status]}`,children:$Us[u.status]})})]}),e.jsxs("div",{className:"p-2",children:[e.jsx("p",{className:"font-bold text-sm text-foreground",children:VUs(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 Rzt(s=10,t){return at({queryKey:["event-leaderboard",s,t],queryFn:async()=>{const{data:n}=await q.from("user_roles").select("user_id").eq("role","admin"),r=new Set((n==null?void 0:n.map(m=>m.user_id))||[]);let a=null;if(t){const{data:m}=await q.from("profiles").select("id").eq("brokerage_id",t);a=new Set((m==null?void 0:m.map(p=>p.id))||[])}const{data:i,error:l}=await q.from("agent_attendance_stats").select("user_id, total_points, total_events_attended, current_streak").order("total_points",{ascending:!1}).limit(s+r.size+50);if(l)throw l;if(!i||i.length===0)return[];let o=i.filter(m=>!r.has(m.user_id));a&&(o=o.filter(m=>a.has(m.user_id)));const c=o.slice(0,s),d=c.map(m=>m.user_id),{data:u}=await q.from("profiles").select("id, name").in("id",d),h=new Map((u==null?void 0:u.map(m=>[m.id,{name:m.name}]))||[]);return c.map(m=>({user_id:m.user_id,total_points:m.total_points,total_events_attended:m.total_events_attended,current_streak:m.current_streak,profile:h.get(m.user_id)||null}))}})}function Fzt(s){return at({queryKey:["user-attendance-stats",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("agent_attendance_stats").select("*").eq("user_id",s).single();if(n&&n.code!=="PGRST116")throw n;return t},enabled:!!s})}function Ozt(s){return at({queryKey:["user-badges",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("agent_badges").select("*").eq("user_id",s).order("earned_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function zzt(s,t){return at({queryKey:["user-rank",s,t],queryFn:async()=>{if(!s)return null;const{data:n}=await q.from("agent_attendance_stats").select("total_points").eq("user_id",s).single();if(!n)return null;const{data:r}=await q.from("user_roles").select("user_id").eq("role","admin"),a=new Set((r==null?void 0:r.map(c=>c.user_id))||[]),{data:i,error:l}=await q.from("agent_attendance_stats").select("user_id, total_points").gt("total_points",n.total_points);if(l)throw l;let o=(i==null?void 0:i.filter(c=>!a.has(c.user_id)))||[];if(t){const{data:c}=await q.from("profiles").select("id").eq("brokerage_id",t),d=new Set((c==null?void 0:c.map(u=>u.id))||[]);o=o.filter(u=>d.has(u.user_id))}return o.length+1},enabled:!!s})}function GUs(){const{user:s,brokerageId:t,isAdmin:n}=hs();Fn();const r=!!t,[a,i]=_.useState("brokerage"),l=()=>{if(n)return null;if(r)return a==="global"?null:t},{data:o,isLoading:c}=Rzt(5,l()),{data:d}=Fzt(s==null?void 0:s.id),{data:u}=zzt(s==null?void 0:s.id,l()),{data:h}=Ozt(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(ve,{children:[e.jsx(bt,{className:"pb-2",children:e.jsxs(St,{className:"text-base flex items-center gap-2",children:[e.jsx(wl,{className:"h-4 w-4 text-yellow-500"}),p()]})}),e.jsx(Me,{children:e.jsx("div",{className:"space-y-2",children:[...Array(m?5:3)].map((y,v)=>e.jsx(cn,{className:"h-10 w-full"},v))})})]});const f=y=>y===0?e.jsx(wl,{className:"h-4 w-4 text-yellow-500 mx-auto"}):y===1?e.jsx("span",{className:"text-sm font-medium text-gray-400",children:"2"}):y===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:y+1});if(m){const y=(o==null?void 0:o.slice(0,5))||[];return e.jsxs(ve,{children:[e.jsxs(bt,{className:"pb-2",children:[e.jsxs(St,{className:"text-base flex items-center gap-2",children:[e.jsx(wl,{className:"h-4 w-4 text-yellow-500"}),p()]}),!n&&r&&e.jsxs("div",{className:"flex gap-1 mt-2",children:[e.jsx(B,{variant:a==="brokerage"?"default":"outline",size:"sm",className:"text-xs h-7 flex-1",onClick:()=>i("brokerage"),children:"My Brokerage"}),e.jsx(B,{variant:a==="global"?"default":"outline",size:"sm",className:"text-xs h-7 flex-1",onClick:()=>i("global"),children:"All LevelUp"})]})]}),e.jsxs(Me,{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:[y.map((v,g)=>{var b,j,S;return e.jsxs("div",{className:`flex items-center gap-2 p-2 rounded-lg ${v.user_id===(s==null?void 0:s.id)?"bg-primary/10 border border-primary/20":g===0?"bg-yellow-500/10":""}`,children:[e.jsx("div",{className:"w-5 text-center",children:f(g)}),e.jsx(ja,{className:"h-6 w-6",children:e.jsx(Na,{className:"text-xs",children:((j=(b=v.profile)==null?void 0:b.name)==null?void 0:j.charAt(0))||"?"})}),e.jsx("span",{className:"flex-1 text-sm font-medium truncate",children:((S=v.profile)==null?void 0:S.name)||"Unknown"}),e.jsx("span",{className:"text-sm font-bold text-primary",children:v.total_points})]},v.user_id)}),y.length===0&&e.jsx("div",{className:"text-center text-muted-foreground py-2 text-sm",children:"No data yet"})]}),e.jsxs(ir,{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(Vo,{className:"h-4 w-4"}),"Spend Points in Reward Store",e.jsx(xi,{className:"h-4 w-4"})]})]})]})}return e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-2",children:e.jsxs(St,{className:"text-base flex items-center gap-2",children:[e.jsx(wl,{className:"h-4 w-4 text-yellow-500"}),"My Points"]})}),e.jsx(Me,{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(gu,{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(Hh,{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(y=>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:y.badge_name},y.id)),h.length>4&&e.jsxs("span",{className:"text-xs text-muted-foreground px-2 py-1",children:["+",h.length-4," more"]})]})]}),e.jsxs(ir,{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(Vo,{className:"h-4 w-4"}),"Spend Points in Reward Store",e.jsx(xi,{className:"h-4 w-4"})]})]}):e.jsxs("div",{className:"text-center text-muted-foreground py-4 text-sm",children:[e.jsx(Da,{className:"h-8 w-8 mx-auto mb-2 text-muted-foreground/50"}),e.jsx("p",{children:"Attend events to earn points!"}),e.jsxs(ir,{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(Vo,{className:"h-4 w-4"}),"Visit Reward Store",e.jsx(xi,{className:"h-4 w-4"})]})]})})]})}const V9=()=>at({queryKey:["lead-sources"],queryFn:async()=>{const{data:s,error:t}=await q.from("lead_sources").select("*").eq("is_active",!0).order("sort_order");if(t)throw t;return s}}),vet=()=>{const s=Bt(),{user:t}=hs();return mt({mutationFn:async n=>{const{data:r}=await q.from("lead_sources").select("id, name").eq("is_active",!0).ilike("name",n.trim()),a=(r||[]).find(o=>o.name.toLowerCase()===n.trim().toLowerCase()&&!0);if(a)throw new Error(`Lead source "${a.name}" already exists`);const{data:i,error:l}=await q.from("lead_sources").insert({name:n,owner_user_id:t==null?void 0:t.id,sort_order:100}).select().single();if(l)throw l;return i},onSuccess:()=>{s.invalidateQueries({queryKey:["lead-sources"]}),se.success("Lead source added")},onError:n=>{se.error("Failed to add lead source"),console.error(n)}})},WUs=()=>{const s=Bt();return mt({mutationFn:async({id:t,name:n})=>{const{error:r}=await q.from("lead_sources").update({name:n}).eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["lead-sources"]}),se.success("Lead source updated")},onError:t=>{se.error(t.message||"Failed to update lead source")}})},KUs=()=>{const s=Bt();return mt({mutationFn:async t=>{const{error:n}=await q.from("lead_sources").update({is_active:!1}).eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["lead-sources"]}),se.success("Lead source removed")},onError:t=>{se.error(t.message||"Failed to remove lead source")}})},bet=(s,t)=>{const{user:n,isAdmin:r}=hs(),a=r&&t?t:n==null?void 0:n.id;return at({queryKey:["scorecard-transactions",s,a],queryFn:async()=>{let i=q.from("scorecard_transactions").select(` *, lead_source:lead_sources(id, name), client_type:relationship_types(id, name), contact:innercircle_contacts(id, first_name, last_name) `).eq("owner_user_id",a).order("close_date",{ascending:!1});s&&(i=i.gte("close_date",`${s}-01-01`).lte("close_date",`${s}-12-31`));const{data:l,error:o}=await i;if(o)throw o;return l},enabled:!!a})},_et=s=>{const{user:t,isAdmin:n}=hs(),r=n&&s?s:t==null?void 0:t.id;return at({queryKey:["scorecard-transactions-all",r],queryFn:async()=>{const{data:a,error:i}=await q.from("scorecard_transactions").select(` *, lead_source:lead_sources(id, name), client_type:relationship_types(id, name), contact:innercircle_contacts(id, first_name, last_name) `).eq("owner_user_id",r).order("close_date",{ascending:!1});if(i)throw i;return a},enabled:!!r})},hLe=()=>{const s=Bt(),{user:t}=hs();return mt({mutationFn:async n=>{const{data:r,error:a}=await q.from("scorecard_transactions").insert({...n,owner_user_id:t.id}).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["scorecard-transactions"]}),s.invalidateQueries({queryKey:["scorecard-transactions-all"]}),se.success("Transaction added")},onError:n=>{se.error("Failed to add transaction"),console.error(n)}})},YUs=()=>{const s=Bt();return mt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("scorecard_transactions").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["scorecard-transactions"]}),s.invalidateQueries({queryKey:["scorecard-transactions-all"]}),se.success("Transaction updated")},onError:t=>{se.error("Failed to update transaction"),console.error(t)}})},ZUs=()=>{const s=Bt();return mt({mutationFn:async t=>{const{error:n}=await q.from("scorecard_transactions").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["scorecard-transactions"]}),s.invalidateQueries({queryKey:["scorecard-transactions-all"]}),se.success("Transaction deleted")},onError:t=>{se.error("Failed to delete transaction"),console.error(t)}})},Bzt=(s,t)=>{const{user:n,isAdmin:r}=hs(),a=r&&t?t:n==null?void 0:n.id;return at({queryKey:["scorecard-goals",s,a],queryFn:async()=>{const{data:i,error:l}=await q.from("scorecard_goals").select("*").eq("owner_user_id",a).eq("year",s).maybeSingle();if(l)throw l;return i},enabled:!!a})},XUs=()=>{const s=Bt(),{user:t}=hs();return mt({mutationFn:async n=>{const{data:r,error:a}=await q.from("scorecard_goals").upsert({...n,owner_user_id:t.id},{onConflict:"owner_user_id,year"}).select().single();if(a)throw a;return r},onSuccess:(n,r)=>{s.invalidateQueries({queryKey:["scorecard-goals",r.year]}),se.success("Goals saved")},onError:n=>{se.error("Failed to save goals"),console.error(n)}})},mLe=()=>{const{user:s}=hs();return at({queryKey:["scorecard-settings",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.from("scorecard_settings").select("*").eq("user_id",s.id).maybeSingle();if(n)throw n;return t},enabled:!!(s!=null&&s.id)})},QUs=()=>{const s=Bt(),{user:t}=hs();return mt({mutationFn:async n=>{const{data:r,error:a}=await q.from("scorecard_settings").upsert({...n,user_id:t.id},{onConflict:"user_id"}).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["scorecard-settings"]}),se.success("Settings saved")},onError:n=>{se.error("Failed to save settings"),console.error(n)}})},Uzt=(s,t)=>{const{data:n,isLoading:r}=bet(s,t),{data:a,isLoading:i}=_et(t),{data:l}=mLe(),o=(l==null?void 0:l.show_commission)??!0,c=d=>{if(!d||d.length===0)return{totalTransactions:0,buyerCount:0,sellerCount:0,totalVolume:0,averagePrice:0,totalCommission:0,totalNetToAgent:0,topLeadSource:null,transactionsByMonth:[],leadSourceBreakdown:[]};const u=d.filter(C=>C.transaction_type==="buyer").length,h=d.filter(C=>C.transaction_type==="seller").length,m=d.reduce((C,E)=>C+Number(E.sale_price),0),p=d.reduce((C,E)=>C+(Number(E.commission_amount)||0),0),f=d.reduce((C,E)=>{const P=Number(E.commission_amount)||0;if(!P)return C;let M=P;return E.brokerage_split_pct&&(M-=P*(E.brokerage_split_pct/100)),E.team_split_pct&&(M-=P*(E.team_split_pct/100)),E.franchise_fee_pct&&(M-=P*(E.franchise_fee_pct/100)),E.referral_fee_pct&&(M-=P*(E.referral_fee_pct/100)),E.transaction_fee&&(M-=E.transaction_fee),C+Math.max(0,M)},0),y={};d.forEach(C=>{var P;const E=((P=C.lead_source)==null?void 0:P.name)||"Unknown";y[E]=(y[E]||0)+1});const v=Object.entries(y).map(([C,E])=>({name:C,count:E})).sort((C,E)=>E.count-C.count),g=v[0]||null,b={};d.forEach(C=>{const E=Ru(C.close_date).toLocaleString("default",{month:"short"});b[E]=(b[E]||0)+1});const S=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"].map(C=>({month:C,count:b[C]||0}));return{totalTransactions:d.length,buyerCount:u,sellerCount:h,totalVolume:m,averagePrice:d.length>0?m/d.length:0,totalCommission:o?p:0,totalNetToAgent:o?f:0,topLeadSource:g,transactionsByMonth:S,leadSourceBreakdown:v}};return{yearStats:c(n),lifetimeStats:c(a),isLoading:r||i,showCommission:o}},JUs=()=>{const{isAdmin:s}=hs();return at({queryKey:["agents-with-transactions"],queryFn:async()=>{const{data:t,error:n}=await q.from("scorecard_transactions").select("owner_user_id").order("owner_user_id");if(n)throw n;const r=[...new Set(t.map(l=>l.owner_user_id))],{data:a,error:i}=await q.from("profiles").select("id, name, email").in("id",r);if(i)throw i;return a},enabled:s})},d6={recency:40,touchpoints:30,transactions:20,referrals:10},Ngt={warm:70,cooling:40};function eqs(s){return s===null?0:s<=14?d6.recency:s<=30?d6.recency*.85:s<=60?d6.recency*.65:s<=90?d6.recency*.4:s<=180?d6.recency*.2:d6.recency*.05}function tqs(s){const t=Math.min(s/12,1);return Math.round(d6.touchpoints*t)}function sqs(s){return s?d6.transactions:0}function nqs(){return 0}function rqs(s){return s>=Ngt.warm?"warm":s>=Ngt.cooling?"cooling":"at-risk"}function lae(){const{data:s,isLoading:t}=Db(),{data:n}=wzt(),{data:r}=vW(365),{data:a}=_et(),i=_.useMemo(()=>{if(!s)return[];const o=new Date,c=hF(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?CN(o,new Date(m)):null,f=d[h.id]||0,y=u.has(h.id),v=eqs(p),g=tqs(f),b=sqs(y),j=nqs(),S=Math.round(v+g+b+j),C={score:S,status:rqs(S),breakdown:{recency:Math.round(v),touchpoints:Math.round(g),transactions:Math.round(b),referrals:Math.round(j)},lastTouchDate:m,daysSinceTouch:p,touchCountLast12Months:f,hasTransaction:y};return{...h,relationshipScore:C}})},[s,n,r,a]),l=_.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 aqs(s){const{contactsWithScores:t,isLoading:n}=lae(),r=_.useMemo(()=>t.find(a=>a.id===s),[t,s]);return{score:r==null?void 0:r.relationshipScore,isLoading:n}}function qzt(){const s=Fn(),{stats:t,contactsWithScores:n,isLoading:r}=lae();if(r)return e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-2",children:e.jsx(cn,{className:"h-5 w-40"})}),e.jsxs(Me,{className:"space-y-4",children:[e.jsx(cn,{className:"h-20 w-full"}),e.jsx(cn,{className:"h-16 w-full"})]})]});if(t.total===0)return e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-2",children:e.jsxs(St,{className:"text-lg flex items-center gap-2",children:[e.jsx(In,{className:"h-5 w-5"}),"Relationship Health"]})}),e.jsxs(Me,{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Add contacts to see your relationship health scores."}),e.jsx(B,{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(ve,{children:[e.jsxs(bt,{className:"pb-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(St,{className:"text-lg flex items-center gap-2",children:[e.jsx(Nl,{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(Me,{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(Fi,{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(Fi,{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(Fi,{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(gS,{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(xi,{className:"h-3 w-3"})]})]},c.id))})]}),e.jsxs(B,{variant:"outline",size:"sm",className:"w-full",onClick:()=>s("/mission-control/contacts?filter=at-risk"),children:["View All At-Risk Contacts",e.jsx(xi,{className:"h-4 w-4 ml-1"})]})]})]})}const iqs=()=>{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"},oqs=()=>new Intl.DateTimeFormat("en-US",{weekday:"long",month:"long",day:"numeric",timeZone:"America/New_York"}).format(new Date);function lqs({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 cqs({name:s,eventsThisWeek:t=0}){const n=Fn(),{user:r}=hs(),{data:a}=het(),{data:i}=yzt(),l=lLe(),{hasAccess:o,hasAssignment:c}=oRt(),{hasFeature:d}=IS(),{data:u}=at({queryKey:["hub-active-listings",r==null?void 0:r.id],enabled:!!(r!=null&&r.id),queryFn:async()=>{const{count:j,error:S}=await q.from("listings").select("id",{count:"exact",head:!0}).eq("agent_id",r.id);return S?0:j||0}}),h=_.useMemo(()=>{if(!i)return 0;const j=Date.now()-7*24*60*60*1e3;return i.filter(S=>S.created_at&&new Date(S.created_at).getTime()>=j).length},[i]),m=(a==null?void 0:a.length)||0,p=(l==null?void 0:l.streak)||0,f=(l==null?void 0:l.actionsThisWeek)||0,y=(l==null?void 0:l.weeklyGoal)||20,v=[m>0?`${m} ${m===1?"person":"people"} to reach out to`:"no follow-ups queued",t>0?`${t} ${t===1?"event":"events"} coming up`:null].filter(Boolean).join(" • "),g=[{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:gu}],b=[{label:"Add Contact",icon:Pl,to:"/mission-control/contacts?new=true"},...d("social")?[{label:"Create Post",icon:bd,to:"/social-swag-2"}]:[],...d("presentations")?[{label:"Listing Presentation",icon:jv,to:"/mission-control/listing-presentations"}]:[],...o?[{label:"Book Coaching",icon:Qd,to:c?"/my-coach":"/coaching"}]:[],{label:"Ask AI",icon:un,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:oqs()}),e.jsxs("h1",{className:"mt-1 text-2xl sm:text-3xl font-bold",children:[iqs(),", ",s]}),e.jsx("p",{className:"mt-1 text-sm hub-ink-muted",children:v?`Today: ${v}.`:"You're all clear today — go create some momentum."}),e.jsx("div",{className:"mt-5 grid grid-cols-2 gap-2 sm:grid-cols-4",children:g.map(j=>e.jsxs("button",{onClick:()=>n(j.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:[j.icon&&e.jsx(j.icon,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),e.jsx("span",{className:"text-xl font-bold",children:j.value})]}),e.jsx("p",{className:"mt-0.5 text-[11px] hub-ink-muted",children:j.label})]},j.label))})]}),e.jsxs("div",{className:"hub-glass flex items-center gap-4 rounded-2xl px-4 py-3 lg:self-center",children:[e.jsx(lqs,{value:f,goal:y}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold",children:"Weekly touches"}),e.jsx("p",{className:"text-xs hub-ink-muted",children:f>=y?"Goal crushed 🎉":`${y-f} to hit your goal`}),e.jsxs("button",{onClick:()=>n("/mission-control"),className:"mt-2 inline-flex items-center gap-1 text-xs font-medium underline-offset-2 hover:underline",children:["Open Agent OS ",e.jsx(La,{className:"h-3 w-3"})]})]})]})]}),e.jsx("div",{className:"hub-scroll relative mt-5 flex gap-2 overflow-x-auto pb-1",children:b.map(j=>e.jsxs("button",{onClick:()=>n(j.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(j.icon,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),j.label]},j.label))})]})}const eq=24*60*60*1e3,dqs=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}},Rle=s=>{const t=dqs(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,hqs=s=>s===0?"today":s===1?"tomorrow":`in ${s} days`,mqs={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}},pqs=(s=5)=>{const t=ha(),{data:n,isLoading:r}=het(),{data:a,isLoading:i}=Db(),l=at({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:f}]=await Promise.all([q.from("contact_snoozes").select("contact_id").gte("snoozed_until",new Date().toISOString()),q.from("contact_touch_logs").select("contact_id").eq("owner_user_id",t).gte("completed_at",new Date(Date.now()-14*eq).toISOString()),q.from("contact_touch_logs").select("contact_id").eq("owner_user_id",t).gte("completed_at",new Date(Date.now()-90*eq).toISOString())]),y=new Set([...(m||[]).map(M=>M.contact_id),...(p||[]).map(M=>M.contact_id)]),v=new Set((f||[]).map(M=>M.contact_id)),g=M=>!y.has(M)&&!c.has(M);for(const M of u){if(!g(M.id))continue;const D=[{days:Rle(M.birthday),label:"Birthday"},{days:Rle(M.home_anniversary),label:"Home anniversary"},{days:Rle(M.wedding_anniversary),label:"Wedding anniversary"},{days:Rle(M.spouse_birthday),label:`${M.spouse_name||"Spouse"}'s birthday`}].find(O=>uqs(O.days,7));D&&d({key:`milestone-${M.id}`,contact:M,kind:"milestone",actionLabel:"Send wishes",reason:`${D.label} ${hqs(D.days)}`,priority:D.days===0?1:5+D.days})}const{data:b}=await q.from("contact_signals").select("contact_id, signal_type, title, weight, detected_at").eq("owner_user_id",t).or(`expires_at.is.null,expires_at.gt.${new Date().toISOString()}`).order("weight",{ascending:!1}).order("detected_at",{ascending:!1}).limit(200);for(const M of b||[]){const I=h.get(M.contact_id);if(!I||!g(M.contact_id))continue;const D=mqs[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:j}=await q.from("deal_pipeline").select("contact_id, deal_name, property_address, updated_at").eq("owner_user_id",t).is("actual_close_date",null).not("contact_id","is",null).order("updated_at",{ascending:!0}).limit(50);for(const M of j||[]){const I=h.get(M.contact_id);!I||!g(M.contact_id)||d({key:`deal-${M.contact_id}`,contact:I,kind:"deal",actionLabel:"Check in",reason:`Open deal with no contact in 2 weeks${M.property_address?` · ${M.property_address}`:""}`,priority:30})}const S=Date.now()-3*eq;for(const M of u)g(M.id)&&(v.has(M.id)||new Date(M.created_at).getTime()g(M.id)&&!v.has(M.id)&&new Date(M.created_at).getTime()M.id.localeCompare(I.id));if(E.length>0){const M=new Date().getDate()*7%E.length;for(let I=0;IM.priority-I.priority).slice(0,s)},enabled:!!t&&!r&&!i});return{...l,isLoading:l.isLoading||r||i}},fqs=()=>{const s=ha(),t=Bt();return mt({mutationFn:async n=>{const r=new Date(Date.now()+14*eq).toISOString(),{error:a}=await q.from("contact_snoozes").insert({contact_id:n,owner_user_id:s,snoozed_until:r});if(a)throw a},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-queue"]}),t.invalidateQueries({queryKey:["today-actions"]}),ia({title:"Snoozed for 14 days"})},onError:n=>ia({title:"Could not snooze",description:n.message,variant:"destructive"})})},xqs=s=>(s||"?").split(" ").map(t=>t[0]).slice(0,2).join("").toUpperCase(),gqs={plan:{icon:bv,tint:"var(--nav-crm)"},milestone:{icon:Bf,tint:"var(--nav-events)"},signal:{icon:gu,tint:"var(--nav-marketing)"},deal:{icon:Cx,tint:"var(--nav-listings)"},new:{icon:un,tint:"var(--nav-apps)"},cold:{icon:sj,tint:"var(--nav-more)"}};function yqs(){const s=Fn(),{data:t,isLoading:n}=pqs(5),r=fqs(),a=lLe(),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(ku,{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(B,{variant:"ghost",size:"sm",className:"gap-1",onClick:()=>s("/mission-control"),children:["Agent OS ",e.jsx(xi,{className:"h-4 w-4"})]})]}),n?e.jsx("div",{className:"space-y-2",children:[0,1,2].map(c=>e.jsx(cn,{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(Er,{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(B,{size:"sm",variant:"outline",className:"mt-3 gap-1.5",onClick:()=>s("/mission-control/contacts?new=true"),children:[e.jsx(Pl,{className:"h-3.5 w-3.5"})," Add Contact"]})]}):e.jsx(FN,{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=gqs[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:xqs(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(Oe,{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(vqs,{contact:d,onOpen:()=>s(`/mission-control/contacts/${d.id}`)}),e.jsxs(ag,{children:[e.jsx(ig,{asChild:!0,children:e.jsx(B,{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(Qn,{className:"h-4 w-4"})})}),e.jsx(Nx,{children:"Not now — hide for 14 days"})]})]})]},c.key)})})}),e.jsxs("div",{className:"mt-4 border-t border-border pt-4",children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between text-sm",children:[e.jsx("span",{className:"font-medium text-foreground",children:"Weekly goal"}),e.jsxs("span",{className:"text-muted-foreground",children:[e.jsx("span",{className:"font-semibold text-primary",children:i})," / ",l," touches"]})]}),e.jsx(Fi,{value:Math.min(i/l*100,100),className:"h-2"})]})]})}function vqs({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(B,{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(_a,{className:"h-4 w-4"})})}),n&&e.jsx(B,{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(Hi,{className:"h-4 w-4"})})}),r&&e.jsx(B,{asChild:!0,size:"icon",variant:"ghost",className:"h-8 w-8","aria-label":"Email",children:e.jsx("a",{href:`mailto:${r}`,onClick:a=>a.stopPropagation(),children:e.jsx(ln,{className:"h-4 w-4"})})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8","aria-label":"Open contact",onClick:t,children:e.jsx(xi,{className:"h-4 w-4"})})]})}const bqs=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 _qs({events:s,registrations:t}){const n=Fn(),{data:r}=VJe(),{data:a}=at({queryKey:["hub-upcoming-sessions",r==null?void 0:r.id],enabled:!!(r!=null&&r.id),queryFn:async()=>{const{data:l,error:o}=await q.from("coaching_sessions").select("id, scheduled_at, zoom_join_url, status, agenda").eq("assignment_id",r.id).gte("scheduled_at",new Date().toISOString()).neq("status","cancelled").order("scheduled_at",{ascending:!0}).limit(3);return o?[]:l||[]}}),i=_.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:jUs(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(pc,{className:"h-4 w-4",style:{color:"hsl(var(--nav-events))"}})}),"Up Next"]}),e.jsxs(B,{variant:"ghost",size:"sm",className:"gap-1",onClick:()=>n("/events"),children:["All ",e.jsx(xi,{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(pc,{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(B,{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(Nv,{className:"h-4 w-4 text-destructive"}):l.kind==="coaching"?e.jsx(mm,{className:"h-4 w-4",style:{color:"hsl(var(--nav-academy))"}}):e.jsx(Kr,{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":`${bqs(l.date)} · ${pte(l.date)}`," ·"," ",l.subtitle]})]}),l.joinUrl&&e.jsxs(B,{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(wr,{className:"h-3 w-3"})," Join"]})]})},l.id))})]})}const kgt=s=>s>=1e6?`$${(s/1e6).toFixed(1)}M`:s>=1e3?`$${Math.round(s/1e3)}K`:`$${s}`;function wqs(){const s=Fn(),{data:t,isLoading:n}=at({queryKey:["hub-pipeline-snapshot"],queryFn:async()=>{const{data:r,error:a}=await q.from("deal_pipeline").select("id, expected_price, sale_price, stage:deal_pipeline_stages(id, name, color, is_won_stage, is_lost_stage)");if(a)throw a;const i=(r||[]).filter(u=>{var h,m;return!((h=u.stage)!=null&&h.is_won_stage)&&!((m=u.stage)!=null&&m.is_lost_stage)}),l=(r||[]).filter(u=>{var h;return(h=u.stage)==null?void 0:h.is_won_stage}),o=i.reduce((u,h)=>u+Number(h.expected_price||0),0),c=l.reduce((u,h)=>u+Number(h.sale_price||h.expected_price||0),0),d={};return i.forEach(u=>{var m,p,f;const h=((m=u.stage)==null?void 0:m.id)||"none";d[h]||(d[h]={name:((p=u.stage)==null?void 0:p.name)||"Unassigned",color:((f=u.stage)==null?void 0:f.color)||null,count:0}),d[h].count+=1}),{openCount:i.length,wonCount:l.length,volume:o,wonVolume:c,stages:Object.values(d).sort((u,h)=>h.count-u.count).slice(0,4)}}});return e.jsxs("section",{className:"hub-card flex flex-col p-5",children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between",children:[e.jsxs("h3",{className:"flex items-center gap-2 text-base font-semibold text-foreground",children:[e.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-full",style:{background:"hsl(var(--nav-listings) / 0.14)"},children:e.jsx(mj,{className:"h-4 w-4",style:{color:"hsl(var(--nav-listings))"}})}),"Pipeline"]}),e.jsxs(B,{variant:"ghost",size:"sm",className:"gap-1",onClick:()=>s("/mission-control/pipeline"),children:["Open ",e.jsx(xi,{className:"h-4 w-4"})]})]}),n?e.jsxs("div",{className:"space-y-2",children:[e.jsx(cn,{className:"h-12 w-full"}),e.jsx(cn,{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(B,{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:kgt(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:kgt(t.wonVolume)})," volume"]})]})]})}function jqs(){const s=Fn(),{user:t}=hs(),{hasFeature:n}=IS(),{data:r}=at({queryKey:["hub-jump-back-in",t==null?void 0:t.id],enabled:!!(t!=null&&t.id),queryFn:async()=>{const i=[],l=q,o=async u=>{try{const h=await u();return(h==null?void 0:h.data)||[]}catch{return[]}},[c,d]=await Promise.all([o(()=>l.from("listing_presentations").select("id, title, updated_at").eq("owner_user_id",t.id).order("updated_at",{ascending:!1}).limit(2)),o(()=>l.from("listings").select("id, property_address, updated_at").eq("agent_id",t.id).order("updated_at",{ascending:!1}).limit(2))]);return c.forEach(u=>i.push({id:`preso-${u.id}`,label:u.title||"Listing Presentation",sub:"Presentation Studio",icon:jv,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:Jr,hue:"--nav-websites",to:`/mission-control/listings/${u.id}`})),i.push({id:"marketing",label:"Create a post",sub:"Marketing Studio",icon:wh,hue:"--nav-marketing",to:"/marketing-studio"}),i.slice(0,8)}}),a=(r||[]).filter(i=>{const l=XIt(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(Gr,{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(La,{className:"h-4 w-4 shrink-0 text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"})]},i.id))})]})}function Nqs({videos:s,kits:t,templates:n,services:r}){const a=Fn(),i=[{id:"videos",label:"Academy",icon:om,hue:"--nav-academy",items:s,viewAll:"/academy",emptyText:"No new videos yet."},{id:"kits",label:"Resource Kits",icon:wy,hue:"--nav-apps",items:t,viewAll:"/toolbox",emptyText:"No resource kits yet."},{id:"templates",label:"Templates",icon:KM,hue:"--nav-marketing",items:n,viewAll:"/templates",emptyText:"No new templates yet.",fit:"contain"},{id:"services",label:"Services",icon:un,hue:"--nav-crm",items:r,viewAll:"/additional-services",emptyText:"No additional services yet."}],[l,o]=_.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(B,{variant:"ghost",size:"sm",className:"gap-1 text-muted-foreground hover:text-foreground",onClick:()=>a(c.viewAll),children:["View All ",e.jsx(La,{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 kqs=()=>{var ie;const{user:s,isAdmin:t}=hs(),n=Fn(),{hasFeature:r}=IS(),[a,i]=_.useState([]),[l,o]=_.useState([]),[c,d]=_.useState([]),[u,h]=_.useState([]),[m,p]=_.useState([]),[f,y]=_.useState([]),[v,g]=_.useState(new Set),[b,j]=_.useState([]),[S,C]=_.useState([]),[E,P]=_.useState([]),[M,I]=_.useState(null),[D,O]=_.useState(!0);_.useEffect(()=>{V()},[s]);const V=async()=>{var te,ae,le,be,me;try{const[he,pe,Ce,Ae,Pe,ze,ke,Ze,Se,Fe,Ne]=await Promise.all([q.from("user_tags").select("tag").eq("user_id",s==null?void 0:s.id),q.from("app_tiles").select("*").order("name"),q.from("user_favorites").select("app_id").eq("user_id",s==null?void 0:s.id),q.from("events").select("*").order("event_date",{ascending:!0}),q.from("event_registrations").select("event_id, zoom_join_url").eq("user_id",s==null?void 0:s.id),q.from("canva_templates").select("id, name, preview_image_url, publish_date").order("publish_date",{ascending:!1}).limit(4),q.from("resource_kits").select("id, name, description, featured_image_url, publish_date").eq("is_published",!0).order("publish_date",{ascending:!1}).limit(4),q.from("academy_videos").select("id, title, description, thumbnail_url, duration, publish_date").eq("is_published",!0).order("publish_date",{ascending:!1}).limit(4),q.from("additional_services").select("id, name, description, preview_image_url, signup_link_url, publish_date").eq("is_published",!0).order("publish_date",{ascending:!1}).limit(4),q.from("dashboard_banners").select("id, title, description, image_url, link_url, link_text, placement, section_after").eq("is_active",!0).order("sort_order"),q.from("profiles").select("name").eq("id",s==null?void 0:s.id).single()]);(te=Ne.data)!=null&&te.name&&I(Ne.data.name);const Ye=((ae=he.data)==null?void 0:ae.map(nt=>nt.tag))||[],Ve=new Set(((le=Ce.data)==null?void 0:le.map(nt=>nt.app_id))||[]);g(Ve);const Qe=(((be=pe.data)==null?void 0:be.filter(nt=>!nt.required_tags||nt.required_tags.length===0?!0:nt.required_tags.some($e=>Ye.includes($e))))||[]).sort((nt,$e)=>nt.name==="LevelUp Members Portal"?-1:$e.name==="LevelUp Members Portal"?1:0);i(Qe.slice(0,6));const Ue=((me=Ae.data)==null?void 0:me.filter(nt=>fF(nt.event_date)!=="ended"))||[];o(Ue.slice(0,4)),j(Pe.data||[]),d(ze.data||[]),h(ke.data||[]),p(Ze.data||[]),y(Se.data||[]);const Xe=Fe.data||[];C(Xe.filter(nt=>nt.placement==="top")),P(Xe.filter(nt=>nt.placement==="between"))}catch(he){console.error("Error loading dashboard:",he),se.error("Failed to load dashboard data")}finally{O(!1)}},G=async te=>{var le,be,me;if(te.target_url.startsWith("/")){q.from("activity_logs").insert({user_id:s==null?void 0:s.id,app_id:te.app_id,app_name:te.name,user_agent:navigator.userAgent}).then(()=>{}),n(te.target_url);return}const ae=window.open("about:blank","_blank");try{await q.from("activity_logs").insert({user_id:s==null?void 0:s.id,app_id:te.app_id,app_name:te.name,user_agent:navigator.userAgent});let{data:he}=await q.auth.getSession();(le=he.session)!=null&&le.access_token||(he=(await q.auth.refreshSession()).data);const pe=(be=he==null?void 0:he.session)==null?void 0:be.access_token;if(!pe){ae==null||ae.close(),se.error("Your session expired — please sign in again to launch this app.");return}const{data:Ce,error:Ae}=await q.functions.invoke("sso-launch",{body:{app_id:te.app_id},headers:{Authorization:`Bearer ${pe}`}});if(Ae)throw Ae;Ce!=null&&Ce.redirect_url?ae&&!ae.closed?(ae.location.href=Ce.redirect_url,(me=ae.focus)==null||me.call(ae)):window.location.assign(Ce.redirect_url):(ae==null||ae.close(),se.error("Launch link unavailable"))}catch(he){ae==null||ae.close(),console.error("Error launching app:",he),se.error("Failed to launch app")}},$={"Newsletter Pro":"newsletter","Social AutoPilot":"social","Staging Studio":"marketing_studio",SigFlow:"marketing_studio","Agent Review":"marketing_studio",AgentReview:"marketing_studio"},H=a.filter(te=>{const ae=$[te.name]||$[te.app_id];return!ae||r(ae)}),Y=te=>E.filter(ae=>ae.section_after===te),Z=(M||((ie=s==null?void 0:s.user_metadata)==null?void 0:ie.name)||"there").split(" ")[0],ne=Date.now()+7*24*60*60*1e3,ce=l.filter(te=>new Date(te.event_date).getTime()<=ne).length;return e.jsxs(zs,{title:"Dashboard",children:[r("learn")&&e.jsx(NUs,{events:l,registrations:b,onNavigateToEvents:()=>n("/events")}),e.jsx(yUs,{}),e.jsx(bUs,{}),e.jsx(_Us,{}),e.jsx(cqs,{name:Z,eventsThisWeek:ce}),e.jsx(CUs,{}),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(yqs,{})}),r("learn")&&e.jsx(_qs,{events:l,registrations:b})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 mb-8 lg:grid-cols-3",children:[e.jsx(qzt,{}),r("deals")&&e.jsx(wqs,{}),r("learn")&&e.jsx(GUs,{})]}),e.jsx(jqs,{}),S.length>0&&e.jsx("div",{className:"mb-8",children:e.jsx(VY,{banners:S})}),e.jsx(UUs,{}),D?e.jsx("div",{className:"mb-10 grid grid-cols-2 gap-4 md:grid-cols-4",children:[0,1,2,3].map(te=>e.jsx("div",{className:"h-44 rounded-2xl bg-muted/40 animate-pulse"},te))}):e.jsx(Nqs,{videos:(r("learn")?m:[]).map(te=>({id:te.id,title:te.title,image:te.thumbnail_url,meta:te.duration,onOpen:()=>n(`/academy/${te.id}`)})),kits:(r("learn")?u:[]).map(te=>({id:te.id,title:te.name,image:te.featured_image_url,onOpen:()=>n(`/toolbox/${te.id}`)})),templates:(r("marketing_studio")?c:[]).map(te=>({id:te.id,title:te.name,image:te.preview_image_url,onOpen:()=>n("/templates")})),services:f.map(te=>({id:te.id,title:te.name,image:te.preview_image_url,onOpen:()=>window.open(te.signup_link_url,"_blank")}))}),Y("academy").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(VY,{banners:Y("academy")})}),r("listing_exchange")&&e.jsx("div",{className:"mb-10",children:e.jsx(HUs,{})}),H.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(B,{variant:"ghost",size:"sm",onClick:()=>n("/apps"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(La,{className:"h-4 w-4"})]})]}),H.length===0?e.jsx(ve,{className:"bg-muted/30 border-dashed",children:e.jsx(Me,{className:"flex items-center justify-center py-12",children:e.jsxs("div",{className:"text-center",children:[e.jsx(C0,{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:H.map(te=>{const ae=v.has(te.id);return e.jsxs("div",{onClick:()=>G(te),className:"hub-card group flex items-start gap-4 p-5 cursor-pointer",children:[e.jsx("div",{className:"flex-shrink-0 w-14 h-14 rounded-xl bg-primary/10 flex items-center justify-center text-3xl",children:te.icon}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-semibold text-foreground group-hover:text-primary transition-colors truncate",children:te.name}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:te.description})]}),ae&&e.jsx(C0,{className:"h-5 w-5 text-primary fill-current flex-shrink-0"})]},te.id)})})]}),Y("templates").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(VY,{banners:Y("templates")})}),Y("events").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(VY,{banners:Y("events")})}),Y("toolbox").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(VY,{banners:Y("toolbox")})})]})},Sqs=[{key:"contacts",label:"Contacts",icon:_a,description:"View, add, and edit contacts"},{key:"pipeline",label:"Deal Pipeline",icon:XM,description:"View, add, and move deals"},{key:"client_portal",label:"Client Portals",icon:wy,description:"Manage client portals on deals"},{key:"videos",label:"Videos",icon:Kr,description:"View and upload videos"},{key:"listings",label:"Listings",icon:Jr,description:"View, create, and edit listings"},{key:"scorecard",label:"Scorecard",icon:qf,description:"View and add transactions"},{key:"popbys",label:"Pop-bys",icon:Xa,description:"View and log pop-bys"},{key:"digital_card",label:"Digital Card",icon:_y,description:"Create and edit digital business card"},{key:"guest_book",label:"Guest Book",icon:Sx,description:"Manage open house guest books"},{key:"presentations",label:"Presentations",icon:jv,description:"Create and manage smart presentations"}];function Cqs(){var P;const{user:s}=hs(),[t,n]=_.useState([]),[r,a]=_.useState(!0),[i,l]=_.useState(!1),[o,c]=_.useState(!1),[d,u]=_.useState(null),[h,m]=_.useState({email:"",name:"",password:""}),[p,f]=_.useState("create"),[y,v]=_.useState(!1),[g,b]=_.useState(null);_.useEffect(()=>{s&&j()},[s]);const j=async()=>{if(s){a(!0);try{const{data:M,error:I}=await q.from("agent_assistant_assignments").select("id, assistant_id, permissions, created_at").eq("agent_id",s.id);if(I)throw I;if(M&&M.length>0){const D=M.map(G=>G.assistant_id),{data:O}=await q.from("profiles").select("id, name, email").in("id",D),V=M.map(G=>{const $=O==null?void 0:O.find(H=>H.id===G.assistant_id);return{...G,permissions:G.permissions,assistant_profile:$?{name:$.name||"",email:$.email||""}:void 0}});n(V)}else n([])}catch(M){console.error("Error loading assistants:",M)}finally{a(!1)}}},S=async()=>{if(s){if(p==="link"){if(!h.email.trim()){se.error("Please enter the assistant's email");return}v(!0);try{const{data:{session:M}}=await q.auth.getSession();if(!M)throw new Error("Not authenticated");const{data:I,error:D}=await q.from("profiles").select("id, name, email").eq("email",h.email.trim().toLowerCase()).single();if(D||!I){se.error("No account found with that email. Try creating a new assistant instead.");return}const{data:O}=await q.from("agent_assistant_assignments").select("id").eq("agent_id",s.id).eq("assistant_id",I.id);if(O&&O.length>0){se.error("This assistant is already assigned to you");return}const V=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})}),G=await V.json();if(!V.ok)throw new Error(G.error||"Failed to assign assistant role");const{error:$}=await q.from("agent_assistant_assignments").insert({agent_id:s.id,assistant_id:I.id,permissions:{contacts:!0,pipeline:!0,videos:!1,listings:!1,scorecard:!1,popbys:!1,digital_card:!1,client_portal:!1,guest_book:!1,presentations:!1}});if($)throw $;se.success(`${I.name||I.email} linked as your assistant`),l(!1),m({email:"",name:"",password:""}),j()}catch(M){console.error("Error linking assistant:",M),se.error(M.message||"Failed to link assistant")}finally{v(!1)}return}if(!h.email.trim()||!h.name.trim()||!h.password.trim()){se.error("Please fill in all fields");return}if(h.password.length<6){se.error("Password must be at least 6 characters");return}v(!0);try{const{data:{session:M}}=await q.auth.getSession();if(!M)throw new Error("Not authenticated");const I=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${M.access_token}`},body:JSON.stringify({email:h.email.trim(),password:h.password,name:h.name.trim(),purpose:"assistant"})}),D=await I.json();if(!I.ok)throw new Error(D.error||"Failed to create assistant account");const O=D.userId||D.id;if(!O)throw new Error("No user ID returned");const V=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:O,role:"assistant",action:"add",agentId:s.id})}),G=await V.json();if(!V.ok)throw new Error(G.error||"Failed to assign assistant role");const{error:$}=await q.from("agent_assistant_assignments").insert({agent_id:s.id,assistant_id:O,permissions:{contacts:!0,pipeline:!0,videos:!1,listings:!1,scorecard:!1,popbys:!1,digital_card:!1,client_portal:!1,guest_book:!1,presentations:!1}});if($)throw $;se.success(`Assistant account created for ${h.name.trim()}`),l(!1),m({email:"",name:"",password:""}),j()}catch(M){console.error("Error adding assistant:",M),se.error(M.message||"Failed to add assistant")}finally{v(!1)}}},C=async()=>{if(!(!d||!s))try{const{data:{session:M}}=await q.auth.getSession();if(!M)throw new Error("Not authenticated");const{error:I}=await q.from("agent_assistant_assignments").delete().eq("id",d.id);if(I)throw I;const{data:D}=await q.from("agent_assistant_assignments").select("id").eq("assistant_id",d.assistant_id);(!D||D.length===0)&&await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${M.access_token}`},body:JSON.stringify({userId:d.assistant_id,role:"assistant",action:"remove"})}),se.success("Assistant removed"),c(!1),u(null),j()}catch(M){console.error("Error removing assistant:",M),se.error(M.message||"Failed to remove assistant")}},E=async(M,I,D)=>{b(M);try{const O=t.find($=>$.id===M);if(!O)return;const V={...O.permissions,[I]:D},{error:G}=await q.from("agent_assistant_assignments").update({permissions:V}).eq("id",M);if(G)throw G;n($=>$.map(H=>H.id===M?{...H,permissions:V}:H))}catch(O){console.error("Error updating permissions:",O),se.error("Failed to update permissions")}finally{b(null)}};return r?e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(In,{className:"h-5 w-5"}),"My Assistants"]})}),e.jsx(Me,{children:e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(In,{className:"h-5 w-5"}),"My Assistants"]}),e.jsx(kn,{children:"Add assistants to help manage your Agent OS"})]}),e.jsxs(B,{size:"sm",onClick:()=>{f("create"),l(!0)},children:[e.jsx(rn,{className:"h-4 w-4 mr-1"}),"Add Assistant"]})]})}),e.jsx(Me,{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,O,V;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(ja,{className:"h-10 w-10",children:e.jsx(Na,{children:((D=(I=M.assistant_profile)==null?void 0:I.name)==null?void 0:D.split(" ").map(G=>G[0]).join("").toUpperCase())||"A"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((O=M.assistant_profile)==null?void 0:O.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:((V=M.assistant_profile)==null?void 0:V.email)||""})]}),e.jsxs(Oe,{variant:"secondary",className:"ml-2",children:[e.jsx(Rm,{className:"h-3 w-3 mr-1"}),"Assistant"]})]}),e.jsx(B,{variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive",onClick:()=>{u(M),c(!0)},children:e.jsx(Sn,{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:Sqs.map(G=>{const $=G.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($,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:G.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:G.description})]})]}),e.jsx(fn,{checked:M.permissions[G.key]||!1,onCheckedChange:H=>E(M.id,G.key,H),disabled:g===M.id})]},G.key)})})]})]},M.id)})})})]}),e.jsx(Ls,{open:i,onOpenChange:l,children:e.jsxs(Ps,{children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Add Assistant"}),e.jsx(_r,{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(B,{variant:p==="create"?"default":"outline",size:"sm",onClick:()=>f("create"),children:[e.jsx(rn,{className:"h-3 w-3 mr-1"}),"Create New"]}),e.jsxs(B,{variant:p==="link"?"default":"outline",size:"sm",onClick:()=>f("link"),children:[e.jsx(Vc,{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(J,{htmlFor:"assistant-name",children:"Name"}),e.jsx(xe,{id:"assistant-name",value:h.name,onChange:M=>m({...h,name:M.target.value}),placeholder:"Assistant's full name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"assistant-email",children:"Email"}),e.jsx(xe,{id:"assistant-email",type:"email",value:h.email,onChange:M=>m({...h,email:M.target.value}),placeholder:"assistant@email.com"})]}),p==="create"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"assistant-password",children:"Temporary Password"}),e.jsx(xe,{id:"assistant-password",type:"password",value:h.password,onChange:M=>m({...h,password:M.target.value}),placeholder:"Min 6 characters"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Your assistant can change this after their first login."})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsxs(B,{onClick:S,disabled:y,children:[y&&e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),p==="create"?"Create Assistant":"Link Assistant"]})]})]})}),e.jsx(Kl,{open:o,onOpenChange:c,children:e.jsxs(Ol,{children:[e.jsxs(zl,{children:[e.jsx(Ul,{children:"Remove Assistant?"}),e.jsxs(ql,{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($l,{children:"Cancel"}),e.jsx(Ml,{onClick:C,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})})]})}function rv(s){this.content=s}rv.prototype={constructor:rv,find:function(s){for(var t=0;t>1}};rv.from=function(s){if(s instanceof rv)return s;var t=[];if(s)for(var n in s)t.push(n,s[n]);return new rv(t)};function $zt(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=$zt(a.content,i.content,n+1);if(l!=null)return l}n+=a.nodeSize}}function Vzt(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 Z1(r,a)}cutByIndex(t,n){return t==n?Z1.empty:t==0&&n==this.content.length?this:new Z1(this.content.slice(t,n))}replaceChild(t,n){let r=this.content[t];if(r==n)return this;let a=this.content.slice(),i=this.size+n.nodeSize-r.nodeSize;return a[t]=n,new Z1(a,i)}addToStart(t){return new Z1([t].concat(this.content),this.size+t.nodeSize)}addToEnd(t){return new Z1(this.content.concat(t),this.size+t.nodeSize)}eq(t){if(this.content.length!=t.content.length)return!1;for(let n=0;nthis.size||t<0)throw new RangeError(`Position ${t} outside of fragment (${this})`);for(let n=0,r=0;;n++){let a=this.child(n),i=r+a.nodeSize;if(i>=t)return i==t?Fle(n+1,i):Fle(n,r);r=i}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(t=>t.toJSON()):null}static fromJSON(t,n){if(!n)return Z1.empty;if(!Array.isArray(n))throw new RangeError("Invalid input for Fragment.fromJSON");return new Z1(n.map(t.nodeFromJSON))}static fromArray(t){if(!t.length)return Z1.empty;let n,r=0;for(let a=0;athis.type.rank&&(n||(n=t.slice(0,a)),n.push(this),r=!0),n&&n.push(i)}}return n||(n=t.slice()),r||n.push(this),n}removeFromSet(t){for(let n=0;nr.type.rank-a.type.rank),n}};Tm.none=[];class LAe extends Error{}class Pi{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=Gzt(this.content,t+this.openStart,n);return r&&new Pi(r,this.openStart,this.openEnd)}removeBetween(t,n){return new Pi(Hzt(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 Pi.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 Pi(Ha.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 Pi(t,r,a)}}Pi.empty=new Pi(Ha.empty,0,0);function Hzt(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(Hzt(i.content,t-a-1,n-a-1)))}function Gzt(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=Gzt(l.content,t-i-1,n,l);return o&&s.replaceChild(a,l.copy(o))}function Aqs(s,t,n){if(n.openStart>s.depth)throw new LAe("Inserted content deeper than insertion position");if(s.depth-n.openStart!=t.depth-n.openEnd)throw new LAe("Inconsistent open depths");return Wzt(s,t,n,0)}function Wzt(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 MJ(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&&(g7(s.nodeAfter,r),i++));for(let o=i;oa&&MVe(s,t,a+1),l=r.depth>a&&MVe(n,r,a+1),o=[];return MJ(null,s,a,o),i&&l&&t.index(a)==n.index(a)?(Kzt(i,l),g7(y7(i,Yzt(s,t,n,r,a+1)),o)):(i&&g7(y7(i,IAe(s,t,a+1)),o),MJ(t,n,a,o),l&&g7(y7(l,IAe(n,r,a+1)),o)),MJ(r,null,a,o),new Ha(o)}function IAe(s,t,n){let r=[];if(MJ(null,s,n,r),s.depth>n){let a=MVe(s,t,n+1);g7(y7(a,IAe(s,t,n+1)),r)}return MJ(t,null,n,r),new Ha(r)}function Eqs(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(Ha.from(a));return{start:a.resolveNoCache(s.openStart+n),end:a.resolveNoCache(a.content.size-s.openEnd-n)}}class fte{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 DAe(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 fte(n,r,i)}static resolveCached(t,n){let r=Sgt.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()+")"),Zzt(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=Ha.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=Ha.fromJSON(t,n.content),i=t.nodeType(n.type).create(n.attrs,a,r);return i.type.checkAttrs(i.attrs),i}};dP.prototype.text=void 0;class RAe extends dP{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):Zzt(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 RAe(this.type,this.attrs,this.text,t)}withText(t){return t==this.text?this:new RAe(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 Zzt(s,t){for(let n=s.length-1;n>=0;n--)t=s[n].type.name+"("+t+")";return t}class J7{constructor(t){this.validEnd=t,this.next=[],this.wrapCache=[]}static parse(t,n){let r=new Lqs(t,n);if(r.next==null)return J7.empty;let a=Xzt(r);r.next&&r.err("Unexpected trailing text");let i=Bqs(zqs(a));return Uqs(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(` `)}}J7.empty=new J7(!0);class Lqs{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 Xzt(s){let t=[];do t.push(Iqs(s));while(s.eat("|"));return t.length==1?t[0]:{type:"choice",exprs:t}}function Iqs(s){let t=[];do t.push(Dqs(s));while(s.next&&s.next!=")"&&s.next!="|");return t.length==1?t[0]:{type:"seq",exprs:t}}function Dqs(s){let t=Oqs(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=Rqs(s,t);else break;return t}function Cgt(s){/\D/.test(s.next)&&s.err("Expected number, got '"+s.next+"'");let t=Number(s.next);return s.pos++,t}function Rqs(s,t){let n=Cgt(s),r=n;return s.eat(",")&&(s.next!="}"?r=Cgt(s):r=-1),s.eat("}")||s.err("Unclosed braced range"),{type:"range",min:n,max:r,expr:t}}function Fqs(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 Oqs(s){if(s.eat("(")){let t=Xzt(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=Fqs(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 zqs(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 J7(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:eBt(this.attrs,t)}create(t=null,n,r){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new dP(this,this.computeAttrs(t),Ha.from(n),Tm.setFrom(r))}createChecked(t=null,n,r){return n=Ha.from(n),this.checkContent(n),new dP(this,this.computeAttrs(t),n,Tm.setFrom(r))}createAndFill(t=null,n,r){if(t=this.computeAttrs(t),n=Ha.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(Ha.empty,!0);return i?new dP(this,t,n.append(i),Tm.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 nBt(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 qqs(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 $qs{constructor(t,n,r){this.hasDefault=Object.prototype.hasOwnProperty.call(r,"default"),this.default=r.default,this.validate=typeof r.validate=="string"?qqs(t,n,r.validate):r.validate}get isRequired(){return!this.hasDefault}}class pLe{constructor(t,n,r,a){this.name=t,this.rank=n,this.schema=r,this.spec=a,this.attrs=sBt(t,a.attrs),this.excluded=null;let i=Jzt(this.attrs);this.instance=i?new Tm(this,i):null}create(t=null){return!t&&this.instance?this.instance:new Tm(this,eBt(this.attrs,t))}static compile(t,n){let r=Object.create(null),a=0;return t.forEach((i,l)=>r[i]=new pLe(i,a++,n,l)),r}removeFromSet(t){for(var n=0;n-1}}let rBt=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=rv.from(t.nodes),n.marks=rv.from(t.marks||{}),this.nodes=Egt.compile(this.spec.nodes,this),this.marks=pLe.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]=J7.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?Tgt(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==""?[]:Tgt(this,l.split(" "))}this.nodeFromJSON=a=>dP.fromJSON(this,a),this.markFromJSON=a=>Tm.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 Egt){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 RAe(r,r.defaultAttrs,t,Tm.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 Tgt(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 Vqs(s){return s.tag!=null}function Hqs(s){return s.style!=null}let PJ=class LVe{constructor(t,n){this.schema=t,this.rules=n,this.tags=[],this.styles=[];let r=this.matchedStyles=[];n.forEach(a=>{if(Vqs(a))this.tags.push(a);else if(Hqs(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 Pgt(this,n,!1);return r.addAll(t,Tm.none,n.from,n.to),r.finish()}parseSlice(t,n={}){let r=new Pgt(this,n,!0);return r.addAll(t,Tm.none,n.from,n.to),Pi.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=Lgt(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=Lgt(l)),l.node||l.ignore||l.mark||(l.node=a)})}return n}static fromSchema(t){return t.cached.domParser||(t.cached.domParser=new LVe(t,LVe.schemaRules(t)))}};const aBt={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},Gqs={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},iBt={ol:!0,ul:!0},xte=1,IVe=2,LJ=4;function Mgt(s,t,n){return t!=null?(t?xte:0)|(t==="full"?IVe:0):s&&s.whitespace=="pre"?xte|IVe:n&~LJ}class Ole{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=Tm.none,this.match=i||(l&LJ?null:t.contentMatch)}findWrapping(t){if(!this.match){if(!this.type)return[];let n=this.type.contentMatch.fillBefore(Ha.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&xte)){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=Ha.from(this.content);return!t&&this.match&&(n=n.append(this.match.fillBefore(Ha.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&&!aBt.hasOwnProperty(t.parentNode.nodeName.toLowerCase())}}class Pgt{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=Mgt(null,n.preserveWhitespace,0)|(r?LJ:0);a?i=new Ole(a.type,a.attrs,Tm.none,!0,n.topMatch||a.type.contentMatch,l):r?i=new Ole(null,null,Tm.none,!0,null,l):i=new Ole(t.schema.topNodeType,null,Tm.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&IVe?"full":this.localPreserveWS||(a.options&xte)>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):Igt(d.type,t))?(c=d.addToSet(c),!1):!0),this.nodes.push(new Ole(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|=xte)}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 Wqs(s){for(let t=s.firstChild,n=null;t;t=t.nextSibling){let r=t.nodeType==1?t.nodeName.toLowerCase():null;r&&iBt.hasOwnProperty(r)&&n?(n.appendChild(t),t=n):r=="li"?n=t:r&&(n=null)}}function Kqs(s,t){return(s.matches||s.msMatchesSelector||s.webkitMatchesSelector||s.mozMatchesSelector).call(s,t)}function Lgt(s){let t={};for(let n in s)t[n]=s[n];return t}function Igt(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&&O4e(c7e(r),a(t,n),null,t.attrs)}static renderSpec(t,n,r=null,a){return O4e(t,n,r,a)}static fromSchema(t){return t.cached.domSerializer||(t.cached.domSerializer=new H9(this.nodesFromSchema(t),this.marksFromSchema(t)))}static nodesFromSchema(t){let n=Dgt(t.nodes);return n.text||(n.text=r=>r.text),n}static marksFromSchema(t){return Dgt(t.marks)}}function Dgt(s){let t={};for(let n in s){let r=s[n].spec.toDOM;r&&(t[n]=r)}return t}function c7e(s){return s.document||window.document}const Rgt=new WeakMap;function Yqs(s){let t=Rgt.get(s);return t===void 0&&Rgt.set(s,t=Zqs(s)),t}function Zqs(s){let t=null;function n(r){if(r&&typeof r=="object")if(Array.isArray(r))if(typeof r[0]=="string")t||(t=[]),t.push(r);else for(let a=0;a-1)throw new RangeError("Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.");let l=a.indexOf(" ");l>0&&(n=a.slice(0,l),a=a.slice(l+1));let o,c=n?s.createElementNS(n,a):s.createElement(a),d=t[1],u=1;if(d&&typeof d=="object"&&d.nodeType==null&&!Array.isArray(d)){u=2;for(let h in d)if(d[h]!=null){let m=h.indexOf(" ");m>0?c.setAttributeNS(h.slice(0,m),h.slice(m+1),d[h]):h=="style"&&c.style?c.style.cssText=d[h]:c.setAttribute(h,d[h])}}for(let h=u;hu)throw new RangeError("Content hole must be the only child of its parent node");return{dom:c,contentDOM:c}}else{let{dom:p,contentDOM:f}=O4e(s,m,n,r);if(c.appendChild(p),f){if(o)throw new RangeError("Multiple content holes");o=f}}}return{dom:c,contentDOM:o}}const oBt=65535,lBt=Math.pow(2,16);function Xqs(s,t){return s+t*lBt}function Fgt(s){return s&oBt}function Qqs(s){return(s-(s&oBt))/lBt}const cBt=1,dBt=2,z4e=4,uBt=8;class DVe{constructor(t,n,r){this.pos=t,this.delInfo=n,this.recover=r}get deleted(){return(this.delInfo&uBt)>0}get deletedBefore(){return(this.delInfo&(cBt|z4e))>0}get deletedAfter(){return(this.delInfo&(dBt|z4e))>0}get deletedAcross(){return(this.delInfo&z4e)>0}}class Xw{constructor(t,n=!1){if(this.ranges=t,this.inverted=n,!t.length&&Xw.empty)return Xw.empty}recover(t){let n=0,r=Fgt(t);if(!this.inverted)for(let a=0;at)break;let d=this.ranges[o+i],u=this.ranges[o+l],h=c+d;if(t<=h){let m=d?t==c?-1:t==h?1:n:n,p=c+a+(m<0?0:u);if(r)return p;let f=t==(n<0?c:h)?null:Xqs(o/3,t-c),y=t==c?dBt:t==h?cBt:z4e;return(n<0?t!=c:t!=h)&&(y|=uBt),new DVe(p,y,f)}a+=u-d}return r?t+a:new DVe(t+a,0,null)}touches(t,n){let r=0,a=Fgt(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 gte;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 Ig.fromReplace(t,this.from,this.to,i)}invert(){return new M4(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 bM(n.pos,r.pos,this.mark)}merge(t){return t instanceof bM&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from?new bM(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 bM(n.from,n.to,t.markFromJSON(n.mark))}}N1.jsonID("addMark",bM);class M4 extends N1{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 Pi(wet(n.content,a=>a.mark(this.mark.removeFromSet(a.marks)),t),n.openStart,n.openEnd);return Ig.fromReplace(t,this.from,this.to,r)}invert(){return new bM(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 M4(n.pos,r.pos,this.mark)}merge(t){return t instanceof M4&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from?new M4(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 M4(n.from,n.to,t.markFromJSON(n.mark))}}N1.jsonID("removeMark",M4);class _M extends N1{constructor(t,n){super(),this.pos=t,this.mark=n}apply(t){let n=t.nodeAt(this.pos);if(!n)return Ig.fail("No node at mark step's position");let r=n.type.create(n.attrs,null,this.mark.addToSet(n.marks));return Ig.fromReplace(t,this.pos,this.pos+1,new Pi(Ha.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 Ay(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 Ay(n.from,n.to,n.gapFrom,n.gapTo,Pi.fromJSON(t,n.slice),n.insert,!!n.structure)}}N1.jsonID("replaceAround",Ay);function RVe(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 Jqs(s,t,n,r){let a=[],i=[],l,o;s.doc.nodesBetween(t,n,(c,d,u)=>{if(!c.isInline)return;let h=c.marks;if(!r.isInSet(h)&&u.type.allowsMarkType(r.type)){let m=Math.max(d,t),p=Math.min(d+c.nodeSize,n),f=r.addToSet(h);for(let y=0;ys.step(c)),i.forEach(c=>s.step(c))}function e$s(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 pLe){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 M4(l.from,l.to,l.style)))}function jet(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 t$s(s,t,n){return(t==0||s.canReplace(t,s.childCount))&&(n==s.childCount||s.canReplace(0,n))}function wW(s){let n=s.parent.content.cutByIndex(s.startIndex,s.endIndex);for(let r=s.depth,a=0,i=0;;--r){let l=s.$from.node(r),o=s.$from.index(r)+a,c=s.$to.indexAfter(r)-i;if(rn;f--)y||r.index(f)>0?(y=!0,u=Ha.from(r.node(f).copy(u)),h++):c--;let m=Ha.empty,p=0;for(let f=i,y=!1;f>n;f--)y||a.after(f+1)=0;l--){if(r.size){let o=n[l].type.contentMatch.matchFragment(r);if(!o||!o.validEnd)throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper")}r=Ha.from(n[l].type.create(n[l].attrs,r))}let a=t.start,i=t.end;s.step(new Ay(a,i,a,i,new Pi(r,0,0),n.length,!0))}function i$s(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)&&o$s(s.doc,s.mapping.slice(i).map(o),r)){let d=null;if(r.schema.linebreakReplacement){let p=r.whitespace=="pre",f=!!r.contentMatch.matchType(r.schema.linebreakReplacement);p&&!f?d=!1:!p&&f&&(d=!0)}d===!1&&mBt(s,l,o,i),jet(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 Ay(h,m,h+1,m-1,new Pi(Ha.from(r.create(c,null,l.marks)),0,0),1,!0)),d===!0&&hBt(s,l,o,i),!1}})}function hBt(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 mBt(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 o$s(s,t,n){let r=s.resolve(t),a=r.index();return r.parent.canReplaceWith(a,a+1,n)}function l$s(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 Ay(t,t+i.nodeSize,t+1,t+i.nodeSize-1,new Pi(Ha.from(l),0,0),1,!0))}function C$(s,t,n=1,r){let a=s.resolve(t),i=a.depth-n,l=r&&r[r.length-1]||a.parent;if(i<0||a.parent.type.spec.isolating||!a.parent.canReplace(a.index(),a.parent.childCount)||!l.type.validContent(a.parent.content.cutByIndex(a.index(),a.parent.childCount)))return!1;for(let d=a.depth-1,u=n-2;d>i;d--,u--){let h=a.node(d),m=a.index(d);if(h.type.spec.isolating)return!1;let p=h.content.cutByIndex(m,h.childCount),f=r&&r[u+1];f&&(p=p.replaceChild(0,f.type.create(f.attrs)));let y=r&&r[u]||h;if(!h.canReplace(m+1,h.childCount)||!y.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 c$s(s,t,n=1,r){let a=s.doc.resolve(t),i=Ha.empty,l=Ha.empty;for(let o=a.depth,c=a.depth-n,d=n-1;o>c;o--,d--){i=Ha.from(a.node(o).copy(i));let u=r&&r[d];l=Ha.from(u?u.type.create(u.attrs,l):a.node(o).copy(l))}s.step(new Eg(t,t,new Pi(i.append(l),n,n),!0))}function pL(s,t){let n=s.resolve(t),r=n.index();return pBt(n.nodeBefore,n.nodeAfter)&&n.parent.canReplace(r,r+1)}function d$s(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&&pBt(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 u$s(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);mBt(s,u.node(),u.before(),o)}l.inlineContent&&jet(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 Eg(d,c.map(t+n,-1),Pi.empty,!0)),r===!0){let u=s.doc.resolve(d);hBt(s,u.node(),u.before(),s.steps.length)}return s}function h$s(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 xLe(s,t,n=t,r=Pi.empty){if(t==n&&!r.size)return null;let a=s.resolve(t),i=s.resolve(n);return xBt(a,i,r)?new Eg(t,n,r):new m$s(a,i,r).fit()}function xBt(s,t,n){return!n.openStart&&!n.openEnd&&s.start()==t.start()&&s.parent.canReplace(s.index(),t.index(),n.content)}class m$s{constructor(t,n,r){this.$from=t,this.$to=n,this.unplaced=r,this.frontier=[],this.placed=Ha.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=Ha.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 Pi(i,l,o);return t>-1?new Ay(r.pos,t,this.$to.pos,this.$to.end(),c,n):c.size||r.pos!=this.$to.pos?new Eg(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=u7e(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(Ha.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=u7e(t,n);return!a.childCount||a.firstChild.isLeaf?!1:(this.unplaced=new Pi(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=u7e(t,n);if(a.childCount<=1&&n>0){let i=t.size-n<=n+a.size;this.unplaced=new Pi(fX(t,n-1,1),n-1,i?n-1:r)}else this.unplaced=new Pi(fX(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 y=0;y1||c==0||y.content.size)&&(h=v,u.push(gBt(y.mark(m.allowedMarks(y.marks)),d==1?c:0,d==o.childCount?p:-1)))}let f=d==o.childCount;f||(p=-1),this.placed=xX(this.placed,n,Ha.from(u)),this.frontier[n].match=h,f&&p<0&&r&&r.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let y=0,v=o;y1&&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=h7e(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=xX(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=xX(this.placed,this.depth,Ha.from(t.create(n,r))),this.frontier.push({type:t,match:t.contentMatch})}closeFrontierNode(){let n=this.frontier.pop().match.fillBefore(Ha.empty,!0);n.childCount&&(this.placed=xX(this.placed,this.frontier.length,n))}}function fX(s,t,n){return t==0?s.cutByIndex(n,s.childCount):s.replaceChild(0,s.firstChild.copy(fX(s.firstChild.content,t-1,n)))}function xX(s,t,n){return t==0?s.append(n):s.replaceChild(s.childCount-1,s.lastChild.copy(xX(s.lastChild.content,t-1,n)))}function u7e(s,t){for(let n=0;n1&&(r=r.replaceChild(0,gBt(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(Ha.empty,!0)))),s.copy(r)}function h7e(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&&!p$s(n,i.content,l)?o:null}function p$s(s,t,n){for(let r=n;r0;m--,p--){let f=a.node(m).type.spec;if(f.defining||f.definingAsContext||f.isolating)break;l.indexOf(m)>-1?o=m:a.before(m)==p&&l.splice(1,0,-m)}let c=l.indexOf(o),d=[],u=r.openStart;for(let m=r.content,p=0;;p++){let f=m.firstChild;if(d.push(f),p==r.openStart)break;m=f.content}for(let m=u-1;m>=0;m--){let p=d[m],f=f$s(p.type);if(f&&!p.sameMarkup(a.node(Math.abs(o)-1)))u=m;else if(f||!p.type.isTextblock)break}for(let m=r.openStart;m>=0;m--){let p=(m+u+1)%(r.openStart+1),f=d[p];if(f)for(let y=0;y=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 yBt(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(Ha.empty,!0))}return s}function g$s(s,t,n,r){if(!r.isInline&&t==n&&s.doc.resolve(t).parent.content.size){let a=h$s(s.doc,t,r.type);a!=null&&(t=n=a)}s.replaceRange(t,n,new Pi(Ha.from(r),0,0))}function y$s(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=vBt(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 vBt(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 A$ extends N1{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 Ig.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 Ig.fromReplace(t,this.pos,this.pos+1,new Pi(Ha.from(a),0,n.isLeaf?0:1))}getMap(){return Xw.empty}invert(t){return new A$(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 A$(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 A$(n.pos,n.attr,n.value)}}N1.jsonID("attr",A$);class yte extends N1{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 Ig.ok(r)}getMap(){return Xw.empty}invert(t){return new yte(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 yte(n.attr,n.value)}}N1.jsonID("docAttr",yte);let RH=class extends Error{};RH=function s(t){let n=Error.call(this,t);return n.__proto__=s.prototype,n};RH.prototype=Object.create(Error.prototype);RH.prototype.constructor=RH;RH.prototype.name="TransformError";let ket=class{constructor(t){this.doc=t,this.steps=[],this.docs=[],this.mapping=new gte}get before(){return this.docs.length?this.docs[0]:this.doc}step(t){let n=this.maybeStep(t);if(n.failed)throw new RH(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=Pi.empty){let a=xLe(this.doc,t,n,r);return a&&this.step(a),this}replaceWith(t,n,r){return this.replace(t,n,new Pi(Ha.from(r),0,0))}delete(t,n){return this.replace(t,n,Pi.empty)}insert(t,n){return this.replaceWith(t,t,n)}replaceRange(t,n,r){return x$s(this,t,n,r),this}replaceRangeWith(t,n,r){return g$s(this,t,n,r),this}deleteRange(t,n){return y$s(this,t,n),this}lift(t,n){return s$s(this,t,n),this}join(t,n=1){return u$s(this,t,n),this}wrap(t,n){return a$s(this,t,n),this}setBlockType(t,n=t,r,a=null){return i$s(this,t,n,r,a),this}setNodeMarkup(t,n,r=null,a){return l$s(this,t,n,r,a),this}setNodeAttribute(t,n,r){return this.step(new A$(t,n,r)),this}setDocAttribute(t,n){return this.step(new yte(t,n)),this}addNodeMark(t,n){return this.step(new _M(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 Tm)n.isInSet(r.marks)&&this.step(new e9(t,n));else{let a=r.marks,i,l=[];for(;i=n.isInSet(a);)l.push(new e9(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 c$s(this,t,n,r),this}addMark(t,n,r){return Jqs(this,t,n,r),this}removeMark(t,n,r){return e$s(this,t,n,r),this}clearIncompatible(t,n,r){return jet(this,t,n,r),this}};const m7e=Object.create(null);class Wl{constructor(t,n,r){this.$anchor=t,this.$head=n,this.ranges=r||[new bBt(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?yU(t.node(0),t.node(i),t.before(i+1),t.index(i),n,r):yU(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 yN(t.node(0))}static atStart(t){return yU(t,t,0,0,1)||new yN(t)}static atEnd(t){return yU(t,t,t.content.size,t.childCount,-1)||new yN(t)}static fromJSON(t,n){if(!n||!n.type)throw new RangeError("Invalid input for Selection.fromJSON");let r=m7e[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 m7e)throw new RangeError("Duplicate use of selection JSON ID "+t);return m7e[t]=n,n.prototype.jsonID=t,n}getBookmark(){return jl.between(this.$anchor,this.$head).getBookmark()}}Wl.prototype.visible=!0;class bBt{constructor(t,n){this.$from=t,this.$to=n}}let zgt=!1;function Bgt(s){!zgt&&!s.parent.inlineContent&&(zgt=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+s.parent.type.name+")"))}class jl extends Wl{constructor(t,n=t){Bgt(t),Bgt(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 Wl.near(r);let a=t.resolve(n.map(this.anchor));return new jl(a.parent.inlineContent?a:r,r)}replace(t,n=Pi.empty){if(super.replace(t,n),n==Pi.empty){let r=this.$from.marksAcross(this.$to);r&&t.ensureMarks(r)}}eq(t){return t instanceof jl&&t.anchor==this.anchor&&t.head==this.head}getBookmark(){return new gLe(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 jl(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=Wl.findFrom(n,r,!0)||Wl.findFrom(n,-r,!0);if(i)n=i.$head;else return Wl.near(n,r)}return t.parent.inlineContent||(a==0?t=n:(t=(Wl.findFrom(t,-r,!0)||Wl.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&&dl.isSelectable(o))return dl.create(s,n-(a<0?o.nodeSize:0))}else{let c=yU(s,o,n+a,a<0?o.childCount:0,a,i);if(c)return c}n+=o.nodeSize*a}return null}function Ugt(s,t,n){let r=s.steps.length-1;if(r{l==null&&(l=u)}),s.setSelection(Wl.near(s.doc.resolve(l),n))}const qgt=1,zle=2,$gt=4;class b$s extends ket{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|=zle,this}ensureMarks(t){return Tm.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&zle)>0}addStep(t,n){super.addStep(t,n),this.updated=this.updated&~zle,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)||Tm.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(Wl.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|=$gt,this}get scrolledIntoView(){return(this.updated&$gt)>0}}function Vgt(s,t){return!t||!s?s:s.bind(t)}class gX{constructor(t,n,r){this.name=t,this.init=Vgt(n.init,r),this.apply=Vgt(n.apply,r)}}const _$s=[new gX("doc",{init(s){return s.doc||s.schema.topNodeType.createAndFill()},apply(s){return s.doc}}),new gX("selection",{init(s,t){return s.selection||Wl.atStart(t.doc)},apply(s){return s.selection}}),new gX("storedMarks",{init(s){return s.storedMarks||null},apply(s,t,n,r){return r.selection.$cursor?s.storedMarks:null}}),new gX("scrollToSelection",{init(){return 0},apply(s,t){return s.scrolledIntoView?t+1:t}})];class p7e{constructor(t,n){this.schema=t,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=_$s.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 gX(r.key,r.spec.state,r))})}}class tq{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 p7e(t.schema,t.plugins),i=new tq(a);return a.fields.forEach(l=>{if(l.name=="doc")i.doc=dP.fromJSON(t.schema,n.doc);else if(l.name=="selection")i.selection=Wl.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 _Bt(s,t,n){for(let r in s){let a=s[r];a instanceof Function?a=a.bind(t):r=="handleDOMEvents"&&(a=_Bt(a,t,{})),n[r]=a}return n}class F0{constructor(t){this.spec=t,this.props={},t.props&&_Bt(t.props,this,this.props),this.key=t.key?t.key.key:wBt("plugin")}getState(t){return t[this.key]}}const f7e=Object.create(null);function wBt(s){return s in f7e?s+"$"+ ++f7e[s]:(f7e[s]=0,s+"$")}class k1{constructor(t="key"){this.key=wBt(t)}get(t){return t.config.pluginsByKey[this.key]}getState(t){return t[this.key]}}const cv=function(s){for(var t=0;;t++)if(s=s.previousSibling,!s)return t},FH=function(s){let t=s.assignedSlot||s.parentNode;return t&&t.nodeType==11?t.host:t};let FVe=null;const B3=function(s,t,n){let r=FVe||(FVe=document.createRange());return r.setEnd(s,n??s.nodeValue.length),r.setStart(s,t||0),r},w$s=function(){FVe=null},t9=function(s,t,n,r){return n&&(Hgt(s,t,n,r,-1)||Hgt(s,t,n,r,1))},j$s=/^(img|br|input|textarea|hr)$/i;function Hgt(s,t,n,r,a){for(var i;;){if(s==n&&t==r)return!0;if(t==(a<0?0:Y2(s))){let l=s.parentNode;if(!l||l.nodeType!=1||cae(s)||j$s.test(s.nodeName)||s.contentEditable=="false")return!1;t=cv(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?Y2(s):0}else return!1}}function Y2(s){return s.nodeType==3?s.nodeValue.length:s.childNodes.length}function N$s(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=Y2(s)}else if(s.parentNode&&!cae(s))t=cv(s),s=s.parentNode;else return null}}function k$s(s,t){for(;;){if(s.nodeType==3&&t2),B2=OH||(dC?/Mac/.test(dC.platform):!1),kBt=dC?/Win/.test(dC.platform):!1,IA=/Android \d/.test(fL),dae=!!Ggt&&"webkitFontSmoothing"in Ggt.documentElement.style,E$s=dae?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function T$s(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 m3(s,t){return typeof s=="number"?s:s[t]}function M$s(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 Wgt(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=FH(l);continue}let o=l,c=o==i.body,d=c?T$s(i):M$s(o),u=0,h=0;if(t.topd.bottom-m3(r,"bottom")&&(h=t.bottom-t.top>d.bottom-d.top?t.top+m3(a,"top")-d.top:t.bottom-d.bottom+m3(a,"bottom")),t.leftd.right-m3(r,"right")&&(u=t.right-d.right+m3(a,"right")),u||h)if(c)i.defaultView.scrollBy(u,h);else{let p=o.scrollLeft,f=o.scrollTop;h&&(o.scrollTop+=h),u&&(o.scrollLeft+=u);let y=o.scrollLeft-p,v=o.scrollTop-f;t={left:t.left-y,top:t.top-v,right:t.right-y,bottom:t.bottom-v}}let m=c?"fixed":getComputedStyle(l).position;if(/^(fixed|sticky)$/.test(m))break;l=m=="absolute"?l.offsetParent:FH(l)}}function P$s(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:SBt(s.dom)}}function SBt(s){let t=[],n=s.ownerDocument;for(let r=s;r&&(t.push({dom:r,top:r.scrollTop,left:r.scrollLeft}),s!=n);r=FH(r));return t}function L$s({refDOM:s,refTop:t,stack:n}){let r=s?s.getBoundingClientRect().top:0;CBt(n,r==0?0:r-t)}function CBt(s,t){for(let n=0;n=o){l=Math.max(f.bottom,l),o=Math.min(f.top,o);let y=f.left>t.left?f.left-t.left:f.right=(f.left+f.right)/2?1:0));continue}}else f.top>t.top&&!c&&f.left<=t.left&&f.right>=t.left&&(c=u,d={left:Math.max(f.left,Math.min(f.right,t.left)),top:f.top});!n&&(t.left>=f.right&&t.top>=f.top||t.left>=f.left&&t.top>=f.bottom)&&(i=h+1)}}return!n&&c&&(n=c,a=d,r=0),n&&n.nodeType==3?D$s(n,a):!n||r&&n.nodeType==1?{node:s,offset:i}:ABt(n,a)}function D$s(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 Aet(s,t){return s.left>=t.left-1&&s.left<=t.right+1&&s.top>=t.top-1&&s.top<=t.bottom+1}function R$s(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 O$s(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 EBt(s,t,n){let r=s.childNodes.length;if(r&&n.topt.top&&a++}let d;dae&&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=O$s(s,r,a,t))}o==null&&(o=F$s(s,l,t));let c=s.docView.nearestDesc(l,!0);return{pos:o,inside:c?c.posAtStart-c.border:-1}}function Kgt(s){return s.top=0&&a==r.nodeValue.length?(c--,u=1):n<0?c--:d++,HY(WT(B3(r,c,d),u),u<0)}if(!s.state.doc.resolve(t-(i||0)).parent.inlineContent){if(i==null&&a&&(n<0||a==Y2(r))){let c=r.childNodes[a-1];if(c.nodeType==1)return x7e(c.getBoundingClientRect(),!1)}if(i==null&&a=0)}if(i==null&&a&&(n<0||a==Y2(r))){let c=r.childNodes[a-1],d=c.nodeType==3?B3(c,Y2(c)-(l?0:1)):c.nodeType==1&&(c.nodeName!="BR"||!c.nextSibling)?c:null;if(d)return HY(WT(d,1),!1)}if(i==null&&a=0)}function HY(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 x7e(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 MBt(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 U$s(s,t,n){let r=t.selection,a=n=="up"?r.$from:r.$to;return MBt(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=TBt(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=B3(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 q$s=/[\u0590-\u08ac]/;function $$s(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?!q$s.test(r.parent.textContent)||!o.modify?n=="left"||n=="backward"?i:l:MBt(s,t,()=>{let{focusNode:c,focusOffset:d,anchorNode:u,anchorOffset:h}=s.domSelectionRange(),m=o.caretBidiLevel;o.modify("move",n,"character");let p=r.depth?s.docView.domAfterPos(r.before()):s.dom,{focusNode:f,focusOffset:y}=s.domSelectionRange(),v=f&&!p.contains(f.nodeType==1?f:f.parentNode)||c==f&&d==y;try{o.collapse(u,h),c&&(c!=u||d!=h)&&o.extend&&o.extend(c,d)}catch{}return m!=null&&(o.caretBidiLevel=m),v}):r.pos==r.start()||r.pos==r.end()}let Ygt=null,Zgt=null,Xgt=!1;function V$s(s,t,n){return Ygt==t&&Zgt==n?Xgt:(Ygt=t,Zgt=n,Xgt=n=="up"||n=="down"?U$s(s,t,n):$$s(s,t,n))}const bN=0,Qgt=1,xF=2,uC=3;class uae{constructor(t,n,r,a){this.parent=t,this.children=n,this.dom=r,this.contentDOM=a,this.dirty=bN,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;ncv(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 LBt){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 PBt&&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?cv(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=cv(m.dom)+1;break}t-=m.size}a==-1&&(a=0)}if(a>-1&&(d>n||o==this.children.length-1)){n=d;for(let u=o+1;uf&&ln){let f=o;o=c,c=f}let p=document.createRange();p.setEnd(c.node,c.offset),p.setStart(o.node,o.offset),d.removeAllRanges(),d.addRange(p)}}ignoreMutation(t){return!this.contentDOM&&t.type!="selection"}get contentLost(){return this.contentDOM&&this.contentDOM!=this.dom&&!this.dom.contains(this.contentDOM)}markDirty(t,n){for(let r=0,a=0;a=r:tr){let o=r+i.border,c=l-i.border;if(t>=o&&n<=c){this.dirty=t==r||n==l?xF:Qgt,t==o&&n==c&&(i.contentLost||i.dom.parentNode!=this.contentDOM)?i.dirty=uC:i.markDirty(t-o,n-o);return}else i.dirty=i.dom==i.contentDOM&&i.dom.parentNode==this.contentDOM&&!i.children.length?xF:uC}r=l}this.dirty=xF}markParentsDirty(){let t=1;for(let n=this.parent;n;n=n.parent,t++){let r=t==1?xF:Qgt;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==bN&&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 H$s extends uae{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 s9 extends uae{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=H9.renderSpec(document,n.type.spec.toDOM(n,r),null,n.attrs)),new s9(t,n,l.dom,l.contentDOM||l.dom,l)}parseRule(){return this.dirty&uC||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(t){return this.dirty!=uC&&this.mark.eq(t)}markDirty(t,n){if(super.markDirty(t,n),this.dirty!=bN){let r=this.parent;for(;!r.node;)r=r.parent;r.dirty0&&(i=qVe(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}=H9.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=RBt(u,r,n),d?c=new G$s(t,n,r,a,u,h||null,m,d,i,l+1):n.isText?new vLe(t,n,r,a,u,m,i):new hP(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=()=>Ha.empty)}return t}matchesNode(t,n,r){return this.dirty==bN&&t.eq(this.node)&&FAe(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 K$s(this,l&&l.node,t);X$s(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?Tm.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==xF)&&(l&&this.protectLocalComposition(t,l),IBt(this.contentDOM,this.children,t),OH&&Q$s(this.dom))}localCompositionInfo(t,n){let{from:r,to:a}=t.state.selection;if(!(t.state.selection instanceof jl)||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=J$s(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 H$s(this,i,n,a);t.input.compositionNodes.push(l),this.children=qVe(this.children,r,r+a.length,t,l)}update(t,n,r,a){return this.dirty==uC||!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=bN}updateOuterDeco(t){if(FAe(t,this.outerDeco))return;let n=this.nodeDOM.nodeType!=1,r=this.dom;this.dom=DBt(this.dom,this.nodeDOM,UVe(this.outerDeco,this.node,n),UVe(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 Jgt(s,t,n,r,a){RBt(r,t,s);let i=new hP(void 0,s,t,n,r,r,r,a,0);return i.contentDOM&&i.updateChildren(a,0),i}class vLe extends hP{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==uC||this.dirty!=bN&&!this.inParent()||!t.sameMarkup(this.node)?!1:(this.updateOuterDeco(n),(this.dirty!=bN||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=bN,!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 vLe(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=uC)}get domAtom(){return!1}isText(t){return this.node.text==t}}class LBt extends uae{parseRule(){return{ignore:!0}}matchesHack(t){return this.dirty==bN&&this.dom.nodeName==t}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}}class G$s extends hP{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==uC)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 IBt(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=s9.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 s9)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 Z$s(s,t){return s.type.side-t.type.side}function X$s(s,t,n,r){let a=t.locals(s),i=0;if(a.length==0){for(let d=0;di;)o.push(a[l++]);let f=i+m.nodeSize;if(m.isText){let v=f;l!v.inline):o.slice();r(m,y,t.forChild(i,m),p),i=f}}function Q$s(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 J$s(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 qVe(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 Eet(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(yLe(n)){for(c=l;a&&!a.node;)a=a.parent;let h=a.node;if(a&&h.isAtom&&dl.isSelectable(h)&&a.parent&&!(h.isInline&&S$s(n.focusNode,n.focusOffset,a.dom))){let m=a.posBefore;d=new dl(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(()=>{(!FBt(s)||s.state.selection.visible)&&s.dom.classList.remove("ProseMirror-hideselection")},20))})}function tVs(s){let t=s.domSelection();if(!t)return;let n=s.cursorWrapper.dom,r=n.nodeName=="IMG";r?t.collapse(n.parentNode,cv(n)+1):t.collapse(n,0),!r&&!s.state.selection.visible&&z_&&uP<=11&&(n.disabled=!0,n.disabled=!1)}function OBt(s,t){if(t instanceof dl){let n=s.docView.descAt(t.from);n!=s.lastSelectedViewDesc&&(r0t(s),n&&n.selectNode(),s.lastSelectedViewDesc=n)}else r0t(s)}function r0t(s){s.lastSelectedViewDesc&&(s.lastSelectedViewDesc.parent&&s.lastSelectedViewDesc.deselectNode(),s.lastSelectedViewDesc=void 0)}function Tet(s,t,n,r){return s.someProp("createSelectionBetween",a=>a(s,t,n))||jl.between(t,n,r)}function a0t(s){return s.editable&&!s.hasFocus()?!1:zBt(s)}function zBt(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 sVs(s){let t=s.docView.domFromPos(s.state.selection.anchor,0),n=s.domSelectionRange();return t9(t.node,t.offset,n.anchorNode,n.anchorOffset)}function $Ve(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&&Wl.findFrom(i,t)}function u6(s,t){return s.dispatch(s.state.tr.setSelection(t).scrollIntoView()),!0}function i0t(s,t,n){let r=s.state.selection;if(r instanceof jl)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 u6(s,new jl(r.$anchor,l))}else if(r.empty){if(s.endOfTextblock(t>0?"forward":"backward")){let a=$Ve(s.state,t);return a&&a instanceof dl?u6(s,a):!1}else if(!(B2&&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?dl.isSelectable(i)?u6(s,new dl(t<0?s.state.doc.resolve(a.pos-i.nodeSize):a)):dae?u6(s,new jl(s.state.doc.resolve(t<0?o:o+i.nodeSize))):!1:!1}}else return!1;else{if(r instanceof dl&&r.node.isInline)return u6(s,new jl(t>0?r.$to:r.$from));{let a=$Ve(s.state,t);return a?u6(s,a):!1}}}function OAe(s){return s.nodeType==3?s.nodeValue.length:s.childNodes.length}function DJ(s,t){let n=s.pmViewDesc;return n&&n.size==0&&(t<0||s.nextSibling||s.nodeName!="BR")}function kB(s,t){return t<0?nVs(s):rVs(s)}function nVs(s){let t=s.domSelectionRange(),n=t.focusNode,r=t.focusOffset;if(!n)return;let a,i,l=!1;for(vN&&n.nodeType==1&&r0){if(n.nodeType!=1)break;{let o=n.childNodes[r-1];if(DJ(o,-1))a=n,i=--r;else if(o.nodeType==3)n=o,r=n.nodeValue.length;else break}}else{if(BBt(n))break;{let o=n.previousSibling;for(;o&&DJ(o,-1);)a=n.parentNode,i=cv(o),o=o.previousSibling;if(o)n=o,r=OAe(n);else{if(n=n.parentNode,n==s.dom)break;r=0}}}l?VVe(s,n,r):a&&VVe(s,a,i)}function rVs(s){let t=s.domSelectionRange(),n=t.focusNode,r=t.focusOffset;if(!n)return;let a=OAe(n),i,l;for(;;)if(r{s.state==a&&eE(s)},50)}function o0t(s,t){let n=s.state.doc.resolve(t);if(!(xv||kBt)&&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 l0t(s,t,n){let r=s.state.selection;if(r instanceof jl&&!r.empty||n.indexOf("s")>-1||B2&&n.indexOf("m")>-1)return!1;let{$from:a,$to:i}=r;if(!a.parent.inlineContent||s.endOfTextblock(t<0?"up":"down")){let l=$Ve(s.state,t);if(l&&l instanceof dl)return u6(s,l)}if(!a.parent.inlineContent){let l=t<0?a:i,o=r instanceof yN?Wl.near(l,t):Wl.findFrom(l,t);return o?u6(s,o):!1}return!1}function c0t(s,t){if(!(s.state.selection instanceof jl))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 d0t(s,t,n){s.domObserver.stop(),t.contentEditable=n,s.domObserver.start()}function oVs(s){if(!b1||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;d0t(s,r,"true"),setTimeout(()=>d0t(s,r,"false"),20)}return!1}function lVs(s){let t="";return s.ctrlKey&&(t+="c"),s.metaKey&&(t+="m"),s.altKey&&(t+="a"),s.shiftKey&&(t+="s"),t}function cVs(s,t){let n=t.keyCode,r=lVs(t);if(n==8||B2&&n==72&&r=="c")return c0t(s,-1)||kB(s,-1);if(n==46&&!t.shiftKey||B2&&n==68&&r=="c")return c0t(s,1)||kB(s,1);if(n==13||n==27)return!0;if(n==37||B2&&n==66&&r=="c"){let a=n==37?o0t(s,s.state.selection.from)=="ltr"?-1:1:-1;return i0t(s,a,r)||kB(s,a)}else if(n==39||B2&&n==70&&r=="c"){let a=n==39?o0t(s,s.state.selection.from)=="ltr"?1:-1:1;return i0t(s,a,r)||kB(s,a)}else{if(n==38||B2&&n==80&&r=="c")return l0t(s,-1,r)||kB(s,-1);if(n==40||B2&&n==78&&r=="c")return oVs(s)||l0t(s,1,r)||kB(s,1);if(r==(B2?"m":"c")&&(n==66||n==73||n==89||n==90))return!0}return!1}function Met(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")||H9.fromSchema(s.state.schema),o=GBt(),c=o.createElement("div");c.appendChild(l.serializeFragment(r,{document:o}));let d=c.firstChild,u,h=0;for(;d&&d.nodeType==1&&(u=HBt[d.nodeName.toLowerCase()]);){for(let p=u.length-1;p>=0;p--){let f=o.createElement(u[p]);for(;c.firstChild;)f.appendChild(c.firstChild);c.appendChild(f),h++}d=c.firstChild}d&&d.nodeType==1&&d.setAttribute("data-pm-slice",`${a} ${i}${h?` -${h}`:""} ${JSON.stringify(n)}`);let m=s.someProp("clipboardTextSerializer",p=>p(t,s))||t.content.textBetween(0,t.content.size,` `);return{dom:c,text:m,slice:t}}function UBt(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 Pi(Ha.from(s.state.schema.text(t.replace(/\r\n?/g,` `))),0,0),s.someProp("transformPasted",m=>{o=m(o,s,!0)}),o;let h=s.someProp("clipboardTextParser",m=>m(t,a,r,s));if(h)o=h;else{let m=a.marks(),{schema:p}=s.state,f=H9.fromSchema(p);l=document.createElement("div"),t.split(/(?:\r\n?|\n)+/).forEach(y=>{let v=l.appendChild(document.createElement("p"));y&&v.appendChild(f.serializeNode(p.text(y,m)))})}}else s.someProp("transformPastedHTML",h=>{n=h(n,s)}),l=mVs(n),dae&&pVs(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")||PJ.fromSchema(s.state.schema)).parseSlice(l,{preserveWhitespace:!!(c||u),context:a,ruleFromNode(m){return m.nodeName=="BR"&&!m.nextSibling&&m.parentNode&&!dVs.test(m.parentNode.nodeName)?{ignore:!0}:null}})),u)o=fVs(u0t(o,+u[1],+u[2]),u[4]);else if(o=Pi.maxOpen(uVs(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 dVs=/^(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 uVs(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&&$Bt(c,i,o,l[l.length-1],0))l[l.length-1]=d;else{l.length&&(l[l.length-1]=VBt(l[l.length-1],i.length));let u=qBt(o,c);l.push(u),a=a.matchType(u.type),i=c}}),l)return Ha.from(l)}return s}function qBt(s,t,n=0){for(let r=t.length-1;r>=n;r--)s=t[r].create(null,Ha.from(s));return s}function $Bt(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(Ha.empty,!0))),s.replaceChild(t<0?0:s.childCount-1,l.copy(o))}function u0t(s,t,n){return tn})),y7e.createHTML(s)):s}function mVs(s){let t=/^(\s*]*>)*/.exec(s);t&&(s=s.slice(t[0].length));let n=GBt().createElement("div"),r=/<([a-z][^>\s]+)/i.exec(s),a;if((a=r&&HBt[r[1].toLowerCase()])&&(s=a.map(i=>"<"+i+">").join("")+s+a.map(i=>"").reverse().join("")),n.innerHTML=hVs(s),a)for(let i=0;i=0;o-=2){let c=n.nodes[r[o]];if(!c||c.hasRequiredAttrs())break;a=Ha.from(c.create(r[o+1],a)),i++,l++}return new Pi(a,i,l)}const Tb={},Mb={},xVs={touchstart:!0,touchmove:!0};class gVs{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 yVs(s){for(let t in Tb){let n=Tb[t];s.dom.addEventListener(t,s.input.eventHandlers[t]=r=>{bVs(s,r)&&!Pet(s,r)&&(s.editable||!(r.type in Mb))&&n(s,r)},xVs[t]?{passive:!0}:void 0)}b1&&s.dom.addEventListener("input",()=>null),GVe(s)}function wM(s,t){s.input.lastSelectionOrigin=t,s.input.lastSelectionTime=Date.now()}function vVs(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 GVe(s){s.someProp("handleDOMEvents",t=>{for(let n in t)s.input.eventHandlers[n]||s.dom.addEventListener(n,s.input.eventHandlers[n]=r=>Pet(s,r))})}function Pet(s,t){return s.someProp("handleDOMEvents",n=>{let r=n[t.type];return r?r(s,t)||t.defaultPrevented:!1})}function bVs(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 _Vs(s,t){!Pet(s,t)&&Tb[t.type]&&(s.editable||!(t.type in Mb))&&Tb[t.type](s,t)}Mb.keydown=(s,t)=>{let n=t;if(s.input.shiftKey=n.keyCode==16||n.shiftKey,!KBt(s,n)&&(s.input.lastKeyCode=n.keyCode,s.input.lastKeyCodeTime=Date.now(),!(IA&&xv&&n.keyCode==13)))if(n.keyCode!=229&&s.domObserver.forceFlush(),OH&&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,JR(13,"Enter"))),s.input.lastIOSEnter=0)},200)}else s.someProp("handleKeyDown",r=>r(s,n))||cVs(s,n)?n.preventDefault():wM(s,"key")};Mb.keyup=(s,t)=>{t.keyCode==16&&(s.input.shiftKey=!1)};Mb.keypress=(s,t)=>{let n=t;if(KBt(s,n)||!n.charCode||n.ctrlKey&&!n.altKey||B2&&n.metaKey)return;if(s.someProp("handleKeyPress",a=>a(s,n))){n.preventDefault();return}let r=s.state.selection;if(!(r instanceof jl)||!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 bLe(s){return{left:s.clientX,top:s.clientY}}function wVs(s,t){let n=t.x-s.clientX,r=t.y-s.clientY;return n*n+r*r<100}function Let(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 E$(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 jVs(s,t){if(t==-1)return!1;let n=s.state.doc.resolve(t),r=n.nodeAfter;return r&&r.isAtom&&dl.isSelectable(r)?(E$(s,new dl(n)),!0):!1}function NVs(s,t){if(t==-1)return!1;let n=s.state.selection,r,a;n instanceof dl&&(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(dl.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?(E$(s,dl.create(s.state.doc,a)),!0):!1}function kVs(s,t,n,r,a){return Let(s,"handleClickOn",t,n,r)||s.someProp("handleClick",i=>i(s,t,r))||(a?NVs(s,n):jVs(s,n))}function SVs(s,t,n,r){return Let(s,"handleDoubleClickOn",t,n,r)||s.someProp("handleDoubleClick",a=>a(s,t,r))}function CVs(s,t,n,r){return Let(s,"handleTripleClickOn",t,n,r)||s.someProp("handleTripleClick",a=>a(s,t,r))||AVs(s,n,r)}function AVs(s,t,n){if(n.button!=0)return!1;let r=s.state.doc;if(t==-1)return r.inlineContent?(E$(s,jl.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)E$(s,jl.create(r,o+1,o+1+l.content.size));else if(dl.isSelectable(l))E$(s,dl.create(r,o));else continue;return!0}}function Iet(s){return zAe(s)}const WBt=B2?"metaKey":"ctrlKey";Tb.mousedown=(s,t)=>{let n=t;s.input.shiftKey=n.shiftKey;let r=Iet(s),a=Date.now(),i="singleClick";a-s.input.lastClick.time<500&&wVs(n,s.input.lastClick)&&!n[WBt]&&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(bLe(n));l&&(i=="singleClick"?(s.input.mouseDown&&s.input.mouseDown.done(),s.input.mouseDown=new EVs(s,l,n,!!r)):(i=="doubleClick"?SVs:CVs)(s,l.pos,l.inside,n)?n.preventDefault():wM(s,"pointer"))};class EVs{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[WBt],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 dl&&d.from<=l&&d.to>l)&&(this.mightDrag={node:i,pos:l,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&vN&&!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)),wM(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(()=>eE(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(bLe(t))),this.updateAllowDefault(t),this.allowDefault||!n?wM(this.view,"pointer"):kVs(this.view,n.pos,n.inside,t,this.selectNode)?t.preventDefault():t.button==0&&(this.flushed||b1&&this.mightDrag&&!this.mightDrag.node.isAtom||xv&&!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)?(E$(this.view,Wl.near(this.view.state.doc.resolve(n.pos))),t.preventDefault()):wM(this.view,"pointer")}move(t){this.updateAllowDefault(t),wM(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)}}Tb.touchstart=s=>{s.input.lastTouch=Date.now(),Iet(s),wM(s,"pointer")};Tb.touchmove=s=>{s.input.lastTouch=Date.now(),wM(s,"pointer")};Tb.contextmenu=s=>Iet(s);function KBt(s,t){return s.composing?!0:b1&&Math.abs(t.timeStamp-s.input.compositionEndedAt)<500?(s.input.compositionEndedAt=-2e8,!0):!1}const TVs=IA?5e3:-1;Mb.compositionstart=Mb.compositionupdate=s=>{if(!s.composing){s.domObserver.flush();let{state:t}=s,n=t.selection.$to;if(t.selection instanceof jl&&(t.storedMarks||!n.textOffset&&n.parentOffset&&n.nodeBefore.marks.some(r=>r.type.spec.inclusive===!1)||xv&&kBt&&MVs(s)))s.markCursor=s.state.storedMarks||n.marks(),zAe(s,!0),s.markCursor=null;else if(zAe(s,!t.selection.empty),vN&&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}YBt(s,TVs)};function MVs(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"}Mb.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++,YBt(s,20))};function YBt(s,t){clearTimeout(s.input.composingTimeout),t>-1&&(s.input.composingTimeout=setTimeout(()=>zAe(s),t))}function ZBt(s){for(s.composing&&(s.input.composing=!1,s.input.compositionEndedAt=LVs());s.input.compositionNodes.length>0;)s.input.compositionNodes.pop().markParentsDirty()}function PVs(s){let t=s.domSelectionRange();if(!t.focusNode)return null;let n=N$s(t.focusNode,t.focusOffset),r=k$s(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 LVs(){let s=document.createEvent("Event");return s.initEvent("event",!0,!0),s.timeStamp}function zAe(s,t=!1){if(!(IA&&s.domObserver.flushingSoon>=0)){if(s.domObserver.forceFlush(),ZBt(s),t||s.docView&&s.docView.dirty){let n=Eet(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 IVs(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 vte=z_&&uP<15||OH&&E$s<604;Tb.copy=Mb.cut=(s,t)=>{let n=t,r=s.state.selection,a=n.type=="cut";if(r.empty)return;let i=vte?null:n.clipboardData,l=r.content(),{dom:o,text:c}=Met(s,l);i?(n.preventDefault(),i.clearData(),i.setData("text/html",o.innerHTML),i.setData("text/plain",c)):IVs(s,o),a&&s.dispatch(s.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function DVs(s){return s.openStart==0&&s.openEnd==0&&s.content.childCount==1?s.content.firstChild:null}function RVs(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?bte(s,r.value,null,a,t):bte(s,r.textContent,r.innerHTML,a,t)},50)}function bte(s,t,n,r,a){let i=UBt(s,t,n,r,s.state.selection.$from);if(s.someProp("handlePaste",c=>c(s,a,i||Pi.empty)))return!0;if(!i)return!1;let l=DVs(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 XBt(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," "):""}Mb.paste=(s,t)=>{let n=t;if(s.composing&&!IA)return;let r=vte?null:n.clipboardData,a=s.input.shiftKey&&s.input.lastKeyCode!=45;r&&bte(s,XBt(r),r.getData("text/html"),a,n)?n.preventDefault():RVs(s,n)};class QBt{constructor(t,n,r){this.slice=t,this.move=n,this.node=r}}const FVs=B2?"altKey":"ctrlKey";function JBt(s,t){let n;return s.someProp("dragCopies",r=>{n=n||r(t)}),n!=null?!n:!t[FVs]}Tb.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(bLe(n)),l;if(!(i&&i.pos>=a.from&&i.pos<=(a instanceof dl?a.to-1:a.to))){if(r&&r.mightDrag)l=dl.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=dl.create(s.state.doc,h.posBefore))}}let o=(l||s.state.selection).content(),{dom:c,text:d,slice:u}=Met(s,o);(!n.dataTransfer.files.length||!xv||NBt>120)&&n.dataTransfer.clearData(),n.dataTransfer.setData(vte?"Text":"text/html",c.innerHTML),n.dataTransfer.effectAllowed="copyMove",vte||n.dataTransfer.setData("text/plain",d),s.dragging=new QBt(u,JBt(s,n),l)};Tb.dragend=s=>{let t=s.dragging;window.setTimeout(()=>{s.dragging==t&&(s.dragging=null)},50)};Mb.dragover=Mb.dragenter=(s,t)=>t.preventDefault();Mb.drop=(s,t)=>{try{OVs(s,t,s.dragging)}finally{s.dragging=null}};function OVs(s,t,n){if(!t.dataTransfer)return;let r=s.posAtCoords(bLe(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=UBt(s,XBt(t.dataTransfer),vte?null:t.dataTransfer.getData("text/html"),!1,a);let l=!!(n&&JBt(s,t));if(s.someProp("handleDrop",p=>p(s,t,i||Pi.empty,l))){t.preventDefault();return}if(!i)return;t.preventDefault();let o=i?fBt(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&&dl.isSelectable(i.content.firstChild)&&m.nodeAfter&&m.nodeAfter.sameMarkup(i.content.firstChild))c.setSelection(new dl(m));else{let p=c.mapping.map(o);c.mapping.maps[c.mapping.maps.length-1].forEach((f,y,v,g)=>p=g),c.setSelection(Tet(s,m,c.doc.resolve(p)))}s.focus(),s.dispatch(c.setMeta("uiEvent","drop"))}Tb.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())&&eE(s)},20))};Tb.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)};Tb.beforeinput=(s,t)=>{if(xv&&IA&&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,JR(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 Mb)Tb[s]=Mb[s];function _te(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 BAe{constructor(t,n){this.toDOM=t,this.spec=n||v7,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 pb(i-r,i-r,this)}valid(){return!0}eq(t){return this==t||t instanceof BAe&&(this.spec.key&&this.spec.key==t.spec.key||this.toDOM==t.toDOM&&_te(this.spec,t.spec))}destroy(t){this.spec.destroy&&this.spec.destroy(t)}}class mP{constructor(t,n){this.attrs=t,this.spec=n||v7}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 pb(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==a1||t.maps.length==0?this:this.mapInner(t,n,0,0,r||v7)}mapInner(t,n,r,a,i){let l;for(let o=0;o{let d=c+r,u;if(u=tUt(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 mP){let d=Math.max(i,c.from)-i,u=Math.min(l,c.to)-i;da.map(t,n,v7));return N6.from(r)}forChild(t,n){if(n.isLeaf)return yx.empty;let r=[];for(let a=0;an instanceof yx)?t:t.reduce((n,r)=>n.concat(r instanceof yx?r:r.members),[]))}}forEachSet(t){for(let n=0;n{let v=y-f-(p-m);for(let g=0;gb+u-h)continue;let j=o[g]+u-h;p>=j?o[g+1]=m<=j?-2:-1:m>=u&&v&&(o[g]+=v,o[g+1]+=v)}h+=v}),u=n.maps[d].map(u,-1)}let c=!1;for(let d=0;d=r.content.size){c=!0;continue}let m=n.map(s[d+1]+i,-1),p=m-a,{index:f,offset:y}=r.content.findIndex(h),v=r.maybeChild(f);if(v&&y==h&&y+v.nodeSize==p){let g=o[d+2].mapInner(n,v,u+1,s[d]+i+1,l);g!=a1?(o[d]=h,o[d+1]=p,o[d+2]=g):(o[d+1]=-2,c=!0)}else c=!0}if(c){let d=BVs(o,s,t,n,a,i,l),u=UAe(d,r,0,l);t=u.local;for(let h=0;hn&&l.to{let d=tUt(s,o,c+n);if(d){i=!0;let u=UAe(d,o,n+c+1,r);u!=a1&&a.push(c,c+o.nodeSize,u)}});let l=eUt(i?sUt(s):s,-n).sort(b7);for(let o=0;o0;)t++;s.splice(t,0,n)}function v7e(s){let t=[];return s.someProp("decorations",n=>{let r=n(s.state);r&&r!=a1&&t.push(r)}),s.cursorWrapper&&t.push(yx.create(s.state.doc,[s.cursorWrapper.deco])),N6.from(t)}const UVs={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},qVs=z_&&uP<=11;class $Vs{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 VVs{constructor(t,n){this.view=t,this.handleDOMChange=n,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new $Vs,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():b1&&t.composing&&r.some(a=>a.type=="childList"&&a.target.nodeName=="TR")?(t.input.badSafariComposition=!0,this.flushSoon()):this.flush()}),qVs&&(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,UVs)),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(a0t(this.view)){if(this.suppressingSelectionUpdates)return eE(this.view);if(z_&&uP<=11&&!this.view.state.selection.empty){let t=this.view.domSelectionRange();if(t.focusNode&&t9(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=FH(i))n.add(i);for(let i=t.anchorNode;i;i=FH(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)&&a0t(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(vN&&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||WVs(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),HVs(t)),t.input.badSafariComposition&&(t.input.badSafariComposition=!1,KVs(t,c)),this.handleDOMChange(i,l,o,c),t.docView&&t.docView.dirty?t.updateState(t.state):this.currentSelection.eq(r)||eE(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;v--){let g=r.childNodes[v-1],b=g.pmViewDesc;if(g.nodeName=="BR"&&!b){i=v;break}if(!b||b.size)break}let h=s.state.doc,m=s.someProp("domParser")||PJ.fromSchema(s.state.schema),p=h.resolve(l),f=null,y=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:ZVs,context:p});if(d&&d[0].pos!=null){let v=d[0].pos,g=d[1]&&d[1].pos;g==null&&(g=v),f={anchor:v+l,head:g+l}}return{doc:y,sel:f,from:l,to:o}}function ZVs(s){let t=s.pmViewDesc;if(t)return t.parseRule();if(s.nodeName=="BR"&&s.parentNode){if(b1&&/^(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||b1&&/^(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 XVs=/^(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 QVs(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=Eet(s,P);if(M&&!s.state.selection.eq(M)){if(xv&&IA&&s.input.lastKeyCode===13&&Date.now()-100D(s,JR(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=YVs(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||IA)&&a.some(P=>P.nodeType==1&&!XVs.test(P.nodeName))&&(!f||f.endA>=f.endB)&&s.someProp("handleKeyDown",P=>P(s,JR(13,"Enter")))){s.input.lastIOSEnter=0;return}if(!f)if(r&&c instanceof jl&&!c.empty&&c.$head.sameParent(c.$anchor)&&!s.composing&&!(d.sel&&d.sel.anchor!=d.sel.head))f={start:c.from,endA:c.to,endB:c.to};else{if(d.sel){let P=g0t(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&&f.start<=s.state.selection.from+2&&s.state.selection.from>=d.from?f.start=s.state.selection.from:f.endA=s.state.selection.to-2&&s.state.selection.to<=d.to&&(f.endB+=s.state.selection.to-f.endA,f.endA=s.state.selection.to)),z_&&uP<=11&&f.endB==f.start+1&&f.endA==f.start&&f.start>d.from&&d.doc.textBetween(f.start-d.from-1,f.start-d.from+1)=="  "&&(f.start--,f.endA--,f.endB--);let y=d.doc.resolveNoCache(f.start-d.from),v=d.doc.resolveNoCache(f.endB-d.from),g=u.resolve(f.start),b=y.sameParent(v)&&y.parent.inlineContent&&g.end()>=f.endA;if((OH&&s.input.lastIOSEnter>Date.now()-225&&(!b||a.some(P=>P.nodeName=="DIV"||P.nodeName=="P"))||!b&&y.posP(s,JR(13,"Enter")))){s.input.lastIOSEnter=0;return}if(s.state.selection.anchor>f.start&&eHs(u,f.start,f.endA,y,v)&&s.someProp("handleKeyDown",P=>P(s,JR(8,"Backspace")))){IA&&xv&&s.domObserver.suppressSelectionUpdates();return}xv&&f.endB==f.start&&(s.input.lastChromeDelete=Date.now()),IA&&!b&&y.start()!=v.start()&&v.parentOffset==0&&y.depth==v.depth&&d.sel&&d.sel.anchor==d.sel.head&&d.sel.head==f.endA&&(f.endB-=2,v=d.doc.resolveNoCache(f.endB-d.from),setTimeout(()=>{s.someProp("handleKeyDown",function(P){return P(s,JR(13,"Enter"))})},20));let j=f.start,S=f.endA,C=P=>{let M=P||s.state.tr.replace(j,S,d.doc.slice(f.start-d.from,f.endB-d.from));if(d.sel){let I=g0t(s,M.doc,d.sel);I&&!(xv&&s.composing&&I.empty&&(f.start!=f.endB||s.input.lastChromeDeleteeE(s),20));let P=C(s.state.tr.delete(j,S)),M=u.resolve(f.start).marksAcross(u.resolve(f.endA));M&&P.ensureMarks(M),s.dispatch(P)}else if(f.endA==f.endB&&(E=JVs(y.parent.content.cut(y.parentOffset,v.parentOffset),g.parent.content.cut(g.parentOffset,f.endA-g.start())))){let P=C(s.state.tr);E.type=="add"?P.addMark(j,S,E.mark):P.removeMark(j,S,E.mark),s.dispatch(P)}else if(y.parent.child(y.index()).isText&&y.index()==v.index()-(v.textOffset?0:1)){let P=y.parent.textBetween(y.parentOffset,v.parentOffset),M=()=>C(s.state.tr.insertText(P,j,S));s.someProp("handleTextInput",I=>I(s,j,S,P,M))||s.dispatch(M())}else s.dispatch(C());else s.dispatch(C())}function g0t(s,t,n){return Math.max(n.anchor,n.head)>t.content.size?null:Tet(s,t.resolve(n.anchor),t.resolve(n.head))}function JVs(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||b7e(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 tHs(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 nUt{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 gVs,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=n,this.state=n.state,this.directPlugins=n.plugins||[],this.directPlugins.forEach(j0t),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=_0t(this),b0t(this),this.nodeViews=w0t(this),this.docView=Jgt(this.state.doc,v0t(this),v7e(this),this.dom,this),this.domObserver=new VVs(this,(r,a,i,l)=>QVs(this,r,a,i,l)),this.domObserver.start(),yVs(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&&GVe(this);let n=this._props;this._props=t,t.plugins&&(t.plugins.forEach(j0t),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&&(ZBt(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=w0t(this);nHs(p,this.nodeViews)&&(this.nodeViews=p,i=!0)}(o||n.handleDOMEvents!=this._props.handleDOMEvents)&&GVe(this),this.editable=_0t(this),b0t(this);let c=v7e(this),d=v0t(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&&P$s(this);if(l){this.domObserver.stop();let p=h&&(z_||xv)&&!this.composing&&!a.selection.empty&&!t.selection.empty&&sHs(a.selection,t.selection);if(h){let f=xv?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=PVs(this)),(i||!this.docView.update(t.doc,d,c,this))&&(this.docView.updateOuterDeco(d),this.docView.destroy(),this.docView=Jgt(t.doc,d,c,this.dom,this)),f&&(!this.trackWrites||!this.dom.contains(this.trackWrites))&&(p=!0)}p||!(this.input.mouseDown&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&sVs(this))?eE(this,p):(OBt(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&&L$s(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 dl){let n=this.docView.domAfterPos(this.state.selection.from);n.nodeType==1&&Wgt(this,n.getBoundingClientRect(),t)}else Wgt(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 z$s(this,t)}coordsAtPos(t,n=1){return TBt(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 V$s(this,n||this.state,t)}pasteHTML(t,n){return bte(this,"",t,!1,n||new ClipboardEvent("paste"))}pasteText(t,n){return bte(this,t,null,!0,n||new ClipboardEvent("paste"))}serializeForClipboard(t){return Met(this,t)}destroy(){this.docView&&(vVs(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],v7e(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,w$s())}get isDestroyed(){return this.docView==null}dispatchEvent(t){return _Vs(this,t)}domSelectionRange(){let t=this.domSelection();return t?b1&&this.root.nodeType===11&&C$s(this.dom.ownerDocument)==this.dom&&GVs(this,t)||t:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}}nUt.prototype.dispatch=function(s){let t=this._props.dispatchTransaction;t?t.call(this,s):this.updateState(this.state.apply(s))};function v0t(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"),[pb.node(0,s.state.doc.content.size,t)]}function b0t(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:pb.widget(s.state.selection.from,t,{raw:!0,marks:s.markCursor})}}else s.cursorWrapper=null}function _0t(s){return!s.someProp("editable",t=>t(s.state)===!1)}function sHs(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 w0t(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 nHs(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 j0t(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 zP={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:"'"},qAe={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},rHs=typeof navigator<"u"&&/Mac/.test(navigator.platform),aHs=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(var dv=0;dv<10;dv++)zP[48+dv]=zP[96+dv]=String(dv);for(var dv=1;dv<=24;dv++)zP[dv+111]="F"+dv;for(var dv=65;dv<=90;dv++)zP[dv]=String.fromCharCode(dv+32),qAe[dv]=String.fromCharCode(dv);for(var _7e in zP)qAe.hasOwnProperty(_7e)||(qAe[_7e]=zP[_7e]);function iHs(s){var t=rHs&&s.metaKey&&s.shiftKey&&!s.ctrlKey&&!s.altKey||aHs&&s.shiftKey&&s.key&&s.key.length==1||s.key=="Unidentified",n=!t&&s.key||(s.shiftKey?qAe:zP)[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 oHs=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),lHs=typeof navigator<"u"&&/Win/.test(navigator.platform);function cHs(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 rUt(s,t){let{$cursor:n}=s.selection;return!n||(t?!t.endOfTextblock("backward",s):n.parentOffset>0)?null:n}const mHs=(s,t,n)=>{let r=rUt(s,n);if(!r)return!1;let a=Oet(r);if(!a){let l=r.blockRange(),o=l&&wW(l);return o==null?!1:(t&&t(s.tr.lift(l,o).scrollIntoView()),!0)}let i=a.nodeBefore;if(lUt(s,a,t,-1))return!0;if(r.parent.content.size==0&&(zH(i,"end")||dl.isSelectable(i)))for(let l=r.depth;;l--){let o=xLe(s.doc,r.before(l),r.after(l),Pi.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},pHs=(s,t,n)=>{let r=rUt(s,n);if(!r)return!1;let a=Oet(r);return a?aUt(s,a,t):!1},fHs=(s,t,n)=>{let r=iUt(s,n);if(!r)return!1;let a=zet(r);return a?aUt(s,a,t):!1};function aUt(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=xLe(s.doc,i,c,Pi.empty);if(!d||d.from!=i||d instanceof Eg&&d.slice.size>=c-i)return!1;if(n){let u=s.tr.step(d);u.setSelection(jl.create(u.doc,i)),n(u.scrollIntoView())}return!0}function zH(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 xHs=(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=Oet(r)}let l=i&&i.nodeBefore;return!l||!dl.isSelectable(l)?!1:(t&&t(s.tr.setSelection(dl.create(s.doc,i.pos-l.nodeSize)).scrollIntoView()),!0)};function Oet(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 iUt(s,t){let{$cursor:n}=s.selection;return!n||(t?!t.endOfTextblock("forward",s):n.parentOffset{let r=iUt(s,n);if(!r)return!1;let a=zet(r);if(!a)return!1;let i=a.nodeAfter;if(lUt(s,a,t,1))return!0;if(r.parent.content.size==0&&(zH(i,"start")||dl.isSelectable(i))){let l=xLe(s.doc,r.before(),r.after(),Pi.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 dl,a;if(r){if(n.node.isTextblock||!pL(s.doc,n.from))return!1;a=n.from}else if(a=fLe(s.doc,n.from,-1),a==null)return!1;if(t){let i=s.tr.join(a);r&&i.setSelection(dl.create(i.doc,a-s.doc.resolve(a).nodeBefore.nodeSize)),t(i.scrollIntoView())}return!0},bHs=(s,t)=>{let n=s.selection,r;if(n instanceof dl){if(n.node.isTextblock||!pL(s.doc,n.to))return!1;r=n.to}else if(r=fLe(s.doc,n.to,1),r==null)return!1;return t&&t(s.tr.join(r).scrollIntoView()),!0},_Hs=(s,t)=>{let{$from:n,$to:r}=s.selection,a=n.blockRange(r),i=a&&wW(a);return i==null?!1:(t&&t(s.tr.lift(a,i).scrollIntoView()),!0)},wHs=(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 oUt(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=oUt(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(Wl.near(c.doc.resolve(o),1)),t(c.scrollIntoView())}return!0},NHs=(s,t)=>{let n=s.selection,{$from:r,$to:a}=n;if(n instanceof yN||r.parent.inlineContent||a.parent.inlineContent)return!1;let i=oUt(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(C$(s.doc,i))return t&&t(s.tr.split(i).scrollIntoView()),!0}let r=n.blockRange(),a=r&&wW(r);return a==null?!1:(t&&t(s.tr.lift(r,a).scrollIntoView()),!0)},SHs=(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(dl.create(s.doc,a))),!0)};function CHs(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||pL(s.doc,t.pos))?!1:(n&&n(s.tr.join(t.pos).scrollIntoView()),!0)}function lUt(s,t,n,r){let a=t.nodeBefore,i=t.nodeAfter,l,o,c=a.type.spec.isolating||i.type.spec.isolating;if(!c&&CHs(s,t,n))return!0;let d=!c&&t.parent.canReplace(t.index(),t.index()+1);if(d&&(l=(o=a.contentMatchAt(a.childCount)).findWrapping(i.type))&&o.matchType(l[0]||i.type).validEnd){if(n){let p=t.pos+i.nodeSize,f=Ha.empty;for(let g=l.length-1;g>=0;g--)f=Ha.from(l[g].create(null,f));f=Ha.from(a.copy(f));let y=s.tr.step(new Ay(t.pos-1,p,t.pos,p,new Pi(f,1,0),l.length,!0)),v=y.doc.resolve(p+2*l.length);v.nodeAfter&&v.nodeAfter.type==a.type&&pL(y.doc,v.pos)&&y.join(v.pos),n(y.scrollIntoView())}return!0}let u=i.type.spec.isolating||r>0&&c?null:Wl.findFrom(t,1),h=u&&u.$from.blockRange(u.$to),m=h&&wW(h);if(m!=null&&m>=t.depth)return n&&n(s.tr.lift(h,m).scrollIntoView()),!0;if(d&&zH(i,"start",!0)&&zH(a,"end")){let p=a,f=[];for(;f.push(p),!p.isTextblock;)p=p.lastChild;let y=i,v=1;for(;!y.isTextblock;y=y.firstChild)v++;if(p.canReplace(p.childCount,p.childCount,y.content)){if(n){let g=Ha.empty;for(let j=f.length-1;j>=0;j--)g=Ha.from(f[j].copy(g));let b=s.tr.step(new Ay(t.pos-f.length,t.pos+i.nodeSize,t.pos+v,t.pos+i.nodeSize-v,new Pi(g,f.length,0),0,!0));n(b.scrollIntoView())}return!0}}return!1}function cUt(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(jl.create(t.doc,s<0?a.start(i):a.end(i)))),!0):!1}}const AHs=cUt(-1),EHs=cUt(1);function THs(s,t=null){return function(n,r){let{$from:a,$to:i}=n.selection,l=a.blockRange(i),o=l&&Net(l,s,t);return o?(r&&r(n.tr.wrap(l,o).scrollIntoView()),!0):!1}}function N0t(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 DAe(c,c,t.depth),t.endIndex=0;u--)i=Ha.from(n[u].type.create(n[u].attrs,i));s.step(new Ay(t.start-(r?2:0),t.end,t.start,t.end,new Pi(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?DHs(t,n,s,i):RHs(t,n,i):!0:!1}}function DHs(s,t,n,r){let a=s.tr,i=r.end,l=r.$to.end(r.depth);iy;f--)p-=a.child(f).nodeSize,r.delete(p-1,p+1);let i=r.doc.resolve(n.start),l=i.nodeAfter;if(r.mapping.map(n.end)!=n.start+i.nodeAfter.nodeSize)return!1;let o=n.startIndex==0,c=n.endIndex==a.childCount,d=i.node(-1),u=i.index(-1);if(!d.canReplace(u+(o?0:1),u+1,l.content.append(c?Ha.empty:Ha.from(a))))return!1;let h=i.pos,m=h+l.nodeSize;return r.step(new Ay(h-(o?1:0),m+(c?1:0),h+1,m-1,new Pi((o?Ha.empty:Ha.from(a.copy(Ha.empty))).append(c?Ha.empty:Ha.from(a.copy(Ha.empty))),o?0:1,c?0:1),o?0:1)),t(r.scrollIntoView()),!0}function FHs(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=Ha.from(d?s.create():null),h=new Pi(Ha.from(s.create(null,Ha.from(o.type.create(null,u)))),d?3:1,0),m=i.start,p=i.end;n(t.tr.step(new Ay(m-(d?3:1),p,m,p,h,1,!0)).scrollIntoView())}return!0}}function _Le(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 wLe=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,(...y)=>{const v=this.buildProps(d,n),g=p(...y)(v);return o.push(g),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:_Le({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}},OHs=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 No(s,t,n){return s.config[t]===void 0&&s.parent?No(s.parent,t,n):typeof s.config[t]=="function"?s.config[t].bind({...n,parent:s.parent?No(s.parent,t,n):null}):s.config[t]}function jLe(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 dUt(s){const t=[],{nodeExtensions:n,markExtensions:r}=jLe(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=No(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=No(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 Ty(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 rp(...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 WVe(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)=>rp(n,r),{})}function uUt(s){return typeof s=="function"}function Bc(s,t=void 0,...n){return uUt(s)?t?s.bind(t)(...n):s(...n):s}function zHs(s={}){return Object.keys(s).length===0&&s.constructor===Object}function BHs(s){return typeof s!="string"?s:s.match(/^[+-]?(?:\d*\.)?\d+$/)?Number(s):s==="true"?!0:s==="false"?!1:s}function k0t(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):BHs(n.getAttribute(l.name));return o==null?i:{...i,[l.name]:o}},{});return{...r,...a}}}}function S0t(s){return Object.fromEntries(Object.entries(s).filter(([t,n])=>t==="attrs"&&zHs(n)?!1:n!=null))}function UHs(s,t){var n;const r=dUt(s),{nodeExtensions:a,markExtensions:i}=jLe(s),l=(n=a.find(d=>No(d,"topNode")))===null||n===void 0?void 0:n.name,o=Object.fromEntries(a.map(d=>{const u=r.filter(g=>g.type===d.name),h={name:d.name,options:d.options,storage:d.storage,editor:t},m=s.reduce((g,b)=>{const j=No(b,"extendNodeSchema",h);return{...g,...j?j(d):{}}},{}),p=S0t({...m,content:Bc(No(d,"content",h)),marks:Bc(No(d,"marks",h)),group:Bc(No(d,"group",h)),inline:Bc(No(d,"inline",h)),atom:Bc(No(d,"atom",h)),selectable:Bc(No(d,"selectable",h)),draggable:Bc(No(d,"draggable",h)),code:Bc(No(d,"code",h)),whitespace:Bc(No(d,"whitespace",h)),linebreakReplacement:Bc(No(d,"linebreakReplacement",h)),defining:Bc(No(d,"defining",h)),isolating:Bc(No(d,"isolating",h)),attrs:Object.fromEntries(u.map(g=>{var b;return[g.name,{default:(b=g==null?void 0:g.attribute)===null||b===void 0?void 0:b.default}]}))}),f=Bc(No(d,"parseHTML",h));f&&(p.parseDOM=f.map(g=>k0t(g,u)));const y=No(d,"renderHTML",h);y&&(p.toDOM=g=>y({node:g,HTMLAttributes:WVe(g,u)}));const v=No(d,"renderText",h);return v&&(p.toText=v),[d.name,p]})),c=Object.fromEntries(i.map(d=>{const u=r.filter(v=>v.type===d.name),h={name:d.name,options:d.options,storage:d.storage,editor:t},m=s.reduce((v,g)=>{const b=No(g,"extendMarkSchema",h);return{...v,...b?b(d):{}}},{}),p=S0t({...m,inclusive:Bc(No(d,"inclusive",h)),excludes:Bc(No(d,"excludes",h)),group:Bc(No(d,"group",h)),spanning:Bc(No(d,"spanning",h)),code:Bc(No(d,"code",h)),attrs:Object.fromEntries(u.map(v=>{var g;return[v.name,{default:(g=v==null?void 0:v.attribute)===null||g===void 0?void 0:g.default}]}))}),f=Bc(No(d,"parseHTML",h));f&&(p.parseDOM=f.map(v=>k0t(v,u)));const y=No(d,"renderHTML",h);return y&&(p.toDOM=v=>y({mark:v,HTMLAttributes:WVe(v,u)})),[d.name,p]}));return new rBt({topNode:l,nodes:o,marks:c})}function j7e(s,t){return t.nodes[s]||t.marks[s]||null}function C0t(s,t){return Array.isArray(t)?t.some(n=>(typeof n=="string"?n:n.name)===s.name):t}function Bet(s,t){const n=H9.fromSchema(t).serializeFragment(s),a=document.implementation.createHTMLDocument().createElement("div");return a.appendChild(n),a.innerHTML}const qHs=(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 Uet(s){return Object.prototype.toString.call(s)==="[object RegExp]"}class NLe{constructor(t){this.find=t.find,this.handler=t.handler}}const $Hs=(s,t)=>{if(Uet(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 Ble(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=qHs(d)+i;return l.forEach(m=>{if(u)return;const p=$Hs(h,m.find);if(!p)return;const f=c.state.tr,y=_Le({state:c.state,transaction:f}),v={from:r-(p[0].length-i.length),to:a},{commands:g,chain:b,can:j}=new wLe({editor:n,state:y});m.handler({state:y,range:v,match:p,commands:g,chain:b,can:j})===null||!f.steps.length||(f.setMeta(o,{transform:f,from:r,to:a,text:i}),c.dispatch(f),u=!0)}),u}function VHs(s){const{editor:t,rules:n}=s,r=new F0({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=Bet(Ha.from(u),l.schema);const{from:h}=c,m=h+u.length;Ble({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 Ble({editor:t,from:i,to:l,text:o,rules:n,plugin:r})},handleDOMEvents:{compositionend:a=>(setTimeout(()=>{const{$cursor:i}=a.state.selection;i&&Ble({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?Ble({editor:t,from:l.pos,to:l.pos,text:` `,rules:n,plugin:r}):!1}},isInputRules:!0});return r}function HHs(s){return Object.prototype.toString.call(s).slice(8,-1)}function Ule(s){return HHs(s)!=="Object"?!1:s.constructor===Object&&Object.getPrototypeOf(s)===Object.prototype}function kLe(s,t){const n={...s};return Ule(s)&&Ule(t)&&Object.keys(t).forEach(r=>{Ule(t[r])&&Ule(s[r])?n[r]=kLe(s[r],t[r]):n[r]=t[r]}),n}class ES{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=Bc(No(this,"addOptions",{name:this.name}))),this.storage=Bc(No(this,"addStorage",{name:this.name,options:this.options}))||{}}static create(t={}){return new ES(t)}configure(t={}){const n=this.extend({...this.config,addOptions:()=>kLe(this.options,t)});return n.name=this.name,n.parent=this.parent,n}extend(t={}){const n=new ES(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=Bc(No(n,"addOptions",{name:n.name})),n.storage=Bc(No(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 GHs(s){return typeof s=="number"}class hUt{constructor(t){this.find=t.find,this.handler=t.handler}}const WHs=(s,t,n)=>{if(Uet(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 KHs(s){const{editor:t,state:n,from:r,to:a,rule:i,pasteEvent:l,dropEvent:o}=s,{commands:c,chain:d,can:u}=new wLe({editor:t,state:n}),h=[];return n.doc.nodesBetween(r,a,(p,f)=>{if(!p.isTextblock||p.type.spec.code)return;const y=Math.max(r,f),v=Math.min(a,f+p.content.size),g=p.textBetween(y-f,v-f,void 0,"");WHs(g,i.find,l).forEach(j=>{if(j.index===void 0)return;const S=y+j.index+1,C=S+j[0].length,E={from:n.tr.mapping.map(S),to:n.tr.mapping.map(C)},P=i.handler({state:n,range:E,match:j,commands:c,chain:d,can:u,pasteEvent:l,dropEvent:o});h.push(P)})}),h.every(p=>p!==null)}let qle=null;const YHs=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 ZHs(s){const{editor:t,rules:n}=s;let r=null,a=!1,i=!1,l=typeof ClipboardEvent<"u"?new ClipboardEvent("paste"):null,o;try{o=typeof DragEvent<"u"?new DragEvent("drop"):null}catch{o=null}const c=({state:u,from:h,to:m,rule:p,pasteEvt:f})=>{const y=u.tr,v=_Le({state:u,transaction:y});if(!(!KHs({editor:t,state:v,from:Math.max(h-1,0),to:m.b-1,rule:p,pasteEvent:f,dropEvent:o})||!y.steps.length)){try{o=typeof DragEvent<"u"?new DragEvent("drop"):null}catch{o=null}return l=typeof ClipboardEvent<"u"?new ClipboardEvent("paste"):null,y}};return n.map(u=>new F0({view(h){const m=f=>{var y;r=!((y=h.dom.parentElement)===null||y===void 0)&&y.contains(f.target)?h.dom.parentElement:null,r&&(qle=t)},p=()=>{qle&&(qle=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=qle;p!=null&&p.isEditable&&setTimeout(()=>{const f=p.state.selection;f&&p.commands.deleteRange({from:f.from,to:f.to})},10)}return!1},paste:(h,m)=>{var p;const f=(p=m.clipboardData)===null||p===void 0?void 0:p.getData("text/html");return l=m,a=!!(f!=null&&f.includes("data-pm-slice")),!1}}},appendTransaction:(h,m,p)=>{const f=h[0],y=f.getMeta("uiEvent")==="paste"&&!a,v=f.getMeta("uiEvent")==="drop"&&!i,g=f.getMeta("applyPasteRules"),b=!!g;if(!y&&!v&&!b)return;if(b){let{text:C}=g;typeof C=="string"?C=C:C=Bet(Ha.from(C),p.schema);const{from:E}=g,P=E+C.length,M=YHs(C);return c({rule:u,state:p,from:E,to:{b:P},pasteEvt:M})}const j=m.doc.content.findDiffStart(p.doc.content),S=m.doc.content.findDiffEnd(p.doc.content);if(!(!GHs(j)||!S||j===S.b))return c({rule:u,state:p,from:j,to:S,pasteEvt:l})}}))}function XHs(s){const t=s.filter((n,r)=>s.indexOf(n)!==r);return Array.from(new Set(t))}class sq{constructor(t,n){this.splittableMarks=[],this.editor=n,this.extensions=sq.resolve(t),this.schema=UHs(this.extensions,n),this.setupExtensions()}static resolve(t){const n=sq.sort(sq.flatten(t)),r=XHs(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=No(n,"addExtensions",r);return a?[n,...this.flatten(a())]:n}).flat(10)}static sort(t){return t.sort((r,a)=>{const i=No(r,"priority")||100,l=No(a,"priority")||100;return i>l?-1:i{const r={name:n.name,options:n.options,storage:n.storage,editor:this.editor,type:j7e(n.name,this.schema)},a=No(n,"addCommands",r);return a?{...t,...a()}:t},{})}get plugins(){const{editor:t}=this,n=sq.sort([...this.extensions].reverse()),r=[],a=[],i=n.map(l=>{const o={name:l.name,options:l.options,storage:l.storage,editor:t,type:j7e(l.name,this.schema)},c=[],d=No(l,"addKeyboardShortcuts",o);let u={};if(l.type==="mark"&&No(l,"exitable",o)&&(u.ArrowRight=()=>ES.handleExit({editor:t,mark:l})),d){const y=Object.fromEntries(Object.entries(d()).map(([v,g])=>[v,()=>g({editor:t})]));u={...u,...y}}const h=uHs(u);c.push(h);const m=No(l,"addInputRules",o);C0t(l,t.options.enableInputRules)&&m&&r.push(...m());const p=No(l,"addPasteRules",o);C0t(l,t.options.enablePasteRules)&&p&&a.push(...p());const f=No(l,"addProseMirrorPlugins",o);if(f){const y=f();c.push(...y)}return c}).flat();return[VHs({editor:t,rules:r}),...ZHs({editor:t,rules:a}),...i]}get attributes(){return dUt(this.extensions)}get nodeViews(){const{editor:t}=this,{nodeExtensions:n}=jLe(this.extensions);return Object.fromEntries(n.filter(r=>!!No(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:Ty(r.name,this.schema)},l=No(r,"addNodeView",i);if(!l)return[];const o=(c,d,u,h,m)=>{const p=WVe(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:j7e(t.name,this.schema)};t.type==="mark"&&(!((n=Bc(No(t,"keepOnSplit",r)))!==null&&n!==void 0)||n)&&this.splittableMarks.push(t.name);const a=No(t,"onBeforeCreate",r),i=No(t,"onCreate",r),l=No(t,"onUpdate",r),o=No(t,"onSelectionUpdate",r),c=No(t,"onTransaction",r),d=No(t,"onFocus",r),u=No(t,"onBlur",r),h=No(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 Tv{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=Bc(No(this,"addOptions",{name:this.name}))),this.storage=Bc(No(this,"addStorage",{name:this.name,options:this.options}))||{}}static create(t={}){return new Tv(t)}configure(t={}){const n=this.extend({...this.config,addOptions:()=>kLe(this.options,t)});return n.name=this.name,n.parent=this.parent,n}extend(t={}){const n=new Tv({...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=Bc(No(n,"addOptions",{name:n.name})),n.storage=Bc(No(n,"addStorage",{name:n.name,options:n.options})),n}}function mUt(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 pUt(s){return Object.fromEntries(Object.entries(s.nodes).filter(([,t])=>t.spec.toText).map(([t,n])=>[t,n.spec.toText]))}const QHs=Tv.create({name:"clipboardTextSerializer",addOptions(){return{blockSeparator:void 0}},addProseMirrorPlugins(){return[new F0({key:new k1("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=pUt(n);return mUt(r,{from:l,to:o},{...this.options.blockSeparator!==void 0?{blockSeparator:this.options.blockSeparator}:{},textSerializers:c})}}})]}}),JHs=()=>({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),eGs=(s=!1)=>({commands:t})=>t.setContent("",s),tGs=()=>({state:s,tr:t,dispatch:n})=>{const{selection:r}=t,{ranges:a}=r;return n&&a.forEach(({$from:i,$to:l})=>{s.doc.nodesBetween(i.pos,l.pos,(o,c)=>{if(o.type.isText)return;const{doc:d,mapping:u}=t,h=d.resolve(u.map(c)),m=d.resolve(u.map(c+o.nodeSize)),p=h.blockRange(m);if(!p)return;const f=wW(p);if(o.type.isTextblock){const{defaultType:y}=h.parent.contentMatchAt(h.index());t.setNodeMarkup(p.start,y)}(f||f===0)&&t.lift(p,f)})}),!0},sGs=s=>t=>s(t),nGs=()=>({state:s,dispatch:t})=>NHs(s,t),rGs=(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 jl(r.doc.resolve(Math.max(l-1,0)))),!0},aGs=()=>({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},iGs=s=>({tr:t,state:n,dispatch:r})=>{const a=Ty(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},oGs=s=>({tr:t,dispatch:n})=>{const{from:r,to:a}=s;return n&&t.delete(r,a),!0},lGs=()=>({state:s,dispatch:t})=>hHs(s,t),cGs=()=>({commands:s})=>s.keyboardShortcut("Enter"),dGs=()=>({state:s,dispatch:t})=>jHs(s,t);function $Ae(s,t,n={strict:!0}){const r=Object.keys(t);return r.length?r.every(a=>n.strict?t[a]===s[a]:Uet(t[a])?t[a].test(s[a]):t[a]===s[a]):!0}function fUt(s,t,n={}){return s.find(r=>r.type===t&&$Ae(Object.fromEntries(Object.keys(n).map(a=>[a,r.attrs[a]])),n))}function A0t(s,t,n={}){return!!fUt(s,t,n)}function qet(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),!fUt([...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&&A0t([...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=xL(s,r.schema),{doc:l,selection:o}=n,{$from:c,from:d,to:u}=o;if(a){const h=qet(c,i,t);if(h&&h.from<=d&&h.to>=u){const m=jl.create(l,h.from,h.to);n.setSelection(m)}}return!0},hGs=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=()=>{(VAe()||E0t())&&r.dom.focus(),requestAnimationFrame(()=>{n.isDestroyed||(r.focus(),mGs()&&!VAe()&&!E0t()&&r.dom.focus({preventScroll:!0}))})};if(r.hasFocus()&&s===null||s===!1)return!0;if(i&&s===null&&!xUt(n.state.selection))return l(),!0;const o=gUt(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},fGs=(s,t)=>n=>s.every((r,a)=>t(r,{...n,index:a})),xGs=(s,t)=>({tr:n,commands:r})=>r.insertContentAt({from:n.selection.from,to:n.selection.to},s,t),yUt=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&&yUt(r)}return s};function $le(s){const t=`${s}`,n=new window.DOMParser().parseFromString(t,"text/html").body;return yUt(n)}function wte(s,t,n){if(s instanceof dP||s instanceof Ha)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 Ha.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),wte("",t,n)}if(a){if(n.errorOnInvalidContent){let l=!1,o="";const c=new rBt({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?PJ.fromSchema(c).parseSlice($le(s),n.parseOptions):PJ.fromSchema(c).parse($le(s),n.parseOptions),n.errorOnInvalidContent&&l)throw new Error("[tiptap error]: Invalid HTML content",{cause:new Error(`Invalid element found: ${o}`)})}const i=PJ.fromSchema(t);return n.slice?i.parseSlice($le(s),n.parseOptions).content:i.parse($le(s),n.parseOptions)}return wte("",t,n)}function gGs(s,t,n){const r=s.steps.length-1;if(r{l===0&&(l=u)}),s.setSelection(Wl.near(s.doc.resolve(l),n))}const yGs=s=>!("type"in s),vGs=(s,t,n)=>({tr:r,dispatch:a,editor:i})=>{var l;if(a){n={parseOptions:i.options.parseOptions,updateSelection:!0,applyInputRules:!1,applyPasteRules:!1,...n};let o;const c=v=>{i.emit("contentError",{editor:i,error:v,disableCollaboration:()=>{i.storage.collaboration&&(i.storage.collaboration.isDisabled=!0)}})},d={preserveWhitespace:"full",...n.parseOptions};if(!n.errorOnInvalidContent&&!i.options.enableContentCheck&&i.options.emitContentError)try{wte(t,i.schema,{parseOptions:d,errorOnInvalidContent:!0})}catch(v){c(v)}try{o=wte(t,i.schema,{parseOptions:d,errorOnInvalidContent:(l=n.errorOnInvalidContent)!==null&&l!==void 0?l:i.options.enableContentCheck})}catch(v){return c(v),!1}let{from:u,to:h}=typeof s=="number"?{from:s,to:s}:{from:s.from,to:s.to},m=!0,p=!0;if((yGs(o)?o:[o]).forEach(v=>{v.check(),m=m?v.isText&&v.marks.length===0:!1,p=p?v.isBlock:!1}),u===h&&p){const{parent:v}=r.doc.resolve(u);v.isTextblock&&!v.type.spec.code&&!v.childCount&&(u-=1,h+=1)}let y;if(m){if(Array.isArray(t))y=t.map(v=>v.text||"").join("");else if(t instanceof Ha){let v="";t.forEach(g=>{g.text&&(v+=g.text)}),y=v}else typeof t=="object"&&t&&t.text?y=t.text:y=t;r.insertText(y,u,h)}else y=o,r.replaceWith(u,h,y);n.updateSelection&&gGs(r,r.steps.length-1,-1),n.applyInputRules&&r.setMeta("applyInputRules",{from:u,text:y}),n.applyPasteRules&&r.setMeta("applyPasteRules",{from:u,text:y})}return!0},bGs=()=>({state:s,dispatch:t})=>vHs(s,t),_Gs=()=>({state:s,dispatch:t})=>bHs(s,t),wGs=()=>({state:s,dispatch:t})=>mHs(s,t),jGs=()=>({state:s,dispatch:t})=>gHs(s,t),NGs=()=>({state:s,dispatch:t,tr:n})=>{try{const r=fLe(s.doc,s.selection.$from.pos,-1);return r==null?!1:(n.join(r,2),t&&t(n),!0)}catch{return!1}},kGs=()=>({state:s,dispatch:t,tr:n})=>{try{const r=fLe(s.doc,s.selection.$from.pos,1);return r==null?!1:(n.join(r,2),t&&t(n),!0)}catch{return!1}},SGs=()=>({state:s,dispatch:t})=>pHs(s,t),CGs=()=>({state:s,dispatch:t})=>fHs(s,t);function vUt(){return typeof navigator<"u"?/Mac/.test(navigator.platform):!1}function AGs(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=AGs(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 jte(s,t,n={}){const{from:r,to:a,empty:i}=s.selection,l=t?Ty(t,s.schema):null,o=[];s.doc.nodesBetween(r,a,(h,m)=>{if(h.isText)return;const p=Math.max(r,m),f=Math.min(a,m+h.nodeSize);o.push({node:h,from:p,to:f})});const c=a-r,d=o.filter(h=>l?l.name===h.node.type.name:!0).filter(h=>$Ae(h.node.attrs,n,{strict:!1}));return i?!!d.length:d.reduce((h,m)=>h+m.to-m.from,0)>=c}const TGs=(s,t={})=>({state:n,dispatch:r})=>{const a=Ty(s,n.schema);return jte(n,a,t)?_Hs(n,r):!1},MGs=()=>({state:s,dispatch:t})=>kHs(s,t),PGs=s=>({state:t,dispatch:n})=>{const r=Ty(s,t.schema);return IHs(r)(t,n)},LGs=()=>({state:s,dispatch:t})=>wHs(s,t);function SLe(s,t){return t.nodes[s]?"node":t.marks[s]?"mark":null}function T0t(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 IGs=(s,t)=>({tr:n,state:r,dispatch:a})=>{let i=null,l=null;const o=SLe(typeof s=="string"?s:s.name,r.schema);return o?(o==="node"&&(i=Ty(s,r.schema)),o==="mark"&&(l=xL(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,T0t(d.attrs,t)),l&&d.marks.length&&d.marks.forEach(h=>{l===h.type&&n.addMark(u,u+d.nodeSize,l.create(T0t(h.attrs,t)))})})}),!0):!1},DGs=()=>({tr:s,dispatch:t})=>(t&&s.scrollIntoView(),!0),RGs=()=>({tr:s,dispatch:t})=>{if(t){const n=new yN(s.doc);s.setSelection(n)}return!0},FGs=()=>({state:s,dispatch:t})=>xHs(s,t),OGs=()=>({state:s,dispatch:t})=>yHs(s,t),zGs=()=>({state:s,dispatch:t})=>SHs(s,t),BGs=()=>({state:s,dispatch:t})=>EHs(s,t),UGs=()=>({state:s,dispatch:t})=>AHs(s,t);function KVe(s,t,n={},r={}){return wte(s,t,{slice:!1,parseOptions:n,errorOnInvalidContent:r.errorOnInvalidContent})}const qGs=(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=KVe(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 bUt(s,t){const n=xL(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 $Gs(s,t){const n=new ket(s);return t.forEach(r=>{r.steps.forEach(a=>{n.step(a)})}),n}function VGs(s){for(let t=0;t{n(a)&&r.push({node:a,pos:i})}),r}function _Ut(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 $et(s){return t=>_Ut(t.$from,s)}function GGs(s,t){const n={from:0,to:s.content.size};return mUt(s,n,t)}function WGs(s,t){const n=Ty(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 wUt(s,t){const n=SLe(typeof t=="string"?t:t.name,s.schema);return n==="node"?WGs(s,t):n==="mark"?bUt(s,t):{}}function KGs(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 YGs(s){const t=KGs(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 ZGs(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}})})}),YGs(r)}function Vet(s,t,n){const r=[];return s===t?n.resolve(s).marks().forEach(a=>{const i=n.resolve(s),l=qet(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 B4e(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 YVe(s,t,n={}){const{empty:r,ranges:a}=s.selection,i=t?xL(t,s.schema):null;if(r)return!!(s.storedMarks||s.selection.$from.marks()).filter(h=>i?i.name===h.type.name:!0).find(h=>$Ae(h.attrs,n,{strict:!1}));let l=0;const o=[];if(a.forEach(({$from:h,$to:m})=>{const p=h.pos,f=m.pos;s.doc.nodesBetween(p,f,(y,v)=>{if(!y.isText&&!y.marks.length)return;const g=Math.max(p,v),b=Math.min(f,v+y.nodeSize),j=b-g;l+=j,o.push(...y.marks.map(S=>({mark:S,from:g,to:b})))})}),l===0)return!1;const c=o.filter(h=>i?i.name===h.mark.type.name:!0).filter(h=>$Ae(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 XGs(s,t,n={}){if(!t)return jte(s,null,n)||YVe(s,null,n);const r=SLe(t,s.schema);return r==="node"?jte(s,t,n):r==="mark"?YVe(s,t,n):!1}function M0t(s,t){const{nodeExtensions:n}=jLe(t),r=n.find(l=>l.name===s);if(!r)return!1;const a={name:r.name,options:r.options,storage:r.storage},i=Bc(No(r,"group",a));return typeof i!="string"?!1:i.split(" ").includes("list")}function Het(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&&(Het(i,{ignoreWhitespace:n,checkChildren:t})||(a=!1))}),a}return!1}function QGs(s){return s instanceof dl}function JGs(s,t,n){var r;const{selection:a}=t;let i=null;if(xUt(a)&&(i=a.$cursor),i){const o=(r=s.storedMarks)!==null&&r!==void 0?r:i.marks();return!!n.isInSet(o)||!o.some(c=>c.type.excludes(n))}const{ranges:l}=a;return l.some(({$from:o,$to:c})=>{let d=o.depth===0?s.doc.inlineContent&&s.doc.type.allowsMarkType(n):!1;return s.doc.nodesBetween(o.pos,c.pos,(u,h,m)=>{if(d)return!1;if(u.isInline){const p=!m||m.type.allowsMarkType(n),f=!!n.isInSet(u.marks)||!u.marks.some(y=>y.type.excludes(n));d=p&&f}return!d}),d})}const eWs=(s,t={})=>({tr:n,state:r,dispatch:a})=>{const{selection:i}=n,{empty:l,ranges:o}=i,c=xL(s,r.schema);if(a)if(l){const d=bUt(r,c);n.addStoredMark(c.create({...d,...t}))}else o.forEach(d=>{const u=d.$from.pos,h=d.$to.pos;r.doc.nodesBetween(u,h,(m,p)=>{const f=Math.max(p,u),y=Math.min(p+m.nodeSize,h);m.marks.find(g=>g.type===c)?m.marks.forEach(g=>{c===g.type&&n.addMark(f,y,c.create({...g.attrs,...t}))}):n.addMark(f,y,c.create(t))})});return JGs(r,n,c)},tWs=(s,t)=>({tr:n})=>(n.setMeta(s,t),!0),sWs=(s,t={})=>({state:n,dispatch:r,chain:a})=>{const i=Ty(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})=>N0t(i,{...l,...t})(n)?!0:o.clearNodes()).command(({state:o})=>N0t(i,{...l,...t})(o,r)).run():(console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'),!1)},nWs=s=>({tr:t,dispatch:n})=>{if(n){const{doc:r}=t,a=yF(s,0,r.content.size),i=dl.create(r,a);t.setSelection(i)}return!0},rWs=s=>({tr:t,dispatch:n})=>{if(n){const{doc:r}=t,{from:a,to:i}=typeof s=="number"?{from:s,to:s}:s,l=jl.atStart(r).from,o=jl.atEnd(r).to,c=yF(a,l,o),d=yF(i,l,o),u=jl.create(r,c,d);t.setSelection(u)}return!0},aWs=s=>({state:t,dispatch:n})=>{const r=Ty(s,t.schema);return FHs(r)(t,n)};function P0t(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 iWs=({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=B4e(d,o.node().type.name,o.node().attrs);if(i instanceof dl&&i.node.isBlock)return!o.parentOffset||!C$(l,o.pos)?!1:(r&&(s&&P0t(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:VGs(o.node(-1).contentMatchAt(o.indexAfter(-1)));let p=h&&m?[{type:m,attrs:u}]:void 0,f=C$(t.doc,t.mapping.map(o.pos),1,p);if(!p&&!f&&C$(t.doc,t.mapping.map(o.pos),1,m?[{type:m}]:void 0)&&(f=!0,p=m?[{type:m,attrs:u}]:void 0),r){if(f&&(i instanceof jl&&t.deleteSelection(),t.split(t.mapping.map(o.pos),1,p),m&&!h&&!o.parentOffset&&o.parent.type!==m)){const y=t.mapping.map(o.before()),v=t.doc.resolve(y);o.node(-1).canReplaceWith(v.index(),v.index()+1,m)&&t.setNodeMarkup(t.mapping.map(o.before()),m)}s&&P0t(n,a.extensionManager.splittableMarks),t.scrollIntoView()}return f},oWs=(s,t={})=>({tr:n,state:r,dispatch:a,editor:i})=>{var l;const o=Ty(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 g=Ha.empty;const b=c.index(-1)?1:c.index(-2)?2:3;for(let M=c.depth-b;M>=c.depth-3;M-=1)g=Ha.from(c.node(M).copy(g));const j=c.indexAfter(-1){if(P>-1)return!1;M.isTextblock&&M.content.size===0&&(P=I+1)}),P>-1&&n.setSelection(jl.near(n.doc.resolve(P))),n.scrollIntoView()}return!0}const p=d.pos===c.end()?h.contentMatchAt(0).defaultType:null,f={...B4e(m,h.type.name,h.attrs),...t},y={...B4e(m,c.node().type.name,c.node().attrs),...t};n.delete(c.pos,d.pos);const v=p?[{type:o,attrs:f},{type:p,attrs:y}]:[{type:o,attrs:f}];if(!C$(n.doc,c.pos,2))return!1;if(a){const{selection:g,storedMarks:b}=r,{splittableMarks:j}=i.extensionManager,S=b||g.$to.parentOffset&&g.$from.marks();if(n.split(c.pos,2,v).scrollIntoView(),!S||!a)return!0;const C=S.filter(E=>j.includes(E.type.name));n.ensureMarks(C)}return!0},N7e=(s,t)=>{const n=$et(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)&&pL(s.doc,n.pos)&&s.join(n.pos),!0},k7e=(s,t)=>{const n=$et(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)&&pL(s.doc,r)&&s.join(r),!0},lWs=(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=Ty(s,l.schema),f=Ty(t,l.schema),{selection:y,storedMarks:v}=l,{$from:g,$to:b}=y,j=g.blockRange(b),S=v||y.$to.parentOffset&&y.$from.marks();if(!j)return!1;const C=$et(E=>M0t(E.type.name,h))(y);if(j.depth>=1&&C&&j.depth-C.depth<=1){if(C.node.type===p)return d.liftListItem(f);if(M0t(C.node.type.name,h)&&p.validContent(C.node.content)&&o)return c().command(()=>(i.setNodeMarkup(C.pos,p),!0)).command(()=>N7e(i,p)).command(()=>k7e(i,p)).run()}return!n||!S||!o?c().command(()=>u().wrapInList(p,r)?!0:d.clearNodes()).wrapInList(p,r).command(()=>N7e(i,p)).command(()=>k7e(i,p)).run():c().command(()=>{const E=u().wrapInList(p,r),P=S.filter(M=>m.includes(M.type.name));return i.ensureMarks(P),E?!0:d.clearNodes()}).wrapInList(p,r).command(()=>N7e(i,p)).command(()=>k7e(i,p)).run()},cWs=(s,t={},n={})=>({state:r,commands:a})=>{const{extendEmptyMarkRange:i=!1}=n,l=xL(s,r.schema);return YVe(r,l,t)?a.unsetMark(l,{extendEmptyMarkRange:i}):a.setMark(l,t)},dWs=(s,t,n={})=>({state:r,commands:a})=>{const i=Ty(s,r.schema),l=Ty(t,r.schema),o=jte(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})},uWs=(s,t={})=>({state:n,commands:r})=>{const a=Ty(s,n.schema);return jte(n,a,t)?r.lift(a):r.wrapIn(a,t)},hWs=()=>({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},mWs=()=>({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},pWs=(s,t={})=>({tr:n,state:r,dispatch:a})=>{var i;const{extendEmptyMarkRange:l=!1}=t,{selection:o}=n,c=xL(s,r.schema),{$from:d,empty:u,ranges:h}=o;if(!a)return!0;if(u&&l){let{from:m,to:p}=o;const f=(i=d.marks().find(v=>v.type===c))===null||i===void 0?void 0:i.attrs,y=qet(d,c,f);y&&(m=y.from,p=y.to),n.removeMark(m,p,c)}else h.forEach(m=>{n.removeMark(m.$from.pos,m.$to.pos,c)});return n.removeStoredMark(c),!0},fWs=(s,t={})=>({tr:n,state:r,dispatch:a})=>{let i=null,l=null;const o=SLe(typeof s=="string"?s:s.name,r.schema);return o?(o==="node"&&(i=Ty(s,r.schema)),o==="mark"&&(l=xL(s,r.schema)),a&&n.selection.ranges.forEach(c=>{const d=c.$from.pos,u=c.$to.pos;let h,m,p,f;n.selection.empty?r.doc.nodesBetween(d,u,(y,v)=>{i&&i===y.type&&(p=Math.max(v,d),f=Math.min(v+y.nodeSize,u),h=v,m=y)}):r.doc.nodesBetween(d,u,(y,v)=>{v=d&&v<=u&&(i&&i===y.type&&n.setNodeMarkup(v,void 0,{...y.attrs,...t}),l&&y.marks.length&&y.marks.forEach(g=>{if(l===g.type){const b=Math.max(v,d),j=Math.min(v+y.nodeSize,u);n.addMark(b,j,l.create({...g.attrs,...t}))}}))}),m&&(h!==void 0&&n.setNodeMarkup(h,void 0,{...m.attrs,...t}),l&&m.marks.length&&m.marks.forEach(y=>{l===y.type&&n.addMark(p,f,l.create({...y.attrs,...t}))}))}),!0):!1},xWs=(s,t={})=>({state:n,dispatch:r})=>{const a=Ty(s,n.schema);return THs(a,t)(n,r)},gWs=(s,t={})=>({state:n,dispatch:r})=>{const a=Ty(s,n.schema);return MHs(a,t)(n,r)};var yWs=Object.freeze({__proto__:null,blur:JHs,clearContent:eGs,clearNodes:tGs,command:sGs,createParagraphNear:nGs,cut:rGs,deleteCurrentNode:aGs,deleteNode:iGs,deleteRange:oGs,deleteSelection:lGs,enter:cGs,exitCode:dGs,extendMarkRange:uGs,first:hGs,focus:pGs,forEach:fGs,insertContent:xGs,insertContentAt:vGs,joinBackward:wGs,joinDown:_Gs,joinForward:jGs,joinItemBackward:NGs,joinItemForward:kGs,joinTextblockBackward:SGs,joinTextblockForward:CGs,joinUp:bGs,keyboardShortcut:EGs,lift:TGs,liftEmptyBlock:MGs,liftListItem:PGs,newlineInCode:LGs,resetAttributes:IGs,scrollIntoView:DGs,selectAll:RGs,selectNodeBackward:FGs,selectNodeForward:OGs,selectParentNode:zGs,selectTextblockEnd:BGs,selectTextblockStart:UGs,setContent:qGs,setMark:eWs,setMeta:tWs,setNode:sWs,setNodeSelection:nWs,setTextSelection:rWs,sinkListItem:aWs,splitBlock:iWs,splitListItem:oWs,toggleList:lWs,toggleMark:cWs,toggleNode:dWs,toggleWrap:uWs,undoInputRule:hWs,unsetAllMarks:mWs,unsetMark:pWs,updateAttributes:fWs,wrapIn:xWs,wrapInList:gWs});const vWs=Tv.create({name:"commands",addCommands(){return{...yWs}}}),bWs=Tv.create({name:"drop",addProseMirrorPlugins(){return[new F0({key:new k1("tiptapDrop"),props:{handleDrop:(s,t,n,r)=>{this.editor.emit("drop",{editor:this.editor,event:t,slice:n,moved:r})}}})]}}),_Ws=Tv.create({name:"editable",addProseMirrorPlugins(){return[new F0({key:new k1("editable"),props:{editable:()=>this.editor.options.editable}})]}}),wWs=new k1("focusEvents"),jWs=Tv.create({name:"focusEvents",addProseMirrorPlugins(){const{editor:s}=this;return[new F0({key:wWs,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}}}})]}}),NWs=Tv.create({name:"keymap",addKeyboardShortcuts(){const s=()=>this.editor.commands.first(({commands:l})=>[()=>l.undoInputRule(),()=>l.command(({tr:o})=>{const{selection:c,doc:d}=o,{empty:u,$anchor:h}=c,{pos:m,parent:p}=h,f=h.parent.isTextblock&&m>0?o.doc.resolve(m-1):h,y=f.parent.type.spec.isolating,v=h.pos-h.parentOffset,g=y&&f.parent.childCount===1?v===h.pos:Wl.atStart(d).from===m;return!u||!p.type.isTextblock||p.textContent.length||!g||g&&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 VAe()||vUt()?i:a},addProseMirrorPlugins(){return[new F0({key:new k1("clearDocument"),appendTransaction:(s,t,n)=>{if(s.some(y=>y.getMeta("composition")))return;const r=s.some(y=>y.docChanged)&&!t.doc.eq(n.doc),a=s.some(y=>y.getMeta("preventClearDocument"));if(!r||a)return;const{empty:i,from:l,to:o}=t.selection,c=Wl.atStart(t.doc).from,d=Wl.atEnd(t.doc).to;if(i||!(l===c&&o===d)||!Het(n.doc))return;const m=n.tr,p=_Le({state:n,transaction:m}),{commands:f}=new wLe({editor:this.editor,state:p});if(f.clearNodes(),!!m.steps.length)return m}})]}}),kWs=Tv.create({name:"paste",addProseMirrorPlugins(){return[new F0({key:new k1("tiptapPaste"),props:{handlePaste:(s,t,n)=>{this.editor.emit("paste",{editor:this.editor,event:t,slice:n})}}})]}}),SWs=Tv.create({name:"tabindex",addProseMirrorPlugins(){return[new F0({key:new k1("tabindex"),props:{attributes:()=>this.editor.isEditable?{tabindex:"0"}:{}}})]}});class eF{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 eF(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 eF(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 eF(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 eF(o,this.editor,a,a?n:null);a&&(c.actualDepth=this.depth+1),t.push(new eF(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 CWs=`.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 AWs(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 EWs extends OHs{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=AWs(CWs,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=uUt(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?[_Ws,QHs.configure({blockSeparator:(n=(t=this.options.coreExtensionOptions)===null||t===void 0?void 0:t.clipboardTextSerializer)===null||n===void 0?void 0:n.blockSeparator}),vWs,jWs,NWs,SWs,bWs,kWs].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 sq(a,this)}createCommandManager(){this.commandManager=new wLe({editor:this})}createSchema(){this.schema=this.extensionManager.schema}createView(){var t;let n;try{n=KVe(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=KVe(this.options.content,this.schema,this.options.parseOptions,{errorOnInvalidContent:!1})}const r=gUt(n,this.options.autofocus);this.view=new nUt(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:tq.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 wUt(this.state,t)}isActive(t,n){const r=typeof t=="string"?t:null,a=typeof t=="string"?n:t;return XGs(this.state,r,a)}getJSON(){return this.state.doc.toJSON()}getHTML(){return Bet(this.state.doc.content,this.schema)}getText(t){const{blockSeparator:n=` `,textSerializers:r={}}=t||{};return GGs(this.state.doc,{blockSeparator:n,textSerializers:{...pUt(this.schema),...r}})}get isEmpty(){return Het(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 eF(n,this)}get $doc(){return this.$pos(0)}}function BH(s){return new NLe({find:s.find,handler:({state:t,range:n,match:r})=>{const a=Bc(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(Vet(n.from,n.to,t.doc).filter(p=>p.mark.type.excluded.find(y=>y===s.type&&y!==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 jUt(s){return new NLe({find:s.find,handler:({state:t,range:n,match:r})=>{const a=Bc(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 ZVe(s){return new NLe({find:s.find,handler:({state:t,range:n,match:r})=>{const a=t.doc.resolve(n.from),i=Bc(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 Nte(s){return new NLe({find:s.find,handler:({state:t,range:n,match:r,chain:a})=>{const i=Bc(s.getAttributes,void 0,r)||{},l=t.tr.delete(n.from,n.to),c=l.doc.resolve(n.from).blockRange(),d=c&&Net(c,s.type,i);if(!d)return null;if(l.wrap(c,d),s.keepMarks&&s.editor){const{selection:h,storedMarks:m}=t,{splittableMarks:p}=s.editor.extensionManager,f=m||h.$to.parentOffset&&h.$from.marks();if(f){const y=f.filter(v=>p.includes(v.type.name));l.ensureMarks(y)}}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&&pL(l.doc,n.from-1)&&(!s.joinPredicate||s.joinPredicate(r,u))&&l.join(n.from-1)}})}let My=class XVe{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=Bc(No(this,"addOptions",{name:this.name}))),this.storage=Bc(No(this,"addStorage",{name:this.name,options:this.options}))||{}}static create(t={}){return new XVe(t)}configure(t={}){const n=this.extend({...this.config,addOptions:()=>kLe(this.options,t)});return n.name=this.name,n.parent=this.parent,n}extend(t={}){const n=new XVe(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=Bc(No(n,"addOptions",{name:n.name})),n.storage=Bc(No(n,"addStorage",{name:n.name,options:n.options})),n}};function n9(s){return new hUt({find:s.find,handler:({state:t,range:n,match:r,pasteEvent:a})=>{const i=Bc(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(Vet(n.from,n.to,t.doc).filter(f=>f.mark.type.excluded.find(v=>v===s.type&&v!==f.mark.type)).filter(f=>f.to>h).length)return null;mn.from&&l.delete(n.from+u,h),d=n.from+u+o.length,l.addMark(n.from+u,d,s.type.create(i||{})),l.removeStoredMark(s.type)}}})}function TWs(s,t){const{selection:n}=s,{$from:r}=n;if(n instanceof dl){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 MWs(s){return new hUt({find:s.find,handler({match:t,chain:n,range:r,pasteEvent:a}){const i=Bc(s.getAttributes,void 0,t,a),l=Bc(s.getContent,void 0,i);if(i===!1||i===null)return null;const o={type:s.type.name,attrs:i};l&&(o.content=l),t.input&&n().deleteRange(r).insertContentAt(r.from,o)}})}function PWs(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var NUt={exports:{}},S7e={};/** * @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 L0t;function LWs(){if(L0t)return S7e;L0t=1;var s=Dt;function t(h,m){return h===m&&(h!==0||1/h===1/m)||h!==h&&m!==m}var n=typeof Object.is=="function"?Object.is:t,r=s.useState,a=s.useEffect,i=s.useLayoutEffect,l=s.useDebugValue;function o(h,m){var p=m(),f=r({inst:{value:p,getSnapshot:m}}),y=f[0].inst,v=f[1];return i(function(){y.value=p,y.getSnapshot=m,c(y)&&v({inst:y})},[h,p,m]),a(function(){return c(y)&&v({inst:y}),h(function(){c(y)&&v({inst:y})})},[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 S7e.useSyncExternalStore=s.useSyncExternalStore!==void 0?s.useSyncExternalStore:u,S7e}NUt.exports=LWs();var Get=NUt.exports;const IWs=(...s)=>t=>{s.forEach(n=>{typeof n=="function"?n(t):n&&(n.current=t)})},DWs=({contentComponent:s})=>{const t=Get.useSyncExternalStore(s.subscribe,s.getSnapshot,s.getServerSnapshot);return Dt.createElement(Dt.Fragment,null,Object.values(t))};function RWs(){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]:PXe.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 FWs extends Dt.Component{constructor(t){var n;super(t),this.editorContentRef=Dt.createRef(),this.initialized=!1,this.state={hasContentComponentInitialized:!!(!((n=t.editor)===null||n===void 0)&&n.contentComponent)}}componentDidMount(){this.init()}componentDidUpdate(){this.init()}init(){const t=this.props.editor;if(t&&!t.isDestroyed&&t.options.element){if(t.contentComponent)return;const n=this.editorContentRef.current;n.append(...t.options.element.childNodes),t.setOptions({element:n}),t.contentComponent=RWs(),this.state.hasContentComponentInitialized||(this.unsubscribeToContentComponent=t.contentComponent.subscribe(()=>{this.setState(r=>r.hasContentComponentInitialized?r:{hasContentComponentInitialized:!0}),this.unsubscribeToContentComponent&&this.unsubscribeToContentComponent()})),t.createNodeViews(),this.initialized=!0}}componentWillUnmount(){const t=this.props.editor;if(!t||(this.initialized=!1,t.isDestroyed||t.view.setProps({nodeViews:{}}),this.unsubscribeToContentComponent&&this.unsubscribeToContentComponent(),t.contentComponent=null,!t.options.element.firstChild))return;const n=document.createElement("div");n.append(...t.options.element.childNodes),t.setOptions({element:n})}render(){const{editor:t,innerRef:n,...r}=this.props;return Dt.createElement(Dt.Fragment,null,Dt.createElement("div",{ref:IWs(n,this.editorContentRef),...r}),(t==null?void 0:t.contentComponent)&&Dt.createElement(DWs,{contentComponent:t.contentComponent}))}}const OWs=_.forwardRef((s,t)=>{const n=Dt.useMemo(()=>Math.floor(Math.random()*4294967295).toString(),[s.editor]);return Dt.createElement(FWs,{key:n,innerRef:t,...s})}),CLe=Dt.memo(OWs);var zWs=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},BWs=PWs(zWs),kUt={exports:{}},C7e={};/** * @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 I0t;function UWs(){if(I0t)return C7e;I0t=1;var s=Dt,t=Get;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 C7e.useSyncExternalStoreWithSelector=function(d,u,h,m,p){var f=i(null);if(f.current===null){var y={hasValue:!1,value:null};f.current=y}else y=f.current;f=o(function(){function g(E){if(!b){if(b=!0,j=E,E=m(E),p!==void 0&&y.hasValue){var P=y.value;if(p(P,E))return S=P}return S=E}if(P=S,r(j,E))return P;var M=m(E);return p!==void 0&&p(P,M)?P:(j=E,S=M)}var b=!1,j,S,C=h===void 0?null:h;return[function(){return g(u())},C===null?void 0:function(){return g(C())}]},[u,h,m,p]);var v=a(d,f[0],f[1]);return l(function(){y.hasValue=!0,y.value=v},[v]),c(v),v},C7e}kUt.exports=UWs();var qWs=kUt.exports;const $Ws=typeof window<"u"?_.useLayoutEffect:_.useEffect;class VWs{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 HWs(s){var t;const[n]=_.useState(()=>new VWs(s.editor)),r=qWs.useSyncExternalStoreWithSelector(n.subscribe,n.getSnapshot,n.getServerSnapshot,s.selector,(t=s.equalityFn)!==null&&t!==void 0?t:BWs);return $Ws(()=>n.watch(s.editor),[s.editor,n]),_.useDebugValue(r),r}const GWs=!1,QVe=typeof window>"u",WWs=QVe||!!(typeof window<"u"&&window.next);class Wet{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 QVe||WWs?null:this.createEditor();if(this.options.current.immediatelyRender&&QVe&&GWs)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 EWs(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?Wet.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 ALe(s={},t=[]){const n=_.useRef(s);n.current=s;const[r]=_.useState(()=>new Wet(n)),a=Get.useSyncExternalStore(r.subscribe,r.getEditor,r.getServerSnapshot);return _.useDebugValue(a),_.useEffect(r.onRender(t)),HWs({editor:a,selector:({transactionNumber:i})=>s.shouldRerenderOnTransaction===!1?null:s.immediatelyRender&&i===0?0:i+1}),a}const KWs=_.createContext({editor:null});KWs.Consumer;const YWs=_.createContext({onDragStart:void 0}),ZWs=()=>_.useContext(YWs);Dt.forwardRef((s,t)=>{const{onDragStart:n}=ZWs(),r=s.as||"div";return Dt.createElement(r,{...s,ref:t,"data-node-view-wrapper":"",onDragStart:n,style:{whiteSpace:"normal",...s.style}})});const XWs=/^\s*>\s$/,QWs=My.create({name:"blockquote",addOptions(){return{HTMLAttributes:{}}},content:"block+",group:"block",defining:!0,parseHTML(){return[{tag:"blockquote"}]},renderHTML({HTMLAttributes:s}){return["blockquote",rp(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[Nte({find:XWs,type:this.type})]}}),JWs=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,eKs=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,tKs=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,sKs=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g,nKs=ES.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",rp(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[BH({find:JWs,type:this.type}),BH({find:tKs,type:this.type})]},addPasteRules(){return[n9({find:eKs,type:this.type}),n9({find:sKs,type:this.type})]}}),rKs="listItem",D0t="textStyle",R0t=/^\s*([-+*])\s$/,aKs=My.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",rp(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(rKs,this.editor.getAttributes(D0t)).run():s.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-8":()=>this.editor.commands.toggleBulletList()}},addInputRules(){let s=Nte({find:R0t,type:this.type});return(this.options.keepMarks||this.options.keepAttributes)&&(s=Nte({find:R0t,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:()=>this.editor.getAttributes(D0t),editor:this.editor})),[s]}}),iKs=/(^|[^`])`([^`]+)`(?!`)/,oKs=/(^|[^`])`([^`]+)`(?!`)/g,lKs=ES.create({name:"code",addOptions(){return{HTMLAttributes:{}}},excludes:"_",code:!0,exitable:!0,parseHTML(){return[{tag:"code"}]},renderHTML({HTMLAttributes:s}){return["code",rp(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[BH({find:iKs,type:this.type})]},addPasteRules(){return[n9({find:oKs,type:this.type})]}}),cKs=/^```([a-z]+)?[\s\n]$/,dKs=/^~~~([a-z]+)?[\s\n]$/,uKs=My.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",rp(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(Wl.near(r.resolve(o))),!0)):s.commands.exitCode()}}},addInputRules(){return[ZVe({find:cKs,type:this.type,getAttributes:s=>({language:s[1]})}),ZVe({find:dKs,type:this.type,getAttributes:s=>({language:s[1]})})]},addProseMirrorPlugins(){return[new F0({key:new k1("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(jl.near(l.doc.resolve(Math.max(0,l.selection.from-2)))),l.setMeta("paste",!0),s.dispatch(l),!0}}})]}}),hKs=My.create({name:"doc",topNode:!0,content:"block+"});function mKs(s={}){return new F0({view(t){return new pKs(t,s)}})}class pKs{constructor(t,n){var r;this.editorView=t,this.cursorPos=null,this.element=null,this.timeout=-1,this.width=(r=n.width)!==null&&r!==void 0?r:1,this.color=n.color===!1?void 0:n.color||"black",this.class=n.class,this.handlers=["dragover","dragend","drop","dragleave"].map(a=>{let i=l=>{this[a](l)};return t.dom.addEventListener(a,i),{name:a,handler:i}})}destroy(){this.handlers.forEach(({name:t,handler:n})=>this.editorView.dom.removeEventListener(t,n))}update(t,n){this.cursorPos!=null&&n.doc!=t.state.doc&&(this.cursorPos>t.state.doc.content.size?this.setCursor(null):this.updateOverlay())}setCursor(t){t!=this.cursorPos&&(this.cursorPos=t,t==null?(this.element.parentNode.removeChild(this.element),this.element=null):this.updateOverlay())}updateOverlay(){let t=this.editorView.state.doc.resolve(this.cursorPos),n=!t.parent.inlineContent,r,a=this.editorView.dom,i=a.getBoundingClientRect(),l=i.width/a.offsetWidth,o=i.height/a.offsetHeight;if(n){let h=t.nodeBefore,m=t.nodeAfter;if(h||m){let p=this.editorView.nodeDOM(this.cursorPos-(h?h.nodeSize:0));if(p){let f=p.getBoundingClientRect(),y=h?f.bottom:f.top;h&&m&&(y=(y+this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top)/2);let v=this.width/2*o;r={left:f.left,right:f.right,top:y-v,bottom:y+v}}}}if(!r){let h=this.editorView.coordsAtPos(this.cursorPos),m=this.width/2*l;r={left:h.left-m,right:h.left+m,top:h.top,bottom:h.bottom}}let c=this.editorView.dom.offsetParent;this.element||(this.element=c.appendChild(document.createElement("div")),this.class&&(this.element.className=this.class),this.element.style.cssText="position: absolute; z-index: 50; pointer-events: none;",this.color&&(this.element.style.backgroundColor=this.color)),this.element.classList.toggle("prosemirror-dropcursor-block",n),this.element.classList.toggle("prosemirror-dropcursor-inline",!n);let d,u;if(!c||c==document.body&&getComputedStyle(c).position=="static")d=-pageXOffset,u=-pageYOffset;else{let h=c.getBoundingClientRect(),m=h.width/c.offsetWidth,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=fBt(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 fKs=Tv.create({name:"dropCursor",addOptions(){return{color:"currentColor",width:1,class:void 0}},addProseMirrorPlugins(){return[mKs(this.options)]}});class vx extends Wl{constructor(t){super(t,t)}map(t,n){let r=t.resolve(n.map(this.head));return vx.valid(r)?new vx(r):Wl.near(r)}content(){return Pi.empty}eq(t){return t instanceof vx&&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 vx(t.resolve(n.pos))}getBookmark(){return new Ket(this.anchor)}static valid(t){let n=t.parent;if(n.inlineContent||!xKs(t)||!gKs(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&&vx.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(vx.valid(c))return c}for(;;){let l=n>0?i.firstChild:i.lastChild;if(!l){if(i.isAtom&&!i.isText&&!dl.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(vx.valid(o))return o}return null}}}vx.prototype.visible=!1;vx.findFrom=vx.findGapCursorFrom;Wl.jsonID("gapcursor",vx);class Ket{constructor(t){this.pos=t}map(t){return new Ket(t.map(this.pos))}resolve(t){let n=t.resolve(this.pos);return vx.valid(n)?new vx(n):Wl.near(n)}}function SUt(s){return s.isAtom||s.spec.isolating||s.spec.createGapCursor}function xKs(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||SUt(a.type))return!0;if(a.inlineContent)return!1}}return!0}function gKs(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||SUt(a.type))return!0;if(a.inlineContent)return!1}}return!0}function yKs(){return new F0({props:{decorations:wKs,createSelectionBetween(s,t,n){return t.pos==n.pos&&vx.valid(n)?new vx(n):null},handleClick:bKs,handleKeyDown:vKs,handleDOMEvents:{beforeinput:_Ks}}})}const vKs=Fet({ArrowLeft:Vle("horiz",-1),ArrowRight:Vle("horiz",1),ArrowUp:Vle("vert",-1),ArrowDown:Vle("vert",1)});function Vle(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 jl){if(!i.endOfTextblock(n)||o.depth==0)return!1;c=!1,o=r.doc.resolve(t>0?o.after():o.before())}let d=vx.findGapCursorFrom(o,t,c);return d?(a&&a(r.tr.setSelection(new vx(d))),!0):!1}}function bKs(s,t,n){if(!s||!s.editable)return!1;let r=s.state.doc.resolve(t);if(!vx.valid(r))return!1;let a=s.posAtCoords({left:n.clientX,top:n.clientY});return a&&a.inside>-1&&dl.isSelectable(s.state.doc.nodeAt(a.inside))?!1:(s.dispatch(s.state.tr.setSelection(new vx(r))),!0)}function _Ks(s,t){if(t.inputType!="insertCompositionText"||!(s.state.selection instanceof vx))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=Ha.empty;for(let l=r.length-1;l>=0;l--)a=Ha.from(r[l].createAndFill(null,a));let i=s.state.tr.replace(n.pos,n.pos,new Pi(a,0,0));return i.setSelection(jl.near(i.doc.resolve(n.pos+1))),s.dispatch(i),!1}function wKs(s){if(!(s.selection instanceof vx))return null;let t=document.createElement("div");return t.className="ProseMirror-gapcursor",yx.create(s.doc,[pb.widget(s.selection.head,t,{key:"gapcursor"})])}const jKs=Tv.create({name:"gapCursor",addProseMirrorPlugins(){return[yKs()]},extendNodeSchema(s){var t;const n={name:s.name,options:s.options,storage:s.storage};return{allowGapCursor:(t=Bc(No(s,"allowGapCursor",n)))!==null&&t!==void 0?t:null}}}),NKs=My.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",rp(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()}}}),kKs=My.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]}`,rp(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=>ZVe({find:new RegExp(`^(#{${Math.min(...this.options.levels)},${s}})\\s$`),type:this.type,getAttributes:{level:s}}))}});var HAe=200,Ey=function(){};Ey.prototype.append=function(t){return t.length?(t=Ey.from(t),!this.length&&t||t.length=n?Ey.empty:this.sliceInner(Math.max(0,t),Math.min(this.length,n))};Ey.prototype.get=function(t){if(!(t<0||t>=this.length))return this.getInner(t)};Ey.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)};Ey.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};Ey.from=function(t){return t instanceof Ey?t:t&&t.length?new CUt(t):Ey.empty};var CUt=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<=HAe)return new t(this.values.concat(a.flatten()))},t.prototype.leafPrepend=function(a){if(this.length+a.length<=HAe)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}(Ey);Ey.empty=new CUt([]);var SKs=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}(Ey);const CKs=500;class sS{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 jT(h.map));let p=h.step.map(a.slice(i)),f;p&&l.maybeStep(p).doc&&(f=l.mapping.maps[l.mapping.maps.length-1],d.push(new jT(f,void 0,void 0,d.length+u.length))),i--,f&&a.appendMap(f,i)}else l.maybeStep(h.step);if(h.selection)return o=a?h.selection.map(a.slice(i)):h.selection,c=new sS(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;uEKs&&(o=AKs(o,d),l-=d),new sS(o.append(i),l)}remapping(t,n){let r=new gte;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 sS(this.items.append(t.map(n=>new jT(n))),this.eventCount)}rebased(t,n){if(!this.eventCount)return this;let r=[],a=Math.max(0,this.items.length-n),i=t.mapping,l=t.steps.length,o=this.eventCount;this.items.forEach(m=>{m.selection&&o--},a);let c=n;this.items.forEach(m=>{let p=i.getMirror(--c);if(p==null)return;l=Math.min(l,p);let f=i.maps[p];if(m.step){let y=t.steps[p].invert(t.docs[p]),v=m.selection&&m.selection.map(i.slice(c+1,p));v&&o++,r.push(new jT(f,y,v))}else r.push(new jT(f))},a);let d=[];for(let m=n;mCKs&&(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 jT(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 sS(Ey.from(a.reverse()),i)}}sS.empty=new sS(Ey.empty,0);function AKs(s,t){let n;return s.forEach((r,a)=>{if(r.selection&&t--==0)return n=a,!1}),s.slice(n)}let jT=class AUt{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 AUt(n.getMap().invert(),n,this.selection)}}};class h6{constructor(t,n,r,a,i){this.done=t,this.undone=n,this.prevRanges=r,this.prevTime=a,this.prevComposition=i}}const EKs=20;function TKs(s,t,n,r){let a=n.getMeta(_7),i;if(a)return a.historyState;n.getMeta(LKs)&&(s=new h6(s.done,s.undone,null,0,-1));let l=n.getMeta("appendedTransaction");if(n.steps.length==0)return s;if(l&&l.getMeta(_7))return l.getMeta(_7).redo?new h6(s.done.addTransform(n,void 0,r,U4e(t)),s.undone,F0t(n.mapping.maps),s.prevTime,s.prevComposition):new h6(s.done,s.undone.addTransform(n,void 0,r,U4e(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||!MKs(n,s.prevRanges)),d=l?A7e(s.prevRanges,n.mapping):F0t(n.mapping.maps);return new h6(s.done.addTransform(n,c?t.selection.getBookmark():void 0,r,U4e(t)),sS.empty,d,n.time,o??s.prevComposition)}else return(i=n.getMeta("rebased"))?new h6(s.done.rebased(n,i),s.undone.rebased(n,i),A7e(s.prevRanges,n.mapping),s.prevTime,s.prevComposition):new h6(s.done.addMaps(n.mapping.maps),s.undone.addMaps(n.mapping.maps),A7e(s.prevRanges,n.mapping),s.prevTime,s.prevComposition)}function MKs(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 F0t(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 A7e(s,t){if(!s)return null;let n=[];for(let r=0;r{let a=_7.getState(n);if(!a||(s?a.undone:a.done).eventCount==0)return!1;if(r){let i=PKs(a,n,s);i&&r(t?i.scrollIntoView():i)}return!0}}const TUt=EUt(!1,!0),MUt=EUt(!0,!0),DKs=Tv.create({name:"history",addOptions(){return{depth:100,newGroupDelay:500}},addCommands(){return{undo:()=>({state:s,dispatch:t})=>TUt(s,t),redo:()=>({state:s,dispatch:t})=>MUt(s,t)}},addProseMirrorPlugins(){return[IKs(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()}}}),RKs=My.create({name:"horizontalRule",addOptions(){return{HTMLAttributes:{}}},group:"block",parseHTML(){return[{tag:"hr"}]},renderHTML({HTMLAttributes:s}){return["hr",rp(this.options.HTMLAttributes,s)]},addCommands(){return{setHorizontalRule:()=>({chain:s,state:t})=>{if(!TWs(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}):QGs(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(jl.create(l.doc,d.pos+1)):d.nodeAfter.isBlock?l.setSelection(dl.create(l.doc,d.pos)):l.setSelection(jl.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(jl.create(l.doc,u+1)))}l.scrollIntoView()}return!0}).run()}}},addInputRules(){return[jUt({find:/^(?:---|—-|___\s|\*\*\*\s)$/,type:this.type})]}}),FKs=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,OKs=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,zKs=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,BKs=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g,UKs=ES.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",rp(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[BH({find:FKs,type:this.type}),BH({find:zKs,type:this.type})]},addPasteRules(){return[n9({find:OKs,type:this.type}),n9({find:BKs,type:this.type})]}}),qKs=My.create({name:"listItem",addOptions(){return{HTMLAttributes:{},bulletListTypeName:"bulletList",orderedListTypeName:"orderedList"}},content:"paragraph block*",defining:!0,parseHTML(){return[{tag:"li"}]},renderHTML({HTMLAttributes:s}){return["li",rp(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)}}}),$Ks="listItem",z0t="textStyle",B0t=/^(\d+)\.\s$/,VKs=My.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",rp(this.options.HTMLAttributes,n),0]:["ol",rp(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($Ks,this.editor.getAttributes(z0t)).run():s.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-7":()=>this.editor.commands.toggleOrderedList()}},addInputRules(){let s=Nte({find:B0t,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=Nte({find:B0t,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:t=>({start:+t[1],...this.editor.getAttributes(z0t)}),joinPredicate:(t,n)=>n.childCount+n.attrs.start===+t[1],editor:this.editor})),[s]}}),HKs=My.create({name:"paragraph",priority:1e3,addOptions(){return{HTMLAttributes:{}}},group:"block",content:"inline*",parseHTML(){return[{tag:"p"}]},renderHTML({HTMLAttributes:s}){return["p",rp(this.options.HTMLAttributes,s),0]},addCommands(){return{setParagraph:()=>({commands:s})=>s.setNode(this.name)}},addKeyboardShortcuts(){return{"Mod-Alt-0":()=>this.editor.commands.setParagraph()}}}),GKs=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))$/,WKs=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))/g,KKs=ES.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",rp(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[BH({find:GKs,type:this.type})]},addPasteRules(){return[n9({find:WKs,type:this.type})]}}),YKs=My.create({name:"text",group:"inline"}),ELe=Tv.create({name:"starterKit",addExtensions(){const s=[];return this.options.bold!==!1&&s.push(nKs.configure(this.options.bold)),this.options.blockquote!==!1&&s.push(QWs.configure(this.options.blockquote)),this.options.bulletList!==!1&&s.push(aKs.configure(this.options.bulletList)),this.options.code!==!1&&s.push(lKs.configure(this.options.code)),this.options.codeBlock!==!1&&s.push(uKs.configure(this.options.codeBlock)),this.options.document!==!1&&s.push(hKs.configure(this.options.document)),this.options.dropcursor!==!1&&s.push(fKs.configure(this.options.dropcursor)),this.options.gapcursor!==!1&&s.push(jKs.configure(this.options.gapcursor)),this.options.hardBreak!==!1&&s.push(NKs.configure(this.options.hardBreak)),this.options.heading!==!1&&s.push(kKs.configure(this.options.heading)),this.options.history!==!1&&s.push(DKs.configure(this.options.history)),this.options.horizontalRule!==!1&&s.push(RKs.configure(this.options.horizontalRule)),this.options.italic!==!1&&s.push(UKs.configure(this.options.italic)),this.options.listItem!==!1&&s.push(qKs.configure(this.options.listItem)),this.options.orderedList!==!1&&s.push(VKs.configure(this.options.orderedList)),this.options.paragraph!==!1&&s.push(HKs.configure(this.options.paragraph)),this.options.strike!==!1&&s.push(KKs.configure(this.options.strike)),this.options.text!==!1&&s.push(YKs.configure(this.options.text)),s}}),ZKs="aaa1rp3bb0ott3vie4c1le2ogado5udhabi7c0ademy5centure6ountant0s9o1tor4d0s1ult4e0g1ro2tna4f0l1rica5g0akhan5ency5i0g1rbus3force5tel5kdn3l0ibaba4pay4lfinanz6state5y2sace3tom5m0azon4ericanexpress7family11x2fam3ica3sterdam8nalytics7droid5quan4z2o0l2partments8p0le4q0uarelle8r0ab1mco4chi3my2pa2t0e3s0da2ia2sociates9t0hleta5torney7u0ction5di0ble3o3spost5thor3o0s4w0s2x0a2z0ure5ba0by2idu3namex4d1k2r0celona5laycard4s5efoot5gains6seball5ketball8uhaus5yern5b0c1t1va3cg1n2d1e0ats2uty4er2rlin4st0buy5t2f1g1h0arti5i0ble3d1ke2ng0o3o1z2j1lack0friday9ockbuster8g1omberg7ue3m0s1w2n0pparibas9o0ats3ehringer8fa2m1nd2o0k0ing5sch2tik2on4t1utique6x2r0adesco6idgestone9oadway5ker3ther5ussels7s1t1uild0ers6siness6y1zz3v1w1y1z0h3ca0b1fe2l0l1vinklein9m0era3p2non3petown5ital0one8r0avan4ds2e0er0s4s2sa1e1h1ino4t0ering5holic7ba1n1re3c1d1enter4o1rn3f0a1d2g1h0anel2nel4rity4se2t2eap3intai5ristmas6ome4urch5i0priani6rcle4sco3tadel4i0c2y3k1l0aims4eaning6ick2nic1que6othing5ud3ub0med6m1n1o0ach3des3ffee4llege4ogne5m0mbank4unity6pany2re3uter5sec4ndos3struction8ulting7tact3ractors9oking4l1p2rsica5untry4pon0s4rses6pa2r0edit0card4union9icket5own3s1uise0s6u0isinella9v1w1x1y0mru3ou3z2dad1nce3ta1e1ing3sun4y2clk3ds2e0al0er2s3gree4livery5l1oitte5ta3mocrat6ntal2ist5si0gn4v2hl2iamonds6et2gital5rect0ory7scount3ver5h2y2j1k1m1np2o0cs1tor4g1mains5t1wnload7rive4tv2ubai3nlop4pont4rban5vag2r2z2earth3t2c0o2deka3u0cation8e1g1mail3erck5nergy4gineer0ing9terprises10pson4quipment8r0icsson6ni3s0q1tate5t1u0rovision8s2vents5xchange6pert3osed4ress5traspace10fage2il1rwinds6th3mily4n0s2rm0ers5shion4t3edex3edback6rrari3ero6i0delity5o2lm2nal1nce1ial7re0stone6mdale6sh0ing5t0ness6j1k1lickr3ghts4r2orist4wers5y2m1o0o0d1tball6rd1ex2sale4um3undation8x2r0ee1senius7l1ogans4ntier7tr2ujitsu5n0d2rniture7tbol5yi3ga0l0lery3o1up4me0s3p1rden4y2b0iz3d0n2e0a1nt0ing5orge5f1g0ee3h1i0ft0s3ves2ing5l0ass3e1obal2o4m0ail3bh2o1x2n1odaddy5ld0point6f2o0dyear5g0le4p1t1v2p1q1r0ainger5phics5tis4een3ipe3ocery4up4s1t1u0cci3ge2ide2tars5ru3w1y2hair2mburg5ngout5us3bo2dfc0bank7ealth0care8lp1sinki6re1mes5iphop4samitsu7tachi5v2k0t2m1n1ockey4ldings5iday5medepot5goods5s0ense7nda3rse3spital5t0ing5t0els3mail5use3w2r1sbc3t1u0ghes5yatt3undai7ibm2cbc2e1u2d1e0ee3fm2kano4l1m0amat4db2mo0bilien9n0c1dustries8finiti5o2g1k1stitute6urance4e4t0ernational10uit4vestments10o1piranga7q1r0ish4s0maili5t0anbul7t0au2v3jaguar4va3cb2e0ep2tzt3welry6io2ll2m0p2nj2o0bs1urg4t1y2p0morgan6rs3uegos4niper7kaufen5ddi3e0rryhotels6properties14fh2g1h1i0a1ds2m1ndle4tchen5wi3m1n1oeln3matsu5sher5p0mg2n2r0d1ed3uokgroup8w1y0oto4z2la0caixa5mborghini8er3nd0rover6xess5salle5t0ino3robe5w0yer5b1c1ds2ease3clerc5frak4gal2o2xus4gbt3i0dl2fe0insurance9style7ghting6ke2lly3mited4o2ncoln4k2ve1ing5k1lc1p2oan0s3cker3us3l1ndon4tte1o3ve3pl0financial11r1s1t0d0a3u0ndbeck6xe1ury5v1y2ma0drid4if1son4keup4n0agement7go3p1rket0ing3s4riott5shalls7ttel5ba2c0kinsey7d1e0d0ia3et2lbourne7me1orial6n0u2rckmsd7g1h1iami3crosoft7l1ni1t2t0subishi9k1l0b1s2m0a2n1o0bi0le4da2e1i1m1nash3ey2ster5rmon3tgage6scow4to0rcycles9v0ie4p1q1r1s0d2t0n1r2u0seum3ic4v1w1x1y1z2na0b1goya4me2vy3ba2c1e0c1t0bank4flix4work5ustar5w0s2xt0direct7us4f0l2g0o2hk2i0co2ke1on3nja3ssan1y5l1o0kia3rton4w0ruz3tv4p1r0a1w2tt2u1yc2z2obi1server7ffice5kinawa6layan0group9lo3m0ega4ne1g1l0ine5oo2pen3racle3nge4g0anic5igins6saka4tsuka4t2vh3pa0ge2nasonic7ris2s1tners4s1y3y2ccw3e0t2f0izer5g1h0armacy6d1ilips5one2to0graphy6s4ysio5ics1tet2ures6d1n0g1k2oneer5zza4k1l0ace2y0station9umbing5s3m1n0c2ohl2ker3litie5rn2st3r0axi3ess3ime3o0d0uctions8f1gressive8mo2perties3y5tection8u0dential9s1t1ub2w0c2y2qa1pon3uebec3st5racing4dio4e0ad1lestate6tor2y4cipes5d0stone5umbrella9hab3ise0n3t2liance6n0t0als5pair3ort3ublican8st0aurant8view0s5xroth6ich0ardli6oh3l1o1p2o0cks3deo3gers4om3s0vp3u0gby3hr2n2w0e2yukyu6sa0arland6fe0ty4kura4le1on3msclub4ung5ndvik0coromant12ofi4p1rl2s1ve2xo3b0i1s2c0b1haeffler7midt4olarships8ol3ule3warz5ience5ot3d1e0arch3t2cure1ity6ek2lect4ner3rvices6ven3w1x0y3fr2g1h0angrila6rp3ell3ia1ksha5oes2p0ping5uji3w3i0lk2na1gles5te3j1k0i0n2y0pe4l0ing4m0art3ile4n0cf3o0ccer3ial4ftbank4ware6hu2lar2utions7ng1y2y2pa0ce3ort2t3r0l2s1t0ada2ples4r1tebank4farm7c0group6ockholm6rage3e3ream4udio2y3yle4u0cks3pplies3y2ort5rf1gery5zuki5v1watch4iss4x1y0dney4stems6z2tab1ipei4lk2obao4rget4tamotors6r2too4x0i3c0i2d0k2eam2ch0nology8l1masek5nnis4va3f1g1h0d1eater2re6iaa2ckets5enda4ps2res2ol4j0maxx4x2k0maxx5l1m0all4n1o0day3kyo3ols3p1ray3shiba5tal3urs3wn2yota3s3r0ade1ing4ining5vel0ers0insurance16ust3v2t1ube2i1nes3shu4v0s2w1z2ua1bank3s2g1k1nicom3versity8o2ol2ps2s1y1z2va0cations7na1guard7c1e0gas3ntures6risign5mögensberater2ung14sicherung10t2g1i0ajes4deo3g1king4llas4n1p1rgin4sa1ion4va1o3laanderen9n1odka3lvo3te1ing3o2yage5u2wales2mart4ter4ng0gou5tch0es6eather0channel12bcam3er2site5d0ding5ibo2r3f1hoswho6ien2ki2lliamhill9n0dows4e1ners6me2olterskluwer11odside6rk0s2ld3w2s1tc1f3xbox3erox4ihuan4n2xx2yz3yachts4hoo3maxun5ndex5e1odobashi7ga2kohama6u0tube6t1un3za0ppos4ra3ero3ip2m1one3uerich6w2",XKs="ελ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",JVe="numeric",eHe="ascii",tHe="alpha",RJ="asciinumeric",yX="alphanumeric",sHe="domain",PUt="emoji",QKs="scheme",JKs="slashscheme",T7e="whitespace";function eYs(s,t){return s in t||(t[s]=[]),t[s]}function vF(s,t,n){t[JVe]&&(t[RJ]=!0,t[yX]=!0),t[eHe]&&(t[RJ]=!0,t[tHe]=!0),t[RJ]&&(t[yX]=!0),t[tHe]&&(t[yX]=!0),t[yX]&&(t[sHe]=!0),t[PUt]&&(t[sHe]=!0);for(const r in t){const a=eYs(r,n);a.indexOf(s)<0&&a.push(s)}}function tYs(s,t){const n={};for(const r in t)t[r].indexOf(s)>=0&&(n[r]=!0);return n}function w_(s=null){this.j={},this.jr=[],this.jd=null,this.t=s}w_.groups={};w_.prototype={accepts(){return!!this.t},go(s){const t=this,n=t.j[s];if(n)return n;for(let r=0;rs.ta(t,n,r,a),lx=(s,t,n,r,a)=>s.tr(t,n,r,a),U0t=(s,t,n,r,a)=>s.ts(t,n,r,a),Ja=(s,t,n,r,a)=>s.tt(t,n,r,a),P3="WORD",nHe="UWORD",LUt="ASCIINUMERICAL",IUt="ALPHANUMERICAL",kte="LOCALHOST",rHe="TLD",aHe="UTLD",q4e="SCHEME",bU="SLASH_SCHEME",Yet="NUM",iHe="WS",Zet="NL",FJ="OPENBRACE",OJ="CLOSEBRACE",GAe="OPENBRACKET",WAe="CLOSEBRACKET",KAe="OPENPAREN",YAe="CLOSEPAREN",ZAe="OPENANGLEBRACKET",XAe="CLOSEANGLEBRACKET",QAe="FULLWIDTHLEFTPAREN",JAe="FULLWIDTHRIGHTPAREN",eEe="LEFTCORNERBRACKET",tEe="RIGHTCORNERBRACKET",sEe="LEFTWHITECORNERBRACKET",nEe="RIGHTWHITECORNERBRACKET",rEe="FULLWIDTHLESSTHAN",aEe="FULLWIDTHGREATERTHAN",iEe="AMPERSAND",oEe="APOSTROPHE",lEe="ASTERISK",m6="AT",cEe="BACKSLASH",dEe="BACKTICK",uEe="CARET",k6="COLON",Xet="COMMA",hEe="DOLLAR",U5="DOT",mEe="EQUALS",Qet="EXCLAMATION",T2="HYPHEN",zJ="PERCENT",pEe="PIPE",fEe="PLUS",xEe="POUND",BJ="QUERY",Jet="QUOTE",DUt="FULLWIDTHMIDDLEDOT",ett="SEMI",q5="SLASH",UJ="TILDE",gEe="UNDERSCORE",RUt="EMOJI",yEe="SYM";var FUt=Object.freeze({__proto__:null,ALPHANUMERICAL:IUt,AMPERSAND:iEe,APOSTROPHE:oEe,ASCIINUMERICAL:LUt,ASTERISK:lEe,AT:m6,BACKSLASH:cEe,BACKTICK:dEe,CARET:uEe,CLOSEANGLEBRACKET:XAe,CLOSEBRACE:OJ,CLOSEBRACKET:WAe,CLOSEPAREN:YAe,COLON:k6,COMMA:Xet,DOLLAR:hEe,DOT:U5,EMOJI:RUt,EQUALS:mEe,EXCLAMATION:Qet,FULLWIDTHGREATERTHAN:aEe,FULLWIDTHLEFTPAREN:QAe,FULLWIDTHLESSTHAN:rEe,FULLWIDTHMIDDLEDOT:DUt,FULLWIDTHRIGHTPAREN:JAe,HYPHEN:T2,LEFTCORNERBRACKET:eEe,LEFTWHITECORNERBRACKET:sEe,LOCALHOST:kte,NL:Zet,NUM:Yet,OPENANGLEBRACKET:ZAe,OPENBRACE:FJ,OPENBRACKET:GAe,OPENPAREN:KAe,PERCENT:zJ,PIPE:pEe,PLUS:fEe,POUND:xEe,QUERY:BJ,QUOTE:Jet,RIGHTCORNERBRACKET:tEe,RIGHTWHITECORNERBRACKET:nEe,SCHEME:q4e,SEMI:ett,SLASH:q5,SLASH_SCHEME:bU,SYM:yEe,TILDE:UJ,TLD:rHe,UNDERSCORE:gEe,UTLD:aHe,UWORD:nHe,WORD:P3,WS:iHe});const p3=/[a-z]/,GY=new RegExp("\\p{L}","u"),M7e=new RegExp("\\p{Emoji}","u"),f3=/\d/,P7e=/\s/,q0t="\r",L7e=` `,sYs="️",nYs="‍",I7e="";let Hle=null,Gle=null;function rYs(s=[]){const t={};w_.groups=t;const n=new w_;Hle==null&&(Hle=$0t(ZKs)),Gle==null&&(Gle=$0t(XKs)),Ja(n,"'",oEe),Ja(n,"{",FJ),Ja(n,"}",OJ),Ja(n,"[",GAe),Ja(n,"]",WAe),Ja(n,"(",KAe),Ja(n,")",YAe),Ja(n,"<",ZAe),Ja(n,">",XAe),Ja(n,"(",QAe),Ja(n,")",JAe),Ja(n,"「",eEe),Ja(n,"」",tEe),Ja(n,"『",sEe),Ja(n,"』",nEe),Ja(n,"<",rEe),Ja(n,">",aEe),Ja(n,"&",iEe),Ja(n,"*",lEe),Ja(n,"@",m6),Ja(n,"`",dEe),Ja(n,"^",uEe),Ja(n,":",k6),Ja(n,",",Xet),Ja(n,"$",hEe),Ja(n,".",U5),Ja(n,"=",mEe),Ja(n,"!",Qet),Ja(n,"-",T2),Ja(n,"%",zJ),Ja(n,"|",pEe),Ja(n,"+",fEe),Ja(n,"#",xEe),Ja(n,"?",BJ),Ja(n,'"',Jet),Ja(n,"/",q5),Ja(n,";",ett),Ja(n,"~",UJ),Ja(n,"_",gEe),Ja(n,"\\",cEe),Ja(n,"・",DUt);const r=lx(n,f3,Yet,{[JVe]:!0});lx(r,f3,r);const a=lx(r,p3,LUt,{[RJ]:!0}),i=lx(r,GY,IUt,{[yX]:!0}),l=lx(n,p3,P3,{[eHe]:!0});lx(l,f3,a),lx(l,p3,l),lx(a,f3,a),lx(a,p3,a);const o=lx(n,GY,nHe,{[tHe]:!0});lx(o,p3),lx(o,f3,i),lx(o,GY,o),lx(i,f3,i),lx(i,p3),lx(i,GY,i);const c=Ja(n,L7e,Zet,{[T7e]:!0}),d=Ja(n,q0t,iHe,{[T7e]:!0}),u=lx(n,P7e,iHe,{[T7e]:!0});Ja(n,I7e,u),Ja(d,L7e,c),Ja(d,I7e,u),lx(d,P7e,u),Ja(u,q0t),Ja(u,L7e),lx(u,P7e,u),Ja(u,I7e,u);const h=lx(n,M7e,RUt,{[PUt]:!0});Ja(h,"#"),lx(h,M7e,h),Ja(h,sYs,h);const m=Ja(h,nYs);Ja(m,"#"),lx(m,M7e,h);const p=[[p3,l],[f3,a]],f=[[p3,null],[GY,o],[f3,i]];for(let y=0;yy[0]>v[0]?1:-1);for(let y=0;y=0?b[sHe]=!0:p3.test(v)?f3.test(v)?b[RJ]=!0:b[eHe]=!0:b[JVe]=!0,U0t(n,v,v,b)}return U0t(n,"localhost",kte,{ascii:!0}),n.jd=new w_(yEe),{start:n,tokens:Object.assign({groups:t},FUt)}}function OUt(s,t){const n=aYs(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 aYs(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 NT(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 Ste={defaultProtocol:"http",events:null,format:V0t,formatHref:V0t,nl2br:!1,tagName:"a",target:null,rel:null,validate:!0,truncate:1/0,className:null,attributes:null,ignoreTags:[],render:null};function ttt(s,t=null){let n=Object.assign({},Ste);s&&(n=Object.assign(n,s instanceof ttt?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=Ste.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 TLe(s,t){class n extends zUt{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 H0t=TLe("email",{isLink:!0,toHref(){return"mailto:"+this.toString()}}),G0t=TLe("text"),iYs=TLe("nl"),Wle=TLe("url",{isLink:!0,toHref(s=Ste.defaultProtocol){return this.hasProtocol()?this.v:`${s}://${this.v}`},hasProtocol(){const s=this.tk;return s.length>=2&&s[0].t!==kte&&s[1].t===k6}}),f2=s=>new w_(s);function oYs({groups:s}){const t=s.domain.concat([iEe,lEe,m6,cEe,dEe,uEe,hEe,mEe,T2,Yet,zJ,pEe,fEe,xEe,q5,yEe,UJ,gEe]),n=[oEe,k6,Xet,U5,Qet,zJ,BJ,Jet,ett,ZAe,XAe,FJ,OJ,WAe,GAe,KAe,YAe,QAe,JAe,eEe,tEe,sEe,nEe,rEe,aEe],r=[iEe,oEe,lEe,cEe,dEe,uEe,hEe,mEe,T2,FJ,OJ,zJ,pEe,fEe,xEe,BJ,q5,yEe,UJ,gEe],a=f2(),i=Ja(a,UJ);ad(i,r,i),ad(i,s.domain,i);const l=f2(),o=f2(),c=f2();ad(a,s.domain,l),ad(a,s.scheme,o),ad(a,s.slashscheme,c),ad(l,r,i),ad(l,s.domain,l);const d=Ja(l,m6);Ja(i,m6,d),Ja(o,m6,d),Ja(c,m6,d);const u=Ja(i,U5);ad(u,r,i),ad(u,s.domain,i);const h=f2();ad(d,s.domain,h),ad(h,s.domain,h);const m=Ja(h,U5);ad(m,s.domain,h);const p=f2(H0t);ad(m,s.tld,p),ad(m,s.utld,p),Ja(d,kte,p);const f=Ja(h,T2);Ja(f,T2,f),ad(f,s.domain,h),ad(p,s.domain,h),Ja(p,U5,m),Ja(p,T2,f);const y=Ja(p,k6);ad(y,s.numeric,H0t);const v=Ja(l,T2),g=Ja(l,U5);Ja(v,T2,v),ad(v,s.domain,l),ad(g,r,i),ad(g,s.domain,l);const b=f2(Wle);ad(g,s.tld,b),ad(g,s.utld,b),ad(b,s.domain,l),ad(b,r,i),Ja(b,U5,g),Ja(b,T2,v),Ja(b,m6,d);const j=Ja(b,k6),S=f2(Wle);ad(j,s.numeric,S);const C=f2(Wle),E=f2();ad(C,t,C),ad(C,n,E),ad(E,t,C),ad(E,n,E),Ja(b,q5,C),Ja(S,q5,C);const P=Ja(o,k6),M=Ja(c,k6),I=Ja(M,q5),D=Ja(I,q5);ad(o,s.domain,l),Ja(o,U5,g),Ja(o,T2,v),ad(c,s.domain,l),Ja(c,U5,g),Ja(c,T2,v),ad(P,s.domain,C),Ja(P,q5,C),Ja(P,BJ,C),ad(D,s.domain,C),ad(D,t,C),Ja(D,q5,C);const O=[[FJ,OJ],[GAe,WAe],[KAe,YAe],[ZAe,XAe],[QAe,JAe],[eEe,tEe],[sEe,nEe],[rEe,aEe]];for(let V=0;V=0&&m++,a++,u++;if(m<0)a-=u,a0&&(i.push(D7e(G0t,t,l)),l=[]),a-=m,u-=m;const p=h.t,f=n.slice(a-u,a);i.push(D7e(p,t,f))}}return l.length>0&&i.push(D7e(G0t,t,l)),i}function D7e(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 cYs=typeof console<"u"&&console&&console.warn||(()=>{}),dYs="until manual call of linkify.init(). Register all schemes and plugins before invoking linkify the first time.",_p={scanner:null,parser:null,tokenQueue:[],pluginQueue:[],customSchemes:[],initialized:!1};function uYs(){return w_.groups={},_p.scanner=null,_p.parser=null,_p.tokenQueue=[],_p.pluginQueue=[],_p.customSchemes=[],_p.initialized=!1,_p}function W0t(s,t=!1){if(_p.initialized&&cYs(`linkifyjs: already initialized - will not register custom scheme "${s}" ${dYs}`),!/^[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`);_p.customSchemes.push([s,t])}function hYs(){_p.scanner=rYs(_p.customSchemes);for(let s=0;s<_p.tokenQueue.length;s++)_p.tokenQueue[s][1]({scanner:_p.scanner});_p.parser=oYs(_p.scanner.tokens);for(let s=0;s<_p.pluginQueue.length;s++)_p.pluginQueue[s][1]({scanner:_p.scanner,parser:_p.parser});return _p.initialized=!0,_p}function stt(s){return _p.initialized||hYs(),lYs(_p.parser.start,s,OUt(_p.scanner.start,s))}stt.scan=OUt;function BUt(s,t=null,n=null){if(t&&typeof t=="object"){if(n)throw Error(`linkifyjs: Invalid link type ${t}; must be a string`);n=t,t=null}const r=new ttt(n),a=stt(s),i=[];for(let l=0;l{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=$Gs(n.doc,[...t]);if(ZGs(o).forEach(({newRange:d})=>{const u=HGs(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(!pYs.test(p))return;h=u[0],m=r.doc.textBetween(h.pos,d.to,void 0," ")}if(h&&m){const p=m.split(mYs).filter(Boolean);if(p.length<=0)return!1;const f=p[p.length-1],y=h.pos+m.lastIndexOf(f);if(!f)return!1;const v=stt(f).map(g=>g.toObject(s.defaultProtocol));if(!xYs(v))return!1;v.filter(g=>g.isLink).map(g=>({...g,from:y+g.start+1,to:y+g.end+1})).filter(g=>r.schema.marks.code?!r.doc.rangeHasMark(g.from,g.to,r.schema.marks.code):!0).filter(g=>s.validate(g.value)).filter(g=>s.shouldAutoLink(g.value)).forEach(g=>{Vet(g.from,g.to,r.doc).some(b=>b.mark.type===s.type)||l.addMark(g.from,g.to,s.type.create({href:g.href}))})}}),!!l.steps.length)return l}})}function yYs(s){return new F0({key:new k1("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=wUt(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 vYs(s){return new F0({key:new k1("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=BUt(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 _I(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(fYs,"").match(new RegExp(`^(?:(?:${n.join("|")}):|[^a-z]|[a-z0-9+.-]+(?:[^a-z+.-:]|$))`,"i"))}const MLe=ES.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"){W0t(s);return}W0t(s.scheme,s.optionalSlashes)})},onDestroy(){uYs()},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)=>!!_I(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=>!!_I(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=>!!_I(t,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?["a",rp(this.options.HTMLAttributes,s),0]:["a",rp(this.options.HTMLAttributes,{...s,href:""}),0]},addCommands(){return{setLink:s=>({chain:t})=>{const{href:n}=s;return this.options.isAllowedUri(n,{defaultValidate:r=>!!_I(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=>!!_I(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[n9({find:s=>{const t=[];if(s){const{protocols:n,defaultProtocol:r}=this.options,a=BUt(s).filter(i=>i.isLink&&this.options.isAllowedUri(i.value,{defaultValidate:l=>!!_I(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(gYs({type:this.type,defaultProtocol:this.options.defaultProtocol,validate:r=>this.options.isAllowedUri(r,{defaultValidate:a=>!!_I(a,t),protocols:t,defaultProtocol:n}),shouldAutoLink:this.options.shouldAutoLink})),this.options.openOnClick===!0&&s.push(yYs({type:this.type})),this.options.linkOnPaste&&s.push(vYs({editor:this.editor,defaultProtocol:this.options.defaultProtocol,type:this.type})),s}}),PLe=Tv.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")}}}),bYs=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}`)})},rtt=ES.create({name:"textStyle",priority:101,addOptions(){return{HTMLAttributes:{},mergeNestedSpanStyles:!1}},parseHTML(){return[{tag:"span",getAttrs:s=>s.hasAttribute("style")?(this.options.mergeNestedSpanStyles&&bYs(s),{}):!1}]},renderHTML({HTMLAttributes:s}){return["span",rp(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}}}}),_Ys=/(?:^|\s)(!\[(.+|:?)]\((\S+)(?:(?:\s+)["'](\S+)["'])?\))$/,UUt=My.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",rp(this.options.HTMLAttributes,s)]},addCommands(){return{setImage:s=>({commands:t})=>t.insertContent({type:this.name,attrs:s})}},addInputRules(){return[jUt({find:_Ys,type:this.type,getAttributes:s=>{const[,,t,n,r]=s;return{src:n,alt:t,title:r}}})]}});let oHe,lHe;if(typeof WeakMap<"u"){let s=new WeakMap;oHe=t=>s.get(t),lHe=(t,n)=>(s.set(t,n),n)}else{const s=[];let n=0;oHe=r=>{for(let a=0;a(n==10&&(n=0),s[n++]=r,s[n++]=a)}var bx=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:g-j});break}const S=a+j*t;for(let C=0;Cr&&(i+=d.attrs.colspan)}}for(let l=0;l1&&(n=!0)}t==-1?t=i:t!=i&&(t=Math.max(t,i))}return t}function NYs(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 SYs(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 RS(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 LLe(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=r9(t.$head)||CYs(t.$head);if(n)return n;throw new RangeError(`No cell found around position ${t.head}`)}function CYs(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 cHe(s){return s.parent.type.spec.tableRole=="row"&&!!s.nodeAfter}function AYs(s){return s.node(0).resolve(s.pos+s.nodeAfter.nodeSize)}function att(s,t){return s.depth==t.depth&&s.pos>=t.start(-1)&&s.pos<=t.end(-1)}function qUt(s,t,n){const r=s.node(-1),a=bx.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 a9(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 $Ut(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 bBt(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(cHe(r)&&cHe(a)&&att(r,a)){const i=this.$anchorCell.node(-1)!=r.node(-1);return i&&this.isRowSelection()?L3.rowSelection(r,a):i&&this.isColSelection()?L3.colSelection(r,a):new L3(r,a)}return jl.between(r,a)}content(){const t=this.$anchorCell.node(-1),n=bx.get(t),r=this.$anchorCell.start(-1),a=n.rectBetween(this.$anchorCell.pos-r,this.$headCell.pos-r),i={},l=[];for(let c=a.top;c0||v>0){let g=f.attrs;if(y>0&&(g=a9(g,0,y)),v>0&&(g=a9(g,g.colspan-v,v)),p.lefta.bottom){const g={...f.attrs,rowspan:Math.min(p.bottom,a.bottom)-Math.max(p.top,a.top)};p.top0)return!1;const r=t+this.$anchorCell.nodeAfter.attrs.rowspan,a=n+this.$headCell.nodeAfter.attrs.rowspan;return Math.max(r,a)==this.$headCell.node(-1).childCount}static colSelection(t,n=t){const r=t.node(-1),a=bx.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 L3&&t.$anchorCell.pos==this.$anchorCell.pos&&t.$headCell.pos==this.$headCell.pos}static rowSelection(t,n=t){const r=t.node(-1),a=bx.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(pb.node(r,r+n.nodeSize,{class:"selectedCell"}))}),yx.create(s.doc,t)}function PYs({$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 LYs({$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 IYs(s,t,n){const r=(t||s).selection,a=(t||s).doc;let i,l;if(r instanceof dl&&(l=r.node.type.spec.tableRole)){if(l=="cell"||l=="header_cell")i=np.create(a,r.from);else if(l=="row"){const o=a.resolve(r.from+1);i=np.rowSelection(o,o)}else if(!n){const o=bx.get(r.node),c=r.from+1,d=c+o.map[o.width*o.height-1];i=np.create(a,c+1,d)}}else r instanceof jl&&PYs(r)?i=jl.create(a,r.from):r instanceof jl&&LYs(r)&&(i=jl.create(a,r.$from.start(),r.$from.end()));return i&&(t||(t=s.tr)).setSelection(i),t}const DYs=new k1("fix-tables");function HUt(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=RYs(s,a,i,n))};return t?t.doc!=s.doc&&HUt(t.doc,s.doc,0,r):s.doc.descendants(r),n}function RYs(s,t,n,r){const a=bx.get(t);if(!a.problems)return r;r||(r=s.tr);const i=[];for(let c=0;c0){let p="cell";u.firstChild&&(p=u.firstChild.type.spec.tableRole);const f=[];for(let v=0;v0?-1:0;EYs(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;UYs(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=K0t(d)?c+1:u;i.replaceWith(h+r.tableStart,u+r.tableStart,o)}i.setSelection(new np(i.doc.resolve(c+r.tableStart))),t(i)}return!0}function Z0t(s,t){const n=_1(s.schema);return WYs(({node:r})=>n[r.type.spec.tableRole])(s,t)}function WYs(s){return(t,n)=>{const r=t.selection;let a,i;if(r instanceof np){if(r.$anchorCell.pos!=r.$headCell.pos)return!1;a=r.$anchorCell.nodeAfter,i=r.$anchorCell.pos}else{var l;if(a=SYs(r.$from),!a)return!1;i=(l=r9(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=NC(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 YYs(s){return function(t,n){if(!RS(t))return!1;if(n){const r=_1(t.schema),a=NC(t),i=t.tr,l=a.map.cellsInRect(s=="column"?{left:a.left,top:0,right:a.right,bottom:a.map.height}:s=="row"?{left:0,top:a.top,right:a.map.width,bottom:a.bottom}:a),o=l.map(c=>a.table.nodeAt(c));for(let c=0;c{const p=m+i.tableStart,f=l.doc.nodeAt(p);f&&l.setNodeMarkup(p,h,f.attrs)}),r(l)}return!0}}Cte("row",{useDeprecatedLogic:!0});Cte("column",{useDeprecatedLogic:!0});const ZYs=Cte("cell",{useDeprecatedLogic:!0});function XYs(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 Kle(s,t){const n=s.selection;if(!(n instanceof np))return!1;if(t){const r=s.tr,a=_1(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 Pi(a,0,0))}),r.docChanged&&t(r)}return!0}function JYs(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(Ha.empty),n[a]r&&(m=m.type.createChecked(a9(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(Ha.from(c))}n=i,t=a}return{width:s,height:t,rows:n}}function sZs(s,t,n,r,a,i,l){const o=s.doc.type.schema,c=_1(o);let d,u;if(a>t.width)for(let h=0,m=0;ht.height){const h=[];for(let f=0,y=(t.height-1)*t.width;f=t.width?!1:n.nodeAt(t.map[y+f]).type==c.header_cell;h.push(v?u||(u=c.header_cell.createAndFill()):d||(d=c.cell.createAndFill()))}const m=c.row.create(null,Ha.from(h)),p=[];for(let f=t.height;f{if(!a)return!1;const i=n.selection;if(i instanceof np)return $4e(n,r,Wl.near(i.$headCell,t));if(s!="horiz"&&!i.empty)return!1;const l=YUt(a,s,t);if(l==null)return!1;if(s=="horiz")return $4e(n,r,Wl.near(n.doc.resolve(i.head+t),t));{const o=n.doc.resolve(l),c=qUt(o,s,t);let d;return c?d=Wl.near(c,1):t<0?d=Wl.near(n.doc.resolve(o.before(-1)),-1):d=Wl.near(n.doc.resolve(o.after(-1)),1),$4e(n,r,d)}}}function Zle(s,t){return(n,r,a)=>{if(!a)return!1;const i=n.selection;let l;if(i instanceof np)l=i;else{const c=YUt(a,s,t);if(c==null)return!1;l=new np(n.doc.resolve(c))}const o=qUt(l.$headCell,s,t);return o?$4e(n,r,new np(l.$anchorCell,o)):!1}}function rZs(s,t){const n=s.state.doc,r=r9(n.resolve(t));return r?(s.dispatch(s.state.tr.setSelection(new np(r))),!0):!1}function aZs(s,t,n){if(!RS(s.state))return!1;let r=JYs(n);const a=s.state.selection;if(a instanceof np){r||(r={width:1,height:1,rows:[Ha.from(dHe(_1(s.state.schema).cell,n))]});const i=a.$anchorCell.node(-1),l=a.$anchorCell.start(-1),o=bx.get(i).rectBetween(a.$anchorCell.pos-l,a.$headCell.pos-l);return r=tZs(r,o.right-o.left,o.bottom-o.top),tyt(s.state,s.dispatch,l,o,r),!0}else if(r){const i=LLe(s.state),l=i.start(-1);return tyt(s.state,s.dispatch,l,bx.get(i.node(-1)).findCell(i.pos-l),r),!0}else return!1}function iZs(s,t){var n;if(t.button!=0||t.ctrlKey||t.metaKey)return;const r=syt(s,t.target);let a;if(t.shiftKey&&s.state.selection instanceof np)i(s.state.selection.$anchorCell,t),t.preventDefault();else if(t.shiftKey&&r&&(a=r9(s.state.selection.$anchor))!=null&&((n=R7e(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=R7e(s,d);const h=S6.getState(s.state)==null;if(!u||!att(c,u))if(h)u=c;else return;const m=new np(c,u);if(h||!s.state.selection.eq(m)){const p=s.state.tr.setSelection(m);h&&p.setMeta(S6,c.pos),s.dispatch(p)}}function l(){s.root.removeEventListener("mouseup",l),s.root.removeEventListener("dragstart",l),s.root.removeEventListener("mousemove",o),S6.getState(s.state)!=null&&s.dispatch(s.state.tr.setMeta(S6,-1))}function o(c){const d=c,u=S6.getState(s.state);let h;if(u!=null)h=s.state.doc.resolve(u);else if(syt(s,d.target)!=r&&(h=R7e(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 YUt(s,t,n){if(!(s.state.selection instanceof jl))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 syt(s,t){for(;t&&t!=s.dom;t=t.parentNode)if(t.nodeName=="TD"||t.nodeName=="TH")return t;return null}function R7e(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&&r9(s.state.doc.resolve(r))||r9(s.state.doc.resolve(a))}var oZs=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")),uHe(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,uHe(t,this.colgroup,this.table,this.defaultCellMinWidth),!0)}ignoreMutation(t){return t.type=="attributes"&&(t.target==this.table||this.colgroup.contains(t.target))}};function uHe(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 cZs(-1,!1)},apply(l,o){return o.apply(l)}},props:{attributes:l=>{const o=Qw.getState(l);return o&&o.activeHandle>-1?{class:"resize-cursor"}:{}},handleDOMEvents:{mousemove:(l,o)=>{dZs(l,o,s,a)},mouseleave:l=>{uZs(l)},mousedown:(l,o)=>{hZs(l,o,t,n)}},decorations:l=>{const o=Qw.getState(l);if(o&&o.activeHandle>-1)return gZs(l,o.activeHandle)},nodeViews:{}}});return i}var cZs=class V4e{constructor(t,n){this.activeHandle=t,this.dragging=n}apply(t){const n=this,r=t.getMeta(Qw);if(r&&r.setHandle!=null)return new V4e(r.setHandle,!1);if(r&&r.setDragging!==void 0)return new V4e(n.activeHandle,r.setDragging);if(n.activeHandle>-1&&t.docChanged){let a=t.mapping.map(n.activeHandle,-1);return cHe(t.doc.resolve(a))||(a=-1),new V4e(a,n.dragging)}return n}};function dZs(s,t,n,r){if(!s.editable)return;const a=Qw.getState(s.state);if(a&&!a.dragging){const i=pZs(t.target);let l=-1;if(i){const{left:o,right:c}=i.getBoundingClientRect();t.clientX-o<=n?l=nyt(s,t,"left",n):c-t.clientX<=n&&(l=nyt(s,t,"right",n))}if(l!=a.activeHandle){if(!r&&l!==-1){const o=s.state.doc.resolve(l),c=o.node(-1),d=bx.get(c),u=o.start(-1);if(d.colCount(o.pos-u)+o.nodeAfter.attrs.colspan-1==d.width-1)return}ZUt(s,l)}}}function uZs(s){if(!s.editable)return;const t=Qw.getState(s.state);t&&t.activeHandle>-1&&!t.dragging&&ZUt(s,-1)}function hZs(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=Qw.getState(s.state);if(!l||l.activeHandle==-1||l.dragging)return!1;const o=s.state.doc.nodeAt(l.activeHandle),c=mZs(s,l.activeHandle,o.attrs);s.dispatch(s.state.tr.setMeta(Qw,{setDragging:{startX:t.clientX,startWidth:c}}));function d(h){i.removeEventListener("mouseup",d),i.removeEventListener("mousemove",u);const m=Qw.getState(s.state);m!=null&&m.dragging&&(fZs(s,m.activeHandle,ryt(m.dragging,h,n)),s.dispatch(s.state.tr.setMeta(Qw,{setDragging:null})))}function u(h){if(!h.which)return d(h);const m=Qw.getState(s.state);if(m&&m.dragging){const p=ryt(m.dragging,h,n);ayt(s,m.activeHandle,p,r)}}return ayt(s,l.activeHandle,c,r),i.addEventListener("mouseup",d),i.addEventListener("mousemove",u),t.preventDefault(),!0}function mZs(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 wZs(s,t,n,r,a){const i=_Zs(s),l=[],o=[];for(let d=0;d{const{selection:t}=s.state;if(!jZs(t))return!1;let n=0;const r=_Ut(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},NZs=My.create({name:"table",addOptions(){return{HTMLAttributes:{},resizable:!1,renderWrapper:!1,handleWidth:5,cellMinWidth:25,View:vZs,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}=bZs(s,this.options.cellMinWidth),i=["table",rp(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=wZs(i.schema,s,t,n);if(a){const o=r.selection.from+1;r.replaceSelectionWith(l).scrollIntoView().setSelection(jl.near(r.doc.resolve(o)))}return!0},addColumnBefore:()=>({state:s,dispatch:t})=>FYs(s,t),addColumnAfter:()=>({state:s,dispatch:t})=>OYs(s,t),deleteColumn:()=>({state:s,dispatch:t})=>BYs(s,t),addRowBefore:()=>({state:s,dispatch:t})=>qYs(s,t),addRowAfter:()=>({state:s,dispatch:t})=>$Ys(s,t),deleteRow:()=>({state:s,dispatch:t})=>HYs(s,t),deleteTable:()=>({state:s,dispatch:t})=>QYs(s,t),mergeCells:()=>({state:s,dispatch:t})=>Y0t(s,t),splitCell:()=>({state:s,dispatch:t})=>Z0t(s,t),toggleHeaderColumn:()=>({state:s,dispatch:t})=>Cte("column")(s,t),toggleHeaderRow:()=>({state:s,dispatch:t})=>Cte("row")(s,t),toggleHeaderCell:()=>({state:s,dispatch:t})=>ZYs(s,t),mergeOrSplit:()=>({state:s,dispatch:t})=>Y0t(s,t)?!0:Z0t(s,t),setCellAttribute:(s,t)=>({state:n,dispatch:r})=>KYs(s,t)(n,r),goToNextCell:()=>({state:s,dispatch:t})=>Q0t(1)(s,t),goToPreviousCell:()=>({state:s,dispatch:t})=>Q0t(-1)(s,t),fixTables:()=>({state:s,dispatch:t})=>(t&&GUt(s),!0),setCellSelection:s=>({tr:t,dispatch:n})=>{if(n){const r=np.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:Xle,"Mod-Backspace":Xle,Delete:Xle,"Mod-Delete":Xle}},addProseMirrorPlugins(){return[...this.options.resizable&&this.editor.isEditable?[lZs({handleWidth:this.options.handleWidth,cellMinWidth:this.options.cellMinWidth,defaultCellMinWidth:this.options.cellMinWidth,View:this.options.View,lastColumnResizable:this.options.lastColumnResizable})]:[],yZs({allowTableNodeSelection:this.options.allowTableNodeSelection})]},extendNodeSchema(s){const t={name:s.name,options:s.options,storage:s.storage};return{tableRole:Bc(No(s,"tableRole",t))}}}),kZs=My.create({name:"tableRow",addOptions(){return{HTMLAttributes:{}}},content:"(tableCell | tableHeader)*",tableRole:"row",parseHTML(){return[{tag:"tr"}]},renderHTML({HTMLAttributes:s}){return["tr",rp(this.options.HTMLAttributes,s),0]}}),SZs=My.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",rp(this.options.HTMLAttributes,s),0]}}),CZs=My.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",rp(this.options.HTMLAttributes,s),0]}});function BN({content:s,onChange:t,placeholder:n="Enter content...",minHeight:r="150px",compact:a=!1}){const[i,l]=_.useState(!1),[o,c]=_.useState(""),[d,u]=_.useState(!0),h=ALe({extensions:[ELe,MLe.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline"}}),PLe.configure({types:["heading","paragraph"]}),rtt,UUt.extend({addAttributes(){var y;return{...(y=this.parent)==null?void 0:y.call(this),width:{default:null},height:{default:null},style:{default:null}}}}).configure({inline:!0,allowBase64:!0}),NZs.extend({addAttributes(){var y;return{...(y=this.parent)==null?void 0:y.call(this),style:{default:null},width:{default:null},cellpadding:{default:null},cellspacing:{default:null},border:{default:null}}}}).configure({resizable:!1}),kZs.extend({addAttributes(){var y;return{...(y=this.parent)==null?void 0:y.call(this),style:{default:null}}}}),SZs.extend({addAttributes(){var y;return{...(y=this.parent)==null?void 0:y.call(this),style:{default:null},width:{default:null},colspan:{default:1},rowspan:{default:1},valign:{default:null}}}}),CZs.extend({addAttributes(){var y;return{...(y=this.parent)==null?void 0:y.call(this),style:{default:null},width:{default:null},colspan:{default:1},rowspan:{default:1}}}})],content:s,onUpdate:({editor:y})=>{t(y.getHTML())},editorProps:{attributes:{class:"outline-none","data-placeholder":n},handlePaste:(y,v)=>{var b;const g=(b=v.clipboardData)==null?void 0:b.items;if(!g)return!1;for(const j of Array.from(g))if(j.type.startsWith("image/")){v.preventDefault();const S=j.getAsFile();if(!S)continue;const C=new FileReader;return C.onload=E=>{var M;const P=(M=E.target)==null?void 0:M.result;y.dispatch(y.state.tr.replaceSelectionWith(y.state.schema.nodes.image.create({src:P})))},C.readAsDataURL(S),!0}return!1}}});_.useEffect(()=>{h&&s!==h.getHTML()&&h.commands.setContent(s)},[s,h]);const m=()=>{if(!h)return;const y=h.getAttributes("link").href||"",v=h.getAttributes("link").target;c(y),u(v==="_blank"),l(!0)},p=()=>{h&&(o===""?h.chain().focus().extendMarkRange("link").unsetLink().run():h.chain().focus().extendMarkRange("link").setLink({href:o,target:d?"_blank":null,rel:d?"noopener noreferrer nofollow":null}).run(),l(!1),c(""))},f=()=>{h&&h.chain().focus().extendMarkRange("link").unsetLink().run()};return h?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-0.5 p-2 border-b bg-muted/30",children:[e.jsx(B,{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(Oq,{className:"h-4 w-4"})}),e.jsx(B,{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(ZO,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().toggleBold().run(),className:h.isActive("bold")?"bg-muted":"",title:"Bold",children:e.jsx(BA,{className:"h-4 w-4"})}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().toggleItalic().run(),className:h.isActive("italic")?"bg-muted":"",title:"Italic",children:e.jsx($A,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().toggleBulletList().run(),className:h.isActive("bulletList")?"bg-muted":"",title:"Bullet List",children:e.jsx(A0,{className:"h-4 w-4"})}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().toggleOrderedList().run(),className:h.isActive("orderedList")?"bg-muted":"",title:"Numbered List",children:e.jsx(xj,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(B,{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(qM,{className:"h-4 w-4"})}),e.jsx(B,{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(UM,{className:"h-4 w-4"})}),e.jsx(B,{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($M,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:m,className:h.isActive("link")?"bg-muted":"",title:"Add Link",children:e.jsx(Vc,{className:"h-4 w-4"})}),h.isActive("link")&&e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:f,title:"Remove Link",children:e.jsx(Vc,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().undo().run(),disabled:!h.can().undo(),title:"Undo",children:e.jsx(JA,{className:"h-4 w-4"})}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().redo().run(),disabled:!h.can().redo(),title:"Redo",children:e.jsx(XA,{className:"h-4 w-4"})})]}),e.jsx(CLe,{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(Ls,{open:i,onOpenChange:l,children:e.jsxs(Ps,{className:"sm:max-w-md",children:[e.jsx(Os,{children:e.jsx(Ds,{children:"Insert Link"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"link-url",children:"URL"}),e.jsx(xe,{id:"link-url",value:o,onChange:y=>c(y.target.value),placeholder:"https://example.com"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(fn,{id:"link-new-tab",checked:d,onCheckedChange:u}),e.jsx(J,{htmlFor:"link-new-tab",children:"Open in new tab"})]})]}),e.jsxs(yr,{children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(B,{type:"button",onClick:p,children:o?"Apply Link":"Remove Link"})]})]})})]}):null}var AZs=Object.defineProperty,EZs=(s,t,n)=>t in s?AZs(s,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):s[t]=n,Kp=(s,t,n)=>EZs(s,typeof t!="symbol"?t+"":t,n);const vEe={x:0,y:0,width:0,height:0,unit:"px"},SB=(s,t,n)=>Math.min(Math.max(s,t),n),TZs=(...s)=>s.filter(t=>t&&typeof t=="string").join(" "),lyt=(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 MZs(s,t,n,r){const a=$5(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==="%"?p6(a,n,r):a}function PZs(s,t,n){const r=$5(s,t,n);return r.x=(t-r.width)/2,r.y=(n-r.height)/2,s.unit==="%"?p6(r,t,n):r}function p6(s,t,n){return s.unit==="%"?{...vEe,...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 $5(s,t,n){return s.unit?s.unit==="px"?{...vEe,...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}:{...vEe,...s,unit:"px"}}function cyt(s,t,n,r,a,i=0,l=0,o=r,c=a){const d={...s};let u=Math.min(i,r),h=Math.min(l,a),m=Math.min(o,r),p=Math.min(c,a);t&&(t>1?(u=l?l*t:u,h=u/t,m=o*t):(h=i?i/t:h,u=h*t,p=c/t)),d.y<0&&(d.height=Math.max(d.height+d.y,h),d.y=0),d.x<0&&(d.width=Math.max(d.width+d.x,u),d.x=0);const f=r-(d.x+d.width);f<0&&(d.x=Math.min(d.x,r-u),d.width+=f);const y=a-(d.y+d.height);if(y<0&&(d.y=Math.min(d.y,a-h),d.height+=y),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 v=d.width/d.height;if(vt){const g=Math.max(d.height*t,u);(n==="sw"||n=="nw")&&(d.x-=g-d.width),d.width=g}}return d}function LZs(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 CB={capture:!0,passive:!1};let IZs=0;const KT=class _k extends _.PureComponent{constructor(){super(...arguments),Kp(this,"docMoveBound",!1),Kp(this,"mouseDownOnCrop",!1),Kp(this,"dragStarted",!1),Kp(this,"evData",{startClientX:0,startClientY:0,startCropX:0,startCropY:0,clientX:0,clientY:0,isResize:!0}),Kp(this,"componentRef",_.createRef()),Kp(this,"mediaRef",_.createRef()),Kp(this,"resizeObserver"),Kp(this,"initChangeCalled",!1),Kp(this,"instanceId",`rc-${IZs++}`),Kp(this,"state",{cropIsActive:!1,newCropIsBeingDrawn:!1}),Kp(this,"onCropPointerDown",t=>{const{crop:n,disabled:r}=this.props,a=this.getBox();if(!n)return;const i=$5(n,a.width,a.height);if(r)return;t.cancelable&&t.preventDefault(),this.bindDocMove(),this.componentRef.current.focus({preventScroll:!0});const l=t.target.dataset.ord,o=!!l;let c=t.clientX,d=t.clientY,u=i.x,h=i.y;if(l){const m=t.clientX-a.x,p=t.clientY-a.y;let f=0,y=0;l==="ne"||l=="e"?(f=m-(i.x+i.width),y=p-i.y,u=i.x,h=i.y+i.height):l==="se"||l==="s"?(f=m-(i.x+i.width),y=p-(i.y+i.height),u=i.x,h=i.y):l==="sw"||l=="w"?(f=m-i.x,y=p-(i.y+i.height),u=i.x+i.width,h=i.y):(l==="nw"||l=="n")&&(f=m-i.x,y=p-i.y,u=i.x+i.width,h=i.y+i.height),c=u+a.x+f,d=h+a.y+y}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})}),Kp(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($5(u,o.width,o.height),p6(u,o.width,o.height)),this.setState({cropIsActive:!0,newCropIsBeingDrawn:!0})}),Kp(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(),lyt(n,c)||a($5(c,l.width,l.height),p6(c,l.width,l.height))}),Kp(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)?_k.nudgeStepLarge:t.shiftKey?_k.nudgeStepMedium:_k.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=SB(d.x,0,c.width-d.width),d.y=SB(d.y,0,c.height-d.height);const h=$5(d,c.width,c.height),m=p6(d,c.width,c.height);a(h,m),i&&i(h,m)}}),Kp(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)?_k.nudgeStepLarge:t.shiftKey?_k.nudgeStepMedium:_k.nudgeStep,f=$5(a,m.width,m.height),y=LZs(f,t.key,p,n),v=cyt(y,r,n,m.width,m.height,l,o,c,d);if(!lyt(a,v)){const g=p6(v,m.width,m.height);u(v,g),h&&h(v,g)}}),Kp(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($5(n,l.width,l.height),p6(n,l.width,l.height)),this.setState({cropIsActive:!1,newCropIsBeingDrawn:!1}))}),Kp(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($5(n,a,i),p6(n,a,i))}}componentWillUnmount(){this.resizeObserver&&this.resizeObserver.disconnect(),this.unbindDocMove()}bindDocMove(){this.docMoveBound||(this.document.addEventListener("pointermove",this.onDocPointerMove,CB),this.document.addEventListener("pointerup",this.onDocPointerDone,CB),this.document.addEventListener("pointercancel",this.onDocPointerDone,CB),this.docMoveBound=!0)}unbindDocMove(){this.docMoveBound&&(this.document.removeEventListener("pointermove",this.onDocPointerMove,CB),this.document.removeEventListener("pointerup",this.onDocPointerDone,CB),this.document.removeEventListener("pointercancel",this.onDocPointerDone,CB),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=SB(t.startCropX+a,0,n.width-r.width),r.y=SB(t.startCropY+i,0,n.height-r.height),r}getPointRegion(t,n,r,a){const{evData:i}=this,l=i.clientX-t.x,o=i.clientY-t.y;let c;a&&n?c=n==="nw"||n==="n"||n==="ne":c=o1?i?[i,i/n]:[l*n,l]:l?[l*n,l]:[i,i/n]}resizeCrop(){const{evData:t}=this,{aspect:n=0,maxWidth:r,maxHeight:a}=this.props,i=this.getBox(),[l,o]=this.resolveMinDimensions(i,n,this.props.minWidth,this.props.minHeight);let c=this.makePixelCrop(i);const d=this.getPointRegion(i,t.ord,l,o),u=t.ord||d;let h=t.clientX-t.startClientX,m=t.clientY-t.startClientY;(l&&u==="nw"||u==="w"||u==="sw")&&(h=Math.min(h,-l)),(o&&u==="nw"||u==="n"||u==="ne")&&(m=Math.min(m,-o));const p={unit:"px",x:0,y:0,width:0,height:0};d==="ne"?(p.x=t.startCropX,p.width=h,n?(p.height=p.width/n,p.y=t.startCropY-p.height):(p.height=Math.abs(m),p.y=t.startCropY-p.height)):d==="se"?(p.x=t.startCropX,p.y=t.startCropY,p.width=h,n?p.height=p.width/n:p.height=m):d==="sw"?(p.x=t.startCropX+h,p.y=t.startCropY,p.width=Math.abs(h),n?p.height=p.width/n:p.height=m):d==="nw"&&(p.x=t.startCropX+h,p.width=Math.abs(h),n?(p.height=p.width/n,p.y=t.startCropY-p.height):(p.height=Math.abs(m),p.y=t.startCropY+m));const f=cyt(p,n,d,i.width,i.height,l,o,r,a);return n||_k.xyOrds.indexOf(u)>-1?c=f:_k.xOrds.indexOf(u)>-1?(c.x=f.x,c.width=f.width):_k.yOrds.indexOf(u)>-1&&(c.y=f.y,c.height=f.height),c.x=SB(c.x,0,i.width-c.width),c.y=SB(c.y,0,i.height-c.height),c}renderCropSelection(){const{ariaLabels:t=_k.defaultProps.ariaLabels,disabled:n,locked:r,renderSelectionAddon:a,ruleOfThirds:i,crop:l}=this.props,o=this.getCropStyle();if(l)return Dt.createElement("div",{style:o,className:"ReactCrop__crop-selection",onPointerDown:this.onCropPointerDown,"aria-label":t.cropArea,tabIndex:0,onKeyDown:this.onComponentKeyDown,role:"group"},!n&&!r&&Dt.createElement("div",{className:"ReactCrop__drag-elements",onFocus:this.onDragFocus},Dt.createElement("div",{className:"ReactCrop__drag-bar ord-n","data-ord":"n"}),Dt.createElement("div",{className:"ReactCrop__drag-bar ord-e","data-ord":"e"}),Dt.createElement("div",{className:"ReactCrop__drag-bar ord-s","data-ord":"s"}),Dt.createElement("div",{className:"ReactCrop__drag-bar ord-w","data-ord":"w"}),Dt.createElement("div",{className:"ReactCrop__drag-handle ord-nw","data-ord":"nw",tabIndex:0,"aria-label":t.nwDragHandle,onKeyDown:c=>this.onHandlerKeyDown(c,"nw"),role:"button"}),Dt.createElement("div",{className:"ReactCrop__drag-handle ord-n","data-ord":"n",tabIndex:0,"aria-label":t.nDragHandle,onKeyDown:c=>this.onHandlerKeyDown(c,"n"),role:"button"}),Dt.createElement("div",{className:"ReactCrop__drag-handle ord-ne","data-ord":"ne",tabIndex:0,"aria-label":t.neDragHandle,onKeyDown:c=>this.onHandlerKeyDown(c,"ne"),role:"button"}),Dt.createElement("div",{className:"ReactCrop__drag-handle ord-e","data-ord":"e",tabIndex:0,"aria-label":t.eDragHandle,onKeyDown:c=>this.onHandlerKeyDown(c,"e"),role:"button"}),Dt.createElement("div",{className:"ReactCrop__drag-handle ord-se","data-ord":"se",tabIndex:0,"aria-label":t.seDragHandle,onKeyDown:c=>this.onHandlerKeyDown(c,"se"),role:"button"}),Dt.createElement("div",{className:"ReactCrop__drag-handle ord-s","data-ord":"s",tabIndex:0,"aria-label":t.sDragHandle,onKeyDown:c=>this.onHandlerKeyDown(c,"s"),role:"button"}),Dt.createElement("div",{className:"ReactCrop__drag-handle ord-sw","data-ord":"sw",tabIndex:0,"aria-label":t.swDragHandle,onKeyDown:c=>this.onHandlerKeyDown(c,"sw"),role:"button"}),Dt.createElement("div",{className:"ReactCrop__drag-handle ord-w","data-ord":"w",tabIndex:0,"aria-label":t.wDragHandle,onKeyDown:c=>this.onHandlerKeyDown(c,"w"),role:"button"})),a&&Dt.createElement("div",{className:"ReactCrop__selection-addon",onPointerDown:c=>c.stopPropagation()},a(this.state)),i&&Dt.createElement(Dt.Fragment,null,Dt.createElement("div",{className:"ReactCrop__rule-of-thirds-hz"}),Dt.createElement("div",{className:"ReactCrop__rule-of-thirds-vt"})))}makePixelCrop(t){const n={...vEe,...this.props.crop||{}};return $5(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=TZs("ReactCrop",a,u&&"ReactCrop--active",l&&"ReactCrop--disabled",o&&"ReactCrop--locked",h&&"ReactCrop--new-crop",i&&t&&"ReactCrop--fixed-aspect",i&&r&&"ReactCrop--circular-crop",i&&d&&"ReactCrop--rule-of-thirds",!this.dragStarted&&i&&!i.width&&!i.height&&"ReactCrop--invisible-crop",r&&"ReactCrop--no-animate");return Dt.createElement("div",{ref:this.componentRef,className:p,style:c},Dt.createElement("div",{ref:this.mediaRef,className:"ReactCrop__child-wrapper",onPointerDown:this.onComponentPointerDown},n),i?Dt.createElement("svg",{className:"ReactCrop__crop-mask",width:"100%",height:"100%"},Dt.createElement("defs",null,Dt.createElement("mask",{id:`hole-${this.instanceId}`},Dt.createElement("rect",{width:"100%",height:"100%",fill:"white"}),r?Dt.createElement("ellipse",{cx:`${i.x+i.width/2}${i.unit}`,cy:`${i.y+i.height/2}${i.unit}`,rx:`${i.width/2}${i.unit}`,ry:`${i.height/2}${i.unit}`,fill:"black"}):Dt.createElement("rect",{x:`${i.x}${i.unit}`,y:`${i.y}${i.unit}`,width:`${i.width}${i.unit}`,height:`${i.height}${i.unit}`,fill:"black"}))),Dt.createElement("rect",{fill:"black",fillOpacity:.5,width:"100%",height:"100%",mask:`url(#hole-${this.instanceId})`})):void 0,m)}};Kp(KT,"xOrds",["e","w"]),Kp(KT,"yOrds",["n","s"]),Kp(KT,"xyOrds",["nw","ne","se","sw"]),Kp(KT,"nudgeStep",1),Kp(KT,"nudgeStepMedium",10),Kp(KT,"nudgeStepLarge",100),Kp(KT,"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 DZs=KT;function RZs(s,t,n){return PZs(MZs({unit:"%",width:90},n,s,t),s,t)}const itt=({open:s,onClose:t,imageSrc:n,onCropComplete:r,aspectRatio:a=1})=>{const i=_.useRef(null),[l,o]=_.useState(),[c,d]=_.useState(),[u,h]=_.useState(1),[m,p]=_.useState(0),f=_.useCallback(g=>{const{width:b,height:j}=g.currentTarget;o(RZs(b,j,a))},[a]),y=_.useCallback(async()=>{const g=i.current;if(!g||!c)return;const b=document.createElement("canvas"),j=b.getContext("2d");if(!j)return;const S=g.naturalWidth/g.width,C=g.naturalHeight/g.height,E=400;b.width=E,b.height=E,j.imageSmoothingQuality="high";const P=c.x*S,M=c.y*C,I=c.width*S,D=c.height*C,O=m*Math.PI/180,V=b.width/2,G=b.height/2;return j.save(),j.translate(V,G),j.rotate(O),j.scale(u,u),j.translate(-V,-G),j.drawImage(g,P,M,I,D,0,0,E,E),j.restore(),new Promise(($,H)=>{b.toBlob(Y=>{Y?$(Y):H(new Error("Canvas is empty"))},"image/jpeg",.95)})},[c,u,m]),v=async()=>{try{const g=await y();g&&(r(g),t())}catch(g){console.error("Error cropping image:",g)}};return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"max-w-lg",children:[e.jsx(Os,{children:e.jsx(Ds,{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(DZs,{crop:l,onChange:(g,b)=>o(b),onComplete:g=>d(g),aspect:a,circularCrop:!0,className:"max-h-[400px]",children:e.jsx("img",{ref:i,src:n,alt:"Crop preview",style:{transform:`scale(${u}) rotate(${m}deg)`,maxHeight:"400px",width:"auto"},onLoad:f})})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(x$,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(kx,{value:[u],min:.5,max:3,step:.1,onValueChange:([g])=>h(g),className:"flex-1"}),e.jsx(aP,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(a7,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(kx,{value:[m],min:-180,max:180,step:1,onValueChange:([g])=>p(g),className:"flex-1"}),e.jsxs("span",{className:"text-sm text-muted-foreground w-12",children:[m,"°"]})]})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:t,children:"Cancel"}),e.jsx(B,{onClick:v,children:"Save Photo"})]})]})})},dyt="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 FZs(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 OZs(){const{user:s}=hs(),{toast:t}=vi(),[n,r]=_.useState(!0),[a,i]=_.useState(!1),[l,o]=_.useState(""),[c,d]=_.useState(!1),[u,h]=_.useState(!1),[m,p]=_.useState(null),[f,y]=_.useState(!1);_.useEffect(()=>{s!=null&&s.id&&(async()=>{const{data:b}=await q.from("profiles").select("phone, phone_e164, sms_consent, sms_consent_at").eq("id",s.id).maybeSingle(),j=b;j&&(o(j.phone_e164||j.phone||""),h(!!j.sms_consent),d(!!j.sms_consent),p(j.sms_consent_at||null)),r(!1)})()},[s==null?void 0:s.id]);const v=async()=>{const b=FZs(l);if(!b){t({title:"Invalid number",description:"Enter a valid mobile number, e.g. (555) 123-4567.",variant:"destructive"});return}if(!c){t({title:"Consent required",description:"Please check the consent box to opt in to text messages.",variant:"destructive"});return}i(!0);const{error:j}=await q.from("profiles").update({phone_e164:b,sms_consent:!0,sms_consent_at:new Date().toISOString(),sms_consent_text:dyt,sms_consent_source:"profile_page",sms_opted_out_at:null}).eq("id",s.id);if(i(!1),j){t({title:"Error",description:j.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."})},g=async()=>{i(!0);const{error:b}=await q.from("profiles").update({sms_consent:!1,sms_opted_out_at:new Date().toISOString()}).eq("id",s.id);if(i(!1),b){t({title:"Error",description:b.message,variant:"destructive"});return}h(!1),d(!1),t({title:"Opted out",description:"You will no longer receive text messages from LevelUp."})};return e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(Hi,{className:"h-5 w-5"}),"Text Message (SMS) Alerts",u&&e.jsx(Oe,{variant:"secondary",children:"Opted in"})]}),e.jsx(kn,{children:"Get a text the moment a new lead comes in, plus important account notifications."})]}),e.jsx(Me,{className:"space-y-4",children:n?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Ct,{className:"h-4 w-4 animate-spin"})," Loading…"]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"rounded-lg border border-primary/30 bg-primary/5 p-3",children:e.jsx("p",{className:"text-sm font-medium",children:"SMS is completely optional. It is not required to create an account, save your profile, purchase, access, or use LevelUp. You may leave this blank or decline."})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"sms-mobile",children:"Mobile Number (optional)"}),e.jsx(xe,{id:"sms-mobile",type:"tel",value:l,onChange:b=>o(b.target.value),placeholder:"(555) 123-4567",maxLength:30,autoComplete:"tel"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Only needed if you choose to opt in. Must be a mobile number that can receive text messages."})]}),e.jsx("div",{className:"rounded-lg border bg-muted/30 p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx($a,{id:"sms-consent",checked:c,onCheckedChange:b=>d(b===!0),disabled:u,className:"mt-0.5"}),e.jsx(J,{htmlFor:"sms-consent",className:"text-sm font-normal leading-relaxed cursor-pointer",children:dyt})]})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Message types: new lead alerts, account notifications, service updates, customer support. Frequency varies. Msg & data rates may apply. Reply STOP to opt out, HELP for help. No mobile information will be shared with third parties or affiliates for marketing purposes."}),u&&m&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Consent recorded on ",new Date(m).toLocaleString("en-US",{timeZone:"America/New_York"}),"."]}),f&&!u&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"You chose not to enroll in text alerts. Nothing was saved and your account is unaffected."}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(B,{onClick:v,disabled:a||u&&!l,children:[a&&e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}),u?"Update Number":"Opt in to SMS"]}),u?e.jsx(B,{variant:"outline",onClick:g,disabled:a,children:"Opt out"}):e.jsx(B,{variant:"outline",type:"button",disabled:a,onClick:()=>{o(""),d(!1),y(!0),t({title:"SMS skipped",description:"No consent was recorded. You can keep using LevelUp normally."})},children:"Skip SMS / Continue without text alerts"})]})]})})]})}const uyt="#2a4c64",hyt="#B8965A",myt="Inter",pyt="Inter";function _U(s){if(typeof s!="string")return null;const t=s.trim();return t.length?t:null}function t_(s,t=null){for(const[n,r]of s){const a=_U(r);if(a)return{value:a,source:n}}return{value:t,source:"default"}}function zZs(s){const t=s.agent??{},n=s.brokerage??{},r=s.legacy??{},a=!!n.lock_colors,i=!!n.lock_logo,l=(E,P,M)=>a?[["brokerage",P],["agent",E],["legacy",M]]:[["agent",E],["brokerage",P],["legacy",M]],o=t_(l(t.brand_color,n.primary_color,r.brand_color),uyt),c=t_(l(t.accent_color,n.accent_color,r.accent_color),hyt),d=t_([["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=t_(u),m=t_([["brokerage",n.logo_url],["legacy",r.brokerage_logo_url]]),p=t_([["agent",t.headshot_url],["legacy",r.avatar_url]]),f=t_([["agent",t.tagline],["legacy",r.tagline||r.title]]),y=t_([["agent",t.preferred_font],["brokerage",n.heading_font]],myt),v=t_([["brokerage",n.body_font]],pyt),g=t_([["agent",t.license_number],["legacy",r.license_number]]),b=t_([["agent",t.license_state],["legacy",r.license_state],["brokerage",n.license_state]]),j=t_([["agent",t.website_url],["legacy",r.website_url]]),S=t_([["brokerage",n.legal_name],["legacy",r.brokerage_name]]),C=t_([["brokerage",n.compliance_line]]);return{agent_name:_U(r.name),brokerage_name:S.value,brand_color:o.value??uyt,secondary_color:d.value,accent_color:c.value??hyt,heading_font:y.value??myt,body_font:v.value??pyt,logo_url:h.value,logo_dark_url:_U(n.logo_dark_url),brokerage_logo_url:m.value,icon_mark_url:_U(n.icon_mark_url),headshot_url:p.value,tagline:f.value,license_number:g.value,license_state:b.value,website_url:j.value,email:_U(r.email),phone:_U(r.phone),compliance_line:C.value,show_equal_housing:!!n.show_equal_housing,show_realtor_logo:!!n.show_realtor_logo,locked:{colors:a,logo:i},sources:{brand_color:o.source,accent_color:c.source,secondary_color:d.source,logo_url:h.source,brokerage_logo_url:m.source,headshot_url:p.source,tagline:f.source,heading_font:y.source,body_font:v.source,license_number:g.source,license_state:b.source,website_url:j.source,brokerage_name:S.source,compliance_line:C.source}}}function BZs(){const{user:s}=hs();return at({queryKey:["agent-brand-profile",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("agent_brand_profiles").select("*").eq("user_id",s.id).maybeSingle();if(n)throw n;return t??null}})}function UZs(){const{user:s}=hs(),t=Bt();return mt({mutationFn:async n=>{if(!s)throw new Error("Not signed in");const{data:r,error:a}=await q.from("agent_brand_profiles").upsert({user_id:s.id,...n},{onConflict:"user_id"}).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["agent-brand-profile",s==null?void 0:s.id]}),t.invalidateQueries({queryKey:["brand-kit",s==null?void 0:s.id]})}})}function qZs(s){return at({queryKey:["brokerage-brand-profile",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("brokerage_brand_profiles").select("*").eq("brokerage_id",s).maybeSingle();if(n)throw n;return t??null}})}function $Zs(s){const{user:t}=hs(),n=Bt();return mt({mutationFn:async r=>{if(!s)throw new Error("No brokerage selected");const{data:a,error:i}=await q.from("brokerage_brand_profiles").upsert({brokerage_id:s,updated_by:(t==null?void 0:t.id)??null,...r},{onConflict:"brokerage_id"}).select().single();if(i)throw i;return a},onSuccess:()=>{n.invalidateQueries({queryKey:["brokerage-brand-profile",s]}),n.invalidateQueries({queryKey:["brand-kit"]})}})}function XUt(){const{user:s}=hs();return at({queryKey:["brand-kit",s==null?void 0:s.id],enabled:!!s,staleTime:6e4,queryFn:async()=>{var m;const t=s.id,[n,r,a,i]=await Promise.all([q.from("profiles").select("name, email, phone, avatar_url, website_url, title, brokerage_name, brokerage_id").eq("id",t).maybeSingle(),q.from("agent_brand_profiles").select("*").eq("user_id",t).maybeSingle(),q.from("agent_cards").select("brokerage_display_name, brokerage_logo_url, team_logo_url, display_email, title, positioning_statement").eq("user_id",t).maybeSingle(),q.from("lead_sites").select("brand_color, accent_color, agent_license_number, license_state, brokerage_legal_name, team_logo_url, is_active, created_at").eq("agent_id",t).order("created_at",{ascending:!0}).limit(5)]),l=n.data??{},o=a.data??{},c=i.data??[],d=c.find(p=>p.is_active)??c[0]??{};let u=null,h=null;if(l.brokerage_id){const[p,f]=await Promise.all([q.from("brokerage_brand_profiles").select("*").eq("brokerage_id",l.brokerage_id).maybeSingle(),q.from("brokerages").select("name").eq("id",l.brokerage_id).maybeSingle()]);u=p.data??null,h=((m=f.data)==null?void 0:m.name)??null}return zZs({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 QUt(s,t,n){var l;const r=((l=t.name.split(".").pop())==null?void 0:l.toLowerCase())||"png",a=`${s}/brand-${n}-${Date.now()}.${r}`,{error:i}=await q.storage.from("card-logos").upload(a,t,{upsert:!0,cacheControl:"3600"});if(i)throw i;return q.storage.from("card-logos").getPublicUrl(a).data.publicUrl}const VZs=["Inter","Playfair Display","Montserrat","Poppins","Lora","Work Sans"];function HZs(){const{user:s}=hs(),{toast:t}=vi(),{data:n,isLoading:r}=BZs(),{data:a}=XUt(),i=UZs(),l=_.useRef(null),[o,c]=_.useState(!1),[d,u]=_.useState({brand_color:"",accent_color:"",logo_url:"",tagline:"",preferred_font:"",license_number:"",license_state:"",website_url:""});_.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=(v,g)=>u(b=>({...b,[v]:g})),f=async v=>{if(s){c(!0);try{const g=await QUt(s.id,v,"logo");p("logo_url",g),t({title:"Logo uploaded"})}catch(g){t({title:"Upload failed",description:g.message,variant:"destructive"})}finally{c(!1)}}},y=async()=>{try{await i.mutateAsync({brand_color:d.brand_color||null,accent_color:d.accent_color||null,logo_url:d.logo_url||null,tagline:d.tagline||null,preferred_font:d.preferred_font||null,license_number:d.license_number||null,license_state:d.license_state||null,website_url:d.website_url||null}),t({title:"Brand kit saved"})}catch(v){t({title:"Could not save",description:v.message,variant:"destructive"})}};return e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(Xc,{className:"h-5 w-5"}),"Brand Kit"]}),e.jsx(kn,{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(Me,{className:"space-y-6",children:r?e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-sm",children:[e.jsx(Ct,{className:"h-4 w-4 animate-spin"})," Loading…"]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(J,{className:"flex items-center gap-2",children:["Brand color",h&&e.jsxs(Oe,{variant:"secondary",className:"gap-1",children:[e.jsx(ec,{className:"h-3 w-3"})," Set by brokerage"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{type:"color",className:"h-10 w-14 p-1",value:d.brand_color||(a==null?void 0:a.brand_color)||"#2a4c64",disabled:h,onChange:v=>p("brand_color",v.target.value)}),e.jsx(xe,{value:d.brand_color,placeholder:(a==null?void 0:a.brand_color)||"#2a4c64",disabled:h,onChange:v=>p("brand_color",v.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Accent color"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{type:"color",className:"h-10 w-14 p-1",value:d.accent_color||(a==null?void 0:a.accent_color)||"#B8965A",disabled:h,onChange:v=>p("accent_color",v.target.value)}),e.jsx(xe,{value:d.accent_color,placeholder:(a==null?void 0:a.accent_color)||"#B8965A",disabled:h,onChange:v=>p("accent_color",v.target.value)})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(J,{className:"flex items-center gap-2",children:["Personal / team logo",m&&e.jsxs(Oe,{variant:"secondary",className:"gap-1",children:[e.jsx(ec,{className:"h-3 w-3"})," Brokerage logo required"]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[d.logo_url&&e.jsx("img",{src:d.logo_url,alt:"Your logo",className:"h-12 w-auto rounded border bg-background p-1"}),e.jsx("input",{ref:l,type:"file",accept:"image/*",className:"hidden",onChange:v=>{var g;return((g=v.target.files)==null?void 0:g[0])&&f(v.target.files[0])}}),e.jsxs(B,{type:"button",variant:"outline",disabled:o||m,onClick:()=>{var v;return(v=l.current)==null?void 0:v.click()},children:[o?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Oa,{className:"h-4 w-4"}),e.jsx("span",{className:"ml-2",children:"Upload logo"})]}),d.logo_url&&e.jsx(B,{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(J,{htmlFor:"brand-tagline",children:"Tagline"}),e.jsx(xe,{id:"brand-tagline",value:d.tagline,placeholder:(a==null?void 0:a.tagline)||"Your positioning statement",onChange:v=>p("tagline",v.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"brand-font",children:"Preferred font"}),e.jsx(xe,{id:"brand-font",list:"brand-font-options",value:d.preferred_font,placeholder:(a==null?void 0:a.heading_font)||"Inter",onChange:v=>p("preferred_font",v.target.value)}),e.jsx("datalist",{id:"brand-font-options",children:VZs.map(v=>e.jsx("option",{value:v},v))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"brand-license",children:"License number"}),e.jsx(xe,{id:"brand-license",value:d.license_number,placeholder:(a==null?void 0:a.license_number)||"DRE #01234567",onChange:v=>p("license_number",v.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"brand-license-state",children:"License state"}),e.jsx(xe,{id:"brand-license-state",value:d.license_state,placeholder:(a==null?void 0:a.license_state)||"CA",onChange:v=>p("license_state",v.target.value)})]}),e.jsxs("div",{className:"space-y-2 sm:col-span-2",children:[e.jsx(J,{htmlFor:"brand-website",children:"Website"}),e.jsx(xe,{id:"brand-website",value:d.website_url,placeholder:(a==null?void 0:a.website_url)||"https://yoursite.com",onChange:v=>p("website_url",v.target.value)})]})]}),(a==null?void 0:a.compliance_line)&&e.jsxs("div",{className:"rounded-md border bg-muted/40 p-3 text-sm text-muted-foreground",children:[e.jsx("span",{className:"font-medium text-foreground",children:"Required disclaimer from your brokerage: "}),a.compliance_line]}),e.jsxs(B,{onClick:y,disabled:i.isPending,children:[i.isPending?e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Ho,{className:"mr-2 h-4 w-4"}),"Save brand kit"]})]})})]})}const F7e="id, name, address, notes, created_at, locked_style, share_token, share_enabled, share_headline, share_message, share_views";function Kbr(s,t){const[n,r]=_.useState(null);return _.useEffect(()=>{let a=!1;if(!t){r(null);return}if(t.startsWith("http")||t.startsWith("data:")){r(t);return}return q.storage.from(s).createSignedUrl(t,60*60).then(({data:i})=>{a||r((i==null?void 0:i.signedUrl)??null)}),()=>{a=!0}},[s,t]),n}function GZs(){var o,c,d;const{user:s}=hs(),t=Bt(),n=at({queryKey:["staging-credits",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),staleTime:3e4,queryFn:async()=>{const{data:u,error:h}=await q.functions.invoke("staging-credits-sync");if(h)throw h;return{credits:(u==null?void 0:u.credits)??null,unlimited:!!(u!=null&&u.unlimited),unlimitedReason:(u==null?void 0:u.unlimitedReason)??null}}}),r=((o=n.data)==null?void 0:o.credits)??null,a=!!((c=n.data)!=null&&c.unlimited),i=r?Math.max(r.monthly_included-r.monthly_used,0):0,l=i+((r==null?void 0:r.purchased_balance)??0);return{credits:r,unlimited:a,unlimitedReason:((d=n.data)==null?void 0:d.unlimitedReason)??null,remainingMonthly:i,purchased:(r==null?void 0:r.purchased_balance)??0,total:l,legacyPlan:(r==null?void 0:r.legacy_plan)??null,isLoading:n.isLoading,refresh:()=>t.invalidateQueries({queryKey:["staging-credits"]})}}function Ybr(){return at({queryKey:["staging-credit-packs"],staleTime:5*6e4,queryFn:async()=>{const{data:s,error:t}=await q.from("staging_credit_packs").select("id, key, name, credits, price_cents, sort_order").eq("is_active",!0).order("sort_order");if(t)throw t;return s??[]}})}function Zbr(){const{user:s}=hs(),t=Bt(),n=at({queryKey:["staging-projects",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),queryFn:async()=>{const{data:o,error:c}=await q.from("staging_projects").select(F7e).eq("user_id",s.id).order("created_at",{ascending:!1});if(c)throw c;return o??[]}}),r=mt({mutationFn:async o=>{const{data:c,error:d}=await q.from("staging_projects").insert({user_id:s.id,name:o.name,address:o.address??null}).select(F7e).single();if(d)throw d;return c},onSuccess:()=>t.invalidateQueries({queryKey:["staging-projects"]})}),a=mt({mutationFn:async o=>{const{error:c}=await q.from("staging_projects").update({name:o.name,address:o.address??null}).eq("id",o.id);if(c)throw c},onSuccess:()=>t.invalidateQueries({queryKey:["staging-projects"]})}),i=mt({mutationFn:async o=>{await q.from("staging_images").update({project_id:null}).eq("project_id",o);const{error:c}=await q.from("staging_projects").delete().eq("id",o);if(c)throw c},onSuccess:()=>{t.invalidateQueries({queryKey:["staging-projects"]}),t.invalidateQueries({queryKey:["staging-images"]})}}),l=mt({mutationFn:async o=>{const{id:c,...d}=o,{data:u,error:h}=await q.from("staging_projects").update(d).eq("id",c).select(F7e).single();if(h)throw h;return u},onSuccess:()=>t.invalidateQueries({queryKey:["staging-projects"]})});return{projects:n.data??[],isLoading:n.isLoading,createProject:r,renameProject:a,deleteProject:i,updateProject:l}}function Xbr(){return mt({mutationFn:async s=>{if(s.length===0)return[];const{data:t,error:n}=await q.functions.invoke("staging-analyze",{body:{images:s}});if(n)throw n;return(t==null?void 0:t.results)??[]}})}function Qbr(s){const{user:t}=hs(),n=Bt(),r=at({queryKey:["staging-images",t==null?void 0:t.id,s??"all"],enabled:!!(t!=null&&t.id),queryFn:async()=>{let o=q.from("staging_images").select("*").eq("user_id",t.id).order("created_at",{ascending:!1}).limit(300);s&&(o=o.eq("project_id",s));const{data:c,error:d}=await o;if(d)throw d;return c??[]}}),a=mt({mutationFn:async o=>{const{data:c,error:d}=await q.from("staging_images").delete().eq("id",o).select("id");if(d)throw d;if(!(c!=null&&c.length))throw new Error("This photo could not be deleted.")},onSuccess:()=>n.invalidateQueries({queryKey:["staging-images"]})}),i=mt({mutationFn:async o=>{const{data:c,error:d}=await q.from("staging_images").update({is_favorite:!o.is_favorite}).eq("id",o.id).select("id");if(d)throw d;if(!(c!=null&&c.length))throw new Error("This photo could not be updated.")},onSuccess:()=>n.invalidateQueries({queryKey:["staging-images"]})}),l=mt({mutationFn:async({id:o,projectId:c})=>{const{data:d,error:u}=await q.from("staging_images").update({project_id:c}).eq("id",o).select("id");if(u)throw u;if(!(d!=null&&d.length))throw new Error("This photo could not be moved.")},onSuccess:()=>n.invalidateQueries({queryKey:["staging-images"]})});return{images:r.data??[],isLoading:r.isLoading,remove:a,toggleFavorite:i,assignProject:l}}function Jbr(){const s=Bt();return mt({mutationFn:async t=>{const{data:n,error:r}=await q.functions.invoke("staging-generate",{body:t});if(r){let a=r.message;try{const i=r.context;if(i){const l=await i.json();a=(l==null?void 0:l.message)||(l==null?void 0:l.error)||a}}catch{}throw new Error(a)}if(n!=null&&n.error)throw new Error(n.message||n.error);return{image:n.image,generatedUrl:n.generatedUrl}},onSuccess:()=>{s.invalidateQueries({queryKey:["staging-images"]}),s.invalidateQueries({queryKey:["staging-credits"]})}})}async function e_r(s){return new Promise((t,n)=>{const r=new FileReader;r.onload=()=>t(r.result),r.onerror=n,r.readAsDataURL(s)})}function WZs(){try{return window.open("","_blank")}catch{return null}}function KZs(s,t){var n;if(s&&!s.closed)try{s.location.href=t,(n=s.focus)==null||n.call(s);return}catch{}window.location.assign(t)}function YZs(s){try{s&&!s.closed&&s.close()}catch{}}async function ZZs(s,t){if(s instanceof Mre)try{const n=await s.context.text();try{const r=JSON.parse(n),a=(r==null?void 0:r.error)??(r==null?void 0:r.message);if(typeof a=="string"&&a.trim())return a}catch{if(n.trim())return n.trim().slice(0,300)}}catch{}return s instanceof Error&&s.message?s.message:t}function XZs(){var i;const s=GZs(),[t,n]=_.useState(!1);if(s.isLoading)return null;const r=s.unlimited&&s.unlimitedReason==="plan",a=async()=>{if(t)return;const l=WZs();n(!0);try{const{data:o,error:c}=await q.functions.invoke("staging-portal");if(c)throw c;if(!(o!=null&&o.url))throw new Error("No billing portal available");KZs(l,o.url)}catch(o){YZs(l);const c=await ZZs(o,"We could not open your billing portal. Contact support and we will sort it out.");console.error("[staging-portal]",c,o),se.error(c)}finally{n(!1)}};return e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-5 w-5"}),"Staging Studio Billing"]}),e.jsx(kn,{children:"Manage the plan and credits that power your AI photo staging"})]}),e.jsxs(Me,{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(Oe,{variant:r?"default":"secondary",children:s.legacyPlan?`${s.legacyPlan} plan`:"Included with LevelUp"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[r?"Unlimited staged photos each month":`${s.remainingMonthly} of ${((i=s.credits)==null?void 0:i.monthly_included)??0} photos left this month`,!r&&s.purchased>0&&` · ${s.purchased} pack credits`]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:a,disabled:t,children:[t?e.jsx(Ct,{className:"mr-1.5 h-3.5 w-3.5 animate-spin"}):e.jsx(_y,{className:"mr-1.5 h-3.5 w-3.5"}),"Manage billing"]}),e.jsx(B,{variant:"ghost",size:"sm",asChild:!0,children:e.jsxs(ir,{to:"/apps/staging-studio/credits",children:["Credits & history ",e.jsx(wr,{className:"ml-1.5 h-3.5 w-3.5"})]})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:s.legacyPlan?"Cancel, update your card or change plans in the billing portal. Changes apply to your Staging Studio credits automatically.":"If you ever bought a Staging Studio plan or credit packs, open the billing portal to update your card, change plans or cancel."})]})]})}const fyt=["image/png","image/jpeg","image/jpg","image/svg+xml","image/webp"],QZs=5*1024*1024;function JZs({userId:s,value:t,onChange:n,persistToProfile:r=!0,label:a="Brokerage logo",description:i="PNG, JPG, SVG or WebP — up to 5MB. Used on your website and marketing.",className:l}){const o=_.useRef(null),[c,d]=_.useState(!1),[u,h]=_.useState(!1),m=async f=>{if(!fyt.includes(f.type)){se.error("Please upload a PNG, JPG, SVG or WebP file");return}if(f.size>QZs){se.error("Please choose a logo under 5MB");return}d(!0);try{const y=(f.name.split(".").pop()||"png").toLowerCase(),v=`${s}/brokerage-logo-${Date.now()}.${y}`,{error:g}=await q.storage.from("card-logos").upload(v,f,{cacheControl:"3600",upsert:!0,contentType:f.type});if(g)throw g;const{data:b}=q.storage.from("card-logos").getPublicUrl(v),j=b.publicUrl;r&&await q.from("profiles").update({brokerage_logo_url:j}).eq("id",s),n(j),se.success("Brokerage logo uploaded")}catch(y){se.error((y==null?void 0:y.message)||"Upload failed")}finally{d(!1)}},p=async()=>{r&&await q.from("profiles").update({brokerage_logo_url:null}).eq("id",s),n(null)};return e.jsxs("div",{className:At("space-y-2",l),children:[e.jsx(J,{children:a}),e.jsxs("div",{onDragOver:f=>{f.preventDefault(),h(!0)},onDragLeave:()=>h(!1),onDrop:f=>{var v;f.preventDefault(),h(!1);const y=(v=f.dataTransfer.files)==null?void 0:v[0];y&&m(y)},onClick:()=>{var f;return!c&&((f=o.current)==null?void 0:f.click())},className:At("flex cursor-pointer items-center gap-4 rounded-xl border border-dashed p-4 transition-colors",u?"border-primary bg-primary/5":"border-border hover:bg-muted/50"),children:[e.jsx("div",{className:"flex h-16 w-24 shrink-0 items-center justify-center overflow-hidden rounded-lg bg-muted",children:t?e.jsx("img",{src:t,alt:"Brokerage logo",className:"h-full w-full object-contain p-1"}):e.jsx(ai,{className:"h-6 w-6 text-muted-foreground"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm font-medium",children:c?"Uploading…":t?"Logo added":"Drag & drop your brokerage logo"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:i})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[e.jsxs(B,{type:"button",variant:"outline",size:"sm",disabled:c,onClick:f=>{var y;f.stopPropagation(),(y=o.current)==null||y.click()},children:[c?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Oa,{className:"h-4 w-4"}),e.jsx("span",{className:"ml-2",children:t?"Replace":"Upload"})]}),t&&!c&&e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:f=>{f.stopPropagation(),p()},children:e.jsx(Sn,{className:"h-4 w-4 text-muted-foreground"})})]})]}),e.jsx("input",{ref:o,type:"file",accept:fyt.join(","),className:"hidden",onChange:f=>{var v;const y=(v=f.target.files)==null?void 0:v[0];y&&m(y),f.target.value=""}})]})}const eXs=()=>{const{user:s}=hs(),{toast:t}=vi(),[n,r]=_.useState(!1),[a,i]=_.useState(!1),[l,o]=_.useState(null);_.useEffect(()=>{s&&c()},[s]);const c=async()=>{r(!0);try{const{data:h}=await q.from("profiles").select("subscription_status, subscription_product_id, subscription_end_date, is_grandfathered").eq("id",s==null?void 0:s.id).single();h&&o({status:h.subscription_status||"none",productId:h.subscription_product_id,endDate:h.subscription_end_date,isGrandfathered:h.is_grandfathered||!1})}catch(h){console.error("Error loading subscription:",h)}finally{r(!1)}},d=async()=>{i(!0);try{const{data:{session:h}}=await q.auth.getSession();if(!h)throw new Error("Not authenticated");const{data:m,error:p}=await q.functions.invoke("customer-portal",{headers:{Authorization:`Bearer ${h.access_token}`}});if(p)throw p;m!=null&&m.url&&window.open(m.url,"_blank")}catch(h){console.error("Error opening customer portal:",h),t({title:"Error",description:h.message||"Failed to open billing portal",variant:"destructive"})}finally{i(!1)}},u=()=>{if(l!=null&&l.isGrandfathered)return e.jsx(Oe,{className:"bg-amber-500",children:"Grandfathered"});switch(l==null?void 0:l.status){case"active":return e.jsx(Oe,{className:"bg-green-500",children:"Active"});case"trialing":return e.jsx(Oe,{className:"bg-blue-500",children:"Trial"});case"past_due":return e.jsx(Oe,{variant:"destructive",children:"Past Due"});case"canceled":return e.jsx(Oe,{variant:"secondary",children:"Canceled"});default:return e.jsx(Oe,{variant:"outline",children:"No Subscription"})}};return n?e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(_y,{className:"h-5 w-5"}),"Subscription"]})}),e.jsx(Me,{children:e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})})})]}):e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(_y,{className:"h-5 w-5"}),"Subscription"]}),e.jsx(kn,{children:"Manage your subscription and billing"})]}),e.jsxs(Me,{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(B,{onClick:d,variant:"outline",disabled:a,children:[a?e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(wr,{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."})]})]})},tXs=()=>{const{user:s}=hs(),t=Fn(),{toast:n}=vi(),[r]=Yl(),a=r.get("setup")==="true",i=r.get("reset")==="true",l=i&&r.get("activation")==="1",{isSupported:o,isSubscribed:c,isLoading:d,subscribe:u,unsubscribe:h}=$Rt(),[m,p]=_.useState(!1),[f,y]=_.useState(""),[v,g]=_.useState(null),[b,j]=_.useState(!1),[S,C]=_.useState(!1),[E,P]=_.useState(""),[M,I]=_.useState({name:"",email:"",phone:"",title:"",bio:"",areas_served:"",years_experience:"",brokerage_name:"",instagram_url:"",facebook_url:"",linkedin_url:"",google_business_url:"",zillow_profile_url:"",realtor_profile_url:"",specialties:"",email_signature:"",use_email_signature:!1}),[D,O]=_.useState(!1),[V,G]=_.useState(!1),[$,H]=_.useState(!1),[Y,Z]=_.useState(!1),[ne,ce]=_.useState(!1),[ie,te]=_.useState({newPassword:"",confirmPassword:""});_.useEffect(()=>{s&&ae()},[s]),_.useEffect(()=>{i&&s&&setTimeout(()=>{var pe;(pe=document.getElementById("change-password-section"))==null||pe.scrollIntoView({behavior:"smooth",block:"center"})},500)},[i,s]);const ae=async()=>{var pe,Ce,Ae,Pe;if(!(s!=null&&s.id)){console.log("No user ID available yet");return}try{console.log("Loading profile for user:",s.id);const{data:ze,error:ke}=await q.from("profiles").select("name, email, phone, digest_opt_out, event_invite_opt_out, title, bio, areas_served, years_experience, brokerage_id, brokerage_name, brokerage_logo_url, instagram_url, facebook_url, linkedin_url, google_business_url, zillow_profile_url, realtor_profile_url, specialties, email_signature, use_email_signature, brokerages(name)").eq("id",s.id).maybeSingle();if(ke)throw console.error("Profile query error:",ke),ke;if(ze){console.log("Profile loaded successfully:",ze);const Se=((pe=ze.brokerages)==null?void 0:pe.name)||"";O(!!ze.brokerage_id),I({name:ze.name||"",email:ze.email||"",phone:ze.phone||"",title:ze.title||"",bio:ze.bio||"",areas_served:ze.areas_served||"",years_experience:((Ce=ze.years_experience)==null?void 0:Ce.toString())||"",brokerage_name:ze.brokerage_id?Se:ze.brokerage_name||"",instagram_url:ze.instagram_url||"",facebook_url:ze.facebook_url||"",linkedin_url:ze.linkedin_url||"",google_business_url:ze.google_business_url||"",zillow_profile_url:ze.zillow_profile_url||"",realtor_profile_url:ze.realtor_profile_url||"",specialties:ze.specialties||"",email_signature:ze.email_signature||"",use_email_signature:ze.use_email_signature||!1}),G(ze.digest_opt_out||!1),Z(ze.event_invite_opt_out||!1),g(ze.brokerage_logo_url||null)}else console.warn("No profile found for user"),I({name:((Ae=s.user_metadata)==null?void 0:Ae.name)||((Pe=s.email)==null?void 0:Pe.split("@")[0])||"",email:s.email||"",phone:"",title:"",bio:"",areas_served:"",years_experience:"",brokerage_name:"",instagram_url:"",facebook_url:"",linkedin_url:"",google_business_url:"",zillow_profile_url:"",realtor_profile_url:"",specialties:"",email_signature:"",use_email_signature:!1});const{data:Ze}=await q.storage.from("avatars").list(`${s.id}`);if(Ze&&Ze.length>0){const{data:Se}=q.storage.from("avatars").getPublicUrl(`${s.id}/${Ze[0].name}`);y(Se.publicUrl)}}catch(ze){console.error("Error loading profile:",ze),n({title:"Error",description:ze.message||"Failed to load profile",variant:"destructive"})}},le=pe=>{var Pe;const Ce=(Pe=pe.target.files)==null?void 0:Pe[0];if(!Ce)return;const Ae=new FileReader;Ae.onloadend=()=>{P(Ae.result),C(!0)},Ae.readAsDataURL(Ce),pe.target.value=""},be=async pe=>{if(s){j(!0);try{const{data:Ce}=await q.storage.from("avatars").list(`${s.id}`),Ae=(Ce??[]).filter(Fe=>/^avatar[.-]/i.test(Fe.name));Ae.length>0&&await q.storage.from("avatars").remove(Ae.map(Fe=>`${s.id}/${Fe.name}`));const ze=`${s.id}/avatar.jpg`,{error:ke}=await q.storage.from("avatars").upload(ze,pe,{upsert:!0,contentType:"image/jpeg"});if(ke)throw ke;const{data:Ze}=q.storage.from("avatars").getPublicUrl(ze),Se=Ze.publicUrl;y(`${Se}?t=${Date.now()}`),await q.from("profiles").update({avatar_url:Se}).eq("id",s.id),n({title:"Success",description:"Profile photo updated successfully"})}catch(Ce){console.error("Error uploading avatar:",Ce),n({title:"Error",description:Ce.message||"Failed to upload photo",variant:"destructive"})}finally{j(!1)}}},me=async()=>{if(!M.name.trim()||!M.email.trim()){n({title:"Error",description:"Name and email are required",variant:"destructive"});return}p(!0);try{const pe=M.email.trim().toLowerCase(),Ce=((s==null?void 0:s.email)||"").toLowerCase(),Ae=!!pe&&pe!==Ce;if(Ae){const{data:ze,error:ke}=await q.functions.invoke("update-own-email",{body:{newEmail:pe}}),Ze=ke||(ze==null?void 0:ze.error);if(Ze)throw new Error(typeof Ze=="string"?Ze:"Could not update your login email. Please try a different address.")}const{error:Pe}=await q.from("profiles").update({name:M.name.trim(),email:pe,phone:M.phone.trim()||null,title:M.title.trim()||null,bio:M.bio.trim()||null,areas_served:M.areas_served.trim()||null,years_experience:M.years_experience?parseInt(M.years_experience):null,...D?{}:{brokerage_name:M.brokerage_name.trim()||null},instagram_url:M.instagram_url.trim()||null,facebook_url:M.facebook_url.trim()||null,linkedin_url:M.linkedin_url.trim()||null,google_business_url:M.google_business_url.trim()||null,zillow_profile_url:M.zillow_profile_url.trim()||null,realtor_profile_url:M.realtor_profile_url.trim()||null,specialties:M.specialties.trim()||null,email_signature:M.email_signature||"",use_email_signature:M.use_email_signature}).eq("id",s==null?void 0:s.id);if(Pe)throw Pe;n({title:"Success",description:Ae?"Profile updated. Your login email is now "+pe:"Profile updated successfully"})}catch(pe){console.error("Error updating profile:",pe),n({title:"Error",description:pe.message||"Failed to update profile",variant:"destructive"})}finally{p(!1)}},he=async()=>{if(!ie.newPassword){n({title:"Error",description:"Please enter a new password",variant:"destructive"});return}if(ie.newPassword.length<6){n({title:"Error",description:"Password must be at least 6 characters",variant:"destructive"});return}if(ie.newPassword!==ie.confirmPassword){n({title:"Error",description:"Passwords do not match",variant:"destructive"});return}p(!0);try{const{error:pe}=await q.auth.updateUser({password:ie.newPassword});if(pe)throw pe;n({title:"Success",description:"Password updated successfully"}),te({newPassword:"",confirmPassword:""}),a&&setTimeout(()=>t("/dashboard"),1e3)}catch(pe){console.error("Error updating password:",pe),n({title:"Error",description:pe.message||"Failed to update password",variant:"destructive"})}finally{p(!1)}};return e.jsx(zs,{title:a?"Complete Your Profile":l?"Welcome to LevelUp":i?"Reset Your Password":"Profile Settings",description:a?"Welcome! Please complete your profile setup":l?"Choose a password below and your account is active":i?"Please set a new password for your account":"Manage your account information and password",children:e.jsxs("div",{className:"mx-auto max-w-4xl",children:[!a&&!i&&e.jsx("div",{className:"mb-6",children:e.jsxs(B,{variant:"outline",onClick:()=>{var pe;(pe=document.getElementById("change-password-section"))==null||pe.scrollIntoView({behavior:"smooth",block:"center"})},className:"gap-2",children:[e.jsx(VA,{className:"h-4 w-4"}),"Change Password"]})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsx(St,{children:"Profile Photo"}),e.jsx(kn,{children:"Upload a professional photo for your profile"})]}),e.jsxs(Me,{className:"flex items-center gap-6",children:[e.jsxs(ja,{className:"h-24 w-24",children:[e.jsx(pi,{src:f}),e.jsx(Na,{className:"text-2xl",children:M.name.split(" ").map(pe=>pe[0]).join("").toUpperCase()||"U"})]}),e.jsxs("div",{className:"flex-1",children:[e.jsx("input",{type:"file",id:"avatar-upload",accept:"image/*",className:"hidden",onChange:le,disabled:b}),e.jsxs(B,{variant:"outline",onClick:()=>{var pe;return(pe=document.getElementById("avatar-upload"))==null?void 0:pe.click()},disabled:b,children:[e.jsx(Oa,{className:"mr-2 h-4 w-4"}),b?"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(ve,{children:[e.jsxs(bt,{children:[e.jsx(St,{children:"Personal Information"}),e.jsx(kn,{children:"Update your profile details"})]}),e.jsxs(Me,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"name",children:"Name"}),e.jsx(xe,{id:"name",value:M.name,onChange:pe=>I({...M,name:pe.target.value}),maxLength:100})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"email",children:"Email"}),e.jsx(xe,{id:"email",type:"email",value:M.email,onChange:pe=>I({...M,email:pe.target.value}),maxLength:255}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Changing this also updates the email you use to sign in."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"phone",children:"Phone Number"}),e.jsx(xe,{id:"phone",type:"tel",value:M.phone,onChange:pe=>I({...M,phone:pe.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(J,{htmlFor:"title",children:"Job Title"}),e.jsx(xe,{id:"title",value:M.title,onChange:pe=>I({...M,title:pe.target.value}),placeholder:"e.g., Broker Associate, Team Lead",maxLength:100})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"bio",children:"Bio"}),e.jsx(Ms,{id:"bio",value:M.bio,onChange:pe=>I({...M,bio:pe.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(J,{htmlFor:"areas_served",children:"Areas Served"}),e.jsx(xe,{id:"areas_served",value:M.areas_served,onChange:pe=>I({...M,areas_served:pe.target.value}),placeholder:"e.g., Downtown, Suburbs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"years_experience",children:"Years Experience"}),e.jsx(xe,{id:"years_experience",type:"number",min:"0",value:M.years_experience,onChange:pe=>I({...M,years_experience:pe.target.value}),placeholder:"e.g., 5"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(J,{htmlFor:"brokerage_name",children:["Brokerage ",D&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(managed)"})]}),e.jsx(xe,{id:"brokerage_name",value:M.brokerage_name,onChange:pe=>I({...M,brokerage_name:pe.target.value}),placeholder:"e.g., Keller Williams Realty",disabled:D,maxLength:150}),e.jsx("p",{className:"text-xs text-muted-foreground",children:D?"Your brokerage is managed by your office and can't be changed here.":"Used as your brokerage name across ReelFlow, branding, and email signatures."})]}),s&&e.jsx(JZs,{userId:s.id,value:v,onChange:g,description:"PNG, JPG, SVG or WebP up to 5MB. Used on your agent website, marketing and email signatures."}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Social Links"}),e.jsxs("div",{className:"grid grid-cols-1 gap-3",children:[e.jsx(xe,{value:M.linkedin_url,onChange:pe=>I({...M,linkedin_url:pe.target.value}),placeholder:"LinkedIn URL"}),e.jsx(xe,{value:M.instagram_url,onChange:pe=>I({...M,instagram_url:pe.target.value}),placeholder:"Instagram URL"}),e.jsx(xe,{value:M.facebook_url,onChange:pe=>I({...M,facebook_url:pe.target.value}),placeholder:"Facebook URL"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"AI Search & Verified Profiles"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Adding these helps ChatGPT, Perplexity, Google and other AI assistants confirm who you are and recommend you for local searches."}),e.jsxs("div",{className:"grid grid-cols-1 gap-3",children:[e.jsx(xe,{value:M.google_business_url,onChange:pe=>I({...M,google_business_url:pe.target.value}),placeholder:"Google Business Profile URL"}),e.jsx(xe,{value:M.zillow_profile_url,onChange:pe=>I({...M,zillow_profile_url:pe.target.value}),placeholder:"Zillow agent profile URL"}),e.jsx(xe,{value:M.realtor_profile_url,onChange:pe=>I({...M,realtor_profile_url:pe.target.value}),placeholder:"Realtor.com profile URL"}),e.jsx(xe,{value:M.specialties,onChange:pe=>I({...M,specialties:pe.target.value}),placeholder:"Specialties (e.g. Waterfront homes, Acreage & farms, First-time buyers)"})]})]}),e.jsxs(B,{onClick:me,disabled:m,children:[e.jsx(Ho,{className:"mr-2 h-4 w-4"}),"Save Changes"]})]})]}),e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(Qm,{className:"h-5 w-5"}),"Email Signature"]}),e.jsx(kn,{children:"Add a signature that will be appended to emails sent via Gmail"})]}),e.jsxs(Me,{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:M.use_email_signature?"Your signature will be added to every email sent via Gmail":"Signature is currently disabled"})]}),e.jsx(fn,{checked:M.use_email_signature,onCheckedChange:pe=>I({...M,use_email_signature:pe})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Signature"}),e.jsx(BN,{content:M.email_signature,onChange:pe=>I({...M,email_signature:pe}),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(B,{onClick:me,disabled:m,children:[e.jsx(Ho,{className:"mr-2 h-4 w-4"}),"Save Signature"]})]})]}),e.jsx(HZs,{}),e.jsxs(ve,{id:"change-password-section",children:[e.jsxs(bt,{children:[e.jsx(St,{children:a||l?"Set Your Password":"Change Password"}),e.jsx(kn,{children:a||l?"Create a secure password for your account":"Update your password to keep your account secure"})]}),e.jsxs(Me,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"newPassword",children:"New Password"}),e.jsx(xe,{id:"newPassword",type:"password",value:ie.newPassword,onChange:pe=>te({...ie,newPassword:pe.target.value}),placeholder:"Min 6 characters"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"confirmPassword",children:"Confirm Password"}),e.jsx(xe,{id:"confirmPassword",type:"password",value:ie.confirmPassword,onChange:pe=>te({...ie,confirmPassword:pe.target.value}),placeholder:"Re-enter your new password"})]}),e.jsxs(B,{onClick:he,disabled:m,children:[e.jsx(Ho,{className:"mr-2 h-4 w-4"}),a?"Complete Setup":"Update Password"]}),a&&e.jsx(B,{variant:"outline",onClick:()=>t("/dashboard"),className:"ml-2",children:"Skip for Now"})]})]}),e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsxs(St,{className:"flex items-center gap-2",children:[c?e.jsx(Rg,{className:"h-5 w-5"}):e.jsx(cS,{className:"h-5 w-5"}),"Push Notifications"]}),e.jsx(kn,{children:"Receive browser notifications when new content is added"})]}),e.jsx(Me,{children:o?e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:c?"Notifications enabled":"Notifications disabled"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:c?"You'll receive notifications about new templates, videos, and events":"Enable to get notified about new content"})]}),e.jsx(fn,{checked:c,onCheckedChange:pe=>{pe?u():h()},disabled:d})]}):e.jsxs("div",{className:"text-sm text-muted-foreground space-y-2",children:[e.jsx("p",{children:"Push notifications are not available in this browser."}),e.jsxs("p",{className:"text-xs space-y-1",children:[e.jsx("strong",{children:"Desktop:"})," Use Chrome, Firefox, or Edge.",e.jsx("br",{}),e.jsx("strong",{children:"Android:"})," Use Chrome or Firefox.",e.jsx("br",{}),e.jsx("strong",{children:"iPhone/iPad:"})," Push notifications on iOS ",e.jsx("em",{children:"only"})," work when this site is installed as an app from ",e.jsx("strong",{children:"Safari"}),". Open this site in Safari → tap the ",e.jsx("strong",{children:"Share"})," button → ",e.jsx("strong",{children:"Add to Home Screen"}),". Other browsers (Chrome, Firefox, etc.) on iOS do not support push notifications due to Apple restrictions."]})]})})]}),e.jsx(OZs,{}),e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsxs(St,{className:"flex items-center gap-2",children:[V?e.jsx(JM,{className:"h-5 w-5"}):e.jsx(ln,{className:"h-5 w-5"}),"Email Preferences"]}),e.jsx(kn,{children:"Manage your email subscription settings"})]}),e.jsxs(Me,{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:V?"You won't receive weekly digest emails":"Receive a weekly summary of new content, events, and your progress"})]}),e.jsx(fn,{checked:!V,onCheckedChange:async pe=>{H(!0);try{const{error:Ce}=await q.from("profiles").update({digest_opt_out:!pe}).eq("id",s==null?void 0:s.id);if(Ce)throw Ce;G(!pe),n({title:pe?"Subscribed":"Unsubscribed",description:pe?"You will now receive weekly digest emails":"You will no longer receive weekly digest emails"})}catch(Ce){n({title:"Error",description:Ce.message||"Failed to update preference",variant:"destructive"})}finally{H(!1)}},disabled:$})]}),e.jsxs("div",{className:"flex items-center justify-between pt-4 mt-4 border-t",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Event Invite Emails"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:Y?"You won't receive event invite emails (weekly digest is unaffected)":"Get invited to LevelUp live trainings and special events"})]}),e.jsx(fn,{checked:!Y,onCheckedChange:async pe=>{ce(!0);try{const{error:Ce}=await q.from("profiles").update({event_invite_opt_out:!pe}).eq("id",s==null?void 0:s.id);if(Ce)throw Ce;Z(!pe),n({title:pe?"Subscribed":"Unsubscribed",description:pe?"You will now receive event invite emails":"You will no longer receive event invite emails"})}catch(Ce){n({title:"Error",description:Ce.message||"Failed to update preference",variant:"destructive"})}finally{ce(!1)}},disabled:ne})]})]})]}),e.jsx(Cqs,{}),e.jsx(eXs,{}),e.jsx(XZs,{})]}),e.jsx(itt,{open:S,onClose:()=>C(!1),imageSrc:E,onCropComplete:be,aspectRatio:1})]})})};var sXs="AspectRatio",JUt=_.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(ii.div,{...a,ref:t,style:{...r,position:"absolute",top:0,right:0,bottom:0,left:0}})})});JUt.displayName=sXs;var nXs=JUt;const rXs=nXs;function aXs(){const{user:s}=hs(),t=Bt(),[n,r]=_.useState(!1),[a,i]=_.useState(!1),{data:l,isLoading:o}=at({queryKey:["calendar-token",s==null?void 0:s.id],queryFn:async()=>{const{data:f,error:y}=await q.from("profiles").select("calendar_token").eq("id",s==null?void 0:s.id).single();if(y)throw y;return f},enabled:!!s&&a}),c=mt({mutationFn:async()=>{const f=new Uint8Array(12);crypto.getRandomValues(f);const y=btoa(String.fromCharCode(...f)).replace(/\+/g,"x").replace(/\//g,"y").replace(/=/g,"").substring(0,16),{error:v}=await q.from("profiles").update({calendar_token:y}).eq("id",s==null?void 0:s.id);if(v)throw v;return y},onSuccess:()=>{t.invalidateQueries({queryKey:["calendar-token",s==null?void 0:s.id]}),se.success("Calendar subscription URL generated!")},onError:f=>{se.error("Failed to generate calendar URL: "+f.message)}}),d=l!=null&&l.calendar_token?`https://dashboard.relevelup.com/api/calendar/${l.calendar_token}.ics`:null,u=async()=>{d&&(await navigator.clipboard.writeText(d),r(!0),se.success("Calendar URL copied to clipboard!"),setTimeout(()=>r(!1),2e3))},h=()=>{d&&(window.location.href=d.replace("https://","webcal://"))},m=()=>{if(d){const f=d.replace("https://","webcal://"),y=`https://calendar.google.com/calendar/r?cid=${encodeURIComponent(f)}`;window.open(y,"_blank")}},p=()=>{if(d){const f=`https://outlook.live.com/calendar/0/addfromweb?url=${encodeURIComponent(d)}&name=Level%20Up%20Events`;window.open(f,"_blank")}};return e.jsxs(Ls,{open:a,onOpenChange:i,children:[e.jsx(nl,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:"gap-2",children:[e.jsx(ga,{className:"h-4 w-4"}),"Subscribe to Calendar"]})}),e.jsxs(Ps,{className:"sm:max-w-md",children:[e.jsxs(Os,{children:[e.jsxs(Ds,{className:"flex items-center gap-2",children:[e.jsx(ga,{className:"h-5 w-5 text-primary"}),"Subscribe to Events Calendar"]}),e.jsx(_r,{children:"Add all Level Up events to your personal calendar. Events will sync automatically and update when we add or change events."})]}),e.jsx("div",{className:"space-y-4 py-4",children:o?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):d?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Your Calendar URL"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{value:d,readOnly:!0,className:"text-xs font-mono"}),e.jsx(B,{variant:"outline",size:"icon",onClick:u,children:n?e.jsx(ea,{className:"h-4 w-4 text-green-500"}):e.jsx(Ia,{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(B,{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(wr,{className:"h-3 w-3 ml-auto opacity-50"})]}),e.jsxs(B,{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(wr,{className:"h-3 w-3 ml-auto opacity-50"})]}),e.jsxs(B,{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(wr,{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(B,{onClick:()=>c.mutate(),disabled:c.isPending,className:"w-full",children:c.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),"Generating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ga,{className:"h-4 w-4 mr-2"}),"Generate Calendar URL"]})})]})})]})]})}const iXs={first_timer:Da,regular:HA,dedicated:Hh,veteran:wl,streak_master:gu,century:wl},oXs={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 xyt(s){return s===1?e.jsx(wl,{className:"h-5 w-5 text-yellow-500"}):s===2?e.jsx(HA,{className:"h-5 w-5 text-gray-400"}):s===3?e.jsx(Hh,{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 eqt({showUserStats:s=!0,compact:t=!1,brokerageId:n,title:r="Event Leaderboard"}){const{user:a}=hs(),{data:i,isLoading:l}=Rzt(t?5:10,n),{data:o}=Fzt(a==null?void 0:a.id),{data:c}=zzt(a==null?void 0:a.id),{data:d}=Ozt(a==null?void 0:a.id);return l?e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(wl,{className:"h-5 w-5 text-yellow-500"}),r]})}),e.jsx(Me,{children:e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((u,h)=>e.jsx(cn,{className:"h-12 w-full"},h))})})]}):e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-3",children:e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(wl,{className:"h-5 w-5 text-yellow-500"}),r]})}),e.jsxs(Me,{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(Oe,{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(gu,{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=iXs[u.badge_type]||Da;return e.jsxs(Oe,{variant:"outline",className:`text-xs ${oXs[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(Oe,{variant:"outline",className:"text-xs",children:["+",d.length-4," more"]})]})]}),e.jsxs(Yr,{defaultValue:"points",className:"w-full",children:[e.jsxs(Zr,{className:"w-full mb-3",children:[e.jsx(Ht,{value:"points",className:"flex-1",children:"By Points"}),e.jsx(Ht,{value:"events",className:"flex-1",children:"By Events"})]}),e.jsx(Gt,{value:"points",className:"mt-0",children:e.jsxs("div",{className:"space-y-2",children:[i==null?void 0:i.map((u,h)=>{var m,p,f;return e.jsxs("div",{className:`flex items-center gap-3 p-2 rounded-lg ${u.user_id===(a==null?void 0:a.id)?"bg-primary/5 border border-primary/10":""} ${h===0?"bg-yellow-500/5":""}`,children:[e.jsx("div",{className:"w-6 flex justify-center",children:xyt(h+1)}),e.jsx(ja,{className:"h-8 w-8",children:e.jsx(Na,{className:"text-xs",children:((p=(m=u.profile)==null?void 0:m.name)==null?void 0:p.charAt(0))||"?"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium text-sm truncate",children:[((f=u.profile)==null?void 0:f.name)||"Unknown",u.user_id===(a==null?void 0:a.id)&&e.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:"(You)"})]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[u.total_events_attended," events"]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("div",{className:"font-bold text-primary",children:u.total_points}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"pts"})]})]},u.user_id)}),(!i||i.length===0)&&e.jsx("div",{className:"text-center text-muted-foreground py-4 text-sm",children:"No attendance data yet. Attend an event to get on the leaderboard!"})]})}),e.jsx(Gt,{value:"events",className:"mt-0",children:e.jsx("div",{className:"space-y-2",children:[...i||[]].sort((u,h)=>h.total_events_attended-u.total_events_attended).map((u,h)=>{var m,p,f;return e.jsxs("div",{className:`flex items-center gap-3 p-2 rounded-lg ${u.user_id===(a==null?void 0:a.id)?"bg-primary/5 border border-primary/10":""} ${h===0?"bg-yellow-500/5":""}`,children:[e.jsx("div",{className:"w-6 flex justify-center",children:xyt(h+1)}),e.jsx(ja,{className:"h-8 w-8",children:e.jsx(Na,{className:"text-xs",children:((p=(m=u.profile)==null?void 0:m.name)==null?void 0:p.charAt(0))||"?"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium text-sm truncate",children:[((f=u.profile)==null?void 0:f.name)||"Unknown",u.user_id===(a==null?void 0:a.id)&&e.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:"(You)"})]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[u.total_points," points"]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("div",{className:"font-bold",children:u.total_events_attended}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"events"})]})]},u.user_id)})})})]})]})]})}function lXs(){const s=Fn(),{user:t,isAdmin:n}=hs(),r=Bt(),[a,i]=_.useState(!1),[l,o]=_.useState(!1),{data:c,isLoading:d}=at({queryKey:["public-events"],queryFn:async()=>{const{data:E,error:P}=await q.from("events").select("*").order("event_date",{ascending:!0});if(P)throw P;return E}}),{data:u}=at({queryKey:["my-registrations"],queryFn:async()=>{if(!t)return[];const{data:E,error:P}=await q.from("event_registrations").select("event_id, zoom_join_url").eq("user_id",t.id);if(P)throw P;return E},enabled:!!t}),{data:h}=at({queryKey:["event-registration-counts"],queryFn:async()=>{let E=[],P=0;const M=1e3;for(;;){const{data:D,error:O}=await q.from("event_registrations").select("event_id").range(P,P+M-1);if(O)throw O;if(!D||D.length===0||(E=E.concat(D),D.length{I[D.event_id]=(I[D.event_id]||0)+1}),I}}),m=mt({mutationFn:async E=>{await q.auth.refreshSession();const{data:P,error:M}=await q.functions.invoke("zoom-register",{body:{event_id:E}});if(M)throw M;if(P!=null&&P.error)throw new Error(P.error);return P},onSuccess:E=>{r.invalidateQueries({queryKey:["my-registrations"]}),r.invalidateQueries({queryKey:["event-registration-counts"]}),E!=null&&E.join_url?se.success("Successfully registered! You'll receive a Zoom confirmation email."):se.success("Successfully registered for the event!")},onError:E=>{se.error("Failed to register: "+E.message)}}),p=mt({mutationFn:async E=>{const{data:P,error:M}=await q.functions.invoke("zoom-unregister",{body:{event_id:E}});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"]}),se.success("Registration cancelled and removed from Zoom")},onError:E=>{se.error("Failed to cancel: "+E.message)}}),f=E=>u==null?void 0:u.some(P=>P.event_id===E),y=E=>{const P=u==null?void 0:u.find(M=>M.event_id===E);return P==null?void 0:P.zoom_join_url},v=E=>E.capacity?((h==null?void 0:h[E.id])||0)>=E.capacity:!1,g=(c==null?void 0:c.filter(E=>fF(E.event_date)!=="ended"))||[],b=(c==null?void 0:c.filter(E=>fF(E.event_date)==="ended"))||[],j=g.filter(E=>fF(E.event_date)==="live").length,S=g.filter(E=>f(E.id)).length,C=l?b:b.slice(0,6);return e.jsx(zs,{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:j>0?"An event is live right now — jump in.":g.length>0?`Next up: ${g[0].title}`:"No upcoming events scheduled — replays are below."})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(aXs,{}),n&&e.jsxs("button",{onClick:()=>s("/admin/events"),className:"hub-glass inline-flex items-center gap-2 rounded-full px-4 py-2 text-sm font-medium transition-colors",children:[e.jsx(qc,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Manage Events"]})]})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 sm:grid-cols-4",children:[{label:"Upcoming",value:g.length,icon:ga},{label:"You're registered",value:S,icon:ea},{label:"Live now",value:j,icon:Nv},{label:"Past events",value:b.length,icon:R_}].map(E=>e.jsxs("div",{className:"hub-glass rounded-xl px-3 py-2.5",children:[e.jsx("span",{className:"text-xl font-bold",children:E.value}),e.jsxs("p",{className:"mt-0.5 flex items-center gap-1 text-[11px] hub-ink-muted",children:[e.jsx(E.icon,{className:"h-3 w-3"}),E.label]})]},E.label))})]})}),e.jsxs("div",{className:`grid grid-cols-1 gap-6 ${n?"lg:grid-cols-3":""}`,children:[e.jsxs("div",{className:`space-y-6 ${n?"lg:col-span-2":""}`,children:[d?e.jsx("div",{className:"grid gap-6 md:grid-cols-2",children:[0,1].map(E=>e.jsx("div",{className:"h-72 animate-pulse rounded-2xl border bg-muted/40"},E))}):g.length===0?e.jsx(ve,{className:"rounded-2xl border-dashed py-12 text-center",children:e.jsxs(Me,{className:"space-y-2",children:[e.jsx(ga,{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:g.map(E=>{const P=fF(E.event_date),M=yet(E.event_date),I=P==="live",D=P==="starting_soon";return e.jsxs(ve,{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/${E.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(Nv,{className:"h-3.5 w-3.5"}),"LIVE NOW"]}):e.jsxs(e.Fragment,{children:[e.jsx(Gr,{className:"h-3.5 w-3.5"}),"STARTING SOON"]})]}),E.image_url&&e.jsxs(rXs,{ratio:16/9,className:"overflow-hidden relative bg-neutral-900",children:[e.jsx("img",{src:E.image_url,alt:"","aria-hidden":"true",className:"absolute inset-0 w-full h-full object-cover blur-2xl scale-110 opacity-60"}),e.jsx("img",{src:E.image_url,alt:E.title,className:"relative w-full h-full object-contain transition-transform group-hover:scale-[1.03]"})]}),e.jsxs(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(ga,{className:"h-3 w-3"}),new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",timeZone:"America/New_York"}).format(new Date(E.event_date))]}),f(E.id)&&e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full bg-emerald-500/10 px-2.5 py-1 text-[11px] font-semibold text-emerald-600 dark:text-emerald-400",children:[e.jsx(ea,{className:"h-3 w-3"}),"Registered"]})]}),e.jsx(St,{className:"line-clamp-2 pt-1",children:E.title}),E.description&&e.jsx(kn,{className:"line-clamp-2",children:E.description.replace(/<[^>]*>/g,"")})]}),e.jsxs(Me,{className:"flex-1 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(ga,{className:"h-4 w-4"}),new Intl.DateTimeFormat("en-US",{weekday:"long",year:"numeric",month:"long",day:"numeric",timeZone:"America/New_York"}).format(new Date(E.event_date))]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Gr,{className:"h-4 w-4"}),pte(new Date(E.event_date))]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(In,{className:"h-4 w-4"}),(h==null?void 0:h[E.id])||0," registered",E.capacity&&` / ${E.capacity} spots`]})]}),e.jsx(Q3e,{className:"flex gap-2",onClick:O=>O.stopPropagation(),children:f(E.id)?e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"outline",className:"flex-1",onClick:()=>p.mutate(E.id),disabled:p.isPending,children:[e.jsx(Qn,{className:"h-4 w-4 mr-2"}),"Cancel"]}),e.jsxs(B,{className:"flex-1",onClick:()=>window.open(y(E.id)||E.zoom_link,"_blank"),children:[e.jsx(wr,{className:"h-4 w-4 mr-2"}),"Join Zoom"]})]}):e.jsx(B,{className:"w-full",onClick:()=>m.mutate(E.id),disabled:m.isPending||v(E),children:v(E)?"Event Full":e.jsxs(e.Fragment,{children:[e.jsx(ea,{className:"h-4 w-4 mr-2"}),"Register"]})})})]},E.id)})}),b.length>0&&e.jsxs(ve,{className:"rounded-2xl",children:[e.jsxs("button",{type:"button",onClick:()=>i(E=>!E),className:"flex w-full items-center justify-between gap-3 px-5 py-4 text-left",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-9 w-9 items-center justify-center rounded-xl bg-muted",children:e.jsx(R_,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold",children:"Past Events"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[b.length," previous ",b.length===1?"session":"sessions"," — open one to watch the replay"]})]})]}),e.jsx(tl,{className:`h-4 w-4 text-muted-foreground transition-transform ${a?"rotate-180":""}`})]}),a&&e.jsxs("div",{className:"border-t",children:[e.jsx("ul",{className:"divide-y",children:C.map(E=>e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:()=>s(`/events/${E.id}`),className:"flex w-full items-center gap-3 px-5 py-3 text-left transition-colors hover:bg-muted/50",children:[e.jsxs("div",{className:"flex w-12 shrink-0 flex-col items-center rounded-lg border bg-muted/40 py-1",children:[e.jsx("span",{className:"text-[10px] font-semibold uppercase text-muted-foreground",children:new Intl.DateTimeFormat("en-US",{month:"short",timeZone:"America/New_York"}).format(new Date(E.event_date))}),e.jsx("span",{className:"text-sm font-bold leading-none",children:new Intl.DateTimeFormat("en-US",{day:"numeric",timeZone:"America/New_York"}).format(new Date(E.event_date))})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:E.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:new Intl.DateTimeFormat("en-US",{year:"numeric",month:"long",day:"numeric",timeZone:"America/New_York"}).format(new Date(E.event_date))})]}),e.jsx(om,{className:"h-4 w-4 shrink-0 text-muted-foreground"})]})},E.id))}),b.length>6&&e.jsx("div",{className:"border-t px-5 py-3",children:e.jsx(B,{variant:"ghost",size:"sm",className:"w-full",onClick:()=>o(E=>!E),children:l?"Show less":`Show all ${b.length}`})})]})]})]}),n&&e.jsx("div",{className:"lg:col-span-1",children:e.jsx(eqt,{showUserStats:!0})})]})]})})}const O7e=[{value:"all",label:"All Roles",icon:In},{value:"newest",label:"Newest Members",icon:Gr},{value:"brokerage_manager",label:"Brokerage Managers",icon:mJ},{value:"admin",label:"Admins",icon:Rm}];function cXs({open:s,onOpenChange:t,resourceType:n,resourceId:r,resourceTitle:a}){var Pe,ze;const{user:i,isAdmin:l,isBrokerageManager:o}=hs(),[c,d]=_.useState([]),[u,h]=_.useState([]),[m,p]=_.useState([]),[f,y]=_.useState([]),[v,g]=_.useState(""),[b,j]=_.useState(""),[S,C]=_.useState(""),[E,P]=_.useState(!1),[M,I]=_.useState(!1),[D,O]=_.useState("agents"),[V,G]=_.useState("all"),[$,H]=_.useState({}),Y=l||o;_.useEffect(()=>{s&&i&&(l?Z():ne())},[s,i,l]),_.useEffect(()=>{s||(p([]),y([]),g(""),j(""),C(""),O("agents"),G("all"))},[s]);const Z=async()=>{if(i){P(!0);try{const{data:ke,error:Ze}=await q.from("brokerages").select("id, name").order("name");if(Ze)throw Ze;const Se=1e3,Fe={};let Ne=0,Ye=!0;for(;Ye;){const{data:Qe,error:Ue}=await q.from("profiles").select("brokerage_id").range(Ne*Se,(Ne+1)*Se-1);if(Ue)throw Ue;Qe==null||Qe.forEach(Xe=>{Xe.brokerage_id&&(Fe[Xe.brokerage_id]=(Fe[Xe.brokerage_id]||0)+1)}),Ye=(Qe==null?void 0:Qe.length)===Se,Ne++}h((ke==null?void 0:ke.map(Qe=>({...Qe,agent_count:Fe[Qe.id]||0})))||[]);const Ve=[];for(Ne=0,Ye=!0;Ye;){const{data:Qe,error:Ue}=await q.from("profiles").select("id, name, email, brokerage_id, created_at, brokerages(name)").neq("id",i.id).order("name").range(Ne*Se,(Ne+1)*Se-1);if(Ue)throw Ue;Qe&&Ve.push(...Qe),Ye=(Qe==null?void 0:Qe.length)===Se,Ne++}const qe={};for(Ne=0,Ye=!0;Ye;){const{data:Qe,error:Ue}=await q.from("user_roles").select("user_id, role").range(Ne*Se,(Ne+1)*Se-1);if(Ue)throw Ue;Qe==null||Qe.forEach(Xe=>{qe[Xe.user_id]||(qe[Xe.user_id]=[]),qe[Xe.user_id].push(Xe.role)}),Ye=(Qe==null?void 0:Qe.length)===Se,Ne++}H(qe),d(Ve.map(Qe=>{var Ue;return{id:Qe.id,name:Qe.name,email:Qe.email,brokerage_name:((Ue=Qe.brokerages)==null?void 0:Ue.name)||"No Brokerage",roles:qe[Qe.id]||[],created_at:Qe.created_at}}))}catch(ke){console.error("Error loading data:",ke),se.error("Failed to load agents and brokerages")}finally{P(!1)}}},ne=async()=>{if(i){P(!0);try{const{data:ke}=await q.from("profiles").select("brokerage_id").eq("id",i.id).single();if(!(ke!=null&&ke.brokerage_id)){se.error("You must be part of a brokerage to share resources"),t(!1);return}const{data:Ze,error:Se}=await q.from("profiles").select("id, name, email").eq("brokerage_id",ke.brokerage_id).neq("id",i.id).order("name");if(Se)throw Se;d(Ze||[])}catch(ke){console.error("Error loading agents:",ke),se.error("Failed to load agents")}finally{P(!1)}}},ce=c.filter(ke=>{var Se;const Ze=ke.name.toLowerCase().includes(v.toLowerCase())||ke.email.toLowerCase().includes(v.toLowerCase())||((Se=ke.brokerage_name)==null?void 0:Se.toLowerCase().includes(v.toLowerCase()));if(l&&V!=="all"&&V!=="newest"){const Fe=$[ke.id]||[];return Ze&&Fe.includes(V)}return Ze}).sort((ke,Ze)=>V==="newest"?(Ze.created_at||"").localeCompare(ke.created_at||""):0),ie=u.filter(ke=>ke.name.toLowerCase().includes(b.toLowerCase())),te=()=>{m.length===ce.length?p([]):p(ce.map(ke=>ke.id))},ae=()=>{f.length===ie.length?y([]):y(ie.map(ke=>ke.id))},le=ke=>{if(!Y){p([ke]);return}p(Ze=>Ze.includes(ke)?Ze.filter(Se=>Se!==ke):[...Ze,ke])},be=ke=>{y(Ze=>Ze.includes(ke)?Ze.filter(Se=>Se!==ke):[...Ze,ke])},me=async()=>{if(!(m.length>0||f.length>0)){se.error("Please select at least one agent or brokerage to share with");return}I(!0);try{const{data:Ze,error:Se}=await q.functions.invoke("send-share-notification",{body:{recipientIds:m,brokerageIds:f,resourceType:n,resourceId:r,resourceTitle:a,message:S.trim()||void 0}});if(Se)throw Se;const Fe=(Ze==null?void 0:Ze.sharesCreated)||m.length;se.success(`Shared with ${Fe} agent${Fe!==1?"s":""}`),t(!1)}catch(Ze){console.error("Error sharing resource:",Ze),se.error("Failed to share resource")}finally{I(!1)}},he=ke=>ke.split(" ").map(Ze=>Ze[0]).join("").toUpperCase().slice(0,2),pe=ke=>{const Ze=$[ke]||[];return Ze.includes("admin")?e.jsx(Oe,{variant:"secondary",className:"text-[10px] px-1.5 py-0",children:"Admin"}):Ze.includes("brokerage_manager")?e.jsx(Oe,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:"Manager"}):null},Ce=m.length+f.length,Ae=V!=="all"&&V!=="newest"?ce.length:null;return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"sm:max-w-lg max-h-[90vh] overflow-hidden flex flex-col",children:[e.jsxs(Os,{className:"flex-shrink-0",children:[e.jsxs(Ds,{className:"flex items-center gap-2",children:[e.jsx(Or,{className:"h-5 w-5 text-primary"}),"Share Resource"]}),e.jsxs(_r,{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(Yr,{value:D,onValueChange:O,className:"flex-1 flex flex-col overflow-hidden",children:[e.jsxs(Zr,{className:"grid w-full grid-cols-2 flex-shrink-0",children:[e.jsxs(Ht,{value:"agents",className:"flex items-center gap-2",children:[e.jsx(In,{className:"h-4 w-4"}),e.jsx("span",{children:"Agents"}),m.length>0&&e.jsx(Oe,{variant:"default",className:"h-5 min-w-5 px-1.5 text-xs",children:m.length})]}),e.jsxs(Ht,{value:"brokerages",className:"flex items-center gap-2",children:[e.jsx(ai,{className:"h-4 w-4"}),e.jsx("span",{children:"Brokerages"}),f.length>0&&e.jsx(Oe,{variant:"default",className:"h-5 min-w-5 px-1.5 text-xs",children:f.length})]})]}),e.jsxs(Gt,{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(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search by name, email, or brokerage...",value:v,onChange:ke=>g(ke.target.value),className:"pl-9"})]}),e.jsxs(is,{value:V,onValueChange:G,children:[e.jsxs(rs,{className:"w-[180px]",children:[e.jsx(D_,{className:"h-4 w-4 mr-2 text-muted-foreground"}),e.jsx(ls,{placeholder:"Filter by role"})]}),e.jsx(as,{children:O7e.map(ke=>e.jsx(He,{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(B,{variant:"ghost",size:"sm",onClick:te,className:"text-xs h-8",disabled:ce.length===0,children:[e.jsx(In,{className:"h-3.5 w-3.5 mr-1.5"}),m.length===ce.length&&ce.length>0?"Deselect All":"Select All"]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[Ae!==null&&e.jsxs("span",{className:"text-primary font-medium",children:[Ae," ",(Pe=O7e.find(ke=>ke.value===V))==null?void 0:Pe.label]}),e.jsxs("span",{className:"font-medium",children:[m.length," selected"]})]})]}),e.jsx(Ji,{className:"h-[300px] border rounded-lg",children:E?e.jsx("div",{className:"flex items-center justify-center h-[200px]",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):ce.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-[200px] text-muted-foreground",children:[e.jsx(In,{className:"h-8 w-8 mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:V!=="all"?`No ${(ze=O7e.find(ke=>ke.value===V))==null?void 0:ze.label.toLowerCase()} found`:"No agents found"})]}):e.jsx("div",{className:"p-2 space-y-1",children:ce.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:()=>le(ke.id),children:[e.jsx($a,{checked:m.includes(ke.id),onCheckedChange:()=>le(ke.id),className:"flex-shrink-0"}),e.jsx(ja,{className:"h-9 w-9 flex-shrink-0",children:e.jsx(Na,{className:"text-xs bg-primary/10 text-primary",children:he(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}),pe(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(Gt,{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(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search brokerages...",value:b,onChange:ke=>j(ke.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex items-center justify-between px-1 flex-shrink-0",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:ae,className:"text-xs h-8",disabled:ie.length===0,children:[e.jsx(ai,{className:"h-3.5 w-3.5 mr-1.5"}),f.length===ie.length&&ie.length>0?"Deselect All":"Select All"]}),e.jsxs("span",{className:"text-xs text-muted-foreground font-medium",children:[f.length," selected"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground px-1 flex-shrink-0",children:"Selecting a brokerage will send to all agents in that brokerage."}),e.jsx(Ji,{className:"h-[250px] border rounded-lg",children:E?e.jsx("div",{className:"flex items-center justify-center h-[180px]",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):ie.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:ie.map(ke=>e.jsxs("div",{className:`flex items-center gap-3 p-2.5 rounded-lg cursor-pointer hover:bg-accent/50 transition-colors ${f.includes(ke.id)?"bg-accent":""}`,onClick:()=>be(ke.id),children:[e.jsx($a,{checked:f.includes(ke.id),onCheckedChange:()=>be(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(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search agents...",value:v,onChange:ke=>g(ke.target.value),className:"pl-9"})]}),Y&&e.jsxs("div",{className:"flex items-center justify-between px-1 flex-shrink-0",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:te,className:"text-xs h-8",disabled:ce.length===0,children:[e.jsx(In,{className:"h-3.5 w-3.5 mr-1.5"}),m.length===ce.length&&ce.length>0?"Deselect All":"Select All"]}),e.jsxs("span",{className:"text-xs text-muted-foreground font-medium",children:[m.length," selected"]})]}),e.jsx(Ji,{className:"h-[300px] border rounded-lg",children:E?e.jsx("div",{className:"flex items-center justify-center h-[200px]",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):ce.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-[200px] text-muted-foreground",children:[e.jsx(In,{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:ce.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:()=>le(ke.id),children:[e.jsx($a,{checked:m.includes(ke.id),onCheckedChange:()=>le(ke.id),className:"flex-shrink-0"}),e.jsx(ja,{className:"h-9 w-9 flex-shrink-0",children:e.jsx(Na,{className:"text-xs bg-primary/10 text-primary",children:he(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(J,{htmlFor:"message",className:"text-sm font-medium",children:"Add a message (optional)"}),e.jsx(Ms,{id:"message",placeholder:"I thought you might find this useful...",value:S,onChange:ke=>C(ke.target.value),rows:2,className:"resize-none"})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2 flex-shrink-0",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(B,{onClick:me,disabled:Ce===0||M,children:M?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),"Sharing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Or,{className:"h-4 w-4 mr-2"}),"Share"]})})]})]})]})})}function jW({resourceType:s,resourceId:t,resourceTitle:n,variant:r="outline",size:a="sm",className:i=""}){const[l,o]=_.useState(!1),{user:c}=hs();return c?e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:r,size:a,onClick:()=>o(!0),className:i,children:[e.jsx(bd,{className:"h-4 w-4 mr-2"}),"Share"]}),e.jsx(cXs,{open:l,onOpenChange:o,resourceType:s,resourceId:t,resourceTitle:n})]}):null}function dXs(){const{eventId:s}=Li(),t=Fn(),{user:n}=hs(),[r,a]=_.useState(null),[i,l]=_.useState(null),[o,c]=_.useState(0),[d,u]=_.useState(!0),[h,m]=_.useState(!1);_.useEffect(()=>{s&&p()},[s,n]);const p=async()=>{try{const{data:j,error:S}=await q.from("events").select("*").eq("id",s).single();if(S)throw S;a(j);const{count:C}=await q.from("event_registrations").select("*",{count:"exact",head:!0}).eq("event_id",s);if(c(C||0),n){const{data:E}=await q.from("event_registrations").select("id, zoom_join_url").eq("event_id",s).eq("user_id",n.id).maybeSingle();l(E)}}catch(j){console.error("Error loading event:",j),se.error("Failed to load event"),t("/events")}finally{u(!1)}},f=async()=>{if(!(!n||!r)){m(!0);try{const{error:j}=await q.auth.refreshSession();if(j){console.error("Session refresh failed:",j),se.error("Your session has expired. Please log in again.");return}if(i){const{error:S}=await q.functions.invoke("zoom-unregister",{body:{event_id:r.id}});if(S)throw S;se.success("Successfully cancelled registration"),l(null),c(C=>C-1)}else{const{data:S,error:C}=await q.functions.invoke("zoom-register",{body:{event_id:r.id}});if(C)throw C;se.success("Successfully registered for event!"),l({id:S.registration_id,zoom_join_url:S.zoom_join_url}),c(E=>E+1)}}catch(j){console.error("Registration error:",j),se.error(i?"Failed to cancel registration":"Failed to register for event")}finally{m(!1)}}},y=j=>{var S,C,E;if(j.includes("iframe.mediadelivery.net")||j.includes("video.bunnycdn.com")){const P=j.match(/embed\/(\d+)\/([a-f0-9-]+)/);if(P)return`https://iframe.mediadelivery.net/embed/${P[1]}/${P[2]}?autoplay=false&preload=true`}if(j.includes("youtube.com")||j.includes("youtu.be")){const P=j.includes("youtu.be")?(S=j.split("youtu.be/")[1])==null?void 0:S.split("?")[0]:(C=j.split("v=")[1])==null?void 0:C.split("&")[0];if(P)return`https://www.youtube.com/embed/${P}`}if(j.includes("vimeo.com")){const P=(E=j.split("vimeo.com/")[1])==null?void 0:E.split("?")[0];if(P)return`https://player.vimeo.com/video/${P}`}return j};if(d)return e.jsx(zs,{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(zs,{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(B,{onClick:()=>t("/events"),className:"mt-4",children:"Back to Events"})]})});const v=X4(new Date(r.event_date)),g=r.capacity&&o>=r.capacity,b=(i==null?void 0:i.zoom_join_url)||r.zoom_link;return e.jsx(zs,{title:r.title,children:e.jsxs("div",{className:"max-w-4xl mx-auto",children:[e.jsxs(B,{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"}),v&&e.jsx("div",{className:"absolute inset-0 bg-black/50 flex items-center justify-center",children:e.jsx(Oe,{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(jW,{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(om,{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:y(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(ve,{children:e.jsxs(Me,{className:"p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(ga,{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:pte(new Date(r.event_date))})]})]}),r.capacity&&e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(In,{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(_l,{className:"h-5 w-5 text-green-600"}),e.jsx("span",{className:"text-sm font-medium text-green-700",children:"You're registered!"})]}),e.jsxs("div",{className:"space-y-2 pt-2",children:[!v&&e.jsx(e.Fragment,{children:i?e.jsxs(e.Fragment,{children:[e.jsxs(B,{className:"w-full gap-2",onClick:()=>window.open(b,"_blank"),children:[e.jsx(wr,{className:"h-4 w-4"}),"Join Event"]}),e.jsxs(B,{variant:"outline",className:"w-full",onClick:f,disabled:h,children:[h?e.jsx(Ct,{className:"h-4 w-4 animate-spin mr-2"}):null,"Cancel Registration"]})]}):e.jsx(B,{className:"w-full gap-2",onClick:f,disabled:h||(g??!1),children:h?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):g?"Event Full":"Register Now"})}),v&&i&&e.jsxs(B,{variant:"outline",className:"w-full gap-2",onClick:()=>window.open(r.zoom_link,"_blank"),children:[e.jsx(wr,{className:"h-4 w-4"}),"View Recording"]})]})]})})})]})]})})}const uXs=[{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 hXs(){const{isAdmin:s}=hs(),t=uXs.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(o6,{to:n.to,end:n.end,className:({isActive:r})=>At("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 bEe=[{id:"market-listing",title:"Market a Listing",blurb:"Presentations, copy, pages and video",icon:Jr,color:"bg-violet-500/15 text-violet-600"},{id:"follow-up",title:"Follow Up With My Database",blurb:"Emails, cards, mail and check-ins",icon:ln,color:"bg-emerald-500/15 text-emerald-600"},{id:"social-content",title:"Create Social Content",blurb:"Reels, posts and captions",icon:wh,color:"bg-rose-500/15 text-rose-600"},{id:"open-house",title:"Host an Open House",blurb:"Promote, sign in and follow up",icon:dN,color:"bg-sky-500/15 text-sky-600"},{id:"new-business",title:"Generate New Business",blurb:"Leads, expireds and by-owner sellers",icon:Nl,color:"bg-amber-500/15 text-amber-600"},{id:"brand",title:"Build My Brand",blurb:"Your card, site, reviews and presence",icon:Xc,color:"bg-teal-500/15 text-teal-600"}];bEe.reduce((s,t)=>({...s,[t.id]:t}),{});const mXs=[{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"}],tqt=[{id:"scheduler",name:"LevelUp Scheduler",description:"Share your booking link, sync Google Calendar and let clients book you",icon:Qd,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:Kr,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:_y,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:jv,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:Fr,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:Sx,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:un,path:"/mission-control/card-studio",color:"bg-pink-500/15 text-pink-600",goals:["follow-up","social-content"],categories:["database","social"],keywords:["birthday card","anniversary","greeting","thank you card"]},{id:"direct-mail",name:"Direct Mail",description:"Send professional postcards to your contacts",icon:ln,path:"/mission-control/direct-mail",color:"bg-indigo-500/15 text-indigo-600",adminOnly:!0,beta:!0,goals:["follow-up","open-house"],categories:["database","open-houses"],keywords:["postcard","mailer","farming","direct mail"]},{id:"reelflow",name:"ReelFlow",description:"Turn property photos into cinematic reels with AI",icon:dm,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:Or,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:Qm,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:Wq,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:mN,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:dm,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:bl,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:jv,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:un,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:Jr,path:"/apps/fsbo-breakthrough",color:"bg-[#5b8a5c]/15 text-[#5b8a5c]",isNew:!0,goals:["new-business"],categories:["leads","ai"],keywords:["fsbo","for sale by owner","by owner","convert fsbo"]},{id:"staging-studio",name:"Staging Studio",description:"Virtually stage, declutter and brighten listing photos",icon:n$,path:"/apps/staging-studio",color:"bg-[#406E71]/15 text-[#406E71]",isNew:!0,featureFlag:"staging_studio_enabled",goals:["market-listing"],categories:["listings","ai"],keywords:["virtual staging","staging","twilight","declutter","sky replacement","landscaping","photo"]}],gyt=tqt.reduce((s,t)=>({...s,[t.id]:t}),{}),pXs={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 fXs(s){return pXs[s]??{goals:[],categories:[],keywords:[]}}const ott=[{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:Jr,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:dN,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:In,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"}]}],i9=ott.reduce((s,t)=>({...s,[t.id]:t}),{});function xXs({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:At("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 gXs({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:At("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:At("flex-shrink-0 w-12 h-12 rounded-xl flex items-center justify-center text-2xl",s.color),children:i?e.jsx(ec,{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:At("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:At("flex-shrink-0 p-2 -m-1 rounded-lg transition-colors",t?"text-primary":"text-muted-foreground/40 hover:text-primary"),children:e.jsx(C0,{className:At("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 w7({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(gXs,{item:a,isFavorite:t(a),onOpen:n,onToggleFavorite:r},a.key))})}const yXs="bg-primary/10 text-primary";function hae(){const{user:s,isAdmin:t}=hs(),n=IS(),r=Fn(),{hasAccess:a}=JMe(),{isFeatureEnabled:i}=Ore(),[l,o]=_.useState([]),[c,d]=_.useState(!0),[u,h]=_.useState(new Set),[m,p]=_.useState(new Set),[f,y]=_.useState(!1),[v,g]=_.useState([]),[b,j]=_.useState(""),S=_.useCallback(async()=>{if(s!=null&&s.id)try{const[{data:H},{data:Y},{data:Z},{data:ne},{data:ce},{data:ie},{data:te}]=await Promise.all([q.from("user_tags").select("tag").eq("user_id",s.id),q.from("app_tiles").select("*").order("name"),q.from("user_favorites").select("app_id").eq("user_id",s.id),q.from("user_tool_favorites").select("tool_id").eq("user_id",s.id),q.from("lead_sites").select("id, mls_provider_id, no_mls_mode, is_active").eq("agent_id",s.id),q.from("activity_logs").select("app_id, app_name, launched_at").eq("user_id",s.id).order("launched_at",{ascending:!1}).limit(40),q.from("profiles").select("name").eq("id",s.id).maybeSingle()]),ae=(H||[]).map(pe=>pe.tag);y((ce||[]).some(pe=>pe.is_active&&pe.mls_provider_id&&!pe.no_mls_mode)),h(new Set((Z||[]).map(pe=>pe.app_id))),p(new Set((ne||[]).map(pe=>pe.tool_id)));const le=(Y||[]).filter(pe=>pe.app_id==="newsletter_studio"?!1:!pe.required_tags||pe.required_tags.length===0?!0:pe.required_tags.some(Ce=>ae.includes(Ce)));o(le.sort((pe,Ce)=>pe.name==="LevelUp Members Portal"?-1:Ce.name==="LevelUp Members Portal"?1:0));const be=new Set,me=[];for(const pe of ie||[])if(!(!pe.app_id||be.has(pe.app_id))&&(be.add(pe.app_id),me.push({appId:pe.app_id,name:pe.app_name,at:pe.launched_at}),me.length>=8))break;g(me);const he=te==null?void 0:te.name;j(he?he.trim().split(" ")[0]:"")}catch(H){console.error("Error loading app catalog:",H),se.error("Failed to load apps")}finally{d(!1)}},[s==null?void 0:s.id]);_.useEffect(()=>{S()},[S]);const C=_.useMemo(()=>{const H=ce=>{if(!n.isRestricted)return null;const ie=k2s(ce);return ie&&!n.hasFeature(ie)?ie:null},Y=tqt.filter(ce=>!(ce.adminOnly&&!t||ce.requiresLeadSiteMLS&&!f&&!t||ce.requiresWeeklyReels&&!a||ce.featureFlag&&!i(ce.featureFlag)&&!t)).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:H(ce.id),tool:ce})),Z={AgentReview:"marketing_studio",SigFlow:"marketing_studio",Staging_Studio:"marketing_studio",social_autopilot:"social",newsletter_studio:"newsletter"},ne=l.map(ce=>{const ie=fXs(ce.app_id),te=Z[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:yXs,goals:ie.goals,categories:ie.categories,keywords:ie.keywords,lockedFeature:n.isRestricted&&te&&!n.hasFeature(te)?te:null,tile:ce}});return[...Y,...ne]},[l,t,f,a,i,n.isRestricted,n.features]),E=_.useCallback(H=>{var Y;return H.kind==="tool"?m.has(H.id):u.has(((Y=H.tile)==null?void 0:Y.id)??"")},[m,u]),P=_.useMemo(()=>C.filter(E),[C,E]),M=_.useMemo(()=>{const H=new Map(C.map(Y=>[Y.id,Y]));return v.map(Y=>H.get(Y.appId)).filter(Boolean)},[C,v]),I=_.useMemo(()=>C.filter(H=>H.kind==="app"),[C]),D=_.useCallback(async(H,Y)=>{try{await q.from("activity_logs").insert({user_id:s==null?void 0:s.id,app_id:H,app_name:Y,user_agent:navigator.userAgent})}catch{}},[s==null?void 0:s.id]),O=_.useCallback(async H=>{var Z;if(H.target_url.startsWith("/")){await D(H.app_id,H.name),r(H.target_url);return}try{const ne=new URL(H.target_url);if(new Set([window.location.hostname,"dashboard.relevelup.com"]).has(ne.hostname)){await D(H.app_id,H.name),r(ne.pathname+ne.search+ne.hash);return}}catch{}const Y=window.open("about:blank","_blank");try{const{data:ne,error:ce}=await q.auth.getSession();if(ce||!ne.session){Y==null||Y.close(),se.error("Session expired. Please refresh the page and try again.");return}await D(H.app_id,H.name);const{data:ie,error:te}=await q.functions.invoke("sso-launch",{body:{app_id:H.app_id},headers:{Authorization:`Bearer ${ne.session.access_token}`}});if(te)throw te;ie!=null&&ie.redirect_url?Y&&!Y.closed?(Y.location.href=ie.redirect_url,(Z=Y.focus)==null||Z.call(Y)):window.location.assign(ie.redirect_url):(Y==null||Y.close(),se.error("Launch link unavailable"))}catch(ne){Y==null||Y.close(),console.error("Error launching app:",ne),se.error("Failed to launch app. Please try again.")}},[D,r]),V=_.useCallback(H=>{if(H.lockedFeature){r(`/upgrade/${H.lockedFeature}`);return}if(H.kind==="app"&&H.tile){O(H.tile);return}H.tool&&(D(H.tool.id,H.tool.name),r(H.tool.path))},[O,D,r]),G=_.useCallback(async H=>{var te;if(!(s!=null&&s.id))return;const Y=E(H),Z=H.kind==="tool"?"user_tool_favorites":"user_favorites",ne=H.kind==="tool"?"tool_id":"app_id",ce=H.kind==="tool"?H.id:(te=H.tile)==null?void 0:te.id;if(!ce)return;const ie=H.kind==="tool"?p:h;ie(ae=>{const le=new Set(ae);return Y?le.delete(ce):le.add(ce),le});try{if(Y){const{error:ae}=await q.from(Z).delete().eq("user_id",s.id).eq(ne,ce);if(ae)throw ae}else{const{error:ae}=await q.from(Z).insert({user_id:s.id,[ne]:ce});if(ae)throw ae}}catch(ae){console.error("Error toggling favorite:",ae),se.error("Failed to update favorites"),ie(le=>{const be=new Set(le);return Y?be.add(ce):be.delete(ce),be})}},[E,s==null?void 0:s.id]),$=_.useCallback((H,Y=C)=>{const Z=H.trim().toLowerCase();if(!Z)return Y;const ne=Z.split(/\s+/);return Y.filter(ce=>{const ie=[ce.name,ce.description,...ce.keywords,...ce.categories,...ce.goals].join(" ").toLowerCase();return ne.every(te=>ie.includes(te))||ie.includes(Z)})},[C]);return{loading:c,items:C,favoriteItems:P,recentItems:M,connectedItems:I,recent:v,firstName:b,isFavorite:E,toggleFavorite:G,openItem:V,search:$,reload:S}}function z7e(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 ILe(s){const t=i9[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 DLe(){const{user:s}=hs(),[t,n]=_.useState([]),[r,a]=_.useState(!0),i=_.useCallback(async()=>{if(s!=null&&s.id)try{const{data:m,error:p}=await q.from("workflow_runs").select("*").eq("user_id",s.id).order("last_activity_at",{ascending:!1});if(p)throw p;n((m||[]).map(z7e))}catch(m){console.error("Error loading workflow runs:",m)}finally{a(!1)}},[s==null?void 0:s.id]);_.useEffect(()=>{i()},[i]);const l=_.useCallback(async(m,p)=>{var f;if(!(s!=null&&s.id))return null;try{const{data:y,error:v}=await q.from("workflow_runs").insert({user_id:s.id,workflow_id:m,run_name:p.trim()||((f=i9[m])==null?void 0:f.title)||"Untitled"}).select("*").single();if(v)throw v;const g=z7e(y);return n(b=>[g,...b]),g}catch(y){return console.error("Error starting workflow:",y),se.error("Could not start this workflow"),null}},[s==null?void 0:s.id]),o=_.useCallback(async(m,p)=>{const f={...p,last_activity_at:new Date().toISOString()};n(v=>v.map(g=>g.id===m?z7e({...g,...f}):g));const{error:y}=await q.from("workflow_runs").update(f).eq("id",m);y&&(console.error("Error updating workflow run:",y),se.error("Could not save your progress"))},[]),c=_.useCallback(async(m,p,f)=>{const y={...m.step_state};f?y[p]=f:delete y[p];const v=i9[m.workflow_id],g=v?v.steps.every(b=>y[b.key]):!1;await o(m.id,{step_state:y,status:g?"completed":"in_progress",completed_at:g?new Date().toISOString():null}),g&&m.status!=="completed"&&se.success("Workflow complete — nice work!")},[o]),d=_.useCallback((m,p)=>o(m.id,{run_name:p.trim()}),[o]),u=_.useCallback(m=>o(m.id,{status:"in_progress",completed_at:null}),[o]),h=_.useCallback(async m=>{n(f=>f.filter(y=>y.id!==m));const{error:p}=await q.from("workflow_runs").delete().eq("id",m);p&&(console.error("Error deleting workflow run:",p),se.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 vXs(){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 bXs(){const s=Fn(),{items:t,firstName:n,recentItems:r,favoriteItems:a,isFavorite:i,toggleFavorite:l,openItem:o,search:c}=hae(),{isAdmin:d}=hs(),{activeRuns:u}=DLe(),h=d?u:[],[m,p]=_.useState(""),f=_.useMemo(()=>m.trim()?c(m).slice(0,8):[],[m,c]),y=_.useMemo(()=>{const g=new Set(r.map(S=>S.id)),b=[],j=S=>{for(const C of S){if(b.length>=4)break;b.some(E=>E.key===C.key)||b.push(C)}};return j(a.filter(S=>!g.has(S.id))),j(t.filter(S=>S.isNew&&!g.has(S.id))),j(t.filter(S=>S.popular&&!g.has(S.id))),b},[t,a,r]),v=g=>s(`/apps/browse?goal=${g.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:[vXs(),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(Lr,{className:"absolute left-4 top-1/2 -translate-y-1/2 h-5 w-5 text-muted-foreground"}),e.jsx(xe,{value:m,onChange:g=>p(g.target.value),onKeyDown:g=>{g.key==="Enter"&&m.trim()&&s(`/apps/browse?q=${encodeURIComponent(m.trim())}`)},placeholder:"Search apps or tell us what you want to do…",className:"pl-12 h-14 text-base rounded-2xl"})]}),m.trim()&&e.jsx("div",{className:"mt-4 max-w-2xl bg-card border border-border rounded-2xl divide-y divide-border overflow-hidden",children:f.length===0?e.jsxs("p",{className:"p-4 text-sm text-muted-foreground",children:["Nothing matched “",m,"”. Try “open house”, “email my database” or “reel”."]}):f.map(g=>{const b=typeof g.icon=="string"?null:g.icon;return e.jsxs("button",{type:"button",onClick:()=>o(g),className:"w-full flex items-center gap-3 p-4 text-left hover:bg-muted/50 transition-colors",children:[e.jsx("span",{className:At("w-10 h-10 rounded-lg flex items-center justify-center text-xl flex-shrink-0",g.color),children:b?e.jsx(b,{className:"h-5 w-5"}):g.icon}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block font-medium text-foreground",children:g.name}),e.jsx("span",{className:"block text-sm text-muted-foreground truncate",children:g.description})]})]},g.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:bEe.map(g=>e.jsx(xXs,{goal:g,onSelect:v},g.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(Gr,{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(g=>{const b=i9[g.workflow_id],j=ILe(g);return e.jsxs("button",{type:"button",onClick:()=>s(`/apps/workflows/${g.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:g.run_name}),e.jsxs("p",{className:"text-sm text-muted-foreground truncate",children:[b==null?void 0:b.title," · Step ",Math.min(j.touched+1,j.total)," of ",j.total]})]}),e.jsx(La,{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:`${j.pct}%`}})})]},g.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(g=>{const b=typeof g.icon=="string"?null:g.icon;return e.jsxs("button",{type:"button",onClick:()=>o(g),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:At("w-10 h-10 rounded-lg flex items-center justify-center text-xl mb-3",g.color),children:b?e.jsx(b,{className:"h-5 w-5"}):g.icon}),e.jsx("span",{className:"block font-medium text-sm text-foreground truncate",children:g.name}),e.jsx("span",{className:"block text-xs text-muted-foreground",children:"Open again"})]},g.key)})})]})]}),y.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(un,{className:"h-4 w-4 text-primary"})," Recommended for you"]}),e.jsx("div",{className:"space-y-3",children:y.map(g=>{const b=typeof g.icon=="string"?null:g.icon;return e.jsxs("button",{type:"button",onClick:()=>o(g),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:At("w-10 h-10 rounded-lg flex items-center justify-center text-xl flex-shrink-0",g.color),children:b?e.jsx(b,{className:"h-5 w-5"}):g.icon}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block font-medium text-foreground",children:g.name}),e.jsx("span",{className:"block text-sm text-muted-foreground line-clamp-2",children:g.description})]})]},g.key)})}),e.jsx(B,{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(B,{variant:"ghost",size:"sm",onClick:()=>s("/apps/my-apps"),children:"View all"})]}),e.jsx(w7,{items:a.slice(0,6),isFavorite:i,onOpen:o,onToggleFavorite:l})]})]})}function sqt({workflow:s,activeRun:t,onStart:n,onResume:r}){const a=s.icon,i=t?ILe(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:At("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(Er,{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(B,{className:"w-full",onClick:()=>r(t),children:["Continue ",e.jsx(La,{className:"h-4 w-4 ml-1"})]})]}):e.jsx("div",{className:"mt-auto",children:e.jsxs(B,{className:"w-full",onClick:()=>n(s),children:["Start Workflow ",e.jsx(La,{className:"h-4 w-4 ml-1"})]})})]})}function nqt({workflow:s,onClose:t,onStart:n}){const[r,a]=_.useState(""),[i,l]=_.useState(!1);_.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(Ls,{open:!!s,onOpenChange:c=>!c&&t(),children:e.jsxs(Ps,{className:"sm:max-w-md",children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:s==null?void 0:s.title}),e.jsxs(_r,{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(J,{htmlFor:"workflow-run-name",children:s==null?void 0:s.namePrompt}),e.jsx(xe,{id:"workflow-run-name",value:r,onChange:c=>a(c.target.value),placeholder:s==null?void 0:s.namePlaceholder,onKeyDown:c=>{c.key==="Enter"&&o()},autoFocus:!0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This is just so you recognize it later. You can change it any time."})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:t,disabled:i,children:"Cancel"}),e.jsx(B,{onClick:o,disabled:i,children:i?"Starting…":"Start workflow"})]})]})})}function _Xs(){const s=Fn(),[t,n]=Yl(),{items:r,isFavorite:a,toggleFavorite:i,openItem:l,search:o}=hae(),{isAdmin:c}=hs(),{activeRuns:d,startRun:u}=DLe(),h=t.get("goal"),m=t.get("category")??null,[p,f]=_.useState(t.get("q")??""),[y,v]=_.useState(null);_.useEffect(()=>{f(t.get("q")??"")},[t]);const g=(E,P)=>{const M=new URLSearchParams(t);P?M.set(E,P):M.delete(E),n(M,{replace:!0})},b=()=>{const E=new URLSearchParams(t);E.delete("category"),E.delete("goal"),E.delete("q"),n(E,{replace:!0}),f("")},j=_.useMemo(()=>{let E=r;return h&&(E=E.filter(P=>P.goals.includes(h))),m&&(E=E.filter(P=>P.categories.includes(m))),p.trim()&&(E=o(p,E)),E},[r,h,m,p,o]),S=_.useMemo(()=>h||m||p.trim()?null:bEe.map(E=>({goal:E,apps:r.filter(P=>P.goals.includes(E.id))})).filter(E=>E.apps.length>0),[r,h,m,p]),C=h?bEe.find(E=>E.id===h):null;return e.jsxs("div",{className:"space-y-8",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Browse apps"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Every LevelUp app in one place, grouped by what it helps you get done."})]}),e.jsxs("div",{className:"relative max-w-2xl",children:[e.jsx(Lr,{className:"absolute left-4 top-1/2 -translate-y-1/2 h-5 w-5 text-muted-foreground"}),e.jsx(xe,{value:p,onChange:E=>{f(E.target.value),g("q",E.target.value||null)},placeholder:"Search apps or tell us what you want to do…",className:"pl-12 h-12 rounded-2xl"})]}),e.jsx("div",{className:"-mx-4 px-4 sm:mx-0 sm:px-0 overflow-x-auto scrollbar-hide",children:e.jsxs("div",{className:"inline-flex gap-2 min-w-max pb-1",children:[e.jsx("button",{type:"button",onClick:b,className:At("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"}),mXs.map(E=>e.jsx("button",{type:"button",onClick:()=>g("category",m===E.id?null:E.id),className:At("px-4 py-2 rounded-full text-sm font-medium border transition-colors whitespace-nowrap",m===E.id?"bg-primary text-primary-foreground border-primary":"bg-card text-muted-foreground border-border hover:text-foreground"),children:E.label},E.id))]})}),C&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Showing apps for"}),e.jsxs("button",{type:"button",onClick:()=>g("goal",null),className:"text-sm font-medium px-3 py-1.5 rounded-full bg-primary/10 text-primary",children:[C.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:ott.map(E=>e.jsx(sqt,{workflow:E,activeRun:d.find(P=>P.workflow_id===E.id),onStart:v,onResume:P=>s(`/apps/workflows/${P.id}`)},E.id))})]}),S?S.map(({goal:E,apps:P})=>e.jsxs("section",{children:[e.jsx("h2",{className:"text-lg font-semibold text-foreground mb-4",children:E.title}),e.jsx(w7,{items:P,isFavorite:a,onOpen:l,onToggleFavorite:i})]},E.id)):j.length>0?e.jsx(w7,{items:j,isFavorite:a,onOpen:l,onToggleFavorite:i}):e.jsxs("div",{className:"text-center py-16 bg-card border border-border rounded-2xl",children:[e.jsx(Lr,{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(nqt,{workflow:y,onClose:()=>v(null),onStart:async(E,P)=>{const M=await u(E.id,P);v(null),M&&s(`/apps/workflows/${M.id}`)}})]})}function wXs(){const s=Fn(),{favoriteItems:t,recentItems:n,connectedItems:r,isFavorite:a,toggleFavorite:i,openItem:l}=hae(),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(C0,{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(B,{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(C0,{className:"h-4 w-4 text-primary"})," Favorites"]}),e.jsx(w7,{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(Gr,{className:"h-4 w-4 text-muted-foreground"})," Recently used"]}),e.jsx(w7,{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(Uw,{className:"h-4 w-4 text-muted-foreground"})," Activated for your account"]}),e.jsx(w7,{items:r,isFavorite:a,onOpen:l,onToggleFavorite:i})]})]})}function jXs(){const{connectedItems:s,isFavorite:t,toggleFavorite:n,openItem:r}=hae();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(vd,{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(w7,{items:s,isFavorite:t,onOpen:r,onToggleFavorite:n})]})}function NXs(){const s=Fn(),{activeRuns:t,completedRuns:n,startRun:r,reopenRun:a,deleteRun:i}=DLe(),[l,o]=_.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=i9[c.workflow_id],u=ILe(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(B,{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:ott.map(c=>e.jsx(sqt,{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(Er,{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=i9[c.workflow_id])==null?void 0:d.title})]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>a(c),children:[e.jsx(Tx,{className:"h-4 w-4 mr-1"})," Reopen"]}),e.jsx(B,{variant:"ghost",size:"icon","aria-label":"Delete workflow",onClick:()=>i(c.id),children:e.jsx(Sn,{className:"h-4 w-4 text-muted-foreground"})})]},c.id)})})]}),e.jsx(nqt,{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 kXs(){const{runId:s}=Li(),t=Fn(),{runs:n,loading:r,setStep:a,renameRun:i,reopenRun:l,deleteRun:o}=DLe(),{items:c,openItem:d}=hae(),[u,h]=_.useState(!1),[m,p]=_.useState(""),f=_.useMemo(()=>n.find(j=>j.id===s),[n,s]),y=f?i9[f.workflow_id]:void 0;if(r)return e.jsx("p",{className:"text-muted-foreground",children:"Loading…"});if(!f||!y)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(B,{className:"mt-4",onClick:()=>t("/apps/workflows"),children:"Back to workflows"})]});const v=ILe(f),g=y.icon,b=j=>{if(!j)return;const S=c.find(E=>E.kind==="tool"&&E.id===j);if(S){d(S);return}const C=gyt[j];C&&t(C.path)};return e.jsxs("div",{className:"space-y-6 max-w-3xl",children:[e.jsxs("button",{type:"button",onClick:()=>t("/apps/workflows"),className:"inline-flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",children:[e.jsx(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:At("w-12 h-12 rounded-xl flex items-center justify-center flex-shrink-0",y.color),children:e.jsx(g,{className:"h-6 w-6"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[u?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xe,{value:m,onChange:j=>p(j.target.value),autoFocus:!0,onKeyDown:j=>{j.key==="Enter"&&(i(f,m),h(!1))}}),e.jsx(B,{size:"sm",onClick:()=>{i(f,m),h(!1)},children:"Save"})]}):e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h1",{className:"text-xl font-bold text-foreground truncate",children:f.run_name}),e.jsx("button",{type:"button","aria-label":"Rename workflow",onClick:()=>{p(f.run_name),h(!0)},className:"text-muted-foreground hover:text-foreground",children:e.jsx(Ya,{className:"h-4 w-4"})})]}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:[y.title," · ",y.description]})]})]}),e.jsxs("div",{className:"mt-5",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm text-muted-foreground mb-2",children:[e.jsxs("span",{children:[v.touched," of ",v.total," steps done"]}),e.jsxs("span",{children:[v.pct,"%"]})]}),e.jsx("div",{className:"h-2 rounded-full bg-muted overflow-hidden",children:e.jsx("div",{className:"h-full bg-primary transition-all",style:{width:`${v.pct}%`}})})]}),f.status==="completed"&&e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-3 rounded-xl bg-emerald-500/10 p-3",children:[e.jsxs("p",{className:"text-sm font-medium text-emerald-700 flex items-center gap-2",children:[e.jsx(Er,{className:"h-4 w-4"})," Workflow complete"]}),e.jsx(B,{variant:"outline",size:"sm",onClick:()=>l(f),children:"Reopen"})]})]}),e.jsx("ol",{className:"space-y-3",children:y.steps.map((j,S)=>{const C=f.step_state[j.key],E=j.toolId?gyt[j.toolId]:void 0,P=C==="done",M=C==="skipped";return e.jsx("li",{className:At("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:At("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(ea,{className:"h-4 w-4"}):S+1}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:At("font-medium text-foreground",(P||M)&&"line-through decoration-muted-foreground/40"),children:j.title}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:j.detail}),E&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Uses ",E.name]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mt-3",children:[E&&e.jsxs(B,{size:"sm",onClick:()=>b(j.toolId),children:["Open ",E.name," ",e.jsx(wr,{className:"h-3.5 w-3.5 ml-1"})]}),e.jsxs(B,{size:"sm",variant:P?"secondary":"outline",onClick:()=>a(f,j.key,P?null:"done"),children:[e.jsx(ea,{className:"h-3.5 w-3.5 mr-1"}),P?"Done":"Mark done"]}),e.jsxs(B,{size:"sm",variant:"ghost",onClick:()=>a(f,j.key,M?null:"skipped"),children:[e.jsx(iJ,{className:"h-3.5 w-3.5 mr-1"}),M?"Un-skip":"Skip"]})]})]})]})},j.key)})}),e.jsx("div",{className:"pt-2",children:e.jsxs(B,{variant:"ghost",size:"sm",className:"text-muted-foreground",onClick:()=>{o(f.id),t("/apps/workflows")},children:[e.jsx(Sn,{className:"h-4 w-4 mr-1"})," Delete this workflow"]})})]})}const SXs=()=>{const{isAdmin:s}=hs();return e.jsx(zs,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(hXs,{}),e.jsxs(jH,{children:[e.jsx(Qt,{index:!0,element:e.jsx(bXs,{})}),e.jsx(Qt,{path:"browse",element:e.jsx(_Xs,{})}),e.jsx(Qt,{path:"my-apps",element:e.jsx(wXs,{})}),e.jsx(Qt,{path:"connected",element:e.jsx(jXs,{})}),s&&e.jsx(Qt,{path:"workflows",element:e.jsx(NXs,{})}),s&&e.jsx(Qt,{path:"workflows/:runId",element:e.jsx(kXs,{})}),e.jsx(Qt,{path:"*",element:e.jsx(fd,{to:"/apps",replace:!0})})]})]})})},CXs=()=>{var j;const s=Fn(),{isAdmin:t}=hs(),[n,r]=_.useState(""),[a,i]=_.useState("all"),[l,o]=_.useState("all"),[c,d]=_.useState("grid"),{data:u=[]}=at({queryKey:["template-categories"],queryFn:async()=>{const{data:S,error:C}=await q.from("template_categories").select("*").order("name");if(C)throw C;return S}}),{data:h=[]}=at({queryKey:["template-types"],queryFn:async()=>{const{data:S,error:C}=await q.from("template_types").select("*").order("name");if(C)throw C;return S}}),{data:m=[],isLoading:p}=at({queryKey:["canva-templates",t],queryFn:async()=>{const{data:S,error:C}=await q.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).order("publish_date",{ascending:!1});if(C)throw C;const{data:E,error:P}=await q.from("template_links").select("*").order("sort_order");if(P)throw P;const M=async H=>{let Z=0;const ne=[];for(;;){const{data:ce,error:ie}=await H().range(Z,Z+1e3-1);if(ie)throw ie;if(!ce||ce.length===0||(ne.push(...ce),ce.length<1e3))break;Z+=1e3}return ne},I=await M(()=>q.from("template_likes").select("template_id")),D=await M(()=>q.from("template_comments").select("template_id")),O=new Map;I.forEach(H=>{O.set(H.template_id,(O.get(H.template_id)||0)+1)});const V=new Map;D.forEach(H=>{V.set(H.template_id,(V.get(H.template_id)||0)+1)});const G=new Map;return t&&(await M(()=>q.from("content_engagement_logs").select("resource_id").eq("resource_type","template").eq("action_type","view"))).forEach(Y=>{G.set(Y.resource_id,(G.get(Y.resource_id)||0)+1)}),(S||[]).map(H=>({...H,links:(E||[]).filter(Y=>Y.template_id===H.id)||[],likesCount:O.get(H.id)||0,commentsCount:V.get(H.id)||0,viewsCount:G.get(H.id)||0}))}}),f=m.filter(S=>{var M;const C=S.name.toLowerCase().includes(n.toLowerCase())||((M=S.description)==null?void 0:M.toLowerCase().includes(n.toLowerCase())),E=a==="all"||S.category_id===a,P=l==="all"||S.type_id===l;return C&&E&&P}),y=()=>{r(""),i("all"),o("all")},v=n||a!=="all"||l!=="all",g=(j=[...m].sort((S,C)=>new Date(C.publish_date||C.created_at).getTime()-new Date(S.publish_date||S.created_at).getTime())[0])==null?void 0:j.id,b=S=>{s(`/templates/${S}`)};return e.jsx(zs,{title:"Canva Templates",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"font-bold text-foreground text-5xl",children:"Canva Templates"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Browse and use our collection of professionally designed templates"})]}),!p&&m.filter(S=>S.is_featured).length>0&&e.jsxs("div",{className:"rounded-xl p-5 space-y-3",style:{backgroundColor:"#9aa8b2"},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Da,{className:"h-5 w-5 fill-foreground text-foreground"}),e.jsx("h2",{className:"text-xl font-semibold text-foreground",children:"Featured Templates"})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4",children:m.filter(S=>S.is_featured).slice(0,4).map(S=>e.jsxs(ve,{className:"group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer relative",onClick:()=>b(S.id),children:[e.jsxs("div",{className:"aspect-[3/2] relative overflow-hidden bg-muted",children:[S.id===g&&e.jsx(Oe,{className:"absolute top-2 left-2 z-10 font-bold border-0 hover:opacity-90",style:{backgroundColor:"#e8c369",color:"#3d2f0a"},children:"NEW!"}),S.preview_image_url?e.jsx("img",{src:S.preview_image_url,alt:S.name,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:"No Preview"})]}),e.jsxs(Me,{className:"p-3",children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 text-sm",children:S.name}),S.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-1",children:Hee(S.description)})]})]},S.id))})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search templates...",value:n,onChange:S=>r(S.target.value),className:"pl-9"})]}),e.jsxs(is,{value:a,onValueChange:i,children:[e.jsx(rs,{className:"w-full sm:w-48",children:e.jsx(ls,{placeholder:"All Categories"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Categories"}),u.map(S=>e.jsx(He,{value:S.id,children:S.name},S.id))]})]}),e.jsxs(is,{value:l,onValueChange:o,children:[e.jsx(rs,{className:"w-full sm:w-48",children:e.jsx(ls,{placeholder:"All Types"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Types"}),h.map(S=>e.jsx(He,{value:S.id,children:S.name},S.id))]})]}),e.jsxs("div",{className:"flex gap-2",children:[v&&e.jsx(B,{variant:"outline",size:"sm",onClick:y,children:"Clear Filters"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{variant:c==="grid"?"secondary":"outline",size:"icon",onClick:()=>d("grid"),className:"rounded-full",children:e.jsx(sf,{className:"h-4 w-4"})}),e.jsx(B,{variant:c==="list"?"secondary":"outline",size:"icon",onClick:()=>d("list"),className:"rounded-full",children:e.jsx(A0,{className:"h-4 w-4"})})]})]})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[f.length," template",f.length!==1?"s":""," found"]}),p&&e.jsx("div",{className:c==="grid"?"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6":"space-y-4",children:[...Array(8)].map((S,C)=>e.jsx(ve,{children:e.jsxs(Me,{className:"p-4",children:[e.jsx(cn,{className:"aspect-[4/3] w-full rounded-lg mb-4"}),e.jsx(cn,{className:"h-5 w-3/4 mb-2"}),e.jsx(cn,{className:"h-4 w-full mb-4"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(cn,{className:"h-5 w-16"}),e.jsx(cn,{className:"h-5 w-20"})]})]})},C))}),!p&&f.length===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx("div",{className:"text-muted-foreground mb-4",children:v?"No templates match your filters":"No templates available yet"}),v&&e.jsx(B,{variant:"outline",onClick:y,children:"Clear Filters"})]}),!p&&f.length>0&&e.jsx("div",{className:c==="grid"?"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6":"space-y-4",children:f.map(S=>e.jsxs(ve,{className:`group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer ${c==="list"?"flex flex-row":""}`,onClick:()=>b(S.id),children:[e.jsxs("div",{className:`relative overflow-hidden bg-muted ${c==="list"?"w-48 shrink-0":"aspect-[3/2]"}`,children:[S.id===g&&e.jsx(Oe,{className:"absolute top-2 left-2 z-10 font-bold border-0 hover:opacity-90",style:{backgroundColor:"#e8c369",color:"#3d2f0a"},children:"NEW!"}),S.preview_image_url?e.jsx("img",{src:S.preview_image_url,alt:S.name,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:"No Preview"}),S.links.length>1&&e.jsx("div",{className:"absolute top-2 right-2",children:e.jsxs(Oe,{variant:"secondary",className:"gap-1 bg-background/90 backdrop-blur-sm !text-secondary",children:[e.jsx(Vc,{className:"h-3 w-3"}),S.links.length]})})]}),e.jsxs(Me,{className:`p-4 flex flex-col ${c==="list"?"flex-1":""}`,children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 mb-1",children:S.name}),S.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3 flex-1",children:Hee(S.description)}),e.jsxs("div",{className:"flex flex-wrap gap-2 mb-3",children:[S.category&&e.jsx(Oe,{variant:"secondary",className:"text-xs",children:S.category.name}),S.type&&e.jsx(Oe,{variant:"outline",className:"text-xs",children:S.type.name})]}),e.jsxs("div",{className:"flex items-center gap-4 text-sm text-muted-foreground mb-3",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Fg,{className:"h-3.5 w-3.5"}),S.likesCount]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ou,{className:"h-3.5 w-3.5"}),S.commentsCount]}),t&&e.jsxs("span",{className:"flex items-center gap-1",title:"Total views (admin only)",children:[e.jsx(ya,{className:"h-3.5 w-3.5"}),S.viewsCount]})]}),e.jsxs(B,{size:"sm",className:"w-full gap-2",onClick:C=>{C.stopPropagation(),b(S.id)},children:[e.jsx(wr,{className:"h-4 w-4"}),"View Template"]})]})]},S.id))})]})})},AXs=()=>{const{templateId:s}=Li(),t=Fn(),{user:n,isAdmin:r}=hs(),{toast:a}=vi(),i=Bt(),{trackEngagement:l}=bW(),[o,c]=_.useState(""),{data:d,isLoading:u}=at({queryKey:["template-detail",s],queryFn:async()=>{const{data:S,error:C}=await q.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).eq("id",s).single();if(C)throw C;const{data:E}=await q.from("template_links").select("*").eq("template_id",s).order("sort_order"),{data:P}=await q.from("template_guides").select("*").eq("template_id",s).order("sort_order");return{...S,links:E||[],guides:P||[]}},enabled:!!s}),{data:h=[]}=at({queryKey:["template-linked-toolkits",s],queryFn:async()=>{const{data:S,error:C}=await q.from("resource_kit_templates").select("kit_id, resource_kits:kit_id(id, name, featured_image_url)").eq("template_id",s);if(C)throw C;return(S||[]).map(E=>E.resource_kits).filter(Boolean)},enabled:!!s});_.useEffect(()=>{d&&l("template",d.id,d.name,"view")},[d==null?void 0:d.id]);const{data:m=[]}=at({queryKey:["template-likes",s],queryFn:async()=>{const{data:S,error:C}=await q.from("template_likes").select("*").eq("template_id",s);if(C)throw C;return S},enabled:!!s}),{data:p=[]}=at({queryKey:["template-comments",s],queryFn:async()=>{const{data:S,error:C}=await q.from("template_comments").select("*").eq("template_id",s).order("created_at",{ascending:!1});if(C)throw C;const E=[...new Set(S.map(I=>I.user_id))],{data:P}=await q.from("profiles").select("id, name").in("id",E),M=new Map((P==null?void 0:P.map(I=>[I.id,I.name]))||[]);return S.map(I=>({...I,user_name:M.get(I.user_id)||"Unknown User"}))},enabled:!!s}),f=mt({mutationFn:async S=>{const{error:C}=await q.from("template_comments").insert({template_id:s,user_id:n.id,content:S});if(C)throw C},onSuccess:()=>{i.invalidateQueries({queryKey:["template-comments",s]}),c(""),a({title:"Comment added!"})},onError:S=>{a({title:"Error adding comment",description:S.message,variant:"destructive"})}}),y=mt({mutationFn:async S=>{const{error:C}=await q.from("template_comments").delete().eq("id",S);if(C)throw C},onSuccess:()=>{i.invalidateQueries({queryKey:["template-comments",s]}),a({title:"Comment deleted"})}}),v=mt({mutationFn:async()=>{const S=m.find(C=>C.user_id===(n==null?void 0:n.id));if(S){const{error:C}=await q.from("template_likes").delete().eq("id",S.id);if(C)throw C}else{const{error:C}=await q.from("template_likes").insert({template_id:s,user_id:n.id});if(C)throw C}},onSuccess:()=>{i.invalidateQueries({queryKey:["template-likes",s]})}}),g=m.some(S=>S.user_id===(n==null?void 0:n.id)),b=S=>S.split(" ").map(C=>C[0]).join("").toUpperCase().slice(0,2),j=S=>{S.preventDefault(),!(!o.trim()||!n)&&f.mutate(o.trim())};return u?e.jsx(zs,{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(zs,{title:d.name,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx(B,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(ir,{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(Oe,{variant:"secondary",children:d.category.name}),d.type&&e.jsx(Oe,{variant:"outline",children:d.type.name})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&e.jsx(B,{variant:"outline",className:"gap-2 rounded-full",asChild:!0,children:e.jsxs(ir,{to:`/admin/templates?edit=${d.id}`,children:[e.jsx(Ya,{className:"h-4 w-4"}),e.jsx("span",{children:"Edit"})]})}),e.jsx(jW,{resourceType:"template",resourceId:d.id,resourceTitle:d.name,size:"default",className:"rounded-full"}),e.jsxs(B,{variant:g?"default":"outline",className:"gap-2 rounded-full",onClick:()=>v.mutate(),disabled:!n||v.isPending,children:[e.jsx(Fg,{className:`h-4 w-4 ${g?"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(ve,{children:e.jsxs(Me,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Vc,{className:"h-4 w-4"}),d.links.length===1?"Template Link":"Template Links"]}),e.jsx("div",{className:"grid gap-2",children:d.links.map(S=>e.jsxs(B,{variant:"outline",className:"w-full justify-between gap-2 h-auto py-3",onClick:()=>{l("template",d.id,d.name,"click_canva"),window.open(S.canva_share_link,"_blank")},children:[e.jsx("span",{className:"font-medium",children:S.title}),e.jsx(wr,{className:"h-4 w-4 text-muted-foreground"})]},S.id))})]})}),d.video_url&&e.jsx(ve,{children:e.jsx(Me,{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(ve,{children:e.jsxs(Me,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Fr,{className:"h-4 w-4"}),"Guide Files"]}),e.jsx("div",{className:"grid gap-2",children:d.guides.map(S=>e.jsxs(B,{variant:"outline",className:"w-full justify-between gap-2 h-auto py-3",onClick:()=>{l("template",d.id,d.name,"click_pdf"),window.open(S.file_url,"_blank")},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"font-medium",children:S.name}),S.file_size&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",(S.file_size/1024).toFixed(0)," KB)"]})]}),e.jsx(li,{className:"h-4 w-4 text-muted-foreground"})]},S.id))})]})}),h.length>0&&e.jsx(ve,{children:e.jsxs(Me,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Nh,{className:"h-4 w-4"}),"Related Toolkits"]}),e.jsx("div",{className:"grid gap-2",children:h.map(S=>e.jsxs(B,{variant:"outline",className:"w-full justify-start gap-3 h-auto py-3",onClick:()=>t(`/toolbox/${S.id}`),children:[S.featured_image_url?e.jsx("img",{src:S.featured_image_url,alt:"",className:"w-10 h-10 rounded object-cover flex-shrink-0"}):e.jsx("div",{className:"w-10 h-10 rounded bg-muted flex items-center justify-center flex-shrink-0",children:e.jsx(Nh,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"font-medium",children:S.name})]},S.id))})]})}),e.jsx(wc,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(Ou,{className:"h-5 w-5"}),"Comments (",p.length,")"]}),n?e.jsxs("form",{onSubmit:j,className:"flex gap-2",children:[e.jsx(Ms,{placeholder:"Add a comment...",value:o,onChange:S=>c(S.target.value),className:"min-h-[80px] resize-none flex-1"}),e.jsx(B,{type:"submit",size:"icon",className:"h-10 w-10",disabled:!o.trim()||f.isPending,children:e.jsx(Or,{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(ve,{children:e.jsx(Me,{className:"py-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No comments yet. Be the first to share your thoughts!"})})}):p.map(S=>e.jsx(ve,{children:e.jsx(Me,{className:"pt-4 pb-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(ja,{className:"h-10 w-10 flex-shrink-0",children:e.jsx(Na,{className:"text-sm",children:b(S.user_name||"U")})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-medium",children:S.user_name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:Ed(new Date(S.created_at),{addSuffix:!0})}),S.user_id===(n==null?void 0:n.id)&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>y.mutate(S.id),children:e.jsx(Sn,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:S.content})]})]})})},S.id))})]})]})}):e.jsx(zs,{title:"Templates",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Vc,{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(B,{asChild:!0,className:"mt-4",children:e.jsx(ir,{to:"/templates",children:"Back to Templates"})})]})})},yyt=({program:s,enrolled:t})=>{const{notOpenYet:n,closed:r,opensLabel:a}=uLe(s);return e.jsxs(ve,{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(un,{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(Oe,{className:"shadow-sm",children:"Featured"}),t&&e.jsxs(Oe,{variant:"secondary",className:"shadow-sm",children:[e.jsx(Er,{className:"mr-1 h-3 w-3"})," Enrolled"]})]})]}),e.jsxs(Me,{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(Gr,{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(pc,{className:"h-3.5 w-3.5"}),"Starts ",xu(s.kickoff_at)]}),e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(In,{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":Tf(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 ",hte(s.duration_weeks)," — no subscription",s.charge_at?` · charged ${xu(s.charge_at)}`:""]}):null]}),e.jsx(B,{asChild:!0,size:"sm",children:e.jsxs(ir,{to:t?`/programs/${s.slug}/workspace`:`/programs/${s.slug}`,children:[t?"Open program":n?"Preview details":"View details",e.jsx(La,{className:"ml-1.5 h-4 w-4"})]})})]})]})]})},EXs=()=>{const{data:s=[],isLoading:t}=Ezt(),{data:n=[]}=xet(),r=new Set(n.filter(l=>DH(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(zs,{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(cn,{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(yyt,{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(ve,{className:"border-dashed",children:e.jsxs(Me,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(un,{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(yyt,{program:l,enrolled:!1},l.id))})]})]})]})})},TXs=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},MXs=({url:s,headline:t,posterUrl:n})=>{const[r,a]=_.useState(!1),i=(s||"").trim();if(!i)return null;const l=TXs(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(om,{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 RLe="Collapsible",[PXs,rqt]=af(RLe),[LXs,ltt]=PXs(RLe),aqt=_.forwardRef((s,t)=>{const{__scopeCollapsible:n,open:r,defaultOpen:a,disabled:i,onOpenChange:l,...o}=s,[c,d]=Ug({prop:r,defaultProp:a??!1,onChange:l,caller:RLe});return e.jsx(LXs,{scope:n,disabled:i,contentId:Og(),open:c,onOpenToggle:_.useCallback(()=>d(u=>!u),[d]),children:e.jsx(ii.div,{"data-state":htt(c),"data-disabled":i?"":void 0,...o,ref:t})})});aqt.displayName=RLe;var iqt="CollapsibleTrigger",ctt=_.forwardRef((s,t)=>{const{__scopeCollapsible:n,...r}=s,a=ltt(iqt,n);return e.jsx(ii.button,{type:"button","aria-controls":a.contentId,"aria-expanded":a.open||!1,"data-state":htt(a.open),"data-disabled":a.disabled?"":void 0,disabled:a.disabled,...r,ref:t,onClick:wa(s.onClick,a.onOpenToggle)})});ctt.displayName=iqt;var dtt="CollapsibleContent",utt=_.forwardRef((s,t)=>{const{forceMount:n,...r}=s,a=ltt(dtt,s.__scopeCollapsible);return e.jsx(pg,{present:n||a.open,children:({present:i})=>e.jsx(IXs,{...r,ref:t,present:i})})});utt.displayName=dtt;var IXs=_.forwardRef((s,t)=>{const{__scopeCollapsible:n,present:r,children:a,...i}=s,l=ltt(dtt,n),[o,c]=_.useState(r),d=_.useRef(null),u=Qo(t,d),h=_.useRef(0),m=h.current,p=_.useRef(0),f=p.current,y=l.open||o,v=_.useRef(y),g=_.useRef(void 0);return _.useEffect(()=>{const b=requestAnimationFrame(()=>v.current=!1);return()=>cancelAnimationFrame(b)},[]),Mx(()=>{const b=d.current;if(b){g.current=g.current||{transitionDuration:b.style.transitionDuration,animationName:b.style.animationName},b.style.transitionDuration="0s",b.style.animationName="none";const j=b.getBoundingClientRect();h.current=j.height,p.current=j.width,v.current||(b.style.transitionDuration=g.current.transitionDuration,b.style.animationName=g.current.animationName),c(r)}},[l.open,r]),e.jsx(ii.div,{"data-state":htt(l.open),"data-disabled":l.disabled?"":void 0,id:l.contentId,hidden:!y,...i,ref:u,style:{"--radix-collapsible-content-height":m?`${m}px`:void 0,"--radix-collapsible-content-width":f?`${f}px`:void 0,...s.style},children:y&&a})});function htt(s){return s?"open":"closed"}var oqt=aqt,DXs=ctt,RXs=utt,FS="Accordion",FXs=["Home","End","ArrowDown","ArrowUp","ArrowLeft","ArrowRight"],[mtt,OXs,zXs]=KG(FS),[FLe,t_r]=af(FS,[zXs,rqt]),ptt=rqt(),lqt=Dt.forwardRef((s,t)=>{const{type:n,...r}=s,a=r,i=r;return e.jsx(mtt.Provider,{scope:s.__scopeAccordion,children:n==="multiple"?e.jsx($Xs,{...i,ref:t}):e.jsx(qXs,{...a,ref:t})})});lqt.displayName=FS;var[cqt,BXs]=FLe(FS),[dqt,UXs]=FLe(FS,{collapsible:!1}),qXs=Dt.forwardRef((s,t)=>{const{value:n,defaultValue:r,onValueChange:a=()=>{},collapsible:i=!1,...l}=s,[o,c]=Ug({prop:n,defaultProp:r??"",onChange:a,caller:FS});return e.jsx(cqt,{scope:s.__scopeAccordion,value:Dt.useMemo(()=>o?[o]:[],[o]),onItemOpen:c,onItemClose:Dt.useCallback(()=>i&&c(""),[i,c]),children:e.jsx(dqt,{scope:s.__scopeAccordion,collapsible:i,children:e.jsx(uqt,{...l,ref:t})})})}),$Xs=Dt.forwardRef((s,t)=>{const{value:n,defaultValue:r,onValueChange:a=()=>{},...i}=s,[l,o]=Ug({prop:n,defaultProp:r??[],onChange:a,caller:FS}),c=Dt.useCallback(u=>o((h=[])=>[...h,u]),[o]),d=Dt.useCallback(u=>o((h=[])=>h.filter(m=>m!==u)),[o]);return e.jsx(cqt,{scope:s.__scopeAccordion,value:l,onItemOpen:c,onItemClose:d,children:e.jsx(dqt,{scope:s.__scopeAccordion,collapsible:!0,children:e.jsx(uqt,{...i,ref:t})})})}),[VXs,OLe]=FLe(FS),uqt=Dt.forwardRef((s,t)=>{const{__scopeAccordion:n,disabled:r,dir:a,orientation:i="vertical",...l}=s,o=Dt.useRef(null),c=Qo(o,t),d=OXs(n),h=DE(a)==="ltr",m=wa(s.onKeyDown,p=>{var M;if(!FXs.includes(p.key))return;const f=p.target,y=d().filter(I=>{var D;return!((D=I.ref.current)!=null&&D.disabled)}),v=y.findIndex(I=>I.ref.current===f),g=y.length;if(v===-1)return;p.preventDefault();let b=v;const j=0,S=g-1,C=()=>{b=v+1,b>S&&(b=j)},E=()=>{b=v-1,b{const{__scopeAccordion:n,value:r,...a}=s,i=OLe(_Ee,n),l=BXs(_Ee,n),o=ptt(n),c=Og(),d=r&&l.value.includes(r)||!1,u=i.disabled||s.disabled;return e.jsx(HXs,{scope:n,open:d,disabled:u,triggerId:c,children:e.jsx(oqt,{"data-orientation":i.orientation,"data-state":yqt(d),...o,...a,ref:t,disabled:u,open:d,onOpenChange:h=>{h?l.onItemOpen(r):l.onItemClose(r)}})})});hqt.displayName=_Ee;var mqt="AccordionHeader",pqt=Dt.forwardRef((s,t)=>{const{__scopeAccordion:n,...r}=s,a=OLe(FS,n),i=ftt(mqt,n);return e.jsx(ii.h3,{"data-orientation":a.orientation,"data-state":yqt(i.open),"data-disabled":i.disabled?"":void 0,...r,ref:t})});pqt.displayName=mqt;var mHe="AccordionTrigger",fqt=Dt.forwardRef((s,t)=>{const{__scopeAccordion:n,...r}=s,a=OLe(FS,n),i=ftt(mHe,n),l=UXs(mHe,n),o=ptt(n);return e.jsx(mtt.ItemSlot,{scope:n,children:e.jsx(DXs,{"aria-disabled":i.open&&!l.collapsible||void 0,"data-orientation":a.orientation,id:i.triggerId,...o,...r,ref:t})})});fqt.displayName=mHe;var xqt="AccordionContent",gqt=Dt.forwardRef((s,t)=>{const{__scopeAccordion:n,...r}=s,a=OLe(FS,n),i=ftt(xqt,n),l=ptt(n);return e.jsx(RXs,{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}})});gqt.displayName=xqt;function yqt(s){return s?"open":"closed"}var GXs=lqt,WXs=hqt,KXs=pqt,vqt=fqt,bqt=gqt;const G9=GXs,gL=_.forwardRef(({className:s,...t},n)=>e.jsx(WXs,{ref:n,className:At("border-b",s),...t}));gL.displayName="AccordionItem";const yL=_.forwardRef(({className:s,children:t,...n},r)=>e.jsx(KXs,{className:"flex",children:e.jsxs(vqt,{ref:r,className:At("flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",s),...n,children:[t,e.jsx(tl,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));yL.displayName=vqt.displayName;const vL=_.forwardRef(({className:s,children:t,...n},r)=>e.jsx(bqt,{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:At("pb-4 pt-0",s),children:t})}));vL.displayName=bqt.displayName;const YXs=({programId:s,opensLabel:t})=>{const{data:n,isLoading:r}=pUs(s),a=fUs(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($4,{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(B,{variant:i?"outline":"default",size:"sm",disabled:r||a.isPending,onClick:()=>a.mutate(!i),className:"shrink-0",children:[a.isPending?e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}):i?e.jsx(ea,{className:"mr-2 h-4 w-4"}):e.jsx($4,{className:"mr-2 h-4 w-4"}),i?"You're on the list":"Notify me"]})]})},ZXs=()=>{const{slug:s}=Li(),{data:t,isLoading:n}=fet(s),{data:r}=Tzt(t==null?void 0:t.id),{data:a}=get(t==null?void 0:t.id),i=DH(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(zs,{children:e.jsxs("div",{className:"mx-auto max-w-5xl space-y-6 p-8",children:[e.jsx(cn,{className:"h-64 w-full rounded-xl"}),e.jsx(cn,{className:"h-40 w-full rounded-xl"})]})});if(!t)return e.jsx(zs,{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(B,{asChild:!0,className:"mt-6",children:e.jsx(ir,{to:"/programs",children:"Back to Programs"})})]})});const p=typeof r=="number"&&r<=0&&!i,{notOpenYet:f,closed:y,opensLabel:v}=uLe(t),g=!i&&(p||y||f),b=i?"Open your program":f?`Enrollment opens ${xu(t.enrollment_open_at)}`:p?"Cohort is full":y?"Enrollment closed":t.payment_mode==="delayed"?"Reserve my seat":"Enroll now",j=i?`/programs/${t.slug}/workspace`:`/programs/${t.slug}/enroll`;return e.jsxs(zs,{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(MXs,{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(Oe,{variant:"secondary",children:[t.duration_weeks,"-week program"]}),typeof r=="number"&&!i&&e.jsx(Oe,{variant:r<=10?"destructive":"outline",children:r>0?`${r} of ${t.capacity} seats left`:"Full"}),i&&e.jsxs(Oe,{children:[e.jsx(Er,{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":Tf(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 ",hte(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:xu(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(_y,{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:[EVe(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:xu(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(B,{asChild:!g,size:"lg",disabled:g,children:g?e.jsx("span",{children:b}):e.jsxs(ir,{to:j,children:[b,e.jsx(La,{className:"ml-2 h-4 w-4"})]})}),e.jsx(B,{asChild:!0,variant:"ghost",size:"lg",children:e.jsx(ir,{to:"/programs",children:"All programs"})})]}),f&&!i&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"inline-flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(pc,{className:"h-3.5 w-3.5"}),"Enrollment opens ",v]}),e.jsx(YXs,{programId:t.id,opensLabel:v})]})]})]}),t.description&&e.jsxs("section",{className:"space-y-3",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"What this program is"}),e.jsx("div",{className:"whitespace-pre-line text-muted-foreground",children:t.description})]}),o.length>0&&e.jsxs("section",{className:"space-y-4",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"What you'll walk away with"}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:o.map((S,C)=>e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border border-border/60 p-4",children:[e.jsx(Er,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),e.jsx("p",{className:"text-sm",children:S})]},C))})]}),m.length>0&&e.jsxs("section",{className:"space-y-4",children:[e.jsxs("h2",{className:"text-xl font-semibold",children:["How the ",t.duration_weeks," weeks flow"]}),e.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:m.map((S,C)=>e.jsx(ve,{className:"border-border/60",children:e.jsxs(Me,{className:"space-y-2 p-5",children:[e.jsxs("p",{className:"text-xs font-semibold uppercase tracking-wider text-primary",children:["Phase ",C+1]}),e.jsx("h3",{className:"font-semibold",children:S.title}),e.jsx("p",{className:"text-sm text-muted-foreground",children:S.detail})]})},C))})]}),c.length>0&&e.jsxs("section",{className:"space-y-4",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"What's included"}),e.jsx("ul",{className:"grid gap-2 sm:grid-cols-2",children:c.map((S,C)=>e.jsxs("li",{className:"flex items-start gap-2.5 text-sm",children:[e.jsx(un,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),S]},C))})]}),(d.length>0||u.length>0)&&e.jsxs("section",{className:"grid gap-6 md:grid-cols-2",children:[d.length>0&&e.jsx(ve,{className:"border-border/60",children:e.jsxs(Me,{className:"space-y-3 p-5",children:[e.jsx("h3",{className:"font-semibold",children:"This is for you if…"}),e.jsx("ul",{className:"space-y-2 text-sm text-muted-foreground",children:d.map((S,C)=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx(Er,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),S]},C))})]})}),u.length>0&&e.jsx(ve,{className:"border-border/60",children:e.jsxs(Me,{className:"space-y-3 p-5",children:[e.jsx("h3",{className:"font-semibold",children:"This isn't for you if…"}),e.jsx("ul",{className:"space-y-2 text-sm text-muted-foreground",children:u.map((S,C)=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx(Gr,{className:"mt-0.5 h-4 w-4 shrink-0"}),S]},C))})]})})]}),h.length>0&&e.jsxs("section",{className:"space-y-4",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"Questions"}),e.jsx(G9,{type:"single",collapsible:!0,className:"rounded-xl border border-border/60 px-4",children:h.map((S,C)=>e.jsxs(gL,{value:`faq-${C}`,children:[e.jsx(yL,{className:"text-left text-sm font-medium",children:S.q}),e.jsx(vL,{className:"text-sm text-muted-foreground",children:S.a})]},C))})]}),e.jsxs("section",{className:"rounded-2xl border border-border/60 bg-muted/40 p-6 text-center md:p-10",children:[e.jsx(Kr,{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(B,{asChild:!g,size:"lg",disabled:g,children:g?e.jsx("span",{children:b}):e.jsxs(ir,{to:j,children:[b,e.jsx(La,{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(In,{className:"h-4 w-4"}),r," seats remaining"]})]}),!i&&(f?e.jsxs("p",{className:"mt-3 inline-flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(pc,{className:"h-3.5 w-3.5"}),"Enrollment opens ",v]}):t.enrollment_close_at?e.jsxs("p",{className:"mt-3 inline-flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(pc,{className:"h-3.5 w-3.5"}),"Enrollment closes ",xu(t.enrollment_close_at)]}):null)]})]})]})},Qle=["Your business","Your content","Your goals","Reserve your seat"],XXs=()=>{const{slug:s}=Li(),t=Fn(),[n,r]=Yl(),{user:a}=hs(),{data:i,isLoading:l}=fet(s),{data:o}=Tzt(i==null?void 0:i.id),{data:c,refetch:d}=get(i==null?void 0:i.id),{data:u}=Mzt(i==null?void 0:i.id),h=HBs(),m=GBs(),p=tUs(),f=sUs(),[y,v]=_.useState(0),[g,b]=_.useState(!1),[j,S]=_.useState(!1),[C,E]=_.useState(!1),[P,M]=_.useState(!1),[I,D]=_.useState(""),[O,V]=_.useState(null),G=_.useRef({}),[$,H]=_.useState({}),Y=_.useRef(!1),Z=(Ve,qe)=>{G.current={...G.current,[Ve]:qe},H(G.current)};_.useEffect(()=>{Y.current||(u?(G.current={...u},H(G.current),Y.current=!0):a&&(G.current={email:a.email,...G.current},H(G.current)))},[u,a]),_.useEffect(()=>{const Ve=c;!i||!(Ve!=null&&Ve.discount_code)||O||V({code:Ve.discount_code,discount_cents:Ve.discount_cents||0,amount_cents:Ve.amount_cents??i.price_cents,original_cents:i.price_cents})},[c,i,O]);const ne=O?O.amount_cents:(i==null?void 0:i.price_cents)??0,ce=_.useMemo(()=>mte(i),[i]),ie=Ve=>VBs(ce,Ve),te=Ve=>jgt(ce,Ve)?e.jsx("span",{className:"text-destructive",children:" *"}):null,ae=(Ve,qe)=>{const Qe={...G.current.extra||{},[Ve]:qe};Z("extra",Qe)},le=Ve=>ce.custom.filter((qe,Qe)=>Qe%3===Ve),be=Ve=>{const qe=le(Ve);if(!qe.length)return null;const Qe=$.extra||{};return e.jsx("div",{className:"space-y-4",children:qe.map(Ue=>e.jsxs("div",{className:"space-y-2",children:[Ue.type==="checkbox"?e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border border-border/60 p-4",children:[e.jsx($a,{id:Ue.id,checked:!!Qe[Ue.id],onCheckedChange:Xe=>ae(Ue.id,!!Xe)}),e.jsxs(J,{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(J,{htmlFor:Ue.id,children:[Ue.label,Ue.required&&e.jsx("span",{className:"text-destructive",children:" *"})]}),Ue.type==="long_text"?e.jsx(Ms,{id:Ue.id,rows:3,value:Qe[Ue.id]||"",onChange:Xe=>ae(Ue.id,Xe.target.value)}):Ue.type==="select"?e.jsxs(is,{value:Qe[Ue.id]||"",onValueChange:Xe=>ae(Ue.id,Xe),children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Select"})}),e.jsx(as,{children:(Ue.options||[]).map(Xe=>e.jsx(He,{value:Xe,children:Xe},Xe))})]}):e.jsx(xe,{id:Ue.id,value:Qe[Ue.id]||"",onChange:Xe=>ae(Ue.id,Xe.target.value)})]}),Ue.help&&e.jsx("p",{className:"text-xs text-muted-foreground",children:Ue.help})]},Ue.id))})},me=Ve=>{const qe=G.current,Qe=$e=>$e==null||$e===""||$e===!1,Ue=pet.find($e=>$e.step===Ve&&jgt(ce,$e.key)&&Qe($e.key==="timezone"?qe.timezone||(i==null?void 0:i.timezone):qe[$e.key]));if(Ue)return Ue.label;const Xe=qe.extra||{},nt=le(Ve).find($e=>$e.required&&Qe(Xe[$e.id]));return nt?nt.label:null},he=()=>{if(y<=2){const Ve=me(y);if(Ve)return se.error(`Please answer: ${Ve}`)}v(Ve=>Ve+1)},pe=async()=>{if(!(!i||!I.trim()))try{let Ve=c==null?void 0:c.id;(!Ve||(c==null?void 0:c.status)==="canceled")&&(Ve=await m.mutateAsync(i.id));const qe=await p.mutateAsync({enrollmentId:Ve,code:I});V(qe),D(""),await d(),se.success(`Code applied — you save ${Tf(qe.discount_cents,i.currency)}`)}catch(Ve){se.error(Ve.message||"That code could not be applied")}},Ce=async()=>{if(!(c!=null&&c.id))return V(null);try{await f.mutateAsync(c.id),V(null),await d()}catch(Ve){se.error(Ve.message||"Could not remove the code")}},Ae=n.get("setup"),Pe=n.get("session_id"),ze=_.useRef(!1);_.useEffect(()=>{Ae!=="success"||!Pe||!(c!=null&&c.id)||ze.current||(ze.current=!0,S(!0),(async()=>{const{data:Ve,error:qe}=await q.functions.invoke("program-enroll",{body:{action:"verify",enrollment_id:c.id,session_id:Pe}});if(S(!1),qe||Ve!=null&&Ve.error||(Ve==null?void 0:Ve.success)===!1){se.error((Ve==null?void 0:Ve.error)||(qe==null?void 0:qe.message)||"We could not confirm your card");return}await d(),n.delete("setup"),n.delete("session_id"),r(n,{replace:!0}),se.success("Your seat is confirmed")})())},[Ae,Pe,c==null?void 0:c.id]),_.useEffect(()=>{Ae==="cancelled"&&se.info("Checkout cancelled — your seat is held for a short while.")},[Ae]);const ke=_.useMemo(()=>c&&["reserved","scheduled_for_charge","paid","completed"].includes(c.status),[c]),Ze=async()=>{if(i){if(!C||i.payment_mode!=="free"&&!P){se.error("Please confirm the checkboxes to continue");return}b(!0);try{let Ve=c==null?void 0:c.id;(!Ve||(c==null?void 0:c.status)==="canceled")&&(Ve=await m.mutateAsync(i.id)),await h.mutateAsync({...G.current,id:void 0,program_id:i.id,enrollment_id:Ve,created_at:void 0,updated_at:void 0,user_id:void 0});const{data:qe,error:Qe}=await q.functions.invoke("program-enroll",{body:{action:"setup",enrollment_id:Ve}});if(Qe||qe!=null&&qe.error)throw new Error((qe==null?void 0:qe.error)||(Qe==null?void 0:Qe.message));if(qe!=null&&qe.free){await d(),se.success("You're in"),t(`/programs/${i.slug}/workspace`);return}qe!=null&&qe.url&&(window.location.href=qe.url)}catch(Ve){se.error(Ve.message||"Could not start enrollment")}finally{b(!1)}}};if(l)return e.jsx(zs,{children:e.jsxs("div",{className:"mx-auto max-w-2xl space-y-4 p-8",children:[e.jsx(cn,{className:"h-10 w-1/2"}),e.jsx(cn,{className:"h-64 w-full rounded-xl"})]})});if(!i)return e.jsx(zs,{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(B,{asChild:!0,className:"mt-6",children:e.jsx(ir,{to:"/programs",children:"Back to Programs"})})]})});if(DH(c)&&ke&&Ae!=="success")return e.jsx(zs,{children:e.jsxs("div",{className:"mx-auto max-w-xl space-y-4 p-12 text-center",children:[e.jsx(Er,{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 ${xu(c==null?void 0:c.charge_scheduled_at)||"the program start date"}.`}),e.jsx(B,{asChild:!0,size:"lg",children:e.jsx(ir,{to:`/programs/${i.slug}/workspace`,children:"Open your program workspace"})})]})});const Se=typeof o=="number"&&o<=0,{notOpenYet:Fe,closed:Ne,opensLabel:Ye}=uLe(i);return Fe||Ne?e.jsx(zs,{children:e.jsxs("div",{className:"mx-auto w-full max-w-xl space-y-4 p-8 text-center",children:[e.jsx("h1",{className:"text-2xl font-bold",children:Fe?"Enrollment is not open yet":"Enrollment is closed"}),e.jsx("p",{className:"text-muted-foreground",children:Fe?`Enrollment for ${i.name} opens ${Ye}. Come back then to reserve your seat.`:`Enrollment for ${i.name} has closed. Watch the Hub for the next cohort.`}),e.jsx(B,{asChild:!0,children:e.jsx(ir,{to:`/programs/${i.slug}`,children:"Back to program details"})})]})}):e.jsx(zs,{children:e.jsxs("div",{className:"mx-auto w-full max-w-3xl space-y-6 p-4 md:p-8",children:[e.jsx(B,{asChild:!0,variant:"ghost",size:"sm",className:"-ml-2",children:e.jsxs(ir,{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?`${EVe(i.price_cents,i.currency,i.duration_weeks)}. Your card is saved today and charged once on ${xu(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:Qle[y]}),e.jsxs("span",{children:["Step ",y+1," of ",Qle.length]})]}),e.jsx(Fi,{value:(y+1)/Qle.length*100})]}),j&&e.jsx(ve,{className:"border-primary/40 bg-primary/5",children:e.jsxs(Me,{className:"flex items-center gap-3 p-4 text-sm",children:[e.jsx(Ct,{className:"h-4 w-4 animate-spin text-primary"}),"Confirming your card with Stripe…"]})}),e.jsx(ve,{children:e.jsxs(Me,{className:"space-y-5 p-6",children:[y===0&&ce.intro&&e.jsx("p",{className:"rounded-lg border border-border/60 bg-muted/30 p-4 text-sm text-muted-foreground",children:ce.intro}),y===0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[ie("full_name")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(J,{htmlFor:"full_name",children:["Full name",te("full_name")]}),e.jsx(xe,{id:"full_name",value:$.full_name||"",onChange:Ve=>Z("full_name",Ve.target.value)})]}),ie("phone")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(J,{htmlFor:"phone",children:["Mobile number",te("phone")]}),e.jsx(xe,{id:"phone",value:$.phone||"",onChange:Ve=>Z("phone",Ve.target.value)})]}),ie("instagram_handle")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(J,{htmlFor:"instagram_handle",children:["Instagram handle",te("instagram_handle")]}),e.jsx(xe,{id:"instagram_handle",placeholder:"@yourhandle",value:$.instagram_handle||"",onChange:Ve=>Z("instagram_handle",Ve.target.value)})]}),ie("city")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(J,{htmlFor:"city",children:["Primary city / market",te("city")]}),e.jsx(xe,{id:"city",value:$.city||"",onChange:Ve=>Z("city",Ve.target.value)})]})]}),ie("service_areas")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(J,{htmlFor:"service_areas",children:["Neighborhoods or areas you serve",te("service_areas")]}),e.jsx(Ms,{id:"service_areas",rows:2,value:$.service_areas||"",onChange:Ve=>Z("service_areas",Ve.target.value)})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[ie("years_experience")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(J,{children:["Years in real estate",te("years_experience")]}),e.jsxs(is,{value:$.years_experience||"",onValueChange:Ve=>Z("years_experience",Ve),children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Select"})}),e.jsx(as,{children:["Less than 1","1-3","4-7","8-15","15+"].map(Ve=>e.jsx(He,{value:Ve,children:Ve},Ve))})]})]}),ie("specialty")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(J,{htmlFor:"specialty",children:["Specialty or niche",te("specialty")]}),e.jsx(xe,{id:"specialty",value:$.specialty||"",onChange:Ve=>Z("specialty",Ve.target.value)})]})]}),be(0)]}),y===1&&e.jsxs(e.Fragment,{children:[ie("target_audience")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(J,{htmlFor:"target_audience",children:["Who are you trying to reach?",te("target_audience")]}),e.jsx(Ms,{id:"target_audience",rows:2,placeholder:"First-time buyers, move-up sellers, investors…",value:$.target_audience||"",onChange:Ve=>Z("target_audience",Ve.target.value)})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[ie("video_comfort")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(J,{children:["How comfortable are you on camera?",te("video_comfort")]}),e.jsxs(is,{value:$.video_comfort||"",onValueChange:Ve=>Z("video_comfort",Ve),children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Select"})}),e.jsx(as,{children:["Terrified","Nervous but willing","Getting comfortable","Very comfortable"].map(Ve=>e.jsx(He,{value:Ve,children:Ve},Ve))})]})]}),ie("posting_frequency")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(J,{children:["How often do you post today?",te("posting_frequency")]}),e.jsxs(is,{value:$.posting_frequency||"",onValueChange:Ve=>Z("posting_frequency",Ve),children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Select"})}),e.jsx(as,{children:["Never","Rarely","Weekly","A few times a week","Daily"].map(Ve=>e.jsx(He,{value:Ve,children:Ve},Ve))})]})]})]}),ie("content_style")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(J,{htmlFor:"content_style",children:["What content style feels like you?",te("content_style")]}),e.jsx(Ms,{id:"content_style",rows:2,placeholder:"Educational, funny, behind-the-scenes, luxury-polished…",value:$.content_style||"",onChange:Ve=>Z("content_style",Ve.target.value)})]}),ie("personal_interests")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(J,{htmlFor:"personal_interests",children:["Interests or hobbies we can weave in",te("personal_interests")]}),e.jsx(Ms,{id:"personal_interests",rows:2,value:$.personal_interests||"",onChange:Ve=>Z("personal_interests",Ve.target.value)})]}),be(1)]}),y===2&&e.jsxs(e.Fragment,{children:[ie("primary_goal")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(J,{htmlFor:"primary_goal",children:["Your #1 goal for this program",te("primary_goal")]}),e.jsx(Ms,{id:"primary_goal",rows:3,value:$.primary_goal||"",onChange:Ve=>Z("primary_goal",Ve.target.value)})]}),ie("topics_to_avoid")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(J,{htmlFor:"topics_to_avoid",children:["Anything you don't want to talk about",te("topics_to_avoid")]}),e.jsx(Ms,{id:"topics_to_avoid",rows:2,value:$.topics_to_avoid||"",onChange:Ve=>Z("topics_to_avoid",Ve.target.value)})]}),ie("timezone")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(J,{children:["Your time zone",te("timezone")]}),e.jsxs(is,{value:$.timezone||i.timezone,onValueChange:Ve=>Z("timezone",Ve),children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Select"})}),e.jsx(as,{children:["America/New_York","America/Chicago","America/Denver","America/Phoenix","America/Los_Angeles","Pacific/Honolulu"].map(Ve=>e.jsx(He,{value:Ve,children:Ve.replace("America/","").replace("_"," ")},Ve))})]})]}),be(2),ie("consent_public_profile")&&e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border border-border/60 p-4",children:[e.jsx($a,{id:"consent_public_profile",checked:!!$.consent_public_profile,onCheckedChange:Ve=>Z("consent_public_profile",!!Ve)}),e.jsx(J,{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."})]})]}),y===3&&e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"rounded-lg border border-border/60 p-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:i.name}),e.jsx("span",{className:"font-semibold",children:i.payment_mode==="free"?"Included":O?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-normal text-muted-foreground line-through",children:Tf(O.original_cents,i.currency)}),Tf(ne,i.currency)]}):Tf(i.price_cents,i.currency)})]}),i.payment_mode!=="free"&&e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:EVe(ne,i.currency,i.duration_weeks)}),i.payment_mode!=="free"&&e.jsx("div",{className:"mt-3 border-t border-border/60 pt-3",children:O?e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 rounded-md bg-primary/5 px-3 py-2 text-sm",children:[e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(Ep,{className:"h-3.5 w-3.5 text-primary"}),"Code ",e.jsx("span",{className:"font-mono font-semibold",children:O.code})," applied — you save ",Tf(O.discount_cents,i.currency)]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:Ce,disabled:f.isPending,children:[e.jsx(Qn,{className:"mr-1 h-3.5 w-3.5"})," Remove"]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"discount_code",className:"text-xs text-muted-foreground",children:"Have a discount code?"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{id:"discount_code",placeholder:"Enter code",className:"font-mono uppercase",value:I,onChange:Ve=>D(Ve.target.value.toUpperCase()),onKeyDown:Ve=>{Ve.key==="Enter"&&(Ve.preventDefault(),pe())}}),e.jsx(B,{variant:"outline",onClick:pe,disabled:!I.trim()||p.isPending||m.isPending,children:p.isPending||m.isPending?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):"Apply"})]})]})}),i.payment_mode==="delayed"&&e.jsxs("div",{className:"mt-3 flex items-start gap-2.5 border-t border-border/60 pt-3 text-sm",children:[e.jsx(_y,{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:xu(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($a,{id:"terms",checked:C,onCheckedChange:Ve=>E(!!Ve)}),e.jsx(J,{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($a,{id:"charge",checked:P,onCheckedChange:Ve=>M(!!Ve)}),e.jsx(J,{htmlFor:"charge",className:"text-sm font-normal leading-relaxed",children:i.payment_mode==="delayed"?`I authorize LevelUp to charge my saved card one time — ${Tf(ne,i.currency)} for the ${hte(i.duration_weeks)} — on ${xu(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 — ${Tf(ne,i.currency)} for the ${hte(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(Dm,{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(B,{variant:"ghost",onClick:()=>v(Ve=>Math.max(0,Ve-1)),disabled:y===0||g,children:[e.jsx(ka,{className:"mr-1.5 h-4 w-4"})," Back"]}),yString(s).padStart(2,"0"),U7e=s=>s.toISOString().replace(/[-:]/g,"").split(".")[0]+"Z",QXs=({program:s,intakeComplete:t})=>{const n=s!=null&&s.kickoff_at?new Date(s.kickoff_at).getTime():null,[r,a]=_.useState(()=>Date.now());_.useEffect(()=>{const d=setInterval(()=>a(Date.now()),1e3);return()=>clearInterval(d)},[]);const i=_.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:${U7e(new Date)}`,`DTSTART:${U7e(d)}`,`DTEND:${U7e(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:B7e(i.hours)},{label:"Minutes",value:B7e(i.minutes)},{label:"Seconds",value:B7e(i.seconds)}];return e.jsxs(ve,{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(Me,{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(Oe,{className:"gap-1.5",children:[e.jsx(un,{className:"h-3.5 w-3.5"})," Your seat is confirmed"]}),e.jsxs(Oe,{variant:"outline",className:"gap-1.5",children:[e.jsx(Gr,{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(B,{onClick:o,size:"lg",children:[e.jsx(gy,{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(Er,{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))})]})]})},q7e=s=>s.toISOString().replace(/[-:]/g,"").split(".")[0]+"Z",JXs=(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:${q7e(new Date)}`,`DTSTART:${q7e(n)}`,`DTEND:${q7e(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)},eQs={pdf:Fr,document:uS,checklist:Ny,template_link:pj,video:dm,external:vd},tQs=()=>{var le;const{slug:s}=Li(),[t]=Yl(),{isAdmin:n}=hs(),r=n?t.get("as"):null,a=t.get("name")||"this member",i=n&&(t.get("preview")==="1"||!!r),{data:l,isLoading:o}=fet(s),{data:c}=get(l==null?void 0:l.id),{data:d,isLoading:u}=WBs(l==null?void 0:l.id,r),h=KBs(l==null?void 0:l.id),m=YBs(l==null?void 0:l.id),p=ZBs(l==null?void 0:l.id),f=XBs(l==null?void 0:l.id),{data:y}=Mzt(l==null?void 0:l.id),v=!!(l!=null&&l.kickoff_at)&&new Date(l.kickoff_at).getTime()>Date.now(),[g,b]=_.useState(!1),[j,S]=_.useState({title:"",instagram_url:""}),[C,E]=_.useState({}),[P,M]=_.useState(null),I=_.useMemo(()=>{if(!(l!=null&&l.kickoff_at))return 1;const be=Math.floor((Date.now()-new Date(l.kickoff_at).getTime())/864e5);return Math.min(Math.max(Math.floor(be/7)+1,1),l.duration_weeks)},[l]),D=new Set(((d==null?void 0:d.completions)||[]).map(be=>be.lesson_id)),O=(d==null?void 0:d.lessons)||[],V=O.length?Math.round(D.size/O.length*100):0,G=((d==null?void 0:d.videoLogs)||[]).filter(be=>be.week_number===I).length,$=((d==null?void 0:d.videoLogs)||[]).length,H=(l==null?void 0:l.weekly_video_goal)||3,Y=_.useMemo(()=>{const be=new Map;((d==null?void 0:d.videoLogs)||[]).forEach(he=>be.set(he.week_number,(be.get(he.week_number)||0)+1));let me=0;for(let he=I;he>=1;he--)if((be.get(he)||0)>=H)me++;else if(he!==I)break;return me},[d==null?void 0:d.videoLogs,I,H]);if(o||u)return e.jsx(zs,{children:e.jsxs("div",{className:"mx-auto max-w-6xl space-y-6 p-8",children:[e.jsx(cn,{className:"h-28 w-full rounded-xl"}),e.jsx(cn,{className:"h-64 w-full rounded-xl"})]})});if(!l)return e.jsx(zs,{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(B,{asChild:!0,className:"mt-6",children:e.jsx(ir,{to:"/programs",children:"Back to Programs"})})]})});if(!DH(c)&&!i)return e.jsx(zs,{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(B,{asChild:!0,size:"lg",children:e.jsx(ir,{to:`/programs/${l.slug}`,children:"View the program"})})]})});const Z=((d==null?void 0:d.events)||[]).filter(be=>new Date(be.starts_at)>=new Date),ne=((d==null?void 0:d.events)||[]).filter(be=>new Date(be.starts_at)be.is_pinned),te=[...(d==null?void 0:d.myResources)||[],...(d==null?void 0:d.resources)||[]].reduce((be,me)=>{const he=me.user_id?`Just for you · ${me.category}`:me.category;return(be[he]||(be[he]=[])).push(me),be},{}),ae=((d==null?void 0:d.progress)||[]).find(be=>be.week_number===I)||{};return e.jsx(zs,{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||!DH(c))&&e.jsx(ve,{className:"border-primary/40 bg-primary/5",children:e.jsxs(Me,{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(B,{variant:"outline",size:"sm",asChild:!0,children:e.jsx(ir,{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(Oe,{variant:"secondary",children:["Week ",I," of ",l.duration_weeks]}),(c==null?void 0:c.status)==="scheduled_for_charge"&&c.charge_scheduled_at&&e.jsxs(Oe,{variant:"outline",children:["Billing ",xu(c.charge_scheduled_at)]}),(c==null?void 0:c.status)==="payment_failed"&&e.jsx(Oe,{variant:"destructive",children:"Payment issue"})]}),e.jsx("p",{className:"neon-eyebrow font-semibold",children:"LevelUp Program"}),e.jsx("h1",{className:"neon-title w-fit text-4xl font-black uppercase tracking-tight md:text-5xl",children:l.name}),l.subtitle&&e.jsx("p",{className:"text-muted-foreground",children:l.subtitle})]}),v&&e.jsx(QXs,{program:l,intakeComplete:!!y}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsx(ve,{className:"neon-topline",children:e.jsxs(Me,{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(ku,{className:"h-3.5 w-3.5 text-primary"})," This week"]}),e.jsxs("p",{className:"neon-stat text-3xl font-black",children:[G,e.jsxs("span",{className:"text-base font-normal text-muted-foreground",children:[" / ",H]})]}),e.jsx(Fi,{value:Math.min(G/H*100,100),className:"h-1.5"})]})}),e.jsx(ve,{className:"neon-topline",children:e.jsxs(Me,{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(dm,{className:"h-3.5 w-3.5 text-primary"})," Videos posted"]}),e.jsx("p",{className:"neon-stat text-3xl font-black",children:$}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"since kickoff"})]})}),e.jsx(ve,{className:"neon-topline",children:e.jsxs(Me,{className:"space-y-1.5 p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs uppercase tracking-[0.16em] text-muted-foreground",children:[e.jsx(gu,{className:"h-3.5 w-3.5 text-primary"})," Streak"]}),e.jsxs("p",{className:"neon-stat text-3xl font-black",children:[Y," wk"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"hitting your goal"})]})}),e.jsx(ve,{className:"neon-topline",children:e.jsxs(Me,{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(Nl,{className:"h-3.5 w-3.5 text-primary"})," Curriculum"]}),e.jsxs("p",{className:"neon-stat text-3xl font-black",children:[V,"%"]}),e.jsx(Fi,{value:V,className:"h-1.5"})]})})]}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[e.jsxs(Ls,{open:g,onOpenChange:b,children:[e.jsx(nl,{asChild:!0,children:e.jsxs(B,{children:[e.jsx(rn,{className:"mr-1.5 h-4 w-4"})," Log a video"]})}),e.jsxs(Ps,{children:[e.jsx(Os,{children:e.jsx(Ds,{children:"Log a posted video"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"v-title",children:"What was it about?"}),e.jsx(xe,{id:"v-title",value:j.title,onChange:be=>S(me=>({...me,title:be.target.value}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"v-url",children:"Instagram link (optional)"}),e.jsx(xe,{id:"v-url",placeholder:"https://instagram.com/reel/…",value:j.instagram_url,onChange:be=>S(me=>({...me,instagram_url:be.target.value}))})]})]}),e.jsx(yr,{children:e.jsx(B,{onClick:async()=>{await m.mutateAsync({week_number:I,...j}),S({title:"",instagram_url:""}),b(!1)},children:"Log video"})})]})]}),((le=Z[0])==null?void 0:le.meeting_link)&&e.jsx(B,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:Z[0].meeting_link,target:"_blank",rel:"noreferrer",children:[e.jsx(om,{className:"mr-1.5 h-4 w-4"})," Join next session"]})})]}),ce.length>0&&e.jsx(ve,{className:"border-primary/30 bg-primary/5",children:e.jsx(Me,{className:"space-y-3 p-5",children:ce.map(be=>e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(wh,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:be.title}),be.body&&e.jsx("p",{className:"text-sm text-muted-foreground",children:be.body})]})]},be.id))})}),e.jsxs(Yr,{defaultValue:"roadmap",children:[e.jsxs(Zr,{className:"flex w-full flex-wrap justify-start",children:[e.jsx(Ht,{value:"roadmap",children:"Roadmap"}),e.jsx(Ht,{value:"lessons",children:"Lessons"}),e.jsx(Ht,{value:"checkin",children:"Weekly check-in"}),e.jsx(Ht,{value:"events",children:"Sessions"}),e.jsx(Ht,{value:"resources",children:"Resources"}),e.jsx(Ht,{value:"profile",children:"Profile review"})]}),e.jsxs(Gt,{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(be=>{const me=be.release_at&&new Date(be.release_at)>new Date;return e.jsx(ve,{className:me?"opacity-60":be.week_number===I?"border-primary/50":"",children:e.jsxs(Me,{className:"space-y-2 p-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(Oe,{variant:"outline",children:["Week ",be.week_number]}),e.jsx("span",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:be.phase}),be.week_number===I&&e.jsx(Oe,{children:"Current"}),me&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(Gr,{className:"h-3 w-3"})," Unlocks ",xu(be.release_at)]})]}),e.jsx("h3",{className:"font-semibold",children:be.title}),be.learning_goal&&e.jsx("p",{className:"text-sm text-muted-foreground",children:be.learning_goal}),!me&&Array.isArray(be.tasks)&&be.tasks.length>0&&e.jsx("ul",{className:"mt-2 space-y-1.5",children:be.tasks.map((he,pe)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(Er,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-primary"}),typeof he=="string"?he:he.label]},pe))})]})},be.id)})]}),e.jsxs(Gt,{value:"lessons",className:"mt-6 space-y-3",children:[O.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Lessons unlock as the program progresses."}),O.map(be=>{const me=Pzt(be.video_url),he=P===be.id;return e.jsx(ve,{children:e.jsxs(Me,{className:"space-y-4 p-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[e.jsx($a,{checked:D.has(be.id),onCheckedChange:pe=>h.mutate({lessonId:be.id,done:!!pe}),"aria-label":`Mark ${be.title} complete`}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-medium",children:be.title}),be.summary&&e.jsx("p",{className:"text-sm text-muted-foreground",children:be.summary}),be.action_assignment&&e.jsxs("p",{className:"mt-1 text-xs text-primary",children:["Action: ",be.action_assignment]})]}),be.duration_minutes&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(Gr,{className:"h-3 w-3"})," ",be.duration_minutes," min"]}),e.jsxs("div",{className:"flex gap-2",children:[be.video_url&&(me||EJ(be.video_url))&&e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>M(he?null:be.id),children:[e.jsx(om,{className:"mr-1.5 h-3.5 w-3.5"})," ",he?"Close":"Watch"]}),be.video_url&&!me&&!EJ(be.video_url)&&e.jsx(B,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:be.video_url,target:"_blank",rel:"noreferrer",children:[e.jsx(om,{className:"mr-1.5 h-3.5 w-3.5"})," Watch"]})}),be.worksheet_url&&e.jsx(B,{size:"sm",variant:"ghost",asChild:!0,children:e.jsxs("a",{href:be.worksheet_url,target:"_blank",rel:"noreferrer",children:[e.jsx(li,{className:"mr-1.5 h-3.5 w-3.5"})," Worksheet"]})})]})]}),he&&me&&e.jsx("div",{className:"overflow-hidden rounded-lg border border-border/60",children:e.jsx("iframe",{src:me,title:be.title,className:"aspect-video w-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; picture-in-picture",allowFullScreen:!0})}),he&&!me&&EJ(be.video_url)&&e.jsx("div",{className:"overflow-hidden rounded-lg border border-border/60 bg-black",children:e.jsx("video",{src:be.video_url,controls:!0,autoPlay:!0,className:"aspect-video w-full"})})]})},be.id)})]}),e.jsx(Gt,{value:"checkin",className:"mt-6",children:e.jsx(ve,{children:e.jsxs(Me,{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(([be,me])=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:be,children:me}),e.jsx(xe,{id:be,type:"number",min:0,defaultValue:ae[be]??"",onChange:he=>E(pe=>({...pe,[be]:Number(he.target.value)}))})]},be))}),[["biggest_win","Biggest win"],["biggest_challenge","Biggest challenge"],["what_to_improve","What you’ll change next week"]].map(([be,me])=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:be,children:me}),e.jsx(Ms,{id:be,rows:2,defaultValue:ae[be]??"",onChange:he=>E(pe=>({...pe,[be]:he.target.value}))})]},be)),e.jsx(B,{onClick:()=>p.mutate({week_number:I,goal_videos:H,...C}),children:"Save check-in"})]})})}),e.jsxs(Gt,{value:"events",className:"mt-6 space-y-4",children:[Z.length===0&&ne.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Sessions will be scheduled before kickoff."}),Z.map(be=>e.jsx(ve,{className:"border-primary/30",children:e.jsxs(Me,{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(Oe,{variant:"secondary",className:"capitalize",children:String(be.event_kind).replace("_"," ")}),e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(pc,{className:"h-3 w-3"})," ",xu(be.starts_at,!0)]})]}),e.jsx("p",{className:"mt-1.5 font-medium",children:be.title}),be.speaker&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:["with ",be.speaker]}),be.description&&e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:be.description})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(B,{size:"sm",variant:"outline",onClick:()=>f.mutate({eventId:be.id,optIn:!0}),children:"Remind me"}),e.jsxs(B,{size:"sm",variant:"ghost",onClick:()=>JXs(be,l.name),children:[e.jsx(pc,{className:"mr-1.5 h-3.5 w-3.5"})," Add to calendar"]}),be.meeting_link&&e.jsx(B,{size:"sm",asChild:!0,children:e.jsxs("a",{href:be.meeting_link,target:"_blank",rel:"noreferrer",children:["Join ",e.jsx(wr,{className:"ml-1.5 h-3.5 w-3.5"})]})})]})]})},be.id)),ne.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"}),ne.map(be=>e.jsx(ve,{children:e.jsxs(Me,{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:be.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:xu(be.starts_at,!0)})]}),be.replay_url?e.jsx(B,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:be.replay_url,target:"_blank",rel:"noreferrer",children:[e.jsx(om,{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"})]})},be.id))]})]}),e.jsxs(Gt,{value:"resources",className:"mt-6 space-y-8",children:[Object.keys(te).length===0&&e.jsx(ve,{className:"border-dashed",children:e.jsxs(Me,{className:"flex flex-col items-center gap-2 p-12 text-center",children:[e.jsx(Fr,{className:"h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"font-medium",children:"Your resource library is being built"}),e.jsx("p",{className:"max-w-md text-sm text-muted-foreground",children:"Worksheets, scripts and swipe files will appear here as the program unlocks."})]})}),Object.entries(te).map(([be,me])=>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:be}),e.jsx("span",{className:"h-px flex-1 bg-border"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[me.length," item",me.length===1?"":"s"]})]}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2 xl:grid-cols-3",children:me.map(he=>{const pe=oae(he),Ce=eQs[he.resource_kind]||Fr;return e.jsxs("div",{role:"button",tabIndex:0,onClick:()=>pe&&TJ(he),onKeyDown:Ae=>{pe&&(Ae.key==="Enter"||Ae.key===" ")&&(Ae.preventDefault(),TJ(he))},className:"group relative flex cursor-pointer flex-col gap-3 overflow-hidden rounded-2xl border border-border/60 bg-card p-5 transition-all hover:-translate-y-0.5 hover:border-primary/50 hover:shadow-lg",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsx("div",{className:"flex h-11 w-11 items-center justify-center rounded-xl bg-primary/10 text-primary",children:e.jsx(Ce,{className:"h-5 w-5"})}),e.jsx(Oe,{variant:"secondary",className:"capitalize",children:String(he.resource_kind).replace("_"," ")})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"font-semibold leading-snug",children:he.title}),he.description&&e.jsx("p",{className:"line-clamp-3 text-sm text-muted-foreground",children:he.description})]}),e.jsxs("div",{className:"mt-auto flex items-center gap-4",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-sm font-medium text-primary",children:[e.jsx(wr,{className:"h-3.5 w-3.5"})," Open"]}),he.file_path&&e.jsxs("button",{type:"button",onClick:Ae=>{Ae.stopPropagation(),TJ(he,"download")},className:"inline-flex items-center gap-1.5 text-sm font-medium text-muted-foreground hover:text-primary",children:[e.jsx(li,{className:"h-3.5 w-3.5"})," Download"]})]})]},he.id)})})]},be))]}),e.jsx(Gt,{value:"profile",className:"mt-6",children:e.jsx(ve,{children:e.jsxs(Me,{className:"space-y-4 p-6",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Im,{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(([be,me])=>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:be.replace(/_/g," ")}),e.jsxs("span",{className:"font-semibold",children:[me,"/10"]})]}),e.jsx(Fi,{value:Number(me)*10,className:"h-1.5"})]},be))}),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((be,me)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(Hh,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-primary"}),typeof be=="string"?be:be.label]},me))})]}),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(B,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:d.analysis.report_url,target:"_blank",rel:"noreferrer",children:[e.jsx(li,{className:"mr-1.5 h-4 w-4"})," Download full report"]})})]})]})})})]})]})})})},Ga=_.forwardRef(({className:s,...t},n)=>e.jsx("div",{className:"relative w-full overflow-auto",children:e.jsx("table",{ref:n,className:At("w-full caption-bottom text-sm",s),...t})}));Ga.displayName="Table";const Wa=_.forwardRef(({className:s,...t},n)=>e.jsx("thead",{ref:n,className:At("[&_tr]:border-b",s),...t}));Wa.displayName="TableHeader";const Ka=_.forwardRef(({className:s,...t},n)=>e.jsx("tbody",{ref:n,className:At("[&_tr:last-child]:border-0",s),...t}));Ka.displayName="TableBody";const sQs=_.forwardRef(({className:s,...t},n)=>e.jsx("tfoot",{ref:n,className:At("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",s),...t}));sQs.displayName="TableFooter";const pn=_.forwardRef(({className:s,...t},n)=>e.jsx("tr",{ref:n,className:At("border-b transition-colors data-[state=selected]:bg-muted hover:bg-muted/50",s),...t}));pn.displayName="TableRow";const Pt=_.forwardRef(({className:s,...t},n)=>e.jsx("th",{ref:n,className:At("h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",s),...t}));Pt.displayName="TableHead";const gt=_.forwardRef(({className:s,...t},n)=>e.jsx("td",{ref:n,className:At("p-4 align-middle [&:has([role=checkbox])]:pr-0",s),...t}));gt.displayName="TableCell";const nQs=_.forwardRef(({className:s,...t},n)=>e.jsx("caption",{ref:n,className:At("mt-4 text-sm text-muted-foreground",s),...t}));nQs.displayName="TableCaption";const Jle=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())}`},ece=s=>s?new Date(s).toISOString():null,$7e=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:Jle(s.enrollment_open_at),enrollment_close_at:Jle(s.enrollment_close_at),kickoff_at:Jle(s.kickoff_at),charge_at:Jle(s.charge_at),status:s.status||"draft",is_public:!!s.is_public,is_featured:!!s.is_featured,sort_order:s.sort_order??0}),rQs=({program:s,onSaved:t})=>{const[n,r]=_.useState(()=>$7e(s)),[a,i]=_.useState(!1),[l,o]=_.useState(!1),[c,d]=_.useState(null),u=_.useRef(null),h=_.useRef(null);_.useEffect(()=>{r($7e(s)),i(!1)},[s.id,s.updated_at]);const m=(v,g)=>{r(b=>({...b,[v]:g})),i(!0)},p=async(v,g)=>{if(!v.type.startsWith("image/")){se.error("Please choose an image file");return}if(v.size>8*1024*1024){se.error("Image must be under 8MB");return}d(g);try{const b=v.name.split(".").pop()||"jpg",j=`programs/${s.id}/${g}-${Date.now()}.${b}`,{error:S}=await q.storage.from("event-images").upload(j,v,{cacheControl:"31536000",upsert:!0});if(S)throw S;const{data:C}=q.storage.from("event-images").getPublicUrl(j);m(g==="cover"?"cover_image_url":"hero_image_url",C.publicUrl),se.success(`${g==="cover"?"Cover":"Hero"} image uploaded — remember to save`)}catch(b){se.error(b.message||"Upload failed")}finally{d(null)}},f=async()=>{if(!n.name.trim())return se.error("Program name is required");if(!n.slug.trim())return se.error("Slug is required");o(!0);try{const v={name:n.name.trim(),slug:n.slug.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""),subtitle:n.subtitle||null,tagline:n.tagline||null,short_description:n.short_description||null,description:n.description||null,price_cents:Math.max(0,Math.round(n.price_cents)),currency:n.currency||"usd",capacity:Math.max(0,Math.round(n.capacity)),duration_weeks:Math.max(1,Math.round(n.duration_weeks)),weekly_video_goal:Math.max(0,Math.round(n.weekly_video_goal)),payment_mode:n.payment_mode,payment_grace_days:Math.max(0,Math.round(n.payment_grace_days)),timezone:n.timezone||"America/New_York",accent_color:n.accent_color||null,cover_image_url:n.cover_image_url||null,hero_image_url:n.hero_image_url||null,promo_video_url:n.promo_video_url.trim()||null,promo_video_headline:n.promo_video_headline.trim()||null,enrollment_open_at:ece(n.enrollment_open_at),enrollment_close_at:ece(n.enrollment_close_at),kickoff_at:ece(n.kickoff_at),charge_at:ece(n.charge_at),status:n.status,is_public:n.is_public,is_featured:n.is_featured,sort_order:Math.round(n.sort_order)},{error:g}=await q.from("programs").update(v).eq("id",s.id);if(g)throw g;se.success("Program saved"),i(!1),t()}catch(v){se.error(v.message||"Could not save the program")}finally{o(!1)}},y=({kind:v,label:g,hint:b})=>{const j=v==="cover"?n.cover_image_url:n.hero_image_url,S=v==="cover"?u:h;return e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:g}),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:j?e.jsxs(e.Fragment,{children:[e.jsx("img",{src:j,alt:`${g} preview`,className:"h-full w-full object-cover"}),e.jsx("button",{type:"button",onClick:()=>m(v==="cover"?"cover_image_url":"hero_image_url",""),className:"absolute right-1.5 top-1.5 rounded-full bg-background/90 p-1 text-foreground shadow","aria-label":`Remove ${g}`,children:e.jsx(Qn,{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(jy,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"No image"})]})}),e.jsxs("div",{className:"min-w-[220px] flex-1 space-y-2",children:[e.jsx("input",{ref:S,type:"file",accept:"image/*",className:"hidden",onChange:C=>{var P;const E=(P=C.target.files)==null?void 0:P[0];E&&p(E,v),C.target.value=""}}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:()=>{var C;return(C=S.current)==null?void 0:C.click()},disabled:c===v,children:[c===v?e.jsx(Ct,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(Oa,{className:"mr-1.5 h-4 w-4"}),"Upload image"]}),e.jsx(xe,{placeholder:"…or paste an image URL",value:j,onChange:C=>m(v==="cover"?"cover_image_url":"hero_image_url",C.target.value)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:b})]})]})]})};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"sticky top-0 z-10 -mx-1 flex flex-wrap items-center justify-between gap-3 rounded-lg border border-border bg-background/95 px-4 py-3 backdrop-blur",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:a?"You have unsaved changes.":"All changes saved."}),e.jsxs("div",{className:"flex gap-2",children:[a&&e.jsx(B,{variant:"ghost",onClick:()=>{r($7e(s)),i(!1)},children:"Discard"}),e.jsxs(B,{onClick:f,disabled:l||!a,children:[l?e.jsx(Ct,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(Ho,{className:"mr-1.5 h-4 w-4"}),"Save changes"]})]})]}),e.jsx(ve,{children:e.jsxs(Me,{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(J,{children:"Program name"}),e.jsx(xe,{value:n.name,onChange:v=>m("name",v.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Slug (public URL)"}),e.jsx(xe,{value:n.slug,onChange:v=>m("slug",v.target.value)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["/programs/",n.slug||"slug"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Subtitle"}),e.jsx(xe,{value:n.subtitle,onChange:v=>m("subtitle",v.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Tagline"}),e.jsx(xe,{value:n.tagline,onChange:v=>m("tagline",v.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Short description (cards & previews)"}),e.jsx(Ms,{rows:2,value:n.short_description,onChange:v=>m("short_description",v.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Full program description (sales page)"}),e.jsx(Ms,{rows:8,value:n.description,onChange:v=>m("description",v.target.value)})]})]})}),e.jsx(ve,{children:e.jsxs(Me,{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(y,{kind:"cover",label:"Program cover image",hint:"Shown on the Programs list and enrollment cards. 1200×630 works great."}),e.jsx(y,{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(J,{children:"Promo video URL (optional)"}),e.jsx(xe,{placeholder:"https://youtu.be/… , Vimeo, or a direct .mp4 link",value:n.promo_video_url,onChange:v=>m("promo_video_url",v.target.value)}),e.jsx(xe,{placeholder:"Video headline (e.g. Watch: what 90 days inside Reel Estate looks like)",value:n.promo_video_headline,onChange:v=>m("promo_video_headline",v.target.value)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Plays in a cinematic player near the top of the program signup page."})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Accent color"}),e.jsx(xe,{placeholder:"#406E71",value:n.accent_color,onChange:v=>m("accent_color",v.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Sort order"}),e.jsx(xe,{type:"number",value:n.sort_order,onChange:v=>m("sort_order",Number(v.target.value))})]})]})]})}),e.jsx(ve,{children:e.jsxs(Me,{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(J,{children:"One-time price (USD)"}),e.jsx(xe,{type:"number",min:0,step:"1",value:n.price_cents/100,onChange:v=>m("price_cents",Math.round(Number(v.target.value)*100))}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Charged one time for the full program — never recurring."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Seats (capacity)"}),e.jsx(xe,{type:"number",min:0,value:n.capacity,onChange:v=>m("capacity",Number(v.target.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Billing mode"}),e.jsxs(is,{value:n.payment_mode,onValueChange:v=>m("payment_mode",v),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"delayed",children:"Save card, charge once later"}),e.jsx(He,{value:"immediate",children:"Charge once at checkout"}),e.jsx(He,{value:"free",children:"Free / included"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Charge date (one-time)"}),e.jsx(xe,{type:"datetime-local",value:n.charge_at,onChange:v=>m("charge_at",v.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Payment grace days"}),e.jsx(xe,{type:"number",min:0,value:n.payment_grace_days,onChange:v=>m("payment_grace_days",Number(v.target.value))}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Days of access kept after a failed charge before access is paused."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Currency"}),e.jsx(xe,{value:n.currency,onChange:v=>m("currency",v.target.value)})]})]})]})}),e.jsx(ve,{children:e.jsxs(Me,{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(J,{children:"Enrollment opens"}),e.jsx(xe,{type:"datetime-local",value:n.enrollment_open_at,onChange:v=>m("enrollment_open_at",v.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Enrollment closes"}),e.jsx(xe,{type:"datetime-local",value:n.enrollment_close_at,onChange:v=>m("enrollment_close_at",v.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Kickoff"}),e.jsx(xe,{type:"datetime-local",value:n.kickoff_at,onChange:v=>m("kickoff_at",v.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Length (weeks)"}),e.jsx(xe,{type:"number",min:1,value:n.duration_weeks,onChange:v=>m("duration_weeks",Number(v.target.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Videos per week goal"}),e.jsx(xe,{type:"number",min:0,value:n.weekly_video_goal,onChange:v=>m("weekly_video_goal",Number(v.target.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Timezone"}),e.jsx(xe,{value:n.timezone,onChange:v=>m("timezone",v.target.value)})]})]})]})}),e.jsx(ve,{children:e.jsxs(Me,{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(J,{children:"Status"}),e.jsxs(is,{value:n.status,onValueChange:v=>m("status",v),children:[e.jsx(rs,{className:"sm:max-w-xs",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"draft",children:"Draft (hidden)"}),e.jsx(He,{value:"published",children:"Published (members can enroll)"}),e.jsx(He,{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(fn,{checked:n.is_featured,onCheckedChange:v=>m("is_featured",v)})]}),e.jsxs("div",{className:"flex items-center justify-between gap-4 border-t border-border/60 pt-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Visible to all members"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Turn off to keep it invite-only via a direct link."})]}),e.jsx(fn,{checked:n.is_public,onCheckedChange:v=>m("is_public",v)})]})]})}),e.jsx("div",{className:"flex justify-end pb-4",children:e.jsxs(B,{onClick:f,disabled:l||!a,size:"lg",children:[l?e.jsx(Ct,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(Ho,{className:"mr-1.5 h-4 w-4"}),"Save changes"]})})]})},vyt={title:"",description:"",category:"Personal",resource_kind:"pdf",url:"",file_path:"",status:"published",sort_order:0},aQs=({programId:s,userId:t,memberName:n})=>{const{data:r=[],isLoading:a}=uUs(s,t),i=hUs(s,t),l=mUs(),[o,c]=_.useState(!1),[d,u]=_.useState({...vyt}),[h,m]=_.useState(!1),p=_.useRef(null),f=()=>{u({...vyt,sort_order:r.length}),c(!0)},y=b=>{u({id:b.id,title:b.title,description:b.description||"",category:b.category||"Personal",resource_kind:b.resource_kind,url:b.url||"",file_path:b.file_path||"",status:b.status,sort_order:b.sort_order}),c(!0)},v=async b=>{if(!(!b||!s||!t)){if(b.size>50*1024*1024)return se.error("File must be under 50MB");m(!0);try{const j=b.name.split(".").pop()||"pdf",S=`programs/${s}/members/${t}/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${j}`,{error:C}=await q.storage.from(_W).upload(S,b,{contentType:b.type||"application/pdf",upsert:!1});if(C)throw C;u(E=>({...E,file_path:S,url:"",title:E.title||b.name.replace(/\.[^.]+$/,""),resource_kind:b.type==="application/pdf"?"pdf":E.resource_kind})),se.success("File uploaded")}catch(j){se.error(j.message||"Upload failed")}finally{m(!1),p.current&&(p.current.value="")}}},g=async()=>{if(!d.title.trim())return se.error("Give the resource a title");if(!d.file_path&&!d.url.trim())return se.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(ec,{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(B,{size:"sm",onClick:f,disabled:!t,children:[e.jsx(rn,{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(ve,{className:"border-dashed",children:e.jsx(Me,{className:"p-6 text-center text-sm text-muted-foreground",children:"No personal resources yet. Upload their custom plan, feedback doc or scripts."})}):e.jsx("div",{className:"space-y-2",children:r.map(b=>e.jsx(ve,{className:"border-border/60",children:e.jsxs(Me,{className:"flex flex-wrap items-start justify-between gap-3 p-4",children:[e.jsxs("div",{className:"min-w-0 space-y-1.5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"font-medium",children:b.title}),e.jsx(Oe,{variant:"secondary",children:b.category}),e.jsx(Oe,{variant:"outline",className:"capitalize",children:b.resource_kind.replace("_"," ")}),b.status!=="published"&&e.jsx(Oe,{variant:"outline",className:"capitalize",children:b.status})]}),b.description&&e.jsx("p",{className:"max-w-xl text-sm text-muted-foreground",children:b.description}),oae(b)&&e.jsxs("button",{type:"button",onClick:()=>TJ(b),className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(wr,{className:"h-3 w-3"})," Open"]})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>y(b),children:e.jsx(Ya,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:async()=>{await Xi(`Remove "${b.title}"?`)&&l.mutate(b)},children:e.jsx(Sn,{className:"h-4 w-4 text-destructive"})})]})]})},b.id))}),e.jsx(Ls,{open:o,onOpenChange:c,children:e.jsxs(Ps,{className:"max-w-lg",children:[e.jsx(Os,{children:e.jsx(Ds,{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(J,{children:"Title"}),e.jsx(xe,{value:d.title,onChange:b=>u({...d,title:b.target.value}),placeholder:"Your 90-day content plan"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Description"}),e.jsx(Ms,{rows:2,value:d.description,onChange:b=>u({...d,description:b.target.value})})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Category"}),e.jsx(xe,{value:d.category,onChange:b=>u({...d,category:b.target.value}),placeholder:"Personal"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Type"}),e.jsxs(is,{value:d.resource_kind,onValueChange:b=>u({...d,resource_kind:b}),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsx(as,{children:Lzt.map(b=>e.jsx(He,{value:b.value,children:b.label},b.value))})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"File"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{type:"button",variant:"outline",size:"sm",disabled:h,onClick:()=>{var b;return(b=p.current)==null?void 0:b.click()},children:[h?e.jsx(Ct,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(Oa,{className:"mr-1.5 h-4 w-4"}),d.file_path?"Replace file":"Upload file"]}),d.file_path&&e.jsx("span",{className:"truncate text-xs text-muted-foreground",children:d.file_path.split("/").pop()})]}),e.jsx("input",{ref:p,type:"file",hidden:!0,onChange:b=>{var j;return v((j=b.target.files)==null?void 0:j[0])}})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"…or link"}),e.jsx(xe,{value:d.url,onChange:b=>u({...d,url:b.target.value,file_path:""}),placeholder:"https://…"})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Status"}),e.jsxs(is,{value:d.status,onValueChange:b=>u({...d,status:b}),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"published",children:"Published"}),e.jsx(He,{value:"draft",children:"Draft"}),e.jsx(He,{value:"archived",children:"Archived"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Sort order"}),e.jsx(xe,{type:"number",value:d.sort_order,onChange:b=>u({...d,sort_order:b.target.value})})]})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"ghost",onClick:()=>c(!1),children:"Cancel"}),e.jsxs(B,{onClick:g,disabled:i.isPending||h,children:[i.isPending&&e.jsx(Ct,{className:"mr-1.5 h-4 w-4 animate-spin"})," Save"]})]})]})})]})},iQs=({program:s,enrollment:t,open:n,onOpenChange:r,onUpdated:a})=>{var H,Y,Z,ne,ce,ie,te,ae,le,be;const i=t==null?void 0:t.user_id,[l,o]=_.useState((t==null?void 0:t.admin_notes)||""),[c,d]=_.useState(!1),[u,h]=_.useState(""),[m,p]=_.useState(!1),[f,y]=_.useState(!1),v=_.useRef(null),{data:g,isLoading:b,refetch:j}=at({queryKey:["admin-program-agent",s.id,i],enabled:n&&!!i,queryFn:async()=>{const[me,he,pe,Ce,Ae,Pe,ze,ke]=await Promise.all([q.from("program_weekly_progress").select("*").eq("program_id",s.id).eq("user_id",i).order("week_number"),q.from("program_video_logs").select("*").eq("program_id",s.id).eq("user_id",i).order("posted_at",{ascending:!1}),q.from("program_lesson_completions").select("*").eq("program_id",s.id).eq("user_id",i),q.from("program_badge_awards").select("*").eq("program_id",s.id).eq("user_id",i),q.from("program_intake_responses").select("*").eq("program_id",s.id).eq("user_id",i).maybeSingle(),q.from("program_event_attendance").select("*").eq("program_id",s.id).eq("user_id",i),q.from("program_lessons").select("id").eq("program_id",s.id),q.from("program_profile_analyses").select("*").eq("program_id",s.id).eq("user_id",i).maybeSingle()]);return{weekly:me.data||[],videos:he.data||[],completions:pe.data||[],badges:Ce.data||[],intake:Ae.data,attendance:Pe.data||[],lessonCount:(ze.data||[]).length,analysis:ke.data}}});_.useEffect(()=>{var me;h(((me=g==null?void 0:g.analysis)==null?void 0:me.member_notes)||"")},[(H=g==null?void 0:g.analysis)==null?void 0:H.id]);const S=_.useMemo(()=>{var pe;const me=mte(s),he=((pe=g==null?void 0:g.intake)==null?void 0:pe.extra)||{};return me.custom.map(Ce=>({label:Ce.label,value:typeof he[Ce.id]=="boolean"?he[Ce.id]?"Yes":"No":he[Ce.id]||""})).filter(Ce=>!!Ce.value)},[s,g==null?void 0:g.intake]),C=async me=>i?q.from("program_profile_analyses").upsert({program_id:s.id,user_id:i,enrollment_id:(t==null?void 0:t.id)||null,...me},{onConflict:"program_id,user_id"}):{error:{message:"Missing agent"}},E=async me=>{if(me.type!=="application/pdf")return se.error("Please choose a PDF file");if(me.size>25*1024*1024)return se.error("PDF must be under 25MB");y(!0);try{const he=`programs/${s.id}/reviews/${i}-${Date.now()}.pdf`,{error:pe}=await q.storage.from("event-images").upload(he,me,{contentType:"application/pdf",upsert:!0});if(pe)throw pe;const{data:Ce}=q.storage.from("event-images").getPublicUrl(he),{error:Ae}=await C({report_url:Ce.publicUrl,status:"ready",reviewed_at:new Date().toISOString()});if(Ae)throw Ae;se.success("Profile review uploaded"),await j()}catch(he){se.error(he.message||"Upload failed")}finally{y(!1)}},P=async()=>{const{error:me}=await C({report_url:null,status:"in_review"});if(me)return se.error(me.message);se.success("Review removed"),await j()},M=async()=>{p(!0);const{error:me}=await C({member_notes:u});if(p(!1),me)return se.error(me.message);se.success("Review notes saved"),await j()},I=async()=>{if(!t)return;d(!0);const{error:me}=await q.from("program_enrollments").update({admin_notes:l}).eq("id",t.id);if(d(!1),me)return se.error(me.message);se.success("Notes saved"),a()},D=((g==null?void 0:g.videos)||[]).filter(me=>me.posted).length,O=(s.weekly_video_goal||0)*(s.duration_weeks||0),V=g!=null&&g.lessonCount?Math.round(((g==null?void 0:g.completions.length)||0)/g.lessonCount*100):0,G=O?Math.min(100,Math.round(D/O*100)):0,$=((g==null?void 0:g.attendance)||[]).filter(me=>me.attended).length;return e.jsx(qg,{open:n,onOpenChange:r,children:e.jsxs(hg,{className:"w-full overflow-y-auto sm:max-w-2xl",children:[e.jsxs(P0,{className:"mb-4",children:[e.jsxs(L0,{children:[((Y=t==null?void 0:t.profile)==null?void 0:Y.name)||"Agent"," · ",s.name]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(Z=t==null?void 0:t.profile)==null?void 0:Z.email}),i&&e.jsx(B,{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(((ne=t==null?void 0:t.profile)==null?void 0:ne.name)||((ce=t==null?void 0:t.profile)==null?void 0:ce.email)||"this member")}`,target:"_blank",rel:"noreferrer",children:[e.jsx(wr,{className:"mr-2 h-4 w-4"}),"Open their dashboard"]})})]}),t?b?e.jsx(cn,{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(ve,{children:e.jsxs(Me,{className:"p-4",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Status"}),e.jsx(Oe,{className:"mt-1 capitalize",children:String(t.status).replace(/_/g," ")}),e.jsxs("p",{className:"mt-2 text-xs text-muted-foreground",children:[Tf(t.amount_cents,t.currency)," ·"," ",t.charged_at?`Charged ${xu(t.charged_at)}`:`Charge ${xu(t.charge_scheduled_at)||"not set"}`]})]})}),e.jsx(ve,{children:e.jsxs(Me,{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:xu(t.last_activity_at,!0)||"No activity yet"}),e.jsxs("p",{className:"mt-2 text-xs text-muted-foreground",children:["Enrolled ",xu(t.created_at)]})]})})]}),e.jsx(ve,{children:e.jsxs(Me,{className:"space-y-4 p-5",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"mb-1 flex items-center justify-between text-sm",children:[e.jsx("span",{className:"font-medium",children:"Videos posted"}),e.jsxs("span",{className:"text-muted-foreground",children:[D," / ",O||"—"]})]}),e.jsx(Fi,{value:G})]}),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:[(g==null?void 0:g.completions.length)||0," / ",(g==null?void 0:g.lessonCount)||0]})]}),e.jsx(Fi,{value:V})]}),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: "}),$]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Badges: "}),(g==null?void 0:g.badges.length)||0]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Weeks reported: "}),(g==null?void 0:g.weekly.length)||0]})]})]})}),e.jsx(ve,{children:e.jsxs(Me,{className:"p-5",children:[e.jsx("p",{className:"mb-3 text-sm font-semibold",children:"Weekly progress"}),((g==null?void 0:g.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:g.weekly.map(me=>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 ",me.week_number]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[me.videos_posted,"/",me.goal_videos||s.weekly_video_goal," posted ·"," ",me.stories_posted," stories"]})]}),me.biggest_win&&e.jsxs("p",{className:"mt-1 text-muted-foreground",children:["Win: ",me.biggest_win]}),me.biggest_challenge&&e.jsxs("p",{className:"text-muted-foreground",children:["Challenge: ",me.biggest_challenge]})]},me.id))})]})}),e.jsx(ve,{children:e.jsxs(Me,{className:"p-5",children:[e.jsx("p",{className:"mb-3 text-sm font-semibold",children:"Video log"}),((g==null?void 0:g.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:g.videos.slice(0,25).map(me=>e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(Kr,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:me.title||"Untitled video"}),e.jsxs("span",{className:"ml-auto shrink-0 text-xs text-muted-foreground",children:["Wk ",me.week_number," · ",xu(me.posted_at)]}),me.instagram_url&&e.jsx("a",{href:me.instagram_url,target:"_blank",rel:"noreferrer",className:"shrink-0 text-muted-foreground hover:text-foreground","aria-label":"Open post",children:e.jsx(wr,{className:"h-3.5 w-3.5"})})]},me.id))})]})}),(g==null?void 0:g.intake)&&e.jsx(ve,{children:e.jsxs(Me,{className:"space-y-1 p-5 text-sm",children:[e.jsx("p",{className:"mb-2 text-sm font-semibold",children:"Intake answers"}),[["Full name",g.intake.full_name],["Email",g.intake.email],["Phone",g.intake.phone],["Instagram",g.intake.instagram_handle],["City / market",g.intake.city],["Areas served",g.intake.service_areas],["Years in real estate",g.intake.years_experience],["Specialty",g.intake.specialty],["Target audience",g.intake.target_audience],["On camera",g.intake.video_comfort],["Posts today",g.intake.posting_frequency],["Content style",g.intake.content_style],["Interests",g.intake.personal_interests],["#1 goal",g.intake.primary_goal],["Topics to avoid",g.intake.topics_to_avoid],["Time zone",g.intake.timezone]].filter(([,me])=>!!me).map(([me,he])=>e.jsxs("p",{children:[e.jsxs("span",{className:"text-muted-foreground",children:[me,": "]}),he]},me)),S.map(({label:me,value:he})=>e.jsxs("p",{children:[e.jsxs("span",{className:"text-muted-foreground",children:[me,": "]}),he]},me)),e.jsxs("p",{className:"pt-1 text-xs text-muted-foreground",children:["Content-sharing consent: ",g.intake.consent_public_profile?"Yes":"No"]})]})}),e.jsx(ve,{children:e.jsx(Me,{className:"p-5",children:e.jsx(aQs,{programId:s.id,userId:i,memberName:(ie=t==null?void 0:t.profile)==null?void 0:ie.name})})}),e.jsx(ve,{children:e.jsxs(Me,{className:"space-y-3 p-5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold",children:"Profile review PDF"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Upload this agent's personalized profile review. They see it in their workspace."})]}),((te=g==null?void 0:g.analysis)==null?void 0:te.status)&&e.jsx(Oe,{variant:"secondary",className:"capitalize",children:String(g.analysis.status).replace(/_/g," ")})]}),(ae=g==null?void 0:g.analysis)!=null&&ae.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(Fr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:"Review uploaded"}),e.jsxs("a",{href:g.analysis.report_url,target:"_blank",rel:"noreferrer",className:"ml-auto inline-flex items-center gap-1 text-primary hover:underline",children:["View ",e.jsx(wr,{className:"h-3.5 w-3.5"})]})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"No review uploaded yet."}),e.jsx("input",{ref:v,type:"file",accept:"application/pdf",className:"hidden",onChange:me=>{var pe;const he=(pe=me.target.files)==null?void 0:pe[0];he&&E(he),me.target.value=""}}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>{var me;return(me=v.current)==null?void 0:me.click()},disabled:f,children:[e.jsx(Oa,{className:"mr-1.5 h-3.5 w-3.5"}),f?"Uploading…":(le=g==null?void 0:g.analysis)!=null&&le.report_url?"Replace PDF":"Upload PDF"]}),((be=g==null?void 0:g.analysis)==null?void 0:be.report_url)&&e.jsx(B,{size:"sm",variant:"ghost",onClick:P,children:"Remove"})]}),e.jsxs("div",{className:"space-y-2 pt-1",children:[e.jsx(J,{children:"Review summary shown to the agent (optional)"}),e.jsx(Ms,{rows:3,value:u,onChange:me=>h(me.target.value),placeholder:"Top 3 priorities, quick wins, what to fix first…"}),e.jsx("div",{className:"flex justify-end",children:e.jsx(B,{size:"sm",variant:"outline",onClick:M,disabled:m,children:"Save review notes"})})]})]})}),e.jsx(ve,{children:e.jsxs(Me,{className:"space-y-3 p-5",children:[e.jsx(J,{children:"Coach notes (internal)"}),e.jsx(Ms,{rows:4,value:l,onChange:me=>o(me.target.value)}),e.jsx("div",{className:"flex justify-end",children:e.jsx(B,{size:"sm",onClick:I,disabled:c,children:"Save notes"})})]})})]}):null]})})},byt={code:"",label:"",kind:"percent",percent_off:"20",amount_off:"",max_redemptions:"",starts_at:"",expires_at:"",is_active:!0},_yt=s=>{if(!s)return"";const t=new Date(s),n=t.getTimezoneOffset();return new Date(t.getTime()-n*6e4).toISOString().slice(0,16)},oQs=({program:s})=>{const{data:t=[],isLoading:n}=QBs(s.id),r=JBs(s.id),a=eUs(),[i,l]=_.useState(!1),[o,c]=_.useState({...byt}),d=()=>{c({...byt}),l(!0)},u=f=>{c({id:f.id,code:f.code,label:f.label||"",kind:f.percent_off!=null?"percent":"amount",percent_off:f.percent_off!=null?String(f.percent_off):"",amount_off:f.amount_off_cents!=null?String(f.amount_off_cents/100):"",max_redemptions:f.max_redemptions!=null?String(f.max_redemptions):"",starts_at:_yt(f.starts_at),expires_at:_yt(f.expires_at),is_active:f.is_active}),l(!0)},h=_.useMemo(()=>{const f=o.kind==="percent"?Math.floor(s.price_cents*Number(o.percent_off||0)/100):Math.round(Number(o.amount_off||0)*100),y=Math.min(Math.max(f,0),s.price_cents);return{discount:y,final:s.price_cents-y}},[o,s.price_cents]),m=async()=>{if(!o.code.trim())return se.error("Give the code a name, e.g. FOUNDER50");await r.mutateAsync({id:o.id,code:o.code,label:o.label||null,percent_off:o.kind==="percent"?Number(o.percent_off)||0:null,amount_off_cents:o.kind==="amount"?Math.round(Number(o.amount_off||0)*100):null,max_redemptions:o.max_redemptions?Number(o.max_redemptions):null,starts_at:o.starts_at?new Date(o.starts_at).toISOString():null,expires_at:o.expires_at?new Date(o.expires_at).toISOString():null,is_active:o.is_active}),l(!1)},p=f=>{const y=f.percent_off!=null?Math.floor(s.price_cents*Number(f.percent_off)/100):f.amount_off_cents||0,v=Math.max(s.price_cents-Math.min(y,s.price_cents),0);return{off:f.percent_off!=null?`${Number(f.percent_off)}% off`:`${Tf(f.amount_off_cents||0,s.currency)} off`,final:Tf(v,s.currency)}};return e.jsxs("div",{className:"space-y-4",children:[e.jsx(ve,{children:e.jsxs(Me,{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 ",Tf(s.price_cents,s.currency)," charge."]})]}),e.jsxs(Ls,{open:i,onOpenChange:l,children:[e.jsx(nl,{asChild:!0,children:e.jsxs(B,{onClick:d,children:[e.jsx(rn,{className:"mr-1.5 h-4 w-4"})," New code"]})}),e.jsxs(Ps,{className:"max-h-[85vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Ds,{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(J,{children:"Code"}),e.jsx(xe,{placeholder:"FOUNDER50",value:o.code,onChange:f=>c({...o,code:f.target.value.toUpperCase()})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Internal label (optional)"}),e.jsx(xe,{placeholder:"Founding cohort",value:o.label,onChange:f=>c({...o,label:f.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Discount type"}),e.jsxs(is,{value:o.kind,onValueChange:f=>c({...o,kind:f}),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"percent",children:"Percent off"}),e.jsx(He,{value:"amount",children:"Dollar amount off"})]})]})]}),o.kind==="percent"?e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Percent off"}),e.jsx(xe,{type:"number",min:1,max:100,value:o.percent_off,onChange:f=>c({...o,percent_off:f.target.value})})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Amount off (USD)"}),e.jsx(xe,{type:"number",min:0,value:o.amount_off,onChange:f=>c({...o,amount_off:f.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Max redemptions (blank = unlimited)"}),e.jsx(xe,{type:"number",min:1,value:o.max_redemptions,onChange:f=>c({...o,max_redemptions:f.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Active from (optional)"}),e.jsx(xe,{type:"datetime-local",value:o.starts_at,onChange:f=>c({...o,starts_at:f.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Expires (optional)"}),e.jsx(xe,{type:"datetime-local",value:o.expires_at,onChange:f=>c({...o,expires_at:f.target.value})})]})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border border-border/60 p-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Code is active"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Turn off to stop new redemptions instantly."})]}),e.jsx(fn,{checked:o.is_active,onCheckedChange:f=>c({...o,is_active:f})})]}),e.jsxs("div",{className:"rounded-lg border border-primary/30 bg-primary/5 p-4 text-sm",children:[e.jsx("p",{className:"font-medium",children:"Enrollee sees"}),e.jsxs("p",{className:"mt-1 text-muted-foreground",children:[Tf(s.price_cents,s.currency)," →"," ",e.jsx("span",{className:"font-semibold text-foreground",children:Tf(h.final,s.currency)})," ","(",Tf(h.discount,s.currency)," off) — charged one time."]})]})]}),e.jsx(yr,{children:e.jsxs(B,{onClick:m,disabled:r.isPending,children:[r.isPending&&e.jsx(Ct,{className:"mr-1.5 h-4 w-4 animate-spin"}),o.id?"Save changes":"Create code"]})})]})]})]})}),n?e.jsx(cn,{className:"h-40 w-full rounded-xl"}):t.length===0?e.jsx(ve,{className:"border-dashed",children:e.jsxs(Me,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(Ep,{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(ve,{children:e.jsx(Me,{className:"overflow-x-auto p-0",children:e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"Code"}),e.jsx(Pt,{children:"Discount"}),e.jsx(Pt,{children:"Price after"}),e.jsx(Pt,{children:"Used"}),e.jsx(Pt,{children:"Window"}),e.jsx(Pt,{children:"Status"}),e.jsx(Pt,{className:"text-right",children:"Actions"})]})}),e.jsx(Ka,{children:t.map(f=>{const y=p(f);return e.jsxs(pn,{children:[e.jsxs(gt,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-mono font-semibold",children:f.code}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>{navigator.clipboard.writeText(f.code),se.success("Code copied")},children:e.jsx(Ia,{className:"h-3.5 w-3.5"})})]}),f.label&&e.jsx("p",{className:"text-xs text-muted-foreground",children:f.label})]}),e.jsx(gt,{className:"whitespace-nowrap",children:e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(F_,{className:"h-3.5 w-3.5 text-muted-foreground"}),y.off]})}),e.jsx(gt,{className:"font-medium",children:y.final}),e.jsxs(gt,{children:[f.times_redeemed,f.max_redemptions?` / ${f.max_redemptions}`:""]}),e.jsxs(gt,{className:"text-xs text-muted-foreground",children:[f.starts_at?`From ${xu(f.starts_at)}`:"Anytime",f.expires_at?` · until ${xu(f.expires_at)}`:""]}),e.jsx(gt,{children:e.jsx(Oe,{variant:f.is_active?"default":"secondary",children:f.is_active?"Active":"Paused"})}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[e.jsx(B,{variant:"outline",size:"sm",onClick:()=>u(f),children:"Edit"}),e.jsx(B,{variant:"ghost",size:"icon",onClick:async()=>{await Xi(`Delete ${f.code}?`)&&a.mutate(f.id)},children:e.jsx(Sn,{className:"h-4 w-4 text-destructive"})})]})})]},f.id)})})]})})})]})},_5=({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(Er,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}):e.jsx(xl,{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})]})]}),lQs=({program:s})=>{var c,d;const{data:t,isLoading:n}=at({queryKey:["admin-program-content-counts",s.id],queryFn:async()=>{const[u,h,m,p,f]=await Promise.all([q.from("program_weeks").select("id, week_number, title").eq("program_id",s.id),q.from("program_lessons").select("id, title").eq("program_id",s.id),q.from("program_resources").select("id, title").eq("program_id",s.id),q.from("program_events").select("id, title, starts_at").eq("program_id",s.id),q.from("program_announcements").select("id, title").eq("program_id",s.id)]);return{weeks:u.data||[],lessons:h.data||[],resources:m.data||[],events:p.data||[],announcements:f.data||[]}}}),{notOpenYet:r,closed:a,opensLabel:i}=uLe(s),l=`/programs/${s.slug}`,o=[{icon:un,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:Jq,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:_y,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 ${Tf(s.price_cents,s.currency)} charge runs on ${xu(s.charge_at||s.kickoff_at)||"the charge date (not set)"}.`:`Stripe charges ${Tf(s.price_cents,s.currency)} once at checkout.`},{icon:ln,title:"4 · Emails",body:"Confirmation right after enrollment, then payment receipt (or a payment-failed action email) when the one-time charge runs."},{icon:Wq,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(ve,{children:e.jsxs(Me,{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(B,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:l,target:"_blank",rel:"noreferrer",children:["Sales page ",e.jsx(wr,{className:"ml-1.5 h-3.5 w-3.5"})]})}),e.jsx(B,{asChild:!0,children:e.jsxs("a",{href:`${l}/workspace?preview=1`,target:"_blank",rel:"noreferrer",children:["Workspace preview ",e.jsx(wr,{className:"ml-1.5 h-3.5 w-3.5"})]})})]})]})}),(s.status!=="published"||r||a)&&e.jsx(ve,{className:"border-amber-500/40 bg-amber-500/5",children:e.jsxs(Me,{className:"flex items-start gap-3 p-5 text-sm",children:[e.jsx(xl,{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(ve,{children:e.jsxs(Me,{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(B,{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(wr,{className:"ml-1 h-3 w-3"})]})})]})]},u.title))})]})}),e.jsx(ve,{children:e.jsxs(Me,{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(cn,{className:"mt-4 h-64 w-full rounded-lg"}):e.jsxs("div",{className:"mt-2",children:[e.jsx(_5,{ok:!!s.cover_image_url,label:"Cover image",detail:s.cover_image_url?"Set":"Missing — cards look empty on the Programs page"}),e.jsx(_5,{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(_5,{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(_5,{ok:s.payment_mode==="free"||s.price_cents>0,label:"One-time price",detail:s.payment_mode==="free"?"Free / included":Tf(s.price_cents,s.currency)}),e.jsx(_5,{ok:!!s.kickoff_at&&(s.payment_mode==="free"||!!s.charge_at),label:"Kickoff and charge dates",detail:`Kickoff ${xu(s.kickoff_at)||"not set"} · charge ${xu(s.charge_at)||"not set"}`}),e.jsx(_5,{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(_5,{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(_5,{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(_5,{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 ${xu(t.events[0].starts_at)}`:""}`}),e.jsx(_5,{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(ve,{children:e.jsx(Me,{className:"grid gap-4 p-5 sm:grid-cols-2 lg:grid-cols-5",children:[{icon:pc,label:"Weeks",value:t.weeks.length},{icon:Fr,label:"Lessons",value:t.lessons.length},{icon:Fr,label:"Resources",value:t.resources.length},{icon:pc,label:"Events",value:t.events.length},{icon:wh,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(Oe,{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."})]})},cQs=["Step 1 · Your business","Step 2 · Your content","Step 3 · Your goals"],dQs={short_text:"Short answer",long_text:"Paragraph",select:"Dropdown",checkbox:"Yes / no checkbox"},uQs=({program:s,onSaved:t})=>{const[n,r]=_.useState(()=>mte(s)),[a,i]=_.useState(!1),[l,o]=_.useState(!1);_.useEffect(()=>{r(mte(s)),i(!1)},[s.id,s.updated_at]);const c=v=>{r(g=>({...g,...v})),i(!0)},d=(v,g)=>{const b=g?n.hidden.filter(S=>S!==v):[...new Set([...n.hidden,v])],j=g?n.required:n.required.filter(S=>S!==v);c({hidden:b,required:j})},u=(v,g)=>{c({required:g?[...new Set([...n.required,v])]:n.required.filter(b=>b!==v)})},h=()=>{const v={id:`q_${Date.now().toString(36)}`,label:"",type:"short_text",required:!1,options:[]};c({custom:[...n.custom,v]})},m=(v,g)=>c({custom:n.custom.map(b=>b.id===v?{...b,...g}:b)}),p=v=>c({custom:n.custom.filter(g=>g.id!==v)}),f=(v,g)=>{const b=[...n.custom],j=v+g;j<0||j>=b.length||([b[v],b[j]]=[b[j],b[v]],c({custom:b}))},y=async()=>{if(n.custom.find(j=>!j.label.trim()))return se.error("Every custom question needs a label");o(!0);const g={...s.sales_copy||{},intake:n},{error:b}=await q.from("programs").update({sales_copy:g}).eq("id",s.id);if(o(!1),b)return se.error(b.message);i(!1),se.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(B,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:`/programs/${s.slug}/enroll`,target:"_blank",rel:"noreferrer",children:[e.jsx(wr,{className:"mr-1.5 h-3.5 w-3.5"})," Preview form"]})}),e.jsxs(B,{size:"sm",onClick:y,disabled:!a||l,children:[e.jsx(Ho,{className:"mr-1.5 h-3.5 w-3.5"}),l?"Saving…":"Save intake form"]})]})]}),e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-3",children:e.jsx(St,{className:"text-sm",children:"Intro message"})}),e.jsx(Me,{children:e.jsx(Ms,{rows:3,placeholder:"Shown at the top of the intake — e.g. “Answer a few questions so we can personalize your 90 days.”",value:n.intro||"",onChange:v=>c({intro:v.target.value})})})]}),[0,1,2].map(v=>e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-3",children:e.jsx(St,{className:"text-sm",children:cQs[v]})}),e.jsxs(Me,{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"})]}),pet.filter(g=>g.step===v).map(g=>{const b=!n.hidden.includes(g.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:g.label}),e.jsx("div",{className:"flex w-16 justify-center",children:e.jsx(fn,{checked:b,onCheckedChange:j=>d(g.key,j),"aria-label":`Show ${g.label}`})}),e.jsx("div",{className:"flex w-16 justify-center",children:e.jsx(fn,{checked:n.required.includes(g.key),disabled:!b,onCheckedChange:j=>u(g.key,j),"aria-label":`Require ${g.label}`})})]},g.key)})]})]},v)),e.jsxs(ve,{children:[e.jsxs(bt,{className:"flex-row items-center justify-between space-y-0 pb-3",children:[e.jsxs(St,{className:"text-sm",children:["Custom questions"," ",e.jsx(Oe,{variant:"secondary",className:"ml-1",children:n.custom.length})]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:h,children:[e.jsx(rn,{className:"mr-1.5 h-3.5 w-3.5"})," Add question"]})]}),e.jsxs(Me,{className:"space-y-3",children:[n.custom.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No custom questions yet. Add program-specific questions here — answers appear on each agent's dashboard."}),n.custom.map((v,g)=>e.jsxs("div",{className:"space-y-3 rounded-lg border border-border/60 p-4",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("div",{className:"flex flex-col pt-1.5",children:e.jsx("button",{type:"button",className:"text-muted-foreground hover:text-foreground",onClick:()=>f(g,-1),"aria-label":"Move up",children:e.jsx(Vf,{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(J,{className:"text-xs",children:"Question"}),e.jsx(xe,{value:v.label,placeholder:"What is your biggest content roadblock?",onChange:b=>m(v.id,{label:b.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs",children:"Answer type"}),e.jsxs(is,{value:v.type,onValueChange:b=>m(v.id,{type:b}),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsx(as,{children:Object.entries(dQs).map(([b,j])=>e.jsx(He,{value:b,children:j},b))})]})]})]}),e.jsx(B,{size:"icon",variant:"ghost",onClick:()=>p(v.id),"aria-label":"Delete question",children:e.jsx(Sn,{className:"h-4 w-4 text-destructive"})})]}),v.type==="select"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs",children:"Options (one per line)"}),e.jsx(Ms,{rows:3,value:(v.options||[]).join(` `),onChange:b=>m(v.id,{options:b.target.value.split(` `).map(j=>j.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(J,{className:"text-xs",children:"Helper text (optional)"}),e.jsx(xe,{value:v.help||"",onChange:b=>m(v.id,{help:b.target.value})})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-6",children:[e.jsx(fn,{checked:!!v.required,onCheckedChange:b=>m(v.id,{required:b}),"aria-label":"Required"}),e.jsx("span",{className:"text-sm",children:"Required"})]})]})]},v.id))]})]})]})},f1=oqt,x1=ctt,g1=utt,hQs=[Cx,Fr,ku],mQs=["Business profile","Content style","Goals & consent"],pQs=({fieldKey:s})=>s.includes("phone")?e.jsx(_a,{className:"h-3.5 w-3.5"}):s.includes("email")?e.jsx(ln,{className:"h-3.5 w-3.5"}):s.includes("instagram")?e.jsx(Im,{className:"h-3.5 w-3.5"}):s.includes("city")||s.includes("area")?e.jsx(Xa,{className:"h-3.5 w-3.5"}):s.includes("timezone")?e.jsx(Gr,{className:"h-3.5 w-3.5"}):s.includes("consent")?s.includes("true")?e.jsx(Er,{className:"h-3.5 w-3.5"}):e.jsx(Rd,{className:"h-3.5 w-3.5"}):e.jsx(Fo,{className:"h-3.5 w-3.5"}),wyt=(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(Er,{className:"h-3.5 w-3.5"})," Yes"]}):e.jsxs("span",{className:"inline-flex items-center gap-1 text-muted-foreground",children:[e.jsx(Rd,{className:"h-3.5 w-3.5"})," No"]}):String(s),fQs=({program:s})=>{const[t,n]=_.useState(""),[r,a]=_.useState(new Set),{data:i=[],isLoading:l}=at({queryKey:["admin-program-intakes",s.id],queryFn:async()=>{const{data:h,error:m}=await q.from("program_intake_responses").select("*").eq("program_id",s.id).order("created_at",{ascending:!1});if(m)throw m;return h||[]}}),o=mte(s),c=pet.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(cn,{className:"h-96 w-full rounded-xl"}):i.length===0?e.jsx(ve,{className:"border-dashed",children:e.jsxs(Me,{className:"p-12 text-center text-sm text-muted-foreground",children:[e.jsx(Fr,{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(Lr,{className:"absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search responses…",value:t,onChange:h=>n(h.target.value),className:"pl-9"})]})]}),d.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No responses match your search."}),e.jsx("div",{className:"space-y-3",children:d.map(h=>{const m=r.has(h.id),p=xu(h.created_at,!0);return e.jsx(ve,{className:"overflow-hidden",children:e.jsxs(f1,{open:m,onOpenChange:()=>u(h.id),children:[e.jsx(x1,{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(Fo,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{children:[e.jsxs(St,{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(B,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0",children:e.jsx(tl,{className:`h-4 w-4 transition-transform ${m?"rotate-180":""}`})})]})]})}),e.jsx(g1,{children:e.jsxs(Me,{className:"space-y-5 p-5",children:[[0,1,2].map(f=>{const y=c.filter(g=>g.step===f),v=hQs[f];return y.length===0?null:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 border-b border-border/40 pb-2",children:[e.jsx("div",{className:"flex h-6 w-6 items-center justify-center rounded-md bg-primary/10",children:e.jsx(v,{className:"h-3.5 w-3.5 text-primary"})}),e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:mQs[f]})]}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:y.map(g=>{const b=h[g.key];return b==null||b===""?null:e.jsxs("div",{className:"rounded-lg border border-border/50 p-3",children:[e.jsxs("div",{className:"mb-1 flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(pQs,{fieldKey:g.key}),g.label]}),e.jsx("p",{className:"text-sm font-medium",children:wyt(b,g.key)})]},g.key)})})]},f)}),o.custom&&o.custom.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 border-b border-border/40 pb-2",children:[e.jsx("div",{className:"flex h-6 w-6 items-center justify-center rounded-md bg-primary/10",children:e.jsx(Fr,{className:"h-3.5 w-3.5 text-primary"})}),e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Custom questions"})]}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:o.custom.map(f=>{var v;const y=(v=h.extra)==null?void 0:v[f.id];return y==null||y===""?null:e.jsxs("div",{className:"rounded-lg border border-border/50 p-3",children:[e.jsx("p",{className:"mb-1 text-xs text-muted-foreground",children:f.label}),e.jsx("p",{className:"text-sm font-medium",children:wyt(y,f.id)})]},f.id)})})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 pt-2 text-xs text-muted-foreground",children:[e.jsx(ga,{className:"h-3.5 w-3.5"}),"Submitted ",p,h.timezone&&e.jsxs("span",{className:"ml-2",children:["· Timezone: ",h.timezone]})]})]})})]})},h.id)})})]})},xQs=[{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"}],gQs=s=>{if(!s)return"";const t=new Date(s),n=t.getTimezoneOffset();return new Date(t.getTime()-n*6e4).toISOString().slice(0,16)},jyt={title:"",description:"",event_kind:"mastermind",starts_at:"",duration_minutes:60,speaker:"",meeting_link:"",replay_url:"",is_published:!0},yQs=({programId:s})=>{const{data:t=[],isLoading:n}=nUs(s),r=rUs(s),a=aUs(),[i,l]=_.useState(!1),[o,c]=_.useState({...jyt}),d=()=>{c({...jyt}),l(!0)},u=v=>{c({id:v.id,title:v.title,description:v.description||"",event_kind:v.event_kind,starts_at:gQs(v.starts_at),duration_minutes:v.duration_minutes,speaker:v.speaker||"",meeting_link:v.meeting_link||"",replay_url:v.replay_url||"",is_published:v.is_published}),l(!0)},h=async()=>{if(!o.title.trim())return se.error("Give the session a title");if(!o.starts_at)return se.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(v=>new Date(v.starts_at).getTime()>=m),f=t.filter(v=>new Date(v.starts_at).getTime()e.jsx(ve,{className:"border-border/60",children:e.jsxs(Me,{className:"flex flex-wrap items-start justify-between gap-4 p-5",children:[e.jsxs("div",{className:"min-w-0 space-y-1.5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"font-medium",children:v.title}),e.jsx(Oe,{variant:"secondary",className:"capitalize",children:v.event_kind.replace("_"," ")}),!v.is_published&&e.jsx(Oe,{variant:"outline",children:"Hidden"})]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[xu(v.starts_at,!0)," · ",v.duration_minutes," min",v.speaker?` · ${v.speaker}`:""]}),v.description&&e.jsx("p",{className:"max-w-2xl text-sm text-muted-foreground",children:v.description}),e.jsxs("div",{className:"flex flex-wrap gap-3 pt-1 text-xs",children:[v.meeting_link?e.jsxs(e.Fragment,{children:[e.jsxs("a",{className:"inline-flex items-center gap-1 text-primary hover:underline",href:v.meeting_link,target:"_blank",rel:"noreferrer",children:[e.jsx(wr,{className:"h-3 w-3"})," Join link"]}),e.jsxs("button",{className:"inline-flex items-center gap-1 text-muted-foreground hover:text-foreground",onClick:()=>{navigator.clipboard.writeText(v.meeting_link),se.success("Join link copied")},children:[e.jsx(Ia,{className:"h-3 w-3"})," Copy"]})]}):e.jsx("span",{className:"text-muted-foreground",children:"No meeting link yet"}),v.replay_url&&e.jsxs("a",{className:"inline-flex items-center gap-1 text-primary hover:underline",href:v.replay_url,target:"_blank",rel:"noreferrer",children:[e.jsx(Kr,{className:"h-3 w-3"})," Replay"]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",size:"sm",onClick:()=>u(v),children:e.jsx(Ya,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"outline",size:"sm",onClick:async()=>{await Xi(`Remove "${v.title}"?`)&&a.mutate(v.id)},children:e.jsx(Sn,{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(B,{onClick:d,children:[e.jsx(rn,{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(ve,{className:"border-dashed",children:e.jsxs(Me,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(Qd,{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(v=>e.jsx(y,{e:v},v.id))]}),f.length>0&&e.jsxs("section",{className:"space-y-3",children:[e.jsxs("h3",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:["Past (",f.length,") — add replay links so members can catch up"]}),f.map(v=>e.jsx(y,{e:v},v.id))]})]}),e.jsx(Ls,{open:i,onOpenChange:l,children:e.jsxs(Ps,{className:"max-h-[85vh] max-w-2xl overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Ds,{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(J,{children:"Title"}),e.jsx(xe,{placeholder:"Week 1 Mastermind — Content that converts",value:o.title,onChange:v=>c({...o,title:v.target.value})})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Type"}),e.jsxs(is,{value:o.event_kind,onValueChange:v=>c({...o,event_kind:v}),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsx(as,{children:xQs.map(v=>e.jsx(He,{value:v.value,children:v.label},v.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Host / speaker"}),e.jsx(xe,{value:o.speaker,onChange:v=>c({...o,speaker:v.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Starts (your local time)"}),e.jsx(xe,{type:"datetime-local",value:o.starts_at,onChange:v=>c({...o,starts_at:v.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Length (minutes)"}),e.jsx(xe,{type:"number",value:o.duration_minutes,onChange:v=>c({...o,duration_minutes:v.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Zoom / meeting link"}),e.jsx(xe,{placeholder:"https://us02web.zoom.us/j/1234567890?pwd=…",value:o.meeting_link,onChange:v=>c({...o,meeting_link:v.target.value})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Members only see this after they're enrolled. A recurring Zoom link can be reused on every session."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Replay link (after the call)"}),e.jsx(xe,{placeholder:"YouTube, Vimeo, Loom or Zoom cloud recording URL",value:o.replay_url,onChange:v=>c({...o,replay_url:v.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"What we'll cover"}),e.jsx(Ms,{rows:3,value:o.description,onChange:v=>c({...o,description:v.target.value})})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border border-border/60 p-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Visible to members"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Turn off to draft a session privately."})]}),e.jsx(fn,{checked:o.is_published,onCheckedChange:v=>c({...o,is_published:v})})]})]}),e.jsx(yr,{children:e.jsxs(B,{onClick:h,disabled:r.isPending,children:[r.isPending&&e.jsx(Ct,{className:"mr-1.5 h-4 w-4 animate-spin"}),o.id?"Save session":"Add session"]})})]})})]})},Nyt={title:"",summary:"",week_id:"none",duration_minutes:"",video_url:"",worksheet_url:"",action_assignment:"",status:"published",sort_order:0},vQs=({programId:s})=>{const{data:t,isLoading:n}=iUs(s),r=(t==null?void 0:t.lessons)||[],a=(t==null?void 0:t.weeks)||[],{data:i=[]}=Izt(s),l=oUs(s),o=lUs(),[c,d]=_.useState(!1),[u,h]=_.useState({...Nyt}),[m,p]=_.useState(!1),f=_.useRef(null),y=async C=>{if(f.current&&(f.current.value=""),!!C){if(!C.type.startsWith("video/"))return se.error("Please choose a video file");if(C.size>500*1024*1024)return se.error("Video must be under 500MB");p(!0);try{const E=C.name.split(".").pop()||"mp4",P=`lessons/${crypto.randomUUID()}.${E}`,{error:M}=await q.storage.from("program-assets").upload(P,C,{contentType:C.type,upsert:!1});if(M)throw M;const{data:I,error:D}=await q.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(O=>({...O,video_url:I.signedUrl})),se.success("Video uploaded")}catch(E){se.error((E==null?void 0:E.message)||"Upload failed")}finally{p(!1)}}},v=()=>{h({...Nyt,sort_order:r.length}),d(!0)},g=C=>{h({id:C.id,title:C.title,summary:C.summary||"",week_id:C.week_id||"none",duration_minutes:C.duration_minutes??"",video_url:C.video_url||"",worksheet_url:C.worksheet_url||"",action_assignment:C.action_assignment||"",status:C.status,sort_order:C.sort_order}),d(!0)},b=async()=>{if(!u.title.trim())return se.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)},j=C=>{const E=a.find(P=>P.id===C);return E?`Week ${E.week_number}`:"Unassigned"},S=Pzt(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(B,{onClick:v,children:[e.jsx(rn,{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(ve,{className:"border-dashed",children:e.jsxs(Me,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(dm,{className:"h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"font-medium",children:"No on-demand videos yet"}),e.jsx("p",{className:"max-w-md text-sm text-muted-foreground",children:"Add training videos members can watch any time — assign each one to a week to build the roadmap."})]})}):e.jsx("div",{className:"space-y-3",children:r.map(C=>e.jsx(ve,{className:"border-border/60",children:e.jsxs(Me,{className:"flex flex-wrap items-start justify-between gap-4 p-5",children:[e.jsxs("div",{className:"min-w-0 space-y-1.5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"font-medium",children:C.title}),e.jsx(Oe,{variant:"secondary",children:j(C.week_id)}),C.status!=="published"&&e.jsx(Oe,{variant:"outline",className:"capitalize",children:C.status}),C.duration_minutes?e.jsxs("span",{className:"text-xs text-muted-foreground",children:[C.duration_minutes," min"]}):null]}),C.summary&&e.jsx("p",{className:"max-w-2xl text-sm text-muted-foreground",children:C.summary}),e.jsxs("div",{className:"flex flex-wrap gap-3 pt-1 text-xs",children:[C.video_url?e.jsxs("a",{className:"inline-flex items-center gap-1 text-primary hover:underline",href:C.video_url,target:"_blank",rel:"noreferrer",children:[e.jsx(wr,{className:"h-3 w-3"})," Video"]}):e.jsx("span",{className:"text-muted-foreground",children:"No video link"}),C.worksheet_url&&e.jsxs("a",{className:"inline-flex items-center gap-1 text-primary hover:underline",href:C.worksheet_url,target:"_blank",rel:"noreferrer",children:[e.jsx(wr,{className:"h-3 w-3"})," Worksheet"]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",size:"sm",onClick:()=>g(C),children:e.jsx(Ya,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"outline",size:"sm",onClick:async()=>{await Xi(`Remove "${C.title}"?`)&&o.mutate(C.id)},children:e.jsx(Sn,{className:"h-3.5 w-3.5"})})]})]})},C.id))}),e.jsx(Ls,{open:c,onOpenChange:d,children:e.jsxs(Ps,{className:"max-h-[85vh] max-w-2xl overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Ds,{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(J,{children:"Title"}),e.jsx(xe,{placeholder:"How to script a 30-second listing reel",value:u.title,onChange:C=>h({...u,title:C.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Video link"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{placeholder:"https://youtu.be/… , Vimeo or Loom URL",value:u.video_url,onChange:C=>h({...u,video_url:C.target.value})}),e.jsxs(B,{type:"button",variant:"outline",className:"shrink-0",disabled:m,onClick:()=>{var C;return(C=f.current)==null?void 0:C.click()},children:[m?e.jsx(Ct,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(Oa,{className:"mr-1.5 h-4 w-4"}),m?"Uploading…":"Upload"]}),e.jsx("input",{ref:f,type:"file",accept:"video/*",className:"hidden",onChange:C=>{var E;return y((E=C.target.files)==null?void 0:E[0])}})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Paste a YouTube / Vimeo / Loom link, or upload an MP4 (up to 500MB) hosted by LevelUp."}),u.video_url&&!S&&!EJ(u.video_url)&&e.jsx("p",{className:"text-xs text-muted-foreground",children:`We can't embed this link — members will get an "Open video" button instead.`})]}),S&&e.jsx("div",{className:"overflow-hidden rounded-lg border border-border/60",children:e.jsx("iframe",{src:S,title:"Video preview",className:"aspect-video w-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; picture-in-picture",allowFullScreen:!0})}),!S&&EJ(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(J,{children:"Week"}),e.jsxs(is,{value:u.week_id,onValueChange:C=>h({...u,week_id:C}),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"none",children:"Unassigned (library)"}),a.map(C=>e.jsxs(He,{value:C.id,children:["Week ",C.week_number," — ",C.title]},C.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Length (minutes)"}),e.jsx(xe,{type:"number",value:u.duration_minutes,onChange:C=>h({...u,duration_minutes:C.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Status"}),e.jsxs(is,{value:u.status,onValueChange:C=>h({...u,status:C}),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"published",children:"Published (visible)"}),e.jsx(He,{value:"draft",children:"Draft (hidden)"}),e.jsx(He,{value:"archived",children:"Archived"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Order"}),e.jsx(xe,{type:"number",value:u.sort_order,onChange:C=>h({...u,sort_order:C.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Summary"}),e.jsx(Ms,{rows:3,value:u.summary,onChange:C=>h({...u,summary:C.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Worksheet / download link"}),i.length>0&&e.jsxs(is,{value:"",onValueChange:C=>{const E=i.find(M=>M.id===C),P=E?oae(E):null;P?h({...u,worksheet_url:P}):se.error("That resource has no file or link yet")},children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Choose an uploaded program resource…"})}),e.jsx(as,{children:i.map(C=>e.jsx(He,{value:C.id,children:C.title},C.id))})]}),e.jsx(xe,{placeholder:"Or paste a link",value:u.worksheet_url,onChange:C=>h({...u,worksheet_url:C.target.value})}),u.worksheet_url&&e.jsxs("a",{href:u.worksheet_url,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(wr,{className:"h-3 w-3"})," Preview worksheet"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Action assignment"}),e.jsx(Ms,{rows:2,placeholder:"Post one reel using this hook before your next mastermind.",value:u.action_assignment,onChange:C=>h({...u,action_assignment:C.target.value})})]})]}),e.jsx(yr,{children:e.jsxs(B,{onClick:b,disabled:l.isPending,children:[l.isPending&&e.jsx(Ct,{className:"mr-1.5 h-4 w-4 animate-spin"}),u.id?"Save video":"Add video"]})})]})})]})},kyt={title:"",description:"",category:"Resources",resource_kind:"pdf",url:"",file_path:"",status:"published",sort_order:0},bQs=({programId:s})=>{const{data:t=[],isLoading:n}=Izt(s),r=cUs(s),a=dUs(),[i,l]=_.useState(!1),[o,c]=_.useState({...kyt}),[d,u]=_.useState(!1),h=_.useRef(null),m=Array.from(new Set(t.map(g=>g.category))).filter(Boolean),p=()=>{c({...kyt,sort_order:t.length}),l(!0)},f=g=>{c({id:g.id,title:g.title,description:g.description||"",category:g.category||"Resources",resource_kind:g.resource_kind,url:g.url||"",file_path:g.file_path||"",status:g.status,sort_order:g.sort_order}),l(!0)},y=async g=>{if(!(!g||!s)){if(g.size>50*1024*1024)return se.error("File must be under 50MB");u(!0);try{const b=g.name.split(".").pop()||"pdf",j=`programs/${s}/resources/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${b}`,{error:S}=await q.storage.from(_W).upload(j,g,{contentType:g.type||"application/pdf",upsert:!1});if(S)throw S;c(C=>({...C,file_path:j,url:"",title:C.title||g.name.replace(/\.[^.]+$/,""),resource_kind:g.type==="application/pdf"?"pdf":C.resource_kind})),se.success("File uploaded")}catch(b){se.error(b.message||"Upload failed")}finally{u(!1),h.current&&(h.current.value="")}}},v=async()=>{if(!o.title.trim())return se.error("Give the resource a title");if(!o.file_path&&!o.url.trim())return se.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(B,{onClick:p,children:[e.jsx(rn,{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(ve,{className:"border-dashed",children:e.jsxs(Me,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(Fr,{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(g=>{const b=oae(g);return e.jsx(ve,{className:"border-border/60",children:e.jsxs(Me,{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:g.title}),e.jsx(Oe,{variant:"secondary",children:g.category}),e.jsx(Oe,{variant:"outline",className:"capitalize",children:g.resource_kind.replace("_"," ")}),g.status!=="published"&&e.jsx(Oe,{variant:"outline",className:"capitalize",children:g.status})]}),g.description&&e.jsx("p",{className:"max-w-2xl text-sm text-muted-foreground",children:g.description}),b&&e.jsxs("button",{type:"button",onClick:()=>TJ(g),className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(wr,{className:"h-3 w-3"})," Open"]})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>f(g),children:e.jsx(Ya,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:async()=>{await Xi(`Remove "${g.title}"?`)&&a.mutate(g)},children:e.jsx(Sn,{className:"h-4 w-4 text-destructive"})})]})]})},g.id)})}),e.jsx(Ls,{open:i,onOpenChange:l,children:e.jsxs(Ps,{className:"max-w-lg",children:[e.jsx(Os,{children:e.jsx(Ds,{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(J,{children:"Title"}),e.jsx(xe,{value:o.title,onChange:g=>c({...o,title:g.target.value}),placeholder:"90-Day Content Calendar"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Description"}),e.jsx(Ms,{rows:2,value:o.description,onChange:g=>c({...o,description:g.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(J,{children:"Category"}),e.jsx(xe,{value:o.category,onChange:g=>c({...o,category:g.target.value}),placeholder:"Getting started",list:"program-resource-categories"}),e.jsx("datalist",{id:"program-resource-categories",children:m.map(g=>e.jsx("option",{value:g},g))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Type"}),e.jsxs(is,{value:o.resource_kind,onValueChange:g=>c({...o,resource_kind:g}),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsx(as,{children:Lzt.map(g=>e.jsx(He,{value:g.value,children:g.label},g.value))})]})]})]}),e.jsxs("div",{className:"space-y-2 rounded-lg border p-3",children:[e.jsx(J,{children:"File"}),e.jsx("input",{ref:h,type:"file",className:"hidden",accept:".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.csv,.zip,image/*",onChange:g=>{var b;return y((b=g.target.files)==null?void 0:b[0])}}),o.file_path?e.jsxs("div",{className:"flex items-center justify-between gap-2 text-sm",children:[e.jsx("span",{className:"truncate",children:o.file_path.split("/").pop()}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>c({...o,file_path:""}),children:"Remove"})]}):e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>{var g;return(g=h.current)==null?void 0:g.click()},disabled:d,children:[d?e.jsx(Ct,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(Oa,{className:"mr-1.5 h-4 w-4"}),"Upload PDF or document"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Or paste an external link instead (Canva, Google Doc, Notion…)."}),e.jsx(xe,{value:o.url,onChange:g=>c({...o,url:g.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(J,{children:"Status"}),e.jsxs(is,{value:o.status,onValueChange:g=>c({...o,status:g}),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"published",children:"Published (visible)"}),e.jsx(He,{value:"draft",children:"Draft (hidden)"}),e.jsx(He,{value:"archived",children:"Archived"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Sort order"}),e.jsx(xe,{type:"number",value:o.sort_order,onChange:g=>c({...o,sort_order:g.target.value})})]})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsxs(B,{onClick:v,disabled:r.isPending||d,children:[r.isPending&&e.jsx(Ct,{className:"mr-1.5 h-4 w-4 animate-spin"})," Save resource"]})]})]})})]})},_Qs=({programId:s})=>{const{data:t=[],isLoading:n}=xUs(s),r=_.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(cn,{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(ve,{children:e.jsxs(Me,{className:"flex items-center gap-3 p-4",children:[e.jsx($4,{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(ve,{children:e.jsxs(Me,{className:"flex items-center gap-3 p-4",children:[e.jsx(In,{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(ve,{children:e.jsx(Me,{className:"flex items-center gap-3 p-4",children:e.jsxs(Oe,{variant:"secondary",children:[t.filter(l=>l.notified_at).length," notified"]})})})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",disabled:!a,onClick:()=>{navigator.clipboard.writeText(a),se.success("Emails copied")},children:[e.jsx(Ia,{className:"mr-2 h-4 w-4"})," Copy emails"]}),e.jsxs(B,{variant:"outline",size:"sm",disabled:!t.length,onClick:i,children:[e.jsx(li,{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(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"Member"}),e.jsx(Pt,{children:"Email"}),e.jsx(Pt,{children:"Phone"}),e.jsx(Pt,{children:"Brokerage"}),e.jsx(Pt,{children:"Joined"})]})}),e.jsx(Ka,{children:t.map(l=>e.jsxs(pn,{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:xu(l.created_at)})]},l.id))})]})})]})},Syt={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:""},wQs=()=>{const s=Bt(),[t,n]=_.useState(null),[r,a]=_.useState(!1),[i,l]=_.useState({...Syt}),[o,c]=_.useState(!1),[d,u]=_.useState(!1),[h,m]=_.useState(null),{data:p=[],isLoading:f}=at({queryKey:["admin-programs"],queryFn:async()=>{const{data:M,error:I}=await q.from("programs").select("*").order("created_at",{ascending:!1});if(I)throw I;return M||[]}}),y=p.find(M=>M.id===t)||p[0]||null,{data:v=[]}=at({queryKey:["admin-program-enrollments",y==null?void 0:y.id],enabled:!!(y!=null&&y.id),queryFn:async()=>{const{data:M,error:I}=await q.from("program_enrollments").select("*").eq("program_id",y.id).order("created_at",{ascending:!1});if(I)throw I;const D=(M||[]).map(G=>G.user_id),{data:O}=D.length?await q.from("profiles").select("id, name, email").in("id",D):{data:[]},V=new Map((O||[]).map(G=>[G.id,G]));return(M||[]).map(G=>({...G,profile:V.get(G.user_id)}))}}),{data:g=[]}=at({queryKey:["admin-program-intakes",y==null?void 0:y.id],enabled:!!(y!=null&&y.id),queryFn:async()=>{const{data:M,error:I}=await q.from("program_intake_responses").select("*").eq("program_id",y.id);if(I)throw I;return M||[]}}),{data:b=[]}=at({queryKey:["admin-program-audit",y==null?void 0:y.id],enabled:!!(y!=null&&y.id),queryFn:async()=>{const{data:M,error:I}=await q.from("program_audit_logs").select("*").eq("program_id",y.id).order("created_at",{ascending:!1}).limit(100);if(I)throw I;return M||[]}}),j=async()=>{c(!0);try{const M={...i,slug:i.slug||i.name.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""),kickoff_at:i.kickoff_at||null,charge_at:i.charge_at||null,enrollment_close_at:i.enrollment_close_at||null},{error:I}=await q.from("programs").insert(M);if(I)throw I;se.success("Program created"),a(!1),l({...Syt}),s.invalidateQueries({queryKey:["admin-programs"]})}catch(M){se.error(M.message||"Could not create the program")}finally{c(!1)}},S=async M=>{if(!y)return;const{error:I}=await q.from("programs").update(M).eq("id",y.id);if(I)return se.error(I.message);s.invalidateQueries({queryKey:["admin-programs"]})},C=async(M,I)=>{const{error:D}=await q.from("program_enrollments").update(I).eq("id",M);if(D)return se.error(D.message);se.success("Enrollment updated"),s.invalidateQueries({queryKey:["admin-program-enrollments"]})},E=async M=>{u(!0);const{data:I,error:D}=await q.functions.invoke("program-charge-due",{body:M?{enrollment_id:M}:{}});if(u(!1),D||I!=null&&I.error)return se.error((I==null?void 0:I.error)||(D==null?void 0:D.message));se.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(zs,{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(B,{variant:"outline",onClick:()=>E(),disabled:d,children:[d?e.jsx(Ct,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(_y,{className:"mr-1.5 h-4 w-4"}),"Run due charges"]}),e.jsxs(Ls,{open:r,onOpenChange:a,children:[e.jsx(nl,{asChild:!0,children:e.jsxs(B,{children:[e.jsx(rn,{className:"mr-1.5 h-4 w-4"})," New program"]})}),e.jsxs(Ps,{className:"max-h-[85vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Ds,{children:"Create a program"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Name"}),e.jsx(xe,{value:i.name,onChange:M=>l({...i,name:M.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Slug (URL)"}),e.jsx(xe,{placeholder:"reel-estate-90",value:i.slug,onChange:M=>l({...i,slug:M.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Subtitle"}),e.jsx(xe,{value:i.subtitle,onChange:M=>l({...i,subtitle:M.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Description"}),e.jsx(Ms,{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(J,{children:"One-time price (USD)"}),e.jsx(xe,{type:"number",value:i.price_cents/100,onChange:M=>l({...i,price_cents:Math.round(Number(M.target.value)*100)})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Charged one time for the full program — never recurring."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Seats"}),e.jsx(xe,{type:"number",value:i.capacity,onChange:M=>l({...i,capacity:Number(M.target.value)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Weeks"}),e.jsx(xe,{type:"number",value:i.duration_weeks,onChange:M=>l({...i,duration_weeks:Number(M.target.value)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Videos per week"}),e.jsx(xe,{type:"number",value:i.weekly_video_goal,onChange:M=>l({...i,weekly_video_goal:Number(M.target.value)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Billing"}),e.jsxs(is,{value:i.payment_mode,onValueChange:M=>l({...i,payment_mode:M}),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"delayed",children:"Save card, charge later"}),e.jsx(He,{value:"immediate",children:"Charge at checkout"}),e.jsx(He,{value:"free",children:"Free / included"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Kickoff"}),e.jsx(xe,{type:"datetime-local",value:i.kickoff_at,onChange:M=>l({...i,kickoff_at:M.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Charge date"}),e.jsx(xe,{type:"datetime-local",value:i.charge_at,onChange:M=>l({...i,charge_at:M.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Enrollment closes"}),e.jsx(xe,{type:"datetime-local",value:i.enrollment_close_at,onChange:M=>l({...i,enrollment_close_at:M.target.value})})]})]})]}),e.jsx(yr,{children:e.jsxs(B,{onClick:j,disabled:o||!i.name,children:[o&&e.jsx(Ct,{className:"mr-1.5 h-4 w-4 animate-spin"})," Create"]})})]})]})]})]}),f?e.jsx(cn,{className:"h-40 w-full rounded-xl"}):p.length===0?e.jsx(ve,{className:"border-dashed",children:e.jsx(Me,{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(B,{variant:(y==null?void 0:y.id)===M.id?"default":"outline",size:"sm",onClick:()=>n(M.id),children:[M.name,e.jsx(Oe,{variant:"secondary",className:"ml-2 capitalize",children:M.status})]},M.id))}),y&&e.jsxs(Yr,{defaultValue:"overview",children:[e.jsxs(Zr,{className:"flex w-full flex-wrap justify-start",children:[e.jsx(Ht,{value:"overview",children:"Overview"}),e.jsx(Ht,{value:"details",children:"Details & pricing"}),e.jsx(Ht,{value:"sessions",children:"Live sessions"}),e.jsx(Ht,{value:"videos",children:"On-demand videos"}),e.jsx(Ht,{value:"resources",children:"Resources"}),e.jsx(Ht,{value:"intake-form",children:"Intake form"}),e.jsx(Ht,{value:"discounts",children:"Discount codes"}),e.jsx(Ht,{value:"experience",children:"Enrollee experience"}),e.jsx(Ht,{value:"interest",children:"Interest list"}),e.jsxs(Ht,{value:"enrollments",children:["Enrollments (",v.length,")"]}),e.jsxs(Ht,{value:"intake",children:["Intake (",g.length,")"]}),e.jsx(Ht,{value:"audit",children:"Audit"})]}),e.jsxs(Gt,{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(ve,{children:e.jsxs(Me,{className:"p-5",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Seats filled"}),e.jsxs("p",{className:"mt-1 text-2xl font-bold",children:[v.filter(M=>["reserved","scheduled_for_charge","paid","completed"].includes(M.status)).length,e.jsxs("span",{className:"text-base font-normal text-muted-foreground",children:[" / ",y.capacity]})]})]})}),e.jsx(ve,{children:e.jsxs(Me,{className:"p-5",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Paid"}),e.jsx("p",{className:"mt-1 text-2xl font-bold",children:v.filter(M=>M.status==="paid").length})]})}),e.jsx(ve,{children:e.jsxs(Me,{className:"p-5",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Failed payments"}),e.jsx("p",{className:"mt-1 text-2xl font-bold",children:v.filter(M=>M.status==="payment_failed").length})]})}),e.jsx(ve,{children:e.jsxs(Me,{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:Tf(v.filter(M=>["scheduled_for_charge","paid","completed"].includes(M.status)).reduce((M,I)=>M+(I.amount_cents||0),0),y.currency)})]})})]}),e.jsx(ve,{children:e.jsxs(Me,{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(fn,{checked:y.status==="published",onCheckedChange:M=>S({status:M?"published":"draft"})})]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4 border-t border-border/60 pt-5",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Feature it"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Pins the program to the top."})]}),e.jsx(fn,{checked:y.is_featured,onCheckedChange:M=>S({is_featured:M})})]}),e.jsxs("div",{className:"grid gap-4 border-t border-border/60 pt-5 sm:grid-cols-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"One-time price"}),e.jsx("p",{className:"font-medium",children:Tf(y.price_cents,y.currency)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Kickoff"}),e.jsx("p",{className:"font-medium",children:xu(y.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:xu(y.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(Gt,{value:"details",className:"mt-6",children:e.jsx(rQs,{program:y,onSaved:()=>s.invalidateQueries({queryKey:["admin-programs"]})})}),e.jsx(Gt,{value:"sessions",className:"mt-6",children:e.jsx(yQs,{programId:y.id})}),e.jsx(Gt,{value:"videos",className:"mt-6",children:e.jsx(vQs,{programId:y.id})}),e.jsx(Gt,{value:"resources",className:"mt-6",children:e.jsx(bQs,{programId:y.id})}),e.jsx(Gt,{value:"discounts",className:"mt-6",children:e.jsx(oQs,{program:y})}),e.jsx(Gt,{value:"intake-form",className:"mt-6",children:e.jsx(uQs,{program:y,onSaved:()=>s.invalidateQueries({queryKey:["admin-programs"]})})}),e.jsx(Gt,{value:"experience",className:"mt-6",children:e.jsx(lQs,{program:y})}),e.jsx(Gt,{value:"interest",className:"mt-6",children:e.jsx(_Qs,{programId:y.id})}),e.jsx(Gt,{value:"enrollments",className:"mt-6",children:e.jsx(ve,{children:e.jsx(Me,{className:"overflow-x-auto p-0",children:e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"Member"}),e.jsx(Pt,{children:"Status"}),e.jsx(Pt,{children:"Charge date"}),e.jsx(Pt,{children:"Amount"}),e.jsx(Pt,{children:"Access"}),e.jsx(Pt,{className:"text-right",children:"Actions"})]})}),e.jsxs(Ka,{children:[v.length===0&&e.jsx(pn,{children:e.jsxs(gt,{colSpan:6,className:"py-10 text-center text-sm text-muted-foreground",children:[e.jsx(In,{className:"mx-auto mb-2 h-5 w-5"}),"No enrollments yet"]})}),v.map(M=>{var I,D;return e.jsxs(pn,{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(Oe,{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:xu(M.charge_scheduled_at)||"—"}),e.jsx(gt,{className:"text-sm",children:Tf(M.amount_cents,M.currency)}),e.jsx(gt,{children:e.jsx(fn,{checked:M.access_override,onCheckedChange:O=>C(M.id,{access_override:O})})}),e.jsxs(gt,{className:"space-x-2 text-right",children:[["scheduled_for_charge","payment_failed"].includes(M.status)&&e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>E(M.id),disabled:d,children:[e.jsx(uo,{className:"mr-1.5 h-3.5 w-3.5"})," Charge now"]}),!["canceled","refunded"].includes(M.status)&&e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>C(M.id,{status:"canceled",canceled_at:new Date().toISOString()}),children:"Cancel"})]})]},M.id)})]})]})})})}),e.jsx(Gt,{value:"intake",className:"mt-6",children:e.jsx(fQs,{program:y})}),e.jsx(Gt,{value:"audit",className:"mt-6",children:e.jsx(ve,{children:e.jsxs(Me,{className:"space-y-2 p-5 text-sm",children:[b.length===0&&e.jsx("p",{className:"text-muted-foreground",children:"No activity yet."}),b.map(M=>e.jsxs("div",{className:"flex flex-wrap items-center gap-2 border-b border-border/40 py-2 last:border-0",children:[e.jsx(Oe,{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:xu(M.created_at,!0)})]},M.id))]})})})]}),y&&e.jsx(iQs,{program:y,enrollment:h,open:!!h,onOpenChange:M=>!M&&m(null),onUpdated:()=>s.invalidateQueries({queryKey:["admin-program-enrollments"]})})]})]})})},jQs=()=>{const{user:s}=hs(),[t,n]=_.useState(""),[r,a]=_.useState("all"),{data:i=[]}=at({queryKey:["academy-categories"],queryFn:async()=>{const{data:m,error:p}=await q.from("academy_categories").select("*").order("sort_order",{ascending:!0});if(p)throw p;return m}}),{data:l=[],isLoading:o}=at({queryKey:["academy-videos"],queryFn:async()=>{const{data:m,error:p}=await q.from("academy_videos").select(` *, category:academy_categories(id, name) `).eq("is_published",!0).order("publish_date",{ascending:!1});if(p)throw p;const{data:f,error:y}=await q.from("academy_resources").select("*").order("sort_order");if(y)throw y;return m.map(g=>({...g,resources:(f==null?void 0:f.filter(b=>b.video_id===g.id))||[]}))}}),{data:c=[]}=at({queryKey:["academy-video-likes"],queryFn:async()=>{const{data:m,error:p}=await q.from("academy_video_likes").select("video_id, user_id");if(p)throw p;return m}}),d=l.filter(m=>{var y;const p=t===""||m.title.toLowerCase().includes(t.toLowerCase())||((y=m.description)==null?void 0:y.toLowerCase().includes(t.toLowerCase())),f=r==="all"||m.category_id===r;return p&&f}),u=m=>c.filter(p=>p.video_id===m).length,h=m=>c.some(p=>p.video_id===m&&p.user_id===(s==null?void 0:s.id));return e.jsx(zs,{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(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search videos...",value:t,onChange:m=>n(m.target.value),className:"pl-10"})]})}),e.jsx(Yr,{value:r,onValueChange:a,children:e.jsxs(Zr,{className:"w-full justify-start flex-wrap h-auto gap-2 bg-transparent p-0",children:[e.jsx(Ht,{value:"all",className:"data-[state=active]:bg-primary data-[state=active]:text-primary-foreground",children:"All Videos"}),i.map(m=>e.jsx(Ht,{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(ve,{children:e.jsxs(Me,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Kr,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold",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(ir,{to:`/academy/${m.id}`,children:e.jsxs(ve,{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(Kr,{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(Jd,{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(Gr,{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(St,{className:"text-lg line-clamp-2",children:m.title})}),m.category&&e.jsx(Oe,{variant:"secondary",className:"w-fit",children:m.category.name})]}),e.jsxs(Me,{className:"pt-0",children:[m.description&&e.jsx(kn,{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(Fg,{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(Fr,{className:"h-4 w-4"}),m.resources.length]})]})]})]})},m.id))})]})})};function _qt({resourceType:s,resourceId:t}){const{data:n=[]}=at({queryKey:["linked-templates",s,t],queryFn:async()=>{if(s==="academy_video"){const{data:r,error:a}=await q.from("academy_video_templates").select("template_id, canva_templates:template_id(id, name, preview_image_url)").eq("video_id",t);if(a)throw a;return(r||[]).map(i=>i.canva_templates).filter(Boolean)}else{const{data:r,error:a}=await q.from("resource_kit_templates").select("template_id, canva_templates:template_id(id, name, preview_image_url)").eq("kit_id",t);if(a)throw a;return(r||[]).map(i=>i.canva_templates).filter(Boolean)}},enabled:!!t});return n.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-sm",children:[e.jsx(Xc,{className:"h-4 w-4"}),"Related Templates"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:n.map(r=>e.jsx(ir,{to:`/templates/${r.id}`,children:e.jsxs(Oe,{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(Xc,{className:"h-3 w-3"}),r.name]})},r.id))})]})}const NQs=(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},kQs=()=>{const{videoId:s}=Li();Fn();const{user:t,isAdmin:n}=hs(),{toast:r}=vi(),a=Bt(),{trackEngagement:i}=bW(),[l,o]=_.useState(""),{data:c,isLoading:d}=at({queryKey:["academy-video",s],queryFn:async()=>{const{data:j,error:S}=await q.from("academy_videos").select(` *, category:academy_categories(id, name) `).eq("id",s).eq("is_published",!0).single();if(S)throw S;const{data:C}=await q.from("academy_resources").select("*").eq("video_id",s).order("sort_order");return{...j,resources:C||[]}},enabled:!!s});_.useEffect(()=>{c&&i("academy_video",c.id,c.title,"view")},[c==null?void 0:c.id]);const{data:u=[]}=at({queryKey:["academy-video-likes",s],queryFn:async()=>{const{data:j,error:S}=await q.from("academy_video_likes").select("*").eq("video_id",s);if(S)throw S;return j},enabled:!!s}),{data:h=[]}=at({queryKey:["academy-video-comments",s],queryFn:async()=>{const{data:j,error:S}=await q.from("academy_video_comments").select("*").eq("video_id",s).order("created_at",{ascending:!1});if(S)throw S;const C=[...new Set(j.map(M=>M.user_id))],{data:E}=await q.from("profiles").select("id, name").in("id",C),P=new Map((E==null?void 0:E.map(M=>[M.id,M.name]))||[]);return j.map(M=>({...M,user_name:P.get(M.user_id)||"Unknown User"}))},enabled:!!s}),m=mt({mutationFn:async j=>{const{error:S}=await q.from("academy_video_comments").insert({video_id:s,user_id:t.id,content:j});if(S)throw S},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-video-comments",s]}),o(""),r({title:"Comment added!"})},onError:j=>{r({title:"Error adding comment",description:j.message,variant:"destructive"})}}),p=mt({mutationFn:async j=>{const{error:S}=await q.from("academy_video_comments").delete().eq("id",j);if(S)throw S},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-video-comments",s]}),r({title:"Comment deleted"})}}),f=mt({mutationFn:async()=>{const j=u.find(S=>S.user_id===(t==null?void 0:t.id));if(j){const{error:S}=await q.from("academy_video_likes").delete().eq("id",j.id);if(S)throw S}else{const{error:S}=await q.from("academy_video_likes").insert({video_id:s,user_id:t.id});if(S)throw S}},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-video-likes",s]})}}),y=u.some(j=>j.user_id===(t==null?void 0:t.id)),v=j=>{switch(j==null?void 0:j.toLowerCase()){case"pdf":return"📄";case"pptx":case"ppt":return"📊";case"xlsx":case"xls":return"📈";case"docx":case"doc":return"📝";case"zip":return"📦";default:return"📁"}},g=j=>j.split(" ").map(S=>S[0]).join("").toUpperCase().slice(0,2),b=j=>{j.preventDefault(),!(!l.trim()||!t)&&m.mutate(l.trim())};return d?e.jsx(zs,{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(zs,{title:c.title,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx(B,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(ir,{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:NQs(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(Kr,{className:"h-16 w-16 opacity-50"}),e.jsx(B,{variant:"secondary",asChild:!0,children:e.jsxs("a",{href:c.video_url,target:"_blank",rel:"noopener noreferrer",className:"gap-2",children:[e.jsx(wr,{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(Oe,{variant:"secondary",children:c.category.name})]}),e.jsxs("div",{className:"flex gap-2",children:[n&&e.jsx(B,{variant:"outline",className:"gap-2 rounded-full",asChild:!0,children:e.jsxs(ir,{to:`/admin/academy?edit=${c.id}`,children:[e.jsx(Ya,{className:"h-4 w-4"}),e.jsx("span",{children:"Edit"})]})}),e.jsx(jW,{resourceType:"academy_video",resourceId:c.id,resourceTitle:c.title}),e.jsxs(B,{variant:y?"default":"outline",className:"gap-2 w-fit",onClick:()=>f.mutate(),disabled:!t||f.isPending,children:[e.jsx(Fg,{className:`h-4 w-4 ${y?"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(ve,{children:e.jsxs(Me,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Fr,{className:"h-4 w-4"}),"Resources"]}),e.jsx("div",{className:"grid gap-2",children:c.resources.map(j=>e.jsxs("a",{href:j.file_url,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-3 p-3 rounded-lg border hover:bg-muted transition-colors",children:[e.jsx("span",{className:"text-2xl",children:v(j.file_type)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:j.title}),e.jsx("p",{className:"text-xs text-muted-foreground uppercase",children:j.file_type})]}),e.jsx(li,{className:"h-4 w-4 text-muted-foreground"})]},j.id))})]})}),e.jsx(_qt,{resourceType:"academy_video",resourceId:c.id}),e.jsx(wc,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(Ou,{className:"h-5 w-5"}),"Comments (",h.length,")"]}),t?e.jsxs("form",{onSubmit:b,className:"flex gap-2",children:[e.jsx(Ms,{placeholder:"Add a comment...",value:l,onChange:j=>o(j.target.value),className:"min-h-[80px] resize-none flex-1"}),e.jsx(B,{type:"submit",size:"icon",className:"h-10 w-10",disabled:!l.trim()||m.isPending,children:e.jsx(Or,{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(ve,{children:e.jsx(Me,{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(j=>e.jsx(ve,{children:e.jsx(Me,{className:"pt-4 pb-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(ja,{className:"h-10 w-10 flex-shrink-0",children:e.jsx(Na,{className:"text-sm",children:g(j.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:j.user_name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:Ed(new Date(j.created_at),{addSuffix:!0})}),j.user_id===(t==null?void 0:t.id)&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>p.mutate(j.id),children:e.jsx(Sn,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:j.content})]})]})})},j.id))})]})]})}):e.jsx(zs,{title:"Academy",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Kr,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold",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(B,{asChild:!0,className:"mt-4",children:e.jsx(ir,{to:"/academy",children:"Back to Academy"})})]})})},AB="https://dashboard.relevelup.com",SQs=(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},CQs=[{icon:om,title:"100+ Training Videos",desc:"On-demand LevelUp Academy content covering lead gen, listings, buyer conversion, marketing, and more."},{icon:nf,title:"Marketing Studio & Tools",desc:"AI-powered marketing tools, listing videos, landing pages, and social content — done for you."},{icon:In,title:"Coaching & Community",desc:"Live coaching sessions, private community, and a network of top-performing agents."},{icon:wl,title:"Business Scorecard",desc:"Track your deals, GCI, and pipeline in one dashboard built for real estate."}];function AQs(){var i;const{slug:s}=Li(),{data:t,isLoading:n,error:r}=at({queryKey:["public-academy-video",s],queryFn:async()=>{if(!s)return null;const{data:l,error:o}=await q.from("academy_videos").select("id, title, description, video_url, video_type, thumbnail_url, duration, category:academy_categories(name)").eq("public_slug",s).eq("is_public",!0).maybeSingle();if(o)throw o;return l},enabled:!!s});_.useEffect(()=>{if(t&&s){q.rpc("increment_academy_public_view",{_slug:s}),document.title=`${t.title} | LevelUp Academy`;const l=(t.description||"").replace(/<[^>]+>/g,"").slice(0,155),o=document.querySelector('meta[name="description"]');o&&o.setAttribute("content",l||"Free training preview from LevelUp Academy.");const c=`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/academy-og?slug=${encodeURIComponent(s)}&mode=image`;let d=document.querySelector('meta[property="og:image"]');d||(d=document.createElement("meta"),d.setAttribute("property","og:image"),document.head.appendChild(d)),d.setAttribute("content",c)}},[t,s]);const a=_.useMemo(()=>t?SQs(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:AB,children:e.jsx(B,{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(un,{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:AB,children:e.jsx(B,{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(Oe,{className:"bg-[#406E71]/20 text-[#7ec0c3] border-[#406E71]/40 hover:bg-[#406E71]/30",children:[e.jsx(om,{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(Sy,{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:AB,className:"w-full sm:w-auto",children:e.jsxs(B,{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(La,{className:"w-4 h-4 ml-2"})]})}),e.jsx("a",{href:AB,className:"w-full sm:w-auto",children:e.jsx(B,{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:CQs.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(Er,{className:"w-4 h-4 text-[#7ec0c3]"})," Trusted by top producers"]}),e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Er,{className:"w-4 h-4 text-[#7ec0c3]"})," New training weekly"]}),e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Er,{className:"w-4 h-4 text-[#7ec0c3]"})," Cancel anytime"]})]}),e.jsx("div",{className:"text-center",children:e.jsx("a",{href:AB,children:e.jsxs(B,{size:"lg",className:"bg-[#406E71] hover:bg-[#4d8285] text-white h-12 px-10 shadow-lg",children:["Get Started at LevelUp",e.jsx(La,{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:AB,className:"hover:text-[#7ec0c3]",children:"dashboard.relevelup.com"})]})]})}function EQs(){const s=Fn(),[t,n]=_.useState(""),{data:r,isLoading:a}=at({queryKey:["resource-kits-published"],queryFn:async()=>{const{data:p,error:f}=await q.from("resource_kits").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(f)throw f;return p}}),{data:i}=at({queryKey:["resource-kit-files-all"],queryFn:async()=>{const{data:p,error:f}=await q.from("resource_kit_files").select("*").order("sort_order",{ascending:!0});if(f)throw f;return p}}),{data:l}=at({queryKey:["resource-kit-likes-all"],queryFn:async()=>{const{data:p,error:f}=await q.from("resource_kit_likes").select("kit_id");if(f)throw f;return p}}),{data:o}=at({queryKey:["resource-kit-comments-all"],queryFn:async()=>{const{data:p,error:f}=await q.from("resource_kit_comments").select("kit_id");if(f)throw f;return p}}),c=r==null?void 0:r.filter(p=>{var f;return p.name.toLowerCase().includes(t.toLowerCase())||((f=p.description)==null?void 0:f.toLowerCase().includes(t.toLowerCase()))}),d=p=>(i==null?void 0:i.filter(f=>f.kit_id===p))||[],u=p=>(l==null?void 0:l.filter(f=>f.kit_id===p).length)||0,h=p=>(o==null?void 0:o.filter(f=>f.kit_id===p).length)||0,m=p=>{s(`/toolbox/${p}`)};return e.jsx(zs,{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(Lr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search resource kits...",value:t,onChange:p=>n(p.target.value),className:"pl-10"})]}),!a&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:[(c==null?void 0:c.length)||0," resource kit",(c==null?void 0:c.length)!==1?"s":""," available"]}),a?e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6",children:[...Array(8)].map((p,f)=>e.jsx(ve,{children:e.jsxs(Me,{className:"p-4",children:[e.jsx(cn,{className:"aspect-[4/3] w-full rounded-lg mb-4"}),e.jsx(cn,{className:"h-5 w-3/4 mb-2"}),e.jsx(cn,{className:"h-4 w-full mb-4"}),e.jsx(cn,{className:"h-4 w-2/3"})]})},f))}):(c==null?void 0:c.length)===0?e.jsxs(ve,{className:"p-12 text-center",children:[e.jsx(Nh,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No resource kits found"}),e.jsx("p",{className:"text-muted-foreground",children:t?"Try adjusting your search terms":"Check back later for new resources"})]}):e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6",children:c==null?void 0:c.map(p=>{const f=d(p.id).length,y=u(p.id),v=h(p.id);return e.jsxs(ve,{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(Nh,{className:"h-16 w-16 text-muted-foreground"})})}),e.jsxs(Me,{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:Hee(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(Fr,{className:"h-4 w-4"}),f," file",f!==1?"s":""]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Fg,{className:"h-3.5 w-3.5"}),y]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ou,{className:"h-3.5 w-3.5"}),v]})]})]})]})]},p.id)})})]})})}const TQs=()=>{const{kitId:s}=Li(),{user:t,isAdmin:n}=hs(),{toast:r}=vi(),a=Bt(),{trackEngagement:i}=bW(),[l,o]=_.useState(""),{data:c,isLoading:d}=at({queryKey:["resource-kit-detail",s],queryFn:async()=>{const{data:j,error:S}=await q.from("resource_kits").select("*").eq("id",s).eq("is_published",!0).single();if(S)throw S;const{data:C}=await q.from("resource_kit_files").select("*").eq("kit_id",s).order("sort_order"),{data:E}=await q.from("resource_kit_links").select("*").eq("kit_id",s).order("sort_order");return{...j,files:C||[],links:E||[]}},enabled:!!s});_.useEffect(()=>{c&&i("toolbox",c.id,c.name,"view")},[c==null?void 0:c.id]);const{data:u=[]}=at({queryKey:["resource-kit-likes",s],queryFn:async()=>{const{data:j,error:S}=await q.from("resource_kit_likes").select("*").eq("kit_id",s);if(S)throw S;return j},enabled:!!s}),{data:h=[]}=at({queryKey:["resource-kit-comments",s],queryFn:async()=>{const{data:j,error:S}=await q.from("resource_kit_comments").select("*").eq("kit_id",s).order("created_at",{ascending:!1});if(S)throw S;const C=[...new Set(j.map(M=>M.user_id))],{data:E}=await q.from("profiles").select("id, name").in("id",C),P=new Map((E==null?void 0:E.map(M=>[M.id,M.name]))||[]);return j.map(M=>({...M,user_name:P.get(M.user_id)||"Unknown User"}))},enabled:!!s}),m=mt({mutationFn:async j=>{const{error:S}=await q.from("resource_kit_comments").insert({kit_id:s,user_id:t.id,content:j});if(S)throw S},onSuccess:()=>{a.invalidateQueries({queryKey:["resource-kit-comments",s]}),o(""),r({title:"Comment added!"})},onError:j=>{r({title:"Error adding comment",description:j.message,variant:"destructive"})}}),p=mt({mutationFn:async j=>{const{error:S}=await q.from("resource_kit_comments").delete().eq("id",j);if(S)throw S},onSuccess:()=>{a.invalidateQueries({queryKey:["resource-kit-comments",s]}),r({title:"Comment deleted"})}}),f=mt({mutationFn:async()=>{const j=u.find(S=>S.user_id===(t==null?void 0:t.id));if(j){const{error:S}=await q.from("resource_kit_likes").delete().eq("id",j.id);if(S)throw S}else{const{error:S}=await q.from("resource_kit_likes").insert({kit_id:s,user_id:t.id});if(S)throw S}},onSuccess:()=>{a.invalidateQueries({queryKey:["resource-kit-likes",s]})}}),y=u.some(j=>j.user_id===(t==null?void 0:t.id)),v=j=>j.split(" ").map(S=>S[0]).join("").toUpperCase().slice(0,2),g=j=>j?j<1024?j+" B":j<1024*1024?(j/1024).toFixed(1)+" KB":(j/(1024*1024)).toFixed(1)+" MB":"",b=j=>{j.preventDefault(),!(!l.trim()||!t)&&m.mutate(l.trim())};return d?e.jsx(zs,{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(zs,{title:c.name,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx(B,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(ir,{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(B,{variant:"outline",className:"gap-2 rounded-full",asChild:!0,children:e.jsxs(ir,{to:`/admin/toolbox?edit=${c.id}`,children:[e.jsx(Ya,{className:"h-4 w-4"}),e.jsx("span",{children:"Edit"})]})}),e.jsx(jW,{resourceType:"resource_kit",resourceId:c.id,resourceTitle:c.name,size:"default",className:"rounded-full"}),e.jsxs(B,{variant:y?"default":"outline",className:"gap-2 rounded-full",onClick:()=>f.mutate(),disabled:!t||f.isPending,children:[e.jsx(Fg,{className:`h-4 w-4 ${y?"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(ve,{children:e.jsxs(Me,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Fr,{className:"h-4 w-4"}),"Included Resources (",c.files.length,")"]}),e.jsx("div",{className:"grid gap-2",children:c.files.map(j=>e.jsxs("a",{href:j.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(Fr,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:j.name}),j.file_size&&e.jsx("div",{className:"text-xs text-muted-foreground",children:g(j.file_size)})]})]}),e.jsx(li,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors"})]},j.id))})]})}),c.links&&c.links.length>0&&e.jsx(ve,{children:e.jsxs(Me,{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"}),"Canva Templates (",c.links.length,")"]}),e.jsx("div",{className:"grid gap-2",children:c.links.map(j=>e.jsxs("a",{href:j.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(wr,{className:"h-4 w-4 text-purple-600"})}),e.jsx("div",{className:"font-medium text-sm",children:j.title})]}),e.jsx("span",{className:"text-xs text-muted-foreground group-hover:text-primary transition-colors",children:"Open in Canva"})]},j.id))})]})}),e.jsx(_qt,{resourceType:"resource_kit",resourceId:c.id}),e.jsx(wc,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(Ou,{className:"h-5 w-5"}),"Comments (",h.length,")"]}),t?e.jsxs("form",{onSubmit:b,className:"flex gap-2",children:[e.jsx(Ms,{placeholder:"Add a comment...",value:l,onChange:j=>o(j.target.value),className:"min-h-[80px] resize-none flex-1"}),e.jsx(B,{type:"submit",size:"icon",className:"h-10 w-10",disabled:!l.trim()||m.isPending,children:e.jsx(Or,{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(ve,{children:e.jsx(Me,{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(j=>e.jsx(ve,{children:e.jsx(Me,{className:"pt-4 pb-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(ja,{className:"h-10 w-10 flex-shrink-0",children:e.jsx(Na,{className:"text-sm",children:v(j.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:j.user_name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:Ed(new Date(j.created_at),{addSuffix:!0})}),j.user_id===(t==null?void 0:t.id)&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>p.mutate(j.id),children:e.jsx(Sn,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:j.content})]})]})})},j.id))})]})]})}):e.jsx(zs,{title:"Toolbox",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Nh,{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(B,{asChild:!0,className:"mt-4",children:e.jsx(ir,{to:"/toolbox",children:"Back to Toolbox"})})]})})},MQs=()=>{const s=Fn(),[t,n]=_.useState(""),[r,a]=_.useState("grid"),{data:i=[],isLoading:l}=at({queryKey:["social-swag"],queryFn:async()=>{const{data:d,error:u}=await q.from("social_swag").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(u)throw u;const{data:h,error:m}=await q.from("social_swag_links").select("*").order("sort_order");if(m)throw m;const{data:p}=await q.from("social_swag_likes").select("swag_id"),{data:f}=await q.from("social_swag_comments").select("swag_id"),y=new Map;p==null||p.forEach(b=>{y.set(b.swag_id,(y.get(b.swag_id)||0)+1)});const v=new Map;return f==null||f.forEach(b=>{v.set(b.swag_id,(v.get(b.swag_id)||0)+1)}),(d||[]).map(b=>({...b,links:(h||[]).filter(j=>j.swag_id===b.id)||[],likesCount:y.get(b.id)||0,commentsCount:v.get(b.id)||0}))}}),o=i.filter(d=>{var h;return d.title.toLowerCase().includes(t.toLowerCase())||((h=d.description)==null?void 0:h.toLowerCase().includes(t.toLowerCase()))}),c=d=>{s(`/social-swag/${d}`)};return e.jsx(zs,{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(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search social swag...",value:t,onChange:d=>n(d.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex gap-2",children:[t&&e.jsx(B,{variant:"outline",size:"sm",onClick:()=>n(""),children:"Clear"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{variant:r==="grid"?"secondary":"outline",size:"icon",onClick:()=>a("grid"),className:"rounded-full",children:e.jsx(sf,{className:"h-4 w-4"})}),e.jsx(B,{variant:r==="list"?"secondary":"outline",size:"icon",onClick:()=>a("list"),className:"rounded-full",children:e.jsx(A0,{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(ve,{children:e.jsxs(Me,{className:"p-4",children:[e.jsx(cn,{className:"aspect-[4/3] w-full rounded-lg mb-4"}),e.jsx(cn,{className:"h-5 w-3/4 mb-2"}),e.jsx(cn,{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(B,{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(ve,{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(Oe,{variant:"secondary",className:"gap-1 bg-background/90 backdrop-blur-sm",children:[e.jsx(Vc,{className:"h-3 w-3"}),d.links.length]})})]}),e.jsxs(Me,{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(Fg,{className:"h-3.5 w-3.5"}),d.likesCount]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ou,{className:"h-3.5 w-3.5"}),d.commentsCount]})]}),e.jsxs(B,{size:"sm",className:"w-full gap-2",onClick:u=>{u.stopPropagation(),c(d.id)},children:[e.jsx(wr,{className:"h-4 w-4"}),"View Details"]})]})]},d.id))})]})})};var Xl=function(){return Xl=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(dJs,{displayMonth:s.displayMonth,hideNext:u,hidePrevious:h,nextMonth:a,previousMonth:r,onPreviousClick:m,onNextClick:p})}function uJs(s){var t,n=ip(),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:Nqt,d;return a?d=e.jsx(c,{id:s.id,displayMonth:s.displayMonth}):l==="dropdown"?d=e.jsx(Cyt,{displayMonth:s.displayMonth,id:s.id}):l==="dropdown-buttons"?d=e.jsxs(e.Fragment,{children:[e.jsx(Cyt,{displayMonth:s.displayMonth,displayIndex:s.displayIndex,id:s.id}),e.jsx(Ayt,{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(Ayt,{displayMonth:s.displayMonth,id:s.id})]}),e.jsx("div",{className:r.caption,style:i.caption,children:d})}function hJs(s){var t=ip(),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 mJs(s,t,n){for(var r=n?_E(new Date):v1(new Date,{locale:s,weekStartsOn:t}),a=[],i=0;i<7;i++){var l=zh(r,i);a.push(l)}return a}function pJs(){var s=ip(),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=mJs(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 fJs(){var s,t=ip(),n=t.classNames,r=t.styles,a=t.components,i=(s=a==null?void 0:a.HeadRow)!==null&&s!==void 0?s:pJs;return e.jsx("thead",{style:r.head,className:n.head,children:e.jsx(i,{})})}function xJs(s){var t=ip(),n=t.locale,r=t.formatters.formatDay;return e.jsx(e.Fragment,{children:r(s.date,{locale:n})})}var xtt=_.createContext(void 0);function gJs(s){if(!mae(s.initialProps)){var t={selected:void 0,modifiers:{disabled:[]}};return e.jsx(xtt.Provider,{value:t,children:s.children})}return e.jsx(yJs,{initialProps:s.initialProps,children:s.children})}function yJs(s){var t=s.initialProps,n=s.children,r=t.selected,a=t.min,i=t.max,l=function(d,u,h){var m,p;(m=t.onDayClick)===null||m===void 0||m.call(t,d,u,h);var f=!!(u.selected&&a&&(r==null?void 0:r.length)===a);if(!f){var y=!!(!u.selected&&i&&(r==null?void 0:r.length)===i);if(!y){var v=r?wqt([],r):[];if(u.selected){var g=v.findIndex(function(b){return cm(d,b)});v.splice(g,1)}else v.push(d);(p=t.onSelect)===null||p===void 0||p.call(t,v,d,u,h)}}},o={disabled:[]};r&&o.disabled.push(function(d){var u=i&&r.length>i-1,h=r.some(function(m){return cm(m,d)});return!!(u&&!h)});var c={selected:r,onDayClick:l,modifiers:o};return e.jsx(xtt.Provider,{value:c,children:n})}function gtt(){var s=_.useContext(xtt);if(!s)throw new Error("useSelectMultiple must be used within a SelectMultipleProvider");return s}function vJs(s,t){var n=t||{},r=n.from,a=n.to;return r&&a?cm(a,s)&&cm(r,s)?void 0:cm(a,s)?{from:a,to:void 0}:cm(r,s)?void 0:Z4(r,s)?{from:s,to:a}:{from:r,to:s}:a?Z4(s,a)?{from:a,to:s}:{from:s,to:a}:r?yS(s,r)?{from:s,to:r}:{from:r,to:s}:{from:s,to:void 0}}var ytt=_.createContext(void 0);function bJs(s){if(!pae(s.initialProps)){var t={selected:void 0,modifiers:{range_start:[],range_end:[],range_middle:[],disabled:[]}};return e.jsx(ytt.Provider,{value:t,children:s.children})}return e.jsx(_Js,{initialProps:s.initialProps,children:s.children})}function _Js(s){var t=s.initialProps,n=s.children,r=t.selected,a=r||{},i=a.from,l=a.to,o=t.min,c=t.max,d=function(p,f,y){var v,g;(v=t.onDayClick)===null||v===void 0||v.call(t,p,f,y);var b=vJs(p,r);(g=t.onSelect)===null||g===void 0||g.call(t,b,p,f,y)},u={range_start:[],range_end:[],range_middle:[],disabled:[]};if(i?(u.range_start=[i],l?(u.range_end=[l],cm(i,l)||(u.range_middle=[{after:i,before:l}])):u.range_end=[i]):l&&(u.range_start=[l],u.range_end=[l]),o&&(i&&!l&&u.disabled.push({after:w4e(i,o-1),before:zh(i,o-1)}),i&&l&&u.disabled.push({after:i,before:zh(i,o-1)}),!i&&l&&u.disabled.push({after:w4e(l,o-1),before:zh(l,o-1)})),c){if(i&&!l&&(u.disabled.push({before:zh(i,-c+1)}),u.disabled.push({after:zh(i,c-1)})),i&&l){var h=pv(l,i)+1,m=c-h;u.disabled.push({before:w4e(i,m)}),u.disabled.push({after:zh(l,m)})}!i&&l&&(u.disabled.push({before:zh(l,-c+1)}),u.disabled.push({after:zh(l,c-1)}))}return e.jsx(ytt.Provider,{value:{selected:r,onDayClick:d,modifiers:u},children:n})}function vtt(){var s=_.useContext(ytt);if(!s)throw new Error("useSelectRange must be used within a SelectRangeProvider");return s}function H4e(s){return Array.isArray(s)?wqt([],s):s!==void 0?[s]:[]}function wJs(s){var t={};return Object.entries(s).forEach(function(n){var r=n[0],a=n[1];t[r]=H4e(a)}),t}var TS;(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"})(TS||(TS={}));var jJs=TS.Selected,x3=TS.Disabled,NJs=TS.Hidden,kJs=TS.Today,V7e=TS.RangeEnd,H7e=TS.RangeMiddle,G7e=TS.RangeStart,SJs=TS.Outside;function CJs(s,t,n){var r,a=(r={},r[jJs]=H4e(s.selected),r[x3]=H4e(s.disabled),r[NJs]=H4e(s.hidden),r[kJs]=[s.today],r[V7e]=[],r[H7e]=[],r[G7e]=[],r[SJs]=[],r);return s.fromDate&&a[x3].push({before:s.fromDate}),s.toDate&&a[x3].push({after:s.toDate}),mae(s)?a[x3]=a[x3].concat(t.modifiers[x3]):pae(s)&&(a[x3]=a[x3].concat(n.modifiers[x3]),a[G7e]=n.modifiers[G7e],a[H7e]=n.modifiers[H7e],a[V7e]=n.modifiers[V7e]),a}var Cqt=_.createContext(void 0);function AJs(s){var t=ip(),n=gtt(),r=vtt(),a=CJs(t,n,r),i=wJs(t.modifiers),l=Xl(Xl({},a),i);return e.jsx(Cqt.Provider,{value:l,children:s.children})}function Aqt(){var s=_.useContext(Cqt);if(!s)throw new Error("useModifiers must be used within a ModifiersProvider");return s}function EJs(s){return!!(s&&typeof s=="object"&&"before"in s&&"after"in s)}function TJs(s){return!!(s&&typeof s=="object"&&"from"in s)}function MJs(s){return!!(s&&typeof s=="object"&&"after"in s)}function PJs(s){return!!(s&&typeof s=="object"&&"before"in s)}function LJs(s){return!!(s&&typeof s=="object"&&"dayOfWeek"in s)}function IJs(s,t){var n,r=t.from,a=t.to;if(r&&a){var i=pv(a,r)<0;i&&(n=[a,r],r=n[0],a=n[1]);var l=pv(s,r)>=0&&pv(a,s)>=0;return l}return a?cm(a,s):r?cm(r,s):!1}function DJs(s){return qQe(s)}function RJs(s){return Array.isArray(s)&&s.every(qQe)}function FJs(s,t){return t.some(function(n){if(typeof n=="boolean")return n;if(DJs(n))return cm(s,n);if(RJs(n))return n.includes(s);if(TJs(n))return IJs(s,n);if(LJs(n))return n.dayOfWeek.includes(s.getDay());if(EJs(n)){var r=pv(n.before,s),a=pv(n.after,s),i=r>0,l=a<0,o=Z4(n.before,n.after);return o?l&&i:i||l}return MJs(n)?pv(s,n.after)>0:PJs(n)?pv(n.before,s)>0:typeof n=="function"?n(s):!1})}function btt(s,t,n){var r=Object.keys(t).reduce(function(i,l){var o=t[l];return FJs(s,o)&&i.push(l),i},[]),a={};return r.forEach(function(i){return a[i]=!0}),n&&!Vre(s,n)&&(a.outside=!0),a}function OJs(s,t){for(var n=rm(s[0]),r=y_(s[s.length-1]),a,i,l=n;l<=r;){var o=btt(l,t),c=!o.disabled&&!o.hidden;if(!c){l=zh(l,1);continue}if(o.selected)return l;o.today&&!i&&(i=l),a||(a=l),l=zh(l,1)}return i||a}var zJs=365;function Eqt(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:zh,week:uF,month:Cy,year:qCs,startOfWeek:function(v){return a.ISOWeek?_E(v):v1(v,{locale:h,weekStartsOn:c})},endOfWeek:function(v){return a.ISOWeek?ZDt(v):gPe(v,{locale:h,weekStartsOn:c})}},p=m[n](s,r==="after"?1:-1);r==="before"&&d?p=$Cs([d,p]):r==="after"&&u&&(p=VCs([u,p]));var f=!0;if(i){var y=btt(p,i);f=!y.disabled&&!y.hidden}return f?p:o.count>zJs?o.lastFocused:Eqt(p,{moveBy:n,direction:r,context:a,modifiers:i,retry:Xl(Xl({},o),{count:o.count+1})})}var Tqt=_.createContext(void 0);function BJs(s){var t=fae(),n=Aqt(),r=_.useState(),a=r[0],i=r[1],l=_.useState(),o=l[0],c=l[1],d=OJs(t.displayMonths,n),u=a??(o&&t.isDateDisplayed(o))?o:d,h=function(){c(a),i(void 0)},m=function(v){i(v)},p=ip(),f=function(v,g){if(a){var b=Eqt(a,{moveBy:v,direction:g,context:p,modifiers:n});cm(a,b)||(t.goToDate(b,a),m(b))}},y={focusedDay:a,focusTarget:u,blur:h,focus:m,focusDayAfter:function(){return f("day","after")},focusDayBefore:function(){return f("day","before")},focusWeekAfter:function(){return f("week","after")},focusWeekBefore:function(){return f("week","before")},focusMonthBefore:function(){return f("month","before")},focusMonthAfter:function(){return f("month","after")},focusYearBefore:function(){return f("year","before")},focusYearAfter:function(){return f("year","after")},focusStartOfWeek:function(){return f("startOfWeek","before")},focusEndOfWeek:function(){return f("endOfWeek","after")}};return e.jsx(Tqt.Provider,{value:y,children:s.children})}function _tt(){var s=_.useContext(Tqt);if(!s)throw new Error("useFocusContext must be used within a FocusProvider");return s}function UJs(s,t){var n=Aqt(),r=btt(s,n,t);return r}var wtt=_.createContext(void 0);function qJs(s){if(!zLe(s.initialProps)){var t={selected:void 0};return e.jsx(wtt.Provider,{value:t,children:s.children})}return e.jsx($Js,{initialProps:s.initialProps,children:s.children})}function $Js(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(wtt.Provider,{value:a,children:n})}function Mqt(){var s=_.useContext(wtt);if(!s)throw new Error("useSelectSingle must be used within a SelectSingleProvider");return s}function VJs(s,t){var n=ip(),r=Mqt(),a=gtt(),i=vtt(),l=_tt(),o=l.focusDayAfter,c=l.focusDayBefore,d=l.focusWeekAfter,u=l.focusWeekBefore,h=l.blur,m=l.focus,p=l.focusMonthBefore,f=l.focusMonthAfter,y=l.focusYearBefore,v=l.focusYearAfter,g=l.focusStartOfWeek,b=l.focusEndOfWeek,j=function(Z){var ne,ce,ie,te;zLe(n)?(ne=r.onDayClick)===null||ne===void 0||ne.call(r,s,t,Z):mae(n)?(ce=a.onDayClick)===null||ce===void 0||ce.call(a,s,t,Z):pae(n)?(ie=i.onDayClick)===null||ie===void 0||ie.call(i,s,t,Z):(te=n.onDayClick)===null||te===void 0||te.call(n,s,t,Z)},S=function(Z){var ne;m(s),(ne=n.onDayFocus)===null||ne===void 0||ne.call(n,s,t,Z)},C=function(Z){var ne;h(),(ne=n.onDayBlur)===null||ne===void 0||ne.call(n,s,t,Z)},E=function(Z){var ne;(ne=n.onDayMouseEnter)===null||ne===void 0||ne.call(n,s,t,Z)},P=function(Z){var ne;(ne=n.onDayMouseLeave)===null||ne===void 0||ne.call(n,s,t,Z)},M=function(Z){var ne;(ne=n.onDayPointerEnter)===null||ne===void 0||ne.call(n,s,t,Z)},I=function(Z){var ne;(ne=n.onDayPointerLeave)===null||ne===void 0||ne.call(n,s,t,Z)},D=function(Z){var ne;(ne=n.onDayTouchCancel)===null||ne===void 0||ne.call(n,s,t,Z)},O=function(Z){var ne;(ne=n.onDayTouchEnd)===null||ne===void 0||ne.call(n,s,t,Z)},V=function(Z){var ne;(ne=n.onDayTouchMove)===null||ne===void 0||ne.call(n,s,t,Z)},G=function(Z){var ne;(ne=n.onDayTouchStart)===null||ne===void 0||ne.call(n,s,t,Z)},$=function(Z){var ne;(ne=n.onDayKeyUp)===null||ne===void 0||ne.call(n,s,t,Z)},H=function(Z){var ne;switch(Z.key){case"ArrowLeft":Z.preventDefault(),Z.stopPropagation(),n.dir==="rtl"?o():c();break;case"ArrowRight":Z.preventDefault(),Z.stopPropagation(),n.dir==="rtl"?c():o();break;case"ArrowDown":Z.preventDefault(),Z.stopPropagation(),d();break;case"ArrowUp":Z.preventDefault(),Z.stopPropagation(),u();break;case"PageUp":Z.preventDefault(),Z.stopPropagation(),Z.shiftKey?y():p();break;case"PageDown":Z.preventDefault(),Z.stopPropagation(),Z.shiftKey?v():f();break;case"Home":Z.preventDefault(),Z.stopPropagation(),g();break;case"End":Z.preventDefault(),Z.stopPropagation(),b();break}(ne=n.onDayKeyDown)===null||ne===void 0||ne.call(n,s,t,Z)},Y={onClick:j,onFocus:S,onBlur:C,onKeyDown:H,onKeyUp:$,onMouseEnter:E,onMouseLeave:P,onPointerEnter:M,onPointerLeave:I,onTouchCancel:D,onTouchEnd:O,onTouchMove:V,onTouchStart:G};return Y}function HJs(){var s=ip(),t=Mqt(),n=gtt(),r=vtt(),a=zLe(s)?t.selected:mae(s)?n.selected:pae(s)?r.selected:void 0;return a}function GJs(s){return Object.values(TS).includes(s)}function WJs(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(GJs(r)){var i=s.classNames["day_".concat(r)];i&&n.push(i)}}),n}function KJs(s,t){var n=Xl({},s.styles.day);return Object.keys(t).forEach(function(r){var a;n=Xl(Xl({},n),(a=s.modifiersStyles)===null||a===void 0?void 0:a[r])}),n}function YJs(s,t,n){var r,a,i,l=ip(),o=_tt(),c=UJs(s,t),d=VJs(s,c),u=HJs(),h=!!(l.onDayClick||l.mode!=="default");_.useEffect(function(){var E;c.outside||o.focusedDay&&h&&cm(o.focusedDay,s)&&((E=n.current)===null||E===void 0||E.focus())},[o.focusedDay,s,n,h,c.outside]);var m=WJs(l,c).join(" "),p=KJs(l,c),f=!!(c.outside&&!l.showOutsideDays||c.hidden),y=(i=(a=l.components)===null||a===void 0?void 0:a.DayContent)!==null&&i!==void 0?i:xJs,v=e.jsx(y,{date:s,displayMonth:t,activeModifiers:c}),g={style:p,className:m,children:v,role:"gridcell"},b=o.focusTarget&&cm(o.focusTarget,s)&&!c.outside,j=o.focusedDay&&cm(o.focusedDay,s),S=Xl(Xl(Xl({},g),(r={disabled:c.disabled,role:"gridcell"},r["aria-selected"]=c.selected,r.tabIndex=j||b?0:-1,r)),d),C={isButton:h,isHidden:f,activeModifiers:c,selectedDays:u,buttonProps:S,divProps:g};return C}function ZJs(s){var t=_.useRef(null),n=YJs(s.date,s.displayMonth,t);return n.isHidden?e.jsx("div",{role:"gridcell"}):n.isButton?e.jsx(wEe,Xl({name:"day",ref:t},n.buttonProps)):e.jsx("div",Xl({},n.divProps))}function XJs(s){var t=s.number,n=s.dates,r=ip(),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(wEe,{name:"week-number","aria-label":h,className:l.weeknumber,style:i.weeknumber,onClick:m,children:u})}function QJs(s){var t,n,r=ip(),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:ZJs,d=(n=o==null?void 0:o.WeekNumber)!==null&&n!==void 0?n:XJs,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})},Y3s(h))})]})}function Eyt(s,t,n){for(var r=n!=null&&n.ISOWeek?ZDt(t):gPe(t,n),a=n!=null&&n.ISOWeek?_E(s):v1(s,n),i=pv(r,a),l=[],o=0;o<=i;o++)l.push(zh(a,o));var c=l.reduce(function(d,u){var h=n!=null&&n.ISOWeek?VQe(u):GQe(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 JJs(s,t){var n=Eyt(rm(s),y_(s),t);if(t!=null&&t.useFixedWeeks){var r=X3s(s,t);if(r<6){var a=n[n.length-1],i=a.dates[a.dates.length-1],l=uF(i,6-r),o=Eyt(uF(i,1),l,t);n.push.apply(n,o)}}return n}function een(s){var t,n,r,a=ip(),i=a.locale,l=a.classNames,o=a.styles,c=a.hideHead,d=a.fixedWeeks,u=a.components,h=a.weekStartsOn,m=a.firstWeekContainsDate,p=a.ISOWeek,f=JJs(s.displayMonth,{useFixedWeeks:!!d,ISOWeek:p,locale:i,weekStartsOn:h,firstWeekContainsDate:m}),y=(t=u==null?void 0:u.Head)!==null&&t!==void 0?t:fJs,v=(n=u==null?void 0:u.Row)!==null&&n!==void 0?n:QJs,g=(r=u==null?void 0:u.Footer)!==null&&r!==void 0?r:hJs;return e.jsxs("table",{id:s.id,className:l.table,style:o.table,role:"grid","aria-labelledby":s["aria-labelledby"],children:[!c&&e.jsx(y,{}),e.jsx("tbody",{className:l.tbody,style:o.tbody,children:f.map(function(b){return e.jsx(v,{displayMonth:s.displayMonth,dates:b.dates,weekNumber:b.weekNumber},b.weekNumber)})}),e.jsx(g,{displayMonth:s.displayMonth})]})}function ten(){return!!(typeof window<"u"&&window.document&&window.document.createElement)}var sen=ten()?_.useLayoutEffect:_.useEffect,W7e=!1,nen=0;function Tyt(){return"react-day-picker-".concat(++nen)}function ren(s){var t,n=s??(W7e?Tyt():null),r=_.useState(n),a=r[0],i=r[1];return sen(function(){a===null&&i(Tyt())},[]),_.useEffect(function(){W7e===!1&&(W7e=!0)},[]),(t=s??a)!==null&&t!==void 0?t:void 0}function aen(s){var t,n,r=ip(),a=r.dir,i=r.classNames,l=r.styles,o=r.components,c=fae().displayMonths,d=ren(r.id?"".concat(r.id,"-").concat(s.displayIndex):void 0),u=r.id?"".concat(r.id,"-grid-").concat(s.displayIndex):void 0,h=[i.month],m=l.month,p=s.displayIndex===0,f=s.displayIndex===c.length-1,y=!p&&!f;a==="rtl"&&(t=[p,f],f=t[0],p=t[1]),p&&(h.push(i.caption_start),m=Xl(Xl({},m),l.caption_start)),f&&(h.push(i.caption_end),m=Xl(Xl({},m),l.caption_end)),y&&(h.push(i.caption_between),m=Xl(Xl({},m),l.caption_between));var v=(n=o==null?void 0:o.Caption)!==null&&n!==void 0?n:uJs;return e.jsxs("div",{className:h.join(" "),style:m,children:[e.jsx(v,{id:d,displayMonth:s.displayMonth,displayIndex:s.displayIndex}),e.jsx(een,{id:u,"aria-labelledby":d,displayMonth:s.displayMonth})]},s.displayIndex)}function ien(s){var t=ip(),n=t.classNames,r=t.styles;return e.jsx("div",{className:n.months,style:r.months,children:s.children})}function oen(s){var t,n,r=s.initialProps,a=ip(),i=_tt(),l=fae(),o=_.useState(!1),c=o[0],d=o[1];_.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=Xl(Xl({},a.styles.root),a.style),m=Object.keys(r).filter(function(f){return f.startsWith("data-")}).reduce(function(f,y){var v;return Xl(Xl({},f),(v={},v[y]=r[y],v))},{}),p=(n=(t=r.components)===null||t===void 0?void 0:t.Months)!==null&&n!==void 0?n:ien;return e.jsx("div",Xl({className:u.join(" "),style:h,dir:a.dir,id:a.id,nonce:r.nonce,title:r.title,lang:r.lang},m,{children:e.jsx(p,{children:l.displayMonths.map(function(f,y){return e.jsx(aen,{displayIndex:y,displayMonth:f},y)})})}))}function len(s){var t=s.children,n=PQs(s,["children"]);return e.jsx(XQs,{initialProps:n,children:e.jsx(oJs,{children:e.jsx(qJs,{initialProps:n,children:e.jsx(gJs,{initialProps:n,children:e.jsx(bJs,{initialProps:n,children:e.jsx(AJs,{children:e.jsx(BJs,{children:t})})})})})})})}function cen(s){return e.jsx(len,Xl({},s,{children:e.jsx(oen,{initialProps:s})}))}function Pj({className:s,classNames:t,showOutsideDays:n=!0,...r}){return e.jsx(cen,{showOutsideDays:n,className:At("p-3",s),classNames:{months:"flex flex-col sm:flex-row space-y-4 sm:space-x-4 sm:space-y-0",month:"space-y-4",caption:"flex justify-center pt-1 relative items-center",caption_label:"text-sm font-medium",caption_dropdowns:"flex gap-2 items-center justify-center",vhidden:"sr-only",nav:"space-x-1 flex items-center",nav_button:At(vH({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:At(vH({variant:"ghost"}),"h-9 w-9 p-0 font-normal aria-selected:opacity-100"),day_range_end:"day-range-end",day_selected:"bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground focus:bg-primary focus:text-primary-foreground",day_today:"bg-accent text-accent-foreground",day_outside:"day-outside text-muted-foreground opacity-50 aria-selected:bg-accent/50 aria-selected:text-muted-foreground aria-selected:opacity-30",day_disabled:"text-muted-foreground opacity-50",day_range_middle:"aria-selected:bg-accent aria-selected:text-accent-foreground",day_hidden:"invisible",dropdown:"h-8 rounded-md border border-input bg-background px-2 py-1 text-sm ring-offset-background focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",...t},components:{IconLeft:({...a})=>e.jsx($c,{className:"h-4 w-4"}),IconRight:({...a})=>e.jsx(xi,{className:"h-4 w-4"})},...r})}Pj.displayName="Calendar";var BLe="Popover",[Pqt,s_r]=af(BLe,[_C]),xae=_C(),[den,bL]=Pqt(BLe),Lqt=s=>{const{__scopePopover:t,children:n,open:r,defaultOpen:a,onOpenChange:i,modal:l=!1}=s,o=xae(t),c=_.useRef(null),[d,u]=_.useState(!1),[h,m]=Ug({prop:r,defaultProp:a??!1,onChange:i,caller:BLe});return e.jsx(Are,{...o,children:e.jsx(den,{scope:t,contentId:Og(),triggerRef:c,open:h,onOpenChange:m,onOpenToggle:_.useCallback(()=>m(p=>!p),[m]),hasCustomAnchor:d,onCustomAnchorAdd:_.useCallback(()=>u(!0),[]),onCustomAnchorRemove:_.useCallback(()=>u(!1),[]),modal:l,children:n})})};Lqt.displayName=BLe;var Iqt="PopoverAnchor",uen=_.forwardRef((s,t)=>{const{__scopePopover:n,...r}=s,a=bL(Iqt,n),i=xae(n),{onCustomAnchorAdd:l,onCustomAnchorRemove:o}=a;return _.useEffect(()=>(l(),()=>o()),[l,o]),e.jsx(tW,{...i,...r,ref:t})});uen.displayName=Iqt;var Dqt="PopoverTrigger",Rqt=_.forwardRef((s,t)=>{const{__scopePopover:n,...r}=s,a=bL(Dqt,n),i=xae(n),l=Qo(t,a.triggerRef),o=e.jsx(ii.button,{type:"button","aria-haspopup":"dialog","aria-expanded":a.open,"aria-controls":a.contentId,"data-state":Uqt(a.open),...r,ref:l,onClick:wa(s.onClick,a.onOpenToggle)});return a.hasCustomAnchor?o:e.jsx(tW,{asChild:!0,...i,children:o})});Rqt.displayName=Dqt;var jtt="PopoverPortal",[hen,men]=Pqt(jtt,{forceMount:void 0}),Fqt=s=>{const{__scopePopover:t,forceMount:n,children:r,container:a}=s,i=bL(jtt,t);return e.jsx(hen,{scope:t,forceMount:n,children:e.jsx(pg,{present:n||i.open,children:e.jsx(YG,{asChild:!0,container:a,children:r})})})};Fqt.displayName=jtt;var UH="PopoverContent",Oqt=_.forwardRef((s,t)=>{const n=men(UH,s.__scopePopover),{forceMount:r=n.forceMount,...a}=s,i=bL(UH,s.__scopePopover);return e.jsx(pg,{present:r||i.open,children:i.modal?e.jsx(fen,{...a,ref:t}):e.jsx(xen,{...a,ref:t})})});Oqt.displayName=UH;var pen=CP("PopoverContent.RemoveScroll"),fen=_.forwardRef((s,t)=>{const n=bL(UH,s.__scopePopover),r=_.useRef(null),a=Qo(t,r),i=_.useRef(!1);return _.useEffect(()=>{const l=r.current;if(l)return SMe(l)},[]),e.jsx(wre,{as:pen,allowPinchZoom:!0,children:e.jsx(zqt,{...s,ref:a,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:wa(s.onCloseAutoFocus,l=>{var o;l.preventDefault(),i.current||(o=n.triggerRef.current)==null||o.focus()}),onPointerDownOutside:wa(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:wa(s.onFocusOutside,l=>l.preventDefault(),{checkForDefaultPrevented:!1})})})}),xen=_.forwardRef((s,t)=>{const n=bL(UH,s.__scopePopover),r=_.useRef(!1),a=_.useRef(!1);return e.jsx(zqt,{...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()}})}),zqt=_.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=bL(UH,n),p=xae(n);return NMe(),e.jsx(_re,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:a,onUnmountAutoFocus:i,children:e.jsx(rL,{asChild:!0,disableOutsidePointerEvents:l,onInteractOutside:u,onEscapeKeyDown:o,onPointerDownOutside:c,onFocusOutside:d,onDismiss:()=>m.onOpenChange(!1),children:e.jsx(Ere,{"data-state":Uqt(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)"}})})})}),Bqt="PopoverClose",gen=_.forwardRef((s,t)=>{const{__scopePopover:n,...r}=s,a=bL(Bqt,n);return e.jsx(ii.button,{type:"button",...r,ref:t,onClick:wa(s.onClick,()=>a.onOpenChange(!1))})});gen.displayName=Bqt;var yen="PopoverArrow",ven=_.forwardRef((s,t)=>{const{__scopePopover:n,...r}=s,a=xae(n);return e.jsx(Tre,{...a,...r,ref:t})});ven.displayName=yen;function Uqt(s){return s?"open":"closed"}var ben=Lqt,_en=Rqt,wen=Fqt,qqt=Oqt;const od=ben,ld=_en,Qc=_.forwardRef(({className:s,align:t="center",sideOffset:n=4,...r},a)=>e.jsx(wen,{children:e.jsx(qqt,{ref:a,align:t,sideOffset:n,className:At("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})}));Qc.displayName=qqt.displayName;async function Ate(s){if(s instanceof Mre)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 jen=F9("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"}}),Ete=_.forwardRef(({className:s,variant:t,...n},r)=>e.jsx("div",{ref:r,role:"alert",className:At(jen({variant:t}),s),...n}));Ete.displayName="Alert";const Nen=_.forwardRef(({className:s,...t},n)=>e.jsx("h5",{ref:n,className:At("mb-1 font-medium leading-none tracking-tight",s),...t}));Nen.displayName="AlertTitle";const Tte=_.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:At("text-sm [&_p]:leading-relaxed",s),...t}));Tte.displayName="AlertDescription";function ken({open:s,onOpenChange:t,imageUrl:n,imageId:r,defaultCaption:a="",swagItemId:i,reelId:l}){const o=Bt(),{user:c}=hs(),d=(c==null?void 0:c.id)??null,[u,h]=_.useState(a),[m,p]=_.useState([]),[f,y]=_.useState(null),[v,g]=_.useState("now"),[b,j]=_.useState(Ept(Rpt(new Date),1)),[S,C]=_.useState("12"),[E,P]=_.useState("00"),[M,I]=_.useState("PM");_.useEffect(()=>{if(s){h(a),g("now"),p([]);const me=Ept(Rpt(new Date),1);j(me);const he=me.getHours();C(String(he>12?he-12:he===0?12:he)),P("00"),I(he>=12?"PM":"AM")}},[s,a]);const D=()=>{if(!b)return null;let me=parseInt(S);const he=parseInt(E);return M==="PM"&&me!==12&&(me+=12),M==="AM"&&me===12&&(me=0),iRt(aRt(b,me),he)},{data:O,isLoading:V}=at({queryKey:["social-accounts-for-post",d],queryFn:async()=>{const{data:{user:me}}=await q.auth.getUser();if(!me)return[];const{data:he,error:pe}=await q.from("social_accounts").select("*").eq("user_id",me.id).eq("is_active",!0).order("platform",{ascending:!0});if(pe)throw pe;return console.log("Fetched social accounts for posting:",he),he},enabled:s,staleTime:0}),G=mt({mutationFn:async({accountId:me,platform:he})=>{y(me);const{data:pe,error:Ce}=await q.functions.invoke("social-post",{body:{platform:he,accountId:me,imageUrl:n,caption:u}});if(Ce)throw new Error(await Ate(Ce));if(pe!=null&&pe.error)throw new Error(pe.error);return pe},onSuccess:me=>{const he=me.platform==="facebook"?"Facebook":me.platform==="instagram"?"Instagram":me.platform==="linkedin"?"LinkedIn":"Google Business";se.success(`Posted to ${he}!`)},onError:me=>{se.error(`Failed to post: ${me.message}`)},onSettled:()=>{y(null)}}),$=mt({mutationFn:async({accountId:me,platform:he,scheduledFor:pe})=>{const{data:{user:Ce}}=await q.auth.getUser();if(!Ce)throw new Error("Not authenticated");const{error:Ae}=await q.from("scheduled_posts").insert({user_id:Ce.id,social_account_id:me,platform:he,image_url:n,caption:u,swag_item_id:i||null,reel_id:l||null,scheduled_for:pe.toISOString(),status:"scheduled"});if(Ae)throw Ae;return{platform:he}},onSuccess:me=>{const he=me.platform==="facebook"?"Facebook":me.platform==="instagram"?"Instagram":"LinkedIn";se.success(`Post scheduled for ${he}!`)},onError:me=>{se.error(`Failed to schedule: ${me.message}`)}}),H=async()=>{if(m.length===0){se.error("Please select at least one account");return}if(v==="schedule"){const me=D();if(!me||me<=new Date){se.error("Please select a future date and time");return}for(const he of m){const pe=O==null?void 0:O.find(Ce=>Ce.id===he);pe&&await $.mutateAsync({accountId:he,platform:pe.platform,scheduledFor:me})}o.invalidateQueries({queryKey:["scheduled-posts",d]}),se.success(`${m.length} post(s) scheduled for ${Hs(me,"PPp")}`)}else for(const me of m){const he=O==null?void 0:O.find(pe=>pe.id===me);he&&await G.mutateAsync({accountId:me,platform:he.platform})}o.invalidateQueries({queryKey:["scheduled-posts",d]}),h(""),p([]),t(!1)},Y=me=>{p(he=>he.includes(me)?he.filter(pe=>pe!==me):[...he,me])},Z=(O==null?void 0:O.filter(me=>me.platform==="facebook"))||[],ne=(O==null?void 0:O.filter(me=>me.platform==="instagram"))||[],ce=(O==null?void 0:O.filter(me=>me.platform==="linkedin"))||[],ie=(O==null?void 0:O.filter(me=>me.platform==="google_business"))||[],te=((O==null?void 0:O.length)||0)>0,ae=G.isPending||$.isPending,le=Array.from({length:12},(me,he)=>String(he+1)),be=["00","15","30","45"];return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Create Social Post"}),e.jsx(_r,{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(J,{htmlFor:"caption",children:"Caption"}),e.jsx(Ms,{id:"caption",placeholder:"Write a caption for your post...",value:u,onChange:me=>h(me.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(J,{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:()=>g("now"),className:At("flex-1 px-4 py-2 rounded-md text-sm font-medium transition-all",v==="now"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:"Post Now"}),e.jsx("button",{type:"button",onClick:()=>g("schedule"),className:At("flex-1 px-4 py-2 rounded-md text-sm font-medium transition-all",v==="schedule"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:"Schedule"})]})]}),v==="schedule"&&e.jsxs("div",{className:"space-y-3 p-4 border rounded-lg bg-muted/30",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(Gr,{className:"h-4 w-4"}),"Schedule for"]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs(od,{children:[e.jsx(ld,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:At("justify-start text-left font-normal flex-1",!b&&"text-muted-foreground"),children:[e.jsx(ga,{className:"mr-2 h-4 w-4"}),b?Hs(b,"PPP"):e.jsx("span",{children:"Pick a date"})]})}),e.jsx(Qc,{className:"w-auto p-0",align:"start",children:e.jsx(Pj,{mode:"single",selected:b,onSelect:j,disabled:me=>mee.jsx(He,{value:me,children:me},me))})]}),e.jsx("span",{className:"text-muted-foreground",children:":"}),e.jsxs(is,{value:E,onValueChange:P,children:[e.jsx(rs,{className:"w-[70px]",children:e.jsx(ls,{})}),e.jsx(as,{children:be.map(me=>e.jsx(He,{value:me,children:me},me))})]}),e.jsxs(is,{value:M,onValueChange:me=>I(me),children:[e.jsx(rs,{className:"w-[70px]",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"AM",children:"AM"}),e.jsx(He,{value:"PM",children:"PM"})]})]})]})]}),b&&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(J,{children:"Post to"}),V&&e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin"})}),!V&&!te&&e.jsxs(Ete,{children:[e.jsx(Xo,{className:"h-4 w-4"}),e.jsxs(Tte,{className:"flex flex-col gap-2",children:[e.jsx("span",{children:"No social accounts connected yet."}),e.jsxs(ir,{to:"/social-connections",className:"inline-flex items-center gap-1.5 text-primary hover:underline font-medium",children:[e.jsx(qc,{className:"h-3.5 w-3.5"}),"Connect your Facebook, Instagram & LinkedIn"]})]})]}),Z.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(tf,{className:"h-4 w-4 text-blue-600"})," Facebook"]}),Z.map(me=>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($a,{checked:m.includes(me.id),onCheckedChange:()=>Y(me.id),disabled:f===me.id}),e.jsxs(ja,{className:"h-8 w-8",children:[e.jsx(pi,{src:me.profile_picture_url||""}),e.jsx(Na,{children:e.jsx(tf,{className:"h-4 w-4"})})]}),e.jsx("span",{className:"flex-1 text-sm font-medium",children:me.page_name||me.platform_username}),f===me.id&&e.jsx(Ct,{className:"h-4 w-4 animate-spin"})]},me.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(Im,{className:"h-4 w-4 text-pink-600"})," Instagram"]}),ne.map(me=>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($a,{checked:m.includes(me.id),onCheckedChange:()=>Y(me.id),disabled:f===me.id}),e.jsxs(ja,{className:"h-8 w-8",children:[e.jsx(pi,{src:me.profile_picture_url||""}),e.jsx(Na,{children:e.jsx(Im,{className:"h-4 w-4"})})]}),e.jsxs("span",{className:"flex-1 text-sm font-medium",children:["@",me.platform_username]}),f===me.id&&e.jsx(Ct,{className:"h-4 w-4 animate-spin"})]},me.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(dg,{className:"h-4 w-4 text-blue-700"})," LinkedIn"]}),ce.map(me=>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($a,{checked:m.includes(me.id),onCheckedChange:()=>Y(me.id),disabled:f===me.id}),e.jsxs(ja,{className:"h-8 w-8",children:[e.jsx(pi,{src:me.profile_picture_url||""}),e.jsx(Na,{children:e.jsx(dg,{className:"h-4 w-4"})})]}),e.jsx("span",{className:"flex-1 text-sm font-medium",children:me.platform_username}),f===me.id&&e.jsx(Ct,{className:"h-4 w-4 animate-spin"})]},me.id))]}),ie.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(Xa,{className:"h-4 w-4 text-red-600"})," Google Business"]}),ie.map(me=>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($a,{checked:m.includes(me.id),onCheckedChange:()=>Y(me.id),disabled:f===me.id}),e.jsxs(ja,{className:"h-8 w-8",children:[e.jsx(pi,{src:me.profile_picture_url||""}),e.jsx(Na,{children:e.jsx(Xa,{className:"h-4 w-4"})})]}),e.jsx("span",{className:"flex-1 text-sm font-medium",children:me.page_name||me.platform_username}),f===me.id&&e.jsx(Ct,{className:"h-4 w-4 animate-spin"})]},me.id))]})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{onClick:H,disabled:m.length===0||ae,className:"gap-2",children:[ae?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):v==="schedule"?e.jsx(ga,{className:"h-4 w-4"}):e.jsx(Or,{className:"h-4 w-4"}),v==="schedule"?`Schedule ${m.length} post${m.length!==1?"s":""}`:`Post to ${m.length} account${m.length!==1?"s":""}`]})]})]})})}function Sen(){const{user:s}=hs(),t=(s==null?void 0:s.id)??null,n=Bt(),[r,a]=_.useState(void 0),[i,l]=_.useState("all"),[o,c]=_.useState(null),[d,u]=_.useState(""),[h,m]=_.useState(void 0),[p,f]=_.useState("12"),[y,v]=_.useState("00"),[g,b]=_.useState("PM"),{data:j=[],isLoading:S}=at({queryKey:["scheduled-posts",t],enabled:!!t,queryFn:async()=>{const{data:ie,error:te}=await q.from("scheduled_posts").select(` *, social_accounts ( page_name, platform_username, profile_picture_url ) `).eq("user_id",t).order("scheduled_for",{ascending:!1});if(te)throw te;return ie}}),C=j.filter(ie=>{if(i!=="all"&&ie.status!==i)return!1;if(r&&ie.scheduled_for){const te=new Date(ie.scheduled_for);if(!cm(te,r))return!1}return!0}),E=j.filter(ie=>ie.scheduled_for).map(ie=>If(new Date(ie.scheduled_for))),P=mt({mutationFn:async ie=>{const{error:te}=await q.from("scheduled_posts").update({caption:ie.caption,scheduled_for:ie.scheduled_for}).eq("id",ie.id);if(te)throw te},onSuccess:()=>{se.success("Post updated!"),n.invalidateQueries({queryKey:["scheduled-posts",t]}),c(null)},onError:ie=>{se.error(`Failed to update: ${ie.message}`)}}),M=mt({mutationFn:async ie=>{const{error:te}=await q.from("scheduled_posts").update({status:"cancelled"}).eq("id",ie);if(te)throw te},onSuccess:()=>{se.success("Post cancelled"),n.invalidateQueries({queryKey:["scheduled-posts",t]})},onError:ie=>{se.error(`Failed to cancel: ${ie.message}`)}}),I=mt({mutationFn:async ie=>{const{error:te}=await q.from("scheduled_posts").delete().eq("id",ie);if(te)throw te},onSuccess:()=>{se.success("Post deleted"),n.invalidateQueries({queryKey:["scheduled-posts",t]})},onError:ie=>{se.error(`Failed to delete: ${ie.message}`)}}),D=mt({mutationFn:async ie=>{const{data:te,error:ae}=await q.functions.invoke("social-post",{body:{platform:ie.platform,accountId:ie.social_account_id,imageUrl:ie.image_url,caption:ie.caption}});if(ae)throw new Error(await Ate(ae));if(te!=null&&te.error)throw new Error(te.error);return await q.from("scheduled_posts").update({status:"posted",posted_at:new Date().toISOString(),post_id:te.postId}).eq("id",ie.id),te},onSuccess:ie=>{const te=ie.platform==="facebook"?"Facebook":ie.platform==="instagram"?"Instagram":"LinkedIn";se.success(`Posted to ${te}!`),n.invalidateQueries({queryKey:["scheduled-posts",t]})},onError:ie=>{se.error(`Failed to post: ${ie.message}`)}}),O=ie=>{if(c(ie),u(ie.caption||""),ie.scheduled_for){const te=new Date(ie.scheduled_for);m(te);const ae=te.getHours();f(String(ae>12?ae-12:ae===0?12:ae)),v(String(te.getMinutes()).padStart(2,"0")),b(ae>=12?"PM":"AM")}},V=()=>{if(!o||!h)return;let ie=parseInt(p);const te=parseInt(y);g==="PM"&&ie!==12&&(ie+=12),g==="AM"&&ie===12&&(ie=0);const ae=iRt(aRt(h,ie),te);P.mutate({id:o.id,caption:d,scheduled_for:ae.toISOString()})},G=ie=>{switch(ie){case"facebook":return e.jsx(tf,{className:"h-4 w-4 text-blue-600"});case"instagram":return e.jsx(Im,{className:"h-4 w-4 text-pink-600"});case"linkedin":return e.jsx(dg,{className:"h-4 w-4 text-blue-700"});default:return null}},$=ie=>{switch(ie){case"scheduled":return e.jsxs(Oe,{variant:"secondary",className:"gap-1",children:[e.jsx(Gr,{className:"h-3 w-3"}),"Scheduled"]});case"posted":return e.jsxs(Oe,{variant:"default",className:"gap-1 bg-green-600",children:[e.jsx(_l,{className:"h-3 w-3"}),"Posted"]});case"failed":return e.jsxs(Oe,{variant:"destructive",className:"gap-1",children:[e.jsx(Rd,{className:"h-3 w-3"}),"Failed"]});case"cancelled":return e.jsxs(Oe,{variant:"outline",className:"gap-1 text-muted-foreground",children:[e.jsx(Xo,{className:"h-3 w-3"}),"Cancelled"]});default:return e.jsx(Oe,{variant:"outline",children:ie})}},H=Array.from({length:12},(ie,te)=>String(te+1)),Y=["00","15","30","45"],Z=j.filter(ie=>ie.status==="scheduled").length,ne=j.filter(ie=>ie.status==="posted").length,ce=j.filter(ie=>ie.status==="scheduled"&&ie.scheduled_for&&Q3s(new Date(ie.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(ve,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:Z}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Scheduled"})]}),e.jsxs(ve,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:ce}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Upcoming"})]}),e.jsxs(ve,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:ne}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Posted"})]}),e.jsxs(ve,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:j.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(ve,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(pc,{className:"h-5 w-5"}),e.jsx("h3",{className:"font-semibold",children:"Calendar"})]}),e.jsx(Pj,{mode:"single",selected:r,onSelect:a,className:At("pointer-events-auto"),modifiers:{hasPost:E},modifiersStyles:{hasPost:{fontWeight:"bold",backgroundColor:"hsl(var(--primary) / 0.1)",borderRadius:"50%"}}}),r&&e.jsx(B,{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(D_,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("div",{className:"flex flex-wrap gap-1",children:["all","scheduled","posted","failed","cancelled"].map(ie=>e.jsx(B,{variant:i===ie?"default":"outline",size:"sm",onClick:()=>l(ie),className:"capitalize",children:ie},ie))})]}),S&&e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Ct,{className:"h-8 w-8 animate-spin text-muted-foreground"})}),!S&&C.length===0&&e.jsxs(ve,{className:"p-8 text-center",children:[e.jsx(ga,{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:C.map(ie=>{var te,ae;return e.jsx(ve,{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:ie.image_url,alt:"Post preview",className:"w-full h-full object-cover"})}),e.jsxs(Me,{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:[G(ie.platform),e.jsx("span",{className:"font-medium",children:((te=ie.social_accounts)==null?void 0:te.page_name)||((ae=ie.social_accounts)==null?void 0:ae.platform_username)||"Unknown"}),$(ie.status)]}),e.jsxs("div",{className:"flex items-center gap-1",children:[ie.status==="scheduled"&&e.jsxs(FN,{children:[e.jsxs(ag,{children:[e.jsx(ig,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>O(ie),children:e.jsx(Ya,{className:"h-4 w-4"})})}),e.jsx(Nx,{children:"Edit post"})]}),e.jsxs(ag,{children:[e.jsx(ig,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>D.mutate(ie),disabled:D.isPending,children:D.isPending?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Or,{className:"h-4 w-4"})})}),e.jsx(Nx,{children:"Post now"})]}),e.jsxs(Kl,{children:[e.jsx(jx,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive",children:e.jsx(Sn,{className:"h-4 w-4"})})}),e.jsxs(Ol,{children:[e.jsxs(zl,{children:[e.jsx(Ul,{children:"Cancel this scheduled post?"}),e.jsx(ql,{children:"This will cancel the post. You can delete it entirely or keep it in your history."})]}),e.jsxs(Bl,{children:[e.jsx($l,{children:"Keep"}),e.jsx(Ml,{onClick:()=>M.mutate(ie.id),className:"bg-amber-600 hover:bg-amber-700",children:"Cancel Post"}),e.jsx(Ml,{onClick:()=>I.mutate(ie.id),className:"bg-destructive hover:bg-destructive/90",children:"Delete"})]})]})]})]}),(ie.status==="posted"||ie.status==="cancelled"||ie.status==="failed")&&e.jsxs(Kl,{children:[e.jsx(jx,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive",children:e.jsx(Sn,{className:"h-4 w-4"})})}),e.jsxs(Ol,{children:[e.jsxs(zl,{children:[e.jsx(Ul,{children:"Delete this post?"}),e.jsx(ql,{children:"This will permanently remove this post from your history."})]}),e.jsxs(Bl,{children:[e.jsx($l,{children:"Cancel"}),e.jsx(Ml,{onClick:()=>I.mutate(ie.id),className:"bg-destructive hover:bg-destructive/90",children:"Delete"})]})]})]})]})]}),ie.caption&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-2",children:ie.caption}),e.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Gr,{className:"h-3 w-3"}),ie.status==="posted"&&ie.posted_at?`Posted ${Hs(new Date(ie.posted_at),"PPp")}`:ie.scheduled_for?`Scheduled for ${Hs(new Date(ie.scheduled_for),"PPp")}`:"Not scheduled"]}),ie.status==="failed"&&ie.error_message&&e.jsxs("p",{className:"text-xs text-destructive mt-2",children:["Error: ",ie.error_message]})]})]})},ie.id)})})]})]}),e.jsx(Ls,{open:!!o,onOpenChange:ie=>!ie&&c(null),children:e.jsxs(Ps,{className:"max-w-lg",children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Edit Scheduled Post"}),e.jsx(_r,{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(J,{children:"Caption"}),e.jsx(Ms,{value:d,onChange:ie=>u(ie.target.value),rows:3})]}),e.jsxs("div",{className:"space-y-3 p-4 border rounded-lg",children:[e.jsx(J,{children:"Schedule for"}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs(od,{children:[e.jsx(ld,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:At("justify-start text-left font-normal flex-1",!h&&"text-muted-foreground"),children:[e.jsx(ga,{className:"mr-2 h-4 w-4"}),h?Hs(h,"PPP"):"Pick a date"]})}),e.jsx(Qc,{className:"w-auto p-0",align:"start",children:e.jsx(Pj,{mode:"single",selected:h,onSelect:m,disabled:ie=>iee.jsx(He,{value:ie,children:ie},ie))})]}),e.jsx("span",{className:"text-muted-foreground",children:":"}),e.jsxs(is,{value:y,onValueChange:v,children:[e.jsx(rs,{className:"w-[70px]",children:e.jsx(ls,{})}),e.jsx(as,{children:Y.map(ie=>e.jsx(He,{value:ie,children:ie},ie))})]}),e.jsxs(is,{value:g,onValueChange:ie=>b(ie),children:[e.jsx(rs,{className:"w-[70px]",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"AM",children:"AM"}),e.jsx(He,{value:"PM",children:"PM"})]})]})]})]})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>c(null),children:"Cancel"}),e.jsxs(B,{onClick:V,disabled:P.isPending,children:[P.isPending?e.jsx(Ct,{className:"h-4 w-4 animate-spin mr-2"}):null,"Save Changes"]})]})]})})]})}function tce(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 $qt={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 tce=="function"&&tce;if(!u&&h)return h(d,!0);if(o)return o(d,!0);var m=new Error("Cannot find module '"+d+"'");throw m.code="MODULE_NOT_FOUND",m}var p=a[d]={exports:{}};r[d][0].call(p.exports,function(f){var y=r[d][1][f];return l(y||f)},p,p.exports,n,r,a,i)}return a[d].exports}for(var o=typeof tce=="function"&&tce,c=0;c>2,p=(3&d)<<4|u>>4,f=1>6:64,y=2>4,u=(15&m)<<4|(p=o.indexOf(c.charAt(y++)))>>2,h=(3&p)<<6|(f=o.indexOf(c.charAt(y++))),b[v++]=d,p!==64&&(b[v++]=u),f!==64&&(b[v++]=h);return b}},{"./support":30,"./utils":32}],2:[function(n,r,a){var i=n("./external"),l=n("./stream/DataWorker"),o=n("./stream/Crc32Probe"),c=n("./stream/DataLengthProbe");function d(u,h,m,p,f){this.compressedSize=u,this.uncompressedSize=h,this.crc32=m,this.compression=p,this.compressedContent=f}d.prototype={getContentWorker:function(){var u=new l(i.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new c("data_length")),h=this;return u.on("end",function(){if(this.streamInfo.data_length!==h.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),u},getCompressedWorker:function(){return new l(i.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},d.createWorkerFrom=function(u,h,m){return u.pipe(new o).pipe(new c("uncompressedSize")).pipe(h.compressWorker(m)).pipe(new c("compressedSize")).withStreamInfo("compression",h)},r.exports=d},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(n,r,a){var i=n("./stream/GenericWorker");a.STORE={magic:"\0\0",compressWorker:function(){return new i("STORE compression")},uncompressWorker:function(){return new i("STORE decompression")}},a.DEFLATE=n("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(n,r,a){var i=n("./utils"),l=function(){for(var o,c=[],d=0;d<256;d++){o=d;for(var u=0;u<8;u++)o=1&o?3988292384^o>>>1:o>>>1;c[d]=o}return c}();r.exports=function(o,c){return o!==void 0&&o.length?i.getTypeOf(o)!=="string"?function(d,u,h,m){var p=l,f=m+h;d^=-1;for(var y=m;y>>8^p[255&(d^u[y])];return-1^d}(0|c,o,o.length,0):function(d,u,h,m){var p=l,f=m+h;d^=-1;for(var y=m;y>>8^p[255&(d^u.charCodeAt(y))];return-1^d}(0|c,o,o.length,0):0}},{"./utils":32}],5:[function(n,r,a){a.base64=!1,a.binary=!1,a.dir=!1,a.createFolders=!0,a.date=null,a.compression=null,a.compressionOptions=null,a.comment=null,a.unixPermissions=null,a.dosPermissions=null},{}],6:[function(n,r,a){var i=null;i=typeof Promise<"u"?Promise:n("lie"),r.exports={Promise:i}},{lie:37}],7:[function(n,r,a){var i=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Uint32Array<"u",l=n("pako"),o=n("./utils"),c=n("./stream/GenericWorker"),d=i?"uint8array":"array";function u(h,m){c.call(this,"FlateWorker/"+h),this._pako=null,this._pakoAction=h,this._pakoOptions=m,this.meta={}}a.magic="\b\0",o.inherits(u,c),u.prototype.processChunk=function(h){this.meta=h.meta,this._pako===null&&this._createPako(),this._pako.push(o.transformTo(d,h.data),!1)},u.prototype.flush=function(){c.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)},u.prototype.cleanUp=function(){c.prototype.cleanUp.call(this),this._pako=null},u.prototype._createPako=function(){this._pako=new l[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var h=this;this._pako.onData=function(m){h.push({data:m,meta:h.meta})}},a.compressWorker=function(h){return new u("Deflate",h)},a.uncompressWorker=function(){return new u("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(n,r,a){function i(p,f){var y,v="";for(y=0;y>>=8;return v}function l(p,f,y,v,g,b){var j,S,C=p.file,E=p.compression,P=b!==d.utf8encode,M=o.transformTo("string",b(C.name)),I=o.transformTo("string",d.utf8encode(C.name)),D=C.comment,O=o.transformTo("string",b(D)),V=o.transformTo("string",d.utf8encode(D)),G=I.length!==C.name.length,$=V.length!==D.length,H="",Y="",Z="",ne=C.dir,ce=C.date,ie={crc32:0,compressedSize:0,uncompressedSize:0};f&&!y||(ie.crc32=p.crc32,ie.compressedSize=p.compressedSize,ie.uncompressedSize=p.uncompressedSize);var te=0;f&&(te|=8),P||!G&&!$||(te|=2048);var ae=0,le=0;ne&&(ae|=16),g==="UNIX"?(le=798,ae|=function(me,he){var pe=me;return me||(pe=he?16893:33204),(65535&pe)<<16}(C.unixPermissions,ne)):(le=20,ae|=function(me){return 63&(me||0)}(C.dosPermissions)),j=ce.getUTCHours(),j<<=6,j|=ce.getUTCMinutes(),j<<=5,j|=ce.getUTCSeconds()/2,S=ce.getUTCFullYear()-1980,S<<=4,S|=ce.getUTCMonth()+1,S<<=5,S|=ce.getUTCDate(),G&&(Y=i(1,1)+i(u(M),4)+I,H+="up"+i(Y.length,2)+Y),$&&(Z=i(1,1)+i(u(O),4)+V,H+="uc"+i(Z.length,2)+Z);var be="";return be+=` \0`,be+=i(te,2),be+=E.magic,be+=i(j,2),be+=i(S,2),be+=i(ie.crc32,4),be+=i(ie.compressedSize,4),be+=i(ie.uncompressedSize,4),be+=i(M.length,2),be+=i(H.length,2),{fileRecord:h.LOCAL_FILE_HEADER+be+M+H,dirRecord:h.CENTRAL_FILE_HEADER+i(le,2)+be+i(O.length,2)+"\0\0\0\0"+i(ae,4)+i(v,4)+M+H+O}}var o=n("../utils"),c=n("../stream/GenericWorker"),d=n("../utf8"),u=n("../crc32"),h=n("../signature");function m(p,f,y,v){c.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=f,this.zipPlatform=y,this.encodeFileName=v,this.streamFiles=p,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}o.inherits(m,c),m.prototype.push=function(p){var f=p.meta.percent||0,y=this.entriesCount,v=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:y?(f+100*(y-v-1))/y:100}}))},m.prototype.openedSource=function(p){this.currentSourceOffset=this.bytesWritten,this.currentFile=p.file.name;var f=this.streamFiles&&!p.file.dir;if(f){var y=l(p,f,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:y.fileRecord,meta:{percent:0}})}else this.accumulate=!0},m.prototype.closedSource=function(p){this.accumulate=!1;var f=this.streamFiles&&!p.file.dir,y=l(p,f,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(y.dirRecord),f)this.push({data:function(v){return h.DATA_DESCRIPTOR+i(v.crc32,4)+i(v.compressedSize,4)+i(v.uncompressedSize,4)}(p),meta:{percent:100}});else for(this.push({data:y.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},m.prototype.flush=function(){for(var p=this.bytesWritten,f=0;f=this.index;c--)d=(d<<8)+this.byteAt(c);return this.index+=o,d},readString:function(o){return i.transformTo("string",this.readData(o))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var o=this.readInt(4);return new Date(Date.UTC(1980+(o>>25&127),(o>>21&15)-1,o>>16&31,o>>11&31,o>>5&63,(31&o)<<1))}},r.exports=l},{"../utils":32}],19:[function(n,r,a){var i=n("./Uint8ArrayReader");function l(o){i.call(this,o)}n("../utils").inherits(l,i),l.prototype.readData=function(o){this.checkOffset(o);var c=this.data.slice(this.zero+this.index,this.zero+this.index+o);return this.index+=o,c},r.exports=l},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(n,r,a){var i=n("./DataReader");function l(o){i.call(this,o)}n("../utils").inherits(l,i),l.prototype.byteAt=function(o){return this.data.charCodeAt(this.zero+o)},l.prototype.lastIndexOfSignature=function(o){return this.data.lastIndexOf(o)-this.zero},l.prototype.readAndCheckSignature=function(o){return o===this.readData(4)},l.prototype.readData=function(o){this.checkOffset(o);var c=this.data.slice(this.zero+this.index,this.zero+this.index+o);return this.index+=o,c},r.exports=l},{"../utils":32,"./DataReader":18}],21:[function(n,r,a){var i=n("./ArrayReader");function l(o){i.call(this,o)}n("../utils").inherits(l,i),l.prototype.readData=function(o){if(this.checkOffset(o),o===0)return new Uint8Array(0);var c=this.data.subarray(this.zero+this.index,this.zero+this.index+o);return this.index+=o,c},r.exports=l},{"../utils":32,"./ArrayReader":17}],22:[function(n,r,a){var i=n("../utils"),l=n("../support"),o=n("./ArrayReader"),c=n("./StringReader"),d=n("./NodeBufferReader"),u=n("./Uint8ArrayReader");r.exports=function(h){var m=i.getTypeOf(h);return i.checkSupport(m),m!=="string"||l.uint8array?m==="nodebuffer"?new d(h):l.uint8array?new u(i.transformTo("uint8array",h)):new o(i.transformTo("array",h)):new c(h)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(n,r,a){a.LOCAL_FILE_HEADER="PK",a.CENTRAL_FILE_HEADER="PK",a.CENTRAL_DIRECTORY_END="PK",a.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK\x07",a.ZIP64_CENTRAL_DIRECTORY_END="PK",a.DATA_DESCRIPTOR="PK\x07\b"},{}],24:[function(n,r,a){var i=n("./GenericWorker"),l=n("../utils");function o(c){i.call(this,"ConvertWorker to "+c),this.destType=c}l.inherits(o,i),o.prototype.processChunk=function(c){this.push({data:l.transformTo(this.destType,c.data),meta:c.meta})},r.exports=o},{"../utils":32,"./GenericWorker":28}],25:[function(n,r,a){var i=n("./GenericWorker"),l=n("../crc32");function o(){i.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}n("../utils").inherits(o,i),o.prototype.processChunk=function(c){this.streamInfo.crc32=l(c.data,this.streamInfo.crc32||0),this.push(c)},r.exports=o},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(n,r,a){var i=n("../utils"),l=n("./GenericWorker");function o(c){l.call(this,"DataLengthProbe for "+c),this.propName=c,this.withStreamInfo(c,0)}i.inherits(o,l),o.prototype.processChunk=function(c){if(c){var d=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=d+c.data.length}l.prototype.processChunk.call(this,c)},r.exports=o},{"../utils":32,"./GenericWorker":28}],27:[function(n,r,a){var i=n("../utils"),l=n("./GenericWorker");function o(c){l.call(this,"DataWorker");var d=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,c.then(function(u){d.dataIsReady=!0,d.data=u,d.max=u&&u.length||0,d.type=i.getTypeOf(u),d.isPaused||d._tickAndRepeat()},function(u){d.error(u)})}i.inherits(o,l),o.prototype.cleanUp=function(){l.prototype.cleanUp.call(this),this.data=null},o.prototype.resume=function(){return!!l.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,i.delay(this._tickAndRepeat,[],this)),!0)},o.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(i.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},o.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var c=null,d=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":c=this.data.substring(this.index,d);break;case"uint8array":c=this.data.subarray(this.index,d);break;case"array":case"nodebuffer":c=this.data.slice(this.index,d)}return this.index=d,this.push({data:c,meta:{percent:this.max?this.index/this.max*100:0}})},r.exports=o},{"../utils":32,"./GenericWorker":28}],28:[function(n,r,a){function i(l){this.name=l||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}i.prototype={push:function(l){this.emit("data",l)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(l){this.emit("error",l)}return!0},error:function(l){return!this.isFinished&&(this.isPaused?this.generatedError=l:(this.isFinished=!0,this.emit("error",l),this.previous&&this.previous.error(l),this.cleanUp()),!0)},on:function(l,o){return this._listeners[l].push(o),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(l,o){if(this._listeners[l])for(var c=0;c "+l:l}},r.exports=i},{}],29:[function(n,r,a){var i=n("../utils"),l=n("./ConvertWorker"),o=n("./GenericWorker"),c=n("../base64"),d=n("../support"),u=n("../external"),h=null;if(d.nodestream)try{h=n("../nodejs/NodejsStreamOutputAdapter")}catch{}function m(f,y){return new u.Promise(function(v,g){var b=[],j=f._internalType,S=f._outputType,C=f._mimeType;f.on("data",function(E,P){b.push(E),y&&y(P)}).on("error",function(E){b=[],g(E)}).on("end",function(){try{var E=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)}}(S,function(P,M){var I,D=0,O=null,V=0;for(I=0;I"u")a.blob=!1;else{var i=new ArrayBuffer(0);try{a.blob=new Blob([i],{type:"application/zip"}).size===0}catch{try{var l=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);l.append(i),a.blob=l.getBlob("application/zip").size===0}catch{a.blob=!1}}}try{a.nodestream=!!n("readable-stream").Readable}catch{a.nodestream=!1}},{"readable-stream":16}],31:[function(n,r,a){for(var i=n("./utils"),l=n("./support"),o=n("./nodejsUtils"),c=n("./stream/GenericWorker"),d=new Array(256),u=0;u<256;u++)d[u]=252<=u?6:248<=u?5:240<=u?4:224<=u?3:192<=u?2:1;d[254]=d[254]=1;function h(){c.call(this,"utf-8 decode"),this.leftOver=null}function m(){c.call(this,"utf-8 encode")}a.utf8encode=function(p){return l.nodebuffer?o.newBufferFrom(p,"utf-8"):function(f){var y,v,g,b,j,S=f.length,C=0;for(b=0;b>>6:(v<65536?y[j++]=224|v>>>12:(y[j++]=240|v>>>18,y[j++]=128|v>>>12&63),y[j++]=128|v>>>6&63),y[j++]=128|63&v);return y}(p)},a.utf8decode=function(p){return l.nodebuffer?i.transformTo("nodebuffer",p).toString("utf-8"):function(f){var y,v,g,b,j=f.length,S=new Array(2*j);for(y=v=0;y>10&1023,S[v++]=56320|1023&g)}return S.length!==v&&(S.subarray?S=S.subarray(0,v):S.length=v),i.applyFromCharCode(S)}(p=i.transformTo(l.uint8array?"uint8array":"array",p))},i.inherits(h,c),h.prototype.processChunk=function(p){var f=i.transformTo(l.uint8array?"uint8array":"array",p.data);if(this.leftOver&&this.leftOver.length){if(l.uint8array){var y=f;(f=new Uint8Array(y.length+this.leftOver.length)).set(this.leftOver,0),f.set(y,this.leftOver.length)}else f=this.leftOver.concat(f);this.leftOver=null}var v=function(b,j){var S;for((j=j||b.length)>b.length&&(j=b.length),S=j-1;0<=S&&(192&b[S])==128;)S--;return S<0||S===0?j:S+d[b[S]]>j?S:j}(f),g=f;v!==f.length&&(l.uint8array?(g=f.subarray(0,v),this.leftOver=f.subarray(v,f.length)):(g=f.slice(0,v),this.leftOver=f.slice(v,f.length))),this.push({data:a.utf8decode(g),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(y){return y}function u(y,v){for(var g=0;g>8;this.dir=!!(16&this.externalFileAttributes),p==0&&(this.dosPermissions=63&this.externalFileAttributes),p==3&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||this.fileNameStr.slice(-1)!=="/"||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var p=i(this.extraFields[1].value);this.uncompressedSize===l.MAX_VALUE_32BITS&&(this.uncompressedSize=p.readInt(8)),this.compressedSize===l.MAX_VALUE_32BITS&&(this.compressedSize=p.readInt(8)),this.localHeaderOffset===l.MAX_VALUE_32BITS&&(this.localHeaderOffset=p.readInt(8)),this.diskNumberStart===l.MAX_VALUE_32BITS&&(this.diskNumberStart=p.readInt(4))}},readExtraFields:function(p){var f,y,v,g=p.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});p.index+4>>6:(p<65536?m[v++]=224|p>>>12:(m[v++]=240|p>>>18,m[v++]=128|p>>>12&63),m[v++]=128|p>>>6&63),m[v++]=128|63&p);return m},a.buf2binstring=function(h){return u(h,h.length)},a.binstring2buf=function(h){for(var m=new i.Buf8(h.length),p=0,f=m.length;p>10&1023,b[f++]=56320|1023&y)}return u(b,f)},a.utf8border=function(h,m){var p;for((m=m||h.length)>h.length&&(m=h.length),p=m-1;0<=p&&(192&h[p])==128;)p--;return p<0||p===0?m:p+c[h[p]]>m?p:m}},{"./common":41}],43:[function(n,r,a){r.exports=function(i,l,o,c){for(var d=65535&i|0,u=i>>>16&65535|0,h=0;o!==0;){for(o-=h=2e3>>1:l>>>1;o[c]=l}return o}();r.exports=function(l,o,c,d){var u=i,h=d+c;l^=-1;for(var m=d;m>>8^u[255&(l^o[m])];return-1^l}},{}],46:[function(n,r,a){var i,l=n("../utils/common"),o=n("./trees"),c=n("./adler32"),d=n("./crc32"),u=n("./messages"),h=0,m=4,p=0,f=-2,y=-1,v=4,g=2,b=8,j=9,S=286,C=30,E=19,P=2*S+1,M=15,I=3,D=258,O=D+I+1,V=42,G=113,$=1,H=2,Y=3,Z=4;function ne(Se,Fe){return Se.msg=u[Fe],Fe}function ce(Se){return(Se<<1)-(4Se.avail_out&&(Ne=Se.avail_out),Ne!==0&&(l.arraySet(Se.output,Fe.pending_buf,Fe.pending_out,Ne,Se.next_out),Se.next_out+=Ne,Fe.pending_out+=Ne,Se.total_out+=Ne,Se.avail_out-=Ne,Fe.pending-=Ne,Fe.pending===0&&(Fe.pending_out=0))}function ae(Se,Fe){o._tr_flush_block(Se,0<=Se.block_start?Se.block_start:-1,Se.strstart-Se.block_start,Fe),Se.block_start=Se.strstart,te(Se.strm)}function le(Se,Fe){Se.pending_buf[Se.pending++]=Fe}function be(Se,Fe){Se.pending_buf[Se.pending++]=Fe>>>8&255,Se.pending_buf[Se.pending++]=255&Fe}function me(Se,Fe){var Ne,Ye,Ve=Se.max_chain_length,qe=Se.strstart,Qe=Se.prev_length,Ue=Se.nice_match,Xe=Se.strstart>Se.w_size-O?Se.strstart-(Se.w_size-O):0,nt=Se.window,$e=Se.w_mask,Ge=Se.prev,ct=Se.strstart+D,xt=nt[qe+Qe-1],qt=nt[qe+Qe];Se.prev_length>=Se.good_match&&(Ve>>=2),Ue>Se.lookahead&&(Ue=Se.lookahead);do if(nt[(Ne=Fe)+Qe]===qt&&nt[Ne+Qe-1]===xt&&nt[Ne]===nt[qe]&&nt[++Ne]===nt[qe+1]){qe+=2,Ne++;do;while(nt[++qe]===nt[++Ne]&&nt[++qe]===nt[++Ne]&&nt[++qe]===nt[++Ne]&&nt[++qe]===nt[++Ne]&&nt[++qe]===nt[++Ne]&&nt[++qe]===nt[++Ne]&&nt[++qe]===nt[++Ne]&&nt[++qe]===nt[++Ne]&&qeXe&&--Ve!=0);return Qe<=Se.lookahead?Qe:Se.lookahead}function he(Se){var Fe,Ne,Ye,Ve,qe,Qe,Ue,Xe,nt,$e,Ge=Se.w_size;do{if(Ve=Se.window_size-Se.lookahead-Se.strstart,Se.strstart>=Ge+(Ge-O)){for(l.arraySet(Se.window,Se.window,Ge,Ge,0),Se.match_start-=Ge,Se.strstart-=Ge,Se.block_start-=Ge,Fe=Ne=Se.hash_size;Ye=Se.head[--Fe],Se.head[Fe]=Ge<=Ye?Ye-Ge:0,--Ne;);for(Fe=Ne=Ge;Ye=Se.prev[--Fe],Se.prev[Fe]=Ge<=Ye?Ye-Ge:0,--Ne;);Ve+=Ge}if(Se.strm.avail_in===0)break;if(Qe=Se.strm,Ue=Se.window,Xe=Se.strstart+Se.lookahead,nt=Ve,$e=void 0,$e=Qe.avail_in,nt<$e&&($e=nt),Ne=$e===0?0:(Qe.avail_in-=$e,l.arraySet(Ue,Qe.input,Qe.next_in,$e,Xe),Qe.state.wrap===1?Qe.adler=c(Qe.adler,Ue,$e,Xe):Qe.state.wrap===2&&(Qe.adler=d(Qe.adler,Ue,$e,Xe)),Qe.next_in+=$e,Qe.total_in+=$e,$e),Se.lookahead+=Ne,Se.lookahead+Se.insert>=I)for(qe=Se.strstart-Se.insert,Se.ins_h=Se.window[qe],Se.ins_h=(Se.ins_h<=I&&(Se.ins_h=(Se.ins_h<=I)if(Ye=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(Ve=Se.strstart+Se.lookahead-I,Ye=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<=Ve&&(Se.ins_h=(Se.ins_h<Se.pending_buf_size-5&&(Ne=Se.pending_buf_size-5);;){if(Se.lookahead<=1){if(he(Se),Se.lookahead===0&&Fe===h)return $;if(Se.lookahead===0)break}Se.strstart+=Se.lookahead,Se.lookahead=0;var Ye=Se.block_start+Ne;if((Se.strstart===0||Se.strstart>=Ye)&&(Se.lookahead=Se.strstart-Ye,Se.strstart=Ye,ae(Se,!1),Se.strm.avail_out===0)||Se.strstart-Se.block_start>=Se.w_size-O&&(ae(Se,!1),Se.strm.avail_out===0))return $}return Se.insert=0,Fe===m?(ae(Se,!0),Se.strm.avail_out===0?Y:Z):(Se.strstart>Se.block_start&&(ae(Se,!1),Se.strm.avail_out),$)}),new Ae(4,4,8,4,pe),new Ae(4,5,16,8,pe),new Ae(4,6,32,32,pe),new Ae(4,4,16,16,Ce),new Ae(8,16,32,32,Ce),new Ae(8,16,128,128,Ce),new Ae(8,32,128,256,Ce),new Ae(32,128,258,1024,Ce),new Ae(32,258,258,4096,Ce)],a.deflateInit=function(Se,Fe){return Ze(Se,Fe,b,15,8,0)},a.deflateInit2=Ze,a.deflateReset=ke,a.deflateResetKeep=ze,a.deflateSetHeader=function(Se,Fe){return Se&&Se.state?Se.state.wrap!==2?f:(Se.state.gzhead=Fe,p):f},a.deflate=function(Se,Fe){var Ne,Ye,Ve,qe;if(!Se||!Se.state||5>8&255),le(Ye,Ye.gzhead.time>>16&255),le(Ye,Ye.gzhead.time>>24&255),le(Ye,Ye.level===9?2:2<=Ye.strategy||Ye.level<2?4:0),le(Ye,255&Ye.gzhead.os),Ye.gzhead.extra&&Ye.gzhead.extra.length&&(le(Ye,255&Ye.gzhead.extra.length),le(Ye,Ye.gzhead.extra.length>>8&255)),Ye.gzhead.hcrc&&(Se.adler=d(Se.adler,Ye.pending_buf,Ye.pending,0)),Ye.gzindex=0,Ye.status=69):(le(Ye,0),le(Ye,0),le(Ye,0),le(Ye,0),le(Ye,0),le(Ye,Ye.level===9?2:2<=Ye.strategy||Ye.level<2?4:0),le(Ye,3),Ye.status=G);else{var Qe=b+(Ye.w_bits-8<<4)<<8;Qe|=(2<=Ye.strategy||Ye.level<2?0:Ye.level<6?1:Ye.level===6?2:3)<<6,Ye.strstart!==0&&(Qe|=32),Qe+=31-Qe%31,Ye.status=G,be(Ye,Qe),Ye.strstart!==0&&(be(Ye,Se.adler>>>16),be(Ye,65535&Se.adler)),Se.adler=1}if(Ye.status===69)if(Ye.gzhead.extra){for(Ve=Ye.pending;Ye.gzindex<(65535&Ye.gzhead.extra.length)&&(Ye.pending!==Ye.pending_buf_size||(Ye.gzhead.hcrc&&Ye.pending>Ve&&(Se.adler=d(Se.adler,Ye.pending_buf,Ye.pending-Ve,Ve)),te(Se),Ve=Ye.pending,Ye.pending!==Ye.pending_buf_size));)le(Ye,255&Ye.gzhead.extra[Ye.gzindex]),Ye.gzindex++;Ye.gzhead.hcrc&&Ye.pending>Ve&&(Se.adler=d(Se.adler,Ye.pending_buf,Ye.pending-Ve,Ve)),Ye.gzindex===Ye.gzhead.extra.length&&(Ye.gzindex=0,Ye.status=73)}else Ye.status=73;if(Ye.status===73)if(Ye.gzhead.name){Ve=Ye.pending;do{if(Ye.pending===Ye.pending_buf_size&&(Ye.gzhead.hcrc&&Ye.pending>Ve&&(Se.adler=d(Se.adler,Ye.pending_buf,Ye.pending-Ve,Ve)),te(Se),Ve=Ye.pending,Ye.pending===Ye.pending_buf_size)){qe=1;break}qe=Ye.gzindexVe&&(Se.adler=d(Se.adler,Ye.pending_buf,Ye.pending-Ve,Ve)),qe===0&&(Ye.gzindex=0,Ye.status=91)}else Ye.status=91;if(Ye.status===91)if(Ye.gzhead.comment){Ve=Ye.pending;do{if(Ye.pending===Ye.pending_buf_size&&(Ye.gzhead.hcrc&&Ye.pending>Ve&&(Se.adler=d(Se.adler,Ye.pending_buf,Ye.pending-Ve,Ve)),te(Se),Ve=Ye.pending,Ye.pending===Ye.pending_buf_size)){qe=1;break}qe=Ye.gzindexVe&&(Se.adler=d(Se.adler,Ye.pending_buf,Ye.pending-Ve,Ve)),qe===0&&(Ye.status=103)}else Ye.status=103;if(Ye.status===103&&(Ye.gzhead.hcrc?(Ye.pending+2>Ye.pending_buf_size&&te(Se),Ye.pending+2<=Ye.pending_buf_size&&(le(Ye,255&Se.adler),le(Ye,Se.adler>>8&255),Se.adler=0,Ye.status=G)):Ye.status=G),Ye.pending!==0){if(te(Se),Se.avail_out===0)return Ye.last_flush=-1,p}else if(Se.avail_in===0&&ce(Fe)<=ce(Ne)&&Fe!==m)return ne(Se,-5);if(Ye.status===666&&Se.avail_in!==0)return ne(Se,-5);if(Se.avail_in!==0||Ye.lookahead!==0||Fe!==h&&Ye.status!==666){var Ue=Ye.strategy===2?function(Xe,nt){for(var $e;;){if(Xe.lookahead===0&&(he(Xe),Xe.lookahead===0)){if(nt===h)return $;break}if(Xe.match_length=0,$e=o._tr_tally(Xe,0,Xe.window[Xe.strstart]),Xe.lookahead--,Xe.strstart++,$e&&(ae(Xe,!1),Xe.strm.avail_out===0))return $}return Xe.insert=0,nt===m?(ae(Xe,!0),Xe.strm.avail_out===0?Y:Z):Xe.last_lit&&(ae(Xe,!1),Xe.strm.avail_out===0)?$:H}(Ye,Fe):Ye.strategy===3?function(Xe,nt){for(var $e,Ge,ct,xt,qt=Xe.window;;){if(Xe.lookahead<=D){if(he(Xe),Xe.lookahead<=D&&nt===h)return $;if(Xe.lookahead===0)break}if(Xe.match_length=0,Xe.lookahead>=I&&0Xe.lookahead&&(Xe.match_length=Xe.lookahead)}if(Xe.match_length>=I?($e=o._tr_tally(Xe,1,Xe.match_length-I),Xe.lookahead-=Xe.match_length,Xe.strstart+=Xe.match_length,Xe.match_length=0):($e=o._tr_tally(Xe,0,Xe.window[Xe.strstart]),Xe.lookahead--,Xe.strstart++),$e&&(ae(Xe,!1),Xe.strm.avail_out===0))return $}return Xe.insert=0,nt===m?(ae(Xe,!0),Xe.strm.avail_out===0?Y:Z):Xe.last_lit&&(ae(Xe,!1),Xe.strm.avail_out===0)?$:H}(Ye,Fe):i[Ye.level].func(Ye,Fe);if(Ue!==Y&&Ue!==Z||(Ye.status=666),Ue===$||Ue===Y)return Se.avail_out===0&&(Ye.last_flush=-1),p;if(Ue===H&&(Fe===1?o._tr_align(Ye):Fe!==5&&(o._tr_stored_block(Ye,0,0,!1),Fe===3&&(ie(Ye.head),Ye.lookahead===0&&(Ye.strstart=0,Ye.block_start=0,Ye.insert=0))),te(Se),Se.avail_out===0))return Ye.last_flush=-1,p}return Fe!==m?p:Ye.wrap<=0?1:(Ye.wrap===2?(le(Ye,255&Se.adler),le(Ye,Se.adler>>8&255),le(Ye,Se.adler>>16&255),le(Ye,Se.adler>>24&255),le(Ye,255&Se.total_in),le(Ye,Se.total_in>>8&255),le(Ye,Se.total_in>>16&255),le(Ye,Se.total_in>>24&255)):(be(Ye,Se.adler>>>16),be(Ye,65535&Se.adler)),te(Se),0=Ne.w_size&&(qe===0&&(ie(Ne.head),Ne.strstart=0,Ne.block_start=0,Ne.insert=0),nt=new l.Buf8(Ne.w_size),l.arraySet(nt,Fe,$e-Ne.w_size,Ne.w_size,0),Fe=nt,$e=Ne.w_size),Qe=Se.avail_in,Ue=Se.next_in,Xe=Se.input,Se.avail_in=$e,Se.next_in=0,Se.input=Fe,he(Ne);Ne.lookahead>=I;){for(Ye=Ne.strstart,Ve=Ne.lookahead-(I-1);Ne.ins_h=(Ne.ins_h<>>=I=M>>>24,j-=I,(I=M>>>16&255)===0)H[u++]=65535&M;else{if(!(16&I)){if(!(64&I)){M=S[(65535&M)+(b&(1<>>=I,j-=I),j<15&&(b+=$[c++]<>>=I=M>>>24,j-=I,!(16&(I=M>>>16&255))){if(!(64&I)){M=C[(65535&M)+(b&(1<>>=I,j-=I,(I=u-h)>3,b&=(1<<(j-=D<<3))-1,i.next_in=c,i.next_out=u,i.avail_in=c>>24&255)+(V>>>8&65280)+((65280&V)<<8)+((255&V)<<24)}function b(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new i.Buf16(320),this.work=new i.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function j(V){var G;return V&&V.state?(G=V.state,V.total_in=V.total_out=G.total=0,V.msg="",G.wrap&&(V.adler=1&G.wrap),G.mode=f,G.last=0,G.havedict=0,G.dmax=32768,G.head=null,G.hold=0,G.bits=0,G.lencode=G.lendyn=new i.Buf32(y),G.distcode=G.distdyn=new i.Buf32(v),G.sane=1,G.back=-1,m):p}function S(V){var G;return V&&V.state?((G=V.state).wsize=0,G.whave=0,G.wnext=0,j(V)):p}function C(V,G){var $,H;return V&&V.state?(H=V.state,G<0?($=0,G=-G):($=1+(G>>4),G<48&&(G&=15)),G&&(G<8||15=Z.wsize?(i.arraySet(Z.window,G,$-Z.wsize,Z.wsize,0),Z.wnext=0,Z.whave=Z.wsize):(H<(Y=Z.wsize-Z.wnext)&&(Y=H),i.arraySet(Z.window,G,$-H,Y,Z.wnext),(H-=Y)?(i.arraySet(Z.window,G,$-H,H,0),Z.wnext=H,Z.whave=Z.wsize):(Z.wnext+=Y,Z.wnext===Z.wsize&&(Z.wnext=0),Z.whave>>8&255,$.check=o($.check,qe,2,0),ae=te=0,$.mode=2;break}if($.flags=0,$.head&&($.head.done=!1),!(1&$.wrap)||(((255&te)<<8)+(te>>8))%31){V.msg="incorrect header check",$.mode=30;break}if((15&te)!=8){V.msg="unknown compression method",$.mode=30;break}if(ae-=4,Se=8+(15&(te>>>=4)),$.wbits===0)$.wbits=Se;else if(Se>$.wbits){V.msg="invalid window size",$.mode=30;break}$.dmax=1<>8&1),512&$.flags&&(qe[0]=255&te,qe[1]=te>>>8&255,$.check=o($.check,qe,2,0)),ae=te=0,$.mode=3;case 3:for(;ae<32;){if(ce===0)break e;ce--,te+=H[Z++]<>>8&255,qe[2]=te>>>16&255,qe[3]=te>>>24&255,$.check=o($.check,qe,4,0)),ae=te=0,$.mode=4;case 4:for(;ae<16;){if(ce===0)break e;ce--,te+=H[Z++]<>8),512&$.flags&&(qe[0]=255&te,qe[1]=te>>>8&255,$.check=o($.check,qe,2,0)),ae=te=0,$.mode=5;case 5:if(1024&$.flags){for(;ae<16;){if(ce===0)break e;ce--,te+=H[Z++]<>>8&255,$.check=o($.check,qe,2,0)),ae=te=0}else $.head&&($.head.extra=null);$.mode=6;case 6:if(1024&$.flags&&(ce<(me=$.length)&&(me=ce),me&&($.head&&(Se=$.head.extra_len-$.length,$.head.extra||($.head.extra=new Array($.head.extra_len)),i.arraySet($.head.extra,H,Z,me,Se)),512&$.flags&&($.check=o($.check,H,me,Z)),ce-=me,Z+=me,$.length-=me),$.length))break e;$.length=0,$.mode=7;case 7:if(2048&$.flags){if(ce===0)break e;for(me=0;Se=H[Z+me++],$.head&&Se&&$.length<65536&&($.head.name+=String.fromCharCode(Se)),Se&&me>9&1,$.head.done=!0),V.adler=$.check=0,$.mode=12;break;case 10:for(;ae<32;){if(ce===0)break e;ce--,te+=H[Z++]<>>=7&ae,ae-=7&ae,$.mode=27;break}for(;ae<3;){if(ce===0)break e;ce--,te+=H[Z++]<>>=1)){case 0:$.mode=14;break;case 1:if(D($),$.mode=20,G!==6)break;te>>>=2,ae-=2;break e;case 2:$.mode=17;break;case 3:V.msg="invalid block type",$.mode=30}te>>>=2,ae-=2;break;case 14:for(te>>>=7&ae,ae-=7&ae;ae<32;){if(ce===0)break e;ce--,te+=H[Z++]<>>16^65535)){V.msg="invalid stored block lengths",$.mode=30;break}if($.length=65535&te,ae=te=0,$.mode=15,G===6)break e;case 15:$.mode=16;case 16:if(me=$.length){if(ce>>=5,ae-=5,$.ndist=1+(31&te),te>>>=5,ae-=5,$.ncode=4+(15&te),te>>>=4,ae-=4,286<$.nlen||30<$.ndist){V.msg="too many length or distance symbols",$.mode=30;break}$.have=0,$.mode=18;case 18:for(;$.have<$.ncode;){for(;ae<3;){if(ce===0)break e;ce--,te+=H[Z++]<>>=3,ae-=3}for(;$.have<19;)$.lens[Qe[$.have++]]=0;if($.lencode=$.lendyn,$.lenbits=7,Ne={bits:$.lenbits},Fe=d(0,$.lens,0,19,$.lencode,0,$.work,Ne),$.lenbits=Ne.bits,Fe){V.msg="invalid code lengths set",$.mode=30;break}$.have=0,$.mode=19;case 19:for(;$.have<$.nlen+$.ndist;){for(;Ae=(Ve=$.lencode[te&(1<<$.lenbits)-1])>>>16&255,Pe=65535&Ve,!((Ce=Ve>>>24)<=ae);){if(ce===0)break e;ce--,te+=H[Z++]<>>=Ce,ae-=Ce,$.lens[$.have++]=Pe;else{if(Pe===16){for(Ye=Ce+2;ae>>=Ce,ae-=Ce,$.have===0){V.msg="invalid bit length repeat",$.mode=30;break}Se=$.lens[$.have-1],me=3+(3&te),te>>>=2,ae-=2}else if(Pe===17){for(Ye=Ce+3;ae>>=Ce)),te>>>=3,ae-=3}else{for(Ye=Ce+7;ae>>=Ce)),te>>>=7,ae-=7}if($.have+me>$.nlen+$.ndist){V.msg="invalid bit length repeat",$.mode=30;break}for(;me--;)$.lens[$.have++]=Se}}if($.mode===30)break;if($.lens[256]===0){V.msg="invalid code -- missing end-of-block",$.mode=30;break}if($.lenbits=9,Ne={bits:$.lenbits},Fe=d(u,$.lens,0,$.nlen,$.lencode,0,$.work,Ne),$.lenbits=Ne.bits,Fe){V.msg="invalid literal/lengths set",$.mode=30;break}if($.distbits=6,$.distcode=$.distdyn,Ne={bits:$.distbits},Fe=d(h,$.lens,$.nlen,$.ndist,$.distcode,0,$.work,Ne),$.distbits=Ne.bits,Fe){V.msg="invalid distances set",$.mode=30;break}if($.mode=20,G===6)break e;case 20:$.mode=21;case 21:if(6<=ce&&258<=ie){V.next_out=ne,V.avail_out=ie,V.next_in=Z,V.avail_in=ce,$.hold=te,$.bits=ae,c(V,be),ne=V.next_out,Y=V.output,ie=V.avail_out,Z=V.next_in,H=V.input,ce=V.avail_in,te=$.hold,ae=$.bits,$.mode===12&&($.back=-1);break}for($.back=0;Ae=(Ve=$.lencode[te&(1<<$.lenbits)-1])>>>16&255,Pe=65535&Ve,!((Ce=Ve>>>24)<=ae);){if(ce===0)break e;ce--,te+=H[Z++]<>ze)])>>>16&255,Pe=65535&Ve,!(ze+(Ce=Ve>>>24)<=ae);){if(ce===0)break e;ce--,te+=H[Z++]<>>=ze,ae-=ze,$.back+=ze}if(te>>>=Ce,ae-=Ce,$.back+=Ce,$.length=Pe,Ae===0){$.mode=26;break}if(32&Ae){$.back=-1,$.mode=12;break}if(64&Ae){V.msg="invalid literal/length code",$.mode=30;break}$.extra=15&Ae,$.mode=22;case 22:if($.extra){for(Ye=$.extra;ae>>=$.extra,ae-=$.extra,$.back+=$.extra}$.was=$.length,$.mode=23;case 23:for(;Ae=(Ve=$.distcode[te&(1<<$.distbits)-1])>>>16&255,Pe=65535&Ve,!((Ce=Ve>>>24)<=ae);){if(ce===0)break e;ce--,te+=H[Z++]<>ze)])>>>16&255,Pe=65535&Ve,!(ze+(Ce=Ve>>>24)<=ae);){if(ce===0)break e;ce--,te+=H[Z++]<>>=ze,ae-=ze,$.back+=ze}if(te>>>=Ce,ae-=Ce,$.back+=Ce,64&Ae){V.msg="invalid distance code",$.mode=30;break}$.offset=Pe,$.extra=15&Ae,$.mode=24;case 24:if($.extra){for(Ye=$.extra;ae>>=$.extra,ae-=$.extra,$.back+=$.extra}if($.offset>$.dmax){V.msg="invalid distance too far back",$.mode=30;break}$.mode=25;case 25:if(ie===0)break e;if(me=be-ie,$.offset>me){if((me=$.offset-me)>$.whave&&$.sane){V.msg="invalid distance too far back",$.mode=30;break}he=me>$.wnext?(me-=$.wnext,$.wsize-me):$.wnext-me,me>$.length&&(me=$.length),pe=$.window}else pe=Y,he=ne-$.offset,me=$.length;for(ieP?(I=he[pe+v[G]],ae[le+v[G]]):(I=96,0),b=1<>ne)+(j-=b)]=M<<24|I<<16|D|0,j!==0;);for(b=1<>=1;if(b!==0?(te&=b-1,te+=b):te=0,G++,--be[V]==0){if(V===H)break;V=h[m+v[G]]}if(Y>>7)]}function le(Ve,qe){Ve.pending_buf[Ve.pending++]=255&qe,Ve.pending_buf[Ve.pending++]=qe>>>8&255}function be(Ve,qe,Qe){Ve.bi_valid>g-Qe?(Ve.bi_buf|=qe<>g-Ve.bi_valid,Ve.bi_valid+=Qe-g):(Ve.bi_buf|=qe<>>=1,Qe<<=1,0<--qe;);return Qe>>>1}function pe(Ve,qe,Qe){var Ue,Xe,nt=new Array(v+1),$e=0;for(Ue=1;Ue<=v;Ue++)nt[Ue]=$e=$e+Qe[Ue-1]<<1;for(Xe=0;Xe<=qe;Xe++){var Ge=Ve[2*Xe+1];Ge!==0&&(Ve[2*Xe]=he(nt[Ge]++,Ge))}}function Ce(Ve){var qe;for(qe=0;qe>1;1<=Qe;Qe--)ze(Ve,nt,Qe);for(Xe=ct;Qe=Ve.heap[1],Ve.heap[1]=Ve.heap[Ve.heap_len--],ze(Ve,nt,1),Ue=Ve.heap[1],Ve.heap[--Ve.heap_max]=Qe,Ve.heap[--Ve.heap_max]=Ue,nt[2*Xe]=nt[2*Qe]+nt[2*Ue],Ve.depth[Xe]=(Ve.depth[Qe]>=Ve.depth[Ue]?Ve.depth[Qe]:Ve.depth[Ue])+1,nt[2*Qe+1]=nt[2*Ue+1]=Xe,Ve.heap[1]=Xe++,ze(Ve,nt,1),2<=Ve.heap_len;);Ve.heap[--Ve.heap_max]=Ve.heap[1],function(qt,Vt){var Xt,fs,Ft,wt,Ts,vt,$s=Vt.dyn_tree,As=Vt.max_code,jn=Vt.stat_desc.static_tree,ar=Vt.stat_desc.has_stree,Dn=Vt.stat_desc.extra_bits,Ur=Vt.stat_desc.extra_base,Vs=Vt.stat_desc.max_length,hn=0;for(wt=0;wt<=v;wt++)qt.bl_count[wt]=0;for($s[2*qt.heap[qt.heap_max]+1]=0,Xt=qt.heap_max+1;Xt>=7;Xe>>=1)if(1&xt&&Ge.dyn_ltree[2*ct]!==0)return l;if(Ge.dyn_ltree[18]!==0||Ge.dyn_ltree[20]!==0||Ge.dyn_ltree[26]!==0)return o;for(ct=32;ct>>3,(nt=Ve.static_len+3+7>>>3)<=Xe&&(Xe=nt)):Xe=nt=Qe+5,Qe+4<=Xe&&qe!==-1?Ye(Ve,qe,Qe,Ue):Ve.strategy===4||nt===Xe?(be(Ve,2+(Ue?1:0),3),ke(Ve,O,V)):(be(Ve,4+(Ue?1:0),3),function(Ge,ct,xt,qt){var Vt;for(be(Ge,ct-257,5),be(Ge,xt-1,5),be(Ge,qt-4,4),Vt=0;Vt>>8&255,Ve.pending_buf[Ve.d_buf+2*Ve.last_lit+1]=255&qe,Ve.pending_buf[Ve.l_buf+Ve.last_lit]=255&Qe,Ve.last_lit++,qe===0?Ve.dyn_ltree[2*Qe]++:(Ve.matches++,qe--,Ve.dyn_ltree[2*($[Qe]+h+1)]++,Ve.dyn_dtree[2*ae(qe)]++),Ve.last_lit===Ve.lit_bufsize-1},a._tr_align=function(Ve){be(Ve,2,3),me(Ve,j,O),function(qe){qe.bi_valid===16?(le(qe,qe.bi_buf),qe.bi_buf=0,qe.bi_valid=0):8<=qe.bi_valid&&(qe.pending_buf[qe.pending++]=255&qe.bi_buf,qe.bi_buf>>=8,qe.bi_valid-=8)}(Ve)}},{"../utils/common":41}],53:[function(n,r,a){r.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(n,r,a){(function(i){(function(l,o){if(!l.setImmediate){var c,d,u,h,m=1,p={},f=!1,y=l.document,v=Object.getPrototypeOf&&Object.getPrototypeOf(l);v=v&&v.setTimeout?v:l,c={}.toString.call(l.process)==="[object process]"?function(S){process.nextTick(function(){b(S)})}:function(){if(l.postMessage&&!l.importScripts){var S=!0,C=l.onmessage;return l.onmessage=function(){S=!1},l.postMessage("","*"),l.onmessage=C,S}}()?(h="setImmediate$"+Math.random()+"$",l.addEventListener?l.addEventListener("message",j,!1):l.attachEvent("onmessage",j),function(S){l.postMessage(h+S,"*")}):l.MessageChannel?((u=new MessageChannel).port1.onmessage=function(S){b(S.data)},function(S){u.port2.postMessage(S)}):y&&"onreadystatechange"in y.createElement("script")?(d=y.documentElement,function(S){var C=y.createElement("script");C.onreadystatechange=function(){b(S),C.onreadystatechange=null,d.removeChild(C),C=null},d.appendChild(C)}):function(S){setTimeout(b,0,S)},v.setImmediate=function(S){typeof S!="function"&&(S=new Function(""+S));for(var C=new Array(arguments.length-1),E=0;E"u"?i===void 0?this:i:self)}).call(this,typeof Cp<"u"?Cp:typeof self<"u"?self:typeof window<"u"?window:{})},{}]},{},[10])(10)})})($qt);var Cen=$qt.exports;const Vqt=_d(Cen);function K7e(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 Hqt=({embedded:s=!1,onCompose:t}={})=>{hs();const[n,r]=_.useState(null),[a,i]=_.useState(null),[l,o]=_.useState("all"),[c,d]=_.useState(new Set),[u,h]=_.useState(!1),[m,p]=_.useState(!1),[f,y]=_.useState("images"),[v,g]=_.useState(null),{data:b=[],isLoading:j}=at({queryKey:["social-swag-2"],queryFn:async()=>{const{data:te,error:ae}=await q.from("social_swag_2").select("*").order("month",{ascending:!1}).order("sort_order");if(ae)throw ae;return te}}),{data:S=[]}=at({queryKey:["social-swag-2-months"],queryFn:async()=>{const{data:te,error:ae}=await q.from("social_swag_2_months").select("*").order("month",{ascending:!1});if(ae)throw ae;return te}}),{data:C=[]}=at({queryKey:["social-swag-2-reels"],queryFn:async()=>{const{data:te,error:ae}=await q.from("social_swag_2_reels").select("*").order("month",{ascending:!1});if(ae)throw ae;return te}}),{data:E=[]}=at({queryKey:["my-social-accounts-count"],queryFn:async()=>{const{data:te,error:ae}=await q.from("social_accounts").select("id, platform").eq("is_active",!0);if(ae)throw ae;return te||[]}}),P=E.length>0,M=_.useMemo(()=>l==="all"?null:C.find(te=>te.month===l)||null,[l,C]),I=_.useMemo(()=>[...new Set(b.map(ae=>ae.month))].sort((ae,le)=>le.localeCompare(ae)),[b]);_.useEffect(()=>{I.length>0&&l==="all"&&o(I[0])},[I,l]);const D=te=>{try{const ae=YQe(te,"yyyy-MM",new Date);return Hs(ae,"MMMM yyyy")}catch{return te}},O=_.useMemo(()=>l==="all"?b:b.filter(te=>te.month===l),[l,b]),V=_.useMemo(()=>{var te;return l==="all"?null:((te=S.find(ae=>ae.month===l))==null?void 0:te.canva_link)||null},[l,S]),G=async te=>{try{await navigator.clipboard.writeText(te),se.success("Caption copied to clipboard!")}catch{se.error("Failed to copy caption")}},$=async(te,ae)=>{try{const be=await(await fetch(te)).blob(),me=/iPhone|iPad|iPod|Android/i.test(navigator.userAgent),he=navigator.canShare&&navigator.canShare({files:[new File([be],"test.jpg",{type:"image/jpeg"})]});if(me&&he){const pe=new File([be],`social-swag-${ae}.jpg`,{type:"image/jpeg"});await navigator.share({files:[pe],title:"Social Swag Image"}),se.success("Image ready to save!")}else{const pe=window.URL.createObjectURL(be),Ce=document.createElement("a");Ce.href=pe,Ce.download=`social-swag-${ae}.jpg`,document.body.appendChild(Ce),Ce.click(),document.body.removeChild(Ce),window.URL.revokeObjectURL(pe),se.success("Image downloaded!")}}catch(le){le.name!=="AbortError"&&se.error("Failed to download image")}},H=te=>{d(ae=>{const le=new Set(ae);return le.has(te)?le.delete(te):le.add(te),le})},Y=()=>{d(new Set(O.map(te=>te.id)))},Z=()=>{d(new Set),h(!1)},ne=async()=>{const te=O.filter(ae=>c.has(ae.id));if(te.length===0){se.error("No images selected");return}p(!0),se.info(`Preparing ${te.length} images for download...`);try{const ae=new Vqt,le=[...te].sort((Ce,Ae)=>Ce.sort_order-Ae.sort_order);for(let Ce=0;Ce{u?H(te.id):r(te)},ie=({children:te})=>s?e.jsx(e.Fragment,{children:te}):e.jsx(zs,{title:"Social Swag 2.0",children:te});return e.jsx(ie,{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(Oe,{variant:"secondary",className:"bg-white/20 text-white border-0 backdrop-blur-sm",children:[e.jsx(un,{className:"h-3 w-3 mr-1"}),"New content monthly"]}),e.jsxs(Oe,{variant:"secondary",className:"bg-white/20 text-white border-0 backdrop-blur-sm",children:[e.jsx(hc,{className:"h-3 w-3 mr-1"}),b.length," images"]})]}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold mb-3",children:"Social Swag 📸"}),e.jsx("p",{className:"text-lg text-primary-foreground/90 max-w-2xl",children:"Ready-to-post social media images delivered to you monthly. Just download, copy the caption, and share with your audience!"})]})]}),e.jsxs(Yr,{defaultValue:"gallery",className:"space-y-6",children:[!s&&e.jsxs(Zr,{className:"grid w-full max-w-md grid-cols-2",children:[e.jsxs(Ht,{value:"gallery",className:"gap-2",children:[e.jsx(hc,{className:"h-4 w-4"}),"Gallery"]}),e.jsxs(Ht,{value:"scheduled",className:"gap-2",children:[e.jsx(pc,{className:"h-4 w-4"}),"Scheduled"]})]}),e.jsxs(Gt,{value:"gallery",className:"space-y-6",children:[P?e.jsx(ve,{className:"border rounded-xl",children:e.jsx(Me,{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(B,{variant:"outline",size:"sm",asChild:!0,className:"gap-2",children:e.jsx(ir,{to:"/mission-control/integrations",children:"Manage Accounts"})})]})})}):e.jsx(ve,{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(Me,{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(tf,{className:"h-5 w-5 text-blue-600"})}),e.jsx("div",{className:"p-2 rounded-full bg-pink-500/10",children:e.jsx(Im,{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(B,{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(ir,{to:"/social-connections",children:[e.jsx(vd,{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(te=>e.jsx("button",{onClick:()=>o(te),className:At("px-4 py-2 rounded-full text-sm font-medium transition-all",l===te?"bg-primary text-primary-foreground shadow-sm":"bg-muted text-muted-foreground hover:text-foreground"),children:D(te)},te))}),l!=="all"&&(V?e.jsxs("a",{href:V,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:()=>{y("images"),Z()},className:At("flex items-center gap-2 px-4 py-2 rounded-full text-sm font-medium transition-all",f==="images"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:[e.jsx(hc,{className:"h-4 w-4"}),"Images"]}),e.jsxs("button",{onClick:()=>{y("reels"),Z()},className:At("flex items-center gap-2 px-4 py-2 rounded-full text-sm font-medium transition-all",f==="reels"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:[e.jsx(dm,{className:"h-4 w-4"}),"Reels"]})]}),f==="images"&&e.jsx("div",{className:"flex flex-wrap items-center gap-3",children:u?e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:Y,className:"gap-2",children:["Select All (",O.length,")"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:Z,className:"gap-2",children:[e.jsx(Qn,{className:"h-4 w-4"}),"Cancel"]}),c.size>0&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(B,{size:"sm",onClick:ne,disabled:m,className:"gap-2",children:[e.jsx(li,{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(B,{variant:"outline",size:"sm",onClick:()=>h(!0),className:"gap-2",children:[e.jsx(ea,{className:"h-4 w-4"}),"Select Images"]})})]}),j&&e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading..."}),!j&&f==="images"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4",children:O.map(te=>{const ae=c.has(te.id);return e.jsx(ve,{className:At("group cursor-pointer overflow-hidden border-0 shadow-md hover:shadow-xl transition-all duration-300 rounded-2xl",u&&ae&&"ring-2 ring-primary ring-offset-2"),onClick:()=>ce(te),children:e.jsxs("div",{className:"relative aspect-[4/5] overflow-hidden",children:[e.jsx("img",{src:K7e(te.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"}),te.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(te.post_date+"T00:00:00"),"MMM d")})}),u&&e.jsx("div",{className:At("absolute top-2 right-2 w-6 h-6 rounded-full border-2 flex items-center justify-center transition-all",ae?"bg-primary border-primary text-primary-foreground":"bg-white/80 border-muted-foreground/50"),children:ae&&e.jsx(ea,{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"})})]})},te.id)})}),O.length===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx(hc,{className:"h-12 w-12 text-muted-foreground/50 mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"No images available for this month yet."})]})]}),!j&&f==="reels"&&e.jsx(e.Fragment,{children:M?e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 gap-4",children:e.jsx(ve,{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:K7e(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(Oe,{variant:"secondary",className:"bg-black/50 text-white border-0 backdrop-blur-sm text-xs",children:[e.jsx(dm,{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(dm,{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(Ls,{open:!!n,onOpenChange:()=>r(null),children:e.jsx(Ps,{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:K7e(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(ga,{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(ga,{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(B,{onClick:()=>{if(t){t({mediaUrl:n.image_url,mediaType:"image",caption:n.caption,swagItemId:n.id}),r(null);return}g({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(Or,{className:"h-4 w-4"}),"Create Post"]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs(B,{variant:"outline",onClick:()=>G(n.caption),className:"flex-1 gap-2",children:[e.jsx(Ia,{className:"h-4 w-4"}),"Copy Caption"]}),e.jsxs(B,{variant:"outline",onClick:()=>$(n.image_url,n.id),className:"flex-1 gap-2",children:[e.jsx(li,{className:"h-4 w-4"}),"Download"]})]})]})]})]})})})}),e.jsx(Ls,{open:!!a,onOpenChange:()=>i(null),children:e.jsx(Ps,{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(dm,{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(B,{onClick:()=>G(a.caption||""),className:"flex-1 gap-2",children:[e.jsx(Ia,{className:"h-4 w-4"}),"Copy Caption"]}),a.canva_link&&e.jsxs(B,{variant:"outline",onClick:()=>window.open(a.canva_link,"_blank"),className:"flex-1 gap-2",children:[e.jsx(wr,{className:"h-4 w-4"}),"Open in Canva"]})]})]})]})})})}),e.jsx(ken,{open:!!v,onOpenChange:te=>!te&&g(null),imageUrl:(v==null?void 0:v.imageUrl)||"",imageId:(v==null?void 0:v.imageId)||"",defaultCaption:(v==null?void 0:v.caption)||"",swagItemId:v==null?void 0:v.imageId})]}),e.jsx(Gt,{value:"scheduled",children:e.jsx(Sen,{})})]})]})})},Myt={facebook:{id:"facebook",label:"Facebook Page",icon:tf,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:Im,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:dg,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:Xa,dot:"bg-emerald-600",chip:"bg-emerald-600/10 text-emerald-700 border-emerald-600/20",captionLimit:1500,supportsVideo:!1,requiresMedia:!1}},tE=s=>Myt[s]??Myt.facebook,Aen=[{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}],Pyt="agent-uploads",Een="social-studio",Ten=200*1024*1024,Lyt=s=>typeof s=="number"?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s):"";function Men({onSelect:s}){const{user:t}=hs(),n=_.useRef(null),[r,a]=_.useState(!1),{data:i=[]}=at({queryKey:["studio-uploads",t==null?void 0:t.id],enabled:!!(t!=null&&t.id),queryFn:async()=>{const{data:d,error:u}=await q.from("social_media_assets").select("*").eq("user_id",t.id).order("created_at",{ascending:!1}).limit(60);if(u)throw u;return d??[]}}),{data:l=[]}=at({queryKey:["studio-swag"],queryFn:async()=>{const{data:d,error:u}=await q.from("social_swag_2").select("id, image_url, caption, month").order("month",{ascending:!1}).order("sort_order").limit(120);if(u)throw u;return d??[]}}),{data:o=[]}=at({queryKey:["studio-listings",t==null?void 0:t.id],enabled:!!(t!=null&&t.id),queryFn:async()=>{const{data:d,error:u}=await q.from("listings").select("id, property_address, city, state, price, bedrooms, bathrooms, square_footage, status, listing_photos(photo_url, sort_order, is_primary)").eq("agent_id",t.id).order("created_at",{ascending:!1}).limit(40);if(u)throw u;return d??[]}}),c=async d=>{if(!(t!=null&&t.id))return;if(d.size>Ten){se.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=`${Een}/${t.id}/${crypto.randomUUID()}.${h}`,{error:p}=await q.storage.from(Pyt).upload(m,d,{cacheControl:"3600",upsert:!1,contentType:d.type});if(p)throw p;const{data:f}=q.storage.from(Pyt).getPublicUrl(m),y=f.publicUrl;await q.from("social_media_assets").insert({user_id:t.id,storage_path:m,public_url:y,media_type:u?"video":"image",file_name:d.name,file_size:d.size}),s({mediaUrl:y,mediaType:u?"video":"image",source:"upload"}),se.success("Media uploaded")}catch(h){console.error(h),se.error("Upload failed. Please try again.")}finally{a(!1),n.current&&(n.current.value="")}};return e.jsxs(Yr,{defaultValue:"upload",className:"space-y-4",children:[e.jsxs(Zr,{className:"grid grid-cols-3 w-full",children:[e.jsxs(Ht,{value:"upload",className:"gap-2",children:[e.jsx(Oa,{className:"h-4 w-4"}),"Upload"]}),e.jsxs(Ht,{value:"swag",className:"gap-2",children:[e.jsx(un,{className:"h-4 w-4"}),"Gallery"]}),e.jsxs(Ht,{value:"listings",className:"gap-2",children:[e.jsx(Jr,{className:"h-4 w-4"}),"Listings"]})]}),e.jsxs(Gt,{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(ve,{className:"border-dashed border-2",children:e.jsxs(Me,{className:"p-6 flex flex-col items-center text-center gap-3",children:[e.jsx(hc,{className:"h-8 w-8 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Upload a photo or video"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"JPG, PNG or MP4 up to 200MB"})]}),e.jsxs(B,{onClick:()=>{var d;return(d=n.current)==null?void 0:d.click()},disabled:r,className:"gap-2",children:[r?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Oa,{className:"h-4 w-4"}),r?"Uploading…":"Choose file"]})]})}),i.length>0&&e.jsx(Ji,{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(Oe,{className:"absolute bottom-1 left-1 text-[10px]",children:"Video"})]},d.id))})})]}),e.jsx(Gt,{value:"swag",children:e.jsx(Ji,{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(Gt,{value:"listings",children:e.jsx(Ji,{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}`,Lyt(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(ve,{children:e.jsxs(Me,{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:Lyt(d.price)})]}),e.jsx(Oe,{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 Pen({platform:s,accountName:t,avatarUrl:n,caption:r,mediaUrl:a,mediaType:i}){const l=tE(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(ve,{className:"overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-3 p-3 border-b",children:[e.jsxs(ja,{className:"h-9 w-9",children:[e.jsx(pi,{src:n??void 0,alt:t}),e.jsx(Na,{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(Do,{className:"h-5 w-5"}),e.jsx(Ou,{className:"h-5 w-5"}),e.jsx(Or,{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(Fg,{className:"h-4 w-4"})," Like"]}),e.jsxs("span",{className:"flex items-center gap-1 text-xs",children:[e.jsx(Ou,{className:"h-4 w-4"})," Comment"]}),e.jsxs("span",{className:"flex items-center gap-1 text-xs",children:[e.jsx(nJ,{className:"h-4 w-4"})," Share"]})]})]})]})}function Gqt(){const{user:s}=hs();return at({queryKey:["studio-accounts",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),queryFn:async()=>{const{data:t,error:n}=await q.from("social_accounts").select("id, platform, platform_username, page_name, profile_picture_url, is_active").eq("user_id",s.id).eq("is_active",!0).order("platform");if(n)throw n;return t??[]}})}function Len(s){const{user:t}=hs();return at({queryKey:["studio-posts",t==null?void 0:t.id,"all"],enabled:!!(t!=null&&t.id),queryFn:async()=>{let n=q.from("social_posts").select("*, social_post_targets(*)").eq("user_id",t.id).order("created_at",{ascending:!1}).limit(500);const{data:r,error:a}=await n;if(a)throw a;return r??[]}})}function Ien(){const s=Bt();return()=>{s.invalidateQueries({queryKey:["studio-posts"]}),s.invalidateQueries({queryKey:["studio-accounts"]})}}const Den="America/New_York",Wqt="levelup.calendar.timezone";function j7(s){if(!s)return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:s}),!0}catch{return!1}}function Ren(){try{const s=localStorage.getItem(Wqt);if(j7(s))return s}catch{}return null}let G4e=Ren();function RE(){return G4e||gae()}function Iyt(s){G4e=j7(s)?s:gae();try{localStorage.setItem(Wqt,G4e)}catch{}return G4e}function gae(){const s=Intl.DateTimeFormat().resolvedOptions().timeZone;return j7(s)?s:Den}function pP(s,t=new Date){try{const n=new Intl.DateTimeFormat("en-US",{timeZone:s,timeZoneName:"short"}).formatToParts(t).find(r=>r.type==="timeZoneName");return(n==null?void 0:n.value)||""}catch{return""}}function Y7e(s,t=new Date){try{return new Intl.DateTimeFormat("en-US",{timeZone:s,hour:"numeric",minute:"2-digit"}).format(t)}catch{return""}}const Kqt=[{value:"America/New_York",label:"Eastern — New York"},{value:"America/Detroit",label:"Eastern — Detroit"},{value:"America/Indiana/Indianapolis",label:"Eastern — Indianapolis"},{value:"America/Chicago",label:"Central — Chicago"},{value:"America/Denver",label:"Mountain — Denver"},{value:"America/Phoenix",label:"Mountain (no DST) — Phoenix"},{value:"America/Los_Angeles",label:"Pacific — Los Angeles"},{value:"America/Anchorage",label:"Alaska — Anchorage"},{value:"Pacific/Honolulu",label:"Hawaii — Honolulu"},{value:"America/Toronto",label:"Eastern — Toronto"},{value:"America/Vancouver",label:"Pacific — Vancouver"},{value:"America/Puerto_Rico",label:"Atlantic — Puerto Rico"}];function Fen(){var r;let s=[];try{s=((r=Intl.supportedValuesOf)==null?void 0:r.call(Intl,"timeZone"))||[]}catch{s=[]}const t=Kqt.map(a=>a.value),n=s.filter(a=>!t.includes(a));return[...t,...n]}function Oen(s,t){const n=(s||"").split("@")[0].replace(/[^a-z0-9]+/gi,"-").toLowerCase(),r=(t||"").slice(0,6);return`${n||"agent"}-${r}`.replace(/^-+|-+$/g,"")||`agent-${Date.now()}`}function yae(){const{user:s}=hs(),t=Bt(),n=at({queryKey:["calendar-timezone",s==null?void 0:s.id],enabled:!!s,staleTime:5*6e4,queryFn:async()=>{const{data:i,error:l}=await q.from("agent_booking_settings").select("timezone").eq("user_id",s.id).maybeSingle();if(l)throw l;return(i==null?void 0:i.timezone)||null}});_.useEffect(()=>{n.data&&j7(n.data)&&Iyt(n.data)},[n.data]);const r=j7(n.data)?n.data:RE()||gae(),a=mt({mutationFn:async i=>{if(!j7(i))throw new Error("That timezone isn't recognized");const{data:l,error:o}=await q.from("agent_booking_settings").update({timezone:i}).eq("user_id",s.id).select("id");if(o)throw o;if(!l||l.length===0){const{error:c}=await q.from("agent_booking_settings").insert({user_id:s.id,slug:Oen(s.email,s.id),timezone:i,is_active:!1});if(c)throw c}return Iyt(i),i},onSuccess:i=>{t.setQueryData(["calendar-timezone",s==null?void 0:s.id],i),t.invalidateQueries({queryKey:["booking-settings"]}),t.invalidateQueries({queryKey:["my-calendar"]}),se.success("Calendar timezone updated")},onError:i=>se.error(i.message||"Could not update timezone")});return{timezone:r,isLoading:n.isLoading,update:a}}function Yqt({open:s,onOpenChange:t}){const{timezone:n,update:r}=yae(),[a,i]=_.useState(n),[l,o]=_.useState("");_.useEffect(()=>{s&&(i(n),o(""))},[s,n]);const c=gae(),d=_.useMemo(()=>{const h=l.trim().toLowerCase();return h?Fen().filter(m=>m.toLowerCase().includes(h.replace(/\s+/g,"_"))).slice(0,40):[]},[l]),u=()=>{r.mutate(a,{onSuccess:()=>t(!1)})};return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"max-w-lg max-h-[85vh] overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsxs(Ds,{className:"flex items-center gap-2",children:[e.jsx($2,{className:"h-4 w-4 text-primary"}),"Calendar settings"]}),e.jsx(_r,{children:"Pick the timezone your calendar, appointments and bookings display in."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-xl border bg-muted/40 px-4 py-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Currently showing"}),e.jsxs("p",{className:"text-sm font-medium mt-0.5",children:[a.replace(/_/g," ")," ",e.jsxs("span",{className:"text-muted-foreground",children:["· ",Y7e(a)," ",pP(a)]})]})]}),c!==a&&e.jsxs(B,{type:"button",variant:"outline",size:"sm",className:"w-full justify-start gap-2",onClick:()=>i(c),children:[e.jsx(Xa,{className:"h-4 w-4"}),"Use my device timezone (",c.replace(/_/g," "),")"]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{className:"text-sm font-medium",children:"Common timezones"}),e.jsx("div",{className:"grid gap-1.5",children:Kqt.map(h=>e.jsxs("button",{type:"button",onClick:()=>i(h.value),className:At("flex items-center justify-between rounded-lg border px-3 py-2 text-left text-sm transition-colors",a===h.value?"border-primary bg-primary/5 font-medium":"hover:bg-muted/60"),children:[e.jsx("span",{children:h.label}),e.jsx(Oe,{variant:"secondary",className:"text-[10px]",children:Y7e(h.value)})]},h.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"tz-search",className:"text-sm font-medium",children:"Search all timezones"}),e.jsx(xe,{id:"tz-search",value:l,onChange:h=>o(h.target.value),placeholder:"e.g. Denver, London, Sao Paulo"}),d.length>0&&e.jsx("div",{className:"max-h-52 overflow-y-auto rounded-lg border divide-y",children:d.map(h=>e.jsxs("button",{type:"button",onClick:()=>i(h),className:At("flex w-full items-center justify-between px-3 py-2 text-left text-sm transition-colors",a===h?"bg-primary/5 font-medium":"hover:bg-muted/60"),children:[e.jsx("span",{children:h.replace(/_/g," ")}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Y7e(h)})]},h))})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(B,{variant:"ghost",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{onClick:u,disabled:r.isPending||a===n,children:[r.isPending&&e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}),"Save timezone"]})]})]})})}const y4=s=>String(s).padStart(2,"0");function vae(s){return j7(s)?s:RE()}function Ntt(s,t){const n=new Intl.DateTimeFormat("en-US",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1}),r={};for(const a of n.formatToParts(s))a.type!=="literal"&&(r[a.type]=Number(a.value));return r.hour===24&&(r.hour=0),r}function Dyt(s,t){const n=Ntt(s,t);return Date.UTC(n.year,n.month-1,n.day,n.hour,n.minute,n.second)-s.getTime()}function pHe(s,t){const n=vae(t),[r,a="00:00"]=s.split("T"),[i,l,o]=r.split("-").map(Number),[c,d]=a.split(":").map(Number),u=Date.UTC(i,(l||1)-1,o||1,c||0,d||0,0);let h=new Date(u-Dyt(new Date(u),n));return h=new Date(u-Dyt(h,n)),h}function Zqt(s,t){const n=vae(t),r=typeof s=="string"?new Date(s):s,a=Ntt(r,n);return`${a.year}-${y4(a.month)}-${y4(a.day)}T${y4(a.hour)}:${y4(a.minute)}`}function zen(s,t){const n=vae(t),r=typeof s=="string"?new Date(s):s,a=Ntt(r,n);return`${a.year}-${a.month-1}-${a.day}`}function Xqt(s,t,n){const r=typeof s=="string"?new Date(s):s;return new Intl.DateTimeFormat("en-US",{timeZone:vae(t),...n}).format(r)}function Qqt(s,t){return Xqt(s,t,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZoneName:"short"})}function Ben(s,t){return Xqt(s,t,{hour:"numeric",minute:"2-digit"})}function Uen(s,t,n,r){const a=vae(n),i=r&&r.includes("T")?r.split("T")[0]:Zqt(new Date,a).split("T")[0];let l=`${i}T${y4(s)}:${y4(t)}`;if(pHe(l,a).getTime()<=Date.now()){const[o,c,d]=i.split("-").map(Number),u=new Date(Date.UTC(o,c-1,d+1));l=`${u.getUTCFullYear()}-${y4(u.getUTCMonth()+1)}-${y4(u.getUTCDate())}T${y4(s)}:${y4(t)}`}return l}const sce=s=>s.page_name||s.platform_username||tE(s.platform).label;function qen({seed:s,editingPost:t,onSaved:n,onCancelEdit:r}){const{user:a}=hs(),{data:i=[],isLoading:l}=Gqt(),{timezone:o}=yae(),[c,d]=_.useState(!1),u=he=>Zqt(he,o),[h,m]=_.useState(""),[p,f]=_.useState(null),[y,v]=_.useState("text"),[g,b]=_.useState("manual"),[j,S]=_.useState([]),[C,E]=_.useState({}),[P,M]=_.useState(!1),[I,D]=_.useState(!1),[O,V]=_.useState(""),[G,$]=_.useState(null);_.useEffect(()=>{s&&(s.mediaUrl&&(f(s.mediaUrl),v(s.mediaType??"image")),s.caption!==void 0&&m(s.caption),s.source&&b(s.source),s.scheduledFor&&(D(!0),V(u(s.scheduledFor))))},[s]),_.useEffect(()=>{var pe;if(!t)return;m(t.caption??""),f(((pe=t.media_urls)==null?void 0:pe[0])??null),v(t.media_type),b(t.source??"manual"),S(t.social_post_targets.map(Ce=>Ce.social_account_id));const he={};t.social_post_targets.forEach(Ce=>{Ce.caption_override&&(he[Ce.social_account_id]=Ce.caption_override)}),E(he),M(Object.keys(he).length>0),t.scheduled_for&&(D(!0),V(u(new Date(t.scheduled_for))))},[t]);const H=_.useMemo(()=>i.filter(he=>j.includes(he.id)),[i,j]),Y=he=>{var pe;return P&&((pe=C[he])!=null&&pe.trim())?C[he]:h},Z=_.useMemo(()=>{const he=[];return H.forEach(pe=>{const Ce=tE(pe.platform),Ae=Y(pe.id);Ce.requiresMedia&&!p&&he.push(`${Ce.label} requires a photo or video.`),!Ce.supportsVideo&&y==="video"&&he.push(`${Ce.label} can't publish video from LevelUp yet.`),Ae.length>Ce.captionLimit&&he.push(`${Ce.label} caption is over the ${Ce.captionLimit.toLocaleString()} character limit.`)}),Array.from(new Set(he))},[H,p,y,h,C,P]),ne=()=>{m(""),f(null),v("text"),b("manual"),S([]),E({}),M(!1),D(!1),V("")},ce=he=>{f(he.mediaUrl),v(he.mediaType),b(he.source),he.caption&&!h.trim()&&m(he.caption)},ie=he=>S(pe=>pe.includes(he)?pe.filter(Ce=>Ce!==he):[...pe,he]),te=async he=>{if(a!=null&&a.id){if(he!=="draft"&&j.length===0){se.error("Choose at least one account to post to.");return}if(he!=="draft"&&!h.trim()&&!p){se.error("Add a caption or media before publishing.");return}if(he==="schedule"&&!O){se.error("Pick a date and time to schedule.");return}if(he!=="draft"&&Z.length>0){se.error(Z[0]);return}$(he);try{const pe={user_id:a.id,caption:h.trim()||null,media_type:y,media_urls:p?[p]:[],source:g,status:he==="draft"?"draft":he==="schedule"?"scheduled":"publishing",scheduled_for:he==="schedule"?pHe(O,o).toISOString():null,timezone:o};let Ce=(t==null?void 0:t.id)??null;if(Ce){const{error:Ae}=await q.from("social_posts").update(pe).eq("id",Ce);if(Ae)throw Ae;await q.from("social_post_targets").delete().eq("post_id",Ce)}else{const{data:Ae,error:Pe}=await q.from("social_posts").insert(pe).select("id").single();if(Pe)throw Pe;Ce=Ae.id}if(j.length>0){const Ae=H.map(ze=>{var ke;return{post_id:Ce,user_id:a.id,social_account_id:ze.id,platform:ze.platform,caption_override:P&&((ke=C[ze.id])!=null&&ke.trim())?C[ze.id].trim():null,status:"pending"}}),{error:Pe}=await q.from("social_post_targets").insert(Ae);if(Pe)throw Pe}if(he==="now"){const{data:Ae,error:Pe}=await q.functions.invoke("social-publish-post",{body:{post_id:Ce}});if(Pe)throw Pe;const ze=Ae==null?void 0:Ae.status;ze==="failed"?se.error("Publishing failed. Check the Queue tab for details."):ze==="partial"?se.warning("Some accounts failed. Check the Queue tab to retry."):se.success("Posted to your accounts.")}else se.success(he==="draft"?"Draft saved":"Post scheduled");t||ne(),n==null||n()}catch(pe){console.error(pe),se.error((pe==null?void 0:pe.message)??"Something went wrong saving your post.")}finally{$(null)}}},ae=(he,pe)=>{D(!0),V(Uen(he,pe,o,O))},le=pP(o),be=gae(),me=be!==o;return e.jsxs("div",{className:"grid gap-6 lg:grid-cols-[minmax(0,1fr)_380px]",children:[e.jsxs("div",{className:"space-y-6",children:[t&&e.jsx(Ete,{children:e.jsxs(Tte,{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{children:"Editing a saved post."}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:r,className:"gap-1",children:[e.jsx(Qn,{className:"h-4 w-4"})," Cancel"]})]})}),e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-3",children:e.jsx(St,{className:"text-base",children:"1. Choose your media"})}),e.jsxs(Me,{className:"space-y-4",children:[p&&e.jsxs("div",{className:"relative w-full max-w-xs overflow-hidden rounded-lg border",children:[y==="video"?e.jsx("video",{src:p,className:"w-full",controls:!0,playsInline:!0}):e.jsx("img",{src:p,alt:"Selected media",className:"w-full object-cover"}),e.jsx(B,{variant:"secondary",size:"icon",className:"absolute top-2 right-2 h-8 w-8",onClick:()=>{f(null),v("text")},children:e.jsx(Sn,{className:"h-4 w-4"})})]}),e.jsx(Men,{onSelect:ce})]})]}),e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-3",children:e.jsx(St,{className:"text-base",children:"2. Write your caption"})}),e.jsxs(Me,{className:"space-y-4",children:[e.jsx(Ms,{value:h,onChange:he=>m(he.target.value),rows:6,placeholder:"What do you want to share with your audience?"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-xs text-muted-foreground",children:[h.length," characters"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(J,{htmlFor:"per-platform",className:"text-xs",children:"Customize per platform"}),e.jsx(fn,{id:"per-platform",checked:P,onCheckedChange:M})]})]}),P&&H.length>0&&e.jsxs(Yr,{defaultValue:H[0].id,className:"pt-2",children:[e.jsx(Zr,{className:"flex-wrap h-auto",children:H.map(he=>e.jsx(Ht,{value:he.id,className:"text-xs",children:sce(he)},he.id))}),H.map(he=>e.jsx(Gt,{value:he.id,className:"pt-3",children:e.jsx(Ms,{rows:5,value:C[he.id]??"",placeholder:`Leave blank to use the main caption for ${tE(he.platform).label}`,onChange:pe=>E(Ce=>({...Ce,[he.id]:pe.target.value}))})},he.id))]})]})]}),e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-3",children:e.jsx(St,{className:"text-base",children:"3. Pick your accounts"})}),e.jsxs(Me,{className:"space-y-3",children:[l&&e.jsx(Ct,{className:"h-4 w-4 animate-spin text-muted-foreground"}),!l&&i.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No connected accounts yet. Connect Facebook, Instagram, LinkedIn or Google Business in Social settings."}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:i.map(he=>{const pe=tE(he.platform),Ce=pe.icon,Ae=j.includes(he.id);return e.jsxs("button",{type:"button",onClick:()=>ie(he.id),className:`flex items-center gap-3 rounded-lg border p-3 text-left transition ${Ae?"border-primary bg-primary/5":"hover:bg-muted/50"}`,children:[e.jsxs(ja,{className:"h-9 w-9",children:[e.jsx(pi,{src:he.profile_picture_url??void 0}),e.jsx(Na,{children:sce(he).slice(0,2).toUpperCase()})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:sce(he)}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Ce,{className:"h-3 w-3"})," ",pe.label]})]}),Ae&&e.jsx(ea,{className:"h-4 w-4 text-primary"})]},he.id)})})]})]}),e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-3",children:e.jsx(St,{className:"text-base",children:"4. Publish or schedule"})}),e.jsxs(Me,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(J,{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(fn,{id:"schedule-toggle",checked:I,onCheckedChange:D})]}),I&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(xe,{type:"datetime-local",value:O,onChange:he=>V(he.target.value)}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-xs text-muted-foreground",children:[e.jsx($2,{className:"h-3.5 w-3.5"}),e.jsxs("span",{children:["Times are in ",e.jsx("span",{className:"font-medium text-foreground",children:o.replace(/_/g," ")}),le?` (${le})`:""]}),e.jsx("button",{type:"button",className:"underline underline-offset-2 hover:text-foreground",onClick:()=>d(!0),children:"Change"})]}),O&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Goes out ",e.jsx("span",{className:"font-medium text-foreground",children:Qqt(pHe(O,o),o)})]}),me&&e.jsxs("p",{className:"text-xs text-amber-600",children:["Your device is set to ",be.replace(/_/g," ")," — posts still go out on your ",le||"saved"," schedule."]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Aen.map(he=>e.jsx(B,{type:"button",variant:"outline",size:"sm",onClick:()=>ae(he.hour,he.minute),children:he.label},he.label))})]}),Z.length>0&&e.jsxs(Ete,{variant:"destructive",children:[e.jsx(xl,{className:"h-4 w-4"}),e.jsx(Tte,{children:e.jsx("ul",{className:"list-disc pl-4 space-y-1",children:Z.map(he=>e.jsx("li",{children:he},he))})})]}),e.jsx(wc,{}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(B,{variant:"outline",onClick:()=>te("draft"),disabled:!!G,className:"gap-2",children:[G==="draft"?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Ho,{className:"h-4 w-4"}),"Save draft"]}),I?e.jsxs(B,{onClick:()=>te("schedule"),disabled:!!G,className:"gap-2",children:[G==="schedule"?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Qd,{className:"h-4 w-4"}),"Schedule post"]}):e.jsxs(B,{onClick:()=>te("now"),disabled:!!G,className:"gap-2",children:[G==="now"?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Or,{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(Oe,{variant:"secondary",children:[H.length," selected"]})]}),H.length===0?e.jsx(ve,{children:e.jsx(Me,{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:H.map(he=>e.jsx(Pen,{platform:he.platform,accountName:sce(he),avatarUrl:he.profile_picture_url,caption:Y(he.id),mediaUrl:p,mediaType:y},he.id))})]}),e.jsx(Yqt,{open:c,onOpenChange:d})]})}const $en=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],Ryt={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 Ven({posts:s,onCreateAt:t,onOpenPost:n}){const{timezone:r}=yae(),a=pP(r),[i,l]=_.useState(()=>{const h=new Date;return new Date(h.getFullYear(),h.getMonth(),1)}),o=_.useMemo(()=>{const h=new Date(i);return h.setDate(1-h.getDay()),Array.from({length:42},(m,p)=>{const f=new Date(h);return f.setDate(h.getDate()+p),f})},[i]),c=_.useMemo(()=>{const h=new Map;return s.forEach(m=>{const p=m.scheduled_for??m.published_at;if(!p)return;const f=zen(p,r);h.set(f,[...h.get(f)??[],m])}),h},[s,r]),d=new Date,u=h=>h.toDateString()===d.toDateString();return e.jsx(ve,{children:e.jsxs(Me,{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold",children:i.toLocaleDateString("en-US",{month:"long",year:"numeric"})}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["All times ",a||r.replace(/_/g," ")]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(B,{variant:"outline",size:"sm",onClick:()=>l(new Date(d.getFullYear(),d.getMonth(),1)),children:"Today"}),e.jsx(B,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>l(new Date(i.getFullYear(),i.getMonth()-1,1)),children:e.jsx($c,{className:"h-4 w-4"})}),e.jsx(B,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>l(new Date(i.getFullYear(),i.getMonth()+1,1)),children:e.jsx(xi,{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:$en.map(h=>e.jsx("div",{className:"py-1",children:h},h))}),e.jsx("div",{className:"grid grid-cols-7 gap-px bg-border rounded-lg overflow-hidden",children:o.map(h=>{const m=`${h.getFullYear()}-${h.getMonth()}-${h.getDate()}`,p=c.get(m)??[],f=h.getMonth()!==i.getMonth();return e.jsxs("div",{className:`group relative min-h-[104px] bg-background p-1.5 ${f?"opacity-50":""}`,children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:`text-xs ${u(h)?"flex h-5 w-5 items-center justify-center rounded-full bg-primary text-primary-foreground":"text-muted-foreground"}`,children:h.getDate()}),e.jsx("button",{type:"button","aria-label":"Create post",onClick:()=>{const y=new Date(h);y.setHours(9,0,0,0),t(y)},className:"opacity-0 group-hover:opacity-100 transition text-muted-foreground hover:text-foreground",children:e.jsx(rn,{className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"mt-1 space-y-1",children:[p.slice(0,3).map(y=>{var g;const v=y.scheduled_for??y.published_at;return e.jsxs("button",{type:"button",onClick:()=>n(y),className:`w-full rounded border px-1.5 py-1 text-left text-[10px] leading-tight ${Ryt[y.status]??Ryt.draft}`,children:[e.jsx("span",{className:"font-medium",children:Ben(v,r)})," ",e.jsx("span",{className:"truncate",children:((g=y.caption)==null?void 0:g.slice(0,24))||"Media post"}),e.jsx("span",{className:"mt-1 flex gap-1",children:y.social_post_targets.slice(0,4).map(b=>e.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${tE(b.platform).dot}`},b.id))})]},y.id)}),p.length>3&&e.jsxs(Oe,{variant:"secondary",className:"text-[10px]",children:["+",p.length-3," more"]})]})]},m)})})]})})}const Hen=s=>{switch(s){case"published":case"success":return{label:"Published",variant:"default",icon:Er};case"partial":return{label:"Partly published",variant:"secondary",icon:xl};case"failed":return{label:"Failed",variant:"destructive",icon:xl};case"publishing":case"pending":return{label:"Publishing",variant:"secondary",icon:Ct};case"scheduled":return{label:"Scheduled",variant:"outline",icon:Qd};default:return{label:"Draft",variant:"outline",icon:Ya}}};function Fyt({posts:s,accounts:t,onEdit:n,onChanged:r,emptyLabel:a}){const[i,l]=_.useState(null),{timezone:o}=yae(),c=h=>t.find(m=>m.id===h),d=async h=>{l(h.id);try{await q.from("social_posts").update({status:"publishing",scheduled_for:null,error_message:null}).eq("id",h.id),await q.from("social_post_targets").update({status:"pending"}).eq("post_id",h.id).in("status",["cancelled","failed"]);const{data:m,error:p}=await q.functions.invoke("social-publish-post",{body:{post_id:h.id}});if(p)throw p;const f=m==null?void 0:m.status;f==="failed"?se.error("Publishing failed. See the error details below."):f==="partial"?se.warning("Some accounts failed."):se.success("Published."),r()}catch(m){se.error((m==null?void 0:m.message)??"Could not publish this post.")}finally{l(null)}},u=async h=>{l(h.id);try{const{error:m}=await q.from("social_posts").delete().eq("id",h.id);if(m)throw m;se.success("Post deleted"),r()}catch(m){se.error((m==null?void 0:m.message)??"Could not delete this post.")}finally{l(null)}};return s.length===0?e.jsx(ve,{children:e.jsx(Me,{className:"p-8 text-center text-sm text-muted-foreground",children:a??"Nothing here yet."})}):e.jsx("div",{className:"space-y-3",children:s.map(h=>{var v,g;const p=h.status==="failed"&&!!((v=h.error_message)!=null&&v.startsWith("Missed its scheduled time"))?{label:"Didn't send",variant:"destructive",icon:xl}:Hen(h.status),f=p.icon,y=h.scheduled_for??h.published_at??h.created_at;return e.jsx(ve,{children:e.jsx(Me,{className:"p-4",children:e.jsxs("div",{className:"flex gap-4",children:[((g=h.media_urls)==null?void 0:g[0])&&(h.media_type==="video"?e.jsx("video",{src:h.media_urls[0],className:"h-20 w-20 rounded-lg object-cover shrink-0"}):e.jsx("img",{src:h.media_urls[0],alt:"",loading:"lazy",className:"h-20 w-20 rounded-lg object-cover shrink-0"})),e.jsxs("div",{className:"min-w-0 flex-1 space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(Oe,{variant:p.variant,className:"gap-1",children:[e.jsx(f,{className:`h-3 w-3 ${p.label==="Publishing"?"animate-spin":""}`}),p.label]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Qqt(y,h.timezone||o)})]}),e.jsx("p",{className:"text-sm line-clamp-2 whitespace-pre-wrap",children:h.caption||"Media only post"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:h.social_post_targets.map(b=>{const j=tE(b.platform),S=j.icon,C=c(b.social_account_id),E=b.status==="published",P=b.status==="failed";return e.jsxs("div",{className:`flex items-center gap-2 rounded-full border px-2.5 py-1 text-xs ${P?"border-destructive/30 bg-destructive/5 text-destructive":j.chip}`,children:[e.jsxs(ja,{className:"h-4 w-4",children:[e.jsx(pi,{src:(C==null?void 0:C.profile_picture_url)??void 0}),e.jsx(Na,{className:"text-[8px]",children:e.jsx(S,{className:"h-2.5 w-2.5"})})]}),e.jsx("span",{className:"max-w-[140px] truncate",children:(C==null?void 0:C.page_name)||(C==null?void 0:C.platform_username)||j.label}),E&&b.permalink&&e.jsx("a",{href:b.permalink,target:"_blank",rel:"noopener noreferrer","aria-label":"View post",children:e.jsx(wr,{className:"h-3 w-3"})}),P&&e.jsx(xl,{className:"h-3 w-3"})]},b.id)})}),h.error_message&&e.jsx("div",{className:"rounded-md border border-destructive/20 bg-destructive/5 p-2",children:e.jsx("p",{className:"text-xs text-destructive",children:h.error_message})}),h.social_post_targets.some(b=>b.status==="failed")&&e.jsx("div",{className:"rounded-md border border-destructive/20 bg-destructive/5 p-2 space-y-1",children:h.social_post_targets.filter(b=>b.status==="failed").map(b=>e.jsxs("p",{className:"text-xs text-destructive",children:[e.jsxs("span",{className:"font-medium",children:[tE(b.platform).label,":"]})," ",b.error_message||"Publishing failed."]},b.id))})]}),e.jsxs("div",{className:"flex flex-col gap-2 shrink-0",children:[e.jsxs(B,{variant:"outline",size:"sm",className:"gap-1",onClick:()=>n(h),children:[e.jsx(Ya,{className:"h-3.5 w-3.5"})," Edit"]}),h.status!=="published"&&e.jsxs(B,{size:"sm",className:"gap-1",disabled:i===h.id,onClick:()=>d(h),children:[i===h.id?e.jsx(Ct,{className:"h-3.5 w-3.5 animate-spin"}):h.status==="failed"||h.status==="partial"?e.jsx(uo,{className:"h-3.5 w-3.5"}):e.jsx(Or,{className:"h-3.5 w-3.5"}),h.status==="failed"||h.status==="partial"?"Retry":"Post now"]}),e.jsxs(B,{variant:"ghost",size:"sm",className:"gap-1 text-muted-foreground",disabled:i===h.id,onClick:()=>u(h),children:[e.jsx(Sn,{className:"h-3.5 w-3.5"})," Delete"]})]})]})})},h.id)})})}const Gen=()=>{const[s,t]=_.useState("compose"),[n,r]=_.useState(null),[a,i]=_.useState(null),{data:l=[]}=Gqt(),{data:o=[],isLoading:c}=Len(),d=Ien(),u=_.useMemo(()=>o.filter(y=>y.status==="scheduled"||y.status==="draft"||y.status==="publishing").sort((y,v)=>new Date(y.scheduled_for??y.created_at).getTime()-new Date(v.scheduled_for??v.created_at).getTime()),[o]),h=_.useMemo(()=>o.filter(y=>["published","partial","failed","cancelled"].includes(y.status)),[o]),m=h.filter(y=>y.status==="failed"||y.status==="partial").length,p=(y,v=null)=>{r(y),i(v),t("compose")},f=y=>{p({mediaUrl:y.mediaUrl,mediaType:y.mediaType,caption:y.caption,source:"swag",sourceRef:y.swagItemId??y.reelId})};return e.jsx(zs,{title:"Social Studio",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(ve,{className:"overflow-hidden border-none bg-gradient-to-br from-primary/10 via-background to-background",children:e.jsxs(Me,{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(Oe,{variant:"secondary",className:"gap-1",children:[e.jsx(un,{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(y=>e.jsxs(ja,{className:"h-8 w-8 border-2 border-background",title:y.page_name??y.platform,children:[e.jsx(pi,{src:y.profile_picture_url??void 0}),e.jsx(Na,{className:"text-[10px]",children:tE(y.platform).label.slice(0,2)})]},y.id))}),e.jsx(B,{variant:"outline",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(ir,{to:"/social-connections",children:[e.jsx(fS,{className:"h-4 w-4"})," Manage accounts"]})})]}),e.jsxs(B,{className:"gap-2",onClick:()=>p(null),children:[e.jsx(wp,{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:G4},{label:"Scheduled & drafts",value:u.length,icon:pc},{label:"Published",value:h.filter(y=>y.status==="published").length,icon:Er}].map(({label:y,value:v,icon:g})=>e.jsx(ve,{children:e.jsxs(Me,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"rounded-lg bg-primary/10 p-2",children:e.jsx(g,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xl font-semibold leading-none",children:v}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:y})]})]})},y))}),e.jsxs(Yr,{value:s,onValueChange:t,className:"space-y-6",children:[e.jsxs(Zr,{className:"flex-wrap h-auto",children:[e.jsxs(Ht,{value:"compose",className:"gap-2",children:[e.jsx(wp,{className:"h-4 w-4"}),"Compose"]}),e.jsxs(Ht,{value:"calendar",className:"gap-2",children:[e.jsx(pc,{className:"h-4 w-4"}),"Calendar"]}),e.jsxs(Ht,{value:"queue",className:"gap-2",children:[e.jsx(Or,{className:"h-4 w-4"}),"Queue",u.length>0&&e.jsx(Oe,{variant:"secondary",className:"ml-1",children:u.length})]}),e.jsxs(Ht,{value:"history",className:"gap-2",children:[e.jsx(Er,{className:"h-4 w-4"}),"History",m>0&&e.jsx(Oe,{variant:"destructive",className:"ml-1",children:m})]}),e.jsxs(Ht,{value:"gallery",className:"gap-2",children:[e.jsx(un,{className:"h-4 w-4"}),"Swag gallery"]})]}),e.jsx(Gt,{value:"compose",children:e.jsx(qen,{seed:n,editingPost:a,onSaved:()=>{d(),i(null),r(null)},onCancelEdit:()=>{i(null),r(null)}})}),e.jsx(Gt,{value:"calendar",children:e.jsx(Ven,{posts:o,onCreateAt:y=>p({scheduledFor:y}),onOpenPost:y=>p(null,y)})}),e.jsx(Gt,{value:"queue",children:e.jsx(Fyt,{posts:u,accounts:l,onEdit:y=>p(null,y),onChanged:d,emptyLabel:c?"Loading your posts…":"Nothing scheduled yet. Compose a post to get started."})}),e.jsx(Gt,{value:"history",children:e.jsx(Fyt,{posts:h,accounts:l,onEdit:y=>p(null,y),onChanged:d,emptyLabel:"Your published posts will show up here."})}),e.jsx(Gt,{value:"gallery",children:e.jsx(Hqt,{embedded:!0,onCompose:f})})]})]})})},Wen=[{id:"branding-bar",title:"Branding Bar Studio",description:"Drop in any image — get a branded version with your headshot, logo, and contact info.",icon:hc,to:"/marketing-studio/branding-bar",color:"from-violet-500 to-fuchsia-500"},{id:"listing-templates",title:"Listing Templates",description:"Just Listed, Just Sold, Open House, Price Drop — pulled from your MLS in one click.",icon:Jr,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:Fo,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:bl,comingSoon:!0,color:"from-orange-500 to-red-500"},{id:"milestones",title:"Client Milestones",description:"Closing day, home anniversaries, birthdays, referral thank-yous.",icon:Bf,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:sj,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:WA,comingSoon:!0,color:"from-amber-500 to-yellow-500"}];function Ken(){return e.jsx(zs,{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(Oe,{variant:"secondary",className:"mb-2 gap-1",children:[e.jsx(un,{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(B,{variant:"outline",asChild:!0,children:e.jsxs(ir,{to:"/marketing-studio/brand-kit",children:[e.jsx(Xc,{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:Wen.map(s=>{const t=s.icon,n=e.jsxs(ve,{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(Me,{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(Oe,{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(ir,{to:s.to,className:"block",children:n},s.id):e.jsx("div",{children:n},s.id)})})]})})}function bae(){const s=ha();return at({queryKey:["marketing-brand-presets",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("marketing_brand_presets").select("*").eq("user_id",s).order("is_default",{ascending:!1}).order("created_at",{ascending:!0});if(n)throw n;return t||[]},enabled:!!s})}function Yen(){const{data:s,...t}=bae();return{data:(s==null?void 0:s.find(n=>n.is_default))??(s==null?void 0:s[0])??null,...t}}function Zen(){const s=ha(),t=Bt();return mt({mutationFn:async n=>{if(!s)throw new Error("Not signed in");if(n.is_default&&await q.from("marketing_brand_presets").update({is_default:!1}).eq("user_id",s),n.id){const{id:r,...a}=n,{data:i,error:l}=await q.from("marketing_brand_presets").update(a).eq("id",r).eq("user_id",s).select().single();if(l)throw l;return i}else{const{data:r,error:a}=await q.from("marketing_brand_presets").insert({...n,user_id:s}).select().single();if(a)throw a;return r}},onSuccess:()=>t.invalidateQueries({queryKey:["marketing-brand-presets",s]})})}function Xen(){const s=ha(),t=Bt();return mt({mutationFn:async n=>{const{error:r}=await q.from("marketing_brand_presets").delete().eq("id",n);if(r)throw r},onSuccess:()=>t.invalidateQueries({queryKey:["marketing-brand-presets",s]})})}async function Qen(s,t,n){var o;const r=((o=t.name.split(".").pop())==null?void 0:o.toLowerCase())||"png",a=`${s}/${n}-${Date.now()}.${r}`,{error:i}=await q.storage.from("marketing-studio-uploads").upload(a,t,{upsert:!0,cacheControl:"3600"});if(i)throw i;const{data:l}=await q.storage.from("marketing-studio-uploads").createSignedUrl(a,60*60*24*365*5);return(l==null?void 0:l.signedUrl)??""}function Jen({preset:s,onSaved:t,onCancel:n}){var y;const r=ha(),a=Zen(),i=Xen(),l=_.useRef(null),o=_.useRef(null),[c,d]=_.useState(null),[u,h]=_.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"});_.useEffect(()=>{s||(async()=>{if(!r)return;const{supabase:v}=await za(async()=>{const{supabase:b}=await Promise.resolve().then(()=>Sws);return{supabase:b}},void 0),{data:g}=await v.from("profiles").select("name, email, phone, avatar_url, website_url, title, brokerage_id").eq("id",r).maybeSingle();g&&h(b=>({...b,display_name:b.display_name||(g.name??""),email:b.email||(g.email??""),phone:b.phone||(g.phone??""),headshot_url:b.headshot_url||(g.avatar_url??""),website_url:b.website_url||(g.website_url??""),tagline:b.tagline||(g.title??"")}))})()},[r]);const m=async(v,g)=>{if(r){d(v);try{const b=await Qen(r,g,v);h(j=>({...j,[v==="headshot"?"headshot_url":"brokerage_logo_url"]:b}))}catch(b){se.error(b.message||"Upload failed")}finally{d(null)}}},p=async()=>{try{const v=await a.mutateAsync({id:s==null?void 0:s.id,...u});se.success("Brand preset saved"),t==null||t(v)}catch(v){se.error(v.message||"Save failed")}},f=async()=>{s!=null&&s.id&&await Xi("Delete this brand preset?")&&(await i.mutateAsync(s.id),se.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(J,{children:"Preset name"}),e.jsx(xe,{value:u.name,onChange:v=>h({...u,name:v.target.value}),placeholder:"Personal, Team, Luxury..."})]}),e.jsxs("div",{className:"flex items-end gap-3 pb-1",children:[e.jsx(fn,{checked:u.is_default,onCheckedChange:v=>h({...u,is_default:v})}),e.jsx(J,{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(J,{children:"Display name"}),e.jsx(xe,{value:u.display_name,onChange:v=>h({...u,display_name:v.target.value})})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Phone"}),e.jsx(xe,{value:u.phone,onChange:v=>h({...u,phone:v.target.value})})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Email"}),e.jsx(xe,{value:u.email,onChange:v=>h({...u,email:v.target.value})})]}),e.jsxs("div",{children:[e.jsx(J,{children:"License #"}),e.jsx(xe,{value:u.license_number,onChange:v=>h({...u,license_number:v.target.value})})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(J,{children:"Tagline"}),e.jsx(xe,{value:u.tagline,onChange:v=>h({...u,tagline:v.target.value}),placeholder:"Helping families find home"})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(J,{children:"Website"}),e.jsx(xe,{value:u.website_url,onChange:v=>h({...u,website_url:v.target.value})})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Headshot"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(ja,{className:"h-16 w-16",children:[e.jsx(pi,{src:u.headshot_url||void 0}),e.jsx(Na,{children:((y=u.display_name)==null?void 0:y[0])??"A"})]}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:()=>{var v;return(v=l.current)==null?void 0:v.click()},disabled:c==="headshot",children:[c==="headshot"?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Oa,{className:"h-4 w-4 mr-1"}),"Upload"]}),e.jsx("input",{ref:l,type:"file",accept:"image/*",hidden:!0,onChange:v=>{var g;return((g=v.target.files)==null?void 0:g[0])&&m("headshot",v.target.files[0])}})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{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(B,{type:"button",variant:"outline",size:"sm",onClick:()=>{var v;return(v=o.current)==null?void 0:v.click()},disabled:c==="logo",children:[c==="logo"?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Oa,{className:"h-4 w-4 mr-1"}),"Upload"]}),e.jsx("input",{ref:o,type:"file",accept:"image/*",hidden:!0,onChange:v=>{var g;return((g=v.target.files)==null?void 0:g[0])&&m("logo",v.target.files[0])}})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Brand color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:u.brand_color,onChange:v=>h({...u,brand_color:v.target.value}),className:"h-10 w-14 rounded cursor-pointer border"}),e.jsx(xe,{value:u.brand_color,onChange:v=>h({...u,brand_color:v.target.value})})]})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Accent color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:u.accent_color,onChange:v=>h({...u,accent_color:v.target.value}),className:"h-10 w-14 rounded cursor-pointer border"}),e.jsx(xe,{value:u.accent_color,onChange:v=>h({...u,accent_color:v.target.value})})]})]})]}),e.jsxs("div",{className:"flex justify-between pt-2",children:[e.jsx("div",{children:(s==null?void 0:s.id)&&e.jsxs(B,{variant:"ghost",size:"sm",onClick:f,className:"text-destructive",children:[e.jsx(Sn,{className:"h-4 w-4 mr-1"})," Delete"]})}),e.jsxs("div",{className:"flex gap-2",children:[n&&e.jsx(B,{variant:"outline",onClick:n,children:"Cancel"}),e.jsxs(B,{onClick:p,disabled:a.isPending,children:[a.isPending&&e.jsx(Ct,{className:"h-4 w-4 mr-1 animate-spin"}),"Save preset"]})]})]})]})}function etn(){const{data:s,isLoading:t}=bae(),[n,r]=_.useState(null);return e.jsx(zs,{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(ir,{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(B,{onClick:()=>r("new"),className:"w-full sm:w-auto",children:[e.jsx(rn,{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(ve,{className:"border-dashed",children:e.jsxs(Me,{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(B,{onClick:()=>r("new"),children:[e.jsx(rn,{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(ve,{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(St,{className:"text-lg flex items-center gap-2",children:[a.name,a.is_default&&e.jsxs(Oe,{variant:"secondary",className:"gap-1",children:[e.jsx(Da,{className:"h-3 w-3"})," Default"]})]}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>r(a),children:e.jsx(Ya,{className:"h-4 w-4"})})]}),e.jsx(kn,{children:a.display_name})]}),e.jsxs(Me,{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(Ls,{open:n!==null,onOpenChange:a=>!a&&r(null),children:e.jsxs(Ps,{className:"max-w-2xl max-h-[90vh] overflow-y-auto w-[calc(100vw-2rem)] sm:w-full",children:[e.jsx(Os,{children:e.jsx(Ds,{children:n==="new"?"New brand preset":"Edit brand preset"})}),e.jsx(Jen,{preset:n==="new"?null:n,onSaved:()=>r(null),onCancel:()=>r(null)})]})})]})})}const fHe=[{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"}],ttn=s=>fHe.find(t=>t.id===s)??fHe[0];function stn(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 ntn({value:s,onChange:t,mediaType:n}){const r=fHe.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:At("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(rtn,{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 rtn({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 atn=Math.PI/180;function itn(){return typeof window<"u"&&({}.toString.call(window)==="[object Window]"||{}.toString.call(window)==="[object global]")}const bF=typeof global<"u"?global:typeof window<"u"?window:typeof WorkerGlobalScope<"u"?self:{},yi={_global:bF,version:"10.2.5",isBrowser:itn(),isUnminified:/param/.test((function(s){}).toString()),dblClickWindow:400,getAngle(s){return yi.angleDeg?s*atn: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 yi.DD.isDragging},isTransforming(){var s,t;return(t=(s=yi.Transformer)===null||s===void 0?void 0:s.isTransforming())!==null&&t!==void 0?t:!1},isDragReady(){return!!yi.DD.node},releaseCanvasOnDestroy:!0,document:bF.document,_injectGlobal(s){typeof bF.Konva<"u"&&console.error("Several Konva instances detected. It is not recommended to use multiple Konva instances in the same environment."),bF.Konva=s}},Zf=s=>{yi[s.prototype.getClassName()]=s};yi._injectGlobal(yi);const otn=`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"; `,Oyt=()=>{if(typeof document>"u")throw new Error(otn)};class Jw{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 Jw(this.m)}copyInto(t){t.m[0]=this.m[0],t.m[1]=this.m[1],t.m[2]=this.m[2],t.m[3]=this.m[3],t.m[4]=this.m[4],t.m[5]=this.m[5]}point(t){const n=this.m;return{x:n[0]*t.x+n[2]*t.y+n[4],y:n[1]*t.x+n[3]*t.y+n[5]}}translate(t,n){return this.m[4]+=this.m[0]*t+this.m[2]*n,this.m[5]+=this.m[1]*t+this.m[3]*n,this}scale(t,n){return this.m[0]*=t,this.m[1]*=t,this.m[2]*=n,this.m[3]*=n,this}rotate(t){const n=Math.cos(t),r=Math.sin(t),a=this.m[0]*n+this.m[2]*r,i=this.m[1]*n+this.m[3]*r,l=this.m[0]*-r+this.m[2]*n,o=this.m[1]*-r+this.m[3]*n;return this.m[0]=a,this.m[1]=i,this.m[2]=l,this.m[3]=o,this}getTranslation(){return{x:this.m[4],y:this.m[5]}}skew(t,n){const r=this.m[0]+this.m[2]*n,a=this.m[1]+this.m[3]*n,i=this.m[2]+this.m[0]*t,l=this.m[3]+this.m[1]*t;return this.m[0]=r,this.m[1]=a,this.m[2]=i,this.m[3]=l,this}multiply(t){const n=this.m[0]*t.m[0]+this.m[2]*t.m[1],r=this.m[1]*t.m[0]+this.m[3]*t.m[1],a=this.m[0]*t.m[2]+this.m[2]*t.m[3],i=this.m[1]*t.m[2]+this.m[3]*t.m[3],l=this.m[0]*t.m[4]+this.m[2]*t.m[5]+this.m[4],o=this.m[1]*t.m[4]+this.m[3]*t.m[5]+this.m[5];return this.m[0]=n,this.m[1]=r,this.m[2]=a,this.m[3]=i,this.m[4]=l,this.m[5]=o,this}invert(){const t=1/(this.m[0]*this.m[3]-this.m[1]*this.m[2]),n=this.m[3]*t,r=-this.m[1]*t,a=-this.m[2]*t,i=this.m[0]*t,l=t*(this.m[2]*this.m[5]-this.m[3]*this.m[4]),o=t*(this.m[1]*this.m[4]-this.m[0]*this.m[5]);return this.m[0]=n,this.m[1]=r,this.m[2]=a,this.m[3]=i,this.m[4]=l,this.m[5]=o,this}getMatrix(){return this.m}decompose(){const t=this.m[0],n=this.m[1],r=this.m[2],a=this.m[3],i=this.m[4],l=this.m[5],o=t*a-n*r,c={x:i,y:l,rotation:0,scaleX:0,scaleY:0,skewX:0,skewY:0};if(t!=0||n!=0){const d=Math.sqrt(t*t+n*n);c.rotation=n>0?Math.acos(t/d):-Math.acos(t/d),c.scaleX=d,c.scaleY=o/d,c.skewX=(t*r+n*a)/o,c.skewY=0}else if(r!=0||a!=0){const d=Math.sqrt(r*r+a*a);c.rotation=Math.PI/2-(a>0?Math.acos(-r/d):-Math.acos(r/d)),c.scaleX=o/d,c.scaleY=d,c.skewX=0,c.skewY=(t*r+n*a)/o}return c.rotation=sr._getRotation(c.rotation),c}}const ltn="[object Array]",ctn="[object Number]",dtn="[object String]",utn="[object Boolean]",htn=Math.PI/180,mtn=180/Math.PI,WY="#",ptn="",ftn="0",xtn="Konva warning: ",zyt="Konva error: ",gtn="rgb(",Z7e={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]},ytn=/rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/;let nce=[],KY=null;const vtn=typeof requestAnimationFrame<"u"&&requestAnimationFrame||function(s){setTimeout(s,16)},sr={_isElement(s){return!!(s&&s.nodeType==1)},_isFunction(s){return!!(s&&s.constructor&&s.call&&s.apply)},_isPlainObject(s){return!!s&&s.constructor===Object},_isArray(s){return Object.prototype.toString.call(s)===ltn},_isNumber(s){return Object.prototype.toString.call(s)===ctn&&!isNaN(s)&&isFinite(s)},_isString(s){return Object.prototype.toString.call(s)===dtn},_isBoolean(s){return Object.prototype.toString.call(s)===utn},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){nce.push(s),nce.length===1&&vtn(function(){const t=nce;nce=[],t.forEach(function(n){n()})})},createCanvasElement(){Oyt();const s=document.createElement("canvas");try{s.style=s.style||{}}catch{}return s},createImageElement(){return Oyt(),document.createElement("img")},_isInDocument(s){for(;s=s.parentNode;)if(s==document)return!0;return!1},_urlToImage(s,t){const n=sr.createImageElement();n.onload=function(){t(n)},n.src=s},_rgbToHex(s,t,n){return((1<<24)+(s<<16)+(t<<8)+n).toString(16).slice(1)},_hexToRgb(s){s=s.replace(WY,ptn);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=ftn+s;return WY+s},isCanvasFarblingActive(){if(KY!==null)return KY;if(typeof document>"u")return KY=!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 KY=r,this.releaseCanvas(s),KY},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),WY+this._rgbToHex(s,t,n)},getSnappedHexColor(s){const t=this._hexToRgb(s);return WY+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 Z7e?(t=Z7e[s],{r:t[0],g:t[1],b:t[2]}):s[0]===WY?this._hexToRgb(s.substring(1)):s.substr(0,4)===gtn?(t=ytn.exec(s.replace(/ /g,"")),{r:parseInt(t[1],10),g:parseInt(t[2],10),b:parseInt(t[3],10)}):{r:0,g:0,b:0}},colorToRGBA(s){return s=s||"black",sr._namedColorToRBA(s)||sr._hex3ColorToRGBA(s)||sr._hex4ColorToRGBA(s)||sr._hex6ColorToRGBA(s)||sr._hex8ColorToRGBA(s)||sr._rgbColorToRGBA(s)||sr._rgbaColorToRGBA(s)||sr._hslColorToRGBA(s)},_namedColorToRBA(s){const t=Z7e[s.toLowerCase()];return t?{r:t[0],g:t[1],b:t[2],a:1}:null},_rgbColorToRGBA(s){if(s.indexOf("rgb(")===0){s=s.match(/rgb\(([^)]+)\)/)[1];const t=s.split(/ *, */).map(Number);return{r:t[0],g:t[1],b:t[2],a:1}}},_rgbaColorToRGBA(s){if(s.indexOf("rgba(")===0){s=s.match(/rgba\(([^)]+)\)/)[1];const t=s.split(/ *, */).map((n,r)=>n.slice(-1)==="%"?r===3?parseInt(n)/100:parseInt(n)/100*255:Number(n));return{r:t[0],g:t[1],b:t[2],a:t[3]}}},_hex8ColorToRGBA(s){if(s[0]==="#"&&s.length===9)return{r:parseInt(s.slice(1,3),16),g:parseInt(s.slice(3,5),16),b:parseInt(s.slice(5,7),16),a:parseInt(s.slice(7,9),16)/255}},_hex6ColorToRGBA(s){if(s[0]==="#"&&s.length===7)return{r:parseInt(s.slice(1,3),16),g:parseInt(s.slice(3,5),16),b:parseInt(s.slice(5,7),16),a:1}},_hex4ColorToRGBA(s){if(s[0]==="#"&&s.length===5)return{r:parseInt(s[1]+s[1],16),g:parseInt(s[2]+s[2],16),b:parseInt(s[3]+s[3],16),a:parseInt(s[4]+s[4],16)/255}},_hex3ColorToRGBA(s){if(s[0]==="#"&&s.length===4)return{r:parseInt(s[1]+s[1],16),g:parseInt(s[2]+s[2],16),b:parseInt(s[3]+s[3],16),a:1}},_hslColorToRGBA(s){if(/hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.test(s)){const[t,...n]=/hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.exec(s),r=Number(n[0])/360,a=Number(n[1])/100,i=Number(n[2])/100;let l,o,c;if(a===0)return c=i*255,{r:Math.round(c),g:Math.round(c),b:Math.round(c),a:1};i<.5?l=i*(1+a):l=i+a-i*a;const d=2*i-l,u=[0,0,0];for(let h=0;h<3;h++)o=r+1/3*-(h-1),o<0&&o++,o>1&&o--,6*o<1?c=d+(l-d)*6*o:2*o<1?c=l:3*o<2?c=d+(l-d)*(2/3-o)*6:c=d,u[h]=c*255;return{r:Math.round(u[0]),g:Math.round(u[1]),b:Math.round(u[2]),a:1}}},haveIntersection(s,t){return!(t.x>s.x+s.width||t.x+t.widths.y+s.height||t.y+t.height1?(l=n,o=r,c=(n-a)*(n-a)+(r-i)*(r-i)):(l=s+u*(n-s),o=t+u*(r-t),c=(l-a)*(l-a)+(o-i)*(o-i))}return[l,o,c]},_getProjectionToLine(s,t,n){const r=sr.cloneObject(s);let a=Number.MAX_VALUE;return t.forEach(function(i,l){if(!n&&l===t.length-1)return;const o=t[(l+1)%t.length],c=sr._getProjectionToSegment(i.x,i.y,o.x,o.y,s.x,s.y),d=c[0],u=c[1],h=c[2];ht.length){const l=t;t=s,s=l}for(let l=0;l{t.width=0,t.height=0})},drawRoundedRectPath(s,t,n,r){let a=t<0?t:0,i=n<0?n:0;t=Math.abs(t),n=Math.abs(n);let l=0,o=0,c=0,d=0;typeof r=="number"?l=o=c=d=Math.min(r,t/2,n/2):(l=Math.min(r[0]||0,t/2,n/2),o=Math.min(r[1]||0,t/2,n/2),d=Math.min(r[2]||0,t/2,n/2),c=Math.min(r[3]||0,t/2,n/2)),s.moveTo(a+l,i),s.lineTo(a+t-o,i),s.arc(a+t-o,i+o,o,Math.PI*3/2,0,!1),s.lineTo(a+t,i+n-d),s.arc(a+t-d,i+n-d,d,0,Math.PI/2,!1),s.lineTo(a+c,i+n),s.arc(a+c,i+n-c,c,Math.PI/2,Math.PI,!1),s.lineTo(a,i+l),s.arc(a+l,i+l,l,Math.PI,Math.PI*3/2,!1)},drawRoundedPolygonPath(s,t,n,r,a){r=Math.abs(r);for(let i=0;itypeof u=="number"?Math.floor(u):u)),i+=_tn+d.join(Byt)+wtn)):(i+=o.property,t||(i+=Ctn+o.val)),i+=ktn;return i}clearTrace(){this.traceArr=[]}_trace(t){let n=this.traceArr,r;n.push(t),r=n.length,r>=Etn&&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=Uyt.length,r=this.setAttr,a,i;const l=function(o){let c=t[o],d;t[o]=function(){return i=btn(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 Lu._dragElements.forEach(t=>{s=t.node}),s},_dragElements:new Map,_drag(s){const t=[];Lu._dragElements.forEach((n,r)=>{const{node:a}=n,i=a.getStage();i.setPointersPositions(s),n.pointerId===void 0&&(n.pointerId=sr._getFirstPointerId(s));const l=i._changedPointerPositions.find(o=>o.id===n.pointerId);if(l){if(n.dragStatus!=="dragging"){const o=a.dragDistance();if(Math.max(Math.abs(l.x-n.startPointerPos.x),Math.abs(l.y-n.startPointerPos.y)){n.getStage()&&n.fire("dragmove",{type:"dragmove",target:n,evt:s},!0)})},_endDragBefore(s){const t=[];Lu._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")&&(Lu.justDragged=!0,yi._mouseListenClick=!1,yi._touchListenClick=!1,yi._pointerListenClick=!1,n.dragStatus="stopped");const l=n.node.getLayer()||n.node instanceof yi.Stage&&n.node;l&&t.indexOf(l)===-1&&t.push(l)}),t.forEach(n=>{n.draw()})},_endDragAfter(s){Lu._dragElements.forEach((t,n)=>{t.dragStatus==="stopped"&&t.node.fire("dragend",{type:"dragend",target:t.node,evt:s},!0),t.dragStatus!=="dragging"&&Lu._dragElements.delete(n)})}};yi.isBrowser&&(window.addEventListener("mouseup",Lu._endDragBefore,!0),window.addEventListener("touchend",Lu._endDragBefore,!0),window.addEventListener("touchcancel",Lu._endDragBefore,!0),window.addEventListener("mousemove",Lu._drag),window.addEventListener("touchmove",Lu._drag),window.addEventListener("mouseup",Lu._endDragAfter,!1),window.addEventListener("touchend",Lu._endDragAfter,!1),window.addEventListener("touchcancel",Lu._endDragAfter,!1));function _L(s){return sr._isString(s)?'"'+s+'"':Object.prototype.toString.call(s)==="[object Number]"||sr._isBoolean(s)?s:Object.prototype.toString.call(s)}function Jqt(s){return s>255?255:s<0?0:Math.round(s)}function hi(){if(yi.isUnminified)return function(s,t){return sr._isNumber(s)||sr.warn(_L(s)+' is a not valid value for "'+t+'" attribute. The value should be a number.'),s}}function qLe(s){if(yi.isUnminified)return function(t,n){let r=sr._isNumber(t),a=sr._isArray(t)&&t.length==s;return!r&&!a&&sr.warn(_L(t)+' is a not valid value for "'+n+'" attribute. The value should be a number or Array('+s+")"),t}}function Ctt(){if(yi.isUnminified)return function(s,t){return sr._isNumber(s)||s==="auto"||sr.warn(_L(s)+' is a not valid value for "'+t+'" attribute. The value should be a number or "auto".'),s}}function W9(){if(yi.isUnminified)return function(s,t){return sr._isString(s)||sr.warn(_L(s)+' is a not valid value for "'+t+'" attribute. The value should be a string.'),s}}function e$t(){if(yi.isUnminified)return function(s,t){const n=sr._isString(s),r=Object.prototype.toString.call(s)==="[object CanvasGradient]"||s&&s.addColorStop;return n||r||sr.warn(_L(s)+' is a not valid value for "'+t+'" attribute. The value should be a string or a native gradient.'),s}}function Ltn(){if(yi.isUnminified)return function(s,t){const n=Int8Array?Object.getPrototypeOf(Int8Array):null;return n&&s instanceof n||(sr._isArray(s)?s.forEach(function(r){sr._isNumber(r)||sr.warn('"'+t+'" attribute has non numeric element '+r+". Make sure that all elements are numbers.")}):sr.warn(_L(s)+' is a not valid value for "'+t+'" attribute. The value should be a array of numbers.')),s}}function OS(){if(yi.isUnminified)return function(s,t){return s===!0||s===!1||sr.warn(_L(s)+' is a not valid value for "'+t+'" attribute. The value should be a boolean.'),s}}function Itn(s){if(yi.isUnminified)return function(t,n){return t==null||sr.isObject(t)||sr.warn(_L(t)+' is a not valid value for "'+n+'" attribute. The value should be an object with properties '+s),t}}const YY="get",ZY="set",xn={addGetterSetter(s,t,n,r,a){xn.addGetter(s,t,n),xn.addSetter(s,t,r,a),xn.addOverloadedGetterSetter(s,t)},addGetter(s,t,n){const r=YY+sr._capitalize(t);s.prototype[r]=s.prototype[r]||function(){const a=this.attrs[t];return a===void 0?n:a}},addSetter(s,t,n,r){const a=ZY+sr._capitalize(t);s.prototype[a]||xn.overWriteSetter(s,t,n,r)},overWriteSetter(s,t,n,r){const a=ZY+sr._capitalize(t);s.prototype[a]=function(i){return n&&i!==void 0&&i!==null&&(i=n.call(this,i,t)),this._setAttr(t,i),r&&r.call(this),this}},addComponentsGetterSetter(s,t,n,r,a){const i=n.length,l=sr._capitalize,o=YY+l(t),c=ZY+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},xn.addOverloadedGetterSetter(s,t)},addOverloadedGetterSetter(s,t){const n=sr._capitalize(t),r=ZY+n,a=YY+n;s.prototype[t]=function(){return arguments.length?(this[r](arguments[0]),this):this[a]()}},addDeprecatedGetterSetter(s,t,n,r){sr.error("Adding deprecated "+t);const a=YY+sr._capitalize(t),i=t+" property is deprecated and will be removed soon. Look at Konva change log for more information.";s.prototype[a]=function(){sr.error(i);const l=this.attrs[t];return l===void 0?n:l},xn.addSetter(s,t,r,function(){sr.error(i)}),xn.addOverloadedGetterSetter(s,t)},backCompat(s,t){sr.each(t,function(n,r){const a=s.prototype[r],i=YY+sr._capitalize(n),l=ZY+sr._capitalize(n);function o(){a.apply(this,arguments),sr.error('"'+n+'" method is deprecated and will be removed soon. Use ""'+r+'" instead.')}s.prototype[n]=o,s.prototype[i]=o,s.prototype[l]=o})},afterSetFilter(){this._filterUpToDate=!1}};function Dtn(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=yi.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=yi.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=yi.Filters;c&&c.Contrast&&c.Contrast.call(this,l)}}case"grayscale":return function(i){const l=yi.Filters;l&&l.Grayscale&&l.Grayscale.call(this,i)};case"sepia":return function(i){const l=yi.Filters;l&&l.Sepia&&l.Sepia.call(this,i)};case"invert":return function(i){const l=yi.Filters;l&&l.Invert&&l.Invert.call(this,i)};default:sr.warn(`CSS filter "${r}" is not supported in fallback mode. Consider using function filters for better compatibility.`);break}}return()=>{}}const W4e="absoluteOpacity",$yt="allEventListeners",I3="absoluteTransform",Vyt="absoluteScale",wI="canvas",Rtn="Change",Ftn="children",Otn="konva",xHe="listening",ztn="mouseenter",Btn="mouseleave",Utn="pointerenter",qtn="pointerleave",$tn="touchenter",Vtn="touchleave",Hyt="set",Gyt="Shape",K4e=" ",Wyt="stage",YT="transform",Htn="Stage",gHe="visible",Gtn=["xChange.konva","yChange.konva","scaleXChange.konva","scaleYChange.konva","skewXChange.konva","skewYChange.konva","rotationChange.konva","offsetXChange.konva","offsetYChange.konva","transformsEnabledChange.konva"].join(K4e);let Wtn=1,ki=class vX{constructor(t){this._id=Wtn++,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===YT||t===I3)&&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===YT||t===I3)&&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(K4e);this.on(a,()=>{this._clearCache(t)}),this._attachedDepsListeners.set(t,!0)}return this._getCache(t,r)}_getCanvasCache(){return this._cache.get(wI)}_clearSelfAndDescendantCache(t){this._clearCache(t),t===I3&&this.fire("absoluteTransformChange")}clearCache(){if(this._cache.has(wI)){const{scene:t,filter:n,hit:r}=this._cache.get(wI);sr.releaseCanvas(t._canvas,n._canvas,r._canvas),this._cache.delete(wI)}return this._clearSelfAndDescendantCache(),this._requestDraw(),this}cache(t){const n=t||{};let r={};(n.x===void 0||n.y===void 0||n.width===void 0||n.height===void 0)&&(r=this.getClientRect({skipTransform:!0,relativeTo:this.getParent()||void 0}));let a=Math.ceil(n.width||r.width),i=Math.ceil(n.height||r.height),l=n.pixelRatio,o=n.x===void 0?Math.floor(r.x):n.x,c=n.y===void 0?Math.floor(r.y):n.y,d=n.offset||0,u=n.drawBorder||!1,h=n.hitCanvasPixelRatio||1;if(!a||!i){sr.error("Can not cache the node. Width or height of the node equals 0. Caching is skipped.");return}const m=Math.abs(Math.round(r.x)-o)>.5?1:0,p=Math.abs(Math.round(r.y)-c)>.5?1:0;a+=d*2+m,i+=d*2+p,o-=d,c-=d;const f=new C6({pixelRatio:l,width:a,height:i}),y=new C6({pixelRatio:l,width:0,height:0,willReadFrequently:!0}),v=new Stt({pixelRatio:h,width:a,height:i}),g=f.getContext(),b=v.getContext(),j=new C6({width:f.width/f.pixelRatio+Math.abs(o),height:f.height/f.pixelRatio+Math.abs(c),pixelRatio:f.pixelRatio}),S=j.getContext();return v.isCache=!0,f.isCache=!0,this._cache.delete(wI),this._filterUpToDate=!1,n.imageSmoothingEnabled===!1&&(f.getContext()._context.imageSmoothingEnabled=!1,y.getContext()._context.imageSmoothingEnabled=!1),g.save(),b.save(),S.save(),g.translate(-o,-c),b.translate(-o,-c),S.translate(-o,-c),j.x=o,j.y=c,this._isUnderCache=!0,this._clearSelfAndDescendantCache(W4e),this._clearSelfAndDescendantCache(Vyt),this.drawScene(f,this,j),this.drawHit(v,this),this._isUnderCache=!1,g.restore(),b.restore(),u&&(g.save(),g.beginPath(),g.rect(0,0,a,i),g.closePath(),g.setAttr("strokeStyle","red"),g.setAttr("lineWidth",5),g.stroke(),g.restore()),sr.releaseCanvas(j._canvas),this._cache.set(wI,{scene:f,filter:y,hit:v,x:o,y:c}),this._requestDraw(),this}isCached(){return this._cache.has(wI)}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)&&Lu._dragElements.delete(n)}),this._remove(),this}_clearCaches(){this._clearSelfAndDescendantCache(I3),this._clearSelfAndDescendantCache(W4e),this._clearSelfAndDescendantCache(Vyt),this._clearSelfAndDescendantCache(Wyt),this._clearSelfAndDescendantCache(gHe),this._clearSelfAndDescendantCache(xHe)}_remove(){this._clearCaches();const t=this.getParent();t&&t.children&&(t.children.splice(this.index,1),t._setChildrenIndices(),this.parent=null)}destroy(){return this.remove(),this.clearCache(),this}getAttr(t){const n="get"+sr._capitalize(t);return sr._isFunction(this[n])?this[n]():this.attrs[t]}getAncestors(){let t=this.getParent(),n=[];for(;t;)n.push(t),t=t.getParent();return n}getAttrs(){return this.attrs||{}}setAttrs(t){return this._batchTransformChanges(()=>{let n,r;if(!t)return this;for(n in t)n!==Ftn&&(r=Hyt+sr._capitalize(n),sr._isFunction(this[r])?this[r](t[n]):this._setAttr(n,t[n]))}),this}isListening(){return this._getCache(xHe,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(gHe,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;Lu._dragElements.forEach(l=>{l.dragStatus==="dragging"&&(l.node.nodeType==="Stage"||l.node.getLayer()===r)&&(a=!0)});const i=!n&&!yi.hitOnDragEnabled&&(a||yi.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!==Htn&&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(YT),this._clearSelfAndDescendantCache(I3)),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 Jw,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(YT);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(YT),this._clearSelfAndDescendantCache(I3),this}_setTransform(t){let n;for(n in t)this.attrs[n]=t[n]}_clearTransform(){const t={x:this.x(),y:this.y(),rotation:this.rotation(),scaleX:this.scaleX(),scaleY:this.scaleY(),offsetX:this.offsetX(),offsetY:this.offsetY(),skewX:this.skewX(),skewY:this.skewY()};return this.attrs.x=0,this.attrs.y=0,this.attrs.rotation=0,this.attrs.scaleX=1,this.attrs.scaleY=1,this.attrs.offsetX=0,this.attrs.offsetY=0,this.attrs.skewX=0,this.attrs.skewY=0,t}move(t){let n=t.x,r=t.y,a=this.x(),i=this.y();return n!==void 0&&(a+=n),r!==void 0&&(i+=r),this.setPosition({x:a,y:i}),this}_eachAncestorReverse(t,n){let r=[],a=this.getParent(),i,l;if(!(n&&n._id===this._id)){for(r.unshift(this);a&&(!n||a._id!==n._id);)r.unshift(a),a=a.parent;for(i=r.length,l=0;l0?(this.parent.children.splice(t,1),this.parent.children.splice(t-1,0,this),this.parent._setChildrenIndices(),!0):!1}moveToBottom(){if(!this.parent)return sr.warn("Node has no parent. moveToBottom function is ignored."),!1;const t=this.index;return t>0?(this.parent.children.splice(t,1),this.parent.children.unshift(this),this.parent._setChildrenIndices(),!0):!1}setZIndex(t){if(!this.parent)return sr.warn("Node has no parent. zIndex parameter is ignored."),this;(t<0||t>=this.parent.children.length)&&sr.warn("Unexpected value "+t+" for zIndex property. zIndex is just index of a node in children of its parent. Expected value is from 0 to "+(this.parent.children.length-1)+".");const n=this.index;return this.parent.children.splice(n,1),this.parent.children.splice(t,0,this),this.parent._setChildrenIndices(),this}getAbsoluteOpacity(){return this._getCache(W4e,this._getAbsoluteOpacity)}_getAbsoluteOpacity(){let t=this.opacity();const n=this.getParent();return n&&!n._isUnderCache&&(t*=n.getAbsoluteOpacity()),t}moveTo(t){return this.getParent()!==t&&(this._remove(),t.add(this)),this}toObject(){let t=this.getAttrs(),n,r,a,i,l;const o={attrs:{},className:this.getClassName()};for(n in t)r=t[n],l=sr.isObject(r)&&!sr._isPlainObject(r)&&!sr._isArray(r),!l&&(a=typeof this[n]=="function"&&this[n],delete t[n],i=a?a.call(this):null,t[n]=r,i!==r&&(o.attrs[n]=r));return sr._prepareToStringify(o)}toJSON(){return JSON.stringify(this.toObject())}getParent(){return this.parent}findAncestors(t,n,r){const a=[];n&&this._isMatch(t)&&a.push(this);let i=this.parent;for(;i;){if(i===r)return a;i._isMatch(t)&&a.push(i),i=i.parent}return a}isAncestorOf(t){return!1}findAncestor(t,n,r){return this.findAncestors(t,n,r)[0]}_isMatch(t){if(!t)return!1;if(typeof t=="function")return t(this);let n=t.replace(/ /g,"").split(","),r=n.length,a,i;for(a=0;a{try{const a=t==null?void 0:t.callback;a&&delete t.callback,sr._urlToImage(this.toDataURL(t),function(i){n(i),a==null||a(i)})}catch(a){r(a)}})}toBlob(t){return new Promise((n,r)=>{try{const a=t==null?void 0:t.callback;a&&delete t.callback,this.toCanvas(t).toBlob(i=>{n(i),a==null||a(i)},t==null?void 0:t.mimeType,t==null?void 0:t.quality)}catch(a){r(a)}})}setSize(t){return this.width(t.width),this.height(t.height),this}getSize(){return{width:this.width(),height:this.height()}}getClassName(){return this.className||this.nodeType}getType(){return this.nodeType}getDragDistance(){return this.attrs.dragDistance!==void 0?this.attrs.dragDistance:this.parent?this.parent.getDragDistance():yi.dragDistance}_off(t,n,r){let a=this.eventListeners[t],i,l,o;for(i=0;i=0)||this.isDragging())return;let a=!1;Lu._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=Lu._dragElements.get(this._id),r=n&&n.dragStatus==="dragging",a=n&&n.dragStatus==="ready";r?this.stopDrag():a&&Lu._dragElements.delete(this._id)}}_dragCleanup(){this.off("mousedown.konva"),this.off("touchstart.konva")}isClientRectOnScreen(t={x:0,y:0}){const n=this.getStage();if(!n)return!1;const r={x:-t.x,y:-t.y,width:n.width()+2*t.x,height:n.height()+2*t.y};return sr.haveIntersection(r,this.getClientRect())}static create(t,n){return sr._isString(t)&&(t=JSON.parse(t)),this._createNode(t,n)}static _createNode(t,n){let r=vX.prototype.getClassName.call(t),a=t.children,i,l,o;n&&(t.attrs.container=n),yi[r]||(sr.warn('Can not find a node with class name "'+r+'". Fallback to "Shape".'),r="Shape");const c=yi[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=ki.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=ki.prototype.clone.call(this,t);return this.getChildren().forEach(function(r){n.add(r.clone())}),n}getAllIntersections(t){const n=[];return this.find("Shape").forEach(r=>{r.isVisible()&&r.intersects(t)&&n.push(r)}),n}_clearSelfAndDescendantCache(t){var n;super._clearSelfAndDescendantCache(t),!this.isCached()&&((n=this.children)===null||n===void 0||n.forEach(function(r){r._clearSelfAndDescendantCache(t)}))}_setChildrenIndices(){var t;(t=this.children)===null||t===void 0||t.forEach(function(n,r){n.index=r}),this._requestDraw()}drawScene(t,n,r){const a=this.getLayer(),i=t||a&&a.getCanvas(),l=i&&i.getContext(),o=this._getCanvasCache(),c=o&&o.scene,d=i&&i.isCache;if(!this.isVisible()&&!d)return this;if(c){l.save();const u=this.getAbsoluteTransform(n).getMatrix();l.transform(u[0],u[1],u[2],u[3],u[4],u[5]),this._drawCachedSceneCanvas(l),l.restore()}else this._drawChildren("drawScene",i,n,r);return this}drawHit(t,n){if(!this.shouldDrawHit(n))return this;const r=this.getLayer(),a=t||r&&r.hitCanvas,i=a&&a.getContext(),l=this._getCanvasCache();if(l&&l.hit){i.save();const c=this.getAbsoluteTransform(n).getMatrix();i.transform(c[0],c[1],c[2],c[3],c[4],c[5]),this._drawCachedHitCanvas(i),i.restore()}else this._drawChildren("drawHit",a,n);return this}_drawChildren(t,n,r,a){var i;const l=n&&n.getContext(),o=this.clipWidth(),c=this.clipHeight(),d=this.clipFunc(),u=typeof o=="number"&&typeof c=="number"||d,h=r===this;if(u){l.save();const p=this.getAbsoluteTransform(r);let f=p.getMatrix();l.transform(f[0],f[1],f[2],f[3],f[4],f[5]),l.beginPath();let y;if(d)y=d.call(this,l,this);else{const v=this.clipX(),g=this.clipY();l.rect(v||0,g||0,o,c)}l.clip.apply(l,y),f=p.copy().invert().getMatrix(),l.transform(f[0],f[1],f[2],f[3],f[4],f[5])}const m=!h&&this.globalCompositeOperation()!=="source-over"&&t==="drawScene";m&&(l.save(),l._applyGlobalCompositeOperation(this)),(i=this.children)===null||i===void 0||i.forEach(function(p){p[t](n,r,a)}),m&&l.restore(),u&&l.restore()}getClientRect(t={}){var n;const r=t.skipTransform,a=t.relativeTo;let i,l,o,c,d={x:1/0,y:1/0,width:0,height:0};const u=this;(n=this.children)===null||n===void 0||n.forEach(function(p){if(!p.visible())return;const f=p.getClientRect({relativeTo:u,skipShadow:t.skipShadow,skipStroke:t.skipStroke});f.width===0&&f.height===0||(i===void 0?(i=f.x,l=f.y,o=f.x+f.width,c=f.y+f.height):(i=Math.min(i,f.x),l=Math.min(l,f.y),o=Math.max(o,f.x+f.width),c=Math.max(c,f.y+f.height)))});const h=this.find("Shape");let m=!1;for(let p=0;ps.indexOf("pointer")>=0?"pointer":s.indexOf("touch")>=0?"touch":"mouse",EB=s=>{const t=NX(s);if(t==="pointer")return yi.pointerEventsEnabled&&Q7e.pointer;if(t==="touch")return Q7e.touch;if(t==="mouse")return Q7e.mouse};function Yyt(s={}){return(s.clipFunc||s.clipWidth||s.clipHeight)&&sr.warn("Stage does not support clipping. Please use clip for Layers or Groups."),s}const esn="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);",$J=[];let $Le=class extends vj{constructor(t){super(Yyt(t)),this._pointerPositions=[],this._changedPointerPositions=[],this._buildDOM(),this._bindContentEvents(),$J.push(this),this.on("widthChange.konva heightChange.konva",this._resizeDOM),this.on("visibleChange.konva",this._checkVisibility),this.on("clipWidthChange.konva clipHeightChange.konva clipFuncChange.konva",()=>{Yyt(this.attrs)}),this._checkVisibility()}_validateAdd(t){const n=t.getType()==="Layer",r=t.getType()==="FastLayer";n||r||sr.throw("You may only add layers to the stage.")}_checkVisibility(){if(!this.content)return;const t=this.visible()?"":"none";this.content.style.display=t}setContainer(t){if(typeof t===Ytn){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&&$J.splice(n,1),sr.releaseCanvas(this.bufferCanvas._canvas,this.bufferHitCanvas._canvas),this}getPointerPosition(){const t=this._pointerPositions[0]||this._changedPointerPositions[0];return t?{x:t.x,y:t.y}:(sr.warn(esn),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 C6({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+Kyt,this.content.style.height=n+Kyt),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;aQtn&&sr.warn("The stage has "+r+" layers. Recommended maximum number of layers is 3-5. Adding more layers into the stage may drop the performance. Rethink your tree structure, you can use Konva.Group."),t.setSize({width:this.width(),height:this.height()}),t.draw(),yi.isBrowser&&this.content.appendChild(t.canvas._canvas),this}getParent(){return null}getLayer(){return null}hasPointerCapture(t){return s$t(t,this)}setPointerCapture(t){n$t(t,this)}releaseCapture(t){qJ(t)}getLayers(){return this.children}_bindContentEvents(){yi.isBrowser&&Jtn.forEach(([t,n])=>{this.content.addEventListener(t,r=>{this[n](r)},{passive:!1})})}_pointerenter(t){this.setPointersPositions(t);const n=EB(t.type);n&&this._fire(n.pointerenter,{evt:t,target:this,currentTarget:this})}_pointerover(t){this.setPointersPositions(t);const n=EB(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=EB(t.type),r=NX(t.type);if(!n)return;this.setPointersPositions(t);const a=this._getTargetShape(r),i=!(yi.isDragging()||yi.isTransforming())||yi.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=EB(t.type),r=NX(t.type);if(!n)return;this.setPointersPositions(t);let a=!1;this._changedPointerPositions.forEach(i=>{const l=this.getIntersection(i);if(Lu.justDragged=!1,yi["_"+r+"ListenClick"]=!0,!l||!l.isListening()){this[r+"ClickStartShape"]=void 0;return}yi.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=EB(t.type),r=NX(t.type);if(!n)return;const a=t.type.indexOf("touch")>=0||t.pointerType==="touch";if(yi.isDragging()&&Lu.node.preventDefault()&&t.cancelable&&a&&t.preventDefault(),this.setPointersPositions(t),!(!(yi.isDragging()||yi.isTransforming())||yi.hitOnDragEnabled))return;const l={};let o=!1;const c=this._getTargetShape(r);this._changedPointerPositions.forEach(d=>{const u=X7e(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=EB(t.type),r=NX(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=X7e(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;yi["_"+r+"InDblClickWindow"]?(m=!0,clearTimeout(this[r+"DblTimeout"])):Lu.justDragged||(yi["_"+r+"InDblClickWindow"]=!0,clearTimeout(this[r+"DblTimeout"])),this[r+"DblTimeout"]=setTimeout(function(){yi["_"+r+"InDblClickWindow"]=!1},yi.dblClickWindow),d&&d.isListening()?(o=!0,this[r+"ClickEndShape"]=d,d._fireAndBubble(n.pointerup,{...h}),yi["_"+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),yi["_"+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}),yi["_"+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(yHe,{evt:t}):this._fire(yHe,{evt:t,target:this,currentTarget:this})}_wheel(t){this.setPointersPositions(t);const n=this.getIntersection(this.getPointerPosition());n&&n.isListening()?n._fireAndBubble(vHe,{evt:t}):this._fire(vHe,{evt:t,target:this,currentTarget:this})}_pointercancel(t){this.setPointersPositions(t);const n=X7e(t.pointerId)||this.getIntersection(this.getPointerPosition());n&&n._fireAndBubble(nq,Att(t)),qJ(t.pointerId)}_lostpointercapture(t){qJ(t.pointerId)}setPointersPositions(t){const n=this._getContentPosition();let r=null,a=null;t=t||window.event,t.touches!==void 0?(this._pointerPositions=[],this._changedPointerPositions=[],Array.prototype.forEach.call(t.touches,i=>{this._pointerPositions.push({id:i.identifier,x:(i.clientX-n.left)/n.scaleX,y:(i.clientY-n.top)/n.scaleY})}),Array.prototype.forEach.call(t.changedTouches||t.touches,i=>{this._changedPointerPositions.push({id:i.identifier,x:(i.clientX-n.left)/n.scaleX,y:(i.clientY-n.top)/n.scaleY})})):(r=(t.clientX-n.left)/n.scaleX,a=(t.clientY-n.top)/n.scaleY,this.pointerPos={x:r,y:a},this._pointerPositions=[{x:r,y:a,id:sr._getFirstPointerId(t)}],this._changedPointerPositions=[{x:r,y:a,id:sr._getFirstPointerId(t)}])}_setPointerPosition(t){sr.warn('Method _setPointerPosition is deprecated. Use "stage.setPointersPositions(event)" instead.'),this.setPointersPositions(t)}_getContentPosition(){if(!this.content||!this.content.getBoundingClientRect)return{top:0,left:0,scaleX:1,scaleY:1};const t=this.content.getBoundingClientRect();return{top:t.top,left:t.left,scaleX:t.width/this.content.clientWidth||1,scaleY:t.height/this.content.clientHeight||1}}_buildDOM(){if(this.bufferCanvas=new C6({width:this.width(),height:this.height()}),this.bufferHitCanvas=new Stt({pixelRatio:1,width:this.width(),height:this.height()}),!yi.isBrowser)return;const t=this.container();if(!t)throw"Stage has no container. A container is required.";t.innerHTML="",this.content=document.createElement("div"),this.content.style.position="relative",this.content.style.userSelect="none",this.content.className="konvajs-content",this.content.setAttribute("role","presentation"),t.appendChild(this.content),this._resizeDOM()}cache(){return sr.warn("Cache function is not allowed for stage. You may use cache only for layers, groups and shapes."),this}clearCache(){return this}batchDraw(){return this.getChildren().forEach(function(t){t.batchDraw()}),this}};$Le.prototype.nodeType=Ktn;Zf($Le);xn.addGetterSetter($Le,"container");yi.isBrowser&&document.addEventListener("visibilitychange",()=>{$J.forEach(s=>{s.batchDraw()})});const p$t="hasShadow",f$t="shadowRGBA",x$t="patternImage",g$t="linearGradient",y$t="radialGradient";let cce;function J7e(){return cce||(cce=sr.createCanvasElement().getContext("2d"),cce)}const VJ={};function tsn(s){const t=this.attrs.fillRule;t?s.fill(t):s.fill()}function ssn(s){s.stroke()}function nsn(s){const t=this.attrs.fillRule;t?s.fill(t):s.fill()}function rsn(s){s.stroke()}function asn(){this._clearCache(p$t)}function isn(){this._clearCache(f$t)}function osn(){this._clearCache(x$t)}function lsn(){this._clearCache(g$t)}function csn(){this._clearCache(y$t)}let si=class extends ki{constructor(t){super(t);let n,r=0;for(;n=sr.getHitColor(),!(n&&!(n in VJ));)if(r++,r>=1e4){sr.warn("Failed to find a unique color key for a shape. Konva may work incorrectly. Most likely your browser is using canvas farbling. Consider disabling it."),n=sr.getRandomColor();break}this.colorKey=n,VJ[n]=this}getContext(){return sr.warn("shape.getContext() method is deprecated. Please do not use it."),this.getLayer().getContext()}getCanvas(){return sr.warn("shape.getCanvas() method is deprecated. Please do not use it."),this.getLayer().getCanvas()}getSceneFunc(){return this.attrs.sceneFunc||this._sceneFunc}getHitFunc(){return this.attrs.hitFunc||this._hitFunc}hasShadow(){return this._getCache(p$t,this._hasShadow)}_hasShadow(){return this.shadowEnabled()&&this.shadowOpacity()!==0&&!!(this.shadowColor()||this.shadowBlur()||this.shadowOffsetX()||this.shadowOffsetY())}_getFillPattern(){return this._getCache(x$t,this.__getFillPattern)}__getFillPattern(){if(this.fillPatternImage()){const n=J7e().createPattern(this.fillPatternImage(),this.fillPatternRepeat()||"repeat");if(n&&n.setTransform){const r=new Jw;r.translate(this.fillPatternX(),this.fillPatternY()),r.rotate(yi.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(g$t,this.__getLinearGradient)}__getLinearGradient(){const t=this.fillLinearGradientColorStops();if(t){const n=J7e(),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 ki.prototype.destroy.call(this),delete VJ[this.colorKey],delete this.colorKey,this}_useBufferCanvas(t){var n;if(!((n=this.attrs.perfectDrawEnabled)!==null&&n!==void 0?n:!0))return!1;const a=t||this.hasFill(),i=this.hasStroke(),l=this.getAbsoluteOpacity()!==1;if(a&&i&&l)return!0;const o=this.hasShadow(),c=this.shadowForStrokeEnabled();return!!(a&&i&&o&&c)}setStrokeHitEnabled(t){sr.warn("strokeHitEnabled property is deprecated. Please use hitStrokeWidth instead."),t?this.hitStrokeWidth("auto"):this.hitStrokeWidth(0)}getStrokeHitEnabled(){return this.hitStrokeWidth()!==0}getSelfRect(){const t=this.size();return{x:this._centroid?-t.width/2:0,y:this._centroid?-t.height/2:0,width:t.width,height:t.height}}getClientRect(t={}){let n=!1,r=this.getParent();for(;r;){if(r.isCached()){n=!0;break}r=r.getParent()}const a=t.skipTransform,i=t.relativeTo||n&&this.getStage()||void 0,l=this.getSelfRect(),c=!t.skipStroke&&this.hasStroke()&&this.strokeWidth()||0,d=l.width+c,u=l.height+c,h=!t.skipShadow&&this.hasShadow(),m=h?this.shadowOffsetX():0,p=h?this.shadowOffsetY():0,f=d+Math.abs(m),y=u+Math.abs(p),v=h&&this.shadowBlur()||0,g=f+v*2,b=y+v*2,j={width:g,height:b,x:-(c/2+v)+Math.min(m,0)+l.x,y:-(c/2+v)+Math.min(p,0)+l.y};return a?j:this._transformedRect(j,i)}drawScene(t,n,r){const a=this.getLayer(),i=t||a.getCanvas(),l=i.getContext(),o=this._getCanvasCache(),c=this.getSceneFunc(),d=this.hasShadow();let u;const h=!1,m=n===this;if(!this.isVisible()&&!m)return this;if(o){l.save();const p=this.getAbsoluteTransform(n).getMatrix();return l.transform(p[0],p[1],p[2],p[3],p[4],p[5]),this._drawCachedSceneCanvas(l),l.restore(),this}if(!c)return this;if(l.save(),this._useBufferCanvas()&&!h){u=this.getStage();const p=r||u.bufferCanvas,f=p.getContext();r?(f.save(),f.setTransform(1,0,0,1,0,0),f.clearRect(0,0,p.width,p.height),f.restore()):f.clear(),f.save(),f._applyLineJoin(this),f._applyMiterLimit(this);const y=this.getAbsoluteTransform(n).getMatrix();f.transform(y[0],y[1],y[2],y[3],y[4],y[5]),c.call(this,f,this),f.restore();const v=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/v,p.height/v)}else{if(l._applyLineJoin(this),l._applyMiterLimit(this),!m){const p=this.getAbsoluteTransform(n).getMatrix();l.transform(p[0],p[1],p[2],p[3],p[4],p[5]),l._applyOpacity(this),l._applyGlobalCompositeOperation(this)}d&&l._applyShadow(this),c.call(this,l,this)}return l.restore(),this}drawHit(t,n,r=!1){if(!this.shouldDrawHit(n,r))return this;const a=this.getLayer(),i=t||a.hitCanvas,l=i&&i.getContext(),o=this.hitFunc()||this.sceneFunc(),c=this._getCanvasCache(),d=c&&c.hit;if(this.colorKey||sr.warn("Looks like your canvas has a destroyed shape in it. Do not reuse shape after you destroyed it. If you want to reuse shape you should call remove() instead of destroy()"),d){l.save();const h=this.getAbsoluteTransform(n).getMatrix();return l.transform(h[0],h[1],h[2],h[3],h[4],h[5]),this._drawCachedHitCanvas(l),l.restore(),this}if(!o)return this;if(l.save(),l._applyLineJoin(this),l._applyMiterLimit(this),!(this===n)){const h=this.getAbsoluteTransform(n).getMatrix();l.transform(h[0],h[1],h[2],h[3],h[4],h[5])}return o.call(this,l,this),l.restore(),this}drawHitFromCache(t=0){const n=this._getCanvasCache(),r=this._getCachedSceneCanvas(),a=n.hit,i=a.getContext(),l=a.getWidth(),o=a.getHeight();i.clear(),i.drawImage(r._canvas,0,0,l,o);try{const c=i.getImageData(0,0,l,o),d=c.data,u=d.length,h=sr._hexToRgb(this.colorKey);for(let m=0;mt?(d[m]=h.r,d[m+1]=h.g,d[m+2]=h.b,d[m+3]=255):d[m+3]=0;i.putImageData(c,0,0)}catch(c){sr.error("Unable to draw hit graph from cached scene canvas. "+c.message)}return this}hasPointerCapture(t){return s$t(t,this)}setPointerCapture(t){n$t(t,this)}releaseCapture(t){qJ(t)}};si.prototype._fillFunc=tsn;si.prototype._strokeFunc=ssn;si.prototype._fillFuncHit=nsn;si.prototype._strokeFuncHit=rsn;si.prototype._centroid=!1;si.prototype.nodeType="Shape";Zf(si);si.prototype.eventListeners={};si.prototype.on("shadowColorChange.konva shadowBlurChange.konva shadowOffsetChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",asn);si.prototype.on("shadowColorChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",isn);si.prototype.on("fillPriorityChange.konva fillPatternImageChange.konva fillPatternRepeatChange.konva fillPatternScaleXChange.konva fillPatternScaleYChange.konva fillPatternOffsetXChange.konva fillPatternOffsetYChange.konva fillPatternXChange.konva fillPatternYChange.konva fillPatternRotationChange.konva",osn);si.prototype.on("fillPriorityChange.konva fillLinearGradientColorStopsChange.konva fillLinearGradientStartPointXChange.konva fillLinearGradientStartPointYChange.konva fillLinearGradientEndPointXChange.konva fillLinearGradientEndPointYChange.konva",lsn);si.prototype.on("fillPriorityChange.konva fillRadialGradientColorStopsChange.konva fillRadialGradientStartPointXChange.konva fillRadialGradientStartPointYChange.konva fillRadialGradientEndPointXChange.konva fillRadialGradientEndPointYChange.konva fillRadialGradientStartRadiusChange.konva fillRadialGradientEndRadiusChange.konva",csn);xn.addGetterSetter(si,"stroke",void 0,e$t());xn.addGetterSetter(si,"strokeWidth",2,hi());xn.addGetterSetter(si,"fillAfterStrokeEnabled",!1);xn.addGetterSetter(si,"hitStrokeWidth","auto",Ctt());xn.addGetterSetter(si,"strokeHitEnabled",!0,OS());xn.addGetterSetter(si,"perfectDrawEnabled",!0,OS());xn.addGetterSetter(si,"shadowForStrokeEnabled",!0,OS());xn.addGetterSetter(si,"lineJoin");xn.addGetterSetter(si,"lineCap");xn.addGetterSetter(si,"miterLimit");xn.addGetterSetter(si,"sceneFunc");xn.addGetterSetter(si,"hitFunc");xn.addGetterSetter(si,"dash");xn.addGetterSetter(si,"dashOffset",0,hi());xn.addGetterSetter(si,"shadowColor",void 0,W9());xn.addGetterSetter(si,"shadowBlur",0,hi());xn.addGetterSetter(si,"shadowOpacity",1,hi());xn.addComponentsGetterSetter(si,"shadowOffset",["x","y"]);xn.addGetterSetter(si,"shadowOffsetX",0,hi());xn.addGetterSetter(si,"shadowOffsetY",0,hi());xn.addGetterSetter(si,"fillPatternImage");xn.addGetterSetter(si,"fill",void 0,e$t());xn.addGetterSetter(si,"fillPatternX",0,hi());xn.addGetterSetter(si,"fillPatternY",0,hi());xn.addGetterSetter(si,"fillLinearGradientColorStops");xn.addGetterSetter(si,"strokeLinearGradientColorStops");xn.addGetterSetter(si,"fillRadialGradientStartRadius",0);xn.addGetterSetter(si,"fillRadialGradientEndRadius",0);xn.addGetterSetter(si,"fillRadialGradientColorStops");xn.addGetterSetter(si,"fillPatternRepeat","repeat");xn.addGetterSetter(si,"fillEnabled",!0);xn.addGetterSetter(si,"strokeEnabled",!0);xn.addGetterSetter(si,"shadowEnabled",!0);xn.addGetterSetter(si,"dashEnabled",!0);xn.addGetterSetter(si,"strokeScaleEnabled",!0);xn.addGetterSetter(si,"fillPriority","color");xn.addComponentsGetterSetter(si,"fillPatternOffset",["x","y"]);xn.addGetterSetter(si,"fillPatternOffsetX",0,hi());xn.addGetterSetter(si,"fillPatternOffsetY",0,hi());xn.addComponentsGetterSetter(si,"fillPatternScale",["x","y"]);xn.addGetterSetter(si,"fillPatternScaleX",1,hi());xn.addGetterSetter(si,"fillPatternScaleY",1,hi());xn.addComponentsGetterSetter(si,"fillLinearGradientStartPoint",["x","y"]);xn.addComponentsGetterSetter(si,"strokeLinearGradientStartPoint",["x","y"]);xn.addGetterSetter(si,"fillLinearGradientStartPointX",0);xn.addGetterSetter(si,"strokeLinearGradientStartPointX",0);xn.addGetterSetter(si,"fillLinearGradientStartPointY",0);xn.addGetterSetter(si,"strokeLinearGradientStartPointY",0);xn.addComponentsGetterSetter(si,"fillLinearGradientEndPoint",["x","y"]);xn.addComponentsGetterSetter(si,"strokeLinearGradientEndPoint",["x","y"]);xn.addGetterSetter(si,"fillLinearGradientEndPointX",0);xn.addGetterSetter(si,"strokeLinearGradientEndPointX",0);xn.addGetterSetter(si,"fillLinearGradientEndPointY",0);xn.addGetterSetter(si,"strokeLinearGradientEndPointY",0);xn.addComponentsGetterSetter(si,"fillRadialGradientStartPoint",["x","y"]);xn.addGetterSetter(si,"fillRadialGradientStartPointX",0);xn.addGetterSetter(si,"fillRadialGradientStartPointY",0);xn.addComponentsGetterSetter(si,"fillRadialGradientEndPoint",["x","y"]);xn.addGetterSetter(si,"fillRadialGradientEndPointX",0);xn.addGetterSetter(si,"fillRadialGradientEndPointY",0);xn.addGetterSetter(si,"fillPatternRotation",0);xn.addGetterSetter(si,"fillRule",void 0,W9());xn.backCompat(si,{dashArray:"dash",getDashArray:"getDash",setDashArray:"getDash",drawFunc:"sceneFunc",getDrawFunc:"getSceneFunc",setDrawFunc:"setSceneFunc",drawHitFunc:"hitFunc",getDrawHitFunc:"getHitFunc",setDrawHitFunc:"setHitFunc"});const dsn="beforeDraw",usn="draw",v$t=[{x:0,y:0},{x:-1,y:-1},{x:1,y:-1},{x:1,y:1},{x:-1,y:1}],hsn=v$t.length;let K9=class extends vj{constructor(t){super(t),this.canvas=new C6,this.hitCanvas=new Stt({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(dsn,{node:this}),this.clearBeforeDraw()&&i.getContext().clear(),vj.prototype.drawScene.call(this,i,n,r),this._fire(usn,{node:this}),this}drawHit(t,n){const r=this.getLayer(),a=t||r&&r.hitCanvas;return r&&r.clearBeforeDraw()&&r.getHitCanvas().getContext().clear(),vj.prototype.drawHit.call(this,a,n),this}enableHitGraph(){return this.hitGraphEnabled(!0),this}disableHitGraph(){return this.hitGraphEnabled(!1),this}setHitGraphEnabled(t){sr.warn("hitGraphEnabled method is deprecated. Please use layer.listening() instead."),this.listening(t)}getHitGraphEnabled(t){return sr.warn("hitGraphEnabled method is deprecated. Please use layer.listening() instead."),this.listening()}toggleHitCanvas(){if(!this.parent||!this.parent.content)return;const t=this.parent;!!this.hitCanvas._canvas.parentNode?t.content.removeChild(this.hitCanvas._canvas):t.content.appendChild(this.hitCanvas._canvas)}destroy(){return sr.releaseCanvas(this.getNativeCanvasElement(),this.getHitCanvas()._canvas),super.destroy()}};K9.prototype.nodeType="Layer";Zf(K9);xn.addGetterSetter(K9,"imageSmoothingEnabled",!0);xn.addGetterSetter(K9,"clearBeforeDraw",!0);xn.addGetterSetter(K9,"hitGraphEnabled",!0,OS());class Ett extends K9{constructor(t){super(t),this.listening(!1),sr.warn('Konva.Fast layer is deprecated. Please use "new Konva.Layer({ listening: false })" instead.')}}Ett.prototype.nodeType="FastLayer";Zf(Ett);let qH=class extends vj{_validateAdd(t){const n=t.getType();n!=="Group"&&n!=="Shape"&&sr.throw("You may only add groups and shapes to groups.")}};qH.prototype.nodeType="Group";Zf(qH);const e9e=function(){return bF.performance&&bF.performance.now?function(){return bF.performance.now()}:function(){return new Date().getTime()}}();class Z2{constructor(t,n){this.id=Z2.animIdCounter++,this.frame={time:0,timeDiff:0,lastTime:e9e(),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=Zyt,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onPlay")}reverse(){this.state=Xyt,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===Zyt?this.setTime(t):this.state===Xyt&&this.setTime(this.duration-t)}pause(){this.state=psn,this.fire("onPause")}getTimer(){return new Date().getTime()}}class Wm{constructor(t){const n=this,r=t.node,a=r._id,i=t.easing||HJ.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=fsn++;const d=r.getLayer()||(r instanceof yi.Stage?r.getLayers():null);d||sr.error("Tween constructor have `node` that is not in a layer. Please add node into layer first."),this.anim=new Z2(function(){n.tween.onEnterFrame()},d),this.tween=new xsn(c,function(u){n._tweenFunc(u)},i,0,1,o*1e3,l),this._addListeners(),Wm.attrs[a]||(Wm.attrs[a]={}),Wm.attrs[a][this._id]||(Wm.attrs[a][this._id]={}),Wm.tweens[a]||(Wm.tweens[a]={});for(c in t)msn[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=Wm.tweens[a][t];u&&delete Wm.attrs[a][u][t];let h=r.getAttr(t);if(sr._isArray(n))if(i=[],l=Math.max(n.length,h.length),t==="points"&&n.length!==h.length&&(n.length>h.length?(c=h,h=sr._prepareArrayForTween(h,n,r.closed())):(o=n,n=sr._prepareArrayForTween(n,h,r.closed()))),t.indexOf("fill")===0)for(let m=0;m{this.anim.start()},this.tween.onReverse=()=>{this.anim.start()},this.tween.onPause=()=>{this.anim.stop()},this.tween.onFinish=()=>{const t=this.node,n=Wm.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=Wm.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=Wm.tweens[t];this.pause(),this.anim&&this.anim.stop();for(const a in r)delete Wm.tweens[t][a];delete Wm.attrs[t][n],Wm.tweens[t]&&(Object.keys(Wm.tweens[t]).length===0&&delete Wm.tweens[t],Object.keys(Wm.attrs[t]).length===0&&delete Wm.attrs[t])}}Wm.attrs={};Wm.tweens={};ki.prototype.to=function(s){const t=s.onFinish;s.node=this,s.onFinish=function(){this.destroy(),t&&t()},new Wm(s).play()};const HJ={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}}}FE.prototype._centroid=!0;FE.prototype.className="Arc";FE.prototype._attrsAffectingSize=["innerRadius","outerRadius","angle","clockwise"];Zf(FE);xn.addGetterSetter(FE,"innerRadius",0,hi());xn.addGetterSetter(FE,"outerRadius",0,hi());xn.addGetterSetter(FE,"angle",0,hi());xn.addGetterSetter(FE,"clockwise",!1,OS());function bHe(s,t,n,r,a,i,l){const o=Math.sqrt(Math.pow(n-s,2)+Math.pow(r-t,2)),c=Math.sqrt(Math.pow(a-n,2)+Math.pow(i-r,2)),d=l*o/(o+c),u=l*c/(o+c),h=n-d*(a-s),m=r-d*(i-t),p=n+u*(a-s),f=r+u*(i-t);return[h,m,p,f]}function Jyt(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 OE=class extends si{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*ysn[20][o]+l,r+=vsn[20][o]*_sn(s,t,a);return l*r},tvt=(s,t,n)=>{n===void 0&&(n=1);const r=s[0]-2*s[1]+s[2],a=t[0]-2*t[1]+t[2],i=2*s[1]-2*s[0],l=2*t[1]-2*t[0],o=4*(r*r+a*a),c=4*(r*i+a*l),d=i*i+l*l;if(o===0)return n*Math.sqrt(Math.pow(s[2]-s[0],2)+Math.pow(t[2]-t[0],2));const u=c/(2*o),h=d/o,m=n+u,p=h-u*u,f=m*m+p>0?Math.sqrt(m*m+p):0,y=u*u+p>0?Math.sqrt(u*u+p):0,v=u+Math.sqrt(u*u+p)!==0?p*Math.log(Math.abs((m+f)/(u+y))):0;return Math.sqrt(o)/2*(m*f-u*y+v)};function _sn(s,t,n){const r=_He(1,n,s),a=_He(1,n,t),i=r*r+a*a;return Math.sqrt(i)}const _He=(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+=bsn[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 X2=class i_ extends si{constructor(t){super(t),this.dataArray=[],this.pathLength=0,this._readDataAttribute(),this.on("dataChange.konva",function(){this._readDataAttribute()})}_readDataAttribute(){this.dataArray=i_.parsePathData(this.data()),this.pathLength=i_.getPathLength(this.dataArray)}_sceneFunc(t){const n=this.dataArray;t.beginPath();let r=!1;for(let a=0;au?d:u,v=d>u?1:d/u,g=d>u?u/d:1;t.translate(o,c),t.rotate(p),t.scale(v,g),t.arc(0,0,y,h,h+m,1-f),t.scale(1/v,1/g),t.rotate(-p),t.translate(-o,-c);break;case"z":r=!0,t.closePath();break}}!r&&!this.hasFill()?t.strokeShape(this):t.fillStrokeShape(this)}getSelfRect(){let t=[];this.dataArray.forEach(function(c){if(c.command==="A"){const d=c.points[4],u=c.points[5],h=c.points[4]+u;let m=Math.PI/180;if(Math.abs(d-h)h;p-=m){const f=i_.getPointOnEllipticalArc(c.points[0],c.points[1],c.points[2],c.points[3],p,0);t.push(f.x,f.y)}else for(let p=d+m;pn[a].pathLength;)t-=n[a].pathLength,++a;if(a===i)return r=n[a-1].points.slice(-2),{x:r[0],y:r[1]};if(t<.01)return n[a].command==="M"?(r=n[a].points.slice(0,2),{x:r[0],y:r[1]}):{x:n[a].start.x,y:n[a].start.y};const l=n[a],o=l.points;switch(l.command){case"L":return i_.getPointOnLine(t,l.start.x,l.start.y,o[0],o[1]);case"C":return i_.getPointOnCubicBezier(svt(t,i_.getPathLength(n),y=>evt([l.start.x,o[0],o[2],o[4]],[l.start.y,o[1],o[3],o[5]],y)),l.start.x,l.start.y,o[0],o[1],o[2],o[3],o[4],o[5]);case"Q":return i_.getPointOnQuadraticBezier(svt(t,i_.getPathLength(n),y=>tvt([l.start.x,o[0],o[2]],[l.start.y,o[1],o[3]],y)),l.start.x,l.start.y,o[0],o[1],o[2],o[3]);case"A":const c=o[0],d=o[1],u=o[2],h=o[3],m=o[5],p=o[6];let f=o[4];return f+=m*t/l.pathLength,i_.getPointOnEllipticalArc(c,d,u,h,f,p)}return null}static getPointOnLine(t,n,r,a,i,l,o){l=l??n,o=o??r;const c=this.getLineLength(n,r,a,i);if(c<1e-10)return{x:n,y:r};if(a===n)return{x:l,y:o+(i>r?t:-t)};const d=(i-r)/(a-n),u=Math.sqrt(t*t/(1+d*d))*(a=0&&(y+=2,y>=7&&(y-=7));continue}if(y>=0){if(y===3){if(/^[01]{2}\d+(?:\.\d+)?$/.test(b)){f.push(parseInt(b[0],10)),f.push(parseInt(b[1],10)),f.push(parseFloat(b.slice(2))),y+=3,y>=7&&(y-=7);continue}if(b==="11"||b==="10"||b==="01"){f.push(parseInt(b[0],10)),f.push(parseInt(b[1],10)),y+=2,y>=7&&(y-=7);continue}if(b==="0"||b==="1"){f.push(parseInt(b,10)),y+=1,y>=7&&(y-=7);continue}}else if(y===4){if(/^[01]\d+(?:\.\d+)?$/.test(b)){f.push(parseInt(b[0],10)),f.push(parseFloat(b.slice(1))),y+=2,y>=7&&(y-=7);continue}if(b==="0"||b==="1"){f.push(parseInt(b,10)),y+=1,y>=7&&(y-=7);continue}}const j=parseFloat(b);isNaN(j)?f.push(0):f.push(j),y+=1,y>=7&&(y-=7)}else{const j=parseFloat(b);isNaN(j)?f.push(0):f.push(j)}}for(;f.length>0&&!isNaN(f[0]);){let v="",g=[];const b=o,j=c;let S,C,E,P,M,I,D,O,V,G;switch(p){case"l":o+=f.shift(),c+=f.shift(),v="L",g.push(o,c);break;case"L":o=f.shift(),c=f.shift(),g.push(o,c);break;case"m":const $=f.shift(),H=f.shift();if(o+=$,c+=H,v="M",i.length>2&&i[i.length-1].command==="z"){for(let Y=i.length-2;Y>=0;Y--)if(i[Y].command==="M"){o=i[Y].points[0]+$,c=i[Y].points[1]+H;break}}g.push(o,c),p="l";break;case"M":o=f.shift(),c=f.shift(),v="M",g.push(o,c),p="L";break;case"h":o+=f.shift(),v="L",g.push(o,c);break;case"H":o=f.shift(),v="L",g.push(o,c);break;case"v":c+=f.shift(),v="L",g.push(o,c);break;case"V":c=f.shift(),v="L",g.push(o,c);break;case"C":g.push(f.shift(),f.shift(),f.shift(),f.shift()),o=f.shift(),c=f.shift(),g.push(o,c);break;case"c":g.push(o+f.shift(),c+f.shift(),o+f.shift(),c+f.shift()),o+=f.shift(),c+=f.shift(),v="C",g.push(o,c);break;case"S":C=o,E=c,S=i[i.length-1],S.command==="C"&&(C=o+(o-S.points[2]),E=c+(c-S.points[3])),g.push(C,E,f.shift(),f.shift()),o=f.shift(),c=f.shift(),v="C",g.push(o,c);break;case"s":C=o,E=c,S=i[i.length-1],S.command==="C"&&(C=o+(o-S.points[2]),E=c+(c-S.points[3])),g.push(C,E,o+f.shift(),c+f.shift()),o+=f.shift(),c+=f.shift(),v="C",g.push(o,c);break;case"Q":g.push(f.shift(),f.shift()),o=f.shift(),c=f.shift(),g.push(o,c);break;case"q":g.push(o+f.shift(),c+f.shift()),o+=f.shift(),c+=f.shift(),v="Q",g.push(o,c);break;case"T":C=o,E=c,S=i[i.length-1],S.command==="Q"&&(C=o+(o-S.points[0]),E=c+(c-S.points[1])),o=f.shift(),c=f.shift(),v="Q",g.push(C,E,o,c);break;case"t":C=o,E=c,S=i[i.length-1],S.command==="Q"&&(C=o+(o-S.points[0]),E=c+(c-S.points[1])),o+=f.shift(),c+=f.shift(),v="Q",g.push(C,E,o,c);break;case"A":P=f.shift(),M=f.shift(),I=f.shift(),D=f.shift(),O=f.shift(),V=o,G=c,o=f.shift(),c=f.shift(),v="A",g=this.convertEndpointToCenterParameterization(V,G,o,c,D,O,P,M,I);break;case"a":P=f.shift(),M=f.shift(),I=f.shift(),D=f.shift(),O=f.shift(),V=o,G=c,o+=f.shift(),c+=f.shift(),v="A",g=this.convertEndpointToCenterParameterization(V,G,o,c,D,O,P,M,I);break}i.push({command:v||p,points:g,start:{x:b,y:j},pathLength:this.calcLength(b,j,v||p,g)})}(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=i_;switch(r){case"L":return d.getLineLength(t,n,a[0],a[1]);case"C":return evt([t,a[0],a[2],a[4]],[n,a[1],a[3],a[5]],1);case"Q":return tvt([t,a[0],a[2]],[n,a[1],a[3]],1);case"A":i=0;const u=a[4],h=a[5],m=a[4]+h;let p=Math.PI/180;if(Math.abs(u-m)m;c-=p)o=d.getPointOnEllipticalArc(a[0],a[1],a[2],a[3],c,0),i+=d.getLineLength(l.x,l.y,o.x,o.y),l=o;else for(c=u+p;c1&&(o*=Math.sqrt(p),c*=Math.sqrt(p));let f=Math.sqrt((o*o*(c*c)-o*o*(m*m)-c*c*(h*h))/(o*o*(m*m)+c*c*(h*h)));i===l&&(f*=-1),isNaN(f)&&(f=0);const y=f*o*m/c,v=f*-c*h/o,g=(t+r)/2+Math.cos(u)*y-Math.sin(u)*v,b=(n+a)/2+Math.sin(u)*y+Math.cos(u)*v,j=function(D){return Math.sqrt(D[0]*D[0]+D[1]*D[1])},S=function(D,O){return(D[0]*O[0]+D[1]*O[1])/(j(D)*j(O))},C=function(D,O){return(D[0]*O[1]=1&&(I=0),l===0&&I>0&&(I=I-2*Math.PI),l===1&&I<0&&(I=I+2*Math.PI),[g,b,o,c,E,I,u,l]}};X2.prototype.className="Path";X2.prototype._attrsAffectingSize=["data"];Zf(X2);xn.addGetterSetter(X2,"data");class Y9 extends OE{_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=X2.calcLength(a[a.length-4],a[a.length-3],"C",m),f=X2.getPointOnQuadraticBezier(Math.min(1,1-l/p),m[0],m[1],m[2],m[3],m[4],m[5]);c=r[o-2]-f.x,d=r[o-1]-f.y}else c=r[o-2]-r[o-4],d=r[o-1]-r[o-3];const u=(Math.atan2(d,c)+n)%n,h=this.pointerWidth();this.pointerAtEnding()&&(t.save(),t.beginPath(),t.translate(r[o-2],r[o-1]),t.rotate(u),t.moveTo(0,0),t.lineTo(-l,h/2),t.lineTo(-l,-h/2),t.closePath(),t.restore(),this.__fillStroke(t)),this.pointerAtBeginning()&&(t.save(),t.beginPath(),t.translate(r[0],r[1]),i?(c=(a[0]+a[2])/2-r[0],d=(a[1]+a[3])/2-r[1]):(c=r[2]-r[0],d=r[3]-r[1]),t.rotate((Math.atan2(-d,-c)+n)%n),t.moveTo(0,0),t.lineTo(-l,h/2),t.lineTo(-l,-h/2),t.closePath(),t.restore(),this.__fillStroke(t))}__fillStroke(t){const n=this.dashEnabled();n&&(this.attrs.dashEnabled=!1,t.setLineDash([])),t.fillStrokeShape(this),n&&(this.attrs.dashEnabled=!0)}getSelfRect(){const t=super.getSelfRect(),n=this.pointerWidth()/2;return{x:t.x,y:t.y-n,width:t.width,height:t.height+n*2}}}Y9.prototype.className="Arrow";Zf(Y9);xn.addGetterSetter(Y9,"pointerLength",10,hi());xn.addGetterSetter(Y9,"pointerWidth",10,hi());xn.addGetterSetter(Y9,"pointerAtBeginning",!1);xn.addGetterSetter(Y9,"pointerAtEnding",!0);class NW extends si{_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)}}NW.prototype._centroid=!0;NW.prototype.className="Circle";NW.prototype._attrsAffectingSize=["radius"];Zf(NW);xn.addGetterSetter(NW,"radius",0,hi());class wL extends si{_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)}}wL.prototype.className="Ellipse";wL.prototype._centroid=!0;wL.prototype._attrsAffectingSize=["radiusX","radiusY"];Zf(wL);xn.addComponentsGetterSetter(wL,"radius",["x","y"]);xn.addGetterSetter(wL,"radiusX",0,hi());xn.addGetterSetter(wL,"radiusY",0,hi());let zS=class b$t extends si{constructor(t){super(t),this._loadListener=()=>{this._requestDraw()},this.on("imageChange.konva",n=>{this._removeImageLoad(n.oldVal),this._setImageLoad()}),this._setImageLoad()}_setImageLoad(){const t=this.image();t&&t.complete||t&&t.readyState===4||t&&t.addEventListener&&t.addEventListener("load",this._loadListener)}_removeImageLoad(t){t&&t.removeEventListener&&t.removeEventListener("load",this._loadListener)}destroy(){return this._removeImageLoad(this.image()),super.destroy(),this}_useBufferCanvas(){const t=!!this.cornerRadius(),n=this.hasShadow();return t&&n?!0:super._useBufferCanvas(!0)}_sceneFunc(t){const n=this.getWidth(),r=this.getHeight(),a=this.cornerRadius(),i=this.attrs.image;let l;if(i){const o=this.attrs.cropWidth,c=this.attrs.cropHeight;o&&c?l=[i,this.cropX(),this.cropY(),o,c,0,0,n,r]:l=[i,0,0,n,r]}(this.hasFill()||this.hasStroke()||a)&&(t.beginPath(),a?sr.drawRoundedRectPath(t,n,r,a):t.rect(0,0,n,r),t.closePath(),t.fillStrokeShape(this)),i&&(a&&t.clip(),t.drawImage.apply(t,l))}_hitFunc(t){const n=this.width(),r=this.height(),a=this.cornerRadius();t.beginPath(),a?sr.drawRoundedRectPath(t,n,r,a):t.rect(0,0,n,r),t.closePath(),t.fillStrokeShape(this)}getWidth(){var t,n,r;return(r=(t=this.attrs.width)!==null&&t!==void 0?t:(n=this.image())===null||n===void 0?void 0:n.width)!==null&&r!==void 0?r:0}getHeight(){var t,n,r;return(r=(t=this.attrs.height)!==null&&t!==void 0?t:(n=this.image())===null||n===void 0?void 0:n.height)!==null&&r!==void 0?r:0}static fromURL(t,n,r=null){const a=sr.createImageElement();a.onload=function(){const i=new b$t({image:a});n(i)},a.onerror=r,a.crossOrigin="Anonymous",a.src=t}};zS.prototype.className="Image";zS.prototype._attrsAffectingSize=["image"];Zf(zS);xn.addGetterSetter(zS,"cornerRadius",0,qLe(4));xn.addGetterSetter(zS,"image");xn.addComponentsGetterSetter(zS,"crop",["x","y","width","height"]);xn.addGetterSetter(zS,"cropX",0,hi());xn.addGetterSetter(zS,"cropY",0,hi());xn.addGetterSetter(zS,"cropWidth",0,hi());xn.addGetterSetter(zS,"cropHeight",0,hi());const _$t=["fontFamily","fontSize","fontStyle","padding","lineHeight","text","width","height","pointerDirection","pointerWidth","pointerHeight"],wsn="Change.konva",jsn="none",wHe="up",jHe="right",NHe="down",kHe="left",Nsn=_$t.length;let Ttt=class extends qH{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)}}jL.prototype.className="RegularPolygon";jL.prototype._centroid=!0;jL.prototype._attrsAffectingSize=["radius"];Zf(jL);xn.addGetterSetter(jL,"radius",0,hi());xn.addGetterSetter(jL,"sides",0,hi());xn.addGetterSetter(jL,"cornerRadius",0,qLe(4));const nvt=Math.PI*2;class X9 extends si{_sceneFunc(t){t.beginPath(),t.arc(0,0,this.innerRadius(),0,nvt,!1),t.moveTo(this.outerRadius(),0),t.arc(0,0,this.outerRadius(),nvt,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)}}X9.prototype.className="Ring";X9.prototype._centroid=!0;X9.prototype._attrsAffectingSize=["innerRadius","outerRadius"];Zf(X9);xn.addGetterSetter(X9,"innerRadius",0,hi());xn.addGetterSetter(X9,"outerRadius",0,hi());class kC extends si{constructor(t){super(t),this._updated=!0,this.anim=new Z2(()=>{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 TB="auto",ksn="center",w$t="inherit",XY="justify",Ssn="Change.konva",j$t="2d",rvt="-",N$t="left",Csn="text",Asn="Text",Esn="top",Tsn="bottom",avt="middle",k$t="normal",Msn="px ",dce=" ",Psn="right",ivt="rtl",Lsn="word",Isn="char",ovt="none",t9e="…",S$t=["direction","fontFamily","fontSize","fontStyle","fontVariant","padding","align","verticalAlign","lineHeight","text","width","height","wrap","ellipsis","letterSpacing"],Dsn=S$t.length;let QY=null;function Rsn(){if(QY!==null)return QY;QY=!1;try{const s=document.createElement("canvas");s.width=10,s.height=10;const t=s.getContext(j$t);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){QY=!0;break}}}catch{}return QY}function Fsn(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 uce;function s9e(){return uce||(uce=sr.createCanvasElement().getContext(j$t),uce)}function Osn(s){s.fillText(this._partialText,this._partialTextX,this._partialTextY)}function zsn(s){s.setAttr("miterLimit",2),s.strokeText(this._partialText,this._partialTextX,this._partialTextY)}function Bsn(s){return s=s||{},!s.fillLinearGradientColorStops&&!s.fillRadialGradientColorStops&&!s.fillPatternImage&&(s.fill=s.fill||"black"),s}let ap=class extends si{constructor(t){super(Bsn(t)),this._partialTextX=0,this._partialTextY=0;for(let n=0;nae+ZT(le.text).length,0),te=Z+ie;y({char:ne,index:te,x:M,y:E+I,lineIndex:C,column:Z,isLastInLine:G,width:this.measureSize(ne).width,context:t})}t.fillStrokeShape(this),y&&t.restore(),M+=this.measureSize(ne).width+f}}else f!==0&&t.setAttr("letterSpacing",`${f}px`),this._partialTextX=M,this._partialTextY=E+I,this._partialText=O,t.fillStrokeShape(this);if(S){t.save(),t.beginPath();const H=yi.legacyTextRendering?0:-Math.round(o/4),Y=$;t.moveTo(Y,E+I+H);const Z=m===XY&&!G?p-l*2:V;t.lineTo(Y+Math.round(Z),E+I+H),t.lineWidth=o/15;const ne=this._getLinearGradient();t.strokeStyle=ne||v,t.stroke(),t.restore()}t.restore(),i>1&&(E+=c)}}_hitFunc(t){const n=this.getWidth(),r=this.getHeight();t.beginPath(),t.rect(0,0,n,r),t.closePath(),t.fillStrokeShape(this)}setText(t){const n=sr._isString(t)?t:t==null?"":t+"";return this._setAttr(Csn,n),this}getWidth(){return this.attrs.width===TB||this.attrs.width===void 0?this.getTextWidth()+this.padding()*2:this.attrs.width}getHeight(){return this.attrs.height===TB||this.attrs.height===void 0?this.fontSize()*this.textArr.length*this.lineHeight()+this.padding()*2:this.attrs.height}getTextWidth(){return this.textWidth}getTextHeight(){return sr.warn("text.getTextHeight() method is deprecated. Use text.height() - for full height and text.fontSize() - for one line height."),this.textHeight}measureSize(t){var n,r,a,i,l,o,c,d,u,h,m;let p=s9e(),f=this.fontSize(),y;p.save(),p.font=this._getContextFont(),y=p.measureText(t),p.restore();const v=f/100;return{actualBoundingBoxAscent:(n=y.actualBoundingBoxAscent)!==null&&n!==void 0?n:71.58203125*v,actualBoundingBoxDescent:(r=y.actualBoundingBoxDescent)!==null&&r!==void 0?r:0,actualBoundingBoxLeft:(a=y.actualBoundingBoxLeft)!==null&&a!==void 0?a:-7.421875*v,actualBoundingBoxRight:(i=y.actualBoundingBoxRight)!==null&&i!==void 0?i:75.732421875*v,alphabeticBaseline:(l=y.alphabeticBaseline)!==null&&l!==void 0?l:0,emHeightAscent:(o=y.emHeightAscent)!==null&&o!==void 0?o:100*v,emHeightDescent:(c=y.emHeightDescent)!==null&&c!==void 0?c:-20*v,fontBoundingBoxAscent:(d=y.fontBoundingBoxAscent)!==null&&d!==void 0?d:91*v,fontBoundingBoxDescent:(u=y.fontBoundingBoxDescent)!==null&&u!==void 0?u:21*v,hangingBaseline:(h=y.hangingBaseline)!==null&&h!==void 0?h:72.80000305175781*v,ideographicBaseline:(m=y.ideographicBaseline)!==null&&m!==void 0?m:-21*v,width:y.width,height:f}}_getContextFont(){return this.fontStyle()+dce+this.fontVariant()+dce+(this.fontSize()+Msn)+Fsn(this.fontFamily())}_addTextLine(t){this.align()===XY&&(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 s9e().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!==TB&&i!==void 0,c=l!==TB&&l!==void 0,d=this.padding(),u=i-d*2,h=l-d*2,m=0,p=this.wrap(),f=p!==ovt,y=p!==Isn&&f,v=this.ellipsis();this.textArr=[],s9e().font=this._getContextFont();const g=v?this._getTextWidth(t9e):0;for(let b=0,j=t.length;bu)for(;S.length>0;){let E=0,P=ZT(S).length,M="",I=0;for(;E>>1,O=ZT(S),V=O.slice(0,D+1).join(""),G=this._getTextWidth(V);(v&&c&&m+a>h?G+g:G)<=u?(E=D+1,M=V,I=G):P=D}if(M){if(y){const V=ZT(S),G=ZT(M),$=V[G.length],H=$===dce||$===rvt;let Y;if(H&&I<=u)Y=G.length;else{const Z=G.lastIndexOf(dce),ne=G.lastIndexOf(rvt);Y=Math.max(Z,ne)+1}Y>0&&(E=Y,M=V.slice(0,E).join(""),I=this._getTextWidth(M))}if(M=M.trimRight(),this._addTextLine(M),r=Math.max(r,I),m+=a,this._shouldHandleEllipsis(m)){this._tryToAddEllipsisToLastLine();break}if(S=ZT(S).slice(E).join("").trimLeft(),S.length>0&&(C=this._getTextWidth(S),C<=u)){this._addTextLine(S),m+=a,r=Math.max(r,C);break}}else break}else this._addTextLine(S),m+=a,r=Math.max(r,C),this._shouldHandleEllipsis(m)&&bh)break}this.textHeight=n,this.textWidth=r}_shouldHandleEllipsis(t){const n=+this.fontSize(),r=this.lineHeight()*n,a=this.attrs.height,i=a!==TB&&a!==void 0,l=this.padding(),o=a-l*2;return!(this.wrap()!==ovt)||i&&t+r>o}_tryToAddEllipsisToLastLine(){const t=this.attrs.width,n=t!==TB&&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+t9e)n?null:X2.getPointAtLengthOfDataArray(t,this.dataArray)}_readDataAttribute(){this.dataArray=X2.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&&g-this.pathLength<=d?this.pathLength:g);if(!b)return;const j=X2.getLineLength(f.x,f.y,b.x,b.y);let S=0;if(c)try{S=c(n[p-1].char,y)*this.fontSize()}catch{S=0}f.x+=S,b.x+=S,this.textWidth+=S;const C=X2.getPointOnLine(S+j/2,f.x,f.y,b.x,b.y),E=Math.atan2(b.y-f.y,b.x-f.x);this.glyphInfo.push({transposeX:C.x,transposeY:C.y,text:t[p],rotation:E,p0:f,p1:b,width:j}),m+=v}}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+`.${T$t}`).join(" "),lvt="nodesRect",$sn=["widthChange","heightChange","scaleXChange","scaleYChange","skewXChange","skewYChange","rotationChange","offsetXChange","offsetYChange","transformsEnabledChange","strokeWidthChange","draggableChange"],Vsn={"top-left":-45,"top-center":0,"top-right":45,"middle-right":-90,"middle-left":90,"bottom-left":-135,"bottom-center":180,"bottom-right":135},Hsn="ontouchstart"in yi._global;function Gsn(s,t,n){if(s==="rotater")return n;t+=sr.degToRad(Vsn[s]||0);const r=(sr.radToDeg(t)%360+360)%360;return sr._inRange(r,315+22.5,360)||sr._inRange(r,0,22.5)?"ns-resize":sr._inRange(r,45-22.5,45+22.5)?"nesw-resize":sr._inRange(r,90-22.5,90+22.5)?"ew-resize":sr._inRange(r,135-22.5,135+22.5)?"nwse-resize":sr._inRange(r,180-22.5,180+22.5)?"ns-resize":sr._inRange(r,225-22.5,225+22.5)?"nesw-resize":sr._inRange(r,270-22.5,270+22.5)?"ew-resize":sr._inRange(r,315-22.5,315+22.5)?"nwse-resize":(sr.error("Transformer has unknown angle for cursor detection: "+r),"pointer")}const jEe=["top-left","top-center","top-right","middle-right","middle-left","bottom-left","bottom-center","bottom-right"],cvt=1e8;function Wsn(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 M$t(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 Ksn(s,t){const n=Wsn(s);return M$t(s,t,n)}function Ysn(s,t,n){let r=t;for(let a=0;aa.isAncestorOf(this)?(sr.error("Konva.Transformer cannot be an a child of the node you are trying to attach"),!1):!0);return this._nodes=t=n,t.length===1&&this.useSingleNodeRotation()?this.rotation(t[0].getAbsoluteRotation()):this.rotation(0),this._nodes.forEach(a=>{const i=()=>{this.nodes().length===1&&this.useSingleNodeRotation()&&this.rotation(this.nodes()[0].getAbsoluteRotation()),this._resetTransformCache(),!this._transforming&&!this.isDragging()&&this.update()};if(a._attrsAffectingSize.length){const l=a._attrsAffectingSize.map(o=>o+"Change."+this._getEventNamespace()).join(" ");a.on(l,i)}a.on($sn.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(lvt),this._clearCache("transform"),this._clearSelfAndDescendantCache("absoluteTransform")}_getNodeRect(){return this._getCache(lvt,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=(yi.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 M$t(u,-yi.getAngle(n),{x:0,y:0})}__getNodeRect(){if(!this.getNode())return{x:-cvt,y:-cvt,width:0,height:0,rotation:0};const n=[];this.nodes().map(d=>{const u=d.getClientRect({skipTransform:!0,skipShadow:!0,skipStroke:this.ignoreStroke()}),h=[{x:u.x,y:u.y},{x:u.x+u.width,y:u.y},{x:u.x+u.width,y:u.y+u.height},{x:u.x,y:u.y+u.height}],m=d.getAbsoluteTransform();h.forEach(function(p){const f=m.point(p);n.push(f)})});const r=new Jw;r.rotate(-yi.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:yi.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(),jEe.forEach(t=>{this._createAnchor(t)}),this._createAnchor("rotater"),this._elementsCreated=!0}_createAnchor(t){const n=new _ae({stroke:"rgb(0, 161, 255)",fill:"white",strokeWidth:1,name:t+" _anchor",dragDistance:0,draggable:!0,hitStrokeWidth:Hsn?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=yi.getAngle(this.rotation()),i=this.rotateAnchorCursor(),l=Gsn(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 si({name:"back",width:0,height:0,sceneFunc(n,r){const a=r.getParent(),i=a.padding(),l=r.width(),o=r.height();if(n.beginPath(),n.rect(-i,-i,l+i*2,o+i*2),a.rotateEnabled()&&a.rotateLineVisible()){const c=a.rotateAnchorAngle(),d=a.rotateAnchorOffset(),u=sr.degToRad(c),h=Math.sin(u),m=-Math.cos(u),p=l/2,f=o/2;let y=1/0;m<0?y=Math.min(y,-f/m):m>0&&(y=Math.min(y,(o-f)/m)),h<0?y=Math.min(y,-p/h):h>0&&(y=Math.min(y,(l-p)/h));const v=p+h*y,g=f+m*y,b=sr._sign(o),j=v+h*d*b,S=g+m*d*b;n.moveTo(v,g),n.lineTo(j,S)}n.fillStrokeShape(r)},hitFunc:(n,r)=>{if(!this.shouldOverdrawWholeArea())return;const a=this.padding();n.beginPath(),n.rect(-a,-a,r.width()+a*2,r.height()+a*2),n.fillStrokeShape(r)}});this.add(t),this._proxyDrag(t),t.on("dragstart",n=>{n.cancelBubble=!0}),t.on("dragmove",n=>{n.cancelBubble=!0}),t.on("dragend",n=>{n.cancelBubble=!0}),this.on("dragmove",n=>{this.update()})}_handleMouseDown(t){if(this._transforming)return;this._movingAnchorName=t.target.name().split(" ")[0];const n=this._getNodeRect(),r=n.width,a=n.height,i=Math.sqrt(Math.pow(r,2)+Math.pow(a,2));this.sin=Math.abs(a/i),this.cos=Math.abs(r/i),typeof window<"u"&&(window.addEventListener("mousemove",this._handleMouseMove),window.addEventListener("touchmove",this._handleMouseMove),window.addEventListener("mouseup",this._handleMouseUp,!0),window.addEventListener("touchend",this._handleMouseUp,!0)),this._transforming=!0;const l=t.target.getAbsolutePosition(),o=t.target.getStage().getPointerPosition();this._anchorDragOffset={x:o.x-l.x,y:o.y-l.y},SHe++,this._fire("transformstart",{evt:t.evt,target:this.getNode()}),this._nodes.forEach(c=>{c._fire("transformstart",{evt:t.evt,target:c})})}_handleMouseMove(t){let n,r,a;const i=this.findOne("."+this._movingAnchorName),l=i.getStage();l.setPointersPositions(t);const o=l.getPointerPosition();let c={x:o.x-this._anchorDragOffset.x,y:o.y-this._anchorDragOffset.y};const d=i.getAbsolutePosition();this.anchorDragBoundFunc()&&(c=this.anchorDragBoundFunc()(d,c,t)),i.setAbsolutePosition(c);const u=i.getAbsolutePosition();if(d.x===u.x&&d.y===u.y)return;if(this._movingAnchorName==="rotater"){const b=this._getNodeRect();n=i.x()-b.width/2,r=-i.y()+b.height/2;const j=yi.getAngle(this.rotateAnchorAngle());let S=Math.atan2(-r,n)+Math.PI/2-j;b.height<0&&(S-=Math.PI);const E=yi.getAngle(this.rotation())+S,P=yi.getAngle(this.rotationSnapTolerance()),I=Ysn(this.rotationSnaps(),E,P)-b.rotation,D=Ksn(b,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 b=p?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".bottom-right").x(),y:this.findOne(".bottom-right").y()};a=Math.sqrt(Math.pow(b.x-i.x(),2)+Math.pow(b.y-i.y(),2));const j=this.findOne(".top-left").x()>b.x?-1:1,S=this.findOne(".top-left").y()>b.y?-1:1;n=a*this.cos*j,r=a*this.sin*S,this.findOne(".top-left").x(b.x-n),this.findOne(".top-left").y(b.y-r)}}else if(this._movingAnchorName==="top-center")this.findOne(".top-left").y(i.y());else if(this._movingAnchorName==="top-right"){if(m){const b=p?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".bottom-left").x(),y:this.findOne(".bottom-left").y()};a=Math.sqrt(Math.pow(i.x()-b.x,2)+Math.pow(b.y-i.y(),2));const j=this.findOne(".top-right").x()b.y?-1:1;n=a*this.cos*j,r=a*this.sin*S,this.findOne(".top-right").x(b.x+n),this.findOne(".top-right").y(b.y-r)}var f=i.position();this.findOne(".top-left").y(f.y),this.findOne(".bottom-right").x(f.x)}else if(this._movingAnchorName==="middle-left")this.findOne(".top-left").x(i.x());else if(this._movingAnchorName==="middle-right")this.findOne(".bottom-right").x(i.x());else if(this._movingAnchorName==="bottom-left"){if(m){const b=p?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".top-right").x(),y:this.findOne(".top-right").y()};a=Math.sqrt(Math.pow(b.x-i.x(),2)+Math.pow(i.y()-b.y,2));const j=b.x{var i;a._fire("transformend",{evt:t,target:a}),(i=a.getLayer())===null||i===void 0||i.batchDraw()}),this._movingAnchorName=null}}_fitNodesInto(t,n){const r=this._getNodeRect(),a=1;if(sr._inRange(t.width,-this.padding()*2-a,a)){this.update();return}if(sr._inRange(t.height,-this.padding()*2-a,a)){this.update();return}const i=new Jw;if(i.rotate(yi.getAngle(this.rotation())),this._movingAnchorName&&t.width<0&&this._movingAnchorName.indexOf("left")>=0){const m=i.point({x:-this.padding()*2,y:0});t.x+=m.x,t.y+=m.y,t.width+=this.padding()*2,this._movingAnchorName=this._movingAnchorName.replace("left","right"),this._anchorDragOffset.x-=m.x,this._anchorDragOffset.y-=m.y}else if(this._movingAnchorName&&t.width<0&&this._movingAnchorName.indexOf("right")>=0){const m=i.point({x:this.padding()*2,y:0});this._movingAnchorName=this._movingAnchorName.replace("right","left"),this._anchorDragOffset.x-=m.x,this._anchorDragOffset.y-=m.y,t.width+=this.padding()*2}if(this._movingAnchorName&&t.height<0&&this._movingAnchorName.indexOf("top")>=0){const m=i.point({x:0,y:-this.padding()*2});t.x+=m.x,t.y+=m.y,this._movingAnchorName=this._movingAnchorName.replace("top","bottom"),this._anchorDragOffset.x-=m.x,this._anchorDragOffset.y-=m.y,t.height+=this.padding()*2}else if(this._movingAnchorName&&t.height<0&&this._movingAnchorName.indexOf("bottom")>=0){const m=i.point({x:0,y:this.padding()*2});this._movingAnchorName=this._movingAnchorName.replace("bottom","top"),this._anchorDragOffset.x-=m.x,this._anchorDragOffset.y-=m.y,t.height+=this.padding()*2}if(this.boundBoxFunc()){const m=this.boundBoxFunc()(r,t);m?t=m:sr.warn("boundBoxFunc returned falsy. You should return new bound rect from it!")}const l=1e7,o=new Jw;o.translate(r.x,r.y),o.rotate(r.rotation),o.scale(r.width/l,r.height/l);const c=new Jw,d=t.width/l,u=t.height/l;this.flipEnabled()===!1?(c.translate(t.x,t.y),c.rotate(t.rotation),c.translate(t.width<0?t.width:0,t.height<0?t.height:0),c.scale(Math.abs(d),Math.abs(u))):(c.translate(t.x,t.y),c.rotate(t.rotation),c.scale(d,u));const h=c.multiply(o.invert());this._nodes.forEach(m=>{var p;if(!m.getStage())return;const f=m.getParent().getAbsoluteTransform(),y=m.getTransform().copy();y.translate(m.offsetX(),m.offsetY());const v=new Jw;v.multiply(f.copy().invert()).multiply(h).multiply(f).multiply(y);const g=v.decompose();m.setAttrs(g),(p=m.getLayer())===null||p===void 0||p.batchDraw()}),this.rotation(sr._getRotation(t.rotation)),this._nodes.forEach(m=>{this._fire("transform",{evt:n,target:m}),m._fire("transform",{evt:n,target:m})}),this._resetTransformCache(),this.update(),this.getLayer().batchDraw()}forceUpdate(){this._resetTransformCache(),this.update()}_batchChangeChild(t,n){this.findOne(t).setAttrs(n)}update(){var t;const n=this._getNodeRect();this.rotation(sr._getRotation(n.rotation));const r=n.width,a=n.height,i=this.enabledAnchors(),l=this.resizeEnabled(),o=this.padding(),c=this.anchorSize(),d=this.find("._anchor");d.forEach(E=>{E.setAttrs({width:c,height:c,offsetX:c/2,offsetY:c/2,stroke:this.anchorStroke(),strokeWidth:this.anchorStrokeWidth(),fill:this.anchorFill(),cornerRadius:this.anchorCornerRadius()})}),this._batchChangeChild(".top-left",{x:0,y:0,offsetX:c/2+o,offsetY:c/2+o,visible:l&&i.indexOf("top-left")>=0}),this._batchChangeChild(".top-center",{x:r/2,y:0,offsetY:c/2+o,visible:l&&i.indexOf("top-center")>=0}),this._batchChangeChild(".top-right",{x:r,y:0,offsetX:c/2-o,offsetY:c/2+o,visible:l&&i.indexOf("top-right")>=0}),this._batchChangeChild(".middle-left",{x:0,y:a/2,offsetX:c/2+o,visible:l&&i.indexOf("middle-left")>=0}),this._batchChangeChild(".middle-right",{x:r,y:a/2,offsetX:c/2-o,visible:l&&i.indexOf("middle-right")>=0}),this._batchChangeChild(".bottom-left",{x:0,y:a,offsetX:c/2+o,offsetY:c/2-o,visible:l&&i.indexOf("bottom-left")>=0}),this._batchChangeChild(".bottom-center",{x:r/2,y:a,offsetY:c/2-o,visible:l&&i.indexOf("bottom-center")>=0}),this._batchChangeChild(".bottom-right",{x:r,y:a,offsetX:c/2-o,offsetY:c/2-o,visible:l&&i.indexOf("bottom-right")>=0});const u=this.rotateAnchorAngle(),h=this.rotateAnchorOffset(),m=sr.degToRad(u),p=Math.sin(m),f=-Math.cos(m),y=r/2,v=a/2;let g=1/0;f<0?g=Math.min(g,-v/f):f>0&&(g=Math.min(g,(a-v)/f)),p<0?g=Math.min(g,-y/p):p>0&&(g=Math.min(g,(r-y)/p));const b=y+p*g,j=v+f*g,S=sr._sign(a);this._batchChangeChild(".rotater",{x:b+p*h*S,y:j+f*h*S-o*f,visible:this.rotateEnabled()}),this._batchChangeChild(".back",{width:r,height:a,visible:this.borderEnabled(),stroke:this.borderStroke(),strokeWidth:this.borderStrokeWidth(),dash:this.borderDash(),draggable:this.nodes().some(E=>E.draggable()),x:0,y:0});const C=this.anchorStyleFunc();C&&d.forEach(E=>{C(E)}),(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=""),qH.prototype.destroy.call(this),this.detach(),this._removeEvents(),this}add(...t){return this._elementsCreated?(sr.error("You cannot add external nodes to the Transformer. Use tr.nodes([node]) instead."),this):super.add(...t)}toObject(){return ki.prototype.toObject.call(this)}clone(t){return ki.prototype.clone.call(this,t)}getClientRect(){return this.nodes().length>0?super.getClientRect():{x:0,y:0,width:0,height:0}}};au.isTransforming=()=>SHe>0;function Zsn(s){return s instanceof Array||sr.warn("enabledAnchors value should be an array"),s instanceof Array&&s.forEach(function(t){jEe.indexOf(t)===-1&&sr.warn("Unknown anchor name: "+t+". Available names are: "+jEe.join(", "))}),s||[]}au.prototype.className="Transformer";Zf(au);xn.addGetterSetter(au,"enabledAnchors",jEe,Zsn);xn.addGetterSetter(au,"flipEnabled",!0,OS());xn.addGetterSetter(au,"resizeEnabled",!0);xn.addGetterSetter(au,"anchorSize",10,hi());xn.addGetterSetter(au,"rotateEnabled",!0);xn.addGetterSetter(au,"rotateLineVisible",!0);xn.addGetterSetter(au,"rotationSnaps",[]);xn.addGetterSetter(au,"rotateAnchorOffset",50,hi());xn.addGetterSetter(au,"rotateAnchorAngle",0,hi());xn.addGetterSetter(au,"rotateAnchorCursor","crosshair");xn.addGetterSetter(au,"rotationSnapTolerance",5,hi());xn.addGetterSetter(au,"borderEnabled",!0);xn.addGetterSetter(au,"anchorStroke","rgb(0, 161, 255)");xn.addGetterSetter(au,"anchorStrokeWidth",1,hi());xn.addGetterSetter(au,"anchorFill","white");xn.addGetterSetter(au,"anchorCornerRadius",0,hi());xn.addGetterSetter(au,"borderStroke","rgb(0, 161, 255)");xn.addGetterSetter(au,"borderStrokeWidth",1,hi());xn.addGetterSetter(au,"borderDash");xn.addGetterSetter(au,"keepRatio",!0);xn.addGetterSetter(au,"shiftBehavior","default");xn.addGetterSetter(au,"centeredScaling",!1);xn.addGetterSetter(au,"ignoreStroke",!1);xn.addGetterSetter(au,"padding",0,hi());xn.addGetterSetter(au,"nodes");xn.addGetterSetter(au,"node");xn.addGetterSetter(au,"boundBoxFunc");xn.addGetterSetter(au,"anchorDragBoundFunc");xn.addGetterSetter(au,"anchorStyleFunc");xn.addGetterSetter(au,"shouldOverdrawWholeArea",!1);xn.addGetterSetter(au,"useSingleNodeRotation",!0);xn.backCompat(au,{lineEnabled:"borderEnabled",rotateHandlerOffset:"rotateAnchorOffset",enabledHandlers:"enabledAnchors"});class zE extends si{_sceneFunc(t){t.beginPath(),t.arc(0,0,this.radius(),0,yi.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)}}zE.prototype.className="Wedge";zE.prototype._centroid=!0;zE.prototype._attrsAffectingSize=["radius"];Zf(zE);xn.addGetterSetter(zE,"radius",0,hi());xn.addGetterSetter(zE,"angle",0,hi());xn.addGetterSetter(zE,"clockwise",!1);xn.backCompat(zE,{angleDeg:"angle",getAngleDeg:"getAngle",setAngleDeg:"setAngle"});function dvt(){this.r=0,this.g=0,this.b=0,this.a=0,this.next=null}const Xsn=[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],Qsn=[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 Jsn(s,t){const n=s.data,r=s.width,a=s.height;let i,l,o,c,d,u,h,m,p,f,y,v,g,b,j,S,C,E,P,M;const I=t+t+1,D=r-1,O=a-1,V=t+1,G=V*(V+1)/2,$=new dvt,H=Xsn[t],Y=Qsn[t];let Z=null,ne=$,ce=null,ie=null;for(let te=1;te>Y,P!==0?(P=255/P,n[l]=(c*H>>Y)*P,n[l+1]=(d*H>>Y)*P,n[l+2]=(u*H>>Y)*P):n[l]=n[l+1]=n[l+2]=0,c-=m,d-=p,u-=f,h-=y,m-=ce.r,p-=ce.g,f-=ce.b,y-=ce.a,i=o+((i=ae+t+1)>Y,P>0?(P=255/P,n[i]=(c*H>>Y)*P,n[i+1]=(d*H>>Y)*P,n[i+2]=(u*H>>Y)*P):n[i]=n[i+1]=n[i+2]=0,c-=m,d-=p,u-=f,h-=y,m-=ce.r,p-=ce.g,f-=ce.b,y-=ce.a,i=te+((i=le+V)0&&Jsn(t,n)};xn.addGetterSetter(ki,"blurRadius",0,hi(),xn.afterSetFilter);const tnn=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};xn.addGetterSetter(ki,"contrast",0,hi(),xn.afterSetFilter);const rnn=function(s){var t,n,r,a,i,l,o,c,d;const u=s.data,h=s.width,m=s.height,p=Math.min(1,Math.max(0,(n=(t=this.embossStrength)===null||t===void 0?void 0:t.call(this))!==null&&n!==void 0?n:.5)),f=Math.min(1,Math.max(0,(a=(r=this.embossWhiteLevel)===null||r===void 0?void 0:r.call(this))!==null&&a!==void 0?a:.5)),v=(o={"top-left":315,top:270,"top-right":225,right:180,"bottom-right":135,bottom:90,"bottom-left":45,left:0}[(l=(i=this.embossDirection)===null||i===void 0?void 0:i.call(this))!==null&&l!==void 0?l:"top-left"])!==null&&o!==void 0?o:315,g=!!((d=(c=this.embossBlend)===null||c===void 0?void 0:c.call(this))!==null&&d!==void 0&&d),b=p*10,j=f*255,S=v*Math.PI/180,C=Math.cos(S),E=Math.sin(S),P=128/1020*b,M=new Uint8ClampedArray(u),I=new Float32Array(h*m);for(let $=0,H=0;H$<0?0:$>255?255:$;for(let $=1;$a&&(a=i),c=t[j+1],co&&(o=c),h=t[j+2],hu&&(u=h);a===r&&(a=255,r=0),o===l&&(o=255,l=0),u===d&&(u=255,d=0);let p,f,y,v,g,b;if(m>0)p=a+m*(255-a),f=r-m*(r-0),y=o+m*(255-o),v=l-m*(l-0),g=u+m*(255-u),b=d-m*(d-0);else{const j=(a+r)*.5;p=a+m*(a-j),f=r+m*(r-j);const S=(o+l)*.5;y=o+m*(o-S),v=l+m*(l-S);const C=(u+d)*.5;g=u+m*(u-C),b=d+m*(d-C)}for(let j=0;jd?m:d;const p=l,f=i,y=360/f*Math.PI/180;for(let v=0;vd?m:d;const p=l,f=i,y=0;let v,g;for(u=0;ut&&(S=j,C=0,E=-1),a=0;a=0&&p=0&&f=0&&p=0&&f=255*4?255:0}return l}function ynn(s,t,n){const r=[.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111],a=Math.round(Math.sqrt(r.length)),i=Math.floor(a/2),l=[];for(let o=0;o=0&&p=0&&f=n))for(let j=y;j=r)continue;const S=(n*j+b)*4;d+=l[S+0],u+=l[S+1],h+=l[S+2],m+=l[S+3],g+=1}d=d/g,u=u/g,h=h/g,m=m/g;for(let b=p;b=n))for(let j=y;j=r)continue;const S=(n*j+b)*4;l[S+0]=d,l[S+1]=u,l[S+2]=h,l[S+3]=m}}};xn.addGetterSetter(ki,"pixelSize",8,hi(),xn.afterSetFilter);const wnn=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)});xn.addGetterSetter(ki,"green",0,function(s){return this._filterUpToDate=!1,s>255?255:s<0?0:Math.round(s)});xn.addGetterSetter(ki,"blue",0,Jqt,xn.afterSetFilter);const Nnn=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)});xn.addGetterSetter(ki,"green",0,function(s){return this._filterUpToDate=!1,s>255?255:s<0?0:Math.round(s)});xn.addGetterSetter(ki,"blue",0,Jqt,xn.afterSetFilter);xn.addGetterSetter(ki,"alpha",1,function(s){return this._filterUpToDate=!1,s>1?1:s<0?0:s});const knn=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},Cnn=function(s){const t=this.threshold()*255,n=s.data,r=n.length;for(let a=0;aZn||dt[Bs]!==Lt[Zn]){var Dr=` `+dt[Bs].replace(" at new "," at ");return re.displayName&&Dr.includes("")&&(Dr=Dr.replace("",re.displayName)),Dr}while(1<=Bs&&0<=Zn);break}}}finally{sa=!1,Error.prepareStackTrace=De}return(re=re?re.displayName||re.name:"")?Br(re):""}var ra=Object.prototype.hasOwnProperty,Si=[],Gi=-1;function rl(re){return{current:re}}function Ii(re){0>Gi||(re.current=Si[Gi],Si[Gi]=null,Gi--)}function Ta(re,de){Gi++,Si[Gi]=re.current,re.current=de}var eo={},So=rl(eo),Ra=rl(!1),Eo=eo;function Ro(re,de){var De=re.type.contextTypes;if(!De)return eo;var st=re.stateNode;if(st&&st.__reactInternalMemoizedUnmaskedChildContext===de)return st.__reactInternalMemoizedMaskedChildContext;var dt={},Lt;for(Lt in De)dt[Lt]=de[Lt];return st&&(re=re.stateNode,re.__reactInternalMemoizedUnmaskedChildContext=de,re.__reactInternalMemoizedMaskedChildContext=dt),dt}function di(re){return re=re.childContextTypes,re!=null}function rr(){Ii(Ra),Ii(So)}function oi(re,de,De){if(So.current!==eo)throw Error(l(168));Ta(So,de),Ta(Ra,De)}function Oo(re,de,De){var st=re.stateNode;if(de=de.childContextTypes,typeof st.getChildContext!="function")return De;st=st.getChildContext();for(var dt in st)if(!(dt in de))throw Error(l(108,M(re)||"Unknown",dt));return i({},De,st)}function kl(re){return re=(re=re.stateNode)&&re.__reactInternalMemoizedMergedChildContext||eo,Eo=So.current,Ta(So,re),Ta(Ra,Ra.current),!0}function Jo(re,de,De){var st=re.stateNode;if(!st)throw Error(l(169));De?(re=Oo(re,de,Eo),st.__reactInternalMemoizedMergedChildContext=re,Ii(Ra),Ii(So),Ta(So,re)):Ii(Ra),Ta(Ra,De)}var Sl=Math.clz32?Math.clz32:Tp,vu=Math.log,Ku=Math.LN2;function Tp(re){return re>>>=0,re===0?32:31-(vu(re)/Ku|0)|0}var Bd=64,xm=4194304;function xs(re){switch(re&-re){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 re&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return re&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return re}}function da(re,de){var De=re.pendingLanes;if(De===0)return 0;var st=0,dt=re.suspendedLanes,Lt=re.pingedLanes,Bs=De&268435455;if(Bs!==0){var Zn=Bs&~dt;Zn!==0?st=xs(Zn):(Lt&=Bs,Lt!==0&&(st=xs(Lt)))}else Bs=De&~dt,Bs!==0?st=xs(Bs):Lt!==0&&(st=xs(Lt));if(st===0)return 0;if(de!==0&&de!==st&&!(de&dt)&&(dt=st&-st,Lt=de&-de,dt>=Lt||dt===16&&(Lt&4194240)!==0))return de;if(st&4&&(st|=De&16),de=re.entangledLanes,de!==0)for(re=re.entanglements,de&=st;0De;De++)de.push(re);return de}function Bu(re,de,De){re.pendingLanes|=de,de!==536870912&&(re.suspendedLanes=0,re.pingedLanes=0),re=re.eventTimes,de=31-Sl(de),re[de]=De}function Uu(re,de){var De=re.pendingLanes&~de;re.pendingLanes=de,re.suspendedLanes=0,re.pingedLanes=0,re.expiredLanes&=de,re.mutableReadLanes&=de,re.entangledLanes&=de,de=re.entanglements;var st=re.eventTimes;for(re=re.expirationTimes;0>=Bs,dt-=Bs,iu=1<<32-Sl(de)+dt|De<Zl?(zp=yo,yo=null):zp=yo.sibling;var Sd=Di(Tr,yo,Hn[Zl],Vi);if(Sd===null){yo===null&&(yo=zp);break}re&&yo&&Sd.alternate===null&&de(Tr,yo),En=Lt(Sd,En,Zl),fl===null?ao=Sd:fl.sibling=Sd,fl=Sd,yo=zp}if(Zl===Hn.length)return De(Tr,yo),An&&Om(Tr,Zl),ao;if(yo===null){for(;ZlZl?(zp=yo,yo=null):zp=yo.sibling;var Yb=Di(Tr,yo,Sd.value,Vi);if(Yb===null){yo===null&&(yo=zp);break}re&&yo&&Yb.alternate===null&&de(Tr,yo),En=Lt(Yb,En,Zl),fl===null?ao=Yb:fl.sibling=Yb,fl=Yb,yo=zp}if(Sd.done)return De(Tr,yo),An&&Om(Tr,Zl),ao;if(yo===null){for(;!Sd.done;Zl++,Sd=Hn.next())Sd=nc(Tr,Sd.value,Vi),Sd!==null&&(En=Lt(Sd,En,Zl),fl===null?ao=Sd:fl.sibling=Sd,fl=Sd);return An&&Om(Tr,Zl),ao}for(yo=st(Tr,yo);!Sd.done;Zl++,Sd=Hn.next())Sd=Mh(yo,Tr,Zl,Sd.value,Vi),Sd!==null&&(re&&Sd.alternate!==null&&yo.delete(Sd.key===null?Zl:Sd.key),En=Lt(Sd,En,Zl),fl===null?ao=Sd:fl.sibling=Sd,fl=Sd);return re&&yo.forEach(function(GL){return de(Tr,GL)}),An&&Om(Tr,Zl),ao}function Wy(Tr,En,Hn,Vi){if(typeof Hn=="object"&&Hn!==null&&Hn.type===u&&Hn.key===null&&(Hn=Hn.props.children),typeof Hn=="object"&&Hn!==null){switch(Hn.$$typeof){case c:e:{for(var ao=Hn.key,fl=En;fl!==null;){if(fl.key===ao){if(ao=Hn.type,ao===u){if(fl.tag===7){De(Tr,fl.sibling),En=dt(fl,Hn.props.children),En.return=Tr,Tr=En;break e}}else if(fl.elementType===ao||typeof ao=="object"&&ao!==null&&ao.$$typeof===j&&Nn(ao)===fl.type){De(Tr,fl.sibling),En=dt(fl,Hn.props),En.ref=Xh(Tr,fl,Hn),En.return=Tr,Tr=En;break e}De(Tr,fl);break}else de(Tr,fl);fl=fl.sibling}Hn.type===u?(En=Us(Hn.props.children,Tr.mode,Vi,Hn.key),En.return=Tr,Tr=En):(Vi=nd(Hn.type,Hn.key,Hn.props,null,Tr.mode,Vi),Vi.ref=Xh(Tr,En,Hn),Vi.return=Tr,Tr=Vi)}return Bs(Tr);case d:e:{for(fl=Hn.key;En!==null;){if(En.key===fl)if(En.tag===4&&En.stateNode.containerInfo===Hn.containerInfo&&En.stateNode.implementation===Hn.implementation){De(Tr,En.sibling),En=dt(En,Hn.children||[]),En.return=Tr,Tr=En;break e}else{De(Tr,En);break}else de(Tr,En);En=En.sibling}En=XC(Hn,Tr.mode,Vi),En.return=Tr,Tr=En}return Bs(Tr);case j:return fl=Hn._init,Wy(Tr,En,fl(Hn._payload),Vi)}if(H(Hn))return rc(Tr,En,Hn,Vi);if(E(Hn))return qx(Tr,En,Hn,Vi);$t(Tr,Hn)}return typeof Hn=="string"&&Hn!==""||typeof Hn=="number"?(Hn=""+Hn,En!==null&&En.tag===6?(De(Tr,En.sibling),En=dt(En,Hn),En.return=Tr,Tr=En):(De(Tr,En),En=o5(Hn,Tr.mode,Vi),En.return=Tr,Tr=En),Bs(Tr)):De(Tr,En)}return Wy}var qr=Un(!0),Ea=Un(!1),gi=rl(null),Mi=null,_i=null,Jc=null;function Su(){Jc=_i=Mi=null}function cp(re,de,De){Pe?(Ta(gi,de._currentValue),de._currentValue=De):(Ta(gi,de._currentValue2),de._currentValue2=De)}function dd(re){var de=gi.current;Ii(gi),Pe?re._currentValue=de:re._currentValue2=de}function Ud(re,de,De){for(;re!==null;){var st=re.alternate;if((re.childLanes&de)!==de?(re.childLanes|=de,st!==null&&(st.childLanes|=de)):st!==null&&(st.childLanes&de)!==de&&(st.childLanes|=de),re===De)break;re=re.return}}function Ch(re,de){Mi=re,Jc=_i=null,re=re.dependencies,re!==null&&re.firstContext!==null&&(re.lanes&de&&(tx=!0),re.firstContext=null)}function Pp(re){var de=Pe?re._currentValue:re._currentValue2;if(Jc!==re)if(re={context:re,memoizedValue:de,next:null},_i===null){if(Mi===null)throw Error(l(308));_i=re,Mi.dependencies={lanes:0,firstContext:re}}else _i=_i.next=re;return de}var Fx=null;function sc(re){Fx===null?Fx=[re]:Fx.push(re)}function Ba(re,de,De,st){var dt=de.interleaved;return dt===null?(De.next=De,sc(de)):(De.next=dt.next,dt.next=De),de.interleaved=De,Hr(re,st)}function Hr(re,de){re.lanes|=de;var De=re.alternate;for(De!==null&&(De.lanes|=de),De=re,re=re.return;re!==null;)re.childLanes|=de,De=re.alternate,De!==null&&(De.childLanes|=de),De=re,re=re.return;return De.tag===3?De.stateNode:null}var Cc=!1;function qa(re){re.updateQueue={baseState:re.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Lp(re,de){re=re.updateQueue,de.updateQueue===re&&(de.updateQueue={baseState:re.baseState,firstBaseUpdate:re.firstBaseUpdate,lastBaseUpdate:re.lastBaseUpdate,shared:re.shared,effects:re.effects})}function ou(re,de){return{eventTime:re,lane:de,tag:0,payload:null,callback:null,next:null}}function va(re,de,De){var st=re.updateQueue;if(st===null)return null;if(st=st.shared,zo&2){var dt=st.pending;return dt===null?de.next=de:(de.next=dt.next,dt.next=de),st.pending=de,Hr(re,De)}return dt=st.interleaved,dt===null?(de.next=de,sc(st)):(de.next=dt.next,dt.next=de),st.interleaved=de,Hr(re,De)}function Wg(re,de,De){if(de=de.updateQueue,de!==null&&(de=de.shared,(De&4194240)!==0)){var st=de.lanes;st&=re.pendingLanes,De|=st,de.lanes=De,Rx(re,De)}}function U0(re,de){var De=re.updateQueue,st=re.alternate;if(st!==null&&(st=st.updateQueue,De===st)){var dt=null,Lt=null;if(De=De.firstBaseUpdate,De!==null){do{var Bs={eventTime:De.eventTime,lane:De.lane,tag:De.tag,payload:De.payload,callback:De.callback,next:null};Lt===null?dt=Lt=Bs:Lt=Lt.next=Bs,De=De.next}while(De!==null);Lt===null?dt=Lt=de:Lt=Lt.next=de}else dt=Lt=de;De={baseState:st.baseState,firstBaseUpdate:dt,lastBaseUpdate:Lt,shared:st.shared,effects:st.effects},re.updateQueue=De;return}re=De.lastBaseUpdate,re===null?De.firstBaseUpdate=de:re.next=de,De.lastBaseUpdate=de}function gg(re,de,De,st){var dt=re.updateQueue;Cc=!1;var Lt=dt.firstBaseUpdate,Bs=dt.lastBaseUpdate,Zn=dt.shared.pending;if(Zn!==null){dt.shared.pending=null;var Dr=Zn,Va=Dr.next;Dr.next=null,Bs===null?Lt=Va:Bs.next=Va,Bs=Dr;var to=re.alternate;to!==null&&(to=to.updateQueue,Zn=to.lastBaseUpdate,Zn!==Bs&&(Zn===null?to.firstBaseUpdate=Va:Zn.next=Va,to.lastBaseUpdate=Dr))}if(Lt!==null){var nc=dt.baseState;Bs=0,to=Va=Dr=null,Zn=Lt;do{var Di=Zn.lane,Mh=Zn.eventTime;if((st&Di)===Di){to!==null&&(to=to.next={eventTime:Mh,lane:0,tag:Zn.tag,payload:Zn.payload,callback:Zn.callback,next:null});e:{var rc=re,qx=Zn;switch(Di=de,Mh=De,qx.tag){case 1:if(rc=qx.payload,typeof rc=="function"){nc=rc.call(Mh,nc,Di);break e}nc=rc;break e;case 3:rc.flags=rc.flags&-65537|128;case 0:if(rc=qx.payload,Di=typeof rc=="function"?rc.call(Mh,nc,Di):rc,Di==null)break e;nc=i({},nc,Di);break e;case 2:Cc=!0}}Zn.callback!==null&&Zn.lane!==0&&(re.flags|=64,Di=dt.effects,Di===null?dt.effects=[Zn]:Di.push(Zn))}else Mh={eventTime:Mh,lane:Di,tag:Zn.tag,payload:Zn.payload,callback:Zn.callback,next:null},to===null?(Va=to=Mh,Dr=nc):to=to.next=Mh,Bs|=Di;if(Zn=Zn.next,Zn===null){if(Zn=dt.shared.pending,Zn===null)break;Di=Zn,Zn=Di.next,Di.next=null,dt.lastBaseUpdate=Di,dt.shared.pending=null}}while(!0);if(to===null&&(Dr=nc),dt.baseState=Dr,dt.firstBaseUpdate=Va,dt.lastBaseUpdate=to,de=dt.shared.interleaved,de!==null){dt=de;do Bs|=dt.lane,dt=dt.next;while(dt!==de)}else Lt===null&&(dt.shared.lanes=0);L1|=Bs,re.lanes=Bs,re.memoizedState=nc}}function Ry(re,de,De){if(re=de.effects,de.effects=null,re!==null)for(de=0;deDe?De:4,re(!0);var st=Rb.transition;Rb.transition={};try{re(!1),de()}finally{hl=De,Rb.transition=st}}function KS(){return ph().memoizedState}function UC(re,de,De){var st=Vy(re);if(De={lane:st,action:De,hasEagerState:!1,eagerState:null,next:null},qC(re))YE(de,De);else if(De=Ba(re,de,De,st),De!==null){var dt=xh();Ux(De,re,st,dt),hd(De,de,st)}}function BL(re,de,De){var st=Vy(re),dt={lane:st,action:De,hasEagerState:!1,eagerState:null,next:null};if(qC(re))YE(de,dt);else{var Lt=re.alternate;if(re.lanes===0&&(Lt===null||Lt.lanes===0)&&(Lt=de.lastRenderedReducer,Lt!==null))try{var Bs=de.lastRenderedState,Zn=Lt(Bs,De);if(dt.hasEagerState=!0,dt.eagerState=Zn,wd(Zn,Bs)){var Dr=de.interleaved;Dr===null?(dt.next=dt,sc(de)):(dt.next=Dr.next,Dr.next=dt),de.interleaved=dt;return}}catch{}finally{}De=Ba(re,de,dt,st),De!==null&&(dt=xh(),Ux(De,re,st,dt),hd(De,de,st))}}function qC(re){var de=re.alternate;return re===Ac||de!==null&&de===Ac}function YE(re,de){$d=$u=!0;var De=re.pending;De===null?de.next=de:(de.next=De.next,De.next=de),re.pending=de}function hd(re,de,De){if(De&4194240){var st=de.lanes;st&=re.pendingLanes,De|=st,de.lanes=De,Rx(re,De)}}var iw={readContext:Pp,useCallback:bm,useContext:bm,useEffect:bm,useImperativeHandle:bm,useInsertionEffect:bm,useLayoutEffect:bm,useMemo:bm,useReducer:bm,useRef:bm,useState:bm,useDebugValue:bm,useDeferredValue:bm,useTransition:bm,useMutableSource:bm,useSyncExternalStore:bm,useId:bm,unstable_isNewReconciler:!1},$C={readContext:Pp,useCallback:function(re,de){return Zg().memoizedState=[re,de===void 0?null:de],re},useContext:Pp,useEffect:M1,useImperativeHandle:function(re,de,De){return De=De!=null?De.concat([re]):null,zb(4194308,4,aw.bind(null,de,re),De)},useLayoutEffect:function(re,de){return zb(4194308,4,re,de)},useInsertionEffect:function(re,de){return zb(4,2,re,de)},useMemo:function(re,de){var De=Zg();return de=de===void 0?null:de,re=re(),De.memoizedState=[re,de],re},useReducer:function(re,de,De){var st=Zg();return de=De!==void 0?De(de):de,st.memoizedState=st.baseState=de,re={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:re,lastRenderedState:de},st.queue=re,re=re.dispatch=UC.bind(null,Ac,re),[st.memoizedState,re]},useRef:function(re){var de=Zg();return re={current:re},de.memoizedState=re},useState:hf,useDebugValue:ZN,useDeferredValue:function(re){return Zg().memoizedState=re},useTransition:function(){var re=hf(!1),de=re[0];return re=To.bind(null,re[1]),Zg().memoizedState=re,[de,re]},useMutableSource:function(){},useSyncExternalStore:function(re,de,De){var st=Ac,dt=Zg();if(An){if(De===void 0)throw Error(l(407));De=De()}else{if(De=de(),kd===null)throw Error(l(349));mh&30||KN(st,de,De)}dt.memoizedState=De;var Lt={value:De,getSnapshot:de};return dt.queue=Lt,M1(Ob.bind(null,st,Lt,re),[re]),st.flags|=2048,_m(9,Fb.bind(null,st,Lt,De,de),void 0,null),De},useId:function(){var re=Zg(),de=kd.identifierPrefix;if(An){var De=lp,st=iu;De=(st&~(1<<32-Sl(st)-1)).toString(32)+De,de=":"+de+"R"+De,De=Yg++,0H0&&(de.flags|=128,st=!0,Mn(dt,!1),de.lanes=4194304)}else{if(!st)if(re=Kg(Lt),re!==null){if(de.flags|=128,st=!0,re=re.updateQueue,re!==null&&(de.updateQueue=re,de.flags|=4),Mn(dt,!0),dt.tail===null&&dt.tailMode==="hidden"&&!Lt.alternate&&!An)return Xn(de),null}else 2*Dc()-dt.renderingStartTime>H0&&De!==1073741824&&(de.flags|=128,st=!0,Mn(dt,!1),de.lanes=4194304);dt.isBackwards?(Lt.sibling=de.child,de.child=Lt):(re=dt.last,re!==null?re.sibling=Lt:de.child=Lt,dt.last=Lt)}return dt.tail!==null?(de=dt.tail,dt.rendering=de,dt.tail=de.sibling,dt.renderingStartTime=Dc(),de.sibling=null,re=ud.current,Ta(ud,st?re&1|2:re&1),de):(Xn(de),null);case 22:case 23:return F1(),De=de.memoizedState!==null,re!==null&&re.memoizedState!==null!==De&&(de.flags|=8192),De&&de.mode&1?up&1073741824&&(Xn(de),ze&&de.subtreeFlags&6&&(de.flags|=8192)):Xn(de),null;case 24:return null;case 25:return null}throw Error(l(156,de.tag))}function $n(re,de){switch(Jt(de),de.tag){case 1:return di(de.type)&&rr(),re=de.flags,re&65536?(de.flags=re&-65537|128,de):null;case 3:return uf(),Ii(Ra),Ii(So),vm(),re=de.flags,re&65536&&!(re&128)?(de.flags=re&-65537|128,de):null;case 5:return T1(de),null;case 13:if(Ii(ud),re=de.memoizedState,re!==null&&re.dehydrated!==null){if(de.alternate===null)throw Error(l(340));fi()}return re=de.flags,re&65536?(de.flags=re&-65537|128,de):null;case 19:return Ii(ud),null;case 4:return uf(),null;case 10:return dd(de.type._context),null;case 22:case 23:return F1(),null;case 24:return null;default:return null}}var nr=!1,Mr=!1,br=typeof WeakSet=="function"?WeakSet:Set,Vn=null;function Vr(re,de){var De=re.ref;if(De!==null)if(typeof De=="function")try{De(null)}catch(st){$i(re,de,st)}else De.current=null}function Sa(re,de,De){try{De()}catch(st){$i(re,de,st)}}var ba=!1;function ro(re,de){for(ce(re.containerInfo),Vn=de;Vn!==null;)if(re=Vn,de=re.child,(re.subtreeFlags&1028)!==0&&de!==null)de.return=re,Vn=de;else for(;Vn!==null;){re=Vn;try{var De=re.alternate;if(re.flags&1024)switch(re.tag){case 0:case 11:case 15:break;case 1:if(De!==null){var st=De.memoizedProps,dt=De.memoizedState,Lt=re.stateNode,Bs=Lt.getSnapshotBeforeUpdate(re.elementType===re.type?st:$0(re.type,st),dt);Lt.__reactInternalSnapshotBeforeUpdate=Bs}break;case 3:ze&&Vs(re.stateNode.containerInfo);break;case 5:case 6:case 4:case 17:break;default:throw Error(l(163))}}catch(Zn){$i(re,re.return,Zn)}if(de=re.sibling,de!==null){de.return=re.return,Vn=de;break}Vn=re.return}return De=ba,ba=!1,De}function Oi(re,de,De){var st=de.updateQueue;if(st=st!==null?st.lastEffect:null,st!==null){var dt=st=st.next;do{if((dt.tag&re)===re){var Lt=dt.destroy;dt.destroy=void 0,Lt!==void 0&&Sa(de,De,Lt)}dt=dt.next}while(dt!==st)}}function Al(re,de){if(de=de.updateQueue,de=de!==null?de.lastEffect:null,de!==null){var De=de=de.next;do{if((De.tag&re)===re){var st=De.create;De.destroy=st()}De=De.next}while(De!==de)}}function Ki(re){var de=re.ref;if(de!==null){var De=re.stateNode;switch(re.tag){case 5:re=Y(De);break;default:re=De}typeof de=="function"?de(re):de.current=re}}function xc(re){var de=re.alternate;de!==null&&(re.alternate=null,xc(de)),re.child=null,re.deletions=null,re.sibling=null,re.tag===5&&(de=re.stateNode,de!==null&&Ye(de)),re.stateNode=null,re.return=null,re.dependencies=null,re.memoizedProps=null,re.memoizedState=null,re.pendingProps=null,re.stateNode=null,re.updateQueue=null}function Cu(re){return re.tag===5||re.tag===3||re.tag===4}function El(re){e:for(;;){for(;re.sibling===null;){if(re.return===null||Cu(re.return))return null;re=re.return}for(re.sibling.return=re.return,re=re.sibling;re.tag!==5&&re.tag!==6&&re.tag!==18;){if(re.flags&2||re.child===null||re.tag===4)continue e;re.child.return=re,re=re.child}if(!(re.flags&2))return re.stateNode}}function Qi(re,de,De){var st=re.tag;if(st===5||st===6)re=re.stateNode,de?Ts(De,re,de):Vt(De,re);else if(st!==4&&(re=re.child,re!==null))for(Qi(re,de,De),re=re.sibling;re!==null;)Qi(re,de,De),re=re.sibling}function mi(re,de,De){var st=re.tag;if(st===5||st===6)re=re.stateNode,de?wt(De,re,de):qt(De,re);else if(st!==4&&(re=re.child,re!==null))for(mi(re,de,De),re=re.sibling;re!==null;)mi(re,de,De),re=re.sibling}var Ll=null,Ao=!1;function gl(re,de,De){for(De=De.child;De!==null;)bu(re,de,De),De=De.sibling}function bu(re,de,De){if(Ti&&typeof Ti.onCommitFiberUnmount=="function")try{Ti.onCommitFiberUnmount(Xf,De)}catch{}switch(De.tag){case 5:Mr||Vr(De,de);case 6:if(ze){var st=Ll,dt=Ao;Ll=null,gl(re,de,De),Ll=st,Ao=dt,Ll!==null&&(Ao?$s(Ll,De.stateNode):vt(Ll,De.stateNode))}else gl(re,de,De);break;case 18:ze&&Ll!==null&&(Ao?Qs(Ll,De.stateNode):Kt(Ll,De.stateNode));break;case 4:ze?(st=Ll,dt=Ao,Ll=De.stateNode.containerInfo,Ao=!0,gl(re,de,De),Ll=st,Ao=dt):(ke&&(st=De.stateNode.containerInfo,dt=dr(st),on(st,dt)),gl(re,de,De));break;case 0:case 11:case 14:case 15:if(!Mr&&(st=De.updateQueue,st!==null&&(st=st.lastEffect,st!==null))){dt=st=st.next;do{var Lt=dt,Bs=Lt.destroy;Lt=Lt.tag,Bs!==void 0&&(Lt&2||Lt&4)&&Sa(De,de,Bs),dt=dt.next}while(dt!==st)}gl(re,de,De);break;case 1:if(!Mr&&(Vr(De,de),st=De.stateNode,typeof st.componentWillUnmount=="function"))try{st.props=De.memoizedProps,st.state=De.memoizedState,st.componentWillUnmount()}catch(Zn){$i(De,de,Zn)}gl(re,de,De);break;case 21:gl(re,de,De);break;case 22:De.mode&1?(Mr=(st=Mr)||De.memoizedState!==null,gl(re,de,De),Mr=st):gl(re,de,De);break;default:gl(re,de,De)}}function Bm(re){var de=re.updateQueue;if(de!==null){re.updateQueue=null;var De=re.stateNode;De===null&&(De=re.stateNode=new br),de.forEach(function(st){var dt=i5.bind(null,re,st);De.has(st)||(De.add(st),st.then(dt,dt))})}}function _u(re,de){var De=de.deletions;if(De!==null)for(var st=0;st";case Ah:return":has("+(Au(re)||"")+")";case Ip:return'[role="'+re.value+'"]';case Qh:return'"'+re.value+'"';case Md:return'[data-testname="'+re.value+'"]';default:throw Error(l(365))}}function nx(re,de){var De=[];re=[re,0];for(var st=0;stdt&&(dt=Bs),st&=~Lt}if(st=dt,st=Dc()-st,st=(120>st?120:480>st?480:1080>st?1080:1920>st?1920:3e3>st?3e3:4320>st?4320:1960*Rp(st/1960))-st,10re?16:re,bg===null)var st=!1;else{if(re=bg,bg=null,uw=0,zo&6)throw Error(l(331));var dt=zo;for(zo|=4,Vn=re.current;Vn!==null;){var Lt=Vn,Bs=Lt.child;if(Vn.flags&16){var Zn=Lt.deletions;if(Zn!==null){for(var Dr=0;DrDc()-s2?G0(re,0):I1|=De),ix(re,de)}function YC(re,de){de===0&&(re.mode&1?(de=xm,xm<<=1,!(xm&130023424)&&(xm=4194304)):de=1);var De=xh();re=Hr(re,de),re!==null&&(Bu(re,de,De),ix(re,De))}function XE(re){var de=re.memoizedState,De=0;de!==null&&(De=de.retryLane),YC(re,De)}function i5(re,de){var De=0;switch(re.tag){case 13:var st=re.stateNode,dt=re.memoizedState;dt!==null&&(De=dt.retryLane);break;case 19:st=re.stateNode;break;default:throw Error(l(314))}st!==null&&st.delete(de),YC(re,De)}var QE;QE=function(re,de,De){if(re!==null)if(re.memoizedProps!==de.pendingProps||Ra.current)tx=!0;else{if(!(re.lanes&De)&&!(de.flags&128))return tx=!1,ft(re,de,De);tx=!!(re.flags&131072)}else tx=!1,An&&de.flags&1048576&&zm(de,Dy,de.index);switch(de.lanes=0,de.tag){case 2:var st=de.type;Te(re,de),re=de.pendingProps;var dt=Ro(de,So.current);Ch(de,De),dt=Vj(null,de,st,re,dt,De);var Lt=sw();return de.flags|=1,typeof dt=="object"&&dt!==null&&typeof dt.render=="function"&&dt.$$typeof===void 0?(de.tag=1,de.memoizedState=null,de.updateQueue=null,di(st)?(Lt=!0,kl(de)):Lt=!1,de.memoizedState=dt.state!==null&&dt.state!==void 0?dt.state:null,qa(de),dt.updater=ow,de.stateNode=dt,dt._reactInternals=de,Bx(de,st,re,De),de=Qj(null,de,st,!0,Lt,De)):(de.tag=0,An&&Lt&&ot(de),mf(null,de,dt,De),de=de.child),de;case 16:st=de.elementType;e:{switch(Te(re,de),re=de.pendingProps,dt=st._init,st=dt(st._payload),de.type=st,dt=de.tag=lr(st),re=$0(st,re),dt){case 0:de=QS(null,de,st,re,De);break e;case 1:de=JS(null,de,st,re,De);break e;case 11:de=HC(null,de,st,re,De);break e;case 14:de=Ov(null,de,st,$0(st.type,re),De);break e}throw Error(l(306,st,""))}return de;case 0:return st=de.type,dt=de.pendingProps,dt=de.elementType===st?dt:$0(st,dt),QS(re,de,st,dt,De);case 1:return st=de.type,dt=de.pendingProps,dt=de.elementType===st?dt:$0(st,dt),JS(re,de,st,dt,De);case 3:e:{if(Jj(de),re===null)throw Error(l(387));st=de.pendingProps,Lt=de.memoizedState,dt=Lt.element,Lp(re,de),gg(de,st,null,De);var Bs=de.memoizedState;if(st=Bs.element,Ze&&Lt.isDehydrated)if(Lt={element:st,isDehydrated:!1,cache:Bs.cache,pendingSuspenseBoundaries:Bs.pendingSuspenseBoundaries,transitions:Bs.transitions},de.updateQueue.baseState=Lt,de.memoizedState=Lt,de.flags&256){dt=Zu(Error(l(423)),de),de=lw(re,de,st,De,dt);break e}else if(st!==dt){dt=Zu(Error(l(424)),de),de=lw(re,de,st,De,dt);break e}else for(Ze&&(Xs=rt(de.stateNode.containerInfo),qs=de,An=!0,Wr=null,zr=!1),De=Ea(de,null,st,De),de.child=De;De;)De.flags=De.flags&-3|4096,De=De.sibling;else{if(fi(),st===dt){de=Be(re,de,De);break e}mf(re,de,st,De)}de=de.child}return de;case 5:return E1(de),re===null&&bo(de),st=de.type,dt=de.pendingProps,Lt=re!==null?re.memoizedProps:null,Bs=dt.children,me(st,dt)?Bs=null:Lt!==null&&me(st,Lt)&&(de.flags|=32),XS(re,de),mf(re,de,Bs,De),de.child;case 6:return re===null&&bo(de),null;case 13:return ZE(re,de,De);case 4:return qd(de,de.stateNode.containerInfo),st=de.pendingProps,re===null?de.child=qr(de,null,st,De):mf(re,de,st,De),de.child;case 11:return st=de.type,dt=de.pendingProps,dt=de.elementType===st?dt:$0(st,dt),HC(re,de,st,dt,De);case 7:return mf(re,de,de.pendingProps,De),de.child;case 8:return mf(re,de,de.pendingProps.children,De),de.child;case 12:return mf(re,de,de.pendingProps.children,De),de.child;case 10:e:{if(st=de.type._context,dt=de.pendingProps,Lt=de.memoizedProps,Bs=dt.value,cp(de,st,Bs),Lt!==null)if(wd(Lt.value,Bs)){if(Lt.children===dt.children&&!Ra.current){de=Be(re,de,De);break e}}else for(Lt=de.child,Lt!==null&&(Lt.return=de);Lt!==null;){var Zn=Lt.dependencies;if(Zn!==null){Bs=Lt.child;for(var Dr=Zn.firstContext;Dr!==null;){if(Dr.context===st){if(Lt.tag===1){Dr=ou(-1,De&-De),Dr.tag=2;var Va=Lt.updateQueue;if(Va!==null){Va=Va.shared;var to=Va.pending;to===null?Dr.next=Dr:(Dr.next=to.next,to.next=Dr),Va.pending=Dr}}Lt.lanes|=De,Dr=Lt.alternate,Dr!==null&&(Dr.lanes|=De),Ud(Lt.return,De,de),Zn.lanes|=De;break}Dr=Dr.next}}else if(Lt.tag===10)Bs=Lt.type===de.type?null:Lt.child;else if(Lt.tag===18){if(Bs=Lt.return,Bs===null)throw Error(l(341));Bs.lanes|=De,Zn=Bs.alternate,Zn!==null&&(Zn.lanes|=De),Ud(Bs,De,de),Bs=Lt.sibling}else Bs=Lt.child;if(Bs!==null)Bs.return=Lt;else for(Bs=Lt;Bs!==null;){if(Bs===de){Bs=null;break}if(Lt=Bs.sibling,Lt!==null){Lt.return=Bs.return,Bs=Lt;break}Bs=Bs.return}Lt=Bs}mf(re,de,dt.children,De),de=de.child}return de;case 9:return dt=de.type,st=de.pendingProps.children,Ch(de,De),dt=Pp(dt),st=st(dt),de.flags|=1,mf(re,de,st,De),de.child;case 14:return st=de.type,dt=$0(st,de.pendingProps),dt=$0(st.type,dt),Ov(re,de,st,dt,De);case 15:return Zj(re,de,de.type,de.pendingProps,De);case 17:return st=de.type,dt=de.pendingProps,dt=de.elementType===st?dt:$0(st,dt),Te(re,de),de.tag=1,di(st)?(re=!0,kl(de)):re=!1,Ch(de,De),qb(de,st,dt),Bx(de,st,dt,De),Qj(null,de,st,!0,re,De);case 19:return dw(re,de,De);case 22:return Xj(re,de,De)}throw Error(l(156,de.tag))};function JE(re,de){return ml(re,de)}function sk(re,de,De,st){this.tag=re,this.key=De,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=de,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=st,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Op(re,de,De,st){return new sk(re,de,De,st)}function cr(re){return re=re.prototype,!(!re||!re.isReactComponent)}function lr(re){if(typeof re=="function")return cr(re)?1:0;if(re!=null){if(re=re.$$typeof,re===y)return 11;if(re===b)return 14}return 2}function Gy(re,de){var De=re.alternate;return De===null?(De=Op(re.tag,de,re.key,re.mode),De.elementType=re.elementType,De.type=re.type,De.stateNode=re.stateNode,De.alternate=re,re.alternate=De):(De.pendingProps=de,De.type=re.type,De.flags=0,De.subtreeFlags=0,De.deletions=null),De.flags=re.flags&14680064,De.childLanes=re.childLanes,De.lanes=re.lanes,De.child=re.child,De.memoizedProps=re.memoizedProps,De.memoizedState=re.memoizedState,De.updateQueue=re.updateQueue,de=re.dependencies,De.dependencies=de===null?null:{lanes:de.lanes,firstContext:de.firstContext},De.sibling=re.sibling,De.index=re.index,De.ref=re.ref,De}function nd(re,de,De,st,dt,Lt){var Bs=2;if(st=re,typeof re=="function")cr(re)&&(Bs=1);else if(typeof re=="string")Bs=5;else e:switch(re){case u:return Us(De.children,dt,Lt,de);case h:Bs=8,dt|=8;break;case m:return re=Op(12,De,de,dt|2),re.elementType=m,re.lanes=Lt,re;case v:return re=Op(13,De,de,dt),re.elementType=v,re.lanes=Lt,re;case g:return re=Op(19,De,de,dt),re.elementType=g,re.lanes=Lt,re;case S:return ZC(De,dt,Lt,de);default:if(typeof re=="object"&&re!==null)switch(re.$$typeof){case p:Bs=10;break e;case f:Bs=9;break e;case y:Bs=11;break e;case b:Bs=14;break e;case j:Bs=16,st=null;break e}throw Error(l(130,re==null?re:typeof re,""))}return de=Op(Bs,De,de,dt),de.elementType=re,de.type=st,de.lanes=Lt,de}function Us(re,de,De,st){return re=Op(7,re,st,de),re.lanes=De,re}function ZC(re,de,De,st){return re=Op(22,re,st,de),re.elementType=S,re.lanes=De,re.stateNode={isHidden:!1},re}function o5(re,de,De){return re=Op(6,re,null,de),re.lanes=De,re}function XC(re,de,De){return de=Op(4,re.children!==null?re.children:[],re.key,de),de.lanes=De,de.stateNode={containerInfo:re.containerInfo,pendingChildren:null,implementation:re.implementation},de}function eT(re,de,De,st,dt){this.tag=de,this.containerInfo=re,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=Ae,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=bi(0),this.expirationTimes=bi(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=bi(0),this.identifierPrefix=st,this.onRecoverableError=dt,Ze&&(this.mutableSourceEagerHydrationData=null)}function $L(re,de,De,st,dt,Lt,Bs,Zn,Dr){return re=new eT(re,de,De,Zn,Dr),de===1?(de=1,Lt===!0&&(de|=8)):de=0,Lt=Op(3,null,null,de),re.current=Lt,Lt.stateNode=re,Lt.memoizedState={element:st,isDehydrated:De,cache:null,transitions:null,pendingSuspenseBoundaries:null},qa(Lt),re}function VL(re){if(!re)return eo;re=re._reactInternals;e:{if(I(re)!==re||re.tag!==1)throw Error(l(170));var de=re;do{switch(de.tag){case 3:de=de.stateNode.context;break e;case 1:if(di(de.type)){de=de.stateNode.__reactInternalMemoizedMergedChildContext;break e}}de=de.return}while(de!==null);throw Error(l(171))}if(re.tag===1){var De=re.type;if(di(De))return Oo(re,De,de)}return de}function nk(re){var de=re._reactInternals;if(de===void 0)throw typeof re.render=="function"?Error(l(188)):(re=Object.keys(re).join(","),Error(l(268,re)));return re=V(de),re===null?null:re.stateNode}function HL(re,de){if(re=re.memoizedState,re!==null&&re.dehydrated!==null){var De=re.retryLane;re.retryLane=De!==0&&De=Va&&Lt>=nc&&dt<=to&&Bs<=Di){re.splice(de,1);break}else if(st!==Va||De.width!==Dr.width||DiBs){if(!(Lt!==nc||De.height!==Dr.height||todt)){Va>st&&(Dr.width+=Va-st,Dr.x=st),toLt&&(Dr.height+=nc-Lt,Dr.y=Lt),DiDe&&(De=Bs)),Bs ")+` No matching component was found for: `)+re.join(" > ")}return null},n.getPublicRootInstance=function(re){if(re=re.current,!re.child)return null;switch(re.child.tag){case 5:return Y(re.child.stateNode);default:return re.child.stateNode}},n.injectIntoDevTools=function(re){if(re={bundleType:re.bundleType,version:re.version,rendererPackageName:re.rendererPackageName,rendererConfig:re.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:o.ReactCurrentDispatcher,findHostInstanceByFiber:Cz,findFiberByHostInstance:re.findFiberByHostInstance||sT,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.3.1"},typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u")re=!1;else{var de=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(de.isDisabled||!de.supportsFiber)re=!0;else{try{Xf=de.inject(re),Ti=de}catch{}re=!!de.checkDCE}}return re},n.isAlreadyRendering=function(){return!1},n.observeVisibleRects=function(re,de,De,st){if(!Qe)throw Error(l(363));re=rx(re,de);var dt=xt(re,De,st).disconnect;return{disconnect:function(){dt()}}},n.registerMutableSourceForHydration=function(re,de){var De=de._getVersion;De=De(de._source),re.mutableSourceEagerHydrationData==null?re.mutableSourceEagerHydrationData=[de,De]:re.mutableSourceEagerHydrationData.push(de,De)},n.runWithPriority=function(re,de){var De=hl;try{return hl=re,de()}finally{hl=De}},n.shouldError=function(){return null},n.shouldSuspend=function(){return!1},n.updateContainer=function(re,de,De,st){var dt=de.current,Lt=xh(),Bs=Vy(dt);return De=VL(De),de.context===null?de.context=De:de.pendingContext=De,de=ou(Lt,Bs),de.payload={element:re},st=st===void 0?null:st,st!==null&&(de.callback=st),re=va(dt,de,Bs),re!==null&&(Ux(re,dt,Bs,Lt),Wg(re,dt,Bs)),Bs},n};P$t.exports=Ann;var Enn=P$t.exports;const Tnn=_d(Enn);var L$t={exports:{}},Q9={};/** * @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. */Q9.ConcurrentRoot=1;Q9.ContinuousEventPriority=4;Q9.DefaultEventPriority=16;Q9.DiscreteEventPriority=1;Q9.IdleEventPriority=536870912;Q9.LegacyRoot=0;L$t.exports=Q9;var I$t=L$t.exports;const uvt={children:!0,ref:!0,key:!0,style:!0,forwardedRef:!0,unstable_applyCache:!0,unstable_applyDrawHitFromCache:!0};let hvt=!1,mvt=!1;const Mtt=".react-konva-event",Mnn=`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 `,Pnn=`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 `,Lnn={};function VLe(s,t,n=Lnn){if(!hvt&&"zIndex"in t&&(console.warn(Pnn),hvt=!0),!mvt&&t.draggable){var r=t.x!==void 0||t.y!==void 0,a=t.onDragEnd||t.onDragMove;r&&!a&&(console.warn(Mnn),mvt=!0)}for(var i in n)if(!uvt[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(!uvt[i]){var l=i.slice(0,2)==="on",f=n[i]!==t[i];if(l&&f){var c=i.substr(2).toLowerCase();c.substr(0,7)==="content"&&(c="content"+c.substr(7,1).toUpperCase()+c.substr(8)),t[i]&&(p[c]=t[i])}!l&&(t[i]!==n[i]||u&&t[i]!==s.getAttr(i))&&(m=!0,h[i]=t[i])}m&&(s.setAttrs(h),kL(s));for(var c in p)s.on(c+Mtt,p[c])}function kL(s){if(!yi.autoDrawEnabled){var t=s.getLayer()||s.getStage();t&&t.batchDraw()}}const D$t={},Inn={};o9.Node.prototype._applyProps=VLe;function Dnn(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),kL(s)}function Rnn(s,t,n){let r=o9[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=o9.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 VLe(c,i),c}function Fnn(s,t,n){console.error(`Text components are not supported for now in ReactKonva. Your text is: "${s}"`)}function Onn(s,t,n){return!1}function znn(s){return s}function Bnn(){return null}function Unn(){return null}function qnn(s,t,n,r){return Inn}function $nn(){}function Vnn(s){}function Hnn(s,t){return!1}function Gnn(){return D$t}function Wnn(){return D$t}const Knn=setTimeout,Ynn=clearTimeout,Znn=-1;function Xnn(s,t){return!1}const Qnn=!1,Jnn=!0,ern=!0;function trn(s,t){t.parent===s?t.moveToTop():s.add(t),kL(s)}function srn(s,t){t.parent===s?t.moveToTop():s.add(t),kL(s)}function R$t(s,t,n){t._remove(),s.add(t),t.setZIndex(n.getZIndex()),kL(s)}function nrn(s,t,n){R$t(s,t,n)}function rrn(s,t){t.destroy(),t.off(Mtt),kL(s)}function arn(s,t){t.destroy(),t.off(Mtt),kL(s)}function irn(s,t,n){console.error(`Text components are not yet supported in ReactKonva. You text is: "${n}"`)}function orn(s,t,n){}function lrn(s,t,n,r,a){VLe(s,a,r)}function crn(s){s.hide(),kL(s)}function drn(s){}function urn(s,t){(t.visible==null||t.visible)&&s.show()}function hrn(s,t){}function mrn(s){}function prn(){}const frn=()=>I$t.DefaultEventPriority,xrn=Object.freeze(Object.defineProperty({__proto__:null,appendChild:trn,appendChildToContainer:srn,appendInitialChild:Dnn,cancelTimeout:Ynn,clearContainer:mrn,commitMount:orn,commitTextUpdate:irn,commitUpdate:lrn,createInstance:Rnn,createTextInstance:Fnn,detachDeletedInstance:prn,finalizeInitialChildren:Onn,getChildHostContext:Wnn,getCurrentEventPriority:frn,getPublicInstance:znn,getRootHostContext:Gnn,hideInstance:crn,hideTextInstance:drn,idlePriority:iQ.unstable_IdlePriority,insertBefore:R$t,insertInContainerBefore:nrn,isPrimaryRenderer:Qnn,noTimeout:Znn,now:iQ.unstable_now,prepareForCommit:Bnn,preparePortalMount:Unn,prepareUpdate:qnn,removeChild:rrn,removeChildFromContainer:arn,resetAfterCommit:$nn,resetTextContent:Vnn,run:iQ.unstable_runWithPriority,scheduleTimeout:Knn,shouldDeprioritizeSubtree:Hnn,shouldSetTextContent:Xnn,supportsMutation:ern,unhideInstance:urn,unhideTextInstance:hrn,warnsIfNotActing:Jnn},Symbol.toStringTag,{value:"Module"}));var grn=Object.defineProperty,yrn=Object.defineProperties,vrn=Object.getOwnPropertyDescriptors,pvt=Object.getOwnPropertySymbols,brn=Object.prototype.hasOwnProperty,_rn=Object.prototype.propertyIsEnumerable,fvt=(s,t,n)=>t in s?grn(s,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):s[t]=n,xvt=(s,t)=>{for(var n in t||(t={}))brn.call(t,n)&&fvt(s,n,t[n]);if(pvt)for(var n of pvt(t))_rn.call(t,n)&&fvt(s,n,t[n]);return s},wrn=(s,t)=>yrn(s,vrn(t)),gvt,yvt;typeof window<"u"&&((gvt=window.document)!=null&&gvt.createElement||((yvt=window.navigator)==null?void 0:yvt.product)==="ReactNative")?_.useLayoutEffect:_.useEffect;function F$t(s,t,n){if(!s)return;if(n(s)===!0)return s;let r=s.child;for(;r;){const a=F$t(r,t,n);if(a)return a;r=r.sibling}}function O$t(s){try{return Object.defineProperties(s,{_currentRenderer:{get(){return null},set(){}},_currentRenderer2:{get(){return null},set(){}}})}catch{return s}}const vvt=console.error;console.error=function(){const s=[...arguments].join("");if(s!=null&&s.startsWith("Warning:")&&s.includes("useContext")){console.error=vvt;return}return vvt.apply(this,arguments)};const Ptt=O$t(_.createContext(null));class z$t extends _.Component{render(){return _.createElement(Ptt.Provider,{value:this._reactInternals},this.props.children)}}function jrn(){const s=_.useContext(Ptt);if(s===null)throw new Error("its-fine: useFiber must be called within a !");const t=_.useId();return _.useMemo(()=>{for(const r of[s,s==null?void 0:s.alternate]){if(!r)continue;const a=F$t(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 Nrn(){const s=jrn(),[t]=_.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!==Ptt&&!t.has(a)&&t.set(a,_.useContext(O$t(a)))}n=n.return}return t}function krn(){const s=Nrn();return _.useMemo(()=>Array.from(s.keys()).reduce((t,n)=>r=>_.createElement(t,null,_.createElement(n.Provider,wrn(xvt({},r),{value:s.get(n)}))),t=>_.createElement(z$t,xvt({},t))),[s])}function Srn(s){const t=Dt.useRef({});return Dt.useLayoutEffect(()=>{t.current=s}),Dt.useLayoutEffect(()=>()=>{t.current={}},[]),t.current}const Crn=s=>{const t=Dt.useRef(null),n=Dt.useRef(null),r=Dt.useRef(null),a=Srn(s),i=krn(),l=o=>{const{forwardedRef:c}=s;c&&(typeof c=="function"?c(o):c.current=o)};return Dt.useLayoutEffect(()=>(n.current=new o9.Stage({width:s.width,height:s.height,container:t.current}),l(n.current),r.current=kX.createContainer(n.current,I$t.LegacyRoot,!1,null),kX.updateContainer(Dt.createElement(i,{},s.children),r.current),()=>{o9.isBrowser&&(l(null),kX.updateContainer(null,r.current,null),n.current.destroy())}),[]),Dt.useLayoutEffect(()=>{l(n.current),VLe(n.current,s,a),kX.updateContainer(Dt.createElement(i,{},s.children),r.current,null)}),Dt.createElement("div",{ref:t,id:s.id,accessKey:s.accessKey,className:s.className,role:s.role,style:s.style,tabIndex:s.tabIndex,title:s.title})},Arn="Layer",jM="Group",R5="Rect",rq="Image",MB="Text",h_r="Transformer",kX=Tnn(xrn);kX.injectIntoDevTools({findHostInstanceByFiber:()=>null,bundleType:0,version:Dt.version,rendererPackageName:"react-konva"});const Ern=Dt.forwardRef((s,t)=>Dt.createElement(z$t,{},Dt.createElement(Crn,{...s,forwardedRef:t})));function Trn({imageUrl:s,preset:t,barStyleId:n,overrides:r,maxDisplayWidth:a=720,stageRef:i}){const l=_.useRef(null),[o,c]=_.useState(null),[d,u]=_.useState(null),[h,m]=_.useState(null),p=(t==null?void 0:t.headshot_url)??"",f=(t==null?void 0:t.brokerage_logo_url)??"";_.useEffect(()=>{if(!s){c(null);return}const G=new window.Image;G.crossOrigin="anonymous",G.onload=()=>c(G),G.onerror=()=>c(null),G.src=s},[s]),_.useEffect(()=>{if(!p){u(null);return}const G=new window.Image;G.crossOrigin="anonymous",G.onload=()=>u(G),G.onerror=()=>u(null),G.src=p},[p]),_.useEffect(()=>{if(!f){m(null);return}const G=new window.Image;G.crossOrigin="anonymous",G.onload=()=>m(G),G.onerror=()=>m(null),G.src=f},[f]);const y=ttn(n),v=(o==null?void 0:o.naturalWidth)??1080,g=(o==null?void 0:o.naturalHeight)??1080,b=_.useMemo(()=>Math.min(1,a/v),[v,a]),j=v*b,S=g*b,C=(r==null?void 0:r.brand_color)??(t==null?void 0:t.brand_color)??"#0f172a",E=(r==null?void 0:r.accent_color)??(t==null?void 0:t.accent_color)??"#3b82f6",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)??"",O=new Set((r==null?void 0:r.hidden_fields)??(t==null?void 0:t.hidden_fields)??[]),V=G=>y.fields.includes(G)&&!O.has(G);return e.jsx("div",{className:"border rounded-lg overflow-hidden bg-muted/40 inline-block",children:e.jsx(Ern,{ref:G=>{l.current=G,i&&(i.current=G)},width:j,height:S,scaleX:b,scaleY:b,children:e.jsxs(Arn,{children:[o&&e.jsx(rq,{image:o,width:v,height:g,listening:!1}),!o&&e.jsx(R5,{x:0,y:0,width:v,height:g,fill:"#e2e8f0"}),e.jsx(Mrn,{style:y,canvasW:v,canvasH:g,brandColor:C,accentColor:E,name:P,phone:M,email:I,tagline:D,headshot:d,logo:h,hidden:O,has:V})]})})})}function Mrn({style:s,canvasW:t,canvasH:n,brandColor:r,accentColor:a,name:i,phone:l,email:o,tagline:c,headshot:d,logo:u,has:h}){const m=n*s.heightRatio,p=m*.18,f=s.textColor==="light"?"#ffffff":s.textColor==="dark"?"#0f172a":s.background==="dark"||s.background==="gradient"?"#ffffff":stn(r),y=f==="#ffffff"?"rgba(255,255,255,0.78)":"rgba(15,23,42,0.7)";if(s.position==="bottom"||s.position==="top"){const v=s.position==="bottom"?n-m:0;return e.jsxs(jM,{children:[e.jsx(R5,{x:0,y:v,width:t,height:m,fill:r}),e.jsx(R5,{x:0,y:s.position==="bottom"?v:m-4,width:t,height:4,fill:a}),e.jsx(mce,{x:p,y:v+p,width:t-p*2,height:m-p*2,textColor:f,subTextColor:y,name:i,phone:l,email:o,tagline:c,headshot:d,logo:u,has:h,circular:s.circularHeadshot})]})}if(s.position==="corner-br"){const v=t*.42,g=m,b=t-v-n*.025,j=n-g-n*.025;return e.jsxs(jM,{children:[e.jsx(R5,{x:b,y:j,width:v,height:g,fill:r,cornerRadius:g*.12,opacity:.92}),e.jsx(R5,{x:b,y:j+g-4,width:v,height:4,fill:a,cornerRadius:2}),e.jsx(mce,{x:b+p,y:j+p,width:v-p*2,height:g-p*2,textColor:f,subTextColor:y,name:i,phone:l,email:o,tagline:c,headshot:d,logo:u,has:h,circular:s.circularHeadshot})]})}if(s.position==="side-right"){const v=Math.max(t*.22,Math.min(t*.3,260)),g=v*.12;return e.jsxs(jM,{children:[e.jsx(R5,{x:t-v,y:0,width:v,height:n,fill:r}),e.jsx(R5,{x:t-v,y:0,width:4,height:n,fill:a}),e.jsx(mce,{x:t-v+g,y:n*.08,width:v-g*2,height:n*.84,textColor:f,subTextColor:y,name:i,phone:l,email:o,tagline:c,headshot:d,logo:u,has:h,circular:s.circularHeadshot,vertical:!0,railWidth:v})]})}return s.position==="letterbox"?e.jsxs(jM,{children:[e.jsx(R5,{x:0,y:0,width:t,height:m,fill:"#0a0a0a"}),e.jsx(R5,{x:0,y:n-m,width:t,height:m,fill:"#0a0a0a"}),e.jsx(R5,{x:0,y:n-m,width:t,height:3,fill:a}),e.jsx(mce,{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(rq,{image:u,x:t-p-m*.7,y:p,height:m-p*2,width:m*.7})]}):null}function mce({x:s,y:t,width:n,height:r,textColor:a,subTextColor:i,name:l,phone:o,email:c,tagline:d,headshot:u,logo:h,has:m,circular:p,vertical:f,railWidth:y}){if(f){const G=y??n,$=Math.min(n,G*.7),H=Math.max(14,G*.13),Y=Math.max(11,G*.085),Z=G*.08,ne=G*.35;let ce=t;const ie=ce;ce+=$+Z;const te=ce,ae=l.length>12?2:1;ce+=H*1.15*ae+Z*.5;const le=ce;m("phone")&&o&&(ce+=Y*1.3+Z*.4);const be=ce;m("email")&&c&&(ce+=Y*1.3+Z*.4);const me=ce+Z*.5;return e.jsxs(jM,{children:[m("headshot")&&u&&e.jsx(jM,{clipFunc:p?he=>{he.beginPath(),he.arc(s+n/2,ie+$/2,$/2,0,Math.PI*2),he.closePath()}:void 0,children:e.jsx(rq,{image:u,x:s+(n-$)/2,y:ie,width:$,height:$})}),m("name")&&l&&e.jsx(MB,{text:l,x:s,y:te,width:n,align:"center",fontSize:H,fontStyle:"bold",fill:a}),m("phone")&&o&&e.jsx(MB,{text:o,x:s,y:le,width:n,align:"center",fontSize:Y,fill:i}),m("email")&&c&&e.jsx(MB,{text:c,x:s,y:be,width:n,align:"center",fontSize:Y,fill:i,ellipsis:!0,wrap:"none"}),m("logo")&&h&&e.jsx(rq,{image:h,x:s,y:me,width:n,height:ne})]})}const v=r*.95,g=u&&m("headshot")?s+v+r*.18:s,b=n-(g-s)-(h&&m("logo")?r*1.6:0),j=Math.max(20,r*.34),S=Math.max(13,r*.22),C=r*.06,E=m("tagline")&&d?1:0,P=m("phone")&&o?1:0,M=m("email")&&c?1:0,I=1+E+(P||M?1:0),D=I*j+(I-1)*C;let V=t+(r-D)/2;return e.jsxs(jM,{children:[m("headshot")&&u&&e.jsx(jM,{clipFunc:p?G=>{G.beginPath(),G.arc(s+v/2,t+v/2,v/2,0,Math.PI*2),G.closePath()}:void 0,children:e.jsx(rq,{image:u,x:s,y:t+(r-v)/2,width:v,height:v})}),m("name")&&l&&e.jsx(MB,{text:l,x:g,y:V,width:b,fontSize:j,fontStyle:"bold",fill:a,ellipsis:!0,wrap:"none"}),(V+=j+C,null),m("tagline")&&d&&e.jsxs(e.Fragment,{children:[e.jsx(MB,{text:d,x:g,y:V,width:b,fontSize:S*1.1,fontStyle:"italic",fill:i,ellipsis:!0,wrap:"none"}),(V+=S*1.1+C,null)]}),P||M?e.jsx(MB,{text:[o,c].filter(Boolean).join(" • "),x:g,y:V,width:b,fontSize:S,fill:i,ellipsis:!0,wrap:"none"}):null,m("logo")&&h&&e.jsx(rq,{image:h,x:s+n-r*1.4,y:t+(r-r*.8)/2,width:r*1.4,height:r*.8})]})}function Prn(){const{data:s}=bae(),t=(s==null?void 0:s.find(V=>V.is_default))??(s==null?void 0:s[0])??null,[n,r]=_.useState(void 0),a=(s==null?void 0:s.find(V=>V.id===n))??t,[i,l]=_.useState([]),[o,c]=_.useState(0),[d,u]=_.useState("minimal-stripe"),[h,m]=_.useState({}),[p,f]=_.useState(!1),y=_.useRef(null),[v,g]=_.useState(780),b=_.useRef(null),j=V=>{if(b.current&&(b.current.disconnect(),b.current=null),!V)return;const G=()=>{const H=V.clientWidth;H>0&&g(Math.min(780,H-16))};G();const $=new ResizeObserver(G);$.observe(V),b.current=$};_.useEffect(()=>()=>{var V;(V=b.current)==null||V.disconnect()},[]);const S=_.useRef(null),C=V=>{if(!V)return;const G=[];Array.from(V).forEach($=>{$.type.startsWith("image/")&&G.push({id:crypto.randomUUID(),url:URL.createObjectURL($),file:$,name:$.name})}),l($=>[...$,...G])},E=V=>{l(G=>{const $=G.find(H=>H.id===V);return $&&URL.revokeObjectURL($.url),G.filter(H=>H.id!==V)}),c(0)},P=typeof navigator<"u"&&/iPad|iPhone|iPod/.test(navigator.userAgent),M=V=>{var ne;const[G,$]=V.split(","),H=((ne=G.match(/:(.*?);/))==null?void 0:ne[1])??"image/jpeg",Y=atob($),Z=new Uint8Array(Y.length);for(let ce=0;ce{var V;if(S.current){f(!0);try{const G=S.current,$=G.toDataURL({pixelRatio:1/(G.scaleX()||1),mimeType:"image/jpeg",quality:.95}),Y=`${((V=i[o])==null?void 0:V.name.replace(/\.[^.]+$/,""))||"branded"}-branded.jpg`,Z=M($),ne=URL.createObjectURL(Z);if(P)window.open(ne,"_blank")||(window.location.href=ne),se.success('Long-press the image and tap "Save to Photos"');else{const ce=document.createElement("a");ce.href=ne,ce.download=Y,document.body.appendChild(ce),ce.click(),ce.remove(),se.success("Image exported")}setTimeout(()=>URL.revokeObjectURL(ne),6e4)}catch(G){se.error(G.message||"Export failed")}finally{f(!1)}}},D=async()=>{if(i.length){f(!0);try{const V=new Vqt,G=i.length,$=o;for(let Z=0;ZsetTimeout(ae,600)),!S.current)continue;const ne=S.current,ie=ne.toDataURL({pixelRatio:1/(ne.scaleX()||1),mimeType:"image/jpeg",quality:.95}).split(",")[1],te=i[Z].name.replace(/\.[^.]+$/,"")||`image-${Z+1}`;V.file(`${te}-branded.jpg`,ie,{base64:!0})}c($);const H=await V.generateAsync({type:"blob"}),Y=document.createElement("a");Y.href=URL.createObjectURL(H),Y.download=`branded-images-${Date.now()}.zip`,Y.click(),URL.revokeObjectURL(Y.href),se.success(`${G} images exported`)}catch(V){se.error(V.message||"Batch export failed")}finally{f(!1)}}},O=i[o];return e.jsx(zs,{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(ir,{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(B,{variant:"outline",asChild:!0,className:"w-full sm:w-auto",children:e.jsxs(ir,{to:"/marketing-studio/brand-kit",children:[e.jsx(Xc,{className:"h-4 w-4 mr-1"})," Brand Kit"]})})]}),!a&&e.jsx(ve,{className:"border-dashed border-amber-500/50 bg-amber-500/5",children:e.jsxs(Me,{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(B,{asChild:!0,className:"w-full sm:w-auto",children:e.jsx(ir,{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(ve,{className:"overflow-hidden",children:e.jsxs(Me,{className:"p-4",children:[O?e.jsx("div",{ref:j,className:"flex justify-center bg-muted/30 rounded p-2 overflow-hidden",children:e.jsx(Trn,{imageUrl:O.url,preset:a,barStyleId:d,overrides:h,maxDisplayWidth:v,stageRef:S})}):e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-12 text-center space-y-3 cursor-pointer hover:bg-muted/30 transition-colors",onClick:()=>{var V;return(V=y.current)==null?void 0:V.click()},onDragOver:V=>V.preventDefault(),onDrop:V=>{V.preventDefault(),C(V.dataTransfer.files)},children:[e.jsx(hc,{className:"h-12 w-12 mx-auto text-muted-foreground/60"}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-medium",children:"Drop images here or click to browse"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Add up to 50 photos at once. We'll batch-brand them all."})]}),e.jsxs(B,{type:"button",children:[e.jsx(Oa,{className:"h-4 w-4 mr-1"})," Choose images"]})]}),e.jsx("input",{ref:y,type:"file",accept:"image/*",multiple:!0,hidden:!0,onChange:V=>C(V.target.files)})]})}),i.length>0&&e.jsx(ve,{className:"overflow-hidden",children:e.jsx(Me,{className:"p-3",children:e.jsxs("div",{className:"flex gap-2 overflow-x-auto py-1",children:[i.map((V,G)=>e.jsxs("div",{className:"relative group flex-shrink-0",children:[e.jsx("button",{onClick:()=>c(G),className:`block h-16 w-16 rounded overflow-hidden border-2 transition-all ${G===o?"border-primary":"border-transparent hover:border-muted-foreground/30"}`,children:e.jsx("img",{src:V.url,alt:"",className:"h-full w-full object-cover"})}),e.jsx("button",{onClick:()=>E(V.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(Qn,{className:"h-3 w-3"})})]},V.id)),e.jsx("button",{onClick:()=>{var V;return(V=y.current)==null?void 0:V.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(rn,{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(B,{variant:"outline",onClick:()=>{i.forEach(V=>URL.revokeObjectURL(V.url)),l([])},children:"Clear all"}),e.jsxs(B,{onClick:I,disabled:p||!O,children:[p?e.jsx(Ct,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(li,{className:"h-4 w-4 mr-1"}),"Download this image"]}),i.length>1&&e.jsxs(B,{onClick:D,disabled:p,children:[p?e.jsx(Ct,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(li,{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(ve,{className:"overflow-hidden",children:[e.jsx(bt,{className:"pb-2",children:e.jsx(St,{className:"text-base",children:"Brand preset"})}),e.jsx(Me,{children:e.jsxs(is,{value:(a==null?void 0:a.id)??"",onValueChange:r,children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Choose preset"})}),e.jsx(as,{children:s==null?void 0:s.map(V=>e.jsxs(He,{value:V.id,children:[V.name," ",V.is_default?"(default)":""]},V.id))})]})})]}),e.jsxs(ve,{className:"overflow-hidden",children:[e.jsx(bt,{className:"pb-2",children:e.jsx(St,{className:"text-base",children:"Bar style"})}),e.jsx(Me,{children:e.jsx(ntn,{value:d,onChange:u,mediaType:"image"})})]}),e.jsxs(ve,{className:"overflow-hidden",children:[e.jsx(bt,{className:"pb-2",children:e.jsx(St,{className:"text-base",children:"Tweak this design"})}),e.jsx(Me,{children:e.jsxs(Yr,{defaultValue:"text",children:[e.jsxs(Zr,{className:"grid grid-cols-2 w-full",children:[e.jsx(Ht,{value:"text",children:"Text"}),e.jsx(Ht,{value:"colors",children:"Colors"})]}),e.jsxs(Gt,{value:"text",className:"space-y-3 pt-3",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Display name"}),e.jsx(xe,{value:h.display_name??(a==null?void 0:a.display_name)??"",onChange:V=>m({...h,display_name:V.target.value})})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Phone"}),e.jsx(xe,{value:h.phone??(a==null?void 0:a.phone)??"",onChange:V=>m({...h,phone:V.target.value})})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Email"}),e.jsx(xe,{value:h.email??(a==null?void 0:a.email)??"",onChange:V=>m({...h,email:V.target.value})})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Tagline"}),e.jsx(xe,{value:h.tagline??(a==null?void 0:a.tagline)??"",onChange:V=>m({...h,tagline:V.target.value})})]})]}),e.jsxs(Gt,{value:"colors",className:"space-y-3 pt-3",children:[e.jsxs("div",{children:[e.jsx(J,{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:V=>m({...h,brand_color:V.target.value}),className:"h-10 w-14 rounded border cursor-pointer"}),e.jsx(xe,{value:h.brand_color??(a==null?void 0:a.brand_color)??"#0f172a",onChange:V=>m({...h,brand_color:V.target.value})})]})]}),e.jsxs("div",{children:[e.jsx(J,{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:V=>m({...h,accent_color:V.target.value}),className:"h-10 w-14 rounded border cursor-pointer"}),e.jsx(xe,{value:h.accent_color??(a==null?void 0:a.accent_color)??"#3b82f6",onChange:V=>m({...h,accent_color:V.target.value})})]})]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>m({}),children:"Reset to preset"})]})]})})]})]})]})]})})}function Lrn(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 Irn=(()=>{let s=0;const t=()=>`0000${(Math.random()*36**4<<0).toString(36)}`.slice(-4);return()=>(s+=1,`u${t()}${s}`)})();function fP(s){const t=[];for(let n=0,r=s.length;nxw||s.height>xw)&&(s.width>xw&&s.height>xw?s.width>s.height?(s.height*=xw/s.width,s.width=xw):(s.width*=xw/s.height,s.height=xw):s.width>xw?(s.height*=xw/s.width,s.width=xw):(s.width*=xw/s.height,s.height=xw))}function kEe(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 zrn(s){return Promise.resolve().then(()=>new XMLSerializer().serializeToString(s)).then(encodeURIComponent).then(t=>`data:image/svg+xml;charset=utf-8,${t}`)}async function Brn(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),zrn(a)}const B_=(s,t)=>{if(s instanceof t)return!0;const n=Object.getPrototypeOf(s);return n===null?!1:n.constructor.name===t.name||B_(n,t)};function Urn(s){const t=s.getPropertyValue("content");return`${s.cssText} content: '${t.replace(/'|"/g,"")}';`}function qrn(s,t){return B$t(t).map(n=>{const r=s.getPropertyValue(n),a=s.getPropertyPriority(n);return`${n}: ${r}${a?" !important":""};`}).join(" ")}function $rn(s,t,n,r){const a=`.${s}:${t}`,i=n.cssText?Urn(n):qrn(n,r);return document.createTextNode(`${a}{${i}}`)}function bvt(s,t,n,r){const a=window.getComputedStyle(s,n),i=a.getPropertyValue("content");if(i===""||i==="none")return;const l=Irn();try{t.className=`${t.className} ${l}`}catch{return}const o=document.createElement("style");o.appendChild($rn(l,n,a,r)),t.appendChild(o)}function Vrn(s,t,n){bvt(s,t,":before",n),bvt(s,t,":after",n)}const _vt="application/font-woff",wvt="image/jpeg",Hrn={woff:_vt,woff2:_vt,ttf:"application/font-truetype",eot:"application/vnd.ms-fontobject",png:"image/png",jpg:wvt,jpeg:wvt,gif:"image/gif",tiff:"image/tiff",svg:"image/svg+xml",webp:"image/webp"};function Grn(s){const t=/\.([^./]*?)$/g.exec(s);return t?t[1]:""}function Ltt(s){const t=Grn(s).toLowerCase();return Hrn[t]||""}function Wrn(s){return s.split(/,/)[1]}function CHe(s){return s.search(/^(data:)/)!==-1}function Krn(s,t){return`data:${t};base64,${s}`}async function q$t(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 r9e={};function Yrn(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 Itt(s,t,n){const r=Yrn(s,t,n.includeQueryParams);if(r9e[r]!=null)return r9e[r];n.cacheBust&&(s+=(/\?/.test(s)?"&":"?")+new Date().getTime());let a;try{const i=await q$t(s,n.fetchRequestInit,({res:l,result:o})=>(t||(t=l.headers.get("Content-Type")||""),Wrn(o)));a=Krn(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 r9e[r]=a,a}async function Zrn(s){const t=s.toDataURL();return t==="data:,"?s.cloneNode(!1):kEe(t)}async function Xrn(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 kEe(o)}const n=s.poster,r=Ltt(n),a=await Itt(n,r,t);return kEe(a)}async function Qrn(s,t){var n;try{if(!((n=s==null?void 0:s.contentDocument)===null||n===void 0)&&n.body)return await HLe(s.contentDocument.body,t,!0)}catch{}return s.cloneNode(!1)}async function Jrn(s,t){return B_(s,HTMLCanvasElement)?Zrn(s):B_(s,HTMLVideoElement)?Xrn(s,t):B_(s,HTMLIFrameElement)?Qrn(s,t):s.cloneNode($$t(s))}const ean=s=>s.tagName!=null&&s.tagName.toUpperCase()==="SLOT",$$t=s=>s.tagName!=null&&s.tagName.toUpperCase()==="SVG";async function tan(s,t,n){var r,a;if($$t(t))return t;let i=[];return ean(s)&&s.assignedNodes?i=fP(s.assignedNodes()):B_(s,HTMLIFrameElement)&&(!((r=s.contentDocument)===null||r===void 0)&&r.body)?i=fP(s.contentDocument.body.childNodes):i=fP(((a=s.shadowRoot)!==null&&a!==void 0?a:s).childNodes),i.length===0||B_(s,HTMLVideoElement)||await i.reduce((l,o)=>l.then(()=>HLe(o,n)).then(c=>{c&&t.appendChild(c)}),Promise.resolve()),t}function san(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):B$t(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`),B_(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 nan(s,t){B_(s,HTMLTextAreaElement)&&(t.innerHTML=s.value),B_(s,HTMLInputElement)&&t.setAttribute("value",s.value)}function ran(s,t){if(B_(s,HTMLSelectElement)){const n=t,r=Array.from(n.children).find(a=>s.value===a.getAttribute("value"));r&&r.setAttribute("selected","")}}function aan(s,t,n){return B_(t,Element)&&(san(s,t,n),Vrn(s,t,n),nan(s,t),ran(s,t)),t}async function ian(s,t){const n=s.querySelectorAll?s.querySelectorAll("use"):[];if(n.length===0)return s;const r={};for(let i=0;iJrn(r,t)).then(r=>tan(s,r,t)).then(r=>aan(s,r,t)).then(r=>ian(r,t))}const V$t=/url\((['"]?)([^'"]+?)\1\)/g,oan=/url\([^)]+\)\s*format\((["']?)([^"']+)\1\)/g,lan=/src:\s*(?:url\([^)]+\)\s*format\([^)]+\)[,;]\s*)+/g;function can(s){const t=s.replace(/([.*+?^${}()|\[\]\/\\])/g,"\\$1");return new RegExp(`(url\\(['"]?)(${t})(['"]?\\))`,"g")}function dan(s){const t=[];return s.replace(V$t,(n,r,a)=>(t.push(a),n)),t.filter(n=>!CHe(n))}async function uan(s,t,n,r,a){try{const i=n?Lrn(t,n):t,l=Ltt(t);let o;return a||(o=await Itt(i,l,r)),s.replace(can(t),`$1${o}$3`)}catch{}return s}function han(s,{preferredFontFormat:t}){return t?s.replace(lan,n=>{for(;;){const[r,,a]=oan.exec(n)||[];if(!a)return"";if(a===t)return`src: ${r};`}}):s}function H$t(s){return s.search(V$t)!==-1}async function G$t(s,t,n){if(!H$t(s))return s;const r=han(s,n);return dan(r).reduce((i,l)=>i.then(o=>uan(o,l,t,n)),Promise.resolve(r))}async function LB(s,t,n){var r;const a=(r=t.style)===null||r===void 0?void 0:r.getPropertyValue(s);if(a){const i=await G$t(a,null,n);return t.style.setProperty(s,i,t.style.getPropertyPriority(s)),!0}return!1}async function man(s,t){await LB("background",s,t)||await LB("background-image",s,t),await LB("mask",s,t)||await LB("-webkit-mask",s,t)||await LB("mask-image",s,t)||await LB("-webkit-mask-image",s,t)}async function pan(s,t){const n=B_(s,HTMLImageElement);if(!(n&&!CHe(s.src))&&!(B_(s,SVGImageElement)&&!CHe(s.href.baseVal)))return;const r=n?s.src:s.href.baseVal,a=await Itt(r,Ltt(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 fan(s,t){const r=fP(s.childNodes).map(a=>W$t(a,t));await Promise.all(r).then(()=>s)}async function W$t(s,t){B_(s,Element)&&(await man(s,t),await pan(s,t),await fan(s,t))}function xan(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 jvt={};async function Nvt(s){let t=jvt[s];if(t!=null)return t;const r=await(await fetch(s)).text();return t={url:s,cssText:r},jvt[s]=t,t}async function kvt(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),q$t(o,t.fetchRequestInit,({result:c})=>(n=n.replace(l,`url(${c})`),[l,c]))});return Promise.all(i).then(()=>n)}function Svt(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 gan(s,t){const n=[],r=[];return s.forEach(a=>{if("cssRules"in a)try{fP(a.cssRules||[]).forEach((i,l)=>{if(i.type===CSSRule.IMPORT_RULE){let o=l+1;const c=i.href,d=Nvt(c).then(u=>kvt(u,t)).then(u=>Svt(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(Nvt(a.href).then(o=>kvt(o,t)).then(o=>Svt(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{fP(a.cssRules||[]).forEach(i=>{n.push(i)})}catch(i){console.error(`Error while reading CSS rules from ${a.href}`,i)}}),n))}function yan(s){return s.filter(t=>t.type===CSSRule.FONT_FACE_RULE).filter(t=>H$t(t.style.getPropertyValue("src")))}async function van(s,t){if(s.ownerDocument==null)throw new Error("Provided element is not within a Document");const n=fP(s.ownerDocument.styleSheets),r=await gan(n,t);return yan(r)}function K$t(s){return s.trim().replace(/["']/g,"")}function ban(s){const t=new Set;function n(r){(r.style.fontFamily||getComputedStyle(r).fontFamily).split(",").forEach(i=>{t.add(K$t(i))}),Array.from(r.children).forEach(i=>{i instanceof HTMLElement&&n(i)})}return n(s),t}async function _an(s,t){const n=await van(s,t),r=ban(s);return(await Promise.all(n.filter(i=>r.has(K$t(i.style.fontFamily))).map(i=>{const l=i.parentStyleSheet?i.parentStyleSheet.href:null;return G$t(i.cssText,l,t)}))).join(` `)}async function wan(s,t){const n=t.fontEmbedCSS!=null?t.fontEmbedCSS:t.skipFonts?null:await _an(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 Y$t(s,t={}){const{width:n,height:r}=U$t(s,t),a=await HLe(s,t,!0);return await wan(a,t),await W$t(a,t),xan(a,t),await Brn(a,n,r)}async function Z$t(s,t={}){const{width:n,height:r}=U$t(s,t),a=await Y$t(s,t),i=await kEe(a),l=document.createElement("canvas"),o=l.getContext("2d"),c=t.pixelRatio||Frn(),d=t.canvasWidth||n,u=t.canvasHeight||r;return l.width=d*c,l.height=u*c,t.skipAutoScale||Orn(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 $H(s,t={}){return(await Z$t(s,t)).toDataURL()}const X$t=Object.freeze(Object.defineProperty({__proto__:null,toCanvas:Z$t,toPng:$H,toSvg:Y$t},Symbol.toStringTag,{value:"Module"})),VH=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),GLe={"just-listed":"JUST LISTED","just-sold":"JUST SOLD","open-house":"OPEN HOUSE","price-drop":"PRICE DROP"},NM={"instagram-square":{width:1080,height:1080},"instagram-story":{width:1080,height:1920},"facebook-post":{width:1200,height:630}},jan=({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})]})]}),Dtt=Dt.forwardRef(({listing:s,postType:t,format:n,branding:r,selectedPhotoIndex:a},i)=>{var h;const l=n==="instagram-story"?{w:1080,h:1920}:n==="facebook-post"?{w:1200,h:630}:{w:1080,h:1080},o=400/l.w,c=(h=s.photos)==null?void 0:h[a],d=GLe[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:VH(s.price)}),t==="just-sold"&&s.soldPrice&&e.jsxs("div",{style:{fontSize:l.w*.028,color:"#C9A84C",marginBottom:l.w*.01},children:["Sold for ",VH(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(jan,{branding:r,dim:l})]})]})]})});Dtt.displayName="LuxuryDarkTemplate";const Nan=({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})]})]}),Rtt=Dt.forwardRef(({listing:s,postType:t,format:n,branding:r,selectedPhotoIndex:a},i)=>{var p;const l=n==="instagram-story"?{w:1080,h:1920}:n==="facebook-post"?{w:1200,h:630}:{w:1080,h:1080},o=400/l.w,c=(p=s.photos)==null?void 0:p[a],d=GLe[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:VH(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(Nan,{branding:r,dim:l,accentColor:m})]})]})});Rtt.displayName="ModernCleanTemplate";const kan=({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})]})]}),Ftt=Dt.forwardRef(({listing:s,postType:t,format:n,branding:r,selectedPhotoIndex:a},i)=>{var m;const l=n==="instagram-story"?{w:1080,h:1920}:n==="facebook-post"?{w:1200,h:630}:{w:1080,h:1080},o=400/l.w,c=(m=s.photos)==null?void 0:m[a],d=GLe[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:VH(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(kan,{branding:r,dim:l})]})]})]})});Ftt.displayName="BoldColorfulTemplate";const San=({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})]})]}),Ott=Dt.forwardRef(({listing:s,postType:t,format:n,branding:r,selectedPhotoIndex:a},i)=>{var h;const l=n==="instagram-story"?{w:1080,h:1920}:n==="facebook-post"?{w:1200,h:630}:{w:1080,h:1080},o=400/l.w,c=(h=s.photos)==null?void 0:h[a],d=GLe[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:VH(s.price)}),t==="just-sold"&&s.soldPrice&&e.jsxs("div",{style:{fontSize:l.w*.02,color:"#8B7355",marginBottom:l.w*.01},children:["Sold: ",VH(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(San,{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"}})]})]})})});Ott.displayName="EditorialTemplate";const Can=[{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:"📉"}],Cvt=[{value:"instagram-square",label:"IG Post",dimensions:"1080×1080",icon:e.jsx(Im,{className:"h-4 w-4"})},{value:"instagram-story",label:"IG Story",dimensions:"1080×1920",icon:e.jsx(Im,{className:"h-4 w-4"})},{value:"facebook-post",label:"Facebook",dimensions:"1200×630",icon:e.jsx(tf,{className:"h-4 w-4"})}],Aan=[{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:"📰"}],Avt={"luxury-dark":Dtt,"modern-clean":Rtt,"bold-colorful":Ftt,editorial:Ott},a9e=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s);function Ean(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;oCe.is_default))??(s==null?void 0:s[0])??null,[n,r]=_.useState(void 0),a=(s==null?void 0:s.find(Ce=>Ce.id===n))??t,i=ha(),[l,o]=_.useState("mine"),[c,d]=_.useState(""),[u,h]=_.useState("address"),[m,p]=_.useState(!1),[f,y]=_.useState([]),[v,g]=_.useState(null),[b,j]=_.useState(0),[S,C]=_.useState("just-listed"),[E,P]=_.useState(["instagram-square"]),[M,I]=_.useState("luxury-dark"),[D,O]=_.useState(!0),[V,G]=_.useState(!1),[$,H]=_.useState([]),[Y,Z]=_.useState("search"),ne=_.useRef({}),{data:ce=[],isLoading:ie}=at({queryKey:["marketing-studio-my-listings",i],enabled:!!i,queryFn:async()=>{const{data:Ce,error:Ae}=await q.from("listings").select("id, property_address, city, state, price, status, bedrooms, bathrooms, square_footage, year_built, property_type, description, created_at, listing_photos(photo_url, sort_order, is_primary)").eq("agent_id",i).order("created_at",{ascending:!1}).limit(60);if(Ae)throw Ae;return(Ce||[]).map(Pe=>{const ze=(Pe.listing_photos||[]).slice().sort((Ze,Se)=>(Se.is_primary?1:0)-(Ze.is_primary?1:0)||(Ze.sort_order??0)-(Se.sort_order??0)).map(Ze=>Ze.photo_url).filter(Boolean),ke=String(Pe.status||"");return{mlsNumber:Pe.id,address:Pe.property_address||"",city:Pe.city||"",state:Pe.state||"",zip:"",price:Number(Pe.price||0),status:ke,bedrooms:Number(Pe.bedrooms||0),bathrooms:Number(Pe.bathrooms||0),sqft:Number(Pe.square_footage||0),lotSize:"",yearBuilt:Pe.year_built??null,propertyType:Pe.property_type||"",description:Pe.description||"",photos:ze,listDate:Pe.created_at,soldDate:ke.toLowerCase().includes("sold")?Pe.created_at:null,soldPrice:null,agent:{name:"",office:""}}})}}),te=_.useMemo(()=>!D||!a?{enabled:!1}:{enabled:!0,agentName:a.display_name||"",brokerage:a.tagline||"",agentPhotoUrl:a.headshot_url||void 0},[D,a]),ae=async()=>{if(c.trim()){p(!0),y([]);try{const{data:Ce,error:Ae}=await q.functions.invoke("repliers-mls-search",{body:{searchType:u,query:c.trim()}});if(Ae)throw Ae;if(Ce!=null&&Ce.error)throw new Error(Ce.error);y((Ce==null?void 0:Ce.listings)||[]),((Ce==null?void 0:Ce.listings)||[]).length===0&&se.info("No listings found. Try a different search.")}catch(Ce){se.error(Ce.message||"Search failed")}finally{p(!1)}}},le=Ce=>{var Ae;g(Ce),j(0),Z("customize"),Ce.soldDate||(Ae=Ce.status)!=null&&Ae.toLowerCase().includes("sold")?C("just-sold"):C("just-listed")},be=Ce=>P(Ae=>Ae.includes(Ce)?Ae.filter(Pe=>Pe!==Ce):[...Ae,Ce]),me=v?{listing:v,postType:S,format:"instagram-square",branding:te,selectedPhotoIndex:b}:null,he=_.useCallback(async()=>{if(!(!v||E.length===0)){G(!0),H([]),Z("generate");try{await new Promise(Ae=>setTimeout(Ae,600));const Ce=[];for(const Ae of E){const Pe=`${M}-${Ae}`,ze=ne.current[Pe];if(!ze)continue;const ke=NM[Ae],Ze=await $H(ze,{width:ke.width,height:ke.height,pixelRatio:1,cacheBust:!0,style:{transform:"none",transformOrigin:"top left"}});Ce.push({format:Ae,url:Ze})}H(Ce),se.success(`Generated ${Ce.length} design${Ce.length>1?"s":""}!`)}catch(Ce){se.error(Ce.message||"Generation failed")}finally{G(!1)}}},[v,E,M]),pe=(Ce,Ae)=>{const Pe=`${((v==null?void 0:v.address)||"listing").replace(/\s+/g,"-")}-${S}-${Ae}.png`;try{const ze=Ean(Ce),ke=URL.createObjectURL(ze);if(Tan)window.open(ke,"_blank"),se.message("Long-press the image to save to Photos");else{const Ze=document.createElement("a");Ze.href=ke,Ze.download=Pe,document.body.appendChild(Ze),Ze.click(),document.body.removeChild(Ze)}setTimeout(()=>URL.revokeObjectURL(ke),6e4)}catch{const ze=document.createElement("a");ze.href=Ce,ze.download=Pe,ze.click()}};return _.useEffect(()=>{!n&&t&&r(t.id)},[t,n]),e.jsx(zs,{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(B,{variant:"ghost",size:"sm",asChild:!0,children:e.jsxs(ir,{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(Oe,{variant:"secondary",className:"mb-2 gap-1",children:[e.jsx(un,{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(J,{className:"text-xs text-muted-foreground",children:"Brand preset"}),e.jsxs(is,{value:n,onValueChange:r,children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Default"})}),e.jsx(as,{children:s.map(Ce=>e.jsxs(He,{value:Ce.id,children:[Ce.name,Ce.is_default?" (default)":""]},Ce.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:()=>Z("search"),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full whitespace-nowrap ${Y==="search"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground"}`,children:[e.jsx(Lr,{className:"h-3.5 w-3.5"})," 1. Find listing"]}),e.jsx(xi,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("button",{onClick:()=>v&&Z("customize"),disabled:!v,className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full whitespace-nowrap ${Y==="customize"?"bg-primary text-primary-foreground":v?"bg-muted text-muted-foreground":"bg-muted text-muted-foreground/50"}`,children:[e.jsx(un,{className:"h-3.5 w-3.5"})," 2. Customize"]}),e.jsx(xi,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("div",{className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full whitespace-nowrap ${Y==="generate"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground/50"}`,children:[e.jsx(li,{className:"h-3.5 w-3.5"})," 3. Download"]})]}),Y==="search"&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(Yr,{value:l,onValueChange:Ce=>o(Ce),children:e.jsxs(Zr,{className:"grid grid-cols-2 w-full sm:w-auto",children:[e.jsxs(Ht,{value:"mine",children:[e.jsx(Jr,{className:"h-4 w-4 mr-1.5"})," My Listings"]}),e.jsxs(Ht,{value:"mls",children:[e.jsx(Lr,{className:"h-4 w-4 mr-1.5"})," MLS Search"]})]})}),l==="mine"&&e.jsx("div",{className:"space-y-3",children:ie?e.jsx(ve,{children:e.jsx(Me,{className:"py-12 flex items-center justify-center",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})})}):ce.length===0?e.jsx(ve,{children:e.jsxs(Me,{className:"py-10 text-center space-y-2",children:[e.jsx(Jr,{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(B,{variant:"outline",size:"sm",asChild:!0,className:"mt-2",children:e.jsx(ir,{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:[ce.length," listing",ce.length!==1?"s":""," from your Listing Exchange"]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:ce.map((Ce,Ae)=>{var Pe;return e.jsx(ve,{className:"cursor-pointer hover:border-primary/50 hover:shadow-md transition-all group overflow-hidden",onClick:()=>le(Ce),children:e.jsx(Me,{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:(Pe=Ce.photos)!=null&&Pe[0]?e.jsx("img",{src:Ce.photos[0],alt:Ce.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(Jr,{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:Ce.price>0?a9e(Ce.price):"—"}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:Ce.address}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[Ce.city,Ce.state?`, ${Ce.state}`:""]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1.5 text-xs text-muted-foreground",children:[Ce.bedrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(q4,{className:"h-3 w-3"})," ",Ce.bedrooms]}),Ce.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(S0,{className:"h-3 w-3"})," ",Ce.bathrooms]}),Ce.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(t7,{className:"h-3 w-3"})," ",Ce.sqft.toLocaleString()]})]}),Ce.status&&e.jsx("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:e.jsx(Oe,{variant:"outline",className:"text-[10px]",children:Ce.status})})]})]})})},Ce.mlsNumber||Ae)})})]})}),l==="mls"&&e.jsxs(e.Fragment,{children:[e.jsxs(ve,{className:"overflow-hidden",children:[e.jsxs(bt,{children:[e.jsxs(St,{className:"flex items-center gap-2 text-base md:text-lg",children:[e.jsx(Lr,{className:"h-5 w-5 text-primary"})," Search MLS"]}),e.jsxs(kn,{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(Me,{className:"space-y-3",children:[e.jsx(Yr,{value:u,onValueChange:Ce=>h(Ce),children:e.jsxs(Zr,{children:[e.jsxs(Ht,{value:"address",children:[e.jsx(Xa,{className:"h-4 w-4 mr-1.5"})," Address"]}),e.jsxs(Ht,{value:"mls",children:[e.jsx(Ep,{className:"h-4 w-4 mr-1.5"})," MLS #"]})]})}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[e.jsx(xe,{value:c,onChange:Ce=>d(Ce.target.value),placeholder:u==="mls"?"Enter MLS number...":"Enter property address...",className:"flex-1",onKeyDown:Ce=>Ce.key==="Enter"&&ae()}),e.jsxs(B,{onClick:ae,disabled:m||!c.trim(),className:"sm:w-auto w-full",children:[m?e.jsx(Ct,{className:"h-4 w-4 animate-spin mr-1.5"}):e.jsx(Lr,{className:"h-4 w-4 mr-1.5"})," Search"]})]})]})]}),f.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h3",{className:"text-sm font-medium text-muted-foreground",children:[f.length," listing",f.length!==1?"s":""," found"]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:f.map((Ce,Ae)=>{var Pe;return e.jsx(ve,{className:"cursor-pointer hover:border-primary/50 hover:shadow-md transition-all group overflow-hidden",onClick:()=>le(Ce),children:e.jsx(Me,{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:(Pe=Ce.photos)!=null&&Pe[0]?e.jsx("img",{src:Ce.photos[0],alt:Ce.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(Jr,{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:a9e(Ce.price)}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:Ce.address}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[Ce.city,", ",Ce.state," ",Ce.zip]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1.5 text-xs text-muted-foreground",children:[Ce.bedrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(q4,{className:"h-3 w-3"})," ",Ce.bedrooms]}),Ce.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(S0,{className:"h-3 w-3"})," ",Ce.bathrooms]}),Ce.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(t7,{className:"h-3 w-3"})," ",Ce.sqft.toLocaleString()]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:[Ce.mlsNumber&&e.jsx(Oe,{variant:"outline",className:"text-[10px]",children:Ce.mlsNumber}),Ce.status&&e.jsx(Oe,{variant:"outline",className:"text-[10px]",children:Ce.status})]})]})]})})},Ce.mlsNumber||Ae)})})]})]})]}),Y==="customize"&&v&&me&&e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4 md:gap-6",children:[e.jsxs(ve,{className:"lg:col-span-1 overflow-hidden min-w-0",children:[e.jsx(bt,{className:"pb-3",children:e.jsx(St,{className:"text-base",children:"Selected listing"})}),e.jsxs(Me,{className:"space-y-3",children:[v.photos.length>0&&e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"aspect-[4/3] rounded-lg overflow-hidden bg-muted",children:e.jsx("img",{src:v.photos[b],alt:"",className:"w-full h-full object-cover"})}),v.photos.length>1&&e.jsxs("div",{className:"flex items-center justify-between mt-2",children:[e.jsx(B,{variant:"outline",size:"icon",className:"h-7 w-7",onClick:()=>j(Ce=>Math.max(0,Ce-1)),disabled:b===0,children:e.jsx($c,{className:"h-4 w-4"})}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[b+1," of ",v.photos.length]}),e.jsx(B,{variant:"outline",size:"icon",className:"h-7 w-7",onClick:()=>j(Ce=>Math.min(v.photos.length-1,Ce+1)),disabled:b===v.photos.length-1,children:e.jsx(xi,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-bold text-lg",children:a9e(v.price)}),e.jsx("p",{className:"text-sm text-muted-foreground",children:v.address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[v.city,", ",v.state," ",v.zip]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 text-center",children:[v.bedrooms>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:v.bedrooms}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Beds"})]}),v.bathrooms>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:v.bathrooms}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Baths"})]}),v.sqft>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:v.sqft.toLocaleString()}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Sq Ft"})]})]}),e.jsxs(B,{variant:"outline",size:"sm",className:"w-full",onClick:()=>{Z("search"),g(null)},children:[e.jsx(Tx,{className:"h-3.5 w-3.5 mr-1.5"})," Choose different listing"]})]})]}),e.jsxs(ve,{className:"lg:col-span-2 overflow-hidden min-w-0",children:[e.jsxs(bt,{children:[e.jsxs(St,{className:"flex items-center gap-2 text-base",children:[e.jsx(un,{className:"h-5 w-5 text-primary"})," Customize"]}),e.jsx(kn,{children:"Pick a template, post type, and output format."})]}),e.jsxs(Me,{className:"space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(J,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Xc,{className:"h-4 w-4"})," Template style"]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:Aan.map(Ce=>e.jsxs("button",{onClick:()=>I(Ce.value),className:`flex flex-col items-center gap-1 px-2 py-3 rounded-lg border-2 transition-all text-center ${M===Ce.value?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("span",{className:"text-2xl",children:Ce.preview}),e.jsx("span",{className:"text-sm font-medium",children:Ce.label}),e.jsx("span",{className:"text-[10px] text-muted-foreground leading-tight",children:Ce.description})]},Ce.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{className:"text-sm font-medium",children:"Post type"}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:Can.map(Ce=>e.jsxs("button",{onClick:()=>C(Ce.value),className:`flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg border-2 transition-all text-sm font-medium ${S===Ce.value?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("span",{className:"text-lg",children:Ce.icon})," ",e.jsx("span",{className:"truncate",children:Ce.label})]},Ce.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{className:"text-sm font-medium",children:"Output formats"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-2",children:Cvt.map(Ce=>e.jsxs("button",{onClick:()=>be(Ce.value),className:`flex items-center gap-2 px-3 py-2.5 rounded-lg border-2 transition-all text-sm ${E.includes(Ce.value)?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[Ce.icon,e.jsxs("div",{className:"text-left min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:Ce.label}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:Ce.dimensions})]})]},Ce.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(J,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Fo,{className:"h-4 w-4"})," Show my branding"]}),e.jsx(fn,{checked:D,onCheckedChange:O})]}),D&&!a&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["No brand preset yet. ",e.jsx(ir,{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(J,{className:"text-sm font-medium",children:"Preview"}),e.jsx("div",{className:"bg-muted/30 rounded-lg p-3 md:p-4 flex justify-center overflow-hidden",children:e.jsx("div",{style:{width:360,maxWidth:"100%",height:360*(NM[E[0]||"instagram-square"].height/NM[E[0]||"instagram-square"].width)},children:(()=>{const Ce=Avt[M],Ae=E[0]||"instagram-square";return e.jsx(Ce,{...me,format:Ae})})()})})]}),e.jsx(B,{onClick:he,disabled:E.length===0||V,size:"lg",className:"w-full gap-2",children:V?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"h-5 w-5 animate-spin"})," Generating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(un,{className:"h-5 w-5"})," Generate ",E.length," design",E.length>1?"s":""]})})]})]})]}),Y==="generate"&&e.jsxs("div",{className:"space-y-4",children:[V&&e.jsx(ve,{children:e.jsxs(Me,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx(Ct,{className:"h-12 w-12 animate-spin text-primary mb-3"}),e.jsx("p",{className:"text-base font-medium",children:"Rendering your designs..."}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"High-resolution PNGs, no AI credits used."})]})}),$.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(B,{variant:"outline",size:"sm",onClick:()=>Z("customize"),children:[e.jsx(Tx,{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:$.map((Ce,Ae)=>{const Pe=Cvt.find(ze=>ze.value===Ce.format);return e.jsxs(ve,{className:"overflow-hidden",children:[e.jsx("div",{className:"bg-muted/30 p-1",children:e.jsx("img",{src:Ce.url,alt:"",className:"w-full rounded"})}),e.jsxs(Me,{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:[Pe==null?void 0:Pe.icon,e.jsx("span",{className:"text-sm font-medium",children:Pe==null?void 0:Pe.label})]}),e.jsx(Oe,{variant:"outline",className:"text-[10px]",children:Pe==null?void 0:Pe.dimensions})]}),e.jsxs(B,{size:"sm",className:"w-full gap-1.5",onClick:()=>pe(Ce.url,Ce.format),children:[e.jsx(li,{className:"h-3.5 w-3.5"})," Download"]})]})]},Ae)})})]})]}),Y==="generate"&&v&&me&&e.jsx("div",{style:{position:"fixed",left:"-99999px",top:0,pointerEvents:"none"},"aria-hidden":!0,children:E.map(Ce=>{const Ae=Avt[M],Pe=NM[Ce];return e.jsx("div",{style:{width:Pe.width,height:Pe.height},children:e.jsx(Ae,{ref:ze=>{ne.current[`${M}-${Ce}`]=ze},...me,format:Ce})},`${M}-${Ce}`)})})]})})}var Q$t="Toggle",ztt=_.forwardRef((s,t)=>{const{pressed:n,defaultPressed:r,onPressedChange:a,...i}=s,[l,o]=Ug({prop:n,onChange:a,defaultProp:r??!1,caller:Q$t});return e.jsx(ii.button,{type:"button","aria-pressed":l,"data-state":l?"on":"off","data-disabled":s.disabled?"":void 0,...i,ref:t,onClick:wa(s.onClick,()=>{s.disabled||o(!l)})})});ztt.displayName=Q$t;var J$t=ztt,SL="ToggleGroup",[eVt,m_r]=af(SL,[iL]),tVt=iL(),Btt=Dt.forwardRef((s,t)=>{const{type:n,...r}=s;if(n==="single"){const a=r;return e.jsx(Pan,{...a,ref:t})}if(n==="multiple"){const a=r;return e.jsx(Lan,{...a,ref:t})}throw new Error(`Missing prop \`type\` expected on \`${SL}\``)});Btt.displayName=SL;var[sVt,nVt]=eVt(SL),Pan=Dt.forwardRef((s,t)=>{const{value:n,defaultValue:r,onValueChange:a=()=>{},...i}=s,[l,o]=Ug({prop:n,defaultProp:r??"",onChange:a,caller:SL});return e.jsx(sVt,{scope:s.__scopeToggleGroup,type:"single",value:Dt.useMemo(()=>l?[l]:[],[l]),onItemActivate:o,onItemDeactivate:Dt.useCallback(()=>o(""),[o]),children:e.jsx(rVt,{...i,ref:t})})}),Lan=Dt.forwardRef((s,t)=>{const{value:n,defaultValue:r,onValueChange:a=()=>{},...i}=s,[l,o]=Ug({prop:n,defaultProp:r??[],onChange:a,caller:SL}),c=Dt.useCallback(u=>o((h=[])=>[...h,u]),[o]),d=Dt.useCallback(u=>o((h=[])=>h.filter(m=>m!==u)),[o]);return e.jsx(sVt,{scope:s.__scopeToggleGroup,type:"multiple",value:l,onItemActivate:c,onItemDeactivate:d,children:e.jsx(rVt,{...i,ref:t})})});Btt.displayName=SL;var[Ian,Dan]=eVt(SL),rVt=Dt.forwardRef((s,t)=>{const{__scopeToggleGroup:n,disabled:r=!1,rovingFocus:a=!0,orientation:i,dir:l,loop:o=!0,...c}=s,d=tVt(n),u=DE(l),h={role:"group",dir:u,...c};return e.jsx(Ian,{scope:n,rovingFocus:a,disabled:r,children:a?e.jsx(WMe,{asChild:!0,...d,orientation:i,dir:u,loop:o,children:e.jsx(ii.div,{...h,ref:t})}):e.jsx(ii.div,{...h,ref:t})})}),SEe="ToggleGroupItem",aVt=Dt.forwardRef((s,t)=>{const n=nVt(SEe,s.__scopeToggleGroup),r=Dan(SEe,s.__scopeToggleGroup),a=tVt(s.__scopeToggleGroup),i=n.value.includes(s.value),l=r.disabled||s.disabled,o={...s,pressed:i,disabled:l},c=Dt.useRef(null);return r.rovingFocus?e.jsx(KMe,{asChild:!0,...a,focusable:!l,active:i,ref:c,children:e.jsx(Evt,{...o,ref:t})}):e.jsx(Evt,{...o,ref:t})});aVt.displayName=SEe;var Evt=Dt.forwardRef((s,t)=>{const{__scopeToggleGroup:n,value:r,...a}=s,i=nVt(SEe,n),l={role:"radio","aria-checked":s.pressed,"aria-pressed":void 0},o=i.type==="single"?l:void 0;return e.jsx(ztt,{...o,...a,ref:t,onPressedChange:c=>{c?i.onItemActivate(r):i.onItemDeactivate(r)}})}),iVt=Btt,oVt=aVt;const lVt=F9("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"}}),Ran=_.forwardRef(({className:s,variant:t,size:n,...r},a)=>e.jsx(J$t,{ref:a,className:At(lVt({variant:t,size:n,className:s})),...r}));Ran.displayName=J$t.displayName;const cVt=_.createContext({size:"default",variant:"default"}),T$=_.forwardRef(({className:s,variant:t,size:n,children:r,...a},i)=>e.jsx(iVt,{ref:i,className:At("flex items-center justify-center gap-1",s),...a,children:e.jsx(cVt.Provider,{value:{variant:t,size:n},children:r})}));T$.displayName=iVt.displayName;const N7=_.forwardRef(({className:s,children:t,variant:n,size:r,...a},i)=>{const l=_.useContext(cVt);return e.jsx(oVt,{ref:i,className:At(lVt({variant:l.variant||n,size:l.size||r}),s),...a,children:t})});N7.displayName=oVt.displayName;const Fan=[{id:"meet",label:"Meet Your Agent",icon:Fo,description:"Polished intro card with your headshot, story, and contact."},{id:"testimonial",label:"Testimonial",icon:pS,description:"Turn a Zillow / Google review into a branded graphic."},{id:"milestone",label:"Milestone",icon:wl,description:"Celebrate homes sold, awards, anniversaries, achievements."},{id:"tip",label:"Pro Tip",icon:mS,description:"Drop a value-bomb tip — buyer/seller advice, market insight."},{id:"quote",label:"Quote / Mantra",icon:wh,description:"Personal philosophy, mantra, or rallying call."}],i9e={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"}},Oan=[{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."}],Tvt={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 zan(){const{data:s}=Yen(),{data:t}=bae(),[n,r]=_.useState(void 0),a=_.useMemo(()=>(t==null?void 0:t.find(f=>f.id===n))??s??null,[t,n,s]),[i,l]=_.useState({template:"meet",style:"editorial",aspect:"portrait",rating:5,...Tvt.meet}),o=f=>l(y=>({...y,...f})),c=f=>l(y=>({...y,template:f,...Tvt[f]})),d=_.useRef(null),[u,h]=_.useState(!1),m=async()=>{if(!d.current)return;h(!0);const f=d.current,y=f.style.transform;try{f.style.transform="none",await new Promise(b=>requestAnimationFrame(()=>b(null)));const v=await $H(f,{cacheBust:!0,pixelRatio:2,width:f.offsetWidth,height:f.offsetHeight,backgroundColor:"#ffffff"}),g=document.createElement("a");g.href=v,g.download=`personal-branding-${i.template}-${Date.now()}.png`,document.body.appendChild(g),g.click(),g.remove(),se.success("Downloaded to your device")}catch(v){se.error((v==null?void 0:v.message)||"Export failed")}finally{f.style.transform=y,h(!1)}},p=i9e[i.aspect];return e.jsx(zs,{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(ir,{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(Oe,{variant:"secondary",className:"gap-1",children:[e.jsx(un,{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(B,{variant:"outline",asChild:!0,children:e.jsxs(ir,{to:"/marketing-studio/brand-kit",children:[e.jsx(Xc,{className:"h-4 w-4 mr-1"})," Brand Kit"]})}),e.jsxs(B,{onClick:m,disabled:u,children:[e.jsx(li,{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(ve,{children:e.jsxs(Me,{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Template"}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:Fan.map(f=>{const y=f.icon,v=i.template===f.id;return e.jsxs("button",{onClick:()=>c(f.id),className:`text-left rounded-lg border p-3 transition-all ${v?"border-primary bg-primary/5 ring-2 ring-primary/30":"border-border hover:border-primary/50"}`,children:[e.jsx(y,{className:"h-4 w-4 mb-1"}),e.jsx("div",{className:"text-xs font-semibold",children:f.label})]},f.id)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Style"}),e.jsx(T$,{type:"single",value:i.style,onValueChange:f=>f&&o({style:f}),className:"grid grid-cols-2 gap-1",children:Oan.map(f=>e.jsx(N7,{value:f.id,className:"text-xs h-9",children:f.label},f.id))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Format"}),e.jsx(T$,{type:"single",value:i.aspect,onValueChange:f=>f&&o({aspect:f}),className:"grid grid-cols-3 gap-1",children:Object.keys(i9e).map(f=>e.jsx(N7,{value:f,className:"text-xs h-9",children:i9e[f].label},f))})]}),t&&t.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Brand preset"}),e.jsxs(is,{value:n??(s==null?void 0:s.id)??"",onValueChange:r,children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Choose preset"})}),e.jsx(as,{children:t.map(f=>e.jsx(He,{value:f.id,children:f.name},f.id))})]})]})]})}),e.jsx(ve,{children:e.jsxs(Me,{className:"p-4 space-y-3",children:[e.jsx(J,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Content"}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{htmlFor:"headline",className:"text-xs",children:"Headline"}),e.jsx(Ms,{id:"headline",value:i.headline,onChange:f=>o({headline:f.target.value}),rows:2})]}),i.template!=="quote"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{htmlFor:"subline",className:"text-xs",children:"Subline"}),e.jsx(xe,{id:"subline",value:i.subline,onChange:f=>o({subline:f.target.value})})]}),i.template!=="quote"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{htmlFor:"body",className:"text-xs",children:"Body"}),e.jsx(Ms,{id:"body",value:i.body,onChange:f=>o({body:f.target.value}),rows:4})]}),(i.template==="testimonial"||i.template==="quote")&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{htmlFor:"attribution",className:"text-xs",children:"Attribution"}),e.jsx(xe,{id:"attribution",value:i.attribution,onChange:f=>o({attribution:f.target.value}),placeholder:"— Client name / Source"})]}),i.template==="testimonial"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs",children:"Rating"}),e.jsx(T$,{type:"single",value:String(i.rating),onValueChange:f=>f&&o({rating:Number(f)}),className:"grid grid-cols-5 gap-1",children:[1,2,3,4,5].map(f=>e.jsxs(N7,{value:String(f),className:"text-xs h-9",children:[f,"★"]},f))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{htmlFor:"badge",className:"text-xs",children:"Eyebrow tag"}),e.jsx(xe,{id:"badge",value:i.badgeText,onChange:f=>o({badgeText:f.target.value})})]})]})})]}),e.jsx(Ban,{aspect:p,canvasRef:d,children:e.jsx(Uan,{form:i,preset:a,width:p.w,height:p.h})})]})]})})}function Ban({aspect:s,canvasRef:t,children:n}){const r=_.useRef(null),[a,i]=_.useState(.5);return _.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 Uan({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(qan,{...p}):s.style==="bold"?e.jsx($an,{...p}):s.style==="luxury"?e.jsx(Han,{...p}):e.jsx(Van,{...p})}function dVt({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 WLe({rating:s,color:t}){return e.jsx("div",{style:{display:"flex",gap:4},children:Array.from({length:5}).map((n,r)=>e.jsx(Da,{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(WLe,{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(dVt,{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 $an(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%, ${Gan(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(WLe,{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(dVt,{name:l,phone:o,email:c,website:d,color:"#fff"})]})]})}function Van(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(WLe,{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 Han(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(WLe,{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 Gan(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 Wan=()=>{const{swagId:s}=Li(),{user:t}=hs(),{toast:n}=vi(),r=Bt(),{trackEngagement:a}=bW(),[i,l]=_.useState(""),{data:o,isLoading:c}=at({queryKey:["social-swag-detail",s],queryFn:async()=>{const{data:g,error:b}=await q.from("social_swag").select("*").eq("id",s).single();if(b)throw b;const{data:j}=await q.from("social_swag_links").select("*").eq("swag_id",s).order("sort_order");return{...g,links:j||[]}},enabled:!!s});_.useEffect(()=>{o&&a("social_swag",o.id,o.title,"view")},[o==null?void 0:o.id]);const{data:d=[]}=at({queryKey:["social-swag-likes",s],queryFn:async()=>{const{data:g,error:b}=await q.from("social_swag_likes").select("*").eq("swag_id",s);if(b)throw b;return g},enabled:!!s}),{data:u=[]}=at({queryKey:["social-swag-comments",s],queryFn:async()=>{const{data:g,error:b}=await q.from("social_swag_comments").select("*").eq("swag_id",s).order("created_at",{ascending:!1});if(b)throw b;const j=[...new Set(g.map(E=>E.user_id))],{data:S}=await q.from("profiles").select("id, name").in("id",j),C=new Map((S==null?void 0:S.map(E=>[E.id,E.name]))||[]);return g.map(E=>({...E,user_name:C.get(E.user_id)||"Unknown User"}))},enabled:!!s}),h=mt({mutationFn:async g=>{const{error:b}=await q.from("social_swag_comments").insert({swag_id:s,user_id:t.id,content:g});if(b)throw b},onSuccess:()=>{r.invalidateQueries({queryKey:["social-swag-comments",s]}),l(""),n({title:"Comment added!"})},onError:g=>{n({title:"Error adding comment",description:g.message,variant:"destructive"})}}),m=mt({mutationFn:async g=>{const{error:b}=await q.from("social_swag_comments").delete().eq("id",g);if(b)throw b},onSuccess:()=>{r.invalidateQueries({queryKey:["social-swag-comments",s]}),n({title:"Comment deleted"})}}),p=mt({mutationFn:async()=>{const g=d.find(b=>b.user_id===(t==null?void 0:t.id));if(g){const{error:b}=await q.from("social_swag_likes").delete().eq("id",g.id);if(b)throw b}else{const{error:b}=await q.from("social_swag_likes").insert({swag_id:s,user_id:t.id});if(b)throw b}},onSuccess:()=>{r.invalidateQueries({queryKey:["social-swag-likes",s]})}}),f=d.some(g=>g.user_id===(t==null?void 0:t.id)),y=g=>g.split(" ").map(b=>b[0]).join("").toUpperCase().slice(0,2),v=g=>{g.preventDefault(),!(!i.trim()||!t)&&h.mutate(i.trim())};return c?e.jsx(zs,{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(zs,{title:o.title,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx(B,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(ir,{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(jW,{resourceType:"social_swag",resourceId:o.id,resourceTitle:o.title}),e.jsxs(B,{variant:f?"default":"outline",className:"gap-2 w-fit",onClick:()=>p.mutate(),disabled:!t||p.isPending,children:[e.jsx(Fg,{className:`h-4 w-4 ${f?"fill-current":""}`}),d.length," ",d.length===1?"Like":"Likes"]})]})]}),o.description&&e.jsx("div",{className:"text-muted-foreground prose prose-sm max-w-none dark:prose-invert",dangerouslySetInnerHTML:{__html:o.description}})]}),o.links.length>0&&e.jsx(ve,{children:e.jsxs(Me,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Vc,{className:"h-4 w-4"}),o.links.length===1?"Canva Link":"Canva Links"]}),e.jsx("div",{className:"grid gap-2",children:o.links.map(g=>e.jsxs(B,{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(g.canva_share_link,"_blank")},children:[e.jsx("span",{className:"font-medium",children:g.title}),e.jsx(wr,{className:"h-4 w-4 text-muted-foreground"})]},g.id))})]})}),e.jsx(wc,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(Ou,{className:"h-5 w-5"}),"Comments (",u.length,")"]}),t?e.jsxs("form",{onSubmit:v,className:"flex gap-2",children:[e.jsx(Ms,{placeholder:"Add a comment...",value:i,onChange:g=>l(g.target.value),className:"min-h-[80px] resize-none flex-1"}),e.jsx(B,{type:"submit",size:"icon",className:"h-10 w-10",disabled:!i.trim()||h.isPending,children:e.jsx(Or,{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(ve,{children:e.jsx(Me,{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(g=>e.jsx(ve,{children:e.jsx(Me,{className:"pt-4 pb-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(ja,{className:"h-10 w-10 flex-shrink-0",children:e.jsx(Na,{className:"text-sm",children:y(g.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:g.user_name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:Ed(new Date(g.created_at),{addSuffix:!0})}),g.user_id===(t==null?void 0:t.id)&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>m.mutate(g.id),children:e.jsx(Sn,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:g.content})]})]})})},g.id))})]})]})}):e.jsx(zs,{title:"Social Swag",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Vc,{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(B,{asChild:!0,className:"mt-4",children:e.jsx(ir,{to:"/social-swag",children:"Back to Social Swag"})})]})})},Kan=({categories:s,privateGroups:t,selectedFilter:n,onFilterChange:r,onlineUsers:a})=>{const[i,l]=_.useState(!0),[o,c]=_.useState(!0),[d,u]=_.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(B,{variant:n==="all"?"secondary":"ghost",className:"w-full justify-start",onClick:()=>r("all"),children:[e.jsx(ZM,{className:"h-4 w-4 mr-2"}),"All Posts"]}),e.jsxs(f1,{open:i,onOpenChange:l,children:[e.jsx(x1,{asChild:!0,children:e.jsxs(B,{variant:"ghost",className:"w-full justify-between text-muted-foreground hover:text-foreground",children:[e.jsx("span",{className:"text-xs font-semibold uppercase tracking-wider",children:"Categories"}),i?e.jsx(tl,{className:"h-4 w-4"}):e.jsx(xi,{className:"h-4 w-4"})]})}),e.jsx(g1,{className:"space-y-1 pl-2",children:s.map(m=>e.jsxs(B,{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(f1,{open:o,onOpenChange:c,children:[e.jsx(x1,{asChild:!0,children:e.jsxs(B,{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(ec,{className:"h-3 w-3"}),"Your Groups"]}),o?e.jsx(tl,{className:"h-4 w-4"}):e.jsx(xi,{className:"h-4 w-4"})]})}),e.jsx(g1,{className:"space-y-1 pl-2",children:t.map(m=>e.jsxs(B,{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(f1,{open:d,onOpenChange:u,children:[e.jsx(x1,{asChild:!0,children:e.jsxs(B,{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(In,{className:"h-3 w-3"}),"Online Now",a.length>0&&e.jsx("span",{className:"ml-1 bg-green-500 text-white text-xs rounded-full px-1.5 py-0.5 min-w-[20px] text-center",children:a.length})]}),d?e.jsx(tl,{className:"h-4 w-4"}):e.jsx(xi,{className:"h-4 w-4"})]})}),e.jsx(g1,{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(ja,{className:"h-7 w-7",children:[e.jsx(pi,{src:m.avatarUrl}),e.jsx(Na,{className:"text-xs",children:h(m.name)})]}),e.jsx(Uf,{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))})]})]})})})},Yan=({categories:s,privateGroups:t,selectedFilter:n,onFilterChange:r,onlineUsers:a})=>{const[i,l]=_.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(tu,{children:[e.jsx(su,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:"flex-1 justify-between",children:[e.jsx("span",{className:"truncate",children:c()}),e.jsx(tl,{className:"h-4 w-4 ml-2 shrink-0"})]})}),e.jsxs(Od,{className:"w-56 bg-background border",children:[e.jsxs(ca,{onClick:()=>r("all"),children:[e.jsx(ZM,{className:"h-4 w-4 mr-2"}),"All Posts"]}),e.jsx(M0,{}),e.jsx(PP,{className:"text-xs text-muted-foreground",children:"Categories"}),s.map(d=>e.jsxs(ca,{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(M0,{}),e.jsxs(PP,{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(ec,{className:"h-3 w-3"}),"Your Groups"]}),t.map(d=>e.jsxs(ca,{onClick:()=>r(`group:${d.id}`),children:[e.jsx("span",{className:"mr-2",children:d.icon||"🔒"}),d.name]},d.id))]})]})]}),e.jsxs(qg,{open:i,onOpenChange:l,children:[e.jsx(zre,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"icon",className:"relative",children:[e.jsx(In,{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(hg,{children:[e.jsx(P0,{children:e.jsxs(L0,{className:"flex items-center gap-2",children:[e.jsx(In,{className:"h-5 w-5"}),"Online Now (",a.length,")"]})}),e.jsx(Ji,{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(ja,{className:"h-10 w-10",children:[e.jsx(pi,{src:d.avatarUrl}),e.jsx(Na,{children:o(d.name)})]}),e.jsx(Uf,{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 o9e,KLe="HoverCard",[uVt,p_r]=af(KLe,[_C]),YLe=_C(),[Zan,Utt]=uVt(KLe),hVt=s=>{const{__scopeHoverCard:t,children:n,open:r,defaultOpen:a,onOpenChange:i,openDelay:l=700,closeDelay:o=300}=s,c=YLe(t),d=_.useRef(0),u=_.useRef(0),h=_.useRef(!1),m=_.useRef(!1),[p,f]=Ug({prop:r,defaultProp:a??!1,onChange:i,caller:KLe}),y=_.useCallback(()=>{clearTimeout(u.current),d.current=window.setTimeout(()=>f(!0),l)},[l,f]),v=_.useCallback(()=>{clearTimeout(d.current),!h.current&&!m.current&&(u.current=window.setTimeout(()=>f(!1),o))},[o,f]),g=_.useCallback(()=>f(!1),[f]);return _.useEffect(()=>()=>{clearTimeout(d.current),clearTimeout(u.current)},[]),e.jsx(Zan,{scope:t,open:p,onOpenChange:f,onOpen:y,onClose:v,onDismiss:g,hasSelectionRef:h,isPointerDownOnContentRef:m,children:e.jsx(Are,{...c,children:n})})};hVt.displayName=KLe;var mVt="HoverCardTrigger",pVt=_.forwardRef((s,t)=>{const{__scopeHoverCard:n,...r}=s,a=Utt(mVt,n),i=YLe(n);return e.jsx(tW,{asChild:!0,...i,children:e.jsx(ii.a,{"data-state":a.open?"open":"closed",...r,ref:t,onPointerEnter:wa(s.onPointerEnter,AEe(a.onOpen)),onPointerLeave:wa(s.onPointerLeave,AEe(a.onClose)),onFocus:wa(s.onFocus,a.onOpen),onBlur:wa(s.onBlur,a.onClose),onTouchStart:wa(s.onTouchStart,l=>l.preventDefault())})})});pVt.displayName=mVt;var Xan="HoverCardPortal",[f_r,Qan]=uVt(Xan,{forceMount:void 0}),CEe="HoverCardContent",fVt=_.forwardRef((s,t)=>{const n=Qan(CEe,s.__scopeHoverCard),{forceMount:r=n.forceMount,...a}=s,i=Utt(CEe,s.__scopeHoverCard);return e.jsx(pg,{present:r||i.open,children:e.jsx(Jan,{"data-state":i.open?"open":"closed",...a,onPointerEnter:wa(s.onPointerEnter,AEe(i.onOpen)),onPointerLeave:wa(s.onPointerLeave,AEe(i.onClose)),ref:t})})});fVt.displayName=CEe;var Jan=_.forwardRef((s,t)=>{const{__scopeHoverCard:n,onEscapeKeyDown:r,onPointerDownOutside:a,onFocusOutside:i,onInteractOutside:l,...o}=s,c=Utt(CEe,n),d=YLe(n),u=_.useRef(null),h=Qo(t,u),[m,p]=_.useState(!1);return _.useEffect(()=>{if(m){const f=document.body;return o9e=f.style.userSelect||f.style.webkitUserSelect,f.style.userSelect="none",f.style.webkitUserSelect="none",()=>{f.style.userSelect=o9e,f.style.webkitUserSelect=o9e}}},[m]),_.useEffect(()=>{if(u.current){const f=()=>{p(!1),c.isPointerDownOnContentRef.current=!1,setTimeout(()=>{var v;((v=document.getSelection())==null?void 0:v.toString())!==""&&(c.hasSelectionRef.current=!0)})};return document.addEventListener("pointerup",f),()=>{document.removeEventListener("pointerup",f),c.hasSelectionRef.current=!1,c.isPointerDownOnContentRef.current=!1}}},[c.isPointerDownOnContentRef,c.hasSelectionRef]),_.useEffect(()=>{u.current&&sin(u.current).forEach(y=>y.setAttribute("tabindex","-1"))}),e.jsx(rL,{asChild:!0,disableOutsidePointerEvents:!1,onInteractOutside:l,onEscapeKeyDown:r,onPointerDownOutside:a,onFocusOutside:wa(i,f=>{f.preventDefault()}),onDismiss:c.onDismiss,children:e.jsx(Ere,{...d,...o,onPointerDown:wa(o.onPointerDown,f=>{f.currentTarget.contains(f.target)&&p(!0),c.hasSelectionRef.current=!1,c.isPointerDownOnContentRef.current=!0}),ref:h,style:{...o.style,userSelect:m?"text":void 0,WebkitUserSelect:m?"text":void 0,"--radix-hover-card-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-hover-card-content-available-width":"var(--radix-popper-available-width)","--radix-hover-card-content-available-height":"var(--radix-popper-available-height)","--radix-hover-card-trigger-width":"var(--radix-popper-anchor-width)","--radix-hover-card-trigger-height":"var(--radix-popper-anchor-height)"}})})}),ein="HoverCardArrow",tin=_.forwardRef((s,t)=>{const{__scopeHoverCard:n,...r}=s,a=YLe(n);return e.jsx(Tre,{...a,...r,ref:t})});tin.displayName=ein;function AEe(s){return t=>t.pointerType==="touch"?void 0:s()}function sin(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 nin=hVt,rin=pVt,xVt=fVt;const ain=nin,iin=rin,gVt=_.forwardRef(({className:s,align:t="center",sideOffset:n=4,...r},a)=>e.jsx(xVt,{ref:a,align:t,sideOffset:n,className:At("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}));gVt.displayName=xVt.displayName;const oin=[{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"}],lin=s=>s.split(" ").map(t=>t[0]).join("").toUpperCase().slice(0,2),yVt=({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(ain,{openDelay:200,closeDelay:100,children:[e.jsx(iin,{asChild:!0,children:e.jsx("div",{className:"cursor-pointer",children:t})}),e.jsx(gVt,{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=oin.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(ja,{className:"h-6 w-6",children:[e.jsx(pi,{src:l.user_avatar||void 0}),e.jsx(Na,{className:"text-[10px]",children:lin(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 cin({images:s,initialIndex:t=0,open:n,onOpenChange:r}){const[a,i]=_.useState(t),[l,o]=_.useState(!1);_.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]);_.useEffect(()=>(window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)),[u]);const h=s[a];return e.jsx(Ls,{open:n,onOpenChange:r,children:e.jsxs(Ps,{className:"max-w-[95vw] max-h-[95vh] w-auto h-auto p-0 border-none bg-black/95 overflow-hidden",children:[e.jsx(B,{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(Qn,{className:"h-6 w-6"})}),s.length>1&&e.jsxs(e.Fragment,{children:[e.jsx(B,{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($c,{className:"h-8 w-8"})}),e.jsx(B,{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(xi,{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(B,{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(x$,{className:"h-5 w-5"}):e.jsx(aP,{className:"h-5 w-5"})}),e.jsx("div",{className:At("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:At("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:At("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 pce=[{type:"like",emoji:"👍",label:"Like"},{type:"love",emoji:"❤️",label:"Love"}],din=({commentId:s,reactions:t,currentUserId:n})=>{var d,u;const r=Bt(),[a,i]=_.useState(!1),l=t.find(h=>h.user_id===n),o=mt({mutationFn:async h=>{l?l.reaction_type===h?await q.from("community_comment_reactions").delete().eq("id",l.id):await q.from("community_comment_reactions").update({reaction_type:h}).eq("id",l.id):await q.from("community_comment_reactions").insert({comment_id:s,user_id:n,reaction_type:h})},onSuccess:()=>{r.invalidateQueries({queryKey:["community-posts"]}),i(!1)}}),c={};return t.forEach(h=>{c[h.reaction_type]=(c[h.reaction_type]||0)+1}),e.jsxs("div",{className:"flex items-center gap-2",children:[t.length>0&&e.jsx(yVt,{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=pce.find(p=>p.type===h))==null?void 0:m.emoji},h)})}),e.jsx("span",{children:t.length})]})}),n&&e.jsxs(od,{open:a,onOpenChange:i,children:[e.jsx(ld,{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=pce.find(h=>h.type===l.reaction_type))==null?void 0:d.emoji," ",(u=pce.find(h=>h.type===l.reaction_type))==null?void 0:u.label]}):e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Do,{className:"h-3 w-3"}),"Like"]})})}),e.jsx(Qc,{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:pce.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 qtt({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(ir,{to:u?`/templates/${d}`:`/profile?user=${d}`,className:At("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(_.Fragment,{children:o},c))})}function EEe({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=_.useRef(null),h=_.useRef(null),[m,p]=_.useState(!1),[f,y]=_.useState("user"),[v,g]=_.useState(""),[b,j]=_.useState(null),[S,C]=_.useState(0),[E,P]=_.useState({top:0,left:0,width:0}),M=_.useRef(new Map),I=_.useRef(new Map),D=ae=>{if(c==="plain"){const he=[];return M.current.forEach((Ce,Ae)=>{ae.includes(`@${Ae}`)&&he.push(Ce)}),[...new Set(he)]}const le=/@\[([^\]]+)\]\(([^)]+)\)/g,be=[];let me;for(;(me=le.exec(ae))!==null;)be.push(me[2]);return[...new Set(be)]},O=ae=>{if(c==="plain"){const he=[];return I.current.forEach((Ce,Ae)=>{ae.includes(`#${Ae}`)&&he.push(Ce)}),[...new Set(he)]}const le=/#\[([^\]]+)\]\(([^)]+)\)/g,be=[];let me;for(;(me=le.exec(ae))!==null;)be.push(me[2]);return[...new Set(be)]};_.useEffect(()=>{if(i){const ae=D(s);i(ae)}if(l){const ae=O(s);l(ae)}},[s,i,l,c]);const{data:V=[],isLoading:G}=at({queryKey:["mention-users",v],queryFn:async()=>{const ae=q.from("profiles").select("id, name").limit(8),le=v.length>=1?ae.ilike("name",`%${v}%`):ae.order("name"),{data:be,error:me}=await le;if(me)throw me;const he=be.map(Ce=>Ce.id),pe=await e8t(he);return be.map(Ce=>({id:Ce.id,name:Ce.name||"Unknown",avatar_url:pe.get(Ce.id)}))},enabled:m&&f==="user",staleTime:3e4}),{data:$=[],isLoading:H}=at({queryKey:["mention-templates",v],queryFn:async()=>{let ae=q.from("canva_templates").select("id, name, preview_image_url").lte("publish_date",new Date().toISOString()).order("publish_date",{ascending:!1}).limit(8);v.length>=1&&(ae=ae.ilike("name",`%${v}%`));const{data:le,error:be}=await ae;if(be)throw be;return le||[]},enabled:m&&f==="template"&&d,staleTime:3e4}),Y=f==="user"?G:H,Z=f==="user"?V:$,ne=ae=>ae.split(" ").map(le=>le[0]).join("").toUpperCase().slice(0,2),ce=ae=>{const le=ae.target.value,be=ae.target.selectionStart;t(le);const me=le.substring(0,be),he=me.lastIndexOf("@"),pe=d?me.lastIndexOf("#"):-1;let Ce=-1,Ae="user";if(he>pe?(Ce=he,Ae="user"):pe>he&&d&&(Ce=pe,Ae="template"),Ce!==-1){const Pe=me.substring(Ce+1),ze=Pe.includes(" "),ke=Pe.includes(` `);if(!ze&&!ke&&Pe.length<=30){j(Ce),g(Pe),y(Ae),p(!0),C(0);return}}p(!1),j(null)},ie=ae=>{if(b===null)return;const le=s.substring(0,b),be=s.substring(b+v.length+1),me=f==="user"?"@":"#",he=c==="plain"?`${me}${ae.name} `:`${me}[${ae.name}](${ae.id}) `;c==="plain"&&(f==="user"?M.current.set(ae.name,ae.id):I.current.set(ae.name,ae.id));const pe=le+he+be;t(pe),p(!1),j(null),g(""),setTimeout(()=>{if(u.current){const Ce=le.length+he.length;u.current.focus(),u.current.setSelectionRange(Ce,Ce)}},0)},te=ae=>{if(!(!m||Z.length===0))switch(ae.key){case"ArrowDown":ae.preventDefault(),C(le=>(le+1)%Z.length);break;case"ArrowUp":ae.preventDefault(),C(le=>(le-1+Z.length)%Z.length);break;case"Enter":Z[S]&&(ae.preventDefault(),ie(Z[S]));break;case"Escape":ae.preventDefault(),p(!1);break;case"Tab":Z[S]&&(ae.preventDefault(),ie(Z[S]));break}};return _.useEffect(()=>{const ae=le=>{h.current&&!h.current.contains(le.target)&&u.current&&!u.current.contains(le.target)&&p(!1)};return document.addEventListener("mousedown",ae),()=>document.removeEventListener("mousedown",ae)},[]),_.useEffect(()=>{if(!m)return;const ae=()=>{const le=u.current;if(!le)return;const be=le.getBoundingClientRect();P({top:be.bottom+4,left:be.left,width:be.width})};return ae(),window.addEventListener("resize",ae),window.addEventListener("scroll",ae,!0),()=>{window.removeEventListener("resize",ae),window.removeEventListener("scroll",ae,!0)}},[m,s]),e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Ms,{ref:u,value:s,onChange:ce,onKeyDown:ae=>{te(ae),ae.defaultPrevented||o==null||o(ae)},placeholder:n,className:At("resize-none",r),style:{minHeight:a}}),m&&mv.createPortal(e.jsxs("div",{ref:h,className:"fixed z-[1000] max-h-[220px] overflow-hidden rounded-lg border bg-popover shadow-lg",style:{top:E.top,left:E.left,width:E.width,maxWidth:"320px"},children:[e.jsx("div",{className:"px-3 py-1.5 text-xs font-medium text-muted-foreground border-b bg-muted/30",children:f==="user"?"👤 Mention a person":"📋 Link a template"}),Y?e.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:"Searching..."}):Z.length===0?e.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:v.length<1?`Type to search ${f==="user"?"people":"templates"}...`:`No ${f==="user"?"users":"templates"} found`}):e.jsx("ul",{className:"py-1 max-h-[180px] overflow-y-auto",children:Z.map((ae,le)=>e.jsx("li",{className:At("flex items-center gap-2 px-3 py-2 cursor-pointer transition-colors",le===S?"bg-accent":"hover:bg-accent/50"),onClick:()=>ie(ae),onMouseEnter:()=>C(le),children:f==="user"?e.jsxs(e.Fragment,{children:[e.jsxs(ja,{className:"h-6 w-6",children:[e.jsx(pi,{src:ae.avatar_url}),e.jsx(Na,{className:"text-xs",children:ne(ae.name)})]}),e.jsx("span",{className:"text-sm font-medium truncate",children:ae.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:ae.preview_image_url?e.jsx("img",{src:ae.preview_image_url,alt:"",className:"w-full h-full object-cover"}):e.jsx(Xc,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"text-sm font-medium truncate",children:ae.name})]})},ae.id))})]}),document.body)]})}function uin(s){const t=/#\[([^\]]+)\]\(([^)]+)\)/g,n=[];let r;for(;(r=t.exec(s))!==null;)n.push(r[2]);return[...new Set(n)]}const Mvt=s=>s.split(" ").map(t=>t[0]).join("").toUpperCase().slice(0,2);function vVt({comment:s,postId:t,currentUserId:n,currentUserAvatar:r,currentUserEmail:a,canModerate:i,depth:l=0}){const o=Bt(),[c,d]=_.useState(!1),[u,h]=_.useState(""),[m,p]=_.useState([]),f=mt({mutationFn:async({content:b,parentCommentId:j})=>{const{data:S,error:C}=await q.from("community_comments").insert({post_id:t,user_id:n,content:b,parent_comment_id:j}).select("id").single();if(C)throw C;const E=m;if(E.length>0&&S){const P=E.filter(M=>M!==n).map(M=>({comment_id:S.id,mentioned_user_id:M,mentioned_by_user_id:n}));P.length>0&&await q.from("community_comment_mentions").insert(P)}},onSuccess:()=>{o.invalidateQueries({queryKey:["community-posts"]}),h(""),p([]),d(!1)}}),y=mt({mutationFn:async b=>{const{error:j}=await q.from("community_comments").delete().eq("id",b);if(j)throw j},onSuccess:()=>o.invalidateQueries({queryKey:["community-posts"]})}),v=()=>{u.trim()&&f.mutate({content:u,parentCommentId:s.id})};return e.jsxs("div",{className:l>0?"ml-8 border-l-2 border-muted pl-3":"",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(ja,{className:"h-8 w-8 shrink-0",children:[e.jsx(pi,{src:s.user_avatar||void 0}),e.jsx(Na,{className:"text-xs",children:Mvt(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(qtt,{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:Ed(new Date(s.created_at),{addSuffix:!0})}),e.jsx(din,{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(Qq,{className:"h-3 w-3"}),"Reply"]}),(s.user_id===n||i)&&e.jsx("button",{onClick:()=>y.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(ja,{className:"h-6 w-6 shrink-0 mt-1",children:[e.jsx(pi,{src:r||void 0}),e.jsx(Na,{className:"text-xs",children:Mvt((a==null?void 0:a.split("@")[0])||"U")})]}),e.jsxs("div",{className:"flex-1 flex gap-2 items-start",children:[e.jsx(EEe,{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(B,{size:"sm",variant:"ghost",onClick:v,disabled:!u.trim()||f.isPending,className:"h-8 px-2 mt-0.5",children:e.jsx(Or,{className:"h-3 w-3"})})]})]})]})]}),s.replies&&s.replies.length>0&&e.jsx("div",{className:"mt-2 space-y-2",children:s.replies.map(b=>e.jsx(vVt,{comment:b,postId:t,currentUserId:n,currentUserAvatar:r,currentUserEmail:a,canModerate:i,depth:l+1},b.id))})]})}const fce=[{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"}],hin=()=>{const{user:s,isBrokerageManager:t,managedBrokerages:n,isAdmin:r}=hs(),{avatarUrl:a}=JIt(s==null?void 0:s.id),{onlineUsers:i}=zLt(),{toast:l}=vi(),o=Bt(),c=_.useRef(null),[d,u]=_.useState("all"),[h,m]=_.useState(""),[p,f]=_.useState(""),[y,v]=_.useState(""),[g,b]=_.useState([]),[j,S]=_.useState([]),[C,E]=_.useState(""),[P,M]=_.useState(!1),[I,D]=_.useState(null),[O,V]=_.useState(""),[G,$]=_.useState(new Set),[H,Y]=_.useState({}),[Z,ne]=_.useState({}),[ce,ie]=_.useState([]),[te,ae]=_.useState([]),[le,be]=_.useState({open:!1,images:[],index:0});_.useEffect(()=>{if(d.startsWith("group:")){const xt=d.replace("group:","");v(xt),f("")}else d!=="all"?(f(d),v("")):(f(""),v(""))},[d]);const{data:me=[]}=at({queryKey:["community-categories"],queryFn:async()=>{const{data:xt,error:qt}=await q.from("community_categories").select("*").order("sort_order");if(qt)throw qt;return xt}}),{data:he=[]}=at({queryKey:["community-private-groups"],queryFn:async()=>{const{data:xt,error:qt}=await q.from("community_private_groups").select("id, name, description, icon, brokerage_id, sort_order").order("sort_order");if(qt)throw qt;return xt}}),pe=20,{data:Ce,isLoading:Ae,hasNextPage:Pe,fetchNextPage:ze,isFetchingNextPage:ke}=Ivs({queryKey:["community-posts",d],initialPageParam:0,queryFn:async({pageParam:xt})=>{var pt;const qt=xt*pe,Vt=qt+pe;let Xt=q.from("community_posts").select("*").order("is_pinned",{ascending:!1}).order("pinned_at",{ascending:!1,nullsFirst:!1}).order("created_at",{ascending:!1}).range(qt,Vt);if(d.startsWith("group:")){const jt=d.replace("group:","");Xt=Xt.eq("private_group_id",jt)}else d==="all"||(Xt=Xt.eq("category_id",d).is("private_group_id",null));const{data:fs,error:Ft}=await Xt;if(Ft)throw Ft;const wt=((fs==null?void 0:fs.length)||0)>pe,Ts=(fs||[]).slice(0,pe);if(Ts.length===0)return{posts:[],hasMore:!1,nextPage:xt+1};const vt=Ts.map(jt=>jt.id),$s=[...new Set(Ts.filter(jt=>jt.category_id).map(jt=>jt.category_id))].filter(Boolean),[As,jn,ar,Dn,Ur]=await Promise.all([$s.length?q.from("community_categories").select("*").in("id",$s):Promise.resolve({data:[]}),q.from("community_post_media").select("*").in("post_id",vt).order("sort_order"),q.from("community_reactions").select("*").in("post_id",vt),q.from("community_comments").select("*").in("post_id",vt).order("created_at",{ascending:!0}),q.from("community_post_resources").select("*").in("post_id",vt)]),Vs=As==null?void 0:As.data,hn=jn==null?void 0:jn.data,dr=ar==null?void 0:ar.data,Cn=Dn==null?void 0:Dn.data,Yn=Ur==null?void 0:Ur.data,on=(Cn||[]).map(jt=>jt.id),[Ir,Wn]=await Promise.all([on.length?q.from("community_comment_reactions").select("*").in("comment_id",on):Promise.resolve({data:[]}),(()=>{const jt=(Yn||[]).filter(Mt=>Mt.resource_type==="template").map(Mt=>Mt.resource_id);return jt.length===0?Promise.resolve({data:[]}):q.from("canva_templates").select("id, name, preview_image_url").in("id",jt)})()]),Js=(Ir==null?void 0:Ir.data)||[],Fa=(Wn==null?void 0:Wn.data)||[],ks=new Map(Fa.map(jt=>[jt.id,{name:jt.name,preview_image_url:jt.preview_image_url}])),Gs=Array.from(new Set([...Ts.map(jt=>jt.user_id),...(dr||[]).map(jt=>jt.user_id),...(Cn||[]).map(jt=>jt.user_id),...Js.map(jt=>jt.user_id)])),[Ws,Ys]=await Promise.all([Gs.length?q.from("profiles").select("id, name").in("id",Gs):Promise.resolve({data:[]}),e8t(Gs)]),Bn=new Map(((pt=Ws==null?void 0:Ws.data)==null?void 0:pt.map(jt=>[jt.id,jt.name]))||[]),or=new Map((Vs||[]).map(jt=>[jt.id,jt])),Wt=jt=>{const Mt=new Map,es=[];return jt.forEach(ps=>{Mt.set(ps.id,{...ps,user_name:Bn.get(ps.user_id)||"Unknown User",user_avatar:Ys.get(ps.user_id),reactions:Js.filter(Is=>Is.comment_id===ps.id).map(Is=>({...Is,user_name:Bn.get(Is.user_id)||"Unknown User",user_avatar:Ys.get(Is.user_id)})),replies:[]})}),jt.forEach(ps=>{const Is=Mt.get(ps.id);if(ps.parent_comment_id&&Mt.has(ps.parent_comment_id)){const js=Mt.get(ps.parent_comment_id);js.replies=js.replies||[],js.replies.push(Is)}else es.push(Is)}),es};return{posts:Ts.map(jt=>{const Mt=(Yn||[]).filter(es=>es.post_id===jt.id).map(es=>{let ps="",Is=null;if(es.resource_type==="template"){const js=ks.get(es.resource_id);ps=(js==null?void 0:js.name)||"Unknown Template",Is=(js==null?void 0:js.preview_image_url)||null}return{id:es.id,resource_type:es.resource_type,resource_id:es.resource_id,resource_name:ps,resource_preview_url:Is}});return{...jt,user_name:Bn.get(jt.user_id)||"Unknown User",user_avatar:Ys.get(jt.user_id),category:jt.category_id?or.get(jt.category_id):null,media:(hn||[]).filter(es=>es.post_id===jt.id),reactions:((dr||[]).filter(es=>es.post_id===jt.id)||[]).map(es=>({...es,user_name:Bn.get(es.user_id)||"Unknown User",user_avatar:Ys.get(es.user_id)})),comments:Wt((Cn||[]).filter(es=>es.post_id===jt.id)),resources:Mt}}),hasMore:wt,nextPage:xt+1}},getNextPageParam:xt=>xt.hasMore?xt.nextPage:void 0}),Ze=_.useMemo(()=>(Ce==null?void 0:Ce.pages.flatMap(xt=>xt.posts))??[],[Ce]),Se=mt({mutationFn:async()=>{M(!0);const{data:xt,error:qt}=await q.from("community_posts").insert({user_id:s.id,category_id:y?null:p||null,private_group_id:y||null,content:h,link_url:C||null}).select().single();if(qt)throw qt;for(let Xt=0;Xt0){const Xt=ce.filter(fs=>fs!==s.id).map(fs=>({post_id:xt.id,mentioned_user_id:fs,mentioned_by_user_id:s.id}));Xt.length>0&&await q.from("community_post_mentions").insert(Xt)}const Vt=uin(h);if(Vt.length>0){const Xt=Vt.map(fs=>({post_id:xt.id,resource_type:"template",resource_id:fs}));await q.from("community_post_resources").insert(Xt)}return xt},onSuccess:async xt=>{var qt;o.invalidateQueries({queryKey:["community-posts"]}),m(""),ie([]),ae([]),f(""),v(""),b([]),S([]),E(""),l({title:"Post created!"});try{const Vt=((qt=s==null?void 0:s.user_metadata)==null?void 0:qt.name)||"Someone",Xt=h.replace(/@\[([^\]]+)\]\([^)]+\)/g,"@$1"),fs=Xt.length>50?Xt.substring(0,50)+"...":Xt;await q.functions.invoke("send-push-notification",{body:{title:"New Community Post",body:`${Vt}: ${fs}`,url:"/community"}})}catch(Vt){console.error("Failed to send push notification:",Vt)}},onError:xt=>{l({title:"Error creating post",description:xt.message,variant:"destructive"})},onSettled:()=>M(!1)}),Fe=mt({mutationFn:async({postId:xt,content:qt})=>{const{error:Vt}=await q.from("community_posts").update({content:qt}).eq("id",xt);if(Vt)throw Vt},onSuccess:()=>{o.invalidateQueries({queryKey:["community-posts"]}),D(null),V(""),l({title:"Post updated!"})}}),Ne=mt({mutationFn:async xt=>{const{error:qt}=await q.from("community_posts").delete().eq("id",xt);if(qt)throw qt},onSuccess:()=>{o.invalidateQueries({queryKey:["community-posts"]}),l({title:"Post deleted"})}}),Ye=mt({mutationFn:async({postId:xt,isPinned:qt})=>{const{error:Vt}=await q.from("community_posts").update({is_pinned:!qt,pinned_at:qt?null:new Date().toISOString(),pinned_by:qt?null:s==null?void 0:s.id}).eq("id",xt);if(Vt)throw Vt},onSuccess:(xt,{isPinned:qt})=>{o.invalidateQueries({queryKey:["community-posts"]}),l({title:qt?"Post unpinned":"Post pinned to top"})}}),Ve=mt({mutationFn:async({postId:xt,reactionType:qt})=>{var Xt;const Vt=(Xt=Ze.find(fs=>fs.id===xt))==null?void 0:Xt.reactions.find(fs=>fs.user_id===(s==null?void 0:s.id));Vt?Vt.reaction_type===qt?await q.from("community_reactions").delete().eq("id",Vt.id):await q.from("community_reactions").update({reaction_type:qt}).eq("id",Vt.id):await q.from("community_reactions").insert({post_id:xt,user_id:s.id,reaction_type:qt})},onSuccess:()=>o.invalidateQueries({queryKey:["community-posts"]})}),qe=mt({mutationFn:async({postId:xt,content:qt})=>{const{data:Vt,error:Xt}=await q.from("community_comments").insert({post_id:xt,user_id:s.id,content:qt}).select("id").single();if(Xt)throw Xt;const fs=Z[xt]||[];if(fs.length>0&&Vt){const Ft=fs.filter(wt=>wt!==s.id).map(wt=>({comment_id:Vt.id,mentioned_user_id:wt,mentioned_by_user_id:s.id}));Ft.length>0&&await q.from("community_comment_mentions").insert(Ft)}},onSuccess:(xt,{postId:qt})=>{o.invalidateQueries({queryKey:["community-posts"]}),Y(Vt=>({...Vt,[qt]:""})),ne(Vt=>({...Vt,[qt]:[]}))}});mt({mutationFn:async xt=>{const{error:qt}=await q.from("community_comments").delete().eq("id",xt);if(qt)throw qt},onSuccess:()=>o.invalidateQueries({queryKey:["community-posts"]})});const Qe=xt=>{const qt=Array.from(xt.target.files||[]);if(qt.length+g.length>10){l({title:"Maximum 10 files allowed",variant:"destructive"});return}b(Vt=>[...Vt,...qt]),qt.forEach(Vt=>{const Xt=new FileReader;Xt.onloadend=()=>{S(fs=>[...fs,Xt.result])},Xt.readAsDataURL(Vt)})},Ue=xt=>{b(qt=>qt.filter((Vt,Xt)=>Xt!==xt)),S(qt=>qt.filter((Vt,Xt)=>Xt!==xt))},Xe=xt=>xt.split(" ").map(qt=>qt[0]).join("").toUpperCase().slice(0,2),nt=xt=>{const qt={};return xt.forEach(Vt=>{qt[Vt.reaction_type]=(qt[Vt.reaction_type]||0)+1}),qt},$e=xt=>{var qt;return(qt=xt.find(Vt=>Vt.user_id===(s==null?void 0:s.id)))==null?void 0:qt.reaction_type},Ge=xt=>xt.reduce((qt,Vt)=>qt+1+(Vt.replies?Ge(Vt.replies):0),0),ct=xt=>{if(r)return!0;if(!t||!xt.private_group_id)return!1;const qt=he.find(Vt=>Vt.id===xt.private_group_id);return qt!=null&&qt.brokerage_id?n.some(Vt=>Vt.id===qt.brokerage_id):!1};return e.jsx(zs,{title:"Community",children:e.jsxs("div",{className:"flex gap-6 w-full isolate z-0",children:[e.jsx(Kan,{categories:me,privateGroups:he,selectedFilter:d,onFilterChange:u,onlineUsers:i}),e.jsxs("div",{className:"flex-1 min-w-0 max-w-2xl mx-auto lg:mx-0 space-y-6",children:[e.jsxs("div",{className:"px-1",children:[e.jsx("h1",{className:"text-4xl lg:text-5xl font-bold text-foreground",children:"Community"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Connect and share with fellow agents"})]}),e.jsx(Yan,{categories:me,privateGroups:he,selectedFilter:d,onFilterChange:u,onlineUsers:i}),e.jsx(ve,{children:e.jsx(Me,{className:"pt-6",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsxs(ja,{className:"h-10 w-10",children:[e.jsx(pi,{src:a||void 0}),e.jsx(Na,{children:s!=null&&s.email?Xe(s.email.split("@")[0]):"U"})]}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsx(EEe,{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:ie,onTemplatesChange:ae,mentionFormat:"encoded",minHeight:"80px",enableTemplateMentions:r}),j.length>0&&e.jsx("div",{className:"grid grid-cols-3 gap-2",children:j.map((xt,qt)=>{var Vt;return e.jsxs("div",{className:"relative aspect-square rounded-lg overflow-hidden bg-muted",children:[(Vt=g[qt])!=null&&Vt.type.startsWith("video/")?e.jsx("video",{src:xt,className:"w-full h-full object-cover"}):e.jsx("img",{src:xt,alt:"",className:"w-full h-full object-cover"}),e.jsx(B,{variant:"destructive",size:"icon",className:"absolute top-1 right-1 h-6 w-6",onClick:()=>Ue(qt),children:e.jsx(Qn,{className:"h-3 w-3"})})]},qt)})}),C&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Vc,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(xe,{value:C,onChange:xt=>E(xt.target.value),placeholder:"https://...",className:"flex-1"}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>E(""),children:e.jsx(Qn,{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:Qe,accept:"image/*,video/*",multiple:!0,className:"hidden"}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>{var xt;return(xt=c.current)==null?void 0:xt.click()},children:[e.jsx(hc,{className:"h-4 w-4 mr-1"}),"Photo"]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>{var xt;return(xt=c.current)==null?void 0:xt.click()},children:[e.jsx(Kr,{className:"h-4 w-4 mr-1"}),"Video"]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>E("https://"),children:[e.jsx(Vc,{className:"h-4 w-4 mr-1"}),"Link"]})]}),e.jsxs("div",{className:"flex items-center gap-2 w-full sm:w-auto justify-end",children:[he.length>0?e.jsxs(is,{value:y||p||"none",onValueChange:xt=>{xt==="none"?(f(""),v("")):xt.startsWith("group:")?(v(xt.replace("group:","")),f("")):(f(xt),v(""))},children:[e.jsx(rs,{className:"w-[130px] sm:w-[160px] h-8 text-xs sm:text-sm",children:e.jsx(ls,{placeholder:"Select..."})}),e.jsxs(as,{children:[e.jsx(He,{value:"none",children:"No category"}),me.map(xt=>e.jsxs(He,{value:xt.id,children:[xt.icon," ",xt.name]},xt.id)),he.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 py-1 text-xs font-semibold text-muted-foreground border-t mt-1 pt-1",children:"🔒 Private Groups"}),he.map(xt=>e.jsxs(He,{value:`group:${xt.id}`,children:[xt.icon||"🔒"," ",xt.name]},xt.id))]})]})]}):e.jsxs(is,{value:p,onValueChange:f,children:[e.jsx(rs,{className:"w-[110px] sm:w-[140px] h-8 text-xs sm:text-sm",children:e.jsx(ls,{placeholder:"Category"})}),e.jsx(as,{children:me.map(xt=>e.jsxs(He,{value:xt.id,children:[xt.icon," ",xt.name]},xt.id))})]}),e.jsxs(B,{size:"sm",onClick:()=>Se.mutate(),disabled:!h.trim()||P,children:[e.jsx(Or,{className:"h-4 w-4 mr-1"}),"Post"]})]})]})]})]})})}),Ae?e.jsx("div",{className:"space-y-4",children:[...Array(3)].map((xt,qt)=>e.jsx(ve,{children:e.jsx(Me,{className:"pt-6",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(cn,{className:"h-10 w-10 rounded-full"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(cn,{className:"h-4 w-32"}),e.jsx(cn,{className:"h-4 w-full"}),e.jsx(cn,{className:"h-4 w-3/4"})]})]})})},qt))}):Ze.length===0?e.jsx(ve,{children:e.jsxs(Me,{className:"py-12 text-center",children:[e.jsx(Ou,{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:[Ze.map(xt=>{var qt,Vt,Xt,fs;return e.jsx(ve,{children:e.jsxs(Me,{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(ja,{className:"h-10 w-10",children:[e.jsx(pi,{src:xt.user_avatar||void 0}),e.jsx(Na,{children:Xe(xt.user_name||"U")})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-semibold break-words",children:xt.user_name}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-sm text-muted-foreground",children:[e.jsx("span",{children:Ed(new Date(xt.created_at),{addSuffix:!0})}),xt.category&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsxs(Oe,{variant:"secondary",className:"text-xs",children:[xt.category.icon," ",xt.category.name]})]})]})]})]}),(xt.user_id===(s==null?void 0:s.id)||ct(xt))&&e.jsxs(tu,{children:[e.jsx(su,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(ob,{className:"h-4 w-4"})})}),e.jsxs(Od,{align:"end",children:[ct(xt)&&xt.private_group_id&&e.jsx(ca,{onClick:()=>Ye.mutate({postId:xt.id,isPinned:xt.is_pinned}),children:xt.is_pinned?e.jsxs(e.Fragment,{children:[e.jsx(JQ,{className:"h-4 w-4 mr-2"}),"Unpin Post"]}):e.jsxs(e.Fragment,{children:[e.jsx(YA,{className:"h-4 w-4 mr-2"}),"Pin to Top"]})}),xt.user_id===(s==null?void 0:s.id)&&e.jsxs(ca,{onClick:()=>{D(xt),V(xt.content)},children:[e.jsx(Ya,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsxs(ca,{className:"text-destructive",onClick:()=>Ne.mutate(xt.id),children:[e.jsx(Sn,{className:"h-4 w-4 mr-2"}),xt.user_id!==(s==null?void 0:s.id)?"Remove (Moderate)":"Delete"]})]})]})]}),xt.is_pinned&&e.jsxs("div",{className:"flex items-center gap-2 mb-2 text-sm text-primary",children:[e.jsx(YA,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium",children:"Pinned"})]}),e.jsx("div",{className:"mb-3",children:e.jsx(qtt,{content:xt.content})}),xt.media.length>0&&e.jsx("div",{className:`grid gap-2 mb-3 ${xt.media.length===1?"grid-cols-1":xt.media.length===2?"grid-cols-2":xt.media.length===3?"grid-cols-3":"grid-cols-2"}`,children:xt.media.slice(0,4).map((Ft,wt)=>{const Ts=wt===3&&xt.media.length>4,vt=xt.media.length-4;return e.jsxs("div",{className:`relative rounded-lg overflow-hidden bg-muted cursor-pointer group ${xt.media.length===1?"max-h-[500px]":xt.media.length===2?"aspect-[4/3]":"aspect-square"}`,onClick:()=>be({open:!0,images:xt.media.map($s=>({url:$s.media_url,type:$s.media_type==="video"?"video":"image"})),index:wt}),children:[Ft.media_type==="video"?e.jsx("video",{src:Ft.media_url,className:"w-full h-full object-cover transition-transform group-hover:scale-105"}):e.jsx("img",{src:Ft.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"})})})}),Ts&&e.jsx("div",{className:"absolute inset-0 bg-black/60 flex items-center justify-center",children:e.jsxs("span",{className:"text-white text-2xl font-bold",children:["+",vt]})})]},Ft.id)})}),xt.link_url&&e.jsxs("a",{href:xt.link_url,target:"_blank",rel:"noopener noreferrer",className:"block rounded-lg border hover:bg-muted transition-colors mb-3 overflow-hidden",children:[xt.link_image&&e.jsx("div",{className:"aspect-video bg-muted",children:e.jsx("img",{src:xt.link_image,alt:xt.link_title||"Link preview",className:"w-full h-full object-cover",onError:Ft=>{Ft.currentTarget.style.display="none"}})}),e.jsx("div",{className:"p-3",children:xt.link_title?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"font-medium text-foreground line-clamp-2",children:xt.link_title}),xt.link_description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mt-1",children:xt.link_description}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2 truncate",children:new URL(xt.link_url).hostname})]}):e.jsxs("div",{className:"flex items-center gap-2 text-sm text-primary",children:[e.jsx(Vc,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:xt.link_url})]})})]}),xt.reactions.length>0&&e.jsx(yVt,{reactions:xt.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(nt(xt.reactions)).slice(0,3).map(([Ft])=>{var wt;return e.jsx("span",{className:"text-base",children:(wt=fce.find(Ts=>Ts.type===Ft))==null?void 0:wt.emoji},Ft)})}),e.jsx("span",{children:xt.reactions.length})]})}),e.jsxs("div",{className:"flex items-center gap-1 border-t border-b py-1 my-2",children:[e.jsxs(od,{children:[e.jsx(ld,{asChild:!0,children:e.jsxs(B,{variant:"ghost",size:"sm",className:"flex-1",children:[$e(xt.reactions)?e.jsx("span",{className:"mr-1",children:(qt=fce.find(Ft=>Ft.type===$e(xt.reactions)))==null?void 0:qt.emoji}):e.jsx(Fg,{className:"h-4 w-4 mr-1"}),$e(xt.reactions)?(Vt=fce.find(Ft=>Ft.type===$e(xt.reactions)))==null?void 0:Vt.label:"Like"]})}),e.jsx(Qc,{className:"w-auto p-2",side:"top",children:e.jsx("div",{className:"flex gap-1",children:fce.map(Ft=>e.jsx("button",{onClick:()=>Ve.mutate({postId:xt.id,reactionType:Ft.type}),className:"text-2xl hover:scale-125 transition-transform p-1",title:Ft.label,children:Ft.emoji},Ft.type))})})]}),e.jsxs(B,{variant:"ghost",size:"sm",className:"flex-1",onClick:()=>$(Ft=>{const wt=new Set(Ft);return wt.has(xt.id)?wt.delete(xt.id):wt.add(xt.id),wt}),children:[e.jsx(Ou,{className:"h-4 w-4 mr-1"}),(()=>{const Ft=Ge(xt.comments);return Ft>0?`Comment (${Ft})`:"Comment"})()]})]}),G.has(xt.id)&&e.jsxs("div",{className:"space-y-3 mt-3",children:[xt.comments.map(Ft=>e.jsx(vVt,{comment:Ft,postId:xt.id,currentUserId:s==null?void 0:s.id,currentUserAvatar:a,currentUserEmail:s==null?void 0:s.email,canModerate:ct(xt)},Ft.id)),s&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(ja,{className:"h-8 w-8",children:[e.jsx(pi,{src:a||void 0}),e.jsx(Na,{className:"text-xs",children:Xe(((Xt=s.email)==null?void 0:Xt.split("@")[0])||"U")})]}),e.jsxs("div",{className:"flex-1 flex gap-2",children:[e.jsx(EEe,{placeholder:"Write a comment... (use @ to mention)",value:H[xt.id]||"",onChange:Ft=>Y(wt=>({...wt,[xt.id]:Ft})),onMentionsChange:Ft=>ne(wt=>({...wt,[xt.id]:Ft})),mentionFormat:"plain",onKeyDown:Ft=>{var wt;Ft.defaultPrevented||Ft.key==="Enter"&&!Ft.shiftKey&&((wt=H[xt.id])!=null&&wt.trim())&&(Ft.preventDefault(),qe.mutate({postId:xt.id,content:H[xt.id]}))},className:"text-sm min-h-0 py-1.5",minHeight:"32px"}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>{var Ft;(Ft=H[xt.id])!=null&&Ft.trim()&&qe.mutate({postId:xt.id,content:H[xt.id]})},disabled:!((fs=H[xt.id])!=null&&fs.trim()),className:"h-8 px-2 mt-0.5",children:e.jsx(Or,{className:"h-4 w-4"})})]})]})]})]})},xt.id)}),Pe&&e.jsx("div",{className:"flex justify-center pt-2",children:e.jsx(B,{variant:"outline",onClick:()=>ze(),disabled:ke,children:ke?"Loading…":"Load more posts"})})]}),e.jsx(Ls,{open:!!I,onOpenChange:()=>D(null),children:e.jsxs(Ps,{children:[e.jsx(Os,{children:e.jsx(Ds,{children:"Edit Post"})}),e.jsx(Ms,{value:O,onChange:xt=>V(xt.target.value),className:"min-h-[120px]"}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{variant:"outline",onClick:()=>D(null),children:"Cancel"}),e.jsx(B,{onClick:()=>{I&&Fe.mutate({postId:I.id,content:O})},disabled:!O.trim(),children:"Save Changes"})]})]})}),e.jsx(cin,{images:le.images,initialIndex:le.index,open:le.open,onOpenChange:xt=>be(qt=>({...qt,open:xt}))})]})]})})},min=50*1024*1024;function bVt({value:s,onChange:t,disabled:n}){const{user:r}=hs(),a=_.useRef(null),[i,l]=_.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/")){se.error(`${h.name}: only images and videos allowed`);continue}if(h.size>min){se.error(`${h.name}: must be under 50MB`);continue}const m=h.name.split(".").pop()||"bin",p=`${r.id}/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${m}`,{error:f}=await q.storage.from("support-attachments").upload(p,h,{contentType:h.type,upsert:!1});if(f){se.error(`${h.name}: ${f.message}`);continue}u.push({path:p,type:h.type,name:h.name,size:h.size})}u.length&&t([...s,...u])}finally{l(!1),a.current&&(a.current.value="")}},c=async d=>{const u=s[d];t(s.filter((h,m)=>m!==d)),await q.storage.from("support-attachments").remove([u.path])};return e.jsxs("div",{className:"space-y-2",children:[s.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:s.map((d,u)=>e.jsxs("div",{className:"flex items-center gap-2 px-2 py-1 rounded-md border bg-muted/40 text-xs",children:[d.type.startsWith("video/")?e.jsx(EQ,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(KM,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"max-w-[160px] truncate",children:d.name}),e.jsx("button",{type:"button",onClick:()=>c(u),className:"text-muted-foreground hover:text-foreground",children:e.jsx(Qn,{className:"h-3 w-3"})})]},d.path))}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:()=>{var d;return(d=a.current)==null?void 0:d.click()},disabled:n||i,className:"gap-1.5",children:[i?e.jsx(Ct,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(eP,{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 _Vt({attachments:s}){const[t,n]=_.useState({}),[r,a]=_.useState(!0);return _.useEffect(()=>{if(!(s!=null&&s.length)){a(!1);return}let i=!1;return(async()=>{const l=s.map(d=>d.path),{data:o}=await q.storage.from("support-attachments").createSignedUrls(l,60*60*24);if(i||!o)return;const c={};o.forEach((d,u)=>{d.signedUrl&&(c[l[u]]=d.signedUrl)}),n(c),a(!1)})(),()=>{i=!0}},[s]),s!=null&&s.length?r?e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground mt-2",children:[e.jsx(Ct,{className:"h-3 w-3 animate-spin"})," Loading attachments..."]}):e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2 mt-3",children:s.map(i=>{const l=t[i.path];return l?i.type.startsWith("video/")?e.jsx("video",{src:l,controls:!0,className:"rounded-md border w-full h-auto max-h-64 bg-black"},i.path):e.jsx("a",{href:l,target:"_blank",rel:"noopener noreferrer",className:"block",children:e.jsx("img",{src:l,alt:i.name,className:"rounded-md border w-full h-32 object-cover hover:opacity-90 transition-opacity"})},i.path):null})}):null}const IB={open:{label:"Open",icon:Gr,color:"bg-yellow-500"},in_progress:{label:"In Progress",icon:Ou,color:"bg-blue-500"},resolved:{label:"Resolved",icon:_l,color:"bg-green-500"},closed:{label:"Closed",icon:Rd,color:"bg-muted-foreground"}},Pvt={general:"General Support",technology:"Technology Support",crm:"CRM Support",marketing:"Marketing Support"};function pin(){const{user:s}=hs(),t=Bt(),[n,r]=_.useState(null),[a,i]=_.useState(""),[l,o]=_.useState([]),{data:c=[],isLoading:d}=at({queryKey:["support-tickets"],queryFn:async()=>{const{data:p,error:f}=await q.from("support_tickets").select("*").eq("user_id",s==null?void 0:s.id).order("created_at",{ascending:!1});if(f)throw f;return p},enabled:!!s}),{data:u=[]}=at({queryKey:["ticket-replies",n==null?void 0:n.id],queryFn:async()=>{if(!n)return[];const{data:p,error:f}=await q.from("support_ticket_replies").select("*, profiles(name)").eq("ticket_id",n.id).order("created_at",{ascending:!0});if(f)throw f;return p},enabled:!!n}),h=mt({mutationFn:async({content:p,attachments:f})=>{if(!n||!s)throw new Error("Missing data");const{error:y}=await q.from("support_ticket_replies").insert({ticket_id:n.id,user_id:s.id,content:p,is_admin_reply:!1,attachments:f});if(y)throw y},onSuccess:()=>{t.invalidateQueries({queryKey:["ticket-replies",n==null?void 0:n.id]}),i(""),o([]),se.success("Reply sent!")},onError:()=>{se.error("Failed to send reply")}}),m=()=>{!a.trim()&&l.length===0||h.mutate({content:a,attachments:l})};if(n){const p=IB[n.status].icon;return e.jsx(zs,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(B,{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(Oe,{variant:"secondary",children:Pvt[n.category]}),e.jsxs(Oe,{className:IB[n.status].color,children:[e.jsx(p,{className:"h-3 w-3 mr-1"}),IB[n.status].label]})]})]})]}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsxs(kn,{children:["Created on ",Hs(new Date(n.created_at),"MMM d, yyyy 'at' h:mm a")]})}),e.jsx(Me,{children:e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:n.description})})]}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-lg",children:"Conversation"})}),e.jsxs(Me,{children:[e.jsx(Ji,{className:"h-[300px] pr-4",children:u.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No replies yet"}):e.jsx("div",{className:"space-y-4",children:u.map(f=>{var y;return e.jsxs("div",{className:`p-4 rounded-lg ${f.is_admin_reply?"bg-primary/10 ml-4":"bg-muted mr-4"}`,children:[e.jsxs("div",{className:"flex justify-between items-start mb-2",children:[e.jsx("span",{className:"font-medium text-sm",children:f.is_admin_reply?"Support Team":((y=f.profiles)==null?void 0:y.name)||"You"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Hs(new Date(f.created_at),"MMM d, h:mm a")})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:f.content}),f.attachments&&f.attachments.length>0&&e.jsx(_Vt,{attachments:f.attachments})]},f.id)})})}),n.status!=="closed"&&e.jsxs(e.Fragment,{children:[e.jsx(wc,{className:"my-4"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ms,{placeholder:"Type your reply...",value:a,onChange:f=>i(f.target.value),className:"min-h-[80px]"}),e.jsx(B,{onClick:m,disabled:!a.trim()&&l.length===0||h.isPending,className:"self-end",children:e.jsx(Or,{className:"h-4 w-4"})})]}),e.jsx(bVt,{value:l,onChange:o,disabled:h.isPending})]})]})]})]})]})})}return e.jsx(zs,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(ve,{className:"bg-gradient-to-br from-primary/10 via-primary/5 to-background border-primary/20",children:e.jsx(Me,{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(f4,{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(L$e,{trigger:e.jsxs(B,{size:"lg",className:"gap-2",children:[e.jsx(rn,{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(_a,{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(L$e,{trigger:e.jsxs(B,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(rn,{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(ve,{className:"border-dashed",children:e.jsxs(Me,{className:"text-center py-12",children:[e.jsx(Ou,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No tickets yet"}),e.jsx("p",{className:"text-muted-foreground",children:"You haven't submitted any support tickets. Use the button above to get started!"})]})}):e.jsx("div",{className:"space-y-3",children:c.map(p=>{const f=IB[p.status].icon;return e.jsx(ve,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>r(p),children:e.jsx(Me,{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(Oe,{variant:"outline",className:"text-xs",children:Pvt[p.category]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Hs(new Date(p.created_at),"MMM d, yyyy")})]})]}),e.jsxs(Oe,{className:IB[p.status].color,children:[e.jsx(f,{className:"h-3 w-3 mr-1"}),IB[p.status].label]})]})})},p.id)})})]})})}function fin({open:s,onOpenChange:t}){return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"max-w-3xl max-h-[90vh] overflow-hidden",children:[e.jsx(Os,{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(ga,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(Ds,{children:"Schedule Agent Onboarding"}),e.jsx(_r,{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 xin({open:s,onOpenChange:t}){const{brokerageId:n}=hs(),[r,a]=_.useState(""),[i,l]=_.useState([]),[o,c]=_.useState(!1),{data:d,isLoading:u}=at({queryKey:["brokerage-agents-for-onboarding",n],queryFn:async()=>{if(!n)return[];const{data:y,error:v}=await q.from("profiles").select("id, name, email").eq("brokerage_id",n).order("name",{ascending:!0});if(v)throw v;return y},enabled:s&&!!n}),h=d==null?void 0:d.filter(y=>y.name.toLowerCase().includes(r.toLowerCase())||y.email.toLowerCase().includes(r.toLowerCase())),m=y=>{l(v=>v.includes(y)?v.filter(g=>g!==y):[...v,y])},p=async()=>{if(i.length===0){se.error("Please select at least one agent");return}c(!0);try{const{data:y,error:v}=await q.functions.invoke("send-onboarding-link",{body:{agentIds:i}});if(v)throw v;se.success(`Onboarding link sent to ${i.length} agent${i.length>1?"s":""}`),l([]),t(!1)}catch(y){console.error("Error sending onboarding link:",y),se.error(y.message||"Failed to send onboarding link")}finally{c(!1)}},f=y=>{y||(l([]),a("")),t(y)};return e.jsx(Ls,{open:s,onOpenChange:f,children:e.jsxs(Ps,{className:"max-w-md",children:[e.jsx(Os,{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(Or,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(Ds,{children:"Send Onboarding Link"}),e.jsx(_r,{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(Lr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search agents...",value:r,onChange:y=>a(y.target.value),className:"pl-10"})]}),u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):(h==null?void 0:h.length)===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(In,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"No agents found"})]}):e.jsx(Ji,{className:"h-[300px] border rounded-lg",children:e.jsx("div",{className:"p-2 space-y-1",children:h==null?void 0:h.map(y=>e.jsxs("div",{className:"flex items-center gap-3 p-2 rounded-lg hover:bg-muted cursor-pointer",onClick:()=>m(y.id),children:[e.jsx($a,{checked:i.includes(y.id),onCheckedChange:()=>m(y.id)}),e.jsx(ja,{className:"h-8 w-8",children:e.jsx(Na,{className:"text-xs",children:y.name.split(" ").map(v=>v[0]).join("").toUpperCase()})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:y.name}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:y.email})]})]},y.id))})}),i.length>0&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:[i.length," agent",i.length>1?"s":""," selected"]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>f(!1),children:"Cancel"}),e.jsx(B,{onClick:p,disabled:i.length===0||o,children:o?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),"Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Or,{className:"h-4 w-4 mr-2"}),"Send Link"]})})]})]})})}function gin(){const[s,t]=_.useState(!1),[n,r]=_.useState(!1);return e.jsxs(e.Fragment,{children:[e.jsxs(ve,{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(In,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx(St,{children:"Agent Onboarding"}),e.jsx(kn,{children:"Schedule onboarding sessions for yourself or your agents"})]})]})}),e.jsx(Me,{children:e.jsxs("div",{className:"flex flex-wrap gap-4",children:[e.jsxs(B,{onClick:()=>t(!0),className:"flex items-center gap-2",children:[e.jsx(ga,{className:"h-4 w-4"}),"Schedule Agent Onboarding"]}),e.jsxs(B,{variant:"outline",onClick:()=>r(!0),className:"flex items-center gap-2",children:[e.jsx(Or,{className:"h-4 w-4"}),"Send New Agent Onboarding Link"]})]})})]}),e.jsx(fin,{open:s,onOpenChange:t}),e.jsx(xin,{open:n,onOpenChange:r})]})}function yin({open:s,onOpenChange:t}){return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"max-w-3xl max-h-[90vh] overflow-hidden",children:[e.jsx(Os,{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(Sy,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(Ds,{children:"Schedule Launch Meeting"}),e.jsx(_r,{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 vin(){const[s,t]=_.useState(!1);return e.jsxs(e.Fragment,{children:[e.jsxs(ve,{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(Sy,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx(St,{children:"Launch or ReLaunch Meeting"}),e.jsx(kn,{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(Me,{children:e.jsxs(B,{onClick:()=>t(!0),className:"flex items-center gap-2",children:[e.jsx(Sy,{className:"h-4 w-4"}),"Schedule Launch Meeting"]})})]}),e.jsx(yin,{open:s,onOpenChange:t})]})}function bin(){const s=Fn(),[t,n]=_.useState(""),[r,a]=_.useState(null),{data:i,isLoading:l}=at({queryKey:["brokerage-resources-published"],queryFn:async()=>{const{data:y,error:v}=await q.from("brokerage_resources").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(v)throw v;return y}}),{data:o}=at({queryKey:["brokerage-resource-categories"],queryFn:async()=>{const{data:y,error:v}=await q.from("brokerage_resource_categories").select("*").order("sort_order",{ascending:!0});if(v)throw v;return y}}),{data:c}=at({queryKey:["brokerage-resource-pdfs-all"],queryFn:async()=>{const{data:y,error:v}=await q.from("brokerage_resource_pdfs").select("resource_id");if(v)throw v;return y}}),{data:d}=at({queryKey:["brokerage-resource-videos-all"],queryFn:async()=>{const{data:y,error:v}=await q.from("brokerage_resource_videos").select("resource_id");if(v)throw v;return y}}),{data:u}=at({queryKey:["brokerage-resource-links-all"],queryFn:async()=>{const{data:y,error:v}=await q.from("brokerage_resource_links").select("resource_id");if(v)throw v;return y}}),h=i==null?void 0:i.filter(y=>{var b;const v=y.title.toLowerCase().includes(t.toLowerCase())||((b=y.description)==null?void 0:b.toLowerCase().includes(t.toLowerCase())),g=!r||y.category_id===r;return v&&g}),m=o==null?void 0:o.filter(y=>i==null?void 0:i.some(v=>v.category_id===y.id)),p=y=>{const v=(c==null?void 0:c.filter(j=>j.resource_id===y).length)||0,g=(d==null?void 0:d.filter(j=>j.resource_id===y).length)||0,b=(u==null?void 0:u.filter(j=>j.resource_id===y).length)||0;return{pdfCount:v,videoCount:g,linkCount:b}},f=y=>{s(`/brokerage-resources/${y}`)};return e.jsx(zs,{title:"Brokerage Resources",description:"Access exclusive resources for brokerage managers",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(gin,{}),e.jsx(vin,{}),e.jsxs("div",{className:"relative max-w-md",children:[e.jsx(Lr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search resources...",value:t,onChange:y=>n(y.target.value),className:"pl-10"})]}),m&&m.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(Oe,{variant:r===null?"default":"outline",className:"cursor-pointer",onClick:()=>a(null),children:"All"}),m.map(y=>e.jsx(Oe,{variant:r===y.id?"default":"outline",className:"cursor-pointer",onClick:()=>a(y.id),children:y.name},y.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((y,v)=>e.jsxs(ve,{children:[e.jsx(cn,{className:"h-40 w-full"}),e.jsx(bt,{children:e.jsx(cn,{className:"h-5 w-3/4"})}),e.jsxs(Me,{children:[e.jsx(cn,{className:"h-4 w-full mb-2"}),e.jsx(cn,{className:"h-4 w-2/3"})]})]},v))}):(h==null?void 0:h.length)===0?e.jsxs(ve,{className:"p-12 text-center",children:[e.jsx(Cx,{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(y=>{const{pdfCount:v,videoCount:g,linkCount:b}=p(y.id),j=o==null?void 0:o.find(S=>S.id===y.category_id);return e.jsxs(ve,{className:"overflow-hidden cursor-pointer hover:shadow-lg transition-shadow",onClick:()=>f(y.id),children:[y.preview_image_url?e.jsx("img",{src:y.preview_image_url,alt:y.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(Cx,{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(St,{className:"text-lg line-clamp-1",children:y.title}),j&&e.jsx(Oe,{variant:"secondary",className:"shrink-0 text-xs",children:j.name})]})}),e.jsxs(Me,{children:[y.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3",children:y.description}),e.jsxs("div",{className:"flex items-center gap-4 text-sm text-muted-foreground",children:[v>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Fr,{className:"h-4 w-4"}),v]}),g>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Kr,{className:"h-4 w-4"}),g]}),b>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Vc,{className:"h-4 w-4"}),b]})]})]})]},y.id)})})]})})}const _in=()=>{const{resourceId:s}=Li(),{data:t,isLoading:n}=at({queryKey:["brokerage-resource-detail",s],queryFn:async()=>{const{data:a,error:i}=await q.from("brokerage_resources").select("*").eq("id",s).eq("is_published",!0).single();if(i)throw i;const{data:l}=await q.from("brokerage_resource_pdfs").select("*").eq("resource_id",s).order("sort_order"),{data:o}=await q.from("brokerage_resource_videos").select("*").eq("resource_id",s).order("sort_order"),{data:c}=await q.from("brokerage_resource_links").select("*").eq("resource_id",s).order("sort_order");return{...a,pdfs:l||[],videos:o||[],links:c||[]}},enabled:!!s}),r=a=>a?a<1024?a+" B":a<1024*1024?(a/1024).toFixed(1)+" KB":(a/(1024*1024)).toFixed(1)+" MB":"";return n?e.jsx(zs,{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(zs,{title:t.title,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx(B,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(ir,{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(ve,{children:e.jsxs(Me,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Kr,{className:"h-4 w-4"}),"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(ve,{children:e.jsxs(Me,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Fr,{className:"h-4 w-4"}),"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(Fr,{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(li,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors"})]},a.id))})]})}),t.links&&t.links.length>0&&e.jsx(ve,{children:e.jsxs(Me,{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"}),"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(wr,{className:"h-4 w-4 text-primary"})}),e.jsx("div",{className:"font-medium text-sm",children:a.title})]}),e.jsx(wr,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors"})]},a.id))})]})})]})}):e.jsx(zs,{title:"Brokerage Resources",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Cx,{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(B,{asChild:!0,className:"mt-4",children:e.jsx(ir,{to:"/brokerage-resources",children:"Back to Resources"})})]})})};function win(){const{onlineUsers:s,totalOnline:t}=zLt(),{user:n}=hs();return e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(St,{className:"text-base flex items-center gap-2",children:[e.jsx(In,{className:"h-4 w-4"}),"Online Now"]}),e.jsxs(Oe,{variant:"secondary",className:"bg-green-100 text-green-700",children:[e.jsx(Uf,{className:"h-2 w-2 fill-green-500 text-green-500 mr-1"}),t," online"]})]})}),e.jsx(Me,{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(Ji,{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(ja,{className:"h-9 w-9",children:[e.jsx(pi,{src:r.avatarUrl,alt:r.name}),e.jsx(Na,{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 ",Ed(new Date(r.onlineSince),{addSuffix:!1})]})]})]},r.id)})})})})]})}const Lvt={users:{label:"Users & Access",sections:[{title:"Member Broadcasts",description:"Email a filtered group of members (paste HTML or write it)",icon:wh,path:"/admin/broadcasts",color:"bg-rose-500/10 text-rose-600"},{title:"Members",description:"Manage users, roles, and brokerage assignments",icon:In,path:"/admin/members",color:"bg-blue-500/10 text-blue-600"},{title:"Partnerships",description:"Manage partnership packages, rosters, and upgrade requests",icon:Vo,path:"/admin/partnerships",color:"bg-indigo-500/10 text-indigo-600"},{title:"Invite Codes",description:"Create and manage signup invite codes",icon:d7,path:"/admin/invite-codes",color:"bg-amber-500/10 text-amber-600"},{title:"Subscriptions",description:"Track and manage user subscriptions",icon:_y,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:jQ,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:Ep,path:"/admin/discounts",color:"bg-red-500/10 text-red-600"},{title:"Referral Program",description:"Track brokerage referrals and discounts",icon:bd,path:"/admin/referrals",color:"bg-teal-500/10 text-teal-600"},{title:"Teams",description:"Manage agent teams across all brokerages",icon:In,path:"/admin/members?tab=teams",color:"bg-violet-500/10 text-violet-600"},{title:"Prospector",description:"Send free trial invites and track conversions",icon:ku,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:Pl,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:wl,path:"/admin/coaching",color:"bg-gradient-to-br from-teal-500/20 to-cyan-500/10 text-teal-600"}]},content:{label:"Content",sections:[{title:"Blog",description:"Write founder articles, moderate comments, publish to /blog",icon:mN,path:"/admin/blog",color:"bg-amber-500/10 text-amber-600"},{title:"Manage Templates",description:"Upload and organize Canva templates",icon:Xc,path:"/admin/templates",color:"bg-pink-500/10 text-pink-600"},{title:"Manage Programs",description:"Cohorts, enrollments and delayed billing",icon:mm,path:"/admin/programs",color:"bg-emerald-500/10 text-emerald-600"},{title:"Manage Academy",description:"Upload videos and training content",icon:mm,path:"/admin/academy",color:"bg-indigo-500/10 text-indigo-600"},{title:"Manage Toolbox",description:"Create and manage resource kits",icon:Y4,path:"/admin/toolbox",color:"bg-orange-500/10 text-orange-600"},{title:"Social Swag",description:"Manage social media content and links",icon:un,path:"/admin/social-swag",color:"bg-fuchsia-500/10 text-fuchsia-600"},{title:"Social Swag 2.0",description:"New monthly social media images",icon:un,path:"/admin/social-swag-2",color:"bg-cyan-500/10 text-cyan-600"},{title:"Newsletters",description:"Manage monthly newsletter templates",icon:mN,path:"/admin/newsletters",color:"bg-violet-500/10 text-violet-600"},{title:"Newsletter Graphics",description:"Upload branded graphics agents drop into newsletters & emails",icon:mN,path:"/admin/newsletter-graphics",color:"bg-fuchsia-500/10 text-fuchsia-600"},{title:"Manage Events",description:"Create and publish events with Zoom integration",icon:pc,path:"/admin/events",color:"bg-green-500/10 text-green-600"},{title:"LevelUp Live",description:"Public streaming pages, invite links, and live leads",icon:Nv,path:"/admin/live",color:"bg-red-500/10 text-red-600"},{title:"Additional Services",description:"Manage additional service offerings",icon:Cx,path:"/admin/additional-services",color:"bg-lime-500/10 text-lime-600"},{title:"Brokerage Resources",description:"Manage resources for brokerage managers",icon:Cx,path:"/admin/brokerage-resources",color:"bg-slate-500/10 text-slate-600"},{title:"Agent Email Templates",description:"Manage curated email templates for agents",icon:ln,path:"/admin/agent-email-templates",color:"bg-rose-500/10 text-rose-600"},{title:"Mass Email Templates",description:"Create and manage shared campaign templates",icon:wh,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:XM,path:"/admin/dashboard-management",color:"bg-teal-500/10 text-teal-600"},{title:"Manage Apps",description:"Configure app tiles and access requirements",icon:Uw,path:"/admin/apps",color:"bg-purple-500/10 text-purple-600"},{title:"Email Templates",description:"Customize system email templates",icon:ln,path:"/admin/email-templates",color:"bg-sky-500/10 text-sky-600"},{title:"The LevelUp Brief",description:"Create popup briefs with videos, links, and polls",icon:wh,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:cN,path:"/admin/onboarding-checklist",color:"bg-emerald-500/10 text-emerald-600"},{title:"Marketplace",description:"Manage store categories, products, and orders",icon:K4,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:Vo,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:wl,path:"/admin/agent-points",color:"bg-amber-500/10 text-amber-600"},{title:"Integrations",description:"Connect Canva, Facebook & Instagram for platform-level features",icon:vd,path:"/admin/integrations",color:"bg-blue-500/10 text-blue-600"},{title:"Agent Cards",description:"Manage digital business cards for agents",icon:In,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:wh,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:Hi,path:"/admin/community",color:"bg-cyan-500/10 text-cyan-600"},{title:"Support Tickets",description:"View and respond to agent support requests",icon:qq,path:"/admin/support-tickets",color:"bg-rose-500/10 text-rose-600"},{title:"Wishlist",description:"Review and manage community feature requests",icon:mS,path:"/admin/wishlist",color:"bg-yellow-500/10 text-yellow-600"},{title:"Membership Reviews",description:"View member feedback and ratings",icon:Da,path:"/admin/membership-reviews",color:"bg-amber-500/10 text-amber-600"},{title:"Weekly Digest",description:"Configure automated weekly email digests",icon:ln,path:"/admin/weekly-digest",color:"bg-indigo-500/10 text-indigo-600"}]},insights:{label:"Insights",sections:[{title:"Analytics",description:"View activity logs and platform statistics",icon:bl,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:Sx,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:jv,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:mm,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:Do,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:Jr,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:Pl,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:Pl,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:jv,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:Fr,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:un,path:"/admin/listing-revival",color:"bg-gradient-to-br from-amber-500/20 to-yellow-500/10 text-amber-600"},{title:"Staging Studio",description:"Member conversions gallery, credits, subscriptions, and credit pack pricing",icon:hc,path:"/admin/staging-studio",color:"bg-gradient-to-br from-teal-500/20 to-emerald-500/10 text-teal-600"},{title:"Weekly Reels",description:"Manage Weekly Reels access, generation runs, and email delivery",icon:dm,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:Sx,path:"/admin/guest-book-analytics",color:"bg-gradient-to-br from-emerald-500/20 to-teal-500/10 text-emerald-600"}]},beta:{label:"🧪 Beta Lab",sections:[{title:"Social Post Generator",description:"Auto-generate branded social media posts from MLS listing data",icon:hc,path:"/admin/beta/social-post-generator",color:"bg-gradient-to-br from-fuchsia-500/20 to-pink-500/10 text-fuchsia-600"},{title:"Postcard Direct Mail",description:"Upload monthly postcard designs and manage agent direct mail via Postalytics",icon:ln,path:"/admin/beta/postcard-manager",color:"bg-gradient-to-br from-orange-500/20 to-amber-500/10 text-orange-600"},{title:"ReelFlow",description:"Turn property photos into cinematic video reels for social media",icon:YM,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:sl,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:Mq,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:Vo,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:Nl,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:Fr,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:Fr,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:Fr,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:yd,path:"/admin/mls-fee-tracker",color:"bg-gradient-to-br from-teal-500/20 to-cyan-500/10 text-teal-600"}]}};function Ivt(){const s=Fn();return console.log("[AdminDashboard] render"),e.jsx(zs,{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(Yr,{defaultValue:"users",className:"w-full",children:[e.jsx(Zr,{className:"w-full justify-start flex-wrap h-auto gap-1 bg-muted/50 p-1 overflow-x-auto",children:Object.entries(Lvt).map(([t,n])=>e.jsx(Ht,{value:t,className:"data-[state=active]:bg-background",children:n.label},t))}),Object.entries(Lvt).map(([t,n])=>e.jsx(Gt,{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(ve,{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(St,{className:"text-base",children:r.title})]}),e.jsx(Me,{className:"pt-0",children:e.jsx(kn,{className:"text-sm",children:r.description})})]},r.path))})},t))]}),e.jsx(win,{})]})})}const jin=()=>{const{isAdmin:s}=hs(),t=Fn(),[n,r]=_.useState([]),[a,i]=_.useState(!0),[l,o]=_.useState(!1),[c,d]=_.useState(null);_.useEffect(()=>{if(!s){t("/dashboard");return}u()},[s]);const u=async()=>{try{const{data:y,error:v}=await q.from("app_tiles").select("*").order("name");if(v)throw v;r(y||[])}catch(y){console.error("Error loading apps:",y),se.error("Failed to load apps")}finally{i(!1)}},h=async y=>{y.preventDefault();const v=new FormData(y.currentTarget),g={name:v.get("name"),description:v.get("description"),icon:v.get("icon"),app_id:v.get("app_id"),target_url:v.get("target_url"),required_tags:v.get("required_tags").split(",").map(b=>b.trim()).filter(Boolean)};try{if(c){const{error:b}=await q.from("app_tiles").update(g).eq("id",c.id);if(b)throw b;se.success("App updated successfully")}else{const{error:b}=await q.from("app_tiles").insert([g]);if(b)throw b;se.success("App created successfully")}o(!1),d(null),u()}catch(b){console.error("Error saving app:",b),se.error("Failed to save app")}},m=async y=>{if(await Xi("Are you sure you want to delete this app?"))try{const{error:v}=await q.from("app_tiles").delete().eq("id",y);if(v)throw v;se.success("App deleted successfully"),u()}catch(v){console.error("Error deleting app:",v),se.error("Failed to delete app")}},p=y=>{d(y),o(!0)},f=()=>{d(null),o(!0)};return a?e.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}):e.jsxs("div",{className:"min-h-screen bg-background",children:[e.jsx("header",{className:"border-b bg-card",children:e.jsx("div",{className:"container mx-auto px-4 py-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs(B,{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(Ls,{open:l,onOpenChange:o,children:[e.jsx(nl,{asChild:!0,children:e.jsxs(B,{onClick:f,children:[e.jsx(rn,{className:"mr-2 h-4 w-4"}),"Add App"]})}),e.jsxs(Ps,{className:"max-w-2xl",children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:c?"Edit App":"Create New App"}),e.jsx(_r,{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(J,{htmlFor:"name",children:"App Name"}),e.jsx(xe,{id:"name",name:"name",defaultValue:c==null?void 0:c.name,required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"app_id",children:"App ID"}),e.jsx(xe,{id:"app_id",name:"app_id",defaultValue:c==null?void 0:c.app_id,placeholder:"agent_connect",required:!0})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"description",children:"Description"}),e.jsx(Ms,{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(J,{htmlFor:"icon",children:"Icon (emoji)"}),e.jsx(xe,{id:"icon",name:"icon",defaultValue:c==null?void 0:c.icon,placeholder:"🚀",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"target_url",children:"Target URL"}),e.jsx(xe,{id:"target_url",name:"target_url",type:"url",defaultValue:c==null?void 0:c.target_url,required:!0})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"required_tags",children:"Required Tags (comma-separated)"}),e.jsx(xe,{id:"required_tags",name:"required_tags",defaultValue:c==null?void 0:c.required_tags.join(", "),placeholder:"levelup-member, agent-connect"})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx(B,{type:"submit",children:c?"Update":"Create"})]})]})]})]})]})})}),e.jsx("div",{className:"container mx-auto px-4 py-8",children:e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsx(St,{children:"Application Tiles"}),e.jsx(kn,{children:"Manage the apps that appear on the member dashboard"})]}),e.jsx(Me,{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(B,{onClick:f,children:[e.jsx(rn,{className:"mr-2 h-4 w-4"}),"Create First App"]})]}):e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"Icon"}),e.jsx(Pt,{children:"Name"}),e.jsx(Pt,{children:"App ID"}),e.jsx(Pt,{children:"Target URL"}),e.jsx(Pt,{children:"Tags"}),e.jsx(Pt,{className:"text-right",children:"Actions"})]})}),e.jsx(Ka,{children:n.map(y=>e.jsxs(pn,{children:[e.jsx(gt,{className:"text-2xl",children:y.icon}),e.jsx(gt,{className:"font-medium",children:y.name}),e.jsx(gt,{className:"font-mono text-sm",children:y.app_id}),e.jsx(gt,{className:"text-sm text-muted-foreground max-w-xs truncate",children:y.target_url}),e.jsx(gt,{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:y.required_tags.map(v=>e.jsx("span",{className:"text-xs bg-secondary text-secondary-foreground px-2 py-1 rounded",children:v},v))})}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>p(y),children:e.jsx(Ya,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>m(y.id),children:e.jsx(Sn,{className:"h-4 w-4"})})]})})]},y.id))})]})})]})})]})};function Wh({title:s,description:t,children:n}){return e.jsxs("div",{className:"space-y-4",children:[e.jsx(ir,{to:"/admin",children:e.jsxs(B,{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 Dvt=({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(Oe,{variant:"destructive",className:At("gap-1",t),children:[e.jsx(xl,{className:"h-3 w-3"}),"Trial Expired"]}):a<=1?e.jsxs(Oe,{variant:"destructive",className:At("gap-1",t),children:[e.jsx(Gr,{className:"h-3 w-3"}),"Trial: <1 day left"]}):a<=3?e.jsxs(Oe,{className:At("gap-1 bg-amber-500 hover:bg-amber-600",t),children:[e.jsx(Gr,{className:"h-3 w-3"}),"Trial: ",a," days left"]}):e.jsxs(Oe,{variant:"secondary",className:At("gap-1",t),children:[e.jsx(Gr,{className:"h-3 w-3"}),"Trial: ",a," days left"]})},wVt=({open:s,onOpenChange:t,brokerages:n,fixedBrokerageId:r,onSuccess:a})=>{const{toast:i}=vi(),l=_.useRef(null),[o,c]=_.useState([]),[d,u]=_.useState(""),[h,m]=_.useState(!1),[p,f]=_.useState("upload"),[y,v]=_.useState(null),g=()=>{c([]),u(""),f("upload"),v(null),l.current&&(l.current.value="")},b=()=>{g(),t(!1)},j=M=>{const I=M.split(` `).map($=>$.trim()).filter($=>$);if(I.length===0)return[];const D=I[0].toLowerCase(),V=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,G=[];for(const $ of V){const Y=($.includes(" ")?$.split(" "):$.split(",")).map(Z=>Z.trim().replace(/^["']|["']$/g,""));if(Y.length>=2){let Z="",ne="",ce="",ie="",te;if(Y.length===2){const be=Y[0].split(" ");Z=be[0]||"",ne=be.slice(1).join(" ")||"",ce=Y[1]}else if(Y.length===3)Z=Y[0],ne=Y[1],ce=Y[2];else if(Y.length===4)Z=Y[0],ne=Y[1],ce=Y[2],ie=Y[3];else if(Y.length>=5){Z=Y[0],ne=Y[1],ce=Y[2],ie=Y[3];const be=Y[4].toLowerCase();te=be==="true"||be==="yes"||be==="1"||be==="y"}const le=/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(ce);G.push({firstName:Z.trim(),lastName:ne.trim(),email:ce.trim().toLowerCase(),phone:ie.trim()||void 0,smsConsent:te,isValid:le&&Z.trim().length>0,error:le?Z.trim()?void 0:"Missing name":"Invalid email"})}}return G},S=M=>{var O;const I=(O=M.target.files)==null?void 0:O[0];if(!I)return;const D=new FileReader;D.onload=V=>{var H;const G=(H=V.target)==null?void 0:H.result,$=j(G);if($.length===0){i({title:"No data found",description:"The CSV file appears to be empty or in an unsupported format.",variant:"destructive"});return}c($),f("preview")},D.readAsText(I)},C=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 q.auth.getSession(),O=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/bulk-create-users",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${D==null?void 0:D.access_token}`},body:JSON.stringify({users:M.map(G=>({firstName:G.firstName,lastName:G.lastName,email:G.email,phone:G.phone,smsConsent:G.smsConsent})),brokerageId:I})}),V=await O.json();if(!O.ok)throw new Error(V.error||"Failed to import users");v(V),f("result"),V.created>0&&a(),i({title:"Import Complete",description:`${V.created} user(s) created successfully.${V.failed>0?` ${V.failed} failed.`:""}`})}catch(D){console.error("Import error:",D),i({title:"Import Failed",description:D.message||"Failed to import users",variant:"destructive"})}finally{m(!1)}},E=o.filter(M=>M.isValid).length,P=o.filter(M=>!M.isValid).length;return e.jsx(Ls,{open:s,onOpenChange:b,children:e.jsxs(Ps,{className:"max-w-2xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsxs(Os,{children:[e.jsxs(Ds,{className:"flex items-center gap-2",children:[e.jsx(uS,{className:"h-5 w-5"}),"Import Agents from CSV"]}),e.jsx(_r,{children:"Upload a CSV file with agent information. Each row should contain First Name, Last Name, and Email."})]}),p==="upload"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-8 text-center",children:[e.jsx("input",{type:"file",accept:".csv,.txt",ref:l,onChange:S,className:"hidden"}),e.jsx(Oa,{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(B,{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(J,{children:"Assign to Brokerage (optional)"}),e.jsxs(is,{value:d||"none",onValueChange:M=>u(M==="none"?"":M),children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Select a brokerage..."})}),e.jsxs(as,{children:[e.jsx(He,{value:"none",children:"No brokerage"}),n.map(M=>e.jsx(He,{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(Er,{className:"h-4 w-4 text-green-500"}),e.jsxs("span",{children:[E," 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(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{className:"bg-muted/30",children:[e.jsx(Pt,{children:"First Name"}),e.jsx(Pt,{children:"Last Name"}),e.jsx(Pt,{children:"Email"}),e.jsx(Pt,{children:"Phone"}),e.jsx(Pt,{children:"SMS"}),e.jsx(Pt,{children:"Status"})]})}),e.jsx(Ka,{children:o.slice(0,100).map((M,I)=>e.jsxs(pn,{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(Oe,{variant:"default",className:"bg-green-500/10 text-green-600",children:"Valid"}):e.jsx(Oe,{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"&&y&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx(Er,{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:[y.created," agent(s) created and invited"]}),y.failed>0&&e.jsxs("p",{className:"text-destructive mt-1",children:[y.failed," failed to create"]})]}),y.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:[y.errors.slice(0,10).map((M,I)=>e.jsxs("li",{children:["• ",M]},I)),y.errors.length>10&&e.jsxs("li",{children:["...and ",y.errors.length-10," more"]})]})]})]}),e.jsxs(yr,{children:[p==="upload"&&e.jsx(B,{variant:"outline",onClick:b,children:"Cancel"}),p==="preview"&&e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"outline",onClick:g,children:"Back"}),e.jsx(B,{onClick:C,disabled:h||E===0,children:h?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}),"Importing..."]}):`Import ${E} Agent${E!==1?"s":""}`})]}),p==="result"&&e.jsx(B,{onClick:b,children:"Done"})]})]})})};function qh({sortKey:s,currentSortKey:t,currentDirection:n,onSort:r,children:a,className:i,...l}){const o=t===s;return e.jsx(Pt,{className:At("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(zf,{className:"h-3.5 w-3.5 shrink-0"}):e.jsx(Lg,{className:"h-3.5 w-3.5 shrink-0 opacity-40"})]})})}function wae(s=null,t=null){const[n,r]=_.useState(s),[a,i]=_.useState(t),l=_.useCallback(c=>{n===c?a==="asc"?i("desc"):a==="desc"?(r(null),i(null)):i("asc"):(r(c),i("asc"))},[n,a]),o=_.useCallback((c,d)=>{if(!n||!a||!d[n])return c;const u=d[n];return[...c].sort((h,m)=>{const p=u(h),f=u(m);if(p==null&&f==null)return 0;if(p==null)return 1;if(f==null)return-1;let y;return typeof p=="string"&&typeof f=="string"?y=p.localeCompare(f,void 0,{sensitivity:"base"}):y=p-f,a==="asc"?y:-y})},[n,a]);return{sortKey:n,sortDirection:a,handleSort:l,sortData:o}}const Nin=[{type:"custom",title:"Great job!",message:"Keep up the amazing work!",icon:Da},{type:"custom",title:"You're on fire!",message:"Your dedication is inspiring!",icon:wl},{type:"custom",title:"Congratulations!",message:"You earned this celebration!",icon:Ex}];function jVt({open:s,onOpenChange:t,userId:n,userName:r}){const[a,i]=_.useState("custom"),[l,o]=_.useState(""),[c,d]=_.useState(""),u=QTs(),h=p=>{i(p.type),o(p.title),d(p.message)},m=async p=>{if(p.preventDefault(),!l.trim()){ia({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}),ia({title:"Celebration sent! 🎉",description:`${r} will see confetti on their next visit!`}),t(!1),o(""),d(""),i("custom")}catch{ia({title:"Error",description:"Failed to send celebration",variant:"destructive"})}};return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"sm:max-w-md",children:[e.jsxs(Os,{children:[e.jsxs(Ds,{className:"flex items-center gap-2",children:[e.jsx(Ex,{className:"h-5 w-5 text-primary"}),"Send Celebration to ",r]}),e.jsx(_r,{children:"They'll see confetti and this message next time they log in!"})]}),e.jsxs("div",{className:"mb-4",children:[e.jsx(J,{className:"text-sm text-muted-foreground mb-2 block",children:"Quick presets:"}),e.jsx("div",{className:"flex gap-2 flex-wrap",children:Nin.map((p,f)=>e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>h(p),className:"text-xs",children:[e.jsx(p.icon,{className:"h-3 w-3 mr-1"}),p.title]},f))})]}),e.jsxs("form",{onSubmit:m,className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(J,{htmlFor:"type",children:"Celebration Type"}),e.jsxs(is,{value:a,onValueChange:p=>i(p),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"custom",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Da,{className:"h-4 w-4"})," Custom"]})}),e.jsx(He,{value:"points_earned",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(wl,{className:"h-4 w-4"})," Points Earned"]})}),e.jsx(He,{value:"listing_created",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Jr,{className:"h-4 w-4"})," Listing Created"]})}),e.jsx(He,{value:"deal_closed",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(yd,{className:"h-4 w-4"})," Deal Closed"]})})]})]})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"title",children:"Title *"}),e.jsx(xe,{id:"title",value:l,onChange:p=>o(p.target.value),placeholder:"e.g., Congratulations!",maxLength:100})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"message",children:"Message (optional)"}),e.jsx(Ms,{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(B,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{type:"submit",disabled:u.isPending,children:[e.jsx(Ex,{className:"h-4 w-4 mr-2"}),u.isPending?"Sending...":"Send Celebration"]})]})]})]})})}const l9e={points_earned:{label:"Points Earned",icon:wl,color:"bg-yellow-500"},listing_created:{label:"Listing Created",icon:Jr,color:"bg-blue-500"},deal_closed:{label:"Deal Closed",icon:yd,color:"bg-green-500"},custom:{label:"Custom",icon:un,color:"bg-purple-500"}};function kin(){const[s,t]=_.useState(""),[n,r]=_.useState("all"),[a,i]=_.useState("all"),{data:l=[],isLoading:o}=at({queryKey:["admin-celebrations"],queryFn:async()=>{const{data:u,error:h}=await q.from("celebration_queue").select("*").order("created_at",{ascending:!1}).limit(500);if(h)throw h;const m=[...new Set([...u.map(y=>y.user_id),...u.map(y=>y.created_by).filter(Boolean)])],{data:p}=await q.from("profiles").select("id, name, email").in("id",m),f=new Map((p==null?void 0:p.map(y=>[y.id,y]))||[]);return u.map(y=>{var v,g,b;return{...y,user_name:((v=f.get(y.user_id))==null?void 0:v.name)||"Unknown",user_email:((g=f.get(y.user_id))==null?void 0:g.email)||"",creator_name:y.created_by?((b=f.get(y.created_by))==null?void 0:b.name)||"System":"Auto-triggered"}})}}),c=l.filter(u=>{var f,y;const h=((f=u.user_name)==null?void 0:f.toLowerCase().includes(s.toLowerCase()))||((y=u.user_email)==null?void 0:y.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(l9e).reduce((u,h)=>(u[h]=l.filter(m=>m.celebration_type===h).length,u),{})};return o?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Ct,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-4",children:[e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-2",children:e.jsx(St,{className:"text-sm font-medium",children:"Total Celebrations"})}),e.jsx(Me,{children:e.jsx("div",{className:"text-2xl font-bold",children:d.total})})]}),e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-2",children:e.jsx(St,{className:"text-sm font-medium text-green-600",children:"Seen"})}),e.jsx(Me,{children:e.jsx("div",{className:"text-2xl font-bold text-green-600",children:d.seen})})]}),e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-2",children:e.jsx(St,{className:"text-sm font-medium text-orange-600",children:"Pending"})}),e.jsx(Me,{children:e.jsx("div",{className:"text-2xl font-bold text-orange-600",children:d.unseen})})]}),e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-2",children:e.jsx(St,{className:"text-sm font-medium text-purple-600",children:"Custom Sent"})}),e.jsx(Me,{children:e.jsx("div",{className:"text-2xl font-bold text-purple-600",children:d.byType.custom||0})})]})]}),e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(Ex,{className:"h-5 w-5"}),"Celebration History"]}),e.jsx(kn,{children:"View all celebrations awarded to agents"})]}),e.jsxs(Me,{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(Lr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search by agent name, email, or title...",value:s,onChange:u=>t(u.target.value),className:"pl-9"})]}),e.jsxs(is,{value:n,onValueChange:r,children:[e.jsx(rs,{className:"w-[180px]",children:e.jsx(ls,{placeholder:"Filter by type"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Types"}),Object.entries(l9e).map(([u,h])=>e.jsx(He,{value:u,children:h.label},u))]})]}),e.jsxs(is,{value:a,onValueChange:i,children:[e.jsx(rs,{className:"w-[140px]",children:e.jsx(ls,{placeholder:"Status"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Status"}),e.jsx(He,{value:"seen",children:"Seen"}),e.jsx(He,{value:"unseen",children:"Pending"})]})]})]}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"Type"}),e.jsx(Pt,{children:"Agent"}),e.jsx(Pt,{children:"Title"}),e.jsx(Pt,{children:"Points"}),e.jsx(Pt,{children:"Created By"}),e.jsx(Pt,{children:"Created"}),e.jsx(Pt,{children:"Status"})]})}),e.jsx(Ka,{children:c.length===0?e.jsx(pn,{children:e.jsx(gt,{colSpan:7,className:"text-center py-8 text-muted-foreground",children:"No celebrations found"})}):c.map(u=>{const h=l9e[u.celebration_type],m=h.icon;return e.jsxs(pn,{children:[e.jsx(gt,{children:e.jsxs(Oe,{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(Oe,{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(Oe,{variant:"outline",className:"bg-green-50 text-green-700 border-green-200",children:"Seen"}):e.jsx(Oe,{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 Sin=()=>{const{user:s}=hs(),{toast:t}=vi(),[n,r]=_.useState([]),[a,i]=_.useState(!0),[l,o]=_.useState(!1),[c,d]=_.useState("all"),[u,h]=_.useState("all"),[m,p]=_.useState("new"),[f,y]=_.useState(new Set),v=_.useCallback(async()=>{try{i(!0);const{data:G,error:$}=await q.from("profiles").select("id, name, email, phone, is_trial, trial_started_at, trial_expires_at, subscription_status, subscription_end_date, converted_from_trial_at, created_at, last_login").or("is_trial.eq.true,subscription_status.eq.trialing,converted_from_trial_at.not.is.null");if($)throw $;const{data:H,error:Y}=await q.from("trial_email_exports").select("user_id");if(Y)throw Y;const Z=new Set((H||[]).map(ce=>ce.user_id)),ne=(G||[]).map(ce=>({...ce,converted_from_trial_at:ce.converted_from_trial_at??null,already_exported:Z.has(ce.id)}));ne.sort((ce,ie)=>new Date(ie.created_at).getTime()-new Date(ce.created_at).getTime()),r(ne)}catch(G){console.error("Error loading trial users:",G),t({title:"Error",description:"Failed to load trial users",variant:"destructive"})}finally{i(!1)}},[t]);_.useEffect(()=>{v()},[v]);const g=G=>G.trial_started_at?"ghl":"stripe",b=G=>G.trial_expires_at?G.trial_expires_at:G.subscription_end_date?G.subscription_end_date:null,j=G=>G.converted_from_trial_at!==null,S=G=>{if(j(G))return!1;const $=b(G);return $?new Date($).getTime()<=Date.now():!1},C=n.filter(G=>!(c!=="all"&&g(G)!==c||u==="active"&&(S(G)||j(G))||u==="expired"&&!S(G)||u==="converted"&&!j(G)||m==="new"&&G.already_exported||m==="exported"&&!G.already_exported)),E=()=>{f.size===C.length?y(new Set):y(new Set(C.map(G=>G.id)))},P=G=>{const $=new Set(f);$.has(G)?$.delete(G):$.add(G),y($)},M=async()=>{if(f.size===0){t({title:"No users selected",description:"Select users to export",variant:"destructive"});return}o(!0);try{const G=n.filter(te=>f.has(te.id)),$="First Name,Last Name,Email,Phone,Trial Type,Status,Signup Date,Expiry Date",H=G.map(te=>{const ae=(te.name||"").split(" "),le=ae[0]||"",be=ae.slice(1).join(" ")||"",me=g(te)==="stripe"?"Credit Card Trial":"Free Trial (No CC)",he=j(te)?"Converted":S(te)?"Expired":"Active",pe=te.created_at?new Date(te.created_at).toLocaleDateString():"",Ce=b(te)?new Date(b(te)).toLocaleDateString():"";return`"${le}","${be}","${te.email}","${te.phone||""}","${me}","${he}","${pe}","${Ce}"`}),Y=[$,...H].join(` `),Z=new Blob([Y],{type:"text/csv"}),ne=URL.createObjectURL(Z),ce=document.createElement("a");ce.href=ne,ce.download=`trial-users-${new Date().toISOString().split("T")[0]}.csv`,ce.click(),URL.revokeObjectURL(ne);const ie=G.filter(te=>!te.already_exported).map(te=>({user_id:te.id,exported_by:s.id}));if(ie.length>0){const{error:te}=await q.from("trial_email_exports").upsert(ie,{onConflict:"user_id"});te&&console.error("Error marking exports:",te)}t({title:"Export complete",description:`Downloaded ${G.length} trial user(s). ${ie.length} newly marked as exported.`}),y(new Set),v()}catch(G){console.error("Export error:",G),t({title:"Error",description:"Failed to export",variant:"destructive"})}finally{o(!1)}},I=n.filter(G=>!G.already_exported).length,D=n.filter(G=>G.already_exported).length,O=n.filter(G=>j(G)).length,V=n.filter(G=>!S(G)&&!j(G)).length;return a?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-5 gap-4",children:[e.jsx(ve,{children:e.jsxs(bt,{className:"pb-2",children:[e.jsx(kn,{children:"Total"}),e.jsx(St,{className:"text-2xl",children:n.length})]})}),e.jsx(ve,{children:e.jsxs(bt,{className:"pb-2",children:[e.jsx(kn,{children:"New (Not Exported)"}),e.jsx(St,{className:"text-2xl text-green-600",children:I})]})}),e.jsx(ve,{children:e.jsxs(bt,{className:"pb-2",children:[e.jsx(kn,{children:"Active Trials"}),e.jsx(St,{className:"text-2xl",children:V})]})}),e.jsx(ve,{children:e.jsxs(bt,{className:"pb-2",children:[e.jsx(kn,{children:"Converted 🎉"}),e.jsx(St,{className:"text-2xl text-primary",children:O})]})}),e.jsx(ve,{children:e.jsxs(bt,{className:"pb-2",children:[e.jsx(kn,{children:"Already Exported"}),e.jsx(St,{className:"text-2xl text-muted-foreground",children:D})]})})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs(is,{value:m,onValueChange:G=>p(G),children:[e.jsx(rs,{className:"w-[160px]",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Users"}),e.jsx(He,{value:"new",children:"New Only"}),e.jsx(He,{value:"exported",children:"Already Exported"})]})]}),e.jsxs(is,{value:c,onValueChange:G=>d(G),children:[e.jsx(rs,{className:"w-[180px]",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Trial Types"}),e.jsx(He,{value:"stripe",children:"Credit Card Trial"}),e.jsx(He,{value:"ghl",children:"Free Trial (No CC)"})]})]}),e.jsxs(is,{value:u,onValueChange:G=>h(G),children:[e.jsx(rs,{className:"w-[160px]",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Statuses"}),e.jsx(He,{value:"active",children:"Active Trial"}),e.jsx(He,{value:"expired",children:"Expired"}),e.jsx(He,{value:"converted",children:"Converted ✓"})]})]}),e.jsx("div",{className:"ml-auto",children:e.jsxs(B,{onClick:M,disabled:l||f.size===0,children:[l?e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(li,{className:"h-4 w-4 mr-2"}),"Export Selected (",f.size,")"]})})]}),e.jsx("div",{className:"border rounded-lg",children:e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Pt,{className:"w-[40px]",children:e.jsx($a,{checked:C.length>0&&f.size===C.length,onCheckedChange:E})}),e.jsx(Pt,{children:"Name"}),e.jsx(Pt,{children:"Email"}),e.jsx(Pt,{children:"Trial Type"}),e.jsx(Pt,{children:"Status"}),e.jsx(Pt,{children:"Signup Date"}),e.jsx(Pt,{children:"Last Login"}),e.jsx(Pt,{children:"Expires / Renews"}),e.jsx(Pt,{children:"Exported"})]})}),e.jsx(Ka,{children:C.length===0?e.jsx(pn,{children:e.jsx(gt,{colSpan:9,className:"text-center py-8 text-muted-foreground",children:"No trial users match the current filters"})}):C.map(G=>{const $=g(G),H=j(G),Y=S(G),Z=b(G);return e.jsxs(pn,{className:`hover:bg-muted/30 ${H?"bg-primary/5":""}`,children:[e.jsx(gt,{children:e.jsx($a,{checked:f.has(G.id),onCheckedChange:()=>P(G.id)})}),e.jsx(gt,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[G.name,H&&e.jsx(Nl,{className:"h-3.5 w-3.5 text-primary"})]})}),e.jsx(gt,{className:"text-muted-foreground",children:G.email}),e.jsx(gt,{children:$==="stripe"?e.jsxs(Oe,{variant:"outline",className:"gap-1",children:[e.jsx(_y,{className:"h-3 w-3"}),"Credit Card"]}):e.jsxs(Oe,{variant:"secondary",className:"gap-1",children:[e.jsx(ln,{className:"h-3 w-3"}),"Free (No CC)"]})}),e.jsx(gt,{children:H?e.jsxs(Oe,{className:"bg-primary/10 text-primary hover:bg-primary/20 gap-1",children:[e.jsx(Nl,{className:"h-3 w-3"}),"Converted"]}):Y?e.jsx(Oe,{variant:"destructive",children:"Expired"}):e.jsx(Oe,{className:"bg-green-500/10 text-green-600 hover:bg-green-500/20",children:"Active Trial"})}),e.jsx(gt,{className:"text-sm",children:G.created_at?new Date(G.created_at).toLocaleDateString():"—"}),e.jsx(gt,{className:"text-sm",children:G.last_login?e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{children:new Date(G.last_login).toLocaleDateString()}),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(G.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:H&&Z?e.jsxs("span",{className:"text-muted-foreground",children:["Renews ",new Date(Z).toLocaleDateString()]}):Z?new Date(Z).toLocaleDateString():"—"}),e.jsx(gt,{children:G.already_exported?e.jsx(Er,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Oe,{variant:"outline",className:"text-green-600 border-green-300",children:"New"})})]},G.id)})})]})}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Showing ",C.length," of ",n.length," trial users · ",O," converted to paid"]})]})},Cin=s=>s==null?'""':`"${String(s).replace(/"/g,'""')}"`,Ain=()=>{const[s,t]=_.useState([]),[n,r]=_.useState(!0);_.useEffect(()=>{(async()=>{const{data:l,error:o}=await q.from("user_deletion_log").select("*").order("created_at",{ascending:!1});!o&&l&&t(l),r(!1)})()},[]);const a=()=>{if(s.length===0){se.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(Cin).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),se.success(`Exported ${s.length} deletion record(s)`)};return n?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):s.length===0?e.jsx(ve,{children:e.jsxs(Me,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(Sn,{className:"h-10 w-10 mx-auto mb-3 opacity-40"}),e.jsx("p",{children:"No deletion records yet"})]})}):e.jsxs(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between",children:[e.jsx(St,{className:"text-lg",children:"User Deletion History"}),e.jsxs(B,{variant:"outline",size:"sm",onClick:a,children:[e.jsx(li,{className:"h-4 w-4 mr-2"}),"Export CSV"]})]}),e.jsx(Me,{children:e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"Date"}),e.jsx(Pt,{children:"User"}),e.jsx(Pt,{children:"Email"}),e.jsx(Pt,{children:"Brokerage"}),e.jsx(Pt,{children:"Type"}),e.jsx(Pt,{children:"Deleted By"})]})}),e.jsx(Ka,{children:s.map(i=>e.jsxs(pn,{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(Oe,{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))})]})})]})},SC=s=>{const{user:t}=hs(),n=Bt(),r=at({queryKey:["teams",s],queryFn:async()=>{let h=q.from("teams").select("*").order("created_at",{ascending:!1});s&&(h=h.eq("brokerage_id",s));const{data:m,error:p}=await h;if(p)throw p;return m||[]},enabled:!!t}),a=h=>at({queryKey:["team-members",h],queryFn:async()=>{const{data:m,error:p}=await q.from("team_members").select("*").eq("team_id",h).order("role",{ascending:!0});if(p)throw p;const f=(m||[]).map(g=>g.user_id),{data:y}=await q.from("profiles").select("id, name, email, avatar_url").in("id",f),v=new Map((y||[]).map(g=>[g.id,g]));return(m||[]).map(g=>({...g,profile:v.get(g.user_id)||null}))},enabled:!!h}),i=mt({mutationFn:async h=>{const m={name:h.name,created_by:t.id,description:h.description,contact_visibility:h.contact_visibility,lead_pond_enabled:h.lead_pond_enabled,shared_assets_enabled:h.shared_assets_enabled};h.brokerage_id&&(m.brokerage_id=h.brokerage_id);const{data:p,error:f}=await q.from("teams").insert(m).select().single();if(f)throw f;return p},onSuccess:()=>{n.invalidateQueries({queryKey:["teams"]}),se.success("Team created!")},onError:h=>{se.error("Failed to create team: "+h.message)}}),l=mt({mutationFn:async({id:h,...m})=>{const{data:p,error:f}=await q.from("teams").update(m).eq("id",h).select().single();if(f)throw f;return p},onSuccess:()=>{n.invalidateQueries({queryKey:["teams"]}),se.success("Team updated")},onError:h=>{se.error("Failed to update team: "+h.message)}}),o=mt({mutationFn:async h=>{const{error:m}=await q.from("teams").delete().eq("id",h);if(m)throw m},onSuccess:()=>{n.invalidateQueries({queryKey:["teams"]}),se.success("Team deleted")},onError:h=>{se.error("Failed to delete team: "+h.message)}}),c=mt({mutationFn:async h=>{const{data:m,error:p}=await q.from("team_members").insert({team_id:h.team_id,user_id:h.user_id,role:h.role||"team_member"}).select().single();if(p)throw p.message.includes("duplicate")||p.message.includes("unique")?new Error("This agent is already on this team."):p;return m},onSuccess:(h,m)=>{n.invalidateQueries({queryKey:["team-members",m.team_id]}),se.success("Member added to team")},onError:h=>{se.error(h.message)}}),d=mt({mutationFn:async h=>{const{error:m}=await q.from("team_members").delete().eq("id",h.member_id);if(m)throw m},onSuccess:(h,m)=>{n.invalidateQueries({queryKey:["team-members",m.team_id]}),se.success("Member removed from team")},onError:h=>{se.error("Failed to remove member: "+h.message)}}),u=mt({mutationFn:async h=>{const{error:m}=await q.from("team_members").update({role:h.role}).eq("id",h.member_id);if(m)throw m},onSuccess:(h,m)=>{n.invalidateQueries({queryKey:["team-members",m.team_id]}),se.success("Member role updated")},onError:h=>{se.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}},$tt=s=>{const t=Bt(),n=at({queryKey:["team-ponds",s],queryFn:async()=>{const{data:o,error:c}=await q.rpc("get_team_ponds",{_team_id:s});if(c)throw c;return o||[]},enabled:!!s}),r=()=>{t.invalidateQueries({queryKey:["team-ponds"]}),t.invalidateQueries({queryKey:["lead-pond"]})},a=mt({mutationFn:async o=>{const{data:c,error:d}=await q.from("team_ponds").insert({team_id:s,name:o.name,description:o.description||null}).select().single();if(d)throw d;return c},onSuccess:()=>{r(),se.success("Pond created")},onError:o=>se.error(o.message)}),i=mt({mutationFn:async({id:o,...c})=>{const{error:d}=await q.from("team_ponds").update(c).eq("id",o);if(d)throw d},onSuccess:()=>{r(),se.success("Pond updated")},onError:o=>se.error(o.message)}),l=mt({mutationFn:async o=>{const{error:c}=await q.from("team_ponds").delete().eq("id",o);if(c)throw c},onSuccess:()=>{r(),se.success("Pond deleted")},onError:o=>se.error(o.message)});return{ponds:n.data||[],isLoading:n.isLoading,createPond:a,updatePond:i,deletePond:l}},Ein=s=>{const t=Bt(),n=at({queryKey:["pond-assignments",s],queryFn:async()=>{const{data:a,error:i}=await q.from("team_pond_members").select("id, user_id").eq("pond_id",s);if(i)throw i;return a||[]},enabled:!!s}),r=mt({mutationFn:async a=>{if(a.assigned){const{error:i}=await q.from("team_pond_members").insert({pond_id:s,user_id:a.user_id});if(i&&!i.message.includes("duplicate"))throw i}else{const{error:i}=await q.from("team_pond_members").delete().eq("pond_id",s).eq("user_id",a.user_id);if(i)throw i}},onSuccess:()=>{t.invalidateQueries({queryKey:["pond-assignments",s]}),t.invalidateQueries({queryKey:["team-ponds"]}),t.invalidateQueries({queryKey:["lead-pond"]})},onError:a=>se.error(a.message)});return{assignedUserIds:(n.data||[]).map(a=>a.user_id),isLoading:n.isLoading,setAssigned:r}},Tin=({pond:s,teamId:t})=>{const{useTeamMembers:n}=SC(),{data:r=[],isLoading:a}=n(t),{assignedUserIds:i,isLoading:l,setAssigned:o}=Ein(s.id);return a||l?e.jsx(cn,{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(In,{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($a,{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(Oe,{variant:"secondary",className:"ml-auto text-[10px]",children:"Leader"})]},c.id)})})]})},NVt=({teamId:s})=>{const{ponds:t,isLoading:n,createPond:r,updatePond:a,deletePond:i}=$tt(s),[l,o]=_.useState(!1),[c,d]=_.useState(""),[u,h]=_.useState(""),[m,p]=_.useState(null),[f,y]=_.useState(null),v=async()=>{c.trim()&&(await r.mutateAsync({name:c.trim(),description:u.trim()}),d(""),h(""),o(!1))};return e.jsxs(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-start justify-between gap-4 space-y-0",children:[e.jsxs("div",{children:[e.jsx(St,{className:"text-lg",children:"Lead Ponds"}),e.jsx(kn,{children:"Create multiple ponds (by area, source, or specialty) and assign which agents can see each one."})]}),e.jsxs(B,{size:"sm",onClick:()=>o(!0),children:[e.jsx(rn,{className:"mr-1 h-4 w-4"})," New Pond"]})]}),e.jsxs(Me,{className:"space-y-3",children:[n&&e.jsx(cn,{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(g=>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(m1,{className:"h-4 w-4 text-primary"}),e.jsx("p",{className:"font-medium",children:g.name}),g.is_default&&e.jsx(Oe,{variant:"secondary",className:"text-[10px]",children:"Default"})]}),g.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:g.description}),e.jsxs("div",{className:"mt-1 flex flex-wrap gap-2 text-[11px] text-muted-foreground",children:[e.jsxs("span",{children:[g.available_count," available"]}),e.jsx("span",{children:"·"}),e.jsxs("span",{children:[g.claimed_count," claimed"]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs(B,{size:"sm",variant:"ghost",onClick:()=>y(f===g.id?null:g.id),children:[e.jsx(In,{className:"mr-1 h-3.5 w-3.5"}),f===g.id?"Hide agents":"Assign agents"]}),e.jsx(B,{size:"icon",variant:"ghost",onClick:()=>p(g),children:e.jsx(Ya,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",onClick:()=>{confirm(`Delete "${g.name}"? Leads in this pond will no longer be shared.`)&&i.mutate(g.id)},children:e.jsx(Sn,{className:"h-3.5 w-3.5 text-destructive"})})]})]}),f===g.id&&e.jsx(Tin,{pond:g,teamId:s})]},g.id))]}),e.jsx(Ls,{open:l,onOpenChange:o,children:e.jsxs(Ps,{children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"New Lead Pond"}),e.jsx(_r,{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(J,{children:"Pond name"}),e.jsx(xe,{value:c,onChange:g=>d(g.target.value),placeholder:"e.g. Northland Buyers"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Description (optional)"}),e.jsx(xe,{value:u,onChange:g=>h(g.target.value),placeholder:"What kind of leads go in this pond?"})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx(B,{onClick:v,disabled:!c.trim()||r.isPending,children:"Create Pond"})]})]})}),e.jsx(Ls,{open:!!m,onOpenChange:g=>!g&&p(null),children:e.jsxs(Ps,{children:[e.jsx(Os,{children:e.jsx(Ds,{children:"Edit Pond"})}),m&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Pond name"}),e.jsx(xe,{value:m.name,onChange:g=>p({...m,name:g.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Description"}),e.jsx(xe,{value:m.description||"",onChange:g=>p({...m,description:g.target.value})})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>p(null),children:"Cancel"}),e.jsx(B,{onClick:async()=>{m&&(await a.mutateAsync({id:m.id,name:m.name,description:m.description||""}),p(null))},disabled:a.isPending,children:"Save"})]})]})})]})},Min=(s,t=!0)=>at({queryKey:["lead-pond-activity",s],queryFn:async()=>{const{data:n,error:r}=await q.rpc("get_lead_pond_activity",{_lead_pond_id:s});if(r)throw r;return n||[]},enabled:!!s&&t}),Pin=()=>{const{user:s}=hs();return at({queryKey:["team-contacts",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.rpc("get_team_contacts",{_user_id:s.id});if(n)throw n;return t||[]},enabled:!!s})},kVt=(s,t)=>{const{user:n}=hs(),r=Bt(),a=at({queryKey:["lead-pond",s,t||"all"],queryFn:async()=>{const{data:c,error:d}=await q.rpc("get_team_lead_pond",{_team_id:s,_pond_id:t||null});if(d)throw d;return(c||[]).map(u=>({id:u.id,team_id:u.team_id,pond_id:u.pond_id,pond_name:u.pond_name,contact_id:u.contact_id,added_by:u.added_by,claimed_by:u.claimed_by,claimed_at:u.claimed_at,returned_at:u.returned_at,notes:u.notes,created_at:u.created_at,status:u.claimed_by?"claimed":"available",contact:{first_name:u.first_name,last_name:u.last_name,email:u.email,phone:u.phone,address:u.address,lead_source:u.lead_source,notes:u.contact_notes},contributor:{name:u.contributor_name,avatar_url:u.contributor_avatar_url},claimer:u.claimed_by?{name:u.claimer_name,avatar_url:u.claimer_avatar_url}:null,touch_count:u.touch_count??0,last_activity_at:u.last_activity_at,can_view_activity:!!u.can_view_activity}))},enabled:!!s&&!!n}),i=mt({mutationFn:async c=>{const{data:d,error:u}=await q.rpc("add_to_lead_pond",{_contact_id:c.contact_id,_team_id:c.team_id,_notes:c.notes||null,_pond_id:c.pond_id||null});if(u)throw u;return d},onSuccess:()=>{r.invalidateQueries({queryKey:["lead-pond"]}),se.success("Contact added to Lead Pond")},onError:c=>{se.error(c.message)}}),l=mt({mutationFn:async c=>{const{error:d}=await q.rpc("claim_lead_pond_contact",{_lead_pond_id:c});if(d)throw d},onSuccess:()=>{r.invalidateQueries({queryKey:["lead-pond"]}),r.invalidateQueries({queryKey:["innercircle-contacts"]}),r.invalidateQueries({queryKey:["contacts"]}),r.invalidateQueries({queryKey:["contact-custom-tags"]}),se.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=>{se.error(c.message)}}),o=mt({mutationFn:async c=>{const{error:d}=await q.rpc("return_lead_pond_contact",{_lead_pond_id:c});if(d)throw d},onSuccess:()=>{r.invalidateQueries({queryKey:["lead-pond"]}),se.success("Lead returned to pond")},onError:c=>{se.error(c.message)}});return{leadPondItems:a.data||[],isLoading:a.isLoading,addToLeadPond:i,claimLead:l,returnLead:o}},Lin=(s,t,n=100)=>at({queryKey:["team-pond-history",s,t||"all",n],queryFn:async()=>{const{data:r,error:a}=await q.rpc("get_team_pond_history",{_team_id:s,_pond_id:t||null,_limit:n});if(a)throw a;return r||[]},enabled:!!s}),Iin=()=>{const s=Bt();return mt({mutationFn:async t=>{const{data:n,error:r}=await q.rpc("transfer_contact",{_contact_id:t.contactId,_to_user_id:t.toUserId,_notes:t.notes||null});if(r)throw r;const a=n;if(!a.success)throw new Error(a.error);return a},onSuccess:()=>{s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["team-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),se.success("Contact transferred successfully")},onError:t=>{se.error(t.message||"Failed to transfer contact")}})};function SVt({open:s,onOpenChange:t,contactIds:n,contactNames:r=[],onComplete:a}){var C;const{user:i}=hs(),{data:l}=G_(),{useTeamMembers:o}=SC(),{data:c=[]}=o((l==null?void 0:l.teamId)||""),d=Iin(),[u,h]=_.useState(null),[m,p]=_.useState(""),[f,y]=_.useState(!1),v=c.filter(E=>E.user_id!==(i==null?void 0:i.id)),g=async()=>{if(u){y(!0);try{for(const E of n)await d.mutateAsync({contactId:E,toUserId:u,notes:m||void 0});t(!1),h(null),p(""),a==null||a()}catch{}finally{y(!1)}}},b=v.find(E=>E.user_id===u),j=n.length>1,S=r.length>0?j?`${r.length} contacts`:r[0]:j?`${n.length} contacts`:"this contact";return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"sm:max-w-md",children:[e.jsxs(Os,{children:[e.jsxs(Ds,{className:"flex items-center gap-2",children:[e.jsx(U4,{className:"h-5 w-5"}),"Transfer ",S]}),e.jsxs(_r,{children:["Select a team member to transfer ",j?"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(J,{className:"text-sm font-medium mb-2 block",children:"Transfer to:"}),e.jsx("div",{className:"space-y-1 max-h-[240px] overflow-y-auto",children:v.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No other team members available"}):v.map(E=>{var P,M,I;return e.jsxs("button",{onClick:()=>h(E.user_id),className:`w-full flex items-center gap-3 p-3 rounded-lg text-left transition-colors ${u===E.user_id?"bg-primary/10 border border-primary/30":"hover:bg-accent border border-transparent"}`,children:[e.jsxs(ja,{className:"h-8 w-8",children:[e.jsx(pi,{src:((P=E.profile)==null?void 0:P.avatar_url)||""}),e.jsx(Na,{className:"text-xs",children:(((M=E.profile)==null?void 0:M.name)||"?").charAt(0).toUpperCase()})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:((I=E.profile)==null?void 0:I.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:E.role.replace("_"," ")})]})]},E.user_id)})})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"transfer-notes",className:"text-sm font-medium",children:"Notes (optional)"}),e.jsx(Ms,{id:"transfer-notes",value:m,onChange:E=>p(E.target.value),placeholder:"Reason for transfer...",className:"mt-1",rows:2})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{onClick:g,disabled:!u||f,children:[f?e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(U4,{className:"h-4 w-4 mr-2"}),"Transfer",b?` to ${(C=b.profile)==null?void 0:C.name}`:""]})]})]})})}const ZLe=()=>{const s=Fn(),{data:t,isLoading:n}=Pin(),{data:r}=G_(),[a,i]=_.useState(""),[l,o]=_.useState("all"),[c,d]=_.useState(null),[u,h]=_.useState(""),m=(r==null?void 0:r.role)==="team_leader",p=_.useMemo(()=>{if(!t)return[];const y=new Map;return t.forEach(v=>{y.has(v.owner_user_id)||y.set(v.owner_user_id,{id:v.owner_user_id,name:v.owner_name||"Unknown",avatar:v.owner_avatar_url})}),Array.from(y.values())},[t]),f=_.useMemo(()=>{if(!t)return[];let y=t;if(l!=="all"&&(y=y.filter(v=>v.owner_user_id===l)),a.trim()){const v=a.toLowerCase();y=y.filter(g=>{var b,j,S;return(g.first_name+" "+(g.last_name||"")).toLowerCase().includes(v)||((b=g.email)==null?void 0:b.toLowerCase().includes(v))||((j=g.phone)==null?void 0:j.includes(v))||((S=g.owner_name)==null?void 0:S.toLowerCase().includes(v))})}return y},[t,a,l]);return n?e.jsxs("div",{className:"space-y-4",children:[e.jsx(cn,{className:"h-10 w-full"}),e.jsx(cn,{className:"h-64 w-full"})]}):!t||t.length===0?e.jsx(ve,{children:e.jsxs(Me,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(In,{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(ve,{children:e.jsx(Me,{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(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search by name, email, phone, or agent...",value:a,onChange:y=>i(y.target.value),className:"pl-9"})]}),e.jsxs(is,{value:l,onValueChange:o,children:[e.jsx(rs,{className:"w-[200px]",children:e.jsx(ls,{placeholder:"Filter by agent"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Team Members"}),p.map(y=>e.jsx(He,{value:y.id,children:y.name},y.id))]})]})]})})}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[f.length," contact",f.length!==1?"s":""," from ",p.length," teammate",p.length!==1?"s":""]}),e.jsx(ve,{children:e.jsx(Me,{className:"p-0 overflow-x-auto",children:e.jsxs(Ga,{className:"min-w-[800px]",children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"Name"}),e.jsx(Pt,{children:"Agent"}),e.jsx(Pt,{children:"Contact Info"}),e.jsx(Pt,{children:"Address"}),e.jsx(Pt,{children:"Lead Source"}),e.jsx(Pt,{children:"Date Added"}),m&&e.jsx(Pt,{className:"w-[80px]",children:"Actions"})]})}),e.jsx(Ka,{children:f.length===0?e.jsx(pn,{children:e.jsx(gt,{colSpan:m?7:6,className:"text-center py-8 text-muted-foreground",children:a||l!=="all"?"No contacts match your filters":"No team contacts available"})}):f.map(y=>e.jsxs(pn,{className:`hover:bg-accent/50 ${m?"cursor-pointer":""}`,onClick:m?()=>s(`/mission-control/contacts/${y.id}`):void 0,children:[e.jsx(gt,{className:"font-medium",children:e.jsxs("span",{className:m?"hover:text-primary hover:underline transition-colors":"",children:[y.first_name," ",y.last_name||""]})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(ja,{className:"h-6 w-6",children:[e.jsx(pi,{src:y.owner_avatar_url||""}),e.jsx(Na,{className:"text-[10px]",children:(y.owner_name||"?").charAt(0).toUpperCase()})]}),e.jsx("span",{className:"text-sm text-muted-foreground truncate max-w-[120px]",children:y.owner_name||"Unknown"})]})}),e.jsx(gt,{children:e.jsxs("div",{className:"space-y-1 text-sm",children:[y.email&&e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(ln,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate",children:y.email})]}),y.phone&&e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(_a,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{children:y.phone})]}),!y.email&&!y.phone&&e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"No contact info"})]})}),e.jsx(gt,{children:y.address?e.jsxs("div",{className:"flex items-center gap-1 text-sm text-muted-foreground",children:[e.jsx(Xa,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate max-w-[180px]",children:y.address})]}):e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"—"})}),e.jsx(gt,{children:y.lead_source?e.jsx(Oe,{variant:"outline",className:"text-xs border-primary/30 text-primary",children:y.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(y.created_at),"MMM d, yyyy")})}),m&&e.jsx(gt,{children:e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:v=>{v.stopPropagation(),d(y.id),h(`${y.first_name} ${y.last_name||""}`.trim())},title:"Transfer to team member",children:e.jsx(U4,{className:"h-4 w-4"})})})]},y.id))})]})})}),e.jsx(SVt,{open:!!c,onOpenChange:y=>{y||d(null)},contactIds:c?[c]:[],contactNames:u?[u]:[],onComplete:()=>d(null)})]})},Din=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)},Rin=({leadPondId:s})=>{const{data:t,isLoading:n,error:r}=Min(s);return n?e.jsxs("div",{className:"space-y-2 pt-2",children:[e.jsx(cn,{className:"h-4 w-2/3"}),e.jsx(cn,{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(c7,{className:"mt-0.5 h-3 w-3 shrink-0 text-muted-foreground"}):e.jsx(hm,{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:Din(a.occurred_at)})]})]},i))})},Fin=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)):"",Oin=s=>{var n;const t=((n=s.contact_name)==null?void 0:n.trim())||"A lead";switch(s.event_type){case"claimed":return{icon:Fq,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:Tx,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:m1,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"]})}}},Rvt=({teamId:s,pondId:t})=>{const{data:n,isLoading:r}=Lin(s,t),[a,i]=_.useState(!1),l=n||[],o=a?l:l.slice(0,8);return e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-3",children:e.jsxs(St,{className:"flex items-center gap-2 text-sm",children:[e.jsx(R_,{className:"h-4 w-4"}),"Pond Activity History"]})}),e.jsx(Me,{className:"space-y-3",children:r?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(c=>e.jsx(cn,{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=Oin(c),h=u.icon;return e.jsxs("div",{className:"flex gap-3",children:[e.jsxs(ja,{className:"h-6 w-6 shrink-0",children:[e.jsx(pi,{src:c.actor_avatar_url||""}),e.jsx(Na,{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:Fin(c.occurred_at)}),c.pond_name&&e.jsx(Oe,{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(B,{size:"sm",variant:"ghost",className:"h-7 px-2 text-xs",onClick:()=>i(c=>!c),children:[a?e.jsx(_v,{className:"mr-1 h-3 w-3"}):e.jsx(tl,{className:"mr-1 h-3 w-3"}),a?"Show less":`Show all ${l.length} events`]})]})})]})},zin=s=>s?new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric"}).format(new Date(s)):null,Bin=({item:s,isClaimer:t,onReturn:n,returning:r})=>{var o,c,d;const[a,i]=_.useState(!1),l=zin(s.last_activity_at);return e.jsx(ve,{children:e.jsxs(Me,{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(Oe,{variant:"secondary",className:"text-xs",children:["Claimed by ",((d=s.claimer)==null?void 0:d.name)||"Unknown"]}),e.jsxs(Oe,{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(Gr,{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(ya,{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(B,{size:"sm",variant:"outline",onClick:n,disabled:r,children:[e.jsx(Tx,{className:"mr-1 h-3 w-3"}),"Return"]})]}),s.can_view_activity&&e.jsxs("div",{className:"border-t pt-2",children:[e.jsxs(B,{size:"sm",variant:"ghost",className:"h-7 px-2 text-xs",onClick:()=>i(u=>!u),children:[a?e.jsx(_v,{className:"mr-1 h-3 w-3"}):e.jsx(tl,{className:"mr-1 h-3 w-3"}),a?"Hide notes & activity":"View notes & activity"]}),a&&e.jsx(Rin,{leadPondId:s.id})]})]})})},XLe=({teamId:s})=>{const{user:t}=hs(),[n,r]=_.useState(null),{ponds:a,isLoading:i}=$tt(s),l=a.filter(f=>f.has_access),{leadPondItems:o,isLoading:c,claimLead:d,returnLead:u}=kVt(s,n),h=l.length>1?e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(B,{size:"sm",variant:n===null?"default":"outline",onClick:()=>r(null),children:"All Ponds"}),l.map(f=>e.jsxs(B,{size:"sm",variant:n===f.id?"default":"outline",onClick:()=>r(f.id),children:[e.jsx(m1,{className:"mr-1 h-3 w-3"}),f.name,e.jsx(Oe,{variant:"secondary",className:"ml-2 text-[10px]",children:f.available_count})]},f.id))]}):null;if(console.log("[LeadPondView] render — teamId:",s,"itemCount:",o.length,"loading:",c),c)return e.jsx("div",{className:"space-y-3",children:[1,2,3].map(f=>e.jsx(cn,{className:"h-20 w-full"},f))});if(o.length===0)return e.jsxs("div",{className:"space-y-4",children:[h,e.jsx(ve,{children:e.jsxs(Me,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(m1,{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(Rvt,{teamId:s,pondId:n})]});const m=o.filter(f=>f.status==="available"),p=o.filter(f=>f.status==="claimed");return e.jsxs("div",{className:"space-y-6",children:[h,e.jsxs("div",{children:[e.jsxs("h3",{className:"text-sm font-semibold text-muted-foreground mb-3",children:["Available (",m.length,")"]}),m.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No leads available right now."}):e.jsx("div",{className:"space-y-2",children:m.map(f=>{var y,v,g,b,j,S,C,E,P,M,I;return e.jsx(ve,{children:e.jsxs(Me,{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:[((y=f.contact)==null?void 0:y.first_name)||"Unnamed"," ",((v=f.contact)==null?void 0:v.last_name)||""]}),e.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1",children:[((g=f.contact)==null?void 0:g.email)&&e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(ln,{className:"h-3 w-3"})," ",f.contact.email]}),((b=f.contact)==null?void 0:b.phone)&&e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(_a,{className:"h-3 w-3"})," ",f.contact.phone]}),((j=f.contact)==null?void 0:j.address)&&e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Xa,{className:"h-3 w-3"})," ",f.contact.address]})]}),f.pond_name&&n===null&&l.length>1&&e.jsxs(Oe,{variant:"secondary",className:"text-[10px]",children:[e.jsx(m1,{className:"mr-1 h-2.5 w-2.5"})," ",f.pond_name]}),((S=f.contact)==null?void 0:S.lead_source)&&e.jsxs(Oe,{variant:"outline",className:"text-[10px]",children:["Source: ",f.contact.lead_source]}),(f.notes||((C=f.contact)==null?void 0:C.notes))&&e.jsxs("p",{className:"text-xs text-muted-foreground flex items-start gap-1 max-w-xl",children:[e.jsx(c7,{className:"h-3 w-3 mt-0.5 shrink-0"}),e.jsx("span",{className:"whitespace-pre-wrap",children:f.notes||((E=f.contact)==null?void 0:E.notes)})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-0.5",children:[e.jsxs(ja,{className:"h-4 w-4",children:[e.jsx(pi,{src:((P=f.contributor)==null?void 0:P.avatar_url)||""}),e.jsx(Na,{className:"text-[8px]",children:(((M=f.contributor)==null?void 0:M.name)||"?").charAt(0)})]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["from ",((I=f.contributor)==null?void 0:I.name)||"Unknown"]})]})]}),e.jsxs(B,{size:"sm",className:"shrink-0",onClick:()=>d.mutate(f.id),disabled:d.isPending,children:[e.jsx(Fq,{className:"mr-1 h-3 w-3"}),"Claim"]})]})},f.id)})})]}),p.length>0&&e.jsxs("div",{children:[e.jsxs("h3",{className:"text-sm font-semibold text-muted-foreground mb-3",children:["Claimed (",p.length,")"]}),e.jsx("div",{className:"space-y-2",children:p.map(f=>e.jsx(Bin,{item:f,isClaimer:f.claimed_by===(t==null?void 0:t.id),onReturn:()=>u.mutate(f.id),returning:u.isPending},f.id))})]}),e.jsx(Rvt,{teamId:s,pondId:n})]})},Vtt=({teamId:s})=>{const{useTeamMembers:t}=SC(),{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}=at({queryKey:["team-shared-presentations",s,r],queryFn:async()=>{if(r.length===0)return[];const{data:p,error:f}=await q.from("smart_presentations").select("id, owner_user_id, title, client_name, status, view_count, cta_clicked_count, share_token, created_at, published_at").in("owner_user_id",r).neq("status","archived").order("created_at",{ascending:!1});if(f)throw f;return p||[]},enabled:r.length>0}),{data:o=[],isLoading:c}=at({queryKey:["team-shared-open-houses",s,r],queryFn:async()=>{if(r.length===0)return[];const{data:p,error:f}=await q.from("open_houses").select("id, agent_id, property_address, city, state, event_date, is_active, visitor_count, slug, created_at").in("agent_id",r).order("event_date",{ascending:!1});if(f)throw f;return p||[]},enabled:r.length>0}),{data:d=[],isLoading:u}=at({queryKey:["team-shared-videos",s,r],queryFn:async()=>{if(r.length===0)return[];const{data:p,error:f}=await q.from("agent_videos").select("id, owner_user_id, title, recipient_name, status, view_count, touch_type, share_token, created_at").in("owner_user_id",r).eq("is_deleted",!1).order("created_at",{ascending:!1}).limit(50);if(f)throw f;return p||[]},enabled:r.length>0});if(l||c||u)return e.jsx("div",{className:"space-y-3",children:[1,2,3].map(p=>e.jsx(cn,{className:"h-20 w-full"},p))});const m=p=>{const f=a.get(p);return{name:(f==null?void 0:f.name)||"Unknown",avatar:(f==null?void 0:f.avatar_url)||"",initials:((f==null?void 0:f.name)||"?").charAt(0).toUpperCase()}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 grid-cols-3",children:[e.jsx(ve,{children:e.jsxs(Me,{className:"flex items-center gap-3 p-4",children:[e.jsx(jv,{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(ve,{children:e.jsxs(Me,{className:"flex items-center gap-3 p-4",children:[e.jsx(Jr,{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(ve,{children:e.jsxs(Me,{className:"flex items-center gap-3 p-4",children:[e.jsx(Kr,{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(Yr,{defaultValue:"presentations",className:"space-y-4",children:[e.jsxs(Zr,{children:[e.jsxs(Ht,{value:"presentations",children:["Presentations (",i.length,")"]}),e.jsxs(Ht,{value:"guest-books",children:["Guest Books (",o.length,")"]}),e.jsxs(Ht,{value:"videos",children:["Videos (",d.length,")"]})]}),e.jsx(Gt,{value:"presentations",className:"space-y-2",children:i.length===0?e.jsx(c9e,{icon:e.jsx(jv,{className:"h-10 w-10"}),label:"No presentations yet"}):i.map(p=>{const f=m(p.owner_user_id);return e.jsx(ve,{children:e.jsxs(Me,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsxs(ja,{className:"h-8 w-8 shrink-0",children:[e.jsx(pi,{src:f.avatar}),e.jsx(Na,{className:"text-xs",children:f.initials})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:p.title||"Untitled"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[f.name," · ",Hs(new Date(p.created_at),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e.jsx(Oe,{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(ya,{className:"h-3 w-3"}),p.view_count||0]})]})]})},p.id)})}),e.jsx(Gt,{value:"guest-books",className:"space-y-2",children:o.length===0?e.jsx(c9e,{icon:e.jsx(Jr,{className:"h-10 w-10"}),label:"No guest books yet"}):o.map(p=>{const f=m(p.agent_id);return e.jsx(ve,{children:e.jsxs(Me,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsxs(ja,{className:"h-8 w-8 shrink-0",children:[e.jsx(pi,{src:f.avatar}),e.jsx(Na,{className:"text-xs",children:f.initials})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:p.property_address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[f.name," · ",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(Oe,{className:"text-xs",children:"Active"}):e.jsx(Oe,{variant:"secondary",className:"text-xs",children:"Inactive"}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(In,{className:"h-3 w-3"}),p.visitor_count||0]})]})]})},p.id)})}),e.jsx(Gt,{value:"videos",className:"space-y-2",children:d.length===0?e.jsx(c9e,{icon:e.jsx(Kr,{className:"h-10 w-10"}),label:"No videos yet"}):d.map(p=>{const f=m(p.owner_user_id);return e.jsx(ve,{children:e.jsxs(Me,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsxs(ja,{className:"h-8 w-8 shrink-0",children:[e.jsx(pi,{src:f.avatar}),e.jsx(Na,{className:"text-xs",children:f.initials})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:p.title||p.recipient_name||"Untitled Video"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[f.name," · ",Hs(new Date(p.created_at),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e.jsx(Oe,{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(ya,{className:"h-3 w-3"}),p.view_count||0]})]})]})},p.id)})})]})]})},c9e=({icon:s,label:t})=>e.jsx(ve,{children:e.jsxs(Me,{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})]})}),CVt=({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}=SC(),{data:h=[],isLoading:m}=u(s.id),[p,f]=_.useState(!1),[y,v]=_.useState(""),[g,b]=_.useState("team_member"),{data:j}=at({queryKey:["agents-on-other-teams",s.id],queryFn:async()=>{const{data:I}=await q.from("team_members").select("user_id, team_id, teams:team_id(name)").neq("team_id",s.id),D=new Map;return(I||[]).forEach(O=>{var G;const V=D.get(O.user_id)||[];V.push(((G=O.teams)==null?void 0:G.name)||"another team"),D.set(O.user_id,V)}),D}}),S=new Set(h.map(I=>I.user_id)),C=t.filter(I=>!S.has(I.id)),E=async()=>{y&&(await a(y,g),v(""),b("team_member"),f(!1))};return e.jsxs("div",{className:"space-y-6",children:[e.jsx(B,{variant:"ghost",onClick:n,className:"mb-2",children:"← Back to Teams"}),e.jsxs(Yr,{defaultValue:"members",className:"space-y-4",children:[e.jsxs(Zr,{children:[e.jsx(Ht,{value:"members",children:"Members"}),e.jsxs(Ht,{value:"contacts",children:[e.jsx(WM,{className:"mr-1 h-3.5 w-3.5"}),"Team Contacts"]}),s.lead_pond_enabled&&e.jsxs(Ht,{value:"lead-pond",children:[e.jsx(m1,{className:"mr-1 h-3.5 w-3.5"}),"Lead Pond"]}),s.shared_assets_enabled&&e.jsxs(Ht,{value:"shared-assets",children:[e.jsx(wy,{className:"mr-1 h-3.5 w-3.5"}),"Shared Assets"]}),e.jsx(Ht,{value:"settings",children:"Settings"})]}),e.jsxs(Gt,{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(Ls,{open:p,onOpenChange:f,children:[e.jsx(nl,{asChild:!0,children:e.jsxs(B,{size:"sm",children:[e.jsx(Pl,{className:"mr-2 h-4 w-4"}),"Add Member"]})}),e.jsxs(Ps,{children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Add Team Member"}),e.jsxs(_r,{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(J,{children:"Agent"}),e.jsxs(od,{children:[e.jsx(ld,{asChild:!0,children:e.jsxs(B,{variant:"outline",role:"combobox",className:"w-full justify-between font-normal",children:[y&&(((P=C.find(I=>I.id===y))==null?void 0:P.name)||((M=C.find(I=>I.id===y))==null?void 0:M.email))||"Select an agent",e.jsx(I_,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Qc,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(Aj,{children:[e.jsx(Ej,{placeholder:"Search agents..."}),e.jsxs(Tj,{children:[e.jsx(Mj,{children:"No agents found."}),e.jsx(V_,{children:C.map(I=>{const D=j==null?void 0:j.get(I.id);return e.jsxs(d1,{value:I.name||I.email||I.id,onSelect:()=>v(I.id),children:[e.jsx(ea,{className:At("mr-2 h-4 w-4",y===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(J,{children:"Role"}),e.jsxs(is,{value:g,onValueChange:b,children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"team_leader",children:"Team Leader"}),e.jsx(He,{value:"team_member",children:"Team Member"})]})]})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>f(!1),children:"Cancel"}),e.jsx(B,{onClick:E,disabled:!y||d,children:d?"Adding...":"Add to Team"})]})]})]})]}),m?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(I=>e.jsx(cn,{className:"h-16 w-full"},I))}):h.length===0?e.jsx(ve,{children:e.jsxs(Me,{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx(In,{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,O,V,G,$;return e.jsx(ve,{children:e.jsxs(Me,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(ja,{className:"h-10 w-10",children:[e.jsx(pi,{src:((D=I.profile)==null?void 0:D.avatar_url)||""}),e.jsx(Na,{children:(((O=I.profile)==null?void 0:O.name)||"?").charAt(0).toUpperCase()})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((V=I.profile)==null?void 0:V.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(G=I.profile)==null?void 0:G.email})]}),I.role==="team_leader"?e.jsxs(Oe,{className:"bg-[hsl(var(--chart-4)/0.1)] text-[hsl(var(--chart-4))] border-[hsl(var(--chart-4))]",children:[e.jsx($f,{className:"mr-1 h-3 w-3"})," Leader"]}):e.jsx(Oe,{variant:"secondary",children:"Member"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(is,{value:I.role,onValueChange:H=>l(I.id,H),children:[e.jsx(rs,{className:"w-[140px]",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"team_leader",children:"Team Leader"}),e.jsx(He,{value:"team_member",children:"Team Member"})]})]}),e.jsxs(Kl,{children:[e.jsx(jx,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-muted-foreground hover:text-destructive",children:e.jsx(u$,{className:"h-4 w-4"})})}),e.jsxs(Ol,{children:[e.jsxs(zl,{children:[e.jsx(Ul,{children:"Remove Member?"}),e.jsxs(ql,{children:["Remove ",(($=I.profile)==null?void 0:$.name)||"this member"," from ",s.name,"?"]})]}),e.jsxs(Bl,{children:[e.jsx($l,{children:"Cancel"}),e.jsx(Ml,{onClick:()=>i(I.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})]})]})]})},I.id)})})]}),e.jsx(Gt,{value:"contacts",className:"space-y-4",children:e.jsx(ZLe,{})}),s.lead_pond_enabled&&e.jsx(Gt,{value:"lead-pond",className:"space-y-4",children:e.jsx(XLe,{teamId:s.id})}),s.shared_assets_enabled&&e.jsx(Gt,{value:"shared-assets",className:"space-y-4",children:e.jsx(Vtt,{teamId:s.id})}),e.jsxs(Gt,{value:"settings",className:"space-y-4",children:[e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsx(St,{className:"text-lg",children:"Team Settings"}),e.jsx(kn,{children:"Configure how this team operates."})]}),e.jsxs(Me,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Team Name"}),e.jsx(xe,{defaultValue:s.name,onBlur:I=>{I.target.value!==s.name&&r({name:I.target.value})}})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Description"}),e.jsx(Ms,{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(J,{children:"Contact Visibility"}),e.jsxs(is,{defaultValue:s.contact_visibility,onValueChange:I=>r({contact_visibility:I}),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"private",children:"Private — Members keep their contacts private"}),e.jsx(He,{value:"leader_only",children:"Leader Only — Only team leaders can see member contacts"}),e.jsx(He,{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(J,{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(fn,{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(J,{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(fn,{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(J,{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(fn,{checked:s.shared_videos_enabled??!1,onCheckedChange:I=>r({shared_videos_enabled:I})})]})]})]}),s.lead_pond_enabled&&e.jsx(NVt,{teamId:s.id}),e.jsxs(Kl,{children:[e.jsx(jx,{asChild:!0,children:e.jsxs(B,{variant:"destructive",size:"sm",children:[e.jsx(Sn,{className:"mr-2 h-4 w-4"}),"Delete Team"]})}),e.jsxs(Ol,{children:[e.jsxs(zl,{children:[e.jsx(Ul,{children:"Delete Team?"}),e.jsxs(ql,{children:['This will permanently delete "',s.name,'" and remove all team members. This cannot be undone.']})]}),e.jsxs(Bl,{children:[e.jsx($l,{children:"Cancel"}),e.jsx(Ml,{onClick:()=>{o(),n()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete Team"})]})]})]})]})]})]})},AVt=({open:s,onOpenChange:t,onCreateTeam:n,isCreating:r,brokerageAgents:a,isAdmin:i,allBrokerages:l,activeBrokerageId:o})=>{const[c,d]=_.useState(1),[u,h]=_.useState(""),[m,p]=_.useState(""),[f,y]=_.useState(""),[v,g]=_.useState(""),[b,j]=_.useState([]),S=()=>{d(1),h(""),p(""),y(""),g(""),j([])},C=I=>{I||S(),t(I)},E=async()=>{const I=f&&f!=="none"?f:o||null;await n({name:u.trim(),description:m.trim()||void 0,brokerage_id:I,leaderId:v||void 0,memberIds:b.length>0?b:void 0}),S()},P=I=>{I!==v&&j(D=>D.includes(I)?D.filter(O=>O!==I):[...D,I])},M=a.filter(I=>I.id!==v);return e.jsx(Ls,{open:s,onOpenChange:C,children:e.jsxs(Ps,{className:"sm:max-w-lg max-h-[90vh] flex flex-col",children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:c===1?"Create New Team":"Assign Team Members"}),e.jsx(_r,{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:At("h-1.5 flex-1 rounded-full transition-colors","bg-primary")}),e.jsx("div",{className:At("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(J,{htmlFor:"team-name",children:"Team Name *"}),e.jsx(xe,{id:"team-name",value:u,onChange:I=>h(I.target.value),placeholder:"e.g., Downtown Squad",autoFocus:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"team-desc",children:"Description"}),e.jsx(Ms,{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(J,{children:"Brokerage"}),e.jsxs(is,{value:f,onValueChange:y,children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"No brokerage (independent team)"})}),e.jsxs(as,{children:[e.jsx(He,{value:"none",children:"No brokerage (independent)"}),l.map(I=>e.jsx(He,{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(J,{className:"flex items-center gap-1.5",children:[e.jsx($f,{className:"h-3.5 w-3.5 text-[hsl(var(--chart-4))]"}),"Team Leader"]}),e.jsxs(is,{value:v,onValueChange:I=>{g(I),j(D=>D.filter(O=>O!==I))},children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Select a team leader (optional)"})}),e.jsxs(as,{children:[e.jsx(He,{value:"none",children:"No leader for now"}),a.map(I=>e.jsx(He,{value:I.id,children:I.name||I.email||"Unknown"},I.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(J,{className:"flex items-center gap-1.5",children:[e.jsx(Pl,{className:"h-3.5 w-3.5"}),"Initial Members",b.length>0&&e.jsxs(Oe,{variant:"secondary",className:"ml-1 text-xs",children:[b.length," selected"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Click agents to add them. You can always add more later."}),e.jsx("div",{className:"border rounded-lg max-h-[240px] overflow-y-auto divide-y",children:M.length===0?e.jsxs("div",{className:"p-4 text-center text-sm text-muted-foreground",children:[e.jsx(In,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),"No agents available"]}):M.map(I=>{const D=b.includes(I.id);return e.jsxs("button",{type:"button",className:At("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(ja,{className:"h-8 w-8",children:[e.jsx(pi,{src:I.avatar_url||""}),e.jsx(Na,{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:At("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(ea,{className:"h-3 w-3"})})]},I.id)})})]})]})}),e.jsx(yr,{className:"gap-2 sm:gap-0",children:c===1?e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"outline",onClick:()=>C(!1),children:"Cancel"}),e.jsxs(B,{onClick:()=>d(2),disabled:!u.trim(),children:["Next",e.jsx(La,{className:"ml-2 h-4 w-4"})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"outline",onClick:()=>d(1),children:[e.jsx(ka,{className:"mr-2 h-4 w-4"}),"Back"]}),e.jsx(B,{onClick:E,disabled:r,children:r?"Creating…":"Create Team"})]})})]})})},Uin=()=>{const{teams:s,isLoading:t,createTeam:n,updateTeam:r,deleteTeam:a,addMember:i,removeMember:l,updateMemberRole:o}=SC(),[c,d]=_.useState(!1),[u,h]=_.useState(null),[m,p]=_.useState(""),{data:f}=at({queryKey:["all-brokerages-for-teams"],queryFn:async()=>{const{data:C,error:E}=await q.from("brokerages").select("id, name").order("name");if(E)throw E;return C||[]}}),{data:y}=at({queryKey:["admin-team-member-info",s.map(C=>C.id).join(",")],queryFn:async()=>{var I;if(s.length===0)return{};const{data:C}=await q.from("team_members").select("team_id, user_id, role").in("team_id",s.map(D=>D.id));if(!C)return{};const E=C.filter(D=>D.role==="team_leader").map(D=>D.user_id);let P={};if(E.length>0){const{data:D}=await q.from("profiles").select("id, name").in("id",E);D&&(P=Object.fromEntries(D.map(O=>[O.id,{name:O.name}])))}const M={};for(const D of s){const O=C.filter(G=>G.team_id===D.id),V=O.find(G=>G.role==="team_leader");M[D.id]={count:O.length,leaderName:V&&((I=P[V.user_id])==null?void 0:I.name)||null}}return M},enabled:s.length>0}),v=(u==null?void 0:u.brokerage_id)||null,{data:g}=at({queryKey:["brokerage-agents-for-teams",v],queryFn:async()=>{let C=q.from("profiles").select("id, name, email, avatar_url").order("name");v&&(C=C.eq("brokerage_id",v));const{data:E,error:P}=await C;if(P)throw P;return E||[]},enabled:!!u}),b=Object.fromEntries((f||[]).map(C=>[C.id,C.name])),j=async C=>{const E=await n.mutateAsync({name:C.name,brokerage_id:C.brokerage_id||null,description:C.description});if(C.leaderId&&C.leaderId!=="none"&&await i.mutateAsync({team_id:E.id,user_id:C.leaderId,role:"team_leader"}),C.memberIds)for(const P of C.memberIds)await i.mutateAsync({team_id:E.id,user_id:P,role:"team_member"});d(!1)};if(u)return e.jsx(CVt,{team:u,brokerageAgents:g||[],onBack:()=>h(null),onUpdate:C=>r.mutateAsync({id:u.id,...C}).then(E=>h(E)),onAddMember:(C,E)=>i.mutateAsync({team_id:u.id,user_id:C,role:E}),onRemoveMember:C=>l.mutateAsync({team_id:u.id,member_id:C}),onUpdateRole:(C,E)=>o.mutateAsync({team_id:u.id,member_id:C,role:E}),onDeleteTeam:()=>{a.mutate(u.id),h(null)},isUpdating:r.isPending,isAddingMember:i.isPending});const S=s.filter(C=>C.name.toLowerCase().includes(m.toLowerCase())||(C.description||"").toLowerCase().includes(m.toLowerCase()));return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(Lr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search teams...",value:m,onChange:C=>p(C.target.value),className:"pl-10"})]}),e.jsxs("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:[S.length," of ",s.length," teams"]})]}),e.jsxs(B,{size:"sm",onClick:()=>d(!0),children:[e.jsx(rn,{className:"mr-2 h-4 w-4"}),"Create Team"]})]}),e.jsx(AVt,{open:c,onOpenChange:d,onCreateTeam:j,isCreating:n.isPending,brokerageAgents:[],isAdmin:!0,allBrokerages:f,activeBrokerageId:null}),e.jsx("div",{className:"border rounded-lg bg-card overflow-hidden",children:e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Pt,{className:"font-semibold",children:"Team Name"}),e.jsx(Pt,{className:"font-semibold",children:"Brokerage"}),e.jsx(Pt,{className:"font-semibold",children:"Leader"}),e.jsx(Pt,{className:"font-semibold",children:"Members"}),e.jsx(Pt,{className:"font-semibold",children:"Visibility"}),e.jsx(Pt,{className:"w-[100px]"})]})}),e.jsx(Ka,{children:t?e.jsx(e.Fragment,{children:[1,2,3].map(C=>e.jsxs(pn,{children:[e.jsx(gt,{children:e.jsx(cn,{className:"h-4 w-32"})}),e.jsx(gt,{children:e.jsx(cn,{className:"h-4 w-24"})}),e.jsx(gt,{children:e.jsx(cn,{className:"h-4 w-28"})}),e.jsx(gt,{children:e.jsx(cn,{className:"h-4 w-12"})}),e.jsx(gt,{children:e.jsx(cn,{className:"h-4 w-20"})}),e.jsx(gt,{children:e.jsx(cn,{className:"h-4 w-16"})})]},C))}):S.length===0?e.jsx(pn,{children:e.jsx(gt,{colSpan:6,className:"text-center py-12 text-muted-foreground",children:m?"No teams match your search":"No teams found. Create one to get started."})}):S.map(C=>{const E=y==null?void 0:y[C.id];return e.jsxs(pn,{className:"hover:bg-muted/30",children:[e.jsxs(gt,{children:[e.jsx("button",{onClick:()=>h(C),className:"text-primary hover:underline font-medium",children:C.name}),C.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:C.description})]}),e.jsx(gt,{children:C.brokerage_id?e.jsx("span",{className:"text-sm",children:b[C.brokerage_id]||"—"}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"Independent"})}),e.jsx(gt,{children:E!=null&&E.leaderName?e.jsxs("span",{className:"text-sm flex items-center gap-1",children:[e.jsx($f,{className:"h-3 w-3 text-[hsl(var(--chart-4))]"}),E.leaderName]}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"No leader"})}),e.jsx(gt,{children:e.jsxs(Oe,{variant:"secondary",className:"text-xs",children:[e.jsx(In,{className:"h-3 w-3 mr-1"}),(E==null?void 0:E.count)??0]})}),e.jsx(gt,{children:e.jsxs("span",{className:"text-xs text-muted-foreground capitalize flex items-center gap-1",children:[e.jsx(Rm,{className:"h-3 w-3"}),C.contact_visibility.replace("_"," ")]})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>h(C),title:"Edit team",children:e.jsx(Ya,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",onClick:async()=>{await Xi(`Delete team "${C.name}"? This cannot be undone.`)&&a.mutate(C.id)},title:"Delete team",children:e.jsx(Sn,{className:"h-3.5 w-3.5"})})]})})]},C.id)})})]})})]})};function Fvt(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 qin({open:s,onOpenChange:t,recipients:n}){const{toast:r}=vi(),[a,i]=_.useState([]),[l,o]=_.useState(!1),[c,d]=_.useState(""),[u,h]=_.useState(""),[m,p]=_.useState(""),[f,y]=_.useState(!1),[v,g]=_.useState(!1),b=_.useMemo(()=>a.find(E=>E.id===c)||null,[a,c]);_.useEffect(()=>{s&&(o(!0),(async()=>{const E=new Date().toISOString(),{data:P,error:M}=await q.from("events").select("id,title,description,event_date,zoom_link,image_url,is_published").gte("event_date",E).order("event_date",{ascending:!0}).limit(50);M?r({title:"Could not load events",description:M.message,variant:"destructive"}):i(P||[]),o(!1)})())},[s,r]);const j=_.useMemo(()=>n.filter(E=>E.email&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(E.email)),[n]),S=()=>{if(!b){r({title:"Pick an event first",variant:"destructive"});return}if(j.length===0){r({title:"No valid recipient emails",variant:"destructive"});return}g(!0)},C=async()=>{if(b){g(!1),y(!0);try{const{data:{session:E}}=await q.auth.getSession(),P=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/admin-send-event-invite",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${E==null?void 0:E.access_token}`},body:JSON.stringify({event_id:b.id,recipients:j.map(V=>({email:V.email,name:V.name,user_id:V.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,O=(M==null?void 0:M.already_invited)??0;r({title:"Invites sent",description:`Sent: ${I}${O?` · Skipped (already invited): ${O}`:""}${D?` · Failed: ${D}`:""}`}),t(!1),p(""),h(""),d("")}catch(E){const P=E instanceof Error?E.message:"Send failed";r({title:"Send failed",description:P,variant:"destructive"})}finally{y(!1)}}};return e.jsxs(e.Fragment,{children:[e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsxs(Ds,{className:"flex items-center gap-2",children:[e.jsx(ln,{className:"h-5 w-5 text-primary"}),"Send Event Invite"]}),e.jsxs(_r,{children:["Send a beautiful event invitation to ",j.length," selected member",j.length===1?"":"s",".",n.length!==j.length&&e.jsxs("span",{className:"block text-amber-600 mt-1",children:[n.length-j.length," skipped (missing or invalid email)"]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(J,{htmlFor:"event-select",children:"Event"}),l?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground py-2",children:[e.jsx(Ct,{className:"h-4 w-4 animate-spin"})," Loading upcoming events..."]}):a.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-2",children:"No upcoming events found. Create an event first."}):e.jsxs(is,{value:c,onValueChange:d,children:[e.jsx(rs,{id:"event-select",children:e.jsx(ls,{placeholder:"Pick an upcoming event..."})}),e.jsx(as,{children:a.map(E=>e.jsx(He,{value:E.id,children:e.jsxs("div",{className:"flex flex-col text-left",children:[e.jsx("span",{className:"font-medium",children:E.title}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[Fvt(E.event_date),!E.is_published&&" · (Draft)"]})]})},E.id))})]})]}),b&&e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3 space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(ga,{className:"h-4 w-4 text-primary"}),b.title]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Fvt(b.event_date)}),b.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-1",children:b.description})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"subject",children:"Subject line (optional)"}),e.jsx(xe,{id:"subject",placeholder:b?`You're invited: ${b.title}`:"You're invited to...",value:u,onChange:E=>h(E.target.value)}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Leave blank to use the default."})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"intro",children:"Personal message (optional)"}),e.jsx(Ms,{id:"intro",placeholder:"Add a custom intro message... e.g. 'As a new member, we'd love to have you at our weekly onboarding event!'",value:m,onChange:E=>p(E.target.value),rows:4}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"This appears at the top of the email. Leave blank for a friendly default."})]}),e.jsxs("div",{className:"rounded-lg border p-3 bg-muted/20",children:[e.jsxs("div",{className:"text-xs font-medium text-muted-foreground mb-2",children:["RECIPIENTS (",j.length,")"]}),e.jsxs("div",{className:"flex flex-wrap gap-1 max-h-24 overflow-y-auto",children:[j.slice(0,30).map(E=>e.jsx(Oe,{variant:"secondary",className:"text-xs font-normal",children:E.name||E.email},E.id)),j.length>30&&e.jsxs(Oe,{variant:"outline",className:"text-xs",children:["+",j.length-30," more"]})]})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),disabled:f,children:"Cancel"}),e.jsx(B,{onClick:S,disabled:f||!c||j.length===0,children:f?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"})," Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Or,{className:"h-4 w-4 mr-2"})," Send to ",j.length]})})]})]})}),e.jsx(Kl,{open:v,onOpenChange:g,children:e.jsxs(Ol,{children:[e.jsxs(zl,{children:[e.jsx(Ul,{children:"Send event invite?"}),e.jsx(ql,{children:b?e.jsxs(e.Fragment,{children:["Send invite for ",e.jsxs("span",{className:"font-medium text-foreground",children:['"',b.title,'"']})," to"," ",e.jsxs("span",{className:"font-medium text-foreground",children:[j.length," member",j.length===1?"":"s"]}),"?"]}):null})]}),e.jsxs(Bl,{children:[e.jsx($l,{children:"Cancel"}),e.jsxs(Ml,{onClick:C,children:[e.jsx(Or,{className:"h-4 w-4 mr-2"})," Send"]})]})]})})]})}const $in=()=>{var Xh;const s=Fn(),{user:t,isAdmin:n}=hs(),{startImpersonation:r,isLoading:a}=GMe(),{toast:i}=vi(),[l,o]=_.useState([]),[c,d]=_.useState([]),[u,h]=_.useState([]),[m,p]=_.useState({}),[f,y]=_.useState(!0);_.useState({});const[v,g]=_.useState(!1),[b,j]=_.useState({email:"",name:"",password:"",brokerage_id:"",role:"user",phone:"",trial_days:""}),[S,C]=_.useState(!1),[E,P]=_.useState(""),[M,I]=_.useState(1),[D,O]=_.useState(50),[V,G]=_.useState("all"),[$,H]=_.useState(!1),[Y,Z]=_.useState(!1),[ne,ce]=_.useState({done:0,total:0}),[ie,te]=_.useState(null),[ae,le]=_.useState("all"),[be,me]=_.useState("all"),[he,pe]=_.useState("all"),[Ce,Ae]=_.useState("all"),[Pe,ze]=_.useState(!1),[ke,Ze]=_.useState(!1),[Se,Fe]=_.useState(!1),[Ne,Ye]=_.useState(""),[Ve,qe]=_.useState(!1),[Qe,Ue]=_.useState(null),[Xe,nt]=_.useState(null),[$e,Ge]=_.useState(!1),[ct,xt]=_.useState({name:"",email:"",brokerage_id:"",phone:""}),[qt,Vt]=_.useState(null),[Xt,fs]=_.useState(!1),[Ft,wt]=_.useState(""),[Ts,vt]=_.useState(!1),[$s,As]=_.useState(!1),[jn,ar]=_.useState(null),[Dn,Ur]=_.useState(""),[Vs,hn]=_.useState(!1),[dr,Cn]=_.useState(!1),[Yn,on]=_.useState(null),[Ir,Wn]=_.useState(!1),[Js,Fa]=_.useState(!1),[ks,Gs]=_.useState(null),[Ws,Ys]=_.useState(""),[Bn,or]=_.useState(!1),[Wt,rt]=_.useState({email:"",name:"",password:"",phone:""}),[pt,jt]=_.useState(!1),[Mt,es]=_.useState(null),[ps,Is]=_.useState([]),[js,Kt]=_.useState("none"),[Qs,an]=_.useState(!1),[er,Xr]=_.useState(""),[ma,Br]=_.useState(!1),[sa,Rr]=_.useState(!1),[ra,Si]=_.useState(""),[Gi,rl]=_.useState(new Set),[Ii,Ta]=_.useState(!1),[eo,So]=_.useState(!1),[Ra,Eo]=_.useState(null),[Ro,di]=_.useState(!1),[rr,oi]=_.useState(null),[Oo,kl]=_.useState([]),[Jo,Sl]=_.useState([]),[vu,Ku]=_.useState(!1),[Tp,Bd]=_.useState({});_.useEffect(()=>{if(!t||!n){t&&!n&&y(!1);return}xs(),da()},[t,n]);const xm=async()=>{try{const{data:$t,error:Nn}=await q.from("brokerage_manager_assignments").select("user_id, brokerage_id");if(Nn)throw Nn;const Un={};for(const qr of $t??[])Un[qr.brokerage_id]||(Un[qr.brokerage_id]=[]),Un[qr.brokerage_id].push(qr.user_id);p(Un)}catch($t){console.error("Error loading brokerage manager assignments:",$t)}},xs=async()=>{try{y(!0);const{data:$t,error:Nn}=await q.functions.invoke("get-user-details");if(Nn)throw Nn;const Un=$t.users||[];o(Un),h($t.brokerages||[]),await xm();const qr=Un.filter(Ea=>Ea.roles.includes("assistant"));if(qr.length>0){const Ea=qr.map(Mi=>Mi.id),{data:gi}=await q.from("agent_assistant_assignments").select("agent_id, assistant_id").in("assistant_id",Ea);if(gi&&gi.length>0){const Mi=[...new Set(gi.map(Su=>Su.agent_id))],{data:_i}=await q.from("profiles").select("id, name, email").in("id",Mi),Jc={};for(const Su of gi){const cp=_i==null?void 0:_i.find(dd=>dd.id===Su.agent_id);cp&&(Jc[Su.assistant_id]={agent_name:cp.name||"",agent_email:cp.email||""})}Bd(Jc)}}}catch($t){console.error("Error loading members:",$t),i({title:"Error",description:"Failed to load members",variant:"destructive"})}finally{y(!1)}},da=async()=>{try{const{data:$t,error:Nn}=await q.from("app_tiles").select("id, name, icon, app_id, required_tags").order("name");if(Nn)throw Nn;d($t||[])}catch($t){console.error("Error loading apps:",$t),i({title:"Error",description:"Failed to load apps",variant:"destructive"})}},so=async $t=>{if(!ct.name.trim()||!ct.email.trim()){i({title:"Error",description:"Name and email are required",variant:"destructive"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(ct.email)){i({title:"Error",description:"Please enter a valid email address",variant:"destructive"});return}try{const{error:Un}=await q.from("profiles").update({name:ct.name.trim(),email:ct.email.trim(),brokerage_id:ct.brokerage_id||null,phone:ct.phone.trim()||null}).eq("id",$t);if(Un)throw Un;i({title:"Success",description:"Member details updated successfully"}),Ue(null),xs()}catch(Un){console.error("Error updating member:",Un),i({title:"Error",description:Un.message||"Failed to update member",variant:"destructive"})}},Ma=async $t=>{try{const{data:{session:Nn}}=await q.auth.getSession(),Un=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Nn==null?void 0:Nn.access_token}`},body:JSON.stringify({userId:$t})}),qr=await Un.json();if(!Un.ok)throw new Error(qr.error||"Failed to resend welcome email");i({title:"Success",description:"Welcome email sent successfully"})}catch(Nn){console.error("Error resending welcome email:",Nn),i({title:"Error",description:Nn.message||"Failed to resend welcome email",variant:"destructive"})}},no=async($t,Nn)=>{try{const{error:Un}=await q.functions.invoke("send-password-reset",{body:{email:$t,redirectTo:"https://dashboard.relevelup.com/profile?reset=true"}});if(Un)throw Un;i({title:"Password Reset Sent",description:`Password reset email sent to ${Nn}`})}catch(Un){console.error("Error sending password reset:",Un),i({title:"Error",description:Un.message||"Failed to send password reset email",variant:"destructive"})}},Co=async($t,Nn)=>{if(await Xi(`Are you sure you want to delete ${Nn}? This action cannot be undone.`))try{const{data:{session:Un}}=await q.auth.getSession(),qr=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/delete-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Un==null?void 0:Un.access_token}`},body:JSON.stringify({userId:$t})}),Ea=await qr.json();if(!qr.ok)throw new Error(Ea.error||"Failed to delete user");i({title:"Success",description:"User deleted successfully"}),xs()}catch(Un){console.error("Error deleting user:",Un),i({title:"Error",description:Un.message||"Failed to delete user",variant:"destructive"})}},bi=async()=>{if(!b.email||!b.name||!b.password){i({title:"Error",description:"Please fill in all fields",variant:"destructive"});return}if(b.role==="brokerage_manager"&&!b.brokerage_id){i({title:"Error",description:"Please select a brokerage for this manager",variant:"destructive"});return}g(!0);try{const{data:{session:$t}}=await q.auth.getSession(),Nn=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${$t==null?void 0:$t.access_token}`},body:JSON.stringify(b)}),Un=await Nn.json();if(!Nn.ok)throw new Error(Un.error||"Failed to create user");if(b.role&&b.role!=="user"&&Un.userId){const qr=b.role==="brokerage_manager"?b.brokerage_id:void 0;await Bu(Un.userId,b.role,"add",qr)}i({title:"Success",description:`User ${b.email} created successfully`}),j({email:"",name:"",password:"",brokerage_id:"",role:"user",phone:"",trial_days:""}),C(!1),xs()}catch($t){console.error("Error creating user:",$t),i({title:"Error",description:$t.message||"Failed to create user",variant:"destructive"})}finally{g(!1)}},Bu=async($t,Nn,Un,qr)=>{try{const{data:{session:Ea}}=await q.auth.getSession(),gi={userId:$t,role:Nn,action:Un};if(Nn==="brokerage_manager"){if(!qr){i({title:"Error",description:"Please choose a brokerage for this manager assignment",variant:"destructive"});return}gi.brokerageId=qr}const Mi=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Ea==null?void 0:Ea.access_token}`},body:JSON.stringify(gi)}),_i=await Mi.json();if(!Mi.ok)throw new Error(_i.error||"Failed to manage user role");i({title:"Success",description:`Role ${Un==="add"?"added":"removed"} successfully`}),xs()}catch(Ea){console.error("Error managing user role:",Ea),i({title:"Error",description:Ea.message||"Failed to manage user role",variant:"destructive"})}},Uu=($t,Nn)=>Nn.length===0?!0:Nn.some(Un=>$t.includes(Un)),Rx=async($t,Nn,Un)=>{const qr=`${$t}-${Nn.id}`;Vt(qr);try{if(Un){const Ea=l.find(Mi=>Mi.id===$t),gi=Nn.required_tags.filter(Mi=>Ea==null?void 0:Ea.tags.includes(Mi));for(const Mi of gi){const{error:_i}=await q.from("user_tags").delete().eq("user_id",$t).eq("tag",Mi);if(_i)throw _i}i({title:"Access Removed",description:`Removed access to ${Nn.name}`})}else if(Nn.required_tags.length>0){const{error:Ea}=await q.from("user_tags").insert({user_id:$t,tag:Nn.required_tags[0]});if(Ea)throw Ea;i({title:"Access Granted",description:`Granted access to ${Nn.name}`})}await xs()}catch(Ea){console.error("Error toggling access:",Ea),i({title:"Error",description:Ea.message||"Failed to update access",variant:"destructive"})}finally{Vt(null)}},hl=async()=>{const $t=Ft.trim();if(!$t){i({title:"Error",description:"Brokerage name is required",variant:"destructive"});return}if($t.length>100){i({title:"Error",description:"Brokerage name must be less than 100 characters",variant:"destructive"});return}if(u.find(Un=>Un.name.toLowerCase()===$t.toLowerCase())){i({title:"Error",description:"A brokerage with this name already exists",variant:"destructive"});return}vt(!0);try{const{error:Un}=await q.from("brokerages").insert({name:$t});if(Un)throw Un;i({title:"Success",description:`Brokerage "${$t}" created successfully`}),wt(""),fs(!1),xs()}catch(Un){console.error("Error creating brokerage:",Un),i({title:"Error",description:Un.message||"Failed to create brokerage",variant:"destructive"})}finally{vt(!1)}},Ua=$t=>{ar($t),Ur($t.name),As(!0)},ml=()=>{ar(null),Ur(""),As(!1)},fg=async()=>{if(!jn)return;const $t=Dn.trim();if(!$t){i({title:"Error",description:"Brokerage name is required",variant:"destructive"});return}if($t.length>100){i({title:"Error",description:"Brokerage name must be less than 100 characters",variant:"destructive"});return}hn(!0);try{const{error:Nn}=await q.from("brokerages").update({name:$t}).eq("id",jn.id);if(Nn)throw Nn;i({title:"Success",description:"Brokerage updated successfully"}),ml(),xs()}catch(Nn){console.error("Error updating brokerage:",Nn),i({title:"Error",description:Nn.message||"Failed to update brokerage",variant:"destructive"})}finally{hn(!1)}},Hg=async($t,Nn)=>{var Un;if(!Nn||typeof Nn!="string"){i({title:"Error",description:"Please select a brokerage first",variant:"destructive"});return}try{const qr={userId:$t,role:"brokerage_manager",action:"add",brokerageId:Nn};console.debug("[assignManagerToBrokerage] payload",qr);const{data:{session:Ea}}=await q.auth.getSession(),gi=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Ea==null?void 0:Ea.access_token}`},body:JSON.stringify(qr)}),Mi=await gi.json();if(!gi.ok&&!((Un=Mi.error)!=null&&Un.includes("duplicate")))throw new Error(Mi.error||"Failed to add role");i({title:"Success",description:"Manager assigned to brokerage"}),await xs()}catch(qr){console.error("Error assigning manager:",qr),i({title:"Error",description:qr.message||"Failed to assign manager",variant:"destructive"})}},Dv=$t=>{on($t),Cn(!0)},Dc=async()=>{if(Yn){Wn(!0);try{const $t=l.filter(qr=>qr.brokerage_id===Yn.id),{data:{session:Nn}}=await q.auth.getSession();for(const qr of $t){const Ea=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/delete-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Nn==null?void 0:Nn.access_token}`},body:JSON.stringify({userId:qr.id})});if(!Ea.ok){const gi=await Ea.json();console.error(`Failed to delete user ${qr.email}:`,gi.error)}}const{error:Un}=await q.from("brokerages").delete().eq("id",Yn.id);if(Un)throw Un;i({title:"Success",description:`Brokerage "${Yn.name}" and ${$t.length} member(s) deleted`}),Cn(!1),on(null),xs()}catch($t){console.error("Error deleting brokerage:",$t),i({title:"Error",description:$t.message||"Failed to delete brokerage",variant:"destructive"})}finally{Wn(!1)}}},Mp=$t=>{Gs($t),Ys(""),Fa(!0)},op=()=>{Gs(null),Ys(""),Fa(!1)},xg=async $t=>{try{const{error:Nn}=await q.from("profiles").update({brokerage_id:null}).eq("id",$t);if(Nn)throw Nn;i({title:"Success",description:"User removed from brokerage"}),xs()}catch(Nn){console.error("Error removing user from brokerage:",Nn),i({title:"Error",description:Nn.message||"Failed to remove user",variant:"destructive"})}},Rv=async($t,Nn)=>{try{const{error:Un}=await q.from("profiles").update({brokerage_id:Nn}).eq("id",$t);if(Un)throw Un;i({title:"Success",description:"User added to brokerage"}),xs()}catch(Un){console.error("Error adding user to brokerage:",Un),i({title:"Error",description:Un.message||"Failed to add user",variant:"destructive"})}};_.useEffect(()=>{(async()=>{var Nn;if(!(ks!=null&&ks.id)){es(null),Is([]),Kt("none");return}try{const{data:Un}=await q.from("partnership_programs").select("id, name, enabled").eq("brokerage_id",ks.id).maybeSingle();if(!Un||!Un.enabled){es(null),Is([]),Kt("none");return}const{data:qr}=await q.from("partnership_packages").select("id, name, description, sort_order").eq("program_id",Un.id).order("sort_order",{ascending:!0});es({id:Un.id,name:Un.name}),Is(qr||[]),Kt(((Nn=qr==null?void 0:qr[0])==null?void 0:Nn.id)||"none")}catch(Un){console.error("Error loading partnership packages:",Un)}})()},[ks==null?void 0:ks.id]);const Xf=async()=>{if(!ks||!Wt.email||!Wt.name||!Wt.password){i({title:"Error",description:"Please fill in all fields",variant:"destructive"});return}jt(!0);try{const{data:{session:$t}}=await q.auth.getSession(),Nn=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${$t==null?void 0:$t.access_token}`},body:JSON.stringify({...Wt,brokerage_id:ks.id,role:"user",partnershipPackageId:Mt&&js!=="none"?js:void 0})}),Un=await Nn.json();if(!Nn.ok)throw new Error(Un.error||"Failed to create agent");i({title:"Success",description:`Agent ${Wt.email} created successfully`}),rt({email:"",name:"",password:"",phone:""}),or(!1),xs()}catch($t){console.error("Error creating agent:",$t),i({title:"Error",description:$t.message||"Failed to create agent",variant:"destructive"})}finally{jt(!1)}},Ti=$t=>l.filter(Nn=>Nn.brokerage_id===$t),gm=$t=>{const Nn=Ti($t);if(!Ws)return Nn;const Un=Ws.toLowerCase();return Nn.filter(qr=>qr.name.toLowerCase().includes(Un)||qr.email.toLowerCase().includes(Un))},Gg=$t=>l.filter(Nn=>Nn.brokerage_id!==$t),wd=l.filter($t=>{var Un;if(E){const qr=E.toLowerCase();if(!($t.name.toLowerCase().includes(qr)||$t.email.toLowerCase().includes(qr)||((Un=$t.brokerage_name)==null?void 0:Un.toLowerCase().includes(qr))))return!1}if(V==="claimed"&&!$t.claimed||V==="unclaimed"&&$t.claimed||ae!=="all"&&!$t.roles.includes(ae))return!1;const Nn=$t.is_trial||$t.subscription_status==="trialing";if(be==="trial"&&!Nn||be==="non-trial"&&Nn||he==="none"&&$t.brokerage_id||he!=="all"&&he!=="none"&&$t.brokerage_id!==he)return!1;if(Ce!=="all"){if(!$t.created_at)return!1;const qr=parseInt(Ce,10),Ea=Date.now()-qr*24*60*60*1e3;if(new Date($t.created_at).getTime(){var Nn;return((Nn=$t.name)==null?void 0:Nn.toLowerCase())||""},brokerage:$t=>{var Nn;return((Nn=$t.brokerage_name)==null?void 0:Nn.toLowerCase())||""},status:$t=>$t.claimed?"active":"pending",role:$t=>$t.roles[0]||"",last_login:$t=>$t.last_sign_in_at?new Date($t.last_sign_in_at).getTime():null,created_at:$t=>$t.created_at?new Date($t.created_at).getTime():null}),Sh=kh.length,Zh=D===0,qu=Zh?1:Math.ceil(Sh/D),Qf=Zh?0:(M-1)*D,Dy=Zh?Sh:Qf+D,dc=kh.slice(Qf,Dy),Nd=$t=>{P($t),I(1)},cf=$t=>{O($t),I(1)},iu=($t,Nn)=>{$t(Nn),I(1)},lp=async($t,Nn)=>{Ze(!0);try{const Un=l.find(Mi=>Mi.id===$t);if(!Un)return;const qr=Un.trial_expires_at?new Date(Un.trial_expires_at):new Date,Ea=new Date(qr.getTime()+Nn*24*60*60*1e3),{error:gi}=await q.from("profiles").update({trial_expires_at:Ea.toISOString()}).eq("id",$t);if(gi)throw gi;i({title:"Trial Extended",description:`Trial extended by ${Nn} days`}),xs()}catch(Un){console.error("Error extending trial:",Un),i({title:"Error",description:Un.message||"Failed to extend trial",variant:"destructive"})}finally{Ze(!1)}},Om=async($t,Nn,Un)=>{Fe(!0);try{const{error:qr}=await q.from("profiles").update({is_paused:Nn,paused_at:Nn?new Date().toISOString():null,paused_reason:Nn&&(Un==null?void 0:Un.trim())||null}).eq("id",$t);if(qr)throw qr;o(Ea=>Ea.map(gi=>gi.id===$t?{...gi,is_paused:Nn,paused_reason:Nn&&(Un==null?void 0:Un.trim())||null,paused_at:Nn?new Date().toISOString():null}:gi)),nt(Ea=>Ea&&Ea.id===$t?{...Ea,is_paused:Nn,paused_reason:Nn&&(Un==null?void 0:Un.trim())||null}:Ea),i({title:Nn?"Account paused":"Account reactivated",description:Nn?"This member can no longer sign in and will see a paused message.":"This member can sign in again."})}catch(qr){console.error("Error updating pause state:",qr),i({title:"Error",description:qr.message||"Failed to update account",variant:"destructive"})}finally{Fe(!1)}},zm=async $t=>{qe(!0);try{const{error:Nn}=await q.from("profiles").update({is_trial:!1,trial_expires_at:null,trial_started_at:null,trial_claimed_at:null}).eq("id",$t);if(Nn)throw Nn;i({title:"Account Converted",description:"User has been converted to a full account"}),xs(),zr()}catch(Nn){console.error("Error converting trial:",Nn),i({title:"Error",description:Nn.message||"Failed to convert account",variant:"destructive"})}finally{qe(!1)}},[ot,Jt]=_.useState(!1),qs=async($t,Nn)=>{if(await Xi(`Revert this user to a ${Nn}-day free trial? This will clear their paid/grandfathered status. Any active Stripe subscription will need to be cancelled separately.`)){Jt(!0);try{const Un=new Date,qr=new Date(Un.getTime()+Nn*24*60*60*1e3),{error:Ea}=await q.from("profiles").update({is_trial:!0,trial_started_at:Un.toISOString(),trial_expires_at:qr.toISOString(),trial_claimed_at:Un.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",$t);if(Ea)throw Ea;i({title:"Reverted to Trial",description:`User is now on a ${Nn}-day free trial.`}),xs()}catch(Un){console.error("Error reverting to trial:",Un),i({title:"Error",description:Un.message||"Failed to revert to trial",variant:"destructive"})}finally{Jt(!1)}}},Xs=async $t=>{Ku(!0);try{const{data:Nn}=await q.from("agent_assistant_assignments").select("id, assistant_id, permissions").eq("agent_id",$t);if(Nn&&Nn.length>0){const qr=Nn.map(gi=>gi.assistant_id),{data:Ea}=await q.from("profiles").select("id, name, email").in("id",qr);kl(Nn.map(gi=>{const Mi=Ea==null?void 0:Ea.find(_i=>_i.id===gi.assistant_id);return{id:gi.id,assistant_id:gi.assistant_id,assistant_name:(Mi==null?void 0:Mi.name)||"Unknown",assistant_email:(Mi==null?void 0:Mi.email)||"",permissions:gi.permissions||{}}}))}else kl([]);const{data:Un}=await q.from("agent_assistant_assignments").select("id, agent_id, permissions").eq("assistant_id",$t);if(Un&&Un.length>0){const qr=Un.map(gi=>gi.agent_id),{data:Ea}=await q.from("profiles").select("id, name, email").in("id",qr);Sl(Un.map(gi=>{const Mi=Ea==null?void 0:Ea.find(_i=>_i.id===gi.agent_id);return{id:gi.id,agent_id:gi.agent_id,agent_name:(Mi==null?void 0:Mi.name)||"Unknown",agent_email:(Mi==null?void 0:Mi.email)||"",permissions:gi.permissions||{}}}))}else Sl([])}catch(Nn){console.error("Error loading assistant data:",Nn)}finally{Ku(!1)}},An=$t=>{nt($t),xt({name:$t.name,email:$t.email,brokerage_id:$t.brokerage_id||"",phone:$t.phone||""}),Ge(!0),Xs($t.id)},zr=()=>{nt(null),Ge(!1),xt({name:"",email:"",brokerage_id:"",phone:""})},Wr=async()=>{Xe&&(await so(Xe.id),zr())},Ar=$t=>{rl(Nn=>{const Un=new Set(Nn);return Un.has($t)?Un.delete($t):Un.add($t),Un})},wi=()=>{if(Gi.size===dc.length&&dc.every($t=>Gi.has($t.id))){const $t=new Set(Gi);dc.forEach(Nn=>$t.delete(Nn.id)),rl($t)}else{const $t=new Set(Gi);dc.forEach(Nn=>$t.add(Nn.id)),rl($t)}},Po=()=>{rl(new Set)},bo=async()=>{if(Gi.size===0)return;Ta(!0);let $t=0,Nn=0;try{const{data:{session:Un}}=await q.auth.getSession();for(const qr of Gi)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Un==null?void 0:Un.access_token}`},body:JSON.stringify({userId:qr,redirectTo:"https://dashboard.relevelup.com/profile?reset=true"})})).ok?$t++:Nn++}catch{Nn++}i({title:"Bulk Email Complete",description:`Sent ${$t} emails${Nn>0?`, ${Nn} failed`:""}`}),Po()}catch(Un){i({title:"Error",description:Un.message||"Failed to send emails",variant:"destructive"})}finally{Ta(!1)}},Vl=async()=>{if(Gi.size===0)return;Ta(!0);let $t=0,Nn=0;try{const{data:{session:Un}}=await q.auth.getSession();for(const qr of Gi)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/send-password-reset",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Un==null?void 0:Un.access_token}`},body:JSON.stringify({userId:qr})})).ok?$t++:Nn++}catch{Nn++}i({title:"Bulk Password Reset Complete",description:`Sent ${$t} reset emails${Nn>0?`, ${Nn} failed`:""}`}),Po()}catch(Un){i({title:"Error",description:Un.message||"Failed to send password reset emails",variant:"destructive"})}finally{Ta(!1)}},cd=async $t=>{Z(!0),ce({done:0,total:$t.length});const Nn=[];try{const{data:{session:Un}}=await q.auth.getSession(),qr=5;for(let gi=0;gi<$t.length;gi+=qr){const Mi=$t.slice(gi,gi+qr);await Promise.all(Mi.map(async _i=>{try{const Jc=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/send-password-reset",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Un==null?void 0:Un.access_token}`},body:JSON.stringify({userId:_i.id,variant:"activation"})}),Su=await Jc.json().catch(()=>({}));Jc.ok&&(Su==null?void 0:Su.sent)!==!1?Nn.push({email:_i.email,ok:!0}):Nn.push({email:_i.email,ok:!1,reason:(Su==null?void 0:Su.reason)||`HTTP ${Jc.status}`})}catch(Jc){Nn.push({email:_i.email,ok:!1,reason:(Jc==null?void 0:Jc.message)||"Network error"})}})),ce({done:Math.min(gi+qr,$t.length),total:$t.length}),gi+qr<$t.length&&await new Promise(_i=>setTimeout(_i,1200))}te(Nn);const Ea=Nn.filter(gi=>gi.ok).length;i({title:"Activation emails sent",description:`${Ea} of ${$t.length} sent successfully`})}finally{Z(!1)}},$r=async()=>{if(Gi.size===0)return;const $t=l.filter(Ea=>Gi.has(Ea.id)).map(Ea=>Ea.name).slice(0,5).join(", "),Nn=Gi.size>5?` and ${Gi.size-5} more`:"";if(!await Xi(`Are you sure you want to delete ${Gi.size} users (${$t}${Nn})? This action cannot be undone.`))return;Ta(!0);let Un=0,qr=0;try{const{data:{session:Ea}}=await q.auth.getSession();for(const gi of Gi)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/delete-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Ea==null?void 0:Ea.access_token}`},body:JSON.stringify({userId:gi})})).ok?Un++:qr++}catch{qr++}i({title:"Bulk Delete Complete",description:`Deleted ${Un} users${qr>0?`, ${qr} failed`:""}`}),Po(),xs()}catch(Ea){i({title:"Error",description:Ea.message||"Failed to delete users",variant:"destructive"})}finally{Ta(!1)}},fi=async()=>{So(!0);try{const{data:{session:$t}}=await q.auth.getSession(),Nn=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ghl-phone-sync",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${$t==null?void 0:$t.access_token}`}});if(!Nn.ok){const qr=await Nn.json();throw new Error(qr.error||"Failed to sync phones")}const Un=await Nn.json();i({title:"Phone Sync Complete",description:`Pulled ${Un.summary.pulledFromGHL} from GHL, pushed ${Un.summary.pushedToGHL} to GHL, ${Un.summary.alreadySynced} already synced`}),xs()}catch($t){i({title:"Error",description:$t.message||"Failed to sync phones with GHL",variant:"destructive"})}finally{So(!1)}},Ci=async($t,Nn)=>{Eo($t);try{const{data:{session:Un}}=await q.auth.getSession(),{data:qr}=await q.from("profiles").select("phone").eq("id",$t).single(),Ea=(qr==null?void 0:qr.phone)||"",gi=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ghl-tag-sync",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Un==null?void 0:Un.access_token}`},body:JSON.stringify({email:Nn,action:"update",phone:Ea||void 0})});if(!gi.ok){const _i=await gi.json();throw new Error(_i.error||"Failed to sync with GHL")}const Mi=await fetch(`https://services.leadconnectorhq.com/contacts/lookup?locationId=&email=${encodeURIComponent(Nn)}`,{method:"GET",headers:{"Content-Type":"application/json"}});i({title:"Phone Synced",description:Ea?`Phone ${Ea} synced to GHL`:"Sync attempted - run bulk sync to pull phone from GHL"}),xs()}catch(Un){i({title:"Error",description:Un.message||"Failed to sync phone",variant:"destructive"})}finally{Eo(null)}},tc=async $t=>{await r($t)},Hc=()=>{if(Gi.size===0){i({title:"No members selected",description:"Please select members to export",variant:"destructive"});return}const $t=l.filter(_i=>Gi.has(_i.id)),Nn=["Name","Email","Phone","Brokerage","Roles","Status","Created At"],Un=$t.map(_i=>[_i.name,_i.email,_i.phone||"",_i.brokerage_name||"",_i.roles.join("; "),_i.claimed?"Claimed":"Unclaimed",new Date(_i.created_at).toLocaleDateString()]),qr=[Nn.join(","),...Un.map(_i=>_i.map(Jc=>`"${(Jc||"").replace(/"/g,'""')}"`).join(","))].join(` `),Ea=new Blob([qr],{type:"text/csv"}),gi=URL.createObjectURL(Ea),Mi=document.createElement("a");Mi.href=gi,Mi.download=`members-export-${new Date().toISOString().split("T")[0]}.csv`,Mi.click(),URL.revokeObjectURL(gi),i({title:"Export complete",description:`Exported ${$t.length} member(s)`})},ho=()=>{if(wd.length===0){i({title:"No members to export",description:"Adjust filters to include at least one member",variant:"destructive"});return}const $t=["Name","Email","Phone","Brokerage","Roles","Status","Created At"],Nn=wd.map(_i=>[_i.name,_i.email,_i.phone||"",_i.brokerage_name||"",_i.roles.join("; "),_i.claimed?"Claimed":"Unclaimed",_i.created_at?new Date(_i.created_at).toLocaleDateString():""]),Un=[$t.join(","),...Nn.map(_i=>_i.map(Jc=>`"${(Jc||"").replace(/"/g,'""')}"`).join(","))].join(` `),qr=new Blob([Un],{type:"text/csv"}),Ea=URL.createObjectURL(qr),gi=document.createElement("a"),Mi=Ce!=="all"?`-last-${Ce}days`:"";gi.href=Ea,gi.download=`members-export${Mi}-${new Date().toISOString().split("T")[0]}.csv`,gi.click(),URL.revokeObjectURL(Ea),i({title:"Export complete",description:`Exported ${wd.length} member(s)`})};return f?e.jsx(zs,{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(zs,{title:"Members",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsx(Wh,{title:"Member Management",description:"Manage users, roles, and permissions",children:e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>s("/admin/unassigned-members"),className:"gap-2",children:[e.jsx(xl,{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(B,{size:"sm",variant:"outline",onClick:fi,disabled:eo,children:[eo?e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(_a,{className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:eo?"Syncing...":"Sync Phones with GHL"}),e.jsx("span",{className:"sm:hidden",children:eo?"Syncing...":"Sync GHL"})]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>an(!0),children:[e.jsx(uS,{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(Ls,{open:S,onOpenChange:C,children:[e.jsx(nl,{asChild:!0,children:e.jsxs(B,{size:"sm",children:[e.jsx(Pl,{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(Ps,{children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Create New User"}),e.jsx(_r,{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(J,{htmlFor:"name",children:"Name"}),e.jsx(xe,{id:"name",placeholder:"John Doe",value:b.name,onChange:$t=>j({...b,name:$t.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"email",children:"Email"}),e.jsx(xe,{id:"email",type:"email",placeholder:"john@example.com",value:b.email,onChange:$t=>j({...b,email:$t.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"password",children:"Password"}),e.jsx(xe,{id:"password",type:"password",placeholder:"Min 6 characters",value:b.password,onChange:$t=>j({...b,password:$t.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"phone",children:"Phone (optional)"}),e.jsx(xe,{id:"phone",type:"tel",placeholder:"555-123-4567",value:b.phone,onChange:$t=>j({...b,phone:$t.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(J,{htmlFor:"brokerage",children:["Brokerage",b.role==="brokerage_manager"?" (required)":""]}),e.jsxs(is,{value:b.brokerage_id||"none",onValueChange:$t=>j({...b,brokerage_id:$t==="none"?"":$t}),children:[e.jsx(rs,{id:"brokerage",children:e.jsx(ls,{placeholder:b.role==="brokerage_manager"?"Select brokerage":"Select brokerage (optional)"})}),e.jsxs(as,{children:[e.jsx(He,{value:"none",children:"None"}),u.map($t=>e.jsx(He,{value:$t.id,children:$t.name},$t.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"role",children:"Role"}),e.jsxs(is,{value:b.role,onValueChange:$t=>j({...b,role:$t}),children:[e.jsx(rs,{id:"role",children:e.jsx(ls,{placeholder:"Select role"})}),e.jsxs(as,{children:[e.jsx(He,{value:"user",children:"User"}),e.jsx(He,{value:"moderator",children:"Moderator"}),e.jsx(He,{value:"brokerage_manager",children:"Brokerage Manager"}),e.jsx(He,{value:"admin",children:"Admin"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"trial_days",children:"Trial Period (optional)"}),e.jsxs(is,{value:b.trial_days||"none",onValueChange:$t=>j({...b,trial_days:$t==="none"?"":$t}),children:[e.jsx(rs,{id:"trial_days",children:e.jsx(ls,{placeholder:"No trial (full access)"})}),e.jsxs(as,{children:[e.jsx(He,{value:"none",children:"No trial (full access)"}),e.jsx(He,{value:"7",children:"7-day trial"}),e.jsx(He,{value:"30",children:"30-day trial"}),e.jsx(He,{value:"60",children:"60-day trial"}),e.jsx(He,{value:"90",children:"90-day trial"}),e.jsx(He,{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(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>C(!1),children:"Cancel"}),e.jsx(B,{onClick:bi,disabled:v,children:v?"Creating...":"Create User"})]})]})]})]})]}),e.jsxs(Yr,{defaultValue:new URLSearchParams(window.location.search).get("tab")||"members",className:"space-y-6",children:[e.jsxs(Zr,{children:[e.jsx(Ht,{value:"members",children:"Members"}),e.jsx(Ht,{value:"brokerages",children:"Brokerages"}),e.jsx(Ht,{value:"teams",children:"Teams"}),e.jsx(Ht,{value:"trials",children:"Trial Users"}),e.jsx(Ht,{value:"access",children:"Access Matrix"}),e.jsx(Ht,{value:"celebrations",children:"Celebrations"}),e.jsx(Ht,{value:"deletions",children:"Deletion Log"})]}),e.jsxs(Gt,{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(Lr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search members...",value:E,onChange:$t=>Nd($t.target.value),className:"pl-10 h-9"})]}),e.jsxs(is,{value:V,onValueChange:$t=>iu(G,$t),children:[e.jsx(rs,{className:"w-[130px] h-9",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Status"}),e.jsx(He,{value:"claimed",children:"Active"}),e.jsx(He,{value:"unclaimed",children:"Pending"})]})]}),e.jsxs(is,{value:ae,onValueChange:$t=>iu(le,$t),children:[e.jsx(rs,{className:"w-[130px] h-9",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Roles"}),e.jsx(He,{value:"admin",children:"Admin"}),e.jsx(He,{value:"brokerage_manager",children:"Manager"}),e.jsx(He,{value:"assistant",children:"Assistant"}),e.jsx(He,{value:"user",children:"User"})]})]}),e.jsxs(is,{value:be,onValueChange:$t=>iu(me,$t),children:[e.jsx(rs,{className:"w-[130px] h-9",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Users"}),e.jsx(He,{value:"trial",children:"Trial Only"}),e.jsx(He,{value:"non-trial",children:"Full Only"})]})]}),e.jsxs(is,{value:he,onValueChange:$t=>iu(pe,$t),children:[e.jsx(rs,{className:"w-[150px] h-9",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Brokerages"}),e.jsx(He,{value:"none",children:"No Brokerage"}),u.map($t=>e.jsx(He,{value:$t.id,children:$t.name},$t.id))]})]}),e.jsxs(is,{value:Ce,onValueChange:$t=>iu(Ae,$t),children:[e.jsx(rs,{className:"w-[150px] h-9",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"Any Join Date"}),e.jsx(He,{value:"30",children:"Joined Last 30 Days"}),e.jsx(He,{value:"60",children:"Joined Last 60 Days"}),e.jsx(He,{value:"90",children:"Joined Last 90 Days"})]})]}),e.jsxs(B,{size:"sm",variant:"outline",className:"h-9",onClick:ho,title:"Export currently filtered members to CSV",children:[e.jsx(li,{className:"h-4 w-4 mr-1"}),"Export Filtered"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"h-9",disabled:kh.filter($t=>!$t.claimed&&$t.email).length===0,onClick:()=>{te(null),H(!0)},title:"Email every pending (never signed in) member a link to set their password",children:[e.jsx(ln,{className:"h-4 w-4 mr-1"}),"Email Pending (",kh.filter($t=>!$t.claimed&&$t.email).length,")"]}),e.jsx(Ls,{open:$,onOpenChange:$t=>{Y||H($t)},children:e.jsxs(Ps,{className:"max-w-lg",children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Email pending members"}),e.jsx(_r,{children:'Sends the branded "Activate your account" email with a set-password link to every member in the current filter who has never signed in. Sent in small batches, so this can take a few minutes.'})]}),Y&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Sending… ",ne.done," of ",ne.total]}),ie&&!Y&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-sm",children:[ie.filter($t=>$t.ok).length," sent",ie.some($t=>!$t.ok)&&`, ${ie.filter($t=>!$t.ok).length} failed`]}),ie.some($t=>!$t.ok)&&e.jsx("div",{className:"max-h-48 overflow-y-auto rounded border p-2 text-xs space-y-1",children:ie.filter($t=>!$t.ok).map($t=>e.jsxs("div",{className:"flex justify-between gap-2",children:[e.jsx("span",{className:"truncate",children:$t.email}),e.jsx("span",{className:"text-muted-foreground truncate",children:$t.reason})]},$t.email))})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",disabled:Y,onClick:()=>H(!1),children:"Close"}),!ie&&e.jsx(B,{disabled:Y,onClick:()=>cd(kh.filter($t=>!$t.claimed&&$t.email).map($t=>({id:$t.id,email:$t.email,name:$t.name}))),children:Y?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"h-4 w-4 mr-1 animate-spin"}),"Sending…"]}):`Send to ${kh.filter($t=>!$t.claimed&&$t.email).length} members`})]})]})}),(E||V!=="all"||ae!=="all"||be!=="all"||he!=="all"||Ce!=="all")&&e.jsxs(B,{variant:"ghost",size:"sm",className:"h-9",onClick:()=>{P(""),G("all"),le("all"),me("all"),pe("all"),Ae("all"),I(1)},children:[e.jsx(Qn,{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:Zh?`Showing all ${Sh} members`:`Showing ${Qf+1}-${Math.min(Dy,Sh)} of ${Sh} members`}),e.jsxs(is,{value:D.toString(),onValueChange:$t=>cf(Number($t)),children:[e.jsx(rs,{className:"h-9 w-[110px]",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"50",children:"50 / page"}),e.jsx(He,{value:"100",children:"100 / page"}),e.jsx(He,{value:"250",children:"250 / page"}),e.jsx(He,{value:"0",children:"All"})]})]})]})]}),Gi.size>0&&e.jsxs("div",{className:"flex flex-col gap-2 p-3 bg-primary/10 border border-primary/20 rounded-lg",children:[dc.length>0&&dc.every($t=>Gi.has($t.id))&&kh.length>Gi.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 ",Gi.size," on this page are selected."]}),e.jsxs(B,{size:"sm",variant:"link",className:"h-auto p-0 text-primary",onClick:()=>rl(new Set(kh.map($t=>$t.id))),children:["Select all ",kh.length," filtered members"]})]}),kh.length>0&&Gi.size===kh.length&&e.jsxs("div",{className:"px-1 text-sm text-muted-foreground",children:["All ",kh.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(Ww,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{className:"text-sm font-medium",children:[Gi.size," selected"]})]}),e.jsx("div",{className:"flex-1"}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(B,{size:"sm",variant:"outline",onClick:bo,disabled:Ii,children:[Ii?e.jsx(Ct,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(ln,{className:"h-4 w-4 mr-1"}),e.jsx("span",{className:"hidden sm:inline",children:"Resend Invite"}),e.jsx("span",{className:"sm:hidden",children:"Invite"})]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:Vl,disabled:Ii,children:[Ii?e.jsx(Ct,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(_b,{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(B,{size:"sm",variant:"outline",onClick:()=>ze(!0),disabled:Ii,className:"bg-primary/5 border-primary/30 text-primary hover:bg-primary/10",children:[e.jsx(dS,{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(B,{size:"sm",variant:"outline",onClick:Hc,children:[e.jsx(li,{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(B,{size:"sm",variant:"destructive",onClick:$r,disabled:Ii,children:[Ii?e.jsx(Ct,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(Sn,{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(B,{size:"sm",variant:"ghost",onClick:Po,disabled:Ii,children:e.jsx(Qn,{className:"h-4 w-4"})})]})]})]}),e.jsx("div",{className:"border rounded-lg bg-card overflow-hidden",children:e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Pt,{className:"w-[50px]",children:e.jsx($a,{checked:dc.length>0&&dc.every($t=>Gi.has($t.id)),onCheckedChange:wi,"aria-label":"Select all on page"})}),e.jsx(qh,{sortKey:"name",currentSortKey:jd,currentDirection:Yu,onSort:Yh,children:"Name"}),e.jsx(qh,{sortKey:"brokerage",currentSortKey:jd,currentDirection:Yu,onSort:Yh,children:"Brokerage"}),e.jsx(qh,{sortKey:"status",currentSortKey:jd,currentDirection:Yu,onSort:Yh,children:"Status"}),e.jsx(qh,{sortKey:"role",currentSortKey:jd,currentDirection:Yu,onSort:Yh,children:"Role"}),e.jsx(qh,{sortKey:"last_login",currentSortKey:jd,currentDirection:Yu,onSort:Yh,children:"Last Login"}),e.jsx(qh,{sortKey:"created_at",currentSortKey:jd,currentDirection:Yu,onSort:Yh,children:"Member Since"}),e.jsx(Pt,{className:"w-[100px]"})]})}),e.jsx(Ka,{children:dc.length===0?e.jsx(pn,{children:e.jsx(gt,{colSpan:8,className:"text-center py-12 text-muted-foreground",children:"No members found"})}):dc.map($t=>e.jsxs(pn,{className:`hover:bg-muted/30 ${Gi.has($t.id)?"bg-primary/5":""}`,children:[e.jsx(gt,{children:e.jsx($a,{checked:Gi.has($t.id),onCheckedChange:()=>Ar($t.id),"aria-label":`Select ${$t.name}`})}),e.jsx(gt,{children:e.jsxs("div",{children:[e.jsx("button",{onClick:()=>An($t),className:"text-primary hover:underline font-medium text-left",children:$t.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:$t.email})]})}),e.jsx(gt,{className:"text-muted-foreground",children:$t.brokerage_name||"—"}),e.jsx(gt,{children:e.jsx("div",{className:"flex flex-col",children:(()=>{const Nn=$t.trial_expires_at||$t.subscription_end_date;if(($t.is_trial||$t.subscription_status==="trialing")&&Nn){const qr=Math.ceil((new Date(Nn).getTime()-Date.now())/864e5),Ea=qr<=0,gi=qr<=3;return e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Oe,{variant:"outline",className:At("w-fit",Ea?"border-destructive text-destructive":gi?"border-amber-500 text-amber-600":"border-violet-300 text-violet-700 bg-violet-50"),children:Ea?"Trial Expired":`Trial · ${qr}d left`}),e.jsx("button",{type:"button",title:"Copy upgrade link — paste into an email so this agent can sign in and pay on their existing account",className:"text-muted-foreground hover:text-primary transition-colors",onClick:async()=>{const Mi="https://dashboard.relevelup.com/upgrade";try{await navigator.clipboard.writeText(Mi),i({title:"Upgrade link copied",description:Mi})}catch{window.prompt("Copy this upgrade link:",Mi)}},children:e.jsx(Ia,{className:"h-3.5 w-3.5"})})]})}return e.jsx(Oe,{variant:$t.claimed?"default":"secondary",className:$t.claimed?"bg-primary text-primary-foreground w-fit":"w-fit",children:$t.claimed?"Active":"Pending"})})()})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex flex-col",children:[$t.roles.length>0?e.jsx("span",{className:"text-sm capitalize",children:$t.roles[0]}):e.jsx("span",{className:"text-muted-foreground",children:"—"}),$t.roles.includes("assistant")&&Tp[$t.id]&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["→ ",Tp[$t.id].agent_name||Tp[$t.id].agent_email]})]})}),e.jsx(gt,{className:"text-muted-foreground",children:$t.last_sign_in_at?new Date($t.last_sign_in_at).toLocaleDateString():"—"}),e.jsx(gt,{className:"text-muted-foreground",children:$t.created_at?new Date($t.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(B,{size:"icon",variant:"ghost",className:"h-8 w-8 text-yellow-500 hover:text-yellow-600 hover:bg-yellow-50",onClick:()=>{oi($t),di(!0)},title:"Send celebration",children:e.jsx(Ex,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>An($t),title:"Edit member",children:e.jsx(Ya,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>Ci($t.id,$t.email),disabled:Ra===$t.id,title:"Sync phone with GHL",children:Ra===$t.id?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(_a,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>Ma($t.id),title:"Resend welcome email",children:e.jsx(ln,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>no($t.email,$t.name),title:"Send password reset",children:e.jsx(VA,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8 text-blue-600 hover:text-blue-700 hover:bg-blue-50",onClick:()=>tc($t.id),disabled:a||$t.id===(t==null?void 0:t.id),title:$t.id===(t==null?void 0:t.id)?"Cannot impersonate yourself":`Login as ${$t.name}`,children:a?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(QM,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:()=>Co($t.id,$t.name),title:"Delete user",children:e.jsx(Sn,{className:"h-4 w-4"})})]})})]},$t.id))})]})}),qu>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 ",qu]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(B,{variant:"outline",size:"sm",onClick:()=>I(1),disabled:M===1,children:"First"}),e.jsx(B,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>I($t=>Math.max(1,$t-1)),disabled:M===1,children:e.jsx($c,{className:"h-4 w-4"})}),e.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:Math.min(5,qu)},($t,Nn)=>{let Un;return qu<=5||M<=3?Un=Nn+1:M>=qu-2?Un=qu-4+Nn:Un=M-2+Nn,e.jsx(B,{variant:M===Un?"default":"outline",size:"sm",className:"h-8 w-8 p-0",onClick:()=>I(Un),children:Un},Un)})}),e.jsx(B,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>I($t=>Math.min(qu,$t+1)),disabled:M===qu,children:e.jsx(xi,{className:"h-4 w-4"})}),e.jsx(B,{variant:"outline",size:"sm",onClick:()=>I(qu),disabled:M===qu,children:"Last"})]})]})]}),e.jsx(Ls,{open:$e,onOpenChange:Ge,children:e.jsxs(Ps,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Edit Member"}),e.jsx(_r,{children:"Update member details, roles, and app access"})]}),Xe&&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(J,{htmlFor:"edit-name",children:"Name"}),e.jsx(xe,{id:"edit-name",value:ct.name,onChange:$t=>xt({...ct,name:$t.target.value}),maxLength:100})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"edit-email",children:"Email"}),e.jsx(xe,{id:"edit-email",type:"email",value:ct.email,onChange:$t=>xt({...ct,email:$t.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(J,{htmlFor:"edit-phone",children:"Phone"}),e.jsx(xe,{id:"edit-phone",type:"tel",value:ct.phone,onChange:$t=>xt({...ct,phone:$t.target.value}),placeholder:"555-123-4567"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"edit-brokerage",children:"Brokerage"}),e.jsxs(is,{value:ct.brokerage_id||"none",onValueChange:$t=>xt({...ct,brokerage_id:$t==="none"?"":$t}),children:[e.jsx(rs,{id:"edit-brokerage",children:e.jsx(ls,{placeholder:"Select brokerage"})}),e.jsxs(as,{children:[e.jsx(He,{value:"none",children:"None"}),u.map($t=>e.jsx(He,{value:$t.id,children:$t.name},$t.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:[Xe.roles.map($t=>e.jsxs(Oe,{variant:"default",className:"gap-1",children:[e.jsx(Rm,{className:"h-3 w-3"}),$t,$t==="brokerage_manager"?e.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:"(manage in Brokerages tab)"}):e.jsx("button",{onClick:()=>Bu(Xe.id,$t,"remove"),className:"ml-1 rounded-full hover:bg-destructive/20",title:"Remove role",children:e.jsx(Qn,{className:"h-3 w-3"})})]},$t)),Xe.roles.length===0&&e.jsx("span",{className:"text-sm text-muted-foreground",children:"No roles assigned"})]}),e.jsxs(is,{onValueChange:$t=>Bu(Xe.id,$t,"add"),children:[e.jsx(rs,{className:"w-[200px]",children:e.jsx(ls,{placeholder:"Add role..."})}),e.jsxs(as,{children:[!Xe.roles.includes("admin")&&e.jsx(He,{value:"admin",children:"Admin"}),!Xe.roles.includes("user")&&e.jsx(He,{value:"user",children:"User"})]})]}),!Xe.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"})]}),(Oo.length>0||Jo.length>0||Xe.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(In,{className:"h-4 w-4"}),"Assistant Relationships"]}),vu?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Ct,{className:"h-4 w-4 animate-spin"}),"Loading..."]}):e.jsxs("div",{className:"space-y-3",children:[Oo.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:"}),Oo.map($t=>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:$t.assistant_name}),e.jsx(Oe,{variant:"outline",className:"text-xs",children:"Assistant"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:$t.assistant_email}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:Object.entries($t.permissions).filter(([,Nn])=>Nn).map(([Nn])=>e.jsx(Oe,{variant:"secondary",className:"text-[10px] capitalize",children:Nn},Nn))})]},$t.id))]}),Jo.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:"}),Jo.map($t=>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:$t.agent_name}),e.jsx(Oe,{variant:"outline",className:"text-xs",children:"Agent"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:$t.agent_email}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:Object.entries($t.permissions).filter(([,Nn])=>Nn).map(([Nn])=>e.jsx(Oe,{variant:"secondary",className:"text-[10px] capitalize",children:Nn},Nn))})]},$t.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($t=>{const Nn=Uu(Xe.tags,$t.required_tags),Un=`${Xe.id}-${$t.id}`,qr=qt===Un,Ea=$t.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:$t.icon}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:$t.name}),Ea&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Available to all members"})]})]}),e.jsx("div",{className:"flex items-center gap-2",children:qr?e.jsx(Ct,{className:"h-4 w-4 animate-spin text-muted-foreground"}):Ea?e.jsx(Oe,{variant:"secondary",className:"text-xs",children:"Always On"}):e.jsx(fn,{checked:Nn,onCheckedChange:()=>Rx(Xe.id,$t,Nn)})})]},$t.id)})})]}),e.jsxs("div",{className:"space-y-3 pt-4 border-t",children:[e.jsx("h3",{className:"text-sm font-semibold",children:"Account Access"}),Xe.is_paused?e.jsxs("div",{className:"p-4 rounded-lg border bg-amber-50 dark:bg-amber-950/20 border-amber-200 dark:border-amber-800 space-y-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:"This account is paused"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["They cannot sign in and see a paused message on the login page.",Xe.paused_reason?` Reason shown: “${Xe.paused_reason}”`:""]})]}),e.jsx(B,{size:"sm",onClick:()=>Om(Xe.id,!1),disabled:Se,children:"Reactivate account"})]}):e.jsxs("div",{className:"p-4 rounded-lg border bg-muted/30 space-y-3",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Pausing blocks sign-in and shows this member a message explaining their account is paused."}),e.jsx(xe,{placeholder:"Optional message shown to them (e.g. Payment is past due.)",value:Ne,onChange:$t=>Ye($t.target.value)}),e.jsx(B,{size:"sm",variant:"destructive",onClick:async()=>{await Om(Xe.id,!0,Ne),Ye("")},disabled:Se,children:"Pause account"})]})]}),(Xe.is_trial||Xe.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(Gr,{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:[Xe.trial_expires_at&&e.jsx(Dvt,{expiresAt:Xe.trial_expires_at}),!Xe.trial_expires_at&&Xe.subscription_status==="trialing"&&Xe.subscription_end_date&&e.jsx(Dvt,{expiresAt:Xe.subscription_end_date})]}),(Xe.trial_expires_at||Xe.subscription_end_date)&&e.jsxs("span",{className:"text-sm text-muted-foreground",children:["Expires: ",new Date(Xe.trial_expires_at||Xe.subscription_end_date).toLocaleDateString()]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>lp(Xe.id,7),disabled:ke,children:[e.jsx(gy,{className:"h-4 w-4 mr-1"}),"+7 Days"]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>lp(Xe.id,14),disabled:ke,children:[e.jsx(gy,{className:"h-4 w-4 mr-1"}),"+14 Days"]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>lp(Xe.id,30),disabled:ke,children:[e.jsx(gy,{className:"h-4 w-4 mr-1"}),"+30 Days"]}),e.jsxs(B,{size:"sm",variant:"default",onClick:()=>zm(Xe.id),disabled:Ve,className:"bg-green-600 hover:bg-green-700",children:[e.jsx(gj,{className:"h-4 w-4 mr-1"}),"Convert to Full Account"]})]}),Xe.trial_started_at&&e.jsxs("div",{className:"mt-3 text-xs text-muted-foreground",children:["Trial started: ",new Date(Xe.trial_started_at).toLocaleDateString(),Xe.trial_claimed_at&&e.jsxs("span",{children:[" • Claimed: ",new Date(Xe.trial_claimed_at).toLocaleDateString()]})]})]})]}),!(Xe.is_trial||Xe.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(Gr,{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($t=>e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>qs(Xe.id,$t),disabled:ot,children:[e.jsx(gy,{className:"h-4 w-4 mr-1"}),$t,"-day trial"]},$t))})]})]}),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:[Xe.email_confirmed_at&&e.jsxs("div",{children:["Claimed: ",new Date(Xe.email_confirmed_at).toLocaleString()]}),Xe.last_sign_in_at&&e.jsxs("div",{children:["Last login: ",new Date(Xe.last_sign_in_at).toLocaleString()]}),e.jsxs("div",{children:["Created: ",new Date(Xe.created_at).toLocaleString()]})]})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:zr,children:"Cancel"}),e.jsx(B,{onClick:Wr,children:"Save Changes"})]})]})}),e.jsxs(Gt,{value:"access",children:[c.length===0?e.jsx(ve,{children:e.jsxs(Me,{className:"py-12 text-center",children:[e.jsx("p",{className:"text-muted-foreground mb-4",children:"No apps configured yet"}),e.jsx(B,{onClick:()=>s("/admin/apps"),children:"Configure Apps"})]})}):e.jsxs(ve,{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(St,{children:"Member Access Matrix"}),e.jsx(kn,{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(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search agents by name or email...",value:E,onChange:$t=>{P($t.target.value),I(1)},className:"pl-9"})]})]}),e.jsxs(Me,{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($t=>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:$t.icon}),e.jsx("span",{className:"text-sm",children:$t.name})]})},$t.id))]})}),e.jsxs("tbody",{children:[dc.map($t=>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:$t.name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:$t.email})]})}),c.map(Nn=>{const Un=Uu($t.tags,Nn.required_tags),qr=`${$t.id}-${Nn.id}`,Ea=qt===qr;return e.jsx("td",{className:"p-4 text-center",children:e.jsx("div",{className:"flex items-center justify-center",children:Ea?e.jsx(Ct,{className:"h-5 w-5 animate-spin text-muted-foreground"}):e.jsx(fn,{checked:Un,onCheckedChange:()=>Rx($t.id,Nn,Un),disabled:Nn.required_tags.length===0})})},Nn.id)})]},$t.id)),dc.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"})})]})]})}),qu>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 ",Qf+1,"-",Math.min(Dy,Sh)," of ",Sh," • Page ",M," of ",qu]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(B,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>I($t=>Math.max(1,$t-1)),disabled:M===1,children:e.jsx($c,{className:"h-4 w-4"})}),e.jsx(B,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>I($t=>Math.min(qu,$t+1)),disabled:M===qu,children:e.jsx(xi,{className:"h-4 w-4"})})]})]})]})]}),e.jsx("div",{className:"mt-6",children:e.jsx(B,{variant:"outline",onClick:()=>s("/admin/apps"),children:"Manage Apps"})})]}),e.jsxs(Gt,{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(Lr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search brokerages...",value:er,onChange:$t=>Xr($t.target.value),className:"pl-10"})]}),e.jsxs("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:[u.filter($t=>$t.name.toLowerCase().includes(er.toLowerCase())).length," of ",u.length," brokerages"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>{const $t=[];for(const Mi of u){const _i=m[Mi.id]??[];for(const Jc of _i){const Su=l.find(cp=>cp.id===Jc);if(Su){const cp=(Su.name||"").trim().split(/\s+/),dd=cp[0]||"",Ud=cp.slice(1).join(" ")||"";$t.push({firstName:dd,lastName:Ud,email:Su.email,brokerageName:Mi.name})}}}if($t.length===0){i({title:"No managers found to export"});return}const Un=[["First Name","Last Name","Email","Brokerage Name"].join(","),...$t.map(Mi=>[Mi.firstName,Mi.lastName,Mi.email,Mi.brokerageName].map(_i=>`"${(_i||"").replace(/"/g,'""')}"`).join(","))].join(` `),qr=new Blob([Un],{type:"text/csv"}),Ea=URL.createObjectURL(qr),gi=document.createElement("a");gi.href=Ea,gi.download=`brokerage-managers-${new Date().toISOString().slice(0,10)}.csv`,gi.click(),URL.revokeObjectURL(Ea),i({title:`Exported ${$t.length} managers`})},children:[e.jsx(li,{className:"mr-2 h-4 w-4"}),"Export Managers"]}),e.jsxs(Ls,{open:Xt,onOpenChange:fs,children:[e.jsx(nl,{asChild:!0,children:e.jsxs(B,{size:"sm",children:[e.jsx(ai,{className:"mr-2 h-4 w-4"}),"Add Brokerage"]})}),e.jsxs(Ps,{children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Create New Brokerage"}),e.jsx(_r,{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(J,{htmlFor:"brokerage-name",children:"Brokerage Name"}),e.jsx(xe,{id:"brokerage-name",placeholder:"Enter brokerage name",value:Ft,onChange:$t=>wt($t.target.value),maxLength:100})]})}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>fs(!1),children:"Cancel"}),e.jsx(B,{onClick:hl,disabled:Ts,children:Ts?"Creating...":"Create Brokerage"})]})]})]})]})]}),e.jsx("div",{className:"border rounded-lg bg-card overflow-hidden",children:e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Pt,{className:"font-semibold",children:"Brokerage Name"}),e.jsx(Pt,{className:"font-semibold",children:"Manager(s)"}),e.jsx(Pt,{className:"font-semibold",children:"Agents"}),e.jsx(Pt,{className:"w-[150px]"})]})}),e.jsx(Ka,{children:(()=>{const $t=u.filter(Nn=>Nn.name.toLowerCase().includes(er.toLowerCase()));return $t.length===0?e.jsx(pn,{children:e.jsx(gt,{colSpan:4,className:"text-center py-12 text-muted-foreground",children:er?"No brokerages match your search":"No brokerages found"})}):$t.map(Nn=>{const Un=l.filter(Mi=>Mi.brokerage_id===Nn.id),Ea=(m[Nn.id]??[]).map(Mi=>l.find(_i=>_i.id===Mi)).filter(Boolean),gi=Un.length;return e.jsxs(pn,{className:"hover:bg-muted/30",children:[e.jsx(gt,{children:e.jsx("button",{onClick:()=>Ua(Nn),className:"text-primary hover:underline font-medium",children:Nn.name})}),e.jsx(gt,{children:Ea.length>0?e.jsx("div",{className:"flex flex-wrap gap-1",children:Ea.map(Mi=>e.jsx(Oe,{variant:"secondary",className:"text-xs",children:Mi.name},Mi.id))}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"No manager"})}),e.jsxs(gt,{children:[gi," member",gi!==1?"s":""]}),e.jsx(gt,{children:e.jsxs("div",{className:"flex gap-1 justify-end",children:[e.jsxs(B,{size:"sm",variant:"outline",className:"h-8",onClick:()=>Mp(Nn),children:[e.jsx(In,{className:"h-4 w-4 mr-1"}),"Manage"]}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>Ua(Nn),title:"Edit brokerage",children:e.jsx(Ya,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:()=>Dv(Nn),title:"Delete brokerage",children:e.jsx(Sn,{className:"h-4 w-4"})})]})})]},Nn.id)})})()})]})}),e.jsx(Ls,{open:$s,onOpenChange:As,children:e.jsxs(Ps,{className:"max-w-lg",children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Edit Brokerage"}),e.jsx(_r,{children:"Update brokerage details and manage managers"})]}),jn&&e.jsxs("div",{className:"space-y-6 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"edit-brokerage-name",children:"Brokerage Name"}),e.jsx(xe,{id:"edit-brokerage-name",value:Dn,onChange:$t=>Ur($t.target.value),maxLength:100})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(J,{children:"Managers"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Click × to remove manager access for this brokerage (keeps them as a member)"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:(()=>{const Nn=(m[jn.id]??[]).map(Un=>l.find(qr=>qr.id===Un)).filter(Boolean);return Nn.length===0?e.jsx("span",{className:"text-sm text-muted-foreground",children:"No managers assigned"}):Nn.map(Un=>e.jsxs(Oe,{variant:"default",className:"gap-1",children:[e.jsx(Rm,{className:"h-3 w-3"}),Un.name,e.jsx("button",{onClick:()=>Bu(Un.id,"brokerage_manager","remove",jn.id),className:"ml-1 rounded-full hover:bg-destructive/20",title:"Remove manager from this brokerage",children:e.jsx(Qn,{className:"h-3 w-3"})})]},Un.id))})()}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{className:"text-sm text-muted-foreground",children:"Assign manager from existing members:"}),e.jsxs(od,{open:ma,onOpenChange:Br,children:[e.jsx(ld,{asChild:!0,children:e.jsxs(B,{variant:"outline",role:"combobox","aria-expanded":ma,className:"w-full justify-between",children:["Search for a member...",e.jsx(Lr,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Qc,{className:"w-full p-0",align:"start",children:e.jsxs(Aj,{children:[e.jsx(Ej,{placeholder:"Search by name or email..."}),e.jsxs(Tj,{className:"max-h-[200px]",children:[e.jsx(Mj,{children:"No members found."}),e.jsx(V_,{children:(()=>{const $t=new Set(m[jn.id]??[]);return l.filter(Nn=>!$t.has(Nn.id)&&(n||Nn.brokerage_id===jn.id)).map(Nn=>e.jsxs(d1,{value:`${Nn.name} ${Nn.email}`,onSelect:()=>{Hg(Nn.id,jn.id),Br(!1)},children:[Nn.name," (",Nn.email,")"]},Nn.id))})()})]})]})})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Members in this Brokerage"}),e.jsx("div",{className:"max-h-32 overflow-y-auto border rounded p-2",children:l.filter($t=>$t.brokerage_id===jn.id).length===0?e.jsx("span",{className:"text-sm text-muted-foreground",children:"No members"}):l.filter($t=>$t.brokerage_id===jn.id).map($t=>e.jsxs("div",{className:"text-sm py-1 flex items-center justify-between",children:[e.jsx("span",{children:$t.name}),$t.roles.includes("brokerage_manager")&&e.jsx(Oe,{variant:"outline",className:"text-xs",children:"Manager"})]},$t.id))})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:ml,children:"Cancel"}),e.jsx(B,{onClick:fg,disabled:Vs,children:Vs?"Saving...":"Save Changes"})]})]})}),e.jsx(Ls,{open:dr,onOpenChange:Cn,children:e.jsxs(Ps,{children:[e.jsxs(Os,{children:[e.jsx(Ds,{className:"text-destructive",children:"Delete Brokerage"}),e.jsxs(_r,{children:['Are you sure you want to delete "',Yn==null?void 0:Yn.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 "',Yn==null?void 0:Yn.name,'"']}),e.jsxs("li",{children:["All ",l.filter($t=>$t.brokerage_id===(Yn==null?void 0:Yn.id)).length," member(s) assigned to this brokerage"]}),e.jsx("li",{children:"All their data, roles, and access"})]})]})}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>Cn(!1),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:Dc,disabled:Ir,children:Ir?"Deleting...":"Yes, Delete Brokerage"})]})]})}),e.jsx(Ls,{open:Js,onOpenChange:Fa,children:e.jsxs(Ps,{className:"max-w-4xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsxs(Os,{children:[e.jsxs(Ds,{className:"flex items-center gap-2",children:[e.jsx(ai,{className:"h-5 w-5"}),"Manage ",ks==null?void 0:ks.name]}),e.jsx(_r,{children:"Add, remove, or manage users in this brokerage"})]}),ks&&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(Lr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search members...",value:Ws,onChange:$t=>Ys($t.target.value),className:"pl-10 h-9"})]}),e.jsxs(Ls,{open:Bn,onOpenChange:or,children:[e.jsx(nl,{asChild:!0,children:e.jsxs(B,{size:"sm",children:[e.jsx(Pl,{className:"h-4 w-4 mr-1"}),"Add New Agent"]})}),e.jsxs(Ps,{children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Add New Agent"}),e.jsxs(_r,{children:["Create a new agent for ",ks.name]})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"agent-name",children:"Name"}),e.jsx(xe,{id:"agent-name",placeholder:"John Doe",value:Wt.name,onChange:$t=>rt({...Wt,name:$t.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"agent-email",children:"Email"}),e.jsx(xe,{id:"agent-email",type:"email",placeholder:"john@example.com",value:Wt.email,onChange:$t=>rt({...Wt,email:$t.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"agent-password",children:"Password"}),e.jsx(xe,{id:"agent-password",type:"password",placeholder:"Min 6 characters",value:Wt.password,onChange:$t=>rt({...Wt,password:$t.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"agent-phone",children:"Phone (optional)"}),e.jsx(xe,{id:"agent-phone",type:"tel",placeholder:"555-123-4567",value:Wt.phone,onChange:$t=>rt({...Wt,phone:$t.target.value})})]}),Mt&&ps.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(J,{htmlFor:"agent-package",children:[Mt.name," Package"]}),e.jsxs(is,{value:js,onValueChange:Kt,children:[e.jsx(rs,{id:"agent-package",children:e.jsx(ls,{placeholder:"Select a package"})}),e.jsxs(as,{children:[ps.map($t=>e.jsx(He,{value:$t.id,children:$t.name},$t.id)),e.jsx(He,{value:"none",children:"No package (full access)"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:js==="none"?"Agent gets unrestricted access; welcome email has no package block.":((Xh=ps.find($t=>$t.id===js))==null?void 0:Xh.description)||"Entitlements and the welcome email reflect this package."})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>or(!1),children:"Cancel"}),e.jsx(B,{onClick:Xf,disabled:pt,children:pt?"Creating...":"Create Agent"})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(J,{className:"text-sm text-muted-foreground whitespace-nowrap",children:"Add existing user:"}),e.jsxs(od,{open:sa,onOpenChange:Rr,children:[e.jsx(ld,{asChild:!0,children:e.jsxs(B,{variant:"outline",role:"combobox","aria-expanded":sa,className:"w-[300px] justify-between",children:["Select a user to add...",e.jsx(Lr,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Qc,{className:"w-[300px] p-0",align:"start",children:e.jsxs(Aj,{children:[e.jsx(Ej,{placeholder:"Search users...",value:ra,onValueChange:Si}),e.jsxs(Tj,{children:[e.jsx(Mj,{children:"No users found."}),e.jsx(V_,{children:Gg(ks.id).filter($t=>ra===""||$t.name.toLowerCase().includes(ra.toLowerCase())||$t.email.toLowerCase().includes(ra.toLowerCase())).map($t=>e.jsxs(d1,{value:`${$t.name} ${$t.email}`,onSelect:()=>{Rv($t.id,ks.id),Rr(!1),Si("")},children:[$t.name," (",$t.email,")"]},$t.id))})]})]})})]})]}),e.jsx("div",{className:"flex-1 overflow-auto border rounded-lg",children:e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Pt,{className:"font-semibold",children:"Name"}),e.jsx(Pt,{className:"font-semibold",children:"Email"}),e.jsx(Pt,{className:"font-semibold",children:"Status"}),e.jsx(Pt,{className:"font-semibold",children:"Role"}),e.jsx(Pt,{className:"w-[120px]"})]})}),e.jsx(Ka,{children:gm(ks.id).length===0?e.jsx(pn,{children:e.jsx(gt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:Ws?"No matching members found":"No members in this brokerage"})}):gm(ks.id).map($t=>e.jsxs(pn,{className:"hover:bg-muted/30",children:[e.jsx(gt,{className:"font-medium",children:$t.name}),e.jsx(gt,{className:"text-muted-foreground",children:$t.email}),e.jsx(gt,{children:$t.claimed?e.jsx(Oe,{variant:"default",className:"bg-green-500/10 text-green-600 hover:bg-green-500/20",children:"Active"}):e.jsx(Oe,{variant:"secondary",children:"Pending"})}),e.jsx(gt,{children:$t.roles.includes("brokerage_manager")?e.jsxs(Oe,{variant:"outline",className:"gap-1",children:[e.jsx(Rm,{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:[!$t.claimed&&e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>Ma($t.id),title:"Resend welcome email",children:e.jsx(ln,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>xg($t.id),title:"Remove from brokerage",children:e.jsx(Qn,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8 text-blue-600 hover:text-blue-700 hover:bg-blue-50",onClick:()=>tc($t.id),disabled:a||$t.id===(t==null?void 0:t.id),title:$t.id===(t==null?void 0:t.id)?"Cannot impersonate yourself":`Login as ${$t.name}`,children:a?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(QM,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:()=>Co($t.id,$t.name),title:"Delete user",children:e.jsx(Sn,{className:"h-4 w-4"})})]})})]},$t.id))})]})}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[Ti(ks.id).length," total member",Ti(ks.id).length!==1?"s":""," •",Ti(ks.id).filter($t=>$t.roles.includes("brokerage_manager")).length," manager",Ti(ks.id).filter($t=>$t.roles.includes("brokerage_manager")).length!==1?"s":""]})]}),e.jsx(yr,{children:e.jsx(B,{variant:"outline",onClick:op,children:"Close"})})]})})]}),e.jsx(Gt,{value:"teams",children:e.jsx(Uin,{})}),e.jsx(Gt,{value:"trials",children:e.jsx(Sin,{})}),e.jsx(Gt,{value:"celebrations",children:e.jsx(kin,{})}),e.jsx(Gt,{value:"deletions",children:e.jsx(Ain,{})})]})]}),e.jsx(wVt,{open:Qs,onOpenChange:an,brokerages:u,onSuccess:xs}),rr&&e.jsx(jVt,{open:Ro,onOpenChange:$t=>{di($t),$t||oi(null)},userId:rr.id,userName:rr.name}),e.jsx(qin,{open:Pe,onOpenChange:ze,recipients:l.filter($t=>Gi.has($t.id)).map($t=>({id:$t.id,name:$t.name,email:$t.email}))})]})};function Vin(){const{toast:s}=vi(),t=Bt(),[n,r]=_.useState(""),[a,i]=_.useState(new Set),[l,o]=_.useState({}),[c,d]=_.useState({}),[u,h]=_.useState(""),[m,p]=_.useState(!1),{data:f=[],isLoading:y}=at({queryKey:["unassigned-members"],queryFn:async()=>{const{data:M,error:I}=await q.from("profiles").select("id, name, email, phone, created_at, subscription_status").is("brokerage_id",null).or("subscription_status.is.null,subscription_status.eq.none").order("created_at",{ascending:!1});if(I)throw I;return M||[]}}),{data:v=[]}=at({queryKey:["brokerages-all"],queryFn:async()=>{const{data:M,error:I}=await q.from("brokerages").select("id, name").order("name");if(I)throw I;return M||[]}}),g=_.useMemo(()=>{const M=n.toLowerCase().trim();return M?f.filter(I=>(I.name||"").toLowerCase().includes(M)||(I.email||"").toLowerCase().includes(M)||(I.phone||"").toLowerCase().includes(M)):f},[f,n]),b=_.useMemo(()=>{var I;const M=new Map;for(const D of f){const O=(I=(D.email||"").split("@")[1])==null?void 0:I.toLowerCase();O&&(["gmail.com","yahoo.com","hotmail.com","outlook.com","icloud.com","aol.com","me.com","comcast.net"].includes(O)||M.set(O,(M.get(O)||0)+1))}return Array.from(M.entries()).sort((D,O)=>O[1]-D[1]).slice(0,10)},[f]),j=M=>{i(I=>{const D=new Set(I);return D.has(M)?D.delete(M):D.add(M),D})},S=()=>{a.size===g.length?i(new Set):i(new Set(g.map(M=>M.id)))},C=async(M,I)=>{if(I){d(D=>({...D,[M]:!0}));try{const{data:D,error:O}=await q.functions.invoke("assign-brokerage",{body:{userId:M,brokerageId:I}});if(O)throw O;if(D!=null&&D.error)throw new Error(D.error);s({title:"Assigned",description:"Member added to brokerage."}),t.invalidateQueries({queryKey:["unassigned-members"]}),i(V=>{const G=new Set(V);return G.delete(M),G})}catch(D){s({title:"Failed",description:D.message,variant:"destructive"})}finally{d(D=>({...D,[M]:!1}))}}},E=async()=>{if(!u||a.size===0)return;p(!0);let M=0,I=0;for(const D of a)try{const{data:O,error:V}=await q.functions.invoke("assign-brokerage",{body:{userId:D,brokerageId:u}});if(V||O!=null&&O.error)throw new Error((V==null?void 0:V.message)||O.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 O of f)(O.email||"").toLowerCase().endsWith(`@${M}`)&&(D[O.id]=I);o(D),s({title:"Suggestions applied",description:`Pre-filled brokerage for @${M}`})};return e.jsx(zs,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Wh,{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(ve,{children:[e.jsx(bt,{className:"pb-2",children:e.jsxs(St,{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(In,{className:"h-4 w-4"})," Orphan members"]})}),e.jsx(Me,{children:e.jsx("div",{className:"text-3xl font-bold",children:f.length})})]}),e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-2",children:e.jsxs(St,{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(Me,{children:e.jsx("div",{className:"text-3xl font-bold",children:a.size})})]}),e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-2",children:e.jsxs(St,{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4"})," Top email domains"]})}),e.jsx(Me,{children:e.jsx("div",{className:"text-3xl font-bold",children:b.length})})]})]}),b.length>0&&e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"Domain suggestions"})}),e.jsx(Me,{children:e.jsx("div",{className:"flex flex-wrap gap-2",children:b.map(([M,I])=>{const D=v.find(O=>O.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(Oe,{variant:"secondary",children:I}),e.jsxs(is,{onValueChange:O=>P(M,O),defaultValue:D==null?void 0:D.id,children:[e.jsx(rs,{className:"h-8 w-[220px]",children:e.jsx(ls,{placeholder:"Apply brokerage…"})}),e.jsx(as,{children:v.map(O=>e.jsx(He,{value:O.id,children:O.name},O.id))})]})]},M)})})})]}),e.jsxs(ve,{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(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{value:n,onChange:M=>r(M.target.value),placeholder:"Search name, email, phone…",className:"pl-9"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(is,{value:u,onValueChange:h,children:[e.jsx(rs,{className:"w-[240px]",children:e.jsx(ls,{placeholder:"Bulk assign to brokerage…"})}),e.jsx(as,{children:v.map(M=>e.jsx(He,{value:M.id,children:M.name},M.id))})]}),e.jsxs(B,{onClick:E,disabled:!u||a.size===0||m,children:[m&&e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),"Assign ",a.size||""]})]})]}),e.jsx(Me,{children:y?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):g.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(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{className:"w-10",children:e.jsx($a,{checked:a.size===g.length&&g.length>0,onCheckedChange:S})}),e.jsx(Pt,{children:"Name"}),e.jsx(Pt,{children:"Email"}),e.jsx(Pt,{children:"Signed up"}),e.jsx(Pt,{children:"Status"}),e.jsx(Pt,{children:"Assign to brokerage"}),e.jsx(Pt,{className:"w-24"})]})}),e.jsx(Ka,{children:g.map(M=>{const I=l[M.id]||"";return e.jsxs(pn,{children:[e.jsx(gt,{children:e.jsx($a,{checked:a.has(M.id),onCheckedChange:()=>j(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:Ed(new Date(M.created_at),{addSuffix:!0})}),e.jsx(gt,{children:e.jsx(Oe,{variant:"outline",children:M.subscription_status||"none"})}),e.jsx(gt,{children:e.jsxs(is,{value:I,onValueChange:D=>o(O=>({...O,[M.id]:D})),children:[e.jsx(rs,{className:"h-9 w-[240px]",children:e.jsx(ls,{placeholder:"Pick brokerage…"})}),e.jsx(as,{children:v.map(D=>e.jsx(He,{value:D.id,children:D.name},D.id))})]})}),e.jsx(gt,{children:e.jsx(B,{size:"sm",disabled:!I||c[M.id],onClick:()=>C(M.id,I),children:c[M.id]?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):"Assign"})})]},M.id)})})]})})})]})]})})}const Hin=()=>{const[s,t]=_.useState([]),[n,r]=_.useState(!0),[a,i]=_.useState(!1),[l,o]=_.useState(""),[c,d]=_.useState(""),[u,h]=_.useState(""),[m,p]=_.useState("");_.useEffect(()=>{f()},[]);const f=async()=>{const{data:C,error:E}=await q.from("invite_codes").select("*").order("created_at",{ascending:!1});E?(se.error("Failed to load invite codes"),console.error(E)):t(C||[]),r(!1)},y=async C=>{if(C.preventDefault(),!l.trim()){se.error("Please enter a code");return}i(!0);const{error:E}=await q.from("invite_codes").insert({code:l.trim().toUpperCase(),description:c.trim()||null,max_uses:u?parseInt(u):null,trial_days:m?parseInt(m):null});E?E.code==="23505"?se.error("This code already exists"):(se.error("Failed to create invite code"),console.error(E)):(se.success("Invite code created"),o(""),d(""),h(""),p(""),f()),i(!1)},v=async(C,E)=>{const{error:P}=await q.from("invite_codes").update({is_active:!E}).eq("id",C);P?se.error("Failed to update code"):t(s.map(M=>M.id===C?{...M,is_active:!E}:M))},g=async C=>{const{error:E}=await q.from("invite_codes").delete().eq("id",C);E?se.error("Failed to delete code"):(se.success("Code deleted"),t(s.filter(P=>P.id!==C)))},b="https://dashboard.relevelup.com",j=C=>{const E=`${b}/join?code=${C}`;navigator.clipboard.writeText(E),se.success("Link copied to clipboard")},S=`${b}/join`;return e.jsx(zs,{title:"Invite Codes",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Wh,{title:"Invite Codes",description:"Manage signup invite codes"}),e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsx(St,{children:"Create New Code"}),e.jsxs(kn,{children:["Share link: ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded text-sm",children:S})]})]}),e.jsx(Me,{children:e.jsxs("form",{onSubmit:y,className:"flex flex-wrap gap-4 items-end",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"code",children:"Code"}),e.jsx(xe,{id:"code",placeholder:"WELCOME2024",value:l,onChange:C=>o(C.target.value),className:"w-40"})]}),e.jsxs("div",{className:"space-y-2 flex-1 min-w-[200px]",children:[e.jsx(J,{htmlFor:"description",children:"Description (optional)"}),e.jsx(xe,{id:"description",placeholder:"For marketing campaign",value:c,onChange:C=>d(C.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"maxUses",children:"Max Uses"}),e.jsx(xe,{id:"maxUses",type:"number",placeholder:"Unlimited",value:u,onChange:C=>h(C.target.value),className:"w-28"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"trialDays",children:"Trial Days"}),e.jsx(xe,{id:"trialDays",type:"number",placeholder:"None",value:m,onChange:C=>p(C.target.value),className:"w-28"})]}),e.jsxs(B,{type:"submit",disabled:a,children:[a?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(rn,{className:"h-4 w-4 mr-2"}),"Create"]})]})})]}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{children:"Active Codes"})}),e.jsx(Me,{children:n?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):s.length===0?e.jsx("p",{className:"text-center py-8 text-muted-foreground",children:"No invite codes yet"}):e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"Code"}),e.jsx(Pt,{children:"Description"}),e.jsx(Pt,{children:"Uses"}),e.jsx(Pt,{children:"Trial"}),e.jsx(Pt,{children:"Created"}),e.jsx(Pt,{children:"Active"}),e.jsx(Pt,{className:"w-24",children:"Actions"})]})}),e.jsx(Ka,{children:s.map(C=>e.jsxs(pn,{children:[e.jsx(gt,{className:"font-mono font-medium",children:C.code}),e.jsx(gt,{className:"text-muted-foreground",children:C.description||"—"}),e.jsxs(gt,{children:[C.uses_count,C.max_uses&&` / ${C.max_uses}`]}),e.jsx(gt,{children:C.trial_days?e.jsxs("span",{className:"text-amber-600 dark:text-amber-400 font-medium",children:[C.trial_days," days"]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(gt,{className:"text-muted-foreground",children:Hs(new Date(C.created_at),"MMM d, yyyy")}),e.jsx(gt,{children:e.jsx(fn,{checked:C.is_active,onCheckedChange:()=>v(C.id,C.is_active)})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>j(C.code),title:"Copy invite link",children:e.jsx(Ia,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>g(C.id),className:"text-destructive hover:text-destructive",title:"Delete code",children:e.jsx(Sn,{className:"h-4 w-4"})})]})})]},C.id))})]})})]})]})})},DA=q;function x_r(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 Gin(s){return s.toLowerCase().replace(/[^a-z0-9\s-]/g,"").trim().replace(/\s+/g,"-").slice(0,70)}const Win="https://dashboard.relevelup.com";function g_r(s,t){const r=`${typeof window<"u"&&window.location.hostname==="localhost"?window.location.origin:Win}/live/${s}`;return t?`${r}?i=${t}`:r}function y_r(){const s=Bt(),t=at({queryKey:["live-events"],queryFn:async()=>{const{data:i,error:l}=await DA.from("live_events").select("*").order("starts_at",{ascending:!1});if(l)throw l;return i||[]}}),n=mt({mutationFn:async i=>{var d;const{data:l}=await q.auth.getUser(),{data:o,error:c}=await DA.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"]}),se.success("Live event created")},onError:i=>se.error((i==null?void 0:i.message)||"Could not create event")}),r=mt({mutationFn:async({id:i,...l})=>{const{error:o}=await DA.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]}),se.success("Saved")},onError:i=>se.error((i==null?void 0:i.message)||"Could not save")}),a=mt({mutationFn:async i=>{const{error:l}=await DA.from("live_events").delete().eq("id",i);if(l)throw l},onSuccess:()=>{s.invalidateQueries({queryKey:["live-events"]}),se.success("Event deleted")},onError:i=>se.error((i==null?void 0:i.message)||"Could not delete")});return{list:t,create:n,update:r,remove:a}}function v_r(s){return at({queryKey:["live-event",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await DA.from("live_events").select("*").eq("id",s).maybeSingle();if(n)throw n;return t}})}function b_r(s){return at({queryKey:["live-registrations",s],enabled:!!s,refetchInterval:2e4,queryFn:async()=>{const{data:t,error:n}=await DA.from("live_registrations").select("*").eq("event_id",s).order("created_at",{ascending:!1});if(n)throw n;return t||[]}})}function __r(s){const t=Bt(),n=at({queryKey:["live-invites",s],enabled:!!s,queryFn:async()=>{const{data:i,error:l}=await DA.from("live_invites").select("*").eq("event_id",s).order("created_at",{ascending:!1});if(l)throw l;return i||[]}}),r=mt({mutationFn:async i=>{const{data:l}=await q.auth.getUser(),o=i.map(u=>{var h;return{event_id:s,code:crypto.randomUUID().replace(/-/g,"").slice(0,12),name:u.name||null,email:u.email||null,phone:u.phone||null,brokerage:u.brokerage||null,created_by:(h=l.user)==null?void 0:h.id}}),{data:c,error:d}=await DA.from("live_invites").insert(o).select();if(d)throw d;return c||[]},onSuccess:i=>{t.invalidateQueries({queryKey:["live-invites",s]}),se.success(`${i.length} invite link${i.length===1?"":"s"} created`)},onError:i=>se.error((i==null?void 0:i.message)||"Could not create invites")}),a=mt({mutationFn:async i=>{const{error:l}=await DA.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 jae=async s=>{try{const{data:t,error:n}=await q.from("push_notification_settings").select("is_enabled").eq("setting_key",s).maybeSingle();return n?(console.error("Error checking notification setting:",n),!0):(t==null?void 0:t.is_enabled)??!0}catch(t){return console.error("Error checking notification setting:",t),!0}},kW=async s=>{try{const{data:t,error:n}=await q.functions.invoke("send-push-notification",{body:s});return n?(console.error("Error sending notification:",n),{success:!1,error:n}):(console.log("Notification sent:",t),{success:!0,data:t})}catch(t){return console.error("Error sending notification:",t),{success:!1,error:t}}},Kin=async(s,t)=>await jae("new_templates")?kW({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}),Yin=async(s,t)=>kW({title:"New Academy Video",body:`New video added: ${s}`,url:`/academy/${t}`}),Zin=async(s,t)=>await jae("new_events")?kW({title:"New Event",body:`New event: ${s}`,url:`/events/${t}`}):(console.log("New event notifications are disabled"),{success:!1,skipped:!0}),Xin=async(s,t)=>await jae("new_toolbox")?kW({title:"New Resource Kit",body:`New resource kit available: ${s}`,url:`/toolbox/${t}`}):(console.log("New toolbox notifications are disabled"),{success:!1,skipped:!0}),AHe=async(s,t)=>await jae("new_social_swag")?kW({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}),Qin=async(s,t)=>await jae("new_newsletters")?kW({title:"New Newsletter",body:`New newsletter available: ${s}`,url:`/newsletters/${t}`}):(console.log("New newsletter notifications are disabled"),{success:!1,skipped:!0}),d9e=400;function Jin(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 eon(){const s=[];let t=0;const n=1e3;for(;;){const{data:r,error:a}=await q.from("profiles").select("id, name, email, event_invite_opt_out").not("email","is",null).neq("email","").eq("event_invite_opt_out",!1).order("created_at",{ascending:!1}).range(t,t+n-1);if(a)throw a;if(!r||r.length===0)break;for(const i of r)i.email&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(i.email)&&s.push({id:i.id,name:i.name||"",email:i.email});if(r.length{if(!s||!n)return;let Y=!1;return(async()=>{h(!0);try{const[Z,ne,ce]=await Promise.all([eon(),Ovt("event_registrations",n.id),Ovt("event_attendees",n.id)]);if(Y)return;p(Z),y(ne),g(ce)}catch(Z){Y||r({title:"Could not load audience",description:Z instanceof Error?Z.message:"Unknown error",variant:"destructive"})}finally{Y||h(!1)}})(),()=>{Y=!0}},[s,n,r]),_.useEffect(()=>{s||(C(null),d(""),o(""),i("not_registered"))},[s]);const D=_.useMemo(()=>a==="all"?m:a==="not_registered"?m.filter(Y=>!f.has(Y.id)):m.filter(Y=>f.has(Y.id)&&!v.has(Y.id)),[a,m,f,v]),O={all:m.length,not_registered:m.filter(Y=>!f.has(Y.id)).length,registered_never_attended:m.filter(Y=>f.has(Y.id)&&!v.has(Y.id)).length},V=async(Y,Z=!1)=>{const{data:{session:ne}}=await q.auth.getSession(),ce=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/admin-send-event-invite",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${ne==null?void 0:ne.access_token}`},body:JSON.stringify({event_id:n.id,recipients:Y.map(te=>({email:te.email,name:te.name,user_id:te.id})),custom_subject:l.trim()||void 0,custom_intro:c.trim()||void 0,force_resend:Z||void 0})}),ie=await ce.json().catch(()=>({}));if(!ce.ok)throw new Error((ie==null?void 0:ie.error)||`HTTP ${ce.status}`);return{sent:(ie==null?void 0:ie.sent)??0,failed:(ie==null?void 0:ie.failed)??0,alreadyInvited:(ie==null?void 0:ie.already_invited)??0}},G=async()=>{var Y;if(n){I(!0);try{const{data:{session:Z}}=await q.auth.getSession(),ne=Z==null?void 0:Z.user;if(!(ne!=null&&ne.email))throw new Error("No signed-in email found");const ce=await V([{id:ne.id,name:((Y=ne.user_metadata)==null?void 0:Y.name)||"",email:ne.email}],!0);r({title:"Test sent",description:`Sent to ${ne.email} · Sent: ${ce.sent} · Failed: ${ce.failed}`})}catch(Z){r({title:"Test failed",description:Z instanceof Error?Z.message:"Unknown error",variant:"destructive"})}finally{I(!1)}}},$=async()=>{if(!(!n||D.length===0)){P(!1),j(!0),C({done:0,total:D.length,sent:0,failed:0});try{let Y=0,Z=0,ne=0;for(let ce=0;ce!b&&t(Y),children:e.jsxs(Ps,{className:"max-w-2xl max-h-[92vh] overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsxs(Ds,{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-5 w-5 text-primary"}),"Invite Members to Event"]}),e.jsx(_r,{children:n?e.jsxs("span",{className:"flex items-center gap-2 text-sm",children:[e.jsx(Qd,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium text-foreground",children:n.title}),e.jsx("span",{children:"·"}),e.jsx("span",{children:Jin(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(J,{className:"flex items-center gap-2",children:[e.jsx(In,{className:"h-4 w-4"})," Audience"]}),u?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground py-2",children:[e.jsx(Ct,{className:"h-4 w-4 animate-spin"})," Loading members..."]}):e.jsxs(k_,{value:a,onValueChange:Y=>i(Y),className:"space-y-2",children:[e.jsxs("label",{htmlFor:"aud-not-reg",className:"flex items-start gap-3 rounded-lg border p-3 cursor-pointer hover:bg-muted/40 transition",children:[e.jsx(sm,{value:"not_registered",id:"aud-not-reg",className:"mt-1"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-medium text-sm",children:"Members not yet registered"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Skip anyone already registered for this event. Best for weekly boost sends."})]}),e.jsx("span",{className:"text-sm font-semibold text-primary",children:O.not_registered.toLocaleString()})]}),e.jsxs("label",{htmlFor:"aud-all",className:"flex items-start gap-3 rounded-lg border p-3 cursor-pointer hover:bg-muted/40 transition",children:[e.jsx(sm,{value:"all",id:"aud-all",className:"mt-1"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-medium text-sm",children:"All members with an email"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Everyone in the system. Use sparingly to avoid inbox fatigue."})]}),e.jsx("span",{className:"text-sm font-semibold text-primary",children:O.all.toLocaleString()})]}),e.jsxs("label",{htmlFor:"aud-reg-noatt",className:"flex items-start gap-3 rounded-lg border p-3 cursor-pointer hover:bg-muted/40 transition",children:[e.jsx(sm,{value:"registered_never_attended",id:"aud-reg-noatt",className:"mt-1"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-medium text-sm",children:"Registered but haven't attended"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Nudge people who signed up but didn't join the Zoom."})]}),e.jsx("span",{className:"text-sm font-semibold text-primary",children:O.registered_never_attended.toLocaleString()})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{htmlFor:"ev-inv-subject",children:"Subject line (optional)"}),e.jsx(xe,{id:"ev-inv-subject",placeholder:n?`You're invited: ${n.title}`:"You're invited to...",value:l,onChange:Y=>o(Y.target.value),disabled:b}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Leave blank for the default."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{htmlFor:"ev-inv-intro",children:"Personal message (optional)"}),e.jsx(Ms,{id:"ev-inv-intro",placeholder:"e.g. Our Wednesday live training this week is on lead conversion. Grab your seat — it's a game-changer.",value:c,onChange:Y=>d(Y.target.value),rows:4,disabled:b}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Appears at the top of the email above the event details."})]}),S&&e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3 space-y-2",children:[e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"text-muted-foreground",children:["Sending ",S.done.toLocaleString()," / ",S.total.toLocaleString()]}),e.jsxs("span",{className:"font-medium",children:["✓ ",S.sent.toLocaleString(),S.failed>0&&e.jsxs("span",{className:"text-destructive",children:[" · ✗ ",S.failed.toLocaleString()]})]})]}),e.jsx(Fi,{value:H})]})]}),e.jsxs(yr,{className:"gap-2 sm:gap-2",children:[e.jsx(B,{variant:"outline",onClick:G,disabled:b||M||u,children:M?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"})," Sending test..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ln,{className:"h-4 w-4 mr-2"})," Send test to me"]})}),e.jsx(B,{variant:"ghost",onClick:()=>t(!1),disabled:b,children:"Cancel"}),e.jsx(B,{onClick:()=>P(!0),disabled:b||u||D.length===0,children:b?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"})," Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Or,{className:"h-4 w-4 mr-2"})," Send to ",D.length.toLocaleString()]})})]})]})}),e.jsx(Kl,{open:E,onOpenChange:P,children:e.jsxs(Ol,{children:[e.jsxs(zl,{children:[e.jsx(Ul,{children:"Send event invite?"}),e.jsxs(ql,{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($l,{children:"Cancel"}),e.jsxs(Ml,{onClick:$,children:[e.jsx(Or,{className:"h-4 w-4 mr-2"})," Send now"]})]})]})})]})}const xce={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 son(){const s=Fn(),t=Bt(),[n,r]=_.useState(!1),[a,i]=_.useState(null),[l,o]=_.useState(xce),[c,d]=_.useState(null),[u,h]=_.useState(null),[m,p]=_.useState(!1),f=_.useRef(null),[y,v]=_.useState(!1),[g,b]=_.useState(null),[j,S]=_.useState(!1),[C,E]=_.useState(null),[P,M]=_.useState(null),[I,D]=_.useState(!0),[O,V]=_.useState(""),[G,$]=_.useState(!1),[H,Y]=_.useState(null),{data:Z,isLoading:ne}=at({queryKey:["admin-events"],queryFn:async()=>{const{data:$e,error:Ge}=await q.from("events").select("*").order("event_date",{ascending:!0});if(Ge)throw Ge;return $e}}),{data:ce}=at({queryKey:["event-registrations-count"],queryFn:async()=>{let $e=[],Ge=0;const ct=1e3;for(;;){const{data:qt,error:Vt}=await q.from("event_registrations").select("event_id").range(Ge,Ge+ct-1);if(Vt)throw Vt;if(!qt||qt.length===0||($e=$e.concat(qt),qt.length{xt[qt.event_id]=(xt[qt.event_id]||0)+1}),xt}}),{data:ie,isLoading:te}=at({queryKey:["event-registrations-details",g==null?void 0:g.id],queryFn:async()=>{if(!g)return[];const{data:$e,error:Ge}=await q.from("event_registrations").select("id, user_id, registered_at, zoom_join_url, zoom_name, zoom_email").eq("event_id",g.id).order("registered_at",{ascending:!1});if(Ge)throw Ge;if(!$e||$e.length===0)return[];const ct=$e.map(Vt=>Vt.user_id).filter(Boolean);let xt=[];if(ct.length>0){const{data:Vt,error:Xt}=await q.from("profiles").select("id, name, email").in("id",ct);if(Xt)throw Xt;xt=Vt||[]}const qt=new Map((xt==null?void 0:xt.map(Vt=>[Vt.id,Vt]))||[]);return $e.map(Vt=>({...Vt,profiles:Vt.user_id&&qt.get(Vt.user_id)||null}))},enabled:!!g}),{data:ae,isLoading:le}=at({queryKey:["event-attendees-details",g==null?void 0:g.id],queryFn:async()=>{if(!g)return[];const{data:$e,error:Ge}=await q.from("event_attendees").select("id, user_id, zoom_email, zoom_name, join_time, leave_time, duration_minutes, manually_added, created_at").eq("event_id",g.id).order("created_at",{ascending:!1});if(Ge)throw Ge;if(!$e||$e.length===0)return[];const ct=$e.map(fs=>fs.user_id).filter(Boolean);let xt=[];if(ct.length>0){const{data:fs,error:Ft}=await q.from("profiles").select("id, name, email").in("id",ct);if(Ft)throw Ft;xt=fs||[]}const{data:qt}=await q.from("agent_points").select("user_id").eq("event_id",g.id),Vt=new Set((qt==null?void 0:qt.map(fs=>fs.user_id))||[]),Xt=new Map((xt==null?void 0:xt.map(fs=>[fs.id,fs]))||[]);return $e.map(fs=>({...fs,profiles:fs.user_id&&Xt.get(fs.user_id)||null,points_awarded:fs.user_id?Vt.has(fs.user_id):!1}))},enabled:!!g}),be=$e=>{b($e),v(!0)},me=mt({mutationFn:async $e=>{const{data:{session:Ge}}=await q.auth.getSession();if(!Ge)throw new Error("Not authenticated");const ct=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/zoom-sync-registrations",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Ge.access_token}`},body:JSON.stringify({event_id:$e})}),xt=await ct.json();if(!ct.ok){const qt=new Error(xt.error||"Failed to sync");throw qt.scopeError=!!xt.scope_error,qt.details=xt.scope_error?"In Zoom, make sure meeting:read:list_registrants:admin is not marked Optional, then Continue/Activate. If it already is required, update the saved Zoom credentials because the backend is using a different app.":void 0,qt}return xt},onSuccess:$e=>{if(t.invalidateQueries({queryKey:["event-registrations-details",g==null?void 0:g.id]}),t.invalidateQueries({queryKey:["event-registrations-count"]}),$e!=null&&$e.scope_error||($e==null?void 0:$e.success)===!1){se.error("Zoom needs one more authorization step",{description:$e!=null&&$e.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.":($e==null?void 0:$e.message)||"Zoom registration sync could not complete.",duration:2e4});return}se.success($e.message)},onError:$e=>{se.error("Failed to sync Zoom registrations",{description:$e.scopeError&&$e.details||$e.message,duration:$e.scopeError?2e4:5e3})}}),he=mt({mutationFn:async $e=>{const{data:{session:Ge}}=await q.auth.getSession();if(!Ge)throw new Error("Not authenticated");const ct=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/zoom-sync-attendees",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Ge.access_token}`},body:JSON.stringify({event_id:$e})}),xt=await ct.json();if(!ct.ok)throw new Error(xt.error||"Failed to sync attendees");return xt},onSuccess:$e=>{if(t.invalidateQueries({queryKey:["event-attendees-details",g==null?void 0:g.id]}),t.invalidateQueries({queryKey:["event-leaderboard"]}),t.invalidateQueries({queryKey:["admin-agent-points"]}),$e!=null&&$e.scope_error||($e==null?void 0:$e.success)===!1){se.error(($e==null?void 0:$e.message)||"Zoom sync failed",{description:$e!=null&&$e.scope_error?"Zoom must be re-authorized after adding the missing report scope.":void 0,duration:15e3});return}$e!=null&&$e.message?se.success($e.message):se.success(`Synced ${$e.synced||0} attendees. ${$e.points_awarded||0} points awarded!`)},onError:$e=>{se.error("Failed to sync attendees: "+$e.message)}}),pe=mt({mutationFn:async()=>{const{data:$e,error:Ge}=await q.functions.invoke("zoom-retry-registrations",{body:{}});if(Ge)throw Ge;return $e},onSuccess:$e=>{t.invalidateQueries({queryKey:["event-registrations-details",g==null?void 0:g.id]}),t.invalidateQueries({queryKey:["event-registrations-count"]}),se.success(`Retry complete: ${($e==null?void 0:$e.successCount)??0} fixed, ${($e==null?void 0:$e.failCount)??0} still failing, ${($e==null?void 0:$e.rateLimitedCount)??0} rate-limited`)},onError:$e=>{se.error("Retry failed: "+$e.message)}}),Ce=mt({mutationFn:async({eventId:$e,testMode:Ge})=>{const{data:{session:ct}}=await q.auth.getSession();if(!ct)throw new Error("Not authenticated");const xt=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/send-event-reminder",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${ct.access_token}`},body:JSON.stringify({event_id:$e,test_mode:Ge})}),qt=await xt.json();if(!xt.ok)throw new Error(qt.error||"Failed to send reminders");return qt},onSuccess:$e=>{$e.test?se.success($e.message||"Test email sent!"):se.success($e.message||`Reminder emails sent to ${$e.sent} registrants!`)},onError:$e=>{se.error("Failed to send reminders: "+$e.message)}}),{data:Ae}=at({queryKey:["all-profiles-for-linking"],queryFn:async()=>{let $e=[],Ge=0;const ct=1e3;for(;;){const{data:xt,error:qt}=await q.from("profiles").select("id, name, email").order("name",{ascending:!0}).range(Ge,Ge+ct-1);if(qt)throw qt;if(!xt||xt.length===0||($e=[...$e,...xt],xt.length{const{error:qt}=await q.from("event_attendees").update({user_id:Ge}).eq("id",$e);if(qt)throw qt;if(xt&&ct){const{error:Xt}=await q.from("zoom_email_aliases").upsert({user_id:Ge,zoom_email:ct.toLowerCase()},{onConflict:"zoom_email"});Xt&&console.error("Failed to save alias:",Xt)}const Vt=g==null?void 0:g.id;if(Vt){const{data:Xt}=await q.from("user_roles").select("id").eq("user_id",Ge).eq("role","admin").single();if(!Xt){const{data:fs}=await q.from("agent_points").select("id").eq("user_id",Ge).eq("event_id",Vt).single();fs||(await q.rpc("award_attendance_points",{p_user_id:Ge,p_event_id:Vt,p_points:10,p_reason:"Event Attendance (Manual Link)"}),await q.rpc("check_and_award_badges",{p_user_id:Ge}))}}return{userId:Ge,zoomEmail:ct,shouldSaveAlias:xt}},onSuccess:$e=>{t.invalidateQueries({queryKey:["event-attendees-details",g==null?void 0:g.id]}),t.invalidateQueries({queryKey:["event-leaderboard"]}),t.invalidateQueries({queryKey:["admin-agent-points"]});let Ge="Attendee linked and points awarded!";$e.shouldSaveAlias&&$e.zoomEmail&&(Ge+=` Email "${$e.zoomEmail}" will be auto-matched in the future.`),se.success(Ge),S(!1),E(null),M(null),V("")},onError:$e=>{se.error("Failed to link attendee: "+$e.message)}}),ze=$e=>{E($e),M(null),D(!0),V(""),S(!0)},ke=()=>{!C||!P||Pe.mutate({attendeeId:C.id,userId:P,zoomEmail:C.zoom_email,shouldSaveAlias:I})},Ze=(Ae==null?void 0:Ae.filter($e=>{var ct,xt;if(!O)return!0;const Ge=O.toLowerCase();return((ct=$e.name)==null?void 0:ct.toLowerCase().includes(Ge))||((xt=$e.email)==null?void 0:xt.toLowerCase().includes(Ge))}))||[],Se=async $e=>{const Ge=$e.name.split(".").pop(),xt=`${`${crypto.randomUUID()}.${Ge}`}`,{error:qt}=await q.storage.from("event-images").upload(xt,$e);if(qt)throw qt;const{data:{publicUrl:Vt}}=q.storage.from("event-images").getPublicUrl(xt);return Vt},Fe=$e=>{var ct;const Ge=(ct=$e.target.files)==null?void 0:ct[0];if(Ge){if(Ge.size>5*1024*1024){se.error("Image must be less than 5MB");return}d(Ge),h(URL.createObjectURL(Ge))}},Ne=()=>{d(null),h(null),o({...l,image_url:""}),f.current&&(f.current.value="")},Ye=mt({mutationFn:async $e=>{p(!0);let Ge=$e.image_url;c&&(Ge=await Se(c)||"");const ct=new Date($e.event_date),[xt,qt]=$e.event_time.split(":");ct.setHours(parseInt(xt),parseInt(qt));const Vt=[new Date(ct)];if($e.is_recurring&&$e.recurrence_end_date){let wt=new Date(ct);for(;$e.recurrence_pattern==="weekly"?wt=uF(wt,1):$e.recurrence_pattern==="biweekly"?wt=uF(wt,2):wt=Cy(wt,1),!(wt>$e.recurrence_end_date);)Vt.push(new Date(wt))}const Xt=Vt.map(wt=>({title:$e.title,description:$e.description||null,image_url:Ge||null,video_url:$e.video_url||null,event_date:wt.toISOString(),zoom_link:$e.zoom_link,zoom_meeting_id:$e.zoom_meeting_id||null,capacity:$e.capacity?parseInt($e.capacity):null,is_published:$e.is_published})),{data:fs,error:Ft}=await q.from("events").insert(Xt).select();if(Ft)throw Ft;return fs&&fs.length>0&&Zin($e.title,fs[0].id),Vt.length},onSuccess:$e=>{t.invalidateQueries({queryKey:["admin-events"]}),se.success($e>1?`${$e} recurring events created successfully`:"Event created successfully"),r(!1),o(xce),d(null),h(null),p(!1)},onError:$e=>{se.error("Failed to create event: "+$e.message),p(!1)}}),Ve=mt({mutationFn:async({id:$e,data:Ge})=>{p(!0);let ct=Ge.image_url;c&&(ct=await Se(c)||"");const xt=new Date(Ge.event_date),[qt,Vt]=Ge.event_time.split(":");xt.setHours(parseInt(qt),parseInt(Vt));const{error:Xt}=await q.from("events").update({title:Ge.title,description:Ge.description||null,image_url:ct||null,video_url:Ge.video_url||null,event_date:xt.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}).eq("id",$e);if(Xt)throw Xt},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-events"]}),se.success("Event updated successfully"),r(!1),i(null),o(xce),d(null),h(null),p(!1)},onError:$e=>{se.error("Failed to update event: "+$e.message),p(!1)}}),qe=mt({mutationFn:async $e=>{const{error:Ge}=await q.from("events").delete().eq("id",$e);if(Ge)throw Ge},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-events"]}),se.success("Event deleted successfully")},onError:$e=>{se.error("Failed to delete event: "+$e.message)}}),Qe=mt({mutationFn:async $e=>{var wt;const{data:Ge}=await q.auth.getUser(),ct=new Date($e.event_date),xt=new Date(ct.getTime()+60*60*1e3),qt=Gin($e.title),Vt=Math.random().toString(36).slice(2,7),Xt=`${qt}-${Vt}`,{data:fs,error:Ft}=await q.from("live_events").insert({slug:Xt,title:$e.title,description:$e.description||null,hero_image_url:$e.image_url||null,starts_at:$e.event_date,ends_at:xt.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:$e.zoom_meeting_id||null,cta_label:"Join the training",cta_url:$e.zoom_link||"https://dashboard.relevelup.com/trial",created_by:(wt=Ge.user)==null?void 0:wt.id,agenda:[],offer_bullets:[]}).select().single();if(Ft)throw Ft;return fs},onSuccess:$e=>{t.invalidateQueries({queryKey:["live-events"]}),se.success("Cloned to LevelUp Live — configure stream next"),s(`/admin/live/${$e.id}`)},onError:$e=>{se.error("Failed to clone to LevelUp Live: "+$e.message)}}),Ue=$e=>{var ct;const Ge=new Date($e.event_date);i($e),o({title:$e.title,description:$e.description||"",image_url:$e.image_url||"",video_url:$e.video_url||"",event_date:Ge,event_time:Hs(Ge,"HH:mm"),zoom_link:$e.zoom_link,zoom_meeting_id:$e.zoom_meeting_id||"",capacity:((ct=$e.capacity)==null?void 0:ct.toString())||"",is_published:$e.is_published,is_recurring:!1,recurrence_pattern:"weekly",recurrence_end_date:void 0}),h($e.image_url||null),d(null),r(!0)},Xe=$e=>{if($e.preventDefault(),!l.event_date){se.error("Please select a date");return}if(l.is_recurring&&!l.recurrence_end_date){se.error("Please select an end date for recurring events");return}a?Ve.mutate({id:a.id,data:l}):Ye.mutate(l)},nt=()=>{r(!1),i(null),o(xce),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(Wh,{title:"Event Management",description:"Create and manage upcoming events"}),e.jsxs(ve,{className:"mb-6",children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between",children:[e.jsx(St,{children:"All Events"}),e.jsxs(Ls,{open:n,onOpenChange:$e=>!$e&&nt(),children:[e.jsx(nl,{asChild:!0,children:e.jsxs(B,{onClick:()=>r(!0),children:[e.jsx(rn,{className:"h-4 w-4 mr-2"}),"Add Event"]})}),e.jsxs(Ps,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Ds,{children:a?"Edit Event":"Create New Event"})}),e.jsxs("form",{onSubmit:Xe,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"title",children:"Title *"}),e.jsx(xe,{id:"title",value:l.title,onChange:$e=>o({...l,title:$e.target.value}),placeholder:"Event title",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Description"}),e.jsx(BN,{content:l.description,onChange:$e=>o({...l,description:$e}),placeholder:"Event description",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Event Image"}),e.jsx("input",{type:"file",ref:f,accept:"image/*",onChange:Fe,className:"hidden"}),u?e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:u,alt:"Event preview",className:"w-full h-32 object-cover rounded-lg border"}),e.jsx(B,{type:"button",variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-6 w-6",onClick:Ne,children:e.jsx(Qn,{className:"h-4 w-4"})})]}):e.jsxs(B,{type:"button",variant:"outline",className:"w-full h-32 border-dashed flex flex-col gap-2",onClick:()=>{var $e;return($e=f.current)==null?void 0:$e.click()},children:[e.jsx(Oa,{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(J,{children:"Date *"}),e.jsxs(od,{children:[e.jsx(ld,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:At("w-full justify-start text-left font-normal",!l.event_date&&"text-muted-foreground"),children:[e.jsx(ga,{className:"mr-2 h-4 w-4"}),l.event_date?Hs(l.event_date,"PPP"):"Pick a date"]})}),e.jsx(Qc,{className:"w-auto p-0",align:"start",children:e.jsx(Pj,{mode:"single",selected:l.event_date,onSelect:$e=>o({...l,event_date:$e}),initialFocus:!0,className:"p-3 pointer-events-auto"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"time",children:"Time *"}),e.jsx(xe,{id:"time",type:"time",value:l.event_time,onChange:$e=>o({...l,event_time:$e.target.value}),required:!0})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"zoom_link",children:"Zoom Link *"}),e.jsx(xe,{id:"zoom_link",value:l.zoom_link,onChange:$e=>o({...l,zoom_link:$e.target.value}),placeholder:"https://zoom.us/j/...",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"zoom_meeting_id",children:"Zoom Meeting ID (for API registration)"}),e.jsx(xe,{id:"zoom_meeting_id",value:l.zoom_meeting_id,onChange:$e=>o({...l,zoom_meeting_id:$e.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(J,{htmlFor:"video_url",children:"Promo Video URL (optional)"}),e.jsx(xe,{id:"video_url",value:l.video_url,onChange:$e=>o({...l,video_url:$e.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(J,{htmlFor:"capacity",children:"Capacity (optional)"}),e.jsx(xe,{id:"capacity",type:"number",value:l.capacity,onChange:$e=>o({...l,capacity:$e.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(QA,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(J,{htmlFor:"is_recurring",children:"Recurring Event"})]}),e.jsx(fn,{id:"is_recurring",checked:l.is_recurring,onCheckedChange:$e=>o({...l,is_recurring:$e})})]}),l.is_recurring&&e.jsxs("div",{className:"space-y-3 pt-1",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Frequency"}),e.jsxs(is,{value:l.recurrence_pattern,onValueChange:$e=>o({...l,recurrence_pattern:$e}),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"weekly",children:"Weekly"}),e.jsx(He,{value:"biweekly",children:"Every 2 Weeks"}),e.jsx(He,{value:"monthly",children:"Monthly"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Repeat Until"}),e.jsxs(od,{children:[e.jsx(ld,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:At("w-full justify-start text-left font-normal",!l.recurrence_end_date&&"text-muted-foreground"),children:[e.jsx(ga,{className:"mr-2 h-4 w-4"}),l.recurrence_end_date?Hs(l.recurrence_end_date,"PPP"):"Pick end date"]})}),e.jsx(Qc,{className:"w-auto p-0",align:"start",children:e.jsx(Pj,{mode:"single",selected:l.recurrence_end_date,onSelect:$e=>o({...l,recurrence_end_date:$e}),disabled:$e=>$e<(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 $e=1,Ge=new Date(l.event_date);for(;Ge=l.recurrence_pattern==="weekly"?uF(Ge,1):l.recurrence_pattern==="biweekly"?uF(Ge,2):Cy(Ge,1),!(Ge>l.recurrence_end_date);)$e++;return $e})()," events with the same Zoom link"]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(J,{htmlFor:"is_published",children:"Published"}),e.jsx(fn,{id:"is_published",checked:l.is_published,onCheckedChange:$e=>o({...l,is_published:$e})})]}),e.jsxs("div",{className:"flex gap-2 pt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:nt,className:"flex-1",children:"Cancel"}),e.jsx(B,{type:"submit",className:"flex-1",disabled:Ye.isPending||Ve.isPending||m,children:m?"Uploading...":a?"Update Event":l.is_recurring&&l.event_date&&l.recurrence_end_date?"Create Recurring Events":"Create Event"})]})]})]})]})]}),e.jsx(Me,{children:ne?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading events..."}):(Z==null?void 0:Z.length)===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No events yet. Create your first event!"}):(()=>{const $e=new Date,Ge=[...Z||[]],ct=Ge.filter(fs=>new Date(fs.event_date)>=$e).sort((fs,Ft)=>new Date(fs.event_date).getTime()-new Date(Ft.event_date).getTime()),xt=Ge.filter(fs=>new Date(fs.event_date)<$e).sort((fs,Ft)=>new Date(Ft.event_date).getTime()-new Date(fs.event_date).getTime()),qt=ct[0],Vt=fs=>e.jsxs(pn,{children:[e.jsx(gt,{className:"font-medium",children:fs.title}),e.jsx(gt,{className:"whitespace-nowrap",children:Hs(new Date(fs.event_date),"PPP p")}),e.jsx(gt,{children:e.jsxs(B,{variant:"ghost",size:"sm",className:"gap-1",onClick:()=>be(fs),children:[e.jsx(In,{className:"h-4 w-4"}),(ce==null?void 0:ce[fs.id])||0,fs.capacity&&` / ${fs.capacity}`]})}),e.jsx(gt,{children:e.jsx("span",{className:At("px-2 py-1 rounded-full text-xs font-medium",fs.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:fs.is_published?"Published":"Draft"})}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",className:"gap-1.5",onClick:()=>{Y(fs),$(!0)},title:"Send invite email to members",children:[e.jsx(Or,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:"Invite Members"})]}),e.jsxs(B,{variant:"outline",size:"sm",className:"gap-1.5 border-primary/50 text-primary hover:bg-primary/10",onClick:()=>Qe.mutate(fs),disabled:Qe.isPending,title:"Clone to LevelUp Live",children:[e.jsx(Nv,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:"LevelUp Live"})]}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>window.open(fs.zoom_link,"_blank"),title:"Open Zoom Link",children:e.jsx(wr,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>Ue(fs),children:e.jsx(Ya,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:async()=>{await Xi("Are you sure you want to delete this event?")&&qe.mutate(fs.id)},children:e.jsx(Sn,{className:"h-4 w-4 text-destructive"})})]})})]},fs.id),Xt=(fs,Ft)=>fs.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:Ft}):e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"Title"}),e.jsx(Pt,{children:"Date & Time"}),e.jsx(Pt,{children:"Registrations"}),e.jsx(Pt,{children:"Status"}),e.jsx(Pt,{className:"text-right",children:"Actions"})]})}),e.jsx(Ka,{children:fs.map(Vt)})]});return e.jsxs("div",{className:"space-y-6",children:[qt&&e.jsx("div",{className:"rounded-xl border bg-gradient-to-br from-primary/10 via-primary/5 to-transparent p-5",children:e.jsxs("div",{className:"flex items-start justify-between gap-4 flex-wrap",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-primary mb-1",children:[e.jsx(Gr,{className:"h-3.5 w-3.5"}),"Next Upcoming Event"]}),e.jsx("h3",{className:"text-xl font-bold truncate",children:qt.title}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:Hs(new Date(qt.event_date),"EEEE, PPP 'at' p")}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[(ce==null?void 0:ce[qt.id])||0," registered",qt.capacity?` of ${qt.capacity}`:""]})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs(B,{size:"sm",className:"gap-1.5",onClick:()=>{Y(qt),$(!0)},children:[e.jsx(Or,{className:"h-4 w-4"}),"Invite Members"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"gap-1.5",onClick:()=>be(qt),children:[e.jsx(In,{className:"h-4 w-4"}),"Registrations"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"gap-1.5 border-primary/50 text-primary hover:bg-primary/10",onClick:()=>Qe.mutate(qt),disabled:Qe.isPending,children:[e.jsx(Nv,{className:"h-4 w-4"}),"LevelUp Live"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"gap-1.5",onClick:()=>window.open(qt.zoom_link,"_blank"),children:[e.jsx(wr,{className:"h-4 w-4"}),"Zoom"]})]})]})}),e.jsxs(Yr,{defaultValue:"upcoming",className:"w-full",children:[e.jsxs(Zr,{children:[e.jsxs(Ht,{value:"upcoming",className:"gap-2",children:[e.jsx(Gr,{className:"h-4 w-4"}),"Upcoming",e.jsx("span",{className:"ml-1 rounded-full bg-muted px-2 py-0.5 text-xs",children:ct.length})]}),e.jsxs(Ht,{value:"past",className:"gap-2",children:[e.jsx(Er,{className:"h-4 w-4"}),"Past",e.jsx("span",{className:"ml-1 rounded-full bg-muted px-2 py-0.5 text-xs",children:xt.length})]})]}),e.jsx(Gt,{value:"upcoming",className:"mt-4",children:Xt(ct,"No upcoming events scheduled.")}),e.jsx(Gt,{value:"past",className:"mt-4",children:Xt(xt,"No past events.")})]})]})})()})]}),e.jsx(ton,{open:G,onOpenChange:$,event:H}),e.jsx(Ls,{open:y,onOpenChange:v,children:e.jsxs(Ps,{className:"max-w-3xl max-h-[80vh] overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsxs(Ds,{className:"flex items-center gap-2",children:[e.jsx(In,{className:"h-5 w-5"}),g==null?void 0:g.title]}),e.jsx(_r,{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(B,{variant:"ghost",size:"sm",onClick:()=>Ce.mutate({eventId:g.id,testMode:!0}),disabled:Ce.isPending,children:[e.jsx(ln,{className:At("h-4 w-4 mr-2",Ce.isPending&&"animate-spin")}),"Send Test to Me"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>Ce.mutate({eventId:g.id}),disabled:Ce.isPending||!(ie!=null&&ie.length),children:[e.jsx(ln,{className:At("h-4 w-4 mr-2",Ce.isPending&&"animate-spin")}),Ce.isPending?"Sending...":"Send Reminder to All"]}),(g==null?void 0:g.zoom_meeting_id)&&e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>me.mutate(g.id),disabled:me.isPending,children:[e.jsx(uo,{className:At("h-4 w-4 mr-2",me.isPending&&"animate-spin")}),me.isPending?"Syncing...":"Sync Registrations"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>pe.mutate(),disabled:pe.isPending,children:[e.jsx(uo,{className:At("h-4 w-4 mr-2",pe.isPending&&"animate-spin")}),pe.isPending?"Retrying...":"Retry Failed Registrations"]}),e.jsxs(B,{variant:"default",size:"sm",onClick:()=>he.mutate(g.id),disabled:he.isPending,children:[e.jsx(wl,{className:At("h-4 w-4 mr-2",he.isPending&&"animate-spin")}),he.isPending?"Syncing...":"Sync Attendees & Award Points"]})]})]}),e.jsxs(Yr,{defaultValue:"registrations",className:"w-full",children:[e.jsxs(Zr,{className:"grid w-full grid-cols-2",children:[e.jsxs(Ht,{value:"registrations",className:"gap-2",children:[e.jsx(In,{className:"h-4 w-4"}),"Registrations (",(ie==null?void 0:ie.length)||0,")"]}),e.jsxs(Ht,{value:"attendees",className:"gap-2",children:[e.jsx(Er,{className:"h-4 w-4"}),"Attendees (",(ae==null?void 0:ae.length)||0,")"]})]}),e.jsx(Gt,{value:"registrations",className:"mt-4",children:te?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading registrations..."}):(ie==null?void 0:ie.length)===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx("p",{children:"No registrations yet for this event."}),(g==null?void 0:g.zoom_meeting_id)&&e.jsx("p",{className:"text-xs mt-2",children:'Click "Sync Registrations" to import from Zoom.'})]}):e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"Name"}),e.jsx(Pt,{children:"Email"}),e.jsx(Pt,{children:"Registered"}),e.jsx(Pt,{children:"Status"})]})}),e.jsx(Ka,{children:ie==null?void 0:ie.map($e=>{var qt,Vt;const Ge=((qt=$e.profiles)==null?void 0:qt.name)||$e.zoom_name||"Unknown",ct=((Vt=$e.profiles)==null?void 0:Vt.email)||$e.zoom_email||null,xt=!$e.user_id;return e.jsxs(pn,{children:[e.jsx(gt,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[Ge,xt&&e.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-muted text-muted-foreground",children:"External"})]})}),e.jsx(gt,{children:ct?e.jsxs("a",{href:`mailto:${ct}`,className:"flex items-center gap-1 text-primary hover:underline",children:[e.jsx(ln,{className:"h-3 w-3"}),ct]}):e.jsx("span",{className:"text-muted-foreground",children:"No email"})}),e.jsx(gt,{className:"text-muted-foreground text-sm",children:Hs(new Date($e.registered_at),"MMM d, yyyy h:mm a")}),e.jsx(gt,{children:$e.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"})})]},$e.id)})})]})}),e.jsx(Gt,{value:"attendees",className:"mt-4",children:le?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading attendees..."}):(ae==null?void 0:ae.length)===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx("p",{children:"No attendees recorded yet."}),(g==null?void 0:g.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:[(ae==null?void 0:ae.filter($e=>!$e.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 (",ae==null?void 0:ae.filter($e=>!$e.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:ae==null?void 0:ae.filter($e=>!$e.user_id).map($e=>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:$e.zoom_name||"Unknown"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:$e.zoom_email||"No email"})]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>ze($e),className:"gap-1",children:[e.jsx(vd,{className:"h-3 w-3"}),"Link to Profile"]})]},$e.id))})]}),e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"Name"}),e.jsx(Pt,{children:"Email"}),e.jsx(Pt,{children:"Duration"}),e.jsx(Pt,{children:"Points"})]})}),e.jsx(Ka,{children:ae==null?void 0:ae.filter($e=>$e.user_id).map($e=>{var xt,qt;const Ge=((xt=$e.profiles)==null?void 0:xt.name)||$e.zoom_name||"Unknown",ct=((qt=$e.profiles)==null?void 0:qt.email)||$e.zoom_email||null;return e.jsxs(pn,{children:[e.jsx(gt,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[Ge,$e.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:ct?e.jsxs("a",{href:`mailto:${ct}`,className:"flex items-center gap-1 text-primary hover:underline",children:[e.jsx(ln,{className:"h-3 w-3"}),ct]}):e.jsx("span",{className:"text-muted-foreground",children:"No email"})}),e.jsx(gt,{children:$e.duration_minutes?e.jsxs("span",{className:"flex items-center gap-1 text-muted-foreground text-sm",children:[e.jsx(Gr,{className:"h-3 w-3"}),$e.duration_minutes," min"]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(gt,{children:$e.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(wl,{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"})})]},$e.id)})})]})]})})]})]})}),e.jsx(Ls,{open:j,onOpenChange:S,children:e.jsxs(Ps,{className:"max-w-md",children:[e.jsxs(Os,{children:[e.jsxs(Ds,{className:"flex items-center gap-2",children:[e.jsx(vd,{className:"h-5 w-5"}),"Link Attendee to Profile"]}),e.jsx(_r,{children:"Link this Zoom attendee to an existing member profile to award them points."})]}),C&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"p-3 bg-muted rounded-lg",children:[e.jsx("p",{className:"text-sm font-medium",children:C.zoom_name||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:C.zoom_email||"No email"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Search for a profile"}),e.jsxs("div",{className:"relative",children:[e.jsx(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search by name or email...",value:O,onChange:$e=>V($e.target.value),className:"pl-9"})]})]}),e.jsx("div",{className:"max-h-48 overflow-y-auto border rounded-md",children:Ze.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:Ze.slice(0,20).map($e=>e.jsxs("button",{type:"button",onClick:()=>M($e.id),className:At("w-full p-3 text-left hover:bg-muted/50 transition-colors",P===$e.id&&"bg-primary/10 border-l-2 border-primary"),children:[e.jsx("p",{className:"text-sm font-medium",children:$e.name||"Unnamed"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:$e.email})]},$e.id))})}),C.zoom_email&&e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx($a,{id:"save-alias",checked:I,onCheckedChange:$e=>D($e)}),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(B,{variant:"outline",onClick:()=>S(!1),children:"Cancel"}),e.jsx(B,{onClick:ke,disabled:!P||Pe.isPending,children:Pe.isPending?"Linking...":"Link & Award Points"})]})]})]})})]})})}const non={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 ron(){const[s,t]=_.useState([]),[n,r]=_.useState(!0),[a,i]=_.useState("issues");async function l(){r(!0);let o=q.from("mcp_audit_log").select("id, user_id, tool_name, outcome, error_message, duration_ms, client_id, created_at").order("created_at",{ascending:!1}).limit(200);a==="issues"&&(o=o.in("outcome",["denied","rate_limited","error"]));const{data:c,error:d}=await o;d||t(c??[]),r(!1)}return _.useEffect(()=>{l()},[a]),e.jsx(zs,{title:"MCP Audit Log",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Wh,{title:"MCP Audit Log",description:"Recent LevelUp MCP tool calls — ChatGPT / Claude / Codex activity, denials, and rate limits."}),e.jsxs(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between",children:[e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(s$,{className:"h-5 w-5"}),"Recent activity"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:a==="issues"?"default":"outline",size:"sm",onClick:()=>i("issues"),children:"Issues only"}),e.jsx(B,{variant:a==="all"?"default":"outline",size:"sm",onClick:()=>i("all"),children:"All calls"}),e.jsx(B,{variant:"ghost",size:"sm",onClick:l,disabled:n,children:e.jsx(uo,{className:`h-4 w-4 ${n?"animate-spin":""}`})})]})]}),e.jsx(Me,{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(Oe,{className:non[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 aon({selectedKitIds:s,onChange:t}){const[n,r]=_.useState(""),[a,i]=_.useState(!1),{data:l=[]}=at({queryKey:["all-resource-kits-picker"],queryFn:async()=>{const{data:h,error:m}=await q.from("resource_kits").select("id, name, featured_image_url").eq("is_published",!0).order("name");if(m)throw m;return h}}),o=l.filter(h=>s.includes(h.id)),c=l.filter(h=>!s.includes(h.id)&&h.name.toLowerCase().includes(n.toLowerCase())),d=h=>{t([...s,h])},u=h=>{t(s.filter(m=>m!==h))};return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(J,{className:"flex items-center gap-2",children:[e.jsx(Nh,{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(Oe,{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(Qn,{className:"h-3 w-3"})})]},h.id))}),e.jsxs(od,{open:a,onOpenChange:i,children:[e.jsx(ld,{asChild:!0,children:e.jsxs(B,{type:"button",variant:"outline",size:"sm",className:"gap-1",children:[e.jsx(Nh,{className:"h-3.5 w-3.5"}),"Add Toolkit"]})}),e.jsxs(Qc,{className:"w-80 p-2",align:"start",children:[e.jsxs("div",{className:"relative mb-2",children:[e.jsx(Lr,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search toolkits...",value:n,onChange:h=>r(h.target.value),className:"pl-7 h-8 text-sm"})]}),e.jsx("div",{className:"max-h-48 overflow-y-auto space-y-0.5",children:c.length===0?e.jsx("p",{className:"text-xs text-muted-foreground text-center py-3",children:n?"No toolkits found":"All toolkits selected"}):c.map(h=>e.jsxs("button",{type:"button",onClick:()=>{d(h.id),r("")},className:"w-full flex items-center gap-2 px-2 py-1.5 rounded-md hover:bg-muted text-left text-sm transition-colors",children:[h.featured_image_url?e.jsx("img",{src:h.featured_image_url,alt:"",className:"w-8 h-8 rounded object-cover flex-shrink-0"}):e.jsx("div",{className:"w-8 h-8 rounded bg-muted flex items-center justify-center flex-shrink-0",children:e.jsx(Nh,{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 ion=()=>{const{user:s}=hs(),{toast:t}=vi(),n=Bt(),[r,a]=Yl(),[i,l]=_.useState(!1),[o,c]=_.useState(null),[d,u]=_.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]=_.useState(null),[p,f]=_.useState(0),[y,v]=_.useState(!1),[g,b]=_.useState(null),[j,S]=_.useState(""),[C,E]=_.useState([]),[P,M]=_.useState(""),[I,D]=_.useState(""),[O,V]=_.useState(!1),[G,$]=_.useState(!1),{data:H=[]}=at({queryKey:["template-categories"],queryFn:async()=>{const{data:Ne,error:Ye}=await q.from("template_categories").select("*").order("name");if(Ye)throw Ye;return Ne}}),{data:Y=[]}=at({queryKey:["template-types"],queryFn:async()=>{const{data:Ne,error:Ye}=await q.from("template_types").select("*").order("name");if(Ye)throw Ye;return Ne}}),{data:Z=[],isLoading:ne}=at({queryKey:["canva-templates-admin"],queryFn:async()=>{const{data:Ne,error:Ye}=await q.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).order("publish_date",{ascending:!1});if(Ye)throw Ye;const{data:Ve,error:qe}=await q.from("template_links").select("*").order("sort_order");if(qe)throw qe;const{data:Qe,error:Ue}=await q.from("template_guides").select("*").order("sort_order");if(Ue)throw Ue;return Ne.map(nt=>({...nt,links:(Ve==null?void 0:Ve.filter($e=>$e.template_id===nt.id))||[],guides:(Qe==null?void 0:Qe.filter($e=>$e.template_id===nt.id))||[]}))}});_.useEffect(()=>{const Ne=r.get("edit");if(Ne&&Z.length>0){const Ye=Z.find(Ve=>Ve.id===Ne);Ye&&(me(Ye),a({},{replace:!0}))}},[Z,r]);const ce=mt({mutationFn:async Ne=>{const{data:Ye,error:Ve}=await q.from("template_categories").insert({name:Ne}).select().single();if(Ve)throw Ve;return Ye},onSuccess:Ne=>{n.invalidateQueries({queryKey:["template-categories"]}),u({...d,category_id:Ne.id}),M(""),V(!1),t({title:"Category added"})},onError:Ne=>{t({title:"Error adding category",description:Ne.message,variant:"destructive"})}}),ie=mt({mutationFn:async Ne=>{const{data:Ye,error:Ve}=await q.from("template_types").insert({name:Ne}).select().single();if(Ve)throw Ve;return Ye},onSuccess:Ne=>{n.invalidateQueries({queryKey:["template-types"]}),u({...d,type_id:Ne.id}),D(""),$(!1),t({title:"Type added"})},onError:Ne=>{t({title:"Error adding type",description:Ne.message,variant:"destructive"})}}),te=mt({mutationFn:async Ne=>{var Ue;let Ye=Ne.existingImageUrl;if(Ne.image){const Xe=Ne.image.name.split(".").pop(),nt=`${Date.now()}-${Math.random().toString(36).substring(7)}.${Xe}`,{error:$e}=await q.storage.from("template-previews").upload(nt,Ne.image);if($e)throw $e;const{data:Ge}=q.storage.from("template-previews").getPublicUrl(nt);Ye=Ge.publicUrl}const Ve={name:Ne.template.name,description:Ne.template.description||null,category_id:Ne.template.category_id||null,type_id:Ne.template.type_id||null,preview_image_url:Ye,video_url:Ne.videoUrl||null,publish_date:Ne.template.publish_date?new Date(Ne.template.publish_date).toISOString():new Date().toISOString(),created_by:s==null?void 0:s.id};let qe=Ne.templateId;if(qe){const{error:Xe}=await q.from("canva_templates").update(Ve).eq("id",qe);if(Xe)throw Xe;const{error:nt}=await q.from("template_links").delete().eq("template_id",qe);if(nt)throw nt;const $e=((Ue=Ne.existingGuides)==null?void 0:Ue.map(xt=>xt.id).filter(Boolean))||[],Ge=Ne.template.guides.map(xt=>xt.id).filter(Boolean),ct=$e.filter(xt=>!Ge.includes(xt));ct.length>0&&await q.from("template_guides").delete().in("id",ct)}else{const{data:Xe,error:nt}=await q.from("canva_templates").insert(Ve).select().single();if(nt)throw nt;qe=Xe.id,Kin(Ne.template.name,Xe.id)}const Qe=Ne.template.links.filter(Xe=>Xe.title.trim()&&Xe.canva_share_link.trim());if(Qe.length>0){const Xe=Qe.map(($e,Ge)=>({template_id:qe,title:$e.title.trim(),canva_share_link:$e.canva_share_link.trim(),sort_order:Ge})),{error:nt}=await q.from("template_links").insert(Xe);if(nt)throw nt}for(let Xe=0;Xe0)){const{error:Xe}=await q.from("resource_kit_templates").insert(Ne.linkedKitIds.map(nt=>({template_id:qe,kit_id:nt})));if(Xe)throw Xe}},onSuccess:()=>{n.invalidateQueries({queryKey:["canva-templates-admin"]}),n.invalidateQueries({queryKey:["canva-templates"]}),be(),l(!1),t({title:o?"Template updated":"Template created"})},onError:Ne=>{t({title:"Error saving template",description:Ne.message,variant:"destructive"})}}),ae=mt({mutationFn:async Ne=>{const{error:Ye}=await q.from("canva_templates").delete().eq("id",Ne);if(Ye)throw Ye},onSuccess:()=>{n.invalidateQueries({queryKey:["canva-templates-admin"]}),n.invalidateQueries({queryKey:["canva-templates"]}),t({title:"Template deleted"})},onError:Ne=>{t({title:"Error deleting template",description:Ne.message,variant:"destructive"})}}),le=mt({mutationFn:async({id:Ne,is_featured:Ye})=>{const{error:Ve}=await q.from("canva_templates").update({is_featured:Ye}).eq("id",Ne);if(Ve)throw Ve},onSuccess:()=>{n.invalidateQueries({queryKey:["canva-templates-admin"]}),n.invalidateQueries({queryKey:["canva-templates"]})},onError:Ne=>{t({title:"Error updating featured",description:Ne.message,variant:"destructive"})}}),be=()=>{u({name:"",description:"",category_id:"",type_id:"",publish_date:new Date().toISOString().split("T")[0],links:[{title:"",canva_share_link:"",sort_order:0}],guides:[],video_url:""}),b(null),S(""),c(null),V(!1),$(!1),M(""),D(""),m(null),f(0),v(!1),E([])},me=async Ne=>{var Ve;c(Ne),u({name:Ne.name,description:Ne.description||"",category_id:Ne.category_id||"",type_id:Ne.type_id||"",publish_date:Ne.publish_date?new Date(Ne.publish_date).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],links:Ne.links&&Ne.links.length>0?Ne.links.map(qe=>({id:qe.id,title:qe.title,canva_share_link:qe.canva_share_link,sort_order:qe.sort_order})):[{title:"",canva_share_link:"",sort_order:0}],guides:((Ve=Ne.guides)==null?void 0:Ve.map(qe=>({id:qe.id,name:qe.name,file_url:qe.file_url,file_type:qe.file_type,file_size:qe.file_size,sort_order:qe.sort_order})))||[],video_url:Ne.video_url||""}),S(Ne.preview_image_url||""),m(null);const{data:Ye}=await q.from("resource_kit_templates").select("kit_id").eq("template_id",Ne.id);E((Ye||[]).map(qe=>qe.kit_id)),l(!0)},he=Ne=>{var Ve;const Ye=(Ve=Ne.target.files)==null?void 0:Ve[0];Ye&&(b(Ye),S(URL.createObjectURL(Ye)))},pe=()=>{u({...d,links:[...d.links,{title:"",canva_share_link:"",sort_order:d.links.length}]})},Ce=Ne=>{if(d.links.length<=1)return;const Ye=d.links.filter((Ve,qe)=>qe!==Ne);u({...d,links:Ye})},Ae=(Ne,Ye,Ve)=>{const qe=[...d.links];qe[Ne]={...qe[Ne],[Ye]:Ve},u({...d,links:qe})},Pe=Ne=>{const Ye=Ne.target.files;if(!Ye)return;const Ve=Array.from(Ye).map((qe,Qe)=>({name:qe.name.replace(/\.[^/.]+$/,""),file_url:"",file_type:qe.type,file_size:qe.size,sort_order:d.guides.length+Qe,file:qe}));u({...d,guides:[...d.guides,...Ve]}),Ne.target.value=""},ze=Ne=>{const Ye=d.guides.filter((Ve,qe)=>qe!==Ne);u({...d,guides:Ye})},ke=(Ne,Ye)=>{const Ve=[...d.guides];Ve[Ne]={...Ve[Ne],name:Ye},u({...d,guides:Ve})},Ze=async()=>{if(!h)return null;v(!0),f(0);try{const{data:Ne,error:Ye}=await q.functions.invoke("bunny-upload",{body:{action:"create",title:d.name||h.name}});if(Ye)throw new Error(Ye.message);const{videoId:Ve,libraryId:qe}=Ne,{data:Qe,error:Ue}=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:Ve}});if(Ue)throw new Error(Ue.message);const Xe=new XMLHttpRequest;return await new Promise(($e,Ge)=>{Xe.upload.addEventListener("progress",ct=>{if(ct.lengthComputable){const xt=Math.round(ct.loaded/ct.total*100);f(xt)}}),Xe.addEventListener("load",()=>{Xe.status>=200&&Xe.status<300?$e():Ge(new Error(`Upload failed with status ${Xe.status}`))}),Xe.addEventListener("error",()=>Ge(new Error("Upload failed"))),Xe.open("PUT",Qe.uploadUrl),Xe.setRequestHeader("AccessKey",Qe.apiKey),Xe.send(h)}),`https://player.mediadelivery.net/embed/${qe}/${Ve}`}catch(Ne){return console.error("Bunny upload error:",Ne),t({title:"Video upload failed",description:Ne instanceof Error?Ne.message:"Unknown error",variant:"destructive"}),null}finally{v(!1)}},Se=Ne=>{var Ve;const Ye=(Ve=Ne.target.files)==null?void 0:Ve[0];Ye&&m(Ye),Ne.target.value=""},Fe=async Ne=>{if(Ne.preventDefault(),!d.name.trim()){t({title:"Please enter a template name",variant:"destructive"});return}if(d.links.filter(qe=>qe.title.trim()&&qe.canva_share_link.trim()).length===0){t({title:"Please add at least one Canva link",variant:"destructive"});return}let Ve=d.video_url;if(h){const qe=await Ze();if(!qe)return;Ve=qe}te.mutate({template:d,image:g,existingImageUrl:(o==null?void 0:o.preview_image_url)||null,templateId:o==null?void 0:o.id,existingGuides:o==null?void 0:o.guides,videoUrl:Ve,linkedKitIds:C})};return e.jsx(zs,{title:"Manage Templates",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Wh,{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(ve,{children:[e.jsx(bt,{className:"pb-2",children:e.jsx(St,{className:"text-sm font-medium text-muted-foreground",children:"Total Templates"})}),e.jsx(Me,{children:e.jsx("div",{className:"text-2xl font-bold",children:Z.length})})]}),e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-2",children:e.jsx(St,{className:"text-sm font-medium text-muted-foreground",children:"Categories"})}),e.jsx(Me,{children:e.jsx("div",{className:"text-2xl font-bold",children:H.length})})]}),e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-2",children:e.jsx(St,{className:"text-sm font-medium text-muted-foreground",children:"Template Types"})}),e.jsx(Me,{children:e.jsx("div",{className:"text-2xl font-bold",children:Y.length})})]})]}),e.jsxs(Ls,{open:i,onOpenChange:Ne=>{l(Ne),Ne||be()},children:[e.jsx(nl,{asChild:!0,children:e.jsxs(B,{className:"gap-2",children:[e.jsx(rn,{className:"h-4 w-4"}),"Add Template"]})}),e.jsxs(Ps,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Ds,{children:o?"Edit Template":"Add New Template"})}),e.jsxs("form",{onSubmit:Fe,className:"space-y-6 pt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"name",children:"Name *"}),e.jsx(xe,{id:"name",value:d.name,onChange:Ne=>u({...d,name:Ne.target.value}),placeholder:"Template name",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Description"}),e.jsx(BN,{content:d.description,onChange:Ne=>u({...d,description:Ne}),placeholder:"Brief description of the template",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(J,{children:"Canva Links *"}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:pe,className:"gap-1",children:[e.jsx(rn,{className:"h-3 w-3"}),"Add Link"]})]}),e.jsx("div",{className:"space-y-3",children:d.links.map((Ne,Ye)=>e.jsxs("div",{className:"flex gap-2 items-start p-3 border rounded-lg bg-muted/30",children:[e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(xe,{value:Ne.title,onChange:Ve=>Ae(Ye,"title",Ve.target.value),placeholder:"Link title (e.g., Instagram Post, Story)"}),e.jsx(xe,{value:Ne.canva_share_link,onChange:Ve=>Ae(Ye,"canva_share_link",Ve.target.value),placeholder:"https://www.canva.com/design/..."})]}),d.links.length>1&&e.jsx(B,{type:"button",variant:"ghost",size:"icon",className:"shrink-0 text-muted-foreground hover:text-destructive",onClick:()=>Ce(Ye),children:e.jsx(Qn,{className:"h-4 w-4"})})]},Ye))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Category"}),O?e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{value:P,onChange:Ne=>M(Ne.target.value),placeholder:"New category name",className:"flex-1"}),e.jsx(B,{type:"button",size:"sm",onClick:()=>P.trim()&&ce.mutate(P.trim()),disabled:ce.isPending,children:"Add"}),e.jsx(B,{type:"button",size:"sm",variant:"ghost",onClick:()=>{V(!1),M("")},children:e.jsx(Qn,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(is,{value:d.category_id,onValueChange:Ne=>u({...d,category_id:Ne}),children:[e.jsx(rs,{className:"flex-1",children:e.jsx(ls,{placeholder:"Select category"})}),e.jsx(as,{children:H.map(Ne=>e.jsx(He,{value:Ne.id,children:Ne.name},Ne.id))})]}),e.jsx(B,{type:"button",variant:"outline",size:"icon",onClick:()=>V(!0),children:e.jsx(rn,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Template Type"}),G?e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{value:I,onChange:Ne=>D(Ne.target.value),placeholder:"New type name",className:"flex-1"}),e.jsx(B,{type:"button",size:"sm",onClick:()=>I.trim()&&ie.mutate(I.trim()),disabled:ie.isPending,children:"Add"}),e.jsx(B,{type:"button",size:"sm",variant:"ghost",onClick:()=>{$(!1),D("")},children:e.jsx(Qn,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(is,{value:d.type_id,onValueChange:Ne=>u({...d,type_id:Ne}),children:[e.jsx(rs,{className:"flex-1",children:e.jsx(ls,{placeholder:"Select type"})}),e.jsx(as,{children:Y.map(Ne=>e.jsx(He,{value:Ne.id,children:Ne.name},Ne.id))})]}),e.jsx(B,{type:"button",variant:"outline",size:"icon",onClick:()=>$(!0),children:e.jsx(rn,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(xe,{id:"publish_date",type:"date",value:d.publish_date,onChange:Ne=>u({...d,publish_date:Ne.target.value})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Templates are sorted by publish date (newest first) on the member page"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Preview Image"}),e.jsxs("div",{className:"flex items-start gap-4",children:[j?e.jsxs("div",{className:"relative w-32 h-24 rounded-lg overflow-hidden border bg-muted",children:[e.jsx("img",{src:j,alt:"Preview",className:"w-full h-full object-cover"}),e.jsx(B,{type:"button",size:"icon",variant:"destructive",className:"absolute top-1 right-1 h-6 w-6",onClick:()=>{b(null),S("")},children:e.jsx(Qn,{className:"h-3 w-3"})})]}):e.jsx("div",{className:"w-32 h-24 rounded-lg border-2 border-dashed border-muted-foreground/25 flex items-center justify-center",children:e.jsx(hc,{className:"h-8 w-8 text-muted-foreground/50"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(xe,{type:"file",accept:"image/*",onChange:he,className:"cursor-pointer"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Upload a preview image for this template"})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(J,{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(Kr,{className:"h-5 w-5 text-primary shrink-0"}),e.jsx("span",{className:"text-sm flex-1 truncate",children:"Video uploaded"}),e.jsx(B,{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})})]}):y?e.jsxs("div",{className:"space-y-2 p-4 border rounded-lg bg-muted/30",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ct,{className:"h-4 w-4 animate-spin"}),e.jsxs("span",{className:"text-sm",children:["Uploading video... ",p,"%"]})]}),e.jsx(Fi,{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(Kr,{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(B,{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(Qn,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(xe,{type:"file",accept:"video/*",onChange: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(Kr,{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(J,{children:"Guide Files (PDFs)"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(xe,{type:"file",accept:".pdf,.doc,.docx",multiple:!0,onChange:Pe,className:"hidden"}),e.jsx(B,{type:"button",variant:"outline",size:"sm",className:"gap-1",asChild:!0,children:e.jsxs("span",{children:[e.jsx(Oa,{className:"h-3 w-3"}),"Add Files"]})})]})]}),d.guides.length>0?e.jsx("div",{className:"space-y-2",children:d.guides.map((Ne,Ye)=>e.jsxs("div",{className:"flex gap-2 items-center p-3 border rounded-lg bg-muted/30",children:[e.jsx(Fr,{className:"h-5 w-5 text-muted-foreground shrink-0"}),e.jsx(xe,{value:Ne.name,onChange:Ve=>ke(Ye,Ve.target.value),placeholder:"Guide name",className:"flex-1"}),Ne.file_size&&e.jsxs("span",{className:"text-xs text-muted-foreground shrink-0",children:[(Ne.file_size/1024).toFixed(0)," KB"]}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",className:"shrink-0 text-muted-foreground hover:text-destructive h-8 w-8",onClick:()=>ze(Ye),children:e.jsx(Qn,{className:"h-4 w-4"})})]},Ne.id||Ye))}):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(aon,{selectedKitIds:C,onChange:E}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>{l(!1),be()},children:"Cancel"}),e.jsx(B,{type:"submit",disabled:te.isPending,children:te.isPending?"Saving...":o?"Update":"Create"})]})]})]})]})]}),e.jsx(ve,{children:e.jsx(Me,{className:"p-0",children:ne?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading..."}):Z.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No templates yet. Add your first template!"}):e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"Preview"}),e.jsx(Pt,{children:"Name"}),e.jsx(Pt,{children:"Links"}),e.jsx(Pt,{children:"Category"}),e.jsx(Pt,{children:"Type"}),e.jsx(Pt,{children:"Publish Date"}),e.jsx(Pt,{className:"w-[72px] text-center",children:"Featured"}),e.jsx(Pt,{className:"text-right",children:"Actions"})]})}),e.jsx(Ka,{children:Z.map(Ne=>{var Ye,Ve,qe,Qe,Ue;return e.jsxs(pn,{children:[e.jsx(gt,{children:e.jsx("div",{className:"w-16 h-12 rounded overflow-hidden bg-muted",children:Ne.preview_image_url?e.jsx("img",{src:Ne.preview_image_url,alt:Ne.name,className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(hc,{className:"h-4 w-4 text-muted-foreground"})})})}),e.jsx(gt,{className:"font-medium",children:Ne.name}),e.jsx(gt,{children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs(Oe,{variant:"secondary",children:[((Ye=Ne.links)==null?void 0:Ye.length)||0," link",(((Ve=Ne.links)==null?void 0:Ve.length)||0)!==1?"s":""]}),(((qe=Ne.guides)==null?void 0:qe.length)||0)>0&&e.jsxs(Oe,{variant:"outline",className:"gap-1",children:[e.jsx(Fr,{className:"h-3 w-3"}),(Qe=Ne.guides)==null?void 0:Qe.length," guide",(((Ue=Ne.guides)==null?void 0:Ue.length)||0)!==1?"s":""]})]})}),e.jsx(gt,{children:Ne.category?e.jsx(Oe,{variant:"secondary",children:Ne.category.name}):e.jsx("span",{className:"text-muted-foreground",children:"-"})}),e.jsx(gt,{children:Ne.type?e.jsx(Oe,{variant:"outline",children:Ne.type.name}):e.jsx("span",{className:"text-muted-foreground",children:"-"})}),e.jsx(gt,{className:"text-muted-foreground",children:new Date(Ne.publish_date).toLocaleDateString()}),e.jsx(gt,{className:"text-center",children:e.jsx(B,{type:"button",size:"icon",variant:"ghost",className:"mx-auto",title:Ne.is_featured?"Remove from featured templates":"Add to featured templates",onClick:()=>le.mutate({id:Ne.id,is_featured:!Ne.is_featured}),children:e.jsx(Da,{className:`h-4 w-4 ${Ne.is_featured?"fill-yellow-400 text-yellow-400":"text-muted-foreground"}`})})}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{size:"icon",variant:"ghost",onClick:()=>me(Ne),children:e.jsx(Ya,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"text-destructive hover:text-destructive",onClick:async()=>{await Xi("Delete this template?")&&ae.mutate(Ne.id)},children:e.jsx(Sn,{className:"h-4 w-4"})})]})})]},Ne.id)})})]})})})]})})};function EVt({selectedTemplateIds:s,onChange:t}){const[n,r]=_.useState(""),[a,i]=_.useState(!1),{data:l=[]}=at({queryKey:["all-canva-templates-picker"],queryFn:async()=>{const{data:h,error:m}=await q.from("canva_templates").select("id, name, preview_image_url").order("name");if(m)throw m;return h}}),o=l.filter(h=>s.includes(h.id)),c=l.filter(h=>!s.includes(h.id)&&h.name.toLowerCase().includes(n.toLowerCase())),d=h=>{t([...s,h])},u=h=>{t(s.filter(m=>m!==h))};return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(J,{className:"flex items-center gap-2",children:[e.jsx(pj,{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(Oe,{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(Qn,{className:"h-3 w-3"})})]},h.id))}),e.jsxs(od,{open:a,onOpenChange:i,children:[e.jsx(ld,{asChild:!0,children:e.jsxs(B,{type:"button",variant:"outline",size:"sm",className:"gap-1",children:[e.jsx(pj,{className:"h-3.5 w-3.5"}),"Add Template"]})}),e.jsxs(Qc,{className:"w-80 p-2",align:"start",children:[e.jsxs("div",{className:"relative mb-2",children:[e.jsx(Lr,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search templates...",value:n,onChange:h=>r(h.target.value),className:"pl-7 h-8 text-sm"})]}),e.jsx("div",{className:"max-h-48 overflow-y-auto space-y-0.5",children:c.length===0?e.jsx("p",{className:"text-xs text-muted-foreground text-center py-3",children:n?"No templates found":"All templates selected"}):c.map(h=>e.jsxs("button",{type:"button",onClick:()=>{d(h.id),r("")},className:"w-full flex items-center gap-2 px-2 py-1.5 rounded-md hover:bg-muted text-left text-sm transition-colors",children:[h.preview_image_url?e.jsx("img",{src:h.preview_image_url,alt:"",className:"w-8 h-8 rounded object-cover flex-shrink-0"}):e.jsx("div",{className:"w-8 h-8 rounded bg-muted flex items-center justify-center flex-shrink-0",children:e.jsx(pj,{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 oon=[{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"}],zvt=new Intl.DateTimeFormat("en-CA",{timeZone:"America/New_York",year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date),Bvt=s=>{const[t,n,r]=s.split(/[-/T]/);return`${Number(n)}/${Number(r)}/${t}`},lon=()=>{const{user:s}=hs(),[t,n]=Yl(),{toast:r}=vi(),a=Bt(),[i,l]=_.useState(!1),[o,c]=_.useState(null),[d,u]=_.useState({title:"",description:"",video_url:"",video_type:"youtube",duration:"",category_id:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),[h,m]=_.useState(null),[p,f]=_.useState(""),[y,v]=_.useState([]),[g,b]=_.useState([]),[j,S]=_.useState([]),[C,E]=_.useState([]),[P,M]=_.useState(""),[I,D]=_.useState(!1),[O,V]=_.useState(null),[G,$]=_.useState(0),[H,Y]=_.useState(!1),[Z,ne]=_.useState(null),{data:ce=[]}=at({queryKey:["academy-categories"],queryFn:async()=>{const{data:Ne,error:Ye}=await q.from("academy_categories").select("*").order("sort_order",{ascending:!0});if(Ye)throw Ye;return Ne}}),{data:ie=[],isLoading:te}=at({queryKey:["academy-videos-admin"],queryFn:async()=>{const{data:Ne,error:Ye}=await q.from("academy_videos").select(` *, category:academy_categories(id, name) `).order("publish_date",{ascending:!1});if(Ye)throw Ye;const{data:Ve,error:qe}=await q.from("academy_resources").select("*").order("sort_order");if(qe)throw qe;return Ne.map(Ue=>({...Ue,resources:(Ve==null?void 0:Ve.filter(Xe=>Xe.video_id===Ue.id))||[]}))}});_.useEffect(()=>{const Ne=t.get("edit");if(Ne&&ie.length>0){const Ye=ie.find(Ve=>Ve.id===Ne);Ye&&(Ae(Ye),n({},{replace:!0}))}},[ie,t]);const ae=mt({mutationFn:async Ne=>{const{data:Ye,error:Ve}=await q.from("academy_categories").insert({name:Ne,sort_order:ce.length}).select().single();if(Ve)throw Ve;return Ye},onSuccess:Ne=>{a.invalidateQueries({queryKey:["academy-categories"]}),u({...d,category_id:Ne.id}),M(""),D(!1),r({title:"Category added"})},onError:Ne=>{r({title:"Error adding category",description:Ne.message,variant:"destructive"})}}),le=mt({mutationFn:async Ne=>{let Ye=Ne.existingThumbnailUrl;if(Ne.thumbnail){const Qe=Ne.thumbnail.name.split(".").pop(),Ue=`thumbnails/${Date.now()}-${Math.random().toString(36).substring(7)}.${Qe}`,{error:Xe}=await q.storage.from("academy-resources").upload(Ue,Ne.thumbnail);if(Xe)throw Xe;const{data:nt}=q.storage.from("academy-resources").getPublicUrl(Ue);Ye=nt.publicUrl}const Ve={title:Ne.video.title,description:Ne.video.description||null,video_url:Ne.video.video_url,video_type:Ne.video.video_type,duration:Ne.video.duration||null,thumbnail_url:Ye,category_id:Ne.video.category_id||null,publish_date:Ne.video.publish_date?new Date(Ne.video.publish_date).toISOString():new Date().toISOString(),is_published:Ne.video.is_published,created_by:s==null?void 0:s.id};let qe=Ne.videoId;if(qe){const{error:Qe}=await q.from("academy_videos").update(Ve).eq("id",qe);if(Qe)throw Qe}else{const{data:Qe,error:Ue}=await q.from("academy_videos").insert(Ve).select().single();if(Ue)throw Ue;qe=Qe.id,Yin(Ne.video.title,Qe.id)}if(Ne.resourcesToDelete.length>0){const{error:Qe}=await q.from("academy_resources").delete().in("id",Ne.resourcesToDelete);if(Qe)throw Qe}for(let Qe=0;Qe0){const{error:Qe}=await q.from("academy_video_templates").insert(C.map(Ue=>({video_id:qe,template_id:Ue})));if(Qe)throw Qe}},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-videos-admin"]}),a.invalidateQueries({queryKey:["academy-videos"]}),Ce(),l(!1),r({title:o?"Video updated":"Video created"})},onError:Ne=>{r({title:"Error saving video",description:Ne.message,variant:"destructive"})}}),be=mt({mutationFn:async Ne=>{const{error:Ye}=await q.from("academy_videos").delete().eq("id",Ne);if(Ye)throw Ye},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-videos-admin"]}),a.invalidateQueries({queryKey:["academy-videos"]}),r({title:"Video deleted"})},onError:Ne=>{r({title:"Error deleting video",description:Ne.message,variant:"destructive"})}}),me=mt({mutationFn:async({id:Ne,is_published:Ye})=>{const{error:Ve}=await q.from("academy_videos").update({is_published:Ye}).eq("id",Ne);if(Ve)throw Ve},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-videos-admin"]}),a.invalidateQueries({queryKey:["academy-videos"]})},onError:Ne=>{r({title:"Error updating video",description:Ne.message,variant:"destructive"})}}),he=async Ne=>{try{let Ye=Ne.public_slug||null,Ve=!!Ne.is_public;if(!Ye||!Ve){const Qe=(Ne.title||"video").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||"video";if(!Ye){let Xe=Qe;const{data:nt}=await q.from("academy_videos").select("id").eq("public_slug",Xe).maybeSingle();nt&&nt.id!==Ne.id&&(Xe=`${Qe}-${Ne.id.slice(0,6)}`),Ye=Xe}const{error:Ue}=await q.from("academy_videos").update({public_slug:Ye,is_public:!0}).eq("id",Ne.id);if(Ue)throw Ue;a.invalidateQueries({queryKey:["academy-videos-admin"]})}const qe=`${window.location.origin}/watch/${Ye}`;await navigator.clipboard.writeText(qe),r({title:"Public link copied",description:qe})}catch(Ye){r({title:"Could not copy link",description:Ye.message,variant:"destructive"})}},pe=async Ne=>{if(!await Xi("Disable the public teaser link for this video?"))return;const{error:Ye}=await q.from("academy_videos").update({is_public:!1}).eq("id",Ne.id);if(Ye){r({title:"Error",description:Ye.message,variant:"destructive"});return}a.invalidateQueries({queryKey:["academy-videos-admin"]}),r({title:"Public link disabled"})},Ce=()=>{u({title:"",description:"",video_url:"",video_type:"bunny_stream",duration:"",category_id:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),m(null),f(""),v([]),b([]),S([]),c(null),E([]),M(""),V(null),$(0),Y(!1),ne(null)},Ae=async Ne=>{c(Ne),u({title:Ne.title,description:Ne.description||"",video_url:Ne.video_url,video_type:Ne.video_type,duration:Ne.duration||"",category_id:Ne.category_id||"",publish_date:Ne.publish_date?new Date(Ne.publish_date).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],is_published:Ne.is_published}),f(Ne.thumbnail_url||""),b(Ne.resources||[]),v([]),S([]);const{data:Ye}=await q.from("academy_video_templates").select("template_id").eq("video_id",Ne.id);E((Ye||[]).map(Ve=>Ve.template_id)),l(!0)},Pe=Ne=>{var Ve;const Ye=(Ve=Ne.target.files)==null?void 0:Ve[0];Ye&&(m(Ye),f(URL.createObjectURL(Ye)))},ze=Ne=>{const Ye=Ne.target.files;if(Ye){const Ve=Array.from(Ye).map(qe=>({file:qe,title:qe.name.replace(/\.[^/.]+$/,"")}));v([...y,...Ve])}Ne.target.value=""},ke=Ne=>{v(y.filter((Ye,Ve)=>Ve!==Ne))},Ze=Ne=>{S([...j,Ne]),b(g.filter(Ye=>Ye.id!==Ne))},Se=async()=>{if(!O)return null;Y(!0),$(0);try{const{data:Ne,error:Ye}=await q.functions.invoke("bunny-upload",{body:{action:"create",title:d.title||O.name}});if(Ye)throw new Error(Ye.message);const{videoId:Ve,libraryId:qe}=Ne;ne(Ve);const{data:Qe,error:Ue}=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:Ve}});if(Ue)throw new Error(Ue.message);const Xe=new XMLHttpRequest;return await new Promise(($e,Ge)=>{Xe.upload.addEventListener("progress",ct=>{if(ct.lengthComputable){const xt=Math.round(ct.loaded/ct.total*100);$(xt)}}),Xe.addEventListener("load",()=>{Xe.status>=200&&Xe.status<300?$e():Ge(new Error(`Upload failed with status ${Xe.status}`))}),Xe.addEventListener("error",()=>Ge(new Error("Upload failed"))),Xe.open("PUT",Qe.uploadUrl),Xe.setRequestHeader("AccessKey",Qe.apiKey),Xe.send(O)}),`https://player.mediadelivery.net/embed/${qe}/${Ve}`}catch(Ne){return console.error("Bunny upload error:",Ne),r({title:"Video upload failed",description:Ne instanceof Error?Ne.message:"Unknown error",variant:"destructive"}),null}finally{Y(!1)}},Fe=async Ne=>{if(Ne.preventDefault(),!d.title.trim()){r({title:"Please enter a video title",variant:"destructive"});return}let Ye=d.video_url;if(d.video_type==="bunny_stream"&&O&&!o){const Ve=await Se();if(!Ve)return;Ye=Ve}else if(!d.video_url.trim()&&d.video_type!=="bunny_stream"){r({title:"Please enter a video URL",variant:"destructive"});return}else if(d.video_type==="bunny_stream"&&!O&&!d.video_url&&!o){r({title:"Please select a video file to upload",variant:"destructive"});return}le.mutate({video:{...d,video_url:Ye},thumbnail:h,existingThumbnailUrl:(o==null?void 0:o.thumbnail_url)||null,videoId:o==null?void 0:o.id,newResources:y,resourcesToDelete:j})};return e.jsx(zs,{title:"Manage Academy",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Wh,{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(ve,{children:[e.jsx(bt,{className:"pb-2",children:e.jsx(St,{className:"text-sm font-medium text-muted-foreground",children:"Total Videos"})}),e.jsx(Me,{children:e.jsx("div",{className:"text-2xl font-bold",children:ie.length})})]}),e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-2",children:e.jsx(St,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Me,{children:e.jsx("div",{className:"text-2xl font-bold",children:ie.filter(Ne=>Ne.is_published).length})})]}),e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-2",children:e.jsx(St,{className:"text-sm font-medium text-muted-foreground",children:"Public Teasers"})}),e.jsx(Me,{children:e.jsx("div",{className:"text-2xl font-bold",children:ie.filter(Ne=>Ne.is_public).length})})]}),e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-2",children:e.jsx(St,{className:"text-sm font-medium text-muted-foreground",children:"Total Public Views"})}),e.jsx(Me,{children:e.jsx("div",{className:"text-2xl font-bold",children:ie.reduce((Ne,Ye)=>Ne+(Ye.public_view_count||0),0).toLocaleString()})})]})]}),e.jsxs(Ls,{open:i,onOpenChange:Ne=>{l(Ne),Ne||Ce()},children:[e.jsx(nl,{asChild:!0,children:e.jsxs(B,{className:"gap-2",children:[e.jsx(rn,{className:"h-4 w-4"}),"Add Video"]})}),e.jsxs(Ps,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Ds,{children:o?"Edit Video":"Add New Video"})}),e.jsxs("form",{onSubmit:Fe,className:"space-y-6 pt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"title",children:"Title *"}),e.jsx(xe,{id:"title",value:d.title,onChange:Ne=>u({...d,title:Ne.target.value}),placeholder:"Video title",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Description"}),e.jsx(BN,{content:d.description,onChange:Ne=>u({...d,description:Ne}),placeholder:"Brief description of the video",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Video Type"}),e.jsxs(is,{value:d.video_type,onValueChange:Ne=>{u({...d,video_type:Ne,video_url:""}),V(null)},disabled:H,children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsx(as,{children:oon.map(Ne=>e.jsx(He,{value:Ne.value,children:Ne.label},Ne.value))})]})]}),d.video_type==="bunny_stream"?e.jsxs("div",{className:"space-y-3",children:[e.jsxs(J,{children:["Upload Video File ",!o&&"*"]}),o&&d.video_url&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Current video: ",e.jsx("a",{href:d.video_url,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline",children:"View"})]}),!o&&e.jsxs(e.Fragment,{children:[e.jsx(xe,{type:"file",accept:"video/*",onChange:Ne=>{var Ve;const Ye=(Ve=Ne.target.files)==null?void 0:Ve[0];Ye&&V(Ye)},disabled:H}),O&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Kr,{className:"h-4 w-4"}),O.name," (",(O.size/(1024*1024)).toFixed(1)," MB)"]}),H&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ct,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{className:"text-sm",children:"Uploading to Bunny.net..."})]}),e.jsx(Fi,{value:G,className:"h-2"}),e.jsxs("p",{className:"text-xs text-muted-foreground text-right",children:[G,"%"]})]})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"video_url",children:"Video URL *"}),e.jsx(xe,{id:"video_url",value:d.video_url,onChange:Ne=>u({...d,video_url:Ne.target.value}),placeholder:"https://...",required:!0})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"duration",children:"Duration"}),e.jsx(xe,{id:"duration",value:d.duration,onChange:Ne=>u({...d,duration:Ne.target.value}),placeholder:"e.g., 45:30"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"publish_date",children:"Publish Date (go-live)"}),e.jsx(xe,{id:"publish_date",type:"date",value:d.publish_date,onChange:Ne=>u({...d,publish_date:Ne.target.value})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Members only see the video on or after this date."})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Category"}),I?e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{value:P,onChange:Ne=>M(Ne.target.value),placeholder:"New category name",className:"flex-1"}),e.jsx(B,{type:"button",size:"sm",onClick:()=>P.trim()&&ae.mutate(P.trim()),disabled:ae.isPending,children:"Add"}),e.jsx(B,{type:"button",size:"sm",variant:"ghost",onClick:()=>{D(!1),M("")},children:e.jsx(Qn,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(is,{value:d.category_id,onValueChange:Ne=>u({...d,category_id:Ne}),children:[e.jsx(rs,{className:"flex-1",children:e.jsx(ls,{placeholder:"Select category"})}),e.jsx(as,{children:ce.map(Ne=>e.jsx(He,{value:Ne.id,children:Ne.name},Ne.id))})]}),e.jsx(B,{type:"button",variant:"outline",size:"sm",onClick:()=>D(!0),children:e.jsx(rn,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Thumbnail Image"}),e.jsxs("div",{className:"flex items-start gap-4",children:[p&&e.jsx("img",{src:p,alt:"Thumbnail preview",className:"w-32 h-20 object-cover rounded-md border"}),e.jsxs("div",{className:"flex-1",children:[e.jsx(xe,{type:"file",accept:"image/*",onChange:Pe,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(J,{children:"Resource Files"}),e.jsx(B,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsxs("label",{className:"cursor-pointer gap-1",children:[e.jsx(Oa,{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"})]})})]}),(g.length>0||y.length>0)&&e.jsxs("div",{className:"space-y-2 mt-2",children:[g.map(Ne=>e.jsxs("div",{className:"flex items-center gap-2 p-2 border rounded-md bg-muted/30",children:[e.jsx(Fr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"flex-1 text-sm truncate",children:Ne.title}),e.jsx(Oe,{variant:"outline",className:"text-xs",children:Ne.file_type}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>Ze(Ne.id),className:"text-destructive hover:text-destructive",children:e.jsx(Qn,{className:"h-4 w-4"})})]},Ne.id)),y.map((Ne,Ye)=>e.jsxs("div",{className:"flex items-center gap-2 p-2 border rounded-md bg-muted/30",children:[e.jsx(Fr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(xe,{value:Ne.title,onChange:Ve=>{const qe=[...y];qe[Ye].title=Ve.target.value,v(qe)},className:"flex-1 h-8",placeholder:"Resource title"}),e.jsx(Oe,{variant:"secondary",className:"text-xs",children:"New"}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>ke(Ye),className:"text-destructive hover:text-destructive",children:e.jsx(Qn,{className:"h-4 w-4"})})]},Ye))]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Supported: PDF, PowerPoint, Excel, Word, ZIP"})]}),e.jsx(EVt,{selectedTemplateIds:C,onChange:E}),e.jsxs("div",{className:"space-y-2 rounded-lg border p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fn,{id:"is_published",checked:d.is_published,onCheckedChange:Ne=>u({...d,is_published:Ne})}),e.jsx(J,{htmlFor:"is_published",children:"Published"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:d.is_published?d.publish_date>zvt?`Scheduled — goes live automatically on ${Bvt(d.publish_date)}.`:"Live now for members.":"Draft — hidden from members until you turn this on."})]}),e.jsxs(yr,{children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>l(!1),disabled:H,children:"Cancel"}),e.jsx(B,{type:"submit",disabled:le.isPending||H,children:H?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),"Uploading..."]}):le.isPending?"Saving...":o?"Update Video":"Add Video"})]})]})]})]})]}),e.jsx(ve,{children:e.jsx(Me,{className:"p-0",children:te?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):ie.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Kr,{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(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"Title"}),e.jsx(Pt,{children:"Category"}),e.jsx(Pt,{children:"Duration"}),e.jsx(Pt,{children:"Resources"}),e.jsx(Pt,{children:"Publish Date"}),e.jsx(Pt,{children:"Status"}),e.jsx(Pt,{children:"Public Views"}),e.jsx(Pt,{className:"w-[120px]",children:"Actions"})]})}),e.jsx(Ka,{children:ie.map(Ne=>e.jsxs(pn,{children:[e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[Ne.thumbnail_url?e.jsx("img",{src:Ne.thumbnail_url,alt:"",className:"w-16 h-10 object-cover rounded"}):e.jsx("div",{className:"w-16 h-10 bg-muted rounded flex items-center justify-center",children:e.jsx(Kr,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:Ne.title}),e.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:Ne.video_type.replace("_"," ")})]})]})}),e.jsx(gt,{children:Ne.category?e.jsx(Oe,{variant:"outline",children:Ne.category.name}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(gt,{children:Ne.duration||"-"}),e.jsx(gt,{children:Ne.resources&&Ne.resources.length>0?e.jsxs(Oe,{variant:"secondary",children:[Ne.resources.length," file(s)"]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(gt,{children:Bvt(Ne.publish_date)}),e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fn,{checked:Ne.is_published,onCheckedChange:Ye=>me.mutate({id:Ne.id,is_published:Ye})}),Ne.is_published?Ne.publish_date.slice(0,10)>zvt?e.jsxs(Oe,{variant:"outline",className:"gap-1",children:[e.jsx(Gr,{className:"h-3 w-3"})," Scheduled"]}):e.jsx(Oe,{variant:"secondary",children:"Live"}):e.jsx(Oe,{variant:"outline",className:"text-muted-foreground",children:"Draft"})]})}),e.jsx(gt,{children:Ne.is_public?e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ya,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-sm font-medium",children:(Ne.public_view_count||0).toLocaleString()})]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(B,{variant:"ghost",size:"sm",title:Ne.is_public?"Copy public teaser link":"Make public & copy teaser link",onClick:()=>he(Ne),children:Ne.is_public?e.jsx(Ia,{className:"h-4 w-4 text-primary"}):e.jsx(bd,{className:"h-4 w-4"})}),Ne.is_public&&e.jsx(B,{variant:"ghost",size:"sm",title:"Disable public link",onClick:()=>pe(Ne),children:e.jsx(sl,{className:"h-4 w-4 text-emerald-500"})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>Ae(Ne),children:e.jsx(Ya,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>be.mutate(Ne.id),className:"text-destructive hover:text-destructive",children:e.jsx(Sn,{className:"h-4 w-4"})})]})})]},Ne.id))})]})})})]})})},eZ=s=>s.toLowerCase().trim().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60),Uvt={public_enabled:!1,public_slug:"",public_headline:"",public_subheadline:"",public_cta_text:"",public_benefits:"",public_hero_image_url:""};function con(){var be,me,he;const s=Bt(),[t,n]=Yl(),[r,a]=_.useState(!1),[i,l]=_.useState(null),[o,c]=_.useState({name:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,...Uvt}),[d,u]=_.useState(null),[h,m]=_.useState(""),[p,f]=_.useState([]),[y,v]=_.useState([]),[g,b]=_.useState([]),[j,S]=_.useState(null),{data:C,isLoading:E}=at({queryKey:["resource-kits"],queryFn:async()=>{const{data:pe,error:Ce}=await q.from("resource_kits").select("*").order("publish_date",{ascending:!1});if(Ce)throw Ce;return pe}}),{data:P}=at({queryKey:["resource-kit-files"],queryFn:async()=>{const{data:pe,error:Ce}=await q.from("resource_kit_files").select("*").order("sort_order",{ascending:!0});if(Ce)throw Ce;return pe}}),{data:M}=at({queryKey:["resource-kit-links"],queryFn:async()=>{const{data:pe,error:Ce}=await q.from("resource_kit_links").select("*").order("sort_order",{ascending:!0});if(Ce)throw Ce;return pe}}),{data:I}=at({queryKey:["resource-kit-leads"],queryFn:async()=>{const{data:pe,error:Ce}=await q.from("resource_kit_leads").select("id, kit_id, full_name, email, brokerage, created_at").order("created_at",{ascending:!1}).limit(500);if(Ce)throw Ce;return pe}});_.useEffect(()=>{const pe=t.get("edit");if(pe&&C&&C.length>0&&P&&M){const Ce=C.find(Ae=>Ae.id===pe);Ce&&(O(Ce),n({},{replace:!0}))}},[C,P,M,t]);const D=()=>{c({name:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,...Uvt}),u(null),m(""),f([]),v([]),b([]),l(null)},O=async pe=>{l(pe),c({name:pe.name,description:pe.description||"",publish_date:pe.publish_date.split("T")[0],is_published:pe.is_published,public_enabled:!!pe.public_enabled,public_slug:pe.public_slug||"",public_headline:pe.public_headline||"",public_subheadline:pe.public_subheadline||"",public_cta_text:pe.public_cta_text||"",public_benefits:Array.isArray(pe.public_benefits)?pe.public_benefits.join(` `):"",public_hero_image_url:pe.public_hero_image_url||""}),m(pe.featured_image_url||"");const Ce=(P==null?void 0:P.filter(ze=>ze.kit_id===pe.id))||[];f(Ce.map(ze=>({id:ze.id,name:ze.name,file_url:ze.file_url,file_type:ze.file_type,file_size:ze.file_size,sort_order:ze.sort_order})));const Ae=(M==null?void 0:M.filter(ze=>ze.kit_id===pe.id))||[];v(Ae.map(ze=>({id:ze.id,title:ze.title,canva_share_link:ze.canva_share_link,sort_order:ze.sort_order})));const{data:Pe}=await q.from("resource_kit_templates").select("template_id").eq("kit_id",pe.id);b((Pe||[]).map(ze=>ze.template_id)),a(!0)},V=pe=>{var Ae;const Ce=(Ae=pe.target.files)==null?void 0:Ae[0];Ce&&(u(Ce),m(URL.createObjectURL(Ce)))},G=()=>{f([...p,{name:"",file_url:"",sort_order:p.length}])},$=pe=>{f(p.filter((Ce,Ae)=>Ae!==pe))},H=(pe,Ce,Ae)=>{const Pe=[...p];Pe[pe]={...Pe[pe],[Ce]:Ae},f(Pe)},Y=()=>{v([...y,{title:"",canva_share_link:"",sort_order:y.length}])},Z=pe=>{v(y.filter((Ce,Ae)=>Ae!==pe))},ne=(pe,Ce,Ae)=>{const Pe=[...y];Pe[pe]={...Pe[pe],[Ce]:Ae},v(Pe)},ce=(pe,Ce)=>{var Pe;const Ae=(Pe=Ce.target.files)==null?void 0:Pe[0];if(Ae){const ze=[...p],ke=Ae.name.replace(/\.[^/.]+$/,"");ze[pe]={...ze[pe],file:Ae,file_type:Ae.type,file_size:Ae.size,name:ze[pe].name||ke},f(ze)}},ie=mt({mutationFn:async()=>{let pe=(i==null?void 0:i.featured_image_url)||null;if(d){const Ze=d.name.split(".").pop(),Se=`${Date.now()}.${Ze}`,{error:Fe}=await q.storage.from("resource-kits").upload(`featured/${Se}`,d);if(Fe)throw Fe;const{data:Ne}=q.storage.from("resource-kits").getPublicUrl(`featured/${Se}`);pe=Ne.publicUrl}const Ce=o.public_enabled?o.public_slug?eZ(o.public_slug):eZ(o.name):o.public_slug?eZ(o.public_slug):null,Ae={name:o.name,description:o.description||null,featured_image_url:pe,publish_date:o.publish_date,is_published:o.is_published,public_enabled:o.public_enabled,public_slug:Ce||null,public_headline:o.public_headline||null,public_subheadline:o.public_subheadline||null,public_cta_text:o.public_cta_text||null,public_benefits:o.public_benefits.split(` `).map(Ze=>Ze.trim()).filter(Boolean),public_hero_image_url:o.public_hero_image_url||null};let Pe;const ze=!i,ke=(i==null?void 0:i.is_published)||!1;if(i){const{error:Ze}=await q.from("resource_kits").update(Ae).eq("id",i.id);if(Ze)throw Ze;Pe=i.id;const Se=(P==null?void 0:P.filter(Qe=>Qe.kit_id===i.id).map(Qe=>Qe.id))||[],Fe=p.filter(Qe=>Qe.id).map(Qe=>Qe.id),Ne=Se.filter(Qe=>!Fe.includes(Qe));Ne.length>0&&await q.from("resource_kit_files").delete().in("id",Ne);const Ye=(M==null?void 0:M.filter(Qe=>Qe.kit_id===i.id).map(Qe=>Qe.id))||[],Ve=y.filter(Qe=>Qe.id).map(Qe=>Qe.id),qe=Ye.filter(Qe=>!Ve.includes(Qe));qe.length>0&&await q.from("resource_kit_links").delete().in("id",qe)}else{const{data:Ze,error:Se}=await q.from("resource_kits").insert(Ae).select().single();if(Se)throw Se;Pe=Ze.id}for(let Ze=0;Ze0){const{error:Ze}=await q.from("resource_kit_templates").insert(g.map(Se=>({kit_id:Pe,template_id:Se})));if(Ze)throw Ze}return{kitId:Pe,kitName:o.name,isNewKit:ze,wasPublished:ke,isPublished:o.is_published}},onSuccess:pe=>{s.invalidateQueries({queryKey:["resource-kits"]}),s.invalidateQueries({queryKey:["resource-kit-files"]}),s.invalidateQueries({queryKey:["resource-kit-links"]}),se.success(i?"Resource kit updated":"Resource kit created"),pe.isPublished&&(pe.isNewKit||!pe.wasPublished)&&Xin(pe.kitName,pe.kitId),a(!1),D()},onError:pe=>{se.error("Failed to save resource kit: "+pe.message)}}),te=mt({mutationFn:async pe=>{const{error:Ce}=await q.from("resource_kits").delete().eq("id",pe);if(Ce)throw Ce},onSuccess:()=>{s.invalidateQueries({queryKey:["resource-kits"]}),s.invalidateQueries({queryKey:["resource-kit-files"]}),se.success("Resource kit deleted")},onError:pe=>{se.error("Failed to delete: "+pe.message)}}),ae=pe=>{if(pe.preventDefault(),!o.name){se.error("Please enter a name");return}ie.mutate()},le=pe=>(P==null?void 0:P.filter(Ce=>Ce.kit_id===pe).length)||0;return e.jsx(zs,{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(ve,{children:[e.jsx(bt,{className:"pb-2",children:e.jsx(St,{className:"text-sm font-medium text-muted-foreground",children:"Total Kits"})}),e.jsx(Me,{children:e.jsx("div",{className:"text-2xl font-bold",children:(C==null?void 0:C.length)||0})})]}),e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-2",children:e.jsx(St,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Me,{children:e.jsx("div",{className:"text-2xl font-bold",children:(C==null?void 0:C.filter(pe=>pe.is_published).length)||0})})]})]}),e.jsxs(B,{onClick:()=>{D(),a(!0)},children:[e.jsx(rn,{className:"h-4 w-4 mr-2"}),"Add Resource Kit"]})]}),e.jsx(ve,{children:e.jsx(Me,{className:"p-0",children:e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"Name"}),e.jsx(Pt,{children:"Files"}),e.jsx(Pt,{children:"Publish Date"}),e.jsx(Pt,{children:"Status"}),e.jsx(Pt,{className:"text-right",children:"Actions"})]})}),e.jsx(Ka,{children:E?e.jsx(pn,{children:e.jsx(gt,{colSpan:5,className:"text-center py-8",children:"Loading..."})}):(C==null?void 0:C.length)===0?e.jsx(pn,{children:e.jsx(gt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No resource kits yet. Create your first one!"})}):C==null?void 0:C.map(pe=>e.jsxs(pn,{children:[e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[pe.featured_image_url?e.jsx("img",{src:pe.featured_image_url,alt:pe.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(Nh,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:pe.name}),pe.description&&e.jsx("div",{className:"text-sm text-muted-foreground line-clamp-1",children:pe.description})]})]})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Fr,{className:"h-4 w-4 text-muted-foreground"}),le(pe.id)]})}),e.jsx(gt,{children:Hs(new Date(pe.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 ${pe.is_published?"bg-green-100 text-green-800":"bg-yellow-100 text-yellow-800"}`,children:pe.is_published?"Published":"Draft"})}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[pe.public_enabled&&pe.public_slug&&e.jsx(B,{variant:"ghost",size:"icon",title:"Copy public landing page link",onClick:()=>{navigator.clipboard.writeText(`${window.location.origin}/resources/${pe.public_slug}`),se.success("Public link copied")},children:e.jsx(sl,{className:"h-4 w-4 text-emerald-600"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{const Ce=(P==null?void 0:P.filter(Pe=>Pe.kit_id===pe.id))||[],Ae=(M==null?void 0:M.filter(Pe=>Pe.kit_id===pe.id))||[];S({...pe,files:Ce,links:Ae})},children:e.jsx(ya,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>O(pe),children:e.jsx(Ya,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:async()=>{await Xi("Delete this resource kit?")&&te.mutate(pe.id)},children:e.jsx(Sn,{className:"h-4 w-4 text-destructive"})})]})})]},pe.id))})]})})}),e.jsxs(ve,{className:"mt-6",children:[e.jsx(bt,{children:e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(In,{className:"h-5 w-5"}),"Public Resource Leads",e.jsxs("span",{className:"text-sm font-normal text-muted-foreground",children:["(",(I==null?void 0:I.length)||0,")"]})]})}),e.jsx(Me,{children:!I||I.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No leads yet. Turn on a public landing page for a kit and share the link."}):e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"Agent"}),e.jsx(Pt,{children:"Email"}),e.jsx(Pt,{children:"Brokerage"}),e.jsx(Pt,{children:"Resource"}),e.jsx(Pt,{children:"Captured"})]})}),e.jsx(Ka,{children:I.map(pe=>{var Ce;return e.jsxs(pn,{children:[e.jsx(gt,{className:"font-medium",children:pe.full_name}),e.jsx(gt,{children:pe.email}),e.jsx(gt,{children:pe.brokerage||"—"}),e.jsx(gt,{children:((Ce=C==null?void 0:C.find(Ae=>Ae.id===pe.kit_id))==null?void 0:Ce.name)||"—"}),e.jsx(gt,{children:Hs(new Date(pe.created_at),"MMM d, yyyy")})]},pe.id)})})]})})]}),e.jsx(Ls,{open:r,onOpenChange:a,children:e.jsxs(Ps,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Ds,{children:i?"Edit Resource Kit":"Add Resource Kit"})}),e.jsxs("form",{onSubmit:ae,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{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(Nh,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx(xe,{type:"file",accept:"image/*",onChange:V})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"name",children:"Name *"}),e.jsx(xe,{id:"name",value:o.name,onChange:pe=>c({...o,name:pe.target.value}),placeholder:"Resource Kit Name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Description"}),e.jsx(BN,{content:o.description,onChange:pe=>c({...o,description:pe}),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(J,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(xe,{id:"publish_date",type:"date",value:o.publish_date,onChange:pe=>c({...o,publish_date:pe.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Published"}),e.jsxs("div",{className:"flex items-center space-x-2 pt-2",children:[e.jsx(fn,{checked:o.is_published,onCheckedChange:pe=>c({...o,is_published:pe})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:o.is_published?"Visible to agents":"Hidden from agents"})]})]})]}),e.jsxs("div",{className:"space-y-3 rounded-xl border p-4 bg-muted/30",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(J,{className:"text-base",children:"Public Landing Page"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Share this resource publicly and capture agent name, email and brokerage as leads."})]}),e.jsx(fn,{checked:o.public_enabled,onCheckedChange:pe=>c({...o,public_enabled:pe,public_slug:o.public_slug||eZ(o.name)})})]}),o.public_enabled&&e.jsxs("div",{className:"space-y-3 pt-1",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Public link"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("div",{className:"flex items-center rounded-md border bg-background px-2 text-sm text-muted-foreground",children:"/resources/"}),e.jsx(xe,{value:o.public_slug,onChange:pe=>c({...o,public_slug:pe.target.value}),placeholder:"listing-checklist"}),e.jsxs(B,{type:"button",variant:"outline",onClick:()=>{const pe=eZ(o.public_slug||o.name);navigator.clipboard.writeText(`${window.location.origin}/resources/${pe}`),se.success("Public link copied")},children:[e.jsx(Vc,{className:"h-4 w-4 mr-1"})," Copy"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Headline"}),e.jsx(xe,{value:o.public_headline,onChange:pe=>c({...o,public_headline:pe.target.value}),placeholder:o.name||"The Ultimate Listing Checklist"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Subheadline"}),e.jsx(xe,{value:o.public_subheadline,onChange:pe=>c({...o,public_subheadline:pe.target.value}),placeholder:"Everything top agents do before a listing goes live."})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Button text"}),e.jsx(xe,{value:o.public_cta_text,onChange:pe=>c({...o,public_cta_text:pe.target.value}),placeholder:"Get Instant Access"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Hero image URL (optional)"}),e.jsx(xe,{value:o.public_hero_image_url,onChange:pe=>c({...o,public_hero_image_url:pe.target.value}),placeholder:"Defaults to featured image"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Benefit bullets (one per line)"}),e.jsx("textarea",{value:o.public_benefits,onChange:pe=>c({...o,public_benefits:pe.target.value}),rows:4,placeholder:`Save hours on every listing Proven scripts included Printable + editable`,className:"w-full rounded-md border bg-background px-3 py-2 text-sm"})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(J,{children:"Resource Files"}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:G,children:[e.jsx(rn,{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((pe,Ce)=>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 ",Ce+1]}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>$(Ce),children:e.jsx(Qn,{className:"h-4 w-4"})})]}),e.jsx(xe,{placeholder:"File name (e.g., Getting Started Guide)",value:pe.name,onChange:Ae=>H(Ce,"name",Ae.target.value)}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xe,{type:"file",onChange:Ae=>ce(Ce,Ae),className:"flex-1"}),pe.file_url&&!pe.file&&e.jsx("a",{href:pe.file_url,target:"_blank",rel:"noopener noreferrer",className:"text-sm text-primary hover:underline whitespace-nowrap",children:"Current file"}),pe.file&&e.jsx("span",{className:"text-sm text-green-600 whitespace-nowrap",children:"New file selected"})]})]},Ce))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(J,{children:"Canva Links"}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:Y,children:[e.jsx(rn,{className:"h-4 w-4 mr-1"}),"Add Canva Link"]})]}),y.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:y.map((pe,Ce)=>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 ",Ce+1]}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>Z(Ce),children:e.jsx(Qn,{className:"h-4 w-4"})})]}),e.jsx(xe,{placeholder:"Link title (e.g., Social Media Post Template)",value:pe.title,onChange:Ae=>ne(Ce,"title",Ae.target.value)}),e.jsx(xe,{placeholder:"Canva share link (e.g., https://www.canva.com/design/...)",value:pe.canva_share_link,onChange:Ae=>ne(Ce,"canva_share_link",Ae.target.value)})]},Ce))})]}),e.jsx(EVt,{selectedTemplateIds:g,onChange:b}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(B,{type:"submit",disabled:ie.isPending,children:ie.isPending?"Saving...":i?"Update":"Create"})]})]})]})}),e.jsx(Ls,{open:!!j,onOpenChange:()=>S(null),children:e.jsxs(Ps,{className:"max-w-lg",children:[e.jsx(Os,{children:e.jsx(Ds,{children:j==null?void 0:j.name})}),e.jsxs("div",{className:"space-y-4",children:[(j==null?void 0:j.featured_image_url)&&e.jsx("img",{src:j.featured_image_url,alt:j.name,className:"w-full h-48 object-cover rounded-lg"}),(j==null?void 0:j.description)&&e.jsx("p",{className:"text-muted-foreground",children:j.description}),e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2",children:["Resource Files (",((be=j==null?void 0:j.files)==null?void 0:be.length)||0,")"]}),((me=j==null?void 0:j.files)==null?void 0:me.length)===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No files in this kit"}):e.jsx("div",{className:"space-y-2",children:(he=j==null?void 0:j.files)==null?void 0:he.map(pe=>e.jsxs("a",{href:pe.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(Fr,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm",children:pe.name})]},pe.id))})]}),(j==null?void 0:j.links)&&j.links.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2",children:["Canva Links (",j.links.length,")"]}),e.jsx("div",{className:"space-y-2",children:j.links.map(pe=>e.jsxs("a",{href:pe.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(Vc,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm",children:pe.title})]},pe.id))})]})]})]})})]})})}const don=()=>{const{user:s}=hs(),{toast:t}=vi(),n=Bt(),[r,a]=_.useState(!1),[i,l]=_.useState(null),[o,c]=_.useState({title:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,links:[{title:"",canva_share_link:"",sort_order:0}]}),[d,u]=_.useState(null),[h,m]=_.useState(""),{data:p=[],isLoading:f}=at({queryKey:["social-swag-admin"],queryFn:async()=>{const{data:M,error:I}=await q.from("social_swag").select("*").order("publish_date",{ascending:!1});if(I)throw I;const{data:D,error:O}=await q.from("social_swag_links").select("*").order("sort_order");if(O)throw O;return M.map(G=>({...G,links:(D==null?void 0:D.filter($=>$.swag_id===G.id))||[]}))}}),y=mt({mutationFn:async M=>{let I=M.existingImageUrl;if(M.image){const H=M.image.name.split(".").pop(),Y=`${Date.now()}-${Math.random().toString(36).substring(7)}.${H}`,{error:Z}=await q.storage.from("template-previews").upload(Y,M.image);if(Z)throw Z;const{data:ne}=q.storage.from("template-previews").getPublicUrl(Y);I=ne.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 O=M.itemId;const V=!O,G=(i==null?void 0:i.is_published)||!1;if(O){const{error:H}=await q.from("social_swag").update(D).eq("id",O);if(H)throw H;await q.from("social_swag_links").delete().eq("swag_id",O)}else{const{data:H,error:Y}=await q.from("social_swag").insert(D).select().single();if(Y)throw Y;O=H.id}const $=M.item.links.filter(H=>H.title.trim()&&H.canva_share_link.trim());if($.length>0){const H=$.map((Z,ne)=>({swag_id:O,title:Z.title.trim(),canva_share_link:Z.canva_share_link.trim(),sort_order:ne})),{error:Y}=await q.from("social_swag_links").insert(H);if(Y)throw Y}return{itemId:O,itemTitle:M.item.title,isNewItem:V,wasPublished:G,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)&&AHe(M.itemTitle,M.itemId),a(!1),g()},onError:M=>{t({title:"Error saving item",description:M.message,variant:"destructive"})}}),v=mt({mutationFn:async M=>{const{error:I}=await q.from("social_swag").delete().eq("id",M);if(I)throw I},onSuccess:()=>{n.invalidateQueries({queryKey:["social-swag-admin"]}),n.invalidateQueries({queryKey:["social-swag"]}),t({title:"Item deleted"})},onError:M=>{t({title:"Error deleting item",description:M.message,variant:"destructive"})}}),g=()=>{c({title:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,links:[{title:"",canva_share_link:"",sort_order:0}]}),u(null),m(""),l(null)},b=M=>{l(M),c({title:M.title,description:M.description||"",publish_date:M.publish_date?new Date(M.publish_date).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],is_published:M.is_published,links:M.links&&M.links.length>0?M.links.map(I=>({id:I.id,title:I.title,canva_share_link:I.canva_share_link,sort_order:I.sort_order})):[{title:"",canva_share_link:"",sort_order:0}]}),m(M.preview_image_url||""),a(!0)},j=M=>{var D;const I=(D=M.target.files)==null?void 0:D[0];I&&(u(I),m(URL.createObjectURL(I)))},S=()=>{c({...o,links:[...o.links,{title:"",canva_share_link:"",sort_order:o.links.length}]})},C=M=>{if(o.links.length<=1)return;const I=o.links.filter((D,O)=>O!==M);c({...o,links:I})},E=(M,I,D)=>{const O=[...o.links];O[M]={...O[M],[I]:D},c({...o,links:O})},P=M=>{if(M.preventDefault(),!o.title.trim()){t({title:"Title is required",variant:"destructive"});return}y.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(zs,{title:"Manage Social Swag",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Wh,{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(ve,{children:[e.jsx(bt,{className:"pb-2",children:e.jsx(St,{className:"text-sm font-medium text-muted-foreground",children:"Total Items"})}),e.jsx(Me,{children:e.jsx("div",{className:"text-2xl font-bold",children:p.length})})]}),e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-2",children:e.jsx(St,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Me,{children:e.jsx("div",{className:"text-2xl font-bold",children:p.filter(M=>M.is_published).length})})]})]}),e.jsxs(Ls,{open:r,onOpenChange:M=>{a(M),M||g()},children:[e.jsx(nl,{asChild:!0,children:e.jsxs(B,{className:"gap-2",children:[e.jsx(rn,{className:"h-4 w-4"}),"Add Item"]})}),e.jsxs(Ps,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Ds,{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(J,{htmlFor:"title",children:"Title *"}),e.jsx(xe,{id:"title",value:o.title,onChange:M=>c({...o,title:M.target.value}),placeholder:"Enter title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Description"}),e.jsx(BN,{content:o.description,onChange:M=>c({...o,description:M}),placeholder:"Enter description",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(xe,{id:"publish_date",type:"date",value:o.publish_date,onChange:M=>c({...o,publish_date:M.target.value})})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(fn,{id:"is_published",checked:o.is_published,onCheckedChange:M=>c({...o,is_published:M})}),e.jsx(J,{htmlFor:"is_published",children:"Published"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{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(B,{type:"button",variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-6 w-6",onClick:()=>{u(null),m("")},children:e.jsx(Qn,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-4 text-center",children:[e.jsx(hc,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx(xe,{type:"file",accept:"image/*",onChange:j,className:"cursor-pointer"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(J,{children:"Canva Links"}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:S,children:[e.jsx(rn,{className:"h-3 w-3 mr-1"}),"Add Link"]})]}),o.links.map((M,I)=>e.jsx(ve,{children:e.jsxs(Me,{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(B,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>C(I),children:e.jsx(Qn,{className:"h-3 w-3"})})]}),e.jsx(xe,{placeholder:"Link title (e.g., Instagram Post)",value:M.title,onChange:D=>E(I,"title",D.target.value)}),e.jsx(xe,{placeholder:"Canva share link",value:M.canva_share_link,onChange:D=>E(I,"canva_share_link",D.target.value)})]})},I))]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(B,{type:"submit",disabled:y.isPending,children:y.isPending?"Saving...":i?"Update":"Create"})]})]})]})]})]}),e.jsx(ve,{children:e.jsx(Me,{className:"p-0",children:f?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):p.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:'No items yet. Click "Add Item" to create your first one.'}):e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{className:"w-16",children:"Preview"}),e.jsx(Pt,{children:"Title"}),e.jsx(Pt,{children:"Links"}),e.jsx(Pt,{children:"Publish Date"}),e.jsx(Pt,{children:"Status"}),e.jsx(Pt,{className:"text-right",children:"Actions"})]})}),e.jsx(Ka,{children:p.map(M=>{var I;return e.jsxs(pn,{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(hc,{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(Oe,{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(B,{variant:"ghost",size:"icon",onClick:()=>window.open(`/social-swag/${M.id}`,"_blank"),children:e.jsx(ya,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>b(M),children:e.jsx(Ya,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:async()=>{await Xi("Are you sure you want to delete this item?")&&v.mutate(M.id)},children:e.jsx(Sn,{className:"h-4 w-4"})})]})})]},M.id)})})]})})})]})})};function uon({item:s,onEdit:t,onDelete:n,onDateChange:r}){const{attributes:a,listeners:i,setNodeRef:l,transform:o,transition:c,isDragging:d}=rLe({id:s.id}),u={transform:OP.Transform.toString(o),transition:c,opacity:d?.5:1,zIndex:d?10:void 0};return e.jsx("div",{ref:l,style:u,children:e.jsxs(ve,{className:"overflow-hidden",children:[e.jsxs("div",{...a,...i,className:"flex items-center justify-center gap-1 py-1.5 bg-muted hover:bg-muted/80 cursor-grab active:cursor-grabbing border-b select-none",title:"Drag to reorder",children:[e.jsx(Vf,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-[10px] text-muted-foreground font-medium",children:"Drag to reorder"})]}),e.jsxs("div",{className:"relative aspect-[4/5]",children:[e.jsx("img",{src:s.image_url,alt:"Social swag",className:"w-full h-full object-cover",loading:"lazy",decoding:"async"}),e.jsxs("div",{className:"absolute top-2 right-2 flex gap-1",children:[e.jsx(B,{variant:"secondary",size:"icon",className:"h-7 w-7 bg-black/50 hover:bg-black/70 border-0 text-white",onClick:()=>t(s),children:e.jsx(Ya,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"destructive",size:"icon",className:"h-7 w-7",onClick:()=>n(s),children:e.jsx(Sn,{className:"h-3.5 w-3.5"})})]}),s.post_date&&e.jsx("div",{className:"absolute bottom-2 left-2",children:e.jsxs(Oe,{className:"bg-primary/90 text-primary-foreground text-[10px] gap-1 backdrop-blur-sm px-1.5 py-0.5",children:[e.jsx(ga,{className:"h-2.5 w-2.5"}),Hs(new Date(s.post_date+"T00:00:00"),"MMM d")]})})]}),e.jsxs(Me,{className:"p-3 space-y-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-3",children:s.caption}),e.jsxs(od,{children:[e.jsx(ld,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:At("w-full h-7 text-[11px] gap-1 justify-start font-normal",!s.post_date&&"text-muted-foreground"),children:[e.jsx(ga,{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(Qc,{className:"w-auto p-0",align:"start",children:[e.jsx(Pj,{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(B,{variant:"ghost",size:"sm",className:"w-full text-xs text-muted-foreground",onClick:()=>r(s.id,null),children:"Clear date"})})]})]})]})]})})}const hon=()=>{const s=Bt(),[t,n]=_.useState("all"),[r,a]=_.useState(!1),[i,l]=_.useState(Hs(new Date,"yyyy-MM")),[o,c]=_.useState([]),[d,u]=_.useState(!1),[h,m]=_.useState(null),[p,f]=_.useState(null),[y,v]=_.useState(""),[g,b]=_.useState(null),[j,S]=_.useState(!1),[C,E]=_.useState(!1),[P,M]=_.useState(Hs(new Date,"yyyy-MM")),[I,D]=_.useState(null),[O,V]=_.useState(""),[G,$]=_.useState(""),[H,Y]=_.useState(""),[Z,ne]=_.useState(!1),ce=YPe(IH(yW,{activationConstraint:{distance:5}}),IH(QPe,{coordinateGetter:tzt})),{data:ie=[],isLoading:te}=at({queryKey:["admin-social-swag-2"],queryFn:async()=>{const{data:nt,error:$e}=await q.from("social_swag_2").select("*").order("month",{ascending:!1}).order("sort_order");if($e)throw $e;return nt}}),{data:ae=[]}=at({queryKey:["admin-social-swag-2-months"],queryFn:async()=>{const{data:nt,error:$e}=await q.from("social_swag_2_months").select("*").order("month",{ascending:!1});if($e)throw $e;return nt}}),{data:le=[]}=at({queryKey:["admin-social-swag-2-reels"],queryFn:async()=>{const{data:nt,error:$e}=await q.from("social_swag_2_reels").select("*").order("month",{ascending:!1});if($e)throw $e;return nt}}),be=[...new Set(ie.map(nt=>nt.month))].sort((nt,$e)=>$e.localeCompare(nt)),me=t==="all"?ie:ie.filter(nt=>nt.month===t),he=nt=>{const $e=YQe(nt,"yyyy-MM",new Date);return Hs($e,"MMMM yyyy")},pe=nt=>{f(nt),v(nt.caption),b(nt.post_date)},Ce=async()=>{if(p){S(!0);try{const{error:nt}=await q.from("social_swag_2").update({caption:y,post_date:g}).eq("id",p.id);if(nt)throw nt;se.success("Image updated"),f(null),s.invalidateQueries({queryKey:["admin-social-swag-2"]}),s.invalidateQueries({queryKey:["social-swag-2"]})}catch{se.error("Failed to update image")}finally{S(!1)}}},Ae=async nt=>{const{active:$e,over:Ge}=nt;if(!Ge||$e.id===Ge.id)return;const ct=me,xt=ct.findIndex(Xt=>Xt.id===$e.id),qt=ct.findIndex(Xt=>Xt.id===Ge.id);if(xt===-1||qt===-1)return;const Vt=sLe(ct,xt,qt);s.setQueryData(["admin-social-swag-2"],Xt=>{if(!Xt)return Xt;const fs={};return Vt.forEach((Ft,wt)=>{fs[Ft.id]=wt}),Xt.map(Ft=>fs[Ft.id]!==void 0?{...Ft,sort_order:fs[Ft.id]}:Ft).sort((Ft,wt)=>Ft.month!==wt.month?wt.month.localeCompare(Ft.month):Ft.sort_order-wt.sort_order)});try{await Promise.all(Vt.map((Xt,fs)=>q.from("social_swag_2").update({sort_order:fs}).eq("id",Xt.id)))}catch{se.error("Failed to save order"),s.invalidateQueries({queryKey:["admin-social-swag-2"]})}},Pe=nt=>{const Ge=Array.from(nt.target.files||[]).sort((ct,xt)=>ct.name.localeCompare(xt.name,void 0,{numeric:!0,sensitivity:"base"})).slice(0,16-o.length).map(ct=>({file:ct,preview:URL.createObjectURL(ct),caption:""}));c(ct=>[...ct,...Ge].slice(0,16))},ze=nt=>{c($e=>{const Ge=[...$e];return URL.revokeObjectURL(Ge[nt].preview),Ge.splice(nt,1),Ge})},ke=(nt,$e)=>{c(Ge=>{const ct=[...Ge];return ct[nt]={...ct[nt],caption:$e},ct})},Ze=async()=>{var $e;if(o.length===0){se.error("Please add at least one image");return}if(o.filter(Ge=>!Ge.caption.trim()).length>0){se.error("Please add captions to all images");return}u(!0);try{const{data:Ge}=await q.from("social_swag_2").select("sort_order").eq("month",i).order("sort_order",{ascending:!1}).limit(1),ct=((($e=Ge==null?void 0:Ge[0])==null?void 0:$e.sort_order)??-1)+1;for(let xt=0;xt{const $e=nt.image_url.split("/social-swag-2/");$e[1]&&await q.storage.from("social-swag-2").remove([$e[1]]);const{error:Ge}=await q.from("social_swag_2").delete().eq("id",nt.id);if(Ge)throw Ge},onSuccess:()=>{se.success("Image deleted"),s.invalidateQueries({queryKey:["admin-social-swag-2"]})},onError:()=>se.error("Failed to delete image")}),Fe=mt({mutationFn:async({id:nt,postDate:$e})=>{const{error:Ge}=await q.from("social_swag_2").update({post_date:$e}).eq("id",nt);if(Ge)throw Ge},onSuccess:()=>{se.success("Post date updated"),s.invalidateQueries({queryKey:["admin-social-swag-2"]}),s.invalidateQueries({queryKey:["social-swag-2"]})},onError:()=>se.error("Failed to update post date")}),Ne=mt({mutationFn:async({month:nt,link:$e})=>{const{error:Ge}=await q.from("social_swag_2_months").upsert({month:nt,canva_link:$e||null},{onConflict:"month"});if(Ge)throw Ge},onSuccess:()=>{se.success("Canva link updated"),m(null),s.invalidateQueries({queryKey:["admin-social-swag-2-months"]})},onError:()=>se.error("Failed to update Canva link")}),Ye=nt=>{var $e;return(($e=ae.find(Ge=>Ge.month===nt))==null?void 0:$e.canva_link)||""},Ve=nt=>le.find($e=>$e.month===nt)||null,qe=nt=>{var Ge;const $e=(Ge=nt.target.files)==null?void 0:Ge[0];$e&&(D($e),V(URL.createObjectURL($e)))},Qe=()=>{O&&URL.revokeObjectURL(O),D(null),V(""),$(""),Y("")},Ue=async()=>{if(!I){se.error("Please select an image");return}ne(!0);try{const nt=I.name.split(".").pop(),$e=`reels/${P}-${Date.now()}.${nt}`,{error:Ge}=await q.storage.from("social-swag-2").upload($e,I);if(Ge)throw Ge;const{data:{publicUrl:ct}}=q.storage.from("social-swag-2").getPublicUrl($e),{error:xt}=await q.from("social_swag_2_reels").upsert({month:P,image_url:ct,canva_link:H||null,caption:G||null},{onConflict:"month"});if(xt)throw xt;se.success("Reel uploaded successfully!"),AHe(`${he(P)} Reel`,"social-swag-2"),Qe(),E(!1),s.invalidateQueries({queryKey:["admin-social-swag-2-reels"]})}catch(nt){console.error("Reel upload error:",nt),se.error("Failed to upload reel")}finally{ne(!1)}},Xe=mt({mutationFn:async nt=>{const $e=nt.image_url.split("/social-swag-2/");$e[1]&&await q.storage.from("social-swag-2").remove([$e[1]]);const{error:Ge}=await q.from("social_swag_2_reels").delete().eq("id",nt.id);if(Ge)throw Ge},onSuccess:()=>{se.success("Reel deleted"),s.invalidateQueries({queryKey:["admin-social-swag-2-reels"]})},onError:()=>se.error("Failed to delete reel")});return e.jsxs(zs,{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(Ls,{open:r,onOpenChange:a,children:[e.jsx(nl,{asChild:!0,children:e.jsxs(B,{className:"gap-2",children:[e.jsx(rn,{className:"h-4 w-4"}),"Upload Images"]})}),e.jsxs(Ps,{className:"max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Ds,{children:"Upload Social Swag Images"})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Month"}),e.jsx(xe,{type:"month",value:i,onChange:nt=>l(nt.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(J,{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:Pe,className:"hidden",id:"swag-upload",disabled:o.length>=16}),e.jsxs("label",{htmlFor:"swag-upload",className:"cursor-pointer",children:[e.jsx(Oa,{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((nt,$e)=>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:nt.preview,alt:`Upload ${$e+1}`,className:"w-full h-full object-cover"}),e.jsx(B,{variant:"destructive",size:"icon",className:"absolute top-1 right-1 h-6 w-6",onClick:()=>ze($e),children:e.jsx(Qn,{className:"h-3 w-3"})})]}),e.jsx(Ms,{placeholder:"Caption...",value:nt.caption,onChange:Ge=>ke($e,Ge.target.value),className:"text-xs h-20"})]},$e))}),e.jsx(B,{onClick:Ze,disabled:d||o.length===0,className:"w-full gap-2",children:d?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"h-4 w-4 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Oa,{className:"h-4 w-4"}),"Upload ",o.length," Images"]})})]})]})]}),e.jsxs(Ls,{open:C,onOpenChange:nt=>{E(nt),nt||Qe()},children:[e.jsx(nl,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:"gap-2",children:[e.jsx(dm,{className:"h-4 w-4"}),"Upload Reel"]})}),e.jsxs(Ps,{className:"max-w-lg max-h-[85vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Ds,{children:"Upload Monthly Reel"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Month"}),e.jsx(xe,{type:"month",value:P,onChange:nt=>M(nt.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Reel Preview Image"}),O?e.jsxs("div",{className:"relative aspect-[9/16] max-w-[120px] mx-auto rounded-lg overflow-hidden bg-muted",children:[e.jsx("img",{src:O,alt:"Reel preview",className:"w-full h-full object-cover"}),e.jsx(B,{variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-6 w-6",onClick:()=>{URL.revokeObjectURL(O),D(null),V("")},children:e.jsx(Qn,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-6 text-center",children:[e.jsx("input",{type:"file",accept:"image/*",onChange:qe,className:"hidden",id:"reel-upload"}),e.jsxs("label",{htmlFor:"reel-upload",className:"cursor-pointer",children:[e.jsx(dm,{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(J,{children:"Canva Download Link"}),e.jsx(xe,{value:H,onChange:nt=>Y(nt.target.value),placeholder:"https://www.canva.com/..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Caption"}),e.jsx(Ms,{value:G,onChange:nt=>$(nt.target.value),placeholder:"Enter caption for this reel...",className:"h-24"})]}),e.jsx(B,{onClick:Ue,disabled:Z||!I,className:"w-full gap-2",children:Z?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"h-4 w-4 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Oa,{className:"h-4 w-4"}),"Upload Reel"]})})]})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(ve,{children:e.jsxs(Me,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:ie.length}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Total Images"})]})}),e.jsx(ve,{children:e.jsxs(Me,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:be.length}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Months"})]})})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(Yr,{value:t,onValueChange:n,children:e.jsxs(Zr,{children:[e.jsx(Ht,{value:"all",children:"All"}),be.map(nt=>e.jsx(Ht,{value:nt,children:he(nt)},nt))]})}),t!=="all"&&e.jsx(ve,{children:e.jsx(Me,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(Vc,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs(J,{className:"text-sm text-muted-foreground",children:["Canva Edit Link for ",he(t)]}),(h==null?void 0:h.month)===t?e.jsxs("div",{className:"flex gap-2 mt-1",children:[e.jsx(xe,{value:h.link,onChange:nt=>m({...h,link:nt.target.value}),placeholder:"https://www.canva.com/..."}),e.jsx(B,{size:"sm",onClick:()=>Ne.mutate(h),children:"Save"}),e.jsx(B,{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:Ye(t)||"No link set"}),e.jsx(B,{size:"sm",variant:"outline",onClick:()=>m({month:t,link:Ye(t)}),children:"Edit"})]})]})]})})}),t!=="all"&&e.jsx(ve,{children:e.jsx(Me,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx(dm,{className:"h-4 w-4 text-muted-foreground mt-1"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs(J,{className:"text-sm text-muted-foreground",children:["Reel for ",he(t)]}),(()=>{const nt=Ve(t);return nt?e.jsxs("div",{className:"flex items-center gap-4 mt-2",children:[e.jsx("img",{src:nt.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:nt.caption||"No caption"}),nt.canva_link&&e.jsx("a",{href:nt.canva_link,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline text-xs",children:"View Canva Link"})]}),e.jsx(B,{variant:"destructive",size:"sm",onClick:()=>Xe.mutate(nt),children:e.jsx(Sn,{className:"h-4 w-4"})})]}):e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"No reel uploaded for this month"})})()]})]})})})]}),te?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading..."}):me.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(hc,{className:"h-12 w-12 mx-auto text-muted-foreground/50 mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"No images yet. Upload some!"})]}):e.jsx(tLe,{sensors:ce,collisionDetection:ZPe,onDragEnd:Ae,children:e.jsx(nLe,{items:me.map(nt=>nt.id),strategy:rae,children:e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4",children:me.map(nt=>e.jsx(uon,{item:nt,onEdit:pe,onDelete:$e=>Se.mutate($e),onDateChange:($e,Ge)=>Fe.mutate({id:$e,postDate:Ge})},nt.id))})})})]}),e.jsx(Ls,{open:!!p,onOpenChange:nt=>{nt||f(null)},children:e.jsxs(Ps,{className:"max-w-md",children:[e.jsx(Os,{children:e.jsx(Ds,{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(J,{children:"Caption"}),e.jsx(Ms,{value:y,onChange:nt=>v(nt.target.value),placeholder:"Enter caption...",className:"h-28"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Post Date"}),e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsxs(od,{children:[e.jsx(ld,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:At("flex-1 justify-start gap-2 font-normal",!g&&"text-muted-foreground"),children:[e.jsx(ga,{className:"h-4 w-4"}),g?Hs(new Date(g+"T00:00:00"),"MMM d, yyyy"):"Pick a date"]})}),e.jsx(Qc,{className:"w-auto p-0",align:"start",children:e.jsx(Pj,{mode:"single",selected:g?new Date(g+"T00:00:00"):void 0,onSelect:nt=>b(nt?Hs(nt,"yyyy-MM-dd"):null),className:"p-3 pointer-events-auto"})})]}),g&&e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>b(null),children:e.jsx(Qn,{className:"h-4 w-4"})})]})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>f(null),children:"Cancel"}),e.jsx(B,{onClick:Ce,disabled:j,className:"gap-2",children:j?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"h-4 w-4 animate-spin"}),"Saving..."]}):"Save Changes"})]})]})})]})},mon=()=>{const{toast:s}=vi(),t=Bt(),[n,r]=_.useState("categories"),[a,i]=_.useState(!1),[l,o]=_.useState(null),[c,d]=_.useState({name:"",description:"",icon:""}),[u,h]=_.useState(!1),[m,p]=_.useState(null),[f,y]=_.useState({name:"",description:"",icon:""}),[v,g]=_.useState(!1),[b,j]=_.useState(null),[S,C]=_.useState(""),{data:E=[],isLoading:P}=at({queryKey:["admin-community-categories"],queryFn:async()=>{const{data:Ae,error:Pe}=await q.from("community_categories").select("*").order("sort_order");if(Pe)throw Pe;return Ae}}),{data:M=[],isLoading:I}=at({queryKey:["admin-private-groups"],queryFn:async()=>{const{data:Ae,error:Pe}=await q.from("community_private_groups").select("*").order("sort_order");if(Pe)throw Pe;return Ae}}),{data:D=[]}=at({queryKey:["admin-group-members",b==null?void 0:b.id],queryFn:async()=>{if(!b)return[];const{data:Ae,error:Pe}=await q.from("community_private_group_members").select("*").eq("group_id",b.id);if(Pe)throw Pe;return Ae},enabled:!!b}),{data:O=[]}=at({queryKey:["admin-all-profiles"],queryFn:async()=>{let Pe=[],ze=0,ke=!0;for(;ke;){const{data:Ze,error:Se}=await q.from("profiles").select("id, name, email, brokerage_id").order("name").range(ze,ze+1e3-1);if(Se)throw Se;Ze&&Ze.length>0?(Pe=[...Pe,...Ze],ze+=1e3,ke=Ze.length===1e3):ke=!1}return Pe}}),{data:V=[]}=at({queryKey:["admin-all-brokerages"],queryFn:async()=>{const{data:Ae,error:Pe}=await q.from("brokerages").select("*").order("name");if(Pe)throw Pe;return Ae}}),G=mt({mutationFn:async Ae=>{if(Ae.id){const{error:Pe}=await q.from("community_categories").update({name:Ae.name,description:Ae.description||null,icon:Ae.icon||null}).eq("id",Ae.id);if(Pe)throw Pe}else{const Pe=Math.max(...E.map(ke=>ke.sort_order),0),{error:ze}=await q.from("community_categories").insert({name:Ae.name,description:Ae.description||null,icon:Ae.icon||null,sort_order:Pe+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:Ae=>{s({title:"Error",description:Ae.message,variant:"destructive"})}}),$=mt({mutationFn:async Ae=>{const{error:Pe}=await q.from("community_categories").delete().eq("id",Ae);if(Pe)throw Pe},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-community-categories"]}),s({title:"Category deleted"})}}),H=mt({mutationFn:async({id:Ae,direction:Pe})=>{const ze=E.findIndex(ke=>ke.id===Ae);if(Pe==="up"&&ze>0){const ke=E[ze-1],Ze=E[ze];await q.from("community_categories").update({sort_order:Ze.sort_order}).eq("id",ke.id),await q.from("community_categories").update({sort_order:ke.sort_order}).eq("id",Ze.id)}else if(Pe==="down"&&zet.invalidateQueries({queryKey:["admin-community-categories"]})}),Y=mt({mutationFn:async Ae=>{if(Ae.id){const{error:Pe}=await q.from("community_private_groups").update({name:Ae.name,description:Ae.description||null,icon:Ae.icon||null}).eq("id",Ae.id);if(Pe)throw Pe}else{const Pe=Math.max(...M.map(ke=>ke.sort_order),0),{error:ze}=await q.from("community_private_groups").insert({name:Ae.name,description:Ae.description||null,icon:Ae.icon||null,sort_order:Pe+1});if(ze)throw ze}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-private-groups"]}),h(!1),p(null),y({name:"",description:"",icon:""}),s({title:m?"Private group updated!":"Private group created!"})},onError:Ae=>{s({title:"Error",description:Ae.message,variant:"destructive"})}}),Z=mt({mutationFn:async Ae=>{const{error:Pe}=await q.from("community_private_groups").delete().eq("id",Ae);if(Pe)throw Pe},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-private-groups"]}),s({title:"Private group deleted"})}}),ne=mt({mutationFn:async({id:Ae,direction:Pe})=>{const ze=M.findIndex(ke=>ke.id===Ae);if(Pe==="up"&&ze>0){const ke=M[ze-1],Ze=M[ze];await q.from("community_private_groups").update({sort_order:Ze.sort_order}).eq("id",ke.id),await q.from("community_private_groups").update({sort_order:ke.sort_order}).eq("id",Ze.id)}else if(Pe==="down"&&zet.invalidateQueries({queryKey:["admin-private-groups"]})}),ce=mt({mutationFn:async({groupId:Ae,userId:Pe,isMember:ze})=>{if(ze){const{error:ke}=await q.from("community_private_group_members").delete().eq("group_id",Ae).eq("user_id",Pe);if(ke)throw ke}else{const{error:ke}=await q.from("community_private_group_members").insert({group_id:Ae,user_id:Pe});if(ke)throw ke}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-group-members",b==null?void 0:b.id]})}}),ie=mt({mutationFn:async({groupId:Ae,brokerageId:Pe,isMember:ze})=>{if(ze){const{error:ke}=await q.from("community_private_group_members").delete().eq("group_id",Ae).eq("brokerage_id",Pe);if(ke)throw ke}else{const{error:ke}=await q.from("community_private_group_members").insert({group_id:Ae,brokerage_id:Pe});if(ke)throw ke}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-group-members",b==null?void 0:b.id]})}}),te=Ae=>{o(Ae),d({name:Ae.name,description:Ae.description||"",icon:Ae.icon||""}),i(!0)},ae=()=>{o(null),d({name:"",description:"",icon:""}),i(!0)},le=Ae=>{p(Ae),y({name:Ae.name,description:Ae.description||"",icon:Ae.icon||""}),h(!0)},be=()=>{p(null),y({name:"",description:"",icon:""}),h(!0)},me=Ae=>{j(Ae),C(""),g(!0)},he=Ae=>D.some(Pe=>Pe.user_id===Ae),pe=Ae=>D.some(Pe=>Pe.brokerage_id===Ae),Ce=O.filter(Ae=>Ae.name.toLowerCase().includes(S.toLowerCase())||Ae.email.toLowerCase().includes(S.toLowerCase()));return e.jsx(zs,{title:"Community Management",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Wh,{title:"Community Management",description:"Manage categories and private groups for community discussions"}),e.jsxs(Yr,{value:n,onValueChange:r,children:[e.jsxs(Zr,{children:[e.jsx(Ht,{value:"categories",children:"Public Categories"}),e.jsxs(Ht,{value:"private-groups",children:[e.jsx(ec,{className:"h-4 w-4 mr-1"}),"Private Groups"]})]}),e.jsxs(Gt,{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(B,{onClick:ae,children:[e.jsx(rn,{className:"h-4 w-4 mr-2"}),"Add Category"]})]}),e.jsx(ve,{children:e.jsx(Me,{className:"pt-6",children:e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{className:"w-[50px]",children:"Order"}),e.jsx(Pt,{className:"w-[80px]",children:"Icon"}),e.jsx(Pt,{children:"Name"}),e.jsx(Pt,{children:"Description"}),e.jsx(Pt,{className:"w-[100px]",children:"Actions"})]})}),e.jsx(Ka,{children:P?e.jsx(pn,{children:e.jsx(gt,{colSpan:5,className:"text-center py-8",children:"Loading..."})}):E.length===0?e.jsx(pn,{children:e.jsx(gt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No categories yet. Create your first one!"})}):E.map((Ae,Pe)=>e.jsxs(pn,{children:[e.jsx(gt,{children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:Pe===0,onClick:()=>H.mutate({id:Ae.id,direction:"up"}),children:"↑"}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:Pe===E.length-1,onClick:()=>H.mutate({id:Ae.id,direction:"down"}),children:"↓"})]})}),e.jsx(gt,{className:"text-2xl",children:Ae.icon||"📁"}),e.jsx(gt,{className:"font-medium",children:Ae.name}),e.jsx(gt,{className:"text-muted-foreground",children:Ae.description||"—"}),e.jsx(gt,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>te(Ae),children:e.jsx(Ya,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive",onClick:async()=>{await Xi("Delete this category? Posts will be uncategorized.")&&$.mutate(Ae.id)},children:e.jsx(Sn,{className:"h-4 w-4"})})]})})]},Ae.id))})]})})})]}),e.jsxs(Gt,{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(B,{onClick:be,children:[e.jsx(rn,{className:"h-4 w-4 mr-2"}),"Add Private Group"]})]}),e.jsx(ve,{children:e.jsx(Me,{className:"pt-6",children:e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{className:"w-[50px]",children:"Order"}),e.jsx(Pt,{className:"w-[80px]",children:"Icon"}),e.jsx(Pt,{children:"Name"}),e.jsx(Pt,{children:"Description"}),e.jsx(Pt,{className:"w-[120px]",children:"Members"}),e.jsx(Pt,{className:"w-[140px]",children:"Actions"})]})}),e.jsx(Ka,{children:I?e.jsx(pn,{children:e.jsx(gt,{colSpan:6,className:"text-center py-8",children:"Loading..."})}):M.length===0?e.jsx(pn,{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((Ae,Pe)=>e.jsxs(pn,{children:[e.jsx(gt,{children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:Pe===0,onClick:()=>ne.mutate({id:Ae.id,direction:"up"}),children:"↑"}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:Pe===M.length-1,onClick:()=>ne.mutate({id:Ae.id,direction:"down"}),children:"↓"})]})}),e.jsx(gt,{className:"text-2xl",children:Ae.icon||"🔒"}),e.jsx(gt,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[Ae.name,Ae.brokerage_id?e.jsxs(Oe,{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(Oe,{variant:"secondary",className:"text-xs",children:[e.jsx(ec,{className:"h-3 w-3 mr-1"}),"Private"]})]})}),e.jsx(gt,{className:"text-muted-foreground",children:Ae.description||"—"}),e.jsx(gt,{children:e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>me(Ae),children:[e.jsx(In,{className:"h-4 w-4 mr-1"}),"Manage"]})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex gap-1",children:[!Ae.brokerage_id&&e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>le(Ae),children:e.jsx(Ya,{className:"h-4 w-4"})}),!Ae.brokerage_id&&e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive",onClick:async()=>{await Xi("Delete this private group? All posts in this group will be deleted.")&&Z.mutate(Ae.id)},children:e.jsx(Sn,{className:"h-4 w-4"})}),Ae.brokerage_id&&e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"Managed via brokerage"})]})})]},Ae.id))})]})})})]})]}),e.jsx(Ls,{open:a,onOpenChange:i,children:e.jsxs(Ps,{children:[e.jsx(Os,{children:e.jsx(Ds,{children:l?"Edit Category":"Create Category"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Icon (emoji)"}),e.jsx(xe,{value:c.icon,onChange:Ae=>d(Pe=>({...Pe,icon:Ae.target.value})),placeholder:"💬",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Name *"}),e.jsx(xe,{value:c.name,onChange:Ae=>d(Pe=>({...Pe,name:Ae.target.value})),placeholder:"Category name",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Description"}),e.jsx(Ms,{value:c.description,onChange:Ae=>d(Pe=>({...Pe,description:Ae.target.value})),placeholder:"Brief description of this category",className:"mt-1"})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{variant:"outline",onClick:()=>i(!1),children:"Cancel"}),e.jsx(B,{onClick:()=>G.mutate({...c,id:l==null?void 0:l.id}),disabled:!c.name.trim(),children:l?"Save Changes":"Create Category"})]})]})]})}),e.jsx(Ls,{open:u,onOpenChange:h,children:e.jsxs(Ps,{children:[e.jsx(Os,{children:e.jsx(Ds,{children:m?"Edit Private Group":"Create Private Group"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Icon (emoji)"}),e.jsx(xe,{value:f.icon,onChange:Ae=>y(Pe=>({...Pe,icon:Ae.target.value})),placeholder:"🔒",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Name *"}),e.jsx(xe,{value:f.name,onChange:Ae=>y(Pe=>({...Pe,name:Ae.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(Ms,{value:f.description,onChange:Ae=>y(Pe=>({...Pe,description:Ae.target.value})),placeholder:"Brief description of this private group",className:"mt-1"})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{variant:"outline",onClick:()=>h(!1),children:"Cancel"}),e.jsx(B,{onClick:()=>Y.mutate({...f,id:m==null?void 0:m.id}),disabled:!f.name.trim(),children:m?"Save Changes":"Create Private Group"})]})]})]})}),e.jsx(Ls,{open:v,onOpenChange:g,children:e.jsxs(Ps,{className:"max-w-2xl",children:[e.jsx(Os,{children:e.jsxs(Ds,{children:["Manage Members: ",b==null?void 0:b.name]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs(Yr,{defaultValue:"brokerages",children:[e.jsxs(Zr,{className:"w-full",children:[e.jsx(Ht,{value:"brokerages",className:"flex-1",children:"By Brokerage"}),e.jsx(Ht,{value:"users",className:"flex-1",children:"Individual Users"})]}),e.jsxs(Gt,{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(Ji,{className:"h-[300px] border rounded-md p-4",children:e.jsxs("div",{className:"space-y-2",children:[V.map(Ae=>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($a,{checked:pe(Ae.id),onCheckedChange:()=>{b&&ie.mutate({groupId:b.id,brokerageId:Ae.id,isMember:pe(Ae.id)})}}),e.jsx("span",{className:"font-medium",children:Ae.name})]}),e.jsxs(Oe,{variant:"secondary",children:[O.filter(Pe=>Pe.brokerage_id===Ae.id).length," agents"]})]},Ae.id)),V.length===0&&e.jsx("p",{className:"text-center text-muted-foreground py-4",children:"No brokerages found"})]})})]}),e.jsxs(Gt,{value:"users",className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search users...",value:S,onChange:Ae=>C(Ae.target.value),className:"pl-9"})]}),e.jsx(Ji,{className:"h-[300px] border rounded-md p-4",children:e.jsxs("div",{className:"space-y-2",children:[Ce.map(Ae=>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($a,{checked:he(Ae.id),onCheckedChange:()=>{b&&ce.mutate({groupId:b.id,userId:Ae.id,isMember:he(Ae.id)})}}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Ae.name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:Ae.email})]})]})},Ae.id)),Ce.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(B,{onClick:()=>g(!1),children:"Done"})})]})]})})]})})},qvt=s=>{switch(s){case"academy_video":return e.jsx(Jd,{className:"h-3 w-3"});case"template":return e.jsx(Fr,{className:"h-3 w-3"});case"toolbox":return e.jsx(Nh,{className:"h-3 w-3"});case"newsletter":return e.jsx(mN,{className:"h-3 w-3"});case"social_swag":return e.jsx(un,{className:"h-3 w-3"});default:return e.jsx(wr,{className:"h-3 w-3"})}},pon=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}},fon=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}},xon=()=>{const{toast:s}=vi(),[t,n]=_.useState([]),[r,a]=_.useState([]),[i,l]=_.useState([]),[o,c]=_.useState(!0),[d,u]=_.useState(""),[h,m]=_.useState(null),[p,f]=_.useState([]),[y,v]=_.useState([]);_.useEffect(()=>{g()},[]);const g=async()=>{try{c(!0);const{data:D,error:O}=await q.from("activity_logs").select(` id, user_id, app_name, launched_at, profiles ( name, email, brokerages ( name ) ) `).order("launched_at",{ascending:!1}).limit(5e3);if(O)throw O;const{data:V,error:G}=await q.from("content_engagement_logs").select(` id, user_id, resource_type, resource_id, resource_title, action_type, created_at `).order("created_at",{ascending:!1}).limit(5e3);if(G)throw G;const $=[...new Set((V==null?void 0:V.map(te=>te.user_id))||[])],{data:H}=await q.from("profiles").select(` id, name, email, brokerages ( name ) `).in("id",$),Y=new Map((H==null?void 0:H.map(te=>[te.id,te]))||[]),Z=(D==null?void 0:D.map(te=>{var ae,le,be,me;return{id:te.id,user_id:te.user_id,app_name:te.app_name,launched_at:te.launched_at,user_name:((ae=te.profiles)==null?void 0:ae.name)||"Unknown",user_email:((le=te.profiles)==null?void 0:le.email)||"Unknown",brokerage_name:((me=(be=te.profiles)==null?void 0:be.brokerages)==null?void 0:me.name)||null}}))||[],ne=(V==null?void 0:V.map(te=>{var le;const ae=Y.get(te.user_id);return{id:te.id,user_id:te.user_id,resource_type:te.resource_type,resource_id:te.resource_id,resource_title:te.resource_title,action_type:te.action_type,created_at:te.created_at,user_name:(ae==null?void 0:ae.name)||"Unknown",user_email:(ae==null?void 0:ae.email)||"Unknown",brokerage_name:((le=ae==null?void 0:ae.brokerages)==null?void 0:le.name)||null}}))||[];n(Z),a(ne);const ce=new Map;Z.forEach(te=>{if(!ce.has(te.user_id))ce.set(te.user_id,{user_id:te.user_id,user_name:te.user_name,user_email:te.user_email,brokerage_name:te.brokerage_name,last_activity_type:"app",last_activity_name:te.app_name,last_activity_at:te.launched_at,total_app_launches:1,total_content_views:0});else{const ae=ce.get(te.user_id);ae.total_app_launches++,new Date(te.launched_at)>new Date(ae.last_activity_at)&&(ae.last_activity_type="app",ae.last_activity_name=te.app_name,ae.last_activity_at=te.launched_at)}}),ne.forEach(te=>{if(!ce.has(te.user_id))ce.set(te.user_id,{user_id:te.user_id,user_name:te.user_name,user_email:te.user_email,brokerage_name:te.brokerage_name,last_activity_type:te.resource_type,last_activity_name:te.resource_title,last_activity_at:te.created_at,total_app_launches:0,total_content_views:1});else{const ae=ce.get(te.user_id);ae.total_content_views++,new Date(te.created_at)>new Date(ae.last_activity_at)&&(ae.last_activity_type=te.resource_type,ae.last_activity_name=te.resource_title,ae.last_activity_at=te.created_at)}});const ie=Array.from(ce.values()).sort((te,ae)=>new Date(ae.last_activity_at).getTime()-new Date(te.last_activity_at).getTime());l(ie)}catch(D){console.error("Error loading activity:",D),s({title:"Error",description:"Failed to load activity logs",variant:"destructive"})}finally{c(!1)}},b=D=>{m({id:D.user_id,name:D.user_name,email:D.user_email});const O=t.filter(G=>G.user_id===D.user_id),V=r.filter(G=>G.user_id===D.user_id);f(O),v(V)},j=()=>{m(null),f([]),v([])},{sortKey:S,sortDirection:C,handleSort:E,sortData:P}=wae("last_activity_at","desc"),M=i.filter(D=>{var V;if(!d)return!0;const O=d.toLowerCase();return D.user_name.toLowerCase().includes(O)||D.user_email.toLowerCase().includes(O)||((V=D.brokerage_name)==null?void 0:V.toLowerCase().includes(O))}),I=P(M,{user:D=>{var O;return((O=D.user_name)==null?void 0:O.toLowerCase())||""},brokerage:D=>{var O;return((O=D.brokerage_name)==null?void 0:O.toLowerCase())||""},last_activity_at:D=>new Date(D.last_activity_at).getTime(),apps:D=>D.total_app_launches,content:D=>D.total_content_views});return o?e.jsx(ve,{children:e.jsx(Me,{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(ve,{children:[e.jsxs(bt,{children:[e.jsx(St,{children:"User Activity"}),e.jsx(kn,{children:"App launches and content engagement - click to see full history"})]}),e.jsxs(Me,{children:[e.jsx("div",{className:"mb-4",children:e.jsxs("div",{className:"relative",children:[e.jsx(Lr,{className:"absolute left-3 top-3 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search by name, email, or brokerage...",value:d,onChange:D=>u(D.target.value),className:"pl-9"})]})}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(qh,{sortKey:"user",currentSortKey:S,currentDirection:C,onSort:E,children:"User"}),e.jsx(qh,{sortKey:"brokerage",currentSortKey:S,currentDirection:C,onSort:E,children:"Brokerage"}),e.jsx(Pt,{children:"Last Activity"}),e.jsx(qh,{sortKey:"last_activity_at",currentSortKey:S,currentDirection:C,onSort:E,children:"Last Active"}),e.jsx(qh,{sortKey:"apps",currentSortKey:S,currentDirection:C,onSort:E,className:"text-right",children:"Apps"}),e.jsx(qh,{sortKey:"content",currentSortKey:S,currentDirection:C,onSort:E,className:"text-right",children:"Content"})]})}),e.jsx(Ka,{children:I.length===0?e.jsx(pn,{children:e.jsx(gt,{colSpan:6,className:"text-center text-muted-foreground",children:"No activity found"})}):I.map(D=>e.jsxs(pn,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>b(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(Oe,{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(Oe,{variant:"secondary",children:[e.jsx(wr,{className:"h-3 w-3 mr-1"}),D.last_activity_name]}):e.jsxs(Oe,{variant:"outline",className:"flex items-center gap-1",children:[qvt(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:Ed(new Date(D.last_activity_at),{addSuffix:!0})}),e.jsx(gt,{className:"text-right",children:e.jsx(Oe,{variant:"outline",children:D.total_app_launches})}),e.jsx(gt,{className:"text-right",children:e.jsx(Oe,{variant:"outline",children:D.total_content_views})})]},D.user_id))})]})})]})]}),e.jsx(Ls,{open:!!h,onOpenChange:D=>!D&&j(),children:e.jsxs(Ps,{className:"max-w-3xl max-h-[80vh] overflow-hidden flex flex-col",children:[e.jsxs(Os,{children:[e.jsxs(Ds,{children:[h==null?void 0:h.name,"'s Activity"]}),e.jsx(_r,{children:h==null?void 0:h.email})]}),e.jsxs(Yr,{defaultValue:"content",className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(Zr,{className:"grid w-full grid-cols-2",children:[e.jsxs(Ht,{value:"content",children:["Content (",y.length,")"]}),e.jsxs(Ht,{value:"apps",children:["App Launches (",p.length,")"]})]}),e.jsx(Gt,{value:"content",className:"flex-1 overflow-auto mt-4",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"Type"}),e.jsx(Pt,{children:"Resource"}),e.jsx(Pt,{children:"Action"}),e.jsx(Pt,{children:"Time"})]})}),e.jsx(Ka,{children:y.length===0?e.jsx(pn,{children:e.jsx(gt,{colSpan:4,className:"text-center text-muted-foreground",children:"No content engagement"})}):y.map(D=>e.jsxs(pn,{children:[e.jsx(gt,{children:e.jsxs(Oe,{variant:"outline",className:"flex items-center gap-1 w-fit",children:[qvt(D.resource_type),pon(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(Oe,{variant:"secondary",children:fon(D.action_type)})}),e.jsx(gt,{className:"text-sm text-muted-foreground",children:Ed(new Date(D.created_at),{addSuffix:!0})})]},D.id))})]})})}),e.jsx(Gt,{value:"apps",className:"flex-1 overflow-auto mt-4",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"App"}),e.jsx(Pt,{children:"Time"})]})}),e.jsx(Ka,{children:p.length===0?e.jsx(pn,{children:e.jsx(gt,{colSpan:2,className:"text-center text-muted-foreground",children:"No app launches"})}):p.map(D=>e.jsxs(pn,{children:[e.jsx(gt,{children:e.jsx(Oe,{variant:"secondary",children:D.app_name})}),e.jsx(gt,{className:"text-sm text-muted-foreground",children:Ed(new Date(D.launched_at),{addSuffix:!0})})]},D.id))})]})})})]})]})})]})},gon=()=>{const{toast:s}=vi(),[t,n]=_.useState({totalUsers:0,activeUsers:0,pendingUsers:0,totalBrokerages:0,totalLaunches:0,launchesThisWeek:0,launchesThisMonth:0,uniqueActiveThisWeek:0}),[r,a]=_.useState(!0);_.useEffect(()=>{i()},[]);const i=async()=>{try{a(!0);const{count:l}=await q.from("profiles").select("*",{count:"exact",head:!0}),{count:o}=await q.from("profiles").select("*",{count:"exact",head:!0}).not("last_login","is",null),c=(l||0)-(o||0),{count:d}=await q.from("brokerages").select("*",{count:"exact",head:!0}),{count:u}=await q.from("activity_logs").select("*",{count:"exact",head:!0}),h=new Date;h.setDate(h.getDate()-7);const{count:m}=await q.from("activity_logs").select("*",{count:"exact",head:!0}).gte("launched_at",h.toISOString()),p=new Date;p.setMonth(p.getMonth()-1);const{count:f}=await q.from("activity_logs").select("*",{count:"exact",head:!0}).gte("launched_at",p.toISOString()),{data:y}=await q.from("activity_logs").select("user_id").gte("launched_at",h.toISOString()),v=new Set(y==null?void 0:y.map(g=>g.user_id)).size;n({totalUsers:l||0,activeUsers:o||0,pendingUsers:c,totalBrokerages:d||0,totalLaunches:u||0,launchesThisWeek:m||0,launchesThisMonth:f||0,uniqueActiveThisWeek:v})}catch(l){console.error("Error loading analytics:",l),s({title:"Error",description:"Failed to load analytics",variant:"destructive"})}finally{a(!1)}};return r?e.jsx(ve,{children:e.jsx(Me,{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(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(St,{className:"text-sm font-medium",children:"Total Users"}),e.jsx(In,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Me,{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(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(St,{className:"text-sm font-medium",children:"Active Users"}),e.jsx(_l,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Me,{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(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(St,{className:"text-sm font-medium",children:"Pending Invites"}),e.jsx(Gr,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Me,{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(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(St,{className:"text-sm font-medium",children:"Brokerages"}),e.jsx(ai,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Me,{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(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(St,{className:"text-sm font-medium",children:"Total App Launches"}),e.jsx(hm,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Me,{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(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(St,{className:"text-sm font-medium",children:"Launches This Week"}),e.jsx(hm,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Me,{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(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(St,{className:"text-sm font-medium",children:"Launches This Month"}),e.jsx(hm,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Me,{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(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(St,{className:"text-sm font-medium",children:"Active This Week"}),e.jsx(Nl,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Me,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.uniqueActiveThisWeek}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Unique users"})]})]})]})},$vt={event:"Event",template:"Template",academy_video:"Academy Video",resource_kit:"Resource Kit",newsletter:"Newsletter",social_swag:"Social Swag"},Vvt={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 TVt({brokerageOnly:s=!1,brokerageId:t}){const[n,r]=_.useState([]),[a,i]=_.useState(!0),[l,o]=_.useState(""),[c,d]=_.useState("all");_.useEffect(()=>{u()},[t]);const u=async()=>{i(!0);try{let E=[];if(s&&t){const{data:$}=await q.from("profiles").select("id").eq("brokerage_id",t);if(E=($==null?void 0:$.map(H=>H.id))||[],E.length===0){r([]),i(!1);return}}let P=q.from("resource_shares").select("*").order("created_at",{ascending:!1});s&&E.length>0&&(P=P.or(`sender_id.in.(${E.join(",")}),recipient_id.in.(${E.join(",")})`));const{data:M,error:I}=await P;if(I)throw I;const D=new Set;M==null||M.forEach($=>{D.add($.sender_id),D.add($.recipient_id)});const{data:O}=await q.from("profiles").select("id, name, email").in("id",Array.from(D)),V=new Map((O==null?void 0:O.map($=>[$.id,$]))||[]),G=(M==null?void 0:M.map($=>({...$,sender:V.get($.sender_id),recipient:V.get($.recipient_id)})))||[];r(G)}catch(E){console.error("Error loading shares:",E)}finally{i(!1)}},{sortKey:h,sortDirection:m,handleSort:p,sortData:f}=wae("created_at","desc"),y=n.filter(E=>{var I,D;const P=l===""||E.resource_title.toLowerCase().includes(l.toLowerCase())||((I=E.sender)==null?void 0:I.name.toLowerCase().includes(l.toLowerCase()))||((D=E.recipient)==null?void 0:D.name.toLowerCase().includes(l.toLowerCase())),M=c==="all"||E.resource_type===c;return P&&M}),v=f(y,{resource:E=>{var P;return((P=E.resource_title)==null?void 0:P.toLowerCase())||""},type:E=>E.resource_type,sender:E=>{var P,M;return((M=(P=E.sender)==null?void 0:P.name)==null?void 0:M.toLowerCase())||""},recipient:E=>{var P,M;return((M=(P=E.recipient)==null?void 0:P.name)==null?void 0:M.toLowerCase())||""},status:E=>E.is_read?1:0,created_at:E=>new Date(E.created_at).getTime()}),g=n.length,b=new Set(n.map(E=>E.sender_id)).size,j=new Set(n.map(E=>E.recipient_id)).size,S=n.length>0?Math.round(n.filter(E=>E.is_read).length/n.length*100):0,C=n.reduce((E,P)=>(E[P.resource_type]=(E[P.resource_type]||0)+1,E),{});return a?e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid gap-4 md:grid-cols-4",children:[...Array(4)].map((E,P)=>e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-2",children:e.jsx(cn,{className:"h-4 w-20"})}),e.jsx(Me,{children:e.jsx(cn,{className:"h-8 w-16"})})]},P))}),e.jsx(ve,{children:e.jsx(Me,{className:"p-6",children:e.jsx(cn,{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(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(St,{className:"text-sm font-medium",children:"Total Shares"}),e.jsx(bd,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Me,{children:e.jsx("div",{className:"text-2xl font-bold",children:g})})]}),e.jsxs(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(St,{className:"text-sm font-medium",children:"Active Sharers"}),e.jsx(In,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Me,{children:e.jsx("div",{className:"text-2xl font-bold",children:b})})]}),e.jsxs(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(St,{className:"text-sm font-medium",children:"Recipients Reached"}),e.jsx(Nl,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Me,{children:e.jsx("div",{className:"text-2xl font-bold",children:j})})]}),e.jsxs(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(St,{className:"text-sm font-medium",children:"Read Rate"}),e.jsx(Fr,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Me,{children:e.jsxs("div",{className:"text-2xl font-bold",children:[S,"%"]})})]})]}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-sm font-medium",children:"Shares by Resource Type"})}),e.jsx(Me,{children:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[Object.entries(C).map(([E,P])=>e.jsxs(Oe,{variant:"secondary",className:Vvt[E],children:[$vt[E],": ",P]},E)),Object.keys(C).length===0&&e.jsx("span",{className:"text-muted-foreground text-sm",children:"No shares yet"})]})})]}),e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsx(St,{children:"Share History"}),e.jsxs(kn,{children:["All resource shares ",s?"in your brokerage":"across the platform"]})]}),e.jsxs(Me,{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(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search by resource, sender, or recipient...",value:l,onChange:E=>o(E.target.value),className:"pl-9"})]}),e.jsxs(is,{value:c,onValueChange:d,children:[e.jsx(rs,{className:"w-[180px]",children:e.jsx(ls,{placeholder:"Resource type"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Types"}),e.jsx(He,{value:"event",children:"Events"}),e.jsx(He,{value:"template",children:"Templates"}),e.jsx(He,{value:"academy_video",children:"Academy Videos"}),e.jsx(He,{value:"resource_kit",children:"Resource Kits"}),e.jsx(He,{value:"newsletter",children:"Newsletters"}),e.jsx(He,{value:"social_swag",children:"Social Swag"})]})]})]}),e.jsx(Ji,{className:"h-[400px]",children:e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(qh,{sortKey:"resource",currentSortKey:h,currentDirection:m,onSort:p,children:"Resource"}),e.jsx(qh,{sortKey:"type",currentSortKey:h,currentDirection:m,onSort:p,children:"Type"}),e.jsx(qh,{sortKey:"sender",currentSortKey:h,currentDirection:m,onSort:p,children:"Sender"}),e.jsx(qh,{sortKey:"recipient",currentSortKey:h,currentDirection:m,onSort:p,children:"Recipient"}),e.jsx(qh,{sortKey:"status",currentSortKey:h,currentDirection:m,onSort:p,children:"Status"}),e.jsx(qh,{sortKey:"created_at",currentSortKey:h,currentDirection:m,onSort:p,children:"Date"})]})}),e.jsx(Ka,{children:v.length===0?e.jsx(pn,{children:e.jsx(gt,{colSpan:6,className:"text-center text-muted-foreground py-8",children:"No shares found"})}):v.map(E=>{var P,M;return e.jsxs(pn,{children:[e.jsx(gt,{className:"font-medium max-w-[200px] truncate",children:E.resource_title}),e.jsx(gt,{children:e.jsx(Oe,{variant:"secondary",className:Vvt[E.resource_type],children:$vt[E.resource_type]})}),e.jsx(gt,{children:((P=E.sender)==null?void 0:P.name)||"Unknown"}),e.jsx(gt,{children:((M=E.recipient)==null?void 0:M.name)||"Unknown"}),e.jsx(gt,{children:e.jsx(Oe,{variant:E.is_read?"default":"outline",children:E.is_read?"Read":"Unread"})}),e.jsx(gt,{className:"text-muted-foreground",children:Hs(new Date(E.created_at),"MMM d, yyyy")})]},E.id)})})]})})]})]})]})}const u9e={academy_video:{label:"Academy Videos",icon:Kr,color:"bg-purple-100 text-purple-800",actionLabel:"Watched",actionIcon:ya},template:{label:"Templates",icon:Z3,color:"bg-blue-100 text-blue-800",actionLabel:"Accessed",actionIcon:v0},toolbox:{label:"Toolkit",icon:Y4,color:"bg-amber-100 text-amber-800",actionLabel:"Downloaded",actionIcon:li},newsletter:{label:"Newsletters",icon:ln,color:"bg-emerald-100 text-emerald-800",actionLabel:"Clicked",actionIcon:v0},social_swag:{label:"Social Swag",icon:Xc,color:"bg-pink-100 text-pink-800",actionLabel:"Accessed",actionIcon:v0},event:{label:"Events",icon:ga,color:"bg-cyan-100 text-cyan-800",actionLabel:"Registered",actionIcon:v0}};function Hvt(s){return s.resource_type==="toolbox"?s.total_downloads:s.total_clicks}function yon(s,t){return s==="toolbox"?t.downloads:t.clicks}function von(){var E;const[s,t]=_.useState([]),[n,r]=_.useState(!0),[a,i]=_.useState(null),l=_.useRef(null),{sortKey:o,sortDirection:c,handleSort:d,sortData:u}=wae("total_views","desc");_.useEffect(()=>{h()},[]);const h=async()=>{try{const{data:P,error:M}=await q.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(ve,{children:[e.jsx(bt,{className:"pb-2",children:e.jsx(cn,{className:"h-4 w-20"})}),e.jsx(Me,{children:e.jsx(cn,{className:"h-8 w-16"})})]},M))}),e.jsx(ve,{children:e.jsx(Me,{className:"py-8",children:e.jsx(cn,{className:"h-64 w-full"})})})]});const p=s.reduce((P,M)=>P+M.total_views,0),f=s.reduce((P,M)=>P+M.total_clicks,0),y=s.reduce((P,M)=>P+M.total_downloads,0),v=s.length,g=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),{}),b=a?s.filter(P=>P.resource_type===a):s,j=u(b,{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=>Hvt(P),unique_users:P=>P.unique_users,last_activity:P=>P.last_engaged_at?new Date(P.last_engaged_at).getTime():0}),S=a?u9e[a]||{label:a,icon:ya,color:"bg-muted text-muted-foreground",actionLabel:"Actions",actionIcon:v0}:null,C=S==null?void 0:S.icon;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 grid-cols-2 md:grid-cols-5",children:[e.jsxs(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(St,{className:"text-sm font-medium",children:"Total Views"}),e.jsx(ya,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Me,{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(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(St,{className:"text-sm font-medium",children:"Total Clicks"}),e.jsx(v0,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Me,{children:[e.jsx("div",{className:"text-2xl font-bold",children:f.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Link & Canva clicks"})]})]}),e.jsxs(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(St,{className:"text-sm font-medium",children:"Downloads"}),e.jsx(li,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Me,{children:[e.jsx("div",{className:"text-2xl font-bold",children:y.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"PDF downloads"})]})]}),e.jsxs(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(St,{className:"text-sm font-medium",children:"Assets Tracked"}),e.jsx(Nl,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Me,{children:[e.jsx("div",{className:"text-2xl font-bold",children:v}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Unique content items"})]})]}),e.jsxs(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(St,{className:"text-sm font-medium",children:"Click Rate"}),e.jsx(v0,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Me,{children:[e.jsxs("div",{className:"text-2xl font-bold",children:[p>0?Math.round((f+y)/p*100):0,"%"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Of views → actions"})]})]})]}),e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsx(St,{className:"text-sm font-medium",children:"Engagement by Content Type"}),e.jsx(kn,{children:"Click a category to see individual asset performance"})]}),e.jsx(Me,{children:e.jsx("div",{className:"grid gap-3 grid-cols-2 md:grid-cols-3",children:Object.entries(g).map(([P,M])=>{const I=u9e[P]||{label:P,icon:ya,color:"bg-muted text-muted-foreground",actionLabel:"Actions",actionIcon:v0},D=I.icon,O=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 ${O?"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(ya,{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"})," ",yon(P,M)]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(In,{className:"h-3 w-3"})," ",M.uniqueUsers]})]})]}),e.jsxs(Oe,{variant:"secondary",className:"text-[10px]",children:[M.assets," items"]})]},P)})})})]}),e.jsx("div",{ref:l,children:e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(St,{className:"text-sm font-medium flex items-center gap-2",children:S&&C?e.jsxs(e.Fragment,{children:[e.jsx(C,{className:"h-4 w-4"}),S.label," — Top Performers"]}):"Top Content by Engagement"}),e.jsx(kn,{children:a?`${b.length} ${((E=S==null?void 0:S.label)==null?void 0:E.toLowerCase())||"items"} ranked by total interactions`:"All tracked assets ranked by total interactions"})]}),a&&e.jsxs(B,{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(Me,{children:b.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No engagement data yet. As users view and click content, stats will appear here."}):e.jsx(Ji,{className:"h-[400px]",children:e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{className:"w-[40px]",children:"#"}),e.jsx(qh,{sortKey:"asset",currentSortKey:o,currentDirection:c,onSort:d,children:"Asset"}),!a&&e.jsx(qh,{sortKey:"type",currentSortKey:o,currentDirection:c,onSort:d,children:"Type"}),e.jsx(qh,{sortKey:"views",currentSortKey:o,currentDirection:c,onSort:d,className:"text-right",children:"Views"}),e.jsx(qh,{sortKey:"actions",currentSortKey:o,currentDirection:c,onSort:d,className:"text-right",children:S?S.actionLabel:"Actions"}),e.jsx(qh,{sortKey:"unique_users",currentSortKey:o,currentDirection:c,onSort:d,className:"text-right",children:"Unique Users"}),e.jsx(qh,{sortKey:"last_activity",currentSortKey:o,currentDirection:c,onSort:d,children:"Last Activity"})]})}),e.jsx(Ka,{children:j.map((P,M)=>{const I=u9e[P.resource_type]||{label:P.resource_type,color:"bg-muted text-muted-foreground",actionLabel:"Actions",actionIcon:v0};return e.jsxs(pn,{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(Oe,{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:Hvt(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?Ed(new Date(P.last_engaged_at),{addSuffix:!0}):"—"})]},`${P.resource_type}-${P.resource_id}`)})})]})})})]})})]})}var bon=Array.isArray,X_=bon,_on=typeof Cp=="object"&&Cp&&Cp.Object===Object&&Cp,MVt=_on,won=MVt,jon=typeof self=="object"&&self&&self.Object===Object&&self,Non=won||jon||Function("return this")(),CC=Non,kon=CC,Son=kon.Symbol,Nae=Son,Gvt=Nae,PVt=Object.prototype,Con=PVt.hasOwnProperty,Aon=PVt.toString,tZ=Gvt?Gvt.toStringTag:void 0;function Eon(s){var t=Con.call(s,tZ),n=s[tZ];try{s[tZ]=void 0;var r=!0}catch{}var a=Aon.call(s);return r&&(t?s[tZ]=n:delete s[tZ]),a}var Ton=Eon,Mon=Object.prototype,Pon=Mon.toString;function Lon(s){return Pon.call(s)}var Ion=Lon,Wvt=Nae,Don=Ton,Ron=Ion,Fon="[object Null]",Oon="[object Undefined]",Kvt=Wvt?Wvt.toStringTag:void 0;function zon(s){return s==null?s===void 0?Oon:Fon:Kvt&&Kvt in Object(s)?Don(s):Ron(s)}var BE=zon;function Bon(s){return s!=null&&typeof s=="object"}var UE=Bon,Uon=BE,qon=UE,$on="[object Symbol]";function Von(s){return typeof s=="symbol"||qon(s)&&Uon(s)==$on}var SW=Von,Hon=X_,Gon=SW,Won=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Kon=/^\w*$/;function Yon(s,t){if(Hon(s))return!1;var n=typeof s;return n=="number"||n=="symbol"||n=="boolean"||s==null||Gon(s)?!0:Kon.test(s)||!Won.test(s)||t!=null&&s in Object(t)}var Htt=Yon;function Zon(s){var t=typeof s;return s!=null&&(t=="object"||t=="function")}var CL=Zon;const CW=_d(CL);var Xon=BE,Qon=CL,Jon="[object AsyncFunction]",eln="[object Function]",tln="[object GeneratorFunction]",sln="[object Proxy]";function nln(s){if(!Qon(s))return!1;var t=Xon(s);return t==eln||t==tln||t==Jon||t==sln}var Gtt=nln;const Rl=_d(Gtt);var rln=CC,aln=rln["__core-js_shared__"],iln=aln,h9e=iln,Yvt=function(){var s=/[^.]+$/.exec(h9e&&h9e.keys&&h9e.keys.IE_PROTO||"");return s?"Symbol(src)_1."+s:""}();function oln(s){return!!Yvt&&Yvt in s}var lln=oln,cln=Function.prototype,dln=cln.toString;function uln(s){if(s!=null){try{return dln.call(s)}catch{}try{return s+""}catch{}}return""}var LVt=uln,hln=Gtt,mln=lln,pln=CL,fln=LVt,xln=/[\\^$.*+?()[\]{}|]/g,gln=/^\[object .+?Constructor\]$/,yln=Function.prototype,vln=Object.prototype,bln=yln.toString,_ln=vln.hasOwnProperty,wln=RegExp("^"+bln.call(_ln).replace(xln,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function jln(s){if(!pln(s)||mln(s))return!1;var t=hln(s)?wln:gln;return t.test(fln(s))}var Nln=jln;function kln(s,t){return s==null?void 0:s[t]}var Sln=kln,Cln=Nln,Aln=Sln;function Eln(s,t){var n=Aln(s,t);return Cln(n)?n:void 0}var J9=Eln,Tln=J9,Mln=Tln(Object,"create"),QLe=Mln,Zvt=QLe;function Pln(){this.__data__=Zvt?Zvt(null):{},this.size=0}var Lln=Pln;function Iln(s){var t=this.has(s)&&delete this.__data__[s];return this.size-=t?1:0,t}var Dln=Iln,Rln=QLe,Fln="__lodash_hash_undefined__",Oln=Object.prototype,zln=Oln.hasOwnProperty;function Bln(s){var t=this.__data__;if(Rln){var n=t[s];return n===Fln?void 0:n}return zln.call(t,s)?t[s]:void 0}var Uln=Bln,qln=QLe,$ln=Object.prototype,Vln=$ln.hasOwnProperty;function Hln(s){var t=this.__data__;return qln?t[s]!==void 0:Vln.call(t,s)}var Gln=Hln,Wln=QLe,Kln="__lodash_hash_undefined__";function Yln(s,t){var n=this.__data__;return this.size+=this.has(s)?0:1,n[s]=Wln&&t===void 0?Kln:t,this}var Zln=Yln,Xln=Lln,Qln=Dln,Jln=Uln,ecn=Gln,tcn=Zln;function AW(s){var t=-1,n=s==null?0:s.length;for(this.clear();++t-1}var ycn=gcn,vcn=JLe;function bcn(s,t){var n=this.__data__,r=vcn(n,s);return r<0?(++this.size,n.push([s,t])):n[r][1]=t,this}var _cn=bcn,wcn=rcn,jcn=hcn,Ncn=fcn,kcn=ycn,Scn=_cn;function EW(s){var t=-1,n=s==null?0:s.length;for(this.clear();++t0?1:-1},_F=function(t){return l9(t)&&t.indexOf("%")===t.length-1},ei=function(t){return Kdn(t)&&!MW(t)},Qdn=function(t){return mc(t)},j0=function(t){return ei(t)||l9(t)},Jdn=0,ez=function(t){var n=++Jdn;return"".concat(t||"").concat(n)},xb=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(!ei(t)&&!l9(t))return r;var i;if(_F(t)){var l=t.indexOf("%");i=n*parseFloat(t.slice(0,l))/100}else i=+t;return MW(i)&&(i=r),a&&i>n&&(i=n),i},A6=function(t){if(!t)return null;var n=Object.keys(t);return n&&n.length?t[n[0]]:null},eun=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 oun(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 THe(s){"@babel/helpers - typeof";return THe=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},THe(s)}var n1t={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"},sE=function(t){return typeof t=="string"?t:t?t.displayName||t.name||"Component":""},r1t=null,p9e=null,sst=function s(t){if(t===r1t&&Array.isArray(p9e))return p9e;var n=[];return _.Children.forEach(t,function(r){mc(r)||($dn.isFragment(r)?n=n.concat(s(r.props.children)):n.push(r))}),p9e=n,r1t=t,n};function _j(s,t){var n=[],r=[];return Array.isArray(t)?r=t.map(function(a){return sE(a)}):r=[sE(t)],sst(s).forEach(function(a){var i=bj(a,"type.displayName")||bj(a,"type.name");r.indexOf(i)!==-1&&n.push(a)}),n}function Hw(s,t){var n=_j(s,t);return n&&n[0]}var a1t=function(t){if(!t||!t.props)return!1;var n=t.props,r=n.width,a=n.height;return!(!ei(r)||r<=0||!ei(a)||a<=0)},lun=["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"],cun=function(t){return t&&t.type&&l9(t.type)&&lun.indexOf(t.type)>=0},$Vt=function(t){return t&&THe(t)==="object"&&"clipDot"in t},dun=function(t,n,r,a){var i,l=(i=m9e==null?void 0:m9e[a])!==null&&i!==void 0?i:[];return n.startsWith("data-")||!Rl(t)&&(a&&l.includes(n)||nun.includes(n))||r&&tst.includes(n)},$o=function(t,n,r){if(!t||typeof t=="function"||typeof t=="boolean")return null;var a=t;if(_.isValidElement(t)&&(a=t.props),!CW(a))return null;var i={};return Object.keys(a).forEach(function(l){var o;dun((o=a)===null||o===void 0?void 0:o[l],l,n,r)&&(i[l]=a[l])}),i},MHe=function s(t,n){if(t===n)return!0;var r=_.Children.count(t);if(r!==_.Children.count(n))return!1;if(r===0)return!0;if(r===1)return i1t(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 fun(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 LHe(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=pun(s,mun),u=a||{width:n,height:r,x:0,y:0},h=jc("recharts-surface",i);return Dt.createElement("svg",PHe({},$o(d,!0,"svg"),{className:h,width:n,height:r,style:l,viewBox:"".concat(u.x," ").concat(u.y," ").concat(u.width," ").concat(u.height)}),Dt.createElement("title",null,o),Dt.createElement("desc",null,c),t)}var xun=["children","className"];function IHe(){return IHe=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 yun(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 Fd=Dt.forwardRef(function(s,t){var n=s.children,r=s.className,a=gun(s,xun),i=jc("recharts-layer",r);return Dt.createElement("g",IHe({className:i},$o(a,!0),{ref:t}),n)}),bS=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:_un(s,t,n)}var jun=wun,Nun="\\ud800-\\udfff",kun="\\u0300-\\u036f",Sun="\\ufe20-\\ufe2f",Cun="\\u20d0-\\u20ff",Aun=kun+Sun+Cun,Eun="\\ufe0e\\ufe0f",Tun="\\u200d",Mun=RegExp("["+Tun+Nun+Aun+Eun+"]");function Pun(s){return Mun.test(s)}var VVt=Pun;function Lun(s){return s.split("")}var Iun=Lun,HVt="\\ud800-\\udfff",Dun="\\u0300-\\u036f",Run="\\ufe20-\\ufe2f",Fun="\\u20d0-\\u20ff",Oun=Dun+Run+Fun,zun="\\ufe0e\\ufe0f",Bun="["+HVt+"]",DHe="["+Oun+"]",RHe="\\ud83c[\\udffb-\\udfff]",Uun="(?:"+DHe+"|"+RHe+")",GVt="[^"+HVt+"]",WVt="(?:\\ud83c[\\udde6-\\uddff]){2}",KVt="[\\ud800-\\udbff][\\udc00-\\udfff]",qun="\\u200d",YVt=Uun+"?",ZVt="["+zun+"]?",$un="(?:"+qun+"(?:"+[GVt,WVt,KVt].join("|")+")"+ZVt+YVt+")*",Vun=ZVt+YVt+$un,Hun="(?:"+[GVt+DHe+"?",DHe,WVt,KVt,Bun].join("|")+")",Gun=RegExp(RHe+"(?="+RHe+")|"+Hun+Vun,"g");function Wun(s){return s.match(Gun)||[]}var Kun=Wun,Yun=Iun,Zun=VVt,Xun=Kun;function Qun(s){return Zun(s)?Xun(s):Yun(s)}var Jun=Qun,ehn=jun,thn=VVt,shn=Jun,nhn=FVt;function rhn(s){return function(t){t=nhn(t);var n=thn(t)?shn(t):void 0,r=n?n[0]:t.charAt(0),a=n?ehn(n,1).join(""):t.slice(1);return r[s]()+a}}var ahn=rhn,ihn=ahn,ohn=ihn("toUpperCase"),lhn=ohn;const mIe=_d(lhn);function Ym(s){return function(){return s}}const XVt=Math.cos,PEe=Math.sin,BS=Math.sqrt,LEe=Math.PI,pIe=2*LEe,FHe=Math.PI,OHe=2*FHe,BR=1e-6,chn=OHe-BR;function QVt(s){this._+=s[0];for(let t=1,n=s.length;t=0))throw new Error(`invalid digits: ${s}`);if(t>15)return QVt;const n=10**t;return function(r){this._+=r[0];for(let a=1,i=r.length;aBR)if(!(Math.abs(h*c-d*u)>BR)||!i)this._append`L${this._x1=t},${this._y1=n}`;else{let p=r-l,f=a-o,y=c*c+d*d,v=p*p+f*f,g=Math.sqrt(y),b=Math.sqrt(m),j=i*Math.tan((FHe-Math.acos((y+m-v)/(2*g*b)))/2),S=j/b,C=j/g;Math.abs(S-1)>BR&&this._append`L${t+S*u},${n+S*h}`,this._append`A${i},${i},0,0,${+(h*p>u*f)},${this._x1=t+C*c},${this._y1=n+C*d}`}}arc(t,n,r,a,i,l){if(t=+t,n=+n,r=+r,l=!!l,r<0)throw new Error(`negative radius: ${r}`);let o=r*Math.cos(a),c=r*Math.sin(a),d=t+o,u=n+c,h=1^l,m=l?a-i:i-a;this._x1===null?this._append`M${d},${u}`:(Math.abs(this._x1-d)>BR||Math.abs(this._y1-u)>BR)&&this._append`L${d},${u}`,r&&(m<0&&(m=m%OHe+OHe),m>chn?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>BR&&this._append`A${r},${r},0,${+(m>=FHe)},${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 nst(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 uhn(t)}function rst(s){return typeof s=="object"&&"length"in s?s:Array.from(s)}function JVt(s){this._context=s}JVt.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 fIe(s){return new JVt(s)}function eHt(s){return s[0]}function tHt(s){return s[1]}function sHt(s,t){var n=Ym(!0),r=null,a=fIe,i=null,l=nst(o);s=typeof s=="function"?s:s===void 0?eHt:Ym(s),t=typeof t=="function"?t:t===void 0?tHt:Ym(t);function o(c){var d,u=(c=rst(c)).length,h,m=!1,p;for(r==null&&(i=a(p=l())),d=0;d<=u;++d)!(d=p;--f)o.point(j[f],S[f]);o.lineEnd(),o.areaEnd()}g&&(j[m]=+s(v,m,h),S[m]=+t(v,m,h),o.point(r?+r(v,m,h):j[m],n?+n(v,m,h):S[m]))}if(b)return o=null,b+""||null}function u(){return sHt().defined(a).curve(l).context(i)}return d.x=function(h){return arguments.length?(s=typeof h=="function"?h:Ym(+h),r=null,d):s},d.x0=function(h){return arguments.length?(s=typeof h=="function"?h:Ym(+h),d):s},d.x1=function(h){return arguments.length?(r=h==null?null:typeof h=="function"?h:Ym(+h),d):r},d.y=function(h){return arguments.length?(t=typeof h=="function"?h:Ym(+h),n=null,d):t},d.y0=function(h){return arguments.length?(t=typeof h=="function"?h:Ym(+h),d):t},d.y1=function(h){return arguments.length?(n=h==null?null:typeof h=="function"?h:Ym(+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:Ym(!!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 nHt{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 hhn(s){return new nHt(s,!0)}function mhn(s){return new nHt(s,!1)}const ast={draw(s,t){const n=BS(t/LEe);s.moveTo(n,0),s.arc(0,0,n,0,pIe)}},phn={draw(s,t){const n=BS(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()}},rHt=BS(1/3),fhn=rHt*2,xhn={draw(s,t){const n=BS(t/fhn),r=n*rHt;s.moveTo(0,-n),s.lineTo(r,0),s.lineTo(0,n),s.lineTo(-r,0),s.closePath()}},ghn={draw(s,t){const n=BS(t),r=-n/2;s.rect(r,r,n,n)}},yhn=.8908130915292852,aHt=PEe(LEe/10)/PEe(7*LEe/10),vhn=PEe(pIe/10)*aHt,bhn=-XVt(pIe/10)*aHt,_hn={draw(s,t){const n=BS(t*yhn),r=vhn*n,a=bhn*n;s.moveTo(0,-n),s.lineTo(r,a);for(let i=1;i<5;++i){const l=pIe*i/5,o=XVt(l),c=PEe(l);s.lineTo(c*n,-o*n),s.lineTo(o*r-c*a,c*r+o*a)}s.closePath()}},f9e=BS(3),whn={draw(s,t){const n=-BS(t/(f9e*3));s.moveTo(0,n*2),s.lineTo(-f9e*n,-n),s.lineTo(f9e*n,-n),s.closePath()}},x2=-.5,g2=BS(3)/2,zHe=1/BS(12),jhn=(zHe/2+1)*3,Nhn={draw(s,t){const n=BS(t/jhn),r=n/2,a=n*zHe,i=r,l=n*zHe+n,o=-i,c=l;s.moveTo(r,a),s.lineTo(i,l),s.lineTo(o,c),s.lineTo(x2*r-g2*a,g2*r+x2*a),s.lineTo(x2*i-g2*l,g2*i+x2*l),s.lineTo(x2*o-g2*c,g2*o+x2*c),s.lineTo(x2*r+g2*a,x2*a-g2*r),s.lineTo(x2*i+g2*l,x2*l-g2*i),s.lineTo(x2*o+g2*c,x2*c-g2*o),s.closePath()}};function khn(s,t){let n=null,r=nst(a);s=typeof s=="function"?s:Ym(s||ast),t=typeof t=="function"?t:Ym(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:Ym(i),a):s},a.size=function(i){return arguments.length?(t=typeof i=="function"?i:Ym(+i),a):t},a.context=function(i){return arguments.length?(n=i??null,a):n},a}function IEe(){}function DEe(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 iHt(s){this._context=s}iHt.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:DEe(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:DEe(this,s,t);break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t}};function Shn(s){return new iHt(s)}function oHt(s){this._context=s}oHt.prototype={areaStart:IEe,areaEnd:IEe,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:DEe(this,s,t);break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t}};function Chn(s){return new oHt(s)}function lHt(s){this._context=s}lHt.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:DEe(this,s,t);break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t}};function Ahn(s){return new lHt(s)}function cHt(s){this._context=s}cHt.prototype={areaStart:IEe,areaEnd:IEe,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 Ehn(s){return new cHt(s)}function l1t(s){return s<0?-1:1}function c1t(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(l1t(i)+l1t(l))*Math.min(Math.abs(i),Math.abs(l),.5*Math.abs(o))||0}function d1t(s,t){var n=s._x1-s._x0;return n?(3*(s._y1-s._y0)/n-t)/2:t}function x9e(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 REe(s){this._context=s}REe.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:x9e(this,this._t0,d1t(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,x9e(this,d1t(this,n=c1t(this,s,t)),n);break;default:x9e(this,this._t0,n=c1t(this,s,t));break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t,this._t0=n}}};function dHt(s){this._context=new uHt(s)}(dHt.prototype=Object.create(REe.prototype)).point=function(s,t){REe.prototype.point.call(this,t,s)};function uHt(s){this._context=s}uHt.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 Thn(s){return new REe(s)}function Mhn(s){return new dHt(s)}function hHt(s){this._context=s}hHt.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=u1t(s),a=u1t(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 Lhn(s){return new xIe(s,.5)}function Ihn(s){return new xIe(s,0)}function Dhn(s){return new xIe(s,1)}function HH(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 Rhn(s,t){return s[t]}function Fhn(s){const t=[];return t.key=s,t}function Ohn(){var s=Ym([]),t=BHe,n=HH,r=Rhn;function a(i){var l=Array.from(s.apply(this,arguments),Fhn),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 Whn(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 mHt={symbolCircle:ast,symbolCross:phn,symbolDiamond:xhn,symbolSquare:ghn,symbolStar:_hn,symbolTriangle:whn,symbolWye:Nhn},Khn=Math.PI/180,Yhn=function(t){var n="symbol".concat(mIe(t));return mHt[n]||ast},Zhn=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*Khn;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}},Xhn=function(t,n){mHt["symbol".concat(mIe(t))]=n},ist=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=Ghn(t,qhn),d=m1t(m1t({},c),{},{type:r,size:i,sizeType:o}),u=function(){var v=Yhn(r),g=khn().type(v).size(Zhn(i,o,r));return g()},h=d.className,m=d.cx,p=d.cy,f=$o(d,!0);return m===+m&&p===+p&&i===+i?Dt.createElement("path",UHe({},f,{className:jc("recharts-symbols",h),transform:"translate(".concat(m,", ").concat(p,")"),d:u()})):null};ist.registerSymbol=Xhn;function GH(s){"@babel/helpers - typeof";return GH=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},GH(s)}function qHe(){return qHe=Object.assign?Object.assign.bind():function(s){for(var t=1;t`);var b=p.inactive?d:p.color;return Dt.createElement("li",qHe({className:v,style:h,key:"legend-item-".concat(f)},c9(r.props,p,f)),Dt.createElement(LHe,{width:l,height:l,viewBox:u,style:m},r.renderIcon(p)),Dt.createElement("span",{className:"recharts-legend-item-text",style:{color:b}},y?y(g,p,f):g))})}},{key:"render",value:function(){var r=this.props,a=r.payload,i=r.layout,l=r.align;if(!a||!a.length)return null;var o={padding:0,margin:0,textAlign:i==="horizontal"?l:"left"};return Dt.createElement("ul",{className:"recharts-default-legend",style:o},this.renderItems())}}])}(_.PureComponent);Lte(ost,"displayName","Legend");Lte(ost,"defaultProps",{iconSize:14,layout:"horizontal",align:"center",verticalAlign:"middle",inactiveColor:"#ccc"});var omn=eIe;function lmn(){this.__data__=new omn,this.size=0}var cmn=lmn;function dmn(s){var t=this.__data__,n=t.delete(s);return this.size=t.size,n}var umn=dmn;function hmn(s){return this.__data__.get(s)}var mmn=hmn;function pmn(s){return this.__data__.has(s)}var fmn=pmn,xmn=eIe,gmn=Ktt,ymn=Ytt,vmn=200;function bmn(s,t){var n=this.__data__;if(n instanceof xmn){var r=n.__data__;if(!gmn||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&qmn?new Omn:void 0;for(i.set(s,t),i.set(t,s);++h-1&&s%1==0&&s-1&&s%1==0&&s<=Gpn}var ust=Wpn,Kpn=BE,Ypn=ust,Zpn=UE,Xpn="[object Arguments]",Qpn="[object Array]",Jpn="[object Boolean]",efn="[object Date]",tfn="[object Error]",sfn="[object Function]",nfn="[object Map]",rfn="[object Number]",afn="[object Object]",ifn="[object RegExp]",ofn="[object Set]",lfn="[object String]",cfn="[object WeakMap]",dfn="[object ArrayBuffer]",ufn="[object DataView]",hfn="[object Float32Array]",mfn="[object Float64Array]",pfn="[object Int8Array]",ffn="[object Int16Array]",xfn="[object Int32Array]",gfn="[object Uint8Array]",yfn="[object Uint8ClampedArray]",vfn="[object Uint16Array]",bfn="[object Uint32Array]",bp={};bp[hfn]=bp[mfn]=bp[pfn]=bp[ffn]=bp[xfn]=bp[gfn]=bp[yfn]=bp[vfn]=bp[bfn]=!0;bp[Xpn]=bp[Qpn]=bp[dfn]=bp[Jpn]=bp[ufn]=bp[efn]=bp[tfn]=bp[sfn]=bp[nfn]=bp[rfn]=bp[afn]=bp[ifn]=bp[ofn]=bp[lfn]=bp[cfn]=!1;function _fn(s){return Zpn(s)&&Ypn(s.length)&&!!bp[Kpn(s)]}var wfn=_fn;function jfn(s){return function(t){return s(t)}}var NHt=jfn,BEe={exports:{}};BEe.exports;(function(s,t){var n=MVt,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})(BEe,BEe.exports);var Nfn=BEe.exports,kfn=wfn,Sfn=NHt,b1t=Nfn,_1t=b1t&&b1t.isTypedArray,Cfn=_1t?Sfn(_1t):kfn,kHt=Cfn,Afn=Mpn,Efn=cst,Tfn=X_,Mfn=jHt,Pfn=dst,Lfn=kHt,Ifn=Object.prototype,Dfn=Ifn.hasOwnProperty;function Rfn(s,t){var n=Tfn(s),r=!n&&Efn(s),a=!n&&!r&&Mfn(s),i=!n&&!r&&!a&&Lfn(s),l=n||r||a||i,o=l?Afn(s.length,String):[],c=o.length;for(var d in s)(t||Dfn.call(s,d))&&!(l&&(d=="length"||a&&(d=="offset"||d=="parent")||i&&(d=="buffer"||d=="byteLength"||d=="byteOffset")||Pfn(d,c)))&&o.push(d);return o}var Ffn=Rfn,Ofn=Object.prototype;function zfn(s){var t=s&&s.constructor,n=typeof t=="function"&&t.prototype||Ofn;return s===n}var Bfn=zfn;function Ufn(s,t){return function(n){return s(t(n))}}var SHt=Ufn,qfn=SHt,$fn=qfn(Object.keys,Object),Vfn=$fn,Hfn=Bfn,Gfn=Vfn,Wfn=Object.prototype,Kfn=Wfn.hasOwnProperty;function Yfn(s){if(!Hfn(s))return Gfn(s);var t=[];for(var n in Object(s))Kfn.call(s,n)&&n!="constructor"&&t.push(n);return t}var Zfn=Yfn,Xfn=Gtt,Qfn=ust;function Jfn(s){return s!=null&&Qfn(s.length)&&!Xfn(s)}var kae=Jfn,exn=Ffn,txn=Zfn,sxn=kae;function nxn(s){return sxn(s)?exn(s):txn(s)}var gIe=nxn,rxn=vpn,axn=Epn,ixn=gIe;function oxn(s){return rxn(s,ixn,axn)}var lxn=oxn,w1t=lxn,cxn=1,dxn=Object.prototype,uxn=dxn.hasOwnProperty;function hxn(s,t,n,r,a,i){var l=n&cxn,o=w1t(s),c=o.length,d=w1t(t),u=d.length;if(c!=u&&!l)return!1;for(var h=c;h--;){var m=o[h];if(!(l?m in t:uxn.call(t,m)))return!1}var p=i.get(s),f=i.get(t);if(p&&f)return p==t&&f==s;var y=!0;i.set(s,t),i.set(t,s);for(var v=l;++h-1}var d0n=c0n;function u0n(s,t,n){for(var r=-1,a=s==null?0:s.length;++r=S0n){var d=t?null:N0n(s);if(d)return k0n(d);l=!1,a=j0n,c=new b0n}else c=t?[]:o;e:for(;++r=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function q0n(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 $0n(s){return s.value}function V0n(s,t){if(Dt.isValidElement(s))return Dt.cloneElement(s,t);if(typeof s=="function")return Dt.createElement(s,t);t.ref;var n=U0n(t,L0n);return Dt.createElement(ost,n)}var O1t=1,P$=function(s){function t(){var n;I0n(this,t);for(var r=arguments.length,a=new Array(r),i=0;iO1t||Math.abs(a.height-this.lastBoundingBox.height)>O1t)&&(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?g3({},this.lastBoundingBox):{width:0,height:0}}},{key:"getDefaultPosition",value:function(r){var a=this.props,i=a.layout,l=a.align,o=a.verticalAlign,c=a.margin,d=a.chartWidth,u=a.chartHeight,h,m;if(!r||(r.left===void 0||r.left===null)&&(r.right===void 0||r.right===null))if(l==="center"&&i==="vertical"){var p=this.getBBoxSnapshot();h={left:((d||0)-p.width)/2}}else h=l==="right"?{right:c&&c.right||0}:{left:c&&c.left||0};if(!r||(r.top===void 0||r.top===null)&&(r.bottom===void 0||r.bottom===null))if(o==="middle"){var f=this.getBBoxSnapshot();m={top:((u||0)-f.height)/2}}else m=o==="bottom"?{bottom:c&&c.bottom||0}:{top:c&&c.top||0};return g3(g3({},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=g3(g3({position:"absolute",width:l||"auto",height:o||"auto"},this.getDefaultPosition(c)),c);return Dt.createElement("div",{className:"recharts-legend-wrapper",style:h,ref:function(p){r.wrapperNode=p}},V0n(i,g3(g3({},this.props),{},{payload:LHt(u,d,$0n)})))}}],[{key:"getWithHeight",value:function(r,a){var i=g3(g3({},this.defaultProps),r.props),l=i.layout;return l==="vertical"&&ei(r.props.height)?{height:r.props.height}:l==="horizontal"?{width:r.props.width||a}:null}}])}(_.PureComponent);yIe(P$,"displayName","Legend");yIe(P$,"defaultProps",{iconSize:14,layout:"horizontal",align:"center",verticalAlign:"bottom"});var z1t=Nae,H0n=cst,G0n=X_,B1t=z1t?z1t.isConcatSpreadable:void 0;function W0n(s){return G0n(s)||H0n(s)||!!(B1t&&s&&s[B1t])}var K0n=W0n,Y0n=_Ht,Z0n=K0n;function RHt(s,t,n,r,a){var i=-1,l=s.length;for(n||(n=Z0n),a||(a=[]);++i0&&n(o)?t>1?RHt(o,t-1,n,r,a):Y0n(a,o):r||(a[a.length]=o)}return a}var FHt=RHt;function X0n(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 Q0n=X0n,J0n=Q0n,eyn=J0n(),tyn=eyn,syn=tyn,nyn=gIe;function ryn(s,t){return s&&syn(s,t,nyn)}var OHt=ryn,ayn=kae;function iyn(s,t){return function(n,r){if(n==null)return n;if(!ayn(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 byn=vyn,b9e=Xtt,_yn=Qtt,wyn=AC,jyn=zHt,Nyn=fyn,kyn=NHt,Syn=byn,Cyn=IW,Ayn=X_;function Eyn(s,t,n){t.length?t=b9e(t,function(i){return Ayn(i)?function(l){return _yn(l,i.length===1?i[0]:i)}:i}):t=[Cyn];var r=-1;t=b9e(t,kyn(wyn));var a=jyn(s,function(i,l,o){var c=b9e(t,function(d){return d(i)});return{criteria:c,index:++r,value:i}});return Nyn(a,function(i,l){return Syn(i,l,n)})}var Tyn=Eyn;function Myn(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 Pyn=Myn,Lyn=Pyn,q1t=Math.max;function Iyn(s,t,n){return t=q1t(t===void 0?s.length-1:t,0),function(){for(var r=arguments,a=-1,i=q1t(r.length-t,0),l=Array(i);++a0){if(++t>=Vyn)return arguments[0]}else t=0;return s.apply(void 0,arguments)}}var Kyn=Wyn,Yyn=$yn,Zyn=Kyn,Xyn=Zyn(Yyn),Qyn=Xyn,Jyn=IW,evn=Dyn,tvn=Qyn;function svn(s,t){return tvn(evn(s,t,Jyn),s+"")}var nvn=svn,rvn=Wtt,avn=kae,ivn=dst,ovn=CL;function lvn(s,t,n){if(!ovn(n))return!1;var r=typeof t;return(r=="number"?avn(n)&&ivn(t,n.length):r=="string"&&t in n)?rvn(n[t],s):!1}var vIe=lvn,cvn=FHt,dvn=Tyn,uvn=nvn,V1t=vIe,hvn=uvn(function(s,t){if(s==null)return[];var n=t.length;return n>1&&V1t(s,t[0],t[1])?t=[]:n>2&&V1t(t[0],t[1],t[2])&&(t=[t[0]]),dvn(s,cvn(t,1),[])}),mvn=hvn;const pst=_d(mvn);function Ite(s){"@babel/helpers - typeof";return Ite=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},Ite(s)}function ZHe(){return ZHe=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(sZ,"-left"),ei(n)&&t&&ei(t.x)&&n=t.y),"".concat(sZ,"-top"),ei(r)&&t&&ei(t.y)&&ry?Math.max(u,c[r]):Math.max(h,c[r])}function Avn(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 Evn(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=W1t({allowEscapeViewBox:t,coordinate:n,key:"x",offsetTopLeft:r,position:a,reverseDirection:i,tooltipDimension:l.width,viewBox:c,viewBoxDimension:c.width}),h=W1t({allowEscapeViewBox:t,coordinate:n,key:"y",offsetTopLeft:r,position:a,reverseDirection:i,tooltipDimension:l.height,viewBox:c,viewBoxDimension:c.height}),d=Avn({translateX:u,translateY:h,useTranslate3d:o})):d=Svn,{cssProperties:d,cssClasses:Cvn({translateX:u,translateY:h,coordinate:n})}}function KH(s){"@babel/helpers - typeof";return KH=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},KH(s)}function K1t(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 Y1t(s){for(var t=1;tZ1t||Math.abs(r.height-this.state.lastBoundingBox.height)>Z1t)&&this.setState({lastBoundingBox:{width:r.width,height:r.height}})}else(this.state.lastBoundingBox.width!==-1||this.state.lastBoundingBox.height!==-1)&&this.setState({lastBoundingBox:{width:-1,height:-1}})}},{key:"componentDidMount",value:function(){document.addEventListener("keydown",this.handleKeyDown),this.updateBBox()}},{key:"componentWillUnmount",value:function(){document.removeEventListener("keydown",this.handleKeyDown)}},{key:"componentDidUpdate",value:function(){var r,a;this.props.active&&this.updateBBox(),this.state.dismissed&&(((r=this.props.coordinate)===null||r===void 0?void 0:r.x)!==this.state.dismissedAtCoordinate.x||((a=this.props.coordinate)===null||a===void 0?void 0:a.y)!==this.state.dismissedAtCoordinate.y)&&(this.state.dismissed=!1)}},{key:"render",value:function(){var r=this,a=this.props,i=a.active,l=a.allowEscapeViewBox,o=a.animationDuration,c=a.animationEasing,d=a.children,u=a.coordinate,h=a.hasPayload,m=a.isAnimationActive,p=a.offset,f=a.position,y=a.reverseDirection,v=a.useTranslate3d,g=a.viewBox,b=a.wrapperStyle,j=Evn({allowEscapeViewBox:l,coordinate:u,offsetTopLeft:p,position:f,reverseDirection:y,tooltipBox:this.state.lastBoundingBox,useTranslate3d:v,viewBox:g}),S=j.cssClasses,C=j.cssProperties,E=Y1t(Y1t({transition:m&&i?"transform ".concat(o,"ms ").concat(c):void 0},C),{},{pointerEvents:"none",visibility:!this.state.dismissed&&i&&h?"visible":"hidden",position:"absolute",top:0,left:0},b);return Dt.createElement("div",{tabIndex:-1,className:S,style:E,ref:function(M){r.wrapperNode=M}},d)}}])}(_.PureComponent),zvn=function(){return!(typeof window<"u"&&window.document&&window.document.createElement&&window.setTimeout)},_S={isSsr:zvn(),get:function(t){return _S[t]},set:function(t,n){if(typeof t=="string")_S[t]=n;else{var r=Object.keys(t);r&&r.length&&r.forEach(function(a){_S[a]=t[a]})}}};function YH(s){"@babel/helpers - typeof";return YH=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},YH(s)}function X1t(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 Q1t(s){for(var t=1;t0;return Dt.createElement(Ovn,{allowEscapeViewBox:l,animationDuration:o,animationEasing:c,isAnimationActive:m,active:i,coordinate:u,hasPayload:E,offset:p,position:v,reverseDirection:g,useTranslate3d:b,viewBox:j,wrapperStyle:S},Yvn(d,Q1t(Q1t({},this.props),{},{payload:C})))}}])}(_.PureComponent);fst(Mf,"displayName","Tooltip");fst(Mf,"defaultProps",{accessibilityLayer:!1,allowEscapeViewBox:{x:!1,y:!1},animationDuration:400,animationEasing:"ease",contentStyle:{},coordinate:{x:0,y:0},cursor:!0,cursorStyle:{},filterNull:!0,isAnimationActive:!_S.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 Zvn=CC,Xvn=function(){return Zvn.Date.now()},Qvn=Xvn,Jvn=/\s/;function e1n(s){for(var t=s.length;t--&&Jvn.test(s.charAt(t)););return t}var t1n=e1n,s1n=t1n,n1n=/^\s+/;function r1n(s){return s&&s.slice(0,s1n(s)+1).replace(n1n,"")}var a1n=r1n,i1n=a1n,J1t=CL,o1n=SW,ebt=NaN,l1n=/^[-+]0x[0-9a-f]+$/i,c1n=/^0b[01]+$/i,d1n=/^0o[0-7]+$/i,u1n=parseInt;function h1n(s){if(typeof s=="number")return s;if(o1n(s))return ebt;if(J1t(s)){var t=typeof s.valueOf=="function"?s.valueOf():s;s=J1t(t)?t+"":t}if(typeof s!="string")return s===0?s:+s;s=i1n(s);var n=c1n.test(s);return n||d1n.test(s)?u1n(s.slice(2),n?2:8):l1n.test(s)?ebt:+s}var HHt=h1n,m1n=CL,w9e=Qvn,tbt=HHt,p1n="Expected a function",f1n=Math.max,x1n=Math.min;function g1n(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(p1n);t=tbt(t)||0,m1n(n)&&(u=!!n.leading,h="maxWait"in n,i=h?f1n(tbt(n.maxWait)||0,t):i,m="trailing"in n?!!n.trailing:m);function p(E){var P=r,M=a;return r=a=void 0,d=E,l=s.apply(M,P),l}function f(E){return d=E,o=setTimeout(g,t),u?p(E):l}function y(E){var P=E-c,M=E-d,I=t-P;return h?x1n(I,i-M):I}function v(E){var P=E-c,M=E-d;return c===void 0||P>=t||P<0||h&&M>=i}function g(){var E=w9e();if(v(E))return b(E);o=setTimeout(g,y(E))}function b(E){return o=void 0,m&&r?p(E):(r=a=void 0,l)}function j(){o!==void 0&&clearTimeout(o),d=0,r=c=a=o=void 0}function S(){return o===void 0?l:b(w9e())}function C(){var E=w9e(),P=v(E);if(r=arguments,a=this,c=E,P){if(o===void 0)return f(c);if(h)return clearTimeout(o),o=setTimeout(g,t),p(c)}return o===void 0&&(o=setTimeout(g,t)),l}return C.cancel=j,C.flush=S,C}var y1n=g1n,v1n=y1n,b1n=CL,_1n="Expected a function";function w1n(s,t,n){var r=!0,a=!0;if(typeof s!="function")throw new TypeError(_1n);return b1n(n)&&(r="leading"in n?!!n.leading:r,a="trailing"in n?!!n.trailing:a),v1n(s,t,{leading:r,maxWait:t,trailing:a})}var j1n=w1n;const GHt=_d(j1n);function Rte(s){"@babel/helpers - typeof";return Rte=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Rte(s)}function sbt(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 bce(s){for(var t=1;ts.length)&&(t=s.length);for(var n=0,r=new Array(t);n0&&(G=GHt(G,y,{trailing:!0,leading:!1}));var $=new ResizeObserver(G),H=C.current.getBoundingClientRect(),Y=H.width,Z=H.height;return O(Y,Z),$.observe(C.current),function(){$.disconnect()}},[O,y]);var V=_.useMemo(function(){var G=I.containerWidth,$=I.containerHeight;if(G<0||$<0)return null;bS(_F(l)||_F(c),`The width(%s) and height(%s) are both fixed numbers, maybe you don't need to use a ResponsiveContainer.`,l,c),bS(!n||n>0,"The aspect(%s) must be greater than zero.",n);var H=_F(l)?G:l,Y=_F(c)?$:c;n&&n>0&&(H?Y=H/n:Y&&(H=Y*n),m&&Y>m&&(Y=m)),bS(H>0||Y>0,`The width(%s) and height(%s) of chart should be greater than 0, please check the style of container, or the props width(%s) and height(%s), or add a minWidth(%s) or minHeight(%s) or use aspect(%s) to control the height and width.`,H,Y,l,c,u,h,n);var Z=!Array.isArray(p)&&sE(p.type).endsWith("Chart");return Dt.Children.map(p,function(ne){return Dt.isValidElement(ne)?_.cloneElement(ne,bce({width:H,height:Y},Z?{style:bce({height:"100%",width:"100%",maxHeight:Y,maxWidth:H},ne.props.style)}:{})):ne})},[n,p,c,m,h,u,I,l]);return Dt.createElement("div",{id:v?"".concat(v):void 0,className:jc("recharts-responsive-container",g),style:bce(bce({},S),{},{width:l,height:c,minWidth:u,minHeight:h,maxHeight:m}),ref:C},V)}),tz=function(t){return null};tz.displayName="Cell";function Fte(s){"@babel/helpers - typeof";return Fte=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Fte(s)}function rbt(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 eGe(s){for(var t=1;t1&&arguments[1]!==void 0?arguments[1]:{};if(t==null||_S.isSsr)return{width:0,height:0};var r=F1n(n),a=JSON.stringify({text:t,copyStyle:r});if(DB.widthCache[a])return DB.widthCache[a];try{var i=document.getElementById(abt);i||(i=document.createElement("span"),i.setAttribute("id",abt),i.setAttribute("aria-hidden","true"),document.body.appendChild(i));var l=eGe(eGe({},R1n),r);Object.assign(i.style,l),i.textContent="".concat(t);var o=i.getBoundingClientRect(),c={width:o.width,height:o.height};return DB.widthCache[a]=c,++DB.cacheCount>D1n&&(DB.cacheCount=0,DB.widthCache={}),c}catch{return{width:0,height:0}}},O1n=function(t){return{top:t.top+window.scrollY-document.documentElement.clientTop,left:t.left+window.scrollX-document.documentElement.clientLeft}};function Ote(s){"@babel/helpers - typeof";return Ote=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Ote(s)}function VEe(s,t){return q1n(s)||U1n(s,t)||B1n(s,t)||z1n()}function z1n(){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 B1n(s,t){if(s){if(typeof s=="string")return ibt(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 ibt(s,t)}}function ibt(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 sbn(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}function hbt(s,t){return ibn(s)||abn(s,t)||rbn(s,t)||nbn()}function nbn(){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 rbn(s,t){if(s){if(typeof s=="string")return mbt(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 mbt(s,t)}}function mbt(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 H.reduce(function(Y,Z){var ne=Z.word,ce=Z.width,ie=Y[Y.length-1];if(ie&&(a==null||i||ie.width+ce+rZ.width?Y:Z})};if(!u)return p;for(var y="…",v=function(H){var Y=h.slice(0,H),Z=ZHt({breakAll:d,style:c,children:Y+y}).wordsWithComputedWidth,ne=m(Z),ce=ne.length>l||f(ne).width>Number(a);return[ce,ne]},g=0,b=h.length-1,j=0,S;g<=b&&j<=h.length-1;){var C=Math.floor((g+b)/2),E=C-1,P=v(E),M=hbt(P,2),I=M[0],D=M[1],O=v(C),V=hbt(O,1),G=V[0];if(!I&&!G&&(g=C+1),I&&G&&(b=C-1),!I&&G){S=D;break}j++}return S||p},pbt=function(t){var n=mc(t)?[]:t.toString().split(YHt);return[{words:n}]},lbn=function(t){var n=t.width,r=t.scaleToFit,a=t.children,i=t.style,l=t.breakAll,o=t.maxLines;if((n||r)&&!_S.isSsr){var c,d,u=ZHt({breakAll:l,children:a,style:i});if(u){var h=u.wordsWithComputedWidth,m=u.spaceWidth;c=h,d=m}else return pbt(a);return obn({breakAll:l,children:a,maxLines:o,style:i},c,d,n,r)}return pbt(a)},fbt="#808080",d9=function(t){var n=t.x,r=n===void 0?0:n,a=t.y,i=a===void 0?0:a,l=t.lineHeight,o=l===void 0?"1em":l,c=t.capHeight,d=c===void 0?"0.71em":c,u=t.scaleToFit,h=u===void 0?!1:u,m=t.textAnchor,p=m===void 0?"start":m,f=t.verticalAnchor,y=f===void 0?"end":f,v=t.fill,g=v===void 0?fbt:v,b=ubt(t,ebn),j=_.useMemo(function(){return lbn({breakAll:b.breakAll,children:b.children,maxLines:b.maxLines,scaleToFit:h,style:b.style,width:b.width})},[b.breakAll,b.children,b.maxLines,h,b.style,b.width]),S=b.dx,C=b.dy,E=b.angle,P=b.className,M=b.breakAll,I=ubt(b,tbn);if(!j0(r)||!j0(i))return null;var D=r+(ei(S)?S:0),O=i+(ei(C)?C:0),V;switch(y){case"start":V=j9e("calc(".concat(d,")"));break;case"middle":V=j9e("calc(".concat((j.length-1)/2," * -").concat(o," + (").concat(d," / 2))"));break;default:V=j9e("calc(".concat(j.length-1," * -").concat(o,")"));break}var G=[];if(h){var $=j[0].width,H=b.width;G.push("scale(".concat((ei(H)?H/$:1)/$,")"))}return E&&G.push("rotate(".concat(E,", ").concat(D,", ").concat(O,")")),G.length&&(I.transform=G.join(" ")),Dt.createElement("text",tGe({},$o(I,!0),{x:D,y:O,className:jc("recharts-text",P),textAnchor:p,fill:g.includes("url")?fbt:g}),j.map(function(Y,Z){var ne=Y.words.join(M?"":" ");return Dt.createElement("tspan",{x:D,dy:Z===0?V:o,key:"".concat(ne,"-").concat(Z)},ne)}))};function xP(s,t){return s==null||t==null?NaN:st?1:s>=t?0:NaN}function cbn(s,t){return s==null||t==null?NaN:ts?1:t>=s?0:NaN}function xst(s){let t,n,r;s.length!==2?(t=xP,n=(o,c)=>xP(s(o),c),r=(o,c)=>s(o)-c):(t=s===xP||s===cbn?s:dbn,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 dbn(){return 0}function XHt(s){return s===null?NaN:+s}function*ubn(s,t){for(let n of s)n!=null&&(n=+n)>=n&&(yield n)}const hbn=xst(xP),Sae=hbn.right;xst(XHt).center;class xbt extends Map{constructor(t,n=fbn){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(gbt(this,t))}has(t){return super.has(gbt(this,t))}set(t,n){return super.set(mbn(this,t),n)}delete(t){return super.delete(pbn(this,t))}}function gbt({_intern:s,_key:t},n){const r=t(n);return s.has(r)?s.get(r):n}function mbn({_intern:s,_key:t},n){const r=t(n);return s.has(r)?s.get(r):(s.set(r,n),n)}function pbn({_intern:s,_key:t},n){const r=t(n);return s.has(r)&&(n=s.get(r),s.delete(r)),n}function fbn(s){return s!==null&&typeof s=="object"?s.valueOf():s}function xbn(s=xP){if(s===xP)return QHt;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 QHt(s,t){return(s==null||!(s>=s))-(t==null||!(t>=t))||(st?1:0)}const gbn=Math.sqrt(50),ybn=Math.sqrt(10),vbn=Math.sqrt(2);function HEe(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>=gbn?10:i>=ybn?5:i>=vbn?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 vbt(s,t){let n;for(const r of s)r!=null&&(n>r||n===void 0&&r>=r)&&(n=r);return n}function JHt(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?QHt:xbn(a);r>n;){if(r-n>600){const c=r-n+1,d=t-n+1,u=Math.log(c),h=.5*Math.exp(2*u/3),m=.5*Math.sqrt(u*h*(c-h)/c)*(d-c/2<0?-1:1),p=Math.max(n,Math.floor(t-d*h/c+m)),f=Math.min(r,Math.floor(t+(c-d)*h/c+m));JHt(s,t,p,f,a)}const i=s[t];let l=n,o=r;for(nZ(s,n,t),a(s[r],i)>0&&nZ(s,n,r);l0;)--o}a(s[n],i)===0?nZ(s,n,o):(++o,nZ(s,o,r)),o<=t&&(n=o+1),t<=o&&(r=o-1)}return s}function nZ(s,t,n){const r=s[t];s[t]=s[n],s[n]=r}function bbn(s,t,n){if(s=Float64Array.from(ubn(s)),!(!(r=s.length)||isNaN(t=+t))){if(t<=0||r<2)return vbt(s);if(t>=1)return ybt(s);var r,a=(r-1)*t,i=Math.floor(a),l=ybt(JHt(s,i).subarray(0,i+1)),o=vbt(s.subarray(i+1));return l+(o-l)*(a-i)}}function _bn(s,t,n=XHt){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 wbn(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?wce(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?wce(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=Nbn.exec(s))?new S_(t[1],t[2],t[3],1):(t=kbn.exec(s))?new S_(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=Sbn.exec(s))?wce(t[1],t[2],t[3],t[4]):(t=Cbn.exec(s))?wce(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=Abn.exec(s))?Sbt(t[1],t[2]/100,t[3]/100,1):(t=Ebn.exec(s))?Sbt(t[1],t[2]/100,t[3]/100,t[4]):bbt.hasOwnProperty(s)?jbt(bbt[s]):s==="transparent"?new S_(NaN,NaN,NaN,0):null}function jbt(s){return new S_(s>>16&255,s>>8&255,s&255,1)}function wce(s,t,n,r){return r<=0&&(s=t=n=NaN),new S_(s,t,n,r)}function Pbn(s){return s instanceof Cae||(s=qte(s)),s?(s=s.rgb(),new S_(s.r,s.g,s.b,s.opacity)):new S_}function iGe(s,t,n,r){return arguments.length===1?Pbn(s):new S_(s,t,n,r??1)}function S_(s,t,n,r){this.r=+s,this.g=+t,this.b=+n,this.opacity=+r}yst(S_,iGe,tGt(Cae,{brighter(s){return s=s==null?GEe:Math.pow(GEe,s),new S_(this.r*s,this.g*s,this.b*s,this.opacity)},darker(s){return s=s==null?Bte:Math.pow(Bte,s),new S_(this.r*s,this.g*s,this.b*s,this.opacity)},rgb(){return this},clamp(){return new S_(k7(this.r),k7(this.g),k7(this.b),WEe(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:Nbt,formatHex:Nbt,formatHex8:Lbn,formatRgb:kbt,toString:kbt}));function Nbt(){return`#${wF(this.r)}${wF(this.g)}${wF(this.b)}`}function Lbn(){return`#${wF(this.r)}${wF(this.g)}${wF(this.b)}${wF((isNaN(this.opacity)?1:this.opacity)*255)}`}function kbt(){const s=WEe(this.opacity);return`${s===1?"rgb(":"rgba("}${k7(this.r)}, ${k7(this.g)}, ${k7(this.b)}${s===1?")":`, ${s})`}`}function WEe(s){return isNaN(s)?1:Math.max(0,Math.min(1,s))}function k7(s){return Math.max(0,Math.min(255,Math.round(s)||0))}function wF(s){return s=k7(s),(s<16?"0":"")+s.toString(16)}function Sbt(s,t,n,r){return r<=0?s=t=n=NaN:n<=0||n>=1?s=t=NaN:t<=0&&(s=NaN),new nS(s,t,n,r)}function sGt(s){if(s instanceof nS)return new nS(s.h,s.s,s.l,s.opacity);if(s instanceof Cae||(s=qte(s)),!s)return new nS;if(s instanceof nS)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 nS(l,o,c,s.opacity)}function Ibn(s,t,n,r){return arguments.length===1?sGt(s):new nS(s,t,n,r??1)}function nS(s,t,n,r){this.h=+s,this.s=+t,this.l=+n,this.opacity=+r}yst(nS,Ibn,tGt(Cae,{brighter(s){return s=s==null?GEe:Math.pow(GEe,s),new nS(this.h,this.s,this.l*s,this.opacity)},darker(s){return s=s==null?Bte:Math.pow(Bte,s),new nS(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 S_(N9e(s>=240?s-240:s+120,a,r),N9e(s,a,r),N9e(s<120?s+240:s-120,a,r),this.opacity)},clamp(){return new nS(Cbt(this.h),jce(this.s),jce(this.l),WEe(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=WEe(this.opacity);return`${s===1?"hsl(":"hsla("}${Cbt(this.h)}, ${jce(this.s)*100}%, ${jce(this.l)*100}%${s===1?")":`, ${s})`}`}}));function Cbt(s){return s=(s||0)%360,s<0?s+360:s}function jce(s){return Math.max(0,Math.min(1,s||0))}function N9e(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 vst=s=>()=>s;function Dbn(s,t){return function(n){return s+n*t}}function Rbn(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 Fbn(s){return(s=+s)==1?nGt:function(t,n){return n-t?Rbn(t,n,s):vst(isNaN(t)?n:t)}}function nGt(s,t){var n=t-s;return n?Dbn(s,n):vst(isNaN(s)?t:s)}const Abt=function s(t){var n=Fbn(t);function r(a,i){var l=n((a=iGe(a)).r,(i=iGe(i)).r),o=n(a.g,i.g),c=n(a.b,i.b),d=nGt(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 Obn(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:KEe(r,a)})),n=k9e.lastIndex;return nt&&(n=s,s=t,t=n),function(r){return Math.max(s,Math.min(t,r))}}function Ybn(s,t,n){var r=s[0],a=s[1],i=t[0],l=t[1];return a2?Zbn:Ybn,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),KEe)))(m)))},h.domain=function(m){return arguments.length?(s=Array.from(m,YEe),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=bst,u()},h.clamp=function(m){return arguments.length?(l=m?!0:gb,u()):l!==gb},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 _st(){return bIe()(gb,gb)}function Xbn(s){return Math.abs(s=Math.round(s))>=1e21?s.toLocaleString("en").replace(/,/g,""):s.toString(10)}function ZEe(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 ZH(s){return s=ZEe(Math.abs(s)),s?s[1]:NaN}function Qbn(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 Jbn(s){return function(t){return t.replace(/[0-9]/g,function(n){return s[+n]})}}var e_n=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function $te(s){if(!(t=e_n.exec(s)))throw new Error("invalid format: "+s);var t;return new wst({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]})}$te.prototype=wst.prototype;function wst(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+""}wst.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 t_n(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 rGt;function s_n(s,t){var n=ZEe(s,t);if(!n)return s+"";var r=n[0],a=n[1],i=a-(rGt=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")+ZEe(s,Math.max(0,t+i-1))[0]}function Tbt(s,t){var n=ZEe(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 Mbt={"%":(s,t)=>(s*100).toFixed(t),b:s=>Math.round(s).toString(2),c:s=>s+"",d:Xbn,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)=>Tbt(s*100,t),r:Tbt,s:s_n,X:s=>Math.round(s).toString(16).toUpperCase(),x:s=>Math.round(s).toString(16)};function Pbt(s){return s}var Lbt=Array.prototype.map,Ibt=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];function n_n(s){var t=s.grouping===void 0||s.thousands===void 0?Pbt:Qbn(Lbt.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?Pbt:Jbn(Lbt.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=$te(h);var m=h.fill,p=h.align,f=h.sign,y=h.symbol,v=h.zero,g=h.width,b=h.comma,j=h.precision,S=h.trim,C=h.type;C==="n"?(b=!0,C="g"):Mbt[C]||(j===void 0&&(j=12),S=!0,C="g"),(v||m==="0"&&p==="=")&&(v=!0,m="0",p="=");var E=y==="$"?n:y==="#"&&/[boxX]/.test(C)?"0"+C.toLowerCase():"",P=y==="$"?r:/[%p]/.test(C)?l:"",M=Mbt[C],I=/[defgprs%]/.test(C);j=j===void 0?6:/[gprs]/.test(C)?Math.max(1,Math.min(21,j)):Math.max(0,Math.min(20,j));function D(O){var V=E,G=P,$,H,Y;if(C==="c")G=M(O)+G,O="";else{O=+O;var Z=O<0||1/O<0;if(O=isNaN(O)?c:M(Math.abs(O),j),S&&(O=t_n(O)),Z&&+O==0&&f!=="+"&&(Z=!1),V=(Z?f==="("?f:o:f==="-"||f==="("?"":f)+V,G=(C==="s"?Ibt[8+rGt/3]:"")+G+(Z&&f==="("?")":""),I){for($=-1,H=O.length;++$Y||Y>57){G=(Y===46?a+O.slice($+1):O.slice($))+G,O=O.slice(0,$);break}}}b&&!v&&(O=t(O,1/0));var ne=V.length+O.length+G.length,ce=ne>1)+V+O+G+ce.slice(ne);break;default:O=ce+V+O+G;break}return i(O)}return D.toString=function(){return h+""},D}function u(h,m){var p=d((h=$te(h),h.type="f",h)),f=Math.max(-8,Math.min(8,Math.floor(ZH(m)/3)))*3,y=Math.pow(10,-f),v=Ibt[8+f/3];return function(g){return p(y*g)+v}}return{format:d,formatPrefix:u}}var Nce,jst,aGt;r_n({thousands:",",grouping:[3],currency:["$",""]});function r_n(s){return Nce=n_n(s),jst=Nce.format,aGt=Nce.formatPrefix,Nce}function a_n(s){return Math.max(0,-ZH(Math.abs(s)))}function i_n(s,t){return Math.max(0,Math.max(-8,Math.min(8,Math.floor(ZH(t)/3)))*3-ZH(Math.abs(s)))}function o_n(s,t){return s=Math.abs(s),t=Math.abs(t)-s,Math.max(0,ZH(t)-ZH(s))+1}function iGt(s,t,n,r){var a=rGe(s,t,n),i;switch(r=$te(r??",f"),r.type){case"s":{var l=Math.max(Math.abs(s),Math.abs(t));return r.precision==null&&!isNaN(i=i_n(a,l))&&(r.precision=i),aGt(r,l)}case"":case"e":case"g":case"p":case"r":{r.precision==null&&!isNaN(i=o_n(a,Math.max(Math.abs(s),Math.abs(t))))&&(r.precision=i-(r.type==="e"));break}case"f":case"%":{r.precision==null&&!isNaN(i=a_n(a))&&(r.precision=i-(r.type==="%")*2);break}}return jst(r)}function AL(s){var t=s.domain;return s.ticks=function(n){var r=t();return sGe(r[0],r[r.length-1],n??10)},s.tickFormat=function(n,r){var a=t();return iGt(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=nGe(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 XEe(){var s=_st();return s.copy=function(){return Aae(s,XEe())},qN.apply(s,arguments),AL(s)}function oGt(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,YEe),n):s.slice()},n.unknown=function(r){return arguments.length?(t=r,n):t},n.copy=function(){return oGt(s).unknown(t)},s=arguments.length?Array.from(s,YEe):[0,1],AL(n)}function lGt(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 h_n(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 Fbt(s){return(t,n)=>-s(-t,n)}function Nst(s){const t=s(Dbt,Rbt),n=t.domain;let r=10,a,i;function l(){return a=h_n(r),i=u_n(r),n()[0]<0?(a=Fbt(a),i=Fbt(i),s(l_n,c_n)):s(Dbt,Rbt),t}return t.base=function(o){return arguments.length?(r=+o,l()):r},t.domain=function(o){return arguments.length?(n(o),l()):n()},t.ticks=o=>{const c=n();let d=c[0],u=c[c.length-1];const h=u0){for(;m<=p;++m)for(f=1;fu)break;g.push(y)}}else for(;m<=p;++m)for(f=r-1;f>=1;--f)if(y=m>0?f/i(-m):f*i(m),!(yu)break;g.push(y)}g.length*2{if(o==null&&(o=10),c==null&&(c=r===10?"s":","),typeof c!="function"&&(!(r%1)&&(c=$te(c)).precision==null&&(c.trim=!0),c=jst(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(lGt(n(),{floor:o=>i(Math.floor(a(o))),ceil:o=>i(Math.ceil(a(o)))})),t}function cGt(){const s=Nst(bIe()).domain([1,10]);return s.copy=()=>Aae(s,cGt()).base(s.base()),qN.apply(s,arguments),s}function Obt(s){return function(t){return Math.sign(t)*Math.log1p(Math.abs(t/s))}}function zbt(s){return function(t){return Math.sign(t)*Math.expm1(Math.abs(t))*s}}function kst(s){var t=1,n=s(Obt(t),zbt(t));return n.constant=function(r){return arguments.length?s(Obt(t=+r),zbt(t)):t},AL(n)}function dGt(){var s=kst(bIe());return s.copy=function(){return Aae(s,dGt()).constant(s.constant())},qN.apply(s,arguments)}function Bbt(s){return function(t){return t<0?-Math.pow(-t,s):Math.pow(t,s)}}function m_n(s){return s<0?-Math.sqrt(-s):Math.sqrt(s)}function p_n(s){return s<0?-s*s:s*s}function Sst(s){var t=s(gb,gb),n=1;function r(){return n===1?s(gb,gb):n===.5?s(m_n,p_n):s(Bbt(n),Bbt(1/n))}return t.exponent=function(a){return arguments.length?(n=+a,r()):n},AL(t)}function Cst(){var s=Sst(bIe());return s.copy=function(){return Aae(s,Cst()).exponent(s.exponent())},qN.apply(s,arguments),s}function f_n(){return Cst.apply(null,arguments).exponent(.5)}function Ubt(s){return Math.sign(s)*s*s}function x_n(s){return Math.sign(s)*Math.sqrt(Math.abs(s))}function uGt(){var s=_st(),t=[0,1],n=!1,r;function a(i){var l=x_n(s(i));return isNaN(l)?r:n?Math.round(l):l}return a.invert=function(i){return s.invert(Ubt(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,YEe)).map(Ubt)),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 uGt(s.domain(),t).round(n).clamp(s.clamp()).unknown(r)},qN.apply(a,arguments),AL(a)}function hGt(){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 mGt().domain([s,t]).range(a).unknown(i)},qN.apply(AL(l),arguments)}function pGt(){var s=[.5],t=[0,1],n,r=1;function a(i){return i!=null&&i<=i?t[Sae(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 pGt().domain(s).range(t).unknown(n)},qN.apply(a,arguments)}const S9e=new Date,C9e=new Date;function z0(s,t,n,r){function a(i){return s(i=arguments.length===0?new Date:new Date(+i)),i}return a.floor=i=>(s(i=new Date(+i)),i),a.ceil=i=>(s(i=new Date(i-1)),t(i,1),s(i),i),a.round=i=>{const l=a(i),o=a.ceil(i);return i-l(t(i=new Date(+i),l==null?1:Math.floor(l)),i),a.range=(i,l,o)=>{const c=[];if(i=a.ceil(i),o=o==null?1:Math.floor(o),!(i0))return c;let d;do c.push(d=new Date(+i)),t(i,o),s(i);while(dz0(l=>{if(l>=l)for(;s(l),!i(l);)l.setTime(l-1)},(l,o)=>{if(l>=l)if(o<0)for(;++o<=0;)for(;t(l,-1),!i(l););else for(;--o>=0;)for(;t(l,1),!i(l););}),n&&(a.count=(i,l)=>(S9e.setTime(+i),C9e.setTime(+l),s(S9e),s(C9e),Math.floor(n(S9e,C9e))),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 QEe=z0(()=>{},(s,t)=>{s.setTime(+s+t)},(s,t)=>t-s);QEe.every=s=>(s=Math.floor(s),!isFinite(s)||!(s>0)?null:s>1?z0(t=>{t.setTime(Math.floor(t/s)*s)},(t,n)=>{t.setTime(+t+n*s)},(t,n)=>(n-t)/s):QEe);QEe.range;const RA=1e3,rN=RA*60,FA=rN*60,wE=FA*24,Ast=wE*7,qbt=wE*30,A9e=wE*365,jF=z0(s=>{s.setTime(s-s.getMilliseconds())},(s,t)=>{s.setTime(+s+t*RA)},(s,t)=>(t-s)/RA,s=>s.getUTCSeconds());jF.range;const Est=z0(s=>{s.setTime(s-s.getMilliseconds()-s.getSeconds()*RA)},(s,t)=>{s.setTime(+s+t*rN)},(s,t)=>(t-s)/rN,s=>s.getMinutes());Est.range;const Tst=z0(s=>{s.setUTCSeconds(0,0)},(s,t)=>{s.setTime(+s+t*rN)},(s,t)=>(t-s)/rN,s=>s.getUTCMinutes());Tst.range;const Mst=z0(s=>{s.setTime(s-s.getMilliseconds()-s.getSeconds()*RA-s.getMinutes()*rN)},(s,t)=>{s.setTime(+s+t*FA)},(s,t)=>(t-s)/FA,s=>s.getHours());Mst.range;const Pst=z0(s=>{s.setUTCMinutes(0,0,0)},(s,t)=>{s.setTime(+s+t*FA)},(s,t)=>(t-s)/FA,s=>s.getUTCHours());Pst.range;const Eae=z0(s=>s.setHours(0,0,0,0),(s,t)=>s.setDate(s.getDate()+t),(s,t)=>(t-s-(t.getTimezoneOffset()-s.getTimezoneOffset())*rN)/wE,s=>s.getDate()-1);Eae.range;const _Ie=z0(s=>{s.setUTCHours(0,0,0,0)},(s,t)=>{s.setUTCDate(s.getUTCDate()+t)},(s,t)=>(t-s)/wE,s=>s.getUTCDate()-1);_Ie.range;const fGt=z0(s=>{s.setUTCHours(0,0,0,0)},(s,t)=>{s.setUTCDate(s.getUTCDate()+t)},(s,t)=>(t-s)/wE,s=>Math.floor(s/wE));fGt.range;function sz(s){return z0(t=>{t.setDate(t.getDate()-(t.getDay()+7-s)%7),t.setHours(0,0,0,0)},(t,n)=>{t.setDate(t.getDate()+n*7)},(t,n)=>(n-t-(n.getTimezoneOffset()-t.getTimezoneOffset())*rN)/Ast)}const wIe=sz(0),JEe=sz(1),g_n=sz(2),y_n=sz(3),XH=sz(4),v_n=sz(5),b_n=sz(6);wIe.range;JEe.range;g_n.range;y_n.range;XH.range;v_n.range;b_n.range;function nz(s){return z0(t=>{t.setUTCDate(t.getUTCDate()-(t.getUTCDay()+7-s)%7),t.setUTCHours(0,0,0,0)},(t,n)=>{t.setUTCDate(t.getUTCDate()+n*7)},(t,n)=>(n-t)/Ast)}const jIe=nz(0),eTe=nz(1),__n=nz(2),w_n=nz(3),QH=nz(4),j_n=nz(5),N_n=nz(6);jIe.range;eTe.range;__n.range;w_n.range;QH.range;j_n.range;N_n.range;const Lst=z0(s=>{s.setDate(1),s.setHours(0,0,0,0)},(s,t)=>{s.setMonth(s.getMonth()+t)},(s,t)=>t.getMonth()-s.getMonth()+(t.getFullYear()-s.getFullYear())*12,s=>s.getMonth());Lst.range;const Ist=z0(s=>{s.setUTCDate(1),s.setUTCHours(0,0,0,0)},(s,t)=>{s.setUTCMonth(s.getUTCMonth()+t)},(s,t)=>t.getUTCMonth()-s.getUTCMonth()+(t.getUTCFullYear()-s.getUTCFullYear())*12,s=>s.getUTCMonth());Ist.range;const jE=z0(s=>{s.setMonth(0,1),s.setHours(0,0,0,0)},(s,t)=>{s.setFullYear(s.getFullYear()+t)},(s,t)=>t.getFullYear()-s.getFullYear(),s=>s.getFullYear());jE.every=s=>!isFinite(s=Math.floor(s))||!(s>0)?null:z0(t=>{t.setFullYear(Math.floor(t.getFullYear()/s)*s),t.setMonth(0,1),t.setHours(0,0,0,0)},(t,n)=>{t.setFullYear(t.getFullYear()+n*s)});jE.range;const NE=z0(s=>{s.setUTCMonth(0,1),s.setUTCHours(0,0,0,0)},(s,t)=>{s.setUTCFullYear(s.getUTCFullYear()+t)},(s,t)=>t.getUTCFullYear()-s.getUTCFullYear(),s=>s.getUTCFullYear());NE.every=s=>!isFinite(s=Math.floor(s))||!(s>0)?null:z0(t=>{t.setUTCFullYear(Math.floor(t.getUTCFullYear()/s)*s),t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0)},(t,n)=>{t.setUTCFullYear(t.getUTCFullYear()+n*s)});NE.range;function xGt(s,t,n,r,a,i){const l=[[jF,1,RA],[jF,5,5*RA],[jF,15,15*RA],[jF,30,30*RA],[i,1,rN],[i,5,5*rN],[i,15,15*rN],[i,30,30*rN],[a,1,FA],[a,3,3*FA],[a,6,6*FA],[a,12,12*FA],[r,1,wE],[r,2,2*wE],[n,1,Ast],[t,1,qbt],[t,3,3*qbt],[s,1,A9e]];function o(d,u,h){const m=uv).right(l,m);if(p===l.length)return s.every(rGe(d/A9e,u/A9e,h));if(p===0)return QEe.every(Math.max(rGe(d,u,h),1));const[f,y]=l[m/l[p-1][2]53)return null;"w"in ke||(ke.w=1),"Z"in ke?(Se=T9e(rZ(ke.y,0,1)),Fe=Se.getUTCDay(),Se=Fe>4||Fe===0?eTe.ceil(Se):eTe(Se),Se=_Ie.offset(Se,(ke.V-1)*7),ke.y=Se.getUTCFullYear(),ke.m=Se.getUTCMonth(),ke.d=Se.getUTCDate()+(ke.w+6)%7):(Se=E9e(rZ(ke.y,0,1)),Fe=Se.getDay(),Se=Fe>4||Fe===0?JEe.ceil(Se):JEe(Se),Se=Eae.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),Fe="Z"in ke?T9e(rZ(ke.y,0,1)).getUTCDay():E9e(rZ(ke.y,0,1)).getDay(),ke.m=0,ke.d="W"in ke?(ke.w+6)%7+ke.W*7-(Fe+5)%7:ke.w+ke.U*7-(Fe+6)%7);return"Z"in ke?(ke.H+=ke.Z/100|0,ke.M+=ke.Z%100,T9e(ke)):E9e(ke)}}function M(Ae,Pe,ze,ke){for(var Ze=0,Se=Pe.length,Fe=ze.length,Ne,Ye;Ze=Fe)return-1;if(Ne=Pe.charCodeAt(Ze++),Ne===37){if(Ne=Pe.charAt(Ze++),Ye=C[Ne in $bt?Pe.charAt(Ze++):Ne],!Ye||(ke=Ye(Ae,ze,ke))<0)return-1}else if(Ne!=ze.charCodeAt(ke++))return-1}return ke}function I(Ae,Pe,ze){var ke=d.exec(Pe.slice(ze));return ke?(Ae.p=u.get(ke[0].toLowerCase()),ze+ke[0].length):-1}function D(Ae,Pe,ze){var ke=p.exec(Pe.slice(ze));return ke?(Ae.w=f.get(ke[0].toLowerCase()),ze+ke[0].length):-1}function O(Ae,Pe,ze){var ke=h.exec(Pe.slice(ze));return ke?(Ae.w=m.get(ke[0].toLowerCase()),ze+ke[0].length):-1}function V(Ae,Pe,ze){var ke=g.exec(Pe.slice(ze));return ke?(Ae.m=b.get(ke[0].toLowerCase()),ze+ke[0].length):-1}function G(Ae,Pe,ze){var ke=y.exec(Pe.slice(ze));return ke?(Ae.m=v.get(ke[0].toLowerCase()),ze+ke[0].length):-1}function $(Ae,Pe,ze){return M(Ae,t,Pe,ze)}function H(Ae,Pe,ze){return M(Ae,n,Pe,ze)}function Y(Ae,Pe,ze){return M(Ae,r,Pe,ze)}function Z(Ae){return l[Ae.getDay()]}function ne(Ae){return i[Ae.getDay()]}function ce(Ae){return c[Ae.getMonth()]}function ie(Ae){return o[Ae.getMonth()]}function te(Ae){return a[+(Ae.getHours()>=12)]}function ae(Ae){return 1+~~(Ae.getMonth()/3)}function le(Ae){return l[Ae.getUTCDay()]}function be(Ae){return i[Ae.getUTCDay()]}function me(Ae){return c[Ae.getUTCMonth()]}function he(Ae){return o[Ae.getUTCMonth()]}function pe(Ae){return a[+(Ae.getUTCHours()>=12)]}function Ce(Ae){return 1+~~(Ae.getUTCMonth()/3)}return{format:function(Ae){var Pe=E(Ae+="",j);return Pe.toString=function(){return Ae},Pe},parse:function(Ae){var Pe=P(Ae+="",!1);return Pe.toString=function(){return Ae},Pe},utcFormat:function(Ae){var Pe=E(Ae+="",S);return Pe.toString=function(){return Ae},Pe},utcParse:function(Ae){var Pe=P(Ae+="",!0);return Pe.toString=function(){return Ae},Pe}}}var $bt={"-":"",_:" ",0:"0"},Py=/^\s*\d+/,T_n=/^%/,M_n=/[\\^$*+?|[\]().{}]/g;function Wu(s,t,n){var r=s<0?"-":"",a=(r?-s:s)+"",i=a.length;return r+(i[t.toLowerCase(),n]))}function L_n(s,t,n){var r=Py.exec(t.slice(n,n+1));return r?(s.w=+r[0],n+r[0].length):-1}function I_n(s,t,n){var r=Py.exec(t.slice(n,n+1));return r?(s.u=+r[0],n+r[0].length):-1}function D_n(s,t,n){var r=Py.exec(t.slice(n,n+2));return r?(s.U=+r[0],n+r[0].length):-1}function R_n(s,t,n){var r=Py.exec(t.slice(n,n+2));return r?(s.V=+r[0],n+r[0].length):-1}function F_n(s,t,n){var r=Py.exec(t.slice(n,n+2));return r?(s.W=+r[0],n+r[0].length):-1}function Vbt(s,t,n){var r=Py.exec(t.slice(n,n+4));return r?(s.y=+r[0],n+r[0].length):-1}function Hbt(s,t,n){var r=Py.exec(t.slice(n,n+2));return r?(s.y=+r[0]+(+r[0]>68?1900:2e3),n+r[0].length):-1}function O_n(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 z_n(s,t,n){var r=Py.exec(t.slice(n,n+1));return r?(s.q=r[0]*3-3,n+r[0].length):-1}function B_n(s,t,n){var r=Py.exec(t.slice(n,n+2));return r?(s.m=r[0]-1,n+r[0].length):-1}function Gbt(s,t,n){var r=Py.exec(t.slice(n,n+2));return r?(s.d=+r[0],n+r[0].length):-1}function U_n(s,t,n){var r=Py.exec(t.slice(n,n+3));return r?(s.m=0,s.d=+r[0],n+r[0].length):-1}function Wbt(s,t,n){var r=Py.exec(t.slice(n,n+2));return r?(s.H=+r[0],n+r[0].length):-1}function q_n(s,t,n){var r=Py.exec(t.slice(n,n+2));return r?(s.M=+r[0],n+r[0].length):-1}function $_n(s,t,n){var r=Py.exec(t.slice(n,n+2));return r?(s.S=+r[0],n+r[0].length):-1}function V_n(s,t,n){var r=Py.exec(t.slice(n,n+3));return r?(s.L=+r[0],n+r[0].length):-1}function H_n(s,t,n){var r=Py.exec(t.slice(n,n+6));return r?(s.L=Math.floor(r[0]/1e3),n+r[0].length):-1}function G_n(s,t,n){var r=T_n.exec(t.slice(n,n+1));return r?n+r[0].length:-1}function W_n(s,t,n){var r=Py.exec(t.slice(n));return r?(s.Q=+r[0],n+r[0].length):-1}function K_n(s,t,n){var r=Py.exec(t.slice(n));return r?(s.s=+r[0],n+r[0].length):-1}function Kbt(s,t){return Wu(s.getDate(),t,2)}function Y_n(s,t){return Wu(s.getHours(),t,2)}function Z_n(s,t){return Wu(s.getHours()%12||12,t,2)}function X_n(s,t){return Wu(1+Eae.count(jE(s),s),t,3)}function gGt(s,t){return Wu(s.getMilliseconds(),t,3)}function Q_n(s,t){return gGt(s,t)+"000"}function J_n(s,t){return Wu(s.getMonth()+1,t,2)}function ewn(s,t){return Wu(s.getMinutes(),t,2)}function twn(s,t){return Wu(s.getSeconds(),t,2)}function swn(s){var t=s.getDay();return t===0?7:t}function nwn(s,t){return Wu(wIe.count(jE(s)-1,s),t,2)}function yGt(s){var t=s.getDay();return t>=4||t===0?XH(s):XH.ceil(s)}function rwn(s,t){return s=yGt(s),Wu(XH.count(jE(s),s)+(jE(s).getDay()===4),t,2)}function awn(s){return s.getDay()}function iwn(s,t){return Wu(JEe.count(jE(s)-1,s),t,2)}function own(s,t){return Wu(s.getFullYear()%100,t,2)}function lwn(s,t){return s=yGt(s),Wu(s.getFullYear()%100,t,2)}function cwn(s,t){return Wu(s.getFullYear()%1e4,t,4)}function dwn(s,t){var n=s.getDay();return s=n>=4||n===0?XH(s):XH.ceil(s),Wu(s.getFullYear()%1e4,t,4)}function uwn(s){var t=s.getTimezoneOffset();return(t>0?"-":(t*=-1,"+"))+Wu(t/60|0,"0",2)+Wu(t%60,"0",2)}function Ybt(s,t){return Wu(s.getUTCDate(),t,2)}function hwn(s,t){return Wu(s.getUTCHours(),t,2)}function mwn(s,t){return Wu(s.getUTCHours()%12||12,t,2)}function pwn(s,t){return Wu(1+_Ie.count(NE(s),s),t,3)}function vGt(s,t){return Wu(s.getUTCMilliseconds(),t,3)}function fwn(s,t){return vGt(s,t)+"000"}function xwn(s,t){return Wu(s.getUTCMonth()+1,t,2)}function gwn(s,t){return Wu(s.getUTCMinutes(),t,2)}function ywn(s,t){return Wu(s.getUTCSeconds(),t,2)}function vwn(s){var t=s.getUTCDay();return t===0?7:t}function bwn(s,t){return Wu(jIe.count(NE(s)-1,s),t,2)}function bGt(s){var t=s.getUTCDay();return t>=4||t===0?QH(s):QH.ceil(s)}function _wn(s,t){return s=bGt(s),Wu(QH.count(NE(s),s)+(NE(s).getUTCDay()===4),t,2)}function wwn(s){return s.getUTCDay()}function jwn(s,t){return Wu(eTe.count(NE(s)-1,s),t,2)}function Nwn(s,t){return Wu(s.getUTCFullYear()%100,t,2)}function kwn(s,t){return s=bGt(s),Wu(s.getUTCFullYear()%100,t,2)}function Swn(s,t){return Wu(s.getUTCFullYear()%1e4,t,4)}function Cwn(s,t){var n=s.getUTCDay();return s=n>=4||n===0?QH(s):QH.ceil(s),Wu(s.getUTCFullYear()%1e4,t,4)}function Awn(){return"+0000"}function Zbt(){return"%"}function Xbt(s){return+s}function Qbt(s){return Math.floor(+s/1e3)}var RB,_Gt,wGt;Ewn({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 Ewn(s){return RB=E_n(s),_Gt=RB.format,RB.parse,wGt=RB.utcFormat,RB.utcParse,RB}function Twn(s){return new Date(s)}function Mwn(s){return s instanceof Date?+s:+new Date(+s)}function Dst(s,t,n,r,a,i,l,o,c,d){var u=_st(),h=u.invert,m=u.domain,p=d(".%L"),f=d(":%S"),y=d("%I:%M"),v=d("%I %p"),g=d("%a %d"),b=d("%b %d"),j=d("%B"),S=d("%Y");function C(E){return(c(E)t(a/(s.length-1)))},n.quantiles=function(r){return Array.from({length:r+1},(a,i)=>bbn(s,i/r))},n.copy=function(){return SGt(t).domain(s)},qE.apply(n,arguments)}function kIe(){var s=0,t=.5,n=1,r=1,a,i,l,o,c,d=gb,u,h=!1,m;function p(y){return isNaN(y=+y)?m:(y=.5+((y=+u(y))-i)*(r*yt}var TGt=Own,zwn=SIe,Bwn=TGt,Uwn=IW;function qwn(s){return s&&s.length?zwn(s,Uwn,Bwn):void 0}var $wn=qwn;const kM=_d($wn);function Vwn(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};go.decimalPlaces=go.dp=function(){var s=this,t=s.d.length-1,n=(t-s.e)*jp;if(t=s.d[t],t)for(;t%10==0;t/=10)n--;return n<0?0:n};go.dividedBy=go.div=function(s){return nE(this,new this.constructor(s))};go.dividedToIntegerBy=go.idiv=function(s){var t=this,n=t.constructor;return Pm(nE(t,new n(s),0,1),n.precision)};go.equals=go.eq=function(s){return!this.cmp(s)};go.exponent=function(){return zg(this)};go.greaterThan=go.gt=function(s){return this.cmp(s)>0};go.greaterThanOrEqualTo=go.gte=function(s){return this.cmp(s)>=0};go.isInteger=go.isint=function(){return this.e>this.d.length-2};go.isNegative=go.isneg=function(){return this.s<0};go.isPositive=go.ispos=function(){return this.s>0};go.isZero=function(){return this.s===0};go.lessThan=go.lt=function(s){return this.cmp(s)<0};go.lessThanOrEqualTo=go.lte=function(s){return this.cmp(s)<1};go.logarithm=go.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(ej))throw Error(EN+"NaN");if(n.s<1)throw Error(EN+(n.s?"NaN":"-Infinity"));return n.eq(ej)?new r(0):(ef=!1,t=nE(Vte(n,i),Vte(s,i),i),ef=!0,Pm(t,a))};go.minus=go.sub=function(s){var t=this;return s=new t.constructor(s),t.s==s.s?DGt(t,s):LGt(t,(s.s=-s.s,s))};go.modulo=go.mod=function(s){var t,n=this,r=n.constructor,a=r.precision;if(s=new r(s),!s.s)throw Error(EN+"NaN");return n.s?(ef=!1,t=nE(n,s,0,1).times(s),ef=!0,n.minus(t)):Pm(new r(n),a)};go.naturalExponential=go.exp=function(){return IGt(this)};go.naturalLogarithm=go.ln=function(){return Vte(this)};go.negated=go.neg=function(){var s=new this.constructor(this);return s.s=-s.s||0,s};go.plus=go.add=function(s){var t=this;return s=new t.constructor(s),t.s==s.s?LGt(t,s):DGt(t,(s.s=-s.s,s))};go.precision=go.sd=function(s){var t,n,r,a=this;if(s!==void 0&&s!==!!s&&s!==1&&s!==0)throw Error(S7+s);if(t=zg(a)+1,r=a.d.length-1,n=r*jp+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};go.squareRoot=go.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(EN+"NaN")}for(s=zg(o),ef=!1,a=Math.sqrt(+o),a==0||a==1/0?(t=P4(o.d),(t.length+s)%2==0&&(t+="0"),a=Math.sqrt(t),s=FW((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(nE(o,i,l+2)).times(.5),P4(i.d).slice(0,l)===(t=P4(r.d)).slice(0,l)){if(t=t.slice(l-3,l+1),a==l&&t=="4999"){if(Pm(i,n+1,0),i.times(i).eq(o)){r=i;break}}else if(t!="9999")break;l+=4}return ef=!0,Pm(r,n)};go.times=go.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%cy|0,t=o/cy|0;i[a]=(i[a]+t)%cy|0}for(;!i[--l];)i.pop();return t?++n:i.shift(),s.d=i,s.e=n,ef?Pm(s,h.precision):s};go.toDecimalPlaces=go.todp=function(s,t){var n=this,r=n.constructor;return n=new r(n),s===void 0?n:(hC(s,0,RW),t===void 0?t=r.rounding:hC(t,0,8),Pm(n,s+zg(n)+1,t))};go.toExponential=function(s,t){var n,r=this,a=r.constructor;return s===void 0?n=h9(r,!0):(hC(s,0,RW),t===void 0?t=a.rounding:hC(t,0,8),r=Pm(new a(r),s+1,t),n=h9(r,!0,s+1)),n};go.toFixed=function(s,t){var n,r,a=this,i=a.constructor;return s===void 0?h9(a):(hC(s,0,RW),t===void 0?t=i.rounding:hC(t,0,8),r=Pm(new i(a),s+zg(a)+1,t),n=h9(r.abs(),!1,s+zg(r)+1),a.isneg()&&!a.isZero()?"-"+n:n)};go.toInteger=go.toint=function(){var s=this,t=s.constructor;return Pm(new t(s),zg(s)+1,t.rounding)};go.toNumber=function(){return+this};go.toPower=go.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(ej);if(o=new c(o),!o.s){if(s.s<1)throw Error(EN+"Infinity");return o}if(o.eq(ej))return o;if(r=c.precision,s.eq(ej))return Pm(o,r);if(t=s.e,n=s.d.length-1,l=t>=n,i=o.s,l){if((n=u<0?-u:u)<=PGt){for(a=new c(ej),t=Math.ceil(r/jp+4),ef=!1;n%2&&(a=a.times(o),t_t(a.d,t)),n=FW(n/2),n!==0;)o=o.times(o),t_t(o.d,t);return ef=!0,s.s<0?new c(ej).div(a):Pm(a,r)}}else if(i<0)throw Error(EN+"NaN");return i=i<0&&s.d[Math.max(t,n)]&1?-1:1,o.s=1,ef=!1,a=s.times(Vte(o,r+d)),ef=!0,a=IGt(a),a.s=i,a};go.toPrecision=function(s,t){var n,r,a=this,i=a.constructor;return s===void 0?(n=zg(a),r=h9(a,n<=i.toExpNeg||n>=i.toExpPos)):(hC(s,1,RW),t===void 0?t=i.rounding:hC(t,0,8),a=Pm(new i(a),s,t),n=zg(a),r=h9(a,s<=n||n<=i.toExpNeg,s)),r};go.toSignificantDigits=go.tosd=function(s,t){var n=this,r=n.constructor;return s===void 0?(s=r.precision,t=r.rounding):(hC(s,1,RW),t===void 0?t=r.rounding:hC(t,0,8)),Pm(new r(n),s,t)};go.toString=go.valueOf=go.val=go.toJSON=go[Symbol.for("nodejs.util.inspect.custom")]=function(){var s=this,t=zg(s),n=s.constructor;return h9(s,t<=n.toExpNeg||t>=n.toExpPos)};function LGt(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)),ef?Pm(t,h):t;if(c=s.d,d=t.d,l=s.e,a=t.e,c=c.slice(),i=l-a,i){for(i<0?(r=c,i=-i,o=d.length):(r=d,a=l,o=c.length),l=Math.ceil(h/jp),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)/cy|0,c[i]%=cy;for(n&&(c.unshift(n),++a),o=c.length;c[--o]==0;)c.pop();return t.d=c,t.e=a,ef?Pm(t,h):t}function hC(s,t,n){if(s!==~~s||sn)throw Error(S7+s)}function P4(s){var t,n,r,a=s.length-1,i="",l=s[0];if(a>0){for(i+=l,t=1;tl?1:-1;else for(o=c=0;oa[o]?1:-1;break}return c}function n(r,a,i){for(var l=0;i--;)r[i]-=l,l=r[i]1;)r.shift()}return function(r,a,i,l){var o,c,d,u,h,m,p,f,y,v,g,b,j,S,C,E,P,M,I=r.constructor,D=r.s==a.s?1:-1,O=r.d,V=a.d;if(!r.s)return new I(r);if(!a.s)throw Error(EN+"Division by zero");for(c=r.e-a.e,P=V.length,C=O.length,p=new I(D),f=p.d=[],d=0;V[d]==(O[d]||0);)++d;if(V[d]>(O[d]||0)&&--c,i==null?b=i=I.precision:l?b=i+(zg(r)-zg(a))+1:b=i,b<0)return new I(0);if(b=b/jp+2|0,d=0,P==1)for(u=0,V=V[0],b++;(d1&&(V=s(V,u),O=s(O,u),P=V.length,C=O.length),S=P,y=O.slice(0,P),v=y.length;v=cy/2&&++E;do u=0,o=t(V,y,P,v),o<0?(g=y[0],P!=v&&(g=g*cy+(y[1]||0)),u=g/E|0,u>1?(u>=cy&&(u=cy-1),h=s(V,u),m=h.length,v=y.length,o=t(h,y,m,v),o==1&&(u--,n(h,P16)throw Error(Ost+zg(s));if(!s.s)return new u(ej);for(t==null?(ef=!1,o=h):o=t,l=new u(.03125);s.abs().gte(.1);)s=s.times(l),d+=5;for(r=Math.log(qR(2,d))/Math.LN10*2+5|0,o+=r,n=a=i=new u(ej),u.precision=o;;){if(a=Pm(a.times(s),o),n=n.times(++c),l=i.plus(nE(a,n,o)),P4(l.d).slice(0,o)===P4(i.d).slice(0,o)){for(;d--;)i=Pm(i.times(i),o);return u.precision=h,t==null?(ef=!0,Pm(i,h)):i}i=l}}function zg(s){for(var t=s.e*jp,n=s.d[0];n>=10;n/=10)t++;return t}function M9e(s,t,n){if(t>s.LN10.sd())throw ef=!0,n&&(s.precision=n),Error(EN+"LN10 precision limit exceeded");return Pm(new s(s.LN10),t)}function f6(s){for(var t="";s--;)t+="0";return t}function Vte(s,t){var n,r,a,i,l,o,c,d,u,h=1,m=10,p=s,f=p.d,y=p.constructor,v=y.precision;if(p.s<1)throw Error(EN+(p.s?"NaN":"-Infinity"));if(p.eq(ej))return new y(0);if(t==null?(ef=!1,d=v):d=t,p.eq(10))return t==null&&(ef=!0),M9e(y,d);if(d+=m,y.precision=d,n=P4(f),r=n.charAt(0),i=zg(p),Math.abs(i)<15e14){for(;r<7&&r!=1||r==1&&n.charAt(1)>3;)p=p.times(s),n=P4(p.d),r=n.charAt(0),h++;i=zg(p),r>1?(p=new y("0."+n),i++):p=new y(r+"."+n.slice(1))}else return c=M9e(y,d+2,v).times(i+""),p=Vte(new y(r+"."+n.slice(1)),d-m).plus(c),y.precision=v,t==null?(ef=!0,Pm(p,v)):p;for(o=l=p=nE(p.minus(ej),p.plus(ej),d),u=Pm(p.times(p),d),a=3;;){if(l=Pm(l.times(u),d),c=o.plus(nE(l,new y(a),d)),P4(c.d).slice(0,d)===P4(o.d).slice(0,d))return o=o.times(2),i!==0&&(o=o.plus(M9e(y,d+2,v).times(i+""))),o=nE(o,new y(h),d),y.precision=v,t==null?(ef=!0,Pm(o,v)):o;o=c,a+=2}}function e_t(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=FW(n/jp),s.d=[],r=(n+1)%jp,n<0&&(r+=jp),rtTe||s.e<-tTe))throw Error(Ost+n)}else s.s=0,s.e=0,s.d=[0];return s}function Pm(s,t,n){var r,a,i,l,o,c,d,u,h=s.d;for(l=1,i=h[0];i>=10;i/=10)l++;if(r=t-l,r<0)r+=jp,a=t,d=h[u=0];else{if(u=Math.ceil((r+1)/jp),i=h.length,u>=i)return s;for(d=i=h[u],l=1;i>=10;i/=10)l++;r%=jp,a=r-jp+l}if(n!==void 0&&(i=qR(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/qR(10,l-a):0:h[u-1])%10&1||n==(s.s<0?8:7))),t<1||!h[0])return c?(i=zg(s),h.length=1,t=t-i-1,h[0]=qR(10,(jp-t%jp)%jp),s.e=FW(-t/jp)||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=qR(10,jp-r),h[u]=a>0?(d/qR(10,l-a)%qR(10,a)|0)*i:0),c)for(;;)if(u==0){(h[0]+=i)==cy&&(h[0]=1,++s.e);break}else{if(h[u]+=i,h[u]!=cy)break;h[u--]=0,i=1}for(r=h.length;h[--r]===0;)h.pop();if(ef&&(s.e>tTe||s.e<-tTe))throw Error(Ost+zg(s));return s}function DGt(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),ef?Pm(t,p):t;if(c=s.d,h=t.d,r=t.e,d=s.e,c=c.slice(),l=d-r,l){for(u=l<0,u?(n=c,l=-l,o=h.length):(n=h,r=d,o=c.length),a=Math.max(Math.ceil(p/jp),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)+f6(r):l>1&&(i=i.charAt(0)+"."+i.slice(1)),i=i+(a<0?"e":"e+")+a):a<0?(i="0."+f6(-a-1)+i,n&&(r=n-l)>0&&(i+=f6(r))):a>=l?(i+=f6(a+1-l),n&&(r=n-a-1)>0&&(i=i+"."+f6(r))):((r=a+1)0&&(a+1===l&&(i+="."),i+=f6(r))),s.s<0?"-"+i:i}function t_t(s,t){if(s.length>t)return s.length=t,!0}function RGt(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(S7+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 e_t(l,i.toString())}else if(typeof i!="string")throw Error(S7+i);if(i.charCodeAt(0)===45?(i=i.slice(1),l.s=-1):l.s=1,ujn.test(i))e_t(l,i);else throw Error(S7+i)}if(a.prototype=go,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=RGt,a.config=a.set=hjn,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(S7+n+": "+r);if((r=s[n="LN10"])!==void 0)if(r==Math.LN10)this[n]=new this(r);else throw Error(S7+n+": "+r);return this}var zst=RGt(djn);ej=new zst(1);const nm=zst;function mjn(s){return gjn(s)||xjn(s)||fjn(s)||pjn()}function pjn(){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 fjn(s,t){if(s){if(typeof s=="string")return cGe(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 cGe(s,t)}}function xjn(s){if(typeof Symbol<"u"&&Symbol.iterator in Object(s))return Array.from(s)}function gjn(s){if(Array.isArray(s))return cGe(s)}function cGe(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,s_t(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 Pjn(s){if(Array.isArray(s))return s}function UGt(s){var t=Hte(s,2),n=t[0],r=t[1],a=n,i=r;return n>r&&(a=r,i=n),[a,i]}function qGt(s,t,n){if(s.lte(0))return new nm(0);var r=EIe.getDigitCount(s.toNumber()),a=new nm(10).pow(r),i=s.div(a),l=r!==1?.05:.1,o=new nm(Math.ceil(i.div(l).toNumber())).add(n).mul(l),c=o.mul(a);return t?c:new nm(Math.ceil(c))}function Ljn(s,t,n){var r=1,a=new nm(s);if(!a.isint()&&n){var i=Math.abs(s);i<1?(r=new nm(10).pow(EIe.getDigitCount(s)-1),a=new nm(Math.floor(a.div(r).toNumber())).mul(r)):i>1&&(a=new nm(Math.floor(s)))}else s===0?a=new nm(Math.floor((t-1)/2)):n||(a=new nm(Math.floor(s)));var l=Math.floor((t-1)/2),o=_jn(bjn(function(c){return a.add(new nm(c-l).mul(r)).toNumber()}),dGe);return o(0,t)}function $Gt(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 nm(0),tickMin:new nm(0),tickMax:new nm(0)};var i=qGt(new nm(t).sub(s).div(n-1),r,a),l;s<=0&&t>=0?l=new nm(0):(l=new nm(s).add(t).div(2),l=l.sub(new nm(l).mod(i)));var o=Math.ceil(l.sub(s).div(i).toNumber()),c=Math.ceil(new nm(t).sub(l).div(i).toNumber()),d=o+c+1;return d>n?$Gt(s,t,n,r,a+1):(d0?c+(n-d):c,o=t>0?o:o+(n-d)),{step:i,tickMin:l.sub(new nm(o).mul(i)),tickMax:l.add(new nm(c).mul(i))})}function Ijn(s){var t=Hte(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=UGt([n,r]),c=Hte(o,2),d=c[0],u=c[1];if(d===-1/0||u===1/0){var h=u===1/0?[d].concat(hGe(dGe(0,a-1).map(function(){return 1/0}))):[].concat(hGe(dGe(0,a-1).map(function(){return-1/0})),[u]);return n>r?uGe(h):h}if(d===u)return Ljn(d,a,i);var m=$Gt(d,u,l,i),p=m.step,f=m.tickMin,y=m.tickMax,v=EIe.rangeStep(f,y.add(new nm(.1).mul(p)),p);return n>r?uGe(v):v}function Djn(s,t){var n=Hte(s,2),r=n[0],a=n[1],i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,l=UGt([r,a]),o=Hte(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=qGt(new nm(d).sub(c).div(u-1),i,0),m=[].concat(hGe(EIe.rangeStep(new nm(c),new nm(d).sub(new nm(.99).mul(h)),h)),[d]);return r>a?uGe(m):m}var Rjn=zGt(Ijn),Fjn=zGt(Djn),Ojn="Invariant failed";function m9(s,t){throw new Error(Ojn)}var zjn=["offset","layout","width","dataKey","data","dataPointFormatter","xAxis","yAxis"];function JH(s){"@babel/helpers - typeof";return JH=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},JH(s)}function sTe(){return sTe=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 Gjn(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 Wjn(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function Kjn(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(fb(h-u)!==fb(m-h)){var f=[];if(fb(m-h)===fb(c[1]-c[0])){p=m;var y=h+c[1]-c[0];f[0]=Math.min(y,(y+u)/2),f[1]=Math.max(y,(y+u)/2)}else{p=u;var v=m+c[1]-c[0];f[0]=Math.min(h,(v+h)/2),f[1]=Math.max(h,(v+h)/2)}var g=[Math.min(h,(p+h)/2),Math.max(h,(p+h)/2)];if(t>g[0]&&t<=g[1]||t>=f[0]&&t<=f[1]){l=a[d].index;break}}else{var b=Math.min(u,m),j=Math.max(u,m);if(t>(b+h)/2&&t<=(j+h)/2){l=a[d].index;break}}}else for(var S=0;S0&&S(r[S].coordinate+r[S-1].coordinate)/2&&t<=(r[S].coordinate+r[S+1].coordinate)/2||S===o-1&&t>(r[S].coordinate+r[S-1].coordinate)/2){l=r[S].index;break}return l},Bst=function(t){var n,r=t,a=r.type.displayName,i=(n=t.type)!==null&&n!==void 0&&n.defaultProps?xx(xx({},t.type.defaultProps),t.props):t.props,l=i.stroke,o=i.fill,c;switch(a){case"Line":c=l;break;case"Area":case"Radar":c=l&&l!=="none"?l:o;break;default:c=o;break}return c},u2n=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(g&&g.length){var b=g[0].type.defaultProps,j=b!==void 0?xx(xx({},b),g[0].props):g[0].props,S=j.barSize,C=j[v];l[C]||(l[C]=[]);var E=mc(S)?n:S;l[C].push({item:g[0],stackList:g.slice(1),barSize:mc(E)?void 0:xb(E,r,0)})}}return l},h2n=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=xb(n,a,0,!0),u,h=[];if(l[0].barSize===+l[0].barSize){var m=!1,p=a/c,f=l.reduce(function(S,C){return S+C.barSize||0},0);f+=(c-1)*d,f>=a&&(f-=(c-1)*d,d=0),f>=a&&p>0&&(m=!0,p*=.9,f=c*p);var y=(a-f)/2>>0,v={offset:y-d,size:0};u=l.reduce(function(S,C){var E={item:C.item,position:{offset:v.offset+v.size+d,size:m?p:C.barSize}},P=[].concat(a_t(S),[E]);return v=P[P.length-1].position,C.stackList&&C.stackList.length&&C.stackList.forEach(function(M){P.push({item:M,position:v})}),P},h)}else{var g=xb(r,a,0,!0);a-2*g-(c-1)*d<=0&&(d=0);var b=(a-2*g-(c-1)*d)/c;b>1&&(b>>=0);var j=o===+o?Math.min(b,o):b;u=l.reduce(function(S,C,E){var P=[].concat(a_t(S),[{item:C.item,position:{offset:g+(b+d)*E+(b-j)/2,size:j}}]);return C.stackList&&C.stackList.length&&C.stackList.forEach(function(M){P.push({item:M,position:P[P.length-1].position})}),P},h)}return u},m2n=function(t,n,r,a){var i=r.children,l=r.width,o=r.margin,c=l-(o.left||0)-(o.right||0),d=WGt({children:i,legendWidth:c});if(d){var u=a||{},h=u.width,m=u.height,p=d.align,f=d.verticalAlign,y=d.layout;if((y==="vertical"||y==="horizontal"&&f==="middle")&&p!=="center"&&ei(t[p]))return xx(xx({},t),{},I$({},p,t[p]+(h||0)));if((y==="horizontal"||y==="vertical"&&p==="center")&&f!=="middle"&&ei(t[f]))return xx(xx({},t),{},I$({},f,t[f]+(m||0)))}return t},p2n=function(t,n,r){return mc(n)?!0:t==="horizontal"?n==="yAxis":t==="vertical"||r==="x"?n==="xAxis":r==="y"?n==="yAxis":!0},KGt=function(t,n,r,a,i){var l=n.props.children,o=_j(l,Tae).filter(function(d){return p2n(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=rg(u,r);if(mc(h))return d;var m=Array.isArray(h)?[CIe(h),kM(h)]:[h,h],p=c.reduce(function(f,y){var v=rg(u,y,0),g=m[0]-Math.abs(Array.isArray(v)?v[0]:v),b=m[1]+Math.abs(Array.isArray(v)?v[1]:v);return[Math.min(g,f[0]),Math.max(b,f[1])]},[1/0,-1/0]);return[Math.min(p[0],d[0]),Math.max(p[1],d[1])]},[1/0,-1/0])}return null},f2n=function(t,n,r,a,i){var l=n.map(function(o){return KGt(t,o,r,i,a)}).filter(function(o){return!mc(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},YGt=function(t,n,r,a,i){var l=n.map(function(c){var d=c.props.dataKey;return r==="number"&&d&&KGt(t,c,d,a)||KJ(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?fb(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!MW(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}})},P9e=new WeakMap,kce=function(t,n){if(typeof n!="function")return t;P9e.has(t)||P9e.set(t,new WeakMap);var r=P9e.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},QGt=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:zte(),realScaleType:"band"}:l==="radial"&&o==="angleAxis"?{scale:XEe(),realScaleType:"linear"}:i==="category"&&n&&(n.indexOf("LineChart")>=0||n.indexOf("AreaChart")>=0||n.indexOf("ComposedChart")>=0&&!r)?{scale:WJ(),realScaleType:"point"}:i==="category"?{scale:zte(),realScaleType:"band"}:{scale:XEe(),realScaleType:"linear"};if(l9(a)){var c="scale".concat(mIe(a));return{scale:(Jbt[c]||WJ)(),realScaleType:Jbt[c]?c:"point"}}return Rl(a)?{scale:a}:{scale:WJ(),realScaleType:"point"}},o_t=1e-4,JGt=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])-o_t,l=Math.max(a[0],a[1])+o_t,o=t(n[0]),c=t(n[r-1]);(ol||cl)&&t.domain([n[0],n[r-1]])}},x2n=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])}},v2n=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)}},b2n={sign:y2n,expand:zhn,none:HH,silhouette:Bhn,wiggle:Uhn,positive:v2n},_2n=function(t,n,r){var a=n.map(function(o){return o.props.dataKey}),i=b2n[r],l=Ohn().keys(a).value(function(o,c){return+rg(o,c,0)}).order(BHe).offset(i);return l(t)},w2n=function(t,n,r,a,i,l){if(!t)return null;var o=l?n.reverse():n,c={},d=o.reduce(function(h,m){var p,f=(p=m.type)!==null&&p!==void 0&&p.defaultProps?xx(xx({},m.type.defaultProps),m.props):m.props,y=f.stackId,v=f.hide;if(v)return h;var g=f[r],b=h[g]||{hasStack:!1,stackGroups:{}};if(j0(y)){var j=b.stackGroups[y]||{numericAxisId:r,cateAxisId:a,items:[]};j.items.push(m),b.hasStack=!0,b.stackGroups[y]=j}else b.stackGroups[ez("_stackId_")]={numericAxisId:r,cateAxisId:a,items:[m]};return xx(xx({},h),{},I$({},g,b))},c),u={};return Object.keys(d).reduce(function(h,m){var p=d[m];if(p.hasStack){var f={};p.stackGroups=Object.keys(p.stackGroups).reduce(function(y,v){var g=p.stackGroups[v];return xx(xx({},y),{},I$({},v,{numericAxisId:r,cateAxisId:a,items:g.items,stackedData:_2n(t,g.items,i)}))},f)}return xx(xx({},h),{},I$({},m,p))},u)},eWt=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=Rjn(d,i,o);return t.domain([CIe(u),kM(u)]),{niceTicks:u}}if(i&&a==="number"){var h=t.domain(),m=Fjn(h,i,o);return{niceTicks:m}}return null};function rTe(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&&!mc(a[t.dataKey])){var o=TEe(n,"value",a[t.dataKey]);if(o)return o.coordinate+r/2}return n[i]?n[i].coordinate+r/2:null}var c=rg(a,mc(l)?t.dataKey:l);return mc(c)?null:t.scale(c)}var l_t=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=rg(l,n.dataKey,n.domain[o]);return mc(c)?null:n.scale(c)-i/2+a},j2n=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]},N2n=function(t,n){var r,a=(r=t.type)!==null&&r!==void 0&&r.defaultProps?xx(xx({},t.type.defaultProps),t.props):t.props,i=a.stackId;if(j0(i)){var l=n[i];if(l){var o=l.items.indexOf(t);return o>=0?l.stackedData[o]:null}}return null},k2n=function(t){return t.reduce(function(n,r){return[CIe(r.concat([n[0]]).filter(ei)),kM(r.concat([n[1]]).filter(ei))]},[1/0,-1/0])},tWt=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=k2n(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})},c_t=/^dataMin[\s]*-[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,d_t=/^dataMax[\s]*\+[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,xGe=function(t,n,r){if(Rl(t))return t(n,r);if(!Array.isArray(t))return n;var a=[];if(ei(t[0]))a[0]=r?t[0]:Math.min(t[0],n[0]);else if(c_t.test(t[0])){var i=+c_t.exec(t[0])[1];a[0]=n[0]-i}else Rl(t[0])?a[0]=t[0](n[0]):a[0]=n[0];if(ei(t[1]))a[1]=r?t[1]:Math.max(t[1],n[1]);else if(d_t.test(t[1])){var l=+d_t.exec(t[1])[1];a[1]=n[1]+l}else Rl(t[1])?a[1]=t[1](n[1]):a[1]=n[1];return a},aTe=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=pst(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},I2n=function(t,n,r,a,i){var l=t.width,o=t.height,c=t.startAngle,d=t.endAngle,u=xb(t.cx,l,l/2),h=xb(t.cy,o,o/2),m=rWt(l,o,r),p=xb(t.innerRadius,m,0),f=xb(t.outerRadius,m,m*.8),y=Object.keys(n);return y.reduce(function(v,g){var b=n[g],j=b.domain,S=b.reversed,C;if(mc(b.range))a==="angleAxis"?C=[c,d]:a==="radiusAxis"&&(C=[p,f]),S&&(C=[C[1],C[0]]);else{C=b.range;var E=C,P=A2n(E,2);c=P[0],d=P[1]}var M=QGt(b,i),I=M.realScaleType,D=M.scale;D.domain(j).range(C),JGt(D);var O=eWt(D,U3(U3({},b),{},{realScaleType:I})),V=U3(U3(U3({},b),O),{},{range:C,radius:f,realScaleType:I,scale:D,cx:u,cy:h,innerRadius:p,outerRadius:f,startAngle:c,endAngle:d});return U3(U3({},v),{},nWt({},g,V))},{})},D2n=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))},R2n=function(t,n){var r=t.x,a=t.y,i=n.cx,l=n.cy,o=D2n({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:L2n(d),angleInRadian:d}},F2n=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}},O2n=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},p_t=function(t,n){var r=t.x,a=t.y,i=R2n({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=F2n(n),h=u.startAngle,m=u.endAngle,p=o,f;if(h<=m){for(;p>m;)p-=360;for(;p=h&&p<=m}else{for(;p>h;)p-=360;for(;p=m&&p<=h}return f?U3(U3({},n),{},{radius:l,angle:O2n(p,n)}):null},aWt=function(t){return!_.isValidElement(t)&&!Rl(t)&&typeof t!="boolean"?t.className:""};function Yte(s){"@babel/helpers - typeof";return Yte=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},Yte(s)}var z2n=["offset"];function B2n(s){return V2n(s)||$2n(s)||q2n(s)||U2n()}function U2n(){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 q2n(s,t){if(s){if(typeof s=="string")return gGe(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 gGe(s,t)}}function $2n(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function V2n(s){if(Array.isArray(s))return gGe(s)}function gGe(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 G2n(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 f_t(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 t0(s){for(var t=1;t=0?1:-1,j,S;a==="insideStart"?(j=p+b*l,S=y):a==="insideEnd"?(j=f-b*l,S=!y):a==="end"&&(j=f+b*l,S=y),S=g<=0?S:!S;var C=tp(d,u,v,j),E=tp(d,u,v,j+(S?1:-1)*359),P="M".concat(C.x,",").concat(C.y,` A`).concat(v,",").concat(v,",0,1,").concat(S?0:1,`, `).concat(E.x,",").concat(E.y),M=mc(t.id)?ez("recharts-radial-line-"):t.id;return Dt.createElement("text",Zte({},r,{dominantBaseline:"central",className:jc("recharts-radial-bar-label",o)}),Dt.createElement("defs",null,Dt.createElement("path",{id:M,d:P})),Dt.createElement("textPath",{xlinkHref:"#".concat(M)},n))},J2n=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=tp(l,o,d+r,m),f=p.x,y=p.y;return{x:f,y,textAnchor:f>=l?"start":"end",verticalAnchor:"middle"}}if(a==="center")return{x:l,y:o,textAnchor:"middle",verticalAnchor:"middle"};if(a==="centerTop")return{x:l,y:o,textAnchor:"middle",verticalAnchor:"start"};if(a==="centerBottom")return{x:l,y:o,textAnchor:"middle",verticalAnchor:"end"};var v=(c+d)/2,g=tp(l,o,v,m),b=g.x,j=g.y;return{x:b,y:j,textAnchor:"middle",verticalAnchor:"middle"}},eNn=function(t){var n=t.viewBox,r=t.parentViewBox,a=t.offset,i=t.position,l=n,o=l.x,c=l.y,d=l.width,u=l.height,h=u>=0?1:-1,m=h*a,p=h>0?"end":"start",f=h>0?"start":"end",y=d>=0?1:-1,v=y*a,g=y>0?"end":"start",b=y>0?"start":"end";if(i==="top"){var j={x:o+d/2,y:c-h*a,textAnchor:"middle",verticalAnchor:p};return t0(t0({},j),r?{height:Math.max(c-r.y,0),width:d}:{})}if(i==="bottom"){var S={x:o+d/2,y:c+u+m,textAnchor:"middle",verticalAnchor:f};return t0(t0({},S),r?{height:Math.max(r.y+r.height-(c+u),0),width:d}:{})}if(i==="left"){var C={x:o-v,y:c+u/2,textAnchor:g,verticalAnchor:"middle"};return t0(t0({},C),r?{width:Math.max(C.x-r.x,0),height:u}:{})}if(i==="right"){var E={x:o+d+v,y:c+u/2,textAnchor:b,verticalAnchor:"middle"};return t0(t0({},E),r?{width:Math.max(r.x+r.width-E.x,0),height:u}:{})}var P=r?{width:d,height:u}:{};return i==="insideLeft"?t0({x:o+v,y:c+u/2,textAnchor:b,verticalAnchor:"middle"},P):i==="insideRight"?t0({x:o+d-v,y:c+u/2,textAnchor:g,verticalAnchor:"middle"},P):i==="insideTop"?t0({x:o+d/2,y:c+m,textAnchor:"middle",verticalAnchor:f},P):i==="insideBottom"?t0({x:o+d/2,y:c+u-m,textAnchor:"middle",verticalAnchor:p},P):i==="insideTopLeft"?t0({x:o+v,y:c+m,textAnchor:b,verticalAnchor:f},P):i==="insideTopRight"?t0({x:o+d-v,y:c+m,textAnchor:g,verticalAnchor:f},P):i==="insideBottomLeft"?t0({x:o+v,y:c+u-m,textAnchor:b,verticalAnchor:p},P):i==="insideBottomRight"?t0({x:o+d-v,y:c+u-m,textAnchor:g,verticalAnchor:p},P):CW(i)&&(ei(i.x)||_F(i.x))&&(ei(i.y)||_F(i.y))?t0({x:o+xb(i.x,d),y:c+xb(i.y,u),textAnchor:"end",verticalAnchor:"end"},P):t0({x:o+d/2,y:c+u/2,textAnchor:"middle",verticalAnchor:"middle"},P)},tNn=function(t){return"cx"in t&&ei(t.cx)};function fy(s){var t=s.offset,n=t===void 0?5:t,r=H2n(s,z2n),a=t0({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||mc(o)&&mc(c)&&!_.isValidElement(d)&&!Rl(d))return null;if(_.isValidElement(d))return _.cloneElement(d,a);var p;if(Rl(d)){if(p=_.createElement(d,a),_.isValidElement(p))return p}else p=Z2n(a);var f=tNn(i),y=$o(a,!0);if(f&&(l==="insideStart"||l==="insideEnd"||l==="end"))return Q2n(a,p,y);var v=f?J2n(a):eNn(a);return Dt.createElement(d9,Zte({className:jc("recharts-label",h)},y,v,{breakAll:m}),p)}fy.displayName="Label";var iWt=function(t){var n=t.cx,r=t.cy,a=t.angle,i=t.startAngle,l=t.endAngle,o=t.r,c=t.radius,d=t.innerRadius,u=t.outerRadius,h=t.x,m=t.y,p=t.top,f=t.left,y=t.width,v=t.height,g=t.clockWise,b=t.labelViewBox;if(b)return b;if(ei(y)&&ei(v)){if(ei(h)&&ei(m))return{x:h,y:m,width:y,height:v};if(ei(p)&&ei(f))return{x:p,y:f,width:y,height:v}}return ei(h)&&ei(m)?{x:h,y:m,width:0,height:0}:ei(n)&&ei(r)?{cx:n,cy:r,startAngle:i||a||0,endAngle:l||a||0,innerRadius:d||0,outerRadius:u||c||o||0,clockWise:g}:t.viewBox?t.viewBox:{}},sNn=function(t,n){return t?t===!0?Dt.createElement(fy,{key:"label-implicit",viewBox:n}):j0(t)?Dt.createElement(fy,{key:"label-implicit",viewBox:n,value:t}):_.isValidElement(t)?t.type===fy?_.cloneElement(t,{key:"label-implicit",viewBox:n}):Dt.createElement(fy,{key:"label-implicit",content:t,viewBox:n}):Rl(t)?Dt.createElement(fy,{key:"label-implicit",content:t,viewBox:n}):CW(t)?Dt.createElement(fy,Zte({viewBox:n},t,{key:"label-implicit"})):null:null},nNn=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=iWt(t),l=_j(a,fy).map(function(c,d){return _.cloneElement(c,{viewBox:n||i,key:"label-".concat(d)})});if(!r)return l;var o=sNn(t.label,n||i);return[o].concat(B2n(l))};fy.parseViewBox=iWt;fy.renderCallByParent=nNn;function rNn(s){var t=s==null?0:s.length;return t?s[t-1]:void 0}var aNn=rNn;const iNn=_d(aNn);function Xte(s){"@babel/helpers - typeof";return Xte=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},Xte(s)}var oNn=["valueAccessor"],lNn=["data","dataKey","clockWise","id","textBreakAll"];function cNn(s){return mNn(s)||hNn(s)||uNn(s)||dNn()}function dNn(){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 uNn(s,t){if(s){if(typeof s=="string")return yGe(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 yGe(s,t)}}function hNn(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function mNn(s){if(Array.isArray(s))return yGe(s)}function yGe(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 gNn(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 yNn=function(t){return Array.isArray(t.value)?iNn(t.value):t.value};function eC(s){var t=s.valueAccessor,n=t===void 0?yNn:t,r=y_t(s,oNn),a=r.data,i=r.dataKey,l=r.clockWise,o=r.id,c=r.textBreakAll,d=y_t(r,lNn);return!a||!a.length?null:Dt.createElement(Fd,{className:"recharts-label-list"},a.map(function(u,h){var m=mc(i)?n(u,h):rg(u&&u.payload,i),p=mc(o)?{}:{id:"".concat(o,"-").concat(h)};return Dt.createElement(fy,oTe({},$o(u,!0),d,p,{parentViewBox:u.parentViewBox,value:m,textBreakAll:c,viewBox:fy.parseViewBox(mc(l)?u:g_t(g_t({},u),{},{clockWise:l})),key:"label-".concat(h),index:h}))}))}eC.displayName="LabelList";function vNn(s,t){return s?s===!0?Dt.createElement(eC,{key:"labelList-implicit",data:t}):Dt.isValidElement(s)||Rl(s)?Dt.createElement(eC,{key:"labelList-implicit",data:t,content:s}):CW(s)?Dt.createElement(eC,oTe({data:t},s,{key:"labelList-implicit"})):null:null}function bNn(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=_j(r,eC).map(function(l,o){return _.cloneElement(l,{data:t,key:"labelList-".concat(o)})});if(!n)return a;var i=vNn(s.label,t);return[i].concat(cNn(a))}eC.renderCallByParent=bNn;function Qte(s){"@babel/helpers - typeof";return Qte=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},Qte(s)}function vGe(){return vGe=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=tp(n,r,a,l),f=tp(n,r,a,d);m+="L ".concat(f.x,",").concat(f.y,` A `).concat(a,",").concat(a,`,0, `).concat(+(Math.abs(c)>180),",").concat(+(l<=d),`, `).concat(p.x,",").concat(p.y," Z")}else m+="L ".concat(n,",").concat(r," Z");return m},kNn=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=fb(u-d),m=Sce({cx:n,cy:r,radius:i,angle:d,sign:h,cornerRadius:l,cornerIsExternal:c}),p=m.circleTangency,f=m.lineTangency,y=m.theta,v=Sce({cx:n,cy:r,radius:i,angle:u,sign:-h,cornerRadius:l,cornerIsExternal:c}),g=v.circleTangency,b=v.lineTangency,j=v.theta,S=c?Math.abs(d-u):Math.abs(d-u)-y-j;if(S<0)return o?"M ".concat(f.x,",").concat(f.y,` a`).concat(l,",").concat(l,",0,0,1,").concat(l*2,`,0 a`).concat(l,",").concat(l,",0,0,1,").concat(-l*2,`,0 `):oWt({cx:n,cy:r,innerRadius:a,outerRadius:i,startAngle:d,endAngle:u});var C="M ".concat(f.x,",").concat(f.y,` A`).concat(l,",").concat(l,",0,0,").concat(+(h<0),",").concat(p.x,",").concat(p.y,` A`).concat(i,",").concat(i,",0,").concat(+(S>180),",").concat(+(h<0),",").concat(g.x,",").concat(g.y,` A`).concat(l,",").concat(l,",0,0,").concat(+(h<0),",").concat(b.x,",").concat(b.y,` `);if(a>0){var E=Sce({cx:n,cy:r,radius:a,angle:d,sign:h,isExternal:!0,cornerRadius:l,cornerIsExternal:c}),P=E.circleTangency,M=E.lineTangency,I=E.theta,D=Sce({cx:n,cy:r,radius:a,angle:u,sign:-h,isExternal:!0,cornerRadius:l,cornerIsExternal:c}),O=D.circleTangency,V=D.lineTangency,G=D.theta,$=c?Math.abs(d-u):Math.abs(d-u)-I-G;if($<0&&l===0)return"".concat(C,"L").concat(n,",").concat(r,"Z");C+="L".concat(V.x,",").concat(V.y,` A`).concat(l,",").concat(l,",0,0,").concat(+(h<0),",").concat(O.x,",").concat(O.y,` A`).concat(a,",").concat(a,",0,").concat(+($>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 C+="L".concat(n,",").concat(r,"Z");return C},SNn={cx:0,cy:0,innerRadius:0,outerRadius:0,startAngle:0,endAngle:0,cornerRadius:0,forceCornerRadius:!1,cornerIsExternal:!1},lWt=function(t){var n=b_t(b_t({},SNn),t),r=n.cx,a=n.cy,i=n.innerRadius,l=n.outerRadius,o=n.cornerRadius,c=n.forceCornerRadius,d=n.cornerIsExternal,u=n.startAngle,h=n.endAngle,m=n.className;if(l0&&Math.abs(u-h)<360?v=kNn({cx:r,cy:a,innerRadius:i,outerRadius:l,cornerRadius:Math.min(y,f/2),forceCornerRadius:c,cornerIsExternal:d,startAngle:u,endAngle:h}):v=oWt({cx:r,cy:a,innerRadius:i,outerRadius:l,startAngle:u,endAngle:h}),Dt.createElement("path",vGe({},$o(n,!0),{className:p,d:v,role:"img"}))};function Jte(s){"@babel/helpers - typeof";return Jte=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},Jte(s)}function bGe(){return bGe=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 UNn(s,t){return OW(s.getTime(),t.getTime())}function A_t(s,t,n){if(s.size!==t.size)return!1;for(var r={},a=s.entries(),i=0,l,o;(l=a.next())&&!l.done;){for(var c=t.entries(),d=!1,u=0;(o=c.next())&&!o.done;){var h=l.value,m=h[0],p=h[1],f=o.value,y=f[0],v=f[1];!d&&!r[u]&&(d=n.equals(m,y,i,u,s,t,n)&&n.equals(p,v,m,y,s,t,n))&&(r[u]=!0),u++}if(!d)return!1;i++}return!0}function qNn(s,t,n){var r=C_t(s),a=r.length;if(C_t(t).length!==a)return!1;for(var i;a-- >0;)if(i=r[a],i===mWt&&(s.$$typeof||t.$$typeof)&&s.$$typeof!==t.$$typeof||!hWt(t,i)||!n.equals(s[i],t[i],i,i,s,t,n))return!1;return!0}function cZ(s,t,n){var r=k_t(s),a=r.length;if(k_t(t).length!==a)return!1;for(var i,l,o;a-- >0;)if(i=r[a],i===mWt&&(s.$$typeof||t.$$typeof)&&s.$$typeof!==t.$$typeof||!hWt(t,i)||!n.equals(s[i],t[i],i,i,s,t,n)||(l=S_t(s,i),o=S_t(t,i),(l||o)&&(!l||!o||l.configurable!==o.configurable||l.enumerable!==o.enumerable||l.writable!==o.writable)))return!1;return!0}function $Nn(s,t){return OW(s.valueOf(),t.valueOf())}function VNn(s,t){return s.source===t.source&&s.flags===t.flags}function E_t(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 HNn(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 GNn="[object Arguments]",WNn="[object Boolean]",KNn="[object Date]",YNn="[object Map]",ZNn="[object Number]",XNn="[object Object]",QNn="[object RegExp]",JNn="[object Set]",ekn="[object String]",tkn=Array.isArray,T_t=typeof ArrayBuffer=="function"&&ArrayBuffer.isView?ArrayBuffer.isView:null,M_t=Object.assign,skn=Object.prototype.toString.call.bind(Object.prototype.toString);function nkn(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(tkn(u))return t(u,h,m);if(T_t!=null&&T_t(u))return c(u,h,m);if(p===Date)return n(u,h,m);if(p===RegExp)return l(u,h,m);if(p===Map)return r(u,h,m);if(p===Set)return o(u,h,m);var f=skn(u);return f===KNn?n(u,h,m):f===QNn?l(u,h,m):f===YNn?r(u,h,m):f===JNn?o(u,h,m):f===XNn?typeof u.then!="function"&&typeof h.then!="function"&&a(u,h,m):f===GNn?a(u,h,m):f===WNn||f===ZNn||f===ekn?i(u,h,m):!1}}function rkn(s){var t=s.circular,n=s.createCustomConfig,r=s.strict,a={areArraysEqual:r?cZ:BNn,areDatesEqual:UNn,areMapsEqual:r?N_t(A_t,cZ):A_t,areObjectsEqual:r?cZ:qNn,arePrimitiveWrappersEqual:$Nn,areRegExpsEqual:VNn,areSetsEqual:r?N_t(E_t,cZ):E_t,areTypedArraysEqual:r?cZ:HNn};if(n&&(a=M_t({},a,n(a))),t){var i=Ace(a.areArraysEqual),l=Ace(a.areMapsEqual),o=Ace(a.areObjectsEqual),c=Ace(a.areSetsEqual);a=M_t({},a,{areArraysEqual:i,areMapsEqual:l,areObjectsEqual:o,areSetsEqual:c})}return a}function akn(s){return function(t,n,r,a,i,l,o){return s(t,n,o)}}function ikn(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 okn=TL();TL({strict:!0});TL({circular:!0});TL({circular:!0,strict:!0});TL({createInternalComparator:function(){return OW}});TL({strict:!0,createInternalComparator:function(){return OW}});TL({circular:!0,createInternalComparator:function(){return OW}});TL({circular:!0,createInternalComparator:function(){return OW},strict:!0});function TL(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=rkn(s),c=nkn(o),d=r?r(c):akn(c);return ikn({circular:n,comparator:c,createState:a,equals:d,strict:l})}function lkn(s){typeof requestAnimationFrame<"u"&&requestAnimationFrame(s)}function P_t(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):lkn(a)};requestAnimationFrame(r)}function _Ge(s){"@babel/helpers - typeof";return _Ge=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},_Ge(s)}function ckn(s){return mkn(s)||hkn(s)||ukn(s)||dkn()}function dkn(){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 ukn(s,t){if(s){if(typeof s=="string")return L_t(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 L_t(s,t)}}function L_t(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:g<0?0:g},y=function(g){for(var b=g>1?1:g,j=b,S=0;S<8;++S){var C=h(j)-b,E=p(j);if(Math.abs(C-b)0&&arguments[0]!==void 0?arguments[0]:{},n=t.stiff,r=n===void 0?100:n,a=t.damping,i=a===void 0?8:a,l=t.dt,o=l===void 0?17:l,c=function(u,h,m){var p=-(u-h)*r,f=m*i,y=m+(p-f)*o/1e3,v=m*o/1e3+u;return Math.abs(v-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 Vkn(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 L9e(s){return Kkn(s)||Wkn(s)||Gkn(s)||Hkn()}function Hkn(){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 Gkn(s,t){if(s){if(typeof s=="string")return SGe(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 SGe(s,t)}}function Wkn(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function Kkn(s){if(Array.isArray(s))return SGe(s)}function SGe(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 dTe(s){return dTe=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(n){return n.__proto__||Object.getPrototypeOf(n)},dTe(s)}var MS=function(s){Jkn(n,s);var t=eSn(n);function n(r,a){var i;Ykn(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(EGe(i)),i.changeStyle=i.changeStyle.bind(EGe(i)),!o||p<=0)return i.state={style:{}},typeof m=="function"&&(i.state={style:u}),AGe(i);if(h&&h.length)i.state={style:h[0].style};else if(d){if(typeof m=="function")return i.state={style:d},AGe(i);i.state={style:c?SX({},c,d):d}}else i.state={style:{}};return i}return Xkn(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?SX({},c,u):u};this.state&&m&&(c&&m[c]!==u||!c&&m!==u)&&this.setState(p);return}if(!(okn(a.to,u)&&a.canBegin&&a.isActive)){var f=!a.canBegin||!a.isActive;this.manager&&this.manager.stop(),this.stopJSAnimation&&this.stopJSAnimation();var y=f||d?h:a.to;if(this.state&&m){var v={style:c?SX({},c,y):y};(c&&m[c]!==y||!c&&m!==y)&&this.setState(v)}this.runAnimation(gk(gk({},this.props),{},{from:y,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=Ukn(l,o,Tkn(d),c,this.changeStyle),f=function(){i.stopJSAnimation=p()};this.manager.start([m,u,f,c,h])}},{key:"runStepAnimation",value:function(a){var i=this,l=a.steps,o=a.begin,c=a.onAnimationStart,d=l[0],u=d.style,h=d.duration,m=h===void 0?0:h,p=function(y,v,g){if(g===0)return y;var b=v.duration,j=v.easing,S=j===void 0?"ease":j,C=v.style,E=v.properties,P=v.onAnimationEnd,M=g>0?l[g-1]:v,I=E||Object.keys(C);if(typeof S=="function"||S==="spring")return[].concat(L9e(y),[i.runJSAnimation.bind(i,{from:M.style,to:C,duration:b,easing:S}),b]);var D=R_t(I,b,S),O=gk(gk(gk({},M.style),C),{},{transition:D});return[].concat(L9e(y),[O,b,P]).filter(ykn)};return this.manager.start([c].concat(L9e(l.reduce(p,[u,Math.max(m,o)])),[a.onAnimationEnd]))}},{key:"runAnimation",value:function(a){this.manager||(this.manager=pkn());var i=a.begin,l=a.duration,o=a.attributeName,c=a.to,d=a.easing,u=a.onAnimationStart,h=a.onAnimationEnd,m=a.steps,p=a.children,f=this.manager;if(this.unSubscribe=f.subscribe(this.handleStyleChange),typeof d=="function"||typeof p=="function"||d==="spring"){this.runJSAnimation(a);return}if(m.length>1){this.runStepAnimation(a);return}var y=o?SX({},o,c):c,v=R_t(Object.keys(y),l,d);f.start([u,i,gk(gk({},y),{},{transition:v}),l,h])}},{key:"render",value:function(){var a=this.props,i=a.children;a.begin;var l=a.duration;a.attributeName,a.easing;var o=a.isActive;a.steps,a.from,a.to,a.canBegin,a.onAnimationEnd,a.shouldReAnimate,a.onAnimationReStart;var c=$kn(a,qkn),d=_.Children.count(i),u=this.state.style;if(typeof i=="function")return i(u);if(!o||d===0||l<=0)return i;var h=function(p){var f=p.props,y=f.style,v=y===void 0?{}:y,g=f.className,b=_.cloneElement(p,gk(gk({},c),{},{style:gk(gk({},v),u),className:g}));return b};return d===1?h(_.Children.only(i)):Dt.createElement("div",null,_.Children.map(i,function(m){return h(m)}))}}]),n}(_.PureComponent);MS.displayName="Animate";MS.defaultProps={begin:0,duration:1e3,from:"",to:"",attributeName:"",easing:"ease",isActive:!0,canBegin:!0,steps:[],onAnimationEnd:function(){},onAnimationStart:function(){}};MS.propTypes={from:bh.oneOfType([bh.object,bh.string]),to:bh.oneOfType([bh.object,bh.string]),attributeName:bh.string,duration:bh.number,begin:bh.number,easing:bh.oneOfType([bh.string,bh.func]),steps:bh.arrayOf(bh.shape({duration:bh.number.isRequired,style:bh.object.isRequired,easing:bh.oneOfType([bh.oneOf(["ease","ease-in","ease-out","ease-in-out","linear"]),bh.func]),properties:bh.arrayOf("string"),onAnimationEnd:bh.func})),children:bh.oneOfType([bh.node,bh.func]),isActive:bh.bool,canBegin:bh.bool,onAnimationEnd:bh.func,shouldReAnimate:bh.bool,onAnimationStart:bh.func,onAnimationReStart:bh.func};function sse(s){"@babel/helpers - typeof";return sse=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},sse(s)}function uTe(){return uTe=Object.assign?Object.assign.bind():function(s){for(var t=1;ts.length)&&(t=s.length);for(var n=0,r=new Array(t);n=0?1:-1,c=r>=0?1:-1,d=a>=0&&r>=0||a<0&&r<0?1:0,u;if(l>0&&i instanceof Array){for(var h=[0,0,0,0],m=0,p=4;ml?l:i[m];u="M".concat(t,",").concat(n+o*h[0]),h[0]>0&&(u+="A ".concat(h[0],",").concat(h[0],",0,0,").concat(d,",").concat(t+c*h[0],",").concat(n)),u+="L ".concat(t+r-c*h[1],",").concat(n),h[1]>0&&(u+="A ".concat(h[1],",").concat(h[1],",0,0,").concat(d,`, `).concat(t+r,",").concat(n+o*h[1])),u+="L ".concat(t+r,",").concat(n+a-o*h[2]),h[2]>0&&(u+="A ".concat(h[2],",").concat(h[2],",0,0,").concat(d,`, `).concat(t+r-c*h[2],",").concat(n+a)),u+="L ".concat(t+c*h[3],",").concat(n+a),h[3]>0&&(u+="A ".concat(h[3],",").concat(h[3],",0,0,").concat(d,`, `).concat(t,",").concat(n+a-o*h[3])),u+="Z"}else if(l>0&&i===+i&&i>0){var f=Math.min(l,i);u="M ".concat(t,",").concat(n+o*f,` A `).concat(f,",").concat(f,",0,0,").concat(d,",").concat(t+c*f,",").concat(n,` L `).concat(t+r-c*f,",").concat(n,` A `).concat(f,",").concat(f,",0,0,").concat(d,",").concat(t+r,",").concat(n+o*f,` L `).concat(t+r,",").concat(n+a-o*f,` A `).concat(f,",").concat(f,",0,0,").concat(d,",").concat(t+r-c*f,",").concat(n+a,` L `).concat(t+c*f,",").concat(n+a,` A `).concat(f,",").concat(f,",0,0,").concat(d,",").concat(t,",").concat(n+a-o*f," Z")}else u="M ".concat(t,",").concat(n," h ").concat(r," v ").concat(a," h ").concat(-r," Z");return u},dSn=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},uSn={x:0,y:0,width:0,height:0,radius:0,isAnimationActive:!1,isUpdateAnimationActive:!1,animationBegin:0,animationDuration:1500,animationEasing:"ease"},Ust=function(t){var n=V_t(V_t({},uSn),t),r=_.useRef(),a=_.useState(-1),i=sSn(a,2),l=i[0],o=i[1];_.useEffect(function(){if(r.current&&r.current.getTotalLength)try{var S=r.current.getTotalLength();S&&o(S)}catch{}},[]);var c=n.x,d=n.y,u=n.width,h=n.height,m=n.radius,p=n.className,f=n.animationEasing,y=n.animationDuration,v=n.animationBegin,g=n.isAnimationActive,b=n.isUpdateAnimationActive;if(c!==+c||d!==+d||u!==+u||h!==+h||u===0||h===0)return null;var j=jc("recharts-rectangle",p);return b?Dt.createElement(MS,{canBegin:l>0,from:{width:u,height:h,x:c,y:d},to:{width:u,height:h,x:c,y:d},duration:y,animationEasing:f,isActive:b},function(S){var C=S.width,E=S.height,P=S.x,M=S.y;return Dt.createElement(MS,{canBegin:l>0,from:"0px ".concat(l===-1?1:l,"px"),to:"".concat(l,"px 0px"),attributeName:"strokeDasharray",begin:v,duration:y,isActive:g,easing:f},Dt.createElement("path",uTe({},$o(n,!0),{className:j,d:H_t(P,M,C,E,m),ref:r})))}):Dt.createElement("path",uTe({},$o(n,!0),{className:j,d:H_t(c,d,u,h,m)}))},hSn=["points","className","baseLinePoints","connectNulls"];function iq(){return iq=Object.assign?Object.assign.bind():function(s){for(var t=1;t=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function pSn(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 G_t(s){return ySn(s)||gSn(s)||xSn(s)||fSn()}function fSn(){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 xSn(s,t){if(s){if(typeof s=="string")return TGe(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 TGe(s,t)}}function gSn(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function ySn(s){if(Array.isArray(s))return TGe(s)}function TGe(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){W_t(r)?n[n.length-1].push(r):n[n.length-1].length>0&&n.push([])}),W_t(t[0])&&n[n.length-1].push(t[0]),n[n.length-1].length<=0&&(n=n.slice(0,-1)),n},ZJ=function(t,n){var r=vSn(t);n&&(r=[r.reduce(function(i,l){return[].concat(G_t(i),G_t(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},bSn=function(t,n,r){var a=ZJ(t,r);return"".concat(a.slice(-1)==="Z"?a.slice(0,-1):a,"L").concat(ZJ(n.reverse(),r).slice(1))},_Sn=function(t){var n=t.points,r=t.className,a=t.baseLinePoints,i=t.connectNulls,l=mSn(t,hSn);if(!n||!n.length)return null;var o=jc("recharts-polygon",r);if(a&&a.length){var c=l.stroke&&l.stroke!=="none",d=bSn(n,a,i);return Dt.createElement("g",{className:o},Dt.createElement("path",iq({},$o(l,!0),{fill:d.slice(-1)==="Z"?l.fill:"none",stroke:"none",d})),c?Dt.createElement("path",iq({},$o(l,!0),{fill:"none",d:ZJ(n,i)})):null,c?Dt.createElement("path",iq({},$o(l,!0),{fill:"none",d:ZJ(a,i)})):null)}var u=ZJ(n,i);return Dt.createElement("path",iq({},$o(l,!0),{fill:u.slice(-1)==="Z"?l.fill:"none",className:o,d:u}))};function MGe(){return MGe=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 ASn(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 ESn=function(t,n,r,a,i,l){return"M".concat(t,",").concat(i,"v").concat(a,"M").concat(l,",").concat(n,"h").concat(r)},TSn=function(t){var n=t.x,r=n===void 0?0:n,a=t.y,i=a===void 0?0:a,l=t.top,o=l===void 0?0:l,c=t.left,d=c===void 0?0:c,u=t.width,h=u===void 0?0:u,m=t.height,p=m===void 0?0:m,f=t.className,y=CSn(t,wSn),v=jSn({x:r,y:i,top:o,left:d,width:h,height:p},y);return!ei(r)||!ei(i)||!ei(h)||!ei(p)||!ei(o)||!ei(d)?null:Dt.createElement("path",PGe({},$o(v,!0),{className:jc("recharts-cross",f),d:ESn(r,i,h,p,o,d)}))},MSn=SIe,PSn=TGt,LSn=AC;function ISn(s,t){return s&&s.length?MSn(s,LSn(t),PSn):void 0}var DSn=ISn;const RSn=_d(DSn);var FSn=SIe,OSn=AC,zSn=MGt;function BSn(s,t){return s&&s.length?FSn(s,OSn(t),zSn):void 0}var USn=BSn;const qSn=_d(USn);var $Sn=["cx","cy","angle","ticks","axisLine"],VSn=["ticks","tick","angle","tickFormatter","stroke"];function tG(s){"@babel/helpers - typeof";return tG=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},tG(s)}function XJ(){return XJ=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 HSn(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 GSn(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function X_t(s,t){for(var n=0;newt?l=a==="outer"?"start":"end":i<-ewt?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=kI(kI({},$o(this.props,!1)),{},{fill:"none"},$o(o,!1));if(c==="circle")return Dt.createElement(Mae,tF({className:"recharts-polar-angle-axis-line"},d,{cx:a,cy:i,r:l}));var u=this.props.ticks,h=u.map(function(m){return tp(a,i,l,m.coordinate)});return Dt.createElement(_Sn,tF({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=$o(this.props,!1),h=$o(l,!1),m=kI(kI({},u),{},{fill:"none"},$o(o,!1)),p=i.map(function(f,y){var v=r.getTickLineCoord(f),g=r.getTickTextAnchor(f),b=kI(kI(kI({textAnchor:g},u),{},{stroke:"none",fill:d},h),{},{index:y,payload:f,x:v.x2,y:v.y2});return Dt.createElement(Fd,tF({className:jc("recharts-polar-angle-axis-tick",aWt(l)),key:"tick-".concat(f.coordinate)},c9(r.props,f,y)),o&&Dt.createElement("line",tF({className:"recharts-polar-angle-axis-tick-line"},m,v)),l&&t.renderTickItem(l,b,c?c(f.value,y):f.value))});return Dt.createElement(Fd,{className:"recharts-polar-angle-axis-ticks"},p)}},{key:"render",value:function(){var r=this.props,a=r.ticks,i=r.radius,l=r.axisLine;return i<=0||!a||!a.length?null:Dt.createElement(Fd,{className:jc("recharts-polar-angle-axis",this.props.className)},l&&this.renderAxisLine(),this.renderTicks())}}],[{key:"renderTickItem",value:function(r,a,i){var l;return Dt.isValidElement(r)?l=Dt.cloneElement(r,a):Rl(r)?l=r(a):l=Dt.createElement(d9,tF({},a,{className:"recharts-polar-angle-axis-tick-value"}),i),l}}])}(_.PureComponent);PIe(LIe,"displayName","PolarAngleAxis");PIe(LIe,"axisType","angleAxis");PIe(LIe,"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 o5n=SHt,l5n=o5n(Object.getPrototypeOf,Object),c5n=l5n,d5n=BE,u5n=c5n,h5n=UE,m5n="[object Object]",p5n=Function.prototype,f5n=Object.prototype,NWt=p5n.toString,x5n=f5n.hasOwnProperty,g5n=NWt.call(Object);function y5n(s){if(!h5n(s)||d5n(s)!=m5n)return!1;var t=u5n(s);if(t===null)return!0;var n=x5n.call(t,"constructor")&&t.constructor;return typeof n=="function"&&n instanceof n&&NWt.call(n)==g5n}var v5n=y5n;const b5n=_d(v5n);var _5n=BE,w5n=UE,j5n="[object Boolean]";function N5n(s){return s===!0||s===!1||w5n(s)&&_5n(s)==j5n}var k5n=N5n;const S5n=_d(k5n);function rse(s){"@babel/helpers - typeof";return rse=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},rse(s)}function pTe(){return pTe=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:y,animationEasing:f,isActive:g},function(j){var S=j.upperWidth,C=j.lowerWidth,E=j.height,P=j.x,M=j.y;return Dt.createElement(MS,{canBegin:l>0,from:"0px ".concat(l===-1?1:l,"px"),to:"".concat(l,"px 0px"),attributeName:"strokeDasharray",begin:v,duration:y,easing:f},Dt.createElement("path",pTe({},$o(n,!0),{className:b,d:rwt(P,M,S,C,E),ref:r})))}):Dt.createElement("g",null,Dt.createElement("path",pTe({},$o(n,!0),{className:b,d:rwt(c,d,u,h,m)})))},F5n=["option","shapeType","propTransformer","activeClassName","isActive"];function ase(s){"@babel/helpers - typeof";return ase=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},ase(s)}function O5n(s,t){if(s==null)return{};var n=z5n(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 z5n(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 awt(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 fTe(s){for(var t=1;t0?bj(j,"paddingAngle",0):0;if(C){var P=y0(C.endAngle-C.startAngle,j.endAngle-j.startAngle),M=Km(Km({},j),{},{startAngle:b+E,endAngle:b+P(y)+E});v.push(M),b=M.endAngle}else{var I=j.endAngle,D=j.startAngle,O=y0(0,I-D),V=O(y),G=Km(Km({},j),{},{startAngle:b+E,endAngle:b+V+E});v.push(G),b=G.endAngle}}),Dt.createElement(Fd,null,r.renderSectorsStatically(v))})}},{key:"attachKeyboardHandlers",value:function(r){var a=this;r.onkeydown=function(i){if(!i.altKey)switch(i.key){case"ArrowLeft":{var l=++a.state.sectorToFocus%a.sectorRefs.length;a.sectorRefs[l].focus(),a.setState({sectorToFocus:l});break}case"ArrowRight":{var o=--a.state.sectorToFocus<0?a.sectorRefs.length-1:a.state.sectorToFocus%a.sectorRefs.length;a.sectorRefs[o].focus(),a.setState({sectorToFocus:o});break}case"Escape":{a.sectorRefs[a.state.sectorToFocus].blur(),a.setState({sectorToFocus:0});break}}}}},{key:"renderSectors",value:function(){var r=this.props,a=r.sectors,i=r.isAnimationActive,l=this.state.prevSectors;return i&&a&&a.length&&(!l||!u9(l,a))?this.renderSectorsWithAnimation():this.renderSectorsStatically(a)}},{key:"componentDidMount",value:function(){this.pieRef&&this.attachKeyboardHandlers(this.pieRef)}},{key:"render",value:function(){var r=this,a=this.props,i=a.hide,l=a.sectors,o=a.className,c=a.label,d=a.cx,u=a.cy,h=a.innerRadius,m=a.outerRadius,p=a.isAnimationActive,f=this.state.isAnimationFinished;if(i||!l||!l.length||!ei(d)||!ei(u)||!ei(h)||!ei(m))return null;var y=jc("recharts-pie",o);return Dt.createElement(Fd,{tabIndex:this.props.rootTabIndex,className:y,ref:function(g){r.pieRef=g}},this.renderSectors(),c&&this.renderLabels(l),fy.renderCallByParent(this.props,null,!1),(!p||f)&&eC.renderCallByParent(this.props,l,!1))}}],[{key:"getDerivedStateFromProps",value:function(r,a){return a.prevIsAnimationActive!==r.isAnimationActive?{prevIsAnimationActive:r.isAnimationActive,prevAnimationId:r.animationId,curSectors:r.sectors,prevSectors:[],isAnimationFinished:!0}:r.isAnimationActive&&r.animationId!==a.prevAnimationId?{prevAnimationId:r.animationId,curSectors:r.sectors,prevSectors:a.curSectors,isAnimationFinished:!0}:r.sectors!==a.curSectors?{curSectors:r.sectors,isAnimationFinished:!0}:null}},{key:"getTextAnchor",value:function(r,a){return r>a?"start":r=360?b:b-1)*c,S=v-b*p-j,C=a.reduce(function(M,I){var D=rg(I,g,0);return M+(ei(D)?D:0)},0),E;if(C>0){var P;E=a.map(function(M,I){var D=rg(M,g,0),O=rg(M,u,I),V=(ei(D)?D:0)/C,G;I?G=P.endAngle+fb(y)*c*(D!==0?1:0):G=l;var $=G+fb(y)*((D!==0?p:0)+V*S),H=(G+$)/2,Y=(f.innerRadius+f.outerRadius)/2,Z=[{name:O,value:D,payload:M,dataKey:g,type:m}],ne=tp(f.cx,f.cy,Y,H);return P=Km(Km(Km({percent:V,cornerRadius:i,name:O,tooltipPayload:Z,midAngle:H,middleRadius:Y,tooltipPosition:ne},M),f),{},{value:rg(M,g),startAngle:G,endAngle:$,payload:M,paddingAngle:fb(y)*c}),P})}return Km(Km({},f),{},{sectors:E,data:a})});var i4n=Math.ceil,o4n=Math.max;function l4n(s,t,n,r){for(var a=-1,i=o4n(i4n((t-s)/(n||1)),0),l=Array(i);i--;)l[r?i:++a]=s,s+=n;return l}var c4n=l4n,d4n=HHt,cwt=1/0,u4n=17976931348623157e292;function h4n(s){if(!s)return s===0?s:0;if(s=d4n(s),s===cwt||s===-cwt){var t=s<0?-1:1;return t*u4n}return s===s?s:0}var AWt=h4n,m4n=c4n,p4n=vIe,I9e=AWt;function f4n(s){return function(t,n,r){return r&&typeof r!="number"&&p4n(t,n,r)&&(n=r=void 0),t=I9e(t),n===void 0?(n=t,t=0):n=I9e(n),r=r===void 0?t0&&r.handleDrag(a.changedTouches[0])}),Tw(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()}),Tw(r,"handleLeaveWrapper",function(){(r.state.isTravellerMoving||r.state.isSlideMoving)&&(r.leaveTimer=window.setTimeout(r.handleDragEnd,r.props.leaveTimeOut))}),Tw(r,"handleEnterSlideOrTraveller",function(){r.setState({isTextActive:!0})}),Tw(r,"handleLeaveSlideOrTraveller",function(){r.setState({isTextActive:!1})}),Tw(r,"handleSlideDragStart",function(a){var i=pwt(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 E4n(t,s),k4n(t,[{key:"componentWillUnmount",value:function(){this.leaveTimer&&(clearTimeout(this.leaveTimer),this.leaveTimer=null),this.detachDragEndListener()}},{key:"getIndex",value:function(r){var a=r.startX,i=r.endX,l=this.state.scaleValues,o=this.props,c=o.gap,d=o.data,u=d.length-1,h=Math.min(a,i),m=Math.max(a,i),p=t.getIndexInRange(l,h),f=t.getIndexInRange(l,m);return{startIndex:p-p%c,endIndex:f===u?u:f-f%c}}},{key:"getTextOfTick",value:function(r){var a=this.props,i=a.data,l=a.tickFormatter,o=a.dataKey,c=rg(i[r],o,r);return Rl(l)?l(c,r):c}},{key:"attachDragEndListener",value:function(){window.addEventListener("mouseup",this.handleDragEnd,!0),window.addEventListener("touchend",this.handleDragEnd,!0),window.addEventListener("mousemove",this.handleDrag,!0)}},{key:"detachDragEndListener",value:function(){window.removeEventListener("mouseup",this.handleDragEnd,!0),window.removeEventListener("touchend",this.handleDragEnd,!0),window.removeEventListener("mousemove",this.handleDrag,!0)}},{key:"handleSlideDrag",value:function(r){var a=this.state,i=a.slideMoveStartX,l=a.startX,o=a.endX,c=this.props,d=c.x,u=c.width,h=c.travellerWidth,m=c.startIndex,p=c.endIndex,f=c.onChange,y=r.pageX-i;y>0?y=Math.min(y,d+u-h-o,d+u-h-l):y<0&&(y=Math.max(y,d-l,d-o));var v=this.getIndex({startX:l+y,endX:o+y});(v.startIndex!==m||v.endIndex!==p)&&f&&f(v),this.setState({startX:l+y,endX:o+y,slideMoveStartX:r.pageX})}},{key:"handleTravellerDragStart",value:function(r,a){var i=pwt(a)?a.changedTouches[0]:a;this.setState({isSlideMoving:!1,isTravellerMoving:!0,movingTravellerId:r,brushMoveStartX:i.pageX}),this.attachDragEndListener()}},{key:"handleTravellerMove",value:function(r){var a=this.state,i=a.brushMoveStartX,l=a.movingTravellerId,o=a.endX,c=a.startX,d=this.state[l],u=this.props,h=u.x,m=u.width,p=u.travellerWidth,f=u.onChange,y=u.gap,v=u.data,g={startX:this.state.startX,endX:this.state.endX},b=r.pageX-i;b>0?b=Math.min(b,h+m-p-d):b<0&&(b=Math.max(b,h-d)),g[l]=d+b;var j=this.getIndex(g),S=j.startIndex,C=j.endIndex,E=function(){var M=v.length-1;return l==="startX"&&(o>c?S%y===0:C%y===0)||oc?C%y===0:S%y===0)||o>c&&C===M};this.setState(Tw(Tw({},l,d+b),"brushMoveStartX",r.pageX),function(){f&&E()&&f(j)})}},{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(Tw({},a,p),function(){i.props.onChange(i.getIndex({startX:i.state.startX,endX:i.state.endX}))})}}}},{key:"renderBackground",value:function(){var r=this.props,a=r.x,i=r.y,l=r.width,o=r.height,c=r.fill,d=r.stroke;return Dt.createElement("rect",{stroke:d,fill:c,x:a,y:i,width:l,height:o})}},{key:"renderPanorama",value:function(){var r=this.props,a=r.x,i=r.y,l=r.width,o=r.height,c=r.data,d=r.children,u=r.padding,h=_.Children.only(d);return h?Dt.cloneElement(h,{x:a,y:i,width:l,height:o,margin:u,compact:!0,data:c}):null}},{key:"renderTravellerLayer",value:function(r,a){var i,l,o=this,c=this.props,d=c.y,u=c.travellerWidth,h=c.height,m=c.traveller,p=c.ariaLabel,f=c.data,y=c.startIndex,v=c.endIndex,g=Math.max(r,this.props.x),b=D9e(D9e({},$o(this.props,!1)),{},{x:g,y:d,width:u,height:h}),j=p||"Min value: ".concat((i=f[y])===null||i===void 0?void 0:i.name,", Max value: ").concat((l=f[v])===null||l===void 0?void 0:l.name);return Dt.createElement(Fd,{tabIndex:0,role:"slider","aria-label":j,"aria-valuenow":r,className:"recharts-brush-traveller",onMouseEnter:this.handleEnterSlideOrTraveller,onMouseLeave:this.handleLeaveSlideOrTraveller,onMouseDown:this.travellerDragStartHandlers[a],onTouchStart:this.travellerDragStartHandlers[a],onKeyDown:function(C){["ArrowLeft","ArrowRight"].includes(C.key)&&(C.preventDefault(),C.stopPropagation(),o.handleTravellerMoveKeyboard(C.key==="ArrowRight"?1:-1,a))},onFocus:function(){o.setState({isTravellerFocused:!0})},onBlur:function(){o.setState({isTravellerFocused:!1})},style:{cursor:"col-resize"}},t.renderTraveller(m,b))}},{key:"renderSlide",value:function(r,a){var i=this.props,l=i.y,o=i.height,c=i.stroke,d=i.travellerWidth,u=Math.min(r,a)+d,h=Math.max(Math.abs(a-r)-d,0);return Dt.createElement("rect",{className:"recharts-brush-slide",onMouseEnter:this.handleEnterSlideOrTraveller,onMouseLeave:this.handleLeaveSlideOrTraveller,onMouseDown:this.handleSlideDragStart,onTouchStart:this.handleSlideDragStart,style:{cursor:"move"},stroke:"none",fill:c,fillOpacity:.2,x:u,y:l,width:h,height:o})}},{key:"renderText",value:function(){var r=this.props,a=r.startIndex,i=r.endIndex,l=r.y,o=r.height,c=r.travellerWidth,d=r.stroke,u=this.state,h=u.startX,m=u.endX,p=5,f={pointerEvents:"none",fill:d};return Dt.createElement(Fd,{className:"recharts-brush-texts"},Dt.createElement(d9,yTe({textAnchor:"end",verticalAnchor:"middle",x:Math.min(h,m)-p,y:l+o/2},f),this.getTextOfTick(a)),Dt.createElement(d9,yTe({textAnchor:"start",verticalAnchor:"middle",x:Math.max(h,m)+c+p,y:l+o/2},f),this.getTextOfTick(i)))}},{key:"render",value:function(){var r=this.props,a=r.data,i=r.className,l=r.children,o=r.x,c=r.y,d=r.width,u=r.height,h=r.alwaysShowText,m=this.state,p=m.startX,f=m.endX,y=m.isTextActive,v=m.isSlideMoving,g=m.isTravellerMoving,b=m.isTravellerFocused;if(!a||!a.length||!ei(o)||!ei(c)||!ei(d)||!ei(u)||d<=0||u<=0)return null;var j=jc("recharts-brush",i),S=Dt.Children.count(l)===1,C=j4n("userSelect","none");return Dt.createElement(Fd,{className:j,onMouseLeave:this.handleLeaveWrapper,onTouchMove:this.handleTouchMove,style:C},this.renderBackground(),S&&this.renderPanorama(),this.renderSlide(p,f),this.renderTravellerLayer(p,"startX"),this.renderTravellerLayer(f,"endX"),(y||v||g||b||h)&&this.renderText())}}],[{key:"renderDefaultTraveller",value:function(r){var a=r.x,i=r.y,l=r.width,o=r.height,c=r.stroke,d=Math.floor(i+o/2)-1;return Dt.createElement(Dt.Fragment,null,Dt.createElement("rect",{x:a,y:i,width:l,height:o,fill:c,stroke:"none"}),Dt.createElement("line",{x1:a+1,y1:d,x2:a+l-1,y2:d,fill:"none",stroke:"#fff"}),Dt.createElement("line",{x1:a+1,y1:d+2,x2:a+l-1,y2:d+2,fill:"none",stroke:"#fff"}))}},{key:"renderTraveller",value:function(r,a){var i;return Dt.isValidElement(r)?i=Dt.cloneElement(r,a):Rl(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 D9e({prevData:i,prevTravellerWidth:c,prevUpdateId:d,prevX:o,prevWidth:l},i&&i.length?M4n({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}}])}(_.PureComponent);Tw(aG,"displayName","Brush");Tw(aG,"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 P4n=mst;function L4n(s,t){var n;return P4n(s,function(r,a,i){return n=t(r,a,i),!n}),!!n}var I4n=L4n,D4n=yHt,R4n=AC,F4n=I4n,O4n=X_,z4n=vIe;function B4n(s,t,n){var r=O4n(s)?D4n:F4n;return n&&z4n(s,t,n)&&(t=void 0),r(s,R4n(t))}var U4n=B4n;const q4n=_d(U4n);var tC=function(t,n){var r=t.alwaysShow,a=t.ifOverflow;return r&&(a="extendDomain"),a===n},fwt=BHt;function $4n(s,t,n){t=="__proto__"&&fwt?fwt(s,t,{configurable:!0,enumerable:!0,value:n,writable:!0}):s[t]=n}var V4n=$4n,H4n=V4n,G4n=OHt,W4n=AC;function K4n(s,t){var n={};return t=W4n(t),G4n(s,function(r,a,i){H4n(n,a,t(r,a,i))}),n}var Y4n=K4n;const Z4n=_d(Y4n);function X4n(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 pCn(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 fCn(s,t){var n=s.x,r=s.y,a=mCn(s,cCn),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 dZ(dZ(dZ(dZ(dZ({},t),a),l?{x:l}:{}),c?{y:c}:{}),{},{height:u,width:m,name:t.name,radius:t.radius})}function gwt(s){return Dt.createElement(kWt,FGe({shapeType:"rectangle",propTransformer:fCn,activeClassName:"recharts-active-bar"},s))}var xCn=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=ei(r)||Qdn(r);return i?t(r,a):(i||m9(),n)}},gCn=["value","background"],LWt;function iG(s){"@babel/helpers - typeof";return iG=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},iG(s)}function yCn(s,t){if(s==null)return{};var n=vCn(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 vCn(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 bTe(){return bTe=Object.assign?Object.assign.bind():function(s){for(var t=1;t0&&Math.abs(H)0&&Math.abs($)0&&(G=Math.min((be||0)-($[me-1]||0),G))}),Number.isFinite(G)){var H=G/V,Y=y.layout==="vertical"?r.height:r.width;if(y.padding==="gap"&&(P=H*Y/2),y.padding==="no-gap"){var Z=xb(t.barCategoryGap,H*Y),ne=H*Y/2;P=ne-Z-(ne-Z)/Y*Z}}}a==="xAxis"?M=[r.left+(j.left||0)+(P||0),r.left+r.width-(j.right||0)-(P||0)]:a==="yAxis"?M=c==="horizontal"?[r.top+r.height-(j.bottom||0),r.top+(j.top||0)]:[r.top+(j.top||0)+(P||0),r.top+r.height-(j.bottom||0)-(P||0)]:M=y.range,C&&(M=[M[1],M[0]]);var ce=QGt(y,i,m),ie=ce.scale,te=ce.realScaleType;ie.domain(g).range(M),JGt(ie);var ae=eWt(ie,Kk(Kk({},y),{},{realScaleType:te}));a==="xAxis"?(O=v==="top"&&!S||v==="bottom"&&S,I=r.left,D=h[E]-O*y.height):a==="yAxis"&&(O=v==="left"&&!S||v==="right"&&S,I=h[E]-O*y.width,D=r.top);var le=Kk(Kk(Kk({},y),ae),{},{realScaleType:te,x:I,y:D,scale:ie,width:a==="xAxis"?r.width:y.width,height:a==="yAxis"?r.height:y.height});return le.bandSize=aTe(le,ae),!y.hide&&a==="xAxis"?h[E]+=(O?-1:1)*le.height:y.hide||(h[E]+=(O?-1:1)*le.width),Kk(Kk({},p),{},RIe({},f,le))},{})},FWt=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)}},TCn=function(t){var n=t.x1,r=t.y1,a=t.x2,i=t.y2;return FWt({x:n,y:r},{x:a,y:i})},OWt=function(){function s(t){CCn(this,s),this.scale=t}return ACn(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)}}])}();RIe(OWt,"EPS",1e-4);var $st=function(t){var n=Object.keys(t).reduce(function(r,a){return Kk(Kk({},r),{},RIe({},a,OWt.create(t[a])))},{});return Kk(Kk({},n),{},{apply:function(a){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},l=i.bandAware,o=i.position;return Z4n(a,function(c,d){return n[d].apply(c,{bandAware:l,position:o})})},isInRange:function(a){return PWt(a,function(i,l){return n[l].isInRange(i)})}})};function MCn(s){return(s%180+180)%180}var PCn=function(t){var n=t.width,r=t.height,a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,i=MCn(a),l=i*Math.PI/180,o=Math.atan(r/n),c=l>o&&l-1?a[i?t[l]:l]:void 0}}var FCn=RCn,OCn=AWt;function zCn(s){var t=OCn(s),n=t%1;return t===t?n?t-n:t:0}var BCn=zCn,UCn=PHt,qCn=AC,$Cn=BCn,VCn=Math.max;function HCn(s,t,n){var r=s==null?0:s.length;if(!r)return-1;var a=n==null?0:$Cn(n);return a<0&&(a=VCn(r+a,0)),UCn(s,qCn(t),a)}var GCn=HCn,WCn=FCn,KCn=GCn,YCn=WCn(KCn),ZCn=YCn;const XCn=_d(ZCn);var QCn=sdn(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("")}),Vst=_.createContext(void 0),Hst=_.createContext(void 0),zWt=_.createContext(void 0),BWt=_.createContext({}),UWt=_.createContext(void 0),qWt=_.createContext(0),$Wt=_.createContext(0),wwt=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=QCn(i);return Dt.createElement(Vst.Provider,{value:r},Dt.createElement(Hst.Provider,{value:a},Dt.createElement(BWt.Provider,{value:i},Dt.createElement(zWt.Provider,{value:u},Dt.createElement(UWt.Provider,{value:l},Dt.createElement(qWt.Provider,{value:d},Dt.createElement($Wt.Provider,{value:c},o)))))))},JCn=function(){return _.useContext(UWt)},VWt=function(t){var n=_.useContext(Vst);n==null&&m9();var r=n[t];return r==null&&m9(),r},e3n=function(){var t=_.useContext(Vst);return A6(t)},t3n=function(){var t=_.useContext(Hst),n=XCn(t,function(r){return PWt(r.domain,Number.isFinite)});return n||A6(t)},HWt=function(t){var n=_.useContext(Hst);n==null&&m9();var r=n[t];return r==null&&m9(),r},s3n=function(){var t=_.useContext(zWt);return t},n3n=function(){return _.useContext(BWt)},Gst=function(){return _.useContext($Wt)},Wst=function(){return _.useContext(qWt)};function oG(s){"@babel/helpers - typeof";return oG=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},oG(s)}function r3n(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function a3n(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 B3n(s,t){return QWt(s,t+1)}function U3n(s,t,n,r,a){for(var i=(r||[]).slice(),l=t.start,o=t.end,c=0,d=1,u=l,h=function(){var f=r==null?void 0:r[c];if(f===void 0)return{v:QWt(r,d)};var y=c,v,g=function(){return v===void 0&&(v=n(f,y)),v},b=f.coordinate,j=c===0||kTe(s,b,g,u,o);j||(c=0,u=l,d+=1),j&&(u=b+s*(g()/2+a),c+=d)},m;d<=i.length;)if(m=h(),m)return m.v;return[]}function dse(s){"@babel/helpers - typeof";return dse=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},dse(s)}function Twt(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 i1(s){for(var t=1;t0?p.coordinate-v*s:p.coordinate})}else i[m]=p=i1(i1({},p),{},{tickCoord:p.coordinate});var g=kTe(s,p.tickCoord,y,o,c);g&&(c=p.tickCoord-s*(y()/2+a),i[m]=i1(i1({},p),{},{isShow:!0}))},u=l-1;u>=0;u--)d(u);return i}function G3n(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=i1(i1({},u),{},{tickCoord:m>0?u.coordinate-m*s:u.coordinate});var p=kTe(s,u.tickCoord,function(){return h},c,d);p&&(d=u.tickCoord-s*(h/2+a),l[o-1]=i1(i1({},u),{},{isShow:!0}))}for(var f=i?o-1:o,y=function(b){var j=l[b],S,C=function(){return S===void 0&&(S=n(j,b)),S};if(b===0){var E=s*(j.coordinate-s*C()/2-c);l[b]=j=i1(i1({},j),{},{tickCoord:E<0?j.coordinate-E*s:j.coordinate})}else l[b]=j=i1(i1({},j),{},{tickCoord:j.coordinate});var P=kTe(s,j.tickCoord,C,c,d);P&&(c=j.tickCoord+s*(C()/2+a),l[b]=i1(i1({},j),{},{isShow:!0}))},v=0;v=2?fb(a[1].coordinate-a[0].coordinate):1,g=z3n(i,v,p);return c==="equidistantPreserveStart"?U3n(v,g,y,a,l):(c==="preserveStart"||c==="preserveStartEnd"?m=G3n(v,g,y,a,l,c==="preserveStartEnd"):m=H3n(v,g,y,a,l),m.filter(function(b){return b.isShow}))}var W3n=["viewBox"],K3n=["viewBox"],Y3n=["ticks"];function dG(s){"@babel/helpers - typeof";return dG=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},dG(s)}function lq(){return lq=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 Z3n(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 X3n(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function Pwt(s,t){for(var n=0;n0?c(this.props):c(p)),l<=0||o<=0||!f||!f.length?null:Dt.createElement(Fd,{className:jc("recharts-cartesian-axis",d),ref:function(v){r.layerReference=v}},i&&this.renderAxisLine(),this.renderTicks(f,this.state.fontSize,this.state.letterSpacing),fy.renderCallByParent(this.props))}}],[{key:"renderTickItem",value:function(r,a,i){var l,o=jc(a.className,"recharts-cartesian-axis-tick-value");return Dt.isValidElement(r)?l=Dt.cloneElement(r,Jg(Jg({},a),{},{className:o})):Rl(r)?l=r(Jg(Jg({},a),{},{className:o})):l=Dt.createElement(d9,lq({},a,{className:"recharts-cartesian-axis-tick-value"}),i),l}}])}(_.Component);Xst(zW,"displayName","CartesianAxis");Xst(zW,"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 rAn=["x1","y1","x2","y2","key"],aAn=["offset"];function p9(s){"@babel/helpers - typeof";return p9=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},p9(s)}function Lwt(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 c1(s){for(var t=1;t=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function cAn(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 dAn=function(t){var n=t.fill;if(!n||n==="none")return null;var r=t.fillOpacity,a=t.x,i=t.y,l=t.width,o=t.height,c=t.ry;return Dt.createElement("rect",{x:a,y:i,ry:c,width:l,height:o,stroke:"none",fill:n,fillOpacity:r,className:"recharts-cartesian-grid-bg"})};function tKt(s,t){var n;if(Dt.isValidElement(s))n=Dt.cloneElement(s,t);else if(Rl(s))n=s(t);else{var r=t.x1,a=t.y1,i=t.x2,l=t.y2,o=t.key,c=Iwt(t,rAn),d=$o(c,!1);d.offset;var u=Iwt(d,aAn);n=Dt.createElement("line",NF({},u,{x1:r,y1:a,x2:i,y2:l,fill:"none",key:o}))}return n}function uAn(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=c1(c1({},s),{},{x1:t,y1:o,x2:t+n,y2:o,key:"line-".concat(c),index:c});return tKt(a,d)});return Dt.createElement("g",{className:"recharts-cartesian-grid-horizontal"},l)}function hAn(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=c1(c1({},s),{},{x1:o,y1:t,x2:o,y2:t+n,key:"line-".concat(c),index:c});return tKt(a,d)});return Dt.createElement("g",{className:"recharts-cartesian-grid-vertical"},l)}function mAn(s){var t=s.horizontalFill,n=s.fillOpacity,r=s.x,a=s.y,i=s.width,l=s.height,o=s.horizontalPoints,c=s.horizontal,d=c===void 0?!0:c;if(!d||!t||!t.length)return null;var u=o.map(function(m){return Math.round(m+a-a)}).sort(function(m,p){return m-p});a!==u[0]&&u.unshift(0);var h=u.map(function(m,p){var f=!u[p+1],y=f?a+l-m:u[p+1]-m;if(y<=0)return null;var v=p%t.length;return Dt.createElement("rect",{key:"react-".concat(p),y:m,x:r,height:y,width:i,stroke:"none",fill:t[v],fillOpacity:n,className:"recharts-cartesian-grid-bg"})});return Dt.createElement("g",{className:"recharts-cartesian-gridstripes-horizontal"},h)}function pAn(s){var t=s.vertical,n=t===void 0?!0:t,r=s.verticalFill,a=s.fillOpacity,i=s.x,l=s.y,o=s.width,c=s.height,d=s.verticalPoints;if(!n||!r||!r.length)return null;var u=d.map(function(m){return Math.round(m+i-i)}).sort(function(m,p){return m-p});i!==u[0]&&u.unshift(0);var h=u.map(function(m,p){var f=!u[p+1],y=f?i+o-m:u[p+1]-m;if(y<=0)return null;var v=p%r.length;return Dt.createElement("rect",{key:"react-".concat(p),x:m,y:l,width:y,height:c,stroke:"none",fill:r[v],fillOpacity:a,className:"recharts-cartesian-grid-bg"})});return Dt.createElement("g",{className:"recharts-cartesian-gridstripes-vertical"},h)}var fAn=function(t,n){var r=t.xAxis,a=t.width,i=t.height,l=t.offset;return XGt(Zst(c1(c1(c1({},zW.defaultProps),r),{},{ticks:OA(r,!0),viewBox:{x:0,y:0,width:a,height:i}})),l.left,l.left+l.width,n)},xAn=function(t,n){var r=t.yAxis,a=t.width,i=t.height,l=t.offset;return XGt(Zst(c1(c1(c1({},zW.defaultProps),r),{},{ticks:OA(r,!0),viewBox:{x:0,y:0,width:a,height:i}})),l.top,l.top+l.height,n)},FB={horizontal:!0,vertical:!0,horizontalPoints:[],verticalPoints:[],stroke:"#ccc",fill:"none",verticalFill:[],horizontalFill:[]};function kE(s){var t,n,r,a,i,l,o=Gst(),c=Wst(),d=n3n(),u=c1(c1({},s),{},{stroke:(t=s.stroke)!==null&&t!==void 0?t:FB.stroke,fill:(n=s.fill)!==null&&n!==void 0?n:FB.fill,horizontal:(r=s.horizontal)!==null&&r!==void 0?r:FB.horizontal,horizontalFill:(a=s.horizontalFill)!==null&&a!==void 0?a:FB.horizontalFill,vertical:(i=s.vertical)!==null&&i!==void 0?i:FB.vertical,verticalFill:(l=s.verticalFill)!==null&&l!==void 0?l:FB.verticalFill,x:ei(s.x)?s.x:d.left,y:ei(s.y)?s.y:d.top,width:ei(s.width)?s.width:d.width,height:ei(s.height)?s.height:d.height}),h=u.x,m=u.y,p=u.width,f=u.height,y=u.syncWithTicks,v=u.horizontalValues,g=u.verticalValues,b=e3n(),j=t3n();if(!ei(p)||p<=0||!ei(f)||f<=0||!ei(h)||h!==+h||!ei(m)||m!==+m)return null;var S=u.verticalCoordinatesGenerator||fAn,C=u.horizontalCoordinatesGenerator||xAn,E=u.horizontalPoints,P=u.verticalPoints;if((!E||!E.length)&&Rl(C)){var M=v&&v.length,I=C({yAxis:j?c1(c1({},j),{},{ticks:M?v:j.ticks}):void 0,width:o,height:c,offset:d},M?!0:y);bS(Array.isArray(I),"horizontalCoordinatesGenerator should return Array but instead it returned [".concat(p9(I),"]")),Array.isArray(I)&&(E=I)}if((!P||!P.length)&&Rl(S)){var D=g&&g.length,O=S({xAxis:b?c1(c1({},b),{},{ticks:D?g:b.ticks}):void 0,width:o,height:c,offset:d},D?!0:y);bS(Array.isArray(O),"verticalCoordinatesGenerator should return Array but instead it returned [".concat(p9(O),"]")),Array.isArray(O)&&(P=O)}return Dt.createElement("g",{className:"recharts-cartesian-grid"},Dt.createElement(dAn,{fill:u.fill,fillOpacity:u.fillOpacity,x:u.x,y:u.y,width:u.width,height:u.height,ry:u.ry}),Dt.createElement(uAn,NF({},u,{offset:d,horizontalPoints:E,xAxis:b,yAxis:j})),Dt.createElement(hAn,NF({},u,{offset:d,verticalPoints:P,xAxis:b,yAxis:j})),Dt.createElement(mAn,NF({},u,{horizontalPoints:E})),Dt.createElement(pAn,NF({},u,{verticalPoints:P})))}kE.displayName="CartesianGrid";var gAn=["type","layout","connectNulls","ref"],yAn=["key"];function uG(s){"@babel/helpers - typeof";return uG=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},uG(s)}function Dwt(s,t){if(s==null)return{};var n=vAn(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 vAn(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 QJ(){return QJ=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(OB(c.slice(0,f)),[h-y]);break}var v=p.length%2===0?[0,m]:[m];return[].concat(OB(t.repeat(c,u)),OB(p),v).map(function(g){return"".concat(g,"px")}).join(", ")}),Yk(n,"id",ez("recharts-line-")),Yk(n,"pathRef",function(l){n.mainCurve=l}),Yk(n,"handleAnimationEnd",function(){n.setState({isAnimationFinished:!0}),n.props.onAnimationEnd&&n.props.onAnimationEnd()}),Yk(n,"handleAnimationStart",function(){n.setState({isAnimationFinished:!1}),n.props.onAnimationStart&&n.props.onAnimationStart()}),n}return EAn(t,s),kAn(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=_j(u,Tae);if(!h)return null;var m=function(y,v){return{x:y.x,y:y.y,value:y.value,errorVal:rg(y.payload,v)}},p={clipPath:r?"url(#clipPath-".concat(a,")"):null};return Dt.createElement(Fd,p,h.map(function(f){return Dt.cloneElement(f,{key:"bar-".concat(f.props.dataKey),data:l,xAxis:o,yAxis:c,layout:d,dataPointFormatter:m})}))}},{key:"renderDots",value:function(r,a,i){var l=this.props.isAnimationActive;if(l&&!this.state.isAnimationFinished)return null;var o=this.props,c=o.dot,d=o.points,u=o.dataKey,h=$o(this.props,!1),m=$o(c,!0),p=d.map(function(y,v){var g=kw(kw(kw({key:"dot-".concat(v),r:3},h),m),{},{index:v,cx:y.x,cy:y.y,value:y.value,dataKey:u,payload:y.payload,points:d});return t.renderDotItem(c,g)}),f={clipPath:r?"url(#clipPath-".concat(a?"":"dots-").concat(i,")"):null};return Dt.createElement(Fd,QJ({className:"recharts-line-dots",key:"dots"},f),p)}},{key:"renderCurveStatically",value:function(r,a,i,l){var o=this.props,c=o.type,d=o.layout,u=o.connectNulls;o.ref;var h=Dwt(o,gAn),m=kw(kw(kw({},$o(h,!0)),{},{fill:"none",className:"recharts-line-curve",clipPath:a?"url(#clipPath-".concat(i,")"):null,points:r},l),{},{type:c,layout:d,connectNulls:u});return Dt.createElement(C7,QJ({},m,{pathRef:this.pathRef}))}},{key:"renderCurveWithAnimation",value:function(r,a){var i=this,l=this.props,o=l.points,c=l.strokeDasharray,d=l.isAnimationActive,u=l.animationBegin,h=l.animationDuration,m=l.animationEasing,p=l.animationId,f=l.animateNewValues,y=l.width,v=l.height,g=this.state,b=g.prevPoints,j=g.totalLength;return Dt.createElement(MS,{begin:u,duration:h,isActive:d,easing:m,from:{t:0},to:{t:1},key:"line-".concat(p),onAnimationEnd:this.handleAnimationEnd,onAnimationStart:this.handleAnimationStart},function(S){var C=S.t;if(b){var E=b.length/o.length,P=o.map(function(V,G){var $=Math.floor(G*E);if(b[$]){var H=b[$],Y=y0(H.x,V.x),Z=y0(H.y,V.y);return kw(kw({},V),{},{x:Y(C),y:Z(C)})}if(f){var ne=y0(y*2,V.x),ce=y0(v/2,V.y);return kw(kw({},V),{},{x:ne(C),y:ce(C)})}return kw(kw({},V),{},{x:V.x,y:V.y})});return i.renderCurveStatically(P,r,a)}var M=y0(0,j),I=M(C),D;if(c){var O="".concat(c).split(/[,\s]+/gim).map(function(V){return parseFloat(V)});D=i.getStrokeDasharray(I,j,O)}else D=i.generateSimpleStrokeDasharray(j,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||!u9(d,l))?this.renderCurveWithAnimation(r,a):this.renderCurveStatically(l,r,a)}},{key:"render",value:function(){var r,a=this.props,i=a.hide,l=a.dot,o=a.points,c=a.className,d=a.xAxis,u=a.yAxis,h=a.top,m=a.left,p=a.width,f=a.height,y=a.isAnimationActive,v=a.id;if(i||!o||!o.length)return null;var g=this.state.isAnimationFinished,b=o.length===1,j=jc("recharts-line",c),S=d&&d.allowDataOverflow,C=u&&u.allowDataOverflow,E=S||C,P=mc(v)?this.id:v,M=(r=$o(l,!1))!==null&&r!==void 0?r:{r:3,strokeWidth:2},I=M.r,D=I===void 0?3:I,O=M.strokeWidth,V=O===void 0?2:O,G=$Vt(l)?l:{},$=G.clipDot,H=$===void 0?!0:$,Y=D*2+V;return Dt.createElement(Fd,{className:j},S||C?Dt.createElement("defs",null,Dt.createElement("clipPath",{id:"clipPath-".concat(P)},Dt.createElement("rect",{x:S?m:m-p/2,y:C?h:h-f/2,width:S?p:p*2,height:C?f:f*2})),!H&&Dt.createElement("clipPath",{id:"clipPath-dots-".concat(P)},Dt.createElement("rect",{x:m-Y/2,y:h-Y/2,width:p+Y,height:f+Y}))):null,!b&&this.renderCurve(E,P),this.renderErrorBar(E,P),(b||l)&&this.renderDots(E,H,P),(!y||g)&&eC.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(OB(r),[0]):r,l=[],o=0;o=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function LAn(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 kF(){return kF=Object.assign?Object.assign.bind():function(s){for(var t=1;t0||!u9(u,l)||!u9(h,o))?this.renderAreaWithAnimation(r,a):this.renderAreaStatically(l,o,r,a)}},{key:"render",value:function(){var r,a=this.props,i=a.hide,l=a.dot,o=a.points,c=a.className,d=a.top,u=a.left,h=a.xAxis,m=a.yAxis,p=a.width,f=a.height,y=a.isAnimationActive,v=a.id;if(i||!o||!o.length)return null;var g=this.state.isAnimationFinished,b=o.length===1,j=jc("recharts-area",c),S=h&&h.allowDataOverflow,C=m&&m.allowDataOverflow,E=S||C,P=mc(v)?this.id:v,M=(r=$o(l,!1))!==null&&r!==void 0?r:{r:3,strokeWidth:2},I=M.r,D=I===void 0?3:I,O=M.strokeWidth,V=O===void 0?2:O,G=$Vt(l)?l:{},$=G.clipDot,H=$===void 0?!0:$,Y=D*2+V;return Dt.createElement(Fd,{className:j},S||C?Dt.createElement("defs",null,Dt.createElement("clipPath",{id:"clipPath-".concat(P)},Dt.createElement("rect",{x:S?u:u-p/2,y:C?d:d-f/2,width:S?p:p*2,height:C?f:f*2})),!H&&Dt.createElement("clipPath",{id:"clipPath-dots-".concat(P)},Dt.createElement("rect",{x:u-Y/2,y:d-Y/2,width:p+Y,height:f+Y}))):null,b?null:this.renderArea(E,P),(l||b)&&this.renderDots(E,H,P),(!y||g)&&eC.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}}])}(_.PureComponent);rKt=U_;L4(U_,"displayName","Area");L4(U_,"defaultProps",{stroke:"#3182bd",fill:"#3182bd",fillOpacity:.6,xAxisId:0,yAxisId:0,legendType:"line",connectNulls:!1,points:[],dot:!1,activeDot:!0,hide:!1,isAnimationActive:!_S.isSsr,animationBegin:0,animationDuration:1500,animationEasing:"ease"});L4(U_,"getBaseValue",function(s,t,n,r){var a=s.layout,i=s.baseValue,l=t.props.baseValue,o=l??i;if(ei(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]});L4(U_,"getComposedData",function(s){var t=s.props,n=s.item,r=s.xAxis,a=s.yAxis,i=s.xAxisTicks,l=s.yAxisTicks,o=s.bandSize,c=s.dataKey,d=s.stackedData,u=s.dataStartIndex,h=s.displayedData,m=s.offset,p=t.layout,f=d&&d.length,y=rKt.getBaseValue(t,n,r,a),v=p==="horizontal",g=!1,b=h.map(function(S,C){var E;f?E=d[u+C]:(E=rg(S,c),Array.isArray(E)?g=!0:E=[y,E]);var P=E[1]==null||f&&rg(S,c)==null;return v?{x:rTe({axis:r,ticks:i,bandSize:o,entry:S,index:C}),y:P?null:a.scale(E[1]),value:E,payload:S}:{x:P?null:r.scale(E[1]),y:rTe({axis:a,ticks:l,bandSize:o,entry:S,index:C}),value:E,payload:S}}),j;return f||g?j=b.map(function(S){var C=Array.isArray(S.value)?S.value[0]:null;return v?{x:S.x,y:C!=null&&S.y!=null?a.scale(C):null}:{x:C!=null?r.scale(C):null,y:S.y}}):j=v?a.scale(y):r.scale(y),XT({points:b,baseLine:j,layout:p,isRange:g},m)});L4(U_,"renderDotItem",function(s,t){var n;if(Dt.isValidElement(s))n=Dt.cloneElement(s,t);else if(Rl(s))n=s(t);else{var r=jc("recharts-area-dot",typeof s!="boolean"?s.className:""),a=t.key,i=aKt(t,PAn);n=Dt.createElement(Mae,kF({},i,{key:a,className:r}))}return n});function mG(s){"@babel/helpers - typeof";return mG=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},mG(s)}function UAn(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function qAn(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 AEn(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 EEn(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function TEn(s,t){for(var n=0;ns.length)&&(t=s.length);for(var n=0,r=new Array(t);n0?l:t&&t.length&&ei(a)&&ei(i)?t.slice(a,i+1):[]};function _Kt(s){return s==="number"?[0,"auto"]:void 0}var nWe=function(t,n,r,a){var i=t.graphicalItems,l=t.tooltipAxis,o=UIe(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=TEe(p,l.dataKey,a)}else m=h&&h[r]||o[r];return m?[].concat(xG(c),[sWt(d,m)]):c},[])},Hwt=function(t,n,r,a){var i=a||{x:t.chartX,y:t.chartY},l=qEn(i,r),o=t.orderedTooltipTicks,c=t.tooltipAxis,d=t.tooltipTicks,u=d2n(l,o,d,c);if(u>=0&&d){var h=d[u]&&d[u].value,m=nWe(t,n,u,h),p=$En(r,o,u,i);return{activeTooltipIndex:u,activeLabel:h,activePayload:m,activeCoordinate:p}}return null},VEn=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=ZGt(u,i);return r.reduce(function(f,y){var v,g=y.type.defaultProps!==void 0?aa(aa({},y.type.defaultProps),y.props):y.props,b=g.type,j=g.dataKey,S=g.allowDataOverflow,C=g.allowDuplicatedCategory,E=g.scale,P=g.ticks,M=g.includeHidden,I=g[l];if(f[I])return f;var D=UIe(t.data,{graphicalItems:a.filter(function(ae){var le,be=l in ae.props?ae.props[l]:(le=ae.type.defaultProps)===null||le===void 0?void 0:le[l];return be===I}),dataStartIndex:c,dataEndIndex:d}),O=D.length,V,G,$;xEn(g.domain,S,b)&&(V=xGe(g.domain,null,S),p&&(b==="number"||E!=="auto")&&($=KJ(D,j,"category")));var H=_Kt(b);if(!V||V.length===0){var Y,Z=(Y=g.domain)!==null&&Y!==void 0?Y:H;if(j){if(V=KJ(D,j,b),b==="category"&&p){var ne=eun(V);C&&ne?(G=V,V=gTe(0,O)):C||(V=u_t(Z,V,y).reduce(function(ae,le){return ae.indexOf(le)>=0?ae:[].concat(xG(ae),[le])},[]))}else if(b==="category")C?V=V.filter(function(ae){return ae!==""&&!mc(ae)}):V=u_t(Z,V,y).reduce(function(ae,le){return ae.indexOf(le)>=0||le===""||mc(le)?ae:[].concat(xG(ae),[le])},[]);else if(b==="number"){var ce=f2n(D,a.filter(function(ae){var le,be,me=l in ae.props?ae.props[l]:(le=ae.type.defaultProps)===null||le===void 0?void 0:le[l],he="hide"in ae.props?ae.props.hide:(be=ae.type.defaultProps)===null||be===void 0?void 0:be.hide;return me===I&&(M||!he)}),j,i,u);ce&&(V=ce)}p&&(b==="number"||E!=="auto")&&($=KJ(D,j,"category"))}else p?V=gTe(0,O):o&&o[I]&&o[I].hasStack&&b==="number"?V=m==="expand"?[0,1]:tWt(o[I].stackGroups,c,d):V=YGt(D,a.filter(function(ae){var le=l in ae.props?ae.props[l]:ae.type.defaultProps[l],be="hide"in ae.props?ae.props.hide:ae.type.defaultProps.hide;return le===I&&(M||!be)}),b,u,!0);if(b==="number")V=eWe(h,V,I,i,P),Z&&(V=xGe(Z,V,S));else if(b==="category"&&Z){var ie=Z,te=V.every(function(ae){return ie.indexOf(ae)>=0});te&&(V=ie)}}return aa(aa({},f),{},Dl({},I,aa(aa({},g),{},{axisType:i,domain:V,categoricalDomain:$,duplicateDomain:G,originalDomain:(v=g.domain)!==null&&v!==void 0?v:H,isCategorical:p,layout:u})))},{})},HEn=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=UIe(t.data,{graphicalItems:r,dataStartIndex:c,dataEndIndex:d}),p=m.length,f=ZGt(u,i),y=-1;return r.reduce(function(v,g){var b=g.type.defaultProps!==void 0?aa(aa({},g.type.defaultProps),g.props):g.props,j=b[l],S=_Kt("number");if(!v[j]){y++;var C;return f?C=gTe(0,p):o&&o[j]&&o[j].hasStack?(C=tWt(o[j].stackGroups,c,d),C=eWe(h,C,j,i)):(C=xGe(S,YGt(m,r.filter(function(E){var P,M,I=l in E.props?E.props[l]:(P=E.type.defaultProps)===null||P===void 0?void 0:P[l],D="hide"in E.props?E.props.hide:(M=E.type.defaultProps)===null||M===void 0?void 0:M.hide;return I===j&&!D}),"number",u),a.defaultProps.allowDataOverflow),C=eWe(h,C,j,i)),aa(aa({},v),{},Dl({},j,aa(aa({axisType:i},a.defaultProps),{},{hide:!0,orientation:bj(BEn,"".concat(i,".").concat(y%2),null),domain:C,originalDomain:S,isCategorical:f,layout:u})))}return v},{})},GEn=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=_j(u,i),p={};return m&&m.length?p=VEn(t,{axes:m,graphicalItems:l,axisType:a,axisIdKey:h,stackGroups:o,dataStartIndex:c,dataEndIndex:d}):l&&l.length&&(p=HEn(t,{Axis:i,graphicalItems:l,axisType:a,axisIdKey:h,stackGroups:o,dataStartIndex:c,dataEndIndex:d})),p},WEn=function(t){var n=A6(t),r=OA(n,!1,!0);return{tooltipTicks:r,orderedTooltipTicks:pst(r,function(a){return a.coordinate}),tooltipAxis:n,tooltipAxisBandSize:aTe(n,r)}},Gwt=function(t){var n=t.children,r=t.defaultShowTooltip,a=Hw(n,aG),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}},KEn=function(t){return!t||!t.length?!1:t.some(function(n){var r=sE(n&&n.type);return r&&r.indexOf("Bar")>=0})},Wwt=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"}},YEn=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=Hw(h,aG),f=Hw(h,P$),y=Object.keys(c).reduce(function(C,E){var P=c[E],M=P.orientation;return!P.mirror&&!P.hide?aa(aa({},C),{},Dl({},M,C[M]+P.width)):C},{left:m.left||0,right:m.right||0}),v=Object.keys(l).reduce(function(C,E){var P=l[E],M=P.orientation;return!P.mirror&&!P.hide?aa(aa({},C),{},Dl({},M,bj(C,"".concat(M))+P.height)):C},{top:m.top||0,bottom:m.bottom||0}),g=aa(aa({},v),y),b=g.bottom;p&&(g.bottom+=p.props.height||aG.defaultProps.height),f&&n&&(g=m2n(g,a,r,n));var j=d-g.left-g.right,S=u-g.top-g.bottom;return aa(aa({brushBottom:b},g),{},{width:Math.max(j,0),height:Math.max(S,0)})},ZEn=function(t,n){if(n==="xAxis")return t[n].width;if(n==="yAxis")return t[n].height},qIe=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(g,b){var j=b.graphicalItems,S=b.stackGroups,C=b.offset,E=b.updateId,P=b.dataStartIndex,M=b.dataEndIndex,I=g.barSize,D=g.layout,O=g.barGap,V=g.barCategoryGap,G=g.maxBarSize,$=Wwt(D),H=$.numericAxisName,Y=$.cateAxisName,Z=KEn(j),ne=[];return j.forEach(function(ce,ie){var te=UIe(g.data,{graphicalItems:[ce],dataStartIndex:P,dataEndIndex:M}),ae=ce.type.defaultProps!==void 0?aa(aa({},ce.type.defaultProps),ce.props):ce.props,le=ae.dataKey,be=ae.maxBarSize,me=ae["".concat(H,"Id")],he=ae["".concat(Y,"Id")],pe={},Ce=c.reduce(function(Ue,Xe){var nt=b["".concat(Xe.axisType,"Map")],$e=ae["".concat(Xe.axisType,"Id")];nt&&nt[$e]||Xe.axisType==="zAxis"||m9();var Ge=nt[$e];return aa(aa({},Ue),{},Dl(Dl({},Xe.axisType,Ge),"".concat(Xe.axisType,"Ticks"),OA(Ge)))},pe),Ae=Ce[Y],Pe=Ce["".concat(Y,"Ticks")],ze=S&&S[me]&&S[me].hasStack&&N2n(ce,S[me].stackGroups),ke=sE(ce.type).indexOf("Bar")>=0,Ze=aTe(Ae,Pe),Se=[],Fe=Z&&u2n({barSize:I,stackGroups:S,totalSize:ZEn(Ce,Y)});if(ke){var Ne,Ye,Ve=mc(be)?G:be,qe=(Ne=(Ye=aTe(Ae,Pe,!0))!==null&&Ye!==void 0?Ye:Ve)!==null&&Ne!==void 0?Ne:0;Se=h2n({barGap:O,barCategoryGap:V,bandSize:qe!==Ze?qe:Ze,sizeList:Fe[he],maxBarSize:Ve}),qe!==Ze&&(Se=Se.map(function(Ue){return aa(aa({},Ue),{},{position:aa(aa({},Ue.position),{},{offset:Ue.position.offset-qe/2})})}))}var Qe=ce&&ce.type&&ce.type.getComposedData;Qe&&ne.push({props:aa(aa({},Qe(aa(aa({},Ce),{},{displayedData:te,props:g,dataKey:le,item:ce,bandSize:Ze,barPosition:Se,offset:C,stackedData:ze,layout:D,dataStartIndex:P,dataEndIndex:M}))),{},Dl(Dl(Dl({key:ce.key||"item-".concat(ie)},H,Ce[H]),Y,Ce[Y]),"animationId",E)),childIndex:hun(ce,g.children),item:ce})}),ne},p=function(g,b){var j=g.props,S=g.dataStartIndex,C=g.dataEndIndex,E=g.updateId;if(!a1t({props:j}))return null;var P=j.children,M=j.layout,I=j.stackOffset,D=j.data,O=j.reverseStackOrder,V=Wwt(M),G=V.numericAxisName,$=V.cateAxisName,H=_j(P,r),Y=w2n(D,H,"".concat(G,"Id"),"".concat($,"Id"),I,O),Z=c.reduce(function(ae,le){var be="".concat(le.axisType,"Map");return aa(aa({},ae),{},Dl({},be,GEn(j,aa(aa({},le),{},{graphicalItems:H,stackGroups:le.axisType===G&&Y,dataStartIndex:S,dataEndIndex:C}))))},{}),ne=YEn(aa(aa({},Z),{},{props:j,graphicalItems:H}),b==null?void 0:b.legendBBox);Object.keys(Z).forEach(function(ae){Z[ae]=u(j,Z[ae],ne,ae.replace("Map",""),n)});var ce=Z["".concat($,"Map")],ie=WEn(ce),te=m(j,aa(aa({},Z),{},{dataStartIndex:S,dataEndIndex:C,updateId:E,graphicalItems:H,stackGroups:Y,offset:ne}));return aa(aa({formattedGraphicalItems:te,graphicalItems:H,offset:ne,stackGroups:Y},ie),Z)},f=function(v){function g(b){var j,S,C;return EEn(this,g),C=PEn(this,g,[b]),Dl(C,"eventEmitterSymbol",Symbol("rechartsEventEmitter")),Dl(C,"accessibilityManager",new fEn),Dl(C,"handleLegendBBoxUpdate",function(E){if(E){var P=C.state,M=P.dataStartIndex,I=P.dataEndIndex,D=P.updateId;C.setState(aa({legendBBox:E},p({props:C.props,dataStartIndex:M,dataEndIndex:I,updateId:D},aa(aa({},C.state),{},{legendBBox:E}))))}}),Dl(C,"handleReceiveSyncEvent",function(E,P,M){if(C.props.syncId===E){if(M===C.eventEmitterSymbol&&typeof C.props.syncMethod!="function")return;C.applySyncEvent(P)}}),Dl(C,"handleBrushChange",function(E){var P=E.startIndex,M=E.endIndex;if(P!==C.state.dataStartIndex||M!==C.state.dataEndIndex){var I=C.state.updateId;C.setState(function(){return aa({dataStartIndex:P,dataEndIndex:M},p({props:C.props,dataStartIndex:P,dataEndIndex:M,updateId:I},C.state))}),C.triggerSyncEvent({dataStartIndex:P,dataEndIndex:M})}}),Dl(C,"handleMouseEnter",function(E){var P=C.getMouseInfo(E);if(P){var M=aa(aa({},P),{},{isTooltipActive:!0});C.setState(M),C.triggerSyncEvent(M);var I=C.props.onMouseEnter;Rl(I)&&I(M,E)}}),Dl(C,"triggeredAfterMouseMove",function(E){var P=C.getMouseInfo(E),M=P?aa(aa({},P),{},{isTooltipActive:!0}):{isTooltipActive:!1};C.setState(M),C.triggerSyncEvent(M);var I=C.props.onMouseMove;Rl(I)&&I(M,E)}),Dl(C,"handleItemMouseEnter",function(E){C.setState(function(){return{isTooltipActive:!0,activeItem:E,activePayload:E.tooltipPayload,activeCoordinate:E.tooltipPosition||{x:E.cx,y:E.cy}}})}),Dl(C,"handleItemMouseLeave",function(){C.setState(function(){return{isTooltipActive:!1}})}),Dl(C,"handleMouseMove",function(E){E.persist(),C.throttleTriggeredAfterMouseMove(E)}),Dl(C,"handleMouseLeave",function(E){C.throttleTriggeredAfterMouseMove.cancel();var P={isTooltipActive:!1};C.setState(P),C.triggerSyncEvent(P);var M=C.props.onMouseLeave;Rl(M)&&M(P,E)}),Dl(C,"handleOuterEvent",function(E){var P=uun(E),M=bj(C.props,"".concat(P));if(P&&Rl(M)){var I,D;/.*touch.*/i.test(P)?D=C.getMouseInfo(E.changedTouches[0]):D=C.getMouseInfo(E),M((I=D)!==null&&I!==void 0?I:{},E)}}),Dl(C,"handleClick",function(E){var P=C.getMouseInfo(E);if(P){var M=aa(aa({},P),{},{isTooltipActive:!0});C.setState(M),C.triggerSyncEvent(M);var I=C.props.onClick;Rl(I)&&I(M,E)}}),Dl(C,"handleMouseDown",function(E){var P=C.props.onMouseDown;if(Rl(P)){var M=C.getMouseInfo(E);P(M,E)}}),Dl(C,"handleMouseUp",function(E){var P=C.props.onMouseUp;if(Rl(P)){var M=C.getMouseInfo(E);P(M,E)}}),Dl(C,"handleTouchMove",function(E){E.changedTouches!=null&&E.changedTouches.length>0&&C.throttleTriggeredAfterMouseMove(E.changedTouches[0])}),Dl(C,"handleTouchStart",function(E){E.changedTouches!=null&&E.changedTouches.length>0&&C.handleMouseDown(E.changedTouches[0])}),Dl(C,"handleTouchEnd",function(E){E.changedTouches!=null&&E.changedTouches.length>0&&C.handleMouseUp(E.changedTouches[0])}),Dl(C,"handleDoubleClick",function(E){var P=C.props.onDoubleClick;if(Rl(P)){var M=C.getMouseInfo(E);P(M,E)}}),Dl(C,"handleContextMenu",function(E){var P=C.props.onContextMenu;if(Rl(P)){var M=C.getMouseInfo(E);P(M,E)}}),Dl(C,"triggerSyncEvent",function(E){C.props.syncId!==void 0&&F9e.emit(O9e,C.props.syncId,E,C.eventEmitterSymbol)}),Dl(C,"applySyncEvent",function(E){var P=C.props,M=P.layout,I=P.syncMethod,D=C.state.updateId,O=E.dataStartIndex,V=E.dataEndIndex;if(E.dataStartIndex!==void 0||E.dataEndIndex!==void 0)C.setState(aa({dataStartIndex:O,dataEndIndex:V},p({props:C.props,dataStartIndex:O,dataEndIndex:V,updateId:D},C.state)));else if(E.activeTooltipIndex!==void 0){var G=E.chartX,$=E.chartY,H=E.activeTooltipIndex,Y=C.state,Z=Y.offset,ne=Y.tooltipTicks;if(!Z)return;if(typeof I=="function")H=I(ne,E);else if(I==="value"){H=-1;for(var ce=0;ce=0){var ze,ke;if(G.dataKey&&!G.allowDuplicatedCategory){var Ze=typeof G.dataKey=="function"?Pe:"payload.".concat(G.dataKey.toString());ze=TEe(ce,Ze,H),ke=ie&&te&&TEe(te,Ze,H)}else ze=ce==null?void 0:ce[$],ke=ie&&te&&te[$];if(he||me){var Se=E.props.activeIndex!==void 0?E.props.activeIndex:$;return[_.cloneElement(E,aa(aa(aa({},I.props),Ce),{},{activeIndex:Se})),null,null]}if(!mc(ze))return[Ae].concat(xG(C.renderActivePoints({item:I,activePoint:ze,basePoint:ke,childIndex:$,isRange:ie})))}else{var Fe,Ne=(Fe=C.getItemByXY(C.state.activeCoordinate))!==null&&Fe!==void 0?Fe:{graphicalItem:Ae},Ye=Ne.graphicalItem,Ve=Ye.item,qe=Ve===void 0?E:Ve,Qe=Ye.childIndex,Ue=aa(aa(aa({},I.props),Ce),{},{activeIndex:Qe});return[_.cloneElement(qe,Ue),null,null]}return ie?[Ae,null,null]:[Ae,null]}),Dl(C,"renderCustomized",function(E,P,M){return _.cloneElement(E,aa(aa({key:"recharts-customized-".concat(M)},C.props),C.state))}),Dl(C,"renderMap",{CartesianGrid:{handler:Tce,once:!0},ReferenceArea:{handler:C.renderReferenceElement},ReferenceLine:{handler:Tce},ReferenceDot:{handler:C.renderReferenceElement},XAxis:{handler:Tce},YAxis:{handler:Tce},Brush:{handler:C.renderBrush,once:!0},Bar:{handler:C.renderGraphicChild},Line:{handler:C.renderGraphicChild},Area:{handler:C.renderGraphicChild},Radar:{handler:C.renderGraphicChild},RadialBar:{handler:C.renderGraphicChild},Scatter:{handler:C.renderGraphicChild},Pie:{handler:C.renderGraphicChild},Funnel:{handler:C.renderGraphicChild},Tooltip:{handler:C.renderCursor,once:!0},PolarGrid:{handler:C.renderPolarGrid,once:!0},PolarAngleAxis:{handler:C.renderPolarAxis},PolarRadiusAxis:{handler:C.renderPolarAxis},Customized:{handler:C.renderCustomized}}),C.clipPathId="".concat((j=b.id)!==null&&j!==void 0?j:ez("recharts"),"-clip"),C.throttleTriggeredAfterMouseMove=GHt(C.triggeredAfterMouseMove,(S=b.throttleDelay)!==null&&S!==void 0?S:1e3/60),C.state={},C}return DEn(g,v),MEn(g,[{key:"componentDidMount",value:function(){var j,S;this.addListener(),this.accessibilityManager.setDetails({container:this.container,offset:{left:(j=this.props.margin.left)!==null&&j!==void 0?j:0,top:(S=this.props.margin.top)!==null&&S!==void 0?S:0},coordinateList:this.state.tooltipTicks,mouseHandlerCallback:this.triggeredAfterMouseMove,layout:this.props.layout}),this.displayDefaultTooltip()}},{key:"displayDefaultTooltip",value:function(){var j=this.props,S=j.children,C=j.data,E=j.height,P=j.layout,M=Hw(S,Mf);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,O=nWe(this.state,C,I,D),V=this.state.tooltipTicks[I].coordinate,G=(this.state.offset.top+E)/2,$=P==="horizontal",H=$?{x:V,y:G}:{y:V,x:G},Y=this.state.formattedGraphicalItems.find(function(ne){var ce=ne.item;return ce.type.name==="Scatter"});Y&&(H=aa(aa({},H),Y.props.points[I].tooltipPosition),O=Y.props.points[I].tooltipPayload);var Z={activeTooltipIndex:I,isTooltipActive:!0,activeLabel:D,activePayload:O,activeCoordinate:H};this.setState(Z),this.renderCursor(M),this.accessibilityManager.setIndex(I)}}}},{key:"getSnapshotBeforeUpdate",value:function(j,S){if(!this.props.accessibilityLayer)return null;if(this.state.tooltipTicks!==S.tooltipTicks&&this.accessibilityManager.setDetails({coordinateList:this.state.tooltipTicks}),this.props.layout!==j.layout&&this.accessibilityManager.setDetails({layout:this.props.layout}),this.props.margin!==j.margin){var C,E;this.accessibilityManager.setDetails({offset:{left:(C=this.props.margin.left)!==null&&C!==void 0?C:0,top:(E=this.props.margin.top)!==null&&E!==void 0?E:0}})}return null}},{key:"componentDidUpdate",value:function(j){MHe([Hw(j.children,Mf)],[Hw(this.props.children,Mf)])||this.displayDefaultTooltip()}},{key:"componentWillUnmount",value:function(){this.removeListener(),this.throttleTriggeredAfterMouseMove.cancel()}},{key:"getTooltipEventType",value:function(){var j=Hw(this.props.children,Mf);if(j&&typeof j.props.shared=="boolean"){var S=j.props.shared?"axis":"item";return o.indexOf(S)>=0?S:i}return i}},{key:"getMouseInfo",value:function(j){if(!this.container)return null;var S=this.container,C=S.getBoundingClientRect(),E=O1n(C),P={chartX:Math.round(j.pageX-E.left),chartY:Math.round(j.pageY-E.top)},M=C.width/S.offsetWidth||1,I=this.inRange(P.chartX,P.chartY,M);if(!I)return null;var D=this.state,O=D.xAxisMap,V=D.yAxisMap,G=this.getTooltipEventType(),$=Hwt(this.state,this.props.data,this.props.layout,I);if(G!=="axis"&&O&&V){var H=A6(O).scale,Y=A6(V).scale,Z=H&&H.invert?H.invert(P.chartX):null,ne=Y&&Y.invert?Y.invert(P.chartY):null;return aa(aa({},P),{},{xValue:Z,yValue:ne},$)}return $?aa(aa({},P),$):null}},{key:"inRange",value:function(j,S){var C=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,E=this.props.layout,P=j/C,M=S/C;if(E==="horizontal"||E==="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 O=this.state,V=O.angleAxisMap,G=O.radiusAxisMap;if(V&&G){var $=A6(V);return p_t({x:P,y:M},$)}return null}},{key:"parseEventsOfWrapper",value:function(){var j=this.props.children,S=this.getTooltipEventType(),C=Hw(j,Mf),E={};C&&S==="axis"&&(C.props.trigger==="click"?E={onClick:this.handleClick}:E={onMouseEnter:this.handleMouseEnter,onDoubleClick:this.handleDoubleClick,onMouseMove:this.handleMouseMove,onMouseLeave:this.handleMouseLeave,onTouchMove:this.handleTouchMove,onTouchStart:this.handleTouchStart,onTouchEnd:this.handleTouchEnd,onContextMenu:this.handleContextMenu});var P=MEe(this.props,this.handleOuterEvent);return aa(aa({},P),E)}},{key:"addListener",value:function(){F9e.on(O9e,this.handleReceiveSyncEvent)}},{key:"removeListener",value:function(){F9e.removeListener(O9e,this.handleReceiveSyncEvent)}},{key:"filterFormatItem",value:function(j,S,C){for(var E=this.state.formattedGraphicalItems,P=0,M=E.length;P{const{data:b,error:j}=await q.from("email_campaigns").select("*").eq("status","sent").order("sent_at",{ascending:!0});if(j)throw j;return b}}),{data:r}=at({queryKey:["campaign-agent-profiles"],queryFn:async()=>{const{data:b,error:j}=await q.from("profiles").select("id, name, email");if(j)throw j;return b}});if(n)return e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading analytics..."});const a=t||[],i=new Map((r||[]).map(b=>[b.id,b])),l=a.reduce((b,j)=>b+(j.sent_count||0),0),o=a.reduce((b,j)=>b+(j.open_count||0),0),c=a.reduce((b,j)=>b+(j.click_count||0),0),d=a.reduce((b,j)=>b+(j.bounce_count||0),0),u=a.reduce((b,j)=>b+(j.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:Or,color:"text-foreground"},{label:"Total Emails Sent",value:l,icon:In,color:"text-green-600"},{label:"Avg Open Rate",value:`${h}%`,icon:ya,color:"text-blue-600"},{label:"Avg Click Rate",value:`${m}%`,icon:v0,color:"text-purple-600"},{label:"Total Bounces",value:d,icon:xl,color:"text-orange-600"},{label:"Complaints",value:u,icon:Nl,color:"text-destructive"}],f=new Map;a.forEach(b=>{var C,E;const j=b.user_id,S=f.get(j)||{name:((C=i.get(j))==null?void 0:C.name)||((E=i.get(j))==null?void 0:E.email)||"Unknown",campaigns:0,sent:0,opens:0,clicks:0};S.campaigns++,S.sent+=b.sent_count||0,S.opens+=b.open_count||0,S.clicks+=b.click_count||0,f.set(j,S)});const y=[...f.entries()].map(([b,j])=>({id:b,...j,openRate:j.sent>0?+(j.opens/j.sent*100).toFixed(1):0})).sort((b,j)=>j.sent-b.sent),v=y.slice(0,6).map(b=>({name:b.name,value:b.sent})),g=a.map(b=>{var j;return{name:b.name.length>20?b.name.slice(0,20)+"…":b.name,agent:((j=i.get(b.user_id))==null?void 0:j.name)||"Unknown",openRate:b.sent_count>0?+(b.open_count/b.sent_count*100).toFixed(1):0,clickRate:b.sent_count>0?+(b.click_count/b.sent_count*100).toFixed(1):0,sent:b.sent_count,date:b.sent_at?Hs(new Date(b.sent_at),"MMM d"):""}});return e.jsx("div",{className:"space-y-6",children:a.length===0?e.jsx(ve,{children:e.jsxs(Me,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Or,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-1",children:"No campaigns sent yet"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Campaign analytics will appear here after the first send."})]})}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3",children:p.map(b=>e.jsx(ve,{children:e.jsxs(Me,{className:"p-4 text-center",children:[e.jsx(b.icon,{className:`h-5 w-5 mx-auto mb-1 ${b.color}`}),e.jsx("p",{className:"text-2xl font-bold",children:b.value}),e.jsx("p",{className:"text-xs text-muted-foreground",children:b.label})]})},b.label))}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"Open & Click Rates by Campaign"})}),e.jsx(Me,{children:e.jsx("div",{className:"h-[280px]",children:e.jsx(jb,{width:"100%",height:"100%",children:e.jsxs(BW,{data:g,children:[e.jsx(Mv,{dataKey:"date",fontSize:11}),e.jsx(Pv,{fontSize:11,unit:"%"}),e.jsx(Mf,{formatter:b=>`${b}%`}),e.jsx(H_,{dataKey:"openRate",fill:"hsl(220, 70%, 50%)",name:"Open Rate",radius:[2,2,0,0]}),e.jsx(H_,{dataKey:"clickRate",fill:"hsl(270, 70%, 50%)",name:"Click Rate",radius:[2,2,0,0]})]})})})})]}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"Send Volume by Agent"})}),e.jsx(Me,{children:e.jsx("div",{className:"h-[280px]",children:e.jsx(jb,{width:"100%",height:"100%",children:e.jsxs(wKt,{children:[e.jsx(EC,{data:v,dataKey:"value",nameKey:"name",cx:"50%",cy:"50%",outerRadius:100,label:({name:b,percent:j})=>`${b} (${(j*100).toFixed(0)}%)`,fontSize:11,children:v.map((b,j)=>e.jsx(tz,{fill:Kwt[j%Kwt.length]},j))}),e.jsx(Mf,{})]})})})})]})]}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"Send Volume Trend"})}),e.jsx(Me,{children:e.jsx("div",{className:"h-[240px]",children:e.jsx(jb,{width:"100%",height:"100%",children:e.jsxs(Qst,{data:g,children:[e.jsx(Mv,{dataKey:"date",fontSize:11}),e.jsx(Pv,{fontSize:11}),e.jsx(Mf,{}),e.jsx(BP,{type:"monotone",dataKey:"sent",stroke:"hsl(142, 71%, 45%)",strokeWidth:2,name:"Emails Sent",dot:{r:4}})]})})})})]}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"Agent Performance"})}),e.jsx(Me,{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:y.map(b=>e.jsxs("tr",{className:"border-b last:border-0 hover:bg-muted/30",children:[e.jsx("td",{className:"py-2.5 font-medium",children:b.name}),e.jsx("td",{className:"py-2.5 text-center",children:b.campaigns}),e.jsx("td",{className:"py-2.5 text-center",children:b.sent}),e.jsx("td",{className:"py-2.5 text-center",children:b.opens}),e.jsx("td",{className:"py-2.5 text-center",children:b.clicks}),e.jsx("td",{className:"py-2.5 text-center",children:e.jsxs(Oe,{variant:"outline",children:[b.openRate,"%"]})})]},b.id))})]})})})]}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"Campaign Leaderboard"})}),e.jsx(Me,{children:e.jsx("div",{className:"space-y-2",children:[...a].sort((b,j)=>{const S=b.sent_count>0?b.open_count/b.sent_count:0;return(j.sent_count>0?j.open_count/j.sent_count:0)-S}).slice(0,10).map((b,j)=>{const S=b.sent_count>0?(b.open_count/b.sent_count*100).toFixed(1):"0.0",C=b.sent_count>0?(b.click_count/b.sent_count*100).toFixed(1):"0.0",E=i.get(b.user_id);return e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg hover:bg-muted/30 cursor-pointer",onClick:()=>s(`/admin/email-campaigns/${b.id}`),children:[e.jsxs("span",{className:"text-lg font-bold text-muted-foreground w-6",children:["#",j+1]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:b.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(E==null?void 0:E.name)||"Unknown"," · ",b.sent_at?Hs(new Date(b.sent_at),"MMM d, yyyy"):""," · ",b.sent_count," sent"]})]}),e.jsxs("div",{className:"flex gap-3 text-xs",children:[e.jsxs(Oe,{variant:"outline",className:"gap-1",children:[e.jsx(ya,{className:"h-3 w-3"})," ",S,"%"]}),e.jsxs(Oe,{variant:"outline",className:"gap-1",children:[e.jsx(v0,{className:"h-3 w-3"})," ",C,"%"]})]})]},b.id)})})})]})]})})}const QEn=()=>{const{toast:s}=vi(),[t,n]=_.useState(!0),[r,a]=_.useState([]),[i,l]=_.useState([]),[o,c]=_.useState({installs:0,activeAgents:0,impressions30d:0,leads30d:0});_.useEffect(()=>{d()},[]);const d=async()=>{try{n(!0);const u=new Date;u.setDate(u.getDate()-30);const h=u.toISOString(),{data:m}=await q.from("website_apps").select("slug, name").order("sort_order"),p=[];let f=0;for(;;){const{data:C,error:E}=await q.from("agent_website_app_installs").select("user_id, app_slug, enabled").range(f,f+999);if(E)throw E;if(p.push(...C||[]),!C||C.length<1e3)break;f+=1e3}const y=[];for(f=0;;){const{data:C,error:E}=await q.from("widget_events").select("user_id, app_slug, event_type, created_at").gte("created_at",h).order("created_at",{ascending:!1}).range(f,f+999);if(E)throw E;if(y.push(...C||[]),!C||C.length<1e3||(f+=1e3,f>2e4))break}const v=new Map;for(const C of m||[])v.set(C.slug,{app_slug:C.slug,app_name:C.name,installs:0,enabled:0,impressions:0,expands:0,cta_clicks:0,lead_captures:0});for(const C of p){const E=v.get(C.app_slug);E&&(E.installs+=1,C.enabled&&(E.enabled+=1))}for(const C of y){const E=v.get(C.app_slug);E&&(C.event_type==="impression"?E.impressions+=1:C.event_type==="expand"?E.expands+=1:C.event_type==="cta_click"?E.cta_clicks+=1:C.event_type==="lead_capture"&&(E.lead_captures+=1))}const g=new Map;for(const C of p){if(!C.enabled)continue;const E=g.get(C.user_id)||{user_id:C.user_id,name:null,email:null,apps_enabled:[],events_30d:0,leads_30d:0};E.apps_enabled.includes(C.app_slug)||E.apps_enabled.push(C.app_slug),g.set(C.user_id,E)}for(const C of y){const E=g.get(C.user_id);E&&(E.events_30d+=1,C.event_type==="lead_capture"&&(E.leads_30d+=1))}const b=Array.from(g.keys());if(b.length>0){const{data:C}=await q.from("profiles").select("id, name, email").in("id",b);for(const E of C||[]){const P=g.get(E.id);P&&(P.name=E.name,P.email=E.email)}}const j=Array.from(v.values()),S=Array.from(g.values()).sort((C,E)=>E.events_30d-C.events_30d);a(j),l(S),c({installs:j.reduce((C,E)=>C+E.enabled,0),activeAgents:S.length,impressions30d:j.reduce((C,E)=>C+E.impressions,0),leads30d:j.reduce((C,E)=>C+E.lead_captures,0)})}catch(u){console.error(u),s({title:"Error",description:u.message||"Failed to load website app analytics",variant:"destructive"})}finally{n(!1)}};return t?e.jsx(ve,{children:e.jsx(Me,{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(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(St,{className:"text-sm font-medium",children:"Active Installs"}),e.jsx(sl,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Me,{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(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(St,{className:"text-sm font-medium",children:"Agents Using Apps"}),e.jsx(In,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Me,{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(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(St,{className:"text-sm font-medium",children:"Impressions (30d)"}),e.jsx(ya,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Me,{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(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(St,{className:"text-sm font-medium",children:"Leads Captured (30d)"}),e.jsx(ln,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Me,{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(ve,{children:[e.jsx(bt,{children:e.jsx(St,{children:"App Performance (last 30 days)"})}),e.jsx(Me,{children:e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"App"}),e.jsx(Pt,{className:"text-right",children:"Installs"}),e.jsx(Pt,{className:"text-right",children:"Enabled"}),e.jsx(Pt,{className:"text-right",children:"Impressions"}),e.jsx(Pt,{className:"text-right",children:"Expands"}),e.jsx(Pt,{className:"text-right",children:"CTA Clicks"}),e.jsx(Pt,{className:"text-right",children:"Leads"}),e.jsx(Pt,{className:"text-right",children:"Conv. Rate"})]})}),e.jsxs(Ka,{children:[r.map(u=>{const h=u.impressions>0?(u.lead_captures/u.impressions*100).toFixed(1):"—";return e.jsxs(pn,{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(pn,{children:e.jsx(gt,{colSpan:8,className:"text-center text-muted-foreground py-6",children:"No data yet"})})]})]})})]}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{children:"Agent Usage (last 30 days)"})}),e.jsxs(Me,{children:[e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"Agent"}),e.jsx(Pt,{children:"Email"}),e.jsx(Pt,{children:"Apps Enabled"}),e.jsx(Pt,{className:"text-right",children:"Events (30d)"}),e.jsx(Pt,{className:"text-right",children:"Leads (30d)"})]})}),e.jsxs(Ka,{children:[i.slice(0,100).map(u=>e.jsxs(pn,{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(Oe,{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(pn,{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."]})]})]})]})},JEn=()=>{const[s,t]=_.useState([]),[n,r]=_.useState([]),[a,i]=_.useState({}),[l,o]=_.useState(!0);_.useEffect(()=>{c()},[]);const c=async()=>{o(!0);try{const[{data:h},{data:m}]=await Promise.all([q.rpc("get_extension_usage_summary"),q.from("extension_usage_events").select("id, user_id, action, metadata, created_at").order("created_at",{ascending:!1}).limit(50)]),p=h||[],f=m||[];t(p),r(f);const y=Array.from(new Set(f.map(v=>v.user_id)));if(y.length){const{data:v}=await q.from("profiles").select("id, name, email").in("id",y),g={};(v||[]).forEach(b=>{g[b.id]={name:b.name,email:b.email}}),i(g)}}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(ve,{children:e.jsx(Me,{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(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(St,{className:"text-sm font-medium",children:"Active Users"}),e.jsx(In,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Me,{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(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(St,{className:"text-sm font-medium",children:"Total Actions"}),e.jsx(GO,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Me,{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(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(St,{className:"text-sm font-medium",children:"Contacts Saved"}),e.jsx(Pl,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Me,{children:e.jsx("div",{className:"text-2xl font-bold",children:d.contacts})})]}),e.jsxs(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(St,{className:"text-sm font-medium",children:"Listings Imported"}),e.jsx(Jr,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Me,{children:e.jsx("div",{className:"text-2xl font-bold",children:d.listings})})]}),e.jsxs(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(St,{className:"text-sm font-medium",children:"Activities Logged"}),e.jsx(Hi,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Me,{children:e.jsx("div",{className:"text-2xl font-bold",children:d.activities})})]})]}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{children:"Users by Extension Activity"})}),e.jsx(Me,{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(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"User"}),e.jsx(Pt,{className:"text-right",children:"Total"}),e.jsx(Pt,{className:"text-right",children:"Contacts"}),e.jsx(Pt,{className:"text-right",children:"Listings"}),e.jsx(Pt,{className:"text-right",children:"Activities"}),e.jsx(Pt,{children:"First Used"}),e.jsx(Pt,{children:"Last Used"})]})}),e.jsx(Ka,{children:s.map(h=>e.jsxs(pn,{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(ve,{children:[e.jsx(bt,{children:e.jsx(St,{children:"Recent Activity"})}),e.jsx(Me,{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(Oe,{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)})})})]})]})},eTn=()=>e.jsx(zs,{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(Yr,{defaultValue:"analytics",className:"space-y-4",children:[e.jsxs(Zr,{children:[e.jsx(Ht,{value:"analytics",children:"Analytics"}),e.jsx(Ht,{value:"website-apps",children:"Website Apps"}),e.jsx(Ht,{value:"extension",children:"Chrome Extension"}),e.jsx(Ht,{value:"content",children:"Content"}),e.jsx(Ht,{value:"email-campaigns",children:"Email Campaigns"}),e.jsx(Ht,{value:"activity",children:"Activity"}),e.jsx(Ht,{value:"shares",children:"Shares"})]}),e.jsx(Gt,{value:"analytics",className:"space-y-4",children:e.jsx(gon,{})}),e.jsx(Gt,{value:"website-apps",className:"space-y-4",children:e.jsx(QEn,{})}),e.jsx(Gt,{value:"extension",className:"space-y-4",children:e.jsx(JEn,{})}),e.jsx(Gt,{value:"content",className:"space-y-4",children:e.jsx(von,{})}),e.jsx(Gt,{value:"email-campaigns",className:"space-y-4",children:e.jsx(XEn,{})}),e.jsx(Gt,{value:"activity",className:"space-y-4",children:e.jsx(xon,{})}),e.jsx(Gt,{value:"shares",className:"space-y-4",children:e.jsx(TVt,{})})]})]})});function tTn(){const s=Bt(),[t,n]=_.useState(!1),[r,a]=_.useState(null),[i,l]=_.useState({title:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,category_id:""}),[o,c]=_.useState(null),[d,u]=_.useState(""),[h,m]=_.useState([]),[p,f]=_.useState([]),[y,v]=_.useState([]),[g,b]=_.useState(!1),[j,S]=_.useState(null),[C,E]=_.useState(""),{data:P,isLoading:M}=at({queryKey:["brokerage-resources"],queryFn:async()=>{const{data:ke,error:Ze}=await q.from("brokerage_resources").select("*").order("publish_date",{ascending:!1});if(Ze)throw Ze;return ke}}),{data:I}=at({queryKey:["brokerage-resource-pdfs"],queryFn:async()=>{const{data:ke,error:Ze}=await q.from("brokerage_resource_pdfs").select("*").order("sort_order",{ascending:!0});if(Ze)throw Ze;return ke}}),{data:D}=at({queryKey:["brokerage-resource-videos"],queryFn:async()=>{const{data:ke,error:Ze}=await q.from("brokerage_resource_videos").select("*").order("sort_order",{ascending:!0});if(Ze)throw Ze;return ke}}),{data:O}=at({queryKey:["brokerage-resource-links"],queryFn:async()=>{const{data:ke,error:Ze}=await q.from("brokerage_resource_links").select("*").order("sort_order",{ascending:!0});if(Ze)throw Ze;return ke}}),{data:V,isLoading:G}=at({queryKey:["brokerage-resource-categories"],queryFn:async()=>{const{data:ke,error:Ze}=await q.from("brokerage_resource_categories").select("*").order("sort_order",{ascending:!0});if(Ze)throw Ze;return ke}}),$=()=>{l({title:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,category_id:""}),c(null),u(""),m([]),f([]),v([]),a(null),E("")},H=ke=>{a(ke),l({title:ke.title,description:ke.description||"",publish_date:ke.publish_date.split("T")[0],is_published:ke.is_published,category_id:ke.category_id||""}),u(ke.preview_image_url||""),E("");const Ze=(I==null?void 0:I.filter(Ne=>Ne.resource_id===ke.id))||[];m(Ze.map(Ne=>({id:Ne.id,name:Ne.name,file_url:Ne.file_url,file_size:Ne.file_size,sort_order:Ne.sort_order})));const Se=(D==null?void 0:D.filter(Ne=>Ne.resource_id===ke.id))||[];f(Se.map(Ne=>({id:Ne.id,title:Ne.title,video_url:Ne.video_url,sort_order:Ne.sort_order})));const Fe=(O==null?void 0:O.filter(Ne=>Ne.resource_id===ke.id))||[];v(Fe.map(Ne=>({id:Ne.id,title:Ne.title,canva_share_link:Ne.canva_share_link,sort_order:Ne.sort_order}))),n(!0)},Y=ke=>{var Se;const Ze=(Se=ke.target.files)==null?void 0:Se[0];Ze&&(c(Ze),u(URL.createObjectURL(Ze)))},Z=()=>{m([...h,{name:"",file_url:"",sort_order:h.length}])},ne=ke=>{m(h.filter((Ze,Se)=>Se!==ke))},ce=(ke,Ze,Se)=>{const Fe=[...h];if(Ze==="file"&&Se instanceof File){const Ne=Se.name.replace(/\.[^/.]+$/,"");Fe[ke]={...Fe[ke],file:Se,file_size:Se.size,name:Fe[ke].name||Ne}}else Fe[ke]={...Fe[ke],[Ze]:Se};m(Fe)},ie=()=>{f([...p,{title:"",video_url:"",sort_order:p.length}])},te=ke=>{f(p.filter((Ze,Se)=>Se!==ke))},ae=(ke,Ze,Se)=>{const Fe=[...p];Ze==="file"&&Se instanceof File?Fe[ke]={...Fe[ke],file:Se}:Fe[ke]={...Fe[ke],[Ze]:Se},f(Fe)},le=()=>{v([...y,{title:"",canva_share_link:"",sort_order:y.length}])},be=ke=>{v(y.filter((Ze,Se)=>Se!==ke))},me=(ke,Ze,Se)=>{const Fe=[...y];Fe[ke]={...Fe[ke],[Ze]:Se},v(Fe)},he=async(ke,Ze)=>{try{const Se=await q.functions.invoke("bunny-upload",{body:{action:"create",title:ke.name}});if(Se.error)throw Se.error;const{videoId:Fe,uploadUrl:Ne,libraryId:Ye}=Se.data,Ve=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:Fe,libraryId:Ye}});if(Ve.error)throw Ve.error;const{uploadUrl:qe,apiKey:Qe}=Ve.data,Ue=new XMLHttpRequest;return Ue.open("PUT",qe,!0),Ue.setRequestHeader("AccessKey",Qe),Ue.upload.onprogress=Xe=>{if(Xe.lengthComputable){const nt=Math.round(Xe.loaded/Xe.total*100),$e=[...p];$e[Ze]={...$e[Ze],uploadProgress:nt},f($e)}},await new Promise((Xe,nt)=>{Ue.onload=()=>Ue.status>=200&&Ue.status<300?Xe():nt(new Error("Upload failed")),Ue.onerror=()=>nt(new Error("Upload failed")),Ue.send(ke)}),`https://iframe.mediadelivery.net/embed/${Ye}/${Fe}`}catch(Se){throw console.error("Bunny upload error:",Se),Se}},pe=mt({mutationFn:async ke=>{const{data:Ze,error:Se}=await q.from("brokerage_resource_categories").insert({name:ke,sort_order:(V==null?void 0:V.length)||0}).select().single();if(Se)throw Se;return Ze},onSuccess:ke=>{s.invalidateQueries({queryKey:["brokerage-resource-categories"]}),l({...i,category_id:ke.id}),E(""),se.success("Category created")},onError:ke=>{se.error("Failed to create category: "+ke.message)}}),Ce=mt({mutationFn:async()=>{b(!0);let ke=(r==null?void 0:r.preview_image_url)||null;if(o){const Fe=o.name.split(".").pop(),Ne=`${Date.now()}.${Fe}`,{error:Ye}=await q.storage.from("brokerage-resources").upload(`previews/${Ne}`,o);if(Ye)throw Ye;const{data:Ve}=q.storage.from("brokerage-resources").getPublicUrl(`previews/${Ne}`);ke=Ve.publicUrl}const Ze={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:Fe}=await q.from("brokerage_resources").update(Ze).eq("id",r.id);if(Fe)throw Fe;Se=r.id;const Ne=(I==null?void 0:I.filter(Ge=>Ge.resource_id===r.id).map(Ge=>Ge.id))||[],Ye=h.filter(Ge=>Ge.id).map(Ge=>Ge.id),Ve=Ne.filter(Ge=>!Ye.includes(Ge));Ve.length>0&&await q.from("brokerage_resource_pdfs").delete().in("id",Ve);const qe=(D==null?void 0:D.filter(Ge=>Ge.resource_id===r.id).map(Ge=>Ge.id))||[],Qe=p.filter(Ge=>Ge.id).map(Ge=>Ge.id),Ue=qe.filter(Ge=>!Qe.includes(Ge));Ue.length>0&&await q.from("brokerage_resource_videos").delete().in("id",Ue);const Xe=(O==null?void 0:O.filter(Ge=>Ge.resource_id===r.id).map(Ge=>Ge.id))||[],nt=y.filter(Ge=>Ge.id).map(Ge=>Ge.id),$e=Xe.filter(Ge=>!nt.includes(Ge));$e.length>0&&await q.from("brokerage_resource_links").delete().in("id",$e)}else{const{data:Fe,error:Ne}=await q.from("brokerage_resources").insert(Ze).select().single();if(Ne)throw Ne;Se=Fe.id}for(let Fe=0;Fe{s.invalidateQueries({queryKey:["brokerage-resources"]}),s.invalidateQueries({queryKey:["brokerage-resource-pdfs"]}),s.invalidateQueries({queryKey:["brokerage-resource-videos"]}),s.invalidateQueries({queryKey:["brokerage-resource-links"]}),se.success(r?"Resource updated":"Resource created"),n(!1),$(),b(!1)},onError:ke=>{se.error("Failed to save resource: "+ke.message),b(!1)}}),Ae=mt({mutationFn:async ke=>{const{error:Ze}=await q.from("brokerage_resources").delete().eq("id",ke);if(Ze)throw Ze},onSuccess:()=>{s.invalidateQueries({queryKey:["brokerage-resources"]}),s.invalidateQueries({queryKey:["brokerage-resource-pdfs"]}),s.invalidateQueries({queryKey:["brokerage-resource-videos"]}),s.invalidateQueries({queryKey:["brokerage-resource-links"]}),se.success("Resource deleted")},onError:ke=>{se.error("Failed to delete: "+ke.message)}}),Pe=ke=>{if(ke.preventDefault(),!i.title){se.error("Please enter a title");return}Ce.mutate()},ze=ke=>{const Ze=(I==null?void 0:I.filter(Ne=>Ne.resource_id===ke).length)||0,Se=(D==null?void 0:D.filter(Ne=>Ne.resource_id===ke).length)||0,Fe=(O==null?void 0:O.filter(Ne=>Ne.resource_id===ke).length)||0;return{pdfCount:Ze,videoCount:Se,linkCount:Fe}};return e.jsx(zs,{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(ve,{children:[e.jsx(bt,{className:"pb-2",children:e.jsx(St,{className:"text-sm font-medium text-muted-foreground",children:"Total Resources"})}),e.jsx(Me,{children:e.jsx("div",{className:"text-2xl font-bold",children:(P==null?void 0:P.length)||0})})]}),e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-2",children:e.jsx(St,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Me,{children:e.jsx("div",{className:"text-2xl font-bold",children:(P==null?void 0:P.filter(ke=>ke.is_published).length)||0})})]})]}),e.jsxs(B,{onClick:()=>{$(),n(!0)},children:[e.jsx(rn,{className:"h-4 w-4 mr-2"}),"Add Resource"]})]}),e.jsx(ve,{children:e.jsx(Me,{className:"p-0",children:e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"Title"}),e.jsx(Pt,{children:"Category"}),e.jsx(Pt,{children:"Content"}),e.jsx(Pt,{children:"Publish Date"}),e.jsx(Pt,{children:"Status"}),e.jsx(Pt,{className:"text-right",children:"Actions"})]})}),e.jsx(Ka,{children:M?e.jsx(pn,{children:e.jsx(gt,{colSpan:6,className:"text-center py-8",children:"Loading..."})}):(P==null?void 0:P.length)===0?e.jsx(pn,{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:Ze,videoCount:Se,linkCount:Fe}=ze(ke.id),Ne=V==null?void 0:V.find(Ye=>Ye.id===ke.category_id);return e.jsxs(pn,{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(Cx,{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:Ne?e.jsx("span",{className:"inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-muted",children:Ne.name}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-3 text-sm text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Fr,{className:"h-3.5 w-3.5"}),Ze]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Kr,{className:"h-3.5 w-3.5"}),Se]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Vc,{className:"h-3.5 w-3.5"}),Fe]})]})}),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(B,{variant:"ghost",size:"icon",onClick:()=>{const Ye=(I==null?void 0:I.filter(Qe=>Qe.resource_id===ke.id))||[],Ve=(D==null?void 0:D.filter(Qe=>Qe.resource_id===ke.id))||[],qe=(O==null?void 0:O.filter(Qe=>Qe.resource_id===ke.id))||[];S({...ke,pdfs:Ye,videos:Ve,links:qe})},children:e.jsx(ya,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>H(ke),children:e.jsx(Ya,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:async()=>{await Xi("Delete this resource?")&&Ae.mutate(ke.id)},children:e.jsx(Sn,{className:"h-4 w-4 text-destructive"})})]})})]},ke.id)})})]})})}),e.jsx(Ls,{open:t,onOpenChange:n,children:e.jsxs(Ps,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Ds,{children:r?"Edit Brokerage Resource":"Add Brokerage Resource"})}),e.jsxs("form",{onSubmit:Pe,className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{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(Cx,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx(xe,{type:"file",accept:"image/*",onChange:Y})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"title",children:"Title *"}),e.jsx(xe,{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(J,{className:"flex items-center gap-2",children:[e.jsx(Ep,{className:"h-4 w-4"}),"Category"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(is,{value:i.category_id,onValueChange:ke=>l({...i,category_id:ke}),children:[e.jsx(rs,{className:"flex-1",children:e.jsx(ls,{placeholder:"Select a category"})}),e.jsx(as,{children:V==null?void 0:V.map(ke=>e.jsx(He,{value:ke.id,children:ke.name},ke.id))})]}),i.category_id&&e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>l({...i,category_id:""}),children:e.jsx(Qn,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{placeholder:"Or create new category...",value:C,onChange:ke=>E(ke.target.value),className:"flex-1"}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",disabled:!C.trim()||pe.isPending,onClick:()=>pe.mutate(C.trim()),children:[e.jsx(rn,{className:"h-4 w-4 mr-1"}),"Add"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Description"}),e.jsx(BN,{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(J,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(xe,{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(J,{children:"Published"}),e.jsxs("div",{className:"flex items-center space-x-2 pt-2",children:[e.jsx(fn,{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(J,{className:"flex items-center gap-2",children:[e.jsx(Fr,{className:"h-4 w-4"}),"PDF Documents (",h.length,")"]}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:Z,children:[e.jsx(rn,{className:"h-4 w-4 mr-1"}),"Add PDF"]})]}),h.map((ke,Ze)=>e.jsxs("div",{className:"flex items-center gap-2 p-3 border rounded-lg bg-muted/50",children:[e.jsx(xe,{placeholder:"PDF Name",value:ke.name,onChange:Se=>ce(Ze,"name",Se.target.value),className:"flex-1"}),e.jsx(xe,{type:"file",accept:".pdf",onChange:Se=>{var Ne;const Fe=(Ne=Se.target.files)==null?void 0:Ne[0];Fe&&ce(Ze,"file",Fe)},className:"flex-1"}),ke.file_url&&!ke.file&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Uploaded"}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>ne(Ze),children:e.jsx(Qn,{className:"h-4 w-4"})})]},Ze))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(J,{className:"flex items-center gap-2",children:[e.jsx(Kr,{className:"h-4 w-4"}),"Videos (",p.length,")"]}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:ie,children:[e.jsx(rn,{className:"h-4 w-4 mr-1"}),"Add Video"]})]}),p.map((ke,Ze)=>e.jsxs("div",{className:"space-y-2 p-3 border rounded-lg bg-muted/50",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xe,{placeholder:"Video Title",value:ke.title,onChange:Se=>ae(Ze,"title",Se.target.value),className:"flex-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>te(Ze),children:e.jsx(Qn,{className:"h-4 w-4"})})]}),e.jsx(xe,{type:"file",accept:"video/*",onChange:Se=>{var Ne;const Fe=(Ne=Se.target.files)==null?void 0:Ne[0];Fe&&ae(Ze,"file",Fe)}}),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"})]},Ze))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(J,{className:"flex items-center gap-2",children:[e.jsx(Vc,{className:"h-4 w-4"}),"Canva Links (",y.length,")"]}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:le,children:[e.jsx(rn,{className:"h-4 w-4 mr-1"}),"Add Link"]})]}),y.map((ke,Ze)=>e.jsxs("div",{className:"flex items-center gap-2 p-3 border rounded-lg bg-muted/50",children:[e.jsx(xe,{placeholder:"Link Title",value:ke.title,onChange:Se=>me(Ze,"title",Se.target.value),className:"flex-1"}),e.jsx(xe,{placeholder:"Canva Share Link",value:ke.canva_share_link,onChange:Se=>me(Ze,"canva_share_link",Se.target.value),className:"flex-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>be(Ze),children:e.jsx(Qn,{className:"h-4 w-4"})})]},Ze))]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(B,{type:"submit",disabled:Ce.isPending||g,children:Ce.isPending||g?"Saving...":r?"Update":"Create"})]})]})]})}),e.jsx(Ls,{open:!!j,onOpenChange:()=>S(null),children:e.jsxs(Ps,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Ds,{children:j==null?void 0:j.title})}),j&&e.jsxs("div",{className:"space-y-4",children:[j.preview_image_url&&e.jsx("img",{src:j.preview_image_url,alt:j.title,className:"w-full h-48 object-cover rounded-lg"}),j.description&&e.jsx("p",{className:"text-muted-foreground",children:j.description}),j.pdfs&&j.pdfs.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2 flex items-center gap-2",children:[e.jsx(Fr,{className:"h-4 w-4"}),"PDF Documents (",j.pdfs.length,")"]}),e.jsx("div",{className:"space-y-1",children:j.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))})]}),j.videos&&j.videos.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2 flex items-center gap-2",children:[e.jsx(Kr,{className:"h-4 w-4"}),"Videos (",j.videos.length,")"]}),e.jsx("div",{className:"space-y-2",children:j.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))})]}),j.links&&j.links.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2 flex items-center gap-2",children:[e.jsx(Vc,{className:"h-4 w-4"}),"Canva Links (",j.links.length,")"]}),e.jsx("div",{className:"space-y-1",children:j.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 jKt=[{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 sTn(){const[s,t]=_.useState([]),[n,r]=_.useState(!0),[a,i]=_.useState(!1),[l,o]=_.useState(!1),[c,d]=_.useState(null),[u,h]=_.useState(!1),[m,p]=_.useState(!1),[f,y]=_.useState(""),[v,g]=_.useState(""),[b,j]=_.useState(""),[S,C]=_.useState(""),[E,P]=_.useState("Learn More"),[M,I]=_.useState("top"),[D,O]=_.useState(""),[V,G]=_.useState(!0),[$,H]=_.useState(""),[Y,Z]=_.useState("");_.useEffect(()=>{ne()},[]);const ne=async()=>{try{const{data:pe,error:Ce}=await q.from("dashboard_banners").select("*").order("placement").order("sort_order");if(Ce)throw Ce;t(pe||[])}catch(pe){se.error("Failed to load banners: "+pe.message)}finally{r(!1)}},ce=()=>{y(""),g(""),j(""),C(""),P("Learn More"),I("top"),O(""),G(!0),H(""),Z(""),d(null)},ie=pe=>{d(pe),y(pe.title),g(pe.description||""),j(pe.image_url),C(pe.link_url||""),P(pe.link_text||"Learn More"),I(pe.placement),O(pe.section_after||""),G(pe.is_active),H(pe.start_date?Hs(new Date(pe.start_date),"yyyy-MM-dd'T'HH:mm"):""),Z(pe.end_date?Hs(new Date(pe.end_date),"yyyy-MM-dd'T'HH:mm"):""),i(!0)},te=async pe=>{var Ae;const Ce=(Ae=pe.target.files)==null?void 0:Ae[0];if(Ce){h(!0);try{const Pe=Ce.name.split(".").pop(),ze=`${Date.now()}.${Pe}`,{error:ke}=await q.storage.from("banner-images").upload(ze,Ce);if(ke)throw ke;const{data:{publicUrl:Ze}}=q.storage.from("banner-images").getPublicUrl(ze);j(Ze),se.success("Image uploaded successfully")}catch(Pe){se.error("Failed to upload image: "+Pe.message)}finally{h(!1)}}},ae=async()=>{if(!f.trim()||!b){se.error("Please fill in required fields (title and image)");return}p(!0);try{const pe={title:f.trim(),description:v.trim()||null,image_url:b,link_url:S.trim()||null,link_text:E.trim()||"Learn More",placement:M,section_after:M==="between"?D:null,is_active:V,start_date:$?new Date($).toISOString():null,end_date:Y?new Date(Y).toISOString():null};if(c){const{error:Ce}=await q.from("dashboard_banners").update(pe).eq("id",c.id);if(Ce)throw Ce;se.success("Banner updated successfully")}else{const Ce=s.filter(Pe=>Pe.placement===M).length,{error:Ae}=await q.from("dashboard_banners").insert({...pe,sort_order:Ce});if(Ae)throw Ae;se.success("Banner created successfully")}i(!1),ce(),ne()}catch(pe){se.error("Failed to save banner: "+pe.message)}finally{p(!1)}},le=async()=>{if(c)try{const{error:pe}=await q.from("dashboard_banners").delete().eq("id",c.id);if(pe)throw pe;se.success("Banner deleted successfully"),o(!1),d(null),ne()}catch(pe){se.error("Failed to delete banner: "+pe.message)}},be=async pe=>{try{const{error:Ce}=await q.from("dashboard_banners").update({is_active:!pe.is_active}).eq("id",pe.id);if(Ce)throw Ce;se.success(pe.is_active?"Banner deactivated":"Banner activated"),ne()}catch(Ce){se.error("Failed to update banner: "+Ce.message)}},me=s.filter(pe=>pe.placement==="top"),he=s.filter(pe=>pe.placement==="between");return n?e.jsx(zs,{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(zs,{title:"Dashboard Management",description:"Configure dashboard modules and banners",children:[e.jsxs("div",{className:"space-y-8",children:[e.jsxs(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(hc,{className:"h-5 w-5"}),"Hero Banners (Top of Dashboard)"]}),e.jsx(kn,{children:"These banners appear in a rotating carousel at the top of the dashboard"})]}),e.jsxs(Ls,{open:a&&M==="top",onOpenChange:pe=>{pe||ce(),i(pe),pe&&I("top")},children:[e.jsx(nl,{asChild:!0,children:e.jsxs(B,{onClick:()=>{ce(),I("top")},children:[e.jsx(rn,{className:"mr-2 h-4 w-4"}),"Add Hero Banner"]})}),e.jsxs(Ps,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsxs(Ds,{children:[c?"Edit":"Create"," Banner"]}),e.jsx(_r,{children:"Configure the banner's content and display settings"})]}),e.jsx(Ywt,{title:f,setTitle:y,description:v,setDescription:g,imageUrl:b,linkUrl:S,setLinkUrl:C,linkText:E,setLinkText:P,placement:M,setPlacement:I,sectionAfter:D,setSectionAfter:O,isActive:V,setIsActive:G,startDate:$,setStartDate:H,endDate:Y,setEndDate:Z,handleImageUpload:te,uploading:u,showPlacementOptions:!1}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>{i(!1),ce()},children:"Cancel"}),e.jsx(B,{onClick:ae,disabled:m,children:m?"Saving...":c?"Update Banner":"Create Banner"})]})]})]})]}),e.jsx(Me,{children:me.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:me.map(pe=>e.jsx(Zwt,{banner:pe,onEdit:()=>ie(pe),onDelete:()=>{d(pe),o(!0)},onToggleActive:()=>be(pe)},pe.id))})})]}),e.jsxs(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(hc,{className:"h-5 w-5"}),"Section Banners"]}),e.jsx(kn,{children:"These banners appear between dashboard content sections"})]}),e.jsxs(Ls,{open:a&&M==="between",onOpenChange:pe=>{pe||ce(),i(pe),pe&&I("between")},children:[e.jsx(nl,{asChild:!0,children:e.jsxs(B,{onClick:()=>{ce(),I("between")},children:[e.jsx(rn,{className:"mr-2 h-4 w-4"}),"Add Section Banner"]})}),e.jsxs(Ps,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsxs(Ds,{children:[c?"Edit":"Create"," Section Banner"]}),e.jsx(_r,{children:"Configure where this banner appears between sections"})]}),e.jsx(Ywt,{title:f,setTitle:y,description:v,setDescription:g,imageUrl:b,linkUrl:S,setLinkUrl:C,linkText:E,setLinkText:P,placement:M,setPlacement:I,sectionAfter:D,setSectionAfter:O,isActive:V,setIsActive:G,startDate:$,setStartDate:H,endDate:Y,setEndDate:Z,handleImageUpload:te,uploading:u,showPlacementOptions:!0}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>{i(!1),ce()},children:"Cancel"}),e.jsx(B,{onClick:ae,disabled:m,children:m?"Saving...":c?"Update Banner":"Create Banner"})]})]})]})]}),e.jsx(Me,{children:he.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No section banners yet. Add your first banner above."}):e.jsx("div",{className:"space-y-3",children:he.map(pe=>e.jsx(Zwt,{banner:pe,onEdit:()=>ie(pe),onDelete:()=>{d(pe),o(!0)},onToggleActive:()=>be(pe),showSection:!0},pe.id))})})]})]}),e.jsx(Ls,{open:l,onOpenChange:o,children:e.jsxs(Ps,{children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Delete Banner"}),e.jsxs(_r,{children:['Are you sure you want to delete "',c==null?void 0:c.title,'"? This action cannot be undone.']})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:le,children:"Delete"})]})]})})]})}function Ywt({title:s,setTitle:t,description:n,setDescription:r,imageUrl:a,linkUrl:i,setLinkUrl:l,linkText:o,setLinkText:c,placement:d,setPlacement:u,sectionAfter:h,setSectionAfter:m,isActive:p,setIsActive:f,startDate:y,setStartDate:v,endDate:g,setEndDate:b,handleImageUpload:j,uploading:S,showPlacementOptions:C}){return e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"title",children:"Title *"}),e.jsx(xe,{id:"title",placeholder:"Banner headline...",value:s,onChange:E=>t(E.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"description",children:"Description"}),e.jsx(Ms,{id:"description",placeholder:"Optional banner description...",value:n,onChange:E=>r(E.target.value),rows:2})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Banner Image *"}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(xe,{type:"file",accept:"image/*",onChange:j,disabled:S,className:"flex-1"}),S&&e.jsx("span",{className:"text-sm text-muted-foreground",children:"Uploading..."})]}),a&&e.jsx("div",{className:"mt-2 relative rounded-lg overflow-hidden border",children:e.jsx("img",{src:a,alt:"Preview",className:"w-full h-40 object-cover"})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"linkUrl",children:"Link URL (optional)"}),e.jsx(xe,{id:"linkUrl",placeholder:"https://...",value:i,onChange:E=>l(E.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"linkText",children:"Button Text"}),e.jsx(xe,{id:"linkText",placeholder:"Learn More",value:o,onChange:E=>c(E.target.value)})]})]}),C&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Placement"}),e.jsxs(is,{value:h,onValueChange:m,children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Select section placement..."})}),e.jsx(as,{children:jKt.map(E=>e.jsx(He,{value:E.value,children:E.label},E.value))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(J,{htmlFor:"startDate",className:"flex items-center gap-2",children:[e.jsx(ga,{className:"h-4 w-4"}),"Start Date (optional)"]}),e.jsx(xe,{id:"startDate",type:"datetime-local",value:y,onChange:E=>v(E.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(J,{htmlFor:"endDate",className:"flex items-center gap-2",children:[e.jsx(ga,{className:"h-4 w-4"}),"End Date (optional)"]}),e.jsx(xe,{id:"endDate",type:"datetime-local",value:g,onChange:E=>b(E.target.value)})]})]}),e.jsx("div",{className:"flex items-center justify-between pt-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fn,{id:"isActive",checked:p,onCheckedChange:f}),e.jsx(J,{htmlFor:"isActive",children:"Active"})]})})]})}function Zwt({banner:s,onEdit:t,onDelete:n,onToggleActive:r,showSection:a=!1}){var c;const i=(c=jKt.find(d=>d.value===s.section_after))==null?void 0:c.label,[l,o]=_.useState(null);return _.useEffect(()=>{(async()=>{const{count:u}=await q.from("content_engagement_logs").select("*",{count:"exact",head:!0}).eq("resource_id",s.id).eq("action_type","click_link");o(u??0)})()},[s.id]),e.jsxs("div",{className:"flex items-center gap-4 p-3 border rounded-lg bg-card hover:bg-accent/50 transition-colors",children:[e.jsx(Vf,{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(Oe,{variant:"secondary",children:"Inactive"}),s.start_date&&new Date(s.start_date)>new Date&&e.jsx(Oe,{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($h,{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(B,{variant:"ghost",size:"icon",children:e.jsx(wr,{className:"h-4 w-4"})})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:r,children:s.is_active?e.jsx(ya,{className:"h-4 w-4"}):e.jsx(Ax,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:t,children:e.jsx(Ya,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:n,children:e.jsx(Sn,{className:"h-4 w-4 text-destructive"})})]})]})}const Mce={open:{label:"Open",icon:Gr,color:"bg-yellow-500"},in_progress:{label:"In Progress",icon:Ou,color:"bg-blue-500"},resolved:{label:"Resolved",icon:_l,color:"bg-green-500"},closed:{label:"Closed",icon:Rd,color:"bg-muted-foreground"}},Xwt={general:"General Support",technology:"Technology Support",crm:"CRM Support",marketing:"Marketing Support"};function nTn(){var M,I;const{user:s}=hs(),t=Bt(),[n,r]=_.useState(null),[a,i]=_.useState(""),[l,o]=_.useState([]),[c,d]=_.useState("all"),[u,h]=_.useState("all"),[m,p]=_.useState(!1),{data:f=[],isLoading:y}=at({queryKey:["admin-support-tickets",c,u],queryFn:async()=>{let D=q.from("support_tickets").select("*, profiles!support_tickets_user_id_fkey(name, email)").order("created_at",{ascending:!1});c!=="all"&&(D=D.eq("status",c)),u!=="all"&&(D=D.eq("category",u));const{data:O,error:V}=await D;if(V)throw V;return O}}),{data:v=[]}=at({queryKey:["admin-users-notifications"],queryFn:async()=>{const{data:D,error:O}=await q.from("user_roles").select("user_id").eq("role","admin");if(O)throw O;const V=D.map(ne=>ne.user_id),{data:G,error:$}=await q.from("profiles").select("id, name, email").in("id",V);if($)throw $;const{data:H,error:Y}=await q.from("support_notification_settings").select("user_id, receive_notifications");if(Y)throw Y;const Z=new Map((H==null?void 0:H.map(ne=>[ne.user_id,ne.receive_notifications]))||[]);return G.map(ne=>({...ne,receives_notifications:Z.get(ne.id)||!1}))}}),{data:g=[]}=at({queryKey:["admin-ticket-replies",n==null?void 0:n.id],queryFn:async()=>{if(!n)return[];const{data:D,error:O}=await q.from("support_ticket_replies").select("*, profiles(name)").eq("ticket_id",n.id).order("created_at",{ascending:!0});if(O)throw O;return D},enabled:!!n}),b=mt({mutationFn:async({userId:D,enabled:O})=>{const{data:V}=await q.from("support_notification_settings").select("id").eq("user_id",D).maybeSingle();if(V){const{error:G}=await q.from("support_notification_settings").update({receive_notifications:O}).eq("user_id",D);if(G)throw G}else{const{error:G}=await q.from("support_notification_settings").insert({user_id:D,receive_notifications:O});if(G)throw G}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-users-notifications"]}),se.success("Notification settings updated")},onError:()=>{se.error("Failed to update settings")}}),j=mt({mutationFn:async({ticketId:D,status:O})=>{const{error:V}=await q.from("support_tickets").update({status:O}).eq("id",D);if(V)throw V},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-support-tickets"]}),n&&r({...n,status:n.status}),se.success("Status updated")},onError:()=>{se.error("Failed to update status")}}),S=mt({mutationFn:async({ticketId:D,assignedTo:O})=>{const{error:V}=await q.from("support_tickets").update({assigned_to:O}).eq("id",D);if(V)throw V},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-support-tickets"]}),se.success("Ticket assigned")},onError:()=>{se.error("Failed to assign ticket")}}),C=mt({mutationFn:async({content:D,attachments:O})=>{var G,$;if(!n||!s)throw new Error("Missing data");const{error:V}=await q.from("support_ticket_replies").insert({ticket_id:n.id,user_id:s.id,content:D,is_admin_reply:!0,attachments:O});if(V)throw V;try{await q.functions.invoke("support-reply-notify",{body:{ticketId:n.id,ticketSubject:n.subject,replyContent:D,userEmail:(G=n.profiles)==null?void 0:G.email,userName:($=n.profiles)==null?void 0:$.name}})}catch(H){console.error("Failed to send reply notification:",H)}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-ticket-replies",n==null?void 0:n.id]}),i(""),o([]),se.success("Reply sent!")},onError:()=>{se.error("Failed to send reply")}}),E=()=>{!a.trim()&&l.length===0||C.mutate({content:a,attachments:l})};_.useEffect(()=>{const D=q.channel("admin-tickets").on("postgres_changes",{event:"*",schema:"public",table:"support_tickets"},()=>{t.invalidateQueries({queryKey:["admin-support-tickets"]})}).subscribe();return()=>{q.removeChannel(D)}},[t]);const P=f.filter(D=>D.status==="open").length;return n?(Mce[n.status].icon,e.jsx(zs,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(B,{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(Oe,{variant:"secondary",children:Xwt[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(ve,{children:[e.jsx(bt,{className:"pb-2",children:e.jsx(St,{className:"text-sm",children:"Status"})}),e.jsx(Me,{children:e.jsxs(is,{value:n.status,onValueChange:D=>{j.mutate({ticketId:n.id,status:D}),r({...n,status:D})},children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"open",children:"Open"}),e.jsx(He,{value:"in_progress",children:"In Progress"}),e.jsx(He,{value:"resolved",children:"Resolved"}),e.jsx(He,{value:"closed",children:"Closed"})]})]})})]}),e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-2",children:e.jsx(St,{className:"text-sm",children:"Assigned To"})}),e.jsx(Me,{children:e.jsxs(is,{value:n.assigned_to||"unassigned",onValueChange:D=>{const O=D==="unassigned"?null:D;S.mutate({ticketId:n.id,assignedTo:O}),r({...n,assigned_to:O})},children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Unassigned"})}),e.jsxs(as,{children:[e.jsx(He,{value:"unassigned",children:"Unassigned"}),v.map(D=>e.jsx(He,{value:D.id,children:D.name},D.id))]})]})})]})]}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsxs(kn,{children:["Created on ",Hs(new Date(n.created_at),"MMM d, yyyy 'at' h:mm a")]})}),e.jsx(Me,{children:e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:n.description})})]}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-lg",children:"Conversation"})}),e.jsxs(Me,{children:[e.jsx(Ji,{className:"h-[300px] pr-4",children:g.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:g.map(D=>{var O,V;return e.jsxs("div",{className:`p-4 rounded-lg ${D.is_admin_reply?"bg-primary/10 ml-4":"bg-muted mr-4"}`,children:[e.jsxs("div",{className:"flex justify-between items-start mb-2",children:[e.jsx("span",{className:"font-medium text-sm",children:D.is_admin_reply?`${((O=D.profiles)==null?void 0:O.name)||"Admin"} (Support)`:((V=D.profiles)==null?void 0:V.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(_Vt,{attachments:D.attachments})]},D.id)})})}),e.jsx(wc,{className:"my-4"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ms,{placeholder:"Type your reply...",value:a,onChange:D=>i(D.target.value),className:"min-h-[80px]"}),e.jsx(B,{onClick:E,disabled:!a.trim()&&l.length===0||C.isPending,className:"self-end",children:e.jsx(Or,{className:"h-4 w-4"})})]}),e.jsx(bVt,{value:l,onChange:o,disabled:C.isPending})]})]})]})]})})):e.jsx(zs,{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(Oe,{variant:"destructive",className:"ml-2",children:[P," open"]})]})]}),e.jsxs(Ls,{open:m,onOpenChange:p,children:[e.jsx(nl,{asChild:!0,children:e.jsxs(B,{variant:"outline",children:[e.jsx(qc,{className:"h-4 w-4 mr-2"}),"Notification Settings"]})}),e.jsxs(Ps,{children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Email Notification Settings"}),e.jsx(_r,{children:"Choose which admins receive email notifications for new support tickets."})]}),e.jsx("div",{className:"space-y-4 mt-4",children:v.map(D=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Fo,{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(Rg,{className:"h-4 w-4 text-primary"}):e.jsx(cS,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(fn,{checked:D.receives_notifications,onCheckedChange:O=>b.mutate({userId:D.id,enabled:O})})]})]},D.id))})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-4 items-center",children:[e.jsx(Yr,{value:c,onValueChange:d,className:"w-auto",children:e.jsxs(Zr,{children:[e.jsx(Ht,{value:"all",children:"All"}),e.jsx(Ht,{value:"open",children:"Open"}),e.jsx(Ht,{value:"in_progress",children:"In Progress"}),e.jsx(Ht,{value:"resolved",children:"Resolved"}),e.jsx(Ht,{value:"closed",children:"Closed"})]})}),e.jsxs(is,{value:u,onValueChange:h,children:[e.jsx(rs,{className:"w-[180px]",children:e.jsx(ls,{placeholder:"All Categories"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Categories"}),e.jsx(He,{value:"general",children:"General Support"}),e.jsx(He,{value:"technology",children:"Technology Support"}),e.jsx(He,{value:"crm",children:"CRM Support"}),e.jsx(He,{value:"marketing",children:"Marketing Support"})]})]})]}),e.jsx("div",{className:"mt-4",children:y?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading tickets..."}):f.length===0?e.jsx(ve,{children:e.jsxs(Me,{className:"text-center py-12",children:[e.jsx(Ou,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No tickets found"}),e.jsx("p",{className:"text-muted-foreground",children:"No support tickets match the current filters."})]})}):e.jsx("div",{className:"space-y-3",children:f.map(D=>{var V,G;const O=Mce[D.status].icon;return e.jsx(ve,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>r(D),children:e.jsx(Me,{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(Oe,{variant:"outline",className:"text-xs",children:Xwt[D.category]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[(V=D.profiles)==null?void 0:V.name," • ",Hs(new Date(D.created_at),"MMM d, yyyy")]}),D.assigned_to&&e.jsxs(Oe,{variant:"secondary",className:"text-xs gap-1",children:[e.jsx(Fo,{className:"h-3 w-3"}),((G=v.find($=>$.id===D.assigned_to))==null?void 0:G.name)||"Assigned"]})]})]}),e.jsxs(Oe,{className:Mce[D.status].color,children:[e.jsx(O,{className:"h-3 w-3 mr-1"}),Mce[D.status].label]})]})})},D.id)})})})]})]})})}const NKt=Tv.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 rTn({content:s,onChange:t,variables:n}){const r=ALe({extensions:[ELe,MLe.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline"}}),PLe.configure({types:["heading","paragraph"]}),rtt,NKt],content:s,onUpdate:({editor:l})=>{t(l.getHTML())}});_.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(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().toggleBold().run(),className:r.isActive("bold")?"bg-muted":"",children:e.jsx(BA,{className:"h-4 w-4"})}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().toggleItalic().run(),className:r.isActive("italic")?"bg-muted":"",children:e.jsx($A,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().toggleBulletList().run(),className:r.isActive("bulletList")?"bg-muted":"",children:e.jsx(A0,{className:"h-4 w-4"})}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().toggleOrderedList().run(),className:r.isActive("orderedList")?"bg-muted":"",children:e.jsx(xj,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().setTextAlign("left").run(),className:r.isActive({textAlign:"left"})?"bg-muted":"",children:e.jsx(qM,{className:"h-4 w-4"})}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().setTextAlign("center").run(),className:r.isActive({textAlign:"center"})?"bg-muted":"",children:e.jsx(UM,{className:"h-4 w-4"})}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().setTextAlign("right").run(),className:r.isActive({textAlign:"right"})?"bg-muted":"",children:e.jsx($M,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:i,className:r.isActive("link")?"bg-muted":"",children:e.jsx(Vc,{className:"h-4 w-4"})}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().toggleCodeBlock().run(),className:r.isActive("codeBlock")?"bg-muted":"",children:e.jsx(UA,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().undo().run(),disabled:!r.can().undo(),children:e.jsx(JA,{className:"h-4 w-4"})}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().redo().run(),disabled:!r.can().redo(),children:e.jsx(XA,{className:"h-4 w-4"})}),e.jsx("div",{className:"flex-1"}),n.length>0&&e.jsxs(tu,{children:[e.jsx(su,{asChild:!0,children:e.jsxs(B,{type:"button",variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(p$,{className:"h-4 w-4"}),"Insert Variable"]})}),e.jsx(Od,{align:"end",className:"w-64",children:n.map(l=>e.jsxs(ca,{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(CLe,{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(Oe,{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 aTn(){const s=Bt(),[t,n]=_.useState(null),[r,a]=_.useState(null),[i,l]=_.useState(""),[o,c]=_.useState(""),[d,u]=_.useState(""),[h,m]=_.useState(!0),[p,f]=_.useState("visual"),{data:y,isLoading:v}=at({queryKey:["email-templates"],queryFn:async()=>{const{data:C,error:E}=await q.from("email_templates").select("*").order("name");if(E)throw E;return C.map(P=>({...P,available_variables:P.available_variables||[]}))}}),g=mt({mutationFn:async C=>{const{error:E}=await q.from("email_templates").update({subject:C.subject,body_html:C.body_html,description:C.description,is_active:C.is_active}).eq("id",C.id);if(E)throw E},onSuccess:()=>{s.invalidateQueries({queryKey:["email-templates"]}),se.success("Email template updated successfully"),n(null)},onError:C=>{se.error("Failed to update template: "+C.message)}}),b=C=>{n(C),l(C.subject),c(C.body_html),u(C.description||""),m(C.is_active),f("visual")},j=()=>{t&&g.mutate({id:t.id,subject:i,body_html:o,description:d,is_active:h})},S=(C,E)=>{let P=C;return E.forEach(M=>{const I=`{{${M.key}}}`,D=`[${M.label}]`;P=P.replace(new RegExp(I.replace(/[{}]/g,"\\$&"),"g"),D)}),P};return t?e.jsxs(zs,{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(B,{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(B,{variant:"outline",onClick:()=>a(t),children:[e.jsx(ya,{className:"h-4 w-4 mr-2"}),"Preview"]}),e.jsxs(B,{onClick:j,disabled:g.isPending,children:[e.jsx(Ho,{className:"h-4 w-4 mr-2"}),g.isPending?"Saving...":"Save Changes"]})]}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(ln,{className:"h-5 w-5"}),t.name]}),e.jsxs(kn,{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(J,{htmlFor:"active-toggle",children:"Active"}),e.jsx(fn,{id:"active-toggle",checked:h,onCheckedChange:m})]})]})}),e.jsxs(Me,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"description",children:"Description"}),e.jsx(Ms,{id:"description",value:d,onChange:C=>u(C.target.value),placeholder:"Brief description of when this email is sent",rows:2})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"subject",children:"Email Subject"}),e.jsx(xe,{id:"subject",value:i,onChange:C=>l(C.target.value),placeholder:"Email subject line"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["You can use variables like ","{{name}}"," in the subject"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(J,{children:"Email Body"}),e.jsx(Yr,{value:p,onValueChange:C=>f(C),children:e.jsxs(Zr,{className:"h-8",children:[e.jsxs(Ht,{value:"visual",className:"text-xs px-3 h-6",children:[e.jsx(hN,{className:"h-3 w-3 mr-1"}),"Visual"]}),e.jsxs(Ht,{value:"html",className:"text-xs px-3 h-6",children:[e.jsx(UA,{className:"h-3 w-3 mr-1"}),"HTML"]})]})})]}),p==="visual"?e.jsx(rTn,{content:o,onChange:c,variables:t.available_variables}):e.jsx(Ms,{value:o,onChange:C=>c(C.target.value),className:"font-mono text-sm min-h-[400px]",placeholder:"HTML email body"})]})]})]})]}),e.jsx(Ls,{open:!!r,onOpenChange:()=>a(null),children:e.jsxs(Ps,{className:"max-w-3xl max-h-[90vh] overflow-auto",children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Email Preview"}),e.jsxs(_r,{children:["Subject: ",i.replace(/\{\{(\w+)\}\}/g,"[$1]")]})]}),e.jsx("div",{className:"border rounded-lg p-4 bg-white",children:e.jsx("div",{dangerouslySetInnerHTML:{__html:S(o,t.available_variables)}})})]})})]}):e.jsx(zs,{title:"Email Templates",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Email Templates"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Manage and customize system email templates"})]}),v?e.jsx("div",{className:"grid gap-4",children:[...Array(4)].map((C,E)=>e.jsx(ve,{children:e.jsxs(bt,{children:[e.jsx(cn,{className:"h-5 w-48"}),e.jsx(cn,{className:"h-4 w-96"})]})},E))}):e.jsx("div",{className:"grid gap-4",children:y==null?void 0:y.map(C=>e.jsxs(ve,{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(St,{className:"flex items-center gap-2 text-lg",children:[e.jsx(ln,{className:"h-5 w-5 text-muted-foreground"}),C.name,!C.is_active&&e.jsx(Oe,{variant:"secondary",children:"Inactive"})]}),e.jsx(kn,{children:C.description})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>a(C),children:[e.jsx(ya,{className:"h-4 w-4 mr-2"}),"Preview"]}),e.jsxs(B,{size:"sm",onClick:()=>b(C),children:[e.jsx(wp,{className:"h-4 w-4 mr-2"}),"Edit"]})]})]})}),e.jsx(Me,{children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Subject:"}),e.jsx("code",{className:"bg-muted px-2 py-0.5 rounded text-sm",children:C.subject})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Variables:"}),e.jsx("div",{className:"flex flex-wrap gap-1",children:C.available_variables.map(E=>e.jsx(Oe,{variant:"outline",className:"font-mono text-xs",children:`{{${E.key}}}`},E.key))})]})]})})]},C.id))}),e.jsx(Ls,{open:!!r&&!t,onOpenChange:()=>a(null),children:e.jsxs(Ps,{className:"max-w-3xl max-h-[90vh] overflow-auto",children:[e.jsxs(Os,{children:[e.jsxs(Ds,{children:["Email Preview: ",r==null?void 0:r.name]}),e.jsxs(_r,{children:["Subject: ",r==null?void 0:r.subject.replace(/\{\{(\w+)\}\}/g,"[$1]")]})]}),r&&e.jsx("div",{className:"border rounded-lg p-4 bg-white",children:e.jsx("div",{dangerouslySetInnerHTML:{__html:S(r.body_html,r.available_variables)}})})]})})]})})}function iTn(){const s=Bt(),[t,n]=_.useState("templates"),[r,a]=_.useState(null),[i,l]=_.useState(null),[o,c]=_.useState(!1),[d,u]=_.useState(!1),[h,m]=_.useState({title:"",subject:"",body:"",description:"",tone:"",category_id:"",is_active:!0}),[p,f]=_.useState({name:"",description:"",icon:"📧"}),{data:y=[]}=at({queryKey:["agent-email-template-categories"],queryFn:async()=>{const{data:D,error:O}=await q.from("email_template_categories").select("*").order("sort_order");if(O)throw O;return D}}),{data:v=[],isLoading:g}=at({queryKey:["agent-email-templates-admin"],queryFn:async()=>{const{data:D,error:O}=await q.from("agent_email_templates").select("*, category:email_template_categories(*)").order("sort_order");if(O)throw O;return D}}),b=mt({mutationFn:async D=>{const O={title:D.title,subject:D.subject,body:D.body,description:D.description||null,tone:D.tone||null,category_id:D.category_id||null,is_active:D.is_active};if(D.id){const{error:V}=await q.from("agent_email_templates").update(O).eq("id",D.id);if(V)throw V}else{const{error:V}=await q.from("agent_email_templates").insert(O);if(V)throw V}},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-email-templates-admin"]}),c(!1),se.success(r?"Template updated":"Template created")},onError:()=>se.error("Failed to save template")}),j=mt({mutationFn:async D=>{const{error:O}=await q.from("agent_email_templates").delete().eq("id",D);if(O)throw O},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-email-templates-admin"]}),se.success("Template deleted")}}),S=mt({mutationFn:async D=>{const O={name:D.name,description:D.description||null,icon:D.icon};if(D.id){const{error:V}=await q.from("email_template_categories").update(O).eq("id",D.id);if(V)throw V}else{const V=y.length>0?Math.max(...y.map($=>$.sort_order))+1:0,{error:G}=await q.from("email_template_categories").insert({...O,sort_order:V});if(G)throw G}},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-email-template-categories"]}),u(!1),se.success(i?"Category updated":"Category created")},onError:()=>se.error("Failed to save category")}),C=mt({mutationFn:async D=>{const{error:O}=await q.from("email_template_categories").delete().eq("id",D);if(O)throw O},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-email-template-categories"]}),se.success("Category deleted")}}),E=()=>{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),f({name:"",description:"",icon:"📧"}),u(!0)},I=D=>{l(D),f({name:D.name,description:D.description||"",icon:D.icon}),u(!0)};return e.jsx(zs,{children:e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsx(Wh,{title:"Agent Email Templates",description:"Manage email templates that agents use when composing emails from Mission Control."}),e.jsxs(Yr,{value:t,onValueChange:n,children:[e.jsxs(Zr,{children:[e.jsxs(Ht,{value:"templates",className:"gap-2",children:[e.jsx(ln,{className:"h-4 w-4"})," Templates"]}),e.jsxs(Ht,{value:"categories",className:"gap-2",children:[e.jsx(wy,{className:"h-4 w-4"})," Categories"]})]}),e.jsxs(Gt,{value:"templates",className:"space-y-4",children:[e.jsx("div",{className:"flex justify-end",children:e.jsxs(B,{onClick:E,className:"gap-2",children:[e.jsx(rn,{className:"h-4 w-4"})," Add Template"]})}),e.jsx(ve,{children:e.jsx(Me,{className:"p-0",children:e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"Template"}),e.jsx(Pt,{className:"hidden md:table-cell",children:"Category"}),e.jsx(Pt,{className:"hidden md:table-cell",children:"Tone"}),e.jsx(Pt,{children:"Status"}),e.jsx(Pt,{className:"text-right",children:"Actions"})]})}),e.jsx(Ka,{children:g?e.jsx(pn,{children:e.jsx(gt,{colSpan:5,className:"text-center py-8",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin mx-auto"})})}):v.length===0?e.jsx(pn,{children:e.jsx(gt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No templates yet. Create your first one!"})}):v.map(D=>e.jsxs(pn,{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(Oe,{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(Oe,{variant:"secondary",children:D.tone}):"—"}),e.jsx(gt,{children:e.jsx(Oe,{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(B,{variant:"ghost",size:"icon",onClick:()=>P(D),children:e.jsx(Ya,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",onClick:async()=>{await Xi("Delete this template?")&&j.mutate(D.id)},children:e.jsx(Sn,{className:"h-4 w-4"})})]})})]},D.id))})]})})})]}),e.jsxs(Gt,{value:"categories",className:"space-y-4",children:[e.jsx("div",{className:"flex justify-end",children:e.jsxs(B,{onClick:M,className:"gap-2",children:[e.jsx(rn,{className:"h-4 w-4"})," Add Category"]})}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:y.map(D=>e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(St,{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(B,{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(B,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive",onClick:async()=>{await Xi("Delete this category?")&&C.mutate(D.id)},children:e.jsx(Sn,{className:"h-3.5 w-3.5"})})]})]})}),e.jsxs(Me,{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:D.description||"No description"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:[v.filter(O=>O.category_id===D.id).length," templates"]})]})]},D.id))})]})]}),e.jsx(Ls,{open:o,onOpenChange:c,children:e.jsxs(Ps,{className:"sm:max-w-[700px] max-h-[90vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Ds,{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(J,{children:"Title"}),e.jsx(xe,{value:h.title,onChange:D=>m(O=>({...O,title:D.target.value})),placeholder:"e.g. Quick Check-in"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Category"}),e.jsxs(is,{value:h.category_id,onValueChange:D=>m(O=>({...O,category_id:D})),children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Select category"})}),e.jsx(as,{children:y.map(D=>e.jsxs(He,{value:D.id,children:[D.icon," ",D.name]},D.id))})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Subject Line"}),e.jsx(xe,{value:h.subject,onChange:D=>m(O=>({...O,subject:D.target.value})),placeholder:"e.g. Hey {{first_name}}, just checking in!"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Use ","{{first_name}}",", ","{{last_name}}",", ","{{full_name}}"," for merge variables"]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Email Body"}),e.jsx(Ms,{value:h.body,onChange:D=>m(O=>({...O,body:D.target.value})),rows:12,placeholder:"Write your email template...",className:"resize-y"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Description (internal)"}),e.jsx(xe,{value:h.description,onChange:D=>m(O=>({...O,description:D.target.value})),placeholder:"Short description for admin reference"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Tone"}),e.jsx(xe,{value:h.tone,onChange:D=>m(O=>({...O,tone:D.target.value})),placeholder:"e.g. Warm & Casual"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fn,{checked:h.is_active,onCheckedChange:D=>m(O=>({...O,is_active:D}))}),e.jsx(J,{children:"Active"})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsxs(B,{onClick:()=>b.mutate({...h,id:r==null?void 0:r.id}),disabled:b.isPending||!h.title||!h.subject||!h.body,children:[b.isPending&&e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),r?"Save Changes":"Create Template"]})]})]})}),e.jsx(Ls,{open:d,onOpenChange:u,children:e.jsxs(Ps,{className:"sm:max-w-[450px]",children:[e.jsx(Os,{children:e.jsx(Ds,{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(J,{children:"Icon"}),e.jsx(xe,{value:p.icon,onChange:D=>f(O=>({...O,icon:D.target.value})),className:"text-center text-lg"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Name"}),e.jsx(xe,{value:p.name,onChange:D=>f(O=>({...O,name:D.target.value})),placeholder:"e.g. Check-in & Stay in Touch"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Description"}),e.jsx(xe,{value:p.description,onChange:D=>f(O=>({...O,description:D.target.value})),placeholder:"Brief description of this category"})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>u(!1),children:"Cancel"}),e.jsxs(B,{onClick:()=>S.mutate({...p,id:i==null?void 0:i.id}),disabled:S.isPending||!p.name,children:[S.isPending&&e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),i?"Save Changes":"Create Category"]})]})]})})]})})}const oTn=({brokerageId:s})=>{var ps,Is,js;const{toast:t}=vi(),n=Fn(),[r,a]=_.useState([]),[i,l]=_.useState(!0),[o,c]=_.useState(""),[d,u]=_.useState("all"),[h,m]=_.useState(new Set),[p,f]=_.useState(!1),[y,v]=_.useState({}),[g,b]=_.useState(!1),[j,S]=_.useState(!1),[C,E]=_.useState({email:"",name:"",password:"",phone:""}),[P,M]=_.useState(null),[I,D]=_.useState([]),[O,V]=_.useState("none"),[G,$]=_.useState(!1),[H,Y]=_.useState(null),[Z,ne]=_.useState(!1),[ce,ie]=_.useState(!1),[te,ae]=_.useState(!1),[le,be]=_.useState(""),[me,he]=_.useState(!1),[pe,Ce]=_.useState([]),[Ae,Pe]=_.useState(!1),[ze,ke]=_.useState(!1),[Ze,Se]=_.useState(null),[Fe,Ne]=_.useState({name:"",phone:"",email:""}),[Ye,Ve]=_.useState(!1),[qe,Qe]=_.useState(!1),[Ue,Xe]=_.useState(null),[nt,$e]=_.useState("asc"),[Ge,ct]=_.useState(!1),[xt,qt]=_.useState(null),[Vt,Xt]=_.useState(!1),[fs,Ft]=_.useState(null),[wt,Ts]=_.useState(""),[vt,$s]=_.useState(!1),[As,jn]=_.useState(null);_.useEffect(()=>{Ur(),Dn(),ar()},[s]);const ar=async()=>{try{const{data:Kt}=await q.from("partnership_programs").select("id, name, enabled").eq("brokerage_id",s).maybeSingle();if(!Kt||!Kt.enabled){M(null),D([]);return}const{data:Qs}=await q.from("partnership_packages").select("id, name, description, sort_order").eq("program_id",Kt.id).order("sort_order",{ascending:!0});M({id:Kt.id,name:Kt.name}),D(Qs||[]),Qs&&Qs.length>0&&V(Qs[0].id)}catch(Kt){console.error("Error loading partnership packages:",Kt)}},Dn=async()=>{try{const{data:Kt,error:Qs}=await q.from("brokerage_manager_assignments").select("user_id").eq("brokerage_id",s);if(Qs)throw Qs;Ce((Kt==null?void 0:Kt.map(an=>an.user_id))||[])}catch(Kt){console.error("Error loading brokerage managers:",Kt)}},Ur=async()=>{try{l(!0);const{data:Kt,error:Qs}=await q.functions.invoke("get-brokerage-agents",{body:{brokerageId:s}});if(Qs)throw Qs;const an=Kt.agents||[];if(a(an),an.length>0){const er=an.map(ma=>ma.id),{data:Xr}=await q.from("agent_assistant_assignments").select("agent_id, assistant_id").in("agent_id",er);if(Xr&&Xr.length>0){const ma=Xr.map(Rr=>Rr.assistant_id),{data:Br}=await q.from("profiles").select("id, name, email").in("id",ma),sa={};for(const Rr of Xr){const ra=Br==null?void 0:Br.find(Si=>Si.id===Rr.assistant_id);ra&&(sa[Rr.agent_id]={name:ra.name||"",email:ra.email||""})}v(sa)}else v({})}}catch(Kt){console.error("Error loading agents:",Kt),t({title:"Error",description:"Failed to load agents",variant:"destructive"})}finally{l(!1)}},Vs=async()=>{var Kt;if(!C.email||!C.name||!C.password){t({title:"Error",description:"Please fill in all fields",variant:"destructive"});return}S(!0);try{const{data:{session:Qs}}=await q.auth.getSession(),an=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Qs==null?void 0:Qs.access_token}`},body:JSON.stringify({...C,brokerageId:s,partnershipPackageId:P&&O!=="none"?O:void 0})}),er=await an.json();if(!an.ok)throw new Error(er.error||"Failed to create agent");t({title:"Success",description:`Agent ${C.email} created successfully`}),E({email:"",name:"",password:"",phone:""}),V(((Kt=I[0])==null?void 0:Kt.id)||"none"),b(!1),Ur()}catch(Qs){console.error("Error creating agent:",Qs),t({title:"Error",description:Qs.message||"Failed to create agent",variant:"destructive"})}finally{S(!1)}},hn=async Kt=>{try{const{data:{session:Qs}}=await q.auth.getSession(),an=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Qs==null?void 0:Qs.access_token}`},body:JSON.stringify({userId:Kt})}),er=await an.json();if(!an.ok)throw new Error(er.error||"Failed to resend welcome email");t({title:"Success",description:"Welcome email sent successfully"})}catch(Qs){console.error("Error resending welcome email:",Qs),t({title:"Error",description:Qs.message||"Failed to resend welcome email",variant:"destructive"})}},dr=async(Kt,Qs)=>{try{const{error:an}=await q.functions.invoke("send-password-reset",{body:{email:Kt,redirectTo:"https://dashboard.relevelup.com/profile?reset=true"}});if(an)throw an;t({title:"Password Reset Sent",description:`Password reset email sent to ${Qs}`})}catch(an){console.error("Error sending password reset:",an),t({title:"Error",description:an.message||"Failed to send password reset email",variant:"destructive"})}},Cn=Kt=>{Y(Kt),$(!0)},Yn=Kt=>{Se(Kt),Ne({name:Kt.name,phone:Kt.phone||"",email:Kt.email}),ke(!0)},on=async()=>{if(!Ze)return;if(!Fe.name.trim()){t({title:"Error",description:"Name is required",variant:"destructive"});return}const Kt=Fe.email.trim().toLowerCase()!==Ze.email.toLowerCase();Ve(!0);try{if(Kt){if(!Fe.email.trim())throw new Error("Email is required");Qe(!0);const{data:{session:an}}=await q.auth.getSession(),er=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/update-agent-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${an==null?void 0:an.access_token}`},body:JSON.stringify({agentId:Ze.id,newEmail:Fe.email.trim(),brokerageId:s})}),Xr=await er.json();if(Qe(!1),!er.ok)throw new Error(Xr.error||"Failed to update email")}const{error:Qs}=await q.from("profiles").update({name:Fe.name.trim(),phone:Fe.phone.trim()||null}).eq("id",Ze.id);if(Qs)throw Qs;t({title:"Success",description:"Agent profile updated successfully"}),ke(!1),Se(null),Ur()}catch(Qs){console.error("Error updating agent:",Qs),t({title:"Error",description:Qs.message||"Failed to update agent",variant:"destructive"})}finally{Ve(!1),Qe(!1)}},Ir=async()=>{if(!le){t({title:"Error",description:"Please select an agent to promote",variant:"destructive"});return}he(!0);try{const{data:{session:Kt}}=await q.auth.getSession(),Qs=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Kt==null?void 0:Kt.access_token}`},body:JSON.stringify({userId:le,role:"brokerage_manager",action:"add",brokerageId:s})}),an=await Qs.json();if(!Qs.ok)throw new Error(an.error||"Failed to add brokerage manager");t({title:"Success",description:"Brokerage manager added successfully"}),ae(!1),be(""),Dn()}catch(Kt){console.error("Error adding brokerage manager:",Kt),t({title:"Error",description:Kt.message||"Failed to add brokerage manager",variant:"destructive"})}finally{he(!1)}},Wn=async Kt=>{try{const{data:{session:Qs}}=await q.auth.getSession(),an=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Qs==null?void 0:Qs.access_token}`},body:JSON.stringify({userId:Kt,role:"brokerage_manager",action:"remove",brokerageId:s})}),er=await an.json();if(!an.ok)throw new Error(er.error||"Failed to remove brokerage manager");t({title:"Success",description:"Brokerage manager role removed"}),Dn()}catch(Qs){console.error("Error removing brokerage manager:",Qs),t({title:"Error",description:Qs.message||"Failed to remove brokerage manager",variant:"destructive"})}},Js=Kt=>pe.includes(Kt),Fa=Kt=>{Ft(Kt),Ts(""),Xt(!0)},ks=async()=>{if(!(!fs||!wt)){if(wt.length<6){t({title:"Error",description:"Password must be at least 6 characters",variant:"destructive"});return}$s(!0);try{const{data:{session:Kt}}=await q.auth.getSession(),Qs=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/update-agent-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Kt==null?void 0:Kt.access_token}`},body:JSON.stringify({agentId:fs.id,brokerageId:s,action:"set_password",newPassword:wt})}),an=await Qs.json();if(!Qs.ok)throw new Error(an.error||"Failed to set password");t({title:"Success",description:`Password set for ${fs.name}`}),Xt(!1),Ft(null),Ts("")}catch(Kt){console.error("Error setting password:",Kt),t({title:"Error",description:Kt.message||"Failed to set password",variant:"destructive"})}finally{$s(!1)}}},Gs=async Kt=>{jn(Kt.id);try{const{data:{session:Qs}}=await q.auth.getSession(),an=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/update-agent-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Qs==null?void 0:Qs.access_token}`},body:JSON.stringify({agentId:Kt.id,brokerageId:s,action:"claim_account"})}),er=await an.json();if(!an.ok)throw new Error(er.error||"Failed to claim account");t({title:"Success",description:`Account claimed for ${Kt.name}`}),Ur()}catch(Qs){console.error("Error claiming account:",Qs),t({title:"Error",description:Qs.message||"Failed to claim account",variant:"destructive"})}finally{jn(null)}},Ws=async()=>{if(H){ne(!0);try{const{data:{session:Kt}}=await q.auth.getSession(),Qs=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/remove-agent",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Kt==null?void 0:Kt.access_token}`},body:JSON.stringify({userId:H.id,brokerageId:s})}),an=await Qs.json();if(!Qs.ok)throw new Error(an.error||"Failed to remove agent");t({title:"Success",description:`${H.name} has been removed from your brokerage`}),$(!1),Y(null),Ur()}catch(Kt){console.error("Error removing agent:",Kt),t({title:"Error",description:Kt.message||"Failed to remove agent",variant:"destructive"})}finally{ne(!1)}}},Ys=Kt=>{const Qs=Kt.trim().split(" ");return Qs.length>1?Qs[Qs.length-1].toLowerCase():Kt.toLowerCase()},Bn=Kt=>{Ue===Kt?$e(nt==="asc"?"desc":"asc"):(Xe(Kt),$e("asc"))},or=Kt=>Ue!==Kt?e.jsx(Lg,{className:"ml-1 h-4 w-4"}):nt==="asc"?e.jsx(sp,{className:"ml-1 h-4 w-4"}):e.jsx(zf,{className:"ml-1 h-4 w-4"}),Wt=r.filter(Kt=>{if(d==="active"&&!Kt.claimed||d==="pending"&&Kt.claimed)return!1;if(!o)return!0;const Qs=o.toLowerCase();return Kt.name.toLowerCase().includes(Qs)||Kt.email.toLowerCase().includes(Qs)}),rt=[...Wt].sort((Kt,Qs)=>{if(!Ue)return 0;let an=0;return Ue==="name"?an=Ys(Kt.name).localeCompare(Ys(Qs.name)):Ue==="status"&&(an=Kt.claimed===Qs.claimed?0:Kt.claimed?-1:1),nt==="asc"?an:-an});Wt.filter(Kt=>Kt.claimed&&!Js(Kt.id));const pt=Kt=>{m(Qs=>{const an=new Set(Qs);return an.has(Kt)?an.delete(Kt):an.add(Kt),an})},jt=()=>{h.size===rt.length?m(new Set):m(new Set(rt.map(Kt=>Kt.id)))},Mt=()=>{m(new Set)},es=async()=>{const Kt=Array.from(h);if(Kt.length===0)return;f(!0);let Qs=0,an=0;try{const{data:{session:er}}=await q.auth.getSession();for(const Xr of Kt)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${er==null?void 0:er.access_token}`},body:JSON.stringify({userId:Xr})})).ok?Qs++:an++}catch{an++}Qs>0?t({title:"Success",description:`Welcome emails sent to ${Qs} agent${Qs>1?"s":""}${an>0?` (${an} failed)`:""}`}):t({title:"Error",description:"Failed to send welcome emails",variant:"destructive"}),Mt()}catch(er){console.error("Error bulk sending welcome emails:",er),t({title:"Error",description:er.message||"Failed to send welcome emails",variant:"destructive"})}finally{f(!1)}};return i?e.jsx(ve,{children:e.jsx(Me,{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(ve,{children:[e.jsx(bt,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(St,{children:"Agents"}),e.jsx(kn,{children:"Manage your brokerage's agents"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{variant:"outline",onClick:()=>ae(!0),children:[e.jsx(Rm,{className:"mr-2 h-4 w-4"}),"Add Brokerage Manager"]}),e.jsxs(B,{variant:"outline",onClick:()=>ie(!0),children:[e.jsx(uS,{className:"mr-2 h-4 w-4"}),"Import CSV"]}),e.jsxs(B,{onClick:()=>b(!0),children:[e.jsx(Pl,{className:"mr-2 h-4 w-4"}),"Add Agent"]})]})]})}),e.jsxs(Me,{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(Lr,{className:"absolute left-3 top-3 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search agents...",value:o,onChange:Kt=>c(Kt.target.value),className:"pl-9"})]}),e.jsxs(is,{value:d,onValueChange:Kt=>u(Kt),children:[e.jsx(rs,{className:"w-[160px]",children:e.jsx(ls,{placeholder:"Filter by status"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Agents"}),e.jsx(He,{value:"active",children:"Active"}),e.jsx(He,{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(B,{size:"sm",variant:"outline",onClick:()=>{const Qs=r.filter(an=>h.has(an.id)&&an.email).map(an=>({email:an.email,name:an.name}));sessionStorage.setItem("campaign_direct_recipients",JSON.stringify(Qs)),n("/admin/email-campaigns/new?directMode=1",{state:{directRecipients:Qs}})},disabled:p,children:[e.jsx(wh,{className:"mr-2 h-4 w-4"}),"Email Agents (",h.size,")"]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:es,disabled:p,children:[e.jsx(ln,{className:"mr-2 h-4 w-4"}),p?"Sending...":"Resend Welcome Email"]}),e.jsx(B,{size:"sm",variant:"ghost",onClick:Mt,children:"Clear"})]}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{className:"w-[40px]",children:e.jsx($a,{checked:rt.length>0&&h.size===rt.length,onCheckedChange:jt,"aria-label":"Select all"})}),e.jsx(Pt,{children:e.jsxs(B,{variant:"ghost",size:"sm",className:"-ml-3 h-8 hover:bg-transparent",onClick:()=>Bn("name"),children:["Name (Last)",or("name")]})}),e.jsx(Pt,{children:"Email"}),e.jsx(Pt,{children:e.jsxs(B,{variant:"ghost",size:"sm",className:"-ml-3 h-8 hover:bg-transparent",onClick:()=>Bn("status"),children:["Status",or("status")]})}),e.jsx(Pt,{children:"Actions"})]})}),e.jsx(Ka,{children:rt.length===0?e.jsx(pn,{children:e.jsx(gt,{colSpan:5,className:"text-center text-muted-foreground",children:"No agents found"})}):rt.map(Kt=>e.jsxs(pn,{children:[e.jsx(gt,{children:e.jsx($a,{checked:h.has(Kt.id),onCheckedChange:()=>pt(Kt.id),"aria-label":`Select ${Kt.name}`})}),e.jsx(gt,{className:"font-medium",children:Kt.name}),e.jsx(gt,{children:Kt.email}),e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[Kt.claimed?e.jsx(Oe,{variant:"default",children:"Active"}):e.jsx(Oe,{variant:"secondary",children:"Pending"}),Js(Kt.id)&&e.jsxs(Oe,{variant:"outline",className:"border-primary text-primary",children:[e.jsx(Dm,{className:"mr-1 h-3 w-3"}),"Manager"]}),y[Kt.id]&&e.jsxs(Oe,{variant:"outline",className:"text-xs",children:[e.jsx(In,{className:"mr-1 h-3 w-3"}),"Asst: ",y[Kt.id].name||y[Kt.id].email]})]})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-1 flex-wrap",children:[e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>{qt(Kt),ct(!0)},title:"Send celebration",className:"text-yellow-500 hover:text-yellow-600 hover:bg-yellow-50",children:e.jsx(Ex,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>Yn(Kt),title:"Edit agent",children:e.jsx(Ya,{className:"h-4 w-4"})}),!Kt.claimed&&e.jsxs(e.Fragment,{children:[e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>hn(Kt.id),title:"Resend welcome email",children:e.jsx(ln,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>Gs(Kt),title:"Claim account for agent",disabled:As===Kt.id,className:"text-green-600 hover:text-green-700 hover:bg-green-50",children:e.jsx(gj,{className:"h-4 w-4"})})]}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>Fa(Kt),title:"Set password",className:"text-blue-600 hover:text-blue-700 hover:bg-blue-50",children:e.jsx(ec,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>dr(Kt.email,Kt.name),title:"Send password reset email",children:e.jsx(VA,{className:"h-4 w-4"})}),Js(Kt.id)&&e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>Wn(Kt.id),title:"Remove manager role",className:"text-orange-500 hover:text-orange-600",children:e.jsx(Rm,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>Cn(Kt),className:"text-destructive hover:text-destructive",title:"Remove agent",children:e.jsx(Sn,{className:"h-4 w-4"})})]})})]},Kt.id))})]})})]})]}),e.jsx(Ls,{open:g,onOpenChange:b,children:e.jsxs(Ps,{children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Add New Agent"}),e.jsx(_r,{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(J,{htmlFor:"name",children:"Name"}),e.jsx(xe,{id:"name",value:C.name,onChange:Kt=>E({...C,name:Kt.target.value}),placeholder:"John Doe"})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"email",children:"Email"}),e.jsx(xe,{id:"email",type:"email",value:C.email,onChange:Kt=>E({...C,email:Kt.target.value}),placeholder:"john@example.com"})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"phone",children:"Phone (optional)"}),e.jsx(xe,{id:"phone",type:"tel",value:C.phone,onChange:Kt=>E({...C,phone:Kt.target.value}),placeholder:"555-123-4567"})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"password",children:"Temporary Password"}),e.jsx(xe,{id:"password",type:"password",value:C.password,onChange:Kt=>E({...C,password:Kt.target.value}),placeholder:"Temporary password"})]}),P&&I.length>0&&e.jsxs("div",{children:[e.jsxs(J,{htmlFor:"package",children:[P.name," Package"]}),e.jsxs(is,{value:O,onValueChange:V,children:[e.jsx(rs,{id:"package",children:e.jsx(ls,{placeholder:"Choose a package"})}),e.jsxs(as,{children:[I.map(Kt=>e.jsx(He,{value:Kt.id,children:Kt.name},Kt.id)),e.jsx(He,{value:"none",children:"No package (full access)"})]})]}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:O==="none"?"Agent gets unrestricted LevelUp access.":((ps=I.find(Kt=>Kt.id===O))==null?void 0:ps.description)||"Their welcome email will list what is included in this package."})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>b(!1),children:"Cancel"}),e.jsx(B,{onClick:Vs,disabled:j,children:j?"Creating...":"Create Agent"})]})]})}),e.jsx(Ls,{open:G,onOpenChange:$,children:e.jsxs(Ps,{children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Remove Agent"}),e.jsxs(_r,{children:["Are you sure you want to remove ",e.jsx("strong",{children:H==null?void 0:H.name})," from your brokerage? This will revoke their access to the dashboard."]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>$(!1),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:Ws,disabled:Z,children:Z?"Removing...":"Remove Agent"})]})]})}),e.jsx(wVt,{open:ce,onOpenChange:ie,fixedBrokerageId:s,onSuccess:Ur}),e.jsx(Ls,{open:te,onOpenChange:ae,children:e.jsxs(Ps,{children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Add Brokerage Manager"}),e.jsx(_r,{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(J,{children:"Select Agent"}),e.jsxs(od,{open:Ae,onOpenChange:Pe,children:[e.jsx(ld,{asChild:!0,children:e.jsxs(B,{variant:"outline",role:"combobox","aria-expanded":Ae,className:"w-full justify-between",children:[le?((Is=r.find(Kt=>Kt.id===le))==null?void 0:Is.name)+" ("+((js=r.find(Kt=>Kt.id===le))==null?void 0:js.email)+")":"Select an agent to promote...",e.jsx(I_,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Qc,{className:"w-full p-0",align:"start",children:e.jsxs(Aj,{children:[e.jsx(Ej,{placeholder:"Search by name or email..."}),e.jsxs(Tj,{className:"max-h-[200px]",children:[e.jsx(Mj,{children:"No eligible agents found."}),e.jsx(V_,{children:r.filter(Kt=>!Js(Kt.id)).map(Kt=>e.jsxs(d1,{value:`${Kt.name} ${Kt.email}`,onSelect:()=>{be(Kt.id),Pe(!1)},children:[e.jsx(ea,{className:`mr-2 h-4 w-4 ${le===Kt.id?"opacity-100":"opacity-0"}`}),Kt.name," (",Kt.email,")"]},Kt.id))})]})]})})]}),r.filter(Kt=>!Js(Kt.id)).length===0&&e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"All agents are already brokerage managers."})]})}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>ae(!1),children:"Cancel"}),e.jsx(B,{onClick:Ir,disabled:me||!le,children:me?"Adding...":"Add as Manager"})]})]})}),e.jsx(Ls,{open:ze,onOpenChange:ke,children:e.jsxs(Ps,{children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Edit Agent"}),e.jsxs(_r,{children:["Update profile information for ",Ze==null?void 0:Ze.name]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(J,{htmlFor:"edit-name",children:"Name"}),e.jsx(xe,{id:"edit-name",value:Fe.name,onChange:Kt=>Ne({...Fe,name:Kt.target.value}),placeholder:"Agent name"})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"edit-email",children:"Email"}),e.jsx(xe,{id:"edit-email",type:"email",value:Fe.email,onChange:Kt=>Ne({...Fe,email:Kt.target.value}),placeholder:"agent@example.com"}),Fe.email.trim().toLowerCase()!==(Ze==null?void 0:Ze.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(J,{htmlFor:"edit-phone",children:"Phone"}),e.jsx(xe,{id:"edit-phone",type:"tel",value:Fe.phone,onChange:Kt=>Ne({...Fe,phone:Kt.target.value}),placeholder:"555-123-4567"})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>ke(!1),children:"Cancel"}),e.jsx(B,{onClick:on,disabled:Ye||qe,children:qe?"Updating email...":Ye?"Saving...":"Save Changes"})]})]})}),xt&&e.jsx(jVt,{open:Ge,onOpenChange:Kt=>{ct(Kt),Kt||qt(null)},userId:xt.id,userName:xt.name}),e.jsx(Ls,{open:Vt,onOpenChange:Xt,children:e.jsxs(Ps,{children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Set Password"}),e.jsxs(_r,{children:["Set a new password for ",fs==null?void 0:fs.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(J,{htmlFor:"new-password",children:"New Password"}),e.jsx(xe,{id:"new-password",type:"password",value:wt,onChange:Kt=>Ts(Kt.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(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>Xt(!1),children:"Cancel"}),e.jsx(B,{onClick:ks,disabled:vt||!wt||wt.length<6,children:vt?"Setting...":"Set Password"})]})]})})]})},lTn={academy_video:"Academy Video",template:"Template",toolbox:"Toolbox Resource",newsletter:"Newsletter",social_swag:"Social Swag",event:"Event"},cTn={view:"Viewed",click_canva:"Opened Canva",click_pdf:"Downloaded PDF",click_video:"Watched Video",click_link:"Clicked Link",register:"Registered"},dTn=s=>{switch(s){case"academy_video":return e.jsx(Kr,{className:"h-4 w-4"});case"template":return e.jsx(Fr,{className:"h-4 w-4"});case"toolbox":return e.jsx(Fr,{className:"h-4 w-4"});case"newsletter":return e.jsx(mN,{className:"h-4 w-4"});case"social_swag":return e.jsx(un,{className:"h-4 w-4"});case"event":return e.jsx(ga,{className:"h-4 w-4"});default:return e.jsx(wr,{className:"h-4 w-4"})}},uTn=({brokerageId:s})=>{const{toast:t}=vi(),[n,r]=_.useState([]),[a,i]=_.useState([]),[l,o]=_.useState([]),[c,d]=_.useState(!0),[u,h]=_.useState(null);_.useEffect(()=>{m()},[s]);const m=async()=>{try{d(!0);const{data:y,error:v}=await q.from("profiles").select("id, name, email").eq("brokerage_id",s);if(v)throw v;const g=y.map(O=>O.id),b=new Map(y.map(O=>[O.id,O]));if(g.length===0){r([]),i([]),o([]);return}const{data:j,error:S}=await q.from("activity_logs").select("*").in("user_id",g).order("launched_at",{ascending:!1});if(S)throw S;const C=j.map(O=>{var V,G;return{id:O.id,user_id:O.user_id,app_name:O.app_name,launched_at:O.launched_at,user_name:((V=b.get(O.user_id))==null?void 0:V.name)||"Unknown",user_email:((G=b.get(O.user_id))==null?void 0:G.email)||"Unknown"}});r(C);const{data:E,error:P}=await q.from("content_engagement_logs").select("*").in("user_id",g).order("created_at",{ascending:!1});if(P)throw P;const M=(E||[]).map(O=>{var V,G;return{id:O.id,user_id:O.user_id,resource_type:O.resource_type,resource_id:O.resource_id,resource_title:O.resource_title,action_type:O.action_type,created_at:O.created_at,user_name:((V=b.get(O.user_id))==null?void 0:V.name)||"Unknown",user_email:((G=b.get(O.user_id))==null?void 0:G.email)||"Unknown"}});i(M);const I=new Map;y.forEach(O=>{I.set(O.id,{user_id:O.id,user_name:O.name,user_email:O.email,app_launches:0,content_views:0,last_activity:""})}),C.forEach(O=>{const V=I.get(O.user_id);V&&(V.app_launches++,(!V.last_activity||new Date(O.launched_at)>new Date(V.last_activity))&&(V.last_activity=O.launched_at))}),M.forEach(O=>{const V=I.get(O.user_id);V&&(V.content_views++,(!V.last_activity||new Date(O.created_at)>new Date(V.last_activity))&&(V.last_activity=O.created_at))});const D=Array.from(I.values()).filter(O=>O.app_launches>0||O.content_views>0).sort((O,V)=>new Date(V.last_activity).getTime()-new Date(O.last_activity).getTime());o(D)}catch(y){console.error("Error loading activity:",y),t({title:"Error",description:"Failed to load activity logs",variant:"destructive"})}finally{d(!1)}},p=y=>n.filter(v=>v.user_id===y),f=y=>a.filter(v=>v.user_id===y);return c?e.jsx(ve,{children:e.jsx(Me,{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(ve,{children:[e.jsxs(bt,{children:[e.jsx(St,{children:"Agent Activity"}),e.jsx(kn,{children:"Track app usage and content engagement - click an agent for details"})]}),e.jsx(Me,{children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"Agent"}),e.jsx(Pt,{className:"text-center",children:"App Launches"}),e.jsx(Pt,{className:"text-center",children:"Content Views"}),e.jsx(Pt,{children:"Last Active"})]})}),e.jsx(Ka,{children:l.length===0?e.jsx(pn,{children:e.jsx(gt,{colSpan:4,className:"text-center text-muted-foreground",children:"No activity yet"})}):l.map(y=>e.jsxs(pn,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>h({id:y.user_id,name:y.user_name,email:y.user_email}),children:[e.jsx(gt,{children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:y.user_name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:y.user_email})]})}),e.jsx(gt,{className:"text-center",children:e.jsxs(Oe,{variant:"outline",className:"gap-1",children:[e.jsx(Jd,{className:"h-3 w-3"}),y.app_launches]})}),e.jsx(gt,{className:"text-center",children:e.jsxs(Oe,{variant:"secondary",className:"gap-1",children:[e.jsx(Fr,{className:"h-3 w-3"}),y.content_views]})}),e.jsx(gt,{className:"text-sm text-muted-foreground",children:y.last_activity&&Ed(new Date(y.last_activity),{addSuffix:!0})})]},y.user_id))})]})})})]}),e.jsx(Ls,{open:!!u,onOpenChange:y=>!y&&h(null),children:e.jsxs(Ps,{className:"max-w-3xl max-h-[80vh] overflow-hidden flex flex-col",children:[e.jsxs(Os,{children:[e.jsxs(Ds,{children:[u==null?void 0:u.name,"'s Activity"]}),e.jsx(_r,{children:u==null?void 0:u.email})]}),e.jsxs(Yr,{defaultValue:"content",className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(Zr,{className:"grid w-full grid-cols-2",children:[e.jsx(Ht,{value:"content",children:"Content Engagement"}),e.jsx(Ht,{value:"apps",children:"App Launches"})]}),e.jsx(Gt,{value:"content",className:"flex-1 overflow-auto",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"Resource"}),e.jsx(Pt,{children:"Type"}),e.jsx(Pt,{children:"Action"}),e.jsx(Pt,{children:"Time"})]})}),e.jsx(Ka,{children:u&&f(u.id).length===0?e.jsx(pn,{children:e.jsx(gt,{colSpan:4,className:"text-center text-muted-foreground",children:"No content engagement yet"})}):u&&f(u.id).map(y=>e.jsxs(pn,{children:[e.jsx(gt,{className:"max-w-[200px] truncate font-medium",children:y.resource_title}),e.jsx(gt,{children:e.jsxs(Oe,{variant:"outline",className:"gap-1",children:[dTn(y.resource_type),lTn[y.resource_type]||y.resource_type]})}),e.jsx(gt,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:cTn[y.action_type]||y.action_type})}),e.jsx(gt,{className:"text-sm text-muted-foreground",children:Ed(new Date(y.created_at),{addSuffix:!0})})]},y.id))})]})})}),e.jsx(Gt,{value:"apps",className:"flex-1 overflow-auto",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"App"}),e.jsx(Pt,{children:"Time"})]})}),e.jsx(Ka,{children:u&&p(u.id).length===0?e.jsx(pn,{children:e.jsx(gt,{colSpan:2,className:"text-center text-muted-foreground",children:"No app launches yet"})}):u&&p(u.id).map(y=>e.jsxs(pn,{children:[e.jsx(gt,{children:e.jsx(Oe,{variant:"outline",children:y.app_name})}),e.jsx(gt,{className:"text-sm text-muted-foreground",children:Ed(new Date(y.launched_at),{addSuffix:!0})})]},y.id))})]})})})]})]})})]})},hTn=({brokerageId:s})=>{const{toast:t}=vi(),[n,r]=_.useState({totalAgents:0,activeAgents:0,pendingAgents:0,totalLaunches:0,launchesThisWeek:0,launchesThisMonth:0}),[a,i]=_.useState(!0);_.useEffect(()=>{l()},[s]);const l=async()=>{try{i(!0);const{data:o,error:c}=await q.from("profiles").select("id").eq("brokerage_id",s);if(c)throw c;const d=o.map(C=>C.id),u=d.length;if(d.length===0){i(!1);return}const{data:h,error:m}=await q.from("profiles").select("id, email").in("id",d);if(m)throw m;const{count:p}=await q.from("profiles").select("*",{count:"exact",head:!0}).eq("brokerage_id",s).not("last_login","is",null),f=p||0,y=u-f,{count:v}=await q.from("activity_logs").select("*",{count:"exact",head:!0}).in("user_id",d),g=new Date;g.setDate(g.getDate()-7);const{count:b}=await q.from("activity_logs").select("*",{count:"exact",head:!0}).in("user_id",d).gte("launched_at",g.toISOString()),j=new Date;j.setMonth(j.getMonth()-1);const{count:S}=await q.from("activity_logs").select("*",{count:"exact",head:!0}).in("user_id",d).gte("launched_at",j.toISOString());r({totalAgents:u,activeAgents:f,pendingAgents:y,totalLaunches:v||0,launchesThisWeek:b||0,launchesThisMonth:S||0})}catch(o){console.error("Error loading analytics:",o),t({title:"Error",description:"Failed to load analytics",variant:"destructive"})}finally{i(!1)}};return a?e.jsx(ve,{children:e.jsx(Me,{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(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(St,{className:"text-sm font-medium",children:"Total Agents"}),e.jsx(In,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Me,{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(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(St,{className:"text-sm font-medium",children:"Active Agents"}),e.jsx(_l,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Me,{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(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(St,{className:"text-sm font-medium",children:"Pending Invites"}),e.jsx(Gr,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Me,{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(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(St,{className:"text-sm font-medium",children:"Total App Launches"}),e.jsx(hm,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Me,{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(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(St,{className:"text-sm font-medium",children:"This Week"}),e.jsx(hm,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Me,{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(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(St,{className:"text-sm font-medium",children:"This Month"}),e.jsx(hm,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Me,{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"})]})]})]})},mTn=({brokerageId:s})=>{const[t,n]=_.useState([]),[r,a]=_.useState(!0),[i,l]=_.useState(!1),[o,c]=_.useState(!1),[d,u]=_.useState({description:"",maxUses:""});_.useEffect(()=>{h()},[s]);const h=async()=>{try{const{data:g,error:b}=await q.from("invite_codes").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(b)throw b;n(g||[])}catch(g){console.error("Error loading invite codes:",g),se.error("Failed to load invite links")}finally{a(!1)}},m=()=>Math.random().toString(36).substring(2,8).toUpperCase(),p=async()=>{l(!0);try{const g=m(),{error:b}=await q.from("invite_codes").insert({code:g,description:d.description||null,max_uses:d.maxUses?parseInt(d.maxUses):null,brokerage_id:s,is_active:!0});if(b)throw b;se.success("Invite link created!"),c(!1),u({description:"",maxUses:""}),h()}catch(g){console.error("Error creating invite code:",g),se.error("Failed to create invite link")}finally{l(!1)}},f=async g=>{try{const{error:b}=await q.from("invite_codes").delete().eq("id",g);if(b)throw b;se.success("Invite link deleted"),n(t.filter(j=>j.id!==g))}catch(b){console.error("Error deleting invite code:",b),se.error("Failed to delete invite link")}},y=async(g,b)=>{try{const{error:j}=await q.from("invite_codes").update({is_active:!b}).eq("id",g);if(j)throw j;n(t.map(S=>S.id===g?{...S,is_active:!b}:S)),se.success(`Invite link ${b?"deactivated":"activated"}`)}catch(j){console.error("Error toggling invite code:",j),se.error("Failed to update invite link")}},v=g=>{const b=`${window.location.origin}/join?code=${g}`;navigator.clipboard.writeText(b),se.success("Link copied to clipboard!")};return r?e.jsx(ve,{children:e.jsx(Me,{className:"flex items-center justify-center py-8",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})})}):e.jsxs(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(Vc,{className:"h-5 w-5"}),"Agent Invite Links"]}),e.jsx(kn,{children:"Create shareable links for agents to join your brokerage"})]}),e.jsxs(Ls,{open:o,onOpenChange:c,children:[e.jsx(nl,{asChild:!0,children:e.jsxs(B,{size:"sm",children:[e.jsx(rn,{className:"mr-2 h-4 w-4"}),"Create Link"]})}),e.jsxs(Ps,{children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Create Invite Link"}),e.jsx(_r,{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(J,{htmlFor:"description",children:"Description (optional)"}),e.jsx(xe,{id:"description",placeholder:"e.g., New agent recruiting campaign",value:d.description,onChange:g=>u({...d,description:g.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"maxUses",children:"Max Uses (optional)"}),e.jsx(xe,{id:"maxUses",type:"number",placeholder:"Leave empty for unlimited",value:d.maxUses,onChange:g=>u({...d,maxUses:g.target.value})})]}),e.jsx(B,{onClick:p,disabled:i,className:"w-full",children:i?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating..."]}):"Create Invite Link"})]})]})]})]}),e.jsx(Me,{children:t.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Vc,{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(g=>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:g.code}),e.jsx(Oe,{variant:g.is_active?"default":"secondary",children:g.is_active?"Active":"Inactive"})]}),g.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1 truncate",children:g.description}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[g.uses_count," uses",g.max_uses&&` / ${g.max_uses} max`]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>v(g.code),title:"Copy link",children:e.jsx(Ia,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>y(g.id,g.is_active),title:g.is_active?"Deactivate":"Activate",children:g.is_active?"Disable":"Enable"}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>f(g.id),className:"text-destructive hover:text-destructive",title:"Delete",children:e.jsx(Sn,{className:"h-4 w-4"})})]})]},g.id))})})]})},pTn=({open:s,onOpenChange:t,referralCode:n,brokerageId:r,senderName:a,brokerageName:i,onInvitesSent:l})=>{const[o,c]=_.useState(""),[d,u]=_.useState([]),[h,m]=_.useState(""),[p,f]=_.useState(!1),y=S=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(S),v=()=>{const S=o.trim().toLowerCase();if(S&&y(S)&&!d.includes(S)){if(d.length>=10){se.error("Maximum 10 emails per invite");return}u([...d,S]),c("")}else S&&!y(S)?se.error("Please enter a valid email address"):d.includes(S)&&se.error("Email already added")},g=S=>{u(d.filter(C=>C!==S))},b=S=>{(S.key==="Enter"||S.key===",")&&(S.preventDefault(),v())},j=async()=>{if(d.length===0){se.error("Please add at least one email address");return}f(!0);try{const{data:S,error:C}=await q.functions.invoke("send-referral-invite",{body:{emails:d,personalMessage:h.trim()||void 0,referralCode:n,brokerageId:r,senderName:a,brokerageName:i}});if(C)throw C;S.successCount===S.totalCount?se.success(`${S.successCount} invite${S.successCount>1?"s":""} sent successfully!`):se.warning(`${S.successCount} of ${S.totalCount} invites sent. Some failed.`),u([]),m(""),t(!1),l==null||l()}catch(S){console.error("Error sending invites:",S),se.error("Failed to send invites. Please try again.")}finally{f(!1)}};return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"sm:max-w-[550px]",children:[e.jsxs(Os,{children:[e.jsxs(Ds,{className:"flex items-center gap-2",children:[e.jsx(ln,{className:"h-5 w-5 text-primary"}),"Invite Broker Friends"]}),e.jsx(_r,{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(Vo,{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(J,{htmlFor:"email",children:"Email Addresses (up to 10)"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{id:"email",type:"email",placeholder:"Enter email and press Enter",value:o,onChange:S=>c(S.target.value),onKeyDown:b,onBlur:v}),e.jsx(B,{type:"button",variant:"secondary",onClick:v,children:"Add"})]}),d.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:d.map(S=>e.jsxs(Oe,{variant:"secondary",className:"flex items-center gap-1 pr-1",children:[S,e.jsx("button",{type:"button",onClick:()=>g(S),className:"ml-1 rounded-full p-0.5 hover:bg-muted",children:e.jsx(Qn,{className:"h-3 w-3"})})]},S))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"message",children:"Personal Message (optional)"}),e.jsx(Ms,{id:"message",placeholder:"Add a personal note that will appear at the top of the email...",value:h,onChange:S=>m(S.target.value),rows:3,maxLength:500}),e.jsxs("p",{className:"text-xs text-muted-foreground text-right",children:[h.length,"/500 characters"]})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-4 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(un,{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(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(B,{onClick:j,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(Or,{className:"h-4 w-4 mr-2"}),"Send ",d.length>0&&`(${d.length})`," Invite",d.length!==1?"s":""]})})]})]})})},fTn=({brokerageId:s,refreshTrigger:t})=>{const[n,r]=_.useState([]),[a,i]=_.useState(!0);_.useEffect(()=>{l()},[s,t]);const l=async()=>{try{const{data:c,error:d}=await q.from("referral_invites").select("*").eq("referrer_brokerage_id",s).order("sent_at",{ascending:!1}).limit(20);if(d)throw d;r(c||[])}catch(c){console.error("Error fetching invites:",c)}finally{i(!1)}},o=c=>{switch(c){case"signed_up":return e.jsxs(Oe,{className:"bg-green-100 text-green-800 gap-1",children:[e.jsx(_l,{className:"h-3 w-3"}),"Signed Up"]});case"expired":return e.jsxs(Oe,{variant:"outline",className:"text-muted-foreground gap-1",children:[e.jsx(Rd,{className:"h-3 w-3"}),"Expired"]});default:return e.jsxs(Oe,{variant:"secondary",className:"gap-1",children:[e.jsx(Gr,{className:"h-3 w-3"}),"Pending"]})}};return a?e.jsx("div",{className:"flex justify-center py-4",children:e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-primary border-t-transparent"})}):n.length===0?e.jsxs("div",{className:"text-center py-6 text-muted-foreground",children:[e.jsx(ln,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No invites sent yet"}),e.jsx("p",{className:"text-xs",children:"Start inviting broker friends to earn rewards!"})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium mb-3",children:"Recent Invites"}),n.map(c=>e.jsxs("div",{className:"flex items-center justify-between p-2.5 bg-muted/30 rounded-lg",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:c.recipient_email}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Sent ",Hs(new Date(c.sent_at),"MMM d, yyyy")]})]}),o(c.status)]},c.id))]})},xTn=()=>{const{brokerageId:s,user:t}=hs(),[n,r]=_.useState(null),[a,i]=_.useState(""),[l,o]=_.useState(""),[c,d]=_.useState([]),[u,h]=_.useState(!0),[m,p]=_.useState(!1),[f,y]=_.useState(0);_.useEffect(()=>{s&&v()},[s]);const v=async()=>{try{const[E,P]=await Promise.all([q.from("brokerages").select("name").eq("id",s).single(),t?q.from("profiles").select("name").eq("id",t.id).single():Promise.resolve({data:null})]);E.data&&i(E.data.name),P.data&&o(P.data.name||"A LevelUp Member");const{data:M}=await q.from("referral_codes").select("code").eq("brokerage_id",s).single();if(M)r(M.code);else{const D=`REF${s==null?void 0:s.slice(0,8).toUpperCase()}`;await q.from("referral_codes").insert({brokerage_id:s,code:D}),r(D)}const{data:I}=await q.from("referrals").select(` *, referred_user:profiles!referred_user_id(name, email), referred_brokerage:brokerages!referred_brokerage_id(name) `).eq("referrer_brokerage_id",s).order("created_at",{ascending:!1});d(I||[])}catch(E){console.error("Error fetching referral data:",E)}finally{h(!1)}},g=()=>{const E=`https://dashboard.relevelup.com/?ref=${n}`;navigator.clipboard.writeText(E),se.success("Referral link copied to clipboard!")},b=c.filter(E=>E.status==="qualified").length,j=c.filter(E=>E.status==="pending").length,S=b*25,C=Math.max(0,Math.ceil((299-S)/25));return u?null:e.jsxs(e.Fragment,{children:[e.jsxs(ve,{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(Vo,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-bold",children:"Referral Rewards Program"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Earn $25/month off your membership for every broker you refer"})]})]}),e.jsx("div",{className:"mt-4 bg-background/80 rounded-lg p-4 border",children:e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-4",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsxs("p",{className:"text-3xl font-bold text-primary",children:["$",S]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Monthly Savings"})]}),S>0&&e.jsxs("div",{className:"flex items-center gap-1 text-green-600",children:[e.jsx(_l,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm font-medium",children:"Active"})]})]}),C>0&&S<299&&e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"text-sm font-medium",children:["Refer ",C," more = ",e.jsx("span",{className:"text-primary",children:"FREE membership!"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Your membership could cost $0/month"})]}),S>=299&&e.jsxs("div",{className:"flex items-center gap-2 text-primary",children:[e.jsx(un,{className:"h-5 w-5"}),e.jsx("span",{className:"font-bold",children:"FREE Membership Unlocked!"})]})]})})]})}),e.jsxs(Me,{className:"pt-6 space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs(B,{onClick:()=>p(!0),className:"w-full",size:"lg",children:[e.jsx(ln,{className:"h-4 w-4 mr-2"}),"Invite Broker Friends"]}),e.jsxs(B,{onClick:g,variant:"outline",className:"w-full",size:"lg",children:[e.jsx(Ia,{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(yd,{className:"h-5 w-5 mx-auto text-green-600 mb-1"}),e.jsxs("p",{className:"text-2xl font-bold text-green-700 dark:text-green-400",children:["$",S]}),e.jsx("p",{className:"text-xs text-green-600 dark:text-green-500",children:"Monthly Savings"})]}),e.jsxs("div",{className:"text-center p-4 bg-primary/5 rounded-lg border border-primary/20",children:[e.jsx(In,{className:"h-5 w-5 mx-auto text-primary mb-1"}),e.jsx("p",{className:"text-2xl font-bold",children:b}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Qualified Referrals"})]}),e.jsxs("div",{className:"text-center p-4 bg-amber-50 dark:bg-amber-950/20 rounded-lg border border-amber-200 dark:border-amber-900",children:[e.jsx(Gr,{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:j}),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(fTn,{brokerageId:s,refreshTrigger:f}),c.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium",children:"Your Referrals"}),c.slice(0,5).map(E=>{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=E.referred_brokerage)==null?void 0:P.name)||((M=E.referred_user)==null?void 0:M.email)||"Pending setup"}),e.jsxs(Oe,{variant:E.status==="qualified"?"default":E.status==="pending"?"secondary":"destructive",className:E.status==="qualified"?"bg-green-600":"",children:[E.status==="qualified"&&e.jsx(_l,{className:"h-3 w-3 mr-1"}),E.status]})]},E.id)})]})]})]}),e.jsx(pTn,{open:m,onOpenChange:p,referralCode:n||"",brokerageId:s||"",senderName:l||"A LevelUp Member",brokerageName:a,onInvitesSent:()=>y(E=>E+1)})]})},gTn=({brokerageId:s})=>{const t=Fn(),{teams:n,isLoading:r}=SC(s),{data:a,isLoading:i}=at({queryKey:["team-aggregate-stats",s,n.map(u=>u.id)],queryFn:async()=>{if(n.length===0)return[];const u=n.map(E=>E.id),{data:h}=await q.from("team_members").select("team_id, user_id, role").in("team_id",u);if(!h||h.length===0)return n.map(E=>({team_id:E.id,team_name:E.name,member_count:0,leader_name:null,leader_avatar:null,total_contacts:0,total_deals:0,total_videos:0}));const m=h.map(E=>E.user_id),p=h.filter(E=>E.role==="team_leader").map(E=>E.user_id),{data:f}=await q.from("profiles").select("id, name, avatar_url").in("id",p),y=new Map((f||[]).map(E=>[E.id,E])),{data:v}=await q.from("innercircle_contacts").select("owner_user_id").in("owner_user_id",m),{data:g}=await q.from("deal_pipeline").select("owner_user_id").in("owner_user_id",m),{data:b}=await q.from("agent_videos").select("owner_user_id").in("owner_user_id",m).eq("is_deleted",!1),j=new Map;(v||[]).forEach(E=>{j.set(E.owner_user_id,(j.get(E.owner_user_id)||0)+1)});const S=new Map;(g||[]).forEach(E=>{S.set(E.owner_user_id,(S.get(E.owner_user_id)||0)+1)});const C=new Map;return(b||[]).forEach(E=>{C.set(E.owner_user_id,(C.get(E.owner_user_id)||0)+1)}),n.map(E=>{const P=h.filter($=>$.team_id===E.id),M=P.find($=>$.role==="team_leader"),I=M?y.get(M.user_id):null,D=P.map($=>$.user_id),O=D.reduce(($,H)=>$+(j.get(H)||0),0),V=D.reduce(($,H)=>$+(S.get(H)||0),0),G=D.reduce(($,H)=>$+(C.get(H)||0),0);return{team_id:E.id,team_name:E.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:O,total_deals:V,total_videos:G}})},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(ve,{children:[e.jsx(bt,{children:e.jsx(cn,{className:"h-5 w-32"})}),e.jsx(Me,{children:e.jsx(cn,{className:"h-24 w-full"})})]},u))});if(n.length===0)return e.jsx(ve,{children:e.jsxs(Me,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(In,{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(B,{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(ve,{children:e.jsxs(Me,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(In,{className:"h-4 w-4"})," Teams"]}),e.jsx("p",{className:"text-2xl font-bold",children:n.length})]})}),e.jsx(ve,{children:e.jsxs(Me,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(In,{className:"h-4 w-4"})," Total Members"]}),e.jsx("p",{className:"text-2xl font-bold",children:o})]})}),e.jsx(ve,{children:e.jsxs(Me,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(WM,{className:"h-4 w-4"})," Total Contacts"]}),e.jsx("p",{className:"text-2xl font-bold",children:c.toLocaleString()})]})}),e.jsx(ve,{children:e.jsxs(Me,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(Cx,{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(ve,{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(St,{className:"text-lg",children:u.team_name}),e.jsxs(Oe,{variant:"secondary",children:[u.member_count," members"]})]}),u.leader_name&&e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[e.jsxs(ja,{className:"h-6 w-6",children:[e.jsx(pi,{src:u.leader_avatar||""}),e.jsx(Na,{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($f,{className:"h-3 w-3 text-amber-500"}),u.leader_name]})]})]}),e.jsx(Me,{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(B,{variant:"outline",onClick:()=>t("/brokerage/teams"),children:"Manage Teams →"})})]})},yTn=()=>{const{user:s,isBrokerageManager:t,brokerageId:n,isAdmin:r,managedBrokerages:a,selectedBrokerageId:i,setSelectedBrokerageId:l}=hs(),o=Fn(),{toast:c}=vi(),[d,u]=_.useState(""),[h,m]=_.useState(!0),p=i||(a.length>0?a[0].id:n);_.useEffect(()=>{if(!s||!t&&!r){o("/dashboard");return}!i&&a.length>0&&l(a[0].id),p?f():a.length===0&&!n&&m(!1)},[s,t,r,p,o,a,i]);const f=async()=>{if(!p){m(!1);return}try{const{data:y,error:v}=await q.from("brokerages").select("name").eq("id",p).single();if(v)throw v;u(y.name)}catch(y){console.error("Error loading brokerage info:",y),c({title:"Error",description:"Failed to load brokerage information",variant:"destructive"})}finally{m(!1)}};return h?e.jsx(zs,{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(zs,{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(is,{value:i||"",onValueChange:l,children:[e.jsxs(rs,{className:"w-[280px]",children:[e.jsx(ai,{className:"mr-2 h-4 w-4"}),e.jsx(ls,{placeholder:"Select brokerage"})]}),e.jsx(as,{children:a.map(y=>e.jsx(He,{value:y.id,children:y.name},y.id))})]})]}),e.jsxs(Yr,{defaultValue:"agents",className:"space-y-4",children:[e.jsxs(Zr,{className:"grid w-full grid-cols-4 md:grid-cols-8",children:[e.jsx(Ht,{value:"agents",children:"Agents"}),e.jsx(Ht,{value:"teams",children:"Teams"}),e.jsx(Ht,{value:"invite",children:"Invite Links"}),e.jsx(Ht,{value:"referrals",children:"Referrals"}),e.jsx(Ht,{value:"leaderboard",children:"Leaderboard"}),e.jsx(Ht,{value:"activity",children:"Activity"}),e.jsx(Ht,{value:"analytics",children:"Analytics"}),e.jsx(Ht,{value:"shares",children:"Shares"})]}),e.jsx(Gt,{value:"agents",className:"space-y-4",children:e.jsx(oTn,{brokerageId:p})}),e.jsx(Gt,{value:"teams",className:"space-y-4",children:e.jsx(gTn,{brokerageId:p})}),e.jsx(Gt,{value:"invite",className:"space-y-4",children:e.jsx(mTn,{brokerageId:p})}),e.jsx(Gt,{value:"referrals",className:"space-y-4",children:e.jsx(xTn,{})}),e.jsx(Gt,{value:"leaderboard",className:"space-y-4",children:e.jsx(eqt,{brokerageId:p,title:`${d} Event Leaderboard`,showUserStats:!1})}),e.jsx(Gt,{value:"activity",className:"space-y-4",children:e.jsx(uTn,{brokerageId:p})}),e.jsx(Gt,{value:"analytics",className:"space-y-4",children:e.jsx(hTn,{brokerageId:p})}),e.jsx(Gt,{value:"shares",className:"space-y-4",children:e.jsx(TVt,{brokerageOnly:!0,brokerageId:p})})]})]})}):e.jsx(zs,{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 vTn({brokerageId:s,canManage:t}){const{user:n}=hs(),[r,a]=_.useState([]),[i,l]=_.useState(!0),[o,c]=_.useState(!1),[d,u]=_.useState(null),[h,m]=_.useState(null),[p,f]=_.useState(!1),[y,v]=_.useState(""),[g,b]=_.useState(""),[j,S]=_.useState(!1),C=async()=>{try{const{data:D,error:O}=await q.from("brokerage_announcements").select("*").eq("brokerage_id",s).order("is_pinned",{ascending:!1}).order("pinned_at",{ascending:!1,nullsFirst:!1}).order("created_at",{ascending:!1});if(O)throw O;const V=D;if(V&&V.length>0){const G=[...new Set(V.map(Z=>Z.created_by))],{data:$}=await q.from("profiles").select("id, name, avatar_url").in("id",G),H=new Map(($==null?void 0:$.map(Z=>[Z.id,Z]))||[]),Y=V.map(Z=>({...Z,author:H.get(Z.created_by)||{name:"Unknown",avatar_url:null}}));a(Y)}else a([])}catch(D){console.error("Error fetching announcements:",D)}finally{l(!1)}};_.useEffect(()=>{C()},[s]);const E=()=>{v(""),b(""),S(!1),u(null)},P=D=>{D?(u(D),v(D.title),b(D.content),S(D.is_pinned)):E(),c(!0)},M=async()=>{if(!y.trim()||!g.trim()){se.error("Please fill in all fields");return}f(!0);try{if(d){const{error:D}=await q.from("brokerage_announcements").update({title:y.trim(),content:g.trim(),is_pinned:j,pinned_at:j?new Date().toISOString():null}).eq("id",d.id);if(D)throw D;se.success("Announcement updated")}else{const{error:D}=await q.from("brokerage_announcements").insert({brokerage_id:s,created_by:n==null?void 0:n.id,title:y.trim(),content:g.trim(),is_pinned:j,pinned_at:j?new Date().toISOString():null});if(D)throw D;se.success("Announcement created")}c(!1),E(),C()}catch(D){console.error("Error saving announcement:",D),se.error("Failed to save announcement")}finally{f(!1)}},I=async()=>{if(h)try{const{error:D}=await q.from("brokerage_announcements").delete().eq("id",h);if(D)throw D;se.success("Announcement deleted"),C()}catch(D){console.error("Error deleting announcement:",D),se.error("Failed to delete announcement")}finally{m(null)}};return i?e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(wh,{className:"h-5 w-5"}),"Announcements"]})}),e.jsx(Me,{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(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between space-y-0 pb-4",children:[e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(wh,{className:"h-5 w-5 text-primary"}),"Announcements"]}),t&&e.jsxs(B,{size:"sm",onClick:()=>P(),className:"gap-1",children:[e.jsx(rn,{className:"h-4 w-4"}),"New"]})]}),e.jsx(Me,{children:r.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No announcements yet"}):e.jsx("div",{className:"space-y-4",children:r.map(D=>{var O,V,G,$;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(YA,{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(ja,{className:"h-5 w-5",children:[e.jsx(pi,{src:((O=D.author)==null?void 0:O.avatar_url)||void 0}),e.jsx(Na,{className:"text-[10px]",children:((G=(V=D.author)==null?void 0:V.name)==null?void 0:G.charAt(0))||"?"})]}),e.jsx("span",{children:($=D.author)==null?void 0:$.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(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>P(D),children:e.jsx(Ya,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",onClick:()=>m(D.id),children:e.jsx(Sn,{className:"h-4 w-4"})})]})]})},D.id)})})})]}),e.jsx(Ls,{open:o,onOpenChange:c,children:e.jsxs(Ps,{children:[e.jsx(Os,{children:e.jsx(Ds,{children:d?"Edit Announcement":"New Announcement"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"title",children:"Title"}),e.jsx(xe,{id:"title",value:y,onChange:D=>v(D.target.value),placeholder:"Announcement title..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"content",children:"Content"}),e.jsx(Ms,{id:"content",value:g,onChange:D=>b(D.target.value),placeholder:"Write your announcement...",rows:4})]}),e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fn,{id:"pinned",checked:j,onCheckedChange:S}),e.jsxs(J,{htmlFor:"pinned",className:"flex items-center gap-1 cursor-pointer",children:[e.jsx(YA,{className:"h-4 w-4"}),"Pin to top"]})]})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx(B,{onClick:M,disabled:p,children:p?"Saving...":d?"Update":"Create"})]})]})]})}),e.jsx(Kl,{open:!!h,onOpenChange:()=>m(null),children:e.jsxs(Ol,{children:[e.jsxs(zl,{children:[e.jsx(Ul,{children:"Delete Announcement"}),e.jsx(ql,{children:"Are you sure you want to delete this announcement? This action cannot be undone."})]}),e.jsxs(Bl,{children:[e.jsx($l,{children:"Cancel"}),e.jsx(Ml,{onClick:I,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})})]})}function bTn({brokerageId:s,canManage:t=!1}){const{startImpersonation:n,isLoading:r}=GMe(),{user:a}=hs(),[i,l]=_.useState([]),[o,c]=_.useState(!0),[d,u]=_.useState(""),[h,m]=_.useState(new Set);_.useEffect(()=>{(async()=>{try{const{data:y,error:v}=await q.from("profiles").select("id, name, email, phone, avatar_url, title, bio, areas_served, years_experience, instagram_url, facebook_url, linkedin_url").eq("brokerage_id",s).order("name");if(v)throw v;if(l(y||[]),y&&y.length>0){const g=y.map(j=>j.id),{data:b}=await q.from("agent_assistant_assignments").select("agent_id").in("agent_id",g);b&&m(new Set(b.map(j=>j.agent_id)))}}catch(y){console.error("Error fetching agents:",y)}finally{c(!1)}})()},[s]);const p=i.filter(f=>{var y,v;return f.name.toLowerCase().includes(d.toLowerCase())||f.email.toLowerCase().includes(d.toLowerCase())||((y=f.title)==null?void 0:y.toLowerCase().includes(d.toLowerCase()))||((v=f.areas_served)==null?void 0:v.toLowerCase().includes(d.toLowerCase()))});return o?e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(In,{className:"h-5 w-5"}),"Agent Roster"]})}),e.jsx(Me,{children:e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:[1,2,3,4].map(f=>e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-48 bg-muted rounded-lg"})},f))})})]}):e.jsxs(ve,{children:[e.jsxs(bt,{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 space-y-0",children:[e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(In,{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(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search agents...",value:d,onChange:f=>u(f.target.value),className:"pl-9"})]})]}),e.jsx(Me,{children:p.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:d?"No agents match your search":"No agents in this brokerage yet"}):e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:p.map(f=>e.jsx(_Tn,{agent:f,hasAssistant:h.has(f.id),canImpersonate:t&&f.id!==(a==null?void 0:a.id),onImpersonate:()=>n(f.id,"/my-brokerage"),impersonationLoading:r},f.id))})})]})}function _Tn({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(ja,{className:"h-20 w-20 mb-3 ring-2 ring-background shadow-md",children:[e.jsx(pi,{src:s.avatar_url||void 0,alt:s.name}),e.jsx(Na,{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(Oe,{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(Xa,{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(ag,{children:[e.jsx(ig,{asChild:!0,children:e.jsx(B,{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(QM,{className:"h-4 w-4"})})}),e.jsxs(Nx,{children:["Login as ",s.name]})]}),s.phone&&e.jsx(B,{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(_a,{className:"h-4 w-4"})})}),e.jsx(B,{variant:"outline",size:"icon",className:"h-8 w-8",asChild:!0,children:e.jsx("a",{href:`mailto:${s.email}`,title:`Email ${s.name}`,children:e.jsx(ln,{className:"h-4 w-4"})})}),s.linkedin_url&&e.jsx(B,{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(dg,{className:"h-4 w-4"})})}),s.instagram_url&&e.jsx(B,{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(Im,{className:"h-4 w-4"})})})]})]})}function wTn({brokerageId:s}){const[t,n]=_.useState([]),[r,a]=_.useState(!0);if(_.useEffect(()=>{(async()=>{try{const{data:c,error:d}=await q.from("profiles").select("id, name, avatar_url").eq("brokerage_id",s);if(d)throw d;if(!c||c.length===0){n([]),a(!1);return}const u=c.map(y=>y.id),{data:h,error:m}=await q.from("agent_attendance_stats").select("user_id, total_points").in("user_id",u).order("total_points",{ascending:!1});if(m)throw m;const p=new Map(c.map(y=>[y.id,y])),f=(h||[]).filter(y=>y.total_points>0).map(y=>{const v=p.get(y.user_id);return{user_id:y.user_id,total_points:y.total_points,name:(v==null?void 0:v.name)||"Unknown",avatar_url:(v==null?void 0:v.avatar_url)||null}});n(f)}catch(c){console.error("Error fetching leaderboard:",c)}finally{a(!1)}})()},[s]),r)return e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(wl,{className:"h-5 w-5"}),"Team Leaderboard"]})}),e.jsx(Me,{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(HA,{className:At("h-5 w-5",i(o))}):e.jsx("span",{className:"w-5 text-center text-sm text-muted-foreground",children:o});return e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(wl,{className:"h-5 w-5 text-primary"}),"Team Leaderboard"]})}),e.jsx(Me,{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:At("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(ja,{className:"h-8 w-8",children:[e.jsx(pi,{src:o.avatar_url||void 0}),e.jsx(Na,{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 jTn({brokerageId:s}){const t=Fn(),[n,r]=_.useState([]),[a,i]=_.useState(!0);_.useEffect(()=>{(async()=>{try{const{data:c,error:d}=await q.from("profiles").select("id, name, avatar_url").eq("brokerage_id",s);if(d)throw d;if(!c||c.length===0){r([]),i(!1);return}const u=c.map(y=>y.id),h=new Map(c.map(y=>[y.id,y])),{data:m,error:p}=await q.from("listings").select(` id, slug, property_address, city, price, property_type, agent_id, listing_photos(photo_url) `).in("agent_id",u).eq("status","active").order("created_at",{ascending:!1}).limit(6);if(p)throw p;const f=(m||[]).map(y=>({id:y.id,slug:y.slug,property_address:y.property_address,city:y.city,price:y.price,property_type:y.property_type,agent_id:y.agent_id,agent:h.get(y.agent_id)||null,photos:y.listing_photos||[]}));r(f)}catch(c){console.error("Error fetching listings:",c)}finally{i(!1)}})()},[s]);const l=o=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(o);return a?e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(Jr,{className:"h-5 w-5"}),"Brokerage Listings"]})}),e.jsx(Me,{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(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between space-y-0 pb-4",children:[e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(Jr,{className:"h-5 w-5 text-primary"}),"Brokerage Listings"]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>t("/mission-control/listings"),className:"gap-1",children:[e.jsx(rn,{className:"h-4 w-4"}),"Add Listing"]})]}),e.jsxs(Me,{children:[n.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx(Jr,{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(B,{size:"sm",onClick:()=>t("/mission-control/listings/new"),className:"gap-1",children:[e.jsx(rn,{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(Jr,{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(B,{variant:"ghost",size:"sm",className:"w-full mt-3",onClick:()=>t("/mission-control/listings"),children:["View All Listings",e.jsx(wr,{className:"h-3 w-3 ml-1"})]})]})]})}const NTn={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 kTn({brokerageId:s,canManage:t}){const{user:n}=hs(),{toast:r}=vi(),{data:a,isLoading:i}=qZs(s),l=$Zs(s),[o,c]=_.useState({...NTn}),[d,u]=_.useState({show_equal_housing:!1,show_realtor_logo:!1,lock_colors:!1,lock_logo:!1}),[h,m]=_.useState(null),p={logo_url:_.useRef(null),logo_dark_url:_.useRef(null),icon_mark_url:_.useRef(null)};_.useEffect(()=>{a&&(c({primary_color:a.primary_color||"",secondary_color:a.secondary_color||"",accent_color:a.accent_color||"",logo_url:a.logo_url||"",logo_dark_url:a.logo_dark_url||"",icon_mark_url:a.icon_mark_url||"",heading_font:a.heading_font||"",body_font:a.body_font||"",legal_name:a.legal_name||"",license_number:a.license_number||"",license_state:a.license_state||"",compliance_line:a.compliance_line||""}),u({show_equal_housing:!!a.show_equal_housing,show_realtor_logo:!!a.show_realtor_logo,lock_colors:!!a.lock_colors,lock_logo:!!a.lock_logo}))},[a]);const f=(b,j)=>c(S=>({...S,[b]:j})),y=async(b,j)=>{if(n){m(b);try{const S=await QUt(n.id,j,`brokerage-${b}`);f(b,S),r({title:"Image uploaded"})}catch(S){r({title:"Upload failed",description:S.message,variant:"destructive"})}finally{m(null)}}},v=async()=>{try{await l.mutateAsync({...Object.fromEntries(Object.entries(o).map(([b,j])=>[b,j||null])),...d}),r({title:"Brokerage brand saved",description:"Agents in this brokerage now inherit these settings."})}catch(b){r({title:"Could not save",description:b.message,variant:"destructive"})}},g=(b,j)=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:j}),e.jsxs("div",{className:"flex items-center gap-3",children:[o[b]&&e.jsx("img",{src:o[b],alt:j,className:"h-12 w-auto rounded border bg-background p-1"}),e.jsx("input",{ref:p[b],type:"file",accept:"image/*",className:"hidden",onChange:S=>{var C;return((C=S.target.files)==null?void 0:C[0])&&y(b,S.target.files[0])}}),e.jsxs(B,{type:"button",variant:"outline",disabled:!t||h===b,onClick:()=>{var S;return(S=p[b].current)==null?void 0:S.click()},children:[h===b?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Oa,{className:"h-4 w-4"}),e.jsx("span",{className:"ml-2",children:"Upload"})]}),o[b]&&t&&e.jsx(B,{type:"button",variant:"ghost",onClick:()=>f(b,""),children:"Remove"})]})]});return e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(ai,{className:"h-5 w-5"}),"Brokerage Brand"]}),e.jsx(kn,{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(Me,{className:"space-y-6",children:i?e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-sm",children:[e.jsx(Ct,{className:"h-4 w-4 animate-spin"})," Loading…"]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid gap-4 sm:grid-cols-3",children:[["primary_color","Primary color","#2a4c64"],["secondary_color","Secondary color","#1c1c1c"],["accent_color","Accent color","#B8965A"]].map(([b,j,S])=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:j}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{type:"color",className:"h-10 w-14 p-1",disabled:!t,value:o[b]||S,onChange:C=>f(b,C.target.value)}),e.jsx(xe,{disabled:!t,value:o[b],placeholder:S,onChange:C=>f(b,C.target.value)})]})]},b))}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-3",children:[g("logo_url","Logo (light background)"),g("logo_dark_url","Logo (dark background)"),g("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(J,{children:"Heading font"}),e.jsx(xe,{disabled:!t,value:o.heading_font,placeholder:"Playfair Display",onChange:b=>f("heading_font",b.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Body font"}),e.jsx(xe,{disabled:!t,value:o.body_font,placeholder:"Inter",onChange:b=>f("body_font",b.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Legal brokerage name"}),e.jsx(xe,{disabled:!t,value:o.legal_name,placeholder:"Acme Realty, Inc.",onChange:b=>f("legal_name",b.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Brokerage license #"}),e.jsx(xe,{disabled:!t,value:o.license_number,placeholder:"DRE #01234567",onChange:b=>f("license_number",b.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"License state"}),e.jsx(xe,{disabled:!t,value:o.license_state,placeholder:"CA",onChange:b=>f("license_state",b.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Required disclaimer / compliance line"}),e.jsx(Ms,{disabled:!t,rows:2,value:o.compliance_line,placeholder:"Each office independently owned and operated. Information deemed reliable but not guaranteed.",onChange:b=>f("compliance_line",b.target.value)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Included in every brand kit so AI-generated marketing carries it automatically."})]}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:[["show_equal_housing","Include Equal Housing logo"],["show_realtor_logo","Include REALTOR® logo"],["lock_colors","Lock colors (agents cannot override)"],["lock_logo","Lock logo (agents cannot override)"]].map(([b,j])=>e.jsxs("div",{className:"flex items-center justify-between rounded-md border p-3",children:[e.jsx(J,{className:"text-sm font-normal",children:j}),e.jsx(fn,{disabled:!t,checked:d[b],onCheckedChange:S=>u(C=>({...C,[b]:S}))})]},b))}),t&&e.jsxs(B,{onClick:v,disabled:l.isPending,children:[l.isPending?e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Ho,{className:"mr-2 h-4 w-4"}),"Save brokerage brand"]})]})})]})}const kKt="brokerage-onboarding-docs",CA=s=>s.status==="approved"||s.status==="complete";function SKt(s){return at({queryKey:["onboarding-templates",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("brokerage_onboarding_templates").select("*").eq("brokerage_id",s).eq("is_archived",!1).order("created_at",{ascending:!0});if(n)throw n;return t||[]}})}function STn(s){return at({queryKey:["onboarding-template-steps",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("brokerage_onboarding_template_steps").select("*").eq("template_id",s).order("sort_order",{ascending:!0});if(n)throw n;return t||[]}})}function CKt(s){return at({queryKey:["onboarding-roster",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("profiles").select("id, name, email, avatar_url, created_at").eq("brokerage_id",s).order("name",{ascending:!0});if(n)throw n;const{data:r,error:a}=await q.from("brokerage_onboarding_assignments").select("*").eq("brokerage_id",s);if(a)throw a;const i=(r||[]).map(c=>c.id);let l=[];if(i.length){const{data:c,error:d}=await q.from("brokerage_onboarding_steps").select("*").in("assignment_id",i);if(d)throw d;l=c||[]}const o=new Date().toISOString().slice(0,10);return(t||[]).map(c=>{const d=(r||[]).find(h=>h.agent_user_id===c.id)||null,u=d?l.filter(h=>h.assignment_id===d.id):[];return{agentId:c.id,name:c.name||c.email,email:c.email,avatarUrl:c.avatar_url||null,joinedAt:c.created_at||null,assignment:d,total:u.length,done:u.filter(CA).length,overdue:u.filter(h=>!CA(h)&&h.due_date&&h.due_dateh.status==="submitted").length}})}})}function AKt(s){return at({queryKey:["onboarding-detail",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("brokerage_onboarding_steps").select("*").eq("assignment_id",s).order("sort_order",{ascending:!0});if(n)throw n;const r=(t||[]).map(i=>i.id);let a=[];if(r.length){const{data:i,error:l}=await q.from("brokerage_onboarding_documents").select("*").in("step_id",r).order("version",{ascending:!1});if(l)throw l;a=i||[]}return{steps:t||[],documents:a}}})}function CTn(s){return at({queryKey:["my-onboarding",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("brokerage_onboarding_assignments").select("*").eq("agent_user_id",s).maybeSingle();if(n)throw n;return t||null}})}function ATn(s,t){return at({queryKey:["agent-record",s,t],enabled:!!s&&!!t,queryFn:async()=>{const{data:n,error:r}=await q.from("brokerage_agent_records").select("*").eq("brokerage_id",s).eq("agent_user_id",t).maybeSingle();if(r)throw r;return n||null}})}function ETn(s,t){return at({queryKey:["agent-notes",s,t],enabled:!!s&&!!t,queryFn:async()=>{const{data:n,error:r}=await q.from("brokerage_agent_notes").select("*").eq("brokerage_id",s).eq("agent_user_id",t).order("created_at",{ascending:!1});if(r)throw r;return n||[]}})}function EKt(s,t){return at({queryKey:["agent-activity",s,t],enabled:!!s&&!!t,queryFn:async()=>{const{data:n,error:r}=await q.from("brokerage_onboarding_activity").select("*").eq("brokerage_id",s).eq("agent_user_id",t).order("created_at",{ascending:!1}).limit(100);if(r)throw r;return n||[]}})}async function Pce(s){const{data:t}=await q.auth.getUser();t.user&&await q.from("brokerage_onboarding_activity").insert({brokerage_id:s.brokerageId,agent_user_id:s.agentUserId,actor_id:t.user.id,event_type:s.eventType,description:s.description})}function $Ie(s){const t=Bt(),n=(h,m)=>{t.invalidateQueries({queryKey:["onboarding-roster",s]}),m&&t.invalidateQueries({queryKey:["onboarding-detail",m]}),h&&(t.invalidateQueries({queryKey:["agent-activity",s,h]}),t.invalidateQueries({queryKey:["my-onboarding",h]}))},r=mt({mutationFn:async({agentUserId:h,templateId:m})=>{var S;const{data:p}=await q.auth.getUser(),{data:f,error:y}=await q.from("brokerage_onboarding_templates").select("id, name").eq("id",m).single();if(y)throw y;const{data:v,error:g}=await q.from("brokerage_onboarding_template_steps").select("*").eq("template_id",m).order("sort_order",{ascending:!0});if(g)throw g;const{data:b,error:j}=await q.from("brokerage_onboarding_assignments").insert({brokerage_id:s,agent_user_id:h,template_id:m,template_name:f.name,status:"in_progress",created_by:((S=p.user)==null?void 0:S.id)??null}).select().single();if(j)throw j;if(v!=null&&v.length){const C=new Date,E=v.map(M=>{let I=null;if(M.due_days!=null){const D=new Date(C);D.setDate(D.getDate()+M.due_days),I=D.toISOString().slice(0,10)}return{assignment_id:b.id,title:M.title,description:M.description,step_type:M.step_type,assignee:M.assignee,form_template_id:M.form_template_id,external_url:M.external_url,due_date:I,sort_order:M.sort_order}}),{error:P}=await q.from("brokerage_onboarding_steps").insert(E);if(P)throw P}return await Pce({brokerageId:s,agentUserId:h,eventType:"onboarding_started",description:`Onboarding started using "${f.name}"`}),b},onSuccess:h=>n(h.agent_user_id,h.id)}),a=mt({mutationFn:async h=>{const{error:m}=await q.from("brokerage_onboarding_assignments").delete().eq("id",h.id);if(m)throw m;return h},onSuccess:h=>n(h.agent_user_id,h.id)}),i=mt({mutationFn:async({step:h,status:m,note:p,agentUserId:f})=>{var b;const{data:y}=await q.auth.getUser(),v=m==="approved"||m==="complete",{error:g}=await q.from("brokerage_onboarding_steps").update({status:m,review_note:p??null,completed_at:v?new Date().toISOString():null,completed_by:v?((b=y.user)==null?void 0:b.id)??null:null}).eq("id",h.id);if(g)throw g;return s&&await Pce({brokerageId:s,agentUserId:f,eventType:`step_${m}`,description:`"${h.title}" marked ${m.replace("_"," ")}`}),{step:h,agentUserId:f}},onSuccess:({step:h,agentUserId:m})=>n(m,h.assignment_id)}),l=mt({mutationFn:async({step:h,file:m,agentUserId:p,existingVersions:f})=>{var S;const{data:y}=await q.auth.getUser(),v=m.name.replace(/[^a-zA-Z0-9._-]/g,"_"),g=`${s}/${p}/${h.id}/${Date.now()}-${v}`,{error:b}=await q.storage.from(kKt).upload(g,m,{upsert:!1,contentType:m.type||void 0});if(b)throw b;const{error:j}=await q.from("brokerage_onboarding_documents").insert({step_id:h.id,storage_path:g,file_name:m.name,file_size:m.size,file_type:m.type,version:f+1,uploaded_by:((S=y.user)==null?void 0:S.id)??null,review_status:"submitted"});if(j)throw j;return await q.from("brokerage_onboarding_steps").update({status:"submitted",review_note:null}).eq("id",h.id),s&&await Pce({brokerageId:s,agentUserId:p,eventType:"document_uploaded",description:`Document uploaded for "${h.title}"`}),{step:h,agentUserId:p}},onSuccess:({step:h,agentUserId:m})=>n(m,h.assignment_id)}),o=mt({mutationFn:async({doc:h,step:m,status:p,note:f,agentUserId:y})=>{var j;const{data:v}=await q.auth.getUser(),{error:g}=await q.from("brokerage_onboarding_documents").update({review_status:p,review_note:f??null,reviewed_by:((j=v.user)==null?void 0:j.id)??null,reviewed_at:new Date().toISOString()}).eq("id",h.id);if(g)throw g;const b=p==="approved"?"approved":p==="changes_requested"?"changes_requested":"submitted";return await q.from("brokerage_onboarding_steps").update({status:b,review_note:f??null,completed_at:p==="approved"?new Date().toISOString():null}).eq("id",m.id),s&&await Pce({brokerageId:s,agentUserId:y,eventType:`document_${p}`,description:`${h.file_name} ${p==="approved"?"approved":p==="changes_requested"?"needs changes":"approval revoked"}`}),{step:m,agentUserId:y}},onSuccess:({step:h,agentUserId:m})=>n(m,h.assignment_id)}),c=mt({mutationFn:async h=>{const{error:m}=await q.from("brokerage_agent_records").upsert(h,{onConflict:"brokerage_id,agent_user_id"});if(m)throw m;return h},onSuccess:h=>{t.invalidateQueries({queryKey:["agent-record",h.brokerage_id,h.agent_user_id]})}}),d=mt({mutationFn:async({agentUserId:h,body:m})=>{const{data:p}=await q.auth.getUser(),{error:f}=await q.from("brokerage_agent_notes").insert({brokerage_id:s,agent_user_id:h,body:m,author_id:p.user.id});if(f)throw f;return h},onSuccess:h=>{t.invalidateQueries({queryKey:["agent-notes",s,h]})}}),u=mt({mutationFn:async({id:h,agentUserId:m})=>{const{error:p}=await q.from("brokerage_agent_notes").delete().eq("id",h);if(p)throw p;return m},onSuccess:h=>{t.invalidateQueries({queryKey:["agent-notes",s,h]})}});return{assignTemplate:r,removeAssignment:a,setStepStatus:i,uploadDocument:l,reviewDocument:o,saveRecord:c,addNote:d,deleteNote:u}}function TTn(s){const t=Bt(),n=d=>{t.invalidateQueries({queryKey:["onboarding-templates",s]}),d&&t.invalidateQueries({queryKey:["onboarding-template-steps",d]})},r=mt({mutationFn:async({name:d,description:u})=>{var f;const{data:h}=await q.auth.getUser(),{data:m,error:p}=await q.from("brokerage_onboarding_templates").insert({brokerage_id:s,name:d,description:u||null,created_by:((f=h.user)==null?void 0:f.id)??null}).select().single();if(p)throw p;return m},onSuccess:()=>n()}),a=mt({mutationFn:async({id:d,...u})=>{const{error:h}=await q.from("brokerage_onboarding_templates").update(u).eq("id",d);if(h)throw h;return d},onSuccess:()=>n()}),i=mt({mutationFn:async d=>{const{error:u}=await q.from("brokerage_onboarding_templates").delete().eq("id",d);if(u)throw u;return d},onSuccess:()=>n()}),l=mt({mutationFn:async d=>{if(d.id){const{error:u}=await q.from("brokerage_onboarding_template_steps").update(d).eq("id",d.id);if(u)throw u}else{const{error:u}=await q.from("brokerage_onboarding_template_steps").insert(d);if(u)throw u}return d.template_id},onSuccess:d=>n(d)}),o=mt({mutationFn:async({id:d,templateId:u})=>{const{error:h}=await q.from("brokerage_onboarding_template_steps").delete().eq("id",d);if(h)throw h;return u},onSuccess:d=>n(d)}),c=mt({mutationFn:async({steps:d,templateId:u})=>{for(let h=0;hn(d)});return{createTemplate:r,updateTemplate:a,deleteTemplate:i,upsertStep:l,deleteStep:o,reorderSteps:c}}async function MTn(s){const{data:t,error:n}=await q.storage.from(kKt).createSignedUrl(s,300);if(n)throw n;return t.signedUrl}const PTn=s=>s==="document"?Fr:s==="form"?lb:Ww,LTn=s=>{switch(s.status){case"approved":return{label:"Approved",className:"bg-emerald-500/15 text-emerald-600 border-emerald-500/30"};case"complete":return{label:"Complete",className:"bg-emerald-500/15 text-emerald-600 border-emerald-500/30"};case"submitted":return{label:"In review",className:"bg-amber-500/15 text-amber-600 border-amber-500/30"};case"changes_requested":return{label:"Needs changes",className:"bg-destructive/10 text-destructive border-destructive/30"};default:return{label:"Pending",className:"bg-muted text-muted-foreground border-border"}}},rWe=({brokerageId:s,agentUserId:t,steps:n,documents:r,mode:a,displayMode:i="all"})=>{const{toast:l}=vi(),{setStepStatus:o,uploadDocument:c,reviewDocument:d}=$Ie(s),u=_.useRef({}),[h,m]=_.useState(null),[p,f]=_.useState(""),y=new Date().toISOString().slice(0,10),v=j=>r.filter(S=>S.step_id===j).sort((S,C)=>C.version-S.version),g=async(j,S)=>{try{await c.mutateAsync({step:j,file:S,agentUserId:t,existingVersions:v(j.id).length}),l({title:"Uploaded",description:`${S.name} is ready for review.`})}catch(C){l({title:"Upload failed",description:C.message,variant:"destructive"})}},b=async j=>{try{const S=await MTn(j);window.open(S,"_blank","noopener,noreferrer")}catch(S){l({title:"Could not open file",description:S.message,variant:"destructive"})}};return e.jsxs("div",{className:"space-y-3",children:[n.filter(j=>i==="all"||j.step_type!=="task").length===0&&e.jsx("p",{className:"py-10 text-center text-sm text-muted-foreground",children:"No steps in this checklist yet."}),n.filter(j=>i==="all"||j.step_type!=="task").map(j=>{const S=PTn(j.step_type),C=LTn(j),E=v(j.id),P=E[0],M=!CA(j)&&j.due_date&&j.due_date0&&e.jsx("div",{className:"mt-3 space-y-1",children:E.map(D=>e.jsxs("div",{className:"flex flex-wrap items-center gap-2 rounded-md bg-muted/50 px-3 py-2 text-sm",children:[e.jsx(Fr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"min-w-0 flex-1 truncate",children:D.file_name}),e.jsxs(Oe,{variant:"outline",className:"capitalize",children:["v",D.version," · ",D.review_status.replace("_"," ")]}),e.jsxs(B,{size:"sm",variant:"ghost",onClick:()=>b(D.storage_path),children:[e.jsx(li,{className:"mr-1 h-4 w-4"})," Open"]})]},D.id))})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[j.step_type!=="task"&&I&&e.jsxs(e.Fragment,{children:[e.jsx("input",{type:"file",className:"hidden",accept:".pdf,.png,.jpg,.jpeg,.heic,.doc,.docx",ref:D=>u.current[j.id]=D,onChange:D=>{var V;const O=(V=D.target.files)==null?void 0:V[0];O&&g(j,O),D.target.value=""}}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>{var D;return(D=u.current[j.id])==null?void 0:D.click()},children:[e.jsx(Oa,{className:"mr-1 h-4 w-4"})," Upload"]})]}),j.step_type==="task"&&I&&!CA(j)&&e.jsxs(B,{size:"sm",onClick:()=>o.mutate({step:j,status:"complete",agentUserId:t}),children:[e.jsx(Ww,{className:"mr-1 h-4 w-4"})," Complete"]}),a==="manager"&&P&&P.review_status!=="approved"&&e.jsxs(e.Fragment,{children:[e.jsxs(B,{size:"sm",onClick:()=>d.mutate({doc:P,step:j,status:"approved",agentUserId:t}),children:[e.jsx(Er,{className:"mr-1 h-4 w-4"})," Approve"]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>{m({step:j,doc:P}),f("")},children:[e.jsx(Rd,{className:"mr-1 h-4 w-4"})," Needs changes"]})]}),a==="manager"&&CA(j)&&e.jsxs(B,{size:"sm",variant:"ghost",onClick:()=>P?d.mutate({doc:P,step:j,status:"submitted",agentUserId:t}):o.mutate({step:j,status:"pending",agentUserId:t}),children:[e.jsx(Tx,{className:"mr-1 h-4 w-4"})," Revoke"]})]})]})},j.id)}),e.jsx(Ls,{open:!!h,onOpenChange:j=>!j&&m(null),children:e.jsxs(Ps,{children:[e.jsx(Os,{children:e.jsx(Ds,{children:"Request changes"})}),e.jsx(Ms,{rows:4,value:p,onChange:j=>f(j.target.value),placeholder:"Tell the agent what needs to be fixed…"}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>m(null),children:"Cancel"}),e.jsx(B,{onClick:async()=>{h&&(await d.mutateAsync({doc:h.doc,step:h.step,status:"changes_requested",note:p,agentUserId:t}),m(null))},children:"Send back"})]})]})})]})},ITn=()=>{const{user:s}=hs(),{data:t}=CTn(s==null?void 0:s.id),{data:n}=AKt(t==null?void 0:t.id);if(!t)return null;const r=(n==null?void 0:n.steps)||[],a=r.filter(CA).length,i=r.length?Math.round(a/r.length*100):0;return e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(cN,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{children:[e.jsx(St,{children:"Your onboarding"}),e.jsx(kn,{children:t.template_name||"Onboarding checklist"})]})]}),e.jsxs("div",{className:"w-full max-w-[220px]",children:[e.jsx(Fi,{value:i}),e.jsxs("p",{className:"mt-1 text-right text-xs text-muted-foreground",children:[a," of ",r.length," complete"]})]})]})}),e.jsx(Me,{children:e.jsx(rWe,{brokerageId:t.brokerage_id,agentUserId:t.agent_user_id,steps:r,documents:(n==null?void 0:n.documents)||[],mode:"agent"})})]})};function DTn(){const{user:s,isAdmin:t,isBrokerageManager:n}=hs(),r=Fn(),[a,i]=_.useState(!0),[l,o]=_.useState(null),[c,d]=_.useState(""),[u,h]=_.useState(0),[m,p]=_.useState(!1),[f,y]=_.useState(!1);return _.useEffect(()=>{(async()=>{if(s)try{const{data:g}=await q.from("profiles").select("brokerage_id").eq("id",s.id).maybeSingle();if(!(g!=null&&g.brokerage_id)){i(!1);return}o(g.brokerage_id);const{data:b}=await q.from("brokerages").select("name").eq("id",g.brokerage_id).maybeSingle();b&&d(b.name);const{count:j}=await q.from("profiles").select("id",{count:"exact",head:!0}).eq("brokerage_id",g.brokerage_id);if(h(j||0),t)p(!0),y(!0);else if(n){const{data:S}=await q.from("brokerage_manager_assignments").select("id").eq("user_id",s.id).eq("brokerage_id",g.brokerage_id).maybeSingle();p(!!S),y(!!S)}}catch(g){console.error("Error fetching brokerage info:",g)}finally{i(!1)}})()},[s,t,n]),a?e.jsx(zs,{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(zs,{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(In,{className:"h-5 w-5 text-primary"}),e.jsxs("span",{className:"font-medium",children:[u," ",u===1?"Agent":"Agents"]})]}),f&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{variant:"outline",onClick:()=>r("/brokerage-content"),children:[e.jsx(Sx,{className:"h-4 w-4 mr-2"}),"Brokerage Content"]}),e.jsxs(B,{onClick:()=>r(`/mission-control/listings/new?brokerage=${l}`),children:[e.jsx(Jr,{className:"h-4 w-4 mr-2"}),"Add Listing"]})]})]}),e.jsx(ITn,{}),e.jsx(kTn,{brokerageId:l,canManage:m}),e.jsx(vTn,{brokerageId:l,canManage:m}),e.jsx(bTn,{brokerageId:l,canManage:m}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[e.jsx(wTn,{brokerageId:l}),e.jsx(jTn,{brokerageId:l})]})]})}):e.jsx(zs,{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 RTn(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 FTn(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 Qwt={video:{icon:Jd,label:"Video",color:"bg-red-500/10 text-red-600 dark:text-red-400"},pdf:{icon:Fr,label:"Document",color:"bg-blue-500/10 text-blue-600 dark:text-blue-400"},link:{icon:vd,label:"Link",color:"bg-green-500/10 text-green-600 dark:text-green-400"},event:{icon:ga,label:"Event",color:"bg-purple-500/10 text-purple-600 dark:text-purple-400"},graphic:{icon:Xc,label:"Graphic",color:"bg-amber-500/10 text-amber-600 dark:text-amber-400"}};function OTn({item:s,canManage:t}){const[n,r]=_.useState(!1),[a,i]=_.useState(null),l=PUs(),o=Fn(),c=Qwt[s.content_type]||Qwt.link,d=c.icon,u=_.useMemo(()=>s.thumbnail_url?s.thumbnail_url:s.content_type==="graphic"&&s.file_url?s.file_url:s.content_type==="video"?RTn(s.url):null,[s]);_.useEffect(()=>{u||!s.url||s.content_type!=="video"||!FTn(s.url)||fetch(`https://www.youtube.com/oembed?url=${encodeURIComponent(s.url)}&format=json`).then(f=>f.ok?f.json():null).then(f=>{f!=null&&f.thumbnail_url&&i(f.thumbnail_url)}).catch(()=>{})},[s.url,s.content_type,u]);const h=u||a,m=()=>{o(`/brokerage-content/${s.id}`)},p=async()=>{try{await l.mutateAsync(s.id),se.success("Content deleted")}catch{se.error("Failed to delete")}r(!1)};return e.jsxs(e.Fragment,{children:[e.jsxs(ve,{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(Me,{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(Oe,{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(Oe,{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(tu,{children:[e.jsx(su,{asChild:!0,onClick:f=>f.stopPropagation(),children:e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0",children:e.jsx(Xx,{className:"h-4 w-4"})})}),e.jsx(Od,{align:"end",children:e.jsxs(ca,{onClick:f=>{f.stopPropagation(),r(!0)},className:"text-destructive",children:[e.jsx(Sn,{className:"h-4 w-4 mr-2"}),"Delete"]})})]})]})})]}),e.jsx(Kl,{open:n,onOpenChange:r,children:e.jsxs(Ol,{children:[e.jsxs(zl,{children:[e.jsx(Ul,{children:"Delete Content"}),e.jsxs(ql,{children:['Are you sure you want to delete "',s.title,'"? This cannot be undone.']})]}),e.jsxs(Bl,{children:[e.jsx($l,{children:"Cancel"}),e.jsx(Ml,{onClick:p,className:"bg-destructive text-destructive-foreground",children:"Delete"})]})]})})]})}function zTn(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 Jwt=[{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 BTn({brokerageId:s,categories:t}){var ae;const{user:n}=hs(),[r,a]=_.useState(!1),[i,l]=_.useState(!1),[o,c]=_.useState(""),[d,u]=_.useState("📁"),[h,m]=_.useState(!1);_.useRef(null);const[p,f]=_.useState("video"),[y,v]=_.useState(""),[g,b]=_.useState(""),[j,S]=_.useState(""),[C,E]=_.useState(""),[P,M]=_.useState(""),[I,D]=_.useState(""),[O,V]=_.useState(""),G=MUs(),$=LUs(s),H=IUs(),Y=DUs(s),Z=()=>{f("video"),v(""),b(""),S(""),E(""),M(""),D(""),V("")},ne=async(le,be)=>{var he;const me=(he=le.target.files)==null?void 0:he[0];if(me){m(!0);try{const pe=me.name.split(".").pop(),Ce=`${s}/${Date.now()}-${Math.random().toString(36).slice(2)}.${pe}`,{error:Ae}=await q.storage.from("brokerage-content").upload(Ce,me);if(Ae)throw Ae;const{data:{publicUrl:Pe}}=q.storage.from("brokerage-content").getPublicUrl(Ce);be==="file"?(E(Pe),p==="graphic"&&!P&&M(Pe)):M(Pe),se.success("File uploaded")}catch(pe){se.error(pe.message||"Upload failed")}finally{m(!1)}}},ce=async()=>{if(!y.trim()){se.error("Title is required");return}if(n)try{await G.mutateAsync({brokerage_id:s,category_id:O||null,content_type:p,title:y.trim(),description:g.trim()||null,url:j.trim()||null,file_url:C.trim()||null,thumbnail_url:P.trim()||null,event_date:I?new Date(I).toISOString():null,created_by:n.id}),se.success("Content added!"),Z(),a(!1)}catch(le){se.error(le.message||"Failed to add content")}},ie=async()=>{if(o.trim())try{await $.mutateAsync({name:o.trim(),icon:d,sort_order:t.length}),c(""),u("📁"),se.success("Category created")}catch(le){se.error(le.message||"Failed to create category")}},te=async()=>{try{await Y.mutateAsync(),se.success("Default categories created")}catch{se.error("Failed to create defaults")}};return e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs(Ls,{open:r,onOpenChange:a,children:[e.jsx(nl,{asChild:!0,children:e.jsxs(B,{children:[e.jsx(rn,{className:"h-4 w-4 mr-2"}),"Add Content"]})}),e.jsxs(Ps,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Ds,{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(J,{children:"Content Type"}),e.jsxs(is,{value:p,onValueChange:f,children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsx(as,{children:Jwt.map(le=>e.jsx(He,{value:le.value,children:le.label},le.value))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(ae=Jwt.find(le=>le.value===p))==null?void 0:ae.hint})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Category"}),e.jsxs(is,{value:O,onValueChange:V,children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Select category (optional)"})}),e.jsx(as,{children:t.map(le=>e.jsxs(He,{value:le.id,children:[le.icon," ",le.name]},le.id))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Title *"}),e.jsx(xe,{value:y,onChange:le=>v(le.target.value),placeholder:"Content title"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Description"}),e.jsx(Ms,{value:g,onChange:le=>b(le.target.value),placeholder:"Brief description...",rows:2})]}),["video","link","graphic","event"].includes(p)&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:p==="video"?"Video URL":p==="graphic"?"Canva / Image URL":p==="event"?"Event Link (Zoom, etc.)":"URL"}),e.jsx(xe,{value:j,onChange:le=>{const be=le.target.value;if(S(be),p==="video"&&!P){const me=zTn(be);me&&M(me)}},placeholder:"https://..."})]}),["pdf","graphic"].includes(p)&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:p==="pdf"?"Upload PDF":"Upload Image"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xe,{type:"file",accept:p==="pdf"?".pdf,.doc,.docx":"image/*",onChange:le=>ne(le,"file"),disabled:h}),h&&e.jsx(Ct,{className:"h-4 w-4 animate-spin"})]}),C&&e.jsx("p",{className:"text-xs text-green-600",children:"✓ File uploaded"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Thumbnail Image (optional)"}),e.jsx(xe,{type:"file",accept:"image/*",onChange:le=>ne(le,"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(Qn,{className:"h-3 w-3"})})]})]}),p==="event"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Event Date & Time"}),e.jsx(xe,{type:"datetime-local",value:I,onChange:le=>D(le.target.value)})]}),e.jsxs(B,{onClick:ce,disabled:G.isPending||!y.trim(),className:"w-full",children:[G.isPending?e.jsx(Ct,{className:"h-4 w-4 animate-spin mr-2"}):e.jsx(rn,{className:"h-4 w-4 mr-2"}),"Add Content"]})]})]})]}),e.jsxs(Ls,{open:i,onOpenChange:l,children:[e.jsx(nl,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",children:[e.jsx(qc,{className:"h-4 w-4 mr-2"}),"Categories"]})}),e.jsxs(Ps,{className:"max-w-md",children:[e.jsx(Os,{children:e.jsx(Ds,{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(B,{variant:"outline",size:"sm",onClick:te,disabled:Y.isPending,children:[Y.isPending?e.jsx(Ct,{className:"h-4 w-4 animate-spin mr-2"}):null,"Create Default Categories"]})]}),t.map(le=>e.jsxs("div",{className:"flex items-center justify-between p-2 rounded-lg border",children:[e.jsxs("span",{className:"text-sm",children:[le.icon," ",le.name]}),!le.is_default&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7 text-destructive",onClick:async()=>{await H.mutateAsync(le.id),se.success("Category deleted")},children:e.jsx(Qn,{className:"h-4 w-4"})})]},le.id)),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(xe,{value:d,onChange:le=>u(le.target.value),className:"w-14 text-center",maxLength:2}),e.jsx(xe,{value:o,onChange:le=>c(le.target.value),placeholder:"New category name",className:"flex-1",onKeyDown:le=>le.key==="Enter"&&ie()}),e.jsx(B,{size:"sm",onClick:ie,disabled:!o.trim(),children:"Add"})]})]})]})]})]})}function UTn(){const{user:s,isAdmin:t,isBrokerageManager:n}=hs(),[r,a]=_.useState(!0),[i,l]=_.useState(null),[o,c]=_.useState(""),[d,u]=_.useState(!1),[h,m]=_.useState(null),[p,f]=_.useState("");_.useEffect(()=>{(async()=>{if(s)try{const{data:S}=await q.from("profiles").select("brokerage_id").eq("id",s.id).maybeSingle();if(!(S!=null&&S.brokerage_id)){a(!1);return}l(S.brokerage_id);const{data:C}=await q.from("brokerages").select("name").eq("id",S.brokerage_id).maybeSingle();if(C&&c(C.name),t)u(!0);else if(n){const{data:E}=await q.from("brokerage_manager_assignments").select("id").eq("user_id",s.id).eq("brokerage_id",S.brokerage_id).maybeSingle();u(!!E)}}catch(S){console.error("Error fetching brokerage info:",S)}finally{a(!1)}})()},[s,t,n]);const{data:y=[]}=AUs(i),{data:v=[],isLoading:g}=EUs(i,h),b=_.useMemo(()=>{if(!p.trim())return v;const j=p.toLowerCase();return v.filter(S=>{var C;return S.title.toLowerCase().includes(j)||((C=S.description)==null?void 0:C.toLowerCase().includes(j))||S.content_type.toLowerCase().includes(j)})},[v,p]);return r?e.jsx(zs,{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(zs,{title:`${o} Content`,description:"Brokerage Content Hub",children:e.jsxs("div",{className:"space-y-6",children:[d&&i&&e.jsx(BTn,{brokerageId:i,categories:y}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search content...",value:p,onChange:j=>f(j.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(B,{variant:h===null?"default":"outline",size:"sm",onClick:()=>m(null),children:"All"}),y.map(j=>e.jsxs(B,{variant:h===j.id?"default":"outline",size:"sm",onClick:()=>m(j.id),children:[e.jsx("span",{className:"mr-1",children:j.icon}),j.name]},j.id))]})]}),g?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):b.length===0?e.jsx(ve,{className:"bg-muted/30 border-dashed",children:e.jsxs(Me,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(wy,{className:"h-12 w-12 text-muted-foreground/50 mb-3"}),e.jsx("p",{className:"text-muted-foreground font-medium",children:p.trim()?"No matching content found":"No content yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:p.trim()?"Try a different search term or category.":d?"Add your first piece of content above.":"Your brokerage hasn't added content yet."})]})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:b.map(j=>e.jsx(OTn,{item:j,canManage:d},j.id))})]})}):e.jsx(zs,{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 ejt={video:{icon:Jd,label:"Video",color:"bg-red-500/10 text-red-600 dark:text-red-400"},pdf:{icon:Fr,label:"Document",color:"bg-blue-500/10 text-blue-600 dark:text-blue-400"},link:{icon:vd,label:"Link",color:"bg-green-500/10 text-green-600 dark:text-green-400"},event:{icon:ga,label:"Event",color:"bg-purple-500/10 text-purple-600 dark:text-purple-400"},graphic:{icon:Xc,label:"Graphic",color:"bg-amber-500/10 text-amber-600 dark:text-amber-400"}};function qTn(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 $Tn(s){try{const t=new URL(s).hostname.replace("www.","");return["youtube.com","youtu.be","m.youtube.com"].includes(t)}catch{return!1}}function VTn(s){try{return new URL(s).hostname.includes("vimeo.com")}catch{return!1}}function HTn(s){try{const t=s.match(/vimeo\.com\/(\d+)/);if(t)return`https://player.vimeo.com/video/${t[1]}`}catch{}return null}function GTn(){const{contentId:s}=Li(),{data:t,isLoading:n}=at({queryKey:["brokerage-content-detail",s],queryFn:async()=>{const{data:d,error:u}=await q.from("brokerage_content").select(` *, category:brokerage_content_categories(*) `).eq("id",s).single();if(u)throw u;return d},enabled:!!s});if(n)return e.jsx(zs,{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(zs,{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(B,{asChild:!0,className:"mt-4",children:e.jsx(ir,{to:"/brokerage-content",children:"Back to Content"})})]})});const r=ejt[t.content_type]||ejt.link,a=r.icon,i=t.url||t.file_url,l=i&&$Tn(i)?qTn(i):null,o=i&&VTn(i)?HTn(i):null,c=l||o;return e.jsx(zs,{title:t.title,children:e.jsxs("div",{className:"space-y-6 max-w-4xl mx-auto",children:[e.jsx(B,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(ir,{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(Oe,{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(Oe,{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(ve,{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(ve,{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(ve,{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(ve,{children:e.jsx(Me,{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(ve,{children:e.jsxs(Me,{className:"pt-6 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-md bg-primary/10",children:e.jsx(ga,{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(B,{asChild:!0,size:"lg",children:e.jsxs("a",{href:t.file_url,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(li,{className:"h-4 w-4 mr-2"}),t.content_type==="pdf"?"Download Document":"Download File"]})}),t.url&&e.jsx(B,{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(wr,{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 PTe={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 WTn(s="open"){const{user:t}=hs();return at({queryKey:["brokerage-help-requests",s,t==null?void 0:t.id],queryFn:async()=>{if(!t)return[];let n=q.from("brokerage_help_requests").select("*, requester:profiles!brokerage_help_requests_requester_user_id_fkey(name, email, avatar_url)").order("created_at",{ascending:!1});if(s==="open")n=n.eq("status","open");else if(s==="mine")n=n.eq("requester_user_id",t.id);else if(s==="filled")n=n.in("status",["filled","completed"]);else if(s==="my_claims"){const{data:i}=await q.from("brokerage_help_claims").select("request_id").eq("claimant_user_id",t.id),l=(i||[]).map(o=>o.request_id);if(l.length===0)return[];n=n.in("id",l)}const{data:r,error:a}=await n;if(a)throw a;return r},enabled:!!t})}function KTn(s){return at({queryKey:["brokerage-help-request",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("brokerage_help_requests").select("*, requester:profiles!brokerage_help_requests_requester_user_id_fkey(name, email, phone, avatar_url)").eq("id",s).single();if(n)throw n;return t},enabled:!!s})}function YTn(s){return at({queryKey:["brokerage-help-claims",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("brokerage_help_claims").select("*, claimant:profiles!brokerage_help_claims_claimant_user_id_fkey(name, email, phone, avatar_url)").eq("request_id",s).order("created_at",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function ZTn(){const s=Bt(),{user:t,brokerageId:n}=hs();return mt({mutationFn:async r=>{if(!t||!n)throw new Error("You must be in a brokerage to post.");const{data:a,error:i}=await q.from("brokerage_help_requests").insert({...r,brokerage_id:n,requester_user_id:t.id}).select().single();if(i)throw i;try{await q.functions.invoke("brokerage-help-notify",{body:{request_id:a.id}})}catch(l){console.warn("notify failed (non-blocking):",l)}return a},onSuccess:()=>{s.invalidateQueries({queryKey:["brokerage-help-requests"]})}})}function XTn(){const s=Bt(),{user:t}=hs();return mt({mutationFn:async({request_id:n,note:r})=>{if(!t)throw new Error("Not signed in");const{data:a,error:i}=await q.from("brokerage_help_claims").insert({request_id:n,claimant_user_id:t.id,note:r}).select().single();if(i)throw i;return a},onSuccess:(n,r)=>{s.invalidateQueries({queryKey:["brokerage-help-claims",r.request_id]}),s.invalidateQueries({queryKey:["brokerage-help-requests"]})}})}function QTn(){const s=Bt();return mt({mutationFn:async({claim_id:t,request_id:n,claimant_user_id:r})=>{const{error:a}=await q.from("brokerage_help_claims").update({status:"accepted",responded_at:new Date().toISOString()}).eq("id",t);if(a)throw a;const{error:i}=await q.from("brokerage_help_requests").update({status:"filled",assigned_user_id:r}).eq("id",n);if(i)throw i;try{await q.functions.invoke("brokerage-help-claim-decision",{body:{claim_id:t}})}catch(l){console.warn("claim decision notify failed:",l)}},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["brokerage-help-claims",n.request_id]}),s.invalidateQueries({queryKey:["brokerage-help-request",n.request_id]}),s.invalidateQueries({queryKey:["brokerage-help-requests"]})}})}function JTn(){const s=Bt();return mt({mutationFn:async({claim_id:t})=>{const{error:n}=await q.from("brokerage_help_claims").update({status:"declined",responded_at:new Date().toISOString()}).eq("id",t);if(n)throw n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["brokerage-help-claims",n.request_id]})}})}function e6n(){const s=Bt();return mt({mutationFn:async t=>{const{error:n}=await q.from("brokerage_help_requests").update({status:"cancelled"}).eq("id",t);if(n)throw n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["brokerage-help-requests"]}),s.invalidateQueries({queryKey:["brokerage-help-request",n]})}})}function t6n(){const s=Bt();return mt({mutationFn:async t=>{const{error:n}=await q.from("brokerage_help_requests").update({status:"completed"}).eq("id",t);if(n)throw n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["brokerage-help-requests"]}),s.invalidateQueries({queryKey:["brokerage-help-request",n]})}})}function s6n(){const{user:s,brokerageId:t}=hs(),n=Bt(),r=at({queryKey:["brokerage-help-prefs",s==null?void 0:s.id,t],queryFn:async()=>{if(!s||!t)return null;const{data:i,error:l}=await q.from("brokerage_help_notification_prefs").select("*").eq("user_id",s.id).eq("brokerage_id",t).maybeSingle();if(l)throw l;return i},enabled:!!s&&!!t}),a=mt({mutationFn:async i=>{if(!s||!t)throw new Error("No user/brokerage");const{error:l}=await q.from("brokerage_help_notification_prefs").upsert({user_id:s.id,brokerage_id:t,email_enabled:i},{onConflict:"user_id,brokerage_id"});if(l)throw l},onSuccess:()=>{n.invalidateQueries({queryKey:["brokerage-help-prefs"]})}});return{...r,setEmailEnabled:a.mutate,isSaving:a.isPending}}function n6n(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 r6n(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 a6n({req:s,onClick:t}){var i;const n=PTe[s.request_type],r=n6n(s.event_start_at,s.event_end_at),a=[s.address,s.city,s.state].filter(Boolean).join(", ");return e.jsx(ve,{className:"cursor-pointer hover:shadow-md transition group",onClick:t,children:e.jsxs(Me,{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(Oe,{variant:"secondary",className:"text-xs",children:[n.emoji," ",n.label]}),s.status!=="open"&&e.jsx(Oe,{variant:"outline",className:"text-xs capitalize",children:s.status})]}),e.jsx(xi,{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(Gr,{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(Xa,{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(yd,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{children:r6n(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 i6n(){var c;const s=Fn(),{brokerageId:t}=hs(),[n,r]=_.useState("open"),{data:a=[],isLoading:i}=WTn(n),l=s6n(),o=((c=l.data)==null?void 0:c.email_enabled)??!0;return t?e.jsx(zs,{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(Yr,{value:n,onValueChange:d=>r(d),children:e.jsxs(Zr,{children:[e.jsx(Ht,{value:"open",children:"Open"}),e.jsx(Ht,{value:"mine",children:"My Posts"}),e.jsx(Ht,{value:"my_claims",children:"My Claims"}),e.jsx(Ht,{value:"filled",children:"Filled"})]})}),e.jsxs(B,{onClick:()=>s("/brokerage/help-board/new"),className:"gap-2",children:[e.jsx(rn,{className:"h-4 w-4"})," Post Request"]})]}),e.jsx(ve,{className:"bg-muted/30 border-dashed",children:e.jsxs(Me,{className:"flex items-center justify-between py-3 px-5",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[o?e.jsx(Rg,{className:"h-4 w-4 text-primary"}):e.jsx(cS,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx(J,{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(fn,{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(ve,{className:"bg-muted/30 border-dashed",children:e.jsxs(Me,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(x4,{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(a6n,{req:d,onClick:()=>s(`/brokerage/help-board/${d.id}`)},d.id))})]})}):e.jsx(zs,{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(x4,{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 o6n(){const s=Fn(),{toast:t}=vi(),n=ZTn(),[r,a]=_.useState("open_house"),[i,l]=_.useState(""),[o,c]=_.useState(""),[d,u]=_.useState(""),[h,m]=_.useState(""),[p,f]=_.useState(""),[y,v]=_.useState(""),[g,b]=_.useState(""),[j,S]=_.useState(""),[C,E]=_.useState(""),[P,M]=_.useState(""),[I,D]=_.useState("goodwill"),[O,V]=_.useState(""),[G,$]=_.useState(""),H=r==="open_house"||r==="showing_coverage",Y=r!=="general",Z=(ce,ie)=>!ce||!ie?null:`${ce}T${ie}:00`,ne=async ce=>{if(ce.preventDefault(),!i.trim()){t({title:"Add a title",description:"Tell teammates what you need help with.",variant:"destructive"});return}try{const ie=Z(d,h),te=Z(d,p);await n.mutateAsync({request_type:r,title:i.trim(),description:o.trim()||null,event_start_at:ie,event_end_at:te,address:H&&y.trim()||null,city:H&&g.trim()||null,state:H&&j.trim()||null,zip:H&&C.trim()||null,mls_number:P.trim()||null,compensation_type:I,compensation_amount:O?Number(O):null,compensation_notes:G.trim()||null}),t({title:"Posted!",description:"Your teammates have been notified."}),s("/brokerage/help-board")}catch(ie){t({title:"Could not post",description:(ie==null?void 0:ie.message)??"Something went wrong.",variant:"destructive"})}};return e.jsx(zs,{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(B,{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:ne,children:e.jsx(ve,{children:e.jsxs(Me,{className:"p-6 space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"What do you need help with?"}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:Object.keys(PTe).map(ce=>{const ie=PTe[ce],te=ce===r;return e.jsxs("button",{type:"button",onClick:()=>a(ce),className:`text-left p-3 rounded-lg border-2 transition ${te?"border-primary bg-primary/5":"border-border hover:border-primary/40"}`,children:[e.jsx("div",{className:"text-lg",children:ie.emoji}),e.jsx("div",{className:"font-medium text-sm mt-1",children:ie.label}),e.jsx("div",{className:"text-xs text-muted-foreground line-clamp-1",children:ie.description})]},ce)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"title",children:"Title *"}),e.jsx(xe,{id:"title",value:i,onChange:ce=>l(ce.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(J,{htmlFor:"description",children:"Details"}),e.jsx(Ms,{id:"description",value:o,onChange:ce=>c(ce.target.value),placeholder:"Any context — lockbox code instructions later, what to expect, etc.",rows:3,maxLength:1e3})]}),Y&&e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"date",children:"Date"}),e.jsx(xe,{id:"date",type:"date",value:d,onChange:ce=>u(ce.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"start",children:"Start"}),e.jsx(xe,{id:"start",type:"time",value:h,onChange:ce=>m(ce.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"end",children:"End"}),e.jsx(xe,{id:"end",type:"time",value:p,onChange:ce=>f(ce.target.value)})]})]}),H&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"address",children:"Address"}),e.jsx(xe,{id:"address",value:y,onChange:ce=>v(ce.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(J,{htmlFor:"city",children:"City"}),e.jsx(xe,{id:"city",value:g,onChange:ce=>b(ce.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"state",children:"State"}),e.jsx(xe,{id:"state",value:j,onChange:ce=>S(ce.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(J,{htmlFor:"zip",children:"Zip"}),e.jsx(xe,{id:"zip",value:C,onChange:ce=>E(ce.target.value),maxLength:10})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"mls",children:"MLS # (optional)"}),e.jsx(xe,{id:"mls",value:P,onChange:ce=>M(ce.target.value)})]})]})]}),e.jsxs("div",{className:"space-y-3 pt-2 border-t",children:[e.jsx(J,{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(ce=>{const ie=I===ce.val;return e.jsxs("button",{type:"button",onClick:()=>D(ce.val),className:`text-left p-3 rounded-lg border-2 transition ${ie?"border-primary bg-primary/5":"border-border hover:border-primary/40"}`,children:[e.jsx("div",{className:"font-medium text-sm",children:ce.label}),e.jsx("div",{className:"text-xs text-muted-foreground",children:ce.sub})]},ce.val)})}),I!=="goodwill"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"amount",children:I==="flat_fee"?"Amount ($)":"Percent (%)"}),e.jsx(xe,{id:"amount",type:"number",min:"0",step:I==="referral_percent"?"1":"5",value:O,onChange:ce=>V(ce.target.value),placeholder:I==="flat_fee"?"100":"25"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"comp-notes",children:"Compensation notes"}),e.jsx(xe,{id:"comp-notes",value:G,onChange:ce=>$(ce.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(B,{type:"button",variant:"ghost",onClick:()=>s("/brokerage/help-board"),children:"Cancel"}),e.jsxs(B,{type:"submit",disabled:n.isPending,className:"gap-2",children:[n.isPending&&e.jsx(Ct,{className:"h-4 w-4 animate-spin"}),"Post & Notify Brokerage"]})]})]})})})]})})}function l6n(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 B9e(s){return s?s.split(" ").map(t=>t[0]).slice(0,2).join("").toUpperCase():"?"}function c6n(){var P,M,I,D,O,V,G,$;const{id:s}=Li(),t=Fn(),{user:n}=hs(),{toast:r}=vi(),{data:a,isLoading:i}=KTn(s),{data:l=[]}=YTn(s),o=XTn(),c=QTn(),d=JTn(),u=e6n(),h=t6n(),[m,p]=_.useState("");if(i)return e.jsx(zs,{title:"Loading...",description:"",children:e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsx(Ct,{className:"h-8 w-8 animate-spin text-primary"})})});if(!a)return e.jsxs(zs,{title:"Not Found",description:"",children:[e.jsxs(B,{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 f=PTe[a.request_type],y=l6n(a.event_start_at,a.event_end_at),v=[a.address,a.city,a.state,a.zip].filter(Boolean).join(", "),g=(n==null?void 0:n.id)===a.requester_user_id,b=l.find(H=>H.claimant_user_id===(n==null?void 0:n.id)),j=l.find(H=>H.status==="accepted"),S=a.status==="open",C=a.compensation_type==="flat_fee"?a.compensation_amount?`$${Number(a.compensation_amount).toFixed(0)} flat fee`:"Flat fee":a.compensation_type==="referral_percent"?a.compensation_amount?`${a.compensation_amount}% referral`:"Referral percentage":"Goodwill (paying it forward)",E=async()=>{if(!m.trim()){r({title:"Add a quick note",description:"Let the requester know you're available."});return}try{await o.mutateAsync({request_id:a.id,note:m.trim()}),r({title:"You're in!",description:"The requester will review and pick someone."}),p("")}catch(H){r({title:"Could not submit",description:H==null?void 0:H.message,variant:"destructive"})}};return e.jsx(zs,{title:a.title,description:`${f.emoji} ${f.label}`,children:e.jsxs("div",{className:"max-w-3xl mx-auto space-y-4",children:[e.jsxs(B,{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(ve,{children:e.jsxs(Me,{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(Oe,{variant:"secondary",children:[f.emoji," ",f.label]}),e.jsx(Oe,{variant:S?"default":"outline",className:"capitalize",children:a.status})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsxs(ja,{className:"h-7 w-7",children:[e.jsx(pi,{src:((P=a.requester)==null?void 0:P.avatar_url)||void 0}),e.jsx(Na,{children:B9e((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:[y&&e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(Gr,{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:y})]})]}),v&&e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(Xa,{className:"h-4 w-4 text-primary mt-0.5"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Where"}),e.jsx("div",{children:v})]})]}),e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(yd,{className:"h-4 w-4 text-primary mt-0.5"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Compensation"}),e.jsx("div",{children:C})]})]}),a.mls_number&&e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(ZM,{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]})]})}),!g&&S&&!b&&e.jsx(ve,{children:e.jsxs(Me,{className:"p-6 space-y-3",children:[e.jsx("h3",{className:"font-semibold",children:"Offer to cover this"}),e.jsx(Ms,{placeholder:"Quick note — e.g. 'I'm 10 min away and free that day'",value:m,onChange:H=>p(H.target.value),rows:3,maxLength:400}),e.jsxs(B,{onClick:E,disabled:o.isPending,className:"gap-2",children:[o.isPending&&e.jsx(Ct,{className:"h-4 w-4 animate-spin"}),"I can cover this"]})]})}),!g&&b&&e.jsx(ve,{className:"border-primary/30 bg-primary/5",children:e.jsxs(Me,{className:"p-4 flex items-center gap-3",children:[e.jsx(ea,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{className:"text-sm",children:[e.jsxs("div",{className:"font-medium capitalize",children:["Your offer: ",b.status]}),e.jsxs("div",{className:"text-muted-foreground",children:[b.status==="pending"&&"Waiting for the requester to pick.",b.status==="accepted"&&"You're confirmed — see contact info below.",b.status==="declined"&&"They went with someone else this time."]})]})]})}),j&&(g||j.claimant_user_id===(n==null?void 0:n.id))&&e.jsx(ve,{className:"border-primary/30",children:e.jsxs(Me,{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(ja,{className:"h-10 w-10",children:[e.jsx(pi,{src:((D=j.claimant)==null?void 0:D.avatar_url)||void 0}),e.jsx(Na,{children:B9e((O=j.claimant)==null?void 0:O.name)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:(V=j.claimant)==null?void 0:V.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:[((G=j.claimant)==null?void 0:G.email)&&e.jsxs("a",{href:`mailto:${j.claimant.email}`,className:"flex items-center gap-2 text-primary hover:underline",children:[e.jsx(ln,{className:"h-4 w-4"})," ",j.claimant.email]}),(($=j.claimant)==null?void 0:$.phone)&&e.jsxs("a",{href:`tel:${j.claimant.phone}`,className:"flex items-center gap-2 text-primary hover:underline",children:[e.jsx(_a,{className:"h-4 w-4"})," ",j.claimant.phone]})]})]})}),g&&e.jsx(ve,{children:e.jsxs(Me,{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(H=>{var Y,Z,ne,ce,ie;return e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg border",children:[e.jsxs(ja,{className:"h-10 w-10",children:[e.jsx(pi,{src:((Y=H.claimant)==null?void 0:Y.avatar_url)||void 0}),e.jsx(Na,{children:B9e((Z=H.claimant)==null?void 0:Z.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:((ne=H.claimant)==null?void 0:ne.name)||"Teammate"}),e.jsx(Oe,{variant:"outline",className:"capitalize text-xs",children:H.status})]}),H.note&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:['"',H.note,'"']}),H.status==="pending"&&S&&e.jsxs("div",{className:"flex gap-2 mt-2",children:[e.jsxs(B,{size:"sm",onClick:()=>c.mutate({claim_id:H.id,request_id:a.id,claimant_user_id:H.claimant_user_id}),disabled:c.isPending,className:"gap-1",children:[e.jsx(ea,{className:"h-3.5 w-3.5"})," Pick ",((ie=(ce=H.claimant)==null?void 0:ce.name)==null?void 0:ie.split(" ")[0])||"them"]}),e.jsxs(B,{size:"sm",variant:"ghost",onClick:()=>d.mutate({claim_id:H.id,request_id:a.id}),disabled:d.isPending,className:"gap-1",children:[e.jsx(Qn,{className:"h-3.5 w-3.5"})," Pass"]})]})]})]},H.id)}),g&&S&&e.jsx("div",{className:"pt-3 border-t flex justify-end",children:e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>u.mutate(a.id),disabled:u.isPending,children:"Cancel request"})}),g&&a.status==="filled"&&e.jsx("div",{className:"pt-3 border-t flex justify-end",children:e.jsx(B,{size:"sm",onClick:()=>h.mutate(a.id),disabled:h.isPending,children:"Mark complete"})})]})})]})})}function TKt({onSelect:s,maxHeight:t="460px"}){const[n,r]=_.useState(""),[a,i]=_.useState("all"),{data:l=[],isLoading:o}=at({queryKey:["newsletter-graphics-picker"],queryFn:async()=>{const{data:u,error:h}=await q.from("newsletter_graphics").select("*").eq("is_active",!0).order("is_featured",{ascending:!1}).order("sort_order",{ascending:!0}).order("created_at",{ascending:!1});if(h)throw h;return u||[]}}),c=_.useMemo(()=>{const u=new Set;return l.forEach(h=>u.add(h.category||"general")),["all",...Array.from(u).sort()]},[l]),d=_.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(Lr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(xe,{value:n,onChange:u=>r(u.target.value),placeholder:"Search graphics...",className:"pl-8 h-9"})]}),c.length>1&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:c.map(u=>e.jsx("button",{onClick:()=>i(u),className:`px-2.5 py-1 rounded-full text-xs font-medium transition-colors ${a===u?"bg-primary text-primary-foreground":"bg-muted hover:bg-muted/70 text-muted-foreground"}`,children:u==="all"?"All":u},u))}),e.jsx(Ji,{style:{maxHeight:t},className:"rounded-md border",children:o?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Ct,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):d.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(hc,{className:"h-8 w-8 text-muted-foreground/50 mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:l.length===0?"No graphics available yet":"No graphics match your search"})]}):e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2 p-2",children:d.map(u=>e.jsxs("button",{onClick:()=>s(u),className:"group relative rounded-md overflow-hidden border bg-muted/30 hover:ring-2 hover:ring-primary hover:border-primary transition-all text-left",title:u.title,children:[e.jsx("div",{className:"aspect-video bg-muted overflow-hidden",children:e.jsx("img",{src:u.thumbnail_url||u.image_url,alt:u.title,loading:"lazy",className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-200"})}),u.is_featured&&e.jsxs(Oe,{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(Da,{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 d6n=[{key:"search",label:"Search for Properties",icon:Lr,defaultText:"Search for Properties",placeholder:"https://your-website.com/search",helper:"Link to your home search page"},{key:"call",label:"Call Agent",icon:_a,defaultText:"Call Me",hrefPrefix:"tel:",placeholder:"+15555551234",helper:"Your phone number"},{key:"email",label:"Email Agent",icon:ln,defaultText:"Email Me",hrefPrefix:"mailto:",placeholder:"you@email.com",helper:"Your email address"},{key:"schedule",label:"Schedule a Call",icon:ga,defaultText:"Schedule a Call",placeholder:"https://calendly.com/you",helper:"Link to your booking page"},{key:"listings",label:"View My Listings",icon:Jr,defaultText:"View My Listings",placeholder:"https://your-website.com/listings",helper:"Link to your listings page"},{key:"valuation",label:"Get Home Value",icon:yd,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:Xa,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:bd,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:$h,defaultText:"Learn More",placeholder:"https://...",helper:"Any link you want"}];function tjt(s){const t=s.match(/(?:youtube\.com\/(?:watch\?v=|embed\/|v\/)|youtu\.be\/)([A-Za-z0-9_-]{11})/);return t?t[1]:null}function u6n(s){const t=s.match(/vimeo\.com\/(?:video\/)?(\d+)/);return t?t[1]:null}function ent({html:s,onChange:t}){const{user:n}=hs(),r=_.useRef(null),a=_.useRef(""),i=_.useRef(t);i.current=t;const[l,o]=_.useState("desktop"),c=_.useRef(null),[d,u]=_.useState(!1),[h,m]=_.useState(""),[p,f]=_.useState(""),y=_.useRef(null),v=()=>{var vt;const wt=(vt=r.current)==null?void 0:vt.contentDocument,Ts=wt==null?void 0:wt.getSelection();Ts&&Ts.rangeCount>0&&(wt!=null&&wt.body.contains(Ts.anchorNode))&&(y.current=Ts.getRangeAt(0).cloneRange())},g=()=>{var jn;const wt=c.current,Ts=(jn=r.current)==null?void 0:jn.contentDocument;if(!wt||!Ts)return;let vt=h.trim();vt&&!/^(https?:|mailto:|tel:|#|\/)/i.test(vt)&&(vt="https://"+vt),wt.setAttribute("href",vt),wt.setAttribute("target","_blank");const $s=p.trim();$s&&$s!==(wt.textContent||"").trim()&&(wt.textContent=$s);const As=` `+Ts.documentElement.outerHTML;a.current=As,i.current(As),u(!1)};_.useEffect(()=>{var vt,$s;const wt=r.current;if(!wt||a.current===s)return;const Ts=()=>{const As=wt.contentDocument;if(!As)return;As.open(),As.write(s||""),As.close(),a.current=s;const jn=As.body;if(!jn)return;jn.setAttribute("contenteditable","true"),jn.style.outline="none",jn.style.minHeight="400px",jn.style.cursor="text";const ar=()=>{const Ur=` `+As.documentElement.outerHTML;a.current=Ur,i.current(Ur)};jn.addEventListener("input",ar),jn.addEventListener("blur",ar),jn.addEventListener("mouseup",v),jn.addEventListener("keyup",v),As.addEventListener("selectionchange",v);const Dn=Ur=>{var on;const Vs=Ur.target,hn=Vs==null?void 0:Vs.closest("a");if(hn){if(Ur.metaKey||Ur.ctrlKey||Ur.shiftKey)return;Ur.preventDefault(),Ur.stopPropagation(),c.current=hn,m(hn.getAttribute("href")||""),f((hn.textContent||"").trim()),u(!0);return}const dr=As.getSelection();if(!dr)return;const Cn=(on=As.caretRangeFromPoint)==null?void 0:on.call(As,Ur.clientX,Ur.clientY),Yn=Cn==null?void 0:Cn.startContainer;if(Yn&&Yn.nodeType===Node.TEXT_NODE){const Ir=Yn.textContent||"",Wn=Cn.startOffset,Js=Ir.lastIndexOf("[",Wn),Fa=Ir.indexOf("]",Wn);if(Js!==-1&&Fa!==-1&&Fa>Js){const ks=As.createRange();ks.setStart(Yn,Js),ks.setEnd(Yn,Fa+1),dr.removeAllRanges(),dr.addRange(ks),y.current=ks.cloneRange()}}};jn.addEventListener("click",Dn,!0)};((vt=wt.contentDocument)==null?void 0:vt.readyState)==="complete"||($s=wt.contentDocument)!=null&&$s.body?Ts():wt.addEventListener("load",Ts,{once:!0})},[s]);const b=(wt,Ts)=>{var As;const vt=(As=r.current)==null?void 0:As.contentDocument;if(!vt)return;vt.body.focus(),vt.execCommand(wt,!1,Ts);const $s=` `+vt.documentElement.outerHTML;a.current=$s,i.current($s)},j=()=>{const wt=window.prompt("Enter URL (https://...)");wt&&b("createLink",wt)},S=(wt,Ts)=>{var As;const vt=(As=r.current)==null?void 0:As.contentDocument;if(!vt)return;if(vt.body.focus(),Ts==="cursor"&&y.current&&vt.body.contains(y.current.startContainer)){const jn=vt.getSelection();if(jn){jn.removeAllRanges(),jn.addRange(y.current),vt.execCommand("insertHTML",!1,wt);const ar=` `+vt.documentElement.outerHTML;a.current=ar,i.current(ar);return}}Ts==="top"?vt.body.insertAdjacentHTML("afterbegin",wt):vt.body.insertAdjacentHTML("beforeend",wt);const $s=` `+vt.documentElement.outerHTML;a.current=$s,i.current($s)},[C,E]=_.useState(!1),[P,M]=_.useState(null),[I,D]=_.useState(""),[O,V]=_.useState(""),[G,$]=_.useState("#406E71"),[H,Y]=_.useState("cursor"),Z=wt=>{M(wt),D(wt.defaultText),V(""),E(!0)},ne=()=>{if(!P)return;const wt=O.trim();if(!P.isForward&&!wt)return;let Ts=wt;if(P.isForward){const jn=wt||"",ar=encodeURIComponent("You should see this newsletter"),Dn=encodeURIComponent(jn?`I thought you'd like this — take a look: ${jn} `:`I thought you'd like this newsletter — take a look! `);Ts=`mailto:?subject=${ar}&body=${Dn}`}else P.hrefPrefix==="tel:"?Ts="tel:"+wt.replace(/[^0-9+]/g,""):P.hrefPrefix==="mailto:"?Ts="mailto:"+wt:/^https?:\/\//i.test(wt)||(Ts="https://"+wt);const vt=(I||P.defaultText).replace(/[<>]/g,""),$s=G||"#406E71",As=`
${vt}

 

`;S(As,H),E(!1)},[ce,ie]=_.useState(!1),[te,ae]=_.useState(""),[le,be]=_.useState(""),[me,he]=_.useState(""),[pe,Ce]=_.useState("cursor"),Ae=(()=>{if(le.trim())return le.trim();const wt=tjt(te);return wt?`https://i.ytimg.com/vi/${wt}/hqdefault.jpg`:""})(),Pe=()=>{ae(""),be(""),he(""),ie(!0)},ze=()=>{const wt=te.trim();if(!wt)return;let Ts=wt;/^https?:\/\//i.test(Ts)||(Ts="https://"+Ts);const vt=tjt(Ts),$s=vt?null:u6n(Ts);let As=le.trim();!As&&vt&&(As=`https://i.ytimg.com/vi/${vt}/hqdefault.jpg`),!As&&$s&&(As=`https://vumbnail.com/${$s}.jpg`),As||(As="https://placehold.co/600x340/406E71/ffffff?text=Watch+Video");const jn=(me||"Watch the video").replace(/[<>]/g,""),ar=`
${jn}
▶ ${jn}

 

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

 

`.trim();S(vt,Qe),Ze(!1)},{data:qt,isLoading:Vt}=at({queryKey:["newsletter-editor-videos",n==null?void 0:n.id],enabled:!!(n!=null&&n.id)&&ce,queryFn:async()=>{const{data:wt,error:Ts}=await q.from("agent_videos").select("id, title, thumbnail_url, share_token, duration_seconds, created_at").eq("owner_user_id",n.id).eq("is_deleted",!1).eq("status","ready").not("share_token","is",null).order("created_at",{ascending:!1}).limit(50);if(Ts)throw Ts;return wt||[]}}),Xt=wt=>{wt.share_token&&(ae(`https://video.relevelup.com/share/video/${wt.share_token}`),be(`https://video.relevelup.com/thumb/${wt.share_token}`),he(wt.title||"Watch the video"))},fs=l==="mobile"?390:"100%",Ft=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(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>b("bold"),title:"Bold",children:e.jsx(BA,{className:"h-3.5 w-3.5"})}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>b("italic"),title:"Italic",children:e.jsx($A,{className:"h-3.5 w-3.5"})}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>b("underline"),title:"Underline",children:e.jsx(u7,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"w-px h-5 bg-border mx-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>b("insertUnorderedList"),title:"Bullet list",children:e.jsx(A0,{className:"h-3.5 w-3.5"})}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>b("insertOrderedList"),title:"Numbered list",children:e.jsx(xj,{className:"h-3.5 w-3.5"})}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:j,title:"Insert link",children:e.jsx(Vc,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"w-px h-5 bg-border mx-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>b("undo"),title:"Undo",children:e.jsx(JA,{className:"h-3.5 w-3.5"})}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>b("redo"),title:"Redo",children:e.jsx(XA,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"w-px h-5 bg-border mx-1"}),e.jsxs(tu,{children:[e.jsx(su,{asChild:!0,children:e.jsxs(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 gap-1.5",title:"Insert CTA Button",children:[e.jsx($h,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-xs font-medium",children:"CTA Button"})]})}),e.jsxs(Od,{align:"start",className:"w-56 bg-popover z-50",children:[e.jsx(PP,{children:"Insert a call-to-action"}),e.jsx(M0,{}),d6n.map(wt=>{const Ts=wt.icon;return e.jsxs(ca,{onClick:()=>Z(wt),children:[e.jsx(Ts,{className:"h-4 w-4 mr-2"}),wt.label]},wt.key)})]})]}),e.jsxs(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 gap-1.5",title:"Insert image",onClick:Ge,children:[e.jsx(hc,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-xs font-medium",children:"Image"})]}),e.jsxs(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 gap-1.5",title:"Insert video block",onClick:Pe,children:[e.jsx(Kr,{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(T$,{type:"single",value:l,onValueChange:wt=>wt&&o(wt),size:"sm",className:"h-7",children:[e.jsx(N7,{value:"desktop",className:"h-7 px-2",title:"Desktop preview",children:e.jsx(hN,{className:"h-3.5 w-3.5"})}),e.jsx(N7,{value:"mobile",className:"h-7 px-2",title:"Mobile preview",children:e.jsx(p1,{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($h,{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:fs,maxWidth:Ft,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(Ls,{open:d,onOpenChange:u,children:e.jsxs(Ps,{className:"sm:max-w-md",children:[e.jsx(Os,{children:e.jsx(Ds,{children:"Edit link"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"link-edit-text",children:"Button / link text"}),e.jsx(xe,{id:"link-edit-text",value:p,onChange:wt=>f(wt.target.value),placeholder:"Click here"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"link-edit-href",children:"Where should this link go?"}),e.jsx(xe,{id:"link-edit-href",value:h,onChange:wt=>m(wt.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(yr,{children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>u(!1),children:"Cancel"}),e.jsx(B,{type:"button",onClick:g,disabled:!h.trim(),children:"Save link"})]})]})}),e.jsx(Ls,{open:C,onOpenChange:E,children:e.jsxs(Ps,{className:"sm:max-w-md",children:[e.jsx(Os,{children:e.jsxs(Ds,{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(J,{htmlFor:"cta-text",children:"Button text"}),e.jsx(xe,{id:"cta-text",value:I,onChange:wt=>D(wt.target.value),placeholder:P==null?void 0:P.defaultText})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"cta-value",children:P==null?void 0:P.helper}),e.jsx(xe,{id:"cta-value",value:O,onChange:wt=>V(wt.target.value),placeholder:P==null?void 0:P.placeholder,autoFocus:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"cta-color",children:"Button color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xe,{id:"cta-color",type:"color",value:G,onChange:wt=>$(wt.target.value),className:"h-9 w-16 p-1 cursor-pointer"}),e.jsx(xe,{value:G,onChange:wt=>$(wt.target.value),className:"flex-1"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Position"}),e.jsxs(k_,{value:H,onValueChange:wt=>Y(wt),className:"flex gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(sm,{value:"cursor",id:"cta-cursor"}),e.jsxs(J,{htmlFor:"cta-cursor",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx($h,{className:"h-3.5 w-3.5"}),"At cursor"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(sm,{value:"top",id:"cta-top"}),e.jsxs(J,{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(sm,{value:"bottom",id:"cta-bottom"}),e.jsxs(J,{htmlFor:"cta-bottom",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(zf,{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:G,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(yr,{children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>E(!1),children:"Cancel"}),e.jsx(B,{type:"button",onClick:ne,disabled:!(P!=null&&P.isForward)&&!O.trim(),children:"Insert Button"})]})]})}),e.jsx(Ls,{open:ce,onOpenChange:ie,children:e.jsxs(Ps,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Ds,{children:"Insert Video Block"})}),e.jsxs(Yr,{defaultValue:"library",className:"space-y-3",children:[e.jsxs(Zr,{className:"grid w-full grid-cols-3",children:[e.jsx(Ht,{value:"library",children:"My Library"}),e.jsx(Ht,{value:"url",children:"From URL"}),e.jsx(Ht,{value:"record",children:"Record New"})]}),e.jsxs(Gt,{value:"library",className:"space-y-3 mt-2",children:[Vt?e.jsxs("div",{className:"text-center py-8 text-sm text-muted-foreground",children:[e.jsx(Ct,{className:"h-5 w-5 animate-spin mx-auto mb-2"}),"Loading your videos..."]}):!qt||qt.length===0?e.jsxs("div",{className:"text-center py-8 text-sm text-muted-foreground border rounded-md",children:[e.jsx(Kr,{className:"h-8 w-8 mx-auto mb-2 opacity-40"}),e.jsx("p",{children:"No videos in your library yet."}),e.jsx("p",{className:"text-xs mt-1",children:'Record one in the "Record New" tab.'})]}):e.jsx("div",{className:"grid grid-cols-2 gap-2 max-h-72 overflow-y-auto pr-1",children:qt.map(wt=>{const Ts=te.includes(wt.share_token||"___"),vt=wt.share_token?`https://video.relevelup.com/thumb/${wt.share_token}`:wt.thumbnail_url||"";return e.jsxs("button",{type:"button",onClick:()=>Xt(wt),className:`group text-left rounded-md border-2 overflow-hidden transition-all ${Ts?"border-primary ring-2 ring-primary/30":"border-transparent hover:border-primary/40"}`,children:[e.jsxs("div",{className:"aspect-video bg-muted relative",children:[vt?e.jsx("img",{src:vt,alt:wt.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(Kr,{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(Jd,{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:wt.title||"Untitled"})})]},wt.id)})}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{htmlFor:"vid-title-lib",className:"text-xs",children:"Caption (optional)"}),e.jsx(xe,{id:"vid-title-lib",value:me,onChange:wt=>he(wt.target.value),placeholder:"Watch the video"})]})]}),e.jsxs(Gt,{value:"url",className:"space-y-3 mt-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{htmlFor:"vid-url",children:"Video URL"}),e.jsx(xe,{id:"vid-url",value:te,onChange:wt=>ae(wt.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(J,{htmlFor:"vid-title",children:"Caption (optional)"}),e.jsx(xe,{id:"vid-title",value:me,onChange:wt=>he(wt.target.value),placeholder:"Watch the video"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{htmlFor:"vid-thumb",children:"Custom thumbnail URL (optional)"}),e.jsx(xe,{id:"vid-thumb",value:le,onChange:wt=>be(wt.target.value),placeholder:"https://... (only if not YouTube/Vimeo)"})]})]}),e.jsx(Gt,{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(Kr,{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(B,{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(J,{children:"Position"}),e.jsxs(k_,{value:pe,onValueChange:wt=>Ce(wt),className:"flex gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(sm,{value:"cursor",id:"vid-cursor"}),e.jsxs(J,{htmlFor:"vid-cursor",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx($h,{className:"h-3.5 w-3.5"}),"At cursor"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(sm,{value:"top",id:"vid-top"}),e.jsxs(J,{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(sm,{value:"bottom",id:"vid-bottom"}),e.jsxs(J,{htmlFor:"vid-bottom",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(zf,{className:"h-3.5 w-3.5"}),"Bottom"]})]})]})]}),Ae&&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:Ae,alt:"thumbnail",className:"w-full rounded-md",style:{maxHeight:180,objectFit:"cover"},onError:wt=>{wt.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(yr,{children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>ie(!1),children:"Cancel"}),e.jsx(B,{type:"button",onClick:ze,disabled:!te.trim(),children:"Insert Video"})]})]})}),e.jsx(Ls,{open:ke,onOpenChange:Ze,children:e.jsxs(Ps,{className:"sm:max-w-md max-h-[90vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Ds,{children:"Insert Image"})}),e.jsxs(Yr,{defaultValue:"library",className:"space-y-3",children:[e.jsxs(Zr,{className:"grid w-full grid-cols-3",children:[e.jsx(Ht,{value:"library",children:"Library"}),e.jsx(Ht,{value:"upload",children:"Upload"}),e.jsx(Ht,{value:"url",children:"From URL"})]}),e.jsx(Gt,{value:"library",className:"mt-2",children:e.jsx(TKt,{maxHeight:"380px",onSelect:wt=>{Fe(wt.image_url),Ne||Ye(wt.title)}})}),e.jsxs(Gt,{value:"upload",className:"space-y-3 mt-2",children:[e.jsx("input",{ref:$e,type:"file",accept:"image/png,image/jpeg,image/webp,image/gif",className:"hidden",onChange:wt=>{var vt;const Ts=(vt=wt.target.files)==null?void 0:vt[0];Ts&&ct(Ts),wt.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(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>Fe(""),children:"Replace"})]})]}):e.jsx("button",{type:"button",onClick:()=>{var wt;return(wt=$e.current)==null?void 0:wt.click()},disabled:Xe,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:Xe?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"h-8 w-8 mx-auto mb-2 animate-spin text-primary"}),e.jsx("p",{className:"text-sm",children:"Uploading..."})]}):e.jsxs(e.Fragment,{children:[e.jsx(Oa,{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(Gt,{value:"url",className:"space-y-3 mt-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{htmlFor:"img-url",children:"Image URL"}),e.jsx(xe,{id:"img-url",value:Se,onChange:wt=>Fe(wt.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:wt=>{wt.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(J,{htmlFor:"img-alt",children:"Alt text (for accessibility)"}),e.jsx(xe,{id:"img-alt",value:Ne,onChange:wt=>Ye(wt.target.value),placeholder:"Describe the image"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Size"}),e.jsxs(k_,{value:Ve,onValueChange:wt=>qe(wt),className:"flex gap-4",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(sm,{value:"full",id:"img-full"}),e.jsx(J,{htmlFor:"img-full",className:"cursor-pointer font-normal",children:"Full width"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(sm,{value:"half",id:"img-half"}),e.jsx(J,{htmlFor:"img-half",className:"cursor-pointer font-normal",children:"Half width"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Position"}),e.jsxs(k_,{value:Qe,onValueChange:wt=>Ue(wt),className:"flex gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(sm,{value:"cursor",id:"img-cursor"}),e.jsxs(J,{htmlFor:"img-cursor",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx($h,{className:"h-3.5 w-3.5"}),"At cursor"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(sm,{value:"top",id:"img-top"}),e.jsxs(J,{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(sm,{value:"bottom",id:"img-bottom"}),e.jsxs(J,{htmlFor:"img-bottom",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(zf,{className:"h-3.5 w-3.5"}),"Bottom"]})]})]})]})]}),e.jsxs(yr,{children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>Ze(!1),children:"Cancel"}),e.jsx(B,{type:"button",onClick:xt,disabled:!Se.trim()||Xe,children:"Insert Image"})]})]})})]})}const sjt="newsletter-content",h6n="inline-images";function m6n(s,t){const n=atob(s),r=new Array(n.length);for(let a=0;a{const{data:M}=await q.from("team_members").select("team_id, role").eq("user_id",a.id).maybeSingle();return M}}),C=(S==null?void 0:S.role)==="team_leader",E=(S==null?void 0:S.team_id)??null;_.useEffect(()=>{s&&(d((n==null?void 0:n.title)??""),h((n==null?void 0:n.description)??""),p((n==null?void 0:n.html_content)??x6n()),y((n==null?void 0:n.is_template)??!1),g((n==null?void 0:n.share_scope)??"private"))},[s,n]);const P=async()=>{if(a){if(!c.trim()){se.error("Please enter a title");return}if(!m.trim()){se.error("Newsletter content is empty");return}j(!0);try{const M=await p6n(m);M!==m&&p(M);const I={user_id:a.id,title:c.trim(),description:u.trim()||null,html_content:M,is_template:f,share_scope:v,shared_team_id:v==="team"?E:null,shared_brokerage_id:v==="brokerage"?o:null};if(v==="team"&&!E){se.error("You must be a team leader to share with a team"),j(!1);return}if(v==="brokerage"&&!l){se.error("Only brokerage managers can share to a brokerage"),j(!1);return}if(v==="global"&&!i){se.error("Only admins can publish global starter templates"),j(!1);return}let D;if(n!=null&&n.id?{error:D}=await q.from("agent_custom_newsletters").update(I).eq("id",n.id):{error:D}=await q.from("agent_custom_newsletters").insert(I),D)throw D;se.success(n!=null&&n.id?"Saved":"Newsletter created"),r==null||r(),t(!1)}catch(M){se.error(M.message||"Failed to save")}finally{j(!1)}}};return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"max-w-6xl h-[92vh] flex flex-col p-0",children:[e.jsx(Os,{className:"px-6 pt-6 pb-3 border-b",children:e.jsx(Ds,{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(J,{htmlFor:"acn-title",children:"Title *"}),e.jsx(xe,{id:"acn-title",value:c,onChange:M=>d(M.target.value),placeholder:"e.g. June Market Update"})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"acn-desc",children:"Description (optional)"}),e.jsx(xe,{id:"acn-desc",value:u,onChange:M=>h(M.target.value),placeholder:"Short summary"})]})]}),e.jsxs("div",{className:"flex items-center gap-3 rounded-lg border bg-muted/30 px-4 py-3",children:[e.jsx(fn,{id:"acn-template",checked:f,onCheckedChange:y}),e.jsx(J,{htmlFor:"acn-template",className:"cursor-pointer",children:"Save as reusable template"}),e.jsx("span",{className:"text-xs text-muted-foreground ml-auto",children:"Templates can be duplicated and reused for future newsletters"})]}),(C||l||i)&&e.jsxs("div",{className:"rounded-lg border p-4 space-y-3",children:[e.jsx(J,{className:"text-sm font-semibold",children:"Sharing"}),e.jsxs(k_,{value:v,onValueChange:M=>g(M),className:"space-y-2",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(sm,{value:"private",id:"s-private",className:"mt-0.5"}),e.jsxs(J,{htmlFor:"s-private",className:"cursor-pointer font-normal",children:[e.jsx("span",{className:"font-medium",children:"Private"}),e.jsx("span",{className:"block text-xs text-muted-foreground",children:"Only you can see this"})]})]}),C&&e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(sm,{value:"team",id:"s-team",className:"mt-0.5"}),e.jsxs(J,{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(sm,{value:"brokerage",id:"s-brokerage",className:"mt-0.5"}),e.jsxs(J,{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(sm,{value:"global",id:"s-global",className:"mt-0.5"}),e.jsxs(J,{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(J,{className:"mb-2 block",children:"Content"}),e.jsx(ent,{html:m,onChange:p})]})]}),e.jsxs(yr,{className:"px-6 py-3 border-t",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),disabled:b,children:"Cancel"}),e.jsxs(B,{onClick:P,disabled:b,children:[b?e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ho,{className:"h-4 w-4 mr-2"}),n!=null&&n.id?"Save Changes":"Create"]})]})]})})}function x6n(){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 tnt=/\[[^\]\[<>]{2,80}\]/g,g6n=/^\[\s*(?:\/?\s*if\b[^\]]*|endif|else|x-apple-[\w-]*|data-[\w-]*|object [^\]]*|cdata[^\]]*)\s*\]$/i;function snt(s){return!g6n.test(s)}function y6n(s){return(s.match(tnt)||[]).filter(snt)}function njt(s){const t=s.toLowerCase();return t.charAt(0).toUpperCase()+t.slice(1)}function v6n(s){const t=[],n=new RegExp(tnt.source,"g");let r;for(;(r=n.exec(s))!==null;)snt(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 · ${njt(h)}`:`Date ${i[l.token]}`:(m=njt(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 b6n({html:s,onChange:t,originalHtml:n}){const r=_.useMemo(()=>v6n(s),[s]),[a,i]=_.useState({}),[l,o]=_.useState([]),c=_.useRef(null);c.current===null&&s&&(c.current=n??s);const d=_.useRef(!1);_.useEffect(()=>{if(d.current){d.current=!1;return}i({}),o([])},[s]);const u=()=>{const g=new RegExp(tnt.source,"g");let b=0;const j=s.replace(g,S=>{if(!snt(S))return S;const C=(a[b]||"").trim();return b+=1,C||S});j!==s&&(o(S=>[...S,{html:s,values:a}]),d.current=!0,i({}),t(j))},h=()=>{const g=l[l.length-1];g&&(o(b=>b.slice(0,-1)),d.current=!0,i(g.values),t(g.html))},m=()=>{const g=c.current;!g||g===s||(o([]),d.current=!0,i({}),t(g))},p=l.length>0,f=!!c.current&&c.current!==s,y=e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(B,{type:"button",size:"sm",variant:"outline",onClick:h,disabled:!p,children:[e.jsx(hJ,{className:"h-3.5 w-3.5 mr-1"}),"Undo last fill"]}),e.jsxs(B,{type:"button",size:"sm",variant:"ghost",onClick:m,disabled:!f,children:[e.jsx(Tx,{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(Er,{className:"h-4 w-4 text-emerald-600 shrink-0"}),e.jsx("span",{className:"text-muted-foreground",children:"All template fields are filled in. Your name, phone, website and brokerage fill in automatically."})]}),(p||f)&&e.jsxs("div",{className:"flex flex-wrap items-center gap-2 pl-6",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Made a typo?"}),y]})]});const v=r.filter(g=>(a[g.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(xl,{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(Oe,{variant:"secondary",className:"shrink-0",children:[v,"/",r.length," ready"]})]}),e.jsx("div",{className:"grid grid-cols-1 gap-4",children:r.map(g=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:g.label}),e.jsx(xe,{value:a[g.index]||"",placeholder:g.hint,className:"h-10 text-sm",onChange:b=>i(j=>({...j,[g.index]:b.target.value})),onKeyDown:b=>{b.key==="Enter"&&(b.preventDefault(),u())}})]},g.index))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(B,{type:"button",size:"sm",onClick:u,children:[e.jsx(Yq,{className:"h-3.5 w-3.5 mr-1"}),"Apply to email"]}),y]}),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 rz(){const s=ha();return at({queryKey:["custom-tags",s],queryFn:async()=>{const{data:t,error:n}=await q.from("contact_custom_tags").select("*").eq("owner_user_id",s).order("name");if(n)throw n;return t},enabled:!!s})}function _6n(s){return at({queryKey:["contact-custom-tags",s],queryFn:async()=>{const{data:t,error:n}=await q.from("contact_custom_tag_assignments").select("*, tag:contact_custom_tags(*)").eq("contact_id",s);if(n)throw n;return t},enabled:!!s})}function nnt(){const s=Bt(),t=ha();return mt({mutationFn:async({name:n,color:r})=>{const{data:a,error:i}=await q.from("contact_custom_tags").insert({owner_user_id:t,name:n.trim(),color:r||"#6366F1"}).select().single();if(i)throw i;return a},onSuccess:()=>{s.invalidateQueries({queryKey:["custom-tags"]})}})}function w6n(){const s=Bt();return mt({mutationFn:async t=>{const{error:n}=await q.from("contact_custom_tags").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["custom-tags"]}),s.invalidateQueries({queryKey:["contact-custom-tags"]}),s.invalidateQueries({queryKey:["all-contact-custom-tags"]})}})}function j6n(){const s=Bt();return mt({mutationFn:async({id:t,name:n,color:r})=>{const a={};n!==void 0&&(a.name=n.trim()),r!==void 0&&(a.color=r);const{error:i}=await q.from("contact_custom_tags").update(a).eq("id",t);if(i)throw i},onSuccess:()=>{s.invalidateQueries({queryKey:["custom-tags"]}),s.invalidateQueries({queryKey:["contact-custom-tags"]}),s.invalidateQueries({queryKey:["all-contact-custom-tags"]})}})}function MKt(){const s=Bt();return mt({mutationFn:async({contactId:t,tagId:n})=>{const{error:r}=await q.from("contact_custom_tag_assignments").insert({contact_id:t,tag_id:n});if(r)throw r},onSuccess:(t,{contactId:n})=>{s.invalidateQueries({queryKey:["contact-custom-tags",n]}),s.invalidateQueries({queryKey:["all-contact-custom-tags"]})}})}function N6n(){const s=Bt();return mt({mutationFn:async({contactId:t,tagId:n})=>{const{error:r}=await q.from("contact_custom_tag_assignments").delete().eq("contact_id",t).eq("tag_id",n);if(r)throw r},onSuccess:(t,{contactId:n})=>{s.invalidateQueries({queryKey:["contact-custom-tags",n]}),s.invalidateQueries({queryKey:["all-contact-custom-tags"]})}})}function Pae(){const s=ha();return at({queryKey:["all-contact-custom-tags",s],queryFn:async()=>{const{data:t,error:n}=await q.from("contact_custom_tag_assignments").select("contact_id, tag_id, tag:contact_custom_tags!inner(id, name, color, owner_user_id)").eq("tag.owner_user_id",s);if(n)throw n;return t},staleTime:5*60*1e3,enabled:!!s})}function rnt(){const{user:s}=hs();return at({queryKey:["contact-smart-lists",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.from("contact_smart_lists").select("*").order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function PKt(){const s=Bt(),{user:t}=hs();return mt({mutationFn:async({name:n,filters:r,sort_by:a})=>{const{data:i,error:l}=await q.from("contact_smart_lists").insert({owner_user_id:t.id,name:n,filters:r,sort_by:a}).select().single();if(l)throw l;return i},onSuccess:()=>{s.invalidateQueries({queryKey:["contact-smart-lists"]}),ia({title:"Smart filter saved"})},onError:n=>{ia({title:"Error saving smart filter",description:n.message,variant:"destructive"})}})}function LKt(){const s=Bt();return mt({mutationFn:async t=>{const{error:n}=await q.from("contact_smart_lists").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["contact-smart-lists"]}),ia({title:"Smart filter deleted"})}})}const rjt=s=>s.replace(/&/g,"&").replace(//g,">").replace(/"/g,""");function ajt(s,t,n,r){const a=t.name||`${t.first_name||""} ${t.last_name||""}`.trim()||"there",i=new Date,l=new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"long",day:"numeric",year:"numeric"}).format(i),o=new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",year:"numeric"}).format(i),c=(n==null?void 0:n.name)||"",d=c.split(/\s+/).filter(Boolean).map(p=>p[0]).join("").slice(0,2).toUpperCase(),u=((n==null?void 0:n.website_url)||"").trim(),h=[n==null?void 0:n.return_address_line1,[n==null?void 0:n.return_address_city,n==null?void 0:n.return_address_state].filter(Boolean).join(", "),n==null?void 0:n.return_address_zip].filter(Boolean).join(" · "),m={first_name:t.first_name||"there",last_name:t.last_name||"",name:a,full_name:a,email:t.email||"",phone:t.phone||"",address:t.address||"",city:t.city||"",state:t.state||"",zip:t.zip||t.zip_code||"",agent_name:c,agent_first_name:c.split(" ")[0]||"",agent_initials:d,agent_email:(n==null?void 0:n.email)||"",agent_phone:(n==null?void 0:n.phone)||"",agent_title:(n==null?void 0:n.title)||"",agent_website:u.replace(/^https?:\/\//i,"").replace(/\/$/,""),agent_website_url:u?/^https?:\/\//i.test(u)?u:`https://${u}`:"#",market_city:(n==null?void 0:n.market_city)||t.city||"",brokerage:r||(n==null?void 0:n.brokerage_name)||"",brokerage_address:h,current_date:l,current_year:o};return s.replace(/\{\{\s*(\w+)\s*\}\}/g,(p,f)=>m[f]??`{{${f}}}`)}function k6n(s,t,n,r){const a=t.trim()?`
${rjt(t).replace(/\n/g,"
")}
`:"",i=n.trim()?`
${rjt(n).replace(/\n/g,"
")}
`:"",l=r?`
${r}
`:"";return`${a} ${s} ${i} ${l}`}function S6n(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 C6n=["free","act now","click here","limited time","urgent","$$$","100% free","guarantee","no obligation","risk-free","winner","cash bonus","make money","earn extra","amazing"];function A6n(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=C6n.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 ant({open:s,onOpenChange:t,newsletterId:n,newsletterTitle:r,htmlCode:a}){const{user:i}=hs();Vg();const{isReady:l,settings:o}=$9(),{data:c}=iae(),[d,u]=_.useState(!1),h=ha(),{data:m}=at({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:Ys}=await q.from("profiles").select("name, email, phone, avatar_url, title, email_signature, use_email_signature, website_url, market_city, brokerage_name, return_address_line1, return_address_city, return_address_state, return_address_zip").eq("id",i.id).maybeSingle();return Ys}}),[p,f]=_.useState("visual"),[y,v]=_.useState("all"),[g,b]=_.useState(""),[j,S]=_.useState(""),[C,E]=_.useState(""),[P,M]=_.useState(""),[I,D]=_.useState(!0),[O,V]=_.useState([]),[G,$]=_.useState(null),[H,Y]=_.useState(new Set),[Z,ne]=_.useState(""),[ce,ie]=_.useState(!1),[te,ae]=_.useState(!1),[le,be]=_.useState(!1),[me,he]=_.useState({sent:0,failed:0,total:0,currentName:""}),[pe,Ce]=_.useState(!0),[Ae,Pe]=_.useState(!1),[ze,ke]=_.useState([]),[Ze,Se]=_.useState(!1),[Fe,Ne]=_.useState(new Set),[Ye,Ve]=_.useState("now"),[qe,Qe]=_.useState(""),{data:Ue=[]}=rz(),{data:Xe=[]}=Pae(),{data:nt=[]}=rnt(),{data:$e=[],isLoading:Ge}=at({queryKey:["newsletter-send-contacts",h],enabled:!!h&&s,queryFn:async()=>{const Ys=[];let Bn=0;const or=1e3;for(;;){const{data:Wt,error:rt}=await q.from("innercircle_contacts").select("id, first_name, last_name, email, phone, address, city, state, zip, zip_code").eq("owner_user_id",h).eq("email_opt_out",!1).not("email","is",null).neq("email","").order("first_name").range(Bn,Bn+or-1);if(rt)throw rt;if(!Wt||Wt.length===0||(Ys.push(...Wt),Wt.length{const{data:Ys}=await q.from("ses_suppressed_emails").select("email");return(Ys||[]).map(Bn=>Bn.email.toLowerCase())}}),{data:xt}=at({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:Ys}=await q.from("profiles").select("brokerage_id").eq("id",i.id).maybeSingle();if(!(Ys!=null&&Ys.brokerage_id))return null;const{data:Bn}=await q.from("brokerages").select("name, city, state").eq("id",Ys.brokerage_id).maybeSingle();return Bn}}),{data:qt}=at({queryKey:["newsletter-active-lead-site",h],enabled:!!h&&s,staleTime:5*60*1e3,queryFn:async()=>{if(!h)return null;const{data:Ys}=await q.from("lead_sites").select("id, subdomain_slug, mls_provider_id, mls_agent_id, mls_agent_key, is_active").eq("agent_id",h).eq("is_active",!0).not("mls_provider_id","is",null).order("created_at",{ascending:!0}).limit(1).maybeSingle();return Ys}}),Vt=!!(qt!=null&&qt.mls_provider_id),Xt=(qt==null?void 0:qt.mls_agent_id)||(qt==null?void 0:qt.mls_agent_key)||null,{data:fs=[],isLoading:Ft}=at({queryKey:["newsletter-agent-listings",h,Xt],enabled:!!h&&!!Xt&&Ze,staleTime:60*1e3,queryFn:async()=>{if(!Xt)return[];const{data:Ys}=await q.from("mlsgrid_listings").select("listing_key, address, city, state, list_price, bedrooms, bathrooms_total, living_area, photos, standard_status, modification_timestamp").eq("list_agent_mls_id",Xt).eq("standard_status","Active").order("modification_timestamp",{ascending:!1}).limit(30);return Ys||[]}}),{data:wt=[],isLoading:Ts}=at({queryKey:["newsletter-exchange-listings",h],enabled:!!h&&Ze,staleTime:60*1e3,queryFn:async()=>{const{data:Ys}=await q.from("listings").select("id, slug, property_address, city, state, price, bedrooms, bathrooms, square_footage, status, created_at").eq("agent_id",h).in("status",["active","coming_soon","office_exclusive","pre_market"]).order("created_at",{ascending:!1}).limit(30),Bn=Ys||[];if(Bn.length===0)return[];const or=Bn.map(jt=>jt.id),{data:Wt}=await q.from("listing_photos").select("listing_id, photo_url, is_primary, sort_order").in("listing_id",or),rt=new Map,pt=new Map;for(const jt of Wt||[])jt.is_primary&&!rt.has(jt.listing_id)&&rt.set(jt.listing_id,jt.photo_url),pt.has(jt.listing_id)||pt.set(jt.listing_id,jt.photo_url);return Bn.map(jt=>({...jt,_photo:rt.get(jt.id)||pt.get(jt.id)||""}))}}),{data:vt=!1}=at({queryKey:["newsletter-exchange-listings-exists",h],enabled:!!h&&s,staleTime:5*60*1e3,queryFn:async()=>{const{count:Ys}=await q.from("listings").select("id",{count:"exact",head:!0}).eq("agent_id",h).in("status",["active","coming_soon","office_exclusive","pre_market"]);return(Ys||0)>0}}),$s=_.useMemo(()=>{const Ys=new Set(ct);return $e.filter(Bn=>Bn.email&&Bn.email.includes("@")&&!Ys.has(Bn.email.toLowerCase()))},[$e,ct]),As=_.useMemo(()=>{if(O.length===0)return null;const Ys=new Set;for(const Bn of Xe)O.includes(Bn.tag_id)&&Ys.add(Bn.contact_id);return Ys},[Xe,O]),jn=_.useMemo(()=>nt.find(Ys=>Ys.id===G)||null,[nt,G]),ar=_.useMemo(()=>{var Ys;if(y==="all")return $s;if(y==="tags")return As?$s.filter(Bn=>As.has(Bn.id)):[];if(y==="smartlists"){if(!jn)return[];const Bn=(((Ys=jn.filters)==null?void 0:Ys.search)||"").toLowerCase().trim();return Bn?$s.filter(or=>`${or.first_name||""} ${or.last_name||""}`.toLowerCase().includes(Bn)||(or.email||"").toLowerCase().includes(Bn)):$s}return $s.filter(Bn=>H.has(Bn.id))},[y,$s,As,jn,H]),Dn=_.useMemo(()=>{if(!Z.trim())return $s;const Ys=Z.toLowerCase();return $s.filter(Bn=>`${Bn.first_name||""} ${Bn.last_name||""}`.toLowerCase().includes(Ys))},[$s,Z]);_.useEffect(()=>{s&&(b(""),S(`Hi {{first_name}}, Sharing this month's update — hope you find something useful!`),E(`As always, reach out anytime if I can help. Talk soon!`),M(a||""),f("light"),v("all"),V([]),$(null),Y(new Set),ne(""),ie(!1),D(!0),Ce(!0),ke([]),Ve("now"),Qe(""),he({sent:0,failed:0,total:0,currentName:""}))},[s,r,a]);const Ur=l,Vs=_.useMemo(()=>y6n(P||a||""),[P,a]),hn=!!(g.trim()&&Ur&&ar.length>0&&!te&&Vs.length===0),dr=Ys=>{const Bn=P||a,or=I&&(m!=null&&m.email_signature)?m.email_signature:null;let Wt;return p==="light"?Wt=k6n(Bn,j,C,or):Wt=or?`${Bn}
${or}
`:Bn,pe&&(Wt+=S6n(m??null,xt??null,Ys.email)),ajt(Wt,Ys,m??null,(xt==null?void 0:xt.name)??null)},Cn=_.useMemo(()=>dr({first_name:"Friend",last_name:"",email:"preview@example.com",phone:"",address:"",city:"",state:"",zip:""}),[p,j,C,P,a,I,m,pe,xt]),Yn=_.useMemo(()=>A6n(g,p==="advanced"||p==="visual"?P:a),[g,p,P,a]),on=async()=>{Pe(!0),ke([]);try{const Ys=p==="advanced"||p==="visual"?P:a,{data:Bn,error:or}=await q.functions.invoke("generate-newsletter-subjects",{body:{newsletterTitle:r,bodyHtml:Ys,currentSubject:g}});if(or)throw or;const Wt=Bn==null?void 0:Bn.subjects;if(!Array.isArray(Wt)||Wt.length===0)throw new Error("No subjects returned");ke(Wt)}catch(Ys){const Bn=(Ys==null?void 0:Ys.message)||"Failed to generate subjects";Bn.includes("credits exhausted")||Bn.includes("402")?se.error("AI credits exhausted. Please add credits to your workspace."):Bn.includes("Rate limit")||Bn.includes("429")?se.error("Rate limit hit — try again in a moment."):se.error(Bn)}finally{Pe(!1)}},Ir=Ys=>Ys?"$"+Number(Ys).toLocaleString("en-US"):"",Wn=()=>{var pt,jt;if(Fe.size===0){se.error("Pick at least one listing first.");return}const Ys=(qt==null?void 0:qt.subdomain_slug)||"",Bn=Ys?`https://${Ys}.relevelup.com`:"https://relevelup.com",or=[];for(const Mt of fs){const es=`mls:${Mt.listing_key}`;if(!Fe.has(es))continue;const ps=Array.isArray(Mt.photos)&&Mt.photos.length>0?typeof Mt.photos[0]=="string"?Mt.photos[0]:((pt=Mt.photos[0])==null?void 0:pt.MediaURL)||((jt=Mt.photos[0])==null?void 0:jt.url)||"":"",Is=Mt.bedrooms?`${Mt.bedrooms} bd`:"",js=Mt.bathrooms_total?`${Mt.bathrooms_total} ba`:"",Kt=Mt.living_area?`${Number(Mt.living_area).toLocaleString()} sqft`:"";or.push({url:`${Bn}/listings/${Mt.listing_key}`,photo:ps,price:Ir(Mt.list_price),addr:`${Mt.address||""}${Mt.city?", "+Mt.city:""}`,stats:[Is,js,Kt].filter(Boolean).join(" • ")})}for(const Mt of wt){const es=`ex:${Mt.id}`;if(!Fe.has(es))continue;const ps=Mt.bedrooms?`${Mt.bedrooms} bd`:"",Is=Mt.bathrooms?`${Mt.bathrooms} ba`:"",js=Mt.square_footage?`${Number(Mt.square_footage).toLocaleString()} sqft`:"";or.push({url:`https://listings.relevelup.com/${Mt.slug||Mt.id}`,photo:Mt._photo||"",price:Ir(Mt.price),addr:`${Mt.property_address||""}${Mt.city?", "+Mt.city:""}`,stats:[ps,Is,js].filter(Boolean).join(" • ")})}const rt=`

Featured Listings

${or.map(Mt=>`
${Mt.photo?`${Mt.addr}`:""}
${Mt.price}
${Mt.addr}
${Mt.stats}
`.trim()).join(` `)}
`.trim();M(Mt=>(Mt||a||"")+` `+rt),f("visual"),Ne(new Set),Se(!1),se.success(`Added ${or.length} listing${or.length===1?"":"s"} to your newsletter.`)},Js=()=>dr({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}}"),Fa=()=>ajt(g,{first_name:"__FN__",last_name:"__LN__",email:"__EM__",name:"__NAME__",phone:"__PHONE__",address:"__ADDR__",city:"__CITY__",state:"__STATE__",zip:"__ZIP__"},m??null,(xt==null?void 0:xt.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}}"),ks=()=>{if(Vs.length>0){se.error(`Fill in ${Vs.length} template field${Vs.length===1?"":"s"} before sending.`);return}if(hn){if(Ye==="later"){if(!qe){se.error("Pick a date and time to schedule.");return}const Ys=new Date(qe).getTime();if(Number.isNaN(Ys)||Ys{if(!(!hn||!i)){be(!1),ae(!0),he({sent:0,failed:0,total:ar.length,currentName:"Preparing campaign…"});try{const Bn=`${((o==null?void 0:o.display_name)||"ReLevelUp").toLowerCase().replace(/[^a-z]/g,".")}@send.relevelup.com`,or=Js(),Wt=Fa(),rt=Ye==="later",{data:pt,error:jt}=await q.from("email_campaigns").insert({user_id:h||i.id,name:`Newsletter: ${r}`,subject:Wt,body_html:or,from_email:Bn,reply_to_email:(o==null?void 0:o.reply_to_email)||null,total_recipients:ar.length,status:rt?"scheduled":"draft",scheduled_at:rt?new Date(qe).toISOString():null}).select("id").single();if(jt)throw jt;he(es=>({...es,currentName:"Adding recipients…"}));const Mt=ar.map(es=>({campaign_id:pt.id,contact_id:es.id,email:es.email,name:[es.first_name,es.last_name].filter(Boolean).join(" ")||null,status:"pending"}));for(let es=0;es({...js,sent:Math.min(es+ps.length,Mt.length)}))}if(rt){const{error:es}=await q.functions.invoke("ses-schedule-campaign",{body:{action:"schedule",campaign_id:pt.id}});if(es)throw es;se.success(`Newsletter scheduled for ${new Date(qe).toLocaleString()}.`)}else{const{error:es}=await q.functions.invoke("ses-send-campaign",{body:{action:"send_campaign",campaign_id:pt.id}});if(es)throw es;se.success(`Sending to ${ar.length} contact${ar.length===1?"":"s"}! Open & click tracking will appear in Sent Emails.`)}t(!1)}catch(Ys){console.error("Newsletter send failed:",Ys),se.error(`Failed to send: ${Ys.message||"Unknown error"}`)}finally{ae(!1)}}},Ws=Ys=>{Y(Bn=>{const or=new Set(Bn);return or.has(Ys)?or.delete(Ys):or.add(Ys),or})};return e.jsxs(Ls,{open:s,onOpenChange:Ys=>!te&&t(Ys),children:[e.jsxs(Ps,{className:"max-w-5xl max-h-[92vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsxs(Ds,{className:"flex items-center gap-2",children:[e.jsx(Or,{className:"h-5 w-5"})," Send Newsletter"]})}),!Ur&&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(B,{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(J,{children:"Subject"}),e.jsxs(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 gap-1 text-xs",onClick:on,disabled:Ae,title:"Generate subject lines with AI",children:[Ae?e.jsx(Ct,{className:"h-3 w-3 animate-spin"}):e.jsx(un,{className:"h-3 w-3"}),"AI Suggestions"]})]}),e.jsx(xe,{value:g,onChange:Ys=>b(Ys.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((Ys,Bn)=>e.jsxs("button",{type:"button",onClick:()=>{b(Ys),ke([])},className:"w-full text-left text-sm px-2 py-1.5 rounded hover:bg-primary/10 transition-colors",children:[e.jsx(un,{className:"h-3 w-3 inline-block mr-1.5 text-primary"}),Ys]},Bn))]}),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}}"})]})]}),Yn.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(s$,{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:Yn.map((Ys,Bn)=>e.jsx("li",{children:Ys},Bn))})]}),(Vt||vt)&&e.jsxs("div",{className:"rounded-lg border border-primary/30 bg-primary/5 p-3 flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"text-xs",children:[e.jsxs("div",{className:"font-medium flex items-center gap-1.5",children:[e.jsx(Jr,{className:"h-3.5 w-3.5 text-primary"}),"Insert your active listings"]}),e.jsx("p",{className:"text-muted-foreground mt-0.5",children:Vt&&vt?"Pick from your live MLS listings or your Listing Exchange listings.":Vt?"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(B,{type:"button",size:"sm",variant:"outline",onClick:()=>Se(!0),children:"Choose listings"})]}),e.jsx(b6n,{html:P||a||"",originalHtml:a||"",onChange:M}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Editing"}),e.jsxs(Yr,{value:p,onValueChange:Ys=>f(Ys),children:[e.jsxs(Zr,{className:"grid grid-cols-3 w-full",children:[e.jsxs(Ht,{value:"visual",children:[e.jsx(Qx,{className:"h-3 w-3 mr-1"}),"Visual"]}),e.jsxs(Ht,{value:"light",children:[e.jsx(Fr,{className:"h-3 w-3 mr-1"}),"Quick edit"]}),e.jsxs(Ht,{value:"advanced",children:[e.jsx(Y3,{className:"h-3 w-3 mr-1"}),"HTML"]})]}),e.jsx(Gt,{value:"visual",className:"mt-3",children:e.jsx(ent,{html:P,onChange:M})}),e.jsxs(Gt,{value:"light",className:"space-y-3 mt-3",children:[e.jsxs("div",{children:[e.jsx(J,{className:"text-xs text-muted-foreground",children:"Personal intro (above newsletter)"}),e.jsx(Ms,{value:j,onChange:Ys=>S(Ys.target.value),rows:4,placeholder:"Hi {{first_name}}, ..."})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs text-muted-foreground",children:"Personal outro (below newsletter)"}),e.jsx(Ms,{value:C,onChange:Ys=>E(Ys.target.value),rows:3,placeholder:"Talk soon!"})]})]}),e.jsxs(Gt,{value:"advanced",className:"mt-3",children:[e.jsx(J,{className:"text-xs text-muted-foreground",children:"Edit full HTML"}),e.jsx(Ms,{value:P,onChange:Ys=>M(Ys.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(fn,{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(fn,{checked:pe,onCheckedChange:Ce})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Recipients"}),e.jsxs(Yr,{value:y,onValueChange:Ys=>v(Ys),children:[e.jsxs(Zr,{className:"grid grid-cols-4 w-full",children:[e.jsxs(Ht,{value:"all",children:[e.jsx(In,{className:"h-3 w-3 mr-1"}),"All"]}),e.jsxs(Ht,{value:"tags",children:[e.jsx(Ep,{className:"h-3 w-3 mr-1"}),"Tags"]}),e.jsxs(Ht,{value:"smartlists",children:[e.jsx(OQ,{className:"h-3 w-3 mr-1"}),"Lists"]}),e.jsxs(Ht,{value:"individual",children:[e.jsx(Fo,{className:"h-3 w-3 mr-1"}),"Pick"]})]}),e.jsx(Gt,{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:$s.length})," contact",$s.length===1?"":"s"," with a valid, non-suppressed email."]})}),e.jsxs(Gt,{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(Ji,{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(Ys=>e.jsxs("label",{className:"flex items-center gap-2 p-1.5 hover:bg-muted rounded cursor-pointer",children:[e.jsx($a,{checked:O.includes(Ys.id),onCheckedChange:Bn=>V(or=>Bn?[...or,Ys.id]:or.filter(Wt=>Wt!==Ys.id))}),e.jsx("span",{className:"inline-block h-2 w-2 rounded-full",style:{background:Ys.color||"#406E71"}}),e.jsx("span",{className:"text-sm",children:Ys.name})]},Ys.id))})]}),e.jsxs(Gt,{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(Ji,{className:"h-40 rounded-lg border p-2",children:nt.length===0?e.jsx("p",{className:"text-xs text-muted-foreground p-2",children:"No smart lists yet. Save one from the contacts page."}):nt.map(Ys=>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:G===Ys.id,onChange:()=>$(Ys.id)}),e.jsx("span",{className:"text-sm",children:Ys.name})]},Ys.id))})]}),e.jsxs(Gt,{value:"individual",className:"mt-3 space-y-2",children:[e.jsx(xe,{placeholder:"Search contacts...",value:Z,onChange:Ys=>ne(Ys.target.value)}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:[H.size," selected"]}),e.jsx("button",{type:"button",className:"underline",onClick:()=>Y(new Set),children:"Clear"})]}),e.jsxs(Ji,{className:"h-48 rounded-lg border p-2",children:[Ge&&e.jsx("p",{className:"text-xs text-muted-foreground p-2",children:"Loading contacts…"}),!Ge&&Dn.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground p-2",children:"No matching contacts."}),Dn.slice(0,200).map(Ys=>e.jsxs("label",{className:"flex items-center gap-2 p-1.5 hover:bg-muted rounded cursor-pointer",children:[e.jsx($a,{checked:H.has(Ys.id),onCheckedChange:()=>Ws(Ys.id)}),e.jsxs("div",{className:"text-sm flex-1 min-w-0",children:[e.jsxs("div",{className:"truncate",children:[Ys.first_name," ",Ys.last_name||""]}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:Ys.email})]})]},Ys.id)),Dn.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(Oe,{variant:"secondary",className:"gap-1",children:[e.jsx(Er,{className:"h-3 w-3"})," ",ar.length," recipient",ar.length===1?"":"s"]}),Ur&&e.jsxs(Oe,{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(J,{children:"Preview"}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>ie(Ys=>!Ys),children:ce?e.jsxs(e.Fragment,{children:[e.jsx(Ax,{className:"h-3 w-3 mr-1"}),"Hide"]}):e.jsxs(e.Fragment,{children:[e.jsx(ya,{className:"h-3 w-3 mr-1"}),"Show"]})})]}),ce?e.jsx("div",{className:"rounded-lg border overflow-hidden bg-white",children:e.jsx("iframe",{title:"newsletter-preview",srcDoc:Cn,className:"w-full h-[560px] bg-white",sandbox:""})}):e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-6 text-center text-sm text-muted-foreground",children:["Click ",e.jsx("strong",{children:"Show"})," to preview how the email looks. Merge tags use sample data (Friend)."]})]})]}),te&&e.jsxs("div",{className:"space-y-2 rounded-lg border p-3 bg-muted/30",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Ct,{className:"h-4 w-4 animate-spin"}),"Sending to ",me.currentName||"..."]}),e.jsxs("span",{className:"text-muted-foreground",children:[me.sent+me.failed," / ",me.total]})]}),e.jsx(Fi,{value:me.total?(me.sent+me.failed)/me.total*100:0}),me.failed>0&&e.jsxs("p",{className:"text-xs text-destructive",children:[me.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(Gr,{className:"h-4 w-4"})," When to send"]}),e.jsxs(k_,{value:Ye,onValueChange:Ys=>Ve(Ys),className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx(sm,{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(sm,{value:"later",id:"send-later"}),e.jsxs("span",{className:"text-sm flex items-center gap-1",children:[e.jsx(Qd,{className:"h-3.5 w-3.5"})," Schedule for later"]})]}),Ye==="later"&&e.jsx(xe,{type:"datetime-local",value:qe,onChange:Ys=>Qe(Ys.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:Vs.length>0?`${Vs.length} template field${Vs.length===1?"":"s"} still need${Vs.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(B,{variant:"outline",onClick:()=>t(!1),disabled:te,children:"Cancel"}),e.jsx(B,{onClick:ks,disabled:!hn,children:te?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"h-4 w-4 mr-1 animate-spin"}),"Working…"]}):Ye==="later"?e.jsxs(e.Fragment,{children:[e.jsx(Qd,{className:"h-4 w-4 mr-1"}),"Schedule for ",ar.length]}):e.jsxs(e.Fragment,{children:[e.jsx(Or,{className:"h-4 w-4 mr-1"}),"Send to ",ar.length]})})]})]})]})]}),e.jsx(Kl,{open:le,onOpenChange:be,children:e.jsxs(Ol,{children:[e.jsxs(zl,{children:[e.jsx(Ul,{children:Ye==="later"?"Schedule newsletter?":"Send newsletter?"}),e.jsxs(ql,{children:[Ye==="later"?"Schedule ":"Send ",e.jsxs("span",{className:"font-medium text-foreground",children:['"',g,'"']})," to"," ",e.jsxs("span",{className:"font-medium text-foreground",children:[ar.length," contact",ar.length===1?"":"s"]}),Ye==="later"&&qe?` for ${new Date(qe).toLocaleString()}`:"","? Suppressed and unsubscribed contacts are skipped automatically."]})]}),e.jsxs(Bl,{children:[e.jsx($l,{children:"Cancel"}),e.jsx(Ml,{onClick:Gs,children:Ye==="later"?e.jsxs(e.Fragment,{children:[e.jsx(Qd,{className:"h-4 w-4 mr-1"}),"Schedule"]}):e.jsxs(e.Fragment,{children:[e.jsx(Or,{className:"h-4 w-4 mr-1"}),"Send to ",ar.length]})})]})]})}),e.jsx(Ls,{open:Ze,onOpenChange:Se,children:e.jsxs(Ps,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsxs(Ds,{className:"flex items-center gap-2",children:[e.jsx(Jr,{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."}),(Ft||Ts)&&e.jsxs("div",{className:"text-sm text-muted-foreground p-6 text-center",children:[e.jsx(Ct,{className:"h-4 w-4 animate-spin inline-block mr-2"}),"Loading your listings…"]}),!Ft&&!Ts&&fs.length===0&&wt.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."}),fs.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:fs.map(Ys=>{var rt,pt;const Bn=`mls:${Ys.listing_key}`,or=Fe.has(Bn),Wt=Array.isArray(Ys.photos)&&Ys.photos.length>0?typeof Ys.photos[0]=="string"?Ys.photos[0]:((rt=Ys.photos[0])==null?void 0:rt.MediaURL)||((pt=Ys.photos[0])==null?void 0:pt.url)||"":"";return e.jsxs("button",{type:"button",onClick:()=>{Ne(jt=>{const Mt=new Set(jt);return Mt.has(Bn)?Mt.delete(Bn):Mt.size<6?Mt.add(Bn):se.error("Max 6 listings per newsletter"),Mt})},className:`relative rounded-lg border-2 overflow-hidden text-left transition-all ${or?"border-primary ring-2 ring-primary/30":"border-border hover:border-primary/50"}`,children:[Wt&&e.jsx("img",{src:Wt,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:Ys.list_price?`$${Number(Ys.list_price).toLocaleString()}`:""}),e.jsx("div",{className:"text-xs truncate",children:Ys.address}),e.jsxs("div",{className:"text-[11px] text-muted-foreground truncate",children:[Ys.city,Ys.state?`, ${Ys.state}`:""]})]}),or&&e.jsx("div",{className:"absolute top-1 right-1 bg-primary text-primary-foreground rounded-full p-0.5",children:e.jsx(Er,{className:"h-4 w-4"})})]},Bn)})})]}),wt.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:wt.map(Ys=>{const Bn=`ex:${Ys.id}`,or=Fe.has(Bn);return e.jsxs("button",{type:"button",onClick:()=>{Ne(Wt=>{const rt=new Set(Wt);return rt.has(Bn)?rt.delete(Bn):rt.size<6?rt.add(Bn):se.error("Max 6 listings per newsletter"),rt})},className:`relative rounded-lg border-2 overflow-hidden text-left transition-all ${or?"border-primary ring-2 ring-primary/30":"border-border hover:border-primary/50"}`,children:[Ys._photo&&e.jsx("img",{src:Ys._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:Ys.price?`$${Number(Ys.price).toLocaleString()}`:""}),e.jsx("div",{className:"text-xs truncate",children:Ys.property_address}),e.jsxs("div",{className:"text-[11px] text-muted-foreground truncate",children:[Ys.city,Ys.state?`, ${Ys.state}`:""]})]}),or&&e.jsx("div",{className:"absolute top-1 right-1 bg-primary text-primary-foreground rounded-full p-0.5",children:e.jsx(Er,{className:"h-4 w-4"})})]},Bn)})})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>Se(!1),children:"Cancel"}),e.jsxs(B,{onClick:Wn,disabled:Fe.size===0,children:["Insert ",Fe.size>0?Fe.size:""," listing",Fe.size===1?"":"s"]})]})]})}),e.jsx(cLe,{open:d,onOpenChange:u,hasPending:!!(c!=null&&c.hasPendingSes),pendingEmails:c==null?void 0:c.pendingEmails})]})}function E6n(){const{user:s}=hs(),t=Bt(),[n,r]=_.useState("starters"),[a,i]=_.useState(!1),[l,o]=_.useState(null),[c,d]=_.useState(null),[u,h]=_.useState(null),{data:m,isLoading:p}=at({queryKey:["agent-custom-newsletters",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),queryFn:async()=>{const{data:P,error:M}=await q.from("agent_custom_newsletters").select("*").order("updated_at",{ascending:!1});if(M)throw M;return P||[]}}),f=()=>t.invalidateQueries({queryKey:["agent-custom-newsletters"]}),y=(m==null?void 0:m.filter(P=>P.user_id===(s==null?void 0:s.id)&&!P.is_template))??[],v=(m==null?void 0:m.filter(P=>P.user_id===(s==null?void 0:s.id)&&P.is_template))??[],g=(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")))??[],b=(m==null?void 0:m.filter(P=>P.share_scope==="global"&&P.is_template))??[],j=n==="starters"?b:n==="mine"?y:n==="templates"?v:g.filter(P=>P.share_scope!=="global"),S=async P=>{if(!s)return;const{error:M}=await q.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){se.error(M.message);return}se.success('Duplicated to "My Newsletters"'),f(),r("mine")},C=async P=>{const{error:M}=await q.from("agent_custom_newsletters").delete().eq("id",P);if(M){se.error(M.message);return}se.success("Deleted"),h(null),f()},E=P=>P.share_scope==="global"?e.jsxs(Oe,{variant:"secondary",className:"gap-1",children:[e.jsx(un,{className:"h-3 w-3"}),"Starter"]}):P.share_scope==="brokerage"?e.jsxs(Oe,{variant:"secondary",className:"gap-1",children:[e.jsx(ai,{className:"h-3 w-3"}),"Brokerage"]}):P.share_scope==="team"?e.jsxs(Oe,{variant:"secondary",className:"gap-1",children:[e.jsx(In,{className:"h-3 w-3"}),"Team"]}):e.jsxs(Oe,{variant:"outline",className:"gap-1 text-muted-foreground",children:[e.jsx(ec,{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(B,{variant:n==="starters"?"default":"outline",size:"sm",onClick:()=>r("starters"),className:"gap-1.5",children:[e.jsx(un,{className:"h-3.5 w-3.5"}),"Starter Templates (",b.length,")"]}),e.jsxs(B,{variant:n==="mine"?"default":"outline",size:"sm",onClick:()=>r("mine"),children:["My Newsletters (",y.length,")"]}),e.jsxs(B,{variant:n==="templates"?"default":"outline",size:"sm",onClick:()=>r("templates"),children:["My Templates (",v.length,")"]}),e.jsxs(B,{variant:n==="shared"?"default":"outline",size:"sm",onClick:()=>r("shared"),children:["Shared with Me (",g.filter(P=>P.share_scope!=="global").length,")"]})]}),e.jsxs(B,{onClick:()=>{o(null),i(!0)},children:[e.jsx(rn,{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(cn,{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(un,{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&&j.length===0&&e.jsx(ve,{children:e.jsxs(Me,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(Fr,{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&&j.length>0&&e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:j.map(P=>{const M=P.user_id===(s==null?void 0:s.id);return e.jsxs(ve,{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(Oe,{className:"bg-primary/90",children:"Template"}),E(P)]})]}),e.jsxs(Me,{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(B,{size:"sm",onClick:()=>d(P),className:"flex-1 min-w-[80px]",children:[e.jsx(Or,{className:"h-3.5 w-3.5 mr-1"})," Send"]}),M?e.jsxs(e.Fragment,{children:[e.jsx(B,{size:"sm",variant:"outline",onClick:()=>{o(P),i(!0)},children:e.jsx(Ya,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"sm",variant:"outline",onClick:()=>S(P),children:e.jsx(Ia,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"sm",variant:"outline",onClick:()=>h(P.id),children:e.jsx(Sn,{className:"h-3.5 w-3.5"})})]}):e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>S(P),children:[e.jsx(Ia,{className:"h-3.5 w-3.5 mr-1"})," Use"]})]})]})]},P.id)})}),e.jsx(f6n,{open:a,onOpenChange:i,initial:l,onSaved:f}),c&&e.jsx(ant,{open:!!c,onOpenChange:P=>!P&&d(null),newsletterId:c.id,newsletterTitle:c.title,htmlCode:c.html_content}),e.jsx(Kl,{open:!!u,onOpenChange:P=>!P&&h(null),children:e.jsxs(Ol,{children:[e.jsxs(zl,{children:[e.jsx(Ul,{children:"Delete this newsletter?"}),e.jsx(ql,{children:"This cannot be undone."})]}),e.jsxs(Bl,{children:[e.jsx($l,{children:"Cancel"}),e.jsx(Ml,{onClick:()=>u&&C(u),children:"Delete"})]})]})})]})}function T6n(){const s=Fn(),[t,n]=_.useState(""),[r,a]=_.useState("grid"),[i,l]=_.useState(null),{data:o,isLoading:c}=at({queryKey:["newsletters"],queryFn:async()=>{const{data:C,error:E}=await q.from("newsletter_content").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(E)throw E;return C}}),{data:d}=at({queryKey:["newsletter-likes-all"],queryFn:async()=>{const{data:C}=await q.from("newsletter_likes").select("newsletter_id");return C||[]}}),{data:u}=at({queryKey:["newsletter-comments-all"],queryFn:async()=>{const{data:C}=await q.from("newsletter_comments").select("newsletter_id");return C||[]}}),{data:h}=at({queryKey:["newsletter-resource-counts"],queryFn:async()=>{const[C,E,P,M]=await Promise.all([q.from("newsletter_canva_links").select("newsletter_id"),q.from("newsletter_pdfs").select("newsletter_id"),q.from("newsletter_videos").select("newsletter_id"),q.from("newsletter_drive_links").select("newsletter_id")]);return{canva:C.data||[],pdfs:E.data||[],videos:P.data||[],drives:M.data||[]}}}),m=C=>(d==null?void 0:d.filter(E=>E.newsletter_id===C).length)||0,p=C=>(u==null?void 0:u.filter(E=>E.newsletter_id===C).length)||0,f=C=>{var E;return((E=h==null?void 0:h.canva)==null?void 0:E.filter(P=>P.newsletter_id===C).length)||0},y=C=>{var E;return((E=h==null?void 0:h.pdfs)==null?void 0:E.filter(P=>P.newsletter_id===C).length)||0},v=C=>{var E;return((E=h==null?void 0:h.videos)==null?void 0:E.filter(P=>P.newsletter_id===C).length)||0},g=C=>{var E;return((E=h==null?void 0:h.drives)==null?void 0:E.filter(P=>P.newsletter_id===C).length)||0},b=C=>f(C)+y(C)+v(C)+g(C),j=o==null?void 0:o.filter(C=>{var E;return C.title.toLowerCase().includes(t.toLowerCase())||((E=C.description)==null?void 0:E.toLowerCase().includes(t.toLowerCase()))}),S=C=>{s(`/newsletters/${C}`)};return e.jsx(zs,{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(Yr,{defaultValue:"custom",className:"space-y-4",children:[e.jsxs(Zr,{children:[e.jsx(Ht,{value:"custom",children:"Build & Send"}),e.jsx(Ht,{value:"curated",children:"Curated Monthly"})]}),e.jsx(Gt,{value:"custom",className:"mt-2",children:e.jsx(E6n,{})}),e.jsxs(Gt,{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(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search newsletters...",value:t,onChange:C=>n(C.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex gap-2",children:[t&&e.jsx(B,{variant:"outline",size:"sm",onClick:()=>n(""),children:"Clear"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{variant:r==="grid"?"secondary":"outline",size:"icon",onClick:()=>a("grid"),className:"rounded-full",children:e.jsx(sf,{className:"h-4 w-4"})}),e.jsx(B,{variant:r==="list"?"secondary":"outline",size:"icon",onClick:()=>a("list"),className:"rounded-full",children:e.jsx(A0,{className:"h-4 w-4"})})]})]})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[(j==null?void 0:j.length)||0," item",(j==null?void 0:j.length)!==1?"s":""," found"]}),c&&e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6",children:[...Array(8)].map((C,E)=>e.jsx(ve,{children:e.jsxs(Me,{className:"p-0",children:[e.jsx(cn,{className:"aspect-[3/2] w-full"}),e.jsxs("div",{className:"p-4 space-y-2",children:[e.jsx(cn,{className:"h-5 w-3/4"}),e.jsx(cn,{className:"h-4 w-full"})]})]})},E))}),!c&&(j==null?void 0:j.length)===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Fr,{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(B,{variant:"outline",onClick:()=>n(""),children:"Clear Search"})]}),!c&&j&&j.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:j.map(C=>{const E=b(C.id),P=f(C.id),M=y(C.id),I=v(C.id);return r==="grid"?e.jsxs(ve,{className:"group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer border-border/50",onClick:()=>S(C.id),children:[e.jsx("div",{className:"relative overflow-hidden bg-muted aspect-[3/2]",children:C.preview_image_url?e.jsx("img",{src:C.preview_image_url,alt:C.title,className:"w-full h-full object-contain group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:e.jsx(Fr,{className:"h-16 w-16"})})}),e.jsxs(Me,{className:"p-4 space-y-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1",children:C.title}),e.jsxs("div",{className:"flex items-center gap-1.5 mt-1 text-xs text-muted-foreground",children:[e.jsx(ga,{className:"h-3 w-3"}),Hs(new Date(C.publish_date),"MMM d, yyyy")]})]}),C.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2",children:C.description.replace(/<[^>]*>/g,"")}),E>0&&e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[P>0&&e.jsxs(Oe,{variant:"secondary",className:"text-xs gap-1 font-normal",children:[e.jsx(Xc,{className:"h-3 w-3"})," ",P," Template",P>1?"s":""]}),M>0&&e.jsxs(Oe,{variant:"secondary",className:"text-xs gap-1 font-normal",children:[e.jsx(li,{className:"h-3 w-3"})," ",M," PDF",M>1?"s":""]}),I>0&&e.jsxs(Oe,{variant:"secondary",className:"text-xs gap-1 font-normal",children:[e.jsx(Jd,{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(Fg,{className:"h-3 w-3"})," ",m(C.id)]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ou,{className:"h-3 w-3"})," ",p(C.id)]})]}),C.html_code&&e.jsxs(B,{size:"sm",className:"w-full bg-gradient-to-r from-[#2a4c64] to-[#406E71] text-white hover:opacity-90",onClick:D=>{D.stopPropagation(),l(C)},children:[e.jsx(Or,{className:"h-4 w-4 mr-1.5"}),"Send Newsletter"]})]})]},C.id):e.jsx(ve,{className:"group overflow-hidden hover:shadow-md transition-all duration-200 cursor-pointer border-border/50",onClick:()=>S(C.id),children:e.jsxs("div",{className:"flex flex-row",children:[e.jsx("div",{className:"relative overflow-hidden bg-muted w-40 sm:w-48 shrink-0",children:C.preview_image_url?e.jsx("img",{src:C.preview_image_url,alt:C.title,className:"w-full h-full object-contain group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground min-h-[100px]",children:e.jsx(Fr,{className:"h-10 w-10"})})}),e.jsxs(Me,{className:"p-4 flex-1 flex flex-col justify-center gap-2",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1",children:C.title}),e.jsxs("div",{className:"flex items-center gap-1.5 mt-0.5 text-xs text-muted-foreground",children:[e.jsx(ga,{className:"h-3 w-3"}),Hs(new Date(C.publish_date),"MMM d, yyyy")]})]}),C.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-1",children:C.description.replace(/<[^>]*>/g,"")}),e.jsxs("div",{className:"flex items-center gap-4 text-xs text-muted-foreground",children:[E>0&&e.jsxs("span",{children:[E," resource",E>1?"s":""]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Fg,{className:"h-3 w-3"})," ",m(C.id)]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ou,{className:"h-3 w-3"})," ",p(C.id)]})]})]}),C.html_code&&e.jsx("div",{className:"p-3 flex items-center shrink-0",children:e.jsxs(B,{size:"sm",className:"bg-gradient-to-r from-[#2a4c64] to-[#406E71] text-white hover:opacity-90",onClick:D=>{D.stopPropagation(),l(C)},children:[e.jsx(Or,{className:"h-4 w-4 mr-1.5"}),"Send"]})})]})},C.id)})})]})]}),(i==null?void 0:i.html_code)&&e.jsx(ant,{open:!!i,onOpenChange:C=>!C&&l(null),newsletterId:i.id,newsletterTitle:i.title,htmlCode:i.html_code})]})})}function M6n({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(ve,{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(Me,{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 P6n(){const{id:s}=Li(),t=Fn(),{user:n}=hs(),{toast:r}=vi(),a=Bt(),{trackEngagement:i}=bW(),[l,o]=_.useState(""),[c,d]=_.useState(!1),{data:u,isLoading:h}=at({queryKey:["newsletter",s],queryFn:async()=>{const{data:P,error:M}=await q.from("newsletter_content").select("*").eq("id",s).single();if(M)throw M;return P},enabled:!!s});_.useEffect(()=>{u&&i("newsletter",u.id,u.title,"view")},[u==null?void 0:u.id]);const{data:m}=at({queryKey:["newsletter-drives",s],queryFn:async()=>{const{data:P}=await q.from("newsletter_drive_links").select("*").eq("newsletter_id",s).order("sort_order");return P||[]},enabled:!!s}),{data:p}=at({queryKey:["newsletter-pdfs",s],queryFn:async()=>{const{data:P}=await q.from("newsletter_pdfs").select("*").eq("newsletter_id",s).order("sort_order");return P||[]},enabled:!!s}),{data:f}=at({queryKey:["newsletter-videos",s],queryFn:async()=>{const{data:P}=await q.from("newsletter_videos").select("*").eq("newsletter_id",s).order("sort_order");return P||[]},enabled:!!s}),{data:y}=at({queryKey:["newsletter-canva-links",s],queryFn:async()=>{const{data:P}=await q.from("newsletter_canva_links").select("*").eq("newsletter_id",s).order("sort_order");return P||[]},enabled:!!s}),{data:v}=at({queryKey:["newsletter-likes",s],queryFn:async()=>{const{data:P}=await q.from("newsletter_likes").select("*").eq("newsletter_id",s);return P||[]},enabled:!!s}),{data:g}=at({queryKey:["newsletter-comments",s],queryFn:async()=>{const{data:P}=await q.from("newsletter_comments").select("*, profiles:user_id(name)").eq("newsletter_id",s).order("created_at",{ascending:!1});return P||[]},enabled:!!s}),b=v==null?void 0:v.some(P=>P.user_id===(n==null?void 0:n.id)),j=mt({mutationFn:async()=>{b?await q.from("newsletter_likes").delete().eq("newsletter_id",s).eq("user_id",n==null?void 0:n.id):await q.from("newsletter_likes").insert({newsletter_id:s,user_id:n==null?void 0:n.id})},onSuccess:()=>{a.invalidateQueries({queryKey:["newsletter-likes",s]})}}),S=mt({mutationFn:async P=>{const{error:M}=await q.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"})}}),C=mt({mutationFn:async P=>{const{error:M}=await q.from("newsletter_comments").delete().eq("id",P);if(M)throw M},onSuccess:()=>{a.invalidateQueries({queryKey:["newsletter-comments",s]}),r({title:"Comment deleted"})}}),E=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(Jd,{className:"h-4 w-4"})," Watch Video"]})};return h?e.jsx(zs,{title:"",description:"",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(cn,{className:"h-8 w-32"}),e.jsx(cn,{className:"h-64 w-full"}),e.jsx(cn,{className:"h-32 w-full"})]})}):u?e.jsx(zs,{title:"",description:"",children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsxs(B,{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(M6n,{rows:u.content_blocks||[]}),e.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[e.jsx(jW,{resourceType:"newsletter",resourceId:u.id,resourceTitle:u.title}),e.jsxs(B,{variant:b?"default":"outline",size:"sm",onClick:()=>j.mutate(),children:[e.jsx(Do,{className:`h-4 w-4 mr-1 ${b?"fill-current":""}`}),(v==null?void 0:v.length)||0," ",(v==null?void 0:v.length)===1?"Like":"Likes"]}),u.html_code&&e.jsxs(B,{size:"sm",className:"bg-gradient-to-r from-[#2a4c64] to-[#406E71] text-white hover:opacity-90",onClick:()=>d(!0),children:[e.jsx(Or,{className:"h-4 w-4 mr-1"}),"Send Newsletter"]})]}),u.html_code&&e.jsx(ant,{open:c,onOpenChange:d,newsletterId:u.id,newsletterTitle:u.title,htmlCode:u.html_code}),y&&y.length>0&&e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-lg",children:"Canva Templates"})}),e.jsx(Me,{className:"space-y-2",children:y.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(Xc,{className:"h-5 w-5 text-purple-500"}),e.jsx("span",{className:"font-medium",children:P.title}),e.jsx(wr,{className:"h-4 w-4 text-muted-foreground ml-auto"})]},P.id))})]}),m&&m.length>0&&e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-lg",children:"Google Drive Files"})}),e.jsx(Me,{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(wr,{className:"h-5 w-5 text-primary"}),e.jsx("span",{className:"font-medium",children:P.title})]},P.id))})]}),p&&p.length>0&&e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-lg",children:"PDF Downloads"})}),e.jsx(Me,{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(Fr,{className:"h-5 w-5 text-red-500"}),e.jsx("span",{className:"font-medium flex-1",children:P.name}),e.jsx(li,{className:"h-4 w-4 text-muted-foreground"})]},P.id))})]}),f&&f.length>0&&e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-lg",children:"Videos"})}),e.jsx(Me,{className:"space-y-6",children:f.map(P=>e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium",children:P.title}),E(P.video_url)]},P.id))})]}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsxs(St,{className:"text-lg",children:["Comments (",(g==null?void 0:g.length)||0,")"]})}),e.jsxs(Me,{className:"space-y-4",children:[e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Ms,{placeholder:"Write a comment...",value:l,onChange:P=>o(P.target.value),className:"flex-1"}),e.jsx(B,{onClick:()=>l.trim()&&S.mutate(l),disabled:!l.trim()||S.isPending,children:e.jsx(Or,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"space-y-4",children:g==null?void 0:g.map(P=>{var M,I,D;return e.jsxs("div",{className:"flex gap-3",children:[e.jsx(ja,{className:"h-8 w-8",children:e.jsx(Na,{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(B,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>C.mutate(P.id),children:e.jsx(Sn,{className:"h-3 w-3"})})]})]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:P.content})]})]},P.id)})})]})]})]})}):e.jsx(zs,{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(B,{variant:"link",onClick:()=>t("/newsletters"),children:"Back to Newsletters"})]})})}function L6n({rows:s,onChange:t}){const[n,r]=_.useState(null),[a,i]=_.useState(null),l=()=>{t([...s,{columns:[{title:"",description:""},{title:"",description:""},{title:"",description:""}]}])},o=h=>{t(s.filter((m,p)=>p!==h))},c=(h,m,p,f)=>{const y=[...s];y[h]={...y[h],columns:y[h].columns.map((v,g)=>g===m?{...v,[p]:f}:v)},t(y)},d=async(h,m,p)=>{var v;const f=(v=p.target.files)==null?void 0:v[0];if(!f)return;const y=`${h}-${m}`;r(y);try{const g=`content-blocks/${Date.now()}-${f.name}`,{error:b}=await q.storage.from("newsletter-content").upload(g,f);if(!b){const{data:j}=q.storage.from("newsletter-content").getPublicUrl(g);c(h,m,"image_url",j.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(J,{className:"text-base font-medium",children:"Content Blocks (3-Column Rows)"}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:l,children:[e.jsx(rn,{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(ve,{className:"relative",children:[e.jsx(B,{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(Qn,{className:"h-4 w-4"})}),e.jsxs(Me,{className:"p-4 pt-3",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(Vf,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:["Row ",m+1]})]}),e.jsx("div",{className:"grid grid-cols-3 gap-3",children:h.columns.map((p,f)=>{const y=`${m}-${f}`;return e.jsxs("div",{className:"space-y-2 border border-border/50 rounded-md p-3 bg-muted/20",children:[e.jsxs("span",{className:"text-xs text-muted-foreground font-medium",children:["Column ",f+1]}),p.image_url?e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:p.image_url,alt:"",className:"w-full h-20 object-cover rounded"}),e.jsx(B,{type:"button",variant:"destructive",size:"icon",className:"absolute top-1 right-1 h-5 w-5 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>u(m,f),children:e.jsx(Qn,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"grid grid-cols-2 gap-1.5",children:[e.jsx(xe,{type:"file",accept:"image/*",className:"hidden",id:`block-img-${y}`,onChange:v=>d(m,f,v)}),e.jsx(B,{type:"button",variant:"outline",size:"sm",className:"text-xs h-8",disabled:n===y,asChild:!0,children:e.jsx("label",{htmlFor:`block-img-${y}`,className:"cursor-pointer",children:n===y?"...":e.jsxs(e.Fragment,{children:[e.jsx(hc,{className:"h-3 w-3 mr-1"})," Upload"]})})}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",className:"text-xs h-8",onClick:()=>i({row:m,col:f}),children:[e.jsx(fj,{className:"h-3 w-3 mr-1"})," Library"]})]}),e.jsx(xe,{placeholder:"Title",value:p.title,onChange:v=>c(m,f,"title",v.target.value),className:"h-8 text-sm"}),e.jsx(Ms,{placeholder:"Description",value:p.description,onChange:v=>c(m,f,"description",v.target.value),className:"text-sm min-h-[60px] resize-none"})]},f)})})]})]},m)),e.jsx(Ls,{open:!!a,onOpenChange:h=>!h&&i(null),children:e.jsxs(Ps,{className:"sm:max-w-2xl",children:[e.jsx(Os,{children:e.jsx(Ds,{children:"Choose a Graphic"})}),e.jsx(TKt,{onSelect:h=>{a&&(c(a.row,a.col,"image_url",h.image_url),i(null))}})]})})]})}function I6n(){const{toast:s}=vi(),t=Bt(),[n,r]=_.useState(!1),[a,i]=_.useState(null),[l,o]=_.useState({title:"",description:"",publish_date:Hs(new Date,"yyyy-MM-dd'T'HH:mm"),is_published:!1}),[c,d]=_.useState(null),[u,h]=_.useState(null),[m,p]=_.useState([]),[f,y]=_.useState([]),[v,g]=_.useState([]),[b,j]=_.useState([]),[S,C]=_.useState([]),[E,P]=_.useState(""),[M,I]=_.useState([]),[D,O]=_.useState(!1),{data:V,isLoading:G}=at({queryKey:["admin-newsletters"],queryFn:async()=>{const{data:pe,error:Ce}=await q.from("newsletter_content").select("*").order("publish_date",{ascending:!1});if(Ce)throw Ce;return pe}}),$=mt({mutationFn:async pe=>{const{data:Ce,error:Ae}=await q.from("newsletter_content").insert({title:pe.title,description:pe.description||null,preview_image_url:pe.preview_image_url,publish_date:pe.publish_date,is_published:pe.is_published,content_blocks:pe.content_blocks,html_code:pe.html_code}).select().single();if(Ae)throw Ae;return Ce},onSuccess:async pe=>{await Z(pe.id),t.invalidateQueries({queryKey:["admin-newsletters"]}),s({title:"Newsletter created successfully"}),pe.is_published&&Qin(pe.title,pe.id),ie()},onError:pe=>{s({title:"Error creating newsletter",description:pe.message,variant:"destructive"})}}),H=mt({mutationFn:async pe=>{const{error:Ce}=await q.from("newsletter_content").update({title:pe.title,description:pe.description||null,preview_image_url:pe.preview_image_url,publish_date:pe.publish_date,is_published:pe.is_published,content_blocks:pe.content_blocks,html_code:pe.html_code}).eq("id",pe.id);if(Ce)throw Ce;return pe.id},onSuccess:async pe=>{await Z(pe),t.invalidateQueries({queryKey:["admin-newsletters"]}),s({title:"Newsletter updated successfully"}),ie()},onError:pe=>{s({title:"Error updating newsletter",description:pe.message,variant:"destructive"})}}),Y=mt({mutationFn:async pe=>{const{error:Ce}=await q.from("newsletter_content").delete().eq("id",pe);if(Ce)throw Ce},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-newsletters"]}),s({title:"Newsletter deleted successfully"})},onError:pe=>{s({title:"Error deleting newsletter",description:pe.message,variant:"destructive"})}}),Z=async pe=>{await q.from("newsletter_drive_links").delete().eq("newsletter_id",pe),await q.from("newsletter_pdfs").delete().eq("newsletter_id",pe),await q.from("newsletter_videos").delete().eq("newsletter_id",pe),await q.from("newsletter_canva_links").delete().eq("newsletter_id",pe);for(const Ce of M){const Ae=`${pe}/${Date.now()}-${Ce.file.name}`,{error:Pe}=await q.storage.from("newsletter-content").upload(Ae,Ce.file);if(!Pe){const{data:ze}=q.storage.from("newsletter-content").getPublicUrl(Ae);f.push({name:Ce.name,file_url:ze.publicUrl,file_size:Ce.file.size,sort_order:f.length})}}m.length>0&&await q.from("newsletter_drive_links").insert(m.map((Ce,Ae)=>({newsletter_id:pe,title:Ce.title,drive_url:Ce.drive_url,sort_order:Ae}))),f.length>0&&await q.from("newsletter_pdfs").insert(f.map((Ce,Ae)=>({newsletter_id:pe,name:Ce.name,file_url:Ce.file_url,file_size:Ce.file_size||null,sort_order:Ae}))),v.length>0&&await q.from("newsletter_videos").insert(v.map((Ce,Ae)=>({newsletter_id:pe,title:Ce.title,video_url:Ce.video_url,sort_order:Ae}))),b.length>0&&await q.from("newsletter_canva_links").insert(b.map((Ce,Ae)=>({newsletter_id:pe,title:Ce.title,canva_share_link:Ce.canva_share_link,sort_order:Ae})))},ne=async pe=>{i(pe),o({title:pe.title,description:pe.description||"",publish_date:Hs(new Date(pe.publish_date),"yyyy-MM-dd'T'HH:mm"),is_published:pe.is_published}),h(pe.preview_image_url),C(pe.content_blocks||[]),P(pe.html_code||"");const[Ce,Ae,Pe,ze]=await Promise.all([q.from("newsletter_drive_links").select("*").eq("newsletter_id",pe.id).order("sort_order"),q.from("newsletter_pdfs").select("*").eq("newsletter_id",pe.id).order("sort_order"),q.from("newsletter_videos").select("*").eq("newsletter_id",pe.id).order("sort_order"),q.from("newsletter_canva_links").select("*").eq("newsletter_id",pe.id).order("sort_order")]);p(Ce.data||[]),y(Ae.data||[]),g(Pe.data||[]),j(ze.data||[]),I([]),r(!0)},ce=async pe=>{const[Ce,Ae,Pe,ze]=await Promise.all([q.from("newsletter_drive_links").select("*").eq("newsletter_id",pe.id).order("sort_order"),q.from("newsletter_pdfs").select("*").eq("newsletter_id",pe.id).order("sort_order"),q.from("newsletter_videos").select("*").eq("newsletter_id",pe.id).order("sort_order"),q.from("newsletter_canva_links").select("*").eq("newsletter_id",pe.id).order("sort_order")]);i(null),o({title:`${pe.title} (Copy)`,description:pe.description||"",publish_date:Hs(new Date,"yyyy-MM-dd'T'HH:mm"),is_published:!1}),h(pe.preview_image_url),C(pe.content_blocks||[]),P(pe.html_code||""),p((Ce.data||[]).map(({id:ke,...Ze})=>Ze)),y((Ae.data||[]).map(({id:ke,...Ze})=>Ze)),g((Pe.data||[]).map(({id:ke,...Ze})=>Ze)),j((ze.data||[]).map(({id:ke,...Ze})=>Ze)),I([]),r(!0)},ie=()=>{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([]),y([]),g([]),j([]),C([]),P(""),I([])},te=async pe=>{var Ae;const Ce=(Ae=pe.target.files)==null?void 0:Ae[0];Ce&&(d(Ce),h(URL.createObjectURL(Ce)))},ae=async()=>{if(!l.title){s({title:"Title is required",variant:"destructive"});return}O(!0);let pe=u;if(c){const Ce=`previews/${Date.now()}-${c.name}`,{error:Ae}=await q.storage.from("newsletter-content").upload(Ce,c);if(!Ae){const{data:Pe}=q.storage.from("newsletter-content").getPublicUrl(Ce);pe=Pe.publicUrl}}a?H.mutate({id:a.id,...l,preview_image_url:pe,content_blocks:S,html_code:E||null}):$.mutate({...l,preview_image_url:pe,content_blocks:S,html_code:E||null}),O(!1)},le=()=>p([...m,{title:"",drive_url:"",sort_order:m.length}]),be=()=>g([...v,{title:"",video_url:"",sort_order:v.length}]),me=()=>j([...b,{title:"",canva_share_link:"",sort_order:b.length}]),he=pe=>{const Ce=pe.target.files;if(!Ce)return;const Ae=Array.from(Ce).map(Pe=>({file:Pe,name:Pe.name.replace(/\.[^/.]+$/,"")}));I([...M,...Ae])};return e.jsx(zs,{title:"Newsletter Content",description:"Manage monthly newsletter templates and resources",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Wh,{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(ve,{children:[e.jsx(bt,{className:"pb-2",children:e.jsx(St,{className:"text-sm font-medium text-muted-foreground",children:"Total"})}),e.jsx(Me,{children:e.jsx("div",{className:"text-2xl font-bold",children:(V==null?void 0:V.length)||0})})]}),e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-2",children:e.jsx(St,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Me,{children:e.jsx("div",{className:"text-2xl font-bold",children:(V==null?void 0:V.filter(pe=>pe.is_published).length)||0})})]})]}),e.jsxs(Ls,{open:n,onOpenChange:pe=>!pe&&ie(),children:[e.jsx(nl,{asChild:!0,children:e.jsxs(B,{onClick:()=>r(!0),children:[e.jsx(rn,{className:"mr-2 h-4 w-4"})," Add Newsletter"]})}),e.jsxs(Ps,{className:"max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Ds,{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(J,{children:"Title *"}),e.jsx(xe,{value:l.title,onChange:pe=>o({...l,title:pe.target.value}),placeholder:"Newsletter title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Publish Date"}),e.jsx(xe,{type:"datetime-local",value:l.publish_date,onChange:pe=>o({...l,publish_date:pe.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Description"}),e.jsx(BN,{content:l.description,onChange:pe=>o({...l,description:pe}),placeholder:"Newsletter description",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{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(B,{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(Qn,{className:"h-3 w-3"})})]}),e.jsxs("div",{children:[e.jsx(xe,{type:"file",accept:"image/*",onChange:te,className:"hidden",id:"preview-upload"}),e.jsx(B,{variant:"outline",asChild:!0,children:e.jsxs("label",{htmlFor:"preview-upload",className:"cursor-pointer",children:[e.jsx(Oa,{className:"mr-2 h-4 w-4"})," Upload Image"]})})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fn,{checked:l.is_published,onCheckedChange:pe=>o({...l,is_published:pe})}),e.jsx(J,{children:"Published"})]}),e.jsx(L6n,{rows:S,onChange:C}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(J,{className:"text-base font-medium",children:"HTML Code (for agent send)"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:'When provided, agents see a "Send Newsletter" button on this newsletter.'})]}),e.jsx("textarea",{value:E,onChange:pe=>P(pe.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(J,{className:"text-base font-medium",children:"Canva Links"}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:me,children:[e.jsx(rn,{className:"mr-1 h-3 w-3"})," Add Canva Link"]})]}),b.map((pe,Ce)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(xe,{placeholder:"Link title",value:pe.title,onChange:Ae=>{const Pe=[...b];Pe[Ce].title=Ae.target.value,j(Pe)},className:"w-1/3"}),e.jsx(xe,{placeholder:"Canva share link",value:pe.canva_share_link,onChange:Ae=>{const Pe=[...b];Pe[Ce].canva_share_link=Ae.target.value,j(Pe)},className:"flex-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>j(b.filter((Ae,Pe)=>Pe!==Ce)),children:e.jsx(Qn,{className:"h-4 w-4"})})]},Ce))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(J,{className:"text-base font-medium",children:"Google Drive Links"}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:le,children:[e.jsx(rn,{className:"mr-1 h-3 w-3"})," Add Link"]})]}),m.map((pe,Ce)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(xe,{placeholder:"Link title",value:pe.title,onChange:Ae=>{const Pe=[...m];Pe[Ce].title=Ae.target.value,p(Pe)},className:"w-1/3"}),e.jsx(xe,{placeholder:"Google Drive URL",value:pe.drive_url,onChange:Ae=>{const Pe=[...m];Pe[Ce].drive_url=Ae.target.value,p(Pe)},className:"flex-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>p(m.filter((Ae,Pe)=>Pe!==Ce)),children:e.jsx(Qn,{className:"h-4 w-4"})})]},Ce))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(J,{className:"text-base font-medium",children:"PDF Files"}),e.jsxs("div",{children:[e.jsx(xe,{type:"file",accept:".pdf",multiple:!0,onChange:he,className:"hidden",id:"pdf-upload"}),e.jsx(B,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("label",{htmlFor:"pdf-upload",className:"cursor-pointer",children:[e.jsx(Oa,{className:"mr-1 h-3 w-3"})," Upload PDF"]})})]})]}),f.map((pe,Ce)=>e.jsxs("div",{className:"flex gap-2 items-center bg-muted/50 p-2 rounded",children:[e.jsx(Fr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"flex-1 text-sm",children:pe.name}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>y(f.filter((Ae,Pe)=>Pe!==Ce)),children:e.jsx(Qn,{className:"h-4 w-4"})})]},`existing-${Ce}`)),M.map((pe,Ce)=>e.jsxs("div",{className:"flex gap-2 items-center bg-muted/50 p-2 rounded",children:[e.jsx(Fr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(xe,{value:pe.name,onChange:Ae=>{const Pe=[...M];Pe[Ce].name=Ae.target.value,I(Pe)},className:"flex-1 h-8",placeholder:"PDF name"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"(new)"}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>I(M.filter((Ae,Pe)=>Pe!==Ce)),children:e.jsx(Qn,{className:"h-4 w-4"})})]},`pending-${Ce}`))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(J,{className:"text-base font-medium",children:"Video Links"}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:be,children:[e.jsx(rn,{className:"mr-1 h-3 w-3"})," Add Video"]})]}),v.map((pe,Ce)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(xe,{placeholder:"Video title",value:pe.title,onChange:Ae=>{const Pe=[...v];Pe[Ce].title=Ae.target.value,g(Pe)},className:"w-1/3"}),e.jsx(xe,{placeholder:"Video URL",value:pe.video_url,onChange:Ae=>{const Pe=[...v];Pe[Ce].video_url=Ae.target.value,g(Pe)},className:"flex-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>g(v.filter((Ae,Pe)=>Pe!==Ce)),children:e.jsx(Qn,{className:"h-4 w-4"})})]},Ce))]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e.jsx(B,{variant:"outline",onClick:ie,children:"Cancel"}),e.jsx(B,{onClick:ae,disabled:D||$.isPending||H.isPending,children:D?"Uploading...":a?"Update":"Create"})]})]})]})]})]}),e.jsx(ve,{children:e.jsx(Me,{className:"p-0",children:e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"Name"}),e.jsx(Pt,{children:"Publish Date"}),e.jsx(Pt,{children:"Status"}),e.jsx(Pt,{className:"text-right",children:"Actions"})]})}),e.jsx(Ka,{children:G?e.jsx(pn,{children:e.jsx(gt,{colSpan:4,className:"text-center py-8",children:"Loading..."})}):(V==null?void 0:V.length)===0?e.jsx(pn,{children:e.jsx(gt,{colSpan:4,className:"text-center py-8 text-muted-foreground",children:"No newsletters yet. Create your first one!"})}):V==null?void 0:V.map(pe=>e.jsxs(pn,{children:[e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[pe.preview_image_url?e.jsx("img",{src:pe.preview_image_url,alt:pe.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(Fr,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:pe.title}),pe.description&&e.jsx("div",{className:"text-sm text-muted-foreground line-clamp-1",children:pe.description.replace(/<[^>]*>/g,"")})]})]})}),e.jsx(gt,{children:Hs(new Date(pe.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 ${pe.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:pe.is_published?"Published":"Draft"})}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>ne(pe),title:"Edit",children:e.jsx(Ya,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>ce(pe),title:"Duplicate",children:e.jsx(Ia,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",title:"Delete",onClick:async()=>{await Xi("Are you sure you want to delete this newsletter?")&&Y.mutate(pe.id)},children:e.jsx(Sn,{className:"h-4 w-4"})})]})})]},pe.id))})]})})})]})})}const D6n={status:"all",billing:"all",role:"all",brokerage:"all",joinedWithinDays:null};function R6n({brokerages:s}){var C;const{toast:t}=vi(),[n,r]=_.useState(D6n),[a,i]=_.useState(""),[l,o]=_.useState(""),[c,d]=_.useState(""),[u,h]=_.useState(null),[m,p]=_.useState(!1),[f,y]=_.useState(!1),[v,g]=_.useState(null),b=(E,P)=>r(M=>({...M,[E]:P}));_.useEffect(()=>{const E=setTimeout(async()=>{p(!0);try{const{data:P,error:M}=await q.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(E)},[n,a]);const j=async()=>{if(!c||!a.trim()){t({title:"Add a test number and message",variant:"destructive"});return}y(!0);const{data:E,error:P}=await q.functions.invoke("admin-broadcast-sms",{body:{action:"test",to:c,sms_body:a}});if(y(!1),P||E!=null&&E.error){t({title:"Test failed",description:(E==null?void 0:E.error)||(P==null?void 0:P.message),variant:"destructive"});return}t({title:"Test text sent",description:`Sent to ${c}`})},S=async()=>{const E=(u==null?void 0:u.count)||0;if(!(!a.trim()||E===0||!await Xi({title:"Send text broadcast?",description:`This will text ${E} member${E===1?"":"s"} who have a recorded SMS opt-in. Texts cannot be recalled.`,confirmText:"Send broadcast"}))){y(!0),g({total:E,sent:0,failed:0});try{const{data:M,error:I}=await q.functions.invoke("admin-broadcast-sms",{body:{action:"queue",name:l||a.slice(0,60),sms_body:a,filters:n}});if(I||M!=null&&M.error)throw new Error((M==null?void 0:M.error)||(I==null?void 0:I.message));let D=0,O=0,V=M.total,G=0;for(;V>0&&G++<400;){const{data:$,error:H}=await q.functions.invoke("admin-broadcast-sms",{body:{action:"process",broadcast_id:M.broadcast_id,limit:40}});if(H||$!=null&&$.error)throw new Error(($==null?void 0:$.error)||(H==null?void 0:H.message));if($.deferred){t({title:"Paused for quiet hours",description:$.reason});break}D+=$.sent||0,O+=$.failed||0,V=$.remaining||0,g({total:E,sent:D,failed:O})}t({title:"Broadcast complete",description:`${D} sent${O?`, ${O} failed`:""}.`})}catch(M){t({title:"Broadcast failed",description:M.message,variant:"destructive"})}finally{y(!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(ve,{children:[e.jsxs(bt,{className:"pb-3",children:[e.jsxs(St,{className:"flex items-center gap-2 text-base",children:[e.jsx(Dm,{className:"h-4 w-4"})," SMS Audience"]}),e.jsx(kn,{children:"Only members with a recorded consent date and source are included. Opted-out and undeliverable numbers are always excluded."})]}),e.jsxs(Me,{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs",children:"Account status"}),e.jsxs(is,{value:n.status,onValueChange:E=>b("status",E),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All members"}),e.jsx(He,{value:"active",children:"Signed in before"}),e.jsx(He,{value:"pending",children:"Never signed in"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs",children:"Billing"}),e.jsxs(is,{value:n.billing,onValueChange:E=>b("billing",E),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All"}),e.jsx(He,{value:"trial",children:"On trial"}),e.jsx(He,{value:"paid",children:"Paid"}),e.jsx(He,{value:"grandfathered",children:"Grandfathered"}),e.jsx(He,{value:"canceled",children:"Canceled / past due"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs",children:"Role"}),e.jsxs(is,{value:n.role,onValueChange:E=>b("role",E),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All roles"}),e.jsx(He,{value:"user",children:"Agents"}),e.jsx(He,{value:"brokerage_manager",children:"Brokerage managers"}),e.jsx(He,{value:"coach",children:"Coaches"}),e.jsx(He,{value:"admin",children:"Admins"})]})]})]}),!!(s!=null&&s.length)&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs",children:"Brokerage"}),e.jsxs(is,{value:n.brokerage,onValueChange:E=>b("brokerage",E),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All brokerages"}),e.jsx(He,{value:"none",children:"No brokerage"}),s.map(E=>e.jsx(He,{value:E.id,children:E.name},E.id))]})]})]}),e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"SMS-eligible members"}),e.jsx("span",{className:"text-lg font-semibold",children:m?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):(u==null?void 0:u.count)??0})]}),(C=u==null?void 0:u.sample)!=null&&C.length?e.jsxs("p",{className:"mt-2 text-xs text-muted-foreground",children:["e.g. ",u.sample.slice(0,3).map(E=>E.name||E.phone).join(", ")]}):null]}),u&&!u.quiet_hours_ok&&e.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-amber-500/40 bg-amber-500/10 p-3 text-xs",children:[e.jsx(Gr,{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(ve,{children:[e.jsxs(bt,{className:"pb-3",children:[e.jsxs(St,{className:"flex items-center gap-2 text-base",children:[e.jsx(Hi,{className:"h-4 w-4"})," Text message"]}),e.jsxs(kn,{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(Me,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{htmlFor:"sms-broadcast-name",className:"text-xs",children:"Internal name"}),e.jsx(xe,{id:"sms-broadcast-name",value:l,onChange:E=>o(E.target.value),placeholder:"August member update"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{htmlFor:"sms-broadcast-body",className:"text-xs",children:"Message"}),e.jsx(Ms,{id:"sms-broadcast-body",value:a,onChange:E=>i(E.target.value),rows:5,maxLength:480,placeholder:"Hi {{first_name}} — join us Thursday at 11am ET for the LevelUp Live session on listing videos."}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:[(u==null?void 0:u.length)??a.length," characters"]}),e.jsxs(Oe,{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(J,{htmlFor:"sms-test-phone",className:"text-xs",children:"Send a test to"}),e.jsx(xe,{id:"sms-test-phone",value:c,onChange:E=>d(E.target.value),placeholder:"(555) 123-4567",type:"tel"})]}),e.jsxs(B,{variant:"outline",onClick:j,disabled:f,children:[f&&e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"})," Send test"]})]}),v&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(Fi,{value:v.total?(v.sent+v.failed)/v.total*100:0}),e.jsxs("div",{className:"flex items-center gap-4 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Er,{className:"h-3 w-3"})," ",v.sent," sent"]}),v.failed>0&&e.jsxs("span",{className:"flex items-center gap-1 text-destructive",children:[e.jsx(Xo,{className:"h-3 w-3"})," ",v.failed," failed"]}),e.jsxs("span",{children:["of ",v.total]})]})]}),e.jsxs(B,{onClick:S,disabled:f||!a.trim()||!(u!=null&&u.count),className:"w-full",children:[f?e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Or,{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 U9e={status:"all",billing:"all",role:"all",brokerage:"all",joinedWithinDays:null,respectOptOut:!0,program:"all",programStatus:"active"},F6n=["{{first_name}}","{{name}}","{{email}}"];function O6n(s){return`${s||'

Your email preview will appear here…

'}`}function z6n(){var $e;const{toast:s}=vi(),{user:t}=hs(),n=Bt(),[r,a]=_.useState("filters"),[i,l]=_.useState([]),[o,c]=_.useState(""),[d,u]=_.useState([]),[h,m]=_.useState(!1),[p,f]=_.useState(""),[y,v]=_.useState(!1),[g,b]=_.useState(U9e),[j,S]=_.useState(null),[C,E]=_.useState(!1),[P,M]=_.useState(""),[I,D]=_.useState(""),[O,V]=_.useState(""),[G,$]=_.useState(""),[H,Y]=_.useState("rich"),[Z,ne]=_.useState(""),[ce,ie]=_.useState(""),[te,ae]=_.useState(""),[le,be]=_.useState(!1),[me,he]=_.useState(null),pe=H==="rich"?Z:ce;_.useEffect(()=>{t!=null&&t.email&&(V(Ge=>Ge||t.email),$(Ge=>Ge||t.email),ae(Ge=>Ge||t.email))},[t==null?void 0:t.email]);const{data:Ce}=at({queryKey:["broadcast-brokerages"],queryFn:async()=>{const{data:Ge}=await q.from("brokerages").select("id, name").order("name");return Ge||[]}}),{data:Ae}=at({queryKey:["broadcast-programs"],queryFn:async()=>{const{data:Ge}=await q.from("programs").select("id, name").order("created_at",{ascending:!1});return Ge||[]}}),{data:Pe}=at({queryKey:["admin-broadcasts"],queryFn:async()=>{const{data:Ge,error:ct}=await q.from("admin_broadcasts").select("*").order("created_at",{ascending:!1}).limit(30);if(ct)throw ct;return Ge}}),{data:ze}=at({queryKey:["admin-broadcast-templates"],queryFn:async()=>{const{data:Ge,error:ct}=await q.from("admin_broadcast_templates").select("*").order("updated_at",{ascending:!1});if(ct)throw ct;return Ge}}),ke=async Ge=>{E(!0);try{const{data:ct,error:xt}=await q.functions.invoke("admin-broadcast",{body:{action:"preview",filters:Ge}});if(xt)throw xt;if(ct!=null&&ct.error)throw new Error(ct.error);S(ct)}catch(ct){s({title:"Could not load audience",description:ct.message,variant:"destructive"})}finally{E(!1)}};_.useEffect(()=>{if(r!=="filters")return;const Ge=setTimeout(()=>ke(g),400);return()=>clearTimeout(Ge)},[g,r]),_.useEffect(()=>{if(r!=="manual")return;const Ge=setTimeout(async()=>{m(!0);try{const{data:ct,error:xt}=await q.functions.invoke("admin-broadcast",{body:{action:"search_members",query:o}});if(xt)throw xt;u((ct==null?void 0:ct.members)||[])}catch{u([])}finally{m(!1)}},350);return()=>clearTimeout(Ge)},[o,r]);const Ze=(Ge,ct)=>b(xt=>({...xt,[Ge]:ct})),Se=r==="manual"?i.length:(j==null?void 0:j.count)||0,Fe=()=>r==="manual"?{recipient_mode:"manual",manual_emails:i.map(Ge=>Ge.email)}:{recipient_mode:"filters",filters:g},Ne=Ge=>l(ct=>ct.some(xt=>xt.email.toLowerCase()===Ge.email.toLowerCase())?ct.filter(xt=>xt.email.toLowerCase()!==Ge.email.toLowerCase()):[...ct,Ge]),Ye=async()=>{const Ge=(p||P||I).trim();if(!Ge||!pe.trim()){s({title:"Add a template name and content first",variant:"destructive"});return}v(!0);try{const{error:ct}=await q.from("admin_broadcast_templates").insert({created_by:t.id,name:Ge,subject:I,body_html:pe,editor_mode:H,from_email:O||null,reply_to_email:G||null,filters:g});if(ct)throw ct;f(""),s({title:"Template saved",description:`"${Ge}" is available for future sends.`}),n.invalidateQueries({queryKey:["admin-broadcast-templates"]})}catch(ct){s({title:"Could not save template",description:ct.message,variant:"destructive"})}finally{v(!1)}},Ve=Ge=>{M(Ge.name||""),D(Ge.subject||""),Ge.from_email&&V(Ge.from_email),Ge.reply_to_email&&$(Ge.reply_to_email);const ct=Ge.editor_mode==="html"?"html":"rich";Y(ct),ct==="html"?ie(Ge.body_html||""):ne(Ge.body_html||""),Ge.filters&&Object.keys(Ge.filters).length&&b({...U9e,...Ge.filters}),s({title:"Template loaded",description:"Edit and send when ready."})},qe=async Ge=>{if(!await Xi(`Delete template "${Ge.name}"?`))return;const{error:ct}=await q.from("admin_broadcast_templates").delete().eq("id",Ge.id);if(ct){s({title:"Delete failed",description:ct.message,variant:"destructive"});return}n.invalidateQueries({queryKey:["admin-broadcast-templates"]})},Qe=_.useMemo(()=>!!I.trim()&&!!pe.trim()&&!!O.trim()&&Se>0,[I,pe,O,Se]),Ue=async()=>{if(!te||!I.trim()||!pe.trim()){s({title:"Add a subject, content and test address first",variant:"destructive"});return}try{const{data:Ge,error:ct}=await q.functions.invoke("admin-broadcast",{body:{action:"test",to:te,subject:I,html:pe,from_email:O,reply_to:G||void 0}});if(ct)throw ct;if(Ge!=null&&Ge.error)throw new Error(Ge.error);s({title:"Test sent",description:`Check ${te}`})}catch(Ge){s({title:"Test failed",description:Ge.message,variant:"destructive"})}},Xe=async()=>{const Ge=Se;if(await Xi({title:"Send this broadcast?",description:`"${I}" will be emailed to ${Ge} member${Ge===1?"":"s"}. Sent emails can't be recalled.`,confirmText:"Send broadcast",cancelText:"Cancel",destructive:!1})){be(!0),he({total:Ge,sent:0,failed:0});try{const{data:xt,error:qt}=await q.functions.invoke("admin-broadcast",{body:{action:"queue",name:P||I,subject:I,html:pe,from_email:O,reply_to:G||void 0,...Fe()}});if(qt)throw qt;if(xt!=null&&xt.error)throw new Error(xt.error);let Vt=0,Xt=0,fs=xt.total,Ft=0;for(;fs>0;){const{data:wt,error:Ts}=await q.functions.invoke("admin-broadcast",{body:{action:"process",broadcast_id:xt.broadcast_id,limit:40}});if(Ts)throw Ts;if(wt!=null&&wt.error)throw new Error(wt.error);if(Vt+=wt.sent,Xt+=wt.failed,fs=wt.remaining,he({total:xt.total,sent:Vt,failed:Xt}),wt.throttled){const vt=Math.min(Math.max(Number(wt.retry_after_ms)||15e3,5e3),45e3);await new Promise($s=>setTimeout($s,vt));continue}if(wt.sent===0&&wt.failed===0){if(++Ft>=3)break;await new Promise(vt=>setTimeout(vt,5e3))}else Ft=0}s({title:"Broadcast complete",description:`${Vt} sent${Xt?`, ${Xt} failed`:""}`}),n.invalidateQueries({queryKey:["admin-broadcasts"]})}catch(xt){s({title:"Send failed",description:xt.message,variant:"destructive"})}finally{be(!1)}}},nt=async Ge=>{be(!0);try{const{data:ct,error:xt}=await q.functions.invoke("admin-broadcast",{body:{action:"retry_failed",broadcast_id:Ge}});if(xt)throw xt;if(ct!=null&&ct.error)throw new Error(ct.error);let qt=0,Vt=0,Xt=ct.requeued,fs=0;for(he({total:Xt,sent:0,failed:0});Xt>0;){const{data:Ft,error:wt}=await q.functions.invoke("admin-broadcast",{body:{action:"process",broadcast_id:Ge,limit:25}});if(wt)throw wt;if(Ft!=null&&Ft.error)throw new Error(Ft.error);if(qt+=Ft.sent,Vt+=Ft.failed,Xt=Ft.remaining,he({total:ct.requeued,sent:qt,failed:Vt}),Ft.throttled){await new Promise(Ts=>setTimeout(Ts,Math.min(Math.max(Number(Ft.retry_after_ms)||15e3,5e3),45e3)));continue}if(Ft.sent===0&&Ft.failed===0){if(++fs>=3)break;await new Promise(Ts=>setTimeout(Ts,5e3))}else fs=0}s({title:"Retry complete",description:`${qt} sent${Vt?`, ${Vt} still failed`:""}`}),n.invalidateQueries({queryKey:["admin-broadcasts"]})}catch(ct){s({title:"Retry failed",description:ct.message,variant:"destructive"})}finally{be(!1)}};return e.jsx(zs,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-8",children:[e.jsx(Wh,{title:"Member Broadcasts",description:"Send a one-off email to a filtered slice of LevelUp members"}),e.jsxs(Yr,{defaultValue:"compose",className:"space-y-6",children:[e.jsxs(Zr,{children:[e.jsxs(Ht,{value:"compose",className:"gap-2",children:[e.jsx(ln,{className:"h-4 w-4"})," Compose"]}),e.jsxs(Ht,{value:"sms",className:"gap-2",children:[e.jsx(Hi,{className:"h-4 w-4"})," Text (SMS)"]}),e.jsxs(Ht,{value:"templates",className:"gap-2",children:[e.jsx(pj,{className:"h-4 w-4"})," Templates"]}),e.jsxs(Ht,{value:"history",className:"gap-2",children:[e.jsx(R_,{className:"h-4 w-4"})," History"]})]}),e.jsx(Gt,{value:"sms",className:"space-y-6",children:e.jsx(R6n,{brokerages:Ce})}),e.jsx(Gt,{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(ve,{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(In,{className:"h-4 w-4"})," Audience"]}),e.jsxs("div",{className:"mt-2 flex items-baseline gap-2",children:[e.jsx("span",{className:"text-4xl font-bold",children:r==="manual"?i.length:C?"—":(j==null?void 0:j.count)??0}),e.jsx("span",{className:"text-sm opacity-90",children:r==="manual"?"members selected":"members match"})]})]}),e.jsxs(Me,{className:"space-y-4 pt-5",children:[e.jsx(Yr,{value:r,onValueChange:Ge=>a(Ge),children:e.jsxs(Zr,{className:"grid w-full grid-cols-2",children:[e.jsxs(Ht,{value:"filters",className:"gap-1.5 text-xs",children:[e.jsx(In,{className:"h-3.5 w-3.5"})," Filters"]}),e.jsxs(Ht,{value:"manual",className:"gap-1.5 text-xs",children:[e.jsx(Pl,{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(J,{children:"Find members"}),e.jsxs("div",{className:"relative",children:[e.jsx(Lr,{className:"pointer-events-none absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{value:o,onChange:Ge=>c(Ge.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(Ge=>e.jsxs(Oe,{variant:"secondary",className:"gap-1",children:[e.jsx("span",{className:"max-w-[150px] truncate",children:Ge.name||Ge.email}),e.jsx("button",{type:"button",onClick:()=>Ne(Ge),"aria-label":`Remove ${Ge.email}`,children:e.jsx(Qn,{className:"h-3 w-3"})})]},Ge.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(Ge=>{const ct=i.some(xt=>xt.email.toLowerCase()===Ge.email.toLowerCase());return e.jsxs("button",{type:"button",onClick:()=>Ne(Ge),className:`flex w-full items-center justify-between rounded-md px-2.5 py-2 text-left text-xs hover:bg-muted ${ct?"bg-muted":""}`,children:[e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block truncate font-medium",children:Ge.name||"Member"}),e.jsx("span",{className:"block truncate text-muted-foreground",children:Ge.email})]}),ct&&e.jsx(Er,{className:"h-4 w-4 shrink-0 text-primary"})]},Ge.id)})})]}),r==="filters"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Account status"}),e.jsxs(is,{value:g.status,onValueChange:Ge=>Ze("status",Ge),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All members"}),e.jsx(He,{value:"active",children:"Active (signed in)"}),e.jsx(He,{value:"pending",children:"Pending (never signed in)"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Membership"}),e.jsxs(is,{value:g.billing,onValueChange:Ge=>Ze("billing",Ge),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"Any membership"}),e.jsx(He,{value:"trial",children:"On trial"}),e.jsx(He,{value:"paid",children:"Paid subscribers"}),e.jsx(He,{value:"grandfathered",children:"Grandfathered"}),e.jsx(He,{value:"canceled",children:"Canceled / past due"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Role"}),e.jsxs(is,{value:g.role,onValueChange:Ge=>Ze("role",Ge),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"Any role"}),e.jsx(He,{value:"user",children:"Members"}),e.jsx(He,{value:"brokerage_manager",children:"Brokerage managers"}),e.jsx(He,{value:"coach",children:"Coaches"}),e.jsx(He,{value:"assistant",children:"Assistants"}),e.jsx(He,{value:"admin",children:"Admins"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Brokerage"}),e.jsxs(is,{value:g.brokerage,onValueChange:Ge=>Ze("brokerage",Ge),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{className:"max-h-72",children:[e.jsx(He,{value:"all",children:"All brokerages"}),e.jsx(He,{value:"none",children:"No brokerage"}),(Ce||[]).map(Ge=>e.jsx(He,{value:Ge.id,children:Ge.name},Ge.id))]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Program enrollment"}),e.jsxs(is,{value:g.program,onValueChange:Ge=>Ze("program",Ge),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{className:"max-h-72",children:[e.jsx(He,{value:"all",children:"Not filtered by program"}),e.jsx(He,{value:"any",children:"Enrolled in any program"}),(Ae||[]).map(Ge=>e.jsx(He,{value:Ge.id,children:Ge.name},Ge.id))]})]})]}),g.program!=="all"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Enrollment status"}),e.jsxs(is,{value:g.programStatus,onValueChange:Ge=>Ze("programStatus",Ge),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"active",children:"Active enrollees (paid, reserved, completed)"}),e.jsx(He,{value:"any",children:"Any enrollment status"}),e.jsx(He,{value:"paid",children:"Paid"}),e.jsx(He,{value:"reserved",children:"Reserved"}),e.jsx(He,{value:"scheduled_for_charge",children:"Scheduled for charge"}),e.jsx(He,{value:"pending_payment_method",children:"Pending payment method"}),e.jsx(He,{value:"payment_failed",children:"Payment failed"}),e.jsx(He,{value:"completed",children:"Completed"}),e.jsx(He,{value:"canceled",children:"Canceled"}),e.jsx(He,{value:"refunded",children:"Refunded"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Joined within"}),e.jsxs(is,{value:g.joinedWithinDays?String(g.joinedWithinDays):"all",onValueChange:Ge=>Ze("joinedWithinDays",Ge==="all"?null:Number(Ge)),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"Any time"}),e.jsx(He,{value:"30",children:"Last 30 days"}),e.jsx(He,{value:"60",children:"Last 60 days"}),e.jsx(He,{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(fn,{checked:g.respectOptOut,onCheckedChange:Ge=>Ze("respectOptOut",Ge)})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>b(U9e),children:"Reset"}),e.jsxs(B,{variant:"outline",size:"sm",className:"gap-2",onClick:()=>ke(g),disabled:C,children:[C?e.jsx(Ct,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(uo,{className:"h-3.5 w-3.5"}),"Refresh"]})]}),($e=j==null?void 0:j.sample)!=null&&$e.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:j.sample.map(Ge=>e.jsxs("p",{className:"truncate text-xs",children:[e.jsx("span",{className:"font-medium",children:Ge.name||"Member"})," ",e.jsx("span",{className:"text-muted-foreground",children:Ge.email})]},Ge.email))})]}):null]})]})]})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(ve,{children:[e.jsxs(bt,{className:"pb-4",children:[e.jsx(St,{className:"text-base",children:"Message"}),e.jsxs(kn,{children:["Personalize with merge tags: ",F6n.join(" ")]})]}),e.jsxs(Me,{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(J,{children:"Internal name"}),e.jsx(xe,{value:P,onChange:Ge=>M(Ge.target.value),placeholder:"August product update"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Subject line"}),e.jsx(xe,{value:I,onChange:Ge=>D(Ge.target.value),placeholder:"Big news for LevelUp members"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"From (must be a verified sender)"}),e.jsx(xe,{value:O,onChange:Ge=>V(Ge.target.value),placeholder:"hello@relevelup.com"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Reply-to"}),e.jsx(xe,{value:G,onChange:Ge=>$(Ge.target.value),placeholder:"support@relevelup.com"})]})]}),e.jsxs(Yr,{value:H,onValueChange:Ge=>Y(Ge),children:[e.jsxs(Zr,{children:[e.jsxs(Ht,{value:"rich",className:"gap-2",children:[e.jsx(un,{className:"h-3.5 w-3.5"})," Rich text"]}),e.jsxs(Ht,{value:"html",className:"gap-2",children:[e.jsx(UA,{className:"h-3.5 w-3.5"})," Paste HTML"]})]}),e.jsx(Gt,{value:"rich",className:"mt-3",children:e.jsx(BN,{content:Z,onChange:ne,minHeight:"320px",placeholder:"Write your message…"})}),e.jsxs(Gt,{value:"html",className:"mt-3 space-y-2",children:[e.jsx(Ms,{value:ce,onChange:Ge=>ie(Ge.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(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between space-y-0 pb-3",children:[e.jsxs(St,{className:"flex items-center gap-2 text-base",children:[e.jsx(ya,{className:"h-4 w-4"})," Preview"]}),e.jsx(Oe,{variant:"secondary",children:H==="html"?"Raw HTML":"Rich text"})]}),e.jsx(Me,{children:e.jsx("iframe",{title:"Email preview",srcDoc:O6n(pe),className:"h-[420px] w-full rounded-lg border bg-white"})})]}),e.jsx(ve,{children:e.jsxs(Me,{className:"space-y-4 pt-6",children:[me&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsxs("span",{children:[me.sent+me.failed," of ",me.total," processed"]}),e.jsxs("span",{className:"text-muted-foreground",children:[me.sent," sent",me.failed?` • ${me.failed} failed`:""]})]}),e.jsx(Fi,{value:me.total?(me.sent+me.failed)/me.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(J,{children:"Send a test to"}),e.jsx(xe,{value:te,onChange:Ge=>ae(Ge.target.value),className:"w-64"})]}),e.jsx(B,{variant:"outline",onClick:Ue,disabled:le,children:"Send test"}),e.jsx("div",{className:"flex-1"}),e.jsxs(B,{onClick:Xe,disabled:!Qe||le,size:"lg",className:"gap-2",children:[le?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Or,{className:"h-4 w-4"}),le?"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(J,{children:"Save as template"}),e.jsx(xe,{value:p,onChange:Ge=>f(Ge.target.value),placeholder:P||I||"Template name",className:"w-64"})]}),e.jsxs(B,{variant:"outline",className:"gap-2",onClick:Ye,disabled:y,children:[y?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(HM,{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(Gt,{value:"templates",className:"space-y-3",children:(ze||[]).length===0?e.jsx(ve,{children:e.jsxs(Me,{className:"flex flex-col items-center py-14 text-center",children:[e.jsx(pj,{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(Ge=>e.jsx(ve,{children:e.jsxs(Me,{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:Ge.name}),e.jsx(Oe,{variant:"secondary",className:"text-xs",children:Ge.editor_mode==="html"?"Raw HTML":"Rich text"})]}),e.jsxs("p",{className:"truncate text-xs text-muted-foreground",children:["Subject: ",Ge.subject||"—"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Updated ",Hs(new Date(Ge.updated_at),"MMM d, yyyy h:mm a")]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{size:"sm",className:"gap-2",onClick:()=>Ve(Ge),children:[e.jsx(Ho,{className:"h-3.5 w-3.5"})," Use template"]}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>qe(Ge),children:e.jsx(Sn,{className:"h-3.5 w-3.5"})})]})]})},Ge.id))}),e.jsx(Gt,{value:"history",className:"space-y-3",children:(Pe||[]).length===0?e.jsx(ve,{children:e.jsxs(Me,{className:"flex flex-col items-center py-14 text-center",children:[e.jsx(ln,{className:"mb-3 h-10 w-10 text-muted-foreground"}),e.jsx("p",{className:"font-medium",children:"No broadcasts sent yet"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Your sent member emails will show up here."})]})}):(Pe||[]).map(Ge=>e.jsx(ve,{children:e.jsxs(Me,{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:Ge.name}),e.jsxs(Oe,{variant:Ge.status==="sent"?"default":Ge.status==="sending"?"secondary":"outline",className:"gap-1 text-xs",children:[Ge.status==="sent"?e.jsx(Er,{className:"h-3 w-3"}):e.jsx(Xo,{className:"h-3 w-3"}),Ge.status]})]}),e.jsxs("p",{className:"truncate text-xs text-muted-foreground",children:["Subject: ",Ge.subject]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Hs(new Date(Ge.created_at),"MMM d, yyyy h:mm a")," • from ",Ge.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:Ge.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:Ge.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:Ge.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:[Ge.open_count??0,Ge.sent_count>0&&e.jsxs("span",{className:"ml-1 text-xs font-medium text-muted-foreground",children:[Math.round((Ge.open_count??0)/Ge.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:[Ge.click_count??0,Ge.sent_count>0&&e.jsxs("span",{className:"ml-1 text-xs font-medium text-muted-foreground",children:[Math.round((Ge.click_count??0)/Ge.sent_count*100),"%"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Clicks"})]}),Ge.failed_count>0&&e.jsx("div",{className:"flex items-center",children:e.jsx(B,{size:"sm",variant:"outline",disabled:le,onClick:()=>nt(Ge.id),children:"Retry failed"})})]})]})},Ge.id))})]})]})})}const B6n=["Headers","Footers","Seasonal","Holidays","Market Updates","Just Sold","Just Listed","Open House","Buyer Tips","Seller Tips","Testimonials","CTAs & Buttons","Dividers","General"];function U6n(){const s=Bt(),t=_.useRef(null),[n,r]=_.useState(""),[a,i]=_.useState("all"),[l,o]=_.useState(null),[c,d]=_.useState(!1),[u,h]=_.useState(!1),[m,p]=_.useState({title:"",description:"",image_url:"",category:"General",tags:"",is_active:!0,is_featured:!1}),{data:f=[],isLoading:y}=at({queryKey:["admin-newsletter-graphics"],queryFn:async()=>{const{data:O,error:V}=await q.from("newsletter_graphics").select("*").order("is_featured",{ascending:!1}).order("created_at",{ascending:!1});if(V)throw V;return O||[]}}),v=_.useMemo(()=>{const O=new Set(B6n);return f.forEach(V=>O.add(V.category)),Array.from(O).sort()},[f]),g=_.useMemo(()=>{const O=n.trim().toLowerCase();return f.filter(V=>a!=="all"&&V.category!==a?!1:O?V.title.toLowerCase().includes(O)||(V.description||"").toLowerCase().includes(O)||V.tags.some(G=>G.toLowerCase().includes(O)):!0)},[f,n,a]),b=()=>{p({title:"",description:"",image_url:"",category:"General",tags:"",is_active:!0,is_featured:!1}),o(null)},j=()=>{b(),d(!0)},S=O=>{o(O),p({title:O.title,description:O.description||"",image_url:O.image_url,category:O.category,tags:O.tags.join(", "),is_active:O.is_active,is_featured:O.is_featured}),d(!0)},C=async O=>{var V;if(!O.type.startsWith("image/")){se.error("Please choose an image file");return}if(O.size>15*1024*1024){se.error("Image must be under 15MB");return}h(!0);try{const G=((V=O.name.split(".").pop())==null?void 0:V.toLowerCase())||"png",$=`graphics-library/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${G}`,{error:H}=await q.storage.from("newsletter-content").upload($,O,{cacheControl:"31536000",upsert:!1,contentType:O.type});if(H)throw H;const{data:Y}=q.storage.from("newsletter-content").getPublicUrl($);p(Z=>({...Z,image_url:Y.publicUrl,title:Z.title||O.name.replace(/\.[^.]+$/,"").replace(/[-_]/g," ")})),se.success("Uploaded")}catch(G){se.error(G.message||"Upload failed")}finally{h(!1),t.current&&(t.current.value="")}},E=mt({mutationFn:async()=>{var G;if(!m.image_url)throw new Error("Please upload an image");if(!m.title.trim())throw new Error("Please add a title");const O=m.tags.split(",").map($=>$.trim()).filter(Boolean),V={title:m.title.trim(),description:m.description.trim()||null,image_url:m.image_url,category:m.category||"General",tags:O,is_active:m.is_active,is_featured:m.is_featured};if(l){const{error:$}=await q.from("newsletter_graphics").update(V).eq("id",l.id);if($)throw $}else{const{data:$}=await q.auth.getUser(),{error:H}=await q.from("newsletter_graphics").insert({...V,created_by:(G=$.user)==null?void 0:G.id});if(H)throw H}},onSuccess:()=>{se.success(l?"Updated":"Graphic added to library"),s.invalidateQueries({queryKey:["admin-newsletter-graphics"]}),s.invalidateQueries({queryKey:["newsletter-graphics-picker"]}),d(!1),b()},onError:O=>se.error(O.message||"Save failed")}),P=mt({mutationFn:async O=>{const{error:V}=await q.from("newsletter_graphics").delete().eq("id",O);if(V)throw V},onSuccess:()=>{se.success("Deleted"),s.invalidateQueries({queryKey:["admin-newsletter-graphics"]}),s.invalidateQueries({queryKey:["newsletter-graphics-picker"]})},onError:O=>se.error(O.message||"Delete failed")}),M=async O=>{const{error:V}=await q.from("newsletter_graphics").update({is_active:!O.is_active}).eq("id",O.id);V?se.error(V.message):(s.invalidateQueries({queryKey:["admin-newsletter-graphics"]}),s.invalidateQueries({queryKey:["newsletter-graphics-picker"]}))},I=async O=>{const{error:V}=await q.from("newsletter_graphics").update({is_featured:!O.is_featured}).eq("id",O.id);V?se.error(V.message):(s.invalidateQueries({queryKey:["admin-newsletter-graphics"]}),s.invalidateQueries({queryKey:["newsletter-graphics-picker"]}))},D=O=>{navigator.clipboard.writeText(O),se.success("URL copied")};return e.jsxs(zs,{children:[e.jsxs("div",{className:"p-4 md:p-6 max-w-7xl mx-auto space-y-5",children:[e.jsx(Wh,{title:"Newsletter Graphics Library",description:"Upload branded graphics agents can drop into their newsletters and email campaigns."}),e.jsx(ve,{children:e.jsxs(Me,{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(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{value:n,onChange:O=>r(O.target.value),placeholder:"Search graphics by title, tag, description...",className:"pl-9"})]}),e.jsxs(is,{value:a,onValueChange:i,children:[e.jsx(rs,{className:"w-full md:w-56",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All categories"}),v.map(O=>e.jsx(He,{value:O,children:O},O))]})]}),e.jsxs(B,{onClick:j,className:"gap-1.5 whitespace-nowrap",children:[e.jsx(jy,{className:"h-4 w-4"})," Add Graphic"]})]})}),y?e.jsx("div",{className:"flex justify-center py-16",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):g.length===0?e.jsx(ve,{children:e.jsxs(Me,{className:"py-16 text-center",children:[e.jsx(hc,{className:"h-10 w-10 mx-auto mb-3 text-muted-foreground/50"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:f.length===0?"No graphics uploaded yet — add your first one to get started.":"No graphics match your filters."}),f.length===0&&e.jsxs(B,{onClick:j,className:"gap-1.5",children:[e.jsx(jy,{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:g.map(O=>e.jsxs(ve,{className:`overflow-hidden group ${O.is_active?"":"opacity-60"}`,children:[e.jsxs("div",{className:"aspect-video bg-muted relative overflow-hidden",children:[e.jsx("img",{src:O.image_url,alt:O.title,loading:"lazy",className:"w-full h-full object-cover"}),O.is_featured&&e.jsxs(Oe,{className:"absolute top-2 left-2 gap-0.5 bg-amber-500 hover:bg-amber-500 text-white border-0",children:[e.jsx(Da,{className:"h-3 w-3 fill-current"})," Featured"]}),!O.is_active&&e.jsx(Oe,{variant:"secondary",className:"absolute top-2 right-2",children:"Hidden"})]}),e.jsxs(Me,{className:"p-3 space-y-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm truncate",children:O.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:O.category})]}),O.tags.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1",children:O.tags.slice(0,3).map(V=>e.jsx(Oe,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:V},V))}),e.jsxs("div",{className:"flex items-center justify-between pt-1 border-t",children:[e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>S(O),title:"Edit",children:e.jsx(Ya,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>I(O),title:O.is_featured?"Unfeature":"Feature",children:e.jsx(Da,{className:`h-3.5 w-3.5 ${O.is_featured?"fill-amber-500 text-amber-500":""}`})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>D(O.image_url),title:"Copy URL",children:e.jsx(Ia,{className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fn,{checked:O.is_active,onCheckedChange:()=>M(O)}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-7 w-7 text-destructive hover:text-destructive",onClick:async()=>{await Xi(`Delete "${O.title}"?`)&&P.mutate(O.id)},children:e.jsx(Sn,{className:"h-3.5 w-3.5"})})]})]})]})]},O.id))})]}),e.jsx(Ls,{open:c,onOpenChange:d,children:e.jsxs(Ps,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Ds,{children:l?"Edit Graphic":"Add New Graphic"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Image"}),e.jsx("input",{ref:t,type:"file",accept:"image/*",className:"hidden",onChange:O=>{var G;const V=(G=O.target.files)==null?void 0:G[0];V&&C(V)}}),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(B,{type:"button",variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-7 w-7",onClick:()=>p(O=>({...O,image_url:""})),children:e.jsx(Qn,{className:"h-3.5 w-3.5"})})]}):e.jsx("button",{type:"button",onClick:()=>{var O;return(O=t.current)==null?void 0:O.click()},disabled:u,className:"w-full mt-1.5 rounded-lg border-2 border-dashed border-border hover:border-primary/50 hover:bg-muted/40 transition-colors py-10 text-center disabled:opacity-60",children:u?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"h-8 w-8 mx-auto mb-2 animate-spin text-primary"}),e.jsx("p",{className:"text-sm",children:"Uploading..."})]}):e.jsxs(e.Fragment,{children:[e.jsx(Oa,{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(J,{htmlFor:"g-title",children:"Title *"}),e.jsx(xe,{id:"g-title",value:m.title,onChange:O=>p(V=>({...V,title:O.target.value})),placeholder:"e.g. Fall Market Update Banner"})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"g-desc",children:"Description"}),e.jsx(Ms,{id:"g-desc",value:m.description,onChange:O=>p(V=>({...V,description:O.target.value})),placeholder:"Short note about when to use this graphic",rows:2})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Category"}),e.jsxs(is,{value:m.category,onValueChange:O=>p(V=>({...V,category:O})),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsx(as,{children:v.map(O=>e.jsx(He,{value:O,children:O},O))})]})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"g-tags",children:"Tags (comma-separated)"}),e.jsx(xe,{id:"g-tags",value:m.tags,onChange:O=>p(V=>({...V,tags:O.target.value})),placeholder:"fall, autumn, banner"})]})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-md border p-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Featured"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show at top of the picker"})]}),e.jsx(fn,{checked:m.is_featured,onCheckedChange:O=>p(V=>({...V,is_featured:O}))})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-md border p-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Active"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Visible to agents"})]}),e.jsx(fn,{checked:m.is_active,onCheckedChange:O=>p(V=>({...V,is_active:O}))})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>d(!1),children:"Cancel"}),e.jsxs(B,{onClick:()=>E.mutate(),disabled:E.isPending,children:[E.isPending&&e.jsx(Ct,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),l?"Save Changes":"Add to Library"]})]})]})})]})}const ijt={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 q6n(){const{user:s}=hs(),{toast:t}=vi(),n=Fn(),r=Bt(),[a,i]=_.useState(""),[l,o]=_.useState("popular"),[c,d]=_.useState(!1),[u,h]=_.useState(""),[m,p]=_.useState(""),[f,y]=_.useState(!1),{data:v=[],isLoading:g}=at({queryKey:["wishlist-items",l,f],queryFn:async()=>{let E=q.from("wishlist_items").select("*");f&&s&&(E=E.eq("user_id",s.id)),l==="latest"?E=E.order("created_at",{ascending:!1}):l==="popular"?E=E.order("vote_count",{ascending:!1}):l==="trending"&&(E=E.order("vote_count",{ascending:!1}));const{data:P,error:M}=await E;if(M)throw M;const I=[...new Set((P==null?void 0:P.map(Y=>Y.user_id))||[])],{data:D}=await q.from("profiles").select("id, name").in("id",I),O=new Map((D==null?void 0:D.map(Y=>[Y.id,Y]))||[]);let V=[];if(s){const{data:Y}=await q.from("wishlist_votes").select("item_id").eq("user_id",s.id);V=(Y==null?void 0:Y.map(Z=>Z.item_id))||[]}const G=(P==null?void 0:P.map(Y=>Y.id))||[],{data:$}=await q.from("wishlist_comments").select("item_id").in("item_id",G),H=new Map;return $==null||$.forEach(Y=>{H.set(Y.item_id,(H.get(Y.item_id)||0)+1)}),P==null?void 0:P.map(Y=>{const Z=O.get(Y.user_id),ne=(Z==null?void 0:Z.name)||"Unknown";return{...Y,user_name:ne,user_initials:ne.split(" ").map(ce=>ce[0]).join("").toUpperCase().slice(0,2),has_voted:V.includes(Y.id),comment_count:H.get(Y.id)||0}})}}),b=mt({mutationFn:async({title:E,description:P})=>{const{error:M}=await q.from("wishlist_items").insert({user_id:s.id,title:E,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:E=>{t({title:"Error",description:E.message,variant:"destructive"})}}),j=mt({mutationFn:async({itemId:E,hasVoted:P})=>{if(P){const{error:M}=await q.from("wishlist_votes").delete().eq("item_id",E).eq("user_id",s.id);if(M)throw M;return{itemId:E,wasAdded:!1}}else{const{error:M}=await q.from("wishlist_votes").insert({item_id:E,user_id:s.id});if(M)throw M;return{itemId:E,wasAdded:!0}}},onSuccess:async E=>{if(r.invalidateQueries({queryKey:["wishlist-items"]}),E!=null&&E.wasAdded){const P=v.find(I=>I.id===E.itemId),M=((P==null?void 0:P.vote_count)||0)+1;q.functions.invoke("wishlist-notify",{body:{itemId:E.itemId,voteCount:M}}).catch(console.error)}},onError:E=>{t({title:"Error",description:E.message,variant:"destructive"})}}),S=v.filter(E=>E.title.toLowerCase().includes(a.toLowerCase())||E.description.toLowerCase().includes(a.toLowerCase())),C=()=>{if(!u.trim()||!m.trim()){t({title:"Error",description:"Please fill in both title and description.",variant:"destructive"});return}b.mutate({title:u.trim(),description:m.trim()})};return e.jsx(zs,{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(mS,{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(Ls,{open:c,onOpenChange:d,children:[e.jsx(nl,{asChild:!0,children:e.jsxs(B,{className:"gap-2",children:[e.jsx(rn,{className:"h-4 w-4"}),"Add Idea"]})}),e.jsxs(Ps,{children:[e.jsx(Os,{children:e.jsx(Ds,{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(J,{htmlFor:"title",children:"Title"}),e.jsx(xe,{id:"title",placeholder:"Give your idea a clear title...",value:u,onChange:E=>h(E.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"description",children:"Description"}),e.jsx(Ms,{id:"description",placeholder:"Describe your idea in detail. What problem does it solve? How would it help agents?",value:m,onChange:E=>p(E.target.value),rows:4})]}),e.jsx(B,{onClick:C,className:"w-full",disabled:b.isPending,children:b.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),"Submitting..."]}):"Submit Idea"})]})]})]})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 mb-6",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search ideas...",value:a,onChange:E=>i(E.target.value),className:"pl-10"})]}),e.jsx("div",{className:"flex gap-2",children:e.jsx(Yr,{value:l,onValueChange:E=>o(E),children:e.jsxs(Zr,{children:[e.jsx(Ht,{value:"popular",children:"Most Popular"}),e.jsx(Ht,{value:"latest",children:"Latest"}),e.jsx(Ht,{value:"trending",children:"Trending"})]})})})]}),e.jsx("div",{className:"flex items-center gap-2 mb-4",children:e.jsx(B,{variant:f?"default":"outline",size:"sm",onClick:()=>y(!f),children:f?"Show All Ideas":"My Ideas"})}),g?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Ct,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):S.length===0?e.jsxs("div",{className:"text-center py-12 bg-muted/30 rounded-lg",children:[e.jsx(mS,{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(B,{onClick:()=>d(!0),children:[e.jsx(rn,{className:"h-4 w-4 mr-2"}),"Add Idea"]})]}):e.jsx("div",{className:"space-y-3",children:S.map(E=>e.jsx("div",{className:"bg-card border rounded-lg p-4 hover:shadow-md transition-shadow cursor-pointer",onClick:()=>n(`/wishlist/${E.id}`),children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsxs("button",{onClick:P=>{P.stopPropagation(),j.mutate({itemId:E.id,hasVoted:E.has_voted||!1})},className:At("flex flex-col items-center justify-center min-w-[50px] py-2 px-3 rounded-lg border transition-colors",E.has_voted?"bg-primary/10 border-primary text-primary":"bg-muted/50 border-border hover:bg-muted"),children:[e.jsx(sp,{className:At("h-4 w-4",E.has_voted&&"fill-current")}),e.jsx("span",{className:"text-sm font-semibold",children:E.vote_count})]}),e.jsx(ja,{className:"h-10 w-10 bg-primary/20",children:e.jsx(Na,{className:"bg-primary/20 text-primary text-sm font-medium",children:E.user_initials})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("h3",{className:"font-semibold text-foreground",children:E.title}),e.jsx(Oe,{className:At("text-xs",ijt[E.status].color),children:ijt[E.status].label})]}),e.jsx("p",{className:"text-muted-foreground text-sm line-clamp-2",children:E.description}),e.jsxs("div",{className:"flex items-center gap-3 mt-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:E.user_name}),e.jsx("span",{children:"•"}),e.jsx("span",{children:new Date(E.created_at).toLocaleDateString()})]})]}),e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(Hi,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm",children:E.comment_count})]})]})},E.id))})]})})}const ojt={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 $6n(){const{itemId:s}=Li(),t=Fn(),{user:n}=hs(),{toast:r}=vi(),a=Bt(),[i,l]=_.useState(""),{data:o=!1}=at({queryKey:["user-is-admin",n==null?void 0:n.id],queryFn:async()=>{if(!n)return!1;const{data:v,error:g}=await q.from("user_roles").select("role").eq("user_id",n.id).eq("role","admin").maybeSingle();return!g&&!!v},enabled:!!n}),{data:c,isLoading:d}=at({queryKey:["wishlist-item",s],queryFn:async()=>{const{data:v,error:g}=await q.from("wishlist_items").select("*").eq("id",s).single();if(g)throw g;const{data:b}=await q.from("profiles").select("name").eq("id",v.user_id).single();let j=!1;if(n){const{data:S}=await q.from("wishlist_votes").select("id").eq("item_id",s).eq("user_id",n.id).maybeSingle();j=!!S}return{...v,user_name:(b==null?void 0:b.name)||"Unknown",user_initials:((b==null?void 0:b.name)||"U").split(" ").map(S=>S[0]).join("").toUpperCase().slice(0,2),has_voted:j}}}),{data:u=[],isLoading:h}=at({queryKey:["wishlist-comments",s],queryFn:async()=>{const{data:v,error:g}=await q.from("wishlist_comments").select("*").eq("item_id",s).order("created_at",{ascending:!0});if(g)throw g;const b=[...new Set((v==null?void 0:v.map(C=>C.user_id))||[])],{data:j}=await q.from("profiles").select("id, name").in("id",b),S=new Map((j==null?void 0:j.map(C=>[C.id,C]))||[]);return v==null?void 0:v.map(C=>{const E=S.get(C.user_id),P=(E==null?void 0:E.name)||"Unknown";return{...C,user_name:P,user_initials:P.split(" ").map(M=>M[0]).join("").toUpperCase().slice(0,2)}})}}),m=mt({mutationFn:async v=>{if(v){const{error:g}=await q.from("wishlist_votes").delete().eq("item_id",s).eq("user_id",n.id);if(g)throw g;return{wasAdded:!1}}else{const{error:g}=await q.from("wishlist_votes").insert({item_id:s,user_id:n.id});if(g)throw g;return{wasAdded:!0}}},onSuccess:async v=>{if(a.invalidateQueries({queryKey:["wishlist-item",s]}),a.invalidateQueries({queryKey:["wishlist-items"]}),v!=null&&v.wasAdded&&c){const g=(c.vote_count||0)+1;q.functions.invoke("wishlist-notify",{body:{itemId:s,voteCount:g}}).catch(console.error)}},onError:v=>{r({title:"Error",description:v.message,variant:"destructive"})}}),p=mt({mutationFn:async v=>{const{error:g}=await q.from("wishlist_comments").insert({item_id:s,user_id:n.id,content:v});if(g)throw g},onSuccess:()=>{a.invalidateQueries({queryKey:["wishlist-comments",s]}),l(""),r({title:"Comment added!"})},onError:v=>{r({title:"Error",description:v.message,variant:"destructive"})}}),f=mt({mutationFn:async v=>{const{error:g}=await q.from("wishlist_comments").delete().eq("id",v);if(g)throw g},onSuccess:()=>{a.invalidateQueries({queryKey:["wishlist-comments",s]}),r({title:"Comment deleted"})},onError:v=>{r({title:"Error",description:v.message,variant:"destructive"})}}),y=()=>{i.trim()&&p.mutate(i.trim())};return d?e.jsx(zs,{title:"Wishlist",children:e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsx(cn,{className:"h-8 w-32 mb-6"}),e.jsx(cn,{className:"h-48 w-full mb-6"}),e.jsx(cn,{className:"h-32 w-full"})]})}):c?e.jsx(zs,{title:"Wishlist",children:e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsxs(B,{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:At("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:At("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(Oe,{className:At("text-xs",ojt[c.status].color),children:ojt[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(ja,{className:"h-6 w-6",children:e.jsx(Na,{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(EEe,{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(B,{onClick:y,disabled:!i.trim()||p.isPending,size:"icon",className:"h-auto",children:p.isPending?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Or,{className:"h-4 w-4"})})]}),h?e.jsx("div",{className:"space-y-4",children:[1,2].map(v=>e.jsx(cn,{className:"h-20 w-full"},v))}):u.length===0?e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No comments yet. Be the first to share your thoughts!"}):e.jsx("div",{className:"space-y-4",children:u.map(v=>e.jsxs("div",{className:"flex gap-3 p-3 bg-muted/30 rounded-lg",children:[e.jsx(ja,{className:"h-8 w-8",children:e.jsx(Na,{className:"bg-primary/20 text-primary text-xs",children:v.user_initials})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-medium text-sm",children:v.user_name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(v.created_at).toLocaleDateString()})]}),e.jsx(qtt,{content:v.content,className:"text-sm text-foreground"})]}),(n==null?void 0:n.id)===v.user_id&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground hover:text-destructive",onClick:()=>f.mutate(v.id),children:e.jsx(Sn,{className:"h-4 w-4"})})]},v.id))})]})]})}):e.jsx(zs,{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(B,{variant:"link",onClick:()=>t("/wishlist"),children:"Go back to Wishlist"})]})})}const ljt={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"}},cjt=["open","under_review","planned","in_progress","launched","declined"];function V6n(){const{toast:s}=vi(),t=Fn(),n=Bt(),[r,a]=_.useState(""),[i,l]=_.useState("all"),[o,c]=_.useState(!1),[d,u]=_.useState(null),{data:h=[],isLoading:m}=at({queryKey:["admin-wishlist-items"],queryFn:async()=>{const{data:g,error:b}=await q.from("wishlist_items").select("*").order("vote_count",{ascending:!1});if(b)throw b;const j=[...new Set((g==null?void 0:g.map(I=>I.user_id))||[])],{data:S}=await q.from("profiles").select("id, name, email").in("id",j),C=new Map((S==null?void 0:S.map(I=>[I.id,I]))||[]),E=(g==null?void 0:g.map(I=>I.id))||[],{data:P}=await q.from("wishlist_comments").select("item_id").in("item_id",E),M=new Map;return P==null||P.forEach(I=>{M.set(I.item_id,(M.get(I.item_id)||0)+1)}),g==null?void 0:g.map(I=>{const D=C.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=mt({mutationFn:async({itemId:g,status:b})=>{const{error:j}=await q.from("wishlist_items").update({status:b}).eq("id",g);if(j)throw j},onSuccess:()=>{n.invalidateQueries({queryKey:["admin-wishlist-items"]}),s({title:"Status updated!"})},onError:g=>{s({title:"Error",description:g.message,variant:"destructive"})}}),f=mt({mutationFn:async g=>{const{error:b}=await q.from("wishlist_items").delete().eq("id",g);if(b)throw b},onSuccess:()=>{n.invalidateQueries({queryKey:["admin-wishlist-items"]}),c(!1),u(null),s({title:"Item deleted!"})},onError:g=>{s({title:"Error",description:g.message,variant:"destructive"})}}),y=h.filter(g=>{const b=g.title.toLowerCase().includes(r.toLowerCase())||g.description.toLowerCase().includes(r.toLowerCase())||g.user_name.toLowerCase().includes(r.toLowerCase()),j=i==="all"||g.status===i;return b&&j}),v={total:h.length,open:h.filter(g=>g.status==="open").length,inProgress:h.filter(g=>g.status==="in_progress").length,launched:h.filter(g=>g.status==="launched").length,highVotes:h.filter(g=>g.vote_count>=10).length};return e.jsx(zs,{title:"Admin - Wishlist",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(B,{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:v.total})]}),e.jsxs("div",{className:"bg-card border rounded-lg p-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Open"}),e.jsx("p",{className:"text-2xl font-bold text-blue-600",children:v.open})]}),e.jsxs("div",{className:"bg-card border rounded-lg p-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"In Progress"}),e.jsx("p",{className:"text-2xl font-bold text-orange-600",children:v.inProgress})]}),e.jsxs("div",{className:"bg-card border rounded-lg p-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Launched"}),e.jsx("p",{className:"text-2xl font-bold text-green-600",children:v.launched})]}),e.jsxs("div",{className:"bg-card border rounded-lg p-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"10+ Votes"}),e.jsx("p",{className:"text-2xl font-bold text-primary",children:v.highVotes})]})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search ideas, users...",value:r,onChange:g=>a(g.target.value),className:"pl-10"})]}),e.jsxs(is,{value:i,onValueChange:g=>l(g),children:[e.jsx(rs,{className:"w-[180px]",children:e.jsx(ls,{placeholder:"Filter by status"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Statuses"}),cjt.map(g=>e.jsx(He,{value:g,children:ljt[g].label},g))]})]})]}),m?e.jsx("div",{className:"space-y-2",children:[1,2,3,4,5].map(g=>e.jsx(cn,{className:"h-16 w-full"},g))}):e.jsx("div",{className:"bg-card border rounded-lg overflow-hidden",children:e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{className:"w-[60px]",children:"Votes"}),e.jsx(Pt,{children:"Title"}),e.jsx(Pt,{className:"hidden md:table-cell",children:"Submitted By"}),e.jsx(Pt,{className:"hidden sm:table-cell",children:"Comments"}),e.jsx(Pt,{children:"Status"}),e.jsx(Pt,{className:"w-[100px]",children:"Actions"})]})}),e.jsx(Ka,{children:y.length===0?e.jsx(pn,{children:e.jsx(gt,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No items found"})}):y.map(g=>e.jsxs(pn,{className:At(g.vote_count>=10&&"bg-primary/5"),children:[e.jsx(gt,{children:e.jsx(Oe,{variant:g.vote_count>=10?"default":"secondary",children:g.vote_count})}),e.jsx(gt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium line-clamp-1",children:g.title}),e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-1",children:g.description})]})}),e.jsx(gt,{className:"hidden md:table-cell",children:e.jsxs("div",{children:[e.jsx("p",{className:"text-sm",children:g.user_name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:g.user_email})]})}),e.jsx(gt,{className:"hidden sm:table-cell",children:g.comment_count}),e.jsx(gt,{children:e.jsxs(is,{value:g.status,onValueChange:b=>p.mutate({itemId:g.id,status:b}),children:[e.jsx(rs,{className:"w-[140px] h-8",children:e.jsx(ls,{})}),e.jsx(as,{children:cjt.map(b=>e.jsx(He,{value:b,children:ljt[b].label},b))})]})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>window.open(`/wishlist/${g.id}`,"_blank"),children:e.jsx(wr,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive",onClick:()=>{u(g.id),c(!0)},children:e.jsx(Sn,{className:"h-4 w-4"})})]})})]},g.id))})]})}),e.jsx(Ls,{open:o,onOpenChange:c,children:e.jsxs(Ps,{children:[e.jsx(Os,{children:e.jsx(Ds,{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(B,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:()=>d&&f.mutate(d),disabled:f.isPending,children:f.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),"Deleting..."]}):"Delete"})]})]})})]})})}function H6n(){const{user:s}=hs(),[t,n]=_.useState([]),[r,a]=_.useState(!0),[i,l]=_.useState(!1),[o,c]=_.useState(null),[d,u]=_.useState(!1),[h,m]=_.useState(null),[p,f]=_.useState(""),[y,v]=_.useState(""),[g,b]=_.useState(""),[j,S]=_.useState(""),[C,E]=_.useState(""),[P,M]=_.useState(!1),[I,D]=_.useState(""),[O,V]=_.useState("once"),[G,$]=_.useState([]),[H,Y]=_.useState([]),[Z,ne]=_.useState(!1),[ce,ie]=_.useState(!1),[te,ae]=_.useState([]),[le,be]=_.useState({total:0,dismissed:0});_.useEffect(()=>{me()},[]);const me=async()=>{const{data:nt,error:$e}=await q.from("levelup_briefs").select("*").order("created_at",{ascending:!1});$e?(se.error("Failed to fetch briefs"),console.error($e)):n(nt||[]),a(!1)},he=()=>{f(""),v(""),b(""),S(""),E(""),M(!1),D(new Date().toISOString().slice(0,16)),V("once"),$([]),Y([]),c(null)},pe=()=>{he(),l(!0)},Ce=async nt=>{c(nt),f(nt.title),v(nt.description||""),b(nt.video_url||""),S(nt.graphic_url||""),E(nt.graphic_link_url||""),M(nt.is_published),D(nt.publish_date.slice(0,16)),V(nt.show_frequency);const{data:$e}=await q.from("levelup_brief_links").select("*").eq("brief_id",nt.id).order("sort_order");$(($e==null?void 0:$e.map(ct=>({title:ct.title,url:ct.url})))||[]);const{data:Ge}=await q.from("levelup_brief_polls").select("*").eq("brief_id",nt.id).order("sort_order");if(Ge){const ct=[];for(const xt of Ge){const{data:qt}=await q.from("levelup_brief_poll_options").select("*").eq("poll_id",xt.id).order("sort_order");ct.push({question:xt.question,poll_type:xt.poll_type,options:(qt==null?void 0:qt.map(Vt=>Vt.option_text))||[]})}Y(ct)}l(!0)},Ae=async nt=>{var Ge;const $e=(Ge=nt.target.files)==null?void 0:Ge[0];if($e){ne(!0);try{const ct=await q.functions.invoke("bunny-upload",{body:{action:"create",title:$e.name.replace(/\.[^/.]+$/,"")}});if(ct.error)throw ct.error;const{videoId:xt,libraryId:qt}=ct.data,Vt=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:xt}});if(Vt.error)throw Vt.error;const{uploadUrl:Xt,apiKey:fs}=Vt.data,Ft=new XMLHttpRequest;await new Promise((Ts,vt)=>{Ft.upload.addEventListener("progress",$s=>{if($s.lengthComputable){const As=Math.round($s.loaded/$s.total*100);console.log("Upload progress:",As)}}),Ft.addEventListener("load",()=>{Ft.status>=200&&Ft.status<300?Ts():vt(new Error(`Upload failed with status ${Ft.status}`))}),Ft.addEventListener("error",()=>vt(new Error("Upload failed"))),Ft.open("PUT",Xt),Ft.setRequestHeader("AccessKey",fs),Ft.send($e)});const wt=`https://player.mediadelivery.net/embed/${qt}/${xt}`;b(wt),se.success("Video uploaded successfully! It may take a few minutes to process.")}catch(ct){console.error("Upload error:",ct),se.error("Failed to upload video")}finally{ne(!1)}}},Pe=async()=>{if(!p.trim()){se.error("Title is required");return}try{let nt;if(o){const{error:$e}=await q.from("levelup_briefs").update({title:p,description:y||null,video_url:g||null,graphic_url:j||null,graphic_link_url:C||null,is_published:P,publish_date:I,show_frequency:O}).eq("id",o.id);if($e)throw $e;nt=o.id,await q.from("levelup_brief_links").delete().eq("brief_id",nt);const{data:Ge}=await q.from("levelup_brief_polls").select("id").eq("brief_id",nt);if(Ge)for(const ct of Ge)await q.from("levelup_brief_poll_options").delete().eq("poll_id",ct.id);await q.from("levelup_brief_polls").delete().eq("brief_id",nt)}else{const{data:$e,error:Ge}=await q.from("levelup_briefs").insert({title:p,description:y||null,video_url:g||null,graphic_url:j||null,graphic_link_url:C||null,is_published:P,publish_date:I,show_frequency:O,created_by:s==null?void 0:s.id}).select().single();if(Ge)throw Ge;nt=$e.id}if(G.length>0){const $e=G.map((Ge,ct)=>({brief_id:nt,title:Ge.title,url:Ge.url,sort_order:ct}));await q.from("levelup_brief_links").insert($e)}for(let $e=0;$e0){const qt=Ge.options.map((Vt,Xt)=>({poll_id:ct.id,option_text:Vt,sort_order:Xt}));await q.from("levelup_brief_poll_options").insert(qt)}}se.success(o?"Brief updated":"Brief created"),l(!1),he(),me()}catch(nt){console.error("Error saving brief:",nt),se.error("Failed to save brief")}},ze=async nt=>{if(await Xi("Are you sure you want to delete this brief?"))try{const{error:$e}=await q.from("levelup_briefs").delete().eq("id",nt);if($e)throw $e;se.success("Brief deleted"),me()}catch($e){console.error("Error deleting brief:",$e),se.error("Failed to delete brief")}},ke=async nt=>{m(nt);const{count:$e}=await q.from("levelup_brief_views").select("*",{count:"exact",head:!0}).eq("brief_id",nt.id),{count:Ge}=await q.from("levelup_brief_views").select("*",{count:"exact",head:!0}).eq("brief_id",nt.id).not("dismissed_at","is",null);be({total:$e||0,dismissed:Ge||0});const{data:ct}=await q.from("levelup_brief_polls").select("*").eq("brief_id",nt.id).order("sort_order");if(ct){const xt=[];for(const qt of ct){const{data:Vt}=await q.from("levelup_brief_poll_options").select("*").eq("poll_id",qt.id).order("sort_order"),{data:Xt}=await q.from("levelup_brief_poll_responses").select("option_id, user_id").eq("poll_id",qt.id),fs=[...new Set((Xt==null?void 0:Xt.map($s=>$s.user_id))||[])];let Ft={};if(fs.length>0){const{data:$s}=await q.from("profiles").select("id, name, email").in("id",fs);$s&&$s.forEach(As=>{Ft[As.id]=As.name||As.email||"Unknown"})}const wt=(Xt||[]).map($s=>({optionId:$s.option_id,userName:Ft[$s.user_id]||"Unknown",userId:$s.user_id})),Ts={};let vt=0;Vt&&Vt.forEach($s=>{const As=(Xt==null?void 0:Xt.filter(jn=>jn.option_id===$s.id).length)||0;Ts[$s.id]=As,vt+=As}),xt.push({...qt,options:Vt||[],results:Ts,respondents:wt,totalResponses:qt.poll_type==="single"?new Set(Xt==null?void 0:Xt.map($s=>$s.user_id)).size:vt})}ae(xt)}u(!0)},Ze=()=>{$([...G,{title:"",url:""}])},Se=(nt,$e,Ge)=>{const ct=[...G];ct[nt][$e]=Ge,$(ct)},Fe=nt=>{$(G.filter(($e,Ge)=>Ge!==nt))},Ne=()=>{Y([...H,{question:"",poll_type:"single",options:["",""]}])},Ye=(nt,$e)=>{const Ge=[...H];Ge[nt].question=$e,Y(Ge)},Ve=(nt,$e)=>{const Ge=[...H];Ge[nt].poll_type=$e,Y(Ge)},qe=nt=>{const $e=[...H];$e[nt].options.push(""),Y($e)},Qe=(nt,$e,Ge)=>{const ct=[...H];ct[nt].options[$e]=Ge,Y(ct)},Ue=(nt,$e)=>{const Ge=[...H];Ge[nt].options=Ge[nt].options.filter((ct,xt)=>xt!==$e),Y(Ge)},Xe=nt=>{Y(H.filter(($e,Ge)=>Ge!==nt))};return e.jsxs(zs,{title:"The LevelUp Brief",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsx(Wh,{title:"The LevelUp Brief",description:"Create engaging popup briefs for your agents",children:e.jsxs(B,{onClick:pe,children:[e.jsx(rn,{className:"h-4 w-4 mr-2"}),"Create Brief"]})}),e.jsx(ve,{children:e.jsx(Me,{className:"p-0",children:e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"Title"}),e.jsx(Pt,{children:"Status"}),e.jsx(Pt,{children:"Frequency"}),e.jsx(Pt,{children:"Publish Date"}),e.jsx(Pt,{className:"text-right",children:"Actions"})]})}),e.jsx(Ka,{children:r?e.jsx(pn,{children:e.jsx(gt,{colSpan:5,className:"text-center py-8",children:"Loading..."})}):t.length===0?e.jsx(pn,{children:e.jsx(gt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No briefs created yet"})}):t.map(nt=>e.jsxs(pn,{children:[e.jsx(gt,{className:"font-medium",children:nt.title}),e.jsx(gt,{children:e.jsx(Oe,{variant:nt.is_published?"default":"secondary",children:nt.is_published?"Published":"Draft"})}),e.jsx(gt,{className:"capitalize",children:nt.show_frequency.replace("_"," ")}),e.jsx(gt,{children:Hs(new Date(nt.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(B,{variant:"ghost",size:"icon",onClick:()=>ke(nt),children:e.jsx(bl,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>Ce(nt),children:e.jsx(wp,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>ze(nt.id),children:e.jsx(Sn,{className:"h-4 w-4 text-destructive"})})]})})]},nt.id))})]})})})]}),e.jsx(Ls,{open:i,onOpenChange:l,children:e.jsxs(Ps,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Ds,{children:o?"Edit Brief":"Create New Brief"})}),e.jsxs(Yr,{defaultValue:"content",className:"w-full",children:[e.jsxs(Zr,{className:"grid w-full grid-cols-4",children:[e.jsx(Ht,{value:"content",children:"Content"}),e.jsx(Ht,{value:"media",children:"Media"}),e.jsx(Ht,{value:"links",children:"Links"}),e.jsx(Ht,{value:"polls",children:"Polls"})]}),e.jsxs(Gt,{value:"content",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Title *"}),e.jsx(xe,{value:p,onChange:nt=>f(nt.target.value),placeholder:"What's happening at LevelUp..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Description"}),e.jsx(BN,{content:y,onChange:nt=>v(nt),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(J,{children:"Publish Date"}),e.jsx(xe,{type:"datetime-local",value:I,onChange:nt=>D(nt.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Show Frequency"}),e.jsxs(is,{value:O,onValueChange:V,children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"once",children:"Once (until dismissed)"}),e.jsx(He,{value:"every_login",children:"Every login"}),e.jsx(He,{value:"daily",children:"Daily"})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(fn,{checked:P,onCheckedChange:M}),e.jsx(J,{children:"Publish immediately"})]})]}),e.jsxs(Gt,{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(J,{children:"Upload Video to Bunny.net"}),e.jsx("div",{className:"flex gap-2",children:e.jsx(xe,{type:"file",accept:"video/*",onChange:Ae,disabled:Z})}),Z&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Uploading..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Or paste embed URL"}),e.jsx(xe,{value:g,onChange:nt=>b(nt.target.value),placeholder:"https://iframe.mediadelivery.net/embed/..."})]}),g&&e.jsx("div",{className:"aspect-video rounded-lg overflow-hidden bg-muted",children:e.jsx("iframe",{src:g,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(J,{children:"Upload Image"}),e.jsx("div",{className:"flex gap-2",children:e.jsx(xe,{type:"file",accept:"image/*",onChange:async nt=>{var Ge;const $e=(Ge=nt.target.files)==null?void 0:Ge[0];if($e){ie(!0);try{const ct=$e.name.split(".").pop(),xt=`brief-graphics/${Date.now()}.${ct}`,{error:qt}=await q.storage.from("banner-images").upload(xt,$e,{upsert:!0});if(qt)throw qt;const{data:Vt}=q.storage.from("banner-images").getPublicUrl(xt);S(Vt.publicUrl),se.success("Image uploaded!")}catch(ct){console.error(ct),se.error("Failed to upload image")}finally{ie(!1)}}},disabled:ce})}),ce&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Uploading..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Or paste Image URL"}),e.jsx(xe,{value:j,onChange:nt=>S(nt.target.value),placeholder:"https://example.com/image.png"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Click-through Link (optional)"}),e.jsx(xe,{value:C,onChange:nt=>E(nt.target.value),placeholder:"https://example.com/landing-page"})]}),j&&e.jsx("div",{className:"rounded-lg overflow-hidden bg-muted border",children:e.jsx("img",{src:j,alt:"Brief graphic preview",className:"w-full object-contain max-h-64"})})]})]}),e.jsxs(Gt,{value:"links",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(J,{children:"Quick Links"}),e.jsxs(B,{variant:"outline",size:"sm",onClick:Ze,children:[e.jsx(rn,{className:"h-4 w-4 mr-1"}),"Add Link"]})]}),G.map((nt,$e)=>e.jsxs("div",{className:"flex gap-2 items-start",children:[e.jsx(xe,{value:nt.title,onChange:Ge=>Se($e,"title",Ge.target.value),placeholder:"Link title",className:"flex-1"}),e.jsx(xe,{value:nt.url,onChange:Ge=>Se($e,"url",Ge.target.value),placeholder:"https://...",className:"flex-[2]"}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>Fe($e),children:e.jsx(Sn,{className:"h-4 w-4 text-destructive"})})]},$e)),G.length===0&&e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No links added yet"})]}),e.jsxs(Gt,{value:"polls",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(J,{children:"Polls"}),e.jsxs(B,{variant:"outline",size:"sm",onClick:Ne,children:[e.jsx(rn,{className:"h-4 w-4 mr-1"}),"Add Poll"]})]}),H.map((nt,$e)=>e.jsx(ve,{className:"p-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(xe,{value:nt.question,onChange:Ge=>Ye($e,Ge.target.value),placeholder:"Poll question...",className:"flex-1 mr-2"}),e.jsxs(is,{value:nt.poll_type,onValueChange:Ge=>Ve($e,Ge),children:[e.jsx(rs,{className:"w-32",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"single",children:"Single"}),e.jsx(He,{value:"multi",children:"Multi-select"})]})]}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>Xe($e),children:e.jsx(Sn,{className:"h-4 w-4 text-destructive"})})]}),e.jsxs("div",{className:"space-y-2 pl-4",children:[nt.options.map((Ge,ct)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{value:Ge,onChange:xt=>Qe($e,ct,xt.target.value),placeholder:`Option ${ct+1}`}),nt.options.length>2&&e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>Ue($e,ct),children:e.jsx(Sn,{className:"h-4 w-4 text-muted-foreground"})})]},ct)),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>qe($e),children:[e.jsx(rn,{className:"h-4 w-4 mr-1"}),"Add Option"]})]})]})},$e)),H.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(B,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(B,{onClick:Pe,children:o?"Update Brief":"Create Brief"})]})]})}),e.jsx(Ls,{open:d,onOpenChange:u,children:e.jsxs(Ps,{className:"max-w-2xl",children:[e.jsx(Os,{children:e.jsxs(Ds,{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(ve,{children:[e.jsx(bt,{className:"pb-2",children:e.jsx(St,{className:"text-sm font-medium text-muted-foreground",children:"Total Views"})}),e.jsx(Me,{children:e.jsx("p",{className:"text-2xl font-bold",children:le.total})})]}),e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-2",children:e.jsx(St,{className:"text-sm font-medium text-muted-foreground",children:"Dismissed"})}),e.jsx(Me,{children:e.jsx("p",{className:"text-2xl font-bold",children:le.dismissed})})]})]}),te.length>0?e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"font-semibold",children:"Poll Results"}),te.map(nt=>e.jsxs(ve,{className:"p-4",children:[e.jsx("h4",{className:"font-medium mb-3",children:nt.question}),e.jsx("div",{className:"space-y-2",children:nt.options.map($e=>{const Ge=nt.results[$e.id]||0,ct=nt.totalResponses>0?Math.round(Ge/nt.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:$e.option_text}),e.jsxs("span",{className:"text-muted-foreground",children:[Ge," (",ct,"%)"]})]}),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:`${ct}%`}})}),Ge>0&&e.jsx("div",{className:"flex flex-wrap gap-1 pt-1",children:(nt.respondents||[]).filter(xt=>xt.optionId===$e.id).map((xt,qt)=>e.jsx(Oe,{variant:"secondary",className:"text-xs font-normal",children:xt.userName},qt))})]},$e.id)})})]},nt.id))]}):e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No polls in this brief"})]})]})})]})}const G6n=()=>{const{user:s}=hs(),{toast:t}=vi(),n=Bt(),[r,a]=_.useState(!1),[i,l]=_.useState(null),[o,c]=_.useState({name:"",description:"",signup_link_url:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),[d,u]=_.useState(null),[h,m]=_.useState(""),{data:p=[],isLoading:f}=at({queryKey:["additional-services-admin"],queryFn:async()=>{const{data:C,error:E}=await q.from("additional_services").select("*").order("publish_date",{ascending:!1});if(E)throw E;return C}}),y=mt({mutationFn:async C=>{let E=C.existingImageUrl;if(C.image){const M=C.image.name.split(".").pop(),I=`${Date.now()}-${Math.random().toString(36).substring(7)}.${M}`,{error:D}=await q.storage.from("service-images").upload(I,C.image);if(D)throw D;const{data:O}=q.storage.from("service-images").getPublicUrl(I);E=O.publicUrl}const P={name:C.item.name,description:C.item.description||null,preview_image_url:E,signup_link_url:C.item.signup_link_url,publish_date:C.item.publish_date?new Date(C.item.publish_date).toISOString():new Date().toISOString(),is_published:C.item.is_published,created_by:s==null?void 0:s.id};if(C.itemId){const{error:M}=await q.from("additional_services").update(P).eq("id",C.itemId);if(M)throw M}else{const{error:M}=await q.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),g()},onError:C=>{t({title:"Error saving service",description:C.message,variant:"destructive"})}}),v=mt({mutationFn:async C=>{const{error:E}=await q.from("additional_services").delete().eq("id",C);if(E)throw E},onSuccess:()=>{n.invalidateQueries({queryKey:["additional-services-admin"]}),n.invalidateQueries({queryKey:["additional-services"]}),t({title:"Service deleted"})},onError:C=>{t({title:"Error deleting service",description:C.message,variant:"destructive"})}}),g=()=>{c({name:"",description:"",signup_link_url:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),u(null),m(""),l(null)},b=C=>{l(C),c({name:C.name,description:C.description||"",signup_link_url:C.signup_link_url,publish_date:C.publish_date?new Date(C.publish_date).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],is_published:C.is_published}),m(C.preview_image_url||""),a(!0)},j=C=>{var P;const E=(P=C.target.files)==null?void 0:P[0];E&&(u(E),m(URL.createObjectURL(E)))},S=C=>{if(C.preventDefault(),!o.name.trim()){t({title:"Name is required",variant:"destructive"});return}if(!o.signup_link_url.trim()){t({title:"Signup link URL is required",variant:"destructive"});return}y.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(zs,{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(ve,{children:[e.jsx(bt,{className:"pb-2",children:e.jsx(St,{className:"text-sm font-medium text-muted-foreground",children:"Total Services"})}),e.jsx(Me,{children:e.jsx("div",{className:"text-2xl font-bold",children:p.length})})]}),e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-2",children:e.jsx(St,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Me,{children:e.jsx("div",{className:"text-2xl font-bold",children:p.filter(C=>C.is_published).length})})]})]}),e.jsxs(Ls,{open:r,onOpenChange:C=>{a(C),C||g()},children:[e.jsx(nl,{asChild:!0,children:e.jsxs(B,{className:"gap-2",children:[e.jsx(rn,{className:"h-4 w-4"}),"Add Service"]})}),e.jsxs(Ps,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Ds,{children:i?"Edit Service":"Add New Service"})}),e.jsxs("form",{onSubmit:S,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"name",children:"Name *"}),e.jsx(xe,{id:"name",value:o.name,onChange:C=>c({...o,name:C.target.value}),placeholder:"Enter service name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Description"}),e.jsx(BN,{content:o.description,onChange:C=>c({...o,description:C}),placeholder:"Enter description",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"signup_link_url",children:"Signup Link URL *"}),e.jsx(xe,{id:"signup_link_url",type:"url",value:o.signup_link_url,onChange:C=>c({...o,signup_link_url:C.target.value}),placeholder:"https://example.com/signup"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(xe,{id:"publish_date",type:"date",value:o.publish_date,onChange:C=>c({...o,publish_date:C.target.value})})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(fn,{id:"is_published",checked:o.is_published,onCheckedChange:C=>c({...o,is_published:C})}),e.jsx(J,{htmlFor:"is_published",children:"Published"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{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(B,{type:"button",variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-6 w-6",onClick:()=>{u(null),m("")},children:e.jsx(Qn,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-4 text-center",children:[e.jsx(hc,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx(xe,{type:"file",accept:"image/*",onChange:j,className:"cursor-pointer"})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(B,{type:"submit",disabled:y.isPending,children:y.isPending?"Saving...":i?"Update":"Create"})]})]})]})]})]}),e.jsx(ve,{children:e.jsx(Me,{className:"p-0",children:f?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):p.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:'No services yet. Click "Add Service" to create your first one.'}):e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{className:"w-16",children:"Preview"}),e.jsx(Pt,{children:"Name"}),e.jsx(Pt,{children:"Signup Link"}),e.jsx(Pt,{children:"Publish Date"}),e.jsx(Pt,{children:"Status"}),e.jsx(Pt,{className:"text-right",children:"Actions"})]})}),e.jsx(Ka,{children:p.map(C=>e.jsxs(pn,{children:[e.jsx(gt,{children:C.preview_image_url?e.jsx("img",{src:C.preview_image_url,alt:"",className:"w-12 h-12 object-cover rounded"}):e.jsx("div",{className:"w-12 h-12 bg-muted rounded flex items-center justify-center",children:e.jsx(hc,{className:"h-5 w-5 text-muted-foreground"})})}),e.jsx(gt,{className:"font-medium",children:C.name}),e.jsx(gt,{children:e.jsxs("a",{href:C.signup_link_url,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline flex items-center gap-1",children:[e.jsx(wr,{className:"h-3 w-3"}),"Link"]})}),e.jsx(gt,{children:new Date(C.publish_date).toLocaleDateString()}),e.jsx(gt,{children:e.jsx(Oe,{variant:C.is_published?"default":"secondary",children:C.is_published?"Published":"Draft"})}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>b(C),children:e.jsx(Ya,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:async()=>{await Xi("Are you sure you want to delete this service?")&&v.mutate(C.id)},children:e.jsx(Sn,{className:"h-4 w-4 text-destructive"})})]})})]},C.id))})]})})})]})})};function W6n(){const{toast:s}=vi(),[t,n]=_.useState([]),[r,a]=_.useState(!0),[i,l]=_.useState(!1),[o,c]=_.useState(!1),[d,u]=_.useState({name:"",promotionCode:"",discountType:"percent",percentOff:"",amountOff:"",duration:"once",durationInMonths:""});_.useEffect(()=>{h()},[]);const h=async()=>{try{const{data:v,error:g}=await q.functions.invoke("stripe-manage-coupons",{body:{action:"list"}});if(g)throw g;n(v.coupons||[])}catch(v){console.error("Error fetching coupons:",v),s({title:"Error",description:"Failed to load coupons",variant:"destructive"})}finally{a(!1)}},m=async()=>{if(!d.name){s({title:"Error",description:"Please enter a coupon name",variant:"destructive"});return}if(d.discountType==="percent"&&!d.percentOff){s({title:"Error",description:"Please enter a percent off value",variant:"destructive"});return}if(d.discountType==="amount"&&!d.amountOff){s({title:"Error",description:"Please enter an amount off value",variant:"destructive"});return}if(d.duration==="repeating"&&!d.durationInMonths){s({title:"Error",description:"Please enter duration in months",variant:"destructive"});return}l(!0);try{const v={action:"create",name:d.name,duration:d.duration,promotion_code:d.promotionCode.trim()||void 0};d.discountType==="percent"?v.percent_off=parseFloat(d.percentOff):(v.amount_off=Math.round(parseFloat(d.amountOff)*100),v.currency="usd"),d.duration==="repeating"&&(v.duration_in_months=parseInt(d.durationInMonths));const{data:g,error:b}=await q.functions.invoke("stripe-manage-coupons",{body:v});if(b)throw b;s({title:"Success",description:"Coupon created successfully"}),c(!1),u({name:"",promotionCode:"",discountType:"percent",percentOff:"",amountOff:"",duration:"once",durationInMonths:""}),h()}catch(v){console.error("Error creating coupon:",v),s({title:"Error",description:v.message||"Failed to create coupon",variant:"destructive"})}finally{l(!1)}},p=async v=>{if(await Xi("Are you sure you want to delete this coupon?"))try{const{error:g}=await q.functions.invoke("stripe-manage-coupons",{body:{action:"delete",couponId:v}});if(g)throw g;s({title:"Success",description:"Coupon deleted successfully"}),h()}catch(g){console.error("Error deleting coupon:",g),s({title:"Error",description:g.message||"Failed to delete coupon",variant:"destructive"})}},f=v=>v.percent_off?`${v.percent_off}% off`:v.amount_off?`$${(v.amount_off/100).toFixed(2)} off`:"N/A",y=v=>{switch(v.duration){case"once":return"Once";case"forever":return"Forever";case"repeating":return`${v.duration_in_months} months`;default:return v.duration}};return e.jsx(zs,{title:"Subscription Discounts",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Wh,{title:"Subscription Discounts",description:"Create and manage discount coupons for subscriptions",children:e.jsxs(Ls,{open:o,onOpenChange:c,children:[e.jsx(nl,{asChild:!0,children:e.jsxs(B,{children:[e.jsx(rn,{className:"mr-2 h-4 w-4"}),"Create Coupon"]})}),e.jsxs(Ps,{children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Create New Coupon"}),e.jsx(_r,{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(J,{children:"Promotion Code (what users will type)"}),e.jsx(xe,{placeholder:"e.g., BROKERAGE50",value:d.promotionCode,onChange:v=>u({...d,promotionCode:v.target.value.toUpperCase().replace(/[^A-Z0-9]/g,"")}),className:"font-mono uppercase"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Letters and numbers only. This is the code users enter at checkout."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Coupon Name (internal label)"}),e.jsx(xe,{placeholder:"e.g., 50% Off Brokerage Launch",value:d.name,onChange:v=>u({...d,name:v.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Discount Type"}),e.jsxs(is,{value:d.discountType,onValueChange:v=>{const g=v==="amount"&&d.duration==="forever"?"once":d.duration;u({...d,discountType:v,duration:g})},children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"percent",children:e.jsxs("span",{className:"flex items-center",children:[e.jsx(F_,{className:"mr-2 h-4 w-4"}),"Percentage Off"]})}),e.jsx(He,{value:"amount",children:e.jsxs("span",{className:"flex items-center",children:[e.jsx(yd,{className:"mr-2 h-4 w-4"}),"Fixed Amount Off"]})})]})]})]}),d.discountType==="percent"?e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Percent Off"}),e.jsxs("div",{className:"relative",children:[e.jsx(xe,{type:"number",min:"1",max:"100",placeholder:"20",value:d.percentOff,onChange:v=>u({...d,percentOff:v.target.value})}),e.jsx("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground",children:"%"})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Amount Off (USD)"}),e.jsxs("div",{className:"relative",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground",children:"$"}),e.jsx(xe,{type:"number",min:"1",placeholder:"10.00",className:"pl-7",value:d.amountOff,onChange:v=>u({...d,amountOff:v.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Duration"}),e.jsxs(is,{value:d.duration,onValueChange:v=>u({...d,duration:v}),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"once",children:"Once (first payment only)"}),e.jsx(He,{value:"repeating",children:"Multiple months"}),e.jsxs(He,{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(J,{children:"Number of Months"}),e.jsx(xe,{type:"number",min:"1",placeholder:"3",value:d.durationInMonths,onChange:v=>u({...d,durationInMonths:v.target.value})})]}),e.jsx(B,{onClick:m,disabled:i,className:"w-full",children:i?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating..."]}):"Create Coupon"})]})]})]})}),e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsx(St,{children:"Active Coupons"}),e.jsx(kn,{children:"Share coupon codes with users to give them discounts on subscriptions"})]}),e.jsx(Me,{children:r?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Ct,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):t.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No coupons created yet. Create your first coupon to get started."}):e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"Promo Code"}),e.jsx(Pt,{children:"Name"}),e.jsx(Pt,{children:"Discount"}),e.jsx(Pt,{children:"Duration"}),e.jsx(Pt,{children:"Redemptions"}),e.jsx(Pt,{children:"Status"}),e.jsx(Pt,{className:"text-right",children:"Actions"})]})}),e.jsx(Ka,{children:t.map(v=>{var g;return e.jsxs(pn,{children:[e.jsx(gt,{className:"font-mono font-medium",children:((g=v.promotion_codes)==null?void 0:g.length)>0?v.promotion_codes.join(", "):e.jsx("span",{className:"text-muted-foreground text-xs",children:"No promo code"})}),e.jsx(gt,{children:v.name||"-"}),e.jsx(gt,{children:f(v)}),e.jsx(gt,{children:y(v)}),e.jsx(gt,{children:v.times_redeemed}),e.jsx(gt,{children:e.jsx(Oe,{variant:v.valid?"default":"secondary",children:v.valid?"Active":"Inactive"})}),e.jsx(gt,{className:"text-right",children:e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>p(v.id),children:e.jsx(Sn,{className:"h-4 w-4 text-destructive"})})})]},v.id)})})]})})]}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{children:"How to Use Coupons"})}),e.jsxs(Me,{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 q9e={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 K6n(){const[s,t]=_.useState(""),[n,r]=_.useState("all"),[a,i]=_.useState("all"),[l,o]=_.useState(null),{data:c,isLoading:d,refetch:u}=at({queryKey:["admin-subscriptions"],queryFn:async()=>{const{data:g,error:b}=await q.from("profiles").select(` *, brokerages:brokerage_id (id, name) `).order("created_at",{ascending:!1});if(b)throw b;return g}}),{data:h}=at({queryKey:["admin-brokerages-subscriptions"],queryFn:async()=>{const{data:g,error:b}=await q.from("brokerages").select("*").order("name");if(b)throw b;return await Promise.all((g||[]).map(async S=>{const{data:C}=await q.from("profiles").select("id, name, email, subscription_status, subscription_product_id").eq("brokerage_id",S.id),{data:E}=await q.from("user_roles").select("user_id").eq("role","brokerage_manager"),P=(E==null?void 0:E.map(D=>D.user_id))||[],M=(C==null?void 0:C.filter(D=>P.includes(D.id)))||[],I=(C==null?void 0:C.length)||0;return{...S,managers:M,agentCount:I}}))}}),{data:m}=at({queryKey:["admin-website-subscriptions"],queryFn:async()=>{const{data:g,error:b}=await q.from("local_move_subscriptions").select("*").order("created_at",{ascending:!1});if(b)throw b;return g}}),p=g=>{if(g.is_grandfathered)return{status:"Grandfathered",badge:"Legacy",variant:"secondary"};if(g.brokerage_id&&!g.subscription_product_id)return{status:"Brokerage",badge:"Team Member",variant:"outline"};if(g.is_trial&&g.trial_expires_at)return new Date(g.trial_expires_at)>new Date?{status:"Trial",badge:"Active Trial",variant:"default"}:{status:"Trial Expired",badge:"Expired",variant:"destructive"};if(g.subscription_status==="active"||g.subscription_status==="trialing"){const b=q9e[g.subscription_product_id];return{status:(b==null?void 0:b.name)||"Active",badge:g.subscription_status==="trialing"?"Trial":"Active",variant:"default"}}return g.subscription_status==="canceled"||g.subscription_status==="past_due"?{status:"Canceled",badge:"Inactive",variant:"destructive"}:{status:"None",badge:"No Subscription",variant:"outline"}},f=c==null?void 0:c.filter(g=>{var j,S;if(!(((j=g.name)==null?void 0:j.toLowerCase().includes(s.toLowerCase()))||((S=g.email)==null?void 0:S.toLowerCase().includes(s.toLowerCase()))))return!1;if(a!=="all"){const C=g.subscription_source||"platform";if(a==="platform"&&C==="local_move_website"||a==="local_move_website"&&C!=="local_move_website")return!1}switch(p(g),n){case"active":return g.subscription_status==="active";case"trialing":return g.subscription_status==="trialing"||g.is_trial&&new Date(g.trial_expires_at)>new Date;case"grandfathered":return g.is_grandfathered;case"brokerage":return g.brokerage_id&&!g.subscription_product_id&&!g.is_grandfathered;case"expired":return g.subscription_status==="canceled"||g.subscription_status==="past_due"||g.is_trial&&new Date(g.trial_expires_at)<=new Date;case"none":return!g.subscription_status||g.subscription_status==="none";default:return!0}}),y={totalUsers:(c==null?void 0:c.length)||0,activeSubscriptions:(c==null?void 0:c.filter(g=>g.subscription_status==="active").length)||0,trials:(c==null?void 0:c.filter(g=>g.subscription_status==="trialing"||g.is_trial&&new Date(g.trial_expires_at)>new Date).length)||0,grandfathered:(c==null?void 0:c.filter(g=>g.is_grandfathered).length)||0,brokerageMembers:(c==null?void 0:c.filter(g=>g.brokerage_id&&!g.subscription_product_id&&!g.is_grandfathered).length)||0,individualSubscribers:(c==null?void 0:c.filter(g=>g.subscription_status==="active"&&g.subscription_product_id==="prod_Tc07cYplXUGNkm").length)||0,brokerageSubscribers:(c==null?void 0:c.filter(g=>g.subscription_status==="active"&&(g.subscription_product_id==="prod_Tc08MupgoVySDG"||g.subscription_product_id==="prod_Tc09N1tJ4RrAFn")).length)||0},v=g=>{window.open(`https://dashboard.stripe.com/customers/${g}`,"_blank")};return e.jsx(zs,{title:"Subscription Management",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Wh,{title:"Subscription Management",description:"Track and manage all subscriptions",children:e.jsxs(B,{onClick:()=>u(),variant:"outline",size:"sm",children:[e.jsx(uo,{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(ve,{children:e.jsxs(Me,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(In,{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:y.totalUsers})]})}),e.jsx(ve,{className:"border-green-500/50",children:e.jsxs(Me,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_y,{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:y.activeSubscriptions})]})}),e.jsx(ve,{className:"border-blue-500/50",children:e.jsxs(Me,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Gr,{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:y.trials})]})}),e.jsx(ve,{className:"border-purple-500/50",children:e.jsxs(Me,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($f,{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:y.grandfathered})]})}),e.jsx(ve,{className:"border-orange-500/50",children:e.jsxs(Me,{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:y.brokerageMembers})]})}),e.jsx(ve,{children:e.jsxs(Me,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(gj,{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:y.individualSubscribers})]})}),e.jsx(ve,{children:e.jsxs(Me,{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:y.brokerageSubscribers})]})})]}),e.jsxs(Yr,{defaultValue:"users",className:"space-y-4",children:[e.jsxs(Zr,{children:[e.jsx(Ht,{value:"users",children:"All Users"}),e.jsx(Ht,{value:"brokerages",children:"Brokerages"}),e.jsxs(Ht,{value:"websites",className:"gap-2",children:[e.jsx(sl,{className:"h-4 w-4"}),"Website Subscriptions",m&&m.length>0&&e.jsx(Oe,{variant:"secondary",className:"ml-1",children:m.length})]})]}),e.jsxs(Gt,{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(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search by name or email...",value:s,onChange:g=>t(g.target.value),className:"pl-9"})]}),e.jsxs(is,{value:a,onValueChange:g=>i(g),children:[e.jsx(rs,{className:"w-[200px]",children:e.jsx(ls,{placeholder:"Source"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Sources"}),e.jsx(He,{value:"platform",children:"Platform"}),e.jsx(He,{value:"local_move_website",children:"Local Move Website"})]})]}),e.jsxs(is,{value:n,onValueChange:g=>r(g),children:[e.jsx(rs,{className:"w-[200px]",children:e.jsx(ls,{placeholder:"Filter by status"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Statuses"}),e.jsx(He,{value:"active",children:"Active Subscriptions"}),e.jsx(He,{value:"trialing",children:"Trials"}),e.jsx(He,{value:"grandfathered",children:"Grandfathered"}),e.jsx(He,{value:"brokerage",children:"Brokerage Members"}),e.jsx(He,{value:"expired",children:"Expired/Canceled"}),e.jsx(He,{value:"none",children:"No Subscription"})]})]})]}),e.jsx(ve,{children:e.jsx(Me,{className:"p-0",children:e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"User"}),e.jsx(Pt,{children:"Status"}),e.jsx(Pt,{children:"Plan"}),e.jsx(Pt,{children:"Brokerage"}),e.jsx(Pt,{children:"End Date"}),e.jsx(Pt,{className:"text-right",children:"Actions"})]})}),e.jsx(Ka,{children:d?e.jsx(pn,{children:e.jsx(gt,{colSpan:6,className:"text-center py-8",children:"Loading subscriptions..."})}):(f==null?void 0:f.length)===0?e.jsx(pn,{children:e.jsx(gt,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No users found"})}):f==null?void 0:f.map(g=>{var S,C;const b=p(g),j=q9e[g.subscription_product_id];return e.jsxs(pn,{children:[e.jsx(gt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:g.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:g.email})]})}),e.jsx(gt,{children:e.jsx(Oe,{variant:b.variant,children:b.badge})}),e.jsx(gt,{children:e.jsx("span",{className:"text-sm",children:g.is_grandfathered?"Legacy Access":g.brokerage_id&&!g.subscription_product_id?"Brokerage Subscription":(j==null?void 0:j.name)||b.status})}),e.jsx(gt,{children:(S=g.brokerages)!=null&&S.name?e.jsx("span",{className:"text-sm",children:g.brokerages.name}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"—"})}),e.jsx(gt,{children:g.subscription_end_date?e.jsx("span",{className:"text-sm",children:Hs(new Date(g.subscription_end_date),"MMM d, yyyy")}):g.trial_expires_at?e.jsxs("span",{className:"text-sm text-blue-600",children:["Trial: ",Hs(new Date(g.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:[g.stripe_customer_id&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>v(g.stripe_customer_id),children:e.jsx(wr,{className:"h-4 w-4"})}),e.jsxs(Ls,{children:[e.jsx(nl,{asChild:!0,children:e.jsx(B,{variant:"outline",size:"sm",onClick:()=>o(g),children:"Details"})}),e.jsxs(Ps,{children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Subscription Details"}),e.jsxs(_r,{children:[g.name," (",g.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(Oe,{variant:b.variant,className:"mt-1",children:b.badge})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Plan"}),e.jsx("p",{className:"font-medium",children:g.is_grandfathered?"Grandfathered (Legacy)":g.brokerage_id&&!g.subscription_product_id?"Brokerage Subscription":(j==null?void 0:j.name)||"None"})]}),g.brokerage_id&&e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Brokerage"}),e.jsx("p",{className:"font-medium",children:((C=g.brokerages)==null?void 0:C.name)||"Unknown"})]}),g.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(g.subscription_end_date),"MMMM d, yyyy")})]}),g.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(g.trial_expires_at),"MMMM d, yyyy")})]}),g.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:g.stripe_customer_id})]})]}),g.stripe_customer_id&&e.jsxs(B,{className:"w-full",onClick:()=>v(g.stripe_customer_id),children:[e.jsx(wr,{className:"h-4 w-4 mr-2"}),"View in Stripe Dashboard"]})]})]})]})]})})]},g.id)})})]})})})]}),e.jsx(Gt,{value:"brokerages",className:"space-y-4",children:e.jsx("div",{className:"grid gap-4",children:h==null?void 0:h.map(g=>{var j,S;const b=(j=g.managers)==null?void 0:j.some(C=>C.subscription_status==="active"&&(C.subscription_product_id==="prod_Tc08MupgoVySDG"||C.subscription_product_id==="prod_Tc09N1tJ4RrAFn"));return e.jsxs(ve,{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(St,{className:"text-lg",children:g.name}),e.jsxs(kn,{children:[g.agentCount," agents"]})]})]}),e.jsx(Oe,{variant:b?"default":"outline",children:b?"Active Subscription":"No Active Subscription"})]})}),e.jsx(Me,{children:((S=g.managers)==null?void 0:S.length)>0?e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium text-muted-foreground",children:"Managers:"}),g.managers.map(C=>{const E=q9e[C.subscription_product_id];return e.jsxs("div",{className:"flex items-center justify-between p-2 rounded-lg bg-muted/50",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:C.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:C.email})]}),e.jsx("div",{className:"text-right",children:E?e.jsxs("div",{children:[e.jsx(Oe,{variant:"default",children:E.name}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:E.price})]}):e.jsx(Oe,{variant:"outline",children:"No Subscription"})})]},C.id)})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"No managers assigned"})})]},g.id)})})}),e.jsx(Gt,{value:"websites",className:"space-y-4",children:e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(sl,{className:"h-5 w-5 text-primary"}),"Local Move Website Subscriptions"]}),e.jsx(kn,{children:"$249 setup fee + $99/mo subscriptions from TheLocalMove.com agent websites"})]}),e.jsx(Me,{className:"p-0",children:e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"Agent"}),e.jsx(Pt,{children:"Status"}),e.jsx(Pt,{children:"Setup Fee"}),e.jsx(Pt,{children:"Monthly"}),e.jsx(Pt,{children:"Next Renewal"}),e.jsx(Pt,{children:"Started"}),e.jsx(Pt,{className:"text-right",children:"Actions"})]})}),e.jsx(Ka,{children:m?m.length===0?e.jsx(pn,{children:e.jsx(gt,{colSpan:7,className:"text-center py-8 text-muted-foreground",children:"No website subscriptions yet"})}):m.map(g=>e.jsxs(pn,{children:[e.jsx(gt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:g.agent_name||"—"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:g.agent_email})]})}),e.jsx(gt,{children:e.jsx(Oe,{variant:g.status==="active"?"default":g.status==="canceled"?"destructive":"outline",children:g.status})}),e.jsx(gt,{children:g.setup_fee_paid?e.jsxs(Oe,{variant:"secondary",children:["Paid · $",(g.setup_fee_amount_cents/100).toFixed(0)]}):e.jsx(Oe,{variant:"outline",children:"Unpaid"})}),e.jsxs(gt,{className:"font-medium",children:["$",(g.monthly_amount_cents/100).toFixed(0),"/mo"]}),e.jsx(gt,{children:g.current_period_end?e.jsx("span",{className:"text-sm",children:Hs(new Date(g.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(g.created_at),"MMM d, yyyy")})}),e.jsx(gt,{className:"text-right",children:g.stripe_customer_id&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>v(g.stripe_customer_id),children:e.jsx(wr,{className:"h-4 w-4"})})})]},g.id)):e.jsx(pn,{children:e.jsx(gt,{colSpan:7,className:"text-center py-8",children:"Loading…"})})})]})})]})})]})]})})}function Y6n(){const[s,t]=_.useState([]),[n,r]=_.useState(!0),[a,i]=_.useState(""),[l,o]=_.useState("all"),[c,d]=_.useState({total:0,qualified:0,pending:0,cancelled:0,totalDiscounts:0});_.useEffect(()=>{u()},[]);const u=async()=>{try{const{data:f,error:y}=await q.from("referrals").select(` *, referrer_brokerage:brokerages!referrer_brokerage_id(name), referred_brokerage:brokerages!referred_brokerage_id(name), referred_user:profiles!referred_user_id(name, email) `).order("created_at",{ascending:!1});if(y)throw y;t(f||[]);const v=(f==null?void 0:f.filter(j=>j.status==="qualified").length)||0,g=(f==null?void 0:f.filter(j=>j.status==="pending").length)||0,b=(f==null?void 0:f.filter(j=>j.status==="cancelled").length)||0;d({total:(f==null?void 0:f.length)||0,qualified:v,pending:g,cancelled:b,totalDiscounts:v*25})}catch(f){console.error("Error fetching referrals:",f),se.error("Failed to load referrals")}finally{r(!1)}},h=async()=>{try{se.loading("Processing qualifications...");const{error:f}=await q.functions.invoke("process-referral-qualifications");if(f)throw f;se.dismiss(),se.success("Qualifications processed successfully"),u()}catch(f){se.dismiss(),console.error("Error processing qualifications:",f),se.error("Failed to process qualifications")}},m=s.filter(f=>{var g,b,j,S,C,E;const y=((b=(g=f.referrer_brokerage)==null?void 0:g.name)==null?void 0:b.toLowerCase().includes(a.toLowerCase()))||((S=(j=f.referred_brokerage)==null?void 0:j.name)==null?void 0:S.toLowerCase().includes(a.toLowerCase()))||((E=(C=f.referred_user)==null?void 0:C.email)==null?void 0:E.toLowerCase().includes(a.toLowerCase())),v=l==="all"||f.status===l;return y&&v}),p=f=>{switch(f){case"qualified":return e.jsxs(Oe,{className:"bg-green-100 text-green-800",children:[e.jsx(_l,{className:"h-3 w-3 mr-1"}),"Qualified"]});case"pending":return e.jsxs(Oe,{variant:"secondary",children:[e.jsx(Gr,{className:"h-3 w-3 mr-1"}),"Pending"]});case"cancelled":return e.jsxs(Oe,{variant:"destructive",children:[e.jsx(Rd,{className:"h-3 w-3 mr-1"}),"Cancelled"]});default:return e.jsx(Oe,{children:f})}};return e.jsx(zs,{title:"Referral Program",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Wh,{title:"Referral Program",description:"Track and manage brokerage referrals",children:e.jsxs(B,{onClick:h,variant:"outline",children:[e.jsx(uo,{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(ve,{children:e.jsx(Me,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(In,{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(ve,{children:e.jsx(Me,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_l,{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(ve,{children:e.jsx(Me,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Gr,{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(ve,{children:e.jsx(Me,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Rd,{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(ve,{children:e.jsx(Me,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(yd,{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(ve,{children:[e.jsxs(bt,{children:[e.jsx(St,{children:"All Referrals"}),e.jsx(kn,{children:"View and manage all referral relationships"})]}),e.jsxs(Me,{children:[e.jsxs("div",{className:"flex gap-4 mb-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search by brokerage or email...",value:a,onChange:f=>i(f.target.value),className:"pl-10"})]}),e.jsxs(is,{value:l,onValueChange:o,children:[e.jsx(rs,{className:"w-[180px]",children:e.jsx(ls,{placeholder:"Filter by status"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Statuses"}),e.jsx(He,{value:"pending",children:"Pending"}),e.jsx(He,{value:"qualified",children:"Qualified"}),e.jsx(He,{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(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"Referrer"}),e.jsx(Pt,{children:"Referred"}),e.jsx(Pt,{children:"Signup Date"}),e.jsx(Pt,{children:"Status"}),e.jsx(Pt,{children:"Qualified Date"}),e.jsx(Pt,{children:"Discount"})]})}),e.jsx(Ka,{children:m.length===0?e.jsx(pn,{children:e.jsx(gt,{colSpan:6,className:"text-center text-muted-foreground py-8",children:"No referrals found"})}):m.map(f=>{var y,v,g,b;return e.jsxs(pn,{children:[e.jsx(gt,{className:"font-medium",children:((y=f.referrer_brokerage)==null?void 0:y.name)||"Unknown"}),e.jsx(gt,{children:e.jsxs("div",{children:[e.jsx("p",{children:((v=f.referred_brokerage)==null?void 0:v.name)||((g=f.referred_user)==null?void 0:g.name)||"Pending setup"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(b=f.referred_user)==null?void 0:b.email})]})}),e.jsx(gt,{children:Hs(new Date(f.signup_date),"MMM d, yyyy")}),e.jsx(gt,{children:p(f.status)}),e.jsx(gt,{children:f.qualified_date?Hs(new Date(f.qualified_date),"MMM d, yyyy"):"-"}),e.jsx(gt,{children:f.discount_applied?e.jsx(Oe,{variant:"outline",className:"text-green-600",children:"$25/mo applied"}):e.jsx("span",{className:"text-muted-foreground",children:"-"})})]},f.id)})})]})]})]})]})})}const $9e=[{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"}],Z6n=[{value:"brokerage_manager",label:"Brokerage Manager"},{value:"agent",label:"Agent"}];function X6n(){const[s,t]=_.useState([]),[n,r]=_.useState(!0),[a,i]=_.useState(!1),[l,o]=_.useState(null),[c,d]=_.useState({title:"",description:"",action_type:"view_template",target_role:"agent",is_active:!0});_.useEffect(()=>{u()},[]);const u=async()=>{try{const{data:b,error:j}=await q.from("onboarding_checklist_items").select("*").order("target_role").order("sort_order");if(j)throw j;t(b||[])}catch(b){console.error("Error fetching checklist items:",b),se.error("Failed to load checklist items")}finally{r(!1)}},h=()=>{o(null),d({title:"",description:"",action_type:"view_template",target_role:"agent",is_active:!0}),i(!0)},m=b=>{o(b),d({title:b.title,description:b.description||"",action_type:b.action_type,target_role:b.target_role,is_active:b.is_active}),i(!0)},p=async()=>{if(!c.title.trim()){se.error("Title is required");return}try{if(l){const{error:b}=await q.from("onboarding_checklist_items").update({title:c.title,description:c.description||null,action_type:c.action_type,target_role:c.target_role,is_active:c.is_active}).eq("id",l.id);if(b)throw b;se.success("Checklist item updated")}else{const b=s.filter(S=>S.target_role===c.target_role).reduce((S,C)=>Math.max(S,C.sort_order),-1),{error:j}=await q.from("onboarding_checklist_items").insert({title:c.title,description:c.description||null,action_type:c.action_type,target_role:c.target_role,is_active:c.is_active,sort_order:b+1});if(j)throw j;se.success("Checklist item created")}i(!1),u()}catch(b){console.error("Error saving checklist item:",b),se.error("Failed to save checklist item")}},f=async b=>{if(await Xi("Are you sure you want to delete this checklist item?"))try{const{error:j}=await q.from("onboarding_checklist_items").delete().eq("id",b);if(j)throw j;se.success("Checklist item deleted"),u()}catch(j){console.error("Error deleting checklist item:",j),se.error("Failed to delete checklist item")}},y=async b=>{try{const{error:j}=await q.from("onboarding_checklist_items").update({is_active:!b.is_active}).eq("id",b.id);if(j)throw j;se.success(b.is_active?"Item deactivated":"Item activated"),u()}catch(j){console.error("Error toggling item:",j),se.error("Failed to update item")}},v=s.filter(b=>b.target_role==="brokerage_manager"),g=s.filter(b=>b.target_role==="agent");return e.jsxs(zs,{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(B,{onClick:h,className:"gap-2",children:[e.jsx(rn,{className:"h-4 w-4"}),"Add Item"]})]}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(Oe,{variant:"secondary",children:"Brokerage Manager"}),"Checklist Items"]})}),e.jsx(Me,{children:v.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No checklist items for brokerage managers"}):e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{className:"w-12",children:"#"}),e.jsx(Pt,{children:"Title"}),e.jsx(Pt,{children:"Action Type"}),e.jsx(Pt,{children:"Status"}),e.jsx(Pt,{className:"text-right",children:"Actions"})]})}),e.jsx(Ka,{children:v.map((b,j)=>{var S;return e.jsxs(pn,{children:[e.jsx(gt,{className:"text-muted-foreground",children:j+1}),e.jsx(gt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:b.title}),b.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-1",children:b.description})]})}),e.jsx(gt,{children:e.jsx(Oe,{variant:"outline",children:((S=$9e.find(C=>C.value===b.action_type))==null?void 0:S.label)||b.action_type})}),e.jsx(gt,{children:e.jsx(fn,{checked:b.is_active,onCheckedChange:()=>y(b)})}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>m(b),children:e.jsx(Ya,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>f(b.id),children:e.jsx(Sn,{className:"h-4 w-4 text-destructive"})})]})})]},b.id)})})]})})]}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(Oe,{variant:"secondary",children:"Agent"}),"Checklist Items"]})}),e.jsx(Me,{children:g.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No checklist items for agents"}):e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{className:"w-12",children:"#"}),e.jsx(Pt,{children:"Title"}),e.jsx(Pt,{children:"Action Type"}),e.jsx(Pt,{children:"Status"}),e.jsx(Pt,{className:"text-right",children:"Actions"})]})}),e.jsx(Ka,{children:g.map((b,j)=>{var S;return e.jsxs(pn,{children:[e.jsx(gt,{className:"text-muted-foreground",children:j+1}),e.jsx(gt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:b.title}),b.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-1",children:b.description})]})}),e.jsx(gt,{children:e.jsx(Oe,{variant:"outline",children:((S=$9e.find(C=>C.value===b.action_type))==null?void 0:S.label)||b.action_type})}),e.jsx(gt,{children:e.jsx(fn,{checked:b.is_active,onCheckedChange:()=>y(b)})}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>m(b),children:e.jsx(Ya,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>f(b.id),children:e.jsx(Sn,{className:"h-4 w-4 text-destructive"})})]})})]},b.id)})})]})})]})]}),e.jsx(Ls,{open:a,onOpenChange:i,children:e.jsxs(Ps,{children:[e.jsx(Os,{children:e.jsx(Ds,{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(J,{htmlFor:"title",children:"Title *"}),e.jsx(xe,{id:"title",value:c.title,onChange:b=>d({...c,title:b.target.value}),placeholder:"e.g., Watch your first academy video"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"description",children:"Description"}),e.jsx(Ms,{id:"description",value:c.description,onChange:b=>d({...c,description:b.target.value}),placeholder:"Optional description for the checklist item",rows:2})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Target Role"}),e.jsxs(is,{value:c.target_role,onValueChange:b=>d({...c,target_role:b}),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsx(as,{children:Z6n.map(b=>e.jsx(He,{value:b.value,children:b.label},b.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Action Type"}),e.jsxs(is,{value:c.action_type,onValueChange:b=>d({...c,action_type:b}),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsx(as,{children:$9e.map(b=>e.jsx(He,{value:b.value,children:b.label},b.value))})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fn,{id:"is_active",checked:c.is_active,onCheckedChange:b=>d({...c,is_active:b})}),e.jsx(J,{htmlFor:"is_active",children:"Active"})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>i(!1),children:"Cancel"}),e.jsx(B,{onClick:p,children:l?"Save Changes":"Create Item"})]})]})})]})}function Q6n(){const[s,t]=_.useState(""),[n,r]=_.useState("all"),[a,i]=_.useState("name"),[l,o]=_.useState("asc"),[c,d]=_.useState(""),[u,h]=_.useState(""),[m,p]=_.useState(""),[f,y]=_.useState(""),{data:v}=at({queryKey:["admin-brokerages"],queryFn:async()=>{const{data:D,error:O}=await q.from("brokerages").select("id, name").order("name");if(O)throw O;return D}}),g=async D=>{let V=[],G=0,$=!0;for(;$;){const{data:H,error:Y}=await D(G,G+1e3-1);if(Y)throw Y;H&&H.length>0?(V=[...V,...H],G+=1e3,$=H.length===1e3):$=!1}return V},{data:b,isLoading:j}=at({queryKey:["admin-agent-os-user-stats"],queryFn:async()=>{const D=await g((Ce,Ae)=>q.from("profiles").select("id, name, email, brokerage_id, created_at").range(Ce,Ae)),{data:O}=await q.from("brokerages").select("id, name"),V=new Map((O==null?void 0:O.map(Ce=>[Ce.id,Ce.name]))||[]),[{data:G},{data:$},{data:H},{data:Y},{data:Z},{data:ne},{data:ce}]=await Promise.all([q.rpc("get_admin_contact_counts"),q.rpc("get_admin_video_counts"),q.rpc("get_admin_popby_counts"),q.rpc("get_admin_listing_counts"),q.rpc("get_admin_deal_counts"),q.rpc("get_admin_portal_counts"),q.rpc("get_admin_sendable_card_counts")]),ie=new Map;G==null||G.forEach(Ce=>ie.set(Ce.owner_user_id,Ce.contact_count));const te=new Map;$==null||$.forEach(Ce=>te.set(Ce.owner_user_id,Ce.video_count));const ae=new Map;H==null||H.forEach(Ce=>ae.set(Ce.owner_user_id,Ce.popby_count));const le=new Map;Y==null||Y.forEach(Ce=>le.set(Ce.agent_id,Ce.listing_count));const be=new Map;Z==null||Z.forEach(Ce=>be.set(Ce.owner_user_id,Ce.deal_count));const me=new Map;ne==null||ne.forEach(Ce=>me.set(Ce.owner_user_id,{total:Ce.portal_count,active:Ce.active_portal_count}));const he=new Map;return ce==null||ce.forEach(Ce=>he.set(Ce.owner_user_id,{total:Ce.card_count,sent:Ce.sent_card_count,views:Ce.total_card_views})),D.map(Ce=>{const Ae=me.get(Ce.id),Pe=he.get(Ce.id);return{id:Ce.id,name:Ce.name||"Unknown",email:Ce.email||"",brokerage_id:Ce.brokerage_id,brokerage_name:Ce.brokerage_id&&V.get(Ce.brokerage_id)||null,contact_count:ie.get(Ce.id)||0,video_count:te.get(Ce.id)||0,popby_count:ae.get(Ce.id)||0,listing_count:le.get(Ce.id)||0,deal_count:be.get(Ce.id)||0,portal_count:(Ae==null?void 0:Ae.total)||0,active_portal_count:(Ae==null?void 0:Ae.active)||0,card_count:(Pe==null?void 0:Pe.total)||0,sent_card_count:(Pe==null?void 0:Pe.sent)||0,total_card_views:(Pe==null?void 0:Pe.views)||0,created_at:Ce.created_at}})}}),S=_.useMemo(()=>{if(!b)return[];let D=b.filter(O=>{const V=s.toLowerCase(),G=!s||O.name.toLowerCase().includes(V)||O.email.toLowerCase().includes(V),$=n==="all"||n==="none"&&!O.brokerage_id||O.brokerage_id===n,H=parseInt(c)||0,Y=parseInt(u)||0,Z=parseInt(m)||0,ne=parseInt(f)||0,ce=O.contact_count>=H&&O.video_count>=Y&&O.popby_count>=Z&&O.listing_count>=ne;return G&&$&&ce});return D.sort((O,V)=>{let G=0;return a==="name"?G=O.name.localeCompare(V.name):G=O[a]-V[a],l==="asc"?G:-G}),D},[b,s,n,a,l,c,u,m,f]),C=D=>{a===D?o(l==="asc"?"desc":"asc"):(i(D),o("desc"))},E=()=>{const D=["Name","Email","Brokerage","Contacts","Videos","Popbys","Listings","Deals","Portals (Active)","Cards Created","Cards Sent","Card Views"],O=S.map(Y=>[Y.name,Y.email,Y.brokerage_name||"None",Y.contact_count,Y.video_count,Y.popby_count,Y.listing_count,Y.deal_count,`${Y.portal_count} (${Y.active_portal_count})`,Y.card_count,Y.sent_card_count,Y.total_card_views]),V=[D.join(","),...O.map(Y=>Y.map(Z=>`"${Z}"`).join(","))].join(` `),G=new Blob([V],{type:"text/csv"}),$=URL.createObjectURL(G),H=document.createElement("a");H.href=$,H.download=`agent-os-user-stats-${new Date().toISOString().split("T")[0]}.csv`,H.click(),URL.revokeObjectURL($)},P=_.useMemo(()=>S.length?S.reduce((D,O)=>({contacts:D.contacts+O.contact_count,videos:D.videos+O.video_count,popbys:D.popbys+O.popby_count,listings:D.listings+O.listing_count,deals:D.deals+O.deal_count,portals:D.portals+O.portal_count,activePortals:D.activePortals+O.active_portal_count,cards:D.cards+O.card_count,sentCards:D.sentCards+O.sent_card_count,cardViews:D.cardViews+O.total_card_views}),{contacts:0,videos:0,popbys:0,listings:0,deals:0,portals:0,activePortals:0,cards:0,sentCards:0,cardViews:0}):{contacts:0,videos:0,popbys:0,listings:0,deals:0,portals:0,activePortals:0,cards:0,sentCards:0,cardViews:0},[S]),M=_.useMemo(()=>S.length?{portals:S.filter(D=>D.portal_count>0).length,cards:S.filter(D=>D.card_count>0).length}:{portals:0,cards:0},[S]),I=({field:D,children:O})=>e.jsx(Pt,{className:"cursor-pointer hover:bg-muted/50 select-none",onClick:()=>C(D),children:e.jsxs("div",{className:"flex items-center gap-1",children:[O,e.jsx(Lg,{className:`h-3 w-3 ${a===D?"text-primary":"text-muted-foreground"}`})]})});return e.jsx(FN,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs(ve,{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(St,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(dN,{className:"h-4 w-4 text-blue-500"}),"Client Portals"]})}),e.jsx(Me,{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(ve,{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(St,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(ln,{className:"h-4 w-4 text-violet-500"}),"Card Studio"]})}),e.jsx(Me,{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(ve,{children:[e.jsx(bt,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(In,{className:"h-5 w-5"}),"User Activity Analytics"]}),e.jsx(kn,{children:"View all users and their Agent OS usage metrics"})]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:E,children:[e.jsx(li,{className:"h-4 w-4 mr-2"}),"Export CSV"]})]})}),e.jsxs(Me,{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(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search by name or email...",value:s,onChange:D=>t(D.target.value),className:"pl-9"})]})}),e.jsx("div",{children:e.jsxs(is,{value:n,onValueChange:r,children:[e.jsxs(rs,{children:[e.jsx(ai,{className:"h-4 w-4 mr-2 text-muted-foreground"}),e.jsx(ls,{placeholder:"Brokerage"})]}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Brokerages"}),e.jsx(He,{value:"none",children:"No Brokerage"}),v==null?void 0:v.map(D=>e.jsx(He,{value:D.id,children:D.name},D.id))]})]})}),e.jsx("div",{children:e.jsx(xe,{type:"number",placeholder:"Min contacts",value:c,onChange:D=>d(D.target.value),min:"0"})}),e.jsx("div",{children:e.jsx(xe,{type:"number",placeholder:"Min videos",value:u,onChange:D=>h(D.target.value),min:"0"})}),e.jsx("div",{children:e.jsx(xe,{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:S.length}),e.jsx("div",{className:"text-muted-foreground",children:"Users"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children: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"})]})]}),j?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(Ct,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsx("div",{className:"rounded-md border overflow-x-auto",children:e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(I,{field:"name",children:"Name"}),e.jsx(Pt,{children:"Email"}),e.jsx(Pt,{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(dN,{className:"h-3 w-3 text-blue-500"}),"Portals"]})}),e.jsx(I,{field:"card_count",children:e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ln,{className:"h-3 w-3 text-violet-500"}),"Cards"]})})]})}),e.jsx(Ka,{children:S.length===0?e.jsx(pn,{children:e.jsx(gt,{colSpan:10,className:"text-center py-8 text-muted-foreground",children:"No users found matching your filters"})}):S.map(D=>e.jsxs(pn,{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(Oe,{variant:"secondary",children:D.brokerage_name}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(gt,{children:e.jsx(Oe,{variant:D.contact_count>0?"default":"outline",children:D.contact_count})}),e.jsx(gt,{children:e.jsx(Oe,{variant:D.video_count>0?"default":"outline",children:D.video_count})}),e.jsx(gt,{children:e.jsx(Oe,{variant:D.popby_count>0?"default":"outline",children:D.popby_count})}),e.jsx(gt,{children:e.jsx(Oe,{variant:D.listing_count>0?"default":"outline",children:D.listing_count})}),e.jsx(gt,{children:e.jsx(Oe,{variant:D.deal_count>0?"default":"outline",children:D.deal_count})}),e.jsx(gt,{children:D.portal_count>0?e.jsxs(ag,{children:[e.jsx(ig,{children:e.jsxs(Oe,{variant:"default",className:"bg-blue-600 hover:bg-blue-700",children:[D.portal_count,D.active_portal_count>0&&e.jsxs("span",{className:"ml-1 opacity-75",children:["(",D.active_portal_count," active)"]})]})}),e.jsxs(Nx,{children:[e.jsxs("p",{children:[D.portal_count," total portals"]}),e.jsxs("p",{children:[D.active_portal_count," currently active"]})]})]}):e.jsx(Oe,{variant:"outline",children:"0"})}),e.jsx(gt,{children:D.card_count>0?e.jsxs(ag,{children:[e.jsx(ig,{children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Oe,{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(Or,{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(ya,{className:"h-3 w-3"}),D.total_card_views]})]})}),e.jsxs(Nx,{children:[e.jsxs("p",{children:[D.card_count," cards created"]}),e.jsxs("p",{children:[D.sent_card_count," sent"]}),e.jsxs("p",{children:[D.total_card_views," total views"]})]})]}):e.jsx(Oe,{variant:"outline",children:"0"})})]},D.id))})]})})]})]})]})})}function J6n(){vi(),Bt();const[s,t]=_.useState("user-analytics"),{data:n}=at({queryKey:["admin-feature-flags"],queryFn:async()=>{const{data:p,error:f}=await q.from("feature_flags").select("*").order("key");if(f)throw f;return p}}),{data:r,isLoading:a}=at({queryKey:["admin-relationship-types"],queryFn:async()=>{const{data:p,error:f}=await q.from("relationship_types").select("*").order("sort_order");if(f)throw f;return p}}),{data:i,isLoading:l}=at({queryKey:["admin-action-types"],queryFn:async()=>{const{data:p,error:f}=await q.from("action_types").select("*").order("sort_order");if(f)throw f;return p}}),{data:o,isLoading:c}=at({queryKey:["admin-action-scripts"],queryFn:async()=>{const{data:p,error:f}=await q.from("action_scripts").select("*, action_type:action_types(*)");if(f)throw f;return p}}),{data:d,isLoading:u}=at({queryKey:["admin-touchpoint-plans"],queryFn:async()=>{const{data:p,error:f}=await q.from("touchpoint_plans").select("*").order("name");if(f)throw f;return p}}),{data:h,isLoading:m}=at({queryKey:["admin-popby-items"],queryFn:async()=>{const{data:p,error:f}=await q.from("popby_items").select("*").is("owner_user_id",null).order("name");if(f)throw f;return p}});return e.jsx(zs,{title:"Agent OS Control Center",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Wh,{title:"Agent OS Control Center",description:"Manage InnerCircle settings, scripts, and touchpoint plans"}),e.jsxs(Yr,{value:s,onValueChange:t,children:[e.jsxs(Zr,{className:"grid w-full grid-cols-9",children:[e.jsxs(Ht,{value:"user-analytics",className:"gap-2",children:[e.jsx(bl,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Users"})]}),e.jsxs(Ht,{value:"relationship-types",className:"gap-2",children:[e.jsx(In,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Relationships"})]}),e.jsxs(Ht,{value:"action-types",className:"gap-2",children:[e.jsx(_a,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Actions"})]}),e.jsxs(Ht,{value:"scripts",className:"gap-2",children:[e.jsx(Fr,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Scripts"})]}),e.jsxs(Ht,{value:"video-scripts",className:"gap-2",children:[e.jsx(dm,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Video Scripts"})]}),e.jsxs(Ht,{value:"plans",className:"gap-2",children:[e.jsx(ga,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Plans"})]}),e.jsxs(Ht,{value:"popbys",className:"gap-2",children:[e.jsx(Vo,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Popbys"})]}),e.jsxs(Ht,{value:"settings",className:"gap-2",children:[e.jsx(qc,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Settings"})]}),e.jsxs(Ht,{value:"feature-flags",className:"gap-2",children:[e.jsx(qA,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Flags"})]})]}),e.jsx(Gt,{value:"user-analytics",className:"mt-6",children:e.jsx(Q6n,{})}),e.jsx(Gt,{value:"relationship-types",className:"mt-6",children:e.jsx(eMn,{types:r||[],isLoading:a})}),e.jsx(Gt,{value:"action-types",className:"mt-6",children:e.jsx(tMn,{types:i||[],isLoading:l})}),e.jsx(Gt,{value:"scripts",className:"mt-6",children:e.jsx(sMn,{scripts:o||[],actionTypes:i||[],isLoading:c})}),e.jsx(Gt,{value:"video-scripts",className:"mt-6",children:e.jsx(iMn,{})}),e.jsx(Gt,{value:"plans",className:"mt-6",children:e.jsx(nMn,{plans:d||[],actionTypes:i||[],scripts:o||[],isLoading:u})}),e.jsx(Gt,{value:"popbys",className:"mt-6",children:e.jsx(aMn,{items:h||[],isLoading:m})}),e.jsx(Gt,{value:"settings",className:"mt-6",children:e.jsx(oMn,{})}),e.jsx(Gt,{value:"feature-flags",className:"mt-6",children:e.jsx(rMn,{flags:n||[]})})]})]})})}function eMn({types:s,isLoading:t}){const{toast:n}=vi(),r=Bt(),[a,i]=_.useState(null),[l,o]=_.useState(!1),c=mt({mutationFn:async u=>{if(u.id){const{error:h}=await q.from("relationship_types").update({name:u.name,description:u.description,icon:u.icon}).eq("id",u.id);if(h)throw h}else{const{error:h}=await q.from("relationship_types").insert([{name:u.name,description:u.description,icon:u.icon,sort_order:s.length}]);if(h)throw h}},onSuccess:()=>{r.invalidateQueries({queryKey:["admin-relationship-types"]}),o(!1),i(null),n({title:"Saved successfully"})},onError:u=>{n({title:"Error",description:u.message,variant:"destructive"})}}),d=async u=>{await q.from("relationship_types").update({active:!u.active}).eq("id",u.id),r.invalidateQueries({queryKey:["admin-relationship-types"]})};return e.jsxs(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(St,{children:"Relationship Types"}),e.jsx(kn,{children:"Define the relationship categories for InnerCircle contacts"})]}),e.jsxs(B,{onClick:()=>{i(null),o(!0)},children:[e.jsx(rn,{className:"h-4 w-4 mr-2"}),"Add Type"]})]}),e.jsx(Me,{children:t?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(Ct,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{className:"w-12"}),e.jsx(Pt,{children:"Name"}),e.jsx(Pt,{children:"Description"}),e.jsx(Pt,{children:"Status"}),e.jsx(Pt,{className:"w-24",children:"Actions"})]})}),e.jsx(Ka,{children:s.map(u=>e.jsxs(pn,{children:[e.jsx(gt,{children:e.jsx(Vf,{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(fn,{checked:u.active,onCheckedChange:()=>d(u)})}),e.jsx(gt,{children:e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{i(u),o(!0)},children:e.jsx(Ya,{className:"h-4 w-4"})})})]},u.id))})]})}),e.jsx(Ls,{open:l,onOpenChange:o,children:e.jsxs(Ps,{children:[e.jsx(Os,{children:e.jsxs(Ds,{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(J,{htmlFor:"name",children:"Name"}),e.jsx(xe,{id:"name",name:"name",defaultValue:a==null?void 0:a.name,required:!0})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"description",children:"Description"}),e.jsx(Ms,{id:"description",name:"description",defaultValue:(a==null?void 0:a.description)||""})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"icon",children:"Icon"}),e.jsx(xe,{id:"icon",name:"icon",defaultValue:(a==null?void 0:a.icon)||"",placeholder:"e.g., star, heart, user"})]})]}),e.jsxs(yr,{className:"mt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsxs(B,{type:"submit",disabled:c.isPending,children:[c.isPending&&e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function tMn({types:s,isLoading:t}){const{toast:n}=vi(),r=Bt(),[a,i]=_.useState(null),[l,o]=_.useState(!1),c=mt({mutationFn:async u=>{if(u.id){const{error:h}=await q.from("action_types").update({name:u.name,description:u.description,icon:u.icon,color:u.color}).eq("id",u.id);if(h)throw h}else{const{error:h}=await q.from("action_types").insert([{name:u.name,description:u.description,icon:u.icon,color:u.color,sort_order:s.length}]);if(h)throw h}},onSuccess:()=>{r.invalidateQueries({queryKey:["admin-action-types"]}),o(!1),i(null),n({title:"Saved successfully"})},onError:u=>{n({title:"Error",description:u.message,variant:"destructive"})}}),d=async u=>{await q.from("action_types").update({active:!u.active}).eq("id",u.id),r.invalidateQueries({queryKey:["admin-action-types"]})};return e.jsxs(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(St,{children:"Action Types"}),e.jsx(kn,{children:"Define the types of touchpoint actions agents can take"})]}),e.jsxs(B,{onClick:()=>{i(null),o(!0)},children:[e.jsx(rn,{className:"h-4 w-4 mr-2"}),"Add Action"]})]}),e.jsx(Me,{children:t?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(Ct,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"Name"}),e.jsx(Pt,{children:"Description"}),e.jsx(Pt,{children:"Color"}),e.jsx(Pt,{children:"Status"}),e.jsx(Pt,{className:"w-24",children:"Actions"})]})}),e.jsx(Ka,{children:s.map(u=>e.jsxs(pn,{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(fn,{checked:u.active,onCheckedChange:()=>d(u)})}),e.jsx(gt,{children:e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{i(u),o(!0)},children:e.jsx(Ya,{className:"h-4 w-4"})})})]},u.id))})]})}),e.jsx(Ls,{open:l,onOpenChange:o,children:e.jsxs(Ps,{children:[e.jsx(Os,{children:e.jsxs(Ds,{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(J,{htmlFor:"name",children:"Name"}),e.jsx(xe,{id:"name",name:"name",defaultValue:a==null?void 0:a.name,required:!0})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"description",children:"Description"}),e.jsx(Ms,{id:"description",name:"description",defaultValue:(a==null?void 0:a.description)||""})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"icon",children:"Icon"}),e.jsx(xe,{id:"icon",name:"icon",defaultValue:(a==null?void 0:a.icon)||"",placeholder:"e.g., phone, message"})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"color",children:"Color"}),e.jsx(xe,{id:"color",name:"color",type:"color",defaultValue:(a==null?void 0:a.color)||"#6366f1"})]})]}),e.jsxs(yr,{className:"mt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsxs(B,{type:"submit",disabled:c.isPending,children:[c.isPending&&e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function sMn({scripts:s,actionTypes:t,isLoading:n}){const{toast:r}=vi(),a=Bt(),[i,l]=_.useState(null),[o,c]=_.useState(!1),d=mt({mutationFn:async h=>{if(h.id){const{error:m}=await q.from("action_scripts").update({title:h.title,action_type_id:h.action_type_id,tone:h.tone,script_body:h.script_body,active:h.active}).eq("id",h.id);if(m)throw m}else{const{error:m}=await q.from("action_scripts").insert([{title:h.title,action_type_id:h.action_type_id,tone:h.tone,script_body:h.script_body,active:!0}]);if(m)throw m}},onSuccess:()=>{a.invalidateQueries({queryKey:["admin-action-scripts"]}),c(!1),l(null),r({title:"Saved successfully"})},onError:h=>{r({title:"Error",description:h.message,variant:"destructive"})}}),u=mt({mutationFn:async h=>{const{error:m}=await q.from("action_scripts").delete().eq("id",h);if(m)throw m},onSuccess:()=>{a.invalidateQueries({queryKey:["admin-action-scripts"]}),r({title:"Deleted successfully"})}});return e.jsxs(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(St,{children:"Script Library"}),e.jsx(kn,{children:"Create and manage scripts for each action type"})]}),e.jsxs(B,{onClick:()=>{l(null),c(!0)},children:[e.jsx(rn,{className:"h-4 w-4 mr-2"}),"Add Script"]})]}),e.jsx(Me,{children:n?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(Ct,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"Title"}),e.jsx(Pt,{children:"Action Type"}),e.jsx(Pt,{children:"Tone"}),e.jsx(Pt,{children:"Status"}),e.jsx(Pt,{className:"w-24",children:"Actions"})]})}),e.jsx(Ka,{children:s.map(h=>{var m;return e.jsxs(pn,{children:[e.jsx(gt,{className:"font-medium",children:h.title}),e.jsx(gt,{children:e.jsx(Oe,{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(Oe,{variant:h.active?"default":"secondary",children:h.active?"Active":"Inactive"})}),e.jsxs(gt,{className:"flex gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{l(h),c(!0)},children:e.jsx(Ya,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>u.mutate(h.id),children:e.jsx(Sn,{className:"h-4 w-4 text-destructive"})})]})]},h.id)})})]})}),e.jsx(Ls,{open:o,onOpenChange:c,children:e.jsxs(Ps,{className:"max-w-2xl",children:[e.jsx(Os,{children:e.jsxs(Ds,{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(J,{htmlFor:"title",children:"Title"}),e.jsx(xe,{id:"title",name:"title",defaultValue:i==null?void 0:i.title,required:!0})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"action_type_id",children:"Action Type"}),e.jsxs(is,{name:"action_type_id",defaultValue:i==null?void 0:i.action_type_id,children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Select action type"})}),e.jsx(as,{children:t.map(h=>e.jsx(He,{value:h.id,children:h.name},h.id))})]})]})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"tone",children:"Tone (optional)"}),e.jsx(xe,{id:"tone",name:"tone",defaultValue:(i==null?void 0:i.tone)||"",placeholder:"e.g., Friendly, Professional, Casual"})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"script_body",children:"Script Body"}),e.jsx(Ms,{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(yr,{className:"mt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsxs(B,{type:"submit",disabled:d.isPending,children:[d.isPending&&e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function nMn({plans:s,actionTypes:t,scripts:n,isLoading:r}){const{toast:a}=vi(),i=Bt(),[l,o]=_.useState(null),[c,d]=_.useState(!1),[u,h]=_.useState(null),[m,p]=_.useState(!1),[f,y]=_.useState(null),[v,g]=_.useState(null),{data:b}=at({queryKey:["plan-items",u],queryFn:async()=>{if(!u)return[];const{data:I,error:D}=await q.from("touchpoint_plan_items").select("*").eq("plan_id",u).order("month_number");if(D)throw D;return I},enabled:!!u}),j=mt({mutationFn:async I=>{if(I.id){const{error:D}=await q.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 q.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"})}}),S=mt({mutationFn:async I=>{if(I.id){const{error:D}=await q.from("touchpoint_plan_items").update({action_type_id:I.action_type_id,default_script_id:I.default_script_id,notes:I.notes}).eq("id",I.id);if(D)throw D}else{const{error:D}=await q.from("touchpoint_plan_items").insert([{plan_id:I.plan_id,month_number:I.month_number,action_type_id:I.action_type_id,default_script_id:I.default_script_id,notes:I.notes}]);if(D)throw D}},onSuccess:()=>{i.invalidateQueries({queryKey:["plan-items",u]}),a({title:"Item saved"})}}),C=mt({mutationFn:async I=>{const{error:D}=await q.from("touchpoint_plan_items").delete().eq("id",I);if(D)throw D},onSuccess:()=>{i.invalidateQueries({queryKey:["plan-items",u]})}}),E=mt({mutationFn:async I=>{const{data:D,error:O}=await q.from("action_scripts").insert([{...I,active:!0}]).select().single();if(O)throw O;return D},onSuccess:async I=>{i.invalidateQueries({queryKey:["admin-action-scripts"]}),f&&await S.mutateAsync({id:f.itemId,plan_id:u,month_number:f.month,action_type_id:f.actionTypeId,default_script_id:I.id}),p(!1),y(null),a({title:"Script created and assigned"})},onError:I=>{a({title:"Error",description:I.message,variant:"destructive"})}}),P=(I,D,O)=>{y({month:I,actionTypeId:D,itemId:O}),p(!0)},M=I=>n.find(D=>D.id===I);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(St,{children:"Touchpoint Plans"}),e.jsx(kn,{children:"Create annual touchpoint plans that agents can apply to their contacts"})]}),e.jsxs(B,{onClick:()=>{o(null),d(!0)},children:[e.jsx(rn,{className:"h-4 w-4 mr-2"}),"Add Plan"]})]}),e.jsx(Me,{children:r?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(Ct,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:s.map(I=>e.jsxs(ve,{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(St,{className:"text-base",children:I.name}),e.jsx(B,{variant:"ghost",size:"icon",onClick:D=>{D.stopPropagation(),o(I),d(!0)},children:e.jsx(Ya,{className:"h-4 w-4"})})]})}),e.jsxs(Me,{children:[e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2",children:I.description}),e.jsx(Oe,{variant:I.active?"default":"secondary",className:"mt-2",children:I.active?"Active":"Inactive"})]})]},I.id))})})]}),u&&e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsx(St,{children:"Plan Schedule"}),e.jsx(kn,{children:"Configure the monthly touchpoint schedule. Select an action type for each month, then assign or create a script."})]}),e.jsx(Me,{children:e.jsx("div",{className:"grid gap-3",children:Array.from({length:12},(I,D)=>D+1).map(I=>{const D=b==null?void 0:b.find(G=>G.month_number===I),O=D!=null&&D.default_script_id?M(D.default_script_id):null,V=n.filter(G=>G.action_type_id===(D==null?void 0:D.action_type_id)&&G.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(is,{value:(D==null?void 0:D.action_type_id)||"none",onValueChange:G=>{G==="none"&&D?C.mutate(D.id):G!=="none"&&S.mutate({id:D==null?void 0:D.id,plan_id:u,month_number:I,action_type_id:G,default_script_id:null})},children:[e.jsx(rs,{className:"w-40",children:e.jsx(ls,{placeholder:"No action"})}),e.jsxs(as,{children:[e.jsx(He,{value:"none",children:"No action"}),t.filter(G=>G.active).map(G=>e.jsx(He,{value:G.id,children:e.jsxs("span",{className:"flex items-center gap-2",children:[G.color&&e.jsx("span",{className:"w-3 h-3 rounded-full",style:{backgroundColor:G.color}}),G.name]})},G.id))]})]}),D&&e.jsxs(e.Fragment,{children:[e.jsxs(is,{value:D.default_script_id||"none",onValueChange:G=>{g(null),S.mutate({id:D.id,default_script_id:G==="none"?null:G})},children:[e.jsx(rs,{className:"w-56",children:e.jsx(ls,{placeholder:"Select script"})}),e.jsxs(as,{children:[e.jsx(He,{value:"none",children:"No default script"}),V.map(G=>e.jsxs(He,{value:G.id,children:[G.title," ",G.tone&&`(${G.tone})`]},G.id))]})]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>P(I,D.action_type_id,D.id),children:[e.jsx(rn,{className:"h-3 w-3 mr-1"}),"New Script"]}),O&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>g((v==null?void 0:v.id)===O.id?null:O),children:(v==null?void 0:v.id)===O.id?"Hide":"Preview"})]})]}),v&&(D==null?void 0:D.default_script_id)===v.id&&e.jsxs("div",{className:"ml-24 p-3 bg-muted rounded-lg text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Oe,{variant:"outline",children:v.title}),v.tone&&e.jsx(Oe,{variant:"secondary",children:v.tone})]}),e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:v.script_body})]})]},I)})})})]}),e.jsx(Ls,{open:c,onOpenChange:d,children:e.jsxs(Ps,{children:[e.jsx(Os,{children:e.jsxs(Ds,{children:[l?"Edit":"Add"," Touchpoint Plan"]})}),e.jsxs("form",{onSubmit:I=>{I.preventDefault();const D=new FormData(I.currentTarget);j.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(J,{htmlFor:"name",children:"Name"}),e.jsx(xe,{id:"name",name:"name",defaultValue:l==null?void 0:l.name,required:!0})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"description",children:"Description"}),e.jsx(Ms,{id:"description",name:"description",defaultValue:(l==null?void 0:l.description)||"",rows:3})]})]}),e.jsxs(yr,{className:"mt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>d(!1),children:"Cancel"}),e.jsxs(B,{type:"submit",disabled:j.isPending,children:[j.isPending&&e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})}),e.jsx(Ls,{open:m,onOpenChange:p,children:e.jsxs(Ps,{className:"max-w-2xl",children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Create New Script"}),e.jsxs(_r,{children:["Create a script for Month ",f==null?void 0:f.month,". Use ","{{FirstName}}",", ","{{LastName}}",", and ","{{AgentName}}"," as placeholders."]})]}),e.jsxs("form",{onSubmit:I=>{I.preventDefault();const D=new FormData(I.currentTarget);E.mutate({title:D.get("title"),action_type_id:f.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(J,{htmlFor:"script_title",children:"Title"}),e.jsx(xe,{id:"script_title",name:"title",placeholder:"e.g., Warm Check-In",required:!0})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"script_tone",children:"Tone"}),e.jsx(xe,{id:"script_tone",name:"tone",placeholder:"e.g., Friendly, Professional"})]})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"script_body",children:"Script Body"}),e.jsx(Ms,{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(yr,{className:"mt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>p(!1),children:"Cancel"}),e.jsxs(B,{type:"submit",disabled:E.isPending,children:[E.isPending&&e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),"Create & Assign"]})]})]})]})})]})}function rMn({flags:s}){const{toast:t}=vi(),n=Bt(),r=async(a,i)=>{const{error:l}=await q.from("feature_flags").update({...i,updated_at:new Date().toISOString()}).eq("id",a.id);l?t({title:"Error",description:l.message,variant:"destructive"}):(n.invalidateQueries({queryKey:["admin-feature-flags"]}),t({title:"Flag updated"}))};return e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsx(St,{children:"Feature Flags"}),e.jsx(kn,{children:"Control which features are enabled for members"})]}),e.jsx(Me,{children:e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"Flag"}),e.jsx(Pt,{children:"Status"}),e.jsx(Pt,{children:"Notes"}),e.jsx(Pt,{children:"Last Updated"})]})}),e.jsx(Ka,{children:s.map(a=>e.jsxs(pn,{children:[e.jsx(gt,{className:"font-mono text-sm",children:a.key}),e.jsx(gt,{children:e.jsx(fn,{checked:a.enabled,onCheckedChange:i=>r(a,{enabled:i})})}),e.jsx(gt,{children:e.jsx(xe,{defaultValue:a.notes||"",placeholder:"Add notes...",className:"max-w-xs",onBlur:i=>{i.target.value!==a.notes&&r(a,{notes:i.target.value})}})}),e.jsx(gt,{className:"text-muted-foreground text-sm",children:new Date(a.updated_at).toLocaleDateString()})]},a.id))})]})})]})}function aMn({items:s,isLoading:t}){const{toast:n}=vi(),r=Bt(),[a,i]=_.useState(null),[l,o]=_.useState(!1),c=mt({mutationFn:async h=>{if(h.id){const{error:m}=await q.from("popby_items").update({name:h.name,description:h.description}).eq("id",h.id);if(m)throw m}else{const{error:m}=await q.from("popby_items").insert([{name:h.name,description:h.description,owner_user_id:null}]);if(m)throw m}},onSuccess:()=>{r.invalidateQueries({queryKey:["admin-popby-items"]}),r.invalidateQueries({queryKey:["popby-items"]}),o(!1),i(null),n({title:"Saved successfully"})},onError:h=>{n({title:"Error",description:h.message,variant:"destructive"})}}),d=async h=>{await q.from("popby_items").update({is_active:!h.is_active}).eq("id",h.id),r.invalidateQueries({queryKey:["admin-popby-items"]}),r.invalidateQueries({queryKey:["popby-items"]})},u=async h=>{await q.from("popby_items").delete().eq("id",h),r.invalidateQueries({queryKey:["admin-popby-items"]}),r.invalidateQueries({queryKey:["popby-items"]}),n({title:"Deleted successfully"})};return e.jsxs(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(St,{children:"Popby Ideas"}),e.jsx(kn,{children:"Manage global popby ideas that all agents can see"})]}),e.jsxs(B,{onClick:()=>{i(null),o(!0)},children:[e.jsx(rn,{className:"h-4 w-4 mr-2"}),"Add Popby Idea"]})]}),e.jsx(Me,{children:t?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(Ct,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):s.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Vo,{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(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"Name"}),e.jsx(Pt,{children:"Description"}),e.jsx(Pt,{children:"Status"}),e.jsx(Pt,{className:"w-24",children:"Actions"})]})}),e.jsx(Ka,{children:s.map(h=>e.jsxs(pn,{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(fn,{checked:h.is_active,onCheckedChange:()=>d(h)})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{i(h),o(!0)},children:e.jsx(Ya,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>u(h.id),children:e.jsx(Sn,{className:"h-4 w-4 text-destructive"})})]})})]},h.id))})]})}),e.jsx(Ls,{open:l,onOpenChange:o,children:e.jsxs(Ps,{children:[e.jsx(Os,{children:e.jsxs(Ds,{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(J,{htmlFor:"name",children:"Name"}),e.jsx(xe,{id:"name",name:"name",defaultValue:a==null?void 0:a.name,required:!0,placeholder:"e.g., Homemade Cookies"})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"description",children:"Description"}),e.jsx(Ms,{id:"description",name:"description",defaultValue:(a==null?void 0:a.description)||"",placeholder:"Brief description of the popby idea..."})]})]}),e.jsxs(yr,{className:"mt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsxs(B,{type:"submit",disabled:c.isPending,children:[c.isPending&&e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function iMn(){var p;const{toast:s}=vi(),t=Bt(),[n,r]=_.useState(null),[a,i]=_.useState(!1),{data:l,isLoading:o}=at({queryKey:["admin-video-script-categories"],queryFn:async()=>{const{data:f,error:y}=await q.from("video_script_categories").select("*").order("sort_order");if(y)throw y;return f}}),{data:c,isLoading:d}=at({queryKey:["admin-video-scripts"],queryFn:async()=>{const{data:f,error:y}=await q.from("video_scripts").select("*, category:video_script_categories(*)").order("title");if(y)throw y;return f}}),u=mt({mutationFn:async f=>{var y,v;if(f.id){const{error:g}=await q.from("video_scripts").update({title:f.title,script_text:f.script_text,category_id:f.category_id,tags:((y=f.tags)==null?void 0:y.split(",").map(b=>b.trim()).filter(Boolean))||[]}).eq("id",f.id);if(g)throw g}else{const{error:g}=await q.from("video_scripts").insert([{title:f.title,script_text:f.script_text,category_id:f.category_id||null,tags:((v=f.tags)==null?void 0:v.split(",").map(b=>b.trim()).filter(Boolean))||[]}]);if(g)throw g}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-video-scripts"]}),i(!1),r(null),s({title:"Video script saved!"})},onError:f=>s({title:"Error",description:f.message,variant:"destructive"})}),h=async f=>{await q.from("video_scripts").update({is_active:!f.is_active}).eq("id",f.id),t.invalidateQueries({queryKey:["admin-video-scripts"]})},m=async f=>{await Xi("Delete this video script?")&&(await q.from("video_scripts").delete().eq("id",f),t.invalidateQueries({queryKey:["admin-video-scripts"]}),s({title:"Script deleted"}))};return e.jsxs(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(St,{children:"Video Scripts"}),e.jsx(kn,{children:"Manage teleprompter scripts for Quick Video Touch"})]}),e.jsxs(B,{onClick:()=>{r(null),i(!0)},children:[e.jsx(rn,{className:"h-4 w-4 mr-2"}),"Add Script"]})]}),e.jsx(Me,{children:d?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(Ct,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"Title"}),e.jsx(Pt,{children:"Category"}),e.jsx(Pt,{children:"Status"}),e.jsx(Pt,{className:"w-24",children:"Actions"})]})}),e.jsx(Ka,{children:c==null?void 0:c.map(f=>{var y;return e.jsxs(pn,{children:[e.jsx(gt,{className:"font-medium",children:f.title}),e.jsx(gt,{className:"text-muted-foreground",children:((y=f.category)==null?void 0:y.name)||"Uncategorized"}),e.jsx(gt,{children:e.jsx(fn,{checked:f.is_active,onCheckedChange:()=>h(f)})}),e.jsxs(gt,{className:"flex gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{r(f),i(!0)},children:e.jsx(Ya,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>m(f.id),children:e.jsx(Sn,{className:"h-4 w-4"})})]})]},f.id)})})]})}),e.jsx(Ls,{open:a,onOpenChange:i,children:e.jsxs(Ps,{className:"max-w-2xl",children:[e.jsx(Os,{children:e.jsxs(Ds,{children:[n?"Edit":"Add"," Video Script"]})}),e.jsxs("form",{onSubmit:f=>{f.preventDefault();const y=new FormData(f.currentTarget);u.mutate({id:n==null?void 0:n.id,title:y.get("title"),script_text:y.get("script_text"),category_id:y.get("category_id")||null,tags:y.get("tags")})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(J,{htmlFor:"title",children:"Title"}),e.jsx(xe,{id:"title",name:"title",defaultValue:n==null?void 0:n.title,required:!0})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"category_id",children:"Category"}),e.jsxs(is,{name:"category_id",defaultValue:(n==null?void 0:n.category_id)||"",children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Select category"})}),e.jsx(as,{children:l==null?void 0:l.map(f=>e.jsx(He,{value:f.id,children:f.name},f.id))})]})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"script_text",children:"Script Text"}),e.jsx(Ms,{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(J,{htmlFor:"tags",children:"Tags (comma-separated)"}),e.jsx(xe,{id:"tags",name:"tags",defaultValue:((p=n==null?void 0:n.tags)==null?void 0:p.join(", "))||"",placeholder:"birthday, follow-up, thank-you"})]})]}),e.jsxs(yr,{className:"mt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>i(!1),children:"Cancel"}),e.jsxs(B,{type:"submit",disabled:u.isPending,children:[u.isPending&&e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function oMn(){const{toast:s}=vi(),[t,n]=_.useState(""),[r,a]=_.useState(!0),[i,l]=_.useState(!1);_.useEffect(()=>{(async()=>{a(!0);try{const{data:d}=await q.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();d!=null&&d.value&&n(d.value)}catch(d){console.error("Error fetching settings:",d)}a(!1)})()},[]);const o=async()=>{l(!0);try{await q.from("settings").upsert({key:"mapbox_public_token",value:t.trim()}),s({title:"Mapbox token saved!"})}catch{s({title:"Error saving token",variant:"destructive"})}l(!1)};return r?e.jsx(ve,{children:e.jsx(Me,{className:"flex justify-center py-8",children:e.jsx(Ct,{className:"h-8 w-8 animate-spin text-muted-foreground"})})}):e.jsx("div",{className:"space-y-6",children:e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(Xa,{className:"h-5 w-5"}),"Popby Map Settings"]}),e.jsx(kn,{children:"Configure the map feature for popbys"})]}),e.jsxs(Me,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"mapbox-token",children:"Mapbox Public Token"}),e.jsx(xe,{id:"mapbox-token",placeholder:"pk.eyJ1I...",value:t,onChange:c=>n(c.target.value)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Get your token at"," ",e.jsx("a",{href:"https://mapbox.com/",target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline",children:"mapbox.com"}),". This token will be used by all agents for the popby map feature."]})]}),e.jsxs(B,{onClick:o,disabled:i,children:[i&&e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),"Save Token"]}),t&&e.jsx(Oe,{variant:"secondary",className:"ml-2",children:"Token configured"})]})]})})}const lMn=()=>{const[s,t]=_.useState(""),[n,r]=_.useState("grid"),a=Fn(),{data:i=[],isLoading:l}=at({queryKey:["additional-services"],queryFn:async()=>{const{data:c,error:d}=await q.from("additional_services").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(d)throw d;return c}}),o=i.filter(c=>{var u;return c.name.toLowerCase().includes(s.toLowerCase())||((u=c.description)==null?void 0:u.toLowerCase().includes(s.toLowerCase()))});return e.jsx(zs,{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(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search services...",value:s,onChange:c=>t(c.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex gap-2",children:[s&&e.jsx(B,{variant:"outline",size:"sm",onClick:()=>t(""),children:"Clear"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{variant:n==="grid"?"secondary":"outline",size:"icon",onClick:()=>r("grid"),className:"rounded-full",children:e.jsx(sf,{className:"h-4 w-4"})}),e.jsx(B,{variant:n==="list"?"secondary":"outline",size:"icon",onClick:()=>r("list"),className:"rounded-full",children:e.jsx(A0,{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(ve,{children:e.jsxs(Me,{className:"p-4",children:[e.jsx(cn,{className:"aspect-[3/2] w-full rounded-lg mb-4"}),e.jsx(cn,{className:"h-5 w-3/4 mb-2"}),e.jsx(cn,{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(B,{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(ve,{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(un,{className:"h-8 w-8"})})}),e.jsxs(Me,{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:Hee(c.description)})]})]},c.id))})]})})},cMn=()=>{const{serviceId:s}=Li(),t=Fn(),{data:n,isLoading:r}=at({queryKey:["additional-service",s],queryFn:async()=>{const{data:a,error:i}=await q.from("additional_services").select("*").eq("id",s).eq("is_published",!0).single();if(i)throw i;return a},enabled:!!s});return r?e.jsx(zs,{title:"Loading...",children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsx(cn,{className:"h-8 w-48"}),e.jsx(cn,{className:"h-64 w-full rounded-lg"}),e.jsx(cn,{className:"h-24 w-full"})]})}):n?e.jsx(zs,{title:n.name,children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsxs(B,{variant:"ghost",onClick:()=>t("/additional-services"),className:"gap-2",children:[e.jsx(ka,{className:"h-4 w-4"}),"Back to Services"]}),e.jsx(ve,{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(un,{className:"h-16 w-16"})})})}),e.jsx(ve,{children:e.jsxs(Me,{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(ga,{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(B,{size:"lg",className:"gap-2",onClick:()=>window.open(n.signup_link_url,"_blank"),children:[e.jsx(wr,{className:"h-5 w-5"}),"Sign Up Now"]})})]})})]})}):e.jsx(zs,{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(B,{onClick:()=>t("/additional-services"),children:[e.jsx(ka,{className:"h-4 w-4 mr-2"}),"Back to Services"]})]})})},uZ=[{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 dMn(){const[s,t]=_.useState(uZ[0].id),n=uZ.find(r=>r.id===s)||uZ[0];return e.jsx(zs,{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(V4,{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(is,{value:s,onValueChange:t,children:[e.jsx(rs,{className:"w-full",children:e.jsx(ls,{placeholder:"Select a tool"})}),e.jsx(as,{children:uZ.map(r=>e.jsx(He,{value:r.id,children:r.name},r.id))})]})}),e.jsx("div",{className:"hidden md:block",children:e.jsx(Yr,{value:s,onValueChange:t,className:"w-full",children:e.jsx(Zr,{className:"w-full flex-wrap h-auto gap-1 bg-muted p-1",children:uZ.map(r=>e.jsx(Ht,{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 uMn(s,t){const n={};return(s[s.length-1]===""?[...s,""]:s).join((n.padRight?" ":"")+","+(n.padLeft===!1?"":" ")).trim()}const hMn=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,mMn=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,pMn={};function djt(s,t){return(pMn.jsx?mMn:hMn).test(s)}const fMn=/[ \t\n\f\r]/g;function xMn(s){return typeof s=="object"?s.type==="text"?ujt(s.value):!1:ujt(s)}function ujt(s){return s.replace(fMn,"")===""}class Lae{constructor(t,n,r){this.normal=n,this.property=t,r&&(this.space=r)}}Lae.prototype.normal={};Lae.prototype.property={};Lae.prototype.space=void 0;function IKt(s,t){const n={},r={};for(const a of s)Object.assign(n,a.property),Object.assign(r,a.normal);return new Lae(n,r,t)}function aWe(s){return s.toLowerCase()}class Q_{constructor(t,n){this.attribute=n,this.property=t}}Q_.prototype.attribute="";Q_.prototype.booleanish=!1;Q_.prototype.boolean=!1;Q_.prototype.commaOrSpaceSeparated=!1;Q_.prototype.commaSeparated=!1;Q_.prototype.defined=!1;Q_.prototype.mustUseProperty=!1;Q_.prototype.number=!1;Q_.prototype.overloadedBoolean=!1;Q_.prototype.property="";Q_.prototype.spaceSeparated=!1;Q_.prototype.space=void 0;let gMn=0;const vc=az(),Cg=az(),iWe=az(),ni=az(),Cm=az(),A7=az(),Sw=az();function az(){return 2**++gMn}const oWe=Object.freeze(Object.defineProperty({__proto__:null,boolean:vc,booleanish:Cg,commaOrSpaceSeparated:Sw,commaSeparated:A7,number:ni,overloadedBoolean:iWe,spaceSeparated:Cm},Symbol.toStringTag,{value:"Module"})),V9e=Object.keys(oWe);class int extends Q_{constructor(t,n,r,a){let i=-1;if(super(t,n),hjt(this,"space",a),typeof r=="number")for(;++i4&&n.slice(0,4)==="data"&&wMn.test(t)){if(t.charAt(4)==="-"){const i=t.slice(5).replace(mjt,kMn);r="data"+i.charAt(0).toUpperCase()+i.slice(1)}else{const i=t.slice(4);if(!mjt.test(i)){let l=i.replace(_Mn,NMn);l.charAt(0)!=="-"&&(l="-"+l),t="data"+l}}a=int}return new a(r,t)}function NMn(s){return"-"+s.toLowerCase()}function kMn(s){return s.charAt(1).toUpperCase()}const SMn=IKt([DKt,yMn,OKt,zKt,BKt],"html"),ont=IKt([DKt,vMn,OKt,zKt,BKt],"svg");function CMn(s){return s.join(" ").trim()}var lnt={},pjt=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,AMn=/\n/g,EMn=/^\s*/,TMn=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,MMn=/^:\s*/,PMn=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,LMn=/^[;\s]*/,IMn=/^\s+|\s+$/g,DMn=` `,fjt="/",xjt="*",sF="",RMn="comment",FMn="declaration";function OMn(s,t){if(typeof s!="string")throw new TypeError("First argument must be a string");if(!s)return[];t=t||{};var n=1,r=1;function a(f){var y=f.match(AMn);y&&(n+=y.length);var v=f.lastIndexOf(DMn);r=~v?f.length-v:r+f.length}function i(){var f={line:n,column:r};return function(y){return y.position=new l(f),d(),y}}function l(f){this.start=f,this.end={line:n,column:r},this.source=t.source}l.prototype.content=s;function o(f){var y=new Error(t.source+":"+n+":"+r+": "+f);if(y.reason=f,y.filename=t.source,y.line=n,y.column=r,y.source=s,!t.silent)throw y}function c(f){var y=f.exec(s);if(y){var v=y[0];return a(v),s=s.slice(v.length),y}}function d(){c(EMn)}function u(f){var y;for(f=f||[];y=h();)y!==!1&&f.push(y);return f}function h(){var f=i();if(!(fjt!=s.charAt(0)||xjt!=s.charAt(1))){for(var y=2;sF!=s.charAt(y)&&(xjt!=s.charAt(y)||fjt!=s.charAt(y+1));)++y;if(y+=2,sF===s.charAt(y-1))return o("End of comment missing");var v=s.slice(2,y-2);return r+=2,a(v),s=s.slice(y),r+=2,f({type:RMn,comment:v})}}function m(){var f=i(),y=c(TMn);if(y){if(h(),!c(MMn))return o("property missing ':'");var v=c(PMn),g=f({type:FMn,property:gjt(y[0].replace(pjt,sF)),value:v?gjt(v[0].replace(pjt,sF)):sF});return c(LMn),g}}function p(){var f=[];u(f);for(var y;y=m();)y!==!1&&(f.push(y),u(f));return f}return d(),p()}function gjt(s){return s?s.replace(IMn,sF):sF}var zMn=OMn,BMn=Cp&&Cp.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(lnt,"__esModule",{value:!0});lnt.default=qMn;const UMn=BMn(zMn);function qMn(s,t){let n=null;if(!s||typeof s!="string")return n;const r=(0,UMn.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 VIe={};Object.defineProperty(VIe,"__esModule",{value:!0});VIe.camelCase=void 0;var $Mn=/^--[a-zA-Z0-9_-]+$/,VMn=/-([a-z])/g,HMn=/^[^-]+$/,GMn=/^-(webkit|moz|ms|o|khtml)-/,WMn=/^-(ms)-/,KMn=function(s){return!s||HMn.test(s)||$Mn.test(s)},YMn=function(s,t){return t.toUpperCase()},yjt=function(s,t){return"".concat(t,"-")},ZMn=function(s,t){return t===void 0&&(t={}),KMn(s)?s:(s=s.toLowerCase(),t.reactCompat?s=s.replace(WMn,yjt):s=s.replace(GMn,yjt),s.replace(VMn,YMn))};VIe.camelCase=ZMn;var XMn=Cp&&Cp.__importDefault||function(s){return s&&s.__esModule?s:{default:s}},QMn=XMn(lnt),JMn=VIe;function lWe(s,t){var n={};return!s||typeof s!="string"||(0,QMn.default)(s,function(r,a){r&&a&&(n[(0,JMn.camelCase)(r,t)]=a)}),n}lWe.default=lWe;var ePn=lWe;const tPn=_d(ePn),UKt=qKt("end"),cnt=qKt("start");function qKt(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 sPn(s){const t=cnt(s),n=UKt(s);if(t&&n)return{start:t,end:n}}function JJ(s){return!s||typeof s!="object"?"":"position"in s||"type"in s?vjt(s.position):"start"in s||"end"in s?vjt(s):"line"in s||"column"in s?cWe(s):""}function cWe(s){return bjt(s&&s.line)+":"+bjt(s&&s.column)}function vjt(s){return cWe(s&&s.start)+"-"+cWe(s&&s.end)}function bjt(s){return s&&typeof s=="number"?s:1}class S1 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=JJ(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}}S1.prototype.file="";S1.prototype.name="";S1.prototype.reason="";S1.prototype.message="";S1.prototype.stack="";S1.prototype.column=void 0;S1.prototype.line=void 0;S1.prototype.ancestors=void 0;S1.prototype.cause=void 0;S1.prototype.fatal=void 0;S1.prototype.place=void 0;S1.prototype.ruleId=void 0;S1.prototype.source=void 0;const dnt={}.hasOwnProperty,nPn=new Map,rPn=/[A-Z]/g,aPn=new Set(["table","tbody","thead","tfoot","tr"]),iPn=new Set(["td","th"]),$Kt="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function oPn(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=fPn(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=pPn(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"?ont:SMn,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},i=VKt(a,s,void 0);return i&&typeof i!="string"?i:a.create(s,a.Fragment,{children:i||void 0},void 0)}function VKt(s,t,n){if(t.type==="element")return lPn(s,t,n);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return cPn(s,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return uPn(s,t,n);if(t.type==="mdxjsEsm")return dPn(s,t);if(t.type==="root")return hPn(s,t,n);if(t.type==="text")return mPn(s,t)}function lPn(s,t,n){const r=s.schema;let a=r;t.tagName.toLowerCase()==="svg"&&r.space==="html"&&(a=ont,s.schema=a),s.ancestors.push(t);const i=GKt(s,t.tagName,!1),l=xPn(s,t);let o=hnt(s,t);return aPn.has(t.tagName)&&(o=o.filter(function(c){return typeof c=="string"?!xMn(c):!0})),HKt(s,l,i,t),unt(l,o),s.ancestors.pop(),s.schema=r,s.create(t,i,l,n)}function cPn(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)}mse(s,t.position)}function dPn(s,t){if(t.data&&t.data.estree&&s.evaluater)return s.evaluater.evaluateProgram(t.data.estree);mse(s,t.position)}function uPn(s,t,n){const r=s.schema;let a=r;t.name==="svg"&&r.space==="html"&&(a=ont,s.schema=a),s.ancestors.push(t);const i=t.name===null?s.Fragment:GKt(s,t.name,!0),l=gPn(s,t),o=hnt(s,t);return HKt(s,l,i,t),unt(l,o),s.ancestors.pop(),s.schema=r,s.create(t,i,l,n)}function hPn(s,t,n){const r={};return unt(r,hnt(s,t)),s.create(t,s.Fragment,r,n)}function mPn(s,t){return t.value}function HKt(s,t,n,r){typeof n!="string"&&n!==s.Fragment&&s.passNode&&(t.node=r)}function unt(s,t){if(t.length>0){const n=t.length>1?t:t[0];n&&(s.children=n)}}function pPn(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 fPn(s,t){return n;function n(r,a,i,l){const o=Array.isArray(i.children),c=cnt(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 xPn(s,t){const n={};let r,a;for(a in t.properties)if(a!=="children"&&dnt.call(t.properties,a)){const i=yPn(s,a,t.properties[a]);if(i){const[l,o]=i;s.tableCellAlignToStyle&&l==="align"&&typeof o=="string"&&iPn.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 gPn(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 mse(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 mse(s,t.position);else i=r.value===null?!0:r.value;n[a]=i}return n}function hnt(s,t){const n=[];let r=-1;const a=s.passKeys?new Map:nPn;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?(mC(s,s.length,0,t),s):t}const jjt={}.hasOwnProperty;function SPn(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 D$(s){return s.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const N4=ML(/[A-Za-z]/),nj=ML(/[\dA-Za-z]/),EPn=ML(/[#-'*+\--9=?A-Z^-~]/);function dWe(s){return s!==null&&(s<32||s===127)}const uWe=ML(/\d/),TPn=ML(/[\dA-Fa-f]/),MPn=ML(/[!-/:-@[-`{-~]/);function lc(s){return s!==null&&s<-2}function q_(s){return s!==null&&(s<0||s===32)}function lh(s){return s===-2||s===-1||s===32}const PPn=ML(new RegExp("\\p{P}|\\p{S}","u")),LPn=ML(/\s/);function ML(s){return t;function t(n){return n!==null&&n>-1&&s.test(String.fromCharCode(n))}}function qW(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 ep(s,t,n,r){const a=r?r-1:Number.POSITIVE_INFINITY;let i=0;return l;function l(c){return lh(c)?(s.enter(n),o(c)):t(c)}function o(c){return lh(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(g(r),E=P;Ej;){const C=n[S];t.containerState=C[1],C[0].exit.call(t,s)}n.length=j}function b(){a.write([null]),i=void 0,a=void 0,t.containerState._closeFlow=void 0}}function OPn(s,t,n){return ep(s,s.attempt(this.parser.constructs.document,t,n),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function kjt(s){if(s===null||q_(s)||LPn(s))return 1;if(PPn(s))return 2}function pnt(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};Sjt(h,-c),Sjt(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=H2(d,[["enter",s[r][1],t],["exit",s[r][1],t]])),d=H2(d,[["enter",a,t],["enter",l,t],["exit",l,t],["enter",i,t]]),d=H2(d,pnt(t.parser.constructs.insideSpan.null,s.slice(r+1,n),t)),d=H2(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=H2(d,[["enter",s[n][1],t],["exit",s[n][1],t]])):u=0,mC(s,r-1,n-r+3,d),n=r+d.length-u-2;break}}for(n=-1;++n0&&lh(E)?ep(s,b,"linePrefix",i+1)(E):b(E)}function b(E){return E===null||lc(E)?s.check(Cjt,y,S)(E):(s.enter("codeFlowValue"),j(E))}function j(E){return E===null||lc(E)?(s.exit("codeFlowValue"),b(E)):(s.consume(E),j)}function S(E){return s.exit("codeFenced"),t(E)}function C(E,P,M){let I=0;return D;function D(H){return E.enter("lineEnding"),E.consume(H),E.exit("lineEnding"),O}function O(H){return E.enter("codeFencedFence"),lh(H)?ep(E,V,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(H):V(H)}function V(H){return H===o?(E.enter("codeFencedFenceSequence"),G(H)):M(H)}function G(H){return H===o?(I++,E.consume(H),G):I>=l?(E.exit("codeFencedFenceSequence"),lh(H)?ep(E,$,"whitespace")(H):$(H)):M(H)}function $(H){return H===null||lc(H)?(E.exit("codeFencedFence"),P(H)):M(H)}}}function ZPn(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 G9e={name:"codeIndented",tokenize:QPn},XPn={partial:!0,tokenize:JPn};function QPn(s,t,n){const r=this;return a;function a(d){return s.enter("codeIndented"),ep(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):lc(d)?s.attempt(XPn,l,c)(d):(s.enter("codeFlowValue"),o(d))}function o(d){return d===null||lc(d)?(s.exit("codeFlowValue"),l(d)):(s.consume(d),o)}function c(d){return s.exit("codeIndented"),t(d)}}function JPn(s,t,n){const r=this;return a;function a(l){return r.parser.lazy[r.now().line]?n(l):lc(l)?(s.enter("lineEnding"),s.consume(l),s.exit("lineEnding"),a):ep(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):lc(l)?a(l):n(l)}}const eLn={name:"codeText",previous:sLn,resolve:tLn,tokenize:nLn};function tLn(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&&hZ(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),hZ(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),hZ(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 JKt(s,t,n,r,a,i,l,o,c){const d=c||Number.POSITIVE_INFINITY;let u=0;return h;function h(g){return g===60?(s.enter(r),s.enter(a),s.enter(i),s.consume(g),s.exit(i),m):g===null||g===32||g===41||dWe(g)?n(g):(s.enter(r),s.enter(l),s.enter(o),s.enter("chunkString",{contentType:"string"}),y(g))}function m(g){return g===62?(s.enter(i),s.consume(g),s.exit(i),s.exit(a),s.exit(r),t):(s.enter(o),s.enter("chunkString",{contentType:"string"}),p(g))}function p(g){return g===62?(s.exit("chunkString"),s.exit(o),m(g)):g===null||g===60||lc(g)?n(g):(s.consume(g),g===92?f:p)}function f(g){return g===60||g===62||g===92?(s.consume(g),p):p(g)}function y(g){return!u&&(g===null||g===41||q_(g))?(s.exit("chunkString"),s.exit(o),s.exit(l),s.exit(r),t(g)):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):lc(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||lc(p)||o++>999?(s.exit("chunkString"),u(p)):(s.consume(p),c||(c=!lh(p)),p===92?m:h)}function m(p){return p===91||p===92||p===93?(s.consume(p),o++,h):h(p)}}function tYt(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):lc(m)?(s.enter("lineEnding"),s.consume(m),s.exit("lineEnding"),ep(s,d,"linePrefix")):(s.enter("chunkString",{contentType:"string"}),u(m))}function u(m){return m===l||m===null||lc(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 eee(s,t){let n;return r;function r(a){return lc(a)?(s.enter("lineEnding"),s.consume(a),s.exit("lineEnding"),n=!0,r):lh(a)?ep(s,r,n?"linePrefix":"lineSuffix")(a):t(a)}}const uLn={name:"definition",tokenize:mLn},hLn={partial:!0,tokenize:pLn};function mLn(s,t,n){const r=this;let a;return i;function i(p){return s.enter("definition"),l(p)}function l(p){return eYt.call(r,s,o,n,"definitionLabel","definitionLabelMarker","definitionLabelString")(p)}function o(p){return a=D$(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 q_(p)?eee(s,d)(p):d(p)}function d(p){return JKt(s,u,n,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(p)}function u(p){return s.attempt(hLn,h,h)(p)}function h(p){return lh(p)?ep(s,m,"whitespace")(p):m(p)}function m(p){return p===null||lc(p)?(s.exit("definition"),r.parser.defined.push(a),t(p)):n(p)}}function pLn(s,t,n){return r;function r(o){return q_(o)?eee(s,a)(o):n(o)}function a(o){return tYt(s,i,n,"definitionTitle","definitionTitleMarker","definitionTitleString")(o)}function i(o){return lh(o)?ep(s,l,"whitespace")(o):l(o)}function l(o){return o===null||lc(o)?t(o):n(o)}}const fLn={name:"hardBreakEscape",tokenize:xLn};function xLn(s,t,n){return r;function r(i){return s.enter("hardBreakEscape"),s.consume(i),a}function a(i){return lc(i)?(s.exit("hardBreakEscape"),t(i)):n(i)}}const gLn={name:"headingAtx",resolve:yLn,tokenize:vLn};function yLn(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"},mC(s,r,n-r+1,[["enter",a,t],["enter",i,t],["exit",i,t],["exit",a,t]])),s}function vLn(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||q_(u)?(s.exit("atxHeadingSequence"),o(u)):n(u)}function o(u){return u===35?(s.enter("atxHeadingSequence"),c(u)):u===null||lc(u)?(s.exit("atxHeading"),t(u)):lh(u)?ep(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||q_(u)?(s.exit("atxHeadingText"),o(u)):(s.consume(u),d)}}const bLn=["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"],Ejt=["pre","script","style","textarea"],_Ln={concrete:!0,name:"htmlFlow",resolveTo:NLn,tokenize:kLn},wLn={partial:!0,tokenize:CLn},jLn={partial:!0,tokenize:SLn};function NLn(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 kLn(s,t,n){const r=this;let a,i,l,o,c;return d;function d(le){return u(le)}function u(le){return s.enter("htmlFlow"),s.enter("htmlFlowData"),s.consume(le),h}function h(le){return le===33?(s.consume(le),m):le===47?(s.consume(le),i=!0,y):le===63?(s.consume(le),a=3,r.interrupt?t:ie):N4(le)?(s.consume(le),l=String.fromCharCode(le),v):n(le)}function m(le){return le===45?(s.consume(le),a=2,p):le===91?(s.consume(le),a=5,o=0,f):N4(le)?(s.consume(le),a=4,r.interrupt?t:ie):n(le)}function p(le){return le===45?(s.consume(le),r.interrupt?t:ie):n(le)}function f(le){const be="CDATA[";return le===be.charCodeAt(o++)?(s.consume(le),o===be.length?r.interrupt?t:V:f):n(le)}function y(le){return N4(le)?(s.consume(le),l=String.fromCharCode(le),v):n(le)}function v(le){if(le===null||le===47||le===62||q_(le)){const be=le===47,me=l.toLowerCase();return!be&&!i&&Ejt.includes(me)?(a=1,r.interrupt?t(le):V(le)):bLn.includes(l.toLowerCase())?(a=6,be?(s.consume(le),g):r.interrupt?t(le):V(le)):(a=7,r.interrupt&&!r.parser.lazy[r.now().line]?n(le):i?b(le):j(le))}return le===45||nj(le)?(s.consume(le),l+=String.fromCharCode(le),v):n(le)}function g(le){return le===62?(s.consume(le),r.interrupt?t:V):n(le)}function b(le){return lh(le)?(s.consume(le),b):D(le)}function j(le){return le===47?(s.consume(le),D):le===58||le===95||N4(le)?(s.consume(le),S):lh(le)?(s.consume(le),j):D(le)}function S(le){return le===45||le===46||le===58||le===95||nj(le)?(s.consume(le),S):C(le)}function C(le){return le===61?(s.consume(le),E):lh(le)?(s.consume(le),C):j(le)}function E(le){return le===null||le===60||le===61||le===62||le===96?n(le):le===34||le===39?(s.consume(le),c=le,P):lh(le)?(s.consume(le),E):M(le)}function P(le){return le===c?(s.consume(le),c=null,I):le===null||lc(le)?n(le):(s.consume(le),P)}function M(le){return le===null||le===34||le===39||le===47||le===60||le===61||le===62||le===96||q_(le)?C(le):(s.consume(le),M)}function I(le){return le===47||le===62||lh(le)?j(le):n(le)}function D(le){return le===62?(s.consume(le),O):n(le)}function O(le){return le===null||lc(le)?V(le):lh(le)?(s.consume(le),O):n(le)}function V(le){return le===45&&a===2?(s.consume(le),Y):le===60&&a===1?(s.consume(le),Z):le===62&&a===4?(s.consume(le),te):le===63&&a===3?(s.consume(le),ie):le===93&&a===5?(s.consume(le),ce):lc(le)&&(a===6||a===7)?(s.exit("htmlFlowData"),s.check(wLn,ae,G)(le)):le===null||lc(le)?(s.exit("htmlFlowData"),G(le)):(s.consume(le),V)}function G(le){return s.check(jLn,$,ae)(le)}function $(le){return s.enter("lineEnding"),s.consume(le),s.exit("lineEnding"),H}function H(le){return le===null||lc(le)?G(le):(s.enter("htmlFlowData"),V(le))}function Y(le){return le===45?(s.consume(le),ie):V(le)}function Z(le){return le===47?(s.consume(le),l="",ne):V(le)}function ne(le){if(le===62){const be=l.toLowerCase();return Ejt.includes(be)?(s.consume(le),te):V(le)}return N4(le)&&l.length<8?(s.consume(le),l+=String.fromCharCode(le),ne):V(le)}function ce(le){return le===93?(s.consume(le),ie):V(le)}function ie(le){return le===62?(s.consume(le),te):le===45&&a===2?(s.consume(le),ie):V(le)}function te(le){return le===null||lc(le)?(s.exit("htmlFlowData"),ae(le)):(s.consume(le),te)}function ae(le){return s.exit("htmlFlow"),t(le)}}function SLn(s,t,n){const r=this;return a;function a(l){return lc(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 CLn(s,t,n){return r;function r(a){return s.enter("lineEnding"),s.consume(a),s.exit("lineEnding"),s.attempt(HIe,t,n)}}const ALn={name:"htmlText",tokenize:ELn};function ELn(s,t,n){const r=this;let a,i,l;return o;function o(ie){return s.enter("htmlText"),s.enter("htmlTextData"),s.consume(ie),c}function c(ie){return ie===33?(s.consume(ie),d):ie===47?(s.consume(ie),C):ie===63?(s.consume(ie),j):N4(ie)?(s.consume(ie),M):n(ie)}function d(ie){return ie===45?(s.consume(ie),u):ie===91?(s.consume(ie),i=0,f):N4(ie)?(s.consume(ie),b):n(ie)}function u(ie){return ie===45?(s.consume(ie),p):n(ie)}function h(ie){return ie===null?n(ie):ie===45?(s.consume(ie),m):lc(ie)?(l=h,Z(ie)):(s.consume(ie),h)}function m(ie){return ie===45?(s.consume(ie),p):h(ie)}function p(ie){return ie===62?Y(ie):ie===45?m(ie):h(ie)}function f(ie){const te="CDATA[";return ie===te.charCodeAt(i++)?(s.consume(ie),i===te.length?y:f):n(ie)}function y(ie){return ie===null?n(ie):ie===93?(s.consume(ie),v):lc(ie)?(l=y,Z(ie)):(s.consume(ie),y)}function v(ie){return ie===93?(s.consume(ie),g):y(ie)}function g(ie){return ie===62?Y(ie):ie===93?(s.consume(ie),g):y(ie)}function b(ie){return ie===null||ie===62?Y(ie):lc(ie)?(l=b,Z(ie)):(s.consume(ie),b)}function j(ie){return ie===null?n(ie):ie===63?(s.consume(ie),S):lc(ie)?(l=j,Z(ie)):(s.consume(ie),j)}function S(ie){return ie===62?Y(ie):j(ie)}function C(ie){return N4(ie)?(s.consume(ie),E):n(ie)}function E(ie){return ie===45||nj(ie)?(s.consume(ie),E):P(ie)}function P(ie){return lc(ie)?(l=P,Z(ie)):lh(ie)?(s.consume(ie),P):Y(ie)}function M(ie){return ie===45||nj(ie)?(s.consume(ie),M):ie===47||ie===62||q_(ie)?I(ie):n(ie)}function I(ie){return ie===47?(s.consume(ie),Y):ie===58||ie===95||N4(ie)?(s.consume(ie),D):lc(ie)?(l=I,Z(ie)):lh(ie)?(s.consume(ie),I):Y(ie)}function D(ie){return ie===45||ie===46||ie===58||ie===95||nj(ie)?(s.consume(ie),D):O(ie)}function O(ie){return ie===61?(s.consume(ie),V):lc(ie)?(l=O,Z(ie)):lh(ie)?(s.consume(ie),O):I(ie)}function V(ie){return ie===null||ie===60||ie===61||ie===62||ie===96?n(ie):ie===34||ie===39?(s.consume(ie),a=ie,G):lc(ie)?(l=V,Z(ie)):lh(ie)?(s.consume(ie),V):(s.consume(ie),$)}function G(ie){return ie===a?(s.consume(ie),a=void 0,H):ie===null?n(ie):lc(ie)?(l=G,Z(ie)):(s.consume(ie),G)}function $(ie){return ie===null||ie===34||ie===39||ie===60||ie===61||ie===96?n(ie):ie===47||ie===62||q_(ie)?I(ie):(s.consume(ie),$)}function H(ie){return ie===47||ie===62||q_(ie)?I(ie):n(ie)}function Y(ie){return ie===62?(s.consume(ie),s.exit("htmlTextData"),s.exit("htmlText"),t):n(ie)}function Z(ie){return s.exit("htmlTextData"),s.enter("lineEnding"),s.consume(ie),s.exit("lineEnding"),ne}function ne(ie){return lh(ie)?ep(s,ce,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(ie):ce(ie)}function ce(ie){return s.enter("htmlTextData"),l(ie)}}const fnt={name:"labelEnd",resolveAll:LLn,resolveTo:ILn,tokenize:DLn},TLn={tokenize:RLn},MLn={tokenize:FLn},PLn={tokenize:OLn};function LLn(s){let t=-1;const n=[];for(;++t=3&&(d===null||lc(d))?(s.exit("thematicBreak"),t(d)):n(d)}function c(d){return d===a?(s.consume(d),r++,c):(s.exit("thematicBreakSequence"),lh(d)?ep(s,o,"whitespace")(d):o(d))}}const o_={continuation:{tokenize:KLn},exit:ZLn,name:"list",tokenize:WLn},HLn={partial:!0,tokenize:XLn},GLn={partial:!0,tokenize:YLn};function WLn(s,t,n){const r=this,a=r.events[r.events.length-1];let i=a&&a[1].type==="linePrefix"?a[2].sliceSerialize(a[1],!0).length:0,l=0;return o;function o(p){const f=r.containerState.type||(p===42||p===43||p===45?"listUnordered":"listOrdered");if(f==="listUnordered"?!r.containerState.marker||p===r.containerState.marker:uWe(p)){if(r.containerState.type||(r.containerState.type=f,s.enter(f,{_container:!0})),f==="listUnordered")return s.enter("listItemPrefix"),p===42||p===45?s.check(Z4e,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 uWe(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(HIe,r.interrupt?n:u,s.attempt(HLn,m,h))}function u(p){return r.containerState.initialBlankLine=!0,i++,m(p)}function h(p){return lh(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 KLn(s,t,n){const r=this;return r.containerState._closeFlow=void 0,s.check(HIe,a,i);function a(o){return r.containerState.furtherBlankLines=r.containerState.furtherBlankLines||r.containerState.initialBlankLine,ep(s,t,"listItemIndent",r.containerState.size+1)(o)}function i(o){return r.containerState.furtherBlankLines||!lh(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(GLn,t,l)(o))}function l(o){return r.containerState._closeFlow=!0,r.interrupt=void 0,ep(s,s.attempt(o_,t,n),"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(o)}}function YLn(s,t,n){const r=this;return ep(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 ZLn(s){s.exit(this.containerState.type)}function XLn(s,t,n){const r=this;return ep(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!lh(i)&&l&&l[1].type==="listItemPrefixWhitespace"?t(i):n(i)}}const Tjt={name:"setextUnderline",resolveTo:QLn,tokenize:JLn};function QLn(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 JLn(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"),lh(d)?ep(s,c,"lineSuffix")(d):c(d))}function c(d){return d===null||lc(d)?(s.exit("setextHeadingLine"),t(d)):n(d)}}const eIn={tokenize:tIn};function tIn(s){const t=this,n=s.attempt(HIe,r,s.attempt(this.parser.constructs.flowInitial,a,ep(s,s.attempt(this.parser.constructs.flow,a,s.attempt(iLn,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 sIn={resolveAll:nYt()},nIn=sYt("string"),rIn=sYt("text");function sYt(s){return{resolveAll:nYt(s==="text"?aIn: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 yIn(s,t){let n=-1;const r=[];let a;for(;++n0){const fs=qt.tokenStack[qt.tokenStack.length-1];(fs[1]||Pjt).call(qt,void 0,fs[0])}for(xt.position={start:kT(ct.length>0?ct[0][1].start:{line:1,column:1,offset:0}),end:kT(ct.length>0?ct[ct.length-2][1].end:{line:1,column:1,offset:0})},Xt=-1;++Xt0&&(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 PIn(s,t){const n={type:"element",tagName:"del",properties:{},children:s.all(t)};return s.patch(t,n),s.applyData(t,n)}function LIn(s,t){const n={type:"element",tagName:"em",properties:{},children:s.all(t)};return s.patch(t,n),s.applyData(t,n)}function IIn(s,t){const n=typeof s.options.clobberPrefix=="string"?s.options.clobberPrefix:"user-content-",r=String(t.identifier).toUpperCase(),a=qW(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 DIn(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 RIn(s,t){if(s.options.allowDangerousHtml){const n={type:"raw",value:t.value};return s.patch(t,n),s.applyData(t,n)}}function iYt(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 FIn(s,t){const n=String(t.identifier).toUpperCase(),r=s.definitionById.get(n);if(!r)return iYt(s,t);const a={src:qW(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 OIn(s,t){const n={src:qW(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 zIn(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 BIn(s,t){const n=String(t.identifier).toUpperCase(),r=s.definitionById.get(n);if(!r)return iYt(s,t);const a={href:qW(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 UIn(s,t){const n={href:qW(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 qIn(s,t,n){const r=s.all(t),a=n?$In(n):oYt(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 VIn(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=cnt(t.children[1]),c=UKt(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 YIn(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(Djt(t.slice(a),a>0,!1)),i.join("")}function Djt(s,t,n){let r=0,a=s.length;if(t){let i=s.codePointAt(r);for(;i===Ljt||i===Ijt;)r++,i=s.codePointAt(r)}if(n){let i=s.codePointAt(a-1);for(;i===Ljt||i===Ijt;)a--,i=s.codePointAt(a-1)}return a>r?s.slice(r,a):""}function QIn(s,t){const n={type:"text",value:XIn(String(t.value))};return s.patch(t,n),s.applyData(t,n)}function JIn(s,t){const n={type:"element",tagName:"hr",properties:{},children:[]};return s.patch(t,n),s.applyData(t,n)}const e8n={blockquote:EIn,break:TIn,code:MIn,delete:PIn,emphasis:LIn,footnoteReference:IIn,heading:DIn,html:RIn,imageReference:FIn,image:OIn,inlineCode:zIn,linkReference:BIn,link:UIn,listItem:qIn,list:VIn,paragraph:HIn,root:GIn,strong:WIn,table:KIn,tableCell:ZIn,tableRow:YIn,text:QIn,thematicBreak:JIn,toml:Lce,yaml:Lce,definition:Lce,footnoteDefinition:Lce};function Lce(){}const lYt=-1,GIe=0,tee=1,LTe=2,xnt=3,gnt=4,ynt=5,vnt=6,cYt=7,dYt=8,uYt=typeof self=="object"?self:globalThis,Rjt=(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 uYt[s](t)},t8n=(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 GIe:case lYt:return n(l,a);case tee:{const o=n([],a);for(const c of l)o.push(r(c));return o}case LTe:{const o=n({},a);for(const[c,d]of l)o[r(c)]=r(d);return o}case xnt:return n(new Date(l),a);case gnt:{const{source:o,flags:c}=l;return n(new RegExp(o,c),a)}case ynt:{const o=n(new Map,a);for(const[c,d]of l)o.set(r(c),r(d));return o}case vnt:{const o=n(new Set,a);for(const c of l)o.add(r(c));return o}case cYt:{const{name:o,message:c}=l;return n(typeof uYt[o]=="function"?Rjt(o,c):new Error(c),a)}case dYt: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(Rjt(i,l),a)};return r},Fjt=s=>t8n(new Map,s)(0),$R="",{toString:s8n}={},{keys:n8n}=Object,mZ=s=>{const t=typeof s;if(t!=="object"||!s)return[GIe,t];const n=s8n.call(s).slice(8,-1);switch(n){case"Array":return[tee,$R];case"Object":return[LTe,$R];case"Date":return[xnt,$R];case"RegExp":return[gnt,$R];case"Map":return[ynt,$R];case"Set":return[vnt,$R];case"DataView":return[tee,n]}return n.includes("Array")?[tee,n]:s instanceof Error?[cYt,s.name||"Error"]:[LTe,n]},Ice=([s,t])=>s===GIe&&(t==="function"||t==="symbol"),r8n=(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]=mZ(l);switch(o){case GIe:{let u=l;switch(c){case"bigint":o=dYt,u=l.toString();break;case"function":case"symbol":if(s)throw new TypeError("unable to serialize "+c);u=null;break;case"undefined":return a([lYt],l)}return a([o,u],l)}case tee:{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 LTe:{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 n8n(l))(s||!Ice(mZ(l[m])))&&u.push([i(m),i(l[m])]);return h}case xnt:return a([o,isNaN(l.getTime())?$R:l.toISOString()],l);case gnt:{const{source:u,flags:h}=l;return a([o,{source:u,flags:h}],l)}case ynt:{const u=[],h=a([o,u],l);for(const[m,p]of l)(s||!(Ice(mZ(m))||Ice(mZ(p))))&&u.push([i(m),i(p)]);return h}case vnt:{const u=[],h=a([o,u],l);for(const m of l)(s||!Ice(mZ(m)))&&u.push(i(m));return h}}const{message:d}=l;return a([o,{name:c,message:d}],l)};return i},Ojt=(s,{json:t,lossy:n}={})=>{const r=[];return r8n(!(t||n),!!t,new Map,r)(s),r},ITe=typeof structuredClone=="function"?(s,t)=>t&&("json"in t||"lossy"in t)?Fjt(Ojt(s,t)):structuredClone(s):(s,t)=>Fjt(Ojt(s,t));function a8n(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 i8n(s,t){return"Back to reference "+(s+1)+(t>1?"-"+t:"")}function o8n(s){const t=typeof s.options.clobberPrefix=="string"?s.options.clobberPrefix:"user-content-",n=s.options.footnoteBackContent||a8n,r=s.options.footnoteBackLabel||i8n,a=s.options.footnoteLabel||"Footnotes",i=s.options.footnoteLabelTagName||"h2",l=s.options.footnoteLabelProperties||{className:["sr-only"]},o=[];let c=-1;for(;++c0&&f.push({type:"text",value:" "});let b=typeof n=="string"?n:n(c,p);typeof b=="string"&&(b={type:"text",value:b}),f.push({type:"element",tagName:"a",properties:{href:"#"+t+"fnref-"+m+(p>1?"-"+p:""),dataFootnoteBackref:"",ariaLabel:typeof r=="string"?r:r(c,p),className:["data-footnote-backref"]},children:Array.isArray(b)?b:[b]})}const v=u[u.length-1];if(v&&v.type==="element"&&v.tagName==="p"){const b=v.children[v.children.length-1];b&&b.type==="text"?b.value+=" ":v.children.push({type:"text",value:" "}),v.children.push(...f)}else u.push(...f);const g={type:"element",tagName:"li",properties:{id:t+"fn-"+m},children:s.wrap(u,!0)};s.patch(d,g),o.push(g)}if(o.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:i,properties:{...ITe(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 hYt=function(s){if(s==null)return u8n;if(typeof s=="function")return WIe(s);if(typeof s=="object")return Array.isArray(s)?l8n(s):c8n(s);if(typeof s=="string")return d8n(s);throw new Error("Expected function, string, or object as test")};function l8n(s){const t=[];let n=-1;for(;++n":""))+")"})}return m;function m(){let p=mYt,f,y,v;if((!t||i(c,d,u[u.length-1]||void 0))&&(p=x8n(n(c,u)),p[0]===zjt))return p;if("children"in c&&c.children){const g=c;if(g.children&&p[0]!==p8n)for(y=(r?g.children.length:-1)+l,v=u.concat(g);y>-1&&y0&&n.push({type:"text",value:` `}),n}function Bjt(s){let t=0,n=s.charCodeAt(t);for(;n===9||n===32;)t++,n=s.charCodeAt(t);return s.slice(t)}function Ujt(s,t){const n=y8n(s,t),r=n.one(s,void 0),a=o8n(n),i=Array.isArray(r)?{type:"root",children:r}:r||{type:"root",children:[]};return a&&i.children.push({type:"text",value:` `},a),i}function j8n(s,t){return s&&"run"in s?async function(n,r){const a=Ujt(n,{file:r,...t});await s.run(a,r)}:function(n,r){return Ujt(n,{file:r,...s||t})}}function qjt(s){if(s)throw s}var X4e=Object.prototype.hasOwnProperty,fYt=Object.prototype.toString,$jt=Object.defineProperty,Vjt=Object.getOwnPropertyDescriptor,Hjt=function(t){return typeof Array.isArray=="function"?Array.isArray(t):fYt.call(t)==="[object Array]"},Gjt=function(t){if(!t||fYt.call(t)!=="[object Object]")return!1;var n=X4e.call(t,"constructor"),r=t.constructor&&t.constructor.prototype&&X4e.call(t.constructor.prototype,"isPrototypeOf");if(t.constructor&&!n&&!r)return!1;var a;for(a in t);return typeof a>"u"||X4e.call(t,a)},Wjt=function(t,n){$jt&&n.name==="__proto__"?$jt(t,n.name,{enumerable:!0,configurable:!0,value:n.newValue,writable:!0}):t[n.name]=n.newValue},Kjt=function(t,n){if(n==="__proto__")if(X4e.call(t,n)){if(Vjt)return Vjt(t,n).value}else return;return t[n]},N8n=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 V5={basename:C8n,dirname:A8n,extname:E8n,join:T8n,sep:"/"};function C8n(s,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');Iae(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 A8n(s){if(Iae(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 E8n(s){Iae(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 T8n(...s){let t=-1,n;for(;++t0&&s.codePointAt(s.length-1)===47&&(n+="/"),t?"/"+n:n}function P8n(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 Iae(s){if(typeof s!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(s))}const L8n={cwd:I8n};function I8n(){return"/"}function fWe(s){return!!(s!==null&&typeof s=="object"&&"href"in s&&s.href&&"protocol"in s&&s.protocol&&s.auth===void 0)}function D8n(s){if(typeof s=="string")s=new URL(s);else if(!fWe(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 R8n(s)}function R8n(s){if(s.hostname!==""){const r=new TypeError('File URL host must be "localhost" or empty on darwin');throw r.code="ERR_INVALID_FILE_URL_HOST",r}const t=s.pathname;let n=-1;for(;++n0){let[p,...f]=u;const y=r[m][1];pWe(y)&&pWe(p)&&(p=K9e(!0,y,p)),r[m]=[d,p,...f]}}}}const B8n=new bnt().freeze();function Q9e(s,t){if(typeof t!="function")throw new TypeError("Cannot `"+s+"` without `parser`")}function J9e(s,t){if(typeof t!="function")throw new TypeError("Cannot `"+s+"` without `compiler`")}function eze(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 Zjt(s){if(!pWe(s)||typeof s.type!="string")throw new TypeError("Expected node, got `"+s+"`")}function Xjt(s,t,n){if(!n)throw new Error("`"+s+"` finished async. Use `"+t+"` instead")}function Dce(s){return U8n(s)?s:new xYt(s)}function U8n(s){return!!(s&&typeof s=="object"&&"message"in s&&"messages"in s)}function q8n(s){return typeof s=="string"||$8n(s)}function $8n(s){return!!(s&&typeof s=="object"&&"byteLength"in s&&"byteOffset"in s)}const V8n="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",Qjt=[],Jjt={allowDangerousHtml:!0},H8n=/^(https?|ircs?|mailto|xmpp)$/i,G8n=[{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 W8n(s){const t=K8n(s),n=Y8n(s);return Z8n(t.runSync(t.parse(n),n),s)}function K8n(s){const t=s.rehypePlugins||Qjt,n=s.remarkPlugins||Qjt,r=s.remarkRehypeOptions?{...s.remarkRehypeOptions,...Jjt}:Jjt;return B8n().use(AIn).use(n).use(j8n,r).use(t)}function Y8n(s){const t=s.children||"",n=new xYt;return typeof t=="string"&&(n.value=t),n}function Z8n(s,t){const n=t.allowedElements,r=t.allowElement,a=t.components,i=t.disallowedElements,l=t.skipHtml,o=t.unwrapDisallowed,c=t.urlTransform||X8n;for(const u of G8n)Object.hasOwn(t,u.from)&&(""+u.from+(u.to?"use `"+u.to+"` instead":"remove it")+V8n+u.id,void 0);return pYt(s,d),oPn(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 H9e)if(Object.hasOwn(H9e,p)&&Object.hasOwn(u.properties,p)){const f=u.properties[p],y=H9e[p];(y===null||y.includes(u.tagName))&&(u.properties[p]=c(String(f||""),p,u))}}if(u.type==="element"){let p=n?!n.includes(u.tagName):i?i.includes(u.tagName):!1;if(!p&&r&&typeof h=="number"&&(p=!r(u,h,m)),p&&m&&typeof h=="number")return o&&u.children?m.children.splice(h,1,...u.children):m.children.splice(h,1),h}}}function X8n(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||H8n.test(s.slice(0,t))?s:""}const Q8n={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(ir,{to:n,className:a,children:[t,e.jsx($O,{className:"h-3 w-3"})]}):e.jsxs("a",{href:n,target:"_blank",rel:"noopener noreferrer",className:a,children:[t,e.jsx($O,{className:"h-3 w-3"})]})}},J8n=["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 eDn(){var h,m,p;const{user:s}=hs(),[t,n]=_.useState([]),[r,a]=_.useState(""),[i,l]=_.useState(!1),o=_.useRef(null),c=_.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])||"";_.useEffect(()=>{var f;(f=c.current)==null||f.scrollTo({top:c.current.scrollHeight,behavior:"smooth"})},[t,i]);const u=async f=>{var b;const y=f.trim();if(!y||i)return;const v=[...t,{role:"user",content:y}];n([...v,{role:"assistant",content:""}]),a(""),l(!0);const g=new AbortController;o.current=g;try{const{data:j}=await q.auth.getSession(),S=(b=j.session)==null?void 0:b.access_token,C=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/levelup-assistant",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${S}`,apikey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM"},body:JSON.stringify({messages:v,agentName:d}),signal:g.signal});if(!C.ok||!C.body){const D=await C.json().catch(()=>({error:"Something went wrong."}));throw new Error(D.error||"Something went wrong.")}const E=C.body.getReader(),P=new TextDecoder;let M="",I="";for(;;){const{done:D,value:O}=await E.read();if(D)break;M+=P.decode(O,{stream:!0});const V=M.split(` `);M=V.pop()||"";for(const G of V){const $=G.trim();if(!$.startsWith("data:"))continue;const H=$.slice(5).trim();if(!(!H||H==="[DONE]"))try{const Y=JSON.parse(H);Y.delta&&(I+=Y.delta,n(Z=>{const ne=[...Z];return ne[ne.length-1]={role:"assistant",content:I},ne}))}catch{}}}I||n(D=>{const O=[...D];return O[O.length-1]={role:"assistant",content:"I didn't catch that — mind asking again?"},O})}catch(j){j.name==="AbortError"?n(S=>S.filter((C,E)=>!(E===S.length-1&&!C.content))):(se.error(j.message||"The assistant is unavailable right now."),n(S=>S.slice(0,-1)))}finally{l(!1),o.current=null}};return e.jsx(zs,{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(V4,{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(B,{variant:"ghost",size:"sm",className:"gap-1",onClick:()=>n([]),children:[e.jsx(Tx,{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(V4,{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:J8n.map(f=>e.jsx("button",{onClick:()=>u(f),className:"rounded-xl border bg-background px-3 py-2.5 text-left text-sm transition-colors hover:border-primary/40 hover:bg-muted/50",children:f},f))})]}):t.map((f,y)=>e.jsx("div",{className:At("flex",f.role==="user"?"justify-end":"justify-start"),children:f.role==="user"?e.jsx("div",{className:"max-w-[85%] rounded-2xl rounded-br-sm bg-primary px-3.5 py-2.5 text-sm text-primary-foreground",children:e.jsx("p",{className:"whitespace-pre-wrap break-words",children:f.content})}):e.jsx("div",{className:"max-w-full text-sm leading-relaxed text-foreground",children:f.content?e.jsx("div",{className:"prose prose-sm max-w-none dark:prose-invert prose-p:my-2 prose-ul:my-2 prose-headings:mt-4 prose-headings:mb-2",children:e.jsx(W8n,{components:Q8n,children:f.content})}):e.jsx("span",{className:"animate-pulse text-muted-foreground",children:"Thinking…"})})},y))}),e.jsxs("div",{className:"mt-3 flex items-end gap-2 rounded-2xl border bg-background p-2",children:[e.jsx(Ms,{value:r,onChange:f=>a(f.target.value),onKeyDown:f=>{f.key==="Enter"&&!f.shiftKey&&(f.preventDefault(),u(r))},rows:1,placeholder:"Ask anything about LevelUp or your business…",className:"min-h-[44px] resize-none border-0 bg-transparent shadow-none focus-visible:ring-0"}),i?e.jsx(B,{size:"icon",variant:"secondary",onClick:()=>{var f;return(f=o.current)==null?void 0:f.abort()},children:e.jsx(wb,{className:"h-4 w-4"})}):e.jsx(B,{size:"icon",disabled:!r.trim(),onClick:()=>u(r),children:e.jsx(Or,{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 tDn({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 Rce({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:At("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(xi,{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 sDn({agentName:s,todayDone:t,todayTotal:n,focusLine:r,weekDone:a,weekGoal:i,streak:l,staleCount:o,sphereCount:c,onEditGoal:d,onStaleClick:u,onSphereClick:h}){const m=new Date().getHours(),p=m<12?"Good morning":m<17?"Good afternoon":"Good evening",f=i>0?Math.min(100,Math.round(a/i*100)):0;return e.jsxs("div",{className:"grid gap-4 lg:grid-cols-[minmax(0,1.15fr)_minmax(0,1fr)]",children:[e.jsxs("div",{className:"relative overflow-hidden rounded-2xl border bg-gradient-to-br from-primary/[0.07] via-card to-card p-5 sm:p-6",children:[e.jsx("div",{className:"pointer-events-none absolute -right-16 -top-16 h-48 w-48 rounded-full bg-primary/10 blur-3xl"}),e.jsxs("div",{className:"relative flex flex-col-reverse items-start gap-5 sm:flex-row sm:items-center",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-primary",children:[p,s?`, ${s}`:""]}),e.jsx("h2",{className:"mt-1.5 text-xl font-semibold leading-snug sm:text-2xl",children:n===0?"Your day is clear — pick a few people to reconnect with.":t>=n?"Today's list is done. That's how referrals get built.":`${n-t} ${n-t===1?"touch":"touches"} left to stay on track.`}),e.jsxs("p",{className:"mt-2 flex items-start gap-1.5 text-sm text-muted-foreground",children:[e.jsx(un,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-primary"}),e.jsx("span",{children:r})]})]}),e.jsx(tDn,{done:t,total:n})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(Rce,{icon:e.jsx(ku,{className:"h-3.5 w-3.5"}),label:"Weekly goal",value:`${a}/${i}`,hint:`${f}% of your weekly touches`,action:e.jsx("button",{onClick:d,className:"rounded p-0.5 text-muted-foreground transition-colors hover:text-primary","aria-label":"Edit weekly goal",children:e.jsx(qc,{className:"h-3.5 w-3.5"})})}),e.jsx(Rce,{icon:e.jsx(gu,{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(Rce,{icon:e.jsx(Gr,{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(Rce,{icon:e.jsx(In,{className:"h-3.5 w-3.5"}),label:"Your sphere",value:String(c),hint:"People in your database",onClick:h})]})]})}const e2t="agent-os-onboarding-completed",Fce=[{icon:Sy,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:nf,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:In,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:pc,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:Vo,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:bl,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"]}],nDn=()=>{const[s,t]=_.useState(!1),[n,r]=_.useState(0),[a,i]=_.useState(!1);_.useEffect(()=>{if(!localStorage.getItem(e2t)){const f=setTimeout(()=>t(!0),500);return()=>clearTimeout(f)}},[]);const l=()=>{n{r(n+1),i(!1)},150)):c()},o=()=>{c()},c=()=>{localStorage.setItem(e2t,"true"),t(!1)},d=Fce[n],u=d.icon,h=n===Fce.length-1,m=p=>{p||c(),t(p)};return e.jsx(Ls,{open:s,onOpenChange:m,children:e.jsxs(Ps,{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(un,{className:"h-3 w-3"}),"Beta"]})]}),e.jsxs("div",{className:"p-6 pt-4",children:[e.jsxs(Os,{className:"text-center sm:text-center pb-2",children:[e.jsx(Ds,{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(_r,{className:`text-base pt-2 transition-all duration-300 delay-75 ${a?"translate-y-2 opacity-0":"translate-y-0 opacity-100"}`,children:d.description})]}),d.highlights&&e.jsx("div",{className:`space-y-2.5 py-4 transition-all duration-300 delay-100 ${a?"translate-y-2 opacity-0":"translate-y-0 opacity-100"}`,children:d.highlights.map((p,f)=>e.jsxs("div",{className:"flex items-center gap-3 group",style:{transitionDelay:`${150+f*50}ms`},children:[e.jsx("div",{className:`flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-gradient-to-br ${d.bgGradient} shadow-sm`,children:e.jsx(ea,{className:"h-3.5 w-3.5 text-white"})}),e.jsx("span",{className:"text-sm text-muted-foreground group-hover:text-foreground transition-colors",children:p})]},f))}),e.jsx("div",{className:"flex justify-center gap-2 py-4",children:Fce.map((p,f)=>e.jsx("button",{onClick:()=>{f!==n&&(i(!0),setTimeout(()=>{r(f),i(!1)},150))},className:`h-2 rounded-full transition-all duration-300 ${f===n?"w-8 bg-gradient-to-r "+d.bgGradient:f{const{user:s}=hs();return at({queryKey:["contact-snoozes",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.from("contact_snoozes").select("*").gte("snoozed_until",new Date().toISOString());if(n)throw n;return t},enabled:!!s})},aDn=()=>{const s=Bt(),{user:t}=hs();return mt({mutationFn:async({contactId:n,days:r})=>{if(!(t!=null&&t.id))throw new Error("Not authenticated");const a=zh(new Date,r);await q.from("contact_snoozes").delete().eq("contact_id",n);const{error:i}=await q.from("contact_snoozes").insert({contact_id:n,owner_user_id:t.id,snoozed_until:a.toISOString()});if(i)throw i},onSuccess:()=>{s.invalidateQueries({queryKey:["contact-snoozes"]}),s.invalidateQueries({queryKey:["today-actions"]}),s.invalidateQueries({queryKey:["popby-logs"]}),ia({title:"Touch snoozed!",description:"Contact has been snoozed."})},onError:n=>{ia({title:"Error snoozing contact",description:n.message,variant:"destructive"})}})},iDn=()=>{const s=Bt();return mt({mutationFn:async t=>{const{error:n}=await q.from("contact_snoozes").delete().eq("contact_id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["contact-snoozes"]}),ia({title:"Snooze cancelled"})},onError:t=>{ia({title:"Error cancelling snooze",description:t.message,variant:"destructive"})}})},oDn=[{label:"1 week",days:7},{label:"2 weeks",days:14},{label:"1 month",days:30}];function KIe({open:s,onOpenChange:t,contactId:n,contactName:r}){const[a,i]=_.useState(null),l=aDn(),o=async()=>{a&&(await l.mutateAsync({contactId:n,days:a}),i(null),t(!1))},c=d=>Hs(zh(new Date,d),"MMM d, yyyy");return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"sm:max-w-md",children:[e.jsxs(Os,{children:[e.jsxs(Ds,{className:"flex items-center gap-2",children:[e.jsx(Gr,{className:"h-5 w-5"}),"Snooze Touch"]}),e.jsxs(_r,{children:["Postpone the next scheduled touch for ",r,". Select how long to snooze."]})]}),e.jsx("div",{className:"space-y-3 py-4",children:oDn.map(d=>e.jsxs("button",{type:"button",onClick:()=>i(d.days),className:At("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(ga,{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(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(B,{onClick:o,disabled:!a||l.isPending,children:l.isPending?"Snoozing...":"Snooze Touch"})]})]})})}const lDn={Crown:$f,FileText:Fr,Users:In,Globe:sl,Star:Da,Phone:_a,MessageSquare:Hi,PenTool:KA,Video:Kr,Gift:Vo};function cDn({actions:s,onMarkComplete:t,onViewScript:n,isLoading:r,buildSmsLink:a,buildEmailLink:i,onGmailCompose:l}){const o=Fn(),[c,d]=_.useState("name"),[u,h]=_.useState("asc"),[m,p]=_.useState(null),[f,y]=_.useState(""),v=C=>{c===C?h(E=>E==="asc"?"desc":"asc"):(d(C),h("asc"))},g=_.useMemo(()=>[...s].sort((C,E)=>{var M,I;let P=0;switch(c){case"name":{const D=`${C.contact.first_name} ${C.contact.last_name||""}`.toLowerCase(),O=`${E.contact.first_name} ${E.contact.last_name||""}`.toLowerCase();P=D.localeCompare(O);break}case"relationship_type":P=(C.relationshipTypeName||"").localeCompare(E.relationshipTypeName||"");break;case"action_type":P=(((M=C.actionType)==null?void 0:M.name)||"").localeCompare(((I=E.actionType)==null?void 0:I.name)||"");break;case"last_touch":P=(C.monthNumber||0)-(E.monthNumber||0);break}return u==="asc"?P:-P}),[s,c,u]),b=C=>lDn[C||"Phone"]||_a,j=({field:C,children:E})=>e.jsxs(B,{variant:"ghost",size:"sm",className:"h-8 -ml-3 font-medium",onClick:()=>v(C),children:[E,c===C?u==="asc"?e.jsx(sp,{className:"ml-2 h-4 w-4"}):e.jsx(zf,{className:"ml-2 h-4 w-4"}):e.jsx(Lg,{className:"ml-2 h-4 w-4 opacity-50"})]}),S=(C,E,P)=>{p(C),y(`${E} ${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(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{className:"bg-muted/50",children:[e.jsx(Pt,{className:"w-[180px]",children:e.jsx(j,{field:"name",children:"Contact"})}),e.jsx(Pt,{className:"w-[130px]",children:e.jsx(j,{field:"relationship_type",children:"Type"})}),e.jsx(Pt,{className:"w-[120px]",children:e.jsx(j,{field:"action_type",children:"Action"})}),e.jsx(Pt,{className:"w-[130px]",children:"Phone"}),e.jsx(Pt,{className:"w-[200px]",children:"Quick Actions"})]})}),e.jsx(Ka,{children:g.map((C,E)=>{var V,G,$,H,Y,Z;const P=C.isSpecialDate,M=C.specialDateType,I=P?M==="birthday"?Bf:Jr:b(((V=C.actionType)==null?void 0:V.icon)||null),D=C.contact.phone,O=C.contact.email;return e.jsxs(pn,{className:At("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/${C.contact.id}`),className:"truncate max-w-[160px] text-left hover:text-primary hover:underline transition-colors",children:[C.contact.first_name," ",C.contact.last_name]})})}),e.jsx(gt,{children:C.relationshipTypeName?e.jsx(Oe,{variant:"secondary",className:"text-xs",children:C.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(Oe,{className:At("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(Bf,{className:"h-3 w-3"})," Birthday"]}):e.jsxs(e.Fragment,{children:[e.jsx(Jr,{className:"h-3 w-3"})," Anniversary"]})}):e.jsxs(Oe,{variant:"outline",className:"gap-1",children:[e.jsx(I,{className:"h-3 w-3"}),(G=C.actionType)==null?void 0:G.name]})})}),e.jsx(gt,{children:D?e.jsx("span",{className:"text-sm font-mono",children:C.contact.phone}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[D&&e.jsx("a",{href:`tel:${C.contact.phone}`,className:"p-1.5 rounded bg-primary/10 hover:bg-primary/20 text-primary transition-colors",title:"Call",children:e.jsx(_a,{className:"h-3.5 w-3.5"})}),D&&e.jsx("a",{href:a(C.contact.phone,($=C.script)==null?void 0:$.script_body,C.contact),className:"p-1.5 rounded bg-emerald-500/10 hover:bg-emerald-500/20 text-emerald-600 dark:text-emerald-400 transition-colors",title:"Text",children:e.jsx(Hi,{className:"h-3.5 w-3.5"})}),O&&(l?e.jsx("button",{onClick:()=>l({id:C.contact.id,first_name:C.contact.first_name,last_name:C.contact.last_name,email:C.contact.email}),className:"p-1.5 rounded bg-sky-500/10 hover:bg-sky-500/20 text-sky-600 dark:text-sky-400 transition-colors",title:"Compose Email",children:e.jsx(ln,{className:"h-3.5 w-3.5"})}):e.jsx("a",{href:i(C.contact.email,(H=C.script)==null?void 0:H.script_body,(Y=C.script)==null?void 0:Y.email_subject,(Z=C.actionType)==null?void 0:Z.name,C.contact),className:"p-1.5 rounded bg-sky-500/10 hover:bg-sky-500/20 text-sky-600 dark:text-sky-400 transition-colors",title:"Email",children:e.jsx(ln,{className:"h-3.5 w-3.5"})})),P&&e.jsxs("button",{onClick:()=>{const ne=`${C.contact.first_name}${C.contact.last_name?" "+C.contact.last_name:""}`,ce=M==="birthday"?"birthday":"home_anniversary",ie=new URLSearchParams({cardType:ce,contactId:C.contact.id,name:ne,...C.contact.address?{address:C.contact.address}:{},...M==="anniversary"&&C.contact.home_anniversary?{date:C.contact.home_anniversary}:{}});o(`/mission-control/card-studio?${ie.toString()}`)},className:At("h-7 px-2 rounded text-xs font-semibold flex items-center gap-1 transition-colors",M==="birthday"?"bg-pink-500/15 hover:bg-pink-500/25 text-pink-600 dark:text-pink-400":"bg-purple-500/15 hover:bg-purple-500/25 text-purple-600 dark:text-purple-400"),title:`Send ${M==="birthday"?"Birthday":"Anniversary"} Card`,children:[e.jsx(ln,{className:"h-3.5 w-3.5"}),"Send Card"]}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-foreground",onClick:()=>S(C.contact.id,C.contact.first_name,C.contact.last_name),title:"Snooze",children:e.jsx(ky,{className:"h-3.5 w-3.5"})}),e.jsxs(B,{variant:"default",size:"sm",className:"h-7 px-2 text-xs ml-1",onClick:()=>{var ne;return t(C.contact.id,C.actionType.id,(ne=C.script)==null?void 0:ne.id)},disabled:r,children:[e.jsx(Er,{className:"h-3.5 w-3.5 mr-1"}),"Done"]})]})})]},`${C.contact.id}-${E}`)})})]})}),e.jsx(KIe,{open:!!m,onOpenChange:C=>!C&&p(null),contactId:m||"",contactName:f})]})}function dDn(){const s=Fn(),{data:t}=yzt(),{data:n}=aae(),r=oLe(),{isGmailConnected:a,gmailEmail:i}=Vg(),[l,o]=_.useState(null),[c,d]=_.useState(!1),[u,h]=_.useState(new Set),m=If(new Date),p=zh(m,30),f=C=>{if(!C)return null;const E=C.split(/[-/T]/);if(E.length<3)return null;const P=parseInt(E[1],10)-1,M=parseInt(E[2],10);return isNaN(P)||isNaN(M)?null:new Date(m.getFullYear(),P,M)},y=_.useMemo(()=>{if(!t)return[];const C=[];for(const E of t){if(E.birthday){const P=f(E.birthday);P&&(cm(P,m)||Z4(P,m)&&yS(P,p))&&C.push({contact:E,type:"birthday",date:P,daysUntil:pv(P,m),dateStr:E.birthday})}if(E.home_anniversary){const P=f(E.home_anniversary);P&&(cm(P,m)||Z4(P,m)&&yS(P,p))&&C.push({contact:E,type:"anniversary",date:P,daysUntil:pv(P,m),dateStr:E.home_anniversary})}if(E.wedding_anniversary){const P=f(E.wedding_anniversary);P&&(cm(P,m)||Z4(P,m)&&yS(P,p))&&C.push({contact:E,type:"wedding_anniversary",date:P,daysUntil:pv(P,m),dateStr:E.wedding_anniversary})}}return C.sort((E,P)=>E.daysUntil-P.daysUntil),C},[t]),v=C=>C==="birthday"?"Birthday":C==="wedding_anniversary"?"Wedding Anniversary":"Home Anniversary",g=async C=>{const E=(n==null?void 0:n.find(P=>P.name==="Call"))||(n==null?void 0:n[0]);if(E)try{await r.mutateAsync({contactId:C.contact.id,actionTypeId:E.id,notes:`${v(C.type)} outreach`}),h(P=>new Set(P).add(`${C.contact.id}-${C.type}`)),ia({title:"Touch logged!",description:`Logged outreach for ${C.contact.first_name}`})}catch{ia({title:"Error",description:"Failed to log touch",variant:"destructive"})}},b=C=>{const E=`${C.contact.first_name}${C.contact.last_name?" "+C.contact.last_name:""}`,P=C.type==="birthday"?"birthday":C.type==="wedding_anniversary"?"wedding_anniversary":"home_anniversary",M=new URLSearchParams({cardType:P,contactId:C.contact.id,name:E,...C.contact.address?{address:C.contact.address}:{},...(C.type==="anniversary"||C.type==="wedding_anniversary")&&C.dateStr?{date:C.dateStr}:{}});s(`/mission-control/card-studio?${M.toString()}`)},j=C=>C===0?"Today!":C===1?"Tomorrow":`${C} days`,S=C=>C===0?"bg-red-500/15 text-red-600 dark:text-red-400 border-red-500/30":C<=3?"bg-amber-500/15 text-amber-600 dark:text-amber-400 border-amber-500/30":C<=7?"bg-blue-500/15 text-blue-600 dark:text-blue-400 border-blue-500/30":"bg-muted text-muted-foreground border-border";return e.jsxs(e.Fragment,{children:[e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(St,{className:"text-lg flex items-center gap-2",children:[e.jsx(pc,{className:"h-5 w-5 text-primary"}),"Upcoming Milestones",e.jsx(Oe,{variant:"secondary",className:"text-xs font-normal",children:"Next 30 days"})]}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:[y.length," event",y.length!==1?"s":""]})]})}),e.jsxs(Me,{className:"space-y-2",children:[y.length===0&&e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Bf,{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."})]}),y.map((C,E)=>{var D,O;const P=`${C.contact.id}-${C.type}`,M=u.has(P),I=`${((D=C.contact.first_name)==null?void 0:D[0])||""}${((O=C.contact.last_name)==null?void 0:O[0])||""}`.toUpperCase();return e.jsxs("div",{className:At("p-3 rounded-lg border transition-colors",C.daysUntil===0&&C.type==="birthday"?"bg-pink-500/10 border-pink-500/30 dark:bg-pink-900/20 dark:border-pink-800/40":C.daysUntil===0&&(C.type==="anniversary"||C.type==="wedding_anniversary")?"bg-blue-500/10 border-blue-500/30 dark:bg-blue-900/20 dark:border-blue-800/40":C.type==="birthday"?"bg-pink-50/60 border-pink-200/60 hover:bg-pink-100/60 dark:bg-pink-950/20 dark:border-pink-900/30 dark:hover:bg-pink-950/30":"bg-blue-50/60 border-blue-200/60 hover:bg-blue-100/60 dark:bg-blue-950/20 dark:border-blue-900/30 dark:hover:bg-blue-950/30"),children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative shrink-0",children:[e.jsx(ja,{className:At("h-10 w-10",C.type==="birthday"?"ring-2 ring-pink-300/50 dark:ring-pink-700/50":"ring-2 ring-blue-300/50 dark:ring-blue-700/50"),children:e.jsx(Na,{className:At("text-xs font-medium",C.type==="birthday"?"bg-pink-100 text-pink-700 dark:bg-pink-900/40 dark:text-pink-300":"bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300"),children:I})}),e.jsx("span",{className:"absolute -bottom-1.5 -right-1.5 text-base leading-none drop-shadow-sm",children:C.type==="birthday"?"🎂":C.type==="wedding_anniversary"?"💍":"🏠"})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"font-medium text-sm truncate",children:[C.contact.first_name," ",C.contact.last_name||""]}),e.jsx(Oe,{variant:"outline",className:At("text-[10px] shrink-0 whitespace-nowrap",S(C.daysUntil)),children:j(C.daysUntil)})]}),e.jsxs("div",{className:At("text-xs flex items-center gap-1.5 mt-0.5",C.type==="birthday"?"text-pink-600/80 dark:text-pink-400/80":"text-blue-600/80 dark:text-blue-400/80"),children:[C.type==="birthday"?e.jsxs(e.Fragment,{children:[e.jsx(Bf,{className:"h-3 w-3"})," Birthday"]}):C.type==="wedding_anniversary"?e.jsxs(e.Fragment,{children:[e.jsx(Do,{className:"h-3 w-3"})," Wedding Anniversary"]}):e.jsxs(e.Fragment,{children:[e.jsx(Jr,{className:"h-3 w-3"})," Home Anniversary"]}),e.jsx("span",{children:"·"}),e.jsx("span",{children:Hs(C.date,"MMM d")})]})]})]}),e.jsxs("div",{className:"flex items-center gap-1 mt-2 pl-[52px]",children:[C.contact.phone&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"Call",asChild:!0,children:e.jsx("a",{href:`tel:${C.contact.phone}`,children:e.jsx(_a,{className:"h-3.5 w-3.5"})})}),C.contact.phone&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"Text",asChild:!0,children:e.jsx("a",{href:`sms:${C.contact.phone}`,children:e.jsx(Hi,{className:"h-3.5 w-3.5"})})}),C.contact.email&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"Email",onClick:()=>{a?(o({id:C.contact.id,first_name:C.contact.first_name,last_name:C.contact.last_name,email:C.contact.email}),d(!0)):window.location.href=`mailto:${C.contact.email}`},children:e.jsx(ln,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"Record video",onClick:()=>s(`/mission-control/video/record?contactId=${C.contact.id}`),children:e.jsx(Kr,{className:"h-3.5 w-3.5"})}),e.jsxs(B,{variant:"ghost",size:"sm",className:At("h-7 px-2 gap-1 text-xs",C.type==="birthday"?"text-pink-600 hover:text-pink-700 dark:text-pink-400":"text-blue-600 hover:text-blue-700 dark:text-blue-400"),title:`Send ${C.type==="birthday"?"birthday":"anniversary"} card`,onClick:()=>b(C),children:[e.jsx(un,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Card"})]}),e.jsx(B,{variant:"ghost",size:"icon",className:At("h-7 w-7",M&&"text-green-600"),title:"Log a touch",disabled:M||r.isPending,onClick:()=>g(C),children:e.jsx(Er,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"View contact",onClick:()=>s(`/mission-control/contacts/${C.contact.id}`),children:e.jsx(ya,{className:"h-3.5 w-3.5"})})]})]},`${P}-${E}`)})]})]}),a&&l&&e.jsx(DS,{open:c,onOpenChange:d,contact:l,gmailEmail:i})]})}function uDn(s){const[t,n]=_.useState([]),[r,a]=_.useState(!1),{data:i,isLoading:l}=at({queryKey:["active-visitors",s],queryFn:async()=>{if(!s)return[];try{await q.rpc("cleanup_stale_visitors")}catch{}const{data:u}=await q.from("lead_site_active_visitors").select("*").eq("lead_site_id",s).gte("last_seen_at",new Date(Date.now()-2*60*1e3).toISOString()).order("last_seen_at",{ascending:!1});if(!u)return[];const h=u.map(f=>f.contact_id).filter(Boolean);let m={};if(h.length>0){const{data:f}=await q.from("innercircle_contacts").select("id, first_name, last_name, email, phone").in("id",h);(f||[]).forEach(y=>{m[y.id]=y})}const p=u.map(f=>f.auth_user_id).filter(Boolean);if(p.length>0){const{data:f}=await q.from("lead_site_consumer_profiles").select("user_id, name, phone, contact_id").eq("lead_site_id",s).in("user_id",p);(f||[]).forEach(y=>{const v=u.find(g=>g.auth_user_id===y.user_id);v&&!v.contact_id&&y.contact_id&&(v.contact_id=y.contact_id),v&&!m[v.contact_id||""]&&y.name&&(m[v.contact_id||v.auth_user_id||""]={first_name:y.name.split(" ")[0],last_name:y.name.split(" ").slice(1).join(" ")||null,email:null,phone:y.phone})})}return u.map(f=>{var y,v;return{...f,contact_name:m[f.contact_id||f.auth_user_id||""]?`${m[f.contact_id||f.auth_user_id||""].first_name} ${m[f.contact_id||f.auth_user_id||""].last_name||""}`.trim():null,contact_email:((y=m[f.contact_id||f.auth_user_id||""])==null?void 0:y.email)||null,contact_phone:((v=m[f.contact_id||f.auth_user_id||""])==null?void 0:v.phone)||null}})},enabled:!!s,refetchInterval:6e4});_.useEffect(()=>{if(!s)return;const u=q.channel(`active-visitors-${s}`).on("postgres_changes",{event:"*",schema:"public",table:"lead_site_active_visitors",filter:`lead_site_id=eq.${s}`},h=>{h.eventType==="INSERT"?n(m=>m.find(f=>f.id===h.new.id)?m:[h.new,...m]):h.eventType==="UPDATE"?n(m=>m.map(p=>p.id===h.new.id?{...p,...h.new}:p)):h.eventType==="DELETE"&&n(m=>m.filter(p=>p.id!==h.old.id))}).subscribe(h=>{h==="SUBSCRIBED"&&a(!0)});return()=>{q.removeChannel(u)}},[s]);const o=r&&t.length>0?hDn([...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 hDn(s){const t=new Set;return s.filter(n=>t.has(n.id)?!1:(t.add(n.id),!0))}const mDn={property_view:{label:"Viewed",icon:ya,color:"text-blue-500",bgColor:"bg-blue-500/10"},new_lead:{label:"New Lead",icon:Pl,color:"text-emerald-500",bgColor:"bg-emerald-500/10"},saved_listing:{label:"Saved",icon:Do,color:"text-rose-500",bgColor:"bg-rose-500/10"}};function pDn(){const{user:s}=hs(),t=Fn(),{isGmailConnected:n,gmailEmail:r}=Vg(),{leadSite:a}=lf(),{count:i}=uDn(a==null?void 0:a.id),[l,o]=_.useState(!1),[c,d]=_.useState(null),{data:u,isLoading:h}=at({queryKey:["lead-site-activity",s==null?void 0:s.id],queryFn:async()=>{const{data:g,error:b}=await q.rpc("get_lead_site_activity",{_user_id:s.id});if(b)throw b;return g},enabled:!!s,refetchInterval:6e4});if(h||!(u!=null&&u.has_site))return null;const m=(u.activities||[]).filter(g=>g.visitor_name&&g.visitor_name!=="Site Visitor"),p=m.filter(g=>g.activity_type==="new_lead"),f=(u.activities||[]).filter(g=>g.activity_type==="property_view").length,y=(u.activities||[]).filter(g=>g.activity_type==="saved_listing").length,v=g=>{if(g.visitor_email)if(n){const b=(g.visitor_name||"").split(" ");d({id:g.contact_id||"",first_name:b[0]||"",last_name:b.slice(1).join(" ")||null,email:g.visitor_email}),o(!0)}else window.location.href=`mailto:${g.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(sl,{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(B,{variant:"ghost",size:"sm",className:"text-primary gap-1",onClick:()=>t("/mission-control/website-activity"),children:["View All",e.jsx(La,{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(Pl,{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(ya,{className:"h-4 w-4 text-blue-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-bold text-blue-600 dark:text-blue-400",children:f}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Views"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 p-3 rounded-lg bg-rose-500/5 border border-rose-200 dark:border-rose-800",children:[e.jsx(Do,{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:y}),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((g,b)=>{const j=mDn[g.activity_type],S=j.icon,C=Ed(new Date(g.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 ${j.bgColor}`,children:e.jsx(S,{className:`h-3.5 w-3.5 ${j.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:()=>{g.contact_id&&t(`/mission-control/contacts/${g.contact_id}`)},children:g.visitor_name}),e.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-muted-foreground",children:[e.jsx("span",{children:j.label}),g.mls_number&&e.jsxs("span",{children:["· MLS# ",g.mls_number]}),g.lead_type&&e.jsxs("span",{children:["· ",g.lead_type]}),e.jsxs("span",{children:["· ",C]})]})]}),e.jsxs("div",{className:"flex items-center gap-0.5 shrink-0",children:[g.visitor_email&&e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-primary",onClick:()=>v(g),children:e.jsx(ln,{className:"h-3.5 w-3.5"})}),g.visitor_phone&&e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-primary",onClick:()=>window.location.href=`tel:${g.visitor_phone}`,children:e.jsx(_a,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-primary",onClick:()=>window.location.href=`sms:${g.visitor_phone}`,children:e.jsx(Hi,{className:"h-3.5 w-3.5"})})]}),g.contact_id&&e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>t(`/mission-control/contacts/${g.contact_id}`),children:e.jsx(xi,{className:"h-3.5 w-3.5"})})]})]},`${g.activity_type}-${g.occurred_at}-${b}`)}),m.length>5&&e.jsxs(B,{variant:"outline",className:"w-full text-xs",onClick:()=>t("/mission-control/website-activity"),children:["View ",m.length-5," more activities",e.jsx(La,{className:"h-3.5 w-3.5 ml-1"})]})]}):e.jsx(ve,{children:e.jsxs(Me,{className:"p-6 text-center",children:[e.jsx(hm,{className:"h-8 w-8 text-muted-foreground/30 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No actionable website activity yet."}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:f>0?`${f} anonymous listing views recorded.`:"Lead engagement will appear here as visitors interact with your site."}),e.jsxs(B,{variant:"outline",size:"sm",className:"mt-3",onClick:()=>t("/mission-control/website-activity"),children:["View Full Activity",e.jsx(La,{className:"h-3.5 w-3.5 ml-1"})]})]})}),n&&c&&e.jsx(DS,{open:l,onOpenChange:o,contact:c,gmailEmail:r})]})}const t2t={Crown:$f,FileText:Fr,Users:In,Globe:sl,Star:Da,Phone:_a,MessageSquare:Hi,PenTool:KA,Video:Kr,Gift:Vo},fDn={"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 xDn(){var ct,xt,qt,Vt,Xt,fs;const s=Fn(),{user:t}=hs(),{data:n}=Z_(),{data:r}=vzt(),{data:a}=Db(),{data:i}=aae(),{data:l}=het(),o=iBs(),c=lLe(),d=nBs(90),u=oLe(),[h,m]=_.useState(null),[p,f]=_.useState(null),[y,v]=_.useState(!1),[g,b]=_.useState(""),[j,S]=_.useState(!1),[C,E]=_.useState(""),[P,M]=_.useState(Nzt()),[I,D]=_.useState("cards"),[O,V]=_.useState(!1),[G,$]=_.useState(null),[H,Y]=_.useState(null),[Z,ne]=_.useState(""),{isGmailConnected:ce,gmailEmail:ie}=Vg(),te=()=>{const Ft=parseInt(C,10);if(isNaN(Ft)||Ft<1){ia({title:"Invalid goal",description:"Please enter a number greater than 0",variant:"destructive"});return}M(Ft),rBs(Ft),S(!1),ia({title:"Goal updated",description:`Weekly touch goal set to ${Ft}`})},ae=()=>{E(P.toString()),S(!0)};_.useEffect(()=>{(async()=>{if(!(t!=null&&t.id))return;const{data:wt}=await q.from("profiles").select("name").eq("id",t.id).single();wt!=null&&wt.name&&b(wt.name.split(" ")[0])})()},[t==null?void 0:t.id]),_.useEffect(()=>{o.mutate()},[]);const le=If(new Date),be=zh(le,7),me=Ft=>{if(!Ft)return null;const wt=Ft.split(/[-/T]/);if(wt.length<3)return null;const Ts=parseInt(wt[1],10)-1,vt=parseInt(wt[2],10);return isNaN(Ts)||isNaN(vt)?null:new Date(le.getFullYear(),Ts,vt)},he=(a==null?void 0:a.filter(Ft=>{const wt=me(Ft.birthday),Ts=me(Ft.home_anniversary);return wt&&cm(wt,le)||Ts&&cm(Ts,le)}))||[],pe=(a==null?void 0:a.filter(Ft=>{if(!Ft.birthday&&!Ft.home_anniversary)return!1;const wt=Ts=>{if(!Ts)return!1;const vt=me(Ts);return vt?Z4(vt,le)&&yS(vt,be):!1};return wt(Ft.birthday)||wt(Ft.home_anniversary)}).slice(0,5))||[],Ce=[],Ae=(i==null?void 0:i.find(Ft=>Ft.name==="Call"))||(i==null?void 0:i[0]);for(const Ft of he){const wt=me(Ft.birthday),Ts=me(Ft.home_anniversary),vt=wt&&cm(wt,le),$s=Ts&&cm(Ts,le);vt&&Ce.push({contact:Ft,actionType:Ae||{id:"special-date-birthday",name:"Birthday Call",icon:"Cake",color:"#EC4899",description:"Wish them happy birthday!",active:!0,sort_order:0,created_at:"",updated_at:""},planName:"🎂 Birthday Today!",relationshipTypeName:((qt=(xt=(ct=Ft.tags)==null?void 0:ct[0])==null?void 0:xt.relationship_type)==null?void 0:qt.name)||"",monthNumber:0,isSpecialDate:!0,specialDateType:"birthday"}),$s&&Ce.push({contact:Ft,actionType:Ae||{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:((fs=(Xt=(Vt=Ft.tags)==null?void 0:Vt[0])==null?void 0:Xt.relationship_type)==null?void 0:fs.name)||"",monthNumber:0,isSpecialDate:!0,specialDateType:"anniversary"})}const ze=l!==void 0?l||[]:(a==null?void 0:a.slice(0,5).map((Ft,wt)=>{var vt,$s,As;const Ts=i==null?void 0:i[wt%((i==null?void 0:i.length)||1)];return Ts?{contact:Ft,actionType:Ts,planName:"Quick Touch",relationshipTypeName:((As=($s=(vt=Ft.tags)==null?void 0:vt[0])==null?void 0:$s.relationship_type)==null?void 0:As.name)||"",monthNumber:0}:null}).filter(Boolean))||[],ke=[...Ce,...ze],{data:Ze}=vW(7),Se=(Ze||[]).filter(Ft=>cm(new Date(Ft.completed_at),le)).length,Fe=Se+ke.length,Ne=(a==null?void 0:a.length)??0,Ye=Ce.length>0?`${Ce.length} celebration${Ce.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.`:pe.length>0?`${pe.length} milestone${pe.length===1?"":"s"} coming up this week — get ahead of them.`:"Consistency beats intensity. A few real conversations today is a win.",Ve=async(Ft,wt,Ts)=>{await u.mutateAsync({contactId:Ft,actionTypeId:wt,scriptUsedId:Ts}),v(!1),f(null)},qe=Ft=>{Ft.script?(f(Ft),v(!0)):Ve(Ft.contact.id,Ft.actionType.id)},Qe=Ft=>t2t[Ft||"Phone"]||_a,Ue=Ft=>t2t[Ft||"Users"]||In,Xe=(Ft,wt)=>Ft.replace(/\{\{FirstName\}\}/g,wt.first_name).replace(/\{\{LastName\}\}/g,wt.last_name||"").replace(/\{\{AgentName\}\}/g,g||"there"),nt=(Ft,wt)=>({Call:`Thinking of you, ${wt}!`,Text:`Quick hello, ${wt}`,Email:`Checking in, ${wt}`,"Handwritten Note":`A note for ${wt}`,Video:`Video message for ${wt}`,Gift:`Something special for you, ${wt}`})[Ft]||`Hello ${wt}!`,$e=(Ft,wt,Ts)=>{const vt=`sms:${Ft}`;if(wt&&Ts){const $s=Xe(wt,Ts);return`${vt}?body=${encodeURIComponent($s)}`}return vt},Ge=(Ft,wt,Ts,vt,$s)=>{const As=`mailto:${Ft}`,jn=[];if($s){const ar=Ts||nt(vt||"Email",$s.first_name);if(jn.push(`subject=${encodeURIComponent(ar)}`),wt){const Dn=Xe(wt,$s);jn.push(`body=${encodeURIComponent(Dn)}`)}}return jn.length>0?`${As}?${jn.join("&")}`:As};return e.jsxs(e.Fragment,{children:[e.jsxs(zs,{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(B,{size:"sm",onClick:()=>s("/mission-control/video/record"),className:"gap-1.5 bg-gradient-to-r from-primary to-primary/80",children:[e.jsx(dm,{className:"h-4 w-4"}),"Quick Video"]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>s("/mission-control/contacts"),className:"gap-1.5",children:[e.jsx(In,{className:"h-4 w-4"}),"Contacts"]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>s("/mission-control/video-library"),className:"gap-1.5",children:[e.jsx(Kr,{className:"h-4 w-4"}),"Library"]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>s("/mission-control/plans"),className:"gap-1.5",children:[e.jsx(qc,{className:"h-4 w-4"}),"Plans"]})]})]}),e.jsx(sDn,{agentName:g,todayDone:Se,todayTotal:Fe,focusLine:Ye,weekDone:c.actionsThisWeek,weekGoal:P,streak:c.streak,staleCount:d.count,sphereCount:Ne,onEditGoal:ae,onStaleClick:()=>s("/mission-control/contacts?filter=not-touched-90"),onSphereClick:()=>s("/mission-control/contacts")}),e.jsx(pDn,{}),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(xi,{className:"h-3 w-3"})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:n==null?void 0:n.filter(Ft=>Ft.active).map(Ft=>{const wt=Ue(Ft.icon),Ts=(r==null?void 0:r[Ft.id])||0,vt=h===Ft.id,$s=fDn[Ft.name]||"bg-secondary text-secondary-foreground";return e.jsxs("button",{onClick:()=>{vt?(m(null),s("/mission-control/contacts")):(m(Ft.id),s(`/mission-control/contacts?type=${Ft.id}`))},className:` inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-sm transition-all ${vt?$s:"bg-card hover:bg-accent"} `,children:[e.jsx(wt,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"font-medium",children:Ft.name}),e.jsx("span",{className:`rounded-full px-1.5 py-0.5 text-[11px] tabular-nums ${vt?"bg-black/15":"bg-muted text-muted-foreground"}`,children:Ts})]},Ft.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(Oe,{variant:"outline",className:"gap-1",children:[e.jsx(un,{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(B,{variant:I==="cards"?"secondary":"ghost",size:"sm",className:"h-7 px-2",onClick:()=>D("cards"),title:"Card view",children:e.jsx(sf,{className:"h-4 w-4"})}),e.jsx(B,{variant:I==="table"?"secondary":"ghost",size:"sm",className:"h-7 px-2",onClick:()=>D("table"),title:"Table view",children:e.jsx(A0,{className:"h-4 w-4"})})]})]}),e.jsx(ve,{children:e.jsx(Me,{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(B,{variant:"outline",className:"mt-4",onClick:()=>s("/mission-control/plans"),children:"Manage Plans"})]}):I==="table"?e.jsx(cDn,{actions:ke,onMarkComplete:Ve,onViewScript:qe,isLoading:u.isPending,buildSmsLink:$e,buildEmailLink:Ge,onGmailCompose:ce?Ft=>{$(Ft),V(!0)}:void 0}):e.jsxs("div",{className:"flex gap-3 overflow-x-auto pb-2",children:[ke.map((Ft,wt)=>{var Ur,Vs,hn,dr,Cn,Yn,on;const Ts=Ft.isSpecialDate,vt=Ft.specialDateType,$s=Ts?vt==="birthday"?Bf:Jr:Qe(((Ur=Ft.actionType)==null?void 0:Ur.icon)||null),As=Ft.contact.phone,jn=Ft.contact.email,ar=Ts?vt==="birthday"?"#EC4899":"#8B5CF6":((Vs=Ft.actionType)==null?void 0:Vs.color)||"#3B82F6",Dn=Ts?vt==="birthday"?"🎂 Birthday Today!":"🏠 Home Anniversary!":(hn=Ft.actionType)==null?void 0:hn.name;return e.jsxs("div",{className:`flex-shrink-0 w-[260px] border rounded-lg overflow-hidden ${Ts?"ring-2 ring-offset-2":""}`,style:Ts?{"--tw-ring-color":ar}:void 0,children:[e.jsxs("div",{className:"p-3 text-white flex items-center gap-2",style:{backgroundColor:ar},children:[e.jsx($s,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium text-sm",children:Dn})]}),e.jsxs("div",{className:"p-3 space-y-2",children:[e.jsxs("button",{onClick:()=>s(`/mission-control/contacts/${Ft.contact.id}`),className:"font-medium text-sm hover:text-primary hover:underline transition-colors text-left",children:[Ft.contact.first_name," ",Ft.contact.last_name]}),e.jsxs("div",{className:"flex gap-1.5",children:[As&&e.jsxs(e.Fragment,{children:[e.jsxs("a",{href:`tel:${Ft.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(_a,{className:"h-3 w-3"}),"Call"]}),e.jsxs("a",{href:$e(Ft.contact.phone,(dr=Ft.script)==null?void 0:dr.script_body,Ft.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(Hi,{className:"h-3 w-3"}),"Text"]})]}),jn&&(ce?e.jsxs("button",{onClick:()=>{$({id:Ft.contact.id,first_name:Ft.contact.first_name,last_name:Ft.contact.last_name,email:Ft.contact.email}),V(!0)},className:"flex-1 flex items-center justify-center gap-1 px-2 py-1.5 bg-sky-500/10 hover:bg-sky-500/20 text-sky-600 dark:text-sky-400 rounded text-xs font-medium transition-colors",title:"Compose Email",children:[e.jsx(ln,{className:"h-3 w-3"}),"Email"]}):e.jsxs("a",{href:Ge(Ft.contact.email,(Cn=Ft.script)==null?void 0:Cn.script_body,(Yn=Ft.script)==null?void 0:Yn.email_subject,(on=Ft.actionType)==null?void 0:on.name,Ft.contact),className:"flex-1 flex items-center justify-center gap-1 px-2 py-1.5 bg-sky-500/10 hover:bg-sky-500/20 text-sky-600 dark:text-sky-400 rounded text-xs font-medium transition-colors",title:"Email",children:[e.jsx(ln,{className:"h-3 w-3"}),"Email"]}))]}),Ts&&e.jsxs("button",{onClick:()=>{const Ir=`${Ft.contact.first_name}${Ft.contact.last_name?" "+Ft.contact.last_name:""}`,Wn=vt==="birthday"?"birthday":"home_anniversary",Js=new URLSearchParams({cardType:Wn,contactId:Ft.contact.id,name:Ir,...Ft.contact.address?{address:Ft.contact.address}:{},...vt==="anniversary"&&Ft.contact.home_anniversary?{date:Ft.contact.home_anniversary}:{}});s(`/mission-control/card-studio?${Js.toString()}`)},className:"w-full flex items-center justify-center gap-1.5 px-2 py-1.5 rounded text-xs font-semibold bg-gradient-to-r from-pink-500/15 to-violet-500/15 hover:from-pink-500/25 hover:to-violet-500/25 text-pink-600 dark:text-pink-400 transition-colors",children:[e.jsx(ln,{className:"h-3 w-3"}),"Send ",vt==="birthday"?"Birthday":"Anniversary"," Card"]}),!As&&!jn&&e.jsx("p",{className:"text-xs text-muted-foreground italic",children:"No contact info"}),e.jsxs("div",{className:"flex gap-1 flex-wrap",children:[Ft.relationshipTypeName&&e.jsx(Oe,{variant:"secondary",className:"text-xs",children:Ft.relationshipTypeName}),Ft.monthNumber>0&&e.jsxs(Oe,{variant:"outline",className:"text-xs",children:["Month ",Ft.monthNumber]})]}),Ft.script&&e.jsx(B,{size:"sm",variant:"outline",className:"w-full",onClick:()=>qe(Ft),children:"View Script"}),e.jsxs("div",{className:"flex gap-1.5",children:[e.jsxs(B,{size:"sm",variant:"outline",className:"flex-1 gap-1",onClick:()=>{Y(Ft.contact.id),ne(`${Ft.contact.first_name} ${Ft.contact.last_name||""}`.trim())},children:[e.jsx(ky,{className:"h-3.5 w-3.5"}),"Snooze"]}),e.jsx(B,{size:"sm",className:"flex-1",onClick:()=>{var Ir;return Ve(Ft.contact.id,Ft.actionType.id,(Ir=Ft.script)==null?void 0:Ir.id)},disabled:u.isPending,children:"Mark Complete"})]})]})]},Ft.contact.id+wt)}),e.jsx("div",{className:"flex-shrink-0 w-[100px] border rounded-lg flex items-center justify-center",children:e.jsxs(tu,{children:[e.jsx(su,{asChild:!0,children:e.jsxs(B,{variant:"ghost",className:"h-full w-full",children:[e.jsx(ob,{className:"h-5 w-5 mr-2"}),"More"]})}),e.jsx(Od,{children:e.jsx(ca,{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(gu,{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(Fi,{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(Ls,{open:j,onOpenChange:S,children:e.jsxs(Ps,{className:"sm:max-w-[360px]",children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Set Weekly Goal"}),e.jsx(_r,{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(J,{htmlFor:"weekly-goal-ic",children:"Weekly touch goal"}),e.jsx(xe,{id:"weekly-goal-ic",type:"number",min:"1",value:C,onChange:Ft=>E(Ft.target.value),placeholder:"20",onKeyDown:Ft=>{Ft.key==="Enter"&&te()}})]}),e.jsx(B,{onClick:te,className:"w-full",children:"Save Goal"})]})]})}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-6",children:[e.jsx(qzt,{}),e.jsx(dDn,{})]})]}),e.jsx(Ls,{open:y,onOpenChange:v,children:e.jsxs(Ps,{className:"max-w-md",children:[e.jsx(Os,{children:e.jsx(Ds,{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:Xe(p.script.script_body,p.contact)})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",className:"flex-1",onClick:()=>v(!1),children:"Close"}),e.jsx(B,{className:"flex-1",onClick:()=>{var Ft;return Ve(p.contact.id,p.actionType.id,(Ft=p.script)==null?void 0:Ft.id)},disabled:u.isPending,children:"Mark Complete"})]})]})]})}),e.jsx(nDn,{})]}),ce&&G&&e.jsx(DS,{open:O,onOpenChange:V,contact:G,gmailEmail:ie}),e.jsx(KIe,{open:!!H,onOpenChange:Ft=>!Ft&&Y(null),contactId:H||"",contactName:Z})]})}const gDn=[{value:"bidirectional",label:"Two-Way",icon:Lg,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:zf,tooltip:"Only pull BoldTrail → Agent OS"}];function DTe({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(T$,{type:"single",value:s,onValueChange:a=>{a&&t(a)},className:"justify-start",children:gDn.map(a=>e.jsxs(ag,{children:[e.jsx(ig,{asChild:!0,children:e.jsxs(N7,{value:a.value,"aria-label":a.tooltip,className:`gap-1.5 ${r} border border-transparent data-[state=on]:!bg-primary data-[state=on]:!text-primary-foreground data-[state=on]:!border-primary data-[state=on]:shadow-sm`,children:[e.jsx(a.icon,{className:n==="sm"?"h-3 w-3":"h-4 w-4"}),a.label]})}),e.jsx(Nx,{children:a.tooltip})]},a.value))})]})}function yDn(){const s=Bt(),[t,n]=_.useState(!1),[r,a]=_.useState(null),[i,l]=_.useState(!1),[o,c]=_.useState(!1),[d,u]=_.useState(null),[h,m]=_.useState(null),[p,f]=_.useState(0),y=_.useRef(!1),{data:v}=at({queryKey:["boldtrail-status"],queryFn:async()=>{const{data:I,error:D}=await q.functions.invoke("boldtrail-sync",{body:{action:"status"}});if(D)throw D;return I}}),g=(v==null?void 0:v.sync_direction)||"bidirectional",b=d??g,j=mt({mutationFn:async()=>{const{data:I,error:D}=await q.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=>{se.error(I.message||"Failed to generate sync preview")}}),S=mt({mutationFn:async()=>{y.current=!1,m("Initializing sync..."),f(5);const{data:I,error:D}=await q.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"init",sync_direction:b}});if(D)throw D;if(I!=null&&I.error)throw new Error(I.error);const O=I;let V=O.sync_log_id,G=O.next_phase,$=O.next_offset,H=O.push_total||0,Y=O.pull_total||0,Z=O.update_total||0,ne=0,ce=0,ie=0;for(;G!=="finalize"&&!y.current;){const le=H+Y+Z;G==="fetch_bt"?m("Fetching BoldTrail contacts..."):G==="analyze"?(m("Analyzing contacts..."),f(15)):G==="push"?(m(`Pushing contacts to BoldTrail... (${ne}/${H})`),f(le>0?ne/le*90:0)):G==="pull"?(m(`Pulling contacts from BoldTrail... (${ce}/${Y})`),f(le>0?(H+ce)/le*90:0)):G==="update"&&(m(`Updating existing contacts... (${ie}/${Z})`),f(le>0?(H+Y+ie)/le*90:0));const{data:be,error:me}=await q.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:G,offset:$,sync_log_id:V,sync_direction:b}});if(me)throw me;if(be!=null&&be.error)throw new Error(be.error);const he=be;ne+=he.chunk_pushed||0,ce+=he.chunk_pulled||0,ie+=he.chunk_updated||0,he.push_total!==void 0&&(H=he.push_total||0),he.pull_total!==void 0&&(Y=he.pull_total||0),he.update_total!==void 0&&(Z=he.update_total||0),he.progress&&m(he.progress),G=he.next_phase,$=he.next_offset}m("Finalizing sync..."),f(95);const{data:te,error:ae}=await q.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"finalize",sync_log_id:V,sync_direction:b}});if(ae)throw ae;return f(100),te},onSuccess:I=>{m(null),f(0),n(!1),s.invalidateQueries({queryKey:["boldtrail-status"]}),s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),s.invalidateQueries({queryKey:["contacts-last-touch"]});const D=[`Pushed ${I.contacts_pushed||0}`,`pulled ${I.contacts_pulled||0}`,`updated ${I.contacts_updated||0}`,`skipped ${I.contacts_skipped||0} duplicates`];se.success(`Sync complete! ${D.join(", ")}.`)},onError:I=>{m(null),f(0),se.error(I.message||"Sync failed")}});if(!(v!=null&&v.connected))return null;const C=b==="pull_only"?0:(r==null?void 0:r.to_push)??0,E=b==="push_only"?0:(r==null?void 0:r.to_pull)??0,P=(r==null?void 0:r.to_update)??0,M=C>0||E>0||P>0;return e.jsxs(e.Fragment,{children:[e.jsxs(ag,{children:[e.jsx(ig,{asChild:!0,children:e.jsx(B,{variant:"outline",size:"icon",onClick:()=>j.mutate(),disabled:j.isPending,className:"shrink-0",children:j.isPending?e.jsx(uo,{className:"h-4 w-4 animate-spin"}):e.jsx(Lg,{className:"h-4 w-4 text-emerald-600"})})}),e.jsx(Nx,{children:"Sync with BoldTrail"})]}),e.jsx(Ls,{open:t,onOpenChange:I=>{S.isPending||n(I)},children:e.jsxs(Ps,{className:"sm:max-w-lg",children:[e.jsxs(Os,{children:[e.jsxs(Ds,{className:"flex items-center gap-2",children:[e.jsx(Lg,{className:"h-5 w-5 text-emerald-600"}),"Sync Preview"]}),e.jsx(_r,{children:"Review what will happen when you sync your contacts."})]}),r&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(DTe,{value:b,onChange:u,size:"sm"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:`rounded-lg border p-3 text-center ${b==="pull_only"?"opacity-40":""}`,children:[e.jsx("p",{className:"text-2xl font-bold text-emerald-600",children:C}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(sp,{className:"h-3 w-3"})," Push to BoldTrail"]})]}),e.jsxs("div",{className:`rounded-lg border p-3 text-center ${b==="push_only"?"opacity-40":""}`,children:[e.jsx("p",{className:"text-2xl font-bold text-blue-600",children:E}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(zf,{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(Xq,{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(In,{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(Xq,{className:"h-3 w-3 inline mr-1"}),P," contacts have missing fields that will be filled from the other system"]}),C>0&&e.jsxs(f1,{open:i,onOpenChange:l,children:[e.jsx(x1,{asChild:!0,children:e.jsxs(B,{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"}),C," contacts to push to BoldTrail"]}),e.jsx(tl,{className:`h-3 w-3 transition-transform ${i?"rotate-180":""}`})]})}),e.jsx(g1,{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"]})]})})]}),E>0&&e.jsxs(f1,{open:o,onOpenChange:c,children:[e.jsx(x1,{asChild:!0,children:e.jsxs(B,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(zf,{className:"h-3 w-3 text-blue-600"}),E," contacts to pull from BoldTrail"]}),e.jsx(tl,{className:`h-3 w-3 transition-transform ${o?"rotate-180":""}`})]})}),e.jsx(g1,{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&&!S.isPending&&e.jsx("div",{className:"text-center py-4 text-sm text-muted-foreground",children:"✅ Everything is already in sync! No contacts to transfer or update."}),S.isPending&&e.jsxs("div",{className:"space-y-2 py-2",children:[e.jsx(Fi,{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(B,{variant:"outline",onClick:()=>n(!1),disabled:S.isPending,children:"Cancel"}),e.jsxs(B,{onClick:()=>S.mutate(),disabled:S.isPending||!M,className:"gap-2",children:[S.isPending?e.jsx(uo,{className:"h-4 w-4 animate-spin"}):e.jsx(Lg,{className:"h-4 w-4"}),S.isPending?"Syncing...":"Sync Now"]})]})]})]})})]})}const vDn=[{key:"first_name",label:"First name"},{key:"last_name",label:"Last name"},{key:"email",label:"Email"},{key:"phone",label:"Phone"},{key:"address",label:"Street address"},{key:"city",label:"City"},{key:"state",label:"State"},{key:"zip",label:"ZIP"},{key:"birthday",label:"Birthday"},{key:"home_anniversary",label:"Home anniversary"},{key:"wedding_anniversary",label:"Wedding anniversary"},{key:"spouse_name",label:"Spouse name"},{key:"spouse_email",label:"Spouse email"},{key:"spouse_birthday",label:"Spouse birthday"},{key:"company_name",label:"Company"},{key:"job_title",label:"Job title"},{key:"lead_source",label:"Lead source"},{key:"avatar_url",label:"Photo"}],bDn="id, first_name, last_name, email, phone, address, city, state, zip, birthday, home_anniversary, wedding_anniversary, spouse_name, spouse_email, spouse_birthday, company_name, job_title, lead_source, avatar_url, notes, created_at, updated_at";function RTe(s){return Object.entries(s).filter(([t,n])=>t!=="id"&&n!==null&&n!==void 0&&String(n).trim()!=="").length}function _Dn(s){return at({queryKey:["contact-duplicates"],enabled:s,staleTime:6e4,queryFn:async()=>{const{data:t,error:n}=await q.rpc("find_duplicate_contacts",{_limit:200});if(n)throw n;return(t??[]).map(r=>({match_type:r.match_type,match_value:r.match_value,contact_ids:r.contact_ids??[],contacts:r.contacts??[]}))}})}function wDn(s,t){return at({queryKey:["merge-candidates",[...s].sort().join(",")],enabled:t&&s.length>1,queryFn:async()=>{const{data:n,error:r}=await q.from("innercircle_contacts").select(bDn).in("id",s);if(r)throw r;return n??[]}})}function gYt(){const s=Bt();return mt({mutationFn:async({primaryId:t,duplicateIds:n,overrides:r})=>{if(r&&Object.keys(r).length>0){const{error:l}=await q.from("innercircle_contacts").update({...r,updated_at:new Date().toISOString()}).eq("id",t);if(l)throw l}const a=[];let i=0;for(const l of n){if(l===t)continue;const{error:o}=await q.rpc("merge_innercircle_contacts",{_primary_id:t,_duplicate_id:l});o?a.push({id:l,message:o.message}):i+=1}return{merged:i,failed:a}},onSuccess:()=>{s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),s.invalidateQueries({queryKey:["all-contact-custom-tags"]}),s.invalidateQueries({queryKey:["contact-duplicates"]})}})}function s2t(s){return[s.first_name,s.last_name].filter(Boolean).join(" ")||"Unnamed contact"}function Oce(s,t){const n=s==null?void 0:s[t];return n==null||String(n).trim()===""?null:String(n)}function yYt({open:s,onOpenChange:t,contactIds:n,onMerged:r}){const{data:a,isLoading:i}=wDn(n,s),l=gYt(),[o,c]=_.useState(null),[d,u]=_.useState({}),h=_.useMemo(()=>a??[],[a]);_.useEffect(()=>{if(!s){c(v=>v===null?v:null),u(v=>Object.keys(v).length===0?v:{});return}if(h.length&&!o){const v=[...h].sort((g,b)=>RTe(b)-RTe(g))[0];c(v.id)}},[s,h,o]),_.useEffect(()=>{u(v=>Object.keys(v).length===0?v:{})},[o]);const m=_.useMemo(()=>vDn.map(v=>{const g=h.map(j=>({id:j.id,value:Oce(j,v.key)})).filter(j=>j.value!==null),b=Array.from(new Set(g.map(j=>j.value)));return{...v,values:g,distinct:b}}).filter(v=>v.distinct.length>1),[h]),p=h.find(v=>v.id===o)??null,f=async()=>{if(!p)return;const v={};for(const[g,b]of Object.entries(d)){const j=h.find(C=>C.id===b);if(!j)continue;const S=Oce(j,g);S!==null&&S!==Oce(p,g)&&(v[g]=j[g])}try{const g=await l.mutateAsync({primaryId:p.id,duplicateIds:h.filter(b=>b.id!==p.id).map(b=>b.id),overrides:v});g.failed.length?ia({title:`Merged ${g.merged} of ${g.merged+g.failed.length}`,description:g.failed[0].message,variant:"destructive"}):ia({title:`Merged into ${s2t(p)}`,description:"Nothing in their history was lost."}),t(!1),r==null||r()}catch(g){ia({title:"Could not merge",description:g.message,variant:"destructive"})}},y=n.length>10;return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"max-w-3xl max-h-[90vh] flex flex-col",children:[e.jsxs(Os,{children:[e.jsxs(Ds,{className:"flex items-center gap-2",children:[e.jsx(s7,{className:"h-4 w-4"}),"Merge contacts"]}),e.jsx(_r,{children:"Choose the record to keep, then pick which details win. Notes, tags, history, deals and tasks from every record stay with the contact you keep."})]}),y?e.jsx("p",{className:"py-6 text-sm text-muted-foreground",children:"You can merge up to 10 contacts at a time. Please narrow your selection."}):i?e.jsx("div",{className:"flex items-center justify-center py-10",children:e.jsx(Ct,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):h.length<2?e.jsx("p",{className:"py-6 text-sm text-muted-foreground",children:"Pick at least two contacts to merge."}):e.jsx(Ji,{className:"flex-1 -mx-2 px-2",children:e.jsxs("div",{className:"space-y-5 pb-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium",children:"Which record should we keep?"}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:h.map(v=>e.jsxs("button",{type:"button",onClick:()=>c(v.id),className:`rounded-lg border p-3 text-left transition-colors ${o===v.id?"border-primary bg-primary/5":"hover:bg-accent"}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"font-medium truncate",children:s2t(v)}),o===v.id&&e.jsx(Oe,{variant:"secondary",children:"Keep"})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:v.email||"No email"}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:v.phone||"No phone"}),v.created_at&&e.jsxs("p",{className:"mt-1 text-[11px] text-muted-foreground",children:["Added ",new Date(String(v.created_at)).toLocaleDateString()]})]},v.id))})]}),m.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-sm font-medium",children:"These details differ — pick what to keep"}),m.map(v=>{var b;const g=d[v.key]??(p&&Oce(p,v.key)!==null?p.id:(b=v.values[0])==null?void 0:b.id);return e.jsxs("div",{className:"rounded-lg border p-3",children:[e.jsx("p",{className:"mb-2 text-xs uppercase tracking-wide text-muted-foreground",children:v.label}),e.jsx("div",{className:"flex flex-wrap gap-2",children:v.values.map(j=>e.jsx("button",{type:"button",onClick:()=>u(S=>({...S,[v.key]:j.id})),className:`rounded-md border px-2.5 py-1.5 text-sm transition-colors ${g===j.id?"border-primary bg-primary/10 font-medium":"hover:bg-accent text-muted-foreground"}`,children:j.value},j.id))})]},v.key)})]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["1 contact will be kept, ",h.length-1," will be removed. Nothing in their history is lost."]})]})}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),disabled:l.isPending,children:"Cancel"}),e.jsxs(B,{onClick:f,disabled:!p||h.length<2||y||l.isPending,children:[l.isPending&&e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}),"Merge — this can't be undone"]})]})]})})}const jDn={email:"Same email",phone:"Same phone",name:"Same name"};function NDn(s){return[s.first_name,s.last_name].filter(Boolean).join(" ")||"Unnamed contact"}function kDn({open:s,onOpenChange:t}){const{data:n,isLoading:r,isError:a,error:i}=_Dn(s),l=gYt(),[o,c]=_.useState(new Set),[d,u]=_.useState(null),[h,m]=_.useState(!1),p=_.useMemo(()=>(n??[]).filter(v=>v.contact_ids.length>1&&!o.has(v.contact_ids.join(","))),[n,o]),f=p.filter(v=>v.match_type!=="name"),y=async()=>{m(!0);let v=0,g=0;try{for(const b of f){const j=[...b.contacts].sort((E,P)=>RTe(P)-RTe(E))[0],S=(j==null?void 0:j.id)??b.contact_ids[0],C=await l.mutateAsync({primaryId:S,duplicateIds:b.contact_ids.filter(E=>E!==S)});v+=C.merged,g+=C.failed.length}ia({title:`Merged ${v} duplicate${v===1?"":"s"}`,description:g?`${g} could not be merged.`:"Name-only matches still need your review.",variant:g?"destructive":void 0})}catch(b){ia({title:"Could not finish merging",description:b.message,variant:"destructive"})}finally{m(!1)}};return e.jsxs(e.Fragment,{children:[e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"flex h-[90dvh] max-h-[90dvh] max-w-2xl flex-col overflow-hidden",children:[e.jsxs(Os,{className:"shrink-0",children:[e.jsx(Ds,{children:"Find duplicates"}),e.jsx(_r,{children:"We looked through your whole database for contacts that share an email, a phone number, or a name."})]}),r?e.jsx("div",{className:"flex items-center justify-center py-10",children:e.jsx(Ct,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):a?e.jsx("p",{className:"py-6 text-sm text-destructive",children:(i==null?void 0:i.message)??"Could not check for duplicates."}):p.length===0?e.jsx("p",{className:"py-8 text-center text-sm text-muted-foreground",children:"No duplicates found. Your database looks clean."}):e.jsx("div",{className:"min-h-0 flex-1 -mx-2 overflow-y-auto overscroll-contain px-2 pr-3 touch-pan-y",children:e.jsx("div",{className:"space-y-3 pb-2",children:p.map(v=>{const g=v.contact_ids.join(",");return e.jsxs("div",{className:"rounded-lg border p-3",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(Oe,{variant:"secondary",children:jDn[v.match_type]}),e.jsx("span",{className:"truncate text-xs text-muted-foreground",children:v.match_value}),e.jsxs("span",{className:"ml-auto text-xs text-muted-foreground",children:[v.contact_ids.length," records"]})]}),e.jsx("div",{className:"space-y-1",children:v.contacts.map(b=>e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 text-sm",children:[e.jsx("span",{className:"font-medium",children:NDn(b)}),b.email&&e.jsx("span",{className:"text-muted-foreground",children:b.email}),b.phone&&e.jsx("span",{className:"text-muted-foreground",children:b.phone}),b.created_at&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["added ",new Date(String(b.created_at)).toLocaleDateString()]})]},b.id))}),e.jsxs("div",{className:"mt-3 flex gap-2",children:[e.jsx(B,{size:"sm",onClick:()=>u(v.contact_ids),children:"Review & merge"}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>c(b=>new Set(b).add(g)),children:"Not a duplicate"})]})]},`${v.match_type}-${g}`)})})}),e.jsxs(yr,{className:"shrink-0 gap-2 sm:justify-between",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),disabled:h,children:"Close"}),f.length>0&&e.jsxs(B,{onClick:y,disabled:h,children:[h?e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(un,{className:"mr-2 h-4 w-4"}),"Merge all safe matches (",f.length,")"]})]})]})}),e.jsx(yYt,{open:!!d,onOpenChange:v=>{v||u(null)},contactIds:d??[]})]})}const SDn=()=>{const{user:s}=hs();return at({queryKey:["popby-items",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.from("popby_items").select("*").or(`owner_user_id.is.null,owner_user_id.eq.${s==null?void 0:s.id}`).eq("is_active",!0).order("name");if(n)throw n;return t},enabled:!!s})},YIe=s=>{const{user:t}=hs();return at({queryKey:["popby-logs",t==null?void 0:t.id,s],queryFn:async()=>{let n=q.from("popby_logs").select("*").order("completed_at",{ascending:!1});if(s){const i=new Date;i.setDate(i.getDate()-s),n=n.gte("completed_at",i.toISOString())}const{data:r,error:a}=await n;if(a)throw a;return r},enabled:!!t})},_nt=()=>{const{user:s}=hs();return at({queryKey:["relationship-type-popby-defaults",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.from("relationship_type_popby_defaults").select("*");if(n)throw n;return t},enabled:!!s})},vYt=()=>{const{user:s}=hs();return at({queryKey:["contact-popby-settings",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.from("contact_popby_settings").select("*");if(n)throw n;return t},enabled:!!s})},CDn=()=>{const{data:s}=Db();Z_();const{data:t}=YIe(),{data:n}=vYt(),{data:r}=_nt(),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=If(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 y=d.tags.map(v=>i.get(v.relationship_type_id)).filter(v=>v!==void 0);y.length>0&&(u=Math.min(...y))}const h=a.get(d.id)||null,m=h?CN(o,If(new Date(h))):null,p=m===null||m>=u,f=p&&m!==null?m-u:0;return{...d,lastPopby:h,daysSinceLastPopby:m,frequencyDays:u,isDue:p,daysOverdue:f}}).sort((d,u)=>u.daysOverdue-d.daysOverdue)},bYt=()=>CDn().filter(t=>t.isDue),ADn=()=>{const s=Bt(),{user:t}=hs();return mt({mutationFn:async n=>{const{error:r}=await q.from("popby_items").insert({...n,owner_user_id:t==null?void 0:t.id});if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["popby-items"]}),ia({title:"Popby item created!"})},onError:n=>{ia({title:"Error creating popby item",description:n.message,variant:"destructive"})}})},EDn=()=>{const s=Bt(),{user:t}=hs();return mt({mutationFn:async n=>{const r=new Date().toISOString(),{error:a}=await q.from("popby_logs").insert({...n,owner_user_id:t==null?void 0:t.id,completed_at:r});if(a)throw a;try{const{data:i}=await q.from("action_types").select("id").ilike("name","Pop-By").eq("active",!0).maybeSingle();i!=null&&i.id&&await q.from("contact_touch_logs").insert({owner_user_id:t==null?void 0:t.id,contact_id:n.contact_id,action_type_id:i.id,notes:n.notes??"Pop-by logged",completed_at:r})}catch(i){console.error("Failed to log corresponding touch for popby",i)}},onSuccess:()=>{s.invalidateQueries({queryKey:["popby-logs"]}),s.invalidateQueries({queryKey:["contact-touch-logs"]}),s.invalidateQueries({queryKey:["contacts-last-touch"]}),ia({title:"Popby logged!"})},onError:n=>{ia({title:"Error logging popby",description:n.message,variant:"destructive"})}})},TDn=()=>{const s=Bt(),{user:t}=hs();return mt({mutationFn:async n=>{const{error:r}=await q.from("relationship_type_popby_defaults").upsert({...n,owner_user_id:t==null?void 0:t.id},{onConflict:"relationship_type_id,owner_user_id"});if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["relationship-type-popby-defaults"]}),ia({title:"Frequency updated!"})},onError:n=>{ia({title:"Error updating frequency",description:n.message,variant:"destructive"})}})},MDn=()=>{const{data:s}=YIe(30),t=bYt(),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 PDn(){const{user:s}=hs();return at({queryKey:["contact-touch-logs",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.from("contact_touch_logs").select("*").order("completed_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function _Yt(s){const{data:t}=PDn(),{data:n}=vYt(),{data:r}=_nt(),{data:a}=rDn();return _.useMemo(()=>{const i=a==null?void 0:a.find(v=>v.contact_id===s.id),l=i?new Date(i.snoozed_until):null,o=If(new Date);if(l&&!yS(l,o))return{nextTouchDate:l,daysUntil:CN(l,o),status:"snoozed",frequencyDays:90,lastTouchDate:null,snoozedUntil:l};const d=((t==null?void 0:t.filter(v=>v.contact_id===s.id))||[]).sort((v,g)=>new Date(g.completed_at).getTime()-new Date(v.completed_at).getTime())[0],u=d?new Date(d.completed_at):null;let h=90;const m=n==null?void 0:n.find(v=>v.contact_id===s.id&&v.is_active);if(m)h=m.frequency_days;else if(s.tags&&s.tags.length>0){const v=s.tags.map(g=>{const b=r==null?void 0:r.find(j=>j.relationship_type_id===g.relationship_type_id);return b==null?void 0:b.frequency_days}).filter(g=>g!==void 0);v.length>0&&(h=Math.min(...v))}if(!u)return{nextTouchDate:null,daysUntil:null,status:"never-touched",frequencyDays:h,lastTouchDate:null,snoozedUntil:null};const p=zh(If(u),h),f=CN(p,o);let y;return f<0?y="overdue":f<=7?y="due-soon":y="on-track",{nextTouchDate:p,daysUntil:f,status:y,frequencyDays:h,lastTouchDate:u,snoozedUntil:null}},[s,t,n,r,a])}function n2t({contact:s}){const t=_Yt(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:Gr,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:Er,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:ky,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:ga,text:"Never touched",className:"border-dashed"}}})(),a=r.icon;return e.jsxs(Oe,{variant:r.variant,className:At("gap-1",r.className),children:[e.jsx(a,{className:"h-3 w-3"}),r.text]})}function LDn({contact:s,onLogTouch:t,onSnooze:n}){const r=_Yt(s),a=iDn(),[i,l]=_.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(Gr,{className:"h-5 w-5 text-amber-600 dark:text-amber-400"});case"on-track":return e.jsx(Er,{className:"h-5 w-5 text-emerald-600 dark:text-emerald-400"});case"snoozed":return e.jsx(ky,{className:"h-5 w-5 text-slate-600 dark:text-slate-400"});case"never-touched":return e.jsx(ga,{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(ve,{children:[e.jsx(bt,{className:"pb-2",children:e.jsxs(St,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(ga,{className:"h-4 w-4"}),"Next Touch"]})}),e.jsxs(Me,{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[c(),e.jsx("span",{className:At("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(B,{size:"sm",variant:"outline",className:"flex-1",onClick:u,disabled:a.isPending,children:[e.jsx(Qn,{className:"h-4 w-4 mr-1"}),"Cancel Snooze"]}),t&&e.jsx(B,{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(B,{size:"sm",variant:"outline",className:"flex-1",onClick:()=>l(!0),children:[e.jsx(ky,{className:"h-4 w-4 mr-1"}),"Snooze"]}),(r.status==="overdue"||r.status==="due-soon"||r.status==="never-touched")&&t&&e.jsx(B,{size:"sm",className:"flex-1",variant:r.status==="overdue"?"default":"outline",onClick:t,children:"Log Touch"})]})]})]}),e.jsx(KIe,{open:i,onOpenChange:l,contactId:s.id,contactName:`${s.first_name} ${s.last_name||""}`.trim()})]})}const tze=768;function $W(){const[s,t]=_.useState(void 0);return _.useEffect(()=>{const n=window.matchMedia(`(max-width: ${tze-1}px)`),r=()=>{t(window.innerWidthn.removeEventListener("change",r)},[]),!!s}function IDn(){const{user:s}=hs(),{hasLeadSite:t,leadSite:n}=lf(),{data:r,isLoading:a}=at({queryKey:["website-active-contacts",s==null?void 0:s.id,n==null?void 0:n.id],queryFn:async()=>{if(!n)return new Set;const{data:i}=await q.from("lead_site_visitors").select("contact_id").eq("lead_site_id",n.id).not("contact_id","is",null),{data:l}=await q.from("lead_site_consumer_profiles").select("contact_id").eq("lead_site_id",n.id).not("contact_id","is",null),o=new Set;return(i||[]).forEach(c=>{c.contact_id&&o.add(c.contact_id)}),(l||[]).forEach(c=>{c.contact_id&&o.add(c.contact_id)}),o},enabled:!!s&&t,staleTime:5*60*1e3});return{activeContactIds:r??new Set,hasLeadSite:t,isLoading:a}}const DDn={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"}},RDn={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 xWe({score:s,showScore:t=!1,showTooltip:n=!0,size:r="sm",className:a}){const i=DDn[s.status],l=RDn[r],o=e.jsxs("div",{className:At("inline-flex items-center rounded-full font-medium",i.bgLightClass,i.textClass,l.badge,l.text,a),children:[e.jsx("span",{className:At("rounded-full",i.bgClass,l.dot)}),t?e.jsx("span",{children:s.score}):e.jsx("span",{children:i.label})]});return n?e.jsx(FN,{children:e.jsxs(ag,{children:[e.jsx(ig,{asChild:!0,children:o}),e.jsx(Nx,{side:"top",className:"w-64 p-3",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"font-semibold",children:"Relationship Score"}),e.jsxs("span",{className:At("font-bold",i.textClass),children:[s.score,"/100"]})]}),e.jsx(Fi,{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 FDn=[{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}],zce=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]},ODn=({open:s,onOpenChange:t,relationshipTypes:n,onSuccess:r})=>{const{user:a}=hs(),{toast:i}=vi(),l=_.useRef(null),[o,c]=_.useState("upload"),[d,u]=_.useState([]),[h,m]=_.useState([]),[p,f]=_.useState({}),[y,v]=_.useState([]),[g,b]=_.useState([]),[j,S]=_.useState([]),[C,E]=_.useState(""),[P,M]=_.useState(!1),[I,D]=_.useState([]),[O,V]=_.useState(!1),[G,$]=_.useState(null);_.useEffect(()=>{!s||!(a!=null&&a.id)||(async()=>{const{data:Pe}=await q.from("contact_custom_tags").select("id, name, color").eq("owner_user_id",a.id).order("name");b(Pe||[])})()},[s,a==null?void 0:a.id]);const H=Pe=>{S(ze=>ze.includes(Pe)?ze.filter(ke=>ke!==Pe):[...ze,Pe])},Y=async()=>{const Pe=C.trim();if(!(!Pe||!(a!=null&&a.id))){M(!0);try{const{data:ze,error:ke}=await q.from("contact_custom_tags").insert({owner_user_id:a.id,name:Pe}).select("id, name, color").single();if(ke)throw ke;ze&&(b(Ze=>[...Ze,ze].sort((Se,Fe)=>Se.name.localeCompare(Fe.name))),S(Ze=>[...Ze,ze.id]),E(""))}catch(ze){i({title:"Could not create tag",description:ze.message||"Try a different name.",variant:"destructive"})}finally{M(!1)}}},Z=()=>{c("upload"),u([]),m([]),f({}),v([]),S([]),E(""),D([]),$(null),l.current&&(l.current.value="")},ne=()=>{Z(),t(!1)},ce=Pe=>{const ze=Pe.split(` `).map(Ye=>Ye.trim()).filter(Ye=>Ye);if(ze.length===0)return{headers:[],data:[]};const ke=Ye=>{const Ve=[];let qe="",Qe=!1;for(let Ue=0;Ue0&&(Ze[0]=Ze[0].replace(/^\uFEFF/,""));const Se=new Map,Fe=Ze.map((Ye,Ve)=>{let qe=(Ye||"").trim();qe||(qe=`Column ${Ve+1}`);const Qe=Se.get(qe)||0;return Se.set(qe,Qe+1),Qe===0?qe:`${qe} (${Qe+1})`}),Ne=ze.slice(1).map(ke);return{headers:Fe,data:Ne}},ie=Pe=>{var Ze;const ze=(Ze=Pe.target.files)==null?void 0:Ze[0];if(!ze)return;const ke=new FileReader;ke.onload=Se=>{var qe;const Fe=(qe=Se.target)==null?void 0:qe.result,{headers:Ne,data:Ye}=ce(Fe);if(Ne.length===0){i({title:"No data found",description:"The CSV file appears to be empty.",variant:"destructive"});return}u(Ne),m(Ye);const Ve={};Ne.forEach(Qe=>{const Ue=Qe.toLowerCase().replace(/[_\s-]/g,"");Ue.includes("firstname")||Ue==="first"?Ve.first_name=Qe:Ue.includes("lastname")||Ue==="last"?Ve.last_name=Qe:Ue.includes("spouse")&&Ue.includes("email")?Ve.spouse_email=Qe:Ue.includes("spouse")||Ue.includes("partner")?Ve.spouse_name=Qe:Ue.includes("email")?Ve.email=Qe:Ue.includes("phone")||Ue.includes("mobile")||Ue.includes("cell")?Ve.phone=Qe:Ue.includes("address")||Ue.includes("street")?Ve.address=Qe:Ue==="city"?Ve.city=Qe:Ue==="state"||Ue==="province"?Ve.state=Qe:Ue==="zip"||Ue==="zipcode"||Ue==="postalcode"?Ve.zip=Qe:Ue.includes("company")||Ue.includes("organization")||Ue.includes("business")?Ve.company_name=Qe:Ue.includes("jobtitle")||Ue.includes("title")&&!Ue.includes("spouse")?Ve.job_title=Qe:Ue.includes("birthday")||Ue.includes("dob")||Ue.includes("birthdate")?Ve.birthday=Qe:Ue.includes("anniversary")||Ue.includes("homeanniversary")?Ve.home_anniversary=Qe:(Ue.includes("notes")||Ue.includes("comment"))&&(Ve.notes=Qe)}),f(Ve),c("mapping")},ke.readAsText(ze)},te=(Pe,ze)=>{f(ke=>{if(ze==="none"){const{[Pe]:Ze,...Se}=ke;return Se}return{...ke,[Pe]:ze}})},ae=Pe=>{v(ze=>ze.includes(Pe)?ze.filter(ke=>ke!==Pe):[...ze,Pe])},le=async()=>{if(!(a!=null&&a.id))return;const{data:Pe}=await q.from("innercircle_contacts").select("id, email, phone").eq("owner_user_id",a.id),ze=new Set((Pe||[]).filter(Se=>Se.email).map(Se=>Se.email.toLowerCase())),ke=new Set((Pe||[]).filter(Se=>Se.phone).map(Se=>Se.phone.replace(/[^0-9]/g,""))),Ze=h.map(Se=>{const Fe=Ue=>{const Xe=p[Ue];if(!Xe)return"";const nt=d.indexOf(Xe);return nt>=0?(Se[nt]||"").trim():""},Ne=Fe("first_name"),Ye=Fe("email"),Ve=Fe("phone"),qe=Ne.length>0,Qe=!!(Ye&&ze.has(Ye.toLowerCase())||Ve&&ke.has(Ve.replace(/[^0-9]/g,"")));return{first_name:Ne,last_name:Fe("last_name"),email:Ye,phone:Ve,address:Fe("address"),city:Fe("city"),state:Fe("state"),zip:Fe("zip"),spouse_name:Fe("spouse_name"),spouse_email:Fe("spouse_email"),company_name:Fe("company_name"),job_title:Fe("job_title"),birthday:Fe("birthday"),home_anniversary:Fe("home_anniversary"),notes:Fe("notes"),isValid:qe,isDuplicate:Qe,error:qe?void 0:"First name is required"}});D(Ze),c("preview")},be=Pe=>{const ze=Pe.trim().split(/\s+/);return{first_name:ze[0],last_name:ze.length>1?ze.slice(1).join(" "):null}},me=async()=>{if(!(a!=null&&a.id))return;const Pe=I.filter(Se=>Se.isValid);if(Pe.length===0){i({title:"No valid contacts",description:"There are no valid contacts to import.",variant:"destructive"});return}V(!0);let ze=0,ke=0,Ze=0;try{for(const Se of Pe)try{let Fe=null;if(Se.email){const{data:Ve}=await q.from("innercircle_contacts").select("id").eq("owner_user_id",a.id).eq("email",Se.email).maybeSingle();Fe=Ve}if(!Fe&&Se.phone){const Ve=Se.phone.replace(/[^0-9]/g,""),{data:qe}=await q.from("innercircle_contacts").select("id, phone").eq("owner_user_id",a.id).not("phone","is",null);if(qe){const Qe=qe.find(Ue=>Ue.phone&&Ue.phone.replace(/[^0-9]/g,"")===Ve);Qe&&(Fe={id:Qe.id})}}const Ne={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:zce(Se.birthday),home_anniversary:zce(Se.home_anniversary),notes:Se.notes||null};let Ye=null;if(Fe){const{data:Ve}=await q.from("innercircle_contacts").select("*").eq("id",Fe.id).single();if(Ve){const qe={},Qe=["last_name","email","phone","address","city","state","zip","spouse_name","spouse_email","company_name","job_title","birthday","home_anniversary","notes"];for(const Ue of Qe){const Xe=Ve[Ue],nt=Ne[Ue];(!Xe||Xe==="")&&nt&&(qe[Ue]=nt)}Object.keys(qe).length>0&&await q.from("innercircle_contacts").update(qe).eq("id",Fe.id)}Ye=Fe.id,ke++}else{const{data:Ve,error:qe}=await q.from("innercircle_contacts").insert(Ne).select("id").single();qe?(console.error("Insert error for contact:",Se.first_name,qe),Ze++):Ve?(Ye=Ve.id,y.length>0&&await q.from("innercircle_contact_tags").insert(y.map(Qe=>({contact_id:Ve.id,relationship_type_id:Qe}))),ze++):Ze++}if(Ye&&j.length>0&&await q.from("contact_custom_tag_assignments").upsert(j.map(Ve=>({contact_id:Ye,tag_id:Ve})),{onConflict:"contact_id,tag_id",ignoreDuplicates:!0}),Ye&&Se.spouse_name){const Ve=be(Se.spouse_name);let qe=null;if(Se.spouse_email){const{data:Ue}=await q.from("innercircle_contacts").select("id").eq("owner_user_id",a.id).eq("email",Se.spouse_email).maybeSingle();qe=Ue}if(!qe){const{data:Ue}=await q.from("innercircle_contacts").select("id").eq("owner_user_id",a.id).eq("first_name",Ve.first_name).eq("last_name",Ve.last_name||Se.last_name||"").maybeSingle();qe=Ue}let Qe=null;if(qe){Qe=qe.id;const Ue=zce(Se.home_anniversary);Ue&&await q.from("innercircle_contacts").update({home_anniversary:Ue}).eq("id",qe.id).is("home_anniversary",null)}else{const{data:Ue}=await q.from("innercircle_contacts").insert({owner_user_id:a.id,first_name:Ve.first_name,last_name:Ve.last_name||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:zce(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&&(Qe=Ue.id,ze++)}Qe&&(await q.from("innercircle_contacts").update({spouse_contact_id:Qe}).eq("id",Ye),await q.from("innercircle_contacts").update({spouse_contact_id:Ye}).eq("id",Qe))}}catch(Fe){console.error("Error importing contact:",Fe),Ze++}$({created:ze,updated:ke,failed:Ze}),c("result"),(ze>0||ke>0)&&r(),i({title:"Import Complete",description:`${ze} created, ${ke} updated${Ze>0?`, ${Ze} failed`:""}.`})}catch(Se){console.error("Import error:",Se),i({title:"Import Failed",description:Se.message||"Failed to import contacts",variant:"destructive"})}finally{V(!1)}},he=I.filter(Pe=>Pe.isValid).length,pe=I.filter(Pe=>!Pe.isValid).length,Ce=I.filter(Pe=>Pe.isValid&&Pe.isDuplicate).length,Ae=he-Ce;return e.jsx(Ls,{open:s,onOpenChange:ne,children:e.jsxs(Ps,{className:"max-w-3xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsxs(Os,{children:[e.jsxs(Ds,{className:"flex items-center gap-2",children:[e.jsx(uS,{className:"h-5 w-5"}),"Import Contacts from CSV"]}),e.jsx(_r,{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:ie,className:"hidden"}),e.jsx(Oa,{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(B,{onClick:()=>{var Pe;return(Pe=l.current)==null?void 0:Pe.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(B,{variant:"outline",size:"sm",onClick:()=>{const Pe=`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([Pe],{type:"text/csv"}),ke=URL.createObjectURL(ze),Ze=document.createElement("a");Ze.href=ke,Ze.download="contact_import_template.csv",Ze.click(),URL.revokeObjectURL(ke)},children:[e.jsx(li,{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(J,{className:"text-base font-medium",children:"Map CSV Columns to Contact Fields"}),e.jsx("div",{className:"grid gap-3",children:FDn.map(Pe=>e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs(J,{className:"w-40 text-sm",children:[Pe.label,Pe.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsxs(is,{value:p[Pe.key]||"none",onValueChange:ze=>te(Pe.key,ze),children:[e.jsx(rs,{className:"w-48",children:e.jsx(ls,{placeholder:"Select column..."})}),e.jsxs(as,{children:[e.jsx(He,{value:"none",children:"-- Not mapped --"}),d.map(ze=>e.jsx(He,{value:ze,children:ze},ze))]})]})]},Pe.key))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(J,{className:"text-base font-medium",children:"Apply Relationship Types (optional)"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:n.map(Pe=>e.jsx(Oe,{variant:y.includes(Pe.id)?"default":"outline",className:"cursor-pointer",onClick:()=>ae(Pe.id),children:Pe.name},Pe.id))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(J,{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."}),g.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:g.map(Pe=>{const ze=j.includes(Pe.id);return e.jsxs(Oe,{variant:ze?"default":"outline",className:"cursor-pointer gap-1",style:ze&&Pe.color?{backgroundColor:Pe.color,borderColor:Pe.color}:void 0,onClick:()=>H(Pe.id),children:[Pe.name,ze&&e.jsx(Qn,{className:"h-3 w-3"})]},Pe.id)})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xe,{placeholder:"Create a new tag (e.g. Open House Oct 2026)",value:C,onChange:Pe=>E(Pe.target.value),onKeyDown:Pe=>{Pe.key==="Enter"&&(Pe.preventDefault(),Y())},className:"max-w-xs"}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:Y,disabled:!C.trim()||P,children:[P?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(rn,{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(Er,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{children:[Ae," new"]})]}),Ce>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:[Ce," existing (will merge gaps)"]})]}),pe>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:[pe," invalid"]})]})]}),Ce>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(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{className:"bg-muted/30",children:[e.jsx(Pt,{children:"First Name"}),e.jsx(Pt,{children:"Last Name"}),e.jsx(Pt,{children:"Email"}),e.jsx(Pt,{children:"Phone"}),e.jsx(Pt,{children:"Status"})]})}),e.jsx(Ka,{children:I.slice(0,100).map((Pe,ze)=>e.jsxs(pn,{children:[e.jsx(gt,{children:Pe.first_name}),e.jsx(gt,{children:Pe.last_name}),e.jsx(gt,{children:Pe.email}),e.jsx(gt,{children:Pe.phone}),e.jsx(gt,{children:Pe.isValid?Pe.isDuplicate?e.jsx(Oe,{variant:"outline",className:"bg-accent text-accent-foreground",children:"Merge"}):e.jsx(Oe,{variant:"secondary",className:"bg-primary/10 text-primary",children:"New"}):e.jsx(Oe,{variant:"destructive",children:Pe.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"&&G&&e.jsxs("div",{className:"space-y-4 py-4 text-center",children:[e.jsx(Er,{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:[G.created," created, ",G.updated," merged"]}),G.failed>0&&e.jsxs("p",{className:"text-destructive",children:[G.failed," failed to import"]})]}),e.jsxs(yr,{children:[o==="upload"&&e.jsx(B,{variant:"outline",onClick:ne,children:"Cancel"}),o==="mapping"&&e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"outline",onClick:Z,children:"Back"}),e.jsx(B,{onClick:le,disabled:!p.first_name,children:"Continue"})]}),o==="preview"&&e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"outline",onClick:()=>c("mapping"),children:"Back"}),e.jsx(B,{onClick:me,disabled:O||he===0,children:O?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}),"Importing..."]}):`Import ${he} Contact${he!==1?"s":""}`})]}),o==="result"&&e.jsx(B,{onClick:ne,children:"Done"})]})]})})};function zDn(){return"contacts"in navigator&&"ContactsManager"in window}function BDn(s){const t=[],n=s.split("BEGIN:VCARD").filter(r=>r.trim());for(const r of n){const a=r.split(/\r?\n/);let i="",l="",o="",c="",d="";for(const u of a){const h=u.replace(/^\s+/,"");if(h.startsWith("N:")||h.startsWith("N;")){const p=h.substring(h.indexOf(":")+1).split(";");l=(p[0]||"").trim(),i=(p[1]||"").trim()}if((h.startsWith("FN:")||h.startsWith("FN;"))&&!i){const p=h.substring(h.indexOf(":")+1).trim().split(" ");i=p[0]||"",l=p.slice(1).join(" ")}(h.startsWith("EMAIL")||h.match(/^item\d+\.EMAIL/i))&&!o&&(o=h.substring(h.indexOf(":")+1).trim()),(h.startsWith("TEL")||h.match(/^item\d+\.TEL/i))&&!c&&(c=h.substring(h.indexOf(":")+1).trim()),(h.startsWith("ADR")||h.match(/^item\d+\.ADR/i))&&!d&&(d=h.substring(h.indexOf(":")+1).split(";").map(f=>f.trim()).filter(Boolean).join(", "))}(i||l)&&t.push({first_name:i,last_name:l,email:o,phone:c,address:d})}return t}function UDn({open:s,onOpenChange:t,onComplete:n}){hs();const{data:r}=Db(),a=iLe(),i=_.useRef(null),[l,o]=_.useState("choose"),[c,d]=_.useState([]),[u,h]=_.useState(new Set),[m,p]=_.useState(0),[f,y]=_.useState(0),v=zDn(),g=_.useCallback(D=>{if(!r)return D;const O=new Set(r.filter(G=>G.email).map(G=>G.email.toLowerCase())),V=new Set(r.filter(G=>G.phone).map(G=>G.phone.replace(/\D/g,"")));return D.map(G=>{var Y,Z;const $=(Y=G.email)==null?void 0:Y.toLowerCase(),H=(Z=G.phone)==null?void 0:Z.replace(/\D/g,"");return $&&O.has($)?{...G,isDuplicate:!0,duplicateField:"email"}:H&&H.length>=7&&V.has(H)?{...G,isDuplicate:!0,duplicateField:"phone"}:G})},[r]),b=async()=>{try{const D=["name","email","tel","address"],O=await navigator.contacts.select(D,{multiple:!0});if(!O||O.length===0)return;const V=O.map(H=>{var ne,ce,ie,te;const Z=(((ne=H.name)==null?void 0:ne[0])||"").split(" ");return{first_name:Z[0]||"",last_name:Z.slice(1).join(" "),email:((ce=H.email)==null?void 0:ce[0])||"",phone:((ie=H.tel)==null?void 0:ie[0])||"",address:(te=H.address)!=null&&te[0]?[H.address[0].streetAddress,H.address[0].city,H.address[0].region,H.address[0].postalCode].filter(Boolean).join(", "):""}}),G=g(V);d(G);const $=new Set;G.forEach((H,Y)=>{H.isDuplicate||$.add(Y)}),h($),o("preview")}catch(D){console.error("Contact Picker error:",D),ia({title:"Could not access contacts",description:"Please try the file upload option instead.",variant:"destructive"})}},j=D=>{var G;const O=(G=D.target.files)==null?void 0:G[0];if(!O)return;const V=new FileReader;V.onload=$=>{var ce;const H=(ce=$.target)==null?void 0:ce.result,Y=BDn(H);if(Y.length===0){ia({title:"No contacts found",description:"The file didn't contain any valid contacts.",variant:"destructive"});return}const Z=g(Y);d(Z);const ne=new Set;Z.forEach((ie,te)=>{ie.isDuplicate||ne.add(te)}),h(ne),o("preview")},V.readAsText(O),i.current&&(i.current.value="")},S=async()=>{const D=c.filter((V,G)=>u.has(G));if(D.length===0)return;o("importing");let O=0;for(const V of D)try{await a.mutateAsync({first_name:V.first_name,last_name:V.last_name||void 0,email:V.email||void 0,phone:V.phone||void 0,address:V.address||void 0}),O++,y(Math.round(O/D.length*100))}catch(G){console.error(`Failed to import ${V.first_name} ${V.last_name}:`,G)}p(O),o("done")},C=D=>{h(O=>{const V=new Set(O);return V.has(D)?V.delete(D):V.add(D),V})},E=()=>{u.size===c.length?h(new Set):h(new Set(c.map((D,O)=>O)))},P=D=>{D||(o("choose"),d([]),h(new Set),p(0),y(0),l==="done"&&n()),t(D)},M=c.filter(D=>D.isDuplicate).length,I=u.size;return e.jsx(Ls,{open:s,onOpenChange:P,children:e.jsxs(Ps,{className:"sm:max-w-lg max-h-[90vh]",children:[e.jsxs(Os,{children:[e.jsxs(Ds,{className:"flex items-center gap-2",children:[e.jsx(p1,{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(_r,{children:"Add contacts from your phone directly into Agent OS."})]}),l==="choose"&&e.jsxs("div",{className:"space-y-4 pt-2",children:[v&&e.jsxs(B,{onClick:b,className:"w-full h-auto py-4 flex flex-col items-center gap-2",children:[e.jsx(p1,{className:"h-6 w-6"}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"font-semibold",children:"Select from Phone"}),e.jsx("div",{className:"text-xs opacity-80",children:"Pick contacts directly from your device"})]})]}),e.jsxs("div",{className:"relative",children:[v&&e.jsx("div",{className:"absolute inset-0 flex items-center",children:e.jsx("span",{className:"w-full border-t"})}),v&&e.jsx("div",{className:"relative flex justify-center text-xs uppercase",children:e.jsx("span",{className:"bg-background px-2 text-muted-foreground",children:"or"})})]}),e.jsxs(B,{variant:v?"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(Oa,{className:"h-6 w-6"}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"font-semibold",children:"Upload Contact File"}),e.jsx("div",{className:"text-xs opacity-80",children:v?"Import a .vcf file exported from your Contacts app":"Export contacts from your phone as a .vcf file, then upload here"})]})]}),e.jsx("input",{ref:i,type:"file",accept:".vcf,.vcard",onChange:j,className:"hidden"}),!v&&e.jsxs("div",{className:"rounded-lg bg-muted p-3 text-sm text-muted-foreground space-y-2",children:[e.jsx("p",{className:"font-medium",children:"How to export contacts:"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-xs",children:"iPhone:"}),e.jsx("p",{className:"text-xs",children:'Open Contacts → select contacts → Share → choose "Export vCard"'})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-xs",children:"Android:"}),e.jsx("p",{className:"text-xs",children:"Open Contacts → Menu → Export → save as .vcf file"})]})]})]}),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(B,{variant:"ghost",size:"sm",onClick:E,children:u.size===c.length?"Deselect All":"Select All"})]}),e.jsx(Ji,{className:"h-[350px] rounded-md border",children:e.jsx("div",{className:"divide-y",children:c.map((D,O)=>e.jsxs("div",{className:`flex items-start gap-3 p-3 cursor-pointer hover:bg-accent/50 transition-colors ${D.isDuplicate?"opacity-60":""}`,onClick:()=>C(O),children:[e.jsx($a,{checked:u.has(O),onCheckedChange:()=>C(O),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(Oe,{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})]})]})]},O))})}),e.jsxs("div",{className:"flex items-center justify-between pt-2",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>o("choose"),children:"Back"}),e.jsxs(B,{onClick:S,disabled:I===0,children:["Import ",I," Contact",I!==1?"s":""]})]})]}),l==="importing"&&e.jsxs("div",{className:"flex flex-col items-center gap-4 py-8",children:[e.jsx(Ct,{className:"h-8 w-8 animate-spin text-primary"}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"font-medium",children:"Importing contacts..."}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[f,"% complete"]})]}),e.jsx("div",{className:"w-full bg-muted rounded-full h-2",children:e.jsx("div",{className:"bg-primary h-2 rounded-full transition-all",style:{width:`${f}%`}})})]}),l==="done"&&e.jsxs("div",{className:"flex flex-col items-center gap-4 py-8",children:[e.jsx("div",{className:"h-12 w-12 rounded-full bg-emerald-500/10 flex items-center justify-center",children:e.jsx(ea,{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(B,{onClick:()=>P(!1),className:"mt-2",children:"Done"})]})]})})}function qDn(s){return at({queryKey:["video-share-recipients",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("video_share_recipients").select("*").eq("video_id",s).order("sent_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function $Dn(){const{user:s}=hs();return at({queryKey:["video-share-stats",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return null;const{data:t,error:n}=await q.from("video_share_recipients").select("*").eq("owner_user_id",s.id);if(n)throw n;const r=t;return{totalSent:r.length,totalOpened:r.filter(a=>a.opened_at).length,totalClicked:r.filter(a=>a.clicked_at).length,totalWatched:r.filter(a=>a.watched_at).length,openRate:r.length>0?Math.round(r.filter(a=>a.opened_at).length/r.length*100):0,clickRate:r.length>0?Math.round(r.filter(a=>a.clicked_at).length/r.length*100):0,watchRate:r.length>0?Math.round(r.filter(a=>a.watched_at).length/r.length*100):0}},enabled:!!(s!=null&&s.id)})}function VDn(){const{user:s}=hs();return at({queryKey:["video-share-history",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return[];const{data:t,error:n}=await q.from("video_share_recipients").select(` *, agent_videos!inner(id, title, thumbnail_url, share_token, duration_seconds) `).eq("owner_user_id",s.id).order("sent_at",{ascending:!1}).limit(200);if(n)throw n;return t},enabled:!!(s!=null&&s.id)})}function wYt(){const{user:s}=hs(),t=Bt();return mt({mutationFn:async n=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:r,error:a}=await q.from("video_share_recipients").insert([{video_id:n.video_id,owner_user_id:s.id,recipient_email:n.recipient_email,recipient_name:n.recipient_name||null,contact_id:n.contact_id||null,sent_via:n.sent_via||"gmail",share_token:"placeholder"}]).select().single();if(a)throw a;return r},onSuccess:n=>{t.invalidateQueries({queryKey:["video-share-recipients",n.video_id]}),t.invalidateQueries({queryKey:["video-share-stats"]}),t.invalidateQueries({queryKey:["video-share-history"]})}})}function jYt(s){return`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/track-video-share?t=${s}&e=open`}function NYt(s){return`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/track-video-share?t=${s}&e=click`}const HDn=100;function GDn({open:s,onOpenChange:t,contacts:n,isGmailConnected:r,isMassEmailReady:a,onSendComplete:i}){const l=Fn(),o=ha(),c=wYt(),[d,u]=_.useState([]),[h,m]=_.useState(!1),[p,f]=_.useState(""),[y,v]=_.useState(null),[g,b]=_.useState(""),[j,S]=_.useState(""),[C,E]=_.useState(!1),[P,M]=_.useState({done:0,total:0,failed:0}),I=n.filter(Z=>!!Z.email),D=n.length-I.length,O=I.length>HDn;_.useEffect(()=>{s&&(v(null),f(""),M({done:0,total:0,failed:0}))},[s]),_.useEffect(()=>{!s||!o||(m(!0),q.from("agent_videos").select("id, title, share_token, thumbnail_url, playback_url, duration_seconds, created_at").eq("owner_user_id",o).eq("is_deleted",!1).eq("status","ready").order("created_at",{ascending:!1}).limit(50).then(({data:Z})=>{u(Z||[]),m(!1)}))},[s,o]),_.useEffect(()=>{if(!y)return;const Z=y.title||"a quick video";b(`I recorded a video for you — ${Z}`),S("Hey {{first_name}}! I recorded a quick video just for you. Click below to watch it:")},[y]);const V=d.filter(Z=>!p||(Z.title||"").toLowerCase().includes(p.toLowerCase())),G=(Z,ne)=>{if(!y)return"";const ce=y.share_token?`https://video.relevelup.com/share/video/${y.share_token}`:"",ie=y.share_token?`https://video.relevelup.com/thumb/${y.share_token}`:y.thumbnail_url||"",te=y.title||"Video Message",le=j.replace(/\{\{first_name\}\}/gi,Z).split(/\n\n+/).map(he=>`

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

`).join(""),be=ne?NYt(ne):ce,me=ne?``:"";return`
${le}

▶ Watch Video

${me}
`},$=async()=>{if(!y)return;E(!0),M({done:0,total:I.length,failed:0});let Z=0,ne=0;for(const ce of I)try{let ie;try{ie=(await c.mutateAsync({video_id:y.id,recipient_email:ce.email,recipient_name:`${ce.first_name} ${ce.last_name||""}`.trim(),contact_id:ce.id,sent_via:"gmail"})).share_token}catch(me){console.warn("Tracking record failed for",ce.email,me)}const te=G(ce.first_name,ie),ae=g.replace(/\{\{first_name\}\}/gi,ce.first_name),{data:le,error:be}=await q.functions.invoke("gmail-send",{body:{to:ce.email,subject:ae,body:te,contactId:ce.id}});if(be||!(le!=null&&le.success))throw new Error((le==null?void 0:le.error)||(be==null?void 0:be.message)||"Send failed");Z+=1}catch(ie){console.error("Failed to send to",ce.email,ie),ne+=1}finally{M({done:Z+ne,total:I.length,failed:ne}),await new Promise(ie=>setTimeout(ie,250))}E(!1),ne===0?se.success(`Video sent to ${Z} ${Z===1?"contact":"contacts"}!`):se.warning(`Sent to ${Z}, ${ne} failed. Check console for details.`),t(!1),i==null||i()},H=()=>{if(!y)return;const Z=G("there",void 0);l("/admin/email-campaigns/new",{state:{directRecipients:I.map(ne=>({email:ne.email,name:`${ne.first_name} ${ne.last_name||""}`.trim()})),initialSubject:g,initialBodyHtml:Z}}),t(!1)},Y=!!y&&!!g.trim()&&I.length>0&&(O?a:r);return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"sm:max-w-[640px] max-h-[90vh] overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsxs(Ds,{className:"flex items-center gap-2",children:[e.jsx(Kr,{className:"h-5 w-5 text-primary"}),"Send Video to ",I.length," ",I.length===1?"Contact":"Contacts"]}),e.jsxs(_r,{children:[O?e.jsxs("span",{className:"flex items-center gap-1.5 text-amber-600",children:[e.jsx(wh,{className:"h-3.5 w-3.5"}),I.length," recipients — will be sent as a Mass Email campaign"]}):e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(ln,{className:"h-3.5 w-3.5"}),"Sent individually via your connected Gmail"]}),D>0&&e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",D," skipped — no email)"]})]})]}),e.jsxs("div",{className:"space-y-4",children:[O&&!a&&e.jsxs("div",{className:"flex items-start gap-2 p-3 rounded-md bg-destructive/10 text-destructive text-sm",children:[e.jsx(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."]})]}),!O&&!r&&e.jsxs("div",{className:"flex items-start gap-2 p-3 rounded-md bg-destructive/10 text-destructive text-sm",children:[e.jsx(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(J,{children:"Choose a video"}),e.jsxs(B,{type:"button",variant:"ghost",size:"sm",className:"gap-1",onClick:()=>l("/innercircle/videos/record"),children:[e.jsx(rn,{className:"h-3.5 w-3.5"})," Record new"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search your video library...",value:p,onChange:Z=>f(Z.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(cn,{className:"h-14 w-full"}),e.jsx(cn,{className:"h-14 w-full"})]}):V.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."}):V.map(Z=>{const ne=(y==null?void 0:y.id)===Z.id;return e.jsxs("button",{type:"button",onClick:()=>v(Z),className:`w-full flex items-center gap-3 p-2 rounded-md border text-left transition-colors ${ne?"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:[Z.thumbnail_url?e.jsx("img",{src:Z.thumbnail_url,alt:"",className:"w-full h-full object-cover",referrerPolicy:"no-referrer"}):e.jsx(dm,{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(Jd,{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:Z.title||"Untitled Video"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Z.duration_seconds?`${Math.round(Z.duration_seconds)}s`:"",Z.created_at?` · ${new Date(Z.created_at).toLocaleDateString()}`:""]})]})]},Z.id)})})]}),e.jsx(wc,{}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{htmlFor:"bulk-video-subject",children:"Subject"}),e.jsx(xe,{id:"bulk-video-subject",value:g,onChange:Z=>b(Z.target.value),placeholder:"I recorded a video for you"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(J,{htmlFor:"bulk-video-message",children:["Personal message ",e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(use ","{{first_name}}"," to personalize)"]})]}),e.jsx(Ms,{id:"bulk-video-message",value:j,onChange:Z=>S(Z.target.value),rows:4,className:"resize-y"})]}),C&&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(B,{variant:"outline",onClick:()=>t(!1),disabled:C,children:"Cancel"}),O?e.jsxs(B,{onClick:H,disabled:!Y,className:"gap-2",children:[e.jsx(wh,{className:"h-4 w-4"}),"Continue in Mass Email"]}):e.jsxs(B,{onClick:$,disabled:!Y||C,className:"gap-2",children:[C?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Or,{className:"h-4 w-4"}),C?"Sending…":`Send to ${I.length}`]})]})]})]})})}function Dae(){const s=ha();return at({queryKey:["drip-campaigns",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("drip_campaigns").select("*").or(`owner_user_id.eq.${s},is_starter.eq.true`).order("is_starter",{ascending:!1}).order("sort_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function WDn(s){return at({queryKey:["drip-campaign",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("drip_campaigns").select("*").eq("id",s).maybeSingle();if(n)throw n;return t},enabled:!!s})}function KDn(){const s=ha(),t=Bt();return mt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("drip_campaigns").insert({owner_user_id:s,name:n.name,description:n.description??null,category:n.category??"nurture",icon:n.icon??"🌱",cover_color:n.cover_color??"from-emerald-500 to-teal-600",goal:n.goal??null,is_active:!1}).select().single();if(a)throw a;return r},onSuccess:()=>t.invalidateQueries({queryKey:["drip-campaigns"]})})}function kYt(){const s=Bt();return mt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("drip_campaigns").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["drip-campaigns"]}),s.invalidateQueries({queryKey:["drip-campaign",n.id]})}})}function YDn(){const s=Bt();return mt({mutationFn:async t=>{const{error:n}=await q.from("drip_campaigns").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["drip-campaigns"]})})}function wnt(){const s=ha(),t=Bt();return mt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const[{data:r,error:a},{data:i,error:l}]=await Promise.all([q.from("drip_campaigns").select("*").eq("id",n).single(),q.from("drip_campaign_steps").select("*").eq("campaign_id",n).order("step_order")]);if(a)throw a;if(l)throw l;const{data:o,error:c}=await q.from("drip_campaigns").insert({owner_user_id:s,name:r.name,description:r.description,category:r.category,icon:r.icon,cover_color:r.cover_color,goal:r.goal,is_active:!1,is_starter:!1}).select().single();if(c)throw c;if(i&&i.length>0){const d=i.map(h=>({campaign_id:o.id,step_order:h.step_order,channel:h.channel,subject:h.subject,body:h.body,video_url:h.video_url,delay_type:h.delay_type,delay_days:h.delay_days,delay_hours:h.delay_hours,anchor_field:h.anchor_field,anchor_offset_days:h.anchor_offset_days,send_window_start:h.send_window_start,send_window_end:h.send_window_end})),{error:u}=await q.from("drip_campaign_steps").insert(d);if(u)throw u}return o},onSuccess:()=>t.invalidateQueries({queryKey:["drip-campaigns"]})})}function SYt(s){return at({queryKey:["drip-campaign-steps",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("drip_campaign_steps").select("*").eq("campaign_id",s).order("step_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function ZDn(){const s=Bt();return mt({mutationFn:async t=>{const{data:n,error:r}=await q.from("drip_campaign_steps").insert({campaign_id:t.campaign_id,step_order:t.step_order,channel:t.channel??"email",subject:t.subject??"",body:t.body??"",video_url:t.video_url??null,delay_type:t.delay_type??"relative",delay_days:t.delay_days??0,delay_hours:t.delay_hours??0,anchor_field:t.anchor_field??null,anchor_offset_days:t.anchor_offset_days??0}).select().single();if(r)throw r;return n},onSuccess:(t,n)=>s.invalidateQueries({queryKey:["drip-campaign-steps",n.campaign_id]})})}function XDn(){const s=Bt();return mt({mutationFn:async({id:t,campaign_id:n,...r})=>{const{data:a,error:i}=await q.from("drip_campaign_steps").update(r).eq("id",t).select().single();if(i)throw i;return{data:a,campaign_id:n}},onSuccess:t=>s.invalidateQueries({queryKey:["drip-campaign-steps",t.campaign_id]})})}function QDn(){const s=Bt();return mt({mutationFn:async({id:t,campaign_id:n})=>{const{error:r}=await q.from("drip_campaign_steps").delete().eq("id",t);if(r)throw r;return n},onSuccess:t=>s.invalidateQueries({queryKey:["drip-campaign-steps",t]})})}function JDn(s){return at({queryKey:["campaign-enrollments",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("drip_campaign_enrollments").select("*, contact:innercircle_contacts(id, first_name, last_name, email)").eq("campaign_id",s).order("enrolled_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function eRn(s){return at({queryKey:["campaign-enrollment-count",s],queryFn:async()=>{if(!s)return 0;const{count:t,error:n}=await q.from("drip_campaign_enrollments").select("id",{count:"exact",head:!0}).eq("campaign_id",s).eq("status","active");if(n)throw n;return t??0},enabled:!!s,staleTime:3e4})}function jnt(){const s=Bt();return mt({mutationFn:async({campaignId:t,contactIds:n})=>{const{data:r,error:a}=await q.functions.invoke("enroll-contacts-in-campaign",{body:{campaign_id:t,contact_ids:n}});if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["campaign-enrollments"]}),s.invalidateQueries({queryKey:["contact-campaigns"]})}})}function tRn(){const s=Bt();return mt({mutationFn:async({id:t,status:n})=>{const r={status:n};n==="paused"&&(r.paused_at=new Date().toISOString()),n==="exited"&&(r.exited_at=new Date().toISOString(),r.exit_reason="manual");const{data:a,error:i}=await q.from("drip_campaign_enrollments").update(r).eq("id",t).select().single();if(i)throw i;return a},onSuccess:()=>{s.invalidateQueries({queryKey:["campaign-enrollments"]}),s.invalidateQueries({queryKey:["contact-campaigns"]})}})}const sRn=[{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"}],ZIe={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"},nRn={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 rRn({open:s,onOpenChange:t,subject:n,body:r,ownerUserId:a,stepLabel:i}){const[l,o]=_.useState(!1),[c,d]=_.useState(""),[u,h]=_.useState(""),[m,p]=_.useState("desktop"),[f,y]=_.useState(""),[v,g]=_.useState(!1);_.useEffect(()=>{if(!s)return;let j=!1;return(async()=>{var S,C;o(!0);try{const{data:E}=await q.auth.getSession();f||y(((C=(S=E==null?void 0:E.session)==null?void 0:S.user)==null?void 0:C.email)||"");const{data:P,error:M}=await q.functions.invoke("process-drip-campaigns",{body:{action:"preview",subject:n,body:r,owner_user_id:a||void 0}});if(M)throw M;if(j)return;d((P==null?void 0:P.html)||""),h((P==null?void 0:P.subject)||n)}catch{j||se.error("Could not build preview")}finally{j||o(!1)}})(),()=>{j=!0}},[s,n,r,a]);const b=async()=>{if(f.trim()){g(!0);try{const{data:j,error:S}=await q.functions.invoke("process-drip-campaigns",{body:{action:"test_send",subject:n,body:r,to:f.trim(),owner_user_id:a||void 0}});if(S)throw S;j!=null&&j.success?se.success(`Test email sent to ${f.trim()}`):se.error((j==null?void 0:j.error)||"Could not send test email",{duration:1e4})}catch{se.error("Could not send test email")}finally{g(!1)}}};return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"sm:max-w-3xl max-h-[92vh] flex flex-col p-0 gap-0",children:[e.jsxs(Os,{className:"p-5 pb-3 border-b shrink-0",children:[e.jsxs(Ds,{children:["Email preview",i?` — ${i}`:""]}),e.jsx(_r,{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(B,{variant:m==="desktop"?"secondary":"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>p("desktop"),children:[e.jsx(hN,{className:"h-3.5 w-3.5 mr-1"})," Desktop"]}),e.jsxs(B,{variant:m==="mobile"?"secondary":"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>p("mobile"),children:[e.jsx(p1,{className:"h-3.5 w-3.5 mr-1"})," Mobile"]})]})]}),e.jsx("div",{className:"flex-1 overflow-y-auto overscroll-contain bg-muted/30 p-4 min-h-0",children:l?e.jsxs("div",{className:"flex items-center justify-center py-16 text-sm text-muted-foreground",children:[e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"})," Building preview…"]}):e.jsx("div",{className:"mx-auto bg-background rounded-lg overflow-hidden border",style:{maxWidth:m==="mobile"?390:"100%"},children:e.jsx("iframe",{title:"Email preview",srcDoc:c,sandbox:"",className:"w-full",style:{height:620,border:0,background:"#fff"}})})}),e.jsxs("div",{className:"border-t p-4 shrink-0 flex flex-col sm:flex-row sm:items-end gap-3",children:[e.jsxs("div",{className:"flex-1 space-y-1.5",children:[e.jsx(J,{className:"text-xs",children:"Send a test to"}),e.jsx(xe,{type:"email",value:f,onChange:j=>y(j.target.value),placeholder:"you@email.com",className:"h-9",onKeyDown:j=>j.key==="Enter"&&b()})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Close"}),e.jsxs(B,{onClick:b,disabled:v||!f.trim(),children:[v?e.jsx(Ct,{className:"h-4 w-4 mr-1.5 animate-spin"}):e.jsx(Or,{className:"h-4 w-4 mr-1.5"}),"Send test"]})]})]})]})})}function iz({userId:s,onSelect:t,onSelectVideo:n,triggerLabel:r="Library",triggerSize:a="sm",triggerVariant:i="outline",triggerClassName:l}){const[o,c]=_.useState(!1),[d,u]=_.useState([]),[h,m]=_.useState(!1),[p,f]=_.useState("");_.useEffect(()=>{!o||!s||(m(!0),q.from("agent_videos").select("id, title, recipient_name, playback_url, thumbnail_url, created_at, duration_seconds").eq("owner_user_id",s).eq("is_deleted",!1).eq("status","ready").order("created_at",{ascending:!1}).limit(50).then(({data:v})=>{u(v||[]),m(!1)}))},[o,s]);const y=d.filter(v=>!p||(v.title||v.recipient_name||"").toLowerCase().includes(p.toLowerCase()));return e.jsxs(Ls,{open:o,onOpenChange:c,children:[e.jsx(nl,{asChild:!0,children:e.jsxs(B,{variant:i,size:a,className:l||"gap-1.5 shrink-0",children:[e.jsx(dm,{className:"h-3.5 w-3.5"}),r]})}),e.jsxs(Ps,{className:"max-w-lg max-h-[70vh] flex flex-col",children:[e.jsxs(Os,{children:[e.jsx(Ds,{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(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search videos...",value:p,onChange:v=>f(v.target.value),className:"pl-10"})]}),e.jsx("div",{className:"flex-1 overflow-y-auto space-y-2 min-h-0",children:h?e.jsxs(e.Fragment,{children:[e.jsx(cn,{className:"h-16 w-full"}),e.jsx(cn,{className:"h-16 w-full"})]}):y.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"}):y.map(v=>e.jsxs("button",{onClick:()=>{t(v.playback_url||""),n==null||n(v),c(!1)},className:"w-full flex items-center gap-3 p-3 rounded-lg border border-border hover:border-primary/50 hover:bg-accent/50 transition-colors text-left",children:[e.jsx("div",{className:"w-16 h-10 rounded bg-muted flex items-center justify-center shrink-0 overflow-hidden",children:v.thumbnail_url?e.jsx("img",{src:v.thumbnail_url,alt:"",className:"w-full h-full object-cover",referrerPolicy:"no-referrer",onError:g=>{const b=g.currentTarget.parentElement;if(b){g.currentTarget.remove();const j=document.createElement("span");j.innerHTML="🎬",j.className="text-lg",b.appendChild(j)}}}):e.jsx(Kr,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:v.title||v.recipient_name||"Untitled Video"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[v.duration_seconds?`${Math.round(v.duration_seconds)}s`:"",v.created_at?` · ${new Date(v.created_at).toLocaleDateString()}`:""]})]})]},v.id))})]})]})}function aRn(){return at({queryKey:["video-script-categories"],queryFn:async()=>{const{data:s,error:t}=await q.from("video_script_categories").select("*").order("sort_order");if(t)throw t;return s}})}function iRn(s){return at({queryKey:["video-scripts",s],queryFn:async()=>{let t=q.from("video_scripts").select("*, category:video_script_categories(*)").eq("is_active",!0).order("title");const{data:n,error:r}=await t;if(r)throw r;return n}})}function oRn(){const{user:s}=hs();return at({queryKey:["user-video-scripts",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return[];const{data:t,error:n}=await q.from("user_video_scripts").select("*, category:video_script_categories(*)").eq("owner_user_id",s.id).order("title");if(n)throw n;return t},enabled:!!(s!=null&&s.id)})}function lRn(){const{user:s}=hs(),t=Bt();return mt({mutationFn:async n=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:r,error:a}=await q.from("user_video_scripts").insert([{owner_user_id:s.id,source_script_id:n.id,category_id:n.category_id,title:n.title,script_text:n.script_text,tags:n.tags,is_custom:!1}]).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["user-video-scripts"]})}})}function cRn(s){const{user:t}=hs();return at({queryKey:["agent-videos",t==null?void 0:t.id,s],queryFn:async()=>{if(!(t!=null&&t.id))return[];let n=q.from("agent_videos").select("*, contact:innercircle_contacts(id, first_name, last_name)").eq("owner_user_id",t.id).order("created_at",{ascending:!1});n=n.eq("is_deleted",!1);const{data:r,error:a}=await n;if(a)throw a;return r},enabled:!!(t!=null&&t.id)})}function dRn(s){return at({queryKey:["agent-video",s],queryFn:async()=>{const{data:t,error:n}=await q.from("agent_videos").select("*, contact:innercircle_contacts(id, first_name, last_name)").eq("id",s).single();if(n)throw n;return t},enabled:!!s})}function TC(){const{user:s}=hs(),t=Bt();return mt({mutationFn:async n=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:r,error:a}=await q.from("agent_videos").insert([{owner_user_id:s.id,contact_id:n.contact_id,bunny_video_id:n.bunny_video_id,playback_url:n.playback_url,thumbnail_url:n.thumbnail_url,preview_url:n.preview_url,duration_seconds:n.duration_seconds,file_size_mb:n.file_size_mb||0,title:n.title,notes:n.notes,task_id:n.task_id,status:n.status||"processing",touch_type:n.touch_type||"video",page_template:"default",category:n.category||"general"}]).select("*, share_token").single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["agent-videos"]}),t.invalidateQueries({queryKey:["storage-usage"]})}})}function uRn(){const s=Bt();return mt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("agent_videos").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["agent-videos"]}),s.invalidateQueries({queryKey:["agent-video",t.id]})}})}function hRn(){const s=Bt();return mt({mutationFn:async({id:t,bunnyVideoId:n,hardDelete:r=!1})=>{if(console.log("Deleting video:",{id:t,bunnyVideoId:n,hardDelete:r}),n){console.log("Calling bunny-upload delete for videoId:",n);const{data:a,error:i}=await q.functions.invoke("bunny-upload",{body:{action:"delete",videoId:n,isAgentVideo:!0}});i?console.error("Failed to delete from Bunny:",i):console.log("Bunny delete response:",a)}else console.warn("No bunnyVideoId provided, skipping Bunny.net deletion");if(r){console.log("Hard deleting from database:",t);const{error:a}=await q.from("agent_videos").delete().eq("id",t);if(a)throw a}else{console.log("Soft deleting from database:",t);const{error:a}=await q.from("agent_videos").update({is_deleted:!0}).eq("id",t);if(a)throw a}console.log("Video deletion complete")},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-videos"]}),s.invalidateQueries({queryKey:["storage-usage"]})}})}function XIe(){const{user:s}=hs();return at({queryKey:["storage-usage",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return null;const{data:t,error:n}=await q.from("agent_storage_usage").select("*").eq("user_id",s.id).maybeSingle();if(n)throw n;return t||{user_id:s.id,total_storage_mb:0,storage_tier:"basic",max_storage_mb:1024}},enabled:!!(s!=null&&s.id)})}function CYt(){const{data:s,isLoading:t}=XIe(),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 PL(s){const{data:t,error:n}=await q.functions.invoke("bunny-upload",{body:{action:"create",title:s,isAgentVideo:!0}});if(n)throw n;return t}async function LL(s){const{data:t,error:n}=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:s,isAgentVideo:!0}});if(n)throw n;return t}async function TN(s){const{data:t,error:n}=await q.functions.invoke("bunny-upload",{body:{action:"status",videoId:s,isAgentVideo:!0}});if(n)throw n;return t}function mRn(){const{user:s}=hs(),t=Bt();return mt({mutationFn:async({contactId:n,videoId:r,notes:a})=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:i}=await q.from("action_types").select("id").eq("name","Video").single();if(!i)throw new Error("Video action type not found");const{data:l,error:o}=await q.from("contact_touch_logs").insert([{owner_user_id:s.id,contact_id:n,action_type_id:i.id,notes:a||`Quick Video Touch - Video ID: ${r}`}]).select().single();if(o)throw o;return l},onSuccess:()=>{t.invalidateQueries({queryKey:["contact-touch-logs"]}),t.invalidateQueries({queryKey:["contacts"]})}})}function AYt({open:s,onOpenChange:t,onUploadComplete:n}){const{data:r}=Db(),{data:a}=XIe(),i=TC(),l=_.useRef(null),[o,c]=_.useState(null),[d,u]=_.useState(""),[h,m]=_.useState(""),[p,f]=_.useState(""),[y,v]=_.useState(!1),[g,b]=_.useState(0),[j,S]=_.useState("idle"),C=(a==null?void 0:a.total_storage_mb)||0,P=((a==null?void 0:a.max_storage_mb)||1024)-C,M=V=>{var H;const G=(H=V.target.files)==null?void 0:H[0];if(!G)return;if(!G.type.startsWith("video/")){se.error("Please select a video file");return}const $=G.size/(1024*1024);if($>500){se.error("Video file must be less than 500MB");return}if($>P){se.error(`Not enough storage. You have ${P.toFixed(1)} MB remaining.`);return}c(G),d||u(G.name.replace(/\.[^/.]+$/,""))},I=async()=>{if(!o){se.error("Please select a video file");return}v(!0),b(0),S("creating");try{const{data:V,error:G}=await q.functions.invoke("bunny-upload",{body:{action:"create",title:d||o.name,isAgentVideo:!0}});if(G)throw new Error(G.message);const{videoId:$,libraryId:H}=V;S("uploading");const{data:Y,error:Z}=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:$,isAgentVideo:!0}});if(Z)throw new Error(Z.message);await new Promise((ie,te)=>{const ae=new XMLHttpRequest;ae.upload.addEventListener("progress",le=>{if(le.lengthComputable){const be=Math.round(le.loaded/le.total*100);b(be)}}),ae.addEventListener("load",()=>{ae.status>=200&&ae.status<300?ie():te(new Error(`Upload failed with status ${ae.status}`))}),ae.addEventListener("error",()=>te(new Error("Upload failed"))),ae.open("PUT",Y.uploadUrl),ae.setRequestHeader("AccessKey",Y.apiKey),ae.send(o)}),S("processing");const ne=o.size/(1024*1024),ce=`https://iframe.mediadelivery.net/embed/${H}/${$}`;await i.mutateAsync({bunny_video_id:$,playback_url:ce,file_size_mb:ne,title:d||o.name,notes:h||void 0,contact_id:p||void 0,status:"processing",touch_type:"video_upload"}),se.success("Video uploaded successfully! Processing may take a few minutes."),n==null||n(ce),D()}catch(V){console.error("Upload error:",V),se.error(V instanceof Error?V.message:"Failed to upload video")}finally{v(!1),S("idle")}},D=()=>{y||(c(null),u(""),m(""),f(""),b(0),S("idle"),t(!1))},O=()=>{switch(j){case"creating":return"Preparing upload...";case"uploading":return`Uploading... ${g}%`;case"processing":return"Saving video...";default:return""}};return e.jsx(Ls,{open:s,onOpenChange:D,children:e.jsxs(Ps,{className:"sm:max-w-md",children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Upload Video"}),e.jsx(_r,{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(J,{children:"Video File"}),o?e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-muted rounded-lg",children:[e.jsx(Kr,{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"]})]}),!y&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:V=>{V.stopPropagation(),c(null)},children:e.jsx(Qn,{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 V;return(V=l.current)==null?void 0:V.click()},children:[e.jsx(Oa,{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:y})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"title",children:"Title"}),e.jsx(xe,{id:"title",value:d,onChange:V=>u(V.target.value),placeholder:"Enter video title",disabled:y})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Associate with Contact (optional)"}),e.jsxs(is,{value:p||"__none__",onValueChange:V=>f(V==="__none__"?"":V),disabled:y,children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Select a contact"})}),e.jsxs(as,{children:[e.jsx(He,{value:"__none__",children:"No contact"}),r==null?void 0:r.map(V=>e.jsxs(He,{value:V.id,children:[V.first_name," ",V.last_name||""]},V.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"notes",children:"Notes (optional)"}),e.jsx(Ms,{id:"notes",value:h,onChange:V=>m(V.target.value),placeholder:"Add any notes about this video",rows:2,disabled:y})]}),y&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Ct,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{children:O()})]}),e.jsx(Fi,{value:j==="uploading"?g:j==="processing"?100:10})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:D,disabled:y,children:"Cancel"}),e.jsx(B,{onClick:I,disabled:!o||y,children:y?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Oa,{className:"h-4 w-4 mr-2"}),"Upload Video"]})})]})]})})}const pRn=["🌱","💎","🏠","🔑","📧","💌","🎂","🥂","🤝","⭐","🎉","📞"],fRn={" ":" ","&":"&","<":"<",">":">",""":'"',"'":"'"},r2t=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=>fRn[t.toLowerCase()]||t).replace(/\n{3,}/g,` `).replace(/[ \t]+\n/g,` `).trim():s:"";function EYt({open:s,onOpenChange:t,campaignId:n}){const[r,a]=_.useState(n??null),[i,l]=_.useState("details");_.useEffect(()=>{a(n??null),l("details")},[n,s]);const o=r,c=!!o,{data:d}=WDn(o||void 0),{data:u,isLoading:h}=SYt(o||void 0),m=KDn(),p=kYt(),f=ZDn(),[y,v]=_.useState(""),[g,b]=_.useState(""),[j,S]=_.useState("nurture"),[C,E]=_.useState("🌱"),[P,M]=_.useState("");_.useEffect(()=>{d?(v(d.name),b(d.description||""),S(d.category),E(d.icon),M(d.goal||"")):c||(v(""),b(""),S("nurture"),E("🌱"),M(""))},[d,c,s]);const I=nRn[j],D=async()=>{if(!y.trim()){se.error("Give your campaign a name");return}try{if(c&&o)await p.mutateAsync({id:o,name:y,description:g,category:j,icon:C,goal:P,cover_color:I}),se.success("Campaign updated");else{const V=await m.mutateAsync({name:y,description:g,category:j,icon:C,goal:P,cover_color:I});return se.success("Campaign created — now add your first step!"),a(V.id),l("steps"),V}}catch(V){se.error(V.message||"Failed to save")}},O=async()=>{if(!o){se.error("Save the campaign first, then add steps");return}const V=((u==null?void 0:u.length)||0)+1;try{await f.mutateAsync({campaign_id:o,step_order:V,channel:"email",subject:"",body:"",delay_type:"relative",delay_days:V===1?0:2,delay_hours:0})}catch{se.error("Failed to add step")}};return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{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:C}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(Ds,{className:"text-lg font-bold text-white",children:c?"Edit Campaign":"Create New Campaign"}),e.jsx(_r,{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(Yr,{value:i,onValueChange:V=>l(V),className:"flex-1 flex flex-col overflow-hidden min-h-0",children:[e.jsxs(Zr,{className:"mx-5 mt-4 grid grid-cols-2 w-fit",children:[e.jsx(Ht,{value:"details",children:"Details"}),e.jsxs(Ht,{value:"steps",disabled:!c,children:["Steps ",u&&u.length>0&&e.jsx(Oe,{variant:"secondary",className:"ml-1.5 text-[10px]",children:u.length})]})]}),e.jsx(Gt,{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(J,{className:"text-xs",children:"Campaign Name *"}),e.jsx(xe,{value:y,onChange:V=>v(V.target.value),placeholder:"e.g. New Buyer Lead — 7 Touch Nurture",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Description"}),e.jsx(Ms,{value:g,onChange:V=>b(V.target.value),placeholder:"What's this campaign for? When should you use it?",rows:2,className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Goal (optional)"}),e.jsx(xe,{value:P,onChange:V=>M(V.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(J,{className:"text-xs",children:"Category"}),e.jsxs(is,{value:j,onValueChange:V=>S(V),children:[e.jsx(rs,{className:"mt-1",children:e.jsx(ls,{})}),e.jsx(as,{children:Object.entries(ZIe).map(([V,G])=>e.jsx(He,{value:V,children:G},V))})]})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Icon"}),e.jsx("div",{className:"flex gap-1.5 flex-wrap mt-1",children:pRn.map(V=>e.jsx("button",{type:"button",onClick:()=>E(V),className:`h-8 w-8 rounded-md text-lg flex items-center justify-center transition-all ${C===V?"bg-primary/15 ring-2 ring-primary":"hover:bg-muted"}`,children:V},V))})]})]}),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(Gt,{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(un,{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(B,{size:"sm",onClick:O,disabled:f.isPending,children:[e.jsx(rn,{className:"h-3.5 w-3.5 mr-1.5"})," Add first step"]})]}):e.jsxs(e.Fragment,{children:[u.map((V,G)=>e.jsx(xRn,{step:V,index:G,totalSteps:u.length},V.id)),e.jsxs(B,{variant:"outline",size:"sm",onClick:O,disabled:f.isPending,className:"w-full",children:[f.isPending?e.jsx(Ct,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(rn,{className:"h-3.5 w-3.5 mr-1.5"}),"Add another step"]})]})})})})]}),e.jsxs(yr,{className:"border-t p-4 shrink-0",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:c?"Done":"Cancel"}),e.jsxs(B,{onClick:D,disabled:m.isPending||p.isPending,children:[(m.isPending||p.isPending)&&e.jsx(Ct,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),c?"Save Changes":"Create Campaign"]})]})]})})}function xRn({step:s,index:t,totalSteps:n}){const r=XDn(),a=QDn(),i=ha(),[l,o]=_.useState(!1),[c,d]=_.useState(()=>({...s,body:r2t(s.body)})),[u,h]=_.useState(!1),[m,p]=_.useState(!1),[f,y]=_.useState(""),[v,g]=_.useState(!1),[b,j]=_.useState(!1);_.useEffect(()=>{d({...s,body:r2t(s.body)})},[s]);const S=JSON.stringify(c)!==JSON.stringify(s),C=async()=>{h(!0);try{await r.mutateAsync({id:s.id,campaign_id:s.campaign_id,channel:c.channel,subject:c.subject,body:c.body,video_url:c.video_url,delay_type:c.delay_type,delay_days:c.delay_days,delay_hours:c.delay_hours,anchor_field:c.anchor_field,anchor_offset_days:c.anchor_offset_days}),se.success(`Step ${t+1} saved`)}catch{se.error("Failed to save step")}finally{h(!1)}},E=async()=>{if(await Xi(`Delete step ${t+1}?`))try{await a.mutateAsync({id:s.id,campaign_id:s.campaign_id}),se.success("Step deleted")}catch{se.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",O=c.anchor_offset_days||0;return O===0?`On their ${D}`:O<0?`${Math.abs(O)}d before ${D}`:`${O}d after ${D}`}if(t===0&&!c.delay_days&&!c.delay_hours)return"Sends immediately";const 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(ga,{className:"h-3 w-3"}):e.jsx(Gr,{className:"h-3 w-3"}),e.jsx("span",{children:M()}),e.jsx("span",{children:"·"}),c.channel==="email"?e.jsx(ln,{className:"h-3 w-3"}):e.jsx(Hi,{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(_v,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(tl,{className:"h-4 w-4 text-muted-foreground"})]}),l&&e.jsxs("div",{className:"border-t p-4 space-y-3 bg-muted/10",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Channel"}),e.jsxs(is,{value:c.channel,onValueChange:I=>d({...c,channel:I}),children:[e.jsx(rs,{className:"mt-1 h-9",children:e.jsx(ls,{})}),e.jsx(as,{children:e.jsx(He,{value:"email",children:"📧 Email"})})]})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Timing Type"}),e.jsxs(is,{value:c.delay_type,onValueChange:I=>d({...c,delay_type:I}),children:[e.jsx(rs,{className:"mt-1 h-9",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"relative",children:"⏱ Relative delay"}),e.jsx(He,{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(J,{className:"text-xs",children:"Days delay"}),e.jsx(xe,{type:"number",min:0,value:c.delay_days,onChange:I=>d({...c,delay_days:parseInt(I.target.value)||0}),className:"mt-1 h-9"})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Hours delay"}),e.jsx(xe,{type:"number",min:0,max:23,value:c.delay_hours,onChange:I=>d({...c,delay_hours:parseInt(I.target.value)||0}),className:"mt-1 h-9"})]})]}):e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Anchor"}),e.jsxs(is,{value:c.anchor_field||"birthday",onValueChange:I=>d({...c,anchor_field:I}),children:[e.jsx(rs,{className:"mt-1 h-9",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"birthday",children:"🎂 Birthday"}),e.jsx(He,{value:"home_anniversary",children:"🏠 Home Anniversary"})]})]})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Offset (days, negative = before)"}),e.jsx(xe,{type:"number",value:c.anchor_offset_days||0,onChange:I=>d({...c,anchor_offset_days:parseInt(I.target.value)||0}),className:"mt-1 h-9",placeholder:"0 = on the day, -7 = week before"})]})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Subject Line"}),e.jsx(xe,{value:c.subject,onChange:I=>d({...c,subject:I.target.value}),placeholder:"e.g. Quick question about your home search, {{client_first_name}}",className:"mt-1 h-9"})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx(J,{className:"text-xs",children:"Email Body"}),e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[c.body.length," chars"]})]}),e.jsx(Ms,{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:"}),sRn.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(J,{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(Kr,{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(B,{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(iz,{userId:i||void 0,onSelect:I=>d({...c,video_url:I}),triggerSize:"sm",triggerClassName:"gap-1.5 flex-1 min-w-[120px]"}),e.jsxs(B,{variant:"outline",size:"sm",className:"gap-1 text-xs flex-1 min-w-[120px]",onClick:()=>g(!0),children:[e.jsx(Oa,{className:"h-3 w-3"})," Upload"]}),e.jsxs(B,{variant:"ghost",size:"sm",className:"gap-1 text-xs text-muted-foreground flex-1 min-w-[120px]",onClick:()=>{y(""),p(!0)},children:[e.jsx(Vc,{className:"h-3 w-3"})," Paste URL"]}),e.jsx(AYt,{open:v,onOpenChange:g,onUploadComplete:I=>d({...c,video_url:I})}),e.jsx(Ls,{open:m,onOpenChange:p,children:e.jsxs(Ps,{className:"sm:max-w-md",children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Add video URL"}),e.jsx(_r,{children:"Paste a YouTube, Loom, or direct video URL."})]}),e.jsx(xe,{value:f,onChange:I=>y(I.target.value),placeholder:"https://...",autoFocus:!0,onKeyDown:I=>{I.key==="Enter"&&f.trim()&&(d({...c,video_url:f.trim()}),p(!1))}}),e.jsxs(yr,{children:[e.jsx(B,{variant:"ghost",onClick:()=>p(!1),children:"Cancel"}),e.jsx(B,{disabled:!f.trim(),onClick:()=>{d({...c,video_url:f.trim()}),p(!1)},children:"Add video"})]})]})})]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:E,className:"text-destructive hover:text-destructive",children:[e.jsx(Sn,{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(B,{variant:"outline",size:"sm",onClick:()=>j(!0),children:[e.jsx(ya,{className:"h-3.5 w-3.5 mr-1.5"})," Preview"]}),e.jsxs(B,{size:"sm",onClick:C,disabled:!S||u,children:[u&&e.jsx(Ct,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),"Save step"]})]})]}),e.jsx(rRn,{open:b,onOpenChange:j,subject:c.subject||"",body:c.body||"",ownerUserId:i,stepLabel:`Step ${t+1}`})]})]})}function gRn({open:s,onOpenChange:t,contactIds:n,onSuccess:r}){const{data:a,isLoading:i}=Dae(),l=jnt(),[o,c]=_.useState(""),[d,u]=_.useState(null),[h,m]=_.useState(!1),p=(a||[]).filter(v=>!v.is_starter),f=p.filter(v=>v.name.toLowerCase().includes(o.toLowerCase())||(v.description||"").toLowerCase().includes(o.toLowerCase())),y=async()=>{if(d)try{const v=await l.mutateAsync({campaignId:d,contactIds:n}),g=[`${v.enrolled} enrolled`];v.skipped>0&&g.push(`${v.skipped} skipped`),v.errors>0&&g.push(`${v.errors} errors`),se.success(g.join(" · ")),t(!1),u(null),r==null||r()}catch(v){se.error(v.message||"Failed to enroll contacts")}};return e.jsxs(Ls,{open:s,onOpenChange:t,children:[e.jsxs(Ps,{className:"max-w-md",children:[e.jsxs(Os,{children:[e.jsxs(Ds,{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4 text-primary"}),"Enroll in Drip Campaign"]}),e.jsxs(_r,{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(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search campaigns...",value:o,onChange:v=>c(v.target.value),className:"pl-9 h-9"})]}),e.jsx(Ji,{className:"h-[320px] -mx-1 px-1",children:i?e.jsx("div",{className:"text-center py-8 text-sm text-muted-foreground",children:"Loading..."}):f.length===0?e.jsx("div",{className:"text-center py-8",children:p.length===0?e.jsxs(e.Fragment,{children:[e.jsx(un,{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(B,{size:"sm",onClick:()=>m(!0),children:[e.jsx(rn,{className:"h-3.5 w-3.5 mr-1.5"})," Create campaign"]})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"No campaigns match your search."})}):e.jsx("div",{className:"space-y-1.5",children:f.map(v=>e.jsxs("button",{onClick:()=>u(v.id),className:`w-full flex items-start gap-3 p-3 rounded-lg border text-left transition-all ${d===v.id?"border-primary bg-primary/5 ring-1 ring-primary":"border-border hover:border-primary/40 hover:bg-muted/30"}`,children:[e.jsx("div",{className:`shrink-0 h-9 w-9 rounded-lg bg-gradient-to-br ${v.cover_color} flex items-center justify-center text-lg`,children:v.icon}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:v.name}),v.is_active&&e.jsx(Oe,{variant:"outline",className:"text-[9px] bg-emerald-500/10 text-emerald-600 border-emerald-200 px-1 py-0",children:"Active"})]}),v.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-0.5",children:v.description})]}),d===v.id&&e.jsx(ea,{className:"h-4 w-4 text-primary shrink-0 mt-1"})]},v.id))})})]}),e.jsxs(yr,{className:"gap-2 sm:gap-2",children:[p.length>0&&e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>m(!0),className:"mr-auto text-xs",children:[e.jsx(rn,{className:"h-3.5 w-3.5 mr-1"})," New campaign"]}),e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{onClick:y,disabled:!d||l.isPending,children:[l.isPending&&e.jsx(Ct,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),"Enroll ",n.length," contact",n.length!==1?"s":""]})]})]}),e.jsx(EYt,{open:h,onOpenChange:m})]})}function yRn({selectedIds:s,contacts:t,onClearSelection:n,onSendToLeadPond:r,showLeadPondAction:a,onTransfer:i,showTransferAction:l}){const o=Fn(),{data:c}=Z_(),d=Gzs(),u=Bt(),{isGmailConnected:h}=Vg(),{isReady:m}=$9(),{data:p}=rz(),f=nnt(),y=MKt(),[v,g]=_.useState(!1),[b,j]=_.useState(!1),[S,C]=_.useState(!1),[E,P]=_.useState(!1),[M,I]=_.useState(!1),[D,O]=_.useState(""),[V,G]=_.useState(!1),[$,H]=_.useState(null),Y=s.size;if(Y===0)return null;const Z=async be=>{g(!0);try{const he=Array.from(s).map(Ce=>({contact_id:Ce,relationship_type_id:be})),{error:pe}=await q.from("innercircle_contact_tags").upsert(he,{onConflict:"contact_id,relationship_type_id",ignoreDuplicates:!0});if(pe)throw pe;u.invalidateQueries({queryKey:["innercircle-contacts"]}),u.invalidateQueries({queryKey:["innercircle-contact-counts"]}),ia({title:`Assigned type to ${Y} contacts`}),n()}catch(me){ia({title:"Error assigning type",description:me.message,variant:"destructive"})}finally{g(!1)}},ne=async be=>{g(!0);try{const me=Array.from(s);for(const he of me)try{await y.mutateAsync({contactId:he,tagId:be})}catch{}u.invalidateQueries({queryKey:["all-contact-custom-tags"]}),ia({title:`Tagged ${Y} contacts`}),I(!1),O("")}catch(me){ia({title:"Error adding tags",description:me.message,variant:"destructive"})}finally{g(!1)}},ce=async()=>{if(D.trim()){g(!0);try{const be=await f.mutateAsync({name:D.trim()});await ne(be.id)}catch(be){ia({title:"Error creating tag",description:be.message,variant:"destructive"}),g(!1)}}},ie=(p==null?void 0:p.filter(be=>be.name.toLowerCase().includes(D.toLowerCase())))||[],te=p==null?void 0:p.find(be=>be.name.toLowerCase()===D.trim().toLowerCase()),ae=()=>{const be=t.filter(ze=>s.has(ze.id)),me=["First Name","Last Name","Email","Phone","Street Address","City","State","ZIP","Full Address","Birthday","Home Anniversary","Notes","Relationship Types"],he=be.map(ze=>{var qe;const ke=ze,Ze=ke.address||"",Se=ke.city||"",Fe=ke.state||"",Ne=ke.zip||ke.zip_code||"",Ye=[Se,[Fe,Ne].filter(Boolean).join(" ")].filter(Boolean).join(", "),Ve=[Ze,Ye].filter(Boolean).join(", ");return[ze.first_name,ze.last_name||"",ze.email||"",ze.phone||"",Ze,Se,Fe,Ne,Ve,ze.birthday||"",ze.home_anniversary||"",ze.notes||"",((qe=ze.tags)==null?void 0:qe.map(Qe=>{var Ue;return(Ue=Qe.relationship_type)==null?void 0:Ue.name}).join("; "))||""]}),pe=[me.join(","),...he.map(ze=>ze.map(ke=>`"${(ke||"").replace(/"/g,'""')}"`).join(","))].join(` `),Ce=new Blob([pe],{type:"text/csv"}),Ae=URL.createObjectURL(Ce),Pe=document.createElement("a");Pe.href=Ae,Pe.download=`contacts-export-${new Date().toISOString().slice(0,10)}.csv`,Pe.click(),URL.revokeObjectURL(Ae),ia({title:`Exported ${Y} contacts`})},le=async()=>{if(!await Xi(`Are you sure you want to delete ${Y} contacts? This cannot be undone.`))return;const be=Array.from(s);g(!0),H({done:0,total:be.length});try{const me=await d.mutateAsync({ids:be,onProgress:(he,pe)=>H({done:he,total:pe})});n(),ia({title:`Deleted ${me.toLocaleString()} contacts`})}catch(me){const he=typeof(me==null?void 0:me.deleted)=="number"?me.deleted:0;ia({title:"Error deleting contacts",description:he>0?`${he.toLocaleString()} of ${be.length.toLocaleString()} were deleted before this failed: ${me.message}`:me.message,variant:"destructive"})}finally{H(null),g(!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(Oe,{variant:"secondary",className:"font-semibold",children:[Y," selected"]}),$&&e.jsxs("span",{className:"text-sm text-muted-foreground",children:["Deleting ",$.done.toLocaleString()," of ",$.total.toLocaleString(),"…"]}),e.jsxs(is,{onValueChange:Z,disabled:v,children:[e.jsx(rs,{className:"w-[180px] h-8",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Ep,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-sm",children:"Assign Type"})]})}),e.jsx(as,{children:c==null?void 0:c.filter(be=>be.active).map(be=>e.jsx(He,{value:be.id,children:be.name},be.id))})]}),e.jsxs(od,{open:M,onOpenChange:I,children:[e.jsx(ld,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",disabled:v,children:[e.jsx(rn,{className:"h-3.5 w-3.5 mr-1"}),"Add Tag"]})}),e.jsxs(Qc,{className:"w-56 p-2",align:"start",children:[e.jsx(xe,{placeholder:"Search or create tag...",value:D,onChange:be=>O(be.target.value),onKeyDown:be=>{be.key==="Enter"&&D.trim()&&!te?(be.preventDefault(),ce()):be.key==="Enter"&&te&&(be.preventDefault(),ne(te.id))},className:"h-8 text-sm mb-2"}),e.jsxs("div",{className:"max-h-[200px] overflow-y-auto space-y-0.5",children:[ie.map(be=>e.jsxs("button",{onClick:()=>ne(be.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:be.color}}),e.jsx("span",{className:"flex-1 text-left truncate",children:be.name})]},be.id)),D.trim()&&!te&&e.jsxs("button",{onClick:ce,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(rn,{className:"h-3.5 w-3.5"}),'Create "',D.trim(),'"']}),ie.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(B,{variant:"outline",size:"sm",onClick:()=>j(!0),disabled:v,children:[e.jsx(ln,{className:"h-3.5 w-3.5 mr-1"}),"Email"]}),m&&e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>{const be=Array.from(s).join(",");o(`/admin/email-campaigns/new?contactIds=${be}`)},disabled:v,children:[e.jsx(wh,{className:"h-3.5 w-3.5 mr-1"}),"Mass Email"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>C(!0),disabled:v,children:[e.jsx(Kr,{className:"h-3.5 w-3.5 mr-1"}),"Send Video"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>P(!0),disabled:v,children:[e.jsx(un,{className:"h-3.5 w-3.5 mr-1"}),"Enroll in Campaign"]}),a&&r&&e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>r(Array.from(s)),disabled:v,children:[e.jsx(m1,{className:"h-3.5 w-3.5 mr-1"}),"Send to Lead Pond"]}),l&&i&&e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>i(Array.from(s)),disabled:v,children:[e.jsx(U4,{className:"h-3.5 w-3.5 mr-1"}),"Transfer"]}),Y>=2&&Y<=10&&e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>G(!0),disabled:v,children:[e.jsx(s7,{className:"h-3.5 w-3.5 mr-1"}),"Merge"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:ae,disabled:v,children:[e.jsx(li,{className:"h-3.5 w-3.5 mr-1"}),"Export"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:le,disabled:v,className:"text-destructive hover:text-destructive",children:[e.jsx(Sn,{className:"h-3.5 w-3.5 mr-1"}),"Delete"]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:n,className:"ml-auto",children:[e.jsx(Qn,{className:"h-3.5 w-3.5 mr-1"}),"Clear"]})]}),e.jsx(yYt,{open:V,onOpenChange:G,contactIds:Array.from(s),onMerged:n}),e.jsx(gRn,{open:E,onOpenChange:P,contactIds:Array.from(s),onSuccess:n}),e.jsx(DS,{open:b,onOpenChange:j,bulkContacts:Array.from(s).map(be=>{const me=t.find(he=>he.id===be);return me?{id:me.id,first_name:me.first_name,last_name:me.last_name,email:me.email||""}:null}).filter(be=>be!==null&&be.email!==""),onSendComplete:()=>{j(!1),n()}}),e.jsx(GDn,{open:S,onOpenChange:C,contacts:Array.from(s).map(be=>t.find(me=>me.id===be)).filter(be=>!!be).map(be=>({id:be.id,first_name:be.first_name,last_name:be.last_name,email:be.email})),isGmailConnected:!!h,isMassEmailReady:!!m,onSendComplete:()=>{C(!1),n()}})]})}function a2t({contact:s,onEdit:t,onDelete:n,onSnooze:r,onSendToLeadPond:a,showLeadPondAction:i,onTransfer:l,showTransferAction:o}){const c=Fn(),{isReady:d}=$9(),u=`${s.first_name} ${s.last_name||""}`.trim();return e.jsxs(tu,{children:[e.jsx(su,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:h=>h.stopPropagation(),children:e.jsx(ob,{className:"h-4 w-4"})})}),e.jsxs(Od,{align:"end",onClick:h=>h.stopPropagation(),children:[e.jsxs(ca,{onClick:()=>c(`/mission-control/contacts/${s.id}?tab=activity&action=log`),children:[e.jsx(_a,{className:"h-4 w-4 mr-2"}),"Log Touch"]}),e.jsxs(ca,{onClick:()=>c(`/mission-control/video?contactId=${s.id}`),children:[e.jsx(Kr,{className:"h-4 w-4 mr-2"}),"Send Video"]}),e.jsxs(ca,{onClick:()=>c(`/mission-control/popbys?contactId=${s.id}`),children:[e.jsx(Xa,{className:"h-4 w-4 mr-2"}),"Schedule Pop-by"]}),d&&s.email&&e.jsxs(ca,{onClick:()=>c(`/admin/email-campaigns/new?contactIds=${s.id}`),children:[e.jsx(ln,{className:"h-4 w-4 mr-2"}),"Mass Email"]}),e.jsxs(ca,{onClick:()=>r(s.id,u),children:[e.jsx(ky,{className:"h-4 w-4 mr-2"}),"Snooze"]}),i&&a&&e.jsxs(ca,{onClick:()=>a(s.id),children:[e.jsx(m1,{className:"h-4 w-4 mr-2"}),"Send to Lead Pond"]}),o&&l&&e.jsxs(ca,{onClick:()=>l(s.id),children:[e.jsx(U4,{className:"h-4 w-4 mr-2"}),"Transfer to Team Member"]}),e.jsxs(ca,{onClick:()=>t(s),children:[e.jsx(Ya,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsxs(ca,{onClick:()=>n(s.id),className:"text-destructive focus:text-destructive",children:[e.jsx(Sn,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})}function i2t({currentFilters:s,currentSortBy:t,onApplySmartList:n}){const{data:r}=rnt(),a=PKt(),i=LKt(),[l,o]=_.useState(!1),[c,d]=_.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(tu,{children:[e.jsx(su,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"gap-1.5",children:[e.jsx(D_,{className:"h-3.5 w-3.5"}),"Smart Filters",r&&r.length>0&&e.jsx(Oe,{variant:"secondary",className:"h-5 px-1.5 text-[10px]",children:r.length}),e.jsx(tl,{className:"h-3.5 w-3.5"})]})}),e.jsxs(Od,{align:"start",className:"w-56",children:[r&&r.length>0?e.jsxs(e.Fragment,{children:[r.map(m=>e.jsxs(ca,{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(B,{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(Sn,{className:"h-3 w-3 text-destructive"})})]},m.id)),e.jsx(M0,{})]}):e.jsx(ca,{disabled:!0,className:"text-muted-foreground text-xs",children:"No saved filters yet"}),u&&e.jsxs(ca,{onClick:()=>o(!0),children:[e.jsx(HM,{className:"h-4 w-4 mr-2"}),"Save Current Filter"]})]})]}),e.jsx(Ls,{open:l,onOpenChange:o,children:e.jsxs(Ps,{className:"max-w-sm",children:[e.jsx(Os,{children:e.jsx(Ds,{children:"Save Smart Filter"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(xe,{placeholder:"e.g. Buyers in 40205",value:c,onChange:m=>d(m.target.value),onKeyDown:m=>m.key==="Enter"&&h(),autoFocus:!0}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx(B,{onClick:h,disabled:!c.trim()||a.isPending,children:"Save"})]})]})]})})]})}const FTe=[{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"}],TYt=[{value:"home_anniversary",label:"Home anniversary"},{value:"wedding_anniversary",label:"Wedding anniversary"}],vRn=[{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 bRn({open:s,onOpenChange:t,hasLeadSite:n,behavior:r,onApply:a,selectedType:i,onSelectedTypeChange:l,relationshipTypes:o,contactLeadSources:c}){const[d,u]=_.useState(r),[h,m]=_.useState(n?"behavior":"contact"),{data:p}=V9(),f=_.useMemo(()=>{const g=new Map;return(p||[]).forEach(b=>{g.set(b.name.trim().toLowerCase(),{value:`name:${b.name}`,label:b.name})}),(c||[]).forEach(b=>{const j=b.trim().toLowerCase();!j||g.has(j)||g.set(j,{value:`name:${b}`,label:b})}),Array.from(g.values()).sort((b,j)=>b.label.localeCompare(j.label))},[p,c]);_.useEffect(()=>{s&&u(r)},[s,r]);const y=g=>u(b=>({...b,...g})),v=Object.entries(d).filter(([,g])=>g!==void 0&&g!==!1&&g!=="").length;return e.jsx(qg,{open:s,onOpenChange:t,children:e.jsxs(hg,{side:"right",className:"w-full sm:max-w-lg overflow-y-auto",children:[e.jsxs(P0,{children:[e.jsxs(L0,{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4 text-primary"}),"Advanced Filters"]}),e.jsx(U9,{children:"Slice your database by website activity, contact details, and engagement."})]}),e.jsxs(Yr,{value:h,onValueChange:g=>m(g),className:"mt-4",children:[e.jsxs(Zr,{className:"grid w-full grid-cols-3",children:[e.jsxs(Ht,{value:"contact",className:"gap-1.5",children:[e.jsx(In,{className:"h-3.5 w-3.5"})," Contact"]}),e.jsxs(Ht,{value:"behavior",disabled:!n,className:"gap-1.5",children:[e.jsx(hm,{className:"h-3.5 w-3.5"})," Behavior"]}),e.jsx(Ht,{value:"engagement",children:"Engagement"})]}),e.jsxs(Gt,{value:"contact",className:"space-y-6 mt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Contact Type"}),e.jsxs(is,{value:i,onValueChange:l,children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"All types"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Types"}),o==null?void 0:o.map(g=>e.jsx(He,{value:g.id,children:g.name},g.id))]})]})]}),e.jsxs(y3,{title:"Contact Info Present",children:[e.jsx(Wv,{label:"Has email",checked:d.hasEmail===!0,onChange:g=>y({hasEmail:g||void 0})}),e.jsx(Wv,{label:"Has phone",checked:d.hasPhone===!0,onChange:g=>y({hasPhone:g||void 0})}),e.jsx(Wv,{label:"Has address",checked:d.hasAddress===!0,onChange:g=>y({hasAddress:g||void 0})}),e.jsx(Wv,{label:"Has birthday",checked:d.hasBirthday===!0,onChange:g=>y({hasBirthday:g||void 0})}),e.jsx(Wv,{label:"Has spouse",checked:d.hasSpouse===!0,onChange:g=>y({hasSpouse:g||void 0})}),e.jsx(Wv,{label:"Has company / job",checked:d.hasCompany===!0,onChange:g=>y({hasCompany:g||void 0})}),e.jsx(Wv,{label:"Has notes",checked:d.hasNotes===!0,onChange:g=>y({hasNotes:g||void 0})})]}),e.jsxs(y3,{title:"Location",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:[e.jsx(sze,{label:"City",value:d.city||"",onChange:g=>y({city:g||void 0}),placeholder:"Any city"}),e.jsx(sze,{label:"State",value:d.state||"",onChange:g=>y({state:g||void 0}),placeholder:"Any state"})]}),e.jsx(sze,{label:"ZIP / Postal",value:d.zip||"",onChange:g=>y({zip:g||void 0}),placeholder:"Any ZIP"})]}),e.jsxs(y3,{title:"Important Dates",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Birthday month"}),e.jsxs(is,{value:d.birthdayMonth?String(d.birthdayMonth):"all",onValueChange:g=>y({birthdayMonth:g==="all"?void 0:Number(g)}),children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Any month"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"Any month"}),FTe.map(g=>e.jsx(He,{value:String(g.value),children:g.label},g.value))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{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(is,{value:d.anniversaryField||"home_anniversary",onValueChange:g=>y({anniversaryField:g}),children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Field"})}),e.jsx(as,{children:TYt.map(g=>e.jsx(He,{value:g.value,children:g.label},g.value))})]}),e.jsxs(is,{value:d.anniversaryMonth?String(d.anniversaryMonth):"all",onValueChange:g=>y({anniversaryMonth:g==="all"?void 0:Number(g)}),children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Any month"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"Any month"}),FTe.map(g=>e.jsx(He,{value:String(g.value),children:g.label},g.value))]})]})]})]})]}),e.jsx(y3,{title:"Date Added",children:e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:[e.jsx(o2t,{label:"From",value:d.dateAddedFrom,onChange:g=>y({dateAddedFrom:g||void 0})}),e.jsx(o2t,{label:"To",value:d.dateAddedTo,onChange:g=>y({dateAddedTo:g||void 0})})]})}),e.jsx(y3,{title:"Lead Source",children:e.jsxs(is,{value:d.leadSourceId||"all",onValueChange:g=>y({leadSourceId:g==="all"?void 0:g}),children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"All sources"})}),e.jsxs(as,{className:"max-h-72",children:[e.jsx(He,{value:"all",children:"All sources"}),e.jsx(He,{value:"none",children:"No source"}),f.map(g=>e.jsx(He,{value:g.value,children:g.label},g.value))]})]})})]}),e.jsx(Gt,{value:"behavior",className:"space-y-6 mt-4",children:n?e.jsxs(e.Fragment,{children:[e.jsxs(y3,{title:"Last Active On Site",children:[e.jsx(k_,{value:d.lastActive||"",onValueChange:g=>y({lastActive:g||void 0}),className:"grid grid-cols-2 gap-2",children:vRn.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(sm,{value:g.value}),e.jsx("span",{className:"text-sm",children:g.label})]},g.value))}),d.lastActive&&e.jsx(B,{variant:"ghost",size:"sm",className:"mt-1 h-7 px-2 text-xs",onClick:()=>y({lastActive:void 0}),children:"Clear"})]}),e.jsxs(y3,{title:"Registration",children:[e.jsx(Wv,{label:"Registered on lead site",checked:d.registered==="yes",onChange:g=>y({registered:g?"yes":void 0})}),e.jsx(Wv,{label:"Anonymous visitors only",checked:d.registered==="no",onChange:g=>y({registered:g?"no":void 0})})]}),e.jsxs(y3,{title:"Property Activity",children:[e.jsx(Wv,{label:"Viewed any listing",checked:d.viewedListing==="any",onChange:g=>y({viewedListing:g?"any":void 0})}),e.jsx(Wv,{label:"Hot buyer — 3+ views in last 7 days",checked:d.viewedListing==="multiple7d",onChange:g=>y({viewedListing:g?"multiple7d":void 0})}),e.jsx(Wv,{label:"Saved a property",checked:!!d.savedProperty,onChange:g=>y({savedProperty:g||void 0})}),e.jsx(Wv,{label:"Has an active saved search / alert",checked:!!d.hasSavedSearch,onChange:g=>y({hasSavedSearch:g||void 0})})]}),e.jsxs(y3,{title:"Requests",children:[e.jsx(Wv,{label:"Requested a showing / asked a question",checked:!!d.requestedShowing,onChange:g=>y({requestedShowing:g||void 0})}),e.jsx(Wv,{label:"Requested a home valuation",checked:!!d.requestedValuation,onChange:g=>y({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(Gt,{value:"engagement",className:"space-y-4 mt-4",children:[e.jsx(Wv,{label:"Any website activity",checked:!!d.websiteActiveOnly,onChange:g=>y({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(s8t,{className:"mt-6 flex-row gap-2 sm:justify-between",children:[e.jsx(B,{variant:"ghost",onClick:()=>u({}),disabled:v===0,children:"Clear behavior filters"}),e.jsx(B,{onClick:()=>{a(d),t(!1)},children:"Apply"})]})]})})}function y3({title:s,children:t}){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:s}),e.jsx("div",{className:"space-y-2",children:t})]})}function Wv({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(fn,{checked:t,onCheckedChange:n})]})}function sze({label:s,value:t,onChange:n,placeholder:r}){return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:s}),e.jsxs("div",{className:"relative",children:[e.jsx(xe,{value:t,onChange:a=>n(a.target.value),placeholder:r,className:"h-8"}),t&&e.jsx("button",{onClick:()=>n(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",children:e.jsx(Qn,{className:"h-3 w-3"})})]})]})}function o2t({label:s,value:t,onChange:n}){const[r,a]=_.useState(!1),i=t?py(t):void 0;return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:s}),e.jsxs(od,{open:r,onOpenChange:a,children:[e.jsx(ld,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:At("w-full justify-start text-left font-normal h-8",!i&&"text-muted-foreground"),children:[e.jsx(ga,{className:"mr-2 h-3.5 w-3.5"}),i?Hs(i,"MMM d, yyyy"):e.jsx("span",{children:"Pick a date"})]})}),e.jsx(Qc,{className:"w-auto p-0",align:"start",children:e.jsx(Pj,{mode:"single",selected:i,onSelect:l=>{n(l?Hs(l,"yyyy-MM-dd"):void 0),a(!1)},initialFocus:!0})})]})]})}function _Rn({behavior:s,onRemove:t,onClearAll:n}){const r=wRn(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 wRn(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=FTe.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=FTe.find(i=>i.value===s.anniversaryMonth),a=((n=TYt.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(py(s.dateAddedFrom),"MMM d, yyyy")}`}),s.dateAddedTo&&t.push({key:"dateAddedTo",label:`Added on/before ${Hs(py(s.dateAddedTo),"MMM d, yyyy")}`}),s.leadSourceId&&t.push({key:"leadSourceId",label:s.leadSourceId==="none"?"No lead source":"Lead source"}),t}function jRn(){const[s,t]=_.useState(""),[n,r]=_.useState(!0);return _.useEffect(()=>{let a=!1;return(async()=>{const{data:i}=await q.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();a||(t((i==null?void 0:i.value)??""),r(!1))})(),()=>{a=!0}},[]),{token:s,loading:n}}function NRn(){const s=ha();return at({queryKey:["sphere-map-contacts",s],queryFn:async()=>{if(!s)return[];const t=1e3,n=[];for(let r=0;;r+=t){const{data:a,error:i}=await q.rpc("get_sphere_map_contacts",{_owner:s}).order("id",{ascending:!0}).range(r,r+t-1);if(i)throw i;const l=a??[];if(n.push(...l),l.length{let n=0,r=0,a=0;for(let i=0;i<20;i++){const{data:l,error:o}=await q.functions.invoke("geocode-contacts",{body:{owner_user_id:s,limit:200}});if(o)throw o;if(n+=(l==null?void 0:l.processed)??0,r+=(l==null?void 0:l.matched)??0,a=(l==null?void 0:l.remaining)??0,!(l!=null&&l.processed))break}return{processed:n,matched:r,remaining:a}},onSuccess:n=>{t.invalidateQueries({queryKey:["sphere-map-contacts"]}),ia({title:n.processed?`Mapped ${n.matched} of ${n.processed} addresses`:"Everything is already mapped",description:n.remaining?`${n.remaining} still to look up`:void 0})},onError:n=>ia({title:"Could not map addresses",description:n.message,variant:"destructive"})})}function j_r(){const s=ha();return at({queryKey:["contact-map-views",s],queryFn:async()=>{const{data:t,error:n}=await q.from("contact_map_views").select("*").eq("owner_user_id",s).order("created_at");if(n)throw n;return t},enabled:!!s})}function N_r(){const s=ha(),t=Bt();return mt({mutationFn:async n=>{const{error:r}=await q.from("contact_map_views").insert({...n,owner_user_id:s});if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["contact-map-views"]}),ia({title:"View saved"})},onError:n=>ia({title:"Could not save view",description:n.message,variant:"destructive"})})}function k_r(){const s=Bt();return mt({mutationFn:async t=>{const{error:n}=await q.from("contact_map_views").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["contact-map-views"]})})}function kRn(){const s=ha();return at({queryKey:["contact-farms",s],queryFn:async()=>{const{data:t,error:n}=await q.from("contact_farms").select("*").eq("owner_user_id",s).order("created_at");if(n)throw n;return t},enabled:!!s})}function S_r(){const s=ha(),t=Bt();return mt({mutationFn:async n=>{const{error:r}=await q.from("contact_farms").insert({...n,boundary:n.boundary,owner_user_id:s});if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["contact-farms"]}),ia({title:"Farm saved"})},onError:n=>ia({title:"Could not save farm",description:n.message,variant:"destructive"})})}function C_r(){const s=Bt();return mt({mutationFn:async t=>{const{error:n}=await q.from("contact_farms").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["contact-farms"]})})}function A_r(){const s=ha();return at({queryKey:["popby-routes",s],queryFn:async()=>{const{data:t,error:n}=await q.from("popby_routes").select("*, stops:popby_route_stops(*)").eq("owner_user_id",s).order("created_at",{ascending:!1});if(n)throw n;return t??[]},enabled:!!s})}function E_r(){const s=ha(),t=Bt();return mt({mutationFn:async({name:n,plannedDate:r,contactIds:a})=>{const{data:i,error:l}=await q.from("popby_routes").insert({owner_user_id:s,name:n,planned_date:r??null}).select().single();if(l)throw l;if(a.length){const{error:o}=await q.from("popby_route_stops").insert(a.map((c,d)=>({route_id:i.id,contact_id:c,sort_order:d})));if(o)throw o}return i},onSuccess:()=>{t.invalidateQueries({queryKey:["popby-routes"]}),ia({title:"Route created"})},onError:n=>ia({title:"Could not create route",description:n.message,variant:"destructive"})})}function T_r(){const s=Bt();return mt({mutationFn:async({id:t,...n})=>{const{error:r}=await q.from("popby_route_stops").update(n).eq("id",t);if(r)throw r},onSuccess:()=>s.invalidateQueries({queryKey:["popby-routes"]})})}function M_r(){const s=Bt();return mt({mutationFn:async t=>{for(const n of t){const{error:r}=await q.from("popby_route_stops").update({sort_order:n.sort_order}).eq("id",n.id);if(r)throw r}},onSuccess:()=>s.invalidateQueries({queryKey:["popby-routes"]})})}function P_r(){const s=Bt();return mt({mutationFn:async t=>{const{error:n}=await q.from("popby_routes").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["popby-routes"]})})}function L_r(){const s=ha();return at({queryKey:["sphere-map-anchors",s],queryFn:async()=>{const[t,n]=await Promise.all([q.from("listings").select("id, property_address, city, state, latitude, longitude, status, slug").eq("agent_id",s).not("latitude","is",null),q.from("open_houses").select("id, property_address, city, state, event_date, slug, is_active").eq("agent_id",s).eq("is_active",!0)]);return{listings:t.data??[],openHouses:n.data??[]}},enabled:!!s})}function I_r(){const s=ha();return at({queryKey:["sphere-map-listings",s],queryFn:async()=>{const t=[];for(let r=0;r<20;r++){const{data:a,error:i}=await q.from("listings").select("id, property_address, city, state, price, status, bedrooms, bathrooms, square_footage, slug, latitude, longitude, listing_class, photos:listing_photos(photo_url, is_primary, sort_order)").eq("agent_id",s).order("created_at",{ascending:!1}).range(r*1e3,r*1e3+1e3-1);if(i)throw i;const l=a??[];if(l.forEach(o=>{var h;const c=(o.photos??[]).slice().sort((m,p)=>(p.is_primary?1:0)-(m.is_primary?1:0)||(m.sort_order??0)-(p.sort_order??0)),{photos:d,...u}=o;t.push({...u,photo_url:((h=c[0])==null?void 0:h.photo_url)??null})}),l.length<1e3)break}return t},enabled:!!s,staleTime:6e4})}function D_r(){const s=ha();return at({queryKey:["sphere-map-open-houses",s],queryFn:async()=>{const t=[];for(let r=0;r<10;r++){const{data:a,error:i}=await q.from("open_houses").select("id, slug, property_address, city, state, zip, event_date, start_time, end_time, price, beds, baths, sqft, photo_url, is_active, latitude, longitude").eq("agent_id",s).order("event_date",{ascending:!1}).range(r*1e3,r*1e3+1e3-1);if(i)throw i;const l=a??[];if(l.forEach(o=>t.push(o)),l.length<1e3)break}return t},enabled:!!s,staleTime:6e4})}function R_r(s){const{leadSiteId:t,filters:n,enabled:r}=s,a=JSON.stringify(n);return at({queryKey:["sphere-map-idx",t,a],queryFn:async()=>{if(!t||!n.cities.length||!n.statuses.length)return[];const{data:i,error:l}=await q.functions.invoke("lead-site-search",{body:{leadSiteId:t,filterCities:n.cities,statuses:n.statuses,minPrice:n.minPrice??void 0,maxPrice:n.maxPrice??void 0,minBeds:n.minBeds??void 0,minBaths:n.minBaths??void 0,propertyType:n.propertyType??void 0,limit:250,pageSize:250}});if(l)throw l;return((i==null?void 0:i.listings)??[]).filter(c=>Number.isFinite(c.latitude)&&Number.isFinite(c.longitude))},enabled:r&&!!t,staleTime:5*60*1e3})}function MYt(s,t,n){const r=Bt(),{token:a}=jRn();return mt({mutationFn:async i=>{var o,c;if(!a)throw new Error("Map is still loading. Try again in a moment.");let l=0;for(const d of i){const u=[d.property_address,d.city,d.state].filter(Boolean).join(", ");if(u)try{const m=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(u)}.json?access_token=${a}&limit=1&country=us`)).json(),p=(c=(o=m==null?void 0:m.features)==null?void 0:o[0])==null?void 0:c.center;if(!p)continue;const[f,y]=p,{error:v}=await q.from(s).update({latitude:y,longitude:f}).eq("id",d.id);v||l++}catch(h){console.error("Geocode error:",h)}}return l},onSuccess:i=>{r.invalidateQueries({queryKey:[t]}),ia({title:i?`${i} ${i===1?n.one:n.many} placed on the map`:"No locations found",description:i?void 0:"Check the street address, city and state."})},onError:i=>ia({title:"Could not look up addresses",description:i.message,variant:"destructive"})})}function F_r(){return MYt("listings","sphere-map-listings",{one:"listing",many:"listings"})}function O_r(){return MYt("open_houses","sphere-map-open-houses",{one:"open house",many:"open houses"})}const z_r={never:{label:"Never contacted",color:"#8b5cf6"},red:{label:"12+ months",color:"#ef4444"},orange:{label:"6–12 months",color:"#f97316"},yellow:{label:"3–6 months",color:"#eab308"},green:{label:"Recent",color:"#22c55e"}};function SRn(s){if(!s)return null;const t=new Date(s).getTime();return Number.isNaN(t)?null:Math.max(0,Math.floor((Date.now()-t)/864e5))}function B_r(s){return s===null?"never":s>=365?"red":s>=180?"orange":s>=90?"yellow":"green"}function CRn(s){return`${s.first_name??""} ${s.last_name??""}`.trim()||"Unnamed contact"}function ARn(s){return[s.address,[s.city,s.state].filter(Boolean).join(", "),s.zip].filter(Boolean).join(" · ")}function U_r(s){const t=new Map;return s.forEach(n=>{if(typeof n.latitude!="number"||typeof n.longitude!="number")return;const r=n.household_key||`${n.latitude.toFixed(5)},${n.longitude.toFixed(5)}`,a=t.get(r);a?a.push(n):t.set(r,[n])}),Array.from(t.entries()).map(([n,r])=>{const a=r.map(c=>SRn(c.last_touch_at)),i=a.some(c=>c===null)?null:Math.max(...a),l=Array.from(new Set(r.map(c=>c.last_name).filter(Boolean))),o=r.length===1?CRn(r[0]):l.length===1?`${r.map(c=>c.first_name).filter(Boolean).join(" & ")} ${l[0]}`:`${r.length} contacts`;return{key:n,lat:r[0].latitude,lng:r[0].longitude,contacts:r,label:o,addressLine:ARn(r[0]),gapDays:i}})}const ERn=3958.8;function PYt(s,t,n,r){const a=c=>c*Math.PI/180,i=a(n-s),l=a(r-t),o=Math.sin(i/2)**2+Math.cos(a(s))*Math.cos(a(n))*Math.sin(l/2)**2;return 2*ERn*Math.asin(Math.sqrt(o))}function TRn(s,t,n){let r=!1;for(let a=0,i=n.length-1;at!=d>t&&s<(c-l)*(t-o)/(d-o)+l&&(r=!r)}return r}function q_r(s,t,n,r=64){const a=[],i=t*Math.PI/180,l=n/69,o=n/(69*Math.max(.15,Math.cos(i)));for(let c=0;c<=r;c++){const d=c/r*Math.PI*2;a.push([s+o*Math.cos(d),t+l*Math.sin(d)])}return a}function $_r(s){const t=s.reduce((n,[r,a])=>({lng:n.lng+r,lat:n.lat+a}),{lng:0,lat:0});return{lng:t.lng/s.length,lat:t.lat/s.length}}function V_r(s,t){if(s.length<=2)return[...s];const n=[...s],r=[];let a={lat:s[0].lat,lng:s[0].lng};for(;n.length;){let i=0,l=1/0;n.forEach((c,d)=>{const u=PYt(a.lat,a.lng,c.lat,c.lng);u{const l=n.filter(o=>typeof o.latitude=="number"&&typeof o.longitude=="number");return s.map(o=>{var u;const c=((u=o.boundary)==null?void 0:u.ring)??[],d=new Set;if(c.length>=3)for(const h of l)TRn(h.longitude,h.latitude,c)&&d.add(h.id);return{id:o.id,name:o.name,color:o.color,contactIds:d,count:d.size}})},[s,n]),i=_.useMemo(()=>n.filter(l=>typeof l.latitude!="number"||typeof l.longitude!="number").length,[n]);return{neighborhoods:a,unmappedCount:i,isLoading:t||r}}function LYt(s,t){const n=t instanceof Set?t:new Set(t);if(n.size===0)return null;const r=new Set;for(const a of s)n.has(a.id)&&a.contactIds.forEach(i=>r.add(i));return r}function PRn({selected:s,onChange:t,className:n}){const{neighborhoods:r,unmappedCount:a,isLoading:i}=Nnt(),l=new Set(s),o=c=>{const d=new Set(l);d.has(c)?d.delete(c):d.add(c),t(Array.from(d))};return e.jsxs(od,{children:[e.jsx(ld,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:`gap-1.5 h-8 rounded-lg ${n??""}`,children:[e.jsx(Xa,{className:"h-3.5 w-3.5"}),"Neighborhoods",s.length>0&&e.jsx(Oe,{variant:"secondary",className:"h-5 px-1.5 text-[10px]",children:s.length})]})}),e.jsxs(Qc,{align:"start",className:"w-72 p-0",children:[e.jsxs("div",{className:"p-3 border-b",children:[e.jsx("p",{className:"text-sm font-medium",children:"Neighborhoods"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Areas you've drawn on the contacts map."})]}),i?e.jsxs("div",{className:"p-6 flex items-center justify-center text-sm text-muted-foreground gap-2",children:[e.jsx(Ct,{className:"h-4 w-4 animate-spin"})," Loading…"]}):r.length===0?e.jsxs("div",{className:"p-4 space-y-2 text-sm",children:[e.jsx("p",{className:"text-muted-foreground",children:"You haven't drawn any neighborhoods yet."}),e.jsx(B,{asChild:!0,variant:"outline",size:"sm",className:"w-full",children:e.jsx(ir,{to:"/mission-control/sphere-map",children:"Open the contacts map"})})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"max-h-64 overflow-y-auto p-2 space-y-1",children:r.map(c=>e.jsxs("button",{type:"button",onClick:()=>o(c.id),className:"w-full flex items-center gap-2 px-2 py-1.5 rounded-md hover:bg-muted text-sm text-left",children:[e.jsx($a,{checked:l.has(c.id),className:"pointer-events-none"}),e.jsx("span",{className:"h-2.5 w-2.5 rounded-full shrink-0",style:{backgroundColor:c.color}}),e.jsx("span",{className:"flex-1 truncate",children:c.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:c.count})]},c.id))}),e.jsxs("div",{className:"p-2 border-t space-y-2",children:[a>0&&e.jsxs("p",{className:"text-[11px] text-muted-foreground px-1",children:[a.toLocaleString()," contacts don't have a mapped address yet, so they can't land in a neighborhood."," ",e.jsx(ir,{to:"/mission-control/sphere-map",className:"underline",children:"Map them"})]}),s.length>0&&e.jsx(B,{variant:"ghost",size:"sm",className:"w-full text-xs",onClick:()=>t([]),children:"Clear neighborhoods"})]})]})]})]})}async function zB(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 pZ(){return{lastActiveAt:null,registered:!1,propertyViewCount:0,propertyViewCount7d:0,savedListingCount:0,activeSavedSearchCount:0,showingRequests:0,valuationRequests:0,viewedCities:[],viewedZips:[]}}function LRn(){const{user:s}=hs(),{leadSite:t,hasLeadSite:n}=lf(),{data:r,isLoading:a}=at({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=(g,b)=>{const j=i.get(g)||pZ();i.set(g,{...j,...b})},o=await zB((g,b)=>q.from("lead_site_visitors").select("id, contact_id, last_seen_at, email").eq("lead_site_id",t.id).not("contact_id","is",null).range(g,b)),c=new Map,d=new Map;o.forEach(g=>{if(!g.contact_id)return;c.set(g.id,g.contact_id),g.email&&d.set(g.email.toLowerCase(),g.contact_id);const b=i.get(g.contact_id);(!b||!b.lastActiveAt||g.last_seen_at>b.lastActiveAt)&&l(g.contact_id,{lastActiveAt:g.last_seen_at})});const u=await zB((g,b)=>q.from("lead_site_consumer_profiles").select("contact_id, user_id").eq("lead_site_id",t.id).not("contact_id","is",null).range(g,b)),h=new Map;u.forEach(g=>{g.contact_id&&(h.set(g.user_id,g.contact_id),l(g.contact_id,{registered:!0}))});const m=new Date(Date.now()-7*24*60*60*1e3).toISOString();return(await zB((g,b)=>q.from("lead_site_property_views").select("visitor_id, viewed_at, property_address").eq("lead_site_id",t.id).not("visitor_id","is",null).range(g,b))).forEach(g=>{const b=g.visitor_id?c.get(g.visitor_id):null;if(!b)return;const j=i.get(b)||pZ();j.propertyViewCount+=1,g.viewed_at>=m&&(j.propertyViewCount7d+=1),i.set(b,j)}),(await zB((g,b)=>q.from("lead_site_saved_listings").select("user_id, mls_number").eq("lead_site_id",t.id).range(g,b))).forEach(g=>{const b=h.get(g.user_id);if(!b)return;const j=i.get(b)||pZ();j.savedListingCount+=1,i.set(b,j)}),(await zB((g,b)=>q.from("lead_site_saved_searches").select("user_id").eq("lead_site_id",t.id).eq("is_active",!0).range(g,b))).forEach(g=>{const b=h.get(g.user_id);if(!b)return;const j=i.get(b)||pZ();j.activeSavedSearchCount+=1,i.set(b,j)}),(await zB((g,b)=>q.from("lead_site_leads").select("email, lead_type").eq("lead_site_id",t.id).not("email","is",null).range(g,b))).forEach(g=>{if(!g.email)return;const b=d.get(g.email.toLowerCase());if(!b)return;const j=i.get(b)||pZ(),S=(g.lead_type||"").toLowerCase();(S.includes("showing")||S.includes("question")||S==="contact")&&(j.showingRequests+=1),(S.includes("valuation")||S.includes("cma")||S.includes("home_value"))&&(j.valuationRequests+=1),i.set(b,j)}),i},enabled:!!s&&n,staleTime:5*60*1e3});return{behaviorMap:r??new Map,hasLeadSite:n,isLoading:a}}const IYt="innercircle_geocode_cache_v1";function IRn(){try{return JSON.parse(localStorage.getItem(IYt)||"{}")}catch{return{}}}function DRn(s){try{localStorage.setItem(IYt,JSON.stringify(s))}catch{}}function RRn(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 FRn({open:s,onOpenChange:t,contacts:n,onCitySelect:r}){const a=_.useRef(null),i=_.useRef(null),[l,o]=_.useState(""),[c,d]=_.useState(!0),[u,h]=_.useState([]),[m,p]=_.useState({done:0,total:0}),[f,y]=_.useState(!1),[v,g]=_.useState("heat");_.useEffect(()=>{if(!s)return;let j=!1;return(async()=>{d(!0);const{data:S}=await q.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();j||(o((S==null?void 0:S.value)||""),d(!1))})(),()=>{j=!0}},[s]),_.useEffect(()=>{if(!s||!l)return;let j=!1;return(async()=>{const C=IRn(),E=n.map($=>({c:$,addr:RRn($)})).filter($=>$.addr),P=[],M=[];for(const{c:$,addr:H}of E){const Y=C[H];Y!==null&&(Y?P.push({id:$.id,name:`${$.first_name||""} ${$.last_name||""}`.trim(),city:$.city||null,state:$.state||null,zip:$.zip||$.zip_code||null,lat:Y.lat,lng:Y.lng}):M.push({c:$,addr:H}))}if(j||h(P),p({done:P.length,total:E.length}),M.length===0)return;y(!0);const I=6;let D=0;const O={...C},V=[...P],G=async()=>{var $;for(;D{j=!0}},[s,l,n]);const b=_.useMemo(()=>{const j=new Map;for(const S of n){const C=(S.city||"").trim();if(!C)continue;const E=(S.state||"").trim()||null,P=`${C.toLowerCase()}|${E||""}`,M=j.get(P);M?M.count++:j.set(P,{city:C,state:E,count:1})}return Array.from(j.values()).sort((S,C)=>C.count-S.count)},[n]);return _.useEffect(()=>{if(!(!s||!l||!a.current||i.current))return Id.accessToken=l,i.current=new Id.Map({container:a.current,style:"mapbox://styles/mapbox/light-v11",center:[-98.5795,39.8283],zoom:3.5}),i.current.addControl(new Id.NavigationControl,"top-right"),()=>{var j;(j=i.current)==null||j.remove(),i.current=null}},[s,l]),_.useEffect(()=>{const j=i.current;if(!j||u.length===0)return;const S=()=>{const E={type:"FeatureCollection",features:u.map(M=>({type:"Feature",properties:{id:M.id,name:M.name},geometry:{type:"Point",coordinates:[M.lng,M.lat]}}))},P=j.getSource("contacts-src");if(P?P.setData(E):(j.addSource("contacts-src",{type:"geojson",data:E}),j.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]}}),j.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}}),j.on("click","contacts-points",M=>{var O;const I=(O=M.features)==null?void 0:O[0];if(!I)return;const D=I.geometry.coordinates.slice();new Id.Popup({offset:12}).setLngLat(D).setHTML(`
${I.properties.name||"Contact"}
`).addTo(j)}),j.on("mouseenter","contacts-points",()=>{j.getCanvas().style.cursor="pointer"}),j.on("mouseleave","contacts-points",()=>{j.getCanvas().style.cursor=""})),j.getLayer("contacts-heat")&&j.setLayoutProperty("contacts-heat","visibility",v==="heat"?"visible":"none"),j.getLayer("contacts-points")&&(j.setPaintProperty("contacts-points","circle-opacity",v==="points"?.9:0),j.setLayoutProperty("contacts-points","visibility","visible")),u.length>0&&!j._fitDone){const M=new Id.LngLatBounds;u.forEach(I=>M.extend([I.lng,I.lat]));try{j.fitBounds(M,{padding:60,maxZoom:11,duration:600}),j._fitDone=!0}catch{}}};j.isStyleLoaded()?S():j.once("load",S)},[u,v]),e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"max-w-6xl w-[95vw] h-[90vh] p-0 flex flex-col",children:[e.jsx(Os,{className:"p-4 pb-2 border-b",children:e.jsxs(Ds,{className:"flex items-center gap-2",children:[e.jsx(gu,{className:"h-5 w-5 text-orange-500"}),"Geographic Heat Map",e.jsxs(Oe,{variant:"secondary",className:"ml-2",children:[u.length," mapped · ",b.length," cities"]})]})}),e.jsxs("div",{className:"flex-1 flex flex-col md:flex-row min-h-0",children:[e.jsx("div",{className:"flex-1 relative min-h-[300px]",children:c?e.jsx("div",{className:"h-full flex items-center justify-center",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):l?e.jsxs(e.Fragment,{children:[e.jsx("div",{ref:a,className:"absolute inset-0"}),e.jsxs("div",{className:"absolute top-3 left-3 flex flex-col gap-2 z-10",children:[e.jsxs("div",{className:"bg-background/95 backdrop-blur rounded-md shadow-md border p-1 flex",children:[e.jsxs(B,{size:"sm",variant:v==="heat"?"default":"ghost",onClick:()=>g("heat"),className:"h-8",children:[e.jsx(gu,{className:"h-3.5 w-3.5 mr-1"})," Heat"]}),e.jsxs(B,{size:"sm",variant:v==="points"?"default":"ghost",onClick:()=>g("points"),className:"h-8",children:[e.jsx(G4,{className:"h-3.5 w-3.5 mr-1"})," Pins"]})]}),f&&e.jsxs("div",{className:"bg-background/95 backdrop-blur rounded-md shadow-md border px-2.5 py-1.5 text-xs flex items-center gap-2",children:[e.jsx(Ct,{className:"h-3 w-3 animate-spin"}),"Mapping ",m.done," / ",m.total]})]})]}):e.jsxs("div",{className:"h-full flex flex-col items-center justify-center gap-3 p-6 text-center",children:[e.jsx(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(Xa,{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(Ji,{className:"flex-1",children:e.jsxs("div",{className:"p-2 space-y-1.5",children:[b.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground p-3 text-center",children:"No city data on your contacts yet. Add city/state to contacts to populate the map."}),b.slice(0,50).map((j,S)=>{var P;const C=((P=b[0])==null?void 0:P.count)||1,E=j.count/C*100;return e.jsx(ve,{className:"cursor-pointer hover:border-primary transition-colors overflow-hidden",onClick:()=>{r==null||r(j.city,j.state),t(!1)},children:e.jsxs(Me,{className:"p-2.5 relative",children:[e.jsx("div",{className:"absolute inset-y-0 left-0 bg-primary/10",style:{width:`${E}%`}}),e.jsxs("div",{className:"relative flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"text-sm font-medium truncate",children:[j.city,j.state?`, ${j.state}`:""]}),e.jsx("div",{className:"text-[10px] text-muted-foreground",children:S===0?"🔥 Hottest market":`Rank #${S+1}`})]}),e.jsx(Oe,{variant:"secondary",className:"shrink-0",children:j.count})]})]})},`${j.city}-${j.state}-${S}`)})]})})]})]})]})})}function VR(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 l2t({birthday:s,homeAnniversary:t,weddingAnniversary:n,className:r,contactId:a,contactName:i,contactAddress:l}){const o=Fn(),c=nze(s,"birthday",7),d=nze(t,"anniversary",7),u=nze(n||null,"anniversary",7);if(!c&&!d&&!u)return null;const h=(m,p,f)=>{f.stopPropagation();const y=new URLSearchParams;a&&y.set("contactId",a),i&&y.set("name",i),l&&y.set("address",l),(m==="home_anniversary"||m==="wedding_anniversary")&&p&&y.set("date",p),y.set("cardType",m),o(`/mission-control/card-studio?${y.toString()}`)};return e.jsxs("div",{className:At("flex flex-wrap gap-1",r),children:[c&&e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx(Oe,{variant:"secondary",className:At("text-[10px] gap-0.5 font-medium",c.daysUntil===0?"bg-pink-100 text-pink-700 dark:bg-pink-900/30 dark:text-pink-400 animate-pulse":"bg-pink-50 text-pink-600 dark:bg-pink-900/20 dark:text-pink-400"),children:c.label}),a&&e.jsxs("button",{onClick:m=>h("birthday",s,m),className:"inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded-full text-[9px] font-semibold bg-pink-500/15 text-pink-600 dark:text-pink-400 hover:bg-pink-500/25 transition-colors",title:"Send a birthday card",children:[e.jsx(ln,{className:"h-2.5 w-2.5"}),"Send Card"]})]}),d&&e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx(Oe,{variant:"secondary",className:At("text-[10px] gap-0.5 font-medium",d.daysUntil===0?"bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400 animate-pulse":"bg-blue-50 text-blue-600 dark:bg-blue-900/20 dark:text-blue-400"),children:d.label}),a&&e.jsxs("button",{onClick:m=>h("home_anniversary",t,m),className:"inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded-full text-[9px] font-semibold bg-blue-500/15 text-blue-600 dark:text-blue-400 hover:bg-blue-500/25 transition-colors",title:"Send an anniversary card",children:[e.jsx(ln,{className:"h-2.5 w-2.5"}),"Send Card"]})]}),u&&e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsxs(Oe,{variant:"secondary",className:At("text-[10px] gap-0.5 font-medium",u.daysUntil===0?"bg-rose-100 text-rose-700 dark:bg-rose-900/30 dark:text-rose-400 animate-pulse":"bg-rose-50 text-rose-600 dark:bg-rose-900/20 dark:text-rose-400"),children:["💍 ",u.label.replace(/^[^\w]+/,"")]}),a&&e.jsxs("button",{onClick:m=>h("wedding_anniversary",n||null,m),className:"inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded-full text-[9px] font-semibold bg-rose-500/15 text-rose-600 dark:text-rose-400 hover:bg-rose-500/25 transition-colors",title:"Send a wedding anniversary card",children:[e.jsx(ln,{className:"h-2.5 w-2.5"}),"Send Card"]})]})]})}function c2t({deal:s}){if(!s||!s.stage)return null;const{stage:t}=s;return e.jsxs(Oe,{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 d2t({count:s,className:t}){return!s||s<=0?null:e.jsxs(Oe,{variant:"outline",className:At("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(nP,{className:"h-2.5 w-2.5"}),s===1?"In drip":`${s} drips`]})}function ORn(){const s=ha();return at({queryKey:["contacts-campaign-counts",s],queryFn:async()=>{if(!s)return{};const{data:t,error:n}=await q.from("drip_campaign_enrollments").select("contact_id, status").eq("owner_user_id",s).eq("status","active");if(n)throw n;const r={};return(t||[]).forEach(a=>{a.contact_id&&(r[a.contact_id]=(r[a.contact_id]||0)+1)}),r},enabled:!!s,staleTime:6e4})}function zRn(){const s=ha();return at({queryKey:["contact-deals-map",s],queryFn:async()=>{const{data:t,error:n}=await q.from("deal_pipeline").select(` id, deal_name, contact_id, deal_type, expected_price, sale_price, stage:deal_pipeline_stages(id, name, color, icon, is_won_stage, is_lost_stage) `).not("contact_id","is",null);if(n)throw n;const r={};return(t||[]).forEach(a=>{a.contact_id&&!r[a.contact_id]&&(r[a.contact_id]=a)}),r},enabled:!!s})}const BRn="#6366F1";function u2t(s,t){return`color-mix(in srgb, ${s} ${t}%, transparent)`}function URn(s){return`color-mix(in oklab, ${s} 78%, hsl(var(--foreground)))`}function DYt({label:s,color:t,className:n,onClick:r,title:a}){const i=t||BRn,l=r?"button":"span";return e.jsxs(l,{type:r?"button":void 0,onClick:r,title:a??s,style:{backgroundColor:u2t(i,14),color:URn(i),boxShadow:`inset 0 0 0 1px ${u2t(i,22)}`},className:At("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 qRn({tags:s,max:t=2,className:n}){const[r,a]=_.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:At("flex flex-wrap items-center gap-1.5",n),children:[i.map(o=>{var c,d;return e.jsx(DYt,{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 h2t({contactId:s,compact:t=!1}){const{data:n}=rz(),{data:r}=_6n(s),a=nnt(),i=MKt(),l=N6n(),[o,c]=_.useState(!1),[d,u]=_.useState(""),h=_.useRef(null),m=new Set((r==null?void 0:r.map(g=>g.tag_id))||[]),p=(n==null?void 0:n.filter(g=>g.name.toLowerCase().includes(d.toLowerCase())))||[],f=n==null?void 0:n.find(g=>g.name.toLowerCase()===d.trim().toLowerCase()),y=async g=>{m.has(g.id)?await l.mutateAsync({contactId:s,tagId:g.id}):await i.mutateAsync({contactId:s,tagId:g.id})},v=async()=>{if(!(!d.trim()||f))try{const g=await a.mutateAsync({name:d.trim()});await i.mutateAsync({contactId:s,tagId:g.id}),u("")}catch{}};return e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[r==null?void 0:r.map(g=>{var b,j,S;return e.jsxs(Oe,{variant:"outline",className:"text-xs gap-1 pr-1",style:{borderColor:((b=g.tag)==null?void 0:b.color)||"#6366F1",color:((j=g.tag)==null?void 0:j.color)||"#6366F1"},children:[e.jsx(Ep,{className:"h-2.5 w-2.5"}),(S=g.tag)==null?void 0:S.name,e.jsx("button",{onClick:C=>{C.stopPropagation(),l.mutate({contactId:s,tagId:g.tag_id})},className:"ml-0.5 rounded-full hover:bg-accent p-0.5",children:e.jsx(Qn,{className:"h-2.5 w-2.5"})})]},g.id)}),e.jsxs(od,{open:o,onOpenChange:c,children:[e.jsx(ld,{asChild:!0,children:e.jsxs(B,{variant:"ghost",size:"sm",className:t?"h-6 w-6 p-0":"h-6 px-2 text-xs",onClick:g=>g.stopPropagation(),children:[e.jsx(rn,{className:"h-3 w-3"}),!t&&e.jsx("span",{className:"ml-1",children:"Tag"})]})}),e.jsxs(Qc,{className:"w-56 p-2",align:"start",onClick:g=>g.stopPropagation(),children:[e.jsx(xe,{ref:h,placeholder:"Search or create tag...",value:d,onChange:g=>u(g.target.value),onKeyDown:g=>{g.key==="Enter"&&d.trim()&&!f?(g.preventDefault(),v()):g.key==="Enter"&&f&&!m.has(f.id)&&(g.preventDefault(),y(f))},className:"h-8 text-sm mb-2"}),e.jsxs("div",{className:"max-h-[200px] overflow-y-auto space-y-0.5",children:[p.map(g=>e.jsxs("button",{onClick:()=>y(g),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:g.color}}),e.jsx("span",{className:"flex-1 text-left truncate",children:g.name}),m.has(g.id)&&e.jsx(ea,{className:"h-3.5 w-3.5 text-primary shrink-0"})]},g.id)),d.trim()&&!f&&e.jsxs("button",{onClick:v,className:"flex items-center gap-2 w-full px-2 py-1.5 rounded-md text-sm hover:bg-accent transition-colors text-primary",children:[e.jsx(rn,{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 m2t({contactId:s,tags:t,max:n=2}){return!t||t.length===0?null:e.jsx(qRn,{tags:t,max:n})}const Bce=["#6366F1","#8B5CF6","#EC4899","#EF4444","#F97316","#F59E0B","#10B981","#14B8A6","#06B6D4","#3B82F6","#6B7280","#1F2937"];function $Rn({open:s,onOpenChange:t}){const{data:n,isLoading:r}=rz(),a=nnt(),i=j6n(),l=w6n(),[o,c]=_.useState(""),[d,u]=_.useState(Bce[0]),[h,m]=_.useState(null),[p,f]=_.useState(""),[y,v]=_.useState(""),g=async()=>{if(o.trim())try{await a.mutateAsync({name:o.trim(),color:d}),c(""),u(Bce[0]),ia({title:"Tag created"})}catch(C){ia({title:"Error",description:C.message,variant:"destructive"})}},b=async C=>{if(p.trim())try{await i.mutateAsync({id:C,name:p.trim(),color:y}),m(null),ia({title:"Tag updated"})}catch(E){ia({title:"Error",description:E.message,variant:"destructive"})}},j=async(C,E)=>{if(await Xi(`Delete tag "${E}"? It will be removed from all contacts.`))try{await l.mutateAsync(C),ia({title:"Tag deleted"})}catch(P){ia({title:"Error",description:P.message,variant:"destructive"})}},S=C=>{m(C.id),f(C.name),v(C.color)};return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"max-w-md",children:[e.jsx(Os,{children:e.jsx(Ds,{children:"Manage Tags"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{placeholder:"New tag name...",value:o,onChange:C=>c(C.target.value),onKeyDown:C=>C.key==="Enter"&&g(),className:"flex-1 h-9"}),e.jsxs(B,{size:"sm",onClick:g,disabled:!o.trim()||a.isPending,className:"h-9",children:[e.jsx(rn,{className:"h-4 w-4 mr-1"}),"Add"]})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:Bce.map(C=>e.jsx("button",{onClick:()=>u(C),className:`h-6 w-6 rounded-full border-2 transition-transform ${d===C?"border-foreground scale-110":"border-transparent hover:scale-105"}`,style:{backgroundColor:C}},C))})]}),e.jsxs("div",{className:"mt-2 space-y-1 max-h-[320px] overflow-y-auto",children:[r&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"Loading..."}),(n==null?void 0:n.length)===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No tags yet. Create one above!"}),n==null?void 0:n.map(C=>e.jsx("div",{className:"flex items-center gap-2 p-2 rounded-lg hover:bg-accent/50 group",children:h===C.id?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex flex-wrap gap-1",children:Bce.map(E=>e.jsx("button",{onClick:()=>v(E),className:`h-5 w-5 rounded-full border-2 ${y===E?"border-foreground":"border-transparent"}`,style:{backgroundColor:E}},E))}),e.jsx(xe,{value:p,onChange:E=>f(E.target.value),onKeyDown:E=>E.key==="Enter"&&b(C.id),className:"flex-1 h-8 text-sm",autoFocus:!0}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>b(C.id),children:e.jsx(ea,{className:"h-4 w-4 text-primary"})}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>m(null),children:e.jsx(Qn,{className:"h-4 w-4"})})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"h-3.5 w-3.5 rounded-full shrink-0",style:{backgroundColor:C.color}}),e.jsx("span",{className:"flex-1 text-sm",children:C.name}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>S(C),children:e.jsx(Ya,{className:"h-3.5 w-3.5"})}),e.jsx(B,{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:()=>j(C.id,C.name),children:e.jsx(Sn,{className:"h-3.5 w-3.5"})})]})},C.id))]})]})})}function VRn({open:s,onOpenChange:t}){const{data:n,isLoading:r}=V9(),a=vet(),i=WUs(),l=KUs(),[o,c]=_.useState(""),[d,u]=_.useState(null),[h,m]=_.useState(""),p=async()=>{if(o.trim())try{await a.mutateAsync(o.trim()),c("")}catch(g){se.error(g.message||"Failed to add lead source")}},f=async g=>{if(h.trim())try{await i.mutateAsync({id:g,name:h.trim()}),u(null)}catch(b){se.error(b.message||"Failed to update")}},y=async(g,b)=>{if(await Xi(`Remove lead source "${b}"? Contacts using it will keep the label but it won't appear in new dropdowns.`))try{await l.mutateAsync(g)}catch(j){se.error(j.message||"Failed to remove")}},v=g=>{u(g.id),m(g.name)};return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"max-w-md",children:[e.jsx(Os,{children:e.jsx(Ds,{children:"Manage Lead Sources"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{placeholder:"New lead source name...",value:o,onChange:g=>c(g.target.value),onKeyDown:g=>g.key==="Enter"&&p(),className:"flex-1 h-9"}),e.jsxs(B,{size:"sm",onClick:p,disabled:!o.trim()||a.isPending,className:"h-9",children:[e.jsx(rn,{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(g=>e.jsx("div",{className:"flex items-center gap-2 p-2 rounded-lg hover:bg-accent/50 group",children:d===g.id?e.jsxs(e.Fragment,{children:[e.jsx(xe,{value:h,onChange:b=>m(b.target.value),onKeyDown:b=>b.key==="Enter"&&f(g.id),className:"flex-1 h-8 text-sm",autoFocus:!0}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>f(g.id),children:e.jsx(ea,{className:"h-4 w-4 text-primary"})}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>u(null),children:e.jsx(Qn,{className:"h-4 w-4"})})]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"flex-1 text-sm",children:g.name}),g.owner_user_id&&e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>v(g),children:e.jsx(Ya,{className:"h-3.5 w-3.5"})}),e.jsx(B,{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:()=>y(g.id,g.name),children:e.jsx(Sn,{className:"h-3.5 w-3.5"})})]}),!g.owner_user_id&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Default"})]})},g.id))]})]})})}function RYt({value:s,onChange:t,label:n="Lead Source"}){const{data:r}=V9(),a=vet(),[i,l]=_.useState(!1),[o,c]=_.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(J,{children:n}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(is,{value:s||"_none",onValueChange:u=>t(u==="_none"?"":u),children:[e.jsx(rs,{className:"flex-1",children:e.jsx(ls,{placeholder:"Select lead source"})}),e.jsxs(as,{children:[e.jsx(He,{value:"_none",children:"No source"}),r==null?void 0:r.map(u=>e.jsx(He,{value:u.id,children:u.name},u.id))]})]}),e.jsx(B,{type:"button",variant:"outline",size:"icon",className:"shrink-0",onClick:()=>l(!i),children:i?e.jsx(Qn,{className:"h-4 w-4"}):e.jsx(rn,{className:"h-4 w-4"})})]}),i&&e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{placeholder:"New lead source name...",value:o,onChange:u=>c(u.target.value),onKeyDown:u=>{u.key==="Enter"&&(u.preventDefault(),d())},className:"flex-1"}),e.jsx(B,{type:"button",size:"sm",onClick:d,disabled:!o.trim()||a.isPending,children:"Add"})]})]})}function gWe({contactId:s,currentSpouseContactId:t,currentSpouseName:n,currentSpouseEmail:r,onLink:a,onUnlink:i,isEditing:l}){const o=Fn(),c=ha(),[d,u]=_.useState(!1),[h,m]=_.useState(""),{data:p}=at({queryKey:["innercircle-contact-spouse",t],queryFn:async()=>{const{data:y,error:v}=await q.from("innercircle_contacts").select("id, first_name, last_name, email, phone, birthday").eq("id",t).maybeSingle();if(v)throw v;return y},enabled:!!t}),{data:f}=at({queryKey:["spouse-search",c,s,h],queryFn:async()=>{let y=q.from("innercircle_contacts").select("id, first_name, last_name, email, phone").eq("owner_user_id",c).is("synced_source",null).neq("id",s).order("first_name").limit(20);if(h.trim()){const b=h.replace(/[,()%]/g," ").trim();b&&(y=y.or(`first_name.ilike.%${b}%,last_name.ilike.%${b}%,email.ilike.%${b}%,phone.ilike.%${b}%`))}const{data:v,error:g}=await y;if(g)throw g;return v},enabled:d&&!!c});if(t&&p){const y=`${p.first_name} ${p.last_name||""}`.trim();return e.jsxs("div",{className:"space-y-1",children:[e.jsx(J,{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(Fo,{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:y}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:[p.phone,p.email].filter(Boolean).join(" · ")||"No contact info"})]}),l&&e.jsxs(B,{variant:"ghost",size:"sm",onClick:i,className:"shrink-0 h-7 px-2",children:[e.jsx(h7,{className:"h-3.5 w-3.5 mr-1"}),"Unlink"]}),!l&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>o(`/mission-control/contacts/${p.id}`),className:"shrink-0 h-7 px-2",children:e.jsx(La,{className:"h-3.5 w-3.5"})})]})]})}return!t&&(n||r)?e.jsxs("div",{className:"space-y-1",children:[e.jsx(J,{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(Fo,{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(od,{open:d,onOpenChange:u,children:[e.jsx(ld,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"shrink-0 h-7 px-2",children:[e.jsx(vd,{className:"h-3.5 w-3.5 mr-1"}),"Link Contact"]})}),e.jsx(Qc,{className:"w-72 p-2",align:"end",children:e.jsx(p2t,{search:h,setSearch:m,results:f,onSelect:y=>{a(y),u(!1),m("")}})})]})]})]}):l?e.jsxs("div",{className:"space-y-1",children:[e.jsx(J,{className:"text-sm font-medium",children:"Spouse / Partner"}),e.jsxs(od,{open:d,onOpenChange:u,children:[e.jsx(ld,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:"w-full justify-start text-muted-foreground font-normal h-10",children:[e.jsx(vd,{className:"h-4 w-4 mr-2"}),"Link an existing contact as spouse..."]})}),e.jsx(Qc,{className:"w-72 p-2",align:"start",children:e.jsx(p2t,{search:h,setSearch:m,results:f,onSelect:y=>{a(y),u(!1),m("")}})})]})]}):null}function p2t({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(Lr,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(xe,{value:s,onChange:a=>t(a.target.value),placeholder:"Search contacts...",className:"pl-7 h-8 text-sm",autoFocus:!0})]}),e.jsx(Ji,{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 HRn={warm:"stroke-emerald-500",cooling:"stroke-amber-500","at-risk":"stroke-red-500"},GRn={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 WRn({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:At("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:HRn[t]})]}),e.jsx("span",{className:At("absolute inset-0 flex items-center justify-center font-semibold tabular-nums",GRn[t],n>=56?"text-lg":"text-[11px]"),children:o})]})}const Uce=new Map;async function KRn(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 YRn(s,t=256){const n=s.trim().toLowerCase();if(!n||!n.includes("@"))return null;const r=`${n}|${t}`;if(Uce.has(r))return Uce.get(r)??null;try{const i=`https://gravatar.com/avatar/${await KRn(n)}?s=${t}&d=404`;return Uce.set(r,i),i}catch{return Uce.set(r,null),null}}function ZRn(s,t=256){const[n,r]=_.useState(null);return _.useEffect(()=>{let a=!0;if(!s){r(null);return}return YRn(s,t).then(i=>{a&&r(i)}),()=>{a=!1}},[s,t]),n}function knt({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=ZRn(n?null:r,Math.max(64,a*2)),[u,h]=_.useState(!1);_.useEffect(()=>h(!1),[d]);const m=n||(u?null:d);return e.jsx("div",{className:At("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 XRn({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(ag,{children:[e.jsx(ig,{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(In,{className:"h-3 w-3"})})}),e.jsx(Nx,{children:r})]})}function QRn({totalLabel:s,stats:t,search:n,onSearchChange:r,onAddContact:a,onImportCsv:i,onImportPhone:l,onManageTags:o,onHeatMap:c,viewMode:d="my",onViewModeChange:u,showTeamTab:h,showLeadPondTab:m,extraActions:p}){const f=!!u&&(h||m);return e.jsx("section",{className:"hub-ink relative overflow-hidden rounded-2xl p-5 sm:p-6",children:e.jsxs("div",{className:"relative flex flex-col gap-5",children:[e.jsxs("div",{className:"flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-xs uppercase tracking-wider hub-ink-muted",children:"Agent OS"}),e.jsx("h1",{className:"mt-1 text-2xl font-bold sm:text-3xl",children:"Contacts"}),e.jsx("p",{className:"mt-1 text-sm hub-ink-muted",children:s})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("button",{onClick:a,className:"inline-flex items-center gap-2 rounded-full bg-background px-4 py-2 text-sm font-semibold text-foreground shadow-sm transition-transform hover:scale-[1.02]",children:[e.jsx(rn,{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(gu,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Heat Map"]}),e.jsxs(tu,{children:[e.jsx(su,{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(Oa,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Import",e.jsx(tl,{className:"h-3.5 w-3.5 opacity-70"})]})}),e.jsxs(Od,{align:"end",children:[e.jsxs(ca,{onClick:i,children:[e.jsx(Oa,{className:"mr-2 h-4 w-4"})," Import CSV"]}),e.jsxs(ca,{onClick:l,children:[e.jsx(p1,{className:"mr-2 h-4 w-4"})," Import from Phone"]}),e.jsxs(ca,{onClick:o,children:[e.jsx(Ep,{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(Lr,{className:"pointer-events-none absolute left-3.5 top-1/2 h-4 w-4 -translate-y-1/2 opacity-70"}),e.jsx(xe,{value:n,onChange:y=>r(y.target.value),placeholder:"Search by name, email, phone, or notes...",className:"h-11 rounded-xl border-transparent bg-white/10 pl-10 text-current placeholder:text-current/50 focus-visible:ring-2 focus-visible:ring-white/30"})]}),f&&e.jsx("div",{className:"hub-glass inline-flex shrink-0 items-center gap-1 rounded-xl p-1",children:[{key:"my",label:"Mine",icon:In,show:!0},{key:"team",label:"Team",icon:In,show:!!h},{key:"lead-pond",label:"Pond",icon:m1,show:!!m}].filter(y=>y.show).map(y=>e.jsxs("button",{onClick:()=>u==null?void 0:u(y.key),className:At("inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-xs font-semibold transition-colors",d===y.key?"bg-background text-foreground shadow-sm":"hub-ink-muted"),children:[e.jsx(y.icon,{className:"h-3.5 w-3.5"}),y.label]},y.key))})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 sm:grid-cols-4",children:t.map(y=>e.jsxs("button",{onClick:y.onClick,className:At("hub-glass rounded-xl px-3 py-2.5 text-left transition-colors",y.active&&"ring-2 ring-white/40"),children:[e.jsx("span",{className:"text-xl font-bold",children:y.value}),e.jsx("p",{className:"mt-0.5 text-[11px] hub-ink-muted",children:y.label})]},y.label))})]})})}function JRn({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(cn,{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(cn,{className:"h-9 w-9 rounded-full"}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(cn,{className:"h-3.5 w-36"}),e.jsx(cn,{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(cn,{className:"h-3.5 w-20"})},i))]},r))})}function eFn({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(cn,{className:"h-10 w-10 rounded-full"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(cn,{className:"h-4 w-2/5"}),e.jsx(cn,{className:"h-3 w-3/5"})]})]}),e.jsxs("div",{className:"mt-3 flex gap-2",children:[e.jsx(cn,{className:"h-6 w-16 rounded-full"}),e.jsx(cn,{className:"h-6 w-20 rounded-full"})]})]},n))})}function f2t({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 FYt(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 x2t(s){if(!s)return null;const t=Ru(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:Pl,color:"text-violet-600 dark:text-violet-400",match:s=>s.relationshipScore.daysSinceTouch===null},{key:"stale-90",title:"Stale 90+ Days",icon:Gr,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:sj,color:"text-cyan-600 dark:text-cyan-400",match:s=>s.relationshipScore.status==="cooling"},{key:"birthdays-soon",title:"Birthdays Soon",icon:Bf,color:"text-pink-600 dark:text-pink-400",match:(s,t)=>t.daysToBirthday!==null&&t.daysToBirthday<=30},{key:"anniversary-soon",title:"Home Anniversary",icon:Jr,color:"text-emerald-600 dark:text-emerald-400",match:(s,t)=>t.daysToAnniv!==null&&t.daysToAnniv<=30},{key:"has-deal",title:"Active Deal",icon:Cx,color:"text-teal-700 dark:text-teal-400",match:(s,t)=>t.hasDeal},{key:"website-active",title:"Active on Site",icon:sl,color:"text-indigo-600 dark:text-indigo-400",match:()=>!1},{key:"vips",title:"VIPs",icon:un,color:"text-amber-600 dark:text-amber-300",match:s=>s.relationshipScore.score>=80},{key:"active-buyers",title:"Active Buyers",icon:Lr,color:"text-sky-600 dark:text-sky-400",match:(s,t)=>t.hasCriteria},{key:"missing-criteria",title:"No Home Search",icon:t$,color:"text-orange-600 dark:text-orange-400",match:(s,t)=>!t.hasCriteria},{key:"missing-info",title:"Missing Info",icon:xl,color:"text-slate-600 dark:text-slate-400",match:s=>FYt(s)}];function tFn({contacts:s,contactDealsMap:t,websiteActiveIds:n,criteriaContactIds:r,totalCount:a,activeKey:i,onSelectSegment:l,currentFilters:o,currentSortBy:c,activeViewId:d,onApplyView:u,onClearAll:h}){const{data:m}=rnt(),p=PKt(),f=LKt(),[y,v]=_.useState(!1),[g,b]=_.useState(""),j=_.useMemo(()=>{const P={"needs-attention":0,cooling:0,"never-contacted":0,"stale-90":0,"birthdays-soon":0,"anniversary-soon":0,"has-deal":0,"website-active":n.size,"missing-info":0,vips:0,"active-buyers":0,"missing-criteria":0};if(!s)return P;for(const M of s){const I={hasDeal:!!(t&&t[M.id]),daysToBirthday:x2t(M.birthday),daysToAnniv:x2t(M.home_anniversary),hasCriteria:!!(r!=null&&r.has(M.id))};for(const D of g2t)D.key!=="website-active"&&D.match(M,I)&&P[D.key]++}return P},[s,t,n,r]),S=!!o.search||!!o.type&&o.type!=="all"||!!o.status&&o.status!=="all"||!!o.behavior&&Object.values(o.behavior).some(P=>P!==void 0&&P!==!1),C=async()=>{g.trim()&&(await p.mutateAsync({name:g.trim(),filters:o,sort_by:c}),b(""),v(!1))},E="inline-flex items-center gap-1.5 h-8 shrink-0 rounded-full border px-3 text-xs font-medium transition-colors whitespace-nowrap";return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2 overflow-x-auto pb-1 -mx-1 px-1 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",children:[e.jsxs("button",{type:"button",onClick:h,className:At(E,!i&&!d?"bg-primary text-primary-foreground border-primary":"bg-card hover:bg-accent border-border"),children:[e.jsx(In,{className:"h-3.5 w-3.5"}),"All Contacts",e.jsx("span",{className:"tabular-nums opacity-70",children:a.toLocaleString()})]}),m==null?void 0:m.map(P=>{const M=d===P.id;return e.jsxs("div",{className:At(E,"group pr-1",M?"bg-primary text-primary-foreground border-primary":"bg-card hover:bg-accent border-border"),children:[e.jsx("button",{type:"button",onClick:()=>u(P.id,P.filters,P.sort_by),children:P.name}),e.jsx("button",{type:"button","aria-label":`Delete view ${P.name}`,className:"h-5 w-5 rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity hover:bg-foreground/10",onClick:()=>{f.mutate(P.id),M&&h()},children:e.jsx(Qn,{className:"h-3 w-3"})})]},P.id)}),e.jsx("div",{className:"h-5 w-px bg-border shrink-0"}),g2t.map(P=>{const M=P.icon,I=j[P.key],D=i===P.key;return e.jsxs("button",{type:"button",onClick:()=>l(D?null:P.key),"aria-pressed":D,className:At(E,D?"bg-primary text-primary-foreground border-primary":"bg-card hover:bg-accent border-border",!D&&I===0&&"opacity-55"),children:[e.jsx(M,{className:At("h-3.5 w-3.5",D?"":P.color)}),P.title,e.jsx("span",{className:"tabular-nums opacity-70",children:I.toLocaleString()})]},P.key)}),e.jsxs(B,{variant:"ghost",size:"sm",className:"h-8 gap-1.5 text-xs shrink-0",disabled:!S,onClick:()=>v(!0),children:[e.jsx(HM,{className:"h-3.5 w-3.5"}),"Save view"]})]}),e.jsx(Ls,{open:y,onOpenChange:v,children:e.jsxs(Ps,{className:"sm:max-w-sm",children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Save this view"}),e.jsx(_r,{children:"Your current search, filters, and sorting are saved as a one-click chip."})]}),e.jsx(xe,{autoFocus:!0,placeholder:"e.g. Past clients cooling off",value:g,onChange:P=>b(P.target.value),onKeyDown:P=>P.key==="Enter"&&C()}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>v(!1),children:"Cancel"}),e.jsx(B,{onClick:C,disabled:!g.trim()||p.isPending,children:"Save view"})]})]})})]})}const y2t=[{key:"relationship",label:"Relationship"},{key:"buyerCriteria",label:"Looking For"},{key:"stage",label:"Stage"},{key:"leadSource",label:"Lead Source"},{key:"tags",label:"Tags"},{key:"lastTouch",label:"Last Touch"},{key:"nextAction",label:"Next Action"},{key:"dealValue",label:"Pipeline Value"},{key:"email",label:"Email"},{key:"phone",label:"Phone"},{key:"address",label:"Address"},{key:"birthday",label:"Birthday"}],rze={relationship:!0,buyerCriteria:!0,stage:!0,leadSource:!0,tags:!0,lastTouch:!0,nextAction:!0,dealValue:!0,email:!1,phone:!1,address:!1,birthday:!1},v2t="innercircle:contact-columns:v1";function sFn(){const[s,t]=_.useState(()=>{try{const a=localStorage.getItem(v2t);if(a)return{...rze,...JSON.parse(a)}}catch{}return rze});_.useEffect(()=>{try{localStorage.setItem(v2t,JSON.stringify(s))}catch{}},[s]);const n=_.useCallback(a=>{t(i=>({...i,[a]:!i[a]}))},[]),r=_.useCallback(()=>t(rze),[]);return{columns:s,toggle:n,reset:r}}function nFn({columns:s,onToggle:t,onReset:n}){const r=y2t.filter(a=>s[a.key]).length;return e.jsxs(od,{children:[e.jsx(ld,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"h-8 gap-1.5 rounded-lg text-xs",children:[e.jsx(a6,{className:"h-3.5 w-3.5"}),"Columns",e.jsx(Oe,{variant:"secondary",className:"h-5 px-1.5 text-[10px]",children:r})]})}),e.jsxs(Qc,{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(Tx,{className:"h-3 w-3"}),"Reset"]})]}),e.jsx("div",{className:"max-h-[320px] overflow-y-auto space-y-0.5",children:y2t.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($a,{checked:s[a.key],className:"pointer-events-none"}),e.jsx("span",{className:"flex-1 text-left",children:a.label})]},a.key))}),e.jsx("p",{className:"px-2 pt-2 text-[11px] text-muted-foreground",children:"Name and actions are always shown."})]})]})}const R$=1e3;function OYt(){const s=ha();return at({queryKey:["contact-criteria-map",s],enabled:!!s,staleTime:60*1e3,queryFn:async()=>{const t=[];for(let r=0;;r+=R$){const{data:a,error:i}=await q.from("contact_property_alerts").select("id, contact_id, is_active, min_price, max_price, min_beds, min_baths, min_sqft, max_sqft, cities, zip_codes, property_types, frequency, last_sent_at").eq("owner_user_id",s).range(r,r+R$-1);if(i)throw i;const l=a||[];if(t.push(...l),l.length{const n=new Date(Date.now()-6048e5).toISOString(),r=[];for(let o=0;;o+=R$){const{data:c,error:d}=await q.from("contact_property_alerts").select("id, contact_id").eq("owner_user_id",t).range(o,o+R$-1);if(d)throw d;const u=c||[];if(r.push(...u),u.length[o.id,o.contact_id])),i={},l=r.map(o=>o.id);for(let o=0;o{const i={contact_id:n,owner_user_id:s,is_active:a.is_active??!0,min_price:a.min_price||null,max_price:a.max_price||null,min_beds:a.min_beds||null,min_baths:a.min_baths||null,min_sqft:a.min_sqft||null,max_sqft:a.max_sqft||null,cities:a.cities||[],zip_codes:a.zip_codes||[],property_types:a.property_types||[],frequency:a.frequency||"daily"};if(r){const{error:l}=await q.from("contact_property_alerts").update(i).eq("id",r);if(l)throw l}else{const{error:l}=await q.from("contact_property_alerts").insert(i);if(l)throw l}},onSuccess:(n,r)=>{t.invalidateQueries({queryKey:["contact-criteria-map"]}),t.invalidateQueries({queryKey:["contact-property-alert",r.contactId]})}})}function iFn(){const s=Bt();return mt({mutationFn:async({id:t})=>{const{error:n}=await q.from("contact_property_alerts").delete().eq("id",t);if(n)throw n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["contact-criteria-map"]}),n.contactId&&s.invalidateQueries({queryKey:["contact-property-alert",n.contactId]})}})}const dq=s=>String(s??"").trim().toLowerCase();function oFn(s,t){const n=dq(s).replace(/[\s_-]+/g,""),r=dq(t).replace(/[\s_-]+/g,"");return!n||!r?!1:n===r||n.includes(r)||r.includes(n)}function lFn(s,t){var m,p,f;const n=[],r=[],a=t.price??null,i=t.bedrooms??null,l=t.bathrooms??null,o=t.sqft??null;if((((m=s.cities)==null?void 0:m.length)||0)>0||(((p=s.zip_codes)==null?void 0:p.length)||0)>0){const y=!!t.city&&(s.cities||[]).some(g=>dq(g)===dq(t.city)),v=!!t.zip&&(s.zip_codes||[]).some(g=>dq(g)===dq(t.zip));y?n.push(`Wants ${t.city}`):v?n.push(`Wants ${t.zip}`):(t.city||t.zip)&&r.push(`Looking in ${[...s.cities||[],...s.zip_codes||[]].slice(0,3).join(", ")}`)}a!==null&&(s.min_price&&as.max_price?r.push(`Over their $${Math.round(s.max_price/1e3)}k budget`):(s.min_price||s.max_price)&&n.push("In their price range")),s.min_beds&&(i!==null&&i0&&(s.min_sqft&&os.max_sqft?r.push("Over their max sqft"):(s.min_sqft||s.max_sqft)&&n.push("Size fits")),(((f=s.property_types)==null?void 0:f.length)||0)>0&&t.propertyType&&(s.property_types.some(v=>oFn(v,t.propertyType))?n.push(String(t.propertyType).replace(/_/g," ")):r.push(`Wants ${s.property_types.slice(0,2).join(" / ")}`));const d=r.length===0&&n.length>0,u=n.length+r.length,h=u===0?0:Math.round(n.length/u*100);return{matches:d,score:h,reasons:n,misses:r}}function cFn(s,t,n,r={}){const a=[];for(const i of s){const l=t[i.id];if(!l)continue;const o=lFn(l,n);(o.matches||r.includeNearMatches&&o.misses.length===1&&o.score>=50)&&a.push({contact:i,criteria:l,result:o})}return a.sort((i,l)=>l.result.score-i.result.score||i.result.misses.length-l.result.misses.length)}const qce=s=>s>=1e3?`$${Math.round(s/1e3)}k`:`$${s}`;function zYt(s){var t,n,r;return s?!!(s.min_price||s.max_price||s.min_beds||s.min_baths||s.min_sqft||s.max_sqft||(t=s.cities)!=null&&t.length||(n=s.zip_codes)!=null&&n.length||(r=s.property_types)!=null&&r.length):!1}function dFn(s){var r;if(!s)return"";const t=[];s.min_price&&s.max_price?t.push(`${qce(s.min_price)}–${qce(s.max_price)}`):s.max_price?t.push(`up to ${qce(s.max_price)}`):s.min_price&&t.push(`${qce(s.min_price)}+`),s.min_beds&&t.push(`${s.min_beds}+ bd`),s.min_baths&&t.push(`${s.min_baths}+ ba`),s.min_sqft&&t.push(`${s.min_sqft.toLocaleString()}+ sqft`);const n=[...s.cities||[],...s.zip_codes||[]];return n.length&&t.push(n.length<=2?n.join(", "):`${n.slice(0,2).join(", ")} +${n.length-2}`),!n.length&&((r=s.property_types)!=null&&r.length)&&t.push(s.property_types.slice(0,2).join(", ")),t.join(" · ")}function b2t({criteria:s,onEdit:t,showAlertState:n,matchCount:r,className:a,compact:i}){const l=dFn(s);return zYt(s)?e.jsxs("button",{type:"button",onClick:t?c=>{c.stopPropagation(),t()}:void 0,className:At("group/crit inline-flex max-w-full items-center gap-1.5 rounded-md px-1.5 py-0.5 text-left",t&&"hover:bg-accent transition-colors",a),title:l,children:[n?s!=null&&s.is_active?e.jsx(Rg,{className:"h-3.5 w-3.5 shrink-0 text-emerald-600 dark:text-emerald-400"}):e.jsx(cS,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):e.jsx(Lr,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),e.jsx("span",{className:At("truncate",i?"text-[11px]":"text-xs","text-foreground/80"),children:l}),!!r&&r>0&&e.jsxs("span",{className:"shrink-0 rounded-full bg-primary/10 px-1.5 text-[10px] font-semibold text-primary tabular-nums",children:[r," new"]})]}):t?e.jsxs("button",{type:"button",onClick:c=>{c.stopPropagation(),t()},className:At("inline-flex items-center gap-1 whitespace-nowrap rounded-full border border-dashed border-primary/40 px-2 py-0.5","text-[11px] text-muted-foreground hover:bg-primary/5 hover:text-primary transition-colors",a),children:[e.jsx(rn,{className:"h-3 w-3"}),"Add home search"]}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"—"})}const BYt=["Single Family","Condo","Townhouse","Multi-Family","Land","Commercial"];function uFn(){const s=ha();return at({queryKey:["agent-lead-site-config",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("lead_sites").select("theme_config, mls_market_area").eq("agent_id",s).eq("is_active",!0).order("created_at",{ascending:!0}).limit(1).maybeSingle();if(n||!t)return{cities:[],zipCodes:[]};const r=t.theme_config||{},a=Array.isArray(r.searchCities)?r.searchCities:[];t.mls_market_area&&!a.includes(t.mls_market_area)&&a.unshift(t.mls_market_area);const i=Array.isArray(r.searchZipCodes)?r.searchZipCodes:[];return{cities:a,zipCodes:i}}})}function _2t({value:s,onChange:t,onAdd:n,suggestions:r,placeholder:a,icon:i}){const[l,o]=_.useState(!1),c=_.useRef(null),d=_.useRef(null);_.useEffect(()=>{const h=m=>{d.current&&!d.current.contains(m.target)&&o(!1)};return document.addEventListener("mousedown",h),()=>document.removeEventListener("mousedown",h)},[]);const u=r.filter(h=>h.toLowerCase().includes(s.trim().toLowerCase()));return e.jsxs("div",{className:"relative",ref:d,children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx("div",{className:"flex-1",children:e.jsx(xe,{value:s,onChange:h=>{t(h.target.value),o(!0)},onFocus:()=>o(!0),onKeyDown:h=>{h.key==="Enter"&&(h.preventDefault(),n(s),o(!1))},placeholder:a})}),e.jsx(B,{type:"button",variant:"outline",size:"sm",onClick:()=>n(s),children:e.jsx(rn,{className:"h-4 w-4"})})]}),l&&u.length>0&&e.jsx("div",{ref:c,className:"absolute z-50 mt-1 w-full max-h-60 overflow-y-auto rounded-md border bg-popover shadow-md",children:u.map(h=>e.jsxs("button",{type:"button",className:"w-full text-left px-3 py-2 text-sm hover:bg-accent hover:text-accent-foreground transition-colors flex items-center gap-2",onClick:()=>{n(h),o(!1)},children:[i||e.jsx(Xa,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}),h]},h))})]})}function UYt({value:s,onChange:t,hasIdx:n=!0,idxNote:r}){const[a,i]=_.useState(""),[l,o]=_.useState(""),{data:c}=uFn(),d=((c==null?void 0:c.cities)||[]).filter(f=>{var y;return!((y=s.cities)!=null&&y.includes(f))}),u=((c==null?void 0:c.zipCodes)||[]).filter(f=>{var y;return!((y=s.zip_codes)!=null&&y.includes(f))}),h=f=>{var v;const y=f.trim();y&&!((v=s.cities)!=null&&v.includes(y))&&t(g=>({...g,cities:[...g.cities||[],y]})),i("")},m=f=>{var v;const y=f.trim();y&&!((v=s.zip_codes)!=null&&v.includes(y))&&t(g=>({...g,zip_codes:[...g.zip_codes||[],y]})),o("")},p=f=>{t(y=>{const v=y.property_types||[];return{...y,property_types:v.includes(f)?v.filter(g=>g!==f):[...v,f]}})};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsxs(J,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(yd,{className:"h-3.5 w-3.5"})," Price Range"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(xe,{type:"number",placeholder:"Min price",value:s.min_price??"",onChange:f=>t(y=>({...y,min_price:f.target.value?Number(f.target.value):null}))}),e.jsx(xe,{type:"number",placeholder:"Max price",value:s.max_price??"",onChange:f=>t(y=>({...y,max_price:f.target.value?Number(f.target.value):null}))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs(J,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(q4,{className:"h-3.5 w-3.5"})," Min Beds"]}),e.jsxs(is,{value:s.min_beds?String(s.min_beds):"any",onValueChange:f=>t(y=>({...y,min_beds:f==="any"?null:Number(f)})),children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Any"})}),e.jsxs(as,{children:[e.jsx(He,{value:"any",children:"Any"}),[1,2,3,4,5].map(f=>e.jsxs(He,{value:String(f),children:[f,"+"]},f))]})]})]}),e.jsxs("div",{children:[e.jsxs(J,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(S0,{className:"h-3.5 w-3.5"})," Min Baths"]}),e.jsxs(is,{value:s.min_baths?String(s.min_baths):"any",onValueChange:f=>t(y=>({...y,min_baths:f==="any"?null:Number(f)})),children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Any"})}),e.jsxs(as,{children:[e.jsx(He,{value:"any",children:"Any"}),[1,1.5,2,2.5,3,4].map(f=>e.jsxs(He,{value:String(f),children:[f,"+"]},f))]})]})]})]}),e.jsxs("div",{children:[e.jsxs(J,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(W4,{className:"h-3.5 w-3.5"})," Square Feet"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(xe,{type:"number",placeholder:"Min sqft",value:s.min_sqft??"",onChange:f=>t(y=>({...y,min_sqft:f.target.value?Number(f.target.value):null}))}),e.jsx(xe,{type:"number",placeholder:"Max sqft",value:s.max_sqft??"",onChange:f=>t(y=>({...y,max_sqft:f.target.value?Number(f.target.value):null}))})]})]}),e.jsxs("div",{children:[e.jsxs(J,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(Xa,{className:"h-3.5 w-3.5"})," Cities"]}),e.jsx(_2t,{value:a,onChange:i,onAdd:h,suggestions:d,placeholder:"Type a city and press Enter..."}),s.cities&&s.cities.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-2",children:s.cities.map(f=>e.jsxs(Oe,{variant:"secondary",className:"gap-1",children:[f,e.jsx("button",{type:"button",onClick:()=>t(y=>{var v;return{...y,cities:(v=y.cities)==null?void 0:v.filter(g=>g!==f)}}),children:e.jsx(Qn,{className:"h-3 w-3"})})]},f))})]}),e.jsxs("div",{children:[e.jsx(J,{className:"mb-1.5",children:"Zip Codes"}),e.jsx(_2t,{value:l,onChange:o,onAdd:m,suggestions:u,placeholder:"Type a zip code and press Enter...",icon:e.jsx("span",{className:"text-xs text-muted-foreground font-mono",children:"#"})}),s.zip_codes&&s.zip_codes.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-2",children:s.zip_codes.map(f=>e.jsxs(Oe,{variant:"secondary",className:"gap-1",children:[f,e.jsx("button",{type:"button",onClick:()=>t(y=>{var v;return{...y,zip_codes:(v=y.zip_codes)==null?void 0:v.filter(g=>g!==f)}}),children:e.jsx(Qn,{className:"h-3 w-3"})})]},f))})]}),e.jsxs("div",{children:[e.jsxs(J,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(Jr,{className:"h-3.5 w-3.5"})," Property Types"]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:BYt.map(f=>{var y;return e.jsx(Oe,{variant:(y=s.property_types)!=null&&y.includes(f)?"default":"outline",className:"cursor-pointer",onClick:()=>p(f),children:f},f)})})]}),n?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Email new matching listings"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Automatic alerts from your MLS feed"})]}),e.jsx(fn,{checked:s.is_active??!0,onCheckedChange:f=>t(y=>({...y,is_active:f}))})]}),e.jsxs("div",{children:[e.jsx(J,{className:"mb-1.5",children:"Frequency"}),e.jsxs(is,{value:s.frequency||"daily",onValueChange:f=>t(y=>({...y,frequency:f})),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"daily",children:"Daily"}),e.jsx(He,{value:"weekly",children:"Weekly"})]})]})]})]}):e.jsxs("div",{className:"rounded-lg border border-dashed bg-muted/40 p-3 space-y-1.5",children:[e.jsxs("p",{className:"text-xs text-muted-foreground flex items-start gap-2",children:[e.jsx(hS,{className:"h-3.5 w-3.5 mt-0.5 shrink-0"}),e.jsx("span",{children:"Saved here so you can match listings to this contact any time. Automatic new-listing emails need an IDX website."})]}),r]})]})}function hFn({open:s,onOpenChange:t,contactId:n,contactName:r,existing:a}){const{hasIdx:i}=lf(),l=aFn(),o=iFn(),[c,d]=_.useState({});_.useEffect(()=>{s&&d({is_active:(a==null?void 0:a.is_active)??!0,min_price:(a==null?void 0:a.min_price)??null,max_price:(a==null?void 0:a.max_price)??null,min_beds:(a==null?void 0:a.min_beds)??null,min_baths:(a==null?void 0:a.min_baths)??null,min_sqft:(a==null?void 0:a.min_sqft)??null,max_sqft:(a==null?void 0:a.max_sqft)??null,cities:(a==null?void 0:a.cities)??[],zip_codes:(a==null?void 0:a.zip_codes)??[],property_types:(a==null?void 0:a.property_types)??[],frequency:(a==null?void 0:a.frequency)??"daily"})},[s,a]);const u=async()=>{try{await l.mutateAsync({contactId:n,existingId:(a==null?void 0:a.id)??null,values:c}),se.success(`Home search saved for ${r}`),t(!1)}catch(m){se.error((m==null?void 0:m.message)||"Could not save home search")}},h=async()=>{if(a!=null&&a.id)try{await o.mutateAsync({id:a.id,contactId:n}),se.success("Home search removed"),t(!1)}catch(m){se.error((m==null?void 0:m.message)||"Could not remove home search")}};return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsxs(Ds,{children:["Home search for ",r]}),e.jsx(_r,{children:"What are they looking for? This shows on your contacts dashboard so you can match new listings to them."})]}),e.jsx(UYt,{value:c,onChange:d,hasIdx:i,idxNote:e.jsx(B,{asChild:!0,variant:"link",size:"sm",className:"h-auto p-0 text-xs",children:e.jsx(ir,{to:"/mission-control/website",children:"Explore IDX websites"})})}),e.jsxs(yr,{className:"gap-2 sm:gap-2",children:[(a==null?void 0:a.id)&&e.jsxs(B,{variant:"ghost",onClick:h,disabled:o.isPending,className:"text-destructive hover:text-destructive mr-auto",children:[o.isPending?e.jsx(Ct,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Sn,{className:"h-4 w-4 mr-1"}),"Remove"]}),e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{onClick:u,disabled:l.isPending,children:[l.isPending?e.jsx(Ct,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Ho,{className:"h-4 w-4 mr-1"}),"Save"]})]})]})})}const mFn={city:"",state:"",zip:"",price:null,bedrooms:null,bathrooms:null,sqft:null,propertyType:"",address:""};function pFn({open:s,onOpenChange:t,contacts:n}){const r=Fn(),{data:a}=OYt(),{data:i}=set(),[l,o]=_.useState(mFn),[c,d]=_.useState(!0),[u,h]=_.useState(""),m=g=>o(b=>({...b,...g})),p=g=>{h(g);const b=(i||[]).find(j=>j.id===g);b&&m({address:b.property_address||"",city:b.city||"",state:b.state||"",zip:"",price:b.price??null,bedrooms:b.bedrooms??null,bathrooms:b.bathrooms??null,sqft:b.square_footage??null,propertyType:b.property_type||""})},f=!!(l.city||l.zip||l.price),y=_.useMemo(()=>!a||!f?[]:cFn(n,a,l,{includeNearMatches:c}),[n,a,l,c,f]),v=_.useMemo(()=>Object.keys(a||{}).length,[a]);return e.jsx(qg,{open:s,onOpenChange:t,children:e.jsxs(hg,{side:"right",className:"w-full sm:max-w-xl overflow-y-auto",children:[e.jsxs(P0,{children:[e.jsxs(L0,{className:"flex items-center gap-2",children:[e.jsx(In,{className:"h-4 w-4 text-primary"}),"Who wants this house?"]}),e.jsx(U9,{children:"Enter a property — or pick one of your listings — and we'll show the contacts whose saved home search fits. No IDX needed."})]}),e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsxs(Yr,{defaultValue:i!=null&&i.length?"listing":"manual",children:[e.jsxs(Zr,{className:"grid w-full grid-cols-2",children:[e.jsx(Ht,{value:"listing",children:"My listings"}),e.jsx(Ht,{value:"manual",children:"Enter a property"})]}),e.jsx(Gt,{value:"listing",className:"pt-3",children:i!=null&&i.length?e.jsxs(is,{value:u,onValueChange:p,children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Choose a listing…"})}),e.jsx(as,{children:i.map(g=>e.jsxs(He,{value:g.id,children:[[g.property_address,g.city].filter(Boolean).join(", "),g.price?` — ${am(Number(g.price))}`:""]},g.id))})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:`You don't have any Listing Exchange listings yet. Use "Enter a property" instead.`})}),e.jsx(Gt,{value:"manual",className:"pt-3",children:e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"Saw something in your MLS? Type the basics here."})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"col-span-2",children:[e.jsx(J,{className:"mb-1.5 text-xs",children:"Address (optional)"}),e.jsx(xe,{value:l.address||"",onChange:g=>m({address:g.target.value}),placeholder:"123 Main St"})]}),e.jsxs("div",{children:[e.jsx(J,{className:"mb-1.5 text-xs",children:"City"}),e.jsx(xe,{value:l.city||"",onChange:g=>m({city:g.target.value}),placeholder:"Cypress"})]}),e.jsxs("div",{children:[e.jsx(J,{className:"mb-1.5 text-xs",children:"Zip"}),e.jsx(xe,{value:l.zip||"",onChange:g=>m({zip:g.target.value}),placeholder:"90630"})]}),e.jsxs("div",{children:[e.jsx(J,{className:"mb-1.5 text-xs",children:"Price"}),e.jsx(xe,{type:"number",value:l.price??"",onChange:g=>m({price:g.target.value?Number(g.target.value):null}),placeholder:"750000"})]}),e.jsxs("div",{children:[e.jsx(J,{className:"mb-1.5 text-xs",children:"Sqft"}),e.jsx(xe,{type:"number",value:l.sqft??"",onChange:g=>m({sqft:g.target.value?Number(g.target.value):null}),placeholder:"1800"})]}),e.jsxs("div",{children:[e.jsx(J,{className:"mb-1.5 text-xs",children:"Beds"}),e.jsx(xe,{type:"number",value:l.bedrooms??"",onChange:g=>m({bedrooms:g.target.value?Number(g.target.value):null}),placeholder:"3"})]}),e.jsxs("div",{children:[e.jsx(J,{className:"mb-1.5 text-xs",children:"Baths"}),e.jsx(xe,{type:"number",step:"0.5",value:l.bathrooms??"",onChange:g=>m({bathrooms:g.target.value?Number(g.target.value):null}),placeholder:"2"})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx(J,{className:"mb-1.5 text-xs",children:"Property type"}),e.jsxs(is,{value:l.propertyType||"any",onValueChange:g=>m({propertyType:g==="any"?"":g}),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"any",children:"Any"}),BYt.map(g=>e.jsx(He,{value:g,children:g},g))]})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between border-t pt-3",children:[e.jsxs("div",{className:"text-xs text-muted-foreground",children:[v," ",v===1?"contact has":"contacts have"," a saved home search"]}),e.jsx(B,{variant:c?"secondary":"outline",size:"sm",className:"h-7 text-xs",onClick:()=>d(g=>!g),children:c?"Including close matches":"Exact matches only"})]}),f?y.length===0?e.jsxs("div",{className:"rounded-lg border border-dashed p-6 text-center text-sm text-muted-foreground",children:[e.jsx(Jr,{className:"h-5 w-5 mx-auto mb-2 opacity-60"}),"No contacts match this property yet. Add home searches to your buyers so matches show up here."]}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:[y.length," ",y.length===1?"match":"matches"]}),y.map(({contact:g,result:b})=>{const j=`${g.first_name} ${g.last_name||""}`.trim();return e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border p-3",children:[e.jsx(knt,{firstName:g.first_name,lastName:g.last_name||void 0,avatarUrl:g.avatar_url||void 0,email:g.email||void 0,size:36}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("button",{type:"button",className:"font-medium text-sm hover:underline",onClick:()=>r(`/mission-control/contacts/${g.id}`),children:j}),e.jsxs("div",{className:"mt-1 flex flex-wrap gap-1",children:[b.reasons.slice(0,4).map(S=>e.jsx(Oe,{variant:"secondary",className:"text-[10px]",children:S},S)),b.misses.map(S=>e.jsx(Oe,{variant:"outline",className:"text-[10px] text-muted-foreground",children:S},S))]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[g.email&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",title:`Email ${j}`,asChild:!0,children:e.jsx("a",{href:`mailto:${g.email}?subject=${encodeURIComponent(`Thought of you: ${l.address||l.city||"this home"}`)}`,children:e.jsx(ln,{className:"h-4 w-4"})})}),g.phone&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",title:`Text ${j}`,asChild:!0,children:e.jsx("a",{href:`sms:${g.phone}`,children:e.jsx(Hi,{className:"h-4 w-4"})})})]})]},g.id)})]}):e.jsxs("div",{className:"rounded-lg border border-dashed p-6 text-center text-sm text-muted-foreground",children:[e.jsx(Lr,{className:"h-5 w-5 mx-auto mb-2 opacity-60"}),"Add a city, zip, or price to see matches."]})]})]})})}function fFn(){var xm;const s=Fn(),[t,n]=Yl(),{user:r}=hs(),a=$W(),i=Bt(),{columns:l,toggle:o,reset:c}=sFn(),d=t.get("type"),u=t.get("filter")??t.get("status"),h=t.get("new")==="true",{contactsWithScores:m,isLoading:p}=lae(),{activeContactIds:f,hasLeadSite:y}=IDn(),{data:v}=ORn(),{data:g}=Z_(),{data:b}=zRn(),{data:j}=rz(),{data:S}=Pae(),{hasIdx:C}=lf(),{data:E}=OYt(),{data:P}=rFn(!!C),M=_.useMemo(()=>new Set(Object.entries(E||{}).filter(([,xs])=>zYt(xs)).map(([xs])=>xs)),[E]),[I,D]=_.useState(null),[O,V]=_.useState(!1),[G,$]=_.useState(new Set),[H,Y]=_.useState("any"),Z=iLe(),ne=uet(),ce=_zt(),ie=bzt(),[te,ae]=_.useState(""),[le,be]=_.useState(!1),[me,he]=_.useState(d||"all"),[pe,Ce]=_.useState(u||"all"),[Ae,Pe]=_.useState("date-added"),[ze,ke]=_.useState("all"),[Ze,Se]=_.useState({}),Fe=_.useMemo(()=>Object.values(Ze).filter(xs=>xs!==void 0&&xs!==!1&&xs!=="").length,[Ze]),[Ne,Ye]=_.useState(!1),[Ve,qe]=_.useState([]),{neighborhoods:Qe}=Nnt(),Ue=_.useMemo(()=>LYt(Qe,Ve),[Qe,Ve]),{behaviorMap:Xe,hasLeadSite:nt}=LRn(),[$e,Ge]=_.useState(h),[ct,xt]=_.useState(null),[qt,Vt]=_.useState(!1),[Xt,fs]=_.useState(!1),[Ft,wt]=_.useState(null),[Ts,vt]=_.useState(""),[$s,As]=_.useState(new Set),[jn,ar]=_.useState(!1),[Dn,Ur]=_.useState(!1),Vs=Math.max(1,parseInt(t.get("page")||"1",10)||1),[hn,dr]=_.useState(Vs),Cn=_.useCallback(xs=>{dr(da=>{const so=typeof xs=="function"?xs(da):xs;return n(Ma=>{const no=new URLSearchParams(Ma);return so<=1?no.delete("page"):no.set("page",String(so)),no},{replace:!0}),so})},[]),[Yn,on]=_.useState(50),[Ir,Wn]=_.useState("my"),[Js,Fa]=_.useState(!1),[ks,Gs]=_.useState(!1),{data:Ws}=G_(),{addToLeadPond:Ys}=kVt(Ws==null?void 0:Ws.teamId),{ponds:Bn}=$tt(Ws==null?void 0:Ws.teamId),or=Bn.filter(xs=>xs.has_access),[Wt,rt]=_.useState(null),[pt,jt]=_.useState(""),Mt=!!((xm=Ws==null?void 0:Ws.team)!=null&&xm.lead_pond_enabled&&(Ws!=null&&Ws.teamId)),es=!!(Ws!=null&&Ws.teamId),[ps,Is]=_.useState([]),[js,Kt]=_.useState(!1),Qs=xs=>{Is([xs]),Kt(!0)},an=xs=>{Is(xs),Kt(!0)},er=(xs,da)=>{Ws!=null&&Ws.teamId&&xs.forEach(so=>{Ys.mutate({contact_id:so,team_id:Ws.teamId,pond_id:da||null})})},Xr=xs=>{var da;if(Ws!=null&&Ws.teamId){if(or.length>1){jt(or[0].id),rt(xs);return}er(xs,((da=or[0])==null?void 0:da.id)||null)}},ma=xs=>Xr([xs]),Br=xs=>Xr(xs),sa=_.useCallback(xs=>{Ur(!1),As(da=>{const so=new Set(da);return so.has(xs)?so.delete(xs):so.add(xs),so})},[]);_.useEffect(()=>{if(!(r!=null&&r.id))return;const xs=q.channel(`innercircle_contacts_inserts_${r.id}`).on("postgres_changes",{event:"INSERT",schema:"public",table:"innercircle_contacts",filter:`owner_user_id=eq.${r.id}`},()=>{i.invalidateQueries({queryKey:["innercircle-contacts"]}),i.invalidateQueries({queryKey:["innercircle-contact-counts"]})}).subscribe();return()=>{q.removeChannel(xs)}},[i,r==null?void 0:r.id]),_.useEffect(()=>{u&&Ce(u)},[u]);const[Rr,ra]=_.useState({first_name:"",last_name:"",email:"",phone:"",address:"",city:"",state:"",zip_code:"",birthday:"",home_anniversary:"",spouse_name:"",spouse_email:"",lead_source_id:"",notes:"",tagIds:[]});_.useEffect(()=>{h&&Ge(!0)},[h]),_.useEffect(()=>{var xs;ct&&ra({first_name:ct.first_name||"",last_name:ct.last_name||"",email:ct.email||"",phone:ct.phone||"",address:ct.address||"",city:ct.city||"",state:ct.state||"",zip_code:ct.zip_code||"",birthday:ct.birthday||"",home_anniversary:ct.home_anniversary||"",spouse_name:ct.spouse_name||"",spouse_email:ct.spouse_email||"",lead_source_id:ct.lead_source_id||"",notes:ct.notes||"",tagIds:((xs=ct.tags)==null?void 0:xs.map(da=>da.relationship_type_id))||[]})},[ct]);const Si=_.useMemo(()=>{const xs=new Set;return j==null||j.forEach(da=>{(da.name==="Recruits"||da.name==="Brokerage Agents")&&xs.add(da.id)}),xs},[j]),Gi=_.useMemo(()=>Array.from(G).some(xs=>Si.has(xs)),[G,Si]),rl=_.useMemo(()=>{const xs={};return(m||[]).forEach(da=>{xs[da.id]=`${da.first_name||""} ${da.last_name||""}`.trim()}),xs},[m]),Ii=_.useMemo(()=>{const xs=new Set;return(m||[]).forEach(da=>{var Ma;const so=(((Ma=da.lead_source_ref)==null?void 0:Ma.name)||da.lead_source||"").trim();so&&xs.add(so)}),Array.from(xs).sort((da,so)=>da.localeCompare(so))},[m]),Ta=_.useMemo(()=>{if(!m)return[];let xs=m.filter(Ma=>{var Hg,Dv,Dc,Mp,op,xg,Rv,Xf,Ti,gm,Gg;const no=Ma.synced_source;if(!Gi&&(no==="recruit"||no==="brokerage_agent")||Ue&&!Ue.has(Ma.id))return!1;const bi=te===""||`${Ma.first_name} ${Ma.last_name}`.toLowerCase().includes(te.toLowerCase())||((Hg=Ma.email)==null?void 0:Hg.toLowerCase().includes(te.toLowerCase()))||((Dv=Ma.phone)==null?void 0:Dv.includes(te))||((Dc=Ma.city)==null?void 0:Dc.toLowerCase().includes(te.toLowerCase()))||((Mp=Ma.state)==null?void 0:Mp.toLowerCase().includes(te.toLowerCase()))||((op=Ma.address)==null?void 0:op.toLowerCase().includes(te.toLowerCase()))||((xg=Ma.zip_code)==null?void 0:xg.toLowerCase().includes(te.toLowerCase())),Bu=me==="all"||((Rv=Ma.tags)==null?void 0:Rv.some(wd=>wd.relationship_type_id===me)),Uu=G.size===0||(()=>{const wd=(S==null?void 0:S.filter(jd=>jd.contact_id===Ma.id).map(jd=>jd.tag_id))||[];return H==="any"?wd.some(jd=>G.has(jd)):Array.from(G).every(jd=>wd.includes(jd))})(),Rx=!!((Xf=Ma.address)!=null&&Xf.trim()||(Ti=Ma.city)!=null&&Ti.trim()||(gm=Ma.state)!=null&&gm.trim()||(Gg=Ma.zip_code)!=null&&Gg.trim()),hl=ze==="all"||ze==="has-address"&&Rx||ze==="no-address"&&!Rx,Ua=Ma,ml=Ze,fg=(ml.hasEmail===void 0||!!Ua.email===ml.hasEmail)&&(ml.hasPhone===void 0||!!Ua.phone===ml.hasPhone)&&(ml.hasAddress===void 0||Rx===ml.hasAddress)&&(ml.hasBirthday===void 0||!!Ua.birthday===ml.hasBirthday)&&(ml.hasSpouse===void 0||!!(Ua.spouse_name||Ua.spouse_contact_id||Ua.spouse_email)===ml.hasSpouse)&&(ml.hasCompany===void 0||!!(Ua.company_name||Ua.job_title)===ml.hasCompany)&&(ml.hasNotes===void 0||!!(Ua.notes&&Ua.notes.trim())===ml.hasNotes)&&(!ml.city||(Ua.city||"").toLowerCase().includes(ml.city.toLowerCase()))&&(!ml.state||(Ua.state||"").toLowerCase().includes(ml.state.toLowerCase()))&&(!ml.zip||((Ua.zip||"")+(Ua.zip_code||"")).toLowerCase().includes(ml.zip.toLowerCase()))&&(!ml.birthdayMonth||!!Ua.birthday&&Ru(Ua.birthday).getMonth()+1===ml.birthdayMonth)&&(!ml.anniversaryMonth||((ml.anniversaryField||"home_anniversary")==="home_anniversary"?!!Ua.home_anniversary&&Ru(Ua.home_anniversary).getMonth()+1===ml.anniversaryMonth:!!Ua.wedding_anniversary&&Ru(Ua.wedding_anniversary).getMonth()+1===ml.anniversaryMonth))&&(!ml.dateAddedFrom||!!Ua.created_at&&Ua.created_at.slice(0,10)>=ml.dateAddedFrom)&&(!ml.dateAddedTo||!!Ua.created_at&&Ua.created_at.slice(0,10)<=ml.dateAddedTo)&&(()=>{var Yu;const wd=ml.leadSourceId;if(!wd)return!0;const jd=(((Yu=Ua.lead_source_ref)==null?void 0:Yu.name)||Ua.lead_source||"").trim();return wd==="none"?!jd&&!Ua.lead_source_id:wd.startsWith("name:")?jd.toLowerCase()===wd.slice(5).toLowerCase():Ua.lead_source_id===wd})();return bi&&Bu&&Uu&&hl&&fg});pe==="not-touched-90"?xs=xs.filter(Ma=>{const no=Ma.relationshipScore.daysSinceTouch;return no===null||no>90}):pe==="at-risk"?xs=xs.filter(Ma=>Ma.relationshipScore.status==="at-risk"):pe==="cooling"?xs=xs.filter(Ma=>Ma.relationshipScore.status==="cooling"):pe==="warm"?xs=xs.filter(Ma=>Ma.relationshipScore.status==="warm"):pe==="has-deal"?xs=xs.filter(Ma=>b&&b[Ma.id]):pe==="no-deal"?xs=xs.filter(Ma=>!b||!b[Ma.id]):pe==="open-house"?xs=xs.filter(Ma=>{var Co;return(((Co=Ma.lead_source_ref)==null?void 0:Co.name)||Ma.lead_source)==="Open House"}):pe==="website-active"?xs=xs.filter(Ma=>f.has(Ma.id)):pe==="never-contacted"?xs=xs.filter(Ma=>Ma.relationshipScore.daysSinceTouch===null):pe==="vips"?xs=xs.filter(Ma=>Ma.relationshipScore.score>=80):pe==="missing-info"?xs=xs.filter(Ma=>FYt(Ma)):pe==="birthdays-soon"?xs=xs.filter(Ma=>{const no=VR(Ma.birthday);return no!==null&&no<=30}):pe==="anniversary-soon"?xs=xs.filter(Ma=>{const no=VR(Ma.home_anniversary);return no!==null&&no<=30}):pe==="in-drip"?xs=xs.filter(Ma=>((v==null?void 0:v[Ma.id])??0)>0):pe==="not-in-drip"?xs=xs.filter(Ma=>((v==null?void 0:v[Ma.id])??0)===0):pe==="active-buyers"?xs=xs.filter(Ma=>M.has(Ma.id)):pe==="missing-criteria"&&(xs=xs.filter(Ma=>!M.has(Ma.id)));const da=Ze;if(da.lastActive||da.registered||da.viewedListing||da.savedProperty||da.hasSavedSearch||da.requestedShowing||da.requestedValuation||da.websiteActiveOnly){const Ma=Date.now(),no={today:24*60*60*1e3,"7d":7*24*60*60*1e3,"30d":30*24*60*60*1e3,"90d":90*24*60*60*1e3};xs=xs.filter(Co=>{const bi=Xe.get(Co.id);if(da.lastActive==="never"){if(bi!=null&&bi.lastActiveAt)return!1}else if(da.lastActive){const Bu=Ma-no[da.lastActive];if(!(bi!=null&&bi.lastActiveAt)||new Date(bi.lastActiveAt).getTime()0)||da.viewedListing==="multiple7d"&&!(bi&&bi.propertyViewCount7d>=3)||da.savedProperty&&!(bi&&bi.savedListingCount>0)||da.hasSavedSearch&&!(bi&&bi.activeSavedSearchCount>0)||da.requestedShowing&&!(bi&&bi.showingRequests>0)||da.requestedValuation&&!(bi&&bi.valuationRequests>0)||da.websiteActiveOnly&&!f.has(Co.id))})}return xs=[...xs].sort((Ma,no)=>{switch(Ae){case"important-dates":{const Co=VR(Ma.birthday),bi=VR(no.birthday),Bu=VR(Ma.home_anniversary),Uu=VR(no.home_anniversary),Rx=[Co,Bu].filter(Ua=>Ua!==null).sort((Ua,ml)=>(Ua??1/0)-(ml??1/0))[0]??1/0,hl=[bi,Uu].filter(Ua=>Ua!==null).sort((Ua,ml)=>(Ua??1/0)-(ml??1/0))[0]??1/0;return Rx-hl}case"last-touched":{const Co=Ma.relationshipScore.lastTouchDate,bi=no.relationshipScore.lastTouchDate;return!Co&&!bi?0:Co?bi?new Date(Co).getTime()-new Date(bi).getTime():1:-1}case"next-touch":{const Co=Ma.relationshipScore.daysSinceTouch,bi=no.relationshipScore.daysSinceTouch;return Co===null&&bi===null?0:Co===null?-1:bi===null?1:bi-Co}case"score":return Ma.relationshipScore.score-no.relationshipScore.score;case"date-added":{const Co=Ma.created_at,bi=no.created_at;return!Co&&!bi?0:Co?bi?new Date(bi).getTime()-new Date(Co).getTime():-1:1}case"last-name":{const Co=(Ma.last_name||"").toLowerCase(),bi=(no.last_name||"").toLowerCase();if(Co!==bi)return Co.localeCompare(bi);const Bu=(Ma.first_name||"").toLowerCase(),Uu=(no.first_name||"").toLowerCase();return Bu.localeCompare(Uu)}case"name":default:{const Co=`${Ma.first_name||""} ${Ma.last_name||""}`.toLowerCase(),bi=`${no.first_name||""} ${no.last_name||""}`.toLowerCase();return Co.localeCompare(bi)}}}),xs},[m,te,me,G,H,pe,Ae,b,S,f,v,ze,Ze,Xe,Gi,M,Ue]),eo=Ta.length,So=Math.max(1,Math.ceil(eo/Yn)),Ra=Math.min(hn,So),Eo=_.useMemo(()=>{const xs=(Ra-1)*Yn;return Ta.slice(xs,xs+Yn)},[Ta,Ra,Yn]),Ro=_.useMemo(()=>{const xs=(m||[]).length;return{total:xs,label:xs===0?"Build your database — add or import your first contacts.":`${xs.toLocaleString()} ${xs===1?"person":"people"} in your database`}},[m]),di=_.useMemo(()=>{const xs=m||[],da=xs.filter(Co=>{var bi;return((bi=Co.relationshipScore)==null?void 0:bi.status)==="at-risk"}).length,so=xs.filter(Co=>{var Bu;const bi=(Bu=Co.relationshipScore)==null?void 0:Bu.daysSinceTouch;return typeof bi=="number"&&bi<=7}).length,Ma=new Date().getMonth()+1,no=xs.filter(Co=>Co.birthday?String(Co.birthday).split(/[-/T]/).map(Number)[1]===Ma:!1).length;return[{label:"Total contacts",value:Ro.total.toLocaleString(),onClick:()=>{Ce("all"),Cn(1)},active:pe==="all"},{label:"Needs attention",value:da,onClick:()=>{Ce("at-risk"),Cn(1)},active:pe==="at-risk"},{label:"Touched this week",value:so,onClick:()=>{Ce("warm"),Cn(1)},active:pe==="warm"},{label:"Birthdays this month",value:no,onClick:()=>{Ce("birthdays-soon"),Cn(1)},active:pe==="birthdays-soon"}]},[m,Ro.total,pe,Cn]),rr=_.useCallback(xs=>{const da=new URLSearchParams;te&&da.set("search",te),me!=="all"&&da.set("type",me),pe!=="all"&&da.set("filter",pe),G.size>0&&(da.set("tags",Array.from(G).join(",")),da.set("tagMode",H));const so=da.toString();s(`/mission-control/contacts/${xs}${so?`?${so}`:""}`)},[s,te,me,pe,G,H]),oi=_.useRef(!1);_.useEffect(()=>{if(!oi.current){oi.current=!0;return}Cn(1)},[te,me,G,H,pe,Ae,ze,Ze]);const Oo=_.useCallback(()=>{Ur(!1),As(xs=>xs.size>0?new Set:new Set(Eo.map(da=>da.id)))},[Eo]),kl=_.useCallback(()=>{Ur(!0),As(new Set(Ta.map(xs=>xs.id)))},[Ta]),[Jo,Sl]=_.useState(null),vu=_.useCallback((xs,da)=>{ae(xs.search||""),he(xs.type||"all"),Ce(xs.status||"all"),Se(xs.behavior||{}),Pe(da||"name")},[]),Ku=()=>{ra({first_name:"",last_name:"",email:"",phone:"",address:"",city:"",state:"",zip_code:"",birthday:"",home_anniversary:"",spouse_name:"",spouse_email:"",lead_source_id:"",notes:"",tagIds:[]})},Tp=async xs=>{xs.preventDefault();const da={...Rr,lead_source_id:Rr.lead_source_id||null};ct?(await ne.mutateAsync({id:ct.id,...da}),xt(null)):(await Z.mutateAsync(da),Ge(!1)),Ku()},Bd=async xs=>{await Xi("Are you sure you want to delete this contact?")&&await ce.mutateAsync(xs)};return e.jsx(zs,{title:"Contacts",description:"Manage your InnerCircle contacts",children:e.jsxs("div",{className:"space-y-6 overflow-x-hidden",children:[e.jsx(QRn,{totalLabel:Ro.label,stats:di,search:te,onSearchChange:ae,onAddContact:()=>Ge(!0),onImportCsv:()=>Vt(!0),onImportPhone:()=>fs(!0),onManageTags:()=>Fa(!0),onHeatMap:()=>be(!0),viewMode:Ir,onViewModeChange:xs=>Wn(xs),showTeamTab:!!Ws&&(Ws.team.contact_visibility==="full_team"||Ws.team.contact_visibility==="leader_only"&&Ws.role==="team_leader"),showLeadPondTab:!!(Ws!=null&&Ws.team.lead_pond_enabled),extraActions:e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"secondary",size:"sm",className:"h-9 gap-1.5",onClick:()=>s("/mission-control/sphere-map"),children:[e.jsx(UQ,{className:"h-4 w-4"}),"Map view"]}),e.jsxs(B,{variant:"secondary",size:"sm",className:"h-9 gap-1.5",onClick:()=>V(!0),children:[e.jsx(Lr,{className:"h-4 w-4"}),"Match a listing"]}),e.jsxs(B,{variant:"secondary",size:"sm",className:"h-9 gap-1.5",onClick:()=>ar(!0),children:[e.jsx(s7,{className:"h-4 w-4"}),"Find duplicates"]}),e.jsx(yDn,{})]})}),e.jsx(kDn,{open:jn,onOpenChange:ar}),e.jsx(pFn,{open:O,onOpenChange:V,contacts:m||[]}),I&&e.jsx(hFn,{open:!!I,onOpenChange:xs=>{xs||D(null)},contactId:I.id,contactName:I.name,existing:(E==null?void 0:E[I.id])??null}),Ir==="team"?e.jsx(ZLe,{}):Ir==="lead-pond"&&Ws?e.jsx(XLe,{teamId:Ws.teamId}):e.jsxs(e.Fragment,{children:[e.jsx(tFn,{contacts:m,contactDealsMap:b,websiteActiveIds:f,criteriaContactIds:M,totalCount:(m||[]).length,activeViewId:Jo,currentFilters:{search:te,type:me,status:pe,behavior:Ze},currentSortBy:Ae,onApplyView:(xs,da,so)=>{Sl(xs),vu(da,so),Cn(1)},onClearAll:()=>{Sl(null),vu({search:"",type:"all",status:"all",behavior:{}},"name"),Cn(1)},activeKey:{"at-risk":"needs-attention",cooling:"cooling","not-touched-90":"stale-90","never-contacted":"never-contacted","birthdays-soon":"birthdays-soon","anniversary-soon":"anniversary-soon","has-deal":"has-deal","website-active":"website-active",vips:"vips","missing-info":"missing-info","active-buyers":"active-buyers","missing-criteria":"missing-criteria"}[pe]??null,onSelectSegment:xs=>{const so=xs?{"needs-attention":"at-risk",cooling:"cooling","stale-90":"not-touched-90","never-contacted":"never-contacted","birthdays-soon":"birthdays-soon","anniversary-soon":"anniversary-soon","has-deal":"has-deal","website-active":"website-active",vips:"vips","missing-info":"missing-info","active-buyers":"active-buyers","missing-criteria":"missing-criteria"}[xs]:"all";Ce(so),Cn(1)}}),e.jsxs(ve,{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(qg,{children:[e.jsx(zre,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:"h-10 flex-1 rounded-xl relative gap-2","aria-label":"Filters",children:[e.jsx(tP,{className:"h-4 w-4"}),"Filters & Views",(()=>{const xs=(me!=="all"?1:0)+(pe!=="all"?1:0)+(ze!=="all"?1:0)+G.size+Fe;return xs>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:xs}):null})()]})}),e.jsxs(hg,{side:"bottom",className:"h-[85vh] rounded-t-2xl overflow-y-auto",children:[e.jsx(P0,{className:"text-left",children:e.jsx(L0,{children:"Filters & Views"})}),e.jsxs("div",{className:"space-y-5 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Type"}),e.jsxs(is,{value:me,onValueChange:he,children:[e.jsx(rs,{className:"h-11 rounded-xl bg-muted/40",children:e.jsx(ls,{placeholder:"All Types"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Types"}),g==null?void 0:g.filter(xs=>xs.active).map(xs=>e.jsx(He,{value:xs.id,children:xs.name},xs.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Status"}),e.jsxs(is,{value:pe,onValueChange:Ce,children:[e.jsx(rs,{className:"h-11 rounded-xl bg-muted/40",children:e.jsx(ls,{placeholder:"All Status"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Status"}),e.jsx(He,{value:"warm",children:"🟢 Warm"}),e.jsx(He,{value:"cooling",children:"🟡 Cooling Off"}),e.jsx(He,{value:"at-risk",children:"🔴 At Risk"}),e.jsx(He,{value:"has-deal",children:"📋 Has Deal"}),e.jsx(He,{value:"no-deal",children:"📭 No Deal"}),e.jsx(He,{value:"open-house",children:"🏠 Open House"}),y&&e.jsx(He,{value:"website-active",children:"🌐 Website Active"}),e.jsx(He,{value:"in-drip",children:"🌱 In Drip Campaign"}),e.jsx(He,{value:"not-in-drip",children:"🚫 Not In Drip"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Address"}),e.jsxs(is,{value:ze,onValueChange:xs=>ke(xs),children:[e.jsx(rs,{className:"h-11 rounded-xl bg-muted/40",children:e.jsx(ls,{placeholder:"All Addresses"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Addresses"}),e.jsx(He,{value:"has-address",children:"Has Address"}),e.jsx(He,{value:"no-address",children:"No Address"})]})]})]}),j&&j.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(J,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Tags"}),e.jsxs("div",{className:"flex items-center gap-1 bg-muted rounded-md p-0.5",children:[e.jsx("button",{onClick:()=>Y("any"),className:`px-2 py-0.5 rounded text-xs font-medium ${H==="any"?"bg-background shadow-sm":"text-muted-foreground"}`,children:"Any"}),e.jsx("button",{onClick:()=>Y("all"),className:`px-2 py-0.5 rounded text-xs font-medium ${H==="all"?"bg-background shadow-sm":"text-muted-foreground"}`,children:"All"})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:j.map(xs=>{const da=G.has(xs.id);return e.jsxs("button",{onClick:()=>{$(so=>{const Ma=new Set(so);return Ma.has(xs.id)?Ma.delete(xs.id):Ma.add(xs.id),Ma})},className:`inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs border transition-colors ${da?"bg-primary text-primary-foreground border-primary":"bg-background border-border"}`,children:[e.jsx("span",{className:"h-2 w-2 rounded-full",style:{backgroundColor:xs.color}}),xs.name]},xs.id)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Sort by"}),e.jsxs(is,{value:Ae,onValueChange:Pe,children:[e.jsx(rs,{className:"h-11 rounded-xl bg-muted/40",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"name",children:"Name (A-Z)"}),e.jsx(He,{value:"last-name",children:"Last Name (A-Z)"}),e.jsx(He,{value:"important-dates",children:"Important Dates"}),e.jsx(He,{value:"last-touched",children:"Last Touched"}),e.jsx(He,{value:"next-touch",children:"Next Touch Due"}),e.jsx(He,{value:"score",children:"Relationship Score"}),e.jsx(He,{value:"date-added",children:"Date Added"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 pt-2",children:[e.jsxs(B,{variant:"outline",className:"h-11 rounded-xl gap-1.5",onClick:()=>Ye(!0),children:[e.jsx(un,{className:"h-4 w-4"})," Advanced"]}),e.jsxs(B,{variant:"outline",className:"h-11 rounded-xl gap-1.5",onClick:()=>Fa(!0),children:[e.jsx(Ep,{className:"h-4 w-4"})," Manage Tags"]})]}),e.jsx("div",{children:e.jsx(i2t,{currentFilters:{search:te,type:me,status:pe,behavior:Ze},currentSortBy:Ae,onApplySmartList:vu})}),e.jsx(B,{variant:"ghost",className:"w-full h-11 rounded-xl text-muted-foreground",onClick:()=>{he("all"),Ce("all"),ke("all"),$(new Set),Se({})},children:"Clear all filters"})]})]})]})})}),e.jsxs("div",{className:"hidden sm:flex items-center gap-3 flex-wrap",children:[e.jsxs("div",{className:"flex-1 min-w-[120px] text-sm text-muted-foreground",children:[eo.toLocaleString()," ",eo===1?"contact":"contacts"," shown"]}),e.jsxs(od,{children:[e.jsx(ld,{asChild:!0,children:e.jsx(B,{variant:"outline",size:"icon",className:"h-10 w-10 rounded-xl",title:"Sort contacts",children:e.jsx(xj,{className:"h-4 w-4"})})}),e.jsxs(Qc,{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(xs=>e.jsx("button",{onClick:()=>Pe(xs.v),className:`w-full text-left px-2 py-1.5 rounded-md text-sm hover:bg-accent transition-colors ${Ae===xs.v?"bg-accent font-medium text-primary":""}`,children:xs.l},xs.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(is,{value:me,onValueChange:he,children:[e.jsx(rs,{className:"h-8 text-xs rounded-lg bg-background w-auto min-w-[130px] gap-2",children:e.jsx(ls,{placeholder:"All Types"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Types"}),g==null?void 0:g.filter(xs=>xs.active).map(xs=>e.jsx(He,{value:xs.id,children:xs.name},xs.id))]})]}),e.jsxs(is,{value:pe,onValueChange:Ce,children:[e.jsx(rs,{className:"h-8 text-xs rounded-lg bg-background w-auto min-w-[130px] gap-2",children:e.jsx(ls,{placeholder:"All Status"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Status"}),e.jsx(He,{value:"warm",children:"🟢 Warm"}),e.jsx(He,{value:"cooling",children:"🟡 Cooling Off"}),e.jsx(He,{value:"at-risk",children:"🔴 At Risk"}),e.jsx(He,{value:"has-deal",children:"📋 Has Deal"}),e.jsx(He,{value:"no-deal",children:"📭 No Deal"}),e.jsx(He,{value:"open-house",children:"🏠 Open House"}),y&&e.jsx(He,{value:"website-active",children:"🌐 Website Active"}),e.jsx(He,{value:"in-drip",children:"🌱 In Drip Campaign"}),e.jsx(He,{value:"not-in-drip",children:"🚫 Not In Drip"})]})]}),e.jsxs(is,{value:ze,onValueChange:xs=>ke(xs),children:[e.jsx(rs,{className:"h-8 text-xs rounded-lg bg-background w-auto min-w-[130px] gap-2",children:e.jsx(ls,{placeholder:"All Addresses"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Addresses"}),e.jsx(He,{value:"has-address",children:"Has Address"}),e.jsx(He,{value:"no-address",children:"No Address"})]})]}),j&&j.length>0&&e.jsxs("div",{className:"inline-flex items-center bg-background border rounded-lg overflow-hidden h-8",children:[e.jsxs(od,{children:[e.jsx(ld,{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(Ep,{className:"h-3.5 w-3.5"}),G.size===0?"Filter by Tags":`${G.size} tag${G.size>1?"s":""}`]})}),e.jsx(Qc,{className:"w-60 p-3",align:"start",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-medium",children:"Tags"}),e.jsxs("div",{className:"flex items-center gap-1 bg-muted rounded-md p-0.5",children:[e.jsx("button",{onClick:()=>Y("any"),className:`px-2 py-0.5 rounded text-xs font-medium transition-colors ${H==="any"?"bg-background text-foreground shadow-sm":"text-muted-foreground"}`,children:"Any"}),e.jsx("button",{onClick:()=>Y("all"),className:`px-2 py-0.5 rounded text-xs font-medium transition-colors ${H==="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:j.map(xs=>{const da=G.has(xs.id);return e.jsxs("button",{onClick:()=>{$(so=>{const Ma=new Set(so);return Ma.has(xs.id)?Ma.delete(xs.id):Ma.add(xs.id),Ma})},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($a,{checked:da,className:"pointer-events-none"}),e.jsx("div",{className:"h-2.5 w-2.5 rounded-full shrink-0",style:{backgroundColor:xs.color}}),e.jsx("span",{className:"flex-1 text-left truncate",children:xs.name})]},xs.id)})}),G.size>0&&e.jsx(B,{variant:"ghost",size:"sm",className:"w-full text-xs",onClick:()=>$(new Set),children:"Clear tags"})]})})]}),e.jsx("div",{className:"w-px h-4 bg-border"}),e.jsxs(tu,{children:[e.jsx(su,{asChild:!0,children:e.jsx("button",{className:"px-2 h-full text-muted-foreground hover:text-primary transition-colors",title:"Manage tags & lead sources",children:e.jsx(qc,{className:"h-3.5 w-3.5"})})}),e.jsxs(Od,{align:"end",children:[e.jsxs(ca,{onClick:()=>Fa(!0),children:[e.jsx(Ep,{className:"h-4 w-4 mr-2"}),"Manage Tags"]}),e.jsxs(ca,{onClick:()=>Gs(!0),children:[e.jsx(m1,{className:"h-4 w-4 mr-2"}),"Manage Lead Sources"]})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(i2t,{currentFilters:{search:te,type:me,status:pe,behavior:Ze},currentSortBy:Ae,onApplySmartList:vu}),e.jsx("div",{className:"h-5 w-px bg-border"}),e.jsx(PRn,{selected:Ve,onChange:qe}),e.jsxs(B,{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:()=>Ye(!0),children:[e.jsx(un,{className:"h-3.5 w-3.5"}),"Advanced Filters",Fe>0&&e.jsx(Oe,{variant:"secondary",className:"h-5 px-1.5 text-[10px]",children:Fe})]}),e.jsx(nFn,{columns:l,onToggle:o,onReset:c})]})]}),Fe>0&&e.jsx("div",{className:"px-3 sm:px-4 py-3 border-t bg-background",children:e.jsx(_Rn,{behavior:Ze,onRemove:xs=>Se(da=>{const so={...da};return delete so[xs],so}),onClearAll:()=>Se({})})})]}),e.jsx(bRn,{open:Ne,onOpenChange:Ye,hasLeadSite:nt||y,behavior:Ze,onApply:Se,selectedType:me,onSelectedTypeChange:he,relationshipTypes:g,contactLeadSources:Ii}),e.jsx(yRn,{selectedIds:$s,contacts:Ta,onClearSelection:()=>{As(new Set),Ur(!1)},showLeadPondAction:Mt,onSendToLeadPond:Br,showTransferAction:es,onTransfer:an}),$s.size>0&&$s.size===Eo.length&&!Dn&&eo>Yn&&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 ",Eo.length," contacts on this page are selected."]}),e.jsxs(B,{variant:"link",size:"sm",className:"h-auto p-0 font-semibold",onClick:kl,children:["Select all ",eo.toLocaleString()," matching contacts"]})]}),Dn&&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 ",eo.toLocaleString()," matching contacts are selected.",e.jsx(B,{variant:"link",size:"sm",className:"h-auto p-0",onClick:()=>{As(new Set),Ur(!1)},children:"Clear selection"})]}),eo>Yn&&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 ",(Ra-1)*Yn+1,"–",Math.min(Ra*Yn,eo)," of ",eo.toLocaleString()," contacts"]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(B,{variant:"outline",size:"sm",disabled:Ra<=1,onClick:()=>Cn(1),children:"First"}),e.jsx(B,{variant:"outline",size:"sm",disabled:Ra<=1,onClick:()=>Cn(xs=>xs-1),children:e.jsx($c,{className:"h-4 w-4"})}),e.jsxs("span",{className:"px-3 text-sm font-medium",children:["Page ",Ra," of ",So]}),e.jsx(B,{variant:"outline",size:"sm",disabled:Ra>=So,onClick:()=>Cn(xs=>xs+1),children:e.jsx(xi,{className:"h-4 w-4"})}),e.jsx(B,{variant:"outline",size:"sm",disabled:Ra>=So,onClick:()=>Cn(So),children:"Last"})]})]}),a?e.jsx("div",{className:"space-y-3",children:p?e.jsx(eFn,{}):Ta.length===0?e.jsx(ve,{children:e.jsx(f2t,{filtered:!!te||me!=="all"||pe!=="all"||ze!=="all"||G.size>0,onAdd:()=>Ge(!0),onImport:()=>Vt(!0),onClearFilters:()=>{ae(""),he("all"),Ce("all"),ke("all"),$(new Set),Se({})}})}):Eo.map(xs=>{var so,Ma,no;const{relationshipScore:da}=xs;return e.jsx(ve,{className:"cursor-pointer hover:bg-accent/50 transition-colors",onClick:()=>rr(xs.id),children:e.jsx(Me,{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:[xs.first_name," ",xs.last_name]}),e.jsx(d2t,{count:(v==null?void 0:v[xs.id])??0}),e.jsx(xi,{className:"h-4 w-4 text-muted-foreground shrink-0 ml-auto"})]}),e.jsxs("div",{className:"space-y-1 text-sm mb-3",children:[xs.email&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(ln,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:xs.email})]}),xs.phone&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(_a,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{children:xs.phone})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1 mb-2",children:[e.jsx(xWe,{score:da,size:"sm"}),e.jsx(n2t,{contact:xs}),(((so=xs.lead_source_ref)==null?void 0:so.name)||xs.lead_source)&&e.jsx(Oe,{variant:"outline",className:"text-xs gap-1 border-primary/30 text-primary",children:((Ma=xs.lead_source_ref)==null?void 0:Ma.name)||xs.lead_source}),(no=xs.tags)==null?void 0:no.map(Co=>{var bi;return e.jsx(Oe,{variant:"secondary",className:"text-xs",children:(bi=Co.relationship_type)==null?void 0:bi.name},Co.id)}),e.jsx(m2t,{contactId:xs.id,tags:S==null?void 0:S.filter(Co=>Co.contact_id===xs.id)}),e.jsx(c2t,{deal:b==null?void 0:b[xs.id]})]}),e.jsx("div",{className:"mb-2",children:e.jsx(b2t,{criteria:E==null?void 0:E[xs.id],onEdit:()=>D({id:xs.id,name:`${xs.first_name}${xs.last_name?" "+xs.last_name:""}`}),showAlertState:!!C,matchCount:P==null?void 0:P[xs.id],compact:!0})}),e.jsx(l2t,{birthday:xs.birthday,homeAnniversary:xs.home_anniversary,weddingAnniversary:xs.wedding_anniversary,className:"mb-2",contactId:xs.id,contactName:`${xs.first_name}${xs.last_name?" "+xs.last_name:""}`,contactAddress:[xs.address,xs.city,xs.state].filter(Boolean).join(", ")}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-xs text-muted-foreground",children:[da.lastTouchDate?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Gr,{className:"h-3 w-3"}),Hs(new Date(da.lastTouchDate),"MMM d")]}):e.jsx("span",{className:"italic",children:"Never contacted"}),xs.birthday&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(ga,{className:"h-3 w-3"}),Hs(Ru(xs.birthday),"MMM d")]}),xs.home_anniversary&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Jr,{className:"h-3 w-3"}),Hs(Ru(xs.home_anniversary),"MMM d")]}),xs.created_at&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(rn,{className:"h-3 w-3"}),"Added ",Hs(new Date(xs.created_at),"MMM d, yyyy")]})]})]}),e.jsx("div",{className:"ml-2",onClick:Co=>Co.stopPropagation(),children:e.jsx(a2t,{contact:xs,onEdit:xt,onDelete:Bd,onSnooze:(Co,bi)=>{wt(Co),vt(bi)},showLeadPondAction:Mt,onSendToLeadPond:ma,showTransferAction:es,onTransfer:Qs})})]})})},xs.id)})}):e.jsx(ve,{children:e.jsx(Me,{className:"p-0 overflow-x-auto",children:e.jsxs(Ga,{className:"min-w-[800px]",children:[e.jsx(Wa,{className:"sticky top-0 z-10 bg-card/95 backdrop-blur supports-[backdrop-filter]:bg-card/80",children:e.jsxs(pn,{className:"hover:bg-transparent",children:[e.jsx(Pt,{className:"w-[40px]",children:e.jsx($a,{checked:Eo.length>0&&Eo.every(xs=>$s.has(xs.id)),onCheckedChange:()=>Oo()})}),e.jsx(Pt,{children:e.jsxs("button",{onClick:()=>Pe(xs=>xs==="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",Ae==="name"&&e.jsx(xi,{className:"h-3 w-3 rotate-90 text-primary"}),Ae==="last-name"&&e.jsx(xi,{className:"h-3 w-3 -rotate-90 text-primary"})]})}),l.relationship&&e.jsx(Pt,{children:"Relationship"}),l.buyerCriteria&&e.jsx(Pt,{className:"min-w-[170px] whitespace-nowrap",children:"Looking For"}),l.stage&&e.jsx(Pt,{children:"Stage"}),l.leadSource&&e.jsx(Pt,{children:"Lead Source"}),l.tags&&e.jsx(Pt,{children:"Tags"}),l.lastTouch&&e.jsx(Pt,{children:"Last Touch"}),l.nextAction&&e.jsx(Pt,{children:"Next Action"}),l.dealValue&&e.jsx(Pt,{title:"Total value of deals linked to this contact in your pipeline",children:"Pipeline Value"}),l.email&&e.jsx(Pt,{children:"Email"}),l.phone&&e.jsx(Pt,{children:"Phone"}),l.address&&e.jsx(Pt,{children:"Address"}),l.birthday&&e.jsx(Pt,{children:"Birthday"}),e.jsx(Pt,{className:"w-[50px]"})]})}),e.jsx(Ka,{children:p?e.jsx(JRn,{columns:2+Object.values(l).filter(Boolean).length}):Ta.length===0?e.jsx(pn,{className:"hover:bg-transparent",children:e.jsx(gt,{colSpan:3+Object.values(l).filter(Boolean).length,className:"p-0",children:e.jsx(f2t,{filtered:!!te||me!=="all"||pe!=="all"||ze!=="all"||G.size>0,onAdd:()=>Ge(!0),onImport:()=>Vt(!0),onClearFilters:()=>{ae(""),he("all"),Ce("all"),ke("all"),$(new Set),Se({})}})})}):Eo.map(xs=>{var Ma;const{relationshipScore:da}=xs,so=b==null?void 0:b[xs.id];return e.jsxs(pn,{className:`group cursor-pointer border-border/60 transition-colors hover:bg-accent/40 [&>td]:py-3.5 ${$s.has(xs.id)?"bg-accent/30":""}`,onClick:()=>rr(xs.id),children:[e.jsx(gt,{onClick:no=>no.stopPropagation(),children:e.jsx($a,{checked:$s.has(xs.id),onCheckedChange:()=>sa(xs.id)})}),e.jsx(gt,{className:"min-w-[220px]",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(knt,{firstName:xs.first_name,lastName:xs.last_name,avatarUrl:xs.avatar_url,email:xs.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:[xs.first_name," ",xs.last_name]}),e.jsx(XRn,{linked:!!xs.spouse_contact_id||!!xs.spouse_name,spouseName:xs.spouse_contact_id&&rl[xs.spouse_contact_id]||xs.spouse_name||null}),e.jsx(d2t,{count:(v==null?void 0:v[xs.id])??0})]}),xs.email&&!l.email&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:xs.email}),xs.phone&&!l.phone&&e.jsx("p",{className:"text-xs text-muted-foreground",children:xs.phone})]})]})}),l.relationship&&e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx(WRn,{score:da.score,status:da.status}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium leading-tight",children:da.status==="warm"?"Strong":da.status==="cooling"?"Cooling":"At Risk"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:da.daysSinceTouch===null?"Never contacted":da.daysSinceTouch===0?"Touched today":`${da.daysSinceTouch}d since touch`})]})]})}),l.buyerCriteria&&e.jsx(gt,{className:"min-w-[170px] max-w-[240px]",children:e.jsx(b2t,{criteria:E==null?void 0:E[xs.id],onEdit:()=>D({id:xs.id,name:`${xs.first_name}${xs.last_name?" "+xs.last_name:""}`}),showAlertState:!!C,matchCount:P==null?void 0:P[xs.id]})}),l.stage&&e.jsx(gt,{children:e.jsx(c2t,{deal:so})}),l.leadSource&&e.jsx(gt,{className:"text-sm text-muted-foreground max-w-[160px] truncate",children:((Ma=xs.lead_source_ref)==null?void 0:Ma.name)||xs.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(m2t,{contactId:xs.id,tags:S==null?void 0:S.filter(no=>no.contact_id===xs.id)})})}),l.lastTouch&&e.jsx(gt,{children:da.lastTouchDate?e.jsxs("div",{className:"flex items-center gap-1.5 text-sm text-muted-foreground",children:[e.jsx(Gr,{className:"h-3.5 w-3.5"}),Hs(new Date(da.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(n2t,{contact:xs}),e.jsx(l2t,{birthday:xs.birthday,homeAnniversary:xs.home_anniversary,weddingAnniversary:xs.wedding_anniversary,contactId:xs.id,contactName:`${xs.first_name}${xs.last_name?" "+xs.last_name:""}`,contactAddress:[xs.address,xs.city,xs.state].filter(Boolean).join(", ")})]})}),l.dealValue&&e.jsx(gt,{children:(()=>{const no=(so==null?void 0:so.sale_price)??(so==null?void 0:so.expected_price);return no?e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold",children:am(Number(no))}),(so==null?void 0:so.deal_type)&&e.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:String(so.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:xs.email||"—"}),l.phone&&e.jsx(gt,{className:"text-sm text-muted-foreground whitespace-nowrap",children:xs.phone||"—"}),l.address&&e.jsx(gt,{className:"text-sm text-muted-foreground max-w-[220px] truncate",children:[xs.address,xs.city,xs.state].filter(Boolean).join(", ")||"—"}),l.birthday&&e.jsx(gt,{className:"text-sm text-muted-foreground whitespace-nowrap",children:xs.birthday?(()=>{const[no,Co,bi]=String(xs.birthday).split(/[-/T]/).map(Number);return Co&&bi?`${Co}/${bi}${no&&no>1900?`/${no}`:""}`:"—"})():"—"}),e.jsx(gt,{onClick:no=>no.stopPropagation(),children:e.jsx(a2t,{contact:xs,onEdit:xt,onDelete:Bd,onSnooze:(no,Co)=>{wt(no),vt(Co)},showLeadPondAction:Mt,onSendToLeadPond:ma,showTransferAction:es,onTransfer:Qs})})]},xs.id)})})]})})}),eo>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 ",(Ra-1)*Yn+1,"–",Math.min(Ra*Yn,eo)," of ",eo.toLocaleString()," contacts"]}),e.jsxs(is,{value:String(Yn),onValueChange:xs=>{on(Number(xs)),Cn(1)},children:[e.jsx(rs,{className:"w-[80px] h-8",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"50",children:"50"}),e.jsx(He,{value:"100",children:"100"}),e.jsx(He,{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(B,{variant:"outline",size:"sm",disabled:Ra<=1,onClick:()=>Cn(1),children:"First"}),e.jsx(B,{variant:"outline",size:"sm",disabled:Ra<=1,onClick:()=>Cn(xs=>xs-1),children:e.jsx($c,{className:"h-4 w-4"})}),e.jsxs("span",{className:"px-3 text-sm font-medium",children:["Page ",Ra," of ",So]}),e.jsx(B,{variant:"outline",size:"sm",disabled:Ra>=So,onClick:()=>Cn(xs=>xs+1),children:e.jsx(xi,{className:"h-4 w-4"})}),e.jsx(B,{variant:"outline",size:"sm",disabled:Ra>=So,onClick:()=>Cn(So),children:"Last"})]})]}),e.jsx(Ls,{open:$e||!!ct,onOpenChange:xs=>{xs||(Ge(!1),xt(null),Ku())},children:e.jsxs(Ps,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Ds,{children:ct?"Edit Contact":"Add Contact"})}),e.jsxs("form",{onSubmit:Tp,className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(J,{htmlFor:"first_name",children:"First Name *"}),e.jsx(xe,{id:"first_name",value:Rr.first_name,onChange:xs=>ra({...Rr,first_name:xs.target.value}),required:!0})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"last_name",children:"Last Name"}),e.jsx(xe,{id:"last_name",value:Rr.last_name,onChange:xs=>ra({...Rr,last_name:xs.target.value})})]})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"email",children:"Email"}),e.jsx(xe,{id:"email",type:"email",value:Rr.email,onChange:xs=>ra({...Rr,email:xs.target.value})})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"phone",children:"Phone"}),e.jsx(xe,{id:"phone",value:Rr.phone,onChange:xs=>ra({...Rr,phone:xs.target.value})})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"address",children:"Address"}),e.jsx(xe,{id:"address",value:Rr.address,onChange:xs=>ra({...Rr,address:xs.target.value}),placeholder:"Street address"})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx(J,{htmlFor:"city",children:"City"}),e.jsx(xe,{id:"city",value:Rr.city,onChange:xs=>ra({...Rr,city:xs.target.value})})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"state",children:"State"}),e.jsx(xe,{id:"state",value:Rr.state,onChange:xs=>ra({...Rr,state:xs.target.value})})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"zip_code",children:"Zip"}),e.jsx(xe,{id:"zip_code",value:Rr.zip_code,onChange:xs=>ra({...Rr,zip_code:xs.target.value})})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(J,{htmlFor:"birthday",children:"Birthday"}),e.jsx(xe,{id:"birthday",type:"date",value:Rr.birthday,onChange:xs=>ra({...Rr,birthday:xs.target.value})})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"home_anniversary",children:"Home Anniversary"}),e.jsx(xe,{id:"home_anniversary",type:"date",value:Rr.home_anniversary,onChange:xs=>ra({...Rr,home_anniversary:xs.target.value})})]})]}),ct&&e.jsx(gWe,{contactId:ct.id,currentSpouseContactId:(ct==null?void 0:ct.spouse_contact_id)||null,currentSpouseName:(ct==null?void 0:ct.spouse_name)||null,currentSpouseEmail:(ct==null?void 0:ct.spouse_email)||null,onLink:xs=>ie.mutate({contactId:ct.id,spouseContactId:xs}),onUnlink:()=>ie.mutate({contactId:ct.id,spouseContactId:null}),isEditing:!0}),e.jsx(RYt,{value:Rr.lead_source_id,onChange:xs=>ra({...Rr,lead_source_id:xs})}),e.jsxs("div",{children:[e.jsx(J,{children:"Relationship Types"}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:g==null?void 0:g.filter(xs=>xs.active).map(xs=>e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx($a,{checked:Rr.tagIds.includes(xs.id),onCheckedChange:da=>{ra(da?{...Rr,tagIds:[...Rr.tagIds,xs.id]}:{...Rr,tagIds:Rr.tagIds.filter(so=>so!==xs.id)})}}),e.jsx("span",{className:"text-sm",children:xs.name})]},xs.id))})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"notes",children:"Notes"}),e.jsx(Ms,{id:"notes",value:Rr.notes,onChange:xs=>ra({...Rr,notes:xs.target.value}),rows:3})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>{Ge(!1),xt(null),Ku()},children:"Cancel"}),e.jsxs(B,{type:"submit",disabled:Z.isPending||ne.isPending,children:[ct?"Update":"Create"," Contact"]})]})]})]})}),e.jsx(ODn,{open:qt,onOpenChange:Vt,relationshipTypes:(g==null?void 0:g.filter(xs=>xs.active))||[],onSuccess:()=>{Vt(!1)}}),e.jsx(UDn,{open:Xt,onOpenChange:fs,onComplete:()=>fs(!1)}),e.jsx(KIe,{open:!!Ft,onOpenChange:xs=>{xs||wt(null)},contactId:Ft||"",contactName:Ts}),e.jsx($Rn,{open:Js,onOpenChange:Fa}),e.jsx(VRn,{open:ks,onOpenChange:Gs}),e.jsx(FRn,{open:le,onOpenChange:be,contacts:m||[],onCitySelect:xs=>{ae(xs),Cn(1)}}),e.jsx(SVt,{open:js,onOpenChange:Kt,contactIds:ps,contactNames:ps.map(xs=>{const da=Ta.find(so=>so.id===xs);return da?`${da.first_name} ${da.last_name||""}`.trim():""}),onComplete:()=>{Is([]),As(new Set),Ur(!1)}}),e.jsx(Ls,{open:!!Wt,onOpenChange:xs=>!xs&&rt(null),children:e.jsxs(Ps,{className:"sm:max-w-md",children:[e.jsx(Os,{children:e.jsx(Ds,{children:"Choose a Lead Pond"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Sharing ",(Wt==null?void 0:Wt.length)||0," contact",((Wt==null?void 0:Wt.length)||0)===1?"":"s"," with your team."]}),e.jsxs(is,{value:pt,onValueChange:jt,children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Select a pond"})}),e.jsx(as,{children:or.map(xs=>e.jsx(He,{value:xs.id,children:xs.name},xs.id))})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{variant:"outline",onClick:()=>rt(null),children:"Cancel"}),e.jsx(B,{onClick:()=>{Wt&&er(Wt,pt),rt(null)},disabled:!pt,children:"Share to Pond"})]})]})]})})]})]})})}const xFn=5*1024*1024;function gFn({contactId:s,firstName:t,lastName:n,avatarUrl:r,email:a,size:i=88}){const l=_.useRef(null),o=Bt(),[c,d]=_.useState(!1),u=()=>{o.invalidateQueries({queryKey:["innercircle-contacts"]}),o.invalidateQueries({queryKey:["innercircle-contact"]}),o.invalidateQueries({queryKey:["contact",s]})},h=async f=>{const{error:y}=await q.from("innercircle_contacts").update({avatar_url:f}).eq("id",s);if(y)throw y;u()},m=async f=>{var y;if(!f.type.startsWith("image/")){ia({title:"Please choose an image file",variant:"destructive"});return}if(f.size>xFn){ia({title:"Image too large",description:"Please use an image under 5MB.",variant:"destructive"});return}d(!0);try{const{data:v}=await q.auth.getUser(),g=(y=v.user)==null?void 0:y.id,b=(f.name.split(".").pop()||"jpg").toLowerCase(),j=`contacts/${g}/${s}-${Date.now()}.${b}`,{error:S}=await q.storage.from("avatars").upload(j,f,{upsert:!0,contentType:f.type});if(S)throw S;const{data:C}=q.storage.from("avatars").getPublicUrl(j);await h(C.publicUrl),ia({title:"Photo updated"})}catch(v){ia({title:"Upload failed",description:v.message,variant:"destructive"})}finally{d(!1),l.current&&(l.current.value="")}},p=async()=>{d(!0);try{await h(null),ia({title:"Photo removed"})}catch(f){ia({title:"Could not remove photo",description:f.message,variant:"destructive"})}finally{d(!1)}};return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{type:"button",onClick:()=>{var f;return(f=l.current)==null?void 0:f.click()},disabled:c,className:"relative group rounded-full focus:outline-none focus-visible:ring-2 focus-visible:ring-ring","aria-label":r?"Change contact photo":"Upload contact photo",children:[e.jsx(knt,{firstName:t,lastName:n,avatarUrl:r,email:a,size:i}),e.jsx("span",{className:"absolute inset-0 rounded-full bg-foreground/55 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center",children:c?e.jsx(Ct,{className:"h-5 w-5 text-background animate-spin"}):e.jsx(cg,{className:"h-5 w-5 text-background"})}),c&&e.jsx("span",{className:"absolute inset-0 rounded-full bg-foreground/55 flex items-center justify-center",children:e.jsx(Ct,{className:"h-5 w-5 text-background animate-spin"})})]}),r&&e.jsxs(B,{variant:"ghost",size:"sm",className:"text-muted-foreground gap-1.5",onClick:p,disabled:c,children:[e.jsx(Sn,{className:"h-3.5 w-3.5"}),"Remove"]}),e.jsx("input",{ref:l,type:"file",accept:"image/*",className:"hidden",onChange:f=>{var v;const y=(v=f.target.files)==null?void 0:v[0];y&&m(y)}})]})}const yFn={job_title:"Job title",company_name:"Company",city:"City",state:"State",avatar_url:"Profile photo",email:"Email",phone:"Phone"},vFn=4e3,bFn=5*60*1e3;function _Fn({open:s,onOpenChange:t,contactId:n,contactName:r,hasEmail:a}){var G;const{toast:i}=vi(),l=Bt(),[o,c]=_.useState(""),[d,u]=_.useState(!1),[h,m]=_.useState(!1),[p,f]=_.useState(null),[y,v]=_.useState(!1),[g,b]=_.useState(null),[j,S]=_.useState(null),[C,E]=_.useState(0),P=_.useRef(null),[M,I]=_.useState({job_title:!0,company_name:!0,city:!0,state:!0,avatar_url:!1,email:!1,phone:!1});_.useEffect(()=>{if(!j||!s)return;P.current=Date.now(),E(0);let $=!1,H=null,Y=null;const Z=async()=>{if(!$)try{const{data:ne,error:ce}=await q.functions.invoke("enrich-contact",{body:{contact_id:n,batch_id:j}});if(ce)throw ce;if((ne==null?void 0:ne.status)==="pending"){E(Date.now()-(P.current||Date.now()));return}ne!=null&&ne.ok&&ne.found?(f(ne.profile),b(ne.matched_on??null),S(null)):(v(!0),S(null))}catch(ne){i({title:"Enrichment status check failed",description:(ne==null?void 0:ne.message)??"Please try again.",variant:"destructive"}),S(null)}};return Z(),H=setInterval(Z,vFn),Y=setTimeout(()=>{$||(S(null),i({title:"Enrichment is taking longer than expected",description:"The provider has not finished processing yet. You can close this dialog and try again later.",variant:"default"}))},bFn),()=>{$=!0,H&&clearInterval(H),Y&&clearTimeout(Y)}},[j,s,n,i]);const D=async()=>{u(!0),v(!1),f(null),S(null);try{const{data:$,error:H}=await q.functions.invoke("enrich-contact",{body:{contact_id:n,linkedin_url:o.trim()||void 0}});if(H)throw H;if(($==null?void 0:$.status)==="pending"&&($!=null&&$.batch_id)){S($.batch_id);return}if(!($!=null&&$.found)){v(!0);return}f($.profile),b($.matched_on??null)}catch($){i({title:"Enrichment failed",description:($==null?void 0:$.message)??"Please try again.",variant:"destructive"})}finally{u(!1)}},O=()=>{var H,Y;if(!p)return[];const $=[];if(p.job_title&&$.push({key:"job_title",value:p.job_title}),p.company_name&&$.push({key:"company_name",value:p.company_name}),p.city&&$.push({key:"city",value:p.city}),p.state&&$.push({key:"state",value:p.state}),p.photo_url&&$.push({key:"avatar_url",value:p.photo_url}),(H=p.emails)!=null&&H.length&&$.push({key:"email",value:p.emails[0]}),(Y=p.phones)!=null&&Y.length&&$.push({key:"phone",value:p.phones[0]}),!p.city&&!p.state&&p.location){const[Z,ne]=p.location.split(",").map(ce=>ce.trim());Z&&$.push({key:"city",value:Z}),ne&&$.push({key:"state",value:ne})}return $},V=async()=>{const $={};for(const H of O())M[H.key]&&($[H.key==="avatar_url"?"avatar_url":H.key]=H.value);if(Object.keys($).length===0){i({title:"Nothing selected",description:"Pick at least one field to save."});return}m(!0);try{const{error:H}=await q.from("innercircle_contacts").update($).eq("id",n);if(H)throw H;await l.invalidateQueries({queryKey:["contact",n]}),await l.invalidateQueries({queryKey:["contacts"]}),i({title:"Contact updated",description:`${Object.keys($).length} field(s) saved.`}),t(!1)}catch(H){i({title:"Could not save",description:(H==null?void 0:H.message)??"Please try again.",variant:"destructive"})}finally{m(!1)}};return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"max-w-lg",children:[e.jsxs(Os,{children:[e.jsxs(Ds,{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4 text-primary"}),"Find person details — ",r]}),e.jsx(_r,{children:"Looks up public professional details (job title, company, social profiles) for this person and lets you choose what to save. This does not look up home or property data — use the Property tab for that."})]}),e.jsxs("div",{className:"space-y-4",children:[!p&&!j&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"li-url",children:"LinkedIn URL (optional)"}),e.jsx(xe,{id:"li-url",placeholder:"https://linkedin.com/in/username",value:o,onChange:$=>c($.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."})]}),j&&e.jsxs("div",{className:"rounded-lg border border-dashed p-4 text-sm text-center space-y-2",children:[e.jsx(Ct,{className:"h-5 w-5 animate-spin mx-auto text-primary"}),e.jsx("p",{className:"font-medium",children:"Searching public profiles…"}),e.jsx("p",{className:"text-muted-foreground",children:"The enrichment provider is processing this lookup. This can take 10–30 seconds."}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Elapsed: ",Math.floor(C/1e3),"s"]})]}),y&&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(Ji,{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}),g&&e.jsxs(Oe,{variant:"secondary",className:"text-[10px]",children:["matched via ",g]})]}),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(Xa,{className:"h-3 w-3"}),p.location]}),p.industry&&e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Cx,{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(dg,{className:"h-3 w-3"})," LinkedIn ",e.jsx(wr,{className:"h-3 w-3"})]})]})]}),p.summary&&e.jsx("p",{className:"text-sm text-muted-foreground whitespace-pre-line",children:p.summary}),!!((G=p.experience)!=null&&G.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(($,H)=>e.jsxs("p",{className:"text-sm",children:[$.title," ",$.company?`· ${$.company}`:"",$.starts_at?e.jsxs("span",{className:"text-muted-foreground text-xs",children:[" (",$.starts_at,$.ends_at?` – ${$.ends_at}`:" – present",")"]}):null]},H))]}),O().length===0&&e.jsx("div",{className:"rounded-lg border border-dashed p-3 text-sm text-muted-foreground",children:"We found this person, but the public profile didn’t include any details we can save to the contact (job title, company, city, state, photo, email or phone). Try adding their LinkedIn address and searching again."}),O().length>0&&e.jsxs("div",{className:"space-y-2 rounded-lg border p-3",children:[e.jsx("p",{className:"text-xs font-semibold uppercase text-muted-foreground",children:"Save to contact"}),O().map($=>e.jsxs("label",{className:"flex items-start gap-2 text-sm",children:[e.jsx($a,{checked:M[$.key],onCheckedChange:H=>I(Y=>({...Y,[$.key]:H===!0}))}),e.jsxs("span",{className:"min-w-0",children:[e.jsxs("span",{className:"font-medium",children:[yFn[$.key],": "]}),e.jsx("span",{className:"text-muted-foreground break-all",children:$.value})]})]},$.key))]})]})})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Close"}),!p&&!j?e.jsxs(B,{onClick:D,disabled:d,children:[d?e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(un,{className:"h-4 w-4 mr-2"}),d?"Searching…":"Find profile"]}):j?e.jsxs(B,{disabled:!0,children:[e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),"Searching…"]}):e.jsxs(B,{onClick:V,disabled:h||O().every($=>!M[$.key]),children:[h&&e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),"Save selected"]})]})]})})}const wFn=["jeremy@relevelup.com"];function jFn(){const{user:s}=hs(),t=((s==null?void 0:s.email)||"").toLowerCase();return wFn.includes(t)}const w2t="America/New_York";function NFn(s){const t=new Date(s),n=new Intl.DateTimeFormat("en-US",{timeZone:w2t,month:"short",day:"numeric",year:"numeric"}).format(t),r=new Intl.DateTimeFormat("en-US",{timeZone:w2t,hour:"numeric",minute:"2-digit"}).format(t);return`${n} · ${r}`}function kFn(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 SFn({contactId:s,ownerUserId:t,legacyNote:n}){const r=Bt(),[a,i]=_.useState(""),{data:l=[],isLoading:o}=at({queryKey:["contact-notes",s],queryFn:async()=>{const{data:u,error:h}=await q.from("innercircle_contact_notes").select("id, body, source, author_name, created_at").eq("contact_id",s).order("created_at",{ascending:!1});if(h)throw h;return u||[]},enabled:!!s}),c=mt({mutationFn:async u=>{var y,v,g;const{data:h}=await q.auth.getUser(),m=h.user,p=((y=m==null?void 0:m.user_metadata)==null?void 0:y.full_name)||[(v=m==null?void 0:m.user_metadata)==null?void 0:v.first_name,(g=m==null?void 0:m.user_metadata)==null?void 0:g.last_name].filter(Boolean).join(" ")||(m==null?void 0:m.email)||null,{error:f}=await q.from("innercircle_contact_notes").insert({contact_id:s,owner_user_id:t||(m==null?void 0:m.id),author_user_id:m==null?void 0:m.id,author_name:p,source:"agent",body:u});if(f)throw f},onSuccess:()=>{i(""),r.invalidateQueries({queryKey:["contact-notes",s]}),ia({title:"Note added"})},onError:u=>ia({title:"Could not add note",description:u.message,variant:"destructive"})}),d=mt({mutationFn:async u=>{const{error:h}=await q.from("innercircle_contact_notes").delete().eq("id",u);if(h)throw h},onSuccess:()=>r.invalidateQueries({queryKey:["contact-notes",s]})});return e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-3",children:e.jsxs(St,{className:"flex items-center gap-2 text-base",children:[e.jsx(Hi,{className:"h-4 w-4 text-primary"}),"Notes",l.length>0&&e.jsx(Oe,{variant:"secondary",className:"ml-1 rounded-full text-[11px]",children:l.length})]})}),e.jsxs(Me,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ms,{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(B,{size:"sm",disabled:!a.trim()||c.isPending,onClick:()=>c.mutate(a.trim()),children:[c.isPending?e.jsx(Ct,{className:"mr-1.5 h-3.5 w-3.5 animate-spin"}):null,"Add Note"]})})]}),o?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading notes…"}):l.length===0&&!n?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No notes yet — add context about this relationship."}):e.jsxs("div",{className:"space-y-3",children:[l.map(u=>e.jsxs("div",{className:"group rounded-xl border border-border/60 bg-muted/30 p-3",children:[e.jsxs("div",{className:"mb-1.5 flex flex-wrap items-center gap-2 text-[11px] text-muted-foreground",children:[e.jsxs("span",{className:"inline-flex items-center gap-1 font-medium text-foreground/80",children:[e.jsx(Gr,{className:"h-3 w-3"}),NFn(u.created_at)]}),e.jsxs("span",{children:["· ",kFn(u.created_at)]}),u.source!=="agent"?e.jsxs(Oe,{variant:"outline",className:"gap-1 text-[10px]",children:[e.jsx(un,{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(Sn,{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 CFn="9a88a47c-cb2a-4401-a2b5-111a76b19f9d";function AFn({open:s,onOpenChange:t,contact:n}){var G;const{user:r}=hs(),a=Fn(),i=Bt(),{intakePage:l,isLoading:o}=dLe(),{isGmailConnected:c,gmailEmail:d}=Vg(),u=oLe(),{data:h}=at({queryKey:["profile-for-invite",r==null?void 0:r.id],enabled:!!(r!=null&&r.id)&&s,queryFn:async()=>{const{data:$}=await q.from("profiles").select("name, email, avatar_url").eq("id",r.id).maybeSingle();return $}}),m=(h==null?void 0:h.name)||((G=r==null?void 0:r.email)==null?void 0:G.split("@")[0])||"Your Agent",p=m.split(" ")[0],f=l?`https://contacts.relevelup.com/${l.slug}`:"",y=_.useMemo(()=>`Hi ${n.first_name}, I'm updating my contact list and want to make sure I have your latest info — the best phone, email, address, and a couple of dates I love to remember (like your birthday and home anniversary). It only takes about a minute, and it helps me stay in touch the right way. Thanks so much!`,[n.first_name]),[v,g]=_.useState("gmail"),[b,j]=_.useState(""),[S,C]=_.useState(""),[E,P]=_.useState(!1);_.useEffect(()=>{s&&(j(`Quick favor, ${n.first_name} — can you update your info?`),C(y),g(c?"gmail":"system"))},[s,y,n.first_name,c]);const M=_.useMemo(()=>S.split(/\n\n+/).map($=>`

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

`).join(""),[S]),I=async()=>{var $,H;if(!l)return f;try{const{data:Y,error:Z}=await q.functions.invoke("process-intake-submissions",{body:{action:"generate_tokens",contact_ids:[n.id],intake_page_id:l.id}}),ne=Z?null:(H=($=Y==null?void 0:Y.tokens)==null?void 0:$[0])==null?void 0:H.token;return ne?`${f}?t=${ne}`:f}catch{return f}},D=$=>`
${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 →

${$}

Sent with care by ${m}

Powered by ReLevelUp

`,O=async()=>{if(!l){se.error("Set up your Connect Page first",{action:{label:"Set Up",onClick:()=>a("/mission-control/connect-page")}});return}if(!b.trim()||!S.trim()){se.error("Subject and message are required");return}P(!0);const $=await I(),H=D($),Y=async()=>{const{data:Z,error:ne}=await q.functions.invoke("send-connect-invite",{body:{contactEmail:n.email,subject:b,htmlBody:H,replyToEmail:(h==null?void 0:h.email)||(r==null?void 0:r.email),agentName:m}});if(ne)throw ne;if(!(Z!=null&&Z.success))throw new Error((Z==null?void 0:Z.error)||"Failed to send")};try{if(v==="gmail"&&c){const{data:Z,error:ne}=await q.functions.invoke("gmail-send",{body:{to:n.email,subject:b,body:H,contactId:n.id}});let ce=Z&&Z.error?Z:null;if(ne){ce={error:"send_failed",message:ne.message};const ie=ne.context;if(ie&&typeof ie.json=="function")try{ce=await ie.clone().json()}catch{}}if(ce)if(ce.error==="insufficient_scope")await Y(),se.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(ce.message||ce.error||"Failed to send");else if(!(Z!=null&&Z.success))throw new Error("Failed to send")}else await Y();try{await u.mutateAsync({contactId:n.id,actionTypeId:CFn,notes:`Sent Connect Page invite — Subject: "${b}"`})}catch(Z){console.warn("Failed to log activity:",Z)}i.invalidateQueries({queryKey:["contact-touch-logs"]}),se.success("Connect Page invite sent!"),t(!1)}catch(Z){console.error("Send error:",Z),se.error(Z instanceof Error?Z.message:"Failed to send invite")}finally{P(!1)}},V=S.split(/\n\n+/).filter(Boolean);return e.jsx(Ls,{open:s,onOpenChange:$=>!E&&t($),children:e.jsxs(Ps,{className:"sm:max-w-[720px] max-h-[92vh] overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsxs(Ds,{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-5 w-5 text-primary"}),"Send Connect Page Invite"]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Ask ",e.jsxs("span",{className:"font-medium",children:[n.first_name," ",n.last_name||""]})," to share their latest contact info — takes them about a minute."]})]}),o?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin text-primary"})}):l?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(J,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Send From"}),e.jsx(Yr,{value:v,onValueChange:$=>g($),className:"mt-1.5",children:e.jsxs(Zr,{className:"grid w-full grid-cols-2",children:[e.jsxs(Ht,{value:"gmail",disabled:!c,children:[e.jsx(ln,{className:"h-3.5 w-3.5 mr-1.5"}),c?`Gmail (${d})`:"Gmail (not connected)"]}),e.jsxs(Ht,{value:"system",children:[e.jsx(un,{className:"h-3.5 w-3.5 mr-1.5"}),"System Email"]})]})}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-1.5",children:v==="gmail"?"Replies go directly to your Gmail inbox.":`Sent from notifications@dashboard.relevelup.com — replies go to ${(h==null?void 0:h.email)||(r==null?void 0:r.email)||"your account email"}.`})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"invite-subject",children:"Subject"}),e.jsx(xe,{id:"invite-subject",value:b,onChange:$=>j($.target.value),className:"mt-1.5"})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"invite-message",children:"Personal Message"}),e.jsx(Ms,{id:"invite-message",value:S,onChange:$=>C($.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(J,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Preview"}),e.jsxs("a",{href:f,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-primary hover:underline flex items-center gap-1",children:["Open Connect Page ",e.jsx(wr,{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:V.map(($,H)=>e.jsx("p",{className:"text-[13px] leading-relaxed text-slate-600 whitespace-pre-line",children:$},H))}),e.jsx("div",{className:"px-6 pb-6",children:e.jsxs("div",{className:"rounded-xl border border-slate-200 bg-slate-50 px-5 py-6 text-center",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-slate-400",children:"Update Your Info"}),e.jsx("p",{className:"mt-1 text-sm font-semibold text-slate-800",children:"Takes about a minute — promise"}),e.jsx("span",{className:"mt-4 inline-block rounded-lg bg-gradient-to-br from-[#406E71] to-[#2a4c64] px-7 py-3 text-sm font-semibold text-white",children:"Share My Info →"}),e.jsxs("p",{className:"mt-3 break-all text-[11px] text-slate-400",children:[f,"?t=…"]})]})}),e.jsx("div",{className:"border-t border-slate-100 px-6 py-4 text-center",children:e.jsxs("p",{className:"text-[11px] text-slate-400",children:["Sent with care by ",m]})})]})}),e.jsxs("p",{className:"text-[11px] text-muted-foreground mt-1.5",children:["Each invite includes a private link that pre-fills ",n.first_name,"'s current info, so their updates come straight back to this contact record."]})]}),e.jsxs("div",{className:"flex items-center justify-end gap-2 pt-2",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),disabled:E,children:"Cancel"}),e.jsx(B,{onClick:O,disabled:E,children:E?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"h-4 w-4 mr-1.5 animate-spin"})," Sending…"]}):e.jsxs(e.Fragment,{children:[e.jsx(Or,{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(B,{onClick:()=>a("/mission-control/connect-page"),children:[e.jsx(vd,{className:"h-4 w-4 mr-1"})," Set Up Connect Page"]})]})]})})}function EFn(){const{user:s}=hs();return at({queryKey:["cmas",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.from("cmas").select("*").eq("agent_id",s.id).order("updated_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function TFn(s){return at({queryKey:["cma",s],queryFn:async()=>{const{data:t,error:n}=await q.from("cmas").select("*").eq("id",s).single();if(n)throw n;return t},enabled:!!s})}function MFn(s){return at({queryKey:["cma-comps",s],queryFn:async()=>{const{data:t,error:n}=await q.from("cma_comps").select("*").eq("cma_id",s).order("position",{ascending:!0});if(n)throw n;return t||[]},enabled:!!s})}function qYt(){const s=Bt(),{user:t}=hs(),{leadSite:n}=lf();return mt({mutationFn:async r=>{const{data:a,error:i}=await q.from("cmas").insert({agent_id:t.id,lead_site_id:(n==null?void 0:n.id)??null,contact_id:r.contactId??null,deal_id:r.dealId??null,buyer_mode:!!r.buyerMode,title:r.title??r.subject.address,subject:r.subject,settings:{sqftPct:.2,monthsBack:6,statuses:["Active","Pending","Closed"]}}).select("*").single();if(i)throw i;return a},onSuccess:()=>s.invalidateQueries({queryKey:["cmas"]})})}function PFn(){const s=Bt();return mt({mutationFn:async({id:t,patch:n})=>{const{data:r,error:a}=await q.from("cmas").update(n).eq("id",t).select("*").single();if(a)throw a;return r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["cma",n.id]}),s.invalidateQueries({queryKey:["cmas"]})}})}function LFn(){const s=Bt();return mt({mutationFn:async t=>{const{error:n}=await q.from("cmas").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["cmas"]})})}function IFn(){const{leadSite:s}=lf();return mt({mutationFn:async t=>{const{data:n,error:r}=await q.functions.invoke("cma-subject-lookup",{body:{...t,leadSiteId:(s==null?void 0:s.id)??null}});if(r)throw r;return n}})}function DFn(){const{leadSite:s}=lf();return mt({mutationFn:async t=>{const{data:n,error:r}=await q.functions.invoke("cma-comp-search",{body:{...t,leadSiteId:t.leadSiteId??(s==null?void 0:s.id)??null}});if(r)throw r;return n}})}function RFn(){const s=Bt();return mt({mutationFn:async({cmaId:t,comps:n})=>{if(await q.from("cma_comps").delete().eq("cma_id",t),!n.length)return;const r=n.map((i,l)=>({cma_id:t,mls_number:i.mlsNumber??null,source_provider:i.source_provider??null,selected:i.selected!==!1,manual:!!i.manual,score:i.score??null,position:l,snapshot:i})),{error:a}=await q.from("cma_comps").insert(r);if(a)throw a},onSuccess:(t,n)=>s.invalidateQueries({queryKey:["cma-comps",n.cmaId]})})}function j2t(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 FFn(s){return at({queryKey:["contact-video-replies",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("video_replies").select(` *, video:agent_videos(id, title, thumbnail_url, playback_url) `).eq("contact_id",s).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function OFn(s){return at({queryKey:["client-portal",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("client_portals").select("*").eq("deal_id",s).maybeSingle();if(n)throw n;return t},enabled:!!s})}function Snt(){const s=ha(),t=Bt();return mt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("client_portals").insert({deal_id:n.deal_id,owner_user_id:s,slug:"",is_enabled:n.is_enabled??!0,visibility:n.visibility||"private",require_onboarding:n.require_onboarding??!0,allow_spouse:n.allow_spouse??!1,client_name:n.client_name||null,client_email:n.client_email||null,client_phone:n.client_phone||null,invite_method:n.invite_method||"email"}).select().single();if(a)throw a;return r},onSuccess:(n,r)=>{t.invalidateQueries({queryKey:["client-portal",r.deal_id]})}})}function VW(){const s=Bt();return mt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("client_portals").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["client-portal",t.deal_id]}),s.invalidateQueries({queryKey:["all-client-portals"]})}})}function $Yt(){const s=Bt();return mt({mutationFn:async t=>{const{data:n,error:r}=await q.from("client_portals").update({archived_at:new Date().toISOString(),is_enabled:!1}).eq("id",t).select().single();if(r)throw r;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["client-portal",t.deal_id]}),s.invalidateQueries({queryKey:["all-client-portals"]})}})}function VYt(){const s=Bt();return mt({mutationFn:async t=>{const{data:n,error:r}=await q.from("client_portals").update({archived_at:null}).eq("id",t).select().single();if(r)throw r;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["client-portal",t.deal_id]}),s.invalidateQueries({queryKey:["all-client-portals"]})}})}function HYt(){const s=Bt();return mt({mutationFn:async({id:t,dealId:n})=>{await q.from("portal_updates").delete().eq("portal_id",t);const{error:r}=await q.from("client_portals").delete().eq("id",t);if(r)throw r;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["client-portal",t]}),s.invalidateQueries({queryKey:["all-client-portals"]})}})}function zFn(s){return at({queryKey:["portal-updates",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("portal_updates").select("*").eq("portal_id",s).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function GYt(){const s=Bt();return mt({mutationFn:async t=>{const{data:n,error:r}=await q.from("portal_updates").insert({portal_id:t.portal_id,title:t.title,content:t.content||null,video_url:t.video_url||null,is_stage_change:t.is_stage_change||!1}).select().single();if(r)throw r;return n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["portal-updates",n.portal_id]})}})}function BFn(){const s=ha();return at({queryKey:["portal-custom-questions",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("portal_custom_questions").select("*").eq("owner_user_id",s).eq("is_active",!0).order("sort_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function UFn(){const s=ha(),t=Bt();return mt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("portal_custom_questions").insert({owner_user_id:s,question_text:n.question_text,field_type:n.field_type,options:n.options||[],is_required:n.is_required||!1,sort_order:n.sort_order||0}).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["portal-custom-questions"]})}})}function qFn(){const s=Bt();return mt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("portal_custom_questions").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["portal-custom-questions"]})}})}function $Fn(){const s=Bt();return mt({mutationFn:async t=>{const{error:n}=await q.from("portal_custom_questions").update({is_active:!1}).eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["portal-custom-questions"]})}})}function wS(s){const t=window.location.hostname;return t==="localhost"||t.includes("lovable.app")?`${window.location.origin}/portal/${s}`:`https://clients.relevelup.com/${s}`}function VFn({contactId:s}){const t=Fn(),n=Bt(),[r,a]=_.useState(null),[i,l]=_.useState(!1),[o,c]=_.useState(!1),[d,u]=_.useState(""),[h,m]=_.useState(""),[p,f]=_.useState(null),y=VW(),v=GYt(),{data:g,isLoading:b}=at({queryKey:["contact-portals",s],queryFn:async()=>{const{data:M,error:I}=await q.from("deal_pipeline").select("id, deal_name, deal_type").eq("contact_id",s);if(I)throw I;if(!M||M.length===0)return[];const D=M.map(G=>G.id),{data:O,error:V}=await q.from("client_portals").select("*").in("deal_id",D).is("archived_at",null);if(V)throw V;return(O||[]).map(G=>({...G,deal:M.find($=>$.id===G.deal_id)}))},enabled:!!s}),j=(g==null?void 0:g.map(M=>M.id))||[],{data:S}=at({queryKey:["contact-portal-updates",j],queryFn:async()=>{if(j.length===0)return{};const{data:M,error:I}=await q.from("portal_updates").select("*").in("portal_id",j).order("created_at",{ascending:!1});if(I)throw I;const D={};return(M||[]).forEach(O=>{D[O.portal_id]||(D[O.portal_id]=O)}),D},enabled:j.length>0}),C=M=>{navigator.clipboard.writeText(wS(M)),a(M),se.success("Portal link copied!"),setTimeout(()=>a(null),2e3)},E=async(M,I)=>{if(!d.trim())return;const D=d.trim(),O=h.trim();await v.mutateAsync({portal_id:M,title:D,content:O||void 0}),c(!1),u(""),m(""),n.invalidateQueries({queryKey:["contact-portal-updates"]});try{const{data:V,error:G}=await q.functions.invoke("send-portal-notification",{body:{portal_id:M,update_title:D,update_content:O||null,portal_url:I?wS(I):void 0,force:!0}});if(G)throw G;V!=null&&V.emailSent?se.success("Update posted & client emailed"):se.success(`Update posted (${(V==null?void 0:V.reason)||"no email sent"})`)}catch(V){console.error("Portal notification failed:",V),se.success("Update posted (notification failed to send)")}},P=async()=>{p&&(await y.mutateAsync({id:p.id,welcome_message:p.welcome_message,next_step_text:p.next_step_text,is_enabled:p.is_enabled,show_post_close_tips:p.show_post_close_tips,review_url:p.review_url}),l(!1),f(null),n.invalidateQueries({queryKey:["contact-portals",s]}),se.success("Portal settings updated!"))};return b||!g||g.length===0?null:e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-2",children:e.jsxs(St,{className:"text-base flex items-center gap-2",children:[e.jsx(sl,{className:"h-4 w-4"}),"Client Portal"]})}),e.jsx(Me,{className:"space-y-3",children:g.map(M=>{var V,G,$;const I=((V=M.stage_mapping)==null?void 0:V.length)>0?M.stage_mapping:BPe(((G=M.deal)==null?void 0:G.deal_type)||"buyer"),D=I==null?void 0:I[M.current_stage_index??0],O=S==null?void 0:S[M.id];return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:(($=M.deal)==null?void 0:$.deal_name)||"Portal"}),D&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Stage: ",D.label||D.name]})]}),e.jsx(Oe,{variant:M.is_enabled?"default":"secondary",className:"text-[10px] flex-shrink-0",children:M.is_enabled?"Active":"Disabled"})]}),O&&e.jsxs("div",{className:"bg-muted/50 rounded-md p-2",children:[e.jsx("p",{className:"text-xs font-medium truncate",children:O.title}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:Hs(new Date(O.created_at),"MMM d, yyyy")})]}),e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[e.jsxs(B,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>C(M.slug),children:[r===M.slug?e.jsx(ea,{className:"h-3 w-3 mr-1"}):e.jsx(Ia,{className:"h-3 w-3 mr-1"}),"Copy Link"]}),e.jsxs(B,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>window.open(wS(M.slug),"_blank"),children:[e.jsx(wr,{className:"h-3 w-3 mr-1"}),"View"]}),e.jsxs(Ls,{open:o,onOpenChange:c,children:[e.jsx(nl,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>c(!0),children:[e.jsx(Hi,{className:"h-3 w-3 mr-1"}),"Post Update"]})}),e.jsxs(Ps,{children:[e.jsx(Os,{children:e.jsx(Ds,{children:"Post Portal Update"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Title"}),e.jsx(xe,{value:d,onChange:H=>u(H.target.value),placeholder:"e.g. Inspection completed!"})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Details (optional)"}),e.jsx(Ms,{value:h,onChange:H=>m(H.target.value),placeholder:"Add more details...",rows:3})]}),e.jsxs(B,{onClick:()=>E(M.id,M.slug),disabled:!d.trim()||v.isPending,className:"w-full",children:[e.jsx(Or,{className:"h-4 w-4 mr-1"}),"Post Update"]})]})]})]}),e.jsxs(Ls,{open:i,onOpenChange:l,children:[e.jsx(nl,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>{f({...M}),l(!0)},children:[e.jsx(qc,{className:"h-3 w-3 mr-1"}),"Settings"]})}),e.jsxs(Ps,{children:[e.jsx(Os,{children:e.jsx(Ds,{children:"Portal Settings"})}),p&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(J,{children:"Portal Enabled"}),e.jsx(fn,{checked:p.is_enabled,onCheckedChange:H=>f({...p,is_enabled:H})})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Welcome Message"}),e.jsx(Ms,{value:p.welcome_message||"",onChange:H=>f({...p,welcome_message:H.target.value}),placeholder:"Welcome to your home journey!",rows:2})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Next Step"}),e.jsx(xe,{value:p.next_step_text||"",onChange:H=>f({...p,next_step_text:H.target.value}),placeholder:"What your client should do next..."})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Review URL"}),e.jsx(xe,{value:p.review_url||"",onChange:H=>f({...p,review_url:H.target.value}),placeholder:"https://..."})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(J,{children:"Show Post-Close Tips"}),e.jsx(fn,{checked:p.show_post_close_tips,onCheckedChange:H=>f({...p,show_post_close_tips:H})})]}),e.jsx(wc,{}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{onClick:P,disabled:y.isPending,className:"flex-1",children:"Save Settings"}),e.jsxs(B,{variant:"outline",onClick:()=>t(`/mission-control/pipeline?deal=${M.deal_id}`),children:[e.jsx(La,{className:"h-4 w-4 mr-1"}),"Full Settings"]})]})]})]})]})]}),g.length>1&&e.jsx(wc,{})]},M.id)})})]})}function HFn({contactId:s}){const{data:t}=at({queryKey:["agent-lead-sites-slugs"],queryFn:async()=>{const{data:l,error:o}=await q.from("lead_sites").select("id, subdomain_slug").eq("is_active",!0);if(o)throw o;return new Map((l||[]).map(c=>[c.id,c.subdomain_slug]))},staleTime:6e5}),n=t&&t.size>0,{data:r,isLoading:a}=at({queryKey:["contact-property-views",s],queryFn:async()=>{const{data:l,error:o}=await q.rpc("get_contact_property_views",{p_contact_id:s});if(o)throw o;return l||[]},enabled:!!s&&!!n});if(!n||a||!r||r.length===0)return null;const i=l=>{const o=t==null?void 0:t.get(l.lead_site_id);return o?`https://${o}.thelocalmove.com/listing/${l.mls_number}`:null};return e.jsxs(ve,{className:"overflow-hidden",children:[e.jsx(bt,{className:"pb-2",children:e.jsxs(St,{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(ya,{className:"h-4 w-4 text-primary"})}),"Property Activity",e.jsxs(Oe,{variant:"secondary",className:"text-xs ml-auto",children:[r.length," ",r.length===1?"property":"properties"]})]})}),e.jsx(Me,{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(Jr,{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(Gr,{className:"h-3 w-3"}),e.jsx("span",{title:Hs(new Date(l.viewed_at),"PPp"),children:Ed(new Date(l.viewed_at),{addSuffix:!0})})]})]}),o&&e.jsx(wr,{className:"h-3.5 w-3.5 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity"})]},l.mls_number)})})})]})}function GFn({contactId:s,contactName:t}){var O,V,G;const{user:n}=hs(),r=ha(),{hasIdx:a}=lf(),i=Bt(),[l,o]=_.useState(!1),[c,d]=_.useState(!1),[u,h]=_.useState(""),[m,p]=_.useState(null),[f,y]=_.useState(!1),[v,g]=_.useState(!1),{data:b,isLoading:j}=at({queryKey:["contact-property-alert",s],queryFn:async()=>{const{data:$,error:H}=await q.from("contact_property_alerts").select("*").eq("contact_id",s).maybeSingle();if(H)throw H;return $},enabled:!!s&&!!n}),[S,C]=_.useState({}),E=()=>{C({is_active:(b==null?void 0:b.is_active)??!0,min_price:(b==null?void 0:b.min_price)??null,max_price:(b==null?void 0:b.max_price)??null,min_beds:(b==null?void 0:b.min_beds)??null,min_baths:(b==null?void 0:b.min_baths)??null,min_sqft:(b==null?void 0:b.min_sqft)??null,max_sqft:(b==null?void 0:b.max_sqft)??null,cities:(b==null?void 0:b.cities)??[],zip_codes:(b==null?void 0:b.zip_codes)??[],property_types:(b==null?void 0:b.property_types)??[],frequency:(b==null?void 0:b.frequency)??"daily"}),o(!0)},P=mt({mutationFn:async()=>{const $={contact_id:s,owner_user_id:r,is_active:S.is_active??!0,min_price:S.min_price||null,max_price:S.max_price||null,min_beds:S.min_beds||null,min_baths:S.min_baths||null,min_sqft:S.min_sqft||null,max_sqft:S.max_sqft||null,cities:S.cities||[],zip_codes:S.zip_codes||[],property_types:S.property_types||[],frequency:S.frequency||"daily"};if(b!=null&&b.id){const{error:H}=await q.from("contact_property_alerts").update($).eq("id",b.id);if(H)throw H}else{const{error:H}=await q.from("contact_property_alerts").insert($);if(H)throw H}},onSuccess:()=>{i.invalidateQueries({queryKey:["contact-property-alert",s]}),i.invalidateQueries({queryKey:["contact-criteria-map"]}),o(!1),se.success("Home search saved!")},onError:$=>{se.error($.message||"Failed to save home search")}}),M=mt({mutationFn:async()=>{if(!(b!=null&&b.id))return;const{error:$}=await q.from("contact_property_alerts").delete().eq("id",b.id);if($)throw $},onSuccess:()=>{i.invalidateQueries({queryKey:["contact-property-alert",s]}),i.invalidateQueries({queryKey:["contact-criteria-map"]}),o(!1),se.success("Home search removed")}}),I=async()=>{if(b!=null&&b.id){y(!0),d(!0),h(""),p(null);try{const{data:$,error:H}=await q.functions.invoke("process-property-alerts",{body:{alert_id:b.id,mode:"preview"}});if(H)throw H;$!=null&&$.html?(h($.html),p({count:$.listings_count||0,recipient:$.recipient,subject:$.subject})):p({count:0,message:($==null?void 0:$.message)||"No matching listings found right now."})}catch($){se.error($.message||"Failed to generate preview"),d(!1)}finally{y(!1)}}},D=async()=>{if(b!=null&&b.id&&await Xi(`Send property alert email to ${t} now?`)){g(!0);try{const{data:$,error:H}=await q.functions.invoke("process-property-alerts",{body:{alert_id:b.id,mode:"send"}});if(H)throw H;$!=null&&$.sent_count?(se.success(`Sent ${$.sent_count} ${$.sent_count===1?"listing":"listings"} to ${$.recipient}`),i.invalidateQueries({queryKey:["contact-property-alert",s]})):se.info(($==null?void 0:$.message)||"No new matching listings to send right now.")}catch($){se.error($.message||"Failed to send alert")}finally{g(!1)}}};return j?null:b&&!l?e.jsxs(e.Fragment,{children:[e.jsxs(ve,{className:"overflow-hidden",children:[e.jsx(bt,{className:"pb-2",children:e.jsxs(St,{className:"text-base flex items-center gap-2",children:[e.jsx("div",{className:`h-7 w-7 rounded-lg flex items-center justify-center ${a&&b.is_active?"bg-green-500/10":"bg-muted"}`,children:a?b.is_active?e.jsx(Rg,{className:"h-4 w-4 text-green-600"}):e.jsx(cS,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Lr,{className:"h-4 w-4 text-muted-foreground"})}),a?"Property Alerts":"Home Search",a&&e.jsxs(Oe,{variant:b.is_active?"default":"secondary",className:"text-xs ml-auto",children:[b.is_active?"Active":"Paused"," · ",b.frequency]})]})}),e.jsxs(Me,{className:"pt-0 space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap gap-1.5 text-xs",children:[b.min_price||b.max_price?e.jsxs(Oe,{variant:"outline",className:"gap-1",children:[e.jsx(yd,{className:"h-3 w-3"}),b.min_price?`$${(b.min_price/1e3).toFixed(0)}k`:"$0"," - ",b.max_price?`$${(b.max_price/1e3).toFixed(0)}k`:"Any"]}):null,b.min_beds?e.jsxs(Oe,{variant:"outline",className:"gap-1",children:[e.jsx(q4,{className:"h-3 w-3"}),b.min_beds,"+ beds"]}):null,b.min_baths?e.jsxs(Oe,{variant:"outline",className:"gap-1",children:[e.jsx(S0,{className:"h-3 w-3"}),b.min_baths,"+ baths"]}):null,(O=b.cities)==null?void 0:O.map($=>e.jsxs(Oe,{variant:"outline",className:"gap-1",children:[e.jsx(Xa,{className:"h-3 w-3"}),$]},$)),(V=b.zip_codes)==null?void 0:V.map($=>e.jsx(Oe,{variant:"outline",children:$},$)),(G=b.property_types)==null?void 0:G.map($=>e.jsx(Oe,{variant:"outline",children:$},$))]}),a&&b.last_sent_at&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Last sent: ",new Date(b.last_sent_at).toLocaleDateString()]}),!a&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Automatic new-listing emails need an IDX website —"," ",e.jsx(ir,{to:"/mission-control/website",className:"text-primary hover:underline",children:"explore IDX websites"}),"."]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[a&&e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:I,disabled:f,children:[f?e.jsx(Ct,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(ya,{className:"h-4 w-4 mr-1"}),"Preview Email"]}),e.jsxs(B,{size:"sm",onClick:D,disabled:v||!b.is_active,title:b.is_active?"Send this alert email now":"Activate alert to send",children:[v?e.jsx(Ct,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Or,{className:"h-4 w-4 mr-1"}),"Send Now"]})]}),e.jsx(B,{variant:"outline",size:"sm",onClick:E,children:"Edit Search"}),e.jsxs(B,{variant:"destructive",size:"sm",onClick:()=>M.mutate(),disabled:M.isPending,children:[M.isPending?e.jsx(Ct,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Qn,{className:"h-4 w-4 mr-1"}),"Remove"]})]})]})]}),e.jsx(Ls,{open:c,onOpenChange:d,children:e.jsxs(Ps,{className:"max-w-3xl max-h-[90vh] flex flex-col",children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Property Alert Email Preview"}),(m==null?void 0:m.subject)&&e.jsxs("div",{className:"text-xs text-muted-foreground space-y-0.5 pt-1",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"To:"})," ",m.recipient]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Subject:"})," ",m.subject]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Listings:"})," ",m.count]})]})]}),e.jsx("div",{className:"flex-1 overflow-hidden border rounded-md bg-muted/30",children:f?e.jsxs("div",{className:"flex items-center justify-center h-96 text-muted-foreground",children:[e.jsx(Ct,{className:"h-5 w-5 mr-2 animate-spin"})," Building preview…"]}):u?e.jsx("iframe",{srcDoc:u,title:"Property alert preview",className:"w-full h-[65vh] bg-white rounded-md"}):e.jsx("div",{className:"flex items-center justify-center h-96 text-sm text-muted-foreground p-6 text-center",children:(m==null?void 0:m.message)||"No matching listings found right now."})}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>d(!1),children:"Close"}),u&&e.jsxs(B,{onClick:()=>{d(!1),D()},disabled:v||!b.is_active,children:[e.jsx(Or,{className:"h-4 w-4 mr-1"}),"Send to ",t]})]})]})})]}):l?e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-3",children:e.jsxs(St,{className:"text-base flex items-center gap-2",children:[a?e.jsx(Rg,{className:"h-4 w-4 text-primary"}):e.jsx(Lr,{className:"h-4 w-4 text-primary"}),b?"Edit":"Set up"," home search for ",t]})}),e.jsxs(Me,{className:"space-y-4",children:[e.jsx(UYt,{value:S,onChange:C,hasIdx:a,idxNote:e.jsx(B,{asChild:!0,variant:"link",size:"sm",className:"h-auto p-0 text-xs",children:e.jsx(ir,{to:"/mission-control/website",children:"Explore IDX websites"})})}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs(B,{onClick:()=>P.mutate(),disabled:P.isPending,className:"flex-1",children:[P.isPending?e.jsx(Ct,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Ho,{className:"h-4 w-4 mr-1"}),"Save"]}),e.jsx(B,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),b&&e.jsx(B,{variant:"destructive",size:"icon",onClick:()=>M.mutate(),disabled:M.isPending,children:e.jsx(Qn,{className:"h-4 w-4"})})]})]})]}):e.jsx(ve,{className:"overflow-hidden",children:e.jsx(Me,{className:"p-4",children:e.jsxs("button",{onClick:E,className:"w-full flex items-center gap-3 p-3 rounded-lg border border-dashed border-primary/30 hover:bg-primary/5 transition-colors",children:[e.jsx("div",{className:"h-9 w-9 rounded-lg bg-primary/10 flex items-center justify-center flex-shrink-0",children:a?e.jsx(Rg,{className:"h-4 w-4 text-primary"}):e.jsx(Lr,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"font-medium text-sm",children:"Add Home Search"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:a?`Automatically email ${t} new listings matching their criteria`:`Save what ${t} is looking for so you can match new listings to them`})]})]})})})}function WFn({contactId:s,contactName:t}){var Y;const{user:n}=hs(),r=ha(),{hasLeadSite:a}=lf(),i=Bt(),[l,o]=_.useState(!1),[c,d]=_.useState(""),[u,h]=_.useState([]),[m,p]=_.useState(!1),[f,y]=_.useState(!1),[v,g]=_.useState(!1),[b,j]=_.useState(""),S=_.useRef(null),C=_.useRef(null),{data:E}=at({queryKey:["agent-lead-site-cities",r],queryFn:async()=>{const{data:Z,error:ne}=await q.from("lead_sites").select("theme_config, mls_market_area").eq("agent_id",r).eq("is_active",!0).order("created_at",{ascending:!0}).limit(1).maybeSingle();if(ne||!Z)return[];const ce=Z.theme_config||{},ie=Array.isArray(ce.searchCities)?ce.searchCities:[];return Z.mls_market_area&&!ie.includes(Z.mls_market_area)&&ie.unshift(Z.mls_market_area),ie},enabled:!!r}),{data:P,isLoading:M}=at({queryKey:["contact-market-report",s],queryFn:async()=>{const{data:Z,error:ne}=await q.from("innercircle_contacts").select("market_report_enabled, market_report_cities").eq("id",s).single();if(ne)throw ne;return Z},enabled:!!s&&!!n});_.useEffect(()=>{const Z=ne=>{C.current&&!C.current.contains(ne.target)&&S.current&&!S.current.contains(ne.target)&&y(!1)};return document.addEventListener("mousedown",Z),()=>document.removeEventListener("mousedown",Z)},[]);const I=()=>{p((P==null?void 0:P.market_report_enabled)??!1),h((P==null?void 0:P.market_report_cities)??[]),o(!0)},D=Z=>{const ne=(Z||c).trim();ne&&!u.includes(ne)&&h([...u,ne]),d(""),y(!1)},O=(E||[]).filter(Z=>!u.includes(Z)&&Z.toLowerCase().includes(c.toLowerCase())),V=mt({mutationFn:async()=>{const{data:Z,error:ne}=await q.functions.invoke("send-market-report",{body:{action:"preview",agentId:r,cities:(P==null?void 0:P.market_report_cities)??[]}});if(ne)throw new Error(ne.message||"Failed to generate preview");if(Z&&!Z.ok&&Z.error)throw new Error(Z.error);return Z},onSuccess:Z=>{j(Z.html),g(!0)},onError:Z=>{se.error(Z.message||"Failed to generate preview")}}),G=mt({mutationFn:async()=>{const{data:Z,error:ne}=await q.functions.invoke("send-market-report",{body:{action:"send",agentId:r,cities:(P==null?void 0:P.market_report_cities)??[],contactIds:[s]}});if(ne)throw new Error(ne.message||"Failed to send report");if(Z&&!Z.ok&&Z.error)throw new Error(Z.error);return Z},onSuccess:()=>{se.success(`Market report sent to ${t}!`)},onError:Z=>{se.error(Z.message||"Failed to send report")}}),$=mt({mutationFn:async()=>{const{error:Z}=await q.from("innercircle_contacts").update({market_report_enabled:m,market_report_cities:u}).eq("id",s);if(Z)throw Z},onSuccess:()=>{i.invalidateQueries({queryKey:["contact-market-report",s]}),o(!1),se.success(m?"Monthly market report enabled!":"Market report disabled")},onError:Z=>{se.error(Z.message||"Failed to save")}}),H=mt({mutationFn:async()=>{const{error:Z}=await q.from("innercircle_contacts").update({market_report_enabled:!1,market_report_cities:[]}).eq("id",s);if(Z)throw Z},onSuccess:()=>{i.invalidateQueries({queryKey:["contact-market-report",s]}),o(!1),p(!1),h([]),se.success("Market report removed")},onError:Z=>{se.error(Z.message||"Failed to remove market report")}});return!a||M?null:P!=null&&P.market_report_enabled&&!l?e.jsxs(ve,{className:"overflow-hidden",children:[e.jsx(bt,{className:"pb-2",children:e.jsxs(St,{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(bl,{className:"h-4 w-4 text-primary"})}),"Monthly Market Report",e.jsx(Oe,{variant:"default",className:"text-xs ml-auto",children:"Active"})]})}),e.jsxs(Me,{className:"pt-0 space-y-2",children:[e.jsx("div",{className:"flex flex-wrap gap-1.5 text-xs",children:((Y=P.market_report_cities)==null?void 0:Y.length)>0?P.market_report_cities.map(Z=>e.jsxs(Oe,{variant:"outline",className:"gap-1",children:[e.jsx(Xa,{className:"h-3 w-3"}),Z]},Z)):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(B,{variant:"outline",size:"sm",onClick:()=>V.mutate(),disabled:V.isPending,className:"flex-1",children:[V.isPending?e.jsx(Ct,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(ya,{className:"h-4 w-4 mr-1"}),"Preview"]}),e.jsxs(B,{variant:"default",size:"sm",onClick:()=>G.mutate(),disabled:G.isPending,className:"flex-1",children:[G.isPending?e.jsx(Ct,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Or,{className:"h-4 w-4 mr-1"}),"Send Now"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",size:"sm",onClick:I,className:"flex-1",children:"Manage"}),e.jsxs(B,{variant:"destructive",size:"sm",onClick:()=>H.mutate(),disabled:H.isPending,className:"flex-1",children:[H.isPending?e.jsx(Ct,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Qn,{className:"h-4 w-4 mr-1"}),"Remove"]})]}),e.jsx(Ls,{open:v,onOpenChange:g,children:e.jsxs(Ps,{className:"max-w-3xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsx(Os,{children:e.jsxs(Ds,{className:"flex items-center gap-2",children:[e.jsx(bl,{className:"h-5 w-5 text-primary"}),"Market Report Preview"]})}),e.jsx("div",{className:"flex-1 overflow-y-auto -mx-6 px-6",children:e.jsx("div",{className:"border rounded-lg overflow-hidden",dangerouslySetInnerHTML:{__html:b}})}),e.jsxs("div",{className:"flex gap-2 pt-4 border-t",children:[e.jsxs(B,{onClick:()=>{g(!1),G.mutate()},disabled:G.isPending,className:"flex-1",children:[G.isPending?e.jsx(Ct,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Or,{className:"h-4 w-4 mr-1"}),"Send to ",t]}),e.jsx(B,{variant:"outline",onClick:()=>g(!1),children:"Close"})]})]})})]})]}):l?e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-3",children:e.jsxs(St,{className:"text-base flex items-center gap-2",children:[e.jsx(bl,{className:"h-4 w-4 text-primary"}),"Market Report for ",t]})}),e.jsxs(Me,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(J,{children:"Send Monthly Report"}),e.jsx(fn,{checked:m,onCheckedChange:p})]}),m&&e.jsxs("div",{children:[e.jsxs(J,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(Xa,{className:"h-3.5 w-3.5"})," Report Cities"]}),e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Select cities from your website's configured areas."}),e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(xe,{ref:S,value:c,onChange:Z=>{d(Z.target.value),y(!0)},onFocus:()=>y(!0),placeholder:"Type to search cities...",onKeyDown:Z=>{Z.key==="Enter"&&(Z.preventDefault(),O.length>0?D(O[0]):D())}}),e.jsx(tl,{className:"absolute right-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground pointer-events-none"})]}),e.jsx(B,{type:"button",variant:"outline",size:"sm",onClick:()=>D(),children:e.jsx(rn,{className:"h-4 w-4"})})]}),f&&O.length>0&&e.jsx("div",{ref:C,className:"absolute z-50 mt-1 w-full max-h-60 overflow-y-auto rounded-md border bg-popover shadow-md",children:O.map(Z=>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(Z),children:[e.jsx(Xa,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}),Z]},Z))})]}),u.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-2",children:u.map(Z=>e.jsxs(Oe,{variant:"secondary",className:"gap-1",children:[Z,e.jsx("button",{onClick:()=>h(u.filter(ne=>ne!==Z)),children:e.jsx(Qn,{className:"h-3 w-3"})})]},Z))})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs(B,{onClick:()=>$.mutate(),disabled:$.isPending,className:"flex-1",children:[$.isPending?e.jsx(Ct,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Ho,{className:"h-4 w-4 mr-1"}),"Save"]}),e.jsx(B,{variant:"outline",onClick:()=>o(!1),children:"Cancel"})]})]})]}):e.jsx(ve,{className:"overflow-hidden",children:e.jsx(Me,{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(bl,{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 KFn({contactId:s,contactName:t}){const n=Bt(),[r,a]=_.useState(""),{data:i,isLoading:l}=at({queryKey:["contact-email-prefs",s],enabled:!!s,queryFn:async()=>{const{data:d,error:u}=await q.from("innercircle_contacts").select("email, email_opt_out, email_opt_out_at, email_opt_out_reason").eq("id",s).single();if(u)throw u;return d}});_.useEffect(()=>{a((i==null?void 0:i.email_opt_out_reason)||"")},[i==null?void 0:i.email_opt_out_reason]);const o=mt({mutationFn:async({optOut:d,reasonText:u})=>{const{error:h}=await q.from("innercircle_contacts").update({email_opt_out:d,email_opt_out_at:d?new Date().toISOString():null,email_opt_out_reason:d&&u.trim()||null}).eq("id",s);if(h)throw h;return d},onSuccess:d=>{n.invalidateQueries({queryKey:["contact-email-prefs",s]}),n.invalidateQueries({queryKey:["contact",s]}),n.invalidateQueries({queryKey:["innercircle-contacts"]}),se.success(d?`${t} will no longer receive newsletters or marketing emails`:`${t} is opted back in to marketing emails`)},onError:d=>se.error(d.message)}),c=!!(i!=null&&i.email_opt_out);return e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-3",children:e.jsxs(St,{className:"flex items-center gap-2 text-base",children:[e.jsx(JM,{className:"h-4 w-4"}),"Email Preferences",c&&e.jsx(Oe,{variant:"destructive",className:"ml-1",children:"Opted out"})]})}),e.jsx(Me,{className:"space-y-4",children:l?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Ct,{className:"h-4 w-4 animate-spin"})," Loading…"]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(J,{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(fn,{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(J,{htmlFor:"opt-out-reason",className:"text-xs",children:"Reason (optional)"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{id:"opt-out-reason",value:r,placeholder:"e.g. Asked to stop monthly newsletter",onChange:d=>a(d.target.value)}),e.jsx(B,{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 YFn(s){return at({queryKey:["contact-drip-activity",s],queryFn:async()=>{if(!s)return{enrollments:[],stepLogs:[]};const{data:t,error:n}=await q.from("drip_campaign_enrollments").select("id, campaign_id, current_step, status, next_send_at, enrolled_at, completed_at, exited_at, exit_reason").eq("contact_id",s).order("enrolled_at",{ascending:!1});if(n)throw console.error("[ContactDripActivity] enrollments error",n),n;const r=(t||[]).map(c=>c.id),a=Array.from(new Set((t||[]).map(c=>c.campaign_id)));let i=new Map;if(a.length>0){const{data:c}=await q.from("drip_campaigns").select("id, name, description, is_active").in("id",a);(c||[]).forEach(d=>i.set(d.id,d))}const l=(t||[]).map(c=>({...c,campaign:i.get(c.campaign_id)||null}));let o=[];if(r.length>0){const{data:c,error:d}=await q.from("drip_campaign_step_log").select("id, enrollment_id, campaign_id, step_order, channel, recipient_email, subject, status, error_message, sent_at").in("enrollment_id",r).order("sent_at",{ascending:!1});d?console.error("[ContactDripActivity] step log error",d):o=(c||[]).map(u=>{var h;return{...u,campaign:{name:((h=i.get(u.campaign_id))==null?void 0:h.name)??""}}})}return{enrollments:l,stepLogs:o}},enabled:!!s})}function ZFn(s){switch(s){case"active":return e.jsx(Oe,{variant:"secondary",className:"bg-emerald-500/10 text-emerald-600 border-emerald-500/20",children:"Active"});case"paused":return e.jsx(Oe,{variant:"secondary",className:"bg-amber-500/10 text-amber-600 border-amber-500/20",children:"Paused"});case"completed":return e.jsx(Oe,{variant:"secondary",className:"bg-sky-500/10 text-sky-600 border-sky-500/20",children:"Completed"});case"exited":return e.jsx(Oe,{variant:"outline",children:"Exited"});default:return e.jsx(Oe,{variant:"outline",children:s})}}function N2t(s){return s==="sent"?e.jsx(Er,{className:"h-4 w-4 text-emerald-500"}):s==="failed"?e.jsx(xl,{className:"h-4 w-4 text-destructive"}):s==="skipped"?e.jsx(ky,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Gr,{className:"h-4 w-4 text-muted-foreground"})}function XFn({contactId:s}){const t=Fn(),{data:n,isLoading:r}=YFn(s),[a,i]=_.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(ve,{children:[e.jsx(bt,{children:e.jsxs(St,{className:"flex items-center gap-2 text-base",children:[e.jsx(nP,{className:"h-5 w-5 text-emerald-500"}),"Drip Campaign Activity"]})}),e.jsxs(Me,{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(nP,{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"}),ZFn(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: ",Ed(new Date(c.next_send_at),{addSuffix:!0})]}),c.completed_at&&e.jsxs(e.Fragment,{children:[" · Completed ",Ed(new Date(c.completed_at),{addSuffix:!0})]}),c.exited_at&&!c.completed_at&&e.jsxs(e.Fragment,{children:[" · ",c.exit_reason||"Exited"," ",Ed(new Date(c.exited_at),{addSuffix:!0})]})]})]}),e.jsx(xi,{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(Ls,{open:(a==null?void 0:a.id)===c.id,onOpenChange:h=>!h&&i(null),children:[e.jsx(nl,{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:N2t(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(Hi,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}):e.jsx(ln,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}),e.jsx("p",{className:"text-sm truncate",children:c.subject||`${c.channel.toUpperCase()} step ${c.step_order+1}`})]}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5 truncate",children:[((d=c.campaign)==null?void 0:d.name)||"Campaign"," · ",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(Ps,{className:"max-w-lg",children:[e.jsx(Os,{children:e.jsxs(Ds,{className:"flex items-center gap-2",children:[N2t(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(B,{variant:"ghost",size:"sm",className:"w-full text-xs",onClick:()=>t("/mission-control/smart-drips"),children:"View all in Smart Drips"})]})]})]})]})}const aze=1e3,QFn=5e4;async function $ce(s){const t=[];for(let n=0;n{const n=t.id,r=await $ce(()=>{let p=q.from("gmail_sent_emails").select("id, contact_id, to_email, subject, sent_at, source").eq("user_id",n).or("source.is.null,source.neq.drip_campaign").order("sent_at",{ascending:!1});return s&&(p=p.eq("contact_id",s)),p}),a=await $ce(()=>{let p=q.from("bulk_email_sends").select("id, contact_id, contact_email, subject, sent_at, source, opened_at, clicked_at").eq("user_id",n).order("sent_at",{ascending:!1});return s&&(p=p.eq("contact_id",s)),p}),i=await $ce(()=>q.from("email_campaigns").select("id, subject").eq("user_id",n).order("id")),l=i.map(p=>p.id),o=new Map(i.map(p=>[p.id,p.subject]));let c=[];if(l.length>0)for(let f=0;f{let g=q.from("email_campaign_recipients").select("id, contact_id, email, sent_at, campaign_id, opened_at, clicked_at").in("campaign_id",y).eq("status","sent").not("sent_at","is",null).order("sent_at",{ascending:!1});return s&&(g=g.eq("contact_id",s)),g});c.push(...v)}const d=r.map(p=>({id:`g-${p.id}`,channel:p.source==="portal_invite"?"Client Portal Invite":"Gmail",subject:p.subject,to_email:p.to_email,contact_id:p.contact_id,sent_at:p.sent_at,source:p.source})),u=a.map(p=>({id:`b-${p.id}`,channel:"Mass Email",subject:p.subject,to_email:p.contact_email,contact_id:p.contact_id,sent_at:p.sent_at,source:p.source,opened_at:p.opened_at,clicked_at:p.clicked_at})),h=c.map(p=>({id:`c-${p.id}`,channel:"Campaign",subject:o.get(p.campaign_id)||"(campaign)",to_email:p.email,contact_id:p.contact_id,sent_at:p.sent_at,source:null,campaign_id:p.campaign_id,opened_at:p.opened_at,clicked_at:p.clicked_at})),m=[...d,...u,...h];return m.sort((p,f)=>p.sent_at0&&e.jsx(Oe,{variant:"secondary",className:"ml-1",children:t.length})]})}),e.jsx(Me,{children:n?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading..."}):t.length===0?e.jsxs("div",{className:"text-center py-6 text-sm text-muted-foreground",children:[e.jsx(ln,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),"No emails sent to this contact yet."]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-2",children:i.map(l=>e.jsx("div",{className:"flex items-start justify-between gap-3 p-3 rounded-lg border hover:bg-muted/30",children:e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(Oe,{variant:"outline",className:`text-xs ${JFn[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(B,{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(ir,{to:"/mission-control/sent-emails",className:"text-xs text-primary hover:underline",children:"View all sent emails →"})})]})})]})}const tOn={alabama:"AL",alaska:"AK",arizona:"AZ",arkansas:"AR",california:"CA",colorado:"CO",connecticut:"CT",delaware:"DE",florida:"FL",georgia:"GA",hawaii:"HI",idaho:"ID",illinois:"IL",indiana:"IN",iowa:"IA",kansas:"KS",kentucky:"KY",louisiana:"LA",maine:"ME",maryland:"MD",massachusetts:"MA",michigan:"MI",minnesota:"MN",mississippi:"MS",missouri:"MO",montana:"MT",nebraska:"NE",nevada:"NV","new hampshire":"NH","new jersey":"NJ","new mexico":"NM","new york":"NY","north carolina":"NC","north dakota":"ND",ohio:"OH",oklahoma:"OK",oregon:"OR",pennsylvania:"PA","rhode island":"RI","south carolina":"SC","south dakota":"SD",tennessee:"TN",texas:"TX",utah:"UT",vermont:"VT",virginia:"VA",washington:"WA","west virginia":"WV",wisconsin:"WI",wyoming:"WY","district of columbia":"DC","puerto rico":"PR"},sOn={avenue:"ave",boulevard:"blvd",circle:"cir",court:"ct",drive:"dr",highway:"hwy",lane:"ln",parkway:"pkwy",place:"pl",road:"rd",square:"sq",street:"st",terrace:"ter",trail:"trl",way:"way","suite ":"ste ","unit ":"unit ","apartment ":"apt ","#":"unit "};function nOn(s){if(!s)return null;const t=s.trim();if(/^[A-Za-z]{2}$/.test(t))return t.toUpperCase();const n=t.toLowerCase();return tOn[n]||null}function rOn(s){return!s||!s.trim().match(/^\d{5}(-?\d{4})?$/)?null:s.trim().split("-")[0]}function aOn(s){let t=s.toLowerCase();for(const[n,r]of Object.entries(sOn))t=t.replace(new RegExp(`\\b${n}\\b`,"g"),r);return t}function iOn(s){const t=s.toLowerCase(),n=[/\b(apt|apartment|unit|suite|ste|#)\s*([A-Za-z0-9\-]+)\b/,/\b(floor|fl)\s*([A-Za-z0-9\-]+)\b/];for(const r of n){const a=t.match(r);if(a){const i=a[0].replace(/#/,"unit ").trim();return{street:s.replace(new RegExp(a[0],"i"),"").replace(/\s+/g," ").trim(),unit:i}}}return{street:s,unit:null}}function KYt(s,t,n,r){const a=[s,t,n,r].filter(Boolean).join(", ").trim(),i=nOn(n),l=rOn(r);let o=null,c=null;if(s){const f=iOn(s.trim());o=f.street,c=f.unit}const d=(t==null?void 0:t.trim())||null,u=[];o&&u.push(aOn(o)),c&&u.push(c.toLowerCase().replace(/\s+/g,"")),d&&u.push(d.toLowerCase()),i&&u.push(i.toLowerCase()),l&&u.push(l);const h=u.join(" | "),m=[!!o,!!d,!!i,!!l].filter(Boolean).length;let p="low";return m>=4?p="high":m>=2&&(p="medium"),{original:a,normalized:h,streetAddress:o,unitNumber:c,city:d,state:i,postalCode:l,confidence:p}}async function Cnt(){const{data:{user:s},error:t}=await q.auth.getUser();if(t||!s)throw new Error("Not authenticated");return s.id}async function oOn(s){const{data:t,error:n}=await q.from("contact_properties").select("*, property:properties(*)").eq("contact_id",s).order("created_at",{ascending:!1});if(n)throw new Error(n.message);const r=t??[],a=Array.from(new Set(r.map(o=>o.property_id).filter(Boolean)));let i=[],l=[];if(a.length){const[o,c]=await Promise.all([q.from("property_field_locks").select("*").in("property_id",a),q.from("property_enrichment_events").select("*").in("property_id",a).order("created_at",{ascending:!1})]);if(o.error)throw new Error(o.error.message);if(c.error)throw new Error(c.error.message);i=o.data??[],l=c.data??[]}return r.map(o=>({property:o.property,relationship:o,locks:i.filter(c=>c.property_id===o.property_id),events:l.filter(c=>c.property_id===o.property_id)}))}async function lOn(s){const t=await Cnt(),{data:n,error:r}=await q.from("properties").insert({...s,owner_user_id:t}).select().single();if(r)throw new Error(r.message);return n}async function cOn(s,t,n={}){const a={owner_user_id:await Cnt(),contact_id:s,property_id:t,relationship_type:n.relationship_type??"unknown",is_primary_residence:n.is_primary_residence??!1,ownership_status:n.ownership_status??"unknown",relationship_started_at:n.relationship_started_at??null,relationship_ended_at:n.relationship_ended_at??null},{data:i,error:l}=await q.from("contact_properties").insert(a).select().single();if(l)throw new Error(l.message);return i}async function dOn(s){const{error:t}=await q.from("contact_properties").delete().eq("id",s);if(t)throw new Error(t.message)}async function k2t(s,t){const{data:n,error:r}=await q.from("contact_properties").update(t).eq("id",s).select().single();if(r)throw new Error(r.message);return n}function v3(s){return s==null||Number.isNaN(s)?"—":new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s)}function b3(s,t=""){return s==null||Number.isNaN(s)?"—":`${new Intl.NumberFormat("en-US").format(s)}${t}`}function S2t(s){return{never_enriched:"Never enriched",pending:"Pending",enriched:"Enriched",partially_enriched:"Partially enriched",not_found:"Not found",unsupported_active_listing:"Active listing — unsupported",incomplete_address:"Incomplete address",needs_review:"Needs review",failed:"Failed"}[s]??s}async function W_r(){const{data:{user:s}}=await q.auth.getUser();if(!s)throw new Error("Not authenticated");const t=s.id,n=new Date;n.setDate(n.getDate()-90);const r=n.toISOString(),[{count:a,error:i},{count:l,error:o},{count:c,error:d},{count:u,error:h},{count:m,error:p},{count:f,error:y},{count:v,error:g},{count:b,error:j},{count:S,error:C},{count:E,error:P}]=await Promise.all([q.from("innercircle_contacts").select("id",{count:"exact",head:!0}).eq("owner_user_id",t).not("address","is",null),q.from("properties").select("id",{count:"exact",head:!0}).eq("owner_user_id",t),q.from("properties").select("id",{count:"exact",head:!0}).eq("owner_user_id",t).eq("enrichment_status","enriched"),q.from("properties").select("id",{count:"exact",head:!0}).eq("owner_user_id",t).eq("enrichment_status","needs_review"),q.from("properties").select("id",{count:"exact",head:!0}).eq("owner_user_id",t).eq("enrichment_status","incomplete_address"),q.from("properties").select("id",{count:"exact",head:!0}).eq("owner_user_id",t).eq("enrichment_status","failed"),q.from("properties").select("id",{count:"exact",head:!0}).eq("owner_user_id",t).or(`last_enriched_at.is.null,last_enriched_at.lt.${r}`),q.from("properties").select("id",{count:"exact",head:!0}).eq("owner_user_id",t).eq("owner_occupied_status","non_owner_occupied"),q.from("properties").select("id",{count:"exact",head:!0}).eq("owner_user_id",t).is("estimated_value",null),q.rpc("count_contacts_missing_property_data",{owner_id:t})]),M=[i,o,d,h,p,y,g,j,C,P].filter(Boolean);if(M.length)throw new Error(M.map(I=>I==null?void 0:I.message).join("; "));return{contactsWithAddresses:a??0,propertiesLinked:l??0,contactsMissingPropertyData:E??0,propertiesEnriched:c??0,propertiesNeedingReview:u??0,incompleteAddresses:m??0,enrichmentFailures:f??0,staleProperties:v??0,possibleNonOwnerOccupied:b??0,propertiesMissingValuation:S??0}}async function K_r(s={}){const{data:{user:t}}=await q.auth.getUser();if(!t)throw new Error("Not authenticated");const n=s.limit??25,r=s.offset??0,a=!!(s.enrichmentStatus&&s.enrichmentStatus!=="all")||!!s.staleBefore,i=s.missingOnly?"":a?"!inner":"",l=s.missingOnly?"":a?"!inner":"";let o=q.from("innercircle_contacts").select(`id, first_name, last_name, address, city, state, zip_code, zip, contact_properties${i}(id, property_id, properties${l}(id, enrichment_status, last_enriched_at))`,{count:"exact"}).eq("owner_user_id",t.id).not("address","is",null);s.city&&(o=o.ilike("city",`%${s.city}%`)),s.state&&(o=o.ilike("state",`%${s.state}%`)),s.postalCode&&(o=o.or(`zip_code.ilike.%${s.postalCode}%,zip.ilike.%${s.postalCode}%`)),s.missingOnly?o=o.is("contact_properties",null):a&&(s.enrichmentStatus&&s.enrichmentStatus!=="all"&&(o=o.eq("contact_properties.properties.enrichment_status",s.enrichmentStatus)),s.staleBefore&&(o=o.or(`last_enriched_at.is.null,last_enriched_at.lt.${s.staleBefore}`,{referencedTable:"contact_properties.properties"})));const{data:c,error:d,count:u}=await o.order("last_name",{ascending:!0}).range(r,r+n-1);if(d)throw new Error(d.message);return{contacts:(c??[]).map(m=>{const p=Array.isArray(m.contact_properties)?m.contact_properties[0]:m.contact_properties,f=p==null?void 0:p.properties;return{id:m.id,first_name:m.first_name,last_name:m.last_name,address:m.address,city:m.city,state:m.state,zip_code:m.zip_code??m.zip,linked_property_id:(p==null?void 0:p.property_id)??null,enrichment_status:(f==null?void 0:f.enrichment_status)??"never_enriched",last_enriched_at:(f==null?void 0:f.last_enriched_at)??null}}),count:u??0}}function uOn(s){switch(s){case"verified":return"default";case"high":return"default";case"medium":return"secondary";case"low":return"outline";default:return"outline"}}async function Y_r(s,t={}){const n=await Cnt();if(!s.length)throw new Error("Select at least one contact");const{data:r,error:a}=await q.from("innercircle_contacts").select("id, address, city, state, zip_code, zip").eq("owner_user_id",n).in("id",s);if(a)throw new Error(a.message);const i=r??[];if(!i.length)throw new Error("No matching contacts found");const{data:l,error:o}=await q.from("property_enrichment_runs").insert({owner_user_id:n,name:t.name??null,requested_source:t.requestedSource??"zillow_chatgpt_app",status:"ready",total_contacts:i.length,pending_count:i.length}).select("id").single();if(o)throw new Error(o.message);const c=i.map(u=>({owner_user_id:n,enrichment_run_id:l.id,contact_id:u.id,normalized_address:KYt(u.address,u.city,u.state,u.zip_code??u.zip).normalized||null,status:"pending"})),{error:d}=await q.from("property_enrichment_items").insert(c);if(d)throw new Error(d.message);return{runId:l.id,count:i.length}}const YYt=[{value:"owner",label:"Owner"},{value:"co_owner",label:"Co-owner"},{value:"household_member",label:"Household member"},{value:"former_owner",label:"Former owner"},{value:"buyer_prospect",label:"Buyer prospect"},{value:"seller_prospect",label:"Seller prospect"},{value:"tenant",label:"Tenant"},{value:"landlord",label:"Landlord"},{value:"unknown",label:"Unknown"}],ZYt=[{value:"current",label:"Current"},{value:"former",label:"Former"},{value:"possible",label:"Possible"},{value:"unknown",label:"Unknown"}];function hOn({detail:s,onMutate:t}){const{property:n,relationship:r,events:a}=s,[i,l]=_.useState(!1),[o,c]=_.useState(!1),[d,u]=_.useState(r.relationship_type),[h,m]=_.useState(r.ownership_status),[p,f]=_.useState(r.is_primary_residence),y=mt({mutationFn:()=>k2t(r.id,{relationship_type:d,ownership_status:h,is_primary_residence:p}),onSuccess:()=>{se.success("Property relationship updated"),c(!1),t()},onError:C=>se.error(C instanceof Error?C.message:"Update failed")}),v=mt({mutationFn:()=>dOn(r.id),onSuccess:()=>{se.success("Property unlinked"),t()},onError:C=>se.error(C instanceof Error?C.message:"Unlink failed")}),g=a[0],b=n.primary_data_source||(g==null?void 0:g.source_name)||"Manual",j=n.last_enriched_at||(g==null?void 0:g.retrieved_at)||n.updated_at,S=[{id:"overview",title:"Property Overview",icon:GM,rows:[{label:"Property type",value:n.property_type||"—"},{label:"Bedrooms",value:b3(n.bedrooms)},{label:"Bathrooms",value:b3(n.bathrooms,"+")},{label:"Living area",value:b3(n.living_area_square_feet," sq ft")},{label:"Lot size",value:n.lot_size?`${b3(n.lot_size)} ${n.lot_size_units||""}`:"—"},{label:"Year built",value:b3(n.year_built)},{label:"Parcel ID",value:n.parcel_id||"—"},{label:"County",value:n.county||"—"}]},{id:"value",title:"Value & Valuation",icon:yd,rows:[{label:"Estimated value",value:v3(n.estimated_value)},{label:"Value range",value:n.estimated_value_low&&n.estimated_value_high?`${v3(n.estimated_value_low)} – ${v3(n.estimated_value_high)}`:"—"},{label:"Rent estimate",value:v3(n.rent_estimate)},{label:"Data confidence",value:n.data_confidence}]},{id:"tax",title:"Tax Information",icon:Rm,rows:[{label:"Tax-assessed value",value:v3(n.tax_assessed_value)},{label:"Assessed year",value:b3(n.tax_assessed_year)},{label:"Annual property tax",value:v3(n.latest_annual_property_tax)},{label:"Tax rate",value:n.property_tax_rate?`${(n.property_tax_rate*100).toFixed(2)}%`:"—"}]},{id:"ownership",title:"Ownership & Relationship",icon:Fo,rows:[{label:"Relationship",value:r.relationship_type.replace(/_/g," ")},{label:"Ownership status",value:r.ownership_status},{label:"Primary residence",value:r.is_primary_residence?"Yes":"No"},{label:"Owner-occupied status",value:n.owner_occupied_status.replace(/_/g," ")},{label:"Foreclosure status",value:n.foreclosure_status||"—"}]},{id:"sale",title:"Sale History",icon:R_,rows:[{label:"Last sale price",value:v3(n.last_sale_price)},{label:"Last sale date",value:n.last_sale_date||"—"}]},{id:"sources",title:"Data Sources",icon:Mq,rows:[{label:"Primary source",value:b},{label:"Source URL",value:n.source_property_url?"View source":"—"},{label:"Last updated",value:j?new Date(j).toLocaleDateString():"—"}]},{id:"history",title:"Enrichment History",icon:ga,rows:a.length?a.slice(0,5).map(C=>({label:new Date(C.created_at).toLocaleDateString(),value:`${C.source_name} — ${S2t(C.status)}`})):[{label:"History",value:"No enrichment events yet"}]}];return e.jsxs(ve,{className:"overflow-hidden",children:[e.jsx(bt,{className:"pb-3",children:e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs(St,{className:"flex items-start gap-2 text-base",children:[e.jsx(Jr,{className:"mt-0.5 h-4 w-4 text-primary"}),e.jsx("span",{children:n.street_address||n.normalized_address})]}),e.jsxs("div",{className:"flex items-center gap-1 text-sm text-muted-foreground",children:[e.jsx(Xa,{className:"h-3.5 w-3.5"}),[n.city,n.state,n.postal_code].filter(Boolean).join(", ")]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[r.is_primary_residence&&e.jsxs(Oe,{variant:"default",className:"gap-1",children:[e.jsx(Da,{className:"h-3 w-3"})," Primary"]}),e.jsx(Oe,{variant:uOn(n.data_confidence),children:n.data_confidence}),e.jsx(Oe,{variant:"outline",children:S2t(n.enrichment_status)})]})]})}),e.jsxs(Me,{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsx(Vce,{label:"Estimated value",value:v3(n.estimated_value)}),e.jsx(Vce,{label:"Tax assessed",value:v3(n.tax_assessed_value)}),e.jsx(Vce,{label:"Bed / Bath",value:`${b3(n.bedrooms)} / ${b3(n.bathrooms)}`}),e.jsx(Vce,{label:"Sq ft",value:b3(n.living_area_square_feet)})]}),e.jsxs(f1,{open:i,onOpenChange:l,children:[e.jsx(x1,{asChild:!0,children:e.jsxs(B,{variant:"ghost",size:"sm",className:"w-full justify-between",children:[e.jsx("span",{children:"Property details"}),e.jsx(tl,{className:At("h-4 w-4 transition-transform",i&&"rotate-180")})]})}),e.jsx(g1,{className:"space-y-4 pt-2",children:S.map(C=>e.jsxs("div",{className:"rounded-xl border border-border/70 bg-muted/30 p-4",children:[e.jsxs("h4",{className:"mb-3 flex items-center gap-2 text-sm font-semibold",children:[e.jsx(C.icon,{className:"h-4 w-4 text-primary"}),C.title]}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:C.rows.map((E,P)=>e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:E.label}),e.jsx("span",{className:"text-sm font-medium",children:E.label==="Source URL"&&E.value!=="—"?e.jsx("a",{href:n.source_property_url||"#",target:"_blank",rel:"noopener noreferrer",className:"text-primary underline",children:E.value}):E.value})]},P))})]},C.id))})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(Ls,{open:o,onOpenChange:c,children:[e.jsx(nl,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",children:[e.jsx(Qm,{className:"mr-1 h-3.5 w-3.5"})," Edit relationship"]})}),e.jsxs(Ps,{className:"sm:max-w-md",children:[e.jsx(Os,{children:e.jsx(Ds,{children:"Edit property relationship"})}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Relationship type"}),e.jsxs(is,{value:d,onValueChange:C=>u(C),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsx(as,{children:YYt.map(C=>e.jsx(He,{value:C.value,children:C.label},C.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Ownership status"}),e.jsxs(is,{value:h,onValueChange:C=>m(C),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsx(as,{children:ZYt.map(C=>e.jsx(He,{value:C.value,children:C.label},C.value))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{id:`primary-${r.id}`,type:"checkbox",checked:p,onChange:C=>f(C.target.checked),className:"h-4 w-4 rounded border-border"}),e.jsx(J,{htmlFor:`primary-${r.id}`,children:"Primary residence"})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx(B,{onClick:()=>y.mutate(),disabled:y.isPending,children:"Save changes"})]})]})]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>k2t(r.id,{is_primary_residence:!r.is_primary_residence}).then(()=>{se.success(r.is_primary_residence?"Removed primary residence":"Marked as primary residence"),t()}).catch(C=>se.error(C.message)),children:[e.jsx(Da,{className:"mr-1 h-3.5 w-3.5"}),r.is_primary_residence?"Unmark primary":"Mark primary"]}),e.jsxs(B,{variant:"outline",size:"sm",className:"text-destructive hover:bg-destructive/10",onClick:()=>v.mutate(),disabled:v.isPending,children:[e.jsx(by,{className:"mr-1 h-3.5 w-3.5"})," Unlink property"]})]})]})]})}function Vce({label:s,value:t}){return e.jsxs("div",{className:"rounded-xl border border-border/70 bg-muted/30 p-3",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:s}),e.jsx("p",{className:"text-sm font-semibold",children:t})]})}function mOn({contactId:s,defaultAddress:t,defaultCity:n,defaultState:r,defaultZip:a,onAdded:i}){const[l,o]=_.useState(!1),[c,d]=_.useState(t||""),[u,h]=_.useState(n||""),[m,p]=_.useState(r||""),[f,y]=_.useState(a||""),[v,g]=_.useState("owner"),[b,j]=_.useState("current"),[S,C]=_.useState(!1),E=mt({mutationFn:async()=>{const P=[c,u,m,f].filter(Boolean).join(", "),M=KYt(c,u,m,f);if(!M.normalized)throw new Error("Could not normalize address. Please check the fields.");const I=await lOn({original_address:P,normalized_address:M.normalized,street_address:M.streetAddress,unit_number:M.unitNumber,city:M.city,state:M.state,postal_code:M.postalCode,property_type:null,enrichment_status:"never_enriched",data_confidence:"unknown",owner_occupied_status:"unknown",photo_usage_authorized:!1,external_ids:{}});await cOn(s,I.id,{relationship_type:v,ownership_status:b,is_primary_residence:S})},onSuccess:()=>{se.success("Property added"),o(!1),d(t||""),h(n||""),p(r||""),y(a||""),i()},onError:P=>se.error(P instanceof Error?P.message:"Failed to add property")});return e.jsxs(Ls,{open:l,onOpenChange:o,children:[e.jsx(nl,{asChild:!0,children:e.jsxs(B,{size:"sm",children:[e.jsx(rn,{className:"mr-1 h-4 w-4"})," Add property"]})}),e.jsxs(Ps,{className:"sm:max-w-lg",children:[e.jsx(Os,{children:e.jsx(Ds,{children:"Add property to contact"})}),e.jsxs("div",{className:"grid gap-4 py-2",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx(J,{htmlFor:"pi-street",children:"Street address"}),e.jsx(xe,{id:"pi-street",value:c,onChange:P=>d(P.target.value),placeholder:"123 Main St"})]}),e.jsxs("div",{className:"grid gap-2 sm:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"pi-city",children:"City"}),e.jsx(xe,{id:"pi-city",value:u,onChange:P=>h(P.target.value),placeholder:"City"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"pi-state",children:"State"}),e.jsx(xe,{id:"pi-state",value:m,onChange:P=>p(P.target.value),placeholder:"State"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"pi-zip",children:"ZIP"}),e.jsx(xe,{id:"pi-zip",value:f,onChange:P=>y(P.target.value),placeholder:"ZIP"})]})]}),e.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Relationship type"}),e.jsxs(is,{value:v,onValueChange:P=>g(P),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsx(as,{children:YYt.map(P=>e.jsx(He,{value:P.value,children:P.label},P.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Ownership status"}),e.jsxs(is,{value:b,onValueChange:P=>j(P),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsx(as,{children:ZYt.map(P=>e.jsx(He,{value:P.value,children:P.label},P.value))})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{id:"pi-primary",type:"checkbox",checked:S,onChange:P=>C(P.target.checked),className:"h-4 w-4 rounded border-border"}),e.jsx(J,{htmlFor:"pi-primary",children:"Primary residence"})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx(B,{onClick:()=>E.mutate(),disabled:E.isPending||!c,children:E.isPending?"Saving...":"Save property"})]})]})]})}function pOn({contactId:s,contactAddress:t,contactCity:n,contactState:r,contactZip:a}){const i=Bt(),{data:l,isLoading:o,error:c}=at({queryKey:["contact-properties",s],queryFn:()=>oOn(s)}),d=()=>{i.invalidateQueries({queryKey:["contact-properties",s]})};if(o)return e.jsxs("div",{className:"space-y-4",children:[e.jsx(cn,{className:"h-10 w-48"}),e.jsx(cn,{className:"h-48 w-full"})]});if(c)return e.jsx(ve,{className:"border-destructive/50 bg-destructive/5",children:e.jsxs(Me,{className:"flex items-center gap-3 py-6",children:[e.jsx(xl,{className:"h-5 w-5 text-destructive"}),e.jsx("p",{className:"text-sm",children:"Could not load property intelligence."})]})});const u=l??[];return e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Property Intelligence"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:'Home and property details for this contact. Property details are filled in from your ChatGPT assistant or entered by hand — the "Find person details" button at the top of the page looks up work and social info, not property data.'})]}),e.jsx(mOn,{contactId:s,defaultAddress:t||void 0,defaultCity:n||void 0,defaultState:r||void 0,defaultZip:a||void 0,onAdded:d})]}),u.length===0?e.jsx(ve,{className:"border-dashed",children:e.jsxs(Me,{className:"flex flex-col items-center justify-center py-10 text-center",children:[e.jsx(Jr,{className:"mb-3 h-10 w-10 text-muted-foreground/60"}),e.jsx("h4",{className:"text-base font-medium",children:"No properties linked yet"}),e.jsx("p",{className:"max-w-md text-sm text-muted-foreground",children:"Add the contact's property above, or run a ChatGPT enrichment to match addresses with public property data."}),t&&e.jsxs("p",{className:"mt-2 text-xs text-muted-foreground",children:["Contact address on file: ",t,n?`, ${n}`:"",r?`, ${r}`:"",a?` ${a}`:""]})]})}):e.jsx("div",{className:"space-y-4",children:u.map(h=>e.jsx(hOn,{detail:h,onMutate:d},h.relationship.id))})]})}function fOn({videoId:s}){var l;const{data:t,isLoading:n,error:r}=dRn(s);if(n)return e.jsxs("div",{className:"space-y-4",children:[e.jsx(cn,{className:"w-full aspect-video rounded-lg"}),e.jsx(cn,{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(xl,{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 xOn({contactId:s}){const t=Fn(),[n,r]=_.useState(!1),{data:a,isLoading:i}=at({queryKey:["deal-tasks","contact",s],queryFn:async()=>{const{data:h,error:m}=await q.from("deal_tasks").select(` id, title, priority, status, due_date, completed_at, deal:deal_pipeline(id, deal_name) `).eq("contact_id",s).order("status").order("due_date",{ascending:!0,nullsFirst:!1});if(m)throw m;return h},enabled:!!s}),l=async(h,m)=>{const p=m==="done"?"todo":"done";await q.from("deal_tasks").update({status:p,completed_at:p==="done"?new Date().toISOString():null}).eq("id",h),window.dispatchEvent(new CustomEvent("refetch-contact-tasks"))},{refetch:o}=at({queryKey:["deal-tasks","contact",s],queryFn:async()=>{const{data:h,error:m}=await q.from("deal_tasks").select(` id, title, priority, status, due_date, completed_at, deal:deal_pipeline(id, deal_name) `).eq("contact_id",s).order("status").order("due_date",{ascending:!0,nullsFirst:!1});if(m)throw m;return h},enabled:!!s}),c={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"},d=(a==null?void 0:a.filter(h=>h.status!=="done"))||[],u=(a==null?void 0:a.filter(h=>h.status==="done"))||[];return e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(St,{className:"text-base flex items-center gap-2",children:[e.jsx(ea,{className:"h-4 w-4"}),"Tasks",d.length>0&&e.jsx(Oe,{variant:"secondary",className:"text-xs",children:d.length})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>t("/mission-control/tasks"),children:"View All"}),e.jsx(B,{variant:"outline",size:"sm",onClick:()=>r(!0),children:e.jsx(rn,{className:"h-3.5 w-3.5"})})]})]})}),e.jsx(Me,{className:"space-y-1",children:i?e.jsx(cn,{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(gOn,{contactId:s,open:n,onOpenChange:h=>{r(h),h||o()}})]})}function gOn({contactId:s,open:t,onOpenChange:n}){const[r,a]=_.useState(""),[i,l]=_.useState("medium"),[o,c]=_.useState(),{data:d}=at({queryKey:["session"],queryFn:async()=>{const{data:h}=await q.auth.getSession();return h.session}}),u=async()=>{var m;if(!r.trim()||!((m=d==null?void 0:d.user)!=null&&m.id))return;const{error:h}=await q.from("deal_tasks").insert([{owner_user_id:d.user.id,contact_id:s,title:r.trim(),priority:i,status:"todo",due_date:o?Hs(o,"yyyy-MM-dd"):null}]);if(h){console.error("Task create error:",h);return}n(!1)};return e.jsx(Ls,{open:t,onOpenChange:n,children:e.jsxs(Ps,{className:"sm:max-w-[400px]",children:[e.jsx(Os,{children:e.jsx(Ds,{children:"Add Task"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Title"}),e.jsx(xe,{value:r,onChange:h=>a(h.target.value),placeholder:"Task title...",onKeyDown:h=>h.key==="Enter"&&u()})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(J,{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(J,{children:"Due Date"}),e.jsx(xe,{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(B,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(B,{onClick:u,disabled:!r.trim(),children:"Create Task"})]})]})]})})}function yOn({contactId:s}){const t=Fn(),{data:n,isLoading:r}=at({queryKey:["contact-linked-deals",s],queryFn:async()=>{const{data:a,error:i}=await q.from("deal_pipeline").select(` id, deal_name, deal_type, expected_price, property_address, stage:deal_pipeline_stages(id, name, color, icon, is_won_stage, is_lost_stage) `).eq("contact_id",s).order("updated_at",{ascending:!1});if(i)throw i;return a},enabled:!!s});return r||!n||n.length===0?null:e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-2",children:e.jsxs(St,{className:"text-base flex items-center gap-2",children:[e.jsx(Cx,{className:"h-4 w-4"}),"Linked Deals"]})}),e.jsx(Me,{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(Oe,{variant:"outline",className:"text-[10px] capitalize",children:a.deal_type}),i&&e.jsxs(Oe,{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(La,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors flex-shrink-0"})]})},a.id)})})]})}function vOn(){var hn,dr,Cn,Yn;const{contactId:s}=Li(),{isAdmin:t}=hs(),{hasIdx:n}=lf(),r=Fn(),[a]=Yl(),i=a.get("search")||"",l=a.get("type")||"all",o=a.get("status")||a.get("filter")||"all",c=a.get("tags")||"",d=a.get("tagMode")==="all"?"all":"any",u=_.useMemo(()=>new Set(c.split(",").map(on=>on.trim()).filter(Boolean)),[c]),{data:h,isLoading:m}=Hzs(s||""),{data:p}=Z_(),{data:f}=aae(),{data:y}=vW(3650),{data:v}=YIe(365),{data:g}=FFn(s),{contactsWithScores:b}=lae(),{data:j}=Pae(),{score:S}=aqs(s||""),C=uet(),E=_zt(),P=oLe(),M=bzt(),[I,D]=_.useState(!1),[O,V]=_.useState("overview"),[G,$]=_.useState(!1),H=jFn(),[Y,Z]=_.useState({}),[ne,ce]=_.useState(!1),[ie,te]=_.useState(null),[ae,le]=_.useState(""),[be,me]=_.useState(void 0),[he,pe]=_.useState(""),[Ce,Ae]=_.useState(null),[Pe,ze]=_.useState(!1),[ke,Ze]=_.useState(null),[Se,Fe]=_.useState(!1),{isGmailConnected:Ne,gmailEmail:Ye}=Vg(),{isReady:Ve}=$9(),qe=Ve||Ne,Qe=qYt(),[Ue,Xe]=_.useState(!1),{data:nt}=at({queryKey:["cma-eligible"],queryFn:async()=>{const{data:{user:on}}=await q.auth.getUser();if(!on)return!1;const{data:Ir}=await q.from("lead_sites").select("id, mls_provider_id, no_mls_mode, is_active").eq("agent_id",on.id);return(Ir||[]).some(Wn=>Wn.is_active&&Wn.mls_provider_id&&!Wn.no_mls_mode)}}),$e=async()=>{var Fa,ks,Gs,Ws;if(!h)return;const on=(Fa=h.address)==null?void 0:Fa.trim(),Ir=(ks=h.city)==null?void 0:ks.trim(),Wn=(Gs=h.state)==null?void 0:Gs.trim().toUpperCase(),Js=((Ws=h.zip_code)==null?void 0:Ws.trim())||"";if(!on||!Ir||!Wn){se.error("Add a full address (street, city, state) before creating a CMA.");return}try{Xe(!0);const Ys=await Qe.mutateAsync({subject:{address:on,city:Ir,state:Wn,zip:Js},contactId:h.id,title:`${h.first_name||""} ${h.last_name||""}`.trim()+" — "+on});r(`/mission-control/cma/${Ys.id}`)}catch(Ys){se.error("Could not create CMA: "+((Ys==null?void 0:Ys.message)||"unknown error"))}finally{Xe(!1)}},{data:Ge}=at({queryKey:["gmail-sent-emails",s],queryFn:async()=>{const{data:on,error:Ir}=await q.from("gmail_sent_emails").select("*").eq("contact_id",s).order("sent_at",{ascending:!1});if(Ir)throw Ir;return on},enabled:!!s}),ct=on=>{if(!on)return null;const Ir=on.match(/Video ID:\s*([a-f0-9-]+)/i);return Ir?Ir[1]:null},xt=_.useMemo(()=>{if(!b)return[];const on=new Map;if(u.size>0&&j)for(const Wn of j)on.has(Wn.contact_id)||on.set(Wn.contact_id,new Set),on.get(Wn.contact_id).add(Wn.tag_id);let Ir=b.filter(Wn=>{var Gs,Ws,Ys;const Js=i===""||`${Wn.first_name} ${Wn.last_name}`.toLowerCase().includes(i.toLowerCase())||((Gs=Wn.email)==null?void 0:Gs.toLowerCase().includes(i.toLowerCase()))||((Ws=Wn.phone)==null?void 0:Ws.includes(i)),Fa=l==="all"||((Ys=Wn.tags)==null?void 0:Ys.some(Bn=>Bn.relationship_type_id===l));let ks=!0;if(u.size>0){const Bn=on.get(Wn.id)||new Set;d==="all"?ks=Array.from(u).every(or=>Bn.has(or)):ks=Array.from(u).some(or=>Bn.has(or))}return Js&&Fa&&ks});return o==="not-touched-90"?Ir=Ir.filter(Wn=>{const Js=Wn.relationshipScore.daysSinceTouch;return Js===null||Js>90}):o==="at-risk"?Ir=Ir.filter(Wn=>Wn.relationshipScore.status==="at-risk"):o==="cooling"?Ir=Ir.filter(Wn=>Wn.relationshipScore.status==="cooling"):o==="warm"&&(Ir=Ir.filter(Wn=>Wn.relationshipScore.status==="warm")),Ir.map(Wn=>Wn.id)},[b,i,l,o,u,d,j]),qt=xt.indexOf(s||""),Vt=qt>0?xt[qt-1]:null,Xt=qt1&&qt!==-1,Ft=on=>{const Ir=new URLSearchParams;i&&Ir.set("search",i),l!=="all"&&Ir.set("type",l),o!=="all"&&Ir.set("status",o),u.size>0&&(Ir.set("tags",Array.from(u).join(",")),Ir.set("tagMode",d));const Wn=Ir.toString();return`/mission-control/contacts/${on}${Wn?`?${Wn}`:""}`},wt=_.useMemo(()=>{const on=((y==null?void 0:y.filter(Wn=>Wn.contact_id===s))||[]).map(Wn=>{var Gs,Ws,Ys;const Js=ct(Wn.notes);let Fa=((Gs=Wn.action_type)==null?void 0:Gs.name)||"Touch",ks=Wn.notes;if(Fa==="Other"&&((Ws=Wn.notes)!=null&&Ws.startsWith("["))){const Bn=Wn.notes.indexOf("]");Bn>0&&(Fa=Wn.notes.substring(1,Bn),ks=Wn.notes.substring(Bn+1).replace(/^\s*—\s*/,"").trim()||null)}return{id:Wn.id,type:"touch",completed_at:Wn.completed_at,name:Fa,color:((Ys=Wn.action_type)==null?void 0:Ys.color)||"#3B82F6",notes:ks,videoId:Js}}),Ir=((v==null?void 0:v.filter(Wn=>Wn.contact_id===s))||[]).map(Wn=>({id:Wn.id,type:"popby",completed_at:Wn.completed_at,name:"Pop-by",color:"#F97316",notes:Wn.notes,videoId:null}));return[...on,...Ir].sort((Wn,Js)=>new Date(Js.completed_at).getTime()-new Date(Wn.completed_at).getTime())},[y,v,s]),Ts=on=>{var Ir;return{first_name:on.first_name||"",last_name:on.last_name||"",email:on.email||"",phone:on.phone||"",address:on.address||"",city:on.city||"",state:on.state||"",zip_code:on.zip_code||"",birthday:on.birthday||"",home_anniversary:on.home_anniversary||"",wedding_anniversary:on.wedding_anniversary||"",spouse_birthday:on.spouse_birthday||"",spouse_name:on.spouse_name||"",spouse_email:on.spouse_email||"",company_name:on.company_name||"",job_title:on.job_title||"",lead_source_id:on.lead_source_id||"",notes:on.notes||"",tagIds:((Ir=on.tags)==null?void 0:Ir.map(Wn=>Wn.relationship_type_id))||[]}};_.useEffect(()=>{D(!1),Z({})},[s]);const vt=_.useRef(null);_.useEffect(()=>{h!=null&&h.id&&vt.current!==h.id&&(vt.current=h.id,Z(Ts(h)))},[h==null?void 0:h.id,h]);const $s=()=>{h&&(Z(Ts(h)),D(!0))},As=async()=>{await C.mutateAsync({id:s,...Y,lead_source_id:Y.lead_source_id||null}),D(!1)},jn=async()=>{await Xi("Are you sure you want to delete this contact?")&&(await E.mutateAsync(s),r("/mission-control/contacts"))},Dn=((hn=f==null?void 0:f.find(on=>on.id===ie))==null?void 0:hn.name)==="Other",Ur=async()=>{if(!ie||Dn&&!he.trim())return;const on=be?new Date(be.getFullYear(),be.getMonth(),be.getDate(),12,0,0).toISOString():void 0,Ir=Dn?`[${he.trim()}]${ae?" — "+ae:""}`:ae;await P.mutateAsync({contactId:s,actionTypeId:ie,notes:Ir,completedAt:on}),ce(!1),te(null),le(""),me(void 0),pe("")},Vs=(on,Ir)=>{qe&&h?(Ze({email:on,name:Ir||`${h.first_name} ${h.last_name||""}`.trim()}),ze(!0)):window.location.href=`mailto:${on}`};return m?e.jsx(zs,{title:"Contact Details",children:e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full"})})}):h?e.jsxs(e.Fragment,{children:[e.jsx(zs,{title:`${h.first_name} ${h.last_name||""}`,description:"Contact details and activity",children:e.jsxs("div",{className:"space-y-5 overflow-x-hidden pb-24 lg:pb-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs(B,{variant:"ghost",size:"sm",className:"-ml-2",onClick:()=>{window.history.length>1?r(-1):r("/mission-control/contacts")},children:[e.jsx($c,{className:"h-4 w-4 mr-1"}),"Back to Contacts"]}),fs&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(B,{variant:"outline",size:"sm",className:"h-8 px-2",onClick:()=>Vt&&r(Ft(Vt)),disabled:!Vt,children:e.jsx($c,{className:"h-4 w-4"})}),e.jsxs("span",{className:"px-1 text-xs text-muted-foreground whitespace-nowrap",children:[qt+1," of ",xt.length]}),e.jsx(B,{variant:"outline",size:"sm",className:"h-8 px-2",onClick:()=>Xt&&r(Ft(Xt)),disabled:!Xt,children:e.jsx(xi,{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(gFn,{contactId:h.id,firstName:h.first_name,lastName:h.last_name,avatarUrl:h.avatar_url,email:h.email,size:72})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("h1",{className:"truncate text-2xl font-bold sm:text-3xl",children:[h.first_name," ",h.last_name||""]}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1.5",children:[S&&e.jsxs("span",{className:"hub-glass inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-[11px] font-semibold capitalize",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full",style:{backgroundColor:S.status==="warm"?"#22c55e":S.status==="cooling"?"#f59e0b":"#ef4444"}}),S.status==="at-risk"?"At risk":S.status," · ",S.score]}),h.email_opt_out&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full bg-destructive/90 px-2.5 py-1 text-[11px] font-semibold text-destructive-foreground",children:[e.jsx(JM,{className:"h-3 w-3"}),"Emails opted out"]}),(((dr=h.lead_source_ref)==null?void 0:dr.name)||h.lead_source)&&e.jsx("span",{className:"hub-glass rounded-full px-2.5 py-1 text-[11px] font-medium",children:((Cn=h.lead_source_ref)==null?void 0:Cn.name)||h.lead_source}),(Yn=h.tags)==null?void 0:Yn.map(on=>{const Ir=p==null?void 0:p.find(Wn=>Wn.id===on.relationship_type_id);return Ir?e.jsx("span",{className:"hub-glass rounded-full px-2.5 py-1 text-[11px] font-medium",children:Ir.name},on.id):null})]}),e.jsxs("div",{className:"mt-3 flex flex-col gap-1.5 text-sm sm:flex-row sm:flex-wrap sm:items-center sm:gap-4",children:[h.email&&e.jsxs("button",{onClick:()=>Vs(h.email),className:"inline-flex min-w-0 items-center gap-1.5 hub-ink-muted transition-opacity hover:opacity-100",children:[e.jsx(ln,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:h.email})]}),h.phone&&e.jsxs("a",{href:`tel:${h.phone}`,className:"inline-flex items-center gap-1.5 hub-ink-muted",children:[e.jsx(_a,{className:"h-3.5 w-3.5"}),h.phone]}),(h.address||h.city)&&e.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5 hub-ink-muted",children:[e.jsx(Xa,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:[h.address,h.city,h.state].filter(Boolean).join(", ")})]})]})]})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[H&&e.jsxs("button",{onClick:()=>$(!0),className:"hub-glass inline-flex items-center gap-2 rounded-full px-4 py-2 text-sm font-semibold transition-transform hover:scale-[1.02]",title:"Find public professional details (job, company, social profiles) for this person. Property data is on the Property tab.",children:[e.jsx(un,{className:"h-4 w-4"}),"Find person details"]}),e.jsxs("button",{onClick:()=>{$s(),V("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(wp,{className:"h-4 w-4"}),"Edit"]}),e.jsx("button",{onClick:jn,className:"hub-glass inline-flex h-9 w-9 items-center justify-center rounded-full",title:"Delete contact",children:e.jsx(Sn,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 sm:flex sm:flex-wrap",children:[h.phone&&e.jsxs("a",{href:`tel:${h.phone}`,className:"hub-glass inline-flex items-center justify-center gap-2 rounded-xl px-4 py-2.5 text-sm font-medium",children:[e.jsx(_a,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Call"]}),h.phone&&e.jsxs("button",{onClick:()=>window.location.href=`sms:${h.phone}`,className:"hub-glass inline-flex items-center justify-center gap-2 rounded-xl px-4 py-2.5 text-sm font-medium",children:[e.jsx(Hi,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Text"]}),h.email&&e.jsxs("button",{onClick:()=>Vs(h.email,`${h.first_name} ${h.last_name||""}`.trim()),className:"hub-glass inline-flex items-center justify-center gap-2 rounded-xl px-4 py-2.5 text-sm font-medium",children:[e.jsx(ln,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Email"]}),e.jsxs("button",{onClick:()=>r(`/mission-control/video/record?contact_id=${s}`),className:"hub-glass inline-flex items-center justify-center gap-2 rounded-xl px-4 py-2.5 text-sm font-medium",children:[e.jsx(Kr,{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(rn,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Log Action"]}),h.email&&e.jsxs("button",{onClick:()=>Fe(!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(un,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Connect Page"]})]})]})}),e.jsxs(Yr,{value:O,onValueChange:on=>{on==="details"&&!I&&$s(),V(on)},children:[e.jsx("div",{className:"-mx-1 overflow-x-auto px-1",children:e.jsxs(Zr,{className:"inline-flex h-10 w-auto",children:[e.jsx(Ht,{value:"overview",children:"Overview"}),e.jsx(Ht,{value:"details",children:"Details"}),e.jsx(Ht,{value:"activity",children:"Activity"}),e.jsx(Ht,{value:"marketing",children:"Marketing"}),t&&e.jsx(Ht,{value:"property-intel",children:"Property Intelligence"})]})}),e.jsx(Gt,{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(LDn,{contact:h,onLogTouch:()=>ce(!0)}),e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-3",children:e.jsxs(St,{className:"flex items-center gap-2 text-base",children:[e.jsx(ga,{className:"h-4 w-4 text-primary"}),"Key Dates"]})}),e.jsxs(Me,{children:[e.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:[{icon:Vo,label:"Birthday",value:h.birthday},{icon:Jr,label:"Home Anniversary",value:h.home_anniversary},{icon:Do,label:"Wedding Anniversary",value:h.wedding_anniversary},{icon:Do,label:"Spouse Birthday",value:h.spouse_birthday}].map(({icon:on,label:Ir,value:Wn})=>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(on,{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:Ir}),e.jsx("p",{className:"truncate text-sm font-medium",children:Wn?Hs(Ru(Wn),Ru(Wn).getFullYear()===1900?"MMMM d":"MMMM d, yyyy"):"—"})]})]},Ir))}),wt.length>0&&e.jsxs("p",{className:"mt-3 text-xs text-muted-foreground",children:["Last contacted ",Hs(new Date(wt[0].completed_at),"MMM d, yyyy")," (",wt[0].name,")",h.created_at&&` · Added ${Hs(new Date(h.created_at),"MMM d, yyyy")}`]})]})]}),(h.address||h.city)&&e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-3",children:e.jsxs(St,{className:"flex items-center gap-2 text-base",children:[e.jsx(Jr,{className:"h-4 w-4 text-primary"}),"Home"]})}),e.jsxs(Me,{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Xa,{className:"mt-0.5 h-4 w-4 text-muted-foreground"}),e.jsxs("div",{className:"text-sm",children:[h.address&&e.jsx("div",{children:h.address}),e.jsxs("div",{className:"text-muted-foreground",children:[[h.city,h.state].filter(Boolean).join(", "),h.zip_code?` ${h.zip_code}`:""]})]})]}),nt&&h.address&&h.city&&h.state&&e.jsxs(B,{size:"sm",variant:"outline",onClick:$e,disabled:Ue,children:[Ue?e.jsx(Ct,{className:"mr-1 h-4 w-4 animate-spin"}):e.jsx(uj,{className:"mr-1 h-4 w-4"}),"Create CMA"]})]})]}),e.jsx(SFn,{contactId:h.id,ownerUserId:h.owner_user_id,legacyNote:h.notes}),e.jsx(xOn,{contactId:s})]}),e.jsxs("div",{className:"space-y-5",children:[e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-3",children:e.jsx(St,{className:"text-base",children:"Tags"})}),e.jsx(Me,{children:e.jsx(h2t,{contactId:s})})]}),e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-3",children:e.jsxs(St,{className:"flex items-center gap-2 text-base",children:[e.jsx(Fo,{className:"h-4 w-4 text-primary"}),"People & Work"]})}),e.jsxs(Me,{className:"space-y-3",children:[e.jsx(gWe,{contactId:s,currentSpouseContactId:(h==null?void 0:h.spouse_contact_id)||null,currentSpouseName:h.spouse_name||null,currentSpouseEmail:h.spouse_email||null,onLink:on=>M.mutate({contactId:s,spouseContactId:on}),onUnlink:()=>M.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:At(!h.company_name&&!h.job_title&&"text-muted-foreground"),children:h.job_title&&h.company_name?`${h.job_title} at ${h.company_name}`:h.job_title||h.company_name||"No company on file"})]})]})]}),e.jsx(yOn,{contactId:s}),e.jsx(VFn,{contactId:s})]})]})}),e.jsx(Gt,{value:"details",className:"mt-4",children:e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-3",children:e.jsx(St,{className:"text-base",children:"Edit Contact"})}),e.jsxs(Me,{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(J,{htmlFor:"first_name",children:"First Name"}),e.jsx(xe,{id:"first_name",value:Y.first_name||"",onChange:on=>Z({...Y,first_name:on.target.value})})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"last_name",children:"Last Name"}),e.jsx(xe,{id:"last_name",value:Y.last_name||"",onChange:on=>Z({...Y,last_name:on.target.value})})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"email",children:"Email"}),e.jsx(xe,{id:"email",type:"email",value:Y.email||"",onChange:on=>Z({...Y,email:on.target.value})})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"phone",children:"Phone"}),e.jsx(xe,{id:"phone",value:Y.phone||"",onChange:on=>Z({...Y,phone:on.target.value})})]})]})]}),e.jsx(wc,{}),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(J,{htmlFor:"address",children:"Street Address"}),e.jsx(xe,{id:"address",value:Y.address||"",onChange:on=>Z({...Y,address:on.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(J,{htmlFor:"city",children:"City"}),e.jsx(xe,{id:"city",value:Y.city||"",onChange:on=>Z({...Y,city:on.target.value}),placeholder:"City"})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"state",children:"State"}),e.jsx(xe,{id:"state",value:Y.state||"",onChange:on=>Z({...Y,state:on.target.value}),placeholder:"TX",maxLength:2})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"zip_code",children:"Zip Code"}),e.jsx(xe,{id:"zip_code",value:Y.zip_code||"",onChange:on=>Z({...Y,zip_code:on.target.value}),placeholder:"12345"})]})]})]}),e.jsx(wc,{}),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(J,{htmlFor:"birthday",children:"Birthday"}),e.jsx(xe,{id:"birthday",type:"date",value:Y.birthday||"",onChange:on=>Z({...Y,birthday:on.target.value})})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"home_anniversary",children:"Home Anniversary"}),e.jsx(xe,{id:"home_anniversary",type:"date",value:Y.home_anniversary||"",onChange:on=>Z({...Y,home_anniversary:on.target.value})})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"wedding_anniversary",children:"Wedding Anniversary"}),e.jsx(xe,{id:"wedding_anniversary",type:"date",value:Y.wedding_anniversary||"",onChange:on=>Z({...Y,wedding_anniversary:on.target.value})})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"spouse_birthday",children:"Spouse Birthday"}),e.jsx(xe,{id:"spouse_birthday",type:"date",value:Y.spouse_birthday||"",onChange:on=>Z({...Y,spouse_birthday:on.target.value})})]})]})]}),e.jsx(wc,{}),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(gWe,{contactId:s,currentSpouseContactId:(h==null?void 0:h.spouse_contact_id)||null,currentSpouseName:(h==null?void 0:h.spouse_name)||null,currentSpouseEmail:(h==null?void 0:h.spouse_email)||null,onLink:on=>M.mutate({contactId:s,spouseContactId:on}),onUnlink:()=>M.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(J,{htmlFor:"company_name",children:"Company"}),e.jsx(xe,{id:"company_name",value:Y.company_name||"",onChange:on=>Z({...Y,company_name:on.target.value}),placeholder:"Enter company name"})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"job_title",children:"Job Title"}),e.jsx(xe,{id:"job_title",value:Y.job_title||"",onChange:on=>Z({...Y,job_title:on.target.value}),placeholder:"Enter job title"})]})]}),e.jsx(RYt,{value:Y.lead_source_id||"",onChange:on=>Z({...Y,lead_source_id:on})})]}),e.jsx(wc,{}),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:p==null?void 0:p.filter(on=>on.active).map(on=>{var Wn;const Ir=!!((Wn=Y.tagIds)!=null&&Wn.includes(on.id));return e.jsxs("label",{className:At("inline-flex cursor-pointer items-center gap-2 rounded-full border px-3 py-1.5 text-sm transition-colors",Ir?"border-primary bg-primary/10 text-primary":"border-border hover:bg-accent"),children:[e.jsx($a,{checked:Ir,onCheckedChange:Js=>{var Fa;Z(Js?{...Y,tagIds:[...Y.tagIds||[],on.id]}:{...Y,tagIds:(Fa=Y.tagIds)==null?void 0:Fa.filter(ks=>ks!==on.id)})}}),on.name]},on.id)})}),e.jsxs("div",{children:[e.jsx(J,{children:"Tags"}),e.jsx("div",{className:"mt-2",children:e.jsx(h2t,{contactId:s})})]})]}),e.jsx(wc,{}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"notes",children:"Notes"}),e.jsx(Ms,{id:"notes",value:Y.notes||"",onChange:on=>Z({...Y,notes:on.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(B,{variant:"outline",onClick:()=>{D(!1),V("overview")},children:"Cancel"}),e.jsxs(B,{onClick:As,disabled:C.isPending,children:[C.isPending?e.jsx(Ct,{className:"mr-1 h-4 w-4 animate-spin"}):e.jsx(ea,{className:"mr-1 h-4 w-4"}),"Save Changes"]})]})]})]})}),e.jsx(Gt,{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(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between gap-2 pb-3",children:[e.jsx(St,{className:"text-base",children:"Activity Log"}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>ce(!0),children:[e.jsx(rn,{className:"mr-1 h-3.5 w-3.5"})," Log Action"]})]}),e.jsx(Me,{children:wt.length>0?e.jsx("div",{className:"space-y-4",children:wt.map(on=>{var Ir;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:on.color},children:on.type==="popby"?e.jsx(Vo,{className:"h-4 w-4"}):(Ir=on.name)==null?void 0:Ir.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:on.name}),on.videoId&&e.jsxs(B,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:()=>Ae(on.videoId),children:[e.jsx(Jd,{className:"mr-1 h-3 w-3"}),"Preview"]})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Hs(new Date(on.completed_at),"MMM d, yyyy h:mm a")}),on.notes&&!on.videoId&&e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:on.notes})]})]},on.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:[g&&g.length>0&&e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-3",children:e.jsxs(St,{className:"flex items-center gap-2 text-base",children:[e.jsx(Hi,{className:"h-4 w-4 text-primary"}),"Video Replies"]})}),e.jsx(Me,{children:e.jsx("div",{className:"space-y-4",children:g.map(on=>{var Ir,Wn;return e.jsxs("div",{className:"flex items-start gap-3 border-b pb-3 last:border-0",children:[(Ir=on.video)!=null&&Ir.thumbnail_url?e.jsx("img",{src:on.video.thumbnail_url,alt:on.video.title||"Video",className:"h-12 w-16 cursor-pointer rounded object-cover transition-opacity hover:opacity-80",onClick:()=>Ae(on.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:()=>Ae(on.video_id),children:e.jsx(Kr,{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: ",((Wn=on.video)==null?void 0:Wn.title)||"Untitled Video"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Hs(new Date(on.created_at),"MMM d, yyyy h:mm a")}),on.message&&e.jsxs("p",{className:"mt-1 line-clamp-2 text-sm text-muted-foreground",children:['"',on.message,'"']})]})]},on.id)})})})]}),Ge&&Ge.length>0&&e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-3",children:e.jsxs(St,{className:"flex items-center gap-2 text-base",children:[e.jsx(Or,{className:"h-4 w-4 text-sky-500"}),"Sent Emails"]})}),e.jsx(Me,{children:e.jsx("div",{className:"space-y-3",children:Ge.map(on=>e.jsxs(Ls,{children:[e.jsx(nl,{asChild:!0,children:e.jsxs("button",{className:"flex w-full cursor-pointer items-start gap-3 rounded-lg border p-3 text-left transition-colors hover:bg-muted/50",children:[e.jsx("div",{className:"flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full bg-sky-500/10 text-sky-600",children:e.jsx(ln,{className:"h-4 w-4"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:on.subject}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["To: ",on.to_email," · ",Hs(new Date(on.sent_at),"MMM d, yyyy h:mm a")]})]}),e.jsx(xi,{className:"mt-1 h-4 w-4 flex-shrink-0 text-muted-foreground"})]})}),e.jsxs(Ps,{className:"flex max-h-[85vh] max-w-2xl flex-col",children:[e.jsxs(Os,{children:[e.jsxs(Ds,{className:"flex items-center gap-2",children:[e.jsx(ln,{className:"h-5 w-5 text-sky-500"}),on.subject]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["To: ",on.to_email," · ",Hs(new Date(on.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:on.body,className:"h-[400px] w-full border-0",sandbox:"",title:`Email: ${on.subject}`})})]})]},on.id))})})]}),e.jsx(eOn,{contactId:s})]})]})}),e.jsx(Gt,{value:"marketing",className:"mt-4",children:e.jsxs("div",{className:"grid gap-5 lg:grid-cols-2",children:[e.jsx(KFn,{contactId:s,contactName:h.first_name}),e.jsx(HFn,{contactId:s}),n&&e.jsxs(e.Fragment,{children:[e.jsx(GFn,{contactId:s,contactName:h.first_name}),e.jsx(WFn,{contactId:s,contactName:h.first_name})]}),e.jsx(XFn,{contactId:s})]})}),t&&e.jsx(Gt,{value:"property-intel",className:"mt-4",children:e.jsx(pOn,{contactId:s,contactAddress:h.address,contactCity:h.city,contactState:h.state,contactZip:h.zip_code})})]}),e.jsxs("div",{className:"fixed inset-x-0 bottom-0 z-40 flex items-center gap-2 border-t bg-background/95 px-3 py-2 pb-[calc(env(safe-area-inset-bottom)+0.5rem)] backdrop-blur lg:hidden",children:[h.phone&&e.jsx("a",{href:`tel:${h.phone}`,className:"flex-1",children:e.jsxs(B,{variant:"outline",className:"w-full",children:[e.jsx(_a,{className:"mr-1 h-4 w-4"})," Call"]})}),h.phone&&e.jsxs(B,{variant:"outline",className:"flex-1",onClick:()=>window.location.href=`sms:${h.phone}`,children:[e.jsx(Hi,{className:"mr-1 h-4 w-4"})," Text"]}),e.jsxs(B,{className:"flex-1",onClick:()=>ce(!0),children:[e.jsx(rn,{className:"mr-1 h-4 w-4"})," Log"]})]}),e.jsx(Ls,{open:ne,onOpenChange:ce,children:e.jsxs(Ps,{className:"max-h-[85vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Ds,{children:"Log an Action"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Action Type"}),e.jsx("div",{className:"mt-2 grid grid-cols-2 gap-2",children:f==null?void 0:f.filter(on=>on.active).map(on=>e.jsxs("button",{onClick:()=>te(on.id),className:At("rounded-lg border p-3 text-left transition-all",ie===on.id?"border-primary bg-primary/10":"hover:bg-accent"),children:[e.jsx("div",{className:"font-medium",children:on.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:on.description})]},on.id))}),Dn&&e.jsxs("div",{className:"mt-3",children:[e.jsx(J,{htmlFor:"custom-action-name",children:"What did you do?"}),e.jsx(xe,{id:"custom-action-name",value:he,onChange:on=>pe(on.target.value),placeholder:"e.g. Met a client for lunch, Dropped off a gift...",className:"mt-1"})]})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Date (optional — backdate if needed)"}),e.jsxs(od,{children:[e.jsx(ld,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:At("mt-2 w-full justify-start text-left font-normal",!be&&"text-muted-foreground"),children:[e.jsx(ga,{className:"mr-2 h-4 w-4"}),be?Hs(be,"PPP"):"Today (default)"]})}),e.jsx(Qc,{className:"w-auto p-0",align:"start",children:e.jsx(Pj,{mode:"single",selected:be,onSelect:me,disabled:on=>on>new Date,initialFocus:!0,className:At("p-3 pointer-events-auto")})})]})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"action-notes",children:"Notes (optional)"}),e.jsx(Ms,{id:"action-notes",value:ae,onChange:on=>le(on.target.value),placeholder:"Add any notes about this interaction...",rows:3})]}),e.jsxs(B,{onClick:Ur,disabled:!ie||Dn&&!he.trim()||P.isPending,className:"w-full",children:[e.jsx(ea,{className:"mr-1 h-4 w-4"}),"Complete Action"]})]})]})}),e.jsx(Ls,{open:!!Ce,onOpenChange:on=>!on&&Ae(null),children:e.jsxs(Ps,{className:"max-w-2xl",children:[e.jsx(Os,{children:e.jsx(Ds,{children:"Video Preview"})}),Ce&&e.jsx(fOn,{videoId:Ce})]})})]})}),H&&h&&e.jsx(_Fn,{open:G,onOpenChange:$,contactId:h.id,contactName:`${h.first_name} ${h.last_name||""}`.trim(),hasEmail:!!h.email}),qe&&h&&ke&&e.jsx(DS,{open:Pe,onOpenChange:ze,contact:{id:h.id,first_name:h.first_name,last_name:h.last_name,email:ke.email},gmailEmail:Ye}),h&&h.email&&e.jsx(AFn,{open:Se,onOpenChange:Fe,contact:{id:h.id,first_name:h.first_name,last_name:h.last_name,email:h.email}})]}):e.jsx(zs,{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(B,{onClick:()=>r("/mission-control/contacts"),children:"Back to Contacts"})]})})}function bOn({rangeDays:s}){const{user:t}=hs(),n=Bt(),[r,a]=_.useState(null),[i,l]=_.useState(null),[o,c]=_.useState(!1),{data:d=[],isLoading:u}=at({queryKey:["newsletter-campaigns",t==null?void 0:t.id,s],enabled:!!t,queryFn:async()=>{let p=q.from("email_campaigns").select("id, name, subject, status, sent_at, scheduled_at, created_at, total_recipients, sent_count, open_count, click_count, bounce_count").eq("user_id",t.id).like("name","Newsletter:%").order("created_at",{ascending:!1}).limit(50);if(s){const v=new Date(Date.now()-s*864e5).toISOString();p=p.gte("created_at",v)}const{data:f,error:y}=await p;if(y)throw y;return f||[]}}),{data:h}=at({queryKey:["newsletter-campaign-recipients",r],enabled:!!r,queryFn:async()=>{const{data:p,error:f}=await q.from("email_campaign_recipients").select("id, email, name, status, sent_at, opened_at, clicked_at, error_message").eq("campaign_id",r).order("sent_at",{ascending:!1}).limit(2e3);if(f)throw f;return p||[]}}),m=async()=>{if(!(!i||!t)){c(!0);try{const{data:p,error:f}=await q.from("email_campaign_recipients").select("email, name, contact_id").eq("campaign_id",i.id).eq("status","sent").is("opened_at",null).limit(5e3);if(f)throw f;if(!p||p.length===0){se.info("All recipients opened — nothing to resend!"),l(null),c(!1);return}const{data:y}=await q.from("email_campaigns").select("subject, body_html, from_email, reply_to_email").eq("id",i.id).single();if(!y)throw new Error("Original campaign not found");const{data:v,error:g}=await q.from("email_campaigns").insert({user_id:t.id,name:`${i.name} (Resend to non-openers)`,subject:y.subject,body_html:y.body_html,from_email:y.from_email,reply_to_email:y.reply_to_email,total_recipients:p.length,status:"draft"}).select("id").single();if(g)throw g;const b=p.map(S=>({campaign_id:v.id,contact_id:S.contact_id,email:S.email,name:S.name,status:"pending"}));for(let S=0;S{const f=p.sent_count||0,y=f>0?p.open_count/f*100:0,v=f>0?p.click_count/f*100:0,g=p.sent_at?CN(new Date,new Date(p.sent_at)):0,b=p.status==="sent"&&g>=3&&f>0&&p.open_counta(p.id),children:[e.jsx(ya,{className:"h-3.5 w-3.5 mr-1"})," Details"]}),b&&e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>l(p),children:[e.jsx(a7,{className:"h-3.5 w-3.5 mr-1"})," Resend"]})]})]}),p.status==="sent"&&f>0&&e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 mt-3",children:[e.jsx(Hce,{icon:e.jsx(Or,{className:"h-3.5 w-3.5"}),label:"Sent",value:f,sub:`of ${p.total_recipients}`}),e.jsx(Hce,{icon:e.jsx(ya,{className:"h-3.5 w-3.5 text-blue-600"}),label:"Opens",value:p.open_count,sub:`${y.toFixed(1)}%`,children:e.jsx(Fi,{value:y,className:"h-1 mt-1"})}),e.jsx(Hce,{icon:e.jsx($h,{className:"h-3.5 w-3.5 text-purple-600"}),label:"Clicks",value:p.click_count,sub:`${v.toFixed(1)}%`,children:e.jsx(Fi,{value:v,className:"h-1 mt-1"})}),e.jsx(Hce,{icon:e.jsx(JM,{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(qg,{open:!!r,onOpenChange:p=>!p&&a(null),children:e.jsxs(hg,{className:"w-full sm:max-w-2xl overflow-y-auto",children:[e.jsx(P0,{children:e.jsx(L0,{children:"Recipient Activity"})}),e.jsx("div",{className:"mt-4 space-y-1",children:h?h.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No recipients yet."}):e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"text-xs uppercase text-muted-foreground border-b",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left py-2",children:"Recipient"}),e.jsx("th",{className:"text-left py-2",children:"Opened"}),e.jsx("th",{className:"text-left py-2",children:"Clicked"}),e.jsx("th",{className:"text-left py-2",children:"Status"})]})}),e.jsx("tbody",{children:h.map(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(Oe,{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(Oe,{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(Oe,{variant:"outline",className:"text-xs",children:"sent"}),p.status==="pending"&&e.jsx(Oe,{variant:"secondary",className:"text-xs",children:"queued"}),p.status==="failed"&&e.jsx(Oe,{variant:"destructive",className:"text-xs",title:p.error_message||"",children:"failed"}),p.status==="suppressed"&&e.jsx(Oe,{variant:"outline",className:"text-xs",children:"suppressed"})]})]},p.id))})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading…"})})]})}),e.jsx(Kl,{open:!!i,onOpenChange:p=>!p&&l(null),children:e.jsxs(Ol,{children:[e.jsxs(zl,{children:[e.jsx(Ul,{children:"Resend to non-openers?"}),e.jsxs(ql,{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($l,{disabled:o,children:"Cancel"}),e.jsx(Ml,{onClick:m,disabled:o,children:o?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"h-4 w-4 mr-1 animate-spin"}),"Resending…"]}):e.jsxs(e.Fragment,{children:[e.jsx(a7,{className:"h-4 w-4 mr-1"}),"Resend"]})})]})]})})]})}function Hce({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 pse(){var r;const{data:{session:s}}=await q.auth.getSession(),t=s!=null&&s.expires_at?s.expires_at*1e3:0;if(!(s!=null&&s.access_token)||t-Date.now()<12e4){const{data:a,error:i}=await q.auth.refreshSession();if(i||!((r=a.session)!=null&&r.access_token))throw new Error("Your session expired. Please refresh the page (or sign in again) and try sending once more.");return a.session.access_token}return s.access_token}function _On(){const{user:s}=hs(),t=Fn(),n=Bt(),{data:r=[],isLoading:a}=at({queryKey:["scheduled-email-campaigns",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:d,error:u}=await q.from("email_campaigns").select("id, name, subject, scheduled_at, total_recipients, status, created_at").eq("user_id",s.id).eq("status","scheduled").order("scheduled_at",{ascending:!0});if(u)throw u;return d||[]},refetchInterval:3e4}),i=async(d,u)=>{const h=await pse(),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=mt({mutationFn:d=>i("cancel",d),onSuccess:()=>{se.success("Schedule cancelled — saved as draft"),n.invalidateQueries({queryKey:["scheduled-email-campaigns"]})},onError:d=>se.error(d.message)}),o=mt({mutationFn:d=>i("delete",d),onSuccess:()=>{se.success("Scheduled email deleted"),n.invalidateQueries({queryKey:["scheduled-email-campaigns"]})},onError:d=>se.error(d.message)}),c=mt({mutationFn:async({id:d,iso:u})=>{const{error:h}=await q.from("email_campaigns").update({scheduled_at:u,status:"scheduled"}).eq("id",d);if(h)throw h;await i("schedule",d)},onSuccess:()=>{se.success("Send time updated"),n.invalidateQueries({queryKey:["scheduled-email-campaigns"]})},onError:d=>se.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(ve,{children:e.jsxs(Me,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Gr,{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(wOn,{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 wOn({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]=_.useState(!1),[d,u]=_.useState(l||void 0),[h,m]=_.useState(l?`${String(l.getHours()).padStart(2,"0")}:${String(l.getMinutes()).padStart(2,"0")}`:"09:00"),p=()=>{if(!d)return se.error("Pick a date");const f=new Date(`${Hs(d,"yyyy-MM-dd")}T${h}:00`).toISOString();if(new Date(f).getTime()fm(f.target.value)})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"ghost",onClick:()=>c(!1),children:"Cancel"}),e.jsxs(B,{onClick:p,disabled:i,children:[i&&e.jsx(Ct,{className:"h-4 w-4 mr-1.5 animate-spin"}),"Save new time"]})]})]})]}),e.jsxs(Kl,{children:[e.jsx(jx,{asChild:!0,children:e.jsxs(B,{size:"sm",variant:"outline",disabled:i,children:[e.jsx(Rd,{className:"h-3.5 w-3.5 mr-1.5"})," Cancel Send"]})}),e.jsxs(Ol,{children:[e.jsxs(zl,{children:[e.jsx(Ul,{children:"Cancel this scheduled send?"}),e.jsxs(ql,{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($l,{children:"Keep scheduled"}),e.jsx(Ml,{onClick:n,children:"Cancel send"})]})]})]}),e.jsxs(Kl,{children:[e.jsx(jx,{asChild:!0,children:e.jsxs(B,{size:"sm",variant:"ghost",className:"text-destructive hover:text-destructive",disabled:i,children:[e.jsx(Sn,{className:"h-3.5 w-3.5 mr-1.5"})," Delete"]})}),e.jsxs(Ol,{children:[e.jsxs(zl,{children:[e.jsx(Ul,{children:"Delete this scheduled email?"}),e.jsx(ql,{children:"This permanently removes the scheduled email and all its recipient records. This can't be undone."})]}),e.jsxs(Bl,{children:[e.jsx($l,{children:"Keep"}),e.jsx(Ml,{onClick:r,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete permanently"})]})]})]})]})]})})})}function jOn({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 Gce({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:At("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(xi,{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 NOn({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(jOn,{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(Gce,{icon:e.jsx(Er,{className:"h-3.5 w-3.5"}),label:"Delivered",value:s.toLocaleString(),hint:"All sends completed"}),e.jsx(Gce,{icon:e.jsx(ya,{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(Gce,{icon:e.jsx($h,{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(Gce,{icon:e.jsx(Gr,{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 C2t=["Gmail","Mass Email","Campaign","Client Portal Invite"],kOn={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 SOn(){const{user:s}=hs(),[t,n]=Yl(),{data:r=[],isLoading:a}=WYt(),[i,l]=_.useState(""),[o,c]=_.useState("all"),[d,u]=_.useState("30"),[h,m]=_.useState(!1),[p,f]=_.useState(t.get("tab")==="scheduled"?"scheduled":"sent"),{gmailEmail:y}=Vg(),{data:v=0}=at({queryKey:["scheduled-email-count",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{count:P}=await q.from("email_campaigns").select("id",{count:"exact",head:!0}).eq("user_id",s.id).eq("status","scheduled");return P||0},refetchInterval:3e4});_.useEffect(()=>{const P=new URLSearchParams(t);p==="scheduled"?P.set("tab","scheduled"):P.delete("tab"),n(P,{replace:!0})},[p]);const g=_.useMemo(()=>Array.from(new Set(r.map(P=>P.contact_id).filter(Boolean))),[r]),{data:b}=at({queryKey:["sent-emails-contact-names",s==null?void 0:s.id,g.length],enabled:g.length>0,queryFn:async()=>{const{data:P}=await q.from("innercircle_contacts").select("id, first_name, last_name").in("id",g),M=new Map;return(P||[]).forEach(I=>{M.set(I.id,[I.first_name,I.last_name].filter(Boolean).join(" ")||"Contact")}),M}}),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 j.forEach(O=>{P[O.channel]=(P[O.channel]||0)+1,(O.channel==="Campaign"||O.channel==="Mass Email")&&(D++,O.opened_at&&M++,O.clicked_at&&I++)}),{byChannel:P,opened:M,clicked:I,trackable:D}},[j]),C=d==="all"?"All time":`Last ${d} days`,E=C2t.map(P=>S.byChannel[P]?`${S.byChannel[P]} ${P}`:null).filter(Boolean).join(" · ");return e.jsx(zs,{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(Or,{className:"h-6 w-6"})," Sent Emails"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Every send in one place — Gmail, mass emails, campaigns, and portal invites."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"inline-flex rounded-full border bg-muted/40 p-1",children:[e.jsxs("button",{onClick:()=>f("sent"),className:`inline-flex items-center gap-1.5 rounded-full px-3 py-1.5 text-sm transition-colors ${p==="sent"?"bg-background shadow-sm font-medium":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(Or,{className:"h-3.5 w-3.5"})," Sent"]}),e.jsxs("button",{onClick:()=>f("scheduled"),className:`inline-flex items-center gap-1.5 rounded-full px-3 py-1.5 text-sm transition-colors ${p==="scheduled"?"bg-background shadow-sm font-medium":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(Gr,{className:"h-3.5 w-3.5"})," Scheduled",v>0&&e.jsx(Oe,{variant:"secondary",className:"ml-0.5 h-5 min-w-5 px-1.5 text-xs",children:v})]})]}),e.jsxs(B,{onClick:()=>m(!0),className:"rounded-full",children:[e.jsx(ln,{className:"h-4 w-4 mr-2"})," Send Email"]})]})]}),e.jsxs(Yr,{value:p,onValueChange:P=>f(P),className:"space-y-5",children:[e.jsxs(Gt,{value:"sent",className:"space-y-5 mt-0",children:[e.jsx(NOn,{total:j.length,opened:S.opened,clicked:S.clicked,trackable:S.trackable,scheduled:v,rangeLabel:C,channelSummary:E,onScheduledClick:()=>f("scheduled")}),e.jsxs("div",{className:"flex flex-col gap-2 rounded-2xl border bg-card p-2 md:flex-row md:items-center",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search subject, recipient, contact...",value:i,onChange: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(is,{value:o,onValueChange:c,children:[e.jsx(rs,{className:"w-[170px] rounded-full h-9",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Channels"}),C2t.map(P=>e.jsx(He,{value:P,children:P},P))]})]}),e.jsxs(is,{value:d,onValueChange:u,children:[e.jsx(rs,{className:"w-[150px] rounded-full h-9",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"7",children:"Last 7 days"}),e.jsx(He,{value:"30",children:"Last 30 days"}),e.jsx(He,{value:"90",children:"Last 90 days"}),e.jsx(He,{value:"365",children:"Last year"}),e.jsx(He,{value:"all",children:"All time"})]})]})]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground -mt-3 px-1",children:[e.jsx(hS,{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(bOn,{rangeDays:d==="all"?null:parseInt(d)}),a?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading..."}):j.length===0?e.jsx(ve,{className:"rounded-2xl",children:e.jsxs(Me,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(ln,{className:"h-12 w-12 text-muted-foreground mb-3"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No sent emails match your filters."})]})}):e.jsx(ve,{className:"rounded-2xl overflow-hidden",children:e.jsx(Me,{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(FN,{children:e.jsxs(ag,{children:[e.jsxs(ig,{className:"inline-flex items-center gap-1",children:["Engagement ",e.jsx(hS,{className:"h-3 w-3"})]}),e.jsx(Nx,{className:"max-w-xs",children:"Open & click tracking works for Mass Emails and Campaigns. Emails sent through your connected Gmail inbox aren't tracked."})]})})})]})}),e.jsx("tbody",{children:j.slice(0,500).map(P=>{const M=P.contact_id?b==null?void 0:b.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(Oe,{variant:"outline",className:kOn[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(ir,{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(Oe,{variant:"outline",className:"bg-slate-50 text-slate-700 border-slate-200 gap-1",children:[e.jsx(Er,{className:"h-3 w-3"})," Delivered"]}),P.opened_at&&e.jsxs(Oe,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200 gap-1",children:[e.jsx(ya,{className:"h-3 w-3"})," Opened"]}),P.clicked_at&&e.jsxs(Oe,{variant:"outline",className:"bg-emerald-50 text-emerald-700 border-emerald-200 gap-1",children:[e.jsx($h,{className:"h-3 w-3"})," Clicked"]})]}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"Not tracked"})})]},P.id)})})]}),j.length>500&&e.jsxs("p",{className:"text-xs text-muted-foreground text-center py-3 border-t",children:["Showing first 500 of ",j.length," — narrow your filters to see more."]})]})})})]}),e.jsx(Gt,{value:"scheduled",className:"mt-0",children:e.jsx(_On,{})})]}),e.jsx(DS,{open:h,onOpenChange:m,gmailEmail:y})]})})}const A2t={Crown:$f,FileText:Fr,Users:In,Globe:sl,Star:Da,Phone:_a,MessageSquare:Hi,PenTool:KA,Video:Kr,Gift:Vo},Wce=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function COn(){var xt,qt;const s=Fn(),{user:t}=hs(),{data:n}=Z_(),{data:r}=Kzs(),{data:a}=tBs(),{data:i}=vzt(),{data:l}=aae(),{data:o}=Wzs(),c=sBs(),d=Yzs(),u=Xzs(),h=Qzs(),m=Jzs(),p=eBs(),f=Zzs(),[y,v]=_.useState(null),[g,b]=_.useState(!1),[j,S]=_.useState(null),[C,E]=_.useState(""),[P,M]=_.useState(""),[I,D]=_.useState([]),[O,V]=_.useState(null),[G,$]=_.useState(null),[H,Y]=_.useState(null),[Z,ne]=_.useState(!1),[ce,ie]=_.useState(""),[te,ae]=_.useState(""),[le,be]=_.useState(""),[me,he]=_.useState(""),pe=(Vt,Xt)=>a==null?void 0:a.some(fs=>fs.plan_id===Vt&&fs.relationship_type_id===Xt&&fs.active),Ce=Vt=>a==null?void 0:a.find(Xt=>Xt.relationship_type_id===Vt&&Xt.active),Ae=async(Vt,Xt)=>{const fs=pe(Vt,Xt);await c.mutateAsync({planId:Vt,relationshipTypeId:Xt,active:!fs})},Pe=(r==null?void 0:r.filter(Vt=>Vt.active&&!Vt.owner_user_id))||[],ze=(r==null?void 0:r.filter(Vt=>Vt.owner_user_id===(t==null?void 0:t.id)))||[],ke=n==null?void 0:n.find(Vt=>Vt.id===y),Ze=y?Ce(y):null,Se=r==null?void 0:r.find(Vt=>Vt.id===(Ze==null?void 0:Ze.plan_id)),Fe=async()=>{if(!C.trim())return;const Vt=await d.mutateAsync({name:C,description:P});Vt&&I.length>0&&await m.mutateAsync({planId:Vt.id,items:I}),qe()},Ne=async()=>{!C.trim()||!j||(await u.mutateAsync({id:j,name:C,description:P}),await m.mutateAsync({planId:j,items:I}),qe())},Ye=Vt=>{var Xt;S(Vt.id),E(Vt.name),M(Vt.description||""),D(((Xt=Vt.items)==null?void 0:Xt.map(fs=>({month_number:fs.month_number,action_type_id:fs.action_type_id,default_script_id:fs.default_script_id||void 0,notes:fs.notes||void 0})))||[]),b(!0)},Ve=async(Vt,Xt)=>{if(Vt.owner_user_id===(t==null?void 0:t.id)){Ye(Vt);return}try{const fs=await f.mutateAsync({sourcePlanId:Vt.id,newName:`${Vt.name} (My Copy)`});if(!fs)return;await c.mutateAsync({planId:Vt.id,relationshipTypeId:Xt,active:!1}),await c.mutateAsync({planId:fs.id,relationshipTypeId:Xt,active:!0}),S(fs.id),E(fs.name),M(fs.description||""),D((Vt.items||[]).map(Ft=>({month_number:Ft.month_number,action_type_id:Ft.action_type_id,default_script_id:Ft.default_script_id||void 0,notes:Ft.notes||void 0}))),b(!0)}catch{}},qe=()=>{b(!1),S(null),E(""),M(""),D([])},Qe=(Vt,Xt)=>{$(Xt)},Ue=(Vt,Xt,fs)=>{D(Ft=>[...Ft.filter(Ts=>Ts.month_number!==Vt),{month_number:Vt,action_type_id:Xt,default_script_id:fs}]),V(null),$(null)},Xe=Vt=>{D(Xt=>Xt.filter(fs=>fs.month_number!==Vt))},nt=async()=>{if(!ce.trim()||!te.trim()||!G)return;const Vt=await p.mutateAsync({actionTypeId:G,title:ce,scriptBody:te,emailSubject:le||void 0,tone:me||void 0});Vt&&O!==null&&Ue(O,G,Vt.id),ne(!1),ie(""),ae(""),be(""),he("")},$e=G?o==null?void 0:o.filter(Vt=>Vt.action_type_id===G&&Vt.active):[],Ge=Vt=>A2t[Vt||"Phone"]||_a,ct=Vt=>A2t[Vt||"Users"]||In;return e.jsxs(zs,{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(B,{variant:"ghost",size:"sm",onClick:()=>s("/mission-control"),children:[e.jsx($c,{className:"h-4 w-4 mr-1"}),"Back"]}),e.jsxs(B,{onClick:()=>b(!0),className:"w-full sm:w-auto",children:[e.jsx(rn,{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(Vt=>Vt.active).map(Vt=>{const Xt=ct(Vt.icon),fs=(i==null?void 0:i[Vt.id])||0,Ft=Ce(Vt.id),wt=r==null?void 0:r.find(vt=>vt.id===(Ft==null?void 0:Ft.plan_id)),Ts=y===Vt.id;return e.jsxs("button",{onClick:()=>v(Vt.id),className:` w-full flex items-center gap-3 p-4 rounded-lg border text-left transition-all ${Ts?"border-primary bg-primary/5 ring-2 ring-primary":"hover:bg-accent"} `,children:[e.jsx(Xt,{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:Vt.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[fs," contacts"]})]}),wt?e.jsxs(Oe,{variant:"secondary",className:"text-xs",children:[e.jsx(_l,{className:"h-3 w-3 mr-1"}),wt.name.split(" ")[0]]}):e.jsx(Oe,{variant:"outline",className:"text-xs text-muted-foreground",children:"No plan"})]},Vt.id)})]}),e.jsx("div",{className:"lg:col-span-2",children:y&&ke?e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsxs(St,{className:"flex items-center gap-2",children:[(()=>{const Vt=ct(ke.icon);return e.jsx(Vt,{className:"h-5 w-5"})})(),ke.name," Touchpoint Plan"]}),e.jsxs(kn,{children:["Choose a plan for your ",ke.name," contacts"]})]}),e.jsxs(Me,{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(_l,{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(B,{variant:"outline",size:"sm",disabled:f.isPending||c.isPending,onClick:()=>Ve(Se,y),children:[e.jsx(V2,{className:"h-4 w-4 mr-1"}),"Edit Steps"]}),e.jsx(B,{variant:"outline",size:"sm",onClick:()=>Ae(Se.id,y),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(ga,{className:"h-4 w-4"}),"12-Month Schedule"]}),e.jsx("div",{className:"grid grid-cols-4 sm:grid-cols-6 gap-2",children:Wce.map((Vt,Xt)=>{var Ts,vt;const fs=((Ts=Se.items)==null?void 0:Ts.filter($s=>$s.month_number===Xt+1))||[],Ft=(vt=fs[0])==null?void 0:vt.action_type,wt=Ft?Ge(Ft.icon):null;return e.jsxs("div",{className:` p-2 rounded border text-center ${fs.length>0?"bg-primary/10 border-primary":"bg-muted"} `,children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:Vt}),wt&&e.jsx(wt,{className:"h-4 w-4 mx-auto mt-1",style:{color:(Ft==null?void 0:Ft.color)||"#3B82F6"}})]},Xt)})})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-3",children:Se?"Switch to a Different Plan":"Choose a Plan"}),Pe.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"}),Pe.map(Vt=>{var fs;const Xt=(Se==null?void 0:Se.id)===Vt.id;return e.jsxs("div",{className:` flex items-center justify-between p-3 rounded-lg border ${Xt?"opacity-50":"hover:bg-accent"} `,children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Vt.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[((fs=Vt.items)==null?void 0:fs.length)||0," touchpoints/year"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{size:"sm",variant:"ghost",title:"View plan details",onClick:()=>Y(Vt.id),children:e.jsx(ya,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",title:"Duplicate as my own plan",disabled:f.isPending,onClick:()=>{const Ft=`${Vt.name} (Copy)`;f.mutate({sourcePlanId:Vt.id,newName:Ft})},children:e.jsx(Ia,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:Xt?"outline":"default",disabled:Xt||c.isPending,onClick:()=>Ae(Vt.id,y),children:Xt?"Active":"Use This"})]})]},Vt.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(Vt=>{var fs;const Xt=(Se==null?void 0:Se.id)===Vt.id;return e.jsxs("div",{className:` flex items-center justify-between p-3 rounded-lg border ${Xt?"opacity-50":"hover:bg-accent"} `,children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Vt.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[((fs=Vt.items)==null?void 0:fs.length)||0," touchpoints/year"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{size:"sm",variant:"ghost",title:"View plan details",onClick:()=>Y(Vt.id),children:e.jsx(ya,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",title:"Edit plan",onClick:()=>Ye(Vt),children:e.jsx(V2,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",title:"Delete plan",onClick:()=>h.mutate(Vt.id),children:e.jsx(Sn,{className:"h-4 w-4 text-destructive"})}),e.jsx(B,{size:"sm",variant:Xt?"outline":"default",disabled:Xt||c.isPending,onClick:()=>Ae(Vt.id,y),children:Xt?"Active":"Use This"})]})]},Vt.id)})]}),Pe.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(ve,{children:e.jsxs(Me,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(ga,{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(ve,{className:"bg-muted/50",children:e.jsx(Me,{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(Ls,{open:g,onOpenChange:Vt=>{Vt?b(!0):qe()},children:e.jsxs(Ps,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Ds,{children:j?"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(J,{htmlFor:"plan-name",children:"Plan Name"}),e.jsx(xe,{id:"plan-name",value:C,onChange:Vt=>E(Vt.target.value),placeholder:"e.g., My VIP Plan"})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"plan-description",children:"Description (optional)"}),e.jsx(Ms,{id:"plan-description",value:P,onChange:Vt=>M(Vt.target.value),placeholder:"Describe your plan...",rows:2})]})]}),e.jsxs("div",{children:[e.jsx(J,{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:Wce.map((Vt,Xt)=>{const fs=Xt+1,Ft=I.find(vt=>vt.month_number===fs),wt=Ft?l==null?void 0:l.find(vt=>vt.id===Ft.action_type_id):null,Ts=wt?Ge(wt.icon):null;return e.jsxs("div",{className:"relative",children:[e.jsxs("button",{type:"button",onClick:()=>V(O===fs?null:fs),className:` w-full p-3 rounded-lg border text-center transition-all ${Ft?"bg-primary/10 border-primary":"bg-muted hover:bg-accent"} ${O===fs?"ring-2 ring-primary":""} `,children:[e.jsx("div",{className:"text-xs text-muted-foreground font-medium",children:Vt}),Ts?e.jsx(Ts,{className:"h-5 w-5 mx-auto mt-1",style:{color:(wt==null?void 0:wt.color)||"#3B82F6"}}):e.jsx(rn,{className:"h-5 w-5 mx-auto mt-1 text-muted-foreground/50"})]}),Ft&&e.jsx("button",{type:"button",onClick:vt=>{vt.stopPropagation(),Xe(fs)},className:"absolute -top-1 -right-1 p-1 bg-destructive text-destructive-foreground rounded-full",children:e.jsx(Qn,{className:"h-3 w-3"})})]},Xt)})}),O!==null&&!G&&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 ",Wce[O-1],":"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:l==null?void 0:l.filter(Vt=>Vt.active).map(Vt=>{const Xt=Ge(Vt.icon);return e.jsxs("button",{type:"button",onClick:()=>Qe(O,Vt.id),className:"flex items-center gap-2 px-3 py-2 rounded-lg border bg-background hover:bg-accent transition-colors",children:[e.jsx(Xt,{className:"h-4 w-4",style:{color:Vt.color||"#3B82F6"}}),e.jsx("span",{className:"text-sm",children:Vt.name})]},Vt.id)})})]}),O!==null&&G&&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(B,{variant:"ghost",size:"sm",onClick:()=>$(null),children:[e.jsx($c,{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(O,G),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"})]})}),$e==null?void 0:$e.map(Vt=>e.jsx("button",{type:"button",onClick:()=>Ue(O,G,Vt.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:Vt.title}),Vt.tone&&e.jsx(Oe,{variant:"secondary",className:"text-xs mt-1",children:Vt.tone}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-1 line-clamp-2",children:[Vt.script_body.substring(0,100),"..."]})]})},Vt.id)),e.jsxs("button",{type:"button",onClick:()=>ne(!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(rn,{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(yr,{children:[e.jsx(B,{variant:"outline",onClick:qe,children:"Cancel"}),e.jsxs(B,{onClick:j?Ne:Fe,disabled:!C.trim()||d.isPending||u.isPending,children:[e.jsx(Ho,{className:"h-4 w-4 mr-2"}),j?"Save Changes":"Create Plan"]})]})]})}),e.jsx(Ls,{open:Z,onOpenChange:ne,children:e.jsxs(Ps,{className:"max-w-lg",children:[e.jsx(Os,{children:e.jsx(Ds,{children:"Create Custom Script"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(J,{htmlFor:"script-title",children:"Script Title"}),e.jsx(xe,{id:"script-title",value:ce,onChange:Vt=>ie(Vt.target.value),placeholder:"e.g., Friendly Check-in Call"})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"script-tone",children:"Tone (optional)"}),e.jsxs(is,{value:me,onValueChange:he,children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Select tone..."})}),e.jsxs(as,{children:[e.jsx(He,{value:"friendly",children:"Friendly"}),e.jsx(He,{value:"professional",children:"Professional"}),e.jsx(He,{value:"casual",children:"Casual"}),e.jsx(He,{value:"formal",children:"Formal"})]})]})]}),((qt=(xt=l==null?void 0:l.find(Vt=>Vt.id===G))==null?void 0:xt.name)==null?void 0:qt.toLowerCase().includes("email"))&&e.jsxs("div",{children:[e.jsx(J,{htmlFor:"script-email-subject",children:"Email Subject"}),e.jsx(xe,{id:"script-email-subject",value:le,onChange:Vt=>be(Vt.target.value),placeholder:"e.g., Quick Hello!"})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"script-body",children:"Script Content"}),e.jsx(Ms,{id:"script-body",value:te,onChange:Vt=>ae(Vt.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(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>ne(!1),children:"Cancel"}),e.jsxs(B,{onClick:nt,disabled:!ce.trim()||!te.trim()||p.isPending,children:[e.jsx(Ho,{className:"h-4 w-4 mr-2"}),"Create & Use Script"]})]})]})}),e.jsx(Ls,{open:!!H,onOpenChange:Vt=>{Vt||Y(null)},children:e.jsx(Ps,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:(()=>{const Vt=r==null?void 0:r.find(Ft=>Ft.id===H);if(!Vt)return null;const Xt=Vt.owner_user_id===(t==null?void 0:t.id),fs=[...Vt.items||[]].sort((Ft,wt)=>Ft.month_number-wt.month_number);return e.jsxs(e.Fragment,{children:[e.jsxs(Os,{children:[e.jsxs(Ds,{className:"flex items-center gap-2",children:[Vt.name,!Xt&&e.jsx(Oe,{variant:"secondary",children:"Template"})]}),Vt.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:Vt.description})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:[fs.length," touchpoint",fs.length!==1?"s":""," per year"]}),e.jsx("div",{className:"space-y-2",children:Array.from({length:12},(Ft,wt)=>wt+1).map(Ft=>{const wt=fs.find(As=>As.month_number===Ft),Ts=wt?l==null?void 0:l.find(As=>As.id===wt.action_type_id):null,vt=wt!=null&&wt.default_script_id?o==null?void 0:o.find(As=>As.id===wt.default_script_id):null,$s=Ts?Ge(Ts.icon):null;return e.jsxs("div",{className:`p-3 rounded-lg border flex items-start gap-3 ${wt?"bg-muted/30":"opacity-60"}`,children:[e.jsx("div",{className:"w-16 shrink-0 font-medium text-sm",children:Wce[Ft-1]}),wt&&Ts?e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[$s&&e.jsx($s,{className:"h-4 w-4",style:{color:Ts.color||"#3B82F6"}}),e.jsx("span",{className:"font-medium text-sm",children:Ts.name}),vt&&e.jsx(Oe,{variant:"outline",className:"text-xs",children:vt.title})]}),vt&&e.jsx("div",{className:"mt-2 text-sm text-muted-foreground whitespace-pre-wrap bg-background p-2 rounded border",children:vt.script_body}),wt.notes&&e.jsx("div",{className:"mt-1 text-xs text-muted-foreground italic",children:wt.notes})]}):e.jsx("div",{className:"flex-1 text-sm text-muted-foreground",children:"No touchpoint scheduled"})]},Ft)})})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>Y(null),children:"Close"}),Xt?e.jsxs(B,{onClick:()=>{const Ft=r==null?void 0:r.find(wt=>wt.id===H);Ft&&(Y(null),Ye(Ft))},children:[e.jsx(V2,{className:"h-4 w-4 mr-2"}),"Edit Plan"]}):e.jsxs(B,{disabled:f.isPending,onClick:()=>{f.mutate({sourcePlanId:Vt.id,newName:`${Vt.name} (Copy)`}),Y(null)},children:[e.jsx(Ia,{className:"h-4 w-4 mr-2"}),"Duplicate to Edit"]})]})]})})()})})]})}const ize="https://cma.relevelup.com";function XYt({open:s,onOpenChange:t,cma:n}){var Y;const{user:r}=hs(),{toast:a}=vi(),[i,l]=_.useState([]),[o,c]=_.useState(null),[d,u]=_.useState(!1),[h,m]=_.useState(""),[p,f]=_.useState(""),[y,v]=_.useState(""),[g,b]=_.useState(!1),[j,S]=_.useState(null),[C,E]=_.useState(!1),[P,M]=_.useState(!1),[I,D]=_.useState(null);_.useEffect(()=>{!s||!r||(async()=>{var be;const[Z,ne,ce,ie,te]=await Promise.all([q.from("innercircle_contacts").select("id, first_name, last_name, email").eq("owner_user_id",r.id).not("email","is",null).order("first_name"),q.from("profiles").select("name, email, phone, brokerage_name, avatar_url, email_signature").eq("id",r.id).maybeSingle(),q.from("gmail_integrations").select("id, is_active").eq("user_id",r.id).maybeSingle(),q.from("ses_verified_emails").select("email, status").eq("user_id",r.id).eq("status","Success").limit(1),q.from("mass_email_settings").select("*").eq("user_id",r.id).maybeSingle()]),ae=(Z.data||[]).filter(me=>me.email&&me.email.includes("@"));l(ae),S(ne.data||null),E(!!((be=ce.data)!=null&&be.is_active)),M(!!(ie.data&&ie.data.length>0)),D(te.data||null);const le=n.contact_id?ae.find(me=>me.id===n.contact_id):null;le&&(c(le),m(le.email))})()},[s,r,n.contact_id]),_.useEffect(()=>{var ie;if(!s)return;const Z=((ie=n.subject)==null?void 0:ie.address)||"your home",ne=((j==null?void 0:j.name)||"").split(" ")[0]||"your agent",ce=(o==null?void 0:o.first_name)||"there";f(`Your home value report for ${Z}`),v(`Hi ${ce}, I put together a fresh market analysis for ${Z}. 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, ${(j==null?void 0:j.name)||ne}`)},[s,o==null?void 0:o.id,j==null?void 0:j.name,(Y=n.subject)==null?void 0:Y.address]);const O=_.useMemo(()=>C?"Gmail (your inbox)":P?"Amazon SES":null,[C,P]),V=!!(h.trim()&&p.trim()&&y.trim()&&O&&!g),G=Z=>{c(Z),m(Z.email||""),u(!1)},$=Z=>{const ne=`${ize}/${n.share_token}?e=${Z}`,te=y.replace(/&/g,"&").replace(//g,">").replace(/\{\{cma_link\}\}/g,`View Your Home Value Report`).split(/\n{2,}/).map(be=>`

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

`).join(""),ae=j!=null&&j.use_email_signature&&(j!=null&&j.email_signature)?`
${j.email_signature}
`:`
${j!=null&&j.name?`
${j.name}
`:""} ${j!=null&&j.brokerage_name?`
${j.brokerage_name}
`:""} ${j!=null&&j.phone?`
${j.phone}
`:""} ${j!=null&&j.email?``:""}
`,le=``;return`
${te} ${ae}
Prepared with LevelUp · ReLevelUp Real Estate
${le}
`},H=async()=>{if(!(!r||!V)){b(!0);try{const{data:Z,error:ne}=await q.from("cma_email_sends").insert({cma_id:n.id,agent_id:r.id,contact_id:(o==null?void 0:o.id)??null,recipient_email:h.trim(),subject:p.trim(),sent_via:C?"gmail":"ses"}).select("id").single();if(ne)throw ne;const ce=$(Z.id);if(C){const{data:ie,error:te}=await q.functions.invoke("gmail-send",{body:{to:h.trim(),subject:p.trim(),body:ce}});if(te)throw te;if(!(ie!=null&&ie.success))throw new Error((ie==null?void 0:ie.error)||"Gmail send failed")}else if(P){const ie=(I==null?void 0:I.display_name)||(j==null?void 0:j.name)||"ReLevelUp",te=`${ie.toLowerCase().replace(/[^a-z]/g,".").replace(/^\.+|\.+$/g,"")||"noreply"}@send.relevelup.com`,{data:ae,error:le}=await q.functions.invoke("ses-send-campaign",{body:{action:"test_send",to:h.trim(),from_email:`${ie} <${te}>`,subject:p.trim(),body_html:ce,reply_to:(I==null?void 0:I.reply_to_email)||(j==null?void 0:j.email)||void 0}});if(le)throw le;if(!(ae!=null&&ae.success))throw new Error((ae==null?void 0:ae.error)||"SES send failed")}o&&!n.contact_id&&await q.from("cmas").update({contact_id:o.id}).eq("id",n.id),a({title:"CMA sent",description:`Delivered to ${h.trim()}`}),t(!1)}catch(Z){console.error("Send CMA error:",Z),a({title:"Send failed",description:Z.message||"Could not send email",variant:"destructive"})}finally{b(!1)}}};return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsxs(Ds,{className:"flex items-center gap-2",children:[e.jsx(ln,{className:"w-5 h-5"}),"Send CMA to contact"]})}),O?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Sending via ",e.jsx("span",{className:"font-semibold text-foreground",children:O})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Contact"}),e.jsxs(od,{open:d,onOpenChange:u,children:[e.jsx(ld,{asChild:!0,children:e.jsxs(B,{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(I_,{className:"w-4 h-4 opacity-50"})]})}),e.jsx(Qc,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(Aj,{children:[e.jsx(Ej,{placeholder:"Search contacts…"}),e.jsxs(Tj,{children:[e.jsx(Mj,{children:"No contacts with email found."}),e.jsx(V_,{children:i.map(Z=>e.jsxs(d1,{value:`${Z.first_name} ${Z.last_name||""} ${Z.email}`,onSelect:()=>G(Z),children:[e.jsx(ea,{className:At("w-4 h-4 mr-2",(o==null?void 0:o.id)===Z.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium",children:[Z.first_name," ",Z.last_name||""]}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:Z.email})]})]},Z.id))})]})]})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"To email"}),e.jsx(xe,{type:"email",value:h,onChange:Z=>m(Z.target.value),placeholder:"client@example.com"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Subject"}),e.jsx(xe,{value:p,onChange:Z=>f(Z.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Message"}),e.jsx(Ms,{rows:10,value:y,onChange:Z=>v(Z.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(wr,{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:`${ize}/${n.share_token}`,target:"_blank",rel:"noreferrer",children:`${ize}/${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(yr,{children:[e.jsx(B,{variant:"ghost",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{onClick:H,disabled:!V,children:[g?e.jsx(Ct,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(Or,{className:"w-4 h-4 mr-2"}),"Send CMA"]})]})]})})}function AOn(s){const{user:t}=hs(),n=Bt(),{data:r}=at({queryKey:["lead-site-upgrade-requests",t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{const{data:l,error:o}=await q.from("lead_site_upgrade_requests").select("id, feature_key, status, created_at").eq("user_id",t.id);if(o)throw o;return l}}),a=mt({mutationFn:async({featureKey:l,notes:o})=>{const{error:c}=await q.from("lead_site_upgrade_requests").insert({user_id:t.id,site_id:s??null,feature_key:l,notes:o??null});if(c)throw c},onSuccess:()=>{n.invalidateQueries({queryKey:["lead-site-upgrade-requests",t==null?void 0:t.id]}),se.success("Request sent — we'll reach out about upgrading your site.")},onError:l=>se.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 EOn="free_luxury",TOn="free_beta";function QYt(s){const t=s==null?void 0:s.planTier;return t===EOn||t===TOn}const MOn={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 POn({featureKey:s,siteId:t,bullets:n}){const r=MOn[s],{requestUpgrade:a,hasRequested:i,isSending:l}=AOn(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(ec,{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(un,{className:"h-4 w-4 mt-0.5 text-amber-500 shrink-0"}),c]},c))}):null,e.jsx(B,{className:"mt-5",disabled:o||l,onClick:()=>a.mutate({featureKey:s}),children:o?e.jsxs(e.Fragment,{children:[e.jsx(ea,{className:"h-4 w-4 mr-2"})," Upgrade requested"]}):"Request this upgrade"})]})]})})}function LOn({onCreated:s}){const[t,n]=_.useState(!1),[r,a]=_.useState(""),[i,l]=_.useState(""),[o,c]=_.useState(""),[d,u]=_.useState(""),h=IFn(),m=qYt(),{toast:p}=vi(),[f,y]=_.useState([]),v=async()=>{var j;y([]);try{const S=await h.mutateAsync({address:r,city:i,state:o,zip:d});y(S.matches||[]),(j=S.matches)!=null&&j.length||p({title:"No MLS match",description:'Use "Create from manual entry" below.'})}catch(S){p({title:"Search failed",description:S.message,variant:"destructive"})}},g=async j=>{const S=await m.mutateAsync({subject:j});n(!1),s(S.id)},b=async()=>{if(!r||!i||!o){p({title:"Address, city, state required"});return}const j=await m.mutateAsync({subject:{address:r,city:i,state:o,zip:d}});n(!1),s(j.id)};return e.jsxs(Ls,{open:t,onOpenChange:n,children:[e.jsx(nl,{asChild:!0,children:e.jsxs(B,{children:[e.jsx(rn,{className:"w-4 h-4 mr-2"}),"New CMA"]})}),e.jsxs(Ps,{className:"max-w-2xl",children:[e.jsx(Os,{children:e.jsx(Ds,{children:"Start a CMA"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-2",children:[e.jsx(xe,{className:"md:col-span-2",placeholder:"Street address",value:r,onChange:j=>a(j.target.value)}),e.jsx(xe,{placeholder:"City",value:i,onChange:j=>l(j.target.value)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{placeholder:"ST",maxLength:2,value:o,onChange:j=>c(j.target.value.toUpperCase())}),e.jsx(xe,{placeholder:"ZIP",value:d,onChange:j=>u(j.target.value)})]})]}),e.jsxs(B,{onClick:v,disabled:!r||h.isPending,className:"w-full",children:[h.isPending?e.jsx(Ct,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(Lr,{className:"w-4 h-4 mr-2"}),"Find in MLS"]}),f.length>0&&e.jsxs("div",{className:"space-y-2 max-h-80 overflow-y-auto",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:[f.length," match(es) — pick the subject property:"]}),f.map((j,S)=>{var C;return e.jsxs("button",{onClick:()=>g(j),className:"w-full text-left p-3 border rounded hover:bg-accent transition",children:[e.jsx("div",{className:"font-medium",children:j.address}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[j.city,", ",j.state," ",j.zip," · ",j.bedrooms??"?"," bd / ",j.bathrooms??"?"," ba · ",((C=j.sqft)==null?void 0:C.toLocaleString())??"?"," sqft",j.mlsNumber?` · MLS# ${j.mlsNumber}`:""," · ",j.source_provider]})]},S)})]}),e.jsx("div",{className:"border-t pt-3",children:e.jsxs(B,{variant:"outline",onClick:b,disabled:m.isPending,className:"w-full",children:[e.jsx(Jr,{className:"w-4 h-4 mr-2"}),"Create from manual entry"]})})]})]})]})}function IOn(){const{data:s,isLoading:t}=EFn(),n=LFn(),r=Fn(),{toast:a}=vi(),[i,l]=_.useState(null),{isFreePlan:o,leadSite:c}=lf();return o?e.jsx(zs,{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(Fr,{className:"w-7 h-7"})," CMAs"]}),e.jsx(POn,{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(zs,{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(Fr,{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(LOn,{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(ve,{className:"hover:shadow-md transition",children:e.jsxs(Me,{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(Oe,{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(B,{variant:"outline",size:"sm",onClick:()=>r(`/mission-control/cma/${d.id}`),children:"Open"}),d.status==="shared"&&e.jsxs(e.Fragment,{children:[e.jsx(B,{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(wr,{className:"w-4 h-4"})}),e.jsxs(B,{variant:"secondary",size:"sm",onClick:()=>l(d),children:[e.jsx(ln,{className:"w-4 h-4 mr-1"}),"Send"]})]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:async()=>{await Xi("Delete this CMA?")&&n.mutate(d.id)},children:e.jsx(Sn,{className:"w-4 h-4"})})]})]})},d.id)})}):e.jsx(ve,{children:e.jsx(Me,{className:"py-12 text-center text-muted-foreground",children:"No CMAs yet. Start one above."})}),i&&e.jsx(XYt,{open:!!i,onOpenChange:d=>!d&&l(null),cma:i})]})})}function DOn(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 E2t(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 ROn({subject:s,comps:t,radiusMiles:n,onMarkerClick:r}){const a=_.useRef(null),i=_.useRef(null),l=_.useRef([]),[o,c]=_.useState(null);_.useEffect(()=>{let u=!1;return(async()=>{const{data:h}=await q.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();!u&&(h!=null&&h.value)&&c(h.value)})(),()=>{u=!0}},[]);const d=_.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 _.useEffect(()=>{if(!o||!a.current||i.current||!d)return;Id.accessToken=o;const u=new Id.Map({container:a.current,style:"mapbox://styles/mapbox/light-v11",center:[d.lng,d.lat],zoom:12});return u.addControl(new Id.NavigationControl({showCompass:!1}),"top-right"),u.on("load",()=>{u.addSource("radius",{type:"geojson",data:E2t(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]),_.useEffect(()=>{const u=i.current;if(!u||!d)return;const h=()=>{const m=u.getSource("radius");m&&m.setData(E2t(d.lat,d.lng,n))};u.isStyleLoaded()?h():u.once("load",h)},[n,d]),_.useEffect(()=>{const u=i.current;if(!u||!d)return;l.current.forEach(v=>v.remove()),l.current=[];const h=document.createElement("div");h.style.cssText=` width: 28px; height: 28px; border-radius: 50%; background: hsl(222 47% 11%); border: 3px solid white; box-shadow: 0 4px 12px rgba(0,0,0,0.3); display: flex; align-items: center; justify-content: center; color: white; font-size: 12px; font-weight: 700; `,h.textContent="★";const m=new Id.Marker({element:h}).setLngLat([d.lng,d.lat]).setPopup(new Id.Popup({offset:18}).setHTML(`Subject
${s.address??""}`)).addTo(u);l.current.push(m);const p=new Id.LngLatBounds;p.extend([d.lng,d.lat]),t.forEach((v,g)=>{const b=Number(v.latitude),j=Number(v.longitude);if(!Number.isFinite(b)||!Number.isFinite(j))return;const S=DOn(v.status),C=document.createElement("div");C.style.cssText="width:22px;height:22px;";const E=document.createElement("div");E.style.cssText=` width: 22px; height: 22px; border-radius: 50%; background: ${S}; border: 2px solid white; box-shadow: 0 2px 6px rgba(0,0,0,0.25); cursor: pointer; opacity: ${v.selected===!1?.4:1}; transition: transform 0.15s; transform-origin: center; `,E.onmouseenter=()=>{E.style.transform="scale(1.25)"},E.onmouseleave=()=>{E.style.transform="scale(1)"},r&&(E.onclick=()=>r(g)),C.appendChild(E);const P=v.soldPrice||v.price,M=new Id.Popup({offset:14}).setHTML(`
${v.address??""}
${v.status??""}`+(P?` · $${P.toLocaleString()}`:"")+"
"),I=new Id.Marker({element:C}).setLngLat([j,b]).setPopup(M).addTo(u);l.current.push(I),p.extend([j,b])});const y=n*1.60934/110.574;p.extend([d.lng,d.lat+y]),p.extend([d.lng,d.lat-y]);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 s_=null;function JYt(){if(s_)return s_;try{const s=document.createElement("canvas"),t=s.getContext("webgl2")||s.getContext("webgl");if(!t)return s_={canRunVirtualBg:!1,reason:"WebGL is not supported on this device"},s_;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 s_={canRunVirtualBg:!1,reason:"Your device uses a software renderer which may cause lag",renderer:r},s_;const o=performance;return o.memory&&o.memory.jsHeapSizeLimit<256*1024*1024?(s_={canRunVirtualBg:!1,reason:"Limited device memory detected",renderer:r},s_):navigator.hardwareConcurrency&&navigator.hardwareConcurrency<2?(s_={canRunVirtualBg:!1,reason:"Single-core device detected — virtual backgrounds may cause lag",renderer:r},s_):(s_={canRunVirtualBg:!0,renderer:r},s_)}catch{return s_={canRunVirtualBg:!0},s_}}const FOn=[{type:"none",label:"Off"},{type:"blur",label:"Blur"}];function OOn({value:s,onChange:t,isLoading:n=!1,disabled:r=!1,className:a}){const i=_.useRef(null),[l,o]=_.useState(!1),[c,d]=_.useState(null),[u]=_.useState(()=>JYt()),h=!u.canRunVirtualBg,{data:m=[],refetch:p}=at({queryKey:["video-backgrounds"],queryFn:async()=>{const{data:{user:j}}=await q.auth.getUser();if(!j)return[];const{data:S,error:C}=await q.from("video_backgrounds").select("*").eq("is_active",!0).order("sort_order",{ascending:!0});return C?(console.error("Failed to load backgrounds:",C),[]):(S||[]).map(E=>({...E,__ownerId:j.id}))}}),f=m.map(j=>({type:"image",label:j.name,imageUrl:j.image_url,thumbnail:j.thumbnail_url||j.image_url,id:j.id,deletable:!j.is_stock&&j.user_id===j.__ownerId})),y=[...FOn,...f],v=j=>j.type!==s.type?!1:j.type==="image"?j.imageUrl===s.imageUrl:!0,g=async j=>{if(!(!j.id||!j.imageUrl)&&window.confirm(`Delete the background "${j.label}"? This can't be undone.`)){d(j.id);try{const{error:S}=await q.from("video_backgrounds").delete().eq("id",j.id);if(S)throw S;const C="/video-backgrounds/",E=j.imageUrl.indexOf(C);if(E!==-1){const P=decodeURIComponent(j.imageUrl.slice(E+C.length).split("?")[0]);await q.storage.from("video-backgrounds").remove([P])}s.type==="image"&&s.imageUrl===j.imageUrl&&t({type:"none",mirror:s.mirror}),await p(),se.success("Background deleted")}catch(S){console.error("Delete background error:",S),se.error((S==null?void 0:S.message)||"Failed to delete background")}finally{d(null)}}},b=async j=>{var C;const S=(C=j.target.files)==null?void 0:C[0];if(S){if(!S.type.startsWith("image/")){se.error("Please select an image file");return}if(S.size>5*1024*1024){se.error("Image must be under 5MB");return}o(!0);try{const{data:{user:E}}=await q.auth.getUser();if(!E)throw new Error("Not authenticated");const P=S.name.split(".").pop()||"jpg",M=`${E.id}/${crypto.randomUUID()}.${P}`,{error:I}=await q.storage.from("video-backgrounds").upload(M,S,{contentType:S.type});if(I)throw I;const{data:D}=q.storage.from("video-backgrounds").getPublicUrl(M),O=D.publicUrl,{error:V}=await q.from("video_backgrounds").insert({name:S.name.replace(/\.[^.]+$/,""),image_url:O,thumbnail_url:O,category:"custom",is_stock:!1,user_id:E.id});if(V)throw V;await p(),t({type:"image",imageUrl:O,blurRadius:15}),se.success("Background uploaded!")}catch(E){console.error("Upload error:",E),se.error("Failed to upload background")}finally{o(!1),i.current&&(i.current.value="")}}};return e.jsxs("div",{className:At("flex flex-col gap-1",a),children:[h&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-amber-600 bg-amber-50 dark:bg-amber-950/30 dark:text-amber-400 rounded px-2 py-1",children:[e.jsx(xl,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{children:u.reason||"Virtual backgrounds may cause lag on this device"})]}),e.jsxs("div",{className:"flex items-center gap-2 overflow-x-auto py-2 px-1 scrollbar-none",children:[e.jsx("span",{className:"text-xs text-muted-foreground whitespace-nowrap mr-1 font-medium",children:"Background:"}),n&&e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(Ct,{className:"h-3 w-3 animate-spin"}),e.jsx("span",{children:"Loading…"})]}),y.map((j,S)=>{const C=v(j);return e.jsxs("div",{className:"relative flex-shrink-0 group",children:[e.jsxs("button",{type:"button",disabled:r,onClick:()=>t({type:j.type,imageUrl:j.imageUrl,blurRadius:15,mirror:s.mirror}),className:At("flex-shrink-0 flex flex-col items-center gap-0.5 rounded-lg border-2 p-1 transition-all","hover:border-primary/50 focus:outline-none focus:ring-2 focus:ring-primary/30",C?"border-primary bg-primary/10":"border-transparent bg-muted/50",r&&"opacity-50 cursor-not-allowed"),children:[e.jsxs("div",{className:"w-12 h-8 rounded flex items-center justify-center overflow-hidden bg-muted",children:[j.type==="none"&&e.jsx(VO,{className:"h-4 w-4 text-muted-foreground"}),j.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"})}),j.type==="image"&&j.thumbnail&&e.jsx("img",{src:j.thumbnail,alt:j.label,className:"w-full h-full object-cover"})]}),e.jsx("span",{className:"text-[10px] text-muted-foreground truncate max-w-14",children:j.label})]}),j.deletable&&e.jsx("button",{type:"button","aria-label":`Delete background ${j.label}`,disabled:r||c===j.id,onClick:E=>{E.stopPropagation(),g(j)},className:At("absolute -top-1 -right-1 h-5 w-5 rounded-full bg-background border shadow-sm","flex items-center justify-center text-muted-foreground hover:text-destructive hover:border-destructive","opacity-100 sm:opacity-0 sm:group-hover:opacity-100 focus:opacity-100 transition-opacity"),children:c===j.id?e.jsx(Ct,{className:"h-3 w-3 animate-spin"}):e.jsx(Qn,{className:"h-3 w-3"})})]},`${j.type}-${j.imageUrl||S}`)}),e.jsxs("button",{type:"button",disabled:r||l,onClick:()=>{var j;return(j=i.current)==null?void 0:j.click()},className:At("flex-shrink-0 flex flex-col items-center gap-0.5 rounded-lg border-2 border-dashed p-1 transition-all","hover:border-primary/50 focus:outline-none focus:ring-2 focus:ring-primary/30","border-muted-foreground/30 bg-muted/30",(r||l)&&"opacity-50 cursor-not-allowed"),children:[e.jsx("div",{className:"w-12 h-8 rounded flex items-center justify-center",children:l?e.jsx(Ct,{className:"h-4 w-4 animate-spin text-muted-foreground"}):e.jsx(rn,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:l?"Uploading":"Custom"})]}),e.jsx("input",{ref:i,type:"file",accept:"image/*",className:"hidden",onChange:b}),e.jsxs("button",{type:"button",disabled:r,onClick:()=>t({...s,mirror:!s.mirror}),className:At("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(TQ,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:"Mirror"})]})]})]})}var gG=typeof self<"u"?self:{};function eZt(s,t){e:{for(var n=["CLOSURE_FLAGS"],r=gG,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 sZt(s){gG.setTimeout(()=>{throw s},0)}var yWe,qOn=eZt(610401301,!1),M2t=eZt(748402147,!0);function P2t(){var s=gG.navigator;return s&&(s=s.userAgent)?s:""}const L2t=gG.navigator;function QIe(s){return QIe[" "](s),s}yWe=L2t&&L2t.userAgentData||null,QIe[" "]=function(){};const nZt={};let CX=null;function $On(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 rZt(){if(!CX){CX={};var s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split(""),t=["+/=","+/","-_=","-_.","-_"];for(let n=0;n<5;n++){const r=s.concat(t[n].split(""));nZt[n]=r;for(let a=0;a0)&&(P2t().indexOf("Trident")!=-1||P2t().indexOf("MSIE")!=-1))&&typeof btoa=="function";const I2t=/[-_.]/g,HOn={"-":"+",_:"/",".":"="};function GOn(s){return HOn[s]||""}function iZt(s){if(!aZt)return $On(s);s=I2t.test(s)?s.replace(I2t,GOn):s,s=atob(s);const t=new Uint8Array(s.length);for(let n=0;n=t||(n[s]=r+1,lZt(s=Error(),"incident"),sZt(s))}}function HW(){return typeof BigInt=="function"}var GW=typeof Symbol=="function"&&typeof Symbol()=="symbol";function MC(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 YOn=MC("jas",void 0,!0),D2t=MC(void 0,"0di"),fZ=MC(void 0,"1oa"),wj=MC(void 0,Symbol()),ZOn=MC(void 0,"0ub"),XOn=MC(void 0,"0ubs"),bWe=MC(void 0,"0ubsb"),QOn=MC(void 0,"0actk"),bG=MC("m_m","Pa",!0),R2t=MC();const cZt={Ga:{value:0,configurable:!0,writable:!0,enumerable:!1}},dZt=Object.defineProperties,Go=GW?YOn:"Ga";var oz;const F2t=[];function Rae(s,t){GW||Go in s||dZt(s,cZt),s[Go]|=t}function I0(s,t){GW||Go in s||dZt(s,cZt),s[Go]=t}function Fae(s){return Rae(s,34),s}function fse(s){return Rae(s,8192),s}I0(F2t,7),oz=Object.freeze(F2t);var _G={};function Lj(s,t){return t===void 0?s.h!==x9&&!!(2&(0|s.v[Go])):!!(2&t)&&s.h!==x9}const x9={};function Tnt(s,t){if(s!=null){if(typeof s=="string")s=s?new sC(s,yG):f9();else if(s.constructor!==sC)if(Ant(s))s=s.length?new sC(new Uint8Array(s),yG):f9();else{if(!t)throw Error();s=void 0}}return s}let O2t=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 JOn=Object.freeze({});function uZt(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"),z2t=JIe(s=>typeof s=="string"),t7n=JIe(s=>typeof s=="boolean"),e8e=typeof gG.BigInt=="function"&&typeof gG.BigInt(0)=="bigint";function jj(s){var t=s;if(z2t(t)){if(!/^\s*(?:-?[1-9]\d*|0)?\s*$/.test(t))throw Error(String(t))}else if(e7n(t)&&!Number.isSafeInteger(t))throw Error(String(t));return e8e?BigInt(s):s=t7n(s)?s?"1":"0":z2t(s)?s.trim()||"0":String(s)}var _We=JIe(s=>e8e?s>=n7n&&s<=a7n:s[0]==="-"?B2t(s,s7n):B2t(s,r7n));const s7n=Number.MIN_SAFE_INTEGER.toString(),n7n=e8e?BigInt(Number.MIN_SAFE_INTEGER):void 0,r7n=Number.MAX_SAFE_INTEGER.toString(),a7n=e8e?BigInt(Number.MAX_SAFE_INTEGER):void 0;function B2t(s,t){if(s.length>t.length)return!1;if(s.lengtha)return!1;if(r>>0;Af=t,Tg=(s-t)/4294967296>>>0}function wG(s){if(s<0){U2t(-s);const[t,n]=Lnt(Af,Tg);Af=t>>>0,Tg=n>>>0}else U2t(s)}function Mnt(s){const t=o7n||(o7n=new DataView(new ArrayBuffer(8)));t.setFloat32(0,+s,!0),Tg=0,Af=t.getUint32(0,!0)}function mZt(s,t){const n=4294967296*t+(s>>>0);return Number.isSafeInteger(n)?n:xse(s,t)}function l7n(s,t){return jj(HW()?BigInt.asUintN(64,(BigInt(t>>>0)<>>0)):xse(s,t))}function pZt(s,t){return HW()?jj(BigInt.asIntN(64,(BigInt.asUintN(32,BigInt(t))<>>=0,(t>>>=0)<=2097151)var n=""+(4294967296*t+s);else HW()?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+q2t(n)+q2t(s));return n}function q2t(s){return s=String(s),"0000000".slice(s.length)+s}function Pnt(s,t){if(2147483648&t)if(HW())s=""+(BigInt(0|t)<>>0));else{const[n,r]=Lnt(s,t);s="-"+xse(n,r)}else s=xse(s,t);return s}function t8e(s){if(s.length<16)wG(Number(s));else if(HW())s=BigInt(s),Af=Number(s&BigInt(4294967295))>>>0,Tg=Number(s>>BigInt(32)&BigInt(4294967295));else{const t=+(s[0]==="-");Tg=Af=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));Tg*=1e6,Af=1e6*Af+i,Af>=4294967296&&(Tg+=Math.trunc(Af/4294967296),Tg>>>=0,Af>>>=0)}if(t){const[r,a]=Lnt(Af,Tg);Af=r,Tg=a}}}function Lnt(s,t){return t=~t,s?s=1+~s:t+=1,[s,t]}function jS(s){return Array.prototype.slice.call(s)}const Oae=typeof BigInt=="function"?BigInt.asIntN:void 0,c7n=typeof BigInt=="function"?BigInt.asUintN:void 0,g9=Number.isSafeInteger,s8e=Number.isFinite,jG=Math.trunc,d7n=jj(0);function AX(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 I4(s){return s==null||typeof s=="number"?s:s==="NaN"||s==="Infinity"||s==="-Infinity"?Number(s):void 0}function gse(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 fZt(s){return s==null||typeof s=="boolean"?s:typeof s=="number"?!!s:void 0}const u7n=/^-?([1-9][0-9]*|0)(\.[0-9]+)?$/;function zae(s){switch(typeof s){case"bigint":return!0;case"number":return s8e(s);case"string":return u7n.test(s);default:return!1}}function KW(s){if(s==null)return s;if(typeof s=="string"&&s)s=+s;else if(typeof s!="number")return;return s8e(s)?0|s:void 0}function xZt(s){if(s==null)return s;if(typeof s=="string"&&s)s=+s;else if(typeof s!="number")return;return s8e(s)?s>>>0:void 0}function gZt(s){const t=s.length;return(s[0]==="-"?t<20||t===20&&s<="-9223372036854775808":t<19||t===19&&s<="9223372036854775807")?s:(t8e(s),Pnt(Af,Tg))}function Int(s){if(s=jG(s),!g9(s)){wG(s);var t=Af,n=Tg;(s=2147483648&n)&&(n=~n>>>0,(t=1+~t>>>0)==0&&(n=n+1>>>0)),s=typeof(t=mZt(t,n))=="number"?s?-t:t:s?"-"+t:t}return s}function yZt(s){var t=jG(Number(s));return g9(t)?String(t):((t=s.indexOf("."))!==-1&&(s=s.substring(0,t)),gZt(s))}function vZt(s){var t=jG(Number(s));return g9(t)?jj(t):((t=s.indexOf("."))!==-1&&(s=s.substring(0,t)),HW()?jj(Oae(64,BigInt(s))):jj(gZt(s)))}function bZt(s){return g9(s)?s=jj(Int(s)):(s=jG(s),g9(s)?s=String(s):(wG(s),s=Pnt(Af,Tg)),s=jj(s)),s}function OTe(s){const t=typeof s;return s==null?s:t==="bigint"?jj(Oae(64,s)):zae(s)?t==="string"?vZt(s):bZt(s):void 0}function _Zt(s){if(typeof s!="string")throw Error();return s}function Bae(s){if(s!=null&&typeof s!="string")throw Error();return s}function kv(s){return s==null||typeof s=="string"?s:void 0}function Dnt(s,t,n,r){return s!=null&&s[bG]===_G?s:Array.isArray(s)?((r=(n=0|s[Go])|32&r|2&r)!==n&&I0(s,r),new t(s)):(n?2&r?((s=t[D2t])||(Fae((s=new t).v),s=t[D2t]=s),t=s):t=new t:t=void 0,t)}function h7n(s,t,n){if(t)e:{if(!zae(t=s))throw vWe("int64");switch(typeof t){case"string":t=vZt(t);break e;case"bigint":t=jj(Oae(64,t));break e;default:t=bZt(t)}}else t=OTe(s);return(s=t)==null?n?d7n:void 0:s}const m7n={};let p7n=function(){try{return QIe(new class extends Map{constructor(){super()}}),!1}catch{return!0}}(),lze=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 f7n=p7n?(Object.setPrototypeOf(lze.prototype,Map.prototype),Object.defineProperties(lze.prototype,{size:{value:0,configurable:!0,enumerable:!0,writable:!0}}),lze):class extends Map{constructor(){super()}};function $2t(s){return s}function cze(s){if(2&s.J)throw Error("Cannot mutate an immutable Map")}var SE=class extends f7n{constructor(s,t,n=$2t,r=$2t){super(),this.J=0|s[Go],this.K=t,this.S=n,this.fa=this.K?x7n:r;for(let a=0;a{s.call(t,a.get(r),r,a)}):super.forEach(s,t)}set(s,t){return cze(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 x7n(s,t,n,r,a,i){return s=Dnt(s,r,n,i),a&&(s=Fnt(s)),s}function g7n(s){return[s,this.get(s)]}let y7n;function V2t(){return y7n||(y7n=new SE(Fae([]),void 0,void 0,void 0,m7n))}function n8e(s){return wj?s[wj]:void 0}function zTe(s,t){for(const n in s)!isNaN(n)&&t(s,+n,s[n])}SE.prototype.toJSON=void 0;var wWe=class{};const v7n={Ka:!0};function b7n(s,t){t<100||vG(XOn,1)}function r8e(s,t,n,r){const a=r!==void 0;r=!!r;var i,l=wj;!a&&GW&&l&&(i=s[l])&&zTe(i,b7n),l=[];var o=s.length;let c;i=4294967295;let d=!1;const u=!!(64&t),h=u?128&t?0:-1:void 0;1&t||(c=o&&s[o-1],c!=null&&typeof c=="object"&&c.constructor===Object?i=--o:c=void 0,!u||128&t||a||(d=!0,i=i-h+h)),t=void 0;for(var m=0;m=i){const f=m-h;(t??(t={}))[f]=p}else l[m]=p}if(c)for(let p in c){if((o=c[p])==null||(o=n(o,r))==null)continue;let f;m=+p,u&&!Number.isNaN(m)&&(f=m+h){f[v]=jS(g)}),f.da=p.da,f}(s)),l}function _7n(s){return s[0]=yse(s[0]),s[1]=yse(s[1]),s}function yse(s){switch(typeof s){case"number":return Number.isFinite(s)?s:""+s;case"bigint":return _We(s)?Number(s):""+s;case"boolean":return s?1:0;case"object":if(Array.isArray(s)){var t=0|s[Go];return s.length===0&&1&t?void 0:r8e(s,t,yse)}if(s!=null&&s[bG]===_G)return wZt(s);if(s instanceof sC){if((t=s.g)==null)s="";else if(typeof t=="string")s=t;else{if(aZt){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 SE?s=s.size!==0?s.V(_7n):void 0:void 0}return s}let w7n,j7n;function wZt(s){return r8e(s=s.v,0|s[Go],yse)}function E7(s,t){return jZt(s,t[0],t[1])}function jZt(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[Go],M2t&&1&a)throw Error("rfarr");if(2048&a&&!(2&a)&&function(){if(M2t)throw Error("carr");vG(QOn,5)}(),256&a)throw Error("farr");if(64&a)return(a|r)!==a&&I0(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 I0(s,64|a|r),s}function N7n(s,t){if(typeof s!="object")return s;if(Array.isArray(s)){var n=0|s[Go];return s.length===0&&1&n?void 0:H2t(s,n,t)}if(s!=null&&s[bG]===_G)return G2t(s);if(s instanceof SE){if(2&(t=s.J))return s;if(!s.size)return;if(n=Fae(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 lm(s,t,n,r){XW(s),E0(s=s.v,0|s[Go],t,n,r)}function E0(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[Go]))>>14&1023||536870912)?r!=null&&(s[l+(a?0:-1)]={[n]:r}):s[i]=r),t)}function SF(){return JOn===void 0?2:4}function CF(s,t,n,r,a){let i=s.v,l=0|i[Go];r=Lj(s,l)?1:r,a=!!a||r===3,r===2&&ZW(s)&&(i=s.v,l=0|i[Go]);let o=(s=znt(i,t))===oz?7:0|s[Go],c=Bnt(o,l);var d=!(4&c);if(d){4&c&&(s=jS(s),o=0,c=M7(c,l),l=E0(i,l,t,s));let u=0,h=0;for(;u{const o=Dnt(l,n,!1,t);return i=o!==l&&o!=null,o}))!=null)return i&&!Lj(r)&&lz(s,t),r}function Gu(s,t,n,r){let a=s.v,i=0|a[Go];if((t=EZt(a,i,t,n,r))==null)return t;if(i=0|a[Go],!Lj(s,i)){const l=Fnt(t);l!==t&&(ZW(s)&&(a=s.v,i=0|a[Go]),i=E0(a,i,n,t=l,r),lz(a,i))}return t}function TZt(s,t,n,r,a,i,l,o){var c=Lj(s,n);i=c?1:i,l=!!l||i===3,c=o&&!c,(i===2||c)&&ZW(s)&&(n=0|(t=s.v)[Go]);var d=(s=znt(t,a))===oz?7:0|s[Go],u=Bnt(d,n);if(o=!(4&u)){var h=s,m=n;const p=!!(2&u);p&&(m|=2);let f=!p,y=!0,v=0,g=0;for(;v32)for(a|=(127&n)>>4,i=3;i<32&&128&n;i+=7)n=l[o++],a|=(127&n)<>>0,a>>>0);throw Error()}function Wnt(s){let t=0,n=s.g;const r=n+10,a=s.h;for(;n>>0}function UTe(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],P7(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 k7n(s){return UP(s)}function P7(s,t){if(s.g=t,t>s.l)throw Error()}function PZt(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 LZt(s,t){if(t==0)return f9();var n=PZt(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):i7n?s.slice(n,t):new Uint8Array(s.subarray(n,t))),n.length==0?f9():new sC(n,yG)}var W2t=[];function IZt(s,t,n,r){if(qTe.length){const a=qTe.pop();return a.o(r),a.g.init(s,t,n,r),a}return new S7n(s,t,n,r)}function DZt(s){s.g.clear(),s.l=-1,s.h=-1,qTe.length<100&&qTe.push(s)}function RZt(s){var t=s.g;if(t.g==t.l)return!1;s.m=s.g.g;var n=pC(s.g);if(t=n>>>3,!((n&=7)>=0&&n<=5)||t<1)throw Error();return s.l=t,s.h=n,!0}function Q4e(s){switch(s.h){case 0:s.h!=0?Q4e(s):Wnt(s.g);break;case 1:P7(s=s.g,s.g+8);break;case 2:if(s.h!=2)Q4e(s);else{var t=pC(s.g);P7(s=s.g,s.g+t)}break;case 5:P7(s=s.g,s.g+4);break;case 3:for(t=s.l;;){if(!RZt(s))throw Error();if(s.h==4){if(s.l!=t)throw Error();break}Q4e(s)}break;default:throw Error()}}function Uae(s,t,n){const r=s.g.l;var a=pC(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 Knt(s){var t=pC(s.g),n=PZt(s=s.g,t);if(s=s.h,zOn){var r,a=s;(r=oze)||(r=oze=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(Kce===void 0){try{r.decode(new Uint8Array([128]))}catch{}try{r.decode(new Uint8Array([97])),Kce=!0}catch{Kce=!1}}throw!Kce&&(oze=void 0),o}}else{t=(i=n)+t,n=[];let o,c=null;for(;i=t?SI():(o=s[i++],l<194||(192&o)!=128?(i--,SI()):n.push((31&l)<<6|63&o)):l<240?i>=t-1?SI():(o=s[i++],(192&o)!=128||l===224&&o<160||l===237&&o>=160||(192&(r=s[i++]))!=128?(i--,SI()):n.push((15&l)<<12|(63&o)<<6|63&r)):l<=244?i>=t-2?SI():(o=s[i++],(192&o)!=128||o-144+(l<<28)>>30||(192&(r=s[i++]))!=128||(192&(a=s[i++]))!=128?(i--,SI()):(l=(7&l)<<18|(63&o)<<12|(63&r)<<6|63&a,l-=65536,n.push(55296+(l>>10&1023),56320+(1023&l)))):SI(),n.length>=8192&&(c=T2t(c,n),n.length=0)}i=T2t(c,n)}return i}function FZt(s){const t=pC(s.g);return LZt(s.g,t)}function i8e(s,t,n){var r=pC(s.g);for(r=s.g.g+r;s.g.g>>0,this.g=t>>>0}};let C7n;function Y2t(s){return s?/^-?\d+$/.test(s)?(t8e(s),new NWe(Af,Tg)):null:A7n||(A7n=new NWe(0,0))}var NWe=class{constructor(s,t){this.h=s>>>0,this.g=t>>>0}};let A7n;function F$(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 JW(s,t){for(;t>127;)s.g.push(127&t|128),t>>>=7;s.g.push(t)}function o8e(s,t){if(t>=0)JW(s,t);else{for(let n=0;n<9;n++)s.g.push(127&t|128),t>>=7;s.g.push(1)}}function Ynt(s){var t=Af;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 NG(s,t){t.length!==0&&(s.l.push(t),s.h+=t.length)}function $N(s,t,n){JW(s.g,8*t+n)}function Znt(s,t){return $N(s,t,2),t=s.g.end(),NG(s,t),t.push(s.h),t}function Xnt(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 l8e(s,t,n){$N(s,t,2),JW(s.g,n.length),NG(s,s.g.end()),NG(s,n)}function $Te(s,t,n,r){n!=null&&(t=Znt(s,t),r(n,s),Xnt(s,t))}function PC(){const s=class{constructor(){throw Error()}};return Object.setPrototypeOf(s,s.prototype),s}var Qnt=PC(),OZt=PC(),Jnt=PC(),ert=PC(),trt=PC(),zZt=PC(),E7n=PC(),c8e=PC(),BZt=PC(),UZt=PC();function LC(s,t,n){var r=s.v;wj&&wj in r&&(r=r[wj])&&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 Wo=class{constructor(s,t){this.v=jZt(s,t,void 0,2048)}toJSON(){return wZt(this)}j(){var a;var s=d9n,t=this.v,n=s.g,r=wj;if(GW&&r&&((a=t[r])==null?void 0:a[n])!=null&&vG(ZOn,3),t=s.g,R2t&&wj&&R2t===void 0&&(r=(n=this.v)[wj])&&(r=r.da))try{r(n,t,v7n)}catch(i){sZt(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[Go];return Ont(this,s,t)?Rnt(this,s,!0):new this.constructor(YW(s,t,!1))}};Wo.prototype[bG]=_G,Wo.prototype.toString=function(){return this.v.toString()};var eK=class{constructor(s,t,n){this.g=s,this.h=t,s=Qnt,this.l=!!s&&n===s||!1}};function d8e(s,t){return new eK(s,t,Qnt)}function qZt(s,t,n,r,a){$Te(s,n,GZt(t,r),a)}const T7n=d8e(function(s,t,n,r,a){return s.h===2&&(Uae(s,$nt(t,r,n),a),!0)},qZt),M7n=d8e(function(s,t,n,r,a){return s.h===2&&(Uae(s,$nt(t,r,n),a),!0)},qZt);var u8e=Symbol(),h8e=Symbol(),kWe=Symbol(),Z2t=Symbol(),X2t=Symbol();let $Zt,VZt;function cz(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 w7n||(w7n=[0,void 0,!0]);case"number":return h>0?void 0:h===0?j7n||(j7n=[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,$Zt??($Zt=i),VZt??(VZt=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 nrt(s,t,n,r,a){const i=n.g;let l,o;s[t]=(c,d,u)=>i(c,d,u,o||(o=cz(h8e,srt,nrt,r).T),l||(l=rrt(r)),a)}function rrt(s){let t=s[kWe];if(t!=null)return t;const n=cz(h8e,srt,nrt,s);return t=n.ma?(r,a)=>$Zt(r,a,n):(r,a)=>{for(;RZt(a)&&a.h!=4;){var i=a.l,l=n[i];if(l==null){var o=n.ba;o&&(o=o[i])&&(o=L7n(o))!=null&&(l=n[i]=o)}if(l==null||!l(a,r,i)){if(l=(o=a).m,Q4e(o),o.ha)var c=void 0;else c=o.g.g-l,o.g.g=l,c=LZt(o.g,c);l=void 0,o=r,c&&((l=o[wj]??(o[wj]=new wWe))[i]??(l[i]=[])).push(c)}}return(r=n8e(r))&&(r.da=n.qa[X2t]),!0},s[kWe]=t,s[X2t]=P7n.bind(s),t}function P7n(s,t,n,r){var a=this[h8e];const i=this[kWe],l=E7(void 0,a.T),o=n8e(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=IZt(p);try{c=!0,i(l,u)}finally{DZt(u)}}else r==null||r(s,h,m)},t==null)zTe(o,a);else if(o!=null){const u=o[t];u&&a(o,t,u)}if(c){let u=0|s[Go];if(2&u&&2048&u&&!(n!=null&&n.Ka))throw Error();const h=WW(u),m=(p,f)=>{if(CE(s,p,h)!=null){if((n==null?void 0:n.Qa)===1)return;throw Error()}f!=null&&(u=E0(s,u,p,f,h)),delete o[p]};t==null?uZt(l,0|l[Go],(p,f)=>{m(p,f)}):m(t,CE(l,t,h))}}}}function L7n(s){const t=(s=HZt(s))[0].g;if(s=s[1]){const n=rrt(s),r=cz(h8e,srt,nrt,s).T;return(a,i,l)=>t(a,i,l,r,n)}return t}function m8e(s,t,n){s[t]=n.h}function p8e(s,t,n,r){let a,i;const l=n.h;s[t]=(o,c,d)=>l(o,c,d,i||(i=cz(u8e,m8e,p8e,r).T),a||(a=WZt(r)))}function WZt(s){let t=s[Z2t];if(!t){const n=cz(u8e,m8e,p8e,s);t=(r,a)=>KZt(r,a,n),s[Z2t]=t}return t}function KZt(s,t,n){uZt(s,0|s[Go],(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=HZt(c))[0].h;if(c=c[1]){const u=WZt(c),h=cz(u8e,m8e,p8e,c).T;c=l.ma?VZt(h,u):(m,p,f)=>d(m,p,f,h,u)}else c=d;return l[o]=c}}(n,r);i?i(t,a,r):r<500||vG(bWe,3)}}),(s=n8e(s))&&zTe(s,(r,a,i)=>{for(NG(t,t.g.end()),r=0;r{$Te(s,n,E7([l,i],r),a)});else if(Array.isArray(t)){for(let i=0;i>BigInt(32))),F$(s.g,n.h,n.g);break;default:n=Y2t(t),F$(s.g,n.h,n.g)}}function XZt(s,t,n){(t=KW(t))!=null&&t!=null&&($N(s,n,0),o8e(s.g,t))}function QZt(s,t,n){(t=fZt(t))!=null&&($N(s,n,0),s.g.g.push(t?1:0))}function JZt(s,t,n){(t=kv(t))!=null&&l8e(s,n,tZt(t))}function eXt(s,t,n,r,a){$Te(s,n,GZt(t,r),a)}function tXt(s,t,n){(t=t==null||typeof t=="string"||t instanceof sC?t:void 0)!=null&&l8e(s,n,Hnt(t,!0).buffer)}function sXt(s,t,n){(t=xZt(t))!=null&&t!=null&&($N(s,n,0),JW(s.g,t))}function nXt(s,t,n){return(s.h===5||s.h===2)&&(t=QW(t,0|t[Go],n),s.h==2?i8e(s,UTe,t):t.push(UTe(s.g)),!0)}var Dg=C1(function(s,t,n){return s.h===5&&(A1(t,n,UTe(s.g)),!0)},YZt,c8e),R7n=sK(nXt,function(s,t,n){if((t=tK(I4,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"))||(t8e(r),r=xse(Af,Tg))),r;if(a==="number")return(r=jG(r))>=0&&g9(r)||(wG(r),r=mZt(Af,Tg)),r}}(t),t!=null&&(typeof t=="string"&&K2t(t),t!=null))switch($N(s,n,0),typeof t){case"number":s=s.g,wG(t),F$(s,Af,Tg);break;case"bigint":n=BigInt.asUintN(64,t),n=new jWe(Number(n&BigInt(4294967295)),Number(n>>BigInt(32))),F$(s.g,n.h,n.g);break;default:n=K2t(t),F$(s.g,n.h,n.g)}},E7n),N0=C1(function(s,t,n){return s.h===0&&(A1(t,n,UP(s.g)),!0)},XZt,ert),qae=sK(function(s,t,n){return(s.h===0||s.h===2)&&(t=QW(t,0|t[Go],n),s.h==2?i8e(s,UP,t):t.push(UP(s.g)),!0)},function(s,t,n){if((t=tK(KW,t))!=null&&t.length){n=Znt(s,n);for(let r=0;r{{const i={ea:!0};r&&Object.assign(i,r),n=IZt(n,void 0,void 0,i);try{const l=new s,o=l.v;rrt(t)(o,n);var a=l}finally{DZt(n)}}return a}}function f8e(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}}}};KZt(this.v,t,cz(u8e,m8e,p8e,s)),NG(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=eNt.createPolicy("goog#html",{createHTML:r,createScript:r,createScriptURL:r})}catch{}return n}()),s=(t=hze)?t.createScriptURL(s):s,new class{constructor(n){this.g=n}toString(){return this.g+""}}(s)}function Yce(s,...t){if(t.length===0)return tNt(s[0]);let n=s[0];for(let r=0;r({index:aN(r,1)??0??-1,score:Yx(r,2)??0,categoryName:kv(Df(r,3))??""??"",displayName:kv(Df(r,4))??""??""})),headIndex:t,headName:n}}function p9n(s){const t={classifications:AE(s,Y7n,1).map(n=>{var r;return mrt(((r=Gu(n,hXt,4))==null?void 0:r.g())??[],aN(n,2)??0,kv(Df(n,3))??"")})};return function(n){return n==null?n:typeof n=="bigint"?(_We(n)?n=Number(n):(n=Oae(64,n),n=_We(n)?Number(n):String(n)),n):zae(n)?typeof n=="number"?Int(n):yZt(n):void 0}(Df(s,2,void 0,void 0,OTe))!=null&&(t.timestampMs=zXt(Df(s,2,void 0,void 0,OTe)??NZt)),t}function BXt(s){var l,o;var t=CF(s,3,I4,SF()),n=CF(s,2,KW,SF()),r=CF(s,1,kv,SF()),a=CF(s,9,kv,SF());const i={categories:[],keypoints:[]};for(let c=0;ct>127?t-256:t)}function mNt(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 pNt(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 $Xt(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 Yo(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 fNt(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]=$Xt(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 xNt(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 w5(s,t,n){s.i.simpleListeners=s.i.simpleListeners||{},s.i.simpleListeners[t]=n}function CT(s,t,n){let r=[];s.i.simpleListeners=s.i.simpleListeners||{},s.i.simpleListeners[t]=(a,i,l)=>{i?(n(r,l),r=[]):r.push(a)}}wU.forVisionTasks=function(s,t=!1){return Xce("vision",s??Yce``,t)},wU.forTextTasks=function(s,t=!1){return Xce("text",s??Yce``,t)},wU.forGenAiTasks=function(s,t=!1){return Xce("genai",s??Yce``,t)},wU.forAudioTasks=function(s,t=!1){return Xce("audio",s??Yce``,t)},wU.isSimdSupported=function(s=!1){return UXt(s)};async function x9n(s,t,n,r){return s=await(async(a,i,l,o,c)=>{if(i&&await pNt(i),!self.ModuleFactory||l&&(await pNt(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 fze(s,t){const n=Gu(s.baseOptions,VTe,1)||new VTe;typeof t=="string"?(lm(n,2,Bae(t)),lm(n,1)):t instanceof Uint8Array&&(lm(n,1,Tnt(t,!1)),lm(n,2)),Tl(s.baseOptions,0,1,n)}function gNt(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 ko(s,t){s.C=Math.max(s.C,t)}function v8e(s,t){s.B=new J_,Ij(s.B,2,"PassThroughCalculator"),rf(s.B,"free_memory"),Nu(s.B,"free_memory_unused_out"),Wf(t,"free_memory"),VN(t,s.B)}function kG(s,t){rf(s.B,t),Nu(s.B,t+"_unused_out")}function b8e(s){s.g.addBoolToStream(!0,"free_memory",s.C)}var TWe=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=Gu(this.baseOptions,VTe,1))!=null&&a.g()||(i=Gu(this.baseOptions,VTe,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=Gu(d.baseOptions,lNt,3);if(!h){var m=h=new lNt,p=new sNt;see(m,4,J4e,p)}"delegate"in u&&(u.delegate==="GPU"?(u=h,m=new q7n,see(u,2,J4e,m)):(u=h,m=new sNt,see(u,4,J4e,m))),Tl(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),fze(this,"/model.dat"),this.m(),this.L()});if(c.modelAssetBuffer instanceof Uint8Array)fze(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=>{fze(this,d),this.m(),this.L()})}return this.m(),this.L(),Promise.resolve()}L(){}ca(){let s;if(this.g.ca(t=>{s=$7n(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,gNt(this)}finishProcessing(){this.g.finishProcessing(),gNt(this)}close(){this.B=void 0,this.g.closeGraph()}};function gP(s,t){if(!s)throw Error(`Unable to obtain required WebGL resource: ${t}`);return s}TWe.prototype.close=TWe.prototype.close;class g9n{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 yNt(s,t,n){const r=s.g;if(n=gP(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 vNt(s,t){const n=s.g,r=gP(n.createVertexArray(),"Failed to create vertex array");n.bindVertexArray(r);const a=gP(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=gP(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 g9n(n,r,a,i)}function prt(s,t){if(s.g){if(t!==s.g)throw Error("Cannot change GL context once initialized")}else s.g=t}function y9n(s,t,n,r){return prt(s,t),s.h||(s.m(),s.D()),n?(s.u||(s.u=vNt(s,!0)),n=s.u):(s.A||(s.A=vNt(s,!1)),n=s.A),t.useProgram(s.h),n.bind(),s.l(),s=r(),n.g.bindVertexArray(null),s}function VXt(s,t,n){return prt(s,t),s=gP(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 HXt(s,t,n){prt(s,t),s.B||(s.B=gP(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 v9n(s){var t;(t=s.g)==null||t.bindFramebuffer(s.g.FRAMEBUFFER,null)}var GXt=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=gP(s.createProgram(),"Failed to create WebGL program"),this.X=yNt(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=yNt(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 AA(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 MWe(s){var t=AA(s,1);if(!t){if(t=AA(s,0))t=new Float32Array(t).map(r=>r/255);else{t=new Float32Array(s.width*s.height);const r=SG(s);var n=frt(s);if(HXt(n,r,WXt(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 MWe(this)}N(){return WXt(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=SG(this),a=frt(this);r.activeTexture(r.TEXTURE1),n=VXt(a,r,this.m?r.LINEAR:r.NEAREST),r.bindTexture(r.TEXTURE_2D,n);const i=KXt(this);r.texImage2D(r.TEXTURE_2D,0,i,this.width,this.height,0,r.RED,r.FLOAT,null),r.bindTexture(r.TEXTURE_2D,null),HXt(a,r,n),y9n(a,r,!1,()=>{YXt(this),r.clearColor(0,0,0,0),r.clear(r.COLOR_BUFFER_BIT),r.drawArrays(r.TRIANGLE_FAN,0,4),PWe(this)}),v9n(a),PWe(this)}}s.push(n)}return new ty(s,this.m,this.R(),this.canvas,this.l,this.width,this.height)}close(){this.j&&SG(this).deleteTexture(AA(this,2)),bNt=-1}};ty.prototype.close=ty.prototype.close,ty.prototype.clone=ty.prototype.clone,ty.prototype.getAsWebGLTexture=ty.prototype.N,ty.prototype.getAsFloat32Array=ty.prototype.ia,ty.prototype.getAsUint8Array=ty.prototype.ja,ty.prototype.hasWebGLTexture=ty.prototype.R,ty.prototype.hasFloat32Array=ty.prototype.ka,ty.prototype.hasUint8Array=ty.prototype.Fa;var bNt=250;function US(...s){return s.map(([t,n])=>({start:t,end:n}))}const b9n=function(s){return class extends s{Ja(){this.i._registerModelResourcesGraphService()}}}((_Nt=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:qXt()?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?'),Yo(this,r||"input_audio",i=>{Yo(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){w5(this,"__graph_config__",t=>{s(t)}),Yo(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),Yo(this,r,l=>{this.i._addAudioToInputStream(this.g,t,n,l,a)})}addGpuBufferToStream(s,t,n){Yo(this,t,r=>{const[a,i]=fNt(this,s,r);this.i._addBoundTextureToStream(r,a,i,n)})}addBoolToStream(s,t,n){Yo(this,t,r=>{this.i._addBoolToInputStream(s,r,n)})}addDoubleToStream(s,t,n){Yo(this,t,r=>{this.i._addDoubleToInputStream(s,r,n)})}addFloatToStream(s,t,n){Yo(this,t,r=>{this.i._addFloatToInputStream(s,r,n)})}addIntToStream(s,t,n){Yo(this,t,r=>{this.i._addIntToInputStream(s,r,n)})}addUintToStream(s,t,n){Yo(this,t,r=>{this.i._addUintToInputStream(s,r,n)})}addStringToStream(s,t,n){Yo(this,t,r=>{Yo(this,s,a=>{this.i._addStringToInputStream(a,r,n)})})}addStringRecordToStream(s,t,n){Yo(this,t,r=>{xNt(this,Object.keys(s),a=>{xNt(this,Object.values(s),i=>{this.i._addFlatHashMapToInputStream(a,i,Object.keys(s).length,r,n)})})})}addProtoToStream(s,t,n,r){Yo(this,n,a=>{Yo(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){Yo(this,s,n=>{this.i._addEmptyPacketToInputStream(n,t)})}addBoolVectorToStream(s,t,n){Yo(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){Yo(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){Yo(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){Yo(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){Yo(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){Yo(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)Yo(this,i,l=>{this.i._addStringVectorEntry(a,l)});this.i._addStringVectorToInputStream(a,r,n)})}addBoolToInputSidePacket(s,t){Yo(this,t,n=>{this.i._addBoolToInputSidePacket(s,n)})}addDoubleToInputSidePacket(s,t){Yo(this,t,n=>{this.i._addDoubleToInputSidePacket(s,n)})}addFloatToInputSidePacket(s,t){Yo(this,t,n=>{this.i._addFloatToInputSidePacket(s,n)})}addIntToInputSidePacket(s,t){Yo(this,t,n=>{this.i._addIntToInputSidePacket(s,n)})}addUintToInputSidePacket(s,t){Yo(this,t,n=>{this.i._addUintToInputSidePacket(s,n)})}addStringToInputSidePacket(s,t){Yo(this,t,n=>{Yo(this,s,r=>{this.i._addStringToInputSidePacket(r,n)})})}addProtoToInputSidePacket(s,t,n){Yo(this,n,r=>{Yo(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){Yo(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){Yo(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){Yo(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){Yo(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){Yo(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){Yo(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)Yo(this,a,i=>{this.i._addStringVectorEntry(r,i)});this.i._addStringVectorToInputSidePacket(r,n)})}attachBoolListener(s,t){w5(this,s,t),Yo(this,s,n=>{this.i._attachBoolListener(n)})}attachBoolVectorListener(s,t){CT(this,s,t),Yo(this,s,n=>{this.i._attachBoolVectorListener(n)})}attachIntListener(s,t){w5(this,s,t),Yo(this,s,n=>{this.i._attachIntListener(n)})}attachIntVectorListener(s,t){CT(this,s,t),Yo(this,s,n=>{this.i._attachIntVectorListener(n)})}attachUintListener(s,t){w5(this,s,t),Yo(this,s,n=>{this.i._attachUintListener(n)})}attachUintVectorListener(s,t){CT(this,s,t),Yo(this,s,n=>{this.i._attachUintVectorListener(n)})}attachDoubleListener(s,t){w5(this,s,t),Yo(this,s,n=>{this.i._attachDoubleListener(n)})}attachDoubleVectorListener(s,t){CT(this,s,t),Yo(this,s,n=>{this.i._attachDoubleVectorListener(n)})}attachFloatListener(s,t){w5(this,s,t),Yo(this,s,n=>{this.i._attachFloatListener(n)})}attachFloatVectorListener(s,t){CT(this,s,t),Yo(this,s,n=>{this.i._attachFloatVectorListener(n)})}attachStringListener(s,t){w5(this,s,t),Yo(this,s,n=>{this.i._attachStringListener(n)})}attachStringVectorListener(s,t){CT(this,s,t),Yo(this,s,n=>{this.i._attachStringVectorListener(n)})}attachProtoListener(s,t,n){w5(this,s,t),Yo(this,s,r=>{this.i._attachProtoListener(r,n||!1)})}attachProtoVectorListener(s,t,n){CT(this,s,t),Yo(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?'),w5(this,s,(r,a)=>{r=new Float32Array(r.buffer,r.byteOffset,r.length/4),t(r,a)}),Yo(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 _Nt{get ga(){return this.i}pa(s,t,n){Yo(this,t,r=>{const[a,i]=fNt(this,s,r);this.ga._addBoundTextureAsImageToStream(r,a,i,n)})}Z(s,t){w5(this,s,t),Yo(this,s,n=>{this.ga._attachImageListener(n)})}aa(s,t){CT(this,s,t),Yo(this,s,n=>{this.ga._attachImageVectorListener(n)})}}));var _Nt,qS=class extends b9n{};async function zu(s,t,n){return async function(r,a,i,l){return x9n(r,a,i,l)}(s,n.canvas??(qXt()?void 0:document.createElement("canvas")),t,n)}function ZXt(s,t,n,r){if(s.U){const i=new gXt;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].");il(i,1,(a.left+a.right)/2),il(i,2,(a.top+a.bottom)/2),il(i,4,a.right-a.left),il(i,3,a.bottom-a.top)}else il(i,1,.5),il(i,2,.5),il(i,4,1),il(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(il(i,5,-Math.PI*n.rotationDegrees/180),(n==null?void 0:n.rotationDegrees)%180!=0){const[l,o]=$Xt(t);n=Yx(i,3)*o/l,a=Yx(i,4)*l/o,il(i,4,n),il(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 $S(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'.");ZXt(s,t,n,s.C+1)}function DC(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'.");ZXt(s,t,n,r)}function CG(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 ty([a],n,!1,s.g.i.canvas,s.P,i,t),r?s.clone():s}var Dj=class extends TWe{constructor(s,t,n,r){super(s),this.g=s,this.X=t,this.U=n,this.oa=r,this.P=new GXt}l(s,t=!0){if("runningMode"in s&&lm(this.baseOptions,2,gse(!!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()}};Dj.prototype.close=Dj.prototype.close;var v2=class extends Dj{constructor(s,t){super(new qS(s,t),"image_in","norm_rect_in",!1),this.j={detections:[]},Tl(s=this.h=new g8e,0,1,t=new Lx),il(this.h,2,.5),il(this.h,3,.3)}get baseOptions(){return Gu(this.h,Lx,1)}set baseOptions(s){Tl(this.h,0,1,s)}o(s){return"minDetectionConfidence"in s&&il(this.h,2,s.minDetectionConfidence??.5),"minSuppressionThreshold"in s&&il(this.h,3,s.minSuppressionThreshold??.3),this.l(s)}F(s,t){return this.j={detections:[]},$S(this,s,t),this.j}G(s,t,n){return this.j={detections:[]},DC(this,s,n,t),this.j}m(){var s=new qj;Wf(s,"image_in"),Wf(s,"norm_rect_in"),ih(s,"detections");const t=new Uj;LC(t,t9n,this.h);const n=new J_;Ij(n,2,"mediapipe.tasks.vision.face_detector.FaceDetectorGraph"),rf(n,"IMAGE:image_in"),rf(n,"NORM_RECT:norm_rect_in"),Nu(n,"DETECTIONS:detections"),n.o(t),VN(s,n),this.g.attachProtoVectorListener("detections",(r,a)=>{for(const i of r)r=pXt(i),this.j.detections.push(BXt(r));ko(this,a)}),this.g.attachEmptyPacketListener("detections",r=>{ko(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};v2.prototype.detectForVideo=v2.prototype.G,v2.prototype.detect=v2.prototype.F,v2.prototype.setOptions=v2.prototype.o,v2.createFromModelPath=async function(s,t){return zu(v2,s,{baseOptions:{modelAssetPath:t}})},v2.createFromModelBuffer=function(s,t){return zu(v2,s,{baseOptions:{modelAssetBuffer:t}})},v2.createFromOptions=function(s,t){return zu(v2,s,t)};var xrt=US([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]),grt=US([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]),yrt=US([276,283],[283,282],[282,295],[295,285],[300,293],[293,334],[334,296],[296,336]),XXt=US([474,475],[475,476],[476,477],[477,474]),vrt=US([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]),brt=US([46,53],[53,52],[52,65],[65,55],[70,63],[63,105],[105,66],[66,107]),QXt=US([469,470],[470,471],[471,472],[472,469]),_rt=US([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]),JXt=[...xrt,...grt,...yrt,...vrt,...brt,..._rt],eQt=US([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 wNt(s){s.j={faceLandmarks:[],faceBlendshapes:[],facialTransformationMatrixes:[]}}var cx=class extends Dj{constructor(s,t){super(new qS(s,t),"image_in","norm_rect",!1),this.j={faceLandmarks:[],faceBlendshapes:[],facialTransformationMatrixes:[]},this.outputFacialTransformationMatrixes=this.outputFaceBlendshapes=!1,Tl(s=this.h=new wXt,0,1,t=new Lx),this.A=new _Xt,Tl(this.h,0,3,this.A),this.u=new g8e,Tl(this.h,0,2,this.u),EE(this.u,4,1),il(this.u,2,.5),il(this.A,2,.5),il(this.h,4,.5)}get baseOptions(){return Gu(this.h,Lx,1)}set baseOptions(s){Tl(this.h,0,1,s)}o(s){return"numFaces"in s&&EE(this.u,4,s.numFaces??1),"minFaceDetectionConfidence"in s&&il(this.u,2,s.minFaceDetectionConfidence??.5),"minTrackingConfidence"in s&&il(this.h,4,s.minTrackingConfidence??.5),"minFacePresenceConfidence"in s&&il(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 wNt(this),$S(this,s,t),this.j}G(s,t,n){return wNt(this),DC(this,s,n,t),this.j}m(){var s=new qj;Wf(s,"image_in"),Wf(s,"norm_rect"),ih(s,"face_landmarks");const t=new Uj;LC(t,n9n,this.h);const n=new J_;Ij(n,2,"mediapipe.tasks.vision.face_landmarker.FaceLandmarkerGraph"),rf(n,"IMAGE:image_in"),rf(n,"NORM_RECT:norm_rect"),Nu(n,"NORM_LANDMARKS:face_landmarks"),n.o(t),VN(s,n),this.g.attachProtoVectorListener("face_landmarks",(r,a)=>{for(const i of r)r=$ae(i),this.j.faceLandmarks.push(y8e(r));ko(this,a)}),this.g.attachEmptyPacketListener("face_landmarks",r=>{ko(this,r)}),this.outputFaceBlendshapes&&(ih(s,"blendshapes"),Nu(n,"BLENDSHAPES:blendshapes"),this.g.attachProtoVectorListener("blendshapes",(r,a)=>{if(this.outputFaceBlendshapes)for(const i of r)r=x8e(i),this.j.faceBlendshapes.push(mrt(r.g()??[]));ko(this,a)}),this.g.attachEmptyPacketListener("blendshapes",r=>{ko(this,r)})),this.outputFacialTransformationMatrixes&&(ih(s,"face_geometry"),Nu(n,"FACE_GEOMETRY:face_geometry"),this.g.attachProtoVectorListener("face_geometry",(r,a)=>{if(this.outputFacialTransformationMatrixes)for(const i of r)(r=Gu(r=s9n(i),W7n,2))&&this.j.facialTransformationMatrixes.push({rows:aN(r,1)??0??0,columns:aN(r,2)??0??0,data:CF(r,3,I4,SF()).slice()??[]});ko(this,a)}),this.g.attachEmptyPacketListener("face_geometry",r=>{ko(this,r)})),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};cx.prototype.detectForVideo=cx.prototype.G,cx.prototype.detect=cx.prototype.F,cx.prototype.setOptions=cx.prototype.o,cx.createFromModelPath=function(s,t){return zu(cx,s,{baseOptions:{modelAssetPath:t}})},cx.createFromModelBuffer=function(s,t){return zu(cx,s,{baseOptions:{modelAssetBuffer:t}})},cx.createFromOptions=function(s,t){return zu(cx,s,t)},cx.FACE_LANDMARKS_LIPS=xrt,cx.FACE_LANDMARKS_LEFT_EYE=grt,cx.FACE_LANDMARKS_LEFT_EYEBROW=yrt,cx.FACE_LANDMARKS_LEFT_IRIS=XXt,cx.FACE_LANDMARKS_RIGHT_EYE=vrt,cx.FACE_LANDMARKS_RIGHT_EYEBROW=brt,cx.FACE_LANDMARKS_RIGHT_IRIS=QXt,cx.FACE_LANDMARKS_FACE_OVAL=_rt,cx.FACE_LANDMARKS_CONTOURS=JXt,cx.FACE_LANDMARKS_TESSELATION=eQt;var wrt=US([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 jNt(s){s.gestures=[],s.landmarks=[],s.worldLandmarks=[],s.handedness=[]}function NNt(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 kNt(s,t=!0){const n=[];for(const a of s){var r=x8e(a);s=[];for(const i of r.g())r=t&&aN(i,1)!=null?aN(i,1)??0:-1,s.push({score:Yx(i,2)??0,index:r,categoryName:kv(Df(i,3))??""??"",displayName:kv(Df(i,4))??""??""});n.push(s)}return n}var gw=class extends Dj{constructor(s,t){super(new qS(s,t),"image_in","norm_rect",!1),this.gestures=[],this.landmarks=[],this.worldLandmarks=[],this.handedness=[],Tl(s=this.j=new kXt,0,1,t=new Lx),this.u=new crt,Tl(this.j,0,2,this.u),this.D=new lrt,Tl(this.u,0,3,this.D),this.A=new NXt,Tl(this.u,0,2,this.A),this.h=new r9n,Tl(this.j,0,3,this.h),il(this.A,2,.5),il(this.u,4,.5),il(this.D,2,.5)}get baseOptions(){return Gu(this.j,Lx,1)}set baseOptions(s){Tl(this.j,0,1,s)}o(s){var a,i,l,o;if(EE(this.A,3,s.numHands??1),"minHandDetectionConfidence"in s&&il(this.A,2,s.minHandDetectionConfidence??.5),"minTrackingConfidence"in s&&il(this.u,4,s.minTrackingConfidence??.5),"minHandPresenceConfidence"in s&&il(this.D,2,s.minHandPresenceConfidence??.5),s.cannedGesturesClassifierOptions){var t=new UB,n=t,r=EWe(s.cannedGesturesClassifierOptions,(a=Gu(this.h,UB,3))==null?void 0:a.l());Tl(n,0,2,r),Tl(this.h,0,3,t)}else s.cannedGesturesClassifierOptions===void 0&&((i=Gu(this.h,UB,3))==null||i.g());return s.customGesturesClassifierOptions?(Tl(n=t=new UB,0,2,r=EWe(s.customGesturesClassifierOptions,(l=Gu(this.h,UB,4))==null?void 0:l.l())),Tl(this.h,0,4,t)):s.customGesturesClassifierOptions===void 0&&((o=Gu(this.h,UB,4))==null||o.g()),this.l(s)}Ha(s,t){return jNt(this),$S(this,s,t),NNt(this)}Ia(s,t,n){return jNt(this),DC(this,s,n,t),NNt(this)}m(){var s=new qj;Wf(s,"image_in"),Wf(s,"norm_rect"),ih(s,"hand_gestures"),ih(s,"hand_landmarks"),ih(s,"world_hand_landmarks"),ih(s,"handedness");const t=new Uj;LC(t,a9n,this.j);const n=new J_;Ij(n,2,"mediapipe.tasks.vision.gesture_recognizer.GestureRecognizerGraph"),rf(n,"IMAGE:image_in"),rf(n,"NORM_RECT:norm_rect"),Nu(n,"HAND_GESTURES:hand_gestures"),Nu(n,"LANDMARKS:hand_landmarks"),Nu(n,"WORLD_LANDMARKS:world_hand_landmarks"),Nu(n,"HANDEDNESS:handedness"),n.o(t),VN(s,n),this.g.attachProtoVectorListener("hand_landmarks",(r,a)=>{for(const i of r){r=$ae(i);const l=[];for(const o of AE(r,xXt,1))l.push({x:Yx(o,1)??0,y:Yx(o,2)??0,z:Yx(o,3)??0,visibility:Yx(o,4)??0});this.landmarks.push(l)}ko(this,a)}),this.g.attachEmptyPacketListener("hand_landmarks",r=>{ko(this,r)}),this.g.attachProtoVectorListener("world_hand_landmarks",(r,a)=>{for(const i of r){r=O$(i);const l=[];for(const o of AE(r,fXt,1))l.push({x:Yx(o,1)??0,y:Yx(o,2)??0,z:Yx(o,3)??0,visibility:Yx(o,4)??0});this.worldLandmarks.push(l)}ko(this,a)}),this.g.attachEmptyPacketListener("world_hand_landmarks",r=>{ko(this,r)}),this.g.attachProtoVectorListener("hand_gestures",(r,a)=>{this.gestures.push(...kNt(r,!1)),ko(this,a)}),this.g.attachEmptyPacketListener("hand_gestures",r=>{ko(this,r)}),this.g.attachProtoVectorListener("handedness",(r,a)=>{this.handedness.push(...kNt(r)),ko(this,a)}),this.g.attachEmptyPacketListener("handedness",r=>{ko(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};function SNt(s){return{landmarks:s.landmarks,worldLandmarks:s.worldLandmarks,handednesses:s.handedness,handedness:s.handedness}}gw.prototype.recognizeForVideo=gw.prototype.Ia,gw.prototype.recognize=gw.prototype.Ha,gw.prototype.setOptions=gw.prototype.o,gw.createFromModelPath=function(s,t){return zu(gw,s,{baseOptions:{modelAssetPath:t}})},gw.createFromModelBuffer=function(s,t){return zu(gw,s,{baseOptions:{modelAssetBuffer:t}})},gw.createFromOptions=function(s,t){return zu(gw,s,t)},gw.HAND_CONNECTIONS=wrt;var yw=class extends Dj{constructor(s,t){super(new qS(s,t),"image_in","norm_rect",!1),this.landmarks=[],this.worldLandmarks=[],this.handedness=[],Tl(s=this.h=new crt,0,1,t=new Lx),this.u=new lrt,Tl(this.h,0,3,this.u),this.j=new NXt,Tl(this.h,0,2,this.j),EE(this.j,3,1),il(this.j,2,.5),il(this.u,2,.5),il(this.h,4,.5)}get baseOptions(){return Gu(this.h,Lx,1)}set baseOptions(s){Tl(this.h,0,1,s)}o(s){return"numHands"in s&&EE(this.j,3,s.numHands??1),"minHandDetectionConfidence"in s&&il(this.j,2,s.minHandDetectionConfidence??.5),"minTrackingConfidence"in s&&il(this.h,4,s.minTrackingConfidence??.5),"minHandPresenceConfidence"in s&&il(this.u,2,s.minHandPresenceConfidence??.5),this.l(s)}F(s,t){return this.landmarks=[],this.worldLandmarks=[],this.handedness=[],$S(this,s,t),SNt(this)}G(s,t,n){return this.landmarks=[],this.worldLandmarks=[],this.handedness=[],DC(this,s,n,t),SNt(this)}m(){var s=new qj;Wf(s,"image_in"),Wf(s,"norm_rect"),ih(s,"hand_landmarks"),ih(s,"world_hand_landmarks"),ih(s,"handedness");const t=new Uj;LC(t,i9n,this.h);const n=new J_;Ij(n,2,"mediapipe.tasks.vision.hand_landmarker.HandLandmarkerGraph"),rf(n,"IMAGE:image_in"),rf(n,"NORM_RECT:norm_rect"),Nu(n,"LANDMARKS:hand_landmarks"),Nu(n,"WORLD_LANDMARKS:world_hand_landmarks"),Nu(n,"HANDEDNESS:handedness"),n.o(t),VN(s,n),this.g.attachProtoVectorListener("hand_landmarks",(r,a)=>{for(const i of r)r=$ae(i),this.landmarks.push(y8e(r));ko(this,a)}),this.g.attachEmptyPacketListener("hand_landmarks",r=>{ko(this,r)}),this.g.attachProtoVectorListener("world_hand_landmarks",(r,a)=>{for(const i of r)r=O$(i),this.worldLandmarks.push(ree(r));ko(this,a)}),this.g.attachEmptyPacketListener("world_hand_landmarks",r=>{ko(this,r)}),this.g.attachProtoVectorListener("handedness",(r,a)=>{var i=this.handedness,l=i.push;const o=[];for(const c of r){r=x8e(c);const d=[];for(const u of r.g())d.push({score:Yx(u,2)??0,index:aN(u,1)??0??-1,categoryName:kv(Df(u,3))??""??"",displayName:kv(Df(u,4))??""??""});o.push(d)}l.call(i,...o),ko(this,a)}),this.g.attachEmptyPacketListener("handedness",r=>{ko(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};yw.prototype.detectForVideo=yw.prototype.G,yw.prototype.detect=yw.prototype.F,yw.prototype.setOptions=yw.prototype.o,yw.createFromModelPath=function(s,t){return zu(yw,s,{baseOptions:{modelAssetPath:t}})},yw.createFromModelBuffer=function(s,t){return zu(yw,s,{baseOptions:{modelAssetBuffer:t}})},yw.createFromOptions=function(s,t){return zu(yw,s,t)},yw.HAND_CONNECTIONS=wrt;var tQt=US([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 CNt(s){s.h={faceLandmarks:[],faceBlendshapes:[],poseLandmarks:[],poseWorldLandmarks:[],poseSegmentationMasks:[],leftHandLandmarks:[],leftHandWorldLandmarks:[],rightHandLandmarks:[],rightHandWorldLandmarks:[]}}function ANt(s){try{if(!s.D)return s.h;s.D(s.h)}finally{b8e(s)}}function Jce(s,t){s=$ae(s),t.push(y8e(s))}var $p=class extends Dj{constructor(s,t){super(new qS(s,t),"input_frames_image",null,!1),this.h={faceLandmarks:[],faceBlendshapes:[],poseLandmarks:[],poseWorldLandmarks:[],poseSegmentationMasks:[],leftHandLandmarks:[],leftHandWorldLandmarks:[],rightHandLandmarks:[],rightHandWorldLandmarks:[]},this.outputPoseSegmentationMasks=this.outputFaceBlendshapes=!1,Tl(s=this.j=new TXt,0,1,t=new Lx),this.I=new lrt,Tl(this.j,0,2,this.I),this.W=new o9n,Tl(this.j,0,3,this.W),this.u=new g8e,Tl(this.j,0,4,this.u),this.O=new _Xt,Tl(this.j,0,5,this.O),this.A=new AXt,Tl(this.j,0,6,this.A),this.M=new EXt,Tl(this.j,0,7,this.M),il(this.u,2,.5),il(this.u,3,.3),il(this.O,2,.5),il(this.A,2,.5),il(this.A,3,.3),il(this.M,2,.5),il(this.I,2,.5)}get baseOptions(){return Gu(this.j,Lx,1)}set baseOptions(s){Tl(this.j,0,1,s)}o(s){return"minFaceDetectionConfidence"in s&&il(this.u,2,s.minFaceDetectionConfidence??.5),"minFaceSuppressionThreshold"in s&&il(this.u,3,s.minFaceSuppressionThreshold??.3),"minFacePresenceConfidence"in s&&il(this.O,2,s.minFacePresenceConfidence??.5),"outputFaceBlendshapes"in s&&(this.outputFaceBlendshapes=!!s.outputFaceBlendshapes),"minPoseDetectionConfidence"in s&&il(this.A,2,s.minPoseDetectionConfidence??.5),"minPoseSuppressionThreshold"in s&&il(this.A,3,s.minPoseSuppressionThreshold??.3),"minPosePresenceConfidence"in s&&il(this.M,2,s.minPosePresenceConfidence??.5),"outputPoseSegmentationMasks"in s&&(this.outputPoseSegmentationMasks=!!s.outputPoseSegmentationMasks),"minHandLandmarksConfidence"in s&&il(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,CNt(this),$S(this,s,r),ANt(this)}G(s,t,n,r){const a=typeof n!="function"?n:{};return this.D=typeof n=="function"?n:r,CNt(this),DC(this,s,a,t),ANt(this)}m(){var s=new qj;Wf(s,"input_frames_image"),ih(s,"pose_landmarks"),ih(s,"pose_world_landmarks"),ih(s,"face_landmarks"),ih(s,"left_hand_landmarks"),ih(s,"left_hand_world_landmarks"),ih(s,"right_hand_landmarks"),ih(s,"right_hand_world_landmarks");const t=new Uj,n=new Q2t;Ij(n,1,"type.googleapis.com/mediapipe.tasks.vision.holistic_landmarker.proto.HolisticLandmarkerGraphOptions"),function(a,i){if(i!=null)if(Array.isArray(i))lm(a,2,r8e(i,0,yse));else{if(!(typeof i=="string"||i instanceof sC||Ant(i)))throw Error("invalid value in Any.value field: "+i+" expected a ByteString, a base64 encoded string, a Uint8Array or a jspb array");x6(a,2,Tnt(i,!1),f9())}}(n,this.j.g());const r=new J_;Ij(r,2,"mediapipe.tasks.vision.holistic_landmarker.HolisticLandmarkerGraph"),Vnt(r,8,Q2t,n),rf(r,"IMAGE:input_frames_image"),Nu(r,"POSE_LANDMARKS:pose_landmarks"),Nu(r,"POSE_WORLD_LANDMARKS:pose_world_landmarks"),Nu(r,"FACE_LANDMARKS:face_landmarks"),Nu(r,"LEFT_HAND_LANDMARKS:left_hand_landmarks"),Nu(r,"LEFT_HAND_WORLD_LANDMARKS:left_hand_world_landmarks"),Nu(r,"RIGHT_HAND_LANDMARKS:right_hand_landmarks"),Nu(r,"RIGHT_HAND_WORLD_LANDMARKS:right_hand_world_landmarks"),r.o(t),VN(s,r),v8e(this,s),this.g.attachProtoListener("pose_landmarks",(a,i)=>{Jce(a,this.h.poseLandmarks),ko(this,i)}),this.g.attachEmptyPacketListener("pose_landmarks",a=>{ko(this,a)}),this.g.attachProtoListener("pose_world_landmarks",(a,i)=>{var l=this.h.poseWorldLandmarks;a=O$(a),l.push(ree(a)),ko(this,i)}),this.g.attachEmptyPacketListener("pose_world_landmarks",a=>{ko(this,a)}),this.outputPoseSegmentationMasks&&(Nu(r,"POSE_SEGMENTATION_MASK:pose_segmentation_mask"),kG(this,"pose_segmentation_mask"),this.g.Z("pose_segmentation_mask",(a,i)=>{this.h.poseSegmentationMasks=[CG(this,a,!0,!this.D)],ko(this,i)}),this.g.attachEmptyPacketListener("pose_segmentation_mask",a=>{this.h.poseSegmentationMasks=[],ko(this,a)})),this.g.attachProtoListener("face_landmarks",(a,i)=>{Jce(a,this.h.faceLandmarks),ko(this,i)}),this.g.attachEmptyPacketListener("face_landmarks",a=>{ko(this,a)}),this.outputFaceBlendshapes&&(ih(s,"extra_blendshapes"),Nu(r,"FACE_BLENDSHAPES:extra_blendshapes"),this.g.attachProtoListener("extra_blendshapes",(a,i)=>{var l=this.h.faceBlendshapes;this.outputFaceBlendshapes&&(a=x8e(a),l.push(mrt(a.g()??[]))),ko(this,i)}),this.g.attachEmptyPacketListener("extra_blendshapes",a=>{ko(this,a)})),this.g.attachProtoListener("left_hand_landmarks",(a,i)=>{Jce(a,this.h.leftHandLandmarks),ko(this,i)}),this.g.attachEmptyPacketListener("left_hand_landmarks",a=>{ko(this,a)}),this.g.attachProtoListener("left_hand_world_landmarks",(a,i)=>{var l=this.h.leftHandWorldLandmarks;a=O$(a),l.push(ree(a)),ko(this,i)}),this.g.attachEmptyPacketListener("left_hand_world_landmarks",a=>{ko(this,a)}),this.g.attachProtoListener("right_hand_landmarks",(a,i)=>{Jce(a,this.h.rightHandLandmarks),ko(this,i)}),this.g.attachEmptyPacketListener("right_hand_landmarks",a=>{ko(this,a)}),this.g.attachProtoListener("right_hand_world_landmarks",(a,i)=>{var l=this.h.rightHandWorldLandmarks;a=O$(a),l.push(ree(a)),ko(this,i)}),this.g.attachEmptyPacketListener("right_hand_world_landmarks",a=>{ko(this,a)}),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 zu($p,s,{baseOptions:{modelAssetPath:t}})},$p.createFromModelBuffer=function(s,t){return zu($p,s,{baseOptions:{modelAssetBuffer:t}})},$p.createFromOptions=function(s,t){return zu($p,s,t)},$p.HAND_CONNECTIONS=wrt,$p.POSE_CONNECTIONS=tQt,$p.FACE_LANDMARKS_LIPS=xrt,$p.FACE_LANDMARKS_LEFT_EYE=grt,$p.FACE_LANDMARKS_LEFT_EYEBROW=yrt,$p.FACE_LANDMARKS_LEFT_IRIS=XXt,$p.FACE_LANDMARKS_RIGHT_EYE=vrt,$p.FACE_LANDMARKS_RIGHT_EYEBROW=brt,$p.FACE_LANDMARKS_RIGHT_IRIS=QXt,$p.FACE_LANDMARKS_FACE_OVAL=_rt,$p.FACE_LANDMARKS_CONTOURS=JXt,$p.FACE_LANDMARKS_TESSELATION=eQt;var b2=class extends Dj{constructor(s,t){super(new qS(s,t),"input_image","norm_rect",!0),this.j={classifications:[]},Tl(s=this.h=new MXt,0,1,t=new Lx)}get baseOptions(){return Gu(this.h,Lx,1)}set baseOptions(s){Tl(this.h,0,1,s)}o(s){return Tl(this.h,0,2,EWe(s,Gu(this.h,irt,2))),this.l(s)}sa(s,t){return this.j={classifications:[]},$S(this,s,t),this.j}ta(s,t,n){return this.j={classifications:[]},DC(this,s,n,t),this.j}m(){var s=new qj;Wf(s,"input_image"),Wf(s,"norm_rect"),ih(s,"classifications");const t=new Uj;LC(t,l9n,this.h);const n=new J_;Ij(n,2,"mediapipe.tasks.vision.image_classifier.ImageClassifierGraph"),rf(n,"IMAGE:input_image"),rf(n,"NORM_RECT:norm_rect"),Nu(n,"CLASSIFICATIONS:classifications"),n.o(t),VN(s,n),this.g.attachProtoListener("classifications",(r,a)=>{this.j=p9n(Z7n(r)),ko(this,a)}),this.g.attachEmptyPacketListener("classifications",r=>{ko(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};b2.prototype.classifyForVideo=b2.prototype.ta,b2.prototype.classify=b2.prototype.sa,b2.prototype.setOptions=b2.prototype.o,b2.createFromModelPath=function(s,t){return zu(b2,s,{baseOptions:{modelAssetPath:t}})},b2.createFromModelBuffer=function(s,t){return zu(b2,s,{baseOptions:{modelAssetBuffer:t}})},b2.createFromOptions=function(s,t){return zu(b2,s,t)};var vw=class extends Dj{constructor(s,t){super(new qS(s,t),"image_in","norm_rect",!0),this.h=new PXt,this.embeddings={embeddings:[]},Tl(s=this.h,0,1,t=new Lx)}get baseOptions(){return Gu(this.h,Lx,1)}set baseOptions(s){Tl(this.h,0,1,s)}o(s){var t=this.h,n=Gu(this.h,oNt,2);return n=n?n.clone():new oNt,s.l2Normalize!==void 0?lm(n,1,gse(s.l2Normalize)):"l2Normalize"in s&&lm(n,1),s.quantize!==void 0?lm(n,2,gse(s.quantize)):"quantize"in s&&lm(n,2),Tl(t,0,2,n),this.l(s)}za(s,t){return $S(this,s,t),this.embeddings}Aa(s,t,n){return DC(this,s,n,t),this.embeddings}m(){var s=new qj;Wf(s,"image_in"),Wf(s,"norm_rect"),ih(s,"embeddings_out");const t=new Uj;LC(t,c9n,this.h);const n=new J_;Ij(n,2,"mediapipe.tasks.vision.image_embedder.ImageEmbedderGraph"),rf(n,"IMAGE:image_in"),rf(n,"NORM_RECT:norm_rect"),Nu(n,"EMBEDDINGS:embeddings_out"),n.o(t),VN(s,n),this.g.attachProtoListener("embeddings_out",(r,a)=>{r=J7n(r),this.embeddings=function(i){return{embeddings:AE(i,Q7n,1).map(l=>{var d,u;const o={headIndex:aN(l,3)??0??-1,headName:kv(Df(l,4))??""??""};var c=l.v;return EZt(c,0|c[Go],iNt,dze(l,1))!==void 0?(l=CF(l=Gu(l,iNt,dze(l,1),void 0),1,I4,SF()),o.floatEmbedding=l.slice()):(c=new Uint8Array(0),o.quantizedEmbedding=((u=(d=Gu(l,X7n,dze(l,2),void 0))==null?void 0:d.na())==null?void 0:u.h())??c),o}),timestampMs:zXt(Df(i,2,void 0,void 0,OTe)??NZt)}}(r),ko(this,a)}),this.g.attachEmptyPacketListener("embeddings_out",r=>{ko(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};vw.cosineSimilarity=function(s,t){if(s.floatEmbedding&&t.floatEmbedding)s=mNt(s.floatEmbedding,t.floatEmbedding);else{if(!s.quantizedEmbedding||!t.quantizedEmbedding)throw Error("Cannot compute cosine similarity between quantized and float embeddings.");s=mNt(hNt(s.quantizedEmbedding),hNt(t.quantizedEmbedding))}return s},vw.prototype.embedForVideo=vw.prototype.Aa,vw.prototype.embed=vw.prototype.za,vw.prototype.setOptions=vw.prototype.o,vw.createFromModelPath=function(s,t){return zu(vw,s,{baseOptions:{modelAssetPath:t}})},vw.createFromModelBuffer=function(s,t){return zu(vw,s,{baseOptions:{modelAssetBuffer:t}})},vw.createFromOptions=function(s,t){return zu(vw,s,t)};var LWe=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 _9n(s){var n,r;const t=function(a){return AE(a,J_,1)}(s.ca()).filter(a=>(kv(Df(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=Gu(t[0],Uj,7))==null?void 0:n.j())==null?void 0:r.g())??new Map).forEach((a,i)=>{s.u[Number(i)]=kv(Df(a,1))??""})}function ENt(s){s.categoryMask=void 0,s.confidenceMasks=void 0,s.qualityScores=void 0}function TNt(s){try{const t=new LWe(s.confidenceMasks,s.categoryMask,s.qualityScores);if(!s.j)return t;s.j(t)}finally{b8e(s)}}LWe.prototype.close=LWe.prototype.close;var X1=class extends Dj{constructor(s,t){super(new qS(s,t),"image_in","norm_rect",!1),this.u=[],this.outputCategoryMask=!1,this.outputConfidenceMasks=!0,this.h=new hrt,this.A=new LXt,Tl(this.h,0,3,this.A),Tl(s=this.h,0,1,t=new Lx)}get baseOptions(){return Gu(this.h,Lx,1)}set baseOptions(s){Tl(this.h,0,1,s)}o(s){return s.displayNamesLocale!==void 0?lm(this.h,2,Bae(s.displayNamesLocale)):"displayNamesLocale"in s&&lm(this.h,2),"outputCategoryMask"in s&&(this.outputCategoryMask=s.outputCategoryMask??!1),"outputConfidenceMasks"in s&&(this.outputConfidenceMasks=s.outputConfidenceMasks??!0),super.l(s)}L(){_9n(this)}segment(s,t,n){const r=typeof t!="function"?t:{};return this.j=typeof t=="function"?t:n,ENt(this),$S(this,s,r),TNt(this)}La(s,t,n,r){const a=typeof n!="function"?n:{};return this.j=typeof n=="function"?n:r,ENt(this),DC(this,s,a,t),TNt(this)}Da(){return this.u}m(){var s=new qj;Wf(s,"image_in"),Wf(s,"norm_rect");const t=new Uj;LC(t,DXt,this.h);const n=new J_;Ij(n,2,"mediapipe.tasks.vision.image_segmenter.ImageSegmenterGraph"),rf(n,"IMAGE:image_in"),rf(n,"NORM_RECT:norm_rect"),n.o(t),VN(s,n),v8e(this,s),this.outputConfidenceMasks&&(ih(s,"confidence_masks"),Nu(n,"CONFIDENCE_MASKS:confidence_masks"),kG(this,"confidence_masks"),this.g.aa("confidence_masks",(r,a)=>{this.confidenceMasks=r.map(i=>CG(this,i,!0,!this.j)),ko(this,a)}),this.g.attachEmptyPacketListener("confidence_masks",r=>{this.confidenceMasks=[],ko(this,r)})),this.outputCategoryMask&&(ih(s,"category_mask"),Nu(n,"CATEGORY_MASK:category_mask"),kG(this,"category_mask"),this.g.Z("category_mask",(r,a)=>{this.categoryMask=CG(this,r,!1,!this.j),ko(this,a)}),this.g.attachEmptyPacketListener("category_mask",r=>{this.categoryMask=void 0,ko(this,r)})),ih(s,"quality_scores"),Nu(n,"QUALITY_SCORES:quality_scores"),this.g.attachFloatVectorListener("quality_scores",(r,a)=>{this.qualityScores=r,ko(this,a)}),this.g.attachEmptyPacketListener("quality_scores",r=>{this.categoryMask=void 0,ko(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};X1.prototype.getLabels=X1.prototype.Da,X1.prototype.segmentForVideo=X1.prototype.La,X1.prototype.segment=X1.prototype.segment,X1.prototype.setOptions=X1.prototype.o,X1.createFromModelPath=function(s,t){return zu(X1,s,{baseOptions:{modelAssetPath:t}})},X1.createFromModelBuffer=function(s,t){return zu(X1,s,{baseOptions:{modelAssetBuffer:t}})},X1.createFromOptions=function(s,t){return zu(X1,s,t)};var IWe=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()}};IWe.prototype.close=IWe.prototype.close;var j5=class extends Dj{constructor(s,t){super(new qS(s,t),"image_in","norm_rect_in",!1),this.outputCategoryMask=!1,this.outputConfidenceMasks=!0,this.h=new hrt,this.u=new LXt,Tl(this.h,0,3,this.u),Tl(s=this.h,0,1,t=new Lx)}get baseOptions(){return Gu(this.h,Lx,1)}set baseOptions(s){Tl(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 RXt,t.keypoint&&t.scribble)throw Error("Cannot provide both keypoint and scribble.");if(t.keypoint){var i=new pze;x6(i,3,gse(!0),!1),x6(i,1,AX(t.keypoint.x),0),x6(i,2,AX(t.keypoint.y),0),see(r,1,AWe,i)}else{if(!t.scribble)throw Error("Must provide either a keypoint or a scribble.");{const o=new u9n;for(i of t.scribble)x6(t=new pze,3,gse(!0),!1),x6(t,1,AX(i.x),0),x6(t,2,AX(i.y),0),Vnt(o,1,pze,t);see(r,2,AWe,o)}}this.g.addProtoToStream(r.g(),"mediapipe.tasks.vision.interactive_segmenter.proto.RegionOfInterest","roi_in",n),$S(this,s,a);e:{try{const o=new IWe(this.confidenceMasks,this.categoryMask,this.qualityScores);if(!this.j){var l=o;break e}this.j(o)}finally{b8e(this)}l=void 0}return l}m(){var s=new qj;Wf(s,"image_in"),Wf(s,"roi_in"),Wf(s,"norm_rect_in");const t=new Uj;LC(t,DXt,this.h);const n=new J_;Ij(n,2,"mediapipe.tasks.vision.interactive_segmenter.InteractiveSegmenterGraphV2"),rf(n,"IMAGE:image_in"),rf(n,"ROI:roi_in"),rf(n,"NORM_RECT:norm_rect_in"),n.o(t),VN(s,n),v8e(this,s),this.outputConfidenceMasks&&(ih(s,"confidence_masks"),Nu(n,"CONFIDENCE_MASKS:confidence_masks"),kG(this,"confidence_masks"),this.g.aa("confidence_masks",(r,a)=>{this.confidenceMasks=r.map(i=>CG(this,i,!0,!this.j)),ko(this,a)}),this.g.attachEmptyPacketListener("confidence_masks",r=>{this.confidenceMasks=[],ko(this,r)})),this.outputCategoryMask&&(ih(s,"category_mask"),Nu(n,"CATEGORY_MASK:category_mask"),kG(this,"category_mask"),this.g.Z("category_mask",(r,a)=>{this.categoryMask=CG(this,r,!1,!this.j),ko(this,a)}),this.g.attachEmptyPacketListener("category_mask",r=>{this.categoryMask=void 0,ko(this,r)})),ih(s,"quality_scores"),Nu(n,"QUALITY_SCORES:quality_scores"),this.g.attachFloatVectorListener("quality_scores",(r,a)=>{this.qualityScores=r,ko(this,a)}),this.g.attachEmptyPacketListener("quality_scores",r=>{this.categoryMask=void 0,ko(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};j5.prototype.segment=j5.prototype.segment,j5.prototype.setOptions=j5.prototype.o,j5.createFromModelPath=function(s,t){return zu(j5,s,{baseOptions:{modelAssetPath:t}})},j5.createFromModelBuffer=function(s,t){return zu(j5,s,{baseOptions:{modelAssetBuffer:t}})},j5.createFromOptions=function(s,t){return zu(j5,s,t)};var _2=class extends Dj{constructor(s,t){super(new qS(s,t),"input_frame_gpu","norm_rect",!1),this.j={detections:[]},Tl(s=this.h=new FXt,0,1,t=new Lx)}get baseOptions(){return Gu(this.h,Lx,1)}set baseOptions(s){Tl(this.h,0,1,s)}o(s){return s.displayNamesLocale!==void 0?lm(this.h,2,Bae(s.displayNamesLocale)):"displayNamesLocale"in s&&lm(this.h,2),s.maxResults!==void 0?EE(this.h,3,s.maxResults):"maxResults"in s&&lm(this.h,3),s.scoreThreshold!==void 0?il(this.h,4,s.scoreThreshold):"scoreThreshold"in s&&lm(this.h,4),s.categoryAllowlist!==void 0?BTe(this.h,5,s.categoryAllowlist):"categoryAllowlist"in s&&lm(this.h,5),s.categoryDenylist!==void 0?BTe(this.h,6,s.categoryDenylist):"categoryDenylist"in s&&lm(this.h,6),this.l(s)}F(s,t){return this.j={detections:[]},$S(this,s,t),this.j}G(s,t,n){return this.j={detections:[]},DC(this,s,n,t),this.j}m(){var s=new qj;Wf(s,"input_frame_gpu"),Wf(s,"norm_rect"),ih(s,"detections");const t=new Uj;LC(t,h9n,this.h);const n=new J_;Ij(n,2,"mediapipe.tasks.vision.ObjectDetectorGraph"),rf(n,"IMAGE:input_frame_gpu"),rf(n,"NORM_RECT:norm_rect"),Nu(n,"DETECTIONS:detections"),n.o(t),VN(s,n),this.g.attachProtoVectorListener("detections",(r,a)=>{for(const i of r)r=pXt(i),this.j.detections.push(BXt(r));ko(this,a)}),this.g.attachEmptyPacketListener("detections",r=>{ko(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};_2.prototype.detectForVideo=_2.prototype.G,_2.prototype.detect=_2.prototype.F,_2.prototype.setOptions=_2.prototype.o,_2.createFromModelPath=async function(s,t){return zu(_2,s,{baseOptions:{modelAssetPath:t}})},_2.createFromModelBuffer=function(s,t){return zu(_2,s,{baseOptions:{modelAssetBuffer:t}})},_2.createFromOptions=function(s,t){return zu(_2,s,t)};var DWe=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 MNt(s){s.landmarks=[],s.worldLandmarks=[],s.segmentationMasks=void 0}function PNt(s){try{const t=new DWe(s.landmarks,s.worldLandmarks,s.segmentationMasks);if(!s.u)return t;s.u(t)}finally{b8e(s)}}DWe.prototype.close=DWe.prototype.close;var bw=class extends Dj{constructor(s,t){super(new qS(s,t),"image_in","norm_rect",!1),this.landmarks=[],this.worldLandmarks=[],this.outputSegmentationMasks=!1,Tl(s=this.h=new OXt,0,1,t=new Lx),this.A=new EXt,Tl(this.h,0,3,this.A),this.j=new AXt,Tl(this.h,0,2,this.j),EE(this.j,4,1),il(this.j,2,.5),il(this.A,2,.5),il(this.h,4,.5)}get baseOptions(){return Gu(this.h,Lx,1)}set baseOptions(s){Tl(this.h,0,1,s)}o(s){return"numPoses"in s&&EE(this.j,4,s.numPoses??1),"minPoseDetectionConfidence"in s&&il(this.j,2,s.minPoseDetectionConfidence??.5),"minTrackingConfidence"in s&&il(this.h,4,s.minTrackingConfidence??.5),"minPosePresenceConfidence"in s&&il(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,MNt(this),$S(this,s,r),PNt(this)}G(s,t,n,r){const a=typeof n!="function"?n:{};return this.u=typeof n=="function"?n:r,MNt(this),DC(this,s,a,t),PNt(this)}m(){var s=new qj;Wf(s,"image_in"),Wf(s,"norm_rect"),ih(s,"normalized_landmarks"),ih(s,"world_landmarks"),ih(s,"segmentation_masks");const t=new Uj;LC(t,m9n,this.h);const n=new J_;Ij(n,2,"mediapipe.tasks.vision.pose_landmarker.PoseLandmarkerGraph"),rf(n,"IMAGE:image_in"),rf(n,"NORM_RECT:norm_rect"),Nu(n,"NORM_LANDMARKS:normalized_landmarks"),Nu(n,"WORLD_LANDMARKS:world_landmarks"),n.o(t),VN(s,n),v8e(this,s),this.g.attachProtoVectorListener("normalized_landmarks",(r,a)=>{this.landmarks=[];for(const i of r)r=$ae(i),this.landmarks.push(y8e(r));ko(this,a)}),this.g.attachEmptyPacketListener("normalized_landmarks",r=>{this.landmarks=[],ko(this,r)}),this.g.attachProtoVectorListener("world_landmarks",(r,a)=>{this.worldLandmarks=[];for(const i of r)r=O$(i),this.worldLandmarks.push(ree(r));ko(this,a)}),this.g.attachEmptyPacketListener("world_landmarks",r=>{this.worldLandmarks=[],ko(this,r)}),this.outputSegmentationMasks&&(Nu(n,"SEGMENTATION_MASK:segmentation_masks"),kG(this,"segmentation_masks"),this.g.aa("segmentation_masks",(r,a)=>{this.segmentationMasks=r.map(i=>CG(this,i,!0,!this.u)),ko(this,a)}),this.g.attachEmptyPacketListener("segmentation_masks",r=>{this.segmentationMasks=[],ko(this,r)})),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};bw.prototype.detectForVideo=bw.prototype.G,bw.prototype.detect=bw.prototype.F,bw.prototype.setOptions=bw.prototype.o,bw.createFromModelPath=function(s,t){return zu(bw,s,{baseOptions:{modelAssetPath:t}})},bw.createFromModelBuffer=function(s,t){return zu(bw,s,{baseOptions:{modelAssetBuffer:t}})},bw.createFromOptions=function(s,t){return zu(bw,s,t)},bw.POSE_CONNECTIONS=tQt;let AF=null,EX=null;async function w9n(){return AF||EX||(EX=(async()=>{const s=await wU.forVisionTasks("https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@latest/wasm");return AF=await X1.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}),AF})(),EX)}function j9n(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 N9n(){AF&&(AF.close(),AF=null,EX=null)}const k9n=1280,S9n=720;function C9n(s,t){const n=_.useRef(null),r=_.useRef(null),a=_.useRef(null),i=_.useRef(0),l=_.useRef(t),[o,c]=_.useState(null),[d,u]=_.useState(!1),[h,m]=_.useState(null);l.current=t;const p=t.type!=="none"&&s!==null;return _.useEffect(()=>{if(t.type==="image"&&t.imageUrl){const f=new Image;f.crossOrigin="anonymous",f.src=t.imageUrl,f.onload=()=>{a.current=f},f.onerror=()=>{a.current=null}}else t.type!=="image"&&(a.current=null)},[t.type,t.imageUrl]),_.useEffect(()=>{if(!p||!s){r.current&&(r.current.srcObject=null,r.current=null);return}const f=document.createElement("video");return f.srcObject=s,f.muted=!0,f.playsInline=!0,f.autoplay=!0,f.play().catch(()=>{}),r.current=f,()=>{f.srcObject=null,r.current=null}},[p,s]),_.useEffect(()=>{if(!p){c(null),m(null);return}let f=!1,y=null,v=null;const g=async()=>{u(!0),m(null);try{const j=await w9n();if(f)return;u(!1);const S=r.current;if(!S||(await new Promise(Xt=>{if(S.videoWidth>0)return Xt();S.onloadedmetadata=()=>Xt(),setTimeout(Xt,2e3)}),f))return;const C=S.videoWidth||640,E=S.videoHeight||480,P=Math.max(C,E),M=Math.min(C,E),I=Math.min(1,k9n/P,S9n/M),D=Math.max(2,Math.round(C*I/2)*2),O=Math.max(2,Math.round(E*I/2)*2),G=!JYt().canRunVirtualBg,H=(G?192:256)/Math.max(D,O),Y=Math.max(2,Math.round(D*H)),Z=Math.max(2,Math.round(O*H)),ne=G?90:55,ce=G?24:30,ie=n.current;if(!ie)return;ie.width=D,ie.height=O;const te=ie.getContext("2d",{alpha:!1}),ae=document.createElement("canvas");ae.width=D,ae.height=O;const le=ae.getContext("2d"),be=document.createElement("canvas");be.width=Math.max(2,Math.round(D/2)),be.height=Math.max(2,Math.round(O/2));const me=be.getContext("2d",{alpha:!1}),he=document.createElement("canvas");he.width=Y,he.height=Z;const pe=he.getContext("2d",{alpha:!1}),Ce=document.createElement("canvas");Ce.width=Y,Ce.height=Z;const Ae=Ce.getContext("2d"),Pe=Ae.createImageData(Y,Z),ze=Pe.data;for(let Xt=0;Xtke.addTrack(Xt)),f||c(ke);const Se=new Float32Array(Y*Z),Fe=new Float32Array(Y*Z),Ne=new Float32Array(Y*Z);let Ye=!1,Ve=!1;const qe=2,Qe=.4;let Ue=0;const Xe=(Xt,fs)=>{pe.drawImage(Xt,0,0,Y,Z);const wt=j.segmentForVideo(he,fs).confidenceMasks;if(!(!wt||wt.length===0)){Fe.fill(0);for(let Ts=1;Ts1?1:jn}}for(const Ts of wt)Ts.close();if(j9n(Fe,Se,Y,Z,qe),Ye)for(let Ts=0;Ts=1?255:$s*255|0}Ae.putImageData(Pe,0,0),Ve=!0}},nt=Xt=>{const fs=l.current;if(fs.type==="blur"){const Ft=Math.max(2,Math.round((fs.blurRadius??15)/2));me.filter=`blur(${Ft}px)`,me.drawImage(Xt,0,0,be.width,be.height),me.filter="none",te.drawImage(be,0,0,D,O)}else if(fs.type==="image"&&a.current){const Ft=a.current,wt=Ft.width/Ft.height,Ts=D/O;let vt=0,$s=0,As=Ft.width,jn=Ft.height;wt>Ts?(As=Ft.height*Ts,vt=(Ft.width-As)/2):(jn=Ft.width/Ts,$s=(Ft.height-jn)/2),te.drawImage(Ft,vt,$s,As,jn,0,0,D,O)}else te.fillStyle="#000",te.fillRect(0,0,D,O)},$e=()=>{if(f||!r.current)return;const Xt=r.current;if(Xt.readyState<2){Vt(Xt);return}try{const fs=performance.now();fs-Ue>=ne&&(Ue=fs,Xe(Xt,fs)),Ve?(nt(Xt),le.globalCompositeOperation="source-over",le.clearRect(0,0,D,O),le.drawImage(Xt,0,0,D,O),le.globalCompositeOperation="destination-in",le.drawImage(Ce,0,0,D,O),le.globalCompositeOperation="source-over",l.current.mirror?(te.save(),te.translate(D,0),te.scale(-1,1),te.drawImage(ae,0,0),te.restore()):te.drawImage(ae,0,0)):te.drawImage(Xt,0,0,D,O)}catch{try{te.drawImage(Xt,0,0,D,O)}catch{}}Vt(Xt)},Ge=typeof S.requestVideoFrameCallback=="function",ct="let id=null;onmessage=(e)=>{if(e.data&&e.data.type==='start'){clearInterval(id);id=setInterval(()=>postMessage('tick'),Math.round(1000/(e.data.fps||30)))}else{clearInterval(id);id=null}}",xt=new Blob([ct],{type:"application/javascript"});v=URL.createObjectURL(xt),y=new Worker(v),y.onmessage=()=>{f||!document.hidden||$e()};const qt=()=>{y&&(document.hidden?y.postMessage({type:"start",fps:ce}):(y.postMessage({type:"stop"}),Vt(r.current)))};document.addEventListener("visibilitychange",qt);const Vt=Xt=>{f||document.hidden||(Ge?Xt.requestVideoFrameCallback(()=>$e()):i.current=requestAnimationFrame($e))};Vt(S),b=()=>{document.removeEventListener("visibilitychange",qt)}}catch(j){console.error("[useVirtualBackground] init error:",j),f||(u(!1),m(j.message||"Failed to initialize virtual background"))}};let b=null;return g(),()=>{f=!0,i.current&&cancelAnimationFrame(i.current),b==null||b(),y&&(y.postMessage({type:"stop"}),y.terminate(),y=null),v&&URL.revokeObjectURL(v),c(null)}},[p,s]),_.useEffect(()=>()=>{N9n()},[]),{canvasRef:n,compositedStream:o,isLoading:d,isActive:p,error:h}}function $E({maxDurationSeconds:s=600,onRecordingComplete:t,onError:n,onRecordingStateChange:r,className:a,teleprompterContent:i}){const l=_.useRef(null),o=_.useRef(null),c=_.useRef(null),[d,u]=_.useState(null),h=_.useRef([]),m=_.useRef(null),p=_.useRef(null),f=_.useRef(null),y=_.useRef(null),v=$W(),[g,b]=_.useState("camera"),j=_.useRef(null),S=_.useRef(null),C=_.useRef(null),E=_.useRef(null),P=_.useRef(null),M=_.useRef(null),[I,D]=_.useState(!0),[O,V]=_.useState(!0),[G,$]=_.useState(null),[H,Y]=_.useState(!1),[Z,ne]=_.useState(!1),[ce,ie]=_.useState(null),[te,ae]=_.useState(null),[le,be]=_.useState(0),[me,he]=_.useState("user"),[pe,Ce]=_.useState(0),[Ae,Pe]=_.useState(!1),[ze,ke]=_.useState(!0),[Ze,Se]=_.useState(null),[Fe,Ne]=_.useState(!1),[Ye,Ve]=_.useState(null),qe=_.useRef(null),[Qe,Ue]=_.useState(()=>{try{const Gs=localStorage.getItem("video-bg-config");if(Gs)return JSON.parse(Gs)}catch{}return{type:"none"}});_.useEffect(()=>{try{localStorage.setItem("video-bg-config",JSON.stringify(Qe))}catch{}},[Qe]);const[Xe,nt]=_.useState([]),[$e,Ge]=_.useState([]),[ct,xt]=_.useState(()=>{try{return localStorage.getItem("video-mic-id")||""}catch{return""}}),[qt,Vt]=_.useState(()=>{try{return localStorage.getItem("video-cam-id")||""}catch{return""}});_.useEffect(()=>{try{localStorage.setItem("video-mic-id",ct)}catch{}},[ct]),_.useEffect(()=>{try{localStorage.setItem("video-cam-id",qt)}catch{}},[qt]),_.useEffect(()=>{var Ws,Ys,Bn;if(!((Ws=navigator.mediaDevices)!=null&&Ws.enumerateDevices))return;const Gs=async()=>{try{const or=await navigator.mediaDevices.enumerateDevices();nt(or.filter(Wt=>Wt.kind==="audioinput")),Ge(or.filter(Wt=>Wt.kind==="videoinput"))}catch(or){console.warn("[VideoRecorder] enumerateDevices failed",or)}};return Gs(),(Bn=(Ys=navigator.mediaDevices).addEventListener)==null||Bn.call(Ys,"devicechange",Gs),()=>{var or,Wt;return(Wt=(or=navigator.mediaDevices).removeEventListener)==null?void 0:Wt.call(or,"devicechange",Gs)}},[G]);const{canvasRef:Xt,compositedStream:fs,isLoading:Ft,isActive:wt,error:Ts}=C9n(d,Qe),vt=_.useRef(n);vt.current=n;const $s=_.useCallback(Gs=>{D(Gs)},[]),As=_.useRef(I),jn=_.useCallback(()=>{C.current&&(cancelAnimationFrame(C.current),C.current=null),E.current&&(E.current.terminate(),E.current=null),j.current&&(j.current.getTracks().forEach(Gs=>Gs.stop()),j.current=null),P.current&&(P.current.getTracks().forEach(Gs=>Gs.stop()),P.current=null),M.current&&(M.current.srcObject=null,M.current=null)},[]),ar=_.useCallback(async()=>{var Gs;try{const Ws=await navigator.mediaDevices.getDisplayMedia({video:{width:{ideal:1920},height:{ideal:1080}},audio:!0});j.current=Ws;let Ys=null;try{Ys=await navigator.mediaDevices.getUserMedia({video:qt?{deviceId:{exact:qt},width:{ideal:320},height:{ideal:240}}:{width:{ideal:320},height:{ideal:240}},audio:!1})}catch{console.warn("[VideoRecorder] No webcam for PiP overlay")}let Bn=null;try{Bn=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,...ct?{deviceId:{exact:ct}}:{}}}),console.log("[VideoRecorder] mic acquired for screen recording",Bn.getAudioTracks().map(Br=>Br.label))}catch(Br){console.warn("[VideoRecorder] No mic audio for screen recording",Br);try{Bn=await navigator.mediaDevices.getUserMedia({audio:!0})}catch{}}const or=Ws.getVideoTracks()[0],Wt=or.getSettings(),rt=Wt.width||1920,pt=Wt.height||1080,jt=document.createElement("canvas");jt.width=rt,jt.height=pt,S.current=jt;const Mt=jt.getContext("2d");let es=null;Ys&&(es=document.createElement("video"),es.srcObject=Ys,es.muted=!0,es.playsInline=!0,es.autoplay=!0,await es.play(),M.current=es);const ps=document.createElement("video");ps.srcObject=Ws,ps.muted=!0,ps.playsInline=!0,ps.autoplay=!0,await ps.play();const Is=()=>{if(Mt.drawImage(ps,0,0,rt,pt),es&&es.readyState>=2){const Br=Math.round(rt*.2),sa=Math.round(Br*(es.videoHeight/es.videoWidth||.75)),Rr=rt-Br-20,ra=pt-sa-20,Si=12;Mt.save(),Mt.beginPath(),Mt.moveTo(Rr+Si,ra),Mt.lineTo(Rr+Br-Si,ra),Mt.quadraticCurveTo(Rr+Br,ra,Rr+Br,ra+Si),Mt.lineTo(Rr+Br,ra+sa-Si),Mt.quadraticCurveTo(Rr+Br,ra+sa,Rr+Br-Si,ra+sa),Mt.lineTo(Rr+Si,ra+sa),Mt.quadraticCurveTo(Rr,ra+sa,Rr,ra+sa-Si),Mt.lineTo(Rr,ra+Si),Mt.quadraticCurveTo(Rr,ra,Rr+Si,ra),Mt.closePath(),Mt.clip(),Mt.translate(Rr+Br,ra),Mt.scale(-1,1),Mt.drawImage(es,0,0,Br,sa),Mt.restore(),Mt.strokeStyle="rgba(255,255,255,0.6)",Mt.lineWidth=2,Mt.beginPath(),Mt.moveTo(Rr+Si,ra),Mt.lineTo(Rr+Br-Si,ra),Mt.quadraticCurveTo(Rr+Br,ra,Rr+Br,ra+Si),Mt.lineTo(Rr+Br,ra+sa-Si),Mt.quadraticCurveTo(Rr+Br,ra+sa,Rr+Br-Si,ra+sa),Mt.lineTo(Rr+Si,ra+sa),Mt.quadraticCurveTo(Rr,ra+sa,Rr,ra+sa-Si),Mt.lineTo(Rr,ra+Si),Mt.quadraticCurveTo(Rr,ra,Rr+Si,ra),Mt.closePath(),Mt.stroke()}},js="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}}",Kt=new Blob([js],{type:"application/javascript"}),Qs=new Worker(URL.createObjectURL(Kt));E.current=Qs,Qs.onmessage=()=>Is(),Qs.postMessage({type:"start",fps:30}),Is();const an=jt.captureStream(30),er=[],Xr=Ws.getAudioTracks();Xr.length&&er.push(...Xr),Bn&&er.push(...Bn.getAudioTracks());const ma=new MediaStream([...an.getVideoTracks(),...er]);return P.current=ma,or.onended=()=>{o.current&&o.current.state!=="inactive"&&o.current.stop(),jn()},ma}catch(Ws){return console.error("[VideoRecorder] Screen capture error:",Ws),Ws.name!=="NotAllowedError"&&((Gs=vt.current)==null||Gs.call(vt,"Failed to start screen capture: "+(Ws.message||"Unknown error"))),null}},[jn]),Dn=_.useCallback(async()=>{var Ws,Ys;V(!0),Se(null);const Gs=v&&I;console.log("[VideoRecorder] initCamera start",{isMobile:v,usePortraitMode:I,shouldBePortrait:Gs,facingMode:me});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(Mt=>Mt.stop()));const Bn=v&&Gs?{width:{ideal:720},height:{ideal:1280}}:{width:{ideal:1280},height:{ideal:720}},or=qt?{...Bn,deviceId:{exact:qt}}:{...Bn,facingMode:{ideal:me}},Wt={echoCancellation:!0,noiseSuppression:!0,...ct?{deviceId:{exact:ct}}:{}};console.log("[VideoRecorder] requesting getUserMedia",or);const rt=await navigator.mediaDevices.getUserMedia({video:or,audio:Wt});if(console.log("[VideoRecorder] getUserMedia success"),rt.getVideoTracks().length===0)throw new Error("Camera stream started but no video track was provided.");c.current=rt,u(rt),$(!0);const jt=rt.getVideoTracks()[0].getSettings();if(console.log("[VideoRecorder] Camera initialized with dimensions:",jt.width,"x",jt.height),l.current){const Mt=l.current;Mt.srcObject=rt,Mt.muted=!0,Mt.playsInline=!0,Mt.autoplay=!0,Mt.setAttribute("muted",""),Mt.setAttribute("playsinline",""),Mt.setAttribute("autoplay","");try{(Ws=Mt.load)==null||Ws.call(Mt)}catch(ps){console.warn("[VideoRecorder] videoEl.load failed",ps)}const es=async()=>{try{return await Mt.play(),console.log("[VideoRecorder] preview play ok"),Ne(!1),setTimeout(()=>{console.debug("[VideoRecorder] preview metrics",{readyState:Mt.readyState,videoWidth:Mt.videoWidth,videoHeight:Mt.videoHeight})},300),!0}catch(ps){return console.warn("[VideoRecorder] preview play blocked",ps),Ne(!0),!1}};await new Promise(ps=>{let Is=!1;const js=()=>{Is||(Is=!0,ps())},Kt=()=>{es().finally(js)};Mt.onloadedmetadata=Kt,Mt.onloadeddata=Kt,setTimeout(js,1500)})}try{p.current=new AudioContext;const Mt=p.current.createMediaStreamSource(rt);f.current=p.current.createAnalyser(),f.current.fftSize=256,Mt.connect(f.current);const es=()=>{if(f.current){const ps=new Uint8Array(f.current.frequencyBinCount);f.current.getByteFrequencyData(ps);const Is=ps.reduce((js,Kt)=>js+Kt)/ps.length;Ce(Math.min(100,Is/128*100))}y.current=requestAnimationFrame(es)};es()}catch(Mt){console.warn("Audio context not available:",Mt)}}catch(Bn){console.error("Camera initialization error:",Bn),$(!1);let or="Failed to access camera or microphone.";Bn.name==="NotAllowedError"?or="Camera permission denied. Please allow camera access in your browser settings.":Bn.name==="NotFoundError"?or="No camera found. Please connect a camera and try again.":Bn.name==="NotReadableError"?or="Camera is in use by another application. Please close other apps using the camera.":Bn.message&&(or=Bn.message),Se(or),(Ys=vt.current)==null||Ys.call(vt,or)}finally{V(!1)}},[me,v,I,ct,qt]);_.useEffect(()=>{As.current!==I&&G&&!H&&!te&&(As.current=I,Dn())},[I,G,H,te,Dn]),_.useEffect(()=>(Dn(),()=>{c.current&&c.current.getTracks().forEach(Gs=>Gs.stop()),m.current&&clearInterval(m.current),y.current&&cancelAnimationFrame(y.current),p.current&&p.current.close(),qe.current&&clearInterval(qe.current),te&&URL.revokeObjectURL(te),jn()}),[Dn,te]),_.useEffect(()=>{if(O||G!==!0||te)return;const Gs=c.current,Ws=l.current;!Gs||!Ws||wt||(Ws.srcObject!==Gs&&(Ws.srcObject=Gs,Ws.muted=!0,Ws.playsInline=!0,Ws.autoplay=!0,Ws.setAttribute("muted",""),Ws.setAttribute("playsinline",""),Ws.setAttribute("autoplay","")),Ws.play().then(()=>Ne(!1)).catch(Ys=>{Ne(!0),console.warn("Live preview play blocked on mount:",Ys)}))},[G,O,te,wt]),_.useEffect(()=>{r==null||r(H)},[H,r]);const Ur=_.useCallback(async()=>{if(te)return;const Gs=l.current;if(Gs)try{await Gs.play(),Ne(!1)}catch(Ws){Ne(!0),console.warn("Live preview still blocked (needs user gesture):",Ws)}},[te]),Vs=_.useCallback(()=>{o.current&&o.current.state!=="inactive"&&o.current.stop(),m.current&&(clearInterval(m.current),m.current=null),jn(),Y(!1),ne(!1)},[jn]),hn=_.useCallback(async()=>{let Gs=null;if(g==="screen"){if(Gs=await ar(),!Gs)return}else Gs=wt&&fs?fs:c.current;if(!Gs)return;Ur(),h.current=[],be(0);const Ys=["video/webm;codecs=vp9,opus","video/webm;codecs=vp8,opus","video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm","video/mp4"].find(or=>MediaRecorder.isTypeSupported(or)),Bn=new MediaRecorder(Gs,Ys?{mimeType:Ys,videoBitsPerSecond:g==="screen"?4e6:25e5,audioBitsPerSecond:128e3}:{videoBitsPerSecond:g==="screen"?4e6:25e5,audioBitsPerSecond:128e3});Bn.ondataavailable=or=>{or.data.size>0&&h.current.push(or.data)},Bn.onstop=()=>{var pt;const or=Bn.mimeType||Ys||((pt=h.current[0])==null?void 0:pt.type)||"video/webm",Wt=new Blob(h.current,{type:or});ie(Wt);const rt=URL.createObjectURL(Wt);ae(rt)},o.current=Bn,Bn.start(1e3),Y(!0),m.current=setInterval(()=>{be(or=>or>=s-1?(Vs(),s):or+1)},1e3)},[Ur,s,Vs,wt,fs,g,ar]),dr=_.useCallback(()=>{qe.current&&(clearInterval(qe.current),qe.current=null),Ve(3);let Gs=3;qe.current=setInterval(()=>{Gs-=1,Gs<=0?(qe.current&&clearInterval(qe.current),qe.current=null,Ve(null),hn()):Ve(Gs)},1e3)},[hn]),Cn=_.useCallback(()=>{o.current&&o.current.state==="recording"&&(o.current.pause(),ne(!0),m.current&&clearInterval(m.current))},[]),Yn=_.useCallback(()=>{o.current&&o.current.state==="paused"&&(o.current.resume(),ne(!1),m.current=setInterval(()=>{be(Gs=>Gs>=s-1?(Vs(),s):Gs+1)},1e3))},[s,Vs]),on=_.useCallback(()=>{te&&URL.revokeObjectURL(te),ie(null),ae(null),be(0),Pe(!1),ke(!0),l.current&&c.current&&!wt&&(l.current.srcObject=c.current,l.current.muted=!0,Ur())},[Ur,te,wt]),Ir=_.useCallback(()=>{he(Gs=>Gs==="user"?"environment":"user")},[]),Wn=_.useCallback(()=>{ce&&t(ce,le)},[ce,le,t]),Js=_.useCallback(()=>{l.current&&te&&(Ae?l.current.pause():(ke(!1),l.current.muted=!1,l.current.play()),Pe(!Ae))},[te,Ae]);_.useEffect(()=>{if(!te)return;const Gs=l.current;if(!Gs)return;ke(!1),Gs.pause(),Gs.removeAttribute("src"),Gs.srcObject=null,Gs.load(),Gs.src=te,Gs.currentTime=0,Gs.playsInline=!0,Gs.muted=!1,Gs.onended=()=>Pe(!1);const Ws=()=>{var or;const Ys=Gs.error,Bn=Ys?`Recorded video failed to play (code ${Ys.code}). Likely unsupported format/codec in this browser.`:"Recorded video failed to play.";console.warn("[VideoRecorder] recorded playback error",Ys),(or=vt.current)==null||or.call(vt,Bn)};return Gs.addEventListener("error",Ws),Gs.load(),()=>{Gs.removeEventListener("error",Ws)}},[te]);const Fa=Gs=>{const Ws=Math.floor(Gs/60),Ys=Gs%60;return`${Ws}:${Ys.toString().padStart(2,"0")}`},ks=g==="screen"?"aspect-video":v&&I?"aspect-[9/16]":"aspect-video";return O?e.jsx("div",{className:At("flex items-center justify-center bg-black rounded-lg",ks,a),children:e.jsxs("div",{className:"text-center text-white",children:[e.jsx(Ct,{className:"h-12 w-12 animate-spin mx-auto mb-4"}),e.jsx("p",{children:"Initializing camera..."})]})}):G===!1?e.jsx("div",{className:At("flex items-center justify-center bg-black rounded-lg",ks,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:Ze||"Please allow camera and microphone access to record videos."}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(B,{onClick:()=>Dn(),variant:"secondary",className:"w-full",children:[e.jsx(uo,{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:At("flex flex-col gap-2",a),children:[!H&&!te&&e.jsxs("div",{className:"flex items-center justify-center gap-1 p-1 bg-muted rounded-lg",children:[e.jsxs(B,{variant:g==="camera"?"default":"ghost",size:"sm",className:"gap-1.5 flex-1",onClick:()=>b("camera"),children:[e.jsx(cg,{className:"h-4 w-4"}),"Camera"]}),e.jsxs(B,{variant:g==="screen"?"default":"ghost",size:"sm",className:"gap-1.5 flex-1",onClick:()=>b("screen"),children:[e.jsx(r7,{className:"h-4 w-4"}),"Screen"]})]}),g==="camera"&&!H&&!te&&e.jsx(OOn,{value:Qe,onChange:Ue,isLoading:Ft,disabled:H}),!H&&!te&&(Xe.length>0||$e.length>0)&&e.jsxs("div",{className:"flex flex-wrap items-center gap-3 px-3 py-2 bg-muted/40 rounded-lg",children:[Xe.length>0&&e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-[200px]",children:[e.jsx(n7,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs(is,{value:ct||"default",onValueChange:Gs=>xt(Gs==="default"?"":Gs),children:[e.jsx(rs,{className:"h-8 text-xs",children:e.jsx(ls,{placeholder:"Default microphone"})}),e.jsxs(as,{children:[e.jsx(He,{value:"default",children:"Default microphone"}),Xe.map(Gs=>e.jsx(He,{value:Gs.deviceId,children:Gs.label||`Microphone ${Gs.deviceId.slice(0,6)}`},Gs.deviceId))]})]})]}),$e.length>1&&g==="camera"&&e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-[200px]",children:[e.jsx(cg,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs(is,{value:qt||"default",onValueChange:Gs=>Vt(Gs==="default"?"":Gs),children:[e.jsx(rs,{className:"h-8 text-xs",children:e.jsx(ls,{placeholder:"Default camera"})}),e.jsxs(as,{children:[e.jsx(He,{value:"default",children:"Default camera"}),$e.map(Gs=>e.jsx(He,{value:Gs.deviceId,children:Gs.label||`Camera ${Gs.deviceId.slice(0,6)}`},Gs.deviceId))]})]})]})]}),g==="camera"&&v&&!H&&!te&&e.jsxs("div",{className:"flex items-center justify-center gap-3 py-2 bg-muted/50 rounded-lg",children:[e.jsx(hN,{className:At("h-4 w-4",I?"text-muted-foreground":"text-primary")}),e.jsx(J,{htmlFor:"orientation-toggle",className:"text-sm text-muted-foreground",children:"Landscape"}),e.jsx(fn,{id:"orientation-toggle",checked:I,onCheckedChange:$s}),e.jsx(J,{htmlFor:"orientation-toggle",className:"text-sm text-muted-foreground",children:"Portrait"}),e.jsx(p1,{className:At("h-4 w-4",I?"text-primary":"text-muted-foreground")})]}),g==="screen"&&!H&&!te&&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(r7,{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:At("relative bg-black rounded-lg overflow-hidden"),onPointerDown:()=>{Ur()},children:[e.jsx("video",{ref:l,src:te??void 0,className:At("w-full bg-black",I&&!te?"object-contain":"object-cover",ks,!te&&me==="user"!==(Qe.mirror??!1)&&"scale-x-[-1]",wt&&!te&&"hidden"),playsInline:!0,controls:!!te,muted:te?ze:!0,autoPlay:!te},te??"live"),wt&&!te&&e.jsx("canvas",{ref:Xt,className:At("w-full bg-black",I?"object-contain":"object-cover",ks,me==="user"!==(Qe.mirror??!1)&&"scale-x-[-1]")}),wt&&Ft&&!te&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/60 z-20",children:e.jsxs("div",{className:"text-center text-white",children:[e.jsx(Ct,{className:"h-8 w-8 animate-spin mx-auto mb-2"}),e.jsx("p",{className:"text-sm",children:"Loading virtual background…"})]})}),!te&&Fe&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/40",children:e.jsx(B,{type:"button",variant:"secondary",onClick:()=>void Ur(),className:"bg-white/20 hover:bg-white/30 text-white",children:"Tap to enable preview"})}),i&&!te&&e.jsx("div",{className:"absolute inset-0 pointer-events-none",children:i}),Ye!==null&&!te&&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:Ye},Ye),e.jsx("p",{className:"text-white/80 text-lg font-medium drop-shadow-md",children:"Get ready…"})]})}),H&&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:At("w-3 h-3 rounded-full",Z?"bg-yellow-500":"bg-red-500 animate-pulse")}),e.jsxs("span",{className:"text-white text-sm font-medium",children:[Fa(le)," / ",Fa(s)]})]}),H&&e.jsx("div",{className:"absolute top-0 left-0 right-0",children:e.jsx(Fi,{value:le/s*100,className:"h-1 rounded-none"})}),!te&&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(n7,{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:`${pe}%`}})})]}),e.jsx("div",{className:"absolute bottom-4 left-0 right-0 flex justify-center gap-3 px-4",children:te?e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"secondary",size:"lg",className:"bg-white/20 hover:bg-white/30 text-white",onClick:on,children:[e.jsx(uo,{className:"h-5 w-5 mr-2"}),"Re-record"]}),e.jsx(B,{variant:"secondary",size:"icon",className:"h-12 w-12 rounded-full bg-white/20 hover:bg-white/30 text-white",onClick:Js,children:Ae?e.jsx(ky,{className:"h-5 w-5"}):e.jsx(Jd,{className:"h-5 w-5"})}),e.jsxs(B,{size:"lg",className:"bg-green-500 hover:bg-green-600 text-white",onClick:Wn,children:[e.jsx(ea,{className:"h-5 w-5 mr-2"}),"Use This Video"]})]}):e.jsxs(e.Fragment,{children:[g==="camera"?e.jsx(B,{variant:"secondary",size:"icon",className:"h-12 w-12 rounded-full bg-white/20 hover:bg-white/30 text-white",onClick:Ir,disabled:H||Ye!==null,children:e.jsx(Tx,{className:"h-5 w-5"})}):e.jsx("div",{className:"h-12 w-12"}),!H&&Ye===null?e.jsx(B,{size:"icon",className:"h-16 w-16 rounded-full bg-red-500 hover:bg-red-600 text-white",onClick:g==="screen"?hn:dr,children:g==="screen"?e.jsx(r7,{className:"h-6 w-6"}):e.jsx(Kr,{className:"h-6 w-6"})}):e.jsxs(e.Fragment,{children:[e.jsx(B,{size:"icon",className:"h-12 w-12 rounded-full bg-white/20 hover:bg-white/30 text-white",onClick:Z?Yn:Cn,children:Z?e.jsx(Jd,{className:"h-5 w-5"}):e.jsx(ky,{className:"h-5 w-5"})}),e.jsx(B,{size:"icon",className:"h-16 w-16 rounded-full bg-red-500 hover:bg-red-600 text-white",onClick:Vs,children:e.jsx(wb,{className:"h-6 w-6 fill-current"})})]}),e.jsx("div",{className:"h-12 w-12"})]})})]})]})}function A9n({open:s,onOpenChange:t,onUploaded:n}){const{user:r}=hs(),{toast:a}=vi(),[i,l]=_.useState(!1),o=async(c,d)=>{if(r){l(!0);try{const u=c.type.includes("mp4")?"mp4":"webm",h=`${r.id}/${crypto.randomUUID()}.${u}`,{error:m}=await q.storage.from("cma-videos").upload(h,c,{contentType:c.type||"video/webm",upsert:!1});if(m)throw m;const{data:p,error:f}=await q.storage.from("cma-videos").createSignedUrl(h,60*60*24*365*5);if(f||!(p!=null&&p.signedUrl))throw f||new Error("Could not sign video URL");n(p.signedUrl,Math.round(d)),a({title:"Video added to your CMA"}),t(!1)}catch(u){a({title:"Upload failed",description:u==null?void 0:u.message,variant:"destructive"})}finally{l(!1)}}};return e.jsx(Ls,{open:s,onOpenChange:c=>!i&&t(c),children:e.jsxs(Ps,{className:"max-w-2xl",children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Record a personal message"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"A 30-second hello goes a long way. Welcome your client, explain the price, and invite their reply."})]}),i?e.jsxs("div",{className:"py-12 flex flex-col items-center gap-3",children:[e.jsx(Ct,{className:"w-8 h-8 animate-spin text-primary"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Uploading your video…"})]}):e.jsx($E,{maxDurationSeconds:180,onRecordingComplete:o})]})})}function E9n({value:s,onChange:t}){const{user:n}=hs(),[r,a]=_.useState(!1);return e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsxs(St,{className:"text-base flex items-center gap-2",children:[e.jsx(Kr,{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(Me,{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(Qn,{className:"w-3.5 h-3.5"})})]}),e.jsxs("p",{className:"text-xs text-emerald-700 flex items-center gap-1",children:[e.jsx(Jd,{className:"w-3 h-3"})," Video attached"]})]}):e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(iz,{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(B,{variant:"outline",onClick:()=>a(!0),className:"gap-2",children:[e.jsx(Kr,{className:"w-4 h-4"}),"Record New"]})]}),e.jsx(A9n,{open:r,onOpenChange:a,onUploaded:i=>t({url:i,label:"Personal message"})})]})]})}function Zk(s){const t=Number(String(s).replace(/[^0-9.]/g,""));return Number.isFinite(t)&&t>0?t:null}function T9n({open:s,onOpenChange:t,subject:n,onSave:r,isSaving:a}){const[i,l]=_.useState({bedrooms:"",bathrooms:"",sqft:"",yearBuilt:"",propertyType:"",propertySubType:""});_.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:Zk(i.bedrooms),bathrooms:Zk(i.bathrooms),sqft:Zk(i.sqft),yearBuilt:Zk(i.yearBuilt),propertyType:i.propertyType||null,propertySubType:i.propertySubType||null}),t(!1)};return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"max-w-lg",children:[e.jsx(Os,{children:e.jsx(Ds,{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(J,{className:"text-xs",children:"Beds"}),e.jsx(xe,{inputMode:"decimal",value:i.bedrooms,onChange:c=>l(d=>({...d,bedrooms:c.target.value})),placeholder:"3"})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Baths"}),e.jsx(xe,{inputMode:"decimal",value:i.bathrooms,onChange:c=>l(d=>({...d,bathrooms:c.target.value})),placeholder:"2"})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Sq Ft"}),e.jsx(xe,{inputMode:"numeric",value:i.sqft,onChange:c=>l(d=>({...d,sqft:c.target.value})),placeholder:"1850"})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Year Built"}),e.jsx(xe,{inputMode:"numeric",value:i.yearBuilt,onChange:c=>l(d=>({...d,yearBuilt:c.target.value})),placeholder:"2006"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Property Type"}),e.jsx(xe,{value:i.propertyType,onChange:c=>l(d=>({...d,propertyType:c.target.value})),placeholder:"Residential"})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Subtype"}),e.jsx(xe,{value:i.propertySubType,onChange:c=>l(d=>({...d,propertySubType:c.target.value})),placeholder:"Single Family"})]})]}),e.jsxs(B,{className:"w-full",onClick:o,disabled:a,children:[a?e.jsx(Ct,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(Ho,{className:"w-4 h-4 mr-2"}),"Save subject details"]})]})]})})}function M9n({open:s,onOpenChange:t,subject:n,onAdd:r}){const[a,i]=_.useState({address:"",city:"",state:"",status:"Closed",price:"",bedrooms:"",bathrooms:"",sqft:"",yearBuilt:""});_.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=Zk(a.price),c=Zk(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:Zk(a.bedrooms),bathrooms:Zk(a.bathrooms),sqft:c,yearBuilt:Zk(a.yearBuilt),photos:[]}),t(!1))};return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"max-w-2xl",children:[e.jsx(Os,{children:e.jsx(Ds,{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(J,{className:"text-xs",children:"Address"}),e.jsx(xe,{value:a.address,onChange:o=>i(c=>({...c,address:o.target.value})),placeholder:"123 Comparable St"})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"City"}),e.jsx(xe,{value:a.city,onChange:o=>i(c=>({...c,city:o.target.value}))})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"State"}),e.jsx(xe,{maxLength:2,value:a.state,onChange:o=>i(c=>({...c,state:o.target.value.toUpperCase()}))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Status"}),e.jsx(xe,{value:a.status,onChange:o=>i(c=>({...c,status:o.target.value})),placeholder:"Closed"})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Price"}),e.jsx(xe,{inputMode:"numeric",value:a.price,onChange:o=>i(c=>({...c,price:o.target.value})),placeholder:"525000"})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Sq Ft"}),e.jsx(xe,{inputMode:"numeric",value:a.sqft,onChange:o=>i(c=>({...c,sqft:o.target.value})),placeholder:"1800"})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Beds"}),e.jsx(xe,{inputMode:"decimal",value:a.bedrooms,onChange:o=>i(c=>({...c,bedrooms:o.target.value})),placeholder:"3"})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Baths"}),e.jsx(xe,{inputMode:"decimal",value:a.bathrooms,onChange:o=>i(c=>({...c,bathrooms:o.target.value})),placeholder:"2"})]})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Year Built"}),e.jsx(xe,{className:"max-w-[180px]",inputMode:"numeric",value:a.yearBuilt,onChange:o=>i(c=>({...c,yearBuilt:o.target.value})),placeholder:"2005"})]}),e.jsxs(B,{className:"w-full",onClick:l,disabled:!a.address.trim()||!Zk(a.price)||!Zk(a.sqft),children:[e.jsx(rn,{className:"w-4 h-4 mr-2"}),"Add comp to CMA"]})]})]})})}function P9n(){var he,pe,Ce,Ae,Pe,ze,ke;const{id:s}=Li(),t=Fn(),{toast:n}=vi(),{data:r,isLoading:a}=TFn(s),{data:i}=MFn(s),l=PFn(),o=DFn(),c=RFn(),{leadSite:d,isLoading:u}=lf(),[h,m]=_.useState([]),[p,f]=_.useState({sqftPct:.2,monthsBack:6,maxMiles:5,statuses:["Active","Pending","Closed"]}),[y,v]=_.useState(null),[g,b]=_.useState(!1),[j,S]=_.useState({low:"",likely:"",high:"",note:""}),[C,E]=_.useState(!1),[P,M]=_.useState(!1),[I,D]=_.useState(!1),[O,V]=_.useState(null),G=async Ze=>{var qe,Qe;if(!r||!(Ze!=null&&Ze.address)||!(Ze!=null&&Ze.city)||!(Ze!=null&&Ze.state))return Ze;let Se={...Ze};const Fe=async Ue=>{const{data:Xe,error:nt}=await q.functions.invoke("cma-subject-lookup",{body:{address:Ue.address,city:Ue.city,state:Ue.state,zip:Ue.zip,latitude:Ue.latitude,longitude:Ue.longitude,leadSiteId:(d==null?void 0:d.id)??r.lead_site_id}});if(nt)throw nt;return(Xe==null?void 0:Xe.matches)||[]},Ne=Ue=>{const nt=Ue.find(xt=>Number.isFinite(Number(xt.latitude))&&Number.isFinite(Number(xt.longitude)))||Ue[0];if(!nt)return;const $e=typeof nt.match_type=="string"&&nt.match_type.startsWith("nearby-"),Ge=$e&&Number.isFinite(Number(Se.latitude))&&Number.isFinite(Number(Se.longitude)),ct=xt=>nt[xt]!==void 0&&nt[xt]!==null&&nt[xt]!==""&&nt[xt]!==0?nt[xt]:Se[xt];Se={...Se,bedrooms:ct("bedrooms"),bathrooms:ct("bathrooms"),sqft:ct("sqft"),yearBuilt:ct("yearBuilt"),lotSize:ct("lotSize"),propertyType:ct("propertyType"),propertySubType:ct("propertySubType"),source_provider:nt.source_provider??Se.source_provider,match_type:nt.match_type??Se.match_type,matched_mls_address:$e?nt.address:Se.matched_mls_address,latitude:Ge?Se.latitude:nt.latitude??Se.latitude,longitude:Ge?Se.longitude:nt.longitude??Se.longitude,mlsNumber:$e?Se.mlsNumber:nt.mlsNumber??Se.mlsNumber,photos:!$e&&Array.isArray(nt.photos)&&nt.photos.length?nt.photos:Se.photos}};Ne(await Fe(Se));const Ye=()=>Number.isFinite(Number(Se.latitude))&&Number.isFinite(Number(Se.longitude));if(!Ye()){const{data:Ue}=await q.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle(),Xe=Ue==null?void 0:Ue.value;if(Xe){const nt=encodeURIComponent(`${Se.address}, ${Se.city}, ${Se.state} ${Se.zip||""}`.trim()),Ge=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${nt}.json?access_token=${Xe}&limit=1&country=us`)).json(),ct=(Qe=(qe=Ge==null?void 0:Ge.features)==null?void 0:qe[0])==null?void 0:Qe.center;Array.isArray(ct)&&ct.length===2&&(Se.longitude=ct[0],Se.latitude=ct[1])}}if((!Se.bedrooms||!Se.bathrooms||!Se.sqft||!Se.yearBuilt)&&Ye())try{Ne(await Fe(Se))}catch(Ue){console.warn("second-pass subject lookup failed",Ue)}return JSON.stringify(Se)!==JSON.stringify(Ze)&&await l.mutateAsync({id:r.id,patch:{subject:Se}}),Se};_.useEffect(()=>{var Fe,Ne;r!=null&&r.settings&&f({sqftPct:r.settings.sqftPct??.2,monthsBack:r.settings.monthsBack??6,maxMiles:r.settings.maxMiles??5,statuses:r.settings.statuses??["Active","Pending","Closed"]});const Ze=(Fe=r==null?void 0:r.settings)==null?void 0:Fe.priceOverride;Ze!=null&&Ze.enabled&&(b(!0),S({low:Ze.low!=null?String(Ze.low):"",likely:Ze.likely!=null?String(Ze.likely):"",high:Ze.high!=null?String(Ze.high):"",note:Ze.note??""}));const Se=(Ne=r==null?void 0:r.settings)==null?void 0:Ne.personalVideo;Se!=null&&Se.url&&V({url:Se.url,thumb:Se.thumb,label:Se.label})},[r==null?void 0:r.id]);const $=_.useRef(!1);_.useEffect(()=>{$.current||i!=null&&i.length&&(m(i.map(Ze=>({...Ze.snapshot,selected:Ze.selected,manual:Ze.manual,score:Ze.score}))),$.current=!0)},[i]);const H=_.useRef(null);_.useEffect(()=>{if(!r||u)return;const Ze=r.subject||{},Se=Number.isFinite(Number(Ze.latitude))&&Number.isFinite(Number(Ze.longitude)),Fe=!!(Number(Ze.bedrooms)||Number(Ze.bathrooms)||Number(Ze.sqft)||Number(Ze.yearBuilt));if(Se&&Fe)return;const Ne=`${r.id}:${(d==null?void 0:d.id)??r.lead_site_id??"no-site"}`;H.current!==Ne&&(!Ze.address||!Ze.city||!Ze.state||(H.current=Ne,(async()=>{try{await G(Ze)}catch(Ye){console.warn("subject enrich failed",Ye)}})()))},[r==null?void 0:r.id,r==null?void 0:r.lead_site_id,d==null?void 0:d.id,u]);const Y=_.useMemo(()=>r?j2t(r.subject,h):null,[r,h]),Z=async()=>{if(r)try{const Ze=await G(r.subject),Se=await o.mutateAsync({subject:Ze,filters:p,leadSiteId:(d==null?void 0:d.id)??r.lead_site_id});m(Se.comps.map(Fe=>({...Fe,selected:!0})).slice(0,12)),n({title:`Found ${Se.comps.length} comps`,description:`Top ${Math.min(12,Se.comps.length)} auto-selected.`})}catch(Ze){n({title:"Search failed",description:Ze.message,variant:"destructive"})}},ne=Ze=>{m(Se=>Se.map((Fe,Ne)=>Ne===Ze?{...Fe,selected:!Fe.selected}:Fe))},ce=Ze=>{m(Se=>Se.filter((Fe,Ne)=>Ne!==Ze))},ie=async Ze=>{if(!r)return;const Se=Object.fromEntries(Object.entries(Ze).filter(([,Ne])=>Ne!=null&&Ne!=="")),Fe={...r.subject,...Se,manually_enriched:!0};await l.mutateAsync({id:r.id,patch:{subject:Fe}}),n({title:"Subject details saved",description:Fe.sqft?"You can now find comps or add your own.":"Add square footage to unlock suggested pricing."})},te=Ze=>{m(Se=>[{...Ze,selected:!0,manual:!0},...Se]),n({title:"Manual comp added"})},ae=async(Ze=!1)=>{if(!r)return;const Se=j2t(r.subject,h),Fe=Qe=>{const Ue=Number(String(Qe).replace(/[^0-9.]/g,""));return Number.isFinite(Ue)&&Ue>0?Math.round(Ue):null},Ne=g?Fe(j.likely):null,Ye=g?Fe(j.low):null,Ve=g?Fe(j.high):null,qe=g&&Ne;await l.mutateAsync({id:r.id,patch:{settings:{...p,priceOverride:{enabled:g,low:Ye,likely:Ne,high:Ve,note:j.note||null},personalVideo:O},price_low:qe?Ye??Ne:Se.low??null,price_likely:qe?Ne:Se.likely??null,price_high:qe?Ve??Ne:Se.high??null,status:Ze?"shared":r.status}}),await c.mutateAsync({cmaId:r.id,comps:h}),n({title:Ze?"CMA published":"CMA saved"})},le=r?`https://cma.relevelup.com/${r.share_token}`:"";if(a||!r)return e.jsx(zs,{children:e.jsx("div",{className:"p-6",children:e.jsx(Ct,{className:"w-6 h-6 animate-spin"})})});const be=h.filter(Ze=>Ze.selected).length,me=!((he=r.subject)!=null&&he.bedrooms)||!((pe=r.subject)!=null&&pe.bathrooms)||!((Ce=r.subject)!=null&&Ce.sqft)||!((Ae=r.subject)!=null&&Ae.yearBuilt);return e.jsx(zs,{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(B,{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(B,{variant:"outline",onClick:()=>ae(!1),disabled:l.isPending,children:[e.jsx(Ho,{className:"w-4 h-4 mr-1"}),"Save"]}),e.jsxs(B,{onClick:()=>ae(!0),disabled:l.isPending,children:[e.jsx(bd,{className:"w-4 h-4 mr-1"}),"Publish & Share"]}),r.status==="shared"&&e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"secondary",onClick:()=>{navigator.clipboard.writeText(le),n({title:"Link copied"})},children:[e.jsx(wr,{className:"w-4 h-4 mr-1"}),"Copy Link"]}),e.jsxs(B,{onClick:()=>E(!0),children:[e.jsx(ln,{className:"w-4 h-4 mr-1"}),"Send to Contact"]})]})]})]}),e.jsxs("div",{className:"grid lg:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"lg:col-span-1 space-y-4",children:[e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"Subject Property"})}),e.jsxs(Me,{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:"})," ",((Pe=r.subject.sqft)==null?void 0:Pe.toLocaleString())??"—"]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Year:"})," ",r.subject.yearBuilt??"—"]})]}),me&&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(B,{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"]})]}),!me&&e.jsxs(B,{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(J,{className:"text-xs",children:"Subject SqFt (needed for price band)"}),e.jsx(xe,{type:"number",defaultValue:"",onBlur:async Ze=>{const Se=Number(Ze.target.value);Se>0&&await l.mutateAsync({id:r.id,patch:{subject:{...r.subject,sqft:Se}}})}})]})]})]}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsxs(St,{className:"text-base flex items-center gap-2",children:[e.jsx(uj,{className:"w-4 h-4"}),"Suggested Price"]})}),e.jsxs(Me,{className:"space-y-3",children:[Y!=null&&Y.likely?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"text-3xl font-bold",children:["$",(g&&Number(j.likely)>0?Number(j.likely):Y.likely).toLocaleString()]}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-1",children:["Comps suggest: $",(ze=Y.low)==null?void 0:ze.toLocaleString()," – $",(ke=Y.high)==null?void 0:ke.toLocaleString()]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["$",Y.ppsf,"/sqft median · ",be," 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(J,{htmlFor:"override-toggle",className:"text-sm font-medium",children:"Override with my price"}),e.jsx(fn,{id:"override-toggle",checked:g,onCheckedChange:b})]}),g&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"My suggested price"}),e.jsx(xe,{type:"number",placeholder:"e.g. 750000",value:j.likely,onChange:Ze=>S(Se=>({...Se,likely:Ze.target.value}))})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Range low"}),e.jsx(xe,{type:"number",placeholder:"optional",value:j.low,onChange:Ze=>S(Se=>({...Se,low:Ze.target.value}))})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Range high"}),e.jsx(xe,{type:"number",placeholder:"optional",value:j.high,onChange:Ze=>S(Se=>({...Se,high:Ze.target.value}))})]})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Why this price (optional)"}),e.jsx(Ms,{rows:2,maxLength:500,placeholder:"Notes shown to your client",value:j.note,onChange:Ze=>S(Se=>({...Se,note:Ze.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(E9n,{value:O,onChange:V}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"Filters"})}),e.jsxs(Me,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsxs(J,{className:"text-xs",children:["SqFt tolerance: ±",Math.round(p.sqftPct*100),"%"]}),e.jsx(kx,{value:[p.sqftPct*100],min:5,max:50,step:5,onValueChange:([Ze])=>f(Se=>({...Se,sqftPct:Ze/100}))})]}),e.jsxs("div",{children:[e.jsxs(J,{className:"text-xs",children:["Search radius: ",p.maxMiles," mi"]}),e.jsx(kx,{value:[p.maxMiles],min:1,max:25,step:1,onValueChange:([Ze])=>f(Se=>({...Se,maxMiles:Ze}))})]}),e.jsxs("div",{children:[e.jsxs(J,{className:"text-xs",children:["Sold within: ",p.monthsBack," months"]}),e.jsx(kx,{value:[p.monthsBack],min:1,max:24,step:1,onValueChange:([Ze])=>f(Se=>({...Se,monthsBack:Ze}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{className:"text-xs",children:"Status"}),["Active","Pending","Closed"].map(Ze=>e.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[e.jsx($a,{checked:p.statuses.includes(Ze),onCheckedChange:Se=>f(Fe=>({...Fe,statuses:Se?[...Fe.statuses,Ze]:Fe.statuses.filter(Ne=>Ne!==Ze)}))})," ",Ze]},Ze))]}),e.jsxs(B,{className:"w-full",onClick:Z,disabled:o.isPending,children:[o.isPending?e.jsx(Ct,{className:"w-4 h-4 animate-spin mr-2"}):e.jsx(un,{className:"w-4 h-4 mr-2"}),"Find Comps"]}),e.jsxs(B,{variant:"outline",className:"w-full",onClick:()=>D(!0),children:[e.jsx(rn,{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(ROn,{subject:r.subject,comps:h,radiusMiles:p.maxMiles,onMarkerClick:Ze=>v(Ze)}),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:[be," selected"]})]}),h.length?e.jsx("div",{className:"space-y-2",children:h.map((Ze,Se)=>{var Fe;return e.jsx(ve,{className:Ze.selected?"":"opacity-50",children:e.jsxs(Me,{className:"p-3 flex gap-3 items-center",children:[e.jsx($a,{checked:Ze.selected,onCheckedChange:()=>ne(Se)}),e.jsxs("button",{type:"button",onClick:()=>v(Se),className:"flex gap-3 items-center flex-1 min-w-0 text-left hover:bg-muted/40 -mx-1 px-1 py-1 rounded transition",children:[e.jsx(NAe,{photos:Ze.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:Ze.address}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[Ze.city,", ",Ze.state," · ",Ze.bedrooms??"?","bd/",Ze.bathrooms??"?","ba · ",((Fe=Ze.sqft)==null?void 0:Fe.toLocaleString())??"?"," sqft",Ze.yearBuilt?` · ${Ze.yearBuilt}`:""]}),e.jsxs("div",{className:"text-xs mt-0.5",children:[e.jsx(Oe,{variant:"outline",className:"mr-1",children:Ze.status}),Ze.score!=null&&e.jsxs("span",{className:"text-muted-foreground",children:["Score ",Ze.score]})]})]}),e.jsxs("div",{className:"text-right",children:[e.jsxs("div",{className:"font-semibold",children:["$",(Ze.soldPrice||Ze.price||0).toLocaleString()]}),Ze.sqft&&(Ze.soldPrice||Ze.price)?e.jsxs("div",{className:"text-xs text-muted-foreground",children:["$",Math.round((Ze.soldPrice||Ze.price)/Ze.sqft),"/sqft"]}):null]})]}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>v(Se),title:"View details",children:e.jsx(ya,{className:"w-4 h-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>ce(Se),title:"Remove",children:e.jsx(Sn,{className:"w-4 h-4"})})]})},Se)})}):e.jsx(ve,{children:e.jsx(Me,{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:[me&&e.jsx(B,{variant:"outline",size:"sm",onClick:()=>M(!0),children:"Fill subject details"}),e.jsx(B,{variant:"outline",size:"sm",onClick:()=>D(!0),children:"Add manual comp"})]})]})})})]})]}),e.jsx(Q7t,{comp:y!=null?h[y]:null,open:y!=null,onClose:()=>v(null)}),e.jsx(T9n,{open:P,onOpenChange:M,subject:r.subject,onSave:ie,isSaving:l.isPending}),e.jsx(M9n,{open:I,onOpenChange:D,subject:r.subject,onAdd:te}),e.jsx(XYt,{open:C,onOpenChange:E,cma:r})]})})}const $P="listing-presentations";function sQt(){const{user:s}=hs(),t=Bt(),n=at({queryKey:["listing-presentation-saved-templates",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:o,error:c}=await q.from("listing_presentation_saved_templates").select("*").eq("owner_user_id",s.id).order("updated_at",{ascending:!1});if(c)throw c;return o}}),r=()=>t.invalidateQueries({queryKey:["listing-presentation-saved-templates",s==null?void 0:s.id]}),a=mt({mutationFn:async o=>{const{data:c,error:d}=await q.from("listing_presentation_saved_templates").insert({...o,owner_user_id:s.id}).select().single();if(d)throw d;return c},onSuccess:()=>{r(),se.success("Template saved")},onError:o=>se.error(o.message||"Could not save the template")}),i=mt({mutationFn:async({id:o,...c})=>{const{error:d}=await q.from("listing_presentation_saved_templates").update(c).eq("id",o);if(d)throw d},onSuccess:()=>{r(),se.success("Template updated")},onError:o=>se.error(o.message||"Could not update the template")}),l=mt({mutationFn:async o=>{const{error:c}=await q.from("listing_presentation_saved_templates").delete().eq("id",o);if(c)throw c},onSuccess:()=>{r(),se.success("Template deleted")},onError:o=>se.error(o.message||"Could not delete the template")});return{savedTemplates:n.data??[],isLoading:n.isLoading,save:a,update:i,remove:l}}function L9n(){return at({queryKey:["listing-presentation-templates"],staleTime:10*60*1e3,queryFn:async()=>{const{data:s,error:t}=await q.from("listing_presentation_templates").select("*").eq("is_active",!0).order("sort_order",{ascending:!0});if(t)throw t;return s}})}function nQt(){const{user:s}=hs(),t=Bt(),n=at({queryKey:["listing-presentations",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:c,error:d}=await q.from("listing_presentations").select("*").eq("owner_user_id",s.id).order("updated_at",{ascending:!1});if(d)throw d;return c}}),r=()=>t.invalidateQueries({queryKey:["listing-presentations",s==null?void 0:s.id]}),a=mt({mutationFn:async c=>{const{data:d,error:u}=await q.from("listing_presentations").insert({...c,owner_user_id:s.id}).select().single();if(u)throw u;return d},onSuccess:r,onError:c=>se.error(c.message||"Could not create presentation")}),i=mt({mutationFn:async({id:c,...d})=>{const{data:u,error:h}=await q.from("listing_presentations").update(d).eq("id",c).select().single();if(h)throw h;return u},onSuccess:c=>{r(),t.invalidateQueries({queryKey:["listing-presentation",c.id]})},onError:c=>se.error(c.message||"Could not save presentation")}),l=mt({mutationFn:async c=>{let d=null;const{data:u,error:h}=await q.from("listing_presentations").insert({owner_user_id:s.id,title:`${c.title} (Copy)`,template_id:c.template_id,status:"draft",property_address_line1:c.property_address_line1,city:c.city,state:c.state,postal_code:c.postal_code,list_price:c.list_price,beds:c.beds,baths:c.baths,sqft:c.sqft,agent_snapshot:c.agent_snapshot,co_agent:c.co_agent,custom_pages:c.custom_pages,services:c.services,page_settings:c.page_settings,photo_focal:c.photo_focal}).select().single();if(h)throw h;if(c.property_photo_path){d=`${s.id}/${u.id}/photo.jpg`;const{error:m}=await q.storage.from($P).copy(c.property_photo_path,d);m||await q.from("listing_presentations").update({property_photo_path:d}).eq("id",u.id)}return u},onSuccess:()=>{r(),se.success("Presentation duplicated")},onError:c=>se.error(c.message||"Could not duplicate")}),o=mt({mutationFn:async c=>{const d=[c.property_photo_path,c.pdf_path,c.thumbnail_path].filter(Boolean);d.length&&await q.storage.from($P).remove(d);const{error:u}=await q.from("listing_presentations").delete().eq("id",c.id);if(u)throw u},onSuccess:()=>{r(),se.success("Presentation deleted")},onError:c=>se.error(c.message||"Could not delete")});return{presentations:n.data??[],isLoading:n.isLoading,create:a,update:i,duplicate:l,remove:o}}function I9n(s){return at({queryKey:["listing-presentation",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("listing_presentations").select("*").eq("id",s).maybeSingle();if(n)throw n;return t}})}async function D9n(s,t=3600){if(!s)return null;const{data:n,error:r}=await q.storage.from($P).createSignedUrl(s,t);return r?null:(n==null?void 0:n.signedUrl)??null}const R9n="#2a4c64",F9n="#B8965A";function rQt(){const{user:s}=hs();return at({queryKey:["agent-brand",s==null?void 0:s.id],enabled:!!s,staleTime:5*60*1e3,queryFn:async()=>{const t=s.id,[n,r,a]=await Promise.all([q.from("profiles").select("name, email, phone, avatar_url, website_url, title, brokerage_name, brokerage_id").eq("id",t).maybeSingle(),q.from("lead_sites").select("brand_color, accent_color, agent_license_number, brokerage_license_number, license_state, brokerage_legal_name, team_logo_url, is_active, created_at").eq("agent_id",t).order("created_at",{ascending:!0}).limit(5),q.from("agent_cards").select("brokerage_display_name, brokerage_logo_url, team_logo_url, title, positioning_statement, display_email").eq("user_id",t).maybeSingle()]),i=n.data||{},l=r.data||[],o=l.find(u=>u.is_active)||l[0]||{},c=a.data||{};let d=i.brokerage_name||c.brokerage_display_name||o.brokerage_legal_name||null;if(!d&&i.brokerage_id){const{data:u}=await q.from("brokerages").select("name").eq("id",i.brokerage_id).maybeSingle();d=(u==null?void 0:u.name)||null}return{name:i.name||s.email||"Your Name",headshotUrl:i.avatar_url||null,brokerageName:d,brokerageLogoUrl:c.brokerage_logo_url||c.team_logo_url||o.team_logo_url||null,licenseNumber:o.agent_license_number||null,licenseState:o.license_state||null,phone:i.phone||null,email:c.display_email||i.email||s.email||null,website:i.website_url||null,brandColor:o.brand_color||R9n,accentColor:o.accent_color||F9n,tagline:c.positioning_statement||i.title||c.title||null}}})}const RWe={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."}},O9n={cover:"Cover",welcome:"Marketing commitment",agent:"About your agent",overview:"Marketing plan overview",closing:"Closing commitment"};function aQt(s,t){var i;const n=((i=s==null?void 0:s.copy)==null?void 0:i[t])||{},r=RWe[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 iQt={enabled:!1,name:"",title:null,headshotUrl:null,phone:null,email:null,brokerageName:null,licenseNumber:null,bio:null};function oQt(s){return{...iQt,...s||{}}}const xze=[{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."}],lQt=()=>typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`cp_${Math.random().toString(36).slice(2)}`;function jrt(s,t=0){const n={id:lQt(),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 cQt(s){return Array.isArray(s)?s.filter(t=>t&&typeof t=="object").map((t,n)=>({...jrt(t.layout||"story",n),...t,id:t.id||lQt(),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 FWe={hidden:["overview"]},OWe={x:.5,y:.5},pd=(s,t,n=!0)=>({key:s,label:t,enabled:n}),HTe=[{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:[pd("hdr","Full HDR interior and exterior photo set"),pd("drone","Aerial drone photography of the home and lot"),pd("twilight","Twilight exterior session for the hero image"),pd("staging","Virtual staging for vacant or transitional rooms",!1),pd("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:[pd("walkthrough","Cinematic full-property walkthrough video"),pd("reels","Vertical short-form cuts for Reels, Shorts, and TikTok"),pd("oncamera","On-camera agent introduction to the home"),pd("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:[pd("data","Complete, accurate MLS data so your home shows in every filter"),pd("copy","Copywriting that leads with the features buyers pay for"),pd("pricing","Pricing built on live comparable and absorption data"),pd("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:[pd("zillow","Zillow — the highest-traffic buyer search portal"),pd("realtor","Realtor.com — direct MLS-sourced listing feed"),pd("homes","Homes.com — agent-attributed listing exposure"),pd("others","Redfin, Trulia, Movoto, and hundreds of partner sites"),pd("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:[pd("gallery","Full-screen gallery, video, and floor plan in one place"),pd("mobile","Mobile-first design with a one-tap inquiry form"),pd("link","Shareable link used across ads, email, and QR signage"),pd("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:[pd("organic","Just-listed launch across feed, stories, and reels"),pd("ads","Geo-targeted paid campaigns aimed at active buyers"),pd("retarget","Retargeting so interested viewers keep seeing your home"),pd("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:[pd("database","Direct email to my buyer and past-client database"),pd("agents","Broadcast to area agents with matching buyers"),pd("referral","Referral partner network notified at launch"),pd("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:[pd("public","Strategically timed public open houses"),pd("broker","Broker open house for agents with active buyers"),pd("signin","Digital sign-in that captures every visitor"),pd("neighbors","Neighbor invitations and just-listed mailers"),pd("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:[pd("weekly","Weekly seller report on the schedule you prefer"),pd("feedback","Showing feedback delivered as it comes in"),pd("analytics","Online traffic and engagement analytics"),pd("access","Direct access to me by call, text, or email")]}],z9n=Object.fromEntries(HTe.map(s=>[s.key,(s.options||[]).map(t=>t.label)]));function zWe(s){return s!=null&&s.length?HTe.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}}):HTe.map(t=>{var n;return{...t,options:(n=t.options)==null?void 0:n.map(r=>({...r}))}})}const B9n={welcome:"Marketing commitment",agent:"About your agent",overview:"Marketing plan overview",closing:"Closing commitment"};function Uh(s){"@babel/helpers - typeof";return Uh=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},Uh(s)}var PS=Uint8Array,rj=Uint16Array,Nrt=Int32Array,krt=new PS([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]),Srt=new PS([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]),LNt=new PS([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),dQt=function(s,t){for(var n=new rj(31),r=0;r<31;++r)n[r]=t+=1<>1|(kp&21845)<<1;AT=(AT&52428)>>2|(AT&13107)<<2,AT=(AT&61680)>>4|(AT&3855)<<4,UWe[kp]=((AT&65280)>>8|(AT&255)<<8)>>1}var aee=function(s,t,n){for(var r=s.length,a=0,i=new rj(t);a>c]=d}else for(o=new rj(r),a=0;a>15-s[a]);return o},y9=new PS(288);for(var kp=0;kp<144;++kp)y9[kp]=8;for(var kp=144;kp<256;++kp)y9[kp]=9;for(var kp=256;kp<280;++kp)y9[kp]=7;for(var kp=280;kp<288;++kp)y9[kp]=8;var GTe=new PS(32);for(var kp=0;kp<32;++kp)GTe[kp]=5;var $9n=aee(y9,9,0),V9n=aee(GTe,5,0),hQt=function(s){return(s+7)/8|0},H9n=function(s,t,n){return(n==null||n>s.length)&&(n=s.length),new PS(s.subarray(t,n))},_3=function(s,t,n){n<<=t&7;var r=t/8|0;s[r]|=n,s[r+1]|=n>>8},xZ=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},gze=function(s,t){for(var n=[],r=0;rm&&(m=i[r].s);var p=new rj(m+1),f=qWe(n[u-1],p,0);if(f>t){var r=0,y=0,v=f-t,g=1<t)y+=g-(1<>=v;y>0;){var j=i[r].s;p[j]=0&&y;--r){var S=i[r].s;p[S]==t&&(--p[S],++y)}f=t}return{t:new PS(p),l:f}},qWe=function(s,t,n){return s.s==-1?Math.max(qWe(s.l,t,n+1),qWe(s.r,t,n+1)):t[s.s]=n},DNt=function(s){for(var t=s.length;t&&!s[--t];);for(var n=new rj(++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}},gZ=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[LNt[V-1]];--V);var G=d+5<<3,$=gZ(a,y9)+gZ(i,GTe)+l,H=gZ(a,m)+gZ(i,y)+l+14+3*V+gZ(P,D)+2*P[16]+3*P[17]+7*P[18];if(c>=0&&G<=$&&G<=H)return mQt(t,u,s.subarray(c,c+d));var Y,Z,ne,ce;if(_3(t,u,1+(H<$)),u+=2,H<$){Y=aee(m,p,0),Z=m,ne=aee(y,v,0),ce=y;var ie=aee(D,O,0);_3(t,u,j-257),_3(t,u+5,E-1),_3(t,u+10,V-4),u+=14;for(var M=0;M15&&(_3(t,u,le[M]>>5&127),u+=le[M]>>12)}}else Y=$9n,Z=y9,ne=V9n,ce=GTe;for(var M=0;M255){var be=me>>18&31;xZ(t,u,Y[be+257]),u+=Z[be+257],be>7&&(_3(t,u,me>>23&31),u+=krt[be]);var he=me&31;xZ(t,u,ne[he]),u+=ce[he],he>3&&(xZ(t,u,me>>5&8191),u+=Srt[he])}else xZ(t,u,Y[me]),u+=Z[me]}return xZ(t,u,Y[256]),u+Z[256]},G9n=new Nrt([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),pQt=new PS(0),W9n=function(s,t,n,r,a,i){var l=i.z||s.length,o=new PS(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=G9n[t-1],m=h>>13,p=h&8191,f=(1<7e3||D>24576)&&(Y>423||!d)){u=RNt(s,c,0,S,C,E,M,D,V,I-V,u),D=P=M=0,V=I;for(var Z=0;Z<286;++Z)C[Z]=0;for(var Z=0;Z<30;++Z)E[Z]=0}var ne=2,ce=0,ie=p,te=$-H&32767;if(Y>2&&G==j(I-te))for(var ae=Math.min(m,Y)-1,le=Math.min(32767,I),be=Math.min(258,Y);te<=le&&--ie&&$!=H;){if(s[I+ne]==s[I+ne-te]){for(var me=0;mene){if(ne=me,ce=te,me>ae)break;for(var he=Math.min(te,me-2),pe=0,Z=0;Zpe&&(pe=Pe,H=Ce)}}}$=H,H=y[$],te+=$-H&32767}if(ce){S[D++]=268435456|BWe[ne]<<18|INt[ce];var ze=BWe[ne]&31,ke=INt[ce]&31;M+=krt[ze]+Srt[ke],++C[257+ze],++E[ke],O=I+ne,++P}else S[D++]=s[I],++C[s[I]]}}for(I=Math.max(I,O);I=l&&(c[u/8|0]=d,Ze=l),u=mQt(c,u+1,s.subarray(I,Ze))}i.i=l}return H9n(o,0,r+hQt(u)+a)},fQt=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}}},K9n=function(s,t,n,r,a){if(!a&&(a={l:1},t.dictionary)){var i=t.dictionary.subarray(-32768),l=new PS(i.length+s.length);l.set(i),l.set(s,i.length),s=l,a.w=i.length}return W9n(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)},xQt=function(s,t,n){for(;n;++t)s[t]=n,n>>>=8},Y9n=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=fQt();a.p(t.dictionary),xQt(s,2,a.d())}};function $We(s,t){t||(t={});var n=fQt();n.p(s);var r=K9n(s,t,t.dictionary?6:2,4);return Y9n(r,t),xQt(r,r.length-4,n.d()),r}var Z9n=typeof TextDecoder<"u"&&new TextDecoder,X9n=0;try{Z9n.decode(pQt,{stream:!0}),X9n=1}catch{}function Q9n(s){if(Array.isArray(s))return s}function J9n(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 FNt(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])})(),yze={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 Crt{constructor(t=rzn,n={}){Pr(this,"buffer");Pr(this,"byteLength");Pr(this,"byteOffset");Pr(this,"length");Pr(this,"offset");Pr(this,"lastWrittenByte");Pr(this,"littleEndian");Pr(this,"_data");Pr(this,"_mark");Pr(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 Crt)&&(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=yze[n].BYTES_PER_ELEMENT*t,a=this.byteOffset+this.offset,i=this.buffer.slice(a,a+r);if(this.littleEndian===azn&&n!=="uint8"&&n!=="int8"){const o=new Uint8Array(this.buffer.slice(a,a+r));o.reverse();const c=new yze[n](o.buffer);return this.offset+=r,c.reverse(),c}const l=new yze[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 izn=4,BNt=0,UNt=1,ozn=2;function nK(s){let t=s.length;for(;--t>=0;)s[t]=0}const lzn=0,gQt=1,czn=2,dzn=3,uzn=258,Art=29,Vae=256,vse=Vae+1+Art,z$=30,Ert=19,yQt=2*vse+1,EF=15,vze=16,hzn=7,Trt=256,vQt=16,bQt=17,_Qt=18,VWe=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]),eCe=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]),mzn=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),wQt=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),pzn=512,X3=new Array((vse+2)*2);nK(X3);const iee=new Array(z$*2);nK(iee);const bse=new Array(pzn);nK(bse);const _se=new Array(uzn-dzn+1);nK(_se);const Mrt=new Array(Art);nK(Mrt);const WTe=new Array(z$);nK(WTe);function bze(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 jQt,NQt,kQt;function _ze(s,t){this.dyn_tree=s,this.max_code=0,this.stat_desc=t}const SQt=s=>s<256?bse[s]:bse[256+(s>>>7)],wse=(s,t)=>{s.pending_buf[s.pending++]=t&255,s.pending_buf[s.pending++]=t>>>8&255},C_=(s,t,n)=>{s.bi_valid>vze-n?(s.bi_buf|=t<>vze-s.bi_valid,s.bi_valid+=n-vze):(s.bi_buf|=t<{C_(s,n[t*2],n[t*2+1])},CQt=(s,t)=>{let n=0;do n|=s&1,s>>>=1,n<<=1;while(--t>0);return n>>>1},fzn=s=>{s.bi_valid===16?(wse(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)},xzn=(s,t)=>{const n=t.dyn_tree,r=t.max_code,a=t.stat_desc.static_tree,i=t.stat_desc.has_stree,l=t.stat_desc.extra_bits,o=t.stat_desc.extra_base,c=t.stat_desc.max_length;let d,u,h,m,p,f,y=0;for(m=0;m<=EF;m++)s.bl_count[m]=0;for(n[s.heap[s.heap_max]*2+1]=0,d=s.heap_max+1;dc&&(m=c,y++),n[u*2+1]=m,!(u>r)&&(s.bl_count[m]++,p=0,u>=o&&(p=l[u-o]),f=n[u*2],s.opt_len+=f*(m+p),i&&(s.static_len+=f*(a[u*2+1]+p)));if(y!==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]--,y-=2}while(y>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--)}},AQt=(s,t,n)=>{const r=new Array(EF+1);let a=0,i,l;for(i=1;i<=EF;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]=CQt(r[o]++,o))}},gzn=()=>{let s,t,n,r,a;const i=new Array(EF+1);for(n=0,r=0;r>=7;r{let t;for(t=0;t{s.bi_valid>8?wse(s,s.bi_buf):s.bi_valid>0&&(s.pending_buf[s.pending++]=s.bi_buf),s.bi_buf=0,s.bi_valid=0},qNt=(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?k4(s,a,t):(l=_se[a],k4(s,l+Vae+1,t),o=VWe[l],o!==0&&(a-=Mrt[l],C_(s,a,o)),r--,l=SQt(r),k4(s,l,n),o=eCe[l],o!==0&&(r-=WTe[l],C_(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=yQt,l=0;l>1;l>=1;l--)wze(s,n,l);d=i;do l=s.heap[1],s.heap[1]=s.heap[s.heap_len--],wze(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++,wze(s,n,1);while(s.heap_len>=2);s.heap[--s.heap_max]=s.heap[1],xzn(s,t),AQt(n,c,s.bl_count)},VNt=(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(VNt(s,s.dyn_ltree,s.l_desc.max_code),VNt(s,s.dyn_dtree,s.d_desc.max_code),HWe(s,s.bl_desc),t=Ert-1;t>=3&&s.bl_tree[wQt[t]*2+1]===0;t--);return s.opt_len+=3*(t+1)+5+5+4,t},vzn=(s,t,n,r)=>{let a;for(C_(s,t-257,5),C_(s,n-1,5),C_(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 BNt;if(s.dyn_ltree[9*2]!==0||s.dyn_ltree[10*2]!==0||s.dyn_ltree[13*2]!==0)return UNt;for(n=32;n{GNt||(gzn(),GNt=!0),s.l_desc=new _ze(s.dyn_ltree,jQt),s.d_desc=new _ze(s.dyn_dtree,NQt),s.bl_desc=new _ze(s.bl_tree,kQt),s.bi_buf=0,s.bi_valid=0,EQt(s)},MQt=(s,t,n,r)=>{C_(s,(lzn<<1)+(r?1:0),3),TQt(s),wse(s,n),wse(s,~n),n&&s.pending_buf.set(s.window.subarray(t,t+n),s.pending),s.pending+=n},wzn=s=>{C_(s,gQt<<1,3),k4(s,Trt,X3),fzn(s)},jzn=(s,t,n,r)=>{let a,i,l=0;s.level>0?(s.strm.data_type===ozn&&(s.strm.data_type=bzn(s)),HWe(s,s.l_desc),HWe(s,s.d_desc),l=yzn(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?MQt(s,t,n,r):s.strategy===izn||i===a?(C_(s,(gQt<<1)+(r?1:0),3),$Nt(s,X3,iee)):(C_(s,(czn<<1)+(r?1:0),3),vzn(s,s.l_desc.max_code+1,s.d_desc.max_code+1,l+1),$Nt(s,s.dyn_ltree,s.dyn_dtree)),EQt(s),r&&TQt(s)},Nzn=(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[(_se[n]+Vae+1)*2]++,s.dyn_dtree[SQt(t)*2]++),s.sym_next===s.sym_end);var kzn=_zn,Szn=MQt,Czn=jzn,Azn=Nzn,Ezn=wzn,Tzn={_tr_init:kzn,_tr_stored_block:Szn,_tr_flush_block:Czn,_tr_tally:Azn,_tr_align:Ezn};const Mzn=(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 jse=Mzn;const Pzn=()=>{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},Lzn=new Uint32Array(Pzn()),Izn=(s,t,n,r)=>{const a=Lzn,i=r+n;s^=-1;for(let l=r;l>>8^a[(s^t[l])&255];return s^-1};var ly=Izn,AG={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"},Hae={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:Dzn,_tr_stored_block:GWe,_tr_flush_block:Rzn,_tr_tally:yP,_tr_align:Fzn}=Tzn,{Z_NO_FLUSH:vP,Z_PARTIAL_FLUSH:Ozn,Z_FULL_FLUSH:zzn,Z_FINISH:J2,Z_BLOCK:WNt,Z_OK:av,Z_STREAM_END:KNt,Z_STREAM_ERROR:nC,Z_DATA_ERROR:Bzn,Z_BUF_ERROR:jze,Z_DEFAULT_COMPRESSION:Uzn,Z_FILTERED:qzn,Z_HUFFMAN_ONLY:ede,Z_RLE:$zn,Z_FIXED:Vzn,Z_DEFAULT_STRATEGY:Hzn,Z_UNKNOWN:Gzn,Z_DEFLATED:_8e}=Hae,Wzn=9,Kzn=15,Yzn=8,Zzn=29,Xzn=256,WWe=Xzn+1+Zzn,Qzn=30,Jzn=19,eBn=2*WWe+1,tBn=15,hu=3,CM=258,rC=CM+hu+1,sBn=32,EG=42,Prt=57,KWe=69,YWe=73,ZWe=91,XWe=103,TF=113,TX=666,yb=1,rK=2,v9=3,aK=4,nBn=3,MF=(s,t)=>(s.msg=AG[t],t),YNt=s=>s*2-(s>4?9:0),T6=s=>{let t=s.length;for(;--t>=0;)s[t]=0},rBn=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 aBn=(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))},aj=(s,t)=>{Rzn(s,s.block_start>=0?s.block_start:-1,s.strstart-s.block_start,t),s.block_start=s.strstart,Mw(s.strm)},nh=(s,t)=>{s.pending_buf[s.pending++]=t},yZ=(s,t)=>{s.pending_buf[s.pending++]=t>>>8&255,s.pending_buf[s.pending++]=t&255},QWe=(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=jse(s.adler,t,a,n):s.state.wrap===2&&(s.adler=ly(s.adler,t,a,n)),s.next_in+=a,s.total_in+=a,a)},PQt=(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-rC?s.strstart-(s.w_size-rC):0,d=s.window,u=s.w_mask,h=s.prev,m=s.strstart+CM;let p=d[r+l-1],f=d[r+l];s.prev_length>=s.good_match&&(n>>=2),o>s.lookahead&&(o=s.lookahead);do if(a=t,!(d[a+l]!==f||d[a+l-1]!==p||d[a]!==d[r]||d[++a]!==d[r+1])){r+=2,a++;do;while(d[++r]===d[++a]&&d[++r]===d[++a]&&d[++r]===d[++a]&&d[++r]===d[++a]&&d[++r]===d[++a]&&d[++r]===d[++a]&&d[++r]===d[++a]&&d[++r]===d[++a]&&rl){if(s.match_start=t,l=i,i>=o)break;p=d[r+l-1],f=d[r+l]}}while((t=h[t&u])>c&&--n!==0);return l<=s.lookahead?l:s.lookahead},TG=s=>{const t=s.w_size;let n,r,a;do{if(r=s.window_size-s.lookahead-s.strstart,s.strstart>=t+(t-rC)&&(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),rBn(s),r+=t),s.strm.avail_in===0)break;if(n=QWe(s.strm,s.window,s.strstart+s.lookahead,r),s.lookahead+=n,s.lookahead+s.insert>=hu)for(a=s.strstart-s.insert,s.ins_h=s.window[a],s.ins_h=bP(s,s.ins_h,s.window[a+1]);s.insert&&(s.ins_h=bP(s,s.ins_h,s.window[a+hu-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,Mw(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&&(QWe(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&&(QWe(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===J2)&&t!==vP&&s.strm.avail_in===0&&a<=i)&&(r=a>i?i:a,l=t===J2&&s.strm.avail_in===0&&r===a?1:0,GWe(s,s.block_start,r,l),s.block_start+=r,Mw(s.strm)),l?v9:yb)},Nze=(s,t)=>{let n,r;for(;;){if(s.lookahead=hu&&(s.ins_h=bP(s,s.ins_h,s.window[s.strstart+hu-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-rC&&(s.match_length=PQt(s,n)),s.match_length>=hu)if(r=yP(s,s.strstart-s.match_start,s.match_length-hu),s.lookahead-=s.match_length,s.match_length<=s.max_lazy_match&&s.lookahead>=hu){s.match_length--;do s.strstart++,s.ins_h=bP(s,s.ins_h,s.window[s.strstart+hu-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=bP(s,s.ins_h,s.window[s.strstart+1]);else r=yP(s,0,s.window[s.strstart]),s.lookahead--,s.strstart++;if(r&&(aj(s,!1),s.strm.avail_out===0))return yb}return s.insert=s.strstart{let n,r,a;for(;;){if(s.lookahead=hu&&(s.ins_h=bP(s,s.ins_h,s.window[s.strstart+hu-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=hu-1,n!==0&&s.prev_length4096)&&(s.match_length=hu-1)),s.prev_length>=hu&&s.match_length<=s.prev_length){a=s.strstart+s.lookahead-hu,r=yP(s,s.strstart-1-s.prev_match,s.prev_length-hu),s.lookahead-=s.prev_length-1,s.prev_length-=2;do++s.strstart<=a&&(s.ins_h=bP(s,s.ins_h,s.window[s.strstart+hu-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=hu-1,s.strstart++,r&&(aj(s,!1),s.strm.avail_out===0))return yb}else if(s.match_available){if(r=yP(s,0,s.window[s.strstart-1]),r&&aj(s,!1),s.strstart++,s.lookahead--,s.strm.avail_out===0)return yb}else s.match_available=1,s.strstart++,s.lookahead--}return s.match_available&&(r=yP(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<=CM){if(TG(s),s.lookahead<=CM&&t===vP)return yb;if(s.lookahead===0)break}if(s.match_length=0,s.lookahead>=hu&&s.strstart>0&&(a=s.strstart-1,r=l[a],r===l[++a]&&r===l[++a]&&r===l[++a])){i=s.strstart+CM;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>=hu?(n=yP(s,1,s.match_length-hu),s.lookahead-=s.match_length,s.strstart+=s.match_length,s.match_length=0):(n=yP(s,0,s.window[s.strstart]),s.lookahead--,s.strstart++),n&&(aj(s,!1),s.strm.avail_out===0))return yb}return s.insert=0,t===J2?(aj(s,!0),s.strm.avail_out===0?v9:aK):s.sym_next&&(aj(s,!1),s.strm.avail_out===0)?yb:rK},oBn=(s,t)=>{let n;for(;;){if(s.lookahead===0&&(TG(s),s.lookahead===0)){if(t===vP)return yb;break}if(s.match_length=0,n=yP(s,0,s.window[s.strstart]),s.lookahead--,s.strstart++,n&&(aj(s,!1),s.strm.avail_out===0))return yb}return s.insert=0,t===J2?(aj(s,!0),s.strm.avail_out===0?v9:aK):s.sym_next&&(aj(s,!1),s.strm.avail_out===0)?yb:rK};function N5(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 MX=[new N5(0,0,0,0,LQt),new N5(4,4,8,4,Nze),new N5(4,5,16,8,Nze),new N5(4,6,32,32,Nze),new N5(4,4,16,16,qB),new N5(8,16,32,32,qB),new N5(8,16,128,128,qB),new N5(8,32,128,256,qB),new N5(32,128,258,1024,qB),new N5(32,258,258,4096,qB)],lBn=s=>{s.window_size=2*s.w_size,T6(s.head),s.max_lazy_match=MX[s.level].max_lazy,s.good_match=MX[s.level].good_length,s.nice_match=MX[s.level].nice_length,s.max_chain_length=MX[s.level].max_chain,s.strstart=0,s.block_start=0,s.lookahead=0,s.insert=0,s.match_length=s.prev_length=hu-1,s.match_available=0,s.ins_h=0};function cBn(){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=_8e,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(eBn*2),this.dyn_dtree=new Uint16Array((2*Qzn+1)*2),this.bl_tree=new Uint16Array((2*Jzn+1)*2),T6(this.dyn_ltree),T6(this.dyn_dtree),T6(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(tBn+1),this.heap=new Uint16Array(2*WWe+1),T6(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(2*WWe+1),T6(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 Gae=s=>{if(!s)return 1;const t=s.state;return!t||t.strm!==s||t.status!==EG&&t.status!==Prt&&t.status!==KWe&&t.status!==YWe&&t.status!==ZWe&&t.status!==XWe&&t.status!==TF&&t.status!==TX?1:0},IQt=s=>{if(Gae(s))return MF(s,nC);s.total_in=s.total_out=0,s.data_type=Gzn;const t=s.state;return t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap===2?Prt:t.wrap?EG:TF,s.adler=t.wrap===2?0:1,t.last_flush=-2,Dzn(t),av},DQt=s=>{const t=IQt(s);return t===av&&lBn(s.state),t},dBn=(s,t)=>Gae(s)||s.state.wrap!==2?nC:(s.state.gzhead=t,av),RQt=(s,t,n,r,a,i)=>{if(!s)return nC;let l=1;if(t===Uzn&&(t=6),r<0?(l=0,r=-r):r>15&&(l=2,r-=16),a<1||a>Wzn||n!==_8e||r<8||r>15||t<0||t>9||i<0||i>Vzn||r===8&&l!==1)return MF(s,nC);r===8&&(r=9);const o=new cBn;return s.state=o,o.strm=s,o.status=EG,o.wrap=l,o.gzhead=null,o.w_bits=r,o.w_size=1<RQt(s,t,_8e,Kzn,Yzn,Hzn),hBn=(s,t)=>{if(Gae(s)||t>WNt||t<0)return s?MF(s,nC):nC;const n=s.state;if(!s.output||s.avail_in!==0&&!s.input||n.status===TX&&t!==J2)return MF(s,s.avail_out===0?jze:nC);const r=n.last_flush;if(n.last_flush=t,n.pending!==0){if(Mw(s),s.avail_out===0)return n.last_flush=-1,av}else if(s.avail_in===0&&YNt(t)<=YNt(r)&&t!==J2)return MF(s,jze);if(n.status===TX&&s.avail_in!==0)return MF(s,jze);if(n.status===EG&&n.wrap===0&&(n.status=TF),n.status===EG){let a=_8e+(n.w_bits-8<<4)<<8,i=-1;if(n.strategy>=ede||n.level<2?i=0:n.level<6?i=1:n.level===6?i=2:i=3,a|=i<<6,n.strstart!==0&&(a|=sBn),a+=31-a%31,yZ(n,a),n.strstart!==0&&(yZ(n,s.adler>>>16),yZ(n,s.adler&65535)),s.adler=1,n.status=TF,Mw(s),n.pending!==0)return n.last_flush=-1,av}if(n.status===Prt){if(s.adler=0,nh(n,31),nh(n,139),nh(n,8),n.gzhead)nh(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)),nh(n,n.gzhead.time&255),nh(n,n.gzhead.time>>8&255),nh(n,n.gzhead.time>>16&255),nh(n,n.gzhead.time>>24&255),nh(n,n.level===9?2:n.strategy>=ede||n.level<2?4:0),nh(n,n.gzhead.os&255),n.gzhead.extra&&n.gzhead.extra.length&&(nh(n,n.gzhead.extra.length&255),nh(n,n.gzhead.extra.length>>8&255)),n.gzhead.hcrc&&(s.adler=ly(s.adler,n.pending_buf,n.pending,0)),n.gzindex=0,n.status=KWe;else if(nh(n,0),nh(n,0),nh(n,0),nh(n,0),nh(n,0),nh(n,n.level===9?2:n.strategy>=ede||n.level<2?4:0),nh(n,nBn),n.status=TF,Mw(s),n.pending!==0)return n.last_flush=-1,av}if(n.status===KWe){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=ly(s.adler,n.pending_buf,n.pending-a,a)),n.gzindex+=o,Mw(s),n.pending!==0)return n.last_flush=-1,av;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=ly(s.adler,n.pending_buf,n.pending-a,a)),n.gzindex=0}n.status=YWe}if(n.status===YWe){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=ly(s.adler,n.pending_buf,n.pending-a,a)),Mw(s),n.pending!==0)return n.last_flush=-1,av;a=0}n.gzindexa&&(s.adler=ly(s.adler,n.pending_buf,n.pending-a,a)),n.gzindex=0}n.status=ZWe}if(n.status===ZWe){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=ly(s.adler,n.pending_buf,n.pending-a,a)),Mw(s),n.pending!==0)return n.last_flush=-1,av;a=0}n.gzindexa&&(s.adler=ly(s.adler,n.pending_buf,n.pending-a,a))}n.status=XWe}if(n.status===XWe){if(n.gzhead.hcrc){if(n.pending+2>n.pending_buf_size&&(Mw(s),n.pending!==0))return n.last_flush=-1,av;nh(n,s.adler&255),nh(n,s.adler>>8&255),s.adler=0}if(n.status=TF,Mw(s),n.pending!==0)return n.last_flush=-1,av}if(s.avail_in!==0||n.lookahead!==0||t!==vP&&n.status!==TX){let a=n.level===0?LQt(n,t):n.strategy===ede?oBn(n,t):n.strategy===$zn?iBn(n,t):MX[n.level].func(n,t);if((a===v9||a===aK)&&(n.status=TX),a===yb||a===v9)return s.avail_out===0&&(n.last_flush=-1),av;if(a===rK&&(t===Ozn?Fzn(n):t!==WNt&&(GWe(n,0,0,!1),t===zzn&&(T6(n.head),n.lookahead===0&&(n.strstart=0,n.block_start=0,n.insert=0))),Mw(s),s.avail_out===0))return n.last_flush=-1,av}return t!==J2?av:n.wrap<=0?KNt:(n.wrap===2?(nh(n,s.adler&255),nh(n,s.adler>>8&255),nh(n,s.adler>>16&255),nh(n,s.adler>>24&255),nh(n,s.total_in&255),nh(n,s.total_in>>8&255),nh(n,s.total_in>>16&255),nh(n,s.total_in>>24&255)):(yZ(n,s.adler>>>16),yZ(n,s.adler&65535)),Mw(s),n.wrap>0&&(n.wrap=-n.wrap),n.pending!==0?av:KNt)},mBn=s=>{if(Gae(s))return nC;const t=s.state.status;return s.state=null,t===TF?MF(s,Bzn):av},pBn=(s,t)=>{let n=t.length;if(Gae(s))return nC;const r=s.state,a=r.wrap;if(a===2||a===1&&r.status!==EG||r.lookahead)return nC;if(a===1&&(s.adler=jse(s.adler,t,n,0)),r.wrap=0,n>=r.w_size){a===0&&(T6(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,TG(r);r.lookahead>=hu;){let c=r.strstart,d=r.lookahead-(hu-1);do r.ins_h=bP(r,r.ins_h,r.window[c+hu-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=hu-1,TG(r)}return r.strstart+=r.lookahead,r.block_start=r.strstart,r.insert=r.lookahead,r.lookahead=0,r.match_length=r.prev_length=hu-1,r.match_available=0,s.next_in=l,s.input=o,s.avail_in=i,r.wrap=a,av};var fBn=uBn,xBn=RQt,gBn=DQt,yBn=IQt,vBn=dBn,bBn=hBn,_Bn=mBn,wBn=pBn,jBn="pako deflate (from Nodeca project)",oee={deflateInit:fBn,deflateInit2:xBn,deflateReset:gBn,deflateResetKeep:yBn,deflateSetHeader:vBn,deflate:bBn,deflateEnd:_Bn,deflateSetDictionary:wBn,deflateInfo:jBn};const NBn=(s,t)=>Object.prototype.hasOwnProperty.call(s,t);var kBn=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)NBn(n,r)&&(s[r]=n[r])}}return s},SBn=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;Nse[254]=Nse[254]=1;var CBn=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 ABn=(s,t)=>{if(t<65534&&s.subarray&&FQt)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 ABn(i,a)},TBn=(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+Nse[s[n]]>t?n:t},kse={string2buf:CBn,buf2string:EBn,utf8border:TBn};function MBn(){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 OQt=MBn;const zQt=Object.prototype.toString,{Z_NO_FLUSH:PBn,Z_SYNC_FLUSH:LBn,Z_FULL_FLUSH:IBn,Z_FINISH:DBn,Z_OK:KTe,Z_STREAM_END:RBn,Z_DEFAULT_COMPRESSION:FBn,Z_DEFAULT_STRATEGY:OBn,Z_DEFLATED:zBn}=Hae;function Lrt(s){this.options=w8e.assign({level:FBn,method:zBn,chunkSize:16384,windowBits:15,memLevel:8,strategy:OBn},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 OQt,this.strm.avail_out=0;let n=oee.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(n!==KTe)throw new Error(AG[n]);if(t.header&&oee.deflateSetHeader(this.strm,t.header),t.dictionary){let r;if(typeof t.dictionary=="string"?r=kse.string2buf(t.dictionary):zQt.call(t.dictionary)==="[object ArrayBuffer]"?r=new Uint8Array(t.dictionary):r=t.dictionary,n=oee.deflateSetDictionary(this.strm,r),n!==KTe)throw new Error(AG[n]);this._dict_set=!0}}Lrt.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?DBn:PBn,typeof s=="string"?n.input=kse.string2buf(s):zQt.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===LBn||i===IBn)&&n.avail_out<=6){this.onData(n.output.subarray(0,n.next_out)),n.avail_out=0;continue}if(a=oee.deflate(n,i),a===RBn)return n.next_out>0&&this.onData(n.output.subarray(0,n.next_out)),a=oee.deflateEnd(this.strm),this.onEnd(a),this.ended=!0,a===KTe;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};Lrt.prototype.onData=function(s){this.chunks.push(s)};Lrt.prototype.onEnd=function(s){s===KTe&&(this.result=w8e.flattenChunks(this.chunks)),this.chunks=[],this.err=s,this.msg=this.strm.msg};const tde=16209,BBn=16191;var UBn=function(t,n){let r,a,i,l,o,c,d,u,h,m,p,f,y,v,g,b,j,S,C,E,P,M,I,D;const O=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=O.dmax,d=O.wsize,u=O.whave,h=O.wnext,m=O.window,p=O.hold,f=O.bits,y=O.lencode,v=O.distcode,g=(1<>>24,p>>>=S,f-=S,S=j>>>16&255,S===0)D[i++]=j&65535;else if(S&16){C=j&65535,S&=15,S&&(f>>=S,f-=S),f<15&&(p+=I[r++]<>>24,p>>>=S,f-=S,S=j>>>16&255,S&16){if(E=j&65535,S&=15,fc){t.msg="invalid distance too far back",O.mode=tde;break e}if(p>>>=S,f-=S,S=i-l,E>S){if(S=E-S,S>u&&O.sane){t.msg="invalid distance too far back",O.mode=tde;break e}if(P=0,M=m,h===0){if(P+=d-S,S2;)D[i++]=M[P++],D[i++]=M[P++],D[i++]=M[P++],C-=3;C&&(D[i++]=M[P++],C>1&&(D[i++]=M[P++]))}else{P=i-E;do D[i++]=D[P++],D[i++]=D[P++],D[i++]=D[P++],C-=3;while(C>2);C&&(D[i++]=D[P++],C>1&&(D[i++]=D[P++]))}}else if(S&64){t.msg="invalid distance code",O.mode=tde;break e}else{j=v[(j&65535)+(p&(1<>3,r-=C,f-=C<<3,p&=(1<{const c=o.bits;let d=0,u=0,h=0,m=0,p=0,f=0,y=0,v=0,g=0,b=0,j,S,C,E,P,M=null,I;const D=new Uint16Array($B+1),O=new Uint16Array($B+1);let V=null,G,$,H;for(d=0;d<=$B;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===QNt||m!==1))return-1;for(O[1]=0,d=1;d<$B;d++)O[d+1]=O[d]+D[d];for(u=0;uZNt||s===JNt&&g>XNt)return 1;for(;;){G=d-y,l[u]+1=I?($=V[l[u]-I],H=M[l[u]-I]):($=96,H=0),j=1<>y)+S]=G<<24|$<<16|H|0;while(S!==0);for(j=1<>=1;if(j!==0?(b&=j-1,b+=j):b=0,u++,--D[d]===0){if(d===m)break;d=t[n+l[u]]}if(d>p&&(b&E)!==C){for(y===0&&(y=p),P+=h,f=d-y,v=1<ZNt||s===JNt&&g>XNt)return 1;C=b&E,a[C]=p<<24|f<<16|P-i|0}}return b!==0&&(a[P+b]=d-y<<24|64<<16|0),o.bits=p,0};var lee=GBn;const WBn=0,BQt=1,UQt=2,{Z_FINISH:ekt,Z_BLOCK:KBn,Z_TREES:sde,Z_OK:b9,Z_STREAM_END:YBn,Z_NEED_DICT:ZBn,Z_STREAM_ERROR:MN,Z_DATA_ERROR:qQt,Z_MEM_ERROR:$Qt,Z_BUF_ERROR:XBn,Z_DEFLATED:tkt}=Hae,j8e=16180,skt=16181,nkt=16182,rkt=16183,akt=16184,ikt=16185,okt=16186,lkt=16187,ckt=16188,dkt=16189,YTe=16190,w3=16191,Sze=16192,ukt=16193,Cze=16194,hkt=16195,mkt=16196,pkt=16197,fkt=16198,nde=16199,rde=16200,xkt=16201,gkt=16202,ykt=16203,vkt=16204,bkt=16205,Aze=16206,_kt=16207,wkt=16208,Vp=16209,VQt=16210,HQt=16211,QBn=852,JBn=592,eUn=15,tUn=eUn,jkt=s=>(s>>>24&255)+(s>>>8&65280)+((s&65280)<<8)+((s&255)<<24);function sUn(){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 dz=s=>{if(!s)return 1;const t=s.state;return!t||t.strm!==s||t.modeHQt?1:0},GQt=s=>{if(dz(s))return MN;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=j8e,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(QBn),t.distcode=t.distdyn=new Int32Array(JBn),t.sane=1,t.back=-1,b9},WQt=s=>{if(dz(s))return MN;const t=s.state;return t.wsize=0,t.whave=0,t.wnext=0,GQt(s)},KQt=(s,t)=>{let n;if(dz(s))return MN;const r=s.state;return t<0?(n=0,t=-t):(n=(t>>4)+5,t<48&&(t&=15)),t&&(t<8||t>15)?MN:(r.window!==null&&r.wbits!==t&&(r.window=null),r.wrap=n,r.wbits=t,WQt(s))},YQt=(s,t)=>{if(!s)return MN;const n=new sUn;s.state=n,n.strm=s,n.window=null,n.mode=j8e;const r=KQt(s,t);return r!==b9&&(s.state=null),r},nUn=s=>YQt(s,tUn);let Nkt=!0,Eze,Tze;const rUn=s=>{if(Nkt){Eze=new Int32Array(512),Tze=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(lee(BQt,s.lens,0,288,Eze,0,s.work,{bits:9}),t=0;t<32;)s.lens[t++]=5;lee(UQt,s.lens,0,32,Tze,0,s.work,{bits:5}),Nkt=!1}s.lencode=Eze,s.lenbits=9,s.distcode=Tze,s.distbits=5},ZQt=(s,t,n,r)=>{let a;const i=s.state;return i.window===null&&(i.wsize=1<=i.wsize?(i.window.set(t.subarray(n-i.wsize,n),0),i.wnext=0,i.whave=i.wsize):(a=i.wsize-i.wnext,a>r&&(a=r),i.window.set(t.subarray(n-r,n-r+a),i.wnext),r-=a,r?(i.window.set(t.subarray(n-r,n),0),i.wnext=r,i.whave=i.wsize):(i.wnext+=a,i.wnext===i.wsize&&(i.wnext=0),i.whave{let n,r,a,i,l,o,c,d,u,h,m,p,f,y,v=0,g,b,j,S,C,E,P,M;const I=new Uint8Array(4);let D,O;const V=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(dz(s)||!s.output||!s.input&&s.avail_in!==0)return MN;n=s.state,n.mode===w3&&(n.mode=Sze),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=b9;e:for(;;)switch(n.mode){case j8e:if(n.wrap===0){n.mode=Sze;break}for(;u<16;){if(o===0)break e;o--,d+=r[i++]<>>8&255,n.check=ly(n.check,I,2,0),d=0,u=0,n.mode=skt;break}if(n.head&&(n.head.done=!1),!(n.wrap&1)||(((d&255)<<8)+(d>>8))%31){s.msg="incorrect header check",n.mode=Vp;break}if((d&15)!==tkt){s.msg="unknown compression method",n.mode=Vp;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=Vp;break}n.dmax=1<>8&1),n.flags&512&&n.wrap&4&&(I[0]=d&255,I[1]=d>>>8&255,n.check=ly(n.check,I,2,0)),d=0,u=0,n.mode=nkt;case nkt: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=ly(n.check,I,4,0)),d=0,u=0,n.mode=rkt;case rkt: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=ly(n.check,I,2,0)),d=0,u=0,n.mode=akt;case akt:if(n.flags&1024){for(;u<16;){if(o===0)break e;o--,d+=r[i++]<>>8&255,n.check=ly(n.check,I,2,0)),d=0,u=0}else n.head&&(n.head.extra=null);n.mode=ikt;case ikt: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=ly(n.check,r,p,i)),o-=p,i+=p,n.length-=p),n.length))break e;n.length=0,n.mode=okt;case okt: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=w3;break;case dkt:for(;u<32;){if(o===0)break e;o--,d+=r[i++]<>>=u&7,u-=u&7,n.mode=Aze;break}for(;u<3;){if(o===0)break e;o--,d+=r[i++]<>>=1,u-=1,d&3){case 0:n.mode=ukt;break;case 1:if(rUn(n),n.mode=nde,t===sde){d>>>=2,u-=2;break e}break;case 2:n.mode=mkt;break;case 3:s.msg="invalid block type",n.mode=Vp}d>>>=2,u-=2;break;case ukt: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=Vp;break}if(n.length=d&65535,d=0,u=0,n.mode=Cze,t===sde)break e;case Cze:n.mode=hkt;case hkt: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=w3;break;case mkt: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=Vp;break}n.have=0,n.mode=pkt;case pkt:for(;n.have>>=3,u-=3}for(;n.have<19;)n.lens[V[n.have++]]=0;if(n.lencode=n.lendyn,n.lenbits=7,D={bits:n.lenbits},M=lee(WBn,n.lens,0,19,n.lencode,0,n.work,D),n.lenbits=D.bits,M){s.msg="invalid code lengths set",n.mode=Vp;break}n.have=0,n.mode=fkt;case fkt:for(;n.have>>24,b=v>>>16&255,j=v&65535,!(g<=u);){if(o===0)break e;o--,d+=r[i++]<>>=g,u-=g,n.lens[n.have++]=j;else{if(j===16){for(O=g+2;u>>=g,u-=g,n.have===0){s.msg="invalid bit length repeat",n.mode=Vp;break}P=n.lens[n.have-1],p=3+(d&3),d>>>=2,u-=2}else if(j===17){for(O=g+3;u>>=g,u-=g,P=0,p=3+(d&7),d>>>=3,u-=3}else{for(O=g+7;u>>=g,u-=g,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=Vp;break}for(;p--;)n.lens[n.have++]=P}}if(n.mode===Vp)break;if(n.lens[256]===0){s.msg="invalid code -- missing end-of-block",n.mode=Vp;break}if(n.lenbits=9,D={bits:n.lenbits},M=lee(BQt,n.lens,0,n.nlen,n.lencode,0,n.work,D),n.lenbits=D.bits,M){s.msg="invalid literal/lengths set",n.mode=Vp;break}if(n.distbits=6,n.distcode=n.distdyn,D={bits:n.distbits},M=lee(UQt,n.lens,n.nlen,n.ndist,n.distcode,0,n.work,D),n.distbits=D.bits,M){s.msg="invalid distances set",n.mode=Vp;break}if(n.mode=nde,t===sde)break e;case nde:n.mode=rde;case rde: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,UBn(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===w3&&(n.back=-1);break}for(n.back=0;v=n.lencode[d&(1<>>24,b=v>>>16&255,j=v&65535,!(g<=u);){if(o===0)break e;o--,d+=r[i++]<>S)],g=v>>>24,b=v>>>16&255,j=v&65535,!(S+g<=u);){if(o===0)break e;o--,d+=r[i++]<>>=S,u-=S,n.back+=S}if(d>>>=g,u-=g,n.back+=g,n.length=j,b===0){n.mode=bkt;break}if(b&32){n.back=-1,n.mode=w3;break}if(b&64){s.msg="invalid literal/length code",n.mode=Vp;break}n.extra=b&15,n.mode=xkt;case xkt:if(n.extra){for(O=n.extra;u>>=n.extra,u-=n.extra,n.back+=n.extra}n.was=n.length,n.mode=gkt;case gkt:for(;v=n.distcode[d&(1<>>24,b=v>>>16&255,j=v&65535,!(g<=u);){if(o===0)break e;o--,d+=r[i++]<>S)],g=v>>>24,b=v>>>16&255,j=v&65535,!(S+g<=u);){if(o===0)break e;o--,d+=r[i++]<>>=S,u-=S,n.back+=S}if(d>>>=g,u-=g,n.back+=g,b&64){s.msg="invalid distance code",n.mode=Vp;break}n.offset=j,n.extra=b&15,n.mode=ykt;case ykt:if(n.extra){for(O=n.extra;u>>=n.extra,u-=n.extra,n.back+=n.extra}if(n.offset>n.dmax){s.msg="invalid distance too far back",n.mode=Vp;break}n.mode=vkt;case vkt: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=Vp;break}p>n.wnext?(p-=n.wnext,f=n.wsize-p):f=n.wnext-p,p>n.length&&(p=n.length),y=n.window}else y=a,f=l-n.offset,p=n.length;p>c&&(p=c),c-=p,n.length-=p;do a[l++]=y[f++];while(--p);n.length===0&&(n.mode=rde);break;case bkt:if(c===0)break e;a[l++]=n.length,c--,n.mode=rde;break;case Aze:if(n.wrap){for(;u<32;){if(o===0)break e;o--,d|=r[i++]<{if(dz(s))return MN;let t=s.state;return t.window&&(t.window=null),s.state=null,b9},oUn=(s,t)=>{if(dz(s))return MN;const n=s.state;return n.wrap&2?(n.head=t,t.done=!1,b9):MN},lUn=(s,t)=>{const n=t.length;let r,a,i;return dz(s)||(r=s.state,r.wrap!==0&&r.mode!==YTe)?MN:r.mode===YTe&&(a=1,a=jse(a,t,n,0),a!==r.check)?qQt:(i=ZQt(s,t,n,n),i?(r.mode=VQt,$Qt):(r.havedict=1,b9))};var cUn=WQt,dUn=KQt,uUn=GQt,hUn=nUn,mUn=YQt,pUn=aUn,fUn=iUn,xUn=oUn,gUn=lUn,yUn="pako inflate (from Nodeca project)",Q3={inflateReset:cUn,inflateReset2:dUn,inflateResetKeep:uUn,inflateInit:hUn,inflateInit2:mUn,inflate:pUn,inflateEnd:fUn,inflateGetHeader:xUn,inflateSetDictionary:gUn,inflateInfo:yUn};function vUn(){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 bUn=vUn;const XQt=Object.prototype.toString,{Z_NO_FLUSH:_Un,Z_FINISH:wUn,Z_OK:Sse,Z_STREAM_END:Mze,Z_NEED_DICT:Pze,Z_STREAM_ERROR:jUn,Z_DATA_ERROR:kkt,Z_MEM_ERROR:NUn}=Hae;function Wae(s){this.options=w8e.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 OQt,this.strm.avail_out=0;let n=Q3.inflateInit2(this.strm,t.windowBits);if(n!==Sse)throw new Error(AG[n]);if(this.header=new bUn,Q3.inflateGetHeader(this.strm,this.header),t.dictionary&&(typeof t.dictionary=="string"?t.dictionary=kse.string2buf(t.dictionary):XQt.call(t.dictionary)==="[object ArrayBuffer]"&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(n=Q3.inflateSetDictionary(this.strm,t.dictionary),n!==Sse)))throw new Error(AG[n])}Wae.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?wUn:_Un,XQt.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=Q3.inflate(n,l),i===Pze&&a&&(i=Q3.inflateSetDictionary(n,a),i===Sse?i=Q3.inflate(n,l):i===kkt&&(i=Pze));n.avail_in>0&&i===Mze&&n.state.wrap>0&&s[n.next_in]!==0;)Q3.inflateReset(n),i=Q3.inflate(n,l);switch(i){case jUn:case kkt:case Pze:case NUn:return this.onEnd(i),this.ended=!0,!1}if(o=n.avail_out,n.next_out&&(n.avail_out===0||i===Mze))if(this.options.to==="string"){let c=kse.utf8border(n.output,n.next_out),d=n.next_out-c,u=kse.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===Sse&&o===0)){if(i===Mze)return i=Q3.inflateEnd(this.strm),this.onEnd(i),this.ended=!0,!0;if(n.avail_in===0)break}}return!0};Wae.prototype.onData=function(s){this.chunks.push(s)};Wae.prototype.onEnd=function(s){s===Sse&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=w8e.flattenChunks(this.chunks)),this.chunks=[],this.err=s,this.msg=this.strm.msg};function Irt(s,t){const n=new Wae(t);if(n.push(s),n.err)throw n.msg||AG[n.err];return n.result}function kUn(s,t){return t=t||{},t.raw=!0,Irt(s,t)}var SUn=Wae,CUn=Irt,AUn=kUn,EUn=Irt,TUn=Hae,MUn={Inflate:SUn,inflate:CUn,inflateRaw:AUn,ungzip:EUn,constants:TUn};const{Inflate:PUn,inflate:LUn,inflateRaw:ewr,ungzip:twr}=MUn;var Skt=PUn,IUn=LUn;const QQt=[];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;QQt[s]=t}const Ckt=4294967295;function DUn(s,t,n){let r=s;for(let a=0;a>>8;return r}function RUn(s,t){return(DUn(Ckt,s,t)^Ckt)>>>0}function Akt(s,t,n){const r=s.readUint32(),a=RUn(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 JQt(s,t,n){for(let r=0;r>1)&255}else{for(;i>1)&255;for(;i>1)&255}}function nJt(s,t,n,r,a){let i=0;if(n.length===0){for(;i=n||E>=r))for(let P=0;P>8&255}const VUn=new Uint16Array([255]),HUn=new Uint8Array(VUn.buffer),GUn=HUn[0]===255,WUn=new Uint8Array(0);function Ekt(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=WUn,u=0,h,m;for(let p=0;p>8&255}const tCe=Uint8Array.of(137,80,78,71,13,10,26,10);function Tkt(s){if(!YUn(s.readBytes(tCe.length)))throw new Error("wrong PNG signature")}function YUn(s){if(s.length79)throw new Error("keyword length must be between 1 and 79")}const JUn=/^[\u0000-\u00FF]*$/;function eqn(s){if(!JUn.test(s))throw new Error("invalid latin1 text")}function tqn(s,t,n){const r=aJt(t);s[r]=sqn(t,n-r.length-1)}function aJt(s){for(s.mark();s.readByte()!==XUn;);const t=s.offset;s.reset();const n=rJt.decode(s.readBytes(t-s.offset-1));return s.skip(1),QUn(n),n}function sqn(s,t){return rJt.decode(s.readBytes(t))}const _w={UNKNOWN:-1,GREYSCALE:0,TRUECOLOUR:2,INDEXED_COLOUR:3,GREYSCALE_ALPHA:4,TRUECOLOUR_ALPHA:6},Lze={UNKNOWN:-1,DEFLATE:0},Mkt={UNKNOWN:-1,ADAPTIVE:0},Ize={UNKNOWN:-1,NO_INTERLACE:0,ADAM7:1},ade={NONE:0,BACKGROUND:1,PREVIOUS:2},Dze={SOURCE:0,OVER:1};class nqn extends Crt{constructor(n,r={}){super(n);Pr(this,"_checkCrc");Pr(this,"_inflator");Pr(this,"_png");Pr(this,"_apng");Pr(this,"_end");Pr(this,"_hasPalette");Pr(this,"_palette");Pr(this,"_hasTransparency");Pr(this,"_transparency");Pr(this,"_compressionMethod");Pr(this,"_filterMethod");Pr(this,"_interlaceMethod");Pr(this,"_colorType");Pr(this,"_isAnimated");Pr(this,"_numberOfFrames");Pr(this,"_numberOfPlays");Pr(this,"_frames");Pr(this,"_writingDataChunks");const{checkCrc:a=!1}=r;this._checkCrc=a,this._inflator=new Skt,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=Lze.UNKNOWN,this._filterMethod=Mkt.UNKNOWN,this._interlaceMethod=Ize.UNKNOWN,this._colorType=_w.UNKNOWN,this._isAnimated=!1,this._numberOfFrames=1,this._numberOfPlays=0,this._frames=[],this._writingDataChunks=!1,this.setBigEndian()}decode(){for(Tkt(this);!this._end;){const n=this.readUint32(),r=this.readChars(4);this.decodeChunk(n,r)}return this.decodeImage(),this._png}decodeApng(){for(Tkt(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 ZUn:tqn(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?Akt(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?Akt(this,n+4,r):this.skip(4)}decodeIHDR(){const n=this._png;n.width=this.readUint32(),n.height=this.readUint32(),n.depth=rqn(this.readUint8());const r=this.readUint8();this._colorType=r;let a;switch(r){case _w.GREYSCALE:a=1;break;case _w.TRUECOLOUR:a=3;break;case _w.INDEXED_COLOUR:a=1;break;case _w.GREYSCALE_ALPHA:a=2;break;case _w.TRUECOLOUR_ALPHA:a=4;break;case _w.UNKNOWN:default:throw new Error(`Unknown color type: ${r}`)}if(this._png.channels=a,this._compressionMethod=this.readUint8(),this._compressionMethod!==Lze.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 Dze.SOURCE:for(let l=0;l=200&&t.status<=299}function ide(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 HR=ic.saveAs||((typeof window>"u"?"undefined":Uh(window))!=="object"||window!==ic?function(){}:typeof HTMLAnchorElement<"u"&&"download"in HTMLAnchorElement.prototype?function(s,t,n){var r=ic.URL||ic.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?Lkt(a.href)?Fze(s,t,n):ide(a,a.target="_blank"):ide(a)):(a.href=r.createObjectURL(s),setTimeout(function(){r.revokeObjectURL(a.href)},4e4),setTimeout(function(){ide(a)},0))}:"msSaveOrOpenBlob"in navigator?function(s,t,n){if(t=t||s.name||"download",typeof s=="string")if(Lkt(s))Fze(s,t,n);else{var r=document.createElement("a");r.href=s,r.target="_blank",setTimeout(function(){ide(r)})}else navigator.msSaveOrOpenBlob(function(a,i){return i===void 0?i={autoBom:!1}:Uh(i)!=="object"&&(Sm.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 Fze(s,t,n);var a=s.type==="application/octet-stream",i=/constructor/i.test(ic.HTMLElement)||ic.safari,l=/CriOS\/[\d]+/.test(navigator.userAgent);if((l||a&&i)&&(typeof FileReader>"u"?"undefined":Uh(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=ic.URL||ic.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 iJt(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 sCe=ic.atob.bind(ic),Ikt=ic.btoa.bind(ic);/** * @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 Oze(s,t){var n=s[0],r=s[1],a=s[2],i=s[3];n=Kv(n,r,a,i,t[0],7,-680876936),i=Kv(i,n,r,a,t[1],12,-389564586),a=Kv(a,i,n,r,t[2],17,606105819),r=Kv(r,a,i,n,t[3],22,-1044525330),n=Kv(n,r,a,i,t[4],7,-176418897),i=Kv(i,n,r,a,t[5],12,1200080426),a=Kv(a,i,n,r,t[6],17,-1473231341),r=Kv(r,a,i,n,t[7],22,-45705983),n=Kv(n,r,a,i,t[8],7,1770035416),i=Kv(i,n,r,a,t[9],12,-1958414417),a=Kv(a,i,n,r,t[10],17,-42063),r=Kv(r,a,i,n,t[11],22,-1990404162),n=Kv(n,r,a,i,t[12],7,1804603682),i=Kv(i,n,r,a,t[13],12,-40341101),a=Kv(a,i,n,r,t[14],17,-1502002290),n=Yv(n,r=Kv(r,a,i,n,t[15],22,1236535329),a,i,t[1],5,-165796510),i=Yv(i,n,r,a,t[6],9,-1069501632),a=Yv(a,i,n,r,t[11],14,643717713),r=Yv(r,a,i,n,t[0],20,-373897302),n=Yv(n,r,a,i,t[5],5,-701558691),i=Yv(i,n,r,a,t[10],9,38016083),a=Yv(a,i,n,r,t[15],14,-660478335),r=Yv(r,a,i,n,t[4],20,-405537848),n=Yv(n,r,a,i,t[9],5,568446438),i=Yv(i,n,r,a,t[14],9,-1019803690),a=Yv(a,i,n,r,t[3],14,-187363961),r=Yv(r,a,i,n,t[8],20,1163531501),n=Yv(n,r,a,i,t[13],5,-1444681467),i=Yv(i,n,r,a,t[2],9,-51403784),a=Yv(a,i,n,r,t[7],14,1735328473),n=Zv(n,r=Yv(r,a,i,n,t[12],20,-1926607734),a,i,t[5],4,-378558),i=Zv(i,n,r,a,t[8],11,-2022574463),a=Zv(a,i,n,r,t[11],16,1839030562),r=Zv(r,a,i,n,t[14],23,-35309556),n=Zv(n,r,a,i,t[1],4,-1530992060),i=Zv(i,n,r,a,t[4],11,1272893353),a=Zv(a,i,n,r,t[7],16,-155497632),r=Zv(r,a,i,n,t[10],23,-1094730640),n=Zv(n,r,a,i,t[13],4,681279174),i=Zv(i,n,r,a,t[0],11,-358537222),a=Zv(a,i,n,r,t[3],16,-722521979),r=Zv(r,a,i,n,t[6],23,76029189),n=Zv(n,r,a,i,t[9],4,-640364487),i=Zv(i,n,r,a,t[12],11,-421815835),a=Zv(a,i,n,r,t[15],16,530742520),n=Xv(n,r=Zv(r,a,i,n,t[2],23,-995338651),a,i,t[0],6,-198630844),i=Xv(i,n,r,a,t[7],10,1126891415),a=Xv(a,i,n,r,t[14],15,-1416354905),r=Xv(r,a,i,n,t[5],21,-57434055),n=Xv(n,r,a,i,t[12],6,1700485571),i=Xv(i,n,r,a,t[3],10,-1894986606),a=Xv(a,i,n,r,t[10],15,-1051523),r=Xv(r,a,i,n,t[1],21,-2054922799),n=Xv(n,r,a,i,t[8],6,1873313359),i=Xv(i,n,r,a,t[15],10,-30611744),a=Xv(a,i,n,r,t[6],15,-1560198380),r=Xv(r,a,i,n,t[13],21,1309151649),n=Xv(n,r,a,i,t[4],6,-145523070),i=Xv(i,n,r,a,t[11],10,-1120210379),a=Xv(a,i,n,r,t[2],15,718787259),r=Xv(r,a,i,n,t[9],21,-343485551),s[0]=AM(n,s[0]),s[1]=AM(r,s[1]),s[2]=AM(a,s[2]),s[3]=AM(i,s[3])}function N8e(s,t,n,r,a,i){return t=AM(AM(t,s),AM(r,i)),AM(t<>>32-a,n)}function Kv(s,t,n,r,a,i,l){return N8e(t&n|~t&r,s,t,a,i,l)}function Yv(s,t,n,r,a,i,l){return N8e(t&r|n&~r,s,t,a,i,l)}function Zv(s,t,n,r,a,i,l){return N8e(t^n^r,s,t,a,i,l)}function Xv(s,t,n,r,a,i,l){return N8e(n^(t|~r),s,t,a,i,l)}function oJt(s){var t,n=s.length,r=[1732584193,-271733879,-1732584194,271733878];for(t=64;t<=s.length;t+=64)Oze(r,iqn(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(Oze(r,a),t=0;t<16;t++)a[t]=0;return a[14]=8*n,Oze(r,a),r}function iqn(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 Dkt="0123456789abcdef".split("");function oqn(s){for(var t="",n=0;n<4;n++)t+=Dkt[s>>8*n+4&15]+Dkt[s>>8*n&15];return t}function lqn(s){return String.fromCharCode(255&s,(65280&s)>>8,(16711680&s)>>16,(4278190080&s)>>24)}function JWe(s){return oJt(s).map(lqn).join("")}var cqn=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 eKe(s,t){var n,r,a,i;if(s!==n){for(var l=(a=s,i=1+(256/s.length|0),new Array(i+1).join(a)),o=[],c=0;c<256;c++)o[c]=c;var d=0;for(c=0;c<256;c++){var u=o[c];d=(d+u+l.charCodeAt(c))%256,o[c]=o[d],o[d]=u}n=s,r=o}else o=r;var h=t.length,m=0,p=0,f="";for(c=0;c€/\f©þdSiz";var i=(t+this.padding).substr(0,32),l=(n+this.padding).substr(0,32);this.O=this.processOwnerPassword(i,l),this.P=-(1+(255^a)),this.encryptionKey=JWe(i+this.O+this.lsbFirstWord(this.P)+this.hexToBytes(r)).substr(0,5),this.U=eKe(this.encryptionKey,this.padding)}function NU(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 Fkt(s){if(Uh(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){ic.console&&Sm.error("jsPDF PubSub Error",o.message,o)}l[1]&&a.push(i)}a.length&&a.forEach(this.unsubscribe)}},this.getTopics=function(){return t}}function ZTe(s){if(!(this instanceof ZTe))return new ZTe(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 lJt(s,t){this.gState=s,this.matrix=t,this.id="",this.objectNumber=-1}function nF(s,t,n,r,a){if(!(this instanceof nF))return new nF(s,t,n,r,a);this.type=s==="axial"?2:3,this.coords=t,this.colors=n,lJt.call(this,r,a)}function hq(s,t,n,r,a){if(!(this instanceof hq))return new hq(s,t,n,r,a);this.boundingBox=s,this.xStep=t,this.yStep=n,this.stream="",this.cloneIndex=0,lJt.call(this,r,a)}function Mo(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;Uh(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=Fkt;var f="1.3",y=p.__private__.getPdfVersion=function(){return f};p.__private__.setPdfVersion=function(ot){f=ot};var v={a0:[2383.94,3370.39],a1:[1683.78,2383.94],a2:[1190.55,1683.78],a3:[841.89,1190.55],a4:[595.28,841.89],a5:[419.53,595.28],a6:[297.64,419.53],a7:[209.76,297.64],a8:[147.4,209.76],a9:[104.88,147.4],a10:[73.7,104.88],b0:[2834.65,4008.19],b1:[2004.09,2834.65],b2:[1417.32,2004.09],b3:[1000.63,1417.32],b4:[708.66,1000.63],b5:[498.9,708.66],b6:[354.33,498.9],b7:[249.45,354.33],b8:[175.75,249.45],b9:[124.72,175.75],b10:[87.87,124.72],c0:[2599.37,3676.54],c1:[1836.85,2599.37],c2:[1298.27,1836.85],c3:[918.43,1298.27],c4:[649.13,918.43],c5:[459.21,649.13],c6:[323.15,459.21],c7:[229.61,323.15],c8:[161.57,229.61],c9:[113.39,161.57],c10:[79.37,113.39],dl:[311.81,623.62],letter:[612,792],"government-letter":[576,756],legal:[612,1008],"junior-legal":[576,360],ledger:[1224,792],tabloid:[792,1224],"credit-card":[153,243]};p.__private__.getPageFormats=function(){return v};var g=p.__private__.getPageFormat=function(ot){return v[ot]};a=a||"a4";var b="compat",j="advanced",S=b;function C(){this.saveGraphicsState(),Fe(new Wn(Xt,0,0,-Xt,0,Om()*Xt).toString()+" cm"),this.setFontSize(this.getFontSize()/Xt),d="n",S=j}function E(){this.restoreGraphicsState(),d="S",S=b}var P=p.__private__.combineFontStyleAndFontWeight=function(ot,Jt){if(ot=="bold"&&Jt=="normal"||ot=="bold"&&Jt==400||ot=="normal"&&Jt=="italic"||ot=="bold"&&Jt=="italic")throw new Error("Invalid Combination of fontweight and fontstyle");return Jt&&(ot=Jt==400||Jt==="normal"?ot==="italic"?"italic":"normal":Jt!=700&&Jt!=="bold"||ot!=="normal"?(Jt==700?"bold":Jt)+""+ot:"bold"),ot};p.advancedAPI=function(ot){var Jt=S===b;return Jt&&C.call(this),typeof ot!="function"||(ot(this),Jt&&E.call(this)),this},p.compatAPI=function(ot){var Jt=S===j;return Jt&&E.call(this),typeof ot!="function"||(ot(this),Jt&&C.call(this)),this},p.isAdvancedAPI=function(){return S===j};var M,I=function(ot){if(S!==j)throw new Error(ot+" is only available in 'advanced' API mode. You need to call advancedAPI() first.")},D=p.roundToPrecision=p.__private__.roundToPrecision=function(ot,Jt){var qs=t||Jt;if(isNaN(ot)||isNaN(qs))throw new Error("Invalid argument passed to jsPDF.roundToPrecision");return ot.toFixed(qs).replace(/0+$/,"")};M=p.hpf=p.__private__.hpf=typeof c=="number"?function(ot){if(isNaN(ot))throw new Error("Invalid argument passed to jsPDF.hpf");return D(ot,c)}:c==="smart"?function(ot){if(isNaN(ot))throw new Error("Invalid argument passed to jsPDF.hpf");return D(ot,ot>-1&&ot<1?16:5)}:function(ot){if(isNaN(ot))throw new Error("Invalid argument passed to jsPDF.hpf");return D(ot,16)};var O=p.f2=p.__private__.f2=function(ot){if(isNaN(ot))throw new Error("Invalid argument passed to jsPDF.f2");return D(ot,2)},V=p.__private__.f3=function(ot){if(isNaN(ot))throw new Error("Invalid argument passed to jsPDF.f3");return D(ot,3)},G=p.scale=p.__private__.scale=function(ot){if(isNaN(ot))throw new Error("Invalid argument passed to jsPDF.scale");return S===b?ot*Xt:S===j?ot:void 0},$=function(ot){return G(function(Jt){return S===b?Om()-Jt:S===j?Jt:void 0}(ot))};p.__private__.setPrecision=p.setPrecision=function(ot){typeof parseInt(ot,10)=="number"&&(t=parseInt(ot,10))};var H,Y="00000000000000000000000000000000",Z=p.__private__.getFileId=function(){return Y},ne=p.__private__.setFileId=function(ot){return Y=ot!==void 0&&/^[a-fA-F0-9]{32}$/.test(ot)?ot.toUpperCase():Y.split("").map(function(){return"ABCDEF0123456789".charAt(Math.floor(16*Math.random()))}).join(""),u!==null&&(Jo=new jU(u.userPermissions,u.userPassword,u.ownerPassword,Y)),Y};p.setFileId=function(ot){return ne(ot),this},p.getFileId=function(){return Z()};var ce=p.__private__.convertDateToPDFDate=function(ot){var Jt=ot.getTimezoneOffset(),qs=Jt<0?"+":"-",Xs=Math.floor(Math.abs(Jt/60)),An=Math.abs(Jt%60),zr=[qs,be(Xs),"'",be(An),"'"].join("");return["D:",ot.getFullYear(),be(ot.getMonth()+1),be(ot.getDate()),be(ot.getHours()),be(ot.getMinutes()),be(ot.getSeconds()),zr].join("")},ie=p.__private__.convertPDFDateToDate=function(ot){var Jt=parseInt(ot.substr(2,4),10),qs=parseInt(ot.substr(6,2),10)-1,Xs=parseInt(ot.substr(8,2),10),An=parseInt(ot.substr(10,2),10),zr=parseInt(ot.substr(12,2),10),Wr=parseInt(ot.substr(14,2),10);return new Date(Jt,qs,Xs,An,zr,Wr,0)},te=p.__private__.setCreationDate=function(ot){var Jt;if(ot===void 0&&(ot=new Date),ot instanceof Date)Jt=ce(ot);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(ot))throw new Error("Invalid argument passed to jsPDF.setCreationDate");Jt=ot}return H=Jt},ae=p.__private__.getCreationDate=function(ot){var Jt=H;return ot==="jsDate"&&(Jt=ie(H)),Jt};p.setCreationDate=function(ot){return te(ot),this},p.getCreationDate=function(ot){return ae(ot)};var le,be=p.__private__.padd2=function(ot){return("0"+parseInt(ot)).slice(-2)},me=p.__private__.padd2Hex=function(ot){return("00"+(ot=ot.toString())).substr(ot.length)},he=0,pe=[],Ce=[],Ae=0,Pe=[],ze=[],ke=!1,Ze=Ce;p.__private__.setCustomOutputDestination=function(ot){ke=!0,Ze=ot};var Se=function(ot){ke||(Ze=ot)};p.__private__.resetCustomOutputDestination=function(){ke=!1,Ze=Ce};var Fe=p.__private__.out=function(ot){return ot=ot.toString(),Ae+=ot.length+1,Ze.push(ot),Ze},Ne=p.__private__.write=function(ot){return Fe(arguments.length===1?ot.toString():Array.prototype.join.call(arguments," "))},Ye=p.__private__.getArrayBuffer=function(ot){for(var Jt=ot.length,qs=new ArrayBuffer(Jt),Xs=new Uint8Array(qs);Jt--;)Xs[Jt]=ot.charCodeAt(Jt);return qs},Ve=[["Helvetica","helvetica","normal","WinAnsiEncoding"],["Helvetica-Bold","helvetica","bold","WinAnsiEncoding"],["Helvetica-Oblique","helvetica","italic","WinAnsiEncoding"],["Helvetica-BoldOblique","helvetica","bolditalic","WinAnsiEncoding"],["Courier","courier","normal","WinAnsiEncoding"],["Courier-Bold","courier","bold","WinAnsiEncoding"],["Courier-Oblique","courier","italic","WinAnsiEncoding"],["Courier-BoldOblique","courier","bolditalic","WinAnsiEncoding"],["Times-Roman","times","normal","WinAnsiEncoding"],["Times-Bold","times","bold","WinAnsiEncoding"],["Times-Italic","times","italic","WinAnsiEncoding"],["Times-BoldItalic","times","bolditalic","WinAnsiEncoding"],["ZapfDingbats","zapfdingbats","normal",null],["Symbol","symbol","normal",null]];p.__private__.getStandardFonts=function(){return Ve};var qe=s.fontSize||16;p.__private__.setFontSize=p.setFontSize=function(ot){return qe=S===j?ot/Xt:ot,this};var Qe,Ue=p.__private__.getFontSize=p.getFontSize=function(){return S===b?qe:qe*Xt},Xe=s.R2L||!1;p.__private__.setR2L=p.setR2L=function(ot){return Xe=ot,this},p.__private__.getR2L=p.getR2L=function(){return Xe};var nt,$e=p.__private__.setZoomMode=function(ot){if(/^(?:\d+\.\d*|\d*\.\d+|\d+)%$/.test(ot))Qe=ot;else if(isNaN(ot)){if([void 0,null,"fullwidth","fullheight","fullpage","original"].indexOf(ot)===-1)throw new Error('zoom must be Integer (e.g. 2), a percentage Value (e.g. 300%) or fullwidth, fullheight, fullpage, original. "'+ot+'" is not recognized.');Qe=ot}else Qe=parseInt(ot,10)};p.__private__.getZoomMode=function(){return Qe};var Ge,ct=p.__private__.setPageMode=function(ot){if([void 0,null,"UseNone","UseOutlines","UseThumbs","FullScreen"].indexOf(ot)==-1)throw new Error('Page mode must be one of UseNone, UseOutlines, UseThumbs, or FullScreen. "'+ot+'" is not recognized.');nt=ot};p.__private__.getPageMode=function(){return nt};var xt=p.__private__.setLayoutMode=function(ot){if([void 0,null,"continuous","single","twoleft","tworight","two"].indexOf(ot)==-1)throw new Error('Layout mode must be one of continuous, single, twoleft, tworight. "'+ot+'" is not recognized.');Ge=ot};p.__private__.getLayoutMode=function(){return Ge},p.__private__.setDisplayMode=p.setDisplayMode=function(ot,Jt,qs){return $e(ot),xt(Jt),ct(qs),this};var qt={title:"",subject:"",author:"",keywords:"",creator:""};p.__private__.getDocumentProperty=function(ot){if(Object.keys(qt).indexOf(ot)===-1)throw new Error("Invalid argument passed to jsPDF.getDocumentProperty");return qt[ot]},p.__private__.getDocumentProperties=function(){return qt},p.__private__.setDocumentProperties=p.setProperties=p.setDocumentProperties=function(ot){for(var Jt in qt)qt.hasOwnProperty(Jt)&&ot[Jt]&&(qt[Jt]=ot[Jt]);return this},p.__private__.setDocumentProperty=function(ot,Jt){if(Object.keys(qt).indexOf(ot)===-1)throw new Error("Invalid arguments passed to jsPDF.setDocumentProperty");return qt[ot]=Jt};var Vt,Xt,fs,Ft,wt,Ts={},vt={},$s=[],As={},jn={},ar={},Dn={},Ur=null,Vs=0,hn=[],dr=new Fkt(p),Cn=s.hotfixes||[],Yn={},on={},Ir=[],Wn=function ot(Jt,qs,Xs,An,zr,Wr){if(!(this instanceof ot))return new ot(Jt,qs,Xs,An,zr,Wr);isNaN(Jt)&&(Jt=1),isNaN(qs)&&(qs=0),isNaN(Xs)&&(Xs=0),isNaN(An)&&(An=1),isNaN(zr)&&(zr=0),isNaN(Wr)&&(Wr=0),this._matrix=[Jt,qs,Xs,An,zr,Wr]};Object.defineProperty(Wn.prototype,"sx",{get:function(){return this._matrix[0]},set:function(ot){this._matrix[0]=ot}}),Object.defineProperty(Wn.prototype,"shy",{get:function(){return this._matrix[1]},set:function(ot){this._matrix[1]=ot}}),Object.defineProperty(Wn.prototype,"shx",{get:function(){return this._matrix[2]},set:function(ot){this._matrix[2]=ot}}),Object.defineProperty(Wn.prototype,"sy",{get:function(){return this._matrix[3]},set:function(ot){this._matrix[3]=ot}}),Object.defineProperty(Wn.prototype,"tx",{get:function(){return this._matrix[4]},set:function(ot){this._matrix[4]=ot}}),Object.defineProperty(Wn.prototype,"ty",{get:function(){return this._matrix[5]},set:function(ot){this._matrix[5]=ot}}),Object.defineProperty(Wn.prototype,"a",{get:function(){return this._matrix[0]},set:function(ot){this._matrix[0]=ot}}),Object.defineProperty(Wn.prototype,"b",{get:function(){return this._matrix[1]},set:function(ot){this._matrix[1]=ot}}),Object.defineProperty(Wn.prototype,"c",{get:function(){return this._matrix[2]},set:function(ot){this._matrix[2]=ot}}),Object.defineProperty(Wn.prototype,"d",{get:function(){return this._matrix[3]},set:function(ot){this._matrix[3]=ot}}),Object.defineProperty(Wn.prototype,"e",{get:function(){return this._matrix[4]},set:function(ot){this._matrix[4]=ot}}),Object.defineProperty(Wn.prototype,"f",{get:function(){return this._matrix[5]},set:function(ot){this._matrix[5]=ot}}),Object.defineProperty(Wn.prototype,"rotation",{get:function(){return Math.atan2(this.shx,this.sx)}}),Object.defineProperty(Wn.prototype,"scaleX",{get:function(){return this.decompose().scale.sx}}),Object.defineProperty(Wn.prototype,"scaleY",{get:function(){return this.decompose().scale.sy}}),Object.defineProperty(Wn.prototype,"isIdentity",{get:function(){return this.sx===1&&this.shy===0&&this.shx===0&&this.sy===1&&this.tx===0&&this.ty===0}}),Wn.prototype.join=function(ot){return[this.sx,this.shy,this.shx,this.sy,this.tx,this.ty].map(M).join(ot)},Wn.prototype.multiply=function(ot){var Jt=ot.sx*this.sx+ot.shy*this.shx,qs=ot.sx*this.shy+ot.shy*this.sy,Xs=ot.shx*this.sx+ot.sy*this.shx,An=ot.shx*this.shy+ot.sy*this.sy,zr=ot.tx*this.sx+ot.ty*this.shx+this.tx,Wr=ot.tx*this.shy+ot.ty*this.sy+this.ty;return new Wn(Jt,qs,Xs,An,zr,Wr)},Wn.prototype.decompose=function(){var ot=this.sx,Jt=this.shy,qs=this.shx,Xs=this.sy,An=this.tx,zr=this.ty,Wr=Math.sqrt(ot*ot+Jt*Jt),Ar=(ot/=Wr)*qs+(Jt/=Wr)*Xs;qs-=ot*Ar,Xs-=Jt*Ar;var wi=Math.sqrt(qs*qs+Xs*Xs);return Ar/=wi,ot*(Xs/=wi)>16&255,Xs=wi>>8&255,An=255&wi}if(Xs===void 0||zr===void 0&&qs===Xs&&Xs===An)Jt=typeof qs=="string"?qs+" "+Wr[0]:ot.precision===2?O(qs/255)+" "+Wr[0]:V(qs/255)+" "+Wr[0];else if(zr===void 0||Uh(zr)==="object"){if(zr&&!isNaN(zr.a)&&zr.a===0)return["1.","1.","1.",Wr[1]].join(" ");Jt=typeof qs=="string"?[qs,Xs,An,Wr[1]].join(" "):ot.precision===2?[O(qs/255),O(Xs/255),O(An/255),Wr[1]].join(" "):[V(qs/255),V(Xs/255),V(An/255),Wr[1]].join(" ")}else Jt=typeof qs=="string"?[qs,Xs,An,zr,Wr[2]].join(" "):ot.precision===2?[O(qs),O(Xs),O(An),O(zr),Wr[2]].join(" "):[V(qs),V(Xs),V(An),V(zr),Wr[2]].join(" ");return Jt},Mt=p.__private__.getFilters=function(){return l},es=p.__private__.putStream=function(ot){var Jt=(ot=ot||{}).data||"",qs=ot.filters||Mt(),Xs=ot.alreadyAppliedFilters||[],An=ot.addLength1||!1,zr=Jt.length,Wr=ot.objectId,Ar=function(Ci){return Ci};if(u!==null&&Wr===void 0)throw new Error("ObjectId must be passed to putStream for file encryption");u!==null&&(Ar=Jo.encryptor(Wr,0));var wi={};qs===!0&&(qs=["FlateEncode"]);var Po=ot.additionalKeyValues||[],bo=(wi=Mo.API.processDataByFilters!==void 0?Mo.API.processDataByFilters(Jt,qs):{data:Jt,reverseChain:[]}).reverseChain+(Array.isArray(Xs)?Xs.join(" "):Xs.toString());if(wi.data.length!==0&&(Po.push({key:"Length",value:wi.data.length}),An===!0&&Po.push({key:"Length1",value:zr})),bo.length!=0)if(bo.split("/").length-1==1)Po.push({key:"Filter",value:bo});else{Po.push({key:"Filter",value:"["+bo+"]"});for(var Vl=0;Vl>"),wi.data.length!==0&&(Fe("stream"),Fe(Ar(wi.data)),Fe("endstream"))},ps=p.__private__.putPage=function(ot){var Jt=ot.number,qs=ot.data,Xs=ot.objId,An=ot.contentsObjId;Bn(Xs,!0),Fe("<>"),Fe("endobj");var zr=qs.join(` `);return S===j&&(zr+=` Q`),Bn(An,!0),es({data:zr,filters:Mt(),objectId:An}),Fe("endobj"),Xs},Is=p.__private__.putPages=function(){var ot,Jt,qs=[];for(ot=1;ot<=Vs;ot++)hn[ot].objId=Ys(),hn[ot].contentsObjId=Ys();for(ot=1;ot<=Vs;ot++)qs.push(ps({number:ot,data:ze[ot],objId:hn[ot].objId,contentsObjId:hn[ot].contentsObjId,mediaBox:hn[ot].mediaBox,cropBox:hn[ot].cropBox,bleedBox:hn[ot].bleedBox,trimBox:hn[ot].trimBox,artBox:hn[ot].artBox,userUnit:hn[ot].userUnit,rootDictionaryObjId:Wt,resourceDictionaryObjId:rt}));Bn(Wt,!0),Fe("<>"),Fe("endobj"),dr.publish("postPutPages")},js=function(ot){dr.publish("putFont",{font:ot,out:Fe,newObject:Ws,putStream:es}),ot.isAlreadyPutted!==!0&&(ot.objectNumber=Ws(),Fe("<<"),Fe("/Type /Font"),Fe("/BaseFont /"+NU(ot.postScriptName)),Fe("/Subtype /Type1"),typeof ot.encoding=="string"&&Fe("/Encoding /"+ot.encoding),Fe("/FirstChar 32"),Fe("/LastChar 255"),Fe(">>"),Fe("endobj"))},Kt=function(ot){ot.objectNumber=Ws();var Jt=[];Jt.push({key:"Type",value:"/XObject"}),Jt.push({key:"Subtype",value:"/Form"}),Jt.push({key:"BBox",value:"["+[M(ot.x),M(ot.y),M(ot.x+ot.width),M(ot.y+ot.height)].join(" ")+"]"}),Jt.push({key:"Matrix",value:"["+ot.matrix.toString()+"]"});var qs=ot.pages[1].join(` `);es({data:qs,additionalKeyValues:Jt,objectId:ot.objectNumber}),Fe("endobj")},Qs=function(ot,Jt){Jt||(Jt=21);var qs=Ws(),Xs=function(Wr,Ar){var wi,Po=[],bo=1/(Ar-1);for(wi=0;wi<1;wi+=bo)Po.push(wi);if(Po.push(1),Wr[0].offset!=0){var Vl={offset:0,color:Wr[0].color};Wr.unshift(Vl)}if(Wr[Wr.length-1].offset!=1){var cd={offset:1,color:Wr[Wr.length-1].color};Wr.push(cd)}for(var $r="",fi=0,Ci=0;CiWr[fi+1].offset;)fi++;var tc=Wr[fi].offset,Hc=(wi-tc)/(Wr[fi+1].offset-tc),ho=Wr[fi].color,Xh=Wr[fi+1].color;$r+=me(Math.round((1-Hc)*ho[0]+Hc*Xh[0]).toString(16))+me(Math.round((1-Hc)*ho[1]+Hc*Xh[1]).toString(16))+me(Math.round((1-Hc)*ho[2]+Hc*Xh[2]).toString(16))}return $r.trim()}(ot.colors,Jt),An=[];An.push({key:"FunctionType",value:"0"}),An.push({key:"Domain",value:"[0.0 1.0]"}),An.push({key:"Size",value:"["+Jt+"]"}),An.push({key:"BitsPerSample",value:"8"}),An.push({key:"Range",value:"[0.0 1.0 0.0 1.0 0.0 1.0]"}),An.push({key:"Decode",value:"[0.0 1.0 0.0 1.0 0.0 1.0]"}),es({data:Xs,additionalKeyValues:An,alreadyAppliedFilters:["/ASCIIHexDecode"],objectId:qs}),Fe("endobj"),ot.objectNumber=Ws(),Fe("<< /ShadingType "+ot.type),Fe("/ColorSpace /DeviceRGB");var zr="/Coords ["+M(parseFloat(ot.coords[0]))+" "+M(parseFloat(ot.coords[1]))+" ";ot.type===2?zr+=M(parseFloat(ot.coords[2]))+" "+M(parseFloat(ot.coords[3])):zr+=M(parseFloat(ot.coords[2]))+" "+M(parseFloat(ot.coords[3]))+" "+M(parseFloat(ot.coords[4]))+" "+M(parseFloat(ot.coords[5])),Fe(zr+="]"),ot.matrix&&Fe("/Matrix ["+ot.matrix.toString()+"]"),Fe("/Function "+qs+" 0 R"),Fe("/Extend [true true]"),Fe(">>"),Fe("endobj")},an=function(ot,Jt){var qs=Ys(),Xs=Ws();Jt.push({resourcesOid:qs,objectOid:Xs}),ot.objectNumber=Xs;var An=[];An.push({key:"Type",value:"/Pattern"}),An.push({key:"PatternType",value:"1"}),An.push({key:"PaintType",value:"1"}),An.push({key:"TilingType",value:"1"}),An.push({key:"BBox",value:"["+ot.boundingBox.map(M).join(" ")+"]"}),An.push({key:"XStep",value:M(ot.xStep)}),An.push({key:"YStep",value:M(ot.yStep)}),An.push({key:"Resources",value:qs+" 0 R"}),ot.matrix&&An.push({key:"Matrix",value:"["+ot.matrix.toString()+"]"}),es({data:ot.stream,additionalKeyValues:An,objectId:ot.objectNumber}),Fe("endobj")},er=function(ot){for(var Jt in ot.objectNumber=Ws(),Fe("<<"),ot)switch(Jt){case"opacity":Fe("/ca "+O(ot[Jt]));break;case"stroke-opacity":Fe("/CA "+O(ot[Jt]))}Fe(">>"),Fe("endobj")},Xr=function(ot){Bn(ot.resourcesOid,!0),Fe("<<"),Fe("/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]"),function(){for(var Jt in Fe("/Font <<"),Ts)Ts.hasOwnProperty(Jt)&&(h===!1||h===!0&&m.hasOwnProperty(Jt))&&Fe("/"+Jt+" "+Ts[Jt].objectNumber+" 0 R");Fe(">>")}(),function(){if(Object.keys(As).length>0){for(var Jt in Fe("/Shading <<"),As)As.hasOwnProperty(Jt)&&As[Jt]instanceof nF&&As[Jt].objectNumber>=0&&Fe("/"+Jt+" "+As[Jt].objectNumber+" 0 R");dr.publish("putShadingPatternDict"),Fe(">>")}}(),function(Jt){if(Object.keys(As).length>0){for(var qs in Fe("/Pattern <<"),As)As.hasOwnProperty(qs)&&As[qs]instanceof p.TilingPattern&&As[qs].objectNumber>=0&&As[qs].objectNumber>")}}(ot.objectOid),function(){if(Object.keys(ar).length>0){var Jt;for(Jt in Fe("/ExtGState <<"),ar)ar.hasOwnProperty(Jt)&&ar[Jt].objectNumber>=0&&Fe("/"+Jt+" "+ar[Jt].objectNumber+" 0 R");dr.publish("putGStateDict"),Fe(">>")}}(),function(){for(var Jt in Fe("/XObject <<"),Yn)Yn.hasOwnProperty(Jt)&&Yn[Jt].objectNumber>=0&&Fe("/"+Jt+" "+Yn[Jt].objectNumber+" 0 R");dr.publish("putXobjectDict"),Fe(">>")}(),Fe(">>"),Fe("endobj")},ma=function(ot){vt[ot.fontName]=vt[ot.fontName]||{},vt[ot.fontName][ot.fontStyle]=ot.id},Br=function(ot,Jt,qs,Xs,An){var zr={id:"F"+(Object.keys(Ts).length+1).toString(10),postScriptName:ot,fontName:Jt,fontStyle:qs,encoding:Xs,isStandardFont:An||!1,metadata:{}};return dr.publish("addFont",{font:zr,instance:this}),Ts[zr.id]=zr,ma(zr),zr.id},sa=p.__private__.pdfEscape=p.pdfEscape=function(ot,Jt){return function(qs,Xs){var An,zr,Wr,Ar,wi,Po,bo,Vl,cd;if(Wr=(Xs=Xs||{}).sourceEncoding||"Unicode",wi=Xs.outputEncoding,(Xs.autoencode||wi)&&Ts[Vt].metadata&&Ts[Vt].metadata[Wr]&&Ts[Vt].metadata[Wr].encoding&&(Ar=Ts[Vt].metadata[Wr].encoding,!wi&&Ts[Vt].encoding&&(wi=Ts[Vt].encoding),!wi&&Ar.codePages&&(wi=Ar.codePages[0]),typeof wi=="string"&&(wi=Ar[wi]),wi)){for(bo=!1,Po=[],An=0,zr=qs.length;An>8&&(bo=!0);qs=Po.join("")}for(An=qs.length;bo===void 0&&An!==0;)qs.charCodeAt(An-1)>>8&&(bo=!0),An--;if(!bo)return qs;for(Po=Xs.noBOM?[]:[254,255],An=0,zr=qs.length;An>8)>>8)throw new Error("Character at position "+An+" of string '"+qs+"' exceeds 16bits. Cannot be encoded into UCS-2 BE");Po.push(cd),Po.push(Vl-(cd<<8))}return String.fromCharCode.apply(void 0,Po)}(ot,Jt).replace(/\\/g,"\\\\").replace(/\(/g,"\\(").replace(/\)/g,"\\)")},Rr=p.__private__.beginPage=function(ot){ze[++Vs]=[],hn[Vs]={objId:0,contentsObjId:0,userUnit:Number(o),artBox:null,bleedBox:null,cropBox:null,trimBox:null,mediaBox:{bottomLeftX:0,bottomLeftY:0,topRightX:Number(ot[0]),topRightY:Number(ot[1])}},Gi(Vs),Se(ze[le])},ra=function(ot,Jt){var qs,Xs,An;switch(n=Jt||n,typeof ot=="string"&&(qs=g(ot.toLowerCase()),Array.isArray(qs)&&(Xs=qs[0],An=qs[1])),Array.isArray(ot)&&(Xs=ot[0]*Xt,An=ot[1]*Xt),isNaN(Xs)&&(Xs=a[0],An=a[1]),(Xs>14400||An>14400)&&(Sm.warn("A page in a PDF can not be wider or taller than 14400 userUnit. jsPDF limits the width/height to 14400"),Xs=Math.min(14400,Xs),An=Math.min(14400,An)),a=[Xs,An],n.substr(0,1)){case"l":An>Xs&&(a=[An,Xs]);break;case"p":Xs>An&&(a=[An,Xs])}Rr(a),fg(Ua),Fe(Xf),Yu!==0&&Fe(Yu+" J"),Yh!==0&&Fe(Yh+" j"),dr.publish("addPage",{pageNumber:Vs})},Si=function(ot){ot>0&&ot<=Vs&&(ze.splice(ot,1),hn.splice(ot,1),Vs--,le>Vs&&(le=Vs),this.setPage(le))},Gi=function(ot){ot>0&&ot<=Vs&&(le=ot)},rl=p.__private__.getNumberOfPages=p.getNumberOfPages=function(){return ze.length-1},Ii=function(ot,Jt,qs){var Xs,An=void 0;return qs=qs||{},ot=ot!==void 0?ot:Ts[Vt].fontName,Jt=Jt!==void 0?Jt:Ts[Vt].fontStyle,Xs=ot.toLowerCase(),vt[Xs]!==void 0&&vt[Xs][Jt]!==void 0?An=vt[Xs][Jt]:vt[ot]!==void 0&&vt[ot][Jt]!==void 0?An=vt[ot][Jt]:qs.disableWarning===!1&&Sm.warn("Unable to look up font label for font '"+ot+"', '"+Jt+"'. Refer to getFontList() for available fonts."),An||qs.noFallback||(An=vt.times[Jt])==null&&(An=vt.times.normal),An},Ta=p.__private__.putInfo=function(){var ot=Ws(),Jt=function(Xs){return Xs};for(var qs in u!==null&&(Jt=Jo.encryptor(ot,0)),Fe("<<"),Fe("/Producer ("+sa(Jt("jsPDF "+Mo.version))+")"),qt)qt.hasOwnProperty(qs)&&qt[qs]&&Fe("/"+qs.substr(0,1).toUpperCase()+qs.substr(1)+" ("+sa(Jt(qt[qs]))+")");Fe("/CreationDate ("+sa(Jt(H))+")"),Fe(">>"),Fe("endobj")},eo=p.__private__.putCatalog=function(ot){var Jt=(ot=ot||{}).rootDictionaryObjId||Wt;switch(Ws(),Fe("<<"),Fe("/Type /Catalog"),Fe("/Pages "+Jt+" 0 R"),Qe||(Qe="fullwidth"),Qe){case"fullwidth":Fe("/OpenAction [3 0 R /FitH null]");break;case"fullheight":Fe("/OpenAction [3 0 R /FitV null]");break;case"fullpage":Fe("/OpenAction [3 0 R /Fit]");break;case"original":Fe("/OpenAction [3 0 R /XYZ null null 1]");break;default:var qs=""+Qe;qs.substr(qs.length-1)==="%"&&(Qe=parseInt(Qe)/100),typeof Qe=="number"&&Fe("/OpenAction [3 0 R /XYZ null null "+O(Qe)+"]")}switch(Ge||(Ge="continuous"),Ge){case"continuous":Fe("/PageLayout /OneColumn");break;case"single":Fe("/PageLayout /SinglePage");break;case"two":case"twoleft":Fe("/PageLayout /TwoColumnLeft");break;case"tworight":Fe("/PageLayout /TwoColumnRight")}nt&&Fe("/PageMode /"+nt),dr.publish("putCatalog"),Fe(">>"),Fe("endobj")},So=p.__private__.putTrailer=function(){Fe("trailer"),Fe("<<"),Fe("/Size "+(he+1)),Fe("/Root "+he+" 0 R"),Fe("/Info "+(he-1)+" 0 R"),u!==null&&Fe("/Encrypt "+Jo.oid+" 0 R"),Fe("/ID [ <"+Y+"> <"+Y+"> ]"),Fe(">>")},Ra=p.__private__.putHeader=function(){Fe("%PDF-"+f),Fe("%ºß¬à")},Eo=p.__private__.putXRef=function(){var ot="0000000000";Fe("xref"),Fe("0 "+(he+1)),Fe("0000000000 65535 f ");for(var Jt=1;Jt<=he;Jt++)typeof pe[Jt]=="function"?Fe((ot+pe[Jt]()).slice(-10)+" 00000 n "):pe[Jt]!==void 0?Fe((ot+pe[Jt]).slice(-10)+" 00000 n "):Fe("0000000000 00000 n ")},Ro=p.__private__.buildDocument=function(){var ot;he=0,Ae=0,Ce=[],pe=[],Pe=[],Wt=Ys(),rt=Ys(),Se(Ce),dr.publish("buildDocument"),Ra(),Is(),function(){dr.publish("putAdditionalObjects");for(var qs=0;qs"),Fe("/O <"+Jo.toHexString(Jo.O)+">"),Fe("/P "+Jo.P),Fe(">>"),Fe("endobj")),Ta(),eo();var Jt=Ae;return Eo(),So(),Fe("startxref"),Fe(""+Jt),Fe("%%EOF"),Se(ze[le]),Ce.join(` `)},di=p.__private__.getBlob=function(ot){return new Blob([Ye(ot)],{type:"application/pdf"})},rr=function(ot){for(;ot.firstChild;)ot.removeChild(ot.firstChild)},oi=function(ot){var Jt,qs=ot.document,Xs=qs.documentElement,An=qs.head,zr=qs.body;return An||(An=qs.createElement("head"),Xs.appendChild(An)),zr||(zr=qs.createElement("body"),Xs.appendChild(zr)),rr(An),rr(zr),(Jt=qs.createElement("style")).appendChild(qs.createTextNode("html, body { padding: 0; margin: 0; } iframe { width: 100%; height: 100%; border: 0;}")),An.appendChild(Jt),{document:qs,body:zr}},Oo=p.output=p.__private__.output=(Gs=function(ot,Jt){switch(typeof(Jt=Jt||{})=="string"?Jt={filename:Jt}:Jt.filename=Jt.filename||"generated.pdf",ot){case void 0:return Ro();case"save":p.save(Jt.filename);break;case"arraybuffer":return Ye(Ro());case"blob":return di(Ro());case"bloburi":case"bloburl":if(ic.URL!==void 0&&typeof ic.URL.createObjectURL=="function")return ic.URL&&ic.URL.createObjectURL(di(Ro()))||void 0;Sm.warn("bloburl is not supported by your system, because URL.createObjectURL is not supported by your browser.");break;case"datauristring":case"dataurlstring":var qs="",Xs=Ro();try{qs=Ikt(Xs)}catch{qs=Ikt(unescape(encodeURIComponent(Xs)))}return"data:application/pdf;filename="+encodeURIComponent(Jt.filename)+";base64,"+qs;case"pdfobjectnewwindow":if(Object.prototype.toString.call(ic)==="[object Window]"){var An="https://cdnjs.cloudflare.com/ajax/libs/pdfobject/2.1.1/pdfobject.min.js",zr=!Jt.pdfObjectUrl;zr||(An=Jt.pdfObjectUrl);var Wr=ic.open();if(Wr!==null){var Ar=oi(Wr),wi=Ar.document.createElement("script"),Po=this;wi.src=An,zr&&(wi.integrity="sha512-4ze/a9/4jqu+tX9dfOqJYSvyYd5M6qum/3HpCLr+/Jqf0whc37VUbkpNGHR7/8pSnCFw47T1fmIpwBV7UySh3g==",wi.crossOrigin="anonymous"),wi.onload=function(){Wr.PDFObject.embed(Po.output("dataurlstring"),Jt)},Ar.body.appendChild(wi)}return Wr}throw new Error("The option pdfobjectnewwindow just works in a browser-environment.");case"pdfjsnewwindow":if(Object.prototype.toString.call(ic)==="[object Window]"){var bo=Jt.pdfJsUrl||"examples/PDF.js/web/viewer.html",Vl=ic.open();if(Vl!==null){var cd=oi(Vl),$r=cd.document.createElement("iframe"),fi=bo.indexOf("?")===-1?"?":"&";Po=this,$r.id="pdfViewer",$r.width="500px",$r.height="400px",$r.src=bo+fi+"file=&downloadName="+encodeURIComponent(Jt.filename),$r.onload=function(){Vl.document.title=Jt.filename,$r.contentWindow.PDFViewerApplication.open(Po.output("bloburl"))},cd.body.appendChild($r)}return Vl}throw new Error("The option pdfjsnewwindow just works in a browser-environment.");case"dataurlnewwindow":if(Object.prototype.toString.call(ic)!=="[object Window]")throw new Error("The option dataurlnewwindow just works in a browser-environment.");var Ci=ic.open();if(Ci!==null){var tc=oi(Ci),Hc=tc.document.createElement("iframe");Hc.src=this.output("datauristring",Jt),tc.body.appendChild(Hc),Ci.document.title=Jt.filename}if(Ci||typeof safari>"u")return Ci;break;case"datauri":case"dataurl":return ic.document.location.href=this.output("datauristring",Jt);default:return null}},Gs.foo=function(){try{return Gs.apply(this,arguments)}catch(qs){var ot=qs.stack||"";~ot.indexOf(" at ")&&(ot=ot.split(" at ")[1]);var Jt="Error in function "+ot.split(` `)[0].split("<")[0]+": "+qs.message;if(!ic.console)throw new Error(Jt);ic.console.error(Jt,qs),ic.alert&&alert(Jt)}},Gs.foo.bar=Gs,Gs.foo),kl=function(ot){return Array.isArray(Cn)===!0&&Cn.indexOf(ot)>-1};switch(r){case"pt":Xt=1;break;case"mm":Xt=72/25.4;break;case"cm":Xt=72/2.54;break;case"in":Xt=72;break;case"px":Xt=kl("px_scaling")==1?.75:96/72;break;case"pc":case"em":Xt=12;break;case"ex":Xt=6;break;default:if(typeof r!="number")throw new Error("Invalid unit: "+r);Xt=r}var Jo=null;te(),ne();var Sl=p.__private__.getPageInfo=p.getPageInfo=function(ot){if(isNaN(ot)||ot%1!=0)throw new Error("Invalid argument passed to jsPDF.getPageInfo");return{objId:hn[ot].objId,pageNumber:ot,pageContext:hn[ot]}},vu=p.__private__.getPageInfoByObjId=function(ot){if(isNaN(ot)||ot%1!=0)throw new Error("Invalid argument passed to jsPDF.getPageInfoByObjId");for(var Jt in hn)if(hn[Jt].objId===ot)break;return Sl(Jt)},Ku=p.__private__.getCurrentPageInfo=p.getCurrentPageInfo=function(){return{objId:hn[le].objId,pageNumber:le,pageContext:hn[le]}};p.addPage=function(){return ra.apply(this,arguments),this},p.setPage=function(){return Gi.apply(this,arguments),Se.call(this,ze[le]),this},p.insertPage=function(ot){return this.addPage(),this.movePage(le,ot),this},p.movePage=function(ot,Jt){var qs,Xs;if(ot>Jt){qs=ze[ot],Xs=hn[ot];for(var An=ot;An>Jt;An--)ze[An]=ze[An-1],hn[An]=hn[An-1];ze[Jt]=qs,hn[Jt]=Xs,this.setPage(Jt)}else if(ot0&&(typeof ot=="string"?ot=fi.splitTextToSize(ot,bo):Object.prototype.toString.call(ot)==="[object Array]"&&(ot=ot.reduce(function(Cl,pl){return Cl.concat(fi.splitTextToSize(pl,bo))},[]))),zr={text:ot,x:Jt,y:qs,options:Xs,mutex:{pdfEscape:sa,activeFontKey:Vt,fonts:Ts,activeFontSize:qe}},dr.publish("preProcessText",zr),ot=zr.text,Ar=(Xs=zr.options).angle,$r instanceof Wn==0&&Ar&&typeof Ar=="number"){Ar*=Math.PI/180,Xs.rotationDirection===0&&(Ar=-Ar),S===j&&(Ar=-Ar);var cp=Math.cos(Ar),dd=Math.sin(Ar);$r=new Wn(cp,dd,-dd,cp,0,0)}else Ar&&Ar instanceof Wn&&($r=Ar);S!==j||$r||($r=Fa),(Po=Xs.charSpace||wd)!==void 0&&(Hc+=M(G(Po))+` Tc `,this.setCharSpace(this.getCharSpace()||0)),(cd=Xs.horizontalScale)!==void 0&&(Hc+=M(100*cd)+` Tz `),Xs.lang;var Ud=-1,Ch=Xs.renderingMode!==void 0?Xs.renderingMode:Xs.stroke,Pp=fi.internal.getCurrentPageInfo().pageContext;switch(Ch){case 0:case!1:case"fill":Ud=0;break;case 1:case!0:case"stroke":Ud=1;break;case 2:case"fillThenStroke":Ud=2;break;case 3:case"invisible":Ud=3;break;case 4:case"fillAndAddForClipping":Ud=4;break;case 5:case"strokeAndAddPathForClipping":Ud=5;break;case 6:case"fillThenStrokeAndAddToPathForClipping":Ud=6;break;case 7:case"addToPathForClipping":Ud=7}var Fx=Pp.usedRenderingMode!==void 0?Pp.usedRenderingMode:-1;Ud!==-1?Hc+=Ud+` Tr `:Fx!==-1&&(Hc+=`0 Tr `),Ud!==-1&&(Pp.usedRenderingMode=Ud),wi=Xs.align||"left";var sc,Ba=qe*ho,Hr=fi.internal.pageSize.getWidth(),Cc=Ts[Vt];Po=Xs.charSpace||wd,bo=Xs.maxWidth||0,Vl=Object.assign({autoencode:!0,noBOM:!0},Xs.flags);var qa=[],Lp=function(Cl){return fi.getStringUnitWidth(Cl,{font:Cc,charSpace:Po,fontSize:qe,doKerning:!1})*qe/Xh};if(Object.prototype.toString.call(ot)==="[object Array]"){var ou;Wr=Nn(ot),wi!=="left"&&(sc=Wr.map(Lp));var va,Wg=0;if(wi==="right"){Jt-=sc[0],ot=[],_i=Wr.length;for(var U0=0;U0<_i;U0++)U0===0?(va=Mp(Jt),ou=op(qs)):(va=G(Wg-sc[U0]),ou=-Ba),ot.push([Wr[U0],va,ou]),Wg=sc[U0]}else if(wi==="center"){Jt-=sc[0]/2,ot=[],_i=Wr.length;for(var gg=0;gg<_i;gg++)gg===0?(va=Mp(Jt),ou=op(qs)):(va=G((Wg-sc[gg])/2),ou=-Ba),ot.push([Wr[gg],va,ou]),Wg=sc[gg]}else if(wi==="left"){ot=[],_i=Wr.length;for(var Ry=0;Ry<_i;Ry++)ot.push(Wr[Ry])}else if(wi==="justify"&&Cc.encoding==="Identity-H"){ot=[],_i=Wr.length,bo=bo!==0?bo:Hr;for(var Ox=0,Td=0;Td<_i;Td++)if(ou=Td===0?op(qs):-Ba,va=Td===0?Mp(Jt):Ox,Td<_i-1){var df=G((bo-sc[Td])/(Wr[Td].split(" ").length-1)),ym=Wr[Td].split(" ");ot.push([ym[0]+" ",va,ou]),Ox=0;for(var hh=1;hh0?(bo-sc[Td])/uf:0;Td<_i-1?qa.push(M(G(E1))):qa.push(0),ot.push([Wr[Td],va,ou])}}}(typeof Xs.R2L=="boolean"?Xs.R2L:Xe)===!0&&(ot=Un(ot,function(Cl,pl,$u){return[Cl.split("").reverse().join(""),pl,$u]})),zr={text:ot,x:Jt,y:qs,options:Xs,mutex:{pdfEscape:sa,activeFontKey:Vt,fonts:Ts,activeFontSize:qe}},dr.publish("postProcessText",zr),ot=zr.text,tc=zr.mutex.isHex||!1;var T1=Ts[Vt].encoding;T1!=="WinAnsiEncoding"&&T1!=="StandardEncoding"||(ot=Un(ot,function(Cl,pl,$u){return[$t(Cl),pl,$u]})),Wr=Nn(ot),ot=[];for(var ud,Kg,Fy,vm=Array.isArray(Wr[0])?1:0,zx="",Rb=function(Cl,pl,$u){var $d="";return $u instanceof Wn?($u=typeof Xs.angle=="number"?Js($u,new Wn(1,0,0,1,Cl,pl)):Js(new Wn(1,0,0,1,Cl,pl),$u),S===j&&($u=Js(new Wn(1,0,0,-1,0,0),$u)),$d=$u.join(" ")+` Tm `):$d=M(Cl)+" "+M(pl)+` Td `,$d},mh=0;mh":")"),ud=parseFloat(Wr[mh][1]),Kg=parseFloat(Wr[mh][2]);break;case 0:Fy=(tc?"<":"(")+Wr[mh]+(tc?">":")"),ud=Mp(Jt),Kg=op(qs)}qa!==void 0&&qa[mh]!==void 0&&(zx=qa[mh]+` Tw `),mh===0?ot.push(zx+Rb(ud,Kg,$r)+Fy):vm===0?ot.push(zx+Fy):vm===1&&ot.push(zx+Rb(ud,Kg,$r)+Fy)}ot=vm===0?ot.join(` Tj T* `):ot.join(` Tj `),ot+=` Tj `;var Ac=`BT /`;return Ac+=Vt+" "+qe+` Tf `,Ac+=M(qe*ho)+` TL `,Ac+=gm+` `,Ac+=Hc,Ac+=ot,Fe(Ac+="ET"),m[Vt]=!0,fi};var Tp=p.__private__.clip=p.clip=function(ot){return Fe(ot==="evenodd"?"W*":"W"),this};p.clipEvenOdd=function(){return Tp("evenodd")},p.__private__.discardPath=p.discardPath=function(){return Fe("n"),this};var Bd=p.__private__.isValidStyle=function(ot){var Jt=!1;return[void 0,null,"S","D","F","DF","FD","f","f*","B","B*","n"].indexOf(ot)!==-1&&(Jt=!0),Jt};p.__private__.setDefaultPathOperation=p.setDefaultPathOperation=function(ot){return Bd(ot)&&(d=ot),this};var xm=p.__private__.getStyle=p.getStyle=function(ot){var Jt=d;switch(ot){case"D":case"S":Jt="S";break;case"F":Jt="f";break;case"FD":case"DF":Jt="B";break;case"f":case"f*":case"B":case"B*":Jt=ot}return Jt},xs=p.close=function(){return Fe("h"),this};p.stroke=function(){return Fe("S"),this},p.fill=function(ot){return da("f",ot),this},p.fillEvenOdd=function(ot){return da("f*",ot),this},p.fillStroke=function(ot){return da("B",ot),this},p.fillStrokeEvenOdd=function(ot){return da("B*",ot),this};var da=function(ot,Jt){Uh(Jt)==="object"?no(Jt,ot):Fe(ot)},so=function(ot){ot===null||S===j&&ot===void 0||(ot=xm(ot),Fe(ot))};function Ma(ot,Jt,qs,Xs,An){var zr=new hq(Jt||this.boundingBox,qs||this.xStep,Xs||this.yStep,this.gState,An||this.matrix);zr.stream=this.stream;var Wr=ot+"$$"+this.cloneIndex+++"$$";return ks(Wr,zr),zr}var no=function(ot,Jt){var qs=jn[ot.key],Xs=As[qs];if(Xs instanceof nF)Fe("q"),Fe(Co(Jt)),Xs.gState&&p.setGState(Xs.gState),Fe(ot.matrix.toString()+" cm"),Fe("/"+qs+" sh"),Fe("Q");else if(Xs instanceof hq){var An=new Wn(1,0,0,-1,0,Om());ot.matrix&&(An=An.multiply(ot.matrix||Fa),qs=Ma.call(Xs,ot.key,ot.boundingBox,ot.xStep,ot.yStep,An).id),Fe("q"),Fe("/Pattern cs"),Fe("/"+qs+" scn"),Xs.gState&&p.setGState(Xs.gState),Fe(Jt),Fe("Q")}},Co=function(ot){switch(ot){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"}},bi=p.moveTo=function(ot,Jt){return Fe(M(G(ot))+" "+M($(Jt))+" m"),this},Bu=p.lineTo=function(ot,Jt){return Fe(M(G(ot))+" "+M($(Jt))+" l"),this},Uu=p.curveTo=function(ot,Jt,qs,Xs,An,zr){return Fe([M(G(ot)),M($(Jt)),M(G(qs)),M($(Xs)),M(G(An)),M($(zr)),"c"].join(" ")),this};p.__private__.line=p.line=function(ot,Jt,qs,Xs,An){if(isNaN(ot)||isNaN(Jt)||isNaN(qs)||isNaN(Xs)||!Bd(An))throw new Error("Invalid arguments passed to jsPDF.line");return S===b?this.lines([[qs-ot,Xs-Jt]],ot,Jt,[1,1],An||"S"):this.lines([[qs-ot,Xs-Jt]],ot,Jt,[1,1]).stroke()},p.__private__.lines=p.lines=function(ot,Jt,qs,Xs,An,zr){var Wr,Ar,wi,Po,bo,Vl,cd,$r,fi,Ci,tc,Hc;if(typeof ot=="number"&&(Hc=qs,qs=Jt,Jt=ot,ot=Hc),Xs=Xs||[1,1],zr=zr||!1,isNaN(Jt)||isNaN(qs)||!Array.isArray(ot)||!Array.isArray(Xs)||!Bd(An)||typeof zr!="boolean")throw new Error("Invalid arguments passed to jsPDF.lines");for(bi(Jt,qs),Wr=Xs[0],Ar=Xs[1],Po=ot.length,Ci=Jt,tc=qs,wi=0;wi>8&255,s>>16&255,s>>24&255)},jU.prototype.toHexString=function(s){return s.split("").map(function(t){return("0"+(255&t.charCodeAt(0)).toString(16)).slice(-2)}).join("")},jU.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 eKe(n,r)}},ZTe.prototype.equals=function(s){var t,n="id,objectNumber,equals";if(!s||Uh(s)!==Uh(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},Mo.API={events:[]},Mo.version="4.2.1";var px=Mo.API,Drt=1,uz=function(s){return s.replace(/\\/g,"\\\\").replace(/\(/g,"\\(").replace(/\)/g,"\\)")},VB=function(s){return s.replace(/\\\\/g,"\\").replace(/\\\(/g,"(").replace(/\\\)/g,")")},_9=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)})},Nc=function(s){return s.toFixed(2)},ET=function(s){return s.toFixed(5)};px.__acroform__={};var ew=function(s,t){s.prototype=Object.create(t.prototype),s.prototype.constructor=s},Okt=function(s){return s*Drt},F5=function(s){var t=new dJt,n=jo.internal.getHeight(s)||0,r=jo.internal.getWidth(s)||0;return t.BBox=[0,0,Number(Nc(r)),Number(Nc(n))],t},dqn=px.__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=ode("3",s,i).height,m=s.multiline?l-i:(l-h)/2,p=m+=2,f=0,y=0,v=0;if(i<=0){t=`(...) Tj `,t+="% Width of Text: "+ode(t,s,i=12).width+", FieldWidth:"+o+` `;break}for(var g="",b=0,j=0;jl)continue e;g+=a[j][v],S=!0,y=j,j--}else{g=(g+=a[j][v]+" ").substr(g.length-1)==" "?g.substr(0,g.length-1):g;var C=parseInt(j),E=c(C,g,i),P=j>=a.length-1;if(E&&!P){g+=" ",v=0;continue}if(E||P){if(P)y=C;else if(s.multiline&&(h+2)*(b+2)+2>l)continue e}else{if(!s.multiline||(h+2)*(b+2)+2>l)continue e;y=C}}for(var M="",I=f;I<=y;I++){var D=a[I];if(s.multiline){if(I===y){M+=D[v]+" ",v=(v+1)%D.length;continue}if(I===f){M+=D[D.length-1]+" ";continue}}M+=D[0]+" "}switch(M=M.substr(M.length-1)==" "?M.substr(0,M.length-1):M,u=ode(M,s,i).width,s.textAlign){case"right":d=o-u-2;break;case"center":d=(o-u)/2;break;default:d=2}t+=Nc(d)+" "+Nc(p)+` Td `,t+="("+uz(M)+`) Tj `,t+=-Nc(d)+` 0 Td `,p=-(i+2),u=0,f=S?y:y+1,b++,g=""}break}return r.text=t,r.fontSize=i,r},ode=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}},fqn={fields:[],xForms:[],acroFormDictionaryRoot:null,printedOut:!1,internal:null,isInitialized:!1},xqn=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)},gqn=function(s,t){if(t.scope=s,s.internal!==void 0&&(s.internal.acroformPlugin===void 0||s.internal.acroformPlugin.isInitialized===!1)){if(VS.FieldNum=0,s.internal.acroformPlugin=JSON.parse(JSON.stringify(fqn)),s.internal.acroformPlugin.acroFormDictionaryRoot)throw new Error("Exception while creating AcroformDictionary");Drt=s.internal.scaleFactor,s.internal.acroformPlugin.acroFormDictionaryRoot=new uJt,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&&xqn(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=mqn(o.Rect,a)),a.internal.newObjectDeferredBegin(o.objId,!0),o.DA=jo.createDefaultAppearanceStream(o),Uh(o)==="object"&&typeof o.getKeyValueListForStream=="function"&&(c=o.getKeyValueListForStream()),o.Rect=d,o.hasAppearanceStream&&!o.appearanceStreamContent){var u=pqn(o);c.push({key:"AP",value:"<>"}),a.internal.acroformPlugin.xForms.push(u)}if(o.appearanceStreamContent){var h="";for(var m in o.appearanceStreamContent)if(o.appearanceStreamContent.hasOwnProperty(m)){var p=o.appearanceStreamContent[m];if(h+="/"+m+" ",h+="<<",Object.keys(p).length>=1||Array.isArray(p)){for(var l in p)if(p.hasOwnProperty(l)){var f=p[l];typeof f=="function"&&(f=f.call(a,o)),h+="/"+l+" "+f+" ",a.internal.acroformPlugin.xForms.indexOf(f)>=0||a.internal.acroformPlugin.xForms.push(f)}}else typeof(f=p)=="function"&&(f=f.call(a,o)),h+="/"+l+" "+f,a.internal.acroformPlugin.xForms.indexOf(f)>=0||a.internal.acroformPlugin.xForms.push(f);h+=">>"}c.push({key:"AP",value:`<< `+h+">>"})}a.internal.putStream({additionalKeyValues:c,objectId:o.objId}),a.internal.out("endobj")}i&&function(y,v){for(var g in y)if(y.hasOwnProperty(g)){var b=g,j=y[g];v.internal.newObjectDeferredBegin(j.objId,!0),Uh(j)==="object"&&typeof j.putStream=="function"&&j.putStream(),delete y[b]}}(a.internal.acroformPlugin.xForms,a)})(n,s)}),s.internal.acroformPlugin.isInitialized=!0}},cJt=px.__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)),"("+uz(n(s))+")"}},set:function(n){s=n}})};ew(uJt,D4);var VS=function s(){D4.call(this);var t=4;Object.defineProperty(this,"F",{enumerable:!1,configurable:!1,get:function(){return t},set:function(g){if(isNaN(g))throw new Error('Invalid value "'+g+'" for attribute F supplied.');t=g}}),Object.defineProperty(this,"showWhenPrinted",{enumerable:!0,configurable:!0,get:function(){return!!Jx(t,3)},set:function(g){g?this.F=eg(t,3):this.F=tg(t,3)}});var n=0;Object.defineProperty(this,"Ff",{enumerable:!1,configurable:!1,get:function(){return n},set:function(g){if(isNaN(g))throw new Error('Invalid value "'+g+'" for attribute Ff supplied.');n=g}});var r=[];Object.defineProperty(this,"Rect",{enumerable:!1,configurable:!1,get:function(){if(r.length!==0)return r},set:function(g){r=g!==void 0?g:[]}}),Object.defineProperty(this,"x",{enumerable:!0,configurable:!0,get:function(){return!r||isNaN(r[0])?0:r[0]},set:function(g){r[0]=g}}),Object.defineProperty(this,"y",{enumerable:!0,configurable:!0,get:function(){return!r||isNaN(r[1])?0:r[1]},set:function(g){r[1]=g}}),Object.defineProperty(this,"width",{enumerable:!0,configurable:!0,get:function(){return!r||isNaN(r[2])?0:r[2]},set:function(g){r[2]=g}}),Object.defineProperty(this,"height",{enumerable:!0,configurable:!0,get:function(){return!r||isNaN(r[3])?0:r[3]},set:function(g){r[3]=g}});var a="";Object.defineProperty(this,"FT",{enumerable:!0,configurable:!1,get:function(){return a},set:function(g){switch(g){case"/Btn":case"/Tx":case"/Ch":case"/Sig":a=g;break;default:throw new Error('Invalid value "'+g+'" 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 XTe)return;i="FieldObject"+s.FieldNum++}var g=function(b){return b};return this.scope&&(g=this.scope.internal.getEncryptor(this.objId)),"("+uz(g(i))+")"},set:function(g){i=g.toString()}}),Object.defineProperty(this,"fieldName",{configurable:!0,enumerable:!0,get:function(){return i},set:function(g){i=g}});var l="helvetica";Object.defineProperty(this,"fontName",{enumerable:!0,configurable:!0,get:function(){return l},set:function(g){l=g}});var o="normal";Object.defineProperty(this,"fontStyle",{enumerable:!0,configurable:!0,get:function(){return o},set:function(g){o=g}});var c=0;Object.defineProperty(this,"fontSize",{enumerable:!0,configurable:!0,get:function(){return c},set:function(g){c=g}});var d=void 0;Object.defineProperty(this,"maxFontSize",{enumerable:!0,configurable:!0,get:function(){return d===void 0?50/Drt:d},set:function(g){d=g}});var u="black";Object.defineProperty(this,"color",{enumerable:!0,configurable:!0,get:function(){return u},set:function(g){u=g}});var h="/F1 0 Tf 0 g";Object.defineProperty(this,"DA",{enumerable:!0,configurable:!1,get:function(){if(!(!h||this instanceof XTe||this instanceof I7))return zze(h,this.objId,this.scope)},set:function(g){g=g.toString(),h=g}});var m=null;Object.defineProperty(this,"DV",{enumerable:!1,configurable:!1,get:function(){if(m)return this instanceof my==0?zze(m,this.objId,this.scope):m},set:function(g){g=g.toString(),m=this instanceof my==0?g.substr(0,1)==="("?VB(g.substr(1,g.length-2)):VB(g):g}}),Object.defineProperty(this,"defaultValue",{enumerable:!0,configurable:!0,get:function(){return this instanceof my==1?VB(m.substr(1,m.length-1)):m},set:function(g){g=g.toString(),m=this instanceof my==1?"/"+_9(g):g}});var p=null;Object.defineProperty(this,"_V",{enumerable:!1,configurable:!1,get:function(){if(p)return p},set:function(g){this.V=g}}),Object.defineProperty(this,"V",{enumerable:!1,configurable:!1,get:function(){if(p)return this instanceof my==0?zze(p,this.objId,this.scope):p},set:function(g){g=g.toString(),p=this instanceof my==0?g.substr(0,1)==="("?VB(g.substr(1,g.length-2)):VB(g):g}}),Object.defineProperty(this,"value",{enumerable:!0,configurable:!0,get:function(){return this instanceof my==1?VB(p.substr(1,p.length-1)):p},set:function(g){g=g.toString(),p=this instanceof my==1?"/"+_9(g):g}}),Object.defineProperty(this,"hasAnnotation",{enumerable:!0,configurable:!0,get:function(){return this.Rect}}),Object.defineProperty(this,"Type",{enumerable:!0,configurable:!1,get:function(){return this.hasAnnotation?"/Annot":null}}),Object.defineProperty(this,"Subtype",{enumerable:!0,configurable:!1,get:function(){return this.hasAnnotation?"/Widget":null}});var f,y=!1;Object.defineProperty(this,"hasAppearanceStream",{enumerable:!0,configurable:!0,get:function(){return y},set:function(g){g=!!g,y=g}}),Object.defineProperty(this,"page",{enumerable:!0,configurable:!0,get:function(){if(f)return f},set:function(g){f=g}}),Object.defineProperty(this,"readOnly",{enumerable:!0,configurable:!0,get:function(){return!!Jx(this.Ff,1)},set:function(g){g?this.Ff=eg(this.Ff,1):this.Ff=tg(this.Ff,1)}}),Object.defineProperty(this,"required",{enumerable:!0,configurable:!0,get:function(){return!!Jx(this.Ff,2)},set:function(g){g?this.Ff=eg(this.Ff,2):this.Ff=tg(this.Ff,2)}}),Object.defineProperty(this,"noExport",{enumerable:!0,configurable:!0,get:function(){return!!Jx(this.Ff,3)},set:function(g){g?this.Ff=eg(this.Ff,3):this.Ff=tg(this.Ff,3)}});var v=null;Object.defineProperty(this,"Q",{enumerable:!0,configurable:!1,get:function(){if(v!==null)return v},set:function(g){if([0,1,2].indexOf(g)===-1)throw new Error('Invalid value "'+g+'" for attribute Q supplied.');v=g}}),Object.defineProperty(this,"textAlign",{get:function(){var g;switch(v){case 0:default:g="left";break;case 1:g="center";break;case 2:g="right"}return g},configurable:!0,enumerable:!0,set:function(g){switch(g){case"right":case 2:v=2;break;case"center":case 1:v=1;break;default:v=0}}})};ew(VS,D4);var B$=function(){VS.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 cJt(t,this.objId,this.scope)},set:function(n){var r,a;a=[],typeof(r=n)=="string"&&(a=function(i,l,o){o||(o=1);for(var c,d=[];c=l.exec(i);)d.push(c[o]);return d}(r,/\((.*?)\)/g)),t=a}}),this.getOptions=function(){return t},this.setOptions=function(n){t=n,this.sort&&t.sort()},this.addOption=function(n){n=(n=n||"").toString(),t.push(n),this.sort&&t.sort()},this.removeOption=function(n,r){for(r=r||!1,n=(n=n||"").toString();t.indexOf(n)!==-1&&(t.splice(t.indexOf(n),1),r!==!1););},Object.defineProperty(this,"combo",{enumerable:!0,configurable:!0,get:function(){return!!Jx(this.Ff,18)},set:function(n){n?this.Ff=eg(this.Ff,18):this.Ff=tg(this.Ff,18)}}),Object.defineProperty(this,"edit",{enumerable:!0,configurable:!0,get:function(){return!!Jx(this.Ff,19)},set:function(n){this.combo===!0&&(n?this.Ff=eg(this.Ff,19):this.Ff=tg(this.Ff,19))}}),Object.defineProperty(this,"sort",{enumerable:!0,configurable:!0,get:function(){return!!Jx(this.Ff,20)},set:function(n){n?(this.Ff=eg(this.Ff,20),t.sort()):this.Ff=tg(this.Ff,20)}}),Object.defineProperty(this,"multiSelect",{enumerable:!0,configurable:!0,get:function(){return!!Jx(this.Ff,22)},set:function(n){n?this.Ff=eg(this.Ff,22):this.Ff=tg(this.Ff,22)}}),Object.defineProperty(this,"doNotSpellCheck",{enumerable:!0,configurable:!0,get:function(){return!!Jx(this.Ff,23)},set:function(n){n?this.Ff=eg(this.Ff,23):this.Ff=tg(this.Ff,23)}}),Object.defineProperty(this,"commitOnSelChange",{enumerable:!0,configurable:!0,get:function(){return!!Jx(this.Ff,27)},set:function(n){n?this.Ff=eg(this.Ff,27):this.Ff=tg(this.Ff,27)}}),this.hasAppearanceStream=!1};ew(B$,VS);var U$=function(){B$.call(this),this.fontName="helvetica",this.combo=!1};ew(U$,B$);var q$=function(){U$.call(this),this.combo=!0};ew(q$,U$);var nCe=function(){q$.call(this),this.edit=!0};ew(nCe,q$);var my=function(){VS.call(this),this.FT="/Btn",Object.defineProperty(this,"noToggleToOff",{enumerable:!0,configurable:!0,get:function(){return!!Jx(this.Ff,15)},set:function(n){n?this.Ff=eg(this.Ff,15):this.Ff=tg(this.Ff,15)}}),Object.defineProperty(this,"radio",{enumerable:!0,configurable:!0,get:function(){return!!Jx(this.Ff,16)},set:function(n){n?this.Ff=eg(this.Ff,16):this.Ff=tg(this.Ff,16)}}),Object.defineProperty(this,"pushButton",{enumerable:!0,configurable:!0,get:function(){return!!Jx(this.Ff,17)},set:function(n){n?this.Ff=eg(this.Ff,17):this.Ff=tg(this.Ff,17)}}),Object.defineProperty(this,"radioIsUnison",{enumerable:!0,configurable:!0,get:function(){return!!Jx(this.Ff,26)},set:function(n){n?this.Ff=eg(this.Ff,26):this.Ff=tg(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+" ("+uz(n(t[r]))+")");return a.push(">>"),a.join(` `)}},set:function(n){Uh(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="/"+_9(r)}}),Object.defineProperty(this,"appearanceState",{enumerable:!0,configurable:!0,get:function(){return s.substr(1,s.length-1)},set:function(n){s="/"+_9(n)}})};ew(my,VS);var rCe=function(){my.call(this),this.pushButton=!0};ew(rCe,my);var $$=function(){my.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:[]}})};ew($$,my);var XTe=function(){var s,t;VS.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+" ("+uz(a(r[i]))+")");return l.push(">>"),l.join(` `)},set:function(a){Uh(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="/"+_9(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="/"+_9(i)}}),this.caption="l",this.appearanceState="Off",this._AppearanceType=jo.RadioButton.Circle,this.appearanceStreamContent=this._AppearanceType.createAppearanceStream(this.optionName)};ew(XTe,VS),$$.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()}},$$.prototype.createOption=function(s){var t=new XTe;return t.Parent=this,t.optionName=s,this.Kids.push(t),yqn.call(this.scope,t),t};var aCe=function(){my.call(this),this.fontName="zapfdingbats",this.caption="3",this.appearanceState="On",this.value="On",this.textAlign="center",this.appearanceStreamContent=jo.CheckBox.createAppearanceStream()};ew(aCe,my);var I7=function(){VS.call(this),this.FT="/Tx",Object.defineProperty(this,"multiline",{enumerable:!0,configurable:!0,get:function(){return!!Jx(this.Ff,13)},set:function(t){t?this.Ff=eg(this.Ff,13):this.Ff=tg(this.Ff,13)}}),Object.defineProperty(this,"fileSelect",{enumerable:!0,configurable:!0,get:function(){return!!Jx(this.Ff,21)},set:function(t){t?this.Ff=eg(this.Ff,21):this.Ff=tg(this.Ff,21)}}),Object.defineProperty(this,"doNotSpellCheck",{enumerable:!0,configurable:!0,get:function(){return!!Jx(this.Ff,23)},set:function(t){t?this.Ff=eg(this.Ff,23):this.Ff=tg(this.Ff,23)}}),Object.defineProperty(this,"doNotScroll",{enumerable:!0,configurable:!0,get:function(){return!!Jx(this.Ff,24)},set:function(t){t?this.Ff=eg(this.Ff,24):this.Ff=tg(this.Ff,24)}}),Object.defineProperty(this,"comb",{enumerable:!0,configurable:!0,get:function(){return!!Jx(this.Ff,25)},set:function(t){t?this.Ff=eg(this.Ff,25):this.Ff=tg(this.Ff,25)}}),Object.defineProperty(this,"richText",{enumerable:!0,configurable:!0,get:function(){return!!Jx(this.Ff,26)},set:function(t){t?this.Ff=eg(this.Ff,26):this.Ff=tg(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}})};ew(I7,VS);var iCe=function(){I7.call(this),Object.defineProperty(this,"password",{enumerable:!0,configurable:!0,get:function(){return!!Jx(this.Ff,14)},set:function(s){s?this.Ff=eg(this.Ff,14):this.Ff=tg(this.Ff,14)}}),this.password=!0};ew(iCe,I7);var jo={CheckBox:{createAppearanceStream:function(){return{N:{On:jo.CheckBox.YesNormal},D:{On:jo.CheckBox.YesPushDown,Off:jo.CheckBox.OffPushDown}}},YesPushDown:function(s){var t=F5(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=tKe(s,s.caption);return n.push("0.749023 g"),n.push("0 0 "+Nc(jo.internal.getWidth(s))+" "+Nc(jo.internal.getHeight(s))+" re"),n.push("f"),n.push("BMC"),n.push("q"),n.push("0 0 1 rg"),n.push("/"+r+" "+Nc(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=F5(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=jo.internal.getHeight(s),l=jo.internal.getWidth(s),o=tKe(s,s.caption);return a.push("1 g"),a.push("0 0 "+Nc(l)+" "+Nc(i)+" re"),a.push("f"),a.push("q"),a.push("0 0 1 rg"),a.push("0 0 "+Nc(l-1)+" "+Nc(i-1)+" re"),a.push("W"),a.push("n"),a.push("0 g"),a.push("BT"),a.push("/"+n+" "+Nc(o.fontSize)+" Tf "+r),a.push(o.text),a.push("ET"),a.push("Q"),t.stream=a.join(` `),t},OffPushDown:function(s){var t=F5(s);t.scope=s.scope;var n=[];return n.push("0.749023 g"),n.push("0 0 "+Nc(jo.internal.getWidth(s))+" "+Nc(jo.internal.getHeight(s))+" re"),n.push("f"),t.stream=n.join(` `),t}},RadioButton:{Circle:{createAppearanceStream:function(s){var t={D:{Off:jo.RadioButton.Circle.OffPushDown},N:{}};return t.N[s]=jo.RadioButton.Circle.YesNormal,t.D[s]=jo.RadioButton.Circle.YesPushDown,t},getCA:function(){return"l"},YesNormal:function(s){var t=F5(s);t.scope=s.scope;var n=[],r=jo.internal.getWidth(s)<=jo.internal.getHeight(s)?jo.internal.getWidth(s)/4:jo.internal.getHeight(s)/4;r=Number((.9*r).toFixed(5));var a=jo.internal.Bezier_C,i=Number((r*a).toFixed(5));return n.push("q"),n.push("1 0 0 1 "+ET(jo.internal.getWidth(s)/2)+" "+ET(jo.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=F5(s);t.scope=s.scope;var n=[],r=jo.internal.getWidth(s)<=jo.internal.getHeight(s)?jo.internal.getWidth(s)/4:jo.internal.getHeight(s)/4;r=Number((.9*r).toFixed(5));var a=Number((2*r).toFixed(5)),i=Number((a*jo.internal.Bezier_C).toFixed(5)),l=Number((r*jo.internal.Bezier_C).toFixed(5));return n.push("0.749023 g"),n.push("q"),n.push("1 0 0 1 "+ET(jo.internal.getWidth(s)/2)+" "+ET(jo.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 "+ET(jo.internal.getWidth(s)/2)+" "+ET(jo.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=F5(s);t.scope=s.scope;var n=[],r=jo.internal.getWidth(s)<=jo.internal.getHeight(s)?jo.internal.getWidth(s)/4:jo.internal.getHeight(s)/4;r=Number((.9*r).toFixed(5));var a=Number((2*r).toFixed(5)),i=Number((a*jo.internal.Bezier_C).toFixed(5));return n.push("0.749023 g"),n.push("q"),n.push("1 0 0 1 "+ET(jo.internal.getWidth(s)/2)+" "+ET(jo.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:jo.RadioButton.Cross.OffPushDown},N:{}};return t.N[s]=jo.RadioButton.Cross.YesNormal,t.D[s]=jo.RadioButton.Cross.YesPushDown,t},getCA:function(){return"8"},YesNormal:function(s){var t=F5(s);t.scope=s.scope;var n=[],r=jo.internal.calculateCross(s);return n.push("q"),n.push("1 1 "+Nc(jo.internal.getWidth(s)-2)+" "+Nc(jo.internal.getHeight(s)-2)+" re"),n.push("W"),n.push("n"),n.push(Nc(r.x1.x)+" "+Nc(r.x1.y)+" m"),n.push(Nc(r.x2.x)+" "+Nc(r.x2.y)+" l"),n.push(Nc(r.x4.x)+" "+Nc(r.x4.y)+" m"),n.push(Nc(r.x3.x)+" "+Nc(r.x3.y)+" l"),n.push("s"),n.push("Q"),t.stream=n.join(` `),t},YesPushDown:function(s){var t=F5(s);t.scope=s.scope;var n=jo.internal.calculateCross(s),r=[];return r.push("0.749023 g"),r.push("0 0 "+Nc(jo.internal.getWidth(s))+" "+Nc(jo.internal.getHeight(s))+" re"),r.push("f"),r.push("q"),r.push("1 1 "+Nc(jo.internal.getWidth(s)-2)+" "+Nc(jo.internal.getHeight(s)-2)+" re"),r.push("W"),r.push("n"),r.push(Nc(n.x1.x)+" "+Nc(n.x1.y)+" m"),r.push(Nc(n.x2.x)+" "+Nc(n.x2.y)+" l"),r.push(Nc(n.x4.x)+" "+Nc(n.x4.y)+" m"),r.push(Nc(n.x3.x)+" "+Nc(n.x3.y)+" l"),r.push("s"),r.push("Q"),t.stream=r.join(` `),t},OffPushDown:function(s){var t=F5(s);t.scope=s.scope;var n=[];return n.push("0.749023 g"),n.push("0 0 "+Nc(jo.internal.getWidth(s))+" "+Nc(jo.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}};jo.internal={Bezier_C:.551915024494,calculateCross:function(s){var t=jo.internal.getWidth(s),n=jo.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}}}},jo.internal.getWidth=function(s){var t=0;return Uh(s)==="object"&&(t=Okt(s.Rect[2])),t},jo.internal.getHeight=function(s){var t=0;return Uh(s)==="object"&&(t=Okt(s.Rect[3])),t};var yqn=px.addField=function(s){if(gqn(this,s),!(s instanceof VS))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};px.AcroFormChoiceField=B$,px.AcroFormListBox=U$,px.AcroFormComboBox=q$,px.AcroFormEditBox=nCe,px.AcroFormButton=my,px.AcroFormPushButton=rCe,px.AcroFormRadioButton=$$,px.AcroFormCheckBox=aCe,px.AcroFormTextField=I7,px.AcroFormPasswordField=iCe,px.AcroFormAppearance=jo,px.AcroForm={ChoiceField:B$,ListBox:U$,ComboBox:q$,EditBox:nCe,Button:my,PushButton:rCe,RadioButton:$$,CheckBox:aCe,TextField:I7,PasswordField:iCe,Appearance:jo},Mo.AcroForm={ChoiceField:B$,ListBox:U$,ComboBox:q$,EditBox:nCe,Button:my,PushButton:rCe,RadioButton:$$,CheckBox:aCe,TextField:I7,PasswordField:iCe,Appearance:jo};function hJt(s){return s.reduce(function(t,n,r){return t[n]=r,t},{})}(function(s){var t="addImage_";s.__addimage__={};var n="UNKNOWN",r={PNG:[[137,80,78,71]],TIFF:[[77,77,0,42],[73,73,42,0]],JPEG:[[255,216,255,224,void 0,void 0,74,70,73,70,0],[255,216,255,225,void 0,void 0,69,120,105,102,0,0],[255,216,255,219],[255,216,255,238]],JPEG2000:[[0,0,0,12,106,80,32,32]],GIF87a:[[71,73,70,56,55,97]],GIF89a:[[71,73,70,56,57,97]],WEBP:[[82,73,70,70,void 0,void 0,void 0,void 0,87,69,66,80]],BMP:[[66,77],[66,65],[67,73],[67,80],[73,67],[80,84]]},a=s.__addimage__.getImageFileTypeByImageData=function(O,V){var G,$,H,Y,Z,ne=n;if((V=V||n)==="RGBA"||O.data!==void 0&&O.data instanceof Uint8ClampedArray&&"height"in O&&"width"in O)return"RGBA";if(E(O))for(Z in r)for(H=r[Z],G=0;G>"}),"transparency"in V&&Array.isArray(V.transparency)&&V.transparency.length>0){for(var Z="",ne=0,ce=V.transparency.length;ne>",y.content=i;var j=y.objId+" 0 R";i="<>";else if(r.options.pageNumber)switch(i="<=0};s.__arabicParser__.arabicLetterHasIsolatedForm=function(y){return l(y)&&i(y)&&t[y.charCodeAt(0)].length>=1};var d=s.__arabicParser__.arabicLetterHasFinalForm=function(y){return l(y)&&i(y)&&t[y.charCodeAt(0)].length>=2};s.__arabicParser__.arabicLetterHasInitialForm=function(y){return l(y)&&i(y)&&t[y.charCodeAt(0)].length>=3};var u=s.__arabicParser__.arabicLetterHasMedialForm=function(y){return l(y)&&i(y)&&t[y.charCodeAt(0)].length==4},h=s.__arabicParser__.resolveLigatures=function(y){var v=0,g=n,b="",j=0;for(v=0;v>"),this.internal.out("endobj")}),this.internal.events.subscribe("putCatalog",function(){this.internal.out("/OpenAction "+t+" 0 R")})),this},function(s){var t=function(){var n=void 0;Object.defineProperty(this,"pdf",{get:function(){return n},set:function(o){n=o}});var r=150;Object.defineProperty(this,"width",{get:function(){return r},set:function(o){r=isNaN(o)||Number.isInteger(o)===!1||o<0?150:o,this.getContext("2d").pageWrapXEnabled&&(this.getContext("2d").pageWrapX=r+1)}});var a=300;Object.defineProperty(this,"height",{get:function(){return a},set:function(o){a=isNaN(o)||Number.isInteger(o)===!1||o<0?300:o,this.getContext("2d").pageWrapYEnabled&&(this.getContext("2d").pageWrapY=a+1)}});var i=[];Object.defineProperty(this,"childNodes",{get:function(){return i},set:function(o){i=o}});var l={};Object.defineProperty(this,"style",{get:function(){return l},set:function(o){l=o}}),Object.defineProperty(this,"parentNode",{})};t.prototype.getContext=function(n,r){var a;if((n=n||"2d")!=="2d")return null;for(a in r)this.pdf.context2d.hasOwnProperty(a)&&(this.pdf.context2d[a]=r[a]);return this.pdf.context2d._canvas=this,this.pdf.context2d},t.prototype.toDataURL=function(){throw new Error("toDataURL is not implemented.")},s.events.push(["initialized",function(){this.canvas=new t,this.canvas.pdf=this}])}(Mo.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(y){c=y}});var d=arguments[1];Object.defineProperty(this,"y",{enumerable:!0,get:function(){return d},set:function(y){d=y}});var u=arguments[2];Object.defineProperty(this,"width",{enumerable:!0,get:function(){return u},set:function(y){u=y}});var h=arguments[3];Object.defineProperty(this,"height",{enumerable:!0,get:function(){return h},set:function(y){h=y}});var m=arguments[4];Object.defineProperty(this,"text",{enumerable:!0,get:function(){return m},set:function(y){m=y}});var p=arguments[5];Object.defineProperty(this,"lineNumber",{enumerable:!0,get:function(){return p},set:function(y){p=y}});var f=arguments[6];return Object.defineProperty(this,"align",{enumerable:!0,get:function(){return f},set:function(y){f=y}}),this};i.prototype.clone=function(){return new i(this.x,this.y,this.width,this.height,this.text,this.lineNumber,this.align)},i.prototype.toArray=function(){return[this.x,this.y,this.width,this.height,this.text,this.lineNumber,this.align]},s.setHeaderFunction=function(c){return r.call(this),this.internal.__cell__.headerFunction=typeof c=="function"?c:void 0,this},s.getTextDimensions=function(c,d){r.call(this);var u=(d=d||{}).fontSize||this.getFontSize(),h=d.font||this.getFont(),m=d.scaleFactor||this.internal.scaleFactor,p=0,f=0,y=0,v=this;if(!Array.isArray(c)&&typeof c!="string"){if(typeof c!="number")throw new Error("getTextDimensions expects text-parameter to be of type String or type Number or an Array of Strings.");c=String(c)}var g=d.maxWidth;g>0?typeof c=="string"?c=this.splitTextToSize(c,g):Object.prototype.toString.call(c)==="[object Array]"&&(c=c.reduce(function(j,S){return j.concat(v.splitTextToSize(S,g))},[])):c=Array.isArray(c)?c:[c];for(var b=0;bthis.getPageHeight()?(this.cellAddPage(),c.y=h.top,p&&m&&(this.printHeaderRow(c.lineNumber,!0),c.y+=m[0].height)):c.y=d.y+d.height||c.y),c.text[0]!==void 0&&(this.rect(c.x,c.y,c.width,c.height,n===!0?"FD":void 0),c.align==="right"?this.text(c.text,c.x+c.width-u,c.y+u,{align:"right",baseline:"top"}):c.align==="center"?this.text(c.text,c.x+c.width/2,c.y+u,{align:"center",baseline:"top",maxWidth:c.width-u-u}):this.text(c.text,c.x+u,c.y+u,{align:"left",baseline:"top",maxWidth:c.width-u-u})),this.internal.__cell__.lastCell=c,this};s.table=function(c,d,u,h,m){if(r.call(this),!u)throw new Error("No data for PDF table.");var p,f,y,v,g=[],b=[],j=[],S={},C={},E=[],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,O=m.margins||Object.assign({width:this.getPageWidth()},t),V=typeof m.padding=="number"?m.padding:3,G=m.headerBackgroundColor||"#c8c8c8",$=m.headerTextColor||"#000";if(a.call(this),this.internal.__cell__.printHeaders=I,this.internal.__cell__.margins=O,this.internal.__cell__.table_font_size=D,this.internal.__cell__.padding=V,this.internal.__cell__.headerBackgroundColor=G,this.internal.__cell__.headerTextColor=$,this.setFontSize(D),h==null)b=g=Object.keys(u[0]),j=g.map(function(){return"left"});else if(Array.isArray(h)&&Uh(h[0])==="object")for(g=h.map(function(ie){return ie.name}),b=h.map(function(ie){return ie.prompt||ie.name||""}),j=h.map(function(ie){return ie.align||"left"}),p=0;p0&&this.setTableHeaderRow(m),this.setFont(void 0,"normal"),n=!1}}(Mo.API);var mJt={italic:["italic","oblique","normal"],oblique:["oblique","italic","normal"],normal:["normal","oblique","italic"]},pJt=["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded"],sKe=hJt(pJt),fJt=[100,200,300,400,500,600,700,800,900],vqn=hJt(fJt);function Bze(s){var t=s.family.replace(/"|'/g,"").toLowerCase(),n=function(i){return mJt[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 sKe[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 zkt(s,t,n,r){var a;for(a=n;a>=0&&a=0&&a>>1)&255}return a}function Zkt(s,t,n){var r=s.length,a=[];a[0]=4;for(var i=0;i>i&l}function Xkt(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,xJt(s,i)&~(o<>7,l=1<<1+(7&a);s[t++],s[t++];var o=null,c=null;i&&(o=t,c=l,t+=3*l);var d=!0,u=[],h=0,m=null,p=0,f=null;for(this.width=n,this.height=r;d&&t=0))throw Error("Invalid block size");if(O===0)break;t+=O}break;case 249:if(s[t++]!==4||s[t+4]!==0)throw new Error("Invalid graphics extension block.");var y=s[t++];h=s[t++]|s[t++]<<8,m=s[t++],1&y||(m=null),p=y>>2&7,t++;break;case 254:for(;;){if(!((O=s[t++])>=0))throw Error("Invalid block size");if(O===0)break;t+=O}break;default:throw new Error("Unknown graphic control label: 0x"+s[t-1].toString(16))}break;case 44:var v=s[t++]|s[t++]<<8,g=s[t++]|s[t++]<<8,b=s[t++]|s[t++]<<8,j=s[t++]|s[t++]<<8,S=s[t++],C=S>>6&1,E=1<<1+(7&S),P=o,M=c,I=!1;S>>7&&(I=!0,P=t,M=E,t+=3*E);var D=t;for(t++;;){var O;if(!((O=s[t++])>=0))throw Error("Invalid block size");if(O===0)break;t+=O}u.push({x:v,y:g,width:b,height:j,has_local_palette:I,palette_offset:P,palette_size:M,data_offset:D,data_length:t-D,transparent_index:m,interlaced:!!C,delay:h,disposal:p});break;case 59:d=!1;break;default:throw new Error("Unknown gif block: 0x"+s[t-1].toString(16))}this.numFrames=function(){return u.length},this.loopCount=function(){return f},this.frameInfo=function(V){if(V<0||V>=u.length)throw new Error("Frame index out of range.");return u[V]},this.decodeAndBlitFrameBGRA=function(V,G){var $=this.frameInfo(V),H=$.width*$.height;if(H>536870912)throw new Error("Image dimensions exceed 512MB, which is too large.");var Y=new Uint8Array(H);Qkt(s,$.data_offset,Y,H);var Z=$.palette_offset,ne=$.transparent_index;ne===null&&(ne=256);var ce=$.width,ie=n-ce,te=ce,ae=4*($.y*n+$.x),le=4*(($.y+$.height)*n+$.x),be=ae,me=4*ie;$.interlaced===!0&&(me+=4*n*7);for(var he=8,pe=0,Ce=Y.length;pe=le&&(me=4*ie+4*n*(he-1),be=ae+(ce+ie)*(he<<1),he>>=1)),Ae===ne)be+=4;else{var Pe=s[Z+3*Ae],ze=s[Z+3*Ae+1],ke=s[Z+3*Ae+2];G[be++]=ke,G[be++]=ze,G[be++]=Pe,G[be++]=255}--te}},this.decodeAndBlitFrameRGBA=function(V,G){var $=this.frameInfo(V),H=$.width*$.height;if(H>536870912)throw new Error("Image dimensions exceed 512MB, which is too large.");var Y=new Uint8Array(H);Qkt(s,$.data_offset,Y,H);var Z=$.palette_offset,ne=$.transparent_index;ne===null&&(ne=256);var ce=$.width,ie=n-ce,te=ce,ae=4*($.y*n+$.x),le=4*(($.y+$.height)*n+$.x),be=ae,me=4*ie;$.interlaced===!0&&(me+=4*n*7);for(var he=8,pe=0,Ce=Y.length;pe=le&&(me=4*ie+4*n*(he-1),be=ae+(ce+ie)*(he<<1),he>>=1)),Ae===ne)be+=4;else{var Pe=s[Z+3*Ae],ze=s[Z+3*Ae+1],ke=s[Z+3*Ae+2];G[be++]=Pe,G[be++]=ze,G[be++]=ke,G[be++]=255}--te}}}function Qkt(s,t,n,r){for(var a=s[t++],i=1<>=c,u-=c,v!==i){if(v===l)break;for(var g=vi;)j=f[j]>>8,++b;var S=j;if(m+b+(g!==v?1:0)>r)return void Sm.log("Warning, gif stream longer than expected.");n[m++]=S;var C=m+=b;for(g!==v&&(n[m++]=S),j=g;b--;)j=f[j],n[--C]=255&j,j>>=8;y!==null&&o<4096&&(f[o++]=y<<8|S,o>=d+1&&c<12&&(++c,d=d<<1|1)),y=v}else o=l+1,d=(1<<(c=a+1))-1,y=null}return m!==r&&Sm.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 $ze(s){var t,n,r,a,i,l=Math.floor,o=new Array(64),c=new Array(64),d=new Array(64),u=new Array(64),h=new Array(65535),m=new Array(65535),p=new Array(64),f=new Array(64),y=[],v=0,g=7,b=new Array(64),j=new Array(64),S=new Array(64),C=new Array(256),E=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],O=[1,2,3,0,4,17,5,18,33,49,65,6,19,81,97,7,34,113,20,50,129,145,161,8,35,66,177,193,21,82,209,240,36,51,98,114,130,9,10,22,23,24,25,26,37,38,39,40,41,42,52,53,54,55,56,57,58,67,68,69,70,71,72,73,74,83,84,85,86,87,88,89,90,99,100,101,102,103,104,105,106,115,116,117,118,119,120,121,122,131,132,133,134,135,136,137,138,146,147,148,149,150,151,152,153,154,162,163,164,165,166,167,168,169,170,178,179,180,181,182,183,184,185,186,194,195,196,197,198,199,200,201,202,210,211,212,213,214,215,216,217,218,225,226,227,228,229,230,231,232,233,234,241,242,243,244,245,246,247,248,249,250],V=[0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0],G=[0,1,2,3,4,5,6,7,8,9,10,11],$=[0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,119],H=[0,1,2,3,17,4,5,33,49,6,18,65,81,7,97,113,19,34,50,129,8,20,66,145,161,177,193,9,35,51,82,240,21,98,114,209,10,22,36,52,225,37,241,23,24,25,26,38,39,40,41,42,53,54,55,56,57,58,67,68,69,70,71,72,73,74,83,84,85,86,87,88,89,90,99,100,101,102,103,104,105,106,115,116,117,118,119,120,121,122,130,131,132,133,134,135,136,137,138,146,147,148,149,150,151,152,153,154,162,163,164,165,166,167,168,169,170,178,179,180,181,182,183,184,185,186,194,195,196,197,198,199,200,201,202,210,211,212,213,214,215,216,217,218,226,227,228,229,230,231,232,233,234,242,243,244,245,246,247,248,249,250];function Y(ae,le){for(var be=0,me=0,he=new Array,pe=1;pe<=16;pe++){for(var Ce=1;Ce<=ae[pe];Ce++)he[le[me]]=[],he[le[me]][0]=be,he[le[me]][1]=pe,me++,be++;be*=2}return he}function Z(ae){for(var le=ae[0],be=ae[1]-1;be>=0;)le&1<>8&255),ne(255&ae)}function ie(ae,le,be,me,he){for(var pe,Ce=he[0],Ae=he[240],Pe=function(qe,Qe){var Ue,Xe,nt,$e,Ge,ct,xt,qt,Vt,Xt,fs=0;for(Vt=0;Vt<8;++Vt){Ue=qe[fs],Xe=qe[fs+1],nt=qe[fs+2],$e=qe[fs+3],Ge=qe[fs+4],ct=qe[fs+5],xt=qe[fs+6];var Ft=Ue+(qt=qe[fs+7]),wt=Ue-qt,Ts=Xe+xt,vt=Xe-xt,$s=nt+ct,As=nt-ct,jn=$e+Ge,ar=$e-Ge,Dn=Ft+jn,Ur=Ft-jn,Vs=Ts+$s,hn=Ts-$s;qe[fs]=Dn+Vs,qe[fs+4]=Dn-Vs;var dr=.707106781*(hn+Ur);qe[fs+2]=Ur+dr,qe[fs+6]=Ur-dr;var Cn=.382683433*((Dn=ar+As)-(hn=vt+wt)),Yn=.5411961*Dn+Cn,on=1.306562965*hn+Cn,Ir=.707106781*(Vs=As+vt),Wn=wt+Ir,Js=wt-Ir;qe[fs+5]=Js+Yn,qe[fs+3]=Js-Yn,qe[fs+1]=Wn+on,qe[fs+7]=Wn-on,fs+=8}for(fs=0,Vt=0;Vt<8;++Vt){Ue=qe[fs],Xe=qe[fs+8],nt=qe[fs+16],$e=qe[fs+24],Ge=qe[fs+32],ct=qe[fs+40],xt=qe[fs+48];var Fa=Ue+(qt=qe[fs+56]),ks=Ue-qt,Gs=Xe+xt,Ws=Xe-xt,Ys=nt+ct,Bn=nt-ct,or=$e+Ge,Wt=$e-Ge,rt=Fa+or,pt=Fa-or,jt=Gs+Ys,Mt=Gs-Ys;qe[fs]=rt+jt,qe[fs+32]=rt-jt;var es=.707106781*(Mt+pt);qe[fs+16]=pt+es,qe[fs+48]=pt-es;var ps=.382683433*((rt=Wt+Bn)-(Mt=Ws+ks)),Is=.5411961*rt+ps,js=1.306562965*Mt+ps,Kt=.707106781*(jt=Bn+Ws),Qs=ks+Kt,an=ks-Kt;qe[fs+40]=an+Is,qe[fs+24]=an-Is,qe[fs+8]=Qs+js,qe[fs+56]=Qs-js,fs++}for(Vt=0;Vt<64;++Vt)Xt=qe[Vt]*Qe[Vt],p[Vt]=Xt>0?Xt+.5|0:Xt-.5|0;return p}(ae,le),ze=0;ze<64;++ze)f[P[ze]]=Pe[ze];var ke=f[0]-be;be=f[0],ke==0?Z(me[0]):(Z(me[m[pe=32767+ke]]),Z(h[pe]));for(var Ze=63;Ze>0&&f[Ze]==0;)Ze--;if(Ze==0)return Z(Ce),be;for(var Se,Fe=1;Fe<=Ze;){for(var Ne=Fe;f[Fe]==0&&Fe<=Ze;)++Fe;var Ye=Fe-Ne;if(Ye>=16){Se=Ye>>4;for(var Ve=1;Ve<=Se;++Ve)Z(Ae);Ye&=15}pe=32767+f[Fe],Z(he[(Ye<<4)+m[pe]]),Z(h[pe]),Fe++}return Ze!=63&&Z(Ce),be}function te(ae){ae=Math.min(Math.max(ae,1),100),i!=ae&&(function(le){for(var be=[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],me=0;me<64;me++){var he=l((be[me]*le+50)/100);he=Math.min(Math.max(he,1),255),o[P[me]]=he}for(var pe=[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],Ce=0;Ce<64;Ce++){var Ae=l((pe[Ce]*le+50)/100);Ae=Math.min(Math.max(Ae,1),255),c[P[Ce]]=Ae}for(var Pe=[1,1.387039845,1.306562965,1.175875602,1,.785694958,.5411961,.275899379],ze=0,ke=0;ke<8;ke++)for(var Ze=0;Ze<8;Ze++)d[ze]=1/(o[P[ze]]*Pe[ke]*Pe[Ze]*8),u[ze]=1/(c[P[ze]]*Pe[ke]*Pe[Ze]*8),ze++}(ae<50?Math.floor(5e3/ae):Math.floor(200-2*ae)),i=ae)}this.encode=function(ae,le){le&&te(le),y=new Array,v=0,g=7,ce(65496),ce(65504),ce(16),ne(74),ne(70),ne(73),ne(70),ne(0),ne(1),ne(1),ne(0),ce(1),ce(1),ne(0),ne(0),function(){ce(65499),ce(132),ne(0);for(var Xe=0;Xe<64;Xe++)ne(o[Xe]);ne(1);for(var nt=0;nt<64;nt++)ne(c[nt])}(),function(Xe,nt){ce(65472),ce(17),ne(8),ce(nt),ce(Xe),ne(3),ne(1),ne(17),ne(0),ne(2),ne(17),ne(1),ne(3),ne(17),ne(1)}(ae.width,ae.height),function(){ce(65476),ce(418),ne(0);for(var Xe=0;Xe<16;Xe++)ne(M[Xe+1]);for(var nt=0;nt<=11;nt++)ne(I[nt]);ne(16);for(var $e=0;$e<16;$e++)ne(D[$e+1]);for(var Ge=0;Ge<=161;Ge++)ne(O[Ge]);ne(1);for(var ct=0;ct<16;ct++)ne(V[ct+1]);for(var xt=0;xt<=11;xt++)ne(G[xt]);ne(17);for(var qt=0;qt<16;qt++)ne($[qt+1]);for(var Vt=0;Vt<=161;Vt++)ne(H[Vt])}(),ce(65498),ce(12),ne(3),ne(1),ne(0),ne(2),ne(17),ne(3),ne(17),ne(0),ne(63),ne(0);var be=0,me=0,he=0;v=0,g=7,this.encode.displayName="_encode_";for(var pe,Ce,Ae,Pe,ze,ke,Ze,Se,Fe,Ne=ae.data,Ye=ae.width,Ve=ae.height,qe=4*Ye,Qe=0;Qe>3)*qe+(Ze=4*(7&Fe)),Qe+Se>=Ve&&(ke-=qe*(Qe+1+Se-Ve)),pe+Ze>=qe&&(ke-=pe+Ze-qe+4),Ce=Ne[ke++],Ae=Ne[ke++],Pe=Ne[ke++],b[Fe]=(E[Ce]+E[Ae+256|0]+E[Pe+512|0]>>16)-128,j[Fe]=(E[Ce+768|0]+E[Ae+1024|0]+E[Pe+1280|0]>>16)-128,S[Fe]=(E[Ce+1280|0]+E[Ae+1536|0]+E[Pe+1792|0]>>16)-128;be=ie(b,d,be,t,r),me=ie(j,u,me,n,a),he=ie(S,u,he,n,a),pe+=32}Qe+=8}if(g>=0){var Ue=[];Ue[1]=g+1,Ue[0]=(1<V;V++)if(I[D+V]!=O.charCodeAt(V))return!0;return!1}function r(I,D,O,V,G){for(var $=0;$$+1?[]:new D),!(H.length<$+1));Z++)V(G[Z],$+1,H)}(O,0,I),O}var c=function(){var I=this;function D(Te,Be){for(var ft=1<>>0;Te&ft;)ft>>>=1;return ft?(Te&ft-1)+ft:Te}function O(Te,Be,ft,_t,ss){t(!(_t%ft));do Te[Be+(_t-=ft)]=ss;while(0<_t)}function V(Te,Be,ft,_t,ss){if(t(2328>=ss),512>=ss)var ms=i(512);else if((ms=i(ss))==null)return 0;return function(vs,Cs,Rs,en,Mn,Xn){var tn,$n,nr=Cs,Mr=1<tn;++tn){if(br[tn]>1<(Al-=br[tn]))return 0;for(;0=tn;++tn,Mn<<=1){if(Oi+=Al<<=1,0>(Al-=br[tn]))return 0;for(;0Sa&&!(0>=(Vr-=br[Sa]));)++Sa,Vr<<=1;Mr+=Ki=1<<(Vr=Sa-Rs),vs[Cs+(Sa=ro&ba)].g=Vr+Rs,vs[Cs+Sa].value=nr-Cs-Sa}en.g=tn-Rs,en.value=Xn[$n++],O(vs,nr+(ro>>Rs),Mn,Ki,en),ro=D(ro,tn)}}return Oi!=2*Vn[15]-1?0:Mr}(Te,Be,ft,_t,ss,ms)}function G(){this.value=this.g=0}function $(){this.value=this.g=0}function H(){this.G=l(5,G),this.H=i(5),this.jc=this.Qb=this.qb=this.nd=0,this.pd=l(Cc,$)}function Y(Te,Be,ft,_t){t(Te!=null),t(Be!=null),t(2147483648>_t),Te.Ca=254,Te.I=0,Te.b=-8,Te.Ka=0,Te.oa=Be,Te.pa=ft,Te.Jd=Be,Te.Yc=ft+_t,Te.Zc=4<=_t?ft+_t-4+1:ft,Ce(Te)}function Z(Te,Be){for(var ft=0;0_t),Te.Sb=_t,Te.Ra=0,Te.u=0,Te.h=0,4<_t&&(_t=4),ss=0;ss<_t;++ss)ms+=Be[ft+ss]<<8*ss;Te.Ra=ms,Te.bb=_t,Te.oa=Be,Te.pa=ft}function ie(Te){for(;8<=Te.u&&Te.bb>>=8,Te.Ra+=Te.oa[Te.pa+Te.bb]<>>0,++Te.bb,Te.u-=8;me(Te)&&(Te.h=1,Te.u=0)}function te(Te,Be){if(t(0<=Be),!Te.h&&Be<=Lp){var ft=be(Te)&qa[Be];return Te.u+=Be,ie(Te),ft}return Te.h=1,Te.u=0}function ae(){this.b=this.Ca=this.I=0,this.oa=[],this.pa=0,this.Jd=[],this.Yc=0,this.Zc=[],this.Ka=0}function le(){this.Ra=0,this.oa=[],this.h=this.u=this.bb=this.Sb=this.pa=0}function be(Te){return Te.Ra>>>(Te.u&ou-1)>>>0}function me(Te){return t(Te.bb<=Te.Sb),Te.h||Te.bb==Te.Sb&&Te.u>ou}function he(Te,Be){Te.u=Be,Te.h=me(Te)}function pe(Te){Te.u>=va&&(t(Te.u>=va),ie(Te))}function Ce(Te){t(Te!=null&&Te.oa!=null),Te.pa>>0,Te.b+=8):(t(Te!=null&&Te.oa!=null),Te.paTe.b&&Ce(Te);var _t=Te.b,ss=ft*Be>>>8,ms=(Te.I>>>_t>ss)+0;for(ms?(ft-=ss,Te.I-=ss+1<<_t>>>0):ft=ss+1,_t=ft,ss=0;256<=_t;)ss+=8,_t>>=8;return _t=7^ss+Wg[_t],Te.b-=_t,Te.Ca=(ft<<_t)-1,ms}function ze(Te,Be,ft){Te[Be+0]=ft>>24&255,Te[Be+1]=ft>>16&255,Te[Be+2]=ft>>8&255,Te[Be+3]=255&ft}function ke(Te,Be){return Te[Be+0]|Te[Be+1]<<8}function Ze(Te,Be){return ke(Te,Be)|Te[Be+2]<<16}function Se(Te,Be){return ke(Te,Be)|ke(Te,Be+2)<<16}function Fe(Te,Be){var ft=1<=ss||0>=ms?0:(ft[0]=ss,_t[0]=ms,1)}function qe(Te,Be){return Te+(1<>>Be}function Qe(Te,Be){return((4278255360&Te)+(4278255360&Be)>>>0&4278255360)+((16711935&Te)+(16711935&Be)>>>0&16711935)>>>0}function Ue(Te,Be){I[Be]=function(ft,_t,ss,ms,vs,Cs,Rs){var en;for(en=0;en>>1)+(Te&Be)>>>0}function $e(Te){return 0<=Te&&256>Te?Te:0>Te?0:255>1))}function ct(Te,Be,ft){return Math.abs(Be-ft)-Math.abs(Te-ft)}function xt(Te,Be,ft,_t,ss,ms,vs){for(_t=ms[vs-1],ft=0;ft>8&255,Rs=16711935&(Rs=(Rs=16711935&vs)+((Cs<<16)+Cs));_t[ss+ms]=(4278255360&vs)+Rs>>>0}}function Vt(Te,Be){Be.jd=255&Te,Be.hd=Te>>8&255,Be.ud=Te>>16&255}function Xt(Te,Be,ft,_t,ss,ms){var vs;for(vs=0;vs<_t;++vs){var Cs=Be[ft+vs],Rs=Cs>>>8,en=Cs,Mn=255&(Mn=(Mn=Cs>>>16)+((Te.jd<<24>>24)*(Rs<<24>>24)>>>5));en=255&(en=(en+=(Te.hd<<24>>24)*(Rs<<24>>24)>>>5)+((Te.ud<<24>>24)*(Mn<<24>>24)>>>5)),ss[ms+vs]=(4278255360&Cs)+(Mn<<16)+en}}function fs(Te,Be,ft,_t,ss){I[Be]=function(ms,vs,Cs,Rs,en,Mn,Xn,tn,$n){for(Rs=Xn;Rs>ms.b,$n=ms.Ea,nr=ms.K[0],Mr=ms.w;if(8>tn)for(ms=(1<>=tn}else I["VP8LMapColor"+ft](Rs,en,nr,Mr,Mn,Xn,vs,Cs,$n)}}function Ft(Te,Be,ft,_t,ss){for(ft=Be+ft;Be>16&255,_t[ss++]=ms>>8&255,_t[ss++]=255&ms}}function wt(Te,Be,ft,_t,ss){for(ft=Be+ft;Be>16&255,_t[ss++]=ms>>8&255,_t[ss++]=255&ms,_t[ss++]=ms>>24&255}}function Ts(Te,Be,ft,_t,ss){for(ft=Be+ft;Be>16&240|vs>>12&15,vs=240&vs|vs>>28&15;_t[ss++]=ms,_t[ss++]=vs}}function vt(Te,Be,ft,_t,ss){for(ft=Be+ft;Be>16&248|vs>>13&7,vs=vs>>5&224|vs>>3&31;_t[ss++]=ms,_t[ss++]=vs}}function $s(Te,Be,ft,_t,ss){for(ft=Be+ft;Be>8&255,_t[ss++]=ms>>16&255}}function As(Te,Be,ft,_t,ss,ms){if(ms==0)for(ft=Be+ft;Be>24|ms[1]>>8&65280|ms[2]<<8&16711680|ms[3]<<24)>>>0),ss+=32;else r(_t,ss,Te,Be,ft)}function jn(Te,Be){I[Be][0]=I[Te+"0"],I[Be][1]=I[Te+"1"],I[Be][2]=I[Te+"2"],I[Be][3]=I[Te+"3"],I[Be][4]=I[Te+"4"],I[Be][5]=I[Te+"5"],I[Be][6]=I[Te+"6"],I[Be][7]=I[Te+"7"],I[Be][8]=I[Te+"8"],I[Be][9]=I[Te+"9"],I[Be][10]=I[Te+"10"],I[Be][11]=I[Te+"11"],I[Be][12]=I[Te+"12"],I[Be][13]=I[Te+"13"],I[Be][14]=I[Te+"0"],I[Be][15]=I[Te+"0"]}function ar(Te){return Te==P1||Te==ZN||Te==Gj||Te==q0}function Dn(){this.eb=[],this.size=this.A=this.fb=0}function Ur(){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 Vs(){this.Rd=this.height=this.width=this.S=0,this.f={},this.f.RGBA=new Dn,this.f.kb=new Ur,this.sd=null}function hn(){this.width=[0],this.height=[0],this.Pd=[0],this.Qd=[0],this.format=[0]}function dr(){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 Cn(Te){return alert("todo:WebPSamplerProcessPlane"),Te.T}function Yn(Te,Be){var ft=Te.T,_t=Be.ba.f.RGBA,ss=_t.eb,ms=_t.fb+Te.ka*_t.A,vs=ex[Be.ba.S],Cs=Te.y,Rs=Te.O,en=Te.f,Mn=Te.N,Xn=Te.ea,tn=Te.W,$n=Be.cc,nr=Be.dc,Mr=Be.Mc,br=Be.Nc,Vn=Te.ka,Vr=Te.ka+Te.T,Sa=Te.U,ba=Sa+1>>1;for(Vn==0?vs(Cs,Rs,null,null,en,Mn,Xn,tn,en,Mn,Xn,tn,ss,ms,null,null,Sa):(vs(Be.ec,Be.fc,Cs,Rs,$n,nr,Mr,br,en,Mn,Xn,tn,ss,ms-_t.A,ss,ms,Sa),++ft);Vn+2ft,ss=ft==Bb||ft==Jf||ft==Fv||ft==Uy||ft==12||ar(ft);if(Be.memory=null,Be.Ib=null,Be.Jb=null,Be.Nd=null,!sc(Be.Oa,Te,ss?11:12))return 0;if(ss&&ar(ft)&&Xh(),Te.da)alert("todo:use_scaling");else{if(_t){if(Be.Ib=Cn,Te.Kb){if(ft=Te.U+1>>1,Be.memory=i(Te.U+2*ft),Be.memory==null)return 0;Be.ec=Be.memory,Be.fc=0,Be.cc=Be.ec,Be.dc=Be.fc+Te.U,Be.Mc=Be.cc,Be.Nc=Be.dc+ft,Be.Ib=Yn,Xh()}}else alert("todo:EmitYUV");ss&&(Be.Jb=on,_t&&Hc())}if(_t&&!Qj){for(Te=0;256>Te;++Te)Jj[Te]=89858*(Te-128)+Zj>>Ov,e5[Te]=-22014*(Te-128)+Zj,JN[Te]=-45773*(Te-128),lw[Te]=113618*(Te-128)+Zj>>Ov;for(Te=Xj;Te>Ov,ZE[Te-Xj]=Ta(Be,255),cw[Te-Xj]=Ta(Be+8>>4,15);Qj=1}return 1}function Wn(Te){var Be=Te.ma,ft=Te.U,_t=Te.T;return t(!(1&Te.ka)),0>=ft||0>=_t?0:(ft=Be.Ib(Te,Be),Be.Jb!=null&&Be.Jb(Te,Be,ft),Be.Dc+=ft,1)}function Js(Te){Te.ma.memory=null}function Fa(Te,Be,ft,_t){return te(Te,8)!=47?0:(Be[0]=te(Te,14)+1,ft[0]=te(Te,14)+1,_t[0]=te(Te,1),te(Te,3)!=0?0:!Te.h)}function ks(Te,Be){if(4>Te)return Te+1;var ft=Te-2>>1;return(2+(1&Te)<>4)*Te+(8-(15&ft)))?ft:1;var ft}function Ws(Te,Be,ft){var _t=be(ft),ss=Te[Be+=255&_t].g-8;return 0>>0,t(8>=ft.g),Te.g}function Bn(Te,Be,ft){var _t=Te.xc;return t((Be=_t==0?0:Te.vc[Te.md*(ft>>_t)+(Be>>_t)])>Ki.b)*Oi;MrSa&&(Qi=Sa),(0,hh[xc[Cu++]>>8&15])(tn,$n+ +El,Vn,Vr+El-Sa,Qi-El,Vn,Vr+El),El=Qi}$n+=Sa,Vr+=Sa,++Mr&ro||(Ki+=Oi)}Xn!=en.nc&&r(Rs,Cs-nr,Rs,Cs+(Xn-Mn-1)*nr,nr);break;case 1:for(nr=tn,br=$n,Sa=(tn=en.Ea)-(Vr=tn&~(Vn=($n=1<>en.b)*Mr;Mn=ss),0ms.o&&(_t=ms.o),ft=_t?ft=0:(ss[0]+=4*ms.v,ms.ka=ft-ms.j,ms.U=ms.va-ms.v,ms.T=_t-ft,ft=1),ft){if(Cs=Cs[0],11>(ft=Te.ca).S){var Mn=ft.f.RGBA,Xn=(_t=ft.S,ss=ms.U,ms=ms.T,en=Mn.eb,Mn.A),tn=ms;for(Mn=Mn.fb+Te.Ma*Mn.A;0_t){var ss=Te.l.width,ms=ft.ca,vs=ft.tb+ss*_t,Cs=Te.V,Rs=Te.Ba+Te.c*_t,en=Te.gc;t(Te.ab==1),t(en[0].hc==3),df(en[0],_t,Be,Cs,Rs,ms,vs),pt(ft,_t,Be,ms,vs,ss)}Te.C=Te.Ma=Be}function Mt(Te,Be,ft,_t,ss,ms,vs){var Cs=Te.$/_t,Rs=Te.$%_t,en=Te.m,Mn=Te.s,Xn=ft+Te.$,tn=Xn;ss=ft+_t*ss;var $n=ft+_t*ms,nr=280+Mn.ua,Mr=Te.Pb?Cs:16777216,br=0=Mr){var ro=Xn-ft;t((Mr=Te).Pb),Mr.wd=Mr.m,Mr.xd=ro,0Al.g?(he(ba,ba.u+Al.g),ro[Oi]=Al.value,ba=0):(he(ba,ba.u+Al.g-256),t(256<=Al.value),ba=Al.value),ba==0&&(Sa=!0)}else ba=Ws(Vr.G[0],Vr.H[0],en);if(en.h)break;if(Sa||256>ba){if(!Sa)if(Vr.nd)Be[Xn]=(Vr.qb|ba<<8)>>>0;else{if(pe(en),Sa=Ws(Vr.G[1],Vr.H[1],en),pe(en),ro=Ws(Vr.G[2],Vr.H[2],en),Oi=Ws(Vr.G[3],Vr.H[3],en),en.h)break;Be[Xn]=(Oi<<24|Sa<<16|ba<<8|ro)>>>0}if(Sa=!1,++Xn,++Rs>=_t&&(Rs=0,++Cs,vs!=null&&Cs<=ms&&!(Cs%16)&&vs(Te,Cs),br!=null))for(;tn>>br.Mb]=ba}else if(280>ba){if(ba=ks(ba-256,en),ro=Ws(Vr.G[4],Vr.H[4],en),pe(en),ro=Gs(_t,ro=ks(ro,en)),en.h)break;if(Xn-ft=_t;)Rs-=_t,++Cs,vs!=null&&Cs<=ms&&!(Cs%16)&&vs(Te,Cs);if(t(Xn<=ss),Rs&Vn&&(Vr=Bn(Mn,Rs,Cs)),br!=null)for(;tn>>br.Mb]=ba}else{if(!(ba>>br.Mb]=ba;ba=Xn,t(!(Sa>>>(ro=br).Xa)),Be[ba]=ro.X[Sa],Sa=!0}Sa||t(en.h==me(en))}if(Te.Pb&&en.h&&Xnms?ms:Cs),Te.a=0,Te.$=Xn-ft}return 1}return Te.a=3,0}function es(Te){t(Te!=null),Te.vc=null,Te.yc=null,Te.Ya=null;var Be=Te.Wa;Be!=null&&(Be.X=null),Te.vb=null,t(Te!=null)}function ps(){var Te=new Ar;return Te==null?null:(Te.a=0,Te.xb=VC,jn("Predictor","VP8LPredictors"),jn("Predictor","VP8LPredictors_C"),jn("PredictorAdd","VP8LPredictorsAdd"),jn("PredictorAdd","VP8LPredictorsAdd_C"),Ry=qt,qd=Xt,uf=Ft,E1=wt,T1=Ts,ud=vt,Kg=$s,I.VP8LMapColor32b=Td,I.VP8LMapColor8b=ym,Te)}function Is(Te,Be,ft,_t,ss){var ms=1,vs=[Te],Cs=[Be],Rs=_t.m,en=_t.s,Mn=null,Xn=0;e:for(;;){if(ft)for(;ms&&te(Rs,1);){var tn=vs,$n=Cs,nr=_t,Mr=1,br=nr.m,Vn=nr.gc[nr.ab],Vr=te(br,2);if(nr.Oc&1<=nr.ab),Vr){case 0:case 1:Vn.b=te(br,3)+2,Mr=Is(qe(Vn.Ea,Vn.b),qe(Vn.nc,Vn.b),0,nr,Vn.K),Vn.K=Vn.K[0];break;case 3:var Sa,ba=te(br,8)+1,ro=16>Ki.b),Cu=i(xc);if(Cu==null)Sa=0;else{var El=Ki.K[0],Qi=Ki.w;for(Cu[0]=Ki.K[0][0],Oi=1;Oi<1*Al;++Oi)Cu[Oi]=Qe(El[Qi+Oi],Cu[Oi-1]);for(;Oi<4*xc;++Oi)Cu[Oi]=0;Ki.K[0]=null,Ki.K[0]=Cu,Sa=1}}Mr=Sa;break;case 2:break;default:t(0)}ms=Mr}}if(vs=vs[0],Cs=Cs[0],ms&&te(Rs,1)&&!(ms=1<=(Xn=te(Rs,4))&&11>=Xn)){_t.a=3;break e}var mi;if(mi=ms)t:{var Ll,Ao,gl,bu=_t,Bm=vs,_u=Cs,Xu=Xn,Vu=ft,sx=bu.m,lu=bu.s,ed=[null],Vd=1,fh=0,md=YE[Xu];s:for(;;){if(Vu&&te(sx,1)){var Ah=te(sx,3)+2,Ip=qe(Bm,Ah),Md=qe(_u,Ah),Qh=Ip*Md;if(!Is(Ip,Md,0,bu,ed))break s;for(ed=ed[0],lu.xc=Ah,Ll=0;Ll>8&65535;ed[Ll]=Ec,Ec>=Vd&&(Vd=Ec+1)}}if(sx.h)break s;for(Ao=0;5>Ao;++Ao){var Eh=KS[Ao];!Ao&&0=Au),rx=nx;var Rp=i(fh);if(rx==null||Rp==null||Dp==null){bu.a=1;break s}var wm=Dp;for(Ll=gl=0;LlAo;++Ao){Eh=KS[Ao],jr[Ao]=wm,zo[Ao]=gl,!Ao&&0Gb)break n}else Uv=Gb;for(bg=0;bgKb)a2[bg++]=Kb,Kb!=0&&(Vy=Kb);else{var WC=Kb==16,t5=Kb-16,D1=To[t5],R1=te(xh,BC[t5])+D1;if(bg+R1>Gb)break n;for(var KC=WC?Vy:0;0=Ao){var F1,G0=Rp[0];for(F1=1;F1G0&&(G0=Rp[F1]);sd+=G0}}if(td.nd=Gc,td.Qb=0,Gc&&(td.qb=(jr[3][zo[3]+0].value<<24|jr[1][zo[1]+0].value<<16|jr[2][zo[2]+0].value)>>>0,kd==0&&256>jr[0][zo[0]+0].value&&(td.Qb=1,td.qb+=jr[0][zo[0]+0].value<<8)),td.jc=!td.Qb&&6>sd,td.jc){var ek,Th=td;for(ek=0;ek>=Ys(ox,8,Eu),hp>>=Ys(Th.G[1][Th.H[1]+hp],16,Eu),hp>>=Ys(Th.G[2][Th.H[2]+hp],0,Eu),Ys(Th.G[3][Th.H[3]+hp],24,Eu))}}}lu.vc=ed,lu.Wb=Vd,lu.Ya=rx,lu.yc=Dp,mi=1;break t}mi=0}if(!(ms=mi)){_t.a=3;break e}if(0_t+1?[]:0),!(ss.length<_t+1));vs++)Be(ft[vs],_t+1,ss)}(Te,0,[3,11]),Te}()}function ma(){this.jb=i(3),this.Wc=o([4,8],Xr),this.Xc=o([4,17],Xr)}function Br(){this.Pc=this.wb=this.Tb=this.zd=0,this.vd=new i(4),this.od=new i(4)}function sa(){this.ld=this.La=this.dd=this.tc=0}function Rr(){this.Na=this.la=0}function ra(){this.Sc=[0,0],this.Eb=[0,0],this.Qc=[0,0],this.ia=this.lc=0}function Si(){this.ad=i(384),this.Za=0,this.Ob=i(16),this.$b=this.Ad=this.ia=this.Gc=this.Hc=this.Dd=0}function Gi(){this.uc=this.M=this.Nb=0,this.wa=Array(new sa),this.Y=0,this.ya=Array(new Si),this.aa=0,this.l=new eo}function rl(){this.y=i(16),this.f=i(8),this.ea=i(8)}function Ii(){this.cb=this.a=0,this.sc="",this.m=new ae,this.Od=new Qs,this.Kc=new an,this.ed=new Br,this.Qa=new er,this.Ic=this.$c=this.Aa=0,this.D=new Gi,this.Xb=this.Va=this.Hb=this.zb=this.yb=this.Ub=this.za=0,this.Jc=l(8,ae),this.ia=0,this.pb=l(4,ra),this.Pa=new ma,this.Bd=this.kc=0,this.Ac=[],this.Bc=0,this.zc=[0,0,0,0],this.Gd=Array(new rl),this.Hd=0,this.rb=Array(new Rr),this.sb=0,this.wa=Array(new sa),this.Y=0,this.oc=[],this.pc=0,this.sa=[],this.ta=0,this.qa=[],this.ra=0,this.Ha=[],this.B=this.R=this.Ia=0,this.Ec=[],this.M=this.ja=this.Vb=this.Fc=0,this.ya=Array(new Si),this.L=this.aa=0,this.gd=o([4,2],sa),this.ga=null,this.Fa=[],this.Cc=this.qc=this.P=0,this.Gb=[],this.Uc=0,this.mb=[],this.nb=0,this.rc=[],this.Ga=this.Vc=0}function Ta(Te,Be){return 0>Te?0:Te>Be?Be:Te}function eo(){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 So(){var Te=new Ii;return Te!=null&&(Te.a=0,Te.sc="OK",Te.cb=0,Te.Xb=0,Ub||(Ub=di)),Te}function Ra(Te,Be,ft){return Te.a==0&&(Te.a=Be,Te.sc=ft,Te.cb=0),0}function Eo(Te,Be,ft){return 3<=ft&&Te[Be+0]==157&&Te[Be+1]==1&&Te[Be+2]==42}function Ro(Te,Be){if(Te==null)return 0;if(Te.a=0,Te.sc="OK",Be==null)return Ra(Te,2,"null VP8Io passed to VP8GetHeaders()");var ft=Be.data,_t=Be.w,ss=Be.ha;if(4>ss)return Ra(Te,7,"Truncated header.");var ms=ft[_t+0]|ft[_t+1]<<8|ft[_t+2]<<16,vs=Te.Od;if(vs.Rb=!(1&ms),vs.td=ms>>1&7,vs.yd=ms>>4&1,vs.ub=ms>>5,3ss)return Ra(Te,7,"cannot parse picture header");if(!Eo(ft,_t,ss))return Ra(Te,3,"Bad code word");Cs.c=16383&(ft[_t+4]<<8|ft[_t+3]),Cs.Td=ft[_t+4]>>6,Cs.i=16383&(ft[_t+6]<<8|ft[_t+5]),Cs.Ud=ft[_t+6]>>6,_t+=7,ss-=7,Te.za=Cs.c+15>>4,Te.Ub=Cs.i+15>>4,Be.width=Cs.c,Be.height=Cs.i,Be.Da=0,Be.j=0,Be.v=0,Be.va=Be.width,Be.o=Be.height,Be.da=0,Be.ib=Be.width,Be.hb=Be.height,Be.U=Be.width,Be.T=Be.height,a((ms=Te.Pa).jb,0,255,ms.jb.length),t((ms=Te.Qa)!=null),ms.Cb=0,ms.Bb=0,ms.Fb=1,a(ms.Zb,0,0,ms.Zb.length),a(ms.Lb,0,0,ms.Lb)}if(vs.ub>ss)return Ra(Te,7,"bad partition length");Y(ms=Te.m,ft,_t,vs.ub),_t+=vs.ub,ss-=vs.ub,vs.Rb&&(Cs.Ld=Ae(ms),Cs.Kd=Ae(ms)),Cs=Te.Qa;var Rs,en=Te.Pa;if(t(ms!=null),t(Cs!=null),Cs.Cb=Ae(ms),Cs.Cb){if(Cs.Bb=Ae(ms),Ae(ms)){for(Cs.Fb=Ae(ms),Rs=0;4>Rs;++Rs)Cs.Zb[Rs]=Ae(ms)?ne(ms,7):0;for(Rs=0;4>Rs;++Rs)Cs.Lb[Rs]=Ae(ms)?ne(ms,6):0}if(Cs.Bb)for(Rs=0;3>Rs;++Rs)en.jb[Rs]=Ae(ms)?Z(ms,8):255}else Cs.Bb=0;if(ms.Ka)return Ra(Te,3,"cannot parse segment header");if((Cs=Te.ed).zd=Ae(ms),Cs.Tb=Z(ms,6),Cs.wb=Z(ms,3),Cs.Pc=Ae(ms),Cs.Pc&&Ae(ms)){for(en=0;4>en;++en)Ae(ms)&&(Cs.vd[en]=ne(ms,6));for(en=0;4>en;++en)Ae(ms)&&(Cs.od[en]=ne(ms,6))}if(Te.L=Cs.Tb==0?0:Cs.zd?1:2,ms.Ka)return Ra(Te,3,"cannot parse filter header");var Mn=ss;if(ss=Rs=_t,_t=Rs+Mn,Cs=Mn,Te.Xb=(1<Cs&&(Xn=Cs),Y(Te.Jc[+Mn],ft,Rs,Xn),Rs+=Xn,Cs-=Xn,ss+=3}Y(Te.Jc[+en],ft,Rs,Cs),ft=Rs<_t?0:5}if(ft!=0)return Ra(Te,ft,"cannot parse partitions");for(ft=Z(Rs=Te.m,7),ss=Ae(Rs)?ne(Rs,4):0,_t=Ae(Rs)?ne(Rs,4):0,Cs=Ae(Rs)?ne(Rs,4):0,en=Ae(Rs)?ne(Rs,4):0,Rs=Ae(Rs)?ne(Rs,4):0,Mn=Te.Qa,Xn=0;4>Xn;++Xn){if(Mn.Cb){var tn=Mn.Zb[Xn];Mn.Fb||(tn+=ft)}else{if(0>16,8>$n.Eb[1]&&($n.Eb[1]=8),$n.Qc[0]=iw[Ta(tn+en,117)],$n.Qc[1]=$C[Ta(tn+Rs,127)],$n.lc=tn+Rs}if(!vs.Rb)return Ra(Te,4,"Not a key frame.");for(Ae(ms),vs=Te.Pa,ft=0;4>ft;++ft){for(ss=0;8>ss;++ss)for(_t=0;3>_t;++_t)for(Cs=0;11>Cs;++Cs)en=Pe(ms,qb[ft][ss][_t][Cs])?Z(ms,8):ow[ft][ss][_t][Cs],vs.Wc[ft][ss].Yb[_t][Cs]=en;for(ss=0;17>ss;++ss)vs.Xc[ft][ss]=vs.Wc[ft][$b[ss]]}return Te.kc=Ae(ms),Te.kc&&(Te.Bd=Z(ms,8)),Te.cb=1}function di(Te,Be,ft,_t,ss,ms,vs){var Cs=Be[ss].Yb[ft];for(ft=0;16>ss;++ss){if(!Pe(Te,Cs[ft+0]))return ss;for(;!Pe(Te,Cs[ft+1]);)if(Cs=Be[++ss].Yb[0],ft=0,ss==16)return 16;var Rs=Be[ss+1].Yb;if(Pe(Te,Cs[ft+2])){var en=Te,Mn=0;if(Pe(en,(tn=Cs)[(Xn=ft)+3]))if(Pe(en,tn[Xn+6])){for(Cs=0,Xn=2*(Mn=Pe(en,tn[Xn+8]))+(tn=Pe(en,tn[Xn+9+Mn])),Mn=0,tn=UL[Xn];tn[Cs];++Cs)Mn+=Mn+Pe(en,tn[Cs]);Mn+=3+(8<(en=Te).b&&Ce(en);var Xn,tn=en.b,$n=(Xn=en.Ca>>1)-(en.I>>tn)>>31;--en.b,en.Ca+=$n,en.Ca|=1,en.I-=(Xn+1&$n)<>3),Te[Be+ft+32*_t]=-256&ss?0>ss?0:255:ss}function Oo(Te,Be,ft,_t,ss,ms){oi(Te,Be,0,ft,_t+ss),oi(Te,Be,1,ft,_t+ms),oi(Te,Be,2,ft,_t-ms),oi(Te,Be,3,ft,_t-ss)}function kl(Te){return(20091*Te>>16)+Te}function Jo(Te,Be,ft,_t){var ss,ms=0,vs=i(16);for(ss=0;4>ss;++ss){var Cs=Te[Be+0]+Te[Be+8],Rs=Te[Be+0]-Te[Be+8],en=(35468*Te[Be+4]>>16)-kl(Te[Be+12]),Mn=kl(Te[Be+4])+(35468*Te[Be+12]>>16);vs[ms+0]=Cs+Mn,vs[ms+1]=Rs+en,vs[ms+2]=Rs-en,vs[ms+3]=Cs-Mn,ms+=4,Be++}for(ss=ms=0;4>ss;++ss)Cs=(Te=vs[ms+0]+4)+vs[ms+8],Rs=Te-vs[ms+8],en=(35468*vs[ms+4]>>16)-kl(vs[ms+12]),oi(ft,_t,0,0,Cs+(Mn=kl(vs[ms+4])+(35468*vs[ms+12]>>16))),oi(ft,_t,1,0,Rs+en),oi(ft,_t,2,0,Rs-en),oi(ft,_t,3,0,Cs-Mn),ms++,_t+=32}function Sl(Te,Be,ft,_t){var ss=Te[Be+0]+4,ms=35468*Te[Be+4]>>16,vs=kl(Te[Be+4]),Cs=35468*Te[Be+1]>>16;Oo(ft,_t,0,ss+vs,Te=kl(Te[Be+1]),Cs),Oo(ft,_t,1,ss+ms,Te,Cs),Oo(ft,_t,2,ss-ms,Te,Cs),Oo(ft,_t,3,ss-vs,Te,Cs)}function vu(Te,Be,ft,_t,ss){Jo(Te,Be,ft,_t),ss&&Jo(Te,Be+16,ft,_t+4)}function Ku(Te,Be,ft,_t){vm(Te,Be+0,ft,_t,1),vm(Te,Be+32,ft,_t+128,1)}function Tp(Te,Be,ft,_t){var ss;for(Te=Te[Be+0]+4,ss=0;4>ss;++ss)for(Be=0;4>Be;++Be)oi(ft,_t,Be,ss,Te)}function Bd(Te,Be,ft,_t){Te[Be+0]&&mh(Te,Be+0,ft,_t),Te[Be+16]&&mh(Te,Be+16,ft,_t+4),Te[Be+32]&&mh(Te,Be+32,ft,_t+128),Te[Be+48]&&mh(Te,Be+48,ft,_t+128+4)}function xm(Te,Be,ft,_t){var ss,ms=i(16);for(ss=0;4>ss;++ss){var vs=Te[Be+0+ss]+Te[Be+12+ss],Cs=Te[Be+4+ss]+Te[Be+8+ss],Rs=Te[Be+4+ss]-Te[Be+8+ss],en=Te[Be+0+ss]-Te[Be+12+ss];ms[0+ss]=vs+Cs,ms[8+ss]=vs-Cs,ms[4+ss]=en+Rs,ms[12+ss]=en-Rs}for(ss=0;4>ss;++ss)vs=(Te=ms[0+4*ss]+3)+ms[3+4*ss],Cs=ms[1+4*ss]+ms[2+4*ss],Rs=ms[1+4*ss]-ms[2+4*ss],en=Te-ms[3+4*ss],ft[_t+0]=vs+Cs>>3,ft[_t+16]=en+Rs>>3,ft[_t+32]=vs-Cs>>3,ft[_t+48]=en-Rs>>3,_t+=64}function xs(Te,Be,ft){var _t,ss=Be-32,ms=_m,vs=255-Te[ss-1];for(_t=0;_tft;++ft)r(Te,Be+32*ft,Te,Be-32,16)}function Co(Te,Be){var ft;for(ft=16;0_t;++_t)a(Be,ft+32*_t,Te,16)}function Bu(Te,Be){var ft,_t=16;for(ft=0;16>ft;++ft)_t+=Te[Be-1+32*ft]+Te[Be+ft-32];bi(_t>>5,Te,Be)}function Uu(Te,Be){var ft,_t=8;for(ft=0;16>ft;++ft)_t+=Te[Be-1+32*ft];bi(_t>>4,Te,Be)}function Rx(Te,Be){var ft,_t=8;for(ft=0;16>ft;++ft)_t+=Te[Be+ft-32];bi(_t>>4,Te,Be)}function hl(Te,Be){bi(128,Te,Be)}function Ua(Te,Be,ft){return Te+2*Be+ft+2>>2}function ml(Te,Be){var ft,_t=Be-32;for(_t=new Uint8Array([Ua(Te[_t-1],Te[_t+0],Te[_t+1]),Ua(Te[_t+0],Te[_t+1],Te[_t+2]),Ua(Te[_t+1],Te[_t+2],Te[_t+3]),Ua(Te[_t+2],Te[_t+3],Te[_t+4])]),ft=0;4>ft;++ft)r(Te,Be+32*ft,_t,0,_t.length)}function fg(Te,Be){var ft=Te[Be-1],_t=Te[Be-1+32],ss=Te[Be-1+64],ms=Te[Be-1+96];ze(Te,Be+0,16843009*Ua(Te[Be-1-32],ft,_t)),ze(Te,Be+32,16843009*Ua(ft,_t,ss)),ze(Te,Be+64,16843009*Ua(_t,ss,ms)),ze(Te,Be+96,16843009*Ua(ss,ms,ms))}function Hg(Te,Be){var ft,_t=4;for(ft=0;4>ft;++ft)_t+=Te[Be+ft-32]+Te[Be-1+32*ft];for(_t>>=3,ft=0;4>ft;++ft)a(Te,Be+32*ft,_t,4)}function Dv(Te,Be){var ft=Te[Be-1+0],_t=Te[Be-1+32],ss=Te[Be-1+64],ms=Te[Be-1-32],vs=Te[Be+0-32],Cs=Te[Be+1-32],Rs=Te[Be+2-32],en=Te[Be+3-32];Te[Be+0+96]=Ua(_t,ss,Te[Be-1+96]),Te[Be+1+96]=Te[Be+0+64]=Ua(ft,_t,ss),Te[Be+2+96]=Te[Be+1+64]=Te[Be+0+32]=Ua(ms,ft,_t),Te[Be+3+96]=Te[Be+2+64]=Te[Be+1+32]=Te[Be+0+0]=Ua(vs,ms,ft),Te[Be+3+64]=Te[Be+2+32]=Te[Be+1+0]=Ua(Cs,vs,ms),Te[Be+3+32]=Te[Be+2+0]=Ua(Rs,Cs,vs),Te[Be+3+0]=Ua(en,Rs,Cs)}function Dc(Te,Be){var ft=Te[Be+1-32],_t=Te[Be+2-32],ss=Te[Be+3-32],ms=Te[Be+4-32],vs=Te[Be+5-32],Cs=Te[Be+6-32],Rs=Te[Be+7-32];Te[Be+0+0]=Ua(Te[Be+0-32],ft,_t),Te[Be+1+0]=Te[Be+0+32]=Ua(ft,_t,ss),Te[Be+2+0]=Te[Be+1+32]=Te[Be+0+64]=Ua(_t,ss,ms),Te[Be+3+0]=Te[Be+2+32]=Te[Be+1+64]=Te[Be+0+96]=Ua(ss,ms,vs),Te[Be+3+32]=Te[Be+2+64]=Te[Be+1+96]=Ua(ms,vs,Cs),Te[Be+3+64]=Te[Be+2+96]=Ua(vs,Cs,Rs),Te[Be+3+96]=Ua(Cs,Rs,Rs)}function Mp(Te,Be){var ft=Te[Be-1+0],_t=Te[Be-1+32],ss=Te[Be-1+64],ms=Te[Be-1-32],vs=Te[Be+0-32],Cs=Te[Be+1-32],Rs=Te[Be+2-32],en=Te[Be+3-32];Te[Be+0+0]=Te[Be+1+64]=ms+vs+1>>1,Te[Be+1+0]=Te[Be+2+64]=vs+Cs+1>>1,Te[Be+2+0]=Te[Be+3+64]=Cs+Rs+1>>1,Te[Be+3+0]=Rs+en+1>>1,Te[Be+0+96]=Ua(ss,_t,ft),Te[Be+0+64]=Ua(_t,ft,ms),Te[Be+0+32]=Te[Be+1+96]=Ua(ft,ms,vs),Te[Be+1+32]=Te[Be+2+96]=Ua(ms,vs,Cs),Te[Be+2+32]=Te[Be+3+96]=Ua(vs,Cs,Rs),Te[Be+3+32]=Ua(Cs,Rs,en)}function op(Te,Be){var ft=Te[Be+0-32],_t=Te[Be+1-32],ss=Te[Be+2-32],ms=Te[Be+3-32],vs=Te[Be+4-32],Cs=Te[Be+5-32],Rs=Te[Be+6-32],en=Te[Be+7-32];Te[Be+0+0]=ft+_t+1>>1,Te[Be+1+0]=Te[Be+0+64]=_t+ss+1>>1,Te[Be+2+0]=Te[Be+1+64]=ss+ms+1>>1,Te[Be+3+0]=Te[Be+2+64]=ms+vs+1>>1,Te[Be+0+32]=Ua(ft,_t,ss),Te[Be+1+32]=Te[Be+0+96]=Ua(_t,ss,ms),Te[Be+2+32]=Te[Be+1+96]=Ua(ss,ms,vs),Te[Be+3+32]=Te[Be+2+96]=Ua(ms,vs,Cs),Te[Be+3+64]=Ua(vs,Cs,Rs),Te[Be+3+96]=Ua(Cs,Rs,en)}function xg(Te,Be){var ft=Te[Be-1+0],_t=Te[Be-1+32],ss=Te[Be-1+64],ms=Te[Be-1+96];Te[Be+0+0]=ft+_t+1>>1,Te[Be+2+0]=Te[Be+0+32]=_t+ss+1>>1,Te[Be+2+32]=Te[Be+0+64]=ss+ms+1>>1,Te[Be+1+0]=Ua(ft,_t,ss),Te[Be+3+0]=Te[Be+1+32]=Ua(_t,ss,ms),Te[Be+3+32]=Te[Be+1+64]=Ua(ss,ms,ms),Te[Be+3+64]=Te[Be+2+64]=Te[Be+0+96]=Te[Be+1+96]=Te[Be+2+96]=Te[Be+3+96]=ms}function Rv(Te,Be){var ft=Te[Be-1+0],_t=Te[Be-1+32],ss=Te[Be-1+64],ms=Te[Be-1+96],vs=Te[Be-1-32],Cs=Te[Be+0-32],Rs=Te[Be+1-32],en=Te[Be+2-32];Te[Be+0+0]=Te[Be+2+32]=ft+vs+1>>1,Te[Be+0+32]=Te[Be+2+64]=_t+ft+1>>1,Te[Be+0+64]=Te[Be+2+96]=ss+_t+1>>1,Te[Be+0+96]=ms+ss+1>>1,Te[Be+3+0]=Ua(Cs,Rs,en),Te[Be+2+0]=Ua(vs,Cs,Rs),Te[Be+1+0]=Te[Be+3+32]=Ua(ft,vs,Cs),Te[Be+1+32]=Te[Be+3+64]=Ua(_t,ft,vs),Te[Be+1+64]=Te[Be+3+96]=Ua(ss,_t,ft),Te[Be+1+96]=Ua(ms,ss,_t)}function Xf(Te,Be){var ft;for(ft=0;8>ft;++ft)r(Te,Be+32*ft,Te,Be-32,8)}function Ti(Te,Be){var ft;for(ft=0;8>ft;++ft)a(Te,Be,Te[Be-1],8),Be+=32}function gm(Te,Be,ft){var _t;for(_t=0;8>_t;++_t)a(Be,ft+32*_t,Te,8)}function Gg(Te,Be){var ft,_t=8;for(ft=0;8>ft;++ft)_t+=Te[Be+ft-32]+Te[Be-1+32*ft];gm(_t>>4,Te,Be)}function wd(Te,Be){var ft,_t=4;for(ft=0;8>ft;++ft)_t+=Te[Be+ft-32];gm(_t>>3,Te,Be)}function jd(Te,Be){var ft,_t=4;for(ft=0;8>ft;++ft)_t+=Te[Be-1+32*ft];gm(_t>>3,Te,Be)}function Yu(Te,Be){gm(128,Te,Be)}function Yh(Te,Be,ft){var _t=Te[Be-ft],ss=Te[Be+0],ms=3*(ss-_t)+rw[1020+Te[Be-2*ft]-Te[Be+ft]],vs=hf[112+(ms+4>>3)];Te[Be-ft]=_m[255+_t+hf[112+(ms+3>>3)]],Te[Be+0]=_m[255+ss-vs]}function B0(Te,Be,ft,_t){var ss=Te[Be+0],ms=Te[Be+ft];return ur[255+Te[Be-2*ft]-Te[Be-ft]]>_t||ur[255+ms-ss]>_t}function kh(Te,Be,ft,_t){return 4*ur[255+Te[Be-ft]-Te[Be+0]]+ur[255+Te[Be-2*ft]-Te[Be+ft]]<=_t}function Sh(Te,Be,ft,_t,ss){var ms=Te[Be-3*ft],vs=Te[Be-2*ft],Cs=Te[Be-ft],Rs=Te[Be+0],en=Te[Be+ft],Mn=Te[Be+2*ft],Xn=Te[Be+3*ft];return 4*ur[255+Cs-Rs]+ur[255+vs-en]>_t?0:ur[255+Te[Be-4*ft]-ms]<=ss&&ur[255+ms-vs]<=ss&&ur[255+vs-Cs]<=ss&&ur[255+Xn-Mn]<=ss&&ur[255+Mn-en]<=ss&&ur[255+en-Rs]<=ss}function Zh(Te,Be,ft,_t){var ss=2*_t+1;for(_t=0;16>_t;++_t)kh(Te,Be+_t,ft,ss)&&Yh(Te,Be+_t,ft)}function qu(Te,Be,ft,_t){var ss=2*_t+1;for(_t=0;16>_t;++_t)kh(Te,Be+_t*ft,1,ss)&&Yh(Te,Be+_t*ft,1)}function Qf(Te,Be,ft,_t){var ss;for(ss=3;0>7,Vn=18*Vr+63>>7,Vr=9*Vr+63>>7;Rs[en-3*Mn]=_m[255+Rs[en-3*Mn]+Vr],Rs[en-2*Mn]=_m[255+Xn+Vn],Rs[en-Mn]=_m[255+tn+br],Rs[en+0]=_m[255+$n-br],Rs[en+Mn]=_m[255+nr-Vn],Rs[en+2*Mn]=_m[255+Mr-Vr]}Be+=_t}}function Nd(Te,Be,ft,_t,ss,ms,vs,Cs){for(ms=2*ms+1;0>3)],Mr=hf[112+(Mr+3>>3)],br=nr+1>>1;Rs[en-2*Mn]=_m[255+Rs[en-2*Mn]+br],Rs[en-Mn]=_m[255+Xn+Mr],Rs[en+0]=_m[255+tn-nr],Rs[en+Mn]=_m[255+$n-br]}Be+=_t}}function cf(Te,Be,ft,_t,ss,ms){dc(Te,Be,ft,1,16,_t,ss,ms)}function iu(Te,Be,ft,_t,ss,ms){dc(Te,Be,1,ft,16,_t,ss,ms)}function lp(Te,Be,ft,_t,ss,ms){var vs;for(vs=3;0en?0:255:en)&255,en=Rs,ss[ms+Cs]=Mn}}function cd(Te,Be,ft,_t){var ss=Be.width,ms=Be.o;if(t(Te!=null&&Be!=null),0>ft||0>=_t||ft+_t>ms)return null;if(!Te.Cc){if(Te.ga==null){var vs;if(Te.ga=new wi,(vs=Te.ga==null)||(vs=Be.width*Be.o,t(Te.Gb.length==0),Te.Gb=i(vs),Te.Uc=0,Te.Gb==null?vs=0:(Te.mb=Te.Gb,Te.nb=Te.Uc,Te.rc=null,vs=1),vs=!vs),!vs){vs=Te.ga;var Cs=Te.Fa,Rs=Te.P,en=Te.qc,Mn=Te.mb,Xn=Te.nb,tn=Rs+1,$n=en-1,nr=vs.l;if(t(Cs!=null&&Mn!=null&&Be!=null),yg[0]=null,yg[1]=Po,yg[2]=bo,yg[3]=Vl,vs.ca=Mn,vs.tb=Xn,vs.c=Be.width,vs.i=Be.height,t(0=en)Be=0;else if(vs.$a=3&Cs[Rs+0],vs.Z=Cs[Rs+0]>>2&3,vs.Lc=Cs[Rs+0]>>4&3,Rs=Cs[Rs+0]>>6&3,0>vs.$a||1=vs.c*vs.i;vs=!Be}if(vs)return null;Te.ga.Lc!=1?Te.Ga=0:_t=ms-ft}t(Te.ga!=null),t(ft+_t<=ms);e:{if(Be=(Cs=Te.ga).c,ms=Cs.l.o,Cs.$a==0){if(tn=Te.rc,$n=Te.Vc,nr=Te.Fa,Rs=Te.P+1+ft*Be,en=Te.mb,Mn=Te.nb+ft*Be,t(Rs<=Te.P+Te.qc),Cs.Z!=0)for(t(yg[Cs.Z]!=null),vs=0;vs<_t;++vs)yg[Cs.Z](tn,$n,nr,Rs,en,Mn,Be),tn=en,$n=Mn,Mn+=Be,Rs+=Be;else for(vs=0;vs<_t;++vs)r(en,Mn,nr,Rs,Be),tn=en,$n=Mn,Mn+=Be,Rs+=Be;Te.rc=tn,Te.Vc=$n}else{if(t(Cs.mc!=null),Be=ft+_t,t((vs=Cs.mc)!=null),t(Be<=vs.i),vs.C>=Be)Be=1;else if(Cs.ic||Hc(),Cs.ic){Cs=vs.V,tn=vs.Ba,$n=vs.c;var Mr=vs.i,br=(nr=1,Rs=vs.$/$n,en=vs.$%$n,Mn=vs.m,Xn=vs.s,vs.$),Vn=$n*Mr,Vr=$n*Be,Sa=Xn.wc,ba=br(Mr=Ws(ba.G[0],ba.H[0],Mn)))Cs[tn+br]=Mr,++br,++en>=$n&&(en=0,++Rs<=Be&&!(Rs%16)&&jt(vs,Rs));else{if(!(280>Mr)){nr=0;break t}Mr=ks(Mr-256,Mn);var ro,Oi=Ws(ba.G[4],ba.H[4],Mn);if(pe(Mn),!(br>=(Oi=Gs($n,Oi=ks(Oi,Mn)))&&Vn-br>=Mr)){nr=0;break t}for(ro=0;ro=$n;)en-=$n,++Rs<=Be&&!(Rs%16)&&jt(vs,Rs);brBe?Be:Rs);break t}!nr||Mn.h&&br=ms&&(Te.Cc=1),_t=1}if(!_t)return null;if(Te.Cc&&((_t=Te.ga)!=null&&(_t.mc=null),Te.ga=null,0>23,Cs[Rs+4*vs+1]=Cs[Rs+4*vs+1]*Xn>>23,Cs[Rs+4*vs+2]=Cs[Rs+4*vs+2]*Xn>>23)}Be+=ms}}function fi(Te,Be,ft,_t,ss){for(;0<_t--;){var ms;for(ms=0;ms>4)*Rs>>16;Te[Be+2*ms+0]=(240&vs|vs>>4)*Rs>>16&240|(15&vs|vs<<4)*Rs>>16>>4&15,Te[Be+2*ms+1]=240&en|Cs}Be+=ss}}function Ci(Te,Be,ft,_t,ss,ms,vs,Cs){var Rs,en,Mn=255;for(en=0;en>8}function Hc(){zy=$r,Hj=fi,By=Ci,nw=tc}function ho(Te,Be,ft){I[Te]=function(_t,ss,ms,vs,Cs,Rs,en,Mn,Xn,tn,$n,nr,Mr,br,Vn,Vr,Sa){var ba,ro=Sa-1>>1,Oi=Cs[Rs+0]|en[Mn+0]<<16,Al=Xn[tn+0]|$n[nr+0]<<16;t(_t!=null);var Ki=3*Oi+Al+131074>>2;for(Be(_t[ss+0],255&Ki,Ki>>16,Mr,br),ms!=null&&(Ki=3*Al+Oi+131074>>2,Be(ms[vs+0],255&Ki,Ki>>16,Vn,Vr)),ba=1;ba<=ro;++ba){var xc=Cs[Rs+ba]|en[Mn+ba]<<16,Cu=Xn[tn+ba]|$n[nr+ba]<<16,El=Oi+xc+Al+Cu+524296,Qi=El+2*(xc+Al)>>3;Ki=Qi+Oi>>1,Oi=(El=El+2*(Oi+Cu)>>3)+xc>>1,Be(_t[ss+2*ba-1],255&Ki,Ki>>16,Mr,br+(2*ba-1)*ft),Be(_t[ss+2*ba-0],255&Oi,Oi>>16,Mr,br+(2*ba-0)*ft),ms!=null&&(Ki=El+Al>>1,Oi=Qi+Cu>>1,Be(ms[vs+2*ba-1],255&Ki,Ki>>16,Vn,Vr+(2*ba-1)*ft),Be(ms[vs+2*ba+0],255&Oi,Oi>>16,Vn,Vr+(2*ba+0)*ft)),Oi=xc,Al=Cu}1&Sa||(Ki=3*Oi+Al+131074>>2,Be(_t[ss+Sa-1],255&Ki,Ki>>16,Mr,br+(Sa-1)*ft),ms!=null&&(Ki=3*Al+Oi+131074>>2,Be(ms[vs+Sa-1],255&Ki,Ki>>16,Vn,Vr+(Sa-1)*ft)))}}function Xh(){ex[zb]=QN,ex[Bb]=Kj,ex[M1]=ZS,ex[Jf]=Yj,ex[Fv]=tx,ex[Uy]=mf,ex[aw]=HC,ex[P1]=Kj,ex[ZN]=Yj,ex[Gj]=tx,ex[q0]=mf}function $t(Te){return Te&~JS?0>Te?0:255:Te>>QS}function Nn(Te,Be){return $t((19077*Te>>8)+(26149*Be>>8)-14234)}function Un(Te,Be,ft){return $t((19077*Te>>8)-(6419*Be>>8)-(13320*ft>>8)+8708)}function qr(Te,Be){return $t((19077*Te>>8)+(33050*Be>>8)-17685)}function Ea(Te,Be,ft,_t,ss){_t[ss+0]=Nn(Te,ft),_t[ss+1]=Un(Te,Be,ft),_t[ss+2]=qr(Te,Be)}function gi(Te,Be,ft,_t,ss){_t[ss+0]=qr(Te,Be),_t[ss+1]=Un(Te,Be,ft),_t[ss+2]=Nn(Te,ft)}function Mi(Te,Be,ft,_t,ss){var ms=Un(Te,Be,ft);Be=ms<<3&224|qr(Te,Be)>>3,_t[ss+0]=248&Nn(Te,ft)|ms>>5,_t[ss+1]=Be}function _i(Te,Be,ft,_t,ss){var ms=240&qr(Te,Be)|15;_t[ss+0]=240&Nn(Te,ft)|Un(Te,Be,ft)>>4,_t[ss+1]=ms}function Jc(Te,Be,ft,_t,ss){_t[ss+0]=255,Ea(Te,Be,ft,_t,ss+1)}function Su(Te,Be,ft,_t,ss){gi(Te,Be,ft,_t,ss),_t[ss+3]=255}function cp(Te,Be,ft,_t,ss){Ea(Te,Be,ft,_t,ss),_t[ss+3]=255}function dd(Te,Be,ft){I[Te]=function(_t,ss,ms,vs,Cs,Rs,en,Mn,Xn){for(var tn=Mn+(-2&Xn)*ft;Mn!=tn;)Be(_t[ss+0],ms[vs+0],Cs[Rs+0],en,Mn),Be(_t[ss+1],ms[vs+0],Cs[Rs+0],en,Mn+ft),ss+=2,++vs,++Rs,Mn+=2*ft;1&Xn&&Be(_t[ss+0],ms[vs+0],Cs[Rs+0],en,Mn)}}function Ud(Te,Be,ft){return ft==0?Te==0?Be==0?6:5:Be==0?4:0:ft}function Ch(Te,Be,ft,_t,ss){switch(Te>>>30){case 3:vm(Be,ft,_t,ss,0);break;case 2:zx(Be,ft,_t,ss);break;case 1:mh(Be,ft,_t,ss)}}function Pp(Te,Be){var ft,_t,ss=Be.M,ms=Be.Nb,vs=Te.oc,Cs=Te.pc+40,Rs=Te.oc,en=Te.pc+584,Mn=Te.oc,Xn=Te.pc+600;for(ft=0;16>ft;++ft)vs[Cs+32*ft-1]=129;for(ft=0;8>ft;++ft)Rs[en+32*ft-1]=129,Mn[Xn+32*ft-1]=129;for(0ft;++ft)r(vs,Cs+32*ft-4,vs,Cs+32*ft+12,4);for(ft=-1;8>ft;++ft)r(Rs,en+32*ft-4,Rs,en+32*ft+4,4),r(Mn,Xn+32*ft-4,Mn,Xn+32*ft+4,4)}var $n=Te.Gd,nr=Te.Hd+_t,Mr=tn.ad,br=tn.Hc;if(0=Te.za-1?a(Vn,Vr,$n[nr].y[15],4):r(Vn,Vr,$n[nr+1].y,0,4)),ft=0;4>ft;ft++)Vn[Vr+128+ft]=Vn[Vr+256+ft]=Vn[Vr+384+ft]=Vn[Vr+0+ft];for(ft=0;16>ft;++ft,br<<=2)Vn=vs,Vr=Cs+zv[ft],Zu[tn.Ob[ft]](Vn,Vr),Ch(br,Mr,16*+ft,Vn,Vr)}else if(Vn=Ud(_t,ss,tn.Ob[0]),Bx[Vn](vs,Cs),br!=0)for(ft=0;16>ft;++ft,br<<=2)Ch(br,Mr,16*+ft,vs,Cs+zv[ft]);for(ft=tn.Gc,Vn=Ud(_t,ss,tn.Dd),V0[Vn](Rs,en),V0[Vn](Mn,Xn),br=Mr,Vn=Rs,Vr=en,255&(tn=0|ft)&&(170&tn?Rb(br,256,Vn,Vr):Ac(br,256,Vn,Vr)),tn=Mn,br=Xn,255&(ft>>=8)&&(170&ft?Rb(Mr,320,tn,br):Ac(Mr,320,tn,br)),ssft;++ft)r($n,nr+ft*Te.R,vs,Cs+32*ft,16);for(ft=0;8>ft;++ft)r(Mr,tn+ft*Te.B,Rs,en+32*ft,8),r(br,Vn+ft*Te.B,Mn,Xn+32*ft,8)}}function Fx(Te,Be,ft,_t,ss,ms,vs,Cs,Rs){var en=[0],Mn=[0],Xn=0,tn=Rs!=null?Rs.kd:0,$n=Rs??new An;if(Te==null||12>ft)return 7;$n.data=Te,$n.w=Be,$n.ha=ft,Be=[Be],ft=[ft],$n.gb=[$n.gb];e:{var nr=Be,Mr=ft,br=$n.gb;if(t(Te!=null),t(Mr!=null),t(br!=null),br[0]=0,12<=Mr[0]&&!n(Te,nr[0],"RIFF")){if(n(Te,nr[0]+8,"WEBP")){br=3;break e}var Vn=Se(Te,nr[0]+4);if(12>Vn||4294967286Mr[0]-8){br=7;break e}br[0]=Vn,nr[0]+=12,Mr[0]-=12}br=0}if(br!=0)return br;for(Vn=0<$n.gb[0],ft=ft[0];;){e:{var Vr=Te;Mr=Be,br=ft;var Sa=en,ba=Mn,ro=nr=[0];if((Ki=Xn=[Xn])[0]=0,8>br[0])br=7;else{if(!n(Vr,Mr[0],"VP8X")){if(Se(Vr,Mr[0]+4)!=10){br=3;break e}if(18>br[0]){br=7;break e}var Oi=Se(Vr,Mr[0]+8),Al=1+Ze(Vr,Mr[0]+12);if(2147483648<=Al*(Vr=1+Ze(Vr,Mr[0]+15))){br=3;break e}ro!=null&&(ro[0]=Oi),Sa!=null&&(Sa[0]=Al),ba!=null&&(ba[0]=Vr),Mr[0]+=18,br[0]-=18,Ki[0]=1}br=0}}if(Xn=Xn[0],nr=nr[0],br!=0)return br;if(Mr=!!(2&nr),!Vn&&Xn)return 3;if(ms!=null&&(ms[0]=!!(16&nr)),vs!=null&&(vs[0]=Mr),Cs!=null&&(Cs[0]=0),vs=en[0],nr=Mn[0],Xn&&Mr&&Rs==null){br=0;break}if(4>ft){br=7;break}if(Vn&&Xn||!Vn&&!Xn&&!n(Te,Be[0],"ALPH")){ft=[ft],$n.na=[$n.na],$n.P=[$n.P],$n.Sa=[$n.Sa];e:{Oi=Te,br=Be,Vn=ft;var Ki=$n.gb;Sa=$n.na,ba=$n.P,ro=$n.Sa,Al=22,t(Oi!=null),t(Vn!=null),Vr=br[0];var xc=Vn[0];for(t(Sa!=null),t(ro!=null),Sa[0]=null,ba[0]=null,ro[0]=0;;){if(br[0]=Vr,Vn[0]=xc,8>xc){br=7;break e}var Cu=Se(Oi,Vr+4);if(4294967286Ki){br=3;break e}if(!n(Oi,Vr,"VP8 ")||!n(Oi,Vr,"VP8L")){br=0;break e}if(xc[0]Vn[0])br=7;else{if(Vr||Al){if(Ki=Se(Ki,Oi+4),12<=Sa&&Ki>Sa-12){br=3;break e}if(tn&&Ki>Vn[0]-8){br=7;break e}ba[0]=Ki,br[0]+=8,Vn[0]-=8,ro[0]=Al}else ro[0]=5<=Vn[0]&&Ki[Oi+0]==47&&!(Ki[Oi+4]>>5),ba[0]=Vn[0];br=0}if(ft=ft[0],$n.Ja=$n.Ja[0],$n.xa=$n.xa[0],Be=Be[0],br!=0)break;if(4294967286<$n.Ja)return 3;if(Cs==null||Mr||(Cs[0]=$n.xa?2:1),vs=[vs],nr=[nr],$n.xa){if(5>ft){br=7;break}Cs=vs,tn=nr,Mr=ms,Te==null||5>ft?Te=0:5<=ft&&Te[Be+0]==47&&!(Te[Be+4]>>5)?(Vn=[0],Ki=[0],Sa=[0],ce(ba=new le,Te,Be,ft),Fa(ba,Vn,Ki,Sa)?(Cs!=null&&(Cs[0]=Vn[0]),tn!=null&&(tn[0]=Ki[0]),Mr!=null&&(Mr[0]=Sa[0]),Te=1):Te=0):Te=0}else{if(10>ft){br=7;break}Cs=nr,Te==null||10>ft||!Eo(Te,Be+3,ft-3)?Te=0:(tn=Te[Be+0]|Te[Be+1]<<8|Te[Be+2]<<16,Mr=16383&(Te[Be+7]<<8|Te[Be+6]),Te=16383&(Te[Be+9]<<8|Te[Be+8]),1&tn||3<(tn>>1&7)||!(tn>>4&1)||tn>>5>=$n.Ja||!Mr||!Te?Te=0:(vs&&(vs[0]=Mr),Cs&&(Cs[0]=Te),Te=1))}if(!Te||(vs=vs[0],nr=nr[0],Xn&&(en[0]!=vs||Mn[0]!=nr)))return 3;Rs!=null&&(Rs[0]=$n,Rs.offset=Be-Rs.w,t(4294967286>Be-Rs.w),t(Rs.offset==Rs.ha-ft));break}return br==0||br==7&&Xn&&Rs==null?(ms!=null&&(ms[0]|=$n.na!=null&&0<$n.na.length),_t!=null&&(_t[0]=vs),ss!=null&&(ss[0]=nr),0):br}function sc(Te,Be,ft){var _t=Be.width,ss=Be.height,ms=0,vs=0,Cs=_t,Rs=ss;if(Be.Da=Te!=null&&0ft||(ms&=-2,vs&=-2),0>ms||0>vs||0>=Cs||0>=Rs||ms+Cs>_t||vs+Rs>ss))return 0;if(Be.v=ms,Be.j=vs,Be.va=ms+Cs,Be.o=vs+Rs,Be.U=Cs,Be.T=Rs,Be.da=Te!=null&&0Te.S){var Be=Te.f.RGBA;Be.fb+=(Te.height-1)*Be.A,Be.A=-Be.A}else Be=Te.f.kb,Te=Te.height,Be.O+=(Te-1)*Be.fa,Be.fa=-Be.fa,Be.N+=(Te-1>>1)*Be.Ab,Be.Ab=-Be.Ab,Be.W+=(Te-1>>1)*Be.Db,Be.Db=-Be.Db,Be.F!=null&&(Be.J+=(Te-1)*Be.lb,Be.lb=-Be.lb);return 0}function Hr(Te,Be,ft,_t){if(_t==null||0>=Te||0>=Be)return 2;if(ft!=null){if(ft.Da){var ss=ft.cd,ms=ft.bd,vs=-2&ft.v,Cs=-2&ft.j;if(0>vs||0>Cs||0>=ss||0>=ms||vs+ss>Te||Cs+ms>Be)return 2;Te=ss,Be=ms}if(ft.da){if(!Ve(Te,Be,ss=[ft.ib],ms=[ft.hb]))return 2;Te=ss[0],Be=ms[0]}}_t.width=Te,_t.height=Be;e:{var Rs=_t.width,en=_t.height;if(Te=_t.S,0>=Rs||0>=en||!(Te>=zb&&13>Te))Te=2;else{if(0>=_t.Rd&&_t.sd==null){vs=ms=ss=Be=0;var Mn=(Cs=Rs*dw[Te])*en;if(11>Te||(ms=(en+1)/2*(Be=(Rs+1)/2),Te==12&&(vs=(ss=Rs)*en)),(en=i(Mn+2*ms+vs))==null){Te=1;break e}_t.sd=en,11>Te?((Rs=_t.f.RGBA).eb=en,Rs.fb=0,Rs.A=Cs,Rs.size=Mn):((Rs=_t.f.kb).y=en,Rs.O=0,Rs.fa=Cs,Rs.Fd=Mn,Rs.f=en,Rs.N=0+Mn,Rs.Ab=Be,Rs.Cd=ms,Rs.ea=en,Rs.W=0+Mn+ms,Rs.Db=Be,Rs.Ed=ms,Te==12&&(Rs.F=en,Rs.J=0+Mn+2*ms),Rs.Tc=vs,Rs.lb=ss)}if(Be=1,ss=_t.S,ms=_t.width,vs=_t.height,ss>=zb&&13>ss)if(11>ss)Te=_t.f.RGBA,Be&=(Cs=Math.abs(Te.A))*(vs-1)+ms<=Te.size,Be&=Cs>=ms*dw[ss],Be&=Te.eb!=null;else{Te=_t.f.kb,Cs=(ms+1)/2,Mn=(vs+1)/2,Rs=Math.abs(Te.fa),en=Math.abs(Te.Ab);var Xn=Math.abs(Te.Db),tn=Math.abs(Te.lb),$n=tn*(vs-1)+ms;Be&=Rs*(vs-1)+ms<=Te.Fd,Be&=en*(Mn-1)+Cs<=Te.Cd,Be=(Be&=Xn*(Mn-1)+Cs<=Te.Ed)&Rs>=ms&en>=Cs&Xn>=Cs,Be&=Te.y!=null,Be&=Te.f!=null,Be&=Te.ea!=null,ss==12&&(Be&=tn>=ms,Be&=$n<=Te.Tc,Be&=Te.F!=null)}else Be=0;Te=Be?0:2}}return Te!=0||ft!=null&&ft.fd&&(Te=Ba(_t)),Te}var Cc=64,qa=[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],Lp=24,ou=32,va=8,Wg=[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(Te){return Te},I.Predictor2=function(Te,Be,ft){return Be[ft+0]},I.Predictor3=function(Te,Be,ft){return Be[ft+1]},I.Predictor4=function(Te,Be,ft){return Be[ft-1]},I.Predictor5=function(Te,Be,ft){return nt(nt(Te,Be[ft+1]),Be[ft+0])},I.Predictor6=function(Te,Be,ft){return nt(Te,Be[ft-1])},I.Predictor7=function(Te,Be,ft){return nt(Te,Be[ft+0])},I.Predictor8=function(Te,Be,ft){return nt(Be[ft-1],Be[ft+0])},I.Predictor9=function(Te,Be,ft){return nt(Be[ft+0],Be[ft+1])},I.Predictor10=function(Te,Be,ft){return nt(nt(Te,Be[ft-1]),nt(Be[ft+0],Be[ft+1]))},I.Predictor11=function(Te,Be,ft){var _t=Be[ft+0];return 0>=ct(_t>>24&255,Te>>24&255,(Be=Be[ft-1])>>24&255)+ct(_t>>16&255,Te>>16&255,Be>>16&255)+ct(_t>>8&255,Te>>8&255,Be>>8&255)+ct(255&_t,255&Te,255&Be)?_t:Te},I.Predictor12=function(Te,Be,ft){var _t=Be[ft+0];return($e((Te>>24&255)+(_t>>24&255)-((Be=Be[ft-1])>>24&255))<<24|$e((Te>>16&255)+(_t>>16&255)-(Be>>16&255))<<16|$e((Te>>8&255)+(_t>>8&255)-(Be>>8&255))<<8|$e((255&Te)+(255&_t)-(255&Be)))>>>0},I.Predictor13=function(Te,Be,ft){var _t=Be[ft-1];return(Ge((Te=nt(Te,Be[ft+0]))>>24&255,_t>>24&255)<<24|Ge(Te>>16&255,_t>>16&255)<<16|Ge(Te>>8&255,_t>>8&255)<<8|Ge(255&Te,255&_t))>>>0};var U0=I.PredictorAdd0;I.PredictorAdd1=xt,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 gg=I.PredictorAdd2;fs("ColorIndexInverseTransform","MapARGB","32b",function(Te){return Te>>8&255},function(Te){return Te}),fs("VP8LColorIndexInverseTransformAlpha","MapAlpha","8b",function(Te){return Te},function(Te){return Te>>8&255});var Ry,Ox=I.ColorIndexInverseTransform,Td=I.MapARGB,df=I.VP8LColorIndexInverseTransformAlpha,ym=I.MapAlpha,hh=I.VP8LPredictorsAdd=[];hh.length=16,(I.VP8LPredictors=[]).length=16,(I.VP8LPredictorsAdd_C=[]).length=16,(I.VP8LPredictors_C=[]).length=16;var qd,uf,E1,T1,ud,Kg,Fy,vm,zx,Rb,mh,Ac,Cl,pl,$u,$d,Yg,Oy,bm,tw,Vj,sw,Zg,ph,zy,Hj,By,nw,WN=i(511),KN=i(2041),Fb=i(225),Ob=i(767),YN=0,rw=KN,hf=Fb,_m=Ob,ur=WN,zb=0,Bb=1,M1=2,Jf=3,Fv=4,Uy=5,aw=6,P1=7,ZN=8,Gj=9,q0=10,BC=[2,3,7],To=[3,3,11],KS=[280,256,256,256,40],UC=[0,1,1,1,0],BL=[17,18,0,1,2,3,4,5,16,6,7,8,9,10,11,12,13,14,15],qC=[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],YE=[2954,2956,2958,2962,2970,2986,3018,3082,3212,3468,3980,5004],hd=8,iw=[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],$C=[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],Ub=null,UL=[[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]],$0=[0,1,4,8,5,2,3,6,9,12,13,10,7,11,14,15],Wj=[-0,1,-1,2,-2,3,4,6,-3,5,-4,-5,-6,7,-7,8,-8,-9],ow=[[[[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]]]],YS=[[[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]]],qb=[[[[255,255,255,255,255,255,255,255,255,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]]]],$b=[0,1,2,3,6,4,5,6,6,6,6,6,6,6,6,7,0],Bx=[],Zu=[],V0=[],XN=1,VC=2,yg=[],ex=[];ho("UpsampleRgbLinePair",Ea,3),ho("UpsampleBgrLinePair",gi,3),ho("UpsampleRgbaLinePair",cp,4),ho("UpsampleBgraLinePair",Su,4),ho("UpsampleArgbLinePair",Jc,4),ho("UpsampleRgba4444LinePair",_i,2),ho("UpsampleRgb565LinePair",Mi,2);var QN=I.UpsampleRgbLinePair,ZS=I.UpsampleBgrLinePair,Kj=I.UpsampleRgbaLinePair,Yj=I.UpsampleBgraLinePair,tx=I.UpsampleArgbLinePair,mf=I.UpsampleRgba4444LinePair,HC=I.UpsampleRgb565LinePair,Ov=16,Zj=1<_t.ca.S||(alert("todo:WebPInitConvertARGBToYUV"),_t.ca.f.kb.F!=null&&Hc()),_t.Pb&&0<_t.s.ua&&_t.s.vb.X==null&&!Fe(_t.s.vb,_t.s.Wa.Xa)){_t.a=1;break s}_t.xb=0}if(!Mt(_t,_t.V,_t.Ba,_t.c,_t.i,ft.o,Wt))break s;ss.Dc=_t.Ma,_t=1;break t}t(_t.a!=0),_t=0}_t=!_t}_t&&(Be=Te.a)}else Be=Te.a}else{if((Te=new So)==null){vs=1;break e}if(Te.Fa=ss.na,Te.P=ss.P,Te.qc=ss.Sa,Ro(Te,_t)){if((Be=Hr(_t.width,_t.height,vs.Oa,vs.ba))==0){if(Te.Aa=0,ft=vs.Oa,t((ss=Te)!=null),ft!=null){if(0<(Rs=0>(Rs=ft.Md)?0:100en;++en)12>(Xn=ss.pb[en]).lc&&(Xn.ia=Rs*dp[0>Xn.lc?0:Xn.lc]>>3),Mn|=Xn.ia;Mn&&(alert("todo:VP8InitRandom"),ss.ia=1)}ss.Ga=ft.Id,100ss.Ga&&(ss.Ga=0)}(function(tn,$n){if(tn==null)return 0;if($n==null)return Ra(tn,2,"NULL VP8Io parameter in VP8Decode().");if(!tn.cb&&!Ro(tn,$n))return 0;if(t(tn.cb),$n.ac==null||$n.ac($n)){$n.ob&&(tn.L=0);var nr=e2[tn.L];if(tn.L==2?(tn.yb=0,tn.zb=0):(tn.yb=$n.v-nr>>4,tn.zb=$n.j-nr>>4,0>tn.yb&&(tn.yb=0),0>tn.zb&&(tn.zb=0)),tn.Va=$n.o+15+nr>>4,tn.Hb=$n.va+15+nr>>4,tn.Hb>tn.za&&(tn.Hb=tn.za),tn.Va>tn.Ub&&(tn.Va=tn.Ub),0nr;++nr){var br;if(tn.Qa.Cb){var Vn=tn.Qa.Lb[nr];tn.Qa.Fb||(Vn+=Mr.Tb)}else Vn=Mr.Tb;for(br=0;1>=br;++br){var Vr=tn.gd[nr][br],Sa=Vn;if(Mr.Pc&&(Sa+=Mr.vd[0],br&&(Sa+=Mr.od[0])),0<(Sa=0>Sa?0:63>2:ba>>1)>9-Mr.wb&&(ba=9-Mr.wb),1>ba&&(ba=1),Vr.dd=ba,Vr.tc=2*Sa+ba,Vr.ld=40<=Sa?2:15<=Sa?1:0}else Vr.tc=0;Vr.La=br}}}nr=0}else Ra(tn,6,"Frame setup failed"),nr=tn.a;if(nr=nr==0){if(nr){tn.$c=0,0tn.Vb){if(tn.Vb=0,tn.Ec=i(Vr),tn.Fc=0,tn.Ec==null){nr=Ra(tn,1,"no memory during frame initialization.");break t}tn.Vb=Vr}Vr=tn.Ec,Sa=tn.Fc,tn.Ac=Vr,tn.Bc=Sa,Sa+=Mr,tn.Gd=l(ro,rl),tn.Hd=0,tn.rb=l(Oi+1,Rr),tn.sb=1,tn.wa=Al?l(Al,sa):null,tn.Y=0,tn.D.Nb=0,tn.D.wa=tn.wa,tn.D.Y=tn.Y,0=nr;++nr)WN[255+nr]=0>nr?-nr:nr;for(nr=-1020;1020>=nr;++nr)KN[1020+nr]=-128>nr?-128:127=nr;++nr)Fb[112+nr]=-16>nr?-16:15=nr;++nr)Ob[255+nr]=0>nr?0:255gl;++gl){var lu,ed=_u[0+gl];for(lu=0;4>lu;++lu){ed=YS[bu[Bm+lu]][ed];for(var Vd=Wj[Pe(Ao,ed[0])];0>3;for(Vd=0;256>Vd;Vd+=16)gl[Vu+Vd]=Qh}Ah=1,Ip=Bm[0]}var Ec=15&Ao.la,Eh=15&sx.la;for(Vd=0;4>Vd;++Vd){var Dp=1&Eh;for(Qh=md=0;4>Qh;++Qh)Ec=Ec>>1|(Dp=(Md=Ub(bu,Ip,Md=Dp+(1&Ec),Xu.Sc,Ah,gl,Vu))>Ah)<<7,md=md<<2|(3>=4,Eh=Eh>>1|Dp<<7,lu=(lu<<8|md)>>>0}for(Ip=Ec,Ah=Eh>>4,fh=0;4>fh;fh+=2){for(md=0,Ec=Ao.la>>4+fh,Eh=sx.la>>4+fh,Vd=0;2>Vd;++Vd){for(Dp=1&Eh,Qh=0;2>Qh;++Qh)Md=Dp+(1&Ec),Ec=Ec>>1|(Dp=0<(Md=Ub(bu,Bm[2],Md,Xu.Qc,0,gl,Vu)))<<3,md=md<<2|(3>=2,Eh=Eh>>1|Dp<<5}ed|=md<<4*fh,Ip|=Ec<<4<=Qi.zb&&Qi.M<=Qi.Va,Qi.Aa==0)t:{if(El.M=Qi.M,El.uc=Ao,Pp(Qi,El),Ll=1,El=(md=Qi.D).Nb,Ao=(ed=e2[Qi.L])*Qi.R,bu=ed/2*Qi.B,Vd=16*El*Qi.R,Qh=8*El*Qi.B,Bm=Qi.sa,_u=Qi.ta-Ao+Vd,Xu=Qi.qa,gl=Qi.ra-bu+Qh,Vu=Qi.Ha,sx=Qi.Ia-bu+Qh,Eh=(Ec=md.M)==0,lu=Ec>=Qi.Va-1,Qi.Aa==2&&Pp(Qi,md),md.uc)for(Dp=(Md=Qi).D.M,t(Md.D.uc),md=Md.yb;mdmi.o&&(Ec=mi.o),mi.F=null,mi.J=null,Qi.Fa!=null&&0>1),mi.W+=Qi.B*(ed>>1),mi.F!=null&&(mi.J+=mi.width*ed)),md>1,mi.W+=mi.v>>1,mi.F!=null&&(mi.J+=mi.v),mi.ka=md-mi.j,mi.U=mi.va-mi.v,mi.T=Ec-md,Ll=mi.put(mi))}El+1!=Qi.Ic||lu||(r(Qi.sa,Qi.ta-Ao,Bm,_u+16*Qi.R,Ao),r(Qi.qa,Qi.ra-bu,Xu,gl+8*Qi.B,bu),r(Qi.Ha,Qi.Ia-bu,Vu,sx+8*Qi.B,bu))}if(!Ll)return Ra(xc,6,"Output aborted.")}return 1}(tn,$n)),$n.bc!=null&&$n.bc($n),nr&=1}return nr?(tn.cb=0,nr):0})(Te,_t)||(Be=Te.a)}}else Be=Te.a}Be==0&&vs.Oa!=null&&vs.Oa.fd&&(Be=Ba(vs.ba))}vs=Be}ms=vs!=0?null:11>ms?Cs.f.RGBA.eb:Cs.f.kb.y}else ms=null;return ms};var dw=[3,4,3,4,4,2,2,4,4,4,2,1,1]};function d(I,D){for(var O="",V=0;V<4;V++)O+=String.fromCharCode(I[D++]);return O}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],f=[0],y=[],v=new c,g=s,b=function(I,D){var O={},V=0,G=!1,$=0,H=0;if(O.frames=[],!function(ae,le){for(var be=0;be<4;be++)if(ae[le+be]!="RIFF".charCodeAt(be))return!0;return!1}(I,D)){for(m(I,D+=4),D+=8;D>1&1}Y!="ANMF"&&(D+=ne)}return O}}(g,0);b.response=g,b.rgbaoutput=!0,b.dataurl=!1;var j=b.header?b.header:null,S=b.frames?b.frames:null;if(j){j.loop_counter=j.loop_count,p=[j.canvas_height],f=[j.canvas_width];for(var C=0;C'+n.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")+"",this.internal.__metadata__.metadataObjectNumber=this.internal.newObject(),this.internal.write("<< /Type /Metadata /Subtype /XML /Length "+s.length+" >>"),this.internal.write("stream"),this.internal.write(s),this.internal.write("endstream"),this.internal.write("endobj")}function Aqn(){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(ae){return ae=ae||{},this.isStrokeTransparent=ae.isStrokeTransparent||!1,this.strokeOpacity=ae.strokeOpacity||1,this.strokeStyle=ae.strokeStyle||"#000000",this.fillStyle=ae.fillStyle||"#000000",this.isFillTransparent=ae.isFillTransparent||!1,this.fillOpacity=ae.fillOpacity||1,this.font=ae.font||"10px sans-serif",this.textBaseline=ae.textBaseline||"alphabetic",this.textAlign=ae.textAlign||"left",this.lineWidth=ae.lineWidth||1,this.lineJoin=ae.lineJoin||"miter",this.lineCap=ae.lineCap||"butt",this.path=ae.path||[],this.transform=ae.transform!==void 0?ae.transform.clone():new c,this.globalCompositeOperation=ae.globalCompositeOperation||"normal",this.globalAlpha=ae.globalAlpha||1,this.clip_path=ae.clip_path||[],this.currentPoint=ae.currentPoint||new l,this.miterLimit=ae.miterLimit||10,this.lastPoint=ae.lastPoint||new l,this.lineDashOffset=ae.lineDashOffset||0,this.lineDash=ae.lineDash||[],this.margin=ae.margin||[0,0,0,0],this.prevPageLastElemOffset=ae.prevPageLastElemOffset||0,this.ignoreClearRect=typeof ae.ignoreClearRect!="boolean"||ae.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(ae){Object.defineProperty(this,"canvas",{get:function(){return{parentNode:!1,style:!1}}});var le=ae;Object.defineProperty(this,"pdf",{get:function(){return le}});var be=!1;Object.defineProperty(this,"pageWrapXEnabled",{get:function(){return be},set:function(Fe){be=!!Fe}});var me=!1;Object.defineProperty(this,"pageWrapYEnabled",{get:function(){return me},set:function(Fe){me=!!Fe}});var he=0;Object.defineProperty(this,"posX",{get:function(){return he},set:function(Fe){isNaN(Fe)||(he=Fe)}});var pe=0;Object.defineProperty(this,"posY",{get:function(){return pe},set:function(Fe){isNaN(Fe)||(pe=Fe)}}),Object.defineProperty(this,"margin",{get:function(){return d.margin},set:function(Fe){var Ne;typeof Fe=="number"?Ne=[Fe,Fe,Fe,Fe]:((Ne=new Array(4))[0]=Fe[0],Ne[1]=Fe.length>=2?Fe[1]:Ne[0],Ne[2]=Fe.length>=3?Fe[2]:Ne[0],Ne[3]=Fe.length>=4?Fe[3]:Ne[1]),d.margin=Ne}});var Ce=!1;Object.defineProperty(this,"autoPaging",{get:function(){return Ce},set:function(Fe){Ce=Fe}});var Ae=0;Object.defineProperty(this,"lastBreak",{get:function(){return Ae},set:function(Fe){Ae=Fe}});var Pe=[];Object.defineProperty(this,"pageBreaks",{get:function(){return Pe},set:function(Fe){Pe=Fe}}),Object.defineProperty(this,"ctx",{get:function(){return d},set:function(Fe){Fe instanceof u&&(d=Fe)}}),Object.defineProperty(this,"path",{get:function(){return d.path},set:function(Fe){d.path=Fe}});var ze=[];Object.defineProperty(this,"ctxStack",{get:function(){return ze},set:function(Fe){ze=Fe}}),Object.defineProperty(this,"fillStyle",{get:function(){return this.ctx.fillStyle},set:function(Fe){var Ne;Ne=m(Fe),this.ctx.fillStyle=Ne.style,this.ctx.isFillTransparent=Ne.a===0,this.ctx.fillOpacity=Ne.a,this.pdf.setFillColor(Ne.r,Ne.g,Ne.b,{a:Ne.a}),this.pdf.setTextColor(Ne.r,Ne.g,Ne.b,{a:Ne.a})}}),Object.defineProperty(this,"strokeStyle",{get:function(){return this.ctx.strokeStyle},set:function(Fe){var Ne=m(Fe);this.ctx.strokeStyle=Ne.style,this.ctx.isStrokeTransparent=Ne.a===0,this.ctx.strokeOpacity=Ne.a,Ne.a===0?this.pdf.setDrawColor(255,255,255):(Ne.a,this.pdf.setDrawColor(Ne.r,Ne.g,Ne.b))}}),Object.defineProperty(this,"lineCap",{get:function(){return this.ctx.lineCap},set:function(Fe){["butt","round","square"].indexOf(Fe)!==-1&&(this.ctx.lineCap=Fe,this.pdf.setLineCap(Fe))}}),Object.defineProperty(this,"lineWidth",{get:function(){return this.ctx.lineWidth},set:function(Fe){isNaN(Fe)||(this.ctx.lineWidth=Fe,this.pdf.setLineWidth(Fe))}}),Object.defineProperty(this,"lineJoin",{get:function(){return this.ctx.lineJoin},set:function(Fe){["bevel","round","miter"].indexOf(Fe)!==-1&&(this.ctx.lineJoin=Fe,this.pdf.setLineJoin(Fe))}}),Object.defineProperty(this,"miterLimit",{get:function(){return this.ctx.miterLimit},set:function(Fe){isNaN(Fe)||(this.ctx.miterLimit=Fe,this.pdf.setMiterLimit(Fe))}}),Object.defineProperty(this,"textBaseline",{get:function(){return this.ctx.textBaseline},set:function(Fe){this.ctx.textBaseline=Fe}}),Object.defineProperty(this,"textAlign",{get:function(){return this.ctx.textAlign},set:function(Fe){["right","end","center","left","start"].indexOf(Fe)!==-1&&(this.ctx.textAlign=Fe)}});var ke=null,Ze=null,Se=null;Object.defineProperty(this,"fontFaces",{get:function(){return Se},set:function(Fe){ke=null,Ze=null,Se=Fe}}),Object.defineProperty(this,"font",{get:function(){return this.ctx.font},set:function(Fe){var Ne;if(this.ctx.font=Fe,(Ne=/^\s*(?=(?:(?:[-a-z]+\s*){0,2}(italic|oblique))?)(?=(?:(?:[-a-z]+\s*){0,2}(small-caps))?)(?=(?:(?:[-a-z]+\s*){0,2}(bold(?:er)?|lighter|[1-9]00))?)(?:(?:normal|\1|\2|\3)\s*){0,3}((?:xx?-)?(?:small|large)|medium|smaller|larger|[.\d]+(?:\%|in|[cem]m|ex|p[ctx]))(?:\s*\/\s*(normal|[.\d]+(?:\%|in|[cem]m|ex|p[ctx])))?\s*([-_,\"\'\sa-z0-9]+?)\s*$/i.exec(Fe))!==null){var Ye=Ne[1];Ne[2];var Ve=Ne[3],qe=Ne[4];Ne[5];var Qe=Ne[6],Ue=/^([.\d]+)((?:%|in|[cem]m|ex|p[ctx]))$/i.exec(qe)[2];qe=Math.floor(Ue==="px"?parseFloat(qe)*this.pdf.internal.scaleFactor:Ue==="em"?parseFloat(qe)*this.pdf.getFontSize():parseFloat(qe)*this.pdf.internal.scaleFactor),this.pdf.setFontSize(qe);var Xe=function(fs){var Ft,wt,Ts=[],vt=fs.trim();if(vt==="")return Uze;if(vt in Bkt)return[Bkt[vt]];for(;vt!=="";){switch(wt=null,Ft=(vt=qkt(vt)).charAt(0)){case'"':case"'":wt=_qn(vt.substring(1),Ft);break;default:wt=wqn(vt)}if(wt===null||(Ts.push(wt[0]),(vt=qkt(wt[1]))!==""&&vt.charAt(0)!==","))return Uze;vt=vt.replace(/^,/,"")}return Ts}(Qe);if(this.fontFaces){var nt=function(fs,Ft){var wt=fs.getFontList(),Ts=JSON.stringify(wt);if(ke===null||Ze!==Ts){var vt=function($s){var As=[];return Object.keys($s).forEach(function(jn){$s[jn].forEach(function(ar){var Dn=null;switch(ar){case"bold":Dn={family:jn,weight:"bold"};break;case"italic":Dn={family:jn,style:"italic"};break;case"bolditalic":Dn={family:jn,weight:"bold",style:"italic"};break;case"":case"normal":Dn={family:jn}}Dn!==null&&(Dn.ref={name:jn,style:ar},As.push(Dn))})}),As}(wt);ke=function($s){for(var As={},jn=0;jn<$s.length;++jn){var ar=Bze($s[jn]),Dn=ar.family,Ur=ar.stretch,Vs=ar.style,hn=ar.weight;As[Dn]=As[Dn]||{},As[Dn][Ur]=As[Dn][Ur]||{},As[Dn][Ur][Vs]=As[Dn][Ur][Vs]||{},As[Dn][Ur][Vs][hn]=ar}return As}(vt.concat(Ft)),Ze=Ts}return ke}(this.pdf,this.fontFaces),$e=Xe.map(function(fs){return{family:fs,stretch:"normal",weight:Ve,style:Ye}}),Ge=function(fs,Ft,wt){for(var Ts=(wt=wt||{}).defaultFontFamily||"times",vt=Object.assign({},bqn,wt.genericFontFamilies||{}),$s=null,As=null,jn=0;jn=700||Ye==="bold")&&(ct="bold"),Ye==="italic"&&(ct+="italic"),ct.length===0&&(ct="normal");for(var xt="",qt={arial:"Helvetica",Arial:"Helvetica",verdana:"Helvetica",Verdana:"Helvetica",helvetica:"Helvetica",Helvetica:"Helvetica","sans-serif":"Helvetica",fixed:"Courier",monospace:"Courier",terminal:"Courier",cursive:"Times",fantasy:"Times",serif:"Times"},Vt=0;Vt=2*Math.PI&&(me=0,he=2*Math.PI),this.path.push({type:"arc",x:ae,y:le,radius:be,startAngle:me,endAngle:he,counterclockwise:pe})},h.prototype.arcTo=function(ae,le,be,me,he){throw new Error("arcTo not implemented.")},h.prototype.rect=function(ae,le,be,me){if(isNaN(ae)||isNaN(le)||isNaN(be)||isNaN(me))throw Sm.error("jsPDF.context2d.rect: Invalid arguments",arguments),new Error("Invalid arguments passed to jsPDF.context2d.rect");this.moveTo(ae,le),this.lineTo(ae+be,le),this.lineTo(ae+be,le+me),this.lineTo(ae,le+me),this.lineTo(ae,le),this.lineTo(ae+be,le),this.lineTo(ae,le)},h.prototype.fillRect=function(ae,le,be,me){if(isNaN(ae)||isNaN(le)||isNaN(be)||isNaN(me))throw Sm.error("jsPDF.context2d.fillRect: Invalid arguments",arguments),new Error("Invalid arguments passed to jsPDF.context2d.fillRect");if(!p.call(this)){var he={};this.lineCap!=="butt"&&(he.lineCap=this.lineCap,this.lineCap="butt"),this.lineJoin!=="miter"&&(he.lineJoin=this.lineJoin,this.lineJoin="miter"),this.beginPath(),this.rect(ae,le,be,me),this.fill(),he.hasOwnProperty("lineCap")&&(this.lineCap=he.lineCap),he.hasOwnProperty("lineJoin")&&(this.lineJoin=he.lineJoin)}},h.prototype.strokeRect=function(ae,le,be,me){if(isNaN(ae)||isNaN(le)||isNaN(be)||isNaN(me))throw Sm.error("jsPDF.context2d.strokeRect: Invalid arguments",arguments),new Error("Invalid arguments passed to jsPDF.context2d.strokeRect");f.call(this)||(this.beginPath(),this.rect(ae,le,be,me),this.stroke())},h.prototype.clearRect=function(ae,le,be,me){if(isNaN(ae)||isNaN(le)||isNaN(be)||isNaN(me))throw Sm.error("jsPDF.context2d.clearRect: Invalid arguments",arguments),new Error("Invalid arguments passed to jsPDF.context2d.clearRect");this.ignoreClearRect||(this.fillStyle="#ffffff",this.fillRect(ae,le,be,me))},h.prototype.save=function(ae){ae=typeof ae!="boolean"||ae;for(var le=this.pdf.internal.getCurrentPageInfo().pageNumber,be=0;be0||this.margin[1]>0||this.margin[2]>0||this.margin[3]>0};h.prototype.drawImage=function(ae,le,be,me,he,pe,Ce,Ae,Pe){var ze=this.pdf.getImageProperties(ae),ke=1,Ze=1,Se=1,Fe=1;me!==void 0&&Ae!==void 0&&(Se=Ae/me,Fe=Pe/he,ke=ze.width/me*Ae/me,Ze=ze.height/he*Pe/he),pe===void 0&&(pe=le,Ce=be,le=0,be=0),me!==void 0&&Ae===void 0&&(Ae=me,Pe=he),me===void 0&&Ae===void 0&&(Ae=ze.width,Pe=ze.height);var Ne=this.ctx.transform.decompose(),Ye=ne(Ne.rotate.shx),Ve=new c,qe=(Ve=(Ve=(Ve=Ve.multiply(Ne.translate)).multiply(Ne.skew)).multiply(Ne.scale)).applyToRectangle(new o(pe-le*Se,Ce-be*Fe,me*ke,he*Ze));if(this.autoPaging){for(var Qe,Ue=v.call(this,qe),Xe=[],nt=0;nt$e||ctqe||Ue0)){for(;Pe>=0;Pe--)if(he[Pe-1].close!==!0&&he[Pe-1].begin!==!0){he[Pe-1].deltas.push(be),he[Pe-1].abs.push(Ae);break}}break;case"bct":be=[Ae.x1-pe[Ce-1].x,Ae.y1-pe[Ce-1].y,Ae.x2-pe[Ce-1].x,Ae.y2-pe[Ce-1].y,Ae.x-pe[Ce-1].x,Ae.y-pe[Ce-1].y],he[he.length-1].deltas.push(be);break;case"qct":var ze=pe[Ce-1].x+2/3*(Ae.x1-pe[Ce-1].x),ke=pe[Ce-1].y+2/3*(Ae.y1-pe[Ce-1].y),Ze=Ae.x+2/3*(Ae.x1-Ae.x),Se=Ae.y+2/3*(Ae.y1-Ae.y),Fe=Ae.x,Ne=Ae.y;be=[ze-pe[Ce-1].x,ke-pe[Ce-1].y,Ze-pe[Ce-1].x,Se-pe[Ce-1].y,Fe-pe[Ce-1].x,Ne-pe[Ce-1].y],he[he.length-1].deltas.push(be);break;case"arc":he.push({deltas:[],abs:[],arc:!0}),Array.isArray(he[he.length-1].abs)&&he[he.length-1].abs.push(Ae)}}me=le?null:ae==="stroke"?"stroke":"fill";for(var Ye=!1,Ve=0;Ve=.01&&(me=this.pdf.internal.getFontSize(),this.pdf.setFontSize(me*ae.scale),he=this.lineWidth,this.lineWidth=he*ae.scale);var Xt=this.autoPaging!=="text";if(Xt||Vt.y+Vt.h<=nt){if(Xt||Vt.y>=Ue&&Vt.x<=Ge){var fs=Xt?ae.text:this.pdf.splitTextToSize(ae.text,ae.maxWidth||Ge-Vt.x)[0],Ft=b([JSON.parse(JSON.stringify(Ze))],this.posX+this.margin[3],-xt+Ue+this.ctx.prevPageLastElemOffset)[0],wt=Xt&&(Qe>Ve||Qe=.01&&(this.pdf.setFontSize(me),this.lineWidth=he)}}else ae.scale>=.01&&(me=this.pdf.internal.getFontSize(),this.pdf.setFontSize(me*ae.scale),he=this.lineWidth,this.lineWidth=he*ae.scale),this.pdf.text(ae.text,Pe.x+this.posX,Pe.y+this.posY,{angle:ae.angle,align:le,renderingMode:ae.renderingMode,maxWidth:ae.maxWidth}),ae.scale>=.01&&(this.pdf.setFontSize(me),this.lineWidth=he)},G=function(ae,le,be,me){be=be||0,me=me||0,this.pdf.internal.out(n(ae+be)+" "+r(le+me)+" l")},$=function(ae,le,be){return this.pdf.lines(ae,le,be,null,null)},H=function(ae,le,be,me,he,pe,Ce,Ae){this.pdf.internal.out([t(a(be+ae)),t(i(me+le)),t(a(he+ae)),t(i(pe+le)),t(a(Ce+ae)),t(i(Ae+le)),"c"].join(" "))},Y=function(ae,le,be,me){for(var he=2*Math.PI,pe=Math.PI/2;le>be;)le-=he;var Ce=Math.abs(be-le);Ce1e-5;){var ke=ze+Pe*Math.min(Ce,pe);Ae.push(Z.call(this,ae,ze,ke)),Ce-=Math.abs(ke-ze),ze=ke}return Ae},Z=function(ae,le,be){var me=(be-le)/2,he=ae*Math.cos(me),pe=ae*Math.sin(me),Ce=he,Ae=-pe,Pe=Ce*Ce+Ae*Ae,ze=Pe+Ce*he+Ae*pe,ke=4/3*(Math.sqrt(2*Pe*ze)-ze)/(Ce*pe-Ae*he),Ze=Ce-ke*Ae,Se=Ae+ke*Ce,Fe=Ze,Ne=-Se,Ye=me+le,Ve=Math.cos(Ye),qe=Math.sin(Ye);return{x1:ae*Math.cos(le),y1:ae*Math.sin(le),x2:Ze*Ve-Se*qe,y2:Ze*qe+Se*Ve,x3:Fe*Ve-Ne*qe,y3:Fe*qe+Ne*Ve,x4:ae*Math.cos(be),y4:ae*Math.sin(be)}},ne=function(ae){return 180*ae/Math.PI},ce=function(ae,le,be,me,he,pe){var Ce=ae+.5*(be-ae),Ae=le+.5*(me-le),Pe=he+.5*(be-he),ze=pe+.5*(me-pe),ke=Math.min(ae,he,Ce,Pe),Ze=Math.max(ae,he,Ce,Pe),Se=Math.min(le,pe,Ae,ze),Fe=Math.max(le,pe,Ae,ze);return new o(ke,Se,Ze-ke,Fe-Se)},ie=function(ae,le,be,me,he,pe,Ce,Ae){var Pe,ze,ke,Ze,Se,Fe,Ne,Ye,Ve,qe,Qe,Ue,Xe,nt,$e=be-ae,Ge=me-le,ct=he-be,xt=pe-me,qt=Ce-he,Vt=Ae-pe;for(ze=0;ze<41;ze++)Ve=(Ne=(ke=ae+(Pe=ze/40)*$e)+Pe*((Se=be+Pe*ct)-ke))+Pe*(Se+Pe*(he+Pe*qt-Se)-Ne),qe=(Ye=(Ze=le+Pe*Ge)+Pe*((Fe=me+Pe*xt)-Ze))+Pe*(Fe+Pe*(pe+Pe*Vt-Fe)-Ye),ze==0?(Qe=Ve,Ue=qe,Xe=Ve,nt=qe):(Qe=Math.min(Qe,Ve),Ue=Math.min(Ue,qe),Xe=Math.max(Xe,Ve),nt=Math.max(nt,qe));return new o(Math.round(Qe),Math.round(Ue),Math.round(Xe-Qe),Math.round(nt-Ue))},te=function(){if(this.prevLineDash||this.ctx.lineDash.length||this.ctx.lineDashOffset){var ae,le,be=(ae=this.ctx.lineDash,le=this.ctx.lineDashOffset,JSON.stringify({lineDash:ae,lineDashOffset:le}));this.prevLineDash!==be&&(this.pdf.setLineDash(this.ctx.lineDash,this.ctx.lineDashOffset),this.prevLineDash=be)}}})(Mo.API),function(s){var t=function(l){var o,c,d,u,h,m,p,f,y,v;for(c=[],d=0,u=(l+=o="\0\0\0\0".slice(l.length%4||4)).length;u>d;d+=4)(h=(l.charCodeAt(d)<<24)+(l.charCodeAt(d+1)<<16)+(l.charCodeAt(d+2)<<8)+l.charCodeAt(d+3))!==0?(m=(h=((h=((h=((h=(h-(v=h%85))/85)-(y=h%85))/85)-(f=h%85))/85)-(p=h%85))/85)%85,c.push(m+33,p+33,f+33,y+33,v+33)):c.push(122);return function(g,b){for(var j=b;j>0;j--)g.pop()}(c,o.length),String.fromCharCode.apply(String,c)+"~>"},n=function(l){var o,c,d,u,h,m=String,p="length",f=255,y="charCodeAt",v="slice",g="replace";for(l[v](-2),l=l[v](0,-2)[g](/\s/g,"")[g]("z","!!!!!"),d=[],u=0,h=(l+=o="uuuuu"[v](l[p]%5||5))[p];h>u;u+=5)c=52200625*(l[y](u)-33)+614125*(l[y](u+1)-33)+7225*(l[y](u+2)-33)+85*(l[y](u+3)-33)+(l[y](u+4)-33),d.push(f&c>>24,f&c>>16,f&c>>8,f&c);return function(b,j){for(var S=j;S>0;S--)b.pop()}(d,o[p]),m.fromCharCode.apply(m,d)},r=function(l){return l.split("").map(function(o){return("0"+o.charCodeAt().toString(16)).slice(-2)}).join("")+">"},a=function(l){var o=new RegExp(/^([0-9A-Fa-f]{2})+$/);if((l=l.replace(/\s/g,"")).indexOf(">")!==-1&&(l=l.substr(0,l.indexOf(">"))),l.length%2&&(l+="0"),o.test(l)===!1)return"";for(var c="",d=0;dimport("./html2canvas.esm-CBrSDip1.js"),[])).catch(function(o){return Promise.reject(new Error("Could not load html2canvas: "+o))}).then(function(o){return o.default?o.default:o})}function n(){return(ic.DOMPurify?Promise.resolve(ic.DOMPurify):za(()=>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=Uh(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;py&&(f=v,v=y,y=f);else{if(o!=="l"&&o!=="landscape")throw"Invalid orientation: "+o;o="l",y>v&&(f=v,v=y,y=f)}return{width:v,height:y,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(Bze):null;var d=new l(c);return c.worker?d:d.from(o).doCallback()}}(Mo.API),Mo.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){$=!0,Y=void 0;var he=I*D;Z=new Uint8Array(he);for(var pe=new DataView(O.buffer),Ce=0;Ce536870912)throw new Error("Image dimensions exceed 512MB, which is too large.");this.data=new Uint8Array(t);try{this[s]()}catch(n){Sm.log("bit decode error:"+n)}},yk.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)}},yk.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)}},yk.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}},yk.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}},yk.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},Hkt=function(s,t,n){n||(n={});var r,a,i,l,o,c,d,u=[],h=[u],m=n.textIndent||0,p=0,f=0,y=s.split(" "),v=lde.apply(this,[" ",n])[0];if(c=n.lineIndent===-1?y[0].length+2:n.lineIndent||0){var g=Array(c).join(" "),b=[];y.map(function(S){(S=S.split(/\s*\n/)).length>1?b=b.concat(S.map(function(C,E){return(E&&C.length?` `:"")+C})):b.push(S[0])}),y=b,c=$kt.apply(this,[g,n])}for(i=0,l=y.length;it||j){if(f>t){for(o=Vkt.apply(this,[r,a,t-(m+p),t]),u.push(o.shift()),u=[o.pop()];o.length;)h.push([o.shift()]);f=a.slice(r.length-(u[0]?u[0].length:0)).reduce(function(S,C){return S+C},0)}else u=[r];h.push(u),m=f+c,p=v}else u.push(r),m+=p+f,p=v}return d=c?function(S,C){return(C?g:"")+S.join(" ")}:function(S){return S.join(" ")},h.map(d)},HB.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-Hl9pYy9t.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)})},Mo.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},Mo.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",Aqn),this.internal.events.subscribe("postPutResources",Cqn)),this},function(s){var t=s.API,n=t.pdfEscape16=function(i,l){for(var o,c=l.metadata.Unicode.widths,d=["","0","00","000","0000"],u=[""],h=0,m=i.length;h> def /CMapName /Adobe-Identity-UCS def /CMapType 2 def 1 begincodespacerange <0000> endcodespacerange`,c=[],h=0,m=(o=Object.keys(i).sort(function(p,f){return p-f})).length;h=100&&(u+=` `+c.length+` beginbfchar `+c.join(` `)+` endbfchar`,c=[]),i[l]!==void 0&&i[l]!==null&&typeof i[l].toString=="function"&&(d=("0000"+i[l].toString(16)).slice(-4),l=("0000"+(+l).toString(16)).slice(-4),c.push("<"+l+"><"+d+">"));return c.length&&(u+=` `+c.length+` beginbfchar `+c.join(` `)+` endbfchar `),u+`endcmap CMapName currentdict /CMap defineresource pop end end`};t.events.push(["putFont",function(i){(function(l){var o=l.font,c=l.out,d=l.newObject,u=l.putStream;if(o.metadata instanceof s.API.TTFFont&&o.encoding==="Identity-H"){for(var h=o.metadata.Unicode.widths,m=o.metadata.subset.encode(o.metadata.glyIdsUsed,1),p="",f=0;f>"),c("endobj");var b=d();c("<<"),c("/Type /Font"),c("/BaseFont /"+NU(o.fontName)),c("/FontDescriptor "+g+" 0 R"),c("/W "+s.API.PDFObject.convert(h)),c("/CIDToGIDMap /Identity"),c("/DW 1000"),c("/Subtype /CIDFontType2"),c("/CIDSystemInfo"),c("<<"),c("/Supplement 0"),c("/Registry (Adobe)"),c("/Ordering ("+o.encoding+")"),c(">>"),c(">>"),c("endobj"),o.objectNumber=d(),c("<<"),c("/Type /Font"),c("/Subtype /Type0"),c("/ToUnicode "+v+" 0 R"),c("/BaseFont /"+NU(o.fontName)),c("/Encoding /"+o.encoding),c("/DescendantFonts ["+b+" 0 R]"),c(">>"),c("endobj"),o.isAlreadyPutted=!0}})(i)}]),t.events.push(["putFont",function(i){(function(l){var o=l.font,c=l.out,d=l.newObject,u=l.putStream;if(o.metadata instanceof s.API.TTFFont&&o.encoding==="WinAnsiEncoding"){for(var h=o.metadata.rawData,m="",p=0;p>"),c("endobj"),o.objectNumber=d();for(var g=0;g>"),c("endobj"),o.isAlreadyPutted=!0}})(i)}]);var a=function(i){var l,o=i.text||"",c=i.x,d=i.y,u=i.options||{},h=i.mutex||{},m=h.pdfEscape,p=h.activeFontKey,f=h.fonts,y=p,v="",g=0,b="",j=f[y].encoding;if(f[y].encoding!=="Identity-H")return{text:o,x:c,y:d,options:u,mutex:h};for(b=o,y=p,Array.isArray(o)&&(b=o[0]),g=0;g","<","[","]","[","{","}","{","«","»","«","‹","›","‹","⁅","⁆","⁅","⁽","⁾","⁽","₍","₎","₍","≤","≥","≤","〈","〉","〈","﹙","﹚","﹙","﹛","﹜","﹛","﹝","﹞","﹝","﹤","﹥","﹤"],g=new RegExp(/^([1-4|9]|1[0-9]|2[0-9]|3[0168]|4[04589]|5[012]|7[78]|159|16[0-9]|17[0-2]|21[569]|22[03489]|250)$/),b=!1,j=0;this.__bidiEngine__={};var S=function(O){var V=O.charCodeAt(),G=V>>8,$=y[G];return $!==void 0?h[256*$+(255&V)]:G===252||G===253?"AL":g.test(G)?"L":G===8?"R":"N"},C=function(O){for(var V,G=0;G=V.length||(H=G[$-1])!=="EN"&&H!=="AN"||(Y=V[$+1])!=="EN"&&Y!=="AN"?ce="N":b&&(Y="AN"),ce=Y===H?Y:"N";break;case"ES":ce=(H=$>0?G[$-1]:"B")==="EN"&&$+10&&G[$-1]==="EN"){ce="EN";break}if(b){ce="N";break}for(Z=$+1,ne=V.length;Z=1425&&ie<=2303||ie===64286;if(H=V[Z],te&&(H==="R"||H==="AL")){ce="R";break}}}ce=$<1||(H=V[$-1])==="B"?"N":G[$-1];break;case"B":b=!1,a=!0,ce=j;break;case"S":i=!0,ce="N"}return ce},P=function(O,V,G){var $=O.split("");return G&&M($,G,{hiLevel:j}),$.reverse(),V&&V.reverse(),$.join("")},M=function(O,V,G){var $,H,Y,Z,ne,ce=-1,ie=O.length,te=0,ae=[],le=j?p:m,be=[];for(b=!1,a=!1,i=!1,H=0;H0)if($===16){for(H=ce;H-1){for(H=ce;H=0&&me[Ae]==="WS";Ae--)he[Ae]=j}}(be,V,ie)},I=function(O,V,G,$,H){if(!(H.hiLevel=O){for(ne=te+1;ne=O;)ne++;for(ce=te,Z=ne-1;ce=0&&(Y[ie]=v[ce+1])}($,G,H),I(2,$,V,G,H),I(1,$,V,G,H),$.join("")};return this.__bidiEngine__.doBidiReorder=function(O,V,G){if(function(H,Y){if(Y)for(var Z=0;Z>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 HS,VP=function(){function s(t){this.data=t??[],this.pos=0,this.length=this.data.length}return s.prototype.readByte=function(){return this.data[this.pos++]},s.prototype.writeByte=function(t){return this.data[this.pos++]=t},s.prototype.readUInt32=function(){return 16777216*this.readByte()+(this.readByte()<<16)+(this.readByte()<<8)+this.readByte()},s.prototype.writeUInt32=function(t){return this.writeByte(t>>>24&255),this.writeByte(t>>16&255),this.writeByte(t>>8&255),this.writeByte(255&t)},s.prototype.readInt32=function(){var t;return(t=this.readUInt32())>=2147483648?t-4294967296:t},s.prototype.writeInt32=function(t){return t<0&&(t+=4294967296),this.writeUInt32(t)},s.prototype.readUInt16=function(){return this.readByte()<<8|this.readByte()},s.prototype.writeUInt16=function(t){return this.writeByte(t>>8&255),this.writeByte(255&t)},s.prototype.readInt16=function(){var t;return(t=this.readUInt16())>=32768?t-65536:t},s.prototype.writeInt16=function(t){return t<0&&(t+=65536),this.writeUInt16(t)},s.prototype.readString=function(t){var n,r;for(r=[],n=0;0<=t?nt;n=0<=t?++n:--n)r[n]=String.fromCharCode(this.readByte());return r.join("")},s.prototype.writeString=function(t){var n,r,a;for(a=[],n=0,r=t.length;0<=r?nr;n=0<=r?++n:--n)a.push(this.writeByte(t.charCodeAt(n)));return a},s.prototype.readShort=function(){return this.readInt16()},s.prototype.writeShort=function(t){return this.writeInt16(t)},s.prototype.readLongLong=function(){var t,n,r,a,i,l,o,c;return t=this.readByte(),n=this.readByte(),r=this.readByte(),a=this.readByte(),i=this.readByte(),l=this.readByte(),o=this.readByte(),c=this.readByte(),128&t?-1*(72057594037927940*(255^t)+281474976710656*(255^n)+1099511627776*(255^r)+4294967296*(255^a)+16777216*(255^i)+65536*(255^l)+256*(255^o)+(255^c)+1):72057594037927940*t+281474976710656*n+1099511627776*r+4294967296*a+16777216*i+65536*l+256*o+c},s.prototype.writeLongLong=function(t){var n,r;return n=Math.floor(t/4294967296),r=4294967295&t,this.writeByte(n>>24&255),this.writeByte(n>>16&255),this.writeByte(n>>8&255),this.writeByte(255&n),this.writeByte(r>>24&255),this.writeByte(r>>16&255),this.writeByte(r>>8&255),this.writeByte(255&r)},s.prototype.readInt=function(){return this.readInt32()},s.prototype.writeInt=function(t){return this.writeInt32(t)},s.prototype.read=function(t){var n,r;for(n=[],r=0;0<=t?rt;r=0<=t?++r:--r)n.push(this.readByte());return n},s.prototype.write=function(t){var n,r,a,i;for(i=[],r=0,a=t.length;ri;a=0<=i?++a:--a)r={tag:n.readString(4),checksum:n.readInt(),offset:n.readInt(),length:n.readInt()},this.tables[r.tag]=r}return t.prototype.encode=function(n){var r,a,i,l,o,c,d,u,h,m,p,f,y;for(y 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 VP).writeInt(this.scalarType),a.writeShort(p),a.writeShort(h),a.writeShort(l),a.writeShort(u),i=16*p,d=a.pos+i,o=null,f=[],n)for(m=n[y],a.writeString(y),a.writeInt(s(m)),a.writeInt(d),a.writeInt(m.length),f=f.concat(m),y==="head"&&(o=d),d+=m.length;d%4;)f.push(0),d++;return a.write(f),r=2981146554-s(a.data),a.pos=o+8,a.writeUInt32(r),a.data},s=function(n){var r,a,i,l;for(n=yJt.call(n);n.length%4;)n.push(0);for(i=new VP(n),a=0,r=0,l=n.length;rm;c=0<=m?++S:--S)C.push(t.readUInt16());return C}(),t.pos+=2,y=function(){var S,C;for(C=[],c=S=0;0<=m?Sm;c=0<=m?++S:--S)C.push(t.readUInt16());return C}(),d=function(){var S,C;for(C=[],c=S=0;0<=m?Sm;c=0<=m?++S:--S)C.push(t.readUInt16());return C}(),u=function(){var S,C;for(C=[],c=S=0;0<=m?Sm;c=0<=m?++S:--S)C.push(t.readUInt16());return C}(),a=(this.length-t.pos+this.offset)/2,o=function(){var S,C;for(C=[],c=S=0;0<=a?Sa;c=0<=a?++S:--S)C.push(t.readUInt16());return C}(),c=g=0,j=i.length;g=v;r=f<=v?++b:--b)u[c]===0?l=r+d[c]:(l=o[u[c]/2+(r-f)-(m-c)]||0)!==0&&(l+=d[c]),this.codeMap[r]=65535&l}t.pos=h}return s.encode=function(t,n){var r,a,i,l,o,c,d,u,h,m,p,f,y,v,g,b,j,S,C,E,P,M,I,D,O,V,G,$,H,Y,Z,ne,ce,ie,te,ae,le,be,me,he,pe,Ce,Ae,Pe,ze,ke;switch($=new VP,l=Object.keys(t).sort(function(Ze,Se){return Ze-Se}),n){case"macroman":for(y=0,v=function(){var Ze=[];for(f=0;f<256;++f)Ze.push(0);return Ze}(),b={0:0},i={},H=0,ce=l.length;H=32768)for(c.push(0),E.push(2*(p.length+I-f)),a=ne=O;O<=u?ne<=u:ne>=u;a=O<=u?++ne:--ne)p.push(r[a].new);else c.push(G-O),E.push(0)}for($.writeUInt16(3),$.writeUInt16(1),$.writeUInt32(12),$.writeUInt16(4),$.writeUInt16(16+8*I+2*p.length),$.writeUInt16(0),$.writeUInt16(D),$.writeUInt16(M),$.writeUInt16(m),$.writeUInt16(P),pe=0,ae=h.length;pea;r=0<=a?++r:--r)n=new eSt(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=eSt.encode(t,n),(a=new VP).writeUInt16(0),a.writeUInt16(1),r.table=a.data.concat(r.subtable),r},s}(),Pqn=function(){function s(){return s.__super__.constructor.apply(this,arguments)}return RC(s,HS),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}(),Lqn=function(){function s(){return s.__super__.constructor.apply(this,arguments)}return RC(s,HS),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}(),Iqn=function(){function s(){return s.__super__.constructor.apply(this,arguments)}return RC(s,HS),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}(),Dqn=function(s,t){this.raw=s,this.length=s.length,this.platformID=t.platformID,this.encodingID=t.encodingID,this.languageID=t.languageID},Rqn=function(){function s(){return s.__super__.constructor.apply(this,arguments)}return RC(s,HS),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}(),yJt=[].slice,zqn=function(){function s(){return s.__super__.constructor.apply(this,arguments)}return RC(s,HS),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 VP(n.read(a))).readShort(),d=o.readShort(),h=o.readShort(),c=o.readShort(),u=o.readShort(),this.cache[t]=l===-1?new Uqn(o,d,h,c,u):new Bqn(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}(),$qn=function(){function s(t){this.font=t,this.subset={},this.unicodes={},this.next=33}return s.prototype.generateCmap=function(){var t,n,r,a,i;for(n in a=this.font.cmap.tables[0].codeMap,t={},i=this.subset)r=i[n],t[n]=a[r];return t},s.prototype.glyphsFor=function(t){var n,r,a,i,l,o,c;for(a={},l=0,o=t.length;l0)for(i in c=this.glyphsFor(n))r=c[i],a[i]=r;return a},s.prototype.encode=function(t,n){var r,a,i,l,o,c,d,u,h,m,p,f,y,v,g;for(a in r=gJt.encode(this.generateCmap(),"unicode"),l=this.glyphsFor(t),p={0:0},g=r.charMap)p[(c=g[a]).old]=c.new;for(f in m=r.maxGlyphID,l)f in p||(p[f]=m++);return u=function(b){var j,S;for(j in S={},b)S[b[j]]=j;return S}(p),h=Object.keys(u).sort(function(b,j){return b-j}),y=function(){var b,j,S;for(S=[],b=0,j=h.length;b>"),i.join(` `)}return""+n},t}();const nKe=[{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}],Vqn="signature";function Hqn(s){return nKe.find(t=>t.id===s)||nKe[0]}const Ic=792,Zm=612,oa=52;function GB(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 Ff(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 FC=[22,24,28],Nb=[124,128,136],Io=[255,255,255];function Gqn(s){return s==null||!Number.isFinite(Number(s))?null:new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(Number(s))}const Vze="https://relzejiswnotikjgvjhz.supabase.co";function Wqn(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(Vze).origin?s:`${Vze}/functions/v1/image-proxy?url=${encodeURIComponent(t.toString())}`}catch{return s}}async function vZ(s,t=2e3){if(!s)return null;try{const n=await fetch(Wqn(s),{mode:"cors"});if(!n.ok)return null;const r=await n.blob(),a=URL.createObjectURL(r),i=await new Promise((y,v)=>{const g=new Image;g.crossOrigin="anonymous",g.onload=()=>y(g),g.onerror=v,g.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(y=>{const v=new Image;v.onload=()=>y(v),v.onerror=()=>y(v),v.src=p}),dataUrl:p,w:o,h:c,format:m}}catch{return null}}let vJt={x:.5,y:.5};function Kqn(s){vJt={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 Kae(s,t,n,r,a,i,l={}){const o=l.dpi??2,c=Math.max(1,Math.round(a*o)),d=Math.max(1,Math.round(i*o)),u=document.createElement("canvas");u.width=c,u.height=d;const h=u.getContext("2d"),m=t.w/t.h,p=a/i;let f=0,y=0,v=t.w,g=t.h;const b=l.focal??vJt;if(m>p?(v=t.h*p,f=Math.min(Math.max(0,t.w*b.x-v/2),t.w-v)):(g=t.w/p,y=Math.min(Math.max(0,t.h*b.y-g/2),t.h-g)),l.radius&&l.radius>0){const C=Math.min(l.radius*o,c/2,d/2);h.beginPath(),h.moveTo(C,0),h.arcTo(c,0,c,d,C),h.arcTo(c,d,0,d,C),h.arcTo(0,d,0,0,C),h.arcTo(0,0,c,0,C),h.closePath(),h.clip()}const j=[];l.grayscale&&j.push("grayscale(1)"),l.blur&&j.push(`blur(${l.blur*o}px)`),j.length&&(h.filter=j.join(" "));try{h.drawImage(t.el,f,y,v,g,0,0,c,d)}catch{h.fillStyle="#e9e6e0",h.fillRect(0,0,c,d)}if(h.filter="none",l.tint&&l.tint.amount>0){const[C,E,P]=l.tint.color;h.globalCompositeOperation="multiply",h.fillStyle=`rgba(${C},${E},${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 C=h.createLinearGradient(0,0,0,d);C.addColorStop(0,"rgba(0,0,0,0)"),C.addColorStop(.45,"rgba(0,0,0,0.05)"),C.addColorStop(1,"rgba(0,0,0,0.8)"),h.fillStyle=C,h.fillRect(0,0,c,d)}else if(l.gradient==="full"){const C=h.createLinearGradient(0,0,0,d);C.addColorStop(0,"rgba(0,0,0,0.4)"),C.addColorStop(.5,"rgba(0,0,0,0.18)"),C.addColorStop(1,"rgba(0,0,0,0.85)"),h.fillStyle=C,h.fillRect(0,0,c,d)}else if(l.gradient==="left"){const C=h.createLinearGradient(0,0,c,0);C.addColorStop(0,"rgba(0,0,0,0.75)"),C.addColorStop(.6,"rgba(0,0,0,0.15)"),C.addColorStop(1,"rgba(0,0,0,0)"),h.fillStyle=C,h.fillRect(0,0,c,d)}const S=u.toDataURL("image/jpeg",.92);s.addImage(S,"JPEG",n,r,a,i,void 0,"FAST")}function D7(s,t,n,r,a,i=3){const l=a*2,o=Math.max(1,Math.round(l*i)),c=document.createElement("canvas");c.width=o,c.height=o;const d=c.getContext("2d");d.fillStyle="#ffffff",d.fillRect(0,0,o,o),d.save(),d.beginPath(),d.arc(o/2,o/2,o/2,0,Math.PI*2),d.closePath(),d.clip();const u=t.w/t.h;let h=0,m=0,p=t.w,f=t.h;u>1?(p=t.h,h=(t.w-p)/2):(f=t.w,m=(t.h-f)/2);try{d.drawImage(t.el,h,m,p,f,0,0,o,o)}catch{}d.restore(),s.addImage(c.toDataURL("image/jpeg",.92),"JPEG",n-a,r-a,l,l,void 0,"FAST")}function Rrt(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 g_(s,t){const n=s.GState;n&&s.setGState(new n({opacity:t}))}function Yqn(s,t,n,r,a,i={font:"helvetica",size:10,color:FC}){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 iK(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=Yqn(s,c,n+13,l,a-13,{font:i.font,size:i.size,color:i.color,leading:o})+(i.gap??7)}),l}function w1(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 hz='',mz='',Zqn={title:"Facebook",slug:"facebook",get svg(){return hz+"Facebook"+mz+this.path+pz},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"},Xqn={title:"Instagram",slug:"instagram",get svg(){return hz+"Instagram"+mz+this.path+pz},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"},Qqn={title:"Pinterest",slug:"pinterest",get svg(){return hz+"Pinterest"+mz+this.path+pz},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"},Jqn={title:"TikTok",slug:"tiktok",get svg(){return hz+"TikTok"+mz+this.path+pz},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"},e$n={title:"trulia",slug:"trulia",get svg(){return hz+"trulia"+mz+this.path+pz},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"},t$n={title:"YouTube",slug:"youtube",get svg(){return hz+"YouTube"+mz+this.path+pz},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"},s$n={title:"Zillow",slug:"zillow",get svg(){return hz+"Zillow"+mz+this.path+pz},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"},n$n={facebook:Zqn,instagram:Xqn,youtube:t$n,tiktok:Jqn,pinterest:Qqn,zillow:s$n,trulia:e$n},tSt=new Map;function r$n(s,t,n){return`${s}|${t}|${n}`}function a$n(s,t,n=128){const r=s.toLowerCase().replace(/[^a-z]/g,""),a=n$n[r];if(!a)return null;const i=r$n(r,t,n),l=tSt.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 tSt.set(i,d),d}catch{return null}}const eu="helvetica";let MG="helvetica";function bJt(s,t,n,r,a,i){const l=`#${n.map(d=>Math.round(d).toString(16).padStart(2,"0")).join("")}`,o=a$n(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(eu,"bold"),s.setFontSize(c*1.15),s.setTextColor(...Io),s.text(t.charAt(0).toUpperCase(),r,a+c*.42,{align:"center"})}let Yae=[252,251,248],w9=[244,247,250],$_=[223,228,234],Lv=[72,78,88];function Zae(s,t){return aQt(s.data.pages,t)}function Frt(s){var n;const t=s.coAgent;return t!=null&&t.enabled&&((n=t.name)!=null&&n.trim())?t:null}function _Jt(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 i$n(s){return[s.agent.brokerageName,s.agent.phone,s.agent.email].filter(Boolean).join(" | ")}function sg(s,t,n,r,a,i,l){const o=l.font||eu,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 dh(s,t,n,r,a,i){s.setFont(eu,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 oK(s,t,n,r,a,i){const{doc:l}=s;l.setFont(eu,"bold"),l.setFontSize(7.5),l.setTextColor(...a||s.accent),l.text(t.toUpperCase(),n,r,{charSpace:1.8,align:i})}function Ly(s,t=Yae){s.doc.addPage("letter","landscape"),s.pageNo+=1,s.doc.setFillColor(...t),s.doc.rect(0,0,Ic,Zm,"F")}function Iv(s,t,n,r,a={}){const{doc:i}=s,l=!!a.dark,o=a.width??Ic-oa*2-60;oK(s,t,oa,62,s.accent),i.setFont(MG,"bold"),i.setFontSize(MG==="times"?25:23);const c=i.splitTextToSize(n,o).slice(0,3);i.setTextColor(...l?Io:s.brand),c.forEach((u,h)=>i.text(u,oa,96+h*29));let d=96+(c.length-1)*29;return r&&(d=dh(i,r,oa,d+26,Math.min(o+40,Ic-oa*2),{size:10,color:l?Ff(Io,s.deep,.28):Nb,leading:15,maxLines:2})),d+34}function Iy(s,t=!1){const{doc:n,data:r}=s,a=t?Ff(Io,s.deep,.7):$_;n.setDrawColor(...a),n.setLineWidth(.6),n.line(oa,Zm-46,Ic-oa,Zm-46);const i=Zm-30;n.setFont(eu,"bold"),n.setFontSize(7),n.setTextColor(...t?Io:s.brand),t&&g_(n,.9),n.text((r.agent.name||"").toUpperCase(),oa,i,{charSpace:1.4});const l=i$n(r);l&&(n.setFont(eu,"normal"),n.setFontSize(7),n.setTextColor(...t?Io:Nb),sg(n,l,Ic/2,i,Ic/2-oa-40,7,{color:t?Io:Nb,align:"center"})),n.setFont(eu,"normal"),n.setFontSize(7),n.setTextColor(...t?Io:Nb),n.text(String(s.pageNo).padStart(2,"0"),Ic-oa,i,{align:"right"}),t&&g_(n,1)}function wJt(s,t,n,r,a){const{doc:i}=s;i.setFont(eu,"bold"),i.setFontSize(8);const l=i.splitTextToSize(t,a-28),o=16+l.length*12;return w1(i,n,r,a,o,6,Ff(s.accent,Io,.86)),i.setTextColor(...Ff(s.brand,FC,.2)),l.forEach((c,d)=>i.text(c,n+14,r+20+d*12)),r+o}function Ort(s,t,n,r,a,i={}){const{doc:l}=s;s.hero?Kae(l,s.hero,t,n,r,a,{radius:10,dpi:s.dpi,tint:i.tint?{color:s.deep,amount:i.tint}:void 0}):w1(l,t,n,r,a,10,Ff(s.deep,Io,.12))}function o$n(s){const{doc:t,data:n}=s,{line1:r,line2:a}=_Jt(n),i=336;s.hero?Kae(t,s.hero,0,0,Ic,Zm,{dpi:s.dpi,darken:.12}):(t.setFillColor(...s.deep),t.rect(0,0,Ic,Zm,"F")),t.setFillColor(...s.deep),t.rect(0,0,i,Zm,"F"),t.setFillColor(...s.accent),t.rect(i-3,0,3,Zm,"F");const l=Zae(s,"cover");oK(s,l.kicker,oa,66),t.setFont(MG,"bold"),t.setFontSize(MG==="times"?29:26),t.setTextColor(...Io);const o=t.splitTextToSize(r,i-oa*2).slice(0,3);o.forEach((v,g)=>t.text(v,oa,102+g*30));let c=102+(o.length-1)*30;a&&(t.setFont(eu,"normal"),t.setFontSize(9),g_(t,.9),sg(t,a.toUpperCase(),oa,c+22,i-oa*2,9,{color:Io,charSpace:1.4}),g_(t,1),c+=22),c=dh(t,l.body,oa,c+34,i-oa*2,{size:10,color:Ff(Io,s.deep,.22),leading:16});const d=[Gqn(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(oa,c+30,oa+40,c+30),sg(t,d.join(" · "),oa,c+54,i-oa*2,10,{style:"bold",color:Io,charSpace:1}));const u=Frt(n),h=Zm-(u?152:128);let m=oa;s.headshot&&(D7(t,s.headshot,oa+22,h+18,22),u&&s.coHeadshot?(D7(t,s.coHeadshot,oa+56,h+18,22),m=oa+90):m=oa+56),sg(t,u?`${n.agent.name} + ${u.name}`:n.agent.name,m,h+12,i-m-24,14,{style:"bold",color:Io}),t.setFont(eu,"normal"),t.setFontSize(8),g_(t,.85);const p=[n.agent.brokerageName].filter(Boolean).join("");p&&sg(t,p,m,h+26,i-m-24,8,{color:Io});const f=[n.agent.phone,n.agent.email].filter(Boolean).join(" · ");if(f&&sg(t,f,m,h+38,i-m-24,8,{color:Io}),u){const v=[u.title||"Co-listing agent",u.phone].filter(Boolean).join(" · ");v&&sg(t,v,oa,h+56,i-oa-24,8,{color:Io})}g_(t,1),s.logo&&(g_(t,.95),Rrt(t,s.logo,oa,Zm-74,132,30,"left"),g_(t,1));const y=n.sellerName?`PREPARED FOR ${n.sellerName.toUpperCase()}`:"PREPARED FOR YOUR HOME";t.setFont(eu,"bold"),t.setFontSize(7.5),t.setTextColor(...Io),g_(t,.9),t.text(y,Ic-oa,Zm-34,{align:"right",charSpace:1.6}),g_(t,1)}function l$n(s){Ly(s);const{doc:t}=s,n=Zae(s,"welcome"),r=Iv(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(...Ff(s.accent,Io,.85)),t.circle(oa+13,i-3,13,"F"),t.setFont(eu,"bold"),t.setFontSize(9),t.setTextColor(...s.brand),t.text(String(c+1).padStart(2,"0"),oa+13,i,{align:"center"});const d=oa+44,u=Ic-d-oa-40;t.setFont(eu,"bold"),t.setFontSize(11.5),t.setTextColor(...FC),t.text(l,d,i),dh(t,o,d,i+18,u,{size:9.5,color:Lv,leading:14,maxLines:2}),i+=88}),Iy(s)}function c$n(s){Ly(s,Io);const{doc:t,data:n}=s,r=Zae(s,"agent"),a=Iv(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=Frt(n),l=Ic-oa-260,o=a-6,c=262;if(i){const f=(y,v,g,b)=>{w1(t,l,y,260,124,10,w9,"FD",$_),t.setFillColor(...s.accent),t.rect(l,y,260,3,"F");let j=l+18;g&&(D7(t,g,l+48,y+62+2,30),j=l+90);const S=260-(j-l)-18;sg(t,v,j,y+40,S,13,{style:"bold",color:s.brand});let C=y+56;b.filter(Boolean).slice(0,4).forEach(E=>{sg(t,String(E),j,C,S,8,{color:Nb}),C+=13})};f(o,n.agent.name,s.headshot,[n.agent.brokerageName,n.agent.phone,n.agent.email]),f(o+124+14,i.name,s.coHeadshot,[i.title||"Co-listing agent",i.brokerageName||n.agent.brokerageName,i.phone,i.email])}else{w1(t,l,o,260,c,10,w9,"FD",$_),t.setFillColor(...s.accent),t.rect(l,o,260,3,"F"),s.headshot&&D7(t,s.headshot,l+130,o+72,42),sg(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=>{sg(t,String(p),l+130,m,220,8.5,{color:Nb,align:"center"}),m+=14}),s.logo&&Rrt(t,s.logo,l+80,o+c-44,100,28,"left")}const d=l-oa-44;let u=dh(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.",oa,a+4,d,{size:10,color:Lv,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(eu,"bold"),t.setFontSize(7),t.setTextColor(...Nb),t.text(m.toUpperCase(),oa,u,{charSpace:1.4}),sg(t,p,oa+86,u,d-86,10.5,{color:FC}),t.setDrawColor(...$_),t.setLineWidth(.5),t.line(oa,u+11,oa+d,u+11),u+=36}),Iy(s)}function d$n(s,t){Ly(s);const{doc:n}=s,r=Zae(s,"overview"),a=Iv(s,r.kicker,r.headline,r.subhead||null),i=4,l=14,o=(Ic-oa*2-l*(i-1))/i,c=96;t.slice(0,8).forEach((d,u)=>{const h=oa+u%i*(o+l),m=a+Math.floor(u/i)*(c+l);w1(n,h,m,o,c,8,Io,"FD",$_),n.setFillColor(...s.accent),n.rect(h,m,3,c,"F"),n.setFont(eu,"bold"),n.setFontSize(15),n.setTextColor(...Ff(s.brand,Io,.55)),n.text(String(u+1).padStart(2,"0"),h+16,m+30),dh(n,d.title,h+16,m+52,o-30,{size:9.5,style:"bold",color:FC,leading:13,maxLines:3})}),Iy(s)}function DL(s,t=5){var n;return(((n=s.options)==null?void 0:n.filter(r=>r.enabled).map(r=>r.label))??z9n[s.key]??[]).slice(0,t)}function sSt(s,t,n){Ly(s,n.dark?s.deep:Yae);const{doc:r}=s,a=Iv(s,n.kicker,n.headline,n.sub,{dark:n.dark}),i=404,l=272,o=!!n.flip,c=o?Ic-oa-i:oa,d=o?oa:oa+i+40,u=Ic-oa*2-i-40;Ort(s,c,a,i,l,{tint:n.dark?.1:0}),oK(s,t.title,d,a+12);let h=dh(r,t.body,d,a+32,u,{size:9.5,color:n.dark?Ff(Io,s.deep,.2):Lv,leading:15,maxLines:4});const m=DL(t,5);if(m.length&&(h=iK(r,m,d,h+28,u,{font:eu,size:9.5,color:n.dark?Io:FC,accent:s.accent,gap:7})),n.note&&!n.dark){const p=Math.min(h+14,Zm-120);wJt(s,n.note,d,p,u)}else n.note&&(r.setFont(eu,"bold"),r.setFontSize(9.5),r.setTextColor(...Io),g_(r,.9),dh(r,n.note,oa,Zm-78,Ic-oa*2,{size:9.5,style:"bold",color:Io,leading:13,maxLines:1}),g_(r,1));Iy(s,n.dark)}function u$n(s,t){Ly(s);const{doc:n}=s,r=Iv(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=DL(t,4),i=["Price + position","MLS story","Media ready","Go live"],l=Math.max(1,a.length||4),o=16,c=(Ic-oa*2-o*(l-1))/l,d=176;(a.length?a:i).forEach((u,h)=>{const m=oa+h*(c+o);w1(n,m,r,c,d,8,Io,"FD",$_),n.setFont(eu,"bold"),n.setFontSize(16),n.setTextColor(...s.accent),n.text(String(h+1),m+16,r+34),n.setFont(eu,"bold"),n.setFontSize(7.5),n.setTextColor(...Nb),n.text((i[h]||`STEP ${h+1}`).toUpperCase(),m+16,r+56,{charSpace:1.2}),dh(n,u,m+16,r+76,c-32,{size:9,color:Lv,leading:13,maxLines:5})}),dh(n,t.body,oa,r+d+34,Ic-oa*2-120,{size:10,style:"bold",color:s.brand,leading:15,maxLines:2}),Iy(s)}function h$n(s,t){Ly(s);const{doc:n}=s,r=Iv(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=(Ic-oa*2-l*(i-1))/i,c=68;a.forEach(([u,h],m)=>{const p=oa+m%i*(o+l),f=r+Math.floor(m/i)*(c+l);w1(n,p,f,o,c,8,Io,"FD",$_),bJt(n,u,h,p+28,f+c/2,20),sg(n,u,p+48,f+c/2+4,o-64,13,{style:"bold",color:h})});const d=r+2*(c+l)+22;dh(n,t.body,oa,d,Ic-oa*2-140,{size:9.5,color:Lv,leading:14,maxLines:3}),n.setFont(eu,"normal"),n.setFontSize(7.5),n.setTextColor(...Nb),n.text("Distribution varies by MLS, market, and portal policies.",oa,Zm-62),Iy(s)}function m$n(s,t){Ly(s,w9);const{doc:n,data:r}=s,{line1:a}=_Jt(r),i=Iv(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;w1(n,oa,i,l,o,10,Io,"FD",$_),w1(n,oa,i,l,22,10,s.deep),n.setFillColor(...s.deep),n.rect(oa,i+12,l,10,"F"),n.setFont(eu,"bold"),n.setFontSize(7),n.setTextColor(...Io);const c=(r.agent.website||`${a}`).replace(/^https?:\/\//,"").toUpperCase();sg(n,c,oa+14,i+15,l-28,7,{style:"bold",color:Io,charSpace:1}),Ort(s,oa+14,i+36,186,142);const d=oa+214,u=l-228;sg(n,a,d,i+54,u,12,{style:"bold",color:s.brand}),dh(n,"Welcome home.",d,i+72,u,{size:9,color:s.accent,leading:12,maxLines:1}),dh(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:Lv,leading:12,maxLines:5}),wJt(s,"Shareable. Trackable. Memorable.",oa+14,i+o-46,l-28);const h=oa+l+40,m=Ic-h-oa;oK(s,t.title,h,i+12);let p=dh(n,t.body,h,i+32,m,{size:9.5,color:Lv,leading:15,maxLines:5});const f=DL(t,5);f.length&&iK(n,f,h,p+26,m,{font:eu,size:9,color:FC,accent:s.accent,gap:7}),Iy(s)}function p$n(s,t){Ly(s,s.deep);const{doc:n}=s,r=Iv(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=oa+h*(i+l);w1(n,m,r,i,i,12,Io),bJt(n,d,u,m+i/2,r+i/2-4,30),n.setFont(eu,"bold"),n.setFontSize(6.5),n.setTextColor(...Nb),n.text(d.toUpperCase(),m+i/2,r+i-8,{align:"center",charSpace:.6})});const o=oa+5*(i+l)+14,c=Ic-o-oa;oK(s,"The campaign can include",o,r+12),iK(n,DL(t,5),o,r+32,c,{font:eu,size:9,color:Io,accent:s.accent,gap:7}),dh(n,t.body,oa,r+i+44,420,{size:9.5,color:Ff(Io,s.deep,.2),leading:15,maxLines:4}),dh(n,"Every post sends attention back to the property.",oa,Zm-84,460,{size:11,style:"bold",color:Io,leading:14,maxLines:1}),Iy(s,!0)}function f$n(s,t){Ly(s);const{doc:n}=s,r=Iv(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=DL(t,4),i=["Email announcement","Agent-to-agent outreach","Database follow-up","Local community visibility"];let l=r+6;a.forEach((o,c)=>{w1(n,oa,l-14,34,34,8,Ff(s.accent,Io,.85)),n.setFont(eu,"bold"),n.setFontSize(11),n.setTextColor(...s.brand),n.text(String(c+1),oa+17,l+7,{align:"center"});const d=oa+52,u=Ic-d-oa-20;n.setFont(eu,"bold"),n.setFontSize(8),n.setTextColor(...s.brand),n.text((i[c]||t.title).toUpperCase(),d,l-2,{charSpace:1.2}),dh(n,o,d,l+14,u,{size:9.5,color:Lv,leading:14,maxLines:2}),l+=76}),dh(n,t.body,oa,Math.min(l+8,Zm-92),Ic-oa*2-120,{size:9.5,color:Nb,leading:14,maxLines:2}),Iy(s)}function x$n(s,t){Ly(s);const{doc:n}=s,r=Iv(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=DL(t,4),i=["Open house","Signage","Neighborhood","Follow-up"],l=2,o=20,c=(Ic-oa*2-o)/l,d=112;a.forEach((u,h)=>{const m=oa+h%l*(c+o),p=r+Math.floor(h/l)*(d+o);w1(n,m,p,c,d,8,w9,"FD",$_),n.setFont(eu,"bold"),n.setFontSize(7.5),n.setTextColor(...s.brand),n.text((i[h]||t.title).toUpperCase(),m+16,p+24,{charSpace:1.2}),dh(n,u,m+16,p+46,c-32,{size:9.5,color:Lv,leading:14,maxLines:3})}),Iy(s)}function g$n(s,t){Ly(s,w9);const{doc:n}=s,r=Iv(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=DL(t,4),i=["Weekly update","Market check","Smart adjustments","Direct access"];let l=r+10;a.forEach((o,c)=>{n.setFont(eu,"bold"),n.setFontSize(11),n.setTextColor(...s.accent),n.text(String(c+1).padStart(2,"0"),oa,l),n.setFont(eu,"bold"),n.setFontSize(9),n.setTextColor(...s.brand),n.text((i[c]||"").toUpperCase(),oa+48,l,{charSpace:1.2}),dh(n,o,oa+250,l-1,Ic-oa-250-oa,{size:9.5,color:Lv,leading:13,maxLines:2}),n.setDrawColor(...$_),n.setLineWidth(.5),n.line(oa,l+22,Ic-oa,l+22),l+=62}),dh(n,"Marketing creates opportunity. Communication helps us act on it.",oa,Math.min(l+18,Zm-84),520,{size:11,style:"bold",color:s.brand,leading:14,maxLines:1}),Iy(s)}function y$n(s){Ly(s,s.deep);const{doc:t,data:n}=s;s.hero&&Kae(t,s.hero,0,0,Ic,Zm,{tint:{color:s.deep,amount:.92},darken:.25,dpi:s.dpi});const r=Zae(s,"closing"),a=Iv(s,r.kicker,r.headline,r.subhead||null,{dark:!0,width:520}),i=420;let l=dh(t,r.body,oa,a,i,{size:10.5,color:Ff(Io,s.deep,.18),leading:17});l+=30,iK(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"],oa,l,i,{font:eu,size:9.5,color:Io,accent:s.accent,gap:8});const o=Frt(n),c=250,d=Ic-oa-c,u=a-20,h=o?300:258;w1(t,d,u,c,h,10,Io),t.setFillColor(...s.accent),t.rect(d,u,c,3,"F"),s.headshot&&(o&&s.coHeadshot?(D7(t,s.headshot,d+c/2-34,u+70,32),D7(t,s.coHeadshot,d+c/2+34,u+70,32)):D7(t,s.headshot,d+c/2,u+70,38)),sg(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=>{sg(t,String(p),d+c/2,m,c-30,8.5,{color:Nb,align:"center"}),m+=14}),o?(m+=6,t.setDrawColor(...$_),t.setLineWidth(.5),t.line(d+24,m-8,d+c-24,m-8),sg(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=>{sg(t,String(p),d+c/2,m,c-30,8.5,{color:Nb,align:"center"}),m+=13})):s.logo&&Rrt(t,s.logo,d+c/2-50,u+h-44,100,28,"left"),t.setFont(eu,"bold"),t.setFontSize(9),t.setTextColor(...Io),g_(t,.9),t.text("LET'S MAKE YOUR HOME THE ONE BUYERS REMEMBER.",oa,Zm-72,{charSpace:1.4}),g_(t,1),Iy(s,!0)}function zrt(s,t){return s.customImages[t.id]||null}function jJt(s,t,n,r,a,i){const l=zrt(s,t);l?Kae(s.doc,l,n,r,a,i,{radius:10,dpi:s.dpi}):Ort(s,n,r,a,i)}function v$n(s,t){Ly(s,t.dark?s.deep:Yae);const{doc:n}=s,r=Iv(s,t.kicker||"About",t.headline,t.subhead||null,{dark:t.dark}),a=300,i=t.imageSide!=="left",l=i?Ic-oa-a:oa,o=i?oa:oa+a+40,c=Ic-oa*2-a-40;jJt(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=dh(n,h,o,u,c,{size:10,color:t.dark?Ff(Io,s.deep,.2):Lv,leading:16,maxLines:7}),u+=26}),t.bullets.length&&iK(n,t.bullets.slice(0,5),o,Math.min(u,Zm-150),c,{font:eu,size:9.5,color:t.dark?Io:FC,accent:s.accent,gap:7}),Iy(s,t.dark)}function b$n(s,t){Ly(s,t.dark?s.deep:w9);const{doc:n}=s,r=Iv(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=(Ic-oa*2-l*(i-1))/i,c=Math.ceil(a.length/i)||1,d=Zm-72-r,u=c>1?Math.min(150,(d-l*(c-1))/c):Math.min(200,d),h=c>1?i===3?4:3:7;a.forEach((m,p)=>{const f=oa+p%i*(o+l),y=r+Math.floor(p/i)*(u+l);w1(n,f,y,o,u,10,t.dark?Ff(s.deep,Io,.08):Io,"FD",$_),n.setFillColor(...s.accent),n.rect(f,y,3,u,"F"),n.setFont(MG,"bold"),n.setFontSize(30),n.setTextColor(...Ff(s.accent,t.dark?s.deep:Io,.4)),n.text("“",f+18,y+40),dh(n,m.quote,f+18,y+56,o-40,{size:9.5,color:t.dark?Ff(Io,s.deep,.2):Lv,leading:14,maxLines:h}),n.setDrawColor(...s.accent),n.setLineWidth(1.2),n.line(f+18,y+u-32,f+42,y+u-32),n.setFont(eu,"bold"),n.setFontSize(8),n.setTextColor(...s.brand);const v=[m.name,m.detail].filter(Boolean).join(" · ");v&&sg(n,v.toUpperCase(),f+18,y+u-16,o-36,8,{style:"bold",color:t.dark?Io:s.brand,charSpace:1.1})}),t.body&&dh(n,t.body,oa,Math.min(r+c*(u+l)+14,Zm-88),Ic-oa*2-120,{size:9.5,color:t.dark?Ff(Io,s.deep,.2):Nb,leading:14,maxLines:2}),Iy(s,t.dark)}function _$n(s,t){Ly(s,t.dark?s.deep:Yae);const{doc:n}=s,r=Iv(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=(Ic-oa*2-18*(a.length-1))/a.length,o=150;a.forEach((c,d)=>{const u=oa+d*(l+18);w1(n,u,r,l,o,10,t.dark?Ff(s.deep,Io,.1):Io,"FD",$_),n.setFillColor(...s.accent),n.rect(u,r,l,3,"F"),sg(n,c.value||"—",u+l/2,r+76,l-28,34,{style:"bold",color:t.dark?Io:s.brand,align:"center"}),dh(n,c.label||"",u+20,r+100,l-40,{size:9,color:t.dark?Ff(Io,s.deep,.3):Nb,leading:12,maxLines:2,align:"center"})}),t.body&&dh(n,t.body,oa,r+o+40,Ic-oa*2-140,{size:10,color:t.dark?Ff(Io,s.deep,.2):Lv,leading:15,maxLines:3})}else t.body&&dh(n,t.body,oa,r,Ic-oa*2-140,{size:10.5,color:t.dark?Io:Lv,leading:16});Iy(s,t.dark)}function w$n(s,t){Ly(s,t.dark?s.deep:Io);const{doc:n}=s,r=Iv(s,t.kicker||"Our promise",t.headline,t.subhead||null,{dark:t.dark}),i=!!zrt(s,t)||!!s.hero,l=i?Ic-oa*2-280:Ic-oa*2-140;let o=r;t.body&&(o=dh(n,t.body,oa,o,l,{size:10,color:t.dark?Ff(Io,s.deep,.2):Lv,leading:15,maxLines:3})+28),t.bullets.filter(d=>d==null?void 0:d.trim()).slice(0,7).forEach(d=>{w1(n,oa,o-9,14,14,4,s.accent),n.setFont(eu,"bold"),n.setFontSize(8),n.setTextColor(...Io),n.text("✓",oa+7,o+1,{align:"center"}),o=dh(n,d,oa+26,o,l-26,{size:10,color:t.dark?Io:FC,leading:14,maxLines:2})+22}),i&&jJt(s,t,Ic-oa-240,r,240,250),Iy(s,t.dark)}function j$n(s,t){Ly(s,s.deep);const{doc:n}=s,r=zrt(s,t)||s.hero;r&&Kae(n,r,0,0,Ic,Zm,{tint:{color:s.deep,amount:.82},darken:.28,dpi:s.dpi}),oK(s,t.kicker||"Our approach",oa,Zm/2-84),n.setFont(eu,"bold"),n.setFontSize(30),n.setTextColor(...Io);const a=n.splitTextToSize(t.headline||"",Ic-oa*2-140).slice(0,4);a.forEach((i,l)=>n.text(i,oa,Zm/2-44+l*38)),t.body&&dh(n,t.body,oa,Zm/2+a.length*38-24,480,{size:10.5,color:Ff(Io,s.deep,.2),leading:16,maxLines:4}),Iy(s,!0)}function nSt(s,t){switch(t.layout){case"testimonials":return b$n(s,t);case"stats":return _$n(s,t);case"checklist":return w$n(s,t);case"statement":return j$n(s,t);case"story":default:return v$n(s,t)}}async function N$n(s,t,n){var P,M,I,D;const r=n==="print"?4:2,a=n==="print"?2600:1600,i=Hqn((P=t.pages)==null?void 0:P.theme);Yae=GB(i.paper),w9=GB(i.paperCool),$_=GB(i.softLine),Lv=GB(i.bodyInk),MG=i.headFont;const l=GB((i.useAgentColors?t.agent.brandColor:i.brand)||i.brand||"#0E1B2C"),o=GB((i.useAgentColors?t.agent.accentColor:i.accent)||i.accent||"#B8965A"),c=Ff(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(O=>O.enabled).sort((O,V)=>O.order-V.order),[h,m,p,f,...y]=await Promise.all([vZ(t.property.photoUrl,a),vZ(t.agent.headshotUrl,700),vZ(t.agent.brokerageLogoUrl,800),vZ((d==null?void 0:d.headshotUrl)||null,700),...u.map(O=>vZ(O.imageUrl||null,a))]),v={};u.forEach((O,V)=>{v[O.id]=y[V]??null}),Kqn(t.focal);const g={doc:s,data:t,brand:l,accent:o,deep:c,hero:h,headshot:m,coHeadshot:f,logo:p,customImages:v,dpi:r,pageNo:1},b=new Set(((D=t.pages)==null?void 0:D.hidden)||[]),j=[...t.services].filter(O=>O.enabled).sort((O,V)=>O.order-V.order),S=O=>j.find(V=>V.key===O);o$n(g),b.has("welcome")||l$n(g),b.has("agent")||c$n(g),u.filter(O=>O.placement!=="end").forEach(O=>nSt(g,O)),b.has("overview")||d$n(g,j);const C=new Set,E=(O,V)=>{const G=S(O);G&&(C.add(O),V(G))};E("photography",O=>sSt(g,O,{kicker:"First impressions",headline:"Buyers will see your home at its absolute best.",sub:"Strong presentation earns the click before a showing is ever scheduled.",note:"Every image has one job: earn the next click."})),E("video",O=>sSt(g,O,{kicker:"More ways to experience it",headline:"Photos introduce the home. Video helps buyers feel it.",sub:"A cinematic walk-through gives the listing movement, emotion, and shareability.",note:"The right format for every screen.",dark:!0,flip:!0})),E("mls",O=>u$n(g,O)),E("syndication",O=>h$n(g,O)),E("website",O=>m$n(g,O)),E("social",O=>p$n(g,O)),E("email",O=>f$n(g,O)),E("openhouse",O=>x$n(g,O)),E("communication",O=>g$n(g,O)),j.filter(O=>!C.has(O.key)).forEach(O=>{Ly(g);const V=Iv(g,"Marketing",O.title,null),G=DL(O,6),$=dh(s,O.body,oa,V,Ic-oa*2-160,{size:10.5,color:Lv,leading:16});G.length&&iK(s,G,oa,$+30,Ic-oa*2-160,{font:eu,size:9.5,color:FC,accent:g.accent,gap:8}),Iy(g)}),u.filter(O=>O.placement==="end").forEach(O=>nSt(g,O)),b.has("closing")||y$n(g)}const rSt=[{id:"signature",name:"Signature",description:"Editorial full-bleed cover with a brand-tinted photo motif throughout.",render:N$n}];function k$n(s){return rSt.find(t=>t.id===s)||rSt[0]}async function NJt(s,t,n="screen"){const r=new Mo({unit:"pt",format:"letter",orientation:"landscape",compress:!0});return await k$n(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 S$n(s){return`${(s.property.addressLine1||s.title||"listing-presentation").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||"listing-presentation"}-presentation.pdf`}const C$n={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 QTe(s){if(!s)return null;const{data:t}=await q.storage.from($P).createSignedUrl(s,3600);return(t==null?void 0:t.signedUrl)??null}function JTe(s,t,n){const r=s.agent_snapshot||{},a={...C$n,...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:oQt(s.co_agent),customPages:cQt(s.custom_pages),services:zWe(s.services),pages:s.page_settings&&Object.keys(s.page_settings).length?s.page_settings:FWe,focal:s.photo_focal||OWe}}async function kJt(s,t){if(s.property.photoUrl||!t)return s;const n=await QTe(t);return{...s,property:{...s.property,photoUrl:n}}}async function SJt(s,t,n){const r=await kJt(s,n);return(await NJt(r,t,"screen")).output("blob")}async function CJt(s,t,n="print",r){const a=await kJt(s,r),l=(await NJt(a,t,n)).output("blob"),o=URL.createObjectURL(l),c=document.createElement("a");return c.href=o,c.download=S$n(a),document.body.appendChild(c),c.click(),c.remove(),setTimeout(()=>URL.revokeObjectURL(o),4e3),l}async function AJt(s,t,n){const r=`${s}/${t}/presentation.pdf`,{error:a}=await q.storage.from($P).upload(r,n,{upsert:!0,contentType:"application/pdf"});return a?null:(await q.from("listing_presentations").update({pdf_path:r,last_generated_at:new Date().toISOString(),status:"final"}).eq("id",t),r)}async function EJt(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 A$n(s,t,n){const r=await EJt(n),a=`${s}/${t}/photo.jpg`,{error:i}=await q.storage.from($P).upload(a,r,{upsert:!0,contentType:"image/jpeg"});if(i)throw i;return a}async function E$n(s,t,n="presentation",r=1800){const a=await EJt(t,r),i=`${s}/${n}-${Date.now()}.jpg`,{error:l}=await q.storage.from("avatars").upload(i,a,{upsert:!0,contentType:"image/jpeg"});if(l)throw l;const{data:o}=q.storage.from("avatars").getPublicUrl(i);return o.publicUrl}function T$n({path:s,alt:t}){const[n,r]=_.useState(null),[a,i]=_.useState(!1);return _.useEffect(()=>{let l=!0;if(r(null),i(!1),!!s)return D9n(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(Jr,{className:"h-8 w-8 text-primary/50"})})}const aSt=60*60*24*30;function TJt({open:s,onOpenChange:t,row:n,brand:r,photoUrl:a}){const{user:i}=hs(),[l,o]=_.useState([]),[c,d]=_.useState(""),[u,h]=_.useState([]),[m,p]=_.useState(!1),[f,y]=_.useState(""),[v,g]=_.useState(""),[b,j]=_.useState(!1),S=_.useRef(null),C=(n==null?void 0:n.property_address_line1)||(n==null?void 0:n.title)||"your home";_.useEffect(()=>{!s||!n||(o([]),d(""),h([]),y(`Your listing presentation for ${C}`),g(`Hi {{first_name}}, Thank you for the opportunity to talk about selling ${C}. I put together a presentation that walks through my pricing strategy, marketing plan, and what to expect at every step. Take a look and let me know what questions come up — I'm happy to walk through it together.`))},[s,n==null?void 0:n.id]),_.useEffect(()=>{S.current&&clearTimeout(S.current);const D=c.trim();if(!i||D.length<2||/\S+@\S+\.\S+/.test(D)){h([]);return}return S.current=setTimeout(async()=>{p(!0);const O=`%${D}%`,V=q,{data:G}=await V.from("innercircle_contacts").select("id, first_name, last_name, email").eq("owner_user_id",i.id).not("email","is",null).or(`first_name.ilike.${O},last_name.ilike.${O},email.ilike.${O}`).order("first_name",{ascending:!0}).limit(6);p(!1),h(G||[])},200),()=>{S.current&&clearTimeout(S.current)}},[c,i==null?void 0:i.id]);const E=D=>{D.email&&(o(O=>O.some(V=>V.email.toLowerCase()===D.email.toLowerCase())?O:[...O,D]),d(""),h([]))},P=()=>{const D=c.trim();if(!/\S+@\S+\.\S+/.test(D)){se.error("Enter a valid email address");return}E({email:D})},M=_.useMemo(()=>!!n&&l.length>0&&f.trim().length>0&&!b,[n,l,f,b]),I=async()=>{if(!(!n||!i)){if(!n.property_photo_path){se.error("Add the primary exterior photo before emailing the presentation");return}j(!0);try{const D=await SJt(JTe(n,r,a??null),n.template_id,n.property_photo_path),O=await AJt(i.id,n.id,D)||n.pdf_path;if(!O)throw new Error("Could not save the presentation PDF");const{data:V,error:G}=await q.storage.from($P).createSignedUrl(O,aSt);if(G||!(V!=null&&V.signedUrl))throw new Error("Could not create a share link");const $=await QTe(n.property_photo_path).then(ne=>ne).catch(()=>null),{data:H}=await q.storage.from($P).createSignedUrl(n.property_photo_path,aSt),{data:Y,error:Z}=await q.functions.invoke("listing-presentation-email",{body:{presentation_id:n.id,subject:f,message:v,pdf_url:V.signedUrl,photo_url:(H==null?void 0:H.signedUrl)||$,recipients:l}});if(Z)throw Z;if(!(Y!=null&&Y.success))throw new Error((Y==null?void 0:Y.error)||"Could not send the email");se.success(Y.failed?`Sent to ${Y.sent} · ${Y.failed} failed`:`Presentation emailed to ${Y.sent} ${Y.sent===1?"contact":"contacts"}`),t(!1)}catch(D){se.error((D==null?void 0:D.message)||"Could not send the presentation")}finally{j(!1)}}};return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"max-w-lg",children:[e.jsxs(Os,{children:[e.jsxs(Ds,{className:"flex items-center gap-2",children:[e.jsx(ln,{className:"h-4 w-4"})," Email this presentation"]}),e.jsxs(_r,{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(J,{children:"To"}),l.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:l.map(D=>e.jsxs(Oe,{variant:"secondary",className:"gap-1 py-1",children:[[D.first_name,D.last_name].filter(Boolean).join(" ")||D.email,e.jsx("button",{type:"button",onClick:()=>o(O=>O.filter(V=>V.email!==D.email)),"aria-label":`Remove ${D.email}`,children:e.jsx(Qn,{className:"h-3 w-3"})})]},D.email))}),e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{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(B,{type:"button",variant:"outline",size:"icon",onClick:P,children:e.jsx(rn,{className:"h-4 w-4"})})]}),(u.length>0||m)&&e.jsxs("div",{className:"absolute z-50 mt-1 w-full overflow-hidden rounded-md border bg-popover shadow-lg",children:[m&&e.jsxs("div",{className:"flex items-center gap-2 p-3 text-sm text-muted-foreground",children:[e.jsx(Ct,{className:"h-3 w-3 animate-spin"})," Searching…"]}),u.map(D=>e.jsxs("button",{type:"button",className:"flex w-full items-center gap-2 px-3 py-2 text-left text-sm hover:bg-accent",onClick:()=>E({email:D.email,first_name:D.first_name,last_name:D.last_name,contact_id:D.id}),children:[e.jsx(Fo,{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(J,{htmlFor:"pres-subject",children:"Subject"}),e.jsx(xe,{id:"pres-subject",value:f,onChange:D=>y(D.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"pres-message",children:"Message"}),e.jsx(Ms,{id:"pres-message",rows:7,value:v,onChange:D=>g(D.target.value)})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),disabled:b,children:"Cancel"}),e.jsxs(B,{onClick:I,disabled:!M,className:"gap-2",children:[b?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Or,{className:"h-4 w-4"}),b?"Sending…":`Send${l.length?` (${l.length})`:""}`]})]})]})})}const M$n=()=>{const s=Fn(),{presentations:t,isLoading:n,create:r,duplicate:a,remove:i,update:l}=nQt(),{data:o}=L9n(),{data:c}=rQt(),{savedTemplates:d,remove:u}=sQt(),[h,m]=_.useState(null),[p,f]=_.useState(""),[y,v]=_.useState(null),[g,b]=_.useState(null),[j,S]=_.useState(null),C=_.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:HTe},[o]),E=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:C});s(`/apps/listing-presentation-studio/${I.id}`)},P=async I=>{var O;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:(O=I.services)!=null&&O.length?I.services:C,page_settings:I.page_settings});s(`/apps/listing-presentation-studio/${D.id}`)},M=async I=>{try{b(I.id),await CJt(JTe(I,c),I.template_id,"print",I.property_photo_path)}catch(D){se.error((D==null?void 0:D.message)||"Could not build the PDF")}finally{b(null)}};return e.jsxs(zs,{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(Oe,{variant:"secondary",className:"gap-1",children:[e.jsx(un,{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(B,{size:"lg",onClick:E,disabled:r.isPending||!c,className:"gap-2",children:[r.isPending?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(rn,{className:"h-4 w-4"}),"New presentation"]}),d.length>0&&e.jsxs(tu,{children:[e.jsx(su,{asChild:!0,children:e.jsxs(B,{size:"lg",variant:"outline",className:"gap-2",children:[e.jsx(C0,{className:"h-4 w-4"})," From template",e.jsx(tl,{className:"h-4 w-4"})]})}),e.jsx(Od,{align:"end",className:"w-64",children:d.map(I=>e.jsxs(ca,{onClick:()=>P(I),children:[e.jsx(C0,{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(ve,{className:"transition-shadow hover:shadow-md",children:e.jsxs(Me,{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(C0,{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(B,{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(Sn,{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(cn,{className:"h-56 rounded-xl"},I))}):t.length===0?e.jsx(ve,{className:"border-dashed",children:e.jsxs(Me,{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(Fr,{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(B,{onClick:E,disabled:r.isPending||!c,className:"gap-2",children:[e.jsx(rn,{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",O=[I.city,I.state].filter(Boolean).join(", ");return e.jsxs(ve,{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(T$n,{path:I.property_photo_path,alt:`${D} property photo`})}),e.jsxs(Me,{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,O?` · ${O}`:""]})]}),e.jsxs(tu,{children:[e.jsx(su,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0",children:e.jsx(Xx,{className:"h-4 w-4"})})}),e.jsxs(Od,{align:"end",children:[e.jsxs(ca,{onClick:()=>s(`/apps/listing-presentation-studio/${I.id}`),children:[e.jsx(Ya,{className:"mr-2 h-4 w-4"})," Open"]}),e.jsxs(ca,{onClick:()=>{m(I),f(I.title)},children:[e.jsx(Fr,{className:"mr-2 h-4 w-4"})," Rename"]}),e.jsxs(ca,{onClick:()=>a.mutate(I),children:[e.jsx(Ia,{className:"mr-2 h-4 w-4"})," Duplicate"]}),e.jsxs(ca,{onClick:()=>M(I),children:[e.jsx(li,{className:"mr-2 h-4 w-4"})," Download PDF"]}),e.jsxs(ca,{onClick:()=>S(I),children:[e.jsx(ln,{className:"mr-2 h-4 w-4"})," Email to a contact"]}),e.jsx(M0,{}),e.jsxs(ca,{className:"text-destructive",onClick:()=>v(I),children:[e.jsx(Sn,{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(Oe,{variant:"secondary",className:"text-[10px]",children:"PDF ready"}):e.jsx(Oe,{variant:"outline",className:"text-[10px]",children:"Draft"})]}),e.jsxs(B,{variant:"outline",size:"sm",className:"w-full gap-2",disabled:g===I.id,onClick:()=>M(I),children:[g===I.id?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(li,{className:"h-4 w-4"}),"Download PDF"]})]})]},I.id)})})]}),e.jsx(Ls,{open:!!h,onOpenChange:I=>!I&&m(null),children:e.jsxs(Ps,{className:"sm:max-w-md",children:[e.jsx(Os,{children:e.jsx(Ds,{children:"Rename presentation"})}),e.jsx(xe,{value:p,onChange:I=>f(I.target.value),autoFocus:!0}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>m(null),children:"Cancel"}),e.jsx(B,{onClick:async()=>{h&&(await l.mutateAsync({id:h.id,title:p.trim()||"Untitled Presentation"}),m(null),se.success("Renamed"))},children:"Save"})]})]})}),e.jsx(Kl,{open:!!y,onOpenChange:I=>!I&&v(null),children:e.jsxs(Ol,{children:[e.jsxs(zl,{children:[e.jsx(Ul,{children:"Delete this presentation?"}),e.jsx(ql,{children:"This permanently removes the presentation, its property photo, and the generated PDF."})]}),e.jsxs(Bl,{children:[e.jsx($l,{children:"Cancel"}),e.jsx(Ml,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",onClick:()=>{y&&i.mutate(y),v(null)},children:"Delete"})]})]})}),e.jsx(TJt,{open:!!j,onOpenChange:I=>!I&&S(null),row:j,brand:c})]})};var cee={};cee.d=(s,t)=>{for(var n in t)cee.o(t,n)&&!cee.o(s,n)&&Object.defineProperty(s,n,{enumerable:!0,get:t[n]})};cee.o=(s,t)=>Object.prototype.hasOwnProperty.call(s,t);var Sc=globalThis.pdfjsLib={};cee.d(Sc,{AbortException:()=>xz,AnnotationEditorLayer:()=>pYe,AnnotationEditorParamsType:()=>bc,AnnotationEditorType:()=>Zc,AnnotationEditorUIManager:()=>N9,AnnotationLayer:()=>EHn,AnnotationMode:()=>M6,ColorPicker:()=>n6e,DOMSVGFactory:()=>Xrt,DrawLayer:()=>yYe,FeatureTest:()=>kb,GlobalWorkerOptions:()=>EA,ImageKind:()=>oCe,InvalidPDFException:()=>PJt,MissingPDFException:()=>fz,OPS:()=>Ek,OutputScale:()=>lKe,PDFDataRangeTransport:()=>Aes,PDFDateString:()=>Vrt,PDFWorker:()=>H$,PasswordResponses:()=>D$n,PermissionFlag:()=>I$n,PixelsPerInch:()=>HP,RenderingCancelledException:()=>qrt,TextLayer:()=>Cse,UnexpectedResponseException:()=>A8e,Util:()=>qo,VerbosityLevel:()=>k8e,XfaLayer:()=>Tes,build:()=>cHn,createValidAbsoluteUrl:()=>z$n,fetchData:()=>T8e,getDocument:()=>eHn,getFilenameFromUrl:()=>K$n,getPdfFilenameFromUrl:()=>Y$n,getXfaPageViewport:()=>Z$n,isDataScheme:()=>M8e,isPdfFile:()=>$rt,noContextMenu:()=>PN,normalizeUnicode:()=>H$n,setLayerDimensions:()=>j9,shadow:()=>fu,version:()=>lHn});const h1=typeof process=="object"&&process+""=="[object process]"&&!process.versions.nw&&!(process.versions.electron&&process.type&&process.type!=="browser"),MJt=[1,0,0,1,0,0],rKe=[.001,0,0,.001,0,0],P$n=1e7,Hze=1.35,qw={ANY:1,DISPLAY:2,PRINT:4,SAVE:8,ANNOTATIONS_FORMS:16,ANNOTATIONS_STORAGE:32,ANNOTATIONS_DISABLE:64,IS_EDITING:128,OPLIST:256},M6={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},L$n="pdfjs_internal_editor_",Zc={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15},bc={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},I$n={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},Qv={FILL:0,STROKE:1,FILL_STROKE:2,INVISIBLE:3,FILL_ADD_TO_PATH:4,STROKE_ADD_TO_PATH:5,FILL_STROKE_ADD_TO_PATH:6,ADD_TO_PATH:7,FILL_STROKE_MASK:3,ADD_TO_PATH_FLAG:4},oCe={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},s0={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},bZ={SOLID:1,DASHED:2,BEVELED:3,INSET:4,UNDERLINE:5},k8e={ERRORS:0,WARNINGS:1,INFOS:5},Ek={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},D$n={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let S8e=k8e.WARNINGS;function R$n(s){Number.isInteger(s)&&(S8e=s)}function F$n(){return S8e}function C8e(s){S8e>=k8e.INFOS&&console.log(`Info: ${s}`)}function gd(s){S8e>=k8e.WARNINGS&&console.log(`Warning: ${s}`)}function Sp(s){throw new Error(s)}function b0(s,t){s||Sp(t)}function O$n(s){switch(s==null?void 0:s.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}function z$n(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=V$n(s)}catch{}}const r=t?new URL(s,t):new URL(s);if(O$n(r))return r}catch{}return null}function fu(s,t,n,r=!1){return Object.defineProperty(s,t,{value:n,enumerable:!r,configurable:!0,writable:!1}),n}const RL=function(){function t(n,r){this.message=n,this.name=r}return t.prototype=new Error,t.constructor=t,t}();class aKe extends RL{constructor(t,n){super(t,"PasswordException"),this.code=n}}class iKe extends RL{constructor(t,n){super(t,"UnknownErrorException"),this.details=n}}class PJt extends RL{constructor(t){super(t,"InvalidPDFException")}}class fz extends RL{constructor(t){super(t,"MissingPDFException")}}class A8e extends RL{constructor(t,n){super(t,"UnexpectedResponseException"),this.status=n}}class B$n extends RL{constructor(t){super(t,"FormatError")}}class xz extends RL{constructor(t){super(t,"AbortException")}}function LJt(s){(typeof s!="object"||(s==null?void 0:s.length)===void 0)&&Sp("Invalid argument for bytesToString");const t=s.length,n=8192;if(t>24&255,s>>16&255,s>>8&255,s&255)}function Brt(s){const t=Object.create(null);for(const[n,r]of s)t[n]=r;return t}function q$n(){const s=new Uint8Array(4);return s[0]=1,new Uint32Array(s.buffer,0,1)[0]===1}function $$n(){try{return new Function(""),!0}catch{return!1}}class kb{static get isLittleEndian(){return fu(this,"isLittleEndian",q$n())}static get isEvalSupported(){return fu(this,"isEvalSupported",$$n())}static get isOffscreenCanvasSupported(){return fu(this,"isOffscreenCanvasSupported",typeof OffscreenCanvas<"u")}static get platform(){return typeof navigator<"u"&&typeof(navigator==null?void 0:navigator.platform)=="string"?fu(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")}):fu(this,"platform",{isMac:!1,isWindows:!1,isFirefox:!1})}static get isCSSRoundSupported(){var t,n;return fu(this,"isCSSRoundSupported",(n=(t=globalThis.CSS)==null?void 0:t.supports)==null?void 0:n.call(t,"width: round(1.5px, 1px)"))}}const Gze=Array.from(Array(256).keys(),s=>s.toString(16).padStart(2,"0"));var hE,lCe,oKe;class qo{static makeHexColor(t,n,r){return`#${Gze[t]}${Gze[n]}${Gze[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)],ts(this,hE,oKe).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),ts(this,hE,oKe).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}}hE=new WeakSet,lCe=function(t,n,r,a,i,l,o,c,d,u){if(d<=0||d>=1)return;const h=1-d,m=d*d,p=m*d,f=h*(h*(h*t+3*d*n)+3*m*r)+p*a,y=h*(h*(h*i+3*d*l)+3*m*o)+p*c;u[0]=Math.min(u[0],f),u[1]=Math.min(u[1],y),u[2]=Math.max(u[2],f),u[3]=Math.max(u[3],y)},oKe=function(t,n,r,a,i,l,o,c,d,u,h,m){if(Math.abs(d)<1e-12){Math.abs(u)>=1e-12&&ts(this,hE,lCe).call(this,t,n,r,a,i,l,o,c,-h/u,m);return}const p=u**2-4*h*d;if(p<0)return;const f=Math.sqrt(p),y=2*d;ts(this,hE,lCe).call(this,t,n,r,a,i,l,o,c,(-u+f)/y,m),ts(this,hE,lCe).call(this,t,n,r,a,i,l,o,c,(-u-f)/y,m)},us(qo,hE);function V$n(s){return decodeURIComponent(escape(s))}let Wze=null,iSt=null;function H$n(s){return Wze||(Wze=/([\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,iSt=new Map([["ſt","ſt"]])),s.replaceAll(Wze,(t,n,r)=>n?n.normalize("NFKC"):iSt.get(r))}function G$n(){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 LJt(s)}const Urt="pdfjs_internal_id_",j3={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 W$n(s){return Uint8Array.prototype.toBase64?s.toBase64():btoa(LJt(s))}const D3="http://www.w3.org/2000/svg",aF=class aF{};Pr(aF,"CSS",96),Pr(aF,"PDF",72),Pr(aF,"PDF_TO_CSS_UNITS",aF.CSS/aF.PDF);let HP=aF;async function T8e(s,t="text"){if(PX(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 Xae{constructor({viewBox:t,scale:n,rotation:r,offsetX:a=0,offsetY:i=0,dontFlip:l=!1}){this.viewBox=t,this.scale=n,this.rotation=r,this.offsetX=a,this.offsetY=i;const o=(t[2]+t[0])/2,c=(t[3]+t[1])/2;let d,u,h,m;switch(r%=360,r<0&&(r+=360),r){case 180:d=-1,u=0,h=0,m=1;break;case 90:d=0,u=1,h=1,m=0;break;case 270:d=0,u=-1,h=-1,m=0;break;case 0:d=1,u=0,h=0,m=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}l&&(h=-h,m=-m);let p,f,y,v;d===0?(p=Math.abs(c-t[1])*n+a,f=Math.abs(o-t[0])*n+i,y=(t[3]-t[1])*n,v=(t[2]-t[0])*n):(p=Math.abs(o-t[0])*n+a,f=Math.abs(c-t[1])*n+i,y=(t[2]-t[0])*n,v=(t[3]-t[1])*n),this.transform=[d*n,u*n,h*n,m*n,p-d*n*o-h*n*c,f-u*n*o-m*n*c],this.width=y,this.height=v}get rawDims(){const{viewBox:t}=this;return fu(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 Xae({viewBox:this.viewBox.slice(),scale:t,rotation:n,offsetX:r,offsetY:a,dontFlip:i})}convertToViewportPoint(t,n){return qo.applyTransform([t,n],this.transform)}convertToViewportRectangle(t){const n=qo.applyTransform([t[0],t[1]],this.transform),r=qo.applyTransform([t[2],t[3]],this.transform);return[n[0],n[1],r[0],r[1]]}convertToPdfPoint(t,n){return qo.applyInverseTransform([t,n],this.transform)}}class qrt extends RL{constructor(t,n=0){super(t,"RenderingCancelledException"),this.extraDelay=n}}function M8e(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))}}ene=new WeakMap,us(Vrt,ene);function Z$n(s,{scale:t=1,rotation:n=0}){const{width:r,height:a}=s.attributes.style,i=[0,0,parseInt(r),parseInt(a)];return new Xae({viewBox:i,scale:t,rotation:n})}function Hrt(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):(gd(`Not a valid color format: "${s}"`),[0,0,0])}function X$n(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,Hrt(r))}t.remove()}function Nf(s){const{a:t,b:n,c:r,d:a,e:i,f:l}=s.getTransform();return[t,n,r,a,i,l]}function N3(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 j9(s,t,n=!1,r=!0){if(t instanceof Xae){const{pageWidth:a,pageHeight:i}=t.rawDims,{style:l}=s,o=kb.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 lKe{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 $6,HF,Pk,GF,tne,sne,q6e,IJt,Ab,DJt,RJt,cCe,FJt,dKe;const H3=class H3{constructor(t){us(this,Ab);us(this,$6,null);us(this,HF,null);us(this,Pk);us(this,GF,null);us(this,tne,null);Ut(this,Pk,t),ye(H3,sne)||Ut(H3,sne,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=Ut(this,$6,document.createElement("div"));t.classList.add("editToolbar","hidden"),t.setAttribute("role","toolbar");const n=ye(this,Pk)._uiManager._signal;t.addEventListener("contextmenu",PN,{signal:n}),t.addEventListener("pointerdown",ts(H3,q6e,IJt),{signal:n});const r=Ut(this,GF,document.createElement("div"));r.className="buttons",t.append(r);const a=ye(this,Pk).toolbarPosition;if(a){const{style:i}=t,l=ye(this,Pk)._uiManager.direction==="ltr"?1-a[0]:a[0];i.insetInlineEnd=`${100*l}%`,i.top=`calc(${100*a[1]}% + var(--editor-toolbar-vert-offset))`}return ts(this,Ab,FJt).call(this),t}get div(){return ye(this,$6)}hide(){var t;ye(this,$6).classList.add("hidden"),(t=ye(this,HF))==null||t.hideDropdown()}show(){var t;ye(this,$6).classList.remove("hidden"),(t=ye(this,tne))==null||t.shown()}async addAltText(t){const n=await t.render();ts(this,Ab,cCe).call(this,n),ye(this,GF).prepend(n,ye(this,Ab,dKe)),Ut(this,tne,t)}addColorPicker(t){Ut(this,HF,t);const n=t.renderButton();ts(this,Ab,cCe).call(this,n),ye(this,GF).prepend(n,ye(this,Ab,dKe))}remove(){var t;ye(this,$6).remove(),(t=ye(this,HF))==null||t.destroy(),Ut(this,HF,null)}};$6=new WeakMap,HF=new WeakMap,Pk=new WeakMap,GF=new WeakMap,tne=new WeakMap,sne=new WeakMap,q6e=new WeakSet,IJt=function(t){t.stopPropagation()},Ab=new WeakSet,DJt=function(t){ye(this,Pk)._focusEventsAllowed=!1,t.preventDefault(),t.stopPropagation()},RJt=function(t){ye(this,Pk)._focusEventsAllowed=!0,t.preventDefault(),t.stopPropagation()},cCe=function(t){const n=ye(this,Pk)._uiManager._signal;t.addEventListener("focusin",ts(this,Ab,DJt).bind(this),{capture:!0,signal:n}),t.addEventListener("focusout",ts(this,Ab,RJt).bind(this),{capture:!0,signal:n}),t.addEventListener("contextmenu",PN,{signal:n})},FJt=function(){const{editorType:t,_uiManager:n}=ye(this,Pk),r=document.createElement("button");r.className="delete",r.tabIndex=0,r.setAttribute("data-l10n-id",ye(H3,sne)[t]),ts(this,Ab,cCe).call(this,r),r.addEventListener("click",a=>{n.delete()},{signal:n._signal}),ye(this,GF).append(r)},dKe=function(){const t=document.createElement("div");return t.className="divider",t},us(H3,q6e),us(H3,sne,null);let cKe=H3;var nne,WF,KF,JP,OJt,zJt,BJt;class Q$n{constructor(t){us(this,JP);us(this,nne,null);us(this,WF,null);us(this,KF);Ut(this,KF,t)}show(t,n,r){const[a,i]=ts(this,JP,zJt).call(this,n,r),{style:l}=ye(this,WF)||Ut(this,WF,ts(this,JP,OJt).call(this));t.append(ye(this,WF)),l.insetInlineEnd=`${100*a}%`,l.top=`calc(${100*i}% + var(--editor-toolbar-vert-offset))`}hide(){ye(this,WF).remove()}}nne=new WeakMap,WF=new WeakMap,KF=new WeakMap,JP=new WeakSet,OJt=function(){const t=Ut(this,WF,document.createElement("div"));t.className="editToolbar",t.setAttribute("role","toolbar"),t.addEventListener("contextmenu",PN,{signal:ye(this,KF)._signal});const n=Ut(this,nne,document.createElement("div"));return n.className="buttons",t.append(n),ts(this,JP,BJt).call(this),t},zJt=function(t,n){let r=0,a=0;for(const i of t){const l=i.y+i.height;if(lr){a=o,r=l;continue}n?o>a&&(a=o):o{ye(this,KF).highlightSelection("floating_button")},{signal:r}),ye(this,nne).append(t)};function e6e(s,t,n){for(const r of n)t.addEventListener(r,s[r].bind(s))}function J$n(s){return Math.round(Math.min(255,Math.max(1,255*s))).toString(16).padStart(2,"0")}var $6e;class eVn{constructor(){us(this,$6e,0)}get id(){return`${L$n}${X0(this,$6e)._++}`}}$6e=new WeakMap;var pV,rne,t1,fV,dCe;const aot=class aot{constructor(){us(this,fV);us(this,pV,G$n());us(this,rne,0);us(this,t1,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 fu(this,"_isSVGFittingCanvas",i)}async getFromFile(t){const{lastModified:n,name:r,size:a,type:i}=t;return ts(this,fV,dCe).call(this,`${n}_${r}_${a}_${i}`,t)}async getFromUrl(t){return ts(this,fV,dCe).call(this,t,t)}async getFromBlob(t,n){const r=await n;return ts(this,fV,dCe).call(this,t,r)}async getFromId(t){ye(this,t1)||Ut(this,t1,new Map);const n=ye(this,t1).get(t);if(!n)return null;if(n.bitmap)return n.refCounter+=1,n;if(n.file)return this.getFromFile(n.file);if(n.blobPromise){const{blobPromise:r}=n;return delete n.blobPromise,this.getFromBlob(n.id,r)}return this.getFromUrl(n.url)}getFromCanvas(t,n){ye(this,t1)||Ut(this,t1,new Map);let r=ye(this,t1).get(t);if(r!=null&&r.bitmap)return r.refCounter+=1,r;const a=new OffscreenCanvas(n.width,n.height);return a.getContext("2d").drawImage(n,0,0),r={bitmap:a.transferToImageBitmap(),id:`image_${ye(this,pV)}_${X0(this,rne)._++}`,refCounter:1,isSvg:!1},ye(this,t1).set(t,r),ye(this,t1).set(r.id,r),r}getSvgUrl(t){const n=ye(this,t1).get(t);return n!=null&&n.isSvg?n.svgUrl:null}deleteId(t){var a;ye(this,t1)||Ut(this,t1,new Map);const n=ye(this,t1).get(t);if(!n||(n.refCounter-=1,n.refCounter!==0))return;const{bitmap:r}=n;if(!n.url&&!n.file){const i=new OffscreenCanvas(r.width,r.height);i.getContext("bitmaprenderer").transferFromImageBitmap(r),n.blobPromise=i.convertToBlob()}(a=r.close)==null||a.call(r),n.bitmap=null}isValidId(t){return t.startsWith(`image_${ye(this,pV)}_`)}};pV=new WeakMap,rne=new WeakMap,t1=new WeakMap,fV=new WeakSet,dCe=async function(t,n){ye(this,t1)||Ut(this,t1,new Map);let r=ye(this,t1).get(t);if(r===null)return null;if(r!=null&&r.bitmap)return r.refCounter+=1,r;try{r||(r={bitmap:null,id:`image_${ye(this,pV)}_${X0(this,rne)._++}`,refCounter:0,isSvg:!1});let a;if(typeof n=="string"?(r.url=n,a=await T8e(n,"blob")):n instanceof File?a=r.file=n:n instanceof Blob&&(a=n),a.type==="image/svg+xml"){const i=aot._isSVGFittingCanvas,l=new FileReader,o=new Image,c=new Promise((d,u)=>{o.onload=()=>{r.bitmap=o,r.isSvg=!0,d()},l.onload=async()=>{const h=r.svgUrl=l.result;o.src=await i?`${h}#svgView(preserveAspectRatio(none))`:h},o.onerror=l.onerror=u});l.readAsDataURL(a),await c}else r.bitmap=await createImageBitmap(a);r.refCounter=1}catch(a){console.error(a),r=null}return ye(this,t1).set(t,r),r&&ye(this,t1).set(r.id,r),r};let uKe=aot;var sy,V6,ane,ny;class tVn{constructor(t=128){us(this,sy,[]);us(this,V6,!1);us(this,ane);us(this,ny,-1);Ut(this,ane,t)}add({cmd:t,undo:n,post:r,mustExec:a,type:i=NaN,overwriteIfSameType:l=!1,keepUndo:o=!1}){if(a&&t(),ye(this,V6))return;const c={cmd:t,undo:n,post:r,type:i};if(ye(this,ny)===-1){ye(this,sy).length>0&&(ye(this,sy).length=0),Ut(this,ny,0),ye(this,sy).push(c);return}if(l&&ye(this,sy)[ye(this,ny)].type===i){o&&(c.undo=ye(this,sy)[ye(this,ny)].undo),ye(this,sy)[ye(this,ny)]=c;return}const d=ye(this,ny)+1;d===ye(this,ane)?ye(this,sy).splice(0,1):(Ut(this,ny,d),di===n[l]))return H6e._colorsMapping.get(r);return n}getHexCode(t){const n=this._colors.get(t);return n?qo.makeHexColor(...n):t}};Pr(H6e,"_colorsMapping",new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]));let hKe=H6e;var xV,Lw,a0,Jy,gV,sA,yV,Lk,H6,vV,YF,X5,Ik,ZF,ine,one,bV,lne,Q5,G6,_V,W6,J5,G6e,K6,cne,Y6,XF,dne,une,ry,Lh,nA,QF,hne,mne,Z6,e4,rA,pne,L2,qi,uCe,mKe,qJt,$Jt,hCe,VJt,HJt,GJt,pKe,WJt,fKe,xKe,KJt,Q1,QT,YJt,ZJt,gKe,XJt,LX,yKe;const _q=class _q{constructor(t,n,r,a,i,l,o,c,d,u,h){us(this,qi);us(this,xV,new AbortController);us(this,Lw,null);us(this,a0,new Map);us(this,Jy,new Map);us(this,gV,null);us(this,sA,null);us(this,yV,null);us(this,Lk,new tVn);us(this,H6,null);us(this,vV,0);us(this,YF,new Set);us(this,X5,null);us(this,Ik,null);us(this,ZF,new Set);us(this,ine,!1);us(this,one,!1);us(this,bV,!1);us(this,lne,null);us(this,Q5,null);us(this,G6,null);us(this,_V,null);us(this,W6,!1);us(this,J5,null);us(this,G6e,new eVn);us(this,K6,!1);us(this,cne,!1);us(this,Y6,null);us(this,XF,null);us(this,dne,null);us(this,une,null);us(this,ry,Zc.NONE);us(this,Lh,new Set);us(this,nA,null);us(this,QF,null);us(this,hne,null);us(this,mne,{isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1});us(this,Z6,[0,0]);us(this,e4,null);us(this,rA,null);us(this,pne,null);us(this,L2,null);const m=this._signal=ye(this,xV).signal;Ut(this,rA,t),Ut(this,pne,n),Ut(this,gV,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}),ts(this,qi,VJt).call(this),ts(this,qi,KJt).call(this),ts(this,qi,pKe).call(this),Ut(this,sA,i.annotationStorage),Ut(this,lne,i.filterFactory),Ut(this,QF,l),Ut(this,_V,o||null),Ut(this,ine,c),Ut(this,one,d),Ut(this,bV,u),Ut(this,une,h||null),this.viewParameters={realScale:HP.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1}static get _keyboardManager(){const t=_q.prototype,n=l=>ye(l,rA).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 fu(this,"_keyboardManager",new Qae([[["ctrl+a","mac+meta+a"],t.selectAll,{checker:r}],[["ctrl+z","mac+meta+z"],t.undo,{checker:r}],[["ctrl+y","ctrl+shift+z","mac+meta+shift+z","ctrl+shift+Z","mac+meta+shift+Z"],t.redo,{checker:r}],[["Backspace","alt+Backspace","ctrl+Backspace","shift+Backspace","mac+Backspace","mac+alt+Backspace","mac+ctrl+Backspace","Delete","ctrl+Delete","shift+Delete","mac+Delete"],t.delete,{checker:r}],[["Enter","mac+Enter"],t.addNewEditorFromKeyboard,{checker:(l,{target:o})=>!(o instanceof HTMLButtonElement)&&ye(l,rA).contains(o)&&!l.isEnterHandled}],[[" ","mac+ "],t.addNewEditorFromKeyboard,{checker:(l,{target:o})=>!(o instanceof HTMLButtonElement)&&ye(l,rA).contains(document.activeElement)}],[["Escape","mac+Escape"],t.unselectAll],[["ArrowLeft","mac+ArrowLeft"],t.translateSelectedEditors,{args:[-a,0],checker:n}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t.translateSelectedEditors,{args:[-i,0],checker:n}],[["ArrowRight","mac+ArrowRight"],t.translateSelectedEditors,{args:[a,0],checker:n}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t.translateSelectedEditors,{args:[i,0],checker:n}],[["ArrowUp","mac+ArrowUp"],t.translateSelectedEditors,{args:[0,-a],checker:n}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t.translateSelectedEditors,{args:[0,-i],checker:n}],[["ArrowDown","mac+ArrowDown"],t.translateSelectedEditors,{args:[0,a],checker:n}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t.translateSelectedEditors,{args:[0,i],checker:n}]]))}destroy(){var t,n,r,a;(t=ye(this,L2))==null||t.resolve(),Ut(this,L2,null),(n=ye(this,xV))==null||n.abort(),Ut(this,xV,null),this._signal=null;for(const i of ye(this,Jy).values())i.destroy();ye(this,Jy).clear(),ye(this,a0).clear(),ye(this,ZF).clear(),Ut(this,Lw,null),ye(this,Lh).clear(),ye(this,Lk).destroy(),(r=ye(this,gV))==null||r.destroy(),(a=ye(this,J5))==null||a.hide(),Ut(this,J5,null),ye(this,Q5)&&(clearTimeout(ye(this,Q5)),Ut(this,Q5,null)),ye(this,e4)&&(clearTimeout(ye(this,e4)),Ut(this,e4,null))}combinedSignal(t){return AbortSignal.any([this._signal,t.signal])}get mlManager(){return ye(this,une)}get useNewAltTextFlow(){return ye(this,one)}get useNewAltTextWhenAddingImage(){return ye(this,bV)}get hcmFilter(){return fu(this,"hcmFilter",ye(this,QF)?ye(this,lne).addHCMFilter(ye(this,QF).foreground,ye(this,QF).background):"none")}get direction(){return fu(this,"direction",getComputedStyle(ye(this,rA)).direction)}get highlightColors(){return fu(this,"highlightColors",ye(this,_V)?new Map(ye(this,_V).split(",").map(t=>t.split("=").map(n=>n.trim()))):null)}get highlightColorNames(){return fu(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,t=>t.reverse())):null)}setMainHighlightColorPicker(t){Ut(this,dne,t)}editAltText(t,n=!1){var r;(r=ye(this,gV))==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":Ut(this,bV,n);break}}onPageChanging({pageNumber:t}){Ut(this,vV,t-1)}focusMainContainer(){ye(this,rA).focus()}findParent(t,n){for(const r of ye(this,Jy).values()){const{x:a,y:i,width:l,height:o}=r.div.getBoundingClientRect();if(t>=a&&t<=a+l&&n>=i&&n<=i+o)return r}return null}disableUserSelect(t=!1){ye(this,pne).classList.toggle("noUserSelect",t)}addShouldRescale(t){ye(this,ZF).add(t)}removeShouldRescale(t){ye(this,ZF).delete(t)}onScaleChanging({scale:t}){this.commitOrRemove(),this.viewParameters.realScale=t*HP.PDF_TO_CSS_UNITS;for(const n of ye(this,ZF))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=ts(this,qi,uCe).call(this,n).closest(".textLayer"),u=this.getSelectionBoxes(d);if(!u)return;n.empty();const h=ts(this,qi,mKe).call(this,d),m=ye(this,ry)===Zc.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(Zc.HIGHLIGHT,p);return}p()}addToAnnotationStorage(t){!t.isEmpty()&&ye(this,sA)&&!ye(this,sA).has(t.id)&&ye(this,sA).setValue(t.id,t)}blur(){if(this.isShiftKeyDown=!1,ye(this,W6)&&(Ut(this,W6,!1),ts(this,qi,hCe).call(this,"main_toolbar")),!this.hasSelection)return;const{activeElement:t}=document;for(const n of ye(this,Lh))if(n.div.contains(t)){Ut(this,XF,[n,t]),n._focusEventsAllowed=!1;break}}focus(){if(!ye(this,XF))return;const[t,n]=ye(this,XF);Ut(this,XF,null),n.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this._signal}),n.focus()}addEditListeners(){ts(this,qi,pKe).call(this),ts(this,qi,fKe).call(this)}removeEditListeners(){ts(this,qi,WJt).call(this),ts(this,qi,xKe).call(this)}dragOver(t){for(const{type:n}of t.dataTransfer.items)for(const r of ye(this,Ik))if(r.isHandlingMimeForPasting(n)){t.dataTransfer.dropEffect="copy",t.preventDefault();return}}drop(t){for(const n of t.dataTransfer.items)for(const r of ye(this,Ik))if(r.isHandlingMimeForPasting(n.type)){r.paste(n,this.currentLayer),t.preventDefault();return}}copy(t){var r;if(t.preventDefault(),(r=ye(this,Lw))==null||r.commitOrRemove(),!this.hasSelection)return;const n=[];for(const a of ye(this,Lh)){const i=a.serialize(!0);i&&n.push(i)}n.length!==0&&t.clipboardData.setData("application/pdfjs",JSON.stringify(n))}cut(t){this.copy(t),this.delete()}async paste(t){t.preventDefault();const{clipboardData:n}=t;for(const i of n.items)for(const l of ye(this,Ik))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){gd(`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)ts(this,qi,gKe).call(this,c);ts(this,qi,yKe).call(this,i)},o=()=>{for(const c of i)c.remove()};this.addCommands({cmd:l,undo:o,mustExec:!0})}catch(i){gd(`paste: "${i.message}".`)}}keydown(t){!this.isShiftKeyDown&&t.key==="Shift"&&(this.isShiftKeyDown=!0),ye(this,ry)!==Zc.NONE&&!this.isEditorHandlingKeyboard&&_q._keyboardManager.exec(this,t)}keyup(t){this.isShiftKeyDown&&t.key==="Shift"&&(this.isShiftKeyDown=!1,ye(this,W6)&&(Ut(this,W6,!1),ts(this,qi,hCe).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?(ts(this,qi,HJt).call(this),ts(this,qi,fKe).call(this),ts(this,qi,Q1).call(this,{isEditing:ye(this,ry)!==Zc.NONE,isEmpty:ts(this,qi,LX).call(this),hasSomethingToUndo:ye(this,Lk).hasSomethingToUndo(),hasSomethingToRedo:ye(this,Lk).hasSomethingToRedo(),hasSelectedEditor:!1})):(ts(this,qi,GJt).call(this),ts(this,qi,xKe).call(this),ts(this,qi,Q1).call(this,{isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(t){if(!ye(this,Ik)){Ut(this,Ik,t);for(const n of ye(this,Ik))ts(this,qi,QT).call(this,n.defaultPropertiesToUpdate)}}getId(){return ye(this,G6e).id}get currentLayer(){return ye(this,Jy).get(ye(this,vV))}getLayer(t){return ye(this,Jy).get(t)}get currentPageIndex(){return ye(this,vV)}addLayer(t){ye(this,Jy).set(t.pageIndex,t),ye(this,K6)?t.enable():t.disable()}removeLayer(t){ye(this,Jy).delete(t.pageIndex)}async updateMode(t,n=null,r=!1){if(ye(this,ry)!==t&&!(ye(this,L2)&&(await ye(this,L2).promise,!ye(this,L2)))){if(Ut(this,L2,Promise.withResolvers()),Ut(this,ry,t),t===Zc.NONE){this.setEditingState(!1),ts(this,qi,ZJt).call(this),ye(this,L2).resolve();return}this.setEditingState(!0),await ts(this,qi,YJt).call(this),this.unselectAll();for(const a of ye(this,Jy).values())a.updateMode(t);if(!n){r&&this.addNewEditorFromKeyboard(),ye(this,L2).resolve();return}for(const a of ye(this,a0).values())a.annotationElementId===n?(this.setSelected(a),a.enterInEditMode()):a.unselect();ye(this,L2).resolve()}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(t){t!==ye(this,ry)&&this._eventBus.dispatch("switchannotationeditormode",{source:this,mode:t})}updateParams(t,n){var r;if(ye(this,Ik)){switch(t){case bc.CREATE:this.currentLayer.addNewEditor();return;case bc.HIGHLIGHT_DEFAULT_COLOR:(r=ye(this,dne))==null||r.updateColor(n);break;case bc.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}}),(ye(this,hne)||Ut(this,hne,new Map)).set(t,n),this.showAllEditors("highlight",n);break}for(const a of ye(this,Lh))a.updateParams(t,n);for(const a of ye(this,Ik))a.updateDefaultParams(t,n)}}showAllEditors(t,n,r=!1){var i;for(const l of ye(this,a0).values())l.editorType===t&&l.show(n);(((i=ye(this,hne))==null?void 0:i.get(bc.HIGHLIGHT_SHOW_ALL))??!0)!==n&&ts(this,qi,QT).call(this,[[bc.HIGHLIGHT_SHOW_ALL,n]])}enableWaiting(t=!1){if(ye(this,cne)!==t){Ut(this,cne,t);for(const n of ye(this,Jy).values())t?n.disableClick():n.enableClick(),n.div.classList.toggle("waiting",t)}}getEditors(t){const n=[];for(const r of ye(this,a0).values())r.pageIndex===t&&n.push(r);return n}getEditor(t){return ye(this,a0).get(t)}addEditor(t){ye(this,a0).set(t.id,t)}removeEditor(t){var n;t.div.contains(document.activeElement)&&(ye(this,Q5)&&clearTimeout(ye(this,Q5)),Ut(this,Q5,setTimeout(()=>{this.focusMainContainer(),Ut(this,Q5,null)},0))),ye(this,a0).delete(t.id),this.unselect(t),(!t.annotationElementId||!ye(this,YF).has(t.annotationElementId))&&((n=ye(this,sA))==null||n.remove(t.id))}addDeletedAnnotationElement(t){ye(this,YF).add(t.annotationElementId),this.addChangedExistingAnnotation(t),t.deleted=!0}isDeletedAnnotationElement(t){return ye(this,YF).has(t)}removeDeletedAnnotationElement(t){ye(this,YF).delete(t.annotationElementId),this.removeChangedExistingAnnotation(t),t.deleted=!1}setActiveEditor(t){ye(this,Lw)!==t&&(Ut(this,Lw,t),t&&ts(this,qi,QT).call(this,t.propertiesToUpdate))}updateUI(t){ye(this,qi,XJt)===t&&ts(this,qi,QT).call(this,t.propertiesToUpdate)}toggleSelected(t){if(ye(this,Lh).has(t)){ye(this,Lh).delete(t),t.unselect(),ts(this,qi,Q1).call(this,{hasSelectedEditor:this.hasSelection});return}ye(this,Lh).add(t),t.select(),ts(this,qi,QT).call(this,t.propertiesToUpdate),ts(this,qi,Q1).call(this,{hasSelectedEditor:!0})}setSelected(t){for(const n of ye(this,Lh))n!==t&&n.unselect();ye(this,Lh).clear(),ye(this,Lh).add(t),t.select(),ts(this,qi,QT).call(this,t.propertiesToUpdate),ts(this,qi,Q1).call(this,{hasSelectedEditor:!0})}isSelected(t){return ye(this,Lh).has(t)}get firstSelectedEditor(){return ye(this,Lh).values().next().value}unselect(t){t.unselect(),ye(this,Lh).delete(t),ts(this,qi,Q1).call(this,{hasSelectedEditor:this.hasSelection})}get hasSelection(){return ye(this,Lh).size!==0}get isEnterHandled(){return ye(this,Lh).size===1&&this.firstSelectedEditor.isEnterHandled}undo(){ye(this,Lk).undo(),ts(this,qi,Q1).call(this,{hasSomethingToUndo:ye(this,Lk).hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:ts(this,qi,LX).call(this)})}redo(){ye(this,Lk).redo(),ts(this,qi,Q1).call(this,{hasSomethingToUndo:!0,hasSomethingToRedo:ye(this,Lk).hasSomethingToRedo(),isEmpty:ts(this,qi,LX).call(this)})}addCommands(t){ye(this,Lk).add(t),ts(this,qi,Q1).call(this,{hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:ts(this,qi,LX).call(this)})}delete(){if(this.commitOrRemove(),!this.hasSelection)return;const t=[...ye(this,Lh)],n=()=>{for(const a of t)a.remove()},r=()=>{for(const a of t)ts(this,qi,gKe).call(this,a)};this.addCommands({cmd:n,undo:r,mustExec:!0})}commitOrRemove(){var t;(t=ye(this,Lw))==null||t.commitOrRemove()}hasSomethingToControl(){return ye(this,Lw)||this.hasSelection}selectAll(){for(const t of ye(this,Lh))t.commit();ts(this,qi,yKe).call(this,ye(this,a0).values())}unselectAll(){if(!(ye(this,Lw)&&(ye(this,Lw).commitOrRemove(),ye(this,ry)!==Zc.NONE))&&this.hasSelection){for(const t of ye(this,Lh))t.unselect();ye(this,Lh).clear(),ts(this,qi,Q1).call(this,{hasSelectedEditor:!1})}}translateSelectedEditors(t,n,r=!1){if(r||this.commitOrRemove(),!this.hasSelection)return;ye(this,Z6)[0]+=t,ye(this,Z6)[1]+=n;const[a,i]=ye(this,Z6),l=[...ye(this,Lh)],o=1e3;ye(this,e4)&&clearTimeout(ye(this,e4)),Ut(this,e4,setTimeout(()=>{Ut(this,e4,null),ye(this,Z6)[0]=ye(this,Z6)[1]=0,this.addCommands({cmd:()=>{for(const c of l)ye(this,a0).has(c.id)&&c.translateInPage(a,i)},undo:()=>{for(const c of l)ye(this,a0).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),Ut(this,X5,new Map);for(const t of ye(this,Lh))ye(this,X5).set(t,{savedX:t.x,savedY:t.y,savedPageIndex:t.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!ye(this,X5))return!1;this.disableUserSelect(!1);const t=ye(this,X5);Ut(this,X5,null);let n=!1;for(const[{x:a,y:i,pageIndex:l},o]of t)o.newX=a,o.newY=i,o.newPageIndex=l,n||(n=a!==o.savedX||i!==o.savedY||l!==o.savedPageIndex);if(!n)return!1;const r=(a,i,l,o)=>{if(ye(this,a0).has(a.id)){const c=ye(this,Jy).get(o);c?a._setParentAndPosition(c,i,l):(a.pageIndex=o,a.x=i,a.y=l)}};return this.addCommands({cmd:()=>{for(const[a,{newX:i,newY:l,newPageIndex:o}]of t)r(a,i,l,o)},undo:()=>{for(const[a,{savedX:i,savedY:l,savedPageIndex:o}]of t)r(a,i,l,o)},mustExec:!0}),!0}dragSelectedEditors(t,n){if(ye(this,X5))for(const r of ye(this,X5).keys())r.drag(t,n)}rebuild(t){if(t.parent===null){const n=this.getLayer(t.pageIndex);n?(n.changeParent(t),n.addOrRebuild(t)):(this.addEditor(t),this.addToAnnotationStorage(t),t.rebuild())}else t.parent.addOrRebuild(t)}get isEditorHandlingKeyboard(){var t;return((t=this.getActive())==null?void 0:t.shouldGetKeyboardEvents())||ye(this,Lh).size===1&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(t){return ye(this,Lw)===t}getActive(){return ye(this,Lw)}getMode(){return ye(this,ry)}get imageManager(){return fu(this,"imageManager",new uKe)}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"&&ts(this,qi,hCe).call(this,"main_toolbar"))};window.addEventListener("pointerup",h,{signal:u}),window.addEventListener("blur",h,{signal:u})}},hCe=function(t=""){ye(this,ry)===Zc.HIGHLIGHT?this.highlightSelection(t):ye(this,ine)&&ts(this,qi,qJt).call(this)},VJt=function(){document.addEventListener("selectionchange",ts(this,qi,$Jt).bind(this),{signal:this._signal})},HJt=function(){if(ye(this,G6))return;Ut(this,G6,new AbortController);const t=this.combinedSignal(ye(this,G6));window.addEventListener("focus",this.focus.bind(this),{signal:t}),window.addEventListener("blur",this.blur.bind(this),{signal:t})},GJt=function(){var t;(t=ye(this,G6))==null||t.abort(),Ut(this,G6,null)},pKe=function(){if(ye(this,Y6))return;Ut(this,Y6,new AbortController);const t=this.combinedSignal(ye(this,Y6));window.addEventListener("keydown",this.keydown.bind(this),{signal:t}),window.addEventListener("keyup",this.keyup.bind(this),{signal:t})},WJt=function(){var t;(t=ye(this,Y6))==null||t.abort(),Ut(this,Y6,null)},fKe=function(){if(ye(this,H6))return;Ut(this,H6,new AbortController);const t=this.combinedSignal(ye(this,H6));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})},xKe=function(){var t;(t=ye(this,H6))==null||t.abort(),Ut(this,H6,null)},KJt=function(){const t=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:t}),document.addEventListener("drop",this.drop.bind(this),{signal:t})},Q1=function(t){Object.entries(t).some(([r,a])=>ye(this,mne)[r]!==a)&&(this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(ye(this,mne),t)}),ye(this,ry)===Zc.HIGHLIGHT&&t.hasSelectedEditor===!1&&ts(this,qi,QT).call(this,[[bc.HIGHLIGHT_FREE,!0]]))},QT=function(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})},YJt=async function(){if(!ye(this,K6)){Ut(this,K6,!0);const t=[];for(const n of ye(this,Jy).values())t.push(n.enable());await Promise.all(t);for(const n of ye(this,a0).values())n.enable()}},ZJt=function(){if(this.unselectAll(),ye(this,K6)){Ut(this,K6,!1);for(const t of ye(this,Jy).values())t.disable();for(const t of ye(this,a0).values())t.disable()}},gKe=function(t){const n=ye(this,Jy).get(t.pageIndex);n?n.addOrRebuild(t):(this.addEditor(t),this.addToAnnotationStorage(t))},XJt=function(){let t=null;for(t of ye(this,Lh));return t},LX=function(){if(ye(this,a0).size===0)return!0;if(ye(this,a0).size===1)for(const t of ye(this,a0).values())return t.isEmpty();return!1},yKe=function(t){for(const n of ye(this,Lh))n.unselect();ye(this,Lh).clear();for(const n of t)n.isEmpty()||(ye(this,Lh).add(n),n.select());ts(this,qi,Q1).call(this,{hasSelectedEditor:this.hasSelection})},Pr(_q,"TRANSLATE_SMALL",1),Pr(_q,"TRANSLATE_BIG",10);let N9=_q;var ay,t4,Dk,wV,s4,Iw,jV,n4,u_,aA,JF,r4,X6,iS,IX,mCe;const eb=class eb{constructor(t){us(this,iS);us(this,ay,null);us(this,t4,!1);us(this,Dk,null);us(this,wV,null);us(this,s4,null);us(this,Iw,null);us(this,jV,!1);us(this,n4,null);us(this,u_,null);us(this,aA,null);us(this,JF,null);us(this,r4,!1);Ut(this,u_,t),Ut(this,r4,t._uiManager.useNewAltTextFlow),ye(eb,X6)||Ut(eb,X6,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){eb._l10n??(eb._l10n=t)}async render(){const t=Ut(this,Dk,document.createElement("button"));t.className="altText",t.tabIndex="0";const n=Ut(this,wV,document.createElement("span"));t.append(n),ye(this,r4)?(t.classList.add("new"),t.setAttribute("data-l10n-id",ye(eb,X6).missing),n.setAttribute("data-l10n-id",ye(eb,X6)["missing-label"])):(t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button"),n.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button-label"));const r=ye(this,u_)._uiManager._signal;t.addEventListener("contextmenu",PN,{signal:r}),t.addEventListener("pointerdown",i=>i.stopPropagation(),{signal:r});const a=i=>{i.preventDefault(),ye(this,u_)._uiManager.editAltText(ye(this,u_)),ye(this,r4)&&ye(this,u_)._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:ye(this,iS,IX)}})};return t.addEventListener("click",a,{capture:!0,signal:r}),t.addEventListener("keydown",i=>{i.target===t&&i.key==="Enter"&&(Ut(this,jV,!0),a(i))},{signal:r}),await ts(this,iS,mCe).call(this),t}finish(){ye(this,Dk)&&(ye(this,Dk).focus({focusVisible:ye(this,jV)}),Ut(this,jV,!1))}isEmpty(){return ye(this,r4)?ye(this,ay)===null:!ye(this,ay)&&!ye(this,t4)}hasData(){return ye(this,r4)?ye(this,ay)!==null||!!ye(this,aA):this.isEmpty()}get guessedText(){return ye(this,aA)}async setGuessedText(t){ye(this,ay)===null&&(Ut(this,aA,t),Ut(this,JF,await eb._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer",{generatedAltText:t})),ts(this,iS,mCe).call(this))}toggleAltTextBadge(t=!1){var n;if(!ye(this,r4)||ye(this,ay)){(n=ye(this,n4))==null||n.remove(),Ut(this,n4,null);return}if(!ye(this,n4)){const r=Ut(this,n4,document.createElement("div"));r.className="noAltTextBadge",ye(this,u_).div.append(r)}ye(this,n4).classList.toggle("hidden",!t)}serialize(t){let n=ye(this,ay);return!t&&ye(this,aA)===n&&(n=ye(this,JF)),{altText:n,decorative:ye(this,t4),guessedText:ye(this,aA),textWithDisclaimer:ye(this,JF)}}get data(){return{altText:ye(this,ay),decorative:ye(this,t4)}}set data({altText:t,decorative:n,guessedText:r,textWithDisclaimer:a,cancel:i=!1}){r&&(Ut(this,aA,r),Ut(this,JF,a)),!(ye(this,ay)===t&&ye(this,t4)===n)&&(i||(Ut(this,ay,t),Ut(this,t4,n)),ts(this,iS,mCe).call(this))}toggle(t=!1){ye(this,Dk)&&(!t&&ye(this,Iw)&&(clearTimeout(ye(this,Iw)),Ut(this,Iw,null)),ye(this,Dk).disabled=!t)}shown(){ye(this,u_)._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:ye(this,iS,IX)}})}destroy(){var t,n;(t=ye(this,Dk))==null||t.remove(),Ut(this,Dk,null),Ut(this,wV,null),Ut(this,s4,null),(n=ye(this,n4))==null||n.remove(),Ut(this,n4,null)}};ay=new WeakMap,t4=new WeakMap,Dk=new WeakMap,wV=new WeakMap,s4=new WeakMap,Iw=new WeakMap,jV=new WeakMap,n4=new WeakMap,u_=new WeakMap,aA=new WeakMap,JF=new WeakMap,r4=new WeakMap,X6=new WeakMap,iS=new WeakSet,IX=function(){return ye(this,ay)&&"added"||ye(this,ay)===null&&this.guessedText&&"review"||"missing"},mCe=async function(){var a,i,l;const t=ye(this,Dk);if(!t)return;if(ye(this,r4)){if(t.classList.toggle("done",!!ye(this,ay)),t.setAttribute("data-l10n-id",ye(eb,X6)[ye(this,iS,IX)]),(a=ye(this,wV))==null||a.setAttribute("data-l10n-id",ye(eb,X6)[`${ye(this,iS,IX)}-label`]),!ye(this,ay)){(i=ye(this,s4))==null||i.remove();return}}else{if(!ye(this,ay)&&!ye(this,t4)){t.classList.remove("done"),(l=ye(this,s4))==null||l.remove();return}t.classList.add("done"),t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-edit-button")}let n=ye(this,s4);if(!n){Ut(this,s4,n=document.createElement("span")),n.className="tooltip",n.setAttribute("role","tooltip"),n.id=`alt-text-tooltip-${ye(this,u_).id}`;const o=100,c=ye(this,u_)._uiManager._signal;c.addEventListener("abort",()=>{clearTimeout(ye(this,Iw)),Ut(this,Iw,null)},{once:!0}),t.addEventListener("mouseenter",()=>{Ut(this,Iw,setTimeout(()=>{Ut(this,Iw,null),ye(this,s4).classList.add("show"),ye(this,u_)._reportTelemetry({action:"alt_text_tooltip"})},o))},{signal:c}),t.addEventListener("mouseleave",()=>{var d;ye(this,Iw)&&(clearTimeout(ye(this,Iw)),Ut(this,Iw,null)),(d=ye(this,s4))==null||d.classList.remove("show")},{signal:c})}ye(this,t4)?n.setAttribute("data-l10n-id","pdfjs-editor-alt-text-decorative-tooltip"):(n.removeAttribute("data-l10n-id"),n.textContent=ye(this,ay)),n.parentNode||t.append(n);const r=ye(this,u_).getImageForAltText();r==null||r.setAttribute("aria-describedby",n.id)},us(eb,X6,null),Pr(eb,"_l10n",null);let t6e=eb;var eO,Rk,wf,NV,tO,ev,sO,Q6,fne,nO,J6,xne,rO,iA,a4,kV,SV,I2,gne,W6e,id,vKe,yne,bKe,_Ke,QJt,JJt,wKe,jKe,NKe,ees,kKe,tes,ses,nes,SKe,DX;const _h=class _h{constructor(t){us(this,id);us(this,eO,null);us(this,Rk,null);us(this,wf,null);us(this,NV,!1);us(this,tO,!1);us(this,ev,null);us(this,sO,null);us(this,Q6,null);us(this,fne,"");us(this,nO,!1);us(this,J6,null);us(this,xne,!1);us(this,rO,!1);us(this,iA,!1);us(this,a4,null);us(this,kV,0);us(this,SV,0);us(this,I2,null);Pr(this,"_editToolbar",null);Pr(this,"_initialOptions",Object.create(null));Pr(this,"_initialData",null);Pr(this,"_isVisible",!0);Pr(this,"_uiManager",null);Pr(this,"_focusEventsAllowed",!0);us(this,gne,!1);us(this,W6e,_h._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=_h.prototype._resizeWithKeyboard,n=N9.TRANSLATE_SMALL,r=N9.TRANSLATE_BIG;return fu(this,"_resizerKeyboardManager",new Qae([[["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"],_h.prototype._stopResizingWithKeyboard]]))}get editorType(){return Object.getPrototypeOf(this).constructor._type}static get _defaultLineColor(){return fu(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(t){const n=new sVn({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(_h._l10n??(_h._l10n=t),_h._l10nResizer||(_h._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"})),_h._borderLineWidth!==-1)return;const r=getComputedStyle(document.documentElement);_h._borderLineWidth=parseFloat(r.getPropertyValue("--outline-width"))||0}static updateDefaultParams(t,n){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(t){return!1}static paste(t,n){Sp("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return ye(this,gne)}set _isDraggable(t){var n;Ut(this,gne,t),(n=this.div)==null||n.classList.toggle("draggable",t)}get isEnterHandled(){return!0}center(){const[t,n]=this.pageDimensions;switch(this.parentRotation){case 90:this.x-=this.height*n/(t*2),this.y+=this.width*t/(n*2);break;case 180:this.x+=this.width/2,this.y+=this.height/2;break;case 270:this.x+=this.height*n/(t*2),this.y-=this.width*t/(n*2);break;default:this.x-=this.width/2,this.y-=this.height/2;break}this.fixAndSetPosition()}addCommands(t){this._uiManager.addCommands(t)}get currentLayer(){return this._uiManager.currentLayer}setInBackground(){this.div.style.zIndex=0}setInForeground(){this.div.style.zIndex=ye(this,W6e)}setParent(t){t!==null?(this.pageIndex=t.pageIndex,this.pageDimensions=t.pageDimensions):ts(this,id,DX).call(this),this.parent=t}focusin(t){this._focusEventsAllowed&&(ye(this,nO)?Ut(this,nO,!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){ts(this,id,vKe).call(this,this.parentDimensions,t,n)}translateInPage(t,n){ye(this,J6)||Ut(this,J6,[this.x,this.y]),ts(this,id,vKe).call(this,this.pageDimensions,t,n),this.div.scrollIntoView({block:"nearest"})}drag(t,n){ye(this,J6)||Ut(this,J6,[this.x,this.y]);const[r,a]=this.parentDimensions;if(this.x+=t/r,this.y+=n/a,this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){const{x:d,y:u}=this.div.getBoundingClientRect();this.parent.findNewParent(this,d,u)&&(this.x-=Math.floor(this.x),this.y-=Math.floor(this.y))}let{x:i,y:l}=this;const[o,c]=this.getBaseTranslation();i+=o,l+=c,this.div.style.left=`${(100*i).toFixed(2)}%`,this.div.style.top=`${(100*l).toFixed(2)}%`,this.div.scrollIntoView({block:"nearest"})}get _hasBeenMoved(){return!!ye(this,J6)&&(ye(this,J6)[0]!==this.x||ye(this,J6)[1]!==this.y)}getBaseTranslation(){const[t,n]=this.parentDimensions,{_borderLineWidth:r}=_h,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 ts(r=_h,yne,bKe).call(r,t,n,this.parentRotation)}pageTranslationToScreen(t,n){var r;return ts(r=_h,yne,bKe).call(r,t,n,360-this.parentRotation)}get parentScale(){return this._uiManager.viewParameters.realScale}get parentRotation(){return(this._uiManager.viewParameters.rotation+this.pageRotation)%360}get parentDimensions(){const{parentScale:t,pageDimensions:[n,r]}=this;return[n*t,r*t]}setDims(t,n){const[r,a]=this.parentDimensions;this.div.style.width=`${(100*t/r).toFixed(2)}%`,ye(this,tO)||(this.div.style.height=`${(100*n/a).toFixed(2)}%`)}fixDims(){const{style:t}=this.div,{height:n,width:r}=t,a=r.endsWith("%"),i=!ye(this,tO)&&n.endsWith("%");if(a&&i)return;const[l,o]=this.parentDimensions;a||(t.width=`${(100*parseFloat(r)/l).toFixed(2)}%`),!ye(this,tO)&&!i&&(t.height=`${(100*parseFloat(n)/o).toFixed(2)}%`)}getInitialTranslation(){return[0,0]}altTextFinish(){var t;(t=ye(this,wf))==null||t.finish()}async addEditToolbar(){return this._editToolbar||ye(this,rO)?this._editToolbar:(this._editToolbar=new cKe(this),this.div.append(this._editToolbar.render()),ye(this,wf)&&await this._editToolbar.addAltText(ye(this,wf)),this._editToolbar)}removeEditToolbar(){var t;this._editToolbar&&(this._editToolbar.remove(),this._editToolbar=null,(t=ye(this,wf))==null||t.destroy())}addContainer(t){var r;const n=(r=this._editToolbar)==null?void 0:r.div;n?n.before(t):this.div.append(t)}getClientDimensions(){return this.div.getBoundingClientRect()}async addAltTextButton(){ye(this,wf)||(t6e.initialize(_h._l10n),Ut(this,wf,new t6e(this)),ye(this,eO)&&(ye(this,wf).data=ye(this,eO),Ut(this,eO,null)),await this.addEditToolbar())}get altTextData(){var t;return(t=ye(this,wf))==null?void 0:t.data}set altTextData(t){ye(this,wf)&&(ye(this,wf).data=t)}get guessedAltText(){var t;return(t=ye(this,wf))==null?void 0:t.guessedText}async setGuessedAltText(t){var n;await((n=ye(this,wf))==null?void 0:n.setGuessedText(t))}serializeAltText(t){var n;return(n=ye(this,wf))==null?void 0:n.serialize(t)}hasAltText(){return!!ye(this,wf)&&!ye(this,wf).isEmpty()}hasAltTextData(){var t;return((t=ye(this,wf))==null?void 0:t.hasData())??!1}render(){this.div=document.createElement("div"),this.div.setAttribute("data-editor-rotation",(360-this.rotation)%360),this.div.className=this.name,this.div.setAttribute("id",this.id),this.div.tabIndex=ye(this,NV)?-1:0,this._isVisible||this.div.classList.add("hidden"),this.setInForeground(),ts(this,id,kKe).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),e6e(this,this.div,["pointerdown"]),this.div}pointerdown(t){const{isMac:n}=kb.platform;if(t.button!==0||t.ctrlKey&&n){t.preventDefault();return}if(Ut(this,nO,!0),this._isDraggable){ts(this,id,ees).call(this,t);return}ts(this,id,NKe).call(this,t)}get isSelected(){return this._uiManager.isSelected(this)}moveInDOM(){ye(this,a4)&&clearTimeout(ye(this,a4)),Ut(this,a4,setTimeout(()=>{var t;Ut(this,a4,null),(t=this.parent)==null||t.moveEditorInDOM(this)},0))}_setParentAndPosition(t,n,r){t.changeParent(this),this.x=n,this.y=r,this.fixAndSetPosition()}getRect(t,n,r=this.rotation){const a=this.parentScale,[i,l]=this.pageDimensions,[o,c]=this.pageTranslation,d=t/a,u=n/a,h=this.x*i,m=this.y*l,p=this.width*i,f=this.height*l;switch(r){case 0:return[h+d+o,l-m-u-f+c,h+d+p+o,l-m-u+c];case 90:return[h+u+o,l-m+d+c,h+u+f+o,l-m+d+p+c];case 180:return[h-d-p+o,l-m+u+c,h-d+o,l-m+u+f+c];case 270:return[h-u-f+o,l-m-d-p+c,h-u+o,l-m-d+c];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(t,n){const[r,a,i,l]=t,o=i-r,c=l-a;switch(this.rotation){case 0:return[r,n-l,o,c];case 90:return[r,n-a,c,o];case 180:return[i,n-a,o,c];case 270:return[i,n-l,c,o];default:throw new Error("Invalid rotation")}}onceAdded(){}isEmpty(){return!1}enableEditMode(){Ut(this,rO,!0)}disableEditMode(){Ut(this,rO,!1)}isInEditMode(){return ye(this,rO)}shouldGetKeyboardEvents(){return ye(this,iA)}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}rebuild(){ts(this,id,kKe).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){Sp("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,Ut(a,eO,t.accessibilityData);const[i,l]=a.pageDimensions,[o,c,d,u]=a.getRectInCurrentCoords(t.rect,l);return a.x=o/i,a.y=c/l,a.width=d/i,a.height=u/l,a}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||this.serialize()!==null)}remove(){var t;if((t=ye(this,Q6))==null||t.abort(),Ut(this,Q6,null),this.isEmpty()||this.commit(),this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),ye(this,a4)&&(clearTimeout(ye(this,a4)),Ut(this,a4,null)),ts(this,id,DX).call(this),this.removeEditToolbar(),ye(this,I2)){for(const n of ye(this,I2).values())clearTimeout(n);Ut(this,I2,null)}this.parent=null}get isResizable(){return!1}makeResizable(){this.isResizable&&(ts(this,id,QJt).call(this),ye(this,ev).classList.remove("hidden"),e6e(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),Ut(this,sO,{savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height});const n=ye(this,ev).children;if(!ye(this,Rk)){Ut(this,Rk,Array.from(n));const l=ts(this,id,tes).bind(this),o=ts(this,id,ses).bind(this),c=this._uiManager._signal;for(const d of ye(this,Rk)){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",ts(this,id,nes).bind(this,u),{signal:c}),d.setAttribute("data-l10n-id",_h._l10nResizer[u])}}const r=ye(this,Rk)[0];let a=0;for(const l of n){if(l===r)break;a++}const i=(360-this.rotation+this.parentRotation)%360/90*(ye(this,Rk).length/4);if(i!==a){if(ia)for(let o=0;o{var a,i;(a=this.div)!=null&&a.classList.contains("selectedEditor")&&((i=this._editToolbar)==null||i.show())});return}(n=this._editToolbar)==null||n.show(),(r=ye(this,wf))==null||r.toggleAltTextBadge(!1)}unselect(){var t,n,r,a,i;(t=ye(this,ev))==null||t.classList.add("hidden"),(n=this.div)==null||n.classList.remove("selectedEditor"),(r=this.div)!=null&&r.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0}),(a=this._editToolbar)==null||a.hide(),(i=ye(this,wf))==null||i.toggleAltTextBadge(!0)}updateParams(t,n){}disableEditing(){}enableEditing(){}enterInEditMode(){}getImageForAltText(){return null}get contentDiv(){return this.div}get isEditing(){return ye(this,xne)}set isEditing(t){Ut(this,xne,t),this.parent&&(t?(this.parent.setSelected(this),this.parent.setActiveEditor(this)):this.parent.setActiveEditor(null))}setAspectRatio(t,n){Ut(this,tO,!0);const r=t/n,{style:a}=this.div;a.aspectRatio=r,a.height="auto"}static get MIN_SIZE(){return 16}static canCreateNewEmptyEditor(){return!0}get telemetryInitialData(){return{action:"added"}}get telemetryFinalData(){return null}_reportTelemetry(t,n=!1){if(n){ye(this,I2)||Ut(this,I2,new Map);const{action:r}=t;let a=ye(this,I2).get(r);a&&clearTimeout(a),a=setTimeout(()=>{this._reportTelemetry(t),ye(this,I2).delete(r),ye(this,I2).size===0&&Ut(this,I2,null)},_h._telemetryTimeout),ye(this,I2).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),Ut(this,NV,!1)}disable(){this.div&&(this.div.tabIndex=-1),Ut(this,NV,!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()}};eO=new WeakMap,Rk=new WeakMap,wf=new WeakMap,NV=new WeakMap,tO=new WeakMap,ev=new WeakMap,sO=new WeakMap,Q6=new WeakMap,fne=new WeakMap,nO=new WeakMap,J6=new WeakMap,xne=new WeakMap,rO=new WeakMap,iA=new WeakMap,a4=new WeakMap,kV=new WeakMap,SV=new WeakMap,I2=new WeakMap,gne=new WeakMap,W6e=new WeakMap,id=new WeakSet,vKe=function([t,n],r,a){[r,a]=this.screenToPageTranslation(r,a),this.x+=r/t,this.y+=a/n,this.fixAndSetPosition()},yne=new WeakSet,bKe=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]}},_Ke=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]}},QJt=function(){if(ye(this,ev))return;Ut(this,ev,document.createElement("div")),ye(this,ev).classList.add("resizers");const t=this._willKeepAspectRatio?["topLeft","topRight","bottomRight","bottomLeft"]:["topLeft","topMiddle","topRight","middleRight","bottomRight","bottomMiddle","bottomLeft","middleLeft"],n=this._uiManager._signal;for(const r of t){const a=document.createElement("div");ye(this,ev).append(a),a.classList.add("resizer",r),a.setAttribute("data-resizer-name",r),a.addEventListener("pointerdown",ts(this,id,JJt).bind(this,r),{signal:n}),a.addEventListener("contextmenu",PN,{signal:n}),a.tabIndex=-1}this.div.prepend(ye(this,ev))},JJt=function(t,n){var f;n.preventDefault();const{isMac:r}=kb.platform;if(n.button!==0||n.ctrlKey&&r)return;(f=ye(this,wf))==null||f.toggle(!1);const a=this._isDraggable;this._isDraggable=!1;const i=new AbortController,l=this._uiManager.combinedSignal(i);this.parent.togglePointerEvents(!1),window.addEventListener("pointermove",ts(this,id,jKe).bind(this,t),{passive:!0,capture:!0,signal:l}),window.addEventListener("contextmenu",PN,{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 y;i.abort(),this.parent.togglePointerEvents(!0),(y=ye(this,wf))==null||y.toggle(!0),this._isDraggable=a,this.parent.div.style.cursor=h,this.div.style.cursor=m,ts(this,id,wKe).call(this,o,c,d,u)};window.addEventListener("pointerup",p,{signal:l}),window.addEventListener("blur",p,{signal:l})},wKe=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})},jKe=function(t,n){const[r,a]=this.parentDimensions,i=this.x,l=this.y,o=this.width,c=this.height,d=_h.MIN_SIZE/r,u=_h.MIN_SIZE/a,h=Z=>Math.round(Z*1e4)/1e4,m=ts(this,id,_Ke).call(this,this.rotation),p=(Z,ne)=>[m[0]*Z+m[2]*ne,m[1]*Z+m[3]*ne],f=ts(this,id,_Ke).call(this,360-this.rotation),y=(Z,ne)=>[f[0]*Z+f[2]*ne,f[1]*Z+f[3]*ne];let v,g,b=!1,j=!1;switch(t){case"topLeft":b=!0,v=(Z,ne)=>[0,0],g=(Z,ne)=>[Z,ne];break;case"topMiddle":v=(Z,ne)=>[Z/2,0],g=(Z,ne)=>[Z/2,ne];break;case"topRight":b=!0,v=(Z,ne)=>[Z,0],g=(Z,ne)=>[0,ne];break;case"middleRight":j=!0,v=(Z,ne)=>[Z,ne/2],g=(Z,ne)=>[0,ne/2];break;case"bottomRight":b=!0,v=(Z,ne)=>[Z,ne],g=(Z,ne)=>[0,0];break;case"bottomMiddle":v=(Z,ne)=>[Z/2,ne],g=(Z,ne)=>[Z/2,0];break;case"bottomLeft":b=!0,v=(Z,ne)=>[0,ne],g=(Z,ne)=>[Z,0];break;case"middleLeft":j=!0,v=(Z,ne)=>[0,ne/2],g=(Z,ne)=>[Z,ne/2];break}const S=v(o,c),C=g(o,c);let E=p(...C);const P=h(i+E[0]),M=h(l+E[1]);let I=1,D=1,[O,V]=this.screenToPageTranslation(n.movementX,n.movementY);if([O,V]=y(O/r,V/a),b){const Z=Math.hypot(o,c);I=D=Math.max(Math.min(Math.hypot(C[0]-S[0]-O,C[1]-S[1]-V)/Z,1/o,1/c),d/o,u/c)}else j?I=Math.max(d,Math.min(1,Math.abs(C[0]-S[0]-O)))/o:D=Math.max(u,Math.min(1,Math.abs(C[1]-S[1]-V)))/c;const G=h(o*I),$=h(c*D);E=p(...g(G,$));const H=P-E[0],Y=M-E[1];this.width=G,this.height=$,this.x=H,this.y=Y,this.setDims(r*G,a*$),this.fixAndSetPosition()},NKe=function(t){const{isMac:n}=kb.platform;t.ctrlKey&&!n||t.shiftKey||t.metaKey&&n?this.parent.toggleSelected(this):this.parent.setSelected(this)},ees=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"),Ut(this,kV,t.clientX),Ut(this,SV,t.clientY);const l=o=>{const{clientX:c,clientY:d}=o,[u,h]=this.screenToPageTranslation(c-ye(this,kV),d-ye(this,SV));Ut(this,kV,c),Ut(this,SV,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"),Ut(this,nO,!1),this._uiManager.endDragSession()||ts(this,id,NKe).call(this,t)};window.addEventListener("pointerup",i,{signal:a}),window.addEventListener("blur",i,{signal:a})},kKe=function(){if(ye(this,Q6)||!this.div)return;Ut(this,Q6,new AbortController);const t=this._uiManager.combinedSignal(ye(this,Q6));this.div.addEventListener("focusin",this.focusin.bind(this),{signal:t}),this.div.addEventListener("focusout",this.focusout.bind(this),{signal:t})},tes=function(t){_h._resizerKeyboardManager.exec(this,t)},ses=function(t){var n;ye(this,iA)&&((n=t.relatedTarget)==null?void 0:n.parentNode)!==ye(this,ev)&&ts(this,id,DX).call(this)},nes=function(t){Ut(this,fne,ye(this,iA)?t:"")},SKe=function(t){if(ye(this,Rk))for(const n of ye(this,Rk))n.tabIndex=t},DX=function(){if(Ut(this,iA,!1),ts(this,id,SKe).call(this,-1),ye(this,sO)){const{savedX:t,savedY:n,savedWidth:r,savedHeight:a}=ye(this,sO);ts(this,id,wKe).call(this,t,n,r,a),Ut(this,sO,null)}},us(_h,yne),Pr(_h,"_l10n",null),Pr(_h,"_l10nResizer",null),Pr(_h,"_borderLineWidth",-1),Pr(_h,"_colorManager",new hKe),Pr(_h,"_zIndex",1),Pr(_h,"_telemetryTimeout",1e3);let Oh=_h;class sVn extends Oh{constructor(t){super(t),this.annotationElementId=t.annotationElementId,this.deleted=!0}serialize(){return this.serializeDeleted()}}const cSt=3285377520,w2=4294901760,k5=65535;class res{constructor(t){this.h1=t?t&4294967295:cSt,this.h2=t?t&4294967295:cSt}update(t){let n,r;if(typeof t=="string"){n=new Uint8Array(t.length*2),r=0;for(let y=0,v=t.length;y>>8,n[r++]=g&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&k5,f=m&k5;for(let y=0;y>>17,o=o*m&w2|o*f&k5,d^=o,d=d<<13|d>>>19,d=d*5+3864292196):(c=l[y],c=c*h&w2|c*p&k5,c=c<<15|c>>>17,c=c*m&w2|c*f&k5,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&w2|o*p&k5,o=o<<15|o>>>17,o=o*m&w2|o*f&k5,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&w2|t*36045&k5,n=n*4283543511&w2|((n<<16|t>>>16)*2950163797&w2)>>>16,t^=n>>>1,t=t*444984403&w2|t*60499&k5,n=n*3301882366&w2|((n<<16|t>>>16)*3120437893&w2)>>>16,t^=n>>>1,(t>>>0).toString(16).padStart(8,"0")+(n>>>0).toString(16).padStart(8,"0")}}const CKe=Object.freeze({map:null,hash:"",transfer:void 0});var aO,iO,iy,K6e,aes;class Grt{constructor(){us(this,K6e);us(this,aO,!1);us(this,iO,null);us(this,iy,new Map);this.onSetModified=null,this.onResetModified=null,this.onAnnotationEditor=null}getValue(t,n){const r=ye(this,iy).get(t);return r===void 0?n:Object.assign(n,r)}getRawValue(t){return ye(this,iy).get(t)}remove(t){if(ye(this,iy).delete(t),ye(this,iy).size===0&&this.resetModified(),typeof this.onAnnotationEditor=="function"){for(const n of ye(this,iy).values())if(n instanceof Oh)return;this.onAnnotationEditor(null)}}setValue(t,n){const r=ye(this,iy).get(t);let a=!1;if(r!==void 0)for(const[i,l]of Object.entries(n))r[i]!==l&&(a=!0,r[i]=l);else a=!0,ye(this,iy).set(t,n);a&&ts(this,K6e,aes).call(this),n instanceof Oh&&typeof this.onAnnotationEditor=="function"&&this.onAnnotationEditor(n.constructor._type)}has(t){return ye(this,iy).has(t)}getAll(){return ye(this,iy).size>0?Brt(ye(this,iy)):null}setAll(t){for(const[n,r]of Object.entries(t))this.setValue(n,r)}get size(){return ye(this,iy).size}resetModified(){ye(this,aO)&&(Ut(this,aO,!1),typeof this.onResetModified=="function"&&this.onResetModified())}get print(){return new ies(this)}get serializable(){if(ye(this,iy).size===0)return CKe;const t=new Map,n=new res,r=[],a=Object.create(null);let i=!1;for(const[l,o]of ye(this,iy)){const c=o instanceof Oh?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}:CKe}get editorStats(){let t=null;const n=new Map;for(const r of ye(this,iy).values()){if(!(r instanceof Oh))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(){Ut(this,iO,null)}get modifiedIds(){if(ye(this,iO))return ye(this,iO);const t=[];for(const n of ye(this,iy).values())!(n instanceof Oh)||!n.annotationElementId||!n.serialize()||t.push(n.annotationElementId);return Ut(this,iO,{ids:new Set(t),hash:t.join(",")})}}aO=new WeakMap,iO=new WeakMap,iy=new WeakMap,K6e=new WeakSet,aes=function(){ye(this,aO)||(Ut(this,aO,!0),typeof this.onSetModified=="function"&&this.onSetModified())};var vne;class ies extends Grt{constructor(n){super();us(this,vne);const{map:r,hash:a,transfer:i}=n.serializable,l=structuredClone(r,i?{transfer:i}:null);Ut(this,vne,{map:l,hash:a,transfer:i})}get print(){Sp("Should not call PrintAnnotationStorage.print")}get serializable(){return ye(this,vne)}get modifiedIds(){return fu(this,"modifiedIds",{ids:new Set,hash:""})}}vne=new WeakMap;var CV;class nVn{constructor({ownerDocument:t=globalThis.document,styleElement:n=null}){us(this,CV,new Set);this._document=t,this.nativeFontFaces=new Set,this.styleElement=null,this.loadingRequests=[],this.loadTestFontId=0}addNativeFontFace(t){this.nativeFontFaces.add(t),this._document.fonts.add(t)}removeNativeFontFace(t){this.nativeFontFaces.delete(t),this._document.fonts.delete(t)}insertRule(t){this.styleElement||(this.styleElement=this._document.createElement("style"),this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement));const n=this.styleElement.sheet;n.insertRule(t,n.cssRules.length)}clear(){for(const t of this.nativeFontFaces)this._document.fonts.delete(t);this.nativeFontFaces.clear(),ye(this,CV).clear(),this.styleElement&&(this.styleElement.remove(),this.styleElement=null)}async loadSystemFont({systemFontInfo:t,_inspectFont:n}){if(!(!t||ye(this,CV).has(t.loadedName))){if(b0(!this.disableFontFace,"loadSystemFont shouldn't be called when `disableFontFace` is set."),this.isFontLoadingAPISupported){const{loadedName:r,src:a,style:i}=t,l=new FontFace(r,a,i);this.addNativeFontFace(l);try{await l.load(),ye(this,CV).add(r),n==null||n(t)}catch{gd(`Cannot load system font: ${t.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(l)}return}Sp("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 gd(`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 fu(this,"isFontLoadingAPISupported",t)}get isSyncFontLoadingSupported(){let t=!1;return(h1||typeof navigator<"u"&&typeof(navigator==null?void 0:navigator.userAgent)=="string"&&/Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent))&&(t=!0),fu(this,"isSyncFontLoadingSupported",t)}_queueLoadingCallback(t){function n(){for(b0(!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 fu(this,"_loadTestFont",t)}_prepareFontLoadEvent(t,n){function r(S,C){return S.charCodeAt(C)<<24|S.charCodeAt(C+1)<<16|S.charCodeAt(C+2)<<8|S.charCodeAt(C+3)&255}function a(S,C,E,P){const M=S.substring(0,C),I=S.substring(C+E);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(S,C){if(++d>30){gd("Load test font never loaded."),C();return}if(c.font="30px "+S,c.fillText(".",0,20),c.getImageData(0,0,1,1).data[3]>0){C();return}setTimeout(u.bind(null,S,C))}const h=`lt${Date.now()}${this.loadTestFontId++}`;let m=this._loadTestFont;m=a(m,976,h.length,h);const f=16,y=1482184792;let v=r(m,f);for(i=0,l=h.length-3;i{j.remove(),n.complete()})}}CV=new WeakMap;class rVn{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,${W$n(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){gd(`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 j3.MOVE_TO:{const[o,c]=r.slice(i,i+2);a.push(d=>d.moveTo(o,c)),i+=2}break;case j3.LINE_TO:{const[o,c]=r.slice(i,i+2);a.push(d=>d.lineTo(o,c)),i+=2}break;case j3.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 j3.RESTORE:a.push(o=>o.restore());break;case j3.SAVE:a.push(o=>o.save());break;case j3.SCALE:b0(a.length===2,"Scale command is only valid at the third position.");break;case j3.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 j3.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){Sp("Abstract method `_fetch` called.")}}class ces extends les{async _fetch(t){const n=await T8e(t,this.isCompressed?"arraybuffer":"text");return n instanceof ArrayBuffer?new Uint8Array(n):E8e(n)}}class des{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 oO,lO,i4,oA,s1,Y6e,cO,co,Jv,kU,SU,pCe,CU,ues,AKe,AU,RX,FX,EKe,OX;class iVn extends des{constructor({docId:n,ownerDocument:r=globalThis.document}){super();us(this,co);us(this,oO);us(this,lO);us(this,i4);us(this,oA);us(this,s1);us(this,Y6e);us(this,cO,0);Ut(this,oA,n),Ut(this,s1,r)}addFilter(n){if(!n)return"none";let r=ye(this,co,Jv).get(n);if(r)return r;const[a,i,l]=ts(this,co,pCe).call(this,n),o=n.length===1?a:`${a}${i}${l}`;if(r=ye(this,co,Jv).get(o),r)return ye(this,co,Jv).set(n,r),r;const c=`g_${ye(this,oA)}_transfer_map_${X0(this,cO)._++}`,d=ts(this,co,CU).call(this,c);ye(this,co,Jv).set(n,d),ye(this,co,Jv).set(o,d);const u=ts(this,co,AU).call(this,c);return ts(this,co,FX).call(this,a,i,l,u),d}addHCMFilter(n,r){var f;const a=`${n}-${r}`,i="base";let l=ye(this,co,kU).get(i);if((l==null?void 0:l.key)===a||(l?((f=l.filter)==null||f.remove(),l.key=a,l.url="none",l.filter=null):(l={key:a,url:"none",filter:null},ye(this,co,kU).set(i,l)),!n||!r))return l.url;const o=ts(this,co,OX).call(this,n);n=qo.makeHexColor(...o);const c=ts(this,co,OX).call(this,r);if(r=qo.makeHexColor(...c),ye(this,co,SU).style.color="",n==="#000000"&&r==="#ffffff"||n===r)return l.url;const d=new Array(256);for(let y=0;y<=255;y++){const v=y/255;d[y]=v<=.03928?v/12.92:((v+.055)/1.055)**2.4}const u=d.join(","),h=`g_${ye(this,oA)}_hcm_filter`,m=l.filter=ts(this,co,AU).call(this,h);ts(this,co,FX).call(this,u,u,u,m),ts(this,co,AKe).call(this,m);const p=(y,v)=>{const g=o[y]/255,b=c[y]/255,j=new Array(v+1);for(let S=0;S<=v;S++)j[S]=g+S/v*(b-g);return j.join(",")};return ts(this,co,FX).call(this,p(0,5),p(1,5),p(2,5),m),l.url=ts(this,co,CU).call(this,h),l.url}addAlphaFilter(n){let r=ye(this,co,Jv).get(n);if(r)return r;const[a]=ts(this,co,pCe).call(this,[n]),i=`alpha_${a}`;if(r=ye(this,co,Jv).get(i),r)return ye(this,co,Jv).set(n,r),r;const l=`g_${ye(this,oA)}_alpha_map_${X0(this,cO)._++}`,o=ts(this,co,CU).call(this,l);ye(this,co,Jv).set(n,o),ye(this,co,Jv).set(i,o);const c=ts(this,co,AU).call(this,l);return ts(this,co,EKe).call(this,a,c),o}addLuminosityFilter(n){let r=ye(this,co,Jv).get(n||"luminosity");if(r)return r;let a,i;if(n?([a]=ts(this,co,pCe).call(this,[n]),i=`luminosity_${a}`):i="luminosity",r=ye(this,co,Jv).get(i),r)return ye(this,co,Jv).set(n,r),r;const l=`g_${ye(this,oA)}_luminosity_map_${X0(this,cO)._++}`,o=ts(this,co,CU).call(this,l);ye(this,co,Jv).set(n,o),ye(this,co,Jv).set(i,o);const c=ts(this,co,AU).call(this,l);return ts(this,co,ues).call(this,c),n&&ts(this,co,EKe).call(this,a,c),o}addHighlightHCMFilter(n,r,a,i,l){var b;const o=`${r}-${a}-${i}-${l}`;let c=ye(this,co,kU).get(n);if((c==null?void 0:c.key)===o||(c?((b=c.filter)==null||b.remove(),c.key=o,c.url="none",c.filter=null):(c={key:o,url:"none",filter:null},ye(this,co,kU).set(n,c)),!r||!a))return c.url;const[d,u]=[r,a].map(ts(this,co,OX).bind(this));let h=Math.round(.2126*d[0]+.7152*d[1]+.0722*d[2]),m=Math.round(.2126*u[0]+.7152*u[1]+.0722*u[2]),[p,f]=[i,l].map(ts(this,co,OX).bind(this));m{const E=new Array(256),P=(m-h)/C,M=j/255,I=(S-j)/(255*C);let D=0;for(let O=0;O<=C;O++){const V=Math.round(h+O*P),G=M+O*I;for(let $=D;$<=V;$++)E[$]=G;D=V+1}for(let O=D;O<256;O++)E[O]=E[D-1];return E.join(",")},v=`g_${ye(this,oA)}_hcm_${n}_filter`,g=c.filter=ts(this,co,AU).call(this,v);return ts(this,co,AKe).call(this,g),ts(this,co,FX).call(this,y(p[0],f[0],5),y(p[1],f[1],5),y(p[2],f[2],5),g),c.url=ts(this,co,CU).call(this,v),c.url}destroy(n=!1){n&&ye(this,co,kU).size!==0||(ye(this,i4)&&(ye(this,i4).parentNode.parentNode.remove(),Ut(this,i4,null)),ye(this,lO)&&(ye(this,lO).clear(),Ut(this,lO,null)),Ut(this,cO,0))}}oO=new WeakMap,lO=new WeakMap,i4=new WeakMap,oA=new WeakMap,s1=new WeakMap,Y6e=new WeakMap,cO=new WeakMap,co=new WeakSet,Jv=function(){return ye(this,lO)||Ut(this,lO,new Map)},kU=function(){return ye(this,Y6e)||Ut(this,Y6e,new Map)},SU=function(){if(!ye(this,i4)){const n=ye(this,s1).createElement("div"),{style:r}=n;r.visibility="hidden",r.contain="strict",r.width=r.height=0,r.position="absolute",r.top=r.left=0,r.zIndex=-1;const a=ye(this,s1).createElementNS(D3,"svg");a.setAttribute("width",0),a.setAttribute("height",0),Ut(this,i4,ye(this,s1).createElementNS(D3,"defs")),n.append(a),a.append(ye(this,i4)),ye(this,s1).body.append(n)}return ye(this,i4)},pCe=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(",")]},CU=function(n){if(ye(this,oO)===void 0){Ut(this,oO,"");const r=ye(this,s1).URL;r!==ye(this,s1).baseURI&&(M8e(r)?gd('#createUrl: ignore "data:"-URL for performance reasons.'):Ut(this,oO,r.split("#",1)[0]))}return`url(${ye(this,oO)}#${n})`},ues=function(n){const r=ye(this,s1).createElementNS(D3,"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)},AKe=function(n){const r=ye(this,s1).createElementNS(D3,"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)},AU=function(n){const r=ye(this,s1).createElementNS(D3,"filter");return r.setAttribute("color-interpolation-filters","sRGB"),r.setAttribute("id",n),ye(this,co,SU).append(r),r},RX=function(n,r,a){const i=ye(this,s1).createElementNS(D3,r);i.setAttribute("type","discrete"),i.setAttribute("tableValues",a),n.append(i)},FX=function(n,r,a,i){const l=ye(this,s1).createElementNS(D3,"feComponentTransfer");i.append(l),ts(this,co,RX).call(this,l,"feFuncR",n),ts(this,co,RX).call(this,l,"feFuncG",r),ts(this,co,RX).call(this,l,"feFuncB",a)},EKe=function(n,r){const a=ye(this,s1).createElementNS(D3,"feComponentTransfer");r.append(a),ts(this,co,RX).call(this,a,"feFuncA",n)},OX=function(n){return ye(this,co,SU).style.color=n,Hrt(getComputedStyle(ye(this,co,SU)).getPropertyValue("color"))};class hes{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){Sp("Abstract method `_fetch` called.")}}class mes extends hes{async _fetch(t){const n=await T8e(t,"arraybuffer");return new Uint8Array(n)}}if(h1){var TKe=Promise.withResolvers(),dee=null;(async()=>{const t=await za(()=>import("./__vite-browser-external-BIHI7g3E.js"),[]),n=await za(()=>import("./__vite-browser-external-BIHI7g3E.js"),[]),r=await za(()=>import("./__vite-browser-external-BIHI7g3E.js"),[]),a=await za(()=>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=>{dee=t,TKe.resolve()},t=>{gd(`loadPackages: ${t}`),dee=new Map,TKe.resolve()})}class GP{static get promise(){return TKe.promise}static get(t){return dee==null?void 0:dee.get(t)}}async function pes(s){const n=await GP.get("fs").promises.readFile(s);return new Uint8Array(n)}class oVn extends des{}class lVn extends oes{_createCanvas(t,n){return GP.get("canvas").createCanvas(t,n)}}class cVn extends les{async _fetch(t){return pes(t)}}class dVn extends hes{async _fetch(t){return pes(t)}}const cb={FILL:"Fill",STROKE:"Stroke",SHADING:"Shading"};function MKe(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 Wrt{getPattern(){Sp("Abstract method `getPattern` called.")}}class uVn extends Wrt{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===cb.STROKE||a===cb.FILL){const l=n.current.getClippedPathBoundingBox(a,Nf(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=qo.transform(r,[1,0,0,1,l[0],l[1]]),u.transform(...n.baseTransform),this.matrix&&u.transform(...this.matrix),MKe(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 MKe(t,this._bbox),i=this._createGradient(t);return i}}function Kze(s,t,n,r,a,i,l,o){const c=t.coords,d=t.colors,u=s.data,h=s.width*4;let m;c[n+1]>c[r+1]&&(m=n,n=r,r=m,m=i,i=l,l=m),c[r+1]>c[a+1]&&(m=r,r=a,a=m,m=l,l=o,o=m),c[n+1]>c[r+1]&&(m=n,n=r,r=m,m=i,i=l,l=m);const p=(c[n]+t.offsetX)*t.scaleX,f=(c[n+1]+t.offsetY)*t.scaleY,y=(c[r]+t.offsetX)*t.scaleX,v=(c[r+1]+t.offsetY)*t.scaleY,g=(c[a]+t.offsetX)*t.scaleX,b=(c[a+1]+t.offsetY)*t.scaleY;if(f>=b)return;const j=d[i],S=d[i+1],C=d[i+2],E=d[l],P=d[l+1],M=d[l+2],I=d[o],D=d[o+1],O=d[o+2],V=Math.round(f),G=Math.round(b);let $,H,Y,Z,ne,ce,ie,te;for(let ae=V;ae<=G;ae++){if(aeb?pe=1:v===b?pe=0:pe=(v-ae)/(v-b),$=y-(y-g)*pe,H=E-(E-I)*pe,Y=P-(P-D)*pe,Z=M-(M-O)*pe}let le;aeb?le=1:le=(f-ae)/(f-b),ne=p-(p-g)*le,ce=j-(j-I)*le,ie=S-(S-D)*le,te=C-(C-O)*le;const be=Math.round(Math.min($,ne)),me=Math.round(Math.max($,ne));let he=h*ae+be*4;for(let pe=be;pe<=me;pe++)le=($-pe)/($-ne),le<0?le=0:le>1&&(le=1),u[he++]=H-(H-ce)*le|0,u[he++]=Y-(Y-ie)*le|0,u[he++]=Z-(Z-te)*le|0,u[he++]=255}}function hVn(s,t,n){const r=t.coords,a=t.colors;let i,l;switch(t.type){case"lattice":const o=t.verticesPerRow,c=Math.floor(r.length/o)-1,d=o-1;for(i=0;i=D?S=c:E=!0,I>=O?C=d:P=!0;const V=this.getSizeAndScale(S,this.ctx.canvas.width,b),G=this.getSizeAndScale(C,this.ctx.canvas.height,j),$=t.cachedCanvases.getCanvas("pattern",V.size,G.size),H=$.context,Y=o.createCanvasGraphics(H);if(Y.groupLevel=t.groupLevel,this.setFillAndStrokeStyleToContext(Y,a,l),H.translate(-V.scale*u,-G.scale*h),Y.transform(V.scale,0,0,G.scale,0,0),H.save(),this.clipBbox(Y,u,h,m,p),Y.baseTransform=Nf(Y.ctx),Y.executeOperatorList(r),Y.endDrawing(),H.restore(),E||P){const Z=$.canvas;E&&(S=c),P&&(C=d);const ne=this.getSizeAndScale(S,this.ctx.canvas.width,b),ce=this.getSizeAndScale(C,this.ctx.canvas.height,j),ie=ne.size,te=ce.size,ae=t.cachedCanvases.getCanvas("pattern-workaround",ie,te),le=ae.context,be=E?Math.floor(f/c):0,me=P?Math.floor(y/d):0;for(let he=0;he<=be;he++)for(let pe=0;pe<=me;pe++)le.drawImage(Z,ie*he,te*pe,ie,te,0,0,ie,te);return{canvas:ae.canvas,scaleX:ne.scale,scaleY:ce.scale,offsetX:u,offsetY:h}}return{canvas:$.canvas,scaleX:V.scale,scaleY:G.scale,offsetX:u,offsetY:h}}getSizeAndScale(t,n,r){const a=Math.max(Z6e.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(Nf(t.ctx),[n,r,a,i]),t.clip(),t.endPath()}setFillAndStrokeStyleToContext(t,n,r){const a=t.ctx,i=t.current;switch(n){case dSt.COLORED:const l=this.ctx;a.fillStyle=l.fillStyle,a.strokeStyle=l.strokeStyle,i.fillColor=l.fillStyle,i.strokeColor=l.strokeStyle;break;case dSt.UNCOLORED:const o=qo.makeHexColor(r[0],r[1],r[2]);a.fillStyle=o,a.strokeStyle=o,i.fillColor=o,i.strokeColor=o;break;default:throw new B$n(`Unsupported paint type: ${n}`)}}getPattern(t,n,r,a){let i=r;a!==cb.SHADING&&(i=qo.transform(i,n.baseTransform),this.matrix&&(i=qo.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}};Pr(Z6e,"MAX_PATTERN_SIZE",3e3);let PKe=Z6e;function xVn({src:s,srcPos:t=0,dest:n,width:r,height:a,nonBlackColor:i=4294967295,inverseDecode:l=!1}){const o=kb.isLittleEndian?4278190080:255,[c,d]=l?[i,o]:[o,i],u=r>>3,h=r&7,m=s.length;n=new Uint32Array(n.buffer);let p=0;for(let f=0;f{s.save=s.__originalSave,s.restore=s.__originalRestore,s.rotate=s.__originalRotate,s.scale=s.__originalScale,s.translate=s.__originalTranslate,s.transform=s.__originalTransform,s.setTransform=s.__originalSetTransform,s.resetTransform=s.__originalResetTransform,s.clip=s.__originalClip,s.moveTo=s.__originalMoveTo,s.lineTo=s.__originalLineTo,s.bezierCurveTo=s.__originalBezierCurveTo,s.rect=s.__originalRect,s.closePath=s.__originalClosePath,s.beginPath=s.__originalBeginPath,delete s._removeMirroring},s.save=function(){t.save(),this.__originalSave()},s.restore=function(){t.restore(),this.__originalRestore()},s.translate=function(r,a){t.translate(r,a),this.__originalTranslate(r,a)},s.scale=function(r,a){t.scale(r,a),this.__originalScale(r,a)},s.transform=function(r,a,i,l,o,c){t.transform(r,a,i,l,o,c),this.__originalTransform(r,a,i,l,o,c)},s.setTransform=function(r,a,i,l,o,c){t.setTransform(r,a,i,l,o,c),this.__originalSetTransform(r,a,i,l,o,c)},s.resetTransform=function(){t.resetTransform(),this.__originalResetTransform()},s.rotate=function(r){t.rotate(r),this.__originalRotate(r)},s.clip=function(r){t.clip(r),this.__originalClip(r)},s.moveTo=function(n,r){t.moveTo(n,r),this.__originalMoveTo(n,r)},s.lineTo=function(n,r){t.lineTo(n,r),this.__originalLineTo(n,r)},s.bezierCurveTo=function(n,r,a,i,l,o){t.bezierCurveTo(n,r,a,i,l,o),this.__originalBezierCurveTo(n,r,a,i,l,o)},s.rect=function(n,r,a,i){t.rect(n,r,a,i),this.__originalRect(n,r,a,i)},s.closePath=function(){t.closePath(),this.__originalClosePath()},s.beginPath=function(){t.beginPath(),this.__originalBeginPath()}}class vVn{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 cde(s,t,n,r,a,i,l,o,c,d){const[u,h,m,p,f,y]=Nf(s);if(h===0&&m===0){const b=l*u+f,j=Math.round(b),S=o*p+y,C=Math.round(S),E=(l+c)*u+f,P=Math.abs(Math.round(E)-j)||1,M=(o+d)*p+y,I=Math.abs(Math.round(M)-C)||1;return s.setTransform(Math.sign(u),0,0,Math.sign(p),j,C),s.drawImage(t,n,r,a,i,0,0,P,I),s.setTransform(u,h,m,p,f,y),[P,I]}if(u===0&&p===0){const b=o*m+f,j=Math.round(b),S=l*h+y,C=Math.round(S),E=(o+d)*m+f,P=Math.abs(Math.round(E)-j)||1,M=(l+c)*h+y,I=Math.abs(Math.round(M)-C)||1;return s.setTransform(0,Math.sign(h),Math.sign(m),0,j,C),s.drawImage(t,n,r,a,i,0,0,I,P),s.setTransform(u,h,m,p,f,y),[I,P]}s.drawImage(t,n,r,a,i,l,o,c,d);const v=Math.hypot(u,h),g=Math.hypot(m,p);return[v*c,g*d]}function bVn(s){const{width:t,height:n}=s;if(t>pSt||n>pSt)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 g of s.data){let b=128;for(;b>0;)h[m++]=g&b?0:255,b>>=1}let p=0;for(m=0,h[m]!==0&&(l[0]=1,++p),c=1;c>2)+(h[m+1]?4:0)+(h[m-u+1]?8:0),a[g]&&(l[d+c]=a[g],++p),m++;if(h[m-u]!==h[m]&&(l[d+c]=h[m]?2:4,++p),p>r)return null}for(m=u*(n-1),d=o*i,h[m]!==0&&(l[d]=8,++p),c=1;cr)return null;const f=new Int32Array([0,i,-1,0,-i,0,0,0,1]),y=new Path2D;for(o=0;p&&o<=n;o++){let g=o*i;const b=g+t;for(;g>4,l[g]&=S>>2|S<<2),y.lineTo(g%i,g/i|0),l[g]||--p}while(j!==g);--o}return h=null,l=null,function(g){g.save(),g.scale(1/t,-1/n),g.translate(0,-n),g.fill(y),g.beginPath(),g.restore()}}class fSt{constructor(t,n){this.alphaIsShape=!1,this.fontSize=0,this.fontSizeScale=1,this.textMatrix=MJt,this.textMatrixScale=1,this.fontMatrix=rKe,this.leading=0,this.x=0,this.y=0,this.lineX=0,this.lineY=0,this.charSpacing=0,this.wordSpacing=0,this.textHScale=1,this.textRenderingMode=Qv.FILL,this.textRise=0,this.fillColor="#000000",this.strokeColor="#000000",this.patternFill=!1,this.fillAlpha=1,this.strokeAlpha=1,this.lineWidth=1,this.activeSMask=null,this.transferMaps="none",this.startNewPathAndClipBox([0,0,t,n])}clone(){const t=Object.create(this);return t.clipBox=this.clipBox.slice(),t}setCurrentPoint(t,n){this.x=t,this.y=n}updatePathMinMax(t,n,r){[n,r]=qo.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=qo.applyTransform(n,t),a=qo.applyTransform(n.slice(2),t),i=qo.applyTransform([n[0],n[3]],t),l=qo.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){qo.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=qo.bezierBoundingBox(n,r,a,i,l,o,c,d,u);u||this.updateRectMinMax(t,h)}getPathBoundingBox(t=cb.FILL,n=null){const r=[this.minX,this.minY,this.maxX,this.maxY];if(t===cb.STROKE){n||Sp("Stroke bounding box must include transform.");const a=qo.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=qo.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=cb.FILL,n=null){return qo.intersect(this.clipBox,this.getPathBoundingBox(t,n))}}function xSt(s,t){if(typeof ImageData<"u"&&t instanceof ImageData){s.putImageData(t,0,0);return}const n=t.height,r=t.width,a=n%x_,i=(n-a)/x_,l=a===0?i:i+1,o=s.createImageData(r,x_);let c=0,d;const u=t.data,h=o.data;let m,p,f,y;if(t.kind===oCe.GRAYSCALE_1BPP){const v=u.byteLength,g=new Uint32Array(h.buffer,0,h.byteLength>>2),b=g.length,j=r+7>>3,S=4294967295,C=kb.isLittleEndian?4278190080:255;for(m=0;mj?r:E*8-7,I=M&-8;let D=0,O=0;for(;P>=1}for(;d=i&&(f=a,y=r*f),d=0,p=y;p--;)h[d++]=u[c++],h[d++]=u[c++],h[d++]=u[c++],h[d++]=255;s.putImageData(o,0,m*x_)}else throw new Error(`bad image kind: ${t.kind}`)}function gSt(s,t){if(t.bitmap){s.drawImage(t.bitmap,0,0);return}const n=t.height,r=t.width,a=n%x_,i=(n-a)/x_,l=a===0?i:i+1,o=s.createImageData(r,x_);let c=0;const d=t.data,u=o.data;for(let h=0;hmSt&&typeof r=="function",u=d?Date.now()+gVn:0;let h=0;const m=this.commonObjs,p=this.objs;let f;for(;;){if(a!==void 0&&o===a.nextBreakPoint)return a.breakIt(o,r),o;if(f=l[o],f!==Ek.dependency)this[f].apply(this,i[o]);else for(const y of i[o]){const v=y.startsWith("g_")?m:p;if(!v.has(y))return v.get(y,r),o}if(o++,o===c)return o;if(d&&++h>mSt){if(Date.now()>u)return r(),o;h=0}}}endDrawing(){ts(this,eL,LKe).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(),ts(this,eL,IKe).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=Nf(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]),O=Math.round(Math.min(o[1],o[3])+o[5]);return{canvas:I,offsetX:D,offsetY:O}}u=I}u||(h=this.cachedCanvases.getCanvas("maskCanvas",r,a),gSt(h.context,t));let m=qo.transform(o,[1/r,0,0,-1/a,0,0]);m=qo.transform(m,[1,0,0,1,0,-a]);const[p,f,y,v]=qo.getAxialAlignedBoundingBox([0,0,r,a],m),g=Math.round(y-p)||1,b=Math.round(v-f)||1,j=this.cachedCanvases.getCanvas("fillCanvas",g,b),S=j.context,C=p,E=f;S.translate(-C,-E),S.transform(...m),u||(u=this._scaleImage(h.canvas,N3(S)),u=u.img,c&&l&&c.set(d,u)),S.imageSmoothingEnabled=ySt(Nf(S),t.interpolate),cde(S,u,0,0,u.width,u.height,0,0,r,a),S.globalCompositeOperation="source-in";const P=qo.transform(N3(S),[1,0,0,1,-C,-E]);return S.fillStyle=l?i.getPattern(n,this,P,cb.FILL):i,S.fillRect(0,0,r,a),c&&!l&&(this.cachedCanvases.delete("fillCanvas"),c.set(d,j.canvas)),{canvas:j.canvas,offsetX:Math.round(C),offsetY:Math.round(E)}}setLineWidth(t){t!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1),this.current.lineWidth=t,this.ctx.lineWidth=t}setLineCap(t){this.ctx.lineCap=_Vn[t]}setLineJoin(t){this.ctx.lineJoin=wVn[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(...Nf(this.suspendedCtx)),_Z(this.suspendedCtx,i),yVn(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(),_Z(this.ctx,this.suspendedCtx),this.ctx=this.suspendedCtx,this.suspendedCtx=null}compose(t){if(!this.current.activeSMask)return;t?(t[0]=Math.floor(t[0]),t[1]=Math.floor(t[1]),t[2]=Math.ceil(t[2]),t[3]=Math.ceil(t[3])):t=[0,0,this.ctx.canvas.width,this.ctx.canvas.height];const n=this.current.activeSMask,r=this.suspendedCtx;this.composeSMask(r,n,this.ctx,t),this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.clearRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height),this.ctx.restore()}composeSMask(t,n,r,a){const i=a[0],l=a[1],o=a[2]-i,c=a[3]-l;o===0||c===0||(this.genericComposeSMask(n.context,r,o,c,n.subtype,n.backdrop,n.transferMap,i,l,n.offsetX,n.offsetY),t.save(),t.globalAlpha=1,t.globalCompositeOperation="source-over",t.setTransform(1,0,0,1,0,0),t.drawImage(r.canvas,0,0),t.restore())}genericComposeSMask(t,n,r,a,i,l,o,c,d,u,h){let m=t.canvas,p=c-u,f=d-h;if(l){const v=qo.makeHexColor(...l);if(p<0||f<0||p+r>m.width||f+a>m.height){const g=this.cachedCanvases.getCanvas("maskExtension",r,a),b=g.context;b.drawImage(m,-p,-f),b.globalCompositeOperation="destination-atop",b.fillStyle=v,b.fillRect(0,0,r,a),b.globalCompositeOperation="source-over",m=g.canvas,p=f=0}else{t.save(),t.globalAlpha=1,t.setTransform(1,0,0,1,0,0);const g=new Path2D;g.rect(p,f,r,a),t.clip(g),t.globalCompositeOperation="destination-atop",t.fillStyle=v,t.fillRect(p,f,r,a),t.restore()}}n.save(),n.globalAlpha=1,n.setTransform(1,0,0,1,0,0),i==="Alpha"&&o?n.filter=this.filterFactory.addAlphaFilter(o):i==="Luminosity"&&(n.filter=this.filterFactory.addLuminosityFilter(o));const y=new Path2D;y.rect(c,d,r,a),n.clip(y),n.globalCompositeOperation="destination-in",n.drawImage(m,p,f,r,a,c,d,r,a),n.restore()}save(){this.inSMaskMode?(_Z(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(),_Z(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=Nf(a),h=u[0]===0&&u[3]===0||u[1]===0&&u[2]===0,m=h?r.slice(0):null;for(let p=0,f=0,y=t.length;phSt&&(d=hSt),this.current.fontSizeScale=n/d,this.ctx.font=`${c} ${o} ${d}px ${l}`}setTextRenderingMode(t){this.current.textRenderingMode=t}setTextRise(t){this.current.textRise=t}moveText(t,n){this.current.x=this.current.lineX+=t,this.current.y=this.current.lineY+=n}setLeadingMoveText(t,n){this.setLeading(-n),this.moveText(t,n)}setTextMatrix(t,n,r,a,i,l){this.current.textMatrix=[t,n,r,a,i,l],this.current.textMatrixScale=Math.hypot(t,n),this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0}nextLine(){this.moveText(0,this.current.leading)}paintChar(t,n,r,a){const i=this.ctx,l=this.current,o=l.font,c=l.textRenderingMode,d=l.fontSize/l.fontSizeScale,u=c&Qv.FILL_STROKE_MASK,h=!!(c&Qv.ADD_TO_PATH_FLAG),m=l.patternFill&&!o.missingFile;let p;(o.disableFontFace||h||m)&&(p=o.getPathGenerator(this.commonObjs,t)),o.disableFontFace||m?(i.save(),i.translate(n,r),i.beginPath(),p(i,d),a&&i.setTransform(...a),(u===Qv.FILL||u===Qv.FILL_STROKE)&&i.fill(),(u===Qv.STROKE||u===Qv.FILL_STROKE)&&i.stroke(),i.restore()):((u===Qv.FILL||u===Qv.FILL_STROKE)&&i.fillText(t,n,r),(u===Qv.STROKE||u===Qv.FILL_STROKE)&&i.strokeText(t,n,r)),h&&(this.pendingTextPaths||(this.pendingTextPaths=[])).push({transform:Nf(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 fu(this,"isFontSubpixelAAEnabled",r)}showText(t){const n=this.current,r=n.font;if(r.isType3Font)return this.showType3Text(t);const a=n.fontSize;if(a===0)return;const i=this.ctx,l=n.fontSizeScale,o=n.charSpacing,c=n.wordSpacing,d=n.fontDirection,u=n.textHScale*d,h=t.length,m=r.vertical,p=m?1:-1,f=r.defaultVMetrics,y=a*n.fontMatrix[0],v=n.textRenderingMode===Qv.FILL&&!r.disableFontFace&&!n.patternFill;i.save(),i.transform(...n.textMatrix),i.translate(n.x,n.y+n.textRise),d>0?i.scale(u,-1):i.scale(u,1);let g;if(n.patternFill){i.save();const E=n.fillColor.getPattern(i,this,N3(i),cb.FILL);g=Nf(i),i.restore(),i.fillStyle=E}let b=n.lineWidth;const j=n.textMatrixScale;if(j===0||b===0){const E=n.textRenderingMode&Qv.FILL_STROKE_MASK;(E===Qv.STROKE||E===Qv.FILL_STROKE)&&(b=this.getSinglePixelWidth())}else b/=j;if(l!==1&&(i.scale(l,l),b/=l),i.lineWidth=b,r.isInvalidPDFjsFont){const E=[];let P=0;for(const M of t)E.push(M.unicode),P+=M.width;i.fillText(E.join(""),0,0),n.x+=P*y*u,i.restore(),this.compose();return}let S=0,C;for(C=0;C0){const H=i.measureText(I).width*1e3/a*l;if(Gnew iot(l,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack})};n=new PKe(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=qo.makeHexColor(t,n,r)}setStrokeTransparent(){this.ctx.strokeStyle=this.current.strokeColor="transparent"}setFillRGBColor(t,n,r){this.ctx.fillStyle=this.current.fillColor=qo.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=fVn(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,N3(n),cb.SHADING);const a=N3(n);if(a){const{width:i,height:l}=n.canvas,[o,c,d,u]=qo.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(){Sp("Should not call beginInlineImage")}beginImageData(){Sp("Should not call beginImageData")}paintFormXObjectBegin(t,n){if(this.contentVisible&&(this.save(),this.baseTransformStack.push(this.baseTransform),t&&this.transform(...t),this.baseTransform=Nf(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(Nf(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||C8e("TODO: Support non-isolated groups."),t.knockout&&gd("Knockout groups not supported.");const r=Nf(n);if(t.matrix&&n.transform(...t.matrix),!t.bbox)throw new Error("Bounding box is required.");let a=qo.getAxialAlignedBoundingBox(t.bbox,Nf(n));const i=[0,0,n.canvas.width,n.canvas.height];a=qo.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()),_Z(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=Nf(this.ctx);this.restore(),this.ctx.save(),this.ctx.setTransform(...a);const i=qo.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(ts(this,eL,LKe).call(this),dde(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]=qo.singularValueDecompose2dScale(Nf(this.ctx)),{viewportScale:u}=this,h=Math.ceil(l*this.outputScaleX*u),m=Math.ceil(o*this.outputScaleY*u);this.annotationCanvas=this.canvasFactory.create(h,m);const{canvas:p,context:f}=this.annotationCanvas;this.annotationCanvasMap.set(t,p),this.annotationCanvas.savedCtx=this.ctx,this.ctx=f,this.ctx.save(),this.ctx.setTransform(c,0,0,-d,0,o*d),dde(this.ctx)}else dde(this.ctx),this.endPath(),this.ctx.rect(n[0],n[1],l,o),this.ctx.clip(),this.ctx.beginPath()}this.current=new fSt(this.ctx.canvas.width,this.ctx.canvas.height),this.transform(...r),this.transform(...a)}endAnnotation(){this.annotationCanvas&&(this.ctx.restore(),ts(this,eL,IKe).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=bVn(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=Nf(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}};eL=new WeakSet,LKe=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)},IKe=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 V$=iot;for(const s in Ek)V$.prototype[s]!==void 0&&(V$.prototype[Ek[s]]=V$.prototype[s]);var _ne,wne;class EA{static get workerPort(){return ye(this,_ne)}static set workerPort(t){if(!(typeof Worker<"u"&&t instanceof Worker)&&t!==null)throw new Error("Invalid `workerPort` type.");Ut(this,_ne,t)}static get workerSrc(){return ye(this,wne)}static set workerSrc(t){if(typeof t!="string")throw new Error("Invalid `workerSrc` type.");Ut(this,wne,t)}}_ne=new WeakMap,wne=new WeakMap,us(EA,_ne,null),us(EA,wne,"");const ude={UNKNOWN:0,DATA:1,ERROR:2},jg={UNKNOWN:0,CANCEL:1,CANCEL_COMPLETE:2,CLOSE:3,ENQUEUE:4,ERROR:5,PULL:6,PULL_COMPLETE:7,START_COMPLETE:8};function ww(s){switch(s instanceof Error||typeof s=="object"&&s!==null||Sp('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),s.name){case"AbortException":return new xz(s.message);case"MissingPDFException":return new fz(s.message);case"PasswordException":return new aKe(s.message,s.code);case"UnexpectedResponseException":return new A8e(s.message,s.status);case"UnknownErrorException":return new iKe(s.message,s.details);default:return new iKe(s.message,s.toString())}}var AV,NN,fes,xes,ges,fCe;class zX{constructor(t,n,r){us(this,NN);us(this,AV,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",ts(this,NN,fes).bind(this),{signal:ye(this,AV).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:jg.PULL,streamId:i,desiredSize:d.desiredSize}),u.promise},cancel:d=>{b0(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:jg.CANCEL,streamId:i,reason:ww(d)}),u.promise}},r)}destroy(){var t;(t=ye(this,AV))==null||t.abort(),Ut(this,AV,null)}}AV=new WeakMap,NN=new WeakSet,fes=function({data:t}){if(t.targetName!==this.sourceName)return;if(t.stream){ts(this,NN,ges).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===ude.DATA)a.resolve(t.data);else if(t.callback===ude.ERROR)a.reject(ww(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:ude.DATA,callbackId:t.callbackId,data:l})},function(l){i.postMessage({sourceName:r,targetName:a,callback:ude.ERROR,callbackId:t.callbackId,reason:ww(l)})});return}if(t.streamId){ts(this,NN,xes).call(this,t);return}n(t.data)},xes=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:jg.ENQUEUE,streamId:n,chunk:d},h)},close(){this.isCancelled||(this.isCancelled=!0,i.postMessage({sourceName:r,targetName:a,stream:jg.CLOSE,streamId:n}),delete l.streamSinks[n])},error(d){b0(d instanceof Error,"error must have a valid reason"),!this.isCancelled&&(this.isCancelled=!0,i.postMessage({sourceName:r,targetName:a,stream:jg.ERROR,streamId:n,reason:ww(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:jg.START_COMPLETE,streamId:n,success:!0})},function(d){i.postMessage({sourceName:r,targetName:a,stream:jg.START_COMPLETE,streamId:n,reason:ww(d)})})},ges=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 jg.START_COMPLETE:t.success?l.startCall.resolve():l.startCall.reject(ww(t.reason));break;case jg.PULL_COMPLETE:t.success?l.pullCall.resolve():l.pullCall.reject(ww(t.reason));break;case jg.PULL:if(!o){i.postMessage({sourceName:r,targetName:a,stream:jg.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:jg.PULL_COMPLETE,streamId:n,success:!0})},function(c){i.postMessage({sourceName:r,targetName:a,stream:jg.PULL_COMPLETE,streamId:n,reason:ww(c)})});break;case jg.ENQUEUE:if(b0(l,"enqueue should have stream controller"),l.isClosed)break;l.controller.enqueue(t.chunk);break;case jg.CLOSE:if(b0(l,"close should have stream controller"),l.isClosed)break;l.isClosed=!0,l.controller.close(),ts(this,NN,fCe).call(this,l,n);break;case jg.ERROR:b0(l,"error should have stream controller"),l.controller.error(ww(t.reason)),ts(this,NN,fCe).call(this,l,n);break;case jg.CANCEL_COMPLETE:t.success?l.cancelCall.resolve():l.cancelCall.reject(ww(t.reason)),ts(this,NN,fCe).call(this,l,n);break;case jg.CANCEL:if(!o)break;new Promise(function(c){var d;c((d=o.onCancel)==null?void 0:d.call(o,ww(t.reason)))}).then(function(){i.postMessage({sourceName:r,targetName:a,stream:jg.CANCEL_COMPLETE,streamId:n,success:!0})},function(c){i.postMessage({sourceName:r,targetName:a,stream:jg.CANCEL_COMPLETE,streamId:n,reason:ww(c)})}),o.sinkCapability.reject(ww(t.reason)),o.isCancelled=!0,delete this.streamSinks[n];break;default:throw new Error("Unexpected stream case")}},fCe=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 dO,jne;class NVn{constructor({parsedData:t,rawData:n}){us(this,dO);us(this,jne);Ut(this,dO,t),Ut(this,jne,n)}getRaw(){return ye(this,jne)}get(t){return ye(this,dO).get(t)??null}getAll(){return Brt(ye(this,dO))}has(t){return ye(this,dO).has(t)}}dO=new WeakMap,jne=new WeakMap;const EU=Symbol("INTERNAL");var Nne,kne,Sne,EV;class kVn{constructor(t,{name:n,intent:r,usage:a,rbGroups:i}){us(this,Nne,!1);us(this,kne,!1);us(this,Sne,!1);us(this,EV,!0);Ut(this,Nne,!!(t&qw.DISPLAY)),Ut(this,kne,!!(t&qw.PRINT)),this.name=n,this.intent=r,this.usage=a,this.rbGroups=i}get visible(){if(ye(this,Sne))return ye(this,EV);if(!ye(this,EV))return!1;const{print:t,view:n}=this.usage;return ye(this,Nne)?(n==null?void 0:n.viewState)!=="OFF":ye(this,kne)?(t==null?void 0:t.printState)!=="OFF":!0}_setVisible(t,n,r=!1){t!==EU&&Sp("Internal method `_setVisible` called."),Ut(this,Sne,r),Ut(this,EV,n)}}Nne=new WeakMap,kne=new WeakMap,Sne=new WeakMap,EV=new WeakMap;var eM,Ih,TV,MV,Cne,DKe;class SVn{constructor(t,n=qw.DISPLAY){us(this,Cne);us(this,eM,null);us(this,Ih,new Map);us(this,TV,null);us(this,MV,null);if(this.renderingIntent=n,this.name=null,this.creator=null,t!==null){this.name=t.name,this.creator=t.creator,Ut(this,MV,t.order);for(const r of t.groups)ye(this,Ih).set(r.id,new kVn(n,r));if(t.baseState==="OFF")for(const r of ye(this,Ih).values())r._setVisible(EU,!1);for(const r of t.on)ye(this,Ih).get(r)._setVisible(EU,!0);for(const r of t.off)ye(this,Ih).get(r)._setVisible(EU,!1);Ut(this,TV,this.getHash())}}isVisible(t){if(ye(this,Ih).size===0)return!0;if(!t)return C8e("Optional content group not defined."),!0;if(t.type==="OCG")return ye(this,Ih).has(t.id)?ye(this,Ih).get(t.id).visible:(gd(`Optional content group not found: ${t.id}`),!0);if(t.type==="OCMD"){if(t.expression)return ts(this,Cne,DKe).call(this,t.expression);if(!t.policy||t.policy==="AnyOn"){for(const n of t.ids){if(!ye(this,Ih).has(n))return gd(`Optional content group not found: ${n}`),!0;if(ye(this,Ih).get(n).visible)return!0}return!1}else if(t.policy==="AllOn"){for(const n of t.ids){if(!ye(this,Ih).has(n))return gd(`Optional content group not found: ${n}`),!0;if(!ye(this,Ih).get(n).visible)return!1}return!0}else if(t.policy==="AnyOff"){for(const n of t.ids){if(!ye(this,Ih).has(n))return gd(`Optional content group not found: ${n}`),!0;if(!ye(this,Ih).get(n).visible)return!0}return!1}else if(t.policy==="AllOff"){for(const n of t.ids){if(!ye(this,Ih).has(n))return gd(`Optional content group not found: ${n}`),!0;if(ye(this,Ih).get(n).visible)return!1}return!0}return gd(`Unknown optional content policy ${t.policy}.`),!0}return gd(`Unknown group type ${t.type}.`),!0}setVisibility(t,n=!0,r=!0){var i;const a=ye(this,Ih).get(t);if(!a){gd(`Optional content group not found: ${t}`);return}if(r&&n&&a.rbGroups.length)for(const l of a.rbGroups)for(const o of l)o!==t&&((i=ye(this,Ih).get(o))==null||i._setVisible(EU,!1,!0));a._setVisible(EU,!!n,!0),Ut(this,eM,null)}setOCGState({state:t,preserveRB:n}){let r;for(const a of t){switch(a){case"ON":case"OFF":case"Toggle":r=a;continue}const i=ye(this,Ih).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}}Ut(this,eM,null)}get hasInitialVisibility(){return ye(this,TV)===null||this.getHash()===ye(this,TV)}getOrder(){return ye(this,Ih).size?ye(this,MV)?ye(this,MV).slice():[...ye(this,Ih).keys()]:null}getGroups(){return ye(this,Ih).size>0?Brt(ye(this,Ih)):null}getGroup(t){return ye(this,Ih).get(t)||null}getHash(){if(ye(this,eM)!==null)return ye(this,eM);const t=new res;for(const[n,r]of ye(this,Ih))t.update(`${n}:${r.visible}`);return Ut(this,eM,t.hexdigest())}}eM=new WeakMap,Ih=new WeakMap,TV=new WeakMap,MV=new WeakMap,Cne=new WeakSet,DKe=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)});b0(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(){b0(!this._fullRequestReader,"PDFDataTransportStream.getFullReader can only be called once.");const t=this._queuedChunks;return this._queuedChunks=null,new AVn(this,t,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(t,n){if(n<=this._progressiveDataLength)return null;const r=new EVn(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 AVn{constructor(t,n,r=!1,a=null){this._stream=t,this._done=r||!1,this._filename=$rt(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 EVn{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 TVn(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=E8e(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[,y,v,g]=m;if(y=parseInt(y,10),y in h){if(y===0)break;continue}h[y]=[v,g]}const f=[];for(let y=0;y{if(!yes(i.status))throw P8e(i.status,a);this._reader=i.body.getReader(),this._headersCapability.resolve();const l=i.headers,{allowRangeRequests:o,suggestedLength:c}=Yrt({responseHeaders:l,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=o,this._contentLength=c||this._contentLength,this._filename=Zrt(l),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new xz("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:bes(t),done:!1})}cancel(t){var n;(n=this._reader)==null||n.cancel(t),this._abortController.abort()}}class PVn{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,ves(i,this._withCredentials,this._abortController)).then(o=>{if(!yes(o.status))throw P8e(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:bes(t),done:!1})}cancel(t){var n;(n=this._reader)==null||n.cancel(t),this._abortController.abort()}}const Yze=200,Zze=206;function LVn(s){const t=s.response;return typeof t!="string"?t:E8e(t).buffer}class IVn{constructor({url:t,httpHeaders:n,withCredentials:r}){this.url=t,this.isHttp=/^https?:/i.test(t),this.headers=Krt(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=Zze):a.expectedStatus=Yze,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||Yze;if(!(i===Yze&&r.expectedStatus===Zze)&&i!==r.expectedStatus){(d=r.onError)==null||d.call(r,a.status);return}const o=LVn(a);if(i===Zze){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 DVn{constructor(t){this._source=t,this._manager=new IVn(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 b0(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once."),this._fullRequestReader=new RVn(this._manager,this._source),this._fullRequestReader}getRangeReader(t,n){const r=new FVn(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 RVn{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}=Yrt({responseHeaders:r,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});a&&(this._isRangeSupported=!0),this._contentLength=i||this._contentLength,this._filename=Zrt(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=P8e(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 FVn{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=P8e(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 OVn=/^[a-z][a-z0-9\-+.]+:/i;function zVn(s){if(OVn.test(s))return new URL(s);const t=GP.get("url");return new URL(t.pathToFileURL(s))}function _es(s,t,n){return s.protocol==="http:"?GP.get("http").request(s,{headers:t},n):GP.get("https").request(s,{headers:t},n)}class BVn{constructor(t){this.source=t,this.url=zVn(t.url),this.isHttp=this.url.protocol==="http:"||this.url.protocol==="https:",this.isFsUrl=this.url.protocol==="file:",this.headers=Krt(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 b0(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once."),this._fullRequestReader=this.isFsUrl?new $Vn(this):new UVn(this),this._fullRequestReader}getRangeReader(t,n){if(n<=this._progressiveDataLength)return null;const r=this.isFsUrl?new VVn(this,t,n):new qVn(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 wes{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 xz("streaming is disabled")),this._storedError&&this._readableStream.destroy(this._storedError)}}class jes{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 UVn extends wes{constructor(t){super(t);const n=Object.fromEntries(t.headers),r=a=>{if(a.statusCode===404){const c=new fz(`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}=Yrt({responseHeaders:i,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=l,this._contentLength=o||this._contentLength,this._filename=Zrt(i)};this._request=_es(this._url,n,r),this._request.on("error",a=>{this._storedError=a,this._headersCapability.reject(a)}),this._request.end()}}class qVn extends jes{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 fz(`Missing PDF "${this._url}".`);this._storedError=o;return}this._setReadableStream(l)};this._request=_es(this._url,a,i),this._request.on("error",l=>{this._storedError=l}),this._request.end()}}class $Vn extends wes{constructor(t){super(t);const n=GP.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 fz(`Missing PDF "${this._url}".`)),this._storedError=r,this._headersCapability.reject(r)})}}class VVn extends jes{constructor(t,n,r){super(t);const a=GP.get("fs");this._setReadableStream(a.createReadStream(this._url,{start:n,end:r-1}))}}const HVn=1e5,n_=30,GVn=.8;var xEt,tM,h_,Ane,Ene,uO,lA,Tne,Mne,hO,PV,LV,sM,IV,Pne,DV,mO,Lne,Ine,pO,fO,Dne,nM,RV,TE,Nes,kes,RKe,Sj,xCe,FKe,Ses,Ces;const r0=class r0{constructor({textContentSource:t,container:n,viewport:r}){us(this,TE);us(this,tM,Promise.withResolvers());us(this,h_,null);us(this,Ane,!1);us(this,Ene,!!((xEt=globalThis.FontInspector)!=null&&xEt.enabled));us(this,uO,null);us(this,lA,null);us(this,Tne,0);us(this,Mne,0);us(this,hO,null);us(this,PV,null);us(this,LV,0);us(this,sM,0);us(this,IV,Object.create(null));us(this,Pne,[]);us(this,DV,null);us(this,mO,[]);us(this,Lne,new WeakMap);us(this,Ine,null);var c;if(t instanceof ReadableStream)Ut(this,DV,t);else if(typeof t=="object")Ut(this,DV,new ReadableStream({start(d){d.enqueue(t),d.close()}}));else throw new Error('No "textContentSource" parameter specified.');Ut(this,h_,Ut(this,PV,n)),Ut(this,sM,r.scale*(globalThis.devicePixelRatio||1)),Ut(this,LV,r.rotation),Ut(this,lA,{div:null,properties:null,ctx:null});const{pageWidth:a,pageHeight:i,pageX:l,pageY:o}=r.rawDims;Ut(this,Ine,[1,0,0,-1,-l,o+i]),Ut(this,Mne,a),Ut(this,Tne,i),ts(c=r0,Sj,Ses).call(c),j9(n,r),ye(this,tM).promise.finally(()=>{ye(r0,RV).delete(this),Ut(this,lA,null),Ut(this,IV,null)}).catch(()=>{})}static get fontFamilyMap(){const{isWindows:t,isFirefox:n}=kb.platform;return fu(this,"fontFamilyMap",new Map([["sans-serif",`${t&&n?"Calibri, ":""}sans-serif`],["monospace",`${t&&n?"Lucida Console, ":""}monospace`]]))}render(){const t=()=>{ye(this,hO).read().then(({value:n,done:r})=>{if(r){ye(this,tM).resolve();return}ye(this,uO)??Ut(this,uO,n.lang),Object.assign(ye(this,IV),n.styles),ts(this,TE,Nes).call(this,n.items),t()},ye(this,tM).reject)};return Ut(this,hO,ye(this,DV).getReader()),ye(r0,RV).add(this),t(),ye(this,tM).promise}update({viewport:t,onBefore:n=null}){var i;const r=t.scale*(globalThis.devicePixelRatio||1),a=t.rotation;if(a!==ye(this,LV)&&(n==null||n(),Ut(this,LV,a),j9(ye(this,PV),{rotation:a})),r!==ye(this,sM)){n==null||n(),Ut(this,sM,r);const l={div:null,properties:null,ctx:ts(i=r0,Sj,xCe).call(i,ye(this,uO))};for(const o of ye(this,mO))l.properties=ye(this,Lne).get(o),l.div=o,ts(this,TE,RKe).call(this,l)}}cancel(){var n;const t=new xz("TextLayer task cancelled.");(n=ye(this,hO))==null||n.cancel(t).catch(()=>{}),Ut(this,hO,null),ye(this,tM).reject(t)}get textDivs(){return ye(this,mO)}get textContentItemsStr(){return ye(this,Pne)}static cleanup(){if(!(ye(this,RV).size>0)){ye(this,pO).clear();for(const{canvas:t}of ye(this,fO).values())t.remove();ye(this,fO).clear()}}};tM=new WeakMap,h_=new WeakMap,Ane=new WeakMap,Ene=new WeakMap,uO=new WeakMap,lA=new WeakMap,Tne=new WeakMap,Mne=new WeakMap,hO=new WeakMap,PV=new WeakMap,LV=new WeakMap,sM=new WeakMap,IV=new WeakMap,Pne=new WeakMap,DV=new WeakMap,mO=new WeakMap,Lne=new WeakMap,Ine=new WeakMap,pO=new WeakMap,fO=new WeakMap,Dne=new WeakMap,nM=new WeakMap,RV=new WeakMap,TE=new WeakSet,Nes=function(t){var a,i;if(ye(this,Ane))return;(i=ye(this,lA)).ctx??(i.ctx=ts(a=r0,Sj,xCe).call(a,ye(this,uO)));const n=ye(this,mO),r=ye(this,Pne);for(const l of t){if(n.length>HVn){gd("Ignoring additional textDivs for performance reasons."),Ut(this,Ane,!0);return}if(l.str===void 0){if(l.type==="beginMarkedContentProps"||l.type==="beginMarkedContent"){const o=ye(this,h_);Ut(this,h_,document.createElement("span")),ye(this,h_).classList.add("markedContent"),l.id!==null&&ye(this,h_).setAttribute("id",`${l.id}`),o.append(ye(this,h_))}else l.type==="endMarkedContent"&&Ut(this,h_,ye(this,h_).parentNode);continue}r.push(l.str),ts(this,TE,kes).call(this,l)}},kes=function(t){var y;const n=document.createElement("span"),r={angle:0,canvasWidth:0,hasText:t.str!=="",hasEOL:t.hasEOL,fontSize:0};ye(this,mO).push(n);const a=qo.transform(ye(this,Ine),t.transform);let i=Math.atan2(a[1],a[0]);const l=ye(this,IV)[t.fontName];l.vertical&&(i+=Math.PI/2);let o=ye(this,Ene)&&l.fontSubstitution||l.fontFamily;o=r0.fontFamilyMap.get(o)||o;const c=Math.hypot(a[2],a[3]),d=c*ts(y=r0,Sj,Ces).call(y,o,ye(this,uO));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;ye(this,h_)===ye(this,PV)?(p.left=`${(100*u/ye(this,Mne)).toFixed(2)}%`,p.top=`${(100*h/ye(this,Tne)).toFixed(2)}%`):(p.left=`${m}${u.toFixed(2)}px)`,p.top=`${m}${h.toFixed(2)}px)`),p.fontSize=`${m}${(ye(r0,nM)*c).toFixed(2)}px)`,p.fontFamily=o,r.fontSize=c,n.setAttribute("role","presentation"),n.textContent=t.str,n.dir=t.dir,ye(this,Ene)&&(n.dataset.fontName=l.fontSubstitutionLoadedName||t.fontName),i!==0&&(r.angle=i*(180/Math.PI));let f=!1;if(t.str.length>1)f=!0;else if(t.str!==" "&&t.transform[0]!==t.transform[3]){const v=Math.abs(t.transform[0]),g=Math.abs(t.transform[3]);v!==g&&Math.max(v,g)/Math.min(v,g)>1.5&&(f=!0)}if(f&&(r.canvasWidth=l.vertical?t.height:t.width),ye(this,Lne).set(n,r),ye(this,lA).div=n,ye(this,lA).properties=r,ts(this,TE,RKe).call(this,ye(this,lA)),r.hasText&&ye(this,h_).append(n),r.hasEOL){const v=document.createElement("br");v.setAttribute("role","presentation"),ye(this,h_).append(v)}},RKe=function(t){var o;const{div:n,properties:r,ctx:a}=t,{style:i}=n;let l="";if(ye(r0,nM)>1&&(l=`scale(${1/ye(r0,nM)})`),r.canvasWidth!==0&&r.hasText){const{fontFamily:c}=i,{canvasWidth:d,fontSize:u}=r;ts(o=r0,Sj,FKe).call(o,a,u*ye(this,sM),c);const{width:h}=a.measureText(n.textContent);h>0&&(l=`scaleX(${d*ye(this,sM)/h}) ${l}`)}r.angle!==0&&(l=`rotate(${r.angle}deg) ${l}`),l.length>0&&(i.transform=l)},Sj=new WeakSet,xCe=function(t=null){let n=ye(this,fO).get(t||(t=""));if(!n){const r=document.createElement("canvas");r.className="hiddenCanvasElement",r.lang=t,document.body.append(r),n=r.getContext("2d",{alpha:!1,willReadFrequently:!0}),ye(this,fO).set(t,n),ye(this,Dne).set(n,{size:0,family:""})}return n},FKe=function(t,n,r){const a=ye(this,Dne).get(t);n===a.size&&r===a.family||(t.font=`${n}px ${r}`,a.size=n,a.family=r)},Ses=function(){if(ye(this,nM)!==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),Ut(this,nM,t.getBoundingClientRect().height),t.remove()},Ces=function(t,n){const r=ye(this,pO).get(t);if(r)return r;const a=ts(this,Sj,xCe).call(this,n);a.canvas.width=a.canvas.height=n_,ts(this,Sj,FKe).call(this,a,n_,t);const i=a.measureText("");let l=i.fontBoundingBoxAscent,o=Math.abs(i.fontBoundingBoxDescent);if(l){const u=l/(l+o);return ye(this,pO).set(t,u),a.canvas.width=a.canvas.height=0,u}a.strokeStyle="red",a.clearRect(0,0,n_,n_),a.strokeText("g",0,0);let c=a.getImageData(0,0,n_,n_).data;o=0;for(let u=c.length-1-3;u>=0;u-=4)if(c[u]>0){o=Math.ceil(u/4/n_);break}a.clearRect(0,0,n_,n_),a.strokeText("A",0,n_),c=a.getImageData(0,0,n_,n_).data,l=0;for(let u=0,h=c.length;u0){l=n_-Math.floor(u/4/n_);break}a.canvas.width=a.canvas.height=0;const d=l?l/(l+o):GVn;return ye(this,pO).set(t,d),d},us(r0,Sj),us(r0,pO,new Map),us(r0,fO,new Map),us(r0,Dne,new WeakMap),us(r0,nM,null),us(r0,RV,new Set);let Cse=r0;class Ase{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(Ase.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 WVn=65536,KVn=100,YVn=5e3,ZVn=h1?lVn:aVn,XVn=h1?cVn:ces,QVn=h1?oVn:iVn,JVn=h1?dVn:mes;function eHn(s={}){typeof s=="string"||s instanceof URL?s={url:s}:(s instanceof ArrayBuffer||ArrayBuffer.isView(s))&&(s={data:s});const t=new OKe,{docId:n}=t,r=s.url?tHn(s.url):null,a=s.data?sHn(s.data):null,i=s.httpHeaders||null,l=s.withCredentials===!0,o=s.password??null,c=s.range instanceof Aes?s.range:null,d=Number.isInteger(s.rangeChunkSize)&&s.rangeChunkSize>0?s.rangeChunkSize:WVn;let u=s.worker instanceof H$?s.worker:null;const h=s.verbosity,m=typeof s.docBaseUrl=="string"&&!M8e(s.docBaseUrl)?s.docBaseUrl:null,p=typeof s.cMapUrl=="string"?s.cMapUrl:null,f=s.cMapPacked!==!1,y=s.CMapReaderFactory||XVn,v=typeof s.standardFontDataUrl=="string"?s.standardFontDataUrl:null,g=s.StandardFontDataFactory||JVn,b=s.stopAtErrors!==!0,j=Number.isInteger(s.maxImageSize)&&s.maxImageSize>-1?s.maxImageSize:-1,S=s.isEvalSupported!==!1,C=typeof s.isOffscreenCanvasSupported=="boolean"?s.isOffscreenCanvasSupported:!h1,E=typeof s.isChrome=="boolean"?s.isChrome:!kb.platform.isFirefox&&typeof window<"u"&&!!(window!=null&&window.chrome),P=Number.isInteger(s.canvasMaxAreaInBytes)?s.canvasMaxAreaInBytes:-1,M=typeof s.disableFontFace=="boolean"?s.disableFontFace:h1,I=s.fontExtraProperties===!0,D=s.enableXfa===!0,O=s.ownerDocument||globalThis.document,V=s.disableRange===!0,G=s.disableStream===!0,$=s.disableAutoFetch===!0,H=s.pdfBug===!0,Y=s.CanvasFactory||ZVn,Z=s.FilterFactory||QVn,ne=s.enableHWA===!0,ce=c?c.length:s.length??NaN,ie=typeof s.useSystemFonts=="boolean"?s.useSystemFonts:!h1&&!M,te=typeof s.useWorkerFetch=="boolean"?s.useWorkerFetch:y===ces&&g===mes&&p&&v&&PX(p,document.baseURI)&&PX(v,document.baseURI);s.canvasFactory&&lSt("`canvasFactory`-instance option, please use `CanvasFactory` instead."),s.filterFactory&&lSt("`filterFactory`-instance option, please use `FilterFactory` instead.");const ae=null;R$n(h);const le={canvasFactory:new Y({ownerDocument:O,enableHWA:ne}),filterFactory:new Z({docId:n,ownerDocument:O}),cMapReaderFactory:te?null:new y({baseUrl:p,isCompressed:f}),standardFontDataFactory:te?null:new g({baseUrl:v})};if(!u){const he={verbosity:h,port:EA.workerPort};u=he.port?H$.fromPort(he):new H$(he),t._worker=u}const be={docId:n,apiVersion:"4.8.69",data:a,password:o,disableAutoFetch:$,rangeChunkSize:d,length:ce,docBaseUrl:m,enableXfa:D,evaluatorOptions:{maxImageSize:j,disableFontFace:M,ignoreErrors:b,isEvalSupported:S,isOffscreenCanvasSupported:C,isChrome:E,canvasMaxAreaInBytes:P,fontExtraProperties:I,useSystemFonts:ie,cMapUrl:te?p:null,standardFontDataUrl:te?v:null}},me={disableFontFace:M,fontExtraProperties:I,ownerDocument:O,pdfBug:H,styleElement:ae,loadingParams:{disableAutoFetch:$,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 he=u.messageHandler.sendWithPromise("GetDocRequest",be,a?[a.buffer]:null);let pe;if(c)pe=new CVn(c,{disableRange:V,disableStream:G});else if(!a){if(!r)throw new Error("getDocument - no `url` parameter provided.");let Ce;h1?Ce=typeof fetch<"u"&&typeof Response<"u"&&"body"in Response.prototype&&PX(r)?bSt:BVn:Ce=PX(r)?bSt:DVn,pe=new Ce({url:r,length:ce,httpHeaders:i,withCredentials:l,rangeChunkSize:d,disableRange:V,disableStream:G})}return he.then(Ce=>{if(t.destroyed)throw new Error("Loading aborted");if(u.destroyed)throw new Error("Worker was destroyed");const Ae=new zX(n,Ce,u.port),Pe=new iHn(Ae,t,pe,me,le);t._transport=Pe,Ae.send("Ready",null)})}).catch(t._capability.reject),t}function tHn(s){if(s instanceof URL)return s.href;try{return new URL(s,window.location).href}catch{if(h1&&typeof s=="string")return s}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}function sHn(s){if(h1&&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 E8e(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 _St(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 X6e;const Q6e=class Q6e{constructor(){this._capability=Promise.withResolvers(),this._transport=null,this._worker=null,this.docId=`d${X0(Q6e,X6e)._++}`,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)}};X6e=new WeakMap,us(Q6e,X6e,0);let OKe=Q6e;class Aes{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){Sp("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class nHn{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 fu(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 rM,cA,eN,TU,gCe;class rHn{constructor(t,n,r,a=!1){us(this,eN);us(this,rM,null);us(this,cA,!1);this._pageIndex=t,this._pageInfo=n,this._transport=r,this._stats=a?new oSt:null,this._pdfBug=a,this.commonObjs=r.commonObjs,this.objs=new Ees,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 Xae({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 fu(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=M6.ENABLE,transform:i=null,background:l=null,optionalContentConfigPromise:o=null,annotationCanvasMap:c=null,pageColors:d=null,printAnnotationStorage:u=null,isEditing:h=!1}){var S,C;(S=this._stats)==null||S.time("Overall");const m=this._transport.getRenderingIntent(r,a,u,h),{renderingIntent:p,cacheKey:f}=m;Ut(this,cA,!1),ts(this,eN,gCe).call(this),o||(o=this._transport.getOptionalContentConfig(p));let y=this._intentStates.get(f);y||(y=Object.create(null),this._intentStates.set(f,y)),y.streamReaderCancelTimeout&&(clearTimeout(y.streamReaderCancelTimeout),y.streamReaderCancelTimeout=null);const v=!!(p&qw.PRINT);y.displayReadyCapability||(y.displayReadyCapability=Promise.withResolvers(),y.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},(C=this._stats)==null||C.time("Page Request"),this._pumpOperatorList(m));const g=E=>{var P;y.renderTasks.delete(b),(this._maybeCleanupAfterRender||v)&&Ut(this,cA,!0),ts(this,eN,TU).call(this,!v),E?(b.capability.reject(E),this._abortOperatorList({intentState:y,reason:E instanceof Error?E:new Error(E)})):b.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))},b=new BKe({callback:g,params:{canvasContext:t,viewport:n,transform:i,background:l},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:c,operatorList:y.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!v,pdfBug:this._pdfBug,pageColors:d});(y.renderTasks||(y.renderTasks=new Set)).add(b);const j=b.task;return Promise.all([y.displayReadyCapability.promise,o]).then(([E,P])=>{var M;if(this.destroyed){g();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.");b.initializeGraphics({transparency:E,optionalContentConfig:P}),b.operatorListChanged()}).catch(g),j}getOperatorList({intent:t="display",annotationMode:n=M6.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=>Ase.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(),Ut(this,cA,!1),ts(this,eN,gCe).call(this),Promise.all(t)}cleanup(t=!1){Ut(this,cA,!0);const n=ts(this,eN,TU).call(this,!1);return t&&n&&this._stats&&(this._stats=new oSt),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();ts(this,eN,TU).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 qrt){let a=KVn;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 xz(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}}rM=new WeakMap,cA=new WeakMap,eN=new WeakSet,TU=function(t=!1){if(ts(this,eN,gCe).call(this),!ye(this,cA)||this.destroyed)return!1;if(t)return Ut(this,rM,setTimeout(()=>{Ut(this,rM,null),ts(this,eN,TU).call(this,!1)},YVn)),!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(),Ut(this,cA,!1),!0},gCe=function(){ye(this,rM)&&(clearTimeout(ye(this,rM)),Ut(this,rM,null))};var dA,J6e;class aHn{constructor(){us(this,dA,new Map);us(this,J6e,Promise.resolve())}postMessage(t,n){const r={data:structuredClone(t,n?{transfer:n}:null)};ye(this,J6e).then(()=>{for(const[a]of ye(this,dA))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){gd("LoopbackPort - cannot use an `aborted` signal.");return}const l=()=>this.removeEventListener(t,n);a=()=>i.removeEventListener("abort",l),i.addEventListener("abort",l)}ye(this,dA).set(n,a)}removeEventListener(t,n){const r=ye(this,dA).get(n);r==null||r(),ye(this,dA).delete(n)}terminate(){for(const[,t]of ye(this,dA))t==null||t();ye(this,dA).clear()}}dA=new WeakMap,J6e=new WeakMap;var eMe,xO,gO,FV,yCe,OV,vCe;const Wp=class Wp{constructor({name:t=null,port:n=null,verbosity:r=F$n()}={}){us(this,FV);var a;if(this.name=t,this.destroyed=!1,this.verbosity=r,this._readyCapability=Promise.withResolvers(),this._port=null,this._webWorker=null,this._messageHandler=null,n){if((a=ye(Wp,gO))!=null&&a.has(n))throw new Error("Cannot use more than one PDFWorker per port.");(ye(Wp,gO)||Ut(Wp,gO,new WeakMap)).set(n,this),this._initializeFromPort(n);return}this._initialize()}get promise(){return h1?Promise.all([GP.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 zX("main","worker",t),this._messageHandler.on("ready",function(){}),ts(this,FV,yCe).call(this)}_initialize(){if(ye(Wp,xO)||ye(Wp,OV,vCe)){this._setupFakeWorker();return}let{workerSrc:t}=Wp;try{Wp._isSameOrigin(window.location.href,t)||(t=Wp._createCDNWrapper(new URL(t,window.location).href));const n=new Worker(t,{type:"module"}),r=new zX("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,ts(this,FV,yCe).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{C8e("The worker has been disabled.")}this._setupFakeWorker()}_setupFakeWorker(){ye(Wp,xO)||(gd("Setting up fake worker."),Ut(Wp,xO,!0)),Wp._setupFakeWorkerGlobal.then(t=>{if(this.destroyed){this._readyCapability.reject(new Error("Worker was destroyed"));return}const n=new aHn;this._port=n;const r=`fake${X0(Wp,eMe)._++}`,a=new zX(r+"_worker",r,n);t.setup(a,n),this._messageHandler=new zX(r,r+"_worker",n),ts(this,FV,yCe).call(this)}).catch(t=>{this._readyCapability.reject(new Error(`Setting up fake worker failed: "${t.message}".`))})}destroy(){var t;this.destroyed=!0,this._webWorker&&(this._webWorker.terminate(),this._webWorker=null),(t=ye(Wp,gO))==null||t.delete(this._port),this._port=null,this._messageHandler&&(this._messageHandler.destroy(),this._messageHandler=null)}static fromPort(t){var r;if(!(t!=null&&t.port))throw new Error("PDFWorker.fromPort - invalid method signature.");const n=(r=ye(this,gO))==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 Wp(t)}static get workerSrc(){if(EA.workerSrc)return EA.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get _setupFakeWorkerGlobal(){return fu(this,"_setupFakeWorkerGlobal",(async()=>ye(this,OV,vCe)?ye(this,OV,vCe):(await import(this.workerSrc)).WorkerMessageHandler)())}};eMe=new WeakMap,xO=new WeakMap,gO=new WeakMap,FV=new WeakSet,yCe=function(){this._readyCapability.resolve(),this._messageHandler.send("configure",{verbosity:this.verbosity})},OV=new WeakSet,vCe=function(){var t;try{return((t=globalThis.pdfjsWorker)==null?void 0:t.WorkerMessageHandler)||null}catch{return null}},us(Wp,OV),us(Wp,eMe,0),us(Wp,xO,!1),us(Wp,gO),h1&&(Ut(Wp,xO,!0),EA.workerSrc||(EA.workerSrc="./pdf.worker.mjs")),Wp._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},Wp._createCDNWrapper=t=>{const n=`await import("${t}");`;return URL.createObjectURL(new Blob([n],{type:"text/javascript"}))};let H$=Wp;var uA,o4,zV,BV,l4,yO,BX;class iHn{constructor(t,n,r,a,i){us(this,yO);us(this,uA,new Map);us(this,o4,new Map);us(this,zV,new Map);us(this,BV,new Map);us(this,l4,null);this.messageHandler=t,this.loadingTask=n,this.commonObjs=new Ees,this.fontLoader=new nVn({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 fu(this,"annotationStorage",new Grt)}getRenderingIntent(t,n=M6.ENABLE,r=null,a=!1,i=!1){let l=qw.DISPLAY,o=CKe;switch(t){case"any":l=qw.ANY;break;case"display":break;case"print":l=qw.PRINT;break;default:gd(`getRenderingIntent - invalid intent: ${t}`)}const c=l&qw.PRINT&&r instanceof ies?r:this.annotationStorage;switch(n){case M6.DISABLE:l+=qw.ANNOTATIONS_DISABLE;break;case M6.ENABLE:break;case M6.ENABLE_FORMS:l+=qw.ANNOTATIONS_FORMS;break;case M6.ENABLE_STORAGE:l+=qw.ANNOTATIONS_STORAGE,o=c.serializable;break;default:gd(`getRenderingIntent - invalid annotationMode: ${n}`)}a&&(l+=qw.IS_EDITING),i&&(l+=qw.OPLIST);const{ids:d,hash:u}=c.modifiedIds,h=[l,o.hash,u];return{renderingIntent:l,cacheKey:h.join("_"),annotationStorageSerializable:o,modifiedIds:d}}destroy(){var r;if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0,this.destroyCapability=Promise.withResolvers(),(r=ye(this,l4))==null||r.reject(new Error("Worker was destroyed during onPassword callback"));const t=[];for(const a of ye(this,o4).values())t.push(a._destroy());ye(this,o4).clear(),ye(this,zV).clear(),ye(this,BV).clear(),this.hasOwnProperty("annotationStorage")&&this.annotationStorage.resetModified();const n=this.messageHandler.sendWithPromise("Terminate",null);return t.push(n),Promise.all(t).then(()=>{var a;this.commonObjs.clear(),this.fontLoader.clear(),ye(this,uA).clear(),this.filterFactory.destroy(),Cse.cleanup(),(a=this._networkStream)==null||a.cancelAllRequests(new xz("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)=>{b0(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}b0(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)=>{b0(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}b0(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 nHn(r,this))}),t.on("DocException",function(r){let a;switch(r.name){case"PasswordException":a=new aKe(r.message,r.code);break;case"InvalidPDFException":a=new PJt(r.message);break;case"MissingPDFException":a=new fz(r.message);break;case"UnexpectedResponseException":a=new A8e(r.message,r.status);break;case"UnknownErrorException":a=new iKe(r.message,r.details);break;default:Sp("DocException - expected a valid Error.")}n._capability.reject(a)}),t.on("PasswordRequest",r=>{if(Ut(this,l4,Promise.withResolvers()),n.onPassword){const a=i=>{i instanceof Error?ye(this,l4).reject(i):ye(this,l4).resolve({password:i})};try{n.onPassword(a,r.code)}catch(i){ye(this,l4).reject(i)}}else ye(this,l4).reject(new aKe(r.message,r.code));return ye(this,l4).promise}),t.on("DataLoaded",r=>{var a;(a=n.onProgress)==null||a.call(n,{loaded:r.length,total:r.length}),this.downloadInfoCapability.resolve(r)}),t.on("StartRenderPage",r=>{if(this.destroyed)return;ye(this,o4).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;gd(`Error during font loading: ${p}`),this.commonObjs.resolve(r,p);break}const u=d&&((l=globalThis.FontInspector)!=null&&l.enabled)?(p,f)=>globalThis.FontInspector.fontAdded(p,f):null,h=new rVn(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;b0(m,"The imageRef must be defined.");for(const p of ye(this,o4).values())for(const[,f]of p.objs)if((f==null?void 0:f.ref)===m)return f.dataLen?(this.commonObjs.resolve(r,structuredClone(f)),f.dataLen):null;break;case"FontPath":case"Image":case"Pattern":this.commonObjs.resolve(r,i);break;default:throw new Error(`Got unknown common object type ${a}`)}return null}),t.on("obj",([r,a,i,l])=>{var c;if(this.destroyed)return;const o=ye(this,o4).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)>P$n&&(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&&gd("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");const{map:t,transfer:n}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise("SaveDocument",{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:t,filename:((r=this._fullReader)==null?void 0:r.filename)??null},n).finally(()=>{this.annotationStorage.resetModified()})}getPage(t){if(!Number.isInteger(t)||t<=0||t>this._numPages)return Promise.reject(new Error("Invalid page request."));const n=t-1,r=ye(this,zV).get(n);if(r)return r;const a=this.messageHandler.sendWithPromise("GetPage",{pageIndex:n}).then(i=>{if(this.destroyed)throw new Error("Transport destroyed");i.refStr&&ye(this,BV).set(i.refStr,t);const l=new rHn(n,i,this,this._params.pdfBug);return ye(this,o4).set(n,l),l});return ye(this,zV).set(n,a),a}getPageIndex(t){return _St(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 ts(this,yO,BX).call(this,"GetFieldObjects")}hasJSActions(){return ts(this,yO,BX).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 ts(this,yO,BX).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 ts(this,yO,BX).call(this,"GetOptionalContentConfig").then(n=>new SVn(n,t))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const t="GetMetadata",n=ye(this,uA).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 NVn(a[1]):null,contentDispositionFilename:((i=this._fullReader)==null?void 0:i.filename)??null,contentLength:((l=this._fullReader)==null?void 0:l.contentLength)??null}});return ye(this,uA).set(t,r),r}getMarkInfo(){return this.messageHandler.sendWithPromise("GetMarkInfo",null)}async startCleanup(t=!1){if(!this.destroyed){await this.messageHandler.sendWithPromise("Cleanup",null);for(const n of ye(this,o4).values())if(!n.cleanup())throw new Error(`startCleanup: Page ${n.pageNumber} is currently rendering.`);this.commonObjs.clear(),t||this.fontLoader.clear(),ye(this,uA).clear(),this.filterFactory.destroy(!0),Cse.cleanup()}}cachedPageNumber(t){if(!_St(t))return null;const n=t.gen===0?`${t.num}R`:`${t.num}R${t.gen}`;return ye(this,BV).get(n)??null}}uA=new WeakMap,o4=new WeakMap,zV=new WeakMap,BV=new WeakMap,l4=new WeakMap,yO=new WeakSet,BX=function(t,n=null){const r=ye(this,uA).get(t);if(r)return r;const a=this.messageHandler.sendWithPromise(t,n);return ye(this,uA).set(t,a),a};const hde=Symbol("INITIAL_DATA");var Fk,Rne,zKe;class Ees{constructor(){us(this,Rne);us(this,Fk,Object.create(null))}get(t,n=null){if(n){const a=ts(this,Rne,zKe).call(this,t);return a.promise.then(()=>n(a.data)),null}const r=ye(this,Fk)[t];if(!r||r.data===hde)throw new Error(`Requesting object that isn't resolved yet ${t}.`);return r.data}has(t){const n=ye(this,Fk)[t];return!!n&&n.data!==hde}resolve(t,n=null){const r=ts(this,Rne,zKe).call(this,t);r.data=n,r.resolve()}clear(){var t;for(const n in ye(this,Fk)){const{data:r}=ye(this,Fk)[n];(t=r==null?void 0:r.bitmap)==null||t.close()}Ut(this,Fk,Object.create(null))}*[Symbol.iterator](){for(const t in ye(this,Fk)){const{data:n}=ye(this,Fk)[t];n!==hde&&(yield[t,n])}}}Fk=new WeakMap,Rne=new WeakSet,zKe=function(t){var n;return(n=ye(this,Fk))[t]||(n[t]={...Promise.withResolvers(),data:hde})};var aM;class oHn{constructor(t){us(this,aM,null);Ut(this,aM,t),this.onContinue=null}get promise(){return ye(this,aM).capability.promise}cancel(t=0){ye(this,aM).cancel(null,t)}get separateAnnots(){const{separateAnnots:t}=ye(this,aM).operatorList;if(!t)return!1;const{annotationCanvasMap:n}=ye(this,aM);return t.form||t.canvas&&(n==null?void 0:n.size)>0}}aM=new WeakMap;var iM,vO;const iF=class iF{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}){us(this,iM,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 oHn(this),this._cancelBound=this.cancel.bind(this),this._continueBound=this._continue.bind(this),this._scheduleNextBound=this._scheduleNext.bind(this),this._nextBound=this._next.bind(this),this._canvas=n.canvasContext.canvas}get completed(){return this.capability.promise.catch(function(){})}initializeGraphics({transparency:t=!1,optionalContentConfig:n}){var o,c;if(this.cancelled)return;if(this._canvas){if(ye(iF,vO).has(this._canvas))throw new Error("Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed.");ye(iF,vO).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 V$(r,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:n},this.annotationCanvasMap,this.pageColors),this.gfx.beginDrawing({transform:i,viewport:a,transparency:t,background:l}),this.operatorListIdx=0,this.graphicsReady=!0,(c=this.graphicsReadyCallback)==null||c.call(this)}cancel(t=null,n=0){var r;this.running=!1,this.cancelled=!0,(r=this.gfx)==null||r.endDrawing(),ye(this,iM)&&(window.cancelAnimationFrame(ye(this,iM)),Ut(this,iM,null)),ye(iF,vO).delete(this._canvas),this.callback(t||new qrt(`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?Ut(this,iM,window.requestAnimationFrame(()=>{Ut(this,iM,null),this._nextBound().catch(this._cancelBound)})):Promise.resolve().then(this._nextBound).catch(this._cancelBound)}async _next(){this.cancelled||(this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper),this.operatorListIdx===this.operatorList.argsArray.length&&(this.running=!1,this.operatorList.lastChunk&&(this.gfx.endDrawing(),ye(iF,vO).delete(this._canvas),this.callback())))}};iM=new WeakMap,vO=new WeakMap,us(iF,vO,new WeakSet);let BKe=iF;const lHn="4.8.69",cHn="3634dab10";function wSt(s){return Math.floor(Math.max(0,Math.min(1,s))*255).toString(16).padStart(2,"0")}function wZ(s){return Math.max(0,Math.min(255,255*s))}class jSt{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=wZ(t),[t,t,t]}static G_HTML([t]){const n=wSt(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(wZ)}static RGB_HTML(t){return`#${t.map(wSt).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[wZ(1-Math.min(1,t+a)),wZ(1-Math.min(1,r+a)),wZ(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 dHn{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){Sp("Abstract method `_createSVG` called.")}}class Xrt extends dHn{_createSVG(t){return document.createElementNS(D3,t)}}class Tes{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&&Ase.shouldBuildText(a.name)&&d.push(p)}return{textDivs:d}}const u=[[a,-1,l]];for(;u.length>0;){const[p,f,y]=u.at(-1);if(f+1===p.children.length){u.pop();continue}const v=p.children[++u.at(-1)[1]];if(v===null)continue;const{name:g}=v;if(g==="#text"){const j=document.createTextNode(v.value);d.push(j),y.append(j);continue}const b=(h=v==null?void 0:v.attributes)!=null&&h.xmlns?document.createElementNS(v.attributes.xmlns,g):document.createElement(g);if(y.append(b),v.attributes&&this.setAttributes({html:b,element:v,storage:n,intent:i,linkService:r}),((m=v.children)==null?void 0:m.length)>0)u.push([v,-1,b]);else if(v.value){const j=document.createTextNode(v.value);o&&Ase.shouldBuildText(g)&&d.push(j),b.append(j)}}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 Jae=1e3,uHn=9,k9=new WeakSet;function rE(s){return{width:s[2]-s[0],height:s[3]-s[1]}}class hHn{static create(t){switch(t.data.annotationType){case s0.LINK:return new Mes(t);case s0.TEXT:return new mHn(t);case s0.WIDGET:switch(t.data.fieldType){case"Tx":return new pHn(t);case"Btn":return t.data.radioButton?new Ies(t):t.data.checkBox?new xHn(t):new gHn(t);case"Ch":return new yHn(t);case"Sig":return new fHn(t)}return new gz(t);case s0.POPUP:return new qKe(t);case s0.FREETEXT:return new zes(t);case s0.LINE:return new bHn(t);case s0.SQUARE:return new _Hn(t);case s0.CIRCLE:return new wHn(t);case s0.POLYLINE:return new Bes(t);case s0.CARET:return new NHn(t);case s0.INK:return new Qrt(t);case s0.POLYGON:return new jHn(t);case s0.HIGHLIGHT:return new Ues(t);case s0.UNDERLINE:return new kHn(t);case s0.SQUIGGLY:return new SHn(t);case s0.STRIKEOUT:return new CHn(t);case s0.STAMP:return new qes(t);case s0.FILEATTACHMENT:return new AHn(t);default:return new mg(t)}}}var bO,UV,qV,Fne,UKe;const oot=class oot{constructor(t,{isRenderable:n=!1,ignoreBorder:r=!1,createQuadrilaterals:a=!1}={}){us(this,Fne);us(this,bO,null);us(this,UV,!1);us(this,qV,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 oot._hasPopupData(this.data)}updateEdited(t){var r;if(!this.container)return;ye(this,bO)||Ut(this,bO,{rect:this.data.rect.slice(0)});const{rect:n}=t;n&&ts(this,Fne,UKe).call(this,n),(r=ye(this,qV))==null||r.popup.updateEdited(t)}resetEdited(){var t;ye(this,bO)&&(ts(this,Fne,UKe).call(this,ye(this,bO).rect),(t=ye(this,qV))==null||t.popup.resetEdited(),Ut(this,bO,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 gz||(i.tabIndex=Jae);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 qKe){const{rotation:y}=n;return!n.hasOwnCanvas&&y!==0&&this.setRotation(y,i),i}const{width:o,height:c}=rE(n.rect);if(!t&&n.borderStyle.width>0){l.borderWidth=`${n.borderStyle.width}px`;const y=n.borderStyle.horizontalCornerRadius,v=n.borderStyle.verticalCornerRadius;if(y>0||v>0){const b=`calc(${y}px * var(--scale-factor)) / calc(${v}px * var(--scale-factor))`;l.borderRadius=b}else if(this instanceof Ies){const b=`calc(${o}px * var(--scale-factor)) / calc(${c}px * var(--scale-factor))`;l.borderRadius=b}switch(n.borderStyle.style){case bZ.SOLID:l.borderStyle="solid";break;case bZ.DASHED:l.borderStyle="dashed";break;case bZ.BEVELED:gd("Unimplemented border style: beveled");break;case bZ.INSET:gd("Unimplemented border style: inset");break;case bZ.UNDERLINE:l.borderBottomStyle="solid";break}const g=n.borderColor||null;g?(Ut(this,UV,!0),l.borderColor=qo.makeHexColor(g[0]|0,g[1]|0,g[2]|0)):l.borderWidth=0}const d=qo.normalizeRect([n.rect[0],r.view[3]-n.rect[1]+r.view[1],n.rect[2],r.view[3]-n.rect[3]+r.view[1]]),{pageWidth:u,pageHeight:h,pageX:m,pageY:p}=a.rawDims;l.left=`${100*(d[0]-m)/u}%`,l.top=`${100*(d[1]-p)/h}%`;const{rotation:f}=n;return n.hasOwnCanvas||f===0?(l.width=`${100*o/u}%`,l.height=`${100*c/h}%`):this.setRotation(f,i),i}setRotation(t,n=this.container){if(!this.data.rect)return;const{pageWidth:r,pageHeight:a}=this.parent.viewport.rawDims,{width:i,height:l}=rE(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]=jSt[`${l}_HTML`](o),this.annotationStorage.setValue(this.data.id,{[r]:jSt[`${l}_rgb`](o)})};return fu(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(y=>Math.fround(y));if(t.length===8){const[y,v,g,b]=t.subarray(2,6);if(a===y&&i===v&&n===g&&r===b)return}const{style:l}=this.container;let o;if(ye(this,UV)){const{borderColor:y,borderWidth:v}=l;l.borderWidth=0,o=["url('data:image/svg+xml;utf8,",'',``],this.container.classList.add("hasBorder")}const c=a-n,d=i-r,{svgFactory:u}=this,h=u.createElement("svg");h.classList.add("quadrilateralsContainer"),h.setAttribute("width",0),h.setAttribute("height",0);const m=u.createElement("defs");h.append(m);const p=u.createElement("clipPath"),f=`clippath_${this.data.id}`;p.setAttribute("id",f),p.setAttribute("clipPathUnits","objectBoundingBox"),m.append(p);for(let y=2,v=t.length;y`)}ye(this,UV)&&(o.push("')"),l.backgroundImage=o.join("")),this.container.append(h),this.container.style.clipPath=`url(#${f})`}_createPopup(){const{data:t}=this,n=Ut(this,qV,new qKe({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(){Sp("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&&!k9.has(d)){gd(`_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&&k9.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})})}};bO=new WeakMap,UV=new WeakMap,qV=new WeakMap,Fne=new WeakSet,UKe=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}=rE(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 mg=oot;var Zw,GR,Pes,Les;class Mes extends mg{constructor(n,r=null){super(n,{isRenderable:!0,ignoreBorder:!!(r!=null&&r.ignoreBorder),createQuadrilaterals:!0});us(this,Zw);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?(ts(this,Zw,Pes).call(this,a,n.attachment,n.attachmentDest),i=!0):n.setOCGState?(ts(this,Zw,Les).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==="")&&ts(this,Zw,GR).call(this)}_bindNamedAction(n,r){n.href=this.linkService.getAnchorUrl(""),n.onclick=()=>(this.linkService.executeNamedAction(r),!1),ts(this,Zw,GR).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),ts(this,Zw,GR).call(this)}_bindResetFormAction(n,r){const a=n.onclick;if(a||(n.href=this.linkService.getAnchorUrl("")),ts(this,Zw,GR).call(this),!this._fieldObjects){gd('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.'),a||(n.onclick=()=>!1);return}n.onclick=()=>{var h;a==null||a();const{fields:i,refs:l,include:o}=r,c=[];if(i.length!==0||l.length!==0){const m=new Set(l);for(const p of i){const f=this._fieldObjects[p]||[];for(const{id:y}of f)m.add(y)}for(const p of Object.values(this._fieldObjects))for(const f of p)m.has(f.id)===o&&c.push(f)}else for(const m of Object.values(this._fieldObjects))c.push(...m);const d=this.annotationStorage,u=[];for(const m of c){const{id:p}=m;switch(u.push(p),m.type){case"text":{const y=m.defaultValue||"";d.setValue(p,{value:y});break}case"checkbox":case"radiobutton":{const y=m.defaultValue===m.exportValues;d.setValue(p,{value:y});break}case"combobox":case"listbox":{const y=m.defaultValue||"";d.setValue(p,{value:y});break}default:continue}const f=document.querySelector(`[data-element-id="${p}"]`);if(f){if(!k9.has(f)){gd(`_bindResetFormAction - element not allowed: ${p}`);continue}}else continue;f.dispatchEvent(new Event("resetform"))}return this.enableScripting&&((h=this.linkService.eventBus)==null||h.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:u,name:"ResetForm"}})),!1}}}Zw=new WeakSet,GR=function(){this.container.setAttribute("data-internal-link","")},Pes=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},ts(this,Zw,GR).call(this)},Les=function(n,r){n.href=this.linkService.getAnchorUrl(""),n.onclick=()=>(this.linkService.executeSetOCGState(r),!1),ts(this,Zw,GR).call(this)};class mHn extends mg{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 gz extends mg{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 kb.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":qo.makeHexColor(n[0],n[1],n[2])}_setTextStyle(t){const n=["left","center","right"],{fontColor:r}=this.data.defaultAppearanceData,a=this.data.defaultAppearanceData.fontSize||uHn,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/(Hze*a))||1,h=d/u;l=Math.min(a,c(h/Hze))}else{const d=Math.abs(this.data.rect[3]-this.data.rect[1]-o);l=Math.min(a,c(d/Hze))}i.fontSize=`calc(${l}px * var(--scale-factor))`,i.color=qo.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 pHn extends gz{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),k9.add(r),r.setAttribute("data-element-id",n),r.disabled=this.data.readOnly,r.name=this.data.fieldName,r.tabIndex=Jae,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 y;if(u.focused)return;const{target:f}=p;u.userValue&&(f.value=u.userValue),u.lastCommittedValue=f.value,u.commitKey=1,(y=this.data.actions)!=null&&y.Focus||(u.focused=!0)}),r.addEventListener("updatefromsandbox",p=>{this.showElementAndHideCanvas(p.target);const f={value(y){u.userValue=y.detail.value??"",t.setValue(n,{value:u.userValue.toString()}),y.target.value=u.userValue},formattedValue(y){const{formattedValue:v}=y.detail;u.formattedValue=v,v!=null&&y.target!==document.activeElement&&(y.target.value=v),t.setValue(n,{formattedValue:v})},selRange(y){y.target.setSelectionRange(...y.detail.selRange)},charLimit:y=>{var j;const{charLimit:v}=y.detail,{target:g}=y;if(v===0){g.removeAttribute("maxLength");return}g.setAttribute("maxLength",v);let b=u.userValue;!b||b.length<=v||(b=b.slice(0,v),g.value=u.userValue=b,t.setValue(n,{value:b}),(j=this.linkService.eventBus)==null||j.dispatch("dispatcheventinsandbox",{source:this,detail:{id:n,name:"Keystroke",value:b,willCommit:!0,commitKey:1,selStart:g.selectionStart,selEnd:g.selectionEnd}}))}};this._dispatchEventFromSandbox(f,p)}),r.addEventListener("keydown",p=>{var v;u.commitKey=1;let f=-1;if(p.key==="Escape"?f=0:p.key==="Enter"&&!this.data.multiLine?f=2:p.key==="Tab"&&(u.commitKey=3),f===-1)return;const{value:y}=p.target;u.lastCommittedValue!==y&&(u.lastCommittedValue=y,u.userValue=y,(v=this.linkService.eventBus)==null||v.dispatch("dispatcheventinsandbox",{source:this,detail:{id:n,name:"Keystroke",value:y,willCommit:!0,commitKey:f,selStart:p.target.selectionStart,selEnd:p.target.selectionEnd}}))});const m=h;h=null,r.addEventListener("blur",p=>{var y,v;if(!u.focused||!p.relatedTarget)return;(y=this.data.actions)!=null&&y.Blur||(u.focused=!1);const{value:f}=p.target;u.userValue=f,u.lastCommittedValue!==f&&((v=this.linkService.eventBus)==null||v.dispatch("dispatcheventinsandbox",{source:this,detail:{id:n,name:"Keystroke",value:f,willCommit:!0,commitKey:u.commitKey,selStart:p.target.selectionStart,selEnd:p.target.selectionEnd}})),m(p)}),(i=this.data.actions)!=null&&i.Keystroke&&r.addEventListener("beforeinput",p=>{var C;u.lastCommittedValue=null;const{data:f,target:y}=p,{value:v,selectionStart:g,selectionEnd:b}=y;let j=g,S=b;switch(p.inputType){case"deleteWordBackward":{const E=v.substring(0,g).match(/\w*[^\w]*$/);E&&(j-=E[0].length);break}case"deleteWordForward":{const E=v.substring(g).match(/^[^\w]*\w*/);E&&(S+=E[0].length);break}case"deleteContentBackward":g===b&&(j-=1);break;case"deleteContentForward":g===b&&(S+=1);break}p.preventDefault(),(C=this.linkService.eventBus)==null||C.dispatch("dispatcheventinsandbox",{source:this,detail:{id:n,name:"Keystroke",value:v,change:f||"",willCommit:!1,selStart:j,selEnd:S}})}),this._setEventListeners(r,u,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],p=>p.target.value)}if(h&&r.addEventListener("blur",h),this.data.comb){const p=(this.data.rect[2]-this.data.rect[0])/c;r.classList.add("comb"),r.style.letterSpacing=`calc(${p}px * var(--scale-factor) - 1ch)`}}else r=document.createElement("div"),r.textContent=this.data.fieldValue,r.style.verticalAlign="middle",r.style.display="table-cell",this.data.hasOwnCanvas&&(r.hidden=!0);return this._setTextStyle(r),this._setBackgroundColor(r),this._setDefaultPropertiesFromJS(r),this.container.append(r),this.container}}class fHn extends gz{constructor(t){super(t,{isRenderable:!!t.data.hasOwnCanvas})}}class xHn extends gz{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 k9.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=Jae,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 Ies extends gz{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(k9.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=Jae,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 gHn extends Mes{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 yHn extends gz{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");k9.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=Jae;let i=this.data.combo&&this.data.options.length>0;this.data.combo||(a.size=this.data.options.length,this.data.multiSelect&&(a.multiple=!0)),a.addEventListener("resetform",u=>{const h=this.data.defaultFieldValue;for(const m of a.options)m.selected=m.value===h});for(const u of this.data.options){const h=document.createElement("option");h.textContent=u.displayValue,h.value=u.exportValue,r.value.includes(u.exportValue)&&(h.setAttribute("selected",!0),i=!1),a.append(h)}let l=null;if(i){const u=document.createElement("option");u.value=" ",u.setAttribute("hidden",!0),u.setAttribute("selected",!0),a.prepend(u),l=()=>{u.remove(),a.removeEventListener("input",l),l=null},a.addEventListener("input",l)}const o=u=>{const h=u?"value":"textContent",{options:m,multiple:p}=a;return p?Array.prototype.filter.call(m,f=>f.selected).map(f=>f[h]):m.selectedIndex===-1?null:m[m.selectedIndex][h]};let c=o(!1);const d=u=>{const h=u.target.options;return Array.prototype.map.call(h,m=>({displayValue:m.textContent,exportValue:m.value}))};return this.enableScripting&&this.hasJSActions?(a.addEventListener("updatefromsandbox",u=>{const h={value(m){l==null||l();const p=m.detail.value,f=new Set(Array.isArray(p)?p:[p]);for(const y of a.options)y.selected=f.has(y.value);t.setValue(n,{value:o(!0)}),c=o(!1)},multipleSelection(m){a.multiple=!0},remove(m){const p=a.options,f=m.detail.remove;p[f].selected=!1,a.remove(f),p.length>0&&Array.prototype.findIndex.call(p,v=>v.selected)===-1&&(p[0].selected=!0),t.setValue(n,{value:o(!0),items:d(m)}),c=o(!1)},clear(m){for(;a.length!==0;)a.remove(0);t.setValue(n,{value:null,items:[]}),c=o(!1)},insert(m){const{index:p,displayValue:f,exportValue:y}=m.detail.insert,v=a.children[p],g=document.createElement("option");g.textContent=f,g.value=y,v?v.before(g):a.append(g),t.setValue(n,{value:o(!0),items:d(m)}),c=o(!1)},items(m){const{items:p}=m.detail;for(;a.length!==0;)a.remove(0);for(const f of p){const{displayValue:y,exportValue:v}=f,g=document.createElement("option");g.textContent=y,g.value=v,a.append(g)}a.options.length>0&&(a.options[0].selected=!0),t.setValue(n,{value:o(!0),items:d(m)}),c=o(!1)},indices(m){const p=new Set(m.detail.indices);for(const f of m.target.options)f.selected=p.has(f.index);t.setValue(n,{value:o(!0)}),c=o(!1)},editable(m){m.target.disabled=!m.detail.editable}};this._dispatchEventFromSandbox(h,u)}),a.addEventListener("input",u=>{var p;const h=o(!0),m=o(!1);t.setValue(n,{value:h}),u.preventDefault(),(p=this.linkService.eventBus)==null||p.dispatch("dispatcheventinsandbox",{source:this,detail:{id:n,name:"Keystroke",value:c,change:m,changeEx:h,willCommit:!1,commitKey:1,keyDown:!1}})}),this._setEventListeners(a,null,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"],["input","Action"],["input","Validate"]],u=>u.target.value)):a.addEventListener("input",function(u){t.setValue(n,{value:o(!0)})}),this.data.combo&&this._setTextStyle(a),this._setBackgroundColor(a),this._setDefaultPropertiesFromJS(a),this.container.append(a),this.container}}class qKe extends mg{constructor(t){const{data:n,elements:r}=t;super(t,{isRenderable:mg._hasPopupData(n)}),this.elements=r,this.popup=null}render(){this.container.classList.add("popupAnnotation");const t=this.popup=new vHn({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=>`${Urt}${r}`).join(",")),this.container}}var $V,tMe,sMe,VV,_O,mx,hA,HV,One,zne,GV,mA,Ok,pA,Bne,fA,Une,wO,jO,fm,bCe,$Ke,Des,Res,Fes,Oes,_Ce,wCe,VKe;class vHn{constructor({container:t,color:n,elements:r,titleObj:a,modificationDate:i,contentsObj:l,richText:o,parent:c,rect:d,parentRect:u,open:h}){us(this,fm);us(this,$V,ts(this,fm,Fes).bind(this));us(this,tMe,ts(this,fm,VKe).bind(this));us(this,sMe,ts(this,fm,wCe).bind(this));us(this,VV,ts(this,fm,_Ce).bind(this));us(this,_O,null);us(this,mx,null);us(this,hA,null);us(this,HV,null);us(this,One,null);us(this,zne,null);us(this,GV,null);us(this,mA,!1);us(this,Ok,null);us(this,pA,null);us(this,Bne,null);us(this,fA,null);us(this,Une,null);us(this,wO,null);us(this,jO,!1);var m;Ut(this,mx,t),Ut(this,Une,a),Ut(this,hA,l),Ut(this,fA,o),Ut(this,zne,c),Ut(this,_O,n),Ut(this,Bne,d),Ut(this,GV,u),Ut(this,One,r),Ut(this,HV,Vrt.toDateObject(i)),this.trigger=r.flatMap(p=>p.getElementsToTriggerPopup());for(const p of this.trigger)p.addEventListener("click",ye(this,VV)),p.addEventListener("mouseenter",ye(this,sMe)),p.addEventListener("mouseleave",ye(this,tMe)),p.classList.add("popupTriggerArea");for(const p of r)(m=p.container)==null||m.addEventListener("keydown",ye(this,$V));ye(this,mx).hidden=!0,h&&ts(this,fm,_Ce).call(this)}render(){if(ye(this,Ok))return;const t=Ut(this,Ok,document.createElement("div"));if(t.className="popup",ye(this,_O)){const i=t.style.outlineColor=qo.makeHexColor(...ye(this,_O));CSS.supports("background-color","color-mix(in srgb, red 30%, white)")?t.style.backgroundColor=`color-mix(in srgb, ${i} 30%, white)`:t.style.backgroundColor=qo.makeHexColor(...ye(this,_O).map(o=>Math.floor(.7*(255-o)+o)))}const n=document.createElement("span");n.className="header";const r=document.createElement("h1");if(n.append(r),{dir:r.dir,str:r.textContent}=ye(this,Une),t.append(n),ye(this,HV)){const i=document.createElement("span");i.classList.add("popupDate"),i.setAttribute("data-l10n-id","pdfjs-annotation-date-time-string"),i.setAttribute("data-l10n-args",JSON.stringify({dateObj:ye(this,HV).valueOf()})),n.append(i)}const a=ye(this,fm,bCe);if(a)Tes.render({xfaHtml:a,intent:"richText",div:t}),t.lastChild.classList.add("richText","popupContent");else{const i=this._formatContents(ye(this,hA));t.append(i)}ye(this,mx).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)&&ts(this,Kne,HKe).call(this)}),!r.popupRef&&this.hasPopupData?this._createPopup():a.classList.add("popupTriggerArea"),n.append(a),n}getElementsToTriggerPopup(){return ye(this,Wne)}addHighlightArea(){this.container.classList.add("highlightArea")}}Wne=new WeakMap,Kne=new WeakSet,HKe=function(){var n;(n=this.downloadManager)==null||n.openOrDownloadData(this.content,this.filename)};var Yne,NO,kO,Zne,L9,$es,GKe;class EHn{constructor({div:t,accessibilityManager:n,annotationCanvasMap:r,annotationEditorUIManager:a,page:i,viewport:l,structTreeLayer:o}){us(this,L9);us(this,Yne,null);us(this,NO,null);us(this,kO,new Map);us(this,Zne,null);this.div=t,Ut(this,Yne,n),Ut(this,NO,r),Ut(this,Zne,o||null),this.page=i,this.viewport=l,this.zIndex=0,this._annotationEditorUIManager=a}hasEditableAnnotations(){return ye(this,kO).size>0}async render(t){var l;const{annotations:n}=t,r=this.div;j9(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 Xrt,annotationStorage:t.annotationStorage||new Grt,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===s0.POPUP;if(c){const h=a.get(o.id);if(!h)continue;i.elements=h}else{const{width:h,height:m}=rE(o.rect);if(h<=0||m<=0)continue}i.data=o;const d=hHn.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 ts(this,L9,$es).call(this,u,o.id),d._isEditable&&(ye(this,kO).set(d.data.id,d),(l=this._annotationEditorUIManager)==null||l.renderAnnotationElement(d))}ts(this,L9,GKe).call(this)}update({viewport:t}){const n=this.div;this.viewport=t,j9(n,{rotation:t.rotation}),ts(this,L9,GKe).call(this),n.hidden=!1}getEditableAnnotations(){return Array.from(ye(this,kO).values())}getEditableAnnotation(t){return ye(this,kO).get(t)}}Yne=new WeakMap,NO=new WeakMap,kO=new WeakMap,Zne=new WeakMap,L9=new WeakSet,$es=async function(t,n){var l,o;const r=t.firstChild||t,a=r.id=`${Urt}${n}`,i=await((l=ye(this,Zne))==null?void 0:l.getAriaAttributes(a));if(i)for(const[c,d]of i)r.setAttribute(c,d);this.div.append(t),(o=ye(this,Yne))==null||o.moveElementInDOM(this.div,t,r,!1)},GKe=function(){if(!ye(this,NO))return;const t=this.div;for(const[n,r]of ye(this,NO)){const a=t.querySelector(`[data-annotation-id="${n}"]`);if(!a)continue;r.className="annotationContent";const{firstChild:i}=a;i?i.nodeName==="CANVAS"?i.replaceWith(r):i.classList.contains("annotationContent")?i.after(r):i.before(r):a.append(r)}ye(this,NO).clear()};const mde=/\r\n?|\n/g;var zk,Dw,Xne,SO,Rw,Bg,Ves,Hes,Ges,jCe,mE,NCe,kCe,Wes,KKe,Kes;const Gm=class Gm extends Oh{constructor(n){super({...n,name:"freeTextEditor"});us(this,Bg);us(this,zk);us(this,Dw,"");us(this,Xne,`${this.id}-editor`);us(this,SO,null);us(this,Rw);Ut(this,zk,n.color||Gm._defaultColor||Oh._defaultLineColor),Ut(this,Rw,n.fontSize||Gm._defaultFontSize)}static get _keyboardManager(){const n=Gm.prototype,r=l=>l.isEmpty(),a=N9.TRANSLATE_SMALL,i=N9.TRANSLATE_BIG;return fu(this,"_keyboardManager",new Qae([[["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){Oh.initialize(n,r);const a=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(a.getPropertyValue("--freetext-padding"))}static updateDefaultParams(n,r){switch(n){case bc.FREETEXT_SIZE:Gm._defaultFontSize=r;break;case bc.FREETEXT_COLOR:Gm._defaultColor=r;break}}updateParams(n,r){switch(n){case bc.FREETEXT_SIZE:ts(this,Bg,Ves).call(this,r);break;case bc.FREETEXT_COLOR:ts(this,Bg,Hes).call(this,r);break}}static get defaultPropertiesToUpdate(){return[[bc.FREETEXT_SIZE,Gm._defaultFontSize],[bc.FREETEXT_COLOR,Gm._defaultColor||Oh._defaultLineColor]]}get propertiesToUpdate(){return[[bc.FREETEXT_SIZE,ye(this,Rw)],[bc.FREETEXT_COLOR,ye(this,zk)]]}_translateEmpty(n,r){this._uiManager.translateSelectedEditors(n,r,!0)}getInitialTranslation(){const n=this.parentScale;return[-Gm._internalPadding*n,-(Gm._internalPadding+ye(this,Rw))*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(Zc.FREETEXT),super.enableEditMode(),this.overlayDiv.classList.remove("enabled"),this.editorDiv.contentEditable=!0,this._isDraggable=!1,this.div.removeAttribute("aria-activedescendant"),Ut(this,SO,new AbortController);const n=this._uiManager.combinedSignal(ye(this,SO));this.editorDiv.addEventListener("keydown",this.editorDivKeydown.bind(this),{signal:n}),this.editorDiv.addEventListener("focus",this.editorDivFocus.bind(this),{signal:n}),this.editorDiv.addEventListener("blur",this.editorDivBlur.bind(this),{signal:n}),this.editorDiv.addEventListener("input",this.editorDivInput.bind(this),{signal:n}),this.editorDiv.addEventListener("paste",this.editorDivPaste.bind(this),{signal:n})}disableEditMode(){var n;this.isInEditMode()&&(this.parent.setEditingState(!0),super.disableEditMode(),this.overlayDiv.classList.add("enabled"),this.editorDiv.contentEditable=!1,this.div.setAttribute("aria-activedescendant",ye(this,Xne)),this._isDraggable=!0,(n=ye(this,SO))==null||n.abort(),Ut(this,SO,null),this.div.focus({preventScroll:!0}),this.isEditing=!1,this.parent.div.classList.add("freetextEditing"))}focusin(n){this._focusEventsAllowed&&(super.focusin(n),n.target!==this.editorDiv&&this.editorDiv.focus())}onceAdded(){var n;this.width||(this.enableEditMode(),this.editorDiv.focus(),(n=this._initialOptions)!=null&&n.isCentered&&this.center(),this._initialOptions=null)}isEmpty(){return!this.editorDiv||this.editorDiv.innerText.trim()===""}remove(){this.isEditing=!1,this.parent&&(this.parent.setEditingState(!0),this.parent.div.classList.add("freetextEditing")),super.remove()}commit(){if(!this.isInEditMode())return;super.commit(),this.disableEditMode();const n=ye(this,Dw),r=Ut(this,Dw,ts(this,Bg,Ges).call(this).trimEnd());if(n===r)return;const a=i=>{if(Ut(this,Dw,i),!i){this.remove();return}ts(this,Bg,kCe).call(this),this._uiManager.rebuild(this),ts(this,Bg,jCe).call(this)};this.addCommands({cmd:()=>{a(r)},undo:()=>{a(n)},mustExec:!1}),ts(this,Bg,jCe).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){Gm._keyboardManager.exec(this,n)}editorDivFocus(n){this.isEditing=!0}editorDivBlur(n){this.isEditing=!1}editorDivInput(n){this.parent.div.classList.toggle("freetextEditing",this.isEmpty())}disableEditing(){this.editorDiv.setAttribute("role","comment"),this.editorDiv.removeAttribute("aria-multiline")}enableEditing(){this.editorDiv.setAttribute("role","textbox"),this.editorDiv.setAttribute("aria-multiline",!0)}render(){if(this.div)return this.div;let n,r;this.width&&(n=this.x,r=this.y),super.render(),this.editorDiv=document.createElement("div"),this.editorDiv.className="internal",this.editorDiv.setAttribute("id",ye(this,Xne)),this.editorDiv.setAttribute("data-l10n-id","pdfjs-free-text2"),this.editorDiv.setAttribute("data-l10n-attrs","default-content"),this.enableEditing(),this.editorDiv.contentEditable=!0;const{style:a}=this.editorDiv;if(a.fontSize=`calc(${ye(this,Rw)}px * var(--scale-factor))`,a.color=ye(this,zk),this.div.append(this.editorDiv),this.overlayDiv=document.createElement("div"),this.overlayDiv.classList.add("overlay","enabled"),this.div.append(this.overlayDiv),e6e(this,this.div,["dblclick","keydown"]),this.width){const[i,l]=this.parentDimensions;if(this.annotationElementId){const{position:o}=this._initialData;let[c,d]=this.getInitialTranslation();[c,d]=this.pageTranslationToScreen(c,d);const[u,h]=this.pageDimensions,[m,p]=this.pageTranslation;let f,y;switch(this.rotation){case 0:f=n+(o[0]-m)/u,y=r+this.height-(o[1]-p)/h;break;case 90:f=n+(o[0]-m)/u,y=r-(o[1]-p)/h,[c,d]=[d,-c];break;case 180:f=n-this.width+(o[0]-m)/u,y=r-(o[1]-p)/h,[c,d]=[-c,-d];break;case 270:f=n+(o[0]-m-this.height*h)/u,y=r+(o[1]-p-this.width*u)/h,[c,d]=[-d,c];break}this.setAt(f*i,y*l,c,d)}else this.setAt(n*i,r*l,this.width*i,this.height*l);ts(this,Bg,kCe).call(this),this._isDraggable=!0,this.editorDiv.contentEditable=!1}else this._isDraggable=!1,this.editorDiv.contentEditable=!0;return this.div}editorDivPaste(n){var f,y,v;const r=n.clipboardData||window.clipboardData,{types:a}=r;if(a.length===1&&a[0]==="text/plain")return;n.preventDefault();const i=ts(f=Gm,mE,KKe).call(f,r.getData("text")||"").replaceAll(mde,` `);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 g=c.parentElement;if(h.push(c.nodeValue.slice(d).replaceAll(mde,"")),g!==this.editorDiv){let b=u;for(const j of this.editorDiv.childNodes){if(j===g){b=h;continue}b.push(ts(y=Gm,mE,NCe).call(y,j))}}u.push(c.nodeValue.slice(0,d).replaceAll(mde,""))}else if(c===this.editorDiv){let g=u,b=0;for(const j of this.editorDiv.childNodes)b++===d&&(g=h),g.push(ts(v=Gm,mE,NCe).call(v,j))}Ut(this,Dw,`${u.join(` `)}${i}${h.join(` `)}`),ts(this,Bg,kCe).call(this);const m=new Range;let p=u.reduce((g,b)=>g+b.length,0);for(const{firstChild:g}of this.editorDiv.childNodes)if(g.nodeType===Node.TEXT_NODE){const b=g.nodeValue.length;if(p<=b){m.setStart(g,p),m.setEnd(g,p);break}p-=b}l.removeAllRanges(),l.addRange(m)}get contentDiv(){return this.editorDiv}static async deserialize(n,r,a){var o;let i=null;if(n instanceof zes){const{data:{defaultAppearanceData:{fontSize:c,fontColor:d},rect:u,rotation:h,id:m,popupRef:p},textContent:f,textPosition:y,parent:{page:{pageNumber:v}}}=n;if(!f||f.length===0)return null;i=n={annotationType:Zc.FREETEXT,color:Array.from(d),fontSize:c,value:f.join(` `),position:y,pageIndex:v-1,rect:u.slice(0),rotation:h,id:m,deleted:!1,popupRef:p}}const l=await super.deserialize(n,r,a);return Ut(l,Rw,n.fontSize),Ut(l,zk,qo.makeHexColor(...n.color)),Ut(l,Dw,ts(o=Gm,mE,KKe).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=Gm._internalPadding*this.parentScale,a=this.getRect(r,r),i=Oh._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:ye(this,zk)),l={annotationType:Zc.FREETEXT,color:i,fontSize:ye(this,Rw),value:ts(this,Bg,Wes).call(this),pageIndex:this.pageIndex,rect:a,rotation:this.rotation,structTreeParentId:this._structTreeParentId};return n?l:this.annotationElementId&&!ts(this,Bg,Kes).call(this,l)?null:(l.id=this.annotationElementId,l)}renderAnnotationElement(n){const r=super.renderAnnotationElement(n);if(this.deleted)return r;const{style:a}=r;a.fontSize=`calc(${ye(this,Rw)}px * var(--scale-factor))`,a.color=ye(this,zk),r.replaceChildren();for(const l of ye(this,Dw).split(` `)){const o=document.createElement("div");o.append(l?document.createTextNode(l):document.createElement("br")),r.append(o)}const i=Gm._internalPadding*this.parentScale;return n.updateEdited({rect:this.getRect(i,i),popupContent:ye(this,Dw)}),r}resetAnnotationElement(n){super.resetAnnotationElement(n),n.resetEdited()}};zk=new WeakMap,Dw=new WeakMap,Xne=new WeakMap,SO=new WeakMap,Rw=new WeakMap,Bg=new WeakSet,Ves=function(n){const r=i=>{this.editorDiv.style.fontSize=`calc(${i}px * var(--scale-factor))`,this.translate(0,-(i-ye(this,Rw))*this.parentScale),Ut(this,Rw,i),ts(this,Bg,jCe).call(this)},a=ye(this,Rw);this.addCommands({cmd:r.bind(this,n),undo:r.bind(this,a),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:bc.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})},Hes=function(n){const r=i=>{Ut(this,zk,this.editorDiv.style.color=i)},a=ye(this,zk);this.addCommands({cmd:r.bind(this,n),undo:r.bind(this,a),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:bc.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})},Ges=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(ts(a=Gm,mE,NCe).call(a,i)),r=i);return n.join(` `)},jCe=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()},mE=new WeakSet,NCe=function(n){return(n.nodeType===Node.TEXT_NODE?n.nodeValue:n.innerText).replaceAll(mde,"")},kCe=function(){if(this.editorDiv.replaceChildren(),!!ye(this,Dw))for(const n of ye(this,Dw).split(` `)){const r=document.createElement("div");r.append(n?document.createTextNode(n):document.createElement("br")),this.editorDiv.append(r)}},Wes=function(){return ye(this,Dw).replaceAll(" "," ")},KKe=function(n){return n.replaceAll(" "," ")},Kes=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},us(Gm,mE),Pr(Gm,"_freeTextDefaultContent",""),Pr(Gm,"_internalPadding",0),Pr(Gm,"_defaultColor",null),Pr(Gm,"_defaultFontSize",10),Pr(Gm,"_type","freetext"),Pr(Gm,"_editorType",Zc.FREETEXT);let WKe=Gm;class Yes{toSVGPath(){Sp("Abstract method `toSVGPath` must be implemented.")}get box(){Sp("Abstract getter `box` must be implemented.")}serialize(t,n){Sp("Abstract method `serialize` must be implemented.")}get classNamesForDrawing(){Sp("Abstract getter `classNamesForDrawing` must be implemented.")}get classNamesForOutlining(){Sp("Abstract getter `classNamesForOutlining` must be implemented.")}get mustRemoveSelfIntersections(){return!1}}var Fw,Bk,WV,KV,c4,Cd,CO,AO,Qne,Jne,YV,ZV,oM,ere,nMe,rMe,k0,UX,Zes,Xes,Qes,Jes,ets,tts;const G3=class G3{constructor({x:t,y:n},r,a,i,l,o=0){us(this,k0);us(this,Fw);us(this,Bk,[]);us(this,WV);us(this,KV);us(this,c4,[]);us(this,Cd,new Float64Array(18));us(this,CO);us(this,AO);us(this,Qne);us(this,Jne);us(this,YV);us(this,ZV);us(this,oM,[]);Ut(this,Fw,r),Ut(this,ZV,i*a),Ut(this,KV,l),ye(this,Cd).set([NaN,NaN,NaN,NaN,t,n],6),Ut(this,WV,o),Ut(this,Jne,ye(G3,ere)*a),Ut(this,Qne,ye(G3,rMe)*a),Ut(this,YV,a),ye(this,oM).push(t,n)}isEmpty(){return isNaN(ye(this,Cd)[8])}add({x:t,y:n}){var I;Ut(this,CO,t),Ut(this,AO,n);const[r,a,i,l]=ye(this,Fw);let[o,c,d,u]=ye(this,Cd).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 ts(this,k0,Xes).call(this,r),r.join(" ")}newFreeDrawOutline(t,n,r,a,i,l){return new sts(t,n,r,a,i,l)}getOutlines(){var h;const t=ye(this,c4),n=ye(this,Bk),r=ye(this,Cd),[a,i,l,o]=ye(this,Fw),c=new Float64Array((((h=ye(this,oM))==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 ts(this,k0,ets).call(this,d,u),this.newFreeDrawOutline(d,c,ye(this,Fw),ye(this,YV),ye(this,WV),ye(this,KV))}};Fw=new WeakMap,Bk=new WeakMap,WV=new WeakMap,KV=new WeakMap,c4=new WeakMap,Cd=new WeakMap,CO=new WeakMap,AO=new WeakMap,Qne=new WeakMap,Jne=new WeakMap,YV=new WeakMap,ZV=new WeakMap,oM=new WeakMap,ere=new WeakMap,nMe=new WeakMap,rMe=new WeakMap,k0=new WeakSet,UX=function(){const t=ye(this,Cd).subarray(4,6),n=ye(this,Cd).subarray(16,18),[r,a,i,l]=ye(this,Fw);return[(ye(this,CO)+(t[0]-n[0])/2-r)/i,(ye(this,AO)+(t[1]-n[1])/2-a)/l,(ye(this,CO)+(n[0]-t[0])/2-r)/i,(ye(this,AO)+(n[1]-t[1])/2-a)/l]},Zes=function(){const[t,n,r,a]=ye(this,Fw),[i,l,o,c]=ts(this,k0,UX).call(this);return`M${(ye(this,Cd)[2]-t)/r} ${(ye(this,Cd)[3]-n)/a} L${(ye(this,Cd)[4]-t)/r} ${(ye(this,Cd)[5]-n)/a} L${i} ${l} L${o} ${c} L${(ye(this,Cd)[16]-t)/r} ${(ye(this,Cd)[17]-n)/a} L${(ye(this,Cd)[14]-t)/r} ${(ye(this,Cd)[15]-n)/a} Z`},Xes=function(t){const n=ye(this,Bk);t.push(`L${n[4]} ${n[5]} Z`)},Qes=function(t){const[n,r,a,i]=ye(this,Fw),l=ye(this,Cd).subarray(4,6),o=ye(this,Cd).subarray(16,18),[c,d,u,h]=ts(this,k0,UX).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}`)},Jes=function(t){const n=ye(this,Cd),[r,a,i,l]=ye(this,Fw),[o,c,d,u]=ts(this,k0,UX).call(this),h=new Float64Array(36);return h.set([NaN,NaN,NaN,NaN,(n[2]-r)/i,(n[3]-a)/l,NaN,NaN,NaN,NaN,(n[4]-r)/i,(n[5]-a)/l,NaN,NaN,NaN,NaN,o,c,NaN,NaN,NaN,NaN,d,u,NaN,NaN,NaN,NaN,(n[16]-r)/i,(n[17]-a)/l,NaN,NaN,NaN,NaN,(n[14]-r)/i,(n[15]-a)/l],0),this.newFreeDrawOutline(h,t,ye(this,Fw),ye(this,YV),ye(this,WV),ye(this,KV))},ets=function(t,n){const r=ye(this,Bk);return t.set([NaN,NaN,NaN,NaN,r[4],r[5]],n),n+=6},tts=function(t,n){const r=ye(this,Cd).subarray(4,6),a=ye(this,Cd).subarray(16,18),[i,l,o,c]=ye(this,Fw),[d,u,h,m]=ts(this,k0,UX).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},us(G3,ere,8),us(G3,nMe,2),us(G3,rMe,ye(G3,ere)+ye(G3,nMe));let s6e=G3;var XV,EO,xA,tre,Ow,sre,Wx,T_,qX,$X,nts;class sts extends Yes{constructor(n,r,a,i,l,o){super();us(this,T_);us(this,XV);us(this,EO,null);us(this,xA);us(this,tre);us(this,Ow);us(this,sre);us(this,Wx);Ut(this,Wx,n),Ut(this,Ow,r),Ut(this,XV,a),Ut(this,sre,i),Ut(this,xA,l),Ut(this,tre,o),ts(this,T_,nts).call(this,o);const{x:c,y:d,width:u,height:h}=ye(this,EO);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 ye(this,lM))n[3]?(t.push(...ts(this,Eb,YKe).call(this,n)),ts(this,Eb,ats).call(this,n)):(ts(this,Eb,its).call(this,n),t.push(...ts(this,Eb,YKe).call(this,n)));return ts(this,Eb,rts).call(this,t)}}nre=new WeakMap,lM=new WeakMap,Uk=new WeakMap,Eb=new WeakSet,rts=function(t){const n=[],r=new Set;for(const l of t){const[o,c,d]=l;n.push([o,c,l],[o,d,l])}n.sort((l,o)=>l[1]-o[1]||l[0]-o[0]);for(let l=0,o=n.length;l0;){const l=r.values().next().value;let[o,c,d,u,h]=l;r.delete(l);let m=o,p=c;for(i=[o,d],a.push(i);;){let f;if(r.has(u))f=u;else if(r.has(h))f=h;else break;r.delete(f),[o,c,d,u,h]=f,m!==o&&(i.push(m,p,o,p===c?c:d),m=o),p=p===c?d:c}i.push(m,p)}return new THn(a,ye(this,nre))},SCe=function(t){const n=ye(this,Uk);let r=0,a=n.length-1;for(;r<=a;){const i=r+a>>1,l=n[i][0];if(l===t)return i;l=0;a--){const[i,l]=ye(this,Uk)[a];if(i!==t)break;if(i===t&&l===n){ye(this,Uk).splice(a,1);return}}},YKe=function(t){const[n,r,a]=t,i=[[n,r,a]],l=ts(this,Eb,SCe).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 rre,QV;class THn extends Yes{constructor(n,r){super();us(this,rre);us(this,QV);Ut(this,QV,n),Ut(this,rre,r)}toSVGPath(){const n=[];for(const r of ye(this,QV)){let[a,i]=r;n.push(`M${a} ${i}`);for(let l=2;l-1?(Ut(this,m_,!0),ts(this,Uc,CCe).call(this,n),ts(this,Uc,KR).call(this)):ye(this,gA)&&(Ut(this,sH,n.anchorNode),Ut(this,cre,n.anchorOffset),Ut(this,dre,n.focusNode),Ut(this,ure,n.focusOffset),ts(this,Uc,eYe).call(this),ts(this,Uc,KR).call(this),this.rotate(this.rotation))}static get _keyboardManager(){const n=rh.prototype;return fu(this,"_keyboardManager",new Qae([[["ArrowLeft","mac+ArrowLeft"],n._moveCaret,{args:[0]}],[["ArrowRight","mac+ArrowRight"],n._moveCaret,{args:[1]}],[["ArrowUp","mac+ArrowUp"],n._moveCaret,{args:[2]}],[["ArrowDown","mac+ArrowDown"],n._moveCaret,{args:[3]}]]))}get telemetryInitialData(){return{action:"added",type:ye(this,m_)?"free_highlight":"highlight",color:this._uiManager.highlightColorNames.get(this.color),thickness:ye(this,R2),methodOfCreation:ye(this,hre)}}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;Oh.initialize(n,r),rh._defaultColor||(rh._defaultColor=((a=r.highlightColors)==null?void 0:a.values().next().value)||"#fff066")}static updateDefaultParams(n,r){switch(n){case bc.HIGHLIGHT_DEFAULT_COLOR:rh._defaultColor=r;break;case bc.HIGHLIGHT_THICKNESS:rh._defaultThickness=r;break}}translateInPage(n,r){}get toolbarPosition(){return ye(this,rH)}updateParams(n,r){switch(n){case bc.HIGHLIGHT_COLOR:ts(this,Uc,lts).call(this,r);break;case bc.HIGHLIGHT_THICKNESS:ts(this,Uc,cts).call(this,r);break}}static get defaultPropertiesToUpdate(){return[[bc.HIGHLIGHT_DEFAULT_COLOR,rh._defaultColor],[bc.HIGHLIGHT_THICKNESS,rh._defaultThickness]]}get propertiesToUpdate(){return[[bc.HIGHLIGHT_COLOR,this.color||rh._defaultColor],[bc.HIGHLIGHT_THICKNESS,ye(this,R2)||rh._defaultThickness],[bc.HIGHLIGHT_FREE,ye(this,m_)]]}async addEditToolbar(){const n=await super.addEditToolbar();return n?(this._uiManager.highlightColors&&(Ut(this,nH,new n6e({editor:this})),n.addColorPicker(ye(this,nH))),n):null}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}fixAndSetPosition(){return super.fixAndSetPosition(ts(this,Uc,VX).call(this))}getBaseTranslation(){return[0,0]}getRect(n,r){return super.getRect(n,r,ts(this,Uc,VX).call(this))}onceAdded(){this.annotationElementId||this.parent.addUndoableEditor(this),this.div.focus()}remove(){ts(this,Uc,tYe).call(this),this._reportTelemetry({action:"deleted"}),super.remove()}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(ts(this,Uc,KR).call(this),this.isAttachedToDOM||this.parent.add(this)))}setParent(n){var a;let r=!1;this.parent&&!n?ts(this,Uc,tYe).call(this):n&&(ts(this,Uc,KR).call(this,n),r=!this.parent&&((a=this.div)==null?void 0:a.classList.contains("selectedEditor"))),super.setParent(n),this.show(this._isVisible),r&&this.select()}rotate(n){var i,l,o;const{drawLayer:r}=this.parent;let a;ye(this,m_)?(n=(n-this.rotation+360)%360,a=ts(i=rh,tN,MU).call(i,ye(this,Vk).box,n)):a=ts(l=rh,tN,MU).call(l,this,n),r.rotate(ye(this,n1),n),r.rotate(ye(this,o0),n),r.updateBox(ye(this,n1),a),r.updateBox(ye(this,o0),ts(o=rh,tN,MU).call(o,ye(this,D2).box,n))}render(){if(this.div)return this.div;const n=super.render();ye(this,aH)&&(n.setAttribute("aria-label",ye(this,aH)),n.setAttribute("role","mark")),ye(this,m_)?n.classList.add("free"):this.div.addEventListener("keydown",ts(this,Uc,uts).bind(this),{signal:this._uiManager._signal});const r=Ut(this,PO,document.createElement("div"));n.append(r),r.setAttribute("aria-hidden","true"),r.className="internal",r.style.clipPath=ye(this,MO);const[a,i]=this.parentDimensions;return this.setDims(this.width*a,this.height*i),e6e(this,ye(this,PO),["pointerover","pointerleave"]),this.enableEditing(),n}pointerover(){this.isSelected||this.parent.drawLayer.addClass(ye(this,o0),"hovered")}pointerleave(){this.isSelected||this.parent.drawLayer.removeClass(ye(this,o0),"hovered")}_moveCaret(n){switch(this.parent.unselect(this),n){case 0:case 2:ts(this,Uc,ACe).call(this,!0);break;case 1:case 3:ts(this,Uc,ACe).call(this,!1);break}}select(){var n,r;super.select(),ye(this,o0)&&((n=this.parent)==null||n.drawLayer.removeClass(ye(this,o0),"hovered"),(r=this.parent)==null||r.drawLayer.addClass(ye(this,o0),"selected"))}unselect(){var n;super.unselect(),ye(this,o0)&&((n=this.parent)==null||n.drawLayer.removeClass(ye(this,o0),"selected"),ye(this,m_)||ts(this,Uc,ACe).call(this,!1))}get _mustFixPosition(){return!ye(this,m_)}show(n=this._isVisible){super.show(n),this.parent&&(this.parent.drawLayer.show(ye(this,n1),n),this.parent.drawLayer.show(ye(this,o0),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=y=>{y.preventDefault(),y.stopPropagation()},f=y=>{h.abort(),ts(this,tN,fts).call(this,n,y)};window.addEventListener("blur",f,{signal:m}),window.addEventListener("pointerup",f,{signal:m}),window.addEventListener("pointerdown",p,{capture:!0,passive:!1,signal:m}),window.addEventListener("contextmenu",PN,{signal:m}),a.addEventListener("pointermove",ts(this,tN,pts).bind(this,n),{signal:m}),this._freeHighlight=new ZKe({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 y,v,g,b;let i=null;if(n instanceof Ues){const{data:{quadPoints:j,rect:S,rotation:C,id:E,color:P,opacity:M,popupRef:I},parent:{page:{pageNumber:D}}}=n;i=n={annotationType:Zc.HIGHLIGHT,color:Array.from(P),opacity:M,quadPoints:j,boxes:null,pageIndex:D-1,rect:S.slice(0),rotation:C,id:E,deleted:!1,popupRef:I}}else if(n instanceof Qrt){const{data:{inkLists:j,rect:S,rotation:C,id:E,color:P,borderStyle:{rawWidth:M},popupRef:I},parent:{page:{pageNumber:D}}}=n;i=n={annotationType:Zc.HIGHLIGHT,color:Array.from(P),thickness:M,inkLists:j,boxes:null,pageIndex:D-1,rect:S.slice(0),rotation:C,id:E,deleted:!1,popupRef:I}}const{color:l,quadPoints:o,inkLists:c,opacity:d}=n,u=await super.deserialize(n,r,a);u.color=qo.makeHexColor(...l),Ut(u,yA,d||1),c&&Ut(u,R2,n.thickness),u.annotationElementId=n.id||null,u._initialData=i;const[h,m]=u.pageDimensions,[p,f]=u.pageTranslation;if(o){const j=Ut(u,gA,[]);for(let S=0;S=0)Ut(this,n1,r),Ut(this,MO,a),this.parent.drawLayer.finalizeLine(r,n),Ut(this,o0,this.parent.drawLayer.drawOutline(ye(this,D2)));else if(this.parent){const p=this.parent.viewport.rotation;this.parent.drawLayer.updateLine(ye(this,n1),n),this.parent.drawLayer.updateBox(ye(this,n1),ts(h=rh,tN,MU).call(h,ye(this,Vk).box,(p-this.rotation+360)%360)),this.parent.drawLayer.updateLine(ye(this,o0),ye(this,D2)),this.parent.drawLayer.updateBox(ye(this,o0),ts(m=rh,tN,MU).call(m,ye(this,D2).box,p))}const{x:l,y:o,width:c,height:d}=n.box;switch(this.rotation){case 0:this.x=l,this.y=o,this.width=c,this.height=d;break;case 90:{const[p,f]=this.parentDimensions;this.x=o,this.y=1-l,this.width=c*f/p,this.height=d*p/f;break}case 180:this.x=1-l,this.y=1-o,this.width=c,this.height=d;break;case 270:{const[p,f]=this.parentDimensions;this.x=1-o,this.y=l,this.width=c*f/p,this.height=d*p/f;break}}const{lastPoint:u}=ye(this,D2).box;Ut(this,rH,[(u[0]-l)/c,(u[1]-o)/d])},lts=function(n){const r=(l,o)=>{var c,d,u;this.color=l,(c=this.parent)==null||c.drawLayer.changeColor(ye(this,n1),l),(d=ye(this,nH))==null||d.updateColor(l),Ut(this,yA,o),(u=this.parent)==null||u.drawLayer.changeOpacity(ye(this,n1),o)},a=this.color,i=ye(this,yA);this.addCommands({cmd:r.bind(this,n,rh._defaultOpacity),undo:r.bind(this,a,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:bc.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"color_changed",color:this._uiManager.highlightColorNames.get(n)},!0)},cts=function(n){const r=ye(this,R2),a=i=>{Ut(this,R2,i),ts(this,Uc,dts).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:bc.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"thickness_changed",thickness:n},!0)},dts=function(n){if(!ye(this,m_))return;ts(this,Uc,CCe).call(this,{highlightOutlines:ye(this,Vk).getNewOutline(n/2)}),this.fixAndSetPosition();const[r,a]=this.parentDimensions;this.setDims(this.width*r,this.height*a)},tYe=function(){ye(this,n1)===null||!this.parent||(this.parent.drawLayer.remove(ye(this,n1)),Ut(this,n1,null),this.parent.drawLayer.remove(ye(this,o0)),Ut(this,o0,null))},KR=function(n=this.parent){ye(this,n1)===null&&({id:X0(this,n1)._,clipPathId:X0(this,MO)._}=n.drawLayer.draw(ye(this,Vk),this.color,ye(this,yA)),Ut(this,o0,n.drawLayer.drawOutline(ye(this,D2))),ye(this,PO)&&(ye(this,PO).style.clipPath=ye(this,MO)))},tN=new WeakSet,MU=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}},uts=function(n){rh._keyboardManager.exec(this,n)},ACe=function(n){if(!ye(this,sH))return;const r=window.getSelection();n?r.setPosition(ye(this,sH),ye(this,cre)):r.setPosition(ye(this,dre),ye(this,ure))},VX=function(){return ye(this,m_)?this.rotation:0},hts=function(){if(ye(this,m_))return null;const[n,r]=this.pageDimensions,[a,i]=this.pageTranslation,l=ye(this,gA),o=new Float32Array(l.length*8);let c=0;for(const{x:d,y:u,width:h,height:m}of l){const p=d*n+a,f=(1-u-m)*r+i;o[c]=o[c+4]=p,o[c+1]=o[c+3]=f,o[c+2]=o[c+6]=p+h*n,o[c+5]=o[c+7]=f+m*r,c+=8}return o},mts=function(n){return ye(this,Vk).serialize(n,ts(this,Uc,VX).call(this))},pts=function(n,r){this._freeHighlight.add(r)&&n.drawLayer.updatePath(this._freeHighlightId,this._freeHighlight)},fts=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=""},xts=function(n){const{color:r}=this._initialData;return n.color.some((a,i)=>a!==r[i])},us(rh,tN),Pr(rh,"_defaultColor",null),Pr(rh,"_defaultOpacity",1),Pr(rh,"_defaultThickness",12),Pr(rh,"_type","highlight"),Pr(rh,"_editorType",Zc.HIGHLIGHT),Pr(rh,"_freeHighlightId",-1),Pr(rh,"_freeHighlight",null),Pr(rh,"_freeHighlightClipId","");let r6e=rh;var LO,IO,d4,vA,F2,DO,RO,FO,bA,iH,OO,zO,dM,Ei,gts,yts,vts,bts,nYe,_ts,rYe,wts,jts,Nts,kts,Sts,YR,aYe,iYe,oYe,ECe,TCe,PU,lYe,MCe,ME,Cts,cYe,Ats,Ets,dYe,PCe,HX;const _f=class _f extends Oh{constructor(n){super({...n,name:"inkEditor"});us(this,Ei);us(this,LO,0);us(this,IO,0);us(this,d4,null);us(this,vA,new Path2D);us(this,F2,!1);us(this,DO,null);us(this,RO,!1);us(this,FO,!1);us(this,bA,null);us(this,iH,null);us(this,OO,0);us(this,zO,0);us(this,dM,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){Oh.initialize(n,r)}static updateDefaultParams(n,r){switch(n){case bc.INK_THICKNESS:_f._defaultThickness=r;break;case bc.INK_COLOR:_f._defaultColor=r;break;case bc.INK_OPACITY:_f._defaultOpacity=r/100;break}}updateParams(n,r){switch(n){case bc.INK_THICKNESS:ts(this,Ei,gts).call(this,r);break;case bc.INK_COLOR:ts(this,Ei,yts).call(this,r);break;case bc.INK_OPACITY:ts(this,Ei,vts).call(this,r);break}}static get defaultPropertiesToUpdate(){return[[bc.INK_THICKNESS,_f._defaultThickness],[bc.INK_COLOR,_f._defaultColor||Oh._defaultLineColor],[bc.INK_OPACITY,Math.round(_f._defaultOpacity*100)]]}get propertiesToUpdate(){return[[bc.INK_THICKNESS,this.thickness||_f._defaultThickness],[bc.INK_COLOR,this.color||_f._defaultColor||Oh._defaultLineColor],[bc.INK_OPACITY,Math.round(100*(this.opacity??_f._defaultOpacity))]]}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.canvas||(ts(this,Ei,ECe).call(this),ts(this,Ei,TCe).call(this)),this.isAttachedToDOM||(this.parent.add(this),ts(this,Ei,PU).call(this)),ts(this,Ei,HX).call(this)))}remove(){var n;this.canvas!==null&&(this.isEmpty()||this.commit(),this.canvas.width=this.canvas.height=0,this.canvas.remove(),this.canvas=null,ye(this,d4)&&(clearTimeout(ye(this,d4)),Ut(this,d4,null)),(n=ye(this,bA))==null||n.disconnect(),Ut(this,bA,null),super.remove())}setParent(n){!this.parent&&n?this._uiManager.removeShouldRescale(this):this.parent&&n===null&&this._uiManager.addShouldRescale(this),super.setParent(n)}onScaleChanging(){const[n,r]=this.parentDimensions,a=this.width*n,i=this.height*r;this.setDimensions(a,i)}enableEditMode(){ye(this,F2)||this.canvas===null||(super.enableEditMode(),this._isDraggable=!1,ts(this,Ei,aYe).call(this))}disableEditMode(){!this.isInEditMode()||this.canvas===null||(super.disableEditMode(),this._isDraggable=!this.isEmpty(),this.div.classList.remove("editing"),ts(this,Ei,iYe).call(this))}onceAdded(){this._isDraggable=!this.isEmpty()}isEmpty(){return this.paths.length===0||this.paths.length===1&&this.paths[0].length===0}commit(){ye(this,F2)||(super.commit(),this.isEditing=!1,this.disableEditMode(),this.setInForeground(),Ut(this,F2,!0),this.div.classList.add("disabled"),ts(this,Ei,HX).call(this,!0),this.select(),this.parent.addInkEditorIfNeeded(!0),this.moveInDOM(),this.div.focus({preventScroll:!0}))}focusin(n){this._focusEventsAllowed&&(super.focusin(n),this.enableEditMode())}canvasPointerdown(n){n.button!==0||!this.isInEditMode()||ye(this,F2)||(this.setInForeground(),n.preventDefault(),this.div.contains(document.activeElement)||this.div.focus({preventScroll:!0}),ts(this,Ei,_ts).call(this,n.offsetX,n.offsetY))}canvasPointermove(n){n.preventDefault(),ts(this,Ei,rYe).call(this,n.offsetX,n.offsetY)}canvasPointerup(n){n.preventDefault(),ts(this,Ei,oYe).call(this,n)}canvasPointerleave(n){ts(this,Ei,oYe).call(this,n)}get isResizable(){return!this.isEmpty()&&ye(this,F2)}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]=ts(this,Ei,bts).call(this);if(this.setAt(a,i,0,0),this.setDims(l,o),ts(this,Ei,ECe).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),Ut(this,FO,!0),ts(this,Ei,PU).call(this),this.setDims(this.width*c,this.height*d),ts(this,Ei,YR).call(this),this.div.classList.add("disabled")}else this.div.classList.add("editing"),this.enableEditMode();return ts(this,Ei,TCe).call(this),this.div}setDimensions(n,r){const a=Math.round(n),i=Math.round(r);if(ye(this,OO)===a&&ye(this,zO)===i)return;Ut(this,OO,a),Ut(this,zO,i),this.canvas.style.visibility="hidden";const[l,o]=this.parentDimensions;this.width=n/l,this.height=r/o,this.fixAndSetPosition(),ye(this,F2)&&ts(this,Ei,lYe).call(this,n,r),ts(this,Ei,PU).call(this),ts(this,Ei,YR).call(this),this.canvas.style.visibility="visible",this.fixDims()}static async deserialize(n,r,a){var v,g,b;if(n instanceof Qrt)return null;const i=await super.deserialize(n,r,a);i.thickness=n.thickness,i.color=qo.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;Ut(i,F2,!0),Ut(i,OO,Math.round(c)),Ut(i,zO,Math.round(d));const{paths:m,rect:p,rotation:f}=n;for(let{bezier:j}of m){j=ts(v=_f,ME,Ats).call(v,j,p,f);const S=[];i.paths.push(S);let C=u*(j[0]-h),E=u*(j[1]-h);for(let M=2,I=j.length;M{this.thickness=i,ts(this,Ei,HX).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:bc.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0})},yts=function(n){const r=i=>{this.color=i,ts(this,Ei,YR).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:bc.INK_COLOR,overwriteIfSameType:!0,keepUndo:!0})},vts=function(n){const r=i=>{this.opacity=i,ts(this,Ei,YR).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:bc.INK_OPACITY,overwriteIfSameType:!0,keepUndo:!0})},bts=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]}},nYe=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}${J$n(a)}`},_ts=function(n,r){this.canvas.addEventListener("contextmenu",PN,{signal:this._uiManager._signal}),ts(this,Ei,iYe).call(this),Ut(this,DO,new AbortController);const a=this._uiManager.combinedSignal(ye(this,DO));this.canvas.addEventListener("pointerleave",this.canvasPointerleave.bind(this),{signal:a}),this.canvas.addEventListener("pointermove",this.canvasPointermove.bind(this),{signal:a}),this.canvas.addEventListener("pointerup",this.canvasPointerup.bind(this),{signal:a}),this.isEditing=!0,ye(this,FO)||(Ut(this,FO,!0),ts(this,Ei,PU).call(this),this.thickness||(this.thickness=_f._defaultThickness),this.color||(this.color=_f._defaultColor||Oh._defaultLineColor),this.opacity??(this.opacity=_f._defaultOpacity)),this.currentPath.push([n,r]),Ut(this,RO,!1),ts(this,Ei,nYe).call(this),Ut(this,dM,()=>{ts(this,Ei,Nts).call(this),ye(this,dM)&&window.requestAnimationFrame(ye(this,dM))}),window.requestAnimationFrame(ye(this,dM))},rYe=function(n,r){const[a,i]=this.currentPath.at(-1);if(this.currentPath.length>1&&n===a&&r===i)return;const l=this.currentPath;let o=ye(this,vA);if(l.push([n,r]),Ut(this,RO,!0),l.length<=2){o.moveTo(...l[0]),o.lineTo(n,r);return}l.length===3&&(Ut(this,vA,o=new Path2D),o.moveTo(...l[0])),ts(this,Ei,kts).call(this,o,...l.at(-3),...l.at(-2),n,r)},wts=function(){if(this.currentPath.length===0)return;const n=this.currentPath.at(-1);ye(this,vA).lineTo(...n)},jts=function(n,r){Ut(this,dM,null),n=Math.min(Math.max(n,0),this.canvas.width),r=Math.min(Math.max(r,0),this.canvas.height),ts(this,Ei,rYe).call(this,n,r),ts(this,Ei,wts).call(this);let a;if(this.currentPath.length!==1)a=ts(this,Ei,Sts).call(this);else{const d=[n,r];a=[[d,d.slice(),d.slice(),d]]}const i=ye(this,vA),l=this.currentPath;this.currentPath=[],Ut(this,vA,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||(ts(this,Ei,ECe).call(this),ts(this,Ei,TCe).call(this)),ts(this,Ei,HX).call(this))};this.addCommands({cmd:o,undo:c,mustExec:!0})},Nts=function(){if(!ye(this,RO))return;Ut(this,RO,!1);const n=Math.ceil(this.thickness*this.parentScale),r=this.currentPath.slice(-3),a=r.map(o=>o[0]),i=r.map(o=>o[1]);Math.min(...a)-n,Math.max(...a)+n,Math.min(...i)-n,Math.max(...i)+n;const{ctx:l}=this;l.save(),l.clearRect(0,0,this.canvas.width,this.canvas.height);for(const o of this.bezierPath2D)l.stroke(o);l.stroke(ye(this,vA)),l.restore()},kts=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)},Sts=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{Ut(this,d4,null),this.canvas.removeEventListener("contextmenu",PN)},10)),ts(this,Ei,jts).call(this,n.offsetX,n.offsetY),this.addToAnnotationStorage(),this.setInBackground()},ECe=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")},TCe=function(){Ut(this,bA,new ResizeObserver(n=>{const r=n[0].contentRect;r.width&&r.height&&this.setDimensions(r.width,r.height)})),ye(this,bA).observe(this.div),this._uiManager._signal.addEventListener("abort",()=>{var n;(n=ye(this,bA))==null||n.disconnect(),Ut(this,bA,null)},{once:!0})},PU=function(){if(!ye(this,FO))return;const[n,r]=this.parentDimensions;this.canvas.width=Math.ceil(this.width*n),this.canvas.height=Math.ceil(this.height*r),ts(this,Ei,MCe).call(this)},lYe=function(n,r){const a=ts(this,Ei,PCe).call(this),i=(n-a)/ye(this,IO),l=(r-a)/ye(this,LO);this.scaleFactor=Math.min(i,l)},MCe=function(){const n=ts(this,Ei,PCe).call(this)/2;this.ctx.setTransform(this.scaleFactor,0,0,this.scaleFactor,this.translationX*this.scaleFactor+n,this.translationY*this.scaleFactor+n)},ME=new WeakSet,Cts=function(n){const r=new Path2D;for(let a=0,i=n.length;a`image/${r}`))}static get supportedTypesStr(){return fu(this,"supportedTypesStr",this.supportedTypes.join(","))}static isHandlingMimeForPasting(n){return this.supportedTypes.includes(n)}static paste(n,r){r.pasteEditor(Zc.STAMP,{bitmapFile:n.getAsFile()})}altTextFinish(){this._uiManager.useNewAltTextFlow&&(this.div.hidden=!1),super.altTextFinish()}get telemetryFinalData(){var n;return{type:"stamp",hasAltText:!!((n=this.altTextData)!=null&&n.altText)}}static computeTelemetryFinalData(n){const r=n.get("hasAltText");return{hasAltText:r.get(!0)??0,hasNoAltText:r.get(!1)??0}}async mlGuessAltText(n=null,r=!0){if(this.hasAltTextData())return null;const{mlManager:a}=this._uiManager;if(!a)throw new Error("No ML.");if(!await a.isEnabledFor("altText"))throw new Error("ML isn't enabled for alt text.");const{data:i,width:l,height:o}=n||this.copyCanvas(null,null,!0).imageData,c=await a.guess({name:"altText",request:{data:i,width:l,height:o,channels:i.length/(l*o)}});if(!c)throw new Error("No response from the AI service.");if(c.error)throw new Error("Error from the AI service.");if(c.cancel)return null;if(!c.output)throw new Error("No valid response from the AI service.");const d=c.output;return await this.setGuessedAltText(d),r&&!this.hasAltTextData()&&(this.altTextData={alt:d,decorative:!1}),d}remove(){var n,r;ye(this,tv)&&(Ut(this,jf,null),this._uiManager.imageManager.deleteId(ye(this,tv)),(n=ye(this,u4))==null||n.remove(),Ut(this,u4,null),(r=ye(this,wA))==null||r.disconnect(),Ut(this,wA,null),ye(this,h4)&&(clearTimeout(ye(this,h4)),Ut(this,h4,null))),super.remove()}rebuild(){if(!this.parent){ye(this,tv)&&ts(this,Xd,LCe).call(this);return}super.rebuild(),this.div!==null&&(ye(this,tv)&&ye(this,u4)===null&&ts(this,Xd,LCe).call(this),this.isAttachedToDOM||this.parent.add(this))}onceAdded(){this._isDraggable=!0,this.div.focus()}isEmpty(){return!(ye(this,uM)||ye(this,jf)||ye(this,_A)||ye(this,hM)||ye(this,tv))}get isResizable(){return!0}render(){if(this.div)return this.div;let n,r;if(this.width&&(n=this.x,r=this.y),super.render(),this.div.hidden=!0,this.div.setAttribute("role","figure"),this.addAltTextButton(),ye(this,jf)?ts(this,Xd,hYe).call(this):ts(this,Xd,LCe).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}=ye(this,jf),o=new lKe;let c=ye(this,jf),d=i,u=l,h=null;if(r){if(i>r||l>r){const M=Math.min(r/i,r/l);d=Math.floor(i*M),u=Math.floor(l*M)}h=document.createElement("canvas");const f=h.width=Math.ceil(d*o.sx),y=h.height=Math.ceil(u*o.sy);ye(this,zw)||(c=ts(this,Xd,ICe).call(this,f,y));const v=h.getContext("2d");v.filter=this._uiManager.hcmFilter;let g="white",b="#cfcfd8";this._uiManager.hcmFilter!=="none"?b="black":(p=window.matchMedia)!=null&&p.call(window,"(prefers-color-scheme: dark)").matches&&(g="#8f8f9d",b="#42414d");const j=15,S=j*o.sx,C=j*o.sy,E=new OffscreenCanvas(S*2,C*2),P=E.getContext("2d");P.fillStyle=g,P.fillRect(0,0,S*2,C*2),P.fillStyle=b,P.fillRect(0,0,S,C),P.fillRect(S,C,S,C),v.fillStyle=v.createPattern(E,"repeat"),v.fillRect(0,0,f,y),v.drawImage(c,0,0,c.width,c.height,0,0,f,y)}let m=null;if(a){let f,y;if(o.symmetric&&c.widthn||l>n){const b=Math.min(n/i,n/l);f=Math.floor(i*b),y=Math.floor(l*b),ye(this,zw)||(c=ts(this,Xd,ICe).call(this,f,y))}const g=new OffscreenCanvas(f,y).getContext("2d",{willReadFrequently:!0});g.drawImage(c,0,0,c.width,c.height,0,0,f,y),m={width:f,height:y,data:g.getImageData(0,0,f,y).data}}return{canvas:h,width:d,height:u,imageData:m}}getImageForAltText(){return ye(this,u4)}static async deserialize(n,r,a){var y;let i=null;if(n instanceof qes){const{data:{rect:v,rotation:g,id:b,structParent:j,popupRef:S},container:C,parent:{page:{pageNumber:E}}}=n,P=C.querySelector("canvas"),M=a.imageManager.getFromCanvas(C.id,P);P.remove();const I=((y=await r._structTree.getAriaAttributes(`${Urt}${b}`))==null?void 0:y.get("aria-label"))||"";i=n={annotationType:Zc.STAMP,bitmapId:M.id,bitmap:M.bitmap,pageIndex:E-1,rect:v.slice(0),rotation:g,id:b,deleted:!1,accessibilityData:{decorative:!1,altText:I},isSvg:!1,structParent:j,popupRef:S}}const l=await super.deserialize(n,r,a),{rect:o,bitmap:c,bitmapUrl:d,bitmapId:u,isSvg:h,accessibilityData:m}=n;u&&a.imageManager.isValidId(u)?(Ut(l,tv,u),c&&Ut(l,jf,c)):Ut(l,_A,d),Ut(l,zw,h);const[p,f]=l.pageDimensions;return l.width=(o[2]-o[0])/p,l.height=(o[3]-o[1])/f,l.annotationElementId=n.id||null,m&&(l.altTextData=m),l._initialData=i,Ut(l,lH,!!i),l}serialize(n=!1,r=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const a={annotationType:Zc.STAMP,bitmapId:ye(this,tv),pageIndex:this.pageIndex,rect:this.getRect(0,0),rotation:this.rotation,isSvg:ye(this,zw),structTreeParentId:this._structTreeParentId};if(n)return a.bitmapUrl=ts(this,Xd,DCe).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=ts(this,Xd,Pts).call(this,a);if(c.isSame)return null;c.isSameAltText?delete a.accessibilityData:a.accessibilityData.structParent=this._initialData.structParent??-1}if(a.id=this.annotationElementId,r===null)return a;r.stamps||(r.stamps=new Map);const o=ye(this,zw)?(a.rect[2]-a.rect[0])*(a.rect[3]-a.rect[1]):null;if(!r.stamps.has(ye(this,tv)))r.stamps.set(ye(this,tv),{area:o,serialized:a}),a.bitmap=ts(this,Xd,DCe).call(this,!1);else if(ye(this,zw)){const c=r.stamps.get(ye(this,tv));o>c.area&&(c.area=o,c.serialized.bitmap.close(),c.serialized.bitmap=ts(this,Xd,DCe).call(this,!1))}return a}renderAnnotationElement(n){return n.updateEdited({rect:this.getRect(0,0)}),null}};jf=new WeakMap,tv=new WeakMap,uM=new WeakMap,_A=new WeakMap,hM=new WeakMap,oH=new WeakMap,u4=new WeakMap,wA=new WeakMap,h4=new WeakMap,zw=new WeakMap,lH=new WeakMap,Xd=new WeakSet,GX=function(n,r=!1){if(!n){this.remove();return}Ut(this,jf,n.bitmap),r||(Ut(this,tv,n.id),Ut(this,zw,n.isSvg)),n.file&&Ut(this,oH,n.file.name),ts(this,Xd,hYe).call(this)},WX=function(){if(Ut(this,uM,null),this._uiManager.enableWaiting(!1),!!ye(this,u4)){if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&ye(this,jf)){this._editToolbar.hide(),this._uiManager.editAltText(this,!0);return}if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&ye(this,jf)){this._reportTelemetry({action:"pdfjs.image.image_added",data:{alt_text_modal:!1,alt_text_type:"empty"}});try{this.mlGuessAltText()}catch{}}this.div.focus()}},LCe=function(){if(ye(this,tv)){this._uiManager.enableWaiting(!0),this._uiManager.imageManager.getFromId(ye(this,tv)).then(a=>ts(this,Xd,GX).call(this,a,!0)).finally(()=>ts(this,Xd,WX).call(this));return}if(ye(this,_A)){const a=ye(this,_A);Ut(this,_A,null),this._uiManager.enableWaiting(!0),Ut(this,uM,this._uiManager.imageManager.getFromUrl(a).then(i=>ts(this,Xd,GX).call(this,i)).finally(()=>ts(this,Xd,WX).call(this)));return}if(ye(this,hM)){const a=ye(this,hM);Ut(this,hM,null),this._uiManager.enableWaiting(!0),Ut(this,uM,this._uiManager.imageManager.getFromFile(a).then(i=>ts(this,Xd,GX).call(this,i)).finally(()=>ts(this,Xd,WX).call(this)));return}const n=document.createElement("input");n.type="file",n.accept=Cee.supportedTypesStr;const r=this._uiManager._signal;Ut(this,uM,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}}),ts(this,Xd,GX).call(this,i)}a()},{signal:r}),n.addEventListener("cancel",()=>{this.remove(),a()},{signal:r})}).finally(()=>ts(this,Xd,WX).call(this))),n.click()},hYe=function(){const{div:n}=this;let{width:r,height:a}=ye(this,jf);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=Ut(this,u4,document.createElement("canvas"));u.setAttribute("role","img"),this.addContainer(u),(!this._uiManager.useNewAltTextWhenAddingImage||!this._uiManager.useNewAltTextFlow||this.annotationElementId)&&(n.hidden=!1),ts(this,Xd,mYe).call(this,r,a),ts(this,Xd,Mts).call(this),ye(this,lH)||(this.parent.addUndoableEditor(this),Ut(this,lH,!0)),this._reportTelemetry({action:"inserted_image"}),ye(this,oH)&&u.setAttribute("aria-label",ye(this,oH))},Tts=function(n,r){var o;const[a,i]=this.parentDimensions;this.width=n/a,this.height=r/i,(o=this._initialOptions)!=null&&o.isCentered?this.center():this.fixAndSetPosition(),this._initialOptions=null,ye(this,h4)!==null&&clearTimeout(ye(this,h4)),Ut(this,h4,setTimeout(()=>{Ut(this,h4,null),ts(this,Xd,mYe).call(this,n,r)},200))},ICe=function(n,r){const{width:a,height:i}=ye(this,jf);let l=a,o=i,c=ye(this,jf);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},mYe=function(n,r){const a=new lKe,i=Math.ceil(n*a.sx),l=Math.ceil(r*a.sy),o=ye(this,u4);if(!o||o.width===i&&o.height===l)return;o.width=i,o.height=l;const c=ye(this,zw)?ye(this,jf):ts(this,Xd,ICe).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)},DCe=function(n){if(n){if(ye(this,zw)){const i=this._uiManager.imageManager.getSvgUrl(ye(this,tv));if(i)return i}const r=document.createElement("canvas");return{width:r.width,height:r.height}=ye(this,jf),r.getContext("2d").drawImage(ye(this,jf),0,0),r.toDataURL()}if(ye(this,zw)){const[r,a]=this.pageDimensions,i=Math.round(this.width*r*HP.PDF_TO_CSS_UNITS),l=Math.round(this.height*a*HP.PDF_TO_CSS_UNITS),o=new OffscreenCanvas(i,l);return o.getContext("2d").drawImage(ye(this,jf),0,0,ye(this,jf).width,ye(this,jf).height,0,0,i,l),o.transferToImageBitmap()}return structuredClone(ye(this,jf))},Mts=function(){this._uiManager._signal&&(Ut(this,wA,new ResizeObserver(n=>{const r=n[0].contentRect;r.width&&r.height&&ts(this,Xd,Tts).call(this,r.width,r.height)})),ye(this,wA).observe(this.div),this._uiManager._signal.addEventListener("abort",()=>{var n;(n=ye(this,wA))==null||n.disconnect(),Ut(this,wA,null)},{once:!0}))},Pts=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}},Pr(Cee,"_type","stamp"),Pr(Cee,"_editorType",Zc.STAMP);let uYe=Cee;var BO,cH,m4,mM,jA,Bw,pM,dH,uH,r1,NA,cl,fM,Cv,Lts,fYe,xYe,gYe,RCe;const Ck=class Ck{constructor({uiManager:t,pageIndex:n,div:r,structTreeLayer:a,accessibilityManager:i,annotationLayer:l,drawLayer:o,textLayer:c,viewport:d,l10n:u}){us(this,Cv);us(this,BO);us(this,cH,!1);us(this,m4,null);us(this,mM,null);us(this,jA,null);us(this,Bw,new Map);us(this,pM,!1);us(this,dH,!1);us(this,uH,!1);us(this,r1,null);us(this,NA,null);us(this,cl);const h=[...ye(Ck,fM).values()];if(!Ck._initialized){Ck._initialized=!0;for(const m of h)m.initialize(u,t)}t.registerEditorTypes(h),Ut(this,cl,t),this.pageIndex=n,this.div=r,Ut(this,BO,i),Ut(this,m4,l),this.viewport=d,Ut(this,r1,c),this.drawLayer=o,this._structTree=a,ye(this,cl).addLayer(this)}get isEmpty(){return ye(this,Bw).size===0}get isInvisible(){return this.isEmpty&&ye(this,cl).getMode()===Zc.NONE}updateToolbar(t){ye(this,cl).updateToolbar(t)}updateMode(t=ye(this,cl).getMode()){switch(ts(this,Cv,RCe).call(this),t){case Zc.NONE:this.disableTextSelection(),this.togglePointerEvents(!1),this.toggleAnnotationLayerPointerEvents(!0),this.disableClick();return;case Zc.INK:this.addInkEditorIfNeeded(!1),this.disableTextSelection(),this.togglePointerEvents(!0),this.disableClick();break;case Zc.HIGHLIGHT:this.enableTextSelection(),this.togglePointerEvents(!1),this.disableClick();break;default:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick()}this.toggleAnnotationLayerPointerEvents(!1);const{classList:n}=this.div;for(const r of ye(Ck,fM).values())n.toggle(`${r._type}Editing`,t===r._editorType);this.div.hidden=!1}hasTextLayer(t){var n;return t===((n=ye(this,r1))==null?void 0:n.div)}addInkEditorIfNeeded(t){if(ye(this,cl).getMode()!==Zc.INK)return;if(!t){for(const r of ye(this,Bw).values())if(r.isEmpty()){r.setInBackground();return}}this.createAndAddNewEditor({offsetX:0,offsetY:0},!1).setInBackground()}setEditingState(t){ye(this,cl).setEditingState(t)}addCommands(t){ye(this,cl).addCommands(t)}toggleDrawing(t=!1){this.div.classList.toggle("drawing",!t)}togglePointerEvents(t=!1){this.div.classList.toggle("disabled",!t)}toggleAnnotationLayerPointerEvents(t=!1){var n;(n=ye(this,m4))==null||n.div.classList.toggle("disabled",!t)}async enable(){this.div.tabIndex=0,this.togglePointerEvents(!0);const t=new Set;for(const r of ye(this,Bw).values())r.enableEditing(),r.show(!0),r.annotationElementId&&(ye(this,cl).removeChangedExistingAnnotation(r),t.add(r.annotationElementId));if(!ye(this,m4))return;const n=ye(this,m4).getEditableAnnotations();for(const r of n){if(r.hide(),ye(this,cl).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;Ut(this,uH,!0),this.div.tabIndex=-1,this.togglePointerEvents(!1);const t=new Map,n=new Map;for(const i of ye(this,Bw).values())if(i.disableEditing(),!!i.annotationElementId){if(i.serialize()!==null){t.set(i.annotationElementId,i);continue}else n.set(i.annotationElementId,i);(a=this.getEditableAnnotation(i.annotationElementId))==null||a.show(),i.remove()}if(ye(this,m4)){const i=ye(this,m4).getEditableAnnotations();for(const l of i){const{id:o}=l.data;if(ye(this,cl).isDeletedAnnotationElement(o))continue;let c=n.get(o);if(c){c.resetAnnotationElement(l),c.show(!1),l.show();continue}c=t.get(o),c&&(ye(this,cl).addChangedExistingAnnotation(c),c.renderAnnotationElement(l)&&c.show(!1)),l.show()}}ts(this,Cv,RCe).call(this),this.isEmpty&&(this.div.hidden=!0);const{classList:r}=this.div;for(const i of ye(Ck,fM).values())r.remove(`${i._type}Editing`);this.disableTextSelection(),this.toggleAnnotationLayerPointerEvents(!0),Ut(this,uH,!1)}getEditableAnnotation(t){var n;return((n=ye(this,m4))==null?void 0:n.getEditableAnnotation(t))||null}setActiveEditor(t){ye(this,cl).getActive()!==t&&ye(this,cl).setActiveEditor(t)}enableTextSelection(){var t;if(this.div.tabIndex=-1,(t=ye(this,r1))!=null&&t.div&&!ye(this,NA)){Ut(this,NA,new AbortController);const n=ye(this,cl).combinedSignal(ye(this,NA));ye(this,r1).div.addEventListener("pointerdown",ts(this,Cv,Lts).bind(this),{signal:n}),ye(this,r1).div.classList.add("highlighting")}}disableTextSelection(){var t;this.div.tabIndex=0,(t=ye(this,r1))!=null&&t.div&&ye(this,NA)&&(ye(this,NA).abort(),Ut(this,NA,null),ye(this,r1).div.classList.remove("highlighting"))}enableClick(){if(ye(this,mM))return;Ut(this,mM,new AbortController);const t=ye(this,cl).combinedSignal(ye(this,mM));this.div.addEventListener("pointerdown",this.pointerdown.bind(this),{signal:t}),this.div.addEventListener("pointerup",this.pointerup.bind(this),{signal:t})}disableClick(){var t;(t=ye(this,mM))==null||t.abort(),Ut(this,mM,null)}attach(t){ye(this,Bw).set(t.id,t);const{annotationElementId:n}=t;n&&ye(this,cl).isDeletedAnnotationElement(n)&&ye(this,cl).removeDeletedAnnotationElement(t)}detach(t){var n;ye(this,Bw).delete(t.id),(n=ye(this,BO))==null||n.removePointerInTextLayer(t.contentDiv),!ye(this,uH)&&t.annotationElementId&&ye(this,cl).addDeletedAnnotationElement(t)}remove(t){this.detach(t),ye(this,cl).removeEditor(t),t.div.remove(),t.isAttachedToDOM=!1,ye(this,dH)||this.addInkEditorIfNeeded(!1)}changeParent(t){var n;t.parent!==this&&(t.parent&&t.annotationElementId&&(ye(this,cl).addDeletedAnnotationElement(t.annotationElementId),Oh.deleteAnnotationElement(t),t.annotationElementId=null),this.attach(t),(n=t.parent)==null||n.detach(t),t.setParent(this),t.div&&t.isAttachedToDOM&&(t.div.remove(),this.div.append(t.div)))}add(t){if(!(t.parent===this&&t.isAttachedToDOM)){if(this.changeParent(t),ye(this,cl).addEditor(t),this.attach(t),!t.isAttachedToDOM){const n=t.render();this.div.append(n),t.isAttachedToDOM=!0}t.fixAndSetPosition(),t.onceAdded(),ye(this,cl).addToAnnotationStorage(t),t._reportTelemetry(t.telemetryInitialData)}}moveEditorInDOM(t){var r;if(!t.isAttachedToDOM)return;const{activeElement:n}=document;t.div.contains(n)&&!ye(this,jA)&&(t._focusEventsAllowed=!1,Ut(this,jA,setTimeout(()=>{Ut(this,jA,null),t.div.contains(document.activeElement)?t._focusEventsAllowed=!0:(t.div.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:ye(this,cl)._signal}),n.focus())},0))),t._structTreeParentId=(r=ye(this,BO))==null?void 0:r.moveElementInDOM(this.div,t.div,t.contentDiv,!0)}addOrRebuild(t){t.needsToBeRebuilt()?(t.parent||(t.parent=this),t.rebuild(),t.show()):this.add(t)}addUndoableEditor(t){const n=()=>t._uiManager.rebuild(t),r=()=>{t.remove()};this.addCommands({cmd:n,undo:r,mustExec:!1})}getNextId(){return ye(this,cl).getId()}combinedSignal(t){return ye(this,cl).combinedSignal(t)}canCreateNewEmptyEditor(){var t;return(t=ye(this,Cv,fYe))==null?void 0:t.canCreateNewEmptyEditor()}pasteEditor(t,n){ye(this,cl).updateToolbar(t),ye(this,cl).updateMode(t);const{offsetX:r,offsetY:a}=ts(this,Cv,gYe).call(this),i=this.getNextId(),l=ts(this,Cv,xYe).call(this,{parent:this,id:i,x:r,y:a,uiManager:ye(this,cl),isCentered:!0,...n});l&&this.add(l)}async deserialize(t){var n;return await((n=ye(Ck,fM).get(t.annotationType??t.annotationEditorType))==null?void 0:n.deserialize(t,this,ye(this,cl)))||null}createAndAddNewEditor(t,n,r={}){const a=this.getNextId(),i=ts(this,Cv,xYe).call(this,{parent:this,id:a,x:t.offsetX,y:t.offsetY,uiManager:ye(this,cl),isCentered:n,...r});return i&&this.add(i),i}addNewEditor(){this.createAndAddNewEditor(ts(this,Cv,gYe).call(this),!0)}setSelected(t){ye(this,cl).setSelected(t)}toggleSelected(t){ye(this,cl).toggleSelected(t)}unselect(t){ye(this,cl).unselect(t)}pointerup(t){const{isMac:n}=kb.platform;if(!(t.button!==0||t.ctrlKey&&n)&&t.target===this.div&&ye(this,pM)){if(Ut(this,pM,!1),!ye(this,cH)){Ut(this,cH,!0);return}if(ye(this,cl).getMode()===Zc.STAMP){ye(this,cl).unselectAll();return}this.createAndAddNewEditor(t,!1)}}pointerdown(t){if(ye(this,cl).getMode()===Zc.HIGHLIGHT&&this.enableTextSelection(),ye(this,pM)){Ut(this,pM,!1);return}const{isMac:n}=kb.platform;if(t.button!==0||t.ctrlKey&&n||t.target!==this.div)return;Ut(this,pM,!0);const r=ye(this,cl).getActive();Ut(this,cH,!r||r.isEmpty())}findNewParent(t,n,r){const a=ye(this,cl).findParent(n,r);return a===null||a===this?!1:(a.changeParent(t),!0)}destroy(){var t,n;((t=ye(this,cl).getActive())==null?void 0:t.parent)===this&&(ye(this,cl).commitOrRemove(),ye(this,cl).setActiveEditor(null)),ye(this,jA)&&(clearTimeout(ye(this,jA)),Ut(this,jA,null));for(const r of ye(this,Bw).values())(n=ye(this,BO))==null||n.removePointerInTextLayer(r.contentDiv),r.setParent(null),r.isAttachedToDOM=!1,r.div.remove();this.div=null,ye(this,Bw).clear(),ye(this,cl).removeLayer(this)}render({viewport:t}){this.viewport=t,j9(this.div,t);for(const n of ye(this,cl).getEditors(this.pageIndex))this.add(n),n.rebuild();this.updateMode()}update({viewport:t}){ye(this,cl).commitOrRemove(),ts(this,Cv,RCe).call(this);const n=this.viewport.rotation,r=t.rotation;if(this.viewport=t,j9(this.div,{rotation:r}),n!==r)for(const a of ye(this,Bw).values())a.rotate(r);this.addInkEditorIfNeeded(!1)}get pageDimensions(){const{pageWidth:t,pageHeight:n}=this.viewport.rawDims;return[t,n]}get scale(){return ye(this,cl).viewParameters.realScale}};BO=new WeakMap,cH=new WeakMap,m4=new WeakMap,mM=new WeakMap,jA=new WeakMap,Bw=new WeakMap,pM=new WeakMap,dH=new WeakMap,uH=new WeakMap,r1=new WeakMap,NA=new WeakMap,cl=new WeakMap,fM=new WeakMap,Cv=new WeakSet,Lts=function(t){ye(this,cl).unselectAll();const{target:n}=t;if(n===ye(this,r1).div||(n.getAttribute("role")==="img"||n.classList.contains("endOfContent"))&&ye(this,r1).div.contains(n)){const{isMac:r}=kb.platform;if(t.button!==0||t.ctrlKey&&r)return;ye(this,cl).showAllEditors("highlight",!0,!0),ye(this,r1).div.classList.add("free"),this.toggleDrawing(),r6e.startHighlighting(this,ye(this,cl).direction==="ltr",{target:ye(this,r1).div,x:t.x,y:t.y}),ye(this,r1).div.addEventListener("pointerup",()=>{ye(this,r1).div.classList.remove("free"),this.toggleDrawing(!0)},{once:!0,signal:ye(this,cl)._signal}),t.preventDefault()}},fYe=function(){return ye(Ck,fM).get(ye(this,cl).getMode())},xYe=function(t){const n=ye(this,Cv,fYe);return n?new n.prototype.constructor(t):null},gYe=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}},RCe=function(){Ut(this,dH,!0);for(const t of ye(this,Bw).values())t.isEmpty()&&t.remove();Ut(this,dH,!1)},Pr(Ck,"_initialized",!1),us(Ck,fM,new Map([WKe,sYe,uYe,r6e].map(t=>[t._editorType,t])));let pYe=Ck;var p4,mre,kg,kA,pre,vYe,I9,bYe,Its;const Qy=class Qy{constructor({pageIndex:t}){us(this,I9);us(this,p4,null);us(this,mre,0);us(this,kg,new Map);us(this,kA,new Map);this.pageIndex=t}setParent(t){if(!ye(this,p4)){Ut(this,p4,t);return}if(ye(this,p4)!==t){if(ye(this,kg).size>0)for(const n of ye(this,kg).values())n.remove(),t.append(n);Ut(this,p4,t)}}static get _svgFactory(){return fu(this,"_svgFactory",new Xrt)}draw(t,n,r,a=!1){const i=X0(this,mre)._++,l=ts(this,I9,bYe).call(this,t.box);l.classList.add(...t.classNamesForDrawing);const o=Qy._svgFactory.createElement("defs");l.append(o);const c=Qy._svgFactory.createElement("path");o.append(c);const d=`path_p${this.pageIndex}_${i}`;c.setAttribute("id",d),c.setAttribute("d",t.toSVGPath()),a&&ye(this,kA).set(i,c);const u=ts(this,I9,Its).call(this,o,d),h=Qy._svgFactory.createElement("use");return l.append(h),l.setAttribute("fill",n),l.setAttribute("fill-opacity",r),h.setAttribute("href",`#${d}`),ye(this,kg).set(i,l),{id:i,clipPathId:`url(#${u})`}}drawOutline(t){const n=X0(this,mre)._++,r=ts(this,I9,bYe).call(this,t.box);r.classList.add(...t.classNamesForOutlining);const a=Qy._svgFactory.createElement("defs");r.append(a);const i=Qy._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=Qy._svgFactory.createElement("mask");a.append(u),o=`mask_p${this.pageIndex}_${n}`,u.setAttribute("id",o),u.setAttribute("maskUnits","objectBoundingBox");const h=Qy._svgFactory.createElement("rect");u.append(h),h.setAttribute("width","1"),h.setAttribute("height","1"),h.setAttribute("fill","white");const m=Qy._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=Qy._svgFactory.createElement("use");r.append(c),c.setAttribute("href",`#${l}`),o&&c.setAttribute("mask",`url(#${o})`);const d=c.cloneNode();return r.append(d),c.classList.add("mainOutline"),d.classList.add("secondaryOutline"),ye(this,kg).set(n,r),n}finalizeLine(t,n){const r=ye(this,kA).get(t);ye(this,kA).delete(t),this.updateBox(t,n.box),r.setAttribute("d",n.toSVGPath())}updateLine(t,n){ye(this,kg).get(t).firstChild.firstChild.setAttribute("d",n.toSVGPath())}updatePath(t,n){ye(this,kA).get(t).setAttribute("d",n.toSVGPath())}updateBox(t,n){var r;ts(r=Qy,pre,vYe).call(r,ye(this,kg).get(t),n)}show(t,n){ye(this,kg).get(t).classList.toggle("hidden",!n)}rotate(t,n){ye(this,kg).get(t).setAttribute("data-main-rotation",n)}changeColor(t,n){ye(this,kg).get(t).setAttribute("fill",n)}changeOpacity(t,n){ye(this,kg).get(t).setAttribute("fill-opacity",n)}addClass(t,n){ye(this,kg).get(t).classList.add(n)}removeClass(t,n){ye(this,kg).get(t).classList.remove(n)}getSVGRoot(t){return ye(this,kg).get(t)}remove(t){ye(this,kA).delete(t),ye(this,p4)!==null&&(ye(this,kg).get(t).remove(),ye(this,kg).delete(t))}destroy(){Ut(this,p4,null);for(const t of ye(this,kg).values())t.remove();ye(this,kg).clear(),ye(this,kA).clear()}};p4=new WeakMap,mre=new WeakMap,kg=new WeakMap,kA=new WeakMap,pre=new WeakSet,vYe=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}%`},I9=new WeakSet,bYe=function(t){var r;const n=Qy._svgFactory.create(1,1,!0);return ye(this,p4).append(n),n.setAttribute("aria-hidden",!0),ts(r=Qy,pre,vYe).call(r,n,t),n},Its=function(t,n){const r=Qy._svgFactory.createElement("clipPath");t.append(r);const a=`clip_${n}`;r.setAttribute("id",a),r.setAttribute("clipPathUnits","objectBoundingBox");const i=Qy._svgFactory.createElement("use");return r.append(i),i.setAttribute("href",`#${n}`),i.classList.add("clip"),a},us(Qy,pre);let yYe=Qy;Sc.AbortException;Sc.AnnotationEditorLayer;Sc.AnnotationEditorParamsType;Sc.AnnotationEditorType;Sc.AnnotationEditorUIManager;Sc.AnnotationLayer;Sc.AnnotationMode;Sc.ColorPicker;Sc.DOMSVGFactory;Sc.DrawLayer;Sc.FeatureTest;var Jrt=Sc.GlobalWorkerOptions;Sc.ImageKind;Sc.InvalidPDFException;Sc.MissingPDFException;Sc.OPS;Sc.OutputScale;Sc.PDFDataRangeTransport;Sc.PDFDateString;Sc.PDFWorker;Sc.PasswordResponses;Sc.PermissionFlag;Sc.PixelsPerInch;Sc.RenderingCancelledException;Sc.TextLayer;Sc.UnexpectedResponseException;Sc.Util;Sc.VerbosityLevel;Sc.XfaLayer;Sc.build;Sc.createValidAbsoluteUrl;Sc.fetchData;var a6e=Sc.getDocument;Sc.getFilenameFromUrl;Sc.getPdfFilenameFromUrl;Sc.getXfaPageViewport;Sc.isDataScheme;Sc.isPdfFile;Sc.noContextMenu;Sc.normalizeUnicode;Sc.setLayerDimensions;Sc.shadow;Sc.version;const eat="/assets/pdf.worker.min-GB3t0DcA.mjs";Jrt.workerSrc=eat;const PHn=({blob:s,scale:t=1.5})=>{const n=_.useRef(null),[r,a]=_.useState(!1),[i,l]=_.useState(null);return _.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 a6e({data:u}).promise;if(o)return;c.innerHTML="";for(let m=1;m<=h.numPages;m+=1){const p=await h.getPage(m);if(o)return;const f=p.getViewport({scale:t}),y=document.createElement("canvas");y.width=Math.floor(f.width),y.height=Math.floor(f.height),y.className="mx-auto w-full max-w-[900px] rounded-md border border-border bg-white shadow-sm";const v=y.getContext("2d");v&&(c.appendChild(y),await p.render({canvasContext:v,viewport:f}).promise)}}catch(u){o||l((u==null?void 0:u.message)||"Could not render the preview")}finally{o||a(!1)}})(),()=>{o=!0})},[s,t]),e.jsxs("div",{className:"relative h-full overflow-y-auto bg-muted/40 p-4",children:[r&&e.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-background/70",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})}),i&&e.jsx("p",{className:"p-4 text-sm text-destructive",children:i}),e.jsx("div",{ref:n,className:"space-y-4"})]})};function yz({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}=hs(),d=_.useRef(null),[u,h]=_.useState(!1),m=async p=>{if(!(!p||!c)){if(!p.type.startsWith("image/")){se.error("Please choose an image file");return}if(p.size>20*1024*1024){se.error("That photo is larger than 20 MB");return}h(!0);try{const f=await E$n(c.id,p,r);n(f),se.success("Photo uploaded")}catch(f){se.error((f==null?void 0:f.message)||"Upload failed")}finally{h(!1),d.current&&(d.current.value="")}}};return e.jsxs("div",{className:At("space-y-2",o),children:[e.jsx(J,{className:"text-xs",children:s}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:At("relative shrink-0 overflow-hidden border bg-muted",l?"h-16 w-16 rounded-full":"h-16 w-24 rounded-md"),children:t?e.jsx("img",{src:t,alt:s,className:"h-full w-full object-cover"}):e.jsx("div",{className:"flex h-full w-full items-center justify-center text-muted-foreground",children:e.jsx(hc,{className:"h-5 w-5"})})}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("input",{ref:d,type:"file",accept:"image/*",className:"hidden",onChange:p=>{var f;return m((f=p.target.files)==null?void 0:f[0])}}),e.jsxs(B,{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(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(jy,{className:"h-4 w-4"}),t?"Replace photo":"Upload photo"]}),t&&e.jsxs(B,{type:"button",variant:"ghost",size:"sm",className:"gap-1 text-muted-foreground",onClick:()=>n(null),children:[e.jsx(Qn,{className:"h-4 w-4"})," Remove"]})]})]}),e.jsx(xe,{value:t||"",onChange:p=>n(p.target.value||null),placeholder:i}),a&&e.jsx("p",{className:"text-xs text-muted-foreground",children:a})]})}function LHn({value:s,onChange:t}){return e.jsxs(ve,{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(In,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(St,{className:"text-base",children:"Co-listing agent"})]}),e.jsx(fn,{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(Me,{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Name"}),e.jsx(xe,{value:s.name,onChange:n=>t({name:n.target.value}),placeholder:"Jordan Ellis"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Title"}),e.jsx(xe,{value:s.title||"",onChange:n=>t({title:n.target.value}),placeholder:"Co-listing agent"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Phone"}),e.jsx(xe,{value:s.phone||"",onChange:n=>t({phone:n.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Email"}),e.jsx(xe,{value:s.email||"",onChange:n=>t({email:n.target.value})})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Brokerage"}),e.jsx(xe,{value:s.brokerageName||"",onChange:n=>t({brokerageName:n.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"License #"}),e.jsx(xe,{value:s.licenseNumber||"",onChange:n=>t({licenseNumber:n.target.value})})]})]}),e.jsx(yz,{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(J,{children:"Shared bio (optional)"}),e.jsx(Ms,{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 IHn({value:s,onChange:t}){return e.jsxs(ve,{children:[e.jsxs(bt,{className:"pb-3",children:[e.jsx(St,{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(Me,{className:"grid gap-2 sm:grid-cols-2",children:nKe.map(n=>{const r=n.id===s;return e.jsxs("button",{type:"button",onClick:()=>t(n.id),className:At("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(ea,{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 DHn={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}]},RHn=["cover","welcome","agent","overview","closing"];function FHn({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(ve,{children:[e.jsxs(bt,{className:"pb-3",children:[e.jsx(St,{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(Me,{children:e.jsx(G9,{type:"multiple",className:"w-full",children:RHn.filter(i=>i==="cover"||!n.has(i)).map(i=>{const l=aQt(s,i);return e.jsxs(gL,{value:i,children:[e.jsx(yL,{className:"text-sm",children:O9n[i]}),e.jsxs(vL,{className:"space-y-3 pt-1",children:[DHn[i].map(o=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs",children:o.label}),o.long?e.jsx(Ms,{rows:2,value:l[o.key]||"",placeholder:RWe[i][o.key],onChange:c=>r(i,o.key,c.target.value)}):e.jsx(xe,{value:l[o.key]||"",placeholder:RWe[i][o.key],onChange:c=>r(i,o.key,c.target.value)})]},o.key)),e.jsxs(B,{variant:"ghost",size:"sm",className:"gap-2",onClick:()=>a(i),children:[e.jsx(Tx,{className:"h-3.5 w-3.5"})," Reset to default wording"]})]})]},i)})})})]})}function OHn({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,jrt(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(ve,{children:[e.jsxs(bt,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pj,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(St,{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(Me,{className:"space-y-4",children:[e.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:xze.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(rn,{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(wc,{}),e.jsx(G9,{type:"multiple",className:"w-full",children:n.map((o,c)=>{var d,u,h;return e.jsxs(gL,{value:o.id,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fn,{checked:o.enabled,onCheckedChange:m=>r(o.id,{enabled:m})}),e.jsx(yL,{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=xze.find(m=>m.layout===o.layout))==null?void 0:u.name),e.jsx(Oe,{variant:"secondary",className:"text-[10px]",children:(h=xze.find(m=>m.layout===o.layout))==null?void 0:h.name})]})}),e.jsx(B,{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(B,{variant:"ghost",size:"icon",className:"h-7 w-7",disabled:c===n.length-1,onClick:()=>l(o.id,1),children:e.jsx(zf,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7 text-destructive",onClick:()=>i(o.id),children:e.jsx(Sn,{className:"h-3.5 w-3.5"})})]}),e.jsxs(vL,{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(J,{className:"text-xs",children:"Placement"}),e.jsxs(is,{value:o.placement,onValueChange:m=>r(o.id,{placement:m}),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"after-agent",children:'After "About your agent"'}),e.jsx(He,{value:"end",children:"Before the closing page"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs",children:"Style"}),e.jsxs("div",{className:"flex h-10 items-center gap-2 rounded-md border px-3",children:[e.jsx(fn,{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(J,{className:"text-xs",children:"Eyebrow"}),e.jsx(xe,{value:o.kicker,onChange:m=>r(o.id,{kicker:m.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs",children:"Headline"}),e.jsx(xe,{value:o.headline,onChange:m=>r(o.id,{headline:m.target.value})})]}),o.layout!=="statement"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs",children:"Subhead"}),e.jsx(xe,{value:o.subhead,onChange:m=>r(o.id,{subhead:m.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs",children:"Body copy"}),e.jsx(Ms,{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(yz,{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(J,{className:"text-xs",children:"Photo side"}),e.jsxs(is,{value:o.imageSide,onValueChange:m=>r(o.id,{imageSide:m}),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"right",children:"Right"}),e.jsx(He,{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(J,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"List items"}),o.bullets.map((m,p)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xe,{value:m,onChange:f=>{const y=[...o.bullets];y[p]=f.target.value,r(o.id,{bullets:y})}}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive",onClick:()=>r(o.id,{bullets:o.bullets.filter((f,y)=>y!==p)}),children:e.jsx(Sn,{className:"h-3.5 w-3.5"})})]},p)),e.jsxs(B,{variant:"outline",size:"sm",className:"gap-2",disabled:o.bullets.length>=7,onClick:()=>r(o.id,{bullets:[...o.bullets,""]}),children:[e.jsx(rn,{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(J,{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(Ms,{rows:3,value:m.quote,placeholder:"Client quote",onChange:f=>{const y=[...o.testimonials];y[p]={...m,quote:f.target.value},r(o.id,{testimonials:y})}}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(xe,{value:m.name,placeholder:"Name",onChange:f=>{const y=[...o.testimonials];y[p]={...m,name:f.target.value},r(o.id,{testimonials:y})}}),e.jsx(xe,{value:m.detail,placeholder:"Neighborhood or year",onChange:f=>{const y=[...o.testimonials];y[p]={...m,detail:f.target.value},r(o.id,{testimonials:y})}})]}),e.jsxs(B,{variant:"ghost",size:"sm",className:"gap-2 text-destructive",onClick:()=>r(o.id,{testimonials:o.testimonials.filter((f,y)=>y!==p)}),children:[e.jsx(Sn,{className:"h-3.5 w-3.5"})," Remove"]})]},p)),e.jsxs(B,{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(rn,{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(J,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Stats (up to 4)"}),o.stats.map((m,p)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xe,{className:"w-28",value:m.value,placeholder:"27",onChange:f=>{const y=[...o.stats];y[p]={...m,value:f.target.value},r(o.id,{stats:y})}}),e.jsx(xe,{value:m.label,placeholder:"Homes sold",onChange:f=>{const y=[...o.stats];y[p]={...m,label:f.target.value},r(o.id,{stats:y})}}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive",onClick:()=>r(o.id,{stats:o.stats.filter((f,y)=>y!==p)}),children:e.jsx(Sn,{className:"h-3.5 w-3.5"})})]},p)),e.jsxs(B,{variant:"outline",size:"sm",className:"gap-2",disabled:o.stats.length>=4,onClick:()=>r(o.id,{stats:[...o.stats,{value:"",label:""}]}),children:[e.jsx(rn,{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 zHn({open:s,onOpenChange:t,defaultName:n,saving:r,onSave:a}){const[i,l]=_.useState(""),[o,c]=_.useState("");return _.useEffect(()=>{s&&(l((n==null?void 0:n.trim())||"My listing presentation"),c(""))},[s,n]),e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"sm:max-w-md",children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Save as a reusable template"}),e.jsx(_r,{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(J,{children:"Template name"}),e.jsx(xe,{value:i,onChange:d=>l(d.target.value),autoFocus:!0})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Notes (optional)"}),e.jsx(Ms,{rows:2,value:o,onChange:d=>c(d.target.value),placeholder:"Luxury version with co-listing agent and testimonials"})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{disabled:!i.trim()||r,onClick:async()=>{await a(i.trim(),o.trim()),t(!1)},className:"gap-2",children:[r&&e.jsx(Ct,{className:"h-4 w-4 animate-spin"})," Save template"]})]})]})})}const kSt=["welcome","agent","overview","closing"],BHn=()=>{const{id:s}=Li(),t=Fn(),{user:n}=hs(),{data:r}=rQt(),{data:a,isLoading:i,refetch:l}=I9n(s),{update:o}=nQt(),{save:c}=sQt(),[d,u]=_.useState(null),[h,m]=_.useState(null),[p,f]=_.useState(zWe(null)),[y,v]=_.useState(iQt),[g,b]=_.useState([]),[j,S]=_.useState(FWe),[C,E]=_.useState(OWe),[P,M]=_.useState(null),[I,D]=_.useState(null),[O,V]=_.useState(!1),[G,$]=_.useState(!1),[H,Y]=_.useState(null),[Z,ne]=_.useState(!1),[ce,ie]=_.useState(!1),[te,ae]=_.useState(!1),[le,be]=_.useState(!1),[me,he]=_.useState(!0),[pe,Ce]=_.useState(!1),Ae=_.useRef(null);_.useEffect(()=>{if(!a||d)return;u({title:a.title||"",addressLine1:a.property_address_line1||"",city:a.city||"",state:a.state||"",postalCode:a.postal_code||"",listPrice:a.list_price!=null?String(a.list_price):"",beds:a.beds!=null?String(a.beds):"",baths:a.baths!=null?String(a.baths):"",sqft:a.sqft!=null?String(a.sqft):""});const Ue=a.agent_snapshot;m({...r,...Ue||{}}),f(zWe(a.services)),v(oQt(a.co_agent)),b(cQt(a.custom_pages)),S(a.page_settings&&Object.keys(a.page_settings).length?a.page_settings:FWe),E(a.photo_focal||OWe),M(a.property_photo_path)},[a,r,d]),_.useEffect(()=>{let Ue=!1;return P?QTe(P).then(Xe=>{Ue||D(Xe)}):D(null),()=>{Ue=!0}},[P]);const Pe=_.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:y,custom_pages:g,services:p,page_settings:j,photo_focal:C,property_photo_path:P},[a,d,h,y,g,p,j,C,P]),ze=Ue=>u(Xe=>Xe&&{...Xe,...Ue}),ke=Ue=>m(Xe=>Xe&&{...Xe,...Ue}),Ze=Ue=>(j.hidden||[]).includes(Ue),Se=(Ue,Xe)=>S(nt=>{const $e=new Set(nt.hidden||[]);return Xe?$e.delete(Ue):$e.add(Ue),{...nt,hidden:Array.from($e)}}),Fe=p.filter(Ue=>Ue.enabled),Ne=1+kSt.filter(Ue=>!Ze(Ue)&&Ue!=="overview").length+(Ze("overview")?0:1)+Fe.filter(Ue=>Ue.key!=="communication").length+g.filter(Ue=>Ue.enabled).length,Ye=async(Ue=!1)=>{if(Pe){be(!0);try{await o.mutateAsync({id:Pe.id,title:Pe.title||"Untitled Presentation",property_address_line1:Pe.property_address_line1,city:Pe.city,state:Pe.state,postal_code:Pe.postal_code,list_price:Pe.list_price,beds:Pe.beds,baths:Pe.baths,sqft:Pe.sqft,agent_snapshot:Pe.agent_snapshot,co_agent:Pe.co_agent,custom_pages:Pe.custom_pages,services:Pe.services,page_settings:Pe.page_settings,photo_focal:Pe.photo_focal,property_photo_path:Pe.property_photo_path}),Ue||se.success("Presentation saved")}finally{be(!1)}}},Ve=async Ue=>{if(!(!n||!s)){if(!Ue.type.startsWith("image/")){se.error("Please choose a JPG or PNG photo");return}if(Ue.size>25*1024*1024){se.error("That photo is larger than 25 MB");return}V(!0);try{const Xe=await A$n(n.id,s,Ue);M(Xe);const nt=await QTe(Xe);D(nt?`${nt}${nt.includes("?")?"&":"?"}v=${Date.now()}`:null),await o.mutateAsync({id:s,property_photo_path:Xe}),se.success("Photo uploaded")}catch(Xe){se.error((Xe==null?void 0:Xe.message)||"Upload failed")}finally{V(!1)}}},qe=async()=>{if(Pe){ne(!0);try{const Ue=await SJt(JTe(Pe,r,I),Pe.template_id,P);Y(Ue)}catch(Ue){se.error((Ue==null?void 0:Ue.message)||"Could not build the preview")}finally{ne(!1)}}};_.useEffect(()=>{if(!me||!Pe)return;const Ue=setTimeout(()=>{qe()},900);return()=>clearTimeout(Ue)},[me,Pe]);const Qe=async()=>{if(!(!Pe||!n)){if(!Pe.property_photo_path){se.error("Add the primary exterior photo before generating the PDF");return}ie(!0);try{await Ye(!0);const Ue=await CJt(JTe(Pe,r,I),Pe.template_id,"print",P);await AJt(n.id,Pe.id,Ue),await l(),se.success("Presentation downloaded")}catch(Ue){se.error((Ue==null?void 0:Ue.message)||"Could not build the PDF")}finally{ie(!1)}}};return i||!d||!a?e.jsx(zs,{children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(cn,{className:"h-10 w-64"}),e.jsx(cn,{className:"h-[60vh] w-full rounded-xl"})]})}):e.jsxs(zs,{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(B,{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(xe,{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:[Fe.length," services selected · ",Ne," pages"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{variant:"outline",onClick:()=>Ye(),disabled:le,className:"gap-2",children:[le?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Ho,{className:"h-4 w-4"})," Save"]}),e.jsxs(B,{variant:"outline",onClick:()=>Ce(!0),className:"gap-2",children:[e.jsx(HM,{className:"h-4 w-4"})," Save as template"]}),e.jsxs(B,{variant:"outline",onClick:qe,disabled:Z,className:"gap-2",children:[Z?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(ya,{className:"h-4 w-4"})," Preview"]}),e.jsxs(B,{variant:"outline",onClick:async()=>{await Ye(!0),ae(!0)},className:"gap-2",children:[e.jsx(ln,{className:"h-4 w-4"})," Email"]}),e.jsxs(B,{onClick:Qe,disabled:ce,className:"gap-2",children:[ce?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(li,{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(Yr,{defaultValue:"property",className:"space-y-4",children:[e.jsxs(Zr,{className:"grid w-full grid-cols-4",children:[e.jsx(Ht,{value:"property",children:"Property"}),e.jsx(Ht,{value:"branding",children:"Branding"}),e.jsx(Ht,{value:"plan",children:"Plan"}),e.jsx(Ht,{value:"pages",children:"Pages"})]}),e.jsxs(Gt,{value:"property",className:"space-y-4",children:[e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-3",children:e.jsx(St,{className:"text-base",children:"Property address"})}),e.jsxs(Me,{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Street address"}),e.jsx(xe,{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(J,{children:"City"}),e.jsx(xe,{value:d.city,onChange:Ue=>ze({city:Ue.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"State"}),e.jsx(xe,{value:d.state,onChange:Ue=>ze({state:Ue.target.value})})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"ZIP"}),e.jsx(xe,{value:d.postalCode,onChange:Ue=>ze({postalCode:Ue.target.value})})]}),e.jsx(wc,{}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"List price (optional)"}),e.jsx(xe,{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(J,{children:"Square feet"}),e.jsx(xe,{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(J,{children:"Beds"}),e.jsx(xe,{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(J,{children:"Baths"}),e.jsx(xe,{inputMode:"numeric",value:d.baths,onChange:Ue=>ze({baths:Ue.target.value.replace(/[^0-9.]/g,"")})})]})]})]})]}),e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-3",children:e.jsxs(St,{className:"text-base",children:["Primary exterior photo ",e.jsx("span",{className:"text-destructive",children:"*"})]})}),e.jsxs(Me,{className:"space-y-3",children:[e.jsx("div",{role:"button",tabIndex:0,onClick:()=>{var Ue;return(Ue=Ae.current)==null?void 0:Ue.click()},onKeyDown:Ue=>{var Xe;return Ue.key==="Enter"&&((Xe=Ae.current)==null?void 0:Xe.click())},onDragOver:Ue=>{Ue.preventDefault(),$(!0)},onDragLeave:()=>$(!1),onDrop:Ue=>{var nt;Ue.preventDefault(),$(!1);const Xe=(nt=Ue.dataTransfer.files)==null?void 0:nt[0];Xe&&Ve(Xe)},className:At("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",G&&"border-primary bg-primary/10"),children:I?e.jsx("img",{src:I,alt:"Property exterior",className:"h-full w-full object-cover",style:{objectPosition:`${C.x*100}% ${C.y*100}%`}}):e.jsxs("div",{className:"flex flex-col items-center gap-2 text-muted-foreground",children:[O?e.jsx(Ct,{className:"h-6 w-6 animate-spin"}):e.jsx(jy,{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:Ae,type:"file",accept:"image/*",className:"hidden",onChange:Ue=>{var nt;const Xe=(nt=Ue.target.files)==null?void 0:nt[0];Xe&&Ve(Xe),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(YQ,{className:"h-3.5 w-3.5"})," Reposition crop"]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs",children:"Horizontal"}),e.jsx(kx,{value:[C.x*100],min:0,max:100,step:1,onValueChange:([Ue])=>E(Xe=>({...Xe,x:Ue/100}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs",children:"Vertical"}),e.jsx(kx,{value:[C.y*100],min:0,max:100,step:1,onValueChange:([Ue])=>E(Xe=>({...Xe,y:Ue/100}))})]})]}),e.jsxs(B,{variant:"outline",size:"sm",className:"w-full gap-2",onClick:()=>{var Ue;return(Ue=Ae.current)==null?void 0:Ue.click()},disabled:O,children:[e.jsx(uo,{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(Gt,{value:"branding",className:"space-y-4",children:[e.jsx(IHn,{value:j.theme||Vqn,onChange:Ue=>S(Xe=>({...Xe,theme:Ue}))}),e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(St,{className:"text-base",children:"Your details"}),e.jsx(Oe,{variant:"secondary",className:"text-[10px]",children:"Loaded from your LevelUp profile"})]})}),e.jsx(Me,{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(J,{children:"Name"}),e.jsx(xe,{value:h.name,onChange:Ue=>ke({name:Ue.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Tagline"}),e.jsx(xe,{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(J,{children:"Phone"}),e.jsx(xe,{value:h.phone||"",onChange:Ue=>ke({phone:Ue.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Email"}),e.jsx(xe,{value:h.email||"",onChange:Ue=>ke({email:Ue.target.value})})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Website"}),e.jsx(xe,{value:h.website||"",onChange:Ue=>ke({website:Ue.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Brokerage"}),e.jsx(xe,{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(J,{children:"License #"}),e.jsx(xe,{value:h.licenseNumber||"",onChange:Ue=>ke({licenseNumber:Ue.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"License state"}),e.jsx(xe,{value:h.licenseState||"",onChange:Ue=>ke({licenseState:Ue.target.value})})]})]}),e.jsx(wc,{}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{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(xe,{value:h.brandColor,onChange:Ue=>ke({brandColor:Ue.target.value})})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{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(xe,{value:h.accentColor,onChange:Ue=>ke({accentColor:Ue.target.value})})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Headshot URL"}),e.jsx(xe,{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(J,{children:"Brokerage logo URL"}),e.jsx(xe,{value:h.brokerageLogoUrl||"",onChange:Ue=>ke({brokerageLogoUrl:Ue.target.value})})]}),r&&e.jsxs(B,{variant:"outline",size:"sm",className:"w-full gap-2",onClick:()=>m({...r}),children:[e.jsx(uo,{className:"h-4 w-4"})," Reset to my LevelUp profile"]})]})})]}),e.jsx(LHn,{value:y,onChange:Ue=>v(Xe=>({...Xe,...Ue}))})]}),e.jsx(Gt,{value:"plan",className:"space-y-4",children:e.jsxs(ve,{children:[e.jsxs(bt,{className:"pb-3",children:[e.jsx(St,{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(Me,{children:e.jsx(G9,{type:"multiple",className:"w-full",children:p.slice().sort((Ue,Xe)=>Ue.order-Xe.order).map(Ue=>{var Xe;return e.jsxs(gL,{value:Ue.key,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(fn,{checked:Ue.enabled,onCheckedChange:nt=>f($e=>$e.map(Ge=>Ge.key===Ue.key?{...Ge,enabled:nt}:Ge))}),e.jsx(yL,{className:"flex-1 text-left text-sm",children:Ue.title})]}),e.jsxs(vL,{className:"space-y-3 pt-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Headline"}),e.jsx(xe,{value:Ue.title,onChange:nt=>f($e=>$e.map(Ge=>Ge.key===Ue.key?{...Ge,title:nt.target.value}:Ge))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Description"}),e.jsx(Ms,{rows:4,value:Ue.body,onChange:nt=>f($e=>$e.map(Ge=>Ge.key===Ue.key?{...Ge,body:nt.target.value}:Ge))})]}),!!((Xe=Ue.options)!=null&&Xe.length)&&e.jsxs("div",{className:"space-y-2 rounded-lg border bg-muted/30 p-3",children:[e.jsx(J,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Included in this page"}),Ue.options.map(nt=>e.jsxs("label",{className:"flex items-start gap-2 text-sm",children:[e.jsx($a,{className:"mt-0.5",checked:nt.enabled,onCheckedChange:$e=>f(Ge=>Ge.map(ct=>{var xt;return ct.key===Ue.key?{...ct,options:(xt=ct.options)==null?void 0:xt.map(qt=>qt.key===nt.key?{...qt,enabled:!!$e}:qt)}:ct}))}),e.jsx("span",{className:"leading-snug",children:nt.label})]},nt.key))]})]})]},Ue.key)})})})]})}),e.jsxs(Gt,{value:"pages",className:"space-y-4",children:[e.jsxs(ve,{children:[e.jsxs(bt,{className:"pb-3",children:[e.jsx(St,{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(Me,{className:"space-y-3",children:[kSt.map(Ue=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsx("span",{className:"text-sm",children:B9n[Ue]}),e.jsx(fn,{checked:!Ze(Ue),onCheckedChange:Xe=>Se(Ue,Xe)})]},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"}),!Ze("welcome")&&e.jsx("li",{children:"Marketing commitment"}),!Ze("agent")&&e.jsx("li",{children:"About your agent"}),g.filter(Ue=>Ue.enabled&&Ue.placement!=="end").sort((Ue,Xe)=>Ue.order-Xe.order).map(Ue=>e.jsx("li",{children:Ue.headline||"Custom page"},Ue.id)),!Ze("overview")&&e.jsx("li",{children:"Marketing plan overview"}),Fe.filter(Ue=>Ue.key!=="communication").map(Ue=>e.jsx("li",{children:Ue.title},Ue.key)),g.filter(Ue=>Ue.enabled&&Ue.placement==="end").sort((Ue,Xe)=>Ue.order-Xe.order).map(Ue=>e.jsx("li",{children:Ue.headline||"Custom page"},Ue.id)),!Ze("closing")&&e.jsx("li",{children:"Communication & closing commitment"})]})]})]})]}),e.jsx(FHn,{pages:j,onChange:S}),e.jsxs(ve,{children:[e.jsxs(bt,{className:"pb-3",children:[e.jsx(St,{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(Me,{children:e.jsx(B,{variant:"outline",size:"sm",className:"w-full",onClick:()=>b(Ue=>[...Ue,{...jrt("testimonials",Ue.length),placement:"end"}]),children:`Add a "What they're saying" page`})})]}),e.jsx(OHn,{pages:g,onChange:b})]})]}),e.jsxs(ve,{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(St,{className:"text-base",children:"Live preview"}),e.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(fn,{checked:me,onCheckedChange:he}),"Auto-update"]})]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:qe,disabled:Z,className:"gap-2",children:[Z?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(uo,{className:"h-4 w-4"}),"Refresh"]})]}),e.jsx(Me,{className:"h-[calc(70vh-60px)] p-0",children:H?e.jsx(PHn,{blob:H}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 bg-muted/30 text-center",children:[e.jsx(ya,{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(B,{onClick:qe,disabled:Z,className:"gap-2",children:[Z?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(ya,{className:"h-4 w-4"}),"Generate preview"]})]})})]})]})]}),e.jsx(zHn,{open:pe,onOpenChange:Ce,defaultName:d.title,saving:c.isPending,onSave:async(Ue,Xe)=>{await c.mutateAsync({name:Ue,description:Xe||null,template_id:a.template_id,agent_snapshot:h||{},co_agent:y,custom_pages:g,services:p,page_settings:j})}}),e.jsx(TJt,{open:te,onOpenChange:ae,row:Pe,brand:r,photoUrl:I})]})};function UHn(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 Dts="popby_geocode_cache_v1";function qHn(){try{return JSON.parse(localStorage.getItem(Dts)||"{}")}catch{return{}}}function $Hn(s){try{localStorage.setItem(Dts,JSON.stringify(s))}catch{}}function VHn({contacts:s,onLogPopby:t}){const[n,r]=_.useState(null),[a,i]=_.useState("idle"),[l,o]=_.useState(5),[c,d]=_.useState(""),[u,h]=_.useState(new Map),[m,p]=_.useState(!1);_.useEffect(()=>{(async()=>{const{data:b}=await q.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();b!=null&&b.value&&d(b.value)})()},[]);const f=_.useMemo(()=>s.filter(b=>b.isDue&&(b.address||b.city&&b.state||b.zip)),[s]),y=()=>{if(!("geolocation"in navigator)){i("unavailable");return}i("loading"),navigator.geolocation.getCurrentPosition(b=>{r({lat:b.coords.latitude,lng:b.coords.longitude}),i("ok")},()=>{i("denied")},{enableHighAccuracy:!0,timeout:1e4,maximumAge:6e4})};_.useEffect(()=>{if(!c||!n||f.length===0)return;let b=!1;const j=qHn(),S=new Map;f.forEach(E=>{const P=[E.address,E.city,E.state,E.zip].filter(Boolean).join("|").toLowerCase();j[P]&&S.set(E.id,j[P])}),h(new Map(S));const C=f.filter(E=>!([E.address,E.city,E.state,E.zip].filter(Boolean).join("|").toLowerCase()in j));if(C.length!==0)return p(!0),(async()=>{const E=[...C],P=async()=>{var M,I;for(;E.length&&!b;){const D=E.shift(),O=[D.address,D.city,D.state,D.zip].filter(Boolean),V=O.join("|").toLowerCase(),G=O.join(", ");try{const H=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(G)}.json?limit=1&access_token=${c}`)).json();if((I=(M=H==null?void 0:H.features)==null?void 0:M[0])!=null&&I.center){const[Y,Z]=H.features[0].center;j[V]={lat:Z,lng:Y},S.set(D.id,{lat:Z,lng:Y})}else j[V]=null}catch{}}};await Promise.all([P(),P(),P(),P()]),b||($Hn(j),h(new Map(S)),p(!1))})(),()=>{b=!0}},[c,n,f]);const v=_.useMemo(()=>{if(!n)return[];const b=[];return f.forEach(j=>{const S=u.get(j.id);if(!S)return;const C=UHn(n.lat,n.lng,S.lat,S.lng);C<=l&&b.push({...j,distanceMiles:C,lat:S.lat,lng:S.lng})}),b.sort((j,S)=>j.distanceMiles-S.distanceMiles)},[n,f,u,l]),g=b=>{const S=/iPad|iPhone|iPod/.test(navigator.userAgent)?`https://maps.apple.com/?daddr=${b.lat},${b.lng}`:`https://www.google.com/maps/dir/?api=1&destination=${b.lat},${b.lng}`;window.open(S,"_blank","noopener")};return e.jsxs(ve,{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(St,{className:"flex items-center gap-2 text-lg",children:[e.jsx($q,{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(is,{value:String(l),onValueChange:b=>o(Number(b)),children:[e.jsx(rs,{className:"w-[110px] h-9",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"2",children:"2 miles"}),e.jsx(He,{value:"5",children:"5 miles"}),e.jsx(He,{value:"10",children:"10 miles"}),e.jsx(He,{value:"25",children:"25 miles"})]})]}),e.jsxs(B,{size:"sm",variant:a==="ok"?"outline":"default",onClick:y,disabled:a==="loading",children:[a==="loading"?e.jsx(uo,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx($q,{className:"h-4 w-4 mr-1"}),a==="ok"?"Refresh":"Use my location"]})]})]})}),e.jsxs(Me,{className:"space-y-3",children:[a==="idle"&&e.jsxs("div",{className:"text-center py-6 text-sm text-muted-foreground",children:[e.jsx(Xa,{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&&f.length===0&&e.jsx("div",{className:"text-center py-6 text-sm text-muted-foreground",children:"No due contacts have addresses yet. Add street addresses to your sphere to power this."}),a==="ok"&&c&&f.length>0&&m&&v.length===0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(cn,{className:"h-14 w-full"}),e.jsx(cn,{className:"h-14 w-full"}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"Locating contacts…"})]}),a==="ok"&&c&&!m&&v.length===0&&f.length>0&&e.jsxs("div",{className:"text-center py-6 text-sm text-muted-foreground",children:["No due contacts within ",l," miles. Try widening the radius."]}),v.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Oe,{variant:"secondary",className:"font-medium",children:[v.length," nearby"]}),m&&e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(uo,{className:"h-3 w-3 animate-spin"})," still locating…"]})]}),e.jsx("div",{className:"space-y-2",children:v.map(b=>e.jsxs("div",{className:"flex items-center justify-between gap-3 p-3 rounded-lg bg-card border hover:border-primary/40 transition-colors",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("span",{className:"font-medium truncate",children:[b.first_name," ",b.last_name]}),e.jsx(Oe,{variant:"outline",className:"text-xs",children:b.distanceMiles<1?`${(b.distanceMiles*5280).toFixed(0)} ft`:`${b.distanceMiles.toFixed(1)} mi`}),b.daysOverdue>0&&e.jsxs(Oe,{variant:"destructive",className:"text-xs",children:[b.daysOverdue,"d overdue"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate mt-0.5",children:[b.address,b.city,b.state].filter(Boolean).join(", ")})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[b.phone&&e.jsx(B,{size:"icon",variant:"ghost",asChild:!0,className:"h-9 w-9",title:"Call",children:e.jsx("a",{href:`tel:${b.phone}`,children:e.jsx(_a,{className:"h-4 w-4"})})}),e.jsx(B,{size:"icon",variant:"ghost",onClick:()=>g(b),className:"h-9 w-9",title:"Directions",children:e.jsx(ZQ,{className:"h-4 w-4"})}),e.jsxs(B,{size:"sm",onClick:()=>t(b),children:[e.jsx(Vo,{className:"h-4 w-4 mr-1"}),"Log"]})]})]},b.id))})]})]})]})}const HHn="0dde5abb-0005-4c8c-a471-30d0cbc9e280",GHn=[{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 WHn(){const s=Fn(),t=bYt(),{data:n}=SDn(),{data:r}=Z_(),{data:a}=_nt(),{data:i}=YIe(90),{data:l}=Db(),o=MDn(),c=EDn(),d=ADn(),u=TDn(),{data:h=[],isLoading:m}=at({queryKey:["popby-templates"],queryFn:async()=>{const{data:H,error:Y}=await q.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).eq("category_id",HHn).order("publish_date",{ascending:!1});if(Y)throw Y;const{data:Z}=await q.from("template_likes").select("template_id"),{data:ne}=await q.from("template_comments").select("template_id"),ce=new Map;Z==null||Z.forEach(te=>{ce.set(te.template_id,(ce.get(te.template_id)||0)+1)});const ie=new Map;return ne==null||ne.forEach(te=>{ie.set(te.template_id,(ie.get(te.template_id)||0)+1)}),(H||[]).map(te=>({...te,likesCount:ce.get(te.id)||0,commentsCount:ie.get(te.id)||0}))}}),p=H=>{const Y=l==null?void 0:l.find(Z=>Z.id===H);return Y?`${Y.first_name} ${Y.last_name||""}`.trim():"Unknown"},f=H=>{if(!H)return null;const Y=n==null?void 0:n.find(Z=>Z.id===H);return(Y==null?void 0:Y.name)||null},[y,v]=_.useState(null),[g,b]=_.useState(!1),[j,S]=_.useState(!1),[C,E]=_.useState(!1),[P,M]=_.useState({popby_item_id:"",notes:""}),[I,D]=_.useState({name:"",description:""}),O=async()=>{y&&(await c.mutateAsync({contact_id:y.id,popby_item_id:P.popby_item_id||void 0,notes:P.notes||void 0}),b(!1),v(null),M({popby_item_id:"",notes:""}))},V=async()=>{I.name.trim()&&(await d.mutateAsync({name:I.name.trim(),description:I.description.trim()||void 0}),E(!1),D({name:"",description:""}))},G=async(H,Y)=>{await u.mutateAsync({relationship_type_id:H,frequency_days:parseInt(Y)})},$=H=>{var Z;const Y=a==null?void 0:a.find(ne=>ne.relationship_type_id===H);return((Z=Y==null?void 0:Y.frequency_days)==null?void 0:Z.toString())||"90"};return e.jsx(zs,{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(ve,{children:e.jsxs(Me,{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(ve,{children:e.jsxs(Me,{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(ve,{children:e.jsxs(Me,{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(B,{onClick:()=>s("/mission-control/popbys/map"),children:[e.jsx(Xa,{className:"h-4 w-4 mr-2"}),"View Map"]}),e.jsxs(B,{variant:"outline",onClick:()=>S(!0),children:[e.jsx(qc,{className:"h-4 w-4 mr-2"}),"Frequency Settings"]}),e.jsxs(B,{variant:"outline",onClick:()=>E(!0),children:[e.jsx(rn,{className:"h-4 w-4 mr-2"}),"Add Popby Idea"]})]}),e.jsxs(Yr,{defaultValue:"due",children:[e.jsxs(Zr,{children:[e.jsx(Ht,{value:"due",children:"Due for Popby"}),e.jsx(Ht,{value:"activity",children:"Recent Activity"}),e.jsx(Ht,{value:"library",children:"Popby Library"}),e.jsx(Ht,{value:"templates",children:"Popby Templates"})]}),e.jsxs(Gt,{value:"due",className:"space-y-4 mt-4",children:[e.jsx(VHn,{contacts:t||[],onLogPopby:H=>{v(H),b(!0)}}),!t||t.length===0?e.jsx(ve,{children:e.jsxs(Me,{className:"p-8 text-center text-muted-foreground",children:[e.jsx(Vo,{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(H=>e.jsx(ve,{className:"hover:shadow-md transition-shadow",children:e.jsx(Me,{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:[H.first_name," ",H.last_name]}),H.daysOverdue>0&&e.jsxs(Oe,{variant:"destructive",className:"text-xs",children:[H.daysOverdue,"+ days overdue"]}),H.daysSinceLastPopby===null&&e.jsx(Oe,{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:[H.address&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Xa,{className:"h-3 w-3"}),H.city||H.address]}),H.tags&&H.tags.length>0&&e.jsx("span",{children:H.tags.map(Y=>{var Z;return(Z=Y.relationship_type)==null?void 0:Z.name}).join(", ")})]}),H.lastPopby&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Last popby: ",Hs(new Date(H.lastPopby),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[H.phone&&e.jsx(B,{size:"sm",variant:"ghost",asChild:!0,children:e.jsx("a",{href:`tel:${H.phone}`,children:e.jsx(_a,{className:"h-4 w-4"})})}),e.jsxs(B,{size:"sm",onClick:()=>{v(H),b(!0)},children:[e.jsx(_l,{className:"h-4 w-4 mr-1"}),"Log Popby"]})]})]})})},H.id))})]}),e.jsx(Gt,{value:"activity",className:"space-y-4 mt-4",children:!i||i.length===0?e.jsx(ve,{children:e.jsxs(Me,{className:"p-8 text-center text-muted-foreground",children:[e.jsx(Gr,{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(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-lg",children:"Recent Popby Log"})}),e.jsx(Me,{className:"space-y-3",children:i.map(H=>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(Vo,{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(H.contact_id)}),f(H.popby_item_id)&&e.jsx(Oe,{variant:"secondary",className:"text-xs",children:f(H.popby_item_id)})]}),e.jsx("div",{className:"text-sm text-muted-foreground",children:Hs(new Date(H.completed_at),"MMM d, yyyy h:mm a")}),H.notes&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:H.notes})]})]},H.id))})]})}),e.jsx(Gt,{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(H=>e.jsx(ve,{children:e.jsx(Me,{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(Vo,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-medium",children:H.name}),H.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:H.description}),!H.owner_user_id&&e.jsx(Oe,{variant:"secondary",className:"mt-2 text-xs",children:"Shared"})]})]})})},H.id)),e.jsx(ve,{className:"border-dashed cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>E(!0),children:e.jsx(Me,{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(rn,{className:"h-8 w-8 mx-auto mb-2"}),e.jsx("p",{children:"Add New Popby Idea"})]})})})]})}),e.jsxs(Gt,{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((H,Y)=>e.jsx(ve,{children:e.jsxs(Me,{className:"p-4",children:[e.jsx(cn,{className:"aspect-[3/2] w-full rounded-lg mb-4"}),e.jsx(cn,{className:"h-5 w-3/4 mb-2"}),e.jsx(cn,{className:"h-4 w-full mb-4"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(cn,{className:"h-5 w-16"}),e.jsx(cn,{className:"h-5 w-20"})]})]})},Y))}),!m&&h.length===0&&e.jsx(ve,{children:e.jsxs(Me,{className:"p-8 text-center text-muted-foreground",children:[e.jsx(Nh,{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(H=>e.jsxs(ve,{className:"group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer",onClick:()=>s(`/templates/${H.id}`),children:[e.jsx("div",{className:"relative overflow-hidden bg-muted aspect-[3/2]",children:H.preview_image_url?e.jsx("img",{src:H.preview_image_url,alt:H.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(Me,{className:"p-4 flex flex-col",children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 mb-1",children:H.name}),H.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3 flex-1",children:Hee(H.description)}),e.jsx("div",{className:"flex flex-wrap gap-2 mb-3",children:e.jsx(Oe,{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(Fg,{className:"h-3.5 w-3.5"}),H.likesCount]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ou,{className:"h-3.5 w-3.5"}),H.commentsCount]})]}),e.jsxs(B,{size:"sm",className:"w-full gap-2",onClick:Y=>{Y.stopPropagation(),s(`/templates/${H.id}`)},children:[e.jsx(wr,{className:"h-4 w-4"}),"View Template"]})]})]},H.id))})]})]}),e.jsx(Ls,{open:g,onOpenChange:b,children:e.jsxs(Ps,{children:[e.jsx(Os,{children:e.jsxs(Ds,{children:["Log Popby for ",y==null?void 0:y.first_name," ",y==null?void 0:y.last_name]})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Popby Item (optional)"}),e.jsxs(is,{value:P.popby_item_id,onValueChange:H=>M(Y=>({...Y,popby_item_id:H})),children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Select a popby item..."})}),e.jsx(as,{children:n==null?void 0:n.map(H=>e.jsx(He,{value:H.id,children:H.name},H.id))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Notes (optional)"}),e.jsx(Ms,{placeholder:"Any notes about this popby...",value:P.notes,onChange:H=>M(Y=>({...Y,notes:H.target.value}))})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>b(!1),children:"Cancel"}),e.jsx(B,{onClick:O,disabled:c.isPending,children:"Log Popby"})]})]})}),e.jsx(Ls,{open:j,onOpenChange:S,children:e.jsxs(Ps,{className:"max-w-md",children:[e.jsx(Os,{children:e.jsx(Ds,{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(H=>e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsx(J,{className:"font-medium",children:H.name}),e.jsxs(is,{value:$(H.id),onValueChange:Y=>G(H.id,Y),children:[e.jsx(rs,{className:"w-[180px]",children:e.jsx(ls,{})}),e.jsx(as,{children:GHn.map(Y=>e.jsx(He,{value:Y.value,children:Y.label},Y.value))})]})]},H.id))]}),e.jsx(yr,{children:e.jsx(B,{onClick:()=>S(!1),children:"Done"})})]})}),e.jsx(Ls,{open:C,onOpenChange:E,children:e.jsxs(Ps,{children:[e.jsx(Os,{children:e.jsx(Ds,{children:"Add Popby Idea"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Name *"}),e.jsx(xe,{placeholder:"e.g., Homemade cookies",value:I.name,onChange:H=>D(Y=>({...Y,name:H.target.value}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Description"}),e.jsx(Ms,{placeholder:"Optional description...",value:I.description,onChange:H=>D(Y=>({...Y,description:H.target.value}))})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>E(!1),children:"Cancel"}),e.jsx(B,{onClick:V,disabled:!I.name.trim()||d.isPending,children:"Add Item"})]})]})})]})})}const KHn=Bj({property_address:Zo().min(1,"Property address is required"),city:Zo().optional(),state:Zo().optional(),zip:Zo().optional(),transaction_type:zQe(["buyer","seller"]),close_date:Zo().min(1,"Close date is required"),sale_price:_J().min(0,"Sale price must be positive"),commission_amount:_J().optional(),lead_source_id:Zo().optional(),client_type_id:Zo().optional(),contact_id:Zo().optional(),notes:Zo().optional(),is_win:A4s()});function Rts({open:s,onOpenChange:t,transaction:n}){const[r,a]=_.useState(!1),[i,l]=_.useState(""),[o,c]=_.useState(!1),[d,u]=_.useState(""),h=hLe(),m=YUs(),{data:p}=V9(),{data:f}=Z_(),{data:y}=Db(),v=iLe(),g=vet(),{data:b}=mLe(),j=(b==null?void 0:b.show_commission)??!0,S=rPe({resolver:aPe(KHn),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}});_.useEffect(()=>{n?S.reset({property_address:n.property_address,city:n.city||"",state:n.state||"",zip:n.zip||"",transaction_type:n.transaction_type,close_date:n.close_date,sale_price:Number(n.sale_price),commission_amount:n.commission_amount?Number(n.commission_amount):void 0,lead_source_id:n.lead_source_id||void 0,client_type_id:n.client_type_id||void 0,contact_id:n.contact_id||void 0,notes:n.notes||"",is_win:n.is_win}):S.reset({property_address:"",city:"",state:"",zip:"",transaction_type:"buyer",close_date:new Date().toISOString().split("T")[0],sale_price:0,commission_amount:void 0,lead_source_id:void 0,client_type_id:void 0,contact_id:void 0,notes:"",is_win:!1})},[n,S]);const C=async 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)},E=async()=>{if(!i.trim())return;const[I,...D]=i.trim().split(" "),O=D.join(" ")||null,V=await v.mutateAsync({first_name:I,last_name:O,tagIds:[]});V&&(S.setValue("contact_id",V.id),l(""),c(!1),a(!1))},P=async()=>{if(!d.trim())return;const I=await g.mutateAsync(d.trim());I&&(S.setValue("lead_source_id",I.id),u(""))},M=y==null?void 0:y.find(I=>I.id===S.watch("contact_id"));return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"max-w-lg max-h-[90vh]",children:[e.jsx(Os,{children:e.jsx(Ds,{children:n?"Edit Transaction":"Add Transaction"})}),e.jsx(Ji,{className:"max-h-[70vh] pr-4",children:e.jsx(cPe,{...S,children:e.jsxs("form",{onSubmit:S.handleSubmit(C),className:"space-y-4",children:[e.jsx(Sf,{control:S.control,name:"property_address",render:({field:I})=>e.jsxs(Yp,{children:[e.jsx(Zp,{children:"Property Address *"}),e.jsx(Xp,{children:e.jsx(xe,{placeholder:"123 Main St",...I})}),e.jsx(ub,{})]})}),e.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[e.jsx(Sf,{control:S.control,name:"city",render:({field:I})=>e.jsxs(Yp,{children:[e.jsx(Zp,{children:"City"}),e.jsx(Xp,{children:e.jsx(xe,{placeholder:"City",...I})})]})}),e.jsx(Sf,{control:S.control,name:"state",render:({field:I})=>e.jsxs(Yp,{children:[e.jsx(Zp,{children:"State"}),e.jsx(Xp,{children:e.jsx(xe,{placeholder:"TX",...I})})]})}),e.jsx(Sf,{control:S.control,name:"zip",render:({field:I})=>e.jsxs(Yp,{children:[e.jsx(Zp,{children:"Zip"}),e.jsx(Xp,{children:e.jsx(xe,{placeholder:"75001",...I})})]})})]}),e.jsx(Sf,{control:S.control,name:"transaction_type",render:({field:I})=>e.jsxs(Yp,{children:[e.jsx(Zp,{children:"Transaction Type *"}),e.jsxs(is,{onValueChange:I.onChange,value:I.value,children:[e.jsx(Xp,{children:e.jsx(rs,{children:e.jsx(ls,{placeholder:"Select type"})})}),e.jsxs(as,{children:[e.jsx(He,{value:"buyer",children:"Buyer"}),e.jsx(He,{value:"seller",children:"Seller"})]})]}),e.jsx(ub,{})]})}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx(Sf,{control:S.control,name:"close_date",render:({field:I})=>e.jsxs(Yp,{children:[e.jsx(Zp,{children:"Close Date *"}),e.jsx(Xp,{children:e.jsx(xe,{type:"date",...I})}),e.jsx(ub,{})]})}),e.jsx(Sf,{control:S.control,name:"sale_price",render:({field:I})=>e.jsxs(Yp,{children:[e.jsx(Zp,{children:"Sale Price *"}),e.jsx(Xp,{children:e.jsx(xe,{type:"number",placeholder:"0",...I,onChange:D=>I.onChange(Number(D.target.value))})}),e.jsx(ub,{})]})})]}),j&&e.jsx(Sf,{control:S.control,name:"commission_amount",render:({field:I})=>e.jsxs(Yp,{children:[e.jsx(Zp,{children:"Commission"}),e.jsx(Xp,{children:e.jsx(xe,{type:"number",placeholder:"0",...I,value:I.value??"",onChange:D=>I.onChange(D.target.value?Number(D.target.value):void 0)})})]})}),e.jsx(Sf,{control:S.control,name:"lead_source_id",render:({field:I})=>e.jsxs(Yp,{children:[e.jsx(Zp,{children:"Lead Source"}),e.jsxs(is,{onValueChange:I.onChange,value:I.value||"",children:[e.jsx(Xp,{children:e.jsx(rs,{children:e.jsx(ls,{placeholder:"Select source"})})}),e.jsx(as,{children:p==null?void 0:p.map(D=>e.jsx(He,{value:D.id,children:D.name},D.id))})]})]})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{placeholder:"Add custom source...",value:d,onChange:I=>u(I.target.value),className:"flex-1"}),e.jsx(B,{type:"button",variant:"outline",size:"icon",onClick:P,disabled:!d.trim(),children:e.jsx(rn,{className:"h-4 w-4"})})]}),e.jsx(Sf,{control:S.control,name:"client_type_id",render:({field:I})=>e.jsxs(Yp,{children:[e.jsx(Zp,{children:"Client Type"}),e.jsxs(is,{onValueChange:I.onChange,value:I.value||"",children:[e.jsx(Xp,{children:e.jsx(rs,{children:e.jsx(ls,{placeholder:"Select client type"})})}),e.jsx(as,{children:f==null?void 0:f.map(D=>e.jsx(He,{value:D.id,children:D.name},D.id))})]})]})}),e.jsx(Sf,{control:S.control,name:"contact_id",render:({field:I})=>e.jsxs(Yp,{children:[e.jsx(Zp,{children:"Client Contact"}),e.jsxs(od,{open:r,onOpenChange:a,children:[e.jsx(ld,{asChild:!0,children:e.jsx(Xp,{children:e.jsxs(B,{variant:"outline",role:"combobox",className:At("w-full justify-between",!I.value&&"text-muted-foreground"),children:[M?`${M.first_name} ${M.last_name||""}`.trim():"Select contact",e.jsx(I_,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})})}),e.jsxs(Qc,{className:"w-full p-0",align:"start",children:[e.jsxs(Aj,{children:[e.jsx(Ej,{placeholder:"Search contacts..."}),e.jsxs(Tj,{children:[e.jsx(Mj,{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(B,{variant:"outline",size:"sm",className:"w-full",onClick:()=>c(!0),children:[e.jsx(rn,{className:"h-4 w-4 mr-2"}),"Add New Contact"]})]})}),e.jsx(V_,{children:y==null?void 0:y.map(D=>e.jsxs(d1,{value:`${D.first_name} ${D.last_name||""}`,onSelect:()=>{I.onChange(D.id),a(!1)},children:[e.jsx(ea,{className:At("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(xe,{placeholder:"Enter contact name...",value:i,onChange:D=>l(D.target.value)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{size:"sm",onClick:E,disabled:!i.trim()||v.isPending,children:"Add Contact"}),e.jsx(B,{size:"sm",variant:"outline",onClick:()=>{c(!1),l("")},children:"Cancel"})]})]})]})]})]})}),e.jsx(Sf,{control:S.control,name:"notes",render:({field:I})=>e.jsxs(Yp,{children:[e.jsx(Zp,{children:"Notes"}),e.jsx(Xp,{children:e.jsx(Ms,{placeholder:"Any notes about this transaction...",...I})})]})}),e.jsx(Sf,{control:S.control,name:"is_win",render:({field:I})=>e.jsxs(Yp,{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(Zp,{children:"Mark as Win 🏆"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Highlight this as a notable success"})]}),e.jsx(Xp,{children:e.jsx(fn,{checked:I.value,onCheckedChange:I.onChange})})]})}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{type:"submit",disabled:h.isPending||m.isPending,children:[n?"Update":"Add"," Transaction"]})]})]})})})]})})}function tat({transactions:s,showCommission:t,isLoading:n,agentNameMap:r,readOnly:a}){const[i,l]=_.useState(null),[o,c]=_.useState(null),[d,u]=_.useState(""),[h,m]=_.useState("all"),[p,f]=_.useState("all"),[y,v]=_.useState("all"),[g,b]=_.useState(!1),j=ZUs(),S=hLe(),{data:C}=V9();Z_();const E=$W(),P=D=>{const{id:O,created_at:V,updated_at:G,lead_source:$,client_type:H,contact:Y,...Z}=D;S.mutate(Z)},M=()=>{o&&(j.mutate(o),c(null))},I=s.filter(D=>{var Y,Z,ne,ce;const O=d===""||D.property_address.toLowerCase().includes(d.toLowerCase())||((Z=(Y=D.contact)==null?void 0:Y.first_name)==null?void 0:Z.toLowerCase().includes(d.toLowerCase()))||((ce=(ne=D.contact)==null?void 0:ne.last_name)==null?void 0:ce.toLowerCase().includes(d.toLowerCase())),V=h==="all"||D.transaction_type===h,G=p==="all"||D.lead_source_id===p,$=y==="all"||D.client_type_id===y,H=!g||D.is_win;return O&&V&&G&&$&&H});return n?e.jsx(ve,{children:e.jsx(Me,{className:"p-6 space-y-4",children:[1,2,3].map(D=>e.jsx(cn,{className:"h-16 w-full"},D))})}):e.jsxs(e.Fragment,{children:[e.jsxs(ve,{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(St,{children:["Transactions (",I.length,")"]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Lr,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search...",value:d,onChange:D=>u(D.target.value),className:"pl-8 w-[150px]"})]}),e.jsxs(is,{value:h,onValueChange:m,children:[e.jsx(rs,{className:"w-[100px]",children:e.jsx(ls,{placeholder:"Type"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Types"}),e.jsx(He,{value:"buyer",children:"Buyer"}),e.jsx(He,{value:"seller",children:"Seller"})]})]}),e.jsxs(is,{value:p,onValueChange:f,children:[e.jsx(rs,{className:"w-[130px]",children:e.jsx(ls,{placeholder:"Lead Source"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Sources"}),C==null?void 0:C.map(D=>e.jsx(He,{value:D.id,children:D.name},D.id))]})]}),e.jsxs(B,{variant:g?"default":"outline",size:"sm",onClick:()=>b(!g),children:[e.jsx(Hh,{className:"h-4 w-4 mr-1"}),"Wins"]})]})]})}),e.jsx(Me,{children:I.length===0?e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No transactions found"}):E?e.jsx("div",{className:"space-y-3",children:I.map(D=>e.jsxs(ve,{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(Hh,{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(Oe,{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: "}),Bht(D.close_date)]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Price: "}),am(D.sale_price)]}),t&&D.commission_amount&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Commission: "}),am(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(B,{variant:"ghost",size:"sm",onClick:()=>l(D),children:e.jsx(wp,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>P(D),children:e.jsx(Ia,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>c(D.id),children:e.jsx(Sn,{className:"h-4 w-4 text-destructive"})})]})]},D.id))}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[r&&e.jsx(Pt,{children:"Agent"}),e.jsx(Pt,{children:"Property"}),e.jsx(Pt,{children:"Type"}),e.jsx(Pt,{children:"Close Date"}),e.jsx(Pt,{children:"Sale Price"}),t&&e.jsx(Pt,{children:"Commission"}),e.jsx(Pt,{children:"Lead Source"}),e.jsx(Pt,{children:"Client"}),!a&&e.jsx(Pt,{className:"w-[50px]"})]})}),e.jsx(Ka,{children:I.map(D=>{var O;return e.jsxs(pn,{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(Hh,{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(Oe,{variant:D.transaction_type==="buyer"?"default":"secondary",children:D.transaction_type})}),e.jsx(gt,{children:Bht(D.close_date)}),e.jsx(gt,{children:am(D.sale_price)}),t&&e.jsx(gt,{children:D.commission_amount?am(D.commission_amount):"-"}),e.jsx(gt,{children:((O=D.lead_source)==null?void 0:O.name)||"-"}),e.jsx(gt,{children:D.contact?`${D.contact.first_name} ${D.contact.last_name||""}`.trim():"-"}),!a&&e.jsx(gt,{children:e.jsxs(tu,{children:[e.jsx(su,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",children:e.jsx(Xx,{className:"h-4 w-4"})})}),e.jsxs(Od,{align:"end",children:[e.jsxs(ca,{onClick:()=>l(D),children:[e.jsx(wp,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsxs(ca,{onClick:()=>P(D),children:[e.jsx(Ia,{className:"h-4 w-4 mr-2"}),"Duplicate"]}),e.jsxs(ca,{onClick:()=>c(D.id),className:"text-destructive",children:[e.jsx(Sn,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})})]},D.id)})})]})})})]}),e.jsx(Rts,{open:!!i,onOpenChange:D=>!D&&l(null),transaction:i||void 0}),e.jsx(Kl,{open:!!o,onOpenChange:D=>!D&&c(null),children:e.jsxs(Ol,{children:[e.jsxs(zl,{children:[e.jsx(Ul,{children:"Delete Transaction?"}),e.jsx(ql,{children:"This action cannot be undone. This will permanently delete this transaction."})]}),e.jsxs(Bl,{children:[e.jsx($l,{children:"Cancel"}),e.jsx(Ml,{onClick:M,className:"bg-destructive text-destructive-foreground",children:"Delete"})]})]})})]})}function Fts({goals:s,stats:t,year:n,showCommission:r}){const a=new Date().getMonth()+1,i=new Date().getFullYear()===n?a:12,l=12-i,o=(m,p)=>{if(!p||p===0)return null;const f=Math.min(m/p*100,100),y=Math.max(p-m,0),v=l>0?y/l:0,g=i/12*100,b=f>=g?"ahead":f>=g*.8?"on-track":"behind";return{percent:f,remaining:y,pace:v,status:b}},c=o(t.totalTransactions,s.transactions_goal),d=o(t.totalVolume,s.volume_goal),u=r?o(t.totalCommission,s.gci_goal):null,h=m=>{switch(m){case"ahead":return e.jsxs(Oe,{className:"bg-green-500 text-white",children:[e.jsx(Nl,{className:"h-3 w-3 mr-1"}),"Ahead"]});case"on-track":return e.jsxs(Oe,{variant:"secondary",children:[e.jsx(uN,{className:"h-3 w-3 mr-1"}),"On Track"]});case"behind":return e.jsxs(Oe,{variant:"destructive",children:[e.jsx(gS,{className:"h-3 w-3 mr-1"}),"Behind"]});default:return null}};return!s.transactions_goal&&!s.volume_goal&&!s.gci_goal?null:e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ku,{className:"h-5 w-5 text-primary"}),e.jsxs(St,{children:[n," Goals Progress"]})]})}),e.jsx(Me,{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(Fi,{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(Fi,{value:d.percent,className:"h-2"}),e.jsxs("div",{className:"flex justify-between text-sm text-muted-foreground",children:[e.jsxs("span",{children:[am(t.totalVolume,!0)," of ",am(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 ",am(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(Fi,{value:u.percent,className:"h-2"}),e.jsxs("div",{className:"flex justify-between text-sm text-muted-foreground",children:[e.jsxs("span",{children:[am(t.totalCommission,!0)," of ",am(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 ",am(u.pace,!0),"/month"]})]})]})})]})}const YHn={light:"",dark:".dark"},Ots=_.createContext(null);function zts(){const s=_.useContext(Ots);if(!s)throw new Error("useChart must be used within a ");return s}const Bts=_.forwardRef(({id:s,className:t,children:n,config:r,...a},i)=>{const l=_.useId(),o=`chart-${s||l.replace(/:/g,"")}`;return e.jsx(Ots.Provider,{value:{config:r},children:e.jsxs("div",{"data-chart":o,ref:i,className:At("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(ZHn,{id:o,config:r}),e.jsx(jb,{children:n})]})})});Bts.displayName="Chart";const ZHn=({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(YHn).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},Uts=_.forwardRef(({active:s,payload:t,className:n,indicator:r="dot",hideLabel:a=!1,hideIndicator:i=!1,label:l,labelFormatter:o,labelClassName:c,formatter:d,color:u,nameKey:h,labelKey:m},p)=>{const{config:f}=zts(),y=_.useMemo(()=>{var C;if(a||!(t!=null&&t.length))return null;const[g]=t,b=`${m||g.dataKey||g.name||"value"}`,j=_Ye(f,g,b),S=!m&&typeof l=="string"?((C=f[l])==null?void 0:C.label)||l:j==null?void 0:j.label;return o?e.jsx("div",{className:At("font-medium",c),children:o(S,t)}):S?e.jsx("div",{className:At("font-medium",c),children:S}):null},[l,o,t,a,c,f,m]);if(!s||!(t!=null&&t.length))return null;const v=t.length===1&&r!=="dot";return e.jsxs("div",{ref:p,className:At("grid min-w-[8rem] items-start gap-1.5 rounded-lg border border-border/50 bg-background px-2.5 py-1.5 text-xs shadow-xl",n),children:[v?null:y,e.jsx("div",{className:"grid gap-1.5",children:t.map((g,b)=>{const j=`${h||g.name||g.dataKey||"value"}`,S=_Ye(f,g,j),C=u||g.payload.fill||g.color;return e.jsx("div",{className:At("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&&(g==null?void 0:g.value)!==void 0&&g.name?d(g.value,g.name,g,b,g.payload):e.jsxs(e.Fragment,{children:[S!=null&&S.icon?e.jsx(S.icon,{}):!i&&e.jsx("div",{className:At("shrink-0 rounded-[2px] border-[--color-border] bg-[--color-bg]",{"h-2.5 w-2.5":r==="dot","w-1":r==="line","w-0 border-[1.5px] border-dashed bg-transparent":r==="dashed","my-0.5":v&&r==="dashed"}),style:{"--color-bg":C,"--color-border":C}}),e.jsxs("div",{className:At("flex flex-1 justify-between leading-none",v?"items-end":"items-center"),children:[e.jsxs("div",{className:"grid gap-1.5",children:[v?y:null,e.jsx("span",{className:"text-muted-foreground",children:(S==null?void 0:S.label)||g.name})]}),g.value&&e.jsx("span",{className:"font-mono font-medium tabular-nums text-foreground",children:g.value.toLocaleString()})]})]})},g.dataKey)})})]})});Uts.displayName="ChartTooltip";const XHn=_.forwardRef(({className:s,hideIcon:t=!1,payload:n,verticalAlign:r="bottom",nameKey:a},i)=>{const{config:l}=zts();return n!=null&&n.length?e.jsx("div",{ref:i,className:At("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=_Ye(l,o,c);return e.jsxs("div",{className:At("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});XHn.displayName="ChartLegend";function _Ye(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 pde=["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 sat({stats:s,year:t}){const n=s.transactionsByMonth.some(a=>a.count>0),r=s.leadSourceBreakdown.length>0;return!n&&!r?e.jsx(ve,{children:e.jsx(Me,{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(ve,{className:"overflow-hidden",children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"Transactions by Month"})}),e.jsx(Me,{className:"overflow-hidden",children:e.jsx(Bts,{config:{count:{label:"Transactions",color:"hsl(var(--primary))"}},className:"h-[250px]",children:e.jsx(jb,{width:"100%",height:"100%",children:e.jsxs(BW,{data:s.transactionsByMonth,margin:{top:5,right:10,left:0,bottom:5},children:[e.jsx(kE,{strokeDasharray:"3 3",className:"stroke-muted"}),e.jsx(Mv,{dataKey:"month",tick:{fontSize:11},className:"fill-muted-foreground",interval:0}),e.jsx(Pv,{allowDecimals:!1,tick:{fontSize:12},className:"fill-muted-foreground",width:30}),e.jsx(Mf,{content:e.jsx(Uts,{})}),e.jsx(H_,{dataKey:"count",fill:"hsl(var(--primary))",radius:[4,4,0,0],name:"Transactions"})]})})})})]}),r&&e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"Lead Sources"})}),e.jsxs(Me,{children:[e.jsx("div",{className:"h-[250px]",children:e.jsx(jb,{width:"100%",height:"100%",children:e.jsxs(wKt,{children:[e.jsx(EC,{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(tz,{fill:pde[i%pde.length]},`cell-${i}`))}),e.jsx(Mf,{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:pde[i%pde.length]}}),e.jsx("span",{className:"text-muted-foreground",children:a.name})]},a.name))})]})]})]})}function QHn(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=YQe(t,r,new Date);if(I$e(a))return Hs(a,"yyyy-MM-dd")}catch{}try{const r=new Date(t);if(I$e(r))return Hs(r,"yyyy-MM-dd")}catch{}return null}const JHn=["property_address","city","state","zip","transaction_type","close_date","sale_price","commission_amount","lead_source","client_type","is_win","notes"];function eGn({open:s,onOpenChange:t}){const[n,r]=_.useState([]),[a,i]=_.useState(!1),[l,o]=_.useState(0),{data:c}=V9(),{data:d}=Z_(),u=hLe(),h=()=>{const g=JHn.join(","),b=["123 Main St","Dallas","TX","75001","buyer","2024-06-15","450000","13500","Referral","Past Client","yes","Great transaction!"].join(","),j=`${g} ${b}`,S=new Blob([j],{type:"text/csv"}),C=URL.createObjectURL(S),E=document.createElement("a");E.href=C,E.download="transaction-import-template.csv",E.click(),URL.revokeObjectURL(C)},m=g=>{const b=g.split(` `).filter(S=>S.trim());if(b.length<2)return[];const j=b[0].split(",").map(S=>S.trim().toLowerCase().replace(/['"]/g,""));return b.slice(1).map((S,C)=>{var Z,ne,ce,ie;const E=[];let P="",M=!1;for(const te of S)te==='"'?M=!M:te===","&&!M?(E.push(P.trim()),P=""):P+=te;E.push(P.trim());const I=te=>{var le;const ae=j.indexOf(te);return ae>=0?(le=E[ae])==null?void 0:le.replace(/^["']|["']$/g,"").trim():""},D=(Z=I("transaction_type"))==null?void 0:Z.toLowerCase(),O=(ne=I("sale_price"))==null?void 0:ne.replace(/[$,]/g,""),V=(ce=I("commission_amount"))==null?void 0:ce.replace(/[$,]/g,""),G=(ie=I("is_win"))==null?void 0:ie.toLowerCase(),$=I("close_date"),H=QHn($);let Y;return I("property_address")?["buyer","seller"].includes(D)?H?(!O||isNaN(Number(O)))&&(Y="Invalid sale price"):Y=`Invalid date format: "${$}" - use MM/DD/YYYY or YYYY-MM-DD`:Y='Transaction type must be "buyer" or "seller"':Y="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:H||"",sale_price:Number(O)||0,commission_amount:V?Number(V):null,lead_source_name:I("lead_source"),client_type_name:I("client_type"),is_win:["yes","true","1"].includes(G),notes:I("notes"),error:Y}})},p=g=>{var S;const b=(S=g.target.files)==null?void 0:S[0];if(!b)return;const j=new FileReader;j.onload=C=>{var M;const E=(M=C.target)==null?void 0:M.result,P=m(E);r(P)},j.readAsText(b)},f=async()=>{const g=n.filter(S=>!S.error);if(g.length===0){se.error("No valid transactions to import");return}i(!0),o(0);let b=0,j=0;for(let S=0;SM.name.toLowerCase()===C.lead_source_name.toLowerCase()),P=d==null?void 0:d.find(M=>M.name.toLowerCase()===C.client_type_name.toLowerCase());await u.mutateAsync({property_address:C.property_address,city:C.city||null,state:C.state||null,zip:C.zip||null,transaction_type:C.transaction_type,close_date:C.close_date,sale_price:C.sale_price,commission_amount:C.commission_amount,lead_source_id:(E==null?void 0:E.id)||null,client_type_id:(P==null?void 0:P.id)||null,contact_id:null,notes:C.notes||null,is_win:C.is_win}),b++}catch(E){j++,console.error("Failed to import transaction:",E)}o(Math.round((S+1)/g.length*100))}i(!1),b>0&&se.success(`Imported ${b} transaction${b>1?"s":""}`),j>0&&se.error(`Failed to import ${j} transaction${j>1?"s":""}`),r([]),t(!1)},y=n.filter(g=>!g.error).length,v=n.filter(g=>g.error).length;return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"max-w-2xl max-h-[90vh]",children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Import Transactions"}),e.jsx(_r,{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(B,{variant:"outline",onClick:h,children:[e.jsx(li,{className:"h-4 w-4 mr-2"}),"Template"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"csv-file",children:"Upload CSV File"}),e.jsx(xe,{id:"csv-file",type:"file",accept:".csv",onChange:p})]}),n.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Oe,{variant:"outline",children:[n.length," rows found"]}),y>0&&e.jsxs(Oe,{className:"bg-green-500 text-white",children:[e.jsx(ea,{className:"h-3 w-3 mr-1"}),y," valid"]}),v>0&&e.jsxs(Oe,{variant:"destructive",children:[e.jsx(Xo,{className:"h-3 w-3 mr-1"}),v," errors"]})]}),e.jsx(Ji,{className:"h-[200px] border rounded-lg",children:e.jsxs("div",{className:"p-2 space-y-2",children:[n.slice(0,10).map((g,b)=>e.jsxs("div",{className:`p-2 rounded text-sm ${g.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:g.property_address||"(no address)"}),e.jsx(Oe,{variant:g.transaction_type==="buyer"?"default":"secondary",children:g.transaction_type})]}),e.jsxs("div",{className:"text-muted-foreground",children:[g.close_date," • $",g.sale_price.toLocaleString()]}),g.error&&e.jsx(Ete,{variant:"destructive",className:"mt-1 py-1",children:e.jsx(Tte,{className:"text-xs",children:g.error})})]},b)),n.length>10&&e.jsxs("p",{className:"text-center text-sm text-muted-foreground",children:["...and ",n.length-10," more"]})]})}),a&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"w-full bg-muted rounded-full h-2",children:e.jsx("div",{className:"bg-primary h-2 rounded-full transition-all",style:{width:`${l}%`}})}),e.jsxs("p",{className:"text-sm text-center text-muted-foreground",children:["Importing... ",l,"%"]})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{onClick:f,disabled:y===0||a,children:[e.jsx(Oa,{className:"h-4 w-4 mr-2"}),"Import ",y," Transaction",y!==1?"s":""]})]})]})]})})}const tGn=Bj({transactions_goal:_J().min(0).optional(),volume_goal:_J().min(0).optional(),gci_goal:_J().min(0).optional()});function sGn({open:s,onOpenChange:t,year:n,existingGoals:r}){const a=XUs(),{data:i}=mLe(),l=(i==null?void 0:i.show_commission)??!0,o=rPe({resolver:aPe(tGn),defaultValues:{transactions_goal:void 0,volume_goal:void 0,gci_goal:void 0}});_.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(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"max-w-md",children:[e.jsxs(Os,{children:[e.jsxs(Ds,{children:[n," Goals"]}),e.jsx(_r,{children:"Set your annual targets to track your progress throughout the year."})]}),e.jsx(cPe,{...o,children:e.jsxs("form",{onSubmit:o.handleSubmit(c),className:"space-y-4",children:[e.jsx(Sf,{control:o.control,name:"transactions_goal",render:({field:d})=>e.jsxs(Yp,{children:[e.jsx(Zp,{children:"Transactions Goal"}),e.jsx(Xp,{children:e.jsx(xe,{type:"number",placeholder:"e.g., 24",...d,value:d.value??"",onChange:u=>d.onChange(u.target.value?Number(u.target.value):void 0)})}),e.jsx(b4e,{children:"Total number of deals you want to close"}),e.jsx(ub,{})]})}),e.jsx(Sf,{control:o.control,name:"volume_goal",render:({field:d})=>e.jsxs(Yp,{children:[e.jsx(Zp,{children:"Volume Goal ($)"}),e.jsx(Xp,{children:e.jsx(xe,{type:"number",placeholder:"e.g., 5000000",...d,value:d.value??"",onChange:u=>d.onChange(u.target.value?Number(u.target.value):void 0)})}),e.jsx(b4e,{children:"Total sales volume you want to achieve"}),e.jsx(ub,{})]})}),l&&e.jsx(Sf,{control:o.control,name:"gci_goal",render:({field:d})=>e.jsxs(Yp,{children:[e.jsx(Zp,{children:"GCI Goal ($)"}),e.jsx(Xp,{children:e.jsx(xe,{type:"number",placeholder:"e.g., 150000",...d,value:d.value??"",onChange:u=>d.onChange(u.target.value?Number(u.target.value):void 0)})}),e.jsx(b4e,{children:"Gross commission income target"}),e.jsx(ub,{})]})}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(B,{type:"submit",disabled:a.isPending,children:"Save Goals"})]})]})})]})})}function nat({transactions:s,isLoading:t}){const n=_.useRef(null),r=_.useRef(null),a=_.useRef([]),i=_.useRef(null),{isAdmin:l}=hs(),[o,c]=_.useState(""),[d,u]=_.useState(!0),[h,m]=_.useState(0),[p,f]=_.useState(!1),y=s.filter(g=>g.latitude!=null&&g.longitude!=null),v=s.filter(g=>g.latitude==null||g.longitude==null);return _.useEffect(()=>{(async()=>{u(!0);try{const{data:b}=await q.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();b!=null&&b.value&&c(b.value)}catch(b){console.error("Error fetching mapbox token:",b)}u(!1)})()},[]),_.useEffect(()=>{if(!o||v.length===0||p)return;(async()=>{var j;f(!0);let b=0;for(const S of v){const C=[S.property_address,S.city,S.state,S.zip].filter(Boolean).join(", ");if(C)try{const P=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(C)}.json?access_token=${o}&limit=1`)).json();if((j=P.features)!=null&&j[0]){const[M,I]=P.features[0].center;await q.from("scorecard_transactions").update({latitude:I,longitude:M}).eq("id",S.id),S.latitude=I,S.longitude=M,b++}}catch(E){console.error("Geocode error:",E)}}m(b),f(!1)})()},[o,s]),_.useEffect(()=>{if(!n.current||!o||r.current)return;Id.accessToken=o;const g=s.filter(S=>S.latitude!=null&&S.longitude!=null);let b=[-98.5795,39.8283],j=4;if(g.length>0){const S=g.reduce((E,P)=>E+P.longitude,0)/g.length,C=g.reduce((E,P)=>E+P.latitude,0)/g.length;b=[S,C],j=g.length===1?12:10}return r.current=new Id.Map({container:n.current,style:"mapbox://styles/mapbox/light-v11",zoom:j,center:b}),r.current.addControl(new Id.NavigationControl,"top-right"),()=>{var S;(S=r.current)==null||S.remove(),r.current=null}},[o]),_.useEffect(()=>{var b;if(!r.current||!o)return;a.current.forEach(j=>j.remove()),a.current=[],(b=i.current)==null||b.remove();const g=s.filter(j=>j.latitude!=null&&j.longitude!=null);if(g.forEach(j=>{var I;const S=j.transaction_type==="buyer",C=S?"#3B82F6":"#10B981",E=document.createElement("div");E.className="cursor-pointer",E.innerHTML=`
${S?'':''}
`;const P=new Id.Popup({offset:25,closeButton:!0}).setHTML(`
${j.property_address}
${j.city?`
${j.city}${j.state?", "+j.state:""} ${j.zip||""}
`:""}
${S?"Buyer":"Seller"} $${Number(j.sale_price).toLocaleString()}
Closed: ${Ru(j.close_date).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})} ${(I=j.lead_source)!=null&&I.name?" · "+j.lead_source.name:""}
${j.contact?`
Client: ${j.contact.first_name} ${j.contact.last_name||""}
`:""}
`),M=new Id.Marker(E).setLngLat([j.longitude,j.latitude]).setPopup(P).addTo(r.current);a.current.push(M)}),g.length>1){const j=new Id.LngLatBounds;g.forEach(S=>j.extend([S.longitude,S.latitude])),r.current.fitBounds(j,{padding:60,maxZoom:13})}else g.length===1&&r.current.flyTo({center:[g[0].longitude,g[0].latitude],zoom:12})},[s,o,p]),d||t?e.jsx(ve,{children:e.jsx(Me,{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(ve,{children:e.jsxs(Me,{className:"flex flex-col items-center justify-center h-[50vh] text-center gap-3",children:[e.jsx(Xa,{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:[y.length," of ",s.length," mapped",p&&" · Geocoding..."]})]}),e.jsx("div",{ref:n,className:"w-full h-[55vh] rounded-lg shadow-lg border"})]}):e.jsx(ve,{children:e.jsxs(Me,{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 qts=()=>{const{data:s}=G_();return at({queryKey:["team-scorecard-members",s==null?void 0:s.teamId],queryFn:async()=>{const{data:t,error:n}=await q.from("team_members").select("user_id").eq("team_id",s.teamId);if(n)throw n;const r=t.map(l=>l.user_id),{data:a,error:i}=await q.from("profiles").select("id, name, email, avatar_url").in("id",r);if(i)throw i;return a||[]},enabled:!!(s!=null&&s.teamId)&&(s==null?void 0:s.role)==="team_leader"})},nGn=s=>{const{data:t}=G_(),{data:n}=qts();return at({queryKey:["team-scorecard-transactions",t==null?void 0:t.teamId,s],queryFn:async()=>{const r=n.map(o=>o.id);let a=q.from("scorecard_transactions").select(` *, lead_source:lead_sources(id, name), client_type:relationship_types(id, name), contact:innercircle_contacts(id, first_name, last_name) `).in("owner_user_id",r).order("close_date",{ascending:!1});s&&(a=a.gte("close_date",`${s}-01-01`).lte("close_date",`${s}-12-31`));const{data:i,error:l}=await a;if(l)throw l;return i},enabled:!!n&&n.length>0})};function rGn(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 aGn(s,t){return s?s.split(" ").map(n=>n[0]).join("").toUpperCase().slice(0,2):t[0].toUpperCase()}function iGn({year:s}){var m;const{data:t,isLoading:n}=qts(),{data:r,isLoading:a}=nGn(s),i=Fn(),l=n||a,{aggregate:o,memberStats:c,topPerformer:d,agentNameMap:u,teamChartStats:h}=_.useMemo(()=>{if(!t||!r)return{aggregate:null,memberStats:[],topPerformer:null,agentNameMap:{},teamChartStats:null};const p=t.map(D=>rGn(D,r));p.sort((D,O)=>O.totalVolume-D.totalVolume);const f={};t.forEach(D=>{f[D.id]=D.name||D.email});const y=r.length,v=r.reduce((D,O)=>D+Number(O.sale_price),0),g=r.reduce((D,O)=>D+(Number(O.commission_amount)||0),0),b=r.filter(D=>D.transaction_type==="buyer").length,j=r.filter(D=>D.transaction_type==="seller").length,S={};r.forEach(D=>{var V;const O=((V=D.lead_source)==null?void 0:V.name)||"Unknown";S[O]=(S[O]||0)+1});const C=Object.entries(S).sort((D,O)=>O[1]-D[1])[0],E={};r.forEach(D=>{const O=Ru(D.close_date).toLocaleString("default",{month:"short"});E[O]=(E[O]||0)+1});const M=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"].map(D=>({month:D,count:E[D]||0})),I=Object.entries(S).map(([D,O])=>({name:D,count:O})).sort((D,O)=>O.count-D.count);return{aggregate:{totalTxns:y,buyerCount:b,sellerCount:j,totalVolume:v,avgPrice:y>0?v/y:0,totalGCI:g,topSource:C?{name:C[0],count:C[1]}:null,memberCount:t.length},memberStats:p,topPerformer:p[0]||null,agentNameMap:f,teamChartStats:{transactionsByMonth:M,leadSourceBreakdown:I}}},[t,r]);return l?e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[1,2,3,4].map(p=>e.jsx(cn,{className:"h-24"},p))}),e.jsx(cn,{className:"h-64"})]}):!o||c.length===0?e.jsx(ve,{className:"py-12",children:e.jsxs(Me,{className:"text-center space-y-2",children:[e.jsx(In,{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(ve,{children:e.jsxs(Me,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(In,{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(ve,{children:e.jsxs(Me,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Jr,{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(ve,{children:e.jsxs(Me,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(yd,{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:am(o.totalVolume,!0)})]})}),e.jsx(ve,{children:e.jsxs(Me,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Nl,{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:am(o.avgPrice,!0)})]})}),e.jsx(ve,{children:e.jsxs(Me,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(yd,{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:am(o.totalGCI,!0)})]})}),e.jsx(ve,{children:e.jsxs(Me,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Hh,{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(ve,{className:"border-primary/30 bg-primary/5",children:e.jsxs(Me,{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(wl,{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:am(d.totalVolume,!0)})]})]})}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-lg",children:"Member Performance"})}),e.jsx(Me,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"Agent"}),e.jsx(Pt,{className:"text-center",children:"Transactions"}),e.jsx(Pt,{className:"text-center",children:"B / S"}),e.jsx(Pt,{className:"text-right",children:"Volume"}),e.jsx(Pt,{className:"text-right",children:"Avg Price"}),e.jsx(Pt,{className:"text-right",children:"GCI"}),e.jsx(Pt,{className:"text-right"})]})}),e.jsx(Ka,{children:c.map((p,f)=>e.jsxs(pn,{children:[e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative",children:[f===0&&p.totalTransactions>0&&e.jsx(wl,{className:"absolute -top-2 -right-2 h-3.5 w-3.5 text-amber-500"}),e.jsxs(ja,{className:"h-8 w-8",children:[e.jsx(pi,{src:p.member.avatar_url||void 0}),e.jsx(Na,{className:"text-xs",children:aGn(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:am(p.totalVolume,!0)}),e.jsx(gt,{className:"text-right text-sm",children:am(p.averagePrice,!0)}),e.jsx(gt,{className:"text-right font-medium",children:am(p.totalGCI,!0)}),e.jsx(gt,{className:"text-right",children:e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>i(`/mission-control/scorecard/${p.member.id}`),children:e.jsx(ya,{className:"h-4 w-4"})})})]},p.member.id))})]})})})]}),e.jsxs(Yr,{defaultValue:"transactions",className:"space-y-4",children:[e.jsxs(Zr,{children:[e.jsxs(Ht,{value:"transactions",children:[e.jsx(A0,{className:"h-4 w-4 mr-1"}),"All Transactions"]}),e.jsxs(Ht,{value:"charts",children:[e.jsx(bl,{className:"h-4 w-4 mr-1"}),"Charts"]}),e.jsxs(Ht,{value:"map",children:[e.jsx(Xa,{className:"h-4 w-4 mr-1"}),"Map"]})]}),e.jsx(Gt,{value:"transactions",children:e.jsx(tat,{transactions:r||[],showCommission:!0,isLoading:a,agentNameMap:u,readOnly:!0})}),e.jsx(Gt,{value:"charts",children:h&&e.jsx(sat,{stats:h,year:s})}),e.jsx(Gt,{value:"map",children:e.jsx(nat,{transactions:r||[],isLoading:a})})]})]})}const FCe=new Date().getFullYear(),SSt=Array.from({length:10},(s,t)=>FCe-t),fde="all";function oGn(){var V;const[s,t]=_.useState(FCe),n=s===null?fde:String(s),r=G=>t(G===fde?null:Number(G)),[a,i]=_.useState(!1),[l,o]=_.useState(!1),[c,d]=_.useState(!1),[u,h]=_.useState(!1),[m,p]=_.useState("my"),{data:f}=G_(),y=(f==null?void 0:f.role)==="team_leader",{data:v,isLoading:g}=bet(s??void 0),{yearStats:b,lifetimeStats:j,isLoading:S,showCommission:C}=Uzt(s??void 0),{data:E,isLoading:P}=Bzt(s??FCe),{data:M}=mLe(),I=QUs(),D=()=>{if(!v||v.length===0)return;const G=["Property Address","City","State","Zip","Transaction Type","Close Date","Sale Price",...C?["Commission"]:[],"Lead Source","Client Type","Contact Name","Is Win","Notes"],$=v.map(ce=>{var ie,te;return[ce.property_address,ce.city||"",ce.state||"",ce.zip||"",ce.transaction_type,ce.close_date,ce.sale_price,...C?[ce.commission_amount||""]:[],((ie=ce.lead_source)==null?void 0:ie.name)||"",((te=ce.client_type)==null?void 0:te.name)||"",ce.contact?`${ce.contact.first_name} ${ce.contact.last_name||""}`.trim():"",ce.is_win?"Yes":"No",ce.notes||""]}),H=[G,...$].map(ce=>ce.map(ie=>`"${String(ie).replace(/"/g,'""')}"`).join(",")).join(` `),Y=new Blob([H],{type:"text/csv"}),Z=URL.createObjectURL(Y),ne=document.createElement("a");ne.href=Z,ne.download=s===null?"transactions-all.csv":`transactions-${s}.csv`,ne.click(),URL.revokeObjectURL(Z)},O=!v||v.length===0;return e.jsxs(zs,{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"})]}),y&&e.jsxs("div",{className:"flex items-center gap-1 bg-muted rounded-lg p-1 w-fit",children:[e.jsx(B,{variant:m==="my"?"default":"ghost",size:"sm",onClick:()=>p("my"),className:"h-8",children:"My Scorecard"}),e.jsxs(B,{variant:m==="team"?"default":"ghost",size:"sm",onClick:()=>p("team"),className:"h-8",children:[e.jsx(In,{className:"h-4 w-4 mr-1.5"}),"Team"]})]}),m==="team"&&y?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(is,{value:n,onValueChange:r,children:[e.jsx(rs,{className:"w-[140px]",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:fde,children:"All Years"}),SSt.map(G=>e.jsx(He,{value:String(G),children:G},G))]})]})]}),e.jsx(iGn,{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(is,{value:n,onValueChange:r,children:[e.jsx(rs,{className:"w-[140px]",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:fde,children:"All Years"}),SSt.map(G=>e.jsx(He,{value:String(G),children:G},G))]})]}),e.jsx(B,{variant:"outline",size:"icon",onClick:()=>h(!u),children:e.jsx(qc,{className:"h-4 w-4"})})]})]}),u&&e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-3",children:e.jsx(St,{className:"text-lg",children:"Settings"})}),e.jsx(Me,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(J,{children:"Show Commission"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Display commission fields and include in stats"})]}),e.jsx(fn,{checked:(M==null?void 0:M.show_commission)??!0,onCheckedChange:G=>I.mutate({show_commission:G})})]})})]}),O&&!g?e.jsx(ve,{className:"py-12",children:e.jsxs(Me,{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(bl,{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(B,{onClick:()=>i(!0),children:[e.jsx(rn,{className:"h-4 w-4 mr-2"}),"Add Your First Transaction"]}),e.jsxs(B,{variant:"outline",onClick:()=>o(!0),children:[e.jsx(Oa,{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(B,{variant:"link",className:"h-auto p-0",asChild:!0,children:e.jsxs("a",{href:"/templates/transaction-import-template.csv",download:!0,children:[e.jsx(li,{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(B,{onClick:()=>i(!0),children:[e.jsx(rn,{className:"h-4 w-4 mr-2"}),"Add Transaction"]}),e.jsxs(B,{variant:"outline",onClick:()=>d(!0),children:[e.jsx(ku,{className:"h-4 w-4 mr-2"}),"Set Goals"]}),e.jsxs(B,{variant:"outline",onClick:()=>o(!0),children:[e.jsx(Oa,{className:"h-4 w-4 mr-2"}),"Import"]}),e.jsxs(B,{variant:"outline",onClick:D,disabled:O,children:[e.jsx(li,{className:"h-4 w-4 mr-2"}),"Export"]}),e.jsx(B,{variant:"ghost",size:"sm",asChild:!0,children:e.jsxs("a",{href:"/templates/transaction-import-template.csv",download:!0,children:[e.jsx(li,{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(ve,{children:e.jsxs(Me,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Jr,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Transactions"})]}),e.jsx("p",{className:"text-2xl font-bold",children:b.totalTransactions}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[j.totalTransactions," lifetime"]})]})}),e.jsx(ve,{children:e.jsxs(Me,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(In,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Buyer/Seller"})]}),e.jsxs("p",{className:"text-2xl font-bold",children:[b.buyerCount,"/",b.sellerCount]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"B/S split"})]})}),e.jsx(ve,{children:e.jsxs(Me,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(yd,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Volume"})]}),e.jsx("p",{className:"text-2xl font-bold",children:am(b.totalVolume,!0)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[am(j.totalVolume,!0)," lifetime"]})]})}),e.jsx(ve,{children:e.jsxs(Me,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Nl,{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:am(b.averagePrice,!0)})]})}),e.jsx(ve,{children:e.jsxs(Me,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Hh,{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:((V=b.topLeadSource)==null?void 0:V.name)||"-"}),b.topLeadSource&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[b.topLeadSource.count," deals"]})]})}),C&&e.jsx(ve,{children:e.jsxs(Me,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(yd,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"GCI"})]}),e.jsx("p",{className:"text-2xl font-bold",children:am(b.totalCommission,!0)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[am(j.totalCommission,!0)," lifetime"]})]})}),C&&b.totalNetToAgent>0&&b.totalNetToAgent!==b.totalCommission&&e.jsx(ve,{children:e.jsxs(Me,{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(yd,{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:am(b.totalNetToAgent,!0)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[am(j.totalNetToAgent,!0)," lifetime"]})]})})]}),s!==null&&E&&e.jsx(Fts,{goals:E,stats:b,year:s,showCommission:C}),e.jsxs(Yr,{defaultValue:"transactions",className:"space-y-4",children:[e.jsxs(Zr,{children:[e.jsx(Ht,{value:"transactions",children:"Transactions"}),e.jsx(Ht,{value:"charts",children:"Charts"}),e.jsxs(Ht,{value:"map",children:[e.jsx(Xa,{className:"h-4 w-4 mr-1"}),"Map"]})]}),e.jsx(Gt,{value:"transactions",children:e.jsx(tat,{transactions:v||[],showCommission:C,isLoading:g})}),e.jsx(Gt,{value:"charts",children:e.jsx(sat,{stats:b,year:s??void 0})}),e.jsx(Gt,{value:"map",children:e.jsx(nat,{transactions:v||[],isLoading:g})})]})]})]})]}),e.jsx(Rts,{open:a,onOpenChange:i}),e.jsx(eGn,{open:l,onOpenChange:o}),e.jsx(sGn,{open:c,onOpenChange:d,year:s??FCe,existingGoals:E})]})}const lGn={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"},cGn={active:"Active",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},dGn={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"};function uGn({listing:s,onClick:t,onEdit:n,onDelete:r,onCreateMusicVideo:a,showActions:i}){var S,C;const{user:l}=hs(),{data:o}=M9t(s.id),c=T9t(),[d,u]=_.useState(!1),h=E=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(E),m=((S=s.photos)==null?void 0:S.find(E=>E.is_primary))||((C=s.photos)==null?void 0:C[0]),p=(l==null?void 0:l.id)===s.agent_id,f=s.listing_class==="commercial",y=s.commercial??null,v=s.lifecycle_stage==="pitch",g=f?[LA(y==null?void 0:y.building_sf)?`${LA(y==null?void 0:y.building_sf)} building`:null,LA(y==null?void 0:y.available_sf)?`${LA(y==null?void 0:y.available_sf)} available`:null,mAe(y==null?void 0:y.cap_rate)?`${mAe(y==null?void 0:y.cap_rate)} cap`:null,(y==null?void 0:y.price_per_sf)!=null?`${K2(y.price_per_sf,2)}/SF`:null,(y==null?void 0:y.units)!=null?`${y.units} units`:null].filter(Boolean).slice(0,3):[],b=async E=>{E.stopPropagation();try{const P=await c.mutateAsync(s.id);se.success(P.saved?"Listing saved!":"Listing removed from saved")}catch{se.error("Failed to save listing")}},j=E=>{if(E.stopPropagation(),l)u(!0);else{const P=`${s.listing_class==="commercial"?"https://commercial.relevelup.com":"https://listings.relevelup.com"}/${s.slug||s.id}`;navigator.clipboard.writeText(P),se.success("Link copied to clipboard!")}};return e.jsxs(ve,{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(wb,{className:"h-12 w-12"})}),e.jsxs("div",{className:"absolute top-2 left-2 flex flex-wrap gap-1",children:[e.jsx(Oe,{className:`${lGn[s.status]} text-white border-0`,children:f&&v?"Pitch":cGn[s.status]}),f&&e.jsx(Oe,{className:"border-0 bg-[#0b0f14]/90 text-white",children:y!=null&&y.deal_type?DP[y.deal_type]:"Commercial"})]}),s.is_featured&&e.jsx("div",{className:"absolute top-2 right-2 p-1.5 bg-amber-500 rounded-full",children:e.jsx(Da,{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(B,{size:"icon",variant:"secondary",className:"h-8 w-8",onClick:b,children:e.jsx(Do,{className:`h-4 w-4 ${o?"fill-pink-500 text-pink-500":""}`})}),e.jsx(B,{size:"icon",variant:"secondary",className:"h-8 w-8",onClick:j,title:p?"Copy link":"Share & earn leads",children:p?e.jsx(bd,{className:"h-4 w-4"}):e.jsx(un,{className:"h-4 w-4 text-amber-500"})})]})]}),e.jsx(aLe,{open:d,onOpenChange:u,listingId:s.id,listingSlug:s.slug||null,listingTitle:s.property_address||`${s.city}, ${s.state}`,isCommercial:s.listing_class==="commercial"}),e.jsxs(Me,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xl font-bold text-primary",children:f?EH(y,s.price):h(s.price)}),s.open_to_referrals&&e.jsxs(Oe,{variant:"outline",className:"text-xs",children:[e.jsx(In,{className:"h-3 w-3 mr-1"}),"Referrals"]})]}),e.jsxs("div",{children:[f?e.jsx("p",{className:"font-medium truncate",children:cP(s,y)}):s.property_address&&e.jsx("p",{className:"font-medium truncate",children:s.property_address}),e.jsxs("p",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[e.jsx(Xa,{className:"h-3 w-3"}),f?Wre(s,y):`${s.city}, ${s.state}${s.neighborhood?` • ${s.neighborhood}`:""}`]})]}),e.jsx("div",{className:"flex items-center gap-4 text-sm text-muted-foreground",children:f?g.map(E=>e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(wb,{className:"h-4 w-4"}),E]},E)):e.jsxs(e.Fragment,{children:[s.bedrooms&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(dj,{className:"h-4 w-4"}),s.bedrooms," bd"]}),s.bathrooms&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(S0,{className:"h-4 w-4"}),s.bathrooms," ba"]}),s.square_footage&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(wb,{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(Oe,{variant:"secondary",className:"text-xs",children:f?y!=null&&y.commercial_type?hL[y.commercial_type]:"Commercial":dGn[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(ya,{className:"h-3 w-3"}),s.view_count]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(bd,{className:"h-3 w-3"}),s.share_count]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Do,{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(B,{variant:"outline",size:"sm",className:"flex-1 min-w-[140px] gap-1.5 border-violet-500/60 text-violet-600 hover:bg-violet-50",onClick:E=>{E.stopPropagation(),a()},children:[e.jsx(Kq,{className:"h-4 w-4"}),"Music Video"]}),n&&e.jsxs(B,{variant:"outline",size:"sm",className:"flex-1",onClick:E=>{E.stopPropagation(),n()},children:[e.jsx(wp,{className:"h-4 w-4 mr-2"}),"Edit"]}),r&&e.jsx(B,{variant:"destructive",size:"sm",onClick:E=>{E.stopPropagation(),r()},children:e.jsx(Sn,{className:"h-4 w-4"})})]})]})]})}const rat="lu_listing_selection_v1",i6e=24,o6e=new Set;function $ts(){try{return JSON.parse(sessionStorage.getItem(rat)||"{}")}catch{return{}}}function Xze(s){try{sessionStorage.setItem(rat,JSON.stringify(s))}catch{}o6e.forEach(t=>t())}let R3=$ts();function hGn(){R3=$ts(),o6e.forEach(s=>s())}typeof window<"u"&&window.addEventListener("storage",s=>{s.key===rat&&hGn()});const g6={getSnapshot:()=>R3,subscribe(s){return o6e.add(s),()=>o6e.delete(s)},toggle(s){const t={...R3};if(t[s.mlsNumber])delete t[s.mlsNumber];else{if(Object.keys(t).length>=i6e)return!1;t[s.mlsNumber]=s}return R3=t,Xze(t),!0},remove(s){const t={...R3};delete t[s],R3=t,Xze(t)},clear(){R3={},Xze({})},has(s){return!!R3[s]},all(){return Object.values(R3)}};function Vts(){const s=_.useSyncExternalStore(g6.subscribe,g6.getSnapshot,g6.getSnapshot);return{selected:Object.values(s),selectedIds:new Set(Object.keys(s)),count:Object.keys(s).length,has:t=>!!s[t],toggle:g6.toggle,remove:g6.remove,clear:g6.clear}}const mGn=new Set(["office_exclusive","coming_soon","pre_market"]);function pGn(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=mGn.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 jZ(s){const{has:t}=Vts(),n=`lx-${s.listing.id}`,r=t(n);return e.jsxs("div",{className:"relative",children:[e.jsx(uGn,{...s}),e.jsx("button",{type:"button",onClick:a=>{a.stopPropagation(),g6.toggle(pGn(s.listing))||se.error(`You can select up to ${i6e} 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(ea,{className:"h-4 w-4"}):e.jsx(ln,{className:"h-4 w-4"})})]})}function fGn({open:s,onOpenChange:t,listings:n}){const{user:r}=hs(),{leadSite:a}=lf(),[i,l]=_.useState("grid"),[o,c]=_.useState(""),[d,u]=_.useState(""),[h,m]=_.useState(""),[p,f]=_.useState(new Set),[y,v]=_.useState(!1),[g,b]=_.useState(!1),{data:j}=iae(),[S,C]=_.useState(!1);_.useEffect(()=>{!s||!(r!=null&&r.id)||q.from("gmail_integrations").select("gmail_email").eq("user_id",r.id).maybeSingle().then(({data:H})=>b(!!(H!=null&&H.gmail_email)))},[s,r==null?void 0:r.id]),_.useEffect(()=>{if(s){if(!o){const H=Array.from(new Set(n.map(Z=>Z.city).filter(Boolean))),Y=H.length===1?` in ${H[0]}`:"";c(n.length===1?`New listing for you${Y}`:`${n.length} hand-picked listings${Y}`)}d||u(`Hi {{first_name}}, Thought of you — I just picked a few properties I think you'll love. Take a look and let me know if anything catches your eye. Happy to set up a private showing whenever works.`)}},[s]);const{data:E=[],isLoading:P}=at({queryKey:["send-listings-contacts",r==null?void 0:r.id],queryFn:async()=>{const{data:H}=await q.from("innercircle_contacts").select("id, first_name, last_name, email, city").eq("owner_user_id",r.id).not("email","is",null).neq("email","").order("first_name");return H||[]},enabled:!!(r!=null&&r.id)&&s}),{data:M}=at({queryKey:["send-listings-suggestions",n.map(H=>H.mlsNumber).join(",")],queryFn:async()=>{const{data:H,error:Y}=await q.functions.invoke("listing-email-suggestions",{body:{listings:n.map(Z=>({mlsNumber:Z.mlsNumber,city:Z.city,state:Z.state,price:Z.price,bedrooms:Z.bedrooms,bathrooms:Z.bathrooms}))}});if(Y)throw Y;return H},enabled:s&&n.length>0}),I=(M==null?void 0:M.suggestions)||[],D=_.useMemo(()=>{const H=h.trim().toLowerCase();return H?E.filter(Y=>`${Y.first_name??""} ${Y.last_name??""} ${Y.email} ${Y.city??""}`.toLowerCase().includes(H)):E},[E,h]),O=H=>{f(Y=>{const Z=new Set(Y);return Z.has(H)?Z.delete(H):Z.add(H),Z})},V=()=>{f(H=>{const Y=new Set(H);return I.forEach(Z=>Y.add(Z.contact_id)),Y})},G=n.length>0&&n.every(H=>H.mlsNumber.startsWith("lx-")),$=async()=>{if(!G&&!(a!=null&&a.id)){se.error("You need an active lead site to send listings.");return}if(!o.trim())return se.error("Subject is required");if(p.size===0)return se.error("Pick at least one recipient");if(!g&&j&&!j.hasVerifiedSes){C(!0);return}const H=E.filter(Y=>p.has(Y.id)).map(Y=>({contact_id:Y.id,email:Y.email,first_name:Y.first_name,last_name:Y.last_name}));v(!0);try{const{data:Y,error:Z}=await q.functions.invoke("listing-email-send",{body:{lead_site_id:(a==null?void 0:a.id)||null,layout:i,subject:o.trim(),intro_message:d.trim()||null,listings:n.map(ne=>({mlsNumber:ne.mlsNumber,address:ne.address,city:ne.city,state:ne.state,zip:ne.zip,price:ne.price,bedrooms:ne.bedrooms,bathrooms:ne.bathrooms,sqft:ne.sqft,status:ne.status,photos:(ne.photos||[]).slice(0,1),description:ne.description||"",external_url:ne.externalUrl||null,is_private:ne.is_private===!0})),recipients:H}});if(Z)throw Z;if(!(Y!=null&&Y.success))throw new Error((Y==null?void 0:Y.error)||"Send failed");se.success(`Sent ${Y.sent}/${H.length} via ${g?"Gmail":"Amazon SES"}${Y.failed?` · ${Y.failed} failed`:""}`),g6.clear(),f(new Set),t(!1)}catch(Y){se.error((Y==null?void 0:Y.message)||"Failed to send")}finally{v(!1)}};return e.jsxs(Ls,{open:s,onOpenChange:t,children:[e.jsxs(Ps,{className:"max-w-5xl max-h-[92vh] overflow-hidden p-0 flex flex-col",children:[e.jsxs(Os,{className:"px-6 pt-6 pb-2",children:[e.jsxs(Ds,{className:"flex items-center gap-2",children:[e.jsx(ln,{className:"h-5 w-5 text-primary"}),"Email ",n.length," ",n.length===1?"Listing":"Listings"]}),e.jsx(_r,{children:G?"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(J,{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(H=>{var Y;return e.jsxs("div",{className:"shrink-0 w-32 rounded-lg overflow-hidden border bg-muted",children:[e.jsx("div",{className:"h-20 w-full bg-muted",children:((Y=H.photos)==null?void 0:Y[0])&&e.jsx("img",{src:H.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:["$",(H.price/1e3).toFixed(0),"k"]}),e.jsxs("div",{className:"text-[10px] text-muted-foreground truncate",children:[H.city,", ",H.state]})]})]},H.mlsNumber)})})]}),e.jsxs("div",{children:[e.jsx(J,{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(sf,{className:"h-4 w-4 mb-1.5"}),e.jsx("div",{className:"text-sm font-medium",children:"Magazine grid"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Clean card stack"})]}),e.jsxs("button",{type:"button",onClick:()=>l("hero"),className:`rounded-lg border p-3 text-left transition ${i==="hero"?"border-primary bg-primary/5":"hover:bg-muted/50"}`,children:[e.jsx(hc,{className:"h-4 w-4 mb-1.5"}),e.jsx("div",{className:"text-sm font-medium",children:"Hero + list"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"First listing gets spotlight"})]})]})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"subject",children:"Subject"}),e.jsx(xe,{id:"subject",value:o,onChange:H=>c(H.target.value),placeholder:"Subject line",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"intro",children:"Personal message"}),e.jsx(Ms,{id:"intro",value:d,onChange:H=>u(H.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:g?"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(ve,{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(un,{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(B,{size:"sm",variant:"outline",onClick:V,children:"Add all"})]}),e.jsx(Ji,{className:"max-h-32 mt-2",children:e.jsx("div",{className:"space-y-1",children:I.slice(0,12).map(H=>{const Y=p.has(H.contact_id);return e.jsxs("label",{className:"flex items-start gap-2 text-xs py-1 cursor-pointer",children:[e.jsx($a,{checked:Y,onCheckedChange:()=>O(H.contact_id),className:"mt-0.5"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium truncate",children:[H.first_name," ",H.last_name??""," ",e.jsxs("span",{className:"text-muted-foreground font-normal",children:["· ",H.email]})]}),e.jsx("div",{className:"text-muted-foreground truncate",children:H.reason})]})]},H.contact_id)})})})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs(J,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:["All contacts (",D.length,")"]}),p.size>0&&e.jsxs(Oe,{variant:"secondary",children:[p.size," selected"]})]}),e.jsx(xe,{placeholder:"Search contacts…",value:h,onChange:H=>m(H.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(Ji,{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(H=>{const Y=p.has(H.id);return e.jsxs("label",{className:"flex items-center gap-2 px-3 py-2 cursor-pointer hover:bg-muted/40",children:[e.jsx($a,{checked:Y,onCheckedChange:()=>O(H.id)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"text-sm font-medium truncate",children:[H.first_name," ",H.last_name??""]}),e.jsxs("div",{className:"text-xs text-muted-foreground truncate",children:[H.email,H.city&&e.jsxs(e.Fragment,{children:[" · ",H.city]})]})]})]},H.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(B,{variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>f(new Set),children:[e.jsx(Qn,{className:"h-3 w-3 mr-1"}),"Clear"]})]})]})]}),e.jsxs(yr,{className:"px-6 py-4 border-t bg-muted/30",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),disabled:y,children:"Cancel"}),e.jsx(B,{onClick:$,disabled:y||p.size===0,children:y?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),"Sending…"]}):e.jsxs(e.Fragment,{children:[e.jsx(Or,{className:"h-4 w-4 mr-2"}),"Send to ",p.size," ",p.size===1?"contact":"contacts"]})})]})]}),e.jsx(cLe,{open:S,onOpenChange:C,hasPending:!!(j!=null&&j.hasPendingSes),pendingEmails:j==null?void 0:j.pendingEmails})]})}function xGn(){const{selected:s,count:t,remove:n,clear:r}=Vts(),[a,i]=_.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>=i6e?"Max reached":`Pick up to ${i6e}`})]})]}),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(Qn,{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(B,{variant:"ghost",size:"sm",onClick:r,className:"gap-1.5",children:[e.jsx(Sn,{className:"h-4 w-4"})," Clear"]}),e.jsxs(B,{size:"sm",className:"gap-1.5",onClick:()=>i(!0),children:[e.jsx(Or,{className:"h-4 w-4"}),"Email these ",t===1?"listing":"listings"]})]})]})}),e.jsx(fGn,{open:a,onOpenChange:i,listings:s})]})}const gGn=[{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"}],yGn=[{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 vGn({filters:s,onFiltersChange:t,onClose:n,showCommercial:r}){const a=s.commercial??{},i=o=>t({...s,commercial:{...a,...o}}),l=()=>{t({sortBy:"newest"})};return e.jsxs(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between pb-3",children:[e.jsx(St,{className:"text-lg",children:"Filters"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:l,children:"Clear All"}),e.jsx(B,{variant:"ghost",size:"icon",onClick:n,children:e.jsx(Qn,{className:"h-4 w-4"})})]})]}),e.jsxs(Me,{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(J,{children:"Status"}),e.jsxs(is,{value:s.status||"all",onValueChange:o=>t({...s,status:o==="all"?void 0:o}),children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"All statuses"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Statuses"}),gGn.map(o=>e.jsx(He,{value:o.value,children:o.label},o.value))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Property Type"}),e.jsxs(is,{value:s.propertyType||"all",onValueChange:o=>t({...s,propertyType:o==="all"?void 0:o}),children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"All types"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Types"}),yGn.map(o=>e.jsx(He,{value:o.value,children:o.label},o.value))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Min Price"}),e.jsx(xe,{type:"number",placeholder:"No minimum",value:s.minPrice||"",onChange:o=>t({...s,minPrice:o.target.value?Number(o.target.value):void 0})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Max Price"}),e.jsx(xe,{type:"number",placeholder:"No maximum",value:s.maxPrice||"",onChange:o=>t({...s,maxPrice:o.target.value?Number(o.target.value):void 0})})]})]}),r&&e.jsxs("div",{className:"mt-4 grid grid-cols-1 gap-4 border-t pt-4 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Deal Type"}),e.jsxs(is,{value:a.dealType||"all",onValueChange:o=>i({dealType:o==="all"?void 0:o}),children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Any"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"Any deal type"}),Object.entries(DP).map(([o,c])=>e.jsx(He,{value:o,children:c},o))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Asset Type"}),e.jsxs(is,{value:a.commercialType||"all",onValueChange:o=>i({commercialType:o==="all"?void 0:o}),children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Any"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"Any asset type"}),Object.entries(hL).map(([o,c])=>e.jsx(He,{value:o,children:c},o))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Min Building SF"}),e.jsx(xe,{type:"number",placeholder:"Any size",value:a.minBuildingSf??"",onChange:o=>i({minBuildingSf:o.target.value?Number(o.target.value):void 0})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Min Cap Rate (%)"}),e.jsx(xe,{type:"number",step:"0.1",placeholder:"Any",value:a.minCapRate??"",onChange:o=>i({minCapRate:o.target.value?Number(o.target.value):void 0})})]})]}),e.jsxs("div",{className:"flex items-center justify-between mt-4 pt-4 border-t",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Open to Referrals Only"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show only listings accepting buyer referrals"})]}),e.jsx(fn,{checked:s.openToReferrals||!1,onCheckedChange:o=>t({...s,openToReferrals:o||void 0})})]})]})]})}function bGn({leaderboard:s}){const t=r=>{switch(r){case 0:return e.jsx(wl,{className:"h-5 w-5 text-amber-500"});case 1:return e.jsx(HA,{className:"h-5 w-5 text-gray-400"});case 2:return e.jsx(Hh,{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(Oe,{variant:l===0?"default":"secondary",children:[i.count," ",a]})]},i.agentId))});return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(wl,{className:"h-5 w-5 text-amber-500"}),"Community Badges"]})}),e.jsx(Me,{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(bd,{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(Jr,{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(HA,{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(wl,{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(ve,{children:[e.jsx(bt,{children:e.jsx(St,{children:"Community Leaderboard"})}),e.jsx(Me,{children:e.jsxs(Yr,{defaultValue:"sharers",children:[e.jsxs(Zr,{className:"w-full",children:[e.jsxs(Ht,{value:"sharers",className:"flex-1",children:[e.jsx(bd,{className:"h-4 w-4 mr-2"}),"Top Sharers"]}),e.jsxs(Ht,{value:"listers",className:"flex-1",children:[e.jsx(Jr,{className:"h-4 w-4 mr-2"}),"Top Contributors"]})]}),e.jsx(Gt,{value:"sharers",className:"mt-4",children:n(s==null?void 0:s.topSharers,"shares")}),e.jsx(Gt,{value:"listers",className:"mt-4",children:n(s==null?void 0:s.topListers,"listings")})]})})]})]})}const CSt={coming_soon:"#F59E0B",office_exclusive:"#6366F1",pre_market:"#06B6D4",active:"#10B981",price_improvement:"#8B5CF6",under_contract:"#3B82F6",sold:"#A855F7"},ASt={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 _Gn(s){return s>=1e6?`$${(s/1e6).toFixed(1)}M`:`$${(s/1e3).toFixed(0)}K`}function wGn({listings:s,isLoading:t}){const n=Fn(),r=_.useRef(null),a=_.useRef(null),i=_.useRef([]),{isAdmin:l}=hs(),[o,c]=_.useState(""),[d,u]=_.useState(!0),[h,m]=_.useState(!1),p=s.filter(y=>y.latitude!=null&&y.longitude!=null),f=s.filter(y=>(y.latitude==null||y.longitude==null)&&(y.property_address||y.city));return _.useEffect(()=>{(async()=>{u(!0);try{const{data:v}=await q.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();v!=null&&v.value&&c(v.value)}catch(v){console.error("Error fetching mapbox token:",v)}u(!1)})()},[]),_.useEffect(()=>{if(!o||f.length===0||h)return;(async()=>{var v;m(!0);for(const g of f){const b=[g.property_address,g.city,g.state].filter(Boolean).join(", ");if(b)try{const S=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(b)}.json?access_token=${o}&limit=1`)).json();if((v=S.features)!=null&&v[0]){const[C,E]=S.features[0].center;await q.from("listings").update({latitude:E,longitude:C}).eq("id",g.id),g.latitude=E,g.longitude=C}}catch(j){console.error("Geocode error:",j)}}m(!1)})()},[o,s]),_.useEffect(()=>{if(!r.current||!o||a.current)return;Id.accessToken=o;const y=s.filter(b=>b.latitude!=null&&b.longitude!=null);let v=[-98.5795,39.8283],g=4;if(y.length>0){const b=y.reduce((S,C)=>S+C.longitude,0)/y.length,j=y.reduce((S,C)=>S+C.latitude,0)/y.length;v=[b,j],g=y.length===1?12:10}return a.current=new Id.Map({container:r.current,style:"mapbox://styles/mapbox/light-v11",zoom:g,center:v}),a.current.addControl(new Id.NavigationControl,"top-right"),()=>{var b;(b=a.current)==null||b.remove(),a.current=null}},[o]),_.useEffect(()=>{if(!a.current||!o)return;i.current.forEach(v=>v.remove()),i.current=[];const y=s.filter(v=>v.latitude!=null&&v.longitude!=null);if(y.forEach(v=>{var E,P,M;const g=CSt[v.status]||"#10B981",b=((E=v.photos)==null?void 0:E.find(I=>I.is_primary))||((P=v.photos)==null?void 0:P[0]),j=document.createElement("div");j.className="cursor-pointer",j.innerHTML=`
`;const S=new Id.Popup({offset:25,closeButton:!0,maxWidth:"280px"}).setHTML(`
${b!=null&&b.photo_url?``:""}
${_Gn(v.price)}
${v.property_address||""}
${v.city}, ${v.state}
${ASt[v.status]||v.status} ${v.bedrooms?`${v.bedrooms} bed`:""} ${v.bathrooms?`${v.bathrooms} bath`:""}
${(M=v.agent)!=null&&M.name?`
Listed by ${v.agent.name}
`:""}
Click to view details →
`),C=new Id.Marker(j).setLngLat([v.longitude,v.latitude]).setPopup(S).addTo(a.current);i.current.push(C)}),y.length>1){const v=new Id.LngLatBounds;y.forEach(g=>v.extend([g.longitude,g.latitude])),a.current.fitBounds(v,{padding:60,maxZoom:13})}else y.length===1&&a.current.flyTo({center:[y[0].longitude,y[0].latitude],zoom:12})},[s,o,h]),_.useEffect(()=>(window.__navigateToListing__=y=>{n(`/mission-control/listings/${y}`)},()=>{delete window.__navigateToListing__}),[n]),d||t?e.jsx(ve,{children:e.jsx(Me,{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(ve,{children:e.jsxs(Me,{className:"flex flex-col items-center justify-center h-[60vh] text-center gap-3",children:[e.jsx(Xa,{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(CSt).map(([y,v])=>e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:"w-3 h-3 rounded-full border-2 border-white shadow",style:{background:v}}),e.jsx("span",{className:"text-xs",children:ASt[y]})]},y)),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(ve,{children:e.jsxs(Me,{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 wYe="homereel_mv_prefill",jYe="homereel_mv_badge_default";function Hts(s){try{sessionStorage.setItem(wYe,JSON.stringify(s)),s.badge&&s.badge.type!=="none"&&sessionStorage.setItem(jYe,JSON.stringify(s.badge))}catch{}}function swr(){try{const s=sessionStorage.getItem(wYe);return s?(sessionStorage.removeItem(wYe),JSON.parse(s)):null}catch{return null}}function nwr(){try{const s=sessionStorage.getItem(jYe);return s?(sessionStorage.removeItem(jYe),JSON.parse(s)):null}catch{return null}}function Gts(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 jGn(){var H,Y,Z,ne,ce,ie,te,ae;const s=Fn(),{brokerageId:t}=hs(),{data:n,isLoading:r}=_9t(),[a,i]=_.useState("feed"),[l,o]=_.useState(!1),[c,d]=_.useState(""),[u,h]=_.useState("all"),[m,p]=_.useState({sortBy:"newest"}),{data:f,isLoading:y}=w9t({...m,listingClass:u==="all"?void 0:u,city:c||m.city}),{data:v,isLoading:g}=F7s(),{data:b,isLoading:j}=set(),{data:S,isLoading:C}=U7s(),{data:E,isLoading:P}=V7s(),{data:M}=$7s(),I=k9t(),D=m.commercial,O=(f??[]).filter(le=>{if(!D||le.listing_class!=="commercial")return!D||Object.values(D).every(me=>me===void 0)||le.listing_class!=="commercial";const be=le.commercial??{};return!(D.dealType&&be.deal_type!==D.dealType||D.commercialType&&be.commercial_type!==D.commercialType||D.minBuildingSf&&Number(be.building_sf??0)le.lifecycle_stage==="pitch"),G=le=>s(le.listing_class==="commercial"?`/mission-control/listings/${le.id}/commercial`:`/mission-control/listings/${le.id}`),$=async le=>{if(await Xi("Are you sure you want to delete this listing? This action cannot be undone."))try{await I.mutateAsync(le),se.success("Listing deleted successfully")}catch{se.error("Failed to delete listing")}};return r?e.jsx(zs,{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(zs,{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(B,{onClick:()=>s("/mission-control/listings/new"),children:[e.jsx(rn,{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(ve,{children:e.jsxs(Me,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(Jr,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(f==null?void 0:f.length)||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Active Listings"})]})]})}),e.jsx(ve,{children:e.jsxs(Me,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-pink-500/10 rounded-lg",children:e.jsx(Do,{className:"h-5 w-5 text-pink-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(v==null?void 0:v.length)||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Saved"})]})]})}),e.jsx(ve,{children:e.jsxs(Me,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-emerald-500/10 rounded-lg",children:e.jsx(GM,{className:"h-5 w-5 text-emerald-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(b==null?void 0:b.length)||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"My Listings"})]})]})}),e.jsx(ve,{children:e.jsxs(Me,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-sky-500/10 rounded-lg",children:e.jsx(In,{className:"h-5 w-5 text-sky-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(((H=S==null?void 0:S.sent)==null?void 0:H.length)||0)+(((Y=S==null?void 0:S.received)==null?void 0:Y.length)||0)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Referrals"})]})]})})]}),e.jsxs(Yr,{value:a,onValueChange:i,children:[e.jsxs(Zr,{className:"w-full justify-start overflow-x-auto",children:[e.jsx(Ht,{value:"feed",children:"Community Feed"}),t&&e.jsx(Ht,{value:"brokerage",children:"Brokerage"}),e.jsx(Ht,{value:"my-listings",children:"My Listings"}),V.length>0&&e.jsxs(Ht,{value:"pitches",children:["Pitches (",V.length,")"]}),e.jsx(Ht,{value:"saved",children:"Saved"}),e.jsx(Ht,{value:"referrals",children:"Referrals"}),e.jsx(Ht,{value:"map",children:"Map"}),e.jsx(Ht,{value:"leaderboard",children:"Leaderboard"})]}),e.jsxs(Gt,{value:"feed",className:"space-y-4",children:[e.jsx("div",{className:"inline-flex rounded-lg border bg-muted/40 p-1",children:["all","residential","commercial"].map(le=>e.jsx("button",{type:"button",onClick:()=>h(le),className:`rounded-md px-4 py-1.5 text-sm font-medium capitalize transition ${u===le?"bg-background shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:le==="all"?"All listings":le},le))}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search by city or neighborhood...",value:c,onChange:le=>d(le.target.value),className:"pl-9"})]}),e.jsxs(is,{value:m.sortBy,onValueChange:le=>p({...m,sortBy:le}),children:[e.jsx(rs,{className:"w-[180px]",children:e.jsx(ls,{placeholder:"Sort by"})}),e.jsxs(as,{children:[e.jsx(He,{value:"newest",children:"Newest First"}),e.jsx(He,{value:"updated",children:"Recently Updated"}),e.jsx(He,{value:"price_asc",children:"Price: Low to High"}),e.jsx(He,{value:"price_desc",children:"Price: High to Low"})]})]}),e.jsxs(B,{variant:"outline",onClick:()=>o(!l),children:[e.jsx(D_,{className:"h-4 w-4 mr-2"}),"Filters"]})]}),l&&e.jsx(vGn,{filters:m,onFiltersChange:p,onClose:()=>o(!1),showCommercial:u!=="residential"}),y?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(6)].map((le,be)=>e.jsxs(ve,{children:[e.jsx(cn,{className:"h-48 w-full"}),e.jsxs(Me,{className:"p-4 space-y-2",children:[e.jsx(cn,{className:"h-5 w-3/4"}),e.jsx(cn,{className:"h-4 w-1/2"}),e.jsx(cn,{className:"h-4 w-1/4"})]})]},be))}):(f==null?void 0:f.length)===0?e.jsx(ve,{children:e.jsxs(Me,{className:"py-12 text-center",children:[e.jsx(Jr,{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(B,{onClick:()=>s("/mission-control/listings/new"),children:[e.jsx(rn,{className:"h-4 w-4 mr-2"}),"Add Listing"]})]})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:O.map(le=>e.jsx(jZ,{listing:le,onClick:()=>G(le)},le.id))})]}),e.jsx(Gt,{value:"my-listings",className:"space-y-4",children:j?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(3)].map((le,be)=>e.jsxs(ve,{children:[e.jsx(cn,{className:"h-48 w-full"}),e.jsxs(Me,{className:"p-4 space-y-2",children:[e.jsx(cn,{className:"h-5 w-3/4"}),e.jsx(cn,{className:"h-4 w-1/2"})]})]},be))}):(b==null?void 0:b.length)===0?e.jsx(ve,{children:e.jsxs(Me,{className:"py-12 text-center",children:[e.jsx(GM,{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(B,{onClick:()=>s("/mission-control/listings/new"),children:[e.jsx(rn,{className:"h-4 w-4 mr-2"}),"Add Your First Listing"]})]})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:b==null?void 0:b.map(le=>e.jsx(jZ,{listing:le,showActions:!0,onClick:()=>G(le),onEdit:()=>s(le.listing_class==="commercial"?`/mission-control/listings/${le.id}/commercial`:`/mission-control/listings/${le.id}/edit`),onDelete:()=>$(le.id),onCreateMusicVideo:()=>{const be=(le.photos??[]).slice().sort((me,he)=>(he.is_primary?1:0)-(me.is_primary?1:0)||(me.sort_order??0)-(he.sort_order??0)).map(me=>me.photo_url).filter(Boolean);if(be.length===0){se.error("Add photos to this listing first.");return}Hts({photos:be,details:{address:le.property_address||`${le.city??""} ${le.state??""}`.trim(),beds:le.bedrooms?String(le.bedrooms):"",baths:le.bathrooms?String(le.bathrooms):"",sqft:le.square_footage?String(le.square_footage):"",price:le.price?String(le.price):"",highlights:le.description||""},sourceLabel:"My Listings",badge:Gts(le.status,le.price)}),s("/admin/beta/homereel?tab=music-video")}},le.id))})}),e.jsxs(Gt,{value:"pitches",className:"space-y-4",children:[e.jsx(ve,{className:"border-dashed",children:e.jsx(Me,{className:"py-4 text-sm text-muted-foreground",children:"Pitches are private to you. They never appear in the Exchange, public search, or sitemaps until you mark the assignment as won."})}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:V.map(le=>e.jsx(jZ,{listing:le,showActions:!0,onClick:()=>s(`/mission-control/listings/${le.id}/commercial`),onEdit:()=>s(`/mission-control/listings/${le.id}/commercial`),onDelete:()=>$(le.id)},le.id))})]}),e.jsx(Gt,{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((le,be)=>e.jsxs(ve,{children:[e.jsx(cn,{className:"h-48 w-full"}),e.jsxs(Me,{className:"p-4 space-y-2",children:[e.jsx(cn,{className:"h-5 w-3/4"}),e.jsx(cn,{className:"h-4 w-1/2"})]})]},be))}):(v==null?void 0:v.length)===0?e.jsx(ve,{children:e.jsxs(Me,{className:"py-12 text-center",children:[e.jsx(Do,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No saved listings"}),e.jsx("p",{className:"text-muted-foreground",children:"Save listings to quickly access them later"})]})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:v==null?void 0:v.map(le=>e.jsx(jZ,{listing:le.listing,onClick:()=>G(le.listing)},le.id))})}),e.jsx(Gt,{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(bd,{className:"h-4 w-4"}),"Referrals Sent (",((Z=S==null?void 0:S.sent)==null?void 0:Z.length)||0,")"]}),((ne=S==null?void 0:S.sent)==null?void 0:ne.length)===0?e.jsx(ve,{children:e.jsx(Me,{className:"py-8 text-center text-muted-foreground",children:"No referrals sent yet"})}):e.jsx("div",{className:"space-y-3",children:(ce=S==null?void 0:S.sent)==null?void 0:ce.map(le=>{var be,me;return e.jsx(ve,{children:e.jsx(Me,{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:le.buyer_name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:((be=le.listing)==null?void 0:be.property_address)||((me=le.listing)==null?void 0:me.city)})]}),e.jsx(Oe,{variant:le.status==="closed"?"default":"secondary",children:le.status.replace("_"," ")})]})})},le.id)})})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"font-semibold mb-3 flex items-center gap-2",children:[e.jsx(In,{className:"h-4 w-4"}),"Referrals Received (",((ie=S==null?void 0:S.received)==null?void 0:ie.length)||0,")"]}),((te=S==null?void 0:S.received)==null?void 0:te.length)===0?e.jsx(ve,{children:e.jsx(Me,{className:"py-8 text-center text-muted-foreground",children:"No referrals received yet"})}):e.jsx("div",{className:"space-y-3",children:(ae=S==null?void 0:S.received)==null?void 0:ae.map(le=>{var be;return e.jsx(ve,{children:e.jsxs(Me,{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:le.buyer_name}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["From: ",(be=le.sender)==null?void 0:be.name]})]}),e.jsx(Oe,{variant:le.status==="closed"?"default":"secondary",children:le.status.replace("_"," ")})]}),e.jsx(B,{size:"sm",variant:"outline",className:"w-full mt-2",onClick:()=>s(`/mission-control/listings/${le.listing_id}`),children:"View Listing"})]})},le.id)})})]})]})}),t&&e.jsx(Gt,{value:"brokerage",className:"space-y-4",children:P?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(3)].map((le,be)=>e.jsxs(ve,{children:[e.jsx(cn,{className:"h-48 w-full"}),e.jsxs(Me,{className:"p-4 space-y-2",children:[e.jsx(cn,{className:"h-5 w-3/4"}),e.jsx(cn,{className:"h-4 w-1/2"})]})]},be))}):(E==null?void 0:E.length)===0?e.jsx(ve,{children:e.jsxs(Me,{className:"py-12 text-center",children:[e.jsx(GM,{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(B,{onClick:()=>s("/mission-control/listings/new"),children:[e.jsx(rn,{className:"h-4 w-4 mr-2"}),"Add a Listing"]})]})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:E==null?void 0:E.map(le=>e.jsx(jZ,{listing:le,onClick:()=>G(le)},le.id))})}),e.jsx(Gt,{value:"map",children:e.jsx(wGn,{listings:f||[],isLoading:y})}),e.jsx(Gt,{value:"leaderboard",children:e.jsx(bGn,{leaderboard:M})})]})]}),e.jsx(xGn,{})]}):e.jsx(zs,{title:"Listing Exchange",description:"Community-powered listing collaboration",children:e.jsx(ve,{children:e.jsxs(Me,{className:"py-12 text-center",children:[e.jsx(Jr,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"Coming Soon"}),e.jsx("p",{className:"text-muted-foreground",children:"Listing Exchange is currently in development. Check back soon!"})]})})})}const NGn=s=>s<1024?`${s} B`:s<1024*1024?`${(s/1024).toFixed(0)} KB`:`${(s/(1024*1024)).toFixed(1)} MB`;function kGn({listingId:s,ownerOnly:t=!1}){const{data:n=[]}=WPe(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 net(i);window.open(l,"_blank")}catch{se.error("Failed to open document")}};return e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsxs(St,{className:"text-lg flex items-center gap-2",children:[e.jsx(Fr,{className:"h-5 w-5"}),"Documents & Disclosures (",r.length,")"]})}),e.jsx(Me,{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(Fr,{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:NGn(i.file_size)})]}),e.jsx(li,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary"})]},i.id))})})]})}function j_(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 eie(){const s=ha();return at({queryKey:["deal-pipeline-stages",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("deal_pipeline_stages").select("*").eq("owner_user_id",s).order("sort_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function Wts(){const s=ha(),t=Bt();return mt({mutationFn:async()=>{if(!s)throw new Error("Not authenticated");const{error:n}=await q.rpc("initialize_deal_pipeline_stages",{p_user_id:s});if(n)throw n},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-pipeline-stages"]})}})}function lK(){const s=ha();return at({queryKey:["deal-pipeline-deals",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("deal_pipeline").select(` *, contact:innercircle_contacts(id, first_name, last_name, email, phone), listing:listings(id, property_address, city, state, price, status, created_at) `).eq("owner_user_id",s).order("updated_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function Kts(){const s=ha(),t=Bt();return mt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("deal_pipeline").insert({deal_name:n.deal_name,deal_type:n.deal_type,stage_id:n.stage_id||null,contact_id:n.contact_id||null,listing_id:n.listing_id||null,property_address:n.property_address||null,city:n.city||null,state:n.state||null,zip_code:n.zip_code||null,expected_price:n.expected_price||null,expected_commission:n.expected_commission||null,commission_percentage:n.commission_percentage||3,target_close_date:n.target_close_date||null,contract_date:n.contract_date||null,listing_date:n.listing_date||null,priority:n.priority||"medium",probability:n.probability||50,notes:n.notes||null,owner_user_id:s}).select().single();if(a)throw a;return await q.from("deal_activities").insert([{deal_id:r.id,activity_type:"system",title:"Deal created",description:`Deal "${n.deal_name}" was created`}]),r},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-pipeline-deals"]}),t.invalidateQueries({queryKey:["deal-pipeline-stats"]})}})}function Yts(){const s=Bt();return mt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("deal_pipeline").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-pipeline-deals"]}),s.invalidateQueries({queryKey:["deal-pipeline-stats"]})}})}function SGn(){const s=Bt();return mt({mutationFn:async({dealId:t,stageId:n,stageName:r})=>{const{data:a}=await q.from("deal_pipeline_stages").select("default_probability").eq("id",n).maybeSingle(),i={stage_id:n};typeof(a==null?void 0:a.default_probability)=="number"&&(i.probability=a.default_probability);const{data:l,error:o}=await q.from("deal_pipeline").update(i).eq("id",t).select().single();if(o)throw o;return await q.from("deal_activities").insert({deal_id:t,activity_type:"stage_change",title:`Moved to ${r}`,metadata:{new_stage_id:n,new_stage_name:r}}),l},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-pipeline-deals"]}),s.invalidateQueries({queryKey:["deal-activities"]})}})}function CGn(){const s=Bt();return mt({mutationFn:async t=>{const{error:n}=await q.from("deal_pipeline").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-pipeline-deals"]}),s.invalidateQueries({queryKey:["deal-pipeline-stats"]})}})}function AGn(s){return at({queryKey:["deal-activities",s],queryFn:async()=>{const{data:t,error:n}=await q.from("deal_activities").select("*").eq("deal_id",s).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function EGn(){const s=Bt();return mt({mutationFn:async t=>{const{data:n,error:r}=await q.from("deal_activities").insert([{deal_id:t.deal_id,activity_type:t.activity_type,title:t.title,description:t.description||null}]).select().single();if(r)throw r;return n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["deal-activities",n.deal_id]})}})}function TGn(s){return at({queryKey:["deal-checklist",s],queryFn:async()=>{const{data:t,error:n}=await q.from("deal_checklist_items").select("*").eq("deal_id",s).order("sort_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function MGn(){const s=Bt();return mt({mutationFn:async({id:t,is_completed:n,deal_id:r})=>{const{data:a,error:i}=await q.from("deal_checklist_items").update({is_completed:n,completed_at:n?new Date().toISOString():null}).eq("id",t).select().single();if(i)throw i;return a},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["deal-checklist",n.deal_id]})}})}function PGn(){const s=Bt();return mt({mutationFn:async t=>{const{data:n,error:r}=await q.from("deal_checklist_items").insert([{deal_id:t.deal_id,title:t.title,description:t.description||null,due_date:t.due_date||null,sort_order:t.sort_order||0}]).select().single();if(r)throw r;return n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["deal-checklist",n.deal_id]})}})}function LGn(){const s=ha();return at({queryKey:["deal-pipeline-stats",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("deal_pipeline").select("*, deal_pipeline_stages(name, is_won_stage, is_lost_stage)").eq("owner_user_id",s);if(n)throw n;const r=(t==null?void 0:t.filter(o=>{var c,d,u;return!((c=o.deal_pipeline_stages)!=null&&c.is_won_stage)&&!((d=o.deal_pipeline_stages)!=null&&d.is_lost_stage)&&((u=o.deal_pipeline_stages)==null?void 0:u.name)!=="Cancelled"}))||[],a=(t==null?void 0:t.filter(o=>{var c;return(c=o.deal_pipeline_stages)==null?void 0:c.is_won_stage}))||[],i=new Date().getFullYear(),l=a.filter(o=>{const c=o.actual_close_date;return c?new Date(c).getFullYear()===i:!0});return{totalDeals:(t==null?void 0:t.length)||0,activeDeals:r.length,wonDeals:a.length,pipelineValue:r.reduce((o,c)=>o+(c.expected_price||0),0),expectedCommission:r.reduce((o,c)=>o+(c.expected_commission||0)+(c.bonus_amount||0),0),expectedNetToAgent:r.reduce((o,c)=>o+(j_(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+(j_(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+(j_(c)||0),0),projectedAnnualNet:l.reduce((o,c)=>o+(j_(c)||0),0)+r.reduce((o,c)=>{const d=(c.probability??50)/100;return o+(j_(c)||0)*d},0)}},enabled:!!s})}function IGn(s){const t=ha();return at({queryKey:["deal-by-listing",s,t],queryFn:async()=>{if(!t||!s)return null;const{data:n,error:r}=await q.from("deal_pipeline").select(` *, deal_pipeline_stages(id, name, color) `).eq("owner_user_id",t).eq("listing_id",s).maybeSingle();if(r)throw r;return n},enabled:!!t&&!!s})}function DGn(){const s=Bt();return mt({mutationFn:async({dealId:t,listingId:n})=>{const{data:r,error:a}=await q.from("deal_pipeline").update({listing_id:n}).eq("id",t).select().single();if(a)throw a;return await q.from("deal_activities").insert({deal_id:t,activity_type:"system",title:"Linked to Listing Exchange",description:"This deal is now synced with Listing Exchange",metadata:{listing_id:n}}),r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["deal-pipeline-deals"]}),s.invalidateQueries({queryKey:["deal-by-listing",n.listingId]})}})}function RGn(){const s=Bt();return mt({mutationFn:async({dealId:t,listingId:n})=>{const{data:r,error:a}=await q.from("deal_pipeline").update({listing_id:null}).eq("id",t).select().single();if(a)throw a;return{data:r,listingId:n}},onSuccess:t=>{s.invalidateQueries({queryKey:["deal-pipeline-deals"]}),s.invalidateQueries({queryKey:["deal-by-listing",t.listingId]})}})}function FGn({listing:s}){const t=Fn(),[n,r]=_.useState(""),[a,i]=_.useState(!1),{data:l,isLoading:o}=IGn(s.id),{data:c,isLoading:d}=eie(),{data:u,isLoading:h}=lK(),m=Wts(),p=DGn(),f=RGn(),y=Kts(),v=(u==null?void 0:u.filter(C=>!C.listing_id))||[],g=C=>{if(!(c!=null&&c.length))return null;switch(C){case"coming_soon":case"active":case"price_improvement":return c.find(E=>E.name==="Active");case"under_contract":return c.find(E=>E.name==="Under Contract");case"sold":return c.find(E=>E.is_won_stage);default:return c.find(E=>E.name==="Active")}},b=async()=>{i(!0);try{c!=null&&c.length||await m.mutateAsync();const C=g(s.status);await y.mutateAsync({deal_name:s.property_address?`${s.property_address}, ${s.city}`:`${s.city}, ${s.state}`,deal_type:"seller",stage_id:(C==null?void 0:C.id)||null,listing_id:s.id,property_address:s.property_address,city:s.city,state:s.state,expected_price:s.price,expected_commission:s.price*.03,commission_percentage:3,priority:"medium",probability:50}),se.success("Deal created and linked to listing!")}catch(C){console.error("Failed to create deal:",C),se.error("Failed to create deal")}finally{i(!1)}},j=async()=>{if(!n){se.error("Please select a deal");return}try{await p.mutateAsync({dealId:n,listingId:s.id}),se.success("Listing linked to deal!"),r("")}catch{se.error("Failed to link listing")}},S=async()=>{if(l)try{await f.mutateAsync({dealId:l.id,listingId:s.id}),se.success("Listing unlinked from deal")}catch{se.error("Failed to unlink listing")}};return o||d?e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsxs(St,{className:"flex items-center gap-2 text-base",children:[e.jsx(mj,{className:"h-4 w-4"}),"Deal Pipeline"]})}),e.jsx(Me,{children:e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(Ct,{className:"h-5 w-5 animate-spin text-muted-foreground"})})})]}):l?e.jsxs(ve,{className:"border-primary/20 bg-primary/5",children:[e.jsx(bt,{className:"pb-2",children:e.jsxs(St,{className:"flex items-center gap-2 text-base",children:[e.jsx(vd,{className:"h-4 w-4 text-primary"}),"Linked to Pipeline"]})}),e.jsxs(Me,{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(Oe,{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(B,{variant:"outline",size:"sm",className:"flex-1",onClick:()=>t("/mission-control/pipeline"),children:["View Pipeline",e.jsx(La,{className:"h-3 w-3 ml-1"})]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:S,disabled:f.isPending,children:f.isPending?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(h7,{className:"h-4 w-4"})})]})]})]}):e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-2",children:e.jsxs(St,{className:"flex items-center gap-2 text-base",children:[e.jsx(mj,{className:"h-4 w-4"}),"Deal Pipeline"]})}),e.jsxs(Me,{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(B,{onClick:b,disabled:a||y.isPending,className:"w-full",size:"sm",children:[a||y.isPending?e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(rn,{className:"h-4 w-4 mr-2"}),"Create New Deal"]}),v.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-0 flex items-center",children:e.jsx("span",{className:"w-full border-t"})}),e.jsx("div",{className:"relative flex justify-center text-xs uppercase",children:e.jsx("span",{className:"bg-card px-2 text-muted-foreground",children:"or"})})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(is,{value:n,onValueChange:r,children:[e.jsx(rs,{className:"flex-1 text-sm",children:e.jsx(ls,{placeholder:"Link to existing deal..."})}),e.jsx(as,{children:v.map(C=>e.jsx(He,{value:C.id,children:C.deal_name},C.id))})]}),e.jsx(B,{variant:"secondary",size:"icon",onClick:j,disabled:!n||p.isPending,children:p.isPending?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(vd,{className:"h-4 w-4"})})]})]})]})]})}const OGn={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"},zGn={active:"Active",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},ESt={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"};function BGn(){var ce,ie,te,ae,le,be,me,he,pe;const{listingId:s}=Li(),t=Fn(),{user:n}=hs(),{data:r,isLoading:a}=eae(s||""),{data:i}=M9t(s||""),{data:l}=z7s(s||""),o=T9t(),c=O7s(),d=B7s(),u=k9t(),h=q7s(),[m,p]=_.useState(!1),[f,y]=_.useState(!1),[v,g]=_.useState(!1),[b,j]=_.useState(!1),[S,C]=_.useState(!1),[E,P]=_.useState(!1),[M,I]=_.useState(null),[D,O]=_.useState({buyerName:"",buyerType:"",notes:""}),V=(n==null?void 0:n.id)===(r==null?void 0:r.agent_id),G=Ce=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(Ce),$=async Ce=>{const Ae=`https://listings.relevelup.com/${(r==null?void 0:r.slug)||(r==null?void 0:r.id)}`,Pe=`Check out this listing: ${(r==null?void 0:r.property_address)||(r==null?void 0:r.city)}`;d.mutate({listingId:r.id,shareType:Ce});try{switch(Ce){case"facebook":window.open(`https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(Ae)}`,"_blank");break;case"copy":await navigator.clipboard.writeText(Ae),se.success("Link copied to clipboard!");break;case"text":window.open(`sms:?body=${encodeURIComponent(`${Pe} ${Ae}`)}`);break;case"email":window.open(`mailto:?subject=${encodeURIComponent(Pe)}&body=${encodeURIComponent(`Check out this listing: ${Ae}`)}`);break}}catch(ze){console.error("Share error:",ze),se.error("Failed to share")}},H=async()=>{try{await u.mutateAsync(r.id),se.success("Listing deleted"),t("/mission-control/listings")}catch{se.error("Failed to delete listing")}},Y=async()=>{if(!D.buyerName.trim()){se.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}),se.success("Referral sent successfully!"),y(!1),O({buyerName:"",buyerType:"",notes:""})}catch{se.error("Failed to send referral")}},Z=Ce=>{var Fe,Ne;const Ae=(r==null?void 0:r.property_address)||`${r==null?void 0:r.city}, ${r==null?void 0:r.state}`,Pe=G((r==null?void 0:r.price)||0),ze=r!=null&&r.bedrooms?`${r.bedrooms}BD`:"",ke=r!=null&&r.bathrooms?`${r.bathrooms}BA`:"",Ze=r!=null&&r.square_footage?`${r.square_footage.toLocaleString()}SF`:"",Se=[ze,ke,Ze].filter(Boolean).join(" | ");switch(Ce){case"just_listed":return`🏡 JUST LISTED! ${Ae} ${Pe} ${Se} ${(r==null?void 0:r.description)||"Schedule your showing today!"} #JustListed #RealEstate #HomeForSale #${(Fe=r==null?void 0:r.city)==null?void 0:Fe.replace(/\s/g,"")}`;case"price_improvement":return`📣 PRICE IMPROVEMENT! ${Ae} Now ${Pe}! ${Se} Don't miss this opportunity! #PriceReduced #RealEstate #HomeForSale`;case"teaser":return`Looking for a ${ESt[(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 #${(Ne=r==null?void 0:r.city)==null?void 0:Ne.replace(/\s/g,"")}`;default:return""}};if(r&&r.listing_class==="commercial")return e.jsx(fd,{to:`/mission-control/listings/${r.id}/commercial`,replace:!0});if(a)return e.jsx(zs,{title:"Listing",description:"",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(cn,{className:"h-10 w-32"}),e.jsx(cn,{className:"h-[400px] w-full"}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[e.jsx(cn,{className:"h-48"}),e.jsx(cn,{className:"h-48"}),e.jsx(cn,{className:"h-48"})]})]})});if(!r)return e.jsx(zs,{title:"Listing Not Found",description:"",children:e.jsx(ve,{children:e.jsxs(Me,{className:"py-12 text-center",children:[e.jsx("p",{className:"text-muted-foreground mb-4",children:"This listing could not be found."}),e.jsx(B,{onClick:()=>t("/mission-control/listings"),children:"Back to Listings"})]})})});const ne=((ce=r.photos)==null?void 0:ce.find(Ce=>Ce.is_primary))||((ie=r.photos)==null?void 0:ie[0]);return e.jsxs(zs,{title:"",description:"",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs(B,{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:()=>ne&&I(ne.photo_url),children:ne?e.jsx("img",{src:ne.photo_url,alt:"Primary",className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:"No photos"})})}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:(te=r.photos)==null?void 0:te.slice(1,5).map((Ce,Ae)=>e.jsx("div",{className:"aspect-square rounded-lg overflow-hidden bg-muted cursor-pointer",onClick:()=>I(Ce.photo_url),children:e.jsx("img",{src:Ce.photo_url,alt:`Photo ${Ae+2}`,className:"w-full h-full object-cover"})},Ce.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(ve,{children:e.jsxs(Me,{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(Oe,{className:`${OGn[r.status]} text-white border-0`,children:zGn[r.status]}),r.is_featured&&e.jsxs(Oe,{variant:"outline",className:"border-amber-500 text-amber-500",children:[e.jsx(Da,{className:"h-3 w-3 mr-1 fill-amber-500"}),"Featured"]}),r.open_to_referrals&&e.jsxs(Oe,{variant:"outline",children:[e.jsx(In,{className:"h-3 w-3 mr-1"}),"Open to Referrals"]})]}),e.jsx("h1",{className:"text-3xl font-bold text-primary mb-2",children:G(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(Xa,{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(B,{variant:"outline",size:"icon",onClick:()=>o.mutate(r.id),children:e.jsx(Do,{className:`h-4 w-4 ${i?"fill-pink-500 text-pink-500":""}`})}),e.jsx(B,{variant:"outline",size:"icon",onClick:()=>c.mutate(r.id),children:l?e.jsx(cS,{className:"h-4 w-4"}):e.jsx(Rg,{className:"h-4 w-4"})}),!V&&e.jsxs(B,{variant:"outline",className:"border-amber-500 text-amber-600 hover:bg-amber-50",onClick:()=>g(!0),children:[e.jsx(un,{className:"h-4 w-4 mr-2"}),"Share & Earn Leads"]}),e.jsxs(tu,{children:[e.jsx(su,{asChild:!0,children:e.jsxs(B,{variant:"outline",children:[e.jsx(bd,{className:"h-4 w-4 mr-2"}),"Share"]})}),e.jsxs(Od,{children:[e.jsxs(ca,{onClick:()=>$("copy"),children:[e.jsx(Ia,{className:"h-4 w-4 mr-2"}),"Copy Link"]}),e.jsxs(ca,{onClick:()=>$("facebook"),children:[e.jsx(tf,{className:"h-4 w-4 mr-2"}),"Facebook"]}),e.jsxs(ca,{onClick:()=>$("text"),children:[e.jsx(Hi,{className:"h-4 w-4 mr-2"}),"Text"]}),e.jsxs(ca,{onClick:()=>$("email"),children:[e.jsx(ln,{className:"h-4 w-4 mr-2"}),"Email"]})]})]}),V&&e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"outline",onClick:()=>{const Ce=(r.photos??[]).slice().sort((Ae,Pe)=>(Pe.is_primary?1:0)-(Ae.is_primary?1:0)||(Ae.sort_order??0)-(Pe.sort_order??0)).map(Ae=>Ae.photo_url).filter(Boolean);if(Ce.length===0){se.error("Add photos to this listing first.");return}Hts({photos:Ce,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:Gts(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(Kq,{className:"h-4 w-4"}),"Create Music Video"]}),e.jsxs(B,{variant:"outline",onClick:()=>C(!0),className:"gap-2 border-amber-500/60 text-amber-600 hover:bg-amber-50",children:[e.jsx(un,{className:"h-4 w-4"}),"Just Listed Graphic"]}),e.jsxs(B,{variant:"outline",onClick:()=>P(!0),className:"gap-2",children:[e.jsx(Hf,{className:"h-4 w-4"}),"QR Code"]}),e.jsxs(B,{variant:"outline",onClick:()=>j(!0),className:"gap-2",children:[e.jsx(ln,{className:"h-4 w-4"}),"Email My Sphere"]}),e.jsxs(B,{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(un,{className:"h-4 w-4"}),"Customize Public Page"]}),e.jsxs(B,{variant:"outline",onClick:()=>t(`/mission-control/listings/${r.id}/edit`),children:[e.jsx(wp,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsx(B,{variant:"destructive",size:"icon",onClick:()=>p(!0),children:e.jsx(Sn,{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(dj,{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(S0,{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(wb,{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(ga,{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(Oe,{variant:"secondary",children:[e.jsx(ai,{className:"h-3 w-3 mr-1"}),ESt[r.property_type]]}),r.lot_size&&e.jsxs(Oe,{variant:"secondary",children:["Lot: ",r.lot_size]}),r.has_hoa&&e.jsx(Oe,{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(B,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:r.mls_link,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(wr,{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(ya,{className:"h-4 w-4"}),r.view_count," views"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(bd,{className:"h-4 w-4"}),r.share_count," shares"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Do,{className:"h-4 w-4"}),r.save_count," saves"]})]})]})}),r.allow_sharing&&e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-lg",children:"Share Content"})}),e.jsx(Me,{className:"space-y-4",children:["just_listed","price_improvement","teaser"].map(Ce=>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:[Ce.replace("_"," ")," Caption"]}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>{navigator.clipboard.writeText(Z(Ce)),se.success("Caption copied!")},children:e.jsx(Ia,{className:"h-3 w-3"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground whitespace-pre-wrap",children:Z(Ce)})]},Ce))})]}),e.jsx(kGn,{listingId:r.id,ownerOnly:V})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-lg",children:"Listing Agent"})}),e.jsxs(Me,{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:((le=(ae=r.agent)==null?void 0:ae.name)==null?void 0:le.charAt(0))||"?"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((be=r.agent)==null?void 0:be.name)||"Unknown"}),((he=(me=r.agent)==null?void 0:me.brokerage)==null?void 0:he.name)&&e.jsx("p",{className:"text-sm text-muted-foreground",children:r.agent.brokerage.name})]})]}),!V&&e.jsx("div",{className:"space-y-2",children:((pe=r.agent)==null?void 0:pe.email)&&e.jsx(B,{variant:"outline",className:"w-full",asChild:!0,children:e.jsxs("a",{href:`mailto:${r.agent.email}`,children:[e.jsx(ln,{className:"h-4 w-4 mr-2"}),"Email Agent"]})})})]})]}),V&&e.jsx(FGn,{listing:r}),!V&&r.open_to_referrals&&e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsxs(St,{className:"text-lg flex items-center gap-2",children:[e.jsx(In,{className:"h-5 w-5"}),"Send a Buyer"]})}),e.jsxs(Me,{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(B,{className:"w-full",onClick:()=>y(!0),children:"Send Referral"})]})]})]})]})]}),e.jsx(Ls,{open:!!M,onOpenChange:()=>I(null),children:e.jsx(Ps,{className:"max-w-4xl",children:e.jsx("img",{src:M||"",alt:"Full size",className:"w-full h-auto"})})}),e.jsx(Ls,{open:m,onOpenChange:p,children:e.jsxs(Ps,{children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Delete Listing"}),e.jsx(_r,{children:"Are you sure you want to delete this listing? This action cannot be undone."})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>p(!1),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:H,disabled:u.isPending,children:u.isPending?"Deleting...":"Delete"})]})]})}),e.jsx(Ls,{open:f,onOpenChange:y,children:e.jsxs(Ps,{children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Send Buyer Referral"}),e.jsx(_r,{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(J,{children:"Buyer Name *"}),e.jsx(xe,{value:D.buyerName,onChange:Ce=>O({...D,buyerName:Ce.target.value}),placeholder:"Enter buyer's name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Buyer Type"}),e.jsxs(is,{value:D.buyerType,onValueChange:Ce=>O({...D,buyerType:Ce}),children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Select type"})}),e.jsxs(as,{children:[e.jsx(He,{value:"first_time",children:"First-Time Buyer"}),e.jsx(He,{value:"investor",children:"Investor"}),e.jsx(He,{value:"relocating",children:"Relocating"}),e.jsx(He,{value:"upgrade",children:"Upgrading"}),e.jsx(He,{value:"downsize",children:"Downsizing"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Notes"}),e.jsx(Ms,{value:D.notes,onChange:Ce=>O({...D,notes:Ce.target.value}),placeholder:"Any additional information..."})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>y(!1),children:"Cancel"}),e.jsx(B,{onClick:Y,disabled:h.isPending,children:h.isPending?"Sending...":"Send Referral"})]})]})}),e.jsx(fzt,{open:E,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(aLe,{open:v,onOpenChange:g,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(Szt,{open:b,onOpenChange:j,listing:r}),e.jsx(met,{listingId:(r==null?void 0:r.id)||null,open:S,onOpenChange:C})]})}function UGn({onImport:s}){const[t,n]=_.useState(""),[r,a]=_.useState([]),[i,l]=_.useState(!1),[o,c]=_.useState(!1),[d,u]=_.useState(null),h=_.useRef(),m=_.useRef(null);_.useEffect(()=>{const b=j=>{m.current&&!m.current.contains(j.target)&&c(!1)};return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[]);const p=async b=>{if(b.trim().length<3){a([]),c(!1);return}l(!0);try{const{data:j,error:S}=await q.functions.invoke("mls-listing-search",{body:{query:b}});if(S)throw S;a((j==null?void 0:j.listings)||[]),c(!0)}catch(j){console.error("MLS search error:",j),a([])}finally{l(!1)}},f=b=>{n(b),h.current&&clearTimeout(h.current),h.current=setTimeout(()=>p(b),400)},y=b=>{u(b.mlsNumber),s(b),c(!1),n(`${b.address}, ${b.city}`),se.success(`Imported: ${b.address}`,{description:"Property details and photos have been auto-filled."}),u(null)},v=b=>b?`$${b.toLocaleString()}`:"",g=b=>{const j=(b||"").toLowerCase();return j.includes("single")||j.includes("detached")?"Single Family":j.includes("condo")?"Condo":j.includes("town")?"Townhouse":j.includes("land")||j.includes("lot")?"Land":j.includes("multi")?"Multi-Family":j.includes("commercial")?"Commercial":b||"Other"};return e.jsxs(ve,{className:"border-primary/30 bg-primary/5",children:[e.jsxs(bt,{className:"pb-3",children:[e.jsxs(St,{className:"text-base flex items-center gap-2",children:[e.jsx(li,{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(Me,{children:e.jsxs("div",{ref:m,className:"relative",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{value:t,onChange:b=>f(b.target.value),onFocus:()=>r.length>0&&c(!0),placeholder:"Start typing a property address...",className:"pl-9 pr-9"}),i&&e.jsx(Ct,{className:"absolute right-3 top-1/2 -translate-y-1/2 h-4 w-4 animate-spin text-muted-foreground"}),t&&!i&&e.jsx("button",{type:"button",onClick:()=>{n(""),a([]),c(!1)},className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",children:e.jsx(Qn,{className:"h-4 w-4"})})]}),o&&e.jsx("div",{className:"absolute z-50 w-full mt-1 bg-popover border rounded-lg shadow-lg max-h-[400px] overflow-y-auto",children:r.length===0&&!i?e.jsx("div",{className:"p-4 text-center text-sm text-muted-foreground",children:"No properties found. Try a different address."}):r.map(b=>e.jsxs("button",{type:"button",onClick:()=>y(b),disabled:d===b.mlsNumber,className:"w-full text-left p-3 hover:bg-accent/50 transition-colors border-b last:border-0 flex items-start gap-3",children:[b.photos[0]?e.jsx("img",{src:b.photos[0],alt:"",className:"w-16 h-12 rounded object-cover flex-shrink-0"}):e.jsx("div",{className:"w-16 h-12 rounded bg-muted flex items-center justify-center flex-shrink-0",children:e.jsx(Xa,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:b.address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[b.city,", ",b.state," ",b.zip]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-muted-foreground",children:[e.jsx("span",{className:"font-semibold text-foreground",children:v(b.price)}),b.bedrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(dj,{className:"h-3 w-3"})," ",b.bedrooms]}),b.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(S0,{className:"h-3 w-3"})," ",b.bathrooms]}),b.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(W4,{className:"h-3 w-3"})," ",b.sqft.toLocaleString()]})]})]}),e.jsxs("div",{className:"flex-shrink-0 flex flex-col items-end gap-1",children:[e.jsx(Oe,{variant:"outline",className:"text-[10px]",children:g(b.propertyType)}),b.photos.length>0&&e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[b.photos.length," photos"]})]})]},b.mlsNumber))})]})})]})}function qGn({selectedVideoId:s,onVideoSelect:t,listingId:n}){const r=Fn(),{user:a}=hs(),[i,l]=_.useState(!1),[o,c]=_.useState([]),[d,u]=_.useState(!1),[h,m]=_.useState(null),[p,f]=_.useState({});_.useEffect(()=>{s&&a?y():m(null)},[s,a]);const y=async()=>{if(!s)return;const{data:I,error:D}=await q.from("agent_videos").select("id, bunny_video_id, title, thumbnail_url, preview_url, playback_url, duration_seconds, status, created_at").eq("id",s).eq("is_deleted",!1).single();!D&&I&&(m(I),v(I))},v=async I=>{try{const{data:D,error:O}=await q.functions.invoke("bunny-upload",{body:{action:"asset-urls",videoId:I.bunny_video_id,isAgentVideo:!0}});!O&&(D!=null&&D.thumbnailUrl)&&f(V=>({...V,[I.id]:{thumbnailUrl:D.thumbnailUrl}}))}catch(D){console.warn("Failed to get signed URL",D)}},g=async()=>{if(a){u(!0);try{const{data:I,error:D}=await q.from("agent_videos").select("id, bunny_video_id, title, thumbnail_url, preview_url, playback_url, duration_seconds, status, created_at").eq("owner_user_id",a.id).eq("is_deleted",!1).eq("status","ready").order("created_at",{ascending:!1});if(D)throw D;c(I||[]),I!=null&&I.length&&b(I)}catch(I){console.error("Error fetching videos:",I),se.error("Failed to load videos")}finally{u(!1)}}},b=async I=>{var D;try{const O=I.map(Y=>Y.bunny_video_id),{data:V,error:G}=await q.functions.invoke("bunny-upload",{body:{action:"bulk-asset-urls",videoIds:O,isAgentVideo:!0}});if(G)throw G;const $=(V==null?void 0:V.assets)||{},H={};for(const Y of I)(D=$[Y.bunny_video_id])!=null&&D.thumbnailUrl&&(H[Y.id]={thumbnailUrl:$[Y.bunny_video_id].thumbnailUrl});f(Y=>({...Y,...H}))}catch(O){console.warn("Failed to bulk-fetch signed URLs",O)}},j=()=>{l(!0),g()},S=I=>{t(I.id),m(I),l(!1),se.success("Video selected")},C=()=>{t(null),m(null)},E=()=>{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),O=I%60;return`${D}:${O.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(ve,{className:"overflow-hidden",children:e.jsx(Me,{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(Kr,{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(Jd,{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(B,{type:"button",variant:"outline",size:"sm",onClick:j,children:"Change"}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:C,className:"text-destructive hover:text-destructive",children:e.jsx(Qn,{className:"h-4 w-4"})})]})]})})}):e.jsx(ve,{className:"border-dashed",children:e.jsx(Me,{className:"p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Kr,{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(B,{type:"button",variant:"outline",onClick:j,className:"gap-2",children:[e.jsx(fj,{className:"h-4 w-4"}),"Select from Library"]}),e.jsxs(B,{type:"button",variant:"outline",onClick:E,className:"gap-2",children:[e.jsx(cg,{className:"h-4 w-4"}),"Record New Video"]})]})]})})}),e.jsx(Ls,{open:i,onOpenChange:l,children:e.jsxs(Ps,{className:"max-w-2xl max-h-[80vh] overflow-hidden flex flex-col",children:[e.jsx(Os,{children:e.jsxs(Ds,{className:"flex items-center gap-2",children:[e.jsx(fj,{className:"h-5 w-5"}),"Select a Video"]})}),e.jsx("div",{className:"flex-1 overflow-y-auto",children:d?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Ct,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):o.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Kr,{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(B,{onClick:E,className:"gap-2",children:[e.jsx(cg,{className:"h-4 w-4"}),"Record Your First Video"]})]}):e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3 p-1",children:o.map(I=>e.jsxs("button",{type:"button",onClick:()=>S(I),className:`group relative rounded-lg overflow-hidden border-2 transition-all text-left ${s===I.id?"border-primary ring-2 ring-primary/20":"border-transparent hover:border-muted-foreground/30"}`,children:[e.jsxs("div",{className:"aspect-video bg-muted relative",children:[M(I)?e.jsx("img",{src:M(I),alt:I.title||"Video",className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(Kr,{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(Jd,{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(B,{type:"button",variant:"ghost",onClick:E,className:"gap-2",children:[e.jsx(cg,{className:"h-4 w-4"}),"Record New Video"]}),e.jsx(B,{type:"button",variant:"outline",onClick:()=>l(!1),children:"Cancel"})]})]})})]})}const $Gn=s=>s<1024?`${s} B`:s<1024*1024?`${(s/1024).toFixed(0)} KB`:`${(s/(1024*1024)).toFixed(1)} MB`;function VGn({listingId:s}){const t=_.useRef(null),{data:n=[],isLoading:r}=WPe(s),a=P9t(),i=L9t(),l=Y7s(),o=async d=>{if(!(!d||d.length===0)){for(const u of Array.from(d)){if(u.size>25*1024*1024){se.error(`${u.name} exceeds 25MB limit`);continue}try{await a.mutateAsync({listingId:s,file:u})}catch(h){se.error(`Failed to upload ${u.name}: ${h.message}`)}}t.current&&(t.current.value=""),se.success("Documents uploaded")}},c=async d=>{try{const u=await net(d);window.open(u,"_blank")}catch{se.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(B,{type:"button",variant:"outline",onClick:()=>{var d;return(d=t.current)==null?void 0:d.click()},disabled:a.isPending,className:"w-full",children:[a.isPending?e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Oa,{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(ve,{className:"p-3 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-md bg-primary/10",children:e.jsx(Fr,{className:"h-4 w-4 text-primary"})}),e.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:$Gn(d.file_size)})]}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[d.visible_on_exchange?e.jsx(ya,{className:"h-3 w-3"}):e.jsx(Ax,{className:"h-3 w-3"}),e.jsx("span",{className:"hidden sm:inline",children:d.visible_on_exchange?"Visible":"Hidden"}),e.jsx(fn,{checked:d.visible_on_exchange,onCheckedChange:u=>l.mutate({id:d.id,visible:u,listingId:s}),className:"ml-1"})]}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>c(d.storage_path),children:e.jsx(li,{className:"h-4 w-4"})}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:async()=>{await Xi(`Delete ${d.file_name}?`)&&i.mutate({id:d.id,storage_path:d.storage_path,listingId:s})},children:e.jsx(Qn,{className:"h-4 w-4 text-destructive"})})]},d.id))})]})}const HGn=[{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"}],GGn=[{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 WGn({id:s,url:t,index:n,onRemove:r}){const{attributes:a,listeners:i,setNodeRef:l,transform:o,transition:c,isDragging:d}=rLe({id:s}),u={transform:OP.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(Vf,{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(Qn,{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(Da,{className:"h-2.5 w-2.5 fill-current"})," Primary"]})]})}function KGn({photoUrls:s,pendingPhotos:t,onRemove:n,onReorder:r,uploading:a,onUpload:i}){const l=YPe(IH(yW,{activationConstraint:{distance:5}})),o=s.map((d,u)=>`pending-${u}`),c=d=>{const{active:u,over:h}=d;if(!h||u.id===h.id)return;const m=o.indexOf(u.id),p=o.indexOf(h.id),f=[...s],y=[...t],[v]=f.splice(m,1),[g]=y.splice(m,1);f.splice(p,0,v),y.splice(p,0,g),r(f,y)};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(tLe,{sensors:l,collisionDetection:ZPe,onDragEnd:c,children:e.jsx(nLe,{items:o,strategy:rae,children:e.jsxs("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-4",children:[s.map((d,u)=>e.jsx(WGn,{id:o[u],url:d,index:u,onRemove:n},o[u])),e.jsxs("label",{className:"aspect-square rounded-lg border-2 border-dashed border-muted-foreground/25 hover:border-muted-foreground/50 cursor-pointer flex flex-col items-center justify-center gap-2 text-muted-foreground",children:[a?e.jsx(Ct,{className:"h-8 w-8 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Oa,{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 TSt(){const{listingId:s}=Li(),[t]=Yl(),n=t.get("brokerage"),r=Fn(),{user:a}=hs(),{hasLeadSite:i}=lf(),l=!!s&&s!=="new",o=!!n&&!l,[c,d]=_.useState([]),[u,h]=_.useState({open:!1,listingId:null,nextPath:"/mission-control/listings"}),{data:m,isLoading:p}=eae(l?s:""),f=j9t(),y=R7s(),v=N9t(),g=S9t(),b=C9t(),j=A9t(),S=E9t(),{data:C=[]}=at({queryKey:["brokerage-agents",n],queryFn:async()=>{if(!n)return[];const{data:he,error:pe}=await q.from("profiles").select("id, name, email").eq("brokerage_id",n).order("name");if(pe)throw pe;return he||[]},enabled:o}),[E,P]=_.useState(""),[M,I]=_.useState(!1),[D,O]=_.useState([]),[V,G]=_.useState([]),[$,H]=_.useState(!1),Y=async he=>{if(he.size>5*1024*1024){se.error("Image must be under 5MB");return}H(!0);try{const pe=he.name.split(".").pop()||"jpg",Ce=`${(a==null?void 0:a.id)||"anon"}/co-agents/${Date.now()}.${pe}`,{error:Ae}=await q.storage.from("listing-photos").upload(Ce,he,{upsert:!0});if(Ae)throw Ae;const{data:Pe}=q.storage.from("listing-photos").getPublicUrl(Ce);ne(ze=>({...ze,co_agent_photo_url:Pe.publicUrl})),se.success("Headshot uploaded")}catch(pe){se.error((pe==null?void 0:pe.message)||"Failed to upload headshot")}finally{H(!1)}},[Z,ne]=_.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});_.useEffect(()=>{var he,pe,Ce,Ae,Pe;m&&l&&ne({property_address:m.property_address||"",city:m.city||"",state:m.state||"",neighborhood:m.neighborhood||"",price:((he=m.price)==null?void 0:he.toString())||"",property_type:m.property_type,status:m.status,bedrooms:((pe=m.bedrooms)==null?void 0:pe.toString())||"",bathrooms:((Ce=m.bathrooms)==null?void 0:Ce.toString())||"",square_footage:((Ae=m.square_footage)==null?void 0:Ae.toString())||"",lot_size:m.lot_size||"",year_built:((Pe=m.year_built)==null?void 0:Pe.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 ce=he=>{var Pe,ze;const pe={"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"},Ce=(he.propertyType||"").toLowerCase(),Ae=((Pe=Object.entries(pe).find(([ke])=>Ce.includes(ke)))==null?void 0:Pe[1])||"other";ne(ke=>({...ke,property_address:he.address||ke.property_address,city:he.city||ke.city,state:he.state||ke.state,price:he.price?String(he.price):ke.price,property_type:Ae,bedrooms:he.bedrooms?String(he.bedrooms):ke.bedrooms,bathrooms:he.bathrooms?String(he.bathrooms):ke.bathrooms,square_footage:he.sqft?String(he.sqft):ke.square_footage,lot_size:he.lotSize?String(he.lotSize):ke.lot_size,year_built:he.yearBuilt?String(he.yearBuilt):ke.year_built,description:he.description||ke.description})),((ze=he.photos)==null?void 0:ze.length)>0&&(d(he.photos),V.forEach(ke=>URL.revokeObjectURL(ke)),O([]),G([]))},ie=he=>{if(!he)return;const pe=Array.from(he);O(Ae=>[...Ae,...pe]);const Ce=pe.map(Ae=>URL.createObjectURL(Ae));G(Ae=>[...Ae,...Ce])},te=he=>{URL.revokeObjectURL(V[he]),O(pe=>pe.filter((Ce,Ae)=>Ae!==he)),G(pe=>pe.filter((Ce,Ae)=>Ae!==he))},ae=async he=>{var pe;if(!(!he||!m)){I(!0);try{for(const Ce of Array.from(he)){const Ae=Ce.name.split(".").pop(),Pe=`${a==null?void 0:a.id}/${m.id}/${Date.now()}.${Ae}`,{error:ze}=await q.storage.from("listing-photos").upload(Pe,Ce);if(ze)throw ze;const{data:{publicUrl:ke}}=q.storage.from("listing-photos").getPublicUrl(Pe);await g.mutateAsync({listingId:m.id,photoUrl:ke,isPrimary:!((pe=m.photos)!=null&&pe.length)})}se.success("Photos uploaded!")}catch(Ce){console.error("Upload error:",Ce),se.error("Failed to upload photos")}finally{I(!1)}}},le=async he=>{for(let pe=0;pe{if(m)try{await b.mutateAsync({photoId:he,listingId:m.id}),se.success("Photo removed")}catch{se.error("Failed to remove photo")}},me=async he=>{if(he.preventDefault(),!Z.city.trim()||!Z.state.trim()||!Z.price){se.error("Please fill in required fields (City, State, Price)");return}if(o&&!E){se.error("Please select an agent to assign this listing to");return}try{const pe={property_address:Z.property_address||null,city:Z.city,state:Z.state,neighborhood:Z.neighborhood||null,price:Number(Z.price),property_type:Z.property_type,status:Z.status,bedrooms:Z.bedrooms?Number(Z.bedrooms):null,bathrooms:Z.bathrooms?Number(Z.bathrooms):null,square_footage:Z.square_footage?Number(Z.square_footage):null,lot_size:Z.lot_size||null,year_built:Z.year_built?Number(Z.year_built):null,has_hoa:Z.has_hoa,description:Z.description||null,agent_notes:Z.agent_notes||null,agent_notes_public:Z.agent_notes_public,mls_link:Z.mls_link||null,video_link:Z.video_link||null,video_id:Z.video_id||null,co_agent_name:Z.co_agent_name||null,co_agent_email:Z.co_agent_email||null,co_agent_phone:Z.co_agent_phone||null,co_agent_brokerage:Z.co_agent_brokerage||null,co_agent_photo_url:Z.co_agent_photo_url||null,allow_sharing:Z.allow_sharing,open_to_referrals:Z.open_to_referrals,open_to_social_promotion:Z.open_to_social_promotion,share_with_brokerage:Z.share_with_brokerage,is_public:Z.site_only?!1:Z.is_public,site_only:Z.site_only,show_on_lead_site:Z.site_only?!0:Z.show_on_lead_site};if(l)await v.mutateAsync({id:s,...pe}),se.success("Listing updated!"),r(`/mission-control/listings/${s}`);else{I(!0);let Ce;if(o&&E?Ce=await y.mutateAsync({agentId:E,...pe}):Ce=await f.mutateAsync(pe),D.length>0)try{await le(Ce.id),V.forEach(Pe=>URL.revokeObjectURL(Pe)),O([]),G([])}catch(Pe){console.error("Photo upload error:",Pe),se.error("Listing created but some photos failed to upload")}if(c.length>0)try{for(let Pe=0;Per(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(ve,{children:[e.jsx(bt,{children:e.jsx(St,{children:"Assign to Agent *"})}),e.jsxs(Me,{children:[e.jsxs(is,{value:E,onValueChange:P,children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Select an agent..."})}),e.jsx(as,{children:C.map(he=>e.jsx(He,{value:he.id,children:he.name||he.email},he.id))})]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:"This listing will appear on the selected agent's Listing Exchange."})]})]}),!l&&i&&!o&&e.jsx(UGn,{onImport:ce}),c.length>0&&e.jsxs(ve,{className:"border-primary/30 bg-primary/5",children:[e.jsxs(bt,{className:"pb-3",children:[e.jsxs(St,{className:"text-base flex items-center gap-2",children:[e.jsx(li,{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(Me,{children:[e.jsxs("div",{className:"grid grid-cols-4 sm:grid-cols-6 gap-2",children:[c.slice(0,12).map((he,pe)=>e.jsx("div",{className:"aspect-square rounded overflow-hidden bg-muted",children:e.jsx("img",{src:he,alt:"",className:"w-full h-full object-cover"})},pe)),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(B,{type:"button",variant:"ghost",size:"sm",className:"mt-2 text-destructive",onClick:()=>d([]),children:[e.jsx(Qn,{className:"h-3 w-3 mr-1"})," Clear MLS photos"]})]})]}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{children:"Property Details"})}),e.jsx(Me,{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(J,{children:"Property Address"}),e.jsx(xe,{value:Z.property_address,onChange:he=>ne({...Z,property_address:he.target.value}),placeholder:"123 Main St"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"City *"}),e.jsx(xe,{value:Z.city,onChange:he=>ne({...Z,city:he.target.value}),placeholder:"City",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"State *"}),e.jsx(xe,{value:Z.state,onChange:he=>ne({...Z,state:he.target.value}),placeholder:"State",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Neighborhood"}),e.jsx(xe,{value:Z.neighborhood,onChange:he=>ne({...Z,neighborhood:he.target.value}),placeholder:"Neighborhood"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Price *"}),e.jsx(xe,{type:"number",value:Z.price,onChange:he=>ne({...Z,price:he.target.value}),placeholder:"500000",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Property Type"}),e.jsxs(is,{value:Z.property_type,onValueChange:he=>ne({...Z,property_type:he}),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsx(as,{children:GGn.map(he=>e.jsx(He,{value:he.value,children:he.label},he.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Status"}),e.jsxs(is,{value:Z.status,onValueChange:he=>ne({...Z,status:he}),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsx(as,{children:HGn.map(he=>e.jsx(He,{value:he.value,children:he.label},he.value))})]})]})]})})]}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{children:"Property Specs (Optional)"})}),e.jsx(Me,{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(J,{children:"Bedrooms"}),e.jsx(xe,{type:"number",value:Z.bedrooms,onChange:he=>ne({...Z,bedrooms:he.target.value}),placeholder:"3"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Bathrooms"}),e.jsx(xe,{type:"number",step:"0.5",value:Z.bathrooms,onChange:he=>ne({...Z,bathrooms:he.target.value}),placeholder:"2"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Sq Ft"}),e.jsx(xe,{type:"number",value:Z.square_footage,onChange:he=>ne({...Z,square_footage:he.target.value}),placeholder:"2000"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Lot Size"}),e.jsx(xe,{value:Z.lot_size,onChange:he=>ne({...Z,lot_size:he.target.value}),placeholder:"0.25 acres"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Year Built"}),e.jsx(xe,{type:"number",value:Z.year_built,onChange:he=>ne({...Z,year_built:he.target.value}),placeholder:"2005"})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-6",children:[e.jsx(fn,{checked:Z.has_hoa,onCheckedChange:he=>ne({...Z,has_hoa:he})}),e.jsx(J,{children:"Has HOA"})]})]})})]}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{children:"Description & Links"})}),e.jsxs(Me,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Description"}),e.jsx(Ms,{value:Z.description,onChange:he=>ne({...Z,description:he.target.value}),placeholder:"Tell the story of this property...",rows:4})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Agent Notes"}),e.jsx(Ms,{value:Z.agent_notes,onChange:he=>ne({...Z,agent_notes:he.target.value}),placeholder:"Notes for other agents...",rows:2}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fn,{checked:Z.agent_notes_public,onCheckedChange:he=>ne({...Z,agent_notes_public:he})}),e.jsx(J,{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(J,{children:"MLS Link"}),e.jsx(xe,{value:Z.mls_link,onChange:he=>ne({...Z,mls_link:he.target.value}),placeholder:"https://..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Video Link"}),e.jsx(xe,{value:Z.video_link,onChange:he=>ne({...Z,video_link:he.target.value}),placeholder:"YouTube or Vimeo URL"})]})]})]})]}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{children:"Co-Listing Agent (optional)"})}),e.jsxs(Me,{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(J,{children:"Name"}),e.jsx(xe,{value:Z.co_agent_name,onChange:he=>ne({...Z,co_agent_name:he.target.value}),placeholder:"Jordan Ellis"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Brokerage"}),e.jsx(xe,{value:Z.co_agent_brokerage,onChange:he=>ne({...Z,co_agent_brokerage:he.target.value}),placeholder:"Brokerage name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Email"}),e.jsx(xe,{type:"email",value:Z.co_agent_email,onChange:he=>ne({...Z,co_agent_email:he.target.value}),placeholder:"agent@email.com"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Phone"}),e.jsx(xe,{value:Z.co_agent_phone,onChange:he=>ne({...Z,co_agent_phone:he.target.value}),placeholder:"(555) 123-4567"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Headshot"}),e.jsxs("div",{className:"flex items-center gap-4",children:[Z.co_agent_photo_url?e.jsx("img",{src:Z.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(Oa,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{id:"co-agent-headshot",type:"file",accept:"image/*",className:"hidden",onChange:he=>{var Ce;const pe=(Ce=he.target.files)==null?void 0:Ce[0];he.target.value="",pe&&Y(pe)}}),e.jsx(B,{type:"button",variant:"outline",disabled:$,onClick:()=>{var he;return(he=document.getElementById("co-agent-headshot"))==null?void 0:he.click()},children:$?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"})," Uploading…"]}):e.jsxs(e.Fragment,{children:[e.jsx(Oa,{className:"h-4 w-4 mr-2"})," ",Z.co_agent_photo_url?"Replace photo":"Upload photo"]})}),Z.co_agent_photo_url&&e.jsxs(B,{type:"button",variant:"ghost",onClick:()=>ne(he=>({...he,co_agent_photo_url:""})),children:[e.jsx(Qn,{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(ve,{children:[e.jsx(bt,{children:e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(Kr,{className:"h-5 w-5"}),"Property Video"]})}),e.jsx(Me,{children:e.jsx(qGn,{selectedVideoId:Z.video_id,onVideoSelect:he=>ne({...Z,video_id:he}),listingId:l?s:void 0})})]}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{children:"Photos"})}),e.jsx(Me,{children:l&&(m!=null&&m.photos)?e.jsx(nzt,{photos:m.photos,uploading:M,onUpload:he=>ae(he),onRemove:he=>be(he),onReorder:he=>{j.mutate({photos:he.map(pe=>({id:pe.id,sort_order:pe.sort_order,is_primary:pe.is_primary}))})},onSetPrimary:he=>{m&&S.mutate({photoId:he,listingId:m.id})}}):e.jsx(KGn,{photoUrls:V,onRemove:te,onReorder:(he,pe)=>{G(he),O(pe)},pendingPhotos:D,uploading:M,onUpload:ie})})]}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(li,{className:"h-5 w-5"}),"Documents & Disclosures"]})}),e.jsx(Me,{children:l&&s?e.jsx(VGn,{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(ve,{children:[e.jsx(bt,{children:e.jsx(St,{children:"Sharing & Collaboration"})}),e.jsxs(Me,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Allow Sharing"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Other agents can share this listing"})]}),e.jsx(fn,{checked:Z.allow_sharing,onCheckedChange:he=>ne({...Z,allow_sharing:he})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Open to Referrals"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Accept buyer referrals"})]}),e.jsx(fn,{checked:Z.open_to_referrals,onCheckedChange:he=>ne({...Z,open_to_referrals:he})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Social Promotion"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Can be promoted on social media"})]}),e.jsx(fn,{checked:Z.open_to_social_promotion,onCheckedChange:he=>ne({...Z,open_to_social_promotion:he})})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Share with Brokerage"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Visible to agents in your brokerage"})]}),e.jsx(fn,{checked:Z.share_with_brokerage,onCheckedChange:he=>ne({...Z,share_with_brokerage:he})})]}),i&&e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsxs("div",{children:[e.jsx(J,{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(fn,{checked:Z.site_only,onCheckedChange:he=>ne({...Z,site_only:he,is_public:he?!1:Z.is_public,show_on_lead_site:he?!0:Z.show_on_lead_site,share_with_brokerage:he?!1:Z.share_with_brokerage})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Make Public"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Publish on listings.relevelup.com to get leads"})]}),e.jsx(fn,{checked:Z.is_public,disabled:Z.site_only,onCheckedChange:he=>ne({...Z,is_public:he})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Show on My Website"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Z.status==="sold"?"Sold listings are hidden from the Listing Exchange and public marketplace — they only build your track record on your website's Sold page.":"Feature this listing on your lead site homepage and listings page"})]}),e.jsx(fn,{checked:Z.show_on_lead_site,onCheckedChange:he=>ne({...Z,show_on_lead_site:he})})]})]})]}),e.jsx(B,{type:"submit",className:"w-full",size:"lg",disabled:f.isPending||v.isPending,children:f.isPending||v.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),"Saving..."]}):l?"Update Listing":"Create Listing"})]})]})]}),e.jsx(met,{listingId:u.listingId,open:u.open,onOpenChange:he=>{if(!he){const{nextPath:pe}=u;h({open:!1,listingId:null,nextPath:pe}),r(pe)}}})]})}const NYe=[{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"}],Zts=[{type:"extra_video",label:"Extra Video / Reel",icon:Kr,desc:"Add a YouTube, Vimeo, or MP4 embed",accent:"from-rose-500/20 to-rose-500/5"},{type:"tour_3d",label:"3D Tour",icon:bQ,desc:"Matterport, iGuide, or Kuula embed",accent:"from-indigo-500/20 to-indigo-500/5"},{type:"floor_plans",label:"Floor Plans",icon:hc,desc:"Upload floor plan images",accent:"from-sky-500/20 to-sky-500/5"},{type:"testimonial",label:"Testimonial",icon:pS,desc:"A quote from a past client",accent:"from-amber-500/20 to-amber-500/5"},{type:"countdown",label:"Offer Countdown",icon:Gr,desc:'"Offers due Friday 5pm"',accent:"from-emerald-500/20 to-emerald-500/5"},{type:"custom_cta",label:"Custom CTA Button",icon:Vc,desc:"Link to a brochure or booking page",accent:"from-violet-500/20 to-violet-500/5"}],YGn=["#0f172a","#406E71","#c9a84c","#b91c1c","#0d7a5f","#4f46e5","#e85d3a","#111827"],Qze={sections:Object.fromEntries(NYe.map(s=>[s.key,!0])),hero_style:"photo",accent_color:null,custom_note:"",addons:[]},ZGn=()=>Math.random().toString(36).slice(2,10);function XGn(){const{listingId:s}=Li(),t=Fn(),{user:n}=hs(),r=Bt(),[a,i]=_.useState("desktop"),[l,o]=_.useState(Qze),[c,d]=_.useState(!1),[u,h]=_.useState(0),{data:m,isLoading:p}=at({queryKey:["listing-customize",s],queryFn:async()=>{const{data:D,error:O}=await q.from("listings").select("id, agent_id, slug, property_address, city, state, price, page_config, page_theme").eq("id",s).single();if(O)throw O;return D},enabled:!!s});_.useEffect(()=>{var D,O;m!=null&&m.page_config&&o({...Qze,...m.page_config||{},sections:{...Qze.sections,...((D=m.page_config)==null?void 0:D.sections)||{}},addons:((O=m.page_config)==null?void 0:O.addons)||[]})},[m==null?void 0:m.id]);const f=!!n&&!!m&&n.id===m.agent_id,y=_.useMemo(()=>m?`/public/listing/${m.slug||m.id}?preview=1&t=${u}`:"",[m,u]),v=_.useMemo(()=>m?`https://listings.relevelup.com/${m.slug||m.id}`:"",[m]),g=mt({mutationFn:async()=>{const{error:D}=await q.from("listings").update({page_config:l}).eq("id",s);if(D)throw D},onSuccess:()=>{se.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=>se.error(`Save failed: ${D.message||"Try again"}`)}),b=D=>{o(O=>({...O,...D})),d(!0)},j=(D,O)=>b({sections:{...l.sections||{},[D]:O}}),S=D=>b({addons:[...l.addons||[],{id:ZGn(),type:D,data:{}}]}),C=(D,O)=>b({addons:(l.addons||[]).map(V=>V.id===D?{...V,data:{...V.data,...O}}:V)}),E=D=>b({addons:(l.addons||[]).filter(O=>O.id!==D)}),P=(D,O)=>{const V=[...l.addons||[]],G=V.findIndex(H=>H.id===D);if(G<0)return;const $=G+O;$<0||$>=V.length||([V[G],V[$]]=[V[$],V[G]],b({addons:V}))};if(p)return e.jsx(zs,{title:"",description:"",children:e.jsx("div",{className:"p-8 text-sm text-muted-foreground",children:"Loading…"})});if(!m)return e.jsx(zs,{title:"",description:"",children:e.jsx("div",{className:"p-8",children:"Listing not found."})});if(!f)return e.jsx(zs,{title:"",description:"",children:e.jsxs("div",{className:"p-8",children:[e.jsx("p",{children:"You can only customize your own listing pages."}),e.jsx(B,{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(zs,{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(B,{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(hN,{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(p1,{className:"h-3.5 w-3.5"})," Mobile"]})]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>h(D=>D+1),children:[e.jsx(uo,{className:"h-3.5 w-3.5 mr-1.5"})," Refresh"]}),e.jsx(B,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:v,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(wr,{className:"h-3.5 w-3.5 mr-1.5"})," Open live"]})}),e.jsx(B,{size:"sm",onClick:()=>g.mutate(),disabled:!c||g.isPending,children:g.isPending?"Saving…":e.jsxs(e.Fragment,{children:[e.jsx(Ho,{className:"h-3.5 w-3.5 mr-1.5"})," Save & Publish"]})})]})]}),e.jsxs("div",{className:"grid lg:grid-cols-[minmax(360px,440px)_1fr] gap-6 mt-4",children:[e.jsx(Ji,{className:"lg:h-[calc(100vh-140px)] pr-2",children:e.jsxs("div",{className:"space-y-6 pb-16",children:[e.jsx(NZ,{icon:e.jsx(un,{className:"h-4 w-4"}),title:"Hero",desc:"What visitors see first",children:e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Hero style"}),e.jsx("div",{className:"mt-2 grid grid-cols-3 gap-2",children:["photo","video","slideshow"].map(D=>e.jsx("button",{onClick:()=>b({hero_style:D}),className:`text-xs rounded-lg border py-3 capitalize transition ${l.hero_style===D?"border-primary bg-primary/5 text-primary font-medium":"border-border hover:bg-muted"}`,children:D},D))})]})}),e.jsx(NZ,{icon:e.jsx(Xc,{className:"h-4 w-4"}),title:"Accent color",desc:"Highlights on the public page",children:e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("button",{onClick:()=>b({accent_color:null}),className:`h-9 px-3 rounded-full text-xs border ${l.accent_color?"border-border hover:bg-muted":"border-primary bg-primary/5 text-primary"}`,children:"Default"}),YGn.map(D=>e.jsx("button",{onClick:()=>b({accent_color:D}),className:`h-9 w-9 rounded-full border-2 transition ${l.accent_color===D?"ring-2 ring-offset-2 ring-primary border-white":"border-white/20"}`,style:{background:D},"aria-label":D},D))]})}),e.jsx(NZ,{icon:e.jsx(Qx,{className:"h-4 w-4"}),title:"Personal note",desc:"Shows in a beautiful callout on the public page",children:e.jsx(Ms,{value:l.custom_note||"",onChange:D=>b({custom_note:D.target.value}),placeholder:"Why we love this home… (optional)",rows:3})}),e.jsx(NZ,{icon:e.jsx(Z3,{className:"h-4 w-4"}),title:"Page sections",desc:"Toggle any default section on or off",rightLabel:`${I} of ${NYe.length} on`,children:e.jsx("div",{className:"divide-y rounded-xl border",children:NYe.map(D=>{var V;const O=((V=l.sections)==null?void 0:V[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(fn,{checked:O,onCheckedChange:G=>j(D.key,G)})]},D.key)})})}),e.jsxs(NZ,{icon:e.jsx(rn,{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:Zts.map(D=>e.jsxs("button",{onClick:()=>S(D.type),className:`group text-left rounded-xl border p-3 hover:shadow-md transition bg-gradient-to-br ${D.accent}`,children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("div",{className:"h-7 w-7 rounded-md bg-background border flex items-center justify-center",children:e.jsx(D.icon,{className:"h-3.5 w-3.5"})}),e.jsx("span",{className:"text-sm font-medium",children:D.label})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground leading-snug",children:D.desc})]},D.type))}),(l.addons||[]).length>0&&e.jsxs("div",{className:"mt-4 space-y-3",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-widest text-muted-foreground",children:"On this page · drag to reorder"}),(l.addons||[]).map((D,O)=>e.jsx(QGn,{addon:D,onChange:V=>C(D.id,V),onRemove:()=>E(D.id),onMoveUp:O>0?()=>P(D.id,-1):void 0,onMoveDown:OP(D.id,1):void 0},D.id))]})]}),e.jsx("div",{className:"lg:hidden",children:e.jsx(B,{className:"w-full",onClick:()=>g.mutate(),disabled:!c||g.isPending,children:g.isPending?"Saving…":e.jsxs(e.Fragment,{children:[e.jsx(Ho,{className:"h-4 w-4 mr-1.5"})," Save & Publish"]})})})]})}),e.jsx("div",{className:"lg:h-[calc(100vh-140px)]",children:e.jsxs(ve,{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(ya,{className:"h-3.5 w-3.5"}),"Live preview",c&&e.jsx(Oe,{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(ea,{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(hN,{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(p1,{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:y,title:"Preview",className:"w-full h-full border-0"},u)})})]})})]})]})}function NZ({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 QGn({addon:s,onChange:t,onRemove:n,onMoveUp:r,onMoveDown:a}){const i=Zts.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(Vf,{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(B,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:a,"aria-label":"Move down",children:e.jsx(Vf,{className:"h-3.5 w-3.5 rotate-180"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-7 w-7 text-destructive hover:text-destructive",onClick:n,"aria-label":"Remove",children:e.jsx(Sn,{className:"h-3.5 w-3.5"})})]})]}),s.type==="extra_video"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{className:"text-xs",children:"Video URL"}),e.jsx(xe,{placeholder:"https://youtu.be/…",value:s.data.url||"",onChange:o=>t({url:o.target.value})}),e.jsx(J,{className:"text-xs",children:"Title (optional)"}),e.jsx(xe,{placeholder:"e.g. Sunset drone flyover",value:s.data.title||"",onChange:o=>t({title:o.target.value})})]}),s.type==="tour_3d"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{className:"text-xs",children:"3D tour embed URL"}),e.jsx(xe,{placeholder:"https://my.matterport.com/show/?m=…",value:s.data.url||"",onChange:o=>t({url:o.target.value})})]}),s.type==="floor_plans"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{className:"text-xs",children:"Floor plan image URLs (one per line)"}),e.jsx(Ms,{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(J,{className:"text-xs",children:"Quote"}),e.jsx(Ms,{rows:3,placeholder:`"Best home-buying experience we've ever had."`,value:s.data.quote||"",onChange:o=>t({quote:o.target.value})}),e.jsx(J,{className:"text-xs",children:"Attribution"}),e.jsx(xe,{placeholder:"Sarah & Mike, past clients",value:s.data.author||"",onChange:o=>t({author:o.target.value})})]}),s.type==="countdown"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{className:"text-xs",children:"Headline"}),e.jsx(xe,{placeholder:"Offers due",value:s.data.headline||"",onChange:o=>t({headline:o.target.value})}),e.jsx(J,{className:"text-xs",children:"Deadline (date & time)"}),e.jsx(xe,{type:"datetime-local",value:s.data.deadline||"",onChange:o=>t({deadline:o.target.value})})]}),s.type==="custom_cta"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{className:"text-xs",children:"Button label"}),e.jsx(xe,{placeholder:"Download brochure",value:s.data.label||"",onChange:o=>t({label:o.target.value})}),e.jsx(J,{className:"text-xs",children:"Link URL"}),e.jsx(xe,{placeholder:"https://…",value:s.data.url||"",onChange:o=>t({url:o.target.value})})]})]})}const Xts="teleprompter_settings",Jze={scrollSpeed:30,fontSize:24,lineHeight:1.6,opacity:.85,position:"top",isMirrored:!1};function JGn(){try{const s=localStorage.getItem(Xts);return s?{...Jze,...JSON.parse(s)}:Jze}catch{return Jze}}function eWn(s){try{localStorage.setItem(Xts,JSON.stringify(s))}catch{}}function aat({text:s,isVisible:t,onToggleVisibility:n,isRecording:r=!1,startCountdown:a=!1,onCountdownComplete:i,className:l}){const o=_.useRef(null),c=_.useRef(null),d=_.useRef(0),u=_.useRef(0),[h,m]=_.useState(JGn),{scrollSpeed:p,fontSize:f,lineHeight:y,opacity:v,position:g,isMirrored:b}=h,j=_.useCallback((V,G)=>{m($=>{const H={...$,[V]:G};return eWn(H),H})},[]),[S,C]=_.useState(!1),[E,P]=_.useState(null),M=_.useCallback(V=>{if(!o.current)return;d.current===0&&(d.current=V);const G=V-d.current;d.current=V,u.current+=p*G/1e3;const $=Math.floor(u.current);$>0&&(o.current.scrollTop+=$,u.current-=$);const{scrollTop:H,scrollHeight:Y,clientHeight:Z}=o.current;if(H+Z>=Y){C(!1);return}c.current=requestAnimationFrame(M)},[p]);_.useEffect(()=>(S?(d.current=0,u.current=0,c.current=requestAnimationFrame(M)):c.current&&cancelAnimationFrame(c.current),()=>{c.current&&cancelAnimationFrame(c.current)}),[S,M]),_.useEffect(()=>{if(r&&t)if(o.current&&(o.current.scrollTop=0),a){P(3);let V=3;const G=setInterval(()=>{V-=1,V<=0?(clearInterval(G),P(null),i==null||i(),C(!0)):P(V)},1e3);return()=>clearInterval(G)}else setTimeout(()=>C(!0),100);else r||(C(!1),P(null))},[r,t,a,i]);const I=_.useCallback(()=>{o.current&&(o.current.scrollTop=0),C(!1)},[]),D=_.useCallback(()=>{C(V=>!V)},[]);if(!t)return e.jsx("div",{className:At("absolute top-4 right-4 pointer-events-auto z-10",l),children:e.jsxs(B,{variant:"secondary",size:"sm",onClick:n,className:"bg-black/50 hover:bg-black/70 text-white border-0",children:[e.jsx(ya,{className:"h-4 w-4 mr-2"}),"Show Script"]})});const O={top:"top-0 pt-16",center:"top-1/2 -translate-y-1/2",bottom:"bottom-0 pb-24"};return e.jsxs("div",{className:At("absolute inset-0 pointer-events-none",l),children:[E!==null&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center z-20 pointer-events-none",children:e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx("div",{className:"text-white font-bold drop-shadow-lg animate-scale-in",style:{fontSize:"96px",lineHeight:1,textShadow:"0 4px 16px rgba(0,0,0,0.8)"},children:E},E),e.jsx("p",{className:"text-white/80 text-lg font-medium drop-shadow-md",children:"Get ready…"})]})}),e.jsx("div",{className:At("absolute left-0 right-0 h-[60%] overflow-hidden pointer-events-auto",O[g],E!==null&&"opacity-30"),style:{opacity:E!==null?.3:v},children:e.jsxs("div",{ref:o,className:At("mx-auto max-w-2xl px-6 overflow-y-auto scrollbar-hide h-full",b&&"scale-x-[-1]"),style:{maskImage:"linear-gradient(to bottom, transparent, black 10%, black 90%, transparent)",WebkitMaskImage:"linear-gradient(to bottom, transparent, black 10%, black 90%, transparent)"},children:[e.jsx("div",{className:"h-full",style:{minHeight:"100%"}}),e.jsx("p",{className:"text-white text-center font-medium drop-shadow-lg",style:{fontSize:`${f}px`,lineHeight:y,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(od,{children:[e.jsx(ld,{asChild:!0,children:e.jsx(B,{variant:"secondary",size:"icon",className:"h-9 w-9 bg-black/50 hover:bg-black/70 text-white border-0",children:e.jsx(qc,{className:"h-4 w-4"})})}),e.jsx(Qc,{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(J,{className:"text-xs",children:"Scroll Speed"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:p})]}),e.jsx(kx,{value:[p],onValueChange:([V])=>j("scrollSpeed",V),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(J,{className:"text-xs",children:"Font Size"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[f,"px"]})]}),e.jsx(kx,{value:[f],onValueChange:([V])=>j("fontSize",V),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(J,{className:"text-xs",children:"Line Spacing"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:y.toFixed(1)})]}),e.jsx(kx,{value:[y*10],onValueChange:([V])=>j("lineHeight",V/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(J,{className:"text-xs",children:"Opacity"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[Math.round(v*100),"%"]})]}),e.jsx(kx,{value:[v*100],onValueChange:([V])=>j("opacity",V/100),min:30,max:100,step:5})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{className:"text-xs",children:"Position"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{variant:g==="top"?"default":"outline",size:"sm",onClick:()=>j("position","top"),children:e.jsx(_v,{className:"h-4 w-4"})}),e.jsx(B,{variant:g==="center"?"default":"outline",size:"sm",onClick:()=>j("position","center"),children:e.jsx(uN,{className:"h-4 w-4"})}),e.jsx(B,{variant:g==="bottom"?"default":"outline",size:"sm",onClick:()=>j("position","bottom"),children:e.jsx(tl,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(J,{className:"text-xs",children:"Mirror Mode"}),e.jsx(fn,{checked:b,onCheckedChange:V=>j("isMirrored",V)})]})]})})]}),e.jsx(B,{variant:"secondary",size:"icon",onClick:D,className:"h-9 w-9 bg-black/50 hover:bg-black/70 text-white border-0",children:S?e.jsx(ky,{className:"h-4 w-4"}):e.jsx(Jd,{className:"h-4 w-4"})}),e.jsx(B,{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(Tx,{className:"h-4 w-4"})}),e.jsxs(B,{variant:"secondary",size:"sm",onClick:n,className:"bg-black/50 hover:bg-black/70 text-white border-0",children:[e.jsx(Ax,{className:"h-4 w-4 mr-2"}),"Hide"]})]})]})}function tWn({onSelectScript:s,onCreateNew:t,selectedScriptId:n,className:r}){const{toast:a}=vi(),[i,l]=_.useState(""),[o,c]=_.useState(null),[d,u]=_.useState("levelup"),{data:h,isLoading:m}=aRn(),{data:p,isLoading:f}=iRn(),{data:y,isLoading:v}=oRn(),g=lRn(),b=_.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]),j=_.useMemo(()=>y?y.filter(P=>!i||P.title.toLowerCase().includes(i.toLowerCase())||P.script_text.toLowerCase().includes(i.toLowerCase())):[],[y,i]),S=P=>{s({title:P.title,text:P.script_text})},C=async P=>{try{await g.mutateAsync(P),a({title:"Script saved to My Scripts"})}catch{a({title:"Failed to save script",variant:"destructive"})}},E=m||f||v;return e.jsxs("div",{className:At("flex flex-col h-full",r),children:[e.jsx("div",{className:"p-4 border-b",children:e.jsxs("div",{className:"relative",children:[e.jsx(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search scripts...",value:i,onChange:P=>l(P.target.value),className:"pl-9"})]})}),e.jsxs(Yr,{value:d,onValueChange:P=>u(P),className:"flex-1 flex flex-col",children:[e.jsxs(Zr,{className:"mx-4 mt-4 grid grid-cols-2",children:[e.jsxs(Ht,{value:"levelup",children:[e.jsx(Fr,{className:"h-4 w-4 mr-2"}),"LevelUp Scripts"]}),e.jsxs(Ht,{value:"my-scripts",children:[e.jsx(C0,{className:"h-4 w-4 mr-2"}),"My Scripts"]})]}),e.jsxs(Gt,{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(Oe,{variant:o?"outline":"default",className:"cursor-pointer",onClick:()=>c(null),children:"All"}),h==null?void 0:h.map(P=>e.jsx(Oe,{variant:o===P.id?"default":"outline",className:"cursor-pointer",onClick:()=>c(P.id),children:P.name},P.id))]}),e.jsx(Ji,{className:"flex-1 max-h-[50vh]",children:E?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):b.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Fr,{className:"h-12 w-12 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"No scripts found"})]}):e.jsx("div",{className:"space-y-2",children:b.map(P=>e.jsxs(ve,{className:At("cursor-pointer hover:bg-accent/50 transition-colors",n===P.id&&"ring-2 ring-primary"),onClick:()=>S(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(St,{className:"text-sm font-medium truncate",children:P.title}),P.category&&e.jsx(Oe,{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(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:M=>{M.stopPropagation(),C(P)},children:e.jsx(C0,{className:"h-4 w-4"})}),e.jsx(xi,{className:"h-4 w-4 text-muted-foreground"})]})]})}),e.jsx(Me,{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(Gt,{value:"my-scripts",className:"flex-1 flex flex-col mt-0 p-4",children:[t&&e.jsxs(B,{variant:"outline",className:"mb-4",onClick:t,children:[e.jsx(rn,{className:"h-4 w-4 mr-2"}),"Create New Script"]}),e.jsx(Ji,{className:"flex-1 max-h-[50vh]",children:v?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):j.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(C0,{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:j.map(P=>e.jsxs(ve,{className:At("cursor-pointer hover:bg-accent/50 transition-colors",n===P.id&&"ring-2 ring-primary"),onClick:()=>S(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(St,{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(Oe,{variant:"outline",className:"text-xs",children:"Custom"}):e.jsx(Oe,{variant:"secondary",className:"text-xs",children:"Saved"})})]}),e.jsx(xi,{className:"h-4 w-4 text-muted-foreground ml-2"})]})}),e.jsx(Me,{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 sWn({selectedTemplate:s,onSelect:t,contactName:n,saving:r=!1}){const[a,i]=_.useState(()=>{const o=k$(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(J,{className:"text-sm font-medium",children:"Share Page Template"}),r&&e.jsx(Ct,{className:"h-3 w-3 animate-spin text-muted-foreground"})]}),e.jsx("div",{className:"space-y-3",children:T7s.map(o=>{const c=M7s(o.id),d=a.has(o.id),u=c.some(h=>h.id===s);return e.jsxs(f1,{open:d,onOpenChange:()=>l(o.id),children:[e.jsxs(x1,{className:"flex items-center justify-between w-full p-2.5 rounded-lg bg-muted/50 hover:bg-muted transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium text-sm",children:o.name}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",c.length,")"]}),u&&!d&&e.jsx("span",{className:"text-xs bg-primary/10 text-primary px-1.5 py-0.5 rounded-full",children:"✓"})]}),e.jsx(tl,{className:At("h-4 w-4 text-muted-foreground transition-transform",d&&"rotate-180")})]}),e.jsx(g1,{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:At("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(ea,{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: "',k$(s).headerText(n),'"']})]})}function Qts({open:s,onOpenChange:t,video:n,contactName:r,onTemplateUpdated:a}){const[i,l]=_.useState(n.page_template||"default"),[o,c]=_.useState(!1),[d,u]=_.useState(!1),[h,m]=_.useState(n.page_template||"default"),[p,f]=_.useState([]),[y,v]=_.useState(n.contact_id&&r?{id:n.contact_id,name:r,email:null}:null),[g,b]=_.useState(!1),[j,S]=_.useState(!1),C=n.share_token?`https://video.relevelup.com/${n.share_token}`:"";_.useEffect(()=>{s&&p.length===0&&E()},[s]);const E=async()=>{S(!0);try{const{data:H,error:Y}=await q.from("innercircle_contacts").select("id, first_name, last_name, email").order("first_name",{ascending:!0}).limit(500);if(Y)throw Y;const Z=(H||[]).map(ne=>({id:ne.id,name:[ne.first_name,ne.last_name].filter(Boolean).join(" ")||"Unnamed",email:ne.email||null}));f(Z)}catch(H){console.error("Failed to fetch contacts:",H)}finally{S(!1)}},P=async H=>{v(H),b(!1),c(!0);try{const{error:Y}=await q.from("agent_videos").update({contact_id:(H==null?void 0:H.id)||null,recipient_name:(H==null?void 0:H.name)||null}).eq("id",n.id);if(Y)throw Y;se.success(H?`Assigned to ${H.name}`:"Contact removed"),a==null||a()}catch(Y){console.error("Failed to update contact:",Y),se.error("Failed to update contact")}finally{c(!1)}},M=async H=>{l(H),c(!0);try{const{error:Y}=await q.from("agent_videos").update({page_template:H}).eq("id",n.id);if(Y)throw Y;m(H),se.success("Template saved!"),a==null||a()}catch(Y){console.error("Failed to save template:",Y),se.error("Failed to save template"),l(h)}finally{c(!1)}},I=(y==null?void 0:y.name)||null,D=()=>{const H=n.title||"Video Message",Y=n.share_token?`https://video.relevelup.com/thumb/${n.share_token}`:n.thumbnail_url||"";return``},O=async()=>{if(!n.thumbnail_url){se.error("Video thumbnail not available yet");return}const H=D(),Y=`Watch: ${n.title||"Video Message"} ${C}`;try{const Z=new Blob([H],{type:"text/html"}),ne=new Blob([Y],{type:"text/plain"}),ce=new ClipboardItem({"text/html":Z,"text/plain":ne});await navigator.clipboard.write([ce]),se.success("Copied! Paste into Gmail - the thumbnail will appear after sending.")}catch{await navigator.clipboard.writeText(Y+` `+H),se.success("Copied! Paste into your email.")}},V=async()=>{await navigator.clipboard.writeText(C),u(!0),se.success("Share link copied!"),setTimeout(()=>u(!1),2e3)},G=()=>{const Y=k$(i).headerText(I),Z=i==="default"?`Check out this video: ${C}`:`${Y} Check out this special video: ${C}`;window.open(`sms:?body=${encodeURIComponent(Z)}`,"_self")},$=()=>{const H=k$(i),Y=H.headerText(I),Z=i==="default"?n.title||"Video Message":Y,ne=`${H.subText} Watch the video: ${C}`,ce=y!=null&&y.email?encodeURIComponent(y.email):"";window.open(`mailto:${ce}?subject=${encodeURIComponent(Z)}&body=${encodeURIComponent(ne)}`,"_self")};return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsxs(Ds,{className:"flex items-center gap-2",children:[e.jsx(Vc,{className:"h-5 w-5"}),"Share Video"]}),e.jsx(_r,{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(J,{className:"text-sm font-medium",children:"Personalize for Contact (Optional)"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(od,{open:g,onOpenChange:b,children:[e.jsx(ld,{asChild:!0,children:e.jsxs(B,{variant:"outline",role:"combobox","aria-expanded":g,className:"flex-1 justify-between",disabled:o,children:[y?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Fo,{className:"h-4 w-4 text-muted-foreground"}),y.name]}):e.jsx("span",{className:"text-muted-foreground",children:"Select a contact..."}),e.jsx(I_,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Qc,{className:"w-[300px] p-0",align:"start",children:e.jsxs(Aj,{children:[e.jsx(Ej,{placeholder:"Search contacts..."}),e.jsxs(Tj,{children:[e.jsx(Mj,{children:j?"Loading...":"No contacts found."}),e.jsx(V_,{children:p.map(H=>e.jsxs(d1,{value:H.name,onSelect:()=>P(H),children:[e.jsx(ea,{className:At("mr-2 h-4 w-4",(y==null?void 0:y.id)===H.id?"opacity-100":"opacity-0")}),H.name]},H.id))})]})]})})]}),y&&e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>P(null),disabled:o,className:"shrink-0",children:e.jsx(Qn,{className:"h-4 w-4"})})]}),y&&i!=="default"&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:['Page will show: "',k$(i).headerText(y.name),'"']})]}),e.jsx(sWn,{selectedTemplate:i,onSelect:M,contactName:I,saving:o}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Share Link"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{value:C,readOnly:!0,className:"font-mono text-sm"}),e.jsx(B,{onClick:V,variant:d?"default":"outline",className:"shrink-0 gap-2",children:d?e.jsxs(e.Fragment,{children:[e.jsx(ea,{className:"h-4 w-4"}),"Copied"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ia,{className:"h-4 w-4"}),"Copy"]})})]})]}),n.thumbnail_url&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Share for Email"}),e.jsxs(B,{variant:"outline",className:"w-full gap-2",onClick:O,children:[e.jsx(hc,{className:"h-4 w-4"}),"Copy with Thumbnail (for Gmail)"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Paste into Gmail to embed a clickable video thumbnail"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Quick Share"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{variant:"outline",className:"flex-1 gap-2",onClick:G,children:[e.jsx(Hi,{className:"h-4 w-4"}),"Text"]}),e.jsxs(B,{variant:"outline",className:"flex-1 gap-2",onClick:$,children:[e.jsx(ln,{className:"h-4 w-4"}),"Email"]})]})]})]}),e.jsx(yr,{children:e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Done"})})]})})}function nWn(){var Ve;const s=Fn(),[t]=Yl(),{toast:n}=vi(),r=t.get("contact_id"),a=t.get("task_id"),{canRecord:i,remainingMb:l,usagePercent:o,isNearLimit:c,storage:d}=CYt(),{data:u}=Db(),h=TC(),m=mRn(),[p,f]=_.useState("record"),[y,v]=_.useState(""),[g,b]=_.useState(!1),[j,S]=_.useState(!1),[C,E]=_.useState(!1),[P,M]=_.useState(null),[I,D]=_.useState(0),[O,V]=_.useState(0),[G,$]=_.useState(null),[H,Y]=_.useState(null),[Z,ne]=_.useState(r||""),[ce,ie]=_.useState(""),[te,ae]=_.useState(""),[le,be]=_.useState(null),[me,he]=_.useState(null),[pe,Ce]=_.useState(null),[Ae,Pe]=_.useState(!1),ze=_.useCallback(async(qe,Qe)=>{M(qe),f("uploading");try{const{videoId:Ue,uploadUrl:Xe}=await PL(ce||"Quick Video Touch");$(Ue);const{apiKey:nt}=await LL(Ue),$e=new XMLHttpRequest;$e.upload.onprogress=qt=>{qt.lengthComputable&&D(qt.loaded/qt.total*100)},await new Promise((qt,Vt)=>{$e.onload=()=>{$e.status>=200&&$e.status<300?qt():Vt(new Error(`Upload failed: ${$e.status}`))},$e.onerror=()=>Vt(new Error("Upload failed")),$e.open("PUT",Xe),$e.setRequestHeader("AccessKey",nt),$e.send(qe)}),f("processing");let Ge=0;const ct=Date.now(),xt=90*1e3;for(;Ge<4;){if(await new Promise(Vt=>setTimeout(Vt,3e3)),Date.now()-ct>xt){const Vt=qe.size/1048576,Xt=`https://iframe.mediadelivery.net/play/${Ue}/${Ue}`;await h.mutateAsync({bunny_video_id:Ue,playback_url:Xt,file_size_mb:Vt,title:ce||"Quick Video Touch",notes:te||void 0,contact_id:Z&&Z!=="none"?Z:void 0,status:"processing",touch_type:"video_touch"}),n({title:"Video saved — still processing",description:'Your video has been saved and will appear in your library with a "processing" badge. It will be ready to share once encoding completes (usually within a few minutes).',duration:8e3}),s("/mission-control/video-library");return}const qt=await TN(Ue);if(Ge=qt.status,V(qt.encodeProgress||0),Ge===4)Y({playbackUrl:qt.directPlayUrl,thumbnailUrl:qt.thumbnailUrl,previewUrl:qt.previewUrl||null,duration:qt.length||Qe,fileSizeMb:(qt.storageSize||qe.size)/(1024*1024)});else if(Ge===5||Ge===6)throw new Error("Video processing failed")}f("details")}catch(Ue){console.error("Upload error:",Ue),n({title:"Upload failed",description:"Please try recording again.",variant:"destructive"}),f("record")}},[ce,n]),ke=async()=>{if(!(!G||!H))try{const qe=Z&&Z!=="none"?Z:null,Qe=await h.mutateAsync({bunny_video_id:G,contact_id:qe,playback_url:H.playbackUrl,thumbnail_url:H.thumbnailUrl,preview_url:H.previewUrl,duration_seconds:H.duration,file_size_mb:H.fileSizeMb,title:ce||"Quick Video Touch",notes:te,task_id:a||null,status:"ready"});be(Qe.id),he(Qe.share_token||null),qe&&await m.mutateAsync({contactId:qe,videoId:Qe.id,notes:te}),n({title:"Video saved successfully!"}),f("share")}catch(qe){console.error("Save video error:",qe),n({title:"Failed to save video",description:(qe==null?void 0:qe.message)||"Please try again.",variant:"destructive"})}},Ze=(qe,Qe)=>{navigator.clipboard.writeText(Qe),Ce(qe),setTimeout(()=>Ce(null),2e3),n({title:"Copied to clipboard!"})},Se=()=>me?`https://video.relevelup.com/${me}`:(H==null?void 0:H.playbackUrl)||"",Fe=()=>{const qe=u==null?void 0:u.find($e=>$e.id===Z),Qe=qe?`${qe.first_name}`:"",Ue=(qe==null?void 0:qe.phone)||"",Xe=(qe==null?void 0:qe.email)||"",nt=Se();return{text:`Hey${Qe?` ${Qe}`:""}! I recorded a quick video for you: ${nt}`,link:nt,contactPhone:Ue,contactEmail:Xe}},Ne=()=>{const{text:qe,contactPhone:Qe}=Fe(),Ue=Qe?`sms:${Qe}?body=${encodeURIComponent(qe)}`:`sms:?body=${encodeURIComponent(qe)}`;window.open(Ue,"_self")},Ye=()=>{const{link:qe,contactEmail:Qe}=Fe(),Ue="Check out this video",Xe=`I recorded a quick video for you: ${qe}`,nt=Qe?`mailto:${Qe}?subject=${encodeURIComponent(Ue)}&body=${encodeURIComponent(Xe)}`:`mailto:?subject=${encodeURIComponent(Ue)}&body=${encodeURIComponent(Xe)}`;window.open(nt,"_self")};return i?e.jsx(zs,{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(B,{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(B,{variant:"outline",size:"sm",onClick:()=>s("/mission-control/video-library"),className:"gap-1.5",children:[e.jsx(Fr,{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($E,{maxDurationSeconds:600,onRecordingComplete:ze,onRecordingStateChange:E,className:"w-full",teleprompterContent:g&&y&&e.jsx(aat,{text:y,isVisible:g,onToggleVisibility:()=>b(!1),isRecording:C,startCountdown:!1})}),!g&&y&&e.jsxs(B,{variant:"outline",className:"mt-4",onClick:()=>b(!0),children:[e.jsx(Fr,{className:"h-4 w-4 mr-2"}),"Show Teleprompter"]})]}),e.jsxs(ve,{className:"lg:col-span-1",children:[e.jsx(bt,{className:"pb-2",children:e.jsx(St,{className:"text-lg",children:"Teleprompter Script"})}),e.jsxs(Me,{className:"space-y-4",children:[e.jsx(Ms,{placeholder:"Type or paste your script here...",value:y,onChange:qe=>v(qe.target.value),rows:6}),e.jsxs(qg,{open:j,onOpenChange:S,children:[e.jsx(zre,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:"w-full",children:[e.jsx(Fr,{className:"h-4 w-4 mr-2"}),"Browse Scripts"]})}),e.jsxs(hg,{side:"right",className:"w-[400px] sm:w-[540px] p-0",children:[e.jsx(P0,{className:"p-4 border-b",children:e.jsx(L0,{children:"Select a Script"})}),e.jsx(tWn,{onSelectScript:qe=>{v(qe.text),S(!1),b(!0)},className:"h-[calc(100vh-80px)]"})]})]}),y&&e.jsx(B,{className:"w-full",onClick:()=>b(!0),children:"Use Script"})]})]})]}),p==="uploading"&&e.jsx(ve,{className:"max-w-md mx-auto",children:e.jsxs(Me,{className:"pt-6 text-center",children:[e.jsx(Oa,{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(Fi,{value:I,className:"mb-2"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[I.toFixed(0),"%"]})]})}),p==="processing"&&e.jsx(ve,{className:"max-w-md mx-auto",children:e.jsxs(Me,{className:"pt-6 text-center space-y-4",children:[e.jsx(Ct,{className:"h-12 w-12 mx-auto mb-4 text-primary animate-spin"}),e.jsx("h2",{className:"text-lg font-semibold mb-2",children:"Processing Video..."}),e.jsx(Fi,{value:O,className:"mb-2"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[O.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(ve,{className:"max-w-lg mx-auto",children:[e.jsx(bt,{children:e.jsx(St,{children:"Video Details"})}),e.jsxs(Me,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Title"}),e.jsx(xe,{value:ce,onChange:qe=>ie(qe.target.value),placeholder:"Quick Video Touch"})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Attach to Contact (Optional)"}),e.jsxs(is,{value:Z,onValueChange:ne,children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"No contact - use anywhere"})}),e.jsxs(as,{children:[e.jsx(He,{value:"none",children:e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Vc,{className:"h-4 w-4"}),"No contact - use anywhere"]})}),u==null?void 0:u.map(qe=>e.jsx(He,{value:qe.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fo,{className:"h-4 w-4"}),qe.first_name," ",qe.last_name]})},qe.id))]})]})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Notes"}),e.jsx(Ms,{value:te,onChange:qe=>ae(qe.target.value),placeholder:"Add notes about this video...",rows:3})]}),e.jsxs(B,{className:"w-full",onClick:ke,disabled:h.isPending,children:[h.isPending&&e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),"Save Video"]})]})]}),p==="share"&&e.jsxs(ve,{className:"max-w-lg mx-auto",children:[e.jsx(bt,{children:e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(ea,{className:"h-5 w-5 text-green-500"}),"Video Saved!"]})}),e.jsxs(Me,{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(B,{variant:"outline",className:"justify-start",onClick:Ne,children:[e.jsx(Hi,{className:"h-4 w-4 mr-2"}),"Text Contact Video"]}),e.jsxs(B,{variant:"outline",className:"justify-start",onClick:Ye,children:[e.jsx(ln,{className:"h-4 w-4 mr-2"}),"Email Contact Video"]}),e.jsxs(B,{variant:"outline",className:"justify-start",onClick:()=>Ze("link",Fe().link),children:[e.jsx(Vc,{className:"h-4 w-4 mr-2"}),"Copy Video Link",pe==="link"&&e.jsx(ea,{className:"h-4 w-4 ml-auto text-green-500"})]}),e.jsxs(B,{variant:"outline",className:"justify-start",onClick:()=>Pe(!0),children:[e.jsx(Xc,{className:"h-4 w-4 mr-2"}),"Send with Page Template"]})]}),e.jsxs("div",{className:"flex gap-3 pt-4",children:[e.jsx(B,{variant:"outline",onClick:()=>s("/mission-control/video-library"),children:"View Library"}),e.jsx(B,{onClick:()=>{f("record"),M(null),$(null),Y(null)},children:"Record Another"})]})]})]}),le&&me&&e.jsx(Qts,{open:Ae,onOpenChange:Pe,video:{id:le,share_token:me,title:ce||null,contact_id:Z||null,thumbnail_url:(H==null?void 0:H.thumbnailUrl)||null},contactName:((Ve=u==null?void 0:u.find(qe=>qe.id===Z))==null?void 0:Ve.first_name)||null})]})}):e.jsx(zs,{title:"QuickVid",children:e.jsxs("div",{className:"max-w-2xl mx-auto text-center py-12",children:[e.jsx(xl,{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(B,{onClick:()=>s("/mission-control/video-library"),children:"Open Video Library"})]})})}function rWn({open:s,onOpenChange:t,video:n,gmailEmail:r,signedThumbnailUrl:a,onSendComplete:i}){const[l,o]=_.useState([]),[c,d]=_.useState(null),[u,h]=_.useState(!1),[m,p]=_.useState(!1),[f,y]=_.useState(""),[v,g]=_.useState(""),[b,j]=_.useState(""),[S,C]=_.useState(!1),E=wYt(),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";_.useEffect(()=>{s&&l.length===0&&D()},[s]),_.useEffect(()=>{if(s&&(g(`I recorded a video for you — ${I}`),j("Hey! I recorded a quick video just for you. Click below to watch it:"),d(null),y(""),n.contact_id)){const Y=l.find(Z=>Z.id===n.contact_id);Y&&(d(Y),y(Y.email||""))}},[s,n.contact_id,l]);const D=async()=>{p(!0);try{const{data:Y,error:Z}=await q.from("innercircle_contacts").select("id, first_name, last_name, email").order("first_name",{ascending:!0}).limit(500);if(Z)throw Z;o(Y||[])}catch{console.error("Failed to fetch contacts")}finally{p(!1)}},O=Y=>{d(Y),h(!1),y(Y.email||""),j(`Hey ${Y.first_name}! I recorded a quick video just for you. Click below to watch it:`),g(`I recorded a video for you — ${I}`)},V=()=>{d(null),y(""),j("Hey! I recorded a quick video just for you. Click below to watch it:")},G=Y=>{const Z=`${Y.first_name||""} ${Y.last_name||""}`.replace(/<[^>]*>/g," ").replace(/\s+/g," ").trim();return Z?Z.length>60?`${Z.slice(0,60)}…`:Z:Y.email||"Unnamed contact"},$=Y=>{const Z=b.split(/\n\n+/).map(ie=>`

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

`).join(""),ne=Y?NYt(Y):P,ce=Y?``:"";return`
${Z}

▶ Watch Video

${ce}
`},H=async()=>{var Y;if(!f){se.error("Please enter a recipient email");return}if(!P){se.error("Video does not have a share link");return}C(!0);try{let Z;try{const ae=c?G(c):f.split("@")[0];Z=(await E.mutateAsync({video_id:n.id,recipient_email:f,recipient_name:ae,contact_id:(c==null?void 0:c.id)||null,sent_via:"gmail"})).share_token}catch(ae){console.warn("Failed to create tracking record, sending without tracking:",ae)}const ne=$(Z),{data:ce,error:ie}=await q.functions.invoke("gmail-send",{body:{to:f,subject:v,body:ne,contactId:(c==null?void 0:c.id)||null}});let te=null;if(ie&&((Y=ie.context)!=null&&Y.json))try{te=await ie.context.json()}catch{}if((te==null?void 0:te.error)==="insufficient_scope"||(ce==null?void 0:ce.error)==="insufficient_scope"){se.error((te==null?void 0:te.message)||"Gmail is missing send permission. Please disconnect and reconnect Gmail, allowing 'Send email on your behalf'.",{duration:1e4});return}if(ie)throw new Error((te==null?void 0:te.message)||ie.message);if(!(ce!=null&&ce.success))throw new Error((ce==null?void 0:ce.error)||"Failed to send");se.success("Video email sent!"),t(!1),i==null||i()}catch(Z){console.error("Gmail send error:",Z),se.error("Failed to send: "+(Z instanceof Error?Z.message:"Unknown error"))}finally{C(!1)}};return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"sm:max-w-[560px] max-h-[90vh] overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsxs(Ds,{className:"flex items-center gap-2",children:[e.jsx(ln,{className:"h-5 w-5 text-red-500"}),"Send Video via Gmail"]}),r&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Sending from ",e.jsx("span",{className:"font-medium",children:r})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Send to Contact"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(od,{open:u,onOpenChange:h,children:[e.jsx(ld,{asChild:!0,children:e.jsxs(B,{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(Fo,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:G(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(I_,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Qc,{className:"w-[350px] p-0",align:"start",children:e.jsxs(Aj,{children:[e.jsx(Ej,{placeholder:"Search contacts..."}),e.jsxs(Tj,{children:[e.jsx(Mj,{children:m?"Loading...":"No contacts found."}),e.jsx(V_,{children:l.filter(Y=>Y.email).map(Y=>e.jsxs(d1,{value:`${G(Y)} ${Y.email||""}`,onSelect:()=>O(Y),children:[e.jsx(ea,{className:At("mr-2 h-4 w-4",(c==null?void 0:c.id)===Y.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-medium truncate",children:G(Y)}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:Y.email})]})]},Y.id))})]})]})})]}),c&&e.jsx(B,{variant:"ghost",size:"icon",onClick:V,className:"shrink-0",children:e.jsx(Qn,{className:"h-4 w-4"})})]})]}),!c&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{htmlFor:"video-to",children:"Or type email address"}),e.jsx(xe,{id:"video-to",value:f,onChange:Y=>y(Y.target.value),placeholder:"recipient@example.com",type:"email"})]}),e.jsx(wc,{}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{htmlFor:"video-subject",children:"Subject"}),e.jsx(xe,{id:"video-subject",value:v,onChange:Y=>g(Y.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{htmlFor:"video-message",children:"Personal Message"}),e.jsx(Ms,{id:"video-message",value:b,onChange:Y=>j(Y.target.value),rows:4,className:"resize-y"})]}),e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3 space-y-2",children:[e.jsx(J,{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(Jd,{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(Jd,{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(B,{variant:"outline",onClick:()=>t(!1),disabled:S,children:"Cancel"}),e.jsxs(B,{onClick:H,disabled:S||!f||!v,className:"gap-2",children:[S?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Or,{className:"h-4 w-4"}),S?"Sending...":"Send Video Email"]})]})]})]})})}const aWn=()=>{const{user:s}=hs();return at({queryKey:["team-videos",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.rpc("get_team_videos",{_user_id:s.id});if(n)throw n;return t||[]},enabled:!!s})};function iWn({recipient:s}){return s.watched_at?e.jsxs(Oe,{className:"bg-emerald-100 text-emerald-800 text-[10px]",children:[e.jsx(Jd,{className:"h-2.5 w-2.5 mr-0.5"}),"Watched"]}):s.clicked_at?e.jsxs(Oe,{className:"bg-blue-100 text-blue-800 text-[10px]",children:[e.jsx(v0,{className:"h-2.5 w-2.5 mr-0.5"}),"Clicked"]}):s.opened_at?e.jsxs(Oe,{className:"bg-amber-100 text-amber-800 text-[10px]",children:[e.jsx(ya,{className:"h-2.5 w-2.5 mr-0.5"}),"Opened"]}):e.jsxs(Oe,{variant:"outline",className:"text-[10px]",children:[e.jsx(Or,{className:"h-2.5 w-2.5 mr-0.5"}),"Sent"]})}function oWn({open:s,onOpenChange:t,videoId:n,videoTitle:r}){const{data:a=[],isLoading:i}=qDn(n);return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"max-w-2xl max-h-[80vh]",children:[e.jsx(Os,{children:e.jsxs(Ds,{className:"flex items-center gap-2",children:[e.jsx(bl,{className:"h-5 w-5"}),"Send Analytics: ",r]})}),i?e.jsx("div",{className:"space-y-2",children:[...Array(3)].map((l,o)=>e.jsx(cn,{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(Ji,{className:"h-[400px]",children:e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"Recipient"}),e.jsx(Pt,{children:"Status"}),e.jsx(Pt,{children:"Sent"}),e.jsx(Pt,{children:"Last Activity"})]})}),e.jsx(Ka,{children:a.map(l=>e.jsxs(pn,{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(iWn,{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?Ed(new Date(l.last_activity_at),{addSuffix:!0}):"—"})]},l.id))})]})})]})]})})}function lWn(){const{data:s,isLoading:t}=$Dn(),{data:n=[],isLoading:r}=VDn(),[a,i]=_.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(ve,{children:[e.jsx(bt,{className:"pb-2",children:e.jsx(cn,{className:"h-4 w-20"})}),e.jsx(Me,{children:e.jsx(cn,{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(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(St,{className:"text-sm font-medium",children:"Total Sent"}),e.jsx(Or,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Me,{children:e.jsx("div",{className:"text-2xl font-bold",children:(s==null?void 0:s.totalSent)||0})})]}),e.jsxs(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(St,{className:"text-sm font-medium",children:"Open Rate"}),e.jsx(ya,{className:"h-4 w-4 text-amber-500"})]}),e.jsxs(Me,{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(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(St,{className:"text-sm font-medium",children:"Click Rate"}),e.jsx(v0,{className:"h-4 w-4 text-blue-500"})]}),e.jsxs(Me,{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(ve,{children:[e.jsxs(bt,{children:[e.jsx(St,{className:"text-sm font-medium",children:"Send History by Video"}),e.jsx(kn,{children:"Click a video to see individual recipient tracking"})]}),e.jsx(Me,{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(Kr,{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(Or,{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(ya,{className:"h-3 w-3"})," ",d]}),e.jsxs("span",{className:"text-xs text-blue-600 flex items-center gap-1",children:[e.jsx(v0,{className:"h-3 w-3"})," ",u]})]})]}),e.jsx(Nl,{className:"h-4 w-4 text-muted-foreground"})]},c.videoId)})})})]}),e.jsx(oWn,{open:!!a,onOpenChange:c=>!c&&i(null),videoId:(a==null?void 0:a.id)||null,videoTitle:(a==null?void 0:a.title)||""})]})}function cWn({previewSrc:s,thumbnailSrc:t,alt:n,isHovered:r}){const[a,i]=_.useState(!1),[l,o]=_.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(Kr,{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 dWn({video:s,previewSrc:t,thumbnailSrc:n,onOpen:r,onDelete:a,onRename:i,onNavigateToContact:l,onGetEmbedCode:o,onCopyEmailHtml:c,onEmbedToCrm:d,onShareWithTemplate:u,onSendViaGmail:h,isGmailConnected:m,getContactName:p,getShareUrl:f,copyToClipboard:y,formatDuration:v}){const[g,b]=_.useState(!1);return e.jsxs(ve,{className:"overflow-hidden group cursor-pointer",onClick:r,onMouseEnter:()=>b(!0),onMouseLeave:()=>b(!1),children:[e.jsxs("div",{className:"relative aspect-video bg-muted overflow-hidden",children:[e.jsx(cWn,{previewSrc:t,thumbnailSrc:n,alt:s.title||"Video preview",isHovered:g}),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(Jd,{className:"h-6 w-6 text-primary ml-1"})})}),e.jsx("div",{className:"absolute bottom-2 right-2 bg-black/70 text-white text-xs px-1.5 py-0.5 rounded",children:v(s.duration_seconds)}),s.status!=="ready"&&e.jsx(Oe,{variant:s.status==="processing"?"secondary":"destructive",className:"absolute top-2 left-2",children:s.status})]}),e.jsx(Me,{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(Fo,{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(Gr,{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(ya,{className:"h-3 w-3"}),e.jsxs("span",{children:[s.view_count," ",s.view_count===1?"view":"views"]})]})]}),m&&s.share_token&&e.jsxs(B,{variant:"outline",size:"sm",className:"mt-2 gap-1.5 text-xs h-7",onClick:j=>{j.stopPropagation(),h==null||h()},children:[e.jsx(ln,{className:"h-3 w-3"}),"Send via Gmail"]}),e.jsx("h3",{className:"font-medium truncate",children:s.title||"Untitled Video"}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground mt-1",children:[e.jsx(Fo,{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(Gr,{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(ya,{className:"h-3 w-3"}),e.jsxs("span",{children:[s.view_count," ",s.view_count===1?"view":"views"]})]})]})]}),e.jsxs(tu,{children:[e.jsx(su,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:j=>j.stopPropagation(),children:e.jsx(Xx,{className:"h-4 w-4"})})}),e.jsxs(Od,{align:"end",className:"bg-popover",children:[e.jsxs(ca,{onClick:j=>{j.stopPropagation(),r()},children:[e.jsx(ya,{className:"h-4 w-4 mr-2"}),"Watch"]}),e.jsx(M0,{}),e.jsxs(ca,{onClick:j=>{j.stopPropagation(),u()},children:[e.jsx(Xc,{className:"h-4 w-4 mr-2"}),"Share with Template"]}),e.jsxs(ca,{onClick:j=>{j.stopPropagation(),y(f(s),"Share link")},children:[e.jsx(Vc,{className:"h-4 w-4 mr-2"}),"Copy Share Link"]}),e.jsxs(ca,{onClick:j=>{j.stopPropagation(),o()},children:[e.jsx(UA,{className:"h-4 w-4 mr-2"}),"Get Embed Code"]}),e.jsxs(ca,{onClick:j=>{j.stopPropagation(),c()},children:[e.jsx(ln,{className:"h-4 w-4 mr-2"}),"Copy HTML for Email"]}),e.jsxs(ca,{onClick:j=>{j.stopPropagation(),d()},children:[e.jsx(wr,{className:"h-4 w-4 mr-2"}),"Embed to CRM"]}),m&&s.share_token&&e.jsxs(ca,{onClick:j=>{j.stopPropagation(),h==null||h()},children:[e.jsx(Or,{className:"h-4 w-4 mr-2"}),"Send via Gmail"]}),e.jsxs(ca,{onClick:j=>{j.stopPropagation(),i()},children:[e.jsx(Ya,{className:"h-4 w-4 mr-2"}),"Rename"]}),e.jsx(M0,{}),s.contact_id&&e.jsxs(ca,{onClick:j=>{j.stopPropagation(),l()},children:[e.jsx(Fo,{className:"h-4 w-4 mr-2"}),"View Contact"]}),e.jsxs(ca,{onClick:j=>{j.stopPropagation(),a()},className:"text-destructive",children:[e.jsx(Sn,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})]})})]})}function uWn(){var Xt,fs;const s=Fn(),{data:t,isLoading:n,refetch:r}=cRn(),{data:a}=XIe(),{data:i}=Db(),l=hRn(),o=uRn(),{isGmailConnected:c,gmailEmail:d}=Vg(),{data:u}=G_(),{data:h=[],isLoading:m}=aWn(),[p,f]=_.useState("my"),[y,v]=_.useState(""),[g,b]=_.useState(null),[j,S]=_.useState(!1),[C,E]=_.useState(!1),[P,M]=_.useState(!1),[I,D]=_.useState(!1),[O,V]=_.useState(!1),[G,$]=_.useState(""),[H,Y]=_.useState(!1),[Z,ne]=_.useState(!1),[ce,ie]=_.useState(!1),[te,ae]=_.useState(!1),[le,be]=_.useState(""),[me,he]=_.useState({}),pe=Ft=>{if(!Ft)return"Unassigned";const wt=i==null?void 0:i.find(Ts=>Ts.id===Ft);return wt?`${wt.first_name} ${wt.last_name||""}`.trim():"Unknown"},Ce=Ft=>{if(!Ft)return"0:00";const wt=Math.floor(Ft/60),Ts=Ft%60;return`${wt}:${Ts.toString().padStart(2,"0")}`},[Ae,Pe]=_.useState("all"),ze=t==null?void 0:t.filter(Ft=>{const wt=Ft.category||"general";if(Ae==="general"&&wt!=="general"||Ae==="open_house"&&wt!=="open_house")return!1;if(!y)return!0;const Ts=pe(Ft.contact_id).toLowerCase(),vt=(Ft.title||"").toLowerCase(),$s=(Ft.notes||"").toLowerCase();return Ts.includes(y.toLowerCase())||vt.includes(y.toLowerCase())||$s.includes(y.toLowerCase())}),ke=(t==null?void 0:t.filter(Ft=>(Ft.category||"general")==="open_house").length)||0,Ze=(t==null?void 0:t.filter(Ft=>(Ft.category||"general")==="general").length)||0,Se=(t||[]).filter(Ft=>Ft.status==="processing"&&Ft.bunny_video_id).map(Ft=>Ft.id).join(",");_.useEffect(()=>{(async()=>{if(!(t!=null&&t.length))return;const wt=t.filter(vt=>vt.status==="processing"&&vt.bunny_video_id);if(!wt.length)return;let Ts=!1;for(const vt of wt)try{const{data:$s,error:As}=await q.functions.invoke("bunny-upload",{body:{action:"status",videoId:vt.bunny_video_id,isAgentVideo:!0}});if(As||!$s)continue;$s.status===4&&(await q.from("agent_videos").update({status:"ready",playback_url:$s.directPlayUrl,thumbnail_url:$s.thumbnailUrl,preview_url:$s.previewUrl,duration_seconds:$s.length||vt.duration_seconds,updated_at:new Date().toISOString()}).eq("id",vt.id),Ts=!0)}catch($s){console.warn("Reconcile check failed for video",vt.id,$s)}Ts&&r()})()},[Se,r]),_.useEffect(()=>{(async()=>{if(!(t!=null&&t.length))return;const wt=t.filter(jn=>(jn==null?void 0:jn.bunny_video_id)&&!me[jn.id]);if(!wt.length)return;const Ts=wt.map(jn=>jn.bunny_video_id),{data:vt,error:$s}=await q.functions.invoke("bunny-upload",{body:{action:"bulk-asset-urls",videoIds:Ts,isAgentVideo:!0}});if($s)throw $s;const As=(vt==null?void 0:vt.assets)||{};he(jn=>{const ar={...jn};for(const Dn of wt)As[Dn.bunny_video_id]&&(ar[Dn.id]={previewUrl:As[Dn.bunny_video_id].previewUrl,thumbnailUrl:As[Dn.bunny_video_id].thumbnailUrl});return ar})})().catch(wt=>console.warn("Failed to load signed Bunny asset URLs",wt))},[t,me]);const Fe=(a==null?void 0:a.total_storage_mb)||0,Ne=(a==null?void 0:a.max_storage_mb)||1024,Ye=Fe/Ne*100,Ve=Ye>=80,qe=Ye>=100,Qe=async(Ft,wt)=>{await navigator.clipboard.writeText(Ft),se.success(`${wt} copied to clipboard`)},Ue=Ft=>Ft.share_token?`https://video.relevelup.com/${Ft.share_token}`:Ft.playback_url||"",Xe=Ft=>{const wt=Ue(Ft),Ts=i==null?void 0:i.find(Dn=>Dn.id===Ft.contact_id),vt=pe(Ft.contact_id),$s=vt!=="Unassigned"?vt.split(" ")[0]:"",As=(Ts==null?void 0:Ts.phone)||"",jn=`Hey${$s?` ${$s}`:""}! I recorded a quick video message for you. Check it out: ${wt}`,ar=As?`sms:${As}?body=${encodeURIComponent(jn)}`:`sms:?body=${encodeURIComponent(jn)}`;window.open(ar,"_self")},nt=Ft=>{const wt=i==null?void 0:i.find(ar=>ar.id===Ft.contact_id),Ts=(wt==null?void 0:wt.email)||"",vt=Ue(Ft),$s="Check out this video",As=`I recorded a quick video for you: ${vt}`,jn=Ts?`mailto:${Ts}?subject=${encodeURIComponent($s)}&body=${encodeURIComponent(As)}`:`mailto:?subject=${encodeURIComponent($s)}&body=${encodeURIComponent(As)}`;window.open(jn,"_self")},$e=Ft=>{var $s;const wt=Ue(Ft),Ts=Ft.title||"Video Message",vt=Ft.share_token?`https://video.relevelup.com/thumb/${Ft.share_token}`:(($s=me[Ft.id])==null?void 0:$s.thumbnailUrl)||Ft.thumbnail_url||"";return``},Ge=async Ft=>{if(!Ft.thumbnail_url&&!Ft.share_token){se.error("Video thumbnail not available yet");return}const wt=$e(Ft),Ts=Ue(Ft),vt=`Watch: ${Ft.title||"Video Message"} ${Ts}`;try{const $s=new Blob([wt],{type:"text/html"}),As=new Blob([vt],{type:"text/plain"}),jn=new ClipboardItem({"text/html":$s,"text/plain":As});await navigator.clipboard.write([jn]),se.success("Copied! Paste into Gmail - the thumbnail will appear after sending.")}catch{await navigator.clipboard.writeText(vt+` `+wt),se.success("Copied! Paste into your email.")}},ct=async Ft=>{try{se.loading("Preparing download...",{id:"download"});const{data:wt,error:Ts}=await q.functions.invoke("bunny-upload",{body:{action:"download-url",videoId:Ft.bunny_video_id,isAgentVideo:!0}});if(Ts||!(wt!=null&&wt.downloadUrl))throw new Error((Ts==null?void 0:Ts.message)||"Failed to get download URL");const $s=`${((Ft.title||"video").toString().trim()||"video").replace(/[\\/:*?"<>|]+/g,"-")}.mp4`,As=await fetch(wt.downloadUrl);if(!As.ok)throw new Error("Failed to fetch video file");const jn=await As.blob(),ar=URL.createObjectURL(jn),Dn=document.createElement("a");Dn.href=ar,Dn.download=$s,Dn.rel="noreferrer",document.body.appendChild(Dn),Dn.click(),Dn.remove(),URL.revokeObjectURL(ar),se.success("Download started",{id:"download"})}catch(wt){console.error("Download error:",wt),se.error("Could not force download (your browser may block it).",{id:"download"})}},xt=async Ft=>{b(Ft),Y(!0),$(""),V(!0);try{const{data:wt,error:Ts}=await q.functions.invoke("bunny-upload",{body:{action:"crm-embed",videoId:Ft.bunny_video_id,title:Ft.title,isAgentVideo:!0,shareToken:Ft.share_token}});if(Ts||!(wt!=null&&wt.html))throw new Error("Failed to generate CRM embed code");$(wt.html)}catch(wt){console.error("CRM embed error:",wt),se.error("Failed to generate CRM embed code"),V(!1)}finally{Y(!1)}},qt=Ft=>{b(Ft),S(!0)},Vt=async()=>{if(g)try{await l.mutateAsync({id:g.id,bunnyVideoId:g.bunny_video_id,hardDelete:!0}),E(!1),b(null),se.success("Video deleted successfully")}catch{se.error("Failed to delete video")}};return e.jsx(zs,{title:"Video Library",description:"Manage your video touches",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Video Library"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage and share your video touches"})]}),e.jsxs("div",{className:"flex bg-muted rounded-lg p-1 gap-0.5 ml-2",children:[e.jsx("button",{onClick:()=>f("my"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors ${p==="my"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:"My Videos"}),u&&((Xt=u.team)==null?void 0:Xt.shared_videos_enabled)&&e.jsxs("button",{onClick:()=>f("team"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors flex items-center gap-1.5 ${p==="team"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(In,{className:"h-3.5 w-3.5"}),"Team"]}),e.jsxs("button",{onClick:()=>f("analytics"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors flex items-center gap-1.5 ${p==="analytics"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(bl,{className:"h-3.5 w-3.5"}),"Analytics"]})]})]}),p==="my"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{variant:"outline",onClick:()=>M(!0),children:[e.jsx(Oa,{className:"h-4 w-4 mr-2"}),"Upload Video"]}),e.jsxs(B,{onClick:()=>s("/mission-control/video/record"),children:[e.jsx(rn,{className:"h-4 w-4 mr-2"}),"Record New Video"]})]})]}),p==="team"?e.jsx(hWn,{videos:h,isLoading:m,searchTerm:y,setSearchTerm:v}):p==="analytics"?e.jsx(lWn,{}):e.jsxs(e.Fragment,{children:[e.jsx(ve,{className:Ve?"border-amber-500":qe?"border-destructive":"",children:e.jsxs(Me,{className:"py-4",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(IQ,{className:`h-5 w-5 ${qe?"text-destructive":Ve?"text-amber-500":"text-muted-foreground"}`}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("span",{className:"text-sm font-medium",children:"Storage Used"}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:[Fe.toFixed(1)," MB / ",Ne>=1024?`${(Ne/1024).toFixed(0)} GB`:`${Ne} MB`]})]}),e.jsx(Fi,{value:Math.min(Ye,100),className:`h-2 ${qe?"[&>div]:bg-destructive":Ve?"[&>div]:bg-amber-500":""}`})]}),Ve&&!qe&&e.jsxs(Oe,{variant:"outline",className:"border-amber-500 text-amber-600",children:[e.jsx(Xo,{className:"h-3 w-3 mr-1"}),"Near Limit"]}),qe&&e.jsxs(Oe,{variant:"destructive",children:[e.jsx(Xo,{className:"h-3 w-3 mr-1"}),"At Limit"]})]}),qe&&e.jsx("p",{className:"text-sm text-destructive mt-2",children:"You've reached your storage limit. Delete videos to record more."})]})}),e.jsx("div",{className:"flex gap-1 p-1 bg-muted rounded-lg w-fit",children:[{id:"all",label:"All",count:(t||[]).length},{id:"general",label:"My Videos",count:Ze},{id:"open_house",label:"Open House Tours",count:ke}].map(Ft=>e.jsxs("button",{onClick:()=>Pe(Ft.id),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors ${Ae===Ft.id?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[Ft.label," ",e.jsx("span",{className:"ml-1 text-xs text-muted-foreground",children:Ft.count})]},Ft.id))}),e.jsxs("div",{className:"relative",children:[e.jsx(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search videos by contact, title, or notes...",value:y,onChange:Ft=>v(Ft.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(ve,{children:e.jsxs(Me,{className:"py-12 text-center",children:[e.jsx(Kr,{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(B,{onClick:()=>s("/mission-control/video/record"),children:[e.jsx(rn,{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(Ft=>{var wt,Ts;return e.jsx(dWn,{video:Ft,previewSrc:(wt=me[Ft.id])==null?void 0:wt.previewUrl,thumbnailSrc:(Ts=me[Ft.id])==null?void 0:Ts.thumbnailUrl,onOpen:()=>qt(Ft),onDelete:()=>{b(Ft),E(!0)},onRename:()=>{b(Ft),be(Ft.title||""),ae(!0)},onNavigateToContact:()=>s(`/mission-control/contacts/${Ft.contact_id}`),onGetEmbedCode:()=>{b(Ft),D(!0)},onCopyEmailHtml:()=>Ge(Ft),onEmbedToCrm:()=>xt(Ft),onShareWithTemplate:()=>{b(Ft),ne(!0)},onSendViaGmail:()=>{b(Ft),ie(!0)},isGmailConnected:c,getContactName:pe,getShareUrl:Ue,copyToClipboard:Qe,formatDuration:Ce},Ft.id)})}),e.jsx(Ls,{open:j,onOpenChange:S,children:e.jsxs(Ps,{className:"max-w-2xl",children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:(g==null?void 0:g.title)||"Video Preview"}),e.jsx(_r,{children:(g==null?void 0:g.contact_id)&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Fo,{className:"h-3 w-3"}),pe(g.contact_id)]})})]}),g&&e.jsxs("div",{className:"space-y-4",children:[g.status==="processing"?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 px-6 bg-muted/50 rounded-lg border border-dashed border-border text-center space-y-4",children:[e.jsx("div",{className:"relative",children:e.jsx("div",{className:"h-16 w-16 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx(Ct,{className:"h-8 w-8 text-primary animate-spin"})})}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"font-semibold text-lg",children:"Video is still processing"}),e.jsx("p",{className:"text-muted-foreground text-sm max-w-sm",children:"Your video is being encoded and will be ready shortly. This usually takes 1–3 minutes. Check back soon!"})]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>{S(!1),r()},children:[e.jsx(uo,{className:"h-4 w-4 mr-2"}),"Refresh Library"]})]}):e.jsx("div",{className:"relative w-full",style:{paddingBottom:"56.25%"},children:g.playback_url?(()=>{let Ft=g.playback_url;return Ft.includes("iframe.mediadelivery.net/play/")&&(Ft=Ft.replace("/play/","/embed/"),Ft+=(Ft.includes("?")?"&":"?")+"autoplay=false&responsive=true"),Ft.includes("iframe.mediadelivery.net")?e.jsx("iframe",{src:Ft,title:g.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:g.playback_url,controls:!0,playsInline:!0,preload:"metadata",poster:g.thumbnail_url||void 0,className:"absolute top-0 left-0 w-full h-full rounded-lg object-cover",onError:()=>se.error("Video preview failed to load")},g.playback_url)})():e.jsxs("div",{className:"absolute inset-0 flex items-center justify-center bg-muted rounded-lg",children:[e.jsx(Kr,{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(B,{variant:"outline",onClick:()=>Xe(g),children:[e.jsx(Hi,{className:"h-4 w-4 mr-2"}),"Text Contact Video"]}),!c&&e.jsxs(B,{variant:"outline",onClick:()=>nt(g),children:[e.jsx(ln,{className:"h-4 w-4 mr-2"}),"Email Contact Video"]}),e.jsxs(B,{variant:"outline",onClick:()=>Qe(Ue(g),"Share link"),children:[e.jsx(Ia,{className:"h-4 w-4 mr-2"}),"Copy Share Link"]}),e.jsxs(B,{variant:"outline",onClick:()=>Ge(g),children:[e.jsx(ln,{className:"h-4 w-4 mr-2"}),"Copy HTML for Email"]}),e.jsxs(B,{variant:"outline",onClick:()=>ct(g),children:[e.jsx(li,{className:"h-4 w-4 mr-2"}),"Download Video"]}),e.jsxs(B,{variant:"outline",onClick:()=>{S(!1),xt(g)},children:[e.jsx(wr,{className:"h-4 w-4 mr-2"}),"Embed to CRM"]}),e.jsxs(B,{variant:"outline",onClick:()=>{S(!1),ne(!0)},children:[e.jsx(Xc,{className:"h-4 w-4 mr-2"}),"Send with Page Template"]}),c&&(g==null?void 0:g.share_token)&&e.jsxs(B,{variant:"outline",onClick:()=>{S(!1),ie(!0)},children:[e.jsx(Or,{className:"h-4 w-4 mr-2"}),"Send via Gmail"]})]}),e.jsx("div",{className:"flex justify-end pt-2 border-t",children:e.jsxs(B,{variant:"destructive",onClick:()=>{S(!1),E(!0)},children:[e.jsx(Sn,{className:"h-4 w-4 mr-2"}),"Delete Video"]})})]})]})}),e.jsx(Ls,{open:C,onOpenChange:E,children:e.jsxs(Ps,{children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Delete Video"}),e.jsx(_r,{children:"Are you sure you want to delete this video? This action cannot be undone."})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>E(!1),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:Vt,disabled:l.isPending,children:l.isPending?"Deleting...":"Delete"})]})]})}),e.jsx(AYt,{open:P,onOpenChange:M}),e.jsx(Ls,{open:I,onOpenChange:D,children:e.jsxs(Ps,{className:"sm:max-w-lg",children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Embed Video"}),e.jsx(_r,{children:"Copy this code to embed the video on your website."})]}),g&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Embed Code"}),e.jsx(Ms,{readOnly:!0,rows:5,value:``,className:"font-mono text-xs"})]}),e.jsx("div",{className:"flex gap-2",children:e.jsxs(B,{className:"flex-1",onClick:()=>{const Ft=``;Qe(Ft,"Embed code")},children:[e.jsx(Ia,{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."})]})]})}),g&&e.jsx(Qts,{open:Z,onOpenChange:ne,video:g,contactName:pe(g.contact_id)}),g&&e.jsx(rWn,{open:ce,onOpenChange:ie,video:g,gmailEmail:d,signedThumbnailUrl:(fs=me[g.id])==null?void 0:fs.thumbnailUrl}),e.jsx(Ls,{open:te,onOpenChange:ae,children:e.jsxs(Ps,{className:"max-w-sm",children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Rename Video"}),e.jsx(_r,{children:"Enter a new title for this video."})]}),e.jsx(xe,{value:le,onChange:Ft=>be(Ft.target.value),placeholder:"Video title",autoFocus:!0,onKeyDown:Ft=>{Ft.key==="Enter"&&le.trim()&&o.mutate({id:g.id,title:le.trim()},{onSuccess:()=>{se.success("Video renamed"),ae(!1)}})}}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>ae(!1),children:"Cancel"}),e.jsx(B,{disabled:!le.trim()||o.isPending,onClick:()=>{o.mutate({id:g.id,title:le.trim()},{onSuccess:()=>{se.success("Video renamed"),ae(!1)}})},children:o.isPending?"Saving...":"Save"})]})]})}),e.jsx(Ls,{open:O,onOpenChange:V,children:e.jsxs(Ps,{className:"sm:max-w-lg",children:[e.jsxs(Os,{children:[e.jsxs(Ds,{className:"flex items-center gap-2",children:[e.jsx(wr,{className:"h-5 w-5"}),"Embed to CRM"]}),e.jsx(_r,{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."})]}),H?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Ct,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):G?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"CRM Email HTML"}),e.jsx(Ms,{readOnly:!0,rows:12,value:G,className:"font-mono text-xs"})]}),e.jsxs(B,{className:"w-full",onClick:()=>{Qe(G,"CRM embed code")},children:[e.jsx(Ia,{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 hWn({videos:s,isLoading:t,searchTerm:n,setSearchTerm:r}){const a=_.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=_.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(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search team videos by title, owner, or recipient...",value:n,onChange:o=>r(o.target.value),className:"pl-10"})]}),t?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full"})}):a.length===0?e.jsx(ve,{children:e.jsxs(Me,{className:"py-12 text-center",children:[e.jsx(In,{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(ja,{className:"h-7 w-7",children:[e.jsx(pi,{src:c.avatar||""}),e.jsx(Na,{children:(c.name||"?").charAt(0).toUpperCase()})]}),e.jsx("h3",{className:"font-semibold text-sm",children:c.name}),e.jsx(Oe,{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(ve,{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(Kr,{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(Me,{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(Fo,{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(ya,{className:"h-3 w-3"}),d.view_count]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Gr,{className:"h-3 w-3"}),Hs(new Date(d.created_at),"MMM d")]})]})]})]},d.id))})]},o))})]})}const mWn=()=>{const{user:s}=hs();return at({queryKey:["team-deals",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.rpc("get_team_deals",{_user_id:s.id});if(n)throw n;return t||[]},enabled:!!s})},MSt=["#8B5CF6","#EC4899","#F59E0B","#10B981","#3B82F6","#EF4444","#06B6D4","#F97316"];function pWn({open:s,onOpenChange:t}){const{data:n,isLoading:r}=mWn(),[a,i]=_.useState(""),[l,o]=_.useState("all"),c=_.useMemo(()=>{if(!n)return new Map;const f=new Map;let y=0;return n.forEach(v=>{f.has(v.owner_user_id)||(f.set(v.owner_user_id,{name:v.owner_name||"Unknown",avatar:v.owner_avatar_url,color:MSt[y%MSt.length]}),y++)}),f},[n]),d=_.useMemo(()=>Array.from(c.entries()).map(([f,y])=>({id:f,...y})),[c]),u=_.useMemo(()=>{if(!n)return[];let f=n;if(l!=="all"&&(f=f.filter(y=>y.owner_user_id===l)),a.trim()){const y=a.toLowerCase();f=f.filter(v=>{var g,b,j,S;return v.deal_name.toLowerCase().includes(y)||((g=v.contact_name)==null?void 0:g.toLowerCase().includes(y))||((b=v.property_address)==null?void 0:b.toLowerCase().includes(y))||((j=v.city)==null?void 0:j.toLowerCase().includes(y))||((S=v.owner_name)==null?void 0:S.toLowerCase().includes(y))})}return f},[n,a,l]),h=_.useMemo(()=>{const f=new Map;return u.forEach(y=>{const v=y.stage_name||"Unknown";f.has(v)||f.set(v,{name:v,color:y.stage_color,icon:y.stage_icon,deals:[],totalValue:0});const g=f.get(v);g.deals.push(y),g.totalValue+=y.sale_price||0}),Array.from(f.values())},[u]),m=f=>f>=1e6?`$${(f/1e6).toFixed(1)}M`:f>=1e3?`$${(f/1e3).toFixed(0)}K`:`$${f.toFixed(0)}`,p=f=>f?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(f):null;return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"max-w-[95vw] w-full max-h-[90vh] flex flex-col",children:[e.jsx(Os,{children:e.jsxs(Ds,{className:"flex items-center gap-2",children:[e.jsx(In,{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(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search deals...",value:a,onChange:f=>i(f.target.value),className:"pl-9"})]}),e.jsxs(is,{value:l,onValueChange:o,children:[e.jsx(rs,{className:"w-[180px]",children:e.jsx(ls,{placeholder:"All Members"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Members"}),d.map(f=>e.jsx(He,{value:f.id,children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"h-2 w-2 rounded-full inline-block",style:{backgroundColor:f.color}}),f.name]})},f.id))]})]}),e.jsxs("div",{className:"hidden md:flex items-center gap-3 ml-auto text-xs text-muted-foreground",children:[d.slice(0,6).map(f=>e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"h-2 w-2 rounded-full",style:{backgroundColor:f.color}}),f.name.split(" ")[0]]},f.id)),d.length>6&&e.jsxs("span",{children:["+",d.length-6," more"]})]})]}),e.jsx("div",{className:"flex-1 overflow-hidden mt-2",children:r?e.jsx("div",{className:"flex gap-4 h-full",children:[1,2,3,4].map(f=>e.jsxs("div",{className:"min-w-[260px] flex-1",children:[e.jsx(cn,{className:"h-12 w-full mb-2 rounded-lg"}),e.jsx(cn,{className:"h-24 w-full mb-2 rounded-lg"}),e.jsx(cn,{className:"h-24 w-full rounded-lg"})]},f))}):h.length===0?e.jsx("div",{className:"flex items-center justify-center h-full text-muted-foreground",children:e.jsxs("div",{className:"text-center",children:[e.jsx(In,{className:"h-10 w-10 mx-auto mb-3 opacity-50"}),e.jsx("p",{className:"font-medium",children:"No team deals found"}),e.jsx("p",{className:"text-sm",children:"Team members' deals will appear here."})]})}):e.jsx("div",{className:"flex gap-3 h-full overflow-x-auto pb-2",children:h.map(f=>{const y=f.icon&&jMe[f.icon]||Uf;return e.jsxs("div",{className:"flex flex-col h-full min-w-[260px] max-w-[300px] flex-1 bg-muted/30 rounded-xl border border-border/50",children:[e.jsxs("div",{className:"p-3 border-b border-border/50 shrink-0",style:{borderTopColor:f.color||"hsl(var(--border))",borderTopWidth:3},children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-6 h-6 rounded-md flex items-center justify-center",style:{backgroundColor:f.color?`${f.color}20`:void 0},children:e.jsx(y,{className:"h-3.5 w-3.5",style:{color:f.color||void 0}})}),e.jsx("h3",{className:"font-semibold text-sm",children:f.name})]}),e.jsx(Oe,{variant:"secondary",className:"text-xs px-2",children:f.deals.length})]}),f.totalValue>0&&e.jsx("p",{className:"text-xs text-muted-foreground ml-8",children:m(f.totalValue)})]}),e.jsx(Ji,{className:"flex-1 p-2",children:e.jsx("div",{className:"space-y-2",children:f.deals.map(v=>{const g=c.get(v.owner_user_id);return e.jsx(fWn,{deal:v,ownerColor:(g==null?void 0:g.color)||"#888",ownerName:(g==null?void 0:g.name)||"Unknown",ownerAvatar:(g==null?void 0:g.avatar)||null,formatPrice:p},v.id)})})})]},f.name)})})}),e.jsxs("p",{className:"text-xs text-muted-foreground text-center pt-2 border-t shrink-0",children:[u.length," deal",u.length!==1?"s":""," across ",h.length," stage",h.length!==1?"s":""," from ",d.length," member",d.length!==1?"s":""]})]})})}function fWn({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(ja,{className:"h-4 w-4",children:[e.jsx(pi,{src:r||""}),e.jsx(Na,{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(Oe,{variant:"outline",className:At("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(Jr,{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(yd,{className:"h-3 w-3 text-emerald-500 shrink-0"}),e.jsx("span",{className:"font-semibold text-foreground",children:a(s.sale_price)})]})]})}function xWn({members:s,enabledMembers:t,onToggleMember:n,isOpen:r,onToggleOpen:a,showOwnDeals:i=!0,onToggleOwnDeals:l}){const o=t.size+(i?1:0);return e.jsxs("div",{className:At("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(B,{variant:"ghost",size:"sm",className:"w-full justify-start gap-2 px-2",onClick:a,children:[e.jsx(In,{className:"h-4 w-4 shrink-0 text-primary"}),r&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-xs font-semibold flex-1 text-left",children:"Team"}),o>0&&e.jsx("span",{className:"text-[10px] bg-primary text-primary-foreground rounded-full px-1.5 py-0.5",children:o}),e.jsx($c,{className:"h-3 w-3 text-muted-foreground"})]}),!r&&o>0&&e.jsx("span",{className:"absolute -top-1 -right-1 text-[9px] bg-primary text-primary-foreground rounded-full w-4 h-4 flex items-center justify-center",children:o})]})}),r?e.jsxs(Ji,{className:"flex-1 p-2",children:[e.jsxs("div",{className:"space-y-1",children:[l&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{onClick:l,className:At("w-full flex items-center gap-2 px-2 py-2 rounded-lg text-left transition-colors",i?"bg-primary/10 hover:bg-primary/15":"hover:bg-muted/50"),children:[e.jsx("div",{className:"h-7 w-7 rounded-full bg-primary/20 flex items-center justify-center shrink-0",children:e.jsx(In,{className:"h-3.5 w-3.5 text-primary"})}),e.jsx("span",{className:At("text-xs truncate flex-1",i?"font-medium text-foreground":"text-muted-foreground"),children:"My deals"}),e.jsx(fn,{checked:i,onCheckedChange:l,className:"scale-75",onClick:c=>c.stopPropagation()})]}),e.jsx("div",{className:"h-px bg-border/60 my-1"})]}),s.map(c=>{const d=t.has(c.id);return e.jsxs("button",{onClick:()=>n(c.id),className:At("w-full flex items-center gap-2 px-2 py-2 rounded-lg text-left transition-colors",d?"bg-primary/10 hover:bg-primary/15":"hover:bg-muted/50"),children:[e.jsxs("div",{className:"relative",children:[e.jsxs(ja,{className:"h-7 w-7",children:[e.jsx(pi,{src:c.avatar_url||""}),e.jsx(Na,{className:"text-[10px] font-semibold text-white",style:{backgroundColor:c.color},children:c.name.charAt(0).toUpperCase()})]}),d&&e.jsx("div",{className:"absolute -bottom-0.5 -right-0.5 w-3 h-3 rounded-full border-2 border-background",style:{backgroundColor:c.color}})]}),e.jsx("span",{className:At("text-xs truncate flex-1",d?"font-medium text-foreground":"text-muted-foreground"),children:c.name}),e.jsx(fn,{checked:d,onCheckedChange:()=>n(c.id),className:"scale-75",onClick:u=>u.stopPropagation()})]},c.id)})]}),s.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground text-center py-4",children:"No team members"})]}):e.jsxs("div",{className:"flex-1 flex flex-col items-center pt-2 gap-2",children:[s.slice(0,5).map(c=>{const d=t.has(c.id);return e.jsx("button",{onClick:()=>n(c.id),className:"relative",title:c.name,children:e.jsxs(ja,{className:At("h-7 w-7 transition-all",d?"ring-2 ring-offset-1 ring-offset-background":"opacity-50"),style:d?{"--tw-ring-color":c.color}:{},children:[e.jsx(pi,{src:c.avatar_url||""}),e.jsx(Na,{className:"text-[10px] font-semibold text-white",style:{backgroundColor:c.color},children:c.name.charAt(0).toUpperCase()})]})},c.id)}),s.length>5&&e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["+",s.length-5]})]})]})}const PSt=["#8B5CF6","#EC4899","#F59E0B","#10B981","#3B82F6","#EF4444","#06B6D4","#F97316"];function gWn(){const s=ha(),{data:t}=G_(),n=(t==null?void 0:t.role)==="team_leader",r=t==null?void 0:t.teamId,a=at({queryKey:["team-pipeline-members",r,s],queryFn:async()=>{const{data:i,error:l}=await q.from("team_members").select("user_id, role").eq("team_id",r).neq("user_id",s);if(l)throw l;if(!i||i.length===0)return[];const o=i.map(u=>u.user_id),{data:c,error:d}=await q.from("profiles").select("id, name, avatar_url").in("id",o);if(d)throw d;return(c||[]).map((u,h)=>({id:u.id,name:u.name||"Unknown",avatar_url:u.avatar_url,color:PSt[h%PSt.length]}))},enabled:!!r&&!!s&&n,staleTime:5*60*1e3});return{isTeamLeader:n,teamMembers:a.data||[],isLoadingMembers:a.isLoading}}function yWn(s){return at({queryKey:["team-member-deals",s],queryFn:async()=>{if(s.length===0)return[];const{data:t,error:n}=await q.from("deal_pipeline").select(` *, contact:innercircle_contacts(id, first_name, last_name, email, phone), listing:listings(id, property_address, city, state, price, status, created_at), deal_pipeline_stages(name) `).in("owner_user_id",s).order("updated_at",{ascending:!1});if(n)throw n;return(t||[]).map(r=>{var a;return{...r,_stage_name:((a=r.deal_pipeline_stages)==null?void 0:a.name)||null}})},enabled:s.length>0})}function vWn(){const s=ha();return at({queryKey:["all-deal-tags-map",s],queryFn:async()=>{if(!s)return{tags:[],byDeal:{},unique:[]};const{data:t,error:n}=await q.from("deal_tags").select("id, deal_id, tag").eq("owner_user_id",s);if(n)throw n;const r=t||[],a={},i=new Set;r.forEach(o=>{a[o.deal_id]||(a[o.deal_id]=[]),a[o.deal_id].push(o.tag),i.add(o.tag)});const l=Array.from(i).sort((o,c)=>o.localeCompare(c));return{tags:r,byDeal:a,unique:l}},enabled:!!s})}function Jts({stages:s,currentStageId:t,onStageSelect:n,disabled:r}){const[a,i]=_.useState(!1),l=s.find(c=>c.id===t),o=c=>{c.id!==t&&n(c.id,c.name),i(!1)};return e.jsxs(tu,{open:a,onOpenChange:i,children:[e.jsx(su,{asChild:!0,children:e.jsxs(B,{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(xi,{className:"h-3 w-3 shrink-0"})]})}),e.jsx(Od,{align:"end",className:"w-48 z-50 bg-popover",onClick:c=>c.stopPropagation(),children:s.map(c=>{const d=c.icon&&jMe[c.icon]||Uf,u=c.id===t;return e.jsxs(ca,{onClick:()=>o(c),className:At("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(ea,{className:"h-4 w-4 text-primary"})]},c.id)})})]})}const bWn={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"}},_Wn={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 ess({deal:s,onClick:t,isDragging:n,stages:r,onStageChange:a,showStagePicker:i=!1,isWonStage:l=!1,isLostStage:o=!1,ownerInfo:c=null,tags:d=[],overdueTaskCount:u=0}){var E,P;const h=$W(),m=bWn[s.deal_type],p=_Wn[s.priority],f=_.useMemo(()=>s.target_close_date?CN(Ru(s.target_close_date),new Date):null,[s.target_close_date]),y=l||o||!!s.actual_close_date,v=!y&&f!==null&&f<0,g=!y&&f!==null&&f<=7&&f>=0,b=_.useMemo(()=>{var D;if(s.deal_type!=="seller"&&s.deal_type!=="dual")return null;const M=((D=s.listing)==null?void 0:D.created_at)||s.listing_date;if(!M)return null;const I=s.contract_date?Ru(s.contract_date):new Date;return CN(I,Ru(M))},[s]),j=l&&!s.scorecard_transaction_id,S=!!s.scorecard_transaction_id,C=M=>M?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(M):null;return e.jsxs(ve,{className:At("cursor-pointer transition-all duration-200 hover:shadow-md hover:border-primary/30 group overflow-hidden",n&&"opacity-50 rotate-2 shadow-xl",v&&"border-red-200 bg-red-50/30",j&&"border-amber-300 bg-amber-50/30 dark:bg-amber-950/20"),onClick:t,style:c?{borderLeftWidth:4,borderLeftColor:c.color}:void 0,children:[!c&&e.jsx("div",{className:At("h-1 w-full",p.stripe),"aria-hidden":!0}),e.jsxs(Me,{className:"p-3 space-y-2.5",children:[c&&e.jsxs("div",{className:"flex items-center gap-1.5 -mt-0.5 mb-1",children:[e.jsxs(ja,{className:"h-4 w-4",children:[e.jsx(pi,{src:c.avatar_url||""}),e.jsx(Na,{className:"text-[8px] font-semibold text-white",style:{backgroundColor:c.color},children:c.name.charAt(0).toUpperCase()})]}),e.jsx("span",{className:"text-[10px] font-medium",style:{color:c.color},children:c.name})]}),e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx("h4",{className:"font-medium text-sm leading-tight line-clamp-2 group-hover:text-primary transition-colors",children:s.deal_name})}),e.jsx(Oe,{variant:"outline",className:At("text-[10px] px-1.5 py-0 shrink-0",m.color),children:m.label})]}),s.contact&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(ja,{className:"h-5 w-5",children:e.jsxs(Na,{className:"text-[10px] bg-primary/10 text-primary",children:[(E=s.contact.first_name)==null?void 0:E[0],(P=s.contact.last_name)==null?void 0:P[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(vd,{className:"h-3 w-3 text-primary shrink-0"}),e.jsx("span",{className:"text-primary truncate",children:"Linked to Listing Exchange"})]}),j&&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(wl,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate font-medium",children:"Add to Scorecard"})]}),S&&l&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-green-600 dark:text-green-400",children:[e.jsx(Er,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate",children:"Synced to Scorecard"})]}),b!==null&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs",children:[e.jsx(Qd,{className:"h-3 w-3 text-muted-foreground shrink-0"}),e.jsxs("span",{className:At("font-medium",b>90?"text-red-600":b>60?"text-amber-600":"text-muted-foreground"),children:[b," DOM"]}),s.contract_date&&e.jsx("span",{className:"text-muted-foreground",children:"(final)"})]}),!s.listing&&(s.property_address||s.city)&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(Jr,{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(yd,{className:"h-3 w-3 text-emerald-500 shrink-0"}),e.jsx("span",{className:"font-semibold text-foreground",children:C(s.expected_price)}),s.expected_commission&&e.jsxs("span",{className:"text-muted-foreground",children:["• ",C(s.expected_commission)," GCI"]}),(()=>{const M=j_(s);return M!==null&&M!==s.expected_commission?e.jsxs("span",{className:"text-teal-600 dark:text-teal-400",children:["• ",C(M)," Net"]}):null})()]}),u>0&&e.jsxs("div",{className:"flex items-center gap-1.5 rounded bg-destructive/10 px-2 py-1 text-xs font-medium text-destructive",children:[e.jsx(Ny,{className:"h-3 w-3 shrink-0"}),e.jsxs("span",{children:[u," overdue task",u>1?"s":""]})]}),d.length>0&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[d.slice(0,3).map(M=>e.jsx(DYt,{label:M},M)),d.length>3&&e.jsxs("span",{className:"inline-flex h-6 items-center rounded-full bg-muted px-2 text-[11px] font-medium text-muted-foreground",children:["+",d.length-3]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between text-[10px] text-muted-foreground",children:[e.jsx("span",{children:"Win probability"}),e.jsxs("span",{className:"font-semibold text-foreground",children:[s.probability,"%"]})]}),e.jsx("div",{className:"h-1.5 w-full overflow-hidden rounded-full bg-muted",children:e.jsx("div",{className:"h-full rounded-full bg-primary transition-all",style:{width:`${Math.min(100,Math.max(0,s.probability??0))}%`}})})]}),e.jsxs("div",{className:"flex items-center justify-between pt-1 border-t border-border/50",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("div",{className:At("flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px]",p.color),children:[e.jsx("div",{className:At("w-1.5 h-1.5 rounded-full",p.dot)}),e.jsx("span",{className:"capitalize",children:s.priority})]})}),i&&h&&r&&a?e.jsx(Jts,{stages:r,currentStageId:s.stage_id||"",onStageSelect:(M,I)=>a(s.id,M,I)}):s.target_close_date?e.jsxs("div",{className:At("flex items-center gap-1 text-[10px]",v&&"text-red-600",g&&!v&&"text-amber-600",!v&&!g&&"text-muted-foreground"),children:[v?e.jsx(Xo,{className:"h-3 w-3"}):e.jsx(ga,{className:"h-3 w-3"}),e.jsx("span",{children:v?`${Math.abs(f)}d overdue`:g?`${f}d left`:Hs(Ru(s.target_close_date),"MMM d")})]}):null]})]})]})}function wWn({stage:s,deals:t,onDealClick:n,onAddDeal:r,onDragStart:a,onDragOver:i,onDrop:l,isDragOver:o,isWonStage:c=!1,isLostStage:d=!1,getOwnerInfo:u,tagsByDeal:h={},overdueTasksByDeal:m={}}){const p=_.useRef(null),[f,y]=_.useState(!1),v=t.reduce((C,E)=>C+(E.expected_price||0),0),g=t.reduce((C,E)=>C+(E.expected_commission||0),0),b=t.reduce((C,E)=>C+(j_(E)||0),0),j=C=>C>=1e6?`$${(C/1e6).toFixed(1)}M`:C>=1e3?`$${(C/1e3).toFixed(0)}K`:`$${C.toFixed(0)}`,S=s.icon&&jMe[s.icon]||Uf;return f?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:()=>y(!1),"aria-label":`Expand ${s.name}`,className:"text-muted-foreground transition-colors hover:text-foreground",children:e.jsx(xi,{className:"h-4 w-4"})}),e.jsx(Oe,{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:p,className:At("flex flex-col h-full min-w-[280px] max-w-[320px] bg-muted/30 rounded-xl border border-border/50 transition-all duration-200",o&&"border-primary/50 bg-primary/5 ring-2 ring-primary/20"),onDragOver:C=>i(C,s.id),onDrop:C=>l(C,s.id),children:[e.jsxs("div",{className:"p-3 border-b border-border/50 shrink-0",style:{borderTopColor:s.color,borderTopWidth:3},children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-7 h-7 rounded-lg flex items-center justify-center",style:{backgroundColor:`${s.color}20`},children:e.jsx(S,{className:"h-4 w-4",style:{color:s.color}})}),e.jsx("div",{children:e.jsx("h3",{className:"font-semibold text-sm",children:s.name})})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Oe,{variant:"secondary",className:"text-xs font-medium px-2",children:t.length}),e.jsx("button",{onClick:()=>y(!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($c,{className:"h-3.5 w-3.5"})})]})]}),v>0&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground flex-wrap",children:[e.jsx("span",{className:"font-medium text-foreground",children:j(v)}),e.jsx("span",{children:"•"}),e.jsxs("span",{children:[j(g)," GCI"]}),b>0&&b!==g&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsxs("span",{className:"text-teal-600 dark:text-teal-400",children:[j(b)," Net"]})]})]})]}),e.jsx(Ji,{className:"flex-1 p-2",children:e.jsxs("div",{className:"space-y-2",children:[t.map(C=>e.jsx("div",{draggable:!0,onDragStart:E=>{E.dataTransfer.effectAllowed="move",a(C.id,s.id)},children:e.jsx(ess,{deal:C,onClick:()=>n(C),isWonStage:c,isLostStage:d,ownerInfo:(u==null?void 0:u(C))||null,tags:h[C.id]||[],overdueTaskCount:m[C.id]||0})},C.id)),t.length===0&&e.jsxs("div",{className:"py-8 px-4 text-center text-muted-foreground text-sm",children:[e.jsx("p",{className:"mb-2",children:"No deals yet"}),e.jsx("p",{className:"text-xs",children:"Drag deals here or add new"})]})]})}),e.jsx("div",{className:"p-2 border-t border-border/50 shrink-0",children:e.jsxs(B,{variant:"ghost",size:"sm",className:"w-full justify-start text-muted-foreground hover:text-foreground",onClick:()=>r(s.id),children:[e.jsx(rn,{className:"h-4 w-4 mr-2"}),"Add Deal"]})})]})}const _N=q;function jWn(s,t=!1){return at({queryKey:["commission-plans",s,t],enabled:!!s,queryFn:async()=>{let n=_N.from("brokerage_commission_plans").select("*").eq("brokerage_id",s).order("name",{ascending:!0});t||(n=n.eq("is_active",!0));const{data:r,error:a}=await n;if(a)throw a;return r||[]}})}function NWn(s){const t=Bt();return mt({mutationFn:async n=>{const r={brokerage_id:s,name:n.name,description:n.description||null,agent_split_pct:n.agent_split_pct??70,team_split_pct:n.team_split_pct??0,cap_amount:n.cap_amount??null,monthly_fee:n.monthly_fee??0,transaction_fee:n.transaction_fee??0,franchise_fee_pct:n.franchise_fee_pct??0,referral_fee_pct:n.referral_fee_pct??null,commission_calc_method:n.commission_calc_method||"standard",is_active:n.is_active??!0};if(n.id){const{error:a}=await _N.from("brokerage_commission_plans").update(r).eq("id",n.id);if(a)throw a}else{const{error:a}=await _N.from("brokerage_commission_plans").insert(r);if(a)throw a}},onSuccess:()=>{t.invalidateQueries({queryKey:["commission-plans",s]}),se.success("Commission plan saved")},onError:n=>se.error(n.message||"Could not save plan")})}function kWn(s){return at({queryKey:["cap-progress",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await _N.rpc("get_agent_cap_progress",{_agent_user_id:s});if(n)throw n;return(t||[])[0]??null}})}function SWn(s){return at({queryKey:["agent-plan-roster",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("profiles").select("id, name, email, avatar_url").eq("brokerage_id",s).order("name",{ascending:!0});if(n)throw n;const{data:r,error:a}=await _N.from("agent_plan_assignments").select("*").eq("brokerage_id",s).is("end_date",null);if(a)throw a;const i=[...new Set((r||[]).map(c=>c.plan_id))];let l=[];if(i.length){const{data:c,error:d}=await _N.from("brokerage_commission_plans").select("*").in("id",i);if(d)throw d;l=c||[]}return await Promise.all((t||[]).map(async c=>{const d=(r||[]).find(m=>m.agent_user_id===c.id)||null,u=d&&l.find(m=>m.id===d.plan_id)||null;let h=null;if(d){const{data:m}=await _N.rpc("get_agent_cap_progress",{_agent_user_id:c.id});h=(m||[])[0]??null}return{agentId:c.id,name:c.name||c.email,email:c.email,avatarUrl:c.avatar_url||null,assignment:d,plan:u,progress:h}}))}})}function CWn(s){const t=Bt();return mt({mutationFn:async n=>{const{error:r}=await _N.from("agent_plan_assignments").update({end_date:n.start_date}).eq("brokerage_id",s).eq("agent_user_id",n.agent_user_id).is("end_date",null);if(r)throw r;const{error:a}=await _N.from("agent_plan_assignments").insert({agent_user_id:n.agent_user_id,brokerage_id:s,plan_id:n.plan_id,start_date:n.start_date,anniversary_date:n.anniversary_date||null,notes:n.notes||null});if(a)throw a},onSuccess:()=>{t.invalidateQueries({queryKey:["agent-plan-roster",s]}),se.success("Plan assigned")},onError:n=>se.error(n.message||"Could not assign plan")})}function AWn(s){const t=Bt();return mt({mutationFn:async n=>{const r=new Date().toISOString().slice(0,10),{error:a}=await _N.from("agent_plan_assignments").update({end_date:r}).eq("id",n);if(a)throw a},onSuccess:()=>{t.invalidateQueries({queryKey:["agent-plan-roster",s]}),se.success("Plan removed from agent")},onError:n=>se.error(n.message||"Could not remove plan")})}function tss(){const{user:s}=hs();return at({queryKey:["my-commission-plan",s==null?void 0:s.id],enabled:!!s,staleTime:5*6e4,queryFn:async()=>{const{data:t,error:n}=await _N.from("agent_plan_assignments").select("*").eq("agent_user_id",s.id).is("end_date",null).order("start_date",{ascending:!1}).limit(1).maybeSingle();if(n)throw n;if(!t)return null;const{data:r,error:a}=await _N.from("brokerage_commission_plans").select("*").eq("id",t.plan_id).maybeSingle();if(a)throw a;return r?{assignment:t,plan:r}:null}})}function EWn({formData:s,onChange:t,isEditing:n}){const{isAdmin:r}=hs(),[a,i]=_.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(un,{className:"h-4 w-4 text-primary"}),e.jsx("h4",{className:"font-medium text-sm",children:"Client Portal"}),e.jsx(Oe,{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(f1,{open:a,onOpenChange:i,children:e.jsxs("div",{className:"border rounded-lg",children:[e.jsxs(x1,{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(un,{className:"h-4 w-4 text-primary"}),e.jsx("h4",{className:"font-medium text-sm",children:"Client Portal"}),s.portal_enabled&&e.jsx(Oe,{className:"text-xs bg-emerald-500/10 text-emerald-600 border-emerald-200",variant:"outline",children:"Enabled"})]}),e.jsx(tl,{className:At("h-4 w-4 text-muted-foreground transition-transform",a&&"rotate-180")})]}),e.jsx(g1,{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(J,{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(fn,{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(J,{className:"text-sm font-medium",children:"Portal Visibility"}),e.jsxs(k_,{value:s.visibility,onValueChange:o=>l({visibility:o}),className:"grid grid-cols-2 gap-3",children:[e.jsxs("label",{className:At("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(sm,{value:"private"}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ec,{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:At("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(sm,{value:"public"}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(sl,{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($a,{id:"require_onboarding",checked:s.require_onboarding,onCheckedChange:o=>l({require_onboarding:!!o}),className:"mt-0.5"}),e.jsxs("div",{children:[e.jsx(J,{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($a,{id:"allow_spouse",checked:s.allow_spouse,onCheckedChange:o=>l({allow_spouse:!!o})}),e.jsx(J,{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(J,{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(J,{className:"text-xs text-muted-foreground",children:"Client Full Name"}),e.jsx(xe,{value:s.client_name,onChange:o=>l({client_name:o.target.value}),placeholder:"Jane Smith"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs text-muted-foreground",children:"Email"}),e.jsx(xe,{type:"email",value:s.client_email,onChange:o=>l({client_email:o.target.value}),placeholder:"jane@example.com"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs text-muted-foreground",children:"Phone"}),e.jsx(xe,{type:"tel",value:s.client_phone,onChange:o=>l({client_phone:o.target.value}),placeholder:"(555) 123-4567"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs text-muted-foreground",children:"Preferred Invite Method"}),e.jsxs(is,{value:s.invite_method,onValueChange:o=>l({invite_method:o}),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"email",children:"Email"}),e.jsxs(He,{value:"sms",disabled:!s.client_phone,children:["SMS ",!s.client_phone&&"(add phone first)"]})]})]})]})]})]})]})]})})]})})}const TWn=[{value:"buyer",label:"Buyer"},{value:"seller",label:"Seller"},{value:"dual",label:"Dual Agency"},{value:"referral",label:"Referral"},{value:"lease",label:"Lease"}],MWn=[{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"},{value:"urgent",label:"Urgent"}];function eBe({label:s,date:t,onChange:n,placeholder:r="Pick a date",disabled:a}){const[i,l]=_.useState(t?Hs(t,"MM/dd/yyyy"):"");_.useEffect(()=>{const c=kxt(i);t&&c&&c.getTime()===t.getTime()||l(t?Hs(t,"MM/dd/yyyy"):"")},[t]);const o=c=>{l(c);const d=kxt(c);d?n(d):c.trim()||n(void 0)};return e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:s}),e.jsxs(od,{children:[e.jsx(ld,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:At("w-full justify-start text-left font-normal",!t&&"text-muted-foreground"),disabled:a,children:[e.jsx(ga,{className:"mr-2 h-4 w-4"}),t?Hs(t,"PPP"):r]})}),e.jsxs(Qc,{className:"w-auto p-0",align:"start",children:[e.jsx("div",{className:"p-3 border-b",children:e.jsx(xe,{type:"text",placeholder:"MM/DD/YYYY",value:i,onChange:c=>o(c.target.value),className:"h-8 text-sm"})}),e.jsx(Pj,{mode:"single",selected:t,onSelect:c=>{n(c),l(c?Hs(c,"MM/dd/yyyy"):"")},initialFocus:!0,className:"pointer-events-auto",captionLayout:"dropdown",fromYear:1900,toYear:2100})]})]})]})}function PWn({open:s,onOpenChange:t,deal:n,defaultStageId:r}){const{data:a}=eie(),{data:i}=Db(),{data:l}=set(),o=iLe(),c=Kts(),d=Yts(),u=Snt(),{data:h}=tss(),{data:m}=QMe(),p=((m==null?void 0:m.length)??0)>0,f=_.useMemo(()=>{const Z=h==null?void 0:h.plan;return Z?{brokerage_split_pct:String(Math.max(0,100-(Z.agent_split_pct??100))),team_split_pct:p&&Z.team_split_pct?String(Z.team_split_pct):"",franchise_fee_pct:Z.franchise_fee_pct?String(Z.franchise_fee_pct):"",transaction_fee:Z.transaction_fee?String(Z.transaction_fee):"",referral_fee_pct:Z.referral_fee_pct!=null?String(Z.referral_fee_pct):"",commission_calc_method:Z.commission_calc_method||"standard"}:{brokerage_split_pct:"",team_split_pct:"",franchise_fee_pct:"",transaction_fee:"",referral_fee_pct:"",commission_calc_method:"standard"}},[h,p]);_.useEffect(()=>{if(!s||n||!h)return;const Z=h.plan;O(ne=>ne.brokerage_split_pct||ne.franchise_fee_pct||ne.transaction_fee||ne.referral_fee_pct||ne.team_split_pct?ne:{...ne,brokerage_split_pct:String(Math.max(0,100-(Z.agent_split_pct??100))),team_split_pct:p&&Z.team_split_pct?String(Z.team_split_pct):"",franchise_fee_pct:Z.franchise_fee_pct?String(Z.franchise_fee_pct):"",transaction_fee:Z.transaction_fee?String(Z.transaction_fee):"",referral_fee_pct:Z.referral_fee_pct!=null?String(Z.referral_fee_pct):"",commission_calc_method:Z.commission_calc_method||"standard"})},[h,s,n,p]);const[y,v]=_.useState({portal_enabled:!1,visibility:"private",require_onboarding:!0,allow_spouse:!1,client_name:"",client_email:"",client_phone:"",invite_method:"email"}),[g,b]=_.useState(""),[j,S]=_.useState(!1),[C,E]=_.useState(!1),[P,M]=_.useState({first_name:"",last_name:"",email:"",phone:""}),I=(l==null?void 0:l.filter(Z=>((n==null?void 0:n.listing_id)===Z.id,!0)))||[],[D,O]=_.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:""});_.useEffect(()=>{var Z,ne,ce,ie,te,ae,le,be,me,he;s&&(n?(O({deal_name:n.deal_name,deal_type:n.deal_type,stage_id:n.stage_id||"",contact_id:n.contact_id||"",listing_id:n.listing_id||"",property_address:n.property_address||"",city:n.city||"",state:n.state||"",zip_code:n.zip_code||"",expected_price:((Z=n.expected_price)==null?void 0:Z.toString())||"",commission_percentage:((ne=n.commission_percentage)==null?void 0:ne.toString())||"3",brokerage_split_pct:((ce=n.brokerage_split_pct)==null?void 0:ce.toString())||"",team_split_pct:((ie=n.team_split_pct)==null?void 0:ie.toString())||"",referral_fee_pct:((te=n.referral_fee_pct)==null?void 0:te.toString())||"",franchise_fee_pct:((ae=n.franchise_fee_pct)==null?void 0:ae.toString())||"",transaction_fee:((le=n.transaction_fee)==null?void 0:le.toString())||"",bonus_amount:((be=n.bonus_amount)==null?void 0:be.toString())||"",commission_calc_method:n.commission_calc_method||"standard",target_close_date:n.target_close_date?Ru(n.target_close_date):void 0,contract_date:n.contract_date?Ru(n.contract_date):void 0,listing_date:n.listing_date?Ru(n.listing_date):void 0,priority:n.priority,probability:n.probability.toString(),notes:n.notes||""}),n.contact&&b(`${n.contact.first_name} ${n.contact.last_name}`)):(O({deal_name:"",deal_type:"buyer",stage_id:r||((me=a==null?void 0:a[0])==null?void 0:me.id)||"",contact_id:"",listing_id:"",property_address:"",city:"",state:"",zip_code:"",expected_price:"",commission_percentage:"3",brokerage_split_pct:f.brokerage_split_pct,team_split_pct:f.team_split_pct,referral_fee_pct:f.referral_fee_pct,franchise_fee_pct:f.franchise_fee_pct,transaction_fee:f.transaction_fee,bonus_amount:"",commission_calc_method:f.commission_calc_method,target_close_date:void 0,contract_date:void 0,listing_date:void 0,priority:"medium",probability:String(((he=a==null?void 0:a.find(pe=>{var Ce;return pe.id===(r||((Ce=a==null?void 0:a[0])==null?void 0:Ce.id))}))==null?void 0:he.default_probability)??50),notes:""}),b(""),v({portal_enabled:!1,visibility:"private",require_onboarding:!0,allow_spouse:!1,client_name:"",client_email:"",client_phone:"",invite_method:"email"})))},[s,n,r,a]);const V=i==null?void 0:i.filter(Z=>{var he,pe,Ce,Ae,Pe;const ne=g.toLowerCase().trim();if(!ne)return!0;const ce=((he=Z.first_name)==null?void 0:he.toLowerCase())||"",ie=((pe=Z.last_name)==null?void 0:pe.toLowerCase())||"",te=((Ce=Z.email)==null?void 0:Ce.toLowerCase())||"",ae=((Pe=(Ae=Z.phone)==null?void 0:Ae.toLowerCase)==null?void 0:Pe.call(Ae))||"",le=`${ce} ${ie}`.trim(),be=`${ie} ${ce}`.trim();if(le.includes(ne)||be.includes(ne)||ce.includes(ne)||ie.includes(ne)||te.includes(ne)||ae.includes(ne))return!0;const me=ne.split(/\s+/).filter(Boolean);return me.length>1?me.every(ze=>ce.includes(ze)||ie.includes(ze)||te.includes(ze)||ae.includes(ze)):!1}).slice(0,8),G=()=>{const Z=parseFloat(D.expected_price)||0,ne=parseFloat(D.commission_percentage)||0;return Z*(ne/100)},$=()=>{const Z=G(),ne=parseFloat(D.bonus_amount)||0;if(!Z)return ne>0?ne:null;const ce=parseFloat(D.brokerage_split_pct)||0,ie=parseFloat(D.team_split_pct)||0,te=parseFloat(D.referral_fee_pct)||0,ae=parseFloat(D.franchise_fee_pct)||0,le=parseFloat(D.transaction_fee)||0,be=parseFloat(D.bonus_amount)||0;if(D.commission_calc_method==="referral_first"){let he=Z;te&&(he-=Z*te/100);let pe=he;return ce&&(pe-=he*ce/100),ie&&(pe-=Z*ie/100),ae&&(pe-=Z*ae/100),le&&(pe-=le),Math.max(0,pe)+be}let me=Z;return ce&&(me=me*((100-ce)/100)),ie&&(me=me*((100-ie)/100)),te&&(me=me-Z*te/100),ae&&(me=me-Z*ae/100),le&&(me=me-le),Math.max(0,me)+be},H=async Z=>{var ne,ce,ie;if(Z.preventDefault(),!D.deal_name.trim()){se.error("Please enter a deal name");return}try{const te={deal_name:D.deal_name,deal_type:D.deal_type,stage_id:D.stage_id||null,contact_id:D.contact_id||null,listing_id:D.listing_id||null,property_address:D.property_address||null,city:D.city||null,state:D.state||null,zip_code:D.zip_code||null,expected_price:D.expected_price?parseFloat(D.expected_price):null,expected_commission:G()||null,commission_percentage:D.commission_percentage?parseFloat(D.commission_percentage):3,brokerage_split_pct:D.brokerage_split_pct?parseFloat(D.brokerage_split_pct):null,team_split_pct:D.team_split_pct?parseFloat(D.team_split_pct):null,referral_fee_pct:D.referral_fee_pct?parseFloat(D.referral_fee_pct):null,franchise_fee_pct:D.franchise_fee_pct?parseFloat(D.franchise_fee_pct):null,transaction_fee:D.transaction_fee?parseFloat(D.transaction_fee):null,bonus_amount:D.bonus_amount?parseFloat(D.bonus_amount):null,commission_calc_method:D.commission_calc_method,target_close_date:((ne=D.target_close_date)==null?void 0:ne.toISOString().split("T")[0])||null,contract_date:((ce=D.contract_date)==null?void 0:ce.toISOString().split("T")[0])||null,listing_date:((ie=D.listing_date)==null?void 0:ie.toISOString().split("T")[0])||null,priority:D.priority,probability:parseInt(D.probability)||50,notes:D.notes||null};if(n)await d.mutateAsync({id:n.id,...te}),se.success("Deal updated successfully");else{const ae=await c.mutateAsync(te);if(se.success("Deal created successfully"),y.portal_enabled&&(ae!=null&&ae.id))try{await u.mutateAsync({deal_id:ae.id,visibility:y.visibility,require_onboarding:y.require_onboarding,allow_spouse:y.allow_spouse,client_name:y.client_name||null,client_email:y.client_email||null,client_phone:y.client_phone||null,invite_method:y.invite_method}),se.success("Client portal created!")}catch{se.error("Deal created, but portal setup failed")}}t(!1)}catch{se.error("Failed to save deal")}},Y=c.isPending||d.isPending;return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:n?"Edit Deal":"Add New Deal"}),e.jsx(_r,{children:n?"Update the deal details below.":"Enter the details for your new deal."})]}),e.jsxs("form",{onSubmit:H,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(J,{htmlFor:"deal_name",children:"Deal Name *"}),e.jsx(xe,{id:"deal_name",value:D.deal_name,onChange:Z=>O(ne=>({...ne,deal_name:Z.target.value})),placeholder:"e.g., Smith Family - 123 Main St"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Deal Type"}),e.jsxs(is,{value:D.deal_type,onValueChange:Z=>O(ne=>({...ne,deal_type:Z})),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsx(as,{children:TWn.map(Z=>e.jsx(He,{value:Z.value,children:Z.label},Z.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Stage"}),e.jsxs(is,{value:D.stage_id||"none",onValueChange:Z=>{const ne=Z==="none"?"":Z,ce=a==null?void 0:a.find(ie=>ie.id===ne);O(ie=>({...ie,stage_id:ne,probability:typeof(ce==null?void 0:ce.default_probability)=="number"?String(ce.default_probability):ie.probability}))},children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Select stage"})}),e.jsxs(as,{children:[e.jsx(He,{value:"none",children:"No Stage"}),a==null?void 0:a.map(Z=>e.jsx(He,{value:Z.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full",style:{backgroundColor:Z.color}}),Z.name]})},Z.id))]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Link to Contact"}),e.jsxs("div",{className:"relative",children:[e.jsx(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{value:g,onChange:Z=>{b(Z.target.value),S(!0),E(!1),Z.target.value||O(ne=>({...ne,contact_id:""}))},onFocus:()=>S(!0),placeholder:"Search contacts...",className:"pl-9"}),j&&g&&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:[V&&V.length>0?V.map(Z=>e.jsxs("button",{type:"button",className:"w-full px-3 py-2 text-left hover:bg-muted flex items-center gap-2",onClick:()=>{O(ne=>({...ne,contact_id:Z.id})),b(`${Z.first_name} ${Z.last_name}`),S(!1)},children:[e.jsx(Fo,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:[Z.first_name," ",Z.last_name]}),Z.email&&e.jsx("span",{className:"text-xs text-muted-foreground ml-auto",children:Z.email})]},Z.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 Z=g.trim().split(/\s+/);M({first_name:Z[0]||"",last_name:Z.slice(1).join(" ")||"",email:"",phone:""}),E(!0),S(!1)},children:[e.jsx(Pl,{className:"h-4 w-4"}),e.jsxs("span",{children:['Create new contact "',g.trim(),'"']})]})]})]}),C&&e.jsxs("div",{className:"border rounded-lg p-3 space-y-3 bg-muted/30",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-sm font-medium flex items-center gap-1.5",children:[e.jsx(Pl,{className:"h-3.5 w-3.5"}),"Quick Add Contact"]}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:()=>E(!1),children:"Cancel"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(xe,{placeholder:"First name *",value:P.first_name,onChange:Z=>M(ne=>({...ne,first_name:Z.target.value})),className:"h-8 text-sm"}),e.jsx(xe,{placeholder:"Last name",value:P.last_name,onChange:Z=>M(ne=>({...ne,last_name:Z.target.value})),className:"h-8 text-sm"}),e.jsx(xe,{placeholder:"Email",type:"email",value:P.email,onChange:Z=>M(ne=>({...ne,email:Z.target.value})),className:"h-8 text-sm"}),e.jsx(xe,{placeholder:"Phone",type:"tel",value:P.phone,onChange:Z=>M(ne=>({...ne,phone:Z.target.value})),className:"h-8 text-sm"})]}),e.jsx(B,{type:"button",size:"sm",className:"w-full h-8",disabled:!P.first_name.trim()||o.isPending,onClick:async()=>{try{const Z=await o.mutateAsync({first_name:P.first_name.trim(),last_name:P.last_name.trim()||null,email:P.email.trim()||null,phone:P.phone.trim()||null});Z&&(O(ne=>({...ne,contact_id:Z.id})),b(`${Z.first_name} ${Z.last_name||""}`.trim()),E(!1))}catch{}},children:o.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"h-3.5 w-3.5 mr-1 animate-spin"})," Creating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Pl,{className:"h-3.5 w-3.5 mr-1"})," Add & Link Contact"]})})]})]}),I.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(J,{className:"flex items-center gap-2",children:[e.jsx(vd,{className:"h-4 w-4"}),"Link to Listing Exchange"]}),e.jsxs(is,{value:D.listing_id||"none",onValueChange:Z=>{const ne=Z==="none"?"":Z,ce=I.find(ie=>ie.id===ne);O(ce?ie=>{var te;return{...ie,listing_id:ne,deal_type:"seller",property_address:ce.property_address||ie.property_address,city:ce.city||ie.city,state:ce.state||ie.state,expected_price:((te=ce.price)==null?void 0:te.toString())||ie.expected_price}}:ie=>({...ie,listing_id:ne}))},children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Select a listing to sync status..."})}),e.jsxs(as,{children:[e.jsx(He,{value:"none",children:"None"}),I.map(Z=>e.jsx(He,{value:Z.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{children:Z.property_address||`${Z.city}, ${Z.state}`}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["$",(Z.price/1e3).toFixed(0),"K"]})]})},Z.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(J,{htmlFor:"property_address",children:"Address"}),e.jsx(xe,{id:"property_address",value:D.property_address,onChange:Z=>O(ne=>({...ne,property_address:Z.target.value})),placeholder:"123 Main Street"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"city",children:"City"}),e.jsx(xe,{id:"city",value:D.city,onChange:Z=>O(ne=>({...ne,city:Z.target.value}))})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"state",children:"State"}),e.jsx(xe,{id:"state",value:D.state,onChange:Z=>O(ne=>({...ne,state:Z.target.value})),maxLength:2,placeholder:"TX"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"zip_code",children:"ZIP"}),e.jsx(xe,{id:"zip_code",value:D.zip_code,onChange:Z=>O(ne=>({...ne,zip_code:Z.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(J,{htmlFor:"expected_price",children:"Expected Price"}),e.jsxs("div",{className:"relative",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground",children:"$"}),e.jsx(xe,{id:"expected_price",type:"number",value:D.expected_price,onChange:Z=>O(ne=>({...ne,expected_price:Z.target.value})),className:"pl-7",placeholder:"500000"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"commission_percentage",children:"Commission %"}),e.jsxs("div",{className:"relative",children:[e.jsx(xe,{id:"commission_percentage",type:"number",step:"0.1",value:D.commission_percentage,onChange:Z=>O(ne=>({...ne,commission_percentage:Z.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(J,{children:"Expected GCI"}),e.jsx(xe,{value:G()?`$${G().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(J,{className:"text-xs whitespace-nowrap",children:"Calculation Method:"}),e.jsxs(is,{value:D.commission_calc_method,onValueChange:Z=>O(ne=>({...ne,commission_calc_method:Z})),children:[e.jsx(rs,{className:"h-7 text-xs",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"standard",children:"Standard (all splits on GCI)"}),e.jsx(He,{value:"referral_first",children:"Referral First (brokerage split after referral)"})]})]})]}),D.commission_calc_method==="referral_first"&&e.jsx("p",{className:"text-[10px] text-muted-foreground bg-blue-50 dark:bg-blue-950/30 p-2 rounded",children:"💡 Referral fee is deducted from GCI first, then the brokerage split is applied to the remaining amount."}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs",children:"Brokerage Split"}),e.jsxs("div",{className:"relative",children:[e.jsx(xe,{type:"number",step:"1",min:"0",max:"100",value:D.brokerage_split_pct,onChange:Z=>O(ne=>({...ne,brokerage_split_pct:Z.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(J,{className:"text-xs",children:"Team Split"}),e.jsxs("div",{className:"relative",children:[e.jsx(xe,{type:"number",step:"1",min:"0",max:"100",value:D.team_split_pct,onChange:Z=>O(ne=>({...ne,team_split_pct:Z.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(J,{className:"text-xs",children:"Referral Fee"}),e.jsxs("div",{className:"relative",children:[e.jsx(xe,{type:"number",step:"1",min:"0",max:"100",value:D.referral_fee_pct,onChange:Z=>O(ne=>({...ne,referral_fee_pct:Z.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(J,{className:"text-xs",children:"Franchise Fee"}),e.jsxs("div",{className:"relative",children:[e.jsx(xe,{type:"number",step:"1",min:"0",max:"100",value:D.franchise_fee_pct,onChange:Z=>O(ne=>({...ne,franchise_fee_pct:Z.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(J,{className:"text-xs",children:"Transaction Fee"}),e.jsxs("div",{className:"relative",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground text-xs",children:"$"}),e.jsx(xe,{type:"number",step:"1",min:"0",value:D.transaction_fee,onChange:Z=>O(ne=>({...ne,transaction_fee:Z.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(J,{className:"text-xs",children:"Bonus"}),e.jsxs("div",{className:"relative",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground text-xs",children:"$"}),e.jsx(xe,{type:"number",step:"1",min:"0",value:D.bonus_amount,onChange:Z=>O(ne=>({...ne,bonus_amount:Z.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(J,{className:"text-xs",children:"Net to Agent"}),e.jsx(xe,{value:$()?`$${Math.round($()).toLocaleString()}`:"-",disabled:!0,className:"bg-muted h-8 text-sm font-semibold"})]})]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"font-medium text-sm",children:"Dates & Status"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx(eBe,{label:"Target Close Date",date:D.target_close_date,onChange:Z=>O(ne=>({...ne,target_close_date:Z}))}),e.jsx(eBe,{label:"Contract Date",date:D.contract_date,onChange:Z=>O(ne=>({...ne,contract_date:Z}))}),(D.deal_type==="seller"||D.deal_type==="dual")&&!D.listing_id&&e.jsxs("div",{className:"space-y-2 col-span-2",children:[e.jsx(eBe,{label:"Listing Date (for Days on Market)",date:D.listing_date,onChange:Z=>O(ne=>({...ne,listing_date:Z}))}),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(J,{children:"Priority"}),e.jsxs(is,{value:D.priority,onValueChange:Z=>O(ne=>({...ne,priority:Z})),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsx(as,{children:MWn.map(Z=>e.jsx(He,{value:Z.value,children:Z.label},Z.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Win Probability"}),e.jsxs("div",{className:"relative",children:[e.jsx(xe,{type:"number",min:"0",max:"100",value:D.probability,onChange:Z=>O(ne=>({...ne,probability:Z.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(J,{htmlFor:"notes",children:"Notes"}),e.jsx(Ms,{id:"notes",value:D.notes,onChange:Z=>O(ne=>({...ne,notes:Z.target.value})),placeholder:"Add any additional notes about this deal...",rows:3})]}),!n&&e.jsx(EWn,{formData:y,onChange:v}),e.jsxs("div",{className:"flex justify-end gap-3 pt-4 border-t",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{type:"submit",disabled:Y,children:[Y&&e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),n?"Update Deal":"Create Deal"]})]})]})]})})}function LWn({dealId:s}){const t=ha(),n=Bt(),[r,a]=_.useState(""),[i,l]=_.useState(!1),{data:o=[]}=at({queryKey:["deal-tags",s],queryFn:async()=>{const{data:f,error:y}=await q.from("deal_tags").select("*").eq("deal_id",s).order("created_at");if(y)throw y;return f},enabled:!!s}),{data:c=[]}=at({queryKey:["all-deal-tags",t],queryFn:async()=>{if(!t)return[];const{data:f,error:y}=await q.from("deal_tags").select("tag").eq("owner_user_id",t);if(y)throw y;return[...new Set(f.map(g=>g.tag))].sort()},enabled:!!t}),d=mt({mutationFn:async f=>{if(!t)throw new Error("Not authenticated");const{error:y}=await q.from("deal_tags").insert({deal_id:s,owner_user_id:t,tag:f.trim()});if(y)throw y},onSuccess:()=>{n.invalidateQueries({queryKey:["deal-tags",s]}),n.invalidateQueries({queryKey:["all-deal-tags"]}),a("")}}),u=mt({mutationFn:async f=>{const{error:y}=await q.from("deal_tags").delete().eq("id",f);if(y)throw y},onSuccess:()=>{n.invalidateQueries({queryKey:["deal-tags",s]})}}),h=()=>{const f=r.trim();f&&(o.some(y=>y.tag.toLowerCase()===f.toLowerCase())||d.mutate(f))},m=o.map(f=>f.tag.toLowerCase()),p=c.filter(f=>f.toLowerCase().includes(r.toLowerCase())&&!m.includes(f.toLowerCase())).slice(0,5);return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[o.map(f=>e.jsxs(Oe,{variant:"secondary",className:"gap-1 text-xs",children:[f.tag,e.jsx("button",{type:"button",onClick:()=>u.mutate(f.id),className:"ml-0.5 hover:text-destructive",children:e.jsx(Qn,{className:"h-3 w-3"})})]},f.id)),!i&&e.jsxs("button",{type:"button",onClick:()=>l(!0),className:"flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground px-2 py-0.5 rounded border border-dashed border-border hover:border-primary transition-colors",children:[e.jsx(rn,{className:"h-3 w-3"})," Add tag"]})]}),i&&e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx(xe,{value:r,onChange:f=>a(f.target.value),onKeyDown:f=>{f.key==="Enter"&&(f.preventDefault(),h()),f.key==="Escape"&&(l(!1),a(""))},placeholder:"Type tag name...",className:"h-8 text-xs flex-1",autoFocus:!0}),e.jsx("button",{type:"button",onClick:h,disabled:!r.trim()||d.isPending,className:"h-8 px-3 rounded-md bg-primary text-primary-foreground text-xs font-medium disabled:opacity-50 shrink-0",children:"Add"}),e.jsx("button",{type:"button",onClick:()=>{l(!1),a("")},className:"h-8 px-2 rounded-md bg-muted text-muted-foreground text-xs shrink-0",children:"Cancel"})]}),r&&p.length>0&&e.jsx("div",{className:"absolute z-20 w-full mt-1 bg-background border rounded shadow-lg max-h-32 overflow-y-auto",children:p.map(f=>e.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-xs hover:bg-muted active:bg-muted",onClick:y=>{y.preventDefault(),d.mutate(f)},children:f},f))})]})]})}function IWn(s){return at({queryKey:["deal-files",s],queryFn:async()=>{const{data:t,error:n}=await q.from("deal_files").select("id, deal_id, owner_user_id, file_name, file_size, file_type, storage_path, visible_on_portal, client_visible, compliance_item_id, version_no, is_current, source, source_ref, created_at").eq("deal_id",s).eq("is_current",!0).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function DWn(){const s=ha(),t=Bt();return mt({mutationFn:async({dealId:n,file:r})=>{if(!s)throw new Error("Not authenticated");const a=r.name.split(".").pop(),i=`${s}/${n}/${crypto.randomUUID()}.${a}`,{error:l}=await q.storage.from("deal-files").upload(i,r);if(l)throw l;const{data:o,error:c}=await q.from("deal_files").insert({deal_id:n,owner_user_id:s,file_name:r.name,file_size:r.size,file_type:r.type||null,storage_path:i,source:"levelup"}).select().single();if(c)throw c;return o},onSuccess:(n,r)=>{t.invalidateQueries({queryKey:["deal-files",r.dealId]})}})}function RWn(){const s=Bt();return mt({mutationFn:async({fileId:t,storagePath:n,dealId:r})=>{await q.storage.from("deal-files").remove([n]);const{error:a}=await q.from("deal_files").delete().eq("id",t);if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["deal-files",t]})}})}function FWn(){const s=Bt();return mt({mutationFn:async({fileId:t,visible:n,dealId:r})=>{const{error:a}=await q.from("deal_files").update({visible_on_portal:n}).eq("id",t);if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["deal-files",t]})}})}async function OWn(s){const{data:t,error:n}=await q.storage.from("deal-files").createSignedUrl(s,3600);if(n)throw n;return t.signedUrl}const zWn={pending:"bg-muted text-muted-foreground",submitted:"bg-amber-500/15 text-amber-600",approved:"bg-emerald-500/15 text-emerald-600",rejected:"bg-destructive/15 text-destructive"},BWn={pending:"Needed",submitted:"In review",approved:"Approved",rejected:"Changes requested"};function sss({dealId:s,canReview:t=!1,canUpload:n=!1}){const{data:r=[],isLoading:a}=dRt(s),{data:i=[]}=AEs(s),l=SEs(),o=EEs(),[c,d]=_.useState(null),[u,h]=_.useState(""),[m,p]=_.useState(null),[f,y]=_.useState(null),v=_.useRef(null),g=_.useRef(null),b=C=>{var E;g.current=C,(E=v.current)==null||E.click()},j=async C=>{const E=g.current;if(!(!C||!E)){y(E.id);try{await o.mutateAsync({item:E,file:C}),se.success("Document uploaded for review")}catch(P){se.error(P.message||"Upload failed")}finally{y(null),g.current=null,v.current&&(v.current.value="")}}},S=async C=>{try{await l.mutateAsync({item:C,status:"rejected",note:u.trim()||"Changes requested"}),d(null),h("")}catch(E){se.error(E.message||"Could not update item")}};return a?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(Ct,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):r.length===0?e.jsx("p",{className:"py-6 text-center text-sm text-muted-foreground",children:"No compliance checklist on this deal yet."}):e.jsxs("div",{className:"space-y-2",children:[e.jsx("input",{ref:v,type:"file",className:"hidden",onChange:C=>{var E;return j((E=C.target.files)==null?void 0:E[0])}}),r.map(C=>{var I;const E=i.filter(D=>D.compliance_item_id===C.id),P=E.find(D=>D.is_current)||E[0],M=C.status!=="approved"&&C.due_date&&C.due_dateD.value===C.phase))==null?void 0:I.label)||C.phase}),C.due_date&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Gr,{className:"h-3 w-3"})," Due ",C.due_date]}),E.length>0&&e.jsxs("button",{className:"flex items-center gap-1 hover:text-foreground",onClick:()=>p(m===C.id?null:C.id),children:[e.jsx(R_,{className:"h-3 w-3"})," ",E.length," version",E.length>1?"s":""]})]}),C.status==="rejected"&&C.review_note&&e.jsx("p",{className:"mt-2 rounded-md bg-destructive/10 p-2 text-xs text-destructive",children:C.review_note})]}),e.jsxs("div",{className:"flex flex-shrink-0 items-center gap-1",children:[P&&e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>Opt(P.storage_path),children:e.jsx(li,{className:"h-4 w-4"})}),n&&C.requires_document&&e.jsx(B,{variant:"outline",size:"sm",onClick:()=>b(C),disabled:f===C.id,children:f===C.id?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(AQ,{className:"mr-1 h-4 w-4"}),P?"Replace":"Upload"]})}),t&&e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"ghost",size:"icon",title:"Approve",onClick:()=>l.mutate({item:C,status:"approved",note:null}),children:e.jsx(Er,{className:"h-4 w-4 text-emerald-600"})}),e.jsx(B,{variant:"ghost",size:"icon",title:"Request changes",onClick:()=>{d(c===C.id?null:C.id),h("")},children:e.jsx(Rd,{className:"h-4 w-4 text-destructive"})})]})]})]}),c===C.id&&e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(Ms,{rows:2,placeholder:"What needs to change?",value:u,onChange:D=>h(D.target.value)}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{variant:"outline",size:"sm",onClick:()=>d(null),children:"Cancel"}),e.jsx(B,{size:"sm",onClick:()=>S(C),children:"Send back to agent"})]})]}),m===C.id&&E.length>0&&e.jsx("div",{className:"mt-3 space-y-1 border-t pt-2",children:E.map(D=>e.jsxs("button",{onClick:()=>Opt(D.storage_path),className:"flex w-full items-center justify-between rounded px-2 py-1 text-left text-xs hover:bg-muted",children:[e.jsxs("span",{className:"truncate",children:["v",D.version_no," — ",D.file_name]}),e.jsx("span",{className:"text-muted-foreground",children:new Date(D.created_at).toLocaleDateString()})]},D.id))})]},C.id)})]})}function nss({dealId:s,brokerageId:t,role:n,counterpartName:r}){const{user:a}=hs(),{data:i=[],isLoading:l}=TEs(s),o=MEs(),c=PEs(),[d,u]=_.useState(""),h=_.useRef(null),m=_.useRef(null);_.useEffect(()=>{var f;(f=h.current)==null||f.scrollIntoView({block:"nearest"})},[i.length]),_.useEffect(()=>{if(l||m.current===s)return;i.some(y=>y.sender_role!==n&&!y.read_at)&&(m.current=s,c.mutate({dealId:s,senderRole:n}))},[s,l,i,n,c]);const p=async()=>{const f=d.trim();if(f)try{await o.mutateAsync({dealId:s,brokerageId:t,body:f,senderRole:n}),u(""),se.success("Message sent — an email notification is on the way")}catch(y){se.error(y.message||"Could not send the message")}};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("p",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(ln,{className:"h-3.5 w-3.5"}),n==="staff"?`Private thread with ${r||"the agent"} — they get an email for every message.`:"Private thread with your transaction team — they get an email for every message."]}),e.jsxs("div",{className:"max-h-[320px] space-y-3 overflow-y-auto rounded-lg border bg-muted/20 p-3",children:[l?e.jsx("div",{className:"flex justify-center py-6",children:e.jsx(Ct,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):i.length===0?e.jsx("p",{className:"py-6 text-center text-sm text-muted-foreground",children:"No messages yet. Start the conversation about what this file still needs."}):i.map(f=>{const y=f.sender_user_id===(a==null?void 0:a.id);return e.jsx("div",{className:`flex ${y?"justify-end":"justify-start"}`,children:e.jsxs("div",{className:`max-w-[85%] rounded-lg px-3 py-2 text-sm ${y?"bg-primary text-primary-foreground":"bg-background border"}`,children:[e.jsxs("p",{className:`mb-1 text-[11px] ${y?"text-primary-foreground/75":"text-muted-foreground"}`,children:[y?"You":f.sender_name||(f.sender_role==="staff"?"Transaction team":"Agent")," ·"," ",new Date(f.created_at).toLocaleString("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})]}),e.jsx("p",{className:"whitespace-pre-wrap leading-relaxed",children:f.body})]})},f.id)}),e.jsx("div",{ref:h})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ms,{value:d,onChange:f=>u(f.target.value),rows:3,placeholder:n==="staff"?"e.g. Please upload the signed disclosure — we need it before Friday.":"Ask a question or let the team know what you uploaded…"}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(B,{onClick:p,disabled:!d.trim()||o.isPending,className:"gap-2",children:[o.isPending?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Or,{className:"h-4 w-4"}),"Send & notify"]})})]})]})}function UWn({dealId:s}){var a;const{data:t=[]}=dRt(s);if(t.length===0)return null;const n=((a=t[0])==null?void 0:a.brokerage_id)??null,r=t.filter(i=>i.status==="approved").length;return e.jsxs("div",{className:"rounded-lg border p-3",children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Dm,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm font-medium",children:"Brokerage compliance"})]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[r," of ",t.length," approved"]})]}),e.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:"This file is shared with your brokerage's compliance team. Upload each required document below."}),e.jsx(sss,{dealId:s,canUpload:!0}),n&&e.jsxs("div",{className:"mt-4 border-t pt-4",children:[e.jsx("p",{className:"mb-2 text-sm font-medium",children:"Messages with your transaction team"}),e.jsx(nss,{dealId:s,brokerageId:n,role:"agent"})]})]})}/*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */var kYe=function(s,t){return kYe=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var a in r)r.hasOwnProperty(a)&&(n[a]=r[a])},kYe(s,t)};function ci(s,t){kYe(s,t);function n(){this.constructor=s}s.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}var uc=function(){return uc=Object.assign||function(t){for(var n,r=1,a=arguments.length;r0&&i[i.length-1])&&(d[0]===6||d[0]===2)){n=0;continue}if(d[0]===3&&(!i||d[1]>i[0]&&d[1]>2],t+=mq[(s[r]&3)<<4|s[r+1]>>4],t+=mq[(s[r+1]&15)<<2|s[r+2]>>6],t+=mq[s[r+2]&63];return n%3===2?t=t.substring(0,t.length-1)+"=":n%3===1&&(t=t.substring(0,t.length-2)+"=="),t},LSt=function(s){var t=s.length*.75,n=s.length,r,a=0,i,l,o,c;s[s.length-1]==="="&&(t--,s[s.length-2]==="="&&t--);var d=new Uint8Array(t);for(r=0;r>4,d[a++]=(l&15)<<4|o>>2,d[a++]=(o&3)<<6|c&63;return d},VWn=/^(data)?:?([\w\/\+]+)?;?(charset=[\w-]+|base64)?.*,/i,HWn=function(s){var t=s.trim(),n=t.substring(0,100),r=n.match(VWn);if(!r)return LSt(t);var a=r[0],i=t.substring(a.length);return LSt(i)},cc=function(s){return s.charCodeAt(0)},GWn=function(s){return s.codePointAt(0)},tie=function(s,t){return Jk(s.toString(16),t,"0").toUpperCase()},L8e=function(s){return tie(s,2)},aE=function(s){return String.fromCharCode(s)},WWn=function(s){return aE(parseInt(s,16))},Jk=function(s,t,n){for(var r="",a=0,i=t-s.length;a=55296&&n<=56319&&s.length>a&&(r=s.charCodeAt(a),r>=56320&&r<=57343&&(i=2)),[s.slice(t,t+i),i]},ZWn=function(s){for(var t=[],n=0,r=s.length;nn&&d(),l+=m,o+=p}}return d(),c},JWn=/^D:(\d\d\d\d)(\d\d)?(\d\d)?(\d\d)?(\d\d)?(\d\d)?([+\-Z])?(\d\d)?'?(\d\d)?'?$/,lss=function(s){var t=s.match(JWn);if(t){var n=t[1],r=t[2],a=r===void 0?"01":r,i=t[3],l=i===void 0?"01":i,o=t[4],c=o===void 0?"00":o,d=t[5],u=d===void 0?"00":d,h=t[6],m=h===void 0?"00":h,p=t[7],f=p===void 0?"Z":p,y=t[8],v=y===void 0?"00":y,g=t[9],b=g===void 0?"00":g,j=f==="Z"?"Z":""+f+v+":"+b,S=new Date(n+"-"+a+"-"+l+"T"+c+":"+u+":"+m+j);return S}},iat=function(s,t){for(var n,r=0,a;r=0&&s<=65535},dKn=function(s){return s>=65536&&s<=1114111},dss=function(s){return Math.floor((s-65536)/1024)+55296},uss=function(s){return(s-65536)%1024+56320},_P;(function(s){s.BigEndian="BigEndian",s.LittleEndian="LittleEndian"})(_P||(_P={}));var SZ="�".codePointAt(0),hss=function(s,t){if(t===void 0&&(t=!0),s.length<=1)return String.fromCodePoint(SZ);for(var n=t?hKn(s):_P.BigEndian,r=t?2:0,a=[];s.length-r>=2;){var i=DSt(s[r++],s[r++],n);if(uKn(i))if(s.length-r<2)a.push(SZ);else{var l=DSt(s[r++],s[r++],n);ISt(l)?a.push(i,l):a.push(SZ)}else ISt(i)?(r+=2,a.push(SZ)):a.push(i)}return r=55296&&s<=56319},ISt=function(s){return s>=56320&&s<=57343},DSt=function(s,t,n){if(n===_P.LittleEndian)return t<<8|s;if(n===_P.BigEndian)return s<<8|t;throw new Error("Invalid byteOrder: "+n)},hKn=function(s){return mss(s)?_P.BigEndian:pss(s)?_P.LittleEndian:_P.BigEndian},mss=function(s){return s[0]===254&&s[1]===255},pss=function(s){return s[0]===255&&s[1]===254},fss=function(s){return mss(s)||pss(s)},mKn=function(s){var t=String(s);if(Math.abs(s)<1){var n=parseInt(s.toString().split("e-")[1]);if(n){var r=s<0;r&&(s*=-1),s*=Math.pow(10,n-1),t="0."+new Array(n).join("0")+s.toString().substring(2),r&&(t="-"+t)}}else{var n=parseInt(s.toString().split("+")[1]);n>20&&(n-=20,s/=Math.pow(10,n),t=s.toString()+new Array(n+1).join("0"))}return t},OCe=function(s){return Math.ceil(s.toString(2).length/8)},KB=function(s){for(var t=new Uint8Array(OCe(s)),n=1;n<=t.length;n++)t[n-1]=s>>(t.length-n)*8;return t},nie=function(s){throw new Error(s)},VE={};(function(s){var t=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Int32Array<"u";function n(i,l){return Object.prototype.hasOwnProperty.call(i,l)}s.assign=function(i){for(var l=Array.prototype.slice.call(arguments,1);l.length;){var o=l.shift();if(o){if(typeof o!="object")throw new TypeError(o+"must be non-object");for(var c in o)n(o,c)&&(i[c]=o[c])}}return i},s.shrinkBuf=function(i,l){return i.length===l?i:i.subarray?i.subarray(0,l):(i.length=l,i)};var r={arraySet:function(i,l,o,c,d){if(l.subarray&&i.subarray){i.set(l.subarray(o,o+c),d);return}for(var u=0;u=0;)s[t]=0}var gKn=0,xss=1,yKn=2,vKn=3,bKn=258,oat=29,aie=256,Ese=aie+1+oat,G$=30,lat=19,gss=2*Ese+1,PF=15,tBe=16,_Kn=7,cat=256,yss=16,vss=17,bss=18,CYe=[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],zCe=[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],wKn=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],_ss=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],jKn=512,J3=new Array((Ese+2)*2);dK(J3);var uee=new Array(G$*2);dK(uee);var Tse=new Array(jKn);dK(Tse);var Mse=new Array(bKn-vKn+1);dK(Mse);var dat=new Array(oat);dK(dat);var c6e=new Array(G$);dK(c6e);function sBe(s,t,n,r,a){this.static_tree=s,this.extra_bits=t,this.extra_base=n,this.elems=r,this.max_length=a,this.has_stree=s&&s.length}var wss,jss,Nss;function nBe(s,t){this.dyn_tree=s,this.max_code=0,this.stat_desc=t}function kss(s){return s<256?Tse[s]:Tse[256+(s>>>7)]}function Pse(s,t){s.pending_buf[s.pending++]=t&255,s.pending_buf[s.pending++]=t>>>8&255}function A_(s,t,n){s.bi_valid>tBe-n?(s.bi_buf|=t<>tBe-s.bi_valid,s.bi_valid+=n-tBe):(s.bi_buf|=t<>>=1,n<<=1;while(--t>0);return n>>>1}function NKn(s){s.bi_valid===16?(Pse(s,s.bi_buf),s.bi_buf=0,s.bi_valid=0):s.bi_valid>=8&&(s.pending_buf[s.pending++]=s.bi_buf&255,s.bi_buf>>=8,s.bi_valid-=8)}function kKn(s,t){var n=t.dyn_tree,r=t.max_code,a=t.stat_desc.static_tree,i=t.stat_desc.has_stree,l=t.stat_desc.extra_bits,o=t.stat_desc.extra_base,c=t.stat_desc.max_length,d,u,h,m,p,f,y=0;for(m=0;m<=PF;m++)s.bl_count[m]=0;for(n[s.heap[s.heap_max]*2+1]=0,d=s.heap_max+1;dc&&(m=c,y++),n[u*2+1]=m,!(u>r)&&(s.bl_count[m]++,p=0,u>=o&&(p=l[u-o]),f=n[u*2],s.opt_len+=f*(m+p),i&&(s.static_len+=f*(a[u*2+1]+p)));if(y!==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]--,y-=2}while(y>0);for(m=c;m!==0;m--)for(u=s.bl_count[m];u!==0;)h=s.heap[--d],!(h>r)&&(n[h*2+1]!==m&&(s.opt_len+=(m-n[h*2+1])*n[h*2],n[h*2+1]=m),u--)}}function Css(s,t,n){var r=new Array(PF+1),a=0,i,l;for(i=1;i<=PF;i++)r[i]=a=a+n[i-1]<<1;for(l=0;l<=t;l++){var o=s[l*2+1];o!==0&&(s[l*2]=Sss(r[o]++,o))}}function SKn(){var s,t,n,r,a,i=new Array(PF+1);for(n=0,r=0;r>=7;r8?Pse(s,s.bi_buf):s.bi_valid>0&&(s.pending_buf[s.pending++]=s.bi_buf),s.bi_buf=0,s.bi_valid=0}function CKn(s,t,n,r){Ess(s),Pse(s,n),Pse(s,~n),pKn.arraySet(s.pending_buf,s.window,t,n,s.pending),s.pending+=n}function OSt(s,t,n,r){var a=t*2,i=n*2;return s[a]>1;l>=1;l--)rBe(s,n,l);d=i;do l=s.heap[1],s.heap[1]=s.heap[s.heap_len--],rBe(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++,rBe(s,n,1);while(s.heap_len>=2);s.heap[--s.heap_max]=s.heap[1],kKn(s,t),Css(n,c,s.bl_count)}function BSt(s,t,n){var r,a=-1,i,l=t[0*2+1],o=0,c=7,d=4;for(l===0&&(c=138,d=3),t[(n+1)*2+1]=65535,r=0;r<=n;r++)i=l,l=t[(r+1)*2+1],!(++o=3&&s.bl_tree[_ss[t]*2+1]===0;t--);return s.opt_len+=3*(t+1)+5+5+4,t}function EKn(s,t,n,r){var a;for(A_(s,t-257,5),A_(s,n-1,5),A_(s,r-4,4),a=0;a>>=1)if(t&1&&s.dyn_ltree[n*2]!==0)return RSt;if(s.dyn_ltree[9*2]!==0||s.dyn_ltree[10*2]!==0||s.dyn_ltree[13*2]!==0)return FSt;for(n=32;n0?(s.strm.data_type===xKn&&(s.strm.data_type=TKn(s)),AYe(s,s.l_desc),AYe(s,s.d_desc),l=AKn(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?Tss(s,t,n,r):s.strategy===fKn||i===a?(A_(s,(xss<<1)+(r?1:0),3),zSt(s,J3,uee)):(A_(s,(yKn<<1)+(r?1:0),3),EKn(s,s.l_desc.max_code+1,s.d_desc.max_code+1,l+1),zSt(s,s.dyn_ltree,s.dyn_dtree)),Ass(s),r&&Ess(s)}function IKn(s,t,n){return s.pending_buf[s.d_buf+s.last_lit*2]=t>>>8&255,s.pending_buf[s.d_buf+s.last_lit*2+1]=t&255,s.pending_buf[s.l_buf+s.last_lit]=n&255,s.last_lit++,t===0?s.dyn_ltree[n*2]++:(s.matches++,t--,s.dyn_ltree[(Mse[n]+aie+1)*2]++,s.dyn_dtree[kss(t)*2]++),s.last_lit===s.lit_bufsize-1}cK._tr_init=MKn;cK._tr_stored_block=Tss;cK._tr_flush_block=LKn;cK._tr_tally=IKn;cK._tr_align=PKn;function DKn(s,t,n,r){for(var a=s&65535|0,i=s>>>16&65535|0,l=0;n!==0;){l=n>2e3?2e3:n,n-=l;do a=a+t[r++]|0,i=i+a|0;while(--l);a%=65521,i%=65521}return a|i<<16|0}var Mss=DKn;function RKn(){for(var s,t=[],n=0;n<256;n++){s=n;for(var r=0;r<8;r++)s=s&1?3988292384^s>>>1:s>>>1;t[n]=s}return t}var FKn=RKn();function OKn(s,t,n,r){var a=FKn,i=r+n;s^=-1;for(var l=r;l>>8^a[(s^t[l])&255];return s^-1}var Pss=OKn,uat={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"},db=VE,wN=cK,Lss=Mss,e6=Pss,zKn=uat,vz=0,BKn=1,UKn=3,wP=4,$St=5,C4=0,VSt=1,jN=-2,qKn=-3,aBe=-5,$Kn=-1,VKn=1,gde=2,HKn=3,GKn=4,WKn=0,KKn=2,I8e=8,YKn=9,ZKn=15,XKn=8,QKn=29,JKn=256,EYe=JKn+1+QKn,eYn=30,tYn=19,sYn=2*EYe+1,nYn=15,mu=3,EM=258,NS=EM+mu+1,rYn=32,D8e=42,TYe=69,BCe=73,UCe=91,qCe=103,LF=113,YX=666,_0=1,iie=2,S9=3,uK=4,aYn=3;function TM(s,t){return s.msg=zKn[t],t}function HSt(s){return(s<<1)-(s>4?9:0)}function P6(s){for(var t=s.length;--t>=0;)s[t]=0}function t6(s){var t=s.state,n=t.pending;n>s.avail_out&&(n=s.avail_out),n!==0&&(db.arraySet(s.output,t.pending_buf,t.pending_out,n,s.next_out),s.next_out+=n,t.pending_out+=n,s.total_out+=n,s.avail_out-=n,t.pending-=n,t.pending===0&&(t.pending_out=0))}function yv(s,t){wN._tr_flush_block(s,s.block_start>=0?s.block_start:-1,s.strstart-s.block_start,t),s.block_start=s.strstart,t6(s.strm)}function Hu(s,t){s.pending_buf[s.pending++]=t}function CZ(s,t){s.pending_buf[s.pending++]=t>>>8&255,s.pending_buf[s.pending++]=t&255}function iYn(s,t,n,r){var a=s.avail_in;return a>r&&(a=r),a===0?0:(s.avail_in-=a,db.arraySet(t,s.input,s.next_in,a,n),s.state.wrap===1?s.adler=Lss(s.adler,t,a,n):s.state.wrap===2&&(s.adler=e6(s.adler,t,a,n)),s.next_in+=a,s.total_in+=a,a)}function Iss(s,t){var n=s.max_chain_length,r=s.strstart,a,i,l=s.prev_length,o=s.nice_match,c=s.strstart>s.w_size-NS?s.strstart-(s.w_size-NS):0,d=s.window,u=s.w_mask,h=s.prev,m=s.strstart+EM,p=d[r+l-1],f=d[r+l];s.prev_length>=s.good_match&&(n>>=2),o>s.lookahead&&(o=s.lookahead);do if(a=t,!(d[a+l]!==f||d[a+l-1]!==p||d[a]!==d[r]||d[++a]!==d[r+1])){r+=2,a++;do;while(d[++r]===d[++a]&&d[++r]===d[++a]&&d[++r]===d[++a]&&d[++r]===d[++a]&&d[++r]===d[++a]&&d[++r]===d[++a]&&d[++r]===d[++a]&&d[++r]===d[++a]&&rl){if(s.match_start=t,l=i,i>=o)break;p=d[r+l-1],f=d[r+l]}}while((t=h[t&u])>c&&--n!==0);return l<=s.lookahead?l:s.lookahead}function C9(s){var t=s.w_size,n,r,a,i,l;do{if(i=s.window_size-s.lookahead-s.strstart,s.strstart>=t+(t-NS)){db.arraySet(s.window,s.window,t,t,0),s.match_start-=t,s.strstart-=t,s.block_start-=t,r=s.hash_size,n=r;do a=s.head[--n],s.head[n]=a>=t?a-t:0;while(--r);r=t,n=r;do a=s.prev[--n],s.prev[n]=a>=t?a-t:0;while(--r);i+=t}if(s.strm.avail_in===0)break;if(r=iYn(s.strm,s.window,s.strstart+s.lookahead,i),s.lookahead+=r,s.lookahead+s.insert>=mu)for(l=s.strstart-s.insert,s.ins_h=s.window[l],s.ins_h=(s.ins_h<s.pending_buf_size-5&&(n=s.pending_buf_size-5);;){if(s.lookahead<=1){if(C9(s),s.lookahead===0&&t===vz)return _0;if(s.lookahead===0)break}s.strstart+=s.lookahead,s.lookahead=0;var r=s.block_start+n;if((s.strstart===0||s.strstart>=r)&&(s.lookahead=s.strstart-r,s.strstart=r,yv(s,!1),s.strm.avail_out===0)||s.strstart-s.block_start>=s.w_size-NS&&(yv(s,!1),s.strm.avail_out===0))return _0}return s.insert=0,t===wP?(yv(s,!0),s.strm.avail_out===0?S9:uK):(s.strstart>s.block_start&&(yv(s,!1),s.strm.avail_out===0),_0)}function iBe(s,t){for(var n,r;;){if(s.lookahead=mu&&(s.ins_h=(s.ins_h<=mu)if(r=wN._tr_tally(s,s.strstart-s.match_start,s.match_length-mu),s.lookahead-=s.match_length,s.match_length<=s.max_lazy_match&&s.lookahead>=mu){s.match_length--;do s.strstart++,s.ins_h=(s.ins_h<=mu&&(s.ins_h=(s.ins_h<4096)&&(s.match_length=mu-1)),s.prev_length>=mu&&s.match_length<=s.prev_length){a=s.strstart+s.lookahead-mu,r=wN._tr_tally(s,s.strstart-1-s.prev_match,s.prev_length-mu),s.lookahead-=s.prev_length-1,s.prev_length-=2;do++s.strstart<=a&&(s.ins_h=(s.ins_h<=mu&&s.strstart>0&&(a=s.strstart-1,r=l[a],r===l[++a]&&r===l[++a]&&r===l[++a])){i=s.strstart+EM;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>=mu?(n=wN._tr_tally(s,1,s.match_length-mu),s.lookahead-=s.match_length,s.strstart+=s.match_length,s.match_length=0):(n=wN._tr_tally(s,0,s.window[s.strstart]),s.lookahead--,s.strstart++),n&&(yv(s,!1),s.strm.avail_out===0))return _0}return s.insert=0,t===wP?(yv(s,!0),s.strm.avail_out===0?S9:uK):s.last_lit&&(yv(s,!1),s.strm.avail_out===0)?_0:iie}function cYn(s,t){for(var n;;){if(s.lookahead===0&&(C9(s),s.lookahead===0)){if(t===vz)return _0;break}if(s.match_length=0,n=wN._tr_tally(s,0,s.window[s.strstart]),s.lookahead--,s.strstart++,n&&(yv(s,!1),s.strm.avail_out===0))return _0}return s.insert=0,t===wP?(yv(s,!0),s.strm.avail_out===0?S9:uK):s.last_lit&&(yv(s,!1),s.strm.avail_out===0)?_0:iie}function S5(s,t,n,r,a){this.good_length=s,this.max_lazy=t,this.nice_length=n,this.max_chain=r,this.func=a}var pq;pq=[new S5(0,0,0,0,oYn),new S5(4,4,8,4,iBe),new S5(4,5,16,8,iBe),new S5(4,6,32,32,iBe),new S5(4,4,16,16,YB),new S5(8,16,32,32,YB),new S5(8,16,128,128,YB),new S5(8,32,128,256,YB),new S5(32,128,258,1024,YB),new S5(32,258,258,4096,YB)];function dYn(s){s.window_size=2*s.w_size,P6(s.head),s.max_lazy_match=pq[s.level].max_lazy,s.good_match=pq[s.level].good_length,s.nice_match=pq[s.level].nice_length,s.max_chain_length=pq[s.level].max_chain,s.strstart=0,s.block_start=0,s.lookahead=0,s.insert=0,s.match_length=s.prev_length=mu-1,s.match_available=0,s.ins_h=0}function uYn(){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=I8e,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 db.Buf16(sYn*2),this.dyn_dtree=new db.Buf16((2*eYn+1)*2),this.bl_tree=new db.Buf16((2*tYn+1)*2),P6(this.dyn_ltree),P6(this.dyn_dtree),P6(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new db.Buf16(nYn+1),this.heap=new db.Buf16(2*EYe+1),P6(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new db.Buf16(2*EYe+1),P6(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function Dss(s){var t;return!s||!s.state?TM(s,jN):(s.total_in=s.total_out=0,s.data_type=KKn,t=s.state,t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap?D8e:LF,s.adler=t.wrap===2?0:1,t.last_flush=vz,wN._tr_init(t),C4)}function Rss(s){var t=Dss(s);return t===C4&&dYn(s.state),t}function hYn(s,t){return!s||!s.state||s.state.wrap!==2?jN:(s.state.gzhead=t,C4)}function Fss(s,t,n,r,a,i){if(!s)return jN;var l=1;if(t===$Kn&&(t=6),r<0?(l=0,r=-r):r>15&&(l=2,r-=16),a<1||a>YKn||n!==I8e||r<8||r>15||t<0||t>9||i<0||i>GKn)return TM(s,jN);r===8&&(r=9);var o=new uYn;return s.state=o,o.strm=s,o.wrap=l,o.gzhead=null,o.w_bits=r,o.w_size=1<$St||t<0)return s?TM(s,jN):jN;if(r=s.state,!s.output||!s.input&&s.avail_in!==0||r.status===YX&&t!==wP)return TM(s,s.avail_out===0?aBe:jN);if(r.strm=s,n=r.last_flush,r.last_flush=t,r.status===D8e)if(r.wrap===2)s.adler=0,Hu(r,31),Hu(r,139),Hu(r,8),r.gzhead?(Hu(r,(r.gzhead.text?1:0)+(r.gzhead.hcrc?2:0)+(r.gzhead.extra?4:0)+(r.gzhead.name?8:0)+(r.gzhead.comment?16:0)),Hu(r,r.gzhead.time&255),Hu(r,r.gzhead.time>>8&255),Hu(r,r.gzhead.time>>16&255),Hu(r,r.gzhead.time>>24&255),Hu(r,r.level===9?2:r.strategy>=gde||r.level<2?4:0),Hu(r,r.gzhead.os&255),r.gzhead.extra&&r.gzhead.extra.length&&(Hu(r,r.gzhead.extra.length&255),Hu(r,r.gzhead.extra.length>>8&255)),r.gzhead.hcrc&&(s.adler=e6(s.adler,r.pending_buf,r.pending,0)),r.gzindex=0,r.status=TYe):(Hu(r,0),Hu(r,0),Hu(r,0),Hu(r,0),Hu(r,0),Hu(r,r.level===9?2:r.strategy>=gde||r.level<2?4:0),Hu(r,aYn),r.status=LF);else{var l=I8e+(r.w_bits-8<<4)<<8,o=-1;r.strategy>=gde||r.level<2?o=0:r.level<6?o=1:r.level===6?o=2:o=3,l|=o<<6,r.strstart!==0&&(l|=rYn),l+=31-l%31,r.status=LF,CZ(r,l),r.strstart!==0&&(CZ(r,s.adler>>>16),CZ(r,s.adler&65535)),s.adler=1}if(r.status===TYe)if(r.gzhead.extra){for(a=r.pending;r.gzindex<(r.gzhead.extra.length&65535)&&!(r.pending===r.pending_buf_size&&(r.gzhead.hcrc&&r.pending>a&&(s.adler=e6(s.adler,r.pending_buf,r.pending-a,a)),t6(s),a=r.pending,r.pending===r.pending_buf_size));)Hu(r,r.gzhead.extra[r.gzindex]&255),r.gzindex++;r.gzhead.hcrc&&r.pending>a&&(s.adler=e6(s.adler,r.pending_buf,r.pending-a,a)),r.gzindex===r.gzhead.extra.length&&(r.gzindex=0,r.status=BCe)}else r.status=BCe;if(r.status===BCe)if(r.gzhead.name){a=r.pending;do{if(r.pending===r.pending_buf_size&&(r.gzhead.hcrc&&r.pending>a&&(s.adler=e6(s.adler,r.pending_buf,r.pending-a,a)),t6(s),a=r.pending,r.pending===r.pending_buf_size)){i=1;break}r.gzindexa&&(s.adler=e6(s.adler,r.pending_buf,r.pending-a,a)),i===0&&(r.gzindex=0,r.status=UCe)}else r.status=UCe;if(r.status===UCe)if(r.gzhead.comment){a=r.pending;do{if(r.pending===r.pending_buf_size&&(r.gzhead.hcrc&&r.pending>a&&(s.adler=e6(s.adler,r.pending_buf,r.pending-a,a)),t6(s),a=r.pending,r.pending===r.pending_buf_size)){i=1;break}r.gzindexa&&(s.adler=e6(s.adler,r.pending_buf,r.pending-a,a)),i===0&&(r.status=qCe)}else r.status=qCe;if(r.status===qCe&&(r.gzhead.hcrc?(r.pending+2>r.pending_buf_size&&t6(s),r.pending+2<=r.pending_buf_size&&(Hu(r,s.adler&255),Hu(r,s.adler>>8&255),s.adler=0,r.status=LF)):r.status=LF),r.pending!==0){if(t6(s),s.avail_out===0)return r.last_flush=-1,C4}else if(s.avail_in===0&&HSt(t)<=HSt(n)&&t!==wP)return TM(s,aBe);if(r.status===YX&&s.avail_in!==0)return TM(s,aBe);if(s.avail_in!==0||r.lookahead!==0||t!==vz&&r.status!==YX){var c=r.strategy===gde?cYn(r,t):r.strategy===HKn?lYn(r,t):pq[r.level].func(r,t);if((c===S9||c===uK)&&(r.status=YX),c===_0||c===S9)return s.avail_out===0&&(r.last_flush=-1),C4;if(c===iie&&(t===BKn?wN._tr_align(r):t!==$St&&(wN._tr_stored_block(r,0,0,!1),t===UKn&&(P6(r.head),r.lookahead===0&&(r.strstart=0,r.block_start=0,r.insert=0))),t6(s),s.avail_out===0))return r.last_flush=-1,C4}return t!==wP?C4:r.wrap<=0?VSt:(r.wrap===2?(Hu(r,s.adler&255),Hu(r,s.adler>>8&255),Hu(r,s.adler>>16&255),Hu(r,s.adler>>24&255),Hu(r,s.total_in&255),Hu(r,s.total_in>>8&255),Hu(r,s.total_in>>16&255),Hu(r,s.total_in>>24&255)):(CZ(r,s.adler>>>16),CZ(r,s.adler&65535)),t6(s),r.wrap>0&&(r.wrap=-r.wrap),r.pending!==0?C4:VSt)}function fYn(s){var t;return!s||!s.state?jN:(t=s.state.status,t!==D8e&&t!==TYe&&t!==BCe&&t!==UCe&&t!==qCe&&t!==LF&&t!==YX?TM(s,jN):(s.state=null,t===LF?TM(s,qKn):C4))}function xYn(s,t){var n=t.length,r,a,i,l,o,c,d,u;if(!s||!s.state||(r=s.state,l=r.wrap,l===2||l===1&&r.status!==D8e||r.lookahead))return jN;for(l===1&&(s.adler=Lss(s.adler,t,n,0)),r.wrap=0,n>=r.w_size&&(l===0&&(P6(r.head),r.strstart=0,r.block_start=0,r.insert=0),u=new db.Buf8(r.w_size),db.arraySet(u,t,n-r.w_size,r.w_size,0),t=u,n=r.w_size),o=s.avail_in,c=s.next_in,d=s.input,s.avail_in=n,s.next_in=0,s.input=t,C9(r);r.lookahead>=mu;){a=r.strstart,i=r.lookahead-(mu-1);do r.ins_h=(r.ins_h<=252?6:TT>=248?5:TT>=240?4:TT>=224?3:TT>=192?2:1;Lse[254]=Lse[254]=1;bz.string2buf=function(s){var t,n,r,a,i,l=s.length,o=0;for(a=0;a>>6,t[i++]=128|n&63):n<65536?(t[i++]=224|n>>>12,t[i++]=128|n>>>6&63,t[i++]=128|n&63):(t[i++]=240|n>>>18,t[i++]=128|n>>>12&63,t[i++]=128|n>>>6&63,t[i++]=128|n&63);return t};function Bss(s,t){if(t<65534&&(s.subarray&&zss||!s.subarray&&Oss))return String.fromCharCode.apply(null,R8e.shrinkBuf(s,t));for(var n="",r=0;r4){o[r++]=65533,n+=i-1;continue}for(a&=i===2?31:i===3?15:7;i>1&&n1){o[r++]=65533;continue}a<65536?o[r++]=a:(a-=65536,o[r++]=55296|a>>10&1023,o[r++]=56320|a&1023)}return Bss(o,r)};bz.utf8border=function(s,t){var n;for(t=t||s.length,t>s.length&&(t=s.length),n=t-1;n>=0&&(s[n]&192)===128;)n--;return n<0||n===0?t:n+Lse[s[n]]>t?n:t};function gYn(){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 Uss=gYn,hee=OC,mee=VE,MYe=bz,PYe=uat,yYn=Uss,qss=Object.prototype.toString,vYn=0,oBe=4,W$=0,GSt=1,WSt=2,bYn=-1,_Yn=0,wYn=8;function A9(s){if(!(this instanceof A9))return new A9(s);this.options=mee.assign({level:bYn,method:wYn,chunkSize:16384,windowBits:15,memLevel:8,strategy:_Yn,to:""},s||{});var t=this.options;t.raw&&t.windowBits>0?t.windowBits=-t.windowBits:t.gzip&&t.windowBits>0&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new yYn,this.strm.avail_out=0;var n=hee.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(n!==W$)throw new Error(PYe[n]);if(t.header&&hee.deflateSetHeader(this.strm,t.header),t.dictionary){var r;if(typeof t.dictionary=="string"?r=MYe.string2buf(t.dictionary):qss.call(t.dictionary)==="[object ArrayBuffer]"?r=new Uint8Array(t.dictionary):r=t.dictionary,n=hee.deflateSetDictionary(this.strm,r),n!==W$)throw new Error(PYe[n]);this._dict_set=!0}}A9.prototype.push=function(s,t){var n=this.strm,r=this.options.chunkSize,a,i;if(this.ended)return!1;i=t===~~t?t:t===!0?oBe:vYn,typeof s=="string"?n.input=MYe.string2buf(s):qss.call(s)==="[object ArrayBuffer]"?n.input=new Uint8Array(s):n.input=s,n.next_in=0,n.avail_in=n.input.length;do{if(n.avail_out===0&&(n.output=new mee.Buf8(r),n.next_out=0,n.avail_out=r),a=hee.deflate(n,i),a!==GSt&&a!==W$)return this.onEnd(a),this.ended=!0,!1;(n.avail_out===0||n.avail_in===0&&(i===oBe||i===WSt))&&(this.options.to==="string"?this.onData(MYe.buf2binstring(mee.shrinkBuf(n.output,n.next_out))):this.onData(mee.shrinkBuf(n.output,n.next_out)))}while((n.avail_in>0||n.avail_out===0)&&a!==GSt);return i===oBe?(a=hee.deflateEnd(this.strm),this.onEnd(a),this.ended=!0,a===W$):(i===WSt&&(this.onEnd(W$),n.avail_out=0),!0)};A9.prototype.onData=function(s){this.chunks.push(s)};A9.prototype.onEnd=function(s){s===W$&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=mee.flattenChunks(this.chunks)),this.chunks=[],this.err=s,this.msg=this.strm.msg};function hat(s,t){var n=new A9(t);if(n.push(s,!0),n.err)throw n.msg||PYe[n.err];return n.result}function jYn(s,t){return t=t||{},t.raw=!0,hat(s,t)}function NYn(s,t){return t=t||{},t.gzip=!0,hat(s,t)}rie.Deflate=A9;rie.deflate=hat;rie.deflateRaw=jYn;rie.gzip=NYn;var oie={},GS={},yde=30,kYn=12,SYn=function(t,n){var r,a,i,l,o,c,d,u,h,m,p,f,y,v,g,b,j,S,C,E,P,M,I,D,O;r=t.state,a=t.next_in,D=t.input,i=a+(t.avail_in-5),l=t.next_out,O=t.output,o=l-(n-t.avail_out),c=l+(t.avail_out-257),d=r.dmax,u=r.wsize,h=r.whave,m=r.wnext,p=r.window,f=r.hold,y=r.bits,v=r.lencode,g=r.distcode,b=(1<>>24,f>>>=C,y-=C,C=S>>>16&255,C===0)O[l++]=S&65535;else if(C&16){E=S&65535,C&=15,C&&(y>>=C,y-=C),y<15&&(f+=D[a++]<>>24,f>>>=C,y-=C,C=S>>>16&255,C&16){if(P=S&65535,C&=15,yd){t.msg="invalid distance too far back",r.mode=yde;break e}if(f>>>=C,y-=C,C=l-o,P>C){if(C=P-C,C>h&&r.sane){t.msg="invalid distance too far back",r.mode=yde;break e}if(M=0,I=p,m===0){if(M+=u-C,C2;)O[l++]=I[M++],O[l++]=I[M++],O[l++]=I[M++],E-=3;E&&(O[l++]=I[M++],E>1&&(O[l++]=I[M++]))}else{M=l-P;do O[l++]=O[M++],O[l++]=O[M++],O[l++]=O[M++],E-=3;while(E>2);E&&(O[l++]=O[M++],E>1&&(O[l++]=O[M++]))}}else if(C&64){t.msg="invalid distance code",r.mode=yde;break e}else{S=g[(S&65535)+(f&(1<>3,a-=E,y-=E<<3,f&=(1<=1&&V[p]===0;p--);if(f>p&&(f=p),p===0)return i[l++]=1<<24|64<<16|0,i[l++]=1<<24|64<<16|0,c.bits=1,0;for(m=1;m0&&(t===XSt||p!==1))return-1;for(G[1]=0,u=1;uYSt||t===QSt&&b>ZSt)return 1;for(;;){Y=u-v,o[h]O?(Z=$[H+o[h]],ne=I[D+o[h]]):(Z=96,ne=0),S=1<>v)+C]=Y<<24|Z<<16|ne|0;while(C!==0);for(S=1<>=1;if(S!==0?(j&=S-1,j+=S):j=0,h++,--V[u]===0){if(u===p)break;u=n[r+o[h]]}if(u>f&&(j&P)!==E){for(v===0&&(v=f),M+=m,y=u-v,g=1<YSt||t===QSt&&b>ZSt)return 1;E=j&P,i[E]=f<<24|y<<16|M-l|0}}return j!==0&&(i[M+j]=u-v<<24|64<<16|0),c.bits=f,0},ij=VE,LYe=Mss,C5=Pss,PYn=SYn,pee=MYn,LYn=0,$ss=1,Vss=2,JSt=4,IYn=5,vde=6,E9=0,DYn=1,RYn=2,LN=-2,Hss=-3,Gss=-4,FYn=-5,e5t=8,Wss=1,t5t=2,s5t=3,n5t=4,r5t=5,a5t=6,i5t=7,o5t=8,l5t=9,c5t=10,d6e=11,k3=12,cBe=13,d5t=14,dBe=15,u5t=16,h5t=17,m5t=18,p5t=19,bde=20,_de=21,f5t=22,x5t=23,g5t=24,y5t=25,v5t=26,uBe=27,b5t=28,_5t=29,Hp=30,Kss=31,OYn=32,zYn=852,BYn=592,UYn=15,qYn=UYn;function w5t(s){return(s>>>24&255)+(s>>>8&65280)+((s&65280)<<8)+((s&255)<<24)}function $Yn(){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 ij.Buf16(320),this.work=new ij.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function Yss(s){var t;return!s||!s.state?LN:(t=s.state,s.total_in=s.total_out=t.total=0,s.msg="",t.wrap&&(s.adler=t.wrap&1),t.mode=Wss,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new ij.Buf32(zYn),t.distcode=t.distdyn=new ij.Buf32(BYn),t.sane=1,t.back=-1,E9)}function Zss(s){var t;return!s||!s.state?LN:(t=s.state,t.wsize=0,t.whave=0,t.wnext=0,Yss(s))}function Xss(s,t){var n,r;return!s||!s.state||(r=s.state,t<0?(n=0,t=-t):(n=(t>>4)+1,t<48&&(t&=15)),t&&(t<8||t>15))?LN:(r.window!==null&&r.wbits!==t&&(r.window=null),r.wrap=n,r.wbits=t,Zss(s))}function Qss(s,t){var n,r;return s?(r=new $Yn,s.state=r,r.window=null,n=Xss(s,t),n!==E9&&(s.state=null),n):LN}function VYn(s){return Qss(s,qYn)}var j5t=!0,hBe,mBe;function HYn(s){if(j5t){var t;for(hBe=new ij.Buf32(512),mBe=new ij.Buf32(32),t=0;t<144;)s.lens[t++]=8;for(;t<256;)s.lens[t++]=9;for(;t<280;)s.lens[t++]=7;for(;t<288;)s.lens[t++]=8;for(pee($ss,s.lens,0,288,hBe,0,s.work,{bits:9}),t=0;t<32;)s.lens[t++]=5;pee(Vss,s.lens,0,32,mBe,0,s.work,{bits:5}),j5t=!1}s.lencode=hBe,s.lenbits=9,s.distcode=mBe,s.distbits=5}function Jss(s,t,n,r){var a,i=s.state;return i.window===null&&(i.wsize=1<=i.wsize?(ij.arraySet(i.window,t,n-i.wsize,i.wsize,0),i.wnext=0,i.whave=i.wsize):(a=i.wsize-i.wnext,a>r&&(a=r),ij.arraySet(i.window,t,n-r,a,i.wnext),r-=a,r?(ij.arraySet(i.window,t,n-r,r,0),i.wnext=r,i.whave=i.wsize):(i.wnext+=a,i.wnext===i.wsize&&(i.wnext=0),i.whave>>8&255,n.check=C5(n.check,I,2,0),d=0,u=0,n.mode=t5t;break}if(n.flags=0,n.head&&(n.head.done=!1),!(n.wrap&1)||(((d&255)<<8)+(d>>8))%31){s.msg="incorrect header check",n.mode=Hp;break}if((d&15)!==e5t){s.msg="unknown compression method",n.mode=Hp;break}if(d>>>=4,u-=4,P=(d&15)+8,n.wbits===0)n.wbits=P;else if(P>n.wbits){s.msg="invalid window size",n.mode=Hp;break}n.dmax=1<>8&1),n.flags&512&&(I[0]=d&255,I[1]=d>>>8&255,n.check=C5(n.check,I,2,0)),d=0,u=0,n.mode=s5t;case s5t: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=C5(n.check,I,4,0)),d=0,u=0,n.mode=n5t;case n5t:for(;u<16;){if(o===0)break e;o--,d+=r[i++]<>8),n.flags&512&&(I[0]=d&255,I[1]=d>>>8&255,n.check=C5(n.check,I,2,0)),d=0,u=0,n.mode=r5t;case r5t:if(n.flags&1024){for(;u<16;){if(o===0)break e;o--,d+=r[i++]<>>8&255,n.check=C5(n.check,I,2,0)),d=0,u=0}else n.head&&(n.head.extra=null);n.mode=a5t;case a5t: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 Array(n.head.extra_len)),ij.arraySet(n.head.extra,r,i,p,P)),n.flags&512&&(n.check=C5(n.check,r,p,i)),o-=p,i+=p,n.length-=p),n.length))break e;n.length=0,n.mode=i5t;case i5t: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=k3;break;case c5t:for(;u<32;){if(o===0)break e;o--,d+=r[i++]<>>=u&7,u-=u&7,n.mode=uBe;break}for(;u<3;){if(o===0)break e;o--,d+=r[i++]<>>=1,u-=1,d&3){case 0:n.mode=d5t;break;case 1:if(HYn(n),n.mode=bde,t===vde){d>>>=2,u-=2;break e}break;case 2:n.mode=h5t;break;case 3:s.msg="invalid block type",n.mode=Hp}d>>>=2,u-=2;break;case d5t: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=Hp;break}if(n.length=d&65535,d=0,u=0,n.mode=dBe,t===vde)break e;case dBe:n.mode=u5t;case u5t:if(p=n.length,p){if(p>o&&(p=o),p>c&&(p=c),p===0)break e;ij.arraySet(a,r,i,p,l),o-=p,i+=p,c-=p,l+=p,n.length-=p;break}n.mode=k3;break;case h5t: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=Hp;break}n.have=0,n.mode=m5t;case m5t:for(;n.have>>=3,u-=3}for(;n.have<19;)n.lens[V[n.have++]]=0;if(n.lencode=n.lendyn,n.lenbits=7,D={bits:n.lenbits},M=pee(LYn,n.lens,0,19,n.lencode,0,n.work,D),n.lenbits=D.bits,M){s.msg="invalid code lengths set",n.mode=Hp;break}n.have=0,n.mode=p5t;case p5t:for(;n.have>>24,b=v>>>16&255,j=v&65535,!(g<=u);){if(o===0)break e;o--,d+=r[i++]<>>=g,u-=g,n.lens[n.have++]=j;else{if(j===16){for(O=g+2;u>>=g,u-=g,n.have===0){s.msg="invalid bit length repeat",n.mode=Hp;break}P=n.lens[n.have-1],p=3+(d&3),d>>>=2,u-=2}else if(j===17){for(O=g+3;u>>=g,u-=g,P=0,p=3+(d&7),d>>>=3,u-=3}else{for(O=g+7;u>>=g,u-=g,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=Hp;break}for(;p--;)n.lens[n.have++]=P}}if(n.mode===Hp)break;if(n.lens[256]===0){s.msg="invalid code -- missing end-of-block",n.mode=Hp;break}if(n.lenbits=9,D={bits:n.lenbits},M=pee($ss,n.lens,0,n.nlen,n.lencode,0,n.work,D),n.lenbits=D.bits,M){s.msg="invalid literal/lengths set",n.mode=Hp;break}if(n.distbits=6,n.distcode=n.distdyn,D={bits:n.distbits},M=pee(Vss,n.lens,n.nlen,n.ndist,n.distcode,0,n.work,D),n.distbits=D.bits,M){s.msg="invalid distances set",n.mode=Hp;break}if(n.mode=bde,t===vde)break e;case bde:n.mode=_de;case _de: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,PYn(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===k3&&(n.back=-1);break}for(n.back=0;v=n.lencode[d&(1<>>24,b=v>>>16&255,j=v&65535,!(g<=u);){if(o===0)break e;o--,d+=r[i++]<>S)],g=v>>>24,b=v>>>16&255,j=v&65535,!(S+g<=u);){if(o===0)break e;o--,d+=r[i++]<>>=S,u-=S,n.back+=S}if(d>>>=g,u-=g,n.back+=g,n.length=j,b===0){n.mode=v5t;break}if(b&32){n.back=-1,n.mode=k3;break}if(b&64){s.msg="invalid literal/length code",n.mode=Hp;break}n.extra=b&15,n.mode=f5t;case f5t:if(n.extra){for(O=n.extra;u>>=n.extra,u-=n.extra,n.back+=n.extra}n.was=n.length,n.mode=x5t;case x5t:for(;v=n.distcode[d&(1<>>24,b=v>>>16&255,j=v&65535,!(g<=u);){if(o===0)break e;o--,d+=r[i++]<>S)],g=v>>>24,b=v>>>16&255,j=v&65535,!(S+g<=u);){if(o===0)break e;o--,d+=r[i++]<>>=S,u-=S,n.back+=S}if(d>>>=g,u-=g,n.back+=g,b&64){s.msg="invalid distance code",n.mode=Hp;break}n.offset=j,n.extra=b&15,n.mode=g5t;case g5t:if(n.extra){for(O=n.extra;u>>=n.extra,u-=n.extra,n.back+=n.extra}if(n.offset>n.dmax){s.msg="invalid distance too far back",n.mode=Hp;break}n.mode=y5t;case y5t: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=Hp;break}p>n.wnext?(p-=n.wnext,f=n.wsize-p):f=n.wnext-p,p>n.length&&(p=n.length),y=n.window}else y=a,f=l-n.offset,p=n.length;p>c&&(p=c),c-=p,n.length-=p;do a[l++]=y[f++];while(--p);n.length===0&&(n.mode=_de);break;case v5t:if(c===0)break e;a[l++]=n.length,c--,n.mode=_de;break;case uBe:if(n.wrap){for(;u<32;){if(o===0)break e;o--,d|=r[i++]<=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,t.windowBits===0&&(t.windowBits=-15)),t.windowBits>=0&&t.windowBits<16&&!(s&&s.windowBits)&&(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&(t.windowBits&15||(t.windowBits|=15)),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new QYn,this.strm.avail_out=0;var n=K$.inflateInit2(this.strm,t.windowBits);if(n!==Gx.Z_OK)throw new Error(IYe[n]);if(this.header=new JYn,K$.inflateGetHeader(this.strm,this.header),t.dictionary&&(typeof t.dictionary=="string"?t.dictionary=$Ce.string2buf(t.dictionary):tns.call(t.dictionary)==="[object ArrayBuffer]"&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(n=K$.inflateSetDictionary(this.strm,t.dictionary),n!==Gx.Z_OK)))throw new Error(IYe[n])}T9.prototype.push=function(s,t){var n=this.strm,r=this.options.chunkSize,a=this.options.dictionary,i,l,o,c,d,u=!1;if(this.ended)return!1;l=t===~~t?t:t===!0?Gx.Z_FINISH:Gx.Z_NO_FLUSH,typeof s=="string"?n.input=$Ce.binstring2buf(s):tns.call(s)==="[object ArrayBuffer]"?n.input=new Uint8Array(s):n.input=s,n.next_in=0,n.avail_in=n.input.length;do{if(n.avail_out===0&&(n.output=new fee.Buf8(r),n.next_out=0,n.avail_out=r),i=K$.inflate(n,Gx.Z_NO_FLUSH),i===Gx.Z_NEED_DICT&&a&&(i=K$.inflateSetDictionary(this.strm,a)),i===Gx.Z_BUF_ERROR&&u===!0&&(i=Gx.Z_OK,u=!1),i!==Gx.Z_STREAM_END&&i!==Gx.Z_OK)return this.onEnd(i),this.ended=!0,!1;n.next_out&&(n.avail_out===0||i===Gx.Z_STREAM_END||n.avail_in===0&&(l===Gx.Z_FINISH||l===Gx.Z_SYNC_FLUSH))&&(this.options.to==="string"?(o=$Ce.utf8border(n.output,n.next_out),c=n.next_out-o,d=$Ce.buf2string(n.output,o),n.next_out=c,n.avail_out=r-c,c&&fee.arraySet(n.output,n.output,o,c,0),this.onData(d)):this.onData(fee.shrinkBuf(n.output,n.next_out))),n.avail_in===0&&n.avail_out===0&&(u=!0)}while((n.avail_in>0||n.avail_out===0)&&i!==Gx.Z_STREAM_END);return i===Gx.Z_STREAM_END&&(l=Gx.Z_FINISH),l===Gx.Z_FINISH?(i=K$.inflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===Gx.Z_OK):(l===Gx.Z_SYNC_FLUSH&&(this.onEnd(Gx.Z_OK),n.avail_out=0),!0)};T9.prototype.onData=function(s){this.chunks.push(s)};T9.prototype.onEnd=function(s){s===Gx.Z_OK&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=fee.flattenChunks(this.chunks)),this.chunks=[],this.err=s,this.msg=this.strm.msg};function mat(s,t){var n=new T9(t);if(n.push(s,!0),n.err)throw n.msg||IYe[n.err];return n.result}function eZn(s,t){return t=t||{},t.raw=!0,mat(s,t)}oie.Inflate=T9;oie.inflate=mat;oie.inflateRaw=eZn;oie.ungzip=mat;var tZn=VE.assign,sZn=rie,nZn=oie,rZn=ens,sns={};tZn(sns,sZn,nZn,rZn);var aZn=sns;const F8e=_d(aZn);var N5t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",ZX=new Uint8Array(256);for(var wde=0;wde>4,d[a++]=(l&15)<<4|o>>2,d[a++]=(o&3)<<6|c&63;return d},oZn=function(s){for(var t="",n=0;nr)throw new Error(c0(t)+" must be at least "+n+" and at most "+r+", but was actually "+s)},wk=function(s,t,n,r){gr(s,t,["number","undefined"]),typeof s=="number"&&oj(s,t,n,r)},ans=function(s,t,n){if(gr(s,t,["number"]),s%n!==0)throw new Error(c0(t)+" must be a multiple of "+n+", but was actually "+s)},IZn=function(s,t){if(!Number.isInteger(s))throw new Error(c0(t)+" must be an integer, but was actually "+s)},z8e=function(s,t){if(![1,0].includes(Math.sign(s)))throw new Error(c0(t)+" must be a positive number or 0, but was actually "+s)},fc=new Uint16Array(256);for(var kde=0;kde<256;kde++)fc[kde]=kde;fc[22]=cc("");fc[24]=cc("˘");fc[25]=cc("ˇ");fc[26]=cc("ˆ");fc[27]=cc("˙");fc[28]=cc("˝");fc[29]=cc("˛");fc[30]=cc("˚");fc[31]=cc("˜");fc[127]=cc("�");fc[128]=cc("•");fc[129]=cc("†");fc[130]=cc("‡");fc[131]=cc("…");fc[132]=cc("—");fc[133]=cc("–");fc[134]=cc("ƒ");fc[135]=cc("⁄");fc[136]=cc("‹");fc[137]=cc("›");fc[138]=cc("−");fc[139]=cc("‰");fc[140]=cc("„");fc[141]=cc("“");fc[142]=cc("”");fc[143]=cc("‘");fc[144]=cc("’");fc[145]=cc("‚");fc[146]=cc("™");fc[147]=cc("fi");fc[148]=cc("fl");fc[149]=cc("Ł");fc[150]=cc("Œ");fc[151]=cc("Š");fc[152]=cc("Ÿ");fc[153]=cc("Ž");fc[154]=cc("ı");fc[155]=cc("ł");fc[156]=cc("œ");fc[157]=cc("š");fc[158]=cc("ž");fc[159]=cc("�");fc[160]=cc("€");fc[173]=cc("�");var ins=function(s){for(var t=new Array(s.length),n=0,r=s.length;n=nn.ExclamationPoint&&s<=nn.Tilde&&!gat[s]},M5t={},P5t=new Map,Zs=function(s){ci(t,s);function t(n,r){var a=this;if(n!==M5t)throw new pat("PDFName");a=s.call(this)||this;for(var i="/",l=0,o=r.length;l=nn.Zero&&d<=nn.Nine||d>=nn.a&&d<=nn.f||d>=nn.A&&d<=nn.F?(r+=c,(r.length===2||!(u>="0"&&u<="9"||u>="a"&&u<="f"||u>="A"&&u<="F"))&&(i(parseInt(r,16)),r="")):i(d):d===nn.Hash?a=!0:i(d)}return new Uint8Array(n)},t.prototype.decodeText=function(){var n=this.asBytes();return String.fromCharCode.apply(String,Array.from(n))},t.prototype.asString=function(){return this.encodedName},t.prototype.value=function(){return this.encodedName},t.prototype.clone=function(){return this},t.prototype.toString=function(){return this.encodedName},t.prototype.sizeInBytes=function(){return this.encodedName.length},t.prototype.copyBytesInto=function(n,r){return r+=gv(this.encodedName,n,r),this.encodedName.length},t.of=function(n){var r=QZn(n),a=P5t.get(r);return a||(a=new t(M5t,r),P5t.set(r,a)),a},t.Length=t.of("Length"),t.FlateDecode=t.of("FlateDecode"),t.Resources=t.of("Resources"),t.Font=t.of("Font"),t.XObject=t.of("XObject"),t.ExtGState=t.of("ExtGState"),t.Contents=t.of("Contents"),t.Type=t.of("Type"),t.Parent=t.of("Parent"),t.MediaBox=t.of("MediaBox"),t.Page=t.of("Page"),t.Annots=t.of("Annots"),t.TrimBox=t.of("TrimBox"),t.ArtBox=t.of("ArtBox"),t.BleedBox=t.of("BleedBox"),t.CropBox=t.of("CropBox"),t.Rotate=t.of("Rotate"),t.Title=t.of("Title"),t.Author=t.of("Author"),t.Subject=t.of("Subject"),t.Creator=t.of("Creator"),t.Keywords=t.of("Keywords"),t.Producer=t.of("Producer"),t.CreationDate=t.of("CreationDate"),t.ModDate=t.of("ModDate"),t}(Sb),eXn=function(s){ci(t,s);function t(){return s!==null&&s.apply(this,arguments)||this}return t.prototype.asNull=function(){return null},t.prototype.clone=function(){return this},t.prototype.toString=function(){return"null"},t.prototype.sizeInBytes=function(){return 4},t.prototype.copyBytesInto=function(n,r){return n[r++]=nn.n,n[r++]=nn.u,n[r++]=nn.l,n[r++]=nn.l,4},t}(Sb);const v_=new eXn;var kc=function(s){ci(t,s);function t(n,r){var a=s.call(this)||this;return a.dict=n,a.context=r,a}return t.prototype.keys=function(){return Array.from(this.dict.keys())},t.prototype.values=function(){return Array.from(this.dict.values())},t.prototype.entries=function(){return Array.from(this.dict.entries())},t.prototype.set=function(n,r){this.dict.set(n,r)},t.prototype.get=function(n,r){r===void 0&&(r=!1);var a=this.dict.get(n);if(!(a===v_&&!r))return a},t.prototype.has=function(n){var r=this.dict.get(n);return r!==void 0&&r!==v_},t.prototype.lookupMaybe=function(n){for(var r,a=[],i=1;ithis.largestObjectNumber&&(this.largestObjectNumber=t.objectNumber)},s.prototype.nextRef=function(){return this.largestObjectNumber+=1,ch.of(this.largestObjectNumber)},s.prototype.register=function(t){var n=this.nextRef();return this.assign(n,t),n},s.prototype.delete=function(t){return this.indirectObjects.delete(t)},s.prototype.lookupMaybe=function(t){for(var n=[],r=1;r1?(this.subsections.push([t]),this.chunkIdx+=1,this.chunkLength=1):(n.push(t),this.chunkLength+=1)},s.create=function(){return new s({ref:ch.of(0,65535),offset:0,deleted:!0})},s.createEmpty=function(){return new s},s}(),vat=function(){function s(t){this.lastXRefOffset=String(t)}return s.prototype.toString=function(){return`startxref `+this.lastXRefOffset+` %%EOF`},s.prototype.sizeInBytes=function(){return 16+this.lastXRefOffset.length},s.prototype.copyBytesInto=function(t,n){var r=n;return t[n++]=nn.s,t[n++]=nn.t,t[n++]=nn.a,t[n++]=nn.r,t[n++]=nn.t,t[n++]=nn.x,t[n++]=nn.r,t[n++]=nn.e,t[n++]=nn.f,t[n++]=nn.Newline,n+=gv(this.lastXRefOffset,t,n),t[n++]=nn.Newline,t[n++]=nn.Percent,t[n++]=nn.Percent,t[n++]=nn.E,t[n++]=nn.O,t[n++]=nn.F,n-r},s.forLastCrossRefSectionOffset=function(t){return new s(t)},s}(),nXn=function(){function s(t){this.dict=t}return s.prototype.toString=function(){return`trailer `+this.dict.toString()},s.prototype.sizeInBytes=function(){return 8+this.dict.sizeInBytes()},s.prototype.copyBytesInto=function(t,n){var r=n;return t[n++]=nn.t,t[n++]=nn.r,t[n++]=nn.a,t[n++]=nn.i,t[n++]=nn.l,t[n++]=nn.e,t[n++]=nn.r,t[n++]=nn.Newline,n+=this.dict.copyBytesInto(t,n),n-r},s.of=function(t){return new s(t)},s}(),cns=function(s){ci(t,s);function t(n,r,a){a===void 0&&(a=!0);var i=s.call(this,n.obj({}),a)||this;return i.objects=r,i.offsets=i.computeObjectOffsets(),i.offsetsString=i.computeOffsetsString(),i.dict.set(Zs.of("Type"),Zs.of("ObjStm")),i.dict.set(Zs.of("N"),Ql.of(i.objects.length)),i.dict.set(Zs.of("First"),Ql.of(i.offsetsString.length)),i}return t.prototype.getObjectsCount=function(){return this.objects.length},t.prototype.clone=function(n){return t.withContextAndObjects(n||this.dict.context,this.objects.slice(),this.encode)},t.prototype.getContentsString=function(){for(var n=this.offsetsString,r=0,a=this.objects.length;r1&&(l.push(o),l.push(u.ref.objectNumber),o=0),o+=1}return l.push(o),l},i.computeEntryTuples=function(){for(var l=new Array(i.entries.length),o=0,c=i.entries.length;oo[0]&&(o[0]=f),y>o[1]&&(o[1]=y),v>o[2]&&(o[2]=v)}return o},i.entries=r||[],i.entryTuplesCache=iE.populatedBy(i.computeEntryTuples),i.maxByteWidthsCache=iE.populatedBy(i.computeMaxEntryByteWidths),i.indexCache=iE.populatedBy(i.computeIndex),n.set(Zs.of("Type"),Zs.of("XRef")),i}return t.prototype.addDeletedEntry=function(n,r){var a=y6.Deleted;this.entries.push({type:a,ref:n,nextFreeObjectNumber:r}),this.entryTuplesCache.invalidate(),this.maxByteWidthsCache.invalidate(),this.indexCache.invalidate(),this.contentsCache.invalidate()},t.prototype.addUncompressedEntry=function(n,r){var a=y6.Uncompressed;this.entries.push({type:a,ref:n,offset:r}),this.entryTuplesCache.invalidate(),this.maxByteWidthsCache.invalidate(),this.indexCache.invalidate(),this.contentsCache.invalidate()},t.prototype.addCompressedEntry=function(n,r,a){var i=y6.Compressed;this.entries.push({type:i,ref:n,objectStreamRef:r,index:a}),this.entryTuplesCache.invalidate(),this.maxByteWidthsCache.invalidate(),this.indexCache.invalidate(),this.contentsCache.invalidate()},t.prototype.clone=function(n){var r=this,a=r.dict,i=r.entries,l=r.encode;return t.of(a.clone(n),i.slice(),l)},t.prototype.getContentsString=function(){for(var n=this.entryTuplesCache.access(),r=this.maxByteWidthsCache.access(),a="",i=0,l=n.length;i=0;f--)a+=(h[f]||0).toString(2);for(var f=r[1]-1;f>=0;f--)a+=(m[f]||0).toString(2);for(var f=r[2]-1;f>=0;f--)a+=(p[f]||0).toString(2)}return a},t.prototype.getUnencodedContents=function(){for(var n=this.entryTuplesCache.access(),r=this.maxByteWidthsCache.access(),a=new Uint8Array(this.getUnencodedContentsSize()),i=0,l=0,o=n.length;l=0;y--)a[i++]=m[y]||0;for(var y=r[1]-1;y>=0;y--)a[i++]=p[y]||0;for(var y=r[2]-1;y>=0;y--)a[i++]=f[y]||0}return a},t.prototype.getUnencodedContentsSize=function(){var n=this.maxByteWidthsCache.access(),r=rKn(n);return r*this.entries.length},t.prototype.updateDict=function(){s.prototype.updateDict.call(this);var n=this.maxByteWidthsCache.access(),r=this.indexCache.access(),a=this.dict.context;this.dict.set(Zs.of("W"),a.obj(n)),this.dict.set(Zs.of("Index"),a.obj(r))},t.create=function(n,r){r===void 0&&(r=!0);var a=new t(n,[],r);return a.addDeletedEntry(ch.of(0,65535),0),a},t.of=function(n,r,a){return a===void 0&&(a=!0),new t(n,r,a)},t}(yat),aXn=function(s){ci(t,s);function t(n,r,a,i){var l=s.call(this,n,r)||this;return l.encodeStreams=a,l.objectsPerStream=i,l}return t.prototype.computeBufferSize=function(){return Mc(this,void 0,void 0,function(){var n,r,a,i,l,o,c,d,f,y,u,g,h,m,v,p,f,y,v,g,b,j,S,C;return Pc(this,function(E){switch(E.label){case 0:n=this.context.largestObjectNumber+1,r=B8e.forVersion(1,7),a=r.sizeInBytes()+2,i=rXn.create(this.createTrailerDict(),this.encodeStreams),l=[],o=[],c=[],d=this.context.enumerateIndirectObjects(),f=0,y=d.length,E.label=1;case 1:return f"},t.prototype.sizeInBytes=function(){return this.value.length+2},t.prototype.copyBytesInto=function(n,r){return n[r++]=nn.LessThan,r+=gv(this.value,n,r),n[r++]=nn.GreaterThan,this.value.length+2},t.of=function(n){return new t(n)},t.fromText=function(n){for(var r=lKn(n),a="",i=0,l=r.length;i> def /CMapName /Adobe-Identity-UCS def /CMapType 2 def 1 begincodespacerange <0000> endcodespacerange `+s.length+` beginbfchar `+s.map(function(t){var n=t[0],r=t[1];return n+" "+r}).join(` `)+` endbfchar endcmap CMapName currentdict /CMap defineresource pop end end`},R5t=function(){for(var s=[],t=0;t"},VCe=function(s){return tie(s,4)},lXn=function(s){if(cKn(s))return VCe(s);if(dKn(s)){var t=dss(s),n=uss(s);return""+VCe(t)+VCe(n)}var r=L8e(s),a="0x"+r+" is not a valid UTF-8 or UTF-16 codepoint.";throw new Error(a)},cXn=function(s){var t=0,n=function(r){t|=1<=nn.Zero&&d<=nn.Seven?(r+=c,(r.length===3||!(u>="0"&&u<="7"))&&(i(parseInt(r,8)),r="")):i(d):d===nn.BackSlash?a=!0:i(d)}return new Uint8Array(n)},t.prototype.decodeText=function(){var n=this.asBytes();return fss(n)?hss(n):ins(n)},t.prototype.decodeDate=function(){var n=this.decodeText(),r=lss(n);if(!r)throw new ons(n);return r},t.prototype.asString=function(){return this.value},t.prototype.clone=function(){return t.of(this.value)},t.prototype.toString=function(){return"("+this.value+")"},t.prototype.sizeInBytes=function(){return this.value.length+2},t.prototype.copyBytesInto=function(n,r){return n[r++]=nn.LeftParen,r+=gv(this.value,n,r),n[r++]=nn.RightParen,this.value.length+2},t.of=function(n){return new t(n)},t.fromDate=function(n){var r=Jk(String(n.getUTCFullYear()),4,"0"),a=Jk(String(n.getUTCMonth()+1),2,"0"),i=Jk(String(n.getUTCDate()),2,"0"),l=Jk(String(n.getUTCHours()),2,"0"),o=Jk(String(n.getUTCMinutes()),2,"0"),c=Jk(String(n.getUTCSeconds()),2,"0");return new t("D:"+r+a+i+l+o+c+"Z")},t}(Sb),bat=function(){function s(t,n,r,a){var i=this;this.allGlyphsInFontSortedById=function(){for(var l=new Array(i.font.characterSet.length),o=0,c=l.length;o>3)]>>7-((p&7)<<0)&1,O=3*D;o[j]=S[O],o[j+1]=S[O+1],o[j+2]=S[O+2],o[j+3]=D>2)]>>6-((p&3)<<1)&3,O=3*D;o[j]=S[O],o[j+1]=S[O+1],o[j+2]=S[O+2],o[j+3]=D>1)]>>4-((p&1)<<2)&15,O=3*D;o[j]=S[O],o[j+1]=S[O+1],o[j+2]=S[O+2],o[j+3]=D>>3)]>>>7-(Y&7)&1),Z=G==v*255?0:255;c[H+Y]=Z<<24|G<<16|G<<8|G}else if(u==2)for(var Y=0;Y>>2)]>>>6-((Y&3)<<1)&3),Z=G==v*85?0:255;c[H+Y]=Z<<24|G<<16|G<<8|G}else if(u==4)for(var Y=0;Y>>1)]>>>4-((Y&1)<<2)&15),Z=G==v*17?0:255;c[H+Y]=Z<<24|G<<16|G<<8|G}else if(u==8)for(var Y=0;Y>>2<<3));a==0;){if(a=v(t,m,1),i=v(t,m+1,2),m+=3,i==0){m&7&&(m+=8-(m&7));var M=(m>>>3)+4,I=t[M-4]|t[M-3]<<8;P&&(n=s.H.W(n,h+I)),n.set(new r(t.buffer,t.byteOffset+M,I),h),m=M+I<<3,h+=I;continue}if(P&&(n=s.H.W(n,h+(1<<17))),i==1&&(p=E.J,f=E.h,d=511,u=31),i==2){l=g(t,m,5)+257,o=g(t,m+5,5)+1,c=g(t,m+10,4)+4,m+=14;for(var D=1,O=0;O<38;O+=2)E.Q[O]=0,E.Q[O+1]=0;for(var O=0;OD&&(D=V)}m+=3*c,j(E.Q,D),S(E.Q,D,E.u),p=E.w,f=E.d,m=b(E.u,(1<>>4;if(!(Y>>>8))n[h++]=Y;else{if(Y==256)break;var Z=h+Y-254;if(Y>264){var ne=E.q[Y-257];Z=h+(ne>>>3)+g(t,m,ne&7),m+=ne&7}var ce=f[C(t,m)&u];m+=ce&15;var ie=ce>>>4,te=E.c[ie],ae=(te>>>4)+v(t,m,te&15);for(m+=te&15;h>>4;if(h<=15)l[d]=h,d++;else{var m=0,p=0;h==16?(p=3+o(a,i,2),i+=2,m=l[d-1]):h==17?(p=3+o(a,i,3),i+=3):h==18&&(p=11+o(a,i,7),i+=7);for(var f=d+p;d>>1;li&&(i=c),l++}for(;l>1,d=t[o+1],u=c<<4|d,h=n-d,m=t[o]<>>15-n;r[f]=u,m++}},s.H.l=function(t,n){for(var r=s.H.m.r,a=15-n,i=0;i>>a}},s.H.M=function(t,n,r){r=r<<(n&7);var a=n>>>3;t[a]|=r,t[a+1]|=r>>>8},s.H.I=function(t,n,r){r=r<<(n&7);var a=n>>>3;t[a]|=r,t[a+1]|=r>>>8,t[a+2]|=r>>>16},s.H.e=function(t,n,r){return(t[n>>>3]|t[(n>>>3)+1]<<8)>>>(n&7)&(1<>>3]|t[(n>>>3)+1]<<8|t[(n>>>3)+2]<<16)>>>(n&7)&(1<>>3]|t[(n>>>3)+1]<<8|t[(n>>>3)+2]<<16)>>>(n&7)},s.H.i=function(t,n){return(t[n>>>3]|t[(n>>>3)+1]<<8|t[(n>>>3)+2]<<16|t[(n>>>3)+3]<<24)>>>(n&7)},s.H.m=function(){var t=Uint16Array,n=Uint32Array;return{K:new t(16),j:new t(16),X:[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],S:[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,999,999,999],T:[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0],q:new t(32),p:[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,65535,65535],z:[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0],c:new n(32),J:new t(512),_:[],h:new t(32),$:[],w:new t(32768),C:[],v:[],d:new t(32768),D:[],u:new t(512),Q:[],r:new t(32768),s:new n(286),Y:new n(30),a:new n(19),t:new n(15e3),k:new t(65536),g:new t(32768)}}(),function(){for(var t=s.H.m,n=32768,r=0;r>>1|(a&1431655765)<<1,a=(a&3435973836)>>>2|(a&858993459)<<2,a=(a&4042322160)>>>4|(a&252645135)<<4,a=(a&4278255360)>>>8|(a&16711935)<<8,t.r[r]=(a>>>16|a<<16)>>>17}function i(l,o,c){for(;o--!=0;)l.push(0,c)}for(var r=0;r<32;r++)t.q[r]=t.S[r]<<3|t.T[r],t.c[r]=t.p[r]<<4|t.z[r];i(t._,144,8),i(t._,112,9),i(t._,24,7),i(t._,8,8),s.H.n(t._,9),s.H.A(t._,9,t.J),s.H.l(t._,9),i(t.$,32,5),s.H.n(t.$,5),s.H.A(t.$,5,t.h),s.H.l(t.$,5),i(t.Q,19,0),i(t.C,286,0),i(t.D,30,0),i(t.v,320,0)}(),s.H.N}();Pa.decode._readInterlace=function(s,t){for(var n=t.width,r=t.height,a=Pa.decode._getBPP(t),i=a>>3,l=Math.ceil(n*a/8),o=new Uint8Array(r*l),c=0,d=[0,0,4,0,2,0,1],u=[0,4,0,2,0,1,0],h=[8,8,8,4,4,2,2],m=[8,8,4,4,2,2,1],p=0;p<7;){for(var f=h[p],y=m[p],v=0,g=0,b=d[p];b>3];I=I>>7-(M&7)&1,o[E*l+(P>>3)]|=I<<7-((P&7)<<0)}if(a==2){var I=s[M>>3];I=I>>6-(M&7)&3,o[E*l+(P>>2)]|=I<<6-((P&3)<<1)}if(a==4){var I=s[M>>3];I=I>>4-(M&7)&15,o[E*l+(P>>1)]|=I<<4-((P&1)<<2)}if(a>=8)for(var D=E*l+P*i,O=0;O>3)+O];M+=a,P+=y}C++,E+=f}v*g!=0&&(c+=g*(1+S)),p=p+1}return o};Pa.decode._getBPP=function(s){var t=[1,null,3,1,2,null,4][s.ctype];return t*s.depth};Pa.decode._filterZero=function(s,t,n,r,a){var i=Pa.decode._getBPP(t),l=Math.ceil(r*i/8),o=Pa.decode._paeth;i=Math.ceil(i/8);var c=0,d=1,u=s[n],h=0;if(u>1&&(s[n]=[0,0,1][u-2]),u==3)for(h=i;h>>1)&255;for(var m=0;m>>1);for(;h>>1)}else{for(;h>8&255,s[t+1]=n&255},readUint:function(s,t){return s[t]*(256*256*256)+(s[t+1]<<16|s[t+2]<<8|s[t+3])},writeUint:function(s,t,n){s[t]=n>>24&255,s[t+1]=n>>16&255,s[t+2]=n>>8&255,s[t+3]=n&255},readASCII:function(s,t,n){for(var r="",a=0;a=0&&o>=0?(h=p*t+f<<2,m=(o+p)*a+l+f<<2):(h=(-o+p)*t-l+f<<2,m=p*a+f<<2),c==0)r[m]=s[h],r[m+1]=s[h+1],r[m+2]=s[h+2],r[m+3]=s[h+3];else if(c==1){var y=s[h+3]*.00392156862745098,v=s[h]*y,g=s[h+1]*y,b=s[h+2]*y,j=r[m+3]*(1/255),S=r[m]*j,C=r[m+1]*j,E=r[m+2]*j,P=1-y,M=y+j*P,I=M==0?0:1/M;r[m+3]=255*M,r[m+0]=(v+S*P)*I,r[m+1]=(g+C*P)*I,r[m+2]=(b+E*P)*I}else if(c==2){var y=s[h+3],v=s[h],g=s[h+1],b=s[h+2],j=r[m+3],S=r[m],C=r[m+1],E=r[m+2];y==j&&v==S&&g==C&&b==E?(r[m]=0,r[m+1]=0,r[m+2]=0,r[m+3]=0):(r[m]=v,r[m+1]=g,r[m+2]=b,r[m+3]=y)}else if(c==3){var y=s[h+3],v=s[h],g=s[h+1],b=s[h+2],j=r[m+3],S=r[m],C=r[m+1],E=r[m+2];if(y==j&&v==S&&g==C&&b==E)continue;if(y<220&&j>20)return!1}return!0};Pa.encode=function(s,t,n,r,a,i,l){r==null&&(r=0),l==null&&(l=!1);var o=Pa.encode.compress(s,t,n,r,[!1,!1,!1,0,l]);return Pa.encode.compressPNG(o,-1),Pa.encode._main(o,t,n,a,i)};Pa.encodeLL=function(s,t,n,r,a,i,l,o){for(var c={ctype:0+(r==1?0:2)+(a==0?0:4),depth:i,frames:[]},d=(r+a)*i,u=d*t,h=0;h1,h=!1,m=33+(u?20:0);if(a.sRGB!=null&&(m+=13),a.pHYs!=null&&(m+=21),s.ctype==3){for(var p=s.plte.length,f=0;f>>24!=255&&(h=!0);m+=8+p*3+4+(h?8+p*1+4:0)}for(var y=0;y>>8&255,P=S>>>16&255;g[d+j+0]=C,g[d+j+1]=E,g[d+j+2]=P}if(d+=p*3,l(g,d,i(g,d-p*3-4,p*3+4)),d+=4,h){l(g,d,p),d+=4,c(g,d,"tRNS"),d+=4;for(var f=0;f>>24&255;d+=p,l(g,d,i(g,d-p-4,p+4)),d+=4}}for(var M=0,y=0;y>2,V>>2));for(var p=0;pH&&Z==$[v-H])Y[v]=Y[v-H];else{var ne=j[Z];if(ne==null&&(j[Z]=ne=S.length,S.push(Z),S.length>=300))break;Y[v]=ne}}}var ce=S.length;ce<=256&&d==!1&&(ce<=2?h=1:ce<=4?h=2:ce<=16?h=4:h=8,h=Math.max(h,c));for(var p=0;p>1)]|=me[pe+Ce]<<4-(Ce&1)*4;else if(h==2)for(var Ce=0;Ce>2)]|=me[pe+Ce]<<6-(Ce&3)*2;else if(h==1)for(var Ce=0;Ce>3)]|=me[pe+Ce]<<7-(Ce&7)*1}te=be,u=3,le=1}else if(g==!1&&b.length==1){for(var be=new Uint8Array(H*ie*3),Ae=H*ie,v=0;vP&&(P=D),IM&&(M=I))}P==-1&&(C=E=P=M=0),a&&((C&1)==1&&C--,(E&1)==1&&E--);var V=(P-C+1)*(M-E+1);Vv&&(v=S),Cg&&(g=C))}v==-1&&(f=y=v=g=0),l&&((f&1)==1&&f--,(y&1)==1&&y--),i={x:f,y,width:v-f+1,height:g-y+1};var M=r[a];M.rect=i,M.blend=1,M.img=new Uint8Array(i.width*i.height*4),r[a-1].dispose==0?(Pa._copyTile(d,t,n,M.img,i.width,i.height,-i.x,-i.y,0),Pa.encode._prepareDiff(m,t,n,M.img,i)):Pa._copyTile(m,t,n,M.img,i.width,i.height,-i.x,-i.y,0)};Pa.encode._prepareDiff=function(s,t,n,r,a){Pa._copyTile(s,t,n,r,a.width,a.height,-a.x,-a.y,2)};Pa.encode._filterZero=function(s,t,n,r,a,i,l){var o=[],c=[0,1,2,3,4];i!=-1?c=[i]:(t*r>5e5||n==1)&&(c=[0]);var d;l&&(d={level:0});for(var u=l&&UZIP!=null?UZIP:F8e,h=0;h>1)+256&255;if(i==4)for(var d=a;d>1)&255;for(var d=a;d>1)&255}if(i==4){for(var d=0;d>>1:n=n>>>1;s[t]=n}return s}(),update:function(s,t,n,r){for(var a=0;a>>8;return s},crc:function(s,t,n){return Pa.crc.update(4294967295,s,t,n)^4294967295}};Pa.quantize=function(s,t){var n=new Uint8Array(s),r=n.slice(0),a=new Uint32Array(r.buffer),i=Pa.quantize.getKDtree(r,t),l=i[0],o=i[1];Pa.quantize.planeDst;for(var c=n,d=a,u=c.length,h=new Uint8Array(n.length>>2),m=0;m>2]=g.ind,d[m>>2]=g.est.rgba}return{abuf:r.buffer,inds:h,plte:o}};Pa.quantize.getKDtree=function(s,t,n){n==null&&(n=1e-4);var r=new Uint32Array(s.buffer),a={i0:0,i1:s.length,bst:null,est:null,tdst:0,left:null,right:null};a.bst=Pa.quantize.stats(s,a.i0,a.i1),a.est=Pa.quantize.estats(a.bst);for(var i=[a];i.lengthl&&(l=i[c].est.L,o=c);if(l=u||d.i1<=u;if(h){d.est.L=0;continue}var m={i0:d.i0,i1:u,bst:null,est:null,tdst:0,left:null,right:null};m.bst=Pa.quantize.stats(s,m.i0,m.i1),m.est=Pa.quantize.estats(m.bst);var p={i0:u,i1:d.i1,bst:null,est:null,tdst:0,left:null,right:null};p.bst={R:[],m:[],N:d.bst.N-m.bst.N};for(var c=0;c<16;c++)p.bst.R[c]=d.bst.R[c]-m.bst.R[c];for(var c=0;c<4;c++)p.bst.m[c]=d.bst.m[c]-m.bst.m[c];p.est=Pa.quantize.estats(p.bst),d.left=m,d.right=p,i[o]=m,i.push(p)}i.sort(function(f,y){return y.bst.N-f.bst.N});for(var c=0;c0&&(l=s.right,o=s.left);var c=Pa.quantize.getNearest(l,t,n,r,a);if(c.tdst<=i*i)return c;var d=Pa.quantize.getNearest(o,t,n,r,a);return d.tdsti;)r-=4;if(n>=r)break;var o=t[n>>2];t[n>>2]=t[r>>2],t[r>>2]=o,n+=4,r-=4}for(;l(s,n,a)>i;)n-=4;return n+4};Pa.quantize.vecDot=function(s,t,n){return s[t]*n[0]+s[t+1]*n[1]+s[t+2]*n[2]+s[t+3]*n[3]};Pa.quantize.stats=function(s,t,n){for(var r=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],a=[0,0,0,0],i=n-t>>2,l=t;l>>0}};Pa.M4={multVec:function(s,t){return[s[0]*t[0]+s[1]*t[1]+s[2]*t[2]+s[3]*t[3],s[4]*t[0]+s[5]*t[1]+s[6]*t[2]+s[7]*t[3],s[8]*t[0]+s[9]*t[1]+s[10]*t[2]+s[11]*t[3],s[12]*t[0]+s[13]*t[1]+s[14]*t[2]+s[15]*t[3]]},dot:function(s,t){return s[0]*t[0]+s[1]*t[1]+s[2]*t[2]+s[3]*t[3]},sml:function(s,t){return[s*t[0],s*t[1],s*t[2],s*t[3]]}};Pa.encode.concatRGBA=function(s){for(var t=0,n=0;n1)throw new Error("Animated PNGs are not supported");var a=new Uint8Array(r[0]),i=fXn(a),l=i.rgbChannel,o=i.alphaChannel;this.rgbChannel=l;var c=o.some(function(d){return d<255});c&&(this.alphaChannel=o),this.type=pXn(n.ctype),this.width=n.width,this.height=n.height,this.bitsPerComponent=8}return s.load=function(t){return new s(t)},s}(),mns=function(){function s(t){this.image=t,this.bitsPerComponent=t.bitsPerComponent,this.width=t.width,this.height=t.height,this.colorSpace="DeviceRGB"}return s.for=function(t){return Mc(this,void 0,void 0,function(){var n;return Pc(this,function(r){return n=xXn.load(t),[2,new s(n)]})})},s.prototype.embedIntoContext=function(t,n){return Mc(this,void 0,void 0,function(){var r,a;return Pc(this,function(i){return r=this.embedAlphaChannel(t),a=t.flateStream(this.image.rgbChannel,{Type:"XObject",Subtype:"Image",BitsPerComponent:this.image.bitsPerComponent,Width:this.image.width,Height:this.image.height,ColorSpace:this.colorSpace,SMask:r}),n?(t.assign(n,a),[2,n]):[2,t.register(a)]})})},s.prototype.embedAlphaChannel=function(t){if(this.image.alphaChannel){var n=t.flateStream(this.image.alphaChannel,{Type:"XObject",Subtype:"Image",Height:this.image.height,Width:this.image.width,BitsPerComponent:this.image.bitsPerComponent,ColorSpace:"DeviceGray",Decode:[0,1]});return t.register(n)}},s}(),pns=function(){function s(t,n,r){this.bytes=t,this.start=n||0,this.pos=this.start,this.end=n&&r?n+r:this.bytes.length}return Object.defineProperty(s.prototype,"length",{get:function(){return this.end-this.start},enumerable:!1,configurable:!0}),Object.defineProperty(s.prototype,"isEmpty",{get:function(){return this.length===0},enumerable:!1,configurable:!0}),s.prototype.getByte=function(){return this.pos>=this.end?-1:this.bytes[this.pos++]},s.prototype.getUint16=function(){var t=this.getByte(),n=this.getByte();return t===-1||n===-1?-1:(t<<8)+n},s.prototype.getInt32=function(){var t=this.getByte(),n=this.getByte(),r=this.getByte(),a=this.getByte();return(t<<24)+(n<<16)+(r<<8)+a},s.prototype.getBytes=function(t,n){n===void 0&&(n=!1);var r=this.bytes,a=this.pos,i=this.end;if(t){var o=a+t;o>i&&(o=i),this.pos=o;var l=r.subarray(a,o);return n?new Uint8ClampedArray(l):l}else{var l=r.subarray(a,i);return n?new Uint8ClampedArray(l):l}},s.prototype.peekByte=function(){var t=this.getByte();return this.pos--,t},s.prototype.peekBytes=function(t,n){n===void 0&&(n=!1);var r=this.getBytes(t,n);return this.pos-=r.length,r},s.prototype.skip=function(t){t||(t=1),this.pos+=t},s.prototype.reset=function(){this.pos=this.start},s.prototype.moveStart=function(){this.start=this.pos},s.prototype.makeSubStream=function(t,n){return new s(this.bytes,t,n)},s.prototype.decode=function(){return this.bytes},s}(),gXn=new Uint8Array(0),lie=function(){function s(t){if(this.pos=0,this.bufferLength=0,this.eof=!1,this.buffer=gXn,this.minBufferLength=512,t)for(;this.minBufferLengthi&&(r=i)}else{for(;!this.eof;)this.readBlock();r=this.bufferLength}this.pos=r;var l=this.buffer.subarray(a,r);return n&&!(l instanceof Uint8ClampedArray)?new Uint8ClampedArray(l):l},s.prototype.peekByte=function(){var t=this.getByte();return this.pos--,t},s.prototype.peekBytes=function(t,n){n===void 0&&(n=!1);var r=this.getBytes(t,n);return this.pos-=r.length,r},s.prototype.skip=function(t){t||(t=1),this.pos+=t},s.prototype.reset=function(){this.pos=0},s.prototype.makeSubStream=function(t,n){for(var r=t+n;this.bufferLength<=r&&!this.eof;)this.readBlock();return new pns(this.buffer,t,n)},s.prototype.decode=function(){for(;!this.eof;)this.readBlock();return this.buffer.subarray(0,this.bufferLength)},s.prototype.readBlock=function(){throw new iN(this.constructor.name,"readBlock")},s.prototype.ensureBuffer=function(t){var n=this.buffer;if(t<=n.byteLength)return n;for(var r=this.minBufferLength;r=0;--d)c[o+d]=h&255,h>>=8}},t}(lie),vXn=function(s){ci(t,s);function t(n,r){var a=s.call(this,r)||this;return a.stream=n,a.firstDigit=-1,r&&(r=.5*r),a}return t.prototype.readBlock=function(){var n=8e3,r=this.stream.getBytes(n);if(!r.length){this.eof=!0;return}for(var a=r.length+1>>1,i=this.ensureBuffer(this.bufferLength+a),l=this.bufferLength,o=this.firstDigit,c=0,d=r.length;c=48&&u<=57)h=u&15;else if(u>=65&&u<=70||u>=97&&u<=102)h=(u&15)+9;else if(u===62){this.eof=!0;break}else continue;o<0?o=h:(i[l++]=o<<4|h,o=-1)}o>=0&&this.eof&&(i[l++]=o<<4,o=-1),this.firstDigit=o,this.bufferLength=l},t}(lie),z5t=new Int32Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),bXn=new Int32Array([3,4,5,6,7,8,9,10,65547,65549,65551,65553,131091,131095,131099,131103,196643,196651,196659,196667,262211,262227,262243,262259,327811,327843,327875,327907,258,258,258]),_Xn=new Int32Array([1,2,3,4,65541,65543,131081,131085,196625,196633,262177,262193,327745,327777,393345,393409,459009,459137,524801,525057,590849,591361,657409,658433,724993,727041,794625,798721,868353,876545]),wXn=[new Int32Array([459008,524368,524304,524568,459024,524400,524336,590016,459016,524384,524320,589984,524288,524416,524352,590048,459012,524376,524312,589968,459028,524408,524344,590032,459020,524392,524328,59e4,524296,524424,524360,590064,459010,524372,524308,524572,459026,524404,524340,590024,459018,524388,524324,589992,524292,524420,524356,590056,459014,524380,524316,589976,459030,524412,524348,590040,459022,524396,524332,590008,524300,524428,524364,590072,459009,524370,524306,524570,459025,524402,524338,590020,459017,524386,524322,589988,524290,524418,524354,590052,459013,524378,524314,589972,459029,524410,524346,590036,459021,524394,524330,590004,524298,524426,524362,590068,459011,524374,524310,524574,459027,524406,524342,590028,459019,524390,524326,589996,524294,524422,524358,590060,459015,524382,524318,589980,459031,524414,524350,590044,459023,524398,524334,590012,524302,524430,524366,590076,459008,524369,524305,524569,459024,524401,524337,590018,459016,524385,524321,589986,524289,524417,524353,590050,459012,524377,524313,589970,459028,524409,524345,590034,459020,524393,524329,590002,524297,524425,524361,590066,459010,524373,524309,524573,459026,524405,524341,590026,459018,524389,524325,589994,524293,524421,524357,590058,459014,524381,524317,589978,459030,524413,524349,590042,459022,524397,524333,590010,524301,524429,524365,590074,459009,524371,524307,524571,459025,524403,524339,590022,459017,524387,524323,589990,524291,524419,524355,590054,459013,524379,524315,589974,459029,524411,524347,590038,459021,524395,524331,590006,524299,524427,524363,590070,459011,524375,524311,524575,459027,524407,524343,590030,459019,524391,524327,589998,524295,524423,524359,590062,459015,524383,524319,589982,459031,524415,524351,590046,459023,524399,524335,590014,524303,524431,524367,590078,459008,524368,524304,524568,459024,524400,524336,590017,459016,524384,524320,589985,524288,524416,524352,590049,459012,524376,524312,589969,459028,524408,524344,590033,459020,524392,524328,590001,524296,524424,524360,590065,459010,524372,524308,524572,459026,524404,524340,590025,459018,524388,524324,589993,524292,524420,524356,590057,459014,524380,524316,589977,459030,524412,524348,590041,459022,524396,524332,590009,524300,524428,524364,590073,459009,524370,524306,524570,459025,524402,524338,590021,459017,524386,524322,589989,524290,524418,524354,590053,459013,524378,524314,589973,459029,524410,524346,590037,459021,524394,524330,590005,524298,524426,524362,590069,459011,524374,524310,524574,459027,524406,524342,590029,459019,524390,524326,589997,524294,524422,524358,590061,459015,524382,524318,589981,459031,524414,524350,590045,459023,524398,524334,590013,524302,524430,524366,590077,459008,524369,524305,524569,459024,524401,524337,590019,459016,524385,524321,589987,524289,524417,524353,590051,459012,524377,524313,589971,459028,524409,524345,590035,459020,524393,524329,590003,524297,524425,524361,590067,459010,524373,524309,524573,459026,524405,524341,590027,459018,524389,524325,589995,524293,524421,524357,590059,459014,524381,524317,589979,459030,524413,524349,590043,459022,524397,524333,590011,524301,524429,524365,590075,459009,524371,524307,524571,459025,524403,524339,590023,459017,524387,524323,589991,524291,524419,524355,590055,459013,524379,524315,589975,459029,524411,524347,590039,459021,524395,524331,590007,524299,524427,524363,590071,459011,524375,524311,524575,459027,524407,524343,590031,459019,524391,524327,589999,524295,524423,524359,590063,459015,524383,524319,589983,459031,524415,524351,590047,459023,524399,524335,590015,524303,524431,524367,590079]),9],jXn=[new Int32Array([327680,327696,327688,327704,327684,327700,327692,327708,327682,327698,327690,327706,327686,327702,327694,0,327681,327697,327689,327705,327685,327701,327693,327709,327683,327699,327691,327707,327687,327703,327695,0]),5],NXn=function(s){ci(t,s);function t(n,r){var a=s.call(this,r)||this;a.stream=n;var i=n.getByte(),l=n.getByte();if(i===-1||l===-1)throw new Error("Invalid header in flate stream: "+i+", "+l);if((i&15)!==8)throw new Error("Unknown compression method in flate stream: "+i+", "+l);if(((i<<8)+l)%31!==0)throw new Error("Bad FCHECK in flate stream: "+i+", "+l);if(l&32)throw new Error("FDICT bit set in flate stream: "+i+", "+l);return a.codeSize=0,a.codeBuf=0,a}return t.prototype.readBlock=function(){var n,r,a=this.stream,i=this.getBits(3);if(i&1&&(this.eof=!0),i>>=1,i===0){var l=void 0;if((l=a.getByte())===-1)throw new Error("Bad block header in flate stream");var o=l;if((l=a.getByte())===-1)throw new Error("Bad block header in flate stream");if(o|=l<<8,(l=a.getByte())===-1)throw new Error("Bad block header in flate stream");var c=l;if((l=a.getByte())===-1)throw new Error("Bad block header in flate stream");if(c|=l<<8,c!==(~o&65535)&&(o!==0||c!==0))throw new Error("Bad uncompressed block length in flate stream");this.codeBuf=0,this.codeSize=0;var d=this.bufferLength;n=this.ensureBuffer(d+o);var u=d+o;if(this.bufferLength=u,o===0)a.peekByte()===-1&&(this.eof=!0);else for(var h=d;h0;)C[b++]=M}m=this.generateHuffmanTable(C.subarray(0,f)),p=this.generateHuffmanTable(C.subarray(f,S))}else throw new Error("Unknown block type in flate stream");n=this.buffer;for(var O=n?n.length:0,V=this.bufferLength;;){var G=this.getCode(m);if(G<256){V+1>=O&&(n=this.ensureBuffer(V+1),O=n.length),n[V++]=G;continue}if(G===256){this.bufferLength=V;return}G-=257,G=bXn[G];var $=G>>16;$>0&&($=this.getBits($)),r=(G&65535)+$,G=this.getCode(p),G=_Xn[G],$=G>>16,$>0&&($=this.getBits($));var H=(G&65535)+$;V+r>=O&&(n=this.ensureBuffer(V+r),O=n.length);for(var Y=0;Y>n,this.codeSize=a-=n,l},t.prototype.getCode=function(n){for(var r=this.stream,a=n[0],i=n[1],l=this.codeSize,o=this.codeBuf,c;l>16,h=d&65535;if(u<1||l>u,this.codeSize=l-u,h},t.prototype.generateHuffmanTable=function(n){var r=n.length,a=0,i;for(i=0;ia&&(a=n[i]);for(var l=1<>=1;for(i=m;i0;if(!C||C<256)v[0]=C,g=1;else if(C>=258)if(C=0;l--)v[l]=h[o],o=p[o];else v[g++]=v[0];else if(C===256){f=9,u=258,g=0;continue}else{this.eof=!0,delete this.lzwState;break}if(E&&(p[u]=y,m[u]=m[y]+1,h[u]=v[0],u++,f=u+d&u+d-1?f:Math.min(Math.log(u+d)/.6931471805599453+1,12)|0),y=C,b+=g,r>>r&(1<0){var l=this.stream.getBytes(i);r.set(l,a),a+=i}}else{i=257-i;var o=n[1];r=this.ensureBuffer(a+i+1);for(var c=0;cr.size())throw new h6e(n,0,r.size());r.remove(n)}else{if(n!==0)throw new h6e(n,0,0);this.setKids([])}},t.prototype.normalizedEntries=function(){var n=this.Kids();return n||(n=this.dict.context.obj([this.ref]),this.dict.set(Zs.of("Kids"),n)),{Kids:n}},t.fromDict=function(n,r){return new t(n,r)},t}(gns),_at=function(s){ci(t,s);function t(){return s!==null&&s.apply(this,arguments)||this}return t.prototype.Opt=function(){return this.dict.lookupMaybe(Zs.of("Opt"),oh,Fl,Iu)},t.prototype.setOpt=function(n){this.dict.set(Zs.of("Opt"),this.dict.context.obj(n))},t.prototype.getExportValues=function(){var n=this.Opt();if(n){if(n instanceof oh||n instanceof Fl)return[n];for(var r=[],a=0,i=n.size();ar.size())throw new h6e(n,0,r.size());r.remove(n)}},t.prototype.normalizeExportValues=function(){for(var n,r,a,i,l=(n=this.getExportValues())!==null&&n!==void 0?n:[],o=[],c=this.getWidgets(),d=0,u=c.length;d1){if(!this.hasFlag(ah.MultiSelect))throw new BZn;this.dict.set(Zs.of("V"),this.dict.context.obj(n))}this.updateSelectedIndices(n)},t.prototype.valuesAreValid=function(n){for(var r=this.getOptions(),a=function(c,d){var u=n[c].decodeText();if(!r.find(function(h){return u===(h.display||h.value).decodeText()}))return{value:!1}},i=0,l=n.length;i1){for(var r=new Array(n.length),a=this.getOptions(),i=function(c,d){var u=n[c].decodeText();r[c]=a.findIndex(function(h){return u===(h.display||h.value).decodeText()})},l=0,o=n.length;l0){var o=l.lookup(0,oh,Fl),c=l.lookupMaybe(1,oh,Fl);r.push({value:o,display:c||o})}}return r}return[]},t}(hK),q8e=function(s){ci(t,s);function t(){return s!==null&&s.apply(this,arguments)||this}return t.fromDict=function(n,r){return new t(n,r)},t.create=function(n){var r=n.obj({FT:"Ch",Ff:ah.Combo,Kids:[]}),a=n.register(r);return new t(r,a)},t}(yns),f6e=function(s){ci(t,s);function t(){return s!==null&&s.apply(this,arguments)||this}return t.prototype.addField=function(n){var r=this.normalizedEntries().Kids;r==null||r.push(n)},t.prototype.normalizedEntries=function(){var n=this.Kids();return n||(n=this.dict.context.obj([]),this.dict.set(Zs.of("Kids"),n)),{Kids:n}},t.fromDict=function(n,r){return new t(n,r)},t.create=function(n){var r=n.obj({}),a=n.register(r);return new t(r,a)},t}(gns),wat=function(s){ci(t,s);function t(){return s!==null&&s.apply(this,arguments)||this}return t.fromDict=function(n,r){return new t(n,r)},t}(hK),$8e=function(s){ci(t,s);function t(){return s!==null&&s.apply(this,arguments)||this}return t.prototype.MaxLen=function(){var n=this.dict.lookup(Zs.of("MaxLen"));if(n instanceof Ql)return n},t.prototype.Q=function(){var n=this.dict.lookup(Zs.of("Q"));if(n instanceof Ql)return n},t.prototype.setMaxLength=function(n){this.dict.set(Zs.of("MaxLen"),Ql.of(n))},t.prototype.removeMaxLength=function(){this.dict.delete(Zs.of("MaxLen"))},t.prototype.getMaxLength=function(){var n;return(n=this.MaxLen())===null||n===void 0?void 0:n.asNumber()},t.prototype.setQuadding=function(n){this.dict.set(Zs.of("Q"),Ql.of(n))},t.prototype.getQuadding=function(){var n;return(n=this.Q())===null||n===void 0?void 0:n.asNumber()},t.prototype.setValue=function(n){this.dict.set(Zs.of("V"),n)},t.prototype.removeValue=function(){this.dict.delete(Zs.of("V"))},t.prototype.getValue=function(){var n=this.V();if(n instanceof oh||n instanceof Fl)return n},t.fromDict=function(n,r){return new t(n,r)},t.create=function(n){var r=n.obj({FT:"Tx",Kids:[]}),a=n.register(r);return new t(r,a)},t}(hK),V8e=function(s){ci(t,s);function t(){return s!==null&&s.apply(this,arguments)||this}return t.fromDict=function(n,r){return new t(n,r)},t.create=function(n){var r=n.obj({FT:"Btn",Ff:G2.PushButton,Kids:[]}),a=n.register(r);return new t(r,a)},t}(_at),H8e=function(s){ci(t,s);function t(){return s!==null&&s.apply(this,arguments)||this}return t.prototype.setValue=function(n){var r=this.getOnValues();if(!r.includes(n)&&n!==Zs.of("Off"))throw new xat;this.dict.set(Zs.of("V"),n);for(var a=this.getWidgets(),i=0,l=a.length;ii)throw new A5t(r,i);for(var l=r,o=0,c=a.size();ol)return u.insertLeafNode(n,l)||d;l-=u.Count().asNumber()}u instanceof oE&&(l-=1)}if(l===0){this.insertLeafKid(a.size(),n);return}throw new E5t(r,"insertLeafNode")},t.prototype.removeLeafNode=function(n,r){r===void 0&&(r=!0);var a=this.Kids(),i=this.Count().asNumber();if(n>=i)throw new A5t(n,i);for(var l=n,o=0,c=a.size();ol){u.removeLeafNode(l,r),r&&u.Kids().size()===0&&a.remove(o);return}else l-=u.Count().asNumber();if(u instanceof oE)if(l===0){this.removeKid(o);return}else l-=1}throw new E5t(n,"removeLeafNode")},t.prototype.ascend=function(n){n(this);var r=this.Parent();r&&r.ascend(n)},t.prototype.traverse=function(n){for(var r=this.Kids(),a=0,i=r.size();aNumber.MAX_SAFE_INTEGER)if(this.capNumbers){var a="Parsed number that is too large for some PDF readers: "+t+", using Number.MAX_SAFE_INTEGER instead.";return console.warn(a),Number.MAX_SAFE_INTEGER}else{var a="Parsed number that is too large for some PDF readers: "+t+", not capping.";console.warn(a)}return r},s.prototype.skipWhitespace=function(){for(;!this.bytes.done()&&HE[this.bytes.peek()];)this.bytes.next()},s.prototype.skipLine=function(){for(;!this.bytes.done();){var t=this.bytes.peek();if(t===q5t||t===$5t)return;this.bytes.next()}},s.prototype.skipComment=function(){if(this.bytes.peek()!==nn.Percent)return!1;for(;!this.bytes.done();){var t=this.bytes.peek();if(t===q5t||t===$5t)return!0;this.bytes.next()}return!0},s.prototype.skipWhitespaceAndComments=function(){for(this.skipWhitespace();this.skipComment();)this.skipWhitespace()},s.prototype.matchKeyword=function(t){for(var n=this.bytes.offset(),r=0,a=t.length;r=this.length},s.prototype.offset=function(){return this.idx},s.prototype.slice=function(t,n){return this.bytes.slice(t,n)},s.prototype.position=function(){return{line:this.line,column:this.column,offset:this.idx}},s.of=function(t){return new s(t)},s.fromPDFRawStream=function(t){return s.of(fns(t).decode())},s}(),FXn=nn.Space,TZ=nn.CarriageReturn,MZ=nn.Newline,PZ=[nn.s,nn.t,nn.r,nn.e,nn.a,nn.m],Cde=[nn.e,nn.n,nn.d,nn.s,nn.t,nn.r,nn.e,nn.a,nn.m],em={header:[nn.Percent,nn.P,nn.D,nn.F,nn.Dash],eof:[nn.Percent,nn.Percent,nn.E,nn.O,nn.F],obj:[nn.o,nn.b,nn.j],endobj:[nn.e,nn.n,nn.d,nn.o,nn.b,nn.j],xref:[nn.x,nn.r,nn.e,nn.f],trailer:[nn.t,nn.r,nn.a,nn.i,nn.l,nn.e,nn.r],startxref:[nn.s,nn.t,nn.a,nn.r,nn.t,nn.x,nn.r,nn.e,nn.f],true:[nn.t,nn.r,nn.u,nn.e],false:[nn.f,nn.a,nn.l,nn.s,nn.e],null:[nn.n,nn.u,nn.l,nn.l],stream:PZ,streamEOF1:pu(PZ,[FXn,TZ,MZ]),streamEOF2:pu(PZ,[TZ,MZ]),streamEOF3:pu(PZ,[TZ]),streamEOF4:pu(PZ,[MZ]),endstream:Cde,EOF1endstream:pu([TZ,MZ],Cde),EOF2endstream:pu([TZ],Cde),EOF3endstream:pu([MZ],Cde)},jns=function(s){ci(t,s);function t(n,r,a){a===void 0&&(a=!1);var i=s.call(this,n,a)||this;return i.context=r,i}return t.prototype.parseObject=function(){if(this.skipWhitespaceAndComments(),this.matchKeyword(em.true))return Dse.True;if(this.matchKeyword(em.false))return Dse.False;if(this.matchKeyword(em.null))return v_;var n=this.bytes.peek();if(n===nn.LessThan&&this.bytes.peekAhead(1)===nn.LessThan)return this.parseDictOrStream();if(n===nn.LessThan)return this.parseHexString();if(n===nn.LeftParen)return this.parseString();if(n===nn.ForwardSlash)return this.parseName();if(n===nn.LeftSquareBracket)return this.parseArray();if(kat[n])return this.parseNumberOrRef();throw new VZn(this.bytes.position(),n)},t.prototype.parseNumberOrRef=function(){var n=this.parseRawNumber();this.skipWhitespaceAndComments();var r=this.bytes.offset();if(j1[this.bytes.peek()]){var a=this.parseRawNumber();if(this.skipWhitespaceAndComments(),this.bytes.peek()===nn.R)return this.bytes.assertNext(nn.R),ch.of(n,a)}return this.bytes.moveTo(r),Ql.of(n)},t.prototype.parseHexString=function(){var n="";for(this.bytes.assertNext(nn.LessThan);!this.bytes.done()&&this.bytes.peek()!==nn.GreaterThan;)n+=aE(this.bytes.next());return this.bytes.assertNext(nn.GreaterThan),Fl.of(n)},t.prototype.parseString=function(){for(var n=0,r=!1,a="";!this.bytes.done();){var i=this.bytes.next();if(a+=aE(i),r||(i===nn.LeftParen&&(n+=1),i===nn.RightParen&&(n-=1)),i===nn.BackSlash?r=!r:r&&(r=!1),n===0)return oh.of(a.substring(1,a.length-1))}throw new WZn(this.bytes.position())},t.prototype.parseName=function(){this.bytes.assertNext(nn.ForwardSlash);for(var n="";!this.bytes.done();){var r=this.bytes.peek();if(HE[r]||HN[r])break;n+=aE(r),this.bytes.next()}return Zs.of(n)},t.prototype.parseArray=function(){this.bytes.assertNext(nn.LeftSquareBracket),this.skipWhitespaceAndComments();for(var n=Iu.withContext(this.context);this.bytes.peek()!==nn.RightSquareBracket;){var r=this.parseObject();n.push(r),this.skipWhitespaceAndComments()}return this.bytes.assertNext(nn.RightSquareBracket),n},t.prototype.parseDict=function(){this.bytes.assertNext(nn.LessThan),this.bytes.assertNext(nn.LessThan),this.skipWhitespaceAndComments();for(var n=new Map;!this.bytes.done()&&this.bytes.peek()!==nn.GreaterThan&&this.bytes.peekAhead(1)!==nn.GreaterThan;){var r=this.parseName(),a=this.parseObject();n.set(r,a),this.skipWhitespaceAndComments()}this.skipWhitespaceAndComments(),this.bytes.assertNext(nn.GreaterThan),this.bytes.assertNext(nn.GreaterThan);var i=n.get(Zs.of("Type"));return i===Zs.of("Catalog")?_ns.fromMapWithContext(n,this.context):i===Zs.of("Pages")?wns.fromMapWithContext(n,this.context):i===Zs.of("Page")?oE.fromMapWithContext(n,this.context):kc.fromMapWithContext(n,this.context)},t.prototype.parseDictOrStream=function(){var n=this.bytes.position(),r=this.parseDict();if(this.skipWhitespaceAndComments(),!this.matchKeyword(em.streamEOF1)&&!this.matchKeyword(em.streamEOF2)&&!this.matchKeyword(em.streamEOF3)&&!this.matchKeyword(em.streamEOF4)&&!this.matchKeyword(em.stream))return r;var a=this.bytes.offset(),i,l=r.get(Zs.of("Length"));l instanceof Ql?(i=a+l.asNumber(),this.bytes.moveTo(i),this.skipWhitespaceAndComments(),this.matchKeyword(em.endstream)||(this.bytes.moveTo(a),i=this.findEndOfStreamFallback(n))):i=this.findEndOfStreamFallback(n);var o=this.bytes.slice(a,i);return Rse.of(r,o)},t.prototype.findEndOfStreamFallback=function(n){for(var r=1,a=this.bytes.offset();!this.bytes.done()&&(a=this.bytes.offset(),this.matchKeyword(em.stream)?r+=1:this.matchKeyword(em.EOF1endstream)||this.matchKeyword(em.EOF2endstream)||this.matchKeyword(em.EOF3endstream)||this.matchKeyword(em.endstream)?r-=1:this.bytes.next(),r!==0););if(r!==0)throw new GZn(n);return a},t.forBytes=function(n,r,a){return new t(K8e.of(n),r,a)},t.forByteStream=function(n,r,a){return a===void 0&&(a=!1),new t(n,r,a)},t}(RXn),OXn=function(s){ci(t,s);function t(n,r){var a=s.call(this,K8e.fromPDFRawStream(n),n.dict.context)||this,i=n.dict;return a.alreadyParsed=!1,a.shouldWaitForTick=r||function(){return!1},a.firstOffset=i.lookup(Zs.of("First"),Ql).asNumber(),a.objectCount=i.lookup(Zs.of("N"),Ql).asNumber(),a}return t.prototype.parseIntoContext=function(){return Mc(this,void 0,void 0,function(){var n,r,a,i,l,o,c,d;return Pc(this,function(u){switch(u.label){case 0:if(this.alreadyParsed)throw new fat("PDFObjectStreamParser","parseIntoContext");this.alreadyParsed=!0,n=this.parseOffsetsAndObjectNumbers(),r=0,a=n.length,u.label=1;case 1:return r=nn.Space&&r<=nn.Tilde;if(a&&(this.matchKeyword(em.xref)||this.matchKeyword(em.trailer)||this.matchKeyword(em.startxref)||this.matchIndirectObjectHeader())){this.bytes.moveTo(n);break}this.bytes.next()}},t.prototype.skipBinaryHeaderComment=function(){this.skipWhitespaceAndComments();try{var n=this.bytes.offset();this.parseIndirectObjectHeader(),this.bytes.moveTo(n)}catch{this.bytes.next(),this.skipWhitespaceAndComments()}},t.forBytesWithOptions=function(n,r,a,i){return new t(n,r,a,i)},t}(jns),A5=function(s){return 1<0&&(r[r.length]=+a),n[n.length]={cmd:t,args:r},r=[],a="",i=!1),t=d;else if([" ",","].includes(d)||d==="-"&&a.length>0&&a[a.length-1]!=="e"||d==="."&&i){if(a.length===0)continue;r.length===l?(n[n.length]={cmd:t,args:r},r=[+a],t==="M"&&(t="L"),t==="m"&&(t="l")):r[r.length]=+a,i=d===".",a=["-","."].includes(d)?d:""}else a+=d,d==="."&&(i=!0)}return a.length>0&&(r.length===l?(n[n.length]={cmd:t,args:r},r=[+a],t==="M"&&(t="L"),t==="m"&&(t="l")):r[r.length]=+a),n[n.length]={cmd:t,args:r},n},JXn=function(s){Bo=Uo=Wd=Kd=XX=QX=0;for(var t=[],n=0;n1&&(m=Math.sqrt(m),n*=m,r*=m);var p=h/n,f=u/n,y=-u/r,v=h/r,g=p*o+f*c,b=y*o+v*c,j=p*s+f*t,S=y*s+v*t,C=(j-g)*(j-g)+(S-b)*(S-b),E=1/C-.25;E<0&&(E=0);var P=Math.sqrt(E);i===a&&(P=-P);var M=.5*(g+j)-P*(S-b),I=.5*(b+S)+P*(j-g),D=Math.atan2(b-I,g-M),O=Math.atan2(S-I,j-M),V=O-D;V<0&&i===1?V+=2*Math.PI:V>0&&i===0&&(V-=2*Math.PI);for(var G=Math.ceil(Math.abs(V/(Math.PI*.5+.001))),$=[],H=0;Hs.length)return a-1;var v=t.heightAtSize(a),g=v+v*.2,b=g*i;if(b>Math.abs(n.height))return a-1;a+=1}return a},_Qn=function(s,t,n,r){for(var a=n.width/r,i=n.height,l=Uns,o=ZWn(s);la*.75;if(h)return l-1}var m=t.heightAtSize(l,{descender:!1});if(m>i)return l-1;l+=1}return l},wQn=function(s){for(var t=s.length;t>0;t--)if(/\s/.test(s[t]))return t},jQn=function(s,t,n,r){for(var a,i=s.length;i>0;){var l=s.substring(0,i),o=n.encodeText(l),c=n.widthOfTextAtSize(l,r);if(cm&&(m=P+C),f+o>p&&(p=f+o),d.push({text:j,encoded:S,width:C,height:o,x:P,y:f}),g=E==null?void 0:E.trim()}return{fontSize:r,lineHeight:c,lines:d,bounds:{x:u,y:h,width:m-u,height:p-h}}},NQn=function(s,t){var n=t.fontSize,r=t.font,a=t.bounds,i=t.cellCount,l=iss(sie(s));if(l.length>i)throw new yQn(l.length,i);(n===void 0||n===0)&&(n=_Qn(l,r,a,i));for(var o=a.width/i,c=r.heightAtSize(n,{descender:!1}),d=a.y+(a.height/2-c/2),u=[],h=a.x,m=a.y,p=a.x+a.width,f=a.y+a.height,y=0,v=0;yp&&(p=P+C),d+c>f&&(f=d+c),u.push({text:l,encoded:S,width:C,height:c,x:P,y:d}),y+=1,v+=j}return{fontSize:n,cells:u,bounds:{x:h,y:m,width:p-h,height:f-m}}},_6e=function(s,t){var n=t.alignment,r=t.fontSize,a=t.font,i=t.bounds,l=iss(sie(s));(r===void 0||r===0)&&(r=$ns([l],a,i));var o=a.encodeText(l),c=a.widthOfTextAtSize(l,r),d=a.heightAtSize(r,{descender:!1}),u=n===p0.Left?i.x:n===p0.Center?i.x+i.width/2-c/2:n===p0.Right?i.x+i.width-c:i.x,h=i.y+(i.height/2-d/2);return{fontSize:r,line:{text:l,encoded:o,width:c,height:d,x:u,y:h},bounds:{x:u,y:h,width:c,height:d}}},pK=function(s){return"normal"in s?s:{normal:s}},kQn=/\/([^\0\t\n\f\r\ ]+)[\0\t\n\f\r\ ]+(\d*\.\d+|\d+)[\0\t\n\f\r\ ]+Tf/,YP=function(s){var t,n,r=(t=s.getDefaultAppearance())!==null&&t!==void 0?t:"",a=(n=iat(r,kQn).match)!==null&&n!==void 0?n:[],i=Number(a[2]);return isFinite(i)?i:void 0},SQn=/(\d*\.\d+|\d+)[\0\t\n\f\r\ ]*(\d*\.\d+|\d+)?[\0\t\n\f\r\ ]*(\d*\.\d+|\d+)?[\0\t\n\f\r\ ]*(\d*\.\d+|\d+)?[\0\t\n\f\r\ ]+(g|rg|k)/,IN=function(s){var t,n=(t=s.getDefaultAppearance())!==null&&t!==void 0?t:"",r=iat(n,SQn).match,a=r??[],i=a[1],l=a[2],o=a[3],c=a[4],d=a[5];if(d==="g"&&i)return Rns(Number(i));if(d==="rg"&&i&&l&&o)return Fu(Number(i),Number(l),Number(o));if(d==="k"&&i&&l&&o&&c)return Fns(Number(i),Number(l),Number(o),Number(c))},DN=function(s,t,n,r){var a;r===void 0&&(r=0);var i=[jz(t).toString(),Eat((a=n==null?void 0:n.name)!==null&&a!==void 0?a:"dummy__noop",r).toString()].join(` `);s.setDefaultAppearance(i)},CQn=function(s,t){var n,r,a,i=IN(t),l=IN(s.acroField),o=t.getRectangle(),c=t.getAppearanceCharacteristics(),d=t.getBorderStyle(),u=(n=d==null?void 0:d.getWidth())!==null&&n!==void 0?n:0,h=GE(c==null?void 0:c.getRotation()),m=_z(o,h),p=m.width,f=m.height,y=OL(uc(uc({},o),{rotation:h})),v=Fu(0,0,0),g=(r=Cb(c==null?void 0:c.getBorderColor()))!==null&&r!==void 0?r:v,b=Cb(c==null?void 0:c.getBackgroundColor()),j=Cb(c==null?void 0:c.getBackgroundColor(),.8),S=(a=i??l)!==null&&a!==void 0?a:v;DN(i?t:s.acroField,S);var C={x:0+u/2,y:0+u/2,width:p-u,height:f-u,thickness:1.5,borderWidth:u,borderColor:g,markColor:S};return{normal:{on:pu(y,Tde(uc(uc({},C),{color:b,filled:!0}))),off:pu(y,Tde(uc(uc({},C),{color:b,filled:!1})))},down:{on:pu(y,Tde(uc(uc({},C),{color:j,filled:!0}))),off:pu(y,Tde(uc(uc({},C),{color:j,filled:!1})))}}},AQn=function(s,t){var n,r,a,i=IN(t),l=IN(s.acroField),o=t.getRectangle(),c=t.getAppearanceCharacteristics(),d=t.getBorderStyle(),u=(n=d==null?void 0:d.getWidth())!==null&&n!==void 0?n:0,h=GE(c==null?void 0:c.getRotation()),m=_z(o,h),p=m.width,f=m.height,y=OL(uc(uc({},o),{rotation:h})),v=Fu(0,0,0),g=(r=Cb(c==null?void 0:c.getBorderColor()))!==null&&r!==void 0?r:v,b=Cb(c==null?void 0:c.getBackgroundColor()),j=Cb(c==null?void 0:c.getBackgroundColor(),.8),S=(a=i??l)!==null&&a!==void 0?a:v;DN(i?t:s.acroField,S);var C={x:p/2,y:f/2,width:p-u,height:f-u,borderWidth:u,borderColor:g,dotColor:S};return{normal:{on:pu(y,Mde(uc(uc({},C),{color:b,filled:!0}))),off:pu(y,Mde(uc(uc({},C),{color:b,filled:!1})))},down:{on:pu(y,Mde(uc(uc({},C),{color:j,filled:!0}))),off:pu(y,Mde(uc(uc({},C),{color:j,filled:!1})))}}},EQn=function(s,t,n){var r,a,i,l,o,c=IN(t),d=IN(s.acroField),u=YP(t),h=YP(s.acroField),m=t.getRectangle(),p=t.getAppearanceCharacteristics(),f=t.getBorderStyle(),y=p==null?void 0:p.getCaptions(),v=(r=y==null?void 0:y.normal)!==null&&r!==void 0?r:"",g=(i=(a=y==null?void 0:y.down)!==null&&a!==void 0?a:v)!==null&&i!==void 0?i:"",b=(l=f==null?void 0:f.getWidth())!==null&&l!==void 0?l:0,j=GE(p==null?void 0:p.getRotation()),S=_z(m,j),C=S.width,E=S.height,P=OL(uc(uc({},m),{rotation:j})),M=Fu(0,0,0),I=Cb(p==null?void 0:p.getBorderColor()),D=Cb(p==null?void 0:p.getBackgroundColor()),O=Cb(p==null?void 0:p.getBackgroundColor(),.8),V={x:b,y:b,width:C-b*2,height:E-b*2},G=_6e(v,{alignment:p0.Center,fontSize:u??h,font:n,bounds:V}),$=_6e(g,{alignment:p0.Center,fontSize:u??h,font:n,bounds:V}),H=Math.min(G.fontSize,$.fontSize),Y=(o=c??d)!==null&&o!==void 0?o:M;DN(c||u!==void 0?t:s.acroField,Y,n,H);var Z={x:0+b/2,y:0+b/2,width:C-b,height:E-b,borderWidth:b,borderColor:I,textColor:Y,font:n.name,fontSize:H};return{normal:pu(P,Z5t(uc(uc({},Z),{color:D,textLines:[G.line]}))),down:pu(P,Z5t(uc(uc({},Z),{color:O,textLines:[$.line]})))}},TQn=function(s,t,n){var r,a,i,l,o=IN(t),c=IN(s.acroField),d=YP(t),u=YP(s.acroField),h=t.getRectangle(),m=t.getAppearanceCharacteristics(),p=t.getBorderStyle(),f=(r=s.getText())!==null&&r!==void 0?r:"",y=(a=p==null?void 0:p.getWidth())!==null&&a!==void 0?a:0,v=GE(m==null?void 0:m.getRotation()),g=_z(h,v),b=g.width,j=g.height,S=OL(uc(uc({},h),{rotation:v})),C=Fu(0,0,0),E=Cb(m==null?void 0:m.getBorderColor()),P=Cb(m==null?void 0:m.getBackgroundColor()),M,I,D=s.isCombed()?0:1,O={x:y+D,y:y+D,width:b-(y+D)*2,height:j-(y+D)*2};if(s.isMultiline()){var V=Vns(f,{alignment:s.getAlignment(),fontSize:d??u,font:n,bounds:O});M=V.lines,I=V.fontSize}else if(s.isCombed()){var V=NQn(f,{fontSize:d??u,font:n,bounds:O,cellCount:(i=s.getMaxLength())!==null&&i!==void 0?i:0});M=V.cells,I=V.fontSize}else{var V=_6e(f,{alignment:s.getAlignment(),fontSize:d??u,font:n,bounds:O});M=[V.line],I=V.fontSize}var G=(l=o??c)!==null&&l!==void 0?l:C;DN(o||d!==void 0?t:s.acroField,G,n,I);var $={x:0+y/2,y:0+y/2,width:b-y,height:j-y,borderWidth:y??0,borderColor:E,textColor:G,font:n.name,fontSize:I,color:P,textLines:M,padding:D};return pu(S,zns($))},MQn=function(s,t,n){var r,a,i,l=IN(t),o=IN(s.acroField),c=YP(t),d=YP(s.acroField),u=t.getRectangle(),h=t.getAppearanceCharacteristics(),m=t.getBorderStyle(),p=(r=s.getSelected()[0])!==null&&r!==void 0?r:"",f=(a=m==null?void 0:m.getWidth())!==null&&a!==void 0?a:0,y=GE(h==null?void 0:h.getRotation()),v=_z(u,y),g=v.width,b=v.height,j=OL(uc(uc({},u),{rotation:y})),S=Fu(0,0,0),C=Cb(h==null?void 0:h.getBorderColor()),E=Cb(h==null?void 0:h.getBackgroundColor()),P=1,M={x:f+P,y:f+P,width:g-(f+P)*2,height:b-(f+P)*2},I=_6e(p,{alignment:p0.Left,fontSize:c??d,font:n,bounds:M}),D=I.line,O=I.fontSize,V=(i=l??o)!==null&&i!==void 0?i:S;DN(l||c!==void 0?t:s.acroField,V,n,O);var G={x:0+f/2,y:0+f/2,width:g-f,height:b-f,borderWidth:f??0,borderColor:C,textColor:V,font:n.name,fontSize:O,color:E,textLines:[D],padding:P};return pu(j,zns(G))},PQn=function(s,t,n){var r,a,i=IN(t),l=IN(s.acroField),o=YP(t),c=YP(s.acroField),d=t.getRectangle(),u=t.getAppearanceCharacteristics(),h=t.getBorderStyle(),m=(r=h==null?void 0:h.getWidth())!==null&&r!==void 0?r:0,p=GE(u==null?void 0:u.getRotation()),f=_z(d,p),y=f.width,v=f.height,g=OL(uc(uc({},d),{rotation:p})),b=Fu(0,0,0),j=Cb(u==null?void 0:u.getBorderColor()),S=Cb(u==null?void 0:u.getBackgroundColor()),C=s.getOptions(),E=s.getSelected();s.isSorted()&&C.sort();for(var P="",M=0,I=C.length;M1||a.length===1&&r)&&this.enableMultiselect();for(var o=new Array(a.length),c=0,d=a.length;c1||a.length===1&&r)&&this.enableMultiselect();for(var l=new Array(a.length),o=0,c=a.length;or)throw new vQn(n.length,r,this.getName());this.markAsDirty(),this.disableRichFormatting(),n?this.acroField.setValue(Fl.fromText(n)):this.acroField.removeValue()},t.prototype.getAlignment=function(){var n=this.acroField.getQuadding();return n===0?p0.Left:n===1?p0.Center:n===2?p0.Right:p0.Left},t.prototype.setAlignment=function(n){MM(n,"alignment",p0),this.markAsDirty(),this.acroField.setQuadding(n)},t.prototype.getMaxLength=function(){return this.acroField.getMaxLength()},t.prototype.setMaxLength=function(n){if(wk(n,"maxLength",0,Number.MAX_SAFE_INTEGER),this.markAsDirty(),n===void 0)this.acroField.removeMaxLength();else{var r=this.getText();if(r&&r.length>n)throw new bQn(r.length,n,this.getName());this.acroField.setMaxLength(n)}},t.prototype.removeMaxLength=function(){this.markAsDirty(),this.acroField.removeMaxLength()},t.prototype.setImage=function(n){for(var r=this.getAlignment(),a=r===p0.Center?jP.Center:r===p0.Right?jP.Right:jP.Left,i=this.acroField.getWidgets(),l=0,o=i.length;l{let l=null;try{const o=i.acroField.getWidgets()[0],c=o==null?void 0:o.P();if(c){const d=n.findIndex(u=>u.ref===c);l=d>=0?d:null}}catch{l=null}return{name:i.getName(),type:Gns(i),page:l}})}catch{r=[]}return{pageCount:n.length,hasAcroform:r.length>0,fields:r}}function X5t(s,t){return s.mapping_mode==="blank"?"":s.mapping_mode==="static"||!s.merge_key?s.static_value||"":t[s.merge_key]??""}async function Wns(s,t,n){const r=await xC.load(s,{updateMetadata:!1}),a=await r.embedFont(IG.Helvetica),i={},l=[],o=t.filter(u=>u.mapping_mode!=="overlay"&&u.pdf_field_name);if(o.length){const u=r.getForm();for(const h of o){const m=X5t(h,n),p=h.pdf_field_name;if(!m){l.push(p);continue}try{const f=u.getField(p),y=Gns(f);if(y==="text")f.setText(m);else if(y==="checkbox")/^(true|yes|x|1|checked)$/i.test(m.trim())?f.check():f.uncheck();else if(y==="dropdown"||y==="optionlist")f.select(m);else if(y==="radio")f.select(m);else{l.push(p);continue}i[p]=m}catch{l.push(p)}}try{u.updateFieldAppearances(a)}catch{}try{u.flatten()}catch{}}const c=t.filter(u=>u.mapping_mode==="overlay"&&(u.field_kind==null||u.field_kind==="data"));if(c.length){const u=r.getPages();for(const h of c){const m=X5t(h,n),p=h.pdf_field_name||h.merge_key||h.field_kind||"overlay",f=u[h.page_index??0];if(!m||!f||h.pos_x==null||h.pos_y==null){l.push(p);continue}const{width:y,height:v}=f.getSize(),g=!!h.coords_normalized,b=Number(h.pos_x)*(g?y:1),j=Number(h.width??(g?.2:120))*(g?y:1),S=Number(h.height??(g?.03:18))*(g?v:1),C=Number(h.pos_y)*(g?v:1),E=g?v-C-S:C,P=Number(h.font_size)||(g?Math.min(11,Math.max(7,S*.7)):10);f.drawText(m,{x:g?b+1:b,y:g?E+Math.max(2,(S-P)/2):E,size:P,font:a,color:Fu(0,0,0),maxWidth:g?Math.max(10,j-2):void 0}),i[p]=m}}return{bytes:await r.save(),applied:i,skipped:l}}function Dat(s){const t=s instanceof Error?s.message:String(s);return/encrypt/i.test(t)?"This PDF is password-protected or encrypted. Please upload an unlocked copy.":/xfa/i.test(t)?"This PDF uses an XFA form layer that LevelUp cannot read yet.":/Failed to parse|Invalid PDF|no PDF header/i.test(t)?"That file could not be read as a PDF.":t||"Something went wrong reading the PDF."}const Kns=20*1024*1024,Rat=[{value:"purchase",label:"Purchase"},{value:"listing",label:"Listing"},{value:"disclosure",label:"Disclosure"},{value:"addendum",label:"Addendum"},{value:"other",label:"Other"}];function _x(s){var t;return(t=s==null?void 0:s.versions)!=null&&t.length?[...s.versions].sort((n,r)=>r.version_number-n.version_number)[0]:null}function Fat(s=!1){const t=ha();return at({queryKey:["form-templates",t,s],enabled:!!t,queryFn:async()=>{let n=q.from("form_templates").select("*, versions:form_template_versions(*)").or(`owner_user_id.eq.${t},brokerage_id.not.is.null`).order("created_at",{ascending:!1});s||(n=n.eq("is_archived",!1));const{data:r,error:a}=await n;if(a)throw a;return(r||[]).map(i=>({...i,scope:i.brokerage_id?"brokerage":"mine"}))}})}function qQn(s,t=!1){return at({queryKey:["brokerage-form-templates",s,t],enabled:!!s,queryFn:async()=>{let n=q.from("form_templates").select("*, versions:form_template_versions(*)").eq("brokerage_id",s).order("created_at",{ascending:!1});t||(n=n.eq("is_archived",!1));const{data:r,error:a}=await n;if(a)throw a;return(r||[]).map(i=>({...i,scope:"brokerage"}))}})}function $Qn(){const s=ha(),t=Bt();return mt({mutationFn:async({name:n,description:r,category:a,file:i,templateId:l,brokerageId:o})=>{var g;if(!s)throw new Error("Not authenticated");if(i.type!=="application/pdf"&&!i.name.toLowerCase().endsWith(".pdf"))throw new Error("Only PDF files can be uploaded.");if(i.size>Kns)throw new Error("That PDF is larger than the 20MB limit.");let c;try{c=await UQn(await i.arrayBuffer())}catch(b){throw new Error(Dat(b))}let d=l;if(!d){const{data:b,error:j}=await q.from("form_templates").insert({owner_user_id:s,name:n,description:r||null,category:a,source_type:o?"brokerage":"user_upload",brokerage_id:o||null,is_published:!1}).select().single();if(j)throw j;d=b.id}const{data:u,error:h}=await q.from("form_template_versions").select("version_number").eq("template_id",d).order("version_number",{ascending:!1}).limit(1);if(h)throw h;const m=(((g=u==null?void 0:u[0])==null?void 0:g.version_number)??0)+1,p=`${s}/${d}/v${m}-${crypto.randomUUID()}.pdf`,{error:f}=await q.storage.from("form-templates").upload(p,i,{contentType:"application/pdf"});if(f)throw f;const{data:y,error:v}=await q.from("form_template_versions").insert({template_id:d,version_number:m,storage_path:p,file_name:i.name,file_size:i.size,page_count:c.pageCount,has_acroform:c.hasAcroform,detected_fields:c.fields,mapping_status:c.hasAcroform?"needs_mapping":"needs_placement",effective_date:new Date().toISOString().slice(0,10),created_by:s}).select().single();if(v)throw await q.storage.from("form-templates").remove([p]),v;return{templateId:d,version:y}},onSuccess:()=>{t.invalidateQueries({queryKey:["form-templates"]}),t.invalidateQueries({queryKey:["form-template"]})}})}function Yns(){const s=Bt();return mt({mutationFn:async({id:t,patch:n})=>{const{error:r}=await q.from("form_templates").update(n).eq("id",t);if(r)throw r;return t},onSuccess:()=>{s.invalidateQueries({queryKey:["form-templates"]}),s.invalidateQueries({queryKey:["brokerage-form-templates"]}),s.invalidateQueries({queryKey:["form-template"]})}})}function VQn(){const s=ha(),t=Bt();return mt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const r=_x(n);if(!r)throw new Error("That template has no uploaded PDF yet.");const a=await J8e(r.storage_path),{data:i,error:l}=await q.from("form_templates").insert({owner_user_id:s,name:`${n.name} (copy)`,description:n.description,category:n.category,source_type:"user_upload"}).select().single();if(l)throw l;const o=`${s}/${i.id}/v1-${crypto.randomUUID()}.pdf`,{error:c}=await q.storage.from("form-templates").upload(o,new Blob([a],{type:"application/pdf"}),{contentType:"application/pdf"});if(c)throw c;const{data:d,error:u}=await q.from("form_template_versions").insert({template_id:i.id,version_number:1,storage_path:o,file_name:r.file_name,file_size:r.file_size,page_count:r.page_count,has_acroform:r.has_acroform,detected_fields:r.detected_fields,mapping_status:r.mapping_status,effective_date:new Date().toISOString().slice(0,10),created_by:s}).select().single();if(u)throw await q.storage.from("form-templates").remove([o]),u;const{data:h}=await q.from("form_field_mappings").select("*").eq("version_id",r.id);if(h!=null&&h.length){const m=h.map(({id:f,created_at:y,updated_at:v,version_id:g,...b})=>({...b,version_id:d.id})),{error:p}=await q.from("form_field_mappings").insert(m);if(p)throw p}return i.id},onSuccess:()=>{t.invalidateQueries({queryKey:["form-templates"]})}})}function Zns(){const s=Bt();return mt({mutationFn:async t=>{const n=(t.versions||[]).map(a=>a.storage_path);n.length&&await q.storage.from("form-templates").remove(n);const{error:r}=await q.from("form_templates").delete().eq("id",t.id);if(r)throw r;return t.id},onSuccess:()=>{s.invalidateQueries({queryKey:["form-templates"]})}})}async function J8e(s){const{data:t,error:n}=await q.storage.from("form-templates").download(s);if(n||!t)throw n||new Error("Could not download the template PDF.");return await t.arrayBuffer()}function vk(s){if(!s)return"";try{const t=Ru(s);if(Number.isNaN(t.getTime()))return"";const n=String(t.getMonth()+1).padStart(2,"0"),r=String(t.getDate()).padStart(2,"0");return`${n}/${r}/${t.getFullYear()}`}catch{return""}}function HQn(){const s=new Date,t=String(s.getMonth()+1).padStart(2,"0"),n=String(s.getDate()).padStart(2,"0");return`${t}/${n}/${s.getFullYear()}`}function GQn(s){if(s==null||Number.isNaN(s))return"";const t=Math.round(s*100)%100!==0;return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t?2:0,maximumFractionDigits:t?2:0}).format(s)}function Oat(s){return s?s<1024*1024?`${(s/1024).toFixed(0)} KB`:`${(s/(1024*1024)).toFixed(1)} MB`:"0 KB"}const DG=[{key:"deal.name",label:"Deal name",group:"Deal",aliases:["deal","transaction name","file name"]},{key:"deal.type",label:"Deal type",group:"Deal",aliases:["transaction type","side"]},{key:"deal.property_address",label:"Property address",group:"Deal",aliases:["property","subject property","street","address of property","premises"]},{key:"deal.city",label:"Property city",group:"Deal",aliases:["property city","city"]},{key:"deal.state",label:"Property state",group:"Deal",aliases:["property state","state"]},{key:"deal.zip",label:"Property ZIP",group:"Deal",aliases:["zip","zipcode","postal"]},{key:"deal.price",label:"Price",group:"Deal",aliases:["purchase price","sale price","sales price","list price","offer price","amount"]},{key:"deal.contract_date",label:"Contract date",group:"Deal",aliases:["contract","acceptance date","effective date","binding date"]},{key:"deal.target_close_date",label:"Target close date",group:"Deal",aliases:["closing date","close date","settlement date","coe"]},{key:"deal.actual_close_date",label:"Actual close date",group:"Deal",aliases:["closed date","actual close"]},{key:"deal.listing_date",label:"Listing date",group:"Deal",aliases:["list date","listing start"]},{key:"deal.inspection_date",label:"Inspection date",group:"Deal",aliases:["inspection"]},{key:"deal.inspection_contingency_date",label:"Inspection contingency date",group:"Deal",aliases:["inspection contingency","due diligence"]},{key:"deal.appraisal_date",label:"Appraisal date",group:"Deal",aliases:["appraisal"]},{key:"deal.loan_approval_date",label:"Loan approval date",group:"Deal",aliases:["loan approval","financing contingency","mortgage commitment"]},{key:"deal.earnest_money_due_date",label:"Earnest money due date",group:"Deal",aliases:["earnest money","emd","deposit due"]},{key:"deal.title_docs_due_date",label:"Title docs due date",group:"Deal",aliases:["title","title commitment"]},{key:"deal.final_walkthrough_date",label:"Final walkthrough date",group:"Deal",aliases:["walkthrough","walk through","final walk"]},{key:"contact.first_name",label:"Client first name",group:"Contact",aliases:["buyer first","seller first","client first","first name"]},{key:"contact.last_name",label:"Client last name",group:"Contact",aliases:["buyer last","seller last","client last","last name","surname"]},{key:"contact.full_name",label:"Client full name",group:"Contact",aliases:["buyer name","seller name","client name","purchaser","buyer","seller","client"]},{key:"contact.email",label:"Client email",group:"Contact",aliases:["buyer email","seller email","client email","email"]},{key:"contact.phone",label:"Client phone",group:"Contact",aliases:["buyer phone","seller phone","client phone","phone","telephone","mobile"]},{key:"contact.address",label:"Client address",group:"Contact",aliases:["buyer address","seller address","mailing address","client address"]},{key:"contact.city",label:"Client city",group:"Contact",aliases:["buyer city","seller city"]},{key:"contact.state",label:"Client state",group:"Contact",aliases:["buyer state","seller state"]},{key:"contact.zip",label:"Client ZIP",group:"Contact",aliases:["buyer zip","seller zip"]},{key:"contact.spouse_name",label:"Spouse name",group:"Contact",aliases:["spouse","co buyer","cobuyer","co seller","partner name","buyer 2","seller 2"]},{key:"contact.spouse_email",label:"Spouse email",group:"Contact",aliases:["spouse email","co buyer email","buyer 2 email"]},{key:"agent.name",label:"Agent name",group:"Agent",aliases:["agent","realtor","listing agent","broker name","salesperson"]},{key:"agent.email",label:"Agent email",group:"Agent",aliases:["agent email","broker email"]},{key:"agent.phone",label:"Agent phone",group:"Agent",aliases:["agent phone","broker phone"]},{key:"agent.brokerage_name",label:"Brokerage name",group:"Agent",aliases:["brokerage","firm","company","office"]},{key:"agent.license_number",label:"Agent license number",group:"Agent",aliases:["license","license no","dre","bre","lic"]},{key:"agent.license_state",label:"Agent license state",group:"Agent",aliases:["license state"]},{key:"agent.website_url",label:"Agent website",group:"Agent",aliases:["website","web site","url"]},{key:"agent.title",label:"Agent title",group:"Agent",aliases:["agent title","designation"]},{key:"today",label:"Today's date",group:"Other",aliases:["date","today","date signed","dated"]}],Xns=new Map(DG.map(s=>[s.key,s])),WQn={buyer:"Buyer",seller:"Seller",dual:"Dual",referral:"Referral",lease:"Lease"};function KQn(s){const t=s.deal||{},n=s.contact||{},r=s.profile||{},a=s.brand||{},i=[n.first_name,n.last_name].filter(Boolean).join(" ").trim(),l=t.sale_price??t.expected_price??null;return{"deal.name":t.deal_name||"","deal.type":WQn[t.deal_type]||t.deal_type||"","deal.property_address":t.property_address||"","deal.city":t.city||"","deal.state":t.state||"","deal.zip":t.zip_code||"","deal.price":GQn(l),"deal.contract_date":vk(t.contract_date),"deal.target_close_date":vk(t.target_close_date),"deal.actual_close_date":vk(t.actual_close_date),"deal.listing_date":vk(t.listing_date),"deal.inspection_date":vk(t.inspection_date),"deal.inspection_contingency_date":vk(t.inspection_contingency_date),"deal.appraisal_date":vk(t.appraisal_date),"deal.loan_approval_date":vk(t.loan_approval_date),"deal.earnest_money_due_date":vk(t.earnest_money_due_date),"deal.title_docs_due_date":vk(t.title_docs_due_date),"deal.final_walkthrough_date":vk(t.final_walkthrough_date),"contact.first_name":n.first_name||"","contact.last_name":n.last_name||"","contact.full_name":i,"contact.email":n.email||"","contact.phone":n.phone||"","contact.address":n.address||"","contact.city":n.city||"","contact.state":n.state||"","contact.zip":n.zip||n.zip_code||"","contact.spouse_name":n.spouse_name||"","contact.spouse_email":n.spouse_email||"","agent.name":r.name||"","agent.email":r.email||"","agent.phone":r.phone||"","agent.brokerage_name":r.brokerage_name||a.brokerage_name||"","agent.license_number":a.license_number||"","agent.license_state":a.license_state||"","agent.website_url":r.website_url||"","agent.title":r.title||"",today:HQn()}}function zat(s){const t=ha();return at({queryKey:["form-merge-data",s,t],enabled:!!s&&!!t,queryFn:async()=>{const{data:n,error:r}=await q.from("deal_pipeline").select("*").eq("id",s).maybeSingle();if(r)throw r;let a=null;if(n!=null&&n.contact_id){const{data:c}=await q.from("innercircle_contacts").select("*").eq("id",n.contact_id).maybeSingle();a=c}const[{data:i},{data:l}]=await Promise.all([q.from("profiles").select("*").eq("id",t).maybeSingle(),q.from("agent_brand_profiles").select("*").eq("user_id",t).maybeSingle()]),o={deal:n,contact:a,profile:i,brand:l};return{sources:o,values:KQn(o)}}})}function YQn(s){return at({queryKey:["form-generations",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("form_generations").select("*, template:form_templates(name), version:form_template_versions(version_number)").eq("deal_id",s).order("created_at",{ascending:!1});if(n)throw n;return t||[]}})}function ZQn(){const s=ha(),t=Bt();return mt({mutationFn:async({dealId:n,template:r,version:a,values:i})=>{if(!s)throw new Error("Not authenticated");const{data:l,error:o}=await q.from("form_field_mappings").select("*").eq("version_id",a.id);if(o)throw o;if(!(l!=null&&l.length))throw new Error("This template has no field mapping yet.");const c=await J8e(a.storage_path);let d;try{d=await Wns(c,l,i)}catch(j){throw new Error(Dat(j))}const h=`${r.name.replace(/[^a-zA-Z0-9-_ ]/g,"").trim()||"Form"} - v${a.version_number}.pdf`,m=d.bytes.buffer.slice(d.bytes.byteOffset,d.bytes.byteOffset+d.bytes.byteLength),p=new Blob([m],{type:"application/pdf"}),f=`${s}/${n}/${crypto.randomUUID()}.pdf`,{error:y}=await q.storage.from("deal-files").upload(f,p,{contentType:"application/pdf"});if(y)throw y;const{data:v,error:g}=await q.from("deal_files").insert({deal_id:n,owner_user_id:s,file_name:h,file_size:p.size,file_type:"application/pdf",storage_path:f}).select().single();if(g)throw g;const{error:b}=await q.from("form_generations").insert({owner_user_id:s,deal_id:n,template_id:r.id,version_id:a.id,deal_file_id:v.id,merge_snapshot:{values:i,applied:d.applied,skipped:d.skipped}});if(b)throw b;return await q.from("deal_activities").insert({deal_id:n,activity_type:"document",title:`Generated ${r.name}`,description:`${h} was generated from a LevelUp form template (v${a.version_number}).`,metadata:{template_id:r.id,version_id:a.id,deal_file_id:v.id}}),{dealFile:v,blob:p,fileName:h,skipped:d.skipped}},onSuccess:(n,r)=>{t.invalidateQueries({queryKey:["deal-files",r.dealId]}),t.invalidateQueries({queryKey:["deal-activities"]}),t.invalidateQueries({queryKey:["form-generations",r.dealId]})}})}function hie(s){return at({queryKey:["form-field-mappings",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("form_field_mappings").select("*").eq("version_id",s).order("created_at",{ascending:!0});if(n)throw n;return t||[]}})}function XQn(){const s=Bt();return mt({mutationFn:async({versionId:t,mappings:n,hasAcroform:r})=>{const{error:a}=await q.from("form_field_mappings").delete().eq("version_id",t);if(a)throw a;const i=n.map(d=>({version_id:t,pdf_field_name:d.pdf_field_name,mapping_mode:d.mapping_mode,merge_key:d.merge_key,static_value:d.static_value,page_index:d.page_index??null,pos_x:d.pos_x??null,pos_y:d.pos_y??null,font_size:d.font_size??null}));if(i.length){const{error:d}=await q.from("form_field_mappings").insert(i);if(d)throw d}const l=n.some(d=>d.mapping_mode==="acroform"&&d.merge_key||d.mapping_mode==="static"||d.mapping_mode==="overlay"&&d.merge_key),o=r?l?"mapped":"needs_mapping":l?"mapped":"needs_placement",{error:c}=await q.from("form_template_versions").update({mapping_status:o}).eq("id",t);if(c)throw c;return t},onSuccess:t=>{s.invalidateQueries({queryKey:["form-field-mappings",t]}),s.invalidateQueries({queryKey:["form-templates"]}),s.invalidateQueries({queryKey:["form-template"]})}})}function Qns({open:s,onOpenChange:t,dealId:n,dealName:r,initialTemplateId:a}){const{data:i=[],isLoading:l}=Fat(),[o,c]=_.useState(a),{data:d,isLoading:u,error:h}=zat(s?n:void 0),m=ZQn(),p=_.useMemo(()=>i.find(E=>E.id===o),[i,o]),f=_x(p),{data:y=[],isLoading:v}=hie(s?f==null?void 0:f.id:void 0);_.useEffect(()=>{s&&a&&c(a)},[s,a]);const g=i.filter(E=>{var P;return((P=_x(E))==null?void 0:P.mapping_status)==="mapped"}),b=_.useMemo(()=>d?y.filter(E=>E.merge_key||E.static_value).map(E=>{var P;return{field:E.pdf_field_name||E.merge_key||"",label:E.merge_key?((P=Xns.get(E.merge_key))==null?void 0:P.label)||E.merge_key:"Fixed text",value:E.mapping_mode==="static"?E.static_value||"":d.values[E.merge_key||""]||""}}):[],[y,d]),j=b.filter(E=>!E.value).length,S=async()=>{if(!(!p||!f||!d))try{const E=await m.mutateAsync({dealId:n,template:p,version:f,values:d.values});se.success(`${E.fileName} saved to this deal's files`),t(!1)}catch(E){se.error((E==null?void 0:E.message)||"Could not generate the form")}},C=(f==null?void 0:f.mapping_status)==="mapped";return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"max-w-2xl max-h-[90vh] overflow-hidden flex flex-col",children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Prepare a form"}),e.jsx(_r,{children:r?`Fill a template with data from ${r}.`:"Fill a template with this deal’s data."})]}),e.jsxs("div",{className:"space-y-4 overflow-y-auto",children:[e.jsxs(is,{value:o,onValueChange:c,disabled:l,children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:l?"Loading templates…":"Choose a template"})}),e.jsx(as,{children:i.map(E=>{const P=_x(E);return e.jsxs(He,{value:E.id,disabled:(P==null?void 0:P.mapping_status)!=="mapped",children:[E.name,E.scope==="brokerage"?" · Brokerage":"",(P==null?void 0:P.mapping_status)!=="mapped"?" — needs mapping":""]},E.id)})})]}),!l&&i.length===0&&e.jsx("p",{className:"rounded-lg border border-dashed p-6 text-center text-sm text-muted-foreground",children:"No form templates yet. Upload one in Forms Library first."}),!l&&i.length>0&&g.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"None of your templates are mapped yet. Finish mapping one in Forms Library."}),h&&e.jsx("p",{className:"text-sm text-destructive",children:"Could not load this deal’s data. Please try again."}),p&&e.jsxs(e.Fragment,{children:[(u||v)&&e.jsx("div",{className:"flex justify-center py-6",children:e.jsx(Ct,{className:"h-5 w-5 animate-spin text-muted-foreground"})}),!u&&!v&&C&&e.jsxs("div",{className:"rounded-lg border",children:[e.jsxs("div",{className:"flex items-center justify-between border-b px-3 py-2 text-xs font-medium text-muted-foreground",children:[e.jsx("span",{children:"What will be filled in"}),j>0&&e.jsxs(Oe,{variant:"outline",className:"gap-1 text-[10px]",children:[e.jsx(xl,{className:"h-3 w-3"})," ",j," blank"]})]}),e.jsx(Ji,{className:"max-h-[280px]",children:e.jsxs("div",{className:"divide-y",children:[b.map((E,P)=>e.jsxs("div",{className:"flex items-center gap-3 px-3 py-2 text-sm",children:[e.jsx("span",{className:"w-1/3 shrink-0 truncate text-muted-foreground",children:E.label}),e.jsx("span",{className:E.value?"truncate":"truncate italic text-muted-foreground/60",children:E.value||"not set"})]},`${E.field}-${P}`)),b.length===0&&e.jsx("p",{className:"p-4 text-center text-sm text-muted-foreground",children:"This template has no mapped fields yet."})]})})]}),!C&&f&&e.jsx("p",{className:"rounded-lg bg-muted/50 p-3 text-sm text-muted-foreground",children:f.has_acroform?"This template still needs its fields mapped.":"This PDF has no fillable fields, so it needs field placement before it can be used."})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{onClick:S,disabled:!C||m.isPending||b.length===0,children:[m.isPending?e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(KO,{className:"mr-2 h-4 w-4"}),m.isPending?"Generating…":"Generate & save to deal"]})]})]})})}const QQn=["Client","Co-Buyer","Co-Seller","Spouse","Lender","Title Company","Inspector","Appraiser","Attorney","Contractor","Other"];function Jns(s){return at({queryKey:["deal-contacts",s],queryFn:async()=>{const{data:t,error:n}=await q.from("deal_contacts").select(` id, deal_id, contact_id, role, created_at, contact:innercircle_contacts(id, first_name, last_name, email, phone) `).eq("deal_id",s).order("created_at");if(n)throw n;return t||[]},enabled:!!s})}function JQn(){const s=Bt();return mt({mutationFn:async({dealId:t,contactId:n,role:r})=>{const{data:a,error:i}=await q.from("deal_contacts").insert({deal_id:t,contact_id:n,role:r}).select().single();if(i)throw i;return a},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["deal-contacts",n.dealId]}),se.success("Contact linked to deal")},onError:t=>{var n;(n=t.message)!=null&&n.includes("duplicate")?se.error("This contact is already linked to this deal"):se.error("Failed to link contact")}})}function eJn(){const s=Bt();return mt({mutationFn:async({id:t,dealId:n})=>{const{error:r}=await q.from("deal_contacts").delete().eq("id",t);if(r)throw r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["deal-contacts",n.dealId]}),se.success("Contact removed from deal")},onError:()=>{se.error("Failed to remove contact")}})}const Bat=[{value:"buyer_1",label:"Buyer 1"},{value:"buyer_2",label:"Buyer 2"},{value:"seller_1",label:"Seller 1"},{value:"seller_2",label:"Seller 2"},{value:"agent",label:"Agent (you)"}];function eDe(s){var t;return((t=Bat.find(n=>n.value===s))==null?void 0:t.label)||s||"Signer"}function tJn(s){const t=ha();return at({queryKey:["form-envelopes",t,s||"all"],enabled:!!t,queryFn:async()=>{let n=q.from("form_envelopes").select("*, template:form_templates(name), version:form_template_versions(version_number), signers:form_envelope_signers(*)").eq("owner_user_id",t).neq("status","draft").order("created_at",{ascending:!1});s&&(n=n.eq("deal_id",s));const{data:r,error:a}=await n;if(a)throw a;return r||[]}})}function sJn(){const s=ha(),t=Bt();return mt({mutationFn:async({dealId:n,template:r,version:a,title:i,message:l,values:o,signers:c})=>{if(!s)throw new Error("Not authenticated");const{data:d,error:u}=await q.from("form_envelopes").insert({owner_user_id:s,deal_id:n,template_id:r.id,version_id:a.id,title:i,message:l||null,merge_snapshot:o}).select("id").single();if(u)throw u;const{data:h,error:m}=await q.functions.invoke("forms-envelope-send",{body:{action:"send",envelope_id:d.id,signers:c}});if(m)throw new Error(m.message||"Could not send the signature request");if(h!=null&&h.error)throw new Error(h.error);return await q.from("deal_activities").insert({deal_id:n,activity_type:"document",title:`Sent for signature: ${i}`,description:`${r.name} (v${a.version_number}) sent to ${c.length} signer${c.length===1?"":"s"}.`,metadata:{envelope_id:d.id,template_id:r.id,version_id:a.id}}),{envelopeId:d.id,result:h}},onSuccess:(n,r)=>{t.invalidateQueries({queryKey:["form-envelopes"]}),t.invalidateQueries({queryKey:["deal-activities"]})}})}function nJn(){const s=Bt();return mt({mutationFn:async({envelopeId:t,action:n,reason:r})=>{const{data:a,error:i}=await q.functions.invoke("forms-envelope-send",{body:{action:n,envelope_id:t,reason:r}});if(i)throw new Error(i.message||"That action failed");if(a!=null&&a.error)throw new Error(a.error);return a},onSuccess:()=>{s.invalidateQueries({queryKey:["form-envelopes"]})}})}function ers(){const s=ha();return at({queryKey:["form-packets",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("form_packets").select("*, items:form_packet_items(*)").eq("owner_user_id",s).eq("is_archived",!1).order("created_at",{ascending:!1});if(n)throw n;return t||[]}})}function Uat(s,t){var n;return(n=s==null?void 0:s.items)!=null&&n.length?[...s.items].sort((r,a)=>r.sort_order-a.sort_order).map(r=>t.find(a=>a.id===r.template_id)).filter(Boolean):[]}function rJn(){const s=ha(),t=Bt();return mt({mutationFn:async({id:n,name:r,description:a,templateIds:i})=>{if(!s)throw new Error("Not authenticated");let l=n;if(l){const{error:o}=await q.from("form_packets").update({name:r,description:a||null,updated_at:new Date().toISOString()}).eq("id",l);if(o)throw o;const{error:c}=await q.from("form_packet_items").delete().eq("packet_id",l);if(c)throw c}else{const{data:o,error:c}=await q.from("form_packets").insert({owner_user_id:s,name:r,description:a||null}).select("id").single();if(c)throw c;l=o.id}if(i.length){const{error:o}=await q.from("form_packet_items").insert(i.map((c,d)=>({packet_id:l,template_id:c,sort_order:d})));if(o)throw o}return l},onSuccess:()=>t.invalidateQueries({queryKey:["form-packets"]})})}function aJn(){const s=Bt();return mt({mutationFn:async t=>{const{error:n}=await q.from("form_packets").delete().eq("id",t);if(n)throw n;return t},onSuccess:()=>s.invalidateQueries({queryKey:["form-packets"]})})}function iJn(){const s=ha(),t=Bt();return mt({mutationFn:async({dealId:n,packet:r,templates:a,titlePrefix:i,message:l,values:o,signers:c})=>{if(!s)throw new Error("Not authenticated");const d=Uat(r,a);if(!d.length)throw new Error("This packet has no templates in it yet.");const u=crypto.randomUUID(),h=[];for(let m=0;mE.field_kind&&E.field_kind!=="data"&&E.signer_role).map(E=>E.signer_role)),j=c.filter(E=>b.has(E.signer_role));if(!j.length)throw new Error(`${p.name} has no signature fields placed yet.`);const{data:S,error:C}=await q.functions.invoke("forms-envelope-send",{body:{action:"send",envelope_id:y.id,signers:j.map((E,P)=>({...E,order_index:P})),notify:m===0}});if(C)throw new Error(C.message||"Could not send the packet");if(S!=null&&S.error)throw new Error(S.error)}return await q.from("deal_activities").insert({deal_id:n,activity_type:"document",title:`Sent packet for signature: ${r.name}`,description:`${d.length} document${d.length===1?"":"s"} sent to ${c.length} signer${c.length===1?"":"s"}.`,metadata:{packet_id:r.id,packet_run_id:u,envelope_ids:h}}),{runId:u,envelopeIds:h}},onSuccess:()=>{t.invalidateQueries({queryKey:["form-envelopes"]}),t.invalidateQueries({queryKey:["deal-activities"]})}})}function trs({open:s,onOpenChange:t,dealId:n,dealName:r,initialTemplateId:a}){const{data:i=[],isLoading:l}=Fat(),[o,c]=_.useState(a),{data:d,isLoading:u}=zat(s?n:void 0),{data:h=[]}=Jns(n),{data:m=[]}=ers(),p=sJn(),f=iJn(),[y,v]=_.useState("single"),[g,b]=_.useState(void 0),j=_.useMemo(()=>m.find(le=>le.id===g),[m,g]),S=_.useMemo(()=>Uat(j,i),[j,i]),{data:C=[],isLoading:E}=at({queryKey:["packet-signer-roles",g,S.map(le=>{var be;return(be=_x(le))==null?void 0:be.id}).join(",")],enabled:y==="packet"&&S.length>0,queryFn:async()=>{const le=S.map(pe=>{var Ce;return(Ce=_x(pe))==null?void 0:Ce.id}).filter(Boolean);if(!le.length)return[];const{data:be,error:me}=await q.from("form_field_mappings").select("field_kind, signer_role").in("version_id",le);if(me)throw me;const he=new Set;for(const pe of be||[])pe.field_kind&&pe.field_kind!=="data"&&pe.signer_role&&he.add(pe.signer_role);return[...he]}}),P=_.useMemo(()=>i.find(le=>le.id===o),[i,o]),M=_x(P),{data:I=[],isLoading:D}=hie(s?M==null?void 0:M.id:void 0),[O,V]=_.useState(""),[G,$]=_.useState(""),[H,Y]=_.useState({});_.useEffect(()=>{s&&a&&c(a)},[s,a]);const Z=_.useMemo(()=>{const le=new Set;if(y==="packet")for(const me of C)le.add(me);else for(const me of I)me.field_kind&&me.field_kind!=="data"&&me.signer_role&&le.add(me.signer_role);const be=Bat.map(me=>me.value);return[...le].sort((me,he)=>be.indexOf(me)-be.indexOf(he))},[I,y,C]);_.useEffect(()=>{var he,pe,Ce;const le={},be=h.filter(Ae=>Ae.contact);let me=0;for(const Ae of Z)if(Ae==="agent"){const Pe=(he=d==null?void 0:d.sources)==null?void 0:he.profile;le[Ae]={name:(Pe==null?void 0:Pe.full_name)||"",email:(Pe==null?void 0:Pe.email)||"",contact_id:null}}else{const Pe=be[me++],ze=Pe!=null&&Pe.contact?`${Pe.contact.first_name||""} ${Pe.contact.last_name||""}`.trim():"";le[Ae]={name:ze,email:((pe=Pe==null?void 0:Pe.contact)==null?void 0:pe.email)||"",contact_id:((Ce=Pe==null?void 0:Pe.contact)==null?void 0:Ce.id)||null}}Y(le),y==="single"&&P&&!O&&V(r?`${P.name} – ${r}`:P.name)},[Z,h,d,o,g,y]);const ne=(M==null?void 0:M.mapping_status)==="mapped",ce=(le,be)=>Y(me=>({...me,[le]:{...me[le],...be}})),ie=Z.length>0&&Z.every(le=>{var be,me,he;return((me=(be=H[le])==null?void 0:be.name)==null?void 0:me.trim())&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(((he=H[le])==null?void 0:he.email)||"")}),te=p.isPending||f.isPending,ae=async()=>{if(!d)return;const le=Z.map((be,me)=>({full_name:H[be].name.trim(),email:H[be].email.trim(),signer_role:be,contact_id:H[be].contact_id,is_agent:be==="agent",order_index:me}));try{if(y==="packet"){if(!j)return;await f.mutateAsync({dealId:n,packet:j,templates:i,titlePrefix:r||"",message:G.trim()||void 0,values:d.values,signers:le}),se.success(`${S.length} documents sent to ${le[0].full_name}`)}else{if(!P||!M)return;await p.mutateAsync({dealId:n,template:P,version:M,title:O.trim()||P.name,message:G.trim()||void 0,values:d.values,signers:le}),se.success(`Signature request sent to ${le[0].full_name}`)}t(!1)}catch(be){se.error((be==null?void 0:be.message)||"Could not send the signature request")}};return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"flex max-h-[90vh] max-w-xl flex-col overflow-hidden",children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Send for signature"}),e.jsx(_r,{children:r?`Fill a template with ${r}'s data, then email it for e-signature.`:"Fill a template with this deal’s data, then email it for e-signature."})]}),e.jsxs("div",{className:"space-y-4 overflow-y-auto",children:[m.length>0&&e.jsx("div",{className:"flex gap-1 rounded-lg bg-muted p-1",children:["single","packet"].map(le=>e.jsx("button",{onClick:()=>v(le),className:`flex-1 rounded-md px-3 py-1.5 text-xs font-medium transition-colors ${y===le?"bg-background shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:le==="single"?"One form":"Packet"},le))}),y==="packet"?e.jsxs(e.Fragment,{children:[e.jsxs(is,{value:g,onValueChange:b,children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Choose a packet"})}),e.jsx(as,{children:m.map(le=>{var be;return e.jsxs(He,{value:le.id,children:[le.name," (",((be=le.items)==null?void 0:be.length)??0," forms)"]},le.id)})})]}),S.length>0&&e.jsxs("div",{className:"rounded-lg border bg-muted/40 p-3 text-xs",children:[e.jsx("p",{className:"mb-1.5 font-semibold",children:"Signers move through these in one session:"}),e.jsx("ol",{className:"ml-4 list-decimal space-y-0.5 text-muted-foreground",children:S.map(le=>{var be;return e.jsxs("li",{children:[le.name,((be=_x(le))==null?void 0:be.mapping_status)!=="mapped"?" — not ready":""]},le.id)})})]})]}):e.jsxs(is,{value:o,onValueChange:c,disabled:l,children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:l?"Loading templates…":"Choose a template"})}),e.jsx(as,{children:i.map(le=>{const be=_x(le);return e.jsxs(He,{value:le.id,disabled:(be==null?void 0:be.mapping_status)!=="mapped",children:[le.name,le.scope==="brokerage"?" · Brokerage":"",(be==null?void 0:be.mapping_status)!=="mapped"?" — not ready":""]},le.id)})})]}),(y==="packet"?j:P)&&(u||D||E)&&e.jsx("div",{className:"flex justify-center py-6",children:e.jsx(Ct,{className:"h-5 w-5 animate-spin text-muted-foreground"})}),(y==="packet"?!!j&&!E:!!P&&!D&&ne)&&Z.length===0&&e.jsxs("div",{className:"flex items-start gap-2 rounded-lg bg-muted/50 p-3 text-sm text-muted-foreground",children:[e.jsx(xl,{className:"mt-0.5 h-4 w-4 shrink-0"}),e.jsxs("span",{children:["This template has no signature fields yet. Open it in the Forms Library and use"," ",e.jsx("strong",{children:"Place fields & signatures"})," to add signature, initials, and date boxes first."]})]}),Z.length>0&&e.jsxs(e.Fragment,{children:[y==="single"&&P&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs",children:"Document title"}),e.jsx(xe,{value:O,onChange:le=>V(le.target.value),placeholder:P.name})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(J,{className:"text-xs",children:"Signers (sign in this order)"}),e.jsxs(Oe,{variant:"outline",className:"text-[10px]",children:[Z.length," signer",Z.length===1?"":"s"]})]}),Z.map((le,be)=>{var me,he,pe;return e.jsxs("div",{className:"space-y-2 rounded-lg border p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-xs font-semibold",children:[be+1,". ",eDe(le)]}),le!=="agent"&&h.length>0&&e.jsxs(is,{value:((me=H[le])==null?void 0:me.contact_id)||"",onValueChange:Ce=>{const Ae=h.find(Pe=>{var ze;return((ze=Pe.contact)==null?void 0:ze.id)===Ce});Ae!=null&&Ae.contact&&ce(le,{contact_id:Ce,name:`${Ae.contact.first_name||""} ${Ae.contact.last_name||""}`.trim(),email:Ae.contact.email||""})},children:[e.jsx(rs,{className:"h-7 w-44 text-[11px]",children:e.jsx(ls,{placeholder:"Pick deal contact…"})}),e.jsx(as,{children:h.map(Ce=>Ce.contact?e.jsxs(He,{value:Ce.contact.id,className:"text-xs",children:[Ce.contact.first_name," ",Ce.contact.last_name]},Ce.contact.id):null)})]})]}),e.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[e.jsx(xe,{className:"h-8 text-xs",placeholder:"Full name",value:((he=H[le])==null?void 0:he.name)||"",onChange:Ce=>ce(le,{name:Ce.target.value,contact_id:null})}),e.jsx(xe,{className:"h-8 text-xs",type:"email",placeholder:"Email address",value:((pe=H[le])==null?void 0:pe.email)||"",onChange:Ce=>ce(le,{email:Ce.target.value,contact_id:null})})]})]},le)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs",children:"Message (optional)"}),e.jsx(Ms,{rows:2,placeholder:"Added to the signature request email",value:G,onChange:le=>$(le.target.value)})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:y==="packet"?"The first signer gets one secure email link and moves straight through every document in the packet with the same adopted signature. Reminders go out automatically on day 3 and day 10.":"The first signer gets a secure email link now; each next signer is notified automatically after the previous one signs. The agent countersigns last, inside LevelUp. Reminders go out automatically on day 3 and day 10."})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{onClick:ae,disabled:!ie||te||u,children:[te?e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Qm,{className:"mr-2 h-4 w-4"}),te?"Sending…":y==="packet"?`Send ${S.length||""} document${S.length===1?"":"s"}`.replace(" "," "):"Send signature request"]})]})]})})}function oJn({status:s}){switch(s){case"completed":return e.jsx(Oe,{className:"bg-emerald-500/15 text-emerald-600 hover:bg-emerald-500/15",children:"Completed"});case"partially_signed":return e.jsx(Oe,{className:"bg-amber-500/15 text-amber-600 hover:bg-amber-500/15",children:"Partially signed"});case"sent":return e.jsx(Oe,{variant:"secondary",children:"Sent"});case"declined":return e.jsx(Oe,{variant:"destructive",children:"Declined"});case"voided":return e.jsx(Oe,{variant:"outline",children:"Voided"});case"expired":return e.jsx(Oe,{variant:"outline",children:"Expired"});case"finalize_failed":return e.jsx(Oe,{variant:"destructive",children:"Needs attention"});default:return e.jsx(Oe,{variant:"secondary",children:s})}}function lJn({envelope:s}){const t=Fn(),n=nJn(),r=[...s.signers||[]].sort((m,p)=>m.order_index-p.order_index),a=r.some((m,p)=>m.is_agent&&m.status!=="signed"&&r.slice(0,p).every(f=>f.status==="signed")),i=s.status==="sent"||s.status==="partially_signed",l=r.find(m=>m.declined_at),o=i&&s.expires_at?Math.ceil((new Date(s.expires_at).getTime()-Date.now())/864e5):null,c=async()=>{try{const m=await n.mutateAsync({envelopeId:s.id,action:"audit_pdf"});if(!(m!=null&&m.pdf_base64))throw new Error("No audit trail was returned");const p=atob(m.pdf_base64),f=new Uint8Array(p.length);for(let g=0;g{if(!s.completed_storage_path)return;const{data:m,error:p}=await q.storage.from("deal-files").createSignedUrl(s.completed_storage_path,300);if(p||!m)return se.error("Could not download the signed document");window.open(m.signedUrl,"_blank")},u=async()=>{try{const m=await n.mutateAsync({envelopeId:s.id,action:"agent_link"});m!=null&&m.path&&t(m.path)}catch(m){se.error((m==null?void 0:m.message)||"Could not open countersigning")}},h=async()=>{const m=window.prompt("Why is this being voided? (optional)")??void 0;if(m!==void 0)try{await n.mutateAsync({envelopeId:s.id,action:"void",reason:m}),se.success("Envelope voided")}catch(p){se.error((p==null?void 0:p.message)||"Could not void")}};return e.jsxs("div",{className:"rounded-lg border bg-background p-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded bg-primary/10",children:e.jsx(Qm,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:s.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:r.map(m=>`${m.full_name} (${eDe(m.signer_role)}): ${m.status.replace("_"," ")}`).join(" · ")})]}),e.jsx(oJn,{status:s.status})]}),l&&e.jsxs("div",{className:"mt-2 ml-11 rounded-md border border-destructive/30 bg-destructive/5 p-2 text-xs text-destructive",children:[e.jsxs("span",{className:"font-semibold",children:[l.full_name," declined."]})," ",l.decline_reason||"No reason was given."]}),o!==null&&o<=4&&e.jsx("p",{className:"mt-2 ml-11 text-xs text-amber-600",children:o>0?`Expires in ${o} day${o===1?"":"s"} — reminders go out automatically.`:"Expires today — reminders go out automatically."}),(i||s.status==="completed"||s.status==="declined")&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-2 pl-11",children:[i&&e.jsxs(B,{variant:"outline",size:"sm",className:"h-7 text-xs",disabled:n.isPending,onClick:async()=>{try{await n.mutateAsync({envelopeId:s.id,action:"remind"}),se.success("Reminder sent")}catch(m){se.error((m==null?void 0:m.message)||"Could not send a reminder")}},children:[e.jsx($4,{className:"mr-1 h-3 w-3"})," Remind"]}),a&&e.jsxs(B,{size:"sm",className:"h-7 text-xs",disabled:n.isPending,onClick:u,children:[e.jsx(KA,{className:"mr-1 h-3 w-3"})," Countersign now"]}),s.status==="completed"&&e.jsxs(B,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:d,children:[e.jsx(li,{className:"mr-1 h-3 w-3"})," Signed PDF"]}),e.jsxs(B,{variant:"ghost",size:"sm",className:"h-7 text-xs",disabled:n.isPending,onClick:c,children:[e.jsx(e$,{className:"mr-1 h-3 w-3"})," Audit trail"]}),i&&e.jsxs(B,{variant:"ghost",size:"sm",className:"h-7 text-xs text-destructive",disabled:n.isPending,onClick:h,children:[e.jsx(VO,{className:"mr-1 h-3 w-3"})," Void"]})]})]})}function cJn({dealId:s,dealName:t}){const[n,r]=_.useState(!1),[a,i]=_.useState(!1),{data:l=[],isLoading:o,error:c}=YQn(s),{data:d=[]}=tJn(s);return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row",children:[e.jsxs(B,{className:"flex-1",onClick:()=>i(!0),children:[e.jsx(Qm,{className:"mr-2 h-4 w-4"})," Send for signature"]}),e.jsxs(B,{variant:"outline",className:"flex-1",onClick:()=>r(!0),children:[e.jsx(Iq,{className:"mr-2 h-4 w-4"})," Prepare a form"]}),e.jsxs(B,{variant:"outline",className:"sm:w-auto",onClick:()=>window.open("/mission-control/forms","_blank","noopener,noreferrer"),children:[e.jsx(wr,{className:"mr-2 h-4 w-4"})," Forms Library"]})]}),d.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Signature requests"}),d.map(u=>e.jsx(lJn,{envelope:u},u.id))]}),o&&e.jsx("div",{className:"flex justify-center py-6",children:e.jsx(Ct,{className:"h-5 w-5 animate-spin text-muted-foreground"})}),c&&e.jsx("p",{className:"text-sm text-destructive",children:"Could not load generated forms."}),!o&&!c&&l.length===0&&d.length===0&&e.jsx("p",{className:"rounded-lg border border-dashed py-8 text-center text-sm text-muted-foreground",children:"No forms generated for this deal yet."}),l.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Generated forms"}),l.map(u=>{var h,m;return e.jsxs("div",{className:"flex items-center gap-3 rounded-lg border bg-background p-3",children:[e.jsx("div",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded bg-muted",children:e.jsx(Fr,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:((h=u.template)==null?void 0:h.name)||"Deleted template"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["v",((m=u.version)==null?void 0:m.version_number)??"—"," · ",Hs(new Date(u.created_at),"MMM d, yyyy")]})]})]},u.id)})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Signature requests email each signer a secure link and remind them automatically on day 3 and day 10. The completed, audit-certified PDF lands in this deal’s Files tab and is emailed to everyone who signed."}),e.jsx(Qns,{open:n,onOpenChange:r,dealId:s,dealName:t}),e.jsx(trs,{open:a,onOpenChange:i,dealId:s,dealName:t})]})}const Q5t={text:"Short Text",textarea:"Long Text",dropdown:"Dropdown",toggle:"Yes / No"};function srs({open:s,onOpenChange:t}){const{data:n,isLoading:r}=BFn(),a=UFn(),i=qFn(),l=$Fn(),[o,c]=_.useState(!1),[d,u]=_.useState({question_text:"",field_type:"text",options:[],is_required:!1}),[h,m]=_.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),se.success("Question added")}catch{se.error("Failed to add question")}},f=async b=>{try{await l.mutateAsync(b),se.success("Question removed")}catch{se.error("Failed to remove question")}},y=async(b,j)=>{try{await i.mutateAsync({id:b,is_required:j})}catch{se.error("Failed to update question")}},v=()=>{h.trim()&&(u(b=>({...b,options:[...b.options,h.trim()]})),m(""))},g=b=>{u(j=>({...j,options:j.options.filter((S,C)=>C!==b)}))};return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"max-w-md max-h-[85vh] flex flex-col",children:[e.jsxs(Os,{children:[e.jsx(Ds,{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(Ji,{className:"flex-1",children:e.jsxs("div",{className:"space-y-3 pr-2",children:[r&&e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(Ct,{className:"h-5 w-5 animate-spin text-muted-foreground"})}),n==null?void 0:n.map(b=>{var j;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(Vf,{className:"h-4 w-4 text-muted-foreground/40 mt-0.5 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:b.question_text}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Oe,{variant:"secondary",className:"text-xs",children:Q5t[b.field_type]||b.field_type}),b.is_required&&e.jsx(Oe,{variant:"outline",className:"text-xs",children:"Required"})]}),b.field_type==="dropdown"&&((j=b.options)==null?void 0:j.length)>0&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Options: ",b.options.join(", ")]})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[e.jsx(fn,{checked:b.is_required,onCheckedChange:S=>y(b.id,S),className:"scale-75"}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive",onClick:()=>f(b.id),children:e.jsx(Sn,{className:"h-3.5 w-3.5"})})]})]})},b.id)}),!r&&(n==null?void 0:n.length)===0&&!o&&e.jsxs("div",{className:"text-center py-8 border border-dashed rounded-lg",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:"No custom questions yet"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Add questions that clients will answer during onboarding."})]}),o&&e.jsxs("div",{className:"border-2 border-primary/20 rounded-lg p-4 space-y-3 bg-primary/5",children:[e.jsxs("div",{children:[e.jsx(J,{className:"text-sm font-medium",children:"Question"}),e.jsx(xe,{value:d.question_text,onChange:b=>u(j=>({...j,question_text:b.target.value})),className:"mt-1",placeholder:"e.g., Do you have a home to sell first?",autoFocus:!0})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-sm font-medium",children:"Answer Type"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:Object.entries(Q5t).map(([b,j])=>e.jsx("button",{type:"button",onClick:()=>u(S=>({...S,field_type:b,options:[]})),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${d.field_type===b?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:j},b))})]}),d.field_type==="dropdown"&&e.jsxs("div",{children:[e.jsx(J,{className:"text-sm font-medium",children:"Options"}),e.jsxs("div",{className:"space-y-1.5 mt-1.5",children:[d.options.map((b,j)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"flex-1 text-sm bg-muted/50 rounded px-2 py-1",children:b}),e.jsx("button",{onClick:()=>g(j),className:"text-muted-foreground hover:text-destructive",children:e.jsx(Qn,{className:"h-3.5 w-3.5"})})]},j)),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{value:h,onChange:b=>m(b.target.value),onKeyDown:b=>b.key==="Enter"&&(b.preventDefault(),v()),placeholder:"Add option...",className:"h-8 text-sm"}),e.jsx(B,{variant:"outline",size:"sm",onClick:v,disabled:!h.trim(),className:"h-8",children:e.jsx(rn,{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(fn,{checked:d.is_required,onCheckedChange:b=>u(j=>({...j,is_required:b}))}),e.jsx(J,{className:"text-xs text-muted-foreground",children:"Required"})]})}),e.jsxs("div",{className:"flex gap-2 pt-1",children:[e.jsx(B,{variant:"outline",size:"sm",onClick:()=>c(!1),className:"flex-1",children:"Cancel"}),e.jsxs(B,{size:"sm",onClick:p,disabled:!d.question_text.trim()||a.isPending,className:"flex-1",children:[a.isPending?e.jsx(Ct,{className:"h-3 w-3 mr-1 animate-spin"}):null,"Add Question"]})]})]})]})}),e.jsxs("div",{className:"flex justify-between pt-4 border-t shrink-0",children:[o?e.jsx("div",{}):e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>c(!0),children:[e.jsx(rn,{className:"h-4 w-4 mr-1"})," Add Question"]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>t(!1),children:"Done"})]})]})})}function dJn({override:s,onChange:t}){const n=ha(),{data:r}=K7t(),[a,i]=_.useState(null),l=d=>t({...s,...d}),o=async(d,u)=>{if(n){if(d.size>5*1024*1024){se.error("Image must be under 5MB");return}i(u);try{const h=await Y7t(n,d,`${u}`);l(u==="logo"?{logo_url:h}:{cover_photo_url:h})}catch(h){se.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(un,{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(J5t,{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(J5t,{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(e4t,{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(e4t,{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(J,{className:"text-sm font-medium",children:"Tagline"}),e.jsx(xe,{value:s.tagline||"",onChange:d=>l({tagline:d.target.value||null}),placeholder:(r==null?void 0:r.tagline)||"Your trusted real estate advisor",maxLength:80,className:"mt-1"})]}),c&&e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>t({}),className:"text-xs text-muted-foreground hover:text-destructive",children:[e.jsx(Sn,{className:"h-3 w-3 mr-1"}),"Clear all overrides"]})]})}function J5t({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(J,{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:At("rounded-lg border-2 border-dashed flex items-center justify-center overflow-hidden bg-muted/30 shrink-0",c?"border-primary":"border-input",l==="square"?"h-16 w-16":"h-16 w-32"),children:o?e.jsx("img",{src:o,alt:s,className:"h-full w-full object-cover"}):e.jsx(hc,{className:"h-5 w-5 text-muted-foreground/40"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("label",{className:"cursor-pointer",children:[e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:d=>{var h;const u=(h=d.target.files)==null?void 0:h[0];u&&a(u),d.target.value=""}}),e.jsxs("span",{className:"inline-flex items-center gap-1.5 h-9 px-3 rounded-md border border-input bg-background hover:bg-accent text-sm font-medium",children:[r?e.jsx(Ct,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Oa,{className:"h-3.5 w-3.5"}),t?"Replace":"Override"]})]}),t&&e.jsx(B,{variant:"ghost",size:"sm",onClick:i,className:"text-muted-foreground hover:text-destructive",children:e.jsx(Sn,{className:"h-3.5 w-3.5"})})]})]})]})}function e4t({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(J,{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:At("mt-1 flex items-center gap-2 h-9 rounded-md border bg-background px-2",i?"border-primary":"border-input"),children:[e.jsx("input",{type:"color",value:a,onChange:l=>r(l.target.value),className:"h-6 w-8 rounded cursor-pointer border-0 bg-transparent"}),e.jsx(xe,{value:t||"",onChange:l=>r(l.target.value||null),placeholder:n||"#406E71",className:"border-0 h-7 px-1 focus-visible:ring-0 text-xs font-mono"}),t&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>r(null),className:"h-6 w-6 p-0 text-muted-foreground hover:text-destructive",children:e.jsx(Sn,{className:"h-3 w-3"})})]})]})}function uJn({portalId:s,agentUserId:t}){const n=Bt(),{data:r,isLoading:a}=at({queryKey:["portal-vendor-manage",s,t],queryFn:async()=>{const{data:h}=await q.from("profiles").select("brokerage_id").eq("id",t).maybeSingle(),m=h==null?void 0:h.brokerage_id,p=q.from("vendors").select("*").eq("is_active",!0),f=m?p.or(`and(owner_type.eq.agent,owner_user_id.eq.${t}),and(owner_type.eq.brokerage,owner_brokerage_id.eq.${m})`):p.eq("owner_type","agent").eq("owner_user_id",t),[{data:y,error:v},{data:g},{data:b}]=await Promise.all([f.order("sort_order",{ascending:!0}).order("name",{ascending:!0}),q.from("agent_vendor_selections").select("vendor_id, is_visible").eq("agent_user_id",t),q.from("portal_vendor_overrides").select("vendor_id, is_visible").eq("portal_id",s)]);if(v)throw v;const j=new Map;(g||[]).forEach(C=>j.set(C.vendor_id,C.is_visible));const S=new Map;return(b||[]).forEach(C=>S.set(C.vendor_id,C.is_visible)),{vendors:y||[],selMap:j,overrideMap:S}}}),i=mt({mutationFn:async({vendorId:h,isVisible:m})=>{const{data:p}=await q.from("portal_vendor_overrides").select("id").eq("portal_id",s).eq("vendor_id",h).maybeSingle();if(p){const{error:f}=await q.from("portal_vendor_overrides").update({is_visible:m}).eq("id",p.id);if(f)throw f}else{const{error:f}=await q.from("portal_vendor_overrides").insert({portal_id:s,vendor_id:h,is_visible:m});if(f)throw f}},onSuccess:()=>{n.invalidateQueries({queryKey:["portal-vendor-manage",s,t]}),n.invalidateQueries({queryKey:["portal-vendors",s]})},onError:h=>se.error(h.message)});if(a)return e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Ct,{className:"w-5 h-5 animate-spin text-muted-foreground"})});const l=(r==null?void 0:r.vendors)||[],o=(r==null?void 0:r.selMap)||new Map,c=(r==null?void 0:r.overrideMap)||new Map;if(l.length===0)return e.jsxs("div",{className:"text-center py-12 border-2 border-dashed rounded-xl",children:[e.jsx(wv,{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=pW.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(Ji,{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(Oe,{variant:"outline",className:"text-[10px] shrink-0",children:u(h.category)}),h.owner_type==="brokerage"&&e.jsx(Oe,{variant:"secondary",className:"text-[10px] shrink-0",children:"Brokerage"}),h.is_required&&e.jsx(Oe,{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(fn,{checked:m,disabled:h.is_required||i.isPending,onCheckedChange:p=>i.mutate({vendorId:h.id,isVisible:p})})]},h.id)})})})]})}function hJn({portalId:s,ownerId:t,clientEmail:n,linkedPortalId:r,onLink:a}){const[i,l]=_.useState(""),[o,c]=_.useState(!1),{data:d,isLoading:u}=at({queryKey:["all-owner-portals",t],queryFn:async()=>{const{data:f,error:y}=await q.from("client_portals").select(` id, slug, client_name, client_email, deal_id, archived_at, deal_pipeline (id, deal_name, deal_type, property_address) `).eq("owner_user_id",t).neq("id",s).is("archived_at",null).eq("is_enabled",!0);if(y)throw y;return f},enabled:o||!!r}),h=_.useMemo(()=>!r||!d?null:d.find(f=>f.id===r),[r,d]),m=_.useMemo(()=>!d||!n?[]:d.filter(f=>{var y;return((y=f.client_email)==null?void 0:y.toLowerCase())===n.toLowerCase()&&f.id!==s}),[d,n,s]),p=_.useMemo(()=>{if(!d||!i.trim())return[];const f=i.toLowerCase();return d.filter(y=>{var g,b,j,S;const v=y.deal_pipeline;return((g=y.client_name)==null?void 0:g.toLowerCase().includes(f))||((b=y.client_email)==null?void 0:b.toLowerCase().includes(f))||((j=v==null?void 0:v.deal_name)==null?void 0:j.toLowerCase().includes(f))||((S=v==null?void 0:v.property_address)==null?void 0:S.toLowerCase().includes(f))})},[d,i]);if(r){const f=h==null?void 0:h.deal_pipeline;return e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{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(vd,{className:"h-4 w-4 text-primary shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:(h==null?void 0:h.client_name)||(f==null?void 0:f.deal_name)||"Linked Portal"}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[(f==null?void 0:f.deal_type)==="listing"?"🏠 Listing":"🔑 Purchase"," · ",(f==null?void 0:f.property_address)||"No address"]})]}),e.jsxs(B,{variant:"ghost",size:"sm",className:"text-xs text-destructive hover:text-destructive shrink-0",onClick:()=>a(null),children:[e.jsx(h7,{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(J,{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(B,{variant:"outline",size:"sm",className:"text-xs",onClick:()=>c(!o),children:[e.jsx(vd,{className:"h-3 w-3 mr-1"}),o?"Cancel":"Link"]})]}),!o&&m.length>0&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"text-[11px] text-muted-foreground font-medium",children:"✨ Suggested match (same client email)"}),m.map(f=>{const y=f.deal_pipeline;return e.jsxs("button",{onClick:()=>a(f.id),className:"w-full flex items-center gap-2 bg-amber-50 border border-amber-200 rounded-lg p-2.5 hover:bg-amber-100 transition-colors text-left",children:[e.jsx(Oe,{variant:"outline",className:"text-[10px] shrink-0 bg-amber-100 border-amber-300 text-amber-700",children:(y==null?void 0:y.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:(y==null?void 0:y.deal_name)||f.client_name}),e.jsx("p",{className:"text-[11px] text-muted-foreground truncate",children:y==null?void 0:y.property_address})]}),e.jsx(vd,{className:"h-3.5 w-3.5 text-amber-600 shrink-0"})]},f.id)})]}),o&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Lr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(xe,{value:i,onChange:f=>l(f.target.value),placeholder:"Search by name, email, or address...",className:"pl-8 h-8 text-xs",autoFocus:!0})]}),u&&e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(Ct,{className:"h-4 w-4 animate-spin text-muted-foreground"})}),p.length>0&&e.jsx("div",{className:"space-y-1 max-h-[200px] overflow-y-auto",children:p.map(f=>{const y=f.deal_pipeline;return e.jsxs("button",{onClick:()=>{a(f.id),c(!1),l("")},className:"w-full flex items-center gap-2 border rounded-lg p-2 hover:bg-muted/50 transition-colors text-left",children:[e.jsx(Oe,{variant:"outline",className:"text-[10px] shrink-0",children:(y==null?void 0:y.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:(y==null?void 0:y.deal_name)||f.client_name}),e.jsx("p",{className:"text-[11px] text-muted-foreground truncate",children:f.client_email})]})]},f.id)})}),i&&p.length===0&&!u&&e.jsx("p",{className:"text-xs text-muted-foreground text-center py-3",children:"No portals found"})]})]})}function qat({contactId:s,onVideoReady:t}){const[n,r]=_.useState(!1),[a,i]=_.useState("record"),[l,o]=_.useState(0),[c,d]=_.useState(0),u=TC(),h=()=>{i("record"),o(0),d(0)},m=f=>{!f&&(a==="uploading"||a==="processing")||(r(f),f||h())},p=_.useCallback(async(f,y)=>{i("uploading");try{const v="Card Video",{videoId:g,libraryId:b}=await PL(v),{uploadUrl:j,apiKey:S}=await LL(g),C=new XMLHttpRequest;C.upload.onprogress=V=>{V.lengthComputable&&o(V.loaded/V.total*100)},await new Promise((V,G)=>{C.onload=()=>C.status>=200&&C.status<300?V():G(new Error("Upload failed")),C.onerror=()=>G(new Error("Upload failed")),C.open("PUT",j),C.setRequestHeader("AccessKey",S),C.send(f)}),i("processing");let E=0;const P=Date.now(),M=9e4,I=`https://iframe.mediadelivery.net/embed/${b}/${g}`;for(;E<4;){if(await new Promise(G=>setTimeout(G,3e3)),Date.now()-P>M){const G=f.size/1048576;await u.mutateAsync({bunny_video_id:g,playback_url:`https://iframe.mediadelivery.net/play/${b}/${g}`,file_size_mb:G,title:v,contact_id:s||void 0,status:"processing",touch_type:"video"}),t(I),se.success("Video saved — still encoding. It will be ready shortly."),i("done"),setTimeout(()=>{r(!1),h()},1500);return}const V=await TN(g);if(E=V.status,d(V.encodeProgress||0),E===5||E===6)throw new Error("Video processing failed")}const D=await TN(g),O=(D.storageSize||f.size)/(1024*1024);await u.mutateAsync({bunny_video_id:g,contact_id:s||void 0,playback_url:D.directPlayUrl||I,thumbnail_url:D.thumbnailUrl,preview_url:D.previewUrl||null,duration_seconds:D.length||y,file_size_mb:O,title:v,status:"ready",touch_type:"video"}),t(I),se.success("Video recorded & added to your library!"),i("done"),setTimeout(()=>{r(!1),h()},1500)}catch(v){console.error("Recording upload error:",v),se.error("Failed to process video. Please try again."),i("record")}},[s,t,u]);return e.jsxs(Ls,{open:n,onOpenChange:m,children:[e.jsx(nl,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"gap-1.5 w-full",children:[e.jsx(Kr,{className:"h-3.5 w-3.5"}),"Record Video"]})}),e.jsxs(Ps,{className:"sm:max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Ds,{children:"Record a Video for Your Card"})}),a==="record"&&e.jsx($E,{maxDurationSeconds:600,onRecordingComplete:p,onError:f=>se.error(f)}),a==="uploading"&&e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12",children:[e.jsx(Ct,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Uploading video..."}),e.jsx(Fi,{value:l,className:"w-64"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Math.round(l),"%"]})]}),a==="processing"&&e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12",children:[e.jsx(Ct,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Processing video..."}),e.jsx(Fi,{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(_l,{className:"h-12 w-12 text-emerald-500"}),e.jsx("p",{className:"text-sm font-medium",children:"Video attached to your card!"})]})]})]})}const mJn=s=>`portal-settings-draft:${s}`;function $at({open:s,onOpenChange:t,portal:n,dealOwnerId:r}){const a=VW(),[i,l]=_.useState(!1),o=_.useMemo(()=>mJn(n.id),[n.id]),[c,d]=_.useState(!1),[u,h]=_.useState(n.next_step_text||""),[m,p]=_.useState(n.next_step_video_url||""),[f,y]=_.useState(n.inspection_date||""),[v,g]=_.useState(n.appraisal_date||""),[b,j]=_.useState(n.welcome_message||""),[S,C]=_.useState(n.review_url||""),[E,P]=_.useState(n.show_post_close_tips),[M,I]=_.useState(n.notify_client),[D,O]=_.useState(n.require_onboarding),[V,G]=_.useState(n.allow_spouse),[$,H]=_.useState(n.visibility),[Y,Z]=_.useState(n.stage_mapping||[]),[ne,ce]=_.useState(null),[ie,te]=_.useState(n.linked_portal_id||null),[ae,le]=_.useState(n.referral_enabled??!0),[be,me]=_.useState(n.referral_reward_text||""),[he,pe]=_.useState(n.referral_cta_headline||""),[Ce,Ae]=_.useState(n.homeowner_hub_video_url||""),[Pe,ze]=_.useState(n.branding_override||{}),ke=()=>{h(n.next_step_text||""),p(n.next_step_video_url||""),y(n.inspection_date||""),g(n.appraisal_date||""),j(n.welcome_message||""),C(n.review_url||""),P(n.show_post_close_tips),I(n.notify_client),O(n.require_onboarding),G(n.allow_spouse),H(n.visibility),Z(n.stage_mapping||[]),te(n.linked_portal_id||null),le(n.referral_enabled??!0),me(n.referral_reward_text||""),pe(n.referral_cta_headline||""),Ae(n.homeowner_hub_video_url||""),ze(n.branding_override||{})};_.useEffect(()=>{d(!1);const qe=localStorage.getItem(o);if(qe)try{const Qe=JSON.parse(qe);h(Qe.nextStepText||""),p(Qe.nextStepVideo||""),y(Qe.inspectionDate||""),g(Qe.appraisalDate||""),j(Qe.welcomeMessage||""),C(Qe.reviewUrl||""),P(!!Qe.showPostClose),I(!!Qe.notifyClient),O(!!Qe.requireOnboarding),G(!!Qe.allowSpouse),H(Qe.visibility||n.visibility),Z(Qe.stageMapping||[]),te(Qe.linkedPortalId??null),le(Qe.referralEnabled??!0),me(Qe.referralRewardText||""),pe(Qe.referralCtaHeadline||""),Ae(Qe.homeownerHubVideoUrl||""),ze(Qe.brandingOverride||{}),d(!0);return}catch{localStorage.removeItem(o)}ke(),d(!0)},[o,n]),_.useEffect(()=>{if(!c)return;const qe={nextStepText:u,nextStepVideo:m,inspectionDate:f,appraisalDate:v,welcomeMessage:b,reviewUrl:S,showPostClose:E,notifyClient:M,requireOnboarding:D,allowSpouse:V,visibility:$,stageMapping:Y,linkedPortalId:ie,referralEnabled:ae,referralRewardText:be,referralCtaHeadline:he,homeownerHubVideoUrl:Ce,brandingOverride:Pe};u!==(n.next_step_text||"")||m!==(n.next_step_video_url||"")||f!==(n.inspection_date||"")||v!==(n.appraisal_date||"")||b!==(n.welcome_message||"")||S!==(n.review_url||"")||E!==n.show_post_close_tips||M!==n.notify_client||D!==n.require_onboarding||V!==n.allow_spouse||$!==n.visibility||JSON.stringify(Y)!==JSON.stringify(n.stage_mapping||[])||ie!==(n.linked_portal_id||null)||ae!==(n.referral_enabled??!0)||be!==(n.referral_reward_text||"")||he!==(n.referral_cta_headline||"")||Ce!==(n.homeowner_hub_video_url||"")||JSON.stringify(Pe)!==JSON.stringify(n.branding_override||{})?localStorage.setItem(o,JSON.stringify(qe)):localStorage.removeItem(o)},[u,m,f,v,b,S,E,M,D,V,$,Y,ie,ae,be,he,Ce,Pe,o,c,n]);const Ze=()=>{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:f||null,appraisal_date:v||null,welcome_message:b||null,review_url:S||null,show_post_close_tips:E,notify_client:M,require_onboarding:D,allow_spouse:V,visibility:$,stage_mapping:Y.length>0?Y:null,linked_portal_id:ie,referral_enabled:ae,referral_reward_text:be||null,referral_cta_headline:he||null,homeowner_hub_video_url:Ce||null,branding_override:Object.values(Pe).some(Qe=>Qe!=null&&Qe!=="")?Pe:null});const qe=n.linked_portal_id;ie&&ie!==qe&&await q.from("client_portals").update({linked_portal_id:n.id}).eq("id",ie),!ie&&qe&&await q.from("client_portals").update({linked_portal_id:null}).eq("id",qe),localStorage.removeItem(o),se.success("Portal settings saved"),t(!1)}catch{se.error("Failed to save settings")}},Fe=()=>{Z([...Y,{label:""}])},Ne=qe=>{Z(Y.filter((Qe,Ue)=>Ue!==qe)),ne===qe&&ce(null)},Ye=(qe,Qe,Ue)=>{const Xe=[...Y];Xe[qe]={...Xe[qe],[Qe]:Ue},Z(Xe)},Ve=()=>{const Qe=BPe(null).map(Ue=>({label:Ue.label,description:Ue.description,stageId:void 0}));Z(Qe)};return e.jsxs(e.Fragment,{children:[e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"max-w-lg max-h-[85vh] flex flex-col",children:[e.jsx(Os,{children:e.jsx(Ds,{children:"Portal Settings"})}),e.jsxs(Yr,{defaultValue:"general",className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(Zr,{className:"grid grid-cols-5 shrink-0",children:[e.jsx(Ht,{value:"general",children:"General"}),e.jsx(Ht,{value:"timeline",children:"Timeline"}),e.jsx(Ht,{value:"content",children:"Content"}),e.jsx(Ht,{value:"vendors",children:"Vendors"}),e.jsx(Ht,{value:"branding",children:"Branding"})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto mt-4 min-h-0",children:[e.jsxs(Gt,{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(J,{className:"text-sm font-medium",children:"Visibility"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Public portals appear without restrictions"})]}),e.jsx("div",{className:"flex gap-1",children:["private","public"].map(qe=>e.jsx("button",{onClick:()=>H(qe),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${$===qe?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:qe.charAt(0).toUpperCase()+qe.slice(1)},qe))})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(J,{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(fn,{checked:D,onCheckedChange:O})]}),D&&e.jsxs("div",{className:"flex items-center justify-between pl-4 border-l-2 border-primary/20",children:[e.jsxs("div",{children:[e.jsx(J,{className:"text-sm font-medium",children:"Custom Questions"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Manage intake form questions"})]}),e.jsx(B,{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(J,{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(fn,{checked:V,onCheckedChange:G})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(J,{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(fn,{checked:E,onCheckedChange:P})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(J,{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(fn,{checked:M,onCheckedChange:I})]}),e.jsx("div",{className:"border-t pt-4",children:e.jsx(hJn,{portalId:n.id,ownerId:r,clientEmail:n.client_email,linkedPortalId:ie,onLink:te})}),e.jsx("div",{children:e.jsx(xe,{type:"date",value:f,onChange:qe=>y(qe.target.value),className:"mt-1"})}),e.jsxs("div",{children:[e.jsx(J,{className:"text-sm font-medium",children:"Appraisal Date"}),e.jsx(xe,{type:"date",value:v,onChange:qe=>g(qe.target.value),className:"mt-1"})]})]}),e.jsx(Gt,{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(J,{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(B,{variant:"outline",size:"sm",onClick:Ve,className:"text-xs",children:"Auto-map"})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground bg-muted/50 rounded-md p-2",children:'💡 These labels are what clients see. Click "More" on any stage to customize its description and add a video link. Internal pipeline stages are automatically translated to friendly names.'}),Y.length===0&&e.jsxs("div",{className:"border border-dashed rounded-lg p-4 text-center",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"No custom mapping — using default client-friendly journey stages"}),e.jsx(B,{variant:"outline",size:"sm",onClick:Ve,children:"Customize journey labels"})]}),e.jsx("div",{className:"space-y-2 mt-2",children:Y.map((qe,Qe)=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Vf,{className:"h-4 w-4 text-muted-foreground/50 flex-shrink-0"}),e.jsx(xe,{value:qe.label,onChange:Ue=>Ye(Qe,"label",Ue.target.value),placeholder:`Stage ${Qe+1} label`,className:"flex-1 h-9 text-sm"}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-9 px-2 text-xs text-muted-foreground hover:text-primary",onClick:()=>ce(ne===Qe?null:Qe),children:ne===Qe?"Less":"More"}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-9 w-9 text-muted-foreground hover:text-destructive",onClick:()=>Ne(Qe),children:e.jsx(Sn,{className:"h-3.5 w-3.5"})})]}),ne===Qe&&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(J,{className:"text-xs text-muted-foreground",children:"Description"}),e.jsx("textarea",{value:qe.description||"",onChange:Ue=>Ye(Qe,"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(J,{className:"text-xs text-muted-foreground",children:"Video"}),qe.video_url?e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[e.jsx("div",{className:"flex-1 text-xs text-muted-foreground truncate bg-muted/50 rounded px-2 py-1.5 border border-input",children:qe.video_url.length>40?qe.video_url.slice(0,40)+"...":qe.video_url}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 text-xs text-destructive hover:text-destructive",onClick:()=>Ye(Qe,"video_url",""),children:"Remove"})]}):e.jsxs("div",{className:"mt-1 flex items-center gap-1.5",children:[e.jsx(qat,{onVideoReady:Ue=>Ye(Qe,"video_url",Ue)}),e.jsx(iz,{userId:r,onSelect:Ue=>Ye(Qe,"video_url",Ue),triggerSize:"sm",triggerClassName:"gap-1.5 shrink-0 flex-1"}),e.jsxs(B,{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&&Ye(Qe,"video_url",Ue)},children:[e.jsx(Vc,{className:"h-3 w-3"}),"Paste URL"]})]})]})]})]},Qe))}),Y.length>0&&e.jsxs(B,{variant:"outline",size:"sm",onClick:Fe,className:"mt-2 text-xs w-full",children:[e.jsx(rn,{className:"h-3 w-3 mr-1"})," Add Stage"]})]})}),e.jsxs(Gt,{value:"content",className:"space-y-4 mt-0 px-1",children:[e.jsxs("div",{children:[e.jsx(J,{className:"text-sm font-medium",children:"Welcome Message"}),e.jsx("textarea",{value:b,onChange:qe=>j(qe.target.value),className:"mt-1 w-full rounded-md border border-input bg-background px-3 py-2 text-sm min-h-[60px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",placeholder:"Welcome! Here's everything you need for your transaction."})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-sm font-medium",children:"What's Next"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Tell your client what to expect next"}),e.jsx("textarea",{value:u,onChange:qe=>h(qe.target.value),className:"mt-1 w-full rounded-md border border-input bg-background px-3 py-2 text-sm min-h-[60px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",placeholder:"We're waiting on the inspection report..."})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-sm font-medium",children:"Next Step Video (optional)"}),e.jsx(xe,{value:m,onChange:qe=>p(qe.target.value),className:"mt-1",placeholder:"YouTube or Loom URL"})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-sm font-medium",children:"Review URL"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Shown after deal closes"}),e.jsx(xe,{value:S,onChange:qe=>C(qe.target.value),className:"mt-1",placeholder:"https://g.page/r/..."})]}),e.jsxs("div",{className:"border-t pt-4 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-base",children:"🎁"}),e.jsx(J,{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(J,{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(fn,{checked:ae,onCheckedChange:le})]}),ae&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx(J,{className:"text-sm font-medium",children:"Headline"}),e.jsx(xe,{value:he,onChange:qe=>pe(qe.target.value),className:"mt-1",placeholder:"Know someone buying or selling?"})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-sm font-medium",children:"Reward (optional)"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"What the client gets for a successful referral"}),e.jsx(xe,{value:be,onChange:qe=>me(qe.target.value),className:"mt-1",placeholder:"$250 gift card • Donation to your charity • Closing gift"})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-sm font-medium",children:"Personal Welcome Video URL (optional)"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:'A "welcome home" video shown above the referral card'}),e.jsx(xe,{value:Ce,onChange:qe=>Ae(qe.target.value),className:"mt-1",placeholder:"YouTube, Loom, or direct video URL"})]})]})]})]}),e.jsx(Gt,{value:"vendors",className:"space-y-4 mt-0 px-1",children:e.jsx(uJn,{portalId:n.id,agentUserId:r})}),e.jsx(Gt,{value:"branding",className:"space-y-4 mt-0 px-1",children:e.jsx(dJn,{override:Pe,onChange:ze})})]})]}),e.jsxs("div",{className:"flex justify-between gap-2 pt-4 border-t shrink-0",children:[e.jsx(B,{variant:"ghost",onClick:Ze,children:"Reset Draft"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Close"}),e.jsxs(B,{onClick:Se,disabled:a.isPending,children:[a.isPending?e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ho,{className:"h-4 w-4 mr-2"}),"Save Settings"]})]})]})]})}),e.jsx(srs,{open:i,onOpenChange:l})]})}const pJn=s=>`portal-update-draft:${s}`;function Vat({open:s,onOpenChange:t,portalId:n,portalSlug:r,notifyClient:a}){const i=_.useMemo(()=>pJn(n),[n]),[l,o]=_.useState(""),[c,d]=_.useState(""),[u,h]=_.useState(""),[m,p]=_.useState(!1),[f,y]=_.useState(a??!0),[v,g]=_.useState(!1),b=GYt();_.useEffect(()=>{g(!1);const C=localStorage.getItem(i);if(C)try{const E=JSON.parse(C);o(E.title||""),d(E.content||""),h(E.videoUrl||""),p(!!E.isStageChange),y(typeof E.sendNotification=="boolean"?E.sendNotification:a??!0),g(!0);return}catch{localStorage.removeItem(i)}o(""),d(""),h(""),p(!1),y(a??!0),g(!0)},[i,a]),_.useEffect(()=>{if(!v)return;const C={title:l,content:c,videoUrl:u,isStageChange:m,sendNotification:f};l.trim()||c.trim()||u.trim()||m||f!==(a??!0)?localStorage.setItem(i,JSON.stringify(C)):localStorage.removeItem(i)},[l,c,u,m,f,v,i,a]);const j=()=>{localStorage.removeItem(i),o(""),d(""),h(""),p(!1),y(a??!0)},S=async()=>{if(l.trim())try{if(await b.mutateAsync({portal_id:n,title:l.trim(),content:c.trim()||void 0,video_url:u.trim()||void 0,is_stage_change:m}),f&&r)try{const C=wS(r),{data:E,error:P}=await q.functions.invoke("send-portal-notification",{body:{portal_id:n,update_title:l.trim(),update_content:c.trim()||null,video_url:u.trim()||null,is_stage_change:m,portal_url:C,force:!0}});if(P)throw P;E!=null&&E.emailSent?se.success("Update posted & client emailed"):se.success(`Update posted (${(E==null?void 0:E.reason)||"no email sent"})`)}catch(C){console.error("Notification failed:",C),se.success("Update posted (notification failed to send)")}else se.success("Update posted to portal");j(),t(!1)}catch{se.error("Failed to post update")}};return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"max-w-md",children:[e.jsx(Os,{children:e.jsx(Ds,{children:"Post Portal Update"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(J,{className:"text-sm font-medium",children:"Title *"}),e.jsx(xe,{value:l,onChange:C=>o(C.target.value),className:"mt-1",placeholder:"Inspection cleared!"})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-sm font-medium",children:"Message"}),e.jsx("textarea",{value:c,onChange:C=>d(C.target.value),className:"mt-1 w-full rounded-md border border-input bg-background px-3 py-2 text-sm min-h-[80px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",placeholder:"Everything looked great during the inspection..."})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-sm font-medium",children:"Video URL (optional)"}),e.jsxs("div",{className:"relative mt-1",children:[e.jsx(xe,{value:u,onChange:C=>h(C.target.value),className:"pl-9",placeholder:"YouTube or Loom link"}),e.jsx(Kr,{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:()=>y(!f),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors flex items-center gap-1.5 ${f?"bg-blue-500/10 text-blue-700 border-blue-200":"bg-background text-muted-foreground border-input"}`,children:[f?e.jsx(Rg,{className:"h-3 w-3"}):e.jsx(cS,{className:"h-3 w-3"}),f?"Notify Client":"No Notification"]})]})]}),e.jsxs("div",{className:"flex justify-between gap-2 pt-2",children:[e.jsx(B,{variant:"ghost",onClick:j,children:"Clear Draft"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Close"}),e.jsxs(B,{onClick:S,disabled:!l.trim()||b.isPending,children:[b.isPending?e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Or,{className:"h-4 w-4 mr-2"}),"Post Update"]})]})]})]})})}function Hat({open:s,onOpenChange:t,portal:n,dealName:r}){const a=VW(),{isGmailConnected:i,gmailEmail:l}=Vg(),[o,c]=_.useState(n.client_name||""),[d,u]=_.useState(n.client_email||""),[h,m]=_.useState(!1),[p,f]=_.useState(!1),y=wS(n.slug),v=o.split(" ")[0]||"there",g=`Your Transaction Portal – ${r}`,b=`Hi ${v}, I've set up a dedicated portal where you can track the progress of your transaction in real-time. Here's your link: ${y} You can view your timeline, key dates, documents, and any updates I post along the way. Let me know if you have any questions!`,j=()=>{navigator.clipboard.writeText(y),f(!0),setTimeout(()=>f(!1),2e3),se.success("Portal link copied!")},S=async()=>{if(!d.trim()){se.error("Please enter the client email");return}m(!0);try{await a.mutateAsync({id:n.id,client_name:o||null,client_email:d||null,invite_sent_at:new Date().toISOString(),invite_method:"email"});const{error:E}=await q.functions.invoke("gmail-send",{body:{to:d,subject:g,body:b.replace(/\n/g,"
")}});if(E){let P="";try{const M=E==null?void 0:E.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||E.message||"Failed to send invite")}se.success(`Invite sent to ${d}`),t(!1)}catch(E){se.error(E.message||"Failed to send invite")}finally{m(!1)}},C=()=>{const E=encodeURIComponent(g),P=encodeURIComponent(b);window.open(`mailto:${d}?subject=${E}&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(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"max-w-md",children:[e.jsx(Os,{children:e.jsx(Ds,{children:"Invite Client to Portal"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(J,{className:"text-sm font-medium",children:"Client Name"}),e.jsx(xe,{value:o,onChange:E=>c(E.target.value),className:"mt-1",placeholder:"John Doe"})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-sm font-medium",children:"Client Email"}),e.jsx(xe,{type:"email",value:d,onChange:E=>u(E.target.value),className:"mt-1",placeholder:"john@example.com"})]}),e.jsxs("div",{children:[e.jsx(J,{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:y})}),e.jsx(B,{variant:"outline",size:"icon",onClick:j,className:"shrink-0",children:p?e.jsx(ea,{className:"h-4 w-4 text-emerald-600"}):e.jsx(Ia,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2 pt-2 border-t",children:[i?e.jsxs(B,{onClick:S,disabled:h||!d.trim(),className:"w-full",children:[h?e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(ln,{className:"h-4 w-4 mr-2"}),"Send via Gmail (",l,")"]}):e.jsxs(B,{onClick:C,disabled:!d.trim(),className:"w-full",variant:"outline",children:[e.jsx(wr,{className:"h-4 w-4 mr-2"}),"Open in Email App"]}),e.jsxs(B,{variant:"ghost",onClick:j,className:"w-full text-muted-foreground",children:[e.jsx(Ia,{className:"h-4 w-4 mr-2"}),"Just Copy Link"]})]})]})]})})}function fJn({deal:s}){const{isAdmin:t,user:n}=hs(),{data:r,isLoading:a}=OFn(s.id),i=Snt(),l=VW(),[o,c]=_.useState(!1),[d,u]=_.useState(!1),[h,m]=_.useState(!1),[p,f]=_.useState(!1),y=`portal-management-ui:${s.id}`;if(_.useEffect(()=>{const E=sessionStorage.getItem(y);if(E)try{const P=JSON.parse(E);u(!!P.settingsOpen),m(!!P.composerOpen),f(!!P.inviteOpen)}catch{sessionStorage.removeItem(y)}},[y]),_.useEffect(()=>{d||h||p?sessionStorage.setItem(y,JSON.stringify({settingsOpen:d,composerOpen:h,inviteOpen:p})):sessionStorage.removeItem(y)},[d,h,p,y]),a)return e.jsx("div",{className:"border rounded-lg p-4",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"font-medium text-sm",children:"Client Portal"}),e.jsx(Ct,{className:"h-3 w-3 animate-spin ml-auto"})]})});const v=async()=>{var E,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:((E=s.contact)==null?void 0:E.email)||void 0,client_phone:((P=s.contact)==null?void 0:P.phone)||void 0}),se.success("Client portal enabled!")}catch{se.error("Failed to create portal")}finally{c(!1)}},g=async E=>{if(r)try{await l.mutateAsync({id:r.id,is_enabled:E}),se.success(E?"Portal enabled":"Portal disabled")}catch{se.error("Failed to update portal")}},b=()=>{if(!r)return;const E=wS(r.slug);navigator.clipboard.writeText(E),se.success("Portal link copied!")},j=()=>{if(!r)return;const E=wS(r.slug);window.open(E,"_blank")};if(!r)return e.jsxs("div",{className:"border rounded-lg p-4 border-dashed",children:[e.jsx("div",{className:"flex items-center justify-between mb-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(un,{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(B,{onClick:v,disabled:o,size:"sm",className:"w-full",children:[o?e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(un,{className:"h-4 w-4 mr-2"}),"Enable Client Portal"]})]});const S=wS(r.slug),C=(n==null?void 0:n.id)||"";return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"border rounded-lg p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"font-medium text-sm",children:"Client Portal"}),e.jsx(Oe,{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(fn,{checked:r.is_enabled,onCheckedChange:g})]}),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(Oe,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:r.visibility==="private"?"Private":"Public"})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:"Onboarding:"}),e.jsx("span",{className:"text-foreground",children:r.require_onboarding?"Required":"Disabled"})]}),r.client_name&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:"Client:"}),e.jsx("span",{className:"text-foreground",children:r.client_name})]})]}),e.jsx("div",{className:"bg-muted/50 rounded-md p-2 mb-3",children:e.jsx("p",{className:"text-xs font-mono text-muted-foreground truncate",children:S})}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 mb-2 w-full",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:b,className:"text-xs w-full min-w-0 px-2",children:[e.jsx(Ia,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Copy"})]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:j,className:"text-xs w-full min-w-0 px-2",children:[e.jsx(wr,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Preview"})]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>f(!0),className:"text-xs w-full min-w-0 px-2",children:[e.jsx(Or,{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(B,{variant:"ghost",size:"sm",onClick:()=>m(!0),className:"text-xs text-muted-foreground w-full min-w-0 px-2",children:[e.jsx(E4,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Post Update"})]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>u(!0),className:"text-xs text-muted-foreground w-full min-w-0 px-2",children:[e.jsx(qc,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Settings"})]})]}),e.jsxs(ir,{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(Vo,{className:"h-3 w-3"}),"View incoming referrals"]})]}),e.jsx($at,{open:d,onOpenChange:u,portal:r,dealOwnerId:C}),e.jsx(Vat,{open:h,onOpenChange:m,portalId:r.id,portalSlug:r.slug,notifyClient:r.notify_client}),e.jsx(Hat,{open:p,onOpenChange:f,portal:r,dealName:s.deal_name})]})}function xJn({dealId:s,primaryContactId:t}){const n=Fn(),{data:r,isLoading:a}=Jns(s),{data:i}=Db(),l=JQn(),o=eJn(),[c,d]=_.useState(!1),[u,h]=_.useState(""),[m,p]=_.useState("Client"),f=new Set((r==null?void 0:r.map(j=>j.contact_id))||[]);t&&f.add(t);const y=i==null?void 0:i.filter(j=>{var C,E,P;if(f.has(j.id))return!1;if(!u.trim())return!0;const S=u.toLowerCase();return((C=j.first_name)==null?void 0:C.toLowerCase().includes(S))||((E=j.last_name)==null?void 0:E.toLowerCase().includes(S))||((P=j.email)==null?void 0:P.toLowerCase().includes(S))}).slice(0,8),v=j=>{l.mutate({dealId:s,contactId:j,role:m}),d(!1),h("")},g=j=>{o.mutate({id:j,dealId:s})},b={Client:"bg-primary/10 text-primary","Co-Buyer":"bg-blue-500/10 text-blue-600","Co-Seller":"bg-emerald-500/10 text-emerald-600",Spouse:"bg-pink-500/10 text-pink-600",Lender:"bg-amber-500/10 text-amber-600","Title Company":"bg-purple-500/10 text-purple-600",Inspector:"bg-orange-500/10 text-orange-600",Appraiser:"bg-cyan-500/10 text-cyan-600",Attorney:"bg-slate-500/10 text-slate-600",Contractor:"bg-lime-500/10 text-lime-600",Other:"bg-muted text-muted-foreground"};return!(r!=null&&r.length)&&!c?e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("h4",{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(In,{className:"h-4 w-4"}),"Additional Contacts"]})}),e.jsxs(od,{open:c,onOpenChange:d,children:[e.jsx(ld,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"w-full text-muted-foreground",children:[e.jsx(rn,{className:"h-3.5 w-3.5 mr-1"}),"Link a contact (lender, spouse, vendor...)"]})}),e.jsx(Qc,{className:"w-80 p-3",align:"start",children:e.jsx(t4t,{search:u,setSearch:h,selectedRole:m,setSelectedRole:p,filteredContacts:y,onAdd:v})})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h4",{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(In,{className:"h-4 w-4"}),"Linked Contacts",r&&r.length>0&&e.jsx(Oe,{variant:"secondary",className:"text-[10px] px-1.5",children:r.length})]}),e.jsxs(od,{open:c,onOpenChange:d,children:[e.jsx(ld,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 px-2",children:e.jsx(rn,{className:"h-3.5 w-3.5"})})}),e.jsx(Qc,{className:"w-80 p-3",align:"end",children:e.jsx(t4t,{search:u,setSearch:h,selectedRole:m,setSelectedRole:p,filteredContacts:y,onAdd:v})})]})]}),e.jsx("div",{className:"space-y-1.5",children:r==null?void 0:r.map(j=>{var S,C,E,P,M,I,D,O;return e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-md bg-muted/40 group",children:[e.jsx(ja,{className:"h-7 w-7",children:e.jsxs(Na,{className:"text-[10px] bg-primary/10 text-primary",children:[(C=(S=j.contact)==null?void 0:S.first_name)==null?void 0:C[0],(P=(E=j.contact)==null?void 0:E.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/${j.contact_id}`),className:"text-sm font-medium hover:underline text-primary truncate block",children:[(M=j.contact)==null?void 0:M.first_name," ",(I=j.contact)==null?void 0:I.last_name]})}),e.jsx(Oe,{variant:"outline",className:`text-[10px] px-1.5 py-0 shrink-0 ${b[j.role]||b.Other}`,children:j.role}),e.jsxs("div",{className:"flex gap-0.5 opacity-0 group-hover:opacity-100 transition-opacity",children:[((D=j.contact)==null?void 0:D.phone)&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6",asChild:!0,children:e.jsx("a",{href:`tel:${j.contact.phone}`,children:e.jsx(_a,{className:"h-3 w-3"})})}),((O=j.contact)==null?void 0:O.email)&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6",asChild:!0,children:e.jsx("a",{href:`mailto:${j.contact.email}`,children:e.jsx(ln,{className:"h-3 w-3"})})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6 text-destructive",onClick:()=>g(j.id),children:e.jsx(Sn,{className:"h-3 w-3"})})]})]},j.id)})})]})}function t4t({search:s,setSearch:t,selectedRole:n,setSelectedRole:r,filteredContacts:a,onAdd:i}){return e.jsxs("div",{className:"space-y-3",children:[e.jsxs(is,{value:n,onValueChange:r,children:[e.jsx(rs,{className:"h-8 text-sm",children:e.jsx(ls,{placeholder:"Role"})}),e.jsx(as,{children:QQn.map(l=>e.jsx(He,{value:l,children:l},l))})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Lr,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(xe,{value:s,onChange:l=>t(l.target.value),placeholder:"Search contacts...",className:"pl-7 h-8 text-sm",autoFocus:!0})]}),e.jsx(Ji,{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 tQ=[{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"}],gJn=[{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 yJn(){const s=Bt();return mt({mutationFn:async({dealId:t,dates:n})=>{const r={};Object.entries(n).forEach(([i,l])=>{r[i]=l&&l.trim()!==""?l:null});const{error:a}=await q.from("deal_pipeline").update(r).eq("id",t);if(a)throw a},onSuccess:()=>{s.invalidateQueries({queryKey:["deals"]}),s.invalidateQueries({queryKey:["deal-pipeline"]}),s.invalidateQueries({queryKey:["tc-dashboard"]})}})}function vJn(){const s=Bt();return mt({mutationFn:async({dealId:t,completed:n})=>{const{error:r}=await q.from("deal_pipeline").update({completed_key_dates:n}).eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["deals"]}),s.invalidateQueries({queryKey:["deal-pipeline"]}),s.invalidateQueries({queryKey:["tc-dashboard"]})}})}function bJn(){return at({queryKey:["tc-playbooks"],queryFn:async()=>{const{data:s,error:t}=await q.from("tc_playbooks").select("*").eq("is_active",!0).order("sort_order");if(t)throw t;const{data:n,error:r}=await q.from("tc_playbook_tasks").select("*").order("sort_order");if(r)throw r;return(s||[]).map(a=>({...a,tasks:(n||[]).filter(i=>i.playbook_id===a.id)}))},staleTime:10*6e4})}function _Jn(){const s=ha(),t=Bt();return mt({mutationFn:async({playbookId:n,dealId:r})=>{if(!s)throw new Error("Not authenticated");const[{data:a,error:i},{data:l,error:o}]=await Promise.all([q.from("deal_pipeline").select("*").eq("id",r).single(),q.from("tc_playbook_tasks").select("*").eq("playbook_id",n).order("sort_order")]);if(i)throw i;if(o)throw o;if(!l||l.length===0)return 0;const{data:c}=await q.from("deal_tasks").select("title").eq("deal_id",r),d=new Set((c||[]).map(f=>String(f.title).toLowerCase())),u=a,h=(f,y)=>{const v=f==="stage_entry"?null:u[f],g=v?new Date(`${v}T12:00:00`):new Date;return g.setDate(g.getDate()+(y||0)),g.toISOString().split("T")[0]},m=l.filter(f=>!d.has(String(f.title).toLowerCase())).map((f,y)=>({owner_user_id:s,deal_id:r,contact_id:u.contact_id,stage_id:u.stage_id,title:f.title,description:f.description,priority:f.priority,status:"todo",due_date:h(f.due_anchor,f.due_offset_days),sort_order:y}));if(m.length===0)return 0;const{error:p}=await q.from("deal_tasks").insert(m);if(p)throw p;return m.length},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-tasks"]}),t.invalidateQueries({queryKey:["tc-dashboard"]})}})}function wJn(){const s=ha(),t=Bt();return mt({mutationFn:async({playbookId:n,stageId:r})=>{if(!s)throw new Error("Not authenticated");const[{data:a},{data:i,error:l}]=await Promise.all([q.from("tc_playbooks").select("deal_type").eq("id",n).single(),q.from("tc_playbook_tasks").select("*").eq("playbook_id",n).order("sort_order")]);if(l)throw l;if(!i||i.length===0)return 0;const{data:o}=await q.from("deal_task_templates").select("title").eq("owner_user_id",s).eq("stage_id",r),c=new Set((o||[]).map(h=>String(h.title).toLowerCase())),d=i.filter(h=>!c.has(String(h.title).toLowerCase())).map((h,m)=>({owner_user_id:s,stage_id:r,title:h.title,description:h.description,priority:h.priority,due_anchor:h.due_anchor,default_due_offset_days:h.due_offset_days,deal_type:(a==null?void 0:a.deal_type)??null,playbook_id:n,sort_order:m}));if(d.length===0)return 0;const{error:u}=await q.from("deal_task_templates").insert(d);if(u)throw u;return d.length},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-task-templates"]})}})}function jJn(){const s=ha();return at({queryKey:["tc-dashboard",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("deal_pipeline").select(` id, deal_name, deal_type, property_address, city, state, expected_price, expected_commission, stage_id, contact_id, contract_date, target_close_date, actual_close_date, inspection_date, inspection_contingency_date, appraisal_date, loan_approval_date, earnest_money_due_date, title_docs_due_date, final_walkthrough_date, stage:deal_pipeline_stages(id, name, color, is_won_stage, is_lost_stage), contact:innercircle_contacts(id, first_name, last_name, email, phone) `).eq("owner_user_id",s);if(n)throw n;const r=(t||[]).filter(l=>{var o,c;return!((o=l.stage)!=null&&o.is_lost_stage)&&!((c=l.stage)!=null&&c.is_won_stage)}),a=r.map(l=>l.id);let i={};if(a.length>0){const{data:l}=await q.from("deal_tasks").select("id, deal_id, title, status, priority, due_date").in("deal_id",a).order("due_date",{ascending:!0,nullsFirst:!1});(l||[]).forEach(o=>{var c;o.deal_id&&(i[c=o.deal_id]||(i[c]=[])).push(o)})}return r.map(l=>({...l,tasks:i[l.id]||[]}))},enabled:!!s})}function Gat(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 H5(s){const t=Gat(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 NJn(s){return s===null?"none":s<0?"overdue":s===0?"today":s<=3?"soon":"upcoming"}const kJn={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 vBe(s){const t=Gat(s);return t?t.toLocaleDateString("en-US",{month:"short",day:"numeric"}):null}function s4t(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 SJn({deal:s,compact:t=!1}){const n=yJn(),r=vJn(),[a,i]=_.useState(!1),[l,o]=_.useState({}),c=Array.isArray(s==null?void 0:s.completed_key_dates)?s.completed_key_dates:[],[d,u]=_.useState(c),h=c.join(","),m=_.useRef(h);_.useEffect(()=>{m.current!==h&&(m.current=h,u(c))},[h]);const p=d,f=()=>{const H={};tQ.forEach(Y=>{H[Y.key]=(s==null?void 0:s[Y.key])??""}),o(H),i(!0)},y=async()=>{try{await n.mutateAsync({dealId:s.id,dates:l}),se.success("Transaction dates updated"),i(!1)}catch(H){se.error((H==null?void 0:H.message)||"Could not save dates")}},v=async(H,Y)=>{const Z=p;u(H);try{await r.mutateAsync({dealId:s.id,completed:H}),se.success(Y)}catch(ne){u(Z),se.error((ne==null?void 0:ne.message)||"Could not update milestone")}},g=_.useMemo(()=>tQ.map(H=>{const Y=(s==null?void 0:s[H.key])??null,Z=H5(Y),ne=p.includes(H.key),ce=Y?ne?"done":NJn(Z):"none";return{...H,value:Y,days:Z,isDone:ne,state:ce}}),[s,p.join(",")]),b=g.filter(H=>H.value).length,j=g.filter(H=>H.state==="done").length,S=H5(s==null?void 0:s.target_close_date),C=g.filter(H=>H.value&&!H.isDone&&H.days!==null&&H.days>=0).sort((H,Y)=>(H.days??0)-(Y.days??0))[0],E=g.filter(H=>H.state==="overdue"),P=()=>{const H=Array.from(new Set([...p,...E.map(Y=>Y.key)]));v(H,"Past milestones marked complete")},M=(H,Y)=>{const Z=Y?p.filter(ne=>ne!==H):[...p,H];v(Z,Y?"Marked as not complete":"Milestone completed")},[I,D]=_.useState(null),[O,V]=_.useState(""),G=H=>{V((s==null?void 0:s[H])??""),D(H)},$=async(H,Y)=>{try{await n.mutateAsync({dealId:s.id,dates:{[H]:Y}}),se.success(Y?"Date saved":"Date cleared"),D(null)}catch(Z){se.error((Z==null?void 0:Z.message)||"Could not save date")}};return e.jsx(FN,{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(Qd,{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:p.includes("target_close_date")||s!=null&&s.actual_close_date?`Closed${vBe((s==null?void 0:s.actual_close_date)||(s==null?void 0:s.target_close_date))?` ${vBe((s==null?void 0:s.actual_close_date)||(s==null?void 0:s.target_close_date))}`:""} · ${j}/${b} milestones done`:S!==null?S>=0?`${S} day${S===1?"":"s"} to closing · ${j}/${b} milestones done`:`Closing was ${Math.abs(S)} day${Math.abs(S)===1?"":"s"} ago`:`${b} of ${tQ.length} key dates set`})]})]}),e.jsxs(Ls,{open:a,onOpenChange:H=>H?f():i(!1),children:[e.jsx(nl,{asChild:!0,children:e.jsxs(B,{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(Ps,{className:"max-w-lg",children:[e.jsx(Os,{children:e.jsx(Ds,{children:"Key transaction dates"})}),e.jsx("div",{className:"grid sm:grid-cols-2 gap-3 max-h-[60vh] overflow-y-auto pr-1",children:tQ.map(H=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(J,{htmlFor:`kd-${H.key}`,className:"text-xs text-muted-foreground",children:H.label}),e.jsx(xe,{id:`kd-${H.key}`,type:"date",value:l[H.key]??"",onChange:Y=>o(Z=>({...Z,[H.key]:Y.target.value})),className:"h-9"})]},H.key))}),e.jsxs(yr,{children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>i(!1),children:"Cancel"}),e.jsxs(B,{size:"sm",onClick:y,disabled:n.isPending,children:[n.isPending?e.jsx(Ct,{className:"h-3.5 w-3.5 mr-1 animate-spin"}):e.jsx(ea,{className:"h-3.5 w-3.5 mr-1"}),"Save all"]})]})]})]})]}),e.jsxs("div",{className:"p-3",children:[e.jsx("div",{className:"grid grid-cols-3 sm:grid-cols-3 gap-2",children:g.map(H=>{const Y=!!H.value;return e.jsxs("div",{className:"relative",children:[e.jsxs(ag,{children:[e.jsx(ig,{asChild:!0,children:e.jsxs("button",{type:"button",disabled:r.isPending,onClick:()=>Y?M(H.key,H.isDone):G(H.key),className:At("relative text-left rounded-lg border px-2.5 py-2 transition-colors w-full",kJn[H.state],"hover:brightness-105 cursor-pointer"),children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide opacity-70 truncate pr-10",children:H.short}),e.jsx("p",{className:"text-sm font-semibold leading-tight truncate",children:vBe(H.value)??"Set date"}),H.value&&e.jsx("p",{className:"text-[10px] opacity-80 truncate",children:s4t(H.state,H.days)}),Y&&e.jsx("span",{className:At("absolute top-1.5 right-7 h-4 w-4 rounded-full border flex items-center justify-center",H.isDone?"bg-emerald-500 border-emerald-500 text-white":"border-current opacity-40"),children:H.isDone&&e.jsx(ea,{className:"h-2.5 w-2.5"})})]})}),e.jsx(Nx,{side:"top",children:H.value?H.isDone?`${H.label} completed — click to reopen`:`Click to mark ${H.label} complete`:`${H.label} — click to set the date`})]}),e.jsxs(od,{open:I===H.key,onOpenChange:Z=>Z?G(H.key):D(null),children:[e.jsx(ld,{asChild:!0,children:e.jsx("button",{type:"button","aria-label":`Edit ${H.label}`,className:"absolute top-1 right-1 h-5 w-5 rounded-md flex items-center justify-center text-muted-foreground hover:bg-muted hover:text-foreground transition-colors",children:e.jsx(Ya,{className:"h-3 w-3"})})}),e.jsxs(Qc,{className:"w-64 p-3",align:"end",children:[e.jsx(J,{className:"text-xs text-muted-foreground",children:H.label}),e.jsx(xe,{type:"date",autoFocus:!0,value:O,onChange:Z=>V(Z.target.value),className:"h-9 mt-1"}),e.jsxs("div",{className:"flex items-center justify-between gap-2 mt-3",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>$(H.key,""),disabled:n.isPending||!H.value,children:"Clear"}),e.jsxs(B,{size:"sm",onClick:()=>$(H.key,O),disabled:n.isPending,children:[n.isPending?e.jsx(Ct,{className:"h-3.5 w-3.5 mr-1 animate-spin"}):e.jsx(ea,{className:"h-3.5 w-3.5 mr-1"}),"Save"]})]})]})]})]},H.key)})}),(E.length>0||C||j>0)&&e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2 text-xs",children:[j>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(HO,{className:"h-3 w-3"}),j," completed"]}),E.length>0&&e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full bg-destructive/10 text-destructive px-2.5 py-1 font-medium",children:[e.jsx(xl,{className:"h-3 w-3"}),E.length," awaiting confirmation"]}),C&&e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full bg-primary/10 text-primary px-2.5 py-1 font-medium",children:["Next: ",C.label," · ",s4t(C.state,C.days)]}),E.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(HO,{className:"h-3 w-3"}),"Mark past dates complete"]})]}),E.length>0&&e.jsx("p",{className:"mt-2 text-[11px] text-muted-foreground",children:"Dates in the past show as awaiting confirmation until you check them off — tap a tile to mark it complete."}),b===0&&e.jsx("p",{className:"mt-3 text-xs text-muted-foreground text-center",children:"No key dates yet. Add them to unlock automatic deadline reminders."})]})]})})}const CJn={Home:Jr,FileSignature:lb,Handshake:wv,CalendarClock:Qd,Sparkles:un,ClipboardCheck:cN},AJn={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 EJn(s,t){var a;const n=((a=gJn.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 nrs({open:s,onOpenChange:t,dealId:n,dealName:r}){const{data:a,isLoading:i}=bJn(),{data:l}=eie(),o=_Jn(),c=wJn(),[d,u]=_.useState(null),[h,m]=_.useState({}),p=v=>{if(h[v.id])return h[v.id];const g=l==null?void 0:l.find(b=>{var j,S;return((j=b.name)==null?void 0:j.toLowerCase())===((S=v.target_stage_name)==null?void 0:S.toLowerCase())});return(g==null?void 0:g.id)??""},f=async v=>{if(n){u(v.id);try{const g=await o.mutateAsync({playbookId:v.id,dealId:n});se.success(g>0?`Added ${g} task${g===1?"":"s"} to this deal`:"All tasks already exist on this deal"),g>0&&t(!1)}catch(g){se.error((g==null?void 0:g.message)||"Could not apply playbook")}finally{u(null)}}},y=async v=>{const g=p(v);if(!g){se.error("Pick which stage this playbook should trigger on");return}u(`install-${v.id}`);try{const b=await c.mutateAsync({playbookId:v.id,stageId:g});se.success(b>0?`Automated — ${b} task${b===1?"":"s"} will now be created every time a deal reaches this stage`:"This playbook is already automated for that stage")}catch(b){se.error((b==null?void 0:b.message)||"Could not automate playbook")}finally{u(null)}};return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"sm:max-w-2xl max-h-[85vh] flex flex-col p-0",children:[e.jsx(Os,{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(Sx,{className:"h-4.5 w-4.5 text-primary"})}),e.jsxs("div",{children:[e.jsx(Ds,{children:"Transaction Playbooks"}),e.jsx(_r,{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(Ji,{className:"flex-1 min-h-0 overflow-y-auto",children:e.jsx("div",{className:"p-6 pt-4",children:i?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsx(G9,{type:"single",collapsible:!0,className:"space-y-3",children:(a||[]).map(v=>{const g=CJn[v.icon||"ClipboardCheck"]||cN,b=v.accent_color||"hsl(var(--primary))";return e.jsxs(gL,{value:v.id,className:"border rounded-xl px-0 overflow-hidden bg-card",children:[e.jsx(yL,{className:"px-4 py-3 hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-3 text-left flex-1 min-w-0",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg flex items-center justify-center shrink-0",style:{backgroundColor:`${b}1a`},children:e.jsx(g,{className:"h-5 w-5",style:{color:b}})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-semibold text-sm",children:v.name}),e.jsxs(Oe,{variant:"secondary",className:"text-[10px]",children:[v.tasks.length," steps"]}),v.deal_type&&e.jsx(Oe,{variant:"outline",className:"text-[10px] capitalize",children:v.deal_type})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:v.description})]})]})}),e.jsxs(vL,{className:"px-4 pb-4",children:[e.jsx("div",{className:"space-y-1.5 mb-4",children:v.tasks.map((j,S)=>e.jsxs("div",{className:"flex items-start gap-2.5 rounded-lg border bg-background px-3 py-2",children:[e.jsx("span",{className:"text-[10px] font-mono text-muted-foreground mt-0.5 w-4 shrink-0",children:S+1}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm font-medium leading-tight",children:j.title}),j.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:j.description}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-1",children:EJn(j.due_anchor,j.due_offset_days)})]}),e.jsx("span",{className:At("text-[10px] px-1.5 py-0.5 rounded-full shrink-0 capitalize",AJn[j.priority]),children:j.priority})]},j.id))}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2 pt-2 border-t",children:[n&&e.jsxs(B,{size:"sm",className:"gap-1.5",onClick:()=>f(v),disabled:d===v.id,children:[d===v.id?e.jsx(Ct,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(nf,{className:"h-3.5 w-3.5"}),"Add to this deal"]}),e.jsxs("div",{className:"flex gap-2 flex-1",children:[e.jsxs(is,{value:p(v),onValueChange:j=>m(S=>({...S,[v.id]:j})),children:[e.jsx(rs,{className:"h-9 text-xs flex-1",children:e.jsx(ls,{placeholder:"Trigger stage"})}),e.jsx(as,{children:(l||[]).map(j=>e.jsx(He,{value:j.id,children:j.name},j.id))})]}),e.jsxs(B,{size:"sm",variant:"outline",className:"gap-1.5 shrink-0",onClick:()=>y(v),disabled:d===`install-${v.id}`,children:[d===`install-${v.id}`?e.jsx(Ct,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(QA,{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(Er,{className:"h-3 w-3"}),"Automating adds these steps to every future deal that reaches that stage."]})]})]},v.id)})})})})]})})}function TJn(s){return at({queryKey:["deal-email-links",s],queryFn:async()=>{const{data:t,error:n}=await q.from("deal_email_links").select("id, gmail_message_id, gmail_thread_id, subject, from_address, participants, sent_at, note, created_at").eq("deal_id",s).order("sent_at",{ascending:!1,nullsFirst:!1}).range(0,999);if(n)throw n;return t},enabled:!!s})}function MJn(s){const t=Bt();return mt({mutationFn:async n=>{const{error:r}=await q.from("deal_email_links").delete().eq("id",n);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-email-links",s]})}})}function PJn(s,t){return s?`https://mail.google.com/mail/u/0/#all/${encodeURIComponent(s)}`:`https://mail.google.com/mail/u/0/#all/${encodeURIComponent(t)}`}function LJn({dealId:s}){const{data:t=[],isLoading:n,error:r}=TJn(s),a=MJn(s);return e.jsxs("section",{"aria-labelledby":"linked-emails-heading",className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h3",{id:"linked-emails-heading",className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(ln,{className:"h-4 w-4 text-primary"})," Linked emails"]}),t.length>0&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:[t.length," connected"]})]}),n?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading linked emails…"}):r?e.jsx("p",{className:"rounded-md border border-destructive/30 bg-destructive/5 p-3 text-sm text-destructive",children:"We couldn't load the emails linked to this transaction. Please refresh and try again."}):t.length===0?e.jsx("p",{className:"rounded-md border border-dashed p-3 text-sm text-muted-foreground",children:"No emails linked yet — attach one from Gmail with the LevelUp Companion extension."}):e.jsx("div",{className:"divide-y rounded-md border",children:t.map(i=>{const l=i.sent_at||i.created_at;return e.jsxs("div",{className:"flex items-start gap-3 p-3",children:[e.jsx(ln,{className:"mt-0.5 h-4 w-4 shrink-0 text-muted-foreground"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:i.subject||"Email from Gmail"}),e.jsxs("p",{className:"truncate text-xs text-muted-foreground",children:[i.from_address||"Unknown sender",l?` · ${Hs(Ru(l),"MMM d, yyyy")}`:"",i.sent_at?"":" (attached)"]}),i.note&&e.jsx("p",{className:"mt-1 line-clamp-2 text-xs text-muted-foreground",children:i.note})]}),e.jsx(B,{variant:"ghost",size:"icon",asChild:!0,title:"Open in Gmail",children:e.jsx("a",{href:PJn(i.gmail_thread_id,i.gmail_message_id),target:"_blank",rel:"noreferrer",children:e.jsx(wr,{className:"h-4 w-4"})})}),e.jsx(B,{variant:"ghost",size:"icon",title:"Remove link",disabled:a.isPending,onClick:()=>a.mutate(i.id),children:e.jsx(Sn,{className:"h-4 w-4"})})]},i.id)})})]})}const IJn=10*1024*1024;function DJn({dealId:s,photoUrl:t}){const n=_.useRef(null),r=Bt(),[a,i]=_.useState(!1),l=async d=>{const{error:u}=await q.from("deal_pipeline").update({property_photo_url:d}).eq("id",s);if(u)throw u;r.invalidateQueries({queryKey:["deal-pipeline-deals"]}),r.invalidateQueries({queryKey:["deals"]})},o=async d=>{var u;if(!d.type.startsWith("image/")){se.error("Please choose an image file");return}if(d.size>IJn){se.error("Image must be under 10MB");return}i(!0);try{const{data:h}=await q.auth.getUser(),m=(d.name.split(".").pop()||"jpg").toLowerCase(),p=`deal-photos/${(u=h.user)==null?void 0:u.id}/${s}-${Date.now()}.${m}`,{error:f}=await q.storage.from("agent-uploads").upload(p,d,{upsert:!0,contentType:d.type});if(f)throw f;const{data:y}=q.storage.from("agent-uploads").getPublicUrl(p);await l(y.publicUrl),se.success("Property photo updated")}catch(h){se.error(h.message||"Upload failed")}finally{i(!1),n.current&&(n.current.value="")}},c=async()=>{i(!0);try{await l(null),se.success("Photo removed")}catch(d){se.error(d.message||"Could not remove photo")}finally{i(!1)}};return e.jsxs("div",{className:"col-span-2",children:[e.jsxs("button",{type:"button",onClick:()=>{var d;return(d=n.current)==null?void 0:d.click()},disabled:a,className:"group relative w-full h-36 rounded-lg overflow-hidden border border-border bg-muted/40 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring","aria-label":t?"Change property photo":"Add property photo",children:[t?e.jsx("img",{src:t,alt:"Property",className:"h-full w-full object-cover"}):e.jsxs("span",{className:"flex h-full w-full flex-col items-center justify-center gap-1 text-muted-foreground",children:[e.jsx(Jr,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"Add property photo"})]}),e.jsx("span",{className:"absolute inset-0 bg-foreground/50 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center",children:a?e.jsx(Ct,{className:"h-5 w-5 text-background animate-spin"}):e.jsx(cg,{className:"h-5 w-5 text-background"})})]}),e.jsxs("div",{className:"flex items-center justify-between mt-1",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Shows on the deal and in the Gmail companion panel."}),t&&e.jsxs(B,{variant:"ghost",size:"sm",className:"gap-1.5 text-muted-foreground",onClick:c,disabled:a,children:[e.jsx(Sn,{className:"h-3.5 w-3.5"}),"Remove"]})]}),e.jsx("input",{ref:n,type:"file",accept:"image/*",className:"hidden",onChange:d=>{var h;const u=(h=d.target.files)==null?void 0:h[0];u&&o(u)}})]})}const RJn={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"}},FJn={note:Hi,call:_a,email:ln,meeting:ga,stage_change:wr,task_completed:Er,document:Jr,system:Gr};function OJn({deal:s,open:t,onOpenChange:n,onEdit:r,onAddToScorecard:a,isWonStage:i}){var Pe,ze;const l=Fn(),{data:o,isLoading:c}=AGn((s==null?void 0:s.id)||""),{data:d,isLoading:u}=TGn((s==null?void 0:s.id)||""),h=EGn(),m=PGn(),p=MGn(),f=CGn(),{data:y,isLoading:v}=IWn((s==null?void 0:s.id)||""),g=DWn(),b=RWn(),j=FWn(),S=_.useRef(null),[C,E]=_.useState(""),[P,M]=_.useState(""),[I,D]=_.useState(!1),[O,V]=_.useState(!1),[G,$]=_.useState(!1);if(!s)return null;const H=RJn[s.deal_type],Y=(()=>{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 Ze=s.contract_date?Ru(s.contract_date):new Date;return CN(Ze,Ru(ke))})(),Z=ke=>ke?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(ke):"-",ne=async()=>{if(C.trim())try{await h.mutateAsync({deal_id:s.id,activity_type:"note",title:"Note added",description:C}),E(""),se.success("Note added")}catch{se.error("Failed to add note")}},ce=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(""),se.success("Task added")}catch{se.error("Failed to add task")}},ie=async(ke,Ze)=>{try{await p.mutateAsync({id:ke,is_completed:Ze,deal_id:s.id})}catch{se.error("Failed to update task")}},te=async()=>{try{await f.mutateAsync(s.id),se.success("Deal deleted"),n(!1)}catch{se.error("Failed to delete deal")}},ae=(d==null?void 0:d.filter(ke=>ke.is_completed).length)||0,le=(d==null?void 0:d.length)||0,be=(y==null?void 0:y.length)||0,me=ke=>ke<1024?`${ke} B`:ke<1024*1024?`${(ke/1024).toFixed(1)} KB`:`${(ke/(1024*1024)).toFixed(1)} MB`,he=ke=>ke?ke.startsWith("image/")?hc:ke.includes("pdf")?Fr:Dq:Dq,pe=async ke=>{const Ze=ke.target.files;if(!(!Ze||!s)){$(!0);try{for(const Se of Array.from(Ze)){if(Se.size>20*1024*1024){se.error(`${Se.name} exceeds 20MB limit`);continue}await g.mutateAsync({dealId:s.id,file:Se})}se.success("File(s) uploaded")}catch{se.error("Failed to upload file")}finally{$(!1),S.current&&(S.current.value="")}}},Ce=async(ke,Ze)=>{if(s)try{await b.mutateAsync({fileId:ke,storagePath:Ze,dealId:s.id}),se.success("File deleted")}catch{se.error("Failed to delete file")}},Ae=async(ke,Ze)=>{try{const Se=await OWn(ke),Fe=document.createElement("a");Fe.href=Se,Fe.download=Ze,Fe.target="_blank",document.body.appendChild(Fe),Fe.click(),document.body.removeChild(Fe)}catch{se.error("Failed to download file")}};return e.jsxs(e.Fragment,{children:[e.jsx(qg,{open:t,onOpenChange:n,children:e.jsxs(hg,{className:"w-full sm:max-w-xl p-0 flex flex-col",children:[e.jsx(P0,{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(Oe,{variant:"outline",className:At("text-xs",H.color),children:H.label}),e.jsxs(Oe,{variant:"secondary",className:"text-xs capitalize",children:[s.priority," priority"]})]}),e.jsx(L0,{className:"text-xl",children:s.deal_name}),e.jsx("div",{className:"mt-2",children:e.jsx(LWn,{dealId:s.id})})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",size:"icon",onClick:()=>r(s),children:e.jsx(wp,{className:"h-4 w-4"})}),e.jsx(B,{variant:"outline",size:"icon",className:"text-destructive hover:bg-destructive/10",onClick:()=>V(!0),children:e.jsx(Sn,{className:"h-4 w-4"})})]})]})}),e.jsx(Ji,{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(ja,{className:"h-10 w-10",children:e.jsxs(Na,{className:"bg-primary/10 text-primary",children:[(Pe=s.contact.first_name)==null?void 0:Pe[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(B,{variant:"outline",size:"icon",asChild:!0,children:e.jsx("a",{href:`tel:${s.contact.phone}`,children:e.jsx(_a,{className:"h-4 w-4"})})}),s.contact.email&&e.jsx(B,{variant:"outline",size:"icon",asChild:!0,children:e.jsx("a",{href:`mailto:${s.contact.email}`,children:e.jsx(ln,{className:"h-4 w-4"})})}),e.jsx(B,{variant:"outline",size:"icon",title:"Open contact record",onClick:()=>{n(!1),l(`/mission-control/contacts/${s.contact_id}`)},children:e.jsx(wr,{className:"h-4 w-4"})})]})]}),e.jsx(xJn,{dealId:s.id,primaryContactId:s.contact_id}),e.jsx(LJn,{dealId:s.id}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx(DJn,{dealId:s.id,photoUrl:s.property_photo_url}),(s.property_address||s.city)&&e.jsxs("div",{className:"col-span-2 flex items-start gap-2 text-sm",children:[e.jsx(Jr,{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:Z(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:Z(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?` (${Z(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:Z(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:["+",Z(s.bonus_amount)]})]}),j_(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:Z(j_(s))})]})})]}),i&&!s.scorecard_transaction_id&&a&&e.jsxs(B,{onClick:()=>a(s),className:"w-full bg-green-600 hover:bg-green-700",children:[e.jsx(wl,{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(Er,{className:"h-4 w-4 text-green-600"}),e.jsx("span",{children:"Synced to Scorecard"})]}),Y!==null&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 col-span-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Days on Market"}),e.jsxs("p",{className:At("text-lg font-bold",Y>90?"text-red-600":Y>60?"text-amber-600":"text-foreground"),children:[Y," ",s.contract_date?"(final)":"days"]})]}),s.target_close_date&&e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(ga,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Close: ",Hs(Ru(s.target_close_date),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(yd,{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(SJn,{deal:s}),e.jsx(fJn,{deal:s}),e.jsxs(Yr,{defaultValue:"tasks",className:"w-full",children:[e.jsxs(Zr,{className:"w-full grid grid-cols-4",children:[e.jsxs(Ht,{value:"tasks",className:"gap-1",children:[e.jsx(Er,{className:"h-4 w-4"}),"Tasks ",le>0&&`(${ae}/${le})`]}),e.jsxs(Ht,{value:"files",className:"gap-1",children:[e.jsx(eP,{className:"h-4 w-4"}),"Files ",be>0&&`(${be})`]}),e.jsxs(Ht,{value:"forms",className:"gap-1",children:[e.jsx(lb,{className:"h-4 w-4"}),"Forms"]}),e.jsxs(Ht,{value:"activity",className:"gap-1",children:[e.jsx(Gr,{className:"h-4 w-4"}),"Activity"]})]}),e.jsx(Gt,{value:"forms",className:"mt-4",children:e.jsx(cJn,{dealId:s.id,dealName:s.deal_name})}),e.jsxs(Gt,{value:"tasks",className:"mt-4 space-y-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{placeholder:"Add a new task...",value:P,onChange:ke=>M(ke.target.value),onKeyDown:ke=>ke.key==="Enter"&&ce()}),e.jsx(B,{onClick:ce,disabled:!P.trim(),children:e.jsx(rn,{className:"h-4 w-4"})}),e.jsxs(B,{variant:"outline",className:"gap-1.5 shrink-0",onClick:()=>D(!0),children:[e.jsx(Sx,{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:At("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($a,{checked:ke.is_completed,onCheckedChange:Ze=>ie(ke.id,!!Ze)}),e.jsx("span",{className:At("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(Gt,{value:"files",className:"mt-4 space-y-3",children:[(s==null?void 0:s.id)&&e.jsx(UWn,{dealId:s.id}),e.jsx("input",{type:"file",ref:S,className:"hidden",multiple:!0,onChange:pe,accept:".pdf,.doc,.docx,.xls,.xlsx,.jpg,.jpeg,.png,.webp,.gif,.txt,.csv"}),e.jsxs(B,{variant:"outline",className:"w-full border-dashed",onClick:()=>{var ke;return(ke=S.current)==null?void 0:ke.click()},disabled:G,children:[G?e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Oa,{className:"h-4 w-4 mr-2"}),G?"Uploading...":"Upload Files"]}),e.jsxs("div",{className:"space-y-2",children:[y==null?void 0:y.map(ke=>{const Ze=he(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(Ze,{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:[me(ke.file_size)," · ",Hs(new Date(ke.created_at),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(FN,{children:e.jsxs(ag,{children:[e.jsx(ig,{asChild:!0,children:e.jsx(B,{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:()=>j.mutate({fileId:ke.id,visible:!ke.visible_on_portal,dealId:s.id}),children:ke.visible_on_portal?e.jsx(ya,{className:"h-4 w-4"}):e.jsx(Ax,{className:"h-4 w-4"})})}),e.jsx(Nx,{side:"top",children:ke.visible_on_portal?"Visible on client portal":"Hidden from client portal"})]})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>Ae(ke.storage_path,ke.file_name),children:e.jsx(li,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",onClick:()=>Ce(ke.id,ke.storage_path),children:e.jsx(Qn,{className:"h-4 w-4"})})]})]},ke.id)}),(y==null?void 0:y.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(Gt,{value:"activity",className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ms,{placeholder:"Add a note...",value:C,onChange:ke=>E(ke.target.value),rows:2}),e.jsxs(B,{onClick:ne,disabled:!C.trim(),size:"sm",className:"w-full",children:[e.jsx(Or,{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 Ze=FJn[ke.activity_type]||Gr;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(Ze,{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:Ed(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(nrs,{open:I,onOpenChange:D,dealId:s==null?void 0:s.id,dealName:s==null?void 0:s.deal_name}),e.jsx(Kl,{open:O,onOpenChange:V,children:e.jsxs(Ol,{children:[e.jsxs(zl,{children:[e.jsx(Ul,{children:"Delete Deal?"}),e.jsxs(ql,{children:['This will permanently delete "',s.deal_name,'" and all associated data. This action cannot be undone.']})]}),e.jsxs(Bl,{children:[e.jsx($l,{children:"Cancel"}),e.jsx(Ml,{onClick:te,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})})]})}function zJn({open:s,onOpenChange:t,deal:n,onComplete:r}){const a=hLe(),i=Yts(),{data:l}=V9(),{data:o}=Z_(),[c,d]=_.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:""});_.useEffect(()=>{if(n&&s){const m=n.deal_type==="seller"?"seller":"buyer",p=n.expected_price||0,f=n.commission_percentage||3,y=n.expected_commission||p*f/100;d({property_address:n.property_address||n.deal_name||"",city:n.city||"",state:n.state||"",zip:n.zip_code||"",transaction_type:m,close_date:n.actual_close_date||n.target_close_date||Hs(new Date,"yyyy-MM-dd"),sale_price:p,commission_amount:y,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}),se.success("Deal added to Scorecard! 🎉"),t(!1),r==null||r()}catch(p){console.error("Error syncing to scorecard:",p),se.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(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"sm:max-w-[550px] max-h-[90vh] overflow-y-auto",children:[e.jsxs(Os,{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(wl,{className:"h-6 w-6 text-green-600 dark:text-green-400"})}),e.jsx(Ds,{className:"text-center text-xl",children:"Congratulations on Closing! 🎉"}),e.jsx(_r,{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(J,{htmlFor:"property_address",className:"flex items-center gap-2",children:[e.jsx(Jr,{className:"h-4 w-4 text-muted-foreground"}),"Property Address *"]}),e.jsx(xe,{id:"property_address",value:c.property_address,onChange:m=>d(p=>({...p,property_address:m.target.value})),placeholder:"123 Main St",required:!0})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"city",children:"City"}),e.jsx(xe,{id:"city",value:c.city,onChange:m=>d(p=>({...p,city:m.target.value})),placeholder:"City"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"state",children:"State"}),e.jsx(xe,{id:"state",value:c.state,onChange:m=>d(p=>({...p,state:m.target.value})),placeholder:"TX",maxLength:2})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"zip",children:"Zip"}),e.jsx(xe,{id:"zip",value:c.zip,onChange:m=>d(p=>({...p,zip:m.target.value})),placeholder:"75001"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Transaction Type *"}),e.jsxs(is,{value:c.transaction_type,onValueChange:m=>d(p=>({...p,transaction_type:m})),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"buyer",children:"Buyer"}),e.jsx(He,{value:"seller",children:"Seller"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(J,{htmlFor:"close_date",className:"flex items-center gap-2",children:[e.jsx(ga,{className:"h-4 w-4 text-muted-foreground"}),"Close Date *"]}),e.jsx(xe,{id:"close_date",type:"date",value:c.close_date,onChange:m=>d(p=>({...p,close_date:m.target.value})),required:!0})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(J,{htmlFor:"sale_price",className:"flex items-center gap-2",children:[e.jsx(yd,{className:"h-4 w-4 text-muted-foreground"}),"Sale Price *"]}),e.jsx(xe,{id:"sale_price",type:"number",value:c.sale_price||"",onChange:m=>d(p=>({...p,sale_price:Number(m.target.value)})),placeholder:"450000",required:!0,min:0}),c.sale_price>0&&e.jsx("p",{className:"text-xs text-muted-foreground",children:h(c.sale_price)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(J,{htmlFor:"commission_amount",className:"flex items-center gap-2",children:[e.jsx(F_,{className:"h-4 w-4 text-muted-foreground"}),"GCI (Commission)"]}),e.jsx(xe,{id:"commission_amount",type:"number",value:c.commission_amount||"",onChange:m=>d(p=>({...p,commission_amount:Number(m.target.value)})),placeholder:"13500",min:0}),c.commission_amount>0&&e.jsx("p",{className:"text-xs text-muted-foreground",children:h(c.commission_amount)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Lead Source"}),e.jsxs(is,{value:c.lead_source_id,onValueChange:m=>d(p=>({...p,lead_source_id:m})),children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Select source"})}),e.jsx(as,{children:l==null?void 0:l.map(m=>e.jsx(He,{value:m.id,children:m.name},m.id))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Client Type"}),e.jsxs(is,{value:c.client_type_id,onValueChange:m=>d(p=>({...p,client_type_id:m})),children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Select type"})}),e.jsx(as,{children:o==null?void 0:o.map(m=>e.jsx(He,{value:m.id,children:m.name},m.id))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"notes",children:"Notes"}),e.jsx(Ms,{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(yr,{className:"gap-2 sm:gap-0 pt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Skip for now"}),e.jsx(B,{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(La,{className:"ml-2 h-4 w-4"})]})})]})]})]})})}const BJn={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"}},n4t={urgent:0,high:1,medium:2,low:3};function UJn({deals:s,stages:t,onDealClick:n,onStageChange:r}){const[a,i]=_.useState("target_close_date"),[l,o]=_.useState("asc"),c=p=>{a===p?o(f=>f==="asc"?"desc":"asc"):(i(p),o("asc"))},d=_.useMemo(()=>[...s].sort((p,f)=>{var v,g;let y=0;switch(a){case"deal_name":y=p.deal_name.localeCompare(f.deal_name);break;case"stage":{const b=((v=t.find(S=>S.id===p.stage_id))==null?void 0:v.sort_order)||0,j=((g=t.find(S=>S.id===f.stage_id))==null?void 0:g.sort_order)||0;y=b-j;break}case"expected_price":y=(p.expected_price||0)-(f.expected_price||0);break;case"expected_commission":y=(p.expected_commission||0)-(f.expected_commission||0);break;case"target_close_date":{const b=p.target_close_date?Ru(p.target_close_date).getTime():1/0,j=f.target_close_date?Ru(f.target_close_date).getTime():1/0;y=b-j;break}case"priority":y=n4t[p.priority]-n4t[f.priority];break}return l==="asc"?y:-y}),[s,t,a,l]),u=p=>p?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(p):"—",h=p=>p?t.find(f=>f.id===p):null,m=({field:p,children:f})=>e.jsxs(B,{variant:"ghost",size:"sm",className:"h-8 -ml-3 font-medium",onClick:()=>c(p),children:[f,a===p?l==="asc"?e.jsx(sp,{className:"ml-2 h-4 w-4"}):e.jsx(zf,{className:"ml-2 h-4 w-4"}):e.jsx(Lg,{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(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{className:"bg-muted/50",children:[e.jsx(Pt,{className:"w-[250px]",children:e.jsx(m,{field:"deal_name",children:"Deal Name"})}),e.jsx(Pt,{className:"w-[150px]",children:e.jsx(m,{field:"stage",children:"Stage"})}),e.jsx(Pt,{className:"w-[100px]",children:"Type"}),e.jsx(Pt,{className:"w-[120px]",children:e.jsx(m,{field:"expected_price",children:"Price"})}),e.jsx(Pt,{className:"w-[120px]",children:e.jsx(m,{field:"expected_commission",children:"GCI"})}),e.jsx(Pt,{className:"w-[130px]",children:e.jsx(m,{field:"target_close_date",children:"Close Date"})}),e.jsx(Pt,{className:"w-[100px]",children:e.jsx(m,{field:"priority",children:"Priority"})})]})}),e.jsx(Ka,{children:d.map(p=>{const f=h(p.stage_id),y=BJn[p.deal_type],v=p.target_close_date?CN(Ru(p.target_close_date),new Date):null,g=!!(f!=null&&f.is_won_stage)||!!(f!=null&&f.is_lost_stage)||!!p.actual_close_date,b=!g&&v!==null&&v<0,j=!g&&v!==null&&v<=7&&v>=0;return e.jsxs(pn,{className:At("cursor-pointer hover:bg-muted/50 transition-colors",b&&"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:S=>S.stopPropagation(),children:e.jsx(Jts,{stages:t,currentStageId:p.stage_id||"",onStageSelect:(S,C)=>r(p.id,S,C)})}),e.jsx(gt,{children:e.jsx(Oe,{variant:"outline",className:At("text-xs",y.color),children:y.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:At("flex items-center gap-1 text-sm",b&&"text-red-600",j&&!b&&"text-amber-600"),children:[b&&e.jsx(Xo,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:Hs(Ru(p.target_close_date),"MMM d, yyyy")})]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(gt,{children:e.jsx(Oe,{variant:"outline",className:At("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 rrs(){const s=ha();return at({queryKey:["deal-tasks",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("deal_tasks").select(` *, deal:deal_pipeline(id, deal_name, stage_id), contact:innercircle_contacts(id, first_name, last_name), stage:deal_pipeline_stages(id, name, color) `).eq("owner_user_id",s).order("sort_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function qJn(s){const t=ha();return at({queryKey:["deal-tasks","deal",s,t],queryFn:async()=>{if(!t||!s)return[];const{data:n,error:r}=await q.from("deal_tasks").select(` *, stage:deal_pipeline_stages(id, name, color) `).eq("owner_user_id",t).eq("deal_id",s).order("sort_order",{ascending:!0});if(r)throw r;return n},enabled:!!t&&!!s})}function $Jn(){const s=ha(),t=Bt();return mt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("deal_tasks").insert({owner_user_id:s,title:n.title,description:n.description||null,deal_id:n.deal_id||null,contact_id:n.contact_id||null,stage_id:n.stage_id||null,priority:n.priority||"medium",status:n.status||"todo",due_date:n.due_date||null,sort_order:n.sort_order||0}).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-tasks"]})}})}function VJn(){const s=Bt();return mt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("deal_tasks").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-tasks"]})}})}function HJn(){const s=Bt();return mt({mutationFn:async t=>{const{error:n}=await q.from("deal_tasks").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-tasks"]})}})}function tDe(){const s=Bt();return mt({mutationFn:async({id:t,status:n})=>{const{data:r,error:a}=await q.from("deal_tasks").update({status:n,completed_at:n==="done"?new Date().toISOString():null}).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-tasks"]})}})}function GJn(){const s=Bt();return mt({mutationFn:async t=>{if(t.length===0)return;const{error:n}=await q.from("deal_tasks").update({status:"done",completed_at:new Date().toISOString()}).in("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-tasks"]})}})}function WJn(s){const t=ha();return at({queryKey:["deal-task-templates",t,s],queryFn:async()=>{if(!t)return[];let n=q.from("deal_task_templates").select("*").eq("owner_user_id",t).order("sort_order",{ascending:!0});s&&(n=n.eq("stage_id",s));const{data:r,error:a}=await n;if(a)throw a;return r},enabled:!!t})}function KJn(){const s=ha(),t=Bt();return mt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("deal_task_templates").insert({owner_user_id:s,stage_id:n.stage_id,title:n.title,description:n.description||null,priority:n.priority||"medium",default_due_offset_days:n.default_due_offset_days||null,sort_order:n.sort_order||0}).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-task-templates"]})}})}function YJn(){const s=Bt();return mt({mutationFn:async t=>{const{error:n}=await q.from("deal_task_templates").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-task-templates"]})}})}function ZJn(){const s=ha(),t=Bt();return mt({mutationFn:async({dealId:n,stageId:r})=>{if(!s)throw new Error("Not authenticated");const{data:a,error:i}=await q.from("deal_task_templates").select("*").eq("owner_user_id",s).eq("stage_id",r).order("sort_order");if(i)throw i;if(!a||a.length===0)return[];const{data:l}=await q.from("deal_tasks").select("title, stage_id").eq("deal_id",n).eq("stage_id",r),o=new Set((l||[]).map(h=>h.title)),c=a.filter(h=>!o.has(h.title)).map((h,m)=>({owner_user_id:s,deal_id:n,stage_id:r,title:h.title,description:h.description,priority:h.priority,due_date:h.default_due_offset_days?new Date(Date.now()+h.default_due_offset_days*864e5).toISOString().split("T")[0]:null,sort_order:m,status:"todo"}));if(c.length===0)return[];const{data:d,error:u}=await q.from("deal_tasks").insert(c).select();if(u)throw u;return d},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-tasks"]})}})}const XJn={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function QJn({open:s,onOpenChange:t,dealId:n,dealName:r,fromStageName:a,toStageName:i,toStageId:l,onConfirm:o}){const{data:c,isLoading:d}=qJn(s?n:void 0),u=GJn(),h=ZJn(),[m,p]=_.useState(new Set),[f,y]=_.useState(!1),v=(c||[]).filter(S=>S.status!=="done");_.useEffect(()=>{v.length>0&&p(new Set(v.map(S=>S.id)))},[c]);const g=S=>{p(C=>{const E=new Set(C);return E.has(S)?E.delete(S):E.add(S),E})},b=async()=>{y(!0);try{const S=Array.from(m);S.length>0&&await u.mutateAsync(S),await o(),await h.mutateAsync({dealId:n,stageId:l}),t(!1)}catch(S){console.error("Stage move failed:",S),se.error((S==null?void 0:S.message)||"Failed to move deal. Please try again.")}finally{y(!1)}},j=async()=>{y(!0);try{await o(),await h.mutateAsync({dealId:n,stageId:l}),t(!1)}catch(S){console.error("Stage move (skip) failed:",S),se.error((S==null?void 0:S.message)||"Failed to move deal. Please try again.")}finally{y(!1)}};return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"sm:max-w-[480px]",children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Move Deal"}),e.jsxs(_r,{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(Oe,{variant:"outline",className:"text-sm",children:a}),e.jsx(La,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(Oe,{className:"text-sm bg-primary",children:i})]}),d?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):v.length>0?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["You have ",e.jsx("span",{className:"font-medium text-foreground",children:v.length})," incomplete task",v.length!==1?"s":"",". Select which to mark as done:"]}),e.jsx(Ji,{className:"max-h-[250px]",children:e.jsx("div",{className:"space-y-1",children:v.map(S=>e.jsxs("label",{className:"flex items-center gap-3 px-3 py-2 rounded-lg hover:bg-muted/50 cursor-pointer transition-colors",children:[e.jsx($a,{checked:m.has(S.id),onCheckedChange:()=>g(S.id)}),e.jsxs("span",{className:"text-sm flex-1",children:[XJn[S.priority]," ",S.title]}),S.stage&&e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full",style:{backgroundColor:S.stage.color+"20",color:S.stage.color},children:S.stage.name})]},S.id))})}),e.jsxs("div",{className:"flex items-center justify-between gap-2 pt-2",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>{m.size===v.length?p(new Set):p(new Set(v.map(S=>S.id)))},children:m.size===v.length?"Deselect All":"Select All"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",size:"sm",onClick:j,disabled:f,children:"Skip"}),e.jsxs(B,{size:"sm",onClick:b,disabled:f,children:[f&&e.jsx(Ct,{className:"h-4 w-4 mr-1 animate-spin"}),m.size>0?`Complete ${m.size} & Move`:"Move Deal"]})]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"text-center py-4",children:[e.jsx(Er,{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(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{onClick:b,disabled:f,children:[f&&e.jsx(Ct,{className:"h-4 w-4 mr-1 animate-spin"}),"Move to ",i]})]})]})]})})}const JJn=[{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"}],eer=[{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 ars({open:s,onOpenChange:t}){const n=ha(),{data:r,isLoading:a}=K7t(),i=YRs(),[l,o]=_.useState({logo_url:null,cover_photo_url:null,brand_color:null,accent_color:null,tagline:null,welcome_message:null,portal_theme:"noir"}),[c,d]=_.useState(null);_.useEffect(()=>{s&&o({logo_url:(r==null?void 0:r.logo_url)??null,cover_photo_url:(r==null?void 0:r.cover_photo_url)??null,brand_color:(r==null?void 0:r.brand_color)??null,accent_color:(r==null?void 0:r.accent_color)??null,tagline:(r==null?void 0:r.tagline)??null,welcome_message:(r==null?void 0:r.welcome_message)??null,portal_theme:(r==null?void 0:r.portal_theme)??"noir"})},[s,r]);const u=p=>o(f=>({...f,...p})),h=async(p,f)=>{if(n){if(p.size>5*1024*1024){se.error("Image must be under 5MB");return}d(f);try{const y=await Y7t(n,p,f);u(f==="logo"?{logo_url:y}:{cover_photo_url:y})}catch(y){se.error(`Upload failed: ${y.message||y}`)}finally{d(null)}}},m=async()=>{try{await i.mutateAsync(l),se.success("Portal branding saved"),t(!1)}catch{se.error("Failed to save branding")}};return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"max-w-lg max-h-[90vh] flex flex-col",children:[e.jsxs(Os,{children:[e.jsxs(Ds,{className:"flex items-center gap-2",children:[e.jsx(Xc,{className:"h-5 w-5 text-primary"}),"Portal Branding"]}),e.jsx(_r,{children:"Customize how your client portals look. These defaults apply to every portal — you can override them per deal."})]}),e.jsx(Ji,{className:"flex-1 pr-3 -mr-3",children:a?e.jsx("div",{className:"py-12 flex justify-center",children:e.jsx(Ct,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-6 py-2",children:[e.jsx(ter,{draft:l}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(J,{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:eer.map(p=>{const f=(l.portal_theme??"noir")===p.id;return e.jsxs("button",{type:"button",onClick:()=>u({portal_theme:p.id}),className:At("rounded-xl border-2 p-3 text-left transition-all",f?"border-primary ring-2 ring-primary/20":"border-input hover:border-primary/40"),children:[e.jsx("div",{className:"rounded-lg overflow-hidden mb-2",style:{background:p.bg},children:e.jsxs("div",{className:"p-3 space-y-1.5",children:[e.jsx("div",{className:"h-1.5 w-10 rounded-full",style:{background:p.accent}}),e.jsx("div",{className:"h-2.5 w-20 rounded",style:{background:p.ink,opacity:.85}}),e.jsx("div",{className:"h-6 rounded-md",style:{background:p.surface,border:`1px solid ${p.accent}44`}})]})}),e.jsx("div",{className:"text-sm font-medium text-foreground",children:p.name}),e.jsx("div",{className:"text-[11px] text-muted-foreground leading-snug",children:p.description})]},p.id)})})]}),e.jsx(r4t,{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(r4t,{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(J,{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:JJn.map(p=>{const f=l.brand_color===p.brand&&l.accent_color===p.accent;return e.jsxs("button",{type:"button",onClick:()=>u({brand_color:p.brand,accent_color:p.accent}),className:At("group relative rounded-lg border-2 p-2 text-left transition-all",f?"border-primary ring-2 ring-primary/20":"border-input hover:border-primary/40"),children:[e.jsxs("div",{className:"flex h-6 rounded-md overflow-hidden",children:[e.jsx("div",{className:"flex-1",style:{background:p.brand}}),e.jsx("div",{className:"flex-1",style:{background:p.accent}})]}),e.jsx("div",{className:"text-[11px] mt-1.5 font-medium text-foreground",children:p.name})]},p.name)})}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(a4t,{label:"Brand",value:l.brand_color,onChange:p=>u({brand_color:p})}),e.jsx(a4t,{label:"Accent",value:l.accent_color,onChange:p=>u({accent_color:p})})]})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-sm font-medium",children:"Tagline"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Short line shown under your name."}),e.jsx(xe,{value:l.tagline||"",onChange:p=>u({tagline:p.target.value}),placeholder:"Your trusted real estate advisor",maxLength:80})]}),e.jsxs("div",{children:[e.jsx(J,{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(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{onClick:m,disabled:i.isPending,children:[i.isPending?e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ho,{className:"h-4 w-4 mr-2"}),"Save Branding"]})]})]})})}function ter({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 r4t({label:s,hint:t,value:n,uploading:r,onUpload:a,onClear:i,aspect:l}){return e.jsxs("div",{children:[e.jsx(J,{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:At("rounded-lg border-2 border-dashed border-input flex items-center justify-center overflow-hidden bg-muted/30 shrink-0",l==="square"?"h-16 w-16":"h-16 w-32"),children:n?e.jsx("img",{src:n,alt:s,className:"h-full w-full object-cover"}):e.jsx(hc,{className:"h-5 w-5 text-muted-foreground/40"})}),e.jsxs("div",{className:"flex-1 flex gap-2",children:[e.jsxs("label",{className:"cursor-pointer",children:[e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:o=>{var d;const c=(d=o.target.files)==null?void 0:d[0];c&&a(c),o.target.value=""}}),e.jsxs("span",{className:"inline-flex items-center gap-1.5 h-9 px-3 rounded-md border border-input bg-background hover:bg-accent text-sm font-medium",children:[r?e.jsx(Ct,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Oa,{className:"h-3.5 w-3.5"}),n?"Replace":"Upload"]})]}),n&&e.jsx(B,{variant:"ghost",size:"sm",onClick:i,className:"text-muted-foreground hover:text-destructive",children:e.jsx(Sn,{className:"h-3.5 w-3.5"})})]})]})]})}function a4t({label:s,value:t,onChange:n}){const r=t||"#000000";return e.jsxs("div",{children:[e.jsx(J,{className:"text-xs text-muted-foreground",children:s}),e.jsxs("div",{className:"mt-1 flex items-center gap-2 h-9 rounded-md border border-input bg-background px-2",children:[e.jsx("input",{type:"color",value:r,onChange:a=>n(a.target.value),className:"h-6 w-8 rounded cursor-pointer border-0 bg-transparent"}),e.jsx(xe,{value:t||"",onChange:a=>n(a.target.value||null),placeholder:"#406E71",className:"border-0 h-7 px-1 focus-visible:ring-0 text-xs font-mono"})]})]})}function ser(){const s=ha();return at({queryKey:["all-client-portals",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("client_portals").select("*").eq("owner_user_id",s);if(n)throw n;return t||[]},enabled:!!s})}function ner({dealId:s,dealName:t,contactName:n,portal:r,onSettingsOpen:a,onComposerOpen:i,onInviteOpen:l,onDeleteConfirm:o}){const c=Snt(),d=VW(),u=$Yt(),h=VYt(),[m,p]=_.useState(!1),f=!!(r!=null&&r.archived_at),y=async()=>{p(!0);try{await c.mutateAsync({deal_id:s,visibility:"private",require_onboarding:!0}),se.success("Portal enabled!")}catch{se.error("Failed to create portal")}finally{p(!1)}},v=async C=>{if(r)try{await d.mutateAsync({id:r.id,is_enabled:C}),se.success(C?"Portal enabled":"Portal disabled")}catch{se.error("Failed to update portal")}},g=()=>{r&&(navigator.clipboard.writeText(wS(r.slug)),se.success("Link copied!"))},b=()=>{r&&window.open(wS(r.slug),"_blank")},j=async()=>{if(r)try{await u.mutateAsync(r.id),se.success("Portal archived")}catch{se.error("Failed to archive portal")}},S=async()=>{if(r)try{await h.mutateAsync(r.id),se.success("Portal restored")}catch{se.error("Failed to restore portal")}};return r?f?e.jsxs("div",{className:"flex items-center gap-4 p-4 border rounded-lg opacity-60 bg-muted/30",children:[e.jsxs(ir,{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(Oe,{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(B,{variant:"ghost",size:"sm",onClick:S,className:"text-xs gap-1",children:[e.jsx(VM,{className:"h-3.5 w-3.5"}),"Restore"]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>o(r),className:"text-xs gap-1 text-destructive hover:text-destructive",children:[e.jsx(Sn,{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(ir,{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(Oe,{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(xi,{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(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:g,title:"Copy link",children:e.jsx(Ia,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:b,title:"Preview",children:e.jsx(wr,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>l(r,t),title:"Invite client",children:e.jsx(Or,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>i(r),title:"Post update",children:e.jsx(E4,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>a(r),title:"Settings",children:e.jsx(qc,{className:"h-3.5 w-3.5"})}),e.jsxs(tu,{children:[e.jsx(su,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(ob,{className:"h-3.5 w-3.5"})})}),e.jsx(Od,{align:"end",children:e.jsxs(ca,{onClick:j,children:[e.jsx(by,{className:"h-4 w-4 mr-2"}),"Archive Portal"]})})]}),e.jsx(fn,{checked:r.is_enabled,onCheckedChange:v,className:"ml-1"})]})]}):e.jsxs("div",{className:"flex items-center justify-between p-4 border rounded-lg border-dashed bg-muted/20",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:t}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:n||"No contact"})]}),e.jsxs(B,{size:"sm",onClick:y,disabled:m,className:"shrink-0 ml-4",children:[m?e.jsx(Ct,{className:"h-3 w-3 animate-spin mr-1"}):e.jsx(un,{className:"h-3 w-3 mr-1"}),"Enable Portal"]})]})}function irs(){const{data:s,isLoading:t}=lK(),{data:n,isLoading:r}=ser(),[a,i]=_.useState(""),[l,o]=_.useState("all"),c=HYt(),[d,u]=_.useState(null),[h,m]=_.useState(null),[p,f]=_.useState(null),[y,v]=_.useState(null),[g,b]=_.useState(!1),j=ha(),S=t||r,C=new Map;n==null||n.forEach(V=>C.set(V.deal_id,V));const P=[...(s||[]).filter(V=>{var Z,ne,ce,ie,te;const G=C.get(V.id),$=a.toLowerCase(),H=!$||V.deal_name.toLowerCase().includes($)||((ne=(Z=V.contact)==null?void 0:Z.first_name)==null?void 0:ne.toLowerCase().includes($))||((ie=(ce=V.contact)==null?void 0:ce.last_name)==null?void 0:ie.toLowerCase().includes($))||((te=G==null?void 0:G.client_name)==null?void 0:te.toLowerCase().includes($));let Y=!0;return l==="active"?Y=!!(G!=null&&G.is_enabled)&&!(G!=null&&G.archived_at):l==="disabled"?Y=!!G&&!G.is_enabled&&!G.archived_at:l==="archived"?Y=!!(G!=null&&G.archived_at):l==="none"?Y=!G:l==="all"&&(Y=!(G!=null&&G.archived_at)||!G),H&&Y})].sort((V,G)=>{const $=C.get(V.id),H=C.get(G.id);if($!=null&&$.archived_at&&!(H!=null&&H.archived_at))return 1;if(!($!=null&&$.archived_at)&&(H!=null&&H.archived_at)||$&&!H)return-1;if(!$&&H)return 1;if($&&H){if($.is_enabled&&!H.is_enabled)return-1;if(!$.is_enabled&&H.is_enabled)return 1}return 0}),M=(n==null?void 0:n.filter(V=>!V.archived_at).length)||0,I=(n==null?void 0:n.filter(V=>V.is_enabled&&!V.archived_at).length)||0,D=(n==null?void 0:n.filter(V=>V.archived_at).length)||0,O=async()=>{if(y)try{await c.mutateAsync({id:y.id,dealId:y.deal_id}),se.success("Portal permanently deleted"),v(null)}catch{se.error("Failed to delete portal")}};return S?e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(un,{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(B,{variant:"outline",size:"sm",onClick:()=>b(!0),className:"gap-1.5",children:[e.jsx(Xc,{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(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search deals or clients...",value:a,onChange:V=>i(V.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(Qn,{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(V=>e.jsx(B,{variant:l===V?"secondary":"ghost",size:"sm",onClick:()=>o(V),className:"text-xs px-3 capitalize",children:V==="none"?"No Portal":V},V))})]}),e.jsx(Ji,{className:"h-[calc(100vh-22rem)]",children:e.jsxs("div",{className:"space-y-2 pb-4",children:[P.map(V=>{const G=C.get(V.id)||null,$=V.contact?`${V.contact.first_name||""} ${V.contact.last_name||""}`.trim():"";return e.jsx(ner,{dealId:V.id,dealName:V.deal_name,contactName:$,portal:G,onSettingsOpen:u,onComposerOpen:H=>m(H),onInviteOpen:(H,Y)=>f({portal:H,dealName:Y}),onDeleteConfirm:v},V.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(un,{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($at,{open:!!d,onOpenChange:V=>!V&&u(null),portal:d,dealOwnerId:j||""}),h&&e.jsx(Vat,{open:!!h,onOpenChange:V=>!V&&m(null),portalId:h.id,portalSlug:h.slug,notifyClient:h.notify_client}),p&&e.jsx(Hat,{open:!!p,onOpenChange:V=>!V&&f(null),portal:p.portal,dealName:p.dealName}),e.jsx(ars,{open:g,onOpenChange:b}),e.jsx(Kl,{open:!!y,onOpenChange:V=>!V&&v(null),children:e.jsxs(Ol,{children:[e.jsxs(zl,{children:[e.jsx(Ul,{children:"Permanently delete this portal?"}),e.jsx(ql,{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($l,{children:"Cancel"}),e.jsx(Ml,{onClick:O,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete Permanently"})]})]})})]})}function rer({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(rn,{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(In,{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(uo,{className:"h-4 w-4"})}),o]})]}),t.length>0&&e.jsx("div",{className:"-mx-1 flex gap-2 overflow-x-auto px-1 pb-1 sm:grid sm:grid-cols-3 sm:overflow-visible lg:grid-cols-5",children:t.map(p=>{const f=p.onClick?"button":"div";return e.jsxs(f,{type:p.onClick?"button":void 0,onClick:p.onClick,title:p.hint,className:At("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(Lr,{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(Qn,{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(Qn,{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 aer={closing_soon:{label:"Closing in 7 days",icon:Qd,tone:"text-primary"},past_due:{label:"Past close date",icon:xl,tone:"text-destructive"},overdue_tasks:{label:"Overdue tasks",icon:Ww,tone:"text-amber-600 dark:text-amber-400"},stalled:{label:"Stalled 14+ days",icon:RQ,tone:"text-muted-foreground"}};function ier({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=aer[a],o=l.icon,c=t===a;return e.jsxs("button",{onClick:()=>n(a),className:At("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:At("h-3.5 w-3.5",!c&&l.tone)}),l.label,e.jsx("span",{className:At("ml-0.5 rounded-full px-1.5 text-[10px] font-bold",c?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground"),children:i})]},a)})]})}const R7=s=>{const t=Number(s);return Number.isFinite(t)?t:0};function WS(s){if(!s)return null;const[t,n,r]=s.split(/[-/T]/).map(a=>parseInt(a,10));return!t||!n||!r?null:{y:t,m:n,d:r}}function RG(s){return R7(s.sale_price)||R7(s.expected_price)}function FG(s){const t=R7(s.expected_commission);if(t>0)return t;const n=R7(s.commission_percentage);return n>0?RG(s)*n/100:0}function zse(s){const t=FG(s);return t*R7(s.brokerage_split_pct)/100+t*R7(s.franchise_fee_pct)/100+R7(s.transaction_fee)}const oer=s=>!!s.actual_close_date,ler=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function cer(s){const t=new Date,n=t.getFullYear(),r=t.getMonth()+1,a=n*1e4+r*100+t.getDate(),i=new Date(t.getTime()+30*864e5),l=i.getFullYear()*1e4+(i.getMonth()+1)*100+i.getDate(),o={activeDeals:0,closedThisYear:0,pipelineVolume:0,pipelineGci:0,brokerageShare:0,closingThisMonth:0,closingNext30:0,closedVolumeThisYear:0,closedCompanyDollarYtd:0,needsReview:0,changesRequested:0,overdueItems:0,agents:[],outlook:[],totalVolume:0},c=new Map,d=new Map;for(let u=0;u<6;u++){const h=(r-1+u)%12+1,m=n+Math.floor((r-1+u)/12),p=`${m}-${String(h).padStart(2,"0")}`;d.set(p,{key:p,label:`${ler[h-1]} ${String(m).slice(2)}`,deals:0,volume:0,gci:0,closed:!1})}return s.forEach(u=>{const h=RG(u),m=FG(u),p=oer(u);o.totalVolume+=h,o.overdueItems+=u.overdue_items,u.submitted_items>0&&(o.needsReview+=1),u.rejected_items>0&&(o.changesRequested+=1);const f=WS(u.actual_close_date||u.target_close_date);if(p)(f==null?void 0:f.y)===n&&(o.closedThisYear+=1,o.closedVolumeThisYear+=h,o.closedCompanyDollarYtd+=zse(u));else if(o.activeDeals+=1,o.pipelineVolume+=h,o.pipelineGci+=m,o.brokerageShare+=zse(u),f){const v=f.y*1e4+f.m*100+f.d;f.y===n&&f.m===r&&(o.closingThisMonth+=1),v>=a&&v<=l&&(o.closingNext30+=1)}if(f){const v=`${f.y}-${String(f.m).padStart(2,"0")}`,g=d.get(v);g&&(g.deals+=1,g.volume+=h,g.gci+=m,p&&(g.closed=!0))}const y=c.get(u.owner_user_id)||{userId:u.owner_user_id,name:u.agent_name||"Agent",avatarUrl:u.agent_avatar_url,activeDeals:0,closedDeals:0,volume:0,gci:0,overdue:0};p?y.closedDeals+=1:y.activeDeals+=1,y.volume+=h,y.gci+=m,y.overdue+=u.overdue_items,c.set(u.owner_user_id,y)}),o.agents=Array.from(c.values()).sort((u,h)=>h.volume-u.volume||h.activeDeals-u.activeDeals),o.outlook=Array.from(d.values()).sort((u,h)=>u.key.localeCompare(h.key)),o}function Xm(s){return s?Math.abs(s)>=1e6?`$${(s/1e6).toFixed(1)}M`:Math.abs(s)>=1e3?`$${Math.round(s/1e3)}K`:`$${Math.round(s).toLocaleString()}`:"$0"}function der(){var i;const{user:s}=hs(),{data:t}=tss(),{data:n}=kWn(t?s==null?void 0:s.id:null);if(!t)return null;const{plan:r}=t,a=Math.max(0,100-r.agent_split_pct);return e.jsx(ve,{className:"border-border/60",children:e.jsxs(Me,{className:"flex flex-col gap-3 p-4 sm:flex-row sm:items-center sm:gap-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-teal-500/10 text-teal-600",children:e.jsx(F_,{className:"h-4.5 w-4.5"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Your commission plan"}),e.jsx("p",{className:"text-sm font-semibold",children:r.name})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1 text-[12px] text-muted-foreground",children:[e.jsxs("span",{children:[e.jsxs("span",{className:"font-medium text-foreground",children:[r.agent_split_pct,"/",a]})," split"]}),r.transaction_fee>0&&e.jsxs("span",{children:[e.jsxs("span",{className:"font-medium text-foreground",children:["$",r.transaction_fee.toLocaleString()]})," per deal"]}),r.franchise_fee_pct>0&&e.jsxs("span",{children:[e.jsxs("span",{className:"font-medium text-foreground",children:[r.franchise_fee_pct,"%"]})," franchise fee"]}),(r.team_split_pct??0)>0&&e.jsxs("span",{children:[e.jsxs("span",{className:"font-medium text-foreground",children:[r.team_split_pct,"%"]})," team split"]})]}),r.cap_amount&&n&&e.jsxs("div",{className:"min-w-[200px] flex-1",children:[e.jsxs("div",{className:"mb-1 flex justify-between text-[11px] text-muted-foreground",children:[e.jsxs("span",{children:["$",Math.round(n.cap_progress).toLocaleString()," of ",Xm(r.cap_amount)," cap"]}),e.jsxs("span",{children:[Math.round(n.pct_to_cap??0),"%"]})]}),e.jsx(Fi,{value:Math.min(100,n.pct_to_cap??0),className:"h-1.5"}),e.jsxs("p",{className:"mt-1 text-[11px] text-muted-foreground",children:["Resets ",((i=n.anniversary_year_end)==null?void 0:i.split(/[-/T]/).slice(0,3).join("/"))||"annually"]})]})]})})}class uer extends _.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(zs,{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 LZ="deal-pipeline-detail-sheet";function IZ(s){return s>=1e6?`$${(s/1e6).toFixed(1)}M`:s>=1e3?`$${(s/1e3).toFixed(0)}K`:`$${Math.round(s).toLocaleString()}`}function her(){var Fa;const s=$W(),{data:t,isLoading:n}=eie(),{data:r,isLoading:a,refetch:i}=lK(),{data:l,isLoading:o}=LGn(),c=Wts(),d=SGn(),[u,h]=_.useState("board"),[m,p]=_.useState(!1),[f,y]=_.useState(!1),[v,g]=_.useState(null),[b,j]=_.useState(null),[S,C]=_.useState(null),[E,P]=_.useState(null),[M,I]=_.useState(!1),[D,O]=_.useState(null),[V,G]=_.useState(""),[$,H]=_.useState("all"),[Y,Z]=_.useState("all"),[ne,ce]=_.useState("all"),[ie,te]=_.useState(null),{data:ae}=rrs(),{data:le}=vWn(),[be,me]=_.useState(!1),[he,pe]=_.useState(!1),[Ce,Ae]=_.useState(new Set),[Pe,ze]=_.useState(!0),ke=_.useRef(!1),[Ze,Se]=_.useState(null),{data:Fe}=G_(),{isTeamLeader:Ne,teamMembers:Ye}=gWn(),Ve=_.useMemo(()=>Array.from(Ce),[Ce]),{data:qe}=yWn(Ve),Qe=_.useMemo(()=>{const ks=new Map;return Ye.forEach(Gs=>ks.set(Gs.id,{name:Gs.name,avatar_url:Gs.avatar_url,color:Gs.color})),ks},[Ye]),Ue=_.useCallback(ks=>ks.owner_user_id&&Qe.get(ks.owner_user_id)||null,[Qe]),Xe=_.useCallback(ks=>{Ae(Gs=>{const Ws=new Set(Gs);return Ws.has(ks)?Ws.delete(ks):Ws.add(ks),Ws})},[]);_.useEffect(()=>{!n&&t&&t.length===0&&c.mutate()},[n,t]);const[nt,$e]=Yl(),Ge=_.useRef(!1);_.useEffect(()=>{const ks=nt.get("deal");if(ks&&r&&r.length>0&&!Ge.current){const Gs=r.find(Ws=>Ws.id===ks);Gs&&(Ge.current=!0,g(Gs),y(!0),nt.delete("deal"),$e(nt,{replace:!0}))}},[r,nt]);const ct=_.useMemo(()=>{if(!qe||!t)return[];const ks=new Map(t.map(Gs=>[Gs.name,Gs.id]));return qe.map(Gs=>{const Ws=Gs._stage_name&&ks.get(Gs._stage_name)||null;return{...Gs,stage_id:Ws||Gs.stage_id}})},[qe,t]),xt=_.useMemo(()=>[...Ne&&!Pe?[]:r||[],...ct],[r,ct,Ne,Pe]);_.useEffect(()=>{if(ke.current||xt.length===0)return;ke.current=!0;const ks=sessionStorage.getItem(LZ);if(ks)try{const Gs=JSON.parse(ks);if(!Gs.open||!Gs.dealId)return;const Ws=xt.find(Ys=>Ys.id===Gs.dealId);Ws&&(g(Ws),y(!0))}catch{sessionStorage.removeItem(LZ)}},[xt]),_.useEffect(()=>{f&&(v!=null&&v.id)?sessionStorage.setItem(LZ,JSON.stringify({dealId:v.id,open:!0})):sessionStorage.removeItem(LZ)},[f,v==null?void 0:v.id]);const qt=_.useMemo(()=>{const ks={},Gs=new Date;return Gs.setHours(0,0,0,0),(ae||[]).forEach(Ws=>{!Ws.deal_id||Ws.status==="done"||!Ws.due_date||Ru(Ws.due_date){const ks=new Set((t||[]).filter(Wt=>Wt.is_won_stage).map(Wt=>Wt.id)),Gs=new Set((t||[]).filter(Wt=>Wt.is_lost_stage).map(Wt=>Wt.id)),Ws=new Date;Ws.setHours(0,0,0,0);const Ys=new Date(Ws);Ys.setDate(Ys.getDate()+7);const Bn=new Date(Ws);Bn.setDate(Bn.getDate()-14);const or={closing_soon:new Set,past_due:new Set,overdue_tasks:new Set,stalled:new Set};return xt.forEach(Wt=>{if(!(Wt.stage_id&&(ks.has(Wt.stage_id)||Gs.has(Wt.stage_id)))){if(Wt.target_close_date){const pt=Ru(Wt.target_close_date);pt[{key:"closing_soon",count:fs.closing_soon.size},{key:"past_due",count:fs.past_due.size},{key:"overdue_tasks",count:fs.overdue_tasks.size},{key:"stalled",count:fs.stalled.size}],[fs]),wt=xt.filter(ks=>{var Mt,es,ps,Is,js,Kt;const Gs=V.toLowerCase(),Ws=Vt[ks.id]||[],Ys=!Gs||ks.deal_name.toLowerCase().includes(Gs)||((es=(Mt=ks.contact)==null?void 0:Mt.first_name)==null?void 0:es.toLowerCase().includes(Gs))||((Is=(ps=ks.contact)==null?void 0:ps.last_name)==null?void 0:Is.toLowerCase().includes(Gs))||((js=ks.property_address)==null?void 0:js.toLowerCase().includes(Gs))||((Kt=ks.city)==null?void 0:Kt.toLowerCase().includes(Gs))||Ws.some(Qs=>Qs.toLowerCase().includes(Gs)),Bn=$==="all"||ks.deal_type===$,or=Y==="all"||Ws.includes(Y),Wt=ks.actual_close_date||ks.target_close_date||ks.contract_date||ks.created_at,rt=Wt?String(Wt).slice(0,4):null,pt=ne==="all"||rt===ne,jt=!ie||fs[ie].has(ks.id);return Ys&&Bn&&or&&pt&&jt}),Ts=_.useMemo(()=>{const ks=new Set;return ks.add(String(new Date().getFullYear())),xt.forEach(Gs=>{const Ws=Gs.actual_close_date||Gs.target_close_date||Gs.contract_date||Gs.created_at;Ws&&ks.add(String(Ws).slice(0,4))}),Array.from(ks).sort((Gs,Ws)=>Number(Ws)-Number(Gs))},[xt]),vt=_.useMemo(()=>{if(!t)return l||null;const ks=new Set(t.filter(Wt=>Wt.is_won_stage).map(Wt=>Wt.id)),Gs=new Set(t.filter(Wt=>Wt.is_lost_stage).map(Wt=>Wt.id)),Ws=xt.filter(Wt=>Wt.stage_id&&!ks.has(Wt.stage_id)&&!Gs.has(Wt.stage_id)),Ys=xt.filter(Wt=>Wt.stage_id&&ks.has(Wt.stage_id)),Bn=new Date().getFullYear(),or=Ys.filter(Wt=>Wt.actual_close_date?new Date(Wt.actual_close_date).getFullYear()===Bn:!0);return{totalDeals:xt.length,activeDeals:Ws.length,wonDeals:Ys.length,pipelineValue:Ws.reduce((Wt,rt)=>Wt+(rt.expected_price||0),0),expectedCommission:Ws.reduce((Wt,rt)=>Wt+(rt.expected_commission||0),0),expectedNetToAgent:Ws.reduce((Wt,rt)=>Wt+(j_(rt)||0),0),wonValue:Ys.reduce((Wt,rt)=>Wt+(rt.expected_price||0),0),weightedGCI:Ws.reduce((Wt,rt)=>Wt+(rt.expected_commission||0)*((rt.probability??50)/100),0),weightedNet:Ws.reduce((Wt,rt)=>Wt+(j_(rt)||0)*((rt.probability??50)/100),0),ytdWonDeals:or.length,ytdWonGCI:or.reduce((Wt,rt)=>Wt+(rt.expected_commission||0),0),ytdWonNet:or.reduce((Wt,rt)=>Wt+(j_(rt)||0),0),projectedAnnualNet:or.reduce((Wt,rt)=>Wt+(j_(rt)||0),0)+Ws.reduce((Wt,rt)=>Wt+(j_(rt)||0)*((rt.probability??50)/100),0)}},[xt,t,l]),$s=ks=>{g(ks),y(!0)},As=ks=>{j(ks||null),g(null),p(!0)},jn=ks=>{g(ks),y(!1),p(!0)},ar=ks=>{y(ks),ks||sessionStorage.removeItem(LZ)},Dn=(ks,Gs)=>{C(ks)},Ur=(ks,Gs)=>{ks.preventDefault(),ks.dataTransfer.dropEffect="move",P(Gs)},Vs=async(ks,Gs)=>{if(ks.preventDefault(),P(null),!S)return;const Ws=r==null?void 0:r.find(or=>or.id===S),Ys=t==null?void 0:t.find(or=>or.id===Gs),Bn=t==null?void 0:t.find(or=>or.id===(Ws==null?void 0:Ws.stage_id));if(!Ws||!Ys||Ws.stage_id===Gs){C(null);return}Se({dealId:S,dealName:Ws.deal_name,fromStageName:(Bn==null?void 0:Bn.name)||"Unknown",toStageName:Ys.name,toStageId:Gs,isWonStage:Ys.is_won_stage,deal:Ws}),C(null)},hn=async()=>{if(!Ze)return;const{dealId:ks,toStageId:Gs,toStageName:Ws,isWonStage:Ys,deal:Bn}=Ze;if(await d.mutateAsync({dealId:ks,stageId:Gs,stageName:Ws}),se.success(`Moved to ${Ws}`),Ys&&!Bn.scorecard_transaction_id){const or={...Bn,stage_id:Gs};O(or),I(!0)}},dr=_.useCallback(async(ks,Gs,Ws)=>{const Ys=r==null?void 0:r.find(Wt=>Wt.id===ks),Bn=t==null?void 0:t.find(Wt=>Wt.id===Gs),or=t==null?void 0:t.find(Wt=>Wt.id===(Ys==null?void 0:Ys.stage_id));!Ys||!Bn||Ys.stage_id===Gs||Se({dealId:ks,dealName:Ys.deal_name,fromStageName:(or==null?void 0:or.name)||"Unknown",toStageName:Ws,toStageId:Gs,isWonStage:Bn.is_won_stage,deal:Ys})},[r,t]),Cn=ks=>wt.filter(Gs=>Gs.stage_id===ks),Yn=n||a,on=s?"list":u,Ir=[{label:"Active Deals",value:(vt==null?void 0:vt.activeDeals)||0,hint:"Deals still in play"},{label:"Weighted GCI",value:IZ((vt==null?void 0:vt.weightedGCI)||0),hint:"GCI adjusted by each deal's win probability"},{label:"Weighted Net",value:IZ((vt==null?void 0:vt.weightedNet)||0),hint:"Net to agent adjusted by each deal's win probability"},{label:"YTD Closed Net",value:IZ((vt==null?void 0:vt.ytdWonNet)||0),subtitle:`${(vt==null?void 0:vt.ytdWonDeals)||0} deals`,hint:"Net commission from deals closed this year"},{label:"Projected Annual",value:IZ((vt==null?void 0:vt.projectedAnnualNet)||0),hint:"YTD closed net + weighted active net"}],Wn=[...$!=="all"?[{key:"type",label:`Type: ${$}`,onClear:()=>H("all")}]:[],...ne!=="all"?[{key:"year",label:`Year: ${ne}`,onClear:()=>ce("all")}]:[],...Y!=="all"?[{key:"tag",label:`Tag: ${Y}`,onClear:()=>Z("all")}]:[],...V?[{key:"search",label:`"${V}"`,onClear:()=>G("")}]:[],...ie?[{key:"attention",label:"Needs attention",onClear:()=>te(null)}]:[]],Js=()=>{G(""),H("all"),Z("all"),ce("all"),te(null)};return e.jsxs(zs,{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(rer,{summary:`${(vt==null?void 0:vt.activeDeals)||0} active deals • ${IZ((vt==null?void 0:vt.weightedNet)||0)} weighted net`,stats:on==="portals"?[]:Ir,search:V,onSearchChange:G,onAddDeal:()=>As(),onRefresh:()=>i(),onTeam:Fe&&!Ne?()=>me(!0):void 0,showSearch:on!=="portals",activeFilters:Wn,onClearAll:Js,resultLabel:Wn.length>0?`${wt.length} of ${xt.length} deals`:null,viewControls:s?null:e.jsx(FN,{children:e.jsx("div",{className:"hub-glass flex items-center gap-0.5 rounded-full p-1",children:[{mode:"board",icon:sf,label:"Board",hint:"Kanban board view"},{mode:"list",icon:A0,label:"List",hint:"Grouped list view"},{mode:"table",icon:a$,label:"Table",hint:"Sortable table view"},{mode:"portals",icon:un,label:"Portals",hint:"Client portal management"}].map(({mode:ks,icon:Gs,label:Ws,hint:Ys})=>e.jsxs(ag,{children:[e.jsx(ig,{asChild:!0,children:e.jsxs("button",{onClick:()=>h(ks),className:At("inline-flex items-center gap-1.5 rounded-full px-3 py-1.5 text-xs font-medium transition-colors",u===ks?"bg-background text-foreground shadow-sm":"opacity-80 hover:opacity-100"),children:[e.jsx(Gs,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:Ws})]})}),e.jsx(Nx,{children:Ys})]},ks))})}),filters:on!=="portals"?e.jsxs(e.Fragment,{children:[e.jsxs(is,{value:$,onValueChange:H,children:[e.jsx(rs,{className:"hub-glass h-10 w-[130px] rounded-full border-0 text-sm",children:e.jsx(ls,{placeholder:"All Types"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Types"}),e.jsx(He,{value:"buyer",children:"Buyer"}),e.jsx(He,{value:"seller",children:"Seller"}),e.jsx(He,{value:"dual",children:"Dual"}),e.jsx(He,{value:"referral",children:"Referral"}),e.jsx(He,{value:"lease",children:"Lease"})]})]}),e.jsxs(is,{value:ne,onValueChange:ce,children:[e.jsx(rs,{className:"hub-glass h-10 w-[110px] rounded-full border-0 text-sm",children:e.jsx(ls,{placeholder:"Year"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Years"}),Ts.map(ks=>e.jsx(He,{value:ks,children:ks},ks))]})]}),e.jsxs(is,{value:Y,onValueChange:Z,children:[e.jsxs(rs,{className:"hub-glass h-10 w-[150px] rounded-full border-0 text-sm",children:[e.jsx(Ep,{className:"mr-1.5 h-3.5 w-3.5 opacity-70"}),e.jsx(ls,{placeholder:"All Tags"})]}),e.jsxs(as,{className:"max-h-[300px]",children:[e.jsx(He,{value:"all",children:"All Tags"}),Xt.length===0&&e.jsx("div",{className:"px-2 py-1.5 text-xs text-muted-foreground",children:"No tags yet"}),Xt.map(ks=>e.jsx(He,{value:ks,children:ks},ks))]})]})]}):null}),e.jsx(der,{}),on!=="portals"&&e.jsx(ier,{items:Ft,active:ie,onToggle:ks=>te(Gs=>Gs===ks?null:ks)})]}),e.jsxs("div",{className:"flex-1 min-h-0 flex",children:[Ne&&!s&&Ye.length>0&&e.jsx(xWn,{members:Ye,enabledMembers:Ce,onToggleMember:Xe,isOpen:he,onToggleOpen:()=>pe(ks=>!ks),showOwnDeals:Pe,onToggleOwnDeals:()=>ze(ks=>!ks)}),e.jsx("div",{className:"flex-1 min-w-0 min-h-0 p-4 md:p-6 pt-4",children:Yn?e.jsx("div",{className:"flex gap-4 h-full",children:[1,2,3,4].map(ks=>e.jsx("div",{className:"min-w-[280px] max-w-[320px] flex-shrink-0",children:e.jsx(cn,{className:"h-full rounded-xl"})},ks))}):on==="board"?e.jsxs(Ji,{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(ks=>e.jsx(wWn,{stage:ks,deals:Cn(ks.id),onDealClick:$s,onAddDeal:As,onDragStart:Dn,onDragOver:Ur,onDrop:Vs,isDragOver:E===ks.id,isWonStage:ks.is_won_stage,isLostStage:ks.is_lost_stage,getOwnerInfo:Ue,tagsByDeal:Vt,overdueTasksByDeal:qt},ks.id))}),e.jsx(Bre,{orientation:"horizontal"})]}):on==="table"?e.jsx(Ji,{className:"h-full",children:e.jsx(UJn,{deals:wt,stages:t||[],onDealClick:$s,onStageChange:dr})}):on==="portals"?e.jsx(irs,{}):e.jsx(Ji,{className:"h-full",children:e.jsxs("div",{className:"space-y-6",children:[t==null?void 0:t.map(ks=>{const Gs=Cn(ks.id);return Gs.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:ks.color}}),e.jsx("h3",{className:"font-semibold",children:ks.name}),e.jsxs("span",{className:"text-muted-foreground text-sm",children:["(",Gs.length,")"]})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3",children:Gs.map(Ws=>e.jsx(ess,{deal:Ws,onClick:()=>$s(Ws),stages:t,onStageChange:dr,showStagePicker:!0,isWonStage:ks.is_won_stage,isLostStage:ks.is_lost_stage,ownerInfo:Ue(Ws),tags:Vt[Ws.id]||[],overdueTaskCount:qt[Ws.id]||0},Ws.id))})]},ks.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(sf,{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(B,{onClick:()=>As(),children:[e.jsx(rn,{className:"h-4 w-4 mr-2"}),"Add Your First Deal"]})]}),((r==null?void 0:r.length)||0)>0&&wt.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(Lr,{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(B,{variant:"outline",onClick:Js,children:"Clear Filters"})]})]})})})]})]}),e.jsx(PWn,{open:m,onOpenChange:p,deal:v,defaultStageId:b}),e.jsx(OJn,{deal:v,open:f,onOpenChange:ar,onEdit:jn,isWonStage:v?(Fa=t==null?void 0:t.find(ks=>ks.id===v.stage_id))==null?void 0:Fa.is_won_stage:!1,onAddToScorecard:ks=>{O(ks),I(!0),y(!1)}}),e.jsx(zJn,{open:M,onOpenChange:I,deal:D,onComplete:()=>{i(),O(null)}}),Ze&&e.jsx(QJn,{open:!!Ze,onOpenChange:ks=>{ks||Se(null)},dealId:Ze.dealId,dealName:Ze.dealName,fromStageName:Ze.fromStageName,toStageName:Ze.toStageName,toStageId:Ze.toStageId,onConfirm:hn}),e.jsx(pWn,{open:be,onOpenChange:me})]})}function mer(){return e.jsx(uer,{children:e.jsx(her,{})})}function w6e({open:s,onOpenChange:t,templateId:n,templateName:r,brokerageId:a,onUploaded:i}){const l=!!n,o=_.useRef(null),[c,d]=_.useState(null),[u,h]=_.useState(""),[m,p]=_.useState(""),[f,y]=_.useState("other"),[v,g]=_.useState(!1),b=$Qn(),j=()=>{d(null),h(""),p(""),y("other"),g(!1),o.current&&(o.current.value="")},S=E=>{if(E){if(E.type!=="application/pdf"&&!E.name.toLowerCase().endsWith(".pdf")){se.error("Only PDF files can be uploaded.");return}if(E.size>Kns){se.error("That PDF is larger than the 20MB limit.");return}d(E),!u&&!l&&h(E.name.replace(/\.pdf$/i,""))}},C=async()=>{if(c)try{const E=await b.mutateAsync({name:u.trim()||c.name.replace(/\.pdf$/i,""),description:m,category:f,file:c,templateId:n,brokerageId:a});se.success(E.version.has_acroform?`Found ${E.version.detected_fields.length} fillable fields — map them next.`:"Uploaded. This PDF has no fillable fields yet."),i==null||i(E.templateId,E.version.id),j(),t(!1)}catch(E){se.error((E==null?void 0:E.message)||"Upload failed")}};return e.jsx(Ls,{open:s,onOpenChange:E=>{E||j(),t(E)},children:e.jsxs(Ps,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:l?`New version of ${r}`:"Upload a form template"}),e.jsxs(_r,{children:["PDF only, up to 20MB."," ",a?"Brokerage templates stay in draft until you publish them to your agents.":"Templates stay private to your account."]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("input",{ref:o,type:"file",accept:"application/pdf,.pdf",className:"hidden",onChange:E=>{var P;return S((P=E.target.files)==null?void 0:P[0])}}),e.jsx("button",{type:"button",onClick:()=>{var E;return(E=o.current)==null?void 0:E.click()},className:"w-full rounded-lg border border-dashed p-6 text-center transition-colors hover:bg-muted/50",children:c?e.jsxs("div",{className:"flex items-center justify-center gap-3",children:[e.jsx(Fr,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"text-sm font-medium",children:c.name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Oat(c.size)})]})]}):e.jsxs("div",{className:"flex flex-col items-center gap-2 text-muted-foreground",children:[e.jsx(Oa,{className:"h-6 w-6"}),e.jsx("span",{className:"text-sm",children:"Choose a blank PDF form"})]})}),!l&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"tpl-name",children:"Template name"}),e.jsx(xe,{id:"tpl-name",value:u,onChange:E=>h(E.target.value),placeholder:"Residential Purchase Agreement"})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx(J,{children:"Category"}),e.jsxs(is,{value:f,onValueChange:E=>y(E),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsx(as,{children:Rat.map(E=>e.jsx(He,{value:E.value,children:E.label},E.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"tpl-desc",children:"Description (optional)"}),e.jsx(Ms,{id:"tpl-desc",rows:2,value:m,onChange:E=>p(E.target.value)})]})]}),e.jsxs("label",{className:"flex items-start gap-3 rounded-lg bg-muted/50 p-3 text-xs text-muted-foreground",children:[e.jsx($a,{checked:v,onCheckedChange:E=>g(!!E),className:"mt-0.5"}),e.jsx("span",{children:"I confirm I am legally permitted to use and store this form. LevelUp does not provide or license association forms."})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{onClick:C,disabled:!c||!v||b.isPending,children:[b.isPending&&e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}),b.isPending?"Reading PDF…":"Upload"]})]})]})})}function HYe(s){return s.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[^a-zA-Z0-9]+/g," ").toLowerCase().trim()}function i4t(s){return HYe(s).split(" ").filter(Boolean)}function per(s,t,n){const r=HYe(s),a=new Set(i4t(s));let i=0;const l=[t,...n];for(const o of l){const c=HYe(o);if(!c)continue;if(r===c){i=Math.max(i,100);continue}if(r.includes(c)){i=Math.max(i,60+Math.min(c.length,30));continue}const d=i4t(o),u=d.filter(h=>a.has(h)).length;u>0&&(i=Math.max(i,Math.round(u/d.length*45)))}return i}function fer(s){if(!s)return null;let t=null;for(const n of DG){const r=per(s,n.label,n.aliases);r>0&&(!t||r>t.confidence)&&(t={mergeKey:n.key,confidence:r})}return!t||t.confidence<35?null:t}const xer=["Deal","Contact","Agent","Other"],bBe="__blank__",_Be="__static__";function ors({version:s}){const{data:t,isLoading:n}=hie(s.id),r=XQn(),[a,i]=_.useState([]),[l,o]=_.useState("");_.useEffect(()=>{if(n)return;const p=new Map((t||[]).map(f=>[f.pdf_field_name||"",f]));i((s.detected_fields||[]).map(f=>{const y=p.get(f.name),v=fer(f.name);return{pdf_field_name:f.name,mapping_mode:(y==null?void 0:y.mapping_mode)||"acroform",merge_key:(y==null?void 0:y.merge_key)??null,static_value:(y==null?void 0:y.static_value)??null,suggested:(v==null?void 0:v.mergeKey)??null}}))},[t,n,s.id,s.detected_fields]);const c=_.useMemo(()=>{if(!l.trim())return a;const p=l.toLowerCase();return a.filter(f=>(f.pdf_field_name||"").toLowerCase().includes(p))},[a,l]),d=a.filter(p=>p.merge_key||p.mapping_mode==="static"&&p.static_value).length,u=(p,f)=>{i(y=>y.map(v=>v.pdf_field_name===p?{...v,...f}:v))},h=()=>{let p=0;i(f=>f.map(y=>y.merge_key||!y.suggested?y:(p+=1,{...y,mapping_mode:"acroform",merge_key:y.suggested}))),se.success(p?`Applied ${p} suggestion${p===1?"":"s"}`:"No new suggestions to apply")},m=async()=>{try{await r.mutateAsync({versionId:s.id,hasAcroform:s.has_acroform,mappings:a.map(({suggested:p,...f})=>f)}),se.success("Field mapping saved")}catch(p){se.error((p==null?void 0:p.message)||"Could not save the mapping")}};return s.has_acroform?n?e.jsx("div",{className:"flex justify-center py-10",children:e.jsx(Ct,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:[d," of ",a.length," fields mapped"]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:h,children:[e.jsx(un,{className:"mr-1.5 h-4 w-4"})," Apply suggestions"]}),e.jsxs(B,{size:"sm",onClick:m,disabled:r.isPending,children:[r.isPending?e.jsx(Ct,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(Ho,{className:"mr-1.5 h-4 w-4"}),"Save mapping"]})]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Lr,{className:"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(xe,{className:"pl-9",placeholder:"Search fields…",value:l,onChange:p=>o(p.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[c.map(p=>{var y;const f=p.mapping_mode==="static"?_Be:p.merge_key?p.merge_key:bBe;return e.jsxs("div",{className:"flex flex-col gap-2 rounded-lg border bg-background p-3 sm:flex-row sm:items-center",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:p.pdf_field_name}),p.suggested&&!p.merge_key&&e.jsxs(Oe,{variant:"secondary",className:"mt-1 text-[10px]",children:["Suggested: ",(y=DG.find(v=>v.key===p.suggested))==null?void 0:y.label]})]}),e.jsxs("div",{className:"flex w-full gap-2 sm:w-[420px]",children:[e.jsxs(is,{value:f,onValueChange:v=>{v===bBe?u(p.pdf_field_name,{mapping_mode:"blank",merge_key:null,static_value:null}):v===_Be?u(p.pdf_field_name,{mapping_mode:"static",merge_key:null}):u(p.pdf_field_name,{mapping_mode:"acroform",merge_key:v,static_value:null})},children:[e.jsx(rs,{className:"flex-1",children:e.jsx(ls,{placeholder:"Leave blank"})}),e.jsxs(as,{className:"max-h-[320px]",children:[e.jsx(He,{value:bBe,children:"Leave blank"}),e.jsx(He,{value:_Be,children:"Fixed text…"}),xer.map(v=>e.jsxs(ICs,{children:[e.jsx(WDt,{children:v}),DG.filter(g=>g.group===v).map(g=>e.jsx(He,{value:g.key,children:g.label},g.key))]},v))]})]}),p.mapping_mode==="static"&&e.jsx(xe,{className:"flex-1",placeholder:"Fixed text",value:p.static_value||"",onChange:v=>u(p.pdf_field_name,{static_value:v.target.value})})]})]},p.pdf_field_name)}),c.length===0&&e.jsx("p",{className:"py-8 text-center text-sm text-muted-foreground",children:"No fields match that search."})]})]}):e.jsx(ve,{children:e.jsxs(Me,{className:"p-6 text-center space-y-2",children:[e.jsx("p",{className:"font-medium",children:"Needs field placement"}),e.jsx("p",{className:"text-sm text-muted-foreground max-w-md mx-auto",children:"This PDF has no fillable form fields, so there is nothing to map yet. Visual field placement for flat PDFs is coming next — for now, upload a fillable (AcroForm) version of this form to use it from a deal."})]})})}Jrt.workerSrc=eat;const YCe={data:{w:.24,h:.028,label:"Data field"},signature:{w:.28,h:.055,label:"Signature"},initials:{w:.1,h:.035,label:"Initials"},date_signed:{w:.14,h:.028,label:"Date signed"},printed_name:{w:.24,h:.03,label:"Printed name"},text:{w:.24,h:.03,label:"Text input"}},wBe=["signature","initials","date_signed","printed_name","text"],o4t=12,ger={buyer_1:"border-emerald-500 bg-emerald-500/15 text-emerald-700",buyer_2:"border-emerald-500 bg-emerald-500/15 text-emerald-700",seller_1:"border-sky-500 bg-sky-500/15 text-sky-700",seller_2:"border-sky-500 bg-sky-500/15 text-sky-700",agent:"border-amber-500 bg-amber-500/15 text-amber-700"},Pde=s=>Math.min(1,Math.max(0,s));function lrs({version:s,templateName:t,open:n,onOpenChange:r}){const a=Bt(),{data:i=[],isLoading:l}=hie(n?s.id:void 0),[o,c]=_.useState(null),[d,u]=_.useState(null),[h,m]=_.useState([]),[p,f]=_.useState("select"),[y,v]=_.useState(null),[g,b]=_.useState(!1),[j,S]=_.useState(!1),C=_.useRef(null),E=_.useRef([]),P=_.useRef(null),M=Math.min(s.page_count||1,o4t);_.useEffect(()=>{if(!n)return;let Z=!1;return c(null),u(null),J8e(s.storage_path).then(ne=>{Z||c(new Blob([ne],{type:"application/pdf"}))}).catch(()=>!Z&&u("Could not load the template PDF.")),()=>{Z=!0}},[n,s.storage_path]),_.useEffect(()=>{let Z=!1;const ne=C.current;return!o||!ne?void 0:((async()=>{try{const ie=await o.arrayBuffer(),te=await a6e({data:ie}).promise;if(Z)return;ne.innerHTML="",E.current=[];const ae=Math.min(ne.clientWidth-32||720,860);for(let le=1;le<=te.numPages;le++){const be=await te.getPage(le);if(Z)return;const me=be.getViewport({scale:1}),he=ae/me.width,pe=be.getViewport({scale:he*(window.devicePixelRatio||1)}),Ce=document.createElement("div");Ce.className="relative mx-auto shadow-sm",Ce.style.width=`${ae}px`,Ce.style.height=`${me.height*he}px`,Ce.dataset.pageIndex=String(le-1);const Ae=document.createElement("canvas");Ae.width=Math.floor(pe.width),Ae.height=Math.floor(pe.height),Ae.style.width="100%",Ae.style.height="100%",Ae.className="rounded-md border border-border bg-white",Ce.appendChild(Ae),ne.appendChild(Ce),E.current[le-1]=Ce;const Pe=Ae.getContext("2d");Pe&&await be.render({canvasContext:Pe,viewport:pe}).promise}Z||m(le=>[...le])}catch(ie){Z||u((ie==null?void 0:ie.message)||"Could not render the PDF")}})(),()=>{Z=!0})},[o]),_.useEffect(()=>{if(!n||l)return;const Z=i.filter(ne=>ne.field_kind!=="data"||ne.mapping_mode==="overlay").filter(ne=>ne.pos_x!=null&&ne.pos_y!=null).map(ne=>({key:ne.id,page_index:ne.page_index??0,x:Number(ne.pos_x),y:Number(ne.pos_y),w:Number(ne.width??.2),h:Number(ne.height??.03),field_kind:ne.field_kind||"data",merge_key:ne.merge_key,static_value:ne.static_value,signer_role:ne.signer_role,label:ne.label,is_required:ne.is_required??!0,font_size:ne.font_size,source:ne.source||"manual"}));m(Z),v(null)},[n,l,i]),_.useEffect(()=>{const Z=ce=>{const ie=P.current;if(!ie)return;const te=(ce.clientX-ie.startX)/ie.pageW,ae=(ce.clientY-ie.startY)/ie.pageH;m(le=>le.map(be=>be.key!==ie.key?be:ie.mode==="move"?{...be,x:Pde(Math.min(ie.orig.x+te,1-be.w)),y:Pde(Math.min(ie.orig.y+ae,1-be.h))}:{...be,w:Math.min(Math.max(.04,ie.orig.w+te),1-be.x),h:Math.min(Math.max(.015,ie.orig.h+ae),1-be.y)}))},ne=()=>{P.current=null};return window.addEventListener("pointermove",Z),window.addEventListener("pointerup",ne),()=>{window.removeEventListener("pointermove",Z),window.removeEventListener("pointerup",ne)}},[]);const I=(Z,ne,ce)=>{Z.stopPropagation(),Z.preventDefault();const ie=E.current[ne.page_index];if(!ie)return;const te=ie.getBoundingClientRect();P.current={key:ne.key,mode:ce,startX:Z.clientX,startY:Z.clientY,orig:ne,pageW:te.width,pageH:te.height},v(ne.key)},D=(Z,ne)=>{if(p==="select"){v(null);return}const ce=E.current[ne];if(!ce)return;const ie=ce.getBoundingClientRect(),te=YCe[p],ae=Pde((Z.clientX-ie.left)/ie.width-te.w/2),le=Pde((Z.clientY-ie.top)/ie.height-te.h/2),be={key:crypto.randomUUID(),page_index:ne,x:Math.min(ae,1-te.w),y:Math.min(le,1-te.h),w:te.w,h:te.h,field_kind:p,merge_key:null,static_value:null,signer_role:wBe.includes(p)?"buyer_1":null,label:null,is_required:!0,font_size:null};m(me=>[...me,be]),v(be.key),f("select")},O=h.find(Z=>Z.key===y)||null,V=Z=>{O&&m(ne=>ne.map(ce=>ce.key===O.key?{...ce,...Z}:ce))},G=async(Z=!1)=>{if(o){S(!0);try{const ne=await o.arrayBuffer(),ce=await a6e({data:ne}).promise,ie=Math.min(ce.numPages,o4t),te=[];for(let he=1;he<=ie;he++){const pe=await ce.getPage(he),Ce=pe.getViewport({scale:1}),Ae=pe.getViewport({scale:Math.min(1e3/Ce.width,1.6)}),Pe=document.createElement("canvas");Pe.width=Math.floor(Ae.width),Pe.height=Math.floor(Ae.height);const ze=Pe.getContext("2d");ze&&(ze.fillStyle="#ffffff",ze.fillRect(0,0,Pe.width,Pe.height),await pe.render({canvasContext:ze,viewport:Ae}).promise,te.push({index:he-1,image:Pe.toDataURL("image/jpeg",.7)}))}const{data:ae,error:le}=await q.functions.invoke("forms-autoplace",{body:{version_id:s.id,pages:te,force:Z}});if(le)throw new Error(le.message||"The field scan failed.");if(ae!=null&&ae.error)throw new Error(ae.error);const be=(ae==null?void 0:ae.fields)||[];if(!be.length){se.info("The scan did not find any blank fields on this form. Place them manually below.");return}const me=be.map(he=>({key:crypto.randomUUID(),page_index:he.page_index,x:he.x,y:he.y,w:he.w,h:he.h,field_kind:he.field_kind,merge_key:null,static_value:null,signer_role:he.signer_role||"buyer_1",label:he.label,is_required:!0,font_size:null,source:"ai"}));m(he=>[...he,...me]),v(null),se.success(`${me.length} field${me.length===1?"":"s"} placed${ae!=null&&ae.cached?" (from the earlier scan)":""}. Review, nudge, then save.`)}catch(ne){se.error((ne==null?void 0:ne.message)||"Could not scan this document. You can still place fields manually.")}finally{S(!1)}}},$=async()=>{const Z=h.filter(ne=>wBe.includes(ne.field_kind));for(const ne of Z)if(!ne.signer_role){se.error("Every signer field needs a role (Buyer 1, Seller 1, Agent…)");return}b(!0);try{const{error:ne}=await q.from("form_field_mappings").delete().eq("version_id",s.id).or("field_kind.neq.data,mapping_mode.eq.overlay");if(ne)throw ne;const ce=h.map((le,be)=>({version_id:s.id,pdf_field_name:null,mapping_mode:(le.field_kind==="data"&&le.static_value&&!le.merge_key,"overlay"),field_kind:le.field_kind,merge_key:le.field_kind==="data"?le.merge_key:null,static_value:le.field_kind==="data"?le.static_value:null,signer_role:wBe.includes(le.field_kind)?le.signer_role:null,label:le.label,is_required:le.is_required,page_index:le.page_index,pos_x:le.x,pos_y:le.y,width:le.w,height:le.h,coords_normalized:!0,font_size:le.font_size,source:le.source||"manual",sort_order:be}));if(ce.length){const{error:le}=await q.from("form_field_mappings").insert(ce);if(le)throw le}const te=h.some(le=>le.field_kind==="data"&&(le.merge_key||le.static_value))||i.some(le=>le.field_kind==="data"&&le.mapping_mode!=="overlay"&&(le.mapping_mode==="acroform"&&le.merge_key||le.mapping_mode==="static"))||Z.length?"mapped":s.has_acroform?"needs_mapping":"needs_placement",{error:ae}=await q.from("form_template_versions").update({mapping_status:te}).eq("id",s.id);if(ae)throw ae;se.success("Placement saved"),a.invalidateQueries({queryKey:["form-field-mappings",s.id]}),a.invalidateQueries({queryKey:["form-templates"]}),r(!1)}catch(ne){se.error((ne==null?void 0:ne.message)||"Could not save placement")}finally{b(!1)}},H=[{tool:"select",label:"Select",icon:KQ},{tool:"data",label:"Merge field",icon:r6},{tool:"signature",label:"Signature",icon:Qm},{tool:"initials",label:"Initials",icon:c$},{tool:"date_signed",label:"Date signed",icon:pc},{tool:"printed_name",label:"Printed name",icon:Fo},{tool:"text",label:"Text input",icon:l$}],Y=s.page_count||1;return e.jsx(Ls,{open:n,onOpenChange:r,children:e.jsxs(Ps,{className:"flex h-[94vh] max-w-6xl flex-col overflow-hidden p-0",children:[e.jsxs(Os,{className:"border-b px-5 py-3 text-left",children:[e.jsxs(Ds,{className:"text-base",children:["Place fields — ",t," (v",s.version_number,")"]}),e.jsx("p",{className:"text-xs font-normal text-muted-foreground",children:"Pick a field type on the left, then click on the document where it belongs. Drag to move, pull the corner to resize."})]}),e.jsxs("div",{className:"flex min-h-0 flex-1",children:[e.jsxs("div",{className:"w-36 shrink-0 space-y-1 overflow-y-auto border-r p-3 sm:w-44",children:[e.jsxs(B,{size:"sm",variant:"secondary",className:"mb-2 h-auto w-full flex-col items-start gap-0.5 py-2 text-left",disabled:j||!o,onClick:()=>G(!!s.autoplace_ran_at),children:[e.jsxs("span",{className:"flex items-center gap-1.5 text-xs font-semibold",children:[j?e.jsx(Ct,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(un,{className:"h-3.5 w-3.5"}),j?"Scanning…":s.autoplace_ran_at?"Re-scan with AI":"Find fields with AI"]}),e.jsx("span",{className:"text-[10px] font-normal opacity-70",children:s.autoplace_ran_at?"Runs a fresh scan":`Scan ${M} page${M===1?"":"s"}`})]}),H.map(Z=>e.jsxs("button",{onClick:()=>f(Z.tool),className:`flex w-full items-center gap-2 rounded-md px-2.5 py-2 text-left text-xs font-medium transition-colors ${p===Z.tool?"bg-primary text-primary-foreground":"hover:bg-muted"}`,children:[e.jsx(Z.icon,{className:"h-3.5 w-3.5 shrink-0"}),Z.label]},Z.tool)),e.jsx("div",{className:"pt-3 text-[11px] leading-snug text-muted-foreground",children:"Merge fields fill automatically from the deal. Signature fields are assigned to a signer."})]}),e.jsxs("div",{className:"relative min-w-0 flex-1 overflow-auto bg-muted/40 p-4",children:[(l||!o)&&!d&&e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})}),d&&e.jsx("p",{className:"p-6 text-center text-sm text-destructive",children:d}),e.jsx("div",{ref:C,className:"space-y-4",onClickCapture:Z=>{const ne=Z.target.closest("[data-page-index]");ne&&D(Z,Number(ne.dataset.pageIndex))}})]}),e.jsxs("div",{className:"hidden w-64 shrink-0 flex-col border-l sm:flex",children:[e.jsx("div",{className:"border-b px-4 py-3 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:O?YCe[O.field_kind].label:"Field settings"}),e.jsx(Ji,{className:"flex-1 p-4",children:O?e.jsxs("div",{className:"space-y-4",children:[O.field_kind==="data"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs",children:"Merge value"}),e.jsxs(is,{value:O.merge_key||"",onValueChange:Z=>V({merge_key:Z||null,static_value:null}),children:[e.jsx(rs,{className:"h-8 text-xs",children:e.jsx(ls,{placeholder:"Choose data…"})}),e.jsx(as,{children:["Deal","Contact","Agent","Other"].map(Z=>e.jsxs("div",{children:[e.jsx("div",{className:"px-2 py-1 text-[10px] font-semibold uppercase text-muted-foreground",children:Z}),DG.filter(ne=>ne.group===Z).map(ne=>e.jsx(He,{value:ne.key,className:"text-xs",children:ne.label},ne.key))]},Z))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs",children:"…or fixed text"}),e.jsx(xe,{className:"h-8 text-xs",placeholder:"Printed exactly as typed",value:O.merge_key?"":O.static_value||"",disabled:!!O.merge_key,onChange:Z=>V({static_value:Z.target.value||null})})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs",children:"Who signs this?"}),e.jsxs(is,{value:O.signer_role||"",onValueChange:Z=>V({signer_role:Z}),children:[e.jsx(rs,{className:"h-8 text-xs",children:e.jsx(ls,{placeholder:"Choose signer…"})}),e.jsx(as,{children:Bat.map(Z=>e.jsx(He,{value:Z.value,className:"text-xs",children:Z.label},Z.value))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs",children:"Label shown to signer"}),e.jsx(xe,{className:"h-8 text-xs",placeholder:YCe[O.field_kind].label,value:O.label||"",onChange:Z=>V({label:Z.target.value||null})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(J,{className:"text-xs",children:"Required"}),e.jsx(fn,{checked:O.is_required,onCheckedChange:Z=>V({is_required:Z})})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs",children:"Font size (optional)"}),e.jsx(xe,{className:"h-8 text-xs",type:"number",min:6,max:24,value:O.font_size??"",onChange:Z=>V({font_size:Z.target.value?Number(Z.target.value):null})})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[O.page_index+1{const Z={...O,key:crypto.randomUUID(),page_index:O.page_index+1};m(ne=>[...ne,Z]),v(Z.key)},children:[e.jsx(Ia,{className:"mr-1 h-3 w-3"})," Next page"]}),e.jsxs(B,{variant:"outline",size:"sm",className:"h-8 flex-1 text-xs text-destructive",onClick:()=>{m(Z=>Z.filter(ne=>ne.key!==O.key)),v(null)},children:[e.jsx(Sn,{className:"mr-1 h-3 w-3"})," Remove"]})]})]}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"Select a box on the document to edit what it fills and who signs it."})}),e.jsx("div",{className:"border-t p-4",children:e.jsxs(B,{className:"w-full",onClick:$,disabled:g,children:[g?e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Ho,{className:"mr-2 h-4 w-4"}),"Save placement"]})})]})]}),e.jsx(yer,{boxes:h,pageRefs:E,selectedKey:y,onSelect:v,onDragStart:I})]})})}function yer({boxes:s,pageRefs:t,selectedKey:n,onSelect:r,onDragStart:a}){const[,i]=_.useState(0);return _.useEffect(()=>{const l=setTimeout(()=>i(o=>o+1),300);return()=>clearTimeout(l)},[s.length===0]),e.jsx(e.Fragment,{children:s.map(l=>{var c;const o=t.current[l.page_index];return o?e.jsx(ver,{target:o,children:e.jsxs("div",{onPointerDown:d=>a(d,l,"move"),onClick:d=>d.stopPropagation(),className:`absolute cursor-move rounded-sm border-2 transition-shadow ${l.field_kind==="data"?"border-primary bg-primary/10 text-primary":ger[l.signer_role||""]||"border-muted-foreground bg-muted/40"} ${n===l.key?"ring-2 ring-ring shadow-md":""}`,style:{left:`${l.x*100}%`,top:`${l.y*100}%`,width:`${l.w*100}%`,height:`${l.h*100}%`},children:[e.jsx("span",{className:"pointer-events-none absolute left-0.5 top-0 max-w-full truncate text-[9px] font-semibold leading-tight",children:l.field_kind==="data"?l.merge_key?((c=DG.find(d=>d.key===l.merge_key))==null?void 0:c.label)||l.merge_key:l.static_value||"Data":`${l.label||YCe[l.field_kind].label} · ${eDe(l.signer_role)}`}),n===l.key&&e.jsx("span",{onPointerDown:d=>a(d,l,"resize"),className:"absolute -bottom-1.5 -right-1.5 h-3.5 w-3.5 cursor-nwse-resize rounded-full border-2 border-background bg-primary"})]})},l.key):null})})}function ver({target:s,children:t}){return mv.createPortal(t,s)}function ber({templates:s}){const{data:t=[],isLoading:n}=ers(),r=rJn(),a=aJn(),[i,l]=_.useState(null),[o,c]=_.useState(""),[d,u]=_.useState(""),[h,m]=_.useState([]);_.useEffect(()=>{i&&(i==="new"?(c(""),u(""),m([])):(c(i.name),u(i.description||""),m([...i.items||[]].sort((g,b)=>g.sort_order-b.sort_order).map(g=>g.template_id))))},[i]);const p=s.filter(g=>{var b;return((b=_x(g))==null?void 0:b.mapping_status)==="mapped"}),f=g=>m(b=>b.includes(g)?b.filter(j=>j!==g):[...b,g]),y=(g,b)=>m(j=>{const S=[...j],C=g+b;return C<0||C>=S.length?j:([S[g],S[C]]=[S[C],S[g]],S)}),v=async()=>{if(!o.trim())return se.error("Give the packet a name");if(!h.length)return se.error("Add at least one form to the packet");try{await r.mutateAsync({id:i==="new"?void 0:i.id,name:o.trim(),description:d.trim()||null,templateIds:h}),se.success(i==="new"?"Packet created":"Packet updated"),l(null)}catch(g){se.error((g==null?void 0:g.message)||"Could not save the packet")}};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"flex items-center gap-2 text-lg font-semibold tracking-tight",children:[e.jsx(G4,{className:"h-4 w-4 text-primary"})," Form packets"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Bundle the forms you always send together. Signers sign the whole packet in one session."})]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>l("new"),disabled:p.length===0,children:[e.jsx(rn,{className:"mr-2 h-4 w-4"})," New packet"]})]}),n?e.jsx("div",{className:"flex justify-center py-6",children:e.jsx(Ct,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):t.length===0?e.jsx(ve,{className:"border-dashed",children:e.jsx(Me,{className:"p-6 text-center text-sm text-muted-foreground",children:p.length===0?"Once at least one template is ready to send, you can bundle templates into a packet.":"No packets yet — build a “New Buyer Packet” or “Listing Agreement Bundle” and send it in one click."})}):e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:t.map(g=>{const b=Uat(g,s);return e.jsx(ve,{children:e.jsxs(Me,{className:"space-y-3 p-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-primary/10",children:e.jsx(G4,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate font-medium",children:g.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[b.length," form",b.length===1?"":"s"]})]})]}),e.jsx("ol",{className:"ml-4 list-decimal space-y-0.5 text-xs text-muted-foreground",children:b.map(j=>e.jsx("li",{className:"truncate",children:j.name},j.id))}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Oe,{variant:"outline",className:"text-[10px]",children:"Send from any deal"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsxs(B,{variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>l(g),children:[e.jsx(Ya,{className:"mr-1 h-3 w-3"})," Edit"]}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 text-xs text-destructive",onClick:async()=>{await Xi(`Delete the "${g.name}" packet? The forms themselves are kept.`)&&(await a.mutateAsync(g.id),se.success("Packet deleted"))},children:e.jsx(Sn,{className:"h-3 w-3"})})]})]})]})},g.id)})}),e.jsx(Ls,{open:!!i,onOpenChange:g=>!g&&l(null),children:e.jsxs(Ps,{className:"flex max-h-[88vh] max-w-lg flex-col overflow-hidden",children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:i==="new"?"New form packet":"Edit packet"}),e.jsx(_r,{children:"Pick the forms and the order signers see them in. Only templates that are ready to send can be added."})]}),e.jsxs("div",{className:"space-y-4 overflow-y-auto",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs",children:"Packet name"}),e.jsx(xe,{value:o,onChange:g=>c(g.target.value),placeholder:"New Buyer Packet"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs",children:"Description (optional)"}),e.jsx(Ms,{rows:2,value:d,onChange:g=>u(g.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs",children:"Forms in this packet"}),e.jsx(Ji,{className:"max-h-56 rounded-lg border",children:e.jsx("div",{className:"divide-y",children:p.map(g=>e.jsxs("label",{className:"flex cursor-pointer items-center gap-3 p-2.5 text-sm hover:bg-muted/50",children:[e.jsx($a,{checked:h.includes(g.id),onCheckedChange:()=>f(g.id)}),e.jsx("span",{className:"min-w-0 flex-1 truncate",children:g.name})]},g.id))})})]}),h.length>0&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs",children:"Signing order"}),e.jsx("div",{className:"space-y-1 rounded-lg border p-2",children:h.map((g,b)=>{const j=s.find(S=>S.id===g);return e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsxs("span",{className:"w-4 text-muted-foreground",children:[b+1,"."]}),e.jsx("span",{className:"min-w-0 flex-1 truncate",children:(j==null?void 0:j.name)||"Removed template"}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>y(b,-1),children:e.jsx(sp,{className:"h-3 w-3"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>y(b,1),children:e.jsx(zf,{className:"h-3 w-3"})})]},g)})})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>l(null),children:"Cancel"}),e.jsxs(B,{onClick:v,disabled:r.isPending,children:[r.isPending&&e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}),"Save packet"]})]})]})})]})}function _er(s){const t=s.indexOf(",");if(t<0)return null;try{const n=atob(s.slice(t+1)),r=new Uint8Array(n.length);for(let a=0;ad.field_kind==null||d.field_kind==="data"),n=await Wns(s.templateBytes,t,s.values),r=n.bytes.buffer.slice(n.bytes.byteOffset,n.bytes.byteOffset+n.bytes.byteLength),a=await xC.load(r,{updateMetadata:!1}),i=await a.embedFont(IG.Helvetica),l=a.getPages(),o=[...n.skipped];for(const d of s.signerBoxes){const u=s.entries[d.id],h=l[d.page_index??0];if(!h||d.pos_x==null||d.pos_y==null)continue;if(!u||!u.png&&!((c=u.text)!=null&&c.trim())){o.push(d.static_value||d.field_kind||"signature");continue}const{width:m,height:p}=h.getSize(),f=d.coords_normalized!==!1,y=Number(d.pos_x)*(f?m:1),v=Number(d.width??(f?.2:140))*(f?m:1),g=Number(d.height??(f?.04:24))*(f?p:1),b=Number(d.pos_y)*(f?p:1),j=f?p-b-g:b;if(u.png){const S=_er(u.png);if(!S){o.push("signature");continue}const C=await a.embedPng(S),E=Math.min(v/C.width,g/C.height),P=C.width*E,M=C.height*E;h.drawImage(C,{x:y+(v-P)/2,y:j+(g-M)/2,width:P,height:M})}else{const S=u.text.trim(),C=Math.min(11,Math.max(7,g*.6));h.drawText(S,{x:y+1,y:j+Math.max(2,(g-C)/2),size:C,font:i,color:Fu(0,0,0),maxWidth:Math.max(10,v-2)})}}return{bytes:await a.save(),skipped:o}}const crs='"Segoe Script","Brush Script MT",cursive';function jer(s){const t=document.createElement("canvas");t.width=640,t.height=200;const n=t.getContext("2d");return n.clearRect(0,0,t.width,t.height),n.fillStyle="#12233f",n.textAlign="center",n.font=`72px ${crs}`,n.fillText(s,t.width/2,t.height/2+24),t.toDataURL("image/png")}function Ner({label:s,onAdopt:t}){const n=_.useRef(null),r=_.useRef(!1),[a,i]=_.useState(""),[l,o]=_.useState(!1),c=m=>{const p=n.current,f=p.getBoundingClientRect();return{x:(m.clientX-f.left)/f.width*p.width,y:(m.clientY-f.top)/f.height*p.height}},d=m=>{const p=n.current;if(!p)return;r.current=!0,p.setPointerCapture(m.pointerId);const f=p.getContext("2d");f.lineWidth=3,f.lineCap="round",f.strokeStyle="#12233f";const y=c(m);f.beginPath(),f.moveTo(y.x,y.y)},u=m=>{if(!r.current)return;const p=n.current.getContext("2d"),f=c(m);p.lineTo(f.x,f.y),p.stroke(),o(!0)},h=()=>{r.current=!1};return e.jsxs(Yr,{defaultValue:"draw",className:"w-full",children:[e.jsxs(Zr,{className:"grid w-full grid-cols-2",children:[e.jsx(Ht,{value:"draw",children:"Draw"}),e.jsx(Ht,{value:"type",children:"Type"})]}),e.jsxs(Gt,{value:"draw",className:"space-y-3 pt-3",children:[e.jsx("canvas",{ref:n,width:640,height:200,className:"h-36 w-full touch-none rounded-lg border bg-white",onPointerDown:d,onPointerMove:u,onPointerUp:h,onPointerLeave:h}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:()=>{var p;const m=n.current;(p=m==null?void 0:m.getContext("2d"))==null||p.clearRect(0,0,m.width,m.height),o(!1)},children:[e.jsx(Lq,{className:"mr-1 h-3.5 w-3.5"})," Clear"]}),e.jsxs(B,{type:"button",size:"sm",className:"flex-1",disabled:!l,onClick:()=>{const m=n.current;m&&t(m.toDataURL("image/png"))},children:["Use this ",s]})]})]}),e.jsxs(Gt,{value:"type",className:"space-y-3 pt-3",children:[e.jsx(xe,{value:a,onChange:m=>i(m.target.value),placeholder:"Type your name"}),e.jsx("div",{className:"flex h-24 items-center justify-center rounded-lg border bg-white",children:e.jsx("span",{className:"text-3xl text-[#12233f]",style:{fontFamily:crs},children:a||" "})}),e.jsxs(B,{type:"button",size:"sm",className:"w-full",disabled:!a.trim(),onClick:()=>t(jer(a.trim())),children:["Use this ",s]})]})]})}const ker=["signature","initials","date_signed","printed_name","text"],Ser={signature:"Signature",initials:"Initials",date_signed:"Date signed",printed_name:"Printed name",text:"Text"};function Cer({open:s,onOpenChange:t,template:n,version:r}){const a=ha(),{data:i=[],isLoading:l}=hie(s?r.id:void 0),{data:o=[]}=lK(),[c,d]=_.useState(""),{data:u}=zat(s&&c?c:void 0),[h,m]=_.useState({}),[p,f]=_.useState({}),[y,v]=_.useState(null),[g,b]=_.useState(!1),j=_.useMemo(()=>i.filter(I=>(I.field_kind==null||I.field_kind==="data")&&I.mapping_mode!=="blank"&&(I.merge_key||I.pdf_field_name||I.static_value)),[i]),S=_.useMemo(()=>i.filter(I=>I.field_kind&&ker.includes(I.field_kind)),[i]);_.useEffect(()=>{u&&m(I=>{const D={...I};for(const[O,V]of Object.entries(u.values))V&&!D[O]&&(D[O]=V);return D})},[u]),_.useEffect(()=>{s||(m({}),f({}),v(null),d(""))},[s]);const C=I=>I.merge_key||I.pdf_field_name||I.id,E=I=>{v(I),f(D=>{var V;const O={...D};for(const G of S)(G.field_kind==="signature"||G.field_kind==="initials")&&(O[G.id]={png:I}),G.field_kind==="date_signed"&&!((V=O[G.id])!=null&&V.text)&&(O[G.id]={text:new Date().toLocaleDateString("en-US")});return O}),se.success("Signature applied to the document")},P=S.filter(I=>{var D,O,V;return((D=p[I.id])==null?void 0:D.png)||((V=(O=p[I.id])==null?void 0:O.text)==null?void 0:V.trim())}).length,M=async()=>{b(!0);try{const I=await J8e(r.storage_path),D={...h},{bytes:O}=await wer({templateBytes:I,mappings:i,values:D,signerBoxes:S,entries:p}),G=`${n.name.replace(/[^a-zA-Z0-9-_ ]/g,"").trim()||"Form"} - signed.pdf`,$=O.buffer.slice(O.byteOffset,O.byteOffset+O.byteLength),H=new Blob([$],{type:"application/pdf"}),Y=URL.createObjectURL(H),Z=document.createElement("a");if(Z.href=Y,Z.download=G,Z.click(),URL.revokeObjectURL(Y),c&&a){const ne=`${a}/${c}/${crypto.randomUUID()}.pdf`,{error:ce}=await q.storage.from("deal-files").upload(ne,H,{contentType:"application/pdf"});if(ce)throw ce;const{error:ie}=await q.from("deal_files").insert({deal_id:c,owner_user_id:a,file_name:G,file_size:H.size,file_type:"application/pdf",storage_path:ne});if(ie)throw ie;await q.from("deal_activities").insert({deal_id:c,activity_type:"document",title:`Filled and signed ${n.name}`,description:`${G} was completed in LevelUp (v${r.version_number}).`,metadata:{template_id:n.id,version_id:r.id}}),se.success("Saved to the deal and downloaded")}else se.success("Your signed PDF is downloading");t(!1)}catch(I){se.error(Dat(I))}finally{b(!1)}};return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"flex max-h-[90vh] max-w-2xl flex-col overflow-hidden",children:[e.jsxs(Os,{children:[e.jsxs(Ds,{children:["Fill & sign — ",n.name]}),e.jsx(_r,{children:"Type in the details, sign once and download the completed PDF. Nothing is emailed to anyone."})]}),e.jsxs("div",{className:"space-y-5 overflow-y-auto pr-1",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Prefill from a deal (optional)"}),e.jsxs(is,{value:c||"none",onValueChange:I=>d(I==="none"?"":I),children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"No deal — I'll type everything"})}),e.jsxs(as,{children:[e.jsx(He,{value:"none",children:"No deal — I'll type everything"}),o.map(I=>e.jsx(He,{value:I.id,children:I.deal_name},I.id))]})]}),c&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"The finished PDF is also saved to this deal's files."})]}),l?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(Ct,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-sm font-medium",children:"Form details"}),j.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"This form has no data fields — just sign it below."}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:j.map(I=>{var G;const D=C(I),O=I.merge_key?((G=Xns.get(I.merge_key))==null?void 0:G.label)||I.merge_key:I.pdf_field_name||"Field",V=I.mapping_mode==="static";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(J,{className:"text-xs text-muted-foreground",children:O}),e.jsx(xe,{value:V?I.static_value||"":h[D]??"",disabled:V,onChange:$=>m(H=>({...H,[D]:$.target.value}))})]},I.id)})})]}),e.jsxs("div",{className:"space-y-3 rounded-lg border p-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(Qm,{className:"h-4 w-4"})," Your signature"]}),S.length>0&&e.jsxs(Oe,{variant:P===S.length?"default":"outline",children:[P,"/",S.length," placed"]})]}),S.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No signature spots are placed on this form yet. Use “Place fields & signatures” first."}):e.jsxs(e.Fragment,{children:[y?e.jsxs("div",{className:"flex items-center gap-3 rounded-md border bg-white p-3",children:[e.jsx("img",{src:y,alt:"Your signature",className:"h-12 object-contain"}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>v(null),children:"Redo"})]}):e.jsx(Ner,{label:"signature",onAdopt:E}),e.jsx("div",{className:"space-y-2",children:S.filter(I=>I.field_kind==="printed_name"||I.field_kind==="text"||I.field_kind==="date_signed").map(I=>{var D;return e.jsxs("div",{className:"space-y-1",children:[e.jsxs(J,{className:"text-xs text-muted-foreground",children:[Ser[I.field_kind||"text"]," · page ",(I.page_index??0)+1,I.signer_role?` · ${eDe(I.signer_role)}`:""]}),e.jsx(xe,{value:((D=p[I.id])==null?void 0:D.text)??"",onChange:O=>f(V=>({...V,[I.id]:{text:O.target.value}}))})]},I.id)})}),e.jsxs("p",{className:"flex items-start gap-2 text-xs text-muted-foreground",children:[e.jsx(Er,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),"By signing you agree your electronic signature is legally binding on this document."]})]})]})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),disabled:g,children:"Cancel"}),e.jsxs(B,{onClick:M,disabled:g||l,children:[g?e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(li,{className:"mr-2 h-4 w-4"}),"Finish & download"]})]})]})})}function Aer({status:s}){return s==="mapped"?e.jsx(Oe,{className:"bg-emerald-500/15 text-emerald-600 hover:bg-emerald-500/15",children:"Ready"}):s==="needs_placement"?e.jsx(Oe,{variant:"outline",children:"Needs field placement"}):e.jsx(Oe,{variant:"secondary",children:"Needs mapping"})}function Eer(){var Z,ne;const{data:s=[],isLoading:t,error:n}=Fat(),{data:r=[]}=lK(),a=Yns(),i=Zns(),l=VQn(),[o,c]=_.useState(!1),[d,u]=_.useState(null),[h,m]=_.useState(null),[p,f]=_.useState(""),[y,v]=_.useState(null),[g,b]=_.useState(""),[j,S]=_.useState(null),[C,E]=_.useState("generate"),[P,M]=_.useState(null),[I,D]=_.useState("all"),O=s.some(ce=>ce.scope==="brokerage"),V=s.filter(ce=>ce.name.toLowerCase().includes(p.trim().toLowerCase())).filter(ce=>I==="all"||(ce.scope||"mine")===I).sort((ce,ie)=>(ce.scope==="brokerage"?1:0)-(ie.scope==="brokerage"?1:0)),G=async ce=>{try{await l.mutateAsync(ce),se.success(`"${ce.name}" copied to your forms`)}catch(ie){se.error((ie==null?void 0:ie.message)||"Could not copy that form")}},$=h?s.find(ce=>ce.id===h.id)||h:null,H=_x($),Y=async ce=>{if(await Xi(`Delete "${ce.name}" and all of its versions? Forms already generated stay on their deals.`))try{await i.mutateAsync(ce),(h==null?void 0:h.id)===ce.id&&m(null),se.success("Template deleted")}catch(ie){se.error((ie==null?void 0:ie.message)||"Could not delete the template")}};return e.jsxs(zs,{children:[e.jsxs("div",{className:"mx-auto w-full max-w-6xl space-y-6 px-4 py-6 sm:px-6",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Forms Library"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Upload blank PDF forms you are permitted to use, map their fields once, then fill them from any deal."})]}),e.jsxs(B,{onClick:()=>c(!0),children:[e.jsx(rn,{className:"mr-2 h-4 w-4"})," Upload template"]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("div",{className:"relative w-full max-w-sm",children:[e.jsx(Lr,{className:"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(xe,{className:"pl-9",placeholder:"Search templates…",value:p,onChange:ce=>f(ce.target.value)})]}),O&&e.jsx("div",{className:"flex gap-1 rounded-lg border p-1",children:[["all","All"],["mine","My forms"],["brokerage","Brokerage forms"]].map(([ce,ie])=>e.jsx(B,{size:"sm",variant:I===ce?"secondary":"ghost",className:"h-7 text-xs",onClick:()=>D(ce),children:ie},ce))})]}),t&&e.jsx("div",{className:"flex justify-center py-16",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})}),n&&e.jsx(ve,{children:e.jsx(Me,{className:"p-6 text-center text-sm text-destructive",children:"Could not load your templates. Please refresh and try again."})}),!t&&!n&&s.length===0&&e.jsx(ve,{className:"border-dashed",children:e.jsxs(Me,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx("div",{className:"flex h-12 w-12 items-center justify-center rounded-full bg-muted",children:e.jsx(Fr,{className:"h-6 w-6 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"No form templates yet"}),e.jsx("p",{className:"mx-auto max-w-sm text-sm text-muted-foreground",children:"Upload a blank PDF form you are legally permitted to use. LevelUp reads its fillable fields so you can map them to your deal, contact and agent data."})]}),e.jsxs(B,{onClick:()=>c(!0),children:[e.jsx(Oa,{className:"mr-2 h-4 w-4"})," Upload your first template"]})]})}),!t&&!n&&s.length>0&&e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:[V.map(ce=>{var ae;const ie=_x(ce),te=ce.scope==="brokerage";return e.jsx(ve,{className:"transition-shadow hover:shadow-md",children:e.jsxs(Me,{className:"space-y-3 p-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-primary/10",children:e.jsx(Fr,{className:"h-5 w-5 text-primary"})}),e.jsxs("button",{className:"min-w-0 flex-1 text-left",onClick:()=>m(ce),children:[e.jsx("p",{className:"truncate font-medium",children:ce.name}),te&&e.jsxs(Oe,{variant:"outline",className:"mt-1 gap-1 text-[10px]",children:[e.jsx(ai,{className:"h-3 w-3"})," Brokerage form"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(ae=Rat.find(le=>le.value===ce.category))==null?void 0:ae.label," · v",(ie==null?void 0:ie.version_number)??1,ie?` · ${ie.page_count} page${ie.page_count===1?"":"s"}`:""]})]}),e.jsxs(tu,{children:[e.jsx(su,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(Xx,{className:"h-4 w-4"})})}),e.jsx(Od,{align:"end",children:te?e.jsxs(e.Fragment,{children:[e.jsx(ca,{onClick:()=>m(ce),children:"View details"}),e.jsxs(ca,{disabled:l.isPending,onClick:()=>G(ce),children:[e.jsx(Ia,{className:"mr-2 h-4 w-4"})," Copy to my forms"]}),e.jsxs(ca,{disabled:(ie==null?void 0:ie.mapping_status)!=="mapped",onClick:()=>M(ce),children:[e.jsx(Qm,{className:"mr-2 h-4 w-4"})," Fill & sign"]})]}):e.jsxs(e.Fragment,{children:[e.jsx(ca,{onClick:()=>m(ce),children:"Open & map fields"}),e.jsxs(ca,{onClick:()=>S(ce),children:[e.jsx(sf,{className:"mr-2 h-4 w-4"})," Place fields & signatures"]}),e.jsxs(ca,{disabled:(ie==null?void 0:ie.mapping_status)!=="mapped",onClick:()=>{E("sign"),v(ce),b("")},children:[e.jsx(Qm,{className:"mr-2 h-4 w-4"})," Send for signature"]}),e.jsxs(ca,{disabled:(ie==null?void 0:ie.mapping_status)!=="mapped",onClick:()=>M(ce),children:[e.jsx(Qm,{className:"mr-2 h-4 w-4"})," Fill & sign myself"]}),e.jsxs(ca,{onClick:()=>u(ce),children:[e.jsx(Oa,{className:"mr-2 h-4 w-4"})," Upload new version"]}),e.jsxs(ca,{onClick:()=>a.mutate({id:ce.id,patch:{is_archived:!0}}),children:[e.jsx(by,{className:"mr-2 h-4 w-4"})," Archive"]}),e.jsxs(ca,{className:"text-destructive",onClick:()=>Y(ce),children:[e.jsx(Sn,{className:"mr-2 h-4 w-4"})," Delete"]})]})})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Aer,{status:ie==null?void 0:ie.mapping_status}),e.jsxs("div",{className:"flex gap-1",children:[e.jsxs(B,{variant:"ghost",size:"sm",disabled:(ie==null?void 0:ie.mapping_status)!=="mapped",onClick:()=>M(ce),children:[e.jsx(Qm,{className:"mr-1.5 h-4 w-4"})," Fill & sign"]}),e.jsxs(B,{variant:"ghost",size:"sm",disabled:(ie==null?void 0:ie.mapping_status)!=="mapped",onClick:()=>{E("sign"),v(ce),b("")},children:[e.jsx(Qm,{className:"mr-1.5 h-4 w-4"})," Send"]}),e.jsxs(B,{variant:"ghost",size:"sm",disabled:(ie==null?void 0:ie.mapping_status)!=="mapped",onClick:()=>{E("generate"),v(ce),b("")},children:[e.jsx(Iq,{className:"mr-1.5 h-4 w-4"})," Use"]})]})]})]})},ce.id)}),V.length===0&&e.jsx("p",{className:"col-span-full py-10 text-center text-sm text-muted-foreground",children:"No templates match that search."})]}),!t&&!n&&s.length>0&&e.jsx("div",{className:"border-t pt-6",children:e.jsx(ber,{templates:s})})]}),e.jsx(qg,{open:!!$,onOpenChange:ce=>!ce&&m(null),children:e.jsxs(hg,{side:"right",className:"w-full overflow-y-auto sm:max-w-2xl",children:[e.jsxs(P0,{className:"space-y-1 text-left",children:[e.jsxs("button",{className:"flex items-center gap-1 text-xs text-muted-foreground sm:hidden",onClick:()=>m(null),children:[e.jsx(ka,{className:"h-3 w-3"})," Back"]}),e.jsx(L0,{children:$==null?void 0:$.name}),H&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["v",H.version_number," · ",H.file_name," · ",Oat(H.file_size)," · uploaded ",Hs(new Date(H.created_at),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"mt-5 space-y-4",children:[($==null?void 0:$.description)&&e.jsx("p",{className:"text-sm text-muted-foreground",children:$.description}),H?e.jsx(e.Fragment,{children:($==null?void 0:$.scope)==="brokerage"?e.jsxs("div",{className:"rounded-lg border bg-muted/40 p-4 text-sm text-muted-foreground",children:[e.jsxs("p",{className:"flex items-center gap-2 font-medium text-foreground",children:[e.jsx(ai,{className:"h-4 w-4"})," Managed by your brokerage"]}),e.jsx("p",{className:"mt-1",children:"Fields on this form are set up by your brokerage. You can fill it from any deal or send it for signature. Need your own version? Use “Copy to my forms”."}),e.jsxs(B,{variant:"outline",className:"mt-3 w-full",disabled:l.isPending,onClick:()=>$&&G($),children:[e.jsx(Ia,{className:"mr-2 h-4 w-4"})," Copy to my forms"]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"outline",className:"w-full",onClick:()=>$&&S($),children:[e.jsx(sf,{className:"mr-2 h-4 w-4"})," Place fields & signatures on the document"]}),e.jsx(ors,{version:H})]})}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"This template has no uploaded version yet."})]})]})}),e.jsx(w6e,{open:o,onOpenChange:c}),e.jsx(w6e,{open:!!d,onOpenChange:ce=>!ce&&u(null),templateId:d==null?void 0:d.id,templateName:d==null?void 0:d.name}),e.jsx(qg,{open:!!y&&!g,onOpenChange:ce=>!ce&&v(null),children:e.jsxs(hg,{side:"bottom",className:"space-y-4",children:[e.jsx(P0,{className:"text-left",children:e.jsx(L0,{children:"Choose a deal"})}),r.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"You don’t have any deals yet."}):e.jsxs(is,{value:g,onValueChange:b,children:[e.jsx(rs,{className:"max-w-md",children:e.jsx(ls,{placeholder:"Select a deal"})}),e.jsx(as,{children:r.map(ce=>e.jsx(He,{value:ce.id,children:ce.deal_name},ce.id))})]})]})}),y&&g&&C==="generate"&&e.jsx(Qns,{open:!0,onOpenChange:ce=>{ce||(v(null),b(""))},dealId:g,dealName:(Z=r.find(ce=>ce.id===g))==null?void 0:Z.deal_name,initialTemplateId:y.id}),y&&g&&C==="sign"&&e.jsx(trs,{open:!0,onOpenChange:ce=>{ce||(v(null),b(""))},dealId:g,dealName:(ne=r.find(ce=>ce.id===g))==null?void 0:ne.deal_name,initialTemplateId:y.id}),j&&_x(j)&&e.jsx(lrs,{open:!0,onOpenChange:ce=>!ce&&S(null),version:_x(j),templateName:j.name}),P&&_x(P)&&e.jsx(Cer,{open:!0,onOpenChange:ce=>!ce&&M(null),template:P,version:_x(P)})]})}function drs({open:s,onOpenChange:t,editTask:n,defaultDealId:r,defaultStageId:a}){var G;const i=$Jn(),l=VJn(),{data:o}=lK(),c=ha(),{data:d}=at({queryKey:["contacts-for-tasks",c],queryFn:async()=>{if(!c)return[];const{data:$,error:H}=await q.from("innercircle_contacts").select("id, first_name, last_name").eq("owner_user_id",c).order("first_name").limit(500);if(H)throw H;return $},enabled:!!c&&s}),[u,h]=_.useState(""),[m,p]=_.useState(""),[f,y]=_.useState("none"),[v,g]=_.useState("none"),[b,j]=_.useState("medium"),[S,C]=_.useState("todo"),[E,P]=_.useState(),[M,I]=_.useState(!1),[D,O]=_.useState(!1);_.useEffect(()=>{n?(h(n.title),p(n.description||""),y(n.deal_id||"none"),g(n.contact_id||"none"),j(n.priority),C(n.status),P(n.due_date?py(n.due_date):void 0)):(h(""),p(""),y(r||"none"),g("none"),j("medium"),C("todo"),P(void 0))},[n,s,r]);const V=async()=>{if(!u.trim()){se.error("Task title is required");return}try{const $={title:u.trim(),description:m.trim()||null,deal_id:f==="none"?null:f,contact_id:v==="none"?null:v,stage_id:a||null,priority:b,status:S,due_date:E?Hs(E,"yyyy-MM-dd"):null};n?(await l.mutateAsync({id:n.id,...$}),se.success("Task updated")):(await i.mutateAsync($),se.success("Task created")),t(!1)}catch{se.error("Failed to save task")}};return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"sm:max-w-[480px]",children:[e.jsx(Os,{children:e.jsx(Ds,{children:n?"Edit Task":"New Task"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Title *"}),e.jsx(xe,{value:u,onChange:$=>h($.target.value),placeholder:"e.g., Send inspection report"})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Description"}),e.jsx(Ms,{value:m,onChange:$=>p($.target.value),placeholder:"Optional details...",rows:2})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Priority"}),e.jsxs(is,{value:b,onValueChange:$=>j($),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"low",children:"🟢 Low"}),e.jsx(He,{value:"medium",children:"🟡 Medium"}),e.jsx(He,{value:"high",children:"🟠 High"}),e.jsx(He,{value:"urgent",children:"🔴 Urgent"})]})]})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Status"}),e.jsxs(is,{value:S,onValueChange:$=>C($),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"todo",children:"To Do"}),e.jsx(He,{value:"in_progress",children:"In Progress"}),e.jsx(He,{value:"done",children:"Done"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Due Date"}),e.jsxs(od,{children:[e.jsx(ld,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:At("w-full justify-start text-left font-normal",!E&&"text-muted-foreground"),children:[e.jsx(ga,{className:"mr-2 h-4 w-4"}),E?Hs(E,"PPP"):"Pick a date"]})}),e.jsx(Qc,{className:"w-auto p-0",align:"start",children:e.jsx(Pj,{mode:"single",selected:E,onSelect:P,initialFocus:!0,className:"p-3 pointer-events-auto"})})]})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Link to Deal"}),e.jsxs(od,{open:M,onOpenChange:I,children:[e.jsx(ld,{asChild:!0,children:e.jsxs(B,{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"}),f!=="none"?((G=o==null?void 0:o.find($=>$.id===f))==null?void 0:G.deal_name)||"Select deal":"No Deal"]}),e.jsx(I_,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Qc,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(Aj,{children:[e.jsx(Ej,{placeholder:"Search deals..."}),e.jsxs(Tj,{children:[e.jsx(Mj,{children:"No deals found."}),e.jsxs(V_,{children:[e.jsxs(d1,{value:"no-deal",onSelect:()=>{y("none"),I(!1)},children:[e.jsx(ea,{className:At("mr-2 h-4 w-4",f==="none"?"opacity-100":"opacity-0")}),"No Deal"]}),o==null?void 0:o.map($=>e.jsxs(d1,{value:$.deal_name,onSelect:()=>{y($.id),I(!1)},children:[e.jsx(ea,{className:At("mr-2 h-4 w-4",f===$.id?"opacity-100":"opacity-0")}),$.deal_name]},$.id))]})]})]})})]})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Link to Contact"}),e.jsxs(od,{open:D,onOpenChange:O,children:[e.jsx(ld,{asChild:!0,children:e.jsxs(B,{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(Fo,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),v!=="none"?(()=>{const $=d==null?void 0:d.find(H=>H.id===v);return $?`${$.first_name} ${$.last_name}`:"Select contact"})():"No Contact"]}),e.jsx(I_,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Qc,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(Aj,{children:[e.jsx(Ej,{placeholder:"Search contacts..."}),e.jsxs(Tj,{children:[e.jsx(Mj,{children:"No contacts found."}),e.jsxs(V_,{children:[e.jsxs(d1,{value:"no-contact",onSelect:()=>{g("none"),O(!1)},children:[e.jsx(ea,{className:At("mr-2 h-4 w-4",v==="none"?"opacity-100":"opacity-0")}),"No Contact"]}),d==null?void 0:d.map($=>e.jsxs(d1,{value:`${$.first_name} ${$.last_name}`,onSelect:()=>{g($.id),O(!1)},children:[e.jsx(ea,{className:At("mr-2 h-4 w-4",v===$.id?"opacity-100":"opacity-0")}),$.first_name," ",$.last_name]},$.id))]})]})]})})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(B,{onClick:V,disabled:i.isPending||l.isPending,children:n?"Save Changes":"Create Task"})]})]})]})})}const Ter={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 Mer({tasks:s}){const t=tDe(),n=HJn(),r=Fn(),[a,i]=_.useState(null),l=async u=>{const h=u.status==="done"?"todo":"done";try{await t.mutateAsync({id:u.id,status:h})}catch{se.error("Failed to update task")}},o=async u=>{try{await n.mutateAsync(u),se.success("Task deleted")}catch{se.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(Er,{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(l4t,{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(Oe,{variant:"secondary",className:"ml-auto text-xs",children:[h.tasks.filter(m=>m.status==="done").length,"/",h.tasks.length]}),e.jsx(xi,{className:"h-3.5 w-3.5 text-muted-foreground"})]}),h.tasks.map(m=>e.jsx(l4t,{task:m,onToggle:l,onDelete:o,onEdit:i,onNavigateDeal:p=>r(`/mission-control/pipeline?deal=${p}`)},m.id))]},u)),a&&e.jsx(drs,{open:!!a,onOpenChange:()=>i(null),editTask:a})]})}function l4t({task:s,onToggle:t,onDelete:n,onEdit:r,onNavigateDeal:a}){const i=s.status==="done",l=!i&&s.due_date&&X4(py(s.due_date))&&!yy(py(s.due_date)),o=!i&&s.due_date&&yy(py(s.due_date)),c=Ter[s.priority];return e.jsxs("div",{className:At("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(Er,{className:"h-5 w-5 text-emerald-500"}):e.jsx(Uf,{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:At("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(Fo,{className:"h-2.5 w-2.5"}),s.contact.first_name," ",s.contact.last_name]})]})]}),e.jsxs(Oe,{variant:"outline",className:At("text-[10px] shrink-0",c.color),children:[c.dot," ",c.label]}),s.due_date&&e.jsxs("span",{className:At("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(Gr,{className:"h-3 w-3"}),Hs(py(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(wp,{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(Sn,{className:"h-3.5 w-3.5 text-destructive"})})]})]})}const Per=[{status:"todo",label:"To Do",icon:Uf,color:"border-t-slate-400"},{status:"in_progress",label:"In Progress",icon:om,color:"border-t-blue-500"},{status:"done",label:"Done",icon:Er,color:"border-t-emerald-500"}],Ler={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function Ier({tasks:s}){const t=tDe(),n=_.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{se.error("Failed to move task")}};return e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:Per.map(i=>e.jsxs("div",{className:At("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(Oe,{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(Der,{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 Der({task:s,onDragStart:t}){const n=s.status==="done",r=!n&&s.due_date&&X4(py(s.due_date))&&!yy(py(s.due_date)),a=!n&&s.due_date&&yy(py(s.due_date));return e.jsx("div",{draggable:!0,onDragStart:i=>t(i,s.id),className:At("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:Ler[s.priority]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:At("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(Fo,{className:"h-2.5 w-2.5"}),s.contact.first_name," ",s.contact.last_name]})]}),s.due_date&&e.jsxs("div",{className:At("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(Gr,{className:"h-2.5 w-2.5"}),r?"Overdue — ":a?"Due today — ":"",Hs(py(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 c4t={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function Rer({tasks:s}){const[t,n]=_.useState(new Date),r=tDe(),a=rm(t),i=y_(t),l=v1(a),o=gPe(i),c=QCs({start:l,end:o}),d=_.useMemo(()=>{const m=new Map;return s.forEach(p=>{if(!p.due_date)return;const f=p.due_date,y=m.get(f)||[];y.push(p),m.set(f,y)}),m},[s]),u=_.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{se.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(B,{variant:"ghost",size:"icon",onClick:()=>n(hF(t,1)),children:e.jsx($c,{className:"h-4 w-4"})}),e.jsx("h3",{className:"font-semibold",children:Hs(t,"MMMM yyyy")}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>n(Cy(t,1)),children:e.jsx(xi,{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"),f=d.get(p)||[],y=Vre(m,t),v=yy(m);return e.jsxs("div",{className:At("border-r border-b min-h-[100px] p-1",!y&&"bg-muted/30",v&&"bg-primary/5"),children:[e.jsx("div",{className:At("text-xs font-medium mb-1 text-right px-1",!y&&"text-muted-foreground/40",v&&"text-primary font-bold"),children:Hs(m,"d")}),e.jsxs("div",{className:"space-y-0.5",children:[f.slice(0,3).map(g=>e.jsxs("button",{onClick:()=>h(g),className:At("w-full text-left text-[10px] px-1 py-0.5 rounded truncate flex items-center gap-0.5 hover:bg-muted transition-colors",g.status==="done"?"text-muted-foreground line-through":"text-foreground"),children:[g.status==="done"?e.jsx(Er,{className:"h-2.5 w-2.5 text-emerald-500 shrink-0"}):e.jsx(Uf,{className:"h-2.5 w-2.5 shrink-0"}),e.jsxs("span",{className:"truncate",children:[c4t[g.priority]," ",g.title]})]},g.id)),f.length>3&&e.jsxs("p",{className:"text-[9px] text-muted-foreground text-center",children:["+",f.length-3," more"]})]})]},p)})}),u.length>0&&e.jsxs("div",{className:"border rounded-lg p-3",children:[e.jsxs("h4",{className:"text-sm font-medium text-muted-foreground mb-2",children:["No Due Date (",u.length,")"]}),e.jsx("div",{className:"space-y-1",children:u.map(m=>e.jsxs("button",{onClick:()=>h(m),className:At("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(Er,{className:"h-3.5 w-3.5 text-emerald-500 shrink-0"}):e.jsx(Uf,{className:"h-3.5 w-3.5 shrink-0"}),e.jsxs("span",{className:"truncate",children:[c4t[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 Fer={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function Oer({open:s,onOpenChange:t,stages:n}){var g;const[r,a]=_.useState(((g=n[0])==null?void 0:g.id)||""),{data:i,isLoading:l}=WJn(r||void 0),o=KJn(),c=YJn(),[d,u]=_.useState(""),[h,m]=_.useState("medium"),[p,f]=_.useState(""),y=async()=>{if(!(!d.trim()||!r))try{await o.mutateAsync({stage_id:r,title:d.trim(),priority:h,default_due_offset_days:p?parseInt(p):null,sort_order:((i==null?void 0:i.length)||0)+1}),u(""),f(""),se.success("Template added")}catch{se.error("Failed to add template")}},v=async b=>{try{await c.mutateAsync(b),se.success("Template deleted")}catch{se.error("Failed to delete template")}};return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"sm:max-w-[560px]",children:[e.jsx(Os,{children:e.jsxs(Ds,{className:"flex items-center gap-2",children:[e.jsx(CQ,{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(J,{children:"Pipeline Stage"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:n.filter(b=>!b.is_won_stage&&!b.is_lost_stage).map(b=>e.jsx("button",{onClick:()=>a(b.id),className:At("px-3 py-1.5 rounded-full text-xs font-medium border transition-colors",r===b.id?"border-primary bg-primary/10 text-primary":"border-border hover:bg-muted"),children:b.name},b.id))})]}),e.jsx(Ji,{className:"max-h-[250px]",children:e.jsxs("div",{className:"space-y-1.5",children:[i==null?void 0:i.map((b,j)=>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:Fer[b.priority]}),e.jsx("span",{className:"text-sm flex-1 truncate",children:b.title}),b.default_due_offset_days&&e.jsxs(Oe,{variant:"outline",className:"text-[10px]",children:["+",b.default_due_offset_days,"d"]}),e.jsx("button",{onClick:()=>v(b.id),className:"opacity-0 group-hover:opacity-100 p-1 hover:bg-destructive/10 rounded transition-opacity",children:e.jsx(Sn,{className:"h-3.5 w-3.5 text-destructive"})})]},b.id)),(i==null?void 0:i.length)===0&&r&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No templates for this stage yet"})]})}),r&&e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(J,{className:"text-xs text-muted-foreground",children:"Add Template Task"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{placeholder:"Task title...",value:d,onChange:b=>u(b.target.value),className:"flex-1",onKeyDown:b=>b.key==="Enter"&&y()}),e.jsxs(is,{value:h,onValueChange:b=>m(b),children:[e.jsx(rs,{className:"w-[100px]",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"low",children:"🟢 Low"}),e.jsx(He,{value:"medium",children:"🟡 Med"}),e.jsx(He,{value:"high",children:"🟠 High"}),e.jsx(He,{value:"urgent",children:"🔴 Urgent"})]})]})]}),e.jsxs("div",{className:"flex gap-2 items-end",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(J,{className:"text-xs",children:"Due offset (days from entering stage)"}),e.jsx(xe,{type:"number",placeholder:"e.g., 7",value:p,onChange:b=>f(b.target.value)})]}),e.jsxs(B,{onClick:y,disabled:!d.trim()||o.isPending,children:[e.jsx(rn,{className:"h-4 w-4 mr-1"}),"Add"]})]})]})]})})}function zer(){const{data:s,isLoading:t}=rrs(),{data:n}=eie(),[r,a]=_.useState("list"),[i,l]=_.useState(""),[o,c]=_.useState("active"),[d,u]=_.useState("all"),[h,m]=_.useState("all"),[p,f]=_.useState(!1),[y,v]=_.useState(!1),g=_.useMemo(()=>{if(!s)return[];const S=new Map;return s.forEach(C=>{C.deal&&S.set(C.deal.id,C.deal.deal_name)}),Array.from(S,([C,E])=>({id:C,name:E}))},[s]),b=_.useMemo(()=>s?s.filter(S=>{var D,O,V,G;const C=i.toLowerCase(),E=!C||S.title.toLowerCase().includes(C)||((O=(D=S.deal)==null?void 0:D.deal_name)==null?void 0:O.toLowerCase().includes(C))||`${((V=S.contact)==null?void 0:V.first_name)||""} ${((G=S.contact)==null?void 0:G.last_name)||""}`.toLowerCase().includes(C),P=o==="all"||o==="active"&&S.status!=="done"||o==="todo"&&S.status==="todo"||o==="in_progress"&&S.status==="in_progress"||o==="done"&&S.status==="done"||o==="overdue"&&S.status!=="done"&&S.due_date&&X4(py(S.due_date))&&!yy(py(S.due_date)),M=d==="all"||S.priority===d,I=h==="all"||h==="no_deal"&&!S.deal_id||S.deal_id===h;return E&&P&&M&&I}):[],[s,i,o,d,h]),j=_.useMemo(()=>{if(!s)return{total:0,overdue:0,dueToday:0,dueThisWeek:0,completed:0};const S=s.filter(C=>C.status!=="done");return{total:S.length,overdue:S.filter(C=>C.due_date&&X4(py(C.due_date))&&!yy(py(C.due_date))).length,dueToday:S.filter(C=>C.due_date&&yy(py(C.due_date))).length,dueThisWeek:S.filter(C=>C.due_date&&YAs(py(C.due_date))).length,completed:s.filter(C=>C.status==="done").length}},[s]);return e.jsx(zs,{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(B,{variant:"outline",size:"sm",onClick:()=>v(!0),children:[e.jsx(D_,{className:"h-4 w-4 mr-1"}),"Templates"]}),e.jsxs(B,{size:"sm",onClick:()=>f(!0),children:[e.jsx(rn,{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(A0,{className:"h-3.5 w-3.5"}),"Active"]}),e.jsx("p",{className:"text-xl font-bold mt-1",children:j.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(xl,{className:"h-3.5 w-3.5"}),"Overdue"]}),e.jsx("p",{className:"text-xl font-bold mt-1 text-destructive",children:j.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(Gr,{className:"h-3.5 w-3.5"}),"Due Today"]}),e.jsx("p",{className:"text-xl font-bold mt-1",children:j.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(pc,{className:"h-3.5 w-3.5"}),"This Week"]}),e.jsx("p",{className:"text-xl font-bold mt-1",children:j.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(Er,{className:"h-3.5 w-3.5"}),"Completed"]}),e.jsx("p",{className:"text-xl font-bold mt-1",children:j.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(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search tasks...",value:i,onChange:S=>l(S.target.value),className:"pl-9"})]}),e.jsxs(is,{value:d,onValueChange:u,children:[e.jsx(rs,{className:"w-[130px]",children:e.jsx(ls,{placeholder:"Priority"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Priorities"}),e.jsx(He,{value:"urgent",children:"🔴 Urgent"}),e.jsx(He,{value:"high",children:"🟠 High"}),e.jsx(He,{value:"medium",children:"🟡 Medium"}),e.jsx(He,{value:"low",children:"🟢 Low"})]})]}),e.jsxs(is,{value:h,onValueChange:m,children:[e.jsx(rs,{className:"w-[160px]",children:e.jsx(ls,{placeholder:"Deal"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Deals"}),e.jsx(He,{value:"no_deal",children:"No Deal"}),g.map(S=>e.jsx(He,{value:S.id,children:S.name},S.id))]})]}),e.jsxs("div",{className:"flex items-center border rounded-lg p-0.5 ml-auto",children:[e.jsx("button",{onClick:()=>a("list"),className:`p-1.5 rounded-md transition-colors ${r==="list"?"bg-primary text-primary-foreground":"text-muted-foreground hover:text-foreground"}`,children:e.jsx(A0,{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(mj,{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(pc,{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(Mer,{tasks:b}),r==="kanban"&&e.jsx(Ier,{tasks:b}),r==="calendar"&&e.jsx(Rer,{tasks:b})]}),e.jsx(drs,{open:p,onOpenChange:f}),e.jsx(Oer,{open:y,onOpenChange:v,stages:n||[]})]})})}function Ber(s){const t=Gat(s);return t?t.toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric"}):""}function Uer({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 Lde({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:At("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 qer(){const s=Fn(),{data:t,isLoading:n}=jJn(),r=tDe(),[a,i]=_.useState(""),[l,o]=_.useState(!1),[c,d]=_.useState("all"),u=_.useMemo(()=>{let b=t||[];c==="contract"&&(b=b.filter(S=>!!S.contract_date));const j=a.trim().toLowerCase();return j&&(b=b.filter(S=>{var C,E,P,M;return((C=S.deal_name)==null?void 0:C.toLowerCase().includes(j))||((E=S.property_address)==null?void 0:E.toLowerCase().includes(j))||`${((P=S.contact)==null?void 0:P.first_name)??""} ${((M=S.contact)==null?void 0:M.last_name)??""}`.toLowerCase().includes(j)})),b},[t,a,c]),h=_.useMemo(()=>{const b=[];return(u||[]).forEach(j=>{tQ.forEach(S=>{const C=j[S.key],E=H5(C);C&&E!==null&&E<=30&&b.push({id:`${j.id}-${S.key}`,kind:"date",label:S.label,dealId:j.id,dealName:j.deal_name,date:C,days:E})}),j.tasks.filter(S=>S.status!=="done"&&S.due_date).forEach(S=>{const C=H5(S.due_date);C!==null&&C<=30&&b.push({id:S.id,kind:"task",label:S.title,dealId:j.id,dealName:j.deal_name,date:S.due_date,days:C,priority:S.priority})})}),b.sort((j,S)=>j.days-S.days)},[u]),m=_.useMemo(()=>({overdue:h.filter(b=>b.days<0),today:h.filter(b=>b.days===0),week:h.filter(b=>b.days>0&&b.days<=7),later:h.filter(b=>b.days>7)}),[h]),p=_.useMemo(()=>{const b=t||[],j=b.filter(E=>{const P=H5(E.target_close_date);return P!==null&&P>=0&&P<=7}).length,S=b.reduce((E,P)=>E+P.tasks.filter(M=>{const I=H5(M.due_date);return M.status!=="done"&&I!==null&&I<0}).length,0),C=b.reduce((E,P)=>E+(Number(P.expected_price)||0),0);return{active:b.length,closingSoon:j,overdueTasks:S,volume:C}},[t]),f=b=>b.tasks.length===0?0:b.tasks.filter(j=>j.status==="done").length/b.tasks.length*100,y=b=>s(`/mission-control/pipeline?deal=${b}`),v=async b=>{try{await r.mutateAsync({id:b,status:"done"}),se.success("Task completed")}catch{se.error("Could not update task")}},g=({title:b,items:j,tone:S})=>{if(j.length===0)return null;const C=S==="danger"?"bg-destructive":S==="warn"?"bg-amber-500":"bg-primary";return e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2 px-1",children:[e.jsx("span",{className:At("h-1.5 w-1.5 rounded-full",C)}),e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:b}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",j.length,")"]})]}),j.slice(0,12).map(E=>e.jsxs("div",{className:At("group flex items-center gap-3 rounded-lg border px-3 py-2 transition-colors hover:bg-muted/50",S==="danger"&&"border-destructive/30 bg-destructive/5"),children:[E.kind==="task"?e.jsx($a,{className:"shrink-0",onCheckedChange:()=>v(E.id),"aria-label":`Complete ${E.label}`}):e.jsx(Qd,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("button",{type:"button",onClick:()=>y(E.dealId),className:"flex-1 min-w-0 text-left",children:[e.jsx("p",{className:"text-sm font-medium leading-tight truncate",children:E.label}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[E.dealName," · ",Ber(E.date)]})]}),e.jsx("span",{className:At("text-[11px] font-semibold shrink-0 tabular-nums",E.days<0?"text-destructive":E.days<=3?"text-amber-600":"text-muted-foreground"),children:E.days<0?`${Math.abs(E.days)}d late`:E.days===0?"Today":`${E.days}d`})]},E.id))]})};return e.jsxs(zs,{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(B,{onClick:()=>o(!0),className:"gap-2 shrink-0",children:[e.jsx(Sx,{className:"h-4 w-4"}),"Playbooks"]})]}),e.jsxs("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-3",children:[e.jsx(Lde,{icon:qf,label:"Active transactions",value:p.active}),e.jsx(Lde,{icon:gu,label:"Closing within 7 days",value:p.closingSoon,tone:"warn"}),e.jsx(Lde,{icon:xl,label:"Overdue tasks",value:p.overdueTasks,tone:p.overdueTasks>0?"danger":"good"}),e.jsx(Lde,{icon:Nl,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(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search transactions, addresses, or clients...",value:a,onChange:b=>i(b.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex gap-1 rounded-lg border p-1 bg-card",children:[e.jsx(B,{size:"sm",variant:c==="all"?"default":"ghost",onClick:()=>d("all"),className:"h-8",children:"All active"}),e.jsx(B,{size:"sm",variant:c==="contract"?"default":"ghost",onClick:()=>d("contract"),className:"h-8",children:"Under contract"})]})]}),n?e.jsx("div",{className:"flex justify-center py-20",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"grid lg:grid-cols-5 gap-6",children:[e.jsx("div",{className:"lg:col-span-2 space-y-4",children:e.jsxs("div",{className:"rounded-xl border bg-card p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(Qd,{className:"h-4 w-4 text-primary"}),e.jsx("h2",{className:"text-sm font-semibold",children:"Deadline Radar"}),e.jsx(Oe,{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(Er,{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(g,{title:"Overdue",items:m.overdue,tone:"danger"}),e.jsx(g,{title:"Today",items:m.today,tone:"warn"}),e.jsx(g,{title:"This week",items:m.week,tone:"warn"}),e.jsx(g,{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(Jr,{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(B,{variant:"outline",className:"mt-4",onClick:()=>s("/mission-control/pipeline"),children:"Go to Deal Pipeline"})]}):u.map(b=>{const j=f(b),S=H5(b.target_close_date),C=b.tasks.filter(M=>M.status!=="done"),E=C.filter(M=>{const I=H5(M.due_date);return I!==null&&I<0}),P=C.filter(M=>M.due_date).sort((M,I)=>(H5(M.due_date)??0)-(H5(I.due_date)??0))[0];return e.jsx("button",{type:"button",onClick:()=>y(b.id),className:"w-full text-left rounded-xl border bg-card p-4 hover:border-primary/40 hover:shadow-sm transition-all group",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx(Uer,{value:j}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-semibold truncate group-hover:text-primary transition-colors",children:b.deal_name}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[b.property_address||"Address TBD",b.contact&&` · ${b.contact.first_name} ${b.contact.last_name}`]})]}),e.jsx(xi,{className:"h-4 w-4 text-muted-foreground shrink-0 mt-0.5"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mt-2",children:[b.stage&&e.jsx("span",{className:"text-[10px] px-2 py-0.5 rounded-full font-medium",style:{backgroundColor:`${b.stage.color}1f`,color:b.stage.color},children:b.stage.name}),e.jsx(Oe,{variant:"outline",className:"text-[10px] capitalize",children:b.deal_type}),S!==null&&e.jsx(Oe,{variant:"secondary",className:At("text-[10px]",S<0&&"bg-destructive/10 text-destructive",S>=0&&S<=7&&"bg-amber-500/10 text-amber-700 dark:text-amber-400"),children:S<0?`Closing ${Math.abs(S)}d overdue`:`Closes in ${S}d`}),E.length>0&&e.jsxs(Oe,{className:"text-[10px] bg-destructive/10 text-destructive hover:bg-destructive/10",children:[E.length," overdue"]})]}),e.jsxs("div",{className:"mt-3",children:[e.jsx(Fi,{value:j,className:"h-1.5"}),e.jsxs("div",{className:"flex items-center justify-between mt-1.5 gap-2",children:[e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:[b.tasks.filter(M=>M.status==="done").length," of"," ",b.tasks.length," steps complete"]}),P&&e.jsxs("p",{className:"text-[11px] text-muted-foreground truncate max-w-[55%]",children:["Next: ",P.title]})]})]}),b.tasks.length===0&&e.jsx("p",{className:"text-[11px] text-muted-foreground mt-2 italic",children:"No checklist yet — open the deal and apply a playbook."})]})]})},b.id)})})]})]}),e.jsx(nrs,{open:l,onOpenChange:o})]})}function urs(){const s=ha();return at({queryKey:["portal-referrals",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("portal_referrals").select("*, client_portals!inner(slug, client_name, deal_id)").eq("owner_user_id",s).order("created_at",{ascending:!1});if(n)throw n;return t||[]},enabled:!!s})}function $er(){const s=Bt();return mt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("portal_referrals").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["portal-referrals"]})}})}function Ver(){const s=Bt();return mt({mutationFn:async t=>{const{error:n}=await q.from("portal_referrals").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["portal-referrals"]})}})}const Her=s=>new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(s)),jBe=[{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"}],Ger={buying:"Buying",selling:"Selling",both:"Buying & Selling",unsure:"Not sure yet"};function hrs(){const{data:s=[],isLoading:t}=urs(),n=$er(),r=Ver(),[a,i]=_.useState("all"),[l,o]=_.useState({}),c=_.useMemo(()=>a==="all"?s:s.filter(p=>p.status===a),[s,a]),d=_.useMemo(()=>({total:s.length,new:s.filter(p=>p.status==="new").length,converted:s.filter(p=>p.status==="converted").length}),[s]),u=(p,f)=>{n.mutate({id:p.id,status:f}),se.success("Status updated")},h=p=>{const f=l[p.id];n.mutate({id:p.id,agent_notes:f}),o(y=>{const{[p.id]:v,...g}=y;return g}),se.success("Notes saved")},m=async p=>{await Xi(`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(Vo,{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"},...jBe.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(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):c.length===0?e.jsx(ve,{children:e.jsxs(Me,{className:"py-12 text-center",children:[e.jsx(Vo,{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 g,b;const f=jBe.find(j=>j.value===p.status),y=(g=p.client_portals)==null?void 0:g.slug,v=p.referrer_name||((b=p.client_portals)==null?void 0:b.client_name)||"Anonymous client";return e.jsxs(ve,{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(St,{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(ga,{className:"h-3 w-3"}),"Referred by ",e.jsx("span",{className:"font-medium text-foreground",children:v})," ·"," ",Her(p.created_at)]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Oe,{variant:"outline",className:f==null?void 0:f.className,children:(f==null?void 0:f.label)||p.status}),e.jsxs(is,{value:p.status,onValueChange:j=>u(p,j),children:[e.jsx(rs,{className:"h-8 w-[130px] text-xs",children:e.jsx(ls,{})}),e.jsx(as,{children:jBe.map(j=>e.jsx(He,{value:j.value,className:"text-xs",children:j.label},j.value))})]})]})]})}),e.jsxs(Me,{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[p.friend_interest&&e.jsx(Oe,{variant:"secondary",className:"text-xs",children:Ger[p.friend_interest]||p.friend_interest}),p.friend_email&&e.jsxs("a",{href:`mailto:${p.friend_email}`,className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(ln,{className:"h-3 w-3"}),p.friend_email]}),p.friend_phone&&e.jsxs(e.Fragment,{children:[e.jsxs("a",{href:`tel:${p.friend_phone}`,className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(_a,{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(Ou,{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(Ms,{value:l[p.id],onChange:j=>o(S=>({...S,[p.id]:j.target.value})),rows:3,className:"text-sm"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{size:"sm",onClick:()=>h(p),children:"Save"}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>o(j=>{const{[p.id]:S,...C}=j;return C}),children:"Cancel"})]})]}):e.jsx("button",{onClick:()=>o(j=>({...j,[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:[y&&e.jsxs("a",{href:`/portal/${y}`,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-muted-foreground hover:text-primary inline-flex items-center gap-1",children:[e.jsx(wr,{className:"h-3 w-3"}),"View source portal"]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>m(p),className:"text-destructive hover:text-destructive ml-auto h-8",children:e.jsx(Sn,{className:"h-3.5 w-3.5"})})]})]})]},p.id)})})]})}function mrs({vendor:s,onEdit:t,onDelete:n,onToggleVisible:r,isVisible:a,showOwnerBadge:i,clickCount:l}){var c;const o=((c=pW.find(d=>d.value===s.category))==null?void 0:c.label)||s.category;return e.jsxs(ve,{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(ec,{className:"w-3.5 h-3.5 text-amber-600","aria-label":"Required"}),s.is_featured&&e.jsx(Da,{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(Oe,{variant:"secondary",className:"text-[10px]",children:o}),i==="brokerage"&&e.jsx(Oe,{variant:"outline",className:"text-[10px]",children:"Brokerage"}),i==="agent"&&e.jsx(Oe,{variant:"outline",className:"text-[10px]",children:"Personal"}),!s.is_active&&e.jsx(Oe,{variant:"destructive",className:"text-[10px]",children:"Inactive"}),typeof l=="number"&&l>0&&e.jsxs(Oe,{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(_a,{className:"w-3 h-3"}),s.phone]}),s.email&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ln,{className:"w-3 h-3"}),e.jsx("span",{className:"truncate",children:s.email})]}),s.website&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(sl,{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(ga,{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(Xa,{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(B,{size:"sm",variant:a?"default":"outline",onClick:()=>r(!a),disabled:s.is_required&&!a,className:"flex-1",children:[a?e.jsx(ya,{className:"w-3.5 h-3.5 mr-1.5"}):e.jsx(Ax,{className:"w-3.5 h-3.5 mr-1.5"}),a?"Showing in portals":"Hidden"]}),t&&e.jsx(B,{size:"sm",variant:"ghost",onClick:t,children:e.jsx(wp,{className:"w-3.5 h-3.5"})}),n&&e.jsx(B,{size:"sm",variant:"ghost",onClick:n,className:"text-destructive",children:e.jsx(Sn,{className:"w-3.5 h-3.5"})})]})]})}function prs({open:s,onOpenChange:t,vendor:n,ownerType:r,brokerageId:a,agentUserId:i,showBrokerageOnlyFields:l}){const o=RRs(),[c,d]=_.useState({}),[u,h]=_.useState(!1),m=_.useRef(null),p=async v=>{if(!v.type.startsWith("image/")){se.error("Please select an image");return}if(v.size>5*1024*1024){se.error("Image must be under 5MB");return}h(!0);try{const g=v.name.split(".").pop()||"png",b=`${r}/${a||i||"misc"}/${Date.now()}.${g}`,{error:j}=await q.storage.from("vendor-logos").upload(b,v,{upsert:!0,contentType:v.type});if(j)throw j;const{data:S}=q.storage.from("vendor-logos").getPublicUrl(b);d(C=>({...C,logo_url:S.publicUrl})),se.success("Logo uploaded")}catch(g){se.error(g.message||"Upload failed")}finally{h(!1)}};_.useEffect(()=>{s&&d(n||{owner_type:r,owner_brokerage_id:r==="brokerage"&&a||null,owner_user_id:r==="agent"&&i||null,category:"other",action_type:"call",is_active:!0,is_featured:!1,is_required:!1})},[s,n,r,a,i]);const f=(v,g)=>d(b=>({...b,[v]:g})),y=async()=>{var v;if(!((v=c.name)!=null&&v.trim())){se.error("Name is required");return}try{await o.mutateAsync(c),se.success(n?"Vendor updated":"Vendor added"),t(!1)}catch(g){se.error(g.message||"Failed to save vendor")}};return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Ds,{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(J,{children:"Contact Name *"}),e.jsx(xe,{value:c.name||"",onChange:v=>f("name",v.target.value),placeholder:"Bob Smith"})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Company"}),e.jsx(xe,{value:c.company||"",onChange:v=>f("company",v.target.value),placeholder:"Smith Inspections"})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Category"}),e.jsxs(is,{value:c.category,onValueChange:v=>f("category",v),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsx(as,{children:pW.map(v=>e.jsx(He,{value:v.value,children:v.label},v.value))})]})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Phone"}),e.jsx(xe,{value:c.phone||"",onChange:v=>f("phone",v.target.value),placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Email"}),e.jsx(xe,{type:"email",value:c.email||"",onChange:v=>f("email",v.target.value),placeholder:"bob@smithinsp.com"})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Website"}),e.jsx(xe,{value:c.website||"",onChange:v=>f("website",v.target.value),placeholder:"https://..."})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Logo"}),e.jsx("input",{ref:m,type:"file",accept:"image/*",className:"hidden",onChange:v=>{var b;const g=(b=v.target.files)==null?void 0:b[0];g&&p(g),v.target.value=""}}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[c.logo_url?e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:c.logo_url,alt:"Vendor logo",className:"h-14 w-14 rounded-md object-cover border"}),e.jsx("button",{type:"button",onClick:()=>f("logo_url",""),className:"absolute -top-2 -right-2 bg-background border rounded-full p-0.5 shadow","aria-label":"Remove logo",children:e.jsx(Qn,{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(Oa,{className:"h-5 w-5"})}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:()=>{var v;return(v=m.current)==null?void 0:v.click()},disabled:u,children:[u?e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Oa,{className:"h-4 w-4 mr-2"}),c.logo_url?"Replace":"Upload Logo"]})]})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(J,{children:"Address"}),e.jsx(xe,{value:c.address||"",onChange:v=>f("address",v.target.value)})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(J,{children:"Description"}),e.jsx(Ms,{rows:3,value:c.description||"",onChange:v=>f("description",v.target.value),placeholder:"Why your clients should use this vendor..."})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Primary Action"}),e.jsxs(is,{value:c.action_type,onValueChange:v=>f("action_type",v),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsx(as,{children:LRs.map(v=>e.jsx(He,{value:v.value,children:v.label},v.value))})]})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Booking URL (Calendly etc.)"}),e.jsx(xe,{value:c.booking_url||"",onChange:v=>f("booking_url",v.target.value),placeholder:"https://calendly.com/..."})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(J,{children:"Compliance Disclosure (optional)"}),e.jsx(Ms,{rows:2,value:c.disclosure_text||"",onChange:v=>f("disclosure_text",v.target.value),placeholder:"e.g. Agent receives no compensation for this referral."})]}),e.jsxs("div",{className:"flex items-center justify-between md:col-span-2 border rounded-lg p-3",children:[e.jsxs("div",{children:[e.jsx(J,{className:"font-medium",children:"Active"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show this vendor in client portals"})]}),e.jsx(fn,{checked:!!c.is_active,onCheckedChange:v=>f("is_active",v)})]}),l&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between border rounded-lg p-3",children:[e.jsxs("div",{children:[e.jsx(J,{className:"font-medium",children:"Featured"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Highlight in agent library"})]}),e.jsx(fn,{checked:!!c.is_featured,onCheckedChange:v=>f("is_featured",v)})]}),e.jsxs("div",{className:"flex items-center justify-between border rounded-lg p-3",children:[e.jsxs("div",{children:[e.jsx(J,{className:"font-medium",children:"Required"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Agents cannot hide"})]}),e.jsx(fn,{checked:!!c.is_required,onCheckedChange:v=>f("is_required",v)})]})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(B,{onClick:y,disabled:o.isPending,children:o.isPending?"Saving...":"Save Vendor"})]})]})})}function frs({embedded:s=!1}={}){const t=ha(),{brokerageId:n}=hs(),{data:r,isLoading:a}=DRs(),{data:i={}}=B7t("agent",t),l=O7t(),o=FRs(),[c,d]=_.useState(null),[u,h]=_.useState(!1),[m,p]=_.useState(""),[f,y]=_.useState("all"),v=(r==null?void 0:r.vendors)||[],g=(r==null?void 0:r.selections)||[],b=_.useMemo(()=>{const D=new Map;return g.forEach(O=>D.set(O.vendor_id,O.is_visible)),D},[g]),j=_.useMemo(()=>v.filter(D=>!(f!=="all"&&D.category!==f||m&&!`${D.name} ${D.company||""}`.toLowerCase().includes(m.toLowerCase()))),[v,m,f]),S=j.filter(D=>D.owner_type==="agent"),C=j.filter(D=>D.owner_type==="brokerage"),E=async D=>{if(await Xi("Delete this vendor?"))try{await l.mutateAsync(D),se.success("Vendor deleted")}catch(O){se.error(O.message)}},P=async(D,O)=>{try{await o.mutateAsync({vendorId:D,isVisible:O})}catch(V){se.error(V.message)}},M=D=>D.is_required?!0:b.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(Cx,{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(B,{onClick:()=>{d(null),h(!0)},children:[e.jsx(rn,{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(Lr,{className:"w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),e.jsx(xe,{className:"pl-9",placeholder:"Search vendors...",value:m,onChange:D=>p(D.target.value)})]}),e.jsxs("select",{value:f,onChange:D=>y(D.target.value),className:"border rounded-md px-3 py-2 text-sm bg-background",children:[e.jsx("option",{value:"all",children:"All categories"}),pW.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(Yr,{defaultValue:n?"all":"personal",children:[e.jsxs(Zr,{children:[e.jsxs(Ht,{value:"all",children:["All (",j.length,")"]}),n&&e.jsxs(Ht,{value:"brokerage",children:["From Brokerage (",C.length,")"]}),e.jsxs(Ht,{value:"personal",children:["My Personal (",S.length,")"]})]}),e.jsx(Gt,{value:"all",className:"mt-4",children:e.jsx(NBe,{vendors:j,isVisibleInPortals:M,onToggle:P,onEdit:D=>{d(D),h(!0)},onDelete:E,userId:t,clicks:i})}),n&&e.jsx(Gt,{value:"brokerage",className:"mt-4",children:C.length===0?e.jsx(d4t,{icon:e.jsx(un,{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(NBe,{vendors:C,isVisibleInPortals:M,onToggle:P,userId:t,clicks:i})}),e.jsx(Gt,{value:"personal",className:"mt-4",children:S.length===0?e.jsx(d4t,{icon:e.jsx(Cx,{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(B,{onClick:()=>{d(null),h(!0)},children:[e.jsx(rn,{className:"w-4 h-4 mr-2"})," Add Your First Vendor"]})}):e.jsx(NBe,{vendors:S,isVisibleInPortals:M,onToggle:P,onEdit:D=>{d(D),h(!0)},onDelete:E,userId:t,clicks:i})})]}),e.jsx(prs,{open:u,onOpenChange:h,vendor:c,ownerType:"agent",agentUserId:t})]});return s?I:e.jsx(zs,{children:I})}function NBe({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(mrs,{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 d4t({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 Wer(s){return at({queryKey:["brokerage-form-folders",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("brokerage_form_folders").select("*").eq("brokerage_id",s).order("sort_order",{ascending:!0}).order("name",{ascending:!0});if(n)throw n;return t||[]}})}function Ker(s){const t=Bt(),n=()=>{t.invalidateQueries({queryKey:["brokerage-form-folders",s]}),t.invalidateQueries({queryKey:["form-templates"]})},r=mt({mutationFn:async o=>{var h;const{data:c}=await q.auth.getUser(),{data:d,error:u}=await q.from("brokerage_form_folders").insert({brokerage_id:s,name:o,created_by:((h=c.user)==null?void 0:h.id)??null}).select().single();if(u)throw u;return d},onSuccess:n}),a=mt({mutationFn:async({id:o,name:c})=>{const{error:d}=await q.from("brokerage_form_folders").update({name:c}).eq("id",o);if(d)throw d},onSuccess:n}),i=mt({mutationFn:async o=>{const{error:c}=await q.from("brokerage_form_folders").delete().eq("id",o);if(c)throw c},onSuccess:n}),l=mt({mutationFn:async({templateId:o,folderId:c})=>{const{error:d}=await q.from("form_templates").update({folder_id:c}).eq("id",o);if(d)throw d},onSuccess:n});return{createFolder:r,renameFolder:a,deleteFolder:i,moveTemplate:l}}function Yer({status:s}){return s==="mapped"?e.jsx(Oe,{className:"bg-emerald-500/15 text-emerald-600 hover:bg-emerald-500/15",children:"Ready"}):s==="needs_placement"?e.jsx(Oe,{variant:"outline",children:"Needs field placement"}):e.jsx(Oe,{variant:"secondary",children:"Needs mapping"})}function Zer(){const{brokerageId:s,isBrokerageManager:t,isAdmin:n,loading:r}=hs(),{data:a=[],isLoading:i}=qQn(s),l=Yns(),o=Zns(),[c,d]=_.useState(!1),[u,h]=_.useState(null),[m,p]=_.useState(null),[f,y]=_.useState(null),[v,g]=_.useState(""),[b,j]=_.useState("all"),{data:S=[]}=Wer(s),{createFolder:C,deleteFolder:E,moveTemplate:P}=Ker(s),M=async()=>{var H;const $=(H=window.prompt("Folder name (for example: Onboarding, Listing paperwork)"))==null?void 0:H.trim();if($)try{const Y=await C.mutateAsync($);j(Y.id),se.success("Folder created")}catch(Y){se.error((Y==null?void 0:Y.message)||"Could not create the folder")}};if(r)return e.jsx(zs,{children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!t&&!n)return e.jsx(zs,{children:e.jsx("div",{className:"p-8 text-center",children:e.jsx("h2",{className:"text-xl font-semibold",children:"Brokerage managers only"})})});const I=a.filter($=>$.name.toLowerCase().includes(v.trim().toLowerCase())).filter($=>b==="all"?!0:b==="unfiled"?!$.folder_id:$.folder_id===b),D=m?a.find($=>$.id===m.id)||m:null,O=_x(D),V=async($,H)=>{const Y=_x($);if(H&&(Y==null?void 0:Y.mapping_status)!=="mapped"){se.error("Map and place the fields before publishing this form to your agents.");return}try{await l.mutateAsync({id:$.id,patch:{is_published:H}}),se.success(H?"Published to your agents":"Unpublished — agents can no longer use it")}catch(Z){se.error((Z==null?void 0:Z.message)||"Could not update the form")}},G=async $=>{if(await Xi(`Delete "${$.name}"? Agents will lose access. Forms already generated stay on their deals.`))try{await o.mutateAsync($),(m==null?void 0:m.id)===$.id&&p(null),se.success("Form deleted")}catch(H){se.error((H==null?void 0:H.message)||"Could not delete the form")}};return e.jsxs(zs,{children:[e.jsxs("div",{className:"mx-auto w-full max-w-6xl space-y-6 px-4 py-6 sm:px-6",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Brokerage Forms"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Build the official set of forms your agents can pick from. Map the fields once, publish, and every agent can fill them straight from a deal."})]}),e.jsxs(B,{onClick:()=>d(!0),children:[e.jsx(rn,{className:"mr-2 h-4 w-4"})," Upload form"]})]}),e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center",children:[e.jsxs("div",{className:"relative max-w-sm flex-1",children:[e.jsx(Lr,{className:"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(xe,{className:"pl-9",placeholder:"Search forms…",value:v,onChange:$=>g($.target.value)})]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:M,children:[e.jsx(MQ,{className:"mr-2 h-4 w-4"})," New folder"]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(B,{size:"sm",variant:b==="all"?"default":"outline",onClick:()=>j("all"),children:"All forms"}),S.map($=>e.jsxs("div",{className:"flex items-center",children:[e.jsxs(B,{size:"sm",variant:b===$.id?"default":"outline",className:"rounded-r-none",onClick:()=>j($.id),children:[e.jsx(Rq,{className:"mr-2 h-4 w-4"}),$.name]}),e.jsx(B,{size:"sm",variant:b===$.id?"default":"outline",className:"rounded-l-none border-l-0 px-2","aria-label":`Delete ${$.name} folder`,onClick:async()=>{await Xi(`Delete the "${$.name}" folder? The forms inside stay in your library.`)&&(await E.mutateAsync($.id),b===$.id&&j("all"))},children:e.jsx(Sn,{className:"h-3.5 w-3.5"})})]},$.id)),S.length>0&&e.jsx(B,{size:"sm",variant:b==="unfiled"?"default":"outline",onClick:()=>j("unfiled"),children:"Unfiled"})]}),i&&e.jsx("div",{className:"flex justify-center py-16",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})}),!i&&a.length===0&&e.jsx(ve,{className:"border-dashed",children:e.jsxs(Me,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx("div",{className:"flex h-12 w-12 items-center justify-center rounded-full bg-muted",children:e.jsx(ai,{className:"h-6 w-6 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"No brokerage forms yet"}),e.jsx("p",{className:"mx-auto max-w-sm text-sm text-muted-foreground",children:"Upload the blank PDFs your office uses. Once you map their fields and publish, your agents can pick them from their Forms library and Deal → Forms tab."})]}),e.jsxs(B,{onClick:()=>d(!0),children:[e.jsx(Oa,{className:"mr-2 h-4 w-4"})," Upload your first form"]})]})}),!i&&a.length>0&&e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:[I.map($=>{var Y;const H=_x($);return e.jsx(ve,{className:"transition-shadow hover:shadow-md",children:e.jsxs(Me,{className:"space-y-3 p-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-primary/10",children:e.jsx(Fr,{className:"h-5 w-5 text-primary"})}),e.jsxs("button",{className:"min-w-0 flex-1 text-left",onClick:()=>p($),children:[e.jsx("p",{className:"truncate font-medium",children:$.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(Y=Rat.find(Z=>Z.value===$.category))==null?void 0:Y.label," · v",(H==null?void 0:H.version_number)??1,H?` · ${H.page_count} page${H.page_count===1?"":"s"}`:""]})]}),e.jsxs(tu,{children:[e.jsx(su,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(Xx,{className:"h-4 w-4"})})}),e.jsxs(Od,{align:"end",children:[e.jsx(ca,{onClick:()=>p($),children:"Open & map fields"}),e.jsxs(ca,{onClick:()=>y($),children:[e.jsx(sf,{className:"mr-2 h-4 w-4"})," Place fields & signatures"]}),e.jsxs(ca,{onClick:()=>h($),children:[e.jsx(Oa,{className:"mr-2 h-4 w-4"})," Upload new version"]}),S.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(M0,{}),e.jsx(PP,{className:"text-xs font-normal text-muted-foreground",children:"Move to folder"}),S.map(Z=>e.jsxs(ca,{disabled:$.folder_id===Z.id,onClick:()=>P.mutate({templateId:$.id,folderId:Z.id}),children:[e.jsx(Rq,{className:"mr-2 h-4 w-4"})," ",Z.name]},Z.id)),$.folder_id&&e.jsx(ca,{onClick:()=>P.mutate({templateId:$.id,folderId:null}),children:"Remove from folder"}),e.jsx(M0,{})]}),e.jsxs(ca,{onClick:()=>l.mutate({id:$.id,patch:{is_archived:!0,is_published:!1}}),children:[e.jsx(by,{className:"mr-2 h-4 w-4"})," Archive"]}),e.jsxs(ca,{className:"text-destructive",onClick:()=>G($),children:[e.jsx(Sn,{className:"mr-2 h-4 w-4"})," Delete"]})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Yer,{status:H==null?void 0:H.mapping_status}),e.jsxs("label",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[$.is_published?"Published":"Draft",e.jsx(fn,{checked:!!$.is_published,onCheckedChange:Z=>V($,Z)})]})]})]})},$.id)}),I.length===0&&e.jsx("p",{className:"col-span-full py-10 text-center text-sm text-muted-foreground",children:"No forms match that search."})]})]}),e.jsx(qg,{open:!!D,onOpenChange:$=>!$&&p(null),children:e.jsxs(hg,{side:"right",className:"w-full overflow-y-auto sm:max-w-2xl",children:[e.jsxs(P0,{className:"space-y-1 text-left",children:[e.jsx(L0,{children:D==null?void 0:D.name}),O&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["v",O.version_number," · ",O.file_name," ·"," ",Oat(O.file_size)," · uploaded"," ",Hs(new Date(O.created_at),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"mt-5 space-y-4",children:[(D==null?void 0:D.description)&&e.jsx("p",{className:"text-sm text-muted-foreground",children:D.description}),O?e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"outline",className:"w-full",onClick:()=>D&&y(D),children:[e.jsx(sf,{className:"mr-2 h-4 w-4"})," Place fields & signatures on the document"]}),e.jsx(ors,{version:O})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"This form has no uploaded version yet."})]})]})}),e.jsx(w6e,{open:c,onOpenChange:d,brokerageId:s}),e.jsx(w6e,{open:!!u,onOpenChange:$=>!$&&h(null),templateId:u==null?void 0:u.id,templateName:u==null?void 0:u.name,brokerageId:s}),f&&_x(f)&&e.jsx(lrs,{open:!0,onOpenChange:$=>!$&&y(null),version:_x(f),templateName:f.name})]})}function Xer(){const{brokerageId:s,isBrokerageManager:t,isAdmin:n,loading:r}=hs(),{data:a=[],isLoading:i}=IRs(s),{data:l={}}=B7t("brokerage",s),o=O7t(),[c,d]=_.useState(null),[u,h]=_.useState(!1),[m,p]=_.useState(""),[f,y]=_.useState("all");if(r)return e.jsx(zs,{children:e.jsx("div",{className:"p-8",children:"Loading..."})});if(!t&&!n)return e.jsx(zs,{children:e.jsx("div",{className:"p-8 text-center",children:e.jsx("h2",{className:"text-xl font-semibold",children:"Brokerage managers only"})})});const v=a.filter(b=>!(f!=="all"&&b.category!==f||m&&!`${b.name} ${b.company||""}`.toLowerCase().includes(m.toLowerCase()))),g=async b=>{if(await Xi("Delete this vendor? This will remove it from all agent libraries."))try{await o.mutateAsync(b),se.success("Vendor deleted")}catch(j){se.error(j.message)}};return e.jsx(zs,{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(B,{onClick:()=>{d(null),h(!0)},children:[e.jsx(rn,{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(Lr,{className:"w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),e.jsx(xe,{className:"pl-9",placeholder:"Search vendors...",value:m,onChange:b=>p(b.target.value)})]}),e.jsxs("select",{value:f,onChange:b=>y(b.target.value),className:"border rounded-md px-3 py-2 text-sm bg-background",children:[e.jsx("option",{value:"all",children:"All categories"}),pW.map(b=>e.jsx("option",{value:b.value,children:b.label},b.value))]})]}),i?e.jsx("div",{className:"text-center text-muted-foreground py-12",children:"Loading vendors..."}):v.length===0?e.jsxs("div",{className:"text-center py-16 border-2 border-dashed rounded-xl",children:[e.jsx(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(B,{onClick:()=>{d(null),h(!0)},children:[e.jsx(rn,{className:"w-4 h-4 mr-2"})," Add Your First Vendor"]})]}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:v.map(b=>e.jsx(mrs,{vendor:b,onEdit:()=>{d(b),h(!0)},onDelete:()=>g(b.id),clickCount:l[b.id]},b.id))}),e.jsx(prs,{open:u,onOpenChange:h,vendor:c,ownerType:"brokerage",brokerageId:s,showBrokerageOnlyFields:!0})]})})}function xrs({portalId:s,portalSlug:t,clientName:n,agentName:r}){const{data:a,isLoading:i}=$7t(s),l=V7t(),o=BRs(),[c,d]=_.useState(""),u=_.useRef(null),h=(a||[]).filter(p=>p.sender_type==="client"&&!p.read_at).length;_.useEffect(()=>{h>0&&o.mutate(s)},[h,s]),_.useEffect(()=>{var p;(p=u.current)==null||p.scrollIntoView({block:"nearest"})},[a==null?void 0:a.length]);const m=async()=>{const p=c.trim();if(p)try{await l.mutateAsync({portalId:s,senderType:"agent",senderName:r||null,body:p,portalUrl:t?`https://clients.relevelup.com/${t}`:void 0}),d(""),se.success("Message sent — your client was emailed")}catch(f){se.error((f==null?void 0:f.message)||"Could not send message")}};return e.jsx(ve,{children:e.jsxs(Me,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("h3",{className:"font-semibold",children:["Conversation with ",n||"your client"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Both sides get an email for every message"})]}),e.jsxs("div",{className:"space-y-3 max-h-[420px] overflow-y-auto pr-1",children:[i&&e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(Ct,{className:"w-4 h-4 animate-spin text-muted-foreground"})}),!i&&(!a||a.length===0)&&e.jsxs("div",{className:"text-center py-10 border-2 border-dashed rounded-lg",children:[e.jsx("p",{className:"text-sm font-medium",children:"No messages yet"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Start the conversation — your client can reply right inside their portal."})]}),a==null?void 0:a.map(p=>{const f=p.sender_type==="agent";return e.jsx("div",{className:`flex ${f?"justify-end":"justify-start"}`,children:e.jsxs("div",{className:`max-w-[80%] rounded-lg px-3 py-2 border ${f?"bg-primary/10 border-primary/20":"bg-muted border-border"}`,children:[e.jsxs("p",{className:"text-[11px] text-muted-foreground mb-1",children:[f?r||"You":p.sender_name||n||"Client"," ·"," ",Hs(new Date(p.created_at),"MMM d, h:mm a")]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:p.body})]})},p.id)}),e.jsx("div",{ref:u})]}),e.jsxs("div",{className:"mt-4 space-y-2",children:[e.jsx(Ms,{value:c,onChange:p=>d(p.target.value),rows:3,placeholder:`Reply to ${n||"your client"}...`}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(B,{onClick:m,disabled:l.isPending||!c.trim(),size:"sm",children:[l.isPending?e.jsx(Ct,{className:"w-4 h-4 mr-1.5 animate-spin"}):e.jsx(Or,{className:"w-4 h-4 mr-1.5"}),"Send & notify"]})})]})]})})}function Qer({selectedPortalId:s,onSelectPortal:t}){const{data:n,isLoading:r}=H7t(),[a,i]=_.useState(""),[l,o]=_.useState(!1),[c,d]=_.useState(s??null);_.useEffect(()=>{s&&d(s)},[s]);const u=_.useMemo(()=>{const f=a.trim().toLowerCase();return(n||[]).filter(y=>l&&y.unreadCount===0?!1:f?(y.clientName||"").toLowerCase().includes(f)||(y.clientEmail||"").toLowerCase().includes(f):!0)},[n,a,l]),h=_.useRef(!1);_.useEffect(()=>{if(h.current||c||u.length===0)return;h.current=!0;const f=u.find(y=>y.messageCount>0)||u[0];d(f.portalId)},[u,c]);const m=f=>{h.current=!0,d(f),t==null||t(f)},p=(n||[]).find(f=>f.portalId===c)||null;return r?e.jsx("div",{className:"flex justify-center py-16",children:e.jsx(Ct,{className:"w-5 h-5 animate-spin text-muted-foreground"})}):!n||n.length===0?e.jsx(ve,{children:e.jsxs(Me,{className:"p-10 text-center",children:[e.jsx(Hi,{className:"w-6 h-6 mx-auto text-muted-foreground mb-3"}),e.jsx("p",{className:"font-medium",children:"No client portals yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Create a portal from a deal and your conversations will appear here."})]})}):e.jsxs("div",{className:"grid gap-4 md:grid-cols-[320px_1fr]",children:[e.jsx("div",{className:`${p?"hidden md:block":"block"}`,children:e.jsxs(ve,{className:"overflow-hidden",children:[e.jsxs("div",{className:"p-3 space-y-2 border-b",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Lr,{className:"w-4 h-4 absolute left-2.5 top-1/2 -translate-y-1/2 text-muted-foreground"}),e.jsx(xe,{value:a,onChange:f=>i(f.target.value),placeholder:"Search clients",className:"pl-8"})]}),e.jsx(B,{variant:l?"default":"outline",size:"sm",onClick:()=>o(f=>!f),children:"Unread only"})]}),e.jsxs("div",{className:"max-h-[560px] overflow-y-auto divide-y",children:[u.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground p-4",children:"No conversations match."}),u.map(f=>{const y=f.portalId===c;return e.jsxs("button",{onClick:()=>m(f.portalId),className:`w-full text-left p-3 transition-colors hover:bg-muted/60 ${y?"bg-muted":""}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"font-medium text-sm truncate",children:f.clientName||"Unnamed client"}),f.unreadCount>0&&e.jsx(Oe,{className:"shrink-0",children:f.unreadCount})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate mt-0.5",children:f.lastMessage?`${f.lastMessage.sender_type==="agent"?"You: ":""}${f.lastMessage.body}`:"No messages yet"}),f.lastMessage&&e.jsx("p",{className:"text-[11px] text-muted-foreground mt-1",children:Ed(new Date(f.lastMessage.created_at),{addSuffix:!0})})]},f.portalId)})]})]})}),e.jsx("div",{className:`${p?"block":"hidden md:block"}`,children:p?e.jsxs("div",{className:"space-y-3",children:[e.jsxs(B,{variant:"ghost",size:"sm",className:"md:hidden",onClick:()=>m(null),children:[e.jsx(ka,{className:"w-4 h-4 mr-1.5"}),"All conversations"]}),e.jsx(xrs,{portalId:p.portalId,portalSlug:p.slug,clientName:p.clientName})]}):e.jsx(ve,{children:e.jsx(Me,{className:"p-10 text-center text-sm text-muted-foreground",children:"Pick a client to see the conversation."})})})]})}const Jer=[{value:"overview",label:"Portals",icon:sf},{value:"messages",label:"Messages",icon:Hi},{value:"vendors",label:"Vendors",icon:wv},{value:"referrals",label:"Referrals",icon:Vo},{value:"branding",label:"Branding",icon:Xc},{value:"questions",label:"Onboarding",icon:Ny}];function etr(){const[s,t]=Yl(),n=s.get("tab")||"overview",[r,a]=_.useState(n),[i,l]=_.useState(!1),[o,c]=_.useState(!1),d=s.get("portal"),{data:u}=H7t(),h=(u||[]).reduce((m,p)=>m+p.unreadCount,0);return _.useEffect(()=>{t(m=>{const p=new URLSearchParams(m);return p.set("tab",r),r!=="messages"&&p.delete("portal"),p},{replace:!0})},[r,t]),e.jsxs(zs,{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(un,{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(p7,{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(B,{asChild:!0,variant:"outline",size:"sm",className:"shrink-0",children:e.jsx(ir,{to:"/mission-control/pipeline",children:"Open Deal Pipeline"})})]})}),e.jsxs(Yr,{value:r,onValueChange:a,className:"w-full",children:[e.jsx(Zr,{className:"w-full justify-start overflow-x-auto h-auto flex-wrap",children:Jer.map(m=>e.jsxs(Ht,{value:m.value,className:"gap-2",children:[e.jsx(m.icon,{className:"w-4 h-4"}),m.label,m.value==="messages"&&h>0&&e.jsx(Oe,{className:"ml-1 h-5 px-1.5",children:h})]},m.value))}),e.jsx(Gt,{value:"overview",className:"mt-6",children:e.jsx(irs,{})}),e.jsx(Gt,{value:"messages",className:"mt-6",children:e.jsx(Qer,{selectedPortalId:d,onSelectPortal:m=>t(p=>{const f=new URLSearchParams(p);return f.set("tab","messages"),m?f.set("portal",m):f.delete("portal"),f},{replace:!0})})}),e.jsx(Gt,{value:"vendors",className:"mt-6",children:e.jsx(ttr,{})}),e.jsx(Gt,{value:"referrals",className:"mt-6",children:e.jsx(str,{})}),e.jsx(Gt,{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(Xc,{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(B,{onClick:()=>l(!0),children:[e.jsx(qc,{className:"w-4 h-4 mr-2"}),"Edit Branding Defaults"]})]})]})})}),e.jsx(Gt,{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(Ny,{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(B,{onClick:()=>c(!0),children:[e.jsx(qc,{className:"w-4 h-4 mr-2"}),"Manage Questions"]})]})]})})})]})]}),e.jsx(ars,{open:i,onOpenChange:l}),e.jsx(srs,{open:o,onOpenChange:c})]})}function ttr(){return e.jsx(frs,{embedded:!0})}function str(){return e.jsx(hrs,{})}const JB=s=>new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(s));function ntr(s){return at({queryKey:["client-portal-by-id",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("client_portals").select("*").eq("id",s).maybeSingle();if(n)throw n;if(!t)return{portal:null,deal:null};const{data:r,error:a}=await q.from("deal_pipeline").select("deal_name, contact_id").eq("id",t.deal_id).maybeSingle();if(a)throw a;let i=null;if(r!=null&&r.contact_id){const{data:l,error:o}=await q.from("innercircle_contacts").select("first_name, last_name, email, phone").eq("id",r.contact_id).maybeSingle();if(o)throw o;i=l}return{portal:t,deal:r?{deal_name:r.deal_name,contact_id:r.contact_id,contact:i}:null}},enabled:!!s})}function rtr(){const{portalId:s}=Li(),t=Fn(),n=ha(),{data:r,isLoading:a}=ntr(s),{data:i=[]}=zFn(s),{data:l=[]}=urs(),o=VW(),c=$Yt(),d=VYt(),u=HYt(),[h,m]=_.useState(!1),[p,f]=_.useState(!1),[y,v]=_.useState(!1),[g,b]=_.useState(!1),j=(r==null?void 0:r.portal)??null,S=(r==null?void 0:r.deal)??null,C=_.useMemo(()=>j?l.filter(Y=>Y.portal_id===j.id):[],[l,j==null?void 0:j.id]);if(a)return e.jsx(zs,{children:e.jsx("div",{className:"flex items-center justify-center py-24",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})})});if(!j)return e.jsx(zs,{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(B,{asChild:!0,variant:"outline",children:e.jsxs(ir,{to:"/mission-control/client-portals",children:[e.jsx(ka,{className:"w-4 h-4 mr-2"}),"Back to Portals"]})})]})});const E=wS(j.slug),P=(S==null?void 0:S.deal_name)||"Untitled deal",M=S==null?void 0:S.contact,I=M?`${M.first_name||""} ${M.last_name||""}`.trim():"",D=!!j.archived_at,O=()=>{navigator.clipboard.writeText(E),se.success("Portal link copied!")},V=async Y=>{try{await o.mutateAsync({id:j.id,is_enabled:Y}),se.success(Y?"Portal enabled":"Portal disabled")}catch{se.error("Failed to update")}},G=async()=>{try{await c.mutateAsync(j.id),se.success("Portal archived")}catch{se.error("Failed to archive")}},$=async()=>{try{await d.mutateAsync(j.id),se.success("Portal restored")}catch{se.error("Failed to restore")}},H=async()=>{try{await u.mutateAsync({id:j.id,dealId:j.deal_id}),se.success("Portal deleted"),t("/mission-control/client-portals")}catch{se.error("Failed to delete")}};return e.jsxs(zs,{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(B,{asChild:!0,variant:"ghost",size:"sm",className:"-ml-2 text-muted-foreground",children:e.jsxs(ir,{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(un,{className:"w-5 h-5 text-primary"}),e.jsx("h1",{className:"text-2xl font-bold truncate",children:P}),e.jsx(Oe,{variant:"outline",className:D?"bg-muted text-muted-foreground":j.is_enabled?"bg-emerald-500/10 text-emerald-700 border-emerald-200":"bg-muted text-muted-foreground",children:D?"Archived":j.is_enabled?"Active":"Disabled"}),e.jsx(Oe,{variant:"outline",className:"capitalize text-xs",children:j.visibility})]}),e.jsxs("p",{className:"text-sm text-muted-foreground flex items-center gap-2 flex-wrap",children:[e.jsx(Fo,{className:"w-3.5 h-3.5"}),j.client_name||I||"No client name set",(M==null?void 0:M.email)&&e.jsxs(e.Fragment,{children:["· ",e.jsx(ln,{className:"w-3.5 h-3.5"}),e.jsx("span",{className:"truncate",children:M.email})]}),(M==null?void 0:M.phone)&&e.jsxs(e.Fragment,{children:["· ",e.jsx(_a,{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:E})})]}),!D&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Live"}),e.jsx(fn,{checked:j.is_enabled,onCheckedChange:V})]})]}),e.jsxs("div",{className:"mt-5 flex items-center gap-2 flex-wrap",children:[e.jsxs(B,{onClick:O,variant:"outline",size:"sm",children:[e.jsx(Ia,{className:"w-4 h-4 mr-1.5"})," Copy Link"]}),e.jsxs(B,{onClick:()=>window.open(E,"_blank"),variant:"outline",size:"sm",children:[e.jsx(wr,{className:"w-4 h-4 mr-1.5"})," Preview"]}),e.jsxs(B,{onClick:()=>v(!0),size:"sm",children:[e.jsx(Or,{className:"w-4 h-4 mr-1.5"})," Invite Client"]}),e.jsxs(B,{onClick:()=>f(!0),variant:"outline",size:"sm",children:[e.jsx(E4,{className:"w-4 h-4 mr-1.5"})," Post Update"]}),e.jsxs(B,{onClick:()=>m(!0),variant:"outline",size:"sm",children:[e.jsx(qc,{className:"w-4 h-4 mr-1.5"})," Settings"]}),e.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[D?e.jsxs(B,{onClick:$,variant:"outline",size:"sm",children:[e.jsx(VM,{className:"w-4 h-4 mr-1.5"})," Restore"]}):e.jsxs(B,{onClick:G,variant:"ghost",size:"sm",children:[e.jsx(by,{className:"w-4 h-4 mr-1.5"})," Archive"]}),e.jsx(B,{onClick:()=>b(!0),variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive",children:e.jsx(Sn,{className:"w-4 h-4"})})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(Ide,{icon:E4,label:"Updates Posted",value:i.length}),e.jsx(Ide,{icon:Vo,label:"Referrals",value:C.length}),e.jsx(Ide,{icon:ga,label:"Inspection",value:j.inspection_date?JB(j.inspection_date):"—"}),e.jsx(Ide,{icon:ga,label:"Appraisal",value:j.appraisal_date?JB(j.appraisal_date):"—"})]}),e.jsxs(Yr,{defaultValue:"updates",className:"w-full",children:[e.jsxs(Zr,{children:[e.jsxs(Ht,{value:"updates",children:["Updates (",i.length,")"]}),e.jsx(Ht,{value:"messages",children:"Messages"}),e.jsxs(Ht,{value:"referrals",children:["Referrals (",C.length,")"]}),e.jsx(Ht,{value:"branding",children:"Branding"}),e.jsx(Ht,{value:"details",children:"Details"})]}),e.jsx(Gt,{value:"messages",className:"mt-4",children:e.jsx(xrs,{portalId:j.id,portalSlug:j.slug,clientName:j.client_name})}),e.jsx(Gt,{value:"updates",className:"mt-4",children:e.jsx(ve,{children:e.jsxs(Me,{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(B,{size:"sm",onClick:()=>f(!0),children:[e.jsx(E4,{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(E4,{className:"w-10 h-10 text-muted-foreground/40 mx-auto mb-3"}),e.jsx("p",{className:"text-sm font-medium",children:"No updates posted yet"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Keep your client in the loop — post your first update."})]}):e.jsx("div",{className:"space-y-3",children:i.map(Y=>e.jsx("div",{className:"border rounded-lg p-4",children:e.jsx("div",{className:"flex items-start justify-between gap-2",children:e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("h4",{className:"font-medium text-sm",children:Y.title}),Y.is_stage_change&&e.jsx(Oe,{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:JB(Y.created_at)}),Y.content&&e.jsx("p",{className:"text-sm text-muted-foreground mt-2 whitespace-pre-wrap",children:Y.content}),Y.video_url&&e.jsxs("a",{href:Y.video_url,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-xs text-primary hover:underline mt-2",children:[e.jsx(Kr,{className:"w-3 h-3"})," View video"]})]})})},Y.id))})]})})}),e.jsx(Gt,{value:"referrals",className:"mt-4",children:e.jsx(ve,{children:e.jsxs(Me,{className:"p-4",children:[e.jsx("h3",{className:"font-semibold mb-4",children:"Referrals from this Portal"}),C.length===0?e.jsxs("div",{className:"text-center py-12 border-2 border-dashed rounded-lg",children:[e.jsx(Vo,{className:"w-10 h-10 text-muted-foreground/40 mx-auto mb-3"}),e.jsx("p",{className:"text-sm font-medium",children:"No referrals yet"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"When your client refers a friend, they'll show up here."})]}):e.jsx("div",{className:"space-y-2",children:C.map(Y=>e.jsx(ir,{to:"/mission-control/client-portals?tab=referrals",className:"block border rounded-lg p-3 hover:bg-muted/50 transition-colors",children:e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:Y.friend_name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Y.friend_email||Y.friend_phone||"No contact info"," · ",JB(Y.created_at)]})]}),e.jsx(Oe,{variant:"outline",className:"text-xs capitalize",children:Y.status})]})},Y.id))})]})})}),e.jsx(Gt,{value:"branding",className:"mt-4",children:e.jsx(ve,{children:e.jsx(Me,{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(Xc,{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(B,{onClick:()=>m(!0),children:[e.jsx(qc,{className:"w-4 h-4 mr-2"}),"Edit Branding (in Settings)"]})]})]})})})}),e.jsx(Gt,{value:"details",className:"mt-4",children:e.jsx(ve,{children:e.jsxs(Me,{className:"p-6 space-y-4",children:[e.jsx(PT,{label:"Visibility",value:j.visibility}),e.jsx(PT,{label:"Onboarding Required",value:j.require_onboarding?"Yes":"No"}),e.jsx(PT,{label:"Allow Spouse",value:j.allow_spouse?"Yes":"No"}),e.jsx(PT,{label:"Notify Client on Updates",value:j.notify_client?"Yes":"No"}),e.jsx(PT,{label:"Show Post-Close Tips",value:j.show_post_close_tips?"Yes":"No"}),e.jsx(PT,{label:"Slug",value:j.slug,mono:!0}),e.jsx(PT,{label:"Created",value:JB(j.created_at)}),e.jsx(PT,{label:"Last Updated",value:JB(j.updated_at)}),e.jsx("div",{className:"pt-2",children:e.jsxs(B,{variant:"outline",onClick:()=>m(!0),children:[e.jsx(qc,{className:"w-4 h-4 mr-2"})," Edit All Settings"]})})]})})})]})]}),e.jsx($at,{open:h,onOpenChange:m,portal:j,dealOwnerId:n||""}),e.jsx(Vat,{open:p,onOpenChange:f,portalId:j.id,portalSlug:j.slug,notifyClient:j.notify_client}),e.jsx(Hat,{open:y,onOpenChange:v,portal:j,dealName:P}),e.jsx(Kl,{open:g,onOpenChange:b,children:e.jsxs(Ol,{children:[e.jsxs(zl,{children:[e.jsx(Ul,{children:"Permanently delete this portal?"}),e.jsx(ql,{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($l,{children:"Cancel"}),e.jsx(Ml,{onClick:H,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete Permanently"})]})]})})]})}function Ide({icon:s,label:t,value:n}){return e.jsxs("div",{className:"border rounded-lg p-4 bg-card",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(s,{className:"w-3.5 h-3.5"}),e.jsx("span",{className:"text-[11px] uppercase tracking-wide",children:t})]}),e.jsx("p",{className:"text-xl font-semibold truncate",children:n})]})}function PT({label:s,value:t,mono:n}){return e.jsxs("div",{className:"flex items-center justify-between gap-4 border-b pb-2 last:border-b-0 last:pb-0",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:s}),e.jsx("span",{className:`text-sm ${n?"font-mono text-xs":""} text-right truncate`,children:t})]})}const GYe=[{value:"video_intro",label:"Video Intro",icon:Kr,description:"Add an intro video"},{value:"testimonials",label:"Testimonials",icon:WA,description:"Client testimonials carousel"},{value:"specialties",label:"Specialties",icon:Ep,description:"Tags for your specialties"},{value:"custom_links",label:"Custom Links",icon:vd,description:"Custom CTA buttons"},{value:"social_media",label:"Social Media",icon:bd,description:"Links to your social profiles"}],atr=["First-Time Buyers","Luxury Homes","Investment Properties","Relocation","New Construction","Condos & Townhomes","Waterfront","Commercial","Land & Lots","Senior Living","Military/VA","Short Sales & Foreclosures"],itr={video_intro:{video_url:""},testimonials:{testimonials:[{name:"",quote:"",role:""}]},specialties:{tags:[]},custom_links:{links:[{label:"",url:""}]},social_media:{platforms:[]}};function grs({cardId:s}){const{data:t,isLoading:n}=rMs(s),r=aMs(),a=iMs(),i=oMs(),[l,o]=_.useState(!1),[c,d]=_.useState(""),[u,h]=_.useState(null);if(n)return e.jsxs("div",{className:"space-y-3",children:[e.jsx(cn,{className:"h-16 w-full"}),e.jsx(cn,{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:itr[c]||{}},{onSuccess:()=>{o(!1),d("")}})},p=b=>{a.mutate({id:b.id,is_visible:!b.is_visible})},f=(b,j)=>{if(!t)return;const S=t.findIndex(P=>P.id===b.id),C=j==="up"?S-1:S+1;if(C<0||C>=t.length)return;const E=t[C];a.mutate({id:b.id,sort_order:E.sort_order}),a.mutate({id:E.id,sort_order:b.sort_order})},y=async b=>{await Xi("Remove this block from this card?")&&i.mutate(b.id)},v=(b,j)=>{a.mutate({id:b.id,config:j},{onSuccess:()=>h(null)})},g=b=>GYe.find(j=>j.value===b);return e.jsxs("div",{className:"space-y-3",children:[!t||t.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx("p",{className:"text-muted-foreground mb-4 text-sm",children:"No blocks yet. Add a block to customize this card."}),e.jsxs(B,{size:"sm",onClick:()=>o(!0),children:[e.jsx(rn,{className:"h-4 w-4 mr-1"})," Add Block"]})]}):e.jsxs(e.Fragment,{children:[t.map((b,j)=>{const S=g(b.block_type),C=(S==null?void 0:S.icon)||Ep;return e.jsx(ve,{className:b.is_visible?"":"opacity-50",children:e.jsx(Me,{className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Vf,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsx(C,{className:"h-4 w-4 text-primary flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-xs",children:(S==null?void 0:S.label)||b.block_type}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:otr(b)})]}),e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>f(b,"up"),disabled:j===0,children:e.jsx(sp,{className:"h-3 w-3"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>f(b,"down"),disabled:j===t.length-1,children:e.jsx(zf,{className:"h-3 w-3"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>p(b),children:b.is_visible?e.jsx(ya,{className:"h-3 w-3"}):e.jsx(Ax,{className:"h-3 w-3"})}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>h(b),children:"Edit"}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7 text-destructive",onClick:()=>y(b),children:e.jsx(Sn,{className:"h-3 w-3"})})]})]})})},b.id)}),e.jsxs(B,{variant:"outline",size:"sm",className:"w-full",onClick:()=>o(!0),children:[e.jsx(rn,{className:"h-4 w-4 mr-1"})," Add Block"]})]}),e.jsx(Ls,{open:l,onOpenChange:o,children:e.jsxs(Ps,{children:[e.jsx(Os,{children:e.jsx(Ds,{children:"Add Block"})}),e.jsx("div",{className:"grid gap-3",children:GYe.map(b=>{const j=b.icon;return e.jsxs("button",{onClick:()=>d(b.value),className:`flex items-center gap-3 p-3 rounded-lg border text-left transition-colors ${c===b.value?"border-primary bg-primary/5":"border-border hover:bg-muted"}`,children:[e.jsx(j,{className:"h-5 w-5 text-primary flex-shrink-0"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:b.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:b.description})]})]},b.value)})}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx(B,{onClick:m,disabled:!c||r.isPending,children:"Add Block"})]})]})}),u&&e.jsx(ltr,{block:u,onSave:b=>v(u,b),onClose:()=>h(null)})]})}function otr(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 ltr({block:s,onSave:t,onClose:n}){const[r,a]=_.useState(s.config),i=GYe.find(l=>l.value===s.block_type);return e.jsx(Ls,{open:!0,onOpenChange:n,children:e.jsxs(Ps,{className:"max-w-lg max-h-[80vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsxs(Ds,{children:["Edit ",i==null?void 0:i.label]})}),s.block_type==="video_intro"&&e.jsx(ctr,{config:r,onChange:a,cardId:s.card_id}),s.block_type==="testimonials"&&e.jsx(dtr,{config:r,onChange:a}),s.block_type==="specialties"&&e.jsx(utr,{config:r,onChange:a}),s.block_type==="custom_links"&&e.jsx(htr,{config:r,onChange:a}),s.block_type==="social_media"&&e.jsx(mtr,{config:r,onChange:a}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:n,children:"Cancel"}),e.jsx(B,{onClick:()=>t(r),children:"Save"})]})]})})}function ctr({config:s,onChange:t,cardId:n}){var p,f;const[r,a]=_.useState(""),[i,l]=_.useState((p=s.video_url)!=null&&p.includes("youtube")||(f=s.video_url)!=null&&f.includes("youtu.be")?"youtube":"library"),{data:o}=at({queryKey:["card-owner",n],queryFn:async()=>{const{data:y}=await q.from("agent_cards").select("user_id").eq("id",n).single();return y==null?void 0:y.user_id},enabled:!!n}),{data:c,isLoading:d}=at({queryKey:["agent-videos-library",o],queryFn:async()=>{const{data:y,error:v}=await q.from("agent_videos").select("id, title, bunny_video_id, thumbnail_url, playback_url, created_at").eq("owner_user_id",o).eq("is_deleted",!1).eq("status","ready").order("created_at",{ascending:!1});if(v)throw v;return y||[]},enabled:!!o}),u=(c==null?void 0:c.filter(y=>!r||(y.title||"").toLowerCase().includes(r.toLowerCase())))||[],h=s.bunny_video_id,m=y=>{var j;const v=(j=y.playback_url)==null?void 0:j.match(/\/(?:play|embed)\/(\d+)\//),b=`https://iframe.mediadelivery.net/embed/${v?v[1]:"570924"}/${y.bunny_video_id}?autoplay=false&responsive=true`;t({...s,video_url:b,bunny_video_id:y.bunny_video_id,video_source:"library"})};return e.jsx("div",{className:"space-y-4",children:e.jsxs(Yr,{value:i,onValueChange:l,children:[e.jsxs(Zr,{className:"w-full",children:[e.jsx(Ht,{value:"library",className:"flex-1",children:"Video Library"}),e.jsx(Ht,{value:"youtube",className:"flex-1",children:"YouTube URL"})]}),e.jsxs(Gt,{value:"library",className:"space-y-3 mt-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search videos...",value:r,onChange:y=>a(y.target.value),className:"pl-9"})]}),e.jsx(Ji,{className:"h-[240px]",children:d?e.jsxs("div",{className:"space-y-2",children:[e.jsx(cn,{className:"h-14 w-full"}),e.jsx(cn,{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(y=>e.jsxs("button",{onClick:()=>m(y),className:`w-full flex items-center gap-3 p-2 rounded-lg border text-left transition-colors ${h===y.bunny_video_id?"border-primary bg-primary/5":"border-border hover:bg-muted"}`,children:[y.thumbnail_url?e.jsx("img",{src:y.thumbnail_url,alt:"",className:"h-10 w-16 rounded object-cover flex-shrink-0 bg-muted",onError:v=>{var g;v.currentTarget.style.display="none",(g=v.currentTarget.nextElementSibling)==null||g.classList.remove("hidden")}}):null,e.jsx("div",{className:`h-10 w-16 rounded bg-muted flex items-center justify-center flex-shrink-0 ${y.thumbnail_url?"hidden":""}`,children:e.jsx(Kr,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"text-sm font-medium truncate flex-1",children:y.title||"Untitled Video"}),h===y.bunny_video_id&&e.jsx(ea,{className:"h-4 w-4 text-primary flex-shrink-0"})]},y.id))})})]}),e.jsx(Gt,{value:"youtube",className:"space-y-3 mt-3",children:e.jsxs("div",{children:[e.jsx(J,{children:"YouTube URL"}),e.jsx(xe,{placeholder:"https://www.youtube.com/watch?v=...",value:s.video_source==="youtube"&&s.video_url||"",onChange:y=>t({...s,video_url:y.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 dtr({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(ve,{children:e.jsxs(Me,{className:"p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(J,{className:"text-xs font-medium",children:["Testimonial ",o+1]}),n.length>1&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6 text-destructive",onClick:()=>i(o),children:e.jsx(Sn,{className:"h-3 w-3"})})]}),e.jsx(xe,{placeholder:"Client name",value:l.name,onChange:c=>r(o,"name",c.target.value)}),e.jsx(xe,{placeholder:"Role/title (optional)",value:l.role||"",onChange:c=>r(o,"role",c.target.value)}),e.jsx("textarea",{className:"w-full min-h-[60px] rounded-md border border-input bg-background px-3 py-2 text-sm",placeholder:"Their testimonial quote...",value:l.quote,onChange:c=>r(o,"quote",c.target.value)})]})},o)),e.jsxs(B,{variant:"outline",size:"sm",onClick:a,className:"w-full",children:[e.jsx(rn,{className:"h-4 w-4 mr-1"})," Add Testimonial"]})]})}function utr({config:s,onChange:t}){const n=s.tags||[],[r,a]=_.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(J,{className:"text-sm mb-2 block",children:"Preset Specialties"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:atr.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(J,{className:"text-sm mb-2 block",children:"Custom Tag"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{placeholder:"Add your own...",value:r,onChange:o=>a(o.target.value),onKeyDown:o=>o.key==="Enter"&&(o.preventDefault(),l())}),e.jsx(B,{variant:"outline",size:"sm",onClick:l,children:"Add"})]})]}),n.length>0&&e.jsxs("div",{children:[e.jsxs(J,{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 htr({config:s,onChange:t}){const n=s.links||[],r=(l,o,c)=>{const d=[...n];d[l]={...d[l],[o]:c},t({...s,links:d})},a=()=>t({...s,links:[...n,{label:"",url:""}]}),i=l=>t({...s,links:n.filter((o,c)=>c!==l)});return e.jsxs("div",{className:"space-y-3",children:[n.map((l,o)=>e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(xe,{placeholder:"Button label",value:l.label,onChange:c=>r(o,"label",c.target.value)}),e.jsx(xe,{placeholder:"https://...",value:l.url,onChange:c=>r(o,"url",c.target.value)})]}),n.length>1&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8 mt-1 text-destructive",onClick:()=>i(o),children:e.jsx(Sn,{className:"h-3 w-3"})})]},o)),e.jsxs(B,{variant:"outline",size:"sm",onClick:a,className:"w-full",children:[e.jsx(rn,{className:"h-4 w-4 mr-1"})," Add Link"]})]})}const u4t=[{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 mtr({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=u4t.filter(c=>!n.find(d=>d.platform===c.value)),o=c=>{const d=W$e[c],u=u4t.find(h=>h.value===c);return{label:(u==null?void 0:u.label)||c,color:(d==null?void 0:d.color)||"#666",iconPath:d==null?void 0:d.icon}};return e.jsxs("div",{className:"space-y-4",children:[n.length>0&&e.jsx("div",{className:"space-y-3",children:n.map((c,d)=>{const u=o(c.platform);return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-9 w-9 rounded-lg flex items-center justify-center flex-shrink-0 border",style:{borderColor:u.color+"30",backgroundColor:u.color+"10"},children:u.iconPath&&e.jsx("svg",{viewBox:"0 0 24 24",width:16,height:16,fill:u.color,children:e.jsx("path",{d:u.iconPath})})}),e.jsx("div",{className:"flex-1",children:e.jsx(xe,{placeholder:`Your ${u.label} profile URL`,value:c.url,onChange:h=>a(d,h.target.value)})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive flex-shrink-0",onClick:()=>i(d),children:e.jsx(Sn,{className:"h-3.5 w-3.5"})})]},d)})}),l.length>0&&e.jsxs("div",{children:[e.jsx(J,{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=W$e[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 ptr({slug:s,agentName:t}){const n=_.useRef(null),r=`https://cards.relevelup.com/${s}`,a=_.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(),se.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(J,{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(AN,{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(B,{variant:"outline",size:"sm",onClick:a,className:"gap-1.5",children:[e.jsx(li,{className:"h-3.5 w-3.5"}),"Download PNG"]})]})]})]})}function kBe(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 ftr(){const{user:s}=hs(),{data:t,isLoading:n}=tMs(s==null?void 0:s.id),r=$W(),[a,i]=_.useState(null),l=_.useMemo(()=>a||(t?kBe(t):null),[a,t]);if(n)return e.jsx(zs,{children:e.jsxs("div",{className:"max-w-2xl mx-auto p-4 space-y-4",children:[e.jsx(cn,{className:"h-8 w-48"}),e.jsx(cn,{className:"h-32 w-full"}),e.jsx(cn,{className:"h-32 w-full"})]})});if(!t)return e.jsx(zs,{children:e.jsx(gtr,{userId:s==null?void 0:s.id})});const o=l||kBe(t),c=d=>{i(u=>{const h=u||kBe(t);return typeof d=="function"?d(h):d})};return e.jsx(zs,{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(ytr,{card:t}),e.jsx(wtr,{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(hN,{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(xtr,{card:t,form:o})})]})})]})})}function xtr({card:s,form:t}){const{data:n}=at({queryKey:["card-preview-profile",s.user_id],queryFn:async()=>{const{data:a}=await q.from("profiles").select("name, email, phone, avatar_url, brokerage_id").eq("id",s.user_id).single();let i=(a==null?void 0:a.avatar_url)||null;if(!i){const{data:l}=await q.storage.from("avatars").list(`${s.user_id}`);if(l&&l.length>0){const{data:o}=q.storage.from("avatars").getPublicUrl(`${s.user_id}/${l[0].name}`);i=`${o.publicUrl}?t=${Date.now()}`}}return{...a,avatar_url:i}}}),r=_.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(pJe,{card:r})})}function gtr({userId:s}){var c;const[t,n]=_.useState(""),r=TFt(),{data:a}=at({queryKey:["my-profile-for-card",s],queryFn:async()=>{if(!s)return null;const{data:d}=await q.from("profiles").select("name").eq("id",s).single();return d},enabled:!!s}),i=((c=a==null?void 0:a.name)==null?void 0:c.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,""))||"",l=()=>{if(!s)return;const d=(t.trim()||i).toLowerCase().replace(/[^a-z0-9-]/g,"-");if(!d){se.error("Please enter a URL slug for your card");return}r.mutate({user_id:s,slug:d,is_published:!0},{onSuccess:()=>se.success("Your digital card has been created!")})},o=[{icon:sl,title:"Shareable Link",desc:"One link that works everywhere"},{icon:nf,title:"Lead Capture",desc:"Collect leads automatically"},{icon:Rm,title:"Always Up-to-Date",desc:"Edit anytime, changes are instant"},{icon:Xc,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(un,{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(ve,{className:"shadow-lg border-2",children:[e.jsxs(bt,{className:"text-center pb-2",children:[e.jsx(St,{className:"text-xl",children:"Set Up Your Card"}),e.jsx(kn,{children:"Choose a URL slug — this is the link you'll share with clients"})]}),e.jsxs(Me,{className:"p-6 pt-2 space-y-5",children:[e.jsxs("div",{children:[e.jsx(J,{className:"text-sm font-medium",children:"Your Card URL"}),e.jsxs("div",{className:"flex items-center gap-0 mt-1.5",children:[e.jsx("span",{className:"inline-flex items-center px-3 h-10 rounded-l-md border border-r-0 bg-muted text-sm text-muted-foreground whitespace-nowrap",children:"cards.relevelup.com/"}),e.jsx(xe,{value:t||i,onChange:d=>n(d.target.value),placeholder:"your-name",className:"rounded-l-none"})]})]}),e.jsxs(B,{onClick:l,disabled:r.isPending,className:"w-full h-11 text-base font-semibold",size:"lg",children:[e.jsx(un,{className:"h-4 w-4 mr-2"}),r.isPending?"Creating...":"Create My Card"]})]})]})]})}function ytr({card:s}){const n=`https://cards.relevelup.com/${s.slug}`,r=()=>{navigator.clipboard.writeText(n),se.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(Oe,{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(sl,{className:"h-3.5 w-3.5"}),"cards.relevelup.com/",s.slug]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:r,className:"gap-1.5",children:[e.jsx(Ia,{className:"h-3.5 w-3.5"})," Copy Link"]}),e.jsx(B,{size:"sm",asChild:!0,className:"gap-1.5",children:e.jsxs("a",{href:n,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(wr,{className:"h-3.5 w-3.5"})," Preview"]})})]})]})})}function vtr({userId:s}){const t=Bt(),n=_.useRef(null),[r,a]=_.useState(!1),[i,l]=_.useState(""),{data:o,isLoading:c}=at({queryKey:["card-editor-profile",s],queryFn:async()=>{const{data:O}=await q.from("profiles").select("name, email, phone, avatar_url").eq("id",s).single();let V=(O==null?void 0:O.avatar_url)||null;if(!V){const{data:G}=await q.storage.from("avatars").list(`${s}`);if(G&&G.length>0){const{data:$}=q.storage.from("avatars").getPublicUrl(`${s}/${G[0].name}`);V=`${$.publicUrl}?t=${Date.now()}`,await q.from("profiles").update({avatar_url:V}).eq("id",s)}}return{...O,avatar_url:V}}}),[d,u]=_.useState(null),[h,m]=_.useState(null),[p,f]=_.useState(null),[y,v]=_.useState(!1),g=d??(o==null?void 0:o.name)??"",b=h??(o==null?void 0:o.phone)??"",j=p??(o==null?void 0:o.email)??"",S=o==null?void 0:o.avatar_url,C=((o==null?void 0:o.name)||"A").split(" ").map(O=>O[0]).join("").toUpperCase().slice(0,2),E=!(o!=null&&o.avatar_url)||!(o!=null&&o.phone),P=mt({mutationFn:async O=>{const{error:V}=await q.from("profiles").update(O).eq("id",s);if(V)throw V},onSuccess:()=>{t.invalidateQueries({queryKey:["card-editor-profile",s]}),t.invalidateQueries({queryKey:["card-preview-profile",s]}),t.invalidateQueries({queryKey:["agent-card-user"]}),se.success("Profile updated!")},onError:()=>se.error("Failed to update profile")}),M=()=>{const O={};if(d!==null&&d!==(o==null?void 0:o.name)&&(O.name=d),h!==null&&h!==(o==null?void 0:o.phone)&&(O.phone=h||null),p!==null&&p!==(o==null?void 0:o.email)&&(O.email=p),Object.keys(O).length===0){se.info("No changes to save");return}P.mutate(O)},I=O=>{var $;const V=($=O.target.files)==null?void 0:$[0];if(!V)return;if(!V.type.startsWith("image/")){se.error("Please select an image file");return}const G=new FileReader;G.onloadend=()=>{l(G.result),a(!0)},G.readAsDataURL(V),O.target.value=""},D=async O=>{v(!0);try{const{data:V}=await q.storage.from("avatars").list(`${s}`);V&&V.length>0&&await q.storage.from("avatars").remove(V.map(Z=>`${s}/${Z.name}`));const G=`${s}/avatar.jpg`,{error:$}=await q.storage.from("avatars").upload(G,O,{upsert:!0,contentType:"image/jpeg"});if($)throw $;const{data:H}=q.storage.from("avatars").getPublicUrl(G),Y=H.publicUrl+"?t="+Date.now();await q.from("profiles").update({avatar_url:Y}).eq("id",s),t.invalidateQueries({queryKey:["card-editor-profile",s]}),t.invalidateQueries({queryKey:["card-preview-profile",s]}),t.invalidateQueries({queryKey:["agent-card-user"]}),se.success("Photo updated!")}catch{se.error("Failed to upload photo")}finally{v(!1)}};return c?e.jsx(cn,{className:"h-32 w-full rounded-xl"}):e.jsxs(e.Fragment,{children:[e.jsx(ve,{className:E?"border-amber-300 dark:border-amber-700":"",children:e.jsxs(Me,{className:"p-5 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(J,{className:"text-sm font-semibold",children:"Profile Info"}),E&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-amber-600 dark:text-amber-400 font-medium",children:[e.jsx(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 O;return(O=n.current)==null?void 0:O.click()},children:[e.jsxs(ja,{className:"h-16 w-16 ring-2 ring-muted",children:[e.jsx(pi,{src:S||void 0,alt:g}),e.jsx(Na,{className:"text-lg font-semibold bg-primary/10 text-primary",children:C})]}),e.jsx("div",{className:"absolute inset-0 bg-black/40 rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx(cg,{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:y?"Uploading...":S?"Tap to change photo":"Add a profile photo"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This photo appears on your card, profile, and community posts"})]})]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs font-medium text-muted-foreground",children:"Full Name"}),e.jsx(xe,{value:g,onChange:O=>u(O.target.value),placeholder:"Your full name",className:"h-10"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs font-medium text-muted-foreground",children:"Phone Number"}),e.jsx(xe,{value:b,onChange:O=>m(O.target.value),placeholder:"(555) 123-4567",className:"h-10",type:"tel"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs font-medium text-muted-foreground",children:"Email"}),e.jsx(xe,{value:j,onChange:O=>f(O.target.value),placeholder:"you@example.com",className:"h-10",type:"email"})]})]})]}),e.jsx(B,{variant:"outline",size:"sm",onClick:M,disabled:P.isPending,className:"w-full",children:P.isPending?"Saving...":"Update Profile Info"})]})}),e.jsx(itt,{open:r,onClose:()=>a(!1),imageSrc:i,onCropComplete:D,aspectRatio:1})]})}function btr({form:s,setForm:t,userId:n}){const[r,a]=_.useState(null),[i,l]=_.useState(s.brokerage_logo_url?"logo":"name"),[o,c]=_.useState(s.team_logo_url?"logo":"name"),d=p=>{l(p),t(p==="name"?f=>({...f,brokerage_logo_url:""}):f=>({...f,brokerage_display_name:""}))},u=p=>{c(p),t(p==="name"?f=>({...f,team_logo_url:""}):f=>({...f,team_name:""}))},h=async(p,f)=>{var v;const y=(v=p.target.files)==null?void 0:v[0];if(y){if(!y.type.startsWith("image/")){se.error("Please select an image file");return}a(f);try{const g=y.name.split(".").pop()||"png",j=`${n}/${f==="brokerage_logo_url"?"brokerage-logo":"team-logo"}.${g}`,{error:S}=await q.storage.from("card-logos").upload(j,y,{upsert:!0});if(S)throw S;const{data:C}=q.storage.from("card-logos").getPublicUrl(j),E=C.publicUrl+"?t="+Date.now();t(f==="brokerage_logo_url"?P=>({...P,[f]:E,brokerage_display_name:""}):P=>({...P,[f]:E,team_name:""})),se.success("Logo uploaded!")}catch{se.error("Failed to upload logo")}finally{a(null),p.target.value=""}}},m=p=>{t(f=>({...f,[p]:""}))};return e.jsx(ve,{children:e.jsxs(Me,{className:"p-5 space-y-5",children:[e.jsxs("div",{children:[e.jsx(J,{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(J,{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Brokerage"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{type:"button",variant:i==="name"?"default":"outline",size:"sm",className:"text-xs",onClick:()=>d("name"),children:"Use Name"}),e.jsx(B,{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(J,{className:"text-xs font-medium text-muted-foreground",children:"Brokerage Name"}),e.jsx(xe,{value:s.brokerage_display_name,onChange:p=>t(f=>({...f,brokerage_display_name:p.target.value})),placeholder:"e.g. Keller Williams Realty",className:"h-10"})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsx(J,{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(cg,{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(J,{className:"text-xs font-medium text-muted-foreground",children:"Logo Size"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[s.brokerage_logo_size||56,"px"]})]}),e.jsx(kx,{value:[s.brokerage_logo_size||56],onValueChange:([p])=>t(f=>({...f,brokerage_logo_size:p})),min:24,max:120,step:4})]})]})]}),e.jsxs("div",{className:"space-y-3 p-3 rounded-lg bg-muted/30 border",children:[e.jsx(J,{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Team"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{type:"button",variant:o==="name"?"default":"outline",size:"sm",className:"text-xs",onClick:()=>u("name"),children:"Use Name"}),e.jsx(B,{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(J,{className:"text-xs font-medium text-muted-foreground",children:"Team Name"}),e.jsx(xe,{value:s.team_name,onChange:p=>t(f=>({...f,team_name:p.target.value})),placeholder:"e.g. The Smith Group",className:"h-10"})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsx(J,{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(cg,{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(J,{className:"text-xs font-medium text-muted-foreground",children:"Logo Size"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[s.team_logo_size||56,"px"]})]}),e.jsx(kx,{value:[s.team_logo_size||56],onValueChange:([p])=>t(f=>({...f,team_logo_size:p})),min:24,max:120,step:4})]})]})]})]})})}function _tr({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(J,{className:"text-sm font-semibold flex items-center gap-1.5",children:[e.jsx(Xc,{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(B,{variant:"ghost",size:"sm",className:"text-xs h-7",onClick:i,children:"Reset to Default"})]}),e.jsx("div",{className:"grid gap-3",children:l.map(({key:o,label:c,desc:d})=>e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("label",{className:"relative shrink-0",children:[e.jsx("input",{type:"color",value:r[o],onChange:u=>a(o,u.target.value),className:"sr-only"}),e.jsx("div",{className:"h-10 w-10 rounded-lg border-2 border-border cursor-pointer shadow-sm hover:scale-105 transition-transform",style:{backgroundColor:r[o]}})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:c}),e.jsx("p",{className:"text-xs text-muted-foreground",children:d})]}),e.jsx(xe,{value:r[o],onChange:u=>{const h=u.target.value;/^#[0-9a-fA-F]{0,6}$/.test(h)&&a(o,h)},className:"w-24 h-8 text-xs font-mono",placeholder:"#ff5722"})]},o))}),e.jsxs("div",{className:"flex items-center gap-2 pt-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Preview:"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx("div",{className:"h-6 w-12 rounded",style:{backgroundColor:r.accent}}),e.jsx("div",{className:"h-6 w-12 rounded",style:{backgroundColor:r.dark}}),e.jsx("div",{className:"h-6 w-12 rounded",style:{backgroundColor:r.button}})]})]})]})}function wtr({card:s,form:t,setForm:n}){var y;const r=MFt(),a=Bt(),{data:i}=PFt(s.id),[l,o]=_.useState(s.slug),[c,d]=_.useState(!1),[u,h]=_.useState("idle"),m=_.useRef(JSON.stringify(t)),p=_.useRef(null);_.useEffect(()=>{const v=JSON.stringify(t);if(v!==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=v,h("saved"),setTimeout(()=>h("idle"),2e3)},onError:()=>h("idle")})},1500),()=>{p.current&&clearTimeout(p.current)}},[t]);const f=async()=>{const v=l.trim().toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/(^-|-$)/g,"");if(!v){se.error("Please enter a valid URL");return}if(v===s.slug){se.info("No changes to save");return}d(!0);try{const{data:g}=await q.from("agent_cards").select("id").eq("slug",v).neq("id",s.id).maybeSingle();if(g){se.error("This URL is already taken. Try another one.");return}const{error:b}=await q.from("agent_cards").update({slug:v}).eq("id",s.id);if(b)throw b;o(v),a.invalidateQueries({queryKey:["agent-card"]}),se.success("Card address updated!")}catch{se.error("Failed to update card address")}finally{d(!1)}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs(Yr,{defaultValue:"content",children:[e.jsxs(Zr,{className:"w-full h-11 p-1",children:[e.jsxs(Ht,{value:"content",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(_y,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Content"]}),e.jsxs(Ht,{value:"sections",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(ya,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Sections"]}),e.jsxs(Ht,{value:"blocks",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(nf,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Blocks"]}),e.jsxs(Ht,{value:"qrcode",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(Hf,{className:"h-3.5 w-3.5 hidden sm:inline"}),"QR Code"]}),e.jsxs(Ht,{value:"analytics",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx($h,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Analytics"]})]}),e.jsxs(Gt,{value:"content",className:"mt-4 space-y-4",children:[e.jsx(vtr,{userId:s.user_id}),e.jsx(btr,{form:t,setForm:n,userId:s.user_id}),e.jsx(ve,{children:e.jsxs(Me,{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(J,{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(fn,{checked:t.is_published,onCheckedChange:v=>n(g=>({...g,is_published:v}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-sm font-medium",children:"Card Address"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"flex flex-1",children:[e.jsx("span",{className:"inline-flex items-center px-3 rounded-l-md border border-r-0 bg-muted text-muted-foreground text-xs whitespace-nowrap",children:"cards.relevelup.com/"}),e.jsx(xe,{value:l,onChange:v=>o(v.target.value.toLowerCase().replace(/[^a-z0-9-]/g,"-")),placeholder:"your-name",className:"rounded-l-none h-10"})]}),e.jsx(B,{variant:"outline",size:"sm",onClick:f,disabled:c||l===s.slug,className:"shrink-0",children:c?"Saving...":"Update"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This is your unique card URL. Only letters, numbers, and dashes allowed."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-sm font-medium",children:"Card Email (Override)"}),e.jsx(xe,{value:t.display_email,onChange:v=>n(g=>({...g,display_email:v.target.value})),placeholder:"you@yourbusiness.com",className:"h-11",type:"email"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Optional — use a different email on your card instead of your sign-in email."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-sm font-medium",children:"Theme"}),e.jsxs(is,{value:t.theme,onValueChange:v=>n(g=>({...g,theme:v})),children:[e.jsx(rs,{className:"h-11",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"standard",children:"✨ Standard — Modern & Clean"}),e.jsx(He,{value:"luxury",children:"🌙 Luxury — Dark & Gold"}),e.jsx(He,{value:"bold",children:"🔥 Bold — Vibrant & Punchy"}),e.jsx(He,{value:"classic",children:"📋 Classic — Professional"})]})]})]}),t.theme==="bold"&&e.jsx(_tr,{form:t,setForm:n}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-sm font-medium",children:"Title / Tagline"}),e.jsx(xe,{value:t.title,onChange:v=>n(g=>({...g,title:v.target.value})),placeholder:"e.g. Luxury Real Estate Specialist",className:"h-11"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Shown below your name on the card"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-sm font-medium",children:"Positioning Statement"}),e.jsx(xe,{value:t.positioning_statement,onChange:v=>n(g=>({...g,positioning_statement:v.target.value})),placeholder:"Your home journey, handled with care.",className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-sm font-medium",children:"Bio"}),e.jsx(Ms,{value:t.bio,onChange:v=>n(g=>({...g,bio:v.target.value})),placeholder:"A short intro about you and what makes you different...",rows:3})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-sm font-medium",children:"Review Snippet"}),e.jsx(xe,{value:t.review_snippet,onChange:v=>n(g=>({...g,review_snippet:v.target.value})),placeholder:"Best agent we've ever worked with...",className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-sm font-medium",children:"Review Source URL"}),e.jsx(xe,{value:t.review_source_url,onChange:v=>n(g=>({...g,review_source_url:v.target.value})),placeholder:"https://g.page/your-business/review",className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-sm font-medium",children:"Booking URL"}),e.jsx(xe,{value:t.booking_url,onChange:v=>n(g=>({...g,booking_url:v.target.value})),placeholder:"https://calendly.com/your-link",className:"h-11"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Leave empty to show a built-in lead form instead"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-sm font-medium",children:"Custom CTA Label"}),e.jsx(xe,{value:t.custom_cta_label,onChange:v=>n(g=>({...g,custom_cta_label:v.target.value})),placeholder:"Book a Call",className:"h-11"})]})]})})]}),e.jsx(Gt,{value:"sections",className:"mt-4",children:e.jsx(ve,{children:e.jsx(Me,{className:"p-5 divide-y",children:[{key:"show_photo",label:"Photo",desc:"Uses the photo from your Profile Info above"},{key:"show_bio",label:"Bio Section",desc:"Display your bio on the card"},{key:"show_credentials",label:"Credentials",desc:"Show star rating and reviews"},{key:"show_social_links",label:"Social Links",desc:"Display your social media links"},{key:"show_save_contact",label:"Save Contact",desc:"Let visitors save you as a contact"},{key:"show_leave_review",label:"Leave Review",desc:"Link to your review page"},{key:"show_refer_friend",label:"Refer a Friend",desc:"Enable referral submissions"}].map(({key:v,label:g,desc:b})=>e.jsxs("div",{className:"flex items-center justify-between py-4 first:pt-0 last:pb-0",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(J,{className:"text-sm font-medium",children:g}),e.jsx("p",{className:"text-xs text-muted-foreground",children:b})]}),e.jsx(fn,{checked:t[v],onCheckedChange:j=>n(S=>({...S,[v]:j}))})]},v))})})}),e.jsx(Gt,{value:"blocks",className:"mt-4",children:e.jsx(grs,{cardId:s.id})}),e.jsx(Gt,{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:ya,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:$h,color:"text-amber-600 bg-amber-100 dark:text-amber-400 dark:bg-amber-900/30"},{label:"Leads",value:((y=i==null?void 0:i.leads)==null?void 0:y.length)??0,icon:Pl,color:"text-emerald-600 bg-emerald-100 dark:text-emerald-400 dark:bg-emerald-900/30"}].map(v=>e.jsx(ve,{className:"overflow-hidden",children:e.jsxs(Me,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("div",{className:`p-1.5 rounded-md ${v.color}`,children:e.jsx(v.icon,{className:"h-3.5 w-3.5"})}),e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:v.label})]}),e.jsx("div",{className:"text-2xl font-bold",children:v.value})]})},v.label))}),i&&i.leads.length>0&&e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-3",children:e.jsx(St,{className:"text-base",children:"Recent Leads"})}),e.jsx(Me,{className:"pt-0 space-y-2",children:i.leads.slice(0,5).map(v=>e.jsxs("div",{className:"flex items-center justify-between text-sm p-3 rounded-lg bg-muted/50",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:v.name}),v.phone&&e.jsx("span",{className:"text-muted-foreground ml-2",children:v.phone})]}),v.intent&&e.jsx(Oe,{variant:"secondary",className:"text-xs",children:v.intent})]},v.id))})]}),(!i||i.leads.length===0)&&e.jsx(ve,{children:e.jsxs(Me,{className:"p-8 text-center",children:[e.jsx($h,{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(Gt,{value:"qrcode",className:"mt-4 space-y-4",children:e.jsx(ve,{children:e.jsx(Me,{className:"p-6",children:e.jsx(ptr,{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 jtr(){const s=Bt(),[t,n]=_.useState(""),[r,a]=_.useState(!1),[i,l]=_.useState(!1),[o,c]=_.useState(null),[d,u]=_.useState(!1),[h,m]=_.useState(!1),[p,f]=_.useState(null),[y,v]=_.useState(null),[g,b]=_.useState(0),[j,S]=_.useState(""),[C,E]=_.useState(!1),{data:P,isLoading:M}=at({queryKey:["boldtrail-status"],queryFn:async()=>{const{data:ce,error:ie}=await q.functions.invoke("boldtrail-sync",{body:{action:"status"}});if(ie)throw ie;return ce}}),I=mt({mutationFn:async ce=>{const{data:ie,error:te}=await q.functions.invoke("boldtrail-sync",{body:{action:"save_token",api_token:ce}});if(te)throw te;if(ie!=null&&ie.error)throw new Error(ie.error);return ie},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),n(""),se.success("BoldTrail connected successfully!")},onError:ce=>{se.error(ce.message||"Failed to connect BoldTrail")}}),D=mt({mutationFn:async()=>{const{data:ce,error:ie}=await q.functions.invoke("boldtrail-sync",{body:{action:"disconnect"}});if(ie)throw ie;return ce},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),se.success("BoldTrail disconnected")},onError:()=>se.error("Failed to disconnect")}),O=mt({mutationFn:async ce=>{const{data:ie,error:te}=await q.functions.invoke("boldtrail-sync",{body:{action:"save_direction",sync_direction:ce}});if(te)throw te;if(ie!=null&&ie.error)throw new Error(ie.error);return ie},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),se.success("Sync direction saved")},onError:ce=>{se.error(ce.message||"Failed to save sync direction")}}),V=mt({mutationFn:async()=>{const{data:ce,error:ie}=await q.functions.invoke("boldtrail-sync",{body:{action:"detect_owner"}});if(ie)throw ie;if(ce!=null&&ce.error)throw new Error(ce.error);return ce},onSuccess:ce=>{if(s.invalidateQueries({queryKey:["boldtrail-status"]}),ce.kvcore_user_id){const ie=ce.detected_name||ce.detected_email||`ID ${ce.kvcore_user_id}`;se.success(`Detected your BoldTrail account: ${ie}`)}else if(ce.candidates&&ce.candidates.length>0){const ie=ce.candidates.slice(0,5).map(te=>`${te.id} (${te.count} contacts)`).join(", ");se.warning(`Couldn't auto-detect your ID. Owner IDs found in your contacts: ${ie}. Pick yours and enter it below.`,{duration:12e3}),E(!0)}else se.warning("Couldn't auto-detect your BoldTrail user ID. Please find it in BoldTrail (My Profile URL) and enter it manually."),E(!0)},onError:ce=>se.error(ce.message||"Detection failed")}),G=mt({mutationFn:async ce=>{const{data:ie,error:te}=await q.functions.invoke("boldtrail-sync",{body:{action:"save_owner_settings",...ce}});if(te)throw te;if(ie!=null&&ie.error)throw new Error(ie.error);return ie},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),se.success("Settings saved"),E(!1)},onError:ce=>se.error(ce.message||"Failed to save settings")}),$=mt({mutationFn:async()=>{const{data:ce,error:ie}=await q.functions.invoke("boldtrail-sync",{body:{action:"sync_preview"}});if(ie)throw ie;if(ce!=null&&ce.error)throw new Error(ce.error);return ce},onSuccess:ce=>{f(null),c(ce),a(!0)},onError:ce=>{se.error(ce.message||"Failed to generate sync preview")}}),H=mt({mutationFn:async()=>{v("Initializing sync..."),b(5);const{data:ce,error:ie}=await q.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"init",sync_direction:ne}});if(ie)throw ie;if(ce!=null&&ce.error)throw new Error(ce.error);const te=ce;let ae=te.sync_log_id,le=te.next_phase,be=te.next_offset,me=te.push_total||0,he=te.pull_total||0,pe=0,Ce=0;for(;le!=="finalize";){const ze=me+he;le==="fetch_bt"?v("Fetching BoldTrail contacts..."):le==="analyze"?(v("Analyzing contacts..."),b(15)):le==="push"?(v(`Pushing contacts to BoldTrail... (${pe}/${me})`),b(ze>0?pe/ze*100:0)):le==="pull"&&(v(`Pulling contacts from BoldTrail... (${Ce}/${he})`),b(ze>0?(me+Ce)/ze*100:0));const{data:ke,error:Ze}=await q.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:le,offset:be,sync_log_id:ae,sync_direction:ne}});if(Ze)throw Ze;if(ke!=null&&ke.error)throw new Error(ke.error);const Se=ke;pe+=Se.chunk_pushed||0,Ce+=Se.chunk_pulled||0,Se.push_total!==void 0&&(me=Se.push_total||0),Se.pull_total!==void 0&&(he=Se.pull_total||0),Se.progress&&v(Se.progress),le==="pull"&&he>0?b(Math.min(95,Ce/he*100)):le==="push"&&me>0&&b(Math.min(95,pe/me*100)),le=Se.next_phase,be=Se.next_offset}v("Finalizing sync..."),b(95);const{data:Ae,error:Pe}=await q.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"finalize",sync_log_id:ae,sync_direction:ne}});if(Pe)throw Pe;return b(100),Ae},onSuccess:ce=>{v(null),b(0),a(!1),s.invalidateQueries({queryKey:["boldtrail-status"]}),s.invalidateQueries({queryKey:["contacts"]}),s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),s.invalidateQueries({queryKey:["contacts-last-touch"]}),se.success(`Sync complete! Pushed ${ce.contacts_pushed||0}, pulled ${ce.contacts_pulled||0}, skipped ${ce.contacts_skipped||0} duplicates.`)},onError:ce=>{v(null),b(0),se.error(ce.message||"Sync failed")}}),Y=P==null?void 0:P.connected,Z=(P==null?void 0:P.sync_direction)||"bidirectional",ne=p??Z;return e.jsxs(e.Fragment,{children:[e.jsxs(ve,{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(Lg,{className:"h-5 w-5 text-emerald-600"})}),e.jsxs("div",{children:[e.jsxs(St,{className:"text-lg flex items-center gap-2",children:["BoldTrail",Y&&e.jsx(Oe,{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(om,{className:"h-3.5 w-3.5"}),"Learn More"]})]}),e.jsx(kn,{children:"Sync contacts bidirectionally between Agent OS and your BoldTrail (kvCORE) CRM."})]})]})}),e.jsx(Me,{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(_l,{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(_l,{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(_l,{className:"h-4 w-4 mt-0.5 text-green-500 shrink-0"}),e.jsx("span",{children:"Syncs name, email, phone, address, notes, and lead source"})]}),Y?e.jsxs("div",{className:"space-y-3 mt-4",children:[e.jsx("div",{className:"rounded-lg border p-3 space-y-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:"BoldTrail Connected"}),(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(Oe,{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(Kl,{children:[e.jsx(jx,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Sn,{className:"h-4 w-4"})})}),e.jsxs(Ol,{children:[e.jsxs(zl,{children:[e.jsx(Ul,{children:"Disconnect BoldTrail?"}),e.jsx(ql,{children:"This will remove your API token. Previously synced contacts will remain in both systems."})]}),e.jsxs(Bl,{children:[e.jsx($l,{children:"Cancel"}),e.jsx(Ml,{onClick:()=>D.mutate(),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]})}),e.jsx("div",{className:"rounded-lg border p-3",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(gj,{className:"h-4 w-4 mt-0.5 text-emerald-600 shrink-0"}),e.jsxs("div",{className:"flex-1 space-y-1",children:[e.jsx("p",{className:"text-sm font-medium",children:"Include contacts without an email address"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Phone or name-only leads come across too. Turn this off to sync only contacts that have an email address."})]}),e.jsx(fn,{checked:(P==null?void 0:P.sync_include_no_email)!==!1,onCheckedChange:ce=>G.mutate({sync_include_no_email:ce}),disabled:G.isPending})]})}),e.jsxs("div",{className:"rounded-lg border p-3 space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(gj,{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(fn,{checked:!!(P!=null&&P.sync_only_owned),onCheckedChange:ce=>G.mutate({sync_only_owned:ce}),disabled:G.isPending})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(J,{className:"text-xs",children:"Your BoldTrail Agent ID"}),C?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xe,{type:"number",placeholder:"e.g. 12345",value:j,onChange:ce=>S(ce.target.value),className:"h-8 text-sm"}),e.jsx(B,{size:"sm",onClick:()=>{const ce=j.trim()===""?null:Number(j);G.mutate({kvcore_user_id:ce})},disabled:G.isPending,children:"Save"}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>E(!1),children:"Cancel"})]}):e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-sm font-mono",children:(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(B,{size:"sm",variant:"outline",onClick:()=>V.mutate(),disabled:V.isPending,children:[V.isPending?e.jsx(uo,{className:"h-3 w-3 mr-1 animate-spin"}):null,"Auto-detect"]}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>{var ce;S(((ce=P==null?void 0:P.kvcore_user_id)==null?void 0:ce.toString())??""),E(!0)},children:"Edit"})]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Your numeric BoldTrail (kvCORE) user ID. To find it: log into BoldTrail → click your avatar (top right) → ",e.jsx("strong",{children:"My Profile"}),". The ID appears in the page URL after ",e.jsx("code",{children:"/users/"})," (e.g. ",e.jsxs("code",{children:[".../users/",e.jsx("strong",{children:"12345"})]}),"). You can also open any contact you own in BoldTrail and look at the URL — your ID is shown as the assigned agent. Auto-detect tries to find it via your API token first."]})]})]}),e.jsx("div",{className:"rounded-lg border p-3",children:e.jsx(DTe,{value:Z,onChange:ce=>O.mutate(ce)})}),e.jsx("div",{className:"flex gap-2",children:e.jsxs(B,{onClick:()=>$.mutate(),disabled:$.isPending||H.isPending,variant:"outline",className:"gap-2",children:[$.isPending?e.jsx(uo,{className:"h-4 w-4 animate-spin"}):e.jsx(ya,{className:"h-4 w-4"}),"Preview Sync"]})})]}):e.jsxs("div",{className:"mt-4 space-y-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{type:"password",placeholder:"Paste your BoldTrail API token",value:t,onChange:ce=>n(ce.target.value),className:"flex-1"}),e.jsxs(B,{onClick:()=>I.mutate(t),disabled:!t||t.length<10||I.isPending,children:[I.isPending?e.jsx(uo,{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(Ls,{open:r,onOpenChange:ce=>{H.isPending||a(ce)},children:e.jsxs(Ps,{className:"sm:max-w-lg",children:[e.jsxs(Os,{children:[e.jsxs(Ds,{className:"flex items-center gap-2",children:[e.jsx(Lg,{className:"h-5 w-5 text-emerald-600"}),"Sync Preview"]}),e.jsx(_r,{children:"Review what will happen when you sync your contacts."})]}),o&&(()=>{const ce=ne==="pull_only"?0:o.to_push,ie=ne==="push_only"?0:o.to_pull;return e.jsxs("div",{className:"space-y-4",children:[e.jsx(DTe,{value:ne,onChange:f,size:"sm"}),o.owner_filter_active&&e.jsxs("div",{className:"rounded-md border border-emerald-200 bg-emerald-50 p-2 text-xs text-emerald-900 flex items-start gap-2",children:[e.jsx(gj,{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 ${ne==="pull_only"?"opacity-40":""}`,children:[e.jsx("p",{className:"text-2xl font-bold text-emerald-600",children:ce}),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 ${ne==="push_only"?"opacity-40":""}`,children:[e.jsx("p",{className:"text-2xl font-bold text-blue-600",children:ie}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(zf,{className:"h-3 w-3"})," 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(In,{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"]}),H.isPending&&e.jsxs("div",{className:"space-y-2 py-2",children:[e.jsx(Fi,{value:g||10,className:"h-2"}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:y||"Sync in progress..."})]}),ce>0&&e.jsxs(f1,{open:d,onOpenChange:u,children:[e.jsx(x1,{asChild:!0,children:e.jsxs(B,{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"}),ce," contacts to push to BoldTrail"]}),e.jsx(tl,{className:`h-3 w-3 transition-transform ${d?"rotate-180":""}`})]})}),e.jsx(g1,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[o.push_preview.map((te,ae)=>e.jsxs("div",{className:"px-3 py-1.5 text-xs flex justify-between",children:[e.jsx("span",{className:"font-medium",children:te.name||"No name"}),e.jsx("span",{className:"text-muted-foreground",children:te.email})]},ae)),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"]})]})})]}),ie>0&&e.jsxs(f1,{open:h,onOpenChange:m,children:[e.jsx(x1,{asChild:!0,children:e.jsxs(B,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(zf,{className:"h-3 w-3 text-blue-600"}),ie," contacts to pull from BoldTrail"]}),e.jsx(tl,{className:`h-3 w-3 transition-transform ${h?"rotate-180":""}`})]})}),e.jsx(g1,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[o.pull_preview.map((te,ae)=>e.jsxs("div",{className:"px-3 py-1.5 text-xs flex justify-between",children:[e.jsx("span",{className:"font-medium",children:te.name||"No name"}),e.jsx("span",{className:"text-muted-foreground",children:te.email})]},ae)),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"]})]})})]}),ce===0&&ie===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(B,{variant:"outline",onClick:()=>a(!1),disabled:H.isPending,children:"Cancel"}),e.jsxs(B,{onClick:()=>H.mutate(),disabled:H.isPending||ce===0&&ie===0,className:"gap-2",children:[H.isPending?e.jsx(uo,{className:"h-4 w-4 animate-spin"}):e.jsx(Lg,{className:"h-4 w-4"}),H.isPending?"Syncing...":"Sync Now"]})]})]})})()]})}),e.jsx(Ls,{open:i,onOpenChange:l,children:e.jsxs(Ps,{className:"sm:max-w-2xl p-0 overflow-hidden",children:[e.jsx(Os,{className:"p-6 pb-0",children:e.jsxs(Ds,{className:"flex items-center gap-2",children:[e.jsx(Lg,{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 eU=async s=>{const{data:t,error:n}=await q.functions.invoke("lofty-sync",{body:s});if(n)throw new Error(n.message);if(t!=null&&t.error)throw new Error(typeof t.error=="string"?t.error:JSON.stringify(t.error));return t};function Ntr(){const s=Bt(),[t,n]=_.useState(""),[r,a]=_.useState(""),[i,l]=_.useState(!1),[o,c]=_.useState(0),[d,u]=_.useState(null),[h,m]=_.useState(null),{data:p,isLoading:f}=at({queryKey:["lofty-status"],queryFn:async()=>await eU({action:"status"})}),y=()=>s.invalidateQueries({queryKey:["lofty-status"]}),v=mt({mutationFn:async()=>eU({action:"save_token",api_token:t.trim()}),onSuccess:E=>{se.success(E!=null&&E.contact_count?`Connected to Lofty — ${E.contact_count} contacts found`:"Connected to Lofty"),n(""),y()},onError:E=>se.error(E.message)}),g=mt({mutationFn:async()=>eU({action:"disconnect"}),onSuccess:()=>{se.success("Lofty disconnected"),y()},onError:E=>se.error(E.message)}),b=mt({mutationFn:async E=>eU({action:"save_settings",...E}),onSuccess:()=>y(),onError:E=>se.error(E.message)}),j=mt({mutationFn:async()=>eU({action:"detect_owner"}),onSuccess:E=>{const P=(E==null?void 0:E.candidates)||[];m(P),P.length===0?se.info("No assigned-agent IDs found on your Lofty contacts."):P.length===1?(b.mutate({lofty_user_id:P[0].id}),se.success(`Using Lofty agent ID ${P[0].id}`)):se.success("Pick which Lofty agent ID is yours below.")},onError:E=>se.error(E.message)}),S=async()=>{l(!0),c(2),u("Starting Lofty sync…");try{let E="start",P=0,M=null,I=0;for(;E&&I<400;){I++;const D=await eU({action:"sync",phase:E,offset:P,sync_log_id:M});M=D.sync_log_id||M,D.progress&&u(D.progress),c(O=>Math.min(95,O+4)),E=D.next_phase,P=D.next_offset||0,E||(c(100),u(D.message||"Sync complete"),se.success(D.message||"Lofty sync complete"))}}catch(E){se.error(E.message||"Lofty sync failed"),u(null)}finally{l(!1),setTimeout(()=>c(0),2500),y()}},C=!!(p!=null&&p.connected);return e.jsxs(ve,{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(St,{className:"flex items-center gap-2",children:["Lofty",C?e.jsxs(Oe,{variant:"secondary",className:"gap-1",children:[e.jsx(_l,{className:"h-3 w-3"})," Connected"]}):e.jsx(Oe,{variant:"outline",children:"Not connected"})]}),e.jsx(kn,{children:"Sync your Lofty (formerly Chime) contacts — names, emails, phones, address, source, stage, tags and notes — into Agent OS."})]}),C&&e.jsxs(Kl,{children:[e.jsx(jx,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon","aria-label":"Disconnect Lofty",children:e.jsx(Sn,{className:"h-4 w-4"})})}),e.jsxs(Ol,{children:[e.jsxs(zl,{children:[e.jsx(Ul,{children:"Disconnect Lofty?"}),e.jsx(ql,{children:"Your API key and sync settings will be removed. Contacts already imported into Agent OS stay put."})]}),e.jsxs(Bl,{children:[e.jsx($l,{children:"Cancel"}),e.jsx(Ml,{onClick:()=>g.mutate(),children:"Disconnect"})]})]})]})]})}),e.jsx(Me,{className:"space-y-5",children:f?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Ct,{className:"h-4 w-4 animate-spin"})," Loading…"]}):C?e.jsxs("div",{className:"space-y-5",children:[e.jsx(DTe,{value:(p==null?void 0:p.sync_direction)||"pull_only",onChange:E=>b.mutate({sync_direction:E}),size:"sm"}),e.jsxs("div",{className:"space-y-3 rounded-lg border p-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Only my contacts"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Skip team/brokerage contacts assigned to other Lofty agents."})]}),e.jsx(fn,{checked:!!(p!=null&&p.sync_only_owned),onCheckedChange:E=>b.mutate({sync_only_owned:E})})]}),(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(B,{size:"sm",variant:"outline",onClick:()=>j.mutate(),disabled:j.isPending,children:[j.isPending?e.jsx(Ct,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(In,{className:"h-3.5 w-3.5"}),"Detect my Lofty agent ID"]}),(p==null?void 0:p.lofty_user_id)&&e.jsxs(Oe,{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(E=>e.jsxs(B,{size:"sm",variant:(p==null?void 0:p.lofty_user_id)===E.id?"default":"outline",onClick:()=>b.mutate({lofty_user_id:E.id}),children:[E.id," · ",E.count," contacts"]},E.id))})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Import notes"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Pull each contact's Lofty notes into their Agent OS notes (deduped)."})]}),e.jsx(fn,{checked:!!(p!=null&&p.import_notes),onCheckedChange:E=>b.mutate({import_notes:E})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{htmlFor:"lofty-tags",className:"text-sm",children:"Tag filter (optional)"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{id:"lofty-tags",placeholder:((p==null?void 0:p.pull_tag_filter)||[]).join(", ")||"e.g. Sphere, Buyer",value:r,onChange:E=>a(E.target.value)}),e.jsx(B,{variant:"outline",onClick:()=>b.mutate({pull_tag_filter:r.split(",").map(E=>E.trim()).filter(Boolean)}),children:"Save"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Leave empty to import every contact. Comma-separated Lofty tags."})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(B,{onClick:S,disabled:i,children:[i?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(uo,{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(Fi,{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(E=>e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 rounded-md border px-3 py-2 text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:new Date(E.created_at).toLocaleString("en-US",{timeZone:"America/New_York"})}),e.jsxs("span",{children:[E.contacts_pulled," imported · ",E.contacts_pushed," pushed ·"," ",E.contacts_skipped," skipped"]}),e.jsx(Oe,{variant:E.status==="completed"?"secondary":"destructive",children:E.status})]},E.id))})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{htmlFor:"lofty-key",children:"Lofty API Key"}),e.jsx(xe,{id:"lofty-key",type:"password",placeholder:"Paste your Lofty API key",value:t,onChange:E=>n(E.target.value),autoComplete:"off"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["In Lofty go to ",e.jsx("strong",{children:"Settings → Integrations → API Key Management"})," and create a key with contact access."]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{onClick:()=>v.mutate(),disabled:t.trim().length<10||v.isPending,children:[v.isPending?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(pN,{className:"h-4 w-4"}),"Connect Lofty"]}),e.jsx(B,{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(wr,{className:"ml-1 h-3 w-3"})]})})]})]})})]})}function ktr(){const s=Bt(),[t,n]=_.useState(""),[r,a]=_.useState(!1),[i,l]=_.useState(0),[o,c]=_.useState(null),{data:d,isLoading:u}=at({queryKey:["fub-status"],queryFn:async()=>{const{data:y,error:v}=await q.functions.invoke("followupboss-sync",{body:{action:"status"}});if(v)throw v;return y}}),h=mt({mutationFn:async y=>{const{data:v,error:g}=await q.functions.invoke("followupboss-sync",{body:{action:"save_token",api_key:y}});if(g)throw g;if(v!=null&&v.error)throw new Error(v.error);return v},onSuccess:()=>{se.success("Connected to Follow Up Boss"),n(""),s.invalidateQueries({queryKey:["fub-status"]})},onError:y=>se.error(y.message)}),m=mt({mutationFn:async()=>{const{error:y}=await q.functions.invoke("followupboss-sync",{body:{action:"disconnect"}});if(y)throw y},onSuccess:()=>{se.success("Disconnected"),s.invalidateQueries({queryKey:["fub-status"]})}}),p=mt({mutationFn:async y=>{const{error:v}=await q.functions.invoke("followupboss-sync",{body:{action:"set_direction",sync_direction:y}});if(v)throw v},onSuccess:()=>s.invalidateQueries({queryKey:["fub-status"]})}),f=async()=>{a(!0),l(0),c("Pulling from FUB…");let y=0,v=0,g=0,b=0;try{for(;;){const{data:E,error:P}=await q.functions.invoke("followupboss-sync",{body:{action:"sync",offset:y}});if(P)throw P;if(E!=null&&E.error)throw new Error(E.error);v+=E.chunk_created||0,g+=E.chunk_updated||0,b+=E.chunk_skipped||0,y=E.next_offset;const M=E.total?Math.min(100,Math.round(y/E.total*100)):100;if(l(M),c(`Pulling · ${y} / ${E.total||"?"}`),E.done)break;await new Promise(I=>setTimeout(I,400))}let j=0,S=0;if((d==null?void 0:d.sync_direction)==="bidirectional"){let E=0;for(l(0),c("Pushing to FUB…");;){const{data:P,error:M}=await q.functions.invoke("followupboss-sync",{body:{action:"push",offset:E}});if(M)throw M;if(P!=null&&P.error)throw new Error(P.error);j+=P.chunk_pushed||0,S+=P.chunk_failed||0,E=P.next_offset;const I=P.total?Math.min(100,Math.round(E/P.total*100)):100;if(l(I),c(`Pushing · ${E} / ${P.total||"?"}`),P.done)break;await new Promise(D=>setTimeout(D,400))}}const C=j||S?` · pushed ${j}${S?`, ${S} failed`:""}`:"";se.success(`Sync complete · ${v} new, ${g} updated${b?`, ${b} skipped`:""}${C}`),s.invalidateQueries({queryKey:["fub-status"]})}catch(j){se.error(j.message||"Sync failed")}finally{a(!1),setTimeout(()=>{l(0),c(null)},2500)}};return e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{children:[e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(pN,{className:"h-5 w-5 text-primary"}),"Follow Up Boss",(d==null?void 0:d.connected)&&e.jsxs(Oe,{variant:"default",className:"ml-1",children:[e.jsx(_l,{className:"h-3 w-3 mr-1"})," Connected"]})]}),e.jsx(kn,{children:"Sync your Follow Up Boss contacts into Agent OS."})]})})}),e.jsx(Me,{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(fn,{checked:d.sync_direction==="bidirectional",onCheckedChange:y=>p.mutate(y?"bidirectional":"pull_only"),disabled:r||p.isPending})]}),o&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(Fi,{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(B,{onClick:f,disabled:r,children:[e.jsx(uo,{className:`h-4 w-4 mr-2 ${r?"animate-spin":""}`}),r?"Syncing…":"Sync Now"]}),e.jsxs(Kl,{children:[e.jsx(jx,{asChild:!0,children:e.jsxs(B,{variant:"outline",disabled:r,children:[e.jsx(Sn,{className:"h-4 w-4 mr-2"})," Disconnect"]})}),e.jsxs(Ol,{children:[e.jsxs(zl,{children:[e.jsx(Ul,{children:"Disconnect Follow Up Boss?"}),e.jsx(ql,{children:"Your API key will be removed. Synced contacts stay in Agent OS."})]}),e.jsxs(Bl,{children:[e.jsx($l,{children:"Cancel"}),e.jsx(Ml,{onClick:()=>m.mutate(),children:"Disconnect"})]})]})]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(J,{htmlFor:"fub-key",children:"Follow Up Boss API Key"}),e.jsx(xe,{id:"fub-key",type:"password",placeholder:"fka_live_...",value:t,onChange:y=>n(y.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(wr,{className:"h-3 w-3"})]})]})]}),e.jsx(B,{onClick:()=>h.mutate(t),disabled:!t.trim()||h.isPending,children:h.isPending?"Connecting…":"Connect"})]})})]})}function Str(){var $;const s=Bt(),[t,n]=_.useState(""),[r,a]=_.useState(""),[i,l]=_.useState(!1),[o,c]=_.useState(0),[d,u]=_.useState(null),[h,m]=_.useState(!1),[p,f]=_.useState(null),[y,v]=_.useState(!1),[g,b]=_.useState(new Set),{data:j,isLoading:S}=at({queryKey:["cloze-status"],queryFn:async()=>{const{data:H,error:Y}=await q.functions.invoke("cloze-sync",{body:{action:"status"}});if(Y)throw Y;return H}}),C=mt({mutationFn:async()=>{const{data:H,error:Y}=await q.functions.invoke("cloze-sync",{body:{action:"save_token",api_key:t.trim(),account_email:r.trim()}});if(Y)throw Y;if(H!=null&&H.error)throw new Error(H.error);return H},onSuccess:()=>{se.success("Connected to Cloze"),n(""),a(""),s.invalidateQueries({queryKey:["cloze-status"]})},onError:H=>se.error(H.message)}),E=mt({mutationFn:async()=>{const{error:H}=await q.functions.invoke("cloze-sync",{body:{action:"disconnect"}});if(H)throw H},onSuccess:()=>{se.success("Cloze disconnected"),s.invalidateQueries({queryKey:["cloze-status"]})}}),P=mt({mutationFn:async H=>{const{error:Y}=await q.functions.invoke("cloze-sync",{body:{action:"set_direction",sync_direction:H}});if(Y)throw Y},onSuccess:()=>s.invalidateQueries({queryKey:["cloze-status"]})}),M=mt({mutationFn:async H=>{const{error:Y}=await q.functions.invoke("cloze-sync",{body:{action:"set_scope",...H}});if(Y)throw Y},onSuccess:()=>s.invalidateQueries({queryKey:["cloze-status"]})}),I=async()=>{v(!0);try{const{data:H,error:Y}=await q.functions.invoke("cloze-sync",{body:{action:"list_segments"}});if(Y)throw Y;if(H!=null&&H.error)throw new Error(H.error);f(H.segments||[]),b(new Set((j==null?void 0:j.selected_segments)||[])),m(!0)}catch(H){se.error(H.message||"Failed to load segments")}finally{v(!1)}},D=async()=>{const H=Array.from(g);await M.mutateAsync({sync_scope:"segments",selected_segments:H}),se.success(`Saved · ${H.length} segment(s) selected`),m(!1)},O=async()=>{const H=(j==null?void 0:j.sync_direction)||"pull_only";l(!0),c(0);try{if(H==="pull_only"||H==="bidirectional"){u("Pulling from Cloze…");let Y=0,Z=0,ne=0;for(;;){const{data:ce,error:ie}=await q.functions.invoke("cloze-sync",{body:{action:"sync",offset:Y}});if(ie)throw ie;if(ce!=null&&ce.error)throw new Error(ce.error);if(Z+=ce.chunk_created||0,ne+=ce.chunk_updated||0,Y=ce.next_offset,u(`Pulling · ${Z+ne} contacts processed`),c(ce.done?100:Math.min(95,(Z+ne)%200/2)),ce.done)break;await new Promise(te=>setTimeout(te,300))}se.success(`Pulled · ${Z} new, ${ne} updated`)}if(H==="push_only"||H==="bidirectional"){c(0),u("Pushing to Cloze…");let Y=0,Z=0,ne=0;for(;;){const{data:ce,error:ie}=await q.functions.invoke("cloze-sync",{body:{action:"push",offset:Y}});if(ie)throw ie;if(ce!=null&&ce.error)throw new Error(ce.error);Z+=ce.chunk_pushed||0,ne+=ce.chunk_failed||0,Y=ce.next_offset;const te=ce.total?Math.min(100,Math.round(Y/ce.total*100)):100;if(c(te),u(`Pushing · ${Y} / ${ce.total||"?"}`),ce.done)break;await new Promise(ae=>setTimeout(ae,300))}se.success(`Pushed · ${Z}${ne?`, ${ne} failed`:""}`)}s.invalidateQueries({queryKey:["cloze-status"]})}catch(Y){se.error(Y.message||"Sync failed")}finally{l(!1),setTimeout(()=>{c(0),u(null)},2e3)}},V=(j==null?void 0:j.sync_scope)||"all",G=(($=j==null?void 0:j.selected_segments)==null?void 0:$.length)||0;return e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{children:[e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(pN,{className:"h-5 w-5 text-primary"}),"Cloze",(j==null?void 0:j.connected)&&e.jsxs(Oe,{variant:"default",className:"ml-1",children:[e.jsx(_l,{className:"h-3 w-3 mr-1"})," Connected"]})]}),e.jsx(kn,{children:"Sync contacts between Cloze and Agent OS using your personal Cloze API key."})]})})}),e.jsx(Me,{className:"space-y-4",children:S?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading…"}):j!=null&&j.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:j.account_email})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Last sync"}),e.jsx("p",{className:"font-medium",children:j.last_sync_at?new Date(j.last_sync_at).toLocaleString():"Never"})]})]}),j.last_sync_status==="error"&&e.jsx("p",{className:"text-sm text-destructive",children:j.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(is,{value:j.sync_direction||"pull_only",onValueChange:H=>P.mutate(H),disabled:i||P.isPending,children:[e.jsx(rs,{className:"w-[180px]",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"pull_only",children:"Pull from Cloze"}),e.jsx(He,{value:"push_only",children:"Push to Cloze"}),e.jsx(He,{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:V==="all"?"All Cloze contacts.":`${G} segment${G===1?"":"s"} selected.`})]}),e.jsxs(is,{value:V,onValueChange:H=>{H==="all"?M.mutate({sync_scope:"all",selected_segments:[]}):(M.mutate({sync_scope:"segments",selected_segments:j.selected_segments||[]}),I())},disabled:i||M.isPending,children:[e.jsx(rs,{className:"w-[180px]",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All contacts"}),e.jsx(He,{value:"segments",children:"Selected segments"})]})]})]}),V==="segments"&&e.jsxs("div",{children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:I,disabled:y,children:[e.jsx(lJ,{className:"h-4 w-4 mr-2"}),y?"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(H=>{const Y=g.has(H.id);return e.jsxs("label",{className:"flex items-center gap-3 p-2 cursor-pointer hover:bg-muted/50",children:[e.jsx($a,{checked:Y,onCheckedChange:Z=>{const ne=new Set(g);Z?ne.add(H.id):ne.delete(H.id),b(ne)}}),e.jsx("span",{className:"flex-1 text-sm",children:H.name}),H.count!=null&&e.jsx(Oe,{variant:"secondary",className:"text-xs",children:H.count})]},H.id)})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{size:"sm",onClick:D,disabled:M.isPending,children:["Save selection (",g.size,")"]}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>m(!1),children:"Cancel"})]})]})]})]}),d&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(Fi,{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(Kl,{children:[e.jsx(jx,{asChild:!0,children:e.jsxs(B,{disabled:i,children:[e.jsx(uo,{className:`h-4 w-4 mr-2 ${i?"animate-spin":""}`}),i?"Syncing…":"Sync Now"]})}),e.jsxs(Ol,{children:[e.jsxs(zl,{children:[e.jsx(Ul,{children:"Preview sync"}),e.jsx(ql,{asChild:!0,children:e.jsx(Ctr,{segments:p})})]}),e.jsxs(Bl,{children:[e.jsx($l,{children:"Cancel"}),e.jsx(Ml,{onClick:O,children:"Start Sync"})]})]})]}),e.jsxs(Kl,{children:[e.jsx(jx,{asChild:!0,children:e.jsxs(B,{variant:"outline",disabled:i,children:[e.jsx(Sn,{className:"h-4 w-4 mr-2"})," Disconnect"]})}),e.jsxs(Ol,{children:[e.jsxs(zl,{children:[e.jsx(Ul,{children:"Disconnect Cloze?"}),e.jsx(ql,{children:"Your API key will be removed. Contacts already synced will remain."})]}),e.jsxs(Bl,{children:[e.jsx($l,{children:"Cancel"}),e.jsx(Ml,{onClick:()=>E.mutate(),children:"Disconnect"})]})]})]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(J,{htmlFor:"cloze-email",children:"Cloze Account Email"}),e.jsx(xe,{id:"cloze-email",type:"email",placeholder:"you@example.com",value:r,onChange:H=>a(H.target.value)})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"cloze-key",children:"Cloze API Key"}),e.jsx(xe,{id:"cloze-key",type:"password",placeholder:"Your personal Cloze API key",value:t,onChange:H=>n(H.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(wr,{className:"h-3 w-3"})]})]})]}),e.jsx(B,{onClick:()=>C.mutate(),disabled:!t.trim()||!r.trim()||C.isPending,children:C.isPending?"Connecting…":"Connect Cloze"})]})})]})}function Ctr({segments:s}){var h;const[t,n]=_.useState(!0),[r,a]=_.useState(null),[i,l]=_.useState(null);if(_.useEffect(()=>{(async()=>{try{const{data:m,error:p}=await q.functions.invoke("cloze-sync",{body:{action:"preview"}});if(p)throw p;if(m!=null&&m.error)throw new Error(m.error);a(m)}catch(m){l(m.message||"Could not load preview")}finally{n(!1)}})()},[]),t)return e.jsx("span",{className:"text-sm",children:"Calculating…"});if(i)return e.jsx("span",{className:"text-sm text-destructive",children:i});const o=new Map((s||[]).map(m=>[m.id,m.name])),c=r.total_incoming??0,d=r.already_synced??0,u=Math.max(0,c-d);return e.jsxs("div",{className:"space-y-3 text-sm text-foreground",children:[e.jsxs("div",{className:"rounded-md border p-3 space-y-1",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsxs("span",{children:["Contacts in Cloze (",r.scope==="segments"?"selected segments":"all",")"]}),e.jsx("strong",{children:c.toLocaleString()})]}),e.jsxs("div",{className:"flex justify-between text-muted-foreground",children:[e.jsx("span",{children:"Already linked to Cloze in your CRM"}),e.jsx("span",{children:d.toLocaleString()})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"Estimated new contacts"}),e.jsxs("strong",{children:["~",u.toLocaleString()]})]})]}),r.scope==="segments"&&((h=r.segment_counts)==null?void 0:h.length)>0&&e.jsx("div",{className:"rounded-md border p-3 space-y-1 max-h-40 overflow-auto",children:r.segment_counts.map(m=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{children:o.get(m.id)||m.id}),e.jsx("span",{className:"text-muted-foreground",children:m.total})]},m.id))}),e.jsx("p",{className:"text-xs text-muted-foreground",children:r.note})]})}function Atr(){const s=Bt(),[t,n]=_.useState(""),[r,a]=_.useState(!1),[i,l]=_.useState(0),[o,c]=_.useState(null),{data:d,isLoading:u}=at({queryKey:["boomtown-status"],queryFn:async()=>{const{data:y,error:v}=await q.functions.invoke("boomtown-sync",{body:{action:"status"}});if(v)throw v;return y}}),h=mt({mutationFn:async y=>{const{data:v,error:g}=await q.functions.invoke("boomtown-sync",{body:{action:"save_token",api_key:y}});if(g)throw g;if(v!=null&&v.error)throw new Error(v.error);return v},onSuccess:()=>{se.success("Connected to Boomtown"),n(""),s.invalidateQueries({queryKey:["boomtown-status"]})},onError:y=>se.error(y.message)}),m=mt({mutationFn:async()=>{const{error:y}=await q.functions.invoke("boomtown-sync",{body:{action:"disconnect"}});if(y)throw y},onSuccess:()=>{se.success("Disconnected"),s.invalidateQueries({queryKey:["boomtown-status"]})}}),p=mt({mutationFn:async y=>{const{error:v}=await q.functions.invoke("boomtown-sync",{body:{action:"set_direction",sync_direction:y}});if(v)throw v},onSuccess:()=>s.invalidateQueries({queryKey:["boomtown-status"]})}),f=async()=>{a(!0),l(0),c("Pulling from Boomtown…");let y=0,v=0,g=0,b=0;try{for(;;){const{data:E,error:P}=await q.functions.invoke("boomtown-sync",{body:{action:"sync",offset:y}});if(P)throw P;if(E!=null&&E.error)throw new Error(E.error);v+=E.chunk_created||0,g+=E.chunk_updated||0,b+=E.chunk_skipped||0,y=E.next_offset;const M=E.total?Math.min(100,Math.round(y/E.total*100)):100;if(l(M),c(`Pulling · ${y} / ${E.total||"?"}`),E.done)break;await new Promise(I=>setTimeout(I,400))}let j=0,S=0;if((d==null?void 0:d.sync_direction)==="bidirectional"){let E=0;for(l(0),c("Pushing to Boomtown…");;){const{data:P,error:M}=await q.functions.invoke("boomtown-sync",{body:{action:"push",offset:E}});if(M)throw M;if(P!=null&&P.error)throw new Error(P.error);j+=P.chunk_pushed||0,S+=P.chunk_failed||0,E=P.next_offset;const I=P.total?Math.min(100,Math.round(E/P.total*100)):100;if(l(I),c(`Pushing · ${E} / ${P.total||"?"}`),P.done)break;await new Promise(D=>setTimeout(D,400))}}const C=j||S?` · pushed ${j}${S?`, ${S} failed`:""}`:"";se.success(`Sync complete · ${v} new, ${g} updated${b?`, ${b} skipped`:""}${C}`),s.invalidateQueries({queryKey:["boomtown-status"]})}catch(j){se.error(j.message||"Sync failed")}finally{a(!1),setTimeout(()=>{l(0),c(null)},2500)}};return e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{children:[e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(pN,{className:"h-5 w-5 text-primary"}),"Boomtown",(d==null?void 0:d.connected)&&e.jsxs(Oe,{variant:"default",className:"ml-1",children:[e.jsx(_l,{className:"h-3 w-3 mr-1"})," Connected"]})]}),e.jsx(kn,{children:"Sync your Boomtown contacts into Agent OS."})]})})}),e.jsx(Me,{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(fn,{checked:d.sync_direction==="bidirectional",onCheckedChange:y=>p.mutate(y?"bidirectional":"pull_only"),disabled:r||p.isPending})]}),o&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(Fi,{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(B,{onClick:f,disabled:r,children:[e.jsx(uo,{className:`h-4 w-4 mr-2 ${r?"animate-spin":""}`}),r?"Syncing…":"Sync Now"]}),e.jsxs(Kl,{children:[e.jsx(jx,{asChild:!0,children:e.jsxs(B,{variant:"outline",disabled:r,children:[e.jsx(Sn,{className:"h-4 w-4 mr-2"})," Disconnect"]})}),e.jsxs(Ol,{children:[e.jsxs(zl,{children:[e.jsx(Ul,{children:"Disconnect Boomtown?"}),e.jsx(ql,{children:"Your API key will be removed. Synced contacts stay in Agent OS."})]}),e.jsxs(Bl,{children:[e.jsx($l,{children:"Cancel"}),e.jsx(Ml,{onClick:()=>m.mutate(),children:"Disconnect"})]})]})]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(J,{htmlFor:"boomtown-key",children:"Boomtown API Key"}),e.jsx(xe,{id:"boomtown-key",type:"password",placeholder:"Paste your Boomtown Ambassador API key",value:t,onChange:y=>n(y.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(wr,{className:"h-3 w-3"})]})]}),e.jsx(B,{onClick:()=>h.mutate(t),disabled:!t.trim()||h.isPending,children:h.isPending?"Connecting…":"Connect"})]})})]})}function yrs(){const s=Fn(),[t,n]=_.useState(""),[r,a]=_.useState(""),[i,l]=_.useState("Test from ReLevelUp"),[o,c]=_.useState(!1),{data:d,isLoading:u}=at({queryKey:["ses-config"],queryFn:async()=>{const p=await pse();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){se.error("Please fill in From and To email addresses");return}c(!0);try{const p=await pse(),y=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();y.success?se.success(`Test email sent! Message ID: ${y.messageId}`):se.error(y.error||"Failed to send test email")}catch(p){se.error(p.message||"Failed to send test email")}finally{c(!1)}},m=(d==null?void 0:d.configured)===!0;return e.jsxs(ve,{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(ln,{className:"h-5 w-5 text-orange-600"})}),e.jsxs("div",{children:[e.jsx(St,{className:"text-lg",children:"Amazon SES — Mass Email"}),e.jsx(kn,{children:"Send bulk email campaigns via Amazon SES"})]})]}),e.jsx(Oe,{variant:m?"default":"secondary",children:u?"Checking...":m?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(_l,{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(Me,{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(J,{className:"text-xs",children:"From Email"}),e.jsx(xe,{placeholder:"notifications@mail.relevelup.com",value:r,onChange:p=>a(p.target.value),className:"text-sm"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(J,{className:"text-xs",children:"To Email"}),e.jsx(xe,{placeholder:"your@email.com",value:t,onChange:p=>n(p.target.value),className:"text-sm"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(J,{className:"text-xs",children:"Subject"}),e.jsx(xe,{value:i,onChange:p=>l(p.target.value),className:"text-sm"})]})]}),e.jsxs(B,{onClick:h,disabled:o,size:"sm",children:[o?e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Or,{className:"h-4 w-4 mr-2"}),"Send Test"]})]}),e.jsxs(B,{onClick:()=>s("/admin/email-campaigns"),className:"w-full",children:[e.jsx(wh,{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(Me,{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 SBe(s){const t=await pse(),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 Etr({status:s}){return s==="verified"?e.jsxs(Oe,{className:"bg-green-500/10 text-green-700 hover:bg-green-500/20 border-green-500/20",children:[e.jsx(Er,{className:"h-3 w-3 mr-1"})," Verified"]}):s==="pending"?e.jsxs(Oe,{variant:"secondary",children:[e.jsx(Gr,{className:"h-3 w-3 mr-1"})," Pending — check inbox"]}):s==="failed"||s==="temporary_failure"?e.jsxs(Oe,{variant:"destructive",children:[e.jsx(Xo,{className:"h-3 w-3 mr-1"})," Failed"]}):e.jsxs(Oe,{variant:"outline",children:[e.jsx(Xo,{className:"h-3 w-3 mr-1"})," Not started"]})}function vrs({brokerageId:s,onVerifiedSelect:t}){const n=Bt(),[r,a]=_.useState(""),[i,l]=_.useState(""),[o,c]=_.useState(!1),[d,u]=_.useState(null),[h,m]=_.useState(null),{data:p,isLoading:f}=at({queryKey:["brokerage-verified-senders",s],queryFn:async()=>{const{data:b,error:j}=await q.from("brokerage_verified_senders").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(j)throw j;return b||[]}}),y=mt({mutationFn:async()=>SBe({action:"request_verification",brokerage_id:s,email:r,display_name:i||void 0}),onSuccess:()=>{n.invalidateQueries({queryKey:["brokerage-verified-senders",s]}),se.success("Verification email sent",{description:`Check ${r} and click the AWS verification link.`}),a(""),l(""),c(!1)},onError:b=>se.error(b.message)}),v=async b=>{var j,S;u(b.id);try{const C=await SBe({action:"check_status",sender_id:b.id});n.invalidateQueries({queryKey:["brokerage-verified-senders",s]}),((j=C.sender)==null?void 0:j.status)==="verified"?se.success(`${b.email} is verified! 🎉`):se.info(`Status: ${((S=C.sender)==null?void 0:S.status)||"unknown"}`)}catch(C){se.error(C.message)}finally{u(null)}},g=mt({mutationFn:async b=>SBe({action:"delete",sender_id:b}),onSuccess:()=>{n.invalidateQueries({queryKey:["brokerage-verified-senders",s]}),se.success("Sender removed"),m(null)},onError:b=>se.error(b.message)});return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium mb-1",children:"Verified Sender Addresses"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Verify any email address (yours or your brokerage's) so recruiting emails can be sent from that address. Anyone managing this brokerage can use these senders."})]}),f?e.jsx("div",{className:"text-xs text-muted-foreground py-3",children:"Loading…"}):p&&p.length>0?e.jsx("div",{className:"space-y-2",children:p.map(b=>e.jsxs("div",{className:"flex items-center justify-between gap-3 p-3 rounded-lg border bg-card",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[e.jsx("div",{className:"h-9 w-9 rounded-full bg-muted flex items-center justify-center shrink-0",children:e.jsx(ln,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-sm font-medium truncate",children:b.email}),e.jsx(Etr,{status:b.status})]}),b.display_name&&e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:['"',b.display_name,'"']})]})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[b.status==="verified"&&t&&e.jsx(B,{size:"sm",variant:"outline",onClick:()=>t(b.email),children:"Use"}),b.status!=="verified"&&e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>v(b),disabled:d===b.id,title:"Refresh status from AWS",children:d===b.id?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(uo,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>m(b),className:"text-destructive hover:text-destructive",children:e.jsx(Sn,{className:"h-4 w-4"})})]})]},b.id))}):e.jsx("div",{className:"text-xs text-muted-foreground py-2 italic",children:"No verified senders yet. Add one below."}),o?e.jsxs("div",{className:"rounded-lg border p-4 space-y-3 bg-muted/30",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(J,{className:"text-xs",children:"Email Address *"}),e.jsx(xe,{type:"email",value:r,onChange:b=>a(b.target.value),placeholder:"broker@yourbrokerage.com",className:"text-sm"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(J,{className:"text-xs",children:"Display Name (optional)"}),e.jsx(xe,{value:i,onChange:b=>l(b.target.value),placeholder:"John at Acme Realty",className:"text-sm"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground leading-relaxed",children:"We'll ask AWS to send a verification email to this address. The owner must click the link before this sender can be used."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{size:"sm",onClick:()=>y.mutate(),disabled:!r.trim()||y.isPending,children:[y.isPending?e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(ln,{className:"h-4 w-4 mr-2"}),"Send Verification Email"]}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>{c(!1),a(""),l("")},children:"Cancel"})]})]}):e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>c(!0),children:[e.jsx(rn,{className:"h-4 w-4 mr-1"})," Add Sender Address"]}),e.jsx(Kl,{open:!!h,onOpenChange:b=>!b&&m(null),children:e.jsxs(Ol,{children:[e.jsxs(zl,{children:[e.jsx(Ul,{children:"Remove this sender?"}),e.jsxs(ql,{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($l,{children:"Cancel"}),e.jsx(Ml,{onClick:()=>h&&g.mutate(h.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})})]})}async function CBe(s){const t=await pse(),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 Ttr({status:s}){return s==="verified"?e.jsxs(Oe,{className:"bg-green-500/10 text-green-700 hover:bg-green-500/20 border-green-500/20",children:[e.jsx(Er,{className:"h-3 w-3 mr-1"})," Verified"]}):s==="pending"?e.jsxs(Oe,{variant:"secondary",children:[e.jsx(Gr,{className:"h-3 w-3 mr-1"})," Pending — check inbox"]}):s==="failed"||s==="temporary_failure"?e.jsxs(Oe,{variant:"destructive",children:[e.jsx(Xo,{className:"h-3 w-3 mr-1"})," Failed"]}):e.jsxs(Oe,{variant:"outline",children:[e.jsx(Xo,{className:"h-3 w-3 mr-1"})," Not started"]})}function Mtr({userId:s,onVerifiedSelect:t}){const n=Bt(),[r,a]=_.useState(""),[i,l]=_.useState(""),[o,c]=_.useState(!1),[d,u]=_.useState(null),[h,m]=_.useState(null),{data:p,isLoading:f}=at({queryKey:["user-verified-senders",s],queryFn:async()=>{const{data:b,error:j}=await q.from("user_verified_senders").select("*").eq("user_id",s).order("created_at",{ascending:!1});if(j)throw j;return b||[]}}),y=mt({mutationFn:async()=>CBe({action:"request_verification",scope:"user",email:r,display_name:i||void 0}),onSuccess:()=>{n.invalidateQueries({queryKey:["user-verified-senders",s]}),se.success("Verification email sent",{description:`Check ${r} and click the AWS verification link.`}),a(""),l(""),c(!1)},onError:b=>se.error(b.message)}),v=async b=>{var j,S;u(b.id);try{const C=await CBe({action:"check_status",sender_id:b.id});n.invalidateQueries({queryKey:["user-verified-senders",s]}),((j=C.sender)==null?void 0:j.status)==="verified"?se.success(`${b.email} is verified! 🎉`):se.info(`Status: ${((S=C.sender)==null?void 0:S.status)||"unknown"}`)}catch(C){se.error(C.message)}finally{u(null)}},g=mt({mutationFn:async b=>CBe({action:"delete",sender_id:b}),onSuccess:()=>{n.invalidateQueries({queryKey:["user-verified-senders",s]}),se.success("Sender removed"),m(null)},onError:b=>se.error(b.message)});return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium mb-1",children:"Your Verified Sender Addresses"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Verify your email address with Amazon so mass emails can be sent ",e.jsx("em",{children:"from"})," you. Add an address, then click the verification link Amazon sends to that inbox."]})]}),f?e.jsx("div",{className:"text-xs text-muted-foreground py-3",children:"Loading…"}):p&&p.length>0?e.jsx("div",{className:"space-y-2",children:p.map(b=>e.jsxs("div",{className:"flex items-center justify-between gap-3 p-3 rounded-lg border bg-card",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[e.jsx("div",{className:"h-9 w-9 rounded-full bg-muted flex items-center justify-center shrink-0",children:e.jsx(ln,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-sm font-medium truncate",children:b.email}),e.jsx(Ttr,{status:b.status})]}),b.display_name&&e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:['"',b.display_name,'"']})]})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[b.status==="verified"&&t&&e.jsx(B,{size:"sm",variant:"outline",onClick:()=>t(b.email),children:"Use"}),b.status!=="verified"&&e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>v(b),disabled:d===b.id,title:"Refresh status from AWS",children:d===b.id?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(uo,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>m(b),className:"text-destructive hover:text-destructive",children:e.jsx(Sn,{className:"h-4 w-4"})})]})]},b.id))}):e.jsx("div",{className:"text-xs text-muted-foreground py-2 italic",children:"No verified senders yet. Add one below."}),o?e.jsxs("div",{className:"rounded-lg border p-4 space-y-3 bg-muted/30",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(J,{className:"text-xs",children:"Email Address *"}),e.jsx(xe,{type:"email",value:r,onChange:b=>a(b.target.value),placeholder:"you@yourdomain.com",className:"text-sm"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(J,{className:"text-xs",children:"Display Name (optional)"}),e.jsx(xe,{value:i,onChange:b=>l(b.target.value),placeholder:"Jane at Acme Realty",className:"text-sm"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground leading-relaxed",children:"We'll ask Amazon to send a verification email to this address. You must click the link before this sender can be used in a campaign."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{size:"sm",onClick:()=>y.mutate(),disabled:!r.trim()||y.isPending,children:[y.isPending?e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(ln,{className:"h-4 w-4 mr-2"}),"Send Verification Email"]}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>{c(!1),a(""),l("")},children:"Cancel"})]})]}):e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>c(!0),children:[e.jsx(rn,{className:"h-4 w-4 mr-1"})," Add Sender Address"]}),e.jsx(Kl,{open:!!h,onOpenChange:b=>!b&&m(null),children:e.jsxs(Ol,{children:[e.jsxs(zl,{children:[e.jsx(Ul,{children:"Remove this sender?"}),e.jsxs(ql,{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($l,{children:"Cancel"}),e.jsx(Ml,{onClick:()=>h&&g.mutate(h.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})})]})}function Ptr(){var S,C,E,P,M;const{user:s,isBrokerageManager:t,isAdmin:n,managedBrokerages:r,selectedBrokerageId:a}=hs(),i=a||((S=r==null?void 0:r[0])==null?void 0:S.id)||null,l=(t||n)&&!!i,o=Bt(),[c,d]=_.useState(!1),[u,h]=_.useState(""),[m,p]=_.useState(""),{data:f}=at({queryKey:["mass-email-settings",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:I,error:D}=await q.from("mass_email_settings").select("*").eq("user_id",s.id).maybeSingle();if(D)throw D;return I}}),{data:y}=at({queryKey:["agent-profile-email",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:I,error:D}=await q.from("profiles").select("email, name").eq("id",s.id).single();if(D)throw D;return I}}),v=((C=f==null?void 0:f.reply_to_email)==null?void 0:C.trim())||((E=y==null?void 0:y.email)==null?void 0:E.trim())||"",g=((P=f==null?void 0:f.display_name)==null?void 0:P.trim())||((M=y==null?void 0:y.name)==null?void 0:M.trim())||"";_.useEffect(()=>{c||(h(v),p(g))},[c,v,g]);const b=mt({mutationFn:async()=>{if(!s||!u.trim())throw new Error("Please enter a reply-to email");const I={reply_to_email:u.trim(),display_name:m.trim()||null,updated_at:new Date().toISOString()};if(f){const{error:D}=await q.from("mass_email_settings").update(I).eq("user_id",s.id);if(D)throw D}else{const{error:D}=await q.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]}),se.success("Reply-to email saved!"),d(!1)},onError:I=>se.error(I.message)}),j=!!v;return e.jsxs(ve,{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(Or,{className:"h-5 w-5 text-orange-600"})}),e.jsxs("div",{children:[e.jsxs(St,{className:"text-lg flex items-center gap-2",children:["Mass Email",j?e.jsxs(Oe,{variant:"default",className:"text-xs bg-green-600",children:[e.jsx(_l,{className:"h-3 w-3 mr-1"})," Set Up"]}):e.jsx(Oe,{variant:"secondary",className:"text-xs",children:"Setup Required"})]}),e.jsx(kn,{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(Me,{className:"space-y-3",children:[j&&!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:g||"No display name"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:v})]}),e.jsxs(B,{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(J,{className:"text-xs",children:"Display Name"}),e.jsx(xe,{placeholder:"e.g. 🏡 Karen Hall",value:m,onChange:I=>p(I.target.value)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"How your name appears in the recipient's inbox"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(J,{className:"text-xs",children:"Reply-To Email *"}),e.jsx(xe,{type:"email",placeholder:"your@email.com",value:u,onChange:I=>h(I.target.value)})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{size:"sm",onClick:()=>b.mutate(),disabled:b.isPending||!u.trim(),children:[e.jsx(Ho,{className:"h-4 w-4 mr-1"})," Save"]}),c&&e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>{d(!1),h(v),p(g)},children:[e.jsx(Qn,{className:"h-4 w-4 mr-1"})," Cancel"]})]})]}),s&&e.jsxs(e.Fragment,{children:[e.jsx(wc,{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(Dm,{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(Mtr,{userId:s.id,onVerifiedSelect:I=>{h(I),d(!0)}})]})]}),l&&e.jsxs(e.Fragment,{children:[e.jsx(wc,{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(Dm,{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(vrs,{brokerageId:i})]})]})]})]})}function Ltr({authUserId:s,actingAsUserId:t}){const n=s??null,r=t??null,a=!!r&&!!n&&r!==n,i=a?r:n;return{scopeUserId:i,isDelegated:a,canViewConnections:!!i&&!a,canManageConnections:!!i&&!a}}const Itr=[{id:"all",label:"All tools",icon:sf},{id:"crm",label:"Real estate CRMs",icon:x0},{id:"social",label:"Social media",icon:bd},{id:"communication",label:"Communication",icon:ln},{id:"marketing",label:"AI & marketing",icon:un}],Dtr={gmail:"Gmail","mass-email":"Mass Email",facebook:"Facebook",instagram:"Instagram",linkedin:"LinkedIn",boldtrail:"BoldTrail",lofty:"Lofty",followupboss:"Follow Up Boss",cloze:"Cloze",boomtown:"BoomTown",chatgpt:"ChatGPT",ses:"Amazon SES"};function Rtr({connected:s,label:t}){return s?e.jsxs(Oe,{className:"border-0 bg-success/10 text-success hover:bg-success/10",children:[e.jsx("span",{className:"mr-1.5 h-1.5 w-1.5 rounded-full bg-success"}),"Connected"]}):e.jsx(Oe,{variant:"outline",className:"text-muted-foreground",children:t||"Available"})}function j2({title:s,description:t,icon:n,connected:r,statusLabel:a,selected:i,onClick:l,badge:o}){return e.jsxs("button",{type:"button",onClick:l,className:`group flex min-h-36 w-full flex-col justify-between rounded-lg border bg-card p-4 text-left shadow-sm transition-[border-color,box-shadow,transform] duration-200 hover:-translate-y-0.5 hover:border-primary/45 hover:shadow-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring ${i?"border-primary ring-1 ring-primary/20":"border-border"}`,children:[e.jsxs("div",{className:"flex w-full items-start justify-between gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-md bg-primary/10 text-primary",children:n}),e.jsxs("div",{className:"flex flex-wrap justify-end gap-1.5",children:[o&&e.jsx(Oe,{variant:"secondary",className:"text-[10px] uppercase",children:o}),e.jsx(Rtr,{connected:r,label:a})]})]}),e.jsxs("div",{className:"mt-5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("h3",{className:"font-display text-base font-semibold text-foreground",children:s}),e.jsx(xi,{className:"h-4 w-4 text-muted-foreground transition-transform duration-200 group-hover:translate-x-0.5 group-hover:text-primary"})]}),e.jsx("p",{className:"mt-1 line-clamp-2 text-sm leading-5 text-muted-foreground",children:t})]})]})}function Ftr(){const s=Fn(),{isAdmin:t,user:n}=hs(),{actingAsAgent:r,effectiveUserId:a}=Ire(),i=Bt(),[l,o]=_.useState(!1),[c,d]=_.useState(!1),[u,h]=_.useState(!1),[m,p]=_.useState("all"),[f,y]=_.useState(null),{scopeUserId:v,isDelegated:g}=Ltr({authUserId:n==null?void 0:n.id,actingAsUserId:(r==null?void 0:r.id)??a}),{data:b,isLoading:j}=at({queryKey:["gmail-integration",v],enabled:!!v&&!g,queryFn:async()=>{const{data:me,error:he}=await q.from("gmail_integrations").select("*").eq("user_id",v).maybeSingle();if(he)throw he;return me}}),{data:S}=at({queryKey:["social-accounts",v],enabled:!!v&&!g,queryFn:async()=>{const{data:me,error:he}=await q.from("social_accounts").select("*").eq("user_id",v).order("created_at",{ascending:!1});if(he)throw he;return me}}),C=async()=>{if(g){se.error("Account connections must be made by the agent from their own login.");return}o(!0);try{const{data:me,error:he}=await q.functions.invoke("gmail-oauth",{body:{action:"get_auth_url"}});if(he)throw he;if(me!=null&&me.authUrl)window.location.href=me.authUrl;else throw new Error("Failed to get authorization URL")}catch(me){console.error("Gmail OAuth error:",me),se.error("Failed to start Gmail connection"),o(!1)}},E=async me=>{if(g){se.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:he,error:pe}=await q.functions.invoke("meta-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/callback",authMode:me}});if(pe)throw pe;if(he!=null&&he.authUrl)window.location.href=he.authUrl;else throw new Error("Failed to get authorization URL")}catch(he){console.error("Meta OAuth error:",he),se.error("Failed to start connection. Make sure Meta App credentials are configured."),d(!1)}},P=async()=>{if(g){se.error("Account connections must be made by the agent from their own login.");return}h(!0);try{const{data:me,error:he}=await q.functions.invoke("linkedin-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/linkedin-callback"}});if(he)throw he;if(me!=null&&me.authUrl)window.location.href=me.authUrl;else throw new Error("Failed to get LinkedIn authorization URL")}catch(me){console.error("LinkedIn OAuth error:",me),se.error("Failed to start LinkedIn connection. Please try again."),h(!1)}},M=mt({mutationFn:async me=>{const{error:he}=await q.from("gmail_integrations").delete().eq("id",me).eq("user_id",v);if(he)throw he},onSuccess:()=>{i.invalidateQueries({queryKey:["gmail-integration",v]}),se.success("Gmail disconnected")},onError:()=>{se.error("Failed to disconnect Gmail")}}),I=mt({mutationFn:async me=>{const{error:he}=await q.from("social_accounts").delete().eq("id",me).eq("user_id",v);if(he)throw he},onSuccess:()=>{i.invalidateQueries({queryKey:["social-accounts",v]}),se.success("Account disconnected")},onError:()=>{se.error("Failed to disconnect account")}}),D=!g&&!!(b!=null&&b.is_active),O=(S==null?void 0:S.filter(me=>me.platform==="facebook"))||[],V=(S==null?void 0:S.filter(me=>me.platform==="instagram"))||[],G=(S==null?void 0:S.filter(me=>me.platform==="linkedin"))||[],{data:$}=at({queryKey:["mass-email-settings",n==null?void 0:n.id],enabled:!!(n!=null&&n.id),queryFn:async()=>{const{data:me,error:he}=await q.from("mass_email_settings").select("reply_to_email").eq("user_id",n==null?void 0:n.id).maybeSingle();if(he)throw he;return me}}),H=(me,he)=>({queryKey:[me],queryFn:async()=>{const{data:pe,error:Ce}=await q.functions.invoke(he,{body:{action:"status"}});if(Ce)throw Ce;return pe},staleTime:6e4}),{data:Y}=at(H("boldtrail-status","boldtrail-sync")),{data:Z}=at(H("lofty-status","lofty-sync")),{data:ne}=at(H("fub-status","followupboss-sync")),{data:ce}=at(H("cloze-status","cloze-sync")),{data:ie}=at(H("boomtown-status","boomtown-sync")),te=[D,!!($!=null&&$.reply_to_email),O.length>0,V.length>0,G.length>0,!!(Y!=null&&Y.connected),!!(Z!=null&&Z.connected),!!(ne!=null&&ne.connected),!!(ce!=null&&ce.connected),!!(ie!=null&&ie.connected)].filter(Boolean).length,ae=me=>{y(he=>he===me?null:me)},le=me=>{const he=me==="facebook"?O:me==="instagram"?V:G,pe=me==="facebook"?tf:me==="instagram"?Im:dg,Ce=me==="facebook"?"Facebook":me==="instagram"?"Instagram":"LinkedIn",Ae=me==="linkedin"?P:()=>E(me),Pe=me==="linkedin"?u:c;return e.jsxs(ve,{className:"border-primary/25 shadow-sm",children:[e.jsxs(bt,{children:[e.jsxs(St,{className:"font-display text-xl",children:["Manage ",Ce]}),e.jsx(kn,{children:me==="instagram"?"Connect a Business or Creator account. Personal Instagram accounts are not supported.":`Manage the ${Ce} account used for publishing LevelUp content.`})]}),e.jsxs(Me,{className:"space-y-3",children:[he.map(ze=>e.jsxs("div",{className:"flex items-center justify-between rounded-md border bg-muted/20 p-3",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsxs(ja,{className:"h-9 w-9",children:[e.jsx(pi,{src:ze.profile_picture_url||""}),e.jsx(Na,{children:e.jsx(pe,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:ze.page_name||ze.platform_username||`${Ce} account`}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connected"})]})]}),e.jsxs(Kl,{children:[e.jsx(jx,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive","aria-label":`Disconnect ${Ce}`,children:e.jsx(Sn,{className:"h-4 w-4"})})}),e.jsxs(Ol,{children:[e.jsxs(zl,{children:[e.jsxs(Ul,{children:["Disconnect ",Ce,"?"]}),e.jsx(ql,{children:"You will need to reconnect this account before publishing again."})]}),e.jsxs(Bl,{children:[e.jsx($l,{children:"Cancel"}),e.jsx(Ml,{onClick:()=>I.mutate(ze.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},ze.id)),e.jsxs(B,{variant:"outline",onClick:Ae,disabled:Pe||g,children:[Pe?e.jsx(uo,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(rn,{className:"mr-2 h-4 w-4"}),he.length?`Add another ${Ce} account`:`Connect ${Ce}`]})]})]})},be=(()=>{switch(f){case"gmail":return e.jsxs(ve,{className:"border-primary/25 shadow-sm",children:[e.jsxs(bt,{children:[e.jsx(St,{className:"font-display text-xl",children:"Manage Gmail"}),e.jsx(kn,{children:"Send personalized emails from contact pages and automatically record the activity."})]}),e.jsxs(Me,{className:"space-y-4",children:[e.jsx("div",{className:"grid gap-2 sm:grid-cols-3",children:["Send from your Gmail account","Log email touchpoints","Compose from any contact"].map(me=>e.jsxs("div",{className:"flex items-start gap-2 rounded-md bg-muted/25 p-3 text-sm",children:[e.jsx(ea,{className:"mt-0.5 h-4 w-4 shrink-0 text-success"}),me]},me))}),D?e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 rounded-md border p-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:b.gmail_email}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connected Gmail account"})]}),e.jsxs(Kl,{children:[e.jsx(jx,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"text-destructive",children:[e.jsx(Sn,{className:"mr-2 h-4 w-4"}),"Disconnect"]})}),e.jsxs(Ol,{children:[e.jsxs(zl,{children:[e.jsx(Ul,{children:"Disconnect Gmail?"}),e.jsx(ql,{children:"You will need to reconnect before sending emails from Gmail."})]}),e.jsxs(Bl,{children:[e.jsx($l,{children:"Cancel"}),e.jsx(Ml,{onClick:()=>M.mutate(b.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]}):e.jsxs(B,{onClick:C,disabled:l||j||g,children:[l?e.jsx(uo,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(ln,{className:"mr-2 h-4 w-4"}),"Connect Gmail"]})]})]});case"mass-email":return e.jsx(Ptr,{});case"facebook":return le("facebook");case"instagram":return le("instagram");case"linkedin":return le("linkedin");case"boldtrail":return e.jsx(jtr,{});case"lofty":return e.jsx(Ntr,{});case"followupboss":return e.jsx(ktr,{});case"cloze":return e.jsx(Str,{});case"boomtown":return e.jsx(Atr,{});case"chatgpt":return e.jsxs(ve,{className:"border-primary/25 shadow-sm",children:[e.jsxs(bt,{children:[e.jsx(St,{className:"font-display text-xl",children:"ChatGPT"}),e.jsx(kn,{children:"Connect ChatGPT to LevelUp so it can use LevelUp tools on your behalf."})]}),e.jsx(Me,{children:e.jsxs(B,{variant:"outline",onClick:()=>s("/connect-chatgpt"),children:["View connection instructions ",e.jsx(La,{className:"ml-2 h-4 w-4"})]})})]});case"ses":return t?e.jsx(yrs,{}):null;default:return null}})();return e.jsx(zs,{children:e.jsxs("div",{className:"integrations-hub mx-auto max-w-7xl animate-fade-in px-4 py-5 sm:px-6 lg:px-8",children:[e.jsxs("header",{className:"flex flex-col gap-4 border-b pb-6 sm:flex-row sm:items-end sm:justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-xs font-semibold uppercase text-primary",children:"Connected workspace"}),e.jsx("h1",{className:"font-display text-3xl font-semibold text-foreground sm:text-4xl",children:"Integrations"}),e.jsx("p",{className:"mt-2 max-w-2xl text-sm text-muted-foreground sm:text-base",children:"Connect the services that power your communication, marketing, and contact workflows."})]}),e.jsxs(Oe,{variant:"outline",className:"w-fit gap-2 border-primary/25 bg-card px-3 py-1.5 text-sm text-foreground",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-success"}),te," services active"]})]}),g&&e.jsx(ve,{className:"mt-5 border-warning/40 bg-warning/5",children:e.jsxs(bt,{className:"flex flex-row items-start gap-3 space-y-0",children:[e.jsx(ec,{className:"mt-0.5 h-5 w-5 text-warning"}),e.jsxs("div",{children:[e.jsx(St,{className:"text-base",children:"Connected accounts are hidden"}),e.jsxs(kn,{children:["You're working on behalf of ",r==null?void 0:r.name,". Email and social account connections are private to each agent and can only be viewed or changed from their own login."]})]})]})}),e.jsxs("div",{className:"mt-6 grid gap-6 lg:grid-cols-[220px_minmax(0,1fr)]",children:[e.jsx("nav",{"aria-label":"Integration categories",className:"min-w-0",children:e.jsx("div",{className:"flex gap-2 overflow-x-auto pb-2 lg:sticky lg:top-5 lg:flex-col lg:overflow-visible",children:Itr.map(me=>{const he=me.icon,pe=m===me.id;return e.jsxs(B,{variant:pe?"secondary":"ghost",className:`shrink-0 justify-start gap-2 ${pe?"text-primary":"text-muted-foreground"}`,onClick:()=>{p(me.id),y(null)},children:[e.jsx(he,{className:"h-4 w-4"}),me.label]},me.id)})})}),e.jsxs("main",{className:"min-w-0 space-y-8",children:[(m==="all"||m==="communication")&&e.jsxs("section",{"aria-labelledby":"email-connections",children:[e.jsxs("div",{className:"mb-3 flex items-end justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{id:"email-connections",className:"font-display text-xl font-semibold",children:"Email connections"}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Your highest-priority tools for individual and campaign email."})]}),e.jsxs(Oe,{variant:"secondary",className:"hidden sm:flex",children:[e.jsx(wh,{className:"mr-1.5 h-3.5 w-3.5"}),"Priority"]})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsx(j2,{title:"Gmail",description:"Send personal emails and automatically log each touchpoint.",icon:e.jsx(ln,{className:"h-5 w-5"}),connected:D,selected:f==="gmail",onClick:()=>ae("gmail"),badge:"Priority"}),e.jsx(j2,{title:"Mass Email",description:"Send polished campaigns from a verified sender address.",icon:e.jsx(Or,{className:"h-5 w-5"}),connected:!!($!=null&&$.reply_to_email),statusLabel:"Setup required",selected:f==="mass-email",onClick:()=>ae("mass-email"),badge:"Priority"})]})]}),(m==="all"||m==="crm")&&e.jsxs("section",{"aria-labelledby":"crm-connections",children:[e.jsxs("div",{className:"mb-3",children:[e.jsx("h2",{id:"crm-connections",className:"font-display text-xl font-semibold",children:"Real estate CRMs"}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Bring contacts into LevelUp and control how they stay synchronized."})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-3",children:[e.jsx(j2,{title:"BoldTrail",description:"Sync contacts, ownership, tags, notes, and lead details.",icon:e.jsx(x0,{className:"h-5 w-5"}),connected:Y==null?void 0:Y.connected,selected:f==="boldtrail",onClick:()=>ae("boldtrail")}),e.jsx(j2,{title:"Lofty",description:"Connect Lofty contacts and control sync direction.",icon:e.jsx(x0,{className:"h-5 w-5"}),connected:Z==null?void 0:Z.connected,selected:f==="lofty",onClick:()=>ae("lofty")}),e.jsx(j2,{title:"Follow Up Boss",description:"Keep Follow Up Boss contacts aligned with LevelUp.",icon:e.jsx(x0,{className:"h-5 w-5"}),connected:ne==null?void 0:ne.connected,selected:f==="followupboss",onClick:()=>ae("followupboss")}),e.jsx(j2,{title:"Cloze",description:"Sync contacts from your Cloze account or selected segments.",icon:e.jsx(x0,{className:"h-5 w-5"}),connected:ce==null?void 0:ce.connected,selected:f==="cloze",onClick:()=>ae("cloze")}),e.jsx(j2,{title:"BoomTown",description:"Import and synchronize your BoomTown contact database.",icon:e.jsx(x0,{className:"h-5 w-5"}),connected:ie==null?void 0:ie.connected,selected:f==="boomtown",onClick:()=>ae("boomtown")})]})]}),(m==="all"||m==="social")&&e.jsxs("section",{"aria-labelledby":"social-connections",children:[e.jsxs("div",{className:"mb-3",children:[e.jsx("h2",{id:"social-connections",className:"font-display text-xl font-semibold",children:"Social media"}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Connect the profiles and pages used by Social Studio."})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-3",children:[e.jsx(j2,{title:"Facebook",description:"Publish to your connected Facebook Pages.",icon:e.jsx(tf,{className:"h-5 w-5"}),connected:O.length>0,selected:f==="facebook",onClick:()=>ae("facebook")}),e.jsx(j2,{title:"Instagram",description:"Schedule content to a Business or Creator account.",icon:e.jsx(Im,{className:"h-5 w-5"}),connected:V.length>0,selected:f==="instagram",onClick:()=>ae("instagram")}),e.jsx(j2,{title:"LinkedIn",description:"Share content with your professional network.",icon:e.jsx(dg,{className:"h-5 w-5"}),connected:G.length>0,selected:f==="linkedin",onClick:()=>ae("linkedin")})]})]}),(m==="all"||m==="marketing")&&e.jsxs("section",{"aria-labelledby":"marketing-connections",children:[e.jsxs("div",{className:"mb-3",children:[e.jsx("h2",{id:"marketing-connections",className:"font-display text-xl font-semibold",children:"AI & marketing"}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Extend LevelUp with AI tools and managed delivery services."})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-3",children:[e.jsx(j2,{title:"ChatGPT",description:"Use your LevelUp tools directly from ChatGPT.",icon:e.jsx(V4,{className:"h-5 w-5"}),statusLabel:"View setup",selected:f==="chatgpt",onClick:()=>ae("chatgpt")}),t&&e.jsx(j2,{title:"Amazon SES",description:"Manage the platform-level mass email delivery service.",icon:e.jsx(fS,{className:"h-5 w-5"}),statusLabel:"Admin only",badge:"Admin",selected:f==="ses",onClick:()=>ae("ses")})]})]})]})]}),e.jsx(qg,{open:f!==null,onOpenChange:me=>{me||y(null)},children:e.jsxs(hg,{side:"right",className:"integrations-hub w-full overflow-y-auto border-l bg-background p-0 sm:max-w-2xl lg:max-w-3xl [&>button]:z-20",children:[e.jsxs(P0,{className:"sticky top-0 z-10 border-b bg-background px-5 py-5 pr-12 text-left sm:px-7",children:[e.jsxs(L0,{className:"font-display text-xl",children:[f?Dtr[f]:"Integration"," settings"]}),e.jsx(U9,{children:"Review the connection and update its settings here."})]}),e.jsx("div",{className:"p-4 sm:p-7",children:be})]})})]})})}const Otr="https://chromewebstore.google.com/detail/levelup-companion/lppakdeaencigddecnkcifdcemlfpkkk";function ztr(){const[s,t]=_.useState(null),[n,r]=_.useState(!1),[a,i]=_.useState(0),[l,o]=_.useState(!1),c="/levelup-extension.zip",d="https://tile-portal.lovable.app/levelup-extension.zip",u=window.location.hostname.startsWith("id-preview--"),h=async v=>{const g=new Uint8Array(await v.slice(0,4).arrayBuffer());return g[0]===80&&g[1]===75&&g[2]===3&&g[3]===4||g[0]===80&&g[1]===75&&g[2]===5&&g[3]===6||g[0]===80&&g[1]===75&&g[2]===7&&g[3]===8},m=v=>{const g=document.createElement("a");g.href=v,g.download="levelup-extension.zip",g.rel="noopener noreferrer",g.target="_blank",document.body.appendChild(g),g.click(),g.remove()},p=async()=>{o(!0);try{if(u){m(`${d}?v=${Date.now()}`);return}const v=await fetch(`${c}?v=${Date.now()}`,{cache:"no-store"});if(!v.ok)throw new Error(`Download failed (${v.status})`);const g=await v.blob();if(!await h(g)){m(`${d}?v=${Date.now()}`);return}const b=new Blob([g],{type:"application/zip"}),j=URL.createObjectURL(b),S=document.createElement("a");S.href=j,S.download="levelup-extension.zip",document.body.appendChild(S),S.click(),S.remove(),setTimeout(()=>URL.revokeObjectURL(j),1e3)}catch(v){se.error(v.message||"Download failed")}finally{o(!1)}},f=async()=>{r(!0);try{await q.auth.refreshSession();const{data:v}=await q.auth.getSession();if(!v.session){se.error("Your session has expired. Please sign in again.");return}const{data:g,error:b}=await q.functions.invoke("extension-pair-start",{headers:{Authorization:`Bearer ${v.session.access_token}`}});if(b)throw b;t(g.code),i(g.expires_in||300);const j=setInterval(()=>{i(S=>S<=1?(clearInterval(j),t(null),0):S-1)},1e3)}catch(v){console.error("generateCode error",v),se.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)}},y=()=>{s&&(navigator.clipboard.writeText(s),se.success("Copied"))};return e.jsx(zs,{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(GO,{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(ve,{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(B,{size:"lg",className:"w-full",onClick:()=>window.open(Otr,"_blank","noopener,noreferrer"),children:[e.jsx(GO,{className:"w-4 h-4 mr-2"}),"Add to Chrome",e.jsx(wr,{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(ve,{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(B,{onClick:y,variant:"outline",className:"flex-1",children:[e.jsx(Ia,{className:"w-4 h-4 mr-2"})," Copy"]}),e.jsxs(B,{onClick:f,variant:"outline",className:"flex-1",children:[e.jsx(uo,{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(ea,{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(B,{onClick:f,disabled:n,size:"lg",className:"w-full",children:n?e.jsxs(e.Fragment,{children:[e.jsx(uo,{className:"w-4 h-4 mr-2 animate-spin"}),"Generating…"]}):"Generate pairing code"})]}),e.jsxs(ve,{className:"p-6 space-y-4 bg-muted/30 border-dashed",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Nh,{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(B,{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 Btr(){const[s]=Yl(),t=Fn(),[n,r]=_.useState("loading"),[a,i]=_.useState("Connecting your Gmail account...");return _.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"),se.error("Connection failed: "+(d||c));return}if(!o){r("error"),i("No authorization code received"),se.error("No authorization code received");return}try{const{data:h,error:m}=await q.functions.invoke("gmail-oauth",{body:{action:"exchange_code",code:o,state:u}});if(m)throw m;if(h!=null&&h.success)r("success"),i(h.message||"Gmail connected successfully!"),se.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"),se.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(ve,{className:"w-full max-w-md",children:[e.jsxs(bt,{className:"text-center",children:[n==="loading"&&e.jsx(Ct,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),n==="success"&&e.jsx(_l,{className:"h-12 w-12 mx-auto text-green-500"}),n==="error"&&e.jsx(Rd,{className:"h-12 w-12 mx-auto text-destructive"}),e.jsxs(St,{className:"mt-4",children:[n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(kn,{children:a})]}),e.jsx(Me,{className:"flex justify-center",children:n!=="loading"&&e.jsx(B,{onClick:()=>t("/mission-control/integrations"),children:n==="success"?"Back to Integrations":"Try Again"})})]})})}function Utr(){const s=Fn();return _.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 qtr(){const[s]=Yl(),t=Fn(),[n,r]=_.useState("loading"),a=_.useRef(!1),[i,l]=_.useState("Processing your connection...");return _.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"),se.error("Connection failed: "+(u||d));return}if(!c){r("error"),l("No authorization code received"),se.error("No authorization code received");return}try{const{data:p,error:f}=await q.functions.invoke("meta-oauth",{body:{action:"exchange_code",code:c,state:h,callbackPath:"/mission-control/integrations/meta/callback"}});if(p&&p.success===!1)throw new Error(p.error||"Failed to connect accounts");if(f){let y=f.message||"Failed to connect accounts";try{const v=f.context;if(v&&typeof v.json=="function"){const g=await v.json();g!=null&&g.error&&(y=g.error)}}catch{}throw new Error(y)}if(p!=null&&p.success)r("success"),l(`Successfully connected ${((m=p.accounts)==null?void 0:m.length)||0} account(s)!`),se.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"),se.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(ve,{className:"w-full max-w-md",children:[e.jsxs(bt,{className:"text-center",children:[n==="loading"&&e.jsx(Ct,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),n==="success"&&e.jsx(_l,{className:"h-12 w-12 mx-auto text-green-500"}),n==="error"&&e.jsx(Rd,{className:"h-12 w-12 mx-auto text-destructive"}),e.jsxs(St,{className:"mt-4",children:[n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(kn,{children:i})]}),e.jsx(Me,{className:"flex justify-center",children:n!=="loading"&&e.jsx(B,{onClick:()=>t("/mission-control/integrations"),children:n==="success"?"View Integrations":"Try Again"})})]})})}const brs=new Date().getFullYear(),$tr=Array.from({length:5},(s,t)=>brs-t);function Vtr(){const[s,t]=_.useState(brs),n=Fn(),{data:r,isLoading:a}=JUs();return a?e.jsx(zs,{title:"Scorecard Admin",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(cn,{className:"h-8 w-64"}),e.jsx("div",{className:"grid grid-cols-4 gap-4",children:[1,2,3,4].map(i=>e.jsx(cn,{className:"h-24"},i))}),e.jsx(cn,{className:"h-96"})]})}):e.jsx(zs,{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(is,{value:String(s),onValueChange:i=>t(Number(i)),children:[e.jsx(rs,{className:"w-[120px]",children:e.jsx(ls,{})}),e.jsx(as,{children:$tr.map(i=>e.jsx(He,{value:String(i),children:i},i))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(ve,{children:e.jsxs(Me,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(In,{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(ve,{children:e.jsxs(Me,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(bl,{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(ve,{children:[e.jsxs(bt,{children:[e.jsx(St,{children:"Agents with Scorecards"}),e.jsx(kn,{children:"Click to view individual agent scorecards"})]}),e.jsx(Me,{children:!r||r.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(bl,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No agents have added transactions yet"})]}):e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"Agent"}),e.jsx(Pt,{children:"Email"}),e.jsx(Pt,{className:"text-right",children:"Actions"})]})}),e.jsx(Ka,{children:r.map(i=>e.jsxs(pn,{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(B,{variant:"ghost",size:"sm",onClick:()=>n(`/admin/scorecard/${i.id}`),children:[e.jsx(ya,{className:"h-4 w-4 mr-2"}),"View Scorecard"]})})]},i.id))})]})})]})]})})}const Htr="00000000-0000-0000-0000-000000000000",Gtr=s=>{if(!s)return"—";const[t,n,r]=s.split(/[-/T]/);return`${n}/${r}/${t}`};function Wtr(s){if(s.total_agents===0)return{label:"Empty",className:"bg-muted text-muted-foreground"};const t=s.active_90d/s.total_agents;return t>=.4?{label:"Healthy",className:"bg-emerald-100 text-emerald-800"}:t>=.15?{label:"At risk",className:"bg-amber-100 text-amber-800"}:{label:"Dormant",className:"bg-red-100 text-red-800"}}const Ktr={never_started:"Never started",signed_in_empty:"Signed in, empty",started:"Started, gone quiet",active:"Active"};function Ytr(){const s=Bt(),[t,n]=_.useState(null),[r,a]=_.useState(""),[i,l]=_.useState(null),{data:o=[]}=at({queryKey:["agent-activation-settings"],queryFn:async()=>{const{data:S,error:C}=await q.from("agent_activation_settings").select("*");if(C)throw C;return S}}),{data:c=[],isLoading:d}=at({queryKey:["brokerage-adoption-stats"],queryFn:async()=>{const{data:S,error:C}=await q.rpc("get_brokerage_adoption_stats");if(C)throw C;return S}}),{data:u}=at({queryKey:["agent-activation-metrics"],refetchInterval:6e4,queryFn:async()=>{const S=async D=>{const{count:O}=await D(q.from("agent_activation_sends").select("id",{count:"exact",head:!0}));return O??0},[C,E,P]=await Promise.all([S(D=>D.eq("status","sent")),S(D=>D.not("opened_at","is",null)),S(D=>D.not("clicked_at","is",null))]),{count:M}=await q.from("agent_activation_state").select("user_id",{count:"exact",head:!0}),{count:I}=await q.from("agent_activation_state").select("user_id",{count:"exact",head:!0}).eq("exit_reason","active");return{sent:C,opened:E,clicked:P,inSequence:M??0,activated:I??0}}}),h=o.find(S=>S.brokerage_id===null),m=!!(h!=null&&h.enabled),p=S=>o.find(C=>C.brokerage_id===S),f=mt({mutationFn:async({brokerageId:S,enabled:C})=>{const{data:E}=await q.from("agent_activation_settings").select("id").eq("brokerage_id",S??Htr).maybeSingle();let P=E;if(S===null){const{data:M}=await q.from("agent_activation_settings").select("id").is("brokerage_id",null).maybeSingle();P=M}if(P){const{error:M}=await q.from("agent_activation_settings").update({enabled:C,updated_at:new Date().toISOString()}).eq("id",P.id);if(M)throw M}else{const{error:M}=await q.from("agent_activation_settings").insert({brokerage_id:S,enabled:C});if(M)throw M}},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-activation-settings"]}),se.success("Setting saved")},onError:()=>se.error("Could not save setting")}),y=mt({mutationFn:async S=>{const{data:C,error:E}=await q.functions.invoke("agent-activation-run",{body:{action:"preview",step:S,brokerage_name:t==null?void 0:t.brokerage_name}});if(E)throw E;return C},onSuccess:l,onError:()=>se.error("Preview failed")}),v=mt({mutationFn:async S=>{const{data:C,error:E}=await q.functions.invoke("agent-activation-run",{body:{action:"test_send",step:S,brokerage_name:t==null?void 0:t.brokerage_name}});if(E)throw E;if(C!=null&&C.error)throw new Error(C.error);return C},onSuccess:S=>se.success(`Test email sent to ${S.sent_to}`),onError:S=>se.error(S.message||"Test send failed")}),g=c.filter(S=>S.brokerage_name.toLowerCase().includes(r.toLowerCase())),b=u!=null&&u.sent?Math.round(u.opened/u.sent*100):0,j=u!=null&&u.sent?Math.round(u.clicked/u.sent*100):0;return e.jsx(zs,{title:"Agent Activation",children:e.jsxs("div",{className:"container mx-auto py-6 space-y-6 max-w-7xl",children:[t?e.jsxs("div",{className:"space-y-4",children:[e.jsxs(B,{variant:"ghost",size:"sm",className:"gap-2 text-muted-foreground hover:text-foreground",onClick:()=>n(null),children:[e.jsx($c,{className:"h-4 w-4"}),"Back to all brokerages"]}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:t.brokerage_name}),e.jsx("p",{className:"text-muted-foreground",children:"Agent Activation · manage this brokerage's agents and sequence."})]})]}):e.jsx(Wh,{title:"Agent Activation",description:"Find dormant agents and walk them into the product with a branded email sequence. Nothing sends until you turn it on."}),e.jsx("div",{className:"grid gap-4 grid-cols-2 lg:grid-cols-5",children:[{label:"Emails sent",value:(u==null?void 0:u.sent)??0,hint:"across all brokerages"},{label:"Opened",value:(u==null?void 0:u.opened)??0,hint:`${b}% open rate`},{label:"Clicked",value:(u==null?void 0:u.clicked)??0,hint:`${j}% click rate`},{label:"Agents in sequence",value:(u==null?void 0:u.inSequence)??0,hint:"currently receiving"},{label:"Activated",value:(u==null?void 0:u.activated)??0,hint:"signed in and working"}].map(S=>e.jsx(ve,{children:e.jsxs(Me,{className:"pt-5",children:[e.jsx("div",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:S.label}),e.jsx("div",{className:"text-2xl font-bold",children:S.value.toLocaleString()}),e.jsx("div",{className:"text-xs text-muted-foreground",children:S.hint})]})},S.label))}),e.jsx(ve,{className:m?"border-emerald-300":"border-amber-300",children:e.jsx(bt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(St,{className:"flex items-center gap-2 text-lg",children:[e.jsx(hm,{className:"h-5 w-5"}),"Master switch"]}),e.jsx(kn,{children:m?"Activation emails are LIVE for brokerages you enable below.":"OFF worldwide. No activation emails can be sent to anyone."})]}),e.jsx(fn,{checked:m,onCheckedChange:S=>f.mutate({brokerageId:null,enabled:S})})]})})}),e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsxs(St,{className:"text-lg flex items-center gap-2",children:[e.jsx(ln,{className:"h-5 w-5"})," The sequence"]}),e.jsx(kn,{children:"Five emails, all sent from LevelUp. Preview any step or send a test to yourself."})]}),e.jsx(Me,{className:"flex flex-wrap gap-2",children:[1,2,3,4,5].map(S=>e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>y.mutate(S),disabled:y.isPending,children:[e.jsx(ya,{className:"h-3.5 w-3.5 mr-1"})," Step ",S]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>v.mutate(S),disabled:v.isPending,title:"Send test to my email",children:e.jsx(Or,{className:"h-3.5 w-3.5"})})]},S))})]}),t?e.jsx(Ztr,{brokerage:t,settings:p(t.brokerage_id),masterOn:m,onBack:()=>n(null),onToggle:S=>f.mutate({brokerageId:t.brokerage_id,enabled:S})}):e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsxs("div",{className:"flex items-center justify-between gap-4 flex-wrap",children:[e.jsxs("div",{children:[e.jsx(St,{className:"text-lg",children:"Brokerage adoption"}),e.jsx(kn,{children:"Select a brokerage to manage agents and enable the sequence."})]}),e.jsx(xe,{placeholder:"Search brokerages…",value:r,onChange:S=>a(S.target.value),className:"max-w-xs"})]})}),e.jsx(Me,{children:d?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"Brokerage"}),e.jsx(Pt,{children:"Health"}),e.jsx(Pt,{className:"text-right",children:"Agents"}),e.jsx(Pt,{className:"text-right",children:"Never in"}),e.jsx(Pt,{className:"text-right",children:"Active 90d"}),e.jsx(Pt,{className:"text-right",children:"With data"}),e.jsx(Pt,{className:"text-right",children:"Activation"})]})}),e.jsx(Ka,{children:g.map(S=>{var P;const C=Wtr(S),E=!!((P=p(S.brokerage_id))!=null&&P.enabled);return e.jsxs(pn,{className:"cursor-pointer",onClick:()=>n(S),children:[e.jsx(gt,{className:"font-medium",children:S.brokerage_name}),e.jsx(gt,{children:e.jsx(Oe,{variant:"secondary",className:C.className,children:C.label})}),e.jsx(gt,{className:"text-right",children:S.total_agents}),e.jsx(gt,{className:"text-right",children:S.never_logged_in}),e.jsx(gt,{className:"text-right",children:S.active_90d}),e.jsx(gt,{className:"text-right",children:S.with_contacts+S.with_deals>0?`${S.with_contacts}`:0}),e.jsx(gt,{className:"text-right",children:e.jsx(Oe,{variant:E?"default":"outline",children:E?"On":"Off"})})]},S.brokerage_id)})})]})})]}),e.jsx(Ls,{open:!!i,onOpenChange:()=>l(null),children:e.jsxs(Ps,{className:"max-w-3xl max-h-[85vh] overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:i==null?void 0:i.subject}),e.jsx(_r,{children:"Exactly as the agent will receive it."})]}),i&&e.jsx("iframe",{title:"Email preview",sandbox:"",srcDoc:i.html,className:"w-full h-[560px] rounded-md border"})]})})]})})}function Ztr({brokerage:s,settings:t,masterOn:n,onBack:r,onToggle:a}){const i=Bt(),[l,o]=_.useState(""),{data:c=[],isLoading:d}=at({queryKey:["brokerage-agent-activation",s.brokerage_id],queryFn:async()=>{const{data:y,error:v}=await q.rpc("get_brokerage_agent_activation",{_brokerage_id:s.brokerage_id});if(v)throw v;return y}}),u=mt({mutationFn:async({userId:y,skip:v})=>{if(v){const{error:g}=await q.from("agent_activation_state").upsert({user_id:y,brokerage_id:s.brokerage_id,exited_at:new Date().toISOString(),exit_reason:"manual_skip",updated_at:new Date().toISOString()},{onConflict:"user_id"});if(g)throw g}else{const{error:g}=await q.from("agent_activation_state").update({exited_at:null,exit_reason:null,updated_at:new Date().toISOString()}).eq("user_id",y);if(g)throw g}},onSuccess:()=>{i.invalidateQueries({queryKey:["brokerage-agent-activation",s.brokerage_id]}),se.success("Agent updated")},onError:()=>se.error("Update failed")}),h=mt({mutationFn:async y=>{const{data:v,error:g}=await q.functions.invoke("agent-activation-run",{body:{action:"send_now",user_id:y,brokerage_id:s.brokerage_id}});if(g)throw g;if(v!=null&&v.error)throw new Error(v.error);return v},onSuccess:()=>{i.invalidateQueries({queryKey:["brokerage-agent-activation",s.brokerage_id]}),se.success("Email sent")},onError:y=>se.error(y.message||"Send failed")}),m=!!(t!=null&&t.enabled),p=m&&n,f=c.filter(y=>(y.name||"").toLowerCase().includes(l.toLowerCase())||(y.email||"").toLowerCase().includes(l.toLowerCase()));return e.jsxs(ve,{children:[e.jsxs(bt,{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(B,{variant:"ghost",size:"sm",onClick:r,children:e.jsx($c,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx(St,{className:"text-lg",children:s.brokerage_name}),e.jsxs(kn,{children:[s.total_agents," agents · ",s.never_logged_in," never logged in ·"," ",s.active_90d," active in 90 days"]})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:p?"Sequence LIVE for this brokerage":n?"Off for this brokerage":"Master switch is off"}),e.jsx(fn,{checked:m,onCheckedChange:a})]})]}),e.jsx("div",{className:"pt-2",children:e.jsx(xe,{placeholder:"Search agents…",value:l,onChange:y=>o(y.target.value),className:"max-w-xs"})})]}),e.jsx(Me,{children:d?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"Agent"}),e.jsx(Pt,{children:"Stage"}),e.jsx(Pt,{className:"text-right",children:"Logins"}),e.jsx(Pt,{children:"Last login"}),e.jsx(Pt,{className:"text-right",children:"Contacts"}),e.jsx(Pt,{className:"text-right",children:"Deals"}),e.jsx(Pt,{className:"text-right",children:"Step"}),e.jsx(Pt,{className:"text-right",children:"Emails"}),e.jsx(Pt,{className:"text-right",children:"Actions"})]})}),e.jsx(Ka,{children:f.map(y=>{const v=y.exit_reason==="manual_skip";return e.jsxs(pn,{children:[e.jsxs(gt,{children:[e.jsx("div",{className:"font-medium",children:y.name||"—"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:y.email})]}),e.jsx(gt,{children:e.jsx(Oe,{variant:y.stage==="active"?"default":"secondary",children:v?"Skipped":Ktr[y.stage]})}),e.jsx(gt,{className:"text-right",children:y.login_count}),e.jsx(gt,{children:Gtr(y.last_login)}),e.jsx(gt,{className:"text-right",children:y.contact_count}),e.jsx(gt,{className:"text-right",children:y.deal_count}),e.jsxs(gt,{className:"text-right",children:[y.step,"/5"]}),e.jsx(gt,{className:"text-right",children:e.jsxs("span",{className:"inline-flex items-center gap-1",children:[y.last_opened_at?e.jsx(JO,{className:"h-3.5 w-3.5 text-emerald-600"}):e.jsx(ln,{className:"h-3.5 w-3.5 text-muted-foreground"}),y.emails_sent]})}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[e.jsx(B,{variant:"ghost",size:"sm",disabled:!p||!!y.exited_at||h.isPending,onClick:()=>h.mutate(y.user_id),title:"Send the next step now",children:e.jsx(Or,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>u.mutate({userId:y.user_id,skip:!v}),title:v?"Include in sequence":"Skip this agent",children:e.jsx(m$,{className:`h-3.5 w-3.5 ${v?"text-red-500":""}`})})]})})]},y.user_id)})})]})})]})}const _rs=new Date().getFullYear(),Xtr=Array.from({length:10},(s,t)=>_rs-t);function h4t(){var y;const{userId:s}=Li(),t=Fn(),r=ru().pathname.startsWith("/mission-control"),[a,i]=_.useState(_rs),{data:l,isLoading:o}=at({queryKey:["agent-profile",s],queryFn:async()=>{const{data:v,error:g}=await q.from("profiles").select("id, name, email").eq("id",s).single();if(g)throw g;return v},enabled:!!s}),{data:c,isLoading:d}=bet(a,s),{yearStats:u,lifetimeStats:h,isLoading:m,showCommission:p}=Uzt(a,s),{data:f}=Bzt(a,s);return o?e.jsx(zs,{title:"Agent Scorecard",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(cn,{className:"h-8 w-64"}),e.jsx("div",{className:"grid grid-cols-4 gap-4",children:[1,2,3,4].map(v=>e.jsx(cn,{className:"h-24"},v))})]})}):e.jsx(zs,{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(B,{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(is,{value:String(a),onValueChange:v=>i(Number(v)),children:[e.jsx(rs,{className:"w-[120px]",children:e.jsx(ls,{})}),e.jsx(as,{children:Xtr.map(v=>e.jsx(He,{value:String(v),children:v},v))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-5 gap-4",children:[e.jsx(ve,{children:e.jsxs(Me,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Jr,{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(ve,{children:e.jsxs(Me,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(In,{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(ve,{children:e.jsxs(Me,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(yd,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Volume"})]}),e.jsx("p",{className:"text-2xl font-bold",children:am(u.totalVolume,!0)})]})}),e.jsx(ve,{children:e.jsxs(Me,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Nl,{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:am(u.averagePrice,!0)})]})}),e.jsx(ve,{children:e.jsxs(Me,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Hh,{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:((y=u.topLeadSource)==null?void 0:y.name)||"-"})]})})]}),f&&e.jsx(Fts,{goals:f,stats:u,year:a,showCommission:p}),e.jsxs(Yr,{defaultValue:"transactions",className:"space-y-4",children:[e.jsxs(Zr,{children:[e.jsx(Ht,{value:"transactions",children:"Transactions"}),e.jsx(Ht,{value:"charts",children:"Charts"}),e.jsxs(Ht,{value:"map",children:[e.jsx(Xa,{className:"h-4 w-4 mr-1"}),"Map"]})]}),e.jsx(Gt,{value:"transactions",children:e.jsx(tat,{transactions:c||[],showCommission:p,isLoading:d})}),e.jsx(Gt,{value:"charts",children:e.jsx(sat,{stats:u,year:a})}),e.jsx(Gt,{value:"map",children:e.jsx(nat,{transactions:c||[],isLoading:d})})]})]})})}function Qtr(){const s=Bt(),[t,n]=_.useState(""),[r,a]=_.useState("all"),[i,l]=_.useState(null);Ore();const{data:o,refetch:c}=at({queryKey:["listing-exchange-flag"],queryFn:async()=>{const{data:I}=await q.from("feature_flags").select("enabled").eq("key","listing_exchange_enabled").single();return(I==null?void 0:I.enabled)??!1}}),{data:d,isLoading:u}=at({queryKey:["admin-listings"],queryFn:async()=>{const{data:I,error:D}=await q.from("listings").select(` *, agent:profiles!listings_agent_id_fkey(id, name, email), photos:listing_photos(id, photo_url, is_primary) `).order("created_at",{ascending:!1});if(D)throw D;return I}}),{data:h}=at({queryKey:["admin-listing-stats"],queryFn:async()=>{const{data:I}=await q.from("listings").select("id, is_approved, status"),{data:D}=await q.from("listing_shares").select("id"),{data:O}=await q.from("listing_views").select("id"),{count:V}=await q.from("listing_leads").select("id",{count:"exact",head:!0}),G=new Date(Date.now()-7*24*60*60*1e3).toISOString(),{count:$}=await q.from("listing_leads").select("id",{count:"exact",head:!0}).gte("created_at",G);return{total:(I==null?void 0:I.length)||0,pending:(I==null?void 0:I.filter(H=>!H.is_approved).length)||0,active:(I==null?void 0:I.filter(H=>H.status==="active").length)||0,totalShares:(D==null?void 0:D.length)||0,totalViews:(O==null?void 0:O.length)||0,totalLeads:V||0,leadsLast7:$||0}}}),{data:m}=at({queryKey:["admin-listing-lead-counts"],queryFn:async()=>{const I={};let D=0;const O=1e3;for(;;){const{data:V,error:G}=await q.from("listing_leads").select("listing_id").range(D,D+O-1);if(G)throw G;if(!V||V.length===0)break;for(const $ of V)$.listing_id&&(I[$.listing_id]=(I[$.listing_id]||0)+1);if(V.length{const{data:I,error:D}=await q.from("listing_leads").select("*").eq("listing_id",i.listingId).order("created_at",{ascending:!1});if(D)throw D;return I}}),y=async(I,D,O="submit_url")=>{try{const{data:{session:V}}=await q.auth.getSession();if(!V)return;const{data:G,error:$}=await q.functions.invoke("google-indexing",{body:{action:O,listing_id:I,listing_slug:D}});if($)throw $;if((G==null?void 0:G.configured)===!1)return;G!=null&&G.success&&se.success("Submitted to Google for indexing")}catch(V){console.error("Google indexing submission failed:",V)}},v=mt({mutationFn:async()=>{const{data:{session:I}}=await q.auth.getSession();if(!I)throw new Error("Not authenticated");const{data:D,error:O}=await q.functions.invoke("google-indexing",{body:{action:"submit_all"}});if(O)throw O;return D},onSuccess:I=>{if((I==null?void 0:I.configured)===!1){se.error("Google Indexing API not configured. Add the GOOGLE_INDEXING_SERVICE_ACCOUNT secret.");return}se.success(`Submitted ${(I==null?void 0:I.succeeded)||0} URLs to Google (${(I==null?void 0:I.failed)||0} failed)`)},onError:I=>{se.error("Failed to submit to Google"),console.error(I)}}),g=mt({mutationFn:async({id:I,approved:D,slug:O})=>{const{error:V}=await q.from("listings").update({is_approved:D}).eq("id",I);if(V)throw V;return{id:I,approved:D,slug:O}},onSuccess:I=>{s.invalidateQueries({queryKey:["admin-listings"]}),s.invalidateQueries({queryKey:["admin-listing-stats"]}),se.success(I.approved?"Listing approved":"Listing unapproved"),I.approved?y(I.id,I.slug||null,"submit_url"):y(I.id,I.slug||null,"remove_url")}}),b=mt({mutationFn:async({id:I,featured:D})=>{const{error:O}=await q.from("listings").update({is_featured:D}).eq("id",I);if(O)throw O},onSuccess:(I,{featured:D})=>{s.invalidateQueries({queryKey:["admin-listings"]}),se.success(D?"Listing featured":"Listing unfeatured")}}),j=mt({mutationFn:async I=>{const{error:D}=await q.from("listings").delete().eq("id",I);if(D)throw D},onSuccess:()=>{s.invalidateQueries({queryKey:["admin-listings"]}),s.invalidateQueries({queryKey:["admin-listing-stats"]}),se.success("Listing deleted")}}),S=mt({mutationFn:async I=>{const{error:D}=await q.from("feature_flags").update({enabled:I}).eq("key","listing_exchange_enabled");if(D)throw D},onSuccess:()=>{c(),se.success("Feature flag updated")}}),C=o??!1,E=d==null?void 0:d.filter(I=>{var V,G,$,H;const D=((V=I.city)==null?void 0:V.toLowerCase().includes(t.toLowerCase()))||(($=(G=I.agent)==null?void 0:G.name)==null?void 0:$.toLowerCase().includes(t.toLowerCase()))||((H=I.property_address)==null?void 0:H.toLowerCase().includes(t.toLowerCase())),O=r==="all"||r==="pending"&&!I.is_approved||r==="approved"&&I.is_approved;return D&&O}),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(zs,{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(B,{variant:"outline",size:"sm",onClick:()=>v.mutate(),disabled:v.isPending,className:"gap-2",children:[v.isPending?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(sl,{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(fn,{checked:C,onCheckedChange:I=>S.mutate(I)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-6 gap-4",children:[e.jsx(ve,{children:e.jsxs(Me,{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(ve,{children:e.jsxs(Me,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Nl,{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(ve,{children:e.jsxs(Me,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(In,{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(ve,{children:e.jsxs(Me,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ya,{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(ve,{children:e.jsxs(Me,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(bd,{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(ve,{children:e.jsxs(Me,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pl,{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(ve,{children:e.jsx(Me,{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(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search by city, address, or agent...",value:t,onChange:I=>n(I.target.value),className:"pl-9"})]}),e.jsx(Yr,{value:r,onValueChange:I=>a(I),children:e.jsxs(Zr,{children:[e.jsx(Ht,{value:"all",children:"All"}),e.jsx(Ht,{value:"pending",children:"Pending"}),e.jsx(Ht,{value:"approved",children:"Approved"})]})})]})})}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsxs(St,{children:["Listings (",(E==null?void 0:E.length)||0,")"]})}),e.jsx(Me,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"Property"}),e.jsx(Pt,{children:"Agent"}),e.jsx(Pt,{children:"Price"}),e.jsx(Pt,{children:"Status"}),e.jsx(Pt,{className:"text-center",children:"Approved"}),e.jsx(Pt,{className:"text-center",children:"Featured"}),e.jsx(Pt,{children:"Views"}),e.jsx(Pt,{children:"Shares"}),e.jsx(Pt,{children:"Leads"}),e.jsx(Pt,{children:"Date"}),e.jsx(Pt,{})]})}),e.jsx(Ka,{children:u?e.jsx(pn,{children:e.jsx(gt,{colSpan:11,className:"text-center py-8 text-muted-foreground",children:"Loading..."})}):(E==null?void 0:E.length)===0?e.jsx(pn,{children:e.jsx(gt,{colSpan:11,className:"text-center py-8 text-muted-foreground",children:"No listings found"})}):E==null?void 0:E.map(I=>{var D,O,V,G,$;return e.jsxs(pn,{children:[e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[(O=(D=I.photos)==null?void 0:D[0])!=null&&O.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:(V=I.property_type)==null?void 0:V.replace("_"," ")})]})]})}),e.jsx(gt,{children:e.jsx("p",{className:"text-sm",children:((G=I.agent)==null?void 0:G.name)||"Unknown"})}),e.jsx(gt,{className:"font-medium",children:P(I.price)}),e.jsx(gt,{children:e.jsx(Oe,{variant:"outline",className:M(I.status),children:($=I.status)==null?void 0:$.replace("_"," ")})}),e.jsx(gt,{className:"text-center",children:e.jsx(fn,{checked:I.is_approved??!1,onCheckedChange:H=>g.mutate({id:I.id,approved:H,slug:I.slug})})}),e.jsx(gt,{className:"text-center",children:e.jsx(fn,{checked:I.is_featured??!1,onCheckedChange:H=>b.mutate({id:I.id,featured:H})})}),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(B,{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(tu,{children:[e.jsx(su,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",children:e.jsx(ob,{className:"h-4 w-4"})})}),e.jsxs(Od,{align:"end",children:[e.jsxs(ca,{onClick:()=>window.open(`/mission-control/listings/${I.id}`,"_blank"),children:[e.jsx(ya,{className:"h-4 w-4 mr-2"}),"View Listing"]}),e.jsxs(ca,{onClick:()=>b.mutate({id:I.id,featured:!I.is_featured}),children:[e.jsx(Da,{className:"h-4 w-4 mr-2"}),I.is_featured?"Unfeature":"Feature"]}),e.jsxs(ca,{className:"text-destructive",onClick:async()=>{await Xi("Are you sure you want to delete this listing?")&&j.mutate(I.id)},children:[e.jsx(Qn,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})})]},I.id)})})]})})})]})]}),e.jsx(Ls,{open:!!i,onOpenChange:I=>!I&&l(null),children:e.jsxs(Ps,{className:"max-w-3xl max-h-[80vh] overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Leads from listing"}),e.jsx(_r,{children:i==null?void 0:i.label})]}),f?e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx(Ct,{className:"h-5 w-5 animate-spin inline mr-2"}),"Loading leads..."]}):!p||p.length===0?e.jsx("div",{className:"py-8 text-center text-muted-foreground",children:"No leads yet."}):e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"Name"}),e.jsx(Pt,{children:"Email"}),e.jsx(Pt,{children:"Phone"}),e.jsx(Pt,{children:"Type"}),e.jsx(Pt,{children:"Captured"})]})}),e.jsx(Ka,{children:p.map(I=>{var D;return e.jsxs(pn,{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(Oe,{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 Jtr(s){return s?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s):"—"}function esr(){const[s,t]=_.useState(""),[n,r]=_.useState("all"),[a,i]=_.useState("all"),{data:l,isLoading:o}=at({queryKey:["admin-all-listing-leads"],queryFn:async()=>{const h=[];let m=0;const p=1e3;for(;;){const{data:f,error:y}=await q.from("listing_leads").select(` id, listing_id, agent_id, referred_by_agent_id, first_name, last_name, email, phone, lead_type, showing_mode, preferred_date, preferred_time, message, created_at, listing:listings!listing_leads_listing_id_fkey(id, slug, property_address, city, state, price), agent:profiles!listing_leads_agent_id_fkey(id, name, email), referrer:profiles!listing_leads_referred_by_agent_id_fkey(id, name, email) `).order("created_at",{ascending:!1}).range(m,m+p-1);if(y)throw y;if(!f||f.length===0||(h.push(...f),f.length{if(!l)return[];const h=n==="all"?0:Date.now()-parseInt(n)*24*60*60*1e3,m=s.trim().toLowerCase();return l.filter(p=>{var y,v,g,b,j,S;return h&&new Date(p.created_at).getTime(){const h=c.length,m=c.filter(y=>y.lead_type==="showing_request").length,p=new Set(c.map(y=>y.agent_id)).size,f=new Set(c.map(y=>y.listing_id)).size;return{total:h,showings:m,uniqueAgents:p,uniqueListings:f}},[c]),u=()=>{const m=[["Date","Name","Email","Phone","Type","Showing Date","Property","City","Price","Assigned Agent","Agent Email","Referred By","Message"],...c.map(v=>{var g,b,j,S,C,E;return[Hs(new Date(v.created_at),"yyyy-MM-dd HH:mm"),`${v.first_name||""} ${v.last_name||""}`.trim(),v.email,v.phone||"",v.lead_type,v.preferred_date?`${v.preferred_date} ${v.preferred_time||""}`:"",((g=v.listing)==null?void 0:g.property_address)||"",((b=v.listing)==null?void 0:b.city)||"",(j=v.listing)!=null&&j.price?String(v.listing.price):"",((S=v.agent)==null?void 0:S.name)||"",((C=v.agent)==null?void 0:C.email)||"",((E=v.referrer)==null?void 0:E.name)||"",(v.message||"").replace(/[\r\n]+/g," ")]})].map(v=>v.map(g=>`"${String(g).replace(/"/g,'""')}"`).join(",")).join(` `),p=new Blob([m],{type:"text/csv"}),f=URL.createObjectURL(p),y=document.createElement("a");y.href=f,y.download=`listing-leads-${Hs(new Date,"yyyy-MM-dd")}.csv`,y.click(),URL.revokeObjectURL(f)};return e.jsx(zs,{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(B,{variant:"outline",onClick:u,disabled:!c.length,className:"gap-2",children:[e.jsx(li,{className:"h-4 w-4"}),"Export CSV"]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(ve,{children:e.jsxs(Me,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pl,{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(ve,{children:e.jsxs(Me,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ga,{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(ve,{children:e.jsxs(Me,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Jr,{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(ve,{children:e.jsxs(Me,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pl,{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(ve,{children:e.jsx(Me,{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(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search name, email, property, agent...",value:s,onChange:h=>t(h.target.value),className:"pl-9"})]}),e.jsxs(is,{value:a,onValueChange:h=>i(h),children:[e.jsx(rs,{className:"w-full sm:w-48",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Types"}),e.jsx(He,{value:"info_request",children:"Info Request"}),e.jsx(He,{value:"showing_request",children:"Showing Request"})]})]}),e.jsxs(is,{value:n,onValueChange:h=>r(h),children:[e.jsx(rs,{className:"w-full sm:w-40",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Time"}),e.jsx(He,{value:"7",children:"Last 7 days"}),e.jsx(He,{value:"30",children:"Last 30 days"}),e.jsx(He,{value:"90",children:"Last 90 days"})]})]})]})})}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsxs(St,{children:["Leads (",c.length,")"]})}),e.jsx(Me,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"Date"}),e.jsx(Pt,{children:"Lead"}),e.jsx(Pt,{children:"Contact"}),e.jsx(Pt,{children:"Property"}),e.jsx(Pt,{children:"Type"}),e.jsx(Pt,{children:"Assigned To"}),e.jsx(Pt,{children:"Referred By"}),e.jsx(Pt,{children:"Message"})]})}),e.jsx(Ka,{children:o?e.jsx(pn,{children:e.jsx(gt,{colSpan:8,className:"text-center py-8 text-muted-foreground",children:"Loading..."})}):c.length===0?e.jsx(pn,{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(pn,{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(ln,{className:"h-3 w-3"}),h.email]}),h.phone&&e.jsxs("a",{href:`tel:${h.phone}`,className:"flex items-center gap-1 text-muted-foreground hover:underline",children:[e.jsx(_a,{className:"h-3 w-3"}),h.phone]})]})}),e.jsx(gt,{children:h.listing?e.jsxs(ir,{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(wr,{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(", ")," · ",Jtr(h.listing.price)]})]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsxs(gt,{children:[e.jsx(Oe,{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(Hi,{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 tU={new_listing_alerts:{label:"New Listing Alerts",icon:Rg,color:"bg-amber-100 text-amber-800"},exit_intent:{label:"Exit Intent",icon:QO,color:"bg-rose-100 text-rose-800"},saved_listing:{label:"Saved Home",icon:Do,color:"bg-pink-100 text-pink-800"},saved_search:{label:"Saved Search",icon:Lr,color:"bg-blue-100 text-blue-800"},buyer_guide:{label:"Buyer's Guide",icon:Sx,color:"bg-emerald-100 text-emerald-800"}},m4t=[{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 p4t(s){return new Date(s).toLocaleString("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"})}function tsr(){const[s,t]=_.useState([]),[n,r]=_.useState(!0),[a,i]=_.useState("30d"),[l,o]=_.useState("all"),[c,d]=_.useState("");_.useEffect(()=>{let p=!1;return(async()=>{r(!0);let f=q.from("public_site_leads").select("*").order("created_at",{ascending:!1}).limit(2e3);const y=m4t.find(b=>b.key===a);if(y&&y.days>0){const b=new Date(Date.now()-y.days*864e5).toISOString();f=f.gte("created_at",b)}const{data:v,error:g}=await f;p||(g?(console.error(g),t([])):t(v||[]),r(!1))})(),()=>{p=!0}},[a]);const u=_.useMemo(()=>s.filter(p=>{if(l!=="all"&&p.lead_type!==l)return!1;if(c){const f=c.toLowerCase();if(![p.email,p.first_name,p.last_name,p.phone,p.source_page,p.referrer].filter(Boolean).join(" ").toLowerCase().includes(f))return!1}return!0}),[s,l,c]),h=_.useMemo(()=>{const p=u.length,f=new Set(u.map(v=>v.email.toLowerCase())).size,y={};return u.forEach(v=>{y[v.lead_type]=(y[v.lead_type]||0)+1}),{total:p,uniqueEmails:f,byType:y}},[u]),m=()=>{const f=[["Date (ET)","Type","Email","First","Last","Phone","Listing ID","Source Page","Referrer","Criteria"].join(",")];u.forEach(b=>{var S;const j=[p4t(b.created_at),((S=tU[b.lead_type])==null?void 0:S.label)||b.lead_type,b.email,b.first_name||"",b.last_name||"",b.phone||"",b.listing_id||"",b.source_page||"",b.referrer||"",b.criteria?JSON.stringify(b.criteria):""].map(C=>`"${String(C).replace(/"/g,'""')}"`);f.push(j.join(","))});const y=new Blob([f.join(` `)],{type:"text/csv"}),v=URL.createObjectURL(y),g=document.createElement("a");g.href=v,g.download=`public-site-leads-${new Date().toISOString().slice(0,10)}.csv`,g.click(),URL.revokeObjectURL(v)};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(ir,{to:"/admin",children:e.jsxs(B,{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(B,{onClick:m,variant:"outline",size:"sm",children:[e.jsx(li,{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(ve,{children:e.jsxs(Me,{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(tU).map(p=>{const f=tU[p],y=f.icon;return e.jsx(ve,{children:e.jsxs(Me,{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(y,{className:"h-3.5 w-3.5"}),f.label]}),e.jsx("div",{className:"text-2xl font-bold mt-1",children:h.byType[p]||0})]})},p)})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(is,{value:a,onValueChange:p=>i(p),children:[e.jsx(rs,{className:"w-[160px] bg-white",children:e.jsx(ls,{})}),e.jsx(as,{children:m4t.map(p=>e.jsx(He,{value:p.key,children:p.label},p.key))})]}),e.jsxs(is,{value:l,onValueChange:o,children:[e.jsx(rs,{className:"w-[200px] bg-white",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All lead types"}),Object.keys(tU).map(p=>e.jsx(He,{value:p,children:tU[p].label},p))]})]}),e.jsxs("div",{className:"relative flex-1 min-w-[200px] max-w-md",children:[e.jsx(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(xe,{placeholder:"Search name, email, phone…",value:c,onChange:p=>d(p.target.value),className:"pl-9 bg-white"})]}),e.jsxs("div",{className:"ml-auto text-sm text-slate-500",children:[u.length," ",u.length===1?"lead":"leads"]})]}),e.jsx(ve,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b bg-slate-50 text-left text-xs uppercase tracking-wide text-slate-500",children:[e.jsx("th",{className:"px-4 py-3",children:"Date"}),e.jsx("th",{className:"px-4 py-3",children:"Type"}),e.jsx("th",{className:"px-4 py-3",children:"Contact"}),e.jsx("th",{className:"px-4 py-3",children:"Phone"}),e.jsx("th",{className:"px-4 py-3",children:"Details"}),e.jsx("th",{className:"px-4 py-3",children:"Source"})]})}),e.jsx("tbody",{children:n?e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"px-4 py-12 text-center text-slate-500",children:"Loading…"})}):u.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"px-4 py-12 text-center text-slate-500",children:"No leads yet in this range."})}):u.map(p=>{const f=tU[p.lead_type],y=f==null?void 0:f.icon,v=[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:p4t(p.created_at)}),e.jsx("td",{className:"px-4 py-3 whitespace-nowrap",children:e.jsxs(Oe,{className:`${(f==null?void 0:f.color)||""} font-normal`,variant:"secondary",children:[y?e.jsx(y,{className:"h-3 w-3 mr-1"}):null,(f==null?void 0:f.label)||p.lead_type]})}),e.jsxs("td",{className:"px-4 py-3",children:[e.jsx("div",{className:"font-medium text-slate-900",children:v}),e.jsxs("a",{href:`mailto:${p.email}`,className:"text-xs text-blue-600 hover:underline inline-flex items-center gap-1",children:[e.jsx(ln,{className:"h-3 w-3"}),p.email]})]}),e.jsx("td",{className:"px-4 py-3 whitespace-nowrap",children:p.phone?e.jsxs("a",{href:`tel:${p.phone}`,className:"text-xs text-blue-600 hover:underline inline-flex items-center gap-1",children:[e.jsx(_a,{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(([g,b])=>`${g}: ${b}`).join(" · ")})]}),e.jsxs("td",{className:"px-4 py-3 text-xs text-slate-500 max-w-xs truncate",children:[p.source_page&&e.jsxs("div",{className:"inline-flex items-center gap-1",children:[e.jsx(wr,{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 ssr=()=>{var h,m;const[s,t]=_.useState(""),[n,r]=_.useState(null),{data:a,isLoading:i}=at({queryKey:["membership-reviews"],queryFn:async()=>{const{data:p,error:f}=await q.from("membership_reviews").select("*").order("created_at",{ascending:!1});if(f)throw f;const y=(p==null?void 0:p.map(b=>b.user_id))||[],{data:v}=await q.from("profiles").select("id, name, email").in("id",y);return p==null?void 0:p.map(b=>({...b,profiles:(v==null?void 0:v.find(j=>j.id===b.user_id))||null}))}}),l=a==null?void 0:a.filter(p=>{var y,v,g,b,j;const f=s.toLowerCase();return((v=(y=p.profiles)==null?void 0:y.name)==null?void 0:v.toLowerCase().includes(f))||((b=(g=p.profiles)==null?void 0:g.email)==null?void 0:b.toLowerCase().includes(f))||((j=p.review_text)==null?void 0:j.toLowerCase().includes(f))}),o=a!=null&&a.length?(a.reduce((p,f)=>p+f.rating,0)/a.length).toFixed(1):"0.0",c=a==null?void 0:a.reduce((p,f)=>(p[f.rating]=(p[f.rating]||0)+1,p),{}),d=(a==null?void 0:a.filter(p=>p.posted_to_google).length)||0,u=p=>e.jsx("div",{className:"flex gap-0.5",children:[1,2,3,4,5].map(f=>e.jsx(Da,{className:At("h-4 w-4",p>=f?"fill-yellow-400 text-yellow-400":"text-muted-foreground")},f))});return e.jsx(zs,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Wh,{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(ve,{children:e.jsxs(bt,{className:"pb-2",children:[e.jsx(kn,{children:"Total Reviews"}),e.jsx(St,{className:"text-3xl",children:(a==null?void 0:a.length)||0})]})}),e.jsx(ve,{children:e.jsxs(bt,{className:"pb-2",children:[e.jsx(kn,{children:"Average Rating"}),e.jsxs(St,{className:"flex items-center gap-2 text-3xl",children:[o,e.jsx(Da,{className:"h-6 w-6 fill-yellow-400 text-yellow-400"})]})]})}),e.jsx(ve,{children:e.jsxs(bt,{className:"pb-2",children:[e.jsx(kn,{children:"5-Star Reviews"}),e.jsx(St,{className:"text-3xl",children:(c==null?void 0:c[5])||0})]})}),e.jsx(ve,{children:e.jsxs(bt,{className:"pb-2",children:[e.jsx(kn,{children:"Posted to Google"}),e.jsxs(St,{className:"flex items-center gap-2 text-3xl",children:[d,e.jsx(wr,{className:"h-5 w-5 text-muted-foreground"})]})]})})]}),e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(Lr,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search by name, email, or review...",value:s,onChange:p=>t(p.target.value),className:"pl-9"})]}),e.jsx(ve,{children:e.jsx(Me,{className:"p-0",children:e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"Member"}),e.jsx(Pt,{children:"Rating"}),e.jsx(Pt,{className:"hidden md:table-cell",children:"Review"}),e.jsx(Pt,{children:"Google"}),e.jsx(Pt,{children:"Date"})]})}),e.jsx(Ka,{children:i?e.jsx(pn,{children:e.jsx(gt,{colSpan:5,className:"text-center py-8",children:"Loading reviews..."})}):(l==null?void 0:l.length)===0?e.jsx(pn,{children:e.jsx(gt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No reviews found"})}):l==null?void 0:l.map(p=>{var f,y;return e.jsxs(pn,{className:"cursor-pointer hover:bg-muted/50",onClick:()=>r(p),children:[e.jsx(gt,{children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:((f=p.profiles)==null?void 0:f.name)||"Unknown"}),e.jsx("div",{className:"text-sm text-muted-foreground",children:(y=p.profiles)==null?void 0:y.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(Oe,{variant:"secondary",className:"bg-green-100 text-green-800",children:"Posted"}):e.jsx(Oe,{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(Ls,{open:!!n,onOpenChange:()=>r(null),children:e.jsxs(Ps,{className:"max-w-lg",children:[e.jsx(Os,{children:e.jsx(Ds,{children:"Review Details"})}),n&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-4 p-4 bg-muted/50 rounded-lg",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-semibold text-lg",children:((h=n.profiles)==null?void 0:h.name)||"Unknown Member"}),((m=n.profiles)==null?void 0:m.email)&&e.jsxs("a",{href:`mailto:${n.profiles.email}`,className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-primary",children:[e.jsx(ln,{className:"h-3 w-3"}),n.profiles.email]})]}),e.jsxs("div",{className:"text-right",children:[u(n.rating),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[n.rating," out of 5 stars"]})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-medium mb-2",children:"Review"}),e.jsx("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap",children:n.review_text||"No written review provided."})]}),e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(ga,{className:"h-4 w-4"}),Hs(new Date(n.created_at),"MMMM d, yyyy 'at' h:mm a")]}),n.posted_to_google?e.jsxs(Oe,{variant:"secondary",className:"bg-green-100 text-green-800",children:[e.jsx(wr,{className:"h-3 w-3 mr-1"}),"Posted to Google"]}):e.jsx(Oe,{variant:"outline",children:"Not posted to Google"})]})]})]})})]})})},f4t={agent_card:"Agent Card",listing:"Listing",lead_site:"Lead Site",guest_book:"Guest Book",landing_page:"Landing Page",connect_page:"Connect Page",booking:"Booking"},nsr={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 rsr(){const[s,t]=_.useState(""),[n,r]=_.useState("all"),[a,i]=_.useState("all"),[l,o]=_.useState("7"),{data:c,isLoading:d}=at({queryKey:["lead-notification-log",l],queryFn:async()=>{const m=new Date(Date.now()-Number(l)*864e5).toISOString(),{data:p,error:f}=await q.from("lead_notification_log").select("*").gte("created_at",m).order("created_at",{ascending:!1}).limit(2e3);if(f)throw f;return p||[]}}),u=_.useMemo(()=>{const m=s.trim().toLowerCase();return(c||[]).filter(p=>n!=="all"&&p.source!==n||a!=="all"&&p.status!==a?!1:m?[p.agent_name,p.agent_email,p.lead_name,p.lead_email,p.lead_phone,p.subject].some(f=>(f||"").toLowerCase().includes(m)):!0)},[c,s,n,a]),h=_.useMemo(()=>{const m=u.length,p=u.filter(v=>v.status==="sent"||v.status==="backfilled").length,f=u.filter(v=>v.status==="failed").length,y=new Set(u.map(v=>v.agent_user_id).filter(Boolean)).size;return{total:m,sent:p,failed:f,agents:y}},[u]);return e.jsx(zs,{children:e.jsxs("div",{className:"container mx-auto py-6 space-y-6",children:[e.jsx(Wh,{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(ve,{children:e.jsxs(Me,{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(ve,{children:e.jsxs(Me,{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(ve,{children:e.jsxs(Me,{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(ve,{children:e.jsxs(Me,{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(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search agent or lead name, email, phone…",value:s,onChange:m=>t(m.target.value),className:"pl-9"})]}),e.jsxs(is,{value:n,onValueChange:r,children:[e.jsx(rs,{className:"w-full md:w-48",children:e.jsx(ls,{placeholder:"Source"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Sources"}),Object.entries(f4t).map(([m,p])=>e.jsx(He,{value:m,children:p},m))]})]}),e.jsxs(is,{value:a,onValueChange:i,children:[e.jsx(rs,{className:"w-full md:w-40",children:e.jsx(ls,{placeholder:"Status"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Statuses"}),e.jsx(He,{value:"sent",children:"Sent"}),e.jsx(He,{value:"backfilled",children:"Backfilled"}),e.jsx(He,{value:"failed",children:"Failed"})]})]}),e.jsxs(is,{value:l,onValueChange:o,children:[e.jsx(rs,{className:"w-full md:w-36",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"1",children:"Last 24h"}),e.jsx(He,{value:"7",children:"Last 7 days"}),e.jsx(He,{value:"14",children:"Last 14 days"}),e.jsx(He,{value:"30",children:"Last 30 days"})]})]})]}),e.jsx(ve,{children:e.jsx(Me,{className:"p-0",children:e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"When"}),e.jsx(Pt,{children:"Source"}),e.jsx(Pt,{children:"Agent"}),e.jsx(Pt,{children:"Lead"}),e.jsx(Pt,{children:"Status"})]})}),e.jsx(Ka,{children:d?e.jsx(pn,{children:e.jsx(gt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"Loading…"})}):u.length===0?e.jsx(pn,{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(pn,{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(Oe,{variant:"secondary",children:f4t[m.source]||m.source})}),e.jsxs(gt,{children:[e.jsx("div",{className:"font-medium",children:m.agent_name||"—"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:m.agent_email||"—"})]}),e.jsxs(gt,{children:[e.jsx("div",{className:"font-medium",children:m.lead_name||"—"}),e.jsxs("div",{className:"text-xs text-muted-foreground flex flex-wrap gap-x-3 gap-y-1",children:[m.lead_email&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ln,{className:"h-3 w-3"}),m.lead_email]}),m.lead_phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(_a,{className:"h-3 w-3"}),m.lead_phone]})]})]}),e.jsxs(gt,{children:[e.jsx(Oe,{className:nsr[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 asr=[{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"}],isr=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 osr(){const s=Bt(),{user:t}=hs(),[n,r]=_.useState(!1),[a,i]=_.useState(!1),[l,o]=_.useState(!1),{data:c,isLoading:d}=at({queryKey:["weekly-digest-settings"],queryFn:async()=>{const{data:M,error:I}=await q.from("weekly_digest_settings").select("*").single();if(I)throw I;return M}}),{data:u,isLoading:h}=at({queryKey:["weekly-digest-logs"],queryFn:async()=>{const{data:M,error:I}=await q.from("weekly_digest_logs").select("*").order("sent_at",{ascending:!1}).limit(100);if(I)throw I;return M}}),{data:m}=at({queryKey:["digest-subscriber-count"],queryFn:async()=>{const{count:M,error:I}=await q.from("profiles").select("id",{count:"exact",head:!0}).eq("digest_opt_out",!1).not("email","is",null);if(I)throw I;return M||0}}),{data:p,refetch:f}=at({queryKey:["digest-queue-status"],queryFn:async()=>{const M=new Date;M.setUTCHours(0,0,0,0);const[I,D,O,V]=await Promise.all([q.from("weekly_digest_send_queue").select("id",{count:"exact",head:!0}).eq("status","pending").gte("created_at",M.toISOString()),q.from("weekly_digest_send_queue").select("id",{count:"exact",head:!0}).eq("status","processing").gte("created_at",M.toISOString()),q.from("weekly_digest_send_queue").select("id",{count:"exact",head:!0}).eq("status","sent").gte("created_at",M.toISOString()),q.from("weekly_digest_send_queue").select("id",{count:"exact",head:!0}).eq("status","failed").gte("created_at",M.toISOString())]);return{pending:I.count||0,processing:D.count||0,sent:O.count||0,failed:V.count||0,total:(I.count||0)+(D.count||0)+(O.count||0)+(V.count||0)}},refetchInterval:5e3});_.useEffect(()=>{if(p&&(p.pending>0||p.processing>0)){const M=setInterval(()=>{f(),s.invalidateQueries({queryKey:["weekly-digest-logs"]}),s.invalidateQueries({queryKey:["digest-today-failed-count"]}),s.invalidateQueries({queryKey:["digest-today-missing-count"]})},5e3);return()=>clearInterval(M)}},[p,f,s]);const{data:y=0}=at({queryKey:["digest-today-failed-count"],queryFn:async()=>{const M=new Date;M.setUTCHours(0,0,0,0);const{count:I,error:D}=await q.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}}),v=mt({mutationFn:async M=>{const{error:I}=await q.from("weekly_digest_settings").update(M).eq("id",c==null?void 0:c.id);if(I)throw I},onSuccess:()=>{s.invalidateQueries({queryKey:["weekly-digest-settings"]}),se.success("Settings updated")},onError:M=>{se.error("Failed to update settings: "+M.message)}}),g=async()=>{r(!0);try{const{data:M,error:I}=await q.functions.invoke("send-weekly-digest",{body:{manual:!0}});if(I)throw I;M.queued?se.success(`${M.queued.toLocaleString()} emails queued! They'll be sent automatically (~80/minute).`):M.sent!==void 0&&se.success(`Digest sent! ${M.sent} emails delivered, ${M.failed} failed`),f(),s.invalidateQueries({queryKey:["weekly-digest-logs"]})}catch(M){se.error("Failed to send digest: "+M.message)}finally{r(!1)}},b=async()=>{var M,I,D,O,V,G;if(!(t!=null&&t.email)){se.error("No email found for your account");return}i(!0);try{const{data:$,error:H}=await q.functions.invoke("send-weekly-digest",{body:{preview:!0,previewEmail:t.email}});if(H)throw H;const Y=$==null?void 0:$.resendId,Z=$==null?void 0:$.resendDetails,ne=Z==null?void 0:Z.status,ce=((M=Z==null?void 0:Z.body)==null?void 0:M.status)||((D=(I=Z==null?void 0:Z.body)==null?void 0:I.data)==null?void 0:D.status),ie=((V=(O=Z==null?void 0:Z.body)==null?void 0:O.error)==null?void 0:V.message)||((G=Z==null?void 0:Z.body)==null?void 0:G.message);se.success(Y?`Preview accepted by email provider (id: ${Y})${ne?`, status check: ${ne}`:""}${ce?`, provider: ${ce}`:""}${ie?` (${ie})`:""}. Check spam/promotions—delivery can take a few minutes.`:"Preview accepted by email provider. Check spam/promotions—delivery can take a few minutes.")}catch($){se.error("Failed to send preview: "+$.message)}finally{i(!1)}},j=async()=>{o(!0);try{const{data:M,error:I}=await q.functions.invoke("send-weekly-digest",{body:{retryFailed:!0}});if(I)throw I;M.queued===0||M.sent===0&&M.failed===0&&!M.queued?se.info("No failed emails to retry"):M.queued?se.success(`${M.queued} emails queued for retry!`):se.success(`Retry complete! ${M.sent} emails delivered, ${M.failed} failed`),f(),s.invalidateQueries({queryKey:["weekly-digest-logs"]}),s.invalidateQueries({queryKey:["digest-today-failed-count"]}),s.invalidateQueries({queryKey:["digest-today-missing-count"]})}catch(M){se.error("Failed to retry: "+M.message)}finally{o(!1)}},S=p!=null&&p.total?Math.round((p.sent+p.failed)/p.total*100):0,C=((p==null?void 0:p.pending)||0)>0||((p==null?void 0:p.processing)||0)>0,{data:E}=at({queryKey:["digest-delivery-stats"],queryFn:async()=>{var G,$;const M=new Date;M.setUTCHours(0,0,0,0);const[I,D,O,V]=await Promise.all([q.from("weekly_digest_logs").select("id",{count:"exact",head:!0}).eq("delivery_status","sent").gte("sent_at",M.toISOString()),q.from("weekly_digest_logs").select("id",{count:"exact",head:!0}).eq("delivery_status","failed").gte("sent_at",M.toISOString()),q.from("weekly_digest_logs").select("id",{count:"exact",head:!0}).eq("has_agent_os_activity",!0).gte("sent_at",M.toISOString()),q.from("weekly_digest_logs").select("sent_at").order("sent_at",{ascending:!1}).limit(1)]);return{totalSent:I.count||0,totalFailed:D.count||0,agentOsEngaged:O.count||0,lastSent:(($=(G=V.data)==null?void 0:G[0])==null?void 0:$.sent_at)||null}},refetchInterval:C?5e3:!1}),P={totalSent:(E==null?void 0:E.totalSent)||0,totalFailed:(E==null?void 0:E.totalFailed)||0,lastSent:E==null?void 0:E.lastSent,agentOsEngaged:(E==null?void 0:E.agentOsEngaged)||0};return d?e.jsx(zs,{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(zs,{title:"Weekly Digest",description:"Configure and manage automated weekly email digests for members",children:e.jsxs(Yr,{defaultValue:"settings",className:"space-y-6",children:[e.jsxs(Zr,{children:[e.jsxs(Ht,{value:"settings",className:"flex items-center gap-2",children:[e.jsx(qc,{className:"h-4 w-4"}),"Settings"]}),e.jsxs(Ht,{value:"stats",className:"flex items-center gap-2",children:[e.jsx(bl,{className:"h-4 w-4"}),"Delivery Stats"]})]}),e.jsxs(Gt,{value:"settings",className:"space-y-6",children:[C&&p&&e.jsx(ve,{className:"border-primary/50 bg-primary/5",children:e.jsxs(Me,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-4 mb-4",children:[e.jsx(Ct,{className:"h-5 w-5 animate-spin text-primary"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-medium",children:"Sending emails..."}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[p.sent.toLocaleString()," sent, ",p.pending.toLocaleString()," pending",p.failed>0&&`, ${p.failed} failed`]})]}),e.jsxs("span",{className:"text-sm font-medium",children:[S,"%"]})]}),e.jsx(Fi,{value:S,className:"h-2"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:["Processing ~80 emails per minute. Estimated time remaining: ~",Math.ceil(p.pending/80)," min"]})]})}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[e.jsx(ve,{children:e.jsx(Me,{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(In,{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(ve,{children:e.jsx(Me,{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(Er,{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(ve,{children:e.jsx(Me,{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(Rd,{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(ve,{children:e.jsx(Me,{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(Gr,{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(ve,{children:[e.jsxs(bt,{children:[e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(Gr,{className:"h-5 w-5"}),"Schedule"]}),e.jsx(kn,{children:"Configure when the digest is sent"})]}),e.jsxs(Me,{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Enable Weekly Digest"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Send automated weekly emails to members"})]}),e.jsx(fn,{checked:c==null?void 0:c.is_enabled,onCheckedChange:M=>v.mutate({is_enabled:M})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Cron Frequency"}),e.jsxs(is,{value:(c==null?void 0:c.cron_frequency)||"daily",onValueChange:M=>v.mutate({cron_frequency:M}),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"daily",children:"Daily (runs once at selected time)"}),e.jsx(He,{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(J,{children:"Day of Week"}),e.jsxs(is,{value:String(c==null?void 0:c.send_day),onValueChange:M=>v.mutate({send_day:parseInt(M)}),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsx(as,{children:asr.map(M=>e.jsx(He,{value:M.value,children:M.label},M.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Time (UTC)"}),e.jsxs(is,{value:String(c==null?void 0:c.send_hour),onValueChange:M=>v.mutate({send_hour:parseInt(M)}),disabled:(c==null?void 0:c.cron_frequency)==="daily",children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsx(as,{children:isr.map(M=>e.jsx(He,{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(B,{onClick:b,disabled:a,variant:"outline",className:"flex-1",children:[e.jsx(ya,{className:"h-4 w-4 mr-2"}),a?"Sending...":"Send Preview to Me"]}),e.jsxs(B,{onClick:g,disabled:n,className:"flex-1",children:[e.jsx(Or,{className:"h-4 w-4 mr-2"}),n?"Sending...":"Send to All"]})]}),y>0&&e.jsxs(B,{onClick:j,disabled:l,variant:"outline",className:"w-full",children:[e.jsx(uo,{className:`h-4 w-4 mr-2 ${l?"animate-spin":""}`}),l?"Retrying...":`Retry ${y} Failed`]})]})]})]}),e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(Fr,{className:"h-5 w-5"}),"Content Sections"]}),e.jsx(kn,{children:"Choose what to include in the digest"})]}),e.jsxs(Me,{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(Fr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(J,{children:"New Resources"})]}),e.jsx(fn,{checked:c==null?void 0:c.include_new_resources,onCheckedChange:M=>v.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(In,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(J,{children:"Community Highlights"})]}),e.jsx(fn,{checked:c==null?void 0:c.include_community_posts,onCheckedChange:M=>v.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(bl,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(J,{children:"Agent OS Stats"})]}),e.jsx(fn,{checked:c==null?void 0:c.include_agent_os_stats,onCheckedChange:M=>v.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(ga,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(J,{children:"Upcoming Events"})]}),e.jsx(fn,{checked:c==null?void 0:c.include_upcoming_events,onCheckedChange:M=>v.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(ku,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(J,{children:"Goals Progress"})]}),e.jsx(fn,{checked:c==null?void 0:c.include_goals_progress,onCheckedChange:M=>v.mutate({include_goals_progress:M})})]})]})]})]}),e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsx(St,{children:"Custom Introduction"}),e.jsx(kn,{children:"Personalize the intro message (optional)"})]}),e.jsx(Me,{children:e.jsx(Ms,{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=>v.mutate({custom_intro_text:M.target.value||null}),rows:3})})]})]}),e.jsx(Gt,{value:"stats",children:e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(ln,{className:"h-5 w-5"}),"Delivery History"]}),e.jsx(kn,{children:"Recent digest emails sent to members"})]}),e.jsx(Me,{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(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"Email"}),e.jsx(Pt,{children:"Sent At"}),e.jsx(Pt,{children:"Status"}),e.jsx(Pt,{children:"Resources"}),e.jsx(Pt,{children:"Agent OS"})]})}),e.jsx(Ka,{children:u.map(M=>e.jsxs(pn,{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(Oe,{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(Oe,{variant:"secondary",children:"Active"}):e.jsx(Oe,{variant:"outline",children:"Not Started"})})]},M.id))})]}):e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(ln,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No digests sent yet"}),e.jsx("p",{className:"text-sm",children:"Send your first digest to see delivery stats"})]})})]})})]})})}const lsr={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 csr(){var ae,le,be;const s=Bt(),[t,n]=_.useState(""),[r,a]=_.useState(null),[i,l]=_.useState(!1),[o,c]=_.useState(!1),[d,u]=_.useState(""),[h,m]=_.useState(""),[p,f]=_.useState(!0),[y,v]=_.useState(!1),[g,b]=_.useState(""),[j,S]=_.useState(null),{data:C,isLoading:E}=at({queryKey:["admin-agent-points"],queryFn:async()=>{const{data:me,error:he}=await q.from("agent_attendance_stats").select("*").order("total_points",{ascending:!1});if(he)throw he;const pe=(me==null?void 0:me.map(Pe=>Pe.user_id))||[],{data:Ce}=await q.from("profiles").select("id, name, email").in("id",pe),Ae=new Map((Ce==null?void 0:Ce.map(Pe=>[Pe.id,{name:Pe.name,email:Pe.email}]))||[]);return me==null?void 0:me.map(Pe=>({...Pe,profile:Ae.get(Pe.user_id)||null}))}}),{data:P}=at({queryKey:["all-profiles-for-points",C],queryFn:async()=>{const he=[];let pe=0;for(;;){const{data:Ce,error:Ae}=await q.from("profiles").select("id, name, email").order("name").range(pe,pe+1e3-1);if(Ae)throw Ae;if(he.push(...Ce),!Ce||Ce.length<1e3)break;pe+=1e3}return he}}),I=((P==null?void 0:P.filter(me=>!(C!=null&&C.some(he=>he.user_id===me.id))))||[]).filter(me=>{var pe,Ce;if(!g)return!0;const he=g.toLowerCase();return((pe=me.name)==null?void 0:pe.toLowerCase().includes(he))||((Ce=me.email)==null?void 0:Ce.toLowerCase().includes(he))}),{data:D,isLoading:O}=at({queryKey:["agent-point-history",r==null?void 0:r.user_id],queryFn:async()=>{if(!(r!=null&&r.user_id))return[];const{data:me,error:he}=await q.from("agent_points").select("*").eq("user_id",r.user_id).order("created_at",{ascending:!1});if(he)throw he;return me},enabled:!!(r!=null&&r.user_id)&&o}),{data:V}=at({queryKey:["agent-badges",r==null?void 0:r.user_id],queryFn:async()=>{if(!(r!=null&&r.user_id))return[];const{data:me,error:he}=await q.from("agent_badges").select("*").eq("user_id",r.user_id).order("earned_at",{ascending:!1});if(he)throw he;return me},enabled:!!(r!=null&&r.user_id)}),G=mt({mutationFn:async({userId:me,points:he,reason:pe})=>{const{error:Ce}=await q.from("agent_points").insert({user_id:me,points:he,reason:pe});if(Ce)throw Ce;const{data:Ae}=await q.from("agent_attendance_stats").select("total_points, spendable_points").eq("user_id",me).maybeSingle(),Pe=((Ae==null?void 0:Ae.total_points)||0)+he,ze=((Ae==null?void 0:Ae.spendable_points)||0)+he,{error:ke}=await q.from("agent_attendance_stats").upsert({user_id:me,total_points:Math.max(0,Pe),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(""),se.success(p?"Points awarded successfully!":"Points deducted successfully!")},onError:me=>{console.error("Error modifying points:",me),se.error("Failed to modify points")}}),$=()=>{if(!r||!d||!h){se.error("Please fill in all fields");return}const me=parseInt(d);if(isNaN(me)||me<=0){se.error("Please enter a valid positive number");return}G.mutate({userId:r.user_id,points:p?me:-me,reason:h})},H=()=>{if(!j||!d||!h){se.error("Please fill in all fields");return}const me=parseInt(d);if(isNaN(me)||me<=0){se.error("Please enter a valid positive number");return}G.mutate({userId:j.id,points:me,reason:h},{onSuccess:()=>{v(!1),S(null),b("")}})},Y=(me,he)=>{a(me),f(he),l(!0)},Z=me=>{a(me),c(!0)},ne=C==null?void 0:C.filter(me=>{var Ae,Pe,ze,ke;const he=((Pe=(Ae=me.profile)==null?void 0:Ae.name)==null?void 0:Pe.toLowerCase())||"",pe=((ke=(ze=me.profile)==null?void 0:ze.email)==null?void 0:ke.toLowerCase())||"",Ce=t.toLowerCase();return he.includes(Ce)||pe.includes(Ce)}),ce=(C==null?void 0:C.reduce((me,he)=>me+he.total_points,0))||0,ie=(C==null?void 0:C.length)||0,te=ie>0?Math.round(ce/ie):0;return E?e.jsx(zs,{title:"Agent Points",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(cn,{className:"h-8 w-64"}),e.jsx("div",{className:"grid grid-cols-3 gap-4",children:[1,2,3].map(me=>e.jsx(cn,{className:"h-24"},me))}),e.jsx(cn,{className:"h-96"})]})}):e.jsx(zs,{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(ve,{children:e.jsxs(Me,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(In,{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:ie}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"with points tracked"})]})}),e.jsx(ve,{children:e.jsxs(Me,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(wl,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Total Points"})]}),e.jsx("p",{className:"text-2xl font-bold",children:ce.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"awarded across all agents"})]})}),e.jsx(ve,{children:e.jsxs(Me,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Nl,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Average Points"})]}),e.jsx("p",{className:"text-2xl font-bold",children:te}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"per agent"})]})})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 items-start sm:items-center justify-between",children:[e.jsxs("div",{className:"relative max-w-sm w-full",children:[e.jsx(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search agents...",value:t,onChange:me=>n(me.target.value),className:"pl-10"})]}),e.jsxs(B,{onClick:()=>v(!0),children:[e.jsx(rn,{className:"h-4 w-4 mr-2"}),"Award Points to New Agent"]})]}),e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsx(St,{children:"Agent Leaderboard"}),e.jsx(kn,{children:"All agents with their points, events, and streaks"})]}),e.jsx(Me,{children:!ne||ne.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(wl,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No agents with points yet"})]}):e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{className:"w-12",children:"#"}),e.jsx(Pt,{children:"Agent"}),e.jsx(Pt,{className:"text-center",children:"Total Points"}),e.jsx(Pt,{className:"text-center",children:"Spendable"}),e.jsx(Pt,{className:"text-center",children:"Events"}),e.jsx(Pt,{className:"text-center",children:"Streak"}),e.jsx(Pt,{className:"text-right",children:"Actions"})]})}),e.jsx(Ka,{children:ne.map((me,he)=>{var pe,Ce,Ae,Pe;return e.jsxs(pn,{children:[e.jsx(gt,{className:"font-medium",children:he<3?e.jsx("div",{className:`w-6 h-6 rounded-full flex items-center justify-center ${he===0?"bg-yellow-100 text-yellow-700":he===1?"bg-gray-100 text-gray-600":"bg-amber-100 text-amber-700"}`,children:he+1}):e.jsx("span",{className:"text-muted-foreground",children:he+1})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ja,{className:"h-8 w-8",children:e.jsx(Na,{children:((Ce=(pe=me.profile)==null?void 0:pe.name)==null?void 0:Ce.charAt(0))||"?"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((Ae=me.profile)==null?void 0:Ae.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(Pe=me.profile)==null?void 0:Pe.email})]})]})}),e.jsx(gt,{className:"text-center",children:e.jsxs(Oe,{variant:"secondary",className:"font-bold",children:[e.jsx(Da,{className:"h-3 w-3 mr-1"}),me.total_points]})}),e.jsx(gt,{className:"text-center",children:e.jsxs(Oe,{variant:"outline",className:"font-bold text-primary",children:[e.jsx(Vo,{className:"h-3 w-3 mr-1"}),me.spendable_points||0]})}),e.jsx(gt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(ga,{className:"h-3 w-3 text-muted-foreground"}),me.total_events_attended]})}),e.jsx(gt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(gu,{className:"h-3 w-3 text-orange-500"}),me.current_streak]})}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>Y(me,!0),title:"Award points",children:e.jsx(rn,{className:"h-4 w-4 text-green-600"})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>Y(me,!1),title:"Deduct points",children:e.jsx(uN,{className:"h-4 w-4 text-red-600"})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>Z(me),title:"View history",children:e.jsx(R_,{className:"h-4 w-4"})})]})})]},me.user_id)})})]})})]}),e.jsx(Ls,{open:i,onOpenChange:l,children:e.jsxs(Ps,{children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:p?"Award Points":"Deduct Points"}),e.jsxs(_r,{children:[p?"Award":"Deduct"," points ",p?"to":"from"," ",((ae=r==null?void 0:r.profile)==null?void 0:ae.name)||"this agent"]})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"points",children:"Points Amount"}),e.jsx(xe,{id:"points",type:"number",min:"1",placeholder:"Enter points...",value:d,onChange:me=>u(me.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"reason",children:"Reason"}),e.jsx(Ms,{id:"reason",placeholder:"Enter reason for this adjustment...",value:h,onChange:me=>m(me.target.value)})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(B,{onClick:$,disabled:G.isPending,className:p?"bg-green-600 hover:bg-green-700":"bg-red-600 hover:bg-red-700",children:G.isPending?"Saving...":p?"Award Points":"Deduct Points"})]})]})}),e.jsx(Ls,{open:o,onOpenChange:c,children:e.jsxs(Ps,{className:"max-w-2xl",children:[e.jsxs(Os,{children:[e.jsxs(Ds,{children:["Point History: ",(le=r==null?void 0:r.profile)==null?void 0:le.name]}),e.jsx(_r,{children:"View all point transactions and badges for this agent"})]}),e.jsxs(Yr,{defaultValue:"history",className:"w-full",children:[e.jsxs(Zr,{className:"grid w-full grid-cols-2",children:[e.jsx(Ht,{value:"history",children:"Point History"}),e.jsx(Ht,{value:"badges",children:"Badges"})]}),e.jsx(Gt,{value:"history",className:"mt-4",children:O?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(me=>e.jsx(cn,{className:"h-12"},me))}):!D||D.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(R_,{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(me=>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:me.reason}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Hs(new Date(me.created_at),"MMM d, yyyy h:mm a")})]}),e.jsxs(Oe,{variant:me.points>=0?"default":"destructive",className:me.points>=0?"bg-green-100 text-green-800":"",children:[me.points>=0?"+":"",me.points]})]},me.id))})}),e.jsx(Gt,{value:"badges",className:"mt-4",children:!V||V.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Hh,{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:V.map(me=>e.jsxs("div",{className:`p-3 rounded-lg ${lsr[me.badge_type]||"bg-gray-100"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Hh,{className:"h-5 w-5"}),e.jsx("span",{className:"font-medium",children:me.badge_name})]}),me.badge_description&&e.jsx("p",{className:"text-xs mt-1 opacity-80",children:me.badge_description}),e.jsxs("p",{className:"text-xs mt-1 opacity-60",children:["Earned ",Hs(new Date(me.earned_at),"MMM d, yyyy")]})]},me.id))})})]})]})}),e.jsx(Ls,{open:y,onOpenChange:me=>{v(me),me||(S(null),b(""),u(""),m(""))},children:e.jsxs(Ps,{className:"max-w-md",children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Award Points to New Agent"}),e.jsx(_r,{children:"Select an agent who doesn't have points yet and award them points"})]}),e.jsx("div",{className:"space-y-4 py-4",children:j?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-muted/50 rounded-lg",children:[e.jsx(ja,{className:"h-10 w-10",children:e.jsx(Na,{children:((be=j.name)==null?void 0:be.charAt(0))||"?"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-medium",children:j.name||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:j.email})]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>S(null),children:"Change"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"new-points",children:"Points Amount"}),e.jsx(xe,{id:"new-points",type:"number",min:"1",placeholder:"Enter points...",value:d,onChange:me=>u(me.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"new-reason",children:"Reason"}),e.jsx(Ms,{id:"new-reason",placeholder:"Enter reason for awarding points...",value:h,onChange:me=>m(me.target.value)})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Search Agent"}),e.jsxs("div",{className:"relative",children:[e.jsx(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search by name or email...",value:g,onChange:me=>b(me.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(In,{className:"h-6 w-6 mx-auto mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:g?"No matching agents found":"All agents already have points"})]}):I.slice(0,20).map(me=>{var he;return e.jsxs("button",{onClick:()=>S(me),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(ja,{className:"h-8 w-8",children:e.jsx(Na,{children:((he=me.name)==null?void 0:he.charAt(0))||"?"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:me.name||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:me.email})]})]},me.id)})})]})}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>v(!1),children:"Cancel"}),j&&e.jsxs(B,{onClick:H,disabled:G.isPending,className:"bg-green-600 hover:bg-green-700",children:[e.jsx(rn,{className:"h-4 w-4 mr-2"}),"Award Points"]})]})]})})]})})}function dsr(){const{data:s,isLoading:t}=eMs(),[n,r]=_.useState(null),[a,i]=_.useState(!1),[l,o]=_.useState(""),[c,d]=_.useState("all"),[u,h]=_.useState("newest"),[m,p]=_.useState("table"),f=_.useMemo(()=>(s==null?void 0:s.map(j=>j.user_id))||[],[s]),y=_.useMemo(()=>(s==null?void 0:s.map(j=>j.id))||[],[s]),{data:v}=at({queryKey:["card-profiles-lookup",f],queryFn:async()=>{if(f.length===0)return{};const{data:j}=await q.from("profiles").select("id, name, email").in("id",f),S={};return j==null||j.forEach(C=>{S[C.id]={name:C.name||"",email:C.email||""}}),S},enabled:f.length>0}),{data:g}=at({queryKey:["card-stats-all",y],queryFn:async()=>{if(y.length===0)return{};const j={};y.forEach(E=>{j[E]={views:0,leads:0}});const{data:S}=await q.from("agent_card_interactions").select("card_id").in("card_id",y).eq("interaction_type","card_view");S==null||S.forEach(E=>{j[E.card_id]&&j[E.card_id].views++});const{data:C}=await q.from("agent_card_leads").select("card_id").in("card_id",y);return C==null||C.forEach(E=>{j[E.card_id]&&j[E.card_id].leads++}),j},enabled:y.length>0}),b=_.useMemo(()=>{if(!s)return[];let j=[...s];if(c==="live"?j=j.filter(S=>S.is_published):c==="draft"&&(j=j.filter(S=>!S.is_published)),l.trim()){const S=l.toLowerCase();j=j.filter(C=>{var P,M;const E=v==null?void 0:v[C.user_id];return C.slug.toLowerCase().includes(S)||((P=E==null?void 0:E.name)==null?void 0:P.toLowerCase().includes(S))||((M=E==null?void 0:E.email)==null?void 0:M.toLowerCase().includes(S))})}return u==="newest"?j.sort((S,C)=>new Date(C.created_at).getTime()-new Date(S.created_at).getTime()):u==="oldest"?j.sort((S,C)=>new Date(S.created_at).getTime()-new Date(C.created_at).getTime()):u==="name"?j.sort((S,C)=>{var E,P;return(((E=v==null?void 0:v[S.user_id])==null?void 0:E.name)||"").localeCompare(((P=v==null?void 0:v[C.user_id])==null?void 0:P.name)||"")}):u==="slug"?j.sort((S,C)=>S.slug.localeCompare(C.slug)):u==="views_desc"?j.sort((S,C)=>{var E,P;return(((E=g==null?void 0:g[C.id])==null?void 0:E.views)||0)-(((P=g==null?void 0:g[S.id])==null?void 0:P.views)||0)}):u==="views_asc"?j.sort((S,C)=>{var E,P;return(((E=g==null?void 0:g[S.id])==null?void 0:E.views)||0)-(((P=g==null?void 0:g[C.id])==null?void 0:P.views)||0)}):u==="leads_desc"?j.sort((S,C)=>{var E,P;return(((E=g==null?void 0:g[C.id])==null?void 0:E.leads)||0)-(((P=g==null?void 0:g[S.id])==null?void 0:P.leads)||0)}):u==="leads_asc"&&j.sort((S,C)=>{var E,P;return(((E=g==null?void 0:g[S.id])==null?void 0:E.leads)||0)-(((P=g==null?void 0:g[C.id])==null?void 0:P.leads)||0)}),j},[s,c,l,u,v]);return e.jsxs(zs,{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(B,{onClick:()=>i(!0),children:[e.jsx(rn,{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(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search by name, email, or slug...",value:l,onChange:j=>o(j.target.value),className:"pl-9"})]}),e.jsxs(is,{value:c,onValueChange:d,children:[e.jsx(rs,{className:"w-full sm:w-36",children:e.jsx(ls,{placeholder:"Status"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Status"}),e.jsx(He,{value:"live",children:"Live"}),e.jsx(He,{value:"draft",children:"Draft"})]})]}),e.jsxs(is,{value:u,onValueChange:h,children:[e.jsx(rs,{className:"w-full sm:w-44",children:e.jsx(ls,{placeholder:"Sort by"})}),e.jsxs(as,{children:[e.jsx(He,{value:"newest",children:"Newest First"}),e.jsx(He,{value:"oldest",children:"Oldest First"}),e.jsx(He,{value:"name",children:"Name A–Z"}),e.jsx(He,{value:"slug",children:"Slug A–Z"}),e.jsx(He,{value:"views_desc",children:"Most Views"}),e.jsx(He,{value:"views_asc",children:"Fewest Views"}),e.jsx(He,{value:"leads_desc",children:"Most Leads"}),e.jsx(He,{value:"leads_asc",children:"Fewest Leads"})]})]}),e.jsxs("div",{className:"flex border rounded-md",children:[e.jsx(B,{variant:m==="table"?"default":"ghost",size:"sm",onClick:()=>p("table"),className:"rounded-r-none",children:e.jsx(a$,{className:"h-4 w-4"})}),e.jsx(B,{variant:m==="grid"?"default":"ghost",size:"sm",onClick:()=>p("grid"),className:"rounded-l-none",children:e.jsx(sf,{className:"h-4 w-4"})})]})]}),!t&&s&&s.length>0&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Showing ",b.length," of ",s.length," cards"]}),t?e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(j=>e.jsx(cn,{className:"h-48"},j))}):b.length>0?m==="table"?e.jsx(usr,{cards:b,cardProfiles:v,cardStats:g,onEdit:r,sortBy:u,setSortBy:h}):e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:b.map(j=>e.jsx(hsr,{card:j,onEdit:()=>r(j),stats:g==null?void 0:g[j.id]},j.id))}):s&&s.length>0?e.jsx(ve,{children:e.jsxs(Me,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(Lr,{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(ve,{children:e.jsxs(Me,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(In,{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(B,{onClick:()=>i(!0),children:[e.jsx(rn,{className:"h-4 w-4 mr-2"}),"Create Card"]})]})})]}),e.jsx(msr,{open:a,onOpenChange:i}),n&&e.jsx(psr,{card:n,open:!!n,onOpenChange:j=>!j&&r(null)})]})}function usr({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(zf,{className:"h-3 w-3"}):a===`${c}_asc`?e.jsx(sp,{className:"h-3 w-3"}):e.jsx(Lg,{className:"h-3 w-3 opacity-40"});return e.jsx(ve,{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(Oe,{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(B,{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(B,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>{navigator.clipboard.writeText(h),se.success("Link copied!")},children:e.jsx(Ia,{className:"h-3.5 w-3.5"})}),e.jsx(B,{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(wr,{className:"h-3.5 w-3.5"})})})]})})]},c.id)})})]})})})}function hsr({card:s,onEdit:t,stats:n}){const[r,a]=_.useState(null);_.useEffect(()=>{(async()=>{const{data:c}=await q.from("profiles").select("name").eq("id",s.user_id).single();let d=null;try{const{data:u}=await q.storage.from("avatars").list(`${s.user_id}`);if(u&&u.length>0){const{data:h}=q.storage.from("avatars").getPublicUrl(`${s.user_id}/${u[0].name}`);d=h.publicUrl}}catch{}a({name:(c==null?void 0:c.name)||"Unknown",avatar_url:d})})()},[s.user_id]);const i=`https://cards.relevelup.com/${s.slug}`,l=()=>{navigator.clipboard.writeText(i),se.success("Link copied!")};return e.jsx(ve,{children:e.jsxs(Me,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start gap-3 mb-3",children:[e.jsxs(ja,{className:"h-10 w-10",children:[e.jsx(pi,{src:(r==null?void 0:r.avatar_url)||void 0}),e.jsx(Na,{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(Oe,{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(ya,{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(In,{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(B,{variant:"outline",size:"sm",onClick:t,className:"flex-1",children:[e.jsx(Ya,{className:"h-3 w-3 mr-1"}),"Edit"]}),e.jsx(B,{variant:"outline",size:"sm",onClick:l,children:e.jsx(Ia,{className:"h-3 w-3"})}),e.jsx(B,{variant:"outline",size:"sm",asChild:!0,children:e.jsx("a",{href:i,target:"_blank",rel:"noopener noreferrer",children:e.jsx(wr,{className:"h-3 w-3"})})})]})]})})}function msr({open:s,onOpenChange:t}){const[n,r]=_.useState(""),[a,i]=_.useState(""),[l,o]=_.useState(""),[c,d]=_.useState(!1),u=TFt(),h=l.trim(),{data:m}=at({queryKey:["profiles-search-for-cards",h],queryFn:async()=>{let b=q.from("profiles").select("id, name, email").order("name").limit(50);h.length>=2&&(b=b.or(`name.ilike.%${h}%,email.ilike.%${h}%`));const{data:j}=await b;return j||[]},enabled:s}),[p,f]=_.useState(null),y=(m==null?void 0:m.find(b=>b.id===n))||p,v=()=>{if(!n||!a.trim()){se.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("")}})},g=b=>{var S;r(b),d(!1);const j=m==null?void 0:m.find(C=>C.id===b);j&&(f(j),i(((S=j.name)==null?void 0:S.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,""))||""))};return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Create Agent Card"}),e.jsx(_r,{children:"Select an agent and set their card URL slug."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Agent"}),e.jsxs(od,{open:c,onOpenChange:d,children:[e.jsx(ld,{asChild:!0,children:e.jsxs(B,{variant:"outline",role:"combobox","aria-expanded":c,className:"w-full justify-between font-normal",children:[y?`${y.name} (${y.email})`:"Search for an agent...",e.jsx(I_,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Qc,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(Aj,{shouldFilter:!1,children:[e.jsx(Ej,{placeholder:"Search by name or email...",value:l,onValueChange:o}),e.jsxs(Tj,{children:[e.jsx(Mj,{children:"No agents found."}),e.jsx(V_,{children:(m||[]).map(b=>e.jsxs(d1,{value:b.id,onSelect:g,children:[e.jsx(ea,{className:At("mr-2 h-4 w-4",n===b.id?"opacity-100":"opacity-0")}),b.name," (",b.email,")"]},b.id))})]})]})})]})]}),e.jsxs("div",{children:[e.jsx(J,{children:"URL Slug"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"/card/"}),e.jsx(xe,{value:a,onChange:b=>i(b.target.value),placeholder:"john-doe"})]})]}),e.jsx(B,{onClick:v,disabled:u.isPending,className:"w-full",children:u.isPending?"Creating...":"Create Card"})]})]})})}function psr({card:s,open:t,onOpenChange:n}){const r=MFt(),{data:a}=PFt(s.id),i=Bt(),[l,o]=_.useState(null),[c,d]=_.useState(!1),[u,h]=_.useState(!1),[m,p]=_.useState(""),[f,y]=_.useState(s.slug),[v,g]=_.useState(!1),[b,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});_.useEffect(()=>{t&&(async()=>{try{const{data:D}=await q.storage.from("avatars").list(`${s.user_id}`);if(D&&D.length>0){const{data:O}=q.storage.from("avatars").getPublicUrl(`${s.user_id}/${D[0].name}`);o(`${O.publicUrl}?t=${Date.now()}`)}}catch{}})()},[s.user_id,t]);const S=I=>{var V;const D=(V=I.target.files)==null?void 0:V[0];if(!D)return;if(!D.type.startsWith("image/")){se.error("Please select an image file");return}if(D.size>5*1024*1024){se.error("Image must be under 5MB");return}const O=new FileReader;O.onloadend=()=>{p(O.result),h(!0)},O.readAsDataURL(D),I.target.value=""},C=async I=>{d(!0);try{const{data:D}=await q.storage.from("avatars").list(`${s.user_id}`);D&&D.length>0&&await q.storage.from("avatars").remove(D.map(H=>`${s.user_id}/${H.name}`));const O=`${s.user_id}/avatar.jpg`,{error:V}=await q.storage.from("avatars").upload(O,I,{upsert:!0,contentType:"image/jpeg"});if(V)throw V;const{data:G}=q.storage.from("avatars").getPublicUrl(O),$=`${G.publicUrl}?t=${Date.now()}`;o($),await q.from("profiles").update({avatar_url:$}).eq("id",s.user_id),i.invalidateQueries({queryKey:["agent-card-public"]}),se.success("Photo updated!")}catch(D){se.error(D.message||"Upload failed")}finally{d(!1)}},E=async()=>{const I=f.trim().toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/(^-|-$)/g,"");if(!I){se.error("Please enter a valid URL");return}if(I===s.slug){se.info("No changes to save");return}g(!0);try{const{data:D}=await q.from("agent_cards").select("id").eq("slug",I).neq("id",s.id).maybeSingle();if(D){se.error("This URL is already taken. Try another one.");return}const{error:O}=await q.from("agent_cards").update({slug:I}).eq("id",s.id);if(O)throw O;y(I),i.invalidateQueries({queryKey:["agent-cards-admin"]}),se.success("Card address updated!")}catch{se.error("Failed to update card address")}finally{g(!1)}},P=async(I,D)=>{var V;const O=(V=I.target.files)==null?void 0:V[0];if(O){if(!O.type.startsWith("image/")){se.error("Please select an image file");return}try{const G=O.name.split(".").pop()||"png",$=D==="brokerage_logo_url"?"brokerage-logo":"team-logo",H=`${s.user_id}/${$}.${G}`,{error:Y}=await q.storage.from("card-logos").upload(H,O,{upsert:!0});if(Y)throw Y;const{data:Z}=q.storage.from("card-logos").getPublicUrl(H),ne=Z.publicUrl+"?t="+Date.now();j(D==="brokerage_logo_url"?ce=>({...ce,[D]:ne,brokerage_display_name:""}):ce=>({...ce,[D]:ne,team_name:""})),se.success("Logo uploaded!")}catch{se.error("Failed to upload logo")}finally{I.target.value=""}}},M=()=>{r.mutate({id:s.id,...b,title:b.title||null,positioning_statement:b.positioning_statement||null,bio:b.bio||null,review_snippet:b.review_snippet||null,review_source_url:b.review_source_url||null,booking_url:b.booking_url||null,custom_cta_label:b.custom_cta_label||null,custom_cta_url:b.custom_cta_url||null,brokerage_display_name:b.brokerage_display_name||null,brokerage_logo_url:b.brokerage_logo_url||null,brokerage_logo_size:b.brokerage_logo_size,team_name:b.team_name||null,team_logo_url:b.team_logo_url||null,team_logo_size:b.team_logo_size},{onSuccess:()=>n(!1)})};return e.jsxs(e.Fragment,{children:[e.jsx(Ls,{open:t,onOpenChange:n,children:e.jsxs(Ps,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Edit Agent Card"}),e.jsxs(_r,{children:["/card/",s.slug]})]}),e.jsxs(Yr,{defaultValue:"content",children:[e.jsxs(Zr,{className:"w-full",children:[e.jsx(Ht,{value:"content",className:"flex-1",children:"Content"}),e.jsx(Ht,{value:"sections",className:"flex-1",children:"Sections"}),e.jsx(Ht,{value:"blocks",className:"flex-1",children:"Blocks"}),e.jsx(Ht,{value:"analytics",className:"flex-1",children:"Analytics"})]}),e.jsxs(Gt,{value:"content",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(J,{children:"Published"}),e.jsx(fn,{checked:b.is_published,onCheckedChange:I=>j(D=>({...D,is_published:I}))})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Agent Photo"}),e.jsxs("div",{className:"flex items-center gap-4 mt-1",children:[e.jsxs(ja,{className:"h-16 w-16",children:[e.jsx(pi,{src:l||void 0}),e.jsx(Na,{children:"?"})]}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:S,disabled:c}),e.jsx(B,{variant:"outline",size:"sm",asChild:!0,disabled:c,children:e.jsx("span",{children:c?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"h-3 w-3 mr-1 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Oa,{className:"h-3 w-3 mr-1"}),"Change Photo"]})})})]})]})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Card Address"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsxs("div",{className:"flex flex-1",children:[e.jsx("span",{className:"inline-flex items-center px-3 rounded-l-md border border-r-0 bg-muted text-muted-foreground text-xs whitespace-nowrap",children:"cards.relevelup.com/"}),e.jsx(xe,{value:f,onChange:I=>y(I.target.value.toLowerCase().replace(/[^a-z0-9-]/g,"-")),placeholder:"agent-name",className:"rounded-l-none"})]}),e.jsx(B,{variant:"outline",size:"sm",onClick:E,disabled:v||f===s.slug,className:"shrink-0",children:v?"Saving...":"Update"})]})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Theme"}),e.jsxs(is,{value:b.theme,onValueChange:I=>j(D=>({...D,theme:I})),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"standard",children:"✨ Standard (Modern Clean)"}),e.jsx(He,{value:"luxury",children:"🌙 Luxury (Dark & Gold)"}),e.jsx(He,{value:"bold",children:"🔥 Bold (Vibrant & Punchy)"}),e.jsx(He,{value:"classic",children:"📋 Classic (Professional)"})]})]})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Title / Tagline"}),e.jsx(xe,{value:b.title,onChange:I=>j(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(J,{children:"Positioning Statement"}),e.jsx(xe,{value:b.positioning_statement,onChange:I=>j(D=>({...D,positioning_statement:I.target.value})),placeholder:"Your home journey, handled with care."})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Bio"}),e.jsx(Ms,{value:b.bio,onChange:I=>j(D=>({...D,bio:I.target.value})),placeholder:"Short about me...",rows:3})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Review Snippet"}),e.jsx(xe,{value:b.review_snippet,onChange:I=>j(D=>({...D,review_snippet:I.target.value})),placeholder:"Best agent we've ever worked with..."})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Review Source URL"}),e.jsx(xe,{value:b.review_source_url,onChange:I=>j(D=>({...D,review_source_url:I.target.value})),placeholder:"https://g.page/your-business/review"})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Booking URL (optional — if empty, shows lead form)"}),e.jsx(xe,{value:b.booking_url,onChange:I=>j(D=>({...D,booking_url:I.target.value})),placeholder:"https://calendly.com/your-link"})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Custom CTA Label (optional)"}),e.jsx(xe,{value:b.custom_cta_label,onChange:I=>j(D=>({...D,custom_cta_label:I.target.value})),placeholder:"Book a Call"})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Custom CTA URL (optional)"}),e.jsx(xe,{value:b.custom_cta_url,onChange:I=>j(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(J,{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Brokerage Branding"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(xe,{value:b.brokerage_display_name,onChange:I=>j(D=>({...D,brokerage_display_name:I.target.value,brokerage_logo_url:""})),placeholder:"Brokerage name (or upload logo below)",disabled:!!b.brokerage_logo_url}),e.jsxs("div",{className:"flex items-center gap-3",children:[b.brokerage_logo_url&&e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:b.brokerage_logo_url,alt:"Brokerage logo",style:{height:`${b.brokerage_logo_size||56}px`},className:"max-w-[200px] object-contain rounded border bg-white p-1"}),e.jsx("button",{onClick:()=>j(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(Oa,{className:"h-3.5 w-3.5"}),b.brokerage_logo_url?"Change Logo":"Upload Logo"]}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:I=>P(I,"brokerage_logo_url")})]})]}),b.brokerage_logo_url&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(J,{className:"text-xs font-medium text-muted-foreground",children:"Logo Size"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[b.brokerage_logo_size||56,"px"]})]}),e.jsx(kx,{value:[b.brokerage_logo_size||56],onValueChange:([I])=>j(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(J,{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Team Branding"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(xe,{value:b.team_name,onChange:I=>j(D=>({...D,team_name:I.target.value,team_logo_url:""})),placeholder:"Team name (or upload logo below)",disabled:!!b.team_logo_url}),e.jsxs("div",{className:"flex items-center gap-3",children:[b.team_logo_url&&e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:b.team_logo_url,alt:"Team logo",style:{height:`${b.team_logo_size||56}px`},className:"max-w-[200px] object-contain rounded border bg-white p-1"}),e.jsx("button",{onClick:()=>j(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(Oa,{className:"h-3.5 w-3.5"}),b.team_logo_url?"Change Logo":"Upload Logo"]}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:I=>P(I,"team_logo_url")})]})]}),b.team_logo_url&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(J,{className:"text-xs font-medium text-muted-foreground",children:"Logo Size"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[b.team_logo_size||56,"px"]})]}),e.jsx(kx,{value:[b.team_logo_size||56],onValueChange:([I])=>j(D=>({...D,team_logo_size:I})),min:24,max:120,step:4})]})]})]})]}),e.jsx(Gt,{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:O})=>e.jsxs("div",{className:"flex items-center justify-between py-2",children:[e.jsxs("div",{children:[e.jsx(J,{children:D}),O&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[O," ",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(fn,{checked:b[I],onCheckedChange:V=>j(G=>({...G,[I]:V}))})]},I))}),e.jsx(Gt,{value:"blocks",className:"mt-4",children:e.jsx(grs,{cardId:s.id})}),e.jsx(Gt,{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(ve,{children:e.jsxs(Me,{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(ve,{children:e.jsxs(Me,{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(ve,{children:e.jsxs(Me,{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(Oe,{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(B,{onClick:M,disabled:r.isPending,className:"w-full mt-4",children:r.isPending?"Saving...":"Save Changes"})]})}),e.jsx(itt,{open:u,onClose:()=>h(!1),imageSrc:m,onCropComplete:C,aspectRatio:1})]})}const Z$={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"},Wat={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 Kat(s=!0){return at({queryKey:["marketplace-categories",s],queryFn:async()=>{let t=q.from("marketplace_categories").select("*").order("sort_order",{ascending:!0});s&&(t=t.eq("is_active",!0));const{data:n,error:r}=await t;if(r)throw r;return n}})}function fsr(){const s=Bt();return mt({mutationFn:async t=>{const{data:n,error:r}=await q.from("marketplace_categories").insert([t]).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-categories"]}),se.success("Category created successfully")},onError:t=>{se.error("Failed to create category: "+t.message)}})}function xsr(){const s=Bt();return mt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("marketplace_categories").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-categories"]}),se.success("Category updated successfully")},onError:t=>{se.error("Failed to update category: "+t.message)}})}function gsr(){const s=Bt();return mt({mutationFn:async t=>{const{error:n}=await q.from("marketplace_categories").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-categories"]}),se.success("Category deleted successfully")},onError:t=>{se.error("Failed to delete category: "+t.message)}})}function wrs(s,t=!0){return at({queryKey:["marketplace-products",s,t],queryFn:async()=>{let n=q.from("marketplace_products").select(` *, category:marketplace_categories(*), images:marketplace_product_images(*), video:marketplace_product_videos(*), variants:marketplace_product_variants(*) `).order("sort_order",{ascending:!0});s&&(n=n.eq("category_id",s)),t&&(n=n.eq("is_active",!0));const{data:r,error:a}=await n;if(a)throw a;return r}})}function ysr(s){return at({queryKey:["marketplace-product",s],queryFn:async()=>{const{data:t,error:n}=await q.from("marketplace_products").select(` *, category:marketplace_categories(*), images:marketplace_product_images(*), video:marketplace_product_videos(*), variants:marketplace_product_variants(*) `).eq("id",s).single();if(n)throw n;return t},enabled:!!s})}function vsr(){const s=Bt();return mt({mutationFn:async t=>{const{data:n,error:r}=await q.from("marketplace_products").insert([t]).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-products"]}),se.success("Product created successfully")},onError:t=>{se.error("Failed to create product: "+t.message)}})}function bsr(){const s=Bt();return mt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("marketplace_products").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",n.id]}),se.success("Product updated successfully")},onError:t=>{se.error("Failed to update product: "+t.message)}})}function _sr(){const s=Bt();return mt({mutationFn:async t=>{const{error:n}=await q.from("marketplace_products").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-products"]}),se.success("Product deleted successfully")},onError:t=>{se.error("Failed to delete product: "+t.message)}})}function wsr(){const s=Bt();return mt({mutationFn:async t=>{const{data:n,error:r}=await q.from("marketplace_product_images").insert([t]).select().single();if(r)throw r;return n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",n.product_id]})}})}function jsr(){const s=Bt();return mt({mutationFn:async({id:t,productId:n})=>{const{error:r}=await q.from("marketplace_product_images").delete().eq("id",t);if(r)throw r;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",t]}),se.success("Image deleted successfully")},onError:t=>{se.error("Failed to delete image: "+t.message)}})}function Nsr(){const s=Bt();return mt({mutationFn:async({imageId:t,productId:n})=>{const{error:r}=await q.from("marketplace_product_images").update({is_primary:!1}).eq("product_id",n);if(r)throw r;const{error:a}=await q.from("marketplace_product_images").update({is_primary:!0}).eq("id",t);if(a)throw a;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",t]}),se.success("Primary image updated")},onError:t=>{se.error("Failed to set primary image: "+t.message)}})}function ksr(){const s=Bt();return mt({mutationFn:async t=>{const{data:n,error:r}=await q.from("marketplace_product_variants").insert([t]).select().single();if(r)throw r;return n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",n.product_id]}),se.success("Variant added successfully")}})}function Ssr(){const s=Bt();return mt({mutationFn:async({id:t,productId:n})=>{const{error:r}=await q.from("marketplace_product_variants").delete().eq("id",t);if(r)throw r;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",t]}),se.success("Variant deleted successfully")}})}function Csr(){const s=Bt();return mt({mutationFn:async({productId:t,videoUrl:n})=>{await q.from("marketplace_product_videos").delete().eq("product_id",t);const{data:r,error:a}=await q.from("marketplace_product_videos").insert({product_id:t,video_url:n}).select().single();if(a)throw a;return r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",n.productId]}),se.success("Video updated successfully")}})}function Asr(s){const{isAdmin:t}=hs();return at({queryKey:["marketplace-orders",s,t],queryFn:async()=>{let n=q.from("marketplace_orders").select(` *, items:marketplace_order_items(*), status_history:marketplace_order_status_history(*) `).order("created_at",{ascending:!1});const{data:r,error:a}=await n;if(a)throw a;if(t&&r){const i=[...new Set(r.map(c=>c.user_id))],{data:l}=await q.from("profiles").select("id, name, email").in("id",i),o=new Map((l==null?void 0:l.map(c=>[c.id,c]))||[]);return r.map(c=>({...c,user:o.get(c.user_id)}))}return r}})}function Esr(){const{user:s}=hs();return at({queryKey:["my-marketplace-orders",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.from("marketplace_orders").select(` *, items:marketplace_order_items(*), status_history:marketplace_order_status_history(*) `).eq("user_id",s.id).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!(s!=null&&s.id)})}function Tsr(s){return at({queryKey:["marketplace-order",s],queryFn:async()=>{const{data:t,error:n}=await q.from("marketplace_orders").select(` *, items:marketplace_order_items(*), status_history:marketplace_order_status_history(*) `).eq("id",s).single();if(n)throw n;return t},enabled:!!s})}function Msr(){const s=Bt(),{user:t}=hs();return mt({mutationFn:async({orderId:n,status:r,notes:a,trackingNumber:i,trackingUrl:l,previousStatus:o})=>{const c={status:r};i!==void 0&&(c.tracking_number=i),l!==void 0&&(c.tracking_url=l);const{error:d}=await q.from("marketplace_orders").update(c).eq("id",n);if(d)throw d;const{error:u}=await q.from("marketplace_order_status_history").insert({order_id:n,status:r,notes:a,created_by:t==null?void 0:t.id});if(u)throw u;if(["shipped","in_production","processing","completed"].includes(r)&&r!==o)try{await q.functions.invoke("marketplace-order-notify",{body:{orderId:n,notificationType:r==="shipped"?"shipped":"status_update",newStatus:r,trackingNumber:i,trackingUrl:l}})}catch(m){console.error("Failed to send notification email:",m)}},onSuccess:(n,r)=>{s.invalidateQueries({queryKey:["marketplace-orders"]}),s.invalidateQueries({queryKey:["marketplace-order",r.orderId]}),s.invalidateQueries({queryKey:["my-marketplace-orders"]}),se.success("Order status updated")},onError:n=>{se.error("Failed to update order: "+n.message)}})}function Psr(){const s=Bt();return mt({mutationFn:async({itemId:t,proofUrl:n,proofNotes:r,orderId:a})=>{const{error:i}=await q.from("marketplace_order_items").update({proof_url:n,proof_notes:r,proof_status:"pending"}).eq("id",t);if(i)throw i;await q.from("marketplace_orders").update({status:"awaiting_proof_approval"}).eq("id",a);try{await q.functions.invoke("marketplace-order-notify",{body:{orderId:a,notificationType:"proof_ready"}})}catch(l){console.error("Failed to send proof notification:",l)}return a},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-orders"]}),s.invalidateQueries({queryKey:["marketplace-order",t]}),s.invalidateQueries({queryKey:["my-marketplace-orders"]}),se.success("Proof uploaded & customer notified")}})}function Lsr(){const s=Bt();return mt({mutationFn:async({itemId:t,orderId:n})=>{const{error:r}=await q.from("marketplace_order_items").update({proof_status:"approved"}).eq("id",t);if(r)throw r;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-orders"]}),s.invalidateQueries({queryKey:["marketplace-order",t]}),s.invalidateQueries({queryKey:["my-marketplace-orders"]}),se.success("Proof approved")}})}function Isr(){const s=Bt();return mt({mutationFn:async({itemId:t,orderId:n,reason:r})=>{const{error:a}=await q.from("marketplace_order_items").update({proof_status:"rejected",proof_notes:r}).eq("id",t);if(a)throw a;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-orders"]}),s.invalidateQueries({queryKey:["marketplace-order",t]}),s.invalidateQueries({queryKey:["my-marketplace-orders"]}),se.success("Proof rejected - please upload a new proof")}})}function Dsr(){const{data:s,isLoading:t}=Kat(!1),n=fsr(),r=xsr(),a=gsr(),[i,l]=_.useState(!1),[o,c]=_.useState(null),[d,u]=_.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=y=>{c(y),u({name:y.name,description:y.description||"",image_url:y.image_url||"",sort_order:y.sort_order,is_active:y.is_active}),l(!0)},p=async y=>{y.preventDefault(),o?await r.mutateAsync({id:o.id,...d}):await n.mutateAsync(d),l(!1),h()},f=async y=>{await Xi("Are you sure you want to delete this category?")&&await a.mutateAsync(y)};return t?e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(cn,{className:"h-8 w-48"})}),e.jsx(Me,{children:e.jsx("div",{className:"space-y-4",children:[1,2,3].map(y=>e.jsx(cn,{className:"h-12 w-full"},y))})})]}):e.jsxs(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between",children:[e.jsx(St,{children:"Categories"}),e.jsxs(Ls,{open:i,onOpenChange:y=>{l(y),y||h()},children:[e.jsx(nl,{asChild:!0,children:e.jsxs(B,{children:[e.jsx(rn,{className:"h-4 w-4 mr-2"}),"Add Category"]})}),e.jsxs(Ps,{children:[e.jsx(Os,{children:e.jsx(Ds,{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(J,{htmlFor:"name",children:"Name"}),e.jsx(xe,{id:"name",value:d.name,onChange:y=>u({...d,name:y.target.value}),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"description",children:"Description"}),e.jsx(Ms,{id:"description",value:d.description,onChange:y=>u({...d,description:y.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"image_url",children:"Image URL"}),e.jsx(xe,{id:"image_url",value:d.image_url,onChange:y=>u({...d,image_url:y.target.value}),placeholder:"https://..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"sort_order",children:"Sort Order"}),e.jsx(xe,{id:"sort_order",type:"number",value:d.sort_order,onChange:y=>u({...d,sort_order:parseInt(y.target.value)||0})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fn,{id:"is_active",checked:d.is_active,onCheckedChange:y=>u({...d,is_active:y})}),e.jsx(J,{htmlFor:"is_active",children:"Active"})]}),e.jsx(B,{type:"submit",className:"w-full",disabled:n.isPending||r.isPending,children:o?"Update Category":"Create Category"})]})]})]})]}),e.jsx(Me,{children:s&&s.length>0?e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"Name"}),e.jsx(Pt,{children:"Description"}),e.jsx(Pt,{children:"Sort Order"}),e.jsx(Pt,{children:"Status"}),e.jsx(Pt,{className:"text-right",children:"Actions"})]})}),e.jsx(Ka,{children:s.map(y=>e.jsxs(pn,{children:[e.jsx(gt,{className:"font-medium",children:y.name}),e.jsx(gt,{className:"max-w-xs truncate",children:y.description}),e.jsx(gt,{children:y.sort_order}),e.jsx(gt,{children:e.jsx("span",{className:`px-2 py-1 rounded-full text-xs ${y.is_active?"bg-green-100 text-green-800":"bg-gray-100 text-gray-800"}`,children:y.is_active?"Active":"Inactive"})}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>m(y),children:e.jsx(Ya,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>f(y.id),disabled:a.isPending,children:e.jsx(Sn,{className:"h-4 w-4 text-destructive"})})]})})]},y.id))})]}):e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No categories yet. Create your first category to get started."})})]})}function Rsr(){var te,ae;const{data:s,isLoading:t}=wrs(void 0,!1),{data:n}=Kat(!1),r=vsr(),a=bsr(),i=_sr(),l=wsr(),o=jsr(),c=Nsr(),d=ksr(),u=Ssr(),h=Csr(),[m,p]=_.useState(!1),[f,y]=_.useState(!1),[v,g]=_.useState(!1),[b,j]=_.useState(null),[S,C]=_.useState(null),[E,P]=_.useState(!1),[M,I]=_.useState({name:"",description:"",base_price:0,shipping_fee:0,category_id:"",allow_artwork_upload:!1,requires_proof_approval:!1,is_active:!0,sort_order:0}),[D,O]=_.useState({name:"",price_adjustment:0}),[V,G]=_.useState(""),$=()=>{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}),j(null)},H=le=>{j(le),I({name:le.name,description:le.description||"",base_price:Number(le.base_price),shipping_fee:Number(le.shipping_fee),category_id:le.category_id||"",allow_artwork_upload:le.allow_artwork_upload,requires_proof_approval:le.requires_proof_approval,is_active:le.is_active,sort_order:le.sort_order}),p(!0)},Y=async le=>{le.preventDefault();const be={...M,category_id:M.category_id||null};b?await a.mutateAsync({id:b.id,...be}):await r.mutateAsync(be),p(!1),$()},Z=async le=>{await Xi("Are you sure you want to delete this product?")&&await i.mutateAsync(le)},ne=async le=>{if(!S||!le.target.files||le.target.files.length===0)return;P(!0);const be=le.target.files[0],me=be.name.split(".").pop(),he=`products/${S.id}/${Date.now()}.${me}`;try{const{error:pe}=await q.storage.from("marketplace").upload(he,be);if(pe)throw pe;const{data:{publicUrl:Ce}}=q.storage.from("marketplace").getPublicUrl(he);await l.mutateAsync({product_id:S.id,image_url:Ce,is_primary:!S.images||S.images.length===0}),se.success("Image uploaded successfully")}catch(pe){se.error("Failed to upload image: "+pe.message)}finally{P(!1)}},ce=async le=>{le.preventDefault(),S&&(await d.mutateAsync({product_id:S.id,name:D.name,price_adjustment:D.price_adjustment}),O({name:"",price_adjustment:0}))},ie=async()=>{!S||!V||(await h.mutateAsync({productId:S.id,videoUrl:V}),G(""))};return t?e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(cn,{className:"h-8 w-48"})}),e.jsx(Me,{children:e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(le=>e.jsx(cn,{className:"h-64 w-full"},le))})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between",children:[e.jsx(St,{children:"Products"}),e.jsxs(Ls,{open:m,onOpenChange:le=>{p(le),le||$()},children:[e.jsx(nl,{asChild:!0,children:e.jsxs(B,{children:[e.jsx(rn,{className:"h-4 w-4 mr-2"}),"Add Product"]})}),e.jsxs(Ps,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Ds,{children:b?"Edit Product":"Add Product"})}),e.jsxs("form",{onSubmit:Y,className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"name",children:"Product Name"}),e.jsx(xe,{id:"name",value:M.name,onChange:le=>I({...M,name:le.target.value}),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"category",children:"Category"}),e.jsxs(is,{value:M.category_id,onValueChange:le=>I({...M,category_id:le}),children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Select category"})}),e.jsx(as,{children:n==null?void 0:n.map(le=>e.jsx(He,{value:le.id,children:le.name},le.id))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"description",children:"Description"}),e.jsx(Ms,{id:"description",value:M.description,onChange:le=>I({...M,description:le.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(J,{htmlFor:"base_price",children:"Base Price ($)"}),e.jsx(xe,{id:"base_price",type:"number",step:"0.01",min:"0",value:M.base_price,onChange:le=>I({...M,base_price:parseFloat(le.target.value)||0}),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"shipping_fee",children:"Shipping Fee ($)"}),e.jsx(xe,{id:"shipping_fee",type:"number",step:"0.01",min:"0",value:M.shipping_fee,onChange:le=>I({...M,shipping_fee:parseFloat(le.target.value)||0})})]})]}),e.jsx("div",{className:"grid grid-cols-2 gap-4",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"sort_order",children:"Sort Order"}),e.jsx(xe,{id:"sort_order",type:"number",value:M.sort_order,onChange:le=>I({...M,sort_order:parseInt(le.target.value)||0})})]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fn,{id:"allow_artwork_upload",checked:M.allow_artwork_upload,onCheckedChange:le=>I({...M,allow_artwork_upload:le})}),e.jsx(J,{htmlFor:"allow_artwork_upload",children:"Allow customer to upload artwork"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fn,{id:"requires_proof_approval",checked:M.requires_proof_approval,onCheckedChange:le=>I({...M,requires_proof_approval:le})}),e.jsx(J,{htmlFor:"requires_proof_approval",children:"Requires proof approval"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fn,{id:"is_active",checked:M.is_active,onCheckedChange:le=>I({...M,is_active:le})}),e.jsx(J,{htmlFor:"is_active",children:"Active"})]})]}),e.jsx(B,{type:"submit",className:"w-full",disabled:r.isPending||a.isPending,children:b?"Update Product":"Create Product"})]})]})]})]}),e.jsx(Me,{children:s&&s.length>0?e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:s.map(le=>{var be,me;return e.jsxs(ve,{className:"overflow-hidden",children:[e.jsxs("div",{className:"aspect-video bg-muted relative",children:[le.images&&le.images.length>0?e.jsx("img",{src:((be=le.images.find(he=>he.is_primary))==null?void 0:be.image_url)||le.images[0].image_url,alt:le.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"}),!le.is_active&&e.jsx(Oe,{variant:"secondary",className:"absolute top-2 right-2",children:"Inactive"})]}),e.jsxs(Me,{className:"p-4",children:[e.jsx("h3",{className:"font-semibold mb-1",children:le.name}),e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:((me=le.category)==null?void 0:me.name)||"No category"}),e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("span",{className:"font-bold",children:["$",Number(le.base_price).toFixed(2)]}),Number(le.shipping_fee)>0&&e.jsxs("span",{className:"text-sm text-muted-foreground",children:["+$",Number(le.shipping_fee).toFixed(2)," shipping"]})]}),e.jsxs("div",{className:"flex flex-wrap gap-1 mb-3",children:[le.allow_artwork_upload&&e.jsx(Oe,{variant:"outline",className:"text-xs",children:"Artwork Upload"}),le.requires_proof_approval&&e.jsx(Oe,{variant:"outline",className:"text-xs",children:"Proof Required"}),le.variants&&le.variants.length>0&&e.jsxs(Oe,{variant:"outline",className:"text-xs",children:[le.variants.length," Variants"]})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>H(le),children:[e.jsx(Ya,{className:"h-3 w-3 mr-1"}),"Edit"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>{C(le),y(!0)},children:[e.jsx(jy,{className:"h-3 w-3 mr-1"}),"Images"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>{C(le),g(!0)},children:[e.jsx(Ep,{className:"h-3 w-3 mr-1"}),"Variants"]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>Z(le.id),children:e.jsx(Sn,{className:"h-3 w-3 text-destructive"})})]})]})]},le.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(Ls,{open:f,onOpenChange:y,children:e.jsxs(Ps,{className:"max-w-2xl",children:[e.jsx(Os,{children:e.jsxs(Ds,{children:["Manage Images - ",S==null?void 0:S.name]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-3 gap-4",children:(te=S==null?void 0:S.images)==null?void 0:te.map(le=>e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:le.image_url,alt:"",className:"w-full aspect-square object-cover rounded-lg"}),le.is_primary&&e.jsx(Oe,{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:[!le.is_primary&&e.jsx(B,{variant:"secondary",size:"icon",onClick:async()=>{var be;await c.mutateAsync({imageId:le.id,productId:S.id}),C({...S,images:(be=S.images)==null?void 0:be.map(me=>({...me,is_primary:me.id===le.id}))})},disabled:c.isPending,title:"Set as primary",children:e.jsx(Da,{className:"h-4 w-4"})}),e.jsx(B,{variant:"destructive",size:"icon",onClick:async()=>{var me;await o.mutateAsync({id:le.id,productId:S.id});const be=s==null?void 0:s.find(he=>he.id===S.id);be&&C({...be,images:(me=be.images)==null?void 0:me.filter(he=>he.id!==le.id)})},disabled:o.isPending,children:e.jsx(Sn,{className:"h-4 w-4"})})]})]},le.id))}),e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-6 text-center",children:[e.jsx("input",{type:"file",accept:"image/*",onChange:ne,className:"hidden",id:"image-upload",disabled:E}),e.jsxs("label",{htmlFor:"image-upload",className:"cursor-pointer",children:[e.jsx(jy,{className:"h-8 w-8 mx-auto mb-2 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:E?"Uploading...":"Click to upload an image"})]})]}),e.jsxs("div",{className:"border-t pt-4 mt-4",children:[e.jsx(J,{children:"Product Video (optional)"}),e.jsxs("div",{className:"flex gap-2 mt-2",children:[e.jsx(xe,{placeholder:"Enter video URL (YouTube, Vimeo, etc.)",value:V,onChange:le=>G(le.target.value)}),e.jsxs(B,{onClick:ie,disabled:!V,children:[e.jsx(Kr,{className:"h-4 w-4 mr-2"}),"Set Video"]})]}),(S==null?void 0:S.video)&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-2",children:["Current video: ",S.video.video_url]})]})]})]})}),e.jsx(Ls,{open:v,onOpenChange:g,children:e.jsxs(Ps,{children:[e.jsx(Os,{children:e.jsxs(Ds,{children:["Manage Variants - ",S==null?void 0:S.name]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("form",{onSubmit:ce,className:"flex gap-2",children:[e.jsx(xe,{placeholder:"Variant name (e.g., 500 count)",value:D.name,onChange:le=>O({...D,name:le.target.value}),required:!0}),e.jsx(xe,{type:"number",step:"0.01",placeholder:"Price adj.",value:D.price_adjustment,onChange:le=>O({...D,price_adjustment:parseFloat(le.target.value)||0}),className:"w-32"}),e.jsx(B,{type:"submit",children:"Add"})]}),e.jsxs("div",{className:"space-y-2",children:[(ae=S==null?void 0:S.variants)==null?void 0:ae.map(le=>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:le.name}),e.jsxs("span",{className:"text-sm text-muted-foreground ml-2",children:[Number(le.price_adjustment)>=0?"+":"","$",Number(le.price_adjustment).toFixed(2)]})]}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>u.mutateAsync({id:le.id,productId:S.id}),children:e.jsx(Sn,{className:"h-4 w-4 text-destructive"})})]},le.id)),(!(S!=null&&S.variants)||S.variants.length===0)&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:'No variants yet. Add variants like "250 count", "500 count", etc.'})]})]})]})})]})}const Fsr=["pending_payment","order_submitted","awaiting_proof_approval","proof_approved","processing","in_production","shipped","completed","cancelled","refunded"];function Osr(){var y,v,g;const{data:s,isLoading:t}=Asr(),n=Msr(),r=Psr(),[a,i]=_.useState(null),[l,o]=_.useState(!1),[c,d]=_.useState({status:"",notes:"",trackingNumber:"",trackingUrl:""}),[u,h]=_.useState(!1),m=b=>{i(b),d({status:b.status,notes:"",trackingNumber:b.tracking_number||"",trackingUrl:b.tracking_url||""}),o(!0)},p=async()=>{a&&(await n.mutateAsync({orderId:a.id,status:c.status,notes:c.notes,trackingNumber:c.trackingNumber,trackingUrl:c.trackingUrl,previousStatus:a.status}),o(!1))},f=async(b,j)=>{if(!a||!b.target.files||b.target.files.length===0)return;h(!0);const S=b.target.files[0],C=S.name.split(".").pop(),E=`proofs/${a.id}/${j}/${Date.now()}.${C}`;try{const{error:P}=await q.storage.from("marketplace").upload(E,S);if(P)throw P;const{data:{publicUrl:M}}=q.storage.from("marketplace").getPublicUrl(E);await r.mutateAsync({itemId:j,proofUrl:M,orderId:a.id}),se.success("Proof uploaded successfully")}catch(P){se.error("Failed to upload proof: "+P.message)}finally{h(!1)}};return t?e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(cn,{className:"h-8 w-48"})}),e.jsx(Me,{children:e.jsx("div",{className:"space-y-4",children:[1,2,3].map(b=>e.jsx(cn,{className:"h-16 w-full"},b))})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{children:"Orders"})}),e.jsx(Me,{children:s&&s.length>0?e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"Order #"}),e.jsx(Pt,{children:"Customer"}),e.jsx(Pt,{children:"Date"}),e.jsx(Pt,{children:"Total"}),e.jsx(Pt,{children:"Status"}),e.jsx(Pt,{className:"text-right",children:"Actions"})]})}),e.jsx(Ka,{children:s.map(b=>{var j,S;return e.jsxs(pn,{children:[e.jsx(gt,{className:"font-mono",children:b.order_number}),e.jsx(gt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((j=b.user)==null?void 0:j.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(S=b.user)==null?void 0:S.email})]})}),e.jsx(gt,{children:Hs(new Date(b.created_at),"MMM d, yyyy")}),e.jsxs(gt,{className:"font-bold",children:["$",Number(b.total).toFixed(2)]}),e.jsx(gt,{children:e.jsx(Oe,{className:Wat[b.status],children:Z$[b.status]})}),e.jsx(gt,{className:"text-right",children:e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>m(b),children:[e.jsx(ya,{className:"h-4 w-4 mr-1"}),"View"]})})]},b.id)})})]}):e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No orders yet."})})]}),e.jsx(Ls,{open:l,onOpenChange:o,children:e.jsxs(Ps,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsxs(Ds,{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:(y=a.user)==null?void 0:y.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(v=a.user)==null?void 0:v.email})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-2",children:"Shipping Address"}),e.jsx("p",{children:a.shipping_name}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[a.shipping_address,e.jsx("br",{}),a.shipping_city,", ",a.shipping_state," ",a.shipping_zip]})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-2",children:"Order Items"}),e.jsx("div",{className:"space-y-3",children:(g=a.items)==null?void 0:g.map(b=>e.jsxs("div",{className:"border rounded-lg p-4",children:[e.jsxs("div",{className:"flex justify-between items-start mb-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:b.product_name}),b.variant_name&&e.jsx("p",{className:"text-sm text-muted-foreground",children:b.variant_name})]}),e.jsxs("p",{className:"font-bold",children:["$",Number(b.unit_price).toFixed(2)," x ",b.quantity]})]}),b.artwork_url&&e.jsxs("div",{className:"mt-2",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-1",children:"Customer Artwork:"}),e.jsx("a",{href:b.artwork_url,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline text-sm",children:"View Artwork"})]}),e.jsx("div",{className:"mt-3 pt-3 border-t",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Proof Status: "}),e.jsx(Oe,{variant:b.proof_status==="approved"?"default":"secondary",children:b.proof_status||"No proof yet"})]}),b.proof_url?e.jsx("a",{href:b.proof_url,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline text-sm",children:"View Proof"}):e.jsxs("div",{children:[e.jsx("input",{type:"file",accept:"image/*,.pdf",onChange:j=>f(j,b.id),className:"hidden",id:`proof-${b.id}`,disabled:u}),e.jsx("label",{htmlFor:`proof-${b.id}`,children:e.jsx(B,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("span",{children:[e.jsx(Oa,{className:"h-4 w-4 mr-1"}),u?"Uploading...":"Upload Proof"]})})})]})]})})]},b.id))})]}),e.jsxs("div",{className:"border-t pt-4",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{children:"Subtotal"}),e.jsxs("span",{children:["$",Number(a.subtotal).toFixed(2)]})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{children:"Shipping"}),e.jsxs("span",{children:["$",Number(a.shipping_total).toFixed(2)]})]}),e.jsxs("div",{className:"flex justify-between font-bold text-lg mt-2",children:[e.jsx("span",{children:"Total"}),e.jsxs("span",{children:["$",Number(a.total).toFixed(2)]})]})]}),e.jsxs("div",{className:"border-t pt-4",children:[e.jsx("h4",{className:"font-medium mb-3",children:"Update Order Status"}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Status"}),e.jsxs(is,{value:c.status,onValueChange:b=>d({...c,status:b}),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsx(as,{children:Fsr.map(b=>e.jsx(He,{value:b,children:Z$[b]},b))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Tracking Number"}),e.jsx(xe,{value:c.trackingNumber,onChange:b=>d({...c,trackingNumber:b.target.value}),placeholder:"Enter tracking number"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Tracking URL"}),e.jsx(xe,{value:c.trackingUrl,onChange:b=>d({...c,trackingUrl:b.target.value}),placeholder:"https://..."})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Notes (optional)"}),e.jsx(Ms,{value:c.notes,onChange:b=>d({...c,notes:b.target.value}),placeholder:"Add a note about this status change..."})]}),e.jsxs(B,{onClick:p,disabled:n.isPending,className:"w-full",children:[e.jsx(Nh,{className:"h-4 w-4 mr-2"}),"Update Status"]})]})]}),a.status_history&&a.status_history.length>0&&e.jsxs("div",{className:"border-t pt-4",children:[e.jsx("h4",{className:"font-medium mb-3",children:"Status History"}),e.jsx("div",{className:"space-y-2",children:a.status_history.map(b=>e.jsxs("div",{className:"flex justify-between text-sm p-2 bg-muted rounded",children:[e.jsxs("div",{children:[e.jsx(Oe,{variant:"outline",children:Z$[b.status]}),b.notes&&e.jsx("p",{className:"text-muted-foreground mt-1",children:b.notes})]}),e.jsx("span",{className:"text-muted-foreground",children:Hs(new Date(b.created_at),"MMM d, h:mm a")})]},b.id))})]})]})]})})]})}function zsr(){const[s,t]=_.useState("products"),n=Fn();return e.jsx(zs,{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(B,{variant:"outline",onClick:()=>n("/marketplace"),children:[e.jsx(wr,{className:"h-4 w-4 mr-2"}),"View Store"]})]}),e.jsxs(Yr,{value:s,onValueChange:t,children:[e.jsxs(Zr,{className:"grid w-full grid-cols-3",children:[e.jsxs(Ht,{value:"products",className:"flex items-center gap-2",children:[e.jsx(Nh,{className:"h-4 w-4"}),"Products"]}),e.jsxs(Ht,{value:"categories",className:"flex items-center gap-2",children:[e.jsx(wy,{className:"h-4 w-4"}),"Categories"]}),e.jsxs(Ht,{value:"orders",className:"flex items-center gap-2",children:[e.jsx(xS,{className:"h-4 w-4"}),"Orders"]})]}),e.jsx(Gt,{value:"products",children:e.jsx(Rsr,{})}),e.jsx(Gt,{value:"categories",children:e.jsx(Dsr,{})}),e.jsx(Gt,{value:"orders",children:e.jsx(Osr,{})})]})]})})}function jrs(){return at({queryKey:["reward-categories"],queryFn:async()=>{const{data:s,error:t}=await q.from("reward_store_categories").select("*").order("sort_order",{ascending:!0});if(t)throw t;return s}})}function Bsr(s){return at({queryKey:["reward-items",s],queryFn:async()=>{let t=q.from("reward_store_items").select(` *, category:reward_store_categories(*) `).order("created_at",{ascending:!1});const{data:n,error:r}=await t;if(r)throw r;return n}})}function Usr(s){return at({queryKey:["active-reward-items",s],queryFn:async()=>{let t=q.from("reward_store_items").select(` *, category:reward_store_categories(*) `).eq("is_active",!0).order("created_at",{ascending:!1});s&&(t=t.eq("category_id",s));const{data:n,error:r}=await t;if(r)throw r;return n}})}function qsr(s){return at({queryKey:["user-purchases",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("reward_store_purchases").select(` *, item:reward_store_items(*) `).eq("user_id",s).order("purchased_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function $sr(){return at({queryKey:["all-reward-purchases"],queryFn:async()=>{const{data:s,error:t}=await q.from("reward_store_purchases").select(` *, item:reward_store_items(*) `).order("purchased_at",{ascending:!1});if(t)throw t;if(!s||s.length===0)return[];const n=[...new Set(s.map(l=>l.user_id))],{data:r,error:a}=await q.from("profiles").select("id, name, email").in("id",n);if(a)throw a;const i=new Map((r==null?void 0:r.map(l=>[l.id,l]))||[]);return s.map(l=>({...l,user:i.get(l.user_id)||null}))}})}function Vsr(s){return at({queryKey:["spendable-points",s],queryFn:async()=>{if(!s)return 0;const{data:t,error:n}=await q.from("agent_attendance_stats").select("spendable_points").eq("user_id",s).single();if(n&&n.code!=="PGRST116")throw n;return(t==null?void 0:t.spendable_points)||0},enabled:!!s})}function Hsr(){const s=Bt();return mt({mutationFn:async t=>{const{data:n,error:r}=await q.rpc("purchase_reward_item",{p_item_id:t});if(r)throw r;const a=n;if(!a.success)throw new Error(a.error||"Purchase failed");return a},onSuccess:()=>{s.invalidateQueries({queryKey:["user-purchases"]}),s.invalidateQueries({queryKey:["spendable-points"]}),s.invalidateQueries({queryKey:["active-reward-items"]}),s.invalidateQueries({queryKey:["reward-items"]}),s.invalidateQueries({queryKey:["homereel-credits"]})}})}function Gsr(){const s=Bt();return mt({mutationFn:async t=>{const{data:n,error:r}=await q.from("reward_store_categories").insert([t]).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-categories"]})}})}function Wsr(){const s=Bt();return mt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("reward_store_categories").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-categories"]})}})}function Ksr(){const s=Bt();return mt({mutationFn:async t=>{const{error:n}=await q.from("reward_store_categories").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-categories"]})}})}function Ysr(){const s=Bt();return mt({mutationFn:async t=>{const{data:n,error:r}=await q.from("reward_store_items").insert([t]).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-items"]}),s.invalidateQueries({queryKey:["active-reward-items"]})}})}function Zsr(){const s=Bt();return mt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("reward_store_items").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-items"]}),s.invalidateQueries({queryKey:["active-reward-items"]})}})}function Xsr(){const s=Bt();return mt({mutationFn:async t=>{const{error:n}=await q.from("reward_store_items").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-items"]}),s.invalidateQueries({queryKey:["active-reward-items"]})}})}function Qsr(s){const t=s.match(/\/storage\/v1\/object\/public\/([^/]+)\/(.+)$/);return t?{bucket:t[1],path:t[2]}:null}async function ABe(s,t){const n=Qsr(s);if(n)try{const{data:r,error:a}=await q.storage.from(n.bucket).download(n.path);if(a){console.error("Error downloading file:",a),se.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),se.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),se.error("Failed to download file")}}function Nrs(){return at({queryKey:["point-reward-settings"],queryFn:async()=>{const{data:s,error:t}=await q.from("point_reward_settings").select("*").order("action_name");if(t)throw t;return s}})}function Jsr(){const s=Bt();return mt({mutationFn:async({id:t,points:n,is_active:r})=>{const a={points:n};r!==void 0&&(a.is_active=r);const{data:i,error:l}=await q.from("point_reward_settings").update(a).eq("id",t).select().single();if(l)throw l;return i},onSuccess:()=>{s.invalidateQueries({queryKey:["point-reward-settings"]})}})}function enr(){const{user:s}=hs(),[t,n]=_.useState("items"),[r,a]=_.useState(!1),[i,l]=_.useState(null),[o,c]=_.useState(""),[d,u]=_.useState(""),[h,m]=_.useState(""),[p,f]=_.useState(null),[y,v]=_.useState(!1),[g,b]=_.useState(null),[j,S]=_.useState(""),[C,E]=_.useState(""),[P,M]=_.useState(null),[I,D]=_.useState(""),[O,V]=_.useState("file"),[G,$]=_.useState(""),[H,Y]=_.useState(""),[Z,ne]=_.useState(""),[ce,ie]=_.useState(!0),[te,ae]=_.useState(null),[le,be]=_.useState(!1),[me,he]=_.useState(!1),pe=_.useRef(null),Ce=_.useRef(null),{data:Ae,isLoading:Pe}=jrs(),{data:ze,isLoading:ke}=Bsr(),{data:Ze,isLoading:Se}=$sr(),{data:Fe,isLoading:Ne}=Nrs(),Ye=Gsr(),Ve=Wsr(),qe=Ksr(),Qe=Ysr(),Ue=Zsr(),Xe=Xsr(),nt=Jsr(),[$e,Ge]=_.useState({}),ct=vt=>{vt?(l(vt),c(vt.name),u(vt.description||""),m(vt.icon||"")):(l(null),c(""),u(""),m("")),a(!0)},xt=async()=>{if(!o.trim()){se.error("Please enter a category name");return}try{i?(await Ve.mutateAsync({id:i.id,name:o,description:d||null,icon:h||null}),se.success("Category updated successfully")):(await Ye.mutateAsync({name:o,description:d||null,icon:h||null,sort_order:((Ae==null?void 0:Ae.length)||0)+1}),se.success("Category created successfully")),a(!1)}catch(vt){console.error("Error saving category:",vt),se.error("Failed to save category")}},qt=async()=>{if(p)try{await qe.mutateAsync(p),se.success("Category deleted successfully"),f(null)}catch(vt){console.error("Error deleting category:",vt),se.error("Failed to delete category")}},Vt=vt=>{var $s;vt?(b(vt),S(vt.name),E(vt.description||""),M(vt.category_id),D(vt.points_cost.toString()),V(vt.item_type),$(vt.file_url||""),Y(vt.preview_image_url||""),ne((($s=vt.max_quantity)==null?void 0:$s.toString())||""),ie(vt.is_active)):(b(null),S(""),E(""),M(null),D(""),V("file"),$(""),Y(""),ne(""),ie(!0)),v(!0)},Xt=async(vt,$s)=>{$s==="file"?be(!0):he(!0);try{const As=vt.name.split(".").pop(),jn=`${Date.now()}-${Math.random().toString(36).substring(7)}.${As}`,ar=`${$s==="file"?"items":"previews"}/${jn}`,{error:Dn}=await q.storage.from("reward-store").upload(ar,vt);if(Dn)throw Dn;const{data:{publicUrl:Ur}}=q.storage.from("reward-store").getPublicUrl(ar);$s==="file"?$(Ur):Y(Ur),se.success("File uploaded successfully")}catch(As){console.error("Error uploading file:",As),se.error("Failed to upload file")}finally{$s==="file"?be(!1):he(!1)}},fs=async()=>{if(!j.trim()){se.error("Please enter an item name");return}if(!I||parseInt(I)<0){se.error("Please enter a valid points cost");return}try{const vt={name:j,description:C||null,category_id:P,points_cost:parseInt(I),item_type:O,file_url:G||null,preview_image_url:H||null,max_quantity:Z?parseInt(Z):null,current_quantity:Z?parseInt(Z):null,is_active:ce,created_by:s==null?void 0:s.id};g?(await Ue.mutateAsync({id:g.id,...vt,current_quantity:g.max_quantity!==(Z?parseInt(Z):null)?Z?parseInt(Z):null:g.current_quantity}),se.success("Item updated successfully")):(await Qe.mutateAsync(vt),se.success("Item created successfully")),v(!1)}catch(vt){console.error("Error saving item:",vt),se.error("Failed to save item")}},Ft=async()=>{if(te)try{await Xe.mutateAsync(te),se.success("Item deleted successfully"),ae(null)}catch(vt){console.error("Error deleting item:",vt),se.error("Failed to delete item")}},wt=async(vt,$s)=>{const As=$e[vt];if(As===void 0||As===$s.toString())return;const jn=parseInt(As);if(isNaN(jn)||jn<0){se.error("Please enter a valid positive number");return}try{await nt.mutateAsync({id:vt,points:jn}),se.success("Points updated successfully"),Ge(ar=>{const Dn={...ar};return delete Dn[vt],Dn})}catch(ar){console.error("Error updating points:",ar),se.error("Failed to update points")}};return Pe||ke||Se||Ne?e.jsx(zs,{title:"Reward Store",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(cn,{className:"h-8 w-64"}),e.jsx(cn,{className:"h-96"})]})}):e.jsxs(zs,{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(ve,{children:e.jsxs(Me,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Nh,{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(vt=>vt.is_active).length)||0," active"]})]})}),e.jsx(ve,{children:e.jsxs(Me,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(wy,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Categories"})]}),e.jsx("p",{className:"text-2xl font-bold",children:(Ae==null?void 0:Ae.length)||0})]})}),e.jsx(ve,{children:e.jsxs(Me,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Da,{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((vt,$s)=>vt+$s.points_cost,0)/ze.length):0," pts"]})]})})]}),e.jsxs(Yr,{value:t,onValueChange:n,children:[e.jsxs(Zr,{children:[e.jsx(Ht,{value:"items",children:"Items"}),e.jsx(Ht,{value:"categories",children:"Categories"}),e.jsx(Ht,{value:"purchases",children:"Purchases"}),e.jsx(Ht,{value:"point-settings",children:"Point Settings"})]}),e.jsx(Gt,{value:"items",className:"mt-4",children:e.jsxs(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(St,{children:"Store Items"}),e.jsx(kn,{children:"Manage rewards that agents can purchase"})]}),e.jsxs(B,{onClick:()=>Vt(),children:[e.jsx(rn,{className:"h-4 w-4 mr-2"}),"Add Item"]})]}),e.jsx(Me,{children:!ze||ze.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Vo,{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(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"Item"}),e.jsx(Pt,{children:"Category"}),e.jsx(Pt,{className:"text-center",children:"Cost"}),e.jsx(Pt,{className:"text-center",children:"Type"}),e.jsx(Pt,{className:"text-center",children:"Quantity"}),e.jsx(Pt,{className:"text-center",children:"Status"}),e.jsx(Pt,{className:"text-right",children:"Actions"})]})}),e.jsx(Ka,{children:ze.map(vt=>e.jsxs(pn,{children:[e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[vt.preview_image_url?e.jsx("img",{src:vt.preview_image_url,alt:vt.name,className:"h-10 w-10 rounded object-cover"}):e.jsx("div",{className:"h-10 w-10 rounded bg-muted flex items-center justify-center",children:e.jsx(Vo,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:vt.name}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1",children:vt.description||"No description"})]})]})}),e.jsx(gt,{children:vt.category?e.jsx(Oe,{variant:"outline",children:vt.category.name}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(gt,{className:"text-center",children:e.jsxs(Oe,{variant:"secondary",className:"font-bold",children:[e.jsx(Da,{className:"h-3 w-3 mr-1"}),vt.points_cost]})}),e.jsx(gt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[vt.item_type==="file"?e.jsx(Fr,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Vc,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-xs capitalize",children:vt.item_type})]})}),e.jsx(gt,{className:"text-center",children:vt.max_quantity!==null?e.jsxs("span",{className:vt.current_quantity===0?"text-red-500":"",children:[vt.current_quantity,"/",vt.max_quantity]}):e.jsx("span",{className:"text-muted-foreground",children:"Unlimited"})}),e.jsx(gt,{className:"text-center",children:e.jsx(Oe,{variant:vt.is_active?"default":"secondary",children:vt.is_active?"Active":"Inactive"})}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>Vt(vt),children:e.jsx(Ya,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>ae(vt.id),children:e.jsx(Sn,{className:"h-4 w-4 text-destructive"})})]})})]},vt.id))})]})})]})}),e.jsx(Gt,{value:"categories",className:"mt-4",children:e.jsxs(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(St,{children:"Categories"}),e.jsx(kn,{children:"Organize your store items into categories"})]}),e.jsxs(B,{onClick:()=>ct(),children:[e.jsx(rn,{className:"h-4 w-4 mr-2"}),"Add Category"]})]}),e.jsx(Me,{children:!Ae||Ae.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(wy,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No categories yet. Add your first category!"})]}):e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"Name"}),e.jsx(Pt,{children:"Description"}),e.jsx(Pt,{className:"text-center",children:"Items"}),e.jsx(Pt,{className:"text-right",children:"Actions"})]})}),e.jsx(Ka,{children:Ae.map(vt=>e.jsxs(pn,{children:[e.jsxs(gt,{className:"font-medium",children:[vt.icon&&e.jsx("span",{className:"mr-2",children:vt.icon}),vt.name]}),e.jsx(gt,{className:"text-muted-foreground",children:vt.description||"—"}),e.jsx(gt,{className:"text-center",children:(ze==null?void 0:ze.filter($s=>$s.category_id===vt.id).length)||0}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>ct(vt),children:e.jsx(Ya,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>f(vt.id),children:e.jsx(Sn,{className:"h-4 w-4 text-destructive"})})]})})]},vt.id))})]})})]})}),e.jsx(Gt,{value:"purchases",className:"mt-4",children:e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(xS,{className:"h-5 w-5"}),"Purchase History"]}),e.jsx(kn,{children:"View all reward redemptions by agents"})]}),e.jsx(Me,{children:!Ze||Ze.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(xS,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No purchases yet."})]}):e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"Date"}),e.jsx(Pt,{children:"Agent"}),e.jsx(Pt,{children:"Item"}),e.jsx(Pt,{className:"text-center",children:"Points Spent"})]})}),e.jsx(Ka,{children:Ze.map(vt=>{var $s,As,jn,ar;return e.jsxs(pn,{children:[e.jsx(gt,{className:"text-muted-foreground",children:Hs(new Date(vt.purchased_at),"MMM d, yyyy 'at' h:mm a")}),e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-8 w-8 rounded-full bg-muted flex items-center justify-center",children:e.jsx(Fo,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:(($s=vt.user)==null?void 0:$s.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:((As=vt.user)==null?void 0:As.email)||"—"})]})]})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[(jn=vt.item)!=null&&jn.preview_image_url?e.jsx("img",{src:vt.item.preview_image_url,alt:vt.item.name,className:"h-8 w-8 rounded object-cover"}):e.jsx("div",{className:"h-8 w-8 rounded bg-muted flex items-center justify-center",children:e.jsx(Vo,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{children:((ar=vt.item)==null?void 0:ar.name)||"Deleted item"})]})}),e.jsx(gt,{className:"text-center",children:e.jsxs(Oe,{variant:"secondary",className:"font-bold",children:[e.jsx(Da,{className:"h-3 w-3 mr-1"}),vt.points_spent]})})]},vt.id)})})]})})]})})]})]}),e.jsx(Ls,{open:r,onOpenChange:a,children:e.jsxs(Ps,{children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:i?"Edit Category":"Add Category"}),e.jsx(_r,{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(J,{htmlFor:"categoryName",children:"Name"}),e.jsx(xe,{id:"categoryName",value:o,onChange:vt=>c(vt.target.value),placeholder:"e.g., Templates, Resources"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"categoryDescription",children:"Description"}),e.jsx(Ms,{id:"categoryDescription",value:d,onChange:vt=>u(vt.target.value),placeholder:"Optional description..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"categoryIcon",children:"Icon (emoji)"}),e.jsx(xe,{id:"categoryIcon",value:h,onChange:vt=>m(vt.target.value),placeholder:"e.g., 📄, 🎁"})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(B,{onClick:xt,disabled:Ye.isPending||Ve.isPending,children:Ye.isPending||Ve.isPending?"Saving...":"Save"})]})]})}),e.jsx(Ls,{open:y,onOpenChange:v,children:e.jsxs(Ps,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:g?"Edit Item":"Add Item"}),e.jsx(_r,{children:g?"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(J,{htmlFor:"itemName",children:"Name *"}),e.jsx(xe,{id:"itemName",value:j,onChange:vt=>S(vt.target.value),placeholder:"e.g., Premium Template Pack"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"itemDescription",children:"Description"}),e.jsx(Ms,{id:"itemDescription",value:C,onChange:vt=>E(vt.target.value),placeholder:"Describe the item..."})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"itemCategory",children:"Category"}),e.jsxs(is,{value:P||"none",onValueChange:vt=>M(vt==="none"?null:vt),children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Select category"})}),e.jsxs(as,{children:[e.jsx(He,{value:"none",children:"No category"}),Ae==null?void 0:Ae.map(vt=>e.jsxs(He,{value:vt.id,children:[vt.icon&&`${vt.icon} `,vt.name]},vt.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"itemPointsCost",children:"Points Cost *"}),e.jsx(xe,{id:"itemPointsCost",type:"number",min:"0",value:I,onChange:vt=>D(vt.target.value),placeholder:"e.g., 100"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"itemType",children:"Type"}),e.jsxs(is,{value:O,onValueChange:V,children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"file",children:"File Download"}),e.jsx(He,{value:"link",children:"External Link"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"itemMaxQuantity",children:"Max Quantity"}),e.jsx(xe,{id:"itemMaxQuantity",type:"number",min:"1",value:Z,onChange:vt=>ne(vt.target.value),placeholder:"Leave empty for unlimited"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"File / Link URL"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{value:G,onChange:vt=>$(vt.target.value),placeholder:O==="file"?"Upload a file or paste URL":"Paste external link"}),O==="file"&&e.jsxs(e.Fragment,{children:[e.jsx(B,{type:"button",variant:"outline",size:"icon",onClick:()=>{var vt;return(vt=pe.current)==null?void 0:vt.click()},disabled:le,children:e.jsx(Oa,{className:"h-4 w-4"})}),e.jsx("input",{ref:pe,type:"file",className:"hidden",onChange:vt=>{var As;const $s=(As=vt.target.files)==null?void 0:As[0];$s&&Xt($s,"file")}})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Preview Image"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{value:H,onChange:vt=>Y(vt.target.value),placeholder:"Upload an image or paste URL"}),e.jsx(B,{type:"button",variant:"outline",size:"icon",onClick:()=>{var vt;return(vt=Ce.current)==null?void 0:vt.click()},disabled:me,children:e.jsx(hc,{className:"h-4 w-4"})}),e.jsx("input",{ref:Ce,type:"file",accept:"image/*",className:"hidden",onChange:vt=>{var As;const $s=(As=vt.target.files)==null?void 0:As[0];$s&&Xt($s,"preview")}})]}),H&&e.jsx("img",{src:H,alt:"Preview",className:"mt-2 h-24 rounded object-cover"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fn,{id:"itemIsActive",checked:ce,onCheckedChange:ie}),e.jsx(J,{htmlFor:"itemIsActive",children:"Active (visible to agents)"})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>v(!1),children:"Cancel"}),e.jsx(B,{onClick:fs,disabled:Qe.isPending||Ue.isPending,children:Qe.isPending||Ue.isPending?"Saving...":"Save"})]})]})}),e.jsx(Kl,{open:!!p,onOpenChange:()=>f(null),children:e.jsxs(Ol,{children:[e.jsxs(zl,{children:[e.jsx(Ul,{children:"Delete Category"}),e.jsx(ql,{children:"Are you sure you want to delete this category? Items in this category will become uncategorized."})]}),e.jsxs(Bl,{children:[e.jsx($l,{children:"Cancel"}),e.jsx(Ml,{onClick:qt,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})}),e.jsx(Kl,{open:!!te,onOpenChange:()=>ae(null),children:e.jsxs(Ol,{children:[e.jsxs(zl,{children:[e.jsx(Ul,{children:"Delete Item"}),e.jsx(ql,{children:"Are you sure you want to delete this item? This action cannot be undone."})]}),e.jsxs(Bl,{children:[e.jsx($l,{children:"Cancel"}),e.jsx(Ml,{onClick:Ft,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})}),t==="point-settings"&&e.jsxs(ve,{className:"mt-4",children:[e.jsx(bt,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qc,{className:"h-5 w-5"}),e.jsxs("div",{children:[e.jsx(St,{children:"Point Reward Settings"}),e.jsx(kn,{children:"Configure how many points agents earn for various actions. Adjust these values to run double-points promotions."})]})]})}),e.jsx(Me,{children:!Fe||Fe.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(qc,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No point settings configured."})]}):e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"Action"}),e.jsx(Pt,{children:"Description"}),e.jsx(Pt,{className:"text-center w-32",children:"Points"}),e.jsx(Pt,{className:"text-right w-24",children:"Save"})]})}),e.jsx(Ka,{children:Fe.map(vt=>e.jsxs(pn,{children:[e.jsx(gt,{children:e.jsx("p",{className:"font-medium",children:vt.action_name})}),e.jsx(gt,{children:e.jsx("p",{className:"text-sm text-muted-foreground",children:vt.description})}),e.jsx(gt,{className:"text-center",children:e.jsx(xe,{type:"number",min:"0",className:"w-20 mx-auto text-center",value:$e[vt.id]??vt.points.toString(),onChange:$s=>Ge(As=>({...As,[vt.id]:$s.target.value}))})}),e.jsx(gt,{className:"text-right",children:e.jsx(B,{size:"sm",variant:"outline",disabled:$e[vt.id]===void 0||$e[vt.id]===vt.points.toString()||nt.isPending,onClick:()=>wt(vt.id,vt.points),children:e.jsx(Ho,{className:"h-4 w-4"})})})]},vt.id))})]})})]})]})}const x4t=()=>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"})]}),g4t=[{value:"template",label:"Templates"},{value:"brand",label:"Brand Assets"},{value:"listing",label:"Listing Assets"},{value:"social",label:"Social Media"},{value:"general",label:"General"}];function tnr(){const s=Bt(),[t,n]=_.useState(!1),[r,a]=_.useState(!1),[i,l]=_.useState(!1),[o,c]=_.useState({brokerage_id:"",folder_id:"",folder_name:"",folder_type:"template",description:""}),{data:d,isLoading:u}=at({queryKey:["canva-integration"],queryFn:async()=>{const{data:b,error:j}=await q.from("canva_integration").select("*").eq("is_active",!0).maybeSingle();if(j)throw j;return b}}),{data:h}=at({queryKey:["brokerages-list"],queryFn:async()=>{const{data:b,error:j}=await q.from("brokerages").select("id, name").order("name");if(j)throw j;return b}}),{data:m}=at({queryKey:["canva-brokerage-folders"],queryFn:async()=>{const{data:b,error:j}=await q.from("canva_brokerage_folders").select("*, brokerages(name)").order("sort_order");if(j)throw j;return b}}),p=async()=>{var b;n(!0);try{const{data:j}=await q.auth.getSession(),S=(b=j==null?void 0:j.session)==null?void 0:b.access_token;if(!S)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 ${S}`,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){se.error("Popup was blocked. Please allow popups for this site and try again."),n(!1);return}const D=V=>{var G,$;V.origin===window.location.origin&&(((G=V.data)==null?void 0:G.type)==="canva-oauth-success"?(window.removeEventListener("message",D),se.success("Canva connected successfully!"),s.invalidateQueries({queryKey:["canva-integration"]}),n(!1)):(($=V.data)==null?void 0:$.type)==="canva-oauth-error"&&(window.removeEventListener("message",D),se.error("Canva connection failed: "+(V.data.error||"Unknown error")),n(!1)))};window.addEventListener("message",D);const O=setInterval(()=>{I.closed&&(clearInterval(O),window.removeEventListener("message",D),s.invalidateQueries({queryKey:["canva-integration"]}),n(!1))},500)}else throw new Error("Failed to get authorization URL")}catch(j){console.error("Canva connect error:",j);const S=(j==null?void 0:j.message)||"";S.includes("CANVA_CLIENT_ID")?se.error("Canva app credentials not configured yet."):se.error(S||"Failed to start Canva connection"),n(!1)}},f=mt({mutationFn:async b=>{var I;const{data:j}=await q.auth.getSession(),S=(I=j==null?void 0:j.session)==null?void 0:I.access_token;if(!S)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 ${S}`,apikey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM"},body:JSON.stringify({action:"disconnect",integrationId:b})}),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"]}),se.success("Canva disconnected")},onError:b=>{se.error(b.message||"Failed to disconnect Canva")}}),y=mt({mutationFn:async b=>{const{error:j}=await q.from("canva_brokerage_folders").insert({brokerage_id:b.brokerage_id,folder_id:b.folder_id.trim(),folder_name:b.folder_name.trim(),folder_type:b.folder_type,description:b.description.trim()||null,sort_order:(m==null?void 0:m.length)||0});if(j)throw j},onSuccess:()=>{s.invalidateQueries({queryKey:["canva-brokerage-folders"]}),se.success("Folder added"),l(!1),c({brokerage_id:"",folder_id:"",folder_name:"",folder_type:"template",description:""})},onError:()=>se.error("Failed to add folder")}),v=mt({mutationFn:async b=>{const{error:j}=await q.from("canva_brokerage_folders").delete().eq("id",b);if(j)throw j},onSuccess:()=>{s.invalidateQueries({queryKey:["canva-brokerage-folders"]}),se.success("Folder removed")},onError:()=>se.error("Failed to remove folder")}),g=!!d;return e.jsxs(e.Fragment,{children:[e.jsxs(ve,{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(x4t,{})}),e.jsxs("div",{children:[e.jsxs(St,{className:"text-lg flex items-center gap-2",children:["Canva Connect",g&&e.jsx(Oe,{variant:"default",className:"text-xs",children:"Connected"}),e.jsx(Oe,{variant:"outline",className:"text-xs",children:"Admin Only"})]}),e.jsx(kn,{children:"Auto-share brokerage asset folders with agents when they connect their Canva accounts."})]})]})})}),e.jsx(Me,{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(_l,{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(_l,{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(_l,{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"})]}),g?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(Kl,{children:[e.jsx(jx,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Sn,{className:"h-4 w-4"})})}),e.jsxs(Ol,{children:[e.jsxs(zl,{children:[e.jsx(Ul,{children:"Disconnect Canva?"}),e.jsx(ql,{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($l,{children:"Cancel"}),e.jsx(Ml,{onClick:()=>f.mutate(d.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]}),e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("button",{onClick:()=>a(!r),className:"w-full flex items-center justify-between p-3 text-sm font-medium hover:bg-muted transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(wy,{className:"h-4 w-4 text-primary"}),"Brokerage Folder Mappings",m&&m.length>0&&e.jsx(Oe,{variant:"secondary",className:"text-xs",children:m.length})]}),r?e.jsx(_v,{className:"h-4 w-4"}):e.jsx(tl,{className:"h-4 w-4"})]}),r&&e.jsxs("div",{className:"border-t p-3 space-y-2",children:[m&&m.length>0?m.map(b=>{var j,S;return e.jsxs("div",{className:"flex items-center justify-between p-2 rounded-md bg-muted/50 text-sm",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-medium truncate",children:b.folder_name}),e.jsx(Oe,{variant:"outline",className:"text-xs shrink-0",children:((j=g4t.find(C=>C.value===b.folder_type))==null?void 0:j.label)||b.folder_type})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(S=b.brokerages)==null?void 0:S.name," · ID: ",e.jsx("span",{className:"font-mono",children:b.folder_id})]})]}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive shrink-0 ml-2",onClick:()=>v.mutate(b.id),children:e.jsx(Qn,{className:"h-3.5 w-3.5"})})]},b.id)}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-2",children:"No folders mapped yet"}),e.jsxs(B,{variant:"outline",size:"sm",className:"w-full gap-1.5 mt-1",onClick:()=>l(!0),children:[e.jsx(rn,{className:"h-3.5 w-3.5"}),"Add Folder Mapping"]})]})]})]}):e.jsxs(B,{className:"mt-4",onClick:p,disabled:t||u,children:[t?e.jsx(uo,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx("div",{className:"mr-2",children:e.jsx(x4t,{})}),"Connect Canva",e.jsx(La,{className:"h-4 w-4 ml-2"})]})]})})]}),e.jsx(Ls,{open:i,onOpenChange:l,children:e.jsxs(Ps,{children:[e.jsx(Os,{children:e.jsx(Ds,{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(J,{children:"Brokerage"}),e.jsxs(is,{value:o.brokerage_id,onValueChange:b=>c(j=>({...j,brokerage_id:b})),children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Select a brokerage…"})}),e.jsx(as,{children:h==null?void 0:h.map(b=>e.jsx(He,{value:b.id,children:b.name},b.id))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Canva Folder ID"}),e.jsx(xe,{placeholder:"e.g. FABCdef123456",value:o.folder_id,onChange:b=>c(j=>({...j,folder_id:b.target.value}))}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Found in the Canva folder URL: canva.com/folder/",e.jsx("strong",{children:"FOLDER_ID"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Folder Display Name"}),e.jsx(xe,{placeholder:"e.g. Brand Templates 2024",value:o.folder_name,onChange:b=>c(j=>({...j,folder_name:b.target.value}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Folder Type"}),e.jsxs(is,{value:o.folder_type,onValueChange:b=>c(j=>({...j,folder_type:b})),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsx(as,{children:g4t.map(b=>e.jsx(He,{value:b.value,children:b.label},b.value))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(J,{children:["Description ",e.jsx("span",{className:"text-muted-foreground",children:"(optional)"})]}),e.jsx(xe,{placeholder:"What's in this folder?",value:o.description,onChange:b=>c(j=>({...j,description:b.target.value}))})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsxs(B,{onClick:()=>y.mutate(o),disabled:!o.brokerage_id||!o.folder_id||!o.folder_name||y.isPending,children:[y.isPending?e.jsx(uo,{className:"h-4 w-4 mr-2 animate-spin"}):null,"Add Folder"]})]})]})})]})}function snr(){const s=Fn();return e.jsx(zs,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-8",children:[e.jsx(Wh,{title:"Integrations",description:"Manage platform-level service connections"}),e.jsxs(ve,{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(bd,{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(B,{onClick:()=>s("/admin/social-connections"),children:["View ",e.jsx(La,{className:"h-4 w-4 ml-1"})]})]}),e.jsx(tnr,{}),e.jsx(yrs,{})]})})}const y4t=s=>{const t="h-4 w-4";return s==="facebook"?e.jsx(tf,{className:t}):s==="instagram"?e.jsx(Im,{className:t}):s==="linkedin"?e.jsx(dg,{className:t}):s==="google"?e.jsx(ln,{className:t}):null},nnr=s=>s?new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",year:"numeric",month:"short",day:"numeric"}).format(new Date(s)):"—";function rnr(){const[s,t]=_.useState([]),[n,r]=_.useState(!0),[a,i]=_.useState(""),[l,o]=_.useState("all");_.useEffect(()=>{(async()=>{r(!0);const{data:m,error:p}=await q.rpc("admin_get_social_connections");if(p){se.error(p.message),r(!1);return}t(m||[]),r(!1)})()},[]);const c=_.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=_.useMemo(()=>{const m=new Map;return s.forEach(p=>{const f=m.get(p.user_id)||{name:p.user_name,email:p.user_email,platforms:new Set,count:0};f.platforms.add(p.platform),f.count+=1,m.set(p.user_id,f)}),Array.from(m.entries()).map(([p,f])=>({user_id:p,...f}))},[s]),u=_.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(ve,{className:"p-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground capitalize flex items-center gap-2",children:[y4t(m)," ",m]}),e.jsx("div",{className:"text-2xl font-bold",children:p})]},m))]}),e.jsxs("div",{className:"flex flex-col md:flex-row gap-3",children:[e.jsx(xe,{placeholder:"Search by user, email, page, or handle…",value:a,onChange:m=>i(m.target.value),className:"md:max-w-md"}),e.jsxs(is,{value:l,onValueChange:o,children:[e.jsx(rs,{className:"md:w-48",children:e.jsx(ls,{placeholder:"All platforms"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All platforms"}),e.jsx(He,{value:"facebook",children:"Facebook"}),e.jsx(He,{value:"instagram",children:"Instagram"}),e.jsx(He,{value:"linkedin",children:"LinkedIn"}),e.jsx(He,{value:"google",children:"Google"})]})]})]}),e.jsx(ve,{children:n?e.jsx("div",{className:"flex items-center justify-center p-12",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"User"}),e.jsx(Pt,{children:"Platform"}),e.jsx(Pt,{children:"Page / Account"}),e.jsx(Pt,{children:"Status"}),e.jsx(Pt,{children:"Connected"})]})}),e.jsx(Ka,{children:c.length===0?e.jsx(pn,{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(pn,{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:[y4t(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(Oe,{variant:"destructive",className:"gap-1",children:[e.jsx(Xo,{className:"h-3 w-3"})," Expired"]}):e.jsx(Oe,{children:"Active"}):e.jsx(Oe,{variant:"secondary",children:"Inactive"})}),e.jsx(gt,{className:"text-sm text-muted-foreground",children:nnr(m.created_at)})]},m.id)})})]})})]})})}const anr={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 DZ(s,t=18,n=10){return s.length<=t+n+3?s:`${s.slice(0,t)}…${s.slice(-n)}`}function inr(){var O,V,G,$,H;const s=Bt(),[t,n]=_.useState("Test Push"),[r,a]=_.useState("Testing web push notification"),[i,l]=_.useState("/community"),[o,c]=_.useState(!1),[d,u]=_.useState(!1),[h,m]=_.useState({isSupported:typeof window<"u"&&"serviceWorker"in navigator&&"PushManager"in window}),[p,f]=_.useState(null),[y,v]=_.useState(null),{data:g,isLoading:b}=at({queryKey:["push-notification-settings"],queryFn:async()=>{const{data:Y,error:Z}=await q.from("push_notification_settings").select("*").order("setting_key");if(Z)throw Z;return Y}}),{data:j,isLoading:S}=at({queryKey:["push-subscription-stats"],queryFn:async()=>{const{count:Y,error:Z}=await q.from("push_subscriptions").select("*",{count:"exact",head:!0});if(Z)throw Z;return{totalSubscriptions:Y||0}}}),C=mt({mutationFn:async({settingKey:Y,isEnabled:Z})=>{const{error:ne}=await q.from("push_notification_settings").update({is_enabled:Z}).eq("setting_key",Y);if(ne)throw ne},onSuccess:()=>{s.invalidateQueries({queryKey:["push-notification-settings"]}),se.success("Notification setting updated")},onError:Y=>{se.error("Failed to update setting: "+Y.message)}}),E=_.useMemo(()=>{var Y,Z;return h.isSupported?`perm=${h.permission??"unknown"} · controller=${h.controllerPresent?"yes":"no"} · sw=${((Y=h.serviceWorker)==null?void 0:Y.activeState)??"unknown"} · sub=${(Z=h.subscription)!=null&&Z.endpoint?"yes":"no"}`:"Push not supported in this browser."},[h]);_.useEffect(()=>{let Y=!0;const Z=async()=>{var te,ae,le,be,me,he,pe;const ce="serviceWorker"in navigator&&"PushManager"in window,ie={isSupported:ce,permission:typeof Notification<"u"?Notification.permission:void 0,controllerPresent:!!((te=navigator.serviceWorker)!=null&&te.controller)};if(!ce){Y&&m(ie);return}try{const{data:Ce,error:Ae}=await q.functions.invoke("get-vapid-public-key",{body:{}});if(Ae)throw Ae;ie.vapidPublicKey=Ce==null?void 0:Ce.vapidPublicKey;const ze=(await navigator.serviceWorker.getRegistrations()).find(ke=>{var Se,Fe,Ne;return(((Se=ke.active)==null?void 0:Se.scriptURL)||((Fe=ke.waiting)==null?void 0:Fe.scriptURL)||((Ne=ke.installing)==null?void 0:Ne.scriptURL)||"").includes("/sw.js")});if(ze){ie.pushWorkerScriptUrl=((ae=ze.active)==null?void 0:ae.scriptURL)||((le=ze.waiting)==null?void 0:le.scriptURL)||((be=ze.installing)==null?void 0:be.scriptURL),ie.serviceWorker={scope:ze.scope,activeState:(me=ze.active)==null?void 0:me.state};const ke=await ze.pushManager.getSubscription();if(ke){const Ze=ke.toJSON();ie.subscription={endpoint:Ze.endpoint,p256dh:(he=Ze.keys)==null?void 0:he.p256dh,auth:(pe=Ze.keys)==null?void 0:pe.auth}}}}catch(Ce){ie.error=(Ce==null?void 0:Ce.message)||String(Ce)}Y&&m(ie)};Z();const ne=window.setInterval(Z,4e3);return()=>{Y=!1,window.clearInterval(ne)}},[]);const P=async()=>{if(typeof Notification>"u"){se.error("Notifications API not available in this browser.");return}try{if(Notification.permission!=="granted"&&await Notification.requestPermission()!=="granted"){se.error("Notification permission not granted.");return}new Notification("Local notification test",{body:"If you see this, OS/browser notifications can display."}),se.success("Triggered a local notification (not push).")}catch(Y){se.error(`Local notification failed: ${(Y==null?void 0:Y.message)||String(Y)}`)}},M=async()=>{c(!0),f(null);try{const{data:Y,error:Z}=await q.functions.invoke("send-push-notification",{body:{title:t,body:r,url:i}});if(Z)throw Z;f({sent:Y==null?void 0:Y.sent,failed:Y==null?void 0:Y.failed,expiredCleaned:Y==null?void 0:Y.expiredCleaned,vapidPublicKey:Y==null?void 0:Y.vapidPublicKey}),(Y==null?void 0:Y.sent)>0?se.success(`Test notification sent to ${Y.sent} subscriber(s)`):(Y==null?void 0:Y.failed)>0?se.warning(`Notification failed for ${Y.failed} subscriber(s). ${Y.expired||0} expired subscriptions cleaned up.`):se.info("No active subscriptions to send to")}catch(Y){console.error("Error sending test notification:",Y),f({error:(Y==null?void 0:Y.message)||String(Y)}),se.error("Failed to send test notification: "+(Y.message||"Unknown error"))}finally{c(!1)}},I=async()=>{u(!0),v(null);try{const{data:Y,error:Z}=await q.functions.invoke("generate-vapid-keys",{body:{}});if(Z)throw Z;const ne=Y==null?void 0:Y.publicKey,ce=Y==null?void 0:Y.privateKey;if(!ne||!ce)throw new Error("generate-vapid-keys did not return keys");v({publicKey:ne,privateKey:ce}),se.success("Generated new VAPID keys. Update backend secrets, then clear + re-subscribe.")}catch(Y){console.error("Error generating VAPID keys:",Y),se.error("Failed to generate VAPID keys: "+((Y==null?void 0:Y.message)||"Unknown error"))}finally{u(!1)}},D=mt({mutationFn:async()=>{const{error:Y}=await q.from("push_subscriptions").delete().neq("id","00000000-0000-0000-0000-000000000000");if(Y)throw Y},onSuccess:()=>{se.success("All subscriptions cleared. Users will need to re-enable notifications."),s.invalidateQueries({queryKey:["push-subscription-stats"]})},onError:Y=>{se.error("Failed to clear subscriptions: "+Y.message)}});return e.jsx(zs,{title:"Notification Settings",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Wh,{title:"Notification Settings",description:"Manage push notifications and test the notification system"}),e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(In,{className:"h-5 w-5"}),"Push Notification Subscribers"]}),e.jsx(kn,{children:"Current active push notification subscriptions"})]}),e.jsx(Me,{children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"text-4xl font-bold",children:S?"...":(j==null?void 0:j.totalSubscriptions)||0}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"active subscriptions"})]})})]}),e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(qc,{className:"h-5 w-5"}),"Notification Types"]}),e.jsx(kn,{children:"Control which types of push notifications are sent to users"})]}),e.jsx(Me,{children:b?e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading settings..."}):e.jsx("div",{className:"space-y-4",children:g==null?void 0:g.map(Y=>{const Z=anr[Y.setting_key]||{label:Y.setting_key,icon:"🔔"};return e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-2xl",children:Z.icon}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Z.label}),e.jsx("div",{className:"text-sm text-muted-foreground",children:Y.description})]})]}),e.jsx(fn,{checked:Y.is_enabled,onCheckedChange:ne=>C.mutate({settingKey:Y.setting_key,isEnabled:ne}),disabled:C.isPending})]},Y.id)})})})]}),e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(Rg,{className:"h-5 w-5"}),"Send Test Notification"]}),e.jsx(kn,{children:"Send a test push notification to all subscribed users"})]}),e.jsxs(Me,{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-md border bg-muted/30 p-3 text-sm",children:[e.jsx("div",{className:"font-medium",children:"Client push debug"}),e.jsx("div",{className:"mt-1 text-muted-foreground",children:E}),h.error&&e.jsx("div",{className:"mt-2 text-destructive",children:h.error}),e.jsxs("div",{className:"mt-2 grid gap-2 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Backend VAPID public key"}),e.jsx("div",{className:"break-all rounded-md border bg-background p-2 font-mono text-xs",children:h.vapidPublicKey?DZ(h.vapidPublicKey):"(not loaded)"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Service worker"}),e.jsxs("div",{className:"rounded-md border bg-background p-2 font-mono text-xs",children:[e.jsxs("div",{children:["scope: ",(O=h.serviceWorker)!=null&&O.scope?DZ(h.serviceWorker.scope,24,8):"none"]}),e.jsxs("div",{children:["active: ",((V=h.serviceWorker)==null?void 0:V.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: ",(G=h.subscription)!=null&&G.endpoint?DZ(h.subscription.endpoint,40,12):"none"]}),e.jsxs("div",{children:["p256dh: ",($=h.subscription)!=null&&$.p256dh?DZ(h.subscription.p256dh,22,10):"none"]}),e.jsxs("div",{children:["auth: ",(H=h.subscription)!=null&&H.auth?DZ(h.subscription.auth,22,10):"none"]})]})]})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(B,{variant:"outline",onClick:P,children:"Local notification test"}),e.jsx(B,{variant:"outline",onClick:()=>window.location.reload(),children:"Reload page"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"test-title",children:"Notification Title"}),e.jsx(xe,{id:"test-title",value:t,onChange:Y=>n(Y.target.value),placeholder:"Enter notification title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"test-body",children:"Notification Body"}),e.jsx(Ms,{id:"test-body",value:r,onChange:Y=>a(Y.target.value),placeholder:"Enter notification message",rows:3})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"test-url",children:"Click URL (optional)"}),e.jsx(xe,{id:"test-url",value:i,onChange:Y=>l(Y.target.value),placeholder:"/community or full URL"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Where users will be taken when they click the notification"})]}),e.jsxs(B,{onClick:M,disabled:o||!t||!r,className:"w-full sm:w-auto",children:[e.jsx(Or,{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(ve,{children:[e.jsxs(bt,{children:[e.jsxs(St,{className:"flex items-center gap-2 text-destructive",children:[e.jsx(Sn,{className:"h-5 w-5"}),"Subscription Maintenance"]}),e.jsx(kn,{children:"Clear all push subscriptions if VAPID keys were changed or subscriptions are invalid"})]}),e.jsxs(Me,{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(B,{variant:"destructive",onClick:()=>D.mutate(),disabled:D.isPending,children:[e.jsx(Sn,{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(B,{variant:"outline",onClick:I,disabled:d,children:d?"Generating…":"Generate VAPID keys"})}),y&&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:y.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:y.privateKey})]})]})]})]})]})]})})}function onr(){const{toast:s}=vi(),[t,n]=_.useState([]),[r,a]=_.useState({totalPresentations:0,totalViews:0,totalLeads:0,totalCtaClicks:0,agentsUsing:0}),[i,l]=_.useState(!0),{sortKey:o,sortDirection:c,handleSort:d,sortData:u}=wae("presentation_count","desc"),h=u(t,{name:f=>{var y;return((y=f.name)==null?void 0:y.toLowerCase())||""},presentations:f=>f.presentation_count,views:f=>f.total_views,leads:f=>f.total_leads,cta_clicks:f=>f.total_cta_clicks,conversion:f=>f.total_views>0?f.total_leads/f.total_views*100:0});_.useEffect(()=>{m()},[]);const m=async()=>{try{l(!0);const{data:f,error:y}=await q.rpc("get_admin_presentation_stats");if(y)throw y;if(!f||f.length===0){l(!1);return}const v=f.map(C=>C.owner_user_id),{data:g,error:b}=await q.from("profiles").select("id, name, email, avatar_url").in("id",v);if(b)throw b;const j=new Map((g==null?void 0:g.map(C=>[C.id,C]))||[]),S=f.map(C=>{const E=j.get(C.owner_user_id);return{owner_user_id:C.owner_user_id,name:(E==null?void 0:E.name)||"Unknown",email:(E==null?void 0:E.email)||"",avatar_url:(E==null?void 0:E.avatar_url)||null,presentation_count:Number(C.presentation_count),total_views:Number(C.total_views),total_leads:Number(C.total_leads),total_cta_clicks:Number(C.total_cta_clicks)}});n(S),n(S),a({totalPresentations:S.reduce((C,E)=>C+E.presentation_count,0),totalViews:S.reduce((C,E)=>C+E.total_views,0),totalLeads:S.reduce((C,E)=>C+E.total_leads,0),totalCtaClicks:S.reduce((C,E)=>C+E.total_cta_clicks,0),agentsUsing:S.length})}catch(f){console.error("Error loading presentation stats:",f),s({title:"Error",description:"Failed to load presentation analytics",variant:"destructive"})}finally{l(!1)}},p=[{label:"Agents Using",value:r.agentsUsing,icon:In,color:"text-blue-600"},{label:"Total Presentations",value:r.totalPresentations,icon:jv,color:"text-violet-600"},{label:"Total Views",value:r.totalViews,icon:ya,color:"text-emerald-600"},{label:"Total Leads",value:r.totalLeads,icon:Pl,color:"text-amber-600"},{label:"CTA Clicks",value:r.totalCtaClicks,icon:$h,color:"text-rose-600"}];return e.jsx(zs,{title:"Presentation Analytics",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Presentation Analytics"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Track Smart Presentations usage and engagement across all agents"})]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-4",children:p.map(f=>e.jsxs(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(St,{className:"text-sm font-medium",children:f.label}),e.jsx(f.icon,{className:`h-4 w-4 ${f.color}`})]}),e.jsx(Me,{children:i?e.jsx(cn,{className:"h-8 w-16"}):e.jsx("div",{className:"text-2xl font-bold",children:f.value.toLocaleString()})})]},f.label))}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(Nl,{className:"h-5 w-5"}),"Agent Breakdown"]})}),e.jsx(Me,{children:i?e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((f,y)=>e.jsx(cn,{className:"h-12 w-full"},y))}):t.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No presentations created yet."}):e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(qh,{sortKey:"name",currentSortKey:o,currentDirection:c,onSort:d,children:"Agent"}),e.jsx(qh,{sortKey:"presentations",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Presentations"}),e.jsx(qh,{sortKey:"views",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Views"}),e.jsx(qh,{sortKey:"leads",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Leads"}),e.jsx(qh,{sortKey:"cta_clicks",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"CTA Clicks"}),e.jsx(qh,{sortKey:"conversion",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Conversion"})]})}),e.jsx(Ka,{children:h.map(f=>{var v,g;const y=f.total_views>0?(f.total_leads/f.total_views*100).toFixed(1):"0.0";return e.jsxs(pn,{children:[e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-8 w-8 rounded-full bg-muted flex items-center justify-center overflow-hidden",children:f.avatar_url?e.jsx("img",{src:f.avatar_url,alt:"",className:"h-full w-full object-cover"}):e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:((g=(v=f.name)==null?void 0:v.charAt(0))==null?void 0:g.toUpperCase())||"?"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:f.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:f.email})]})]})}),e.jsx(gt,{className:"text-center font-medium",children:f.presentation_count}),e.jsx(gt,{className:"text-center",children:f.total_views.toLocaleString()}),e.jsx(gt,{className:"text-center",children:f.total_leads>0?e.jsx(Oe,{variant:"secondary",children:f.total_leads}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(gt,{className:"text-center",children:f.total_cta_clicks}),e.jsx(gt,{className:"text-center",children:e.jsxs("span",{className:Number(y)>0?"text-emerald-600 font-medium":"text-muted-foreground",children:[y,"%"]})})]},f.owner_user_id)})})]})})]})]})})}const EBe=s=>s?new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(s)):"—",lnr=s=>s==null?"—":`$${Number(s).toLocaleString("en-US",{maximumFractionDigits:0})}`;function cnr(){const{toast:s}=vi(),[t,n]=_.useState(!0),[r,a]=_.useState([]),[i,l]=_.useState({}),[o,c]=_.useState("");_.useEffect(()=>{(async()=>{try{n(!0);const v=[],g=1e3;for(let S=0;;S+=g){const{data:C,error:E}=await q.from("listing_presentations").select("id, owner_user_id, title, status, property_address_line1, city, state, list_price, template_id, last_generated_at, created_at, updated_at").order("created_at",{ascending:!1}).range(S,S+g-1);if(E)throw E;if(v.push(...C??[]),!C||C.lengthS.owner_user_id))),j={};for(let S=0;S{j[E.id]={name:E.name??"Unknown",email:E.email??""}})}l(j)}catch(v){console.error(v),s({title:"Error",description:"Failed to load presentation data",variant:"destructive"})}finally{n(!1)}})()},[s]);const d=_.useMemo(()=>{const y=Date.now(),v=y-7*24*60*60*1e3,g=y-30*24*60*60*1e3;return{total:r.length,generated:r.filter(b=>!!b.last_generated_at).length,agents:new Set(r.map(b=>b.owner_user_id)).size,thisWeek:r.filter(b=>new Date(b.created_at).getTime()>=v).length,thisMonth:r.filter(b=>new Date(b.created_at).getTime()>=g).length}},[r]),u=_.useMemo(()=>{const y=new Map;return r.forEach(v=>{const g=i[v.owner_user_id],b=y.get(v.owner_user_id)??{user_id:v.owner_user_id,name:(g==null?void 0:g.name)??"Unknown",email:(g==null?void 0:g.email)??"",total:0,generated:0,last_activity:v.updated_at};b.total+=1,v.last_generated_at&&(b.generated+=1),new Date(v.updated_at)>new Date(b.last_activity)&&(b.last_activity=v.updated_at),y.set(v.owner_user_id,b)}),Array.from(y.values()).sort((v,g)=>g.total-v.total)},[r,i]),h=o.trim().toLowerCase(),m=h?u.filter(y=>y.name.toLowerCase().includes(h)||y.email.toLowerCase().includes(h)):u,p=h?r.filter(y=>{const v=i[y.owner_user_id];return(y.title??"").toLowerCase().includes(h)||(y.property_address_line1??"").toLowerCase().includes(h)||(y.city??"").toLowerCase().includes(h)||((v==null?void 0:v.name)??"").toLowerCase().includes(h)||((v==null?void 0:v.email)??"").toLowerCase().includes(h)}):r,f=[{label:"Total presentations",value:d.total,icon:Fr,sub:"All time"},{label:"Agents using it",value:d.agents,icon:In,sub:"Created at least one"},{label:"PDFs generated",value:d.generated,icon:un,sub:"Rendered at least once"},{label:"Created last 30 days",value:d.thisMonth,icon:Qd,sub:`${d.thisWeek} in last 7 days`}];return e.jsx(zs,{title:"Listing Presentation Studio",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Wh,{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(y=>e.jsx(cn,{className:"h-28 w-full"},y))}):e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-4",children:f.map(y=>e.jsxs(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(St,{className:"text-sm font-medium",children:y.label}),e.jsx(y.icon,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Me,{children:[e.jsx("div",{className:"text-2xl font-bold",children:y.value}),e.jsx("p",{className:"text-xs text-muted-foreground",children:y.sub})]})]},y.label))}),e.jsxs("div",{className:"relative max-w-md",children:[e.jsx(Lr,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(xe,{className:"pl-9",placeholder:"Search agents, addresses, titles...",value:o,onChange:y=>c(y.target.value)})]}),e.jsxs(Yr,{defaultValue:"agents",className:"space-y-4",children:[e.jsxs(Zr,{children:[e.jsxs(Ht,{value:"agents",children:["By agent (",m.length,")"]}),e.jsxs(Ht,{value:"all",children:["All presentations (",p.length,")"]})]}),e.jsx(Gt,{value:"agents",children:e.jsx(ve,{children:e.jsx(Me,{className:"p-0",children:e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"Agent"}),e.jsx(Pt,{className:"text-right",children:"Presentations"}),e.jsx(Pt,{className:"text-right",children:"Generated"}),e.jsx(Pt,{children:"Last activity"})]})}),e.jsxs(Ka,{children:[m.map(y=>e.jsxs(pn,{children:[e.jsxs(gt,{children:[e.jsx("div",{className:"font-medium",children:y.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:y.email})]}),e.jsx(gt,{className:"text-right font-semibold",children:y.total}),e.jsx(gt,{className:"text-right",children:y.generated}),e.jsx(gt,{children:EBe(y.last_activity)})]},y.user_id)),!t&&m.length===0&&e.jsx(pn,{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(Gt,{value:"all",children:e.jsx(ve,{children:e.jsx(Me,{className:"p-0",children:e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"Presentation"}),e.jsx(Pt,{children:"Agent"}),e.jsx(Pt,{children:"Property"}),e.jsx(Pt,{children:"Price"}),e.jsx(Pt,{children:"Status"}),e.jsx(Pt,{children:"Created"}),e.jsx(Pt,{children:"Last generated"})]})}),e.jsxs(Ka,{children:[p.slice(0,300).map(y=>{var v,g;return e.jsxs(pn,{children:[e.jsx(gt,{className:"font-medium",children:y.title||"Untitled"}),e.jsxs(gt,{children:[e.jsx("div",{children:((v=i[y.owner_user_id])==null?void 0:v.name)??"Unknown"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:((g=i[y.owner_user_id])==null?void 0:g.email)??""})]}),e.jsx(gt,{className:"text-sm",children:[y.property_address_line1,y.city,y.state].filter(Boolean).join(", ")||"—"}),e.jsx(gt,{children:lnr(y.list_price)}),e.jsx(gt,{children:e.jsx(Oe,{variant:y.last_generated_at?"default":"secondary",children:y.last_generated_at?"Generated":y.status||"Draft"})}),e.jsx(gt,{children:EBe(y.created_at)}),e.jsx(gt,{children:EBe(y.last_generated_at)})]},y.id)}),!t&&p.length===0&&e.jsx(pn,{children:e.jsx(gt,{colSpan:7,className:"py-10 text-center text-muted-foreground",children:"No presentations found."})})]})]})})})})]})]})})}const _ee="listing_revival";function dnr(){const{user:s,loading:t,isAdmin:n}=hs(),{data:r}=at({queryKey:["feature-entitlement",_ee,s==null?void 0:s.id],enabled:!!s&&!n,staleTime:5*60*1e3,queryFn:async()=>{const{data:a,error:i}=await q.from("feature_entitlements").select("enabled, expires_at, tier").eq("user_id",s.id).eq("feature_key",_ee).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 unr=s=>s?new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(s)):"—";function hnr(){var u,h;const{user:s}=hs(),t=Bt(),[n,r]=_.useState(""),a=at({queryKey:["lr-admin-stats"],queryFn:async()=>{const{data:m,error:p}=await q.rpc("get_admin_listing_revival_stats");if(p)throw p;return m??[]}}),i=at({queryKey:["lr-admin-members",n],queryFn:async()=>{let m=q.from("profiles").select("id, name, email").order("name").limit(200);if(n.trim()){const b=`%${n.trim()}%`;m=m.or(`email.ilike.${b},name.ilike.${b}`)}const{data:p,error:f}=await m;if(f)throw f;const y=(p??[]).map(b=>b.id),{data:v}=await q.from("feature_entitlements").select("user_id, enabled, tier").eq("feature_key",_ee).in("user_id",y.length?y:["00000000-0000-0000-0000-000000000000"]),g=new Map((v??[]).map(b=>[b.user_id,b]));return(p??[]).map(b=>{var j;return{user_id:b.id,name:b.name,email:b.email,enabled:!!((j=g.get(b.id))!=null&&j.enabled)}})}}),l=mt({mutationFn:async({userId:m,enabled:p})=>{const{error:f}=await q.from("feature_entitlements").upsert({user_id:m,feature_key:_ee,enabled:p,tier:"member",enabled_by:s.id,enabled_at:new Date().toISOString()},{onConflict:"user_id,feature_key"});if(f)throw f;await q.from("feature_entitlement_audit").insert({feature_key:_ee,target_user_id:m,action:p?"grant":"revoke",performed_by:s.id})},onSuccess:(m,p)=>{t.invalidateQueries({queryKey:["lr-admin-members"]}),se.success(p.enabled?"Access granted":"Access revoked")},onError:m=>se.error(m.message)}),o=at({queryKey:["lr-admin-stat-profiles",(a.data??[]).length],enabled:!!((u=a.data)!=null&&u.length),queryFn:async()=>{const m=(a.data??[]).map(f=>f.owner_user_id),{data:p}=await q.from("profiles").select("id, name, email").in("id",m);return new Map((p??[]).map(f=>[f.id,f]))}}),c=_.useMemo(()=>{const m=a.data??[];return{agents:m.length,campaigns:m.reduce((p,f)=>p+Number(f.campaign_count),0),leads:m.reduce((p,f)=>p+Number(f.lead_count),0),hot:m.reduce((p,f)=>p+Number(f.hot_lead_count),0)}},[a.data]),d=[{label:"Agents using it",value:c.agents,icon:In},{label:"Campaigns built",value:c.campaigns,icon:un},{label:"Seller leads",value:c.leads,icon:Sy},{label:"Hot leads",value:c.hot,icon:gu}];return e.jsxs(zs,{title:"Listing Revival Admin",children:[e.jsx(Wh,{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(ve,{children:e.jsxs(Me,{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(Yr,{defaultValue:"usage",className:"mt-6",children:[e.jsxs(Zr,{children:[e.jsx(Ht,{value:"usage",children:"Agent usage"}),e.jsx(Ht,{value:"access",children:"Access"})]}),e.jsx(Gt,{value:"usage",className:"mt-4",children:e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"Usage by agent"})}),e.jsx(Me,{children:a.isLoading?e.jsx("div",{className:"space-y-2",children:[0,1,2].map(m=>e.jsx(cn,{className:"h-10 w-full"},m))}):(h=a.data)!=null&&h.length?e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"Agent"}),e.jsx(Pt,{className:"text-right",children:"Campaigns"}),e.jsx(Pt,{className:"text-right",children:"Live pages"}),e.jsx(Pt,{className:"text-right",children:"Leads"}),e.jsx(Pt,{className:"text-right",children:"Hot"}),e.jsx(Pt,{className:"text-right",children:"Engagement"}),e.jsx(Pt,{className:"text-right",children:"Last activity"})]})}),e.jsx(Ka,{children:[...a.data].sort((m,p)=>Number(p.campaign_count)-Number(m.campaign_count)).map(m=>{var f;const p=(f=o.data)==null?void 0:f.get(m.owner_user_id);return e.jsxs(pn,{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(Oe,{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:unr(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(Gt,{value:"access",className:"mt-4",children:e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"Who can use Listing Revival"})}),e.jsxs(Me,{className:"space-y-4",children:[e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(Lr,{className:"h-4 w-4 absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),e.jsx(xe,{className:"pl-9",placeholder:"Search agents by name or email",value:n,onChange:m=>r(m.target.value)})]}),i.isLoading?e.jsx("div",{className:"space-y-2",children:[0,1,2].map(m=>e.jsx(cn,{className:"h-10 w-full"},m))}):e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"Agent"}),e.jsx(Pt,{children:"Email"}),e.jsx(Pt,{className:"text-right",children:"Access"})]})}),e.jsx(Ka,{children:(i.data??[]).map(m=>e.jsxs(pn,{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(fn,{checked:m.enabled,onCheckedChange:p=>l.mutate({userId:m.user_id,enabled:p})})})]},m.user_id))})]})]})]})})]})]})}function mnr(){const{toast:s}=vi(),[t,n]=_.useState([]),[r,a]=_.useState({totalOpenHouses:0,totalVisitors:0,totalLeads:0,activeOpenHouses:0,agentsUsing:0}),[i,l]=_.useState(!0);_.useEffect(()=>{o()},[]);const o=async()=>{try{l(!0);const{data:d,error:u}=await q.rpc("get_admin_guest_book_stats");if(u)throw u;if(!d||d.length===0){l(!1);return}const h=d.map(v=>v.agent_id),{data:m,error:p}=await q.from("profiles").select("id, name, email, avatar_url").in("id",h);if(p)throw p;const f=new Map((m==null?void 0:m.map(v=>[v.id,v]))||[]),y=d.map(v=>{const g=f.get(v.agent_id);return{agent_id:v.agent_id,name:(g==null?void 0:g.name)||"Unknown",email:(g==null?void 0:g.email)||"",avatar_url:(g==null?void 0:g.avatar_url)||null,open_house_count:Number(v.open_house_count),total_visitors:Number(v.total_visitors),total_leads:Number(v.total_leads),active_count:Number(v.active_count)}});y.sort((v,g)=>g.total_visitors-v.total_visitors),n(y),a({totalOpenHouses:y.reduce((v,g)=>v+g.open_house_count,0),totalVisitors:y.reduce((v,g)=>v+g.total_visitors,0),totalLeads:y.reduce((v,g)=>v+g.total_leads,0),activeOpenHouses:y.reduce((v,g)=>v+g.active_count,0),agentsUsing:y.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:In,color:"text-blue-600"},{label:"Total Open Houses",value:r.totalOpenHouses,icon:Jr,color:"text-violet-600"},{label:"Active Now",value:r.activeOpenHouses,icon:_l,color:"text-emerald-600"},{label:"Total Visitors",value:r.totalVisitors,icon:ya,color:"text-amber-600"},{label:"Leads Created",value:r.totalLeads,icon:Pl,color:"text-rose-600"}];return e.jsx(zs,{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(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(St,{className:"text-sm font-medium",children:d.label}),e.jsx(d.icon,{className:`h-4 w-4 ${d.color}`})]}),e.jsx(Me,{children:i?e.jsx(cn,{className:"h-8 w-16"}):e.jsx("div",{className:"text-2xl font-bold",children:d.value.toLocaleString()})})]},d.label))}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(Nl,{className:"h-5 w-5"}),"Agent Breakdown"]})}),e.jsx(Me,{children:i?e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((d,u)=>e.jsx(cn,{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(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"Agent"}),e.jsx(Pt,{className:"text-center",children:"Open Houses"}),e.jsx(Pt,{className:"text-center",children:"Active"}),e.jsx(Pt,{className:"text-center",children:"Visitors"}),e.jsx(Pt,{className:"text-center",children:"Leads"}),e.jsx(Pt,{className:"text-center",children:"Conversion"})]})}),e.jsx(Ka,{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(pn,{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(Oe,{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(Oe,{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 pnr(){const[s]=Yl(),t=Fn(),[n,r]=_.useState("loading"),a=_.useRef(!1),[i,l]=_.useState("Processing connection...");return _.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"),se.error("Failed to connect: "+(u||d));return}if(!c){r("error"),l("No authorization code received"),se.error("Failed to connect: No authorization code");return}try{const{data:m,error:p}=await q.functions.invoke("meta-oauth",{body:{action:"exchange_code",code:c,state:h}});if(m&&m.success===!1)throw new Error(m.error||"Failed to connect accounts");if(p){let f=p.message||"Failed to connect accounts";try{const y=p.context;if(y&&typeof y.json=="function"){const v=await y.json();v!=null&&v.error&&(f=v.error)}}catch{}throw new Error(f)}if(m!=null&&m.success)r("success"),l(m.message||"Accounts connected successfully!"),se.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"),se.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(ve,{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(Ct,{className:"h-12 w-12 animate-spin text-primary"}),n==="success"&&e.jsx(_l,{className:"h-12 w-12 text-green-500"}),n==="error"&&e.jsx(Rd,{className:"h-12 w-12 text-destructive"})]}),e.jsxs(St,{children:[n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(kn,{children:i})]}),e.jsx(Me,{className:"flex justify-center",children:e.jsx(B,{onClick:()=>t("/admin/integrations"),children:n==="success"?"View Integrations":"Back to Integrations"})})]})})}function fnr(){const s=Bt(),[t,n]=_.useState(""),[r,a]=_.useState(""),[i,l]=_.useState([]),o=_.useRef(null),{data:c,isLoading:d}=at({queryKey:["prospect-emails"],queryFn:async()=>{const{data:b,error:j}=await q.from("prospect_emails").select("*").order("sent_at",{ascending:!1});if(j)throw j;return b}}),u=(c==null?void 0:c.filter(b=>b.status==="live_lead"))||[],h={total:(c==null?void 0:c.length)||0,sent:(c==null?void 0:c.filter(b=>b.status==="sent").length)||0,converted:(c==null?void 0:c.filter(b=>b.status==="converted").length)||0,liveLeads:u.length,conversionRate:c!=null&&c.length?Math.round(c.filter(b=>b.status==="converted").length/c.length*100):0},m=mt({mutationFn:async b=>{const{data:j,error:S}=await q.functions.invoke("send-prospect-email",{body:{emails:b}});if(S)throw S;return j},onSuccess:b=>{s.invalidateQueries({queryKey:["prospect-emails"]}),se.success(`${b.sent} email${b.sent>1?"s":""} sent successfully!`),n(""),a(""),l([])},onError:b=>{se.error("Failed to send: "+b.message)}}),p=mt({mutationFn:async()=>{var C,E;const{data:{user:b}}=await q.auth.getUser();if(!(b!=null&&b.email))throw new Error("Could not get your email");const{data:j,error:S}=await q.functions.invoke("send-prospect-email",{body:{emails:[{email:b.email,first_name:(E=(C=b.user_metadata)==null?void 0:C.name)==null?void 0:E.split(" ")[0]}],test_mode:!0}});if(S)throw S;return j},onSuccess:()=>{se.success("Test email sent to your inbox!")},onError:b=>{se.error("Failed to send test: "+b.message)}}),f=mt({mutationFn:async()=>{const{data:b,error:j}=await q.functions.invoke("send-prospect-email",{body:{mode:"live_leads"}});if(j)throw j;return b},onSuccess:b=>{s.invalidateQueries({queryKey:["prospect-emails"]}),se.success(`${b.sent} live lead invite${b.sent===1?"":"s"} sent!`)},onError:b=>{se.error("Failed to send live lead invites: "+b.message)}}),y=()=>{if(!t.trim()){se.error("Please enter an email address");return}if(c==null?void 0:c.find(j=>j.email.toLowerCase()===t.trim().toLowerCase())){se.error("This email has already been prospected");return}m.mutate([{email:t.trim(),first_name:r.trim()||void 0}])},v=b=>{var C;const j=(C=b.target.files)==null?void 0:C[0];if(!j)return;const S=new FileReader;S.onload=E=>{var O,V;const M=((O=E.target)==null?void 0:O.result).split(` `).filter(G=>G.trim()),I=[],D=(V=M[0])!=null&&V.toLowerCase().includes("email")?1:0;for(let G=D;GZ.trim().replace(/"/g,"")),H=$[0],Y=$[1];H&&H.includes("@")&&I.push({email:H,first_name:Y||void 0})}l(I),se.success(`${I.length} entries loaded from CSV`)},S.readAsText(j),o.current&&(o.current.value="")},g=()=>{if(i.length===0){se.error("No entries to send");return}const b=new Set((c==null?void 0:c.map(S=>S.email.toLowerCase()))||[]),j=i.filter(S=>!b.has(S.email.toLowerCase()));if(j.length===0){se.error("All emails have already been prospected");return}j.length0&&e.jsxs(ve,{className:"border-red-200/50 bg-red-500/[0.02]",children:[e.jsxs(bt,{children:[e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(Nv,{className:"h-5 w-5 text-red-600"}),"Live Event Leads",e.jsx(Oe,{variant:"secondary",className:"ml-2",children:h.liveLeads})]}),e.jsx(kn,{children:"These agents registered on a LevelUp Live page but haven't received a free trial invite yet."})]}),e.jsx(Me,{children:e.jsxs(B,{onClick:()=>f.mutate(),disabled:f.isPending,className:"gap-2",children:[f.isPending?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Or,{className:"h-4 w-4"}),"Send free trial invite to all live leads"]})})]}),e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(ku,{className:"h-5 w-5"}),"Send Prospect Email"]}),e.jsxs(kn,{className:"flex items-center justify-between",children:[e.jsx("span",{children:"Send a beautiful free trial invitation email to potential members"}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>p.mutate(),disabled:p.isPending,className:"gap-2 ml-4 shrink-0",children:[p.isPending?e.jsx(Ct,{className:"h-3 w-3 animate-spin"}):e.jsx(ln,{className:"h-3 w-3"}),"Send Test to Me"]})]})]}),e.jsx(Me,{children:e.jsxs(Yr,{defaultValue:"single",children:[e.jsxs(Zr,{className:"mb-4",children:[e.jsxs(Ht,{value:"single",children:[e.jsx(Or,{className:"h-4 w-4 mr-2"}),"Single Send"]}),e.jsxs(Ht,{value:"bulk",children:[e.jsx(Oa,{className:"h-4 w-4 mr-2"}),"Bulk CSV"]})]}),e.jsx(Gt,{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(J,{htmlFor:"prospect-email",className:"sr-only",children:"Email"}),e.jsx(xe,{id:"prospect-email",type:"email",placeholder:"agent@example.com",value:t,onChange:b=>n(b.target.value),onKeyDown:b=>b.key==="Enter"&&y()})]}),e.jsxs("div",{className:"w-full sm:w-48",children:[e.jsx(J,{htmlFor:"prospect-name",className:"sr-only",children:"First Name"}),e.jsx(xe,{id:"prospect-name",placeholder:"First name (optional)",value:r,onChange:b=>a(b.target.value),onKeyDown:b=>b.key==="Enter"&&y()})]}),e.jsxs(B,{onClick:y,disabled:m.isPending,className:"gap-2",children:[m.isPending?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Or,{className:"h-4 w-4"}),"Send Invite"]})]})}),e.jsx(Gt,{value:"bulk",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("input",{ref:o,type:"file",accept:".csv",onChange:v,className:"hidden"}),e.jsxs(B,{variant:"outline",onClick:()=>{var b;return(b=o.current)==null?void 0:b.click()},className:"gap-2",children:[e.jsx(Fr,{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(Oe,{variant:"secondary",className:"gap-1",children:[e.jsx(In,{className:"h-3 w-3"}),i.length," entries ready"]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>l([]),children:[e.jsx(Qn,{className:"h-4 w-4"}),"Clear"]})]}),e.jsxs("div",{className:"max-h-40 overflow-y-auto border rounded-lg p-3 bg-muted/30 text-sm font-mono space-y-1",children:[i.slice(0,20).map((b,j)=>e.jsxs("div",{className:"text-muted-foreground",children:[b.email,b.first_name?` — ${b.first_name}`:""]},j)),i.length>20&&e.jsxs("div",{className:"text-muted-foreground/60",children:["...and ",i.length-20," more"]})]}),e.jsxs(B,{onClick:g,disabled:m.isPending,className:"gap-2",children:[m.isPending?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Or,{className:"h-4 w-4"}),"Send ",i.length," Invites"]})]})]})})]})})]}),e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(ln,{className:"h-5 w-5"}),"Prospect Log"]}),e.jsx(kn,{children:"Track all sent invitations and their conversion status"})]}),e.jsx(Me,{children:d?e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((b,j)=>e.jsx(cn,{className:"h-12 w-full"},j))}):c&&c.length>0?e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b",children:[e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-muted-foreground",children:"Email"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-muted-foreground",children:"Name"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-muted-foreground",children:"Sent"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-muted-foreground",children:"Status"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-muted-foreground",children:"Source"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-muted-foreground",children:"Converted"})]})}),e.jsx("tbody",{children:c.map(b=>{var j;return e.jsxs("tr",{className:"border-b last:border-0 hover:bg-muted/30",children:[e.jsx("td",{className:"py-3 px-4 text-sm font-medium text-foreground",children:b.email}),e.jsx("td",{className:"py-3 px-4 text-sm text-muted-foreground",children:b.first_name||"—"}),e.jsx("td",{className:"py-3 px-4 text-sm text-muted-foreground",children:Hs(new Date(b.sent_at),"MMM d, yyyy")}),e.jsx("td",{className:"py-3 px-4",children:b.status==="converted"?e.jsxs(Oe,{className:"bg-green-500/10 text-green-700 hover:bg-green-500/20 border-0",children:[e.jsx(Er,{className:"h-3 w-3 mr-1"}),"Converted"]}):b.status==="live_lead"?e.jsxs(Oe,{className:"bg-red-500/10 text-red-700 hover:bg-red-500/20 border-0 gap-1",children:[e.jsx(Nv,{className:"h-3 w-3"}),"Live lead"]}):e.jsxs(Oe,{variant:"secondary",className:"gap-1",children:[e.jsx(Gr,{className:"h-3 w-3"}),"Sent"]})}),e.jsx("td",{className:"py-3 px-4 text-sm text-muted-foreground",children:(j=b.utm_source)!=null&&j.startsWith("toolbox:")?e.jsxs(Oe,{variant:"outline",className:"gap-1 font-normal",children:[e.jsx(Fr,{className:"h-3 w-3"}),b.utm_source.replace("toolbox:","")]}):b.utm_source||"—"}),e.jsx("td",{className:"py-3 px-4 text-sm text-muted-foreground",children:b.converted_at?Hs(new Date(b.converted_at),"MMM d, yyyy"):"—"})]},b.id)})})]})}):e.jsxs("div",{className:"text-center py-12",children:[e.jsx(ku,{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 kz(s){const t=Bt(),{toast:n}=vi(),r=at({queryKey:["recruit-stages",s],queryFn:async()=>{if(!s)return[];const{data:c,error:d}=await q.from("recruit_pipeline_stages").select("*").eq("brokerage_id",s).order("sort_order");if(d)throw d;return c},enabled:!!s}),a=at({queryKey:["recruit-prospects",s],queryFn:async()=>{if(!s)return[];const c=1e3;let d=[],u=0,h=!0;for(;h;){const{data:m,error:p}=await q.from("recruit_prospects").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1}).range(u,u+c-1);if(p)throw p;d=d.concat(m),h=m.length===c,u+=c}return d},enabled:!!s}),i=mt({mutationFn:async c=>{const{data:{user:d}}=await q.auth.getUser();if(!d)throw new Error("Not authenticated");const u={first_name:c.first_name||"",last_name:c.last_name||null,email:c.email||null,phone:c.phone||null,current_brokerage:c.current_brokerage||null,license_number:c.license_number||null,experience_years:c.experience_years??null,annual_production:c.annual_production||null,source:c.source||"manual",notes:c.notes||null,stage_id:c.stage_id||null,brokerage_id:s,created_by:d.id,address:c.address||null,city:c.city||null,state:c.state||null,zip_code:c.zip_code||null,last_year_volume:c.last_year_volume||null,last_year_transactions:c.last_year_transactions??null,avg_sale_price:c.avg_sale_price||null,specialties:c.specialties||null,linkedin_url:c.linkedin_url||null,website_url:c.website_url||null,instagram_handle:c.instagram_handle||null,facebook_url:c.facebook_url||null,birthday:c.birthday||null,spouse_name:c.spouse_name||null,interests:c.interests||null,referred_by:c.referred_by||null},{data:h,error:m}=await q.from("recruit_prospects").insert(u).select().single();if(m)throw m;return h},onSuccess:()=>{t.invalidateQueries({queryKey:["recruit-prospects",s]}),n({title:"Prospect added"})},onError:c=>n({title:"Error",description:c.message,variant:"destructive"})}),l=mt({mutationFn:async({id:c,...d})=>{const{data:u,error:h}=await q.from("recruit_prospects").update({...d,updated_at:new Date().toISOString()}).eq("id",c).select().single();if(h)throw h;return u},onSuccess:()=>{t.invalidateQueries({queryKey:["recruit-prospects",s]})},onError:c=>n({title:"Error",description:c.message,variant:"destructive"})}),o=mt({mutationFn:async c=>{const{error:d}=await q.from("recruit_prospects").delete().eq("id",c);if(d)throw d},onSuccess:()=>{t.invalidateQueries({queryKey:["recruit-prospects",s]}),n({title:"Prospect removed"})}});return{stages:r.data||[],prospects:a.data||[],isLoading:r.isLoading||a.isLoading,addProspect:i,updateProspect:l,deleteProspect:o}}function xnr(s){const t=Bt(),{toast:n}=vi(),r=at({queryKey:["recruit-activities",s],queryFn:async()=>{if(!s)return[];const{data:i,error:l}=await q.from("recruit_activities").select("*").eq("prospect_id",s).order("created_at",{ascending:!1});if(l)throw l;return i},enabled:!!s}),a=mt({mutationFn:async i=>{const{data:{user:l}}=await q.auth.getUser();if(!l)throw new Error("Not authenticated");const{data:o,error:c}=await q.from("recruit_activities").insert({...i,created_by:l.id}).select().single();if(c)throw c;return o},onSuccess:()=>{t.invalidateQueries({queryKey:["recruit-activities",s]}),n({title:"Activity logged"})},onError:i=>n({title:"Error",description:i.message,variant:"destructive"})});return{activities:r.data||[],isLoading:r.isLoading,addActivity:a}}const v4t=(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 Yat({open:s,onOpenChange:t,stages:n,defaultStageId:r,onSubmit:a,isSubmitting:i}){const[l,o]=_.useState(v4t(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(v4t(r,n)),t(!1)};return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Ds,{children:"Add Recruit Prospect"})}),e.jsxs("form",{onSubmit:d,className:"space-y-4",children:[e.jsxs(Yr,{defaultValue:"basic",className:"w-full",children:[e.jsxs(Zr,{className:"grid w-full grid-cols-4",children:[e.jsx(Ht,{value:"basic",children:"Basic Info"}),e.jsx(Ht,{value:"production",children:"Production"}),e.jsx(Ht,{value:"social",children:"Social & Web"}),e.jsx(Ht,{value:"personal",children:"Personal"})]}),e.jsxs(Gt,{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(J,{children:"First Name *"}),e.jsx(xe,{required:!0,value:l.first_name,onChange:c("first_name")})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Last Name"}),e.jsx(xe,{value:l.last_name,onChange:c("last_name")})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Email"}),e.jsx(xe,{type:"email",value:l.email,onChange:c("email")})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Phone"}),e.jsx(xe,{value:l.phone,onChange:c("phone")})]})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Current Brokerage"}),e.jsx(xe,{value:l.current_brokerage,onChange:c("current_brokerage")})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(J,{children:"License #"}),e.jsx(xe,{value:l.license_number,onChange:c("license_number")})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Experience (years)"}),e.jsx(xe,{type:"number",min:"0",value:l.experience_years,onChange:c("experience_years")})]})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Address"}),e.jsx(xe,{placeholder:"Street address",value:l.address,onChange:c("address")})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(J,{children:"City"}),e.jsx(xe,{value:l.city,onChange:c("city")})]}),e.jsxs("div",{children:[e.jsx(J,{children:"State"}),e.jsx(xe,{value:l.state,onChange:c("state")})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Zip"}),e.jsx(xe,{value:l.zip_code,onChange:c("zip_code")})]})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Pipeline Stage"}),e.jsxs(is,{value:l.stage_id,onValueChange:u=>o(h=>({...h,stage_id:u})),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsx(as,{children:n.map(u=>e.jsx(He,{value:u.id,children:u.name},u.id))})]})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Referred By"}),e.jsx(xe,{placeholder:"Who referred this prospect?",value:l.referred_by,onChange:c("referred_by")})]})]}),e.jsxs(Gt,{value:"production",className:"space-y-4 mt-4",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Annual Production Volume"}),e.jsx(xe,{placeholder:"e.g. $5M, 20 transactions",value:l.annual_production,onChange:c("annual_production")})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Last Year Volume"}),e.jsx(xe,{placeholder:"e.g. $8.2M",value:l.last_year_volume,onChange:c("last_year_volume")})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Last Year Transactions"}),e.jsx(xe,{type:"number",min:"0",placeholder:"e.g. 24",value:l.last_year_transactions,onChange:c("last_year_transactions")})]})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Avg Sale Price"}),e.jsx(xe,{placeholder:"e.g. $350K",value:l.avg_sale_price,onChange:c("avg_sale_price")})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Specialties / Niche"}),e.jsx(xe,{placeholder:"e.g. Luxury, First-time buyers, Investment",value:l.specialties,onChange:c("specialties")})]})]}),e.jsxs(Gt,{value:"social",className:"space-y-4 mt-4",children:[e.jsxs("div",{children:[e.jsx(J,{children:"LinkedIn URL"}),e.jsx(xe,{type:"url",placeholder:"https://linkedin.com/in/...",value:l.linkedin_url,onChange:c("linkedin_url")})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Website URL"}),e.jsx(xe,{type:"url",placeholder:"https://...",value:l.website_url,onChange:c("website_url")})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Instagram Handle"}),e.jsx(xe,{placeholder:"@handle",value:l.instagram_handle,onChange:c("instagram_handle")})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Facebook URL"}),e.jsx(xe,{type:"url",placeholder:"https://facebook.com/...",value:l.facebook_url,onChange:c("facebook_url")})]})]}),e.jsxs(Gt,{value:"personal",className:"space-y-4 mt-4",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Birthday"}),e.jsx(xe,{type:"date",value:l.birthday,onChange:c("birthday")})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Spouse / Partner Name"}),e.jsx(xe,{value:l.spouse_name,onChange:c("spouse_name")})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Interests / Hobbies"}),e.jsx(xe,{placeholder:"Golf, travel, community events...",value:l.interests,onChange:c("interests")})]})]})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Notes"}),e.jsx(Ms,{value:l.notes,onChange:c("notes"),rows:3})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(B,{type:"submit",disabled:i,children:"Add Prospect"})]})]})]})})}function sDe(){const{user:s}=hs();return at({queryKey:["recruit-email-senders",s==null?void 0:s.id],enabled:!!s,staleTime:6e4,queryFn:async()=>{const[t,n]=await Promise.all([q.from("user_verified_senders").select("email, display_name, status").eq("user_id",s.id).eq("status","verified").limit(1).maybeSingle(),q.from("gmail_integrations").select("gmail_email, is_active").eq("user_id",s.id).eq("is_active",!0).maybeSingle()]);return{massEmail:t.data?{email:t.data.email,displayName:t.data.display_name}:null,gmail:n.data?{email:n.data.gmail_email}:null}}})}function Zat({value:s,onChange:t}){const{data:n,isLoading:r}=sDe();return e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Send from"}),e.jsxs(is,{value:s,onValueChange:a=>t(a),disabled:r,children:[e.jsx(rs,{className:"mt-1",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{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(He,{value:"mass_email",disabled:!(n!=null&&n.massEmail),children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(XO,{className:"h-3.5 w-3.5"}),"Mass Email",n!=null&&n.massEmail?` (${n.massEmail.email})`:" — not configured"]})}),e.jsx(He,{value:"gmail",disabled:!(n!=null&&n.gmail),children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(ln,{className:"h-3.5 w-3.5"}),"Gmail",n!=null&&n.gmail?` (${n.gmail.email})`:" — not connected"]})})]})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-1",children:"Mass Email and Gmail use your own verified sender. Configure them under Integrations."})]})}function krs({open:s,onOpenChange:t,recruitVideoId:n,brokerageId:r,prospectName:a,prospectEmail:i,videoTitle:l,defaultMessage:o}){const c=(a||"").split(" ")[0]||"there",[d,u]=_.useState(""),[h,m]=_.useState(""),[p,f]=_.useState("default"),[y,v]=_.useState(!1),g=Bt(),{data:b}=sDe();_.useEffect(()=>{s&&(u(`${c}, I made you a quick video 🎥`),m(o||""),f(b!=null&&b.massEmail?"mass_email":b!=null&&b.gmail?"gmail":"default"))},[s,c,o,b==null?void 0:b.massEmail,b==null?void 0:b.gmail]);const j=async()=>{var S,C;if(!i){se.error("This prospect has no email address on file.");return}v(!0);try{const{data:E,error:P}=await q.functions.invoke("send-recruit-video-email",{body:{recruit_video_ids:[n],brokerage_id:r,subject_override:d.trim()||void 0,message_override:h.trim()||void 0,send_via:p}});if(P)throw P;if(((E==null?void 0:E.sent)??0)>0)se.success(`Email sent to ${i}`),g.invalidateQueries({queryKey:["recruit-videos"]}),g.invalidateQueries({queryKey:["recruit-videos-prospect"]}),t(!1);else{const I=((C=(S=E==null?void 0:E.results)==null?void 0:S[0])==null?void 0:C.error)||"Failed to send";se.error(I)}}catch(E){se.error((E==null?void 0:E.message)||"Failed to send email")}finally{v(!1)}};return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"max-w-lg",children:[e.jsx(Os,{children:e.jsxs(Ds,{className:"flex items-center gap-2",children:[e.jsx(ln,{className:"h-5 w-5"})," Email video to ",a]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"To"}),e.jsx(xe,{value:i||"— no email on file —",disabled:!0,className:"mt-1"})]}),e.jsx(Zat,{value:p,onChange:f}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Subject"}),e.jsx(xe,{value:d,onChange:S=>u(S.target.value),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Personal message (optional)"}),e.jsx(Ms,{value:h,onChange:S=>m(S.target.value),rows:5,placeholder:`Hi ${c}, wanted to share a quick video...`,className:"mt-1"})]}),l&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Video: ",e.jsx("span",{className:"font-medium",children:l})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"ghost",onClick:()=>t(!1),disabled:y,children:"Cancel"}),e.jsxs(B,{onClick:j,disabled:y||!i,children:[y?e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Or,{className:"h-4 w-4 mr-2"}),"Send Email"]})]})]})})}function R4(s){return s?s.share_token?`https://video.relevelup.com/thumb/${s.share_token}`:s.thumbnail_url||s.preview_url||null:null}const WYe=[{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 gnr(s){return at({queryKey:["recruit-videos",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("recruit_videos").select(` *, prospect:recruit_prospects(id, first_name, last_name, email, phone, current_brokerage), video:agent_videos(id, title, thumbnail_url, playback_url, preview_url, duration_seconds, status, share_token) `).eq("brokerage_id",s).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function ynr(s){return at({queryKey:["recruit-videos-prospect",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("recruit_videos").select(` *, video:agent_videos(id, title, thumbnail_url, playback_url, preview_url, duration_seconds, status, share_token) `).eq("prospect_id",s).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function Srs(){const s=Bt(),{toast:t}=vi();return mt({mutationFn:async n=>{const{data:{user:r}}=await q.auth.getUser();if(!r)throw new Error("Not authenticated");const{data:a,error:i}=await q.from("recruit_videos").insert({prospect_id:n.prospect_id,video_id:n.video_id,brokerage_id:n.brokerage_id,message:n.message||null,created_by:r.id}).select("*, prospect:recruit_prospects(id, first_name, last_name, email, phone, current_brokerage), video:agent_videos(id, title, thumbnail_url, playback_url, preview_url, duration_seconds, status, share_token)").single();if(i)throw i;return a},onSuccess:n=>{s.invalidateQueries({queryKey:["recruit-videos"]}),s.invalidateQueries({queryKey:["recruit-videos-prospect",n.prospect_id]}),t({title:"Video linked to prospect"})},onError:n=>t({title:"Error",description:n.message,variant:"destructive"})})}function Crs(){const s=Bt();return mt({mutationFn:async({id:t,sent_via:n})=>{const{error:r}=await q.from("recruit_videos").update({sent_at:new Date().toISOString(),sent_via:n,updated_at:new Date().toISOString()}).eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["recruit-videos"]})}})}function Ars(s){return at({queryKey:["recruit-video-scripts",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("recruit_video_scripts").select("*").or(`brokerage_id.eq.${s},is_global.eq.true`).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function vnr(){const s=Bt(),{toast:t}=vi();return mt({mutationFn:async n=>{const{data:{user:r}}=await q.auth.getUser();if(!r)throw new Error("Not authenticated");const{data:a,error:i}=await q.from("recruit_video_scripts").insert({...n,created_by:r.id}).select().single();if(i)throw i;return a},onSuccess:()=>{s.invalidateQueries({queryKey:["recruit-video-scripts"]}),t({title:"Script saved"})},onError:n=>t({title:"Error",description:n.message,variant:"destructive"})})}function bnr(){const s=Bt();return mt({mutationFn:async t=>{const{error:n}=await q.from("recruit_video_scripts").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["recruit-video-scripts"]})}})}function _nr({prospectId:s,prospectName:t,prospectEmail:n,brokerageId:r}){var H;const{data:a=[],isLoading:i}=ynr(s),{data:l=[]}=Ars(r),o=Srs(),c=TC();Crs();const[d,u]=_.useState("idle"),[h,m]=_.useState(0),[p,f]=_.useState(0),[y,v]=_.useState(""),[g,b]=_.useState(""),[j,S]=_.useState(!1),[C,E]=_.useState(null),[P,M]=_.useState(null),[I,D]=_.useState(null),O=((H=l.find(Y=>Y.id===y))==null?void 0:H.script_text)||"",V=()=>{u("idle"),m(0),f(0),v(""),b("")},G=_.useCallback(async(Y,Z)=>{u("uploading");try{const ne=`Recruiting: ${t}`,{videoId:ce,libraryId:ie}=await PL(ne),{uploadUrl:te,apiKey:ae}=await LL(ce),le=new XMLHttpRequest;le.upload.onprogress=ze=>{ze.lengthComputable&&m(ze.loaded/ze.total*100)},await new Promise((ze,ke)=>{le.onload=()=>le.status>=200&&le.status<300?ze():ke(new Error("Upload failed")),le.onerror=()=>ke(new Error("Upload failed")),le.open("PUT",te),le.setRequestHeader("AccessKey",ae),le.send(Y)}),u("processing");let be=0;const me=Date.now(),he=9e4,pe=`https://iframe.mediadelivery.net/embed/${ie}/${ce}`;for(;be<4&&(await new Promise(ke=>setTimeout(ke,3e3)),!(Date.now()-me>he));){const ze=await TN(ce);if(be=ze.status,f(ze.encodeProgress||0),be===5||be===6)throw new Error("Video processing failed")}const Ce=await TN(ce),Ae=(Ce.storageSize||Y.size)/(1024*1024),Pe=await c.mutateAsync({bunny_video_id:ce,playback_url:Ce.directPlayUrl||pe,thumbnail_url:Ce.thumbnailUrl,preview_url:Ce.previewUrl||null,duration_seconds:Ce.length||Z,file_size_mb:Ae,title:ne,status:be>=4?"ready":"processing",touch_type:"recruiting"});await o.mutateAsync({prospect_id:s,video_id:Pe.id,brokerage_id:r,message:g||void 0}),u("done"),se.success("Video recorded and linked to prospect!"),setTimeout(()=>{S(!1),V()},1500)}catch(ne){se.error(ne.message||"Failed to upload video"),u("record")}},[s,t,r,g,c,o]),$=Y=>{Y&&(navigator.clipboard.writeText(`${window.location.origin}/recruit-video/${Y}`),se.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(Kr,{className:"h-4 w-4"})," Video Outreach"]}),e.jsxs(Ls,{open:j,onOpenChange:Y=>{!Y&&(d==="uploading"||d==="processing")||(S(Y),Y||V())},children:[e.jsx(nl,{asChild:!0,children:e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>u("script"),children:[e.jsx(rn,{className:"h-3.5 w-3.5 mr-1"})," Record Video"]})}),e.jsxs(Ps,{className:"max-w-2xl",children:[e.jsx(Os,{children:e.jsxs(Ds,{children:["Record Video for ",t]})}),d==="script"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Choose a Script (optional)"}),e.jsxs(is,{value:y,onValueChange:v,children:[e.jsx(rs,{className:"mt-1",children:e.jsx(ls,{placeholder:"No script — speak freely"})}),e.jsxs(as,{children:[e.jsx(He,{value:"none",children:"No script"}),l.map(Y=>{var Z;return e.jsx(He,{value:Y.id,children:e.jsxs("span",{className:"flex items-center gap-2",children:[Y.title,e.jsx(Oe,{variant:"outline",className:"text-[9px] ml-1",children:(Z=WYe.find(ne=>ne.value===Y.category))==null?void 0:Z.label})]})},Y.id)})]})]}),O&&e.jsx("div",{className:"mt-2 p-3 bg-muted/50 rounded-md text-sm max-h-32 overflow-y-auto whitespace-pre-wrap",children:O})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Personal Message (shown on landing page)"}),e.jsx(Ms,{value:g,onChange:Y=>b(Y.target.value),placeholder:`Hi ${t.split(" ")[0]}, I'd love to chat about what we're building here...`,rows:3,className:"mt-1"})]}),e.jsxs(B,{onClick:()=>u("record"),className:"w-full",children:[e.jsx(Kr,{className:"h-4 w-4 mr-2"})," Start Recording"]})]}),d==="record"&&e.jsx($E,{maxDurationSeconds:600,onRecordingComplete:G,teleprompterContent:O||void 0}),d==="uploading"&&e.jsxs("div",{className:"py-8 space-y-4 text-center",children:[e.jsx("p",{className:"font-medium",children:"Uploading video…"}),e.jsx(Fi,{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(Fi,{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(Jd,{className:"h-6 w-6 text-emerald-600"})}),e.jsx("p",{className:"font-medium text-emerald-600",children:"Video ready!"})]})]})]})]}),i?e.jsx("div",{className:"text-center py-4",children:e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-primary border-t-transparent mx-auto"})}):a.length===0?e.jsx("p",{className:"text-xs text-muted-foreground text-center py-3",children:"No videos sent yet"}):e.jsx("div",{className:"space-y-2",children:a.map(Y=>{var Z;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:R4(Y.video)?e.jsx("img",{src:R4(Y.video),alt:"",className:"h-full w-full object-cover",referrerPolicy:"no-referrer"}):e.jsx("div",{className:"h-full w-full flex items-center justify-center",children:e.jsx(Kr,{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:((Z=Y.video)==null?void 0:Z.title)||"Untitled"}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[Y.view_count>0?e.jsxs(Oe,{variant:"secondary",className:"text-[9px] h-4",children:[e.jsx(ya,{className:"h-2.5 w-2.5 mr-0.5"}),Y.view_count]}):Y.sent_at?e.jsxs(Oe,{variant:"outline",className:"text-[9px] h-4",children:[e.jsx(Or,{className:"h-2.5 w-2.5 mr-0.5"}),"Sent"]}):e.jsxs(Oe,{variant:"outline",className:"text-[9px] h-4",children:[e.jsx(Gr,{className:"h-2.5 w-2.5 mr-0.5"}),"Draft"]}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:Hs(new Date(Y.created_at),"MMM d")})]})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>$(Y.share_token),title:"Copy link",children:e.jsx(Ia,{className:"h-3 w-3"})}),e.jsxs(B,{variant:Y.sent_at?"ghost":"default",size:"sm",className:"h-7 gap-1",disabled:!n,onClick:()=>{var ne;E(Y.id),M(((ne=Y.video)==null?void 0:ne.title)||null),D(Y.message||null)},title:n?"Email video to prospect":"No email on file",children:[e.jsx(ln,{className:"h-3 w-3"}),e.jsx("span",{className:"text-[10px]",children:Y.sent_at?"Resend":"Email"})]})]})]},Y.id)})}),C&&e.jsx(krs,{open:!!C,onOpenChange:Y=>{Y||E(null)},recruitVideoId:C,brokerageId:r,prospectName:t,prospectEmail:n,videoTitle:P,defaultMessage:I})]})}function wnr({brokerageId:s,onSelect:t}){const{data:n=[],isLoading:r}=at({queryKey:["recruit-email-templates",s??"global-only"],queryFn:async()=>{let i=q.from("recruit_email_templates").select("id,brokerage_id,category,title,subject,body,sort_order").eq("is_active",!0).order("sort_order");s?i=i.or(`brokerage_id.is.null,brokerage_id.eq.${s}`):i=i.is("brokerage_id",null);const{data:l,error:o}=await i;if(o)throw o;return l}}),a=n.reduce((i,l)=>{var o;return(i[o=l.category]||(i[o]=[])).push(l),i},{});return e.jsxs(tu,{children:[e.jsx(su,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"gap-2",type:"button",children:[e.jsx(Fr,{className:"h-4 w-4"}),"Use Template",e.jsx(tl,{className:"h-3.5 w-3.5 opacity-60"})]})}),e.jsx(Od,{align:"end",className:"w-80 max-h-[420px] overflow-y-auto",children:r?e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(Ct,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):n.length===0?e.jsx("div",{className:"px-3 py-4 text-xs text-muted-foreground text-center",children:"No templates available."}):Object.entries(a).map(([i,l],o)=>e.jsxs("div",{children:[o>0&&e.jsx(M0,{}),e.jsx(PP,{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:i}),l.map(c=>e.jsxs(ca,{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(Oe,{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 jnr({open:s,onOpenChange:t,prospectId:n,brokerageId:r,prospectName:a,prospectEmail:i}){const{user:l}=hs(),o=(a||"").split(" ")[0]||"there",[c,d]=_.useState(""),[u,h]=_.useState(""),[m,p]=_.useState("default"),[f,y]=_.useState(!1),[v,g]=_.useState(null),[b,j]=_.useState(!1),S=Bt(),{data:C}=sDe();_.useEffect(()=>{if(s){d(`Hi ${o}`),h("");const O=C!=null&&C.massEmail?"mass_email":C!=null&&C.gmail?"gmail":"default";p(O),g(null),j(!1)}},[s,o,C==null?void 0:C.massEmail,C==null?void 0:C.gmail]);const{data:E=[],isLoading:P}=at({queryKey:["prospect-email-video-library",l==null?void 0:l.id],queryFn:async()=>{const{data:O,error:V}=await q.from("agent_videos").select("id, title, thumbnail_url, duration_seconds, touch_type, created_at, share_token").eq("owner_user_id",l.id).eq("status","ready").eq("is_deleted",!1).order("created_at",{ascending:!1}).limit(50);if(V)throw V;return O??[]},enabled:s&&!!(l!=null&&l.id)}),M=E.find(O=>O.id===v)||null,I=async()=>{var O,V;if(!i){se.error("This prospect has no email address on file.");return}if(!c.trim()||!u.trim()){se.error("Subject and message are required.");return}y(!0);try{if(v){const{data:G}=await q.from("recruit_videos").select("id").eq("prospect_id",n).eq("video_id",v).maybeSingle();let $=G==null?void 0:G.id;if(!$){const{data:ne,error:ce}=await q.from("recruit_videos").insert({prospect_id:n,video_id:v,brokerage_id:r,message:u.trim(),created_by:l.id}).select("id").single();if(ce)throw ce;$=ne.id}const{data:H,error:Y}=await q.functions.invoke("send-recruit-video-email",{body:{recruit_video_ids:[$],brokerage_id:r,subject_override:c.trim(),message_override:u.trim(),send_via:m}});if(Y)throw Y;if(((H==null?void 0:H.sent)??0)>0)se.success(`Email sent to ${i}`),S.invalidateQueries({queryKey:["recruit-videos"]}),S.invalidateQueries({queryKey:["recruit-videos-prospect",n]}),S.invalidateQueries({queryKey:["recruit-activities",n]}),S.invalidateQueries({queryKey:["recruit-sent-emails"]}),t(!1);else{const ne=((V=(O=H==null?void 0:H.results)==null?void 0:O[0])==null?void 0:V.error)||"Failed to send";se.error(ne)}}else{const{data:G,error:$}=await q.functions.invoke("send-recruit-prospect-email",{body:{prospect_id:n,brokerage_id:r,subject:c.trim(),message:u.trim(),send_via:m}});if($)throw $;G!=null&&G.success?(se.success(`Email sent to ${i}`),S.invalidateQueries({queryKey:["recruit-activities",n]}),S.invalidateQueries({queryKey:["recruit-sent-emails"]}),t(!1)):se.error((G==null?void 0:G.error)||"Failed to send")}}catch(G){se.error((G==null?void 0:G.message)||"Failed to send email")}finally{y(!1)}},D=O=>{const V=G=>G.replace(/\[First Name\]/gi,o);d(V(O.subject)),h(V(O.body)),se.success(`Loaded "${O.title}"`)};return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsxs(Ds,{className:"flex items-center gap-2",children:[e.jsx(ln,{className:"h-5 w-5"})," Email ",a]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"To"}),e.jsx(xe,{value:i||"— no email on file —",disabled:!0,className:"mt-1"})]}),e.jsx(Zat,{value:m,onChange:p}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(J,{className:"text-xs",children:"Subject"}),e.jsx(wnr,{brokerageId:r,onSelect:D})]}),e.jsx(xe,{value:c,onChange:O=>d(O.target.value)}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Message"}),e.jsx(Ms,{value:u,onChange:O=>h(O.target.value),rows:8,placeholder:`Hi ${o}, wanted to reach out…`,className:"mt-1"})]}),e.jsxs("div",{className:"rounded-md border p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(J,{className:"text-xs flex items-center gap-1.5",children:[e.jsx(Kr,{className:"h-3.5 w-3.5"})," Include a video"]}),M?e.jsxs(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>{g(null),j(!1)},children:[e.jsx(Qn,{className:"h-3 w-3 mr-1"})," Remove"]}):e.jsx(B,{type:"button",variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>j(O=>!O),children:b?"Hide library":"Pick from library"})]}),M&&e.jsxs("div",{className:"flex items-center gap-3 p-2 rounded bg-muted/40",children:[e.jsx("div",{className:"h-10 w-16 rounded bg-muted overflow-hidden flex-shrink-0",children:R4(M)?e.jsx("img",{src:R4(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(Kr,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsx("p",{className:"text-xs font-medium truncate flex-1",children:M.title||"Untitled video"})]}),!M&&b&&e.jsx("div",{className:"max-h-56 overflow-y-auto space-y-1 -mx-1 px-1",children:P?e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(Ct,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):E.length===0?e.jsx("p",{className:"text-xs text-muted-foreground text-center py-3",children:"No videos in your library yet. Record one from a prospect to get started."}):E.map(O=>e.jsxs("button",{type:"button",onClick:()=>{g(O.id),j(!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:R4(O)?e.jsx("img",{src:R4(O),alt:"",className:"h-full w-full object-cover",referrerPolicy:"no-referrer"}):e.jsx("div",{className:"h-full w-full flex items-center justify-center",children:e.jsx(Kr,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-xs font-medium truncate",children:O.title||"Untitled video"}),O.duration_seconds&&e.jsxs("p",{className:"text-[10px] text-muted-foreground",children:[Math.floor(O.duration_seconds/60),":",String(Math.floor(O.duration_seconds%60)).padStart(2,"0")]})]})]},O.id))}),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(yr,{children:[e.jsx(B,{variant:"ghost",onClick:()=>t(!1),disabled:f,children:"Cancel"}),e.jsxs(B,{onClick:I,disabled:f||!i,children:[f?e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Or,{className:"h-4 w-4 mr-2"}),"Send Email"]})]})]})})}function Nnr(s){return at({queryKey:["recruit-campaign-sends",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("recruit_campaign_sends").select("id, prospect_id, subject, email_number, status, sent_at, opened_at, clicked_at, error_message, created_at").eq("prospect_id",s).neq("status","failed").order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}const b4t=[{value:"call",label:"Phone Call",icon:_a},{value:"email",label:"Email",icon:ln},{value:"text",label:"Text Message",icon:Hi},{value:"meeting",label:"Meeting",icon:ga},{value:"note",label:"Note",icon:Fr},{value:"campaign_email",label:"Campaign Email",icon:Or}];function jw({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 Dde({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(wr,{className:"h-3 w-3 opacity-50"})]}):null}function yp({label:s,value:t,onChange:n,type:r="text",placeholder:a}){return e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:s}),e.jsx(xe,{type:r,value:t,onChange:i=>n(i.target.value),placeholder:a,className:"mt-1 h-8 text-sm"})]})}function Xat({prospect:s,stages:t,brokerageId:n,open:r,onOpenChange:a,onUpdate:i,onDelete:l}){const{activities:o,addActivity:c}=xnr((s==null?void 0:s.id)||null),{data:d=[]}=Nnr((s==null?void 0:s.id)||null),[u,h]=_.useState({type:"note",title:"",description:""}),[m,p]=_.useState(!1),[f,y]=_.useState(!1),[v,g]=_.useState({}),[b,j]=_.useState(!1);if(!s)return null;const S=()=>{var $,H;g({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:(($=s.experience_years)==null?void 0:$.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:((H=s.last_year_transactions)==null?void 0:H.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||""}),y(!0)},C=()=>{const $={id:s.id};for(const[H,Y]of Object.entries(v))H==="experience_years"||H==="last_year_transactions"?$[H]=Y?parseInt(Y):null:$[H]=Y||null;i($),y(!1)},E=()=>y(!1),P=$=>H=>g(Y=>({...Y,[$]:H})),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($=>$.id===s.stage_id),D=s.address||s.city||s.state,O=s.last_year_volume||s.last_year_transactions||s.avg_sale_price||s.specialties||s.annual_production,V=s.linkedin_url||s.website_url||s.instagram_handle||s.facebook_url,G=s.birthday||s.spouse_name||s.interests||s.referred_by;return e.jsxs(qg,{open:r,onOpenChange:$=>{$||y(!1),a($)},children:[e.jsx(hg,{className:"w-full sm:max-w-lg p-0",children:e.jsx(Ji,{className:"h-full",children:e.jsxs("div",{className:"p-6 space-y-5",children:[e.jsx(P0,{children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsxs(L0,{className:"text-xl",children:[s.first_name," ",s.last_name]}),I&&e.jsx(Oe,{variant:"outline",style:{borderColor:I.color,color:I.color},className:"mt-1",children:I.name})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[f?e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:E,children:e.jsx(Qn,{className:"h-4 w-4"})}),e.jsx(B,{variant:"default",size:"icon",onClick:C,children:e.jsx(Ho,{className:"h-4 w-4"})})]}):e.jsx(B,{variant:"ghost",size:"icon",onClick:S,title:"Edit prospect",children:e.jsx(Ya,{className:"h-4 w-4"})}),e.jsxs(Kl,{children:[e.jsx(jx,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Sn,{className:"h-4 w-4"})})}),e.jsxs(Ol,{children:[e.jsxs(zl,{children:[e.jsx(Ul,{children:"Delete prospect?"}),e.jsx(ql,{children:"This will permanently remove this prospect and all their activity history."})]}),e.jsxs(Bl,{children:[e.jsx($l,{children:"Cancel"}),e.jsx(Ml,{onClick:()=>{l(s.id),a(!1)},children:"Delete"})]})]})]})]})]})}),!f&&e.jsxs("div",{className:"space-y-2 text-sm",children:[s.email&&e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground min-w-0",children:[e.jsx(ln,{className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:s.email})]}),e.jsxs(B,{size:"sm",variant:"outline",className:"h-7 gap-1.5 flex-shrink-0",onClick:()=>j(!0),children:[e.jsx(ln,{className:"h-3 w-3"})," Email"]})]}),s.phone&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(_a,{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(Xa,{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(J,{className:"text-xs text-muted-foreground",children:"Move to Stage"}),e.jsxs(is,{value:s.stage_id||"",onValueChange:$=>i({id:s.id,stage_id:$}),children:[e.jsx(rs,{className:"mt-1",children:e.jsx(ls,{})}),e.jsx(as,{children:t.map($=>e.jsx(He,{value:$.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:$.color}}),$.name]})},$.id))})]})]}),e.jsxs(Yr,{defaultValue:"details",className:"w-full",children:[e.jsxs(Zr,{className:"grid w-full grid-cols-4 h-8 text-xs",children:[e.jsx(Ht,{value:"details",className:"text-xs",children:"Details"}),e.jsx(Ht,{value:"production",className:"text-xs",children:"Production"}),e.jsx(Ht,{value:"social",className:"text-xs",children:"Social"}),e.jsx(Ht,{value:"personal",className:"text-xs",children:"Personal"})]}),f?e.jsxs(e.Fragment,{children:[e.jsxs(Gt,{value:"details",className:"mt-3 space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(yp,{label:"First Name",value:v.first_name,onChange:P("first_name")}),e.jsx(yp,{label:"Last Name",value:v.last_name,onChange:P("last_name")})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(yp,{label:"Email",value:v.email,onChange:P("email"),type:"email"}),e.jsx(yp,{label:"Phone",value:v.phone,onChange:P("phone")})]}),e.jsx(yp,{label:"Current Brokerage",value:v.current_brokerage,onChange:P("current_brokerage")}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(yp,{label:"License #",value:v.license_number,onChange:P("license_number")}),e.jsx(yp,{label:"Experience (years)",value:v.experience_years,onChange:P("experience_years"),type:"number"})]}),e.jsx(yp,{label:"Address",value:v.address,onChange:P("address"),placeholder:"Street address"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsx(yp,{label:"City",value:v.city,onChange:P("city")}),e.jsx(yp,{label:"State",value:v.state,onChange:P("state")}),e.jsx(yp,{label:"Zip",value:v.zip_code,onChange:P("zip_code")})]}),e.jsx(yp,{label:"Source",value:v.source,onChange:P("source")}),e.jsx(yp,{label:"Referred By",value:v.referred_by,onChange:P("referred_by")}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Notes"}),e.jsx(Ms,{value:v.notes,onChange:$=>g(H=>({...H,notes:$.target.value})),rows:3,className:"mt-1 text-sm"})]})]}),e.jsxs(Gt,{value:"production",className:"mt-3 space-y-3",children:[e.jsx(yp,{label:"Annual Production",value:v.annual_production,onChange:P("annual_production"),placeholder:"e.g. $5M"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(yp,{label:"Last Year Volume",value:v.last_year_volume,onChange:P("last_year_volume"),placeholder:"e.g. $8.2M"}),e.jsx(yp,{label:"Last Year Transactions",value:v.last_year_transactions,onChange:P("last_year_transactions"),type:"number",placeholder:"e.g. 24"})]}),e.jsx(yp,{label:"Avg Sale Price",value:v.avg_sale_price,onChange:P("avg_sale_price"),placeholder:"e.g. $350K"}),e.jsx(yp,{label:"Specialties / Niche",value:v.specialties,onChange:P("specialties"),placeholder:"e.g. Luxury, Investment"})]}),e.jsxs(Gt,{value:"social",className:"mt-3 space-y-3",children:[e.jsx(yp,{label:"LinkedIn URL",value:v.linkedin_url,onChange:P("linkedin_url"),type:"url",placeholder:"https://linkedin.com/in/..."}),e.jsx(yp,{label:"Website URL",value:v.website_url,onChange:P("website_url"),type:"url",placeholder:"https://..."}),e.jsx(yp,{label:"Instagram Handle",value:v.instagram_handle,onChange:P("instagram_handle"),placeholder:"@handle"}),e.jsx(yp,{label:"Facebook URL",value:v.facebook_url,onChange:P("facebook_url"),type:"url",placeholder:"https://facebook.com/..."})]}),e.jsxs(Gt,{value:"personal",className:"mt-3 space-y-3",children:[e.jsx(yp,{label:"Birthday",value:v.birthday,onChange:P("birthday"),type:"date"}),e.jsx(yp,{label:"Spouse / Partner",value:v.spouse_name,onChange:P("spouse_name")}),e.jsx(yp,{label:"Interests / Hobbies",value:v.interests,onChange:P("interests"),placeholder:"Golf, travel, community events..."})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(Gt,{value:"details",className:"mt-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(jw,{label:"Current Brokerage",value:s.current_brokerage}),e.jsx(jw,{label:"License #",value:s.license_number}),e.jsx(jw,{label:"Experience",value:s.experience_years!=null?`${s.experience_years} years`:null}),e.jsx(jw,{label:"Referred By",value:s.referred_by}),e.jsx(jw,{label:"Source",value:s.source})]}),s.notes&&e.jsxs("div",{className:"mt-3",children:[e.jsx(J,{className:"text-xs text-muted-foreground",children:"Notes"}),e.jsx("p",{className:"text-sm mt-1 whitespace-pre-wrap",children:s.notes})]})]}),e.jsx(Gt,{value:"production",className:"mt-3",children:O?e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(jw,{label:"Annual Production",value:s.annual_production}),e.jsx(jw,{label:"Last Year Volume",value:s.last_year_volume}),e.jsx(jw,{label:"Last Year Transactions",value:s.last_year_transactions}),e.jsx(jw,{label:"Avg Sale Price",value:s.avg_sale_price}),e.jsx(jw,{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(Gt,{value:"social",className:"mt-3",children:V?e.jsxs("div",{className:"space-y-2",children:[e.jsx(Dde,{label:"LinkedIn",url:s.linkedin_url,icon:dg}),e.jsx(Dde,{label:"Website",url:s.website_url,icon:sl}),s.instagram_handle&&e.jsx(Dde,{label:s.instagram_handle,url:`https://instagram.com/${s.instagram_handle.replace("@","")}`,icon:Im}),e.jsx(Dde,{label:"Facebook",url:s.facebook_url,icon:tf})]}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No social profiles added yet"})}),e.jsx(Gt,{value:"personal",className:"mt-3",children:G?e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(jw,{label:"Birthday",value:s.birthday?Hs(new Date(s.birthday+"T00:00:00"),"MMMM d, yyyy"):null,icon:Vo}),e.jsx(jw,{label:"Spouse / Partner",value:s.spouse_name,icon:Do}),e.jsx("div",{className:"col-span-2",children:e.jsx(jw,{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(_nr,{prospectId:s.id,prospectName:`${s.first_name} ${s.last_name||""}`,prospectEmail:s.email,brokerageId:n}),e.jsx(wc,{}),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(B,{size:"sm",variant:"outline",onClick:()=>p(!m),children:[e.jsx(rn,{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(is,{value:u.type,onValueChange:$=>h(H=>({...H,type:$})),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsx(as,{children:b4t.map($=>e.jsx(He,{value:$.value,children:$.label},$.value))})]}),e.jsx(xe,{placeholder:"Subject / Title",value:u.title,onChange:$=>h(H=>({...H,title:$.target.value}))}),e.jsx(Ms,{placeholder:"Details (optional)",value:u.description,onChange:$=>h(H=>({...H,description:$.target.value})),rows:2}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>p(!1),children:"Cancel"}),e.jsx(B,{size:"sm",onClick:M,disabled:!u.title.trim(),children:"Save"})]})]}),e.jsx("div",{className:"space-y-3",children:(()=>{const $=[...o.map(H=>({type:"manual",data:H,date:H.created_at})),...d.map(H=>({type:"campaign_email",data:H,date:H.sent_at||H.created_at}))].sort((H,Y)=>new Date(Y.date).getTime()-new Date(H.date).getTime());return $.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No activity logged yet"}):$.map(H=>{if(H.type==="manual"){const Z=H.data,ne=b4t.find(ie=>ie.value===Z.activity_type),ce=(ne==null?void 0:ne.icon)||Fr;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(ce,{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:Z.title}),Z.description&&e.jsx("p",{className:"text-muted-foreground text-xs mt-0.5",children:Z.description}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:Hs(new Date(Z.created_at),"MMM d, yyyy h:mm a")})]})]},`activity-${Z.id}`)}const Y=H.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(Or,{className:"h-3.5 w-3.5 text-primary"})})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:"font-medium",children:["Campaign Email #",Y.email_number]}),e.jsx("p",{className:"text-muted-foreground text-xs mt-0.5",children:Y.subject}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mt-1.5",children:[Y.status==="failed"?e.jsx(Oe,{variant:"destructive",className:"text-[10px] px-1.5 py-0 h-4",children:"Failed"}):e.jsxs(Oe,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 border-green-500 text-green-600",children:[e.jsx(Or,{className:"h-2.5 w-2.5 mr-0.5"})," Sent"]}),Y.opened_at?e.jsxs(Oe,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 border-blue-500 text-blue-600",children:[e.jsx(ya,{className:"h-2.5 w-2.5 mr-0.5"})," Opened ",Hs(new Date(Y.opened_at),"MMM d, h:mm a")]}):Y.status!=="failed"?e.jsx(Oe,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 text-muted-foreground",children:"Not opened"}):null,Y.clicked_at&&e.jsxs(Oe,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 border-purple-500 text-purple-600",children:[e.jsx(v0,{className:"h-2.5 w-2.5 mr-0.5"})," Clicked ",Hs(new Date(Y.clicked_at),"MMM d, h:mm a")]})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:Hs(new Date(Y.sent_at||Y.created_at),"MMM d, yyyy h:mm a")})]})]},`send-${Y.id}`)})})()})]})]})})}),e.jsx(jnr,{open:b,onOpenChange:j,prospectId:s.id,brokerageId:s.brokerage_id,prospectName:`${s.first_name} ${s.last_name??""}`.trim(),prospectEmail:s.email})]})}const knr=["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 Qat({open:s,onOpenChange:t,brokerageId:n,stages:r}){var D;const{toast:a}=vi(),i=Bt(),l=_.useRef(null),[o,c]=_.useState([]),[d,u]=_.useState([]),[h,m]=_.useState({}),[p,f]=_.useState(((D=r[0])==null?void 0:D.id)||""),[y,v]=_.useState(!1),[g,b]=_.useState("upload"),[j,S]=_.useState(0),C=()=>{c([]),u([]),m({}),b("upload"),S(0)},E=O=>{var $;const V=($=O.target.files)==null?void 0:$[0];if(!V)return;const G=new FileReader;G.onload=H=>{var ae;const Z=((ae=H.target)==null?void 0:ae.result).split(/\r?\n/).filter(le=>le.trim());if(Z.length<2){a({title:"Invalid CSV",description:"File must have a header row and at least one data row",variant:"destructive"});return}const ne=P(Z[0]);u(ne);const ce={},ie=new Set;ne.forEach((le,be)=>{const me=le.toLowerCase().replace(/[^a-z0-9]/g,"");let he=null;/^firstname$/.test(me)||me==="first"?he="first_name":/^lastname$/.test(me)||me==="last"?he="last_name":/^email$/.test(me)||me==="emailaddress"?he="email":/^mobile$|^phone$|^cellphone$|^mobilephone$/.test(me)?he="phone":/officename|currentbrokerage|brokerage|company/.test(me)?he="current_brokerage":/membernumber|licensenumber|license/.test(me)?he="license_number":/experienceyears|yearsexperience/.test(me)?he="experience_years":/^totalvolume$|annualproduction/.test(me)?he="annual_production":/^address$/.test(me)?he="address":/^city$/.test(me)?he="city":/^state$/.test(me)?he="state":/^postalcode$|^zip$|^zipcode$/.test(me)?he="zip_code":/listsidevolume|lastyearvolume/.test(me)?he="last_year_volume":/^totalcount$|lastyeartransactions/.test(me)?he="last_year_transactions":/avgsaleprice|averageprice/.test(me)?he="avg_sale_price":/linkedin/.test(me)?he="linkedin_url":/website/.test(me)?he="website_url":/specialt/.test(me)?he="specialties":/referr/.test(me)?he="referred_by":/^notes$|^note$/.test(me)&&(he="notes"),he&&!ie.has(he)&&(ce[String(be)]=he,ie.add(he))}),m(ce);const te=Z.slice(1).map(le=>{const be=P(le),me={};return ne.forEach((he,pe)=>{me[String(pe)]=be[pe]||""}),me});c(te),b("map")},G.readAsText(V)},P=O=>{const V=[];let G="",$=!1;for(const H of O)H==='"'?$=!$:H===","&&!$?(V.push(G.trim()),G=""):G+=H;return V.push(G.trim()),V},M=async()=>{v(!0);try{const{data:{user:O}}=await q.auth.getUser();if(!O)throw new Error("Not authenticated");const V=o.map($=>{const H={brokerage_id:n,created_by:O.id,stage_id:p,source:"csv_import",first_name:"Unknown"},Y=H;return Object.entries(h).forEach(([Z,ne])=>{var ie;const ce=(ie=$[Z])==null?void 0:ie.trim();ce&&(ne==="experience_years"||ne==="last_year_transactions"?Y[ne]=parseInt(ce.replace(/[^0-9.-]/g,""))||null:ne==="annual_production"||ne==="last_year_volume"||ne==="avg_sale_price"?Y[ne]=ce.replace(/[^0-9.$,.-]/g,""):Y[ne]=ce)}),H});let G=0;for(let $=0;${const O=`first_name,last_name,email,phone,current_brokerage,license_number,experience_years,annual_production,notes Jane,Smith,jane@example.com,555-0100,ABC Realty,RE12345,8,$5M,Met at conference`,V=new Blob([O],{type:"text/csv"}),G=URL.createObjectURL(V),$=document.createElement("a");$.href=G,$.download="recruit-prospects-template.csv",$.click(),URL.revokeObjectURL(G)};return e.jsx(Ls,{open:s,onOpenChange:O=>{O||C(),t(O)},children:e.jsxs(Ps,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Ds,{children:"Import Prospects from CSV"})}),g==="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(uS,{className:"h-10 w-10 mx-auto text-muted-foreground mb-3"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Upload a CSV file with prospect data"}),e.jsx("input",{ref:l,type:"file",accept:".csv",className:"hidden",onChange:E}),e.jsxs(B,{onClick:()=>{var O;return(O=l.current)==null?void 0:O.click()},children:[e.jsx(Oa,{className:"h-4 w-4 mr-2"})," Choose File"]})]}),e.jsx(B,{variant:"link",className:"text-xs",onClick:I,children:"Download CSV template"})]}),g==="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(is,{value:p,onValueChange:f,children:[e.jsx(rs,{className:"w-[180px]",children:e.jsx(ls,{})}),e.jsx(as,{children:r.map(O=>e.jsx(He,{value:O.id,children:O.name},O.id))})]})]})]}),e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{className:"w-[140px]",children:"CSV Column"}),e.jsx(Pt,{className:"w-[160px]",children:"Map To"}),e.jsx(Pt,{children:"Preview"})]})}),e.jsx(Ka,{children:d.map((O,V)=>{var G;return e.jsxs(pn,{children:[e.jsx(gt,{className:"font-medium text-xs",children:O}),e.jsx(gt,{children:e.jsxs(is,{value:h[String(V)]||"skip",onValueChange:$=>m(H=>({...H,[String(V)]:$==="skip"?"":$})),children:[e.jsx(rs,{className:"h-8 text-xs",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"skip",children:"— Skip —"}),knr.map($=>e.jsx(He,{value:$,children:$.replace(/_/g," ")},$))]})]})}),e.jsx(gt,{className:"text-xs text-muted-foreground truncate max-w-[200px]",children:((G=o[0])==null?void 0:G[String(V)])||"—"})]},V)})})]})}),!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(B,{variant:"outline",onClick:()=>{C()},children:"Back"}),e.jsx(B,{onClick:M,disabled:y||!Object.values(h).includes("first_name"),children:y?"Importing...":`Import ${o.length} Prospects`})]})]}),g==="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(ea,{className:"h-6 w-6 text-green-600"})}),e.jsxs("p",{className:"font-semibold",children:[j," prospects imported successfully!"]}),e.jsx(B,{onClick:()=>{C(),t(!1)},children:"Close"})]})]})})}function Ers({brokerageId:s}){const{stages:t,prospects:n,isLoading:r,addProspect:a,updateProspect:i,deleteProspect:l}=kz(s),[o,c]=_.useState(!1),[d,u]=_.useState(),[h,m]=_.useState(null),[p,f]=_.useState(!1),[y,v]=_.useState(!1),[g,b]=_.useState(null),[j,S]=_.useState(""),[C,E]=_.useState("all");if(r)return e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})});const P=[...new Set(n.map(H=>H.source).filter(H=>!!H))].sort(),M=n.filter(H=>{const Y=j.trim().toLowerCase();return(!Y||`${H.first_name} ${H.last_name||""} ${H.current_brokerage||""} ${H.email||""}`.toLowerCase().includes(Y))&&(C==="all"||H.source===C)}),I=H=>M.filter(Y=>Y.stage_id===H),D=(H,Y)=>{b(Y),H.dataTransfer.effectAllowed="move"},O=H=>{H.preventDefault(),H.dataTransfer.dropEffect="move"},V=(H,Y)=>{H.preventDefault(),g&&(i.mutate({id:g,stage_id:Y}),b(null))},G=H=>{u(H),c(!0)},$=H=>{m(H),f(!0)};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col gap-3 rounded-md border bg-card p-3 lg:flex-row lg:items-center lg:justify-between",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-2 sm:flex-row",children:[e.jsxs("div",{className:"relative min-w-0 flex-1 sm:max-w-sm",children:[e.jsx(Lr,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(xe,{className:"h-9 pl-9",value:j,onChange:H=>S(H.target.value),placeholder:"Search pipeline…"})]}),e.jsxs(is,{value:C,onValueChange:E,children:[e.jsxs(rs,{className:"h-9 w-full sm:w-[190px]",children:[e.jsx(D_,{className:"mr-2 h-3.5 w-3.5"}),e.jsx(ls,{})]}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All sources"}),P.map(H=>e.jsx(He,{value:H,children:H.replace(/_/g," ")},H))]})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(B,{variant:"outline",onClick:()=>v(!0),children:[e.jsx(Oa,{className:"h-4 w-4 mr-2"})," Import CSV"]}),e.jsxs(B,{onClick:()=>{u(void 0),c(!0)},children:[e.jsx(rn,{className:"h-4 w-4 mr-2"})," Add Prospect"]})]})]}),e.jsxs("div",{className:"flex items-center justify-between px-1",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Showing ",M.length," of ",n.length," prospects"]}),(j||C!=="all")&&e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>{S(""),E("all")},children:"Clear filters"})]}),e.jsxs(Ji,{className:"w-full",children:[e.jsx("div",{className:"flex gap-4 pb-4",style:{minWidth:t.length*300},children:t.map(H=>{const Y=I(H.id);return e.jsxs("div",{className:"w-[280px] flex-shrink-0 flex flex-col",onDragOver:O,onDrop:Z=>V(Z,H.id),children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between border-b pb-2 px-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-3 w-3 rounded-full",style:{backgroundColor:H.color}}),e.jsx("h3",{className:"font-semibold text-sm",children:H.name}),e.jsx(Oe,{variant:"secondary",className:"text-xs h-5 px-1.5",children:Y.length})]}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>G(H.id),children:e.jsx(rn,{className:"h-3.5 w-3.5"})})]}),e.jsx("div",{className:"min-h-[220px] space-y-2 rounded-md border border-dashed bg-muted/20 p-2",children:Y.map(Z=>e.jsx(ve,{className:"group cursor-pointer rounded-md border-l-4 p-3 shadow-xs transition-all hover:-translate-y-0.5 hover:border-primary/40 hover:shadow-md motion-reduce:hover:translate-y-0",style:{borderLeftColor:H.color},draggable:!0,onDragStart:ne=>D(ne,Z.id),onClick:()=>$(Z),children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Vf,{className:"mt-0.5 h-4 w-4 cursor-grab text-muted-foreground/40 opacity-40 transition-opacity group-hover:opacity-100"}),e.jsxs("div",{className:"flex-1 min-w-0 space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"truncate text-sm font-semibold",children:[Z.first_name," ",Z.last_name]}),Z.source&&e.jsx(Oe,{variant:"secondary",className:"h-5 shrink-0 px-1.5 text-[9px] capitalize",children:Z.source.replace(/_/g," ")})]}),Z.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:Z.current_brokerage})]}),(Z.annual_production||Z.last_year_volume||Z.specialties)&&e.jsx("p",{className:"truncate text-[11px] font-medium text-primary",children:Z.last_year_volume||Z.annual_production||Z.specialties}),e.jsxs("div",{className:"flex items-center justify-between gap-2 border-t pt-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[Z.email&&e.jsx(ln,{className:"h-3 w-3 text-muted-foreground"}),Z.phone&&e.jsx(_a,{className:"h-3 w-3 text-muted-foreground"}),!Z.email&&!Z.phone&&e.jsx("span",{className:"text-[10px] text-amber-700",children:"Contact info needed"})]}),Z.experience_years!=null&&e.jsxs(Oe,{variant:"secondary",className:"text-[10px] h-4 px-1",children:[Z.experience_years,"yr"]})]})]})]})},Z.id))})]},H.id)})}),e.jsx(Bre,{orientation:"horizontal"})]}),e.jsx(Yat,{open:o,onOpenChange:c,stages:t,defaultStageId:d,onSubmit:H=>a.mutate(H),isSubmitting:a.isPending}),e.jsx(Xat,{prospect:h,stages:t,brokerageId:s,open:p,onOpenChange:f,onUpdate:H=>{i.mutate(H),m(Y=>Y?{...Y,...H}:null)},onDelete:H=>l.mutate(H)}),e.jsx(Qat,{open:y,onOpenChange:v,brokerageId:s,stages:t})]})}function KYe({brokerageId:s}){const{stages:t,prospects:n,isLoading:r,addProspect:a,updateProspect:i,deleteProspect:l}=kz(s),{user:o}=hs(),c=Bt(),[d,u]=_.useState(!1),[h,m]=_.useState(null),[p,f]=_.useState(!1),[y,v]=_.useState(!1),[g,b]=_.useState(""),[j,S]=_.useState("all"),[C,E]=_.useState("all"),[P,M]=_.useState("all"),[I,D]=_.useState(null),[O,V]=_.useState("asc"),[G,$]=_.useState(new Set),[H,Y]=_.useState(!1),[Z,ne]=_.useState(""),ce=_.useMemo(()=>{const ke=new Set;return n.forEach(Ze=>{Ze.current_brokerage&&ke.add(Ze.current_brokerage)}),Array.from(ke).sort()},[n]),{data:ie=[]}=at({queryKey:["recruit-campaigns-list",s],queryFn:async()=>{const{data:ke,error:Ze}=await q.from("recruit_campaigns").select("id, name, warmth_level").or(`brokerage_id.is.null,brokerage_id.eq.${s}`).order("name");if(Ze)throw Ze;return ke}}),{data:te=[]}=at({queryKey:["recruit-campaign-assignments-lookup",s],queryFn:async()=>{let Ze=[],Se=0;for(;;){const{data:Fe,error:Ne}=await q.from("recruit_campaign_assignments").select("prospect_id, campaign_id, status").eq("brokerage_id",s).range(Se,Se+1e3-1);if(Ne)throw Ne;if(Ze=Ze.concat(Fe??[]),!Fe||Fe.length<1e3)break;Se+=1e3}return Ze}}),ae=_.useMemo(()=>{const ke=new Map;return te.forEach(Ze=>{ke.has(Ze.prospect_id)||ke.set(Ze.prospect_id,new Set),ke.get(Ze.prospect_id).add(Ze.campaign_id)}),ke},[te]),le=ke=>{I===ke?V(Ze=>Ze==="asc"?"desc":"asc"):(D(ke),V("asc"))},be=({column:ke})=>I!==ke?e.jsx(Lg,{className:"h-3.5 w-3.5 ml-1 text-muted-foreground/50"}):O==="asc"?e.jsx(sp,{className:"h-3.5 w-3.5 ml-1 text-primary"}):e.jsx(zf,{className:"h-3.5 w-3.5 ml-1 text-primary"}),me=ke=>t.find(Ze=>Ze.id===ke),he=_.useMemo(()=>{let ke=n.filter(Ze=>{var Ve,qe,Qe;const Se=!g||`${Ze.first_name} ${Ze.last_name}`.toLowerCase().includes(g.toLowerCase())||((Ve=Ze.email)==null?void 0:Ve.toLowerCase().includes(g.toLowerCase()))||((qe=Ze.current_brokerage)==null?void 0:qe.toLowerCase().includes(g.toLowerCase())),Fe=j==="all"||Ze.stage_id===j,Ne=C==="all"||Ze.current_brokerage===C;let Ye=!0;return P==="in_campaign"?Ye=ae.has(Ze.id):P==="not_in_campaign"?Ye=!ae.has(Ze.id):P!=="all"&&(Ye=((Qe=ae.get(Ze.id))==null?void 0:Qe.has(P))??!1),Se&&Fe&&Ne&&Ye});return I&&(ke=[...ke].sort((Ze,Se)=>{var Ve,qe;let Fe=null,Ne=null;switch(I){case"name":Fe=`${Ze.first_name} ${Ze.last_name||""}`.toLowerCase(),Ne=`${Se.first_name} ${Se.last_name||""}`.toLowerCase();break;case"stage":Fe=((Ve=me(Ze.stage_id))==null?void 0:Ve.sort_order)??999,Ne=((qe=me(Se.stage_id))==null?void 0:qe.sort_order)??999;break;case"brokerage":Fe=(Ze.current_brokerage||"").toLowerCase(),Ne=(Se.current_brokerage||"").toLowerCase();break;case"experience":Fe=Ze.experience_years??-1,Ne=Se.experience_years??-1;break;case"production":Fe=(Ze.annual_production||"").toLowerCase(),Ne=(Se.annual_production||"").toLowerCase();break;case"source":Fe=(Ze.source||"").toLowerCase(),Ne=(Se.source||"").toLowerCase();break;default:return 0}if(Fe===Ne)return 0;if(Fe==null)return 1;if(Ne==null)return-1;const Ye=Fe0&&he.every(ke=>G.has(ke.id)),Ce=he.some(ke=>G.has(ke.id)),Ae=()=>{$(pe?new Set:new Set(he.map(ke=>ke.id)))},Pe=ke=>{$(Ze=>{const Se=new Set(Ze);return Se.has(ke)?Se.delete(ke):Se.add(ke),Se})},ze=mt({mutationFn:async()=>{if(!Z||!(o!=null&&o.id))throw new Error("Select a campaign");const ke=new Set(te.filter(Fe=>Fe.campaign_id===Z).map(Fe=>Fe.prospect_id)),Ze=Array.from(G).filter(Fe=>!ke.has(Fe)).map(Fe=>({prospect_id:Fe,campaign_id:Z,brokerage_id:s,assigned_by:o.id,status:"active",current_email_number:0}));if(Ze.length===0)throw new Error("All selected prospects are already in this campaign");const{error:Se}=await q.from("recruit_campaign_assignments").insert(Ze);if(Se)throw Se;return Ze.length},onSuccess:ke=>{se.success(`${ke} prospect(s) added to campaign`),Y(!1),$(new Set),ne(""),c.invalidateQueries({queryKey:["recruit-campaign-assignments-lookup"]})},onError:ke=>se.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(Lr,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search prospects...",value:g,onChange:ke=>b(ke.target.value),className:"pl-8"})]}),e.jsxs("div",{className:"flex gap-2",children:[G.size>0&&e.jsxs(B,{variant:"secondary",onClick:()=>Y(!0),className:"gap-1.5",children:[e.jsx(Or,{className:"h-4 w-4"})," Add ",G.size," to Campaign"]}),e.jsxs(B,{variant:"outline",onClick:()=>v(!0),children:[e.jsx(Oa,{className:"h-4 w-4 mr-2"})," Import CSV"]}),e.jsxs(B,{onClick:()=>u(!0),children:[e.jsx(rn,{className:"h-4 w-4 mr-2"})," Add Prospect"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(D_,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs(is,{value:j,onValueChange:S,children:[e.jsx(rs,{className:"w-[160px] h-8 text-xs",children:e.jsx(ls,{placeholder:"All stages"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All stages"}),t.map(ke=>e.jsx(He,{value:ke.id,children:ke.name},ke.id))]})]}),e.jsxs(is,{value:C,onValueChange:E,children:[e.jsxs(rs,{className:"w-[200px] h-8 text-xs",children:[e.jsx(ai,{className:"h-3.5 w-3.5 mr-1.5"}),e.jsx(ls,{placeholder:"All brokerages"})]}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All brokerages"}),ce.map(ke=>e.jsx(He,{value:ke,children:ke},ke))]})]}),e.jsxs(is,{value:P,onValueChange:M,children:[e.jsxs(rs,{className:"w-[200px] h-8 text-xs",children:[e.jsx(ln,{className:"h-3.5 w-3.5 mr-1.5"}),e.jsx(ls,{placeholder:"Campaign status"})]}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All contacts"}),e.jsx(He,{value:"in_campaign",children:"In any campaign"}),e.jsx(He,{value:"not_in_campaign",children:"Not in any campaign"}),ie.map(ke=>e.jsxs(He,{value:ke.id,children:["In: ",ke.name]},ke.id))]})]}),(j!=="all"||C!=="all"||P!=="all")&&e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 text-xs text-muted-foreground",onClick:()=>{S("all"),E("all"),M("all")},children:"Clear filters"})]}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{className:"w-[40px]",children:e.jsx($a,{checked:pe,onCheckedChange:Ae,"aria-label":"Select all",...Ce&&!pe?{"data-state":"indeterminate"}:{}})}),e.jsx(Pt,{className:"cursor-pointer select-none",onClick:()=>le("name"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Name ",e.jsx(be,{column:"name"})]})}),e.jsx(Pt,{className:"cursor-pointer select-none",onClick:()=>le("stage"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Stage ",e.jsx(be,{column:"stage"})]})}),e.jsx(Pt,{className:"hidden md:table-cell cursor-pointer select-none",onClick:()=>le("brokerage"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Brokerage ",e.jsx(be,{column:"brokerage"})]})}),e.jsx(Pt,{className:"hidden md:table-cell",children:"Contact"}),e.jsx(Pt,{className:"hidden lg:table-cell cursor-pointer select-none",onClick:()=>le("experience"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Experience ",e.jsx(be,{column:"experience"})]})}),e.jsx(Pt,{className:"hidden lg:table-cell cursor-pointer select-none",onClick:()=>le("production"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Production ",e.jsx(be,{column:"production"})]})}),e.jsx(Pt,{className:"hidden lg:table-cell",children:"Campaigns"}),e.jsx(Pt,{className:"w-[50px]"})]})}),e.jsx(Ka,{children:he.length===0?e.jsx(pn,{children:e.jsx(gt,{colSpan:9,className:"text-center text-muted-foreground py-8",children:"No prospects found"})}):he.map(ke=>{const Ze=me(ke.stage_id),Se=ae.get(ke.id),Fe=(Se==null?void 0:Se.size)??0;return e.jsxs(pn,{className:"cursor-pointer",onClick:()=>{m(ke),f(!0)},children:[e.jsx(gt,{onClick:Ne=>Ne.stopPropagation(),children:e.jsx($a,{checked:G.has(ke.id),onCheckedChange:()=>Pe(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:Ze?e.jsxs(Oe,{variant:"outline",className:"text-xs gap-1 whitespace-nowrap",style:{borderColor:Ze.color,color:Ze.color,backgroundColor:`${Ze.color}10`},children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full inline-block",style:{backgroundColor:Ze.color}}),Ze.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(ln,{className:"h-3.5 w-3.5 text-muted-foreground"}),ke.phone&&e.jsx(_a,{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:Fe>0?e.jsxs(Oe,{variant:"secondary",className:"text-xs",children:[Fe," campaign",Fe>1?"s":""]}):e.jsx("span",{className:"text-muted-foreground text-xs",children:"None"})}),e.jsx(gt,{children:e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive",onClick:Ne=>{Ne.stopPropagation(),l.mutate(ke.id)},children:e.jsx(Sn,{className:"h-3.5 w-3.5"})})})]},ke.id)})})]})}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[G.size>0&&e.jsxs("span",{className:"font-medium text-foreground",children:[G.size," selected · "]}),he.length," of ",n.length," prospects"]}),e.jsx(Ls,{open:H,onOpenChange:Y,children:e.jsxs(Ps,{className:"sm:max-w-md",children:[e.jsx(Os,{children:e.jsx(Ds,{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:G.size})," selected prospect(s) to a recruiting campaign drip."]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Campaign"}),e.jsxs(is,{value:Z,onValueChange:ne,children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Select a campaign..."})}),e.jsx(as,{children:ie.map(ke=>e.jsxs(He,{value:ke.id,children:[ke.name," ",e.jsxs("span",{className:"text-muted-foreground ml-1",children:["(",ke.warmth_level,")"]})]},ke.id))})]})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>Y(!1),children:"Cancel"}),e.jsx(B,{onClick:()=>ze.mutate(),disabled:!Z||ze.isPending,children:ze.isPending?"Adding...":"Add to Campaign"})]})]})}),e.jsx(Yat,{open:d,onOpenChange:u,stages:t,onSubmit:ke=>a.mutate(ke),isSubmitting:a.isPending}),e.jsx(Xat,{prospect:h,stages:t,brokerageId:s,open:p,onOpenChange:f,onUpdate:ke=>{i.mutate(ke),m(Ze=>Ze?{...Ze,...ke}:null)},onDelete:ke=>l.mutate(ke)}),e.jsx(Qat,{open:y,onOpenChange:v,brokerageId:s,stages:t})]})}function Trs({brokerageId:s}){const{stages:t,prospects:n,isLoading:r}=kz(s),a=_.useMemo(()=>{if(!t.length||!n.length)return null;const i=n.length,l=t.find(g=>g.name==="Signed"),o=t.find(g=>g.name==="Onboarded"),c=n.filter(g=>g.stage_id===(l==null?void 0:l.id)||g.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((g,b)=>g+CN(u,new Date(b.created_at)),0)/i):0,m=t.map(g=>({...g,count:n.filter(b=>b.stage_id===g.id).length})),p={};n.forEach(g=>{const b=g.source||"unknown";p[b]=(p[b]||0)+1});const f=Object.entries(p).sort((g,b)=>b[1]-g[1]),y=new Date;y.setDate(y.getDate()-30);const v=n.filter(g=>new Date(g.created_at)>=y).length;return{total:i,signed:c,conversionRate:d,avgDays:h,byStage:m,bySrc:f,recentCount:v}},[t,n]);return r?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):a?e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(ve,{children:e.jsx(Me,{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(In,{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(ve,{children:e.jsx(Me,{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(Nl,{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(ve,{children:e.jsx(Me,{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(Gr,{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(ve,{children:e.jsx(Me,{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(ku,{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(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"Pipeline Breakdown"})}),e.jsx(Me,{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(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"Lead Sources"})}),e.jsxs(Me,{className:"space-y-3",children:[a.bySrc.map(([i,l])=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Oe,{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 Snr=["Outreach","Follow-up","Interview","Offer","Referral","Other"];function Mrs({brokerageId:s}){const{toast:t}=vi(),{user:n}=hs(),r=Bt(),[a,i]=_.useState(null),[l,o]=_.useState(null),[c,d]=_.useState(!1),[u,h]=_.useState(null),{data:m=[],isLoading:p}=at({queryKey:["recruit-email-templates-manage",s],queryFn:async()=>{const{data:S,error:C}=await q.from("recruit_email_templates").select("*").or(`brokerage_id.is.null,brokerage_id.eq.${s}`).order("sort_order");if(C)throw C;return S}}),f=mt({mutationFn:async S=>{if(S.id){const{error:C}=await q.from("recruit_email_templates").update({category:S.category,title:S.title,subject:S.subject,body:S.body}).eq("id",S.id);if(C)throw C}else{const{error:C}=await q.from("recruit_email_templates").insert({brokerage_id:s,category:S.category||"Outreach",title:S.title,subject:S.subject,body:S.body,created_by:n==null?void 0:n.id,sort_order:100});if(C)throw C}},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-email-templates-manage",s]}),r.invalidateQueries({queryKey:["recruit-email-templates"]}),t({title:"Template saved"}),d(!1),h(null)},onError:S=>t({title:"Save failed",description:S.message,variant:"destructive"})}),y=mt({mutationFn:async S=>{const{error:C}=await q.from("recruit_email_templates").delete().eq("id",S);if(C)throw C},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-email-templates-manage",s]}),r.invalidateQueries({queryKey:["recruit-email-templates"]}),t({title:"Template deleted"})},onError:S=>t({title:"Delete failed",description:S.message,variant:"destructive"})}),v=(S,C)=>{navigator.clipboard.writeText(S),i(C),t({title:"Copied to clipboard!"}),setTimeout(()=>i(null),2e3)},g=()=>{h({category:"Outreach",title:"",subject:"",body:""}),d(!0)},b=S=>{h(S),d(!0)},j=Array.from(new Set(m.map(S=>S.category)));return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Pre-built and custom recruiting templates. Built-in templates are global; your custom ones are private to this brokerage."}),e.jsxs(B,{onClick:g,size:"sm",className:"gap-1.5",children:[e.jsx(rn,{className:"h-4 w-4"})," New Template"]})]}),p?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Ct,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):j.map(S=>e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h3",{className:"font-semibold text-sm flex items-center gap-2",children:[e.jsx(ln,{className:"h-4 w-4"})," ",S]}),m.filter(C=>C.category===S).map(C=>{const E=C.brokerage_id!==null;return e.jsxs(ve,{className:`transition-all ${l===C.id?"ring-2 ring-primary/20":"hover:shadow-sm"}`,children:[e.jsx(bt,{className:"pb-2 cursor-pointer",onClick:()=>o(l===C.id?null:C.id),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs(St,{className:"text-sm flex items-center gap-2",children:[e.jsx("span",{className:"truncate",children:C.title}),!E&&e.jsx(Oe,{variant:"secondary",className:"text-[10px] shrink-0",children:"Built-in"}),E&&e.jsx(Oe,{className:"text-[10px] shrink-0",children:"Custom"})]}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5 truncate",children:["Subject: ",C.subject]})]}),e.jsx(Oe,{variant:"outline",className:"text-[10px] shrink-0",children:C.category})]})}),l===C.id&&e.jsxs(Me,{className:"pt-0 space-y-3",children:[e.jsxs("div",{className:"bg-muted/50 rounded-lg p-4",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Subject Line:"}),e.jsx("p",{className:"text-sm mb-3",children:C.subject}),e.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Body:"}),e.jsx("pre",{className:"text-sm whitespace-pre-wrap font-sans",children:C.body})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>v(C.subject,C.id+"-s"),children:[a===C.id+"-s"?e.jsx(ea,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(Ia,{className:"h-3.5 w-3.5 mr-1"}),"Copy Subject"]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>v(C.body,C.id+"-b"),children:[a===C.id+"-b"?e.jsx(ea,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(Ia,{className:"h-3.5 w-3.5 mr-1"}),"Copy Body"]}),E&&e.jsxs(e.Fragment,{children:[e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>b(C),children:[e.jsx(Ya,{className:"h-3.5 w-3.5 mr-1"})," Edit"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"text-destructive hover:text-destructive",onClick:async()=>{await Xi("Delete this template?")&&y.mutate(C.id)},children:[e.jsx(Sn,{className:"h-3.5 w-3.5 mr-1"})," Delete"]})]})]})]})]},C.id)})]},S)),e.jsx(Ls,{open:c,onOpenChange:d,children:e.jsxs(Ps,{className:"max-w-2xl",children:[e.jsx(Os,{children:e.jsx(Ds,{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(J,{className:"text-xs",children:"Title"}),e.jsx(xe,{value:(u==null?void 0:u.title)||"",onChange:S=>h(C=>({...C,title:S.target.value})),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Category"}),e.jsx("select",{value:(u==null?void 0:u.category)||"Outreach",onChange:S=>h(C=>({...C,category:S.target.value})),className:"mt-1 flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm",children:Snr.map(S=>e.jsx("option",{value:S,children:S},S))})]})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Subject"}),e.jsx(xe,{value:(u==null?void 0:u.subject)||"",onChange:S=>h(C=>({...C,subject:S.target.value})),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Body"}),e.jsx(Ms,{value:(u==null?void 0:u.body)||"",onChange:S=>h(C=>({...C,body:S.target.value})),rows:12,className:"mt-1 font-sans",placeholder:`Hi [First Name], ... Best, [Your Name]`}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-1",children:"Available placeholders: [First Name], [Your Name], [Brokerage Name]"})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"ghost",onClick:()=>d(!1),children:"Cancel"}),e.jsxs(B,{onClick:()=>f.mutate(u||{}),disabled:f.isPending||!(u!=null&&u.title)||!(u!=null&&u.subject)||!(u!=null&&u.body),children:[f.isPending&&e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),"Save Template"]})]})]})})]})}const _4t={call:_a,email:ln,text:Hi,meeting:ga,note:Fr};function Prs({brokerageId:s}){const{data:t,isLoading:n}=at({queryKey:["recruit-activity-report",s],queryFn:async()=>{const{data:r,error:a}=await q.from("recruit_prospects").select("id, created_by").eq("brokerage_id",s);if(a)throw a;const i=(r==null?void 0:r.map(p=>p.id))||[];if(i.length===0)return{recruiters:[],recentActivities:[]};const{data:l,error:o}=await q.from("recruit_activities").select("*").in("prospect_id",i).order("created_at",{ascending:!1});if(o)throw o;const c=[...new Set([...r.map(p=>p.created_by),...(l||[]).map(p=>p.created_by)])],{data:d}=await q.from("profiles").select("id, name, email").in("id",c),u=Object.fromEntries((d||[]).map(p=>[p.id,p])),h=w4e(new Date,30);return{recruiters:c.map(p=>{var b,j;const f=(l||[]).filter(S=>S.created_by===p),y=f.filter(S=>new Date(S.created_at)>=h),v={};y.forEach(S=>{v[S.activity_type]=(v[S.activity_type]||0)+1});const g=r.filter(S=>S.created_by===p).length;return{id:p,name:((b=u[p])==null?void 0:b.name)||"Unknown",email:((j=u[p])==null?void 0:j.email)||"",totalActivities:f.length,recentActivities:y.length,byType:v,prospectsCreated:g}}).sort((p,f)=>f.recentActivities-p.recentActivities),recentActivities:(l||[]).slice(0,20)}},enabled:!!s});return n?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):t!=null&&t.recruiters.length?e.jsxs("div",{className:"space-y-6",children:[e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"Recruiter Leaderboard (Last 30 Days)"})}),e.jsx(Me,{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(Fo,{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=_4t[i]||Fr;return e.jsxs(Oe,{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(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"Recent Activity"})}),e.jsx(Me,{className:"space-y-3",children:t.recentActivities.map(r=>{const a=_4t[r.activity_type]||Fr;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 Lrs({brokerageId:s}){const{toast:t}=vi(),n=Bt(),[r,a]=_.useState(!1),[i,l]=_.useState({first_name:"",last_name:"",email:"",phone:"",current_brokerage:"",notes:""}),{data:o=[],isLoading:c}=at({queryKey:["recruit-referrals",s],queryFn:async()=>{const{data:v,error:g}=await q.from("recruit_referrals").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(g)throw g;return v}}),d=[...new Set(o.map(v=>v.referred_by))],{data:u=[]}=at({queryKey:["referral-profiles",d],queryFn:async()=>{if(!d.length)return[];const{data:v}=await q.from("profiles").select("id, name, email").in("id",d);return v||[]},enabled:d.length>0}),h=Object.fromEntries(u.map(v=>[v.id,v])),m=mt({mutationFn:async v=>{const{data:{user:g}}=await q.auth.getUser();if(!g)throw new Error("Not authenticated");const{error:b}=await q.from("recruit_referrals").insert({brokerage_id:s,referred_by:g.id,referee_first_name:v.first_name,referee_last_name:v.last_name||null,referee_email:v.email||null,referee_phone:v.phone||null,referee_current_brokerage:v.current_brokerage||null,notes:v.notes||null});if(b)throw b},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-referrals",s]}),t({title:"Referral submitted!"}),l({first_name:"",last_name:"",email:"",phone:"",current_brokerage:"",notes:""}),a(!1)},onError:v=>t({title:"Error",description:v.message,variant:"destructive"})}),p=mt({mutationFn:async({id:v,status:g,incentive_status:b})=>{const j={updated_at:new Date().toISOString()};g&&(j.status=g),b&&(j.incentive_status=b);const{error:S}=await q.from("recruit_referrals").update(j).eq("id",v);if(S)throw S},onSuccess:()=>n.invalidateQueries({queryKey:["recruit-referrals",s]})}),f=v=>v==="approved"||v==="signed"?e.jsx(ea,{className:"h-3 w-3"}):v==="rejected"?e.jsx(Rd,{className:"h-3 w-3"}):e.jsx(Gr,{className:"h-3 w-3"}),y=v=>v==="approved"||v==="signed"||v==="paid"?"bg-green-500/10 text-green-600 border-green-200":v==="rejected"?"bg-red-500/10 text-red-600 border-red-200":"bg-amber-500/10 text-amber-600 border-amber-200";return c?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:[o.length," referral",o.length!==1?"s":""]}),e.jsxs(B,{onClick:()=>a(!0),children:[e.jsx(rn,{className:"h-4 w-4 mr-2"})," Submit Referral"]})]}),o.length===0?e.jsxs(ve,{className:"py-12 text-center",children:[e.jsx(Pl,{className:"h-10 w-10 mx-auto text-muted-foreground mb-3"}),e.jsx("p",{className:"text-muted-foreground",children:"No referrals yet. Agents can refer potential recruits here."})]}):e.jsx("div",{className:"space-y-3",children:o.map(v=>{var g;return e.jsx(ve,{className:"p-4",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsxs("span",{className:"font-medium",children:[v.referee_first_name," ",v.referee_last_name]}),e.jsxs(Oe,{variant:"outline",className:y(v.status),children:[f(v.status)," ",v.status]}),v.incentive_status&&e.jsxs(Oe,{variant:"outline",className:y(v.incentive_status),children:[e.jsx(Vo,{className:"h-3 w-3 mr-1"})," ",v.incentive_status]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground space-y-0.5",children:[v.referee_email&&e.jsx("p",{children:v.referee_email}),v.referee_phone&&e.jsx("p",{children:v.referee_phone}),v.referee_current_brokerage&&e.jsxs("p",{children:["Currently at: ",v.referee_current_brokerage]}),e.jsxs("p",{children:["Referred by: ",((g=h[v.referred_by])==null?void 0:g.name)||"Unknown"," • ",Hs(new Date(v.created_at),"MMM d, yyyy")]})]}),v.notes&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1 italic",children:v.notes})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsxs(is,{value:v.status,onValueChange:b=>p.mutate({id:v.id,status:b}),children:[e.jsx(rs,{className:"h-7 text-xs w-[110px]",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"pending",children:"Pending"}),e.jsx(He,{value:"contacted",children:"Contacted"}),e.jsx(He,{value:"approved",children:"Approved"}),e.jsx(He,{value:"signed",children:"Signed"}),e.jsx(He,{value:"rejected",children:"Rejected"})]})]}),e.jsxs(is,{value:v.incentive_status||"pending",onValueChange:b=>p.mutate({id:v.id,incentive_status:b}),children:[e.jsx(rs,{className:"h-7 text-xs w-[100px]",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"pending",children:"Unpaid"}),e.jsx(He,{value:"paid",children:"Paid"}),e.jsx(He,{value:"n/a",children:"N/A"})]})]})]})]})},v.id)})}),e.jsx(Ls,{open:r,onOpenChange:a,children:e.jsxs(Ps,{children:[e.jsx(Os,{children:e.jsx(Ds,{children:"Submit a Recruit Referral"})}),e.jsxs("form",{onSubmit:v=>{v.preventDefault(),m.mutate(i)},className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(J,{children:"First Name *"}),e.jsx(xe,{required:!0,value:i.first_name,onChange:v=>l(g=>({...g,first_name:v.target.value}))})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Last Name"}),e.jsx(xe,{value:i.last_name,onChange:v=>l(g=>({...g,last_name:v.target.value}))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Email"}),e.jsx(xe,{type:"email",value:i.email,onChange:v=>l(g=>({...g,email:v.target.value}))})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Phone"}),e.jsx(xe,{value:i.phone,onChange:v=>l(g=>({...g,phone:v.target.value}))})]})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Current Brokerage"}),e.jsx(xe,{value:i.current_brokerage,onChange:v=>l(g=>({...g,current_brokerage:v.target.value}))})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Notes"}),e.jsx(Ms,{value:i.notes,onChange:v=>l(g=>({...g,notes:v.target.value})),rows:2})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(B,{type:"submit",disabled:m.isPending,children:"Submit"})]})]})]})})]})}function Irs({brokerageId:s}){const{toast:t}=vi(),n=Bt(),[r,a]=_.useState(!1),{data:i}=at({queryKey:["brokerage-recruit-form",s],queryFn:async()=>{const{data:m,error:p}=await q.from("brokerages").select("id, name, recruit_form_slug, recruit_form_enabled").eq("id",s).single();if(p)throw p;return m}}),{data:l=[]}=at({queryKey:["recruit-interest-submissions",s],queryFn:async()=>{const{data:m,error:p}=await q.from("recruit_interest_submissions").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(p)throw p;return m}}),o=mt({mutationFn:async m=>{const{error:p}=await q.from("brokerages").update({recruit_form_enabled:m}).eq("id",s);if(p)throw p},onSuccess:()=>{n.invalidateQueries({queryKey:["brokerage-recruit-form",s]}),t({title:i!=null&&i.recruit_form_enabled?"Form disabled":"Form enabled"})}}),c=mt({mutationFn:async({id:m,status:p})=>{const{error:f}=await q.from("recruit_interest_submissions").update({status:p}).eq("id",m);if(f)throw f},onSuccess:()=>n.invalidateQueries({queryKey:["recruit-interest-submissions",s]})}),d=`https://bestbrokerage.relevelup.com/join-brokerage/${(i==null?void 0:i.recruit_form_slug)||""}`,u=()=>{navigator.clipboard.writeText(d),a(!0),t({title:"Link copied!"}),setTimeout(()=>a(!1),2e3)},h=m=>m==="contacted"||m==="converted"?"bg-green-500/10 text-green-600":m==="dismissed"?"bg-red-500/10 text-red-600":"bg-blue-500/10 text-blue-600";return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"Public Interest Form"})}),e.jsxs(Me,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(J,{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(fn,{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(B,{size:"sm",variant:"outline",onClick:u,children:r?e.jsx(ea,{className:"h-3.5 w-3.5"}):e.jsx(Ia,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"sm",variant:"outline",asChild:!0,children:e.jsx("a",{href:d,target:"_blank",rel:"noopener noreferrer",children:e.jsx(wr,{className:"h-3.5 w-3.5"})})})]})]})]}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsxs(St,{className:"text-base",children:["Interest Submissions (",l.length,")"]})}),e.jsx(Me,{children:l.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx(Pl,{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(Oe,{variant:"outline",className:h(m.status),children:m.status})]}),e.jsxs("div",{className:"flex flex-wrap gap-3 text-xs text-muted-foreground",children:[m.email&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ln,{className:"h-3 w-3"}),m.email]}),m.phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(_a,{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(is,{value:m.status,onValueChange:p=>c.mutate({id:m.id,status:p}),children:[e.jsx(rs,{className:"h-7 text-xs w-[110px]",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"new",children:"New"}),e.jsx(He,{value:"contacted",children:"Contacted"}),e.jsx(He,{value:"converted",children:"Converted"}),e.jsx(He,{value:"dismissed",children:"Dismissed"})]})]})]},m.id))})})]})]})}function Drs({brokerageId:s}){const{toast:t}=vi(),n=Bt(),[r,a]=_.useState(!1),[i,l]=_.useState({prospect_id:"",title:"",description:"",due_date:Hs(zh(new Date,1),"yyyy-MM-dd'T'HH:mm")}),[o,c]=_.useState("pending"),{data:d=[]}=at({queryKey:["recruit-prospects-list",s],queryFn:async()=>{const{data:C,error:E}=await q.from("recruit_prospects").select("id, first_name, last_name").eq("brokerage_id",s).order("first_name");if(E)throw E;return C}}),{data:u=[],isLoading:h}=at({queryKey:["recruit-follow-ups",s],queryFn:async()=>{const C=d.map(M=>M.id);if(!C.length)return[];const{data:E,error:P}=await q.from("recruit_follow_ups").select("*").in("prospect_id",C).order("due_date");if(P)throw P;return E},enabled:d.length>0}),m=Object.fromEntries(d.map(C=>[C.id,C])),p=mt({mutationFn:async C=>{const{data:{user:E}}=await q.auth.getUser();if(!E)throw new Error("Not authenticated");const{error:P}=await q.from("recruit_follow_ups").insert({prospect_id:C.prospect_id,assigned_to:E.id,title:C.title,description:C.description||null,due_date:new Date(C.due_date).toISOString()});if(P)throw P},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-follow-ups",s]}),t({title:"Follow-up scheduled"}),l({prospect_id:"",title:"",description:"",due_date:Hs(zh(new Date,1),"yyyy-MM-dd'T'HH:mm")}),a(!1)},onError:C=>t({title:"Error",description:C.message,variant:"destructive"})}),f=mt({mutationFn:async({id:C,completed:E})=>{const{error:P}=await q.from("recruit_follow_ups").update({completed_at:E?new Date().toISOString():null}).eq("id",C);if(P)throw P},onSuccess:()=>n.invalidateQueries({queryKey:["recruit-follow-ups",s]})}),y=u.filter(C=>o==="pending"?!C.completed_at:o==="completed"?!!C.completed_at:!0),v=y.filter(C=>!C.completed_at&&X4(new Date(C.due_date))&&!yy(new Date(C.due_date))),g=y.filter(C=>!C.completed_at&&yy(new Date(C.due_date))),b=y.filter(C=>!C.completed_at&&!X4(new Date(C.due_date))&&!yy(new Date(C.due_date))),j=y.filter(C=>!!C.completed_at),S=C=>{const E=m[C.prospect_id],P=!C.completed_at&&X4(new Date(C.due_date))&&!yy(new Date(C.due_date));return e.jsxs("div",{className:"flex items-start gap-3 p-3 border rounded-lg",children:[e.jsx($a,{checked:!!C.completed_at,onCheckedChange:M=>f.mutate({id:C.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 ${C.completed_at?"line-through text-muted-foreground":""}`,children:C.title}),C.description&&e.jsx("p",{className:"text-xs text-muted-foreground",children:C.description}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 text-xs text-muted-foreground",children:[E&&e.jsxs(Oe,{variant:"secondary",className:"text-[10px]",children:[E.first_name," ",E.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(ga,{className:"h-3 w-3"}),Hs(new Date(C.due_date),"MMM d, h:mm a")]}),C.is_automated&&e.jsx(Oe,{variant:"outline",className:"text-[10px]",children:"Auto"})]})]})]},C.id)};return h?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"flex gap-2",children:["pending","completed","all"].map(C=>e.jsxs(B,{size:"sm",variant:o===C?"default":"outline",onClick:()=>c(C),className:"capitalize text-xs",children:[C," ",C==="pending"&&v.length+g.length+b.length>0&&`(${v.length+g.length+b.length})`]},C))}),e.jsxs(B,{size:"sm",onClick:()=>a(!0),children:[e.jsx(rn,{className:"h-4 w-4 mr-1"})," Add Follow-up"]})]}),o!=="completed"&&v.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"text-xs font-semibold text-destructive flex items-center gap-1",children:[e.jsx(Xo,{className:"h-3.5 w-3.5"})," Overdue (",v.length,")"]}),v.map(S)]}),o!=="completed"&&g.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(Gr,{className:"h-3.5 w-3.5"})," Today (",g.length,")"]}),g.map(S)]}),o!=="completed"&&b.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"text-xs font-semibold text-muted-foreground flex items-center gap-1",children:[e.jsx(ga,{className:"h-3.5 w-3.5"})," Upcoming (",b.length,")"]}),b.map(S)]}),o!=="pending"&&j.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"text-xs font-semibold text-muted-foreground flex items-center gap-1",children:[e.jsx(ea,{className:"h-3.5 w-3.5"})," Completed (",j.length,")"]}),j.map(S)]}),y.length===0&&e.jsxs("p",{className:"text-sm text-muted-foreground text-center py-8",children:["No follow-ups ",o!=="all"?`(${o})`:""]}),e.jsx(Ls,{open:r,onOpenChange:a,children:e.jsxs(Ps,{children:[e.jsx(Os,{children:e.jsx(Ds,{children:"Schedule Follow-up"})}),e.jsxs("form",{onSubmit:C=>{C.preventDefault(),p.mutate(i)},className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Prospect *"}),e.jsxs("select",{className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm",required:!0,value:i.prospect_id,onChange:C=>l(E=>({...E,prospect_id:C.target.value})),children:[e.jsx("option",{value:"",children:"Select prospect..."}),d.map(C=>e.jsxs("option",{value:C.id,children:[C.first_name," ",C.last_name]},C.id))]})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Task *"}),e.jsx(xe,{required:!0,value:i.title,onChange:C=>l(E=>({...E,title:C.target.value})),placeholder:"e.g. Follow-up call"})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Details"}),e.jsx(Ms,{value:i.description,onChange:C=>l(E=>({...E,description:C.target.value})),rows:2})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Due Date *"}),e.jsx(xe,{type:"datetime-local",required:!0,value:i.due_date,onChange:C=>l(E=>({...E,due_date:C.target.value}))})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(B,{type:"submit",disabled:p.isPending,children:"Schedule"})]})]})]})})]})}const Cnr=[{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 Rrs({brokerageId:s}){const{toast:t}=vi(),n=Bt(),[r,a]=_.useState(null),{data:i,isLoading:l}=at({queryKey:["recruit-landing-settings",s],queryFn:async()=>{const{data:v,error:g}=await q.from("recruit_landing_page_settings").select("*").eq("brokerage_id",s).maybeSingle();if(g)throw g;return v}}),[o,c]=_.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:Cnr,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});_.useEffect(()=>{i&&c({id:i.id,brokerage_id:i.brokerage_id,hero_headline:i.hero_headline,hero_subtext:i.hero_subtext||"",hero_image_url:i.hero_image_url,logo_url:i.logo_url,primary_color:i.primary_color,accent_color:i.accent_color,benefits:i.benefits||[],testimonials:i.testimonials||[],gallery_images:i.gallery_images||[],calculator_enabled:i.calculator_enabled??!1,calculator_config:i.calculator_config||{},lead_magnet_enabled:i.lead_magnet_enabled??!1,lead_magnet_config:i.lead_magnet_config||{},form_style:i.form_style||"classic",confidential_messaging:i.confidential_messaging??!0})},[i]);const d=mt({mutationFn:async()=>{const v={brokerage_id:s,hero_headline:o.hero_headline,hero_subtext:o.hero_subtext,hero_image_url:o.hero_image_url,logo_url:o.logo_url,primary_color:o.primary_color,accent_color:o.accent_color,benefits:JSON.parse(JSON.stringify(o.benefits)),testimonials:JSON.parse(JSON.stringify(o.testimonials)),gallery_images:JSON.parse(JSON.stringify(o.gallery_images)),calculator_enabled:o.calculator_enabled,calculator_config:JSON.parse(JSON.stringify(o.calculator_config)),lead_magnet_enabled:o.lead_magnet_enabled,lead_magnet_config:JSON.parse(JSON.stringify(o.lead_magnet_config)),form_style:o.form_style,confidential_messaging:o.confidential_messaging,updated_at:new Date().toISOString()};if(o.id){const{error:g}=await q.from("recruit_landing_page_settings").update(v).eq("id",o.id);if(g)throw g}else{const{error:g}=await q.from("recruit_landing_page_settings").insert(v);if(g)throw g}},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-landing-settings",s]}),t({title:"Landing page saved!"})},onError:v=>t({title:"Error",description:v.message,variant:"destructive"})}),u=async(v,g)=>{const b=v.name.split(".").pop(),j=`${s}/${g}-${Date.now()}.${b}`,{error:S}=await q.storage.from("recruit-landing").upload(j,v);if(S)throw S;const{data:{publicUrl:C}}=q.storage.from("recruit-landing").getPublicUrl(j);return C},h=async(v,g)=>{var j;const b=(j=v.target.files)==null?void 0:j[0];if(b){a(g);try{const S=await u(b,g);c(C=>({...C,[g]:S})),t({title:"Image uploaded!"})}catch(S){t({title:"Upload failed",description:S.message,variant:"destructive"})}finally{a(null)}}},m=async v=>{var b;const g=(b=v.target.files)==null?void 0:b[0];if(g){a("gallery");try{const j=await u(g,"gallery");c(S=>({...S,gallery_images:[...S.gallery_images,j]})),t({title:"Gallery image added!"})}catch(j){t({title:"Upload failed",description:j.message,variant:"destructive"})}finally{a(null)}}},p=async(v,g)=>{var j;const b=(j=v.target.files)==null?void 0:j[0];if(b){a(`testimonial-${g}`);try{const S=await u(b,`testimonial-${g}`);c(C=>{const E=[...C.testimonials];return E[g]={...E[g],photo_url:S},{...C,testimonials:E}})}catch(S){t({title:"Upload failed",description:S.message,variant:"destructive"})}finally{a(null)}}},{data:f}=at({queryKey:["brokerage-slug-for-landing",s],queryFn:async()=>{const{data:v,error:g}=await q.from("brokerages").select("recruit_form_slug, recruit_form_enabled").eq("id",s).single();if(g)throw g;return v}}),y=`https://bestbrokerage.relevelup.com/join-brokerage/${(f==null?void 0:f.recruit_form_slug)||""}`;return l?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):e.jsxs("div",{className:"space-y-6",children:[(f==null?void 0:f.recruit_form_enabled)&&e.jsxs("div",{className:"flex items-center gap-2 p-3 bg-muted/50 rounded-lg border",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Live page:"}),e.jsx("code",{className:"text-xs flex-1 truncate",children:y}),e.jsx(B,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:y,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(wr,{className:"h-3.5 w-3.5 mr-1"})," Preview"]})})]}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"Branding"})}),e.jsx(Me,{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(J,{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(B,{variant:"outline",size:"sm",asChild:!0,disabled:r==="logo_url",children:e.jsxs("span",{children:[e.jsx(Oa,{className:"h-3.5 w-3.5 mr-1"}),r==="logo_url"?"Uploading...":"Upload Logo"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:v=>h(v,"logo_url")})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Primary Color"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("input",{type:"color",value:o.primary_color,onChange:v=>c(g=>({...g,primary_color:v.target.value})),className:"h-9 w-12 rounded border cursor-pointer"}),e.jsx(xe,{value:o.primary_color,onChange:v=>c(g=>({...g,primary_color:v.target.value})),className:"font-mono text-xs"})]})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Accent Color"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("input",{type:"color",value:o.accent_color,onChange:v=>c(g=>({...g,accent_color:v.target.value})),className:"h-9 w-12 rounded border cursor-pointer"}),e.jsx(xe,{value:o.accent_color,onChange:v=>c(g=>({...g,accent_color:v.target.value})),className:"font-mono text-xs"})]})]})]})]})})]}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"Hero Section"})}),e.jsxs(Me,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Headline"}),e.jsx(xe,{value:o.hero_headline,onChange:v=>c(g=>({...g,hero_headline:v.target.value})),placeholder:"Join Our Team"})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Subtext"}),e.jsx(Ms,{value:o.hero_subtext,onChange:v=>c(g=>({...g,hero_subtext:v.target.value})),rows:2,placeholder:"Take your career to the next level..."})]}),e.jsxs("div",{children:[e.jsx(J,{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(B,{variant:"outline",size:"sm",asChild:!0,disabled:r==="hero_image_url",children:e.jsxs("span",{children:[e.jsx(Oa,{className:"h-3.5 w-3.5 mr-1"}),r==="hero_image_url"?"Uploading...":"Upload Image"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:v=>h(v,"hero_image_url")})]}),o.hero_image_url&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>c(v=>({...v,hero_image_url:null})),children:e.jsx(Sn,{className:"h-3.5 w-3.5"})})]})]})]})]}),e.jsxs(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between",children:[e.jsx(St,{className:"text-base",children:"Benefits / Why Join Us"}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>c(v=>({...v,benefits:[...v.benefits,{title:"",description:"",icon:"✨"}]})),children:[e.jsx(rn,{className:"h-3.5 w-3.5 mr-1"})," Add"]})]}),e.jsxs(Me,{className:"space-y-3",children:[o.benefits.map((v,g)=>e.jsxs("div",{className:"flex items-start gap-3 p-3 border rounded-lg",children:[e.jsx(Vf,{className:"h-4 w-4 mt-2 text-muted-foreground"}),e.jsx(xe,{value:v.icon,onChange:b=>{const j=[...o.benefits];j[g]={...v,icon:b.target.value},c(S=>({...S,benefits:j}))},className:"w-14 text-center"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(xe,{value:v.title,onChange:b=>{const j=[...o.benefits];j[g]={...v,title:b.target.value},c(S=>({...S,benefits:j}))},placeholder:"Benefit title"}),e.jsx(xe,{value:v.description,onChange:b=>{const j=[...o.benefits];j[g]={...v,description:b.target.value},c(S=>({...S,benefits:j}))},placeholder:"Short description"})]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>c(b=>({...b,benefits:b.benefits.filter((j,S)=>S!==g)})),children:e.jsx(Sn,{className:"h-3.5 w-3.5 text-destructive"})})]},g)),o.benefits.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No benefits added yet"})]})]}),e.jsxs(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between",children:[e.jsx(St,{className:"text-base",children:"Testimonials"}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>c(v=>({...v,testimonials:[...v.testimonials,{name:"",role:"",quote:""}]})),children:[e.jsx(rn,{className:"h-3.5 w-3.5 mr-1"})," Add"]})]}),e.jsxs(Me,{className:"space-y-3",children:[o.testimonials.map((v,g)=>{var b;return e.jsxs("div",{className:"flex items-start gap-3 p-3 border rounded-lg",children:[e.jsxs("div",{className:"flex flex-col items-center gap-1",children:[v.photo_url?e.jsx("img",{src:v.photo_url,alt:v.name,className:"h-10 w-10 rounded-full object-cover"}):e.jsx("div",{className:"h-10 w-10 rounded-full bg-muted flex items-center justify-center text-xs text-muted-foreground",children:((b=v.name)==null?void 0:b[0])||"?"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx("span",{className:"text-[10px] text-primary hover:underline",children:r===`testimonial-${g}`?"...":"Photo"}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:j=>p(j,g)})]})]}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(xe,{value:v.name,onChange:j=>{const S=[...o.testimonials];S[g]={...v,name:j.target.value},c(C=>({...C,testimonials:S}))},placeholder:"Name"}),e.jsx(xe,{value:v.role,onChange:j=>{const S=[...o.testimonials];S[g]={...v,role:j.target.value},c(C=>({...C,testimonials:S}))},placeholder:"Role / Title"})]}),e.jsx(Ms,{value:v.quote,onChange:j=>{const S=[...o.testimonials];S[g]={...v,quote:j.target.value},c(C=>({...C,testimonials:S}))},placeholder:"What they say about working here...",rows:2})]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>c(j=>({...j,testimonials:j.testimonials.filter((S,C)=>C!==g)})),children:e.jsx(Sn,{className:"h-3.5 w-3.5 text-destructive"})})]},g)}),o.testimonials.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No testimonials added yet"})]})]}),e.jsxs(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between",children:[e.jsx(St,{className:"text-base",children:"Team & Culture Gallery"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(B,{size:"sm",variant:"outline",asChild:!0,disabled:r==="gallery",children:e.jsxs("span",{children:[e.jsx(hc,{className:"h-3.5 w-3.5 mr-1"}),r==="gallery"?"Uploading...":"Add Photo"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:m})]})]}),e.jsx(Me,{children:o.gallery_images.length>0?e.jsx("div",{className:"grid grid-cols-3 md:grid-cols-4 gap-2",children:o.gallery_images.map((v,g)=>e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:v,alt:`Gallery ${g+1}`,className:"h-24 w-full object-cover rounded-lg"}),e.jsx(B,{variant:"destructive",size:"sm",className:"absolute top-1 right-1 h-6 w-6 p-0 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>c(b=>({...b,gallery_images:b.gallery_images.filter((j,S)=>S!==g)})),children:e.jsx(Sn,{className:"h-3 w-3"})})]},g))}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No gallery images added yet"})})]}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsxs(St,{className:"text-base flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4 text-primary"})," Form Style & Trust"]})}),e.jsxs(Me,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Application Form Style"}),e.jsxs(is,{value:o.form_style,onValueChange:v=>c(g=>({...g,form_style:v})),children:[e.jsx(rs,{className:"mt-1.5",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"classic",children:"Classic — single-page form (all fields visible)"}),e.jsx(He,{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(ec,{className:"h-4 w-4 mt-0.5 text-primary"}),e.jsxs("div",{children:[e.jsx(J,{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(fn,{checked:o.confidential_messaging,onCheckedChange:v=>c(g=>({...g,confidential_messaging:v}))})]})]})]}),e.jsxs(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between",children:[e.jsxs(St,{className:"text-base flex items-center gap-2",children:[e.jsx(uj,{className:"h-4 w-4 text-primary"})," Split & Income Calculator"]}),e.jsx(fn,{checked:o.calculator_enabled,onCheckedChange:v=>c(g=>({...g,calculator_enabled:v}))})]}),o.calculator_enabled&&e.jsxs(Me,{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(J,{className:"text-xs",children:"Calculator Headline"}),e.jsx(xe,{value:o.calculator_config.headline||"",onChange:v=>c(g=>({...g,calculator_config:{...g.calculator_config,headline:v.target.value}})),placeholder:"See What You Could Earn With Us"})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Subtext"}),e.jsx(xe,{value:o.calculator_config.subtext||"",onChange:v=>c(g=>({...g,calculator_config:{...g.calculator_config,subtext:v.target.value}})),placeholder:"Confidential 60-second calculator"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Pre-Cap Split % (agent keeps)"}),e.jsx(xe,{type:"number",value:o.calculator_config.commission_split_pct??80,onChange:v=>c(g=>({...g,calculator_config:{...g.calculator_config,commission_split_pct:parseFloat(v.target.value)||0}}))}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:"e.g. 80 for an 80/20"})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Cap Amount ($)"}),e.jsx(xe,{type:"number",value:o.calculator_config.cap_amount??16e3,onChange:v=>c(g=>({...g,calculator_config:{...g.calculator_config,cap_amount:parseFloat(v.target.value)||0}}))}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:"Annual cap to brokerage"})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Post-Cap Split % (agent keeps)"}),e.jsx(xe,{type:"number",value:o.calculator_config.post_cap_split_pct??100,onChange:v=>c(g=>({...g,calculator_config:{...g.calculator_config,post_cap_split_pct:parseFloat(v.target.value)||0}}))}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:"e.g. 95 for 95/5 after cap, 100 for 100%"})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Monthly Fee ($)"}),e.jsx(xe,{type:"number",value:o.calculator_config.monthly_fee??99,onChange:v=>c(g=>({...g,calculator_config:{...g.calculator_config,monthly_fee:parseFloat(v.target.value)||0}}))})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Per-Transaction Fee ($)"}),e.jsx(xe,{type:"number",value:o.calculator_config.transaction_fee??0,onChange:v=>c(g=>({...g,calculator_config:{...g.calculator_config,transaction_fee:parseFloat(v.target.value)||0}}))}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:"Multiplied by # of transactions"})]})]}),e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border bg-muted/30",children:[e.jsxs("div",{children:[e.jsx(J,{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(fn,{checked:o.calculator_config.show_email_capture!==!1,onCheckedChange:v=>c(g=>({...g,calculator_config:{...g.calculator_config,show_email_capture:v}}))})]})]})]}),e.jsxs(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between",children:[e.jsxs(St,{className:"text-base flex items-center gap-2",children:[e.jsx(hj,{className:"h-4 w-4 text-primary"})," Lead Magnet (Gated PDF)"]}),e.jsx(fn,{checked:o.lead_magnet_enabled,onCheckedChange:v=>c(g=>({...g,lead_magnet_enabled:v}))})]}),o.lead_magnet_enabled&&e.jsxs(Me,{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(J,{className:"text-xs",children:"Title"}),e.jsx(xe,{value:o.lead_magnet_config.title||"",onChange:v=>c(g=>({...g,lead_magnet_config:{...g.lead_magnet_config,title:v.target.value}})),placeholder:"Get the Full Comp Plan PDF"})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Description"}),e.jsx(Ms,{rows:2,value:o.lead_magnet_config.description||"",onChange:v=>c(g=>({...g,lead_magnet_config:{...g.lead_magnet_config,description:v.target.value}})),placeholder:"See exactly how splits, caps, and fees work..."})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Button Text"}),e.jsx(xe,{value:o.lead_magnet_config.button_text||"",onChange:v=>c(g=>({...g,lead_magnet_config:{...g.lead_magnet_config,button_text:v.target.value}})),placeholder:"Email Me the PDF"})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"PDF / File URL"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(xe,{value:o.lead_magnet_config.pdf_url||"",onChange:v=>c(g=>({...g,lead_magnet_config:{...g.lead_magnet_config,pdf_url:v.target.value||null}})),placeholder:"https://...",className:"flex-1"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(B,{variant:"outline",size:"sm",asChild:!0,disabled:r==="lead_magnet_pdf",children:e.jsxs("span",{children:[e.jsx(Oa,{className:"h-3.5 w-3.5 mr-1"}),r==="lead_magnet_pdf"?"...":"Upload"]})}),e.jsx("input",{type:"file",accept:"application/pdf,.pdf,.doc,.docx",className:"hidden",onChange:async v=>{var b;const g=(b=v.target.files)==null?void 0:b[0];if(g){a("lead_magnet_pdf");try{const j=await u(g,"lead-magnet");c(S=>({...S,lead_magnet_config:{...S.lead_magnet_config,pdf_url:j}})),t({title:"PDF uploaded!"})}catch(j){t({title:"Upload failed",description:j.message,variant:"destructive"})}finally{a(null)}}}})]})]})]})]})]})]}),e.jsx(Anr,{brokerageId:s}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(B,{onClick:()=>d.mutate(),disabled:d.isPending,size:"lg",children:[e.jsx(Ho,{className:"h-4 w-4 mr-2"}),d.isPending?"Saving...":"Save Landing Page"]})})]})}function Anr({brokerageId:s}){const{data:t=[]}=at({queryKey:["lead-magnet-downloads",s],queryFn:async()=>{const{data:n,error:r}=await q.from("recruit_lead_magnet_downloads").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1}).limit(100);if(r)throw r;return n}});return t.length===0?null:e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsxs(St,{className:"text-base flex items-center gap-2",children:[e.jsx(li,{className:"h-4 w-4 text-primary"})," Lead Magnet Downloads (",t.length,")"]})}),e.jsx(Me,{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 Frs({brokerageId:s,trigger:t,initialProspectId:n,open:r,onOpenChange:a}){const[i,l]=_.useState(!1),o=r??i,c=a??l,[d,u]=_.useState("pick-recipients"),[h,m]=_.useState(new Set(n?[n]:[])),[p,f]=_.useState("all"),[y,v]=_.useState(""),[g,b]=_.useState(null),[j,S]=_.useState(""),[C,E]=_.useState(0),[P,M]=_.useState(0),[I,D]=_.useState(""),[O,V]=_.useState(""),{data:G}=sDe(),[$,H]=_.useState("default");_.useEffect(()=>{H(G!=null&&G.massEmail?"mass_email":G!=null&&G.gmail?"gmail":"default")},[G==null?void 0:G.massEmail,G==null?void 0:G.gmail]);const[Y,Z]=_.useState(null),{prospects:ne,stages:ce}=kz(s),ie=Srs(),te=TC(),{data:ae=[]}=at({queryKey:["brokerage-recruit-video-pool",s],queryFn:async()=>{const{data:ke,error:Ze}=await q.from("agent_videos").select("id, title, thumbnail_url, duration_seconds, created_at, owner_user_id, share_token").eq("touch_type","recruiting").eq("status","ready").eq("is_deleted",!1).order("created_at",{ascending:!1}).limit(50);if(Ze)throw Ze;return ke??[]},enabled:o&&d==="pick-video"}),le=_.useCallback(()=>{u("pick-recipients"),m(new Set(n?[n]:[])),f("all"),v(""),b(null),S(""),E(0),M(0),D(""),V(""),H("default"),Z(null)},[n]),be=ke=>{!ke&&(d==="uploading"||d==="processing"||d==="sending")||(c(ke),ke||setTimeout(le,200))},me=_.useMemo(()=>ne.filter(ke=>{if(!ke.email||p!=="all"&&ke.stage_id!==p)return!1;if(y){const Ze=y.toLowerCase();if(!`${ke.first_name} ${ke.last_name??""}`.toLowerCase().includes(Ze)&&!ke.email.toLowerCase().includes(Ze))return!1}return!0}),[ne,p,y]),he=ke=>{m(Ze=>{const Se=new Set(Ze);return Se.has(ke)?Se.delete(ke):Se.add(ke),Se})},pe=()=>{h.size===me.length?m(new Set):m(new Set(me.map(ke=>ke.id)))},Ce=_.useCallback(async(ke,Ze)=>{u("uploading");try{const Se=`Recruiting blast (${h.size} recipients)`,{videoId:Fe,libraryId:Ne}=await PL(Se),{uploadUrl:Ye,apiKey:Ve}=await LL(Fe),qe=new XMLHttpRequest;qe.upload.onprogress=xt=>{xt.lengthComputable&&E(xt.loaded/xt.total*100)},await new Promise((xt,qt)=>{qe.onload=()=>qe.status>=200&&qe.status<300?xt():qt(new Error("Upload failed")),qe.onerror=()=>qt(new Error("Upload failed")),qe.open("PUT",Ye),qe.setRequestHeader("AccessKey",Ve),qe.send(ke)}),u("processing");const Qe=`https://iframe.mediadelivery.net/embed/${Ne}/${Fe}`;let Ue=0;const Xe=Date.now(),nt=9e4;for(;Ue<4&&(await new Promise(qt=>setTimeout(qt,3e3)),!(Date.now()-Xe>nt));){const xt=await TN(Fe);if(Ue=xt.status,M(xt.encodeProgress||0),Ue===5||Ue===6)throw new Error("Video processing failed")}const $e=await TN(Fe),Ge=($e.storageSize||ke.size)/(1024*1024),ct=await te.mutateAsync({bunny_video_id:Fe,playback_url:$e.directPlayUrl||Qe,thumbnail_url:$e.thumbnailUrl,preview_url:$e.previewUrl||null,duration_seconds:$e.length||Ze,file_size_mb:Ge,title:Se,status:Ue>=4?"ready":"processing",touch_type:"recruiting"});b(ct.id),S(Se),u("compose")}catch(Se){se.error((Se==null?void 0:Se.message)||"Failed to upload video"),u("pick-video")}},[h.size,te]),Ae=_.useCallback(async()=>{if(!(!g||h.size===0)){u("sending");try{const ke=[];for(const Fe of h){const Ne=await ie.mutateAsync({prospect_id:Fe,video_id:g,brokerage_id:s,message:O||void 0});ke.push(Ne.id)}const{data:Ze,error:Se}=await q.functions.invoke("send-recruit-video-email",{body:{recruit_video_ids:ke,brokerage_id:s,subject_override:I||void 0,message_override:O||void 0,send_via:$}});if(Se)throw new Error(Se.message);Z({sent:(Ze==null?void 0:Ze.sent)??0,total:(Ze==null?void 0:Ze.total)??ke.length}),u("done"),se.success(`Sent ${(Ze==null?void 0:Ze.sent)??0} of ${(Ze==null?void 0:Ze.total)??ke.length} videos`)}catch(ke){se.error((ke==null?void 0:ke.message)||"Failed to send"),u("compose")}}},[g,h,s,O,I,$,ie]),Pe=h.size,ze=ne.filter(ke=>!ke.email).length;return e.jsxs(Ls,{open:o,onOpenChange:be,children:[t&&e.jsx(nl,{asChild:!0,children:t}),e.jsxs(Ps,{className:"max-w-3xl max-h-[90vh] overflow-hidden flex flex-col",children:[e.jsx(Os,{children:e.jsxs(Ds,{className:"flex items-center gap-2",children:[e.jsx(Kr,{className:"h-5 w-5 text-primary"}),"Send Recruiting Video",Pe>0&&e.jsxs(Oe,{variant:"secondary",className:"ml-2",children:[e.jsx(In,{className:"h-3 w-3 mr-1"}),Pe," ",Pe===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(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search prospects...",value:y,onChange:ke=>v(ke.target.value),className:"pl-9"})]}),e.jsxs(is,{value:p,onValueChange:f,children:[e.jsx(rs,{className:"w-48",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All stages"}),ce.map(ke=>e.jsx(He,{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:pe,className:"hover:underline",children:[h.size===me.length&&me.length>0?"Deselect all":"Select all"," ","(",me.length,")"]}),ze>0&&e.jsxs("span",{children:[ze," prospect(s) hidden — no email on file"]})]}),e.jsx(Ji,{className:"flex-1 border rounded-md",children:me.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:me.map(ke=>{const Ze=h.has(ke.id),Se=ce.find(Fe=>Fe.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($a,{checked:Ze,onCheckedChange:()=>he(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(Oe,{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(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>be(!1),children:"Cancel"}),e.jsx(B,{disabled:Pe===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(Yr,{defaultValue:"record",className:"flex-1 flex flex-col overflow-hidden",children:[e.jsxs(Zr,{className:"self-start",children:[e.jsxs(Ht,{value:"record",children:[e.jsx(rn,{className:"h-3.5 w-3.5 mr-1"}),"Record New"]}),e.jsxs(Ht,{value:"library",children:[e.jsx(fj,{className:"h-3.5 w-3.5 mr-1"}),"Use Existing"]})]}),e.jsx(Gt,{value:"record",className:"flex-1 overflow-auto",children:e.jsxs("div",{className:"text-center py-8 space-y-4",children:[e.jsx(dm,{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 ",Pe," ",Pe===1?"recipient":"recipients"," — each gets their own tracked link."]})]}),e.jsxs(B,{onClick:()=>u("record"),children:[e.jsx(Kr,{className:"h-4 w-4 mr-2"}),"Start Recording"]})]})}),e.jsx(Gt,{value:"library",className:"flex-1 overflow-auto",children:ae.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:ae.map(ke=>e.jsxs("button",{onClick:()=>{b(ke.id),S(ke.title||"Untitled"),u("compose")},className:"text-left group rounded-md border overflow-hidden hover:border-primary transition-colors",children:[e.jsx("div",{className:"aspect-video bg-muted relative",children:R4(ke)?e.jsx("img",{src:R4(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(Kr,{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(yr,{children:e.jsx(B,{variant:"outline",onClick:()=>u("pick-recipients"),children:"Back"})})]}),d==="record"&&e.jsxs("div",{className:"flex-1 overflow-auto",children:[e.jsx($E,{maxDurationSeconds:600,onRecordingComplete:Ce}),e.jsx("div",{className:"mt-2 flex justify-start",children:e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>u("pick-video"),children:"← Back"})})]}),(d==="uploading"||d==="processing")&&e.jsxs("div",{className:"py-12 space-y-4 text-center",children:[e.jsx(Ct,{className:"h-8 w-8 animate-spin mx-auto text-primary"}),e.jsx("p",{className:"font-medium",children:d==="uploading"?"Uploading video…":"Processing video…"}),e.jsx(Fi,{value:d==="uploading"?C:P,className:"mx-auto max-w-sm"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Math.round(d==="uploading"?C: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(Er,{className:"h-4 w-4 text-primary"}),e.jsxs("div",{className:"flex-1 text-sm",children:[e.jsx("span",{className:"font-medium",children:j})," selected · sending to ",e.jsx("strong",{children:Pe})," recipient",Pe===1?"":"s"]})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Subject (optional override)"}),e.jsx(xe,{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(J,{className:"text-xs",children:"Personal message shown in the email & on the landing page"}),e.jsx(Ms,{value:O,onChange:ke=>V(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(Zat,{value:$,onChange:H}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>u("pick-video"),children:"Back"}),e.jsxs(B,{onClick:Ae,disabled:!g||Pe===0,children:[e.jsx(Or,{className:"h-4 w-4 mr-2"})," Send to ",Pe," ",Pe===1?"prospect":"prospects"]})]})]}),d==="sending"&&e.jsxs("div",{className:"py-12 text-center space-y-3",children:[e.jsx(Ct,{className:"h-8 w-8 animate-spin mx-auto text-primary"}),e.jsxs("p",{className:"font-medium",children:["Sending to ",Pe," recipient",Pe===1?"":"s","…"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Each prospect gets their own tracked share link."})]}),d==="done"&&Y&&e.jsxs("div",{className:"py-12 text-center space-y-4",children:[e.jsx("div",{className:`h-16 w-16 rounded-full mx-auto flex items-center justify-center ${Y.sent===Y.total?"bg-primary/10":"bg-muted"}`,children:Y.sent===Y.total?e.jsx(Er,{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:[Y.sent," of ",Y.total," sent"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"View engagement under the Video Outreach tab."})]}),e.jsx(B,{onClick:()=>be(!1),children:"Done"})]})]})]})}function Enr(s){if(!s)return"—";const t=Math.floor(s/60),n=s%60;return t>0?`${t}m ${n}s`:`${n}s`}function Tnr({video:s}){return s.cta_clicked_at?e.jsx(Oe,{className:"bg-emerald-500/10 text-emerald-600 border-emerald-200",children:"CTA Clicked"}):s.view_count>0?e.jsxs(Oe,{className:"bg-blue-500/10 text-blue-600 border-blue-200",children:[e.jsx(ya,{className:"h-3 w-3 mr-1"}),s.view_count," views"]}):s.sent_at?e.jsxs(Oe,{variant:"secondary",children:[e.jsx(Or,{className:"h-3 w-3 mr-1"}),"Sent"]}):e.jsxs(Oe,{variant:"outline",children:[e.jsx(Gr,{className:"h-3 w-3 mr-1"}),"Draft"]})}function Ors({brokerageId:s}){var j,S,C,E;const{data:t=[],isLoading:n}=gnr(s),{data:r=[]}=Ars(s),a=vnr(),i=bnr(),l=Crs(),[o,c]=_.useState(""),[d,u]=_.useState(!1),[h,m]=_.useState({title:"",script_text:"",category:"general"}),[p,f]=_.useState(null),y=t.filter(P=>{var I,D,O,V;return o?`${((I=P.prospect)==null?void 0:I.first_name)||""} ${((D=P.prospect)==null?void 0:D.last_name)||""}`.toLowerCase().includes(o.toLowerCase())||((V=(O=P.video)==null?void 0:O.title)==null?void 0:V.toLowerCase().includes(o.toLowerCase())):!0}),v={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},g=_.useCallback(P=>{if(!P)return;const M=`${window.location.origin}/recruit-video/${P}`;navigator.clipboard.writeText(M),se.success("Share link copied")},[]);_.useCallback((P,M)=>{l.mutate({id:P,sent_via:M})},[l]);const b=()=>{!h.title.trim()||!h.script_text.trim()||a.mutate({brokerage_id:s,...h},{onSuccess:()=>{m({title:"",script_text:"",category:"general"}),u(!1)}})};return e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[{label:"Total Videos",value:v.total,icon:Kr,color:"text-primary"},{label:"Sent",value:v.sent,icon:Or,color:"text-blue-500"},{label:"Viewed",value:v.viewed,icon:ya,color:"text-amber-500"},{label:"CTA Clicked",value:v.ctaClicked,icon:Er,color:"text-emerald-500"}].map(P=>e.jsx(ve,{children:e.jsxs(Me,{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(Yr,{defaultValue:"videos",className:"space-y-4",children:[e.jsxs(Zr,{children:[e.jsxs(Ht,{value:"videos",children:[e.jsx(Kr,{className:"h-4 w-4 mr-1.5"}),"All Videos"]}),e.jsxs(Ht,{value:"scripts",children:[e.jsx(Fr,{className:"h-4 w-4 mr-1.5"}),"Script Library"]}),e.jsxs(Ht,{value:"analytics",children:[e.jsx(bl,{className:"h-4 w-4 mr-1.5"}),"Engagement"]})]}),e.jsx(Gt,{value:"videos",children:e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[e.jsx(St,{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(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search by name or title...",value:o,onChange:P=>c(P.target.value),className:"pl-9"})]}),e.jsx(Frs,{brokerageId:s,trigger:e.jsxs(B,{size:"sm",className:"gap-1.5",children:[e.jsx(ln,{className:"h-4 w-4"})," Send Video Email"]})})]})]})}),e.jsx(Me,{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"})}):y.length===0?e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(Kr,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{className:"font-medium",children:"No 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:y.map(P=>{var M,I,D,O,V,G,$;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:[R4(P.video)?e.jsx("img",{src:R4(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(Kr,{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:Enr(((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(Tnr,{video:P})]}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:((O=P.video)==null?void 0:O.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"),((V=P.prospect)==null?void 0:V.current_brokerage)&&` · ${P.prospect.current_brokerage}`]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>g(P.share_token),title:"Copy share link",children:e.jsx(Ia,{className:"h-4 w-4"})}),e.jsxs(B,{variant:P.sent_at?"ghost":"default",size:"sm",className:"h-8 gap-1.5",onClick:()=>f(P),disabled:!((G=P.prospect)!=null&&G.email),title:($=P.prospect)!=null&&$.email?"Email this video to the prospect":"Prospect has no email",children:[e.jsx(ln,{className:"h-4 w-4"}),P.sent_at?"Resend":"Email"]}),P.share_token&&e.jsx(B,{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(wr,{className:"h-4 w-4"})})]})]},P.id)})})})]})}),e.jsx(Gt,{value:"scripts",children:e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(St,{className:"text-lg",children:"Recruiting Scripts"}),e.jsxs(Ls,{open:d,onOpenChange:u,children:[e.jsx(nl,{asChild:!0,children:e.jsxs(B,{size:"sm",children:[e.jsx(rn,{className:"h-4 w-4 mr-1.5"}),"New Script"]})}),e.jsxs(Ps,{children:[e.jsx(Os,{children:e.jsx(Ds,{children:"Create Recruiting Script"})}),e.jsxs("div",{className:"space-y-4 mt-2",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Title"}),e.jsx(xe,{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(J,{children:"Category"}),e.jsxs(is,{value:h.category,onValueChange:P=>m(M=>({...M,category:P})),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsx(as,{children:WYe.map(P=>e.jsx(He,{value:P.value,children:P.label},P.value))})]})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Script"}),e.jsx(Ms,{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(B,{onClick:b,disabled:!h.title.trim()||!h.script_text.trim(),className:"w-full",children:"Save Script"})]})]})]})]})}),e.jsx(Me,{children:r.length===0?e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(Fr,{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=WYe.find(D=>D.value===P.category))==null?void 0:I.label)||P.category;return e.jsx(ve,{className:"relative group",children:e.jsxs(Me,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx(Oe,{variant:"outline",className:"text-[10px] mb-2",children:M}),e.jsx("h4",{className:"font-medium text-sm",children:P.title})]}),e.jsx(B,{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(Sn,{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(Oe,{variant:"secondary",className:"mt-2 text-[10px]",children:"Template"})]})},P.id)})})})]})}),e.jsx(Gt,{value:"analytics",children:e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-lg",children:"Engagement Funnel"})}),e.jsxs(Me,{children:[e.jsx("div",{className:"space-y-4",children:[{label:"Videos Created",count:v.total,pct:100,color:"bg-primary"},{label:"Sent to Prospects",count:v.sent,pct:v.total?Math.round(v.sent/v.total*100):0,color:"bg-blue-500"},{label:"Viewed by Prospect",count:v.viewed,pct:v.sent?Math.round(v.viewed/v.sent*100):0,color:"bg-amber-500"},{label:"CTA Clicked",count:v.ctaClicked,pct:v.viewed?Math.round(v.ctaClicked/v.viewed*100):0,color:"bg-emerald-500"}].map(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(ya,{className:"h-3.5 w-3.5"})," ",P.view_count]}),P.cta_clicked_at&&e.jsx(Er,{className:"h-4 w-4 text-emerald-500"})]})]},P.id)})})]})]})]})})]}),p&&e.jsx(krs,{open:!!p,onOpenChange:P=>{P||f(null)},recruitVideoId:p.id,brokerageId:s,prospectName:`${((j=p.prospect)==null?void 0:j.first_name)||""} ${((S=p.prospect)==null?void 0:S.last_name)||""}`.trim(),prospectEmail:(C=p.prospect)==null?void 0:C.email,videoTitle:(E=p.video)==null?void 0:E.title,defaultMessage:p.message})]})}function zrs({brokerageId:s}){const{toast:t}=vi(),n=Bt(),{stages:r,prospects:a}=kz(s),[i,l]=_.useState(!1),[o,c]=_.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}=at({queryKey:["recruit-goals",s],queryFn:async()=>{const{data:f,error:y}=await q.from("recruit_goals").select("*").eq("brokerage_id",s).order("period_end",{ascending:!1});if(y)throw y;return f}}),h=mt({mutationFn:async f=>{const{data:{user:y}}=await q.auth.getUser();if(!y)throw new Error("Not authenticated");const{error:v}=await q.from("recruit_goals").insert({brokerage_id:s,title:f.title,target_count:parseInt(f.target_count),target_stage_id:f.target_stage_id||null,period_start:f.period_start,period_end:f.period_end,created_by:y.id});if(v)throw v},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-goals",s]}),t({title:"Goal created"}),l(!1)},onError:f=>t({title:"Error",description:f.message,variant:"destructive"})}),m=mt({mutationFn:async f=>{const{error:y}=await q.from("recruit_goals").delete().eq("id",f);if(y)throw y},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-goals",s]}),t({title:"Goal removed"})}}),p=f=>{const y=r.find(g=>g.id===f.target_stage_id);return{count:a.filter(g=>Wk(new Date(g.created_at),{start:new Date(f.period_start),end:new Date(f.period_end)})?f.target_stage_id?g.stage_id===f.target_stage_id:!0:!1).length,stage:y}};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(B,{size:"sm",onClick:()=>l(!0),children:[e.jsx(rn,{className:"h-4 w-4 mr-1"})," New Goal"]})]}),d.length===0?e.jsxs(ve,{className:"py-12 text-center",children:[e.jsx(ku,{className:"h-10 w-10 mx-auto text-muted-foreground mb-3"}),e.jsx("p",{className:"text-muted-foreground",children:"No goals set. Create a recruiting target to track progress."})]}):e.jsx("div",{className:"grid md:grid-cols-2 gap-4",children:d.map(f=>{const{count:y,stage:v}=p(f),g=Math.min(100,y/f.target_count*100),b=Wk(new Date,{start:new Date(f.period_start),end:new Date(f.period_end)});return e.jsxs(ve,{className:b?"":"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(St,{className:"text-sm",children:f.title}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[Hs(new Date(f.period_start),"MMM d")," – ",Hs(new Date(f.period_end),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[b?e.jsx(Oe,{className:"text-[10px]",children:"Active"}):e.jsx(Oe,{variant:"secondary",className:"text-[10px]",children:"Ended"}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6 text-muted-foreground",onClick:()=>m.mutate(f.id),children:e.jsx(Sn,{className:"h-3.5 w-3.5"})})]})]})}),e.jsxs(Me,{className:"space-y-2",children:[v&&e.jsxs(Oe,{variant:"outline",className:"text-[10px]",style:{borderColor:v.color,color:v.color},children:["Stage: ",v.name]}),e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"font-bold text-lg",children:y}),e.jsxs("span",{className:"text-muted-foreground",children:["/ ",f.target_count]})]}),e.jsx(Fi,{value:g,className:"h-2"}),e.jsxs("p",{className:"text-xs text-muted-foreground text-right",children:[g.toFixed(0),"% complete"]})]})]},f.id)})}),e.jsx(Ls,{open:i,onOpenChange:l,children:e.jsxs(Ps,{children:[e.jsx(Os,{children:e.jsx(Ds,{children:"Create Recruiting Goal"})}),e.jsxs("form",{onSubmit:f=>{f.preventDefault(),h.mutate(o)},className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Goal Title *"}),e.jsx(xe,{required:!0,value:o.title,onChange:f=>c(y=>({...y,title:f.target.value})),placeholder:"e.g. Q2 Recruiting Target"})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Target Count *"}),e.jsx(xe,{type:"number",min:"1",required:!0,value:o.target_count,onChange:f=>c(y=>({...y,target_count:f.target.value}))})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Target Stage (optional)"}),e.jsxs("select",{className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm",value:o.target_stage_id,onChange:f=>c(y=>({...y,target_stage_id:f.target.value})),children:[e.jsx("option",{value:"",children:"All stages (total prospects)"}),r.map(f=>e.jsx("option",{value:f.id,children:f.name},f.id))]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Count prospects that reach this stage"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Start Date"}),e.jsx(xe,{type:"date",required:!0,value:o.period_start,onChange:f=>c(y=>({...y,period_start:f.target.value}))})]}),e.jsxs("div",{children:[e.jsx(J,{children:"End Date"}),e.jsx(xe,{type:"date",required:!0,value:o.period_end,onChange:f=>c(y=>({...y,period_end:f.target.value}))})]})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(B,{type:"submit",disabled:h.isPending,children:"Create Goal"})]})]})]})})]})}const Mnr={first_name:"Sarah",brokerage_name:"ABC Realty",city:"Austin",sender_name:"Jeremy"};function Brs({email:s,mergeValues:t=Mnr,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(Ls,{open:!0,onOpenChange:()=>r(),children:e.jsxs(Ps,{className:"max-w-2xl max-h-[85vh] overflow-y-auto p-0",children:[e.jsxs(Os,{className:"px-6 pt-6 pb-4 border-b",children:[e.jsxs(Ds,{className:"text-base",children:["Email #",s.email_number," — ",s.title]}),e.jsxs("div",{className:"flex items-center gap-3 mt-2",children:[e.jsxs(Oe,{variant:"outline",className:"text-xs gap-1",children:[e.jsx(Gr,{className:"h-3 w-3"}),s.email_number===1?"Sent immediately":`Day ${s.delay_days}`]}),i.length>1&&e.jsxs(Oe,{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 Jat({brokerageId:s}){const t=Bt(),{user:n}=hs(),[r,a]=_.useState(""),[i,l]=_.useState(!1),[o,c]=_.useState({brokerage_id:s,sender_name:"LevelUp",sender_email:"recruiting@relevelup.com",reply_to_email:"",merge_fields:{city:"",broker_name:""}}),{data:d}=at({queryKey:["brokerage-recruit-settings",s],queryFn:async()=>{const{data:f,error:y}=await q.from("brokerage_recruit_settings").select("*").eq("brokerage_id",s).maybeSingle();if(y)throw y;return f}}),{data:u}=at({queryKey:["brokerage-detail",s],queryFn:async()=>{const{data:f,error:y}=await q.from("brokerages").select("name, city, state").eq("id",s).single();if(y)throw y;return f}});_.useEffect(()=>{d?c({...d,merge_fields:d.merge_fields||{city:"",broker_name:""}}):u&&c(f=>({...f,merge_fields:{...f.merge_fields,brokerage_name:u.name,city:u.city||""}}))},[d,u]),_.useEffect(()=>{n!=null&&n.id&&q.from("profiles").select("recruit_cta_url").eq("id",n.id).single().then(({data:f})=>a((f==null?void 0:f.recruit_cta_url)||""))},[n==null?void 0:n.id]);const h=async()=>{if(!(n!=null&&n.id))return;l(!0);const{error:f}=await q.from("profiles").update({recruit_cta_url:r.trim()||null}).eq("id",n.id);l(!1),f?se.error(f.message):se.success("Scheduling link saved!")},m=mt({mutationFn:async()=>{const f={brokerage_id:s,sender_name:o.sender_name,sender_email:o.sender_email,reply_to_email:o.reply_to_email||null,merge_fields:o.merge_fields,updated_at:new Date().toISOString()};if(d!=null&&d.id){const{error:y}=await q.from("brokerage_recruit_settings").update(f).eq("id",d.id);if(y)throw y}else{const{error:y}=await q.from("brokerage_recruit_settings").insert(f);if(y)throw y}},onSuccess:()=>{t.invalidateQueries({queryKey:["brokerage-recruit-settings",s]}),se.success("Recruiting email settings saved!")},onError:f=>se.error(f.message)}),p=(f,y)=>{c(v=>({...v,merge_fields:{...v.merge_fields,[f]:y}}))};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(ga,{className:"h-4 w-4 text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Your Scheduling Link"})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["This URL powers the ",e.jsx("strong",{children:'"Schedule a Conversation"'})," button on every recruiting video page you send. Paste your Calendly, HubSpot Meetings, Google Calendar booking link, etc."]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{value:r,onChange:f=>a(f.target.value),placeholder:"https://calendly.com/your-name/intro"}),e.jsxs(B,{onClick:h,disabled:i,size:"sm",children:[e.jsx(Ho,{className:"h-4 w-4 mr-1"})," Save"]})]}),!r&&e.jsx("p",{className:"text-xs text-amber-600",children:"⚠️ No link set — the CTA button will be hidden on your video pages until you add one."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(J,{className:"text-xs",children:"Sender Display Name"}),e.jsx(xe,{value:o.sender_name,onChange:f=>c({...o,sender_name:f.target.value}),placeholder:"e.g. Jeremy at LevelUp"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(J,{className:"text-xs",children:"Sender Email Address"}),e.jsx(xe,{value:o.sender_email,onChange:f=>c({...o,sender_email:f.target.value}),placeholder:"recruiting@relevelup.com"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Must be a verified SES identity. Verify your own address below to send from it."})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(J,{className:"text-xs",children:"Reply-To Email (optional)"}),e.jsx(xe,{value:o.reply_to_email,onChange:f=>c({...o,reply_to_email:f.target.value}),placeholder:"jeremy@relevelup.com"})]})]}),e.jsxs("div",{className:"border-t pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(Dm,{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(vrs,{brokerageId:s,onVerifiedSelect:f=>{c(y=>({...y,sender_email:f})),se.success(`Sender set to ${f}`)}})]}),e.jsxs("div",{className:"border-t pt-4",children:[e.jsx("p",{className:"text-sm font-medium mb-3",children:"Default Merge Fields"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"These values will auto-fill in campaign emails for this brokerage."}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(J,{className:"text-xs",children:"{{brokerage_name}}"}),e.jsx(xe,{value:o.merge_fields.brokerage_name||"",onChange:f=>p("brokerage_name",f.target.value),placeholder:(u==null?void 0:u.name)||"Brokerage Name"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(J,{className:"text-xs",children:"{{city}}"}),e.jsx(xe,{value:o.merge_fields.city||"",onChange:f=>p("city",f.target.value),placeholder:"e.g. Austin"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(J,{className:"text-xs",children:"{{sender_name}}"}),e.jsx(xe,{value:o.merge_fields.sender_name||"",onChange:f=>p("sender_name",f.target.value),placeholder:"e.g. Jeremy"})]})]})]}),e.jsxs(B,{onClick:()=>m.mutate(),disabled:m.isPending,className:"w-full",children:[e.jsx(Ho,{className:"h-4 w-4 mr-1"})," Save Settings"]})]})}const Urs=ES.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",rp(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()}}}),w4t=[{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 Xy({onClick:s,active:t,disabled:n,icon:r,tooltip:a}){return e.jsxs(ag,{children:[e.jsx(ig,{asChild:!0,children:e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:s,disabled:n,className:`h-8 w-8 p-0 ${t?"bg-accent text-accent-foreground":"text-muted-foreground hover:text-foreground"}`,children:e.jsx(r,{className:"h-4 w-4"})})}),e.jsx(Nx,{side:"bottom",className:"text-xs",children:a})]})}function Pnr({content:s,onChange:t}){const n=ALe({extensions:[ELe.configure({heading:{levels:[1,2,3]}}),Urs,MLe.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline cursor-pointer"}}),PLe.configure({types:["heading","paragraph"]}),rtt,NKt],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())}});_.useEffect(()=>{n&&s!==n.getHTML()&&n.commands.setContent(s)},[s,n]);const r=_.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=_.useCallback(i=>{n&&n.chain().focus().insertContent(`{{${i}}}`).run()},[n]);return n?e.jsx(FN,{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(Xy,{onClick:()=>n.chain().focus().toggleBold().run(),active:n.isActive("bold"),icon:BA,tooltip:"Bold"}),e.jsx(Xy,{onClick:()=>n.chain().focus().toggleItalic().run(),active:n.isActive("italic"),icon:$A,tooltip:"Italic"}),e.jsx(Xy,{onClick:()=>n.chain().focus().toggleUnderline().run(),active:n.isActive("underline"),icon:u7,tooltip:"Underline"}),e.jsx(Xy,{onClick:()=>n.chain().focus().toggleStrike().run(),active:n.isActive("strike"),icon:oJ,tooltip:"Strikethrough"}),e.jsx(wc,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Xy,{onClick:()=>n.chain().focus().toggleHeading({level:1}).run(),active:n.isActive("heading",{level:1}),icon:Oq,tooltip:"Heading 1"}),e.jsx(Xy,{onClick:()=>n.chain().focus().toggleHeading({level:2}).run(),active:n.isActive("heading",{level:2}),icon:ZO,tooltip:"Heading 2"}),e.jsx(Xy,{onClick:()=>n.chain().focus().toggleHeading({level:3}).run(),active:n.isActive("heading",{level:3}),icon:zq,tooltip:"Heading 3"}),e.jsx(wc,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Xy,{onClick:()=>n.chain().focus().toggleBulletList().run(),active:n.isActive("bulletList"),icon:A0,tooltip:"Bullet List"}),e.jsx(Xy,{onClick:()=>n.chain().focus().toggleOrderedList().run(),active:n.isActive("orderedList"),icon:xj,tooltip:"Numbered List"}),e.jsx(Xy,{onClick:()=>n.chain().focus().toggleBlockquote().run(),active:n.isActive("blockquote"),icon:pS,tooltip:"Blockquote"}),e.jsx(Xy,{onClick:()=>n.chain().focus().setHorizontalRule().run(),icon:uN,tooltip:"Divider"}),e.jsx(wc,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Xy,{onClick:()=>n.chain().focus().setTextAlign("left").run(),active:n.isActive({textAlign:"left"}),icon:qM,tooltip:"Align Left"}),e.jsx(Xy,{onClick:()=>n.chain().focus().setTextAlign("center").run(),active:n.isActive({textAlign:"center"}),icon:UM,tooltip:"Align Center"}),e.jsx(Xy,{onClick:()=>n.chain().focus().setTextAlign("right").run(),active:n.isActive({textAlign:"right"}),icon:$M,tooltip:"Align Right"}),e.jsx(wc,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Xy,{onClick:r,active:n.isActive("link"),icon:Vc,tooltip:"Insert Link"}),e.jsx(wc,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Xy,{onClick:()=>n.chain().focus().undo().run(),disabled:!n.can().undo(),icon:JA,tooltip:"Undo"}),e.jsx(Xy,{onClick:()=>n.chain().focus().redo().run(),disabled:!n.can().redo(),icon:XA,tooltip:"Redo"}),e.jsx("div",{className:"flex-1"}),e.jsx(B,{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(tu,{children:[e.jsx(su,{asChild:!0,children:e.jsxs(B,{type:"button",variant:"outline",size:"sm",className:"h-8 gap-1.5 text-xs font-medium",children:[e.jsx(p$,{className:"h-3.5 w-3.5"}),"Merge Tags"]})}),e.jsx(Od,{align:"end",className:"w-56",children:w4t.map(i=>e.jsxs(ca,{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(CLe,{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:"}),w4t.map(i=>e.jsx(Oe,{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 Lnr({open:s,onClose:t,campaignName:n,stat:r}){return e.jsx(Ls,{open:s,onOpenChange:a=>!a&&t(),children:e.jsxs(Ps,{className:"max-w-3xl max-h-[85vh] overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsxs(Ds,{className:"flex items-center gap-2",children:[e.jsx(Nl,{className:"h-5 w-5 text-primary"}),n," — Engagement Stats"]}),e.jsx(_r,{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(Or,{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(Rde,{icon:ln,color:"text-blue-500",label:"Total Sent",value:r.sent.toLocaleString()}),e.jsx(Rde,{icon:ya,color:"text-amber-500",label:"Opens",value:`${r.opened.toLocaleString()}`,sub:`${r.openRate.toFixed(1)}% open rate`}),e.jsx(Rde,{icon:$h,color:"text-green-500",label:"Clicks",value:`${r.clicked.toLocaleString()}`,sub:`${r.clickRate.toFixed(1)}% click rate`}),e.jsx(Rde,{icon:xl,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(Gr,{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(ve,{className:"overflow-hidden",children:e.jsxs(Me,{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(Oe,{variant:"outline",className:"text-[10px] gap-1",children:[e.jsx(ln,{className:"h-2.5 w-2.5"})," ",a.sent_count.toLocaleString()," sent"]}),e.jsxs(Oe,{variant:"outline",className:"text-[10px] gap-1 border-amber-500/30 text-amber-600",children:[e.jsx(ya,{className:"h-2.5 w-2.5"})," ",a.opened_count.toLocaleString()," (",i.toFixed(1),"%)"]}),e.jsxs(Oe,{variant:"outline",className:"text-[10px] gap-1 border-green-500/30 text-green-600",children:[e.jsx($h,{className:"h-2.5 w-2.5"})," ",a.clicked_count.toLocaleString()," (",l.toFixed(1),"%)"]}),a.failed_count>0&&e.jsxs(Oe,{variant:"outline",className:"text-[10px] gap-1 border-destructive/30 text-destructive",children:[e.jsx(xl,{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 Rde({icon:s,color:t,label:n,value:r,sub:a}){return e.jsx(ve,{children:e.jsx(Me,{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 eit(s){return at({queryKey:["recruit-campaign-stats",s],enabled:!!s,staleTime:6e4,queryFn:async()=>{const{data:t,error:n}=await q.from("recruit_campaign_email_stats").select("*").eq("brokerage_id",s);if(n)throw n;const r=t??[],a={};for(const i of r){a[i.campaign_id]||(a[i.campaign_id]={campaign_id:i.campaign_id,sent:0,opened:0,clicked:0,failed:0,openRate:0,clickRate:0,byEmail:[],lastSentAt:null});const l=a[i.campaign_id];l.sent+=i.sent_count,l.opened+=i.opened_count,l.clicked+=i.clicked_count,l.failed+=i.failed_count,l.byEmail.push(i),i.last_sent_at&&(!l.lastSentAt||i.last_sent_at>l.lastSentAt)&&(l.lastSentAt=i.last_sent_at)}return Object.values(a).forEach(i=>{i.openRate=i.sent>0?i.opened/i.sent*100:0,i.clickRate=i.sent>0?i.clicked/i.sent*100:0,i.byEmail.sort((l,o)=>l.email_number-o.email_number)}),a}})}const j4t={cold:{icon:sj,color:"text-blue-500",bg:"bg-blue-50 dark:bg-blue-950/30",label:"Cold — Curiosity"},warm:{icon:fN,color:"text-amber-500",bg:"bg-amber-50 dark:bg-amber-950/30",label:"Warm — Growth"},hot:{icon:gu,color:"text-red-500",bg:"bg-red-50 dark:bg-red-950/30",label:"Hot — Private Invite"}};function qrs({brokerageId:s}){var pe,Ce,Ae,Pe;const{user:t}=hs(),n=Bt(),[r,a]=_.useState(null),[i,l]=_.useState(null),[o,c]=_.useState(null),[d,u]=_.useState(!1),[h,m]=_.useState(!1),[p,f]=_.useState("editor"),[y,v]=_.useState(null),[g,b]=_.useState(null),{data:j={}}=eit(s),[S,C]=_.useState({name:"",description:"",theme:"",goal:"",primary_cta:"Learn more",warmth_level:"warm",sender_name:"",sender_email:"",reply_to_email:""}),{data:E}=at({queryKey:["brokerage-detail",s],queryFn:async()=>{const{data:ze,error:ke}=await q.from("brokerages").select("name, city, state").eq("id",s).single();if(ke)throw ke;return ze}}),{data:P}=at({queryKey:["brokerage-recruit-settings",s],queryFn:async()=>{const{data:ze,error:ke}=await q.from("brokerage_recruit_settings").select("*").eq("brokerage_id",s).maybeSingle();if(ke)throw ke;return ze}}),M={first_name:"Sarah",brokerage_name:((pe=P==null?void 0:P.merge_fields)==null?void 0:pe.brokerage_name)||(E==null?void 0:E.name)||"Your Brokerage",city:((Ce=P==null?void 0:P.merge_fields)==null?void 0:Ce.city)||(E==null?void 0:E.city)||"Your City",sender_name:((Ae=P==null?void 0:P.merge_fields)==null?void 0:Ae.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:O}=at({queryKey:["recruit-campaigns",s],queryFn:async()=>{const{data:ze,error:ke}=await q.from("recruit_campaigns").select("*").or(`brokerage_id.is.null,brokerage_id.eq.${s}`).order("sort_order");if(ke)throw ke;return ze}}),{data:V={}}=at({queryKey:["recruit-campaign-emails",s],enabled:D.length>0,queryFn:async()=>{const ze=D.map(Fe=>Fe.id),{data:ke,error:Ze}=await q.from("recruit_campaign_emails").select("*").in("campaign_id",ze).order("email_number");if(Ze)throw Ze;const Se={};return ke.forEach(Fe=>{Se[Fe.campaign_id]||(Se[Fe.campaign_id]=[]),Se[Fe.campaign_id].push(Fe)}),Se}}),G=Object.values(V).flat().map(ze=>ze.id),{data:$=[]}=at({queryKey:["recruit-subject-overrides",s],enabled:G.length>0,queryFn:async()=>{const{data:ze,error:ke}=await q.from("recruit_brokerage_subject_overrides").select("*").eq("brokerage_id",s);if(ke)throw ke;return ze}}),H={};$.forEach(ze=>{H[ze.campaign_email_id]=ze.selected_subject_index});const Y=mt({mutationFn:async({campaignEmailId:ze,selectedIndex:ke})=>{const{error:Ze}=await q.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(Ze)throw Ze},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-subject-overrides",s]}),se.success("Subject line updated for your brokerage")},onError:ze=>se.error(ze.message)}),Z=mt({mutationFn:async ze=>{const{error:ke}=await q.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"]}),se.success("Email template saved!"),l(null)},onError:ze=>se.error(ze.message)}),ne=mt({mutationFn:async()=>{const ze=S.name.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,""),{data:ke,error:Ze}=await q.from("recruit_campaigns").insert({name:S.name,slug:ze,description:S.description||null,theme:S.theme||null,goal:S.goal||null,primary_cta:S.primary_cta||"Learn more",warmth_level:S.warmth_level,brokerage_id:s,created_by:t==null?void 0:t.id,sender_name:S.sender_name||null,sender_email:S.sender_email||null,reply_to_email:S.reply_to_email||null,is_active:!0,sort_order:D.length+1}).select().single();if(Ze)throw Ze;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:Fe}=await q.from("recruit_campaign_emails").insert(Se.map(Ne=>({campaign_id:ke.id,...Ne,body_html:"

Hi {{first_name}},

Write your message here...

Best,
{{sender_name}}

",body_text:"",subject_line_options:[],is_active:!0})));if(Fe)throw Fe;return ke},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaigns"]}),n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),se.success("Campaign created with 4 starter emails!"),m(!1),C({name:"",description:"",theme:"",goal:"",primary_cta:"Learn more",warmth_level:"warm",sender_name:"",sender_email:"",reply_to_email:""})},onError:ze=>se.error(ze.message)}),ce=mt({mutationFn:async ze=>{const{error:ke}=await q.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"]}),se.success("Campaign settings saved!"),v(null)},onError:ze=>se.error(ze.message)}),ie=mt({mutationFn:async ze=>{var Ye,Ve;const{data:ke}=await q.from("recruit_campaign_emails").select("email_number, delay_days").eq("campaign_id",ze).order("email_number",{ascending:!1}).limit(1),Ze=((Ye=ke==null?void 0:ke[0])==null?void 0:Ye.email_number)??0,Se=((Ve=ke==null?void 0:ke[0])==null?void 0:Ve.delay_days)??0,Fe=Ze+1,{error:Ne}=await q.from("recruit_campaign_emails").insert({campaign_id:ze,email_number:Fe,title:`Email ${Fe}`,subject_line:"Hey {{first_name}}",subject_line_options:[],body_html:"

Hi {{first_name}},

Write your message here...

Best,
{{sender_name}}

",body_text:"",delay_days:Se+7,is_active:!0});if(Ne)throw Ne},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),se.success("Email added to campaign!")},onError:ze=>se.error(ze.message)}),te=mt({mutationFn:async ze=>{const{error:ke}=await q.from("recruit_campaigns").delete().eq("id",ze);if(ke)throw ke},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaigns"]}),n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),se.success("Campaign deleted")},onError:ze=>se.error(ze.message)}),ae=mt({mutationFn:async ze=>{const{error:ke}=await q.from("recruit_campaign_emails").delete().eq("id",ze);if(ke)throw ke},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),se.success("Email removed from campaign")},onError:ze=>se.error(ze.message)}),le=mt({mutationFn:async({emailId:ze,delay_days:ke})=>{const{error:Ze}=await q.from("recruit_campaign_emails").update({delay_days:ke,updated_at:new Date().toISOString()}).eq("id",ze);if(Ze)throw Ze},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),se.success("Send delay updated")},onError:ze=>se.error(ze.message)});if(O)return e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})});const be=D.filter(ze=>!ze.brokerage_id),me=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(B,{variant:"outline",size:"sm",onClick:()=>u(!0),className:"gap-1.5",children:[e.jsx(qc,{className:"h-4 w-4"})," Default Settings"]}),e.jsxs(B,{size:"sm",onClick:()=>m(!0),className:"gap-1.5",children:[e.jsx(rn,{className:"h-4 w-4"})," New Campaign"]})]})]}),e.jsx(ve,{className:"border-primary/20 bg-primary/5",children:e.jsx(Me,{className:"py-3",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(un,{className:"h-5 w-5 text-primary mt-0.5 shrink-0"}),e.jsxs("div",{className:"text-sm",children:[e.jsx("p",{className:"font-semibold",children:"Per-Campaign Email Settings"}),e.jsxs("p",{className:"text-muted-foreground",children:["Each campaign can override the default sender name, email, and reply-to. Click the ",e.jsx(qc,{className:"inline h-3.5 w-3.5"})," icon on any campaign to customize."]})]})]})})}),me.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(Hq,{className:"h-4 w-4"})," Your Custom Campaigns"]}),e.jsx("div",{className:"space-y-3",children:me.map(ze=>he(ze,!0))})]}),be.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"text-sm font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4"})," System Campaigns"]}),e.jsx("div",{className:"space-y-3",children:be.map(ze=>he(ze,!1))})]}),D.length===0&&e.jsx(ve,{children:e.jsxs(Me,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(ln,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No campaigns yet. Create your first campaign to start automated outreach."}),e.jsxs(B,{className:"mt-4",onClick:()=>m(!0),children:[e.jsx(rn,{className:"h-4 w-4 mr-1"})," Create Campaign"]})]})}),e.jsx(Lnr,{open:!!g,onClose:()=>b(null),campaignName:(g==null?void 0:g.name)||"",stat:g&&j[g.id]||null}),o&&e.jsx(Brs,{email:o,mergeValues:M,selectedSubjectIndex:H[o.id],onClose:()=>c(null)}),e.jsx(Ls,{open:!!i,onOpenChange:ze=>!ze&&l(null),children:e.jsxs(Ps,{className:"max-w-4xl max-h-[90vh] overflow-y-auto p-0",children:[e.jsxs(Os,{className:"px-6 pt-6 pb-4 border-b",children:[e.jsxs(Ds,{className:"flex items-center gap-2",children:[e.jsx(ZM,{className:"h-5 w-5 text-primary"}),"Edit Email #",i==null?void 0:i.email_number]}),e.jsx(_r,{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(J,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Email Title"}),e.jsx(xe,{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(J,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Delay (days after previous)"}),e.jsx(xe,{type:"number",min:0,max:90,value:i.delay_days,onChange:ze=>l({...i,delay_days:parseInt(ze.target.value)||7}),className:"h-9"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Subject Line"}),e.jsx(xe,{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(J,{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(Ms,{value:((Pe=i.subject_line_options)==null?void 0:Pe.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(J,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Email Body"}),e.jsx(Yr,{value:p,onValueChange:ze=>f(ze),children:e.jsxs(Zr,{className:"h-7",children:[e.jsx(Ht,{value:"editor",className:"text-xs px-3 h-6",children:"Editor"}),e.jsx(Ht,{value:"preview",className:"text-xs px-3 h-6",children:"Preview"})]})})]}),p==="editor"?e.jsx(Pnr,{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(B,{variant:"outline",size:"sm",onClick:()=>l(null),children:"Cancel"}),e.jsxs(B,{size:"sm",onClick:()=>Z.mutate(i),disabled:Z.isPending,className:"gap-1.5",children:[e.jsx(Ho,{className:"h-3.5 w-3.5"})," Save Changes"]})]})]})]})]})}),e.jsx(Ls,{open:h,onOpenChange:m,children:e.jsxs(Ps,{className:"max-w-lg",children:[e.jsxs(Os,{children:[e.jsxs(Ds,{className:"flex items-center gap-2",children:[e.jsx(rn,{className:"h-5 w-5 text-primary"})," Create Custom Campaign"]}),e.jsx(_r,{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(J,{className:"text-xs font-medium",children:"Campaign Name *"}),e.jsx(xe,{value:S.name,onChange:ze=>C({...S,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(J,{className:"text-xs font-medium",children:"Warmth Level"}),e.jsxs(is,{value:S.warmth_level,onValueChange:ze=>C({...S,warmth_level:ze}),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"cold",children:"❄️ Cold — Curiosity"}),e.jsx(He,{value:"warm",children:"☀️ Warm — Growth"}),e.jsx(He,{value:"hot",children:"🔥 Hot — Private Invite"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs font-medium",children:"Primary CTA"}),e.jsx(xe,{value:S.primary_cta,onChange:ze=>C({...S,primary_cta:ze.target.value}),placeholder:"Learn more"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs font-medium",children:"Description"}),e.jsx(Ms,{value:S.description,onChange:ze=>C({...S,description:ze.target.value}),placeholder:"What is this campaign about?",rows:2})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs font-medium",children:"Goal"}),e.jsx(xe,{value:S.goal,onChange:ze=>C({...S,goal:ze.target.value}),placeholder:"e.g. Convert warm leads to meetings"})]}),e.jsxs(f1,{children:[e.jsx(x1,{asChild:!0,children:e.jsxs(B,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs font-medium text-muted-foreground hover:text-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(ln,{className:"h-3.5 w-3.5"})," Email Settings Override"]}),e.jsx(tl,{className:"h-3.5 w-3.5"})]})}),e.jsxs(g1,{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(J,{className:"text-xs",children:"Sender Name"}),e.jsx(xe,{value:S.sender_name,onChange:ze=>C({...S,sender_name:ze.target.value}),placeholder:"e.g. Jeremy at LevelUp"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs",children:"Sender Email"}),e.jsx(xe,{value:S.sender_email,onChange:ze=>C({...S,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(J,{className:"text-xs",children:"Reply-To Email"}),e.jsx(xe,{value:S.reply_to_email,onChange:ze=>C({...S,reply_to_email:ze.target.value}),placeholder:"e.g. jeremy@mybrokerage.com"})]})]})]}),e.jsxs(B,{className:"w-full",disabled:!S.name.trim()||ne.isPending,onClick:()=>ne.mutate(),children:[e.jsx(rn,{className:"h-4 w-4 mr-1"})," Create Campaign"]})]})]})}),e.jsx(Ls,{open:!!y,onOpenChange:ze=>!ze&&v(null),children:e.jsxs(Ps,{className:"max-w-lg",children:[e.jsxs(Os,{children:[e.jsxs(Ds,{className:"flex items-center gap-2",children:[e.jsx(qc,{className:"h-5 w-5 text-primary"})," Campaign Email Settings"]}),e.jsx(_r,{children:"Override the default sender for this campaign. Leave blank to use brokerage defaults."})]}),y&&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(J,{className:"text-xs font-medium",children:"Campaign Name"}),e.jsx(xe,{value:y.name,onChange:ze=>v({...y,name:ze.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs font-medium",children:"Warmth Level"}),e.jsxs(is,{value:y.warmth_level,onValueChange:ze=>v({...y,warmth_level:ze}),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"cold",children:"❄️ Cold"}),e.jsx(He,{value:"warm",children:"☀️ Warm"}),e.jsx(He,{value:"hot",children:"🔥 Hot"})]})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs font-medium",children:"Goal"}),e.jsx(xe,{value:y.goal||"",onChange:ze=>v({...y,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(ln,{className:"h-4 w-4 text-primary"})," Email Sender Override"]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs",children:"Sender Name"}),e.jsx(xe,{value:y.sender_name||"",onChange:ze=>v({...y,sender_name:ze.target.value}),placeholder:"Uses brokerage default"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs",children:"Sender Email"}),e.jsx(xe,{value:y.sender_email||"",onChange:ze=>v({...y,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(J,{className:"text-xs",children:"Reply-To Email"}),e.jsx(xe,{value:y.reply_to_email||"",onChange:ze=>v({...y,reply_to_email:ze.target.value}),placeholder:"Uses brokerage default"})]})]}),e.jsxs(B,{className:"w-full",onClick:()=>ce.mutate(y),disabled:ce.isPending,children:[e.jsx(Ho,{className:"h-4 w-4 mr-1"})," Save Campaign Settings"]})]})]})}),e.jsx(Ls,{open:d,onOpenChange:u,children:e.jsxs(Ps,{className:"max-w-lg",children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Default Recruiting Email Settings"}),e.jsx(_r,{children:"These defaults apply to campaigns without their own overrides."})]}),e.jsx(Jat,{brokerageId:s})]})})]});function he(ze,ke){const Ze=j4t[ze.warmth_level]||j4t.cold,Se=Ze.icon,Fe=V[ze.id]||[],Ne=r===ze.id,Ye=!!(ze.sender_name||ze.sender_email||ze.reply_to_email),Ve=j[ze.id];return e.jsxs(ve,{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(Ne?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 ${Ze.bg} flex items-center justify-center`,children:e.jsx(Se,{className:`h-5 w-5 ${Ze.color}`})}),e.jsxs("div",{children:[e.jsxs(St,{className:"text-base flex items-center gap-2",children:[ze.name,e.jsx(Oe,{variant:ze.is_active?"default":"secondary",className:"text-[10px] px-1.5",children:ze.is_active?"Active":"Draft"}),ke&&e.jsx(Oe,{variant:"outline",className:"text-[10px] px-1.5",children:"Custom"}),Ye&&e.jsxs(Oe,{variant:"outline",className:"text-[10px] px-1.5 border-primary/30 text-primary",children:[e.jsx(ln,{className:"h-2.5 w-2.5 mr-0.5"})," Custom Sender"]})]}),e.jsx(kn,{className:"text-xs mt-0.5",children:ze.theme||ze.description})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:qe=>{qe.stopPropagation(),v({...ze})},children:e.jsx(qc,{className:"h-4 w-4 text-muted-foreground"})}),ke&&e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:async qe=>{qe.stopPropagation(),await Xi("Delete this campaign and all its emails? This cannot be undone.")&&te.mutate(ze.id)},children:e.jsx(Sn,{className:"h-4 w-4"})}),Ve&&Ve.sent>0&&e.jsxs("div",{className:"hidden md:flex items-center gap-1.5",children:[e.jsxs(Oe,{variant:"outline",className:"text-[10px] gap-1 font-medium",title:"Total emails sent",children:[e.jsx(ln,{className:"h-2.5 w-2.5"})," ",Ve.sent.toLocaleString()]}),e.jsxs(Oe,{variant:"outline",className:"text-[10px] gap-1 border-amber-500/30 text-amber-600 font-medium",title:`${Ve.openRate.toFixed(1)}% open rate`,children:[e.jsx(ya,{className:"h-2.5 w-2.5"})," ",Ve.opened.toLocaleString()," (",Ve.openRate.toFixed(0),"%)"]}),e.jsxs(Oe,{variant:"outline",className:"text-[10px] gap-1 border-green-500/30 text-green-600 font-medium",title:`${Ve.clickRate.toFixed(1)}% click rate`,children:[e.jsx($h,{className:"h-2.5 w-2.5"})," ",Ve.clicked.toLocaleString()," (",Ve.clickRate.toFixed(1),"%)"]})]}),e.jsxs(B,{variant:"outline",size:"sm",className:"h-7 px-2 gap-1 text-xs",onClick:qe=>{qe.stopPropagation(),b(ze)},title:"View detailed engagement stats",children:[e.jsx(bl,{className:"h-3.5 w-3.5"})," Stats"]}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(ln,{className:"h-3.5 w-3.5"}),e.jsxs("span",{children:[Fe.length," emails"]})]}),e.jsx("div",{className:"h-7 w-7 rounded-md flex items-center justify-center",children:Ne?e.jsx(_v,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(tl,{className:"h-4 w-4 text-muted-foreground"})})]})]})}),Ne&&e.jsxs(Me,{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||"—"})]})]}),Ye&&e.jsxs("div",{className:"p-3 rounded-lg bg-primary/5 border border-primary/10 text-sm",children:[e.jsxs("p",{className:"text-xs font-semibold text-primary mb-1 flex items-center gap-1",children:[e.jsx(ln,{className:"h-3 w-3"})," Campaign Sender Override"]}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 text-xs text-muted-foreground",children:[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:Fe.map((qe,Qe)=>{var Ue,Xe;return e.jsxs("div",{className:"relative flex gap-4 pb-4 last:pb-0",children:[Qent.stopPropagation(),onBlur:nt=>{const $e=parseInt(nt.target.value)||0;$e!==qe.delay_days&&le.mutate({emailId:qe.id,delay_days:$e})},onKeyDown:nt=>{nt.key==="Enter"&&nt.target.blur()}}),"days"]})]}):e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Gr,{className:"h-3 w-3"}),qe.email_number===1?"Sent immediately":`Day ${qe.delay_days}`]}),e.jsx("span",{className:"text-border",children:"•"}),e.jsxs("span",{className:"truncate",children:["Subject: ",I(((Ue=qe.subject_line_options)==null?void 0:Ue.length)>0&&qe.subject_line_options[H[qe.id]??0]||qe.subject_line)]})]}),((Xe=qe.subject_line_options)==null?void 0:Xe.length)>1&&e.jsx("div",{className:"mt-2",children:e.jsxs(is,{value:String(H[qe.id]??0),onValueChange:nt=>Y.mutate({campaignEmailId:qe.id,selectedIndex:parseInt(nt)}),children:[e.jsx(rs,{className:"h-7 text-xs w-full max-w-sm",children:e.jsx(ls,{placeholder:"Choose subject line"})}),e.jsx(as,{children:qe.subject_line_options.map((nt,$e)=>e.jsxs(He,{value:String($e),className:"text-xs",children:[e.jsxs("span",{className:"font-medium mr-1.5",children:[$e===0?"Primary":`Alt ${$e}`,":"]}),I(nt)]},$e))})]})})]}),e.jsxs("div",{className:"flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity shrink-0",children:[e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>c(qe),children:e.jsx(ya,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>{l({...qe}),f("editor")},children:e.jsx(Ya,{className:"h-4 w-4"})}),ke&&Fe.length>1&&e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:async()=>{await Xi("Delete this email from the sequence?")&&ae.mutate(qe.id)},children:e.jsx(Sn,{className:"h-4 w-4"})})]})]})})]},qe.id)})}),ke&&e.jsxs(B,{variant:"outline",size:"sm",className:"w-full gap-1.5",onClick:()=>ie.mutate(ze.id),disabled:ie.isPending,children:[e.jsx(rn,{className:"h-3.5 w-3.5"})," Add Email to Sequence"]})]})]},ze.id)}}const N4t={active:{icon:Jd,color:"bg-green-500/10 text-green-600",label:"Active"},paused:{icon:ky,color:"bg-amber-500/10 text-amber-600",label:"Paused"},completed:{icon:_l,color:"bg-blue-500/10 text-blue-600",label:"Completed"},cancelled:{icon:Rd,color:"bg-red-500/10 text-red-600",label:"Cancelled"}},k4t={sent:{icon:ln,color:"text-blue-500"},opened:{icon:ya,color:"text-amber-500"},clicked:{icon:$h,color:"text-green-500"},failed:{icon:xl,color:"text-destructive"}};function $rs({brokerageId:s}){var Pe,ze,ke,Ze,Se;const{user:t}=hs(),n=Bt(),[r,a]=_.useState(!1),[i,l]=_.useState(""),[o,c]=_.useState(new Set),[d,u]=_.useState("assignments"),[h,m]=_.useState(null),[p,f]=_.useState(""),[y,v]=_.useState("all"),[g,b]=_.useState("all"),[j,S]=_.useState(!1),{data:C}=iae(),{data:E={}}=at({queryKey:["recruit-campaign-emails-for-preview",s],queryFn:async()=>{const{data:Fe,error:Ne}=await q.from("recruit_campaign_emails").select("*").order("email_number");if(Ne)throw Ne;const Ye={};return(Fe??[]).forEach(Ve=>{Ye[Ve.campaign_id]||(Ye[Ve.campaign_id]=[]),Ye[Ve.campaign_id].push(Ve)}),Ye}}),{data:P}=at({queryKey:["brokerage-detail",s],queryFn:async()=>{const{data:Fe,error:Ne}=await q.from("brokerages").select("name, city, state").eq("id",s).single();if(Ne)throw Ne;return Fe}}),{data:M}=at({queryKey:["brokerage-recruit-settings",s],queryFn:async()=>{const{data:Fe,error:Ne}=await q.from("brokerage_recruit_settings").select("*").eq("brokerage_id",s).maybeSingle();if(Ne)throw Ne;return Fe}}),{data:I=[]}=at({queryKey:["recruit-subject-overrides",s],queryFn:async()=>{const{data:Fe,error:Ne}=await q.from("recruit_brokerage_subject_overrides").select("*").eq("brokerage_id",s);if(Ne)throw Ne;return Fe}}),D={};I.forEach(Fe=>{D[Fe.campaign_email_id]=Fe.selected_subject_index});const O={first_name:((Pe=h==null?void 0:h.prospect)==null?void 0:Pe.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:((Ze=M==null?void 0:M.merge_fields)==null?void 0:Ze.sender_name)||(M==null?void 0:M.sender_name)||"Your Name"},V=Fe=>{const Ne=E[Fe.campaign_id]||[],Ye=Fe.current_email_number+1;return Ne.find(Ve=>Ve.email_number===Ye)||null},{data:G=[],isLoading:$}=at({queryKey:["recruit-campaign-assignments",s],queryFn:async()=>{let Ne=[],Ye=0;for(;;){const{data:Ve,error:qe}=await q.from("recruit_campaign_assignments").select(` *, prospect:recruit_prospects(first_name, last_name, email), campaign:recruit_campaigns(name, warmth_level) `).eq("brokerage_id",s).order("created_at",{ascending:!1}).range(Ye,Ye+1e3-1);if(qe)throw qe;if(Ne=Ne.concat(Ve??[]),!Ve||Ve.length<1e3)break;Ye+=1e3}return Ne}}),{data:H=[]}=at({queryKey:["recruit-campaign-sends",s],queryFn:async()=>{const{data:Fe,error:Ne}=await q.from("recruit_campaign_sends").select(` *, prospect:recruit_prospects(first_name, last_name, email), campaign_email:recruit_campaign_emails(title, campaign_id) `).eq("brokerage_id",s).neq("status","failed").order("sent_at",{ascending:!1}).limit(500);if(Ne)throw Ne;return Fe}}),{data:Y=[]}=at({queryKey:["recruit-campaigns"],queryFn:async()=>{const{data:Fe,error:Ne}=await q.from("recruit_campaigns").select("id, name, warmth_level").eq("is_active",!0).order("sort_order");if(Ne)throw Ne;return Fe}}),{data:Z=[]}=at({queryKey:["recruit-prospects-for-assign",s],queryFn:async()=>{let Ne=[],Ye=0;for(;;){const{data:Ve,error:qe}=await q.from("recruit_prospects").select("id, first_name, last_name, email").eq("brokerage_id",s).order("first_name").range(Ye,Ye+1e3-1);if(qe)throw qe;if(Ne=Ne.concat(Ve??[]),!Ve||Ve.length<1e3)break;Ye+=1e3}return Ne}}),ne=new Set(G.map(Fe=>`${Fe.prospect_id}-${Fe.campaign_id}`)),ce=mt({mutationFn:async()=>{if(!i||o.size===0)throw new Error("Select a campaign and at least one prospect");const Fe=new Date,Ne=Array.from(o).filter(Ve=>!ne.has(`${Ve}-${i}`)).map(Ve=>({prospect_id:Ve,campaign_id:i,brokerage_id:s,assigned_by:t.id,status:"active",current_email_number:0,next_send_at:Fe.toISOString(),started_at:Fe.toISOString()}));if(Ne.length===0)throw new Error("All selected prospects are already assigned to this campaign");const{error:Ye}=await q.from("recruit_campaign_assignments").insert(Ne);if(Ye)throw Ye},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-assignments",s]}),se.success(`Campaign assigned to ${o.size} prospect(s)!`),a(!1),l(""),c(new Set)},onError:Fe=>se.error(Fe.message)}),ie=mt({mutationFn:async({id:Fe,newStatus:Ne})=>{const{error:Ye}=await q.from("recruit_campaign_assignments").update({status:Ne,updated_at:new Date().toISOString()}).eq("id",Fe);if(Ye)throw Ye},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-assignments",s]}),se.success("Assignment updated")}}),te=mt({mutationFn:async()=>{const{data:Fe,error:Ne}=await q.functions.invoke("ses-recruit-drip",{body:{action:"process_drips"}});if(Ne)throw Ne;return Fe},onSuccess:Fe=>{n.invalidateQueries({queryKey:["recruit-campaign-assignments",s]}),n.invalidateQueries({queryKey:["recruit-campaign-sends",s]}),se.success(`Wave sent! ${Fe.sent} emails delivered, ${Fe.skipped} skipped, ${Fe.failed} failed`)},onError:Fe=>se.error(`Send failed: ${Fe.message}`)}),ae=G.filter(Fe=>Fe.status==="active").length;G.filter(Fe=>Fe.status==="completed").length;const le=G.filter(Fe=>Fe.status==="active"&&Fe.next_send_at&&new Date(Fe.next_send_at)<=new Date).length,{data:be={}}=eit(s),me=G.reduce((Fe,Ne)=>Fe+Math.max(0,Ne.current_email_number||0),0),he=Object.values(be).reduce((Fe,Ne)=>Fe+Ne.opened,0),pe=Object.values(be).reduce((Fe,Ne)=>Fe+Ne.clicked,0);Object.values(be).reduce((Fe,Ne)=>Fe+Ne.failed,0);const Ce=me>0?Math.round(he/me*100):0,Ae=me>0?pe/me*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:[le>0&&e.jsxs(B,{variant:"outline",onClick:()=>{te.mutate()},disabled:te.isPending,className:"border-amber-500/50 text-amber-600 hover:bg-amber-500/10",children:[e.jsx(nf,{className:"h-4 w-4 mr-1"}),te.isPending?"Sending...":`Send Next Wave (${le})`]}),e.jsxs(B,{onClick:()=>a(!0),children:[e.jsx(Or,{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(ve,{children:e.jsxs(Me,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(In,{className:"h-7 w-7 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xl font-bold",children:G.length}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Assigned"})]})]})}),e.jsx(ve,{children:e.jsxs(Me,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(Jd,{className:"h-7 w-7 text-green-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xl font-bold",children:ae}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Active"})]})]})}),e.jsx(ve,{children:e.jsxs(Me,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(ln,{className:"h-7 w-7 text-blue-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xl font-bold",children:me.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Emails Sent"})]})]})}),e.jsx(ve,{children:e.jsxs(Me,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(ya,{className:"h-7 w-7 text-amber-500"}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-xl font-bold",children:[Ce,"%"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Open Rate (",he.toLocaleString(),")"]})]})]})}),e.jsx(ve,{children:e.jsxs(Me,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx($h,{className:"h-7 w-7 text-green-500"}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-xl font-bold",children:[Ae.toFixed(1),"%"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Click Rate (",pe.toLocaleString(),")"]})]})]})})]}),e.jsxs(Yr,{value:d,onValueChange:u,children:[e.jsxs(Zr,{children:[e.jsxs(Ht,{value:"assignments",children:["Active Drips (",ae,")"]}),e.jsxs(Ht,{value:"history",children:["Send History (",me.toLocaleString(),")"]})]}),e.jsx(Gt,{value:"assignments",className:"mt-4",children:$?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"})}):G.length===0?e.jsx(ve,{children:e.jsxs(Me,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(Or,{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:G.map(Fe=>{var Ue,Xe,nt,$e;const Ne=N4t[Fe.status]||N4t.active,Ye=Ne.icon,qe=(E[Fe.campaign_id]||[]).length||4,Qe=V(Fe);return e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border hover:bg-muted/30 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsxs(Oe,{className:`text-xs ${Ne.color} border-0`,children:[e.jsx(Ye,{className:"h-3 w-3 mr-1"}),Ne.label]}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"font-medium text-sm",children:[(Ue=Fe.prospect)==null?void 0:Ue.first_name," ",(Xe=Fe.prospect)==null?void 0:Xe.last_name,e.jsx("span",{className:"text-muted-foreground font-normal ml-2",children:(nt=Fe.prospect)==null?void 0:nt.email})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[($e=Fe.campaign)==null?void 0:$e.name," · Email ",Fe.current_email_number,"/",qe,Fe.next_send_at&&Fe.status==="active"&&e.jsxs(e.Fragment,{children:[" ","· ",e.jsx(Gr,{className:"h-3 w-3 inline"})," Next: ",Hs(new Date(Fe.next_send_at),"MMM d, h:mm a"),new Date(Fe.next_send_at)<=new Date&&e.jsx(Oe,{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:[Qe&&e.jsx(B,{variant:"ghost",size:"sm",title:"Preview next email",onClick:()=>m(Fe),children:e.jsx(ya,{className:"h-3.5 w-3.5"})}),Fe.status==="active"&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>ie.mutate({id:Fe.id,newStatus:"paused"}),children:e.jsx(ky,{className:"h-3.5 w-3.5"})}),Fe.status==="paused"&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>ie.mutate({id:Fe.id,newStatus:"active"}),children:e.jsx(Jd,{className:"h-3.5 w-3.5"})}),(Fe.status==="active"||Fe.status==="paused")&&e.jsx(B,{variant:"ghost",size:"sm",className:"text-destructive",onClick:()=>ie.mutate({id:Fe.id,newStatus:"cancelled"}),children:e.jsx(Rd,{className:"h-3.5 w-3.5"})})]})]},Fe.id)})})}),e.jsxs(Gt,{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(is,{value:y,onValueChange:v,children:[e.jsx(rs,{className:"w-[220px] h-8 text-xs",children:e.jsx(ls,{placeholder:"All campaigns"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All campaigns"}),Y.map(Fe=>e.jsx(He,{value:Fe.id,children:Fe.name},Fe.id))]})]}),e.jsxs(is,{value:g,onValueChange:b,children:[e.jsx(rs,{className:"w-[160px] h-8 text-xs",children:e.jsx(ls,{placeholder:"All statuses"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All statuses"}),e.jsx(He,{value:"sent",children:"Sent (no engagement)"}),e.jsx(He,{value:"opened",children:"Opened"}),e.jsx(He,{value:"clicked",children:"Clicked"})]})]}),(y!=="all"||g!=="all")&&e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 text-xs",onClick:()=>{v("all"),b("all")},children:"Clear"})]}),(()=>{var Ne;const Fe=H.filter(Ye=>{var Ve;return!(y!=="all"&&((Ve=Ye.campaign_email)==null?void 0:Ve.campaign_id)!==y||g==="opened"&&!Ye.opened_at||g==="clicked"&&!Ye.clicked_at||g==="sent"&&(Ye.opened_at||Ye.clicked_at))});return Fe.length===0?e.jsx(ve,{children:e.jsxs(Me,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(ln,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{className:"font-medium",children:H.length===0?"No emails sent yet":"No emails match these filters"}),e.jsx("p",{className:"text-sm",children:H.length===0?"Emails will appear here once campaigns start sending":"Try clearing the filters above"})]})}):e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Showing ",Fe.length," of ",H.length," recent sends",y!=="all"&&` · ${(Ne=Y.find(Ye=>Ye.id===y))==null?void 0:Ne.name}`]}),e.jsx("div",{className:"space-y-1",children:Fe.map(Ye=>{var Ue,Xe,nt;const Ve=k4t[Ye.status]||k4t.sent,qe=Ve.icon,Qe=(Ue=Y.find($e=>{var Ge;return $e.id===((Ge=Ye.campaign_email)==null?void 0:Ge.campaign_id)}))==null?void 0:Ue.name;return e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border hover:bg-muted/30 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx(qe,{className:`h-4 w-4 flex-shrink-0 ${Ve.color}`}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"font-medium text-sm truncate",children:[(Xe=Ye.prospect)==null?void 0:Xe.first_name," ",(nt=Ye.prospect)==null?void 0:nt.last_name,e.jsxs("span",{className:"text-muted-foreground font-normal ml-2",children:["Email #",Ye.email_number]}),Qe&&e.jsx(Oe,{variant:"outline",className:"ml-2 text-[10px] px-1.5 py-0 font-normal",children:Qe})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:Ye.subject})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground flex-shrink-0",children:[Ye.opened_at&&e.jsxs("span",{className:"flex items-center gap-1 text-amber-500",children:[e.jsx(ya,{className:"h-3 w-3"})," ",Hs(new Date(Ye.opened_at),"MMM d")]}),Ye.clicked_at&&e.jsxs("span",{className:"flex items-center gap-1 text-green-500",children:[e.jsx($h,{className:"h-3 w-3"})," ",Hs(new Date(Ye.clicked_at),"MMM d")]}),e.jsx("span",{children:Hs(new Date(Ye.sent_at),"MMM d, h:mm a")})]})]},Ye.id)})})]})})()]})]}),e.jsx(Ls,{open:r,onOpenChange:Fe=>{a(Fe),Fe||(f(""),c(new Set),l(""))},children:e.jsxs(Ps,{className:"max-w-lg max-h-[85vh] flex flex-col p-0",children:[e.jsxs(Os,{className:"px-6 pt-6 pb-4",children:[e.jsx(Ds,{children:"Assign Campaign to Prospects"}),e.jsx(_r,{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(J,{className:"text-sm font-medium",children:"1. Select Campaign"}),e.jsxs(is,{value:i,onValueChange:l,children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Choose a campaign..."})}),e.jsx(as,{children:Y.map(Fe=>e.jsx(He,{value:Fe.id,children:Fe.name},Fe.id))})]})]}),i&&(()=>{const Fe=p.toLowerCase(),Ne=Z.filter(qe=>`${qe.first_name} ${qe.last_name}`.toLowerCase().includes(Fe)||qe.email.toLowerCase().includes(Fe)),Ye=Ne.filter(qe=>!ne.has(`${qe.id}-${i}`)),Ve=Ye.length>0&&Ye.every(qe=>o.has(qe.id));return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(J,{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(Lr,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search by name or email...",value:p,onChange:qe=>f(qe.target.value),className:"pl-9 h-9"})]}),e.jsxs(B,{variant:"outline",size:"sm",className:"h-9 whitespace-nowrap",onClick:()=>{if(Ve){const qe=new Set(o);Ye.forEach(Qe=>qe.delete(Qe.id)),c(qe)}else{const qe=new Set(o);Ye.forEach(Qe=>qe.add(Qe.id)),c(qe)}},children:[e.jsx(HO,{className:"h-3.5 w-3.5 mr-1"}),Ve?"Deselect All":`Select All (${Ye.length})`]})]}),e.jsx("div",{className:"border rounded-lg max-h-60 overflow-y-auto divide-y",children:Ne.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:p?"No prospects match your search":"No prospects found for this brokerage"}):Ne.map(qe=>{const Qe=ne.has(`${qe.id}-${i}`);return e.jsxs("label",{className:`flex items-center gap-3 p-2.5 hover:bg-muted/50 cursor-pointer ${Qe?"opacity-40":""}`,children:[e.jsx($a,{checked:o.has(qe.id),disabled:Qe,onCheckedChange:Ue=>{const Xe=new Set(o);Ue?Xe.add(qe.id):Xe.delete(qe.id),c(Xe)}}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"text-sm font-medium truncate",children:[qe.first_name," ",qe.last_name]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:qe.email})]}),Qe&&e.jsx(Oe,{variant:"outline",className:"text-[10px] shrink-0",children:"Already assigned"})]},qe.id)})}),Ne.length>0&&e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Showing ",Ne.length," of ",Z.length," prospects",Ye.length0&&e.jsx(ve,{className:"bg-primary/5 border-primary/20",children:e.jsxs(Me,{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=Y.find(Fe=>Fe.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(yr,{className:"px-6 py-4 border-t",children:[e.jsx(B,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsxs(B,{onClick:()=>{ce.mutate()},disabled:ce.isPending||!i||o.size===0,children:[e.jsx(Or,{className:"h-4 w-4 mr-1"}),ce.isPending?"Assigning...":`Assign & Start (${o.size})`]})]})]})}),h&&(()=>{const Fe=V(h);return Fe?e.jsx(Brs,{email:Fe,mergeValues:O,selectedSubjectIndex:D[Fe.id],onClose:()=>m(null)}):null})(),e.jsx(cLe,{open:j,onOpenChange:S,hasPending:C==null?void 0:C.hasPendingSes,pendingEmails:C==null?void 0:C.pendingEmails})]})}function Vrs({brokerageId:s}){const t=Bt(),[n,r]=_.useState([]),[a,i]=_.useState([]),[l,o]=_.useState(!1),c=_.useRef(!1),{data:d,isLoading:u}=at({queryKey:["recruit-stages-editor",s],queryFn:async()=>{const{data:v,error:g}=await q.from("recruit_pipeline_stages").select("*").eq("brokerage_id",s).order("sort_order");if(g)throw g;return v},enabled:!!s});_.useEffect(()=>{if(d){if(c.current){c.current=!1;return}r(d.map(v=>({id:v.id,name:v.name,color:v.color,sort_order:v.sort_order}))),i([]),o(!1)}},[d]);const h=mt({mutationFn:async()=>{for(const b of a){const{error:j}=await q.from("recruit_pipeline_stages").delete().eq("id",b);if(j)throw j}const v=n.filter(b=>b.id&&!b.isNew),g=n.filter(b=>!b.id||b.isNew);for(const b of v){const{error:j}=await q.from("recruit_pipeline_stages").update({name:b.name,color:b.color,sort_order:b.sort_order}).eq("id",b.id);if(j)throw j}if(g.length>0){const{error:b}=await q.from("recruit_pipeline_stages").insert(g.map(j=>({brokerage_id:s,name:j.name,color:j.color,sort_order:j.sort_order})));if(b)throw b}},onSuccess:()=>{i([]),t.invalidateQueries({queryKey:["recruit-stages-editor",s]}),t.invalidateQueries({queryKey:["recruit-stages",s]}),se.success("Pipeline stages saved!"),o(!1)},onError:v=>se.error(v.message)}),m=(v,g,b)=>{r(j=>j.map((S,C)=>C===v?{...S,[g]:b}:S)),o(!0)},p=()=>{const v=n.length>0?Math.max(...n.map(g=>g.sort_order)):0;r(g=>[...g,{name:"",color:"#6366f1",sort_order:v+1,isNew:!0}]),o(!0)},f=v=>{const g=n[v];g.id&&!g.isNew&&i(b=>[...b,g.id]),r(b=>b.filter((j,S)=>S!==v)),o(!0)},y=(v,g)=>{const b=v+g;if(b<0||b>=n.length)return;const j=[...n];[j[v],j[b]]=[j[b],j[v]],j.forEach((S,C)=>S.sort_order=C+1),r(j),o(!0)};return u?e.jsx("div",{className:"text-sm text-muted-foreground py-8 text-center",children:"Loading stages…"}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold mb-1",children:"Pipeline Stages"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Customize the recruiting pipeline stages for this brokerage. Changes will apply to the Kanban board and all prospect tracking."})]}),e.jsx("div",{className:"space-y-2",children:n.map((v,g)=>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:()=>y(g,-1),disabled:g===0,className:"text-muted-foreground hover:text-foreground disabled:opacity-30 text-xs",children:"▲"}),e.jsx("button",{type:"button",onClick:()=>y(g,1),disabled:g===n.length-1,className:"text-muted-foreground hover:text-foreground disabled:opacity-30 text-xs",children:"▼"})]}),e.jsx(Vf,{className:"h-4 w-4 text-muted-foreground/50 shrink-0"}),e.jsx("input",{type:"color",value:v.color,onChange:b=>m(g,"color",b.target.value),className:"h-8 w-8 rounded cursor-pointer border-0 p-0 shrink-0"}),e.jsx(xe,{value:v.name,onChange:b=>m(g,"name",b.target.value),placeholder:"Stage name…",className:"flex-1"}),e.jsx("span",{className:"text-xs text-muted-foreground w-6 text-center shrink-0",children:g+1}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>f(g),className:"text-destructive hover:text-destructive shrink-0 h-8 w-8",children:e.jsx(Sn,{className:"h-4 w-4"})})]},v.id||`new-${g}`))}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:p,className:"gap-1",children:[e.jsx(rn,{className:"h-4 w-4"})," Add Stage"]}),l&&e.jsxs(B,{size:"sm",onClick:()=>h.mutate(),disabled:h.isPending,className:"gap-1",children:[e.jsx(Ho,{className:"h-4 w-4"})," Save Changes"]})]}),n.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No stages configured. Add stages to build your recruiting pipeline."})]})}function Inr({brokerageId:s}){const{data:t=[],isLoading:n}=at({queryKey:["recruit-unsubscribed",s],queryFn:async()=>{const{data:r,error:a}=await q.from("recruit_prospects").select("id, first_name, last_name, email, unsubscribed_at, unsubscribe_reason, current_brokerage").eq("brokerage_id",s).not("unsubscribed_at","is",null).order("unsubscribed_at",{ascending:!1}).limit(500);if(a)throw a;return r||[]},enabled:!!s});return n?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-2 border-primary border-t-transparent"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx(i7,{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(Oe,{variant:"secondary",className:"text-base px-3 py-1",children:[t.length," total"]})]}),t.length===0?e.jsx(ve,{children:e.jsxs(Me,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(i7,{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(ve,{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(St,{className:"text-base",children:[r.first_name," ",r.last_name]}),e.jsxs("div",{className:"flex items-center gap-3 text-xs text-muted-foreground mt-1",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ln,{className:"h-3 w-3"}),r.email]}),r.current_brokerage&&e.jsxs("span",{children:["· ",r.current_brokerage]})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground whitespace-nowrap",children:[e.jsx(ga,{className:"h-3 w-3"}),r.unsubscribed_at&&Hs(new Date(r.unsubscribed_at),"MMM d, yyyy")]})]})}),r.unsubscribe_reason&&e.jsx(Me,{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 Dnr(){var o;const[s,t]=_.useState(""),[n,r]=_.useState("board"),{data:a=[],isLoading:i}=at({queryKey:["all-brokerages"],queryFn:async()=>{const{data:c,error:d}=await q.from("brokerages").select("id, name").order("name");if(d)throw d;return c}}),l=s||((o=a[0])==null?void 0:o.id)||"";return i?e.jsx(zs,{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(zs,{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(is,{value:l,onValueChange:t,children:[e.jsxs(rs,{className:"w-[280px]",children:[e.jsx(ai,{className:"mr-2 h-4 w-4"}),e.jsx(ls,{placeholder:"Select brokerage"})]}),e.jsx(as,{children:a.map(c=>e.jsx(He,{value:c.id,children:c.name},c.id))})]})]}):e.jsx("div",{}),l&&e.jsx(Frs,{brokerageId:l,trigger:e.jsxs(B,{size:"sm",className:"gap-1.5",children:[e.jsx(Kr,{className:"h-4 w-4"})," Record & Send Video"]})})]}),l?e.jsxs(Yr,{defaultValue:"pipeline",className:"space-y-4",children:[e.jsxs(Zr,{className:"flex-wrap h-auto gap-1",children:[e.jsx(Ht,{value:"pipeline",children:"Pipeline"}),e.jsxs(Ht,{value:"contacts",children:[e.jsx(In,{className:"h-3.5 w-3.5 mr-1"}),"Contacts"]}),e.jsxs(Ht,{value:"video-outreach",children:[e.jsx(Kr,{className:"h-3.5 w-3.5 mr-1"}),"Video Outreach"]}),e.jsx(Ht,{value:"follow-ups",children:"Follow-ups"}),e.jsx(Ht,{value:"referrals",children:"Referrals"}),e.jsx(Ht,{value:"interest",children:"Interest Form"}),e.jsx(Ht,{value:"landing-page",children:"Landing Page"}),e.jsx(Ht,{value:"goals",children:"Goals"}),e.jsx(Ht,{value:"metrics",children:"Metrics"}),e.jsx(Ht,{value:"templates",children:"Email Templates"}),e.jsxs(Ht,{value:"campaigns",children:[e.jsx(ln,{className:"h-3.5 w-3.5 mr-1"}),"Campaigns"]}),e.jsxs(Ht,{value:"drip-assignments",children:[e.jsx(Or,{className:"h-3.5 w-3.5 mr-1"}),"Drip Assignments"]}),e.jsx(Ht,{value:"activity",children:"Recruiter Activity"}),e.jsxs(Ht,{value:"email-settings",children:[e.jsx(qc,{className:"h-3.5 w-3.5 mr-1"}),"Email Settings"]}),e.jsxs(Ht,{value:"pipeline-stages",children:[e.jsx(tP,{className:"h-3.5 w-3.5 mr-1"}),"Pipeline Stages"]}),e.jsxs(Ht,{value:"unsubscribed",children:[e.jsx(i7,{className:"h-3.5 w-3.5 mr-1"}),"Unsubscribed"]})]}),e.jsxs(Gt,{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(B,{variant:n==="board"?"default":"ghost",size:"sm",className:"h-7 px-2.5 gap-1.5",onClick:()=>r("board"),children:[e.jsx(sf,{className:"h-3.5 w-3.5"})," Board"]}),e.jsxs(B,{variant:n==="table"?"default":"ghost",size:"sm",className:"h-7 px-2.5 gap-1.5",onClick:()=>r("table"),children:[e.jsx(i$,{className:"h-3.5 w-3.5"})," Table"]})]})}),n==="board"?e.jsx(Ers,{brokerageId:l}):e.jsx(KYe,{brokerageId:l})]}),e.jsx(Gt,{value:"contacts",children:e.jsx(KYe,{brokerageId:l})}),e.jsx(Gt,{value:"video-outreach",children:e.jsx(Ors,{brokerageId:l})}),e.jsx(Gt,{value:"follow-ups",children:e.jsx(Drs,{brokerageId:l})}),e.jsx(Gt,{value:"referrals",children:e.jsx(Lrs,{brokerageId:l})}),e.jsx(Gt,{value:"interest",children:e.jsx(Irs,{brokerageId:l})}),e.jsx(Gt,{value:"landing-page",children:e.jsx(Rrs,{brokerageId:l})}),e.jsx(Gt,{value:"goals",children:e.jsx(zrs,{brokerageId:l})}),e.jsx(Gt,{value:"metrics",children:e.jsx(Trs,{brokerageId:l})}),e.jsx(Gt,{value:"templates",children:e.jsx(Mrs,{brokerageId:l})}),e.jsx(Gt,{value:"campaigns",children:e.jsx(qrs,{brokerageId:l})}),e.jsx(Gt,{value:"drip-assignments",children:e.jsx($rs,{brokerageId:l})}),e.jsx(Gt,{value:"activity",children:e.jsx(Prs,{brokerageId:l})}),e.jsx(Gt,{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(Jat,{brokerageId:l})]})}),e.jsx(Gt,{value:"pipeline-stages",children:e.jsx("div",{className:"max-w-2xl",children:e.jsx(Vrs,{brokerageId:l})})}),e.jsx(Gt,{value:"unsubscribed",children:e.jsx(Inr,{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."})]})]})})}const S4t=()=>{const s=new Date;return new Date(s.getFullYear(),s.getMonth(),s.getDate()).getTime()},sU=s=>{const t=s.split(/[-/T]/).slice(0,3).map(Number);return new Date(t[0],(t[1]||1)-1,t[2]||1).getTime()},nU=s=>Date.parse(s);async function RZ(s,t,n){const a=[];for(let i=0;;i+=1e3){const l=n(q.from(s).select(t)).range(i,i+1e3-1),{data:o,error:c}=await l;if(c)throw c;if(a.push(...o??[]),!o||o.length<1e3)break}return a}function Rnr(s){var o;const t=kz(s),n=eit(s),r=at({queryKey:["recruit-command-sources",s,t.prospects.length],enabled:!!s&&!t.isLoading,queryFn:async()=>{if(!s)return{followUps:[],activities:[],goals:[],assignments:[],campaigns:[]};const c=t.prospects.map(f=>f.id),[d,u,h,m,p]=await Promise.all([c.length?RZ("recruit_follow_ups","id, prospect_id, title, due_date, completed_at, assigned_to",f=>f.in("prospect_id",c).order("due_date")):Promise.resolve([]),c.length?RZ("recruit_activities","id, prospect_id, activity_type, title, created_by, created_at",f=>f.in("prospect_id",c).order("created_at",{ascending:!1})):Promise.resolve([]),RZ("recruit_goals","id, title, target_count, target_stage_id, period_start, period_end",f=>f.eq("brokerage_id",s).order("period_end",{ascending:!1})),RZ("recruit_campaign_assignments","id, prospect_id, status",f=>f.eq("brokerage_id",s)),RZ("recruit_campaigns","id, name, is_active, brokerage_id",f=>f.or(`brokerage_id.is.null,brokerage_id.eq.${s}`))]);return{followUps:d,activities:u,goals:h,assignments:m,campaigns:p}}}),a=_.useMemo(()=>{var d;const c=new Set;return t.prospects.forEach(u=>u.created_by&&c.add(u.created_by)),(((d=r.data)==null?void 0:d.activities)??[]).forEach(u=>u.created_by&&c.add(u.created_by)),[...c]},[t.prospects,(o=r.data)==null?void 0:o.activities]),i=at({queryKey:["recruit-command-profiles",s,a],enabled:a.length>0,queryFn:async()=>{const{data:c,error:d}=await q.from("profiles").select("id, name, email").in("id",a);if(d)throw d;return c??[]}});return{..._.useMemo(()=>{var be,me,he,pe,Ce;const c=t.prospects,d=t.stages,u=((be=r.data)==null?void 0:be.followUps)??[],h=((me=r.data)==null?void 0:me.activities)??[],m=((he=r.data)==null?void 0:he.goals)??[],p=((pe=r.data)==null?void 0:pe.assignments)??[],f=((Ce=r.data)==null?void 0:Ce.campaigns)??[],y=S4t(),v=y+864e5,g=Date.now()-30*864e5,b=Date.now()-21*864e5,j=new Map(c.map(Ae=>[Ae.id,Ae])),S=u.filter(Ae=>!Ae.completed_at),C=S.filter(Ae=>nU(Ae.due_date){const Pe=nU(Ae.due_date);return Pe>=y&&Pe{const Pe=j.get(Ae.prospect_id);if(!Pe)return[];const ze=nU(Ae.due_date)Ae.prospect_id));c.filter(Ae=>nU(Ae.updated_at)P.push({id:`stalled-${Ae.id}`,prospect:Ae,title:"No next step scheduled",detail:"No movement in 21+ days",tone:"stalled",dueAt:null}));const I=d.map(Ae=>({...Ae,count:c.filter(Pe=>Pe.stage_id===Ae.id).length,stalled:c.filter(Pe=>Pe.stage_id===Ae.id&&nU(Pe.updated_at)sU(Ae.period_start)<=D&&sU(Ae.period_end)>=D)??null,V=O?c.filter(Ae=>sU(Ae.created_at)>=sU(O.period_start)&&sU(Ae.created_at)<=sU(O.period_end)&&(!O.target_stage_id||Ae.stage_id===O.target_stage_id)).length:0,G=Object.values(n.data??{}),$=G.reduce((Ae,Pe)=>Ae+Pe.sent,0),H=G.reduce((Ae,Pe)=>Ae+Pe.opened,0),Y=$?Math.round(H/$*100):0,Z=new Map((i.data??[]).map(Ae=>[Ae.id,Ae])),ne=a.map(Ae=>{var Ze;const Pe=h.filter(Se=>Se.created_by===Ae),ze=Pe.filter(Se=>nU(Se.created_at)>=g),ke=Z.get(Ae);return{id:Ae,name:(ke==null?void 0:ke.name)||(ke==null?void 0:ke.email)||"Unknown recruiter",email:(ke==null?void 0:ke.email)||"",prospects:c.filter(Se=>Se.created_by===Ae).length,activities30d:ze.length,lastActivityAt:((Ze=Pe[0])==null?void 0:Ze.created_at)??null}}).sort((Ae,Pe)=>Pe.activities30d-Ae.activities30d),ce=new Map;c.forEach(Ae=>{const Pe=(Ae.source||"Not recorded").replace(/_/g," ");ce.set(Pe,(ce.get(Pe)??0)+1)});const ie=[...ce.entries()].sort((Ae,Pe)=>Pe[1]-Ae[1]).slice(0,6),te=new Set(["signed","onboarded","hired","joined"]),ae=new Set(d.filter(Ae=>te.has(Ae.name.toLowerCase())).map(Ae=>Ae.id)),le=c.filter(Ae=>Ae.stage_id&&ae.has(Ae.stage_id)).length;return{prospects:c,stages:I,followUps:u,activities:h,priority:P.slice(0,12),overdueCount:C.length,dueTodayCount:E.length,currentGoal:O,goalCurrent:V,goalPercent:O?Math.min(100,Math.round(V/Math.max(1,O.target_count)*100)):0,campaignOpenRate:Y,campaignSent:$,activeCampaigns:f.filter(Ae=>Ae.is_active).length,activeAssignments:p.filter(Ae=>Ae.status==="active").length,recruiters:ne,sources:ie,converted:le,conversionRate:c.length?Math.round(le/c.length*100):0}},[t.prospects,t.stages,r.data,n.data,i.data,a]),pipeline:t,isLoading:t.isLoading||r.isLoading||n.isLoading||i.isLoading}}const Fnr=s=>s.split(/\s+/).filter(Boolean).slice(0,2).map(t=>t[0]).join("").toUpperCase(),Onr=s=>{if(!s)return"No activity";const t=Math.max(0,Math.floor((Date.now()-Date.parse(s))/864e5));return t===0?"Today":t===1?"Yesterday":`${t}d ago`},Fde=({label:s,value:t,detail:n,icon:r,tone:a,onClick:i})=>e.jsxs("button",{type:"button",onClick:i,className:"flex min-h-[112px] w-full items-start justify-between rounded-md border bg-card p-4 text-left shadow-xs transition-colors hover:border-primary/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase text-muted-foreground",children:s}),e.jsx("p",{className:"mt-1 font-['Outfit'] text-3xl font-bold text-foreground",children:t}),e.jsx("p",{className:"mt-1 truncate text-xs text-muted-foreground",children:n})]}),e.jsx("span",{className:At("flex h-10 w-10 shrink-0 items-center justify-center rounded-full",a),children:e.jsx(r,{className:"h-5 w-5"})})]});function znr({brokerageId:s,onNavigate:t,onOpenProspect:n,onAddProspect:r}){var u;const a=Rnr(s),[i,l]=_.useState("all"),o=i==="all"?a.priority:a.priority.filter(h=>h.tone===i),c=Math.max(1,...a.stages.map(h=>h.count)),d=Math.max(1,...a.sources.map(([,h])=>h));return a.isLoading?e.jsxs("div",{className:"space-y-4","aria-busy":"true",children:[e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4",children:[0,1,2,3].map(h=>e.jsx(cn,{className:"h-28 rounded-md"},h))}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,1.5fr)_minmax(300px,.8fr)]",children:[e.jsx(cn,{className:"h-[520px] rounded-md"}),e.jsx(cn,{className:"h-[520px] rounded-md"})]})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4",children:[e.jsx(Fde,{label:"Active pipeline",value:a.prospects.length,detail:`${a.converted} converted · ${a.conversionRate}% rate`,icon:x0,tone:"bg-primary/10 text-primary",onClick:()=>t("pipeline-board")}),e.jsx(Fde,{label:"Follow-ups due",value:a.overdueCount+a.dueTodayCount,detail:`${a.overdueCount} overdue · ${a.dueTodayCount} today`,icon:Tq,tone:a.overdueCount?"bg-destructive/10 text-destructive":"bg-amber-500/10 text-amber-700",onClick:()=>t("pipeline-follow-ups")}),e.jsx(Fde,{label:"Campaign engagement",value:`${a.campaignOpenRate}%`,detail:`${a.campaignSent} sent · ${a.activeAssignments} enrolled`,icon:Vq,tone:"bg-emerald-500/10 text-emerald-700",onClick:()=>t("campaigns-manager")}),e.jsx(Fde,{label:"Current goal",value:a.currentGoal?`${a.goalCurrent}/${a.currentGoal.target_count}`:"—",detail:((u=a.currentGoal)==null?void 0:u.title)||"No active goal set",icon:ku,tone:"bg-recruit-gold/15 text-recruit-navy",onClick:()=>t("reporting-goals")})]}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,1.55fr)_minmax(310px,.75fr)]",children:[e.jsxs("section",{className:"overflow-hidden rounded-md border bg-card shadow-xs",children:[e.jsxs("header",{className:"flex flex-col gap-3 border-b p-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"font-['Outfit'] text-base font-semibold",children:"Needs attention"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"The next recruiting moves with the most urgency"})]}),e.jsx("div",{className:"flex flex-wrap gap-1 rounded-md bg-muted/50 p-1",children:["all","overdue","today","stalled"].map(h=>e.jsx(B,{size:"sm",variant:i===h?"default":"ghost",className:"h-7 px-2.5 text-xs capitalize",onClick:()=>l(h),children:h},h))})]}),e.jsxs("div",{className:"divide-y",children:[o.length===0&&e.jsxs("div",{className:"px-4 py-12 text-center",children:[e.jsx(Er,{className:"mx-auto mb-2 h-7 w-7 text-emerald-600"}),e.jsx("p",{className:"text-sm font-medium",children:"Your priority queue is clear."}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Add a prospect or review the full pipeline for your next move."})]}),o.slice(0,8).map(h=>{const m=`${h.prospect.first_name} ${h.prospect.last_name||""}`.trim();return e.jsxs("button",{type:"button",onClick:()=>n(h.prospect),className:"group flex w-full items-center gap-3 px-4 py-3 text-left transition-colors hover:bg-muted/30 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",children:[e.jsx(ja,{className:"h-9 w-9",children:e.jsx(Na,{className:"bg-primary/10 text-xs font-semibold text-primary",children:Fnr(m)})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"truncate text-sm font-semibold",children:m}),e.jsx(Oe,{className:At("border-0 text-[10px]",h.tone==="overdue"?"bg-destructive/10 text-destructive":h.tone==="today"?"bg-amber-500/10 text-amber-700":"bg-muted text-muted-foreground"),children:h.tone==="stalled"?"Stalled":h.tone==="today"?"Due today":"Overdue"})]}),e.jsxs("p",{className:"truncate text-xs text-muted-foreground",children:[h.title," · ",h.prospect.current_brokerage||h.detail]})]}),e.jsx(La,{className:"h-4 w-4 shrink-0 text-muted-foreground transition-transform group-hover:translate-x-0.5 group-hover:text-primary"})]},h.id)})]}),e.jsxs("footer",{className:"flex flex-wrap items-center justify-between gap-2 border-t bg-muted/10 px-4 py-3",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>t("pipeline-follow-ups"),children:["View all follow-ups ",e.jsx(La,{className:"ml-1.5 h-3.5 w-3.5"})]}),e.jsxs(B,{size:"sm",onClick:r,children:[e.jsx(Pl,{className:"mr-1.5 h-3.5 w-3.5"}),"Add prospect"]})]})]}),e.jsxs("section",{className:"rounded-md border bg-card p-4 shadow-xs",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"font-['Outfit'] text-base font-semibold",children:"Goal pace"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Progress toward the current target"})]}),e.jsxs("span",{className:"font-['Outfit'] text-xl font-bold text-primary",children:[a.goalPercent,"%"]})]}),e.jsx(Fi,{value:a.goalPercent,className:"h-2.5"}),e.jsxs("div",{className:"mt-5 border-t pt-4",children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between",children:[e.jsx("h3",{className:"font-['Outfit'] text-sm font-semibold",children:"Recruiter accountability"}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>t("reporting-activity"),children:"Full activity"})]}),e.jsxs("div",{className:"space-y-3",children:[a.recruiters.slice(0,5).map((h,m)=>e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"flex h-7 w-7 items-center justify-center rounded-full bg-muted text-xs font-bold",children:m+1}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:h.name}),e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Last activity ",Onr(h.lastActivityAt)]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"font-['Outfit'] text-base font-bold",children:h.activities30d}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"30d moves"})]})]},h.id)),!a.recruiters.length&&e.jsx("p",{className:"py-5 text-center text-sm text-muted-foreground",children:"Recruiter activity will appear here."})]})]})]})]}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsxs(ve,{className:"rounded-md p-4 shadow-xs",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"font-['Outfit'] text-base font-semibold",children:"Pipeline momentum"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Volume and stalled prospects by stage"})]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>t("pipeline-board"),children:"Open board"})]}),e.jsxs("div",{className:"space-y-3",children:[a.stages.map(h=>e.jsxs("div",{children:[e.jsxs("div",{className:"mb-1 flex items-center justify-between text-xs",children:[e.jsxs("span",{className:"flex min-w-0 items-center gap-2 font-medium",children:[e.jsx("span",{className:"h-2.5 w-2.5 shrink-0 rounded-full",style:{backgroundColor:h.color}}),e.jsx("span",{className:"truncate",children:h.name}),h.stalled>0&&e.jsxs("span",{className:"text-amber-700",children:[h.stalled," stalled"]})]}),e.jsx("span",{className:"font-bold",children:h.count})]}),e.jsx("div",{className:"h-2 overflow-hidden rounded-full bg-muted",children:e.jsx("div",{className:"h-full rounded-full bg-primary transition-[width] motion-reduce:transition-none",style:{width:`${Math.max(h.count?5:0,h.count/c*100)}%`}})})]},h.id)),!a.stages.length&&e.jsx("p",{className:"py-8 text-center text-sm text-muted-foreground",children:"Set up pipeline stages to see momentum."})]})]}),e.jsxs(ve,{className:"rounded-md p-4 shadow-xs",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"font-['Outfit'] text-base font-semibold",children:"Source intelligence"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Where recruiting relationships originate"})]}),e.jsxs("span",{className:"flex items-center gap-1 text-xs font-semibold text-primary",children:[e.jsx(Nl,{className:"h-3.5 w-3.5"}),a.conversionRate,"% conversion"]})]}),e.jsxs("div",{className:"space-y-3",children:[a.sources.map(([h,m])=>e.jsxs("div",{className:"grid grid-cols-[minmax(100px,1fr)_2fr_32px] items-center gap-3",children:[e.jsx("span",{className:"truncate text-xs font-medium capitalize",children:h}),e.jsx("div",{className:"h-2 overflow-hidden rounded-full bg-muted",children:e.jsx("div",{className:"h-full rounded-full bg-recruit-gold",style:{width:`${Math.max(6,m/d*100)}%`}})}),e.jsx("span",{className:"text-right text-xs font-bold",children:m})]},h)),!a.sources.length&&e.jsx("p",{className:"py-8 text-center text-sm text-muted-foreground",children:"Source data will appear as prospects are added."})]}),e.jsxs(B,{variant:"outline",size:"sm",className:"mt-5 w-full",onClick:()=>t("reporting-metrics"),children:[e.jsx(bl,{className:"mr-1.5 h-3.5 w-3.5"}),"Open recruiting analytics"]})]})]})]})}function Bnr({brokerageId:s}){const[t,n]=_.useState(""),[r,a]=_.useState("all"),{data:i,isLoading:l}=at({queryKey:["recruit-sent-emails",s],queryFn:async()=>{var v;const{data:d,error:u}=await q.from("recruit_prospects").select("id, first_name, last_name, email").eq("brokerage_id",s);if(u)throw u;const h=new Map((d||[]).map(g=>[g.id,g]));if(Array.from(h.keys()).length===0)return[];const{data:p}=await q.from("recruit_videos").select("id, prospect_id, share_token, sent_at, sent_via, view_count, first_viewed_at, cta_clicked_at, video:agent_videos(title)").eq("brokerage_id",s).not("sent_at","is",null).order("sent_at",{ascending:!1}),{data:f}=await q.from("recruit_campaign_sends").select("id, prospect_id, subject, status, sent_at, opened_at, clicked_at, error_message, email_number").eq("brokerage_id",s).order("sent_at",{ascending:!1,nullsFirst:!1}),y=[];for(const g of p||[]){const b=h.get(g.prospect_id);b&&y.push({id:`v-${g.id}`,kind:"video",prospect_id:g.prospect_id,prospect_name:`${b.first_name||""} ${b.last_name||""}`.trim()||"—",prospect_email:b.email,subject:(v=g.video)!=null&&v.title?`Video: ${g.video.title}`:"Recruiting Video",status:g.cta_clicked_at?"clicked":g.first_viewed_at?"viewed":"sent",sent_at:g.sent_at,opened_at:g.first_viewed_at,clicked_at:g.cta_clicked_at,view_count:g.view_count,share_token:g.share_token})}for(const g of f||[]){if(!g.sent_at)continue;const b=h.get(g.prospect_id);b&&y.push({id:`c-${g.id}`,kind:"campaign",prospect_id:g.prospect_id,prospect_name:`${b.first_name||""} ${b.last_name||""}`.trim()||"—",prospect_email:b.email,subject:g.subject||`Email #${g.email_number}`,status:g.status||"sent",sent_at:g.sent_at,opened_at:g.opened_at,clicked_at:g.clicked_at,error:g.error_message})}return y.sort((g,b)=>new Date(b.sent_at).getTime()-new Date(g.sent_at).getTime()),y}}),o=_.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=_.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:Or,color:"text-primary"},{label:"Video Emails",value:o.videos,icon:Kr,color:"text-blue-500"},{label:"Campaign Emails",value:o.campaigns,icon:ln,color:"text-violet-500"},{label:"Opened / Viewed",value:o.opened,icon:ya,color:"text-amber-500"},{label:"Clicked",value:o.clicked,icon:$h,color:"text-emerald-500"}].map(d=>e.jsx(ve,{children:e.jsxs(Me,{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(ve,{children:[e.jsx(bt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[e.jsx(St,{className:"text-lg",children:"Sent Emails"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Yr,{value:r,onValueChange:d=>a(d),children:e.jsxs(Zr,{className:"h-8",children:[e.jsx(Ht,{value:"all",className:"text-xs h-7",children:"All"}),e.jsx(Ht,{value:"video",className:"text-xs h-7",children:"Video"}),e.jsx(Ht,{value:"campaign",className:"text-xs h-7",children:"Campaign"})]})}),e.jsxs("div",{className:"relative w-56",children:[e.jsx(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search recruit, subject...",value:t,onChange:d=>n(d.target.value),className:"pl-9 h-9"})]})]})]})}),e.jsx(Me,{children:l?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):c.length===0?e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(ln,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{className:"font-medium",children:"No emails sent yet"}),e.jsx("p",{className:"text-sm mt-1",children:"Emails sent from Video Outreach or Drip Campaigns will appear here."})]}):e.jsx("div",{className:"rounded-lg border overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-muted/40 text-xs text-muted-foreground",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left font-medium px-3 py-2",children:"Type"}),e.jsx("th",{className:"text-left font-medium px-3 py-2",children:"Recruit"}),e.jsx("th",{className:"text-left font-medium px-3 py-2",children:"Subject"}),e.jsx("th",{className:"text-left font-medium px-3 py-2",children:"Status"}),e.jsx("th",{className:"text-left font-medium px-3 py-2",children:"Sent"}),e.jsx("th",{className:"text-right font-medium px-3 py-2",children:"Engagement"})]})}),e.jsx("tbody",{children:c.map(d=>e.jsxs("tr",{className:"border-t hover:bg-muted/30 transition-colors",children:[e.jsx("td",{className:"px-3 py-2",children:d.kind==="video"?e.jsxs(Oe,{variant:"outline",className:"gap-1",children:[e.jsx(Kr,{className:"h-3 w-3"}),"Video"]}):e.jsxs(Oe,{variant:"outline",className:"gap-1",children:[e.jsx(ln,{className:"h-3 w-3"}),"Campaign"]})}),e.jsxs("td",{className:"px-3 py-2",children:[e.jsx("div",{className:"font-medium",children:d.prospect_name}),d.prospect_email&&e.jsx("div",{className:"text-xs text-muted-foreground",children:d.prospect_email})]}),e.jsx("td",{className:"px-3 py-2 max-w-xs truncate",children:d.subject}),e.jsxs("td",{className:"px-3 py-2",children:[d.status==="failed"||d.status==="bounced"?e.jsxs(Oe,{variant:"destructive",className:"gap-1",children:[e.jsx(Xo,{className:"h-3 w-3"}),d.status]}):d.clicked_at?e.jsxs(Oe,{className:"bg-emerald-500/15 text-emerald-700 border-emerald-200 gap-1",children:[e.jsx($h,{className:"h-3 w-3"}),"Clicked"]}):d.opened_at?e.jsxs(Oe,{className:"bg-blue-500/15 text-blue-700 border-blue-200 gap-1",children:[e.jsx(ya,{className:"h-3 w-3"}),"Opened"]}):e.jsxs(Oe,{variant:"secondary",className:"gap-1",children:[e.jsx(Or,{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(ya,{className:"h-3 w-3"}),d.view_count]}),d.kind==="video"&&d.share_token&&e.jsx(B,{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(wr,{className:"h-3.5 w-3.5"})})]})})]},d.id))})]})})})]})]})}const C4t={pipeline:[{value:"pipeline-board",label:"Board",icon:sf},{value:"pipeline-table",label:"Table",icon:i$},{value:"pipeline-contacts",label:"Contacts",icon:In},{value:"pipeline-follow-ups",label:"Follow-ups",icon:qf},{value:"pipeline-referrals",label:"Referrals",icon:h$}],outreach:[{value:"outreach-video",label:"Video outreach",icon:Kr},{value:"outreach-templates",label:"Email templates",icon:Hq},{value:"outreach-sent",label:"Sent emails",icon:ln}],campaigns:[{value:"campaigns-manager",label:"Campaigns",icon:ln},{value:"campaigns-assignments",label:"Drip assignments",icon:Or}],assets:[{value:"assets-landing",label:"Landing page",icon:$2},{value:"assets-interest",label:"Interest form",icon:qf}],reporting:[{value:"reporting-metrics",label:"Analytics",icon:bl},{value:"reporting-goals",label:"Goals",icon:ku},{value:"reporting-activity",label:"Recruiter activity",icon:In}],settings:[{value:"settings-email",label:"Email settings",icon:qc},{value:"settings-stages",label:"Pipeline stages",icon:tP}]},Hrs=[{value:"command",label:"Command"},{value:"pipeline",label:"Pipeline"},{value:"outreach",label:"Outreach"},{value:"campaigns",label:"Campaigns"},{value:"assets",label:"Growth assets"},{value:"reporting",label:"Reporting"},{value:"settings",label:"Settings"}],Unr=s=>{var t;return((t=Hrs.find(n=>s===n.value||s.startsWith(`${n.value}-`)))==null?void 0:t.value)??"command"};function qnr(){var P;const{managedBrokerages:s,selectedBrokerageId:t,setSelectedBrokerageId:n}=hs(),r=t||((P=s[0])==null?void 0:P.id)||"",a=kz(r||null),[i,l]=_.useState("command"),[o,c]=_.useState(!1),[d,u]=_.useState(!1),[h,m]=_.useState(null),[p,f]=_.useState(!1),[y,v]=_.useState(""),g=Unr(i),b=s.find(M=>M.id===r),j=_.useMemo(()=>{const M=y.trim().toLowerCase();return M?a.prospects.filter(I=>`${I.first_name} ${I.last_name||""} ${I.current_brokerage||""} ${I.email||""}`.toLowerCase().includes(M)).slice(0,6):[]},[a.prospects,y]),S=M=>l(M),C=M=>{m(M),f(!0),v("")},E=M=>l(M==="command"?"command":C4t[M][0].value);return s.length===0?e.jsx(zs,{title:"Recruiting",description:"Brokerage recruiting command center",children:e.jsxs("div",{className:"py-16 text-center text-muted-foreground",children:[e.jsx(ai,{className:"mx-auto mb-4 h-12 w-12 opacity-50"}),e.jsx("p",{children:"No brokerages assigned to you. Contact an admin for access."})]})}):e.jsx(zs,{title:"Recruiting",description:"Brokerage recruiting command center",children:e.jsxs("div",{className:"recruiting-console -m-4 min-h-[calc(100vh-72px)] bg-background font-['Figtree'] sm:-m-6 lg:-m-8",children:[e.jsxs("header",{className:"bg-secondary px-4 py-4 text-secondary-foreground sm:px-6 lg:px-8",children:[e.jsxs("div",{className:"flex flex-col gap-4 xl:flex-row xl:items-center xl:justify-between",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-4",children:[e.jsx("span",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-md bg-primary text-primary-foreground",children:e.jsx(h$,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h1",{className:"truncate text-xl font-bold",children:"Recruiting Command"}),e.jsxs("p",{className:"truncate text-xs text-secondary-foreground/70",children:[(b==null?void 0:b.name)||"Brokerage"," · Pipeline, outreach and growth"]})]})]}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsxs("div",{className:"relative min-w-0 sm:w-72",children:[e.jsx(Lr,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-secondary-foreground/60"}),e.jsx(xe,{value:y,onChange:M=>v(M.target.value),placeholder:"Search prospects…",className:"border-secondary-foreground/15 bg-primary/40 pl-9 text-secondary-foreground placeholder:text-secondary-foreground/55 focus-visible:ring-recruit-gold"}),y.trim()&&e.jsxs("div",{className:"absolute left-0 right-0 top-[calc(100%+6px)] z-40 overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-lg",children:[j.map(M=>e.jsxs("button",{type:"button",className:"flex w-full items-center justify-between gap-3 border-b px-3 py-2.5 text-left text-sm last:border-0 hover:bg-accent",onClick:()=>C(M),children:[e.jsxs("span",{className:"truncate font-medium",children:[M.first_name," ",M.last_name]}),e.jsx("span",{className:"truncate text-xs text-muted-foreground",children:M.current_brokerage||"Prospect"})]},M.id)),j.length===0&&e.jsx("p",{className:"px-3 py-4 text-sm text-muted-foreground",children:"No matching prospects."})]})]}),e.jsxs(tu,{children:[e.jsx(su,{asChild:!0,children:e.jsxs(B,{className:"bg-recruit-gold text-recruit-navy hover:bg-recruit-gold/90",children:[e.jsx(rn,{className:"mr-1.5 h-4 w-4"}),"New prospect ",e.jsx(tl,{className:"ml-2 h-3.5 w-3.5"})]})}),e.jsxs(Od,{align:"end",children:[e.jsxs(ca,{onSelect:()=>c(!0),children:[e.jsx(rn,{className:"mr-2 h-4 w-4"}),"Add prospect"]}),e.jsxs(ca,{onSelect:()=>u(!0),children:[e.jsx(Oa,{className:"mr-2 h-4 w-4"}),"Import CSV"]})]})]})]})]}),e.jsx("nav",{className:"-mx-4 mt-4 overflow-x-auto px-4 sm:-mx-6 sm:px-6 lg:-mx-8 lg:px-8","aria-label":"Recruiting sections",children:e.jsx("div",{className:"flex min-w-max items-center gap-1",children:Hrs.map(M=>e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>E(M.value),className:At("h-9 rounded-none border-b-2 px-3 text-secondary-foreground/70 hover:bg-secondary-foreground/5 hover:text-secondary-foreground",g===M.value?"border-recruit-gold text-recruit-gold":"border-transparent"),children:M.label},M.value))})})]}),e.jsxs("div",{className:"px-4 py-5 sm:px-6 lg:px-8",children:[s.length>1&&e.jsxs("div",{className:"mb-4 flex items-center gap-3",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Managing:"}),e.jsxs(is,{value:r,onValueChange:n,children:[e.jsxs(rs,{className:"w-[280px] bg-card",children:[e.jsx(ai,{className:"mr-2 h-4 w-4"}),e.jsx(ls,{})]}),e.jsx(as,{children:s.map(M=>e.jsx(He,{value:M.id,children:M.name},M.id))})]})]}),g!=="command"&&e.jsx("div",{className:"mb-5 overflow-x-auto pb-1",children:e.jsx(Yr,{value:i,onValueChange:l,children:e.jsx(Zr,{className:"h-auto min-w-max rounded-md border bg-card p-1",children:C4t[g].map(M=>{const I=M.icon;return e.jsxs(Ht,{value:M.value,className:"gap-1.5",children:[e.jsx(I,{className:"h-3.5 w-3.5"}),M.label]},M.value)})})})}),g==="command"&&r&&e.jsx(znr,{brokerageId:r,onNavigate:S,onOpenProspect:C,onAddProspect:()=>c(!0)}),i==="pipeline-board"&&e.jsx(Ers,{brokerageId:r}),(i==="pipeline-table"||i==="pipeline-contacts")&&e.jsx(KYe,{brokerageId:r}),i==="pipeline-follow-ups"&&e.jsx(Drs,{brokerageId:r}),i==="pipeline-referrals"&&e.jsx(Lrs,{brokerageId:r}),i==="outreach-video"&&e.jsx(Ors,{brokerageId:r}),i==="outreach-templates"&&e.jsx(Mrs,{brokerageId:r}),i==="outreach-sent"&&e.jsx(Bnr,{brokerageId:r}),i==="campaigns-manager"&&e.jsx(qrs,{brokerageId:r}),i==="campaigns-assignments"&&e.jsx($rs,{brokerageId:r}),i==="assets-landing"&&e.jsx(Rrs,{brokerageId:r}),i==="assets-interest"&&e.jsx(Irs,{brokerageId:r}),i==="reporting-metrics"&&e.jsx(Trs,{brokerageId:r}),i==="reporting-goals"&&e.jsx(zrs,{brokerageId:r}),i==="reporting-activity"&&e.jsx(Prs,{brokerageId:r}),i==="settings-email"&&e.jsxs("div",{className:"max-w-3xl rounded-md border bg-card p-5",children:[e.jsxs("div",{className:"mb-5",children:[e.jsx("h2",{className:"font-['Outfit'] text-lg font-semibold",children:"Email settings"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Configure sender identity, merge fields and brokerage location."})]}),e.jsx(Jat,{brokerageId:r})]}),i==="settings-stages"&&e.jsx("div",{className:"max-w-3xl rounded-md border bg-card p-5",children:e.jsx(Vrs,{brokerageId:r})})]}),e.jsx(Yat,{open:o,onOpenChange:c,stages:a.stages,onSubmit:M=>a.addProspect.mutate(M),isSubmitting:a.addProspect.isPending}),e.jsx(Qat,{open:d,onOpenChange:u,brokerageId:r,stages:a.stages}),e.jsx(Xat,{prospect:h,stages:a.stages,brokerageId:r,open:p,onOpenChange:f,onUpdate:M=>{a.updateProspect.mutate(M),m(I=>I?{...I,...M}:null)},onDelete:M=>a.deleteProspect.mutate(M)})]})})}const $nr=[{key:"license_number",label:"License #"},{key:"license_state",label:"License state"},{key:"license_expiration",label:"License expiration",type:"date"},{key:"eo_carrier",label:"E&O carrier"},{key:"eo_policy_number",label:"E&O policy #"},{key:"eo_expiration",label:"E&O expiration",type:"date"},{key:"first_year_licensed",label:"First year licensed",type:"number"},{key:"anniversary_date",label:"Anniversary",type:"date"},{key:"birthday",label:"Birthday",type:"date"},{key:"mobile_phone",label:"Mobile"},{key:"personal_email",label:"Personal email"},{key:"address_line1",label:"Address"},{key:"city",label:"City"},{key:"state",label:"State"},{key:"postal_code",label:"Zip"},{key:"specialization",label:"Specialization"},{key:"prior_firm",label:"Prior firm"},{key:"designations",label:"Designations"},{key:"goal_amount",label:"Production goal",type:"number"},{key:"internal_role",label:"Role"}],Vnr=({brokerageId:s,agentUserId:t,readOnly:n})=>{const{toast:r}=vi(),{data:a}=ATn(s,t),{saveRecord:i}=$Ie(s),[l,o]=_.useState({brokerage_id:s,agent_user_id:t});return _.useEffect(()=>{o({brokerage_id:s,agent_user_id:t,...a||{}})},[a,s,t]),e.jsxs("div",{className:"space-y-5",children:[e.jsx("div",{className:"grid gap-4 sm:grid-cols-2 xl:grid-cols-3",children:$nr.map(c=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:c.label}),e.jsx(xe,{type:c.type||"text",disabled:n,value:l[c.key]??"",onChange:d=>o({...l,[c.key]:c.type==="number"?d.target.value===""?null:Number(d.target.value):d.target.value||null})})]},String(c.key)))}),!n&&e.jsxs(B,{onClick:async()=>{await i.mutateAsync(l),r({title:"Record saved"})},children:[e.jsx(Ho,{className:"mr-2 h-4 w-4"})," Save record"]})]})},Hnr=({brokerageId:s,agentUserId:t})=>{const{data:n=[]}=ETn(s,t),{data:r=[]}=EKt(s,t),{addNote:a,deleteNote:i}=$Ie(s),[l,o]=_.useState("");return e.jsxs("div",{className:"grid gap-6 xl:grid-cols-2",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ec,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("h3",{className:"font-medium",children:"Private notes"}),e.jsx(Oe,{variant:"secondary",children:"Managers only"})]}),e.jsx(Ms,{rows:3,value:l,onChange:c=>o(c.target.value),placeholder:"Add a note about this agent…"}),e.jsx(B,{size:"sm",disabled:!l.trim(),onClick:async()=>{await a.mutateAsync({agentUserId:t,body:l.trim()}),o("")},children:"Add note"}),e.jsxs("div",{className:"space-y-2",children:[n.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No notes yet."}),n.map(c=>e.jsxs("div",{className:"rounded-md border bg-card p-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("p",{className:"whitespace-pre-wrap text-sm",children:c.body}),e.jsx(B,{size:"icon",variant:"ghost",className:"text-destructive",onClick:()=>i.mutate({id:c.id,agentUserId:t}),"aria-label":"Delete note",children:e.jsx(Sn,{className:"h-4 w-4"})})]}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:new Date(c.created_at).toLocaleString("en-US",{timeZone:"America/New_York"})})]},c.id))]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(hm,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("h3",{className:"font-medium",children:"Activity"})]}),e.jsxs("div",{className:"space-y-2",children:[r.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nothing yet."}),r.map(c=>e.jsxs("div",{className:"relative border-l-2 border-primary/40 bg-muted/30 px-4 py-2.5",children:[e.jsx("p",{className:"text-sm",children:c.description}),e.jsx("p",{className:"text-xs text-muted-foreground",children:new Date(c.created_at).toLocaleString("en-US",{timeZone:"America/New_York"})})]},c.id))]})]})]})},A4t=s=>s.split(/\s+/).filter(Boolean).slice(0,2).map(t=>t[0]).join("").toUpperCase(),Grs=s=>s?s.split(/[-/T]/).slice(0,3).join("/"):null,Gnr=s=>s.assignment?s.total>0&&s.done===s.total?{label:"Completed",className:"bg-emerald-500/10 text-emerald-700"}:s.overdue>0?{label:"Overdue",className:"bg-destructive/10 text-destructive"}:s.needsReview>0?{label:"Waiting on review",className:"bg-amber-500/10 text-amber-700"}:{label:"In progress",className:"bg-primary/10 text-primary"}:{label:"Not started",className:"bg-muted/70 text-muted-foreground"},Ode=({label:s,value:t,icon:n,active:r,tone:a,onClick:i})=>e.jsxs("button",{type:"button",onClick:i,"aria-pressed":r,className:At("flex min-h-[92px] w-full items-center justify-between rounded-md border bg-card p-4 text-left shadow-xs transition-colors hover:border-primary/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",r&&"border-primary bg-primary/5 ring-1 ring-primary/20"),children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase text-muted-foreground",children:s}),e.jsx("p",{className:"mt-1 font-['Outfit'] text-3xl font-bold text-foreground",children:t})]}),e.jsx("span",{className:At("flex h-10 w-10 items-center justify-center rounded-full",a),children:e.jsx(n,{className:"h-5 w-5"})})]}),Wnr=({brokerageId:s,agentUserId:t})=>{const{data:n=[]}=EKt(s,t);return e.jsxs("aside",{className:"rounded-md border bg-card p-4",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[e.jsx("h3",{className:"font-['Outfit'] text-sm font-semibold",children:"Recent activity"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Latest updates"})]}),e.jsxs("div",{className:"space-y-4",children:[n.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No activity yet."}),n.slice(0,6).map((r,a)=>e.jsxs("div",{className:"relative flex gap-3",children:[e.jsx("span",{className:At("mt-1.5 h-2.5 w-2.5 shrink-0 rounded-full ring-4 ring-background",a===0?"bg-primary":"bg-muted-foreground/40")}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm leading-snug",children:r.description}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:Grs(r.created_at)})]})]},r.id))]})]})},Knr=({brokerageId:s})=>{var O,V;const{toast:t}=vi(),{data:n=[],isLoading:r}=CKt(s),{data:a=[]}=SKt(s),{assignTemplate:i,removeAssignment:l}=$Ie(s),[o,c]=_.useState(""),[d,u]=_.useState("all"),[h,m]=_.useState(null),[p,f]=_.useState(!1),[y,v]=_.useState(null),[g,b]=_.useState(""),j=_.useMemo(()=>{const G=o.trim().toLowerCase();return n.filter($=>{if(G&&!$.name.toLowerCase().includes(G)&&!$.email.toLowerCase().includes(G))return!1;const H=!!$.assignment&&$.total>0&&$.done===$.total;return d==="not_started"?!$.assignment:d==="in_progress"?!!$.assignment&&!H:d==="finished"?H:d==="review"?$.needsReview>0:d==="overdue"?$.overdue>0:!0})},[n,o,d]);_.useEffect(()=>{var G;h&&j.some($=>$.agentId===h)||m(((G=j[0])==null?void 0:G.agentId)??null)},[j,h]);const S=n.find(G=>G.agentId===h)||null,{data:C}=AKt((O=S==null?void 0:S.assignment)==null?void 0:O.id),E=(C==null?void 0:C.steps)||[],P=E.filter(CA).length,M=E.length?Math.round(P/E.length*100):0,I=_.useMemo(()=>{const G=n.filter($=>$.assignment);return{inProgress:G.filter($=>!($.total>0&&$.done===$.total)).length,finished:G.filter($=>$.total>0&&$.done===$.total).length,needsReview:n.reduce(($,H)=>$+H.needsReview,0),overdue:n.reduce(($,H)=>$+H.overdue,0)}},[n]),D=G=>{m(G),f(!0)};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4",children:[e.jsx(Ode,{label:"In progress",value:I.inProgress,icon:x0,active:d==="in_progress",tone:"bg-primary/10 text-primary",onClick:()=>u(d==="in_progress"?"all":"in_progress")}),e.jsx(Ode,{label:"Finished",value:I.finished,icon:Er,active:d==="finished",tone:"bg-emerald-500/10 text-emerald-700",onClick:()=>u(d==="finished"?"all":"finished")}),e.jsx(Ode,{label:"Waiting on review",value:I.needsReview,icon:Tq,active:d==="review",tone:"bg-amber-500/10 text-amber-700",onClick:()=>u(d==="review"?"all":"review")}),e.jsx(Ode,{label:"Overdue steps",value:I.overdue,icon:xl,active:d==="overdue",tone:"bg-destructive/10 text-destructive",onClick:()=>u(d==="overdue"?"all":"overdue")})]}),e.jsxs("div",{className:"grid min-h-[620px] overflow-hidden rounded-md border bg-card shadow-sm lg:grid-cols-[310px_minmax(0,1fr)] xl:grid-cols-[340px_minmax(0,1fr)]",children:[e.jsxs("section",{className:At("border-r bg-muted/10",p&&"hidden lg:block"),children:[e.jsxs("header",{className:"border-b p-4",children:[e.jsx("h2",{className:"font-['Outfit'] text-base font-semibold",children:"Agents"}),e.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:"Track each agent’s onboarding"}),e.jsxs("div",{className:"relative mb-2",children:[e.jsx(Lr,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(xe,{className:"h-9 bg-background pl-9",placeholder:"Search agents",value:o,onChange:G=>c(G.target.value)})]}),e.jsxs(is,{value:d,onValueChange:G=>u(G),children:[e.jsx(rs,{className:"h-9 bg-background",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All agents"}),e.jsx(He,{value:"not_started",children:"Not started"}),e.jsx(He,{value:"in_progress",children:"In progress"}),e.jsx(He,{value:"finished",children:"Finished"}),e.jsx(He,{value:"review",children:"Waiting on review"}),e.jsx(He,{value:"overdue",children:"Overdue"})]})]})]}),e.jsxs("div",{className:"max-h-[650px] overflow-y-auto p-2",children:[r&&e.jsx("p",{className:"p-3 text-sm text-muted-foreground",children:"Loading…"}),!r&&j.length===0&&e.jsx("p",{className:"p-3 text-sm text-muted-foreground",children:"No agents match."}),j.map(G=>{const $=G.total?Math.round(G.done/G.total*100):0,H=Gnr(G);return e.jsxs("button",{type:"button",onClick:()=>D(G.agentId),className:At("mb-1 flex w-full items-center gap-3 rounded-md border border-transparent p-2.5 text-left transition-colors hover:bg-muted/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",G.agentId===h&&"border-primary/30 bg-primary/5"),children:[e.jsxs(ja,{className:"h-10 w-10 border-2 border-background shadow-xs",children:[e.jsx(pi,{src:G.avatarUrl||void 0,alt:G.name,className:"object-cover"}),e.jsx(Na,{className:"bg-primary/10 text-xs font-semibold text-primary",children:A4t(G.name)})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm font-semibold",children:G.name}),e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:G.assignment?`${$}% complete`:"No flow assigned"}),e.jsx(Oe,{className:At("mt-1 border-0 px-1.5 py-0 text-[10px] font-medium",H.className),children:H.label})]}),G.needsReview>0&&e.jsx("span",{className:"flex h-6 min-w-6 items-center justify-center rounded-full bg-amber-500/10 px-1.5 text-[10px] font-bold text-amber-700",children:G.needsReview})]},G.agentId)})]})]}),e.jsx("section",{className:At("min-w-0",!p&&"hidden lg:block"),children:S?e.jsxs(e.Fragment,{children:[e.jsxs("header",{className:"border-b bg-card p-4 md:p-5",children:[e.jsxs(B,{variant:"ghost",size:"sm",className:"mb-3 -ml-2 lg:hidden",onClick:()=>f(!1),children:[e.jsx(ka,{className:"mr-2 h-4 w-4"}),"All agents"]}),e.jsxs("div",{className:"flex flex-col gap-4 xl:flex-row xl:items-start xl:justify-between",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsxs(ja,{className:"h-14 w-14 border shadow-xs",children:[e.jsx(pi,{src:S.avatarUrl||void 0,alt:S.name,className:"object-cover"}),e.jsx(Na,{className:"bg-primary text-base font-semibold text-primary-foreground",children:A4t(S.name)})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{className:"truncate font-['Outfit'] text-xl font-bold",children:S.name}),e.jsx("p",{className:"truncate text-sm text-muted-foreground",children:S.email}),e.jsxs("p",{className:"mt-0.5 text-xs text-muted-foreground",children:[((V=S.assignment)==null?void 0:V.template_name)||"No flow assigned",S.joinedAt?` · Joined ${Grs(S.joinedAt)}`:""]})]})]}),S.assignment?e.jsxs(B,{variant:"outline",className:"text-destructive",onClick:async()=>{await l.mutateAsync(S.assignment),t({title:"Onboarding removed"})},children:[e.jsx(Sn,{className:"mr-2 h-4 w-4"}),"Remove checklist"]}):e.jsxs(B,{onClick:()=>{var G,$;v(S),b(((G=a.find(H=>H.is_default))==null?void 0:G.id)||(($=a[0])==null?void 0:$.id)||"")},disabled:a.length===0,children:[e.jsx(Jd,{className:"mr-2 h-4 w-4"}),"Start onboarding"]})]}),S.assignment&&e.jsxs("div",{className:"mt-5",children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between text-sm",children:[e.jsx("span",{className:"font-medium",children:"Onboarding progress"}),e.jsxs("span",{className:"font-['Outfit'] text-lg font-bold text-primary",children:[M,"%"]})]}),e.jsx(Fi,{value:M,className:"h-2.5 bg-muted"}),e.jsxs("p",{className:"mt-1.5 text-right text-xs text-muted-foreground",children:[P," of ",E.length," steps complete"]})]}),a.length===0&&!S.assignment&&e.jsxs("p",{className:"mt-3 flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(xl,{className:"h-4 w-4"}),"Build an onboarding flow first on the Flows tab."]})]}),e.jsx("div",{className:"p-4 md:p-5",children:e.jsxs(Yr,{defaultValue:"checklist",className:"space-y-4",children:[e.jsx("div",{className:"overflow-x-auto pb-1",children:e.jsxs(Zr,{className:"grid h-auto min-w-[500px] grid-cols-4 rounded-md border bg-muted/40 p-1",children:[e.jsx(Ht,{value:"checklist",children:"Checklist"}),e.jsx(Ht,{value:"record",children:"Record"}),e.jsx(Ht,{value:"notes",children:"Notes & activity"}),e.jsx(Ht,{value:"documents",children:"Documents"})]})}),e.jsx(Gt,{value:"checklist",children:S.assignment?e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,1.6fr)_minmax(240px,.8fr)]",children:[e.jsx(rWe,{brokerageId:s,agentUserId:S.agentId,steps:E,documents:(C==null?void 0:C.documents)||[],mode:"manager"}),e.jsx(Wnr,{brokerageId:s,agentUserId:S.agentId})]}):e.jsx("p",{className:"py-12 text-center text-sm text-muted-foreground",children:"No checklist assigned yet."})}),e.jsx(Gt,{value:"record",children:e.jsx(Vnr,{brokerageId:s,agentUserId:S.agentId})}),e.jsx(Gt,{value:"notes",children:e.jsx(Hnr,{brokerageId:s,agentUserId:S.agentId})}),e.jsx(Gt,{value:"documents",children:S.assignment?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mb-4 flex items-center gap-2",children:[e.jsx(KO,{className:"h-4 w-4 text-primary"}),e.jsx("h3",{className:"font-['Outfit'] font-semibold",children:"Onboarding documents"})]}),e.jsx(rWe,{brokerageId:s,agentUserId:S.agentId,steps:E,documents:(C==null?void 0:C.documents)||[],mode:"manager",displayMode:"documents"})]}):e.jsx("p",{className:"py-12 text-center text-sm text-muted-foreground",children:"No documents yet."})})]})})]}):e.jsxs("div",{className:"flex min-h-[620px] flex-col items-center justify-center text-center",children:[e.jsx(cN,{className:"mb-3 h-10 w-10 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Select an agent to see their onboarding."})]})})]}),e.jsx(Ls,{open:!!y,onOpenChange:G=>!G&&v(null),children:e.jsxs(Ps,{children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Start onboarding"}),e.jsxs(_r,{children:["Pick the flow for ",y==null?void 0:y.name,". Later flow edits will not change this checklist."]})]}),e.jsxs(is,{value:g,onValueChange:b,children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Choose a flow"})}),e.jsx(as,{children:a.map(G=>e.jsx(He,{value:G.id,children:G.name},G.id))})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>v(null),children:"Cancel"}),e.jsxs(B,{disabled:!g||!y,onClick:async()=>{if(y)try{await i.mutateAsync({agentUserId:y.agentId,templateId:g}),t({title:"Onboarding started"}),v(null)}catch(G){t({title:"Could not start",description:G.message,variant:"destructive"})}},children:[e.jsx(i6,{className:"mr-2 h-4 w-4"}),"Start"]})]})]})})]})},Ynr=s=>s==="document"?Fr:s==="form"?lb:Ww,Znr=({brokerageId:s})=>{var G,$;const{toast:t}=vi(),{data:n=[],isLoading:r}=SKt(s),[a,i]=_.useState(null),l=a??((G=n[0])==null?void 0:G.id)??null,o=n.find(H=>H.id===l)||null,{data:c=[]}=STn(l),{createTemplate:d,updateTemplate:u,deleteTemplate:h,upsertStep:m,deleteStep:p,reorderSteps:f}=TTn(s),{data:y=[]}=at({queryKey:["brokerage-form-templates",s],queryFn:async()=>{const{data:H,error:Y}=await q.from("form_templates").select("id, name").eq("brokerage_id",s).eq("is_archived",!1).order("name");if(Y)throw Y;return H||[]}}),[v,g]=_.useState(!1),[b,j]=_.useState(""),[S,C]=_.useState(""),[E,P]=_.useState(!1),[M,I]=_.useState(null),D=()=>I({title:"",description:"",step_type:"document",assignee:"agent",due_days:null}),O=async()=>{var H;!l||!((H=M==null?void 0:M.title)!=null&&H.trim())||(await m.mutateAsync({...M.id?{id:M.id}:{},template_id:l,title:M.title.trim(),description:M.description||null,step_type:M.step_type||"document",assignee:M.assignee||"agent",form_template_id:M.step_type==="form"&&M.form_template_id||null,due_days:M.due_days??null,sort_order:M.sort_order??c.length}),P(!1),I(null),t({title:"Step saved"}))},V=async(H,Y)=>{const Z=[...c],ne=H+Y;ne<0||ne>=Z.length||([Z[H],Z[ne]]=[Z[ne],Z[H]],await f.mutateAsync({steps:Z,templateId:l}))};return e.jsxs("div",{className:"grid min-h-[620px] overflow-hidden rounded-md border bg-card shadow-sm lg:grid-cols-[300px_minmax(0,1fr)]",children:[e.jsxs(ve,{className:"rounded-none border-0 border-r shadow-none",children:[e.jsxs(bt,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(St,{className:"text-base",children:"Onboarding flows"}),e.jsx(B,{size:"sm",variant:"outline",onClick:()=>g(!0),children:e.jsx(rn,{className:"h-4 w-4"})})]}),e.jsx(kn,{children:"Reusable checklists for new agents"})]}),e.jsxs(Me,{className:"space-y-2",children:[r&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading…"}),!r&&n.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No flows yet. Create your first one."}),n.map(H=>e.jsxs("button",{onClick:()=>i(H.id),className:`w-full rounded-md border p-3 text-left transition-colors ${H.id===l?"border-primary bg-primary/5":"hover:bg-muted/50"}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"font-medium text-sm",children:H.name}),H.is_default&&e.jsxs(Oe,{variant:"secondary",className:"gap-1",children:[e.jsx(Da,{className:"h-3 w-3"})," Default"]})]}),H.description&&e.jsx("p",{className:"mt-1 line-clamp-2 text-xs text-muted-foreground",children:H.description})]},H.id))]})]}),e.jsx(ve,{className:"rounded-none border-0 shadow-none",children:o?e.jsxs(e.Fragment,{children:[e.jsx(bt,{children:e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx(St,{children:o.name}),e.jsx(kn,{children:o.description||"No description"})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>u.mutate({id:o.id,is_default:!o.is_default}),children:[e.jsx(Da,{className:"mr-2 h-4 w-4"}),o.is_default?"Unset default":"Set default"]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>{D(),P(!0)},children:[e.jsx(rn,{className:"mr-2 h-4 w-4"})," Add step"]}),e.jsx(B,{size:"sm",variant:"ghost",className:"text-destructive",onClick:async()=>{await h.mutateAsync(o.id),i(null)},children:e.jsx(Sn,{className:"h-4 w-4"})})]})]})}),e.jsxs(Me,{className:"space-y-2",children:[c.length===0&&e.jsx("p",{className:"py-8 text-center text-sm text-muted-foreground",children:"No steps yet — add documents, forms and tasks agents need to complete."}),c.map((H,Y)=>{const Z=Ynr(H.step_type);return e.jsxs("div",{className:"flex items-start gap-3 rounded-md border p-3 transition-colors hover:bg-muted/40",children:[e.jsx("div",{className:"mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-md bg-primary/10 text-primary",children:e.jsx(Z,{className:"h-4 w-4"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"font-medium text-sm",children:H.title}),e.jsx(Oe,{variant:"outline",className:"capitalize",children:H.step_type}),e.jsx(Oe,{variant:"secondary",className:"capitalize",children:H.assignee}),H.due_days!=null&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["due in ",H.due_days,"d"]})]}),H.description&&e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:H.description})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(B,{size:"icon",variant:"ghost",onClick:()=>V(Y,-1),"aria-label":"Move up",children:e.jsx(sp,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",onClick:()=>V(Y,1),"aria-label":"Move down",children:e.jsx(zf,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",onClick:()=>{I(H),P(!0)},"aria-label":"Edit step",children:e.jsx(Ya,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"text-destructive",onClick:()=>p.mutate({id:H.id,templateId:o.id}),"aria-label":"Delete step",children:e.jsx(Sn,{className:"h-4 w-4"})})]})]},H.id)})]})]}):e.jsxs(Me,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(qf,{className:"mb-3 h-10 w-10 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Select or create an onboarding flow."})]})}),e.jsx(Ls,{open:v,onOpenChange:g,children:e.jsxs(Ps,{children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"New onboarding flow"}),e.jsx(_r,{children:"Name it for the kind of agent it fits."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Name"}),e.jsx(xe,{value:b,onChange:H=>j(H.target.value),placeholder:"New Agent Onboarding"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Description"}),e.jsx(Ms,{value:S,onChange:H=>C(H.target.value),rows:3})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>g(!1),children:"Cancel"}),e.jsx(B,{disabled:!b.trim(),onClick:async()=>{const H=await d.mutateAsync({name:b.trim(),description:S});i(H.id),j(""),C(""),g(!1)},children:"Create"})]})]})}),e.jsx(Ls,{open:E,onOpenChange:P,children:e.jsxs(Ps,{children:[e.jsx(Os,{children:e.jsx(Ds,{children:M!=null&&M.id?"Edit step":"Add step"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Title"}),e.jsx(xe,{value:(M==null?void 0:M.title)||"",onChange:H=>I({...M,title:H.target.value}),placeholder:"Independent contractor agreement"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Instructions"}),e.jsx(Ms,{rows:2,value:(M==null?void 0:M.description)||"",onChange:H=>I({...M,description:H.target.value})})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Type"}),e.jsxs(is,{value:(M==null?void 0:M.step_type)||"document",onValueChange:H=>I({...M,step_type:H}),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"document",children:"Document upload"}),e.jsx(He,{value:"form",children:"Form from library"}),e.jsx(He,{value:"task",children:"Task / check off"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Who completes it"}),e.jsxs(is,{value:(M==null?void 0:M.assignee)||"agent",onValueChange:H=>I({...M,assignee:H}),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"agent",children:"Agent"}),e.jsx(He,{value:"manager",children:"Manager"})]})]})]})]}),(M==null?void 0:M.step_type)==="form"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Form"}),e.jsxs(is,{value:(M==null?void 0:M.form_template_id)||"",onValueChange:H=>I({...M,form_template_id:H}),children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Choose a form"})}),e.jsx(as,{children:y.map(H=>e.jsx(He,{value:H.id,children:H.name},H.id))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Due (days after start)"}),e.jsx(xe,{type:"number",min:0,value:(M==null?void 0:M.due_days)??"",onChange:H=>I({...M,due_days:H.target.value===""?null:Number(H.target.value)}),placeholder:"Optional"})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>P(!1),children:"Cancel"}),e.jsx(B,{onClick:O,disabled:!(($=M==null?void 0:M.title)!=null&&$.trim()),children:"Save step"})]})]})})]})},Xnr=()=>{const{user:s,isBrokerageManager:t,isAdmin:n,brokerageId:r,managedBrokerages:a,selectedBrokerageId:i,setSelectedBrokerageId:l}=hs(),o=Fn(),[c,d]=_.useState(!1),u=i||(a.length>0?a[0].id:r);return _.useEffect(()=>{if(s){if(!t&&!n){o("/dashboard");return}!i&&a.length>0&&l(a[0].id),d(!0)}},[s,t,n,o,a,i,l]),c?e.jsx(zs,{title:"Agent Onboarding",description:"Build your onboarding flow, collect documents and keep notes",children:e.jsxs("div",{className:"onboarding-console space-y-5 font-['Figtree']",children:[a.length>1&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Managing:"}),e.jsxs(is,{value:i||"",onValueChange:l,children:[e.jsxs(rs,{className:"w-[280px]",children:[e.jsx(ai,{className:"mr-2 h-4 w-4"}),e.jsx(ls,{placeholder:"Select brokerage"})]}),e.jsx(as,{children:a.map(h=>e.jsx(He,{value:h.id,children:h.name},h.id))})]})]}),u?e.jsxs(Yr,{defaultValue:"board",className:"space-y-4",children:[e.jsxs(Zr,{className:"grid h-10 w-full max-w-sm grid-cols-2 rounded-md border bg-muted/40 p-1",children:[e.jsx(Ht,{value:"board",children:"Agents"}),e.jsx(Ht,{value:"flows",children:"Flows"})]}),e.jsx(Gt,{value:"board",children:e.jsx(Knr,{brokerageId:u})}),e.jsx(Gt,{value:"flows",children:e.jsx(Znr,{brokerageId:u})})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(ai,{className:"mb-4 h-12 w-12 text-muted-foreground"}),e.jsx("h2",{className:"mb-1 text-xl font-semibold",children:"No Brokerage Assigned"}),e.jsx("p",{className:"text-muted-foreground",children:"You don't have any brokerages to manage."})]})]})}):null},Qnr={checklist_applied:"Checklist applied",document_uploaded:"Document uploaded",item_approved:"Item approved",item_rejected:"Changes requested",item_added:"Item added",item_updated:"Item updated"};function Jnr({dealId:s}){const{data:t=[]}=kEs(s),[n,r]=_.useState({});return _.useEffect(()=>{const a=Array.from(new Set(t.map(i=>i.actor_user_id).filter(Boolean)));a.length!==0&&(async()=>{const{data:i}=await q.from("profiles").select("id, name, email").in("id",a),l={};(i||[]).forEach(o=>{l[o.id]=o.name||o.email||"Someone"}),r(l)})()},[t]),t.length===0?e.jsx("p",{className:"py-6 text-center text-sm text-muted-foreground",children:"No compliance activity yet."}):e.jsx("div",{className:"space-y-3",children:t.map(a=>e.jsxs("div",{className:"flex gap-3 text-sm",children:[e.jsx("div",{className:"mt-1.5 h-2 w-2 flex-shrink-0 rounded-full bg-primary/60"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium",children:Qnr[a.event_type]||a.event_type}),a.detail&&e.jsx("p",{className:"text-xs text-muted-foreground",children:a.detail}),e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:[a.actor_user_id?n[a.actor_user_id]||"Someone":"System"," ·"," ",new Date(a.created_at).toLocaleString()]})]})]},a.id))})}function err({brokerageId:s,deal:t,open:n,onOpenChange:r}){const{data:a=[]}=cRt(s),i=CEs(),[l,o]=_.useState("");if(!t)return null;const c=F$e(t),d=async()=>{if(l)try{await i.mutateAsync({dealId:t.deal_id,brokerageId:s,templateId:l,deal:{contract_date:t.contract_date,target_close_date:t.target_close_date}}),se.success("Checklist added to this file")}catch(u){se.error(u.message||"Could not apply checklist")}};return e.jsx(qg,{open:n,onOpenChange:r,children:e.jsxs(hg,{className:"w-full overflow-y-auto sm:max-w-xl",children:[e.jsxs(P0,{className:"text-left",children:[e.jsx(L0,{className:"pr-8",children:t.property_address||t.deal_name}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 pt-1",children:[e.jsx(Oe,{variant:"secondary",children:t.agent_name||"Agent"}),t.stage_name&&e.jsx(Oe,{variant:"outline",children:t.stage_name}),e.jsx(Oe,{variant:c==="compliant"?"default":"outline",children:lRt[c]})]})]}),e.jsxs("div",{className:"mt-5 grid grid-cols-3 gap-3 rounded-lg border p-3 text-center text-xs",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Contract"}),e.jsx("p",{className:"font-medium",children:t.contract_date||"—"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Target close"}),e.jsx("p",{className:"font-medium",children:t.target_close_date||"—"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Approved"}),e.jsxs("p",{className:"font-medium",children:[t.approved_items,"/",t.total_items]})]})]}),e.jsxs(Yr,{defaultValue:"checklist",className:"mt-5",children:[e.jsxs(Zr,{className:"grid w-full grid-cols-3",children:[e.jsx(Ht,{value:"checklist",children:"Checklist"}),e.jsx(Ht,{value:"messages",children:"Messages"}),e.jsx(Ht,{value:"audit",children:"Audit trail"})]}),e.jsxs(Gt,{value:"checklist",className:"mt-4 space-y-4",children:[t.total_items===0&&a.length>0&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(is,{value:l,onValueChange:o,children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Apply a checklist"})}),e.jsx(as,{children:a.map(u=>e.jsx(He,{value:u.id,children:u.name},u.id))})]}),e.jsx(B,{onClick:d,disabled:!l||i.isPending,children:"Apply"})]}),e.jsx(sss,{dealId:t.deal_id,canReview:!0})]}),e.jsx(Gt,{value:"messages",className:"mt-4",children:e.jsx(nss,{dealId:t.deal_id,brokerageId:s,role:"staff",counterpartName:t.agent_name})}),e.jsx(Gt,{value:"audit",className:"mt-4",children:e.jsx(Jnr,{dealId:t.deal_id})})]})]})})}function trr({metrics:s}){const t=[{label:"Active transactions",value:String(s.activeDeals),caption:`${s.closedThisYear} closed this year`,icon:ai,tint:"bg-blue-500/10 text-blue-600"},{label:"Pipeline volume",value:Xm(s.pipelineVolume),caption:`${Xm(s.closedVolumeThisYear)} closed YTD`,icon:Nl,tint:"bg-indigo-500/10 text-indigo-600"},{label:"Projected commission",value:Xm(s.pipelineGci),caption:"Gross on active files",icon:yd,tint:"bg-emerald-500/10 text-emerald-600"},{label:"Est. brokerage share",value:Xm(s.brokerageShare),caption:`${Xm(s.closedCompanyDollarYtd)} company dollar YTD`,icon:QQ,tint:"bg-teal-500/10 text-teal-600"},{label:"Closing soon",value:String(s.closingNext30),caption:`${s.closingThisMonth} this month`,icon:Qd,tint:"bg-amber-500/10 text-amber-600"}],n=[{label:"Files awaiting review",value:s.needsReview,icon:KO,tint:"text-blue-600"},{label:"Changes requested",value:s.changesRequested,icon:GQ,tint:"text-destructive"},{label:"Overdue items",value:s.overdueItems,icon:xl,tint:"text-amber-600"}];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-5",children:t.map(r=>e.jsx(ve,{className:"border-border/60",children:e.jsx(Me,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("span",{className:At("flex h-9 w-9 shrink-0 items-center justify-center rounded-lg",r.tint),children:e.jsx(r.icon,{className:"h-4.5 w-4.5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:r.label}),e.jsx("p",{className:"text-2xl font-bold tabular-nums tracking-tight",children:r.value}),e.jsx("p",{className:"mt-0.5 truncate text-[11px] text-muted-foreground",children:r.caption})]})]})})},r.label))}),e.jsx(ve,{className:"border-border/60",children:e.jsx(Me,{className:"flex flex-wrap items-center gap-x-8 gap-y-3 p-4",children:n.map(r=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(r.icon,{className:At("h-4 w-4",r.tint)}),e.jsx("span",{className:"text-sm font-semibold tabular-nums",children:r.value}),e.jsx("span",{className:"text-xs text-muted-foreground",children:r.label})]},r.label))})})]})}function srr({outlook:s}){const t=s.some(n=>n.deals>0);return e.jsxs(ve,{className:"border-border/60",children:[e.jsxs(bt,{className:"pb-2",children:[e.jsx(St,{className:"text-base",children:"Closing outlook"}),e.jsx(kn,{children:"Expected closings over the next 6 months"})]}),e.jsx(Me,{className:"pt-2",children:t?e.jsx("div",{className:"h-[220px] w-full",children:e.jsx(jb,{width:"100%",height:"100%",children:e.jsxs(BW,{data:s,margin:{top:8,right:8,left:0,bottom:0},children:[e.jsx(kE,{strokeDasharray:"3 3",vertical:!1,stroke:"hsl(var(--border))"}),e.jsx(Mv,{dataKey:"label",tickLine:!1,axisLine:!1,fontSize:11,stroke:"hsl(var(--muted-foreground))"}),e.jsx(Pv,{tickLine:!1,axisLine:!1,fontSize:11,stroke:"hsl(var(--muted-foreground))",tickFormatter:n=>Xm(Number(n)),width:54}),e.jsx(Mf,{cursor:{fill:"hsl(var(--muted) / 0.4)"},contentStyle:{background:"hsl(var(--popover))",border:"1px solid hsl(var(--border))",borderRadius:8,fontSize:12,color:"hsl(var(--popover-foreground))"},formatter:(n,r,a)=>{var i,l;return[`${Xm(Number(n))} · ${((i=a==null?void 0:a.payload)==null?void 0:i.deals)??0} deal${((l=a==null?void 0:a.payload)==null?void 0:l.deals)===1?"":"s"}`,"Volume"]}}),e.jsx(H_,{dataKey:"volume",radius:[6,6,0,0],children:s.map(n=>e.jsx(tz,{fill:n.closed?"hsl(var(--primary))":"hsl(var(--primary) / 0.45)"},n.key))})]})})}):e.jsx("p",{className:"py-10 text-center text-sm text-muted-foreground",children:"No closing dates set on the current transactions yet."})})]})}function nrr({agents:s,totalVolume:t,selectedAgentId:n,onSelectAgent:r}){return s.length===0?null:e.jsxs(ve,{className:"border-border/60",children:[e.jsxs(bt,{className:"pb-2",children:[e.jsx(St,{className:"text-base",children:"Agent production"}),e.jsx(kn,{children:"Company-visible transactions by agent — tap a row to filter the board"})]}),e.jsx(Me,{className:"space-y-1 pt-2",children:s.slice(0,12).map(a=>{const i=t>0?Math.round(a.volume/t*100):0,l=n===a.userId;return e.jsxs("button",{onClick:()=>r(l?"all":a.userId),className:`flex w-full items-center gap-3 rounded-lg px-2 py-2 text-left transition-colors hover:bg-muted/60 ${l?"bg-muted":""}`,children:[e.jsxs(ja,{className:"h-8 w-8 shrink-0",children:[e.jsx(pi,{src:a.avatarUrl||void 0,alt:a.name}),e.jsx(Na,{className:"text-[11px]",children:a.name.slice(0,2).toUpperCase()})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:a.name}),e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:[a.activeDeals," active · ",a.closedDeals," closed",a.overdue>0?` · ${a.overdue} overdue`:""]}),e.jsx("div",{className:"mt-1.5 h-1.5 w-full overflow-hidden rounded-full bg-muted",children:e.jsx("div",{className:"h-full rounded-full bg-primary",style:{width:`${i}%`}})})]}),e.jsxs("div",{className:"shrink-0 text-right",children:[e.jsx("p",{className:"text-sm font-semibold tabular-nums",children:Xm(a.volume)}),e.jsxs("p",{className:"text-[11px] text-muted-foreground tabular-nums",children:[Xm(a.gci)," GCI"]})]})]},a.userId)})})]})}const E4t={ownerUserId:"",dealName:"",dealType:"buyer",stageId:"",propertyAddress:"",city:"",state:"",zipCode:"",contractDate:"",targetCloseDate:"",actualCloseDate:"",price:"",commissionPercentage:"",notes:""};function rrr({brokerageId:s,open:t,onOpenChange:n}){const[r,a]=_.useState(E4t),[i,l]=_.useState(""),{data:o=[],isLoading:c}=LEs(t?s:null),{data:d=[],isLoading:u}=IEs(r.ownerUserId||null),h=DEs();_.useEffect(()=>{t||(a(E4t),l(""))},[t]),_.useEffect(()=>{d.length>0&&!d.some(j=>j.id===r.stageId)&&a(j=>({...j,stageId:d[0].id}))},[d,r.stageId]);const m=_.useMemo(()=>{const j=i.trim().toLowerCase();return j?o.filter(S=>`${S.name??""} ${S.email??""}`.toLowerCase().includes(j)):o},[o,i]),p=(j,S)=>a(C=>({...C,[j]:S})),f=r.price?Number(r.price):null,y=r.commissionPercentage?Number(r.commissionPercentage):null,v=f!=null&&y!=null&&Number.isFinite(f)&&Number.isFinite(y)?Math.round(f*(y/100)*100)/100:null,g=!!r.ownerUserId&&!!r.stageId&&r.dealName.trim().length>0&&!h.isPending,b=async()=>{try{await h.mutateAsync({brokerageId:s,ownerUserId:r.ownerUserId,dealName:r.dealName,dealType:r.dealType,stageId:r.stageId||null,propertyAddress:r.propertyAddress,city:r.city,state:r.state,zipCode:r.zipCode,contractDate:r.contractDate,targetCloseDate:r.targetCloseDate,actualCloseDate:r.actualCloseDate,price:f!=null&&Number.isFinite(f)?f:null,commissionPercentage:y!=null&&Number.isFinite(y)?y:null,notes:r.notes});const j=o.find(S=>S.id===r.ownerUserId);se.success(`Deal added to ${(j==null?void 0:j.name)||"the agent"}'s pipeline.`),n(!1)}catch(j){se.error((j==null?void 0:j.message)||"Could not add the deal.")}};return e.jsx(Ls,{open:t,onOpenChange:n,children:e.jsxs(Ps,{className:"max-h-[90vh] max-w-2xl overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Add a deal for an agent"}),e.jsx(_r,{children:"The deal is created in the agent's own pipeline, so it shows up here and in their account."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Agent"}),e.jsx(xe,{placeholder:"Search agents by name or email",value:i,onChange:j=>l(j.target.value)}),e.jsxs(is,{value:r.ownerUserId,onValueChange:j=>p("ownerUserId",j),children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:c?"Loading agents…":"Select an agent"})}),e.jsx(as,{children:m.map(j=>e.jsx(He,{value:j.id,children:j.name||j.email||"Agent"},j.id))})]})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2 sm:col-span-2",children:[e.jsx(J,{children:"Deal name"}),e.jsx(xe,{placeholder:"Client name or property address",value:r.dealName,onChange:j=>p("dealName",j.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Type"}),e.jsxs(is,{value:r.dealType,onValueChange:j=>p("dealType",j),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"buyer",children:"Buyer"}),e.jsx(He,{value:"seller",children:"Seller"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Stage"}),e.jsxs(is,{value:r.stageId,onValueChange:j=>p("stageId",j),disabled:!r.ownerUserId||u,children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:r.ownerUserId?u?"Loading stages…":"Select a stage":"Pick an agent first"})}),e.jsx(as,{children:d.map(j=>e.jsx(He,{value:j.id,children:j.name},j.id))})]})]}),e.jsxs("div",{className:"space-y-2 sm:col-span-2",children:[e.jsx(J,{children:"Property address"}),e.jsx(xe,{value:r.propertyAddress,onChange:j=>p("propertyAddress",j.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"City"}),e.jsx(xe,{value:r.city,onChange:j=>p("city",j.target.value)})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"State"}),e.jsx(xe,{value:r.state,onChange:j=>p("state",j.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"ZIP"}),e.jsx(xe,{value:r.zipCode,onChange:j=>p("zipCode",j.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Contract date"}),e.jsx(xe,{type:"date",value:r.contractDate,onChange:j=>p("contractDate",j.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Target close date"}),e.jsx(xe,{type:"date",value:r.targetCloseDate,onChange:j=>p("targetCloseDate",j.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Actual close date"}),e.jsx(xe,{type:"date",value:r.actualCloseDate,onChange:j=>p("actualCloseDate",j.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Price"}),e.jsx(xe,{type:"number",inputMode:"decimal",value:r.price,onChange:j=>p("price",j.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Commission %"}),e.jsx(xe,{type:"number",inputMode:"decimal",step:"0.01",value:r.commissionPercentage,onChange:j=>p("commissionPercentage",j.target.value)}),v!=null&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Expected commission: $",v.toLocaleString()]})]}),e.jsxs("div",{className:"space-y-2 sm:col-span-2",children:[e.jsx(J,{children:"Notes"}),e.jsx(Ms,{rows:3,value:r.notes,onChange:j=>p("notes",j.target.value)})]})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsxs(B,{onClick:b,disabled:!g,children:[h.isPending&&e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}),"Add deal"]})]})]})})}const arr={not_started:"bg-muted text-muted-foreground",in_review:"bg-amber-500/15 text-amber-600",changes_requested:"bg-destructive/15 text-destructive",compliant:"bg-emerald-500/15 text-emerald-600"};function irr({brokerageId:s,canAddDeals:t=!1}){const{data:n=[],isLoading:r}=XQe(s),[a,i]=_.useState(""),[l,o]=_.useState("all"),[c,d]=_.useState("all"),[u,h]=_.useState("all"),[m,p]=_.useState("stage"),[f,y]=_.useState(null),[v,g]=_.useState(!1),b=_.useMemo(()=>cer(n),[n]),j=_.useMemo(()=>{const P=new Map;return n.forEach(M=>P.set(M.owner_user_id,M.agent_name||"Agent")),Array.from(P,([M,I])=>({id:M,name:I}))},[n]),S=_.useMemo(()=>{const P=new Set;return n.forEach(M=>M.stage_name&&P.add(M.stage_name)),Array.from(P).sort((M,I)=>M.localeCompare(I))},[n]),C=_.useMemo(()=>{const P=a.trim().toLowerCase();return n.filter(M=>{if(c!=="all"&&M.owner_user_id!==c||u!=="all"&&(M.stage_name||"No stage")!==u)return!1;const I=F$e(M);return(l==="overdue"?M.overdue_items===0:l!=="all"&&l!==I)?!1:P?[M.deal_name,M.property_address,M.city,M.agent_name].filter(Boolean).some(D=>D.toLowerCase().includes(P)):!0})},[n,a,l,c,u]),E=_.useMemo(()=>{const P=[...C],M=I=>I.actual_close_date||I.target_close_date||"";return P.sort((I,D)=>{switch(m){case"agent":return(I.agent_name||"").localeCompare(D.agent_name||"");case"close":return(M(I)||"9999").localeCompare(M(D)||"9999");case"overdue":return D.overdue_items-I.overdue_items;case"progress":{const O=V=>V.total_items?V.approved_items/V.total_items:0;return O(I)-O(D)}case"stage":default:{const O=(I.stage_name||"zzz").localeCompare(D.stage_name||"zzz");return O!==0?O:(I.agent_name||"").localeCompare(D.agent_name||"")}}}),P},[C,m]);return r?e.jsx("div",{className:"flex justify-center py-16",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-4",children:[t&&e.jsx("div",{className:"flex justify-end",children:e.jsxs(B,{onClick:()=>g(!0),children:[e.jsx(rn,{className:"mr-2 h-4 w-4"}),"Add deal"]})}),t&&e.jsx(rrr,{brokerageId:s,open:v,onOpenChange:g}),n.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(trr,{metrics:b}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-2",children:[e.jsx(srr,{outlook:b.outlook}),e.jsx(nrr,{agents:b.agents,totalVolume:b.totalVolume,selectedAgentId:c,onSelectAgent:d})]})]}),e.jsxs("div",{className:"flex flex-col gap-3 lg:flex-row",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Lr,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(xe,{className:"pl-9",placeholder:"Search address, agent or file name",value:a,onChange:P=>i(P.target.value)})]}),e.jsxs(is,{value:l,onValueChange:o,children:[e.jsx(rs,{className:"lg:w-[180px]",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All statuses"}),e.jsx(He,{value:"not_started",children:"Not started"}),e.jsx(He,{value:"in_review",children:"In review"}),e.jsx(He,{value:"changes_requested",children:"Changes requested"}),e.jsx(He,{value:"compliant",children:"Compliant"}),e.jsx(He,{value:"overdue",children:"Has overdue items"})]})]}),e.jsxs(is,{value:u,onValueChange:h,children:[e.jsx(rs,{className:"lg:w-[180px]",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All stages"}),S.map(P=>e.jsx(He,{value:P,children:P},P))]})]}),e.jsxs(is,{value:m,onValueChange:p,children:[e.jsx(rs,{className:"lg:w-[180px]",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"stage",children:"Sort: Deal stage"}),e.jsx(He,{value:"agent",children:"Sort: Agent"}),e.jsx(He,{value:"close",children:"Sort: Closing date"}),e.jsx(He,{value:"overdue",children:"Sort: Most overdue"}),e.jsx(He,{value:"progress",children:"Sort: Least complete"})]})]}),e.jsxs(is,{value:c,onValueChange:d,children:[e.jsx(rs,{className:"lg:w-[180px]",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All agents"}),j.map(P=>e.jsx(He,{value:P.id,children:P.name},P.id))]})]})]}),E.length===0?e.jsx(ve,{children:e.jsxs(Me,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(wy,{className:"mb-3 h-10 w-10 text-muted-foreground"}),e.jsx("p",{className:"font-medium",children:"No transactions to review"}),e.jsx("p",{className:"mt-1 max-w-md text-sm text-muted-foreground",children:"Deals appear here once an agent reaches a company-visible phase — everything earlier stays private to the agent."})]})}):e.jsx("div",{className:"space-y-2",children:E.map(P=>{const M=F$e(P),I=P.total_items?Math.round(P.approved_items/P.total_items*100):0;return e.jsxs("button",{onClick:()=>y(P),className:"w-full rounded-lg border p-4 text-left transition-colors hover:bg-muted/50",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate font-medium",children:P.property_address||P.deal_name}),e.jsxs("p",{className:"mt-0.5 text-xs text-muted-foreground",children:[P.agent_name,P.stage_name?` · ${P.stage_name}`:"",P.actual_close_date?` · Closed ${P.actual_close_date}`:P.target_close_date?` · Closes ${P.target_close_date}`:""]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[P.overdue_items>0&&e.jsxs(Oe,{variant:"destructive",className:"gap-1 text-[10px]",children:[e.jsx(xl,{className:"h-3 w-3"})," ",P.overdue_items," overdue"]}),e.jsx("span",{className:`rounded-full px-2 py-0.5 text-[11px] font-medium ${arr[M]}`,children:lRt[M]})]})]}),e.jsxs("div",{className:"mt-3 flex items-center gap-3",children:[e.jsx(Fi,{value:I,className:"h-1.5 flex-1"}),e.jsxs("span",{className:"w-24 text-right text-[11px] text-muted-foreground",children:[P.approved_items," of ",P.total_items," approved"]})]})]},P.deal_id)})}),e.jsx(err,{brokerageId:s,deal:f,open:!!f,onOpenChange:P=>!P&&y(null)})]})}const T4t=[{value:"any",label:"Any deal type"},{value:"listing",label:"Listing"},{value:"buyer",label:"Buyer"},{value:"lease",label:"Lease"},{value:"referral",label:"Referral"}];function orr({brokerageId:s}){var b,j;const{data:t=[],isLoading:n}=cRt(s),r=_Es(),a=wEs(),[i,l]=_.useState(null),o=i??((b=t[0])==null?void 0:b.id)??null,c=t.find(S=>S.id===o)||null,{data:d=[]}=bEs(o),u=jEs(),h=NEs(),[m,p]=_.useState(!1),[f,y]=_.useState(null),v=async()=>{try{const S=await r.mutateAsync({brokerage_id:s,name:"New checklist",deal_type:null,is_active:!0});l(S)}catch(S){se.error(S.message||"Could not create checklist")}},g=async()=>{var S;if(!(!o||!((S=f==null?void 0:f.title)!=null&&S.trim())))try{await u.mutateAsync({...f,template_id:o,title:f.title.trim(),sort_order:f.sort_order??d.length}),p(!1),y(null)}catch(C){se.error(C.message||"Could not save item")}};return n?e.jsx("div",{className:"flex justify-center py-10",children:e.jsx(Ct,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"grid gap-6 lg:grid-cols-[280px_1fr]",children:[e.jsxs(ve,{children:[e.jsxs(bt,{className:"flex-row items-center justify-between space-y-0",children:[e.jsx(St,{className:"text-base",children:"Checklists"}),e.jsx(B,{size:"sm",variant:"outline",onClick:v,children:e.jsx(rn,{className:"h-4 w-4"})})]}),e.jsx(Me,{className:"space-y-2",children:t.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Create a checklist per deal type — Listing, Buyer, Lease."}):t.map(S=>{var C;return e.jsxs("button",{onClick:()=>l(S.id),className:`w-full rounded-lg border p-3 text-left transition-colors ${S.id===o?"border-primary bg-primary/5":"hover:bg-muted"}`,children:[e.jsx("p",{className:"truncate text-sm font-medium",children:S.name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(C=T4t.find(E=>E.value===(S.deal_type||"any")))==null?void 0:C.label})]},S.id)})})]}),c?e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsx(St,{className:"text-lg",children:"Checklist details"}),e.jsx(kn,{children:"Applied automatically when a deal becomes company-visible."})]}),e.jsxs(Me,{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Name"}),e.jsx(xe,{defaultValue:c.name,onBlur:S=>r.mutate({id:c.id,brokerage_id:s,name:S.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Applies to"}),e.jsxs(is,{value:c.deal_type||"any",onValueChange:S=>r.mutate({id:c.id,brokerage_id:s,deal_type:S==="any"?null:S}),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsx(as,{children:T4t.map(S=>e.jsx(He,{value:S.value,children:S.label},S.value))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(J,{children:"Required items"}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>{y({phase:"contract",requires_document:!0,required_for_closing:!0}),p(!0)},children:[e.jsx(rn,{className:"mr-1 h-4 w-4"})," Add item"]})]}),d.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No items yet."}):e.jsx("div",{className:"space-y-2",children:d.map(S=>{var C;return e.jsxs("div",{className:"flex items-start justify-between gap-3 rounded-lg border p-3",children:[e.jsxs("button",{className:"min-w-0 flex-1 text-left",onClick:()=>{y(S),p(!0)},children:[e.jsx("p",{className:"truncate text-sm font-medium",children:S.title}),e.jsxs("div",{className:"mt-1 flex flex-wrap gap-1.5",children:[e.jsx(Oe,{variant:"secondary",className:"text-[10px]",children:((C=uAe.find(E=>E.value===S.phase))==null?void 0:C.label)||S.phase}),S.requires_document&&e.jsx(Oe,{variant:"outline",className:"text-[10px]",children:"Document"}),S.required_for_closing&&e.jsx(Oe,{variant:"outline",className:"text-[10px]",children:"Required to close"}),S.due_anchor&&e.jsxs(Oe,{variant:"outline",className:"text-[10px]",children:[S.due_offset_days??0,"d after"," ",S.due_anchor==="contract_date"?"contract":"target close"]})]})]}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>h.mutate({id:S.id,templateId:c.id}),children:e.jsx(Sn,{className:"h-4 w-4 text-destructive"})})]},S.id)})})]}),e.jsxs(B,{variant:"outline",className:"text-destructive",onClick:async()=>{await Xi(`Delete "${c.name}"?`)&&(a.mutate({id:c.id,brokerageId:s}),l(null))},children:[e.jsx(Sn,{className:"mr-2 h-4 w-4"})," Delete checklist"]})]})]}):e.jsx(ve,{children:e.jsxs(Me,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(Fr,{className:"mb-3 h-10 w-10 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Select or create a checklist to add required documents."})]})}),e.jsx(Ls,{open:m,onOpenChange:p,children:e.jsxs(Ps,{children:[e.jsx(Os,{children:e.jsx(Ds,{children:f!=null&&f.id?"Edit item":"Add item"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Title"}),e.jsx(xe,{value:(f==null?void 0:f.title)||"",onChange:S=>y(C=>({...C,title:S.target.value})),placeholder:"Purchase agreement (fully executed)"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Instructions for the agent"}),e.jsx(Ms,{rows:2,value:(f==null?void 0:f.description)||"",onChange:S=>y(C=>({...C,description:S.target.value}))})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Phase"}),e.jsxs(is,{value:(f==null?void 0:f.phase)||"contract",onValueChange:S=>y(C=>({...C,phase:S})),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsx(as,{children:uAe.map(S=>e.jsx(He,{value:S.value,children:S.label},S.value))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Due"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{type:"number",className:"w-20",value:(f==null?void 0:f.due_offset_days)??"",onChange:S=>y(C=>({...C,due_offset_days:S.target.value===""?null:Number(S.target.value)})),placeholder:"days"}),e.jsxs(is,{value:(f==null?void 0:f.due_anchor)||"none",onValueChange:S=>y(C=>({...C,due_anchor:S==="none"?null:S})),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"none",children:"No due date"}),e.jsx(He,{value:"contract_date",children:"after contract date"}),e.jsx(He,{value:"target_close_date",children:"after target close"})]})]})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsx(J,{className:"text-sm",children:"Requires an uploaded document"}),e.jsx(fn,{checked:(f==null?void 0:f.requires_document)??!0,onCheckedChange:S=>y(C=>({...C,requires_document:S}))})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsx(J,{className:"text-sm",children:"Required before closing"}),e.jsx(fn,{checked:(f==null?void 0:f.required_for_closing)??!0,onCheckedChange:S=>y(C=>({...C,required_for_closing:S}))})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>p(!1),children:"Cancel"}),e.jsxs(B,{onClick:g,disabled:!((j=f==null?void 0:f.title)!=null&&j.trim())||u.isPending,children:[u.isPending&&e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}),"Save"]})]})]})})]})}function lrr({brokerageId:s}){const{data:t,isLoading:n}=yEs(s),r=vEs(),{data:a=[]}=fEs(s),i=xEs(),l=gEs(),[o,c]=_.useState(["contract","closing","closed"]),[d,u]=_.useState(!0),[h,m]=_.useState(!0),[p,f]=_.useState(""),[y,v]=_.useState(!1);_.useEffect(()=>{t&&(c(t.visible_phases||[]),u(t.include_contract_dated_deals),m(t.is_enabled))},[t]);const g=S=>c(C=>C.includes(S)?C.filter(E=>E!==S):[...C,S]),b=async()=>{try{await r.mutateAsync({brokerage_id:s,visible_phases:o,include_contract_dated_deals:d,is_enabled:h}),se.success("Compliance settings saved")}catch(S){se.error(S.message||"Could not save settings")}},j=async()=>{const S=p.trim().toLowerCase();if(S){v(!0);try{const{data:C,error:E}=await q.from("profiles").select("id, email").ilike("email",S).maybeSingle();if(E)throw E;if(!C){se.error("No LevelUp account found with that email");return}await i.mutateAsync({brokerageId:s,userId:C.id}),f(""),se.success("Transaction admin added")}catch(C){se.error(C.message||"Could not add transaction admin")}finally{v(!1)}}};return n?e.jsx("div",{className:"flex justify-center py-10",children:e.jsx(Ct,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"grid gap-6 lg:grid-cols-2",children:[e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsx(St,{className:"text-lg",children:"What the company can see"}),e.jsx(kn,{children:"Agent leads, consultations and early conversations stay private. Deals become visible to compliance once they reach one of the phases below."})]}),e.jsxs(Me,{className:"space-y-5",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(J,{className:"text-sm font-medium",children:"Compliance tracking on"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Turn off to hide all agent deals from the company view."})]}),e.jsx(fn,{checked:h,onCheckedChange:m})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{className:"text-sm font-medium",children:"Company-visible phases"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:uAe.map(S=>e.jsx("button",{type:"button",onClick:()=>g(S.value),className:`rounded-full border px-3 py-1.5 text-xs font-medium transition-colors ${o.includes(S.value)?"border-primary bg-primary/10 text-primary":"border-border text-muted-foreground hover:bg-muted"}`,children:S.label},S.value))})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(J,{className:"text-sm font-medium",children:"Include any deal with a contract date"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:'Recommended — catches "agreement signed" deals even when an agent uses custom stage names.'})]}),e.jsx(fn,{checked:d,onCheckedChange:u})]}),e.jsxs(B,{onClick:b,disabled:r.isPending,children:[r.isPending&&e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}),"Save settings"]})]})]}),e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsxs(St,{className:"flex items-center gap-2 text-lg",children:[e.jsx(Dm,{className:"h-4 w-4"})," Transaction admins"]}),e.jsx(kn,{children:"Give staff compliance-only access — deals, documents, checklists and notes. No recruiting or billing."})]}),e.jsxs(Me,{className:"space-y-4",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{placeholder:"admin@yourbrokerage.com",value:p,onChange:S=>f(S.target.value),onKeyDown:S=>S.key==="Enter"&&j()}),e.jsx(B,{onClick:j,disabled:y||!p.trim(),children:y?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Pl,{className:"h-4 w-4"})})]}),a.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No transaction admins yet."}):e.jsx("div",{className:"space-y-2",children:a.map(S=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:S.name||S.email}),e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:S.email})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Oe,{variant:"secondary",className:"text-[10px]",children:"Compliance"}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>l.mutate({id:S.id,brokerageId:s}),children:e.jsx(Sn,{className:"h-4 w-4 text-destructive"})})]})]},S.id))})]})]})]})}const crr=()=>{const{user:s,isBrokerageManager:t,isAdmin:n,brokerageId:r,managedBrokerages:a,selectedBrokerageId:i,setSelectedBrokerageId:l}=hs(),o=Fn(),{data:c=[],isLoading:d}=ZQe(),[u,h]=_.useState(!1),m=c.length>0,p=t||n,f=_.useMemo(()=>{var y;return i||(a.length>0?a[0].id:null)||((y=c[0])==null?void 0:y.brokerage_id)||r},[i,a,c,r]);return _.useEffect(()=>{if(!(!s||d)){if(!p&&!m){o("/dashboard");return}!i&&a.length>0&&l(a[0].id),h(!0)}},[s,d,p,m,o,a,i,l]),u?e.jsx(zs,{title:"Transactions & Compliance",description:"Review agent files, required documents and closing compliance",children:e.jsxs("div",{className:"space-y-6",children:[a.length>1&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Managing:"}),e.jsxs(is,{value:i||"",onValueChange:l,children:[e.jsxs(rs,{className:"w-[280px]",children:[e.jsx(ai,{className:"mr-2 h-4 w-4"}),e.jsx(ls,{placeholder:"Select brokerage"})]}),e.jsx(as,{children:a.map(y=>e.jsx(He,{value:y.id,children:y.name},y.id))})]})]}),f?e.jsxs(Yr,{defaultValue:"board",className:"space-y-4",children:[e.jsxs(Zr,{className:`grid w-full ${p?"max-w-lg grid-cols-3":"max-w-xs grid-cols-1"}`,children:[e.jsx(Ht,{value:"board",children:"Transactions"}),p&&e.jsx(Ht,{value:"checklists",children:"Checklists"}),p&&e.jsx(Ht,{value:"settings",children:"Settings"})]}),e.jsx(Gt,{value:"board",children:e.jsx(irr,{brokerageId:f,canAddDeals:p||m})}),p&&e.jsx(Gt,{value:"checklists",children:e.jsx(orr,{brokerageId:f})}),p&&e.jsx(Gt,{value:"settings",children:e.jsx(lrr,{brokerageId:f})})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(ai,{className:"mb-4 h-12 w-12 text-muted-foreground"}),e.jsx("h2",{className:"mb-1 text-xl font-semibold",children:"No Brokerage Assigned"}),e.jsx("p",{className:"text-muted-foreground",children:"You don't have any brokerages to manage."})]})]})}):null},Bse=q,TBe={draft:"Draft",approved:"Approved",paid:"Paid",void:"Void"},ib=s=>{const t=Number(s);return Number.isFinite(t)?t:0};function OG(s){const t=ib(s.gross_commission),n=ib(s.referral_amount)>0?ib(s.referral_amount):t*ib(s.referral_fee_pct)/100,r=Math.max(0,t-n),a=r*(100-ib(s.agent_split_pct))/100,i=r*ib(s.franchise_fee_pct)/100,l=ib(s.transaction_fee),o=(s.line_items||[]).reduce((u,h)=>u+ib(h.amount),0),c=a+i+l,d=r-c-o;return{gross:t,referral:n,adjustedGross:r,brokerageSplit:a,franchiseFee:i,transactionFee:l,otherCharges:o,companyDollar:c,agentNet:d}}function drr(s,t){const n=ib(s.brokerage_split_pct),r=(t==null?void 0:t.agent_split_pct)!=null?ib(t.agent_split_pct):n?100-n:70;return{deal_id:s.deal_id,agent_user_id:s.owner_user_id,status:"draft",property_address:s.property_address||s.deal_name,escrow_company:null,escrow_number:null,closing_date:s.actual_close_date||s.target_close_date,sale_price:RG(s),gross_commission:FG(s),agent_split_pct:r,franchise_fee_pct:s.franchise_fee_pct!=null?ib(s.franchise_fee_pct):ib(t==null?void 0:t.franchise_fee_pct),transaction_fee:s.transaction_fee!=null?ib(s.transaction_fee):ib(t==null?void 0:t.transaction_fee),referral_fee_pct:ib(t==null?void 0:t.referral_fee_pct),referral_amount:0,referral_payee:null,line_items:[],notes:null}}function Wrs(s){return at({queryKey:["disbursements",s],enabled:!!s,queryFn:async()=>{const t=[];for(let r=0;;r+=1e3){const{data:a,error:i}=await Bse.from("brokerage_disbursements").select("*").eq("brokerage_id",s).order("closing_date",{ascending:!1,nullsFirst:!1}).range(r,r+1e3-1);if(i)throw i;if(t.push(...a||[]),!a||a.length<1e3)break}return t.map(r=>({...r,line_items:r.line_items||[]}))}})}function urr(s){const t=Bt(),{user:n}=hs();return mt({mutationFn:async r=>{const a=OG(r),i={brokerage_id:s,deal_id:r.deal_id,agent_user_id:r.agent_user_id,status:r.status,property_address:r.property_address,escrow_company:r.escrow_company,escrow_number:r.escrow_number,closing_date:r.closing_date,sale_price:r.sale_price||0,gross_commission:r.gross_commission||0,agent_split_pct:r.agent_split_pct||0,franchise_fee_pct:r.franchise_fee_pct||0,transaction_fee:r.transaction_fee||0,referral_fee_pct:r.referral_fee_pct||0,referral_amount:r.referral_amount||0,referral_payee:r.referral_payee,line_items:r.line_items||[],notes:r.notes,company_dollar:a.companyDollar,agent_net:a.agentNet};if(r.id){const{error:l}=await Bse.from("brokerage_disbursements").update(i).eq("id",r.id);if(l)throw l}else{i.created_by=(n==null?void 0:n.id)??null;const{error:l}=await Bse.from("brokerage_disbursements").insert(i);if(l)throw l}},onSuccess:()=>{t.invalidateQueries({queryKey:["disbursements",s]}),se.success("Disbursement saved")},onError:r=>se.error(r.message||"Could not save the disbursement")})}function hrr(s){const t=Bt(),{user:n}=hs();return mt({mutationFn:async({id:r,status:a})=>{const i={status:a};a==="approved"&&(i.approved_at=new Date().toISOString(),i.approved_by=(n==null?void 0:n.id)??null),a==="paid"&&(i.paid_at=new Date().toISOString());const{error:l}=await Bse.from("brokerage_disbursements").update(i).eq("id",r);if(l)throw l},onSuccess:()=>t.invalidateQueries({queryKey:["disbursements",s]}),onError:r=>se.error(r.message||"Could not update the status")})}function mrr(s){const t=Bt();return mt({mutationFn:async n=>{const{error:r}=await Bse.from("brokerage_disbursements").delete().eq("id",n);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["disbursements",s]}),se.success("Disbursement removed")},onError:n=>se.error(n.message||"Could not remove the disbursement")})}function Krs(s){return at({queryKey:["brokerage-agent-records",s],enabled:!!s,queryFn:async()=>{const t=[];for(let r=0;;r+=1e3){const{data:a,error:i}=await q.from("brokerage_agent_records").select("*").eq("brokerage_id",s).range(r,r+1e3-1);if(i)throw i;if(t.push(...a||[]),!a||a.length<1e3)break}return t}})}const j6e=q;function prr(s){return at({queryKey:["ops-follow-ups",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await j6e.from("recruit_prospects").select("id, first_name, last_name").eq("brokerage_id",s).limit(1e3);if(n)throw n;const r=t||[];if(!r.length)return[];const a=new Map(r.map(o=>[o.id,[o.first_name,o.last_name].filter(Boolean).join(" ")])),{data:i,error:l}=await j6e.from("recruit_follow_ups").select("id, title, due_date, prospect_id, completed_at").in("prospect_id",r.map(o=>o.id)).is("completed_at",null).order("due_date",{ascending:!0}).limit(500);if(l)throw l;return(i||[]).map(o=>({id:o.id,title:o.title,due_date:o.due_date,prospectName:a.get(o.prospect_id)||null}))}})}function frr(s){return at({queryKey:["ops-help-requests",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await j6e.from("brokerage_help_requests").select("id, title, request_type, event_start_at, requester_user_id").eq("brokerage_id",s).eq("status","open").order("event_start_at",{ascending:!0}).limit(200);if(n)throw n;const r=t||[],a=Array.from(new Set(r.map(l=>l.requester_user_id).filter(Boolean))),i=new Map;if(a.length){const{data:l}=await j6e.from("profiles").select("id, name").in("id",a);(l||[]).forEach(o=>i.set(o.id,o.name))}return r.map(l=>({id:l.id,title:l.title,request_type:l.request_type,event_start_at:l.event_start_at,requesterName:i.get(l.requester_user_id)??null}))}})}const gC=q,Yrs=[{value:"general",label:"General"},{value:"compliance",label:"Compliance"},{value:"disbursements",label:"Disbursements"},{value:"renewals",label:"Renewals"},{value:"onboarding",label:"Onboarding"},{value:"recruiting",label:"Recruiting"},{value:"help_board",label:"Help Board"},{value:"marketing",label:"Marketing"},{value:"listings",label:"Listings"}],N6e=Object.fromEntries(Yrs.map(s=>[s.value,s.label])),YYe={todo:"To do",in_progress:"In progress",done:"Done"},xrr={low:"Low",medium:"Medium",high:"High",urgent:"Urgent"};function grr(s){return at({queryKey:["ops-tasks",s],enabled:!!s,queryFn:async()=>{const t=[];for(let r=0;;r+=1e3){const{data:a,error:i}=await gC.from("brokerage_operations_tasks").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1}).range(r,r+1e3-1);if(i)throw i;if(t.push(...a||[]),!a||a.length<1e3)break}return t}})}function yrr(s){const t=Bt(),{user:n}=hs();return mt({mutationFn:async r=>{var o;const a={brokerage_id:s,assignee_user_id:r.assignee_user_id||null,category:r.category||"general",title:r.title.trim(),description:((o=r.description)==null?void 0:o.trim())||null,status:r.status||"todo",priority:r.priority||"medium",due_date:r.due_date||null,source_type:r.source_type||"manual",source_id:r.source_id||null,source_url:r.source_url||null};if(a.status==="done"&&(a.completed_at=new Date().toISOString()),r.id){const{error:c}=await gC.from("brokerage_operations_tasks").update(a).eq("id",r.id);if(c)throw c;return r.id}a.created_by=(n==null?void 0:n.id)??null;const{data:i,error:l}=await gC.from("brokerage_operations_tasks").insert(a).select("id").single();if(l)throw l;return i.id},onSuccess:()=>{t.invalidateQueries({queryKey:["ops-tasks",s]}),t.invalidateQueries({queryKey:["my-ops-tasks"]}),se.success("Task saved")},onError:r=>se.error(r.message||"Could not save task")})}function vrr(s){const t=Bt();return mt({mutationFn:async({id:n,status:r})=>{const{error:a}=await gC.from("brokerage_operations_tasks").update({status:r,completed_at:r==="done"?new Date().toISOString():null}).eq("id",n);if(a)throw a},onSuccess:()=>{t.invalidateQueries({queryKey:["ops-tasks",s]}),t.invalidateQueries({queryKey:["my-ops-tasks"]})},onError:n=>se.error(n.message||"Could not update task")})}function brr(s){const t=Bt();return mt({mutationFn:async n=>{const{error:r}=await gC.from("brokerage_operations_tasks").delete().eq("id",n);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["ops-tasks",s]}),t.invalidateQueries({queryKey:["my-ops-tasks"]}),se.success("Task removed")},onError:n=>se.error(n.message||"Could not remove task")})}function _rr(s){const t=Bt(),{user:n}=hs();return mt({mutationFn:async r=>{const{error:a}=await gC.from("brokerage_operations_tasks").insert({brokerage_id:s,created_by:(n==null?void 0:n.id)??null,title:r.title,category:r.category,status:"done",source_type:r.sourceType,source_id:r.sourceId,dismissed_at:new Date().toISOString(),dismissed_by:(n==null?void 0:n.id)??null,completed_at:new Date().toISOString()});if(a)throw a},onSuccess:()=>{t.invalidateQueries({queryKey:["ops-tasks",s]}),se.success("Dismissed")},onError:r=>se.error(r.message||"Could not dismiss")})}function wrr(s){return at({queryKey:["ops-task-comments",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await gC.from("brokerage_operations_task_comments").select("*").eq("task_id",s).order("created_at",{ascending:!0});if(n)throw n;return t||[]}})}function jrr(){const s=Bt(),{user:t}=hs();return mt({mutationFn:async({taskId:n,body:r})=>{const{error:a}=await gC.from("brokerage_operations_task_comments").insert({task_id:n,body:r.trim(),author_user_id:t==null?void 0:t.id});if(a)throw a},onSuccess:(n,r)=>s.invalidateQueries({queryKey:["ops-task-comments",r.taskId]}),onError:n=>se.error(n.message||"Could not add note")})}function Nrr(s){const{user:t}=hs();return at({queryKey:["ops-digest-prefs",s,t==null?void 0:t.id],enabled:!!s&&!!t,queryFn:async()=>{const{data:n,error:r}=await gC.from("brokerage_operations_digest_prefs").select("*").eq("brokerage_id",s).eq("user_id",t.id).maybeSingle();if(r)throw r;return n||null}})}function krr(s){const t=Bt(),{user:n}=hs();return mt({mutationFn:async r=>{const{error:a}=await gC.from("brokerage_operations_digest_prefs").upsert({user_id:n.id,brokerage_id:s,email_enabled:r.email_enabled??!1,push_enabled:r.push_enabled??!1,send_day:r.send_day??1},{onConflict:"user_id,brokerage_id"});if(a)throw a},onSuccess:()=>{t.invalidateQueries({queryKey:["ops-digest-prefs",s]}),se.success("Notification settings saved")},onError:r=>se.error(r.message||"Could not save settings")})}const Srr={license:"License renewal",eo:"E&O insurance",anniversary:"Work anniversary",birthday:"Birthday"},Zrs=864e5,Xrs=()=>{const s=new Date;return{y:s.getFullYear(),m:s.getMonth()+1,d:s.getDate()}},xq=(s,t,n)=>Date.UTC(s,t-1,n),tit=s=>{const t=WS(s);return t?new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric",timeZone:"UTC"}).format(new Date(Date.UTC(t.y,t.m-1,t.d))):s},k6e=s=>String(s).padStart(2,"0");function M4t(s){const t=WS(s||"");if(!t)return null;const n=Xrs(),r=Math.round((xq(t.y,t.m,t.d)-xq(n.y,n.m,n.d))/Zrs);return{dueDate:`${t.y}-${k6e(t.m)}-${k6e(t.d)}`,daysUntil:r,expired:r<0}}function P4t(s){const t=WS(s||"");if(!t)return null;const n=Xrs();let r=n.y;xq(r,t.m,t.d)[i.agentId,i])),a=[];return s.forEach(i=>{const l=r.get(i.agent_user_id),o={agentId:i.agent_user_id,agentName:(l==null?void 0:l.name)||"Agent",avatarUrl:(l==null?void 0:l.avatarUrl)??null},c=M4t(i.license_expiration);c&&a.push({...o,kind:"license",sourceDate:i.license_expiration,detail:[i.license_state,i.license_number].filter(Boolean).join(" · ")||null,...c});const d=M4t(i.eo_expiration);d&&a.push({...o,kind:"eo",sourceDate:i.eo_expiration,detail:[i.eo_carrier,i.eo_policy_number].filter(Boolean).join(" · ")||null,...d});const u=P4t(i.anniversary_date);u&&a.push({...o,kind:"anniversary",sourceDate:i.anniversary_date,detail:u.years?`${u.years} year${u.years===1?"":"s"} with the brokerage`:null,...u});const h=P4t(i.birthday);h&&a.push({...o,kind:"birthday",sourceDate:i.birthday,detail:null,dueDate:h.dueDate,daysUntil:h.daysUntil,expired:!1})}),a.filter(i=>i.expired||i.daysUntil<=n).sort((i,l)=>i.daysUntil-l.daysUntil||i.agentName.localeCompare(l.agentName))}function Crr(s,t,n){const r=new Map(n.map(i=>[i.userId,i])),a=new Map(t.map(i=>[i.agentId,i]));return s.filter(i=>Number(i.goal_amount)>0).map(i=>{const l=a.get(i.agent_user_id),o=r.get(i.agent_user_id),c=Number(i.goal_amount)||0,d=(o==null?void 0:o.volume)||0;return{agentId:i.agent_user_id,name:(l==null?void 0:l.name)||"Agent",avatarUrl:(l==null?void 0:l.avatarUrl)??null,goal:c,volume:d,gci:(o==null?void 0:o.gci)||0,closedDeals:(o==null?void 0:o.closedDeals)||0,pct:c>0?Math.min(999,d/c*100):0}}).sort((i,l)=>l.pct-i.pct)}const Arr=864e5;function FZ(s){const t=WS(s||"");if(!t)return null;const n=new Date,r=Date.UTC(n.getFullYear(),n.getMonth(),n.getDate());return Math.round((Date.UTC(t.y,t.m-1,t.d)-r)/Arr)}function Err(s){const t=new Set(s.tasks.filter(i=>i.source_id&&(i.dismissed_at||i.status==="done"||i.source_type!=="manual")).map(i=>`${i.source_type}:${i.source_id}`)),n=[],r=i=>{t.has(`${i.sourceType}:${i.sourceId}`)||n.push(i)};s.complianceDeals.forEach(i=>{i.submitted_items>0&&r({key:`compliance-review-${i.deal_id}`,sourceType:"compliance",sourceId:`review:${i.deal_id}`,category:"compliance",title:`${i.submitted_items} document${i.submitted_items===1?"":"s"} awaiting review`,context:i.deal_name,agentName:i.agent_name,avatarUrl:i.agent_avatar_url,dueDate:i.target_close_date,daysUntil:FZ(i.target_close_date),overdue:i.overdue_items>0,priority:i.overdue_items>0?"urgent":"high",url:"/brokerage/transactions",actionLabel:"Review"}),i.rejected_items>0&&r({key:`compliance-rejected-${i.deal_id}`,sourceType:"compliance",sourceId:`rejected:${i.deal_id}`,category:"compliance",title:`${i.rejected_items} item${i.rejected_items===1?"":"s"} need changes`,context:i.deal_name,agentName:i.agent_name,avatarUrl:i.agent_avatar_url,dueDate:i.target_close_date,daysUntil:FZ(i.target_close_date),overdue:!1,priority:"medium",url:"/brokerage/transactions",actionLabel:"Open file"})}),s.disbursements.forEach(i=>{var o;if(i.status!=="draft"&&i.status!=="approved")return;const l=FZ(i.closing_date);r({key:`disbursement-${i.id}`,sourceType:"disbursement",sourceId:i.id,category:"disbursements",title:i.status==="draft"?"Disbursement awaiting approval":"Approved disbursement awaiting payment",context:i.property_address||"Commission disbursement",agentName:((o=s.nameFor)==null?void 0:o.call(s,i.agent_user_id))??null,avatarUrl:null,dueDate:i.closing_date,daysUntil:l,overdue:l!==null&&l<0,priority:i.status==="draft"?"high":"medium",url:"/brokerage/commission-plans",actionLabel:i.status==="draft"?"Approve":"Mark paid"})}),Qrs(s.agentRecords,s.renewalAgents,30).filter(i=>i.kind==="license"||i.kind==="eo").forEach(i=>{r({key:`renewal-${i.kind}-${i.agentId}`,sourceType:"renewal",sourceId:`${i.kind}:${i.agentId}:${i.dueDate}`,category:"renewals",title:i.expired?`${i.kind==="license"?"License":"E&O policy"} expired`:`${i.kind==="license"?"License":"E&O policy"} expires in ${i.daysUntil} day${i.daysUntil===1?"":"s"}`,context:i.detail||null,agentName:i.agentName,avatarUrl:i.avatarUrl,dueDate:i.dueDate,daysUntil:i.daysUntil,overdue:i.expired,priority:i.expired?"urgent":"high",url:"/brokerage/commission-plans",actionLabel:"Open record"})}),s.roster.forEach(i=>{i.overdue>0&&r({key:`onboarding-overdue-${i.agentId}`,sourceType:"onboarding",sourceId:`overdue:${i.agentId}`,category:"onboarding",title:`${i.overdue} onboarding step${i.overdue===1?"":"s"} overdue`,context:"Agent onboarding",agentName:i.name,avatarUrl:i.avatarUrl,dueDate:null,daysUntil:null,overdue:!0,priority:"high",url:"/brokerage/onboarding",actionLabel:"Open"}),i.needsReview>0&&r({key:`onboarding-review-${i.agentId}`,sourceType:"onboarding",sourceId:`review:${i.agentId}`,category:"onboarding",title:`${i.needsReview} onboarding item${i.needsReview===1?"":"s"} to review`,context:"Agent onboarding",agentName:i.name,avatarUrl:i.avatarUrl,dueDate:null,daysUntil:null,overdue:!1,priority:"medium",url:"/brokerage/onboarding",actionLabel:"Review"})}),s.followUps.forEach(i=>{const l=FZ(i.due_date?i.due_date.slice(0,10):null);l===null||l>0||r({key:`recruiting-${i.id}`,sourceType:"recruiting",sourceId:i.id,category:"recruiting",title:i.title||"Recruiting follow-up",context:i.prospectName,agentName:null,avatarUrl:null,dueDate:i.due_date?i.due_date.slice(0,10):null,daysUntil:l,overdue:l<0,priority:l<0?"high":"medium",url:"/brokerage/recruiting",actionLabel:"Follow up"})}),s.helpRequests.forEach(i=>{const l=i.event_start_at?i.event_start_at.slice(0,10):null,o=FZ(l);r({key:`help-${i.id}`,sourceType:"help_board",sourceId:i.id,category:"help_board",title:i.title||"Coverage needed",context:i.requesterName?`Posted by ${i.requesterName}`:"Help Board",agentName:null,avatarUrl:null,dueDate:l,daysUntil:o,overdue:o!==null&&o<0,priority:o!==null&&o<=2?"high":"low",url:`/brokerage/help-board/${i.id}`,actionLabel:"Open"})});const a={urgent:0,high:1,medium:2,low:3};return n.sort((i,l)=>{if(i.overdue!==l.overdue)return i.overdue?-1:1;if(a[i.priority]!==a[l.priority])return a[i.priority]-a[l.priority];const o=i.daysUntil??9999,c=l.daysUntil??9999;return o-c})}const Trr={urgent:"bg-destructive/10 text-destructive border-destructive/30",high:"bg-amber-500/10 text-amber-700 border-amber-500/30 dark:text-amber-400",medium:"bg-muted text-muted-foreground border-border",low:"bg-muted text-muted-foreground border-border"},Mrr=s=>(s||"?").split(" ").map(t=>t[0]).filter(Boolean).slice(0,2).join("").toUpperCase();function Prr({items:s,loading:t,onDismiss:n,onTrack:r}){const a=Fn(),[i,l]=_.useState("all"),o=_.useMemo(()=>{const h=new Set(s.map(m=>m.category));return Array.from(h)},[s]),c=_.useMemo(()=>i==="all"?s:s.filter(h=>h.category===i),[s,i]),d=s.filter(h=>h.overdue).length,u=s.filter(h=>!h.overdue&&h.daysUntil!==null&&h.daysUntil<=7).length;return t?e.jsx("div",{className:"space-y-3",children:[0,1,2,3].map(h=>e.jsx(cn,{className:"h-20 w-full"},h))}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsx(ve,{children:e.jsxs(Me,{className:"p-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Needs attention"}),e.jsx("p",{className:"text-2xl font-semibold",children:s.length})]})}),e.jsx(ve,{children:e.jsxs(Me,{className:"p-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Overdue"}),e.jsx("p",{className:At("text-2xl font-semibold",d>0&&"text-destructive"),children:d})]})}),e.jsx(ve,{children:e.jsxs(Me,{className:"p-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Due this week"}),e.jsx("p",{className:"text-2xl font-semibold",children:u})]})})]}),e.jsxs(ve,{children:[e.jsxs(bt,{className:"flex-row items-start justify-between gap-3 space-y-0",children:[e.jsxs("div",{children:[e.jsx(St,{className:"text-base",children:"What needs your attention"}),e.jsx(kn,{children:"Pulled live from compliance, financials, onboarding, recruiting and the help board."})]}),e.jsxs(is,{value:i,onValueChange:l,children:[e.jsx(rs,{className:"w-[160px] shrink-0",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All areas"}),o.map(h=>e.jsx(He,{value:h,children:N6e[h]||h},h))]})]})]}),e.jsx(Me,{className:"space-y-2",children:c.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Er,{className:"mb-3 h-10 w-10 text-emerald-500"}),e.jsx("p",{className:"font-medium",children:"Nothing needs attention right now"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"New items appear here as files, renewals and requests come in."})]}):c.map(h=>e.jsxs("div",{className:At("flex flex-col gap-3 rounded-lg border p-3 sm:flex-row sm:items-center",h.overdue&&"border-destructive/40 bg-destructive/[0.03]"),children:[e.jsxs(ja,{className:"h-9 w-9 shrink-0",children:[h.avatarUrl&&e.jsx(pi,{src:h.avatarUrl,alt:""}),e.jsx(Na,{className:"text-xs",children:Mrr(h.agentName)})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:h.title}),e.jsx(Oe,{variant:"outline",className:At("text-[10px]",Trr[h.priority]),children:N6e[h.category]||h.category})]}),e.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground",children:[h.agentName&&e.jsx("span",{children:h.agentName}),h.context&&e.jsx("span",{className:"truncate",children:h.context}),h.dueDate&&e.jsxs("span",{className:At("flex items-center gap-1",h.overdue&&"font-medium text-destructive"),children:[h.overdue?e.jsx(xl,{className:"h-3 w-3"}):e.jsx(Qd,{className:"h-3 w-3"}),tit(h.dueDate)]})]})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[e.jsx(B,{size:"sm",onClick:()=>a(h.url),children:h.actionLabel}),e.jsx(B,{size:"sm",variant:"outline",title:"Track as a task",onClick:()=>r({title:h.title,description:[h.agentName,h.context].filter(Boolean).join(" — ")||null,category:h.category,priority:h.priority,due_date:h.dueDate,source_type:h.sourceType,source_id:h.sourceId,source_url:h.url}),children:e.jsx(zQ,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",title:"Dismiss",onClick:()=>n(h),children:e.jsx(Qn,{className:"h-4 w-4"})})]})]},h.key))})]})]})}const zde=["todo","in_progress","done"],Lrr={urgent:"bg-destructive",high:"bg-amber-500",medium:"bg-primary/60",low:"bg-muted-foreground/40"};function Irr({tasks:s,people:t,loading:n,onNew:r,onEdit:a,onStatus:i,onDelete:l}){const[o,c]=_.useState("all"),[d,u]=_.useState("all"),h=_.useMemo(()=>s.filter(y=>!y.dismissed_at).filter(y=>o==="all"?!0:o==="unassigned"?!y.assignee_user_id:y.assignee_user_id===o).filter(y=>d==="all"?!0:y.category===d),[s,o,d]),m=y=>{var v;return y?((v=t.find(g=>g.id===y))==null?void 0:v.name)||"Team member":"Unassigned"},p=_.useMemo(()=>Array.from(new Set(s.map(y=>y.category))),[s]);if(n)return e.jsx(cn,{className:"h-72 w-full"});const f=(y,v)=>{const g=zde.indexOf(y.status),b=zde[g+v];b&&i(y,b)};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(is,{value:o,onValueChange:c,children:[e.jsx(rs,{className:"w-[180px]",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"Everyone"}),e.jsx(He,{value:"unassigned",children:"Unassigned"}),t.map(y=>e.jsx(He,{value:y.id,children:y.name},y.id))]})]}),e.jsxs(is,{value:d,onValueChange:u,children:[e.jsx(rs,{className:"w-[170px]",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All categories"}),p.map(y=>e.jsx(He,{value:y,children:N6e[y]||y},y))]})]}),e.jsxs(B,{className:"ml-auto",onClick:r,children:[e.jsx(rn,{className:"mr-2 h-4 w-4"})," New task"]})]}),e.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:zde.map(y=>{const v=h.filter(g=>g.status===y);return e.jsxs(ve,{className:"flex flex-col",children:[e.jsx(bt,{className:"pb-3",children:e.jsxs(St,{className:"flex items-center justify-between text-sm",children:[YYe[y],e.jsx(Oe,{variant:"secondary",children:v.length})]})}),e.jsxs(Me,{className:"space-y-2",children:[v.length===0&&e.jsx("p",{className:"py-6 text-center text-sm text-muted-foreground",children:"Nothing here"}),v.map(g=>{const b=!!g.due_date&&g.status!=="done"&&g.due_datea(g),children:[e.jsx("p",{className:"truncate font-medium",children:g.title}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[N6e[g.category]||g.category," · ",m(g.assignee_user_id)]})]}),e.jsxs(tu,{children:[e.jsx(su,{asChild:!0,children:e.jsx(B,{size:"icon",variant:"ghost",className:"h-7 w-7",children:e.jsx(Xx,{className:"h-4 w-4"})})}),e.jsxs(Od,{align:"end",children:[e.jsxs(ca,{onClick:()=>a(g),children:[e.jsx(Ya,{className:"mr-2 h-4 w-4"})," Edit"]}),zde.filter(j=>j!==g.status).map(j=>e.jsxs(ca,{onClick:()=>i(g,j),children:["Move to ",YYe[j]]},j)),e.jsxs(ca,{className:"text-destructive",onClick:()=>l(g),children:[e.jsx(Sn,{className:"mr-2 h-4 w-4"})," Delete"]})]})]})]}),g.due_date&&e.jsxs("p",{className:At("mt-2 flex items-center gap-1 text-xs",b?"text-destructive":"text-muted-foreground"),children:[e.jsx(Qd,{className:"h-3 w-3"})," ",tit(g.due_date)]}),e.jsxs("div",{className:"mt-2 flex gap-1 md:hidden",children:[e.jsx(B,{size:"sm",variant:"outline",className:"flex-1",disabled:y==="todo",onClick:()=>f(g,-1),children:e.jsx(ka,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"outline",className:"flex-1",disabled:y==="done",onClick:()=>f(g,1),children:e.jsx(La,{className:"h-4 w-4"})})]})]},g.id)})]})]},y)})})]})}const Drr=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],L4t=(s,t,n)=>`${s}-${String(t+1).padStart(2,"0")}-${String(n).padStart(2,"0")}`;function Rrr({items:s,tasks:t,closings:n}){const r=new Date,[a,i]=_.useState({y:r.getFullYear(),m:r.getMonth()}),[l,o]=_.useState(null),c=_.useMemo(()=>{const b=[];return s.forEach(j=>{j.dueDate&&b.push({id:j.key,label:j.title,tone:"bg-amber-500",date:j.dueDate})}),t.filter(j=>!j.dismissed_at&&j.due_date&&j.status!=="done").forEach(j=>b.push({id:j.id,label:j.title,tone:"bg-primary",date:j.due_date})),n.forEach(j=>{j.date&&b.push({id:`close-${j.id}`,label:`Closing — ${j.label}`,tone:"bg-emerald-500",date:j.date.slice(0,10)})}),b},[s,t,n]),d=_.useMemo(()=>{const b=new Map;return c.forEach(j=>{const S=b.get(j.date)||[];S.push(j),b.set(j.date,S)}),b},[c]),u=new Date(Date.UTC(a.y,a.m,1)),h=u.getUTCDay(),m=new Date(Date.UTC(a.y,a.m+1,0)).getUTCDate(),p=[...Array.from({length:h},()=>null),...Array.from({length:m},(b,j)=>j+1)],f=new Intl.DateTimeFormat("en-US",{month:"long",year:"numeric",timeZone:"UTC"}).format(u),y=L4t(r.getFullYear(),r.getMonth(),r.getDate()),v=l?d.get(l)||[]:[],g=b=>i(j=>{const S=j.m+b;return S<0?{y:j.y-1,m:11}:S>11?{y:j.y+1,m:0}:{y:j.y,m:S}});return e.jsxs("div",{className:"grid gap-4 lg:grid-cols-[2fr,1fr]",children:[e.jsxs(ve,{children:[e.jsxs(bt,{className:"flex-row items-center justify-between space-y-0",children:[e.jsxs("div",{children:[e.jsx(St,{className:"text-base",children:f}),e.jsx(kn,{children:"Closings, renewals and due dates in one place."})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{size:"icon",variant:"outline",onClick:()=>g(-1),children:e.jsx($c,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"outline",onClick:()=>g(1),children:e.jsx(xi,{className:"h-4 w-4"})})]})]}),e.jsxs(Me,{children:[e.jsx("div",{className:"grid grid-cols-7 gap-1 text-center text-xs text-muted-foreground",children:Drr.map(b=>e.jsx("div",{className:"py-1",children:b},b))}),e.jsx("div",{className:"grid grid-cols-7 gap-1",children:p.map((b,j)=>{if(b===null)return e.jsx("div",{},`pad-${j}`);const S=L4t(a.y,a.m,b),C=d.get(S)||[];return e.jsxs("button",{onClick:()=>o(S),className:At("flex min-h-[64px] flex-col items-start rounded-md border p-1 text-left text-xs transition hover:bg-muted/60",S===y&&"border-primary",l===S&&"bg-muted"),children:[e.jsx("span",{className:At("mb-1 font-medium",S===y&&"text-primary"),children:b}),e.jsx("span",{className:"flex flex-wrap gap-0.5",children:C.slice(0,4).map(E=>e.jsx("span",{className:At("h-1.5 w-1.5 rounded-full",E.tone)},E.id))}),C.length>0&&e.jsxs("span",{className:"mt-auto text-[10px] text-muted-foreground",children:[C.length," item",C.length===1?"":"s"]})]},S)})})]})]}),e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsx(St,{className:"text-base",children:l?new Intl.DateTimeFormat("en-US",{dateStyle:"medium",timeZone:"UTC"}).format(new Date(`${l}T12:00:00Z`)):"Pick a day"}),e.jsx(kn,{children:l?`${v.length} item${v.length===1?"":"s"}`:"Select a date to see what is happening."})]}),e.jsxs(Me,{className:"space-y-2",children:[l&&v.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nothing scheduled."}),v.map(b=>e.jsxs("div",{className:"flex items-start gap-2 rounded-md border p-2 text-sm",children:[e.jsx("span",{className:At("mt-1.5 h-2 w-2 shrink-0 rounded-full",b.tone)}),e.jsx("span",{className:"min-w-0 flex-1",children:b.label})]},b.id)),e.jsx("div",{className:"pt-2",children:e.jsxs("div",{className:"flex flex-wrap gap-2 text-xs text-muted-foreground",children:[e.jsxs(Oe,{variant:"outline",children:[e.jsx("span",{className:"mr-1 h-2 w-2 rounded-full bg-emerald-500"})," Closings"]}),e.jsxs(Oe,{variant:"outline",children:[e.jsx("span",{className:"mr-1 h-2 w-2 rounded-full bg-amber-500"})," Action items"]}),e.jsxs(Oe,{variant:"outline",children:[e.jsx("span",{className:"mr-1 h-2 w-2 rounded-full bg-primary"})," Tasks"]})]})})]})]})]})}function Frr({taskId:s,people:t}){const{data:n=[]}=wrr(s),r=jrr(),[a,i]=_.useState(""),l=o=>{var c;return((c=t.find(d=>d.id===o))==null?void 0:c.name)||"Team member"};return e.jsxs("div",{className:"space-y-2 rounded-lg border p-3",children:[e.jsx(J,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Notes"}),e.jsxs("div",{className:"space-y-2",children:[n.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No notes yet."}),n.map(o=>e.jsxs("div",{className:"rounded-md bg-muted/50 p-2 text-sm",children:[e.jsxs("p",{className:"text-xs text-muted-foreground",children:[l(o.author_user_id)," · ",new Date(o.created_at).toLocaleDateString()]}),e.jsx("p",{className:"whitespace-pre-wrap",children:o.body})]},o.id))]}),e.jsx(Ms,{rows:2,placeholder:"Add a note…",value:a,onChange:o=>i(o.target.value)}),e.jsx(B,{size:"sm",variant:"outline",disabled:!a.trim()||r.isPending,onClick:()=>r.mutate({taskId:s,body:a},{onSuccess:()=>i("")}),children:"Add note"})]})}const I4t={title:"",description:"",category:"general",status:"todo",priority:"medium",due_date:null,assignee_user_id:null};function Orr({open:s,onOpenChange:t,task:n,initial:r,people:a,onSave:i,saving:l}){const[o,c]=_.useState(I4t);_.useEffect(()=>{s&&c(n?{id:n.id,title:n.title,description:n.description||"",category:n.category,status:n.status,priority:n.priority,due_date:n.due_date,assignee_user_id:n.assignee_user_id,source_type:n.source_type,source_id:n.source_id,source_url:n.source_url}:{...I4t,...r||{}})},[s,n,r]);const d=u=>c(h=>({...h,...u}));return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"max-h-[90vh] max-w-lg overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:n?"Edit task":"New task"}),e.jsx(_r,{children:"Assign office work to yourself or another manager."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"ops-title",children:"Title"}),e.jsx(xe,{id:"ops-title",value:o.title,onChange:u=>d({title:u.target.value}),placeholder:"Order new signage for the Maple listing"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"ops-desc",children:"Details"}),e.jsx(Ms,{id:"ops-desc",rows:3,value:o.description||"",onChange:u=>d({description:u.target.value})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Category"}),e.jsxs(is,{value:o.category,onValueChange:u=>d({category:u}),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsx(as,{children:Yrs.map(u=>e.jsx(He,{value:u.value,children:u.label},u.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Priority"}),e.jsxs(is,{value:o.priority,onValueChange:u=>d({priority:u}),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsx(as,{children:Object.entries(xrr).map(([u,h])=>e.jsx(He,{value:u,children:h},u))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Status"}),e.jsxs(is,{value:o.status,onValueChange:u=>d({status:u}),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsx(as,{children:Object.entries(YYe).map(([u,h])=>e.jsx(He,{value:u,children:h},u))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"ops-due",children:"Due date"}),e.jsx(xe,{id:"ops-due",type:"date",value:o.due_date||"",onChange:u=>d({due_date:u.target.value||null})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Assigned to"}),e.jsxs(is,{value:o.assignee_user_id||"unassigned",onValueChange:u=>d({assignee_user_id:u==="unassigned"?null:u}),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"unassigned",children:"Unassigned"}),a.map(u=>e.jsx(He,{value:u.id,children:u.name},u.id))]})]})]}),n&&e.jsx(Frr,{taskId:n.id,people:a})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(B,{disabled:!o.title.trim()||l,onClick:()=>i(o),children:l?"Saving…":"Save task"})]})]})})}const zrr=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];function Brr({brokerageId:s}){const{data:t}=Nrr(s),n=krr(s),[r,a]=_.useState(!1),[i,l]=_.useState(!1),[o,c]=_.useState("1");return _.useEffect(()=>{a((t==null?void 0:t.email_enabled)??!1),l((t==null?void 0:t.push_enabled)??!1),c(String((t==null?void 0:t.send_day)??1))},[t]),e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsx(St,{className:"text-base",children:"Weekly summary"}),e.jsx(kn,{children:"Off by default. Turn it on and you alone get a weekly rundown of what is open, due and overdue."})]}),e.jsxs(Me,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4 rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(J,{htmlFor:"digest-email",children:"Email me the weekly summary"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Sent once a week to your account email."})]}),e.jsx(fn,{id:"digest-email",checked:r,onCheckedChange:a})]}),e.jsxs("div",{className:"flex items-center justify-between gap-4 rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(J,{htmlFor:"digest-push",children:"Send me a phone notification"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Same summary, delivered as a push alert."})]}),e.jsx(fn,{id:"digest-push",checked:i,onCheckedChange:l})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Send day"}),e.jsxs(is,{value:o,onValueChange:c,disabled:!r&&!i,children:[e.jsx(rs,{className:"w-[200px]",children:e.jsx(ls,{})}),e.jsx(as,{children:zrr.map((d,u)=>e.jsx(He,{value:String(u),children:d},d))})]})]}),e.jsx(B,{disabled:n.isPending,onClick:()=>n.mutate({email_enabled:r,push_enabled:i,send_day:Number(o)}),children:n.isPending?"Saving…":"Save settings"})]})]})}const Urr=()=>{const{user:s,rolesLoading:t,isBrokerageManager:n,isAdmin:r,brokerageId:a,managedBrokerages:i,selectedBrokerageId:l,setSelectedBrokerageId:o}=hs(),c=Fn(),{data:d=[],isLoading:u}=ZQe(),[h,m]=_.useState(!1),p=d.length>0,f=n||r,y=_.useMemo(()=>{var pe;return l||(i.length>0?i[0].id:null)||((pe=d[0])==null?void 0:pe.brokerage_id)||a},[l,i,d,a]);_.useEffect(()=>{if(!(!s||u||t)){if(!f&&!p){c("/dashboard");return}!l&&i.length>0&&o(i[0].id),m(!0)}},[s,u,t,f,p,c,i,l,o]);const{data:v=[],isLoading:g}=XQe(y),{data:b=[]}=Wrs(y),{data:j=[]}=Krs(y),{data:S=[]}=CKt(y),{data:C=[]}=prr(y),{data:E=[]}=frr(y),{data:P=[],isLoading:M}=grr(y),I=yrr(y),D=vrr(y),O=brr(y),V=_rr(y),[G,$]=_.useState(!1),[H,Y]=_.useState(null),[Z,ne]=_.useState(null),ce=_.useMemo(()=>S.map(pe=>({id:pe.agentId,name:pe.name})),[S]),ie=pe=>{var Ce;return pe?((Ce=ce.find(Ae=>Ae.id===pe))==null?void 0:Ce.name)??null:null},te=_.useMemo(()=>Err({complianceDeals:v,disbursements:b,agentRecords:j,renewalAgents:S.map(pe=>({agentId:pe.agentId,name:pe.name,avatarUrl:pe.avatarUrl})),roster:S.map(pe=>({agentId:pe.agentId,name:pe.name,avatarUrl:pe.avatarUrl,overdue:pe.overdue,needsReview:pe.needsReview})),followUps:C,helpRequests:E,tasks:P,nameFor:ie}),[v,b,j,S,C,E,P]),ae=_.useMemo(()=>v.filter(pe=>pe.target_close_date).map(pe=>({id:pe.deal_id,label:pe.property_address||pe.deal_name,date:pe.target_close_date})),[v]),le=()=>{Y(null),ne(null),$(!0)},be=pe=>{Y(null),ne(pe),$(!0)},me=pe=>{Y(pe),ne(null),$(!0)},he=pe=>V.mutate({sourceType:pe.sourceType,sourceId:pe.sourceId,title:pe.title,category:pe.category});return h?e.jsx(zs,{title:"Operations",description:"Everything that needs a decision today, plus your office task board and calendar",children:e.jsxs("div",{className:"space-y-6",children:[i.length>1&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Managing:"}),e.jsxs(is,{value:l||"",onValueChange:o,children:[e.jsxs(rs,{className:"w-[280px]",children:[e.jsx(ai,{className:"mr-2 h-4 w-4"}),e.jsx(ls,{placeholder:"Select brokerage"})]}),e.jsx(as,{children:i.map(pe=>e.jsx(He,{value:pe.id,children:pe.name},pe.id))})]})]}),y?e.jsxs(Yr,{defaultValue:"today",className:"space-y-4",children:[e.jsx("div",{className:"overflow-x-auto pb-1",children:e.jsxs(Zr,{className:"grid h-auto min-w-[460px] grid-cols-4",children:[e.jsx(Ht,{value:"today",children:"Today"}),e.jsx(Ht,{value:"tasks",children:"Task board"}),e.jsx(Ht,{value:"calendar",children:"Calendar"}),e.jsx(Ht,{value:"notifications",children:"Notifications"})]})}),e.jsx(Gt,{value:"today",children:e.jsx(Prr,{items:te,loading:g,onDismiss:he,onTrack:be})}),e.jsx(Gt,{value:"tasks",children:e.jsx(Irr,{tasks:P,people:ce,loading:M,onNew:le,onEdit:me,onStatus:(pe,Ce)=>D.mutate({id:pe.id,status:Ce}),onDelete:pe=>O.mutate(pe.id)})}),e.jsx(Gt,{value:"calendar",children:e.jsx(Rrr,{items:te,tasks:P,closings:ae})}),e.jsx(Gt,{value:"notifications",children:e.jsx(Brr,{brokerageId:y})})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(ai,{className:"mb-4 h-12 w-12 text-muted-foreground"}),e.jsx("h2",{className:"mb-1 text-xl font-semibold",children:"No Brokerage Assigned"}),e.jsx("p",{className:"text-muted-foreground",children:"You don't have any brokerages to manage."})]}),e.jsx(Orr,{open:G,onOpenChange:$,task:H,initial:Z,people:ce,saving:I.isPending,onSave:pe=>I.mutate(pe,{onSuccess:()=>$(!1)})})]})}):null},D4t="id, agent_id, brokerage_id, team_id, owner_type, subdomain_slug, custom_domain, site_title, org_name, org_logo_url, brand_color, is_active, created_at";function MBe(s,t){return t?`https://${t}`:s?`https://${s}.thelocalmove.com`:null}function Jrs(){const{user:s,isAdmin:t,isBrokerageManager:n,managedBrokerages:r,brokerageId:a,selectedBrokerageId:i}=hs(),{data:l=[]}=QMe(),o=_.useMemo(()=>l.filter(p=>p.role==="team_leader"),[l]),c=_.useMemo(()=>r.length?r:(n||t)&&a?[{id:a,name:"My brokerage"}]:[],[r,n,t,a]),d=_.useMemo(()=>c.map(p=>p.id),[c]),u=_.useMemo(()=>o.map(p=>p.teamId),[o]),h=at({queryKey:["my-websites",s==null?void 0:s.id,d.join(","),u.join(",")],enabled:!!(s!=null&&s.id),staleTime:60*1e3,queryFn:async()=>{const[p,f]=await Promise.all([q.from("lead_sites").select(D4t).eq("agent_id",s.id).order("created_at",{ascending:!0}),d.length||u.length?q.from("lead_sites").select(D4t).or([d.length?`brokerage_id.in.(${d.join(",")})`:"",u.length?`team_id.in.(${u.join(",")})`:""].filter(Boolean).join(",")):Promise.resolve({data:[],error:null})]);if(p.error)throw p.error;if(f.error)throw f.error;return{own:(p.data||[]).filter(y=>(y.owner_type||"agent")==="agent"),org:f.data||[]}}}),m=_.useMemo(()=>{var g,b,j;const p=((g=h.data)==null?void 0:g.own)||[],f=((b=h.data)==null?void 0:b.org)||[],y=[],v=p.find(S=>S.is_active)||p[0]||null;v?y.push({kind:"agent",id:v.id,ownerId:null,name:v.site_title||"My website",kindLabel:"My agent site",slug:v.subdomain_slug,customDomain:v.custom_domain,isActive:!!v.is_active,logoUrl:null,brandColor:v.brand_color,editPath:`/my-website/${v.id}/edit`,publicUrl:MBe(v.subdomain_slug,v.custom_domain),exists:!0}):y.push({kind:"agent",id:null,ownerId:null,name:"My agent site",kindLabel:"My agent site",slug:null,customDomain:null,isActive:!1,logoUrl:null,brandColor:null,editPath:"/need-a-website",publicUrl:null,exists:!1});for(const S of c){const C=f.find(E=>E.owner_type==="brokerage"&&E.brokerage_id===S.id)||null;y.push({kind:"brokerage",id:(C==null?void 0:C.id)??null,ownerId:S.id,name:(C==null?void 0:C.org_name)||(C==null?void 0:C.site_title)||S.name,kindLabel:"Company site",slug:(C==null?void 0:C.subdomain_slug)??null,customDomain:(C==null?void 0:C.custom_domain)??null,isActive:!!(C!=null&&C.is_active),logoUrl:(C==null?void 0:C.org_logo_url)??null,brandColor:(C==null?void 0:C.brand_color)??null,editPath:"/brokerage/website",publicUrl:MBe((C==null?void 0:C.subdomain_slug)??null,(C==null?void 0:C.custom_domain)??null),exists:!!C})}for(const S of o){const C=f.find(E=>E.owner_type==="team"&&E.team_id===S.teamId)||null;y.push({kind:"team",id:(C==null?void 0:C.id)??null,ownerId:S.teamId,name:(C==null?void 0:C.org_name)||(C==null?void 0:C.site_title)||((j=S.team)==null?void 0:j.name)||"My team",kindLabel:"Team site",slug:(C==null?void 0:C.subdomain_slug)??null,customDomain:(C==null?void 0:C.custom_domain)??null,isActive:!!(C!=null&&C.is_active),logoUrl:(C==null?void 0:C.org_logo_url)??null,brandColor:(C==null?void 0:C.brand_color)??null,editPath:`/team/website?teamId=${S.teamId}`,publicUrl:MBe((C==null?void 0:C.subdomain_slug)??null,(C==null?void 0:C.custom_domain)??null),exists:!!C})}return y},[h.data,c,o]);return{websites:m,isLoading:h.isLoading,ledTeams:o,hasOrgSites:m.some(p=>p.kind!=="agent")}}const qrr={agent:sl,brokerage:ai,team:In};function $rr({site:s}){const t=Fn(),n=qrr[s.kind],r=s.customDomain||(s.slug?`${s.slug}.thelocalmove.com`:null);return e.jsx(ve,{className:"overflow-hidden transition-shadow hover:shadow-md",children:e.jsxs(Me,{className:"flex flex-col gap-5 p-6 sm:flex-row sm:items-center",children:[e.jsx("div",{className:"flex h-16 w-16 shrink-0 items-center justify-center overflow-hidden rounded-xl",style:{backgroundColor:s.brandColor||"hsl(var(--muted))"},children:s.logoUrl?e.jsx("img",{src:s.logoUrl,alt:"",className:"max-h-full max-w-full object-contain"}):e.jsx(n,{className:`h-7 w-7 ${s.brandColor?"text-white":"text-muted-foreground"}`})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"truncate text-lg font-semibold",children:s.name}),s.exists?s.isActive?e.jsx(Oe,{children:"Live"}):e.jsx(Oe,{variant:"secondary",children:"Private preview"}):e.jsx(Oe,{variant:"outline",children:"Not created yet"})]}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:s.kindLabel}),e.jsx("p",{className:"mt-1 truncate text-sm text-muted-foreground",children:r||"Pick a web address when you create it"})]}),e.jsxs("div",{className:"flex shrink-0 flex-wrap gap-2",children:[s.exists&&s.publicUrl&&e.jsx(B,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:s.publicUrl,target:"_blank",rel:"noreferrer",children:[e.jsx(wr,{className:"mr-2 h-4 w-4"})," View"]})}),e.jsx(B,{onClick:()=>t(s.editPath),children:s.exists?e.jsxs(e.Fragment,{children:[e.jsx(Ya,{className:"mr-2 h-4 w-4"})," Edit site"]}):e.jsxs(e.Fragment,{children:[e.jsx(rn,{className:"mr-2 h-4 w-4"})," Create site"]})})]})]})})}function Vrr(){const{websites:s,isLoading:t}=Jrs();return e.jsx(zs,{title:"My Websites",description:"Every website you can edit, in one place",children:e.jsx("div",{className:"mx-auto max-w-4xl space-y-4 p-4 lg:p-8",children:t?[0,1].map(n=>e.jsx("div",{className:"h-32 animate-pulse rounded-xl bg-muted"},n)):e.jsxs(e.Fragment,{children:[s.map(n=>e.jsx($rr,{site:n},`${n.kind}-${n.ownerId||"me"}`)),e.jsxs("p",{className:"pt-2 text-center text-sm text-muted-foreground",children:["Looking for lead magnets, pop-ups and other add-ons?"," ",e.jsx(ir,{to:"/website-apps",className:"underline",children:"Website Apps"})]})]})})})}const R4t={bold_national:{display:"'Archivo', 'Helvetica Neue', Arial, sans-serif",body:"'Inter', system-ui, sans-serif",radius:"0.25rem"},editorial_boutique:{display:"'Playfair Display', Georgia, serif",body:"'Inter', system-ui, sans-serif",radius:"0px"},modern_minimal:{display:"'Sora', system-ui, sans-serif",body:"'Manrope', system-ui, sans-serif",radius:"0.75rem"},coastal_luxury:{display:"'Cormorant Garamond', Georgia, serif",body:"'Karla', system-ui, sans-serif",radius:"0.5rem"}};function rwr(s,t){var a;const n=(t==null?void 0:t.orgPreset)||((a=s==null?void 0:s.themeConfig)==null?void 0:a.orgPreset)||"editorial_boutique",r=R4t[n]||R4t.editorial_boutique;return{primary:(s==null?void 0:s.brandColor)||(t==null?void 0:t.primaryColor)||"#12222e",accent:(s==null?void 0:s.accentColor)||(t==null?void 0:t.accentColor)||"#c9a96e",display:r.display,body:r.body,radius:r.radius,name:(s==null?void 0:s.orgName)||(s==null?void 0:s.siteTitle)||"Our Company",logoUrl:(s==null?void 0:s.orgLogoUrl)||(s==null?void 0:s.teamLogoUrl)||null,logoDarkUrl:(s==null?void 0:s.orgLogoDarkUrl)||(s==null?void 0:s.orgLogoUrl)||(s==null?void 0:s.teamLogoUrl)||null}}const eas=[{key:"bold_national",label:"Bold National",description:"Confident, bold type and a tight grid — national franchise energy."},{key:"editorial_boutique",label:"Editorial Boutique",description:"Serif display type and magazine layouts for a boutique feel."},{key:"modern_minimal",label:"Modern Minimal",description:"Clean geometry, generous whitespace, soft rounded cards."},{key:"coastal_luxury",label:"Coastal Luxury",description:"Airy, elegant serif with warm light and wide imagery."}];function tas(s){return(s==null?void 0:s.orgProfile)||{}}function awr(s){const t=(s==null?void 0:s.ownerType)==="team";return{isTeam:t,org:t?"team":"brokerage",people:t?"Our Team":"Our Agents",meetPeople:t?"Meet Our Team":"Meet Our Agents",peopleNoun:t?"team members":"agents",joinShort:t?"Join Our Team":"Join Us",joinTitle:t?"Join Our Team":"Careers"}}function iwr(s){var n;if((s==null?void 0:s.ownerType)!=="team")return null;const t=(n=tas(s).affiliation)==null?void 0:n.trim();return t||null}function owr(s){const t=tas(s),n=(t.offices||[]).filter(o=>o&&(o.address||o.city||o.phone||o.email)),r=n[0]||{},a=[r.name||null,r.address||null,[r.city,r.state].filter(Boolean).join(", ")+(r.zip?` ${r.zip}`:"")].filter(o=>!!o&&o.trim().length>0),i=[{label:"Facebook",url:t.facebookUrl},{label:"Instagram",url:t.instagramUrl},{label:"LinkedIn",url:t.linkedinUrl},{label:"YouTube",url:t.youtubeUrl}].filter(o=>!!o.url),l=s!=null&&s.brokerageLicenseNumber?`License #${s.brokerageLicenseNumber}${s!=null&&s.licenseState?` (${s.licenseState})`:""}`:null;return{phone:r.phone||null,email:r.email||null,addressLines:a,hours:r.hours||null,offices:n,social:i,legalName:(s==null?void 0:s.brokerageLegalName)||null,licenseLine:l}}const Hrr=10*1024*1024;function PBe({label:s,hint:t,value:n,onChange:r,slot:a,siteId:i,dark:l,className:o}){const c=_.useRef(null),[d,u]=_.useState(!1),[h,m]=_.useState(!1),p=async f=>{if(!f.type.startsWith("image/")){se.error("Please choose an image file");return}if(f.size>Hrr){se.error("Image must be under 10MB");return}u(!0);try{const y=(f.name.split(".").pop()||"png").toLowerCase(),v=`org-sites/${i}/${a}-${Date.now()}.${y}`,{error:g}=await q.storage.from("agent-uploads").upload(v,f,{upsert:!0,contentType:f.type});if(g)throw g;const{data:b}=q.storage.from("agent-uploads").getPublicUrl(v);r(b.publicUrl),se.success(`${s} uploaded`)}catch(y){se.error(y.message||"Upload failed")}finally{u(!1),c.current&&(c.current.value="")}};return e.jsxs("div",{className:o,children:[e.jsx(J,{className:"text-sm font-medium",children:s}),t&&e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:t}),e.jsxs("div",{onDragOver:f=>{f.preventDefault(),m(!0)},onDragLeave:()=>m(!1),onDrop:f=>{var v;f.preventDefault(),m(!1);const y=(v=f.dataTransfer.files)==null?void 0:v[0];y&&p(y)},onClick:()=>{var f;return!d&&((f=c.current)==null?void 0:f.click())},className:`mt-2 flex cursor-pointer items-center gap-4 rounded-lg border-2 border-dashed p-4 transition-colors ${h?"border-primary bg-primary/5":"border-muted-foreground/25 hover:border-muted-foreground/50"}`,children:[e.jsx("div",{className:`flex h-20 w-28 shrink-0 items-center justify-center overflow-hidden rounded-md ${l?"bg-slate-900":"bg-muted"}`,children:n?e.jsx("img",{src:n,alt:s,className:"max-h-full max-w-full object-contain"}):e.jsx(hc,{className:"h-6 w-6 text-muted-foreground"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm font-medium",children:d?"Uploading…":n?"Replace image":"Drag an image here, or click to choose"}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"PNG, JPG or SVG up to 10MB"})]}),d?e.jsx(Ct,{className:"h-4 w-4 animate-spin text-muted-foreground"}):e.jsx(Oa,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx("input",{ref:c,type:"file",accept:"image/*",className:"hidden",onChange:f=>{var v;const y=(v=f.target.files)==null?void 0:v[0];y&&p(y)}}),e.jsxs("div",{className:"mt-2 flex items-center gap-2",children:[e.jsx(xe,{value:n||"",onChange:f=>r(f.target.value||null),placeholder:"…or paste an image URL",className:"h-9 text-xs"}),n&&e.jsx(B,{type:"button",variant:"ghost",size:"icon",className:"h-9 w-9 shrink-0",onClick:()=>r(null),children:e.jsx(Sn,{className:"h-4 w-4"})})]})]})}const Grr="id, agent_id, subdomain_slug, custom_domain, site_title, site_tagline, is_active, brand_color, accent_color, theme_config, owner_type, org_tier, org_name, org_logo_url, org_logo_dark_url, org_profile, brokerage_id, team_id";function Wrr(s){const{brokerageId:t,teamId:n}=s;return at({queryKey:["org-site",t,n],enabled:!!(t||n),queryFn:async()=>{let r=q.from("lead_sites").select(Grr).limit(1);r=n?r.eq("team_id",n).eq("owner_type","team"):r.eq("brokerage_id",t).eq("owner_type","brokerage");const{data:a,error:i}=await r.maybeSingle();if(i)throw i;return a??null}})}function Krr(s){return at({queryKey:["org-site-roster-admin",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("org_site_agents").select("id, site_id, user_id, display_order, is_featured, is_visible, profile_slug, headline, blurb, specialties, languages").eq("site_id",s).order("display_order",{ascending:!0});if(n)throw n;const r=t||[];if(!r.length)return[];const{data:a}=await q.from("profiles").select("id, name, avatar_url, email, title").in("id",r.map(l=>l.user_id)),i=new Map((a||[]).map(l=>[l.id,l]));return r.map(l=>({...l,profile:i.get(l.user_id)}))}})}function Yrr(s){const t=Bt();return mt({mutationFn:async()=>{const{data:n,error:r}=await q.rpc("sync_org_site_roster",{p_site_id:s});if(r)throw r;return n},onSuccess:n=>{t.invalidateQueries({queryKey:["org-site-roster-admin",s]}),t.invalidateQueries({queryKey:["org-site-roster",s]}),se.success(n?`${n} agent${n===1?"":"s"} added to the roster.`:"Roster is already up to date.")},onError:n=>se.error(n.message||"Could not refresh the roster.")})}function Zrr(s){const t=Bt();return mt({mutationFn:async({id:n,patch:r})=>{const{error:a}=await q.from("org_site_agents").update(r).eq("id",n);if(a)throw a},onSuccess:()=>{t.invalidateQueries({queryKey:["org-site-roster-admin",s]}),t.invalidateQueries({queryKey:["org-site-roster",s]})},onError:n=>se.error(n.message||"Could not save that change.")})}function Xrr(s){const t=Bt();return mt({mutationFn:async n=>{const{error:r}=await q.from("lead_sites").update(n).eq("id",s);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["org-site"]}),se.success("Saved.")},onError:n=>se.error(n.message||"Could not save the website.")})}function Bde(s){return s.toLowerCase().trim().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,40)}function sit({brokerageId:s,teamId:t,orgLabel:n="brokerage"}){const{data:r,isLoading:a,refetch:i}=Wrr({brokerageId:s,teamId:t});return a?e.jsx("div",{className:"flex h-40 items-center justify-center",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-2 border-primary border-t-transparent"})}):r?e.jsx(Jrr,{site:r,orgLabel:n}):e.jsx(Qrr,{brokerageId:s,teamId:t,orgLabel:n,onCreated:()=>i()})}function Qrr({brokerageId:s,teamId:t,orgLabel:n,onCreated:r}){const{user:a}=hs(),[i,l]=_.useState(""),[o,c]=_.useState(""),[d,u]=_.useState("editorial_boutique"),[h,m]=_.useState(!1),[p,f]=_.useState(null);_.useEffect(()=>{let v=!1;return(async()=>{if(t){const{data:S}=await q.from("teams").select("name, description, avatar_url, brokerage_id").eq("id",t).maybeSingle();if(v||!S)return;const C=S.name||"";C&&(l(M=>M||C),c(M=>M||Bde(C)));let E=null,P=null;if(S.brokerage_id){const[{data:M},{data:I}]=await Promise.all([q.from("brokerages").select("name").eq("id",S.brokerage_id).maybeSingle(),q.from("brokerage_brand_profiles").select("primary_color, accent_color, legal_name, license_number").eq("brokerage_id",S.brokerage_id).maybeSingle()]);E=(M==null?void 0:M.name)||null,P=I}if(v)return;f({logo:S.avatar_url||null,primary:(P==null?void 0:P.primary_color)||null,accent:(P==null?void 0:P.accent_color)||null,legalName:(P==null?void 0:P.legal_name)||null,license:(P==null?void 0:P.license_number)||null,about:S.description||null,affiliation:E});return}if(!s)return;const[{data:g},{data:b}]=await Promise.all([q.from("brokerage_brand_profiles").select("logo_url, primary_color, accent_color, legal_name, license_number").eq("brokerage_id",s).maybeSingle(),q.from("brokerages").select("name").eq("id",s).maybeSingle()]);if(v)return;const j=(b==null?void 0:b.name)||"";j&&(l(S=>S||j),c(S=>S||Bde(j))),f({logo:(g==null?void 0:g.logo_url)||null,primary:(g==null?void 0:g.primary_color)||null,accent:(g==null?void 0:g.accent_color)||null,legalName:(g==null?void 0:g.legal_name)||null,license:(g==null?void 0:g.license_number)||null,about:null,affiliation:null})})(),()=>{v=!0}},[s,t]);const y=async()=>{if(!a||!s&&!t)return;if(!i.trim()||!o.trim()){se.error(`Add a ${n} name and web address.`);return}m(!0);const{error:v}=await q.from("lead_sites").insert({agent_id:a.id,brokerage_id:t?null:s,team_id:t||null,owner_type:t?"team":"brokerage",org_tier:"essential",org_name:i.trim(),site_title:i.trim(),subdomain_slug:o.trim(),is_active:!1,org_logo_url:(p==null?void 0:p.logo)||null,brand_color:(p==null?void 0:p.primary)||"#12222e",accent_color:(p==null?void 0:p.accent)||"#c9a96e",brokerage_legal_name:(p==null?void 0:p.legalName)||null,brokerage_license_number:(p==null?void 0:p.license)||null,org_profile:{offices:[{name:t?`${i.trim()} — Office`:`${i.trim()} — Main Office`}],...p!=null&&p.about?{about:p.about}:{},...p!=null&&p.affiliation?{affiliation:p.affiliation}:{}},theme_config:{orgPreset:d}});if(m(!1),v){se.error(v.message.includes("duplicate")?"That web address is taken — try another.":v.message);return}se.success("Website created as a private preview."),r()};return e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(sl,{className:"h-5 w-5"})," Create your ",n," website"]}),e.jsxs(kn,{children:["One site for your whole ",n," — every agent's profile, every listing, city pages, blog, recruiting page and lead capture straight into LevelUp. It starts as a private preview that only you can see."]})]}),e.jsxs(Me,{className:"space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:n==="team"?"Team name":"Company name"}),e.jsx(xe,{value:i,onChange:v=>{l(v.target.value),o||c(Bde(v.target.value))},placeholder:n==="team"?"The Bishop Group":"RE/MAX Executives"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Web address"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xe,{value:o,onChange:v=>c(Bde(v.target.value)),placeholder:"bishop-group"}),e.jsx("span",{className:"whitespace-nowrap text-sm text-muted-foreground",children:".thelocalmove.com"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"You can point your own domain at it later."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Design"}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:eas.map(v=>e.jsxs("button",{type:"button",onClick:()=>u(v.key),className:`rounded-lg border p-4 text-left transition-colors ${d===v.key?"border-primary bg-primary/5":"border-border hover:border-primary/40"}`,children:[e.jsx("p",{className:"font-medium",children:v.label}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:v.description})]},v.key))})]}),(p==null?void 0:p.logo)&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"We'll start the site with your company logo and brand colors — you can change them anytime."}),e.jsx(B,{onClick:y,disabled:h,className:"w-full",children:h?"Creating…":"Create website"})]})]})}function Jrr({site:s,orgLabel:t}){var Z;const{isAdmin:n}=hs(),r=Xrr(s.id),{data:a=[],isLoading:i}=Krr(s.id),l=Yrr(s.id),o=Zrr(s.id),[c,d]=_.useState(s.site_title||""),[u,h]=_.useState(s.site_tagline||""),[m,p]=_.useState(s.org_name||""),[f,y]=_.useState(s.org_logo_url||null),[v,g]=_.useState(s.org_logo_dark_url||null),[b,j]=_.useState(s.org_profile||{}),S=(ne,ce)=>j(ie=>({...ie,[ne]:ce})),C=b.offices||[],E=(ne,ce)=>S("offices",C.map((ie,te)=>te===ne?{...ie,...ce}:ie)),P=b.stats||[],[M,I]=_.useState(s.brand_color||"#12222e"),[D,O]=_.useState(s.accent_color||"#c9a96e"),[V,G]=_.useState(s.custom_domain||""),$=((Z=s.theme_config)==null?void 0:Z.orgPreset)||"editorial_boutique",H=s.custom_domain?`https://${s.custom_domain}`:`https://${s.subdomain_slug}.thelocalmove.com`,Y=`${H}?previewSlug=${s.subdomain_slug}`;return e.jsxs("div",{className:"space-y-6",children:[e.jsx(ve,{children:e.jsxs(bt,{className:"flex-row items-start justify-between gap-4 space-y-0",children:[e.jsxs("div",{children:[e.jsxs(St,{className:"flex flex-wrap items-center gap-2",children:[s.org_name||s.site_title,e.jsx(Oe,{variant:s.is_active?"default":"secondary",children:s.is_active?"Live":"Preview"}),e.jsx(Oe,{variant:"outline",children:s.org_tier==="pro"?"Pro (IDX)":"Essential"})]}),e.jsx(kn,{children:H})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(B,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:s.is_active?H:Y,target:"_blank",rel:"noreferrer",children:[e.jsx(wr,{className:"mr-2 h-4 w-4"})," Preview"]})}),e.jsxs("div",{className:"flex items-center gap-2 rounded-md border px-3 py-2",children:[e.jsx("span",{className:"text-sm",children:"Published"}),e.jsx(fn,{checked:s.is_active,onCheckedChange:ne=>r.mutate({is_active:ne})})]})]})]})}),e.jsxs(Yr,{defaultValue:"brand",children:[e.jsxs(Zr,{className:"h-auto flex-wrap justify-start gap-1",children:[e.jsx(Ht,{value:"brand",children:"Identity"}),e.jsx(Ht,{value:"story",children:"Story"}),e.jsx(Ht,{value:"offices",children:"Offices"}),e.jsx(Ht,{value:"social",children:"Social"}),e.jsxs(Ht,{value:"agents",children:["Agents (",a.length,")"]}),e.jsx(Ht,{value:"domain",children:"Address"}),e.jsx(Ht,{value:"plan",children:"Plan"})]}),e.jsx(Gt,{value:"brand",className:"mt-6",children:e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsx(St,{children:"Brand & content"}),e.jsx(kn,{children:"The look adapts to your colors, logo and chosen design."})]}),e.jsxs(Me,{className:"space-y-5",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:t==="team"?"Team name":"Company name"}),e.jsx(xe,{value:m,onChange:ne=>p(ne.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Headline"}),e.jsx(xe,{value:c,onChange:ne=>d(ne.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Tagline"}),e.jsx(Ms,{rows:2,value:u,onChange:ne=>h(ne.target.value)})]}),t==="team"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Brokerage the team hangs its license with"}),e.jsx(xe,{value:b.affiliation||"",onChange:ne=>S("affiliation",ne.target.value),placeholder:"RE/MAX Integrity"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Shown quietly in the footer and on the About page — most states require a team's advertising to name the brokerage."})]}),e.jsxs("div",{className:"grid gap-5 sm:grid-cols-2",children:[e.jsx(PBe,{label:t==="team"?"Team logo":"Company logo",hint:"Shown in the header. Use a version that reads well on white.",value:f,onChange:y,slot:"logo",siteId:s.id}),e.jsx(PBe,{label:"Logo for dark backgrounds",hint:"Optional — used in the footer and dark headers.",value:v,onChange:g,slot:"logo-dark",siteId:s.id,dark:!0})]}),e.jsx(PBe,{label:"Homepage hero image",hint:"A wide photo of your market, office or team. 2000px wide works best.",value:b.heroImageUrl,onChange:ne=>S("heroImageUrl",ne||void 0),slot:"hero",siteId:s.id}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Primary color"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{type:"color",value:M,onChange:ne=>I(ne.target.value),className:"h-10 w-14 rounded border"}),e.jsx(xe,{value:M,onChange:ne=>I(ne.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Accent color"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{type:"color",value:D,onChange:ne=>O(ne.target.value),className:"h-10 w-14 rounded border"}),e.jsx(xe,{value:D,onChange:ne=>O(ne.target.value)})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Design"}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:eas.map(ne=>e.jsxs("button",{type:"button",onClick:()=>r.mutate({theme_config:{...s.theme_config||{},orgPreset:ne.key}}),className:`rounded-lg border p-4 text-left transition-colors ${$===ne.key?"border-primary bg-primary/5":"border-border hover:border-primary/40"}`,children:[e.jsx("p",{className:"font-medium",children:ne.label}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:ne.description})]},ne.key))})]}),e.jsx(B,{onClick:()=>r.mutate({org_name:m||null,site_title:c||null,site_tagline:u||null,org_logo_url:f||null,org_logo_dark_url:v||null,org_profile:b,brand_color:M,accent_color:D}),disabled:r.isPending,children:r.isPending?"Saving…":"Save changes"})]})]})}),e.jsx(Gt,{value:"story",className:"mt-6",children:e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsx(St,{children:"Your story"}),e.jsxs(kn,{children:["This is your ",t," speaking — not any individual agent. It fills the About page and the homepage numbers."]})]}),e.jsxs(Me,{className:"space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(J,{children:["About ",t==="team"?"the team":"the company"]}),e.jsx(Ms,{rows:7,value:b.about||"",onChange:ne=>S("about",ne.target.value),placeholder:"Who you are, how long you've served the area, and what clients can expect."})]}),e.jsx("div",{className:"grid gap-4 sm:grid-cols-2",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Founded"}),e.jsx(xe,{value:b.foundedYear||"",onChange:ne=>S("foundedYear",ne.target.value),placeholder:"1998"})]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Why agents join us"}),e.jsx(Ms,{rows:4,value:b.whyJoin||"",onChange:ne=>S("whyJoin",ne.target.value),placeholder:"Shown on your careers page and the homepage recruiting section."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(J,{children:"Homepage numbers"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Up to four. Leave empty and we'll show agent, listing and market counts automatically."}),P.map((ne,ce)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{value:ne.value,onChange:ie=>S("stats",P.map((te,ae)=>ae===ce?{...te,value:ie.target.value}:te)),placeholder:"$412M",className:"max-w-[140px]"}),e.jsx(xe,{value:ne.label,onChange:ie=>S("stats",P.map((te,ae)=>ae===ce?{...te,label:ie.target.value}:te)),placeholder:"Sold last year"}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>S("stats",P.filter((ie,te)=>te!==ce)),children:e.jsx(Sn,{className:"h-4 w-4"})})]},ce)),P.length<4&&e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>S("stats",[...P,{label:"",value:""}]),children:[e.jsx(rn,{className:"mr-2 h-4 w-4"})," Add a number"]})]}),e.jsx(B,{onClick:()=>r.mutate({org_profile:b}),disabled:r.isPending,children:r.isPending?"Saving…":"Save story"})]})]})}),e.jsx(Gt,{value:"offices",className:"mt-6",children:e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsx(St,{children:"Offices"}),e.jsx(kn,{children:"These appear on your contact page and in the footer. The first one is your main office."})]}),e.jsxs(Me,{className:"space-y-5",children:[C.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No offices yet — add your main office so visitors can reach you."}),C.map((ne,ce)=>e.jsxs("div",{className:"space-y-3 rounded-lg border p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("p",{className:"text-sm font-medium",children:ce===0?"Main office":`Office ${ce+1}`}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>S("offices",C.filter((ie,te)=>te!==ce)),children:e.jsx(Sn,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsx(xe,{value:ne.name||"",onChange:ie=>E(ce,{name:ie.target.value}),placeholder:"Office name"}),e.jsx(xe,{value:ne.phone||"",onChange:ie=>E(ce,{phone:ie.target.value}),placeholder:"Phone"}),e.jsx(xe,{value:ne.email||"",onChange:ie=>E(ce,{email:ie.target.value}),placeholder:"Email"}),e.jsx(xe,{value:ne.hours||"",onChange:ie=>E(ce,{hours:ie.target.value}),placeholder:"Mon–Fri 9–5"}),e.jsx(xe,{value:ne.address||"",onChange:ie=>E(ce,{address:ie.target.value}),placeholder:"Street address"}),e.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[e.jsx(xe,{value:ne.city||"",onChange:ie=>E(ce,{city:ie.target.value}),placeholder:"City"}),e.jsx(xe,{value:ne.state||"",onChange:ie=>E(ce,{state:ie.target.value}),placeholder:"ST"}),e.jsx(xe,{value:ne.zip||"",onChange:ie=>E(ce,{zip:ie.target.value}),placeholder:"ZIP"})]})]})]},ce)),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>S("offices",[...C,{}]),children:[e.jsx(rn,{className:"mr-2 h-4 w-4"})," Add an office"]}),e.jsx(B,{onClick:()=>r.mutate({org_profile:b}),disabled:r.isPending,children:r.isPending?"Saving…":"Save offices"})]})]})]})}),e.jsx(Gt,{value:"social",className:"mt-6",children:e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsx(St,{children:"Social profiles"}),e.jsxs(kn,{children:["Your ",t," accounts — linked in the footer and on the contact page."]})]}),e.jsxs(Me,{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(J,{children:"Facebook"}),e.jsx(xe,{value:b.facebookUrl||"",onChange:ne=>S("facebookUrl",ne.target.value),placeholder:"https://facebook.com/…"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Instagram"}),e.jsx(xe,{value:b.instagramUrl||"",onChange:ne=>S("instagramUrl",ne.target.value),placeholder:"https://instagram.com/…"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"LinkedIn"}),e.jsx(xe,{value:b.linkedinUrl||"",onChange:ne=>S("linkedinUrl",ne.target.value),placeholder:"https://linkedin.com/company/…"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"YouTube"}),e.jsx(xe,{value:b.youtubeUrl||"",onChange:ne=>S("youtubeUrl",ne.target.value),placeholder:"https://youtube.com/@…"})]})]}),e.jsx(B,{onClick:()=>r.mutate({org_profile:b}),disabled:r.isPending,children:r.isPending?"Saving…":"Save social links"})]})]})}),e.jsx(Gt,{value:"agents",className:"mt-6",children:e.jsxs(ve,{children:[e.jsxs(bt,{className:"flex-row items-start justify-between gap-4 space-y-0",children:[e.jsxs("div",{children:[e.jsx(St,{children:"Agent roster"}),e.jsx(kn,{children:"Everyone here gets a profile page on your site with their own listings."})]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>l.mutate(),disabled:l.isPending,children:[e.jsx(uo,{className:`mr-2 h-4 w-4 ${l.isPending?"animate-spin":""}`})," Refresh from LevelUp"]})]}),e.jsx(Me,{className:"space-y-3",children:i?e.jsx("p",{className:"py-8 text-center text-sm text-muted-foreground",children:"Loading roster…"}):a.length===0?e.jsx("p",{className:"py-8 text-center text-sm text-muted-foreground",children:"No agents yet — click “Refresh from LevelUp” to pull in your agents."}):a.map(ne=>{var ce,ie,te,ae;return e.jsxs("div",{className:"flex flex-wrap items-center gap-4 rounded-lg border p-4",children:[(ce=ne.profile)!=null&&ce.avatar_url?e.jsx("img",{src:ne.profile.avatar_url,alt:"",className:"h-11 w-11 rounded-full object-cover object-top"}):e.jsx("div",{className:"h-11 w-11 rounded-full bg-muted"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate font-medium",children:((ie=ne.profile)==null?void 0:ie.name)||"Unnamed agent"}),e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:ne.headline||((te=ne.profile)==null?void 0:te.title)||((ae=ne.profile)==null?void 0:ae.email)})]}),e.jsxs(B,{variant:ne.is_featured?"default":"outline",size:"sm",onClick:()=>o.mutate({id:ne.id,patch:{is_featured:!ne.is_featured}}),children:[e.jsx(Da,{className:"mr-2 h-4 w-4"})," ",ne.is_featured?"Featured":"Feature"]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>o.mutate({id:ne.id,patch:{is_visible:!ne.is_visible}}),children:[ne.is_visible?e.jsx(ya,{className:"mr-2 h-4 w-4"}):e.jsx(Ax,{className:"mr-2 h-4 w-4"}),ne.is_visible?"Shown":"Hidden"]})]},ne.id)})})]})}),e.jsx(Gt,{value:"domain",className:"mt-6",children:e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsx(St,{children:"Web address"}),e.jsx(kn,{children:"Use the free address or point your own domain at the site."})]}),e.jsxs(Me,{className:"space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Free address"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[s.subdomain_slug,".thelocalmove.com"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Your own domain"}),e.jsx(xe,{value:V,onChange:ne=>G(ne.target.value.trim().toLowerCase()),placeholder:"www.yourcompany.com"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Add the domain here, then point its DNS to LevelUp. Our team confirms it once the DNS is in place."})]}),e.jsx(B,{onClick:()=>r.mutate({custom_domain:V||null}),disabled:r.isPending,children:r.isPending?"Saving…":"Save address"})]})]})}),e.jsxs(Gt,{value:"plan",className:"mt-6 space-y-5",children:[e.jsxs("div",{className:"grid gap-5 md:grid-cols-2",children:[e.jsxs(ve,{className:s.org_tier==="essential"?"border-primary":"",children:[e.jsxs(bt,{children:[e.jsx(St,{children:"Essential"}),e.jsx(kn,{children:"Everything except live MLS search."})]}),e.jsxs(Me,{className:"space-y-2 text-sm text-muted-foreground",children:[e.jsx("p",{children:"• Company homepage, about and contact"}),e.jsx("p",{children:"• Full agent roster with individual profile pages"}),e.jsx("p",{children:"• Every agent's Listing Exchange listings"}),e.jsx("p",{children:"• Blog, city pages, SEO and lead capture"}),e.jsx("p",{children:"• Recruiting page tied to your pipeline"})]})]}),e.jsxs(ve,{className:s.org_tier==="pro"?"border-primary":"",children:[e.jsxs(bt,{children:[e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4"})," Pro"]}),e.jsx(kn,{children:"Everything in Essential, plus live MLS."})]}),e.jsxs(Me,{className:"space-y-2 text-sm text-muted-foreground",children:[e.jsx("p",{children:"• Full IDX property search"}),e.jsx("p",{children:"• Office listing feed and sold comps"}),e.jsx("p",{children:"• Saved searches and buyer alerts"}),e.jsx("p",{children:"• Market reports and CMA tools"}),e.jsx("p",{className:"pt-2 text-foreground",children:s.org_tier==="pro"?"Your site is on Pro.":"Ask your LevelUp rep to switch this site to Pro — nothing gets rebuilt."})]})]})]}),n&&e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsx(St,{className:"text-base",children:"Admin: plan control"}),e.jsx(kn,{children:"Switch this site between Essential and Pro."})]}),e.jsxs(Me,{className:"flex items-center gap-3",children:[e.jsx(B,{variant:s.org_tier==="essential"?"default":"outline",size:"sm",onClick:()=>r.mutate({org_tier:"essential"}),children:"Essential"}),e.jsx(B,{variant:s.org_tier==="pro"?"default":"outline",size:"sm",onClick:()=>r.mutate({org_tier:"pro"}),children:"Pro (IDX)"})]})]})]})]})]})}const F4t={agent:sl,brokerage:ai,team:In};function sas({current:s,className:t}){const n=Fn(),{websites:r}=Jrs();if(r.length<2)return null;const a=r.find(l=>l.kind===s.kind&&(!s.ownerId||l.ownerId===s.ownerId))||r.find(l=>l.kind===s.kind),i=F4t[(a==null?void 0:a.kind)||"agent"];return e.jsx("div",{className:t,children:e.jsxs(tu,{children:[e.jsx(su,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:"h-auto w-full justify-between gap-3 py-2.5 sm:w-auto sm:min-w-[320px]",children:[e.jsxs("span",{className:"flex min-w-0 items-center gap-3 text-left",children:[e.jsx(i,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block truncate text-sm font-medium",children:(a==null?void 0:a.name)||"Choose a website"}),e.jsx("span",{className:"block text-xs text-muted-foreground",children:a==null?void 0:a.kindLabel})]})]}),e.jsx(I_,{className:"h-4 w-4 shrink-0 text-muted-foreground"})]})}),e.jsxs(Od,{align:"start",className:"w-[320px]",children:[e.jsx(PP,{children:"Switch website"}),r.map(l=>{const o=F4t[l.kind],c=l===a;return e.jsxs(ca,{onSelect:()=>n(l.editPath),className:"gap-3 py-2.5",children:[e.jsx(o,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block truncate text-sm",children:l.name}),e.jsx("span",{className:"block text-xs text-muted-foreground",children:l.kindLabel})]}),l.exists?l.isActive?null:e.jsx(Oe,{variant:"secondary",className:"shrink-0 text-[10px]",children:"Preview"}):e.jsx(Oe,{variant:"outline",className:"shrink-0 text-[10px]",children:"Not created"}),c&&e.jsx(ea,{className:"h-4 w-4 shrink-0"})]},`${l.kind}-${l.ownerId||"me"}`)}),e.jsx(M0,{}),e.jsxs(ca,{onSelect:()=>n("/websites"),className:"gap-3",children:[e.jsx(sf,{className:"h-4 w-4 text-muted-foreground"})," See all my websites"]})]})]})})}function ear(){const s=Fn(),[t]=Yl(),{data:n=[],isLoading:r}=QMe(),a=_.useMemo(()=>n.filter(o=>o.role==="team_leader"),[n]),i=t.get("teamId"),l=a.find(o=>o.teamId===i)||a[0]||null;return _.useEffect(()=>{!r&&a.length===0&&s("/websites")},[r,a.length,s]),e.jsx(zs,{title:"Team Website",description:"Your team site — members, listings and leads",children:e.jsxs("div",{className:"mx-auto max-w-5xl space-y-6 p-4 lg:p-8",children:[e.jsx(sas,{current:{kind:"team",ownerId:l==null?void 0:l.teamId}}),r?e.jsx("div",{className:"h-40 animate-pulse rounded-xl bg-muted"}):l?e.jsx(sit,{teamId:l.teamId,orgLabel:"team"}):e.jsx(ve,{children:e.jsx(Me,{className:"p-8 text-center text-sm text-muted-foreground",children:"Only team leaders can build a team website."})})]})})}function tar(){const{user:s,isAdmin:t,isBrokerageManager:n,rolesLoading:r,brokerageId:a,managedBrokerages:i,selectedBrokerageId:l}=hs(),o=Fn(),c=_.useMemo(()=>{var d;return l||((d=i[0])==null?void 0:d.id)||a},[l,i,a]);return _.useEffect(()=>{r||!s||!t&&!n&&o("/dashboard")},[r,s,t,n,o]),e.jsx(zs,{title:"Company Website",description:"Your brokerage website — agents, listings, recruiting and leads",children:e.jsxs("div",{className:"mx-auto max-w-5xl space-y-6 p-4 lg:p-8",children:[e.jsx(sas,{current:{kind:"brokerage",ownerId:c}}),e.jsx(sit,{brokerageId:c,orgLabel:"brokerage"})]})})}const O4t={name:"",description:"",agent_split_pct:"70",team_split_pct:"",cap_amount:"",monthly_fee:"",transaction_fee:"",franchise_fee_pct:"",referral_fee_pct:"",commission_calc_method:"standard",is_active:!0};function sar({open:s,onOpenChange:t,plan:n,onSave:r,saving:a}){const[i,l]=_.useState(O4t);_.useEffect(()=>{var d,u;s&&l(n?{name:n.name,description:n.description||"",agent_split_pct:String(n.agent_split_pct),team_split_pct:n.team_split_pct?String(n.team_split_pct):"",cap_amount:((d=n.cap_amount)==null?void 0:d.toString())||"",monthly_fee:n.monthly_fee?String(n.monthly_fee):"",transaction_fee:n.transaction_fee?String(n.transaction_fee):"",franchise_fee_pct:n.franchise_fee_pct?String(n.franchise_fee_pct):"",referral_fee_pct:((u=n.referral_fee_pct)==null?void 0:u.toString())||"",commission_calc_method:n.commission_calc_method||"standard",is_active:n.is_active}:O4t)},[s,n]);const o=(d,u)=>l(h=>({...h,[d]:u})),c=()=>{r({id:n==null?void 0:n.id,name:i.name.trim(),description:i.description.trim()||null,agent_split_pct:parseFloat(i.agent_split_pct)||0,team_split_pct:i.team_split_pct?Math.min(100,Math.max(0,parseFloat(i.team_split_pct)||0)):0,cap_amount:i.cap_amount?parseFloat(i.cap_amount):null,monthly_fee:i.monthly_fee?parseFloat(i.monthly_fee):0,transaction_fee:i.transaction_fee?parseFloat(i.transaction_fee):0,franchise_fee_pct:i.franchise_fee_pct?parseFloat(i.franchise_fee_pct):0,referral_fee_pct:i.referral_fee_pct?parseFloat(i.referral_fee_pct):null,commission_calc_method:i.commission_calc_method,is_active:i.is_active})};return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"max-h-[90vh] overflow-y-auto sm:max-w-lg",children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:n?"Edit commission plan":"New commission plan"}),e.jsx(_r,{children:n?"Saving creates a new version — the previous terms stay on record.":'A named plan you can assign to agents, e.g. "70/30 with $16K cap".'})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{htmlFor:"plan-name",children:"Plan name"}),e.jsx(xe,{id:"plan-name",value:i.name,onChange:d=>o("name",d.target.value),placeholder:"70/30 split"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{htmlFor:"plan-desc",children:"Description (optional)"}),e.jsx(Ms,{id:"plan-desc",value:i.description,onChange:d=>o("description",d.target.value),rows:2})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{htmlFor:"plan-split",children:"Agent split %"}),e.jsx(xe,{id:"plan-split",type:"number",min:"0",max:"100",step:"0.5",value:i.agent_split_pct,onChange:d=>o("agent_split_pct",d.target.value)}),e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Brokerage keeps ",Math.max(0,100-(parseFloat(i.agent_split_pct)||0)),"%"]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{htmlFor:"plan-cap",children:"Annual cap ($)"}),e.jsx(xe,{id:"plan-cap",type:"number",min:"0",value:i.cap_amount,onChange:d=>o("cap_amount",d.target.value),placeholder:"No cap"}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Total brokerage takes before 100%"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{htmlFor:"plan-monthly",children:"Monthly desk fee ($)"}),e.jsx(xe,{id:"plan-monthly",type:"number",min:"0",value:i.monthly_fee,onChange:d=>o("monthly_fee",d.target.value),placeholder:"0"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{htmlFor:"plan-txn",children:"Per-transaction fee ($)"}),e.jsx(xe,{id:"plan-txn",type:"number",min:"0",value:i.transaction_fee,onChange:d=>o("transaction_fee",d.target.value),placeholder:"0"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{htmlFor:"plan-franchise",children:"Franchise fee %"}),e.jsx(xe,{id:"plan-franchise",type:"number",min:"0",step:"0.1",value:i.franchise_fee_pct,onChange:d=>o("franchise_fee_pct",d.target.value),placeholder:"0"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{htmlFor:"plan-referral",children:"Default referral fee %"}),e.jsx(xe,{id:"plan-referral",type:"number",min:"0",step:"0.1",value:i.referral_fee_pct,onChange:d=>o("referral_fee_pct",d.target.value),placeholder:"Optional"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{htmlFor:"plan-team",children:"Team split %"}),e.jsx(xe,{id:"plan-team",type:"number",min:"0",max:"100",step:"0.5",value:i.team_split_pct,onChange:d=>o("team_split_pct",d.target.value),placeholder:"0"}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Only applies to agents on a team"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Calculation method"}),e.jsxs(is,{value:i.commission_calc_method,onValueChange:d=>o("commission_calc_method",d),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"standard",children:"Standard — all fees off gross commission"}),e.jsx(He,{value:"referral_first",children:"Referral first — split applies after referral fee"})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Active"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Only active plans can be assigned to agents"})]}),e.jsx(fn,{checked:i.is_active,onCheckedChange:d=>o("is_active",d)})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(B,{onClick:c,disabled:a||!i.name.trim(),children:a?"Saving…":n?"Save new version":"Create plan"})]})]})})}const z4t=()=>new Date().toISOString().slice(0,10);function nar({open:s,onOpenChange:t,agent:n,plans:r,onAssign:a,saving:i}){const[l,o]=_.useState(""),[c,d]=_.useState(z4t()),[u,h]=_.useState(""),[m,p]=_.useState("");return _.useEffect(()=>{var f,y,v,g,b;s&&(o(((f=n==null?void 0:n.plan)==null?void 0:f.id)||((y=r[0])==null?void 0:y.id)||""),d(((v=n==null?void 0:n.assignment)==null?void 0:v.start_date)||z4t()),h(((g=n==null?void 0:n.assignment)==null?void 0:g.anniversary_date)||""),p(((b=n==null?void 0:n.assignment)==null?void 0:b.notes)||""))},[s,n,r]),e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"sm:max-w-md",children:[e.jsxs(Os,{children:[e.jsxs(Ds,{children:[n!=null&&n.assignment?"Change plan":"Assign plan"," — ",n==null?void 0:n.name]}),e.jsx(_r,{children:n!=null&&n.assignment?"The current plan ends on the new start date; cap tracking starts fresh.":"The plan pre-fills commission splits and fees on the agent’s new deals."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Commission plan"}),e.jsxs(is,{value:l,onValueChange:o,children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Choose a plan"})}),e.jsx(as,{children:r.map(f=>e.jsxs(He,{value:f.id,children:[f.name," — ",f.agent_split_pct,"/",Math.max(0,100-f.agent_split_pct),f.cap_amount?` · $${f.cap_amount.toLocaleString()} cap`:" · no cap"]},f.id))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{htmlFor:"ap-start",children:"Start date"}),e.jsx(xe,{id:"ap-start",type:"date",value:c,onChange:f=>d(f.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{htmlFor:"ap-anniv",children:"Anniversary date"}),e.jsx(xe,{id:"ap-anniv",type:"date",value:u,onChange:f=>h(f.target.value)}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Cap resets yearly on this date (defaults to start date)"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{htmlFor:"ap-notes",children:"Notes (optional)"}),e.jsx(Ms,{id:"ap-notes",rows:2,value:m,onChange:f=>p(f.target.value),placeholder:"e.g. Negotiated 80/20 for first year"})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(B,{disabled:i||!l||!c||!n,onClick:()=>n&&a({agent_user_id:n.agentId,plan_id:l,start_date:c,anniversary_date:u||null,notes:m.trim()||null}),children:i?"Saving…":"Save assignment"})]})]})})}const nDe=q,ZCe={monthly_fee:"Monthly desk fee",transaction_fee:"Transaction fee",adjustment:"Adjustment",payment:"Payment received"};function rar(s){return at({queryKey:["fee-ledger",s],enabled:!!s,queryFn:async()=>{const t=[];for(let r=0;;r+=1e3){const{data:a,error:i}=await nDe.from("agent_fee_ledger").select("*").eq("brokerage_id",s).order("entry_date",{ascending:!1}).range(r,r+1e3-1);if(i)throw i;if(t.push(...a||[]),!a||a.length<1e3)break}return t}})}function aar(s){const t=Bt(),{user:n}=hs();return mt({mutationFn:async r=>{const{error:a}=await nDe.from("agent_fee_ledger").insert({agent_user_id:r.agent_user_id,brokerage_id:s,entry_type:r.entry_type,amount:r.amount,entry_date:r.entry_date,note:r.note||null,created_by:(n==null?void 0:n.id)??null});if(a)throw a},onSuccess:()=>{t.invalidateQueries({queryKey:["fee-ledger",s]}),se.success("Ledger entry added")},onError:r=>se.error(r.message||"Could not add entry")})}function iar(s){const t=Bt();return mt({mutationFn:async n=>{const{error:r}=await nDe.from("agent_fee_ledger").delete().eq("id",n);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["fee-ledger",s]}),se.success("Entry removed")},onError:n=>se.error(n.message||"Could not remove entry")})}function oar(s){const t=Bt(),{user:n}=hs();return mt({mutationFn:async r=>{const a=`${r.month}-01`,i=new Set(r.existing.filter(c=>c.entry_type==="monthly_fee"&&(c.entry_date||"").slice(0,7)===r.month).map(c=>c.agent_user_id)),l=r.agents.filter(c=>c.monthlyFee>0&&!i.has(c.agentId)).map(c=>({agent_user_id:c.agentId,brokerage_id:s,entry_type:"monthly_fee",amount:c.monthlyFee,entry_date:a,note:`Desk fee ${r.month}`,created_by:(n==null?void 0:n.id)??null}));if(!l.length)return 0;const{error:o}=await nDe.from("agent_fee_ledger").insert(l);if(o)throw o;return l.length},onSuccess:r=>{t.invalidateQueries({queryKey:["fee-ledger",s]}),se.success(r?`Posted ${r} desk fee${r===1?"":"s"}`:"All desk fees already posted")},onError:r=>se.error(r.message||"Could not post desk fees")})}const lar=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function nas(s,t){return s.filter(n=>{const r=WS(n.actual_close_date);return!!r&&r.y===t})}function ras(s,t,n,r=[]){const a=nas(s,n),i=Array.from({length:12},(c,d)=>({key:`${n}-${String(d+1).padStart(2,"0")}`,label:lar[d],companyDollar:0,gci:0,deals:0})),l=new Map;r.forEach(c=>l.set(c.agentId,{userId:c.agentId,name:c.name,avatarUrl:c.avatarUrl,closedDeals:0,volume:0,gci:0,companyDollar:0,agentShare:0,feesCharged:0,feesPaid:0,balance:0}));const o={year:n,closedDeals:a.length,volume:0,gci:0,companyDollar:0,agentShare:0,feesOutstanding:0,months:i,agents:[]};return a.forEach(c=>{const d=RG(c),u=FG(c),h=zse(c),m=Math.max(0,u-h);o.volume+=d,o.gci+=u,o.companyDollar+=h,o.agentShare+=m;const p=WS(c.actual_close_date);if(p){const y=i[p.m-1];y&&(y.companyDollar+=h,y.gci+=u,y.deals+=1)}const f=l.get(c.owner_user_id)||{userId:c.owner_user_id,name:c.agent_name||"Agent",avatarUrl:c.agent_avatar_url,closedDeals:0,volume:0,gci:0,companyDollar:0,agentShare:0,feesCharged:0,feesPaid:0,balance:0};f.closedDeals+=1,f.volume+=d,f.gci+=u,f.companyDollar+=h,f.agentShare+=m,l.set(c.owner_user_id,f)}),t.forEach(c=>{const d=Number(c.amount)||0,u=l.get(c.agent_user_id);u&&(c.entry_type==="payment"?u.feesPaid+=Math.abs(d):u.feesCharged+=d)}),l.forEach(c=>{c.balance=c.feesCharged-c.feesPaid,o.feesOutstanding+=c.balance}),o.agents=Array.from(l.values()).filter(c=>c.closedDeals>0||c.feesCharged>0||c.feesPaid>0).sort((c,d)=>d.companyDollar-c.companyDollar||d.volume-c.volume),o}const car=[64,110,113],LBe=[42,76,100],LT=[110,118,125],Nw=s=>`$${Math.round(s).toLocaleString("en-US")}`,B4t=s=>{const t=WS(s);return t?`${String(t.m).padStart(2,"0")}/${String(t.d).padStart(2,"0")}/${String(t.y).slice(2)}`:"—"},U4t=(s,t,n)=>{let r=t||"";for(;r.length>3&&s.getTextWidth(r)>n;)r=r.slice(0,-1);return r===t?r:`${r.trim()}…`};function dar(s){const t=new Mo({unit:"pt",format:"letter"}),n=t.internal.pageSize.getWidth(),r=t.internal.pageSize.getHeight(),a=48;let i=0;t.setFillColor(...LBe),t.rect(0,0,n,92,"F"),t.setTextColor(255,255,255),t.setFont("helvetica","bold"),t.setFontSize(18),t.text(s.brokerageName||"Brokerage",a,40),t.setFont("helvetica","normal"),t.setFontSize(11),t.text(`Agent commission statement · ${s.year}`,a,60),t.setFontSize(9),t.text(`Generated ${new Date().toLocaleDateString("en-US")}`,n-a,60,{align:"right"}),i=122,t.setTextColor(0,0,0),t.setFont("helvetica","bold"),t.setFontSize(14),t.text(s.agentName,a,i),t.setFont("helvetica","normal"),t.setFontSize(9),t.setTextColor(...LT);const l=[s.agentEmail,s.planName?`Plan: ${s.planName}`:null,s.planSummary].filter(Boolean).join(" · ");l&&t.text(l,a,i+14),i+=40;const o=s.deals.reduce((g,b)=>{const j=FG(b),S=zse(b);return g.volume+=RG(b),g.gci+=j,g.company+=S,g.agent+=Math.max(0,j-S),g},{volume:0,gci:0,company:0,agent:0}),c=s.ledger.filter(g=>g.entry_type!=="payment").reduce((g,b)=>g+(Number(b.amount)||0),0),d=s.ledger.filter(g=>g.entry_type==="payment").reduce((g,b)=>g+Math.abs(Number(b.amount)||0),0),u=c-d,h=[{label:"Closed sides",value:String(s.deals.length)},{label:"Volume",value:Nw(o.volume)},{label:"Gross commission",value:Nw(o.gci)},{label:"Agent share",value:Nw(o.agent)}],m=(n-a*2-18)/4;if(h.forEach((g,b)=>{const j=a+b*(m+6);t.setDrawColor(224,228,232),t.setFillColor(248,250,250),t.roundedRect(j,i,m,48,6,6,"FD"),t.setFontSize(8),t.setTextColor(...LT),t.text(g.label,j+10,i+17),t.setFontSize(13),t.setFont("helvetica","bold"),t.setTextColor(...LBe),t.text(g.value,j+10,i+36),t.setFont("helvetica","normal")}),i+=72,s.capAmount){const g=Math.min(100,(s.capProgress||0)/s.capAmount*100);t.setFontSize(9),t.setTextColor(...LT),t.text(`Cap progress: ${Nw(s.capProgress||0)} of ${Nw(s.capAmount)} (${Math.round(g)}%)`,a,i);const b=n-a*2;t.setFillColor(232,236,238),t.roundedRect(a,i+6,b,7,3.5,3.5,"F"),t.setFillColor(...car),t.roundedRect(a,i+6,Math.max(2,b*g/100),7,3.5,3.5,"F"),i+=34}const p=g=>{i>r-120&&(t.addPage(),i=60),t.setFont("helvetica","bold"),t.setFontSize(11),t.setTextColor(...LBe),t.text(g,a,i),t.setFont("helvetica","normal"),i+=14},f=()=>{t.setDrawColor(234,238,240),t.line(a,i,n-a,i)};p("Closed transactions");const y=[a,a+62,a+280,a+360,a+440];t.setFontSize(8),t.setTextColor(...LT),t.text("Closed",y[0],i),t.text("Property",y[1],i),t.text("Volume",y[2],i,{align:"right"}),t.text("GCI",y[3],i,{align:"right"}),t.text("Agent share",n-a,i,{align:"right"}),i+=5,f(),i+=13,t.setTextColor(30,34,38),t.setFontSize(9),s.deals.length||(t.setTextColor(...LT),t.text("No closed transactions in this period.",a,i),i+=18,t.setTextColor(30,34,38)),s.deals.slice().sort((g,b)=>(g.actual_close_date||"").localeCompare(b.actual_close_date||"")).forEach(g=>{i>r-90&&(t.addPage(),i=60);const b=FG(g),j=Math.max(0,b-zse(g));t.text(B4t(g.actual_close_date),y[0],i),t.text(U4t(t,g.property_address||g.deal_name||"Transaction",205),y[1],i),t.text(Nw(RG(g)),y[2],i,{align:"right"}),t.text(Nw(b),y[3],i,{align:"right"}),t.text(Nw(j),n-a,i,{align:"right"}),i+=16}),i+=4,f(),i+=15,t.setFont("helvetica","bold"),t.text("Totals",y[1],i),t.text(Nw(o.volume),y[2],i,{align:"right"}),t.text(Nw(o.gci),y[3],i,{align:"right"}),t.text(Nw(o.agent),n-a,i,{align:"right"}),t.setFont("helvetica","normal"),i+=34,p("Fees & payments"),t.setFontSize(8),t.setTextColor(...LT),t.text("Date",y[0],i),t.text("Item",y[1],i),t.text("Amount",n-a,i,{align:"right"}),i+=5,f(),i+=13,t.setFontSize(9),t.setTextColor(30,34,38),s.ledger.length||(t.setTextColor(...LT),t.text("No fees or payments recorded.",a,i),i+=18,t.setTextColor(30,34,38)),s.ledger.slice().sort((g,b)=>(g.entry_date||"").localeCompare(b.entry_date||"")).forEach(g=>{i>r-90&&(t.addPage(),i=60);const b=Number(g.amount)||0,j=g.entry_type==="payment",S=ZCe[g.entry_type]||g.entry_type;t.text(B4t(g.entry_date),y[0],i),t.text(U4t(t,g.note?`${S} — ${g.note}`:S,330),y[1],i),t.text(`${j?"-":""}${Nw(Math.abs(b))}`,n-a,i,{align:"right"}),i+=16}),i+=4,f(),i+=15,t.setFont("helvetica","bold"),t.text("Balance due to brokerage",y[1],i),t.text(Nw(u),n-a,i,{align:"right"});const v=t.getNumberOfPages();for(let g=1;g<=v;g++)t.setPage(g),t.setFont("helvetica","normal"),t.setFontSize(8),t.setTextColor(...LT),t.text("Estimated figures based on recorded transactions and plan terms. Not an accounting document.",a,r-28),t.text(`Page ${g} of ${v}`,n-a,r-28,{align:"right"});return t}function uar(s){const t=dar(s),n=s.agentName.replace(/[^a-z0-9]+/gi,"-").toLowerCase();t.save(`statement-${n}-${s.year}.pdf`)}const q4t=s=>`$${Math.round(s).toLocaleString()}`;function har({deals:s,ledger:t,roster:n,brokerageName:r,loading:a}){const i=new Date().getFullYear(),[l,o]=_.useState(String(i)),c=_.useMemo(()=>{const m=new Set([i]);return s.forEach(p=>{const f=WS(p.actual_close_date);f&&m.add(f.y)}),Array.from(m).sort((p,f)=>f-p)},[s,i]),d=_.useMemo(()=>ras(s,t,Number(l),n.map(m=>({agentId:m.agentId,name:m.name,avatarUrl:m.avatarUrl}))),[s,t,n,l]),u=Math.max(1,...d.months.map(m=>m.companyDollar)),h=m=>{var v,g,b;const p=n.find(j=>j.agentId===m),f=d.agents.find(j=>j.userId===m),y=nas(s,Number(l)).filter(j=>j.owner_user_id===m);uar({brokerageName:r,agentName:(p==null?void 0:p.name)||(f==null?void 0:f.name)||"Agent",agentEmail:(p==null?void 0:p.email)||null,planName:((v=p==null?void 0:p.plan)==null?void 0:v.name)||null,planSummary:p!=null&&p.plan?`${p.plan.agent_split_pct}/${Math.max(0,100-p.plan.agent_split_pct)} split`:null,year:Number(l),deals:y,ledger:t.filter(j=>j.agent_user_id===m&&(j.entry_date||"").slice(0,4)===l),capAmount:((g=p==null?void 0:p.plan)==null?void 0:g.cap_amount)??null,capProgress:((b=p==null?void 0:p.progress)==null?void 0:b.cap_progress)??null})};return a?e.jsxs("div",{className:"space-y-3",children:[e.jsx(cn,{className:"h-24 w-full rounded-xl"}),e.jsx(cn,{className:"h-64 w-full rounded-xl"})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Closed business and company dollar earned, by month and by agent."}),e.jsxs(is,{value:l,onValueChange:o,children:[e.jsx(rs,{className:"w-32",children:e.jsx(ls,{})}),e.jsx(as,{children:c.map(m=>e.jsx(He,{value:String(m),children:m},m))})]})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3 lg:grid-cols-4",children:[{label:"Closed sides",value:String(d.closedDeals)},{label:"Closed volume",value:Xm(d.volume)},{label:"Gross commission",value:Xm(d.gci)},{label:"Company dollar",value:Xm(d.companyDollar),accent:!0}].map(m=>e.jsx(ve,{className:"border-border/60",children:e.jsxs(Me,{className:"p-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:m.label}),e.jsx("p",{className:`text-2xl font-bold tabular-nums tracking-tight ${m.accent?"text-teal-600":""}`,children:m.value})]})},m.label))}),e.jsxs(ve,{className:"border-border/60",children:[e.jsxs(bt,{className:"pb-2",children:[e.jsxs(St,{className:"flex items-center gap-2 text-base",children:[e.jsx(Nl,{className:"h-4 w-4 text-teal-600"})," Company dollar by month"]}),e.jsx(kn,{children:"Brokerage split, franchise fees and transaction fees on closed deals"})]}),e.jsx(Me,{children:e.jsx("div",{className:"flex h-40 items-end gap-1.5",children:d.months.map(m=>e.jsxs("div",{className:"group flex flex-1 flex-col items-center gap-1",children:[e.jsx("span",{className:"text-[10px] font-medium tabular-nums text-muted-foreground opacity-0 transition group-hover:opacity-100",children:Xm(m.companyDollar)}),e.jsx("div",{className:"w-full rounded-t bg-teal-500/80 transition group-hover:bg-teal-600",style:{height:`${Math.max(2,m.companyDollar/u*110)}px`},title:`${m.label}: ${q4t(m.companyDollar)} from ${m.deals} closed`}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:m.label})]},m.key))})})]}),e.jsxs(ve,{className:"border-border/60",children:[e.jsxs(bt,{className:"pb-2",children:[e.jsx(St,{className:"text-base",children:"Agent production & statements"}),e.jsx(kn,{children:"Download a per-agent statement with closed deals, fees and balance"})]}),e.jsx(Me,{className:"pt-1",children:d.agents.length===0?e.jsx("p",{className:"py-8 text-center text-sm text-muted-foreground",children:"No closed deals recorded yet."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full min-w-[640px] text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b text-[11px] uppercase tracking-wide text-muted-foreground",children:[e.jsx("th",{className:"py-2 text-left font-medium",children:"Agent"}),e.jsx("th",{className:"py-2 text-right font-medium",children:"Closed"}),e.jsx("th",{className:"py-2 text-right font-medium",children:"Volume"}),e.jsx("th",{className:"py-2 text-right font-medium",children:"GCI"}),e.jsx("th",{className:"py-2 text-right font-medium",children:"Company $"}),e.jsx("th",{className:"py-2 text-right font-medium",children:"Balance"}),e.jsx("th",{className:"py-2"})]})}),e.jsx("tbody",{children:d.agents.map(m=>e.jsxs("tr",{className:"border-b last:border-0 hover:bg-muted/40",children:[e.jsx("td",{className:"py-2.5",children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsxs(ja,{className:"h-7 w-7",children:[e.jsx(pi,{src:m.avatarUrl||void 0,alt:m.name}),e.jsx(Na,{className:"text-[10px]",children:m.name.slice(0,2).toUpperCase()})]}),e.jsx("span",{className:"truncate font-medium",children:m.name})]})}),e.jsx("td",{className:"py-2.5 text-right tabular-nums",children:m.closedDeals}),e.jsx("td",{className:"py-2.5 text-right tabular-nums",children:Xm(m.volume)}),e.jsx("td",{className:"py-2.5 text-right tabular-nums",children:Xm(m.gci)}),e.jsx("td",{className:"py-2.5 text-right font-medium tabular-nums text-teal-700",children:Xm(m.companyDollar)}),e.jsx("td",{className:"py-2.5 text-right tabular-nums",children:m.balance>0?e.jsx(Oe,{variant:"outline",className:"border-amber-300 text-amber-700",children:q4t(m.balance)}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx("td",{className:"py-2.5 text-right",children:e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>h(m.userId),children:[e.jsx(hj,{className:"mr-1.5 h-4 w-4"})," Statement"]})})]},m.userId))})]})})})]})]})}const $4t=s=>`$${Math.round(s).toLocaleString()}`,mar=()=>new Date().toISOString().slice(0,10),par=()=>new Date().toISOString().slice(0,7);function far({brokerageId:s,ledger:t,roster:n,loading:r}){const a=aar(s),i=iar(s),l=oar(s),[o,c]=_.useState(!1),[d,u]=_.useState(""),[h,m]=_.useState("adjustment"),[p,f]=_.useState(""),[y,v]=_.useState(mar()),[g,b]=_.useState(""),[j,S]=_.useState(par()),[C,E]=_.useState("all"),P=$=>{var H;return((H=n.find(Y=>Y.agentId===$))==null?void 0:H.name)||"Agent"},M=_.useMemo(()=>{const $=new Map;return t.forEach(H=>{const Y=Number(H.amount)||0,Z=H.entry_type==="payment"?-Math.abs(Y):Y;$.set(H.agent_user_id,($.get(H.agent_user_id)||0)+Z)}),$},[t]),I=_.useMemo(()=>Array.from(M.values()).reduce(($,H)=>$+Math.max(0,H),0),[M]),D=_.useMemo(()=>t.filter($=>$.entry_type==="payment").reduce(($,H)=>$+Math.abs(Number(H.amount)||0),0),[t]),O=_.useMemo(()=>C==="all"?t:t.filter($=>$.agent_user_id===C),[t,C]),V=n.filter($=>$.plan&&($.plan.monthly_fee||0)>0).map($=>({agentId:$.agentId,name:$.name,monthlyFee:$.plan.monthly_fee})),G=()=>{const $=parseFloat(p);!d||!Number.isFinite($)||$<=0||a.mutate({agent_user_id:d,entry_type:h,amount:$,entry_date:y,note:g},{onSuccess:()=>{c(!1),f(""),b("")}})};return r?e.jsx(cn,{className:"h-64 w-full rounded-xl"}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-3",children:[e.jsx(ve,{className:"border-border/60",children:e.jsxs(Me,{className:"p-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Outstanding fees"}),e.jsx("p",{className:"text-2xl font-bold tabular-nums text-amber-600",children:Xm(I)})]})}),e.jsx(ve,{className:"border-border/60",children:e.jsxs(Me,{className:"p-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Payments recorded"}),e.jsx("p",{className:"text-2xl font-bold tabular-nums text-emerald-600",children:Xm(D)})]})}),e.jsx(ve,{className:"border-border/60",children:e.jsxs(Me,{className:"p-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Agents with a desk fee"}),e.jsx("p",{className:"text-2xl font-bold tabular-nums",children:V.length})]})})]}),e.jsxs(ve,{className:"border-border/60",children:[e.jsx(bt,{className:"pb-3",children:e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx(St,{className:"text-base",children:"Fee ledger"}),e.jsx(kn,{children:"Desk fees, transaction fees, adjustments and payments received"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(xe,{type:"month",value:j,onChange:$=>S($.target.value),className:"h-9 w-[150px]"}),e.jsxs(B,{variant:"outline",size:"sm",disabled:l.isPending||V.length===0,onClick:()=>l.mutate({month:j,agents:V,existing:t}),children:[e.jsx(gy,{className:"mr-1.5 h-4 w-4"})," Post desk fees"]}),e.jsxs(B,{size:"sm",onClick:()=>c(!0),children:[e.jsx(rn,{className:"mr-1.5 h-4 w-4"})," Add entry"]})]})]})}),e.jsxs(Me,{className:"space-y-3",children:[e.jsxs(is,{value:C,onValueChange:E,children:[e.jsx(rs,{className:"h-9 w-full sm:w-64",children:e.jsx(ls,{placeholder:"All agents"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All agents"}),n.map($=>e.jsxs(He,{value:$.agentId,children:[$.name,M.get($.agentId)?` · ${$4t(M.get($.agentId))}`:""]},$.agentId))]})]}),O.length===0?e.jsx("p",{className:"py-10 text-center text-sm text-muted-foreground",children:"No ledger entries yet. Post this month's desk fees or add an entry."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full min-w-[620px] text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b text-[11px] uppercase tracking-wide text-muted-foreground",children:[e.jsx("th",{className:"py-2 text-left font-medium",children:"Date"}),e.jsx("th",{className:"py-2 text-left font-medium",children:"Agent"}),e.jsx("th",{className:"py-2 text-left font-medium",children:"Item"}),e.jsx("th",{className:"py-2 text-right font-medium",children:"Amount"}),e.jsx("th",{className:"py-2"})]})}),e.jsx("tbody",{children:O.map($=>e.jsxs("tr",{className:"border-b last:border-0 hover:bg-muted/40",children:[e.jsx("td",{className:"py-2.5 tabular-nums text-muted-foreground",children:$.entry_date}),e.jsx("td",{className:"py-2.5 font-medium",children:P($.agent_user_id)}),e.jsx("td",{className:"py-2.5",children:e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsx(Oe,{variant:$.entry_type==="payment"?"secondary":"outline",children:ZCe[$.entry_type]||$.entry_type}),$.note&&e.jsx("span",{className:"text-xs text-muted-foreground",children:$.note})]})}),e.jsxs("td",{className:`py-2.5 text-right font-medium tabular-nums ${$.entry_type==="payment"?"text-emerald-600":""}`,children:[$.entry_type==="payment"?"-":"",$4t(Math.abs(Number($.amount)||0))]}),e.jsx("td",{className:"py-2.5 text-right",children:e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground",onClick:()=>i.mutate($.id),children:e.jsx(Sn,{className:"h-4 w-4"})})})]},$.id))})]})})]})]}),e.jsx(Ls,{open:o,onOpenChange:c,children:e.jsxs(Ps,{className:"sm:max-w-md",children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Add ledger entry"}),e.jsx(_r,{children:"Record a fee charged to an agent, or a payment they made."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Agent"}),e.jsxs(is,{value:d,onValueChange:u,children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Choose an agent"})}),e.jsx(as,{children:n.map($=>e.jsx(He,{value:$.agentId,children:$.name},$.agentId))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Type"}),e.jsxs(is,{value:h,onValueChange:$=>m($),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsx(as,{children:Object.keys(ZCe).map($=>e.jsx(He,{value:$,children:ZCe[$]},$))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Amount"}),e.jsx(xe,{type:"number",min:"0",step:"0.01",value:p,onChange:$=>f($.target.value),placeholder:"0.00"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Date"}),e.jsx(xe,{type:"date",value:y,onChange:$=>v($.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Note (optional)"}),e.jsx(Ms,{rows:2,value:g,onChange:$=>b($.target.value)})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx(B,{onClick:G,disabled:a.isPending||!d||!p,children:"Add entry"})]})]})})]})}const xar={license:FQ,eo:Dm,anniversary:Ex,birthday:Bf},gar=[30,60,90,180];function yar({records:s,roster:t,deals:n,loading:r}){const[a,i]=_.useState(90),l=_.useMemo(()=>t.map(v=>({agentId:v.agentId,name:v.name,avatarUrl:v.avatarUrl})),[t]),o=_.useMemo(()=>Qrs(s,l,a),[s,l,a]),c=o.filter(v=>v.expired),d=o.filter(v=>!v.expired&&(v.kind==="license"||v.kind==="eo")),u=o.filter(v=>v.kind==="anniversary"||v.kind==="birthday"),h=_.useMemo(()=>{const v=new Map(s.map(g=>[g.agent_user_id,g]));return t.filter(g=>{const b=v.get(g.agentId);return!(b!=null&&b.license_expiration)||!(b!=null&&b.eo_expiration)})},[s,t]),m=new Date().getFullYear(),p=_.useMemo(()=>ras(n,[],m,l).agents,[n,l,m]),f=_.useMemo(()=>Crr(s,l,p),[s,l,p]);if(r)return e.jsx("div",{className:"space-y-3",children:Array.from({length:3}).map((v,g)=>e.jsx(cn,{className:"h-32 w-full rounded-xl"},g))});const y=(v,g)=>{const b=xar[v.kind];return e.jsxs("div",{className:"flex items-center gap-3 rounded-lg px-2 py-2.5 hover:bg-muted/50",children:[e.jsxs(ja,{className:"h-8 w-8 shrink-0",children:[e.jsx(pi,{src:v.avatarUrl||void 0,alt:v.agentName}),e.jsx(Na,{className:"text-[10px]",children:v.agentName.slice(0,2).toUpperCase()})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:v.agentName}),e.jsxs("p",{className:"flex items-center gap-1.5 truncate text-[11px] text-muted-foreground",children:[e.jsx(b,{className:"h-3 w-3"}),Srr[v.kind],v.detail?` · ${v.detail}`:""]})]}),e.jsxs("div",{className:"shrink-0 text-right",children:[e.jsx("p",{className:"text-xs font-medium tabular-nums",children:tit(v.dueDate)}),v.expired?e.jsxs(Oe,{variant:"destructive",className:"mt-0.5 h-5 text-[10px]",children:[Math.abs(v.daysUntil)," days overdue"]}):e.jsx("p",{className:`text-[11px] ${v.daysUntil<=30?"font-medium text-amber-600":"text-muted-foreground"}`,children:v.daysUntil===0?"Today":`in ${v.daysUntil} days`})]})]},`${v.agentId}-${v.kind}-${g}`)};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-3",children:[e.jsx(ve,{className:"border-border/60",children:e.jsxs(Me,{className:"flex items-center gap-3 p-4",children:[e.jsx("span",{className:"flex h-9 w-9 items-center justify-center rounded-lg bg-red-500/10 text-red-600",children:e.jsx(xl,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Expired"}),e.jsx("p",{className:"text-2xl font-bold tabular-nums tracking-tight",children:c.length})]})]})}),e.jsx(ve,{className:"border-border/60",children:e.jsxs(Me,{className:"flex items-center gap-3 p-4",children:[e.jsx("span",{className:"flex h-9 w-9 items-center justify-center rounded-lg bg-amber-500/10 text-amber-600",children:e.jsx(Qd,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Due in ",a," days"]}),e.jsx("p",{className:"text-2xl font-bold tabular-nums tracking-tight",children:d.length})]})]})}),e.jsx(ve,{className:"border-border/60",children:e.jsxs(Me,{className:"flex items-center gap-3 p-4",children:[e.jsx("span",{className:"flex h-9 w-9 items-center justify-center rounded-lg bg-slate-500/10 text-slate-600",children:e.jsx(Dm,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Missing license or E&O date"}),e.jsx("p",{className:"text-2xl font-bold tabular-nums tracking-tight",children:h.length})]})]})})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsx("span",{className:"mr-1 text-xs text-muted-foreground",children:"Look ahead:"}),gar.map(v=>e.jsxs(B,{size:"sm",variant:a===v?"default":"outline",onClick:()=>i(v),children:[v," days"]},v))]}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsxs(ve,{className:"border-border/60",children:[e.jsxs(bt,{className:"pb-2",children:[e.jsx(St,{className:"text-base",children:"License & E&O renewals"}),e.jsx(kn,{children:"Expired items first, then everything due inside your window"})]}),e.jsx(Me,{className:"space-y-0.5 pt-2",children:c.length===0&&d.length===0?e.jsxs("p",{className:"py-8 text-center text-sm text-muted-foreground",children:["Nothing expiring in the next ",a," days."]}):[...c,...d].map(y)})]}),e.jsxs(ve,{className:"border-border/60",children:[e.jsxs(bt,{className:"pb-2",children:[e.jsx(St,{className:"text-base",children:"Anniversaries & birthdays"}),e.jsx(kn,{children:"Reach out before the day — retention lives here"})]}),e.jsx(Me,{className:"space-y-0.5 pt-2",children:u.length===0?e.jsxs("p",{className:"py-8 text-center text-sm text-muted-foreground",children:["No milestones in the next ",a," days."]}):u.map(y)})]})]}),e.jsxs(ve,{className:"border-border/60",children:[e.jsxs(bt,{className:"pb-2",children:[e.jsxs(St,{className:"flex items-center gap-2 text-base",children:[e.jsx(ku,{className:"h-4 w-4 text-teal-600"})," Production goals — ",m]}),e.jsx(kn,{children:"Goal amounts come from each agent's record; progress uses closed volume this year"})]}),e.jsx(Me,{className:"space-y-2 pt-2",children:f.length===0?e.jsx("p",{className:"py-8 text-center text-sm text-muted-foreground",children:"No production goals set yet — add one on an agent's record in Onboarding."}):f.map(v=>e.jsxs("div",{className:"rounded-lg px-2 py-2.5 hover:bg-muted/50",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(ja,{className:"h-8 w-8 shrink-0",children:[e.jsx(pi,{src:v.avatarUrl||void 0,alt:v.name}),e.jsx(Na,{className:"text-[10px]",children:v.name.slice(0,2).toUpperCase()})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:v.name}),e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:[Xm(v.volume)," of ",Xm(v.goal)," · ",v.closedDeals," closed"]})]}),e.jsxs("span",{className:"shrink-0 text-sm font-semibold tabular-nums",children:[Math.round(v.pct),"%"]})]}),e.jsx(Fi,{value:Math.min(100,v.pct),className:"mt-2 h-1.5"})]},v.agentId))})]})]})}const Ude=s=>`${s<0?"-":""}$${Math.abs(Math.round(s)).toLocaleString()}`;function bar({open:s,onOpenChange:t,draft:n,roster:r,onSave:a,saving:i}){const[l,o]=_.useState(n);_.useEffect(()=>o(n),[n]);const c=_.useMemo(()=>OG(l||{}),[l]);if(!l)return null;const d=m=>o({...l,...m}),u=(m,p,f)=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs",children:p}),e.jsxs("div",{className:"relative",children:[e.jsx(xe,{type:"number",value:l[m]??0,onChange:y=>d({[m]:parseFloat(y.target.value)||0})}),f&&e.jsx("span",{className:"pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 text-xs text-muted-foreground",children:f})]})]}),h=(m,p)=>{const f=[...l.line_items||[]];f[m]={...f[m],...p},d({line_items:f})};return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"max-h-[90vh] max-w-3xl overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:l.id?"Edit disbursement":"New disbursement"}),e.jsx(_r,{children:"Set the closing details and how the commission is split. The CDA is generated from these numbers."})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs",children:"Agent"}),e.jsxs(is,{value:l.agent_user_id,onValueChange:m=>d({agent_user_id:m}),children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Choose an agent"})}),e.jsx(as,{children:r.map(m=>e.jsx(He,{value:m.agentId,children:m.name},m.agentId))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs",children:"Closing date"}),e.jsx(xe,{type:"date",value:l.closing_date||"",onChange:m=>d({closing_date:m.target.value||null})})]}),e.jsxs("div",{className:"space-y-1.5 sm:col-span-2",children:[e.jsx(J,{className:"text-xs",children:"Property"}),e.jsx(xe,{value:l.property_address||"",onChange:m=>d({property_address:m.target.value}),placeholder:"123 Main St, Nashville TN"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs",children:"Escrow / title company"}),e.jsx(xe,{value:l.escrow_company||"",onChange:m=>d({escrow_company:m.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs",children:"Escrow / file number"}),e.jsx(xe,{value:l.escrow_number||"",onChange:m=>d({escrow_number:m.target.value})})]}),u("sale_price","Sale price","$"),u("gross_commission","Gross commission","$"),u("agent_split_pct","Agent split","%"),u("franchise_fee_pct","Franchise fee","%"),u("transaction_fee","Transaction fee","$"),u("referral_fee_pct","Referral fee","%"),u("referral_amount","Referral flat amount","$"),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs",children:"Referral paid to"}),e.jsx(xe,{value:l.referral_payee||"",onChange:m=>d({referral_payee:m.target.value})})]})]}),e.jsxs("div",{className:"space-y-2 rounded-lg border border-border/60 p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-sm font-medium",children:"Other charges & credits"}),e.jsxs(B,{type:"button",size:"sm",variant:"outline",onClick:()=>d({line_items:[...l.line_items||[],{label:"",amount:0}]}),children:[e.jsx(rn,{className:"mr-1 h-3.5 w-3.5"})," Add line"]})]}),(l.line_items||[]).length===0&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Positive amounts are deducted from the agent; use a negative amount for a credit."}),(l.line_items||[]).map((m,p)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xe,{className:"flex-1",value:m.label,placeholder:"E&O fee, sign rental, admin fee…",onChange:f=>h(p,{label:f.target.value})}),e.jsx(xe,{className:"w-32",type:"number",value:m.amount,onChange:f=>h(p,{amount:parseFloat(f.target.value)||0})}),e.jsx(B,{type:"button",size:"icon",variant:"ghost",onClick:()=>d({line_items:(l.line_items||[]).filter((f,y)=>y!==p)}),children:e.jsx(Sn,{className:"h-4 w-4 text-muted-foreground"})})]},p))]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs",children:"Notes for escrow"}),e.jsx(Ms,{rows:2,value:l.notes||"",onChange:m=>d({notes:m.target.value}),placeholder:"Wire instructions, check delivery, anything escrow should know"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 rounded-lg bg-muted/50 p-3 sm:grid-cols-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Gross"}),e.jsx("p",{className:"font-semibold tabular-nums",children:Ude(c.gross)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Referral"}),e.jsx("p",{className:"font-semibold tabular-nums",children:Ude(c.referral)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Brokerage"}),e.jsx("p",{className:"font-semibold tabular-nums text-teal-600",children:Ude(c.companyDollar+c.otherCharges)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Agent net"}),e.jsx("p",{className:"font-semibold tabular-nums text-emerald-600",children:Ude(c.agentNet)})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(B,{disabled:!l.agent_user_id||i,onClick:()=>a(l),children:i?"Saving…":"Save disbursement"})]})]})})}const IBe=[42,76,100],V4t=[64,110,113],DBe=[110,118,125],qde=s=>`${s<0?"-":""}$${Math.abs(Math.round(s)).toLocaleString("en-US")}`,H4t=s=>{const t=WS(s);return t?new Intl.DateTimeFormat("en-US",{month:"long",day:"numeric",year:"numeric",timeZone:"America/New_York"}).format(new Date(Date.UTC(t.y,t.m-1,t.d))):"—"};function _ar(s){const t=s.disbursement,n=OG(t),r=new Mo({unit:"pt",format:"letter"}),a=r.internal.pageSize.getWidth(),i=r.internal.pageSize.getHeight(),l=48;r.setFillColor(...IBe),r.rect(0,0,a,86,"F"),r.setTextColor(255,255,255),r.setFont("helvetica","bold"),r.setFontSize(16),r.text("Commission Disbursement Authorization",l,40),r.setFont("helvetica","normal"),r.setFontSize(10),r.text(s.brokerageName,l,60),r.text(`Issued ${H4t(new Date().toISOString().slice(0,10))}`,a-l,60,{align:"right"});let o=118;const c=(h,m,p,f)=>{r.setFontSize(8),r.setTextColor(...DBe),r.text(h.toUpperCase(),p,o),r.setFontSize(10.5),r.setTextColor(25,30,35),r.text(r.splitTextToSize(m||"—",f)[0],p,o+15)},d=(a-l*2)/2;c("Property",t.property_address||"—",l,d-12),c("Closing date",H4t(t.closing_date),l+d,d),o+=40,c("Escrow / title company",t.escrow_company||"—",l,d-12),c("Escrow / file number",t.escrow_number||"—",l+d,d),o+=40,c("Agent",s.agentName,l,d-12),c("Sale price",qde(t.sale_price),l+d,d),o+=46,r.setDrawColor(224,228,232),r.line(l,o,a-l,o),o+=24,r.setFont("helvetica","bold"),r.setFontSize(11),r.setTextColor(...IBe),r.text("Disbursement of commission",l,o),r.setFont("helvetica","normal"),o+=20;const u=(h,m,p)=>{o>i-140&&(r.addPage(),o=60),r.setFont("helvetica",p!=null&&p.bold?"bold":"normal"),r.setFontSize(10);const f=p!=null&&p.teal?V4t:[25,30,35];r.setTextColor(f[0],f[1],f[2]),r.text(h,l,o),r.text(qde(m),a-l,o,{align:"right"}),o+=8,r.setDrawColor(238,241,243),r.line(l,o,a-l,o),o+=14,r.setFont("helvetica","normal")};return u("Gross commission due at closing",n.gross,{bold:!0}),n.referral>0&&u(`Referral fee${t.referral_payee?` — ${t.referral_payee}`:""}`,-n.referral),n.referral>0&&u("Adjusted gross commission",n.adjustedGross,{bold:!0}),u(`Brokerage split (${Math.round(100-Number(t.agent_split_pct||0))}% to brokerage)`,-n.brokerageSplit),n.franchiseFee>0&&u(`Franchise fee (${t.franchise_fee_pct}%)`,-n.franchiseFee),n.transactionFee>0&&u("Transaction fee",-n.transactionFee),(t.line_items||[]).forEach(h=>u(h.label||"Adjustment",-Number(h.amount||0))),o+=6,r.setFillColor(246,249,249),r.roundedRect(l,o-4,a-l*2,76,6,6,"F"),o+=16,r.setFont("helvetica","bold"),r.setFontSize(11),r.setTextColor(...IBe),r.text(`Pay to ${s.brokerageName}`,l+14,o),r.text(qde(n.companyDollar+n.otherCharges),a-l-14,o,{align:"right"}),o+=24,r.setTextColor(...V4t),r.text(`Pay to ${s.agentName}`,l+14,o),r.text(qde(n.agentNet),a-l-14,o,{align:"right"}),r.setFont("helvetica","normal"),o+=52,t.notes&&(r.setFontSize(9),r.setTextColor(...DBe),r.splitTextToSize(t.notes,a-l*2).forEach(h=>{r.text(h,l,o),o+=12}),o+=10),o>i-130&&(r.addPage(),o=80),o=Math.max(o,i-150),r.setDrawColor(150,158,165),r.line(l,o,l+220,o),r.line(a-l-160,o,a-l,o),r.setFontSize(8),r.setTextColor(...DBe),r.text("Authorized broker signature",l,o+13),r.text("Date",a-l-160,o+13),r.setFontSize(7.5),r.text("This authorization instructs the escrow or title company to disburse the commission as set out above. Amounts are subject to the final settlement statement.",l,i-44,{maxWidth:a-l*2}),r}function war(s){const t=(s.disbursement.property_address||s.agentName||"cda").replace(/[^a-z0-9]+/gi,"-").toLowerCase().slice(0,48);_ar(s).save(`cda-${t}.pdf`)}const jar=s=>{const t=s==null?"":String(s);return/[",\n]/.test(t)?`"${t.replace(/"/g,'""')}"`:t},AI=s=>Math.round(s*100)/100,Nar=["Date","Ref Number","Name","Account","Memo","Debit","Credit"];function kar(s,t){const n=[];return s.forEach((r,a)=>{const i=OG(r),l=r.closing_date||r.created_at.slice(0,10),o=r.escrow_number||`CDA-${String(a+1).padStart(4,"0")}`,c=t(r.agent_user_id),d=r.property_address||"Commission disbursement";n.push({date:l,refNumber:o,name:c,account:"Commission Income",memo:d,debit:"",credit:AI(i.gross)}),i.referral>0&&n.push({date:l,refNumber:o,name:r.referral_payee||"Referral partner",account:"Referral Fees",memo:d,debit:AI(i.referral),credit:""}),i.agentNet!==0&&n.push({date:l,refNumber:o,name:c,account:"Agent Commission Expense",memo:d,debit:AI(i.agentNet),credit:""}),i.franchiseFee>0&&n.push({date:l,refNumber:o,name:c,account:"Franchise Fees",memo:d,debit:AI(i.franchiseFee),credit:""}),(r.line_items||[]).forEach(h=>{const m=Number(h.amount)||0;m&&n.push({date:l,refNumber:o,name:c,account:h.label||"Agent Charges",memo:d,debit:m<0?AI(-m):"",credit:m>0?AI(m):""})});const u=AI(i.gross-i.referral-i.agentNet-i.franchiseFee);u!==0&&n.push({date:l,refNumber:o,name:c,account:"Undeposited Funds",memo:d,debit:u>0?u:"",credit:u<0?-u:""})}),n}function Sar(s){const t=[Nar.join(",")];return s.forEach(n=>t.push([n.date,n.refNumber,n.name,n.account,n.memo,n.debit,n.credit].map(jar).join(","))),t.join(` `)}function Car(s,t,n=`quickbooks-disbursements-${new Date().toISOString().slice(0,10)}.csv`){const r=new Blob([Sar(kar(s,t))],{type:"text/csv;charset=utf-8"}),a=URL.createObjectURL(r),i=document.createElement("a");i.href=a,i.download=n,i.click(),URL.revokeObjectURL(a)}const Aar={draft:"bg-muted text-muted-foreground",approved:"bg-blue-500/10 text-blue-600",paid:"bg-emerald-500/10 text-emerald-600",void:"bg-destructive/10 text-destructive"},RBe=s=>`${s<0?"-":""}$${Math.abs(Math.round(s)).toLocaleString()}`,Ear=s=>{const t=WS(s);return t?`${t.m}/${t.d}/${String(t.y).slice(2)}`:"—"};function Tar({brokerageId:s,disbursements:t,deals:n,roster:r,brokerageName:a,loading:i}){const l=urr(s),o=hrr(s),c=mrr(s),[d,u]=_.useState(null),[h,m]=_.useState("all"),p=j=>{var S;return((S=r.find(C=>C.agentId===j))==null?void 0:S.name)||"Agent"},f=_.useMemo(()=>h==="all"?t:t.filter(j=>j.status===h),[t,h]),y=_.useMemo(()=>t.filter(S=>S.status!=="void").reduce((S,C)=>{const E=OG(C);return S.gross+=E.gross,S.company+=E.companyDollar+E.otherCharges,S.agent+=E.agentNet,C.status==="draft"&&(S.pending+=1),S},{gross:0,company:0,agent:0,pending:0}),[t]),v=_.useMemo(()=>{const j=new Set(t.map(S=>S.deal_id).filter(Boolean));return n.filter(S=>!!S.actual_close_date&&!j.has(S.deal_id)).slice(0,20)},[n,t]),g=j=>{var C;const S=((C=r.find(E=>E.agentId===j.owner_user_id))==null?void 0:C.plan)||null;u(drr(j,S))},b=()=>{var j,S,C,E,P,M,I;return{deal_id:null,agent_user_id:((j=r[0])==null?void 0:j.agentId)||"",status:"draft",property_address:"",escrow_company:null,escrow_number:null,closing_date:new Date().toISOString().slice(0,10),sale_price:0,gross_commission:0,agent_split_pct:((C=(S=r[0])==null?void 0:S.plan)==null?void 0:C.agent_split_pct)??70,franchise_fee_pct:((P=(E=r[0])==null?void 0:E.plan)==null?void 0:P.franchise_fee_pct)??0,transaction_fee:((I=(M=r[0])==null?void 0:M.plan)==null?void 0:I.transaction_fee)??0,referral_fee_pct:0,referral_amount:0,referral_payee:null,line_items:[],notes:null}};return i?e.jsx(cn,{className:"h-64 w-full rounded-xl"}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-4",children:[e.jsx(ve,{className:"border-border/60",children:e.jsxs(Me,{className:"p-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Commission authorized"}),e.jsx("p",{className:"text-2xl font-bold tabular-nums",children:Xm(y.gross)})]})}),e.jsx(ve,{className:"border-border/60",children:e.jsxs(Me,{className:"p-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"To the brokerage"}),e.jsx("p",{className:"text-2xl font-bold tabular-nums text-teal-600",children:Xm(y.company)})]})}),e.jsx(ve,{className:"border-border/60",children:e.jsxs(Me,{className:"p-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"To agents"}),e.jsx("p",{className:"text-2xl font-bold tabular-nums text-emerald-600",children:Xm(y.agent)})]})}),e.jsx(ve,{className:"border-border/60",children:e.jsxs(Me,{className:"p-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Awaiting approval"}),e.jsx("p",{className:"text-2xl font-bold tabular-nums text-amber-600",children:y.pending})]})})]}),v.length>0&&e.jsxs(ve,{className:"border-border/60",children:[e.jsxs(bt,{className:"pb-2",children:[e.jsx(St,{className:"text-base",children:"Closed deals without a disbursement"}),e.jsx(kn,{children:"Start a CDA prefilled from the deal and the agent's commission plan"})]}),e.jsx(Me,{className:"flex flex-wrap gap-2 pt-2",children:v.map(j=>e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>g(j),children:[e.jsx(sJ,{className:"mr-1.5 h-3.5 w-3.5"}),j.property_address||j.deal_name]},j.deal_id))})]}),e.jsxs(ve,{className:"border-border/60",children:[e.jsxs(bt,{className:"flex flex-row flex-wrap items-center justify-between gap-3 pb-2",children:[e.jsxs("div",{children:[e.jsx(St,{className:"text-base",children:"Disbursement authorizations"}),e.jsx(kn,{children:"Approve, mark paid, print the CDA or export to QuickBooks"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(is,{value:h,onValueChange:j=>m(j),children:[e.jsx(rs,{className:"h-9 w-[150px]",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All statuses"}),Object.keys(TBe).map(j=>e.jsx(He,{value:j,children:TBe[j]},j))]})]}),e.jsxs(B,{size:"sm",variant:"outline",disabled:!f.length,onClick:()=>Car(f,p),children:[e.jsx(li,{className:"mr-1.5 h-4 w-4"})," QuickBooks CSV"]}),e.jsxs(B,{size:"sm",disabled:!r.length,onClick:()=>u(b()),children:[e.jsx(rn,{className:"mr-1.5 h-4 w-4"})," New CDA"]})]})]}),e.jsxs(Me,{className:"space-y-1 pt-2",children:[!f.length&&e.jsx("p",{className:"py-8 text-center text-sm text-muted-foreground",children:"No disbursements yet — start one from a closed deal above."}),f.map(j=>{const S=OG(j);return e.jsxs("div",{className:"flex flex-wrap items-center gap-3 rounded-lg border border-border/50 p-3",children:[e.jsxs("div",{className:"min-w-[180px] flex-1",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:j.property_address||"Transaction"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[p(j.agent_user_id)," · closed ",Ear(j.closing_date),j.escrow_number?` · file ${j.escrow_number}`:""]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Gross"}),e.jsx("p",{className:"text-sm font-semibold tabular-nums",children:RBe(S.gross)})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Brokerage"}),e.jsx("p",{className:"text-sm font-semibold tabular-nums text-teal-600",children:RBe(S.companyDollar+S.otherCharges)})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Agent"}),e.jsx("p",{className:"text-sm font-semibold tabular-nums text-emerald-600",children:RBe(S.agentNet)})]}),e.jsx(Oe,{variant:"secondary",className:Aar[j.status],children:TBe[j.status]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>war({disbursement:j,brokerageName:a,agentName:p(j.agent_user_id)}),children:[e.jsx(Fr,{className:"mr-1.5 h-3.5 w-3.5"})," CDA"]}),e.jsxs(tu,{children:[e.jsx(su,{asChild:!0,children:e.jsx(B,{size:"icon",variant:"ghost",children:e.jsx(Xx,{className:"h-4 w-4"})})}),e.jsxs(Od,{align:"end",children:[e.jsx(ca,{onClick:()=>u({...j}),children:"Edit"}),j.status==="draft"&&e.jsxs(ca,{onClick:()=>o.mutate({id:j.id,status:"approved"}),children:[e.jsx(Er,{className:"mr-2 h-4 w-4"})," Approve"]}),j.status!=="paid"&&j.status!=="void"&&e.jsxs(ca,{onClick:()=>o.mutate({id:j.id,status:"paid"}),children:[e.jsx(m7,{className:"mr-2 h-4 w-4"})," Mark paid"]}),j.status!=="void"&&e.jsx(ca,{onClick:()=>o.mutate({id:j.id,status:"void"}),children:"Void"}),e.jsxs(ca,{className:"text-destructive",onClick:()=>c.mutate(j.id),children:[e.jsx(Sn,{className:"mr-2 h-4 w-4"})," Delete"]})]})]})]},j.id)})]})]}),e.jsx(bar,{open:!!d,onOpenChange:j=>!j&&u(null),draft:d,roster:r,saving:l.isPending,onSave:j=>l.mutate(j,{onSuccess:()=>u(null)})})]})}const $de=s=>`$${Math.round(s).toLocaleString()}`,Mar=()=>{var H;const{brokerageId:s,managedBrokerages:t,selectedBrokerageId:n}=hs(),r=_.useMemo(()=>{var Y;return n||((Y=t[0])==null?void 0:Y.id)||s},[n,t,s]),{data:a=[],isLoading:i}=jWn(r,!0),{data:l=[],isLoading:o}=SWn(r),c=NWn(r),d=CWn(r),u=AWn(r),{data:h=[],isLoading:m}=XQe(r),{data:p=[],isLoading:f}=rar(r),{data:y=[],isLoading:v}=Krs(r),{data:g=[],isLoading:b}=Wrs(r),j=((H=t.find(Y=>Y.id===r))==null?void 0:H.name)||"Brokerage",[S,C]=_.useState(!1),[E,P]=_.useState(null),[M,I]=_.useState(!1),[D,O]=_.useState(null),V=a.filter(Y=>Y.is_active),G=l.filter(Y=>Y.assignment),$=G.reduce((Y,Z)=>{var ne;return Y+(((ne=Z.plan)==null?void 0:ne.monthly_fee)||0)},0);return e.jsxs(zs,{title:"Brokerage Financials",description:"Commission plans, cap progress, company dollar and agent fee statements",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-3",children:[e.jsx(ve,{className:"border-border/60",children:e.jsxs(Me,{className:"flex items-center gap-3 p-4",children:[e.jsx("span",{className:"flex h-9 w-9 items-center justify-center rounded-lg bg-teal-500/10 text-teal-600",children:e.jsx(F_,{className:"h-4.5 w-4.5"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Active plans"}),e.jsx("p",{className:"text-2xl font-bold tabular-nums tracking-tight",children:V.length})]})]})}),e.jsx(ve,{className:"border-border/60",children:e.jsxs(Me,{className:"flex items-center gap-3 p-4",children:[e.jsx("span",{className:"flex h-9 w-9 items-center justify-center rounded-lg bg-blue-500/10 text-blue-600",children:e.jsx(In,{className:"h-4.5 w-4.5"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Agents on a plan"}),e.jsxs("p",{className:"text-2xl font-bold tabular-nums tracking-tight",children:[G.length,e.jsxs("span",{className:"text-sm font-normal text-muted-foreground",children:[" of ",l.length]})]})]})]})}),e.jsx(ve,{className:"border-border/60",children:e.jsxs(Me,{className:"flex items-center gap-3 p-4",children:[e.jsx("span",{className:"flex h-9 w-9 items-center justify-center rounded-lg bg-emerald-500/10 text-emerald-600",children:e.jsx(m7,{className:"h-4.5 w-4.5"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Monthly desk fees"}),e.jsx("p",{className:"text-2xl font-bold tabular-nums tracking-tight",children:Xm($)}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"expected across assigned agents"})]})]})})]}),e.jsxs(Yr,{defaultValue:"agents",className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsx("div",{className:"overflow-x-auto pb-1",children:e.jsxs(Zr,{children:[e.jsx(Ht,{value:"agents",children:"Agents"}),e.jsx(Ht,{value:"plans",children:"Plans"}),e.jsx(Ht,{value:"company",children:"Company dollar"}),e.jsx(Ht,{value:"ledger",children:"Fees & statements"}),e.jsx(Ht,{value:"disbursements",children:"Disbursements"}),e.jsx(Ht,{value:"renewals",children:"Renewals & goals"})]})}),e.jsxs(B,{size:"sm",onClick:()=>{P(null),C(!0)},children:[e.jsx(rn,{className:"mr-1.5 h-4 w-4"})," New plan"]})]}),e.jsx(Gt,{value:"agents",className:"space-y-2",children:e.jsxs(ve,{className:"border-border/60",children:[e.jsxs(bt,{className:"pb-2",children:[e.jsx(St,{className:"text-base",children:"Agent plans & cap progress"}),e.jsx(kn,{children:"Assign a plan to each agent — their new deals inherit the splits and fees automatically"})]}),e.jsx(Me,{className:"space-y-1 pt-2",children:o?Array.from({length:4}).map((Y,Z)=>e.jsx(cn,{className:"h-16 w-full rounded-lg"},Z)):l.length===0?e.jsx("p",{className:"py-8 text-center text-sm text-muted-foreground",children:"No agents in this brokerage yet."}):l.map(Y=>{var ne;const Z=(ne=Y.progress)==null?void 0:ne.pct_to_cap;return e.jsxs("div",{className:"flex flex-col gap-3 rounded-lg px-2 py-3 hover:bg-muted/50 sm:flex-row sm:items-center",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-3",children:[e.jsxs(ja,{className:"h-9 w-9 shrink-0",children:[e.jsx(pi,{src:Y.avatarUrl||void 0,alt:Y.name}),e.jsx(Na,{className:"text-[11px]",children:Y.name.slice(0,2).toUpperCase()})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:Y.name}),e.jsx("p",{className:"truncate text-[11px] text-muted-foreground",children:Y.email})]})]}),e.jsx("div",{className:"min-w-0 flex-1",children:Y.plan?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsx(Oe,{variant:"secondary",className:"font-medium",children:Y.plan.name}),e.jsxs("span",{className:"text-[11px] text-muted-foreground",children:[Y.plan.agent_split_pct,"/",Math.max(0,100-Y.plan.agent_split_pct),Y.plan.cap_amount?` · ${Xm(Y.plan.cap_amount)} cap`:" · no cap"]})]}),Y.plan.cap_amount&&Y.progress?e.jsxs("div",{className:"mt-1.5 max-w-xs",children:[e.jsxs("div",{className:"mb-1 flex justify-between text-[11px] text-muted-foreground",children:[e.jsxs("span",{children:[$de(Y.progress.cap_progress)," to cap"]}),e.jsxs("span",{children:[Math.round(Z??0),"%"]})]}),e.jsx(Fi,{value:Math.min(100,Z??0),className:"h-1.5"})]}):e.jsx("p",{className:"mt-1 text-[11px] text-muted-foreground",children:"No cap on this plan"})]}):e.jsx("p",{className:"text-[12px] italic text-muted-foreground",children:"No plan assigned"})}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[e.jsx(B,{variant:"outline",size:"sm",disabled:V.length===0,onClick:()=>{O(Y),I(!0)},children:Y.assignment?"Change plan":"Assign plan"}),Y.assignment&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground",title:"Remove plan",onClick:()=>u.mutate(Y.assignment.id),children:e.jsx(m$,{className:"h-4 w-4"})})]})]},Y.agentId)})})]})}),e.jsx(Gt,{value:"plans",className:"space-y-3",children:i?e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:Array.from({length:2}).map((Y,Z)=>e.jsx(cn,{className:"h-44 w-full rounded-xl"},Z))}):a.length===0?e.jsx(ve,{className:"border-dashed",children:e.jsxs(Me,{className:"flex flex-col items-center gap-3 py-12 text-center",children:[e.jsx("span",{className:"flex h-11 w-11 items-center justify-center rounded-xl bg-teal-500/10 text-teal-600",children:e.jsx(F_,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"No commission plans yet"}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Create your first plan — e.g. a 70/30 split with an annual cap — then assign it to agents."})]}),e.jsxs(B,{onClick:()=>{P(null),C(!0)},children:[e.jsx(rn,{className:"mr-1.5 h-4 w-4"})," Create plan"]})]})}):e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:a.map(Y=>e.jsxs(ve,{className:`border-border/60 ${Y.is_active?"":"opacity-60"}`,children:[e.jsx(bt,{className:"pb-2",children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx(St,{className:"text-base",children:Y.name}),Y.description&&e.jsx(kn,{className:"mt-1",children:Y.description})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[!Y.is_active&&e.jsx(Oe,{variant:"outline",children:"Retired"}),e.jsxs(Oe,{variant:"secondary",children:["v",Y.version_no]}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>{P(Y),C(!0)},children:e.jsx(Ya,{className:"h-4 w-4"})})]})]})}),e.jsxs(Me,{className:"grid grid-cols-2 gap-x-4 gap-y-2 pt-1 text-sm",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Split (agent/brokerage)"}),e.jsxs("p",{className:"font-medium tabular-nums",children:[Y.agent_split_pct,"/",Math.max(0,100-Y.agent_split_pct)]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Annual cap"}),e.jsx("p",{className:"font-medium tabular-nums",children:Y.cap_amount?$de(Y.cap_amount):"None"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Monthly desk fee"}),e.jsx("p",{className:"font-medium tabular-nums",children:Y.monthly_fee?$de(Y.monthly_fee):"—"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Per-transaction fee"}),e.jsx("p",{className:"font-medium tabular-nums",children:Y.transaction_fee?$de(Y.transaction_fee):"—"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Franchise fee"}),e.jsx("p",{className:"font-medium tabular-nums",children:Y.franchise_fee_pct?`${Y.franchise_fee_pct}%`:"—"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Team split"}),e.jsx("p",{className:"font-medium tabular-nums",children:Y.team_split_pct?`${Y.team_split_pct}%`:"—"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Agents on plan"}),e.jsx("p",{className:"font-medium tabular-nums",children:l.filter(Z=>{var ne;return((ne=Z.plan)==null?void 0:ne.id)===Y.id}).length})]})]})]},Y.id))})}),e.jsx(Gt,{value:"company",children:e.jsx(har,{deals:h,ledger:p,roster:l,brokerageName:j,loading:m||o})}),e.jsx(Gt,{value:"ledger",children:e.jsx(far,{brokerageId:r,ledger:p,roster:l,loading:f||o})}),e.jsx(Gt,{value:"renewals",children:e.jsx(yar,{records:y,roster:l,deals:h,loading:v||o})}),e.jsx(Gt,{value:"disbursements",children:e.jsx(Tar,{brokerageId:r,disbursements:g,deals:h,roster:l,brokerageName:j,loading:b||o})})]})]}),e.jsx(sar,{open:S,onOpenChange:C,plan:E,saving:c.isPending,onSave:Y=>c.mutate(Y,{onSuccess:()=>C(!1)})}),e.jsx(nar,{open:M,onOpenChange:I,agent:D,plans:V,saving:d.isPending,onAssign:Y=>d.mutate(Y,{onSuccess:()=>I(!1)})})]})};function Par(){const[s,t]=_.useState(""),{data:n,isLoading:r}=at({queryKey:["admin-brokerage-content-activity"],queryFn:async()=>{const{data:o}=await q.from("brokerages").select("id, name");if(!o)return[];const{data:c}=await q.from("brokerage_content").select("id, brokerage_id, content_type, created_at"),{data:d}=await q.from("brokerage_content_categories").select("id, brokerage_id"),u=c||[],h=d||[],m=o.map(p=>{const f=u.filter(g=>g.brokerage_id===p.id),y=h.filter(g=>g.brokerage_id===p.id),v=f.length>0?f.reduce((g,b)=>b.created_at>g?b.created_at:g,f[0].created_at):null;return{brokerage_id:p.id,brokerage_name:p.name,total_items:f.length,videos:f.filter(g=>g.content_type==="video").length,pdfs:f.filter(g=>g.content_type==="pdf").length,links:f.filter(g=>g.content_type==="link"||g.content_type==="canva_link").length,events:f.filter(g=>g.content_type==="event").length,graphics:f.filter(g=>g.content_type==="graphic").length,latest_item_date:v,categories:y.length}});return m.sort((p,f)=>f.total_items-p.total_items),m}}),a=(n||[]).filter(o=>o.brokerage_name.toLowerCase().includes(s.toLowerCase())),i=a.reduce((o,c)=>o+c.total_items,0),l=a.filter(o=>o.total_items>0).length;return e.jsx(zs,{title:"Brokerage Content Activity",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Wh,{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(ve,{children:[e.jsx(bt,{className:"pb-2",children:e.jsx(St,{className:"text-sm font-medium text-muted-foreground",children:"Active Brokerages"})}),e.jsxs(Me,{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(ve,{children:[e.jsx(bt,{className:"pb-2",children:e.jsx(St,{className:"text-sm font-medium text-muted-foreground",children:"Total Content Items"})}),e.jsxs(Me,{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(ve,{children:[e.jsx(bt,{className:"pb-2",children:e.jsx(St,{className:"text-sm font-medium text-muted-foreground",children:"Total Brokerages"})}),e.jsxs(Me,{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(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search brokerages...",value:s,onChange:o=>t(o.target.value),className:"pl-9"})]}),e.jsx(ve,{children:e.jsx(Me,{className:"p-0",children:e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"Brokerage"}),e.jsx(Pt,{className:"text-center",children:"Total"}),e.jsx(Pt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(Kr,{className:"h-3 w-3"})," Videos"]})}),e.jsx(Pt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(Fr,{className:"h-3 w-3"})," PDFs"]})}),e.jsx(Pt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(vd,{className:"h-3 w-3"})," Links"]})}),e.jsx(Pt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(pc,{className:"h-3 w-3"})," Events"]})}),e.jsx(Pt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(hc,{className:"h-3 w-3"})," Graphics"]})}),e.jsx(Pt,{className:"text-center",children:"Categories"}),e.jsx(Pt,{children:"Last Upload"})]})}),e.jsx(Ka,{children:r?e.jsx(pn,{children:e.jsx(gt,{colSpan:9,className:"text-center py-8 text-muted-foreground",children:"Loading..."})}):a.length===0?e.jsx(pn,{children:e.jsx(gt,{colSpan:9,className:"text-center py-8 text-muted-foreground",children:"No brokerages found"})}):a.map(o=>e.jsxs(pn,{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(Oe,{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 Lar=[{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:"📉"}],G4t=[{value:"instagram-square",label:"Instagram Post",dimensions:"1080×1080",icon:e.jsx(Im,{className:"h-4 w-4"})},{value:"instagram-story",label:"Instagram Story",dimensions:"1080×1920",icon:e.jsx(Im,{className:"h-4 w-4"})},{value:"facebook-post",label:"Facebook Post",dimensions:"1200×630",icon:e.jsx(tf,{className:"h-4 w-4"})}],Iar=[{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:"📰"}],W4t=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),K4t={"luxury-dark":Dtt,"modern-clean":Rtt,"bold-colorful":Ftt,editorial:Ott};function Dar(){const[s,t]=_.useState(""),[n,r]=_.useState("address"),[a,i]=_.useState(!1),[l,o]=_.useState([]),[c,d]=_.useState(null),[u,h]=_.useState(0),[m,p]=_.useState("just-listed"),[f,y]=_.useState(["instagram-square"]),[v,g]=_.useState("luxury-dark"),[b,j]=_.useState(!1),[S,C]=_.useState(""),[E,P]=_.useState(""),[M,I]=_.useState(""),[D,O]=_.useState(!1),[V,G]=_.useState(!1),[$,H]=_.useState([]),[Y,Z]=_.useState("search"),ne=_.useRef({});_.useEffect(()=>{(async()=>{const{data:{user:Ce}}=await q.auth.getUser();if(!Ce)return;const{data:Ae}=await q.from("profiles").select("name, avatar_url, brokerages(name)").eq("id",Ce.id).single();if(Ae){C(Ae.name||""),I(Ae.avatar_url||"");const Pe=Ae.brokerages;P((Pe==null?void 0:Pe.name)||"")}})()},[]);const ce=async()=>{var pe;if(s.trim()){i(!0),o([]);try{const{data:Ce,error:Ae}=await q.functions.invoke("repliers-mls-search",{body:{searchType:n,query:s.trim()}});if(Ae)throw Ae;if(Ce.error)throw new Error(Ce.error);o(Ce.listings||[]),((pe=Ce.listings)==null?void 0:pe.length)===0&&se.info("No listings found. Try a different search.")}catch(Ce){se.error(Ce.message||"Search failed")}finally{i(!1)}}},ie=pe=>{var Ce;d(pe),h(0),Z("customize"),pe.soldDate||(Ce=pe.status)!=null&&Ce.toLowerCase().includes("sold")?p("just-sold"):p("just-listed")},te=pe=>{y(Ce=>Ce.includes(pe)?Ce.filter(Ae=>Ae!==pe):[...Ce,pe])},ae=_.useCallback(async()=>{if(!(!c||f.length===0)){O(!0),H([]),Z("generate");try{await new Promise(Ce=>setTimeout(Ce,500));const pe=[];for(const Ce of f){const Ae=`${v}-${Ce}`,Pe=ne.current[Ae];if(!Pe)continue;const ze=NM[Ce],ke=await $H(Pe,{width:ze.width,height:ze.height,pixelRatio:1,cacheBust:!0,style:{transform:"none",transformOrigin:"top left"}});pe.push({format:Ce,imageUrl:ke})}H(pe),se.success(`Generated ${pe.length} social post${pe.length>1?"s":""}!`)}catch(pe){se.error(pe.message||"Generation failed")}finally{O(!1)}}},[c,f,v,u,b,S,E,M,m]),le=async()=>{if(!(!c||f.length===0)){O(!0),H([]),Z("generate");try{const pe={...c,photos:c.photos.length>0?[c.photos[u]]:[]},Ce=[];for(const Ae of f){const{data:Pe,error:ze}=await q.functions.invoke("generate-listing-social-post",{body:{listing:pe,postType:m,format:Ae,branding:b?{enabled:!0,agentName:S,brokerage:E}:{enabled:!1}}});if(ze)throw ze;if(Pe.error)throw new Error(Pe.error);Ce.push({format:Ae,imageUrl:Pe.imageUrl})}H(Ce),se.success(`Generated ${Ce.length} AI post${Ce.length>1?"s":""}!`)}catch(pe){se.error(pe.message||"AI generation failed")}finally{O(!1)}}},be=()=>V?le():ae(),me=(pe,Ce)=>{var Pe;const Ae=document.createElement("a");Ae.href=pe,Ae.download=`${((Pe=c==null?void 0:c.address)==null?void 0:Pe.replace(/\s+/g,"-"))||"listing"}-${m}-${Ce}.png`,document.body.appendChild(Ae),Ae.click(),document.body.removeChild(Ae)},he=c?{listing:c,postType:m,format:"instagram-square",branding:b?{enabled:!0,agentName:S,brokerage:E,agentPhotoUrl:M||void 0}:{enabled:!1},selectedPhotoIndex:u}:null;return e.jsx(zs,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-8",children:[e.jsx(Wh,{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:()=>Z("search"),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full transition-colors ${Y==="search"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground hover:text-foreground"}`,children:[e.jsx(Lr,{className:"h-3.5 w-3.5"})," 1. Find Listing"]}),e.jsx(xi,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("button",{onClick:()=>c&&Z("customize"),disabled:!c,className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full transition-colors ${Y==="customize"?"bg-primary text-primary-foreground":c?"bg-muted text-muted-foreground hover:text-foreground":"bg-muted text-muted-foreground/50 cursor-not-allowed"}`,children:[e.jsx(un,{className:"h-3.5 w-3.5"})," 2. Customize"]}),e.jsx(xi,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full ${Y==="generate"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground/50"}`,children:[e.jsx(hc,{className:"h-3.5 w-3.5"})," 3. Generate"]})]}),Y==="search"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(Lr,{className:"h-5 w-5 text-primary"})," Search MLS Listings ",e.jsx(Dzt,{})]}),e.jsx(kn,{children:"Find a listing by MLS number or property address using Repliers.io"})]}),e.jsxs(Me,{className:"space-y-4",children:[e.jsx(Yr,{value:n,onValueChange:pe=>r(pe),children:e.jsxs(Zr,{children:[e.jsxs(Ht,{value:"address",children:[e.jsx(Xa,{className:"h-4 w-4 mr-1.5"})," Address"]}),e.jsxs(Ht,{value:"mls",children:[e.jsx(Ep,{className:"h-4 w-4 mr-1.5"})," MLS #"]})]})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{value:s,onChange:pe=>t(pe.target.value),placeholder:n==="mls"?"Enter MLS number...":"Enter property address...",className:"flex-1",onKeyDown:pe=>pe.key==="Enter"&&ce()}),e.jsxs(B,{onClick:ce,disabled:a||!s.trim(),children:[a?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Lr,{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((pe,Ce)=>{var Ae;return e.jsx(ve,{className:"cursor-pointer hover:border-primary/50 hover:shadow-md transition-all group",onClick:()=>ie(pe),children:e.jsx(Me,{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:(Ae=pe.photos)!=null&&Ae[0]?e.jsx("img",{src:pe.photos[0],alt:pe.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(Jr,{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:W4t(pe.price)}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:pe.address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[pe.city,", ",pe.state," ",pe.zip]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1.5 text-xs text-muted-foreground",children:[pe.bedrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(q4,{className:"h-3 w-3"})," ",pe.bedrooms]}),pe.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(S0,{className:"h-3 w-3"})," ",pe.bathrooms]}),pe.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(t7,{className:"h-3 w-3"})," ",pe.sqft.toLocaleString()]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Oe,{variant:"outline",className:"text-[10px]",children:pe.mlsNumber}),e.jsx(Oe,{variant:"outline",className:"text-[10px]",children:pe.status})]})]})]})})},pe.mlsNumber||Ce)})})]})]}),Y==="customize"&&c&&e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs(ve,{className:"lg:col-span-1",children:[e.jsx(bt,{className:"pb-3",children:e.jsx(St,{className:"text-base",children:"Selected Listing"})}),e.jsxs(Me,{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(B,{variant:"outline",size:"icon",className:"h-7 w-7",onClick:()=>h(pe=>Math.max(0,pe-1)),disabled:u===0,children:e.jsx($c,{className:"h-4 w-4"})}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[u+1," of ",c.photos.length]}),e.jsx(B,{variant:"outline",size:"icon",className:"h-7 w-7",onClick:()=>h(pe=>Math.min(c.photos.length-1,pe+1)),disabled:u===c.photos.length-1,children:e.jsx(xi,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-bold text-lg",children:W4t(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(B,{variant:"outline",size:"sm",className:"w-full",onClick:()=>{Z("search"),d(null)},children:[e.jsx(Tx,{className:"h-3.5 w-3.5 mr-1.5"})," Choose Different Listing"]})]})]}),e.jsxs(ve,{className:"lg:col-span-2",children:[e.jsxs(bt,{children:[e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-5 w-5 text-primary"})," Customize Your Post"]}),e.jsx(kn,{children:"Choose template, post type, format, and branding"})]}),e.jsxs(Me,{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(Xc,{className:"h-4 w-4 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:V?"AI Custom Generation":"Template-Based (Free)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:V?"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(fn,{checked:V,onCheckedChange:G}),V&&e.jsx(Qx,{className:"h-4 w-4 text-purple-500"})]})]}),!V&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(J,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Xc,{className:"h-4 w-4"})," Template Style"]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:Iar.map(pe=>e.jsxs("button",{onClick:()=>g(pe.value),className:`flex flex-col items-center gap-1 px-3 py-3 rounded-lg border-2 transition-all text-center ${v===pe.value?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("span",{className:"text-2xl",children:pe.preview}),e.jsx("span",{className:"text-sm font-medium",children:pe.label}),e.jsx("span",{className:"text-[10px] text-muted-foreground leading-tight",children:pe.description})]},pe.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{className:"text-sm font-medium",children:"Post Type"}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:Lar.map(pe=>e.jsxs("button",{onClick:()=>p(pe.value),className:`flex items-center gap-2 px-3 py-2.5 rounded-lg border-2 transition-all text-sm font-medium ${m===pe.value?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("span",{className:"text-lg",children:pe.icon})," ",pe.label]},pe.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{className:"text-sm font-medium",children:"Output Formats"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-2",children:G4t.map(pe=>e.jsxs("button",{onClick:()=>te(pe.value),className:`flex items-center gap-2 px-3 py-2.5 rounded-lg border-2 transition-all text-sm ${f.includes(pe.value)?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[pe.icon,e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"font-medium",children:pe.label}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:pe.dimensions})]})]},pe.value))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(J,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Fo,{className:"h-4 w-4"})," Agent Branding"]}),e.jsx(fn,{checked:b,onCheckedChange:j})]}),b&&e.jsxs("div",{className:"space-y-3 pl-6 border-l-2 border-primary/20",children:[M&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("img",{src:M,alt:"Agent",className:"w-12 h-12 rounded-full object-cover border-2 border-primary/30"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Profile photo will appear on the post"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(J,{className:"text-xs text-muted-foreground",children:"Agent Name"}),e.jsx(xe,{value:S,onChange:pe=>C(pe.target.value),placeholder:"Jane Smith"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(J,{className:"text-xs text-muted-foreground",children:"Brokerage (optional)"}),e.jsx(xe,{value:E,onChange:pe=>P(pe.target.value),placeholder:"XYZ Realty"})]})]})]})]}),!V&&he&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{className:"text-sm font-medium",children:"Preview"}),e.jsx("div",{className:"bg-muted/30 rounded-lg p-4 flex justify-center overflow-hidden",children:e.jsx("div",{style:{width:400,height:400*(NM[f[0]||"instagram-square"].height/NM[f[0]||"instagram-square"].width)},children:(()=>{const pe=K4t[v],Ce=f[0]||"instagram-square";return e.jsx(pe,{...he,format:Ce})})()})})]}),e.jsx(B,{onClick:be,disabled:f.length===0||D,size:"lg",className:"w-full gap-2",children:D?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"h-5 w-5 animate-spin"})," Generating ",f.length," post",f.length>1?"s":"","..."]}):e.jsxs(e.Fragment,{children:[V?e.jsx(Qx,{className:"h-5 w-5"}):e.jsx(un,{className:"h-5 w-5"}),"Generate ",f.length," Social Post",f.length>1?"s":"",V&&e.jsx(Oe,{variant:"outline",className:"ml-2 text-[10px]",children:"Uses Credits"})]})})]})]})]}),Y==="generate"&&e.jsxs("div",{className:"space-y-4",children:[D&&e.jsx(ve,{children:e.jsxs(Me,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx(Ct,{className:"h-12 w-12 animate-spin text-primary mb-4"}),e.jsx("p",{className:"text-lg font-medium",children:"Generating your social posts..."}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:V?"AI is creating your unique designs":"Rendering templates to high-res images"})]})}),$.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(B,{variant:"outline",size:"sm",onClick:()=>Z("customize"),children:[e.jsx(Tx,{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:$.map((pe,Ce)=>{const Ae=G4t.find(Pe=>Pe.value===pe.format);return e.jsxs(ve,{className:"overflow-hidden",children:[e.jsx("div",{className:"bg-muted/30 p-1",children:e.jsx("img",{src:pe.imageUrl,alt:`${pe.format} social post`,className:"w-full rounded"})}),e.jsxs(Me,{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:[Ae==null?void 0:Ae.icon,e.jsx("span",{className:"text-sm font-medium",children:Ae==null?void 0:Ae.label})]}),e.jsx(Oe,{variant:"outline",className:"text-[10px]",children:Ae==null?void 0:Ae.dimensions})]}),e.jsxs(B,{size:"sm",className:"w-full gap-1.5",onClick:()=>me(pe.imageUrl,pe.format),children:[e.jsx(li,{className:"h-3.5 w-3.5"})," Download"]})]})]},Ce)})})]})]}),Y==="generate"&&!V&&c&&he&&e.jsx("div",{style:{position:"absolute",left:"-9999px",top:0},"aria-hidden":!0,children:f.map(pe=>{const Ce=K4t[v],Ae=NM[pe];return e.jsx("div",{style:{width:Ae.width,height:Ae.height},children:e.jsx(Ce,{ref:Pe=>{ne.current[`${v}-${pe}`]=Pe},...he,format:pe})},`${v}-${pe}`)})})]})})}function Rar(){return at({queryKey:["lms-courses-admin"],queryFn:async()=>{const{data:s,error:t}=await q.from("lms_courses").select("*, modules:lms_modules(count), access:lms_course_access(*)").order("sort_order");if(t)throw t;return s}})}function Far(s){return at({queryKey:["lms-course-admin",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("lms_courses").select("*, modules:lms_modules(*, resources:lms_module_resources(*)), access:lms_course_access(*)").eq("id",s).single();if(n)throw n;return t!=null&&t.modules&&(t.modules.sort((r,a)=>r.sort_order-a.sort_order),t.modules.forEach(r=>{r.resources&&r.resources.sort((a,i)=>a.sort_order-i.sort_order)})),t},enabled:!!s})}function Oar(){const s=Bt();return mt({mutationFn:async t=>{const{data:n,error:r}=await q.from("lms_courses").insert(t).select().single();if(r)throw r;return n},onSuccess:()=>s.invalidateQueries({queryKey:["lms-courses"]})})}function aas(){const s=Bt();return mt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("lms_courses").update({...n,updated_at:new Date().toISOString()}).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-courses"]}),s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-courses-admin"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function zar(){const s=Bt();return mt({mutationFn:async t=>{const{error:n}=await q.from("lms_courses").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["lms-courses"]})})}function Bar(){const s=Bt();return mt({mutationFn:async t=>{const{data:n,error:r}=await q.from("lms_modules").insert(t).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function Uar(){const s=Bt();return mt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("lms_modules").update({...n,updated_at:new Date().toISOString()}).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function qar(){const s=Bt();return mt({mutationFn:async t=>{const{error:n}=await q.from("lms_modules").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function $ar(){const s=Bt();return mt({mutationFn:async t=>{const{data:n,error:r}=await q.from("lms_module_resources").insert(t).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function Var(){const s=Bt();return mt({mutationFn:async t=>{const{error:n}=await q.from("lms_module_resources").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function Har(){const s=Bt();return mt({mutationFn:async({courseId:t,accessRules:n})=>{const{error:r}=await q.from("lms_course_access").delete().eq("course_id",t);if(r)throw r;if(n.length>0){const a=n.map(l=>({...l,course_id:t})),{error:i}=await q.from("lms_course_access").insert(a);if(i)throw i}},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-courses"]}),s.invalidateQueries({queryKey:["lms-course"]})}})}function Gar(){return at({queryKey:["lms-courses-agent"],queryFn:async()=>{const{data:s,error:t}=await q.from("lms_courses").select("*, modules:lms_modules(id)").eq("is_published",!0).order("sort_order");if(t)throw t;return s}})}function War(s){return at({queryKey:["lms-course-agent",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("lms_courses").select("*, modules:lms_modules(*, resources:lms_module_resources(*))").eq("id",s).single();if(n)throw n;return t!=null&&t.modules&&(t.modules.sort((r,a)=>r.sort_order-a.sort_order),t.modules.forEach(r=>{r.resources&&r.resources.sort((a,i)=>a.sort_order-i.sort_order)})),t},enabled:!!s})}function ias(s){return at({queryKey:["lms-progress",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("lms_progress").select("*").eq("course_id",s);if(n)throw n;return t},enabled:!!s})}function Kar(){const s=Bt();return mt({mutationFn:async({courseId:t,moduleId:n,userId:r})=>{const{data:a,error:i}=await q.from("lms_progress").upsert({user_id:r,course_id:t,module_id:n,completed:!0,completed_at:new Date().toISOString()},{onConflict:"user_id,module_id"}).select().single();if(i)throw i;return a},onSuccess:()=>s.invalidateQueries({queryKey:["lms-progress"]})})}function Yar(){const{user:s}=hs(),t=Fn(),{data:n,isLoading:r}=Rar(),a=Oar(),i=aas(),l=zar(),[o,c]=_.useState(!1),[d,u]=_.useState(""),[h,m]=_.useState(""),[p,f]=_.useState(!0),y=async()=>{if(!(!d.trim()||!s))try{const b=await a.mutateAsync({title:d.trim(),description:h.trim()||void 0,is_sequential:p,created_by:s.id});se.success("Course created"),c(!1),u(""),m(""),f(!0),t(`/admin/lms/${b.id}`)}catch{se.error("Failed to create course")}},v=async b=>{try{await i.mutateAsync({id:b.id,is_published:!b.is_published}),se.success(b.is_published?"Course unpublished":"Course published")}catch{se.error("Failed to update course")}},g=async b=>{if(await Xi("Delete this course and all its modules? This cannot be undone."))try{await l.mutateAsync(b),se.success("Course deleted")}catch{se.error("Failed to delete")}};return e.jsxs(zs,{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(mm,{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(B,{variant:"outline",onClick:()=>t("/admin/lms/stats"),children:[e.jsx(bl,{className:"h-4 w-4 mr-2"}),"Analytics"]}),e.jsxs(B,{onClick:()=>c(!0),children:[e.jsx(rn,{className:"h-4 w-4 mr-2"}),"New Course"]})]})]}),r?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4",children:[1,2,3].map(b=>e.jsx(ve,{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"})]})},b))}):n!=null&&n.length?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4",children:n.map(b=>{var E,P;const j=((P=(E=b.modules)==null?void 0:E[0])==null?void 0:P.count)??0,S=b.access||[],C=S.length===0?"No access set":S.some(M=>M.access_type==="all")?"All agents":`${S.length} rule(s)`;return e.jsxs(ve,{className:"group hover:shadow-md transition-all hover:border-primary/50 cursor-pointer",onClick:()=>t(`/admin/lms/${b.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(St,{className:"text-base truncate",children:b.title}),b.description&&e.jsx(kn,{className:"mt-1 line-clamp-2",children:b.description})]}),e.jsx(Oe,{variant:b.is_published?"default":"secondary",className:"ml-2 shrink-0",children:b.is_published?"Published":"Draft"})]})}),e.jsxs(Me,{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(Sx,{className:"h-3.5 w-3.5"}),j," module",j!==1?"s":""]}),e.jsxs("span",{className:"flex items-center gap-1",children:[b.is_sequential?e.jsx(xj,{className:"h-3.5 w-3.5"}):e.jsx(l7,{className:"h-3.5 w-3.5"}),b.is_sequential?"Sequential":"Free order"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(In,{className:"h-3.5 w-3.5"}),C]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-3 opacity-0 group-hover:opacity-100 transition-opacity",children:[e.jsxs(B,{size:"sm",variant:"ghost",onClick:M=>{M.stopPropagation(),v(b)},children:[b.is_published?e.jsx(Ax,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(ya,{className:"h-3.5 w-3.5 mr-1"}),b.is_published?"Unpublish":"Publish"]}),e.jsx(B,{size:"sm",variant:"ghost",className:"text-destructive",onClick:M=>{M.stopPropagation(),g(b.id)},children:e.jsx(Sn,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"flex-1"}),e.jsx(La,{className:"h-4 w-4 text-muted-foreground"})]})]})]},b.id)})}):e.jsx(ve,{className:"border-dashed",children:e.jsxs(Me,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(Sx,{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(B,{onClick:()=>c(!0),children:[e.jsx(rn,{className:"h-4 w-4 mr-2"}),"Create Course"]})]})})]}),e.jsx(Ls,{open:o,onOpenChange:c,children:e.jsxs(Ps,{children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Create New Course"}),e.jsx(_r,{children:"Set up a new training course for your agents"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Course Title"}),e.jsx(xe,{value:d,onChange:b=>u(b.target.value),placeholder:"e.g. LevelUp Onboarding"})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Description"}),e.jsx(Ms,{value:h,onChange:b=>m(b.target.value),placeholder:"What will agents learn?",rows:3})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Sequential Learning"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Agents must complete modules in order"})]}),e.jsx(fn,{checked:p,onCheckedChange:f})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx(B,{onClick:y,disabled:!d.trim()||a.isPending,children:a.isPending?"Creating...":"Create Course"})]})]})})]})}function Zar(){const{courseId:s}=Li(),t=Fn(),{data:n,isLoading:r}=Far(s),a=aas(),i=Bar(),l=Uar(),o=qar(),c=$ar(),d=Var(),u=Har(),{data:h}=at({queryKey:["all-brokerages"],queryFn:async()=>{const{data:Xe}=await q.from("brokerages").select("id, name").order("name");return Xe||[]}}),[m,p]=_.useState(null),[f,y]=_.useState(!1),[v,g]=_.useState({title:"",description:"",video_url:"",text_content:"",duration_minutes:""}),[b,j]=_.useState(null),[S,C]=_.useState({title:"",resource_type:"link",url:""}),[E,P]=_.useState(new Set),[M,I]=_.useState(null),[D,O]=_.useState(0),[V,G]=_.useState(!1),$=_.useRef(null),H=_.useRef(null),[Y,Z]=_.useState(!1),[ne,ce]=_.useState(""),[ie,te]=_.useState(""),[ae,le]=_.useState(""),[be,me]=_.useState(!1);if(r)return e.jsx(zs,{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(zs,{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(B,{variant:"outline",className:"mt-4",onClick:()=>t("/admin/lms"),children:[e.jsx(ka,{className:"h-4 w-4 mr-2"})," Back to Courses"]})]})});const he=n.modules||[],pe=n.access||[],Ce=pe.some(Xe=>Xe.access_type==="all"),Ae=pe.filter(Xe=>Xe.access_type==="brokerage").map(Xe=>Xe.brokerage_id),Pe=(h||[]).filter(Xe=>Xe.name.toLowerCase().includes(ne.toLowerCase())),ze=Xe=>{const nt=new Set(E);nt.has(Xe)?nt.delete(Xe):nt.add(Xe),P(nt)},ke=async()=>{if(!M)return null;G(!0),O(0);try{const{data:Xe,error:nt}=await q.functions.invoke("bunny-upload",{body:{action:"create",title:M.name}});if(nt)throw new Error(nt.message);const{videoId:$e,libraryId:Ge}=Xe,{data:ct,error:xt}=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:$e,libraryId:Ge}});if(xt)throw new Error(xt.message);const qt=new XMLHttpRequest;return await new Promise((Vt,Xt)=>{qt.upload.onprogress=fs=>{fs.lengthComputable&&O(Math.round(fs.loaded/fs.total*100))},qt.onload=()=>qt.status>=200&&qt.status<300?Vt():Xt(new Error(`Upload failed: ${qt.status}`)),qt.onerror=()=>Xt(new Error("Upload failed")),qt.open("PUT",ct.uploadUrl),qt.setRequestHeader("AccessKey",ct.apiKey),qt.send(M)}),`https://iframe.mediadelivery.net/embed/${Ge}/${$e}`}catch(Xe){return console.error("Bunny upload error:",Xe),se.error("Video upload failed"),null}finally{G(!1),O(0)}},Ze=async()=>{if(v.title.trim())try{let Xe=v.video_url.trim()||void 0;if(M){const nt=await ke();if(!nt)return;Xe=nt}await i.mutateAsync({course_id:n.id,title:v.title.trim(),description:v.description.trim()||void 0,video_url:Xe,text_content:v.text_content.trim()||void 0,duration_minutes:v.duration_minutes?parseInt(v.duration_minutes):void 0,sort_order:he.length}),se.success("Module added"),y(!1),g({title:"",description:"",video_url:"",text_content:"",duration_minutes:""}),I(null)}catch{se.error("Failed to add module")}},Se=async()=>{if(m)try{let Xe=v.video_url.trim()||null;if(M){const nt=await ke();if(!nt)return;Xe=nt}await l.mutateAsync({id:m.id,title:v.title.trim(),description:v.description.trim()||null,video_url:Xe,text_content:v.text_content.trim()||null,duration_minutes:v.duration_minutes?parseInt(v.duration_minutes):null}),se.success("Module updated"),p(null),I(null)}catch{se.error("Failed to update")}},Fe=async Xe=>{if(await Xi("Delete this module?"))try{await o.mutateAsync(Xe),se.success("Module deleted")}catch{se.error("Failed to delete")}},Ne=async Xe=>{if(S.title.trim())try{await c.mutateAsync({module_id:Xe,title:S.title.trim(),resource_type:S.resource_type,url:S.url.trim()||void 0}),se.success("Resource added"),j(null),C({title:"",resource_type:"link",url:""})}catch{se.error("Failed to add resource")}},Ye=async()=>{try{await u.mutateAsync({courseId:n.id,accessRules:[{access_type:"all"}]}),se.success("Access updated: All brokerages / all agents")}catch{se.error("Failed to update access")}},Ve=async Xe=>{const nt=pe.filter(xt=>xt.access_type==="brokerage").map(xt=>xt.brokerage_id),$e=nt.includes(Xe);let Ge;$e?Ge=nt.filter(xt=>xt!==Xe):Ge=[...nt,Xe];const ct=Ge.map(xt=>({access_type:"brokerage",brokerage_id:xt}));try{await u.mutateAsync({courseId:n.id,accessRules:ct}),se.success($e?"Brokerage removed":"Brokerage added")}catch{se.error("Failed to update access")}},qe=async()=>{try{await u.mutateAsync({courseId:n.id,accessRules:[]}),se.success("Access cleared")}catch{se.error("Failed")}},Qe=async(Xe,nt)=>{const $e=nt==="up"?Xe-1:Xe+1;if(!($e<0||$e>=he.length))try{await Promise.all([l.mutateAsync({id:he[Xe].id,sort_order:$e}),l.mutateAsync({id:he[$e].id,sort_order:Xe})])}catch{se.error("Failed to reorder")}},Ue=async()=>{try{await a.mutateAsync({id:n.id,title:ie,description:ae||null}),se.success("Course updated"),me(!1)}catch{se.error("Failed to update")}};return e.jsxs(zs,{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(B,{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(Oe,{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(xj,{className:"h-3.5 w-3.5"}):e.jsx(l7,{className:"h-3.5 w-3.5"}),n.is_sequential?"Sequential":"Free order"]}),e.jsxs("span",{children:[he.length," module",he.length!==1?"s":""]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>{te(n.title),le(n.description||""),me(!0)},children:[e.jsx(Ya,{className:"h-3.5 w-3.5 mr-1"})," Edit"]}),e.jsxs(B,{variant:n.is_published?"secondary":"default",size:"sm",onClick:()=>a.mutateAsync({id:n.id,is_published:!n.is_published}).then(()=>se.success(n.is_published?"Unpublished":"Published")),children:[n.is_published?e.jsx(Ax,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(ya,{className:"h-3.5 w-3.5 mr-1"}),n.is_published?"Unpublish":"Publish"]})]})]}),e.jsxs(Yr,{defaultValue:"modules",className:"w-full",children:[e.jsxs(Zr,{children:[e.jsx(Ht,{value:"modules",children:"Modules"}),e.jsx(Ht,{value:"access",children:"Access & Permissions"}),e.jsx(Ht,{value:"settings",children:"Settings"})]}),e.jsxs(Gt,{value:"modules",className:"mt-6 space-y-4",children:[he.map((Xe,nt)=>e.jsxs(ve,{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(Xe.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:$e=>{$e.stopPropagation(),Qe(nt,"up")},disabled:nt===0,className:"hover:text-foreground disabled:opacity-30",children:e.jsx(_v,{className:"h-3.5 w-3.5"})}),e.jsx("button",{onClick:$e=>{$e.stopPropagation(),Qe(nt,"down")},disabled:nt===he.length-1,className:"hover:text-foreground disabled:opacity-30",children:e.jsx(tl,{className:"h-3.5 w-3.5"})})]})}),e.jsx(Oe,{variant:"outline",className:"shrink-0 font-mono text-xs",children:nt+1}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:Xe.title}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground mt-0.5",children:[Xe.video_url&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(Kr,{className:"h-3 w-3"})," Video"]}),Xe.text_content&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(Fr,{className:"h-3 w-3"})," Text"]}),Xe.duration_minutes&&e.jsxs("span",{children:[Xe.duration_minutes," min"]}),Xe.resources&&Xe.resources.length>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(vd,{className:"h-3 w-3"})," ",Xe.resources.length," resource(s)"]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(B,{size:"sm",variant:"ghost",onClick:$e=>{var Ge;$e.stopPropagation(),p(Xe),g({title:Xe.title,description:Xe.description||"",video_url:Xe.video_url||"",text_content:Xe.text_content||"",duration_minutes:((Ge=Xe.duration_minutes)==null?void 0:Ge.toString())||""})},children:e.jsx(Ya,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"sm",variant:"ghost",className:"text-destructive",onClick:$e=>{$e.stopPropagation(),Fe(Xe.id)},children:e.jsx(Sn,{className:"h-3.5 w-3.5"})})]})]}),E.has(Xe.id)&&e.jsxs("div",{className:"border-t bg-muted/30 p-4 space-y-3",children:[Xe.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:Xe.description}),Xe.video_url&&e.jsxs("div",{className:"text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Video: "}),e.jsx("a",{href:Xe.video_url,target:"_blank",rel:"noreferrer",className:"text-primary hover:underline break-all",children:Xe.video_url})]}),Xe.text_content&&e.jsx("div",{className:"text-sm bg-background rounded-md p-3 border max-h-40 overflow-auto whitespace-pre-wrap",children:Xe.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(B,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>{j(Xe.id),C({title:"",resource_type:"link",url:""})},children:[e.jsx(rn,{className:"h-3 w-3 mr-1"})," Add Resource"]})]}),Xe.resources&&Xe.resources.length>0?e.jsx("div",{className:"space-y-1",children:Xe.resources.map($e=>e.jsxs("div",{className:"flex items-center gap-2 text-sm bg-background rounded p-2 border",children:[e.jsx(Oe,{variant:"outline",className:"text-[10px]",children:$e.resource_type}),e.jsx("span",{className:"flex-1 truncate",children:$e.title}),$e.url&&e.jsx("a",{href:$e.url,target:"_blank",rel:"noreferrer",className:"text-primary hover:underline text-xs",children:"Open"}),e.jsx(B,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0 text-destructive",onClick:()=>d.mutateAsync($e.id),children:e.jsx(Qn,{className:"h-3 w-3"})})]},$e.id))}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"No resources yet"})]})]})]},Xe.id)),e.jsxs(B,{variant:"outline",className:"w-full border-dashed",onClick:()=>{y(!0),g({title:"",description:"",video_url:"",text_content:"",duration_minutes:""})},children:[e.jsx(rn,{className:"h-4 w-4 mr-2"})," Add Module"]})]}),e.jsx(Gt,{value:"access",className:"mt-6 space-y-4",children:e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"Who can access this course?"})}),e.jsxs(Me,{className:"space-y-5",children:[e.jsxs("div",{className:At("flex items-center gap-3 p-4 rounded-xl border-2 cursor-pointer transition-all",Ce?"border-primary bg-primary/5":"border-muted hover:border-muted-foreground/30"),onClick:Ye,children:[e.jsx("div",{className:At("h-10 w-10 rounded-full flex items-center justify-center shrink-0",Ce?"bg-primary/15 text-primary":"bg-muted text-muted-foreground"),children:e.jsx(sl,{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(fn,{checked:Ce,onCheckedChange:Ye})]}),!Ce&&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:Ae.length===0?"No brokerages selected — agents won't see this course":`${Ae.length} brokerage${Ae.length!==1?"s":""} selected`})]}),Ae.length>0&&e.jsx(B,{size:"sm",variant:"ghost",className:"text-xs text-muted-foreground",onClick:qe,children:"Clear all"})]}),e.jsx(xe,{placeholder:"Search brokerages...",value:ne,onChange:Xe=>ce(Xe.target.value),className:"h-9"}),e.jsx("div",{className:"border rounded-lg divide-y max-h-[360px] overflow-auto",children:Pe.length===0?e.jsx("div",{className:"p-4 text-center text-sm text-muted-foreground",children:"No brokerages found"}):Pe.map(Xe=>{const nt=Ae.includes(Xe.id);return e.jsxs("div",{className:At("flex items-center gap-3 px-3 py-2.5 cursor-pointer transition-colors",nt?"bg-primary/5":"hover:bg-muted/50"),onClick:()=>Ve(Xe.id),children:[e.jsx("div",{className:At("h-5 w-5 rounded border-2 flex items-center justify-center shrink-0 transition-colors",nt?"bg-primary border-primary":"border-muted-foreground/30"),children:nt&&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:Xe.name}),nt&&e.jsx(Oe,{variant:"secondary",className:"text-[10px] shrink-0",children:"Active"})]},Xe.id)})})]})]})]})}),e.jsxs(Gt,{value:"settings",className:"mt-6 space-y-4",children:[e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"Course Thumbnail"})}),e.jsx(Me,{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(()=>se.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(Qn,{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(jy,{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:H,type:"file",accept:"image/*",className:"hidden",onChange:async Xe=>{var $e;const nt=($e=Xe.target.files)==null?void 0:$e[0];if(!(!nt||!n)){Z(!0);try{const Ge=nt.name.split(".").pop(),ct=`${n.id}/thumbnail.${Ge}`,{error:xt}=await q.storage.from("lms-thumbnails").upload(ct,nt,{upsert:!0});if(xt)throw xt;const{data:qt}=q.storage.from("lms-thumbnails").getPublicUrl(ct),Vt=`${qt.publicUrl}?t=${Date.now()}`;await a.mutateAsync({id:n.id,thumbnail_url:Vt}),se.success("Thumbnail uploaded")}catch{se.error("Failed to upload thumbnail")}finally{Z(!1),H.current&&(H.current.value="")}}}}),e.jsxs(B,{variant:"outline",size:"sm",disabled:Y,onClick:()=>{var Xe;return(Xe=H.current)==null?void 0:Xe.click()},children:[Y?e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Oa,{className:"h-4 w-4 mr-2"}),Y?"Uploading...":"Upload Thumbnail"]})]})]})})]}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"Course Settings"})}),e.jsxs(Me,{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(fn,{checked:n.is_sequential,onCheckedChange:Xe=>a.mutateAsync({id:n.id,is_sequential:Xe}).then(()=>se.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(fn,{checked:n.is_published,onCheckedChange:Xe=>a.mutateAsync({id:n.id,is_published:Xe}).then(()=>se.success("Updated"))})]})]})]})]})]})]}),e.jsx(Ls,{open:f||!!m,onOpenChange:Xe=>{Xe||(y(!1),p(null))},children:e.jsxs(Ps,{className:"max-w-lg",children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:m?"Edit Module":"Add Module"}),e.jsx(_r,{children:"Configure the module content"})]}),e.jsxs("div",{className:"space-y-4 max-h-[60vh] overflow-auto",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Title"}),e.jsx(xe,{value:v.title,onChange:Xe=>g(nt=>({...nt,title:Xe.target.value})),placeholder:"Module title"})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Description"}),e.jsx(Ms,{value:v.description,onChange:Xe=>g(nt=>({...nt,description:Xe.target.value})),placeholder:"Brief description",rows:2})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Video"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:At("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 Xe;return(Xe=$.current)==null?void 0:Xe.click()},children:[e.jsx("input",{ref:$,type:"file",accept:"video/*",className:"hidden",onChange:Xe=>{var $e;const nt=($e=Xe.target.files)==null?void 0:$e[0];nt&&(I(nt),g(Ge=>({...Ge,video_url:""})))}}),M?e.jsxs("div",{className:"flex items-center justify-center gap-2 text-sm",children:[e.jsx(Kr,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"font-medium text-primary",children:M.name}),e.jsx(B,{type:"button",size:"sm",variant:"ghost",className:"h-6 w-6 p-0",onClick:Xe=>{Xe.stopPropagation(),I(null)},children:e.jsx(Qn,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"flex flex-col items-center gap-1 text-muted-foreground",children:[e.jsx(Oa,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"Click to upload a video file"})]})]}),V&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(Ct,{className:"h-3.5 w-3.5 animate-spin"}),e.jsxs("span",{children:["Uploading to Bunny.net... ",D,"%"]})]}),e.jsx(Fi,{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(xe,{value:v.video_url,onChange:Xe=>g(nt=>({...nt,video_url:Xe.target.value})),placeholder:"YouTube, Vimeo, or Bunny.net URL"})]})]})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Text Content"}),e.jsx(Ms,{value:v.text_content,onChange:Xe=>g(nt=>({...nt,text_content:Xe.target.value})),placeholder:"Additional text content, instructions, notes...",rows:4})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Duration (minutes)"}),e.jsx(xe,{type:"number",value:v.duration_minutes,onChange:Xe=>g(nt=>({...nt,duration_minutes:Xe.target.value})),placeholder:"e.g. 15"})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>{y(!1),p(null),I(null)},children:"Cancel"}),e.jsxs(B,{onClick:m?Se:Ze,disabled:!v.title.trim()||V,children:[V?e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ho,{className:"h-4 w-4 mr-2"}),V?"Uploading...":m?"Save Changes":"Add Module"]})]})]})}),e.jsx(Ls,{open:!!b,onOpenChange:Xe=>{Xe||j(null)},children:e.jsxs(Ps,{children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Add Resource"}),e.jsx(_r,{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(J,{children:"Title"}),e.jsx(xe,{value:S.title,onChange:Xe=>C(nt=>({...nt,title:Xe.target.value})),placeholder:"Resource title"})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Type"}),e.jsxs(is,{value:S.resource_type,onValueChange:Xe=>C(nt=>({...nt,resource_type:Xe})),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"link",children:"Link"}),e.jsx(He,{value:"pdf",children:"PDF"}),e.jsx(He,{value:"template",children:"Template"}),e.jsx(He,{value:"worksheet",children:"Worksheet"})]})]})]}),e.jsxs("div",{children:[e.jsx(J,{children:"URL"}),e.jsx(xe,{value:S.url,onChange:Xe=>C(nt=>({...nt,url:Xe.target.value})),placeholder:"https://..."})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>j(null),children:"Cancel"}),e.jsx(B,{onClick:()=>b&&Ne(b),disabled:!S.title.trim(),children:"Add Resource"})]})]})}),e.jsx(Ls,{open:be,onOpenChange:me,children:e.jsxs(Ps,{children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Edit Course"}),e.jsx(_r,{children:"Update the course title and description"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Title"}),e.jsx(xe,{value:ie,onChange:Xe=>te(Xe.target.value)})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Description"}),e.jsx(Ms,{value:ae,onChange:Xe=>le(Xe.target.value),rows:3})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>me(!1),children:"Cancel"}),e.jsx(B,{onClick:Ue,disabled:!ie.trim(),children:"Save"})]})]})})]})}function Xar(){return at({queryKey:["lms-stats-overview"],queryFn:async()=>{const{data:s,error:t}=await q.rpc("get_lms_stats");if(t)throw t;return s}})}function Qar(){return at({queryKey:["lms-stats-courses"],queryFn:async()=>{const{data:s,error:t}=await q.rpc("get_lms_course_stats");if(t)throw t;return s||[]}})}function Jar(s){return at({queryKey:["lms-stats-agents",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.rpc("get_lms_agent_progress",{p_course_id:s});if(n)throw n;return t||[]},enabled:!!s})}function eir(){const s=Fn(),{data:t,isLoading:n}=Xar(),{data:r,isLoading:a}=Qar(),[i,l]=_.useState(null),{data:o,isLoading:c}=Jar(i),[d,u]=_.useState(""),h=r==null?void 0:r.find(f=>f.course_id===i),m=o==null?void 0:o.filter(f=>{var y,v;return!d||((y=f.agent_name)==null?void 0:y.toLowerCase().includes(d.toLowerCase()))||((v=f.email)==null?void 0:v.toLowerCase().includes(d.toLowerCase()))}),p=[{label:"Total Courses",value:(t==null?void 0:t.total_courses)??0,icon:Sx,color:"text-primary"},{label:"Published",value:(t==null?void 0:t.published_courses)??0,icon:Er,color:"text-emerald-500"},{label:"Enrolled Agents",value:(t==null?void 0:t.total_enrollments)??0,icon:In,color:"text-blue-500"},{label:"Modules Completed",value:(t==null?void 0:t.total_completions)??0,icon:wl,color:"text-amber-500"},{label:"Active (30d)",value:(t==null?void 0:t.active_learners)??0,icon:Nl,color:"text-violet-500"},{label:"Total Modules",value:(t==null?void 0:t.total_modules)??0,icon:bl,color:"text-rose-500"}];return e.jsx(zs,{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(B,{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(mm,{className:"h-7 w-7 text-primary"}),"LevelUp U — Analytics"]}),e.jsx("p",{className:"text-muted-foreground text-sm mt-0.5",children:"Track enrollment, progress, and completion across all courses"})]})]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 xl:grid-cols-6 gap-3",children:p.map(f=>e.jsx(ve,{className:At("transition-all",n&&"animate-pulse"),children:e.jsxs(Me,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(f.icon,{className:At("h-4 w-4",f.color)}),e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:f.label})]}),e.jsx("p",{className:"text-2xl font-bold text-foreground",children:n?"—":f.value})]})},f.label))}),e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-5 gap-6",children:[e.jsxs("div",{className:"xl:col-span-2 space-y-3",children:[e.jsxs("h2",{className:"text-lg font-semibold text-foreground flex items-center gap-2",children:[e.jsx(bl,{className:"h-5 w-5 text-primary"}),"Course Breakdown"]}),a?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(f=>e.jsx(ve,{className:"animate-pulse",children:e.jsx(Me,{className:"p-4",children:e.jsx("div",{className:"h-16 bg-muted rounded"})})},f))}):r!=null&&r.length?e.jsx("div",{className:"space-y-2",children:r.map(f=>{const y=i===f.course_id;return e.jsx(ve,{className:At("cursor-pointer transition-all hover:shadow-md",y?"border-primary ring-1 ring-primary/30 shadow-md":"hover:border-primary/40"),onClick:()=>l(y?null:f.course_id),children:e.jsxs(Me,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between mb-3",children:[e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-semibold text-sm text-foreground truncate",children:f.course_title}),e.jsx(Oe,{variant:f.is_published?"default":"secondary",className:"shrink-0 text-[10px] px-1.5 py-0",children:f.is_published?"Live":"Draft"})]})}),e.jsx(xi,{className:At("h-4 w-4 text-muted-foreground transition-transform shrink-0 ml-2",y&&"rotate-90")})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3 text-center",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-bold text-foreground",children:f.enrolled_agents}),e.jsx("p",{className:"text-[10px] text-muted-foreground uppercase tracking-wide",children:"Enrolled"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-bold text-foreground",children:f.total_completions}),e.jsx("p",{className:"text-[10px] text-muted-foreground uppercase tracking-wide",children:"Completed"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-bold text-foreground",children:f.total_modules}),e.jsx("p",{className:"text-[10px] text-muted-foreground uppercase tracking-wide",children:"Modules"})]})]}),e.jsxs("div",{className:"mt-3",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[e.jsx("span",{className:"text-muted-foreground",children:"Avg. Completion"}),e.jsxs("span",{className:"font-semibold text-foreground",children:[f.avg_completion_pct,"%"]})]}),e.jsx(Fi,{value:f.avg_completion_pct,className:"h-2"})]})]})},f.course_id)})}):e.jsx(ve,{className:"border-dashed",children:e.jsx(Me,{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(gj,{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(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{value:d,onChange:f=>u(f.target.value),placeholder:"Search agents...",className:"pl-9"})]}),c?e.jsx("div",{className:"space-y-2",children:[1,2,3,4].map(f=>e.jsx(ve,{className:"animate-pulse",children:e.jsx(Me,{className:"p-4",children:e.jsx("div",{className:"h-12 bg-muted rounded"})})},f))}):m!=null&&m.length?e.jsx("div",{className:"space-y-2 max-h-[600px] overflow-y-auto pr-1",children:m.map((f,y)=>{const v=f.completion_pct>=100;return e.jsx(ve,{className:At("transition-all",v&&"border-emerald-200 bg-emerald-50/30 dark:border-emerald-900/40 dark:bg-emerald-950/10"),children:e.jsx(Me,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:At("flex items-center justify-center w-7 h-7 rounded-full text-xs font-bold shrink-0",y===0?"bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400":y===1?"bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-400":y===2?"bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400":"bg-muted text-muted-foreground"),children:y+1}),e.jsxs(ja,{className:"h-9 w-9 shrink-0",children:[e.jsx(pi,{src:f.avatar_url||void 0}),e.jsx(Na,{className:"text-xs bg-primary/10 text-primary",children:(f.agent_name||f.email||"?").charAt(0).toUpperCase()})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"text-sm font-medium text-foreground truncate",children:f.agent_name||f.email}),v&&e.jsxs(Oe,{variant:"default",className:"text-[10px] px-1.5 py-0 bg-emerald-500 hover:bg-emerald-600 shrink-0",children:[e.jsx(Er,{className:"h-3 w-3 mr-0.5"})," Complete"]})]}),e.jsxs("div",{className:"flex items-center gap-3 text-[11px] text-muted-foreground mt-0.5",children:[e.jsxs("span",{children:[f.modules_completed,"/",f.total_modules," modules"]}),f.last_activity&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Gr,{className:"h-3 w-3"}),Hs(new Date(f.last_activity),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"text-right shrink-0 w-20",children:[e.jsxs("p",{className:At("text-sm font-bold",v?"text-emerald-600 dark:text-emerald-400":"text-foreground"),children:[f.completion_pct,"%"]}),e.jsx(Fi,{value:f.completion_pct,className:"h-1.5 mt-1"})]})]})})},f.user_id)})}):e.jsx(ve,{className:"border-dashed",children:e.jsx(Me,{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(ve,{className:"border-dashed",children:e.jsxs(Me,{className:"py-16 text-center",children:[e.jsx(In,{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 tir(){const{user:s}=hs(),t=Fn(),{data:n,isLoading:r}=Gar();return e.jsx(zs,{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(mm,{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(ve,{className:"animate-pulse",children:e.jsxs(Me,{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(sir,{course:a,userId:s==null?void 0:s.id,onClick:()=>t(`/levelup-u/${a.id}`)},a.id))}):e.jsx(ve,{className:"border-dashed",children:e.jsxs(Me,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(Sx,{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 sir({course:s,userId:t,onClick:n}){var o;const r=((o=s.modules)==null?void 0:o.length)??0,{data:a}=ias(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(ve,{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(mm,{className:"h-10 w-10 text-primary/40"})}),e.jsxs(Me,{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(Sx,{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(xj,{className:"h-3.5 w-3.5"}):e.jsx(l7,{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(Fi,{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(xi,{className:"h-3.5 w-3.5"})]})})]})]})}function nir(){const{courseId:s}=Li(),t=Fn(),{user:n}=hs(),{data:r,isLoading:a}=War(s),{data:i}=ias(s),l=Kar(),[o,c]=_.useState(null),d=(r==null?void 0:r.modules)||[],u=new Set((i==null?void 0:i.filter(b=>b.completed).map(b=>b.module_id))||[]),h=u.size,m=d.length>0?Math.round(h/d.length*100):0;_.useEffect(()=>{if(d.length>0&&!o){const b=d.find(j=>!u.has(j.id));c((b==null?void 0:b.id)||d[0].id)}},[d,o,u]);const p=d.find(b=>b.id===o),f=d.findIndex(b=>b.id===o),y=(b,j)=>{if(!(r!=null&&r.is_sequential)||j===0)return!1;for(let S=0;S{if(!(!p||!n||!s))try{await l.mutateAsync({courseId:s,moduleId:p.id,userId:n.id}),se.success("Module completed! 🎉"),f{const j=b.match(/(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([a-zA-Z0-9_-]{11})/);if(j)return`https://www.youtube.com/embed/${j[1]}`;const S=b.match(/vimeo\.com\/(\d+)/);if(S)return`https://player.vimeo.com/video/${S[1]}`;const C=b.match(/(?:iframe\.mediadelivery\.net|video\.bunnycdn\.com)\/(?:play|embed)\/(\d+)\/([a-f0-9-]+)/);return C?`https://iframe.mediadelivery.net/embed/${C[1]}/${C[2]}?responsive=true`:b};return a?e.jsx(zs,{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(zs,{title:r.title,children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(B,{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(Fi,{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(ve,{className:"lg:sticky lg:top-4",children:e.jsxs(Me,{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(Ji,{className:"max-h-[calc(100vh-280px)]",children:e.jsx("div",{className:"p-1",children:d.map((b,j)=>{const S=y(b,j),C=u.has(b.id),E=b.id===o;return e.jsxs("button",{disabled:S,onClick:()=>!S&&c(b.id),className:At("w-full flex items-center gap-3 p-3 rounded-lg text-left transition-all text-sm",E?"bg-primary/10 text-primary":"hover:bg-muted/50",S&&"opacity-50 cursor-not-allowed"),children:[e.jsx("div",{className:"shrink-0",children:S?e.jsx(ec,{className:"h-4 w-4 text-muted-foreground"}):C?e.jsx(Er,{className:"h-4 w-4 text-green-500"}):e.jsx(Uf,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:At("font-medium truncate",E&&"text-primary"),children:[j+1,". ",b.title]}),b.duration_minutes&&e.jsxs("span",{className:"text-[11px] text-muted-foreground flex items-center gap-0.5 mt-0.5",children:[e.jsx(Gr,{className:"h-3 w-3"})," ",b.duration_minutes," min"]})]})]},b.id)})})})]})}),e.jsx("div",{className:"space-y-4",children:p?e.jsxs(e.Fragment,{children:[p.video_url&&e.jsx(ve,{className:"overflow-hidden",children:e.jsx("div",{className:"aspect-video bg-black",children:e.jsx("iframe",{src:g(p.video_url),className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})}),e.jsx(ve,{children:e.jsxs(Me,{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(Oe,{className:"bg-green-500/15 text-green-600 border-green-500/30 shrink-0",children:[e.jsx(Er,{className:"h-3.5 w-3.5 mr-1"})," Completed"]}):e.jsxs(B,{size:"sm",onClick:v,disabled:l.isPending,children:[e.jsx(Er,{className:"h-4 w-4 mr-1"}),"Mark Complete"]})]}),p.text_content&&e.jsx("div",{className:"prose prose-sm max-w-none text-foreground border-t pt-4 whitespace-pre-wrap",children:p.text_content}),p.resources&&p.resources.length>0&&e.jsxs("div",{className:"border-t pt-4",children:[e.jsx("p",{className:"text-sm font-medium mb-2",children:"Resources"}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:p.resources.map(b=>e.jsxs("a",{href:b.url||b.file_url||"#",target:"_blank",rel:"noreferrer",className:"flex items-center gap-2 p-3 rounded-lg border hover:bg-muted/50 transition-colors text-sm",children:[b.resource_type==="pdf"?e.jsx(Fr,{className:"h-4 w-4 text-red-500 shrink-0"}):b.resource_type==="template"?e.jsx(mm,{className:"h-4 w-4 text-purple-500 shrink-0"}):e.jsx(vd,{className:"h-4 w-4 text-blue-500 shrink-0"}),e.jsx("span",{className:"flex-1 truncate",children:b.title}),e.jsx(wr,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"})]},b.id))})]}),e.jsxs("div",{className:"flex items-center justify-between border-t pt-4",children:[e.jsxs(B,{variant:"outline",size:"sm",disabled:f===0,onClick:()=>f>0&&c(d[f-1].id),children:[e.jsx(ka,{className:"h-3.5 w-3.5 mr-1"})," Previous"]}),fc(d[f+1].id),children:["Next ",e.jsx(xi,{className:"h-3.5 w-3.5 ml-1"})]}):m===100&&e.jsx(Oe,{className:"bg-green-500/15 text-green-600 border-green-500/30 text-sm px-3 py-1.5",children:"🎉 Course Complete!"})]})]})})]}):e.jsx(ve,{children:e.jsx(Me,{className:"flex items-center justify-center py-16 text-muted-foreground",children:"Select a module to begin"})})})]})]})}):e.jsx(zs,{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(B,{variant:"outline",className:"mt-4",onClick:()=>t("/levelup-u"),children:[e.jsx(ka,{className:"h-4 w-4 mr-2"})," Back"]})]})})}function rir({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(Sr.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(Sr.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(Sr.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(Sr.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(Sr.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(La,{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(Sr.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 Fj({children:s,className:t="",delay:n=0,direction:r="up"}){const a=_.useRef(null),i=kRs(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(Sr.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 air({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(Fj,{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(Fj,{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 iir({images:s,primaryColor:t,accentColor:n}){const[r,a]=_.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(Fj,{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(In,{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(Fj,{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(Qn,{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 oir({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(Fj,{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(Fj,{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(pS,{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 lir({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(Fj,{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(Fj,{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(J,{className:"text-gray-700 text-sm font-medium",children:"First Name *"}),e.jsx(xe,{required:!0,value:s.first_name,onChange:l=>t(o=>({...o,first_name:l.target.value})),className:"h-11 rounded-lg border-gray-200 focus:border-gray-400 transition-colors",placeholder:"John"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-gray-700 text-sm font-medium",children:"Last Name"}),e.jsx(xe,{value:s.last_name,onChange:l=>t(o=>({...o,last_name:l.target.value})),className:"h-11 rounded-lg border-gray-200 focus:border-gray-400 transition-colors",placeholder:"Smith"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-gray-700 text-sm font-medium",children:"Email *"}),e.jsx(xe,{type:"email",required:!0,value:s.email,onChange:l=>t(o=>({...o,email:l.target.value})),className:"h-11 rounded-lg border-gray-200 focus:border-gray-400 transition-colors",placeholder:"john@email.com"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-gray-700 text-sm font-medium",children:"Phone"}),e.jsx(xe,{value:s.phone,onChange:l=>t(o=>({...o,phone:l.target.value})),className:"h-11 rounded-lg border-gray-200 focus:border-gray-400 transition-colors",placeholder:"(555) 123-4567"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-gray-700 text-sm font-medium",children:"Current Brokerage"}),e.jsx(xe,{value:s.current_brokerage,onChange:l=>t(o=>({...o,current_brokerage:l.target.value})),className:"h-11 rounded-lg border-gray-200 focus:border-gray-400 transition-colors",placeholder:"Your current brokerage name"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-gray-700 text-sm font-medium",children:"License #"}),e.jsx(xe,{value:s.license_number,onChange:l=>t(o=>({...o,license_number:l.target.value})),className:"h-11 rounded-lg border-gray-200 focus:border-gray-400 transition-colors"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-gray-700 text-sm font-medium",children:"Years Experience"}),e.jsx(xe,{type:"number",min:"0",value:s.experience_years,onChange:l=>t(o=>({...o,experience_years:l.target.value})),className:"h-11 rounded-lg border-gray-200 focus:border-gray-400 transition-colors"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-gray-700 text-sm font-medium",children:"Annual Production"}),e.jsx(xe,{value:s.annual_production,onChange:l=>t(o=>({...o,annual_production:l.target.value})),className:"h-11 rounded-lg border-gray-200 focus:border-gray-400 transition-colors",placeholder:"e.g. $5M, 20 transactions"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-gray-700 text-sm font-medium",children:"Why are you interested?"}),e.jsx(Ms,{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(B,{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(La,{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(Rm,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Your information is confidential and will not be shared."})]})]})})]})]})}function cir({form:s,setForm:t,onSubmit:n,isPending:r,primaryColor:a,accentColor:i,showConfidentialBadges:l=!0}){const[o,c]=_.useState(1),[d,u]=_.useState(""),h=3,m=!!s.first_name&&!!s.email,p=f=>{u(f),t(y=>({...y,why_interested:f})),setTimeout(()=>c(2),200)};return e.jsxs("section",{id:"apply",className:"py-24 md:py-32 px-6 relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 top-0 h-1/2",style:{background:`linear-gradient(160deg, ${i}, ${a})`}}),e.jsx("div",{className:"absolute inset-0 top-1/2 bg-gray-50"}),e.jsxs("div",{className:"relative z-10 max-w-xl mx-auto",children:[e.jsx(Fj,{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(ec,{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(Fj,{delay:.15,children:e.jsxs("div",{className:"bg-white rounded-3xl shadow-2xl p-8 md:p-10",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-7",children:[[1,2,3].map(f=>e.jsx("div",{className:"h-1 flex-1 rounded-full transition-colors duration-500",style:{backgroundColor:f<=o?a:"#e5e7eb"}},f)),e.jsxs("span",{className:"text-xs text-gray-400 ml-2",children:[o,"/",h]})]}),e.jsxs(mW,{mode:"wait",children:[o===1&&e.jsxs(Sr.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:-20},transition:{duration:.25},className:"space-y-3",children:[e.jsx("h3",{className:"text-lg font-semibold mb-1",style:{color:i},children:"What's most important to you?"}),e.jsx("p",{className:"text-sm text-gray-500 mb-5",children:"Pick the one that resonates most. We'll tailor the conversation."}),[{val:"Better commission split / cap",label:"Better Splits & Caps",icon:"💰"},{val:"Better technology and tools",label:"Better Tech & Tools",icon:"🛠️"},{val:"Better training and mentorship",label:"Better Training",icon:"📚"},{val:"Better culture and team",label:"Better Culture",icon:"🤝"},{val:"Just exploring options confidentially",label:"Just Exploring",icon:"🔍"}].map(f=>e.jsxs("button",{type:"button",onClick:()=>p(f.val),className:"w-full flex items-center gap-3 p-4 rounded-xl border-2 border-gray-100 hover:border-gray-300 transition-all text-left group",children:[e.jsx("span",{className:"text-2xl",children:f.icon}),e.jsx("span",{className:"font-medium text-gray-700 group-hover:text-gray-900 flex-1",children:f.label}),e.jsx(La,{className:"h-4 w-4 text-gray-300 group-hover:text-gray-500 group-hover:translate-x-1 transition-all"})]},f.val))]},"step1"),o===2&&e.jsxs(Sr.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(J,{className:"text-gray-700 text-sm font-medium",children:"First Name *"}),e.jsx(xe,{required:!0,value:s.first_name,onChange:f=>t(y=>({...y,first_name:f.target.value})),className:"h-11",placeholder:"John"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-gray-700 text-sm font-medium",children:"Last Name"}),e.jsx(xe,{value:s.last_name,onChange:f=>t(y=>({...y,last_name:f.target.value})),className:"h-11",placeholder:"Smith"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-gray-700 text-sm font-medium",children:"Email *"}),e.jsx(xe,{type:"email",required:!0,value:s.email,onChange:f=>t(y=>({...y,email:f.target.value})),className:"h-11",placeholder:"john@email.com"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-gray-700 text-sm font-medium",children:"Phone (preferred)"}),e.jsx(xe,{value:s.phone,onChange:f=>t(y=>({...y,phone:f.target.value})),className:"h-11",placeholder:"(555) 123-4567"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs(B,{type:"button",variant:"ghost",onClick:()=>c(1),className:"h-11",children:[e.jsx(ka,{className:"h-4 w-4 mr-1"})," Back"]}),e.jsxs(B,{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(La,{className:"h-4 w-4 ml-1"})]})]})]},"step2"),o===3&&e.jsxs(Sr.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(J,{className:"text-gray-700 text-sm font-medium",children:"Current Brokerage"}),e.jsx(xe,{value:s.current_brokerage,onChange:f=>t(y=>({...y,current_brokerage:f.target.value})),className:"h-11",placeholder:"(stays private)"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-gray-700 text-sm font-medium",children:"Years Experience"}),e.jsx(xe,{type:"number",min:"0",value:s.experience_years,onChange:f=>t(y=>({...y,experience_years:f.target.value})),className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-gray-700 text-sm font-medium",children:"Annual Production"}),e.jsx(xe,{value:s.annual_production,onChange:f=>t(y=>({...y,annual_production:f.target.value})),className:"h-11",placeholder:"e.g. $5M"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-gray-700 text-sm font-medium",children:"Anything else?"}),e.jsx(Ms,{value:s.why_interested,onChange:f=>t(y=>({...y,why_interested:f.target.value})),rows:2,className:"resize-none",placeholder:"Optional message..."})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs(B,{type:"button",variant:"ghost",onClick:()=>c(2),className:"h-11",children:[e.jsx(ka,{className:"h-4 w-4 mr-1"})," Back"]}),e.jsx(B,{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(ea,{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(Rm,{className:"h-3 w-3"})," Confidential"]}),e.jsxs("div",{className:"flex items-center gap-1 justify-center",children:[e.jsx(Hi,{className:"h-3 w-3"})," Text first"]}),e.jsxs("div",{className:"flex items-center gap-1 justify-center",children:[e.jsx(_a,{className:"h-3 w-3"})," No spam"]})]})]})})]})]})}function dir({config:s,primaryColor:t,accentColor:n,brokerageId:r,brokerageName:a}){const{toast:i}=vi(),[l,o]=_.useState("250000"),[c,d]=_.useState("12"),[u,h]=_.useState("70"),[m,p]=_.useState("150"),[f,y]=_.useState(""),[v,g]=_.useState(!1),[b,j]=_.useState(!1),S=s.commission_split_pct??80,C=s.cap_amount??16e3,E=s.post_cap_split_pct??100,P=s.monthly_fee??99,M=s.transaction_fee??0,I=_.useMemo(()=>{const V=parseFloat(l)||0,G=Math.max(0,parseInt(c,10)||0),$=parseFloat(u)||0,H=parseFloat(m)||0,Y=V*($/100)-H*12-M*G,Z=1-S/100,ne=Z>0?C/Z:V,ce=Math.min(V,ne),ie=Math.max(0,V-ne),te=ce*Z+ie*(1-E/100),ae=V-te-P*12-M*G,le=ae-Y;return{currentNet:Y,newNet:ae,diff:le}},[l,c,u,m,S,C,E,P,M]),D=V=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(V),O=async V=>{if(V.preventDefault(),!!f){j(!0);try{const{error:G}=await q.from("recruit_lead_magnet_downloads").insert({brokerage_id:r,email:f,source:"calculator"});if(G)throw G;const{error:$}=await q.functions.invoke("send-calculator-breakdown",{body:{brokerage_id:r,brokerage_name:a,email:f,inputs:{gci:parseFloat(l)||0,transactions:parseInt(c,10)||0,current_split_pct:parseFloat(u)||0,current_monthly_fee:parseFloat(m)||0},plan:{commission_split_pct:S,cap_amount:C,post_cap_split_pct:E,monthly_fee:P,transaction_fee:M},result:I,primary_color:t,accent_color:n}});$&&console.error("Breakdown email failed:",$),g(!0),i({title:"Sent!",description:"Check your email for the full breakdown."})}catch(G){i({title:"Error",description:G.message,variant:"destructive"})}finally{j(!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(Fj,{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(ec,{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(Fj,{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(uj,{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(J,{className:"text-gray-600 text-sm",children:"Your GCI Last 12 Months"}),e.jsxs("div",{className:"relative mt-1.5",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-sm",children:"$"}),e.jsx(xe,{type:"number",value:l,onChange:V=>o(V.target.value),className:"pl-7 h-11 text-base",placeholder:"250,000"})]})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-gray-600 text-sm",children:"Transactions per Year"}),e.jsx(xe,{type:"number",min:"0",value:c,onChange:V=>d(V.target.value),className:"mt-1.5 h-11 text-base",placeholder:"12"})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-gray-600 text-sm",children:"Your Current Commission Split (%)"}),e.jsx(xe,{type:"number",value:u,onChange:V=>h(V.target.value),className:"mt-1.5 h-11 text-base",placeholder:"70"})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-gray-600 text-sm",children:"Your Current Monthly Fees"}),e.jsxs("div",{className:"relative mt-1.5",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-sm",children:"$"}),e.jsx(xe,{type:"number",value:m,onChange:V=>p(V.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(Nl,{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(Sr.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&&!v&&e.jsxs("form",{onSubmit:O,className:"mt-6 space-y-2",children:[e.jsx("p",{className:"text-white/80 text-xs",children:s.email_capture_label||"Want the full breakdown? Enter your email."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{type:"email",required:!0,value:f,onChange:V=>y(V.target.value),placeholder:"you@email.com",className:"bg-white/95 border-0 text-gray-900 h-10 text-sm"}),e.jsx(B,{type:"submit",disabled:b,className:"h-10 bg-white text-gray-900 hover:bg-white/90 text-sm font-semibold",children:"Send"})]})]}),v&&e.jsxs("div",{className:"mt-6 flex items-center gap-2 text-sm text-white/90 bg-white/10 rounded-lg p-3",children:[e.jsx(ea,{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 uir({config:s,primaryColor:t,accentColor:n,brokerageId:r}){const{toast:a}=vi(),[i,l]=_.useState(""),[o,c]=_.useState(""),[d,u]=_.useState(!1),[h,m]=_.useState(!1),p=async f=>{f.preventDefault(),m(!0);try{const{error:y}=await q.from("recruit_lead_magnet_downloads").insert({brokerage_id:r,email:i,first_name:o||null,source:"lead_magnet",user_agent:navigator.userAgent,referrer:document.referrer||null});if(y)throw y;u(!0),s.pdf_url&&window.open(s.pdf_url,"_blank","noopener,noreferrer")}catch(y){a({title:"Error",description:y.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(Fj,{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(hj,{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(ec,{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(ea,{className:"h-5 w-5 shrink-0"}),e.jsxs("span",{children:["Sent! ",s.pdf_url?"Your download should open in a new tab.":"Check your email shortly."]})]}):e.jsxs("form",{onSubmit:p,className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsx(xe,{value:o,onChange:f=>c(f.target.value),placeholder:"First name (optional)",className:"h-11"}),e.jsx(xe,{type:"email",required:!0,value:i,onChange:f=>l(f.target.value),placeholder:"your@email.com",className:"h-11"})]}),e.jsxs(B,{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(hj,{className:"h-4 w-4 mr-2"}),h?"Sending...":s.button_text||"Email Me the PDF"]})]})]})]})})})})})}function hir(){const{slug:s}=Li(),{toast:t}=vi(),[n,r]=_.useState(!1),[a,i]=_.useState({first_name:"",last_name:"",email:"",phone:"",current_brokerage:"",experience_years:"",annual_production:"",license_number:"",why_interested:""});_.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(G=>document.querySelectorAll(G).forEach($=>$.style.display="none"))};I();const D=[setTimeout(I,500),setTimeout(I,1500),setTimeout(I,3e3)],O=new MutationObserver(I);return O.observe(document.body,{childList:!0,subtree:!0}),()=>{document.body.classList.remove("recruit-landing-page"),D.forEach(clearTimeout),O.disconnect()}},[]);const{data:l,isLoading:o,error:c}=at({queryKey:["recruit-form-brokerage",s],queryFn:async()=>{const{data:I,error:D}=await q.from("brokerages").select("id, name, recruit_form_enabled").eq("recruit_form_slug",s).single();if(D)throw D;return I},enabled:!!s}),{data:d}=at({queryKey:["recruit-landing-public",l==null?void 0:l.id],queryFn:async()=>{const{data:I,error:D}=await q.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=mt({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 q.from("recruit_interest_submissions").insert(I);if(D)throw D;q.functions.invoke("recruit-lead-notify",{body:{lead:I,brokerage_id:l.id}}).catch(O=>console.error("Lead notification error:",O))},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",f=(h==null?void 0:h.benefits)||[],y=(h==null?void 0:h.testimonials)||[],v=(h==null?void 0:h.gallery_images)||[],g=(h==null?void 0:h.hero_headline)||`Join ${l.name}`,b=(h==null?void 0:h.hero_subtext)||"Take your real estate career to the next level with a brokerage that invests in your growth.",j=(h==null?void 0:h.calculator_enabled)===!0,S=(h==null?void 0:h.calculator_config)||{},C=(h==null?void 0:h.lead_magnet_enabled)===!0,E=(h==null?void 0:h.lead_magnet_config)||{},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(Sr.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(ea,{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(La,{className:"h-3.5 w-3.5"})]})]})}),e.jsx(rir,{headline:g,subtext:b,primaryColor:m,accentColor:p,heroImageUrl:h==null?void 0:h.hero_image_url,logoUrl:h==null?void 0:h.logo_url,brokerageName:l.name}),e.jsx(air,{benefits:f,accentColor:p,primaryColor:m}),e.jsx(iir,{images:v,primaryColor:m,accentColor:p}),e.jsx(oir,{testimonials:y,primaryColor:m,accentColor:p}),j&&e.jsx(dir,{config:S,primaryColor:m,accentColor:p,brokerageId:l.id,brokerageName:l.name}),C&&e.jsx(uir,{config:E,primaryColor:m,accentColor:p,brokerageId:l.id}),P==="multi_step"?e.jsx(cir,{form:a,setForm:i,onSubmit:()=>u.mutate(),isPending:u.isPending,primaryColor:m,accentColor:p,showConfidentialBadges:M}):e.jsx(lir,{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 mir(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 pir(){var m,p,f,y;const{shareToken:s}=Li(),t=_.useRef(!1),{data:n,isLoading:r,error:a}=at({queryKey:["public-recruit-video",s],queryFn:async()=>{var C;if(!s)throw new Error("No token");const{data:v,error:g}=await q.from("recruit_videos").select(` *, prospect:recruit_prospects(first_name, last_name), video:agent_videos(id, title, playback_url, thumbnail_url, duration_seconds, owner_user_id) `).eq("share_token",s).single();if(g)throw g;const{data:b}=await q.from("profiles").select("name, avatar_url, title, recruit_cta_url").eq("id",(C=v.video)==null?void 0:C.owner_user_id).single(),{data:j}=await q.from("brokerages").select("name").eq("id",v.brokerage_id).single(),{data:S}=await q.from("recruit_landing_page_settings").select("logo_url, primary_color, accent_color, hero_headline").eq("brokerage_id",v.brokerage_id).maybeSingle();return{rv:v,profile:b,brokerage:j,settings:S}},enabled:!!s});if(_.useEffect(()=>{var v;!((v=n==null?void 0:n.rv)!=null&&v.id)||t.current||(t.current=!0,q.rpc("log_recruit_video_view",{p_recruit_video_id:n.rv.id,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null}).then(()=>{}))},[(m=n==null?void 0:n.rv)==null?void 0:m.id]),r)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})});if(a||!n)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsx("p",{className:"text-muted-foreground",children:"This video is no longer available."})});const{rv:i,profile:l,brokerage:o,settings:c}=n,d=(c==null?void 0:c.primary_color)||"#3b82f6",u=((p=i.prospect)==null?void 0:p.first_name)||"there",h=(f=i.video)!=null&&f.playback_url?mir(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:((y=l==null?void 0:l.name)==null?void 0:y.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(B,{size:"lg",asChild:!0,className:"text-white shadow-lg hover:shadow-xl transition-shadow px-8",style:{backgroundColor:d},onClick:()=>{q.from("recruit_videos").update({cta_clicked_at:new Date().toISOString()}).eq("id",i.id).then(()=>{})},children:e.jsxs("a",{href:l.recruit_cta_url,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(ga,{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 fir="relzejiswnotikjgvjhz",Y4t=`https://${fir}.supabase.co/functions/v1/recruit-unsubscribe`;function xir(){const[s]=Yl(),t=s.get("token")||"",[n,r]=_.useState(!0),[a,i]=_.useState(!1),[l,o]=_.useState(!1),[c,d]=_.useState(""),[u,h]=_.useState({});_.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(g=>document.querySelectorAll(g).forEach(b=>b.style.display="none"))};p();const f=[setTimeout(p,500),setTimeout(p,1500),setTimeout(p,3e3)],y=new MutationObserver(p);return y.observe(document.body,{childList:!0,subtree:!0}),()=>{document.body.classList.remove("recruit-unsubscribe-page"),f.forEach(clearTimeout),y.disconnect()}},[]),_.useEffect(()=>{if(!t){h({error:"Missing unsubscribe token in link."}),r(!1);return}fetch(`${Y4t}?token=${encodeURIComponent(t)}`).then(async p=>{const f=await p.json();if(!p.ok)throw new Error(f.error||"Lookup failed");h(f),f.already_unsubscribed&&o(!0)}).catch(p=>h({error:p.message||"Could not load status"})).finally(()=>r(!1))},[t]);const m=async()=>{i(!0);try{const p=await fetch(Y4t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t,reason:c.trim()||null})}),f=await p.json();if(!p.ok)throw new Error(f.error||"Failed");o(!0)}catch(p){h({...u,error:p.message||"Could not unsubscribe"})}finally{i(!1)}};return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-50 via-white to-slate-100 flex items-center justify-center p-6",children:e.jsx("div",{className:"w-full max-w-lg bg-white rounded-2xl shadow-xl border border-slate-200 p-8 sm:p-10",children:n?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 gap-3 text-slate-500",children:[e.jsx(Ct,{className:"h-8 w-8 animate-spin"}),e.jsx("p",{className:"text-sm",children:"Loading…"})]}):u.error?e.jsxs("div",{className:"text-center space-y-3",children:[e.jsx("div",{className:"mx-auto w-14 h-14 rounded-full bg-red-50 flex items-center justify-center",children:e.jsx(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(Er,{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(Dm,{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(Dm,{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(J,{htmlFor:"reason",className:"text-xs text-slate-500",children:"Optional — what's the main reason? (helps us improve)"}),e.jsx(Ms,{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(B,{onClick:m,disabled:a,className:"w-full h-11",variant:"default",children:a?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),"Unsubscribing…"]}):"Confirm Unsubscribe"}),e.jsx("p",{className:"text-[11px] text-slate-400 text-center",children:"No login required. We process your request instantly."})]})})})}const gir="relzejiswnotikjgvjhz",Z4t=`https://${gir}.supabase.co/functions/v1/event-invite-unsubscribe`;function yir(){const[s]=Yl(),t=s.get("token")||"",[n,r]=_.useState(!0),[a,i]=_.useState(!1),[l,o]=_.useState(!1),[c,d]=_.useState({});_.useEffect(()=>(document.body.classList.add("event-invite-unsubscribe-page"),()=>{document.body.classList.remove("event-invite-unsubscribe-page")}),[]),_.useEffect(()=>{if(!t){d({error:"Missing unsubscribe token in link."}),r(!1);return}fetch(`${Z4t}?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(Z4t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t})}),m=await h.json();if(!h.ok)throw new Error(m.error||"Failed");o(!0)}catch(h){d({...c,error:h.message||"Could not unsubscribe"})}finally{i(!1)}};return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-50 via-white to-slate-100 flex items-center justify-center p-6",children:e.jsx("div",{className:"w-full max-w-lg bg-white rounded-2xl shadow-xl border border-slate-200 p-8 sm:p-10",children:n?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 gap-3 text-slate-500",children:[e.jsx(Ct,{className:"h-8 w-8 animate-spin"}),e.jsx("p",{className:"text-sm",children:"Loading…"})]}):c.error?e.jsxs("div",{className:"text-center space-y-3",children:[e.jsx("div",{className:"mx-auto w-14 h-14 rounded-full bg-red-50 flex items-center justify-center",children:e.jsx(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(Er,{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(Dm,{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(wQ,{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(B,{onClick:u,disabled:a,className:"w-full h-11",variant:"default",children:a?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),"Unsubscribing…"]}):"Unsubscribe from event invites only"}),e.jsx("p",{className:"text-[11px] text-slate-400 text-center",children:"No login required. You can re-enable event invites anytime in your Profile."})]})})})}function vir(){const s=Fn(),t=Bt(),{isAdmin:n}=hs(),[r,a]=_.useState(!1),[i,l]=_.useState(null),[o,c]=_.useState(null),{data:d,isLoading:u}=at({queryKey:["my-social-accounts"],queryFn:async()=>{const{data:{user:C},error:E}=await q.auth.getUser();if(E)throw E;if(!C)return[];const{data:P,error:M}=await q.from("social_accounts").select("*").eq("user_id",C.id).order("created_at",{ascending:!1});if(M)throw M;return P}}),h=mt({mutationFn:async C=>{const{data:{user:E},error:P}=await q.auth.getUser();if(P)throw P;if(!E)throw new Error("Not authenticated");const{error:M}=await q.from("social_accounts").delete().eq("id",C).eq("user_id",E.id);if(M)throw M},onSuccess:()=>{t.invalidateQueries({queryKey:["my-social-accounts"]}),t.invalidateQueries({queryKey:["social-accounts-for-post"]}),se.success("Account disconnected successfully")},onError:()=>{se.error("Failed to disconnect account")}}),m=async C=>{a(!0),sessionStorage.setItem("social-connect-return-to",window.location.pathname);try{const{data:E,error:P}=await q.functions.invoke("meta-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/callback",authMode:C}});if(P)throw P;if(E!=null&&E.authUrl)window.location.href=E.authUrl;else throw new Error("Failed to get authorization URL")}catch(E){console.error("Meta OAuth error:",E),se.error("Failed to start connection. Please try again."),a(!1)}},p=async()=>{a(!0);try{const{data:C,error:E}=await q.functions.invoke("linkedin-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/linkedin-callback"}});if(E)throw E;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),se.error("Failed to start LinkedIn connection. Please try again."),a(!1)}},f=async()=>{a(!0);try{const{data:C,error:E}=await q.functions.invoke("google-business-oauth",{body:{action:"get_auth_url",returnPath:"/social-connections"}});if(E)throw E;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),se.error("Failed to start Google connection. Please try again."),a(!1)}},y=(d==null?void 0:d.filter(C=>C.platform==="facebook"))||[],v=(d==null?void 0:d.filter(C=>C.platform==="instagram"))||[],g=(d==null?void 0:d.filter(C=>C.platform==="linkedin"))||[],b=(d==null?void 0:d.filter(C=>C.platform==="google_business"))||[],j=((d==null?void 0:d.length)||0)>0,S=async(C,E)=>{l(C),c(null);try{const{data:P,error:M}=await q.functions.invoke("meta-api-test",{body:{testType:"all",accountId:C}});if(M)throw M;c(P.results||[]),se.success(P.summary||"API tests completed")}catch(P){console.error("Meta API test error:",P),se.error("Failed to run API tests")}finally{l(null)}};return e.jsx(zs,{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(Oe,{variant:"secondary",className:"bg-white/20 text-white border-0 backdrop-blur-sm",children:[e.jsx(un,{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(B,{variant:"ghost",onClick:()=>s("/social-studio"),className:"gap-2",children:[e.jsx(ka,{className:"h-4 w-4"}),"Back to Social Studio"]}),j&&e.jsx(ve,{className:"border-green-200 bg-green-50 dark:bg-green-950/20 dark:border-green-900",children:e.jsxs(Me,{className:"flex items-center gap-4 p-4",children:[e.jsx("div",{className:"rounded-full bg-green-500 p-2",children:e.jsx(_l,{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(ve,{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(tf,{className:"h-6 w-6 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(St,{className:"text-lg",children:"Facebook"}),e.jsx(kn,{children:"Connect your Facebook Page"})]})]})}),e.jsxs(Me,{className:"space-y-4",children:[u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(uo,{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(ja,{className:"h-10 w-10",children:[e.jsx(pi,{src:C.profile_picture_url||""}),e.jsx(Na,{children:e.jsx(tf,{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(Oe,{variant:C.is_active?"default":"secondary",className:"text-xs",children:C.is_active?"Connected":"Inactive"})]})]}),e.jsxs(Kl,{children:[e.jsx(jx,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Sn,{className:"h-4 w-4"})})}),e.jsxs(Ol,{children:[e.jsxs(zl,{children:[e.jsx(Ul,{children:"Disconnect Facebook?"}),e.jsx(ql,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(Bl,{children:[e.jsx($l,{children:"Cancel"}),e.jsx(Ml,{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(B,{onClick:()=>m("facebook"),disabled:r,className:"w-full gap-2",variant:"outline",children:[r?e.jsx(uo,{className:"h-4 w-4 animate-spin"}):e.jsx(rn,{className:"h-4 w-4"}),y.length>0?"Connect Another Page":"Connect Facebook Page"]})]})]}),e.jsxs(ve,{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(Im,{className:"h-6 w-6 text-pink-600"})}),e.jsxs("div",{children:[e.jsx(St,{className:"text-lg",children:"Instagram"}),e.jsx(kn,{children:"Connect your Instagram Business or Creator account"})]})]})}),e.jsxs(Me,{className:"space-y-4",children:[u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(uo,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):v.length>0?e.jsx("div",{className:"space-y-3",children:v.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(ja,{className:"h-10 w-10",children:[e.jsx(pi,{src:C.profile_picture_url||""}),e.jsx(Na,{children:e.jsx(Im,{className:"h-5 w-5"})})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-medium",children:["@",C.platform_username||"Instagram Account"]}),e.jsx(Oe,{variant:C.is_active?"default":"secondary",className:"text-xs",children:C.is_active?"Connected":"Inactive"})]})]}),e.jsxs(Kl,{children:[e.jsx(jx,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Sn,{className:"h-4 w-4"})})}),e.jsxs(Ol,{children:[e.jsxs(zl,{children:[e.jsx(Ul,{children:"Disconnect Instagram?"}),e.jsx(ql,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(Bl,{children:[e.jsx($l,{children:"Cancel"}),e.jsx(Ml,{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(B,{onClick:()=>m("instagram"),disabled:r,className:"w-full gap-2",variant:"outline",children:[r?e.jsx(uo,{className:"h-4 w-4 animate-spin"}):e.jsx(rn,{className:"h-4 w-4"}),v.length>0?"Reconnect Instagram":"Connect Instagram"]}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"Use Instagram login for Business or Creator accounts; Facebook Page login is only needed if you want to connect Pages."})]})]}),e.jsxs(ve,{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(dg,{className:"h-6 w-6 text-blue-700"})}),e.jsxs("div",{children:[e.jsx(St,{className:"text-lg",children:"LinkedIn"}),e.jsx(kn,{children:"Connect your LinkedIn profile"})]})]})}),e.jsxs(Me,{className:"space-y-4",children:[u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(uo,{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(ja,{className:"h-10 w-10",children:[e.jsx(pi,{src:C.profile_picture_url||""}),e.jsx(Na,{children:e.jsx(dg,{className:"h-5 w-5"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:C.platform_username||"LinkedIn Account"}),e.jsx(Oe,{variant:C.is_active?"default":"secondary",className:"text-xs",children:C.is_active?"Connected":"Inactive"})]})]}),e.jsxs(Kl,{children:[e.jsx(jx,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Sn,{className:"h-4 w-4"})})}),e.jsxs(Ol,{children:[e.jsxs(zl,{children:[e.jsx(Ul,{children:"Disconnect LinkedIn?"}),e.jsx(ql,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(Bl,{children:[e.jsx($l,{children:"Cancel"}),e.jsx(Ml,{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(B,{onClick:p,disabled:r,className:"w-full gap-2",variant:g.length>0?"outline":"default",children:[r?e.jsx(uo,{className:"h-4 w-4 animate-spin"}):e.jsx(rn,{className:"h-4 w-4"}),g.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(ve,{className:`relative overflow-hidden ${n?"":"opacity-75"}`,children:[!n&&e.jsx("div",{className:"absolute top-3 right-3 z-10",children:e.jsx(Oe,{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(Oe,{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(Xa,{className:"h-6 w-6 text-red-600"})}),e.jsxs("div",{children:[e.jsx(St,{className:"text-lg",children:"Google Business"}),e.jsx(kn,{children:"Connect your Google Business Profile"})]})]})}),e.jsxs(Me,{className:"space-y-4",children:[u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(uo,{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(ja,{className:"h-10 w-10",children:[e.jsx(pi,{src:C.profile_picture_url||""}),e.jsx(Na,{children:e.jsx(Xa,{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(Oe,{variant:C.is_active?"default":"secondary",className:"text-xs",children:C.is_active?"Connected":"Inactive"})]})]}),e.jsxs(Kl,{children:[e.jsx(jx,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Sn,{className:"h-4 w-4"})})}),e.jsxs(Ol,{children:[e.jsxs(zl,{children:[e.jsx(Ul,{children:"Disconnect Google Business?"}),e.jsx(ql,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(Bl,{children:[e.jsx($l,{children:"Cancel"}),e.jsx(Ml,{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(B,{onClick:n?f:void 0,disabled:!n||r,className:"w-full gap-2",variant:b.length>0?"outline":"default",children:[r?e.jsx(uo,{className:"h-4 w-4 animate-spin"}):e.jsx(rn,{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&&(y.length>0||v.length>0)&&e.jsxs(ve,{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(YM,{className:"h-6 w-6 text-amber-600"})}),e.jsxs("div",{children:[e.jsx(St,{className:"text-lg",children:"Meta API Testing (Admin Only)"}),e.jsx(kn,{children:"Run API tests to trigger all required permissions for Meta App Review"})]})]})}),e.jsxs(Me,{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:[y.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(tf,{className:"h-5 w-5 text-blue-600"}),e.jsx("span",{className:"font-medium",children:C.page_name||"Facebook Page"})]}),e.jsx(B,{size:"sm",variant:"outline",onClick:()=>S(C.id),disabled:i===C.id,children:i===C.id?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),"Testing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(YM,{className:"h-4 w-4 mr-2"}),"Run Tests"]})})]},`test-fb-${C.id}`)),v.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(Im,{className:"h-5 w-5 text-pink-600"}),e.jsxs("span",{className:"font-medium",children:["@",C.platform_username||"Instagram"]})]}),e.jsx(B,{size:"sm",variant:"outline",onClick:()=>S(C.id),disabled:i===C.id,children:i===C.id?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),"Testing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(YM,{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,E)=>e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[C.status==="success"?e.jsx(Er,{className:"h-4 w-4 text-green-600 mt-0.5 shrink-0"}):C.status==="pending"?e.jsx(Ct,{className:"h-4 w-4 text-amber-600 mt-0.5 shrink-0"}):e.jsx(Rd,{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})]})]},E))})]}),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(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-lg",children:"How it works"})}),e.jsx(Me,{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 bir(){const[s]=Yl(),t=Fn(),[n,r]=_.useState("loading"),a=_.useRef(!1),[i,l]=_.useState("Processing your connection..."),[o,c]=_.useState(!1),d=(()=>{const u=sessionStorage.getItem("social-connect-return-to");return u&&u.startsWith("/")&&!u.startsWith("/admin")?u:"/social-connections"})();return _.useEffect(()=>{if(a.current)return;a.current=!0,(async()=>{var y;const h=s.get("code"),m=s.get("error"),p=s.get("error_description"),f=s.get("state");if(m){r("error"),l(p||"Authorization was denied"),se.error("Connection failed: "+(p||m));return}if(!h){r("error"),l("No authorization code received"),se.error("No authorization code received");return}try{const{data:v,error:g}=await q.functions.invoke("meta-oauth",{body:{action:"exchange_code",code:h,state:f,callbackPath:"/social-connections/callback"}});if(g)throw g;if(v!=null&&v.success)r("success"),l(`Successfully connected ${((y=v.accounts)==null?void 0:y.length)||0} account(s)!`),se.success("Social accounts connected successfully!");else throw new Error((v==null?void 0:v.error)||"Unknown error")}catch(v){console.error("OAuth callback error:",v),r("error");const g=v instanceof Error?v.message:"Failed to connect accounts";l(g),/page/i.test(g)&&/(no|didn't|did not|zero|empty|return)/i.test(g)&&c(!0),se.error("Failed to connect: "+(v instanceof Error?v.message:"Unknown error"))}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(ve,{className:"w-full max-w-md",children:[e.jsxs(bt,{className:"text-center",children:[n==="loading"&&e.jsx(Ct,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),n==="success"&&e.jsx(_l,{className:"h-12 w-12 mx-auto text-green-500"}),n==="error"&&e.jsx(Rd,{className:"h-12 w-12 mx-auto text-destructive"}),e.jsxs(St,{className:"mt-4",children:[n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(kn,{children:i})]}),e.jsxs(Me,{className:"flex flex-col items-center gap-4",children:[n==="error"&&o&&e.jsxs("div",{className:"w-full rounded-lg border bg-muted/40 p-4 text-left text-sm space-y-3",children:[e.jsxs("p",{className:"font-medium text-foreground",children:["Meta didn't return any Pages — this almost always means your personal Facebook profile doesn't have"," ",e.jsx("span",{className:"font-semibold",children:"Full control"})," of your business Page yet."]}),e.jsxs("ol",{className:"list-decimal list-inside space-y-2 text-muted-foreground",children:[e.jsxs("li",{children:["Open"," ",e.jsxs("a",{href:"https://business.facebook.com/latest/settings/people",target:"_blank",rel:"noopener noreferrer",className:"text-primary underline inline-flex items-center gap-1",children:["Meta Business Suite → Settings → People",e.jsx(wr,{className:"h-3 w-3"})]})]}),e.jsxs("li",{children:["Select yourself, then under ",e.jsx("span",{className:"font-medium text-foreground",children:"Pages"})," assign your business Page."]}),e.jsxs("li",{children:["Turn on ",e.jsx("span",{className:"font-medium text-foreground",children:"Full control"})," (an Editor or Moderator role is not enough — Meta hides those Pages from apps)."]}),e.jsxs("li",{children:["Make sure you're logged into Facebook with the same personal profile that manages the Page, then click ",e.jsx("span",{className:"font-medium text-foreground",children:"Try Again"})," below."]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"When you reconnect, Meta's dialog should list your Page by name. If the list is still empty, the Page access change hasn't taken effect yet — wait a minute and retry."})]}),n!=="loading"&&e.jsx(B,{onClick:()=>t(d),children:n==="success"?"View Connected Accounts":"Try Again"})]})]})})}function _ir(){const[s]=Yl(),t=Fn();return _.useEffect(()=>{const n=new URLSearchParams,r=s.get("error");r?n.set("google_error",r):s.get("code")&&n.set("google_error","legacy_callback_retry");const a=n.toString();t(`/apps/reviews${a?`?${a}`:""}`,{replace:!0})},[s,t]),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsx(Ct,{className:"h-8 w-8 animate-spin text-primary"})})}function wir(){const[s]=Yl(),t=Fn(),[n,r]=_.useState("loading"),[a,i]=_.useState("Connecting your LinkedIn account...");return _.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"),se.error(u||"Failed to connect LinkedIn");return}if(!o){r("error"),i("No authorization code received"),se.error("No authorization code received");return}try{const{data:m,error:p}=await q.functions.invoke("linkedin-oauth",{body:{action:"exchange_code",code:o,state:c,callbackPath:"/social-connections/linkedin-callback"}});if(p)throw p;if(m!=null&&m.success)r("success"),i(`Successfully connected ${((h=m.accounts)==null?void 0:h.length)||1} LinkedIn account`),se.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"),se.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(ve,{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(Ct,{className:"h-8 w-8 animate-spin text-blue-600"}),n==="success"&&e.jsx(_l,{className:"h-8 w-8 text-green-600"}),n==="error"&&e.jsx(Rd,{className:"h-8 w-8 text-red-600"})]}),e.jsxs(St,{className:"flex items-center justify-center gap-2",children:[e.jsx(dg,{className:"h-5 w-5 text-blue-600"}),n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(kn,{children:a})]}),e.jsx(Me,{className:"flex justify-center",children:e.jsx(B,{onClick:()=>t("/mission-control/integrations"),disabled:n==="loading",children:n==="success"?"View Integrations":"Back to Integrations"})})]})})}function jir(){const s=Fn(),[t,n]=_.useState(null),{data:r,isLoading:a}=wrs(t||void 0,!0),{data:i,isLoading:l}=Kat(!0),{cartItems:o}=kPe(),c=o.reduce((u,h)=>u+h.quantity,0),d=u=>{s(`/marketplace/${u.id}`)};return a||l?e.jsx(zs,{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(cn,{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(cn,{className:"h-72 w-full"},u))})]})}):e.jsx(zs,{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(B,{variant:"outline",onClick:()=>s("/marketplace/cart"),className:"relative",children:[e.jsx(xS,{className:"h-4 w-4 mr-2"}),"Cart",c>0&&e.jsx(Oe,{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(B,{variant:t===null?"default":"outline",size:"sm",onClick:()=>n(null),children:"All"}),i.map(u=>e.jsx(B,{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(ve,{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(Nh,{className:"h-12 w-12 text-muted-foreground"})}),u.category&&e.jsx(Oe,{className:"absolute top-2 left-2",variant:"secondary",children:u.category.name})]}),e.jsxs(Me,{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(Nh,{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 oas=_.forwardRef(({...s},t)=>e.jsx("nav",{ref:t,"aria-label":"breadcrumb",...s}));oas.displayName="Breadcrumb";const las=_.forwardRef(({className:s,...t},n)=>e.jsx("ol",{ref:n,className:At("flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",s),...t}));las.displayName="BreadcrumbList";const XCe=_.forwardRef(({className:s,...t},n)=>e.jsx("li",{ref:n,className:At("inline-flex items-center gap-1.5",s),...t}));XCe.displayName="BreadcrumbItem";const ZYe=_.forwardRef(({asChild:s,className:t,...n},r)=>{const a=s?LXe:"a";return e.jsx(a,{ref:r,className:At("transition-colors hover:text-foreground",t),...n})});ZYe.displayName="BreadcrumbLink";const cas=_.forwardRef(({className:s,...t},n)=>e.jsx("span",{ref:n,role:"link","aria-disabled":"true","aria-current":"page",className:At("font-normal text-foreground",s),...t}));cas.displayName="BreadcrumbPage";const XYe=({children:s,className:t,...n})=>e.jsx("li",{role:"presentation","aria-hidden":"true",className:At("[&>svg]:size-3.5",t),...n,children:s??e.jsx(xi,{})});XYe.displayName="BreadcrumbSeparator";function Nir(){var G,$;const{productId:s}=Li(),t=Fn(),{data:n,isLoading:r}=ysr(s||""),{addToCart:a,cartItems:i}=kPe(),[l,o]=_.useState(null),[c,d]=_.useState(1),[u,h]=_.useState(0),[m,p]=_.useState(null),[f,y]=_.useState(!1),[v,g]=_.useState(!1),b=(G=n==null?void 0:n.variants)==null?void 0:G.find(H=>H.id===l),j=(($=n==null?void 0:n.variants)==null?void 0:$.filter(H=>H.is_active))||[],S=Number((n==null?void 0:n.base_price)||0),C=b?Number(b.price_adjustment):0,E=S+C,P=Number((n==null?void 0:n.shipping_fee)||0),M=i.reduce((H,Y)=>H+Y.quantity,0),I=async H=>{if(!H.target.files||H.target.files.length===0)return;y(!0);const Y=H.target.files[0],Z=Y.name.split(".").pop(),ne=`artwork/${Date.now()}-${Math.random().toString(36).substring(7)}.${Z}`;try{const{error:ce}=await q.storage.from("marketplace").upload(ne,Y);if(ce)throw ce;const{data:{publicUrl:ie}}=q.storage.from("marketplace").getPublicUrl(ne);p(ie),se.success("Artwork uploaded successfully")}catch(ce){se.error("Failed to upload artwork: "+ce.message)}finally{y(!1)}},D=()=>{if(n){if(j.length>0&&!l){se.error("Please select an option");return}a(n,b||void 0,c,m||void 0),g(!0),se.success("Added to cart!"),setTimeout(()=>g(!1),2e3)}},O=()=>{n!=null&&n.images&&h(H=>(H+1)%n.images.length)},V=()=>{n!=null&&n.images&&h(H=>(H-1+n.images.length)%n.images.length)};return r?e.jsx(zs,{title:"Product",children:e.jsxs("div",{className:"grid gap-8 lg:grid-cols-2",children:[e.jsx(cn,{className:"aspect-square w-full"}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(cn,{className:"h-8 w-3/4"}),e.jsx(cn,{className:"h-6 w-1/4"}),e.jsx(cn,{className:"h-24 w-full"}),e.jsx(cn,{className:"h-12 w-full"})]})]})}):n?e.jsxs(zs,{title:n.name,children:[e.jsx(oas,{className:"mb-6",children:e.jsxs(las,{children:[e.jsx(XCe,{children:e.jsx(ZYe,{asChild:!0,children:e.jsx(ir,{to:"/marketplace",children:"Marketplace"})})}),n.category&&e.jsxs(e.Fragment,{children:[e.jsx(XYe,{}),e.jsx(XCe,{children:e.jsx(ZYe,{asChild:!0,children:e.jsx(ir,{to:`/marketplace?category=${n.category.id}`,children:n.category.name})})})]}),e.jsx(XYe,{}),e.jsx(XCe,{children:e.jsx(cas,{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(B,{variant:"ghost",size:"icon",className:"absolute left-2 top-1/2 -translate-y-1/2 bg-background/80 hover:bg-background",onClick:V,children:e.jsx($c,{className:"h-6 w-6"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"absolute right-2 top-1/2 -translate-y-1/2 bg-background/80 hover:bg-background",onClick:O,children:e.jsx(xi,{className:"h-6 w-6"})})]})]}):e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx(Nh,{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((H,Y)=>e.jsx("button",{onClick:()=>h(Y),className:`w-16 h-16 flex-shrink-0 rounded-md overflow-hidden border-2 ${Y===u?"border-primary":"border-transparent"}`,children:e.jsx("img",{src:H.image_url,alt:"",className:"w-full h-full object-cover"})},H.id))}),n.video&&e.jsx(ve,{children:e.jsxs(Me,{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(Oe,{variant:"secondary",className:"mb-2",children:n.category.name}),e.jsx("h1",{className:"text-3xl font-bold mb-2",children:n.name}),e.jsxs("div",{className:"flex items-baseline gap-2",children:[e.jsxs("span",{className:"text-3xl font-bold",children:["$",E.toFixed(2)]}),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})}),j.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(J,{children:"Select Option"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:j.map(H=>e.jsxs(B,{variant:l===H.id?"default":"outline",onClick:()=>o(H.id),children:[H.name,Number(H.price_adjustment)!==0&&e.jsxs("span",{className:"ml-1 opacity-70",children:["(",Number(H.price_adjustment)>0?"+":"","$",Number(H.price_adjustment).toFixed(2),")"]})]},H.id))})]}),n.allow_artwork_upload&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(J,{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(B,{variant:"ghost",size:"sm",className:"absolute -top-2 -right-2",onClick:()=>p(null),children:"×"})]}):e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-6",children:[e.jsx("input",{type:"file",accept:"image/*,.pdf,.ai,.eps",onChange:I,className:"hidden",id:"artwork-upload",disabled:f}),e.jsxs("label",{htmlFor:"artwork-upload",className:"flex flex-col items-center cursor-pointer",children:[e.jsx(Oa,{className:"h-8 w-8 text-muted-foreground mb-2"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:f?"Uploading...":"Click to upload artwork"}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"Supported: JPG, PNG, PDF, AI, EPS"})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(J,{children:"Quantity"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(B,{variant:"outline",size:"icon",onClick:()=>d(H=>Math.max(1,H-1)),children:"-"}),e.jsx(xe,{type:"number",value:c,onChange:H=>d(Math.max(1,parseInt(H.target.value)||1)),className:"w-20 text-center",min:"1"}),e.jsx(B,{variant:"outline",size:"icon",onClick:()=>d(H=>H+1),children:"+"})]})]}),e.jsxs("div",{className:"flex gap-4",children:[e.jsx(B,{size:"lg",className:"flex-1",onClick:D,disabled:v,children:v?e.jsxs(e.Fragment,{children:[e.jsx(ea,{className:"h-5 w-5 mr-2"}),"Added!"]}):e.jsxs(e.Fragment,{children:[e.jsx(xS,{className:"h-5 w-5 mr-2"}),"Add to Cart"]})}),e.jsxs(B,{variant:"outline",size:"lg",onClick:()=>t("/marketplace/cart"),className:"relative",children:[e.jsx(xS,{className:"h-5 w-5"}),M>0&&e.jsx(Oe,{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(zs,{title:"Product Not Found",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Nh,{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(B,{onClick:()=>t("/marketplace"),children:"Back to Marketplace"})]})})}function kir(){const s=Fn(),{cartItems:t,removeFromCart:n,updateQuantity:r,getItemPrice:a,getSubtotal:i,getShippingTotal:l,getTotal:o,clearCart:c}=kPe(),[d,u]=_.useState(!1),[h,m]=_.useState(""),p=async()=>{if(t.length===0){se.error("Your cart is empty");return}u(!0);try{const{data:f,error:y}=await q.functions.invoke("marketplace-checkout",{body:{items:t.map(v=>{var g;return{product_id:v.product.id,variant_id:((g=v.variant)==null?void 0:g.id)||null,quantity:v.quantity,artwork_url:v.artworkUrl||null}}),notes:h.trim()||null}});if(y)throw y;if(f!=null&&f.url)c(),window.open(f.url,"_blank");else throw new Error("No checkout URL received")}catch(f){se.error("Checkout failed: "+f.message)}finally{u(!1)}};return t.length===0?e.jsx(zs,{title:"Shopping Cart",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(K4,{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(B,{onClick:()=>s("/marketplace"),children:"Browse Marketplace"})]})}):e.jsx(zs,{title:"Shopping Cart",children:e.jsxs("div",{className:"grid gap-8 lg:grid-cols-3",children:[e.jsxs("div",{className:"lg:col-span-2 space-y-4",children:[t.map(f=>{var y,v;return e.jsx(ve,{children:e.jsx(Me,{className:"p-4",children:e.jsxs("div",{className:"flex gap-4",children:[e.jsx("div",{className:"w-24 h-24 flex-shrink-0 bg-muted rounded-lg overflow-hidden",children:f.product.images&&f.product.images.length>0?e.jsx("img",{src:((y=f.product.images.find(g=>g.is_primary))==null?void 0:y.image_url)||f.product.images[0].image_url,alt:f.product.name,className:"w-full h-full object-cover"}):e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx(K4,{className:"h-8 w-8 text-muted-foreground"})})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-semibold line-clamp-1",children:f.product.name}),f.variant&&e.jsx("p",{className:"text-sm text-muted-foreground",children:f.variant.name}),e.jsxs("p",{className:"font-medium mt-1",children:["$",a(f).toFixed(2),Number(f.product.shipping_fee)>0&&e.jsxs("span",{className:"text-sm text-muted-foreground ml-2",children:["+ $",Number(f.product.shipping_fee).toFixed(2)," shipping"]})]}),f.artworkUrl&&e.jsx("div",{className:"mt-2",children:e.jsx("span",{className:"text-xs text-muted-foreground",children:"Artwork uploaded ✓"})})]}),e.jsxs("div",{className:"flex flex-col items-end gap-2",children:[e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>{var g;return n(f.product.id,(g=f.variant)==null?void 0:g.id)},children:e.jsx(Sn,{className:"h-4 w-4 text-destructive"})}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(B,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>{var g;return r(f.product.id,(g=f.variant)==null?void 0:g.id,f.quantity-1)},disabled:f.quantity<=1,children:e.jsx(uN,{className:"h-3 w-3"})}),e.jsx(xe,{type:"number",value:f.quantity,onChange:g=>{var b;return r(f.product.id,(b=f.variant)==null?void 0:b.id,parseInt(g.target.value)||1)},className:"w-14 h-8 text-center text-sm",min:"1"}),e.jsx(B,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>{var g;return r(f.product.id,(g=f.variant)==null?void 0:g.id,f.quantity+1)},children:e.jsx(rn,{className:"h-3 w-3"})})]})]})]})})},`${f.product.id}-${((v=f.variant)==null?void 0:v.id)||"base"}`)}),e.jsx(B,{variant:"ghost",className:"text-destructive",onClick:c,children:"Clear Cart"})]}),e.jsx("div",{children:e.jsxs(ve,{className:"sticky top-4",children:[e.jsx(bt,{children:e.jsx(St,{children:"Order Summary"})}),e.jsxs(Me,{className:"space-y-4",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsxs("span",{children:["Subtotal (",t.reduce((f,y)=>f+y.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(wc,{}),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(wc,{}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"orderNotes",children:"Order Notes (Optional)"}),e.jsx(Ms,{id:"orderNotes",placeholder:"Add any special instructions, design notes, or comments for your order...",value:h,onChange:f=>m(f.target.value),rows:3,className:"resize-none"})]}),e.jsx(B,{className:"w-full",size:"lg",onClick:p,disabled:d,children:d?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"h-5 w-5 mr-2 animate-spin"}),"Processing..."]}):e.jsxs(e.Fragment,{children:["Checkout",e.jsx(La,{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 Sir(){const s=Fn(),{data:t,isLoading:n}=Esr();return n?e.jsx(zs,{title:"My Orders",children:e.jsx("div",{className:"space-y-4",children:[1,2,3].map(r=>e.jsx(cn,{className:"h-32 w-full"},r))})}):!t||t.length===0?e.jsx(zs,{title:"My Orders",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Nh,{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(B,{onClick:()=>s("/marketplace"),children:"Browse Marketplace"})]})}):e.jsx(zs,{title:"My Orders",children:e.jsx("div",{className:"space-y-4",children:t.map(r=>{var a,i,l;return e.jsx(ve,{className:"cursor-pointer hover:shadow-md transition-shadow",onClick:()=>s(`/marketplace/orders/${r.id}`),children:e.jsxs(Me,{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(Oe,{className:Wat[r.status],children:Z$[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(B,{variant:"outline",size:"sm",onClick:o=>{o.stopPropagation(),window.open(r.tracking_url,"_blank")},children:[e.jsx(wr,{className:"h-4 w-4 mr-1"}),"Track"]}),e.jsx(xi,{className:"h-5 w-5 text-muted-foreground"})]})]})]})},r.id)})})})}const X4t=["order_submitted","awaiting_proof_approval","proof_approved","processing","in_production","shipped","completed"];function Cir({currentStatus:s,statusHistory:t}){const n=X4t.indexOf(s);return e.jsx("div",{className:"space-y-3",children:X4t.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(Er,{className:"h-4 w-4"}):o?e.jsx(Gr,{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:Z$[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 Air(){var g;const{orderId:s}=Li(),t=Fn(),{data:n,isLoading:r,refetch:a}=Tsr(s||""),i=Lsr(),l=Isr(),[o,c]=_.useState(!1),[d,u]=_.useState(null),[h,m]=_.useState(""),[p,f]=_.useState(null),y=async b=>{f(b);try{await i.mutateAsync({orderId:s,itemId:b}),se.success("Proof approved!"),a()}catch{se.error("Failed to approve proof")}finally{f(null)}},v=async()=>{if(d){f(d);try{await l.mutateAsync({orderId:s,itemId:d,reason:h}),se.success("Revision requested"),c(!1),m(""),u(null),a()}catch{se.error("Failed to request revision")}finally{f(null)}}};return r?e.jsx(zs,{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(cn,{className:"h-64 w-full"}),e.jsx(cn,{className:"h-48 w-full"})]}),e.jsx(cn,{className:"h-96 w-full"})]})}):n?e.jsxs(zs,{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(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between",children:[e.jsx(St,{children:"Order Status"}),e.jsx(Oe,{className:Wat[n.status],children:Z$[n.status]})]}),e.jsx(Me,{children:e.jsx(Cir,{currentStatus:n.status,statusHistory:n.status_history})})]}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{children:"Items"})}),e.jsx(Me,{className:"space-y-4",children:(g=n.items)==null?void 0:g.map(b=>e.jsxs("div",{className:"border rounded-lg p-4",children:[e.jsxs("div",{className:"flex justify-between items-start mb-3",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold",children:b.product_name}),b.variant_name&&e.jsx("p",{className:"text-sm text-muted-foreground",children:b.variant_name}),e.jsxs("p",{className:"text-sm",children:["Qty: ",b.quantity," × $",Number(b.unit_price).toFixed(2)]})]}),e.jsxs("p",{className:"font-semibold",children:["$",(Number(b.unit_price)*b.quantity).toFixed(2)]})]}),b.artwork_url&&e.jsxs("div",{className:"mb-3",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:"Your Artwork:"}),e.jsxs("a",{href:b.artwork_url,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 text-primary hover:underline",children:[e.jsx(KM,{className:"h-4 w-4"}),"View Artwork",e.jsx(wr,{className:"h-3 w-3"})]})]}),b.proof_url&&e.jsxs("div",{className:"bg-muted rounded-lg p-3",children:[e.jsx("p",{className:"text-sm font-medium mb-2",children:"Proof Ready for Review"}),e.jsxs("a",{href:b.proof_url,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 text-primary hover:underline mb-3",children:[e.jsx(KM,{className:"h-4 w-4"}),"View Proof",e.jsx(wr,{className:"h-3 w-3"})]}),b.proof_status==="pending"&&e.jsxs("div",{className:"flex gap-2 mt-3",children:[e.jsxs(B,{size:"sm",onClick:()=>y(b.id),disabled:p===b.id,children:[p===b.id?e.jsx(Ct,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Fg,{className:"h-4 w-4 mr-1"}),"Approve"]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>{u(b.id),c(!0)},disabled:p===b.id,children:[e.jsx(cJ,{className:"h-4 w-4 mr-1"}),"Request Changes"]})]}),b.proof_status==="approved"&&e.jsxs(Oe,{className:"bg-green-100 text-green-800",children:[e.jsx(Er,{className:"h-3 w-3 mr-1"}),"Proof Approved"]}),b.proof_status==="rejected"&&b.proof_notes&&e.jsxs("div",{className:"mt-2",children:[e.jsx(Oe,{variant:"destructive",className:"mb-2",children:"Revision Requested"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:b.proof_notes})]})]})]},b.id))})]}),n.shipping_name&&e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(dJ,{className:"h-5 w-5"}),"Shipping"]})}),e.jsxs(Me,{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(B,{variant:"link",className:"p-0 h-auto mt-1",onClick:()=>window.open(n.tracking_url,"_blank"),children:["Track Package",e.jsx(wr,{className:"h-3 w-3 ml-1"})]})]})]})]})]}),e.jsx("div",{children:e.jsxs(ve,{className:"sticky top-4",children:[e.jsx(bt,{children:e.jsx(St,{children:"Order Summary"})}),e.jsxs(Me,{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(wc,{}),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(wc,{}),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(wc,{}),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(Ls,{open:o,onOpenChange:c,children:e.jsxs(Ps,{children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Request Changes"}),e.jsx(_r,{children:"Please describe what changes you'd like made to the proof."})]}),e.jsx(Ms,{placeholder:"Describe the changes needed...",value:h,onChange:b=>m(b.target.value),rows:4}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsxs(B,{onClick:v,disabled:!h.trim()||p!==null,children:[p?e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):null,"Submit Request"]})]})]})})]}):e.jsx(zs,{title:"Order Not Found",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Nh,{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(B,{onClick:()=>t("/marketplace/orders"),children:"View All Orders"})]})})}function Eir(){const s=Fn(),[t]=Yl();return t.get("session_id"),_.useEffect(()=>{localStorage.removeItem("marketplace-cart")},[]),e.jsx(zs,{title:"Order Confirmed",children:e.jsx("div",{className:"max-w-lg mx-auto text-center py-8",children:e.jsx(ve,{children:e.jsxs(Me,{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(Er,{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(Nh,{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(B,{className:"flex-1",onClick:()=>s("/marketplace/orders"),children:["View My Orders",e.jsx(La,{className:"h-4 w-4 ml-2"})]}),e.jsx(B,{variant:"outline",className:"flex-1",onClick:()=>s("/marketplace"),children:"Continue Shopping"})]})]})})})})}function Tir(){const{user:s}=hs(),[t,n]=_.useState("store"),[r,a]=_.useState(null),[i,l]=_.useState(null),[o,c]=_.useState(!1),[d,u]=_.useState(5),[h,m]=_.useState(""),[p,f]=_.useState(!1),[y,v]=_.useState(!1),[g,b]=_.useState(""),[j,S]=_.useState(null),[C,E]=_.useState(!1),{hasSubmittedReview:P,submitReview:M,markPostedToGoogle:I}=qRt(),{data:D}=Nrs(),{data:O,isLoading:V}=jrs(),{data:G,isLoading:$}=Usr(r),{data:H,isLoading:Y}=qsr(s==null?void 0:s.id),{data:Z=0}=Vsr(s==null?void 0:s.id),ne=Hsr(),ce=new Set((H==null?void 0:H.map(he=>he.item_id))||[]),ie=async()=>{if(i)try{const he=await ne.mutateAsync(i.id);i.item_type==="reelflow_credits"?se.success(`🎬 ${i.max_quantity} ReelFlow credits added to your balance!`):se.success(`Successfully purchased "${i.name}"!`),l(null)}catch(he){se.error(he.message||"Failed to purchase item")}},te=async()=>{if(!h.trim()){se.error("Please write a review");return}f(!0);const he=await M(d,h);f(!1),he.success?(se.success("Thank you for your review! You earned 25 points!"),b(h),v(!0),m(""),u(5)):se.error(he.error||"Failed to submit review")},ae=()=>{navigator.clipboard.writeText(g),se.success("Review copied to clipboard!")},le=()=>{I(),window.open("https://g.page/r/CT8bqTBTm7nJEBM/review","_blank")},be=()=>{v(!1),c(!1),b("")};return V||$||Y?e.jsx(zs,{title:"Reward Store",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(cn,{className:"h-24 w-full"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[1,2,3,4,5,6].map(he=>e.jsx(cn,{className:"h-64"},he))})]})}):e.jsxs(zs,{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(ve,{className:"bg-gradient-to-r from-primary/10 to-primary/5 border-primary/20",children:e.jsx(Me,{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(Da,{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:Z.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(wl,{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(gu,{className:"h-4 w-4 text-orange-500"}),e.jsx("span",{children:"Streak bonuses add extra points!"})]})]})]})})}),e.jsx(f1,{open:C,onOpenChange:E,children:e.jsxs(ve,{className:"border-primary/20",children:[e.jsx(x1,{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(wl,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(St,{className:"text-base",children:"How to Earn Points"}),e.jsx(kn,{children:"See all the ways you can earn spendable points"})]})]}),C?e.jsx(_v,{className:"h-5 w-5 text-muted-foreground"}):e.jsx(tl,{className:"h-5 w-5 text-muted-foreground"})]})})}),e.jsx(g1,{children:e.jsx(Me,{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(he=>he.is_active).map(he=>{const pe=Ce=>{switch(Ce){case"event_attendance":return e.jsx(ga,{className:"h-5 w-5"});case"leave_review":return e.jsx(Da,{className:"h-5 w-5"});case"add_listing":return e.jsx(Jr,{className:"h-5 w-5"});case"first_contact":return e.jsx(In,{className:"h-5 w-5"});case"first_video":return e.jsx(Kr,{className:"h-5 w-5"});case"first_community_post":return e.jsx(Hi,{className:"h-5 w-5"});default:return e.jsx(Vo,{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:pe(he.action_key)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm",children:he.action_name}),he.description&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:he.description})]}),e.jsxs(Oe,{variant:"secondary",className:"font-bold shrink-0",children:["+",he.points]})]},he.id)}),e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg bg-orange-500/10 border border-orange-500/20",children:[e.jsx("div",{className:"h-10 w-10 rounded-full bg-orange-500/20 flex items-center justify-center text-orange-500 shrink-0",children:e.jsx(gu,{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(Oe,{variant:"outline",className:"font-bold shrink-0 border-orange-500/50 text-orange-600",children:"+Bonus"})]})]})})})]})}),!P&&e.jsx(ve,{className:"bg-gradient-to-r from-yellow-500/10 to-orange-500/10 border-yellow-500/20",children:e.jsx(Me,{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(Hi,{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(B,{onClick:()=>c(!0),className:"bg-yellow-600 hover:bg-yellow-700",children:[e.jsx(Da,{className:"h-4 w-4 mr-2"}),"Leave Review"]})]})})}),e.jsxs(Yr,{value:t,onValueChange:n,children:[e.jsxs(Zr,{children:[e.jsxs(Ht,{value:"store",className:"flex items-center gap-2",children:[e.jsx(K4,{className:"h-4 w-4"}),"Store"]}),e.jsxs(Ht,{value:"my-rewards",className:"flex items-center gap-2",children:[e.jsx(Nh,{className:"h-4 w-4"}),"My Rewards",H&&H.length>0&&e.jsx(Oe,{variant:"secondary",className:"ml-1",children:H.length})]})]}),e.jsxs(Gt,{value:"store",className:"mt-6",children:[O&&O.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-2 mb-6",children:[e.jsx(B,{variant:r===null?"default":"outline",size:"sm",onClick:()=>a(null),children:"All"}),O.map(he=>e.jsxs(B,{variant:r===he.id?"default":"outline",size:"sm",onClick:()=>a(he.id),children:[he.icon&&`${he.icon} `,he.name]},he.id))]}),!G||G.length===0?e.jsx(ve,{children:e.jsx(Me,{className:"py-12",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(Vo,{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:G.map(he=>{const pe=he.item_type==="reelflow_credits",Ce=!pe&&ce.has(he.id),Ae=!pe&&he.max_quantity!==null&&he.current_quantity===0,Pe=Z>=he.points_cost;return e.jsxs(ve,{className:`overflow-hidden transition-all cursor-pointer hover:shadow-lg ${Ce?"ring-2 ring-green-500/50 bg-green-500/5":""}`,onClick:()=>S(he),children:[he.preview_image_url?e.jsxs("div",{className:"aspect-video relative overflow-hidden bg-muted",children:[e.jsx("img",{src:he.preview_image_url,alt:he.name,className:"w-full h-full object-cover"}),Ce&&e.jsx("div",{className:"absolute top-2 right-2",children:e.jsxs(Oe,{className:"bg-green-500 text-white",children:[e.jsx(Er,{className:"h-3 w-3 mr-1"}),"Owned"]})}),Ae&&!Ce&&e.jsx("div",{className:"absolute inset-0 bg-black/50 flex items-center justify-center",children:e.jsx(Oe,{variant:"destructive",children:"Sold Out"})})]}):e.jsxs("div",{className:"aspect-video bg-muted flex items-center justify-center relative",children:[e.jsx(Vo,{className:"h-12 w-12 text-muted-foreground/50"}),Ce&&e.jsx("div",{className:"absolute top-2 right-2",children:e.jsxs(Oe,{className:"bg-green-500 text-white",children:[e.jsx(Er,{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(St,{className:"text-lg",children:he.name}),e.jsxs(Oe,{variant:"secondary",className:"font-bold shrink-0",children:[e.jsx(Da,{className:"h-3 w-3 mr-1"}),he.points_cost]})]}),he.category&&e.jsxs(Oe,{variant:"outline",className:"w-fit",children:[he.category.icon&&`${he.category.icon} `,he.category.name]})]}),e.jsxs(Me,{children:[e.jsx(kn,{className:"mb-4 line-clamp-2",children:he.description||"No description available"}),he.max_quantity!==null&&!Ce&&!pe&&e.jsxs("p",{className:"text-xs text-muted-foreground mb-3",children:[he.current_quantity," of ",he.max_quantity," remaining"]}),pe&&e.jsxs("p",{className:"text-xs text-violet-600 font-medium mb-3",children:["🎬 Grants ",he.max_quantity," ReelFlow credits per purchase"]}),Ce?e.jsx(B,{className:"w-full",onClick:ze=>{ze.stopPropagation(),he.file_url&&ABe(he.file_url,he.name)},disabled:!he.file_url,children:he.item_type==="file"?e.jsxs(e.Fragment,{children:[e.jsx(li,{className:"h-4 w-4 mr-2"}),"Download"]}):e.jsxs(e.Fragment,{children:[e.jsx(wr,{className:"h-4 w-4 mr-2"}),"Access"]})}):e.jsx(B,{className:"w-full",onClick:ze=>{ze.stopPropagation(),l(he)},disabled:Ae||!Pe,children:Ae?"Sold Out":Pe?e.jsxs(e.Fragment,{children:[e.jsx(K4,{className:"h-4 w-4 mr-2"}),"Purchase"]}):`Need ${he.points_cost-Z} more pts`})]})]},he.id)})})]}),e.jsx(Gt,{value:"my-rewards",className:"mt-6",children:!H||H.length===0?e.jsx(ve,{children:e.jsx(Me,{className:"py-12",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(Nh,{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:H.map(he=>{var pe,Ce,Ae,Pe,ze,ke,Ze;return e.jsxs(ve,{className:"overflow-hidden",children:[(pe=he.item)!=null&&pe.preview_image_url?e.jsx("div",{className:"aspect-video relative overflow-hidden bg-muted",children:e.jsx("img",{src:he.item.preview_image_url,alt:((Ce=he.item)==null?void 0:Ce.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(Vo,{className:"h-12 w-12 text-muted-foreground/50"})}),e.jsxs(bt,{className:"pb-2",children:[e.jsx(St,{className:"text-lg",children:((Ae=he.item)==null?void 0:Ae.name)||"Unknown Item"}),e.jsxs(kn,{className:"text-xs",children:["Purchased for ",he.points_spent," points • ",new Date(he.purchased_at).toLocaleDateString()]})]}),e.jsx(Me,{children:((Pe=he.item)==null?void 0:Pe.item_type)==="reelflow_credits"?e.jsxs(B,{className:"w-full",variant:"outline",disabled:!0,children:[e.jsx(Er,{className:"h-4 w-4 mr-2 text-green-500"}),(ze=he.item)==null?void 0:ze.max_quantity," Credits Applied"]}):e.jsx(B,{className:"w-full",onClick:()=>{var Se,Fe;(Se=he.item)!=null&&Se.file_url&&ABe(he.item.file_url,(Fe=he.item)==null?void 0:Fe.name)},disabled:!((ke=he.item)!=null&&ke.file_url),children:((Ze=he.item)==null?void 0:Ze.item_type)==="file"?e.jsxs(e.Fragment,{children:[e.jsx(li,{className:"h-4 w-4 mr-2"}),"Download"]}):e.jsxs(e.Fragment,{children:[e.jsx(wr,{className:"h-4 w-4 mr-2"}),"Access"]})})})]},he.id)})})})]})]}),e.jsx(Kl,{open:!!i,onOpenChange:()=>l(null),children:e.jsxs(Ol,{children:[e.jsxs(zl,{children:[e.jsx(Ul,{children:"Confirm Purchase"}),e.jsxs(ql,{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:[Z," points"]}),". After this purchase, you'll have"," ",e.jsxs("strong",{children:[Z-((i==null?void 0:i.points_cost)||0)," points"]})," remaining."]})]}),e.jsxs(Bl,{children:[e.jsx($l,{children:"Cancel"}),e.jsx(Ml,{onClick:ie,disabled:ne.isPending,children:ne.isPending?"Purchasing...":"Confirm Purchase"})]})]})}),e.jsx(Ls,{open:o,onOpenChange:he=>{!he&&y?be():c(he)},children:e.jsx(Ps,{children:y?e.jsxs(e.Fragment,{children:[e.jsxs(Os,{children:[e.jsxs(Ds,{className:"flex items-center gap-2",children:[e.jsx(Er,{className:"h-5 w-5 text-green-500"}),"Thank You for Your Review!"]}),e.jsx(_r,{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:['"',g,'"']})]}),e.jsxs(B,{variant:"outline",className:"w-full",onClick:ae,children:[e.jsx(Ia,{className:"h-4 w-4 mr-2"}),"Copy Review to Clipboard"]})]}),e.jsxs(yr,{className:"flex-col sm:flex-row gap-2",children:[e.jsx(B,{variant:"outline",onClick:be,children:"Maybe Later"}),e.jsxs(B,{onClick:le,className:"bg-blue-600 hover:bg-blue-700",children:[e.jsx(wr,{className:"h-4 w-4 mr-2"}),"Leave Google Review"]})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Leave a Review"}),e.jsx(_r,{children:"Share your experience with LevelUp and earn 25 spendable points!"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium mb-2 block",children:"Your Rating"}),e.jsx("div",{className:"flex gap-1",children:[1,2,3,4,5].map(he=>e.jsx("button",{type:"button",onClick:()=>u(he),className:"focus:outline-none",children:e.jsx(Da,{className:`h-8 w-8 transition-colors ${d>=he?"fill-yellow-400 text-yellow-400":"text-muted-foreground hover:text-yellow-400"}`})},he))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium mb-2 block",children:"Your Review"}),e.jsx(Ms,{placeholder:"What do you love about LevelUp? How has it helped your business?",value:h,onChange:he=>m(he.target.value),rows:4})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx(B,{onClick:te,disabled:p,className:"bg-yellow-600 hover:bg-yellow-700",children:p?"Submitting...":"Submit & Earn 25 Points"})]})]})})}),e.jsx(Ls,{open:!!j,onOpenChange:()=>S(null),children:e.jsxs(Ps,{className:"max-w-lg",children:[e.jsxs(Os,{children:[e.jsxs(Ds,{className:"flex items-center gap-2",children:[j==null?void 0:j.name,e.jsxs(Oe,{variant:"secondary",className:"font-bold",children:[e.jsx(Da,{className:"h-3 w-3 mr-1"}),j==null?void 0:j.points_cost]})]}),(j==null?void 0:j.category)&&e.jsxs(Oe,{variant:"outline",className:"w-fit",children:[j.category.icon&&`${j.category.icon} `,j.category.name]})]}),(j==null?void 0:j.preview_image_url)&&e.jsx("div",{className:"aspect-video relative overflow-hidden bg-muted rounded-lg",children:e.jsx("img",{src:j.preview_image_url,alt:j.name,className:"w-full h-full object-cover"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-muted-foreground",children:(j==null?void 0:j.description)||"No description available"}),(j==null?void 0:j.item_type)==="reelflow_credits"&&e.jsxs("p",{className:"text-sm text-violet-600 font-medium",children:["🎬 Grants ",j==null?void 0:j.max_quantity," ReelFlow credits per purchase"]}),(j==null?void 0:j.item_type)!=="reelflow_credits"&&(j==null?void 0:j.max_quantity)!==null&&!ce.has((j==null?void 0:j.id)||"")&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:[j==null?void 0:j.current_quantity," of ",j==null?void 0:j.max_quantity," remaining"]})]}),e.jsx(yr,{children:j&&j.item_type!=="reelflow_credits"&&ce.has(j.id)?e.jsx(B,{className:"w-full",onClick:()=>{j.file_url&&ABe(j.file_url,j.name)},disabled:!j.file_url,children:j.item_type==="file"?e.jsxs(e.Fragment,{children:[e.jsx(li,{className:"h-4 w-4 mr-2"}),"Download"]}):e.jsxs(e.Fragment,{children:[e.jsx(wr,{className:"h-4 w-4 mr-2"}),"Access"]})}):j&&e.jsx(B,{className:"w-full",onClick:()=>{S(null),l(j)},disabled:j.item_type!=="reelflow_credits"&&j.max_quantity!==null&&j.current_quantity===0||Z{s&&Y()},[s==null?void 0:s.id]);const Y=async()=>{if(!s)return;o(!0),g(!1),y(!0);const{data:ze}=await q.from("point_reward_settings").select("action_key, points").in("action_key",["referral_signup","referral_paid"]);ze==null||ze.forEach(Fe=>{Fe.action_key==="referral_signup"&&h(Fe.points),Fe.action_key==="referral_paid"&&p(Fe.points)});const{data:ke}=await q.from("profiles").select("name").eq("id",s.id).maybeSingle();ke!=null&&ke.name&&j(ke.name);let{data:Ze}=await q.from("agent_referral_codes").select("code").eq("user_id",s.id).maybeSingle();if(!Ze){const{data:Fe}=await q.rpc("generate_agent_referral_code",{_user_id:s.id}),Ne=Fe||`agent${s.id.slice(0,6)}`,{data:Ye,error:Ve}=await q.from("agent_referral_codes").insert({user_id:s.id,code:Ne}).select("code").maybeSingle();!Ve&&Ye&&(Ze=Ye)}i((Ze==null?void 0:Ze.code)??null);const{data:Se}=await q.from("agent_referrals").select("id, referred_user_id, status, signed_up_at, qualified_at, signup_points_awarded, paid_points_awarded").eq("referrer_user_id",s.id).order("signed_up_at",{ascending:!1});if(Se&&Se.length>0){const Fe=Se.map(Ve=>Ve.referred_user_id),{data:Ne}=await q.from("profiles").select("id, name, email").in("id",Fe),Ye=new Map((Ne==null?void 0:Ne.map(Ve=>[Ve.id,Ve]))??[]);d(Se.map(Ve=>({...Ve,referred_profile:Ye.get(Ve.referred_user_id)??null})))}else d([]);o(!1)},Z=_.useMemo(()=>a?`${Mir}/trial?ref=${a}`:"",[a]),ne=c.length,ce=c.filter(ze=>ze.status==="qualified").length,ie=c.filter(ze=>ze.signup_points_awarded).length*u+c.filter(ze=>ze.paid_points_awarded).length*m,te=async()=>{Z&&(await navigator.clipboard.writeText(Z),se.success("Referral link copied!"))},ae=()=>{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: ${Z} Let me know if you have any questions!`);window.location.href=`mailto:?subject=${ze}&body=${ke}`},le=()=>{const ze=encodeURIComponent(`Hey! I think you'd love LevelUp for your business — sign up with my link: ${Z}`);window.location.href=`sms:?&body=${ze}`},be=async()=>{if(navigator.share&&Z)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:Z})}catch{}else te()},me=ze=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(ze.trim()),he=ze=>{const ke=(ze??E).trim().replace(/,$/,"");if(!ke)return;const Ze=ke.split(/[\s,;]+/).filter(Boolean),Se=[...M];let Fe=0;for(const Ne of Ze){if(!me(Ne)){se.error(`Invalid email: ${Ne}`);continue}Se.includes(Ne)||(Se.push(Ne),Fe++)}I(Se),Fe>0&&P("")},pe=ze=>I(M.filter(ke=>ke!==ze)),Ce=()=>{G(`${b?b.split(" ")[0]+" invited you to":"Join me on"} LevelUp`),O("I've been using LevelUp to grow my real estate business and it's been a game changer. I think you'd love it too — sign up with my link and we'll both get a head start."),C(!0)},Ae=ze=>{const ke=ze.replace(/&/g,"&").replace(//g,">").replace(/\n/g,"
"),Ze=b||"A fellow agent",Se="https://relzejiswnotikjgvjhz.supabase.co/storage/v1/object/public/email-assets/levelup-logo-email.png",Fe=Z;return`
LevelUp
You're Invited

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

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

`.trim()},Pe=async()=>{if(M.length===0&&(E.trim()&&he(),M.length===0)){se.error("Add at least one recipient");return}if(!V.trim()){se.error("Subject is required");return}H(!0);const ze=Ae(D);let ke=0,Ze=0;for(const Se of M)try{const{data:Fe,error:Ne}=await q.functions.invoke("gmail-send",{body:{to:Se,subject:V,body:ze,source:"referral_invite"}});if(Ne||Fe!=null&&Fe.error)throw new Error((Ne==null?void 0:Ne.message)||(Fe==null?void 0:Fe.error));ke++}catch(Fe){console.error("Gmail send failed for",Se,Fe),Ze++}H(!1),ke>0?(se.success(`Invite sent to ${ke} ${ke===1?"person":"people"}`+(Ze>0?` (${Ze} failed)`:"")),I([]),P(""),C(!1)):se.error("Failed to send invites")};return!v&&!f?e.jsx(zs,{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(ve,{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(ec,{className:"h-6 w-6 text-muted-foreground"})}),e.jsx(St,{children:"Refer & Earn is for active members"}),e.jsx(kn,{children:"Activate your subscription to unlock your personal referral link and start earning points."})]}),e.jsx(Me,{className:"flex justify-center",children:e.jsx(B,{onClick:()=>t("/subscription"),children:"View Subscription"})})]})]})}):e.jsxs(zs,{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(Vo,{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(ve,{children:e.jsxs(Me,{className:"p-4 flex items-center gap-3",children:[e.jsx(In,{className:"h-5 w-5 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:ne}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Friends signed up"})]})]})}),e.jsx(ve,{children:e.jsxs(Me,{className:"p-4 flex items-center gap-3",children:[e.jsx(Er,{className:"h-5 w-5 text-emerald-600"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:ce}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Activated paid plan"})]})]})}),e.jsx(ve,{children:e.jsxs(Me,{className:"p-4 flex items-center gap-3",children:[e.jsx(wl,{className:"h-5 w-5 text-amber-500"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:ie.toLocaleString()}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Points earned"})]})]})})]}),e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-5 w-5 text-primary"}),"Your referral link"]}),e.jsx(kn,{children:"Anyone who signs up through this link is credited to you."})]}),e.jsxs(Me,{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[e.jsx(xe,{readOnly:!0,value:l?"Loading…":Z,className:"font-mono text-sm",onFocus:ze=>ze.currentTarget.select()}),e.jsxs(B,{onClick:te,disabled:!Z,children:[e.jsx(Ia,{className:"h-4 w-4 mr-2"}),"Copy link"]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[n&&e.jsxs(B,{size:"sm",onClick:Ce,disabled:!Z,className:"bg-primary hover:bg-primary/90",children:[e.jsx(Or,{className:"h-4 w-4 mr-2"})," Send via Gmail"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:ae,disabled:!Z,children:[e.jsx(ln,{className:"h-4 w-4 mr-2"})," Email"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:le,disabled:!Z,children:[e.jsx(Hi,{className:"h-4 w-4 mr-2"})," Text"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:be,disabled:!Z,children:[e.jsx(bd,{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(ve,{children:[e.jsxs(bt,{children:[e.jsx(St,{children:"Your Referrals"}),e.jsx(kn,{children:"Track who joined and when they upgrade."})]}),e.jsx(Me,{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(In,{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,Fe;const ke=((Se=ze.referred_profile)==null?void 0:Se.name)||((Fe=ze.referred_profile)==null?void 0:Fe.email)||"New agent",Ze=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 ",Ze]})]}),ze.status==="qualified"?e.jsxs(Oe,{className:"bg-emerald-100 text-emerald-700 border-emerald-200 hover:bg-emerald-100",children:[e.jsx(Er,{className:"h-3 w-3 mr-1"})," Paid · +",u+m," pts"]}):e.jsxs(Oe,{variant:"secondary",children:[e.jsx(Gr,{className:"h-3 w-3 mr-1"})," Signed up · +",u," pts"]})]},ze.id)})})})]}),e.jsx(ve,{className:"bg-muted/30",children:e.jsxs(Me,{className:"p-6",children:[e.jsxs("h3",{className:"font-semibold mb-3 flex items-center gap-2",children:[e.jsx(un,{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(wc,{className:"opacity-0"})]}),e.jsx(Ls,{open:S,onOpenChange:C,children:e.jsxs(Ps,{className:"sm:max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsxs(Ds,{className:"flex items-center gap-2",children:[e.jsx(Or,{className:"h-5 w-5 text-primary"})," Send referral invites via Gmail"]}),e.jsxs(_r,{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(J,{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(Oe,{variant:"secondary",className:"gap-1 pr-1",children:[ze,e.jsx("button",{type:"button",onClick:()=>pe(ze),className:"hover:bg-muted-foreground/20 rounded-full p-0.5","aria-label":`Remove ${ze}`,children:e.jsx(Qn,{className:"h-3 w-3"})})]},ze)),e.jsx("input",{type:"email",value:E,onChange:ze=>P(ze.target.value),onKeyDown:ze=>{ze.key==="Enter"||ze.key===","||ze.key===" "?(ze.preventDefault(),he()):ze.key==="Backspace"&&!E&&M.length>0&&I(M.slice(0,-1))},onBlur:()=>E.trim()&&he(),onPaste:ze=>{const ke=ze.clipboardData.getData("text");/[\s,;]/.test(ke)&&(ze.preventDefault(),he(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(J,{htmlFor:"email-subject",children:"Subject"}),e.jsx(xe,{id:"email-subject",value:V,onChange:ze=>G(ze.target.value),placeholder:"Subject line"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"personal-note",children:"Your personal note"}),e.jsx(Ms,{id:"personal-note",value:D,onChange:ze=>O(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(J,{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: ",V||"(no subject)"]})]}),e.jsx("iframe",{title:"Email preview",srcDoc:Ae(D),className:"w-full h-[420px] bg-white"})]})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>C(!1),disabled:$,children:"Cancel"}),e.jsxs(B,{onClick:Pe,disabled:$,children:[e.jsx(Or,{className:"h-4 w-4 mr-2"}),$?"Sending…":`Send${M.length>0?` to ${M.length}`:""}`]})]})]})})]})}const das=()=>{const{user:s}=hs(),t=Bt(),n=at({queryKey:["smart-presentations",s==null?void 0:s.id],queryFn:async()=>{const{data:d,error:u}=await q.from("smart_presentations").select("*").eq("owner_user_id",s.id).neq("status","archived").order("created_at",{ascending:!1});if(u)throw u;return d||[]},enabled:!!s}),r=at({queryKey:["smart-presentation-templates",s==null?void 0:s.id],queryFn:async()=>{const{data:d,error:u}=await q.from("smart_presentation_templates").select("*").eq("is_active",!0).order("created_at",{ascending:!0});if(u)throw u;return d||[]},enabled:!!s}),a=mt({mutationFn:async d=>{const{data:u,error:h}=await q.from("smart_presentations").insert({owner_user_id:s.id,...d}).select().single();if(h)throw h;return u},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentations"]})}}),i=mt({mutationFn:async({id:d,...u})=>{const{data:h,error:m}=await q.from("smart_presentations").update(u).eq("id",d).select().single();if(m)throw m;return h},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentations"]})}}),l=mt({mutationFn:async d=>{const{data:u,error:h}=await q.from("smart_presentations").update({status:"published",published_at:new Date().toISOString()}).eq("id",d).select().single();if(h)throw h;return u},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentations"]}),se.success("Presentation published!")}}),o=mt({mutationFn:async d=>{const{error:u}=await q.from("smart_presentations").update({status:"archived"}).eq("id",d);if(u)throw u},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentations"]}),se.success("Presentation archived")}}),c=mt({mutationFn:async d=>{const{error:u}=await q.from("smart_presentation_templates").insert({owner_user_id:s.id,name:d.title+" Template",description:"Created from "+d.title,template_type:"custom",icon:"📄",sections:d.sections,cta_config:{type:d.cta_type,label:d.cta_label},is_system:!1});if(u)throw u},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentation-templates"]}),se.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}},Lir=()=>{const s=Fn(),{presentations:t,isLoading:n,archivePresentation:r,saveAsTemplate:a}=das(),i=o=>o.status==="draft"?e.jsx(Oe,{variant:"outline",className:"text-xs",children:"Draft"}):o.view_count>1?e.jsx(Oe,{className:"text-xs bg-emerald-100 text-emerald-700 border-emerald-200",children:"Revisited"}):o.view_count===1?e.jsx(Oe,{className:"text-xs bg-blue-100 text-blue-700 border-blue-200",children:"Opened"}):e.jsx(Oe,{variant:"secondary",className:"text-xs",children:"Not Opened"}),l=o=>{const c=`https://presentations.relevelup.com/${o}`;navigator.clipboard.writeText(c),se.success("Link copied!")};return e.jsx(zs,{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(B,{onClick:()=>s("/mission-control/presentations/new"),className:"gap-2",children:[e.jsx(rn,{className:"h-4 w-4"}),"Create Presentation"]})]}),n?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(o=>e.jsx(cn,{className:"h-20 w-full rounded-lg"},o))}):t.length===0?e.jsx(ve,{children:e.jsxs(Me,{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(jv,{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(B,{onClick:()=>s("/mission-control/presentations/new"),className:"gap-2",children:[e.jsx(rn,{className:"h-4 w-4"}),"Create Your First Presentation"]})]})}):e.jsx("div",{className:"space-y-3",children:t.map(o=>e.jsx(ve,{className:"hover:shadow-sm transition-shadow",children:e.jsx(Me,{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(Fr,{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(ya,{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(B,{variant:"outline",size:"sm",onClick:()=>l(o.share_token),children:[e.jsx(Ia,{className:"h-3.5 w-3.5 mr-1"}),"Copy Link"]}),o.status==="published"&&e.jsx(B,{variant:"outline",size:"sm",onClick:()=>s(`/mission-control/presentations/${o.id}?edit=true`),children:"Edit"}),e.jsx(B,{variant:"outline",size:"sm",onClick:()=>s(`/mission-control/presentations/${o.id}`),children:o.status==="draft"?"Edit":"View"}),e.jsxs(tu,{children:[e.jsx(su,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(Xx,{className:"h-4 w-4"})})}),e.jsxs(Od,{align:"end",children:[o.status==="published"&&o.share_token&&e.jsxs(ca,{onClick:()=>window.open(`https://presentations.relevelup.com/${o.share_token}`,"_blank"),children:[e.jsx(wr,{className:"h-4 w-4 mr-2"}),"Preview Link"]}),e.jsxs(ca,{onClick:()=>a.mutate(o),children:[e.jsx(Fr,{className:"h-4 w-4 mr-2"}),"Save as Template"]}),e.jsxs(ca,{onClick:()=>r.mutate(o.id),className:"text-destructive",children:[e.jsx(by,{className:"h-4 w-4 mr-2"}),"Archive"]})]})]})]})]})})]})})},o.id))})]})})},Q4t={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."}]},Iir=[{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 Dir(s){const t=Q4t[s];if(t)return t;const n=s.toLowerCase();for(const[r,a]of Object.entries(Q4t))if(n.includes(r.toLowerCase())||r.toLowerCase().includes(n))return a;return Iir}function Rir({sectionTitle:s,contactId:t,onVideoReady:n}){const[r,a]=_.useState(!1),[i,l]=_.useState("script"),[o,c]=_.useState(0),[d,u]=_.useState(0),{canRecord:h}=CYt(),m=TC(),[p,f]=_.useState(""),[y,v]=_.useState(!1),[g,b]=_.useState(!0),[j,S]=_.useState(!1),[C,E]=_.useState(null),P=Dir(s),M=()=>{l("script"),c(0),u(0),f(""),v(!1),b(!0),S(!1),E(null)},I=$=>{!$&&(i==="uploading"||i==="processing")||(a($),$||M())},D=$=>{E($),f(P[$].text),v(!1)},O=()=>{l("record"),b(p.trim().length>0)},V=()=>{f(""),b(!1),l("record")},G=_.useCallback(async($,H)=>{l("uploading");try{const Y=s||"Presentation Video",{videoId:Z,uploadUrl:ne,libraryId:ce}=await PL(Y),{apiKey:ie}=await LL(Z),te=new XMLHttpRequest;te.upload.onprogress=he=>{he.lengthComputable&&c(he.loaded/he.total*100)},await new Promise((he,pe)=>{te.onload=()=>te.status>=200&&te.status<300?he():pe(new Error("Upload failed")),te.onerror=()=>pe(new Error("Upload failed")),te.open("PUT",ne),te.setRequestHeader("AccessKey",ie),te.send($)}),l("processing");let ae=0;const le=Date.now(),be=9e4;let me=null;for(;ae<4;){if(await new Promise(pe=>setTimeout(pe,3e3)),Date.now()-le>be){const pe=$.size/1048576,Ce=`https://iframe.mediadelivery.net/embed/${ce}/${Z}?responsive=true`;await m.mutateAsync({bunny_video_id:Z,playback_url:Ce,file_size_mb:pe,title:Y,contact_id:t||void 0,status:"processing",touch_type:"presentation"}),n(Ce),se.success("Video saved — still encoding. It will be ready shortly."),l("done"),setTimeout(()=>a(!1),1500);return}const he=await TN(Z);if(ae=he.status,u(he.encodeProgress||0),ae===4)me={playbackUrl:he.directPlayUrl,thumbnailUrl:he.thumbnailUrl,previewUrl:he.previewUrl||null,duration:he.length||H,fileSizeMb:(he.storageSize||$.size)/(1024*1024)};else if(ae===5||ae===6)throw new Error("Video processing failed")}if(!me)throw new Error("No video data");await m.mutateAsync({bunny_video_id:Z,contact_id:t||void 0,playback_url:me.playbackUrl,thumbnail_url:me.thumbnailUrl,preview_url:me.previewUrl,duration_seconds:me.duration,file_size_mb:me.fileSizeMb,title:Y,status:"ready",touch_type:"presentation"}),n(me.playbackUrl),se.success("Video recorded, saved to library & attached!"),l("done"),setTimeout(()=>a(!1),1500)}catch(Y){console.error("Recording upload error:",Y),se.error("Failed to process video. Please try again."),l("record")}},[s,t,n,m]);return e.jsxs(Ls,{open:r,onOpenChange:I,children:[e.jsx(nl,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"gap-1.5 shrink-0",title:"Record a video",children:[e.jsx(Kr,{className:"h-3.5 w-3.5"}),"Record"]})}),e.jsxs(Ps,{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(Os,{children:e.jsxs(Ds,{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(($,H)=>e.jsxs("button",{onClick:()=>D(H),className:At("text-left p-3 rounded-lg border transition-all hover:bg-accent/50",C===H?"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(Fr,{className:"h-3.5 w-3.5 text-primary shrink-0"}),e.jsx("span",{className:"text-sm font-medium",children:$.label})]}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 ml-5.5",children:$.text})]},H))})]}),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"}),!y&&e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>v(!0),className:"h-7 text-xs gap-1",children:[e.jsx(Ya,{className:"h-3 w-3"}),"Edit"]})]}),y?e.jsx(Ms,{value:p,onChange:$=>f($.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(Ms,{value:p,onChange:$=>{f($.target.value),E(null)},rows:4,placeholder:"Type your own script here...",className:"text-sm"})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:V,className:"text-muted-foreground",children:"Skip — no teleprompter"}),e.jsx(B,{onClick:O,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(xl,{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(B,{variant:"ghost",size:"sm",onClick:()=>b(!g),className:"h-7 text-xs gap-1",children:[g?e.jsx(Ax,{className:"h-3 w-3"}):e.jsx(ya,{className:"h-3 w-3"}),g?"Hide Script":"Show Script"]})]}),e.jsx($E,{maxDurationSeconds:600,onRecordingComplete:G,onRecordingStateChange:S,onError:$=>se.error($),teleprompterContent:p.trim()?e.jsx(aat,{text:p,isVisible:g,onToggleVisibility:()=>b(!g),isRecording:j,startCountdown:!1}):void 0}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>l("script"),className:"text-xs text-muted-foreground",children:"← Back to script"})]}):i==="uploading"?e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12",children:[e.jsx(Ct,{className:"h-10 w-10 animate-spin text-primary"}),e.jsxs("div",{className:"w-full max-w-xs space-y-2",children:[e.jsx(Fi,{value:o,className:"h-2"}),e.jsxs("p",{className:"text-sm text-muted-foreground text-center",children:["Uploading... ",Math.round(o),"%"]})]})]}):i==="processing"?e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12",children:[e.jsx(Ct,{className:"h-10 w-10 animate-spin text-primary"}),e.jsxs("div",{className:"w-full max-w-xs space-y-2",children:[e.jsx(Fi,{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(_l,{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 Fir({sectionTitle:s,contactId:t,onVideoReady:n}){const[r,a]=_.useState(!1),[i,l]=_.useState(null),[o,c]=_.useState("idle"),[d,u]=_.useState(0),h=_.useRef(null),m=TC(),{data:p}=XIe(),f=(p==null?void 0:p.total_storage_mb)||0,v=((p==null?void 0:p.max_storage_mb)||1024)-f,g=()=>{l(null),c("idle"),u(0)},b=P=>{!P&&o!=="idle"&&o!=="done"||(a(P),P||g())},j=P=>{var D;const M=(D=P.target.files)==null?void 0:D[0];if(!M)return;if(!M.type.startsWith("video/")){se.error("Please select a video file");return}const I=M.size/(1024*1024);if(I>500){se.error("Video file must be less than 500MB");return}if(I>v){se.error(`Not enough storage. You have ${v.toFixed(1)} MB remaining.`);return}l(M)},S=_.useCallback(async()=>{if(i){c("creating"),u(0);try{const P=s||i.name,{data:M,error:I}=await q.functions.invoke("bunny-upload",{body:{action:"create",title:P,isAgentVideo:!0}});if(I)throw new Error(I.message);const{videoId:D,libraryId:O}=M;c("uploading");const{data:V,error:G}=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:D,isAgentVideo:!0}});if(G)throw new Error(G.message);await new Promise((Y,Z)=>{const ne=new XMLHttpRequest;ne.upload.addEventListener("progress",ce=>{ce.lengthComputable&&u(Math.round(ce.loaded/ce.total*100))}),ne.addEventListener("load",()=>ne.status>=200&&ne.status<300?Y():Z(new Error(`Upload failed (${ne.status})`))),ne.addEventListener("error",()=>Z(new Error("Upload failed"))),ne.open("PUT",V.uploadUrl),ne.setRequestHeader("AccessKey",V.apiKey),ne.send(i)}),c("processing");const $=i.size/(1024*1024),H=`https://iframe.mediadelivery.net/embed/${O}/${D}`;await m.mutateAsync({bunny_video_id:D,playback_url:H,file_size_mb:$,title:P,contact_id:t||void 0,status:"processing",touch_type:"presentation"}),n(H),c("done"),se.success("Video uploaded & attached to section!"),setTimeout(()=>a(!1),1200)}catch(P){console.error("Upload error:",P),se.error(P instanceof Error?P.message:"Failed to upload video"),c("idle")}}},[i,s,t,n,m]),C=()=>{switch(o){case"creating":return"Preparing upload...";case"uploading":return`Uploading... ${d}%`;case"processing":return"Saving video...";case"done":return"Done!";default:return""}},E=o!=="idle"&&o!=="done";return e.jsxs(Ls,{open:r,onOpenChange:b,children:[e.jsx(nl,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"gap-1.5 shrink-0",title:"Upload a video file",children:[e.jsx(Oa,{className:"h-3.5 w-3.5"}),"Upload"]})}),e.jsxs(Ps,{className:"sm:max-w-md",children:[e.jsx(Os,{children:e.jsxs(Ds,{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(Kr,{className:"h-8 w-8 text-primary flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:i.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(i.size/(1024*1024)).toFixed(1)," MB"]})]}),!E&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>l(null),children:e.jsx(Qn,{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(Oa,{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:j,disabled:E}),E&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Ct,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{children:C()})]}),e.jsx(Fi,{value:o==="uploading"?d:o==="processing"?100:10})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>b(!1),disabled:E,children:"Cancel"}),e.jsx(B,{onClick:S,disabled:!i||E,children:E?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Oa,{className:"h-4 w-4 mr-2"}),"Upload & Attach"]})})]})]})]})}const J4t=[{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"}],eCt=()=>{const s=Fn(),{id:t}=Li(),{user:n}=hs(),{templates:r,templatesLoading:a,createPresentation:i,updatePresentation:l,publishPresentation:o}=das(),{isGmailConnected:c,gmailEmail:d}=Vg(),[u,h]=_.useState(!1),[m,p]=_.useState("client"),[f,y]=_.useState(!1),[v,g]=_.useState(""),[b,j]=_.useState([]),[S,C]=_.useState(!1),[E,P]=_.useState(null),[M,I]=_.useState(!1),[D,O]=_.useState(""),[V,G]=_.useState(""),[$,H]=_.useState(""),[Y,Z]=_.useState("buyer"),[ne,ce]=_.useState(""),[ie,te]=_.useState(null),[ae,le]=_.useState(""),[be,me]=_.useState([]),[he,pe]=_.useState("schedule_call"),[Ce,Ae]=_.useState("Schedule a Call"),[Pe,ze]=_.useState(""),[ke,Ze]=_.useState(""),[Se,Fe]=_.useState(null),[Ne,Ye]=_.useState(t||null),[Ve,qe]=_.useState(null),[Qe,Ue]=_.useState(!1),Xe=async(vt,$s)=>{if(!n)return;const As=5*1024*1024;if(vt.size>As){se.error("Image must be under 5MB");return}if(!vt.type.startsWith("image/")){se.error("Please upload an image file");return}Fe($s);try{const jn=vt.name.split(".").pop()||"jpg",ar=`${n.id}/${Date.now()}.${jn}`,{error:Dn}=await q.storage.from("listing-photos").upload(ar,vt);if(Dn)throw Dn;const{data:{publicUrl:Ur}}=q.storage.from("listing-photos").getPublicUrl(ar);qt($s,{image_url:Ur}),se.success("Image uploaded")}catch{se.error("Failed to upload image")}finally{Fe(null)}};_.useEffect(()=>{t&&nt(t)},[t]);const nt=async vt=>{const{data:$s,error:As}=await q.from("smart_presentations").select("*").eq("id",vt).single();if(As||!$s)return;const jn=$s;if(y(!0),le(jn.title),O(jn.client_name||""),ce(jn.property_address||""),me(jn.sections||[]),pe(jn.cta_type||"schedule_call"),Ae(jn.cta_label||"Schedule a Call"),ze(jn.cta_url||""),Ze(jn.heading||""),qe(jn.share_token),Ue(jn.status==="published"),Ye(jn.id),p("builder"),jn.contact_id){const{data:ar}=await q.from("innercircle_contacts").select("id, first_name, last_name, email, phone").eq("id",jn.contact_id).maybeSingle();ar&&(P(ar),G(ar.email||""),H(ar.phone||""))}};_.useEffect(()=>{if(!n||v.length<1){j([]);return}const vt=setTimeout(async()=>{C(!0);const{data:$s}=await q.from("innercircle_contacts").select("id, first_name, last_name, email, phone, lead_source").eq("owner_user_id",n.id).or(`first_name.ilike.%${v}%,last_name.ilike.%${v}%,email.ilike.%${v}%`).limit(10);j($s||[]),C(!1)},300);return()=>clearTimeout(vt)},[v,n]);const $e=vt=>{P(vt),O(`${vt.first_name} ${vt.last_name||""}`.trim()),G(vt.email||""),H(vt.phone||""),I(!1)},Ge=async()=>{if(!D.trim()){se.error("Client name is required");return}const vt=D.trim().split(" "),$s=vt[0],As=vt.slice(1).join(" ")||null,{data:jn,error:ar}=await q.from("innercircle_contacts").insert({owner_user_id:n.id,first_name:$s,last_name:As,email:V||null,phone:$||null,lead_source:"Smart Presentation"}).select().single();if(ar){se.error("Failed to create client");return}P(jn),se.success("Client created & saved to Agent OS"),p("template")},ct=vt=>{te(vt);const $s=(vt.sections||[]).map(As=>({...As,is_visible:!0,video_url:"",text:""}));if(me($s),le(vt.name+(D?` for ${D}`:"")),vt.cta_config){const As=vt.cta_config;pe(As.type||"schedule_call"),Ae(As.label||"Schedule a Call")}p("builder")},xt=()=>{me([{title:"Welcome",description:"A personal welcome",type:"video",icon:"👋",is_visible:!0}]),le(D?`Presentation for ${D}`:"New Presentation"),p("builder")},qt=(vt,$s)=>{me(As=>As.map((jn,ar)=>ar===vt?{...jn,...$s}:jn))},Vt=vt=>{qt(vt,{is_visible:!be[vt].is_visible})},Xt=()=>{me(vt=>[...vt,{title:"New Section",description:"",type:"video",icon:"📝",is_visible:!0}])},fs=vt=>{me($s=>$s.filter((As,jn)=>jn!==vt))},Ft=async()=>{if(!ae.trim()){se.error("Title is required");return}try{if(Ne){const vt=await l.mutateAsync({id:Ne,title:ae,sections:be,client_name:D,property_address:ne||null,cta_type:he,cta_label:Ce,cta_url:Pe||null,heading:ke||null});se.success("Saved")}else{const vt=await i.mutateAsync({title:ae,contact_id:(E==null?void 0:E.id)||void 0,client_name:D,property_address:ne||void 0,template_id:(ie==null?void 0:ie.id)||void 0,sections:be,cta_type:he,cta_label:Ce,cta_url:Pe||void 0,heading:ke||void 0});Ye(vt.id),qe(vt.share_token),se.success("Presentation created!")}}catch(vt){console.error("Failed to save presentation:",vt);const $s=(vt==null?void 0:vt.message)||(vt==null?void 0:vt.toString())||"Unknown error";se.error(`Failed to save: ${$s}`)}},wt=async()=>{try{await Ft();const vt=Ne;if(vt){const $s=await o.mutateAsync(vt);qe($s.share_token),Ue(!0),p("share")}}catch(vt){console.error("Failed to publish presentation:",vt),se.error(`Failed to publish: ${(vt==null?void 0:vt.message)||"Unknown error"}`)}},Ts=Ve?`https://presentations.relevelup.com/${Ve}`:"";return e.jsx(zs,{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(B,{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:f?"Edit Presentation":"Create Smart Presentation"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[m==="client"&&"Who is this presentation for?",m==="template"&&"Choose a starting template",m==="builder"&&"Customize your presentation",m==="share"&&"Share with your client"]})]})]}),!f&&e.jsx("div",{className:"flex items-center gap-2",children:["client","template","builder","share"].map((vt,$s)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:At("w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium transition-colors",m===vt?"bg-primary text-primary-foreground":$s<["client","template","builder","share"].indexOf(m)?"bg-emerald-100 text-emerald-700":"bg-muted text-muted-foreground"),children:$s<["client","template","builder","share"].indexOf(m)?e.jsx(ea,{className:"h-4 w-4"}):$s+1}),e.jsx("span",{className:"text-sm font-medium capitalize hidden sm:inline",children:vt}),$s<3&&e.jsx("div",{className:"w-8 h-px bg-border"})]},vt))}),m==="client"&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("button",{onClick:()=>{P(null),O(""),G(""),H(""),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(Or,{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(La,{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(ve,{children:[e.jsx(bt,{className:"pb-3",children:e.jsxs(St,{className:"text-base flex items-center gap-2",children:[e.jsx(Lr,{className:"h-4 w-4 text-muted-foreground"}),"Select Existing Client"]})}),e.jsxs(Me,{className:"space-y-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search by name or email...",value:v,onChange:vt=>g(vt.target.value),className:"pl-10"})]}),e.jsxs("div",{className:"space-y-2 max-h-56 overflow-y-auto",children:[S&&e.jsx(cn,{className:"h-12 w-full"}),b.map(vt=>e.jsxs("button",{onClick:()=>$e(vt),className:At("w-full text-left p-3 rounded-lg border transition-colors",(E==null?void 0:E.id)===vt.id?"border-primary bg-primary/5":"border-border hover:border-primary/50"),children:[e.jsxs("p",{className:"font-medium text-sm",children:[vt.first_name," ",vt.last_name]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:vt.email||vt.phone||"No contact info"})]},vt.id)),!v&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"Start typing to search your contacts"}),v&&b.length===0&&!S&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No clients found"})]}),E&&e.jsxs(B,{onClick:()=>p("template"),className:"w-full gap-2",children:["Continue with ",E.first_name,e.jsx(La,{className:"h-4 w-4"})]})]})]}),e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-3",children:e.jsxs(St,{className:"text-base flex items-center gap-2",children:[e.jsx(Pl,{className:"h-4 w-4 text-muted-foreground"}),"Add New Client"]})}),e.jsxs(Me,{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(J,{className:"text-xs",children:"Name *"}),e.jsx(xe,{value:D,onChange:vt=>{O(vt.target.value),I(!0),P(null)},placeholder:"Sarah & Mike Johnson"})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Email"}),e.jsx(xe,{value:V,onChange:vt=>G(vt.target.value),placeholder:"Optional",type:"email"})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Phone"}),e.jsx(xe,{value:$,onChange:vt=>H(vt.target.value),placeholder:"Optional"})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Client Type"}),e.jsxs(is,{value:Y,onValueChange:Z,children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"buyer",children:"Buyer"}),e.jsx(He,{value:"seller",children:"Seller"}),e.jsx(He,{value:"recruit",children:"Recruit"}),e.jsx(He,{value:"other",children:"Other"})]})]})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Property Address"}),e.jsx(xe,{value:ne,onChange:vt=>ce(vt.target.value),placeholder:"Optional"})]})]}),M&&D&&e.jsxs(B,{onClick:Ge,className:"w-full gap-2",children:["Create Client & Continue",e.jsx(La,{className:"h-4 w-4"})]})]})]})]})]}),m==="template"&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs(Yr,{defaultValue:"system",children:[e.jsxs(Zr,{children:[e.jsx(Ht,{value:"mine",children:"My Core Templates"}),e.jsx(Ht,{value:"system",children:"LevelUp Smart Templates"}),e.jsx(Ht,{value:"blank",children:"+ Start Blank"})]}),e.jsx(Gt,{value:"mine",className:"mt-4",children:a?e.jsx("div",{className:"grid grid-cols-2 gap-4",children:[1,2].map(vt=>e.jsx(cn,{className:"h-32"},vt))}):e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:r.filter(vt=>!vt.is_system).length===0?e.jsx("p",{className:"text-muted-foreground col-span-2 text-center py-8",children:"You haven't saved any templates yet. Create a presentation and save it as a template!"}):r.filter(vt=>!vt.is_system).map(vt=>e.jsx(tCt,{template:vt,onSelect:ct},vt.id))})}),e.jsx(Gt,{value:"system",className:"mt-4",children:e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:r.filter(vt=>vt.is_system).map(vt=>e.jsx(tCt,{template:vt,onSelect:ct},vt.id))})}),e.jsx(Gt,{value:"blank",className:"mt-4",children:e.jsx(ve,{children:e.jsxs(Me,{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(B,{onClick:xt,children:"Start from Scratch"})]})})})]}),e.jsxs(B,{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(ve,{children:e.jsxs(Me,{className:"pt-6 space-y-4",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Presentation Title"}),e.jsx(xe,{value:ae,onChange:vt=>le(vt.target.value)})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Page Heading"}),e.jsx(xe,{value:ke,onChange:vt=>Ze(vt.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(J,{children:"Client Name"}),e.jsx(xe,{value:D,onChange:vt=>O(vt.target.value)})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Property Address"}),e.jsx(xe,{value:ne,onChange:vt=>ce(vt.target.value),placeholder:"Optional"})]})]})]})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Sections"}),e.jsx(B,{variant:"outline",size:"sm",onClick:Xt,children:"+ Add Section"})]}),e.jsx("div",{className:"space-y-3",children:be.map((vt,$s)=>e.jsx(ve,{className:At(!vt.is_visible&&"opacity-50"),children:e.jsx(Me,{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(Vf,{className:"h-4 w-4 text-muted-foreground cursor-grab"}),e.jsx("span",{className:"text-lg",children:vt.icon})]}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(xe,{value:vt.title,onChange:As=>qt($s,{title:As.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(B,{variant:"ghost",size:"icon",onClick:()=>Vt($s),children:vt.is_visible?e.jsx(ya,{className:"h-4 w-4"}):e.jsx(Ax,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>fs($s),className:"text-destructive hover:text-destructive",children:e.jsx(Sn,{className:"h-4 w-4"})})]})]}),e.jsx(xe,{value:vt.description||"",onChange:As=>qt($s,{description:As.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(J,{className:"text-xs",children:"Video URL"}),e.jsx(xe,{value:vt.video_url||"",onChange:As=>qt($s,{video_url:As.target.value}),placeholder:"Paste a YouTube or video URL...",className:"text-sm"})]}),e.jsx(Rir,{sectionTitle:vt.title,contactId:E==null?void 0:E.id,onVideoReady:As=>qt($s,{video_url:As})}),e.jsx(Fir,{sectionTitle:vt.title,contactId:E==null?void 0:E.id,onVideoReady:As=>qt($s,{video_url:As})}),e.jsx(iz,{userId:n==null?void 0:n.id,onSelect:As=>qt($s,{video_url:As})})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Image (optional — shown if no video is set)"}),vt.image_url?e.jsxs("div",{className:"relative mt-1 rounded-lg overflow-hidden border border-border bg-muted/30 group",children:[e.jsx("img",{src:vt.image_url,alt:"",className:"w-full max-h-40 object-cover"}),e.jsx(B,{variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>qt($s,{image_url:""}),children:e.jsx(Qn,{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===$s?e.jsx(Ct,{className:"h-4 w-4 animate-spin text-muted-foreground"}):e.jsx(jy,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:Se===$s?"Uploading...":"Click to upload an image"}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",disabled:Se===$s,onChange:As=>{var ar;const jn=(ar=As.target.files)==null?void 0:ar[0];jn&&Xe(jn,$s),As.target.value=""}})]})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Text (optional)"}),e.jsx(BN,{content:vt.text||"",onChange:As=>qt($s,{text:As}),placeholder:"Add supporting text...",minHeight:"80px",compact:!0})]})]})]})})},$s))})]}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"Call to Action"})}),e.jsxs(Me,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(J,{children:"CTA Type"}),e.jsxs(is,{value:he,onValueChange:vt=>{pe(vt);const $s=J4t.find(As=>As.value===vt);$s&&Ae($s.label)},children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsx(as,{children:J4t.map(vt=>e.jsx(He,{value:vt.value,children:vt.label},vt.value))})]})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Button Label"}),e.jsx(xe,{value:Ce,onChange:vt=>Ae(vt.target.value)})]}),e.jsxs("div",{children:[e.jsxs(J,{children:["Link URL ",e.jsx("span",{className:"text-muted-foreground",children:"(optional — leave blank to show a lead capture form instead)"})]}),e.jsx(xe,{value:Pe,onChange:vt=>ze(vt.target.value),placeholder:"https://calendly.com/..."}),!Pe&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Without a URL, clients will see a contact form — their info gets added to your contacts and you'll receive an email notification."})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[!f&&e.jsxs(B,{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(B,{variant:"outline",onClick:Ft,disabled:i.isPending||l.isPending,children:"Save Draft"}),e.jsxs(B,{onClick:wt,disabled:o.isPending,className:"gap-2",children:[e.jsx(Or,{className:"h-4 w-4"}),Qe?"Update & Reshare":"Publish & Share"]})]})]})]}),m==="share"&&Ve&&e.jsxs("div",{className:"space-y-6",children:[e.jsx(ve,{children:e.jsxs(Me,{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(ea,{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(xe,{value:Ts,readOnly:!0,className:"text-center font-mono text-sm"}),e.jsx(B,{onClick:()=>{navigator.clipboard.writeText(Ts),se.success("Link copied!")},children:e.jsx(Ia,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex gap-3 mt-6",children:[e.jsxs(B,{variant:"outline",className:"gap-2",onClick:()=>{const vt=`Hi ${D||""}! I put together something for you — check it out: ${Ts}`;navigator.clipboard.writeText(vt),se.success("Message copied!")},children:[e.jsx(Hi,{className:"h-4 w-4"}),"Copy Text Message"]}),e.jsxs(B,{variant:"outline",className:"gap-2",onClick:()=>{c?h(!0):window.open(`mailto:${V||""}?subject=${encodeURIComponent(ae)}&body=${encodeURIComponent(`Hi ${(E==null?void 0:E.first_name)||(D==null?void 0:D.split(" ")[0])||""}, I put together a personalized presentation for you: ${Ts} Looking forward to connecting!`)}`)},children:[e.jsx(ln,{className:"h-4 w-4"}),"Send Email"]})]}),c&&e.jsx(DS,{open:u,onOpenChange:h,contact:E?{id:E.id,first_name:E.first_name,last_name:E.last_name,email:V||E.email||""}:V?{id:"",first_name:(D==null?void 0:D.split(" ")[0])||"",last_name:(D==null?void 0:D.split(" ").slice(1).join(" "))||"",email:V}:void 0,defaultSubject:ae,defaultBody:`Hi ${(E==null?void 0:E.first_name)||(D==null?void 0:D.split(" ")[0])||""}, I put together a personalized presentation for you: ${Ts} Looking forward to connecting!`,gmailEmail:d})]})}),e.jsxs("div",{className:"flex justify-between",children:[e.jsxs(B,{variant:"outline",onClick:()=>p("builder"),children:[e.jsx(ka,{className:"h-4 w-4 mr-2"}),"Edit Presentation"]}),e.jsx(B,{onClick:()=>s("/mission-control/presentations"),children:"Done"})]})]})]})})},tCt=({template:s,onSelect:t})=>e.jsx(ve,{className:"hover:shadow-sm transition-shadow",children:e.jsxs(Me,{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(Oe,{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(B,{className:"w-full mt-4",size:"sm",onClick:()=>t(s),children:"Use Template"})]})}),Oir=()=>{var y;const{shareToken:s}=Li(),[t,n]=_.useState(null),[r,a]=_.useState(!0),[i,l]=_.useState(0),[o,c]=_.useState(!1);_.useEffect(()=>(document.body.classList.add("presentation-page"),()=>{document.body.classList.remove("presentation-page")}),[]),_.useEffect(()=>{s&&d()},[s]);const d=async()=>{const{data:v,error:g}=await q.from("smart_presentations").select("*").eq("share_token",s).eq("status","published").single();if(g||!v){c(!0),a(!1);return}const{data:b}=await q.from("profiles").select("name, email, phone, avatar_url, title, brokerage_id").eq("id",v.owner_user_id).single();let j;if(b!=null&&b.brokerage_id){const{data:C}=await q.from("brokerages").select("name").eq("id",b.brokerage_id).single();j=(C==null?void 0:C.name)||void 0}let S=null;if(v.contact_id){const{data:C}=await q.from("innercircle_contacts").select("first_name, last_name, email, phone").eq("id",v.contact_id).single();S=C}n({...v,owner_name:b==null?void 0:b.name,owner_email:b==null?void 0:b.email,owner_phone:b==null?void 0:b.phone,owner_avatar:b==null?void 0:b.avatar_url,owner_title:(b==null?void 0:b.title)||void 0,brokerage_name:j,contact_name:S?[S.first_name,S.last_name].filter(Boolean).join(" "):void 0,contact_email:(S==null?void 0:S.email)||void 0,contact_phone:(S==null?void 0:S.phone)||void 0}),a(!1);try{await q.rpc("log_presentation_view",{p_presentation_id:v.id,p_section_index:0,p_cta_clicked:!1,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null})}catch{}},u=async()=>{if(t){try{await q.rpc("log_presentation_view",{p_presentation_id:t.id,p_section_index:null,p_cta_clicked:!0,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:null})}catch{}t.cta_url&&window.open(t.cta_url,"_blank")}};if(r)return e.jsx("div",{className:"min-h-screen bg-white flex items-center justify-center",children:e.jsxs("div",{className:"space-y-4 w-full max-w-2xl px-4",children:[e.jsx(cn,{className:"h-12 w-3/4 mx-auto"}),e.jsx(cn,{className:"h-64 w-full"}),e.jsx(cn,{className:"h-8 w-1/2 mx-auto"})]})});if(o||!t)return e.jsx("div",{className:"min-h-screen bg-white flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Presentation Not Found"}),e.jsx("p",{className:"text-gray-500",children:"This presentation may have been removed or is no longer available."})]})});const h=t.sections.filter(v=>v.is_visible!==!1),m=h[i],p=v=>{const g=v.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/)([a-zA-Z0-9_-]+)/);if(g)return`https://www.youtube.com/embed/${g[1]}?rel=0`;if(v.includes("iframe.mediadelivery.net/play/")){const S=v.replace("/play/","/embed/"),C=S.includes("?")?"&":"?";return`${S}${C}responsive=true`}if(v.includes("iframe.mediadelivery.net")){if(v.match(/\/embed\/(\d+)\/([a-f0-9-]+)/)){const C=v.includes("?")?"&":"?";return`${v}${C}responsive=true`}return""}const b=v.match(/loom\.com\/share\/([a-zA-Z0-9]+)/);if(b)return`https://www.loom.com/embed/${b[1]}`;const j=v.match(/video\.bunnycdn\.com\/play\/(\d+)\/([a-f0-9-]+)/);return j?`https://iframe.mediadelivery.net/embed/${j[1]}/${j[2]}?responsive=true`:v},f=!!((y=t.cta_url)!=null&&y.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((v,g)=>e.jsx("button",{onClick:()=>l(g),className:At("w-full text-left p-4 rounded-xl border transition-all",i===g?"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(g+1).padStart(2,"0"),"."]}),e.jsxs("div",{children:[e.jsx("span",{className:"mr-2",children:v.icon}),e.jsx("span",{className:"font-semibold text-gray-900",children:v.title}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:v.description})]})]})},g))})]}),e.jsxs("div",{className:"mt-12 max-w-md mx-auto bg-white rounded-2xl border border-gray-200 shadow-sm p-6 text-center",children:[t.owner_avatar&&e.jsx("img",{src:t.owner_avatar,alt:t.owner_name||"Agent",className:"h-20 w-20 rounded-full object-cover mx-auto mb-3 border-2 border-gray-100"}),e.jsx("h3",{className:"text-lg font-bold text-gray-900",children:t.owner_name}),t.owner_title&&e.jsx("p",{className:"text-sm text-gray-500",children:t.owner_title}),t.brokerage_name&&e.jsx("p",{className:"text-sm text-gray-500",children:t.brokerage_name}),e.jsxs("div",{className:"mt-3 flex flex-col items-center gap-1 text-sm text-gray-600",children:[t.owner_phone&&e.jsx("a",{href:`tel:${t.owner_phone}`,className:"hover:text-blue-600 transition-colors",children:t.owner_phone}),t.owner_email&&e.jsx("a",{href:`mailto:${t.owner_email}`,className:"hover:text-blue-600 transition-colors",children:t.owner_email})]})]}),t.cta_label&&e.jsxs("div",{className:"text-center mt-8 py-8",children:[e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-4",children:"Ready to Get Started?"}),f?e.jsxs(B,{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(wr,{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(LFt,{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"})]})},FBe="__none__";function zir({value:s,onChange:t}){const{data:n=[],isLoading:r}=Dae(),a=wnt(),[i,l]=_.useState(!1),o=_.useMemo(()=>n.filter(h=>!h.is_starter),[n]),c=_.useMemo(()=>n.find(h=>h.is_starter&&/open house/i.test(h.name||"")),[n]),d=_.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),ia({title:"Open House Follow-Up added",description:"The 6-email sequence is now in your library and selected here."})}catch(h){ia({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(J,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(nP,{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(Oe,{variant:"outline",className:"text-[10px] border-emerald-300 bg-emerald-500/10 text-emerald-700",children:"On"})]}),e.jsxs(is,{value:s??FBe,onValueChange:h=>t(h===FBe?null:h),disabled:r,children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"No follow-up campaign"})}),e.jsxs(as,{children:[e.jsx(He,{value:FBe,children:"No follow-up campaign"}),o.map(h=>e.jsxs(He,{value:h.id,children:[h.icon?`${h.icon} `:"",h.name,h.is_active?"":" (paused)"]},h.id))]})]}),c&&!d&&e.jsxs(B,{type:"button",variant:"outline",size:"sm",className:"w-full gap-1.5 text-xs",onClick:u,disabled:i,children:[i?e.jsx(Ct,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(un,{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 Bir({openHouseId:s,enableSurvey:t,onToggleSurvey:n}){const{data:r,isLoading:a}=DMs(s),i=zMs(),l=BMs(),o=UMs(),c=qMs(),[d,u]=_.useState(""),[h,m]=_.useState("rating"),p=async g=>{n(g),g&&(!r||r.length===0)&&await c.mutateAsync(s)},f=async()=>{if(!d.trim())return;const g=(r==null?void 0:r.reduce((b,j)=>Math.max(b,j.sort_order),0))??0;await i.mutateAsync({open_house_id:s,question_type:h,question_text:d.trim(),sort_order:g+1}),u("")},y=async g=>{await l.mutateAsync({id:g.id,open_house_id:s,is_active:!g.is_active})},v=async g=>{await o.mutateAsync({id:g.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(J,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(qf,{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(fn,{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(Ct,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-2",children:r==null?void 0:r.map(g=>e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg border border-border bg-muted/20",children:[e.jsx(Vf,{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:g.question_text}),e.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:g.question_type.replace("_"," ")})]}),e.jsx(fn,{checked:g.is_active,onCheckedChange:()=>y(g),className:"scale-75"}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0 text-muted-foreground hover:text-destructive",onClick:()=>v(g),children:e.jsx(Sn,{className:"h-3.5 w-3.5"})})]},g.id))}),e.jsxs("div",{className:"flex items-end gap-2",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(J,{className:"text-xs text-muted-foreground",children:"Add Question"}),e.jsx(xe,{value:d,onChange:g=>u(g.target.value),placeholder:"e.g. How did you hear about this listing?",className:"mt-1 h-9 text-sm",onKeyDown:g=>g.key==="Enter"&&f()})]}),e.jsxs(is,{value:h,onValueChange:m,children:[e.jsx(rs,{className:"w-28 h-9 text-xs",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"rating",children:"Rating"}),e.jsx(He,{value:"open_text",children:"Text"})]})]}),e.jsx(B,{size:"sm",variant:"outline",onClick:f,disabled:!d.trim()||i.isPending,className:"h-9",children:e.jsx(rn,{className:"h-3.5 w-3.5"})})]})]})})]})}function Uir({openHouseId:s}){const{user:t}=hs(),{data:n=[],isLoading:r}=GMs(s),a=KMs(),i=JMs(),l=(m,p)=>{const f=m+p;if(f<0||f>=n.length)return;const y=n.map(v=>v.id);[y[m],y[f]]=[y[f],y[m]],i.mutate({open_house_id:s,orderedIds:y})},[o,c]=_.useState(""),[d,u]=_.useState(!1),h=async()=>{const m=o.trim();if(m){u(!0);try{await a.mutateAsync({open_house_id:s,name:m,sort_order:n.length}),c("")}finally{u(!1)}}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(J,{className:"text-sm font-medium",children:"Rooms"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Add rooms and upload photos or videos (or pull a clip from your Video Library). Use the up/down arrows to reorder rooms and the arrows on each tile to reorder photos and videos. Visitors swipe through them on mobile and tab through them on desktop."})]}),r?e.jsxs("div",{className:"py-6 text-center text-sm text-muted-foreground",children:[e.jsx(Ct,{className:"h-4 w-4 animate-spin inline"})," Loading…"]}):n.length===0?e.jsx("p",{className:"text-xs text-muted-foreground italic",children:"No rooms yet — add your first below."}):e.jsx("div",{className:"space-y-3",children:n.map((m,p)=>e.jsx(qir,{room:m,index:p,total:n.length,userId:(t==null?void 0:t.id)||"",openHouseId:s,onMoveRoom:l},m.id))}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(xe,{value:o,onChange:m=>c(m.target.value),placeholder:"e.g. Kitchen, Primary Bedroom, Backyard…",onKeyDown:m=>{m.key==="Enter"&&(m.preventDefault(),h())}}),e.jsx(B,{onClick:h,disabled:!o.trim()||d,size:"sm",children:d?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(rn,{className:"h-4 w-4 mr-1"})," Add"]})})]})]})}function qir({room:s,index:t,total:n,userId:r,openHouseId:a,onMoveRoom:i}){const l=YMs(),o=ZMs(),c=XMs(),d=QMs(),u=ePs(),h=_.useRef(null),[m,p]=_.useState(!0),[f,y]=_.useState(s.name),[v,g]=_.useState(s.description||""),[b,j]=_.useState(!1),S=_.useMemo(()=>s.media.filter(V=>V.kind==="video"&&V.agent_video_id).map(V=>V.agent_video_id),[s.media]),{data:C={}}=at({queryKey:["room-video-statuses",s.id,S.join(",")],enabled:S.length>0,queryFn:async()=>{const{data:V,error:G}=await q.from("agent_videos").select("id, status, bunny_video_id, thumbnail_url, preview_url").in("id",S);if(G)throw G;const $=V||[],H=$.filter(Z=>Z.status==="processing"&&Z.bunny_video_id);await Promise.all(H.map(async Z=>{try{const{data:ne}=await q.functions.invoke("bunny-upload",{body:{action:"status",videoId:Z.bunny_video_id,isAgentVideo:!0}});ne&&ne.status===4&&(await q.from("agent_videos").update({status:"ready",playback_url:ne.directPlayUrl,thumbnail_url:ne.thumbnailUrl,preview_url:ne.previewUrl,duration_seconds:ne.length||void 0,updated_at:new Date().toISOString()}).eq("id",Z.id),Z.status="ready",Z.thumbnail_url=ne.thumbnailUrl,Z.preview_url=ne.previewUrl)}catch{}}));const Y={};return $.forEach(Z=>{Y[Z.id]={status:Z.status,thumbnail_url:Z.thumbnail_url,preview_url:Z.preview_url}}),Y},refetchInterval:V=>{const G=V.state.data;return G?Object.values(G).some($=>$.status!=="ready"&&$.status!=="failed")?5e3:!1:5e3}}),E=()=>{f.trim()&&f!==s.name&&l.mutate({id:s.id,open_house_id:a,name:f.trim()})},P=()=>{v!==(s.description||"")&&l.mutate({id:s.id,open_house_id:a,description:v.trim()||null})},M=async()=>{await Xi(`Delete "${s.name}" and all its media?`)&&o.mutate({id:s.id,open_house_id:a})},I=V=>i(t,V),D=(V,G)=>{const $=V+G;if($<0||$>=s.media.length)return;const H=s.media.map(Y=>Y.id);[H[V],H[$]]=[H[$],H[V]],u.mutate({open_house_id:a,room_id:s.id,orderedIds:H})},O=async V=>{const G=Array.from(V.target.files||[]);if(!(!G.length||!r)){j(!0);try{for(const $ of G){const H=$.type.startsWith("video/"),Y=H?500*1024*1024:15*1024*1024;if($.size>Y){ia({title:`${$.name} is too large`,description:H?"Videos must be under 500MB":"Photos must be under 15MB",variant:"destructive"});continue}if(H){try{const te=`${s.name} – ${$.name.replace(/\.[^/.]+$/,"")}`,{data:ae,error:le}=await q.functions.invoke("bunny-upload",{body:{action:"create",title:te,isAgentVideo:!0}});if(le||!ae)throw new Error((le==null?void 0:le.message)||"Could not start upload");const{videoId:be,libraryId:me}=ae,{data:he,error:pe}=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:be,isAgentVideo:!0}});if(pe||!he)throw new Error((pe==null?void 0:pe.message)||"Could not get upload URL");await new Promise((ke,Ze)=>{const Se=new XMLHttpRequest;Se.addEventListener("load",()=>{Se.status>=200&&Se.status<300?ke():Ze(new Error(`Upload failed (${Se.status})`))}),Se.addEventListener("error",()=>Ze(new Error("Upload failed"))),Se.open("PUT",he.uploadUrl),Se.setRequestHeader("AccessKey",he.apiKey),Se.send($)});const Ce=`https://iframe.mediadelivery.net/embed/${me}/${be}`,Ae=$.size/(1024*1024),{data:Pe,error:ze}=await q.from("agent_videos").insert({owner_user_id:r,bunny_video_id:be,playback_url:Ce,file_size_mb:Ae,title:te,status:"processing",touch_type:"open_house_tour",category:"open_house",page_template:"default"}).select().single();if(ze)throw ze;await c.mutateAsync({open_house_id:a,room_id:s.id,kind:"video",url:Ce,sort_order:s.media.length,agent_video_id:Pe.id}),ia({title:"Video uploaded",description:"Processing in the background — it’ll appear in your Video Library too."})}catch(te){ia({title:"Video upload failed",description:(te==null?void 0:te.message)||"Try again",variant:"destructive"})}continue}const Z=$.name.split(".").pop()||"jpg",ne=`${r}/${a}/rooms/${s.id}-${Date.now()}-${Math.random().toString(36).slice(2,7)}.${Z}`,{error:ce}=await q.storage.from("open-house-tour-media").upload(ne,$,{upsert:!1,contentType:$.type});if(ce){ia({title:"Upload failed",description:ce.message,variant:"destructive"});continue}const{data:ie}=q.storage.from("open-house-tour-media").getPublicUrl(ne);await c.mutateAsync({open_house_id:a,room_id:s.id,kind:"photo",url:ie.publicUrl,sort_order:s.media.length})}}finally{j(!1),h.current&&(h.current.value="")}}};return e.jsxs("div",{className:"rounded-lg border border-border bg-card",children:[e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 border-b border-border",children:[e.jsx(Vf,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("button",{onClick:()=>p(V=>!V),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(B,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>I(-1),disabled:t===0,children:e.jsx(_v,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>I(1),disabled:t===n-1,children:e.jsx(tl,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-7 w-7 text-destructive",onClick:M,children:e.jsx(Sn,{className:"h-4 w-4"})})]}),m&&e.jsxs("div",{className:"p-3 space-y-3",children:[e.jsx(xe,{value:f,onChange:V=>y(V.target.value),onBlur:E,placeholder:"Room name",className:"h-9"}),e.jsx(Ms,{value:v,onChange:V=>g(V.target.value),onBlur:P,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((V,G)=>{const $=V.agent_video_id?C[V.agent_video_id]:void 0,H=$==null?void 0:$.status,Y=V.kind==="video"&&H&&H!=="ready"&&H!=="failed",Z=V.kind==="video"&&H==="failed",ne=($==null?void 0:$.thumbnail_url)||($==null?void 0:$.preview_url);return e.jsxs("div",{className:"relative aspect-square rounded-md overflow-hidden bg-muted group",children:[V.kind==="video"?e.jsxs(e.Fragment,{children:[ne?e.jsx("img",{src:ne,alt:"",className:"w-full h-full object-cover"}):/iframe\.mediadelivery\.net\/embed\//.test(V.url)?e.jsx("div",{className:"w-full h-full bg-slate-800"}):e.jsx("video",{src:V.url,className:"w-full h-full object-cover"}),!Y&&!Z&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/30 pointer-events-none",children:e.jsx(Kr,{className:"h-6 w-6 text-white"})}),Y&&e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center bg-black/70 text-white gap-1 pointer-events-none",children:[e.jsx(Ct,{className:"h-5 w-5 animate-spin"}),e.jsx("span",{className:"text-[10px] font-medium uppercase tracking-wide",children:"Processing"})]}),Z&&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:V.url,alt:"",className:"w-full h-full object-cover"}),e.jsx("span",{className:"absolute top-1 left-1 px-1.5 h-5 rounded-full bg-black/60 text-white text-[10px] font-semibold flex items-center",children:G+1}),e.jsx("button",{type:"button","aria-label":"Remove media",onClick:()=>d.mutate({id:V.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(Qn,{className:"h-3.5 w-3.5"})}),e.jsxs("div",{className:"absolute inset-x-1 bottom-1 flex items-center justify-between opacity-0 group-hover:opacity-100 transition",children:[e.jsx("button",{type:"button","aria-label":"Move earlier",disabled:G===0,onClick:()=>D(G,-1),className:"w-6 h-6 rounded-full bg-black/60 text-white flex items-center justify-center disabled:opacity-30",children:e.jsx($c,{className:"h-3.5 w-3.5"})}),e.jsx("button",{type:"button","aria-label":"Move later",disabled:G===s.media.length-1,onClick:()=>D(G,1),className:"w-6 h-6 rounded-full bg-black/60 text-white flex items-center justify-center disabled:opacity-30",children:e.jsx(xi,{className:"h-3.5 w-3.5"})})]})]},V.id)})}),e.jsx("input",{ref:h,type:"file",accept:"image/*,video/*",multiple:!0,onChange:O,className:"hidden"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",size:"sm",onClick:()=>{var V;return(V=h.current)==null?void 0:V.click()},disabled:b,className:"flex-1",children:b?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Oa,{className:"h-4 w-4 mr-2"})," Upload"]})}),e.jsx(iz,{userId:r,triggerLabel:"From Video Library",triggerClassName:"gap-1.5 flex-1 justify-center",onSelect:()=>{},onSelectVideo:async V=>{try{await c.mutateAsync({open_house_id:a,room_id:s.id,kind:"video",url:V.playback_url||"",sort_order:s.media.length,agent_video_id:V.id}),ia({title:"Video added to room"})}catch(G){ia({title:"Failed to add video",description:G==null?void 0:G.message,variant:"destructive"})}}})]})]})]})}function $ir({open:s,onOpenChange:t,openHouse:n}){const r=DFt(),{user:a}=hs(),i=_.useRef(null),l=_.useRef(null),o=_.useRef(null),c=n.kind==="virtual",[d,u]=_.useState(n.auto_forward_to_card??!1),[h,m]=_.useState(n.disclosure_pdf_url??""),[p,f]=_.useState(n.enable_survey??!1),[y,v]=_.useState(n.ask_visitor_intent??!0),[g,b]=_.useState(n.ask_visitor_address??!1),[j,S]=_.useState(n.photo_url??""),[C,E]=_.useState(!1),[P,M]=_.useState(!1),[I,D]=_.useState(!1),[O,V]=_.useState(n.property_address??""),[G,$]=_.useState(n.city??""),[H,Y]=_.useState(n.state??""),[Z,ne]=_.useState(n.zip??""),[ce,ie]=_.useState((n.event_date??"").slice(0,10)),[te,ae]=_.useState((n.start_time??"").slice(0,5)),[le,be]=_.useState((n.end_time??"").slice(0,5)),[me,he]=_.useState(n.hero_video_url??""),[pe,Ce]=_.useState(!1),[Ae,Pe]=_.useState(n.price!=null?String(n.price):""),[ze,ke]=_.useState(n.beds!=null?String(n.beds):""),[Ze,Se]=_.useState(n.baths!=null?String(n.baths):""),[Fe,Ne]=_.useState(n.sqft!=null?String(n.sqft):""),[Ye,Ve]=_.useState(n.enable_question??!0),[qe,Qe]=_.useState(n.enable_showing??!0),[Ue,Xe]=_.useState(n.enable_disclosures??!0),[nt,$e]=_.useState(n.enable_offer??!0),[Ge,ct]=_.useState(n.brand_color_override??""),[xt,qt]=_.useState(n.property_description??""),[Vt,Xt]=_.useState(n.drip_campaign_id??null),fs=async As=>{var hn;const jn=(hn=As.target.files)==null?void 0:hn[0];if(!jn||!a)return;if(jn.size>200*1024*1024){ia({title:"Video must be under 200MB",variant:"destructive"});return}if(!jn.type.startsWith("video/")){ia({title:"Please upload a video file",variant:"destructive"});return}Ce(!0);const ar=jn.name.split(".").pop()||"mp4",Dn=`${a.id}/${n.id}/hero-${Date.now()}.${ar}`,{error:Ur}=await q.storage.from("open-house-tour-media").upload(Dn,jn,{upsert:!0,contentType:jn.type});if(Ur){ia({title:"Upload failed",description:Ur.message,variant:"destructive"}),Ce(!1);return}const{data:Vs}=q.storage.from("open-house-tour-media").getPublicUrl(Dn);he(Vs.publicUrl),Ce(!1),ia({title:"Video uploaded!"})},Ft=async As=>{var hn;const jn=(hn=As.target.files)==null?void 0:hn[0];if(!jn||!a)return;if(jn.size>10*1024*1024){ia({title:"Image must be under 10MB",variant:"destructive"});return}if(!jn.type.startsWith("image/")){ia({title:"Please upload an image file",variant:"destructive"});return}M(!0);const ar=jn.name.split(".").pop()||"jpg",Dn=`${a.id}/${n.id}-${Date.now()}.${ar}`,{error:Ur}=await q.storage.from("open-house-photos").upload(Dn,jn,{upsert:!0});if(Ur){ia({title:"Upload failed",description:Ur.message,variant:"destructive"}),M(!1);return}const{data:Vs}=q.storage.from("open-house-photos").getPublicUrl(Dn);S(Vs.publicUrl),M(!1),ia({title:"Photo updated!"})},wt=()=>{S(""),l.current&&(l.current.value="")},Ts=async As=>{var Vs;const jn=(Vs=As.target.files)==null?void 0:Vs[0];if(!jn||!a)return;if(jn.size>20*1024*1024){ia({title:"File must be under 20MB",variant:"destructive"});return}if(jn.type!=="application/pdf"){ia({title:"Only PDF files are accepted",variant:"destructive"});return}E(!0);const ar=`${a.id}/disclosures/${n.id}-${Date.now()}.pdf`,{error:Dn}=await q.storage.from("open-house-photos").upload(ar,jn,{upsert:!0});if(Dn){ia({title:"Upload failed",description:Dn.message,variant:"destructive"}),E(!1);return}const{data:Ur}=q.storage.from("open-house-photos").getPublicUrl(ar);m(Ur.publicUrl),E(!1),ia({title:"PDF uploaded!"})},vt=()=>{m(""),i.current&&(i.current.value="")},$s=async()=>{if(!O.trim()){ia({title:"Add a property address",variant:"destructive"});return}if(!ce){ia({title:"Pick a date for the open house",variant:"destructive"});return}D(!0);try{const As={id:n.id,property_address:O.trim(),city:G.trim()||null,state:H.trim()||null,zip:Z.trim()||null,event_date:ce,start_time:te||null,end_time:le||null,auto_forward_to_card:d,disclosure_pdf_url:h||null,enable_survey:p,ask_visitor_intent:y,ask_visitor_address:g,photo_url:j||null,drip_campaign_id:Vt};c&&(As.hero_video_url=me||null,As.price=Ae.trim()?Number(Ae):null,As.beds=ze.trim()?parseInt(ze,10):null,As.baths=Ze.trim()?Number(Ze):null,As.sqft=Fe.trim()?parseInt(Fe,10):null,As.enable_question=Ye,As.enable_showing=qe,As.enable_disclosures=Ue,As.enable_offer=nt,As.brand_color_override=Ge.trim()||null,As.property_description=xt.trim()||null),(O.trim()!==(n.property_address??"")||(G.trim()||null)!==(n.city??null)||(H.trim()||null)!==(n.state??null)||(Z.trim()||null)!==(n.zip??null))&&(As.latitude=null,As.longitude=null,As.geocode_status="pending",As.geocoded_at=null),await r.mutateAsync(As),ia({title:"Settings saved!"}),t(!1)}catch{ia({title:"Failed to save",variant:"destructive"})}finally{D(!1)}};return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"sm:max-w-md max-h-[85vh] overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:c?"Virtual Open House Settings":"Guest Book Settings"}),e.jsx(_r,{className:"truncate",children:n.property_address})]}),e.jsxs("div",{className:"space-y-6 pt-2",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(J,{className:"text-sm font-medium",children:"Date & Time"}),e.jsx("p",{className:"text-xs text-muted-foreground -mt-1",children:"Change when this open house takes place. Updates the sign-in page right away."}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(J,{className:"text-xs text-muted-foreground",children:"Date"}),e.jsx(xe,{type:"date",value:ce,onChange:As=>ie(As.target.value),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs text-muted-foreground",children:"Start"}),e.jsx(xe,{type:"time",value:te,onChange:As=>ae(As.target.value),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs text-muted-foreground",children:"End"}),e.jsx(xe,{type:"time",value:le,onChange:As=>be(As.target.value),className:"mt-1"})]})]}),e.jsx(J,{className:"text-sm font-medium",children:"Property Address"}),e.jsx(xe,{value:O,onChange:As=>V(As.target.value),placeholder:"412 Oak St"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(J,{className:"text-xs text-muted-foreground",children:"City"}),e.jsx(xe,{value:G,onChange:As=>$(As.target.value),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs text-muted-foreground",children:"State"}),e.jsx(xe,{value:H,onChange:As=>Y(As.target.value),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs text-muted-foreground",children:"ZIP"}),e.jsx(xe,{value:Z,onChange:As=>ne(As.target.value),className:"mt-1"})]})]})]}),c&&e.jsxs(e.Fragment,{children:[n.tour_mode==="single_video"?e.jsxs("div",{className:"space-y-2",children:[e.jsxs(J,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Kr,{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:fs,className:"hidden"}),me?e.jsxs("div",{className:"relative rounded-lg overflow-hidden border border-border bg-black",children:[e.jsx("video",{src:me,controls:!0,className:"w-full max-h-48"}),e.jsxs("div",{className:"absolute top-2 right-2 flex gap-2",children:[e.jsx(B,{variant:"secondary",size:"sm",className:"h-8",onClick:()=>{var As;return(As=o.current)==null?void 0:As.click()},disabled:pe,children:pe?e.jsx(Ct,{className:"h-3.5 w-3.5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Oa,{className:"h-3.5 w-3.5 mr-1"}),"Replace"]})}),e.jsx(B,{variant:"secondary",size:"icon",className:"h-8 w-8",onClick:()=>he(""),children:e.jsx(Qn,{className:"h-4 w-4"})})]})]}):e.jsx("button",{type:"button",onClick:()=>{var As;return(As=o.current)==null?void 0:As.click()},disabled:pe,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:pe?e.jsx(Ct,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Kr,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"Upload tour video (max 200MB)"})]})})]}):e.jsx(Uir,{openHouseId:n.id}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{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(J,{className:"text-xs text-muted-foreground",children:"Price (USD)"}),e.jsx(xe,{type:"number",value:Ae,onChange:As=>Pe(As.target.value),placeholder:"650000",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs text-muted-foreground",children:"Sq Ft"}),e.jsx(xe,{type:"number",value:Fe,onChange:As=>Ne(As.target.value),placeholder:"2200",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs text-muted-foreground",children:"Beds"}),e.jsx(xe,{type:"number",value:ze,onChange:As=>ke(As.target.value),placeholder:"3",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs text-muted-foreground",children:"Baths"}),e.jsx(xe,{type:"number",step:"0.5",value:Ze,onChange:As=>Se(As.target.value),placeholder:"2.5",className:"mt-1"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{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(Ms,{value:xt,onChange:As=>qt(As.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(J,{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(fn,{checked:Ye,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(fn,{checked:qe,onCheckedChange:Qe})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"Request seller disclosures"}),e.jsx(fn,{checked:Ue,onCheckedChange:Xe})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"Make an offer / express interest"}),e.jsx(fn,{checked:nt,onCheckedChange:$e})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{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:Ge||"#0f172a",onChange:As=>ct(As.target.value),className:"h-10 w-14 rounded-md border border-input cursor-pointer bg-transparent"}),e.jsx(xe,{value:Ge,onChange:As=>ct(As.target.value),placeholder:"#0f172a",className:"flex-1 font-mono text-sm"}),Ge&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>ct(""),children:"Reset"})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5 pt-1",children:["#0f172a","#406E71","#2a4c64","#7c2d12","#1e3a8a","#581c87","#9f1239","#065f46"].map(As=>e.jsx("button",{type:"button",onClick:()=>ct(As),className:"w-6 h-6 rounded-full border border-border hover:scale-110 transition-transform",style:{backgroundColor:As},"aria-label":As},As))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{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:Ft,className:"hidden"}),j?e.jsxs("div",{className:"relative rounded-lg overflow-hidden border border-border",children:[e.jsx("img",{src:j,alt:"Property",className:"w-full h-40 object-cover"}),e.jsxs("div",{className:"absolute top-2 right-2 flex gap-2",children:[e.jsxs(B,{variant:"secondary",size:"sm",className:"h-8",onClick:()=>{var As;return(As=l.current)==null?void 0:As.click()},disabled:P,children:[P?e.jsx(Ct,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Oa,{className:"h-3.5 w-3.5 mr-1"}),P?"":"Replace"]}),e.jsx(B,{variant:"secondary",size:"icon",className:"h-8 w-8",onClick:wt,children:e.jsx(Qn,{className:"h-4 w-4"})})]})]}):e.jsx("button",{type:"button",onClick:()=>{var As;return(As=l.current)==null?void 0:As.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(Ct,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(hc,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"Upload property photo (max 10MB)"})]})})]}),e.jsx(zir,{value:Vt,onChange:Xt}),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(J,{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(fn,{checked:d,onCheckedChange:u})]})}),!d&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{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:Ts,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(Fr,{className:"h-5 w-5 text-primary shrink-0"}),e.jsx("span",{className:"text-sm truncate flex-1",children:"Disclosure PDF uploaded"}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0",onClick:vt,children:e.jsx(Qn,{className:"h-4 w-4"})})]}):e.jsx("button",{type:"button",onClick:()=>{var As;return(As=i.current)==null?void 0:As.click()},disabled:C,className:"w-full h-24 rounded-xl border-2 border-dashed border-muted-foreground/25 hover:border-muted-foreground/50 flex flex-col items-center justify-center gap-2 text-muted-foreground hover:text-foreground transition-colors",children:C?e.jsx(Ct,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Oa,{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(J,{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(fn,{checked:y,onCheckedChange:v})]})}),e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(J,{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(fn,{checked:g,onCheckedChange:b})]})}),e.jsx(Bir,{openHouseId:n.id,enableSurvey:p,onToggleSurvey:f}),e.jsx(B,{onClick:$s,disabled:I,className:"w-full",children:I?"Saving...":"Save Settings"})]})]})})}const uas={5:"Excellent",4:"Good",3:"Neutral",2:"Bad",1:"Very Bad"};function Vir({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:uas[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 Hir({openHouseId:s}){const{data:t,isLoading:n}=OMs(s),{data:r}=IFt(s),a=_.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(ve,{children:[e.jsx(bt,{className:"pb-3",children:e.jsxs(St,{className:"text-base flex items-center gap-2",children:[e.jsx(qf,{className:"h-4 w-4"}),"Survey Results"]})}),e.jsx(Me,{children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"No survey responses yet."})})]}):e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-3",children:e.jsxs(St,{className:"text-base flex items-center gap-2",children:[e.jsx(qf,{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(Me,{children:e.jsxs(Yr,{defaultValue:"summary",children:[e.jsxs(Zr,{className:"mb-4",children:[e.jsxs(Ht,{value:"summary",className:"text-xs gap-1",children:[e.jsx(bl,{className:"h-3.5 w-3.5"})," Summary"]}),e.jsxs(Ht,{value:"individual",className:"text-xs gap-1",children:[e.jsx(Fo,{className:"h-3.5 w-3.5"})," Per Visitor"]})]}),e.jsxs(Gt,{value:"summary",className:"space-y-6",children:[o.map(h=>e.jsx(Vir,{question:h,responses:l},h.id)),c.map(h=>{const m=l.filter(p=>p.question_id===h.id&&p.text_value);return m.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsx("span",{className:"text-sm font-medium",children:h.question_text}),e.jsx("div",{className:"space-y-1.5 max-h-40 overflow-y-auto",children:m.map(p=>{const f=a[p.visitor_id];return e.jsxs("div",{className:"text-sm p-2 bg-muted/30 rounded-lg",children:[e.jsxs("span",{className:"text-muted-foreground text-xs",children:[f?`${f.first_name} ${f.last_name||""}`.trim():"Visitor",":"]}),e.jsx("p",{className:"mt-0.5",children:p.text_value})]},p.id)})})]},h.id)})]}),e.jsx(Gt,{value:"individual",className:"space-y-4",children:d.map(h=>{const m=a[h],p=l.filter(f=>f.visitor_id===h);return e.jsxs("div",{className:"p-3 rounded-lg border border-border space-y-2",children:[e.jsxs("p",{className:"text-sm font-medium",children:[m?`${m.first_name} ${m.last_name||""}`.trim():"Unknown Visitor",(m==null?void 0:m.email)&&e.jsx("span",{className:"text-xs text-muted-foreground ml-2",children:m.email})]}),e.jsx("div",{className:"space-y-1",children:p.map(f=>{const y=i.find(v=>v.id===f.question_id);return y?e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:y.question_text}),e.jsx("span",{className:"font-medium",children:f.rating_value!=null?uas[f.rating_value]||f.rating_value:f.text_value})]},f.id):null})})]},h)})})]})})]})}const Gir={question:{label:"Question",icon:Hi,color:"text-sky-700 dark:text-sky-300",bg:"bg-sky-100 dark:bg-sky-950"},showing:{label:"Showing",icon:ga,color:"text-orange-700 dark:text-orange-300",bg:"bg-orange-100 dark:bg-orange-950"},disclosure:{label:"Disclosures",icon:Fr,color:"text-indigo-700 dark:text-indigo-300",bg:"bg-indigo-100 dark:bg-indigo-950"},offer:{label:"Hot Lead",icon:yd,color:"text-emerald-700 dark:text-emerald-300",bg:"bg-emerald-100 dark:bg-emerald-950"}},sCt={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 Wir({openHouseId:s}){const{data:t=[],isLoading:n}=tPs(s),r=sPs(),[a,i]=_.useState(null),[l,o]=_.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(XO,{className:"h-4 w-4"}),"Virtual Open House Leads",e.jsx(Oe,{variant:"secondary",className:"ml-1",children:d.all}),d.new>0&&e.jsxs(Oe,{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=Gir[h.action_type],p=m.icon,f=h.payload||{},y=a===h.id,v=h.status==="contacted",g=h.status==="archived";return e.jsxs("li",{className:`transition-colors ${g?"opacity-60":""} ${h.status==="new"?"bg-emerald-50/40 dark:bg-emerald-950/10":""}`,children:[e.jsxs("button",{onClick:()=>i(y?null:h.id),className:"w-full text-left px-4 py-3 flex items-start gap-3 hover:bg-muted/40 transition-colors",children:[e.jsx("div",{className:`w-9 h-9 rounded-lg flex items-center justify-center shrink-0 ${m.bg}`,children:e.jsx(p,{className:`h-4 w-4 ${m.color}`})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-semibold text-sm truncate",children:f.visitor_name||"Visitor"}),e.jsx(Oe,{variant:"outline",className:`text-[10px] ${m.color}`,children:m.label}),h.status==="new"&&e.jsx("span",{className:"text-[10px] font-bold text-emerald-600 uppercase tracking-wide",children:"New"}),v&&e.jsxs("span",{className:"text-[10px] font-bold text-muted-foreground uppercase tracking-wide flex items-center gap-1",children:[e.jsx(Er,{className:"h-3 w-3"}),"Contacted"]})]}),f.message&&e.jsxs("p",{className:"text-sm text-muted-foreground line-clamp-1 mt-0.5 italic",children:['"',f.message,'"']}),e.jsxs("div",{className:"flex items-center gap-3 text-[11px] text-muted-foreground mt-1",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Gr,{className:"h-3 w-3"}),Hs(new Date(h.created_at),"MMM d, h:mm a")]}),f.email&&e.jsxs("span",{className:"flex items-center gap-1 truncate",children:[e.jsx(ln,{className:"h-3 w-3"}),f.email]}),f.phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(_a,{className:"h-3 w-3"}),f.phone]})]})]}),y?e.jsx(tl,{className:"h-4 w-4 mt-1 text-muted-foreground"}):e.jsx(xi,{className:"h-4 w-4 mt-1 text-muted-foreground"})]}),y&&e.jsxs("div",{className:"px-4 pb-4 pl-16 space-y-3",children:[f.message&&e.jsxs("div",{className:"bg-muted/40 rounded-md p-3 text-sm border-l-2 border-foreground/30",children:['"',f.message,'"']}),Object.keys(sCt).some(b=>f[b]!=null&&f[b]!==""&&!(Array.isArray(f[b])&&f[b].length===0))&&e.jsx("div",{className:"grid grid-cols-2 gap-x-4 gap-y-1.5 text-sm",children:Object.entries(sCt).map(([b,j])=>{const S=f[b];return S==null||S===""||Array.isArray(S)&&S.length===0?null:e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] text-muted-foreground uppercase tracking-wide",children:j}),e.jsx("div",{className:"font-medium",children:Array.isArray(S)?S.join(", "):String(S)})]},b)})}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 pt-1",children:[f.email&&e.jsx("a",{href:`mailto:${f.email}?subject=${encodeURIComponent("Re: your open house inquiry")}`,children:e.jsxs(B,{size:"sm",variant:"default",className:"gap-1.5",children:[e.jsx(ln,{className:"h-3.5 w-3.5"}),"Reply"]})}),f.phone&&e.jsx("a",{href:`tel:${String(f.phone).replace(/[^0-9+]/g,"")}`,children:e.jsxs(B,{size:"sm",variant:"outline",className:"gap-1.5",children:[e.jsx(_a,{className:"h-3.5 w-3.5"}),"Call"]})}),!v&&e.jsxs(B,{size:"sm",variant:"outline",className:"gap-1.5",onClick:()=>u(h.id,"contacted"),children:[e.jsx(Er,{className:"h-3.5 w-3.5"}),"Mark contacted"]}),g?e.jsx(B,{size:"sm",variant:"ghost",className:"gap-1.5 text-muted-foreground",onClick:()=>u(h.id,"new"),children:"Restore"}):e.jsxs(B,{size:"sm",variant:"ghost",className:"gap-1.5 text-muted-foreground",onClick:()=>u(h.id,"archived"),children:[e.jsx(by,{className:"h-3.5 w-3.5"}),"Archive"]})]})]})]},h.id)})})]})}const nCt=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}`},Kir=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"})},rCt=25;function Yir({open:s,onOpenChange:t,openHouse:n,variant:r="tour"}){var Qe;const a=r==="rsvp",{isGmailConnected:i,gmailEmail:l}=Vg(),{data:o}=iae(),c=!!(o!=null&&o.hasVerifiedSes),d=ha(),{data:u=[]}=Z_(),[h,m]=_.useState([]),[p,f]=_.useState(!1),[y,v]=_.useState("all"),[g,b]=_.useState([]),[j,S]=_.useState([]),[C,E]=_.useState(""),[P,M]=_.useState([]),[I,D]=_.useState(""),[O,V]=_.useState(""),[G,$]=_.useState(""),[H,Y]=_.useState("platform"),[Z,ne]=_.useState(!1),[ce,ie]=_.useState(0),[te,ae]=_.useState(!1),le=a?`https://guestbook.relevelup.com/rsvp/${n.slug}`:`https://guestbook.relevelup.com/${n.slug}`,be=Kir(n.event_date),me=n.start_time?`${nCt(n.start_time)}${n.end_time?` – ${nCt(n.end_time)}`:""}`:"",he=[be,me].filter(Boolean).join(" · ");_.useEffect(()=>{s&&(V(a?`You're invited: Open House at ${n.property_address}`:`Take a virtual tour of ${n.property_address}`),$(a?`I'm hosting an open house at ${n.property_address}${be?` on ${be}`:""}${me?` from ${me}`:""}. I'd love for you to stop by — tap below to RSVP so I can save you a spot.`:`I wanted to share an immersive virtual tour of ${n.property_address} with you. Step inside from anywhere — explore every room at your own pace.`),S([]),b([]),M([]),E(""),v("all"),ie(0),Y(c?"ses":i?"gmail":"platform"),h.length===0&&pe())},[s,n.id,i,c]);const pe=async()=>{if(d){f(!0);try{const Ue=[];let nt=0;for(;;){const{data:$e,error:Ge}=await q.from("innercircle_contacts").select("id, first_name, last_name, email, tags:innercircle_contact_tags(relationship_type_id)").eq("owner_user_id",d).eq("email_opt_out",!1).not("email","is",null).neq("email","").order("first_name",{ascending:!0}).order("id",{ascending:!0}).range(nt,nt+1e3-1);if(Ge)throw Ge;const ct=$e||[];if(Ue.push(...ct),ct.length<1e3)break;nt+=1e3}m(Ue.map($e=>({id:$e.id,first_name:$e.first_name,last_name:$e.last_name,email:$e.email,tagIds:($e.tags||[]).map(Ge=>Ge.relationship_type_id)})))}catch{se.error("Failed to load contacts")}finally{f(!1)}}},Ce=Ue=>`${Ue.first_name} ${Ue.last_name||""}`.trim(),Ae=_.useMemo(()=>{const Ue=I.trim().toLowerCase();return Ue?h.filter(Xe=>`${Ce(Xe)} ${Xe.email||""}`.toLowerCase().includes(Ue)):h},[h,I]),Pe=_.useMemo(()=>{const Ue={};return h.forEach(Xe=>Xe.tagIds.forEach(nt=>{Ue[nt]=(Ue[nt]||0)+1})),Ue},[h]),ze=_.useMemo(()=>y==="all"?h:y==="tags"?g.length===0?[]:h.filter(Ue=>Ue.tagIds.some(Xe=>g.includes(Xe))):h.filter(Ue=>j.includes(Ue.id)),[y,h,g,j]),ke=_.useMemo(()=>{const Ue=new Set,Xe=[];return[...ze.map(nt=>({email:nt.email,name:Ce(nt)})),...P].forEach(nt=>{const $e=nt.email.toLowerCase();!nt.email||Ue.has($e)||(Ue.add($e),Xe.push(nt))}),Xe},[ze,P]),Ze=()=>{const Ue=C.trim();if(Ue){if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(Ue)){se.error("Invalid email");return}M(Xe=>[...Xe,{email:Ue,name:Ue.split("@")[0]}]),E("")}},Se=Ue=>Ue.replace(/&/g,"&").replace(//g,">"),Fe=n.photo_url&&n.photo_url.includes("/storage/v1/object/public/")?n.photo_url.replace("/object/public/","/render/image/public/")+"?width=1200&height=630&resize=cover":n.photo_url||"",Ne=Ue=>{const Xe=Ue?`Hi ${Se(Ue)},`:"Hi there,",nt=[n.city,n.state].filter(Boolean).join(", "),$e=Se(G).split(/\n\n+/).map(Ge=>`

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

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

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

${Se(n.property_address)}

${nt?`

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

`:""}
 

When

${Se(he)}

${Xe}

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

Or copy this link:
${le}

`},Ye=_.useMemo(()=>Ne("Alex"),[G,n.id,Fe,a,he]),Ve=async()=>{var Ue;if(ke.length===0){se.error("Add at least one recipient");return}ne(!0),ie(0);try{if(H==="gmail"&&i){let Xe=0;for(const nt of ke){const{data:$e,error:Ge}=await q.functions.invoke("gmail-send",{body:{to:nt.email,subject:O,body:Ne((Ue=nt.name)==null?void 0:Ue.split(" ")[0])}});!Ge&&($e!=null&&$e.success)&&(Xe+=1),ie(Xe)}if(Xe===0)throw new Error("Gmail send failed");se.success(`Sent to ${Xe} of ${ke.length} via Gmail`)}else{let Xe=0;for(let nt=0;nt{await navigator.clipboard.writeText(le),ae(!0),setTimeout(()=>ae(!1),1500)};return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"sm:max-w-[900px] w-[calc(100vw-2rem)] max-h-[92vh] overflow-y-auto overflow-x-hidden",children:[e.jsxs(Os,{className:"min-w-0",children:[e.jsxs(Ds,{className:"flex items-center gap-2",children:[e.jsx(ln,{className:"h-5 w-5 text-primary"}),a?"Invite to Open House":"Email Virtual Tour"]}),e.jsx(_r,{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(Vc,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("code",{className:"flex-1 min-w-0 text-xs truncate",children:le}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:qe,className:"shrink-0 h-7 gap-1",children:[te?e.jsx(ea,{className:"h-3.5 w-3.5 text-emerald-600"}):e.jsx(Ia,{className:"h-3.5 w-3.5"}),te?"Copied":"Copy"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(J,{className:"flex items-center gap-1.5",children:[e.jsx(ln,{className:"h-3.5 w-3.5"}),"Send from"]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[c&&e.jsx(B,{type:"button",variant:H==="ses"?"default":"outline",size:"sm",onClick:()=>Y("ses"),className:"gap-1.5",children:"Mass Email (your address)"}),i&&e.jsx(B,{type:"button",variant:H==="gmail"?"default":"outline",size:"sm",onClick:()=>Y("gmail"),className:"gap-1.5",children:"Gmail"}),e.jsx(B,{type:"button",variant:H==="platform"?"default":"outline",size:"sm",onClick:()=>Y("platform"),className:"gap-1.5",children:"LevelUp"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:H==="ses"&&((Qe=o==null?void 0:o.verifiedEmails)!=null&&Qe[0])?e.jsxs(e.Fragment,{children:["Sending as ",e.jsx("span",{className:"font-medium",children:o.verifiedEmails[0]})," via your Mass Email setup"]}):H==="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(J,{className:"flex items-center gap-1.5",children:[e.jsx(In,{className:"h-3.5 w-3.5"}),"Who should receive this?"]}),e.jsxs(Yr,{value:y,onValueChange:Ue=>v(Ue),children:[e.jsxs(Zr,{className:"grid w-full grid-cols-3",children:[e.jsx(Ht,{value:"all",children:"All contacts"}),e.jsx(Ht,{value:"tags",children:"By tag"}),e.jsx(Ht,{value:"select",children:"Pick people"})]}),e.jsx(Gt,{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(Gt,{value:"tags",className:"pt-3",children:e.jsx(Ji,{className:"h-[210px] rounded-lg border p-2",children:e.jsxs("div",{className:"space-y-1",children:[u.map(Ue=>{const Xe=g.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($a,{checked:Xe,onCheckedChange:()=>b(nt=>Xe?nt.filter($e=>$e!==Ue.id):[...nt,Ue.id])}),e.jsxs("span",{className:"flex items-center gap-1.5 text-sm flex-1 min-w-0 truncate",children:[e.jsx(Ep,{className:"h-3 w-3 text-muted-foreground shrink-0"}),Ue.name]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Pe[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(Gt,{value:"select",className:"pt-3 space-y-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Lr,{className:"absolute left-2.5 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(xe,{value:I,onChange:Ue=>D(Ue.target.value),placeholder:"Search contacts...",className:"pl-8 h-9"})]}),e.jsx(Ji,{className:"h-[210px] rounded-lg border p-2",children:e.jsxs("div",{className:"space-y-1",children:[Ae.slice(0,300).map(Ue=>{const Xe=j.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($a,{checked:Xe,onCheckedChange:()=>S(nt=>Xe?nt.filter($e=>$e!==Ue.id):[...nt,Ue.id])}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-sm font-medium truncate",children:Ce(Ue)||"(no name)"}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:Ue.email})]})]},Ue.id)}),Ae.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground p-2",children:p?"Loading…":"No contacts found."})]})})]})]}),e.jsxs("div",{className:"flex gap-2 pt-1",children:[e.jsx(xe,{value:C,onChange:Ue=>E(Ue.target.value),placeholder:"Also send to an email...",type:"email",onKeyDown:Ue=>{Ue.key==="Enter"&&(Ue.preventDefault(),Ze())}}),e.jsx(B,{type:"button",variant:"outline",size:"sm",onClick:Ze,children:"Add"})]}),P.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:P.map(Ue=>e.jsxs(Oe,{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(Xe=>Xe.filter(nt=>nt.email!==Ue.email)),className:"hover:bg-muted-foreground/20 rounded p-0.5",children:e.jsx(Qn,{className:"h-3 w-3"})})]},Ue.email))})]}),e.jsx(wc,{}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{htmlFor:"vt-subject",children:"Subject"}),e.jsx(xe,{id:"vt-subject",value:O,onChange:Ue=>V(Ue.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{htmlFor:"vt-message",children:"Message"}),e.jsx(Ms,{id:"vt-message",value:G,onChange:Ue=>$(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(J,{className:"flex items-center gap-1.5",children:[e.jsx(ya,{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:`${Ye}`,className:"w-full h-[420px] lg:h-[560px] border-0 bg-white",sandbox:""})})]})]}),e.jsxs("div",{className:At("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",Z&&ce>0&&e.jsxs("span",{children:[" · sent ",ce]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),disabled:Z,children:"Cancel"}),e.jsxs(B,{onClick:Ve,disabled:Z||ke.length===0||!O.trim(),className:"gap-2",children:[Z?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Or,{className:"h-4 w-4"}),Z?"Sending...":`Send${ke.length?` to ${ke.length}`:""}`]})]})]})]})})}function Zir({openHouseId:s}){const{data:t=[],isLoading:n}=yPs(s),r=bPs(s),a=_Ps(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(bv,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm font-semibold",children:"RSVPs"}),e.jsx(Oe,{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(Oe,{className:"text-[10px] gap-1",children:[e.jsx(ea,{className:"h-3 w-3"}),"Checked in"]}),l.has_agent&&e.jsxs(Oe,{variant:"outline",className:"text-[10px] gap-1",children:[e.jsx(gj,{className:"h-3 w-3"}),l.working_with_agent_name||"Has an agent"]})]}),e.jsxs("div",{className:"flex items-center gap-3 mt-0.5 text-xs text-muted-foreground flex-wrap",children:[l.email&&e.jsxs("span",{className:"flex items-center gap-1 truncate",children:[e.jsx(ln,{className:"h-3 w-3"}),l.email]}),l.phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(_a,{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(B,{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(B,{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(Sn,{className:"h-4 w-4"})})]},l.id))})]})}function Xir({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(rn,{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(Hf,{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(Lr,{className:"pointer-events-none absolute left-3.5 top-1/2 h-4 w-4 -translate-y-1/2 opacity-70"}),e.jsx(xe,{value:n,onChange:i=>r(i.target.value),placeholder:"Search by address, event name, or city...",className:"h-11 rounded-xl border-transparent bg-white/10 pl-10 text-current placeholder:text-current/50 focus-visible:ring-2 focus-visible:ring-white/30"})]}),e.jsx("div",{className:"-mx-1 flex gap-2 overflow-x-auto px-1 pb-1 scrollbar-hide",children:t.map(i=>e.jsxs("button",{type:"button",onClick:i.onClick,disabled:!i.onClick,className:At("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 aCt={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 Qir({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(In,{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(B,{variant:"outline",size:"sm",className:"mt-4 gap-1.5",onClick:n,children:[e.jsx(bd,{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(gu,{className:"h-3 w-3"}),r," hot"]})]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:t,className:"h-7 gap-1 text-xs",children:[e.jsx(li,{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=aCt[a.visitor_intent||""]||aCt.browsing;return e.jsxs("tr",{className:At("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:At("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:At("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 QCe="guestbook.relevelup.com";function Jir(){const{data:s,isLoading:t}=PMs(),n=LMs(),r=DFt(),a=IMs(),[i,l]=_.useState(!1),[o,c]=_.useState(null),[d,u]=_.useState(""),[h,m]=_.useState("all"),[p,f]=_.useState(!1),{user:y}=hs(),v=ha(),[g,b]=_.useState(null),[j,S]=_.useState(null),[C,E]=_.useState(!1),P=_.useRef(null),[M,I]=_.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=te=>{var le;const ae=(le=te.target.files)==null?void 0:le[0];if(ae){if(ae.size>5*1024*1024){ia({title:"Photo must be under 5MB",variant:"destructive"});return}b(ae),S(URL.createObjectURL(ae))}},O=()=>{b(null),S(null),P.current&&(P.current.value="")},V=async()=>{if(!M.property_address){ia({title:M.event_type==="community"?"Event name is required":"Address is required",variant:"destructive"});return}let te;if(g&&y){E(!0);const le=g.name.split(".").pop(),be=`${v}/${Date.now()}.${le}`,{error:me}=await q.storage.from("open-house-photos").upload(be,g,{upsert:!0});if(me){ia({title:"Photo upload failed",description:me.message,variant:"destructive"}),E(!1);return}const{data:he}=q.storage.from("open-house-photos").getPublicUrl(be);te=he.publicUrl,E(!1)}const ae=M.kind==="virtual"?{...M,start_time:void 0,end_time:void 0,photo_url:te}:{...M,photo_url:te};await n.mutateAsync(ae),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"}),O()},G=te=>{navigator.clipboard.writeText(`https://${QCe}/${te}`),ia({title:"Link copied!"})},$=Hs(new Date,"yyyy-MM-dd"),H=_.useMemo(()=>{const te=s??[],ae=d.trim().toLowerCase(),le=ke=>!ae||[ke.property_address,ke.city,ke.state].filter(Boolean).join(" ").toLowerCase().includes(ae),be=te.filter(le),me=be.filter(ke=>ke.kind==="virtual"),he=be.filter(ke=>ke.kind!=="virtual"),pe=he.filter(ke=>ke.event_date===$),Ce=he.filter(ke=>ke.event_date>$).sort((ke,Ze)=>ke.event_date.localeCompare(Ze.event_date)),Ae=he.filter(ke=>ke.event_date<$).sort((ke,Ze)=>Ze.event_date.localeCompare(ke.event_date)),Pe=te.reduce((ke,Ze)=>ke+(Ze.visitor_count||0),0),ze=te.reduce((ke,Ze)=>ke+(Ze.qr_scan_count||0),0);return{today:pe,upcoming:Ce,past:Ae,virtual:me,totalSignIns:Pe,totalScans:ze}},[s,d,$]),Y=H.today.length+H.upcoming.length,Z=Y>0?`${Y} upcoming · ${H.totalSignIns.toLocaleString()} total sign-ins`:`${H.totalSignIns.toLocaleString()} total sign-ins collected`,ne=te=>h==="all"||h===te,ce=te=>m(ae=>ae===te?"all":te),ie=te=>e.jsx(eor,{openHouse:te,isExpanded:o===te.id,onToggle:()=>c(o===te.id?null:te.id),onCopyLink:()=>G(te.slug||""),onToggleActive:()=>r.mutate({id:te.id,is_active:!te.is_active}),onDelete:()=>a.mutate(te.id),isToday:te.kind!=="virtual"&&te.event_date===$},te.id);return e.jsxs(zs,{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(Xir,{summary:Z,search:d,onSearchChange:u,onCreate:()=>l(!0),stats:[{key:"today",label:"Live Today",value:H.today.length,onClick:()=>ce("today"),active:h==="today"},{key:"upcoming",label:"Upcoming",value:H.upcoming.length,onClick:()=>ce("upcoming"),active:h==="upcoming"},{key:"virtual",label:"Virtual Tours",value:H.virtual.length,onClick:()=>ce("virtual"),active:h==="virtual"},{key:"signins",label:"Total Sign-Ins",value:H.totalSignIns.toLocaleString()},{key:"scans",label:"Total QR Scans",value:H.totalScans.toLocaleString()}]}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(Ls,{open:i,onOpenChange:l,children:[e.jsx(nl,{asChild:!0,children:e.jsx("span",{className:"sr-only",children:"Open create dialog"})}),e.jsxs(Ps,{className:"sm:max-w-lg max-h-[90vh] flex flex-col",children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Create Open House"}),e.jsx(_r,{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(J,{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(te=>({...te,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(te=>({...te,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(te=>({...te,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(te=>({...te,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(J,{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(te=>({...te,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(te=>({...te,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(J,{children:M.event_type==="community"?"Event Name *":"Property Address *"}),e.jsx(xe,{value:M.property_address,onChange:te=>I(ae=>({...ae,property_address:te.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(J,{children:"City"}),e.jsx(xe,{value:M.city,onChange:te=>I(ae=>({...ae,city:te.target.value})),placeholder:"Austin"})]}),e.jsxs("div",{children:[e.jsx(J,{children:"State"}),e.jsx(xe,{value:M.state,onChange:te=>I(ae=>({...ae,state:te.target.value})),placeholder:"TX",maxLength:2})]}),e.jsxs("div",{children:[e.jsx(J,{children:"ZIP"}),e.jsx(xe,{value:M.zip,onChange:te=>I(ae=>({...ae,zip:te.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(J,{children:"Date"}),e.jsx(xe,{type:"date",value:M.event_date,onChange:te=>I(ae=>({...ae,event_date:te.target.value}))})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Start Time"}),e.jsx(xe,{type:"time",value:M.start_time,onChange:te=>I(ae=>({...ae,start_time:te.target.value}))})]}),e.jsxs("div",{children:[e.jsx(J,{children:"End Time"}),e.jsx(xe,{type:"time",value:M.end_time,onChange:te=>I(ae=>({...ae,end_time:te.target.value}))})]})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Welcome Message"}),e.jsx(Ms,{value:M.agent_greeting,onChange:te=>I(ae=>({...ae,agent_greeting:te.target.value})),placeholder:"Welcome! Please sign in below."})]}),e.jsxs("div",{children:[e.jsx(J,{children:M.event_type==="community"?"Event Photo":"Property Photo"}),e.jsx("input",{ref:P,type:"file",accept:"image/*",onChange:D,className:"hidden"}),j?e.jsxs("div",{className:"relative mt-1 rounded-xl overflow-hidden border border-border",children:[e.jsx("img",{src:j,alt:"Property preview",className:"w-full h-40 object-cover"}),e.jsx("button",{type:"button",onClick:O,className:"absolute top-2 right-2 bg-black/60 hover:bg-black/80 text-white rounded-full p-1 transition-colors",children:e.jsx(Qn,{className:"h-4 w-4"})})]}):e.jsxs("button",{type:"button",onClick:()=>{var te;return(te=P.current)==null?void 0:te.click()},className:"mt-1 w-full h-32 rounded-xl border-2 border-dashed border-muted-foreground/25 hover:border-muted-foreground/50 flex flex-col items-center justify-center gap-2 text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(jy,{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(B,{onClick:V,disabled:n.isPending||C,className:"w-full",children:C?"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(te=>e.jsx(ve,{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"})]})},te))}):s!=null&&s.length?e.jsxs("div",{className:"space-y-8",children:[H.today.length>0&&ne("today")&&e.jsxs("section",{className:"space-y-3",children:[e.jsx(OBe,{title:"Happening Today",count:H.today.length,accent:!0}),e.jsx("div",{className:"space-y-4",children:H.today.map(ie)})]}),H.upcoming.length>0&&ne("upcoming")&&e.jsxs("section",{className:"space-y-3",children:[e.jsx(OBe,{title:"Upcoming",count:H.upcoming.length}),e.jsx("div",{className:"space-y-4",children:H.upcoming.map(ie)})]}),H.virtual.length>0&&ne("virtual")&&e.jsxs("section",{className:"space-y-3",children:[e.jsx(OBe,{title:"Virtual Tours",count:H.virtual.length}),e.jsx("div",{className:"space-y-4",children:H.virtual.map(ie)})]}),H.past.length>0&&h==="all"&&e.jsxs("section",{className:"space-y-3",children:[e.jsxs("button",{onClick:()=>f(te=>!te),className:"flex w-full items-center justify-between rounded-xl border border-border bg-card px-4 py-3 text-left transition-colors hover:bg-muted/40",children:[e.jsxs("span",{className:"flex items-center gap-2 text-sm font-semibold text-foreground",children:[e.jsx(R_,{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:H.past.length})]}),p?e.jsx(_v,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(tl,{className:"h-4 w-4 text-muted-foreground"})]}),p&&e.jsx("div",{className:"space-y-4",children:H.past.map(ie)})]}),Y===0&&H.virtual.length===0&&H.past.length===0&&e.jsx(ve,{className:"border-dashed",children:e.jsxs(Me,{className:"py-12 text-center text-sm text-muted-foreground",children:["No open houses match “",d,"”."]})})]}):e.jsx(ve,{className:"border-dashed",children:e.jsxs(Me,{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(Hf,{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(B,{onClick:()=>l(!0),children:[e.jsx(rn,{className:"h-4 w-4 mr-2"}),"Create Your First Open House"]})]})})]})]})}function OBe({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 eor({openHouse:s,isExpanded:t,onToggle:n,onCopyLink:r,onToggleActive:a,onDelete:i,isToday:l}){const{data:o}=IFt(t?s.id:void 0),{data:c}=at({queryKey:["agent-profile-flyer",s.agent_id],queryFn:async()=>{const{data:M,error:I}=await q.from("profiles").select("name, avatar_url, phone, title, brokerages:brokerage_id(name)").eq("id",s.agent_id).single();if(I)throw I;const D=M.brokerages;return{...M,brokerage_name:(D==null?void 0:D.name)||null}},enabled:!!s.agent_id}),[d,u]=_.useState(!1),[h,m]=_.useState(!1),[p,f]=_.useState(!1),[y,v]=_.useState(!1),g=_.useRef(null),b=`https://${QCe}/${s.slug}`,j=M=>{if(!M)return"";const[I,D]=M.split(":"),O=parseInt(I),V=O>=12?"PM":"AM";return`${O>12?O-12:O||12}:${D} ${V}`},S=()=>{if(!(o!=null&&o.length))return;const M=["First Name","Last Name","Email","Phone","Address","Intent","Wants Market Updates","Message","Signed In"],I=o.map($=>[$.first_name,$.last_name||"",$.email||"",$.phone||"",$.visitor_address||"",$.visitor_intent||"",$.wants_market_updates?"Yes":"No",($.message||"").replace(/"/g,'""'),Hs(new Date($.created_at),"MM/dd/yyyy h:mm a")]),D=[M,...I].map($=>$.map(H=>`"${H}"`).join(",")).join(` `),O=new Blob([D],{type:"text/csv"}),V=URL.createObjectURL(O),G=document.createElement("a");G.href=V,G.download=`${s.property_address.replace(/[^a-zA-Z0-9]/g,"-")}-visitors.csv`,G.click(),URL.revokeObjectURL(V)},C=_.useCallback(()=>{if(!g.current)return;const M=g.current.querySelector("svg");if(!M)return;const I=new XMLSerializer().serializeToString(M),D=document.createElement("canvas");D.width=1024,D.height=1024;const O=D.getContext("2d"),V=new Image;V.onload=()=>{O==null||O.drawImage(V,0,0,1024,1024);const G=document.createElement("a");G.download=`${s.property_address.replace(/[^a-zA-Z0-9]/g,"-")}-qr.png`,G.href=D.toDataURL("image/png"),G.click()},V.src="data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent(I)))},[s.property_address]),E=_.useCallback(()=>{var Fe;if(!g.current)return;const M=g.current.querySelector("svg");if(!M)return;const I=new XMLSerializer().serializeToString(M),D="data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent(I))),O=Hs(new Date(s.event_date+"T00:00:00"),"EEEE, MMMM d, yyyy"),V=s.start_time?`${j(s.start_time)}${s.end_time?" – "+j(s.end_time):""}`:"",G=[s.city,s.state].filter(Boolean).join(", "),$=s.agent_greeting||"Welcome! Please sign in below.",H=!!s.photo_url,Y=!!c,Z=H||Y,ne=H&&Y,ce=ne?"0.35in 0.75in 0.3in":"0.55in 0.75in 0.45in",ie=ne?"28px":"34px",te=ne?"0.2in 0.75in":Z?"0.3in 0.75in":"0.4in 0.75in",ae=Z?"0.15in":"0.3in",le=Z?"0.15in":"0.3in",be=ne?"14px 36px":"22px 44px",me=ne?"20px":"24px",he=Z?"0.2in":"0.35in",pe=ne?"1.8in":"2.4in",Ce=Z?"0.15in":"0.3in",Ae=ne?"140px":Z?"160px":"200px",Pe=ne?"16px":"24px",ze=ne?"10px 20px":"16px 28px",ke=ne?"44px":"56px",Ze="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}
${G?`
${G}${s.zip?" "+s.zip:""}
`:""}
Date
${O}
${V?`
Time
${V}
`:""}
${$}
${c?`
${c.avatar_url?`${c.name}`:`
${((Fe=c.name)==null?void 0:Fe.charAt(0))||"A"}
`}
Hosted By
${c.name}
${c.title?`
${c.title}
`:""} ${c.brokerage_name?`
${c.brokerage_name}
`:""} ${c.phone?`
${c.phone}
`:""}
`:""} ${s.photo_url?`Property`:""}
QR Code
Scan to Sign In
Point your phone camera at the QR code
`),Se.document.close(),setTimeout(()=>{Se.focus(),Se.print()},500))},[s,b,c]),P=async()=>{v(!0);try{const{error:M}=await q.functions.invoke("guestbook-email-link",{body:{openHouseId:s.id}});if(M)throw M;ia({title:"Email sent!",description:"Check your inbox for the guest book link."})}catch(M){ia({title:"Failed to send",description:M.message,variant:"destructive"})}finally{v(!1)}};return e.jsxs(ve,{className:At("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:At("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(St,{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(Oe,{className:"shrink-0 gap-1 border-none bg-emerald-500/15 text-[11px] text-emerald-700 dark:text-emerald-300",children:[e.jsx(Nv,{className:"h-3 w-3"}),"Today"]}),e.jsx(Oe,{variant:s.is_active?"default":"secondary",className:"shrink-0 text-[11px]",children:s.is_active?"Active":"Inactive"}),s.kind==="virtual"?e.jsxs(Oe,{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(ya,{className:"h-3 w-3"}),"Virtual"]}):e.jsxs(Oe,{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(Xa,{className:"h-3 w-3"}),"In-Person"]}),s.agent_name&&e.jsxs(Oe,{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(Fo,{className:"h-3 w-3"}),s.agent_name]}),s.event_type==="community"&&e.jsxs(Oe,{variant:"outline",className:"shrink-0 gap-1 text-[11px]",children:[e.jsx(ai,{className:"h-3 w-3"}),"Community"]})]})]}),e.jsx(B,{variant:"ghost",size:"icon",onClick:n,className:"shrink-0 -mr-2 -mt-1",children:t?e.jsx(_v,{className:"h-4 w-4"}):e.jsx(tl,{className:"h-4 w-4"})})]}),e.jsxs(kn,{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(Xa,{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(Gr,{className:"h-3 w-3"}),"Always on"]}):e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ga,{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(Gr,{className:"h-3 w-3"}),j(s.start_time),s.end_time?` – ${j(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(In,{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(Hf,{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(B,{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(Nv,{className:"h-3.5 w-3.5"}),"Live"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:r,className:"h-8 gap-1.5 text-xs",children:[e.jsx(Ia,{className:"h-3.5 w-3.5"}),"Copy Link"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>u(!0),className:"h-8 gap-1.5 text-xs",children:[e.jsx(Hf,{className:"h-3.5 w-3.5"}),"QR Code"]}),s.kind==="virtual"?e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>f(!0),className:"h-8 gap-1.5 text-xs text-primary border-primary/30 hover:bg-primary/10",children:[e.jsx(bd,{className:"h-3.5 w-3.5"}),"Email Tour"]}):e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>f(!0),className:"h-8 gap-1.5 text-xs text-primary border-primary/30 hover:bg-primary/10",children:[e.jsx(ln,{className:"h-3.5 w-3.5"}),"Invite"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>window.open(`${b}?kiosk=1`,"_blank"),className:"h-8 gap-1.5 text-xs",children:[e.jsx(o$,{className:"h-3.5 w-3.5"}),"Tablet Mode"]})]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>m(!0),className:"h-8 gap-1.5 text-xs",children:[e.jsx(qc,{className:"h-3.5 w-3.5"}),"Settings"]}),e.jsxs(tu,{children:[e.jsx(su,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0","aria-label":"More actions",children:e.jsx(ob,{className:"h-4 w-4"})})}),e.jsxs(Od,{align:"end",className:"w-52",children:[e.jsxs(ca,{onClick:()=>window.open(b,"_blank"),children:[e.jsx(wr,{className:"mr-2 h-4 w-4"}),"Preview sign-in page"]}),s.kind==="virtual"?e.jsxs(ca,{onClick:()=>window.open(`/guestbook/${s.slug}?preview=1`,"_blank"),children:[e.jsx(ya,{className:"mr-2 h-4 w-4"}),"Preview tour"]}):e.jsxs(ca,{onClick:()=>window.open(`https://${QCe}/rsvp/${s.slug}`,"_blank"),children:[e.jsx(bv,{className:"mr-2 h-4 w-4"}),"Preview RSVP page"]}),e.jsxs(ca,{onClick:a,children:[s.is_active?e.jsx(Ax,{className:"mr-2 h-4 w-4"}):e.jsx(ya,{className:"mr-2 h-4 w-4"}),s.is_active?"Deactivate":"Activate"]}),e.jsx(M0,{}),e.jsxs(ca,{onClick:i,className:"text-destructive focus:text-destructive",children:[e.jsx(Sn,{className:"mr-2 h-4 w-4"}),"Delete"]})]})]})]})]})}),t&&e.jsxs(Me,{className:"pt-0",children:[e.jsx(wc,{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://",QCe,"/",s.slug]})]}),e.jsx(Qir,{visitors:o??[],onExport:S}),s.kind!=="virtual"&&e.jsx("div",{className:"mt-4",children:e.jsx(Zir,{openHouseId:s.id})}),s.kind==="virtual"&&e.jsx("div",{className:"mt-4",children:e.jsx(Wir,{openHouseId:s.id})}),s.enable_survey&&e.jsx("div",{className:"mt-4",children:e.jsx(Hir,{openHouseId:s.id})})]}),e.jsx(Ls,{open:d,onOpenChange:u,children:e.jsxs(Ps,{className:"sm:max-w-sm",children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"QR Code"}),e.jsx(_r,{className:"truncate",children:s.property_address})]}),e.jsxs("div",{className:"flex flex-col items-center gap-4 py-4",children:[e.jsx("div",{ref:g,className:"bg-white p-4 rounded-xl",children:e.jsx(AN,{value:b,size:240,level:"H"})}),e.jsx("p",{className:"text-xs text-muted-foreground text-center break-all",children:b}),e.jsxs("div",{className:"flex gap-2 w-full",children:[e.jsxs(B,{variant:"outline",className:"flex-1",onClick:C,children:[e.jsx(li,{className:"h-4 w-4 mr-2"}),"Download"]}),e.jsxs(B,{variant:"outline",className:"flex-1",onClick:E,children:[e.jsx(ZA,{className:"h-4 w-4 mr-2"}),"Print Flyer"]})]}),e.jsxs(B,{variant:"default",className:"w-full",onClick:P,disabled:y,children:[e.jsx(ln,{className:"h-4 w-4 mr-2"}),y?"Sending...":"Email Link to Me"]})]})]})}),e.jsx($ir,{open:h,onOpenChange:m,openHouse:s}),e.jsx(Yir,{open:p,onOpenChange:f,variant:s.kind==="virtual"?"tour":"rsvp",openHouse:{id:s.id,slug:s.slug,property_address:s.property_address,city:s.city,state:s.state,zip:s.zip,photo_url:s.photo_url,event_date:s.event_date,start_time:s.start_time,end_time:s.end_time}})]})}const tor=Bj({full_name:Zo().trim().min(2,"Please enter your name").max(120),email:Zo().trim().email("Please enter a valid email").max(200),brokerage:Zo().trim().min(2,"Please enter your brokerage").max(160)}),iCt=s=>s?s.replace(/<\s*(br|\/p|\/div|\/li)\s*\/?\s*>/gi,` `).replace(/<[^>]*>/g,"").replace(/ /g," ").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/\n{2,}/g,` `).trim():"",sor=s=>{if(!s)return"";const t=s/(1024*1024);return t>=1?`${t.toFixed(1)} MB`:`${Math.max(1,Math.round(s/1024))} KB`};function nor(){var S;const{slug:s}=Li(),[t,n]=_.useState(!0),[r,a]=_.useState(null),[i,l]=_.useState([]),[o,c]=_.useState(!1),[d,u]=_.useState({full_name:"",email:"",brokerage:""}),[h,m]=_.useState(""),[p,f]=_.useState(!1),[y,v]=_.useState(!1);_.useEffect(()=>{let C=!0;return(async()=>{n(!0);const{data:E,error:P}=await q.functions.invoke("resource-kit-public",{body:{slug:s}});C&&(P||!(E!=null&&E.kit)?c(!0):(a(E.kit),l(E.files??[])),n(!1))})(),()=>{C=!1}},[s]);const g=async C=>{C.preventDefault(),m("");const E=tor.safeParse(d);if(!E.success){m(E.error.issues[0].message);return}f(!0);try{const{data:P,error:M}=await q.functions.invoke("resource-kit-unlock",{body:{slug:s,...E.data}});if(M)throw M;if(P!=null&&P.error)throw new Error("Something went wrong. Please try again.");l(P.files??[]),v(!0)}catch(P){m(P.message||"Something went wrong. Please try again.")}finally{f(!1)}};if(t)return e.jsx("div",{className:"min-h-screen bg-slate-950 p-6",children:e.jsxs("div",{className:"max-w-5xl mx-auto space-y-6 pt-16",children:[e.jsx(cn,{className:"h-10 w-2/3 bg-white/10"}),e.jsx(cn,{className:"h-64 w-full bg-white/10"})]})});if(o||!r)return e.jsx("div",{className:"min-h-screen bg-slate-950 flex items-center justify-center px-6 text-center",children:e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-white",children:"This resource isn't available"}),e.jsx("p",{className:"mt-2 text-slate-400",children:"The link may have expired or been unpublished."})]})});const b=iCt(r.subheadline),j=(b||`Download ${r.name} — a free resource for real estate agents.`).replace(/\s*\n\s*/g," ").slice(0,155);return e.jsxs("div",{className:"min-h-screen bg-slate-950 text-white",children:[e.jsxs(ul,{children:[e.jsx("title",{children:`${r.headline} | LevelUp`.slice(0,60)}),e.jsx("meta",{name:"description",content:j}),e.jsx("link",{rel:"canonical",href:`${window.location.origin}/resources/${r.slug}`}),e.jsx("meta",{property:"og:title",content:r.headline}),e.jsx("meta",{property:"og:description",content:j}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:url",content:`${window.location.origin}/resources/${r.slug}`}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),r.hero_image_url&&e.jsx("meta",{property:"og:image",content:r.hero_image_url}),r.hero_image_url&&e.jsx("meta",{name:"twitter:image",content:r.hero_image_url})]}),e.jsxs("div",{className:"pointer-events-none fixed inset-0 opacity-60",children:[e.jsx("div",{className:"absolute -top-40 -left-32 h-96 w-96 rounded-full bg-amber-500/20 blur-3xl"}),e.jsx("div",{className:"absolute top-1/3 -right-32 h-96 w-96 rounded-full bg-sky-500/20 blur-3xl"})]}),e.jsxs("div",{className:"relative max-w-6xl mx-auto px-5 py-12 md:py-20",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-bold tracking-tight mb-10",children:[e.jsxs("span",{className:"text-white",children:["Level",e.jsx("span",{className:"text-amber-400",children:"Up"})]}),e.jsx("span",{className:"text-slate-500 font-medium",children:"· Free Agent Resource"})]}),e.jsxs("div",{className:"grid lg:grid-cols-[1.15fr_1fr] gap-10 lg:gap-14 items-start",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/5 px-3 py-1 text-[12px] font-semibold text-amber-300",children:[e.jsx(un,{className:"h-3.5 w-3.5"})," Instant download"]}),e.jsx("h1",{className:"mt-5 text-4xl md:text-5xl font-black tracking-tight leading-[1.05]",children:r.headline}),b&&e.jsx("p",{className:"mt-5 text-lg text-slate-300 leading-relaxed max-w-xl whitespace-pre-line",children:b}),r.hero_image_url&&e.jsx("div",{className:"mt-8 overflow-hidden rounded-2xl border border-white/10 shadow-2xl",children:e.jsx("img",{src:r.hero_image_url,alt:r.name,loading:"lazy",className:"w-full h-56 md:h-72 object-cover"})}),((S=r.benefits)==null?void 0:S.length)>0&&e.jsx("ul",{className:"mt-8 space-y-3",children:r.benefits.map((C,E)=>e.jsxs("li",{className:"flex items-start gap-3 text-slate-200",children:[e.jsx(Er,{className:"h-5 w-5 shrink-0 text-amber-400 mt-0.5"}),e.jsx("span",{className:"leading-relaxed",children:iCt(C)||C})]},E))}),i.length>0&&e.jsxs("div",{className:"mt-10",children:[e.jsx("div",{className:"text-xs uppercase tracking-widest text-slate-400 font-semibold mb-3",children:"What's inside"}),e.jsx("div",{className:"space-y-2",children:i.map(C=>e.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-white/10 bg-white/5 px-4 py-3",children:[e.jsx(Fr,{className:"h-4 w-4 text-slate-300 shrink-0"}),e.jsx("span",{className:"flex-1 text-sm text-slate-100 truncate",children:C.name}),e.jsx("span",{className:"text-[11px] text-slate-400",children:sor(C.file_size)}),y&&C.file_url?e.jsx(B,{asChild:!0,size:"sm",className:"h-8 rounded-full bg-amber-400 text-slate-900 hover:bg-amber-300",children:e.jsxs("a",{href:C.file_url,target:"_blank",rel:"noopener noreferrer",download:!0,children:[e.jsx(li,{className:"h-3.5 w-3.5 mr-1"})," Download"]})}):e.jsx(ec,{className:"h-3.5 w-3.5 text-slate-500"})]},C.id))})]})]}),e.jsx("div",{className:"lg:sticky lg:top-10",children:e.jsx("div",{className:"rounded-3xl border border-white/10 bg-white/[0.06] backdrop-blur p-6 md:p-8 shadow-2xl",children:y?e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"mx-auto h-14 w-14 rounded-2xl bg-emerald-400/15 grid place-items-center",children:e.jsx(Er,{className:"h-7 w-7 text-emerald-400"})}),e.jsx("h2",{className:"mt-4 text-xl font-bold",children:"You're all set"}),e.jsxs("p",{className:"mt-1.5 text-sm text-slate-300",children:["Your files are unlocked on this page and a copy is on the way to ",d.email,"."]}),e.jsx("div",{className:"mt-6 space-y-2 text-left",children:i.map(C=>C.file_url&&e.jsxs("a",{href:C.file_url,target:"_blank",rel:"noopener noreferrer",download:!0,className:"flex items-center gap-3 rounded-xl border border-white/10 bg-white/5 px-4 py-3 hover:bg-white/10 transition",children:[e.jsx(li,{className:"h-4 w-4 text-amber-400"}),e.jsx("span",{className:"text-sm truncate",children:C.name})]},C.id))}),e.jsxs("div",{className:"mt-7 rounded-2xl bg-slate-900/60 border border-white/10 p-5 text-left",children:[e.jsx("div",{className:"font-semibold",children:"Want the whole toolbox?"}),e.jsx("p",{className:"mt-1 text-sm text-slate-300",children:"LevelUp gives agents marketing, CRM, listing tools, and coaching in one place."}),e.jsx(B,{asChild:!0,className:"mt-4 w-full h-11 rounded-xl bg-white text-slate-900 font-bold hover:bg-slate-100",children:e.jsx("a",{href:"https://dashboard.relevelup.com/trial",children:"Try LevelUp Free"})})]})]}):e.jsxs(e.Fragment,{children:[e.jsx("h2",{className:"text-xl font-bold",children:"Get instant access"}),e.jsx("p",{className:"mt-1.5 text-sm text-slate-300",children:"Tell us where to send it and the files unlock right here."}),e.jsxs("form",{onSubmit:g,className:"mt-6 space-y-4",children:[e.jsxs("div",{children:[e.jsx(J,{htmlFor:"full_name",className:"text-slate-200",children:"Agent name"}),e.jsx(xe,{id:"full_name",value:d.full_name,onChange:C=>u({...d,full_name:C.target.value}),placeholder:"Jane Smith",className:"mt-1.5 h-11 bg-white/5 border-white/15 text-white placeholder:text-slate-500"})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"email",className:"text-slate-200",children:"Email"}),e.jsx(xe,{id:"email",type:"email",value:d.email,onChange:C=>u({...d,email:C.target.value}),placeholder:"you@email.com",className:"mt-1.5 h-11 bg-white/5 border-white/15 text-white placeholder:text-slate-500"})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"brokerage",className:"text-slate-200",children:"Brokerage"}),e.jsx(xe,{id:"brokerage",value:d.brokerage,onChange:C=>u({...d,brokerage:C.target.value}),placeholder:"Your brokerage",className:"mt-1.5 h-11 bg-white/5 border-white/15 text-white placeholder:text-slate-500"})]}),h&&e.jsx("p",{className:"text-sm text-red-300",children:h}),e.jsxs(B,{type:"submit",disabled:p,className:"w-full h-12 rounded-xl bg-amber-400 text-slate-900 font-bold hover:bg-amber-300",children:[p?"Unlocking…":r.cta_text,e.jsx(La,{className:"h-4 w-4 ml-1.5"})]}),e.jsxs("p",{className:"flex items-start gap-2 text-[11px] leading-relaxed text-slate-400",children:[e.jsx(Dm,{className:"h-3.5 w-3.5 shrink-0 mt-0.5"}),"By downloading, you agree to receive occasional emails from LevelUp about tools and resources for agents. Unsubscribe anytime."]})]})]})})})]})]})]})}Jrt.workerSrc=eat;const ror={signature:Qm,initials:c$,date_signed:pc,printed_name:Fo,text:l$},has={signature:"Signature",initials:"Initials",date_signed:"Date signed",printed_name:"Printed name",text:"Text"};function mas(){return new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"2-digit",day:"2-digit",year:"numeric"}).format(new Date)}function aor(s,t){const n=document.createElement("canvas");n.width=600,n.height=t?200:140;const r=n.getContext("2d");return r.fillStyle="#12233f",r.font=`${t?84:64}px "Segoe Script", "Brush Script MT", "Snell Roundhand", cursive`,r.textAlign="center",r.textBaseline="middle",r.fillText(s,n.width/2,n.height/2+10),n.toDataURL("image/png")}function ior(){var H,Y,Z,ne;const{token:s}=Li(),t=Fn(),[n,r]=_.useState(!0),[a,i]=_.useState(null),[l,o]=_.useState(null),[c,d]=_.useState(null),[u,h]=_.useState(null),m=_.useRef(null),p=_.useRef([]),[f,y]=_.useState({}),[v,g]=_.useState({}),[b,j]=_.useState(null),[S,C]=_.useState(!1),[E,P]=_.useState(!1),[M,I]=_.useState(!1);_.useEffect(()=>{let ce=!1;return r(!0),i(null),o(null),d(null),h(null),y({}),C(!1),(async()=>{var ae;const{data:ie,error:te}=await q.functions.invoke("forms-sign-public",{body:{action:"load",token:s}});if(!ce){if(te||ie!=null&&ie.error)i((ie==null?void 0:ie.error)||"This signing link could not be loaded.");else if(ie.state==="already_signed")d("signed");else{o(ie);const le={};for(const be of ie.fields||[])be.field_kind==="printed_name"&&(le[be.id]={value:((ae=ie.signer)==null?void 0:ae.full_name)||""}),be.field_kind==="date_signed"&&(le[be.id]={value:mas()});y(le)}r(!1)}})(),()=>{ce=!0}},[s]),_.useEffect(()=>{let ce=!1;const ie=m.current;if(!(!(l!=null&&l.pdf_url)||!ie))return(async()=>{try{const ae=await(await fetch(l.pdf_url)).arrayBuffer(),le=await a6e({data:ae}).promise;if(ce)return;ie.innerHTML="",p.current=[];const be=Math.min(ie.clientWidth-16||700,820);for(let me=1;me<=le.numPages;me++){const he=await le.getPage(me);if(ce)return;const pe=he.getViewport({scale:1}),Ce=be/pe.width,Ae=he.getViewport({scale:Ce*(window.devicePixelRatio||1)}),Pe=document.createElement("div");Pe.className="relative mx-auto shadow",Pe.style.width=`${be}px`,Pe.style.height=`${pe.height*Ce}px`;const ze=document.createElement("canvas");ze.width=Math.floor(Ae.width),ze.height=Math.floor(Ae.height),ze.style.width="100%",ze.style.height="100%",ze.className="rounded-md border border-border bg-white",Pe.appendChild(ze),ie.appendChild(Pe),p.current[me-1]=Pe;const ke=ze.getContext("2d");ke&&await he.render({canvasContext:ke,viewport:Ae}).promise}ce||y(me=>({...me}))}catch{ce||i("The document could not be displayed.")}})(),()=>{ce=!0}},[l==null?void 0:l.pdf_url]);const D=(l==null?void 0:l.fields)||[],O=D.filter(ce=>{var ie,te;return ce.is_required&&!((ie=f[ce.id])!=null&&ie.value)&&!((te=f[ce.id])!=null&&te.png)}),V=async()=>{if(!S){se.error("Please agree to sign electronically first.");return}if(O.length){se.error("Please complete every highlighted field.");return}P(!0);try{const{data:ce,error:ie}=await q.functions.invoke("forms-sign-public",{body:{action:"submit",token:s,consent:!0,fields:D.filter(te=>f[te.id]).map(te=>{var ae,le;return{mapping_id:te.id,value:(ae=f[te.id])==null?void 0:ae.value,signature_png:(le=f[te.id])==null?void 0:le.png}})}});if(ie||ce!=null&&ce.error)throw new Error((ce==null?void 0:ce.error)||(ie==null?void 0:ie.message)||"Could not submit");ce!=null&&ce.next_token&&h({token:ce.next_token,title:ce.next_title??null}),d("signed"),window.scrollTo({top:0})}catch(ce){se.error((ce==null?void 0:ce.message)||"Could not finish signing")}finally{P(!1)}},G=async()=>{const ce=window.prompt("Optional: tell the sender why you are declining.")??"";I(!0),await q.functions.invoke("forms-sign-public",{body:{action:"decline",token:s,reason:ce}}),d("declined"),I(!1)},$=(ce,ie)=>{y(te=>({...te,[ce.id]:ie})),j(null)};return n?e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-slate-100",children:e.jsx(Ct,{className:"h-8 w-8 animate-spin text-[#406E71]"})}):a?e.jsx(Vde,{icon:e.jsx(Rd,{className:"h-8 w-8 text-destructive"}),title:"Link unavailable",body:a}):c==="declined"?e.jsx(Vde,{icon:e.jsx(Rd,{className:"h-8 w-8 text-muted-foreground"}),title:"Document declined",body:"The sender has been notified that you declined to sign this document."}):c==="signed"&&u?e.jsx(Vde,{icon:e.jsx(Er,{className:"h-8 w-8 text-emerald-600"}),title:"Signed — one more to go",body:u.title?`Next up in this packet: ${u.title}. Your signature is saved and ready to reuse.`:"There is one more document in this packet. Your signature is saved and ready to reuse.",action:e.jsx(B,{className:"mt-5 bg-[#406E71] hover:bg-[#375d60]",onClick:()=>t(`/sign/${u.token}`),children:"Continue to the next document"})}):c==="signed"||(l==null?void 0:l.state)==="already_signed"?e.jsx(Vde,{icon:e.jsx(Er,{className:"h-8 w-8 text-emerald-600"}),title:"You're all set",body:"Thank you — your signature has been recorded. Once everyone has signed, the completed document is delivered to your agent automatically."}):e.jsxs("div",{className:"min-h-screen bg-slate-100 pb-40",children:[e.jsx("header",{className:"sticky top-0 z-20 border-b bg-[#2a4c64] px-4 py-3 text-white shadow-md",children:e.jsxs("div",{className:"mx-auto max-w-3xl",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-[0.18em] opacity-70",children:"LevelUp Forms"}),e.jsx("h1",{className:"truncate text-base font-semibold",children:(H=l==null?void 0:l.envelope)==null?void 0:H.title}),e.jsxs("p",{className:"text-xs opacity-80",children:["Signing as ",(Y=l==null?void 0:l.signer)==null?void 0:Y.full_name]})]})}),((Z=l==null?void 0:l.envelope)==null?void 0:Z.message)&&e.jsx("div",{className:"mx-auto mt-4 max-w-3xl rounded-lg border bg-white px-4 py-3 text-sm text-slate-600 shadow-sm",children:l.envelope.message}),e.jsxs("div",{className:"mx-auto mt-4 max-w-3xl space-y-4 px-2",children:[e.jsx("div",{ref:m,className:"space-y-4"}),D.map(ce=>{const ie=p.current[ce.page_index];if(!ie)return null;const te=f[ce.id],ae=!!(te!=null&&te.png||te!=null&&te.value),le=ror[ce.field_kind];return e.jsx(oCt,{target:ie,children:e.jsx("button",{onClick:()=>j(ce),className:`absolute flex items-center justify-center gap-1 rounded-sm border-2 transition-colors ${ae?"border-emerald-500 bg-emerald-500/10":"animate-pulse border-[#406E71] bg-[#406E71]/15 hover:bg-[#406E71]/25"}`,style:{left:`${ce.pos_x*100}%`,top:`${ce.pos_y*100}%`,width:`${ce.width*100}%`,height:`${ce.height*100}%`},children:te!=null&&te.png?e.jsx("img",{src:te.png,alt:ce.label||"Signature",className:"max-h-full max-w-full object-contain"}):te!=null&&te.value?e.jsx("span",{className:"truncate px-1 text-[10px] font-medium text-emerald-800",children:te.value}):e.jsxs("span",{className:"flex items-center gap-1 px-1 text-[10px] font-semibold text-[#2f5c60]",children:[e.jsx(le,{className:"h-3 w-3"})," ",ce.label||has[ce.field_kind]]})})},ce.id)}),((l==null?void 0:l.data_overlays)||[]).map(ce=>{const ie=p.current[ce.page_index];return!ie||!ce.value?null:e.jsx(oCt,{target:ie,children:e.jsx("div",{className:"pointer-events-none absolute flex items-center",style:{left:`${ce.pos_x*100}%`,top:`${ce.pos_y*100}%`,width:`${ce.width*100}%`,height:`${ce.height*100}%`},children:e.jsx("span",{className:"truncate px-0.5 text-[10px] text-slate-900",children:ce.value})})},ce.id)})]}),e.jsx("div",{className:"fixed inset-x-0 bottom-0 z-30 border-t bg-white/95 px-4 py-3 shadow-[0_-4px_20px_rgba(0,0,0,0.08)] backdrop-blur",children:e.jsxs("div",{className:"mx-auto flex max-w-3xl flex-col gap-2",children:[e.jsxs("label",{className:"flex items-start gap-2 text-xs text-slate-600",children:[e.jsx($a,{checked:S,onCheckedChange:ce=>C(!!ce),className:"mt-0.5"}),e.jsx("span",{children:l==null?void 0:l.consent_text})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{className:"flex-1 bg-[#406E71] hover:bg-[#355c5f]",disabled:E||!S||O.length>0,onClick:V,children:[E?e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Qm,{className:"mr-2 h-4 w-4"}),O.length>0?`${O.length} field${O.length===1?"":"s"} left`:"Finish signing"]}),e.jsx(B,{variant:"ghost",size:"sm",disabled:M,onClick:G,className:"text-muted-foreground",children:"Decline"})]})]})}),e.jsx(oor,{field:b,signerName:((ne=l==null?void 0:l.signer)==null?void 0:ne.full_name)||"",current:b?f[b.id]:void 0,adopted:v,onAdopt:(ce,ie)=>{g(te=>({...te,[ce]:ie})),y(te=>{var le;const ae={...te};for(const be of D)be.field_kind===ce&&!((le=ae[be.id])!=null&&le.png)&&(ae[be.id]={png:ie});return ae})},onClose:()=>j(null),onApply:$})]})}function Vde({icon:s,title:t,body:n,action:r}){return e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-slate-100 p-4",children:e.jsxs("div",{className:"w-full max-w-md rounded-2xl border bg-white p-8 text-center shadow-sm",children:[e.jsx("div",{className:"mx-auto mb-4 flex h-14 w-14 items-center justify-center rounded-full bg-slate-100",children:s}),e.jsx("h1",{className:"text-lg font-semibold",children:t}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:n}),r]})})}function oCt({target:s,children:t}){return mv.createPortal(t,s)}function oor({field:s,signerName:t,current:n,adopted:r,onAdopt:a,onClose:i,onApply:l}){const o=(s==null?void 0:s.field_kind)==="signature"||(s==null?void 0:s.field_kind)==="initials",c=(s==null?void 0:s.field_kind)==="initials"?"initials":"signature",[d,u]=_.useState(""),h=_.useRef(null),m=_.useRef(!1),[p,f]=_.useState("");_.useEffect(()=>{if(!s)return;f((n==null?void 0:n.value)||(s.field_kind==="printed_name"?t:s.field_kind==="date_signed"?mas():"")),u(s.field_kind==="initials"?t.split(" ").map(S=>S[0]).join(""):t);const j=h.current;if(j){const S=j.getContext("2d");S==null||S.clearRect(0,0,j.width,j.height)}},[s==null?void 0:s.id]);const y=j=>{const S=h.current;if(!S)return;m.current=!0,S.setPointerCapture(j.pointerId);const C=S.getContext("2d"),E=S.getBoundingClientRect();C.strokeStyle="#12233f",C.lineWidth=3,C.lineCap="round",C.beginPath(),C.moveTo((j.clientX-E.left)/E.width*S.width,(j.clientY-E.top)/E.height*S.height)},v=j=>{if(!m.current)return;const S=h.current;if(!S)return;const C=S.getContext("2d"),E=S.getBoundingClientRect();C.lineTo((j.clientX-E.left)/E.width*S.width,(j.clientY-E.top)/E.height*S.height),C.stroke()},g=()=>{m.current=!1},b=(j,S)=>{s&&(S&&o&&a(c,j),l(s,{png:j}))};return e.jsx(qg,{open:!!s,onOpenChange:j=>!j&&i(),children:e.jsxs(hg,{side:"bottom",className:"mx-auto max-w-lg rounded-t-2xl",children:[e.jsx(P0,{className:"text-left",children:e.jsx(L0,{className:"text-base",children:(s==null?void 0:s.label)||(s?has[s.field_kind]:"")})}),s&&o&&e.jsxs(Yr,{defaultValue:r[c]?"saved":"draw",className:"mt-3",children:[e.jsxs(Zr,{className:"grid w-full grid-cols-3",children:[e.jsx(Ht,{value:"draw",children:"Draw"}),e.jsx(Ht,{value:"type",children:"Type"}),e.jsx(Ht,{value:"saved",disabled:!r[c],children:"Saved"})]}),e.jsxs(Gt,{value:"draw",className:"space-y-3 pt-3",children:[e.jsx("canvas",{ref:h,width:640,height:220,className:"h-40 w-full touch-none rounded-lg border bg-white",onPointerDown:y,onPointerMove:v,onPointerUp:g}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>{var S;const j=h.current;(S=j==null?void 0:j.getContext("2d"))==null||S.clearRect(0,0,j.width,j.height)},children:[e.jsx(Lq,{className:"mr-1 h-3.5 w-3.5"})," Clear"]}),e.jsxs(B,{size:"sm",className:"flex-1 bg-[#406E71] hover:bg-[#355c5f]",onClick:()=>{const j=h.current;j&&b(j.toDataURL("image/png"),!0)},children:["Use this ",s.field_kind==="initials"?"initials":"signature"," everywhere"]})]})]}),e.jsxs(Gt,{value:"type",className:"space-y-3 pt-3",children:[e.jsx(xe,{value:d,onChange:j=>u(j.target.value),placeholder:"Type your name"}),d.trim()&&e.jsx("div",{className:"flex h-24 items-center justify-center rounded-lg border bg-white",children:e.jsx("span",{className:"text-3xl text-[#12233f]",style:{fontFamily:'"Segoe Script","Brush Script MT",cursive'},children:d})}),e.jsx(B,{size:"sm",className:"w-full bg-[#406E71] hover:bg-[#355c5f]",disabled:!d.trim(),onClick:()=>b(aor(d.trim(),s.field_kind==="signature"),!0),children:"Use this everywhere"})]}),e.jsx(Gt,{value:"saved",className:"space-y-3 pt-3",children:r[c]&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex h-24 items-center justify-center rounded-lg border bg-white p-2",children:e.jsx("img",{src:r[c],alt:"Saved signature",className:"max-h-full object-contain"})}),e.jsxs(B,{size:"sm",className:"w-full bg-[#406E71] hover:bg-[#355c5f]",onClick:()=>b(r[c],!1),children:["Use saved ",s.field_kind==="initials"?"initials":"signature"]})]})})]}),s&&!o&&e.jsxs("div",{className:"mt-3 space-y-3",children:[e.jsx(xe,{value:p,onChange:j=>f(j.target.value),autoFocus:!0}),e.jsx(B,{size:"sm",className:"w-full bg-[#406E71] hover:bg-[#355c5f]",disabled:!p.trim(),onClick:()=>l(s,{value:p.trim()}),children:"Apply"})]})]})})}const lCt="https://dashboard.relevelup.com/trial",lor=["Full LevelUp Agent OS access","300+ marketing templates & AI tools","Cancel anytime — no risk"];function QYe({variant:s="full",className:t=""}){return s==="compact"?e.jsxs("div",{className:`rounded-2xl border border-amber-400/20 bg-gradient-to-br from-amber-500/10 to-transparent p-5 ${t}`,children:[e.jsxs("div",{className:"inline-flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-widest text-amber-300",children:[e.jsx(un,{className:"h-3.5 w-3.5"})," Free trial"]}),e.jsx("h3",{className:"mt-3 text-lg font-bold text-white leading-snug",children:"Try LevelUp free"}),e.jsx("p",{className:"mt-2 text-sm text-slate-300 leading-relaxed",children:"Everything you just read — plus the tools to actually run it. Start your free trial today."}),e.jsxs("a",{href:lCt,className:"mt-4 inline-flex w-full items-center justify-center gap-2 rounded-xl bg-amber-400 px-4 py-2.5 text-sm font-bold text-slate-950 transition hover:bg-amber-300",children:["Start free trial ",e.jsx(La,{className:"h-4 w-4"})]})]}):e.jsxs("section",{className:`relative overflow-hidden rounded-3xl border border-amber-400/20 bg-gradient-to-br from-amber-500/15 via-slate-900 to-slate-900 p-8 md:p-12 ${t}`,children:[e.jsx("div",{className:"pointer-events-none absolute -top-24 -right-16 h-64 w-64 rounded-full bg-amber-400/20 blur-3xl"}),e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/5 px-3 py-1 text-[12px] font-semibold text-amber-300",children:[e.jsx(un,{className:"h-3.5 w-3.5"})," Free trial · no credit card hassle"]}),e.jsx("h2",{className:"mt-5 text-3xl md:text-4xl font-black tracking-tight text-white leading-[1.1]",children:"Ready to put this into action?"}),e.jsx("p",{className:"mt-4 max-w-xl text-slate-300 leading-relaxed",children:"LevelUp gives real estate agents the marketing, CRM, and AI tools to win more listings — all in one place. Take it for a spin free."}),e.jsx("ul",{className:"mt-6 grid gap-2 sm:grid-cols-3",children:lor.map(n=>e.jsxs("li",{className:"flex items-start gap-2 text-sm text-slate-200",children:[e.jsx(ea,{className:"mt-0.5 h-4 w-4 shrink-0 text-amber-400"}),e.jsx("span",{children:n})]},n))}),e.jsxs("a",{href:lCt,className:"mt-8 inline-flex items-center gap-2 rounded-xl bg-amber-400 px-6 py-3 text-base font-bold text-slate-950 transition hover:bg-amber-300",children:["Start your free trial ",e.jsx(La,{className:"h-5 w-5"})]})]})]})}const cCt=s=>{if(!s)return"";const[t,n,r]=s.split(/[-/T]/).map(Number);return new Intl.DateTimeFormat("en-US",{month:"long",day:"numeric",year:"numeric",timeZone:"America/New_York"}).format(new Date(Date.UTC(t,n-1,r,12)))},cor=s=>{const t=s.replace(/<[^>]*>/g," ").split(/\s+/).filter(Boolean).length;return Math.max(1,Math.round(t/220))};function dor(){const[s,t]=_.useState([]),[n,r]=_.useState(!0),[a,i]=_.useState("all");_.useEffect(()=>{(async()=>{const{data:u}=await q.from("blog_posts").select("id, slug, title, excerpt, cover_image_url, category, featured, published_at, content").eq("status","published").order("published_at",{ascending:!1}).limit(200);t(u||[]),r(!1)})()},[]);const l=["all",...Array.from(new Set(s.map(u=>u.category).filter(Boolean)))],o=a==="all"?s:s.filter(u=>u.category===a),[c,...d]=o;return e.jsxs("div",{className:"min-h-screen bg-slate-950 text-white",children:[e.jsxs(ul,{children:[e.jsx("title",{children:"The LevelUp Blog | Real Estate Growth Insights"}),e.jsx("meta",{name:"description",content:"Strategies, systems, and stories from the founder of LevelUp — helping real estate agents win more listings and build a business they love."}),e.jsx("link",{rel:"canonical",href:`${window.location.origin}/blog`}),e.jsx("meta",{property:"og:title",content:"The LevelUp Blog"}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:description",content:"Strategies, systems, and stories from the founder of LevelUp for real estate agents."}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"})]}),e.jsxs("div",{className:"pointer-events-none fixed inset-0 opacity-60",children:[e.jsx("div",{className:"absolute -top-40 -left-32 h-96 w-96 rounded-full bg-amber-500/20 blur-3xl"}),e.jsx("div",{className:"absolute top-1/3 -right-32 h-96 w-96 rounded-full bg-sky-500/20 blur-3xl"})]}),e.jsxs("div",{className:"relative mx-auto max-w-6xl px-5 py-12 md:py-16",children:[e.jsxs(ir,{to:"/",className:"flex items-center gap-2 text-sm font-bold tracking-tight",children:[e.jsxs("span",{className:"text-white",children:["Level",e.jsx("span",{className:"text-amber-400",children:"Up"})]}),e.jsx("span",{className:"font-medium text-slate-500",children:"· Blog"})]}),e.jsxs("header",{className:"mt-10 max-w-3xl",children:[e.jsxs("h1",{className:"text-4xl font-black leading-[1.05] tracking-tight md:text-6xl",children:["Ideas that move your ",e.jsx("span",{className:"text-amber-400",children:"real estate business"})," forward."]}),e.jsx("p",{className:"mt-5 text-lg leading-relaxed text-slate-300",children:"Strategies, systems, and honest lessons from the founder of LevelUp — written for agents who want to grow on purpose."})]}),l.length>2&&e.jsx("div",{className:"mt-8 flex flex-wrap gap-2",children:l.map(u=>e.jsx("button",{onClick:()=>i(u),className:`rounded-full border px-4 py-1.5 text-sm font-medium transition ${a===u?"border-amber-400/40 bg-amber-400/15 text-amber-200":"border-white/10 bg-white/5 text-slate-300 hover:bg-white/10"}`,children:u==="all"?"All articles":u},u))}),n?e.jsx("div",{className:"mt-12 grid gap-6 md:grid-cols-3",children:[0,1,2].map(u=>e.jsx(cn,{className:"h-72 w-full bg-white/10"},u))}):o.length===0?e.jsx("p",{className:"mt-16 text-slate-400",children:"No articles published yet — check back soon."}):e.jsxs(e.Fragment,{children:[c&&e.jsxs(ir,{to:`/blog/${c.slug}`,className:"group mt-12 grid gap-8 overflow-hidden rounded-3xl border border-white/10 bg-white/5 p-6 transition hover:border-amber-400/30 md:grid-cols-2 md:p-8",children:[c.cover_image_url&&e.jsx("div",{className:"overflow-hidden rounded-2xl",children:e.jsx("img",{src:c.cover_image_url,alt:c.title,className:"h-56 w-full object-cover transition duration-500 group-hover:scale-105 md:h-72"})}),e.jsxs("div",{className:"flex flex-col justify-center",children:[e.jsxs("div",{className:"flex items-center gap-3 text-xs text-slate-400",children:[c.category&&e.jsx(Oe,{className:"border-amber-400/30 bg-amber-400/15 text-amber-200",children:c.category}),e.jsx("span",{children:cCt(c.published_at)}),e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Gr,{className:"h-3 w-3"})," ",cor(c.content)," min read"]})]}),e.jsx("h2",{className:"mt-4 text-2xl font-bold leading-tight md:text-3xl",children:c.title}),c.excerpt&&e.jsx("p",{className:"mt-3 leading-relaxed text-slate-300",children:c.excerpt}),e.jsxs("span",{className:"mt-5 inline-flex items-center gap-2 text-sm font-semibold text-amber-300",children:["Read article ",e.jsx(La,{className:"h-4 w-4 transition group-hover:translate-x-1"})]})]})]}),d.length>0&&e.jsx("div",{className:"mt-8 grid gap-6 md:grid-cols-3",children:d.map(u=>e.jsxs(ir,{to:`/blog/${u.slug}`,className:"group flex flex-col overflow-hidden rounded-2xl border border-white/10 bg-white/5 transition hover:border-amber-400/30",children:[u.cover_image_url?e.jsx("img",{src:u.cover_image_url,alt:u.title,loading:"lazy",className:"h-44 w-full object-cover transition duration-500 group-hover:scale-105"}):e.jsx("div",{className:"h-44 w-full bg-gradient-to-br from-amber-500/20 to-slate-900"}),e.jsxs("div",{className:"flex flex-1 flex-col p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-slate-400",children:[u.category&&e.jsx("span",{className:"text-amber-300",children:u.category}),e.jsx("span",{children:cCt(u.published_at)})]}),e.jsx("h3",{className:"mt-2 text-lg font-bold leading-snug",children:u.title}),u.excerpt&&e.jsx("p",{className:"mt-2 line-clamp-3 text-sm leading-relaxed text-slate-400",children:u.excerpt}),e.jsxs("span",{className:"mt-4 inline-flex items-center gap-1.5 text-sm font-semibold text-amber-300",children:["Read ",e.jsx(La,{className:"h-3.5 w-3.5 transition group-hover:translate-x-1"})]})]})]},u.id))})]}),e.jsx(QYe,{className:"mt-16"}),e.jsxs("footer",{className:"mt-14 border-t border-white/10 pt-8 text-sm text-slate-500",children:["© ",new Date().getFullYear()," LevelUp · ",e.jsx(ir,{to:"/",className:"hover:text-slate-300",children:"Home"})]})]})]})}const uor=s=>(s||"LevelUp Member").split(" ").map(t=>t[0]).slice(0,2).join("").toUpperCase(),hor=s=>{const[t,n]=s.split("T"),[r,a,i]=t.split("-").map(Number);return new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric",timeZone:"America/New_York"}).format(new Date(Date.UTC(r,a-1,i,Number((n||"12").slice(0,2))||12)))};function mor({postId:s,allowComments:t}){const{user:n}=hs(),[r,a]=_.useState([]),[i,l]=_.useState(!0),[o,c]=_.useState(""),[d,u]=_.useState(null),[h,m]=_.useState(""),[p,f]=_.useState(!1),y=_.useCallback(async()=>{l(!0);const{data:C,error:E}=await q.from("blog_comments").select("id, post_id, user_id, parent_id, body, created_at").eq("post_id",s).eq("is_hidden",!1).order("created_at",{ascending:!0});if(E){l(!1);return}const P=C||[],M=[...new Set(P.map(I=>I.user_id))];if(M.length){const{data:I}=await q.from("profiles").select("id, name, avatar_url").in("id",M),D=new Map((I||[]).map(O=>[O.id,O]));P.forEach(O=>{O.author=D.get(O.user_id)})}a(P),l(!1)},[s]);_.useEffect(()=>{y()},[y]);const v=async(C,E)=>{if(!n){se.error("Sign in to comment");return}if(!C.trim())return;f(!0);const{error:P}=await q.from("blog_comments").insert({post_id:s,user_id:n.id,parent_id:E,body:C.trim()});if(f(!1),P){se.error(P.message);return}c(""),m(""),u(null),se.success("Comment posted"),y()},g=async C=>{const{error:E}=await q.from("blog_comments").delete().eq("id",C);if(E){se.error(E.message);return}y()},b=r.filter(C=>!C.parent_id),j=C=>r.filter(E=>E.parent_id===C),S=({c:C,nested:E=!1})=>{var P,M,I;return e.jsxs("div",{className:`flex gap-3 ${E?"ml-10 mt-4":"mt-6"}`,children:[e.jsxs(ja,{className:"h-9 w-9 shrink-0",children:[e.jsx(pi,{src:((P=C.author)==null?void 0:P.avatar_url)||void 0}),e.jsx(Na,{className:"bg-white/10 text-xs text-white",children:uor((M=C.author)==null?void 0:M.name)})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-sm font-semibold text-white",children:((I=C.author)==null?void 0:I.name)||"LevelUp Member"}),e.jsx("span",{className:"text-xs text-slate-500",children:hor(C.created_at)})]}),e.jsx("p",{className:"mt-1 whitespace-pre-wrap text-[15px] leading-relaxed text-slate-300",children:C.body}),e.jsxs("div",{className:"mt-1.5 flex items-center gap-3",children:[!E&&n&&e.jsxs("button",{className:"inline-flex items-center gap-1 text-xs font-medium text-slate-400 hover:text-amber-300",onClick:()=>{u(d===C.id?null:C.id),m("")},children:[e.jsx(NQ,{className:"h-3 w-3"})," Reply"]}),(n==null?void 0:n.id)===C.user_id&&e.jsxs("button",{className:"inline-flex items-center gap-1 text-xs font-medium text-slate-500 hover:text-red-400",onClick:()=>g(C.id),children:[e.jsx(Sn,{className:"h-3 w-3"})," Delete"]})]}),d===C.id&&e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(Ms,{value:h,onChange:D=>m(D.target.value),placeholder:"Write a reply…",className:"border-white/10 bg-white/5 text-white placeholder:text-slate-500"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{size:"sm",disabled:p,onClick:()=>v(h,C.id),children:[p&&e.jsx(Ct,{className:"mr-1.5 h-3.5 w-3.5 animate-spin"})," Post reply"]}),e.jsx(B,{size:"sm",variant:"ghost",className:"text-slate-400",onClick:()=>u(null),children:"Cancel"})]})]}),j(C.id).map(D=>e.jsx(S,{c:D,nested:!0},D.id))]})]})};return e.jsxs("section",{id:"comments",className:"mt-14 border-t border-white/10 pt-10",children:[e.jsxs("h2",{className:"flex items-center gap-2 text-xl font-bold text-white",children:[e.jsx(Ou,{className:"h-5 w-5 text-amber-400"}),"Discussion ",r.length>0&&e.jsxs("span",{className:"text-slate-500",children:["(",r.length,")"]})]}),t?n?e.jsxs("div",{className:"mt-5 space-y-3",children:[e.jsx(Ms,{value:o,onChange:C=>c(C.target.value),placeholder:"Share your take with the LevelUp community…",rows:4,className:"border-white/10 bg-white/5 text-white placeholder:text-slate-500"}),e.jsxs(B,{disabled:p||!o.trim(),onClick:()=>v(o,null),children:[p&&e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"})," Post comment"]})]}):e.jsxs("div",{className:"mt-5 rounded-xl border border-white/10 bg-white/5 p-5 text-sm text-slate-300",children:[e.jsx(ir,{to:"/auth",className:"font-semibold text-amber-300 hover:underline",children:"Sign in"})," ","to join the conversation — comments are open to all LevelUp members."]}):e.jsx("p",{className:"mt-4 text-sm text-slate-400",children:"Comments are closed on this article."}),i?e.jsxs("div",{className:"mt-8 flex items-center gap-2 text-sm text-slate-400",children:[e.jsx(Ct,{className:"h-4 w-4 animate-spin"})," Loading comments…"]}):b.length===0?e.jsx("p",{className:"mt-8 text-sm text-slate-500",children:"No comments yet — be the first."}):e.jsx("div",{className:"mt-2",children:b.map(C=>e.jsx(S,{c:C},C.id))})]})}const dCt=s=>{if(!s)return"";const[t,n,r]=s.split(/[-/T]/).map(Number);return new Intl.DateTimeFormat("en-US",{month:"long",day:"numeric",year:"numeric",timeZone:"America/New_York"}).format(new Date(Date.UTC(t,n-1,r,12)))},por=s=>Math.max(1,Math.round(s.replace(/<[^>]*>/g," ").split(/\s+/).filter(Boolean).length/220));function xor(){var h;const{slug:s=""}=Li(),[t,n]=_.useState(null),[r,a]=_.useState([]),[i,l]=_.useState(!0);_.useEffect(()=>{(async()=>{l(!0);const{data:m}=await q.from("blog_posts").select("*").eq("slug",s).eq("status","published").maybeSingle();if(n(m||null),l(!1),m){q.rpc("increment_blog_post_views",{_slug:s});const{data:p}=await q.from("blog_posts").select("id, slug, title, excerpt, cover_image_url, category, published_at, content").eq("status","published").neq("slug",s).order("published_at",{ascending:!1}).limit(3);a(p||[])}})()},[s]);const o=typeof window<"u"?`${window.location.origin}/blog/${s}`:"",c=async m=>{const p=encodeURIComponent((t==null?void 0:t.title)||"LevelUp"),f=encodeURIComponent(o),y={facebook:`https://www.facebook.com/sharer/sharer.php?u=${f}`,linkedin:`https://www.linkedin.com/sharing/share-offsite/?url=${f}`,twitter:`https://twitter.com/intent/tweet?url=${f}&text=${p}`,email:`mailto:?subject=${p}&body=${f}`};if(m==="copy"){await navigator.clipboard.writeText(o),se.success("Link copied");return}if(m==="native"&&navigator.share){try{await navigator.share({title:t==null?void 0:t.title,url:o})}catch{}return}window.open(y[m],"_blank","noopener,width=640,height=560")};if(i)return e.jsx("div",{className:"min-h-screen bg-slate-950 p-6",children:e.jsxs("div",{className:"mx-auto max-w-3xl space-y-6 pt-16",children:[e.jsx(cn,{className:"h-12 w-3/4 bg-white/10"}),e.jsx(cn,{className:"h-64 w-full bg-white/10"}),e.jsx(cn,{className:"h-40 w-full bg-white/10"})]})});if(!t)return e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-slate-950 px-6 text-center",children:e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-white",children:"Article not found"}),e.jsx("p",{className:"mt-2 text-slate-400",children:"It may have been unpublished or moved."}),e.jsx(ir,{to:"/blog",className:"mt-5 inline-block font-semibold text-amber-300 hover:underline",children:"Back to the blog"})]})});const d=(t.seo_title||t.title).slice(0,60),u=(t.seo_description||t.excerpt||t.title).slice(0,155);return e.jsxs("div",{className:"min-h-screen bg-slate-950 text-white",children:[e.jsxs(ul,{children:[e.jsx("title",{children:`${d} | LevelUp`}),e.jsx("meta",{name:"description",content:u}),e.jsx("link",{rel:"canonical",href:o}),e.jsx("meta",{property:"og:type",content:"article"}),e.jsx("meta",{property:"og:title",content:t.title}),e.jsx("meta",{property:"og:description",content:u}),e.jsx("meta",{property:"og:url",content:o}),t.cover_image_url&&e.jsx("meta",{property:"og:image",content:t.cover_image_url}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),t.cover_image_url&&e.jsx("meta",{name:"twitter:image",content:t.cover_image_url}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify({"@context":"https://schema.org","@type":"BlogPosting",headline:t.title,description:u,image:t.cover_image_url||void 0,datePublished:t.published_at,author:{"@type":"Person",name:t.author_name},publisher:{"@type":"Organization",name:"LevelUp"},mainEntityOfPage:o})})]}),e.jsx("div",{className:"pointer-events-none fixed inset-0 opacity-50",children:e.jsx("div",{className:"absolute -top-40 -left-32 h-96 w-96 rounded-full bg-amber-500/20 blur-3xl"})}),e.jsxs("div",{className:"relative mx-auto max-w-6xl px-5 py-10 md:py-14",children:[e.jsxs(ir,{to:"/blog",className:"inline-flex items-center gap-2 text-sm font-medium text-slate-400 hover:text-white",children:[e.jsx(ka,{className:"h-4 w-4"})," All articles"]}),e.jsxs("div",{className:"mt-8 grid gap-12 lg:grid-cols-[minmax(0,1fr)_300px]",children:[e.jsxs("article",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-xs text-slate-400",children:[t.category&&e.jsx(Oe,{className:"border-amber-400/30 bg-amber-400/15 text-amber-200",children:t.category}),e.jsx("span",{children:dCt(t.published_at)}),e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Gr,{className:"h-3 w-3"})," ",por(t.content)," min read"]})]}),e.jsx("h1",{className:"mt-4 text-3xl font-black leading-[1.1] tracking-tight md:text-5xl",children:t.title}),t.excerpt&&e.jsx("p",{className:"mt-5 text-lg leading-relaxed text-slate-300",children:t.excerpt}),e.jsxs("div",{className:"mt-7 flex items-center gap-3 border-y border-white/10 py-4",children:[e.jsxs(ja,{className:"h-11 w-11",children:[e.jsx(pi,{src:t.author_avatar_url||void 0}),e.jsx(Na,{className:"bg-amber-400/20 text-amber-200",children:t.author_name.split(" ").map(m=>m[0]).slice(0,2).join("")})]}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"text-sm font-semibold text-white",children:t.author_name}),e.jsx("div",{className:"text-xs text-slate-400",children:t.author_title})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("button",{onClick:()=>c("copy"),title:"Copy link",className:"rounded-lg p-2 text-slate-400 hover:bg-white/10 hover:text-white",children:e.jsx(vd,{className:"h-4 w-4"})}),e.jsx("button",{onClick:()=>c("facebook"),title:"Share on Facebook",className:"rounded-lg p-2 text-slate-400 hover:bg-white/10 hover:text-white",children:e.jsx(tf,{className:"h-4 w-4"})}),e.jsx("button",{onClick:()=>c("linkedin"),title:"Share on LinkedIn",className:"rounded-lg p-2 text-slate-400 hover:bg-white/10 hover:text-white",children:e.jsx(dg,{className:"h-4 w-4"})}),e.jsx("button",{onClick:()=>c("twitter"),title:"Share on X",className:"rounded-lg p-2 text-slate-400 hover:bg-white/10 hover:text-white",children:e.jsx(uJ,{className:"h-4 w-4"})}),e.jsx("button",{onClick:()=>c("email"),title:"Share by email",className:"rounded-lg p-2 text-slate-400 hover:bg-white/10 hover:text-white",children:e.jsx(ln,{className:"h-4 w-4"})}),e.jsx("button",{onClick:()=>c("native"),title:"Share",className:"rounded-lg p-2 text-slate-400 hover:bg-white/10 hover:text-white md:hidden",children:e.jsx(bd,{className:"h-4 w-4"})})]})]}),t.cover_image_url&&e.jsx("img",{src:t.cover_image_url,alt:t.title,className:"mt-8 w-full rounded-2xl border border-white/10 object-cover"}),e.jsx("div",{className:"blog-content prose prose-invert mt-10 max-w-none prose-headings:font-bold prose-headings:tracking-tight prose-a:text-amber-300 prose-img:rounded-2xl prose-video:rounded-2xl",dangerouslySetInnerHTML:{__html:t.content}}),((h=t.tags)==null?void 0:h.length)>0&&e.jsx("div",{className:"mt-10 flex flex-wrap gap-2",children:t.tags.map(m=>e.jsxs("span",{className:"rounded-full border border-white/10 bg-white/5 px-3 py-1 text-xs text-slate-300",children:["#",m]},m))}),e.jsx(QYe,{className:"mt-14"}),e.jsx(mor,{postId:t.id,allowComments:t.allow_comments})]}),e.jsxs("aside",{className:"space-y-6 lg:sticky lg:top-8 lg:self-start",children:[e.jsx(QYe,{variant:"compact"}),r.length>0&&e.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/5 p-5",children:[e.jsx("div",{className:"text-xs font-semibold uppercase tracking-widest text-slate-400",children:"Keep reading"}),e.jsx("div",{className:"mt-4 space-y-4",children:r.map(m=>e.jsxs(ir,{to:`/blog/${m.slug}`,className:"group block",children:[e.jsx("div",{className:"text-sm font-semibold leading-snug text-slate-100 group-hover:text-amber-300",children:m.title}),e.jsx("div",{className:"mt-1 text-xs text-slate-500",children:dCt(m.published_at)})]},m.id))})]})]})]}),e.jsxs("footer",{className:"mt-16 border-t border-white/10 pt-8 text-sm text-slate-500",children:["© ",new Date().getFullYear()," LevelUp · ",e.jsx(ir,{to:"/blog",className:"hover:text-slate-300",children:"Blog"})]})]})]})}const gor=/^((?:https?:)?\/\/)?((?:www|m|music)\.)?((?:youtube\.com|youtu\.be|youtube-nocookie\.com))(\/(?:[\w-]+\?v=|embed\/|v\/)?)([\w-]+)(\S+)?$/,yor=/^((?:https?:)?\/\/)?((?:www|m|music)\.)?((?:youtube\.com|youtu\.be|youtube-nocookie\.com))(\/(?:[\w-]+\?v=|embed\/|v\/)?)([\w-]+)(\S+)?$/g,pas=s=>s.match(gor),vor=(s,t)=>t?"https://www.youtube-nocookie.com/embed/videoseries?list=":s?"https://www.youtube-nocookie.com/embed/":"https://www.youtube.com/embed/",bor=s=>s.searchParams.has("v")?{id:s.searchParams.get("v")}:s.hostname==="youtu.be"||s.pathname.includes("shorts")||s.pathname.includes("live")?{id:s.pathname.split("/").pop()}:s.searchParams.has("list")?{id:s.searchParams.get("list"),isPlaylist:!0}:null,_or=s=>{var t;const{url:n,allowFullscreen:r,autoplay:a,ccLanguage:i,ccLoadPolicy:l,controls:o,disableKBcontrols:c,enableIFrameApi:d,endTime:u,interfaceLanguage:h,ivLoadPolicy:m,loop:p,modestBranding:f,nocookie:y,origin:v,playlist:g,progressBarColor:b,startAt:j,rel:S}=s;if(!pas(n))return null;if(n.includes("/embed/"))return n;const C=new URL(n),{id:E,isPlaylist:P}=(t=bor(C))!==null&&t!==void 0?t:{};if(!E)return null;const M=new URL(`${vor(y,P)}${E}`);return C.searchParams.has("t")&&M.searchParams.set("start",C.searchParams.get("t").replaceAll("s","")),r===!1&&M.searchParams.set("fs","0"),a&&M.searchParams.set("autoplay","1"),i&&M.searchParams.set("cc_lang_pref",i),l&&M.searchParams.set("cc_load_policy","1"),o||M.searchParams.set("controls","0"),c&&M.searchParams.set("disablekb","1"),d&&M.searchParams.set("enablejsapi","1"),u&&M.searchParams.set("end",u.toString()),h&&M.searchParams.set("hl",h),m&&M.searchParams.set("iv_load_policy",m.toString()),p&&M.searchParams.set("loop","1"),f&&M.searchParams.set("modestbranding","1"),v&&M.searchParams.set("origin",v),g&&M.searchParams.set("playlist",g),j&&M.searchParams.set("start",j.toString()),b&&M.searchParams.set("color",b),S!==void 0&&M.searchParams.set("rel",S.toString()),M.toString()},wor=My.create({name:"youtube",addOptions(){return{addPasteHandler:!0,allowFullscreen:!0,autoplay:!1,ccLanguage:void 0,ccLoadPolicy:void 0,controls:!0,disableKBcontrols:!1,enableIFrameApi:!1,endTime:0,height:480,interfaceLanguage:void 0,ivLoadPolicy:0,loop:!1,modestBranding:!1,HTMLAttributes:{},inline:!1,nocookie:!1,origin:"",playlist:"",progressBarColor:void 0,width:640,rel:1}},inline(){return this.options.inline},group(){return this.options.inline?"inline":"block"},draggable:!0,addAttributes(){return{src:{default:null},start:{default:0},width:{default:this.options.width},height:{default:this.options.height}}},parseHTML(){return[{tag:"div[data-youtube-video] iframe"}]},addCommands(){return{setYoutubeVideo:s=>({commands:t})=>pas(s.src)?t.insertContent({type:this.name,attrs:s}):!1}},addPasteRules(){return this.options.addPasteHandler?[MWs({find:yor,type:this.type,getAttributes:s=>({src:s.input})})]:[]},renderHTML({HTMLAttributes:s}){const t=_or({url:s.src,allowFullscreen:this.options.allowFullscreen,autoplay:this.options.autoplay,ccLanguage:this.options.ccLanguage,ccLoadPolicy:this.options.ccLoadPolicy,controls:this.options.controls,disableKBcontrols:this.options.disableKBcontrols,enableIFrameApi:this.options.enableIFrameApi,endTime:this.options.endTime,interfaceLanguage:this.options.interfaceLanguage,ivLoadPolicy:this.options.ivLoadPolicy,loop:this.options.loop,modestBranding:this.options.modestBranding,nocookie:this.options.nocookie,origin:this.options.origin,playlist:this.options.playlist,progressBarColor:this.options.progressBarColor,startAt:s.start||0,rel:this.options.rel});return s.src=t,["div",{"data-youtube-video":""},["iframe",rp(this.options.HTMLAttributes,{width:this.options.width,height:this.options.height,allowfullscreen:this.options.allowFullscreen,autoplay:this.options.autoplay,ccLanguage:this.options.ccLanguage,ccLoadPolicy:this.options.ccLoadPolicy,disableKBcontrols:this.options.disableKBcontrols,enableIFrameApi:this.options.enableIFrameApi,endTime:this.options.endTime,interfaceLanguage:this.options.interfaceLanguage,ivLoadPolicy:this.options.ivLoadPolicy,loop:this.options.loop,modestBranding:this.options.modestBranding,origin:this.options.origin,playlist:this.options.playlist,progressBarColor:this.options.progressBarColor,rel:this.options.rel},s)]]}}),jor=My.create({name:"videoEmbed",group:"block",atom:!0,draggable:!0,addAttributes(){return{src:{default:null},poster:{default:null}}},parseHTML(){return[{tag:"video[src]"}]},renderHTML({HTMLAttributes:s}){return["video",rp(s,{controls:"true",playsinline:"true",preload:"metadata",class:"w-full rounded-xl"})]}}),e0=({onClick:s,active:t,title:n,children:r,disabled:a})=>e.jsx(B,{type:"button",variant:t?"secondary":"ghost",size:"sm",className:"h-8 w-8 p-0",title:n,disabled:a,onClick:s,children:r});function Nor({content:s,onChange:t,placeholder:n="Write your article…"}){const[r,a]=_.useState(!1),[i,l]=_.useState(""),[o,c]=_.useState(!1),[d,u]=_.useState(""),[h,m]=_.useState(!1),p=_.useRef(null),f=_.useRef(null),y=ALe({extensions:[ELe.configure({heading:{levels:[2,3,4]}}),Urs,MLe.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline"}}),UUt.configure({HTMLAttributes:{class:"rounded-xl w-full"}}),PLe.configure({types:["heading","paragraph"]}),wor.configure({width:960,height:540,HTMLAttributes:{class:"w-full aspect-video rounded-xl"}}),jor],content:s||"",editorProps:{attributes:{class:"prose prose-slate dark:prose-invert max-w-none min-h-[420px] focus:outline-none px-4 py-4"}},onUpdate:({editor:j})=>t(j.getHTML())});_.useEffect(()=>{y&&s!==y.getHTML()&&y.commands.setContent(s||"",!1)},[s]);const v=_.useCallback(async(j,S)=>{var D;const{data:C}=await q.auth.getUser(),E=(D=C.user)==null?void 0:D.id;if(!E)return se.error("You must be signed in"),null;const P=j.name.split(".").pop()||(S==="image"?"jpg":"mp4"),M=`${E}/blog/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${P}`,{error:I}=await q.storage.from("email-assets").upload(M,j,{cacheControl:"31536000",upsert:!1});return I?(se.error(`Upload failed: ${I.message}`),null):q.storage.from("email-assets").getPublicUrl(M).data.publicUrl},[]),g=async(j,S)=>{if(!j||!y)return;m(!0);const C=await v(j,S);m(!1),C&&(S==="image"?y.chain().focus().setImage({src:C}).run():y.chain().focus().insertContent({type:"videoEmbed",attrs:{src:C}}).run())};if(!y)return null;const b=y;return e.jsxs("div",{className:"rounded-xl border bg-background overflow-hidden",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-0.5 border-b bg-muted/40 px-2 py-1.5 sticky top-0 z-10",children:[e.jsx(e0,{title:"Bold",active:b.isActive("bold"),onClick:()=>b.chain().focus().toggleBold().run(),children:e.jsx(BA,{className:"h-4 w-4"})}),e.jsx(e0,{title:"Italic",active:b.isActive("italic"),onClick:()=>b.chain().focus().toggleItalic().run(),children:e.jsx($A,{className:"h-4 w-4"})}),e.jsx(e0,{title:"Underline",active:b.isActive("underline"),onClick:()=>b.chain().focus().toggleUnderline().run(),children:e.jsx(u7,{className:"h-4 w-4"})}),e.jsx("div",{className:"mx-1 h-5 w-px bg-border"}),e.jsx(e0,{title:"Heading",active:b.isActive("heading",{level:2}),onClick:()=>b.chain().focus().toggleHeading({level:2}).run(),children:e.jsx(ZO,{className:"h-4 w-4"})}),e.jsx(e0,{title:"Subheading",active:b.isActive("heading",{level:3}),onClick:()=>b.chain().focus().toggleHeading({level:3}).run(),children:e.jsx(zq,{className:"h-4 w-4"})}),e.jsx(e0,{title:"Bullet list",active:b.isActive("bulletList"),onClick:()=>b.chain().focus().toggleBulletList().run(),children:e.jsx(A0,{className:"h-4 w-4"})}),e.jsx(e0,{title:"Numbered list",active:b.isActive("orderedList"),onClick:()=>b.chain().focus().toggleOrderedList().run(),children:e.jsx(xj,{className:"h-4 w-4"})}),e.jsx(e0,{title:"Quote",active:b.isActive("blockquote"),onClick:()=>b.chain().focus().toggleBlockquote().run(),children:e.jsx(pS,{className:"h-4 w-4"})}),e.jsx(e0,{title:"Code block",active:b.isActive("codeBlock"),onClick:()=>b.chain().focus().toggleCodeBlock().run(),children:e.jsx(UA,{className:"h-4 w-4"})}),e.jsx("div",{className:"mx-1 h-5 w-px bg-border"}),e.jsx(e0,{title:"Align left",active:b.isActive({textAlign:"left"}),onClick:()=>b.chain().focus().setTextAlign("left").run(),children:e.jsx(qM,{className:"h-4 w-4"})}),e.jsx(e0,{title:"Align center",active:b.isActive({textAlign:"center"}),onClick:()=>b.chain().focus().setTextAlign("center").run(),children:e.jsx(UM,{className:"h-4 w-4"})}),e.jsx(e0,{title:"Align right",active:b.isActive({textAlign:"right"}),onClick:()=>b.chain().focus().setTextAlign("right").run(),children:e.jsx($M,{className:"h-4 w-4"})}),e.jsx("div",{className:"mx-1 h-5 w-px bg-border"}),e.jsx(e0,{title:"Link",active:b.isActive("link"),onClick:()=>{l(b.getAttributes("link").href||""),a(!0)},children:e.jsx(Vc,{className:"h-4 w-4"})}),e.jsx(e0,{title:"Insert image",disabled:h,onClick:()=>{var j;return(j=p.current)==null?void 0:j.click()},children:e.jsx(jy,{className:"h-4 w-4"})}),e.jsx(e0,{title:"Upload video",disabled:h,onClick:()=>{var j;return(j=f.current)==null?void 0:j.click()},children:e.jsx(Kr,{className:"h-4 w-4"})}),e.jsx(e0,{title:"Embed YouTube / Vimeo",onClick:()=>{u(""),c(!0)},children:e.jsx(f$,{className:"h-4 w-4"})}),e.jsx(e0,{title:"Divider",onClick:()=>b.chain().focus().setHorizontalRule().run(),children:e.jsx(uN,{className:"h-4 w-4"})}),e.jsx("div",{className:"mx-1 h-5 w-px bg-border"}),e.jsx(e0,{title:"Undo",onClick:()=>b.chain().focus().undo().run(),children:e.jsx(JA,{className:"h-4 w-4"})}),e.jsx(e0,{title:"Redo",onClick:()=>b.chain().focus().redo().run(),children:e.jsx(XA,{className:"h-4 w-4"})}),h&&e.jsxs("span",{className:"ml-2 flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(Ct,{className:"h-3.5 w-3.5 animate-spin"})," Uploading…"]})]}),e.jsx(CLe,{editor:y,"data-placeholder":n}),e.jsx("input",{ref:p,type:"file",accept:"image/*",className:"hidden",onChange:j=>{var S;g((S=j.target.files)==null?void 0:S[0],"image"),j.target.value=""}}),e.jsx("input",{ref:f,type:"file",accept:"video/*",className:"hidden",onChange:j=>{var S;g((S=j.target.files)==null?void 0:S[0],"video"),j.target.value=""}}),e.jsx(Ls,{open:r,onOpenChange:a,children:e.jsxs(Ps,{children:[e.jsx(Os,{children:e.jsx(Ds,{children:"Insert link"})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"URL"}),e.jsx(xe,{value:i,onChange:j=>l(j.target.value),placeholder:"https://…"})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>{b.chain().focus().unsetLink().run(),a(!1)},children:"Remove link"}),e.jsx(B,{onClick:()=>{i.trim()&&b.chain().focus().extendMarkRange("link").setLink({href:i.trim(),target:"_blank"}).run(),a(!1)},children:"Apply"})]})]})}),e.jsx(Ls,{open:o,onOpenChange:c,children:e.jsxs(Ps,{children:[e.jsx(Os,{children:e.jsx(Ds,{children:"Embed a video"})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"YouTube or Vimeo URL"}),e.jsx(xe,{value:d,onChange:j=>u(j.target.value),placeholder:"https://youtube.com/watch?v=…"})]}),e.jsx(yr,{children:e.jsx(B,{onClick:()=>{const j=d.trim();if(j){if(/vimeo\.com/i.test(j)){const S=j.split("/").filter(Boolean).pop();b.chain().focus().insertContent(`
`).run()}else b.commands.setYoutubeVideo({src:j});c(!1)}},children:"Embed"})})]})})]})}const Hde=s=>s.toLowerCase().trim().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").slice(0,80),kor=()=>({title:"",slug:"",excerpt:"",content:"",cover_image_url:null,category:"",tags:[],author_name:"Jeremy Collins",author_title:"Founder, LevelUp",status:"draft",featured:!1,allow_comments:!0});function Sor(){const{user:s}=hs(),[t,n]=_.useState([]),[r,a]=_.useState(!0),[i,l]=_.useState(null),[o,c]=_.useState(!1),[d,u]=_.useState(""),[h,m]=_.useState(""),[p,f]=_.useState(!1),y=_.useRef(null),[v,g]=_.useState([]),b=async()=>{a(!0);const{data:O,error:V}=await q.from("blog_posts").select("*").order("created_at",{ascending:!1});V&&se.error(V.message),n(O||[]),a(!1)},j=async()=>{const{data:O}=await q.from("blog_comments").select("id, body, created_at, is_hidden, user_id, post_id").order("created_at",{ascending:!1}).limit(200),V=O||[],G=[...new Set(V.map(ce=>ce.user_id))],$=[...new Set(V.map(ce=>ce.post_id))],[{data:H},{data:Y}]=await Promise.all([G.length?q.from("profiles").select("id, name, email").in("id",G):Promise.resolve({data:[]}),$.length?q.from("blog_posts").select("id, title, slug").in("id",$):Promise.resolve({data:[]})]),Z=new Map((H||[]).map(ce=>[ce.id,ce])),ne=new Map((Y||[]).map(ce=>[ce.id,ce]));g(V.map(ce=>({...ce,author:Z.get(ce.user_id),post:ne.get(ce.post_id)})))};_.useEffect(()=>{b(),j()},[]);const S=_.useMemo(()=>t.filter(O=>O.title.toLowerCase().includes(d.toLowerCase())),[t,d]),C=async O=>{if(!O||!s)return;f(!0);const V=O.name.split(".").pop()||"jpg",G=`${s.id}/blog/cover-${Date.now()}.${V}`,{error:$}=await q.storage.from("email-assets").upload(G,O);if(f(!1),$){se.error($.message);return}const H=q.storage.from("email-assets").getPublicUrl(G).data.publicUrl;l(Y=>({...Y||{},cover_image_url:H}))},E=async O=>{if(!i)return;const V=(i.title||"").trim();if(!V){se.error("Give the article a title");return}const G=Hde(i.slug||V),$=O===void 0?i.status||"draft":O?"published":"draft";c(!0);const H={title:V,slug:G,excerpt:i.excerpt||null,content:i.content||"",cover_image_url:i.cover_image_url||null,category:i.category||null,tags:i.tags||[],author_name:i.author_name||"Jeremy Collins",author_title:i.author_title||"Founder, LevelUp",author_avatar_url:i.author_avatar_url||null,status:$,featured:!!i.featured,allow_comments:i.allow_comments!==!1,seo_title:i.seo_title||null,seo_description:i.seo_description||null,published_at:$==="published"?i.published_at||new Date().toISOString():i.published_at||null};let Y;if(i.id)({error:Y}=await q.from("blog_posts").update(H).eq("id",i.id));else{H.created_by=(s==null?void 0:s.id)||null;const Z=await q.from("blog_posts").insert(H).select().single();Y=Z.error,Z.data&&l(Z.data)}if(c(!1),Y){se.error(Y.message);return}se.success($==="published"?"Published":"Saved"),b()},P=async O=>{if(!confirm("Delete this article and its comments?"))return;const{error:V}=await q.from("blog_posts").delete().eq("id",O);if(V){se.error(V.message);return}se.success("Deleted"),(i==null?void 0:i.id)===O&&l(null),b()},M=async O=>{const V=O.status==="published"?"draft":"published",{error:G}=await q.from("blog_posts").update({status:V,published_at:V==="published"?O.published_at||new Date().toISOString():O.published_at}).eq("id",O.id);if(G){se.error(G.message);return}b()},I=async O=>{const{error:V}=await q.from("blog_comments").update({is_hidden:!O.is_hidden}).eq("id",O.id);if(V){se.error(V.message);return}j()},D=async O=>{const{error:V}=await q.from("blog_comments").delete().eq("id",O);if(V){se.error(V.message);return}j()};return i?e.jsxs("div",{className:"container mx-auto max-w-6xl space-y-6 p-4 md:p-6",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs(B,{variant:"ghost",onClick:()=>l(null),children:[e.jsx(ka,{className:"mr-2 h-4 w-4"})," Back to articles"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[i.slug&&i.status==="published"&&e.jsx(B,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:`/blog/${i.slug}`,target:"_blank",rel:"noreferrer",children:[e.jsx(wr,{className:"mr-2 h-4 w-4"})," View live"]})}),e.jsxs(B,{variant:"outline",disabled:o,onClick:()=>E(!1),children:[o&&e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"})," Save draft"]}),e.jsxs(B,{disabled:o,onClick:()=>E(!0),children:[o&&e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"})," Publish"]})]})]}),e.jsxs("div",{className:"grid gap-6 lg:grid-cols-[minmax(0,1fr)_320px]",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx(xe,{value:i.title||"",onChange:O=>l({...i,title:O.target.value}),placeholder:"Article title",className:"h-14 border-0 bg-transparent px-0 text-3xl font-bold shadow-none focus-visible:ring-0"}),e.jsx(Ms,{value:i.excerpt||"",onChange:O=>l({...i,excerpt:O.target.value}),placeholder:"Short excerpt shown on the blog index and social previews…",rows:2}),e.jsx(Nor,{content:i.content||"",onChange:O=>l(V=>({...V||{},content:O}))})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(ve,{children:e.jsxs(Me,{className:"space-y-4 pt-6",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Cover image"}),i.cover_image_url?e.jsxs("div",{className:"mt-2 space-y-2",children:[e.jsx("img",{src:i.cover_image_url,alt:"cover",className:"h-36 w-full rounded-lg object-cover"}),e.jsx(B,{variant:"outline",size:"sm",className:"w-full",onClick:()=>l({...i,cover_image_url:null}),children:"Remove"})]}):e.jsxs(B,{variant:"outline",className:"mt-2 w-full",disabled:p,onClick:()=>{var O;return(O=y.current)==null?void 0:O.click()},children:[p?e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(jy,{className:"mr-2 h-4 w-4"}),"Upload cover"]}),e.jsx("input",{ref:y,type:"file",accept:"image/*",className:"hidden",onChange:O=>{var V;C((V=O.target.files)==null?void 0:V[0]),O.target.value=""}})]}),e.jsxs("div",{children:[e.jsx(J,{children:"URL slug"}),e.jsx(xe,{className:"mt-1",value:i.slug||"",onChange:O=>l({...i,slug:O.target.value}),onBlur:O=>l({...i,slug:Hde(O.target.value||i.title||"")}),placeholder:Hde(i.title||"")||"my-article"}),e.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["/blog/",i.slug||Hde(i.title||"")||"…"]})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Category"}),e.jsx(xe,{className:"mt-1",value:i.category||"",onChange:O=>l({...i,category:O.target.value}),placeholder:"e.g. Lead Generation"})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Tags"}),e.jsx("div",{className:"mt-1 flex gap-2",children:e.jsx(xe,{value:h,onChange:O=>m(O.target.value),placeholder:"Add a tag and press Enter",onKeyDown:O=>{O.key==="Enter"&&h.trim()&&(O.preventDefault(),l({...i,tags:[...i.tags||[],h.trim()]}),m(""))}})}),(i.tags||[]).length>0&&e.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:(i.tags||[]).map((O,V)=>e.jsxs(Oe,{variant:"secondary",className:"cursor-pointer",onClick:()=>l({...i,tags:(i.tags||[]).filter((G,$)=>$!==V)}),children:[O," ×"]},`${O}-${V}`))})]}),e.jsx(wc,{}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(J,{htmlFor:"featured",children:"Featured article"}),e.jsx(fn,{id:"featured",checked:!!i.featured,onCheckedChange:O=>l({...i,featured:O})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(J,{htmlFor:"comments",children:"Allow comments"}),e.jsx(fn,{id:"comments",checked:i.allow_comments!==!1,onCheckedChange:O=>l({...i,allow_comments:O})})]})]})}),e.jsx(ve,{children:e.jsxs(Me,{className:"space-y-4 pt-6",children:[e.jsx("div",{className:"text-sm font-semibold",children:"Author"}),e.jsx(xe,{value:i.author_name||"",placeholder:"Author name",onChange:O=>l({...i,author_name:O.target.value})}),e.jsx(xe,{value:i.author_title||"",placeholder:"Author title",onChange:O=>l({...i,author_title:O.target.value})}),e.jsx(xe,{value:i.author_avatar_url||"",placeholder:"Author photo URL (optional)",onChange:O=>l({...i,author_avatar_url:O.target.value})})]})}),e.jsx(ve,{children:e.jsxs(Me,{className:"space-y-4 pt-6",children:[e.jsx("div",{className:"text-sm font-semibold",children:"SEO"}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"SEO title"}),e.jsx(xe,{className:"mt-1",maxLength:60,value:i.seo_title||"",onChange:O=>l({...i,seo_title:O.target.value})})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Meta description"}),e.jsx(Ms,{className:"mt-1",maxLength:160,rows:3,value:i.seo_description||"",onChange:O=>l({...i,seo_description:O.target.value})})]})]})})]})]})]}):e.jsxs("div",{className:"container mx-auto max-w-6xl space-y-6 p-4 md:p-6",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Blog"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Founder articles published publicly at ",e.jsx("a",{className:"underline",href:"/blog",target:"_blank",rel:"noreferrer",children:"/blog"})]})]}),e.jsxs(B,{onClick:()=>l(kor()),children:[e.jsx(rn,{className:"mr-2 h-4 w-4"})," New article"]})]}),e.jsxs(Yr,{defaultValue:"articles",children:[e.jsxs(Zr,{children:[e.jsxs(Ht,{value:"articles",children:["Articles (",t.length,")"]}),e.jsxs(Ht,{value:"comments",children:["Comments (",v.length,")"]})]}),e.jsxs(Gt,{value:"articles",className:"mt-4 space-y-3",children:[e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(Lr,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(xe,{className:"pl-9",value:d,onChange:O=>u(O.target.value),placeholder:"Search articles…"})]}),r?e.jsxs("div",{className:"flex items-center gap-2 py-10 text-sm text-muted-foreground",children:[e.jsx(Ct,{className:"h-4 w-4 animate-spin"})," Loading…"]}):S.length===0?e.jsx(ve,{children:e.jsx(Me,{className:"py-12 text-center text-sm text-muted-foreground",children:"No articles yet. Write your first one."})}):S.map(O=>e.jsx(ve,{className:"transition hover:border-primary/30",children:e.jsxs(Me,{className:"flex flex-wrap items-center gap-4 py-4",children:[O.cover_image_url?e.jsx("img",{src:O.cover_image_url,alt:"",className:"h-14 w-20 rounded-md object-cover"}):e.jsx("div",{className:"h-14 w-20 rounded-md bg-muted"}),e.jsxs("button",{className:"min-w-0 flex-1 text-left",onClick:()=>l(O),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"truncate font-semibold",children:O.title}),O.featured&&e.jsx(Da,{className:"h-3.5 w-3.5 fill-amber-400 text-amber-400"})]}),e.jsxs("div",{className:"mt-0.5 flex flex-wrap items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(Oe,{variant:O.status==="published"?"default":"secondary",children:O.status}),O.category&&e.jsx("span",{children:O.category}),e.jsxs("span",{children:[O.view_count," views"]}),e.jsxs("span",{children:["/blog/",O.slug]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(B,{variant:"ghost",size:"sm",title:"Toggle publish",onClick:()=>M(O),children:O.status==="published"?e.jsx(Ax,{className:"h-4 w-4"}):e.jsx(ya,{className:"h-4 w-4"})}),O.status==="published"&&e.jsx(B,{variant:"ghost",size:"sm",asChild:!0,children:e.jsx("a",{href:`/blog/${O.slug}`,target:"_blank",rel:"noreferrer",children:e.jsx(wr,{className:"h-4 w-4"})})}),e.jsx(B,{variant:"ghost",size:"sm",className:"text-destructive",onClick:()=>P(O.id),children:e.jsx(Sn,{className:"h-4 w-4"})})]})]})},O.id))]}),e.jsx(Gt,{value:"comments",className:"mt-4 space-y-3",children:v.length===0?e.jsx(ve,{children:e.jsx(Me,{className:"py-12 text-center text-sm text-muted-foreground",children:"No comments yet."})}):v.map(O=>{var V,G,$;return e.jsx(ve,{children:e.jsxs(Me,{className:"flex flex-wrap items-start gap-4 py-4",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"text-sm font-semibold",children:[((V=O.author)==null?void 0:V.name)||((G=O.author)==null?void 0:G.email)||"Member",e.jsxs("span",{className:"ml-2 font-normal text-muted-foreground",children:["on “",(($=O.post)==null?void 0:$.title)||"article","”"]})]}),e.jsx("p",{className:"mt-1 whitespace-pre-wrap text-sm text-muted-foreground",children:O.body})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[O.is_hidden&&e.jsx(Oe,{variant:"secondary",children:"hidden"}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>I(O),children:O.is_hidden?e.jsx(ya,{className:"h-4 w-4"}):e.jsx(Ax,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"sm",className:"text-destructive",onClick:()=>D(O.id),children:e.jsx(Sn,{className:"h-4 w-4"})})]})]})},O.id)})})]})]})}const Cor=["What was it like working together?","What moment stood out the most?","Would you recommend me to a friend?"];function Aor(s){return new Promise((t,n)=>{const r=new FileReader;r.onload=()=>t(String(r.result)),r.onerror=n,r.readAsDataURL(s)})}function Eor(){var E,P,M,I,D,O,V;const{token:s}=Li(),[t,n]=_.useState(null),[r,a]=_.useState(!0),[i,l]=_.useState("none"),[o,c]=_.useState(""),[d,u]=_.useState(5),[h,m]=_.useState(""),[p,f]=_.useState(!1),[y,v]=_.useState(!1),[g,b]=_.useState(null);_.useEffect(()=>{(async()=>{const{data:G}=await q.rpc("get_review_request_by_token",{_token:s}),$=G;n($),$!=null&&$.recipient_name&&c($.recipient_name),a(!1)})()},[s]);const j=_.useCallback(()=>{q.functions.invoke("review-public",{body:{action:"clicked",token:s}}).catch(()=>{}),t!=null&&t.google_review_link&&window.open(t.google_review_link,"_blank","noopener")},[s,t]),S=_.useCallback(async G=>{f(!0),b(null);try{const $={action:"submit",token:s,reviewer_name:o,rating:d,review_text:h||void 0};G&&($.video_base64=await Aor(G),$.video_type=G.type||"video/webm");const{data:H,error:Y}=await q.functions.invoke("review-public",{body:$});if(Y||H!=null&&H.error)throw new Error((H==null?void 0:H.error)||(Y==null?void 0:Y.message)||"Something went wrong");v(!0)}catch($){b($.message)}finally{f(!1)}},[s,o,d,h]);if(r)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-[#f7f5f1]",children:e.jsx(Ct,{className:"h-8 w-8 animate-spin text-[#406E71]"})});if(!t)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-[#f7f5f1] p-6",children:e.jsx("p",{className:"text-slate-600 text-center",children:"This review link is invalid or has expired."})});const C=((E=t.agent)==null?void 0:E.name)||"Your agent";return y?e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-[#f7f5f1] p-6",children:e.jsxs("div",{className:"text-center max-w-md",children:[e.jsx(Er,{className:"h-16 w-16 text-[#406E71] mx-auto mb-4"}),e.jsx("h1",{className:"text-3xl font-serif text-[#2a4c64] mb-2",children:"Thank you!"}),e.jsxs("p",{className:"text-slate-600",children:["Your review means the world to ",((M=(P=t.agent)==null?void 0:P.name)==null?void 0:M.split(" ")[0])||"us",". We appreciate you taking the time."]})]})}):e.jsx("div",{className:"min-h-screen bg-[#f7f5f1] py-10 px-4",children:e.jsxs("div",{className:"max-w-lg mx-auto",children:[e.jsxs("div",{className:"text-center mb-8",children:[((I=t.agent)==null?void 0:I.avatar_url)&&e.jsx("img",{src:t.agent.avatar_url,alt:C,className:"w-20 h-20 rounded-full object-cover mx-auto mb-4 border-4 border-white shadow-lg"}),e.jsx("h1",{className:"text-3xl font-serif text-[#2a4c64]",children:C}),((D=t.agent)==null?void 0:D.title)&&e.jsx("p",{className:"text-slate-500 text-sm mt-1",children:t.agent.title}),e.jsx("p",{className:"text-slate-600 mt-4",children:"Thank you for your trust. How would you like to share your experience?"})]}),e.jsx("div",{className:"flex justify-center gap-1 mb-8",children:[1,2,3,4,5].map(G=>e.jsx("button",{onClick:()=>u(G),"aria-label":`${G} stars`,children:e.jsx(Da,{className:At("h-8 w-8 transition-colors",G<=d?"fill-[#c9a24b] text-[#c9a24b]":"text-slate-300")})},G))}),i==="none"&&e.jsxs("div",{className:"grid gap-4",children:[t.google_review_link&&e.jsx("button",{onClick:j,className:"bg-white rounded-2xl p-6 shadow-sm border border-slate-200 hover:shadow-md hover:border-[#406E71] transition-all text-left group",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-[#406E71]/10 flex items-center justify-center group-hover:bg-[#406E71]/20 transition-colors",children:e.jsx(Da,{className:"h-6 w-6 text-[#406E71]"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-[#2a4c64]",children:"Leave a Google review"}),e.jsxs("p",{className:"text-sm text-slate-500",children:["Takes 30 seconds — helps others find ",(V=(O=t.agent)==null?void 0:O.name)==null?void 0:V.split(" ")[0]]})]})]})}),e.jsx("button",{onClick:()=>l("video"),className:"bg-white rounded-2xl p-6 shadow-sm border border-slate-200 hover:shadow-md hover:border-[#406E71] transition-all text-left group",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-[#c9a24b]/10 flex items-center justify-center group-hover:bg-[#c9a24b]/20 transition-colors",children:e.jsx(Kr,{className:"h-6 w-6 text-[#c9a24b]"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-[#2a4c64]",children:"Record a quick video"}),e.jsx("p",{className:"text-sm text-slate-500",children:"60 seconds, right from your phone"})]})]})}),e.jsx("button",{onClick:()=>l("write"),className:"bg-white rounded-2xl p-6 shadow-sm border border-slate-200 hover:shadow-md hover:border-[#406E71] transition-all text-left group",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-slate-100 flex items-center justify-center group-hover:bg-slate-200 transition-colors",children:e.jsx(Qm,{className:"h-6 w-6 text-slate-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-[#2a4c64]",children:"Write a note"}),e.jsx("p",{className:"text-sm text-slate-500",children:"A few kind words go a long way"})]})]})})]}),i!=="none"&&e.jsxs("div",{className:"bg-white rounded-2xl p-6 shadow-sm border border-slate-200 space-y-5",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-slate-700",children:"Your name"}),e.jsx(xe,{value:o,onChange:G=>c(G.target.value),placeholder:"Jane Smith",className:"mt-1"})]}),i==="write"&&e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-slate-700",children:"Your review"}),e.jsx(Ms,{value:h,onChange:G=>m(G.target.value),rows:5,placeholder:"Share a few words about your experience...",className:"mt-1"})]}),i==="video"&&e.jsxs("div",{children:[e.jsxs("div",{className:"bg-[#2a4c64]/5 rounded-xl p-4 mb-4",children:[e.jsx("p",{className:"text-xs font-semibold text-[#2a4c64] uppercase tracking-wide mb-2",children:"Not sure what to say? Try these:"}),e.jsx("ul",{className:"text-sm text-slate-600 space-y-1",children:Cor.map(G=>e.jsxs("li",{children:["• ",G]},G))})]}),e.jsx($E,{maxDurationSeconds:60,onRecordingComplete:G=>S(G),onError:G=>b(G)})]}),g&&e.jsx("p",{className:"text-sm text-red-600",children:g}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx(B,{variant:"ghost",onClick:()=>l("none"),disabled:p,children:"Back"}),i==="write"&&e.jsxs(B,{onClick:()=>S(),disabled:p||!o.trim()||!h.trim(),className:"bg-[#406E71] hover:bg-[#355e61] text-white flex-1",children:[p?e.jsx(Ct,{className:"h-4 w-4 animate-spin mr-2"}):null,"Send review"]})]}),i==="video"&&p&&e.jsxs("p",{className:"text-sm text-slate-500 flex items-center gap-2",children:[e.jsx(Ct,{className:"h-4 w-4 animate-spin"})," Uploading your video…"]})]})]})})}function Gde({rating:s,size:t="h-4 w-4"}){return e.jsx("div",{className:"flex gap-0.5",children:[1,2,3,4,5].map(n=>e.jsx(Da,{className:At(t,n<=s?"fill-[#c9a24b] text-[#c9a24b]":"text-slate-300")},n))})}function Tor(){var d,u;const{slug:s}=Li(),[t,n]=_.useState(null),[r,a]=_.useState(!0);_.useEffect(()=>{(async()=>{const{data:h}=await q.rpc("get_public_reviews_page",{_slug:s});n(h),a(!1)})()},[s]);const i=_.useMemo(()=>{var h;return((h=t==null?void 0:t.agent)==null?void 0:h.name)??""},[t]);if(_.useEffect(()=>{var m;if(!t)return;document.title=`Reviews for ${i}`;const h=document.createElement("script");return h.type="application/ld+json",h.text=JSON.stringify({"@context":"https://schema.org","@type":"RealEstateAgent",name:i,image:(m=t.agent)==null?void 0:m.avatar_url,aggregateRating:t.stats.total_reviews>0?{"@type":"AggregateRating",ratingValue:t.stats.avg_rating,reviewCount:t.stats.total_reviews}:void 0}),document.head.appendChild(h),()=>{document.head.removeChild(h)}},[t,i]),r)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-[#f7f5f1]",children:e.jsx(Ct,{className:"h-8 w-8 animate-spin text-[#406E71]"})});if(!t)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-[#f7f5f1] p-6",children:e.jsx("p",{className:"text-slate-600",children:"This reviews page isn't available."})});const l=t.reviews.filter(h=>h.source==="video"&&h.video_url),o=t.reviews.filter(h=>h.source==="google"),c=t.reviews.filter(h=>h.source==="video"&&!h.video_url);return e.jsxs("div",{className:"min-h-screen bg-[#f7f5f1]",children:[e.jsxs("header",{className:"bg-[#2a4c64] text-white py-16 px-6 text-center",children:[((d=t.agent)==null?void 0:d.avatar_url)&&e.jsx("img",{src:t.agent.avatar_url,alt:i,className:"w-24 h-24 rounded-full object-cover mx-auto mb-5 border-4 border-[#c9a24b]/60 shadow-xl"}),e.jsx("h1",{className:"text-4xl font-serif",children:i}),((u=t.agent)==null?void 0:u.title)&&e.jsx("p",{className:"text-white/70 mt-1",children:t.agent.title}),e.jsxs("div",{className:"flex items-center justify-center gap-3 mt-5",children:[e.jsx(Gde,{rating:Math.round(t.stats.avg_rating),size:"h-6 w-6"}),e.jsx("span",{className:"text-2xl font-semibold",children:t.stats.avg_rating}),e.jsxs("span",{className:"text-white/60",children:["· ",t.stats.total_reviews," review",t.stats.total_reviews!==1?"s":""]})]}),t.settings.intro_text&&e.jsx("p",{className:"max-w-xl mx-auto mt-5 text-white/80 leading-relaxed",children:t.settings.intro_text})]}),e.jsxs("main",{className:"max-w-4xl mx-auto px-4 py-12 space-y-14",children:[l.length>0&&e.jsxs("section",{children:[e.jsxs("h2",{className:"text-2xl font-serif text-[#2a4c64] mb-6 flex items-center gap-2",children:[e.jsx(Kr,{className:"h-6 w-6 text-[#c9a24b]"})," Video testimonials"]}),e.jsx("div",{className:"grid sm:grid-cols-2 gap-6",children:l.map(h=>e.jsxs("figure",{className:"bg-white rounded-2xl overflow-hidden shadow-sm border border-slate-200",children:[e.jsx("video",{src:h.video_url,controls:!0,playsInline:!0,preload:"metadata",className:"w-full aspect-video bg-black"}),e.jsxs("figcaption",{className:"p-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"font-medium text-[#2a4c64]",children:h.reviewer_name}),h.rating&&e.jsx(Gde,{rating:h.rating})]}),h.review_text&&e.jsx("p",{className:"text-sm text-slate-600 mt-2",children:h.review_text})]})]},h.id))})]}),o.length>0&&e.jsxs("section",{children:[e.jsx("h2",{className:"text-2xl font-serif text-[#2a4c64] mb-6",children:"Google reviews"}),e.jsx("div",{className:"grid sm:grid-cols-2 gap-6",children:o.map(h=>{var m,p;return e.jsxs("blockquote",{className:"bg-white rounded-2xl p-6 shadow-sm border border-slate-200 flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[h.rating&&e.jsx(Gde,{rating:h.rating}),e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-[#406E71] bg-[#406E71]/10 px-2 py-1 rounded-full",children:[e.jsx(K3,{className:"h-3.5 w-3.5"})," Verified Google review"]})]}),h.review_text&&e.jsxs("p",{className:"text-slate-700 leading-relaxed flex-1",children:['"',h.review_text,'"']}),e.jsxs("footer",{className:"mt-4 text-sm font-medium text-[#2a4c64]",children:["— ",h.reviewer_name]}),h.reply_text&&e.jsxs("div",{className:"mt-4 pl-4 border-l-2 border-[#c9a24b]/50 bg-[#f7f5f1] rounded-r-lg p-3",children:[e.jsxs("p",{className:"text-xs font-semibold text-[#2a4c64] flex items-center gap-1 mb-1",children:[e.jsx(HQ,{className:"h-3.5 w-3.5"})," Response from ",(p=(m=t.agent)==null?void 0:m.name)==null?void 0:p.split(" ")[0]]}),e.jsx("p",{className:"text-sm text-slate-600",children:h.reply_text})]})]},h.id)})})]}),c.length>0&&e.jsxs("section",{children:[e.jsx("h2",{className:"text-2xl font-serif text-[#2a4c64] mb-6",children:"Kind words"}),e.jsx("div",{className:"grid sm:grid-cols-2 gap-6",children:c.map(h=>e.jsxs("blockquote",{className:"bg-white rounded-2xl p-6 shadow-sm border border-slate-200",children:[h.rating&&e.jsx(Gde,{rating:h.rating}),h.review_text&&e.jsxs("p",{className:"text-slate-700 leading-relaxed mt-3",children:['"',h.review_text,'"']}),e.jsxs("footer",{className:"mt-4 text-sm font-medium text-[#2a4c64]",children:["— ",h.reviewer_name]})]},h.id))})]})]})]})}function uCt({rating:s,size:t="h-4 w-4"}){return e.jsx("div",{className:"flex gap-0.5",children:[1,2,3,4,5].map(n=>e.jsx(Da,{className:At(t,n<=s?"fill-[#c9a24b] text-[#c9a24b]":"text-slate-300")},n))})}function hCt(s){return s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,"")}function Mor(){var Fe;const{user:s,isAdmin:t,rolesLoading:n}=hs(),[r,a]=_.useState([]),[i,l]=_.useState([]),[o,c]=_.useState(!0),[d,u]=_.useState({slug:"",intro_text:"",is_published:!1,show_google_reviews:!0,show_video_reviews:!0}),[h,m]=_.useState(!1),[p,f]=_.useState(!1),[y,v]=_.useState(""),[g,b]=_.useState("email"),[j,S]=_.useState(""),[C,E]=_.useState(!1),[P,M]=_.useState(null),[I,D]=_.useState(""),[O,V]=_.useState(!1),[G,$]=_.useState(!1),[H,Y]=_.useState(!1),[Z,ne]=_.useState(null),ce=Z?Z.connected:null,[ie,te]=Yl(),ae=_.useRef(!1),le=_.useCallback(async()=>{const{data:Ne,error:Ye}=await q.functions.invoke("google-business-oauth",{body:{action:"get_status"}});if(Ye||Ne!=null&&Ne.error){ne({connected:!1,email:null,apiAccessPending:!1,hasRefreshToken:!1,connectedAt:null,locations:[]});return}ne(Ne)},[]),be=_.useCallback(async()=>{if(!s)return;c(!0);const[{data:Ne},{data:Ye},{data:Ve}]=await Promise.all([q.from("review_responses").select("*").eq("user_id",s.id).order("is_pinned",{ascending:!1}).order("created_at",{ascending:!1}),q.from("review_requests").select("*").eq("user_id",s.id).order("created_at",{ascending:!1}).limit(100),q.from("agent_review_page_settings").select("*").eq("user_id",s.id).maybeSingle()]);if(a(Ne??[]),l(Ye??[]),le(),Ve)u({id:Ve.id,slug:Ve.slug??"",intro_text:Ve.intro_text??"",is_published:Ve.is_published,show_google_reviews:Ve.show_google_reviews,show_video_reviews:Ve.show_video_reviews});else{const{data:qe}=await q.from("profiles").select("name").eq("id",s.id).single(),Qe=hCt((qe==null?void 0:qe.name)??"");u(Ue=>({...Ue,slug:Ue.slug||Qe}))}c(!1)},[s,le]);_.useEffect(()=>{be()},[be]),_.useEffect(()=>{if(ae.current)return;const Ne=ie.get("google"),Ye=ie.get("google_error");if(!Ne&&!Ye)return;if(ae.current=!0,Ye)se.error(Ye==="access_denied"?"Google connection was cancelled":Ye==="invalid_state"?"That connection link expired — please try again":Ye==="not_configured"?"Google Business credentials are not configured yet":`Google connection failed: ${Ye}`);else{const qe=Number(ie.get("locations")??0);se.success(ie.get("google_pending")?"Google connected — review access is still pending Google approval":`Google Business Profile connected${qe?` (${qe} location${qe>1?"s":""})`:""}`)}const Ve=new URLSearchParams(ie);["google","google_error","google_pending","locations"].forEach(qe=>Ve.delete(qe)),te(Ve,{replace:!0}),le()},[ie,te,le]);const me=async()=>{Y(!0);const{data:Ne,error:Ye}=await q.functions.invoke("google-business-oauth",{body:{action:"get_auth_url",returnPath:"/apps/reviews"}});if(Ye||Ne!=null&&Ne.error||!(Ne!=null&&Ne.authUrl))return Y(!1),se.error((Ne==null?void 0:Ne.error)||(Ye==null?void 0:Ye.message)||"Could not start Google connection");window.location.href=Ne.authUrl},he=async()=>{const{error:Ne}=await q.functions.invoke("google-business-oauth",{body:{action:"disconnect"}});if(Ne)return se.error("Could not disconnect");se.success("Google Business Profile disconnected"),le()},pe=_.useMemo(()=>{const Ne=r.filter(Xe=>Xe.status!=="hidden"),Ye=Ne.filter(Xe=>Xe.rating),Ve=Ye.length?Ye.reduce((Xe,nt)=>Xe+(nt.rating??0),0)/Ye.length:0,qe=i.filter(Xe=>["sent","reminded","clicked"].includes(Xe.status)).length,Qe=i.filter(Xe=>Xe.status==="completed").length,Ue=i.length?Math.round(Qe/i.length*100):0;return{avg:Math.round(Ve*10)/10,total:Ne.length,pending:qe,responseRate:Ue,newCount:r.filter(Xe=>Xe.status==="new").length}},[r,i]),Ce=async(Ne,Ye)=>{const{error:Ve}=await q.from("review_responses").update({status:Ye}).eq("id",Ne);if(Ve)return se.error(Ve.message);a(qe=>qe.map(Qe=>Qe.id===Ne?{...Qe,status:Ye}:Qe))},Ae=async Ne=>{const{error:Ye}=await q.from("review_responses").update({is_pinned:!Ne.is_pinned}).eq("id",Ne.id);if(Ye)return se.error(Ye.message);a(Ve=>Ve.map(qe=>qe.id===Ne.id?{...qe,is_pinned:!Ne.is_pinned}:qe))},Pe=async()=>{if(!s)return;if(!d.slug)return se.error("Choose a slug for your page");m(!0);const Ne={user_id:s.id,slug:hCt(d.slug),intro_text:d.intro_text||null,is_published:d.is_published,show_google_reviews:d.show_google_reviews,show_video_reviews:d.show_video_reviews},{error:Ye}=d.id?await q.from("agent_review_page_settings").update(Ne).eq("id",d.id):await q.from("agent_review_page_settings").insert(Ne);if(m(!1),Ye)return se.error(Ye.message.includes("unique")?"That slug is taken — try another":Ye.message);se.success(d.is_published?"Your reviews page is live":"Settings saved"),be()},ze=async()=>{const Ye=y.split(` `).map(Ue=>Ue.trim()).filter(Boolean).map(Ue=>{const[Xe,nt,$e]=Ue.split(",").map(Ge=>Ge.trim());return{name:Xe,email:nt,phone:$e}}).filter(Ue=>Ue.email||Ue.phone);if(Ye.length===0)return se.error("Add at least one recipient (Name, email, phone — one per line)");E(!0);const{data:Ve,error:qe}=await q.functions.invoke("review-request-send",{body:{recipients:Ye,channel:g,message:j||void 0}});if(E(!1),qe||Ve!=null&&Ve.error)return se.error((Ve==null?void 0:Ve.error)||(qe==null?void 0:qe.message)||"Send failed");const Qe=(Ve.results??[]).filter(Ue=>Ue.ok).length;se.success(`${Qe} review request${Qe!==1?"s":""} sent`),f(!1),v(""),be()},ke=async()=>{if(!(!P||!I.trim())){if(V(!0),P.source==="google"){const{data:Ne,error:Ye}=await q.functions.invoke("google-reviews-sync",{body:{action:"reply",review_id:P.id,text:I.trim()}});if(Ye||Ne!=null&&Ne.error)return V(!1),se.error((Ne==null?void 0:Ne.error)||(Ye==null?void 0:Ye.message)||"Reply failed")}else{const{error:Ne}=await q.from("review_responses").update({reply_text:I.trim(),replied_at:new Date().toISOString()}).eq("id",P.id);if(Ne)return V(!1),se.error(Ne.message)}V(!1),se.success("Reply posted"),M(null),D(""),be()}},Ze=async()=>{$(!0);const{data:Ne,error:Ye}=await q.functions.invoke("google-reviews-sync",{body:{action:"sync_mine"}});if($(!1),Ye||Ne!=null&&Ne.error)return se.error((Ne==null?void 0:Ne.error)||(Ye==null?void 0:Ye.message)||"Sync failed");if(Ne!=null&&Ne.needsReconnect)return se.error("Your Google connection expired — click Connect Google to reconnect");se.success(`Synced ${(Ne==null?void 0:Ne.synced)??0} reviews`),be()};if(n)return e.jsx("div",{className:"min-h-screen flex items-center justify-center",children:e.jsx(Ct,{className:"h-8 w-8 animate-spin text-primary"})});if(!t)return e.jsx("div",{className:"min-h-screen flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center max-w-md",children:[e.jsx(un,{className:"h-12 w-12 text-[#c9a24b] mx-auto mb-4"}),e.jsx("h1",{className:"text-2xl font-serif text-foreground mb-2",children:"Reviews is coming soon"}),e.jsx("p",{className:"text-muted-foreground",children:"We're putting the finishing touches on this app. Stay tuned."})]})});const Se=d.slug?`${window.location.origin}/reviews/${d.slug}`:null;return e.jsx(zs,{title:"Reviews",children:e.jsxs("div",{className:"min-h-screen bg-background pb-20",children:[e.jsx("div",{className:"bg-[#2a4c64] text-white",children:e.jsxs("div",{className:"max-w-6xl mx-auto px-4 py-10",children:[e.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-6",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-white/60 text-sm uppercase tracking-widest mb-1",children:"Reputation"}),e.jsx("h1",{className:"text-4xl font-serif",children:"Reviews"}),e.jsxs("div",{className:"flex items-center gap-3 mt-4",children:[e.jsx("span",{className:"text-5xl font-bold tabular-nums",children:pe.avg||"—"}),e.jsxs("div",{children:[e.jsx(uCt,{rating:Math.round(pe.avg),size:"h-5 w-5"}),e.jsxs("p",{className:"text-white/60 text-sm mt-1",children:[pe.total," review",pe.total!==1?"s":""," collected"]})]})]})]}),e.jsxs("div",{className:"flex gap-3 items-center",children:[ce===!1?e.jsxs(B,{onClick:me,disabled:H,className:"bg-[#c9a24b] hover:bg-[#b8923f] text-[#2a4c64] font-semibold",children:[H?e.jsx(Ct,{className:"h-4 w-4 animate-spin mr-2"}):e.jsx(sl,{className:"h-4 w-4 mr-2"}),"Connect Google"]}):e.jsxs(B,{onClick:Ze,variant:"outline",className:"border-white/30 text-white hover:bg-white/10",disabled:G,children:[G?e.jsx(Ct,{className:"h-4 w-4 animate-spin mr-2"}):e.jsx(sl,{className:"h-4 w-4 mr-2"}),"Sync Google"]}),e.jsxs(B,{onClick:()=>f(!0),className:"bg-[#c9a24b] hover:bg-[#b8923f] text-[#2a4c64] font-semibold",children:[e.jsx(Or,{className:"h-4 w-4 mr-2"})," Request a Review"]}),e.jsx(FN,{children:e.jsxs(ag,{children:[e.jsx(ig,{asChild:!0,children:e.jsx(ir,{to:"/social-connections","aria-label":"All social connections",className:"p-2.5 rounded-xl border border-white/20 text-white/70 hover:text-white hover:bg-white/10 transition-colors",children:e.jsx(fS,{className:"h-5 w-5"})})}),e.jsx(Nx,{children:"All social connections"})]})})]})]}),Z&&e.jsx("div",{className:"mt-6 rounded-2xl border border-white/15 bg-white/5 backdrop-blur px-4 py-3 flex flex-wrap items-center gap-x-5 gap-y-2 text-sm",children:Z.connected?e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-2 text-emerald-300",children:[e.jsx(Er,{className:"h-4 w-4"}),"Google connected",Z.email?` — ${Z.email}`:""]}),Z.apiAccessPending?e.jsxs("span",{className:"flex items-center gap-2 text-amber-300",children:[e.jsx(xl,{className:"h-4 w-4"})," Review access pending Google approval"]}):e.jsxs("span",{className:"flex items-center gap-2 text-white/70",children:[e.jsx(Xa,{className:"h-4 w-4"}),Z.locations.length," location",Z.locations.length!==1?"s":"",(Fe=Z.locations[0])!=null&&Fe.last_synced_at?` · last synced ${new Date(Z.locations[0].last_synced_at).toLocaleString()}`:" · not synced yet"]}),!Z.hasRefreshToken&&e.jsxs("span",{className:"flex items-center gap-2 text-amber-300",children:[e.jsx(xl,{className:"h-4 w-4"})," Reconnect to enable automatic syncing"]}),e.jsxs("button",{onClick:he,className:"ml-auto flex items-center gap-1.5 text-white/60 hover:text-white transition-colors",children:[e.jsx(d$,{className:"h-4 w-4"})," Disconnect"]})]}):e.jsxs("span",{className:"flex items-center gap-2 text-white/70",children:[e.jsx(xl,{className:"h-4 w-4 text-[#c9a24b]"}),"Google Business Profile not connected — review requests and video reviews still work."]})}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 mt-8",children:[{label:"Total reviews",value:pe.total,icon:Da},{label:"Awaiting response",value:pe.newCount,icon:Hi},{label:"Pending requests",value:pe.pending,icon:In},{label:"Response rate",value:`${pe.responseRate}%`,icon:Nl}].map(Ne=>e.jsxs("div",{className:"bg-white/10 backdrop-blur rounded-xl p-4 border border-white/10",children:[e.jsx(Ne.icon,{className:"h-5 w-5 text-[#c9a24b] mb-2"}),e.jsx("p",{className:"text-2xl font-bold",children:Ne.value}),e.jsx("p",{className:"text-white/60 text-xs mt-1",children:Ne.label})]},Ne.label))})]})}),e.jsx("div",{className:"max-w-6xl mx-auto px-4 mt-8",children:e.jsxs(Yr,{defaultValue:"inbox",children:[e.jsxs(Zr,{children:[e.jsxs(Ht,{value:"inbox",children:["Inbox ",pe.newCount>0&&e.jsx(Oe,{className:"ml-2 bg-[#c9a24b] text-[#2a4c64]",children:pe.newCount})]}),e.jsx(Ht,{value:"requests",children:"Requests"}),e.jsx(Ht,{value:"page",children:"Public Page"})]}),e.jsxs(Gt,{value:"inbox",className:"mt-6",children:[ce===!1&&e.jsxs("div",{className:"bg-amber-50 border border-amber-200 rounded-xl p-4 mb-6 text-sm text-amber-800 flex flex-wrap items-center gap-3",children:[e.jsx("span",{className:"flex-1 min-w-[240px]",children:"Connect your Google Business Profile to pull in Google reviews and reply from here. (Reading reviews requires Google's API approval — until then, requests and video reviews work fully.)"}),e.jsxs(B,{size:"sm",onClick:me,disabled:H,className:"bg-[#406E71] hover:bg-[#355e61] text-white",children:[H?e.jsx(Ct,{className:"h-4 w-4 animate-spin mr-2"}):e.jsx(sl,{className:"h-4 w-4 mr-2"}),"Connect Google"]})]}),(Z==null?void 0:Z.connected)&&Z.apiAccessPending&&e.jsx("div",{className:"bg-amber-50 border border-amber-200 rounded-xl p-4 mb-6 text-sm text-amber-800",children:"Google is connected, but the Business Profile review APIs aren't approved for this app yet, so reviews can't be read or replied to. Requesting reviews and video testimonials work today."}),o?e.jsx("div",{className:"flex justify-center py-16",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin text-primary"})}):r.length===0?e.jsxs("div",{className:"text-center py-16 text-muted-foreground",children:[e.jsx(Da,{className:"h-10 w-10 mx-auto mb-3 text-[#c9a24b]"}),e.jsx("p",{children:"No reviews yet. Send your first request to get the stars rolling in."})]}):e.jsx("div",{className:"grid md:grid-cols-2 gap-5",children:r.map(Ne=>e.jsxs("div",{className:At("bg-card rounded-2xl border p-5 shadow-sm",Ne.status==="hidden"&&"opacity-50"),children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-full bg-[#406E71]/10 flex items-center justify-center",children:Ne.source==="google"?e.jsx(K3,{className:"h-5 w-5 text-[#406E71]"}):e.jsx(Kr,{className:"h-5 w-5 text-[#c9a24b]"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-foreground",children:Ne.reviewer_name||"Anonymous"}),Ne.rating&&e.jsx(uCt,{rating:Ne.rating})]})]}),e.jsx(Oe,{variant:"outline",className:"capitalize",children:Ne.source})]}),Ne.video_url&&e.jsx("video",{src:Ne.video_url,controls:!0,playsInline:!0,preload:"metadata",className:"w-full rounded-xl mt-4 aspect-video bg-black"}),Ne.review_text&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-3 leading-relaxed",children:['"',Ne.review_text,'"']}),Ne.reply_text&&e.jsxs("p",{className:"text-sm mt-3 pl-3 border-l-2 border-[#c9a24b]/60 text-muted-foreground",children:[e.jsx("span",{className:"font-medium text-foreground",children:"Your reply:"})," ",Ne.reply_text]}),e.jsxs("div",{className:"flex flex-wrap gap-2 mt-4",children:[Ne.status!=="approved"&&Ne.status!=="featured"&&e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>Ce(Ne.id,"approved"),children:[e.jsx(ya,{className:"h-3.5 w-3.5 mr-1"})," Approve"]}),Ne.status==="approved"&&e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>Ce(Ne.id,"featured"),children:[e.jsx(un,{className:"h-3.5 w-3.5 mr-1"})," Feature"]}),e.jsxs(B,{size:"sm",variant:"ghost",onClick:()=>Ae(Ne),children:[e.jsx(YA,{className:At("h-3.5 w-3.5 mr-1",Ne.is_pinned&&"fill-current")})," ",Ne.is_pinned?"Unpin":"Pin"]}),!Ne.reply_text&&e.jsxs(B,{size:"sm",variant:"ghost",onClick:()=>{M(Ne),D("")},children:[e.jsx(Qq,{className:"h-3.5 w-3.5 mr-1"})," Reply"]}),Ne.status!=="hidden"?e.jsxs(B,{size:"sm",variant:"ghost",className:"text-muted-foreground",onClick:()=>Ce(Ne.id,"hidden"),children:[e.jsx(Ax,{className:"h-3.5 w-3.5 mr-1"})," Hide"]}):e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>Ce(Ne.id,"new"),children:"Restore"})]})]},Ne.id))})]}),e.jsxs(Gt,{value:"requests",className:"mt-6",children:[e.jsxs("div",{className:"flex justify-between items-center mb-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Every request sends a branded email (and optional text) with a personal review link. A gentle reminder goes out automatically after 3 days."}),e.jsxs(B,{onClick:()=>f(!0),className:"bg-[#406E71] hover:bg-[#355e61] text-white shrink-0 ml-4",children:[e.jsx(Or,{className:"h-4 w-4 mr-2"})," New request"]})]}),e.jsx("div",{className:"bg-card rounded-2xl border overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-muted/50 text-muted-foreground",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left p-3 font-medium",children:"Recipient"}),e.jsx("th",{className:"text-left p-3 font-medium",children:"Channel"}),e.jsx("th",{className:"text-left p-3 font-medium",children:"Status"}),e.jsx("th",{className:"text-left p-3 font-medium",children:"Sent"})]})}),e.jsxs("tbody",{children:[i.map(Ne=>e.jsxs("tr",{className:"border-t",children:[e.jsxs("td",{className:"p-3",children:[e.jsx("p",{className:"font-medium text-foreground",children:Ne.recipient_name||"—"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Ne.recipient_email||Ne.recipient_phone})]}),e.jsx("td",{className:"p-3 capitalize",children:Ne.channel}),e.jsx("td",{className:"p-3",children:e.jsx(Oe,{variant:Ne.status==="completed"?"default":"outline",className:At("capitalize",Ne.status==="completed"&&"bg-[#406E71]"),children:Ne.status})}),e.jsx("td",{className:"p-3 text-muted-foreground",children:Ne.sent_at?new Date(Ne.sent_at).toLocaleDateString():"—"})]},Ne.id)),i.length===0&&e.jsx("tr",{children:e.jsx("td",{colSpan:4,className:"p-8 text-center text-muted-foreground",children:"No requests sent yet."})})]})]})})]}),e.jsx(Gt,{value:"page",className:"mt-6",children:e.jsx("div",{className:"max-w-xl space-y-5",children:e.jsxs("div",{className:"bg-card rounded-2xl border p-6 space-y-4",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Page URL slug"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"/reviews/"}),e.jsx(xe,{value:d.slug,onChange:Ne=>u(Ye=>({...Ye,slug:Ne.target.value})),placeholder:"jane-smith"})]})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Intro text"}),e.jsx(Ms,{value:d.intro_text,onChange:Ne=>u(Ye=>({...Ye,intro_text:Ne.target.value})),rows:3,placeholder:"A short note shown at the top of your page...",className:"mt-1"})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(J,{children:"Show Google reviews"}),e.jsx(fn,{checked:d.show_google_reviews,onCheckedChange:Ne=>u(Ye=>({...Ye,show_google_reviews:Ne}))})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(J,{children:"Show video testimonials"}),e.jsx(fn,{checked:d.show_video_reviews,onCheckedChange:Ne=>u(Ye=>({...Ye,show_video_reviews:Ne}))})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Publish page"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Only approved & featured reviews appear publicly."})]}),e.jsx(fn,{checked:d.is_published,onCheckedChange:Ne=>u(Ye=>({...Ye,is_published:Ne}))})]}),e.jsxs("div",{className:"flex gap-3 pt-2",children:[e.jsxs(B,{onClick:Pe,disabled:h,className:"bg-[#406E71] hover:bg-[#355e61] text-white",children:[h&&e.jsx(Ct,{className:"h-4 w-4 animate-spin mr-2"})," Save"]}),d.is_published&&Se&&e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"outline",onClick:()=>{navigator.clipboard.writeText(Se),se.success("Link copied")},children:[e.jsx(Ia,{className:"h-4 w-4 mr-2"})," Copy link"]}),e.jsx(B,{variant:"ghost",asChild:!0,children:e.jsxs("a",{href:Se,target:"_blank",rel:"noreferrer",children:[e.jsx(wr,{className:"h-4 w-4 mr-2"})," View page"]})})]})]})]})})})]})}),e.jsx(Ls,{open:p,onOpenChange:f,children:e.jsxs(Ps,{className:"max-w-lg",children:[e.jsx(Os,{children:e.jsx(Ds,{children:"Request reviews"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Recipients — one per line: Name, email, phone"}),e.jsx(Ms,{value:y,onChange:Ne=>v(Ne.target.value),rows:6,placeholder:`Jane Smith, jane@email.com, 555-123-4567 John Doe, john@email.com`,className:"mt-1 font-mono text-sm"})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Send via"}),e.jsxs(is,{value:g,onValueChange:Ne=>b(Ne),children:[e.jsx(rs,{className:"mt-1",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"email",children:"Email"}),e.jsx(He,{value:"sms",children:"Text message"}),e.jsx(He,{value:"both",children:"Email + text"})]})]})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Personal note (optional)"}),e.jsx(Ms,{value:j,onChange:Ne=>S(Ne.target.value),rows:3,placeholder:"It was a pleasure working with you...",className:"mt-1"})]}),e.jsxs(B,{onClick:ze,disabled:C,className:"w-full bg-[#406E71] hover:bg-[#355e61] text-white",children:[C?e.jsx(Ct,{className:"h-4 w-4 animate-spin mr-2"}):e.jsx(Or,{className:"h-4 w-4 mr-2"}),"Send requests"]})]})]})}),e.jsx(Ls,{open:!!P,onOpenChange:Ne=>!Ne&&M(null),children:e.jsxs(Ps,{children:[e.jsx(Os,{children:e.jsxs(Ds,{children:["Reply to ",P==null?void 0:P.reviewer_name]})}),(P==null?void 0:P.review_text)&&e.jsxs("p",{className:"text-sm text-muted-foreground italic",children:['"',P.review_text,'"']}),e.jsx(Ms,{value:I,onChange:Ne=>D(Ne.target.value),rows:4,placeholder:"Thank you so much, Jane..."}),e.jsxs(B,{onClick:ke,disabled:O||!I.trim(),className:"bg-[#406E71] hover:bg-[#355e61] text-white",children:[O&&e.jsx(Ct,{className:"h-4 w-4 animate-spin mr-2"}),(P==null?void 0:P.source)==="google"?"Post reply to Google":"Save reply"]})]})})]})})}function Por(){const{slug:s}=Li();return s?e.jsx(Z7t,{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 Lor(s){return`https://cardstudio.relevelup.com/c/${s}`}function Ior({shareToken:s,personalMessage:t,emailIntro:n,propertyAddress:r}){const a=Lor(s),i=(t||"").trim(),l=(n||"").trim();return`
${i?`

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


`:""} ${l?`

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

`:""} ${r?`

${r}

`:""}
`}function mCt(s,t,n){const[r,a,i]=s.split(/[-/T]/).map(Number),[l,o]=t.split(":").map(Number);let c=Date.UTC(r,(a||1)-1,i||1,l||0,o||0,0);for(let d=0;d<2;d++){const u=Dor(n,new Date(c));c=Date.UTC(r,(a||1)-1,i||1,l||0,o||0,0)-u}return new Date(c).toISOString()}function Dor(s,t){const n=new Intl.DateTimeFormat("en-US",{timeZone:s,hour12:!1,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}),r=Object.fromEntries(n.formatToParts(t).map(i=>[i.type,i.value]));return Date.UTC(Number(r.year),Number(r.month)-1,Number(r.day),Number(r.hour)%24,Number(r.minute),Number(r.second))-t.getTime()}function JYe(s,t){return new Intl.DateTimeFormat("en-US",{timeZone:t,month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}).format(new Date(s))}function Ror(s){return at({queryKey:["card-schedules",s],queryFn:async()=>{const{data:t,error:n}=await q.from("sendable_card_schedules").select("*").eq("status","pending").order("scheduled_at",{ascending:!0});if(n)throw n;const r={};for(const a of t||[])r[a.card_id]=a;return r},enabled:!!s})}function For(){const s=Bt();return mt({mutationFn:async t=>{const{data:{user:n}}=await q.auth.getUser();if(!n)throw new Error("Not signed in");await q.from("sendable_card_schedules").update({status:"canceled"}).eq("card_id",t.card_id).eq("status","pending");const{error:r}=await q.from("sendable_card_schedules").insert({...t,user_id:n.id});if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["card-schedules"]})},onError:t=>se.error(t.message||"Could not schedule the card")})}function Oor(){const s=Bt();return mt({mutationFn:async t=>{const{error:n}=await q.from("sendable_card_schedules").update({status:"canceled"}).eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["card-schedules"]}),se.success("Schedule canceled")},onError:t=>se.error(t.message||"Could not cancel")})}function fas({photoUrl:s,videoUrl:t,onPhotoChange:n,onVideoChange:r,contactId:a}){const{user:i}=hs(),l=TC(),o=_.useRef(null),c=_.useRef(null),[d,u]=_.useState(!1),[h,m]=_.useState(!1),[p,f]=_.useState(0),y=async g=>{if(i){u(!0);try{const b=g.name.split(".").pop()||"jpg",j=`${i.id}/card-${Date.now()}.${b}`,{error:S}=await q.storage.from("listing-photos").upload(j,g);if(S)throw S;const{data:{publicUrl:C}}=q.storage.from("listing-photos").getPublicUrl(j);n(C),se.success("Photo uploaded")}catch(b){se.error(b.message||"Failed to upload photo")}finally{u(!1)}}},v=async g=>{if(i){if(g.size>500*1024*1024){se.error("Video must be under 500MB");return}m(!0),f(0);try{const{videoId:b,libraryId:j}=await PL(`Card Video - ${Date.now()}`),{uploadUrl:S,apiKey:C}=await LL(b);await new Promise((M,I)=>{const D=new XMLHttpRequest;D.upload.addEventListener("progress",O=>{O.lengthComputable&&f(Math.round(O.loaded/O.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",S),D.setRequestHeader("AccessKey",C),D.send(g)});const E=`https://iframe.mediadelivery.net/embed/${j}/${b}`;r(E);const P=parseFloat((g.size/(1024*1024)).toFixed(2));await l.mutateAsync({bunny_video_id:b,playback_url:`https://iframe.mediadelivery.net/play/${j}/${b}`,file_size_mb:P,title:"Card Video",status:"processing",touch_type:"video",contact_id:a||void 0}),se.success("Video uploaded & added to your library")}catch(b){se.error(b.message||"Failed to upload video")}finally{m(!1),f(0)}}};return e.jsxs("div",{className:"space-y-3",children:[e.jsx(J,{children:"Media (optional)"}),e.jsxs(Yr,{defaultValue:"photo",className:"w-full",children:[e.jsxs(Zr,{className:"grid w-full grid-cols-2",children:[e.jsxs(Ht,{value:"photo",className:"gap-1.5 text-xs",children:[e.jsx(hc,{className:"h-3.5 w-3.5"}),"Photo"]}),e.jsxs(Ht,{value:"video",className:"gap-1.5 text-xs",children:[e.jsx(Kr,{className:"h-3.5 w-3.5"}),"Video"]})]}),e.jsxs(Gt,{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(B,{variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-7 w-7",onClick:()=>n(null),children:e.jsx(Qn,{className:"h-3.5 w-3.5"})})]}):e.jsx("button",{onClick:()=>{var g;return(g=o.current)==null?void 0:g.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(Ct,{className:"h-6 w-6 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(cg,{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:g=>{var j;const b=(j=g.target.files)==null?void 0:j[0];b&&y(b),g.target.value=""}})]}),e.jsxs(Gt,{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(B,{variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-7 w-7",onClick:()=>r(null),children:e.jsx(Qn,{className:"h-3.5 w-3.5"})})]}):e.jsx("button",{onClick:()=>{var g;return(g=c.current)==null?void 0:g.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(Ct,{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(Oa,{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(qat,{contactId:a,onVideoReady:g=>r(g)})}),e.jsx("input",{ref:c,type:"file",accept:"video/*",className:"hidden",onChange:g=>{var j;const b=(j=g.target.files)==null?void 0:j[0];b&&v(b),g.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 zor=[{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 Bor({onSelect:s}){return e.jsx("div",{className:"grid grid-cols-2 gap-2.5",children:zor.map((t,n)=>e.jsxs(Sr.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 Sz={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 pCt({initialOpen:s,initialCardType:t,initialContactId:n,initialRecipientName:r,initialAddress:a,initialDate:i,onOpenChange:l}){const{user:o}=hs(),c=Bt(),[d,u]=_.useState(!1),[h,m]=_.useState("type"),[p,f]=_.useState(""),[y,v]=_.useState(null),[g,b]=_.useState(!1),[j,S]=_.useState("home_anniversary"),[C,E]=_.useState(""),[P,M]=_.useState(""),[I,D]=_.useState(!0),[O,V]=_.useState(""),[G,$]=_.useState(""),[H,Y]=_.useState("elegant"),[Z,ne]=_.useState(null),[ce,ie]=_.useState(null),te=_.useState(!1);!te[0]&&s&&t&&(te[1](!0),u(!0),S(t),n&&v(n),r&&E(r),a&&M(a),i&&V(i),m(r?"details":"contact"));const{data:ae}=at({queryKey:["contacts-for-card",o==null?void 0:o.id,p],queryFn:async()=>{let ke=q.from("innercircle_contacts").select("id, first_name, last_name, address, city, state, home_anniversary, wedding_anniversary, email, phone").eq("owner_user_id",o.id).order("first_name").limit(20);p&&(ke=ke.or(`first_name.ilike.%${p}%,last_name.ilike.%${p}%`));const{data:Ze,error:Se}=await ke;if(Se)throw Se;return Ze},enabled:!!(o!=null&&o.id)&&d}),{data:le}=at({queryKey:["agent-profile-card",o==null?void 0:o.id],queryFn:async()=>{const{data:ke,error:Ze}=await q.from("profiles").select("name, email, phone, avatar_url, brokerage:brokerages(name)").eq("id",o.id).single();if(Ze)throw Ze;return ke},enabled:!!(o!=null&&o.id)}),be=ke=>{v(ke.id),E(`${ke.first_name}${ke.last_name?" "+ke.last_name:""}`),M([ke.address,ke.city,ke.state].filter(Boolean).join(", "));const Ze=j==="wedding_anniversary"?ke.wedding_anniversary:j==="home_anniversary"?ke.home_anniversary:"";V(Ze||""),m("details")},me=ke=>{S(ke),D(["home_anniversary","just_listed","just_sold"].includes(ke)),m("contact")},he=async()=>{var ke;if(!(!o||!le)){b(!0);try{const Ze={owner_user_id:o.id,contact_id:y,card_type:j,template:H,recipient_name:C,property_address:I&&P.trim()?P.trim():null,home_anniversary_date:O||null,custom_message:G||null,property_photo_url:Z||null,video_url:ce||null,agent_name:le.name||"Agent",agent_photo_url:le.avatar_url,agent_phone:le.phone,agent_email:le.email,agent_brokerage:((ke=le.brokerage)==null?void 0:ke.name)||null},{error:Se}=await q.from("sendable_cards").insert(Ze);if(Se)throw Se;se.success("Card created! Copy the link to share it."),c.invalidateQueries({queryKey:["sendable-cards"]}),pe()}catch(Ze){se.error(Ze.message||"Failed to create card")}finally{b(!1)}}},pe=()=>{u(!1),m("type"),S("home_anniversary"),f(""),v(null),E(""),M(""),D(!0),V(""),$(""),Y("elegant"),ne(null),ie(null)},Ce={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"},Ae=Sz[j],Pe=j==="home_anniversary"||j==="wedding_anniversary",ze=j==="wedding_anniversary"?"Wedding Anniversary Date":"Home Anniversary Date";return e.jsxs(Ls,{open:d,onOpenChange:ke=>{ke?u(!0):(pe(),l==null||l(!1))},children:[e.jsx(nl,{asChild:!0,children:e.jsxs(B,{className:"gap-2",children:[e.jsx(rn,{className:"h-4 w-4"}),"Create Card"]})}),e.jsxs(Ps,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Ds,{children:h==="type"?"What type of card?":h==="contact"?`${Ce[j]} — Choose a Contact`:`${Ce[j]} — Customize`})}),h==="type"&&e.jsx(Bor,{onSelect:me}),h==="contact"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs(B,{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(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search contacts...",value:p,onChange:ke=>f(ke.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"space-y-1 max-h-64 overflow-y-auto",children:[ae==null?void 0:ae.map(ke=>e.jsxs("button",{onClick:()=>be(ke),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(Fo,{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:[ke.first_name," ",ke.last_name]}),ke.address&&e.jsxs("p",{className:"text-xs text-muted-foreground truncate flex items-center gap-1",children:[e.jsx(Jr,{className:"h-3 w-3"}),ke.address]})]}),(j==="home_anniversary"&&ke.home_anniversary||j==="wedding_anniversary"&&ke.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"})]},ke.id)),(ae==null?void 0:ae.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(B,{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(B,{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(J,{children:"Recipient Name"}),e.jsx(xe,{value:C,onChange:ke=>E(ke.target.value),placeholder:"John & Jane Smith"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx("input",{type:"checkbox",className:"h-4 w-4 accent-primary",checked:I,onChange:ke=>D(ke.target.checked)}),"Include an address on this card"]}),I&&e.jsx(xe,{value:P,onChange:ke=>M(ke.target.value),placeholder:"123 Main St, Austin, TX"})]}),Pe&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:ze}),e.jsx(xe,{type:"date",value:O,onChange:ke=>V(ke.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Personal Message (optional)"}),e.jsx(Ms,{value:G,onChange:ke=>$(ke.target.value),placeholder:Ae.defaultMessage,rows:3})]}),e.jsx(fas,{photoUrl:Z,videoUrl:ce,onPhotoChange:ne,onVideoChange:ie,contactId:y}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{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:ke,label:Ze,gradient:Se})=>e.jsxs("button",{onClick:()=>Y(ke),className:`p-2 rounded-lg border-2 transition-all text-center ${H===ke?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("div",{className:`h-10 rounded-md mb-1.5 ${Se}`}),e.jsx("span",{className:"text-[10px] font-medium",children:Ze})]},ke))})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(B,{variant:"outline",onClick:()=>m("contact"),className:"flex-1",children:"Back"}),e.jsx(B,{onClick:he,disabled:!C||g,className:"flex-1 gap-2",children:g?"Creating...":"Create Card"})]})]})]})]})}const Uor={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 qor({card:s,existingSchedule:t}){const{user:n}=hs(),{isGmailConnected:r,hasVerifiedSes:a,canSendEmail:i,sendMethod:l}=Vg(),o=Bt(),c=For(),d=RE(),[u,h]=_.useState(!1);_.useState(!1);const[m,p]=_.useState((t==null?void 0:t.to_email)||""),[f,y]=_.useState(t?"later":"now"),[v,g]=_.useState(()=>t?new Intl.DateTimeFormat("en-CA",{timeZone:d,year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date(t.scheduled_at)):""),[b,j]=_.useState(()=>t?new Intl.DateTimeFormat("en-GB",{timeZone:d,hour:"2-digit",minute:"2-digit",hour12:!1}).format(new Date(t.scheduled_at)):"09:00");_.useEffect(()=>{u&&s.contact_id&&!m&&q.from("innercircle_contacts").select("email").eq("id",s.contact_id).maybeSingle().then(({data:$})=>{$!=null&&$.email&&p($.email)})},[u,s.contact_id]);const S={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}!`},[C,E]=_.useState((t==null?void 0:t.subject)||S[s.card_type]||`A Special Card for ${s.recipient_name}!`),[P,M]=_.useState((t==null?void 0:t.personal_message)||""),[I,D]=_.useState((t==null?void 0:t.email_intro)??`I made you a special ${Uor[s.card_type]||s.card_type} card — click below to view it!`),O=`https://cardstudio.relevelup.com/c/${s.share_token}`,V=mt({mutationFn:async()=>{if(!m)throw new Error("Recipient email is required");const $=Ior({shareToken:s.share_token,personalMessage:P,emailIntro:I,propertyAddress:s.property_address}),H=async()=>{const{data:ce,error:ie}=await q.functions.invoke("send-connect-invite",{body:{contactEmail:m,subject:C,htmlBody:$}});if(ie)throw ie;if(!(ce!=null&&ce.success))throw new Error((ce==null?void 0:ce.error)||"Failed to send");return"system"};if(!i)return await H();const{data:Y,error:Z}=await q.functions.invoke("gmail-send",{body:{to:m,subject:C,body:$,contactId:s.contact_id||void 0}});let ne=Y&&Y.error?Y:null;if(Z){ne={error:"send_failed",message:Z.message};const ce=Z.context;if(ce&&typeof ce.json=="function")try{ne=await ce.clone().json()}catch{}}if(ne){if(ne.error==="insufficient_scope"||ne.error==="no_integration")return await H(),se.warning("Sent using system email — reconnect Gmail in Integrations to send from your own inbox.",{duration:8e3}),"system";throw new Error(ne.message||ne.error||"Failed to send")}if(!(Y!=null&&Y.success))throw new Error("Failed to send");return"gmail"},onSuccess:async $=>{await q.from("sendable_cards").update({sent_at:new Date().toISOString(),sent_via:$==="gmail"?"gmail":"system"}).eq("id",s.id),o.invalidateQueries({queryKey:["sendable-cards"]}),se.success(`Card sent to ${m}!`),h(!1)},onError:$=>{se.error($.message||"Failed to send email")}}),G=l==="mass_email"?"Mass Email":l==="gmail"?"Gmail":"Email";return e.jsxs(Ls,{open:u,onOpenChange:h,children:[e.jsx(nl,{asChild:!0,children:e.jsx(B,{variant:"outline",size:"sm",className:"gap-1 text-xs",children:e.jsx(Or,{className:"h-3 w-3"})})}),e.jsxs(Ps,{className:"sm:max-w-md",children:[e.jsx(Os,{children:e.jsxs(Ds,{children:["Send Card via ",G]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-2 gap-2",children:["now","later"].map($=>e.jsx("button",{onClick:()=>y($),className:`rounded-lg border-2 px-3 py-2 text-xs font-medium transition-all ${f===$?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:$==="now"?"Send now":"Schedule"},$))}),f==="later"&&e.jsxs("div",{className:"space-y-2 rounded-lg border border-border p-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(J,{className:"text-xs",children:"Date"}),e.jsx(xe,{type:"date",value:v,onChange:$=>g($.target.value)})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(J,{className:"text-xs",children:"Time"}),e.jsx(xe,{type:"time",value:b,onChange:$=>j($.target.value)})]})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:v?`Goes out ${JYe(mCt(v,b,d),d)} ${pP(d)} (within about 15 minutes of that time).`:`Times are in your calendar time zone (${pP(d)}).`})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"gmail-to",children:"To"}),e.jsx(kzt,{value:m,onChange:p,userId:n==null?void 0:n.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(J,{children:"Subject"}),e.jsx(xe,{value:C,onChange:$=>E($.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Personal Note (optional)"}),e.jsx(Ms,{value:P,onChange:$=>M($.target.value),placeholder:"Add a warm personal note before the card link...",rows:3})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Message in the email"}),e.jsx(Ms,{value:I,onChange:$=>D($.target.value),placeholder:"Leave blank to send just the card button.",rows:2}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"This is the line that appears above the “View Your Card” button. Edit it or clear it."})]}),e.jsxs("div",{className:"rounded-lg bg-muted/50 p-3 text-xs text-muted-foreground",children:[l==="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:O})]}),f==="now"?e.jsx(B,{onClick:()=>V.mutate(),disabled:!m||V.isPending,className:"w-full gap-2",children:V.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"h-4 w-4 animate-spin"})," Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Or,{className:"h-4 w-4"})," Send Card"]})}):e.jsx(B,{onClick:async()=>{const $=mCt(v,b,d);if(!v||new Date($).getTime()<=Date.now()){se.error("Pick a date and time in the future");return}await c.mutateAsync({card_id:s.id,to_email:m,subject:C,personal_message:P,email_intro:I,scheduled_at:$,timezone:d}),se.success(`Card scheduled for ${JYe($,d)} ${pP(d)}`),h(!1)},disabled:!m||!v||c.isPending,className:"w-full gap-2",children:c.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"h-4 w-4 animate-spin"})," Scheduling..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Qd,{className:"h-4 w-4"})," Schedule card"]})})]})]})]})}const $or=[{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"}];function Vor({card:s}){const t=Bt(),[n,r]=_.useState(!1),[a,i]=_.useState(!1),[l,o]=_.useState(s.recipient_name),[c,d]=_.useState(s.property_address||""),[u,h]=_.useState(!!s.property_address),[m,p]=_.useState(s.home_anniversary_date||""),[f,y]=_.useState(s.custom_message||""),[v,g]=_.useState(s.template),[b,j]=_.useState(s.property_photo_url),[S,C]=_.useState(s.video_url||null),E=s.card_type,P=Sz[E],M=E==="home_anniversary"||E==="wedding_anniversary",I=E==="wedding_anniversary"?"Wedding Anniversary Date":"Home Anniversary Date",D=V=>{V&&(o(s.recipient_name),d(s.property_address||""),h(!!s.property_address),p(s.home_anniversary_date||""),y(s.custom_message||""),g(s.template),j(s.property_photo_url),C(s.video_url||null)),r(V)},O=async()=>{if(!l.trim()){se.error("Recipient name is required");return}i(!0);try{const{error:V}=await q.from("sendable_cards").update({recipient_name:l.trim(),property_address:u&&c.trim()?c.trim():null,home_anniversary_date:M&&m||null,custom_message:f.trim()||null,template:v,property_photo_url:b||null,video_url:S||null}).eq("id",s.id);if(V)throw V;t.invalidateQueries({queryKey:["sendable-cards"]}),se.success("Card updated"),r(!1)}catch(V){se.error(V.message||"Failed to update card")}finally{i(!1)}};return e.jsxs(Ls,{open:n,onOpenChange:D,children:[e.jsx(nl,{asChild:!0,children:e.jsx(B,{variant:"outline",size:"sm",className:"gap-1 text-xs",children:e.jsx(Ya,{className:"h-3 w-3"})})}),e.jsxs(Ps,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Ds,{children:"Edit Card"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Recipient Name"}),e.jsx(xe,{value:l,onChange:V=>o(V.target.value),placeholder:"John & Jane Smith"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx("input",{type:"checkbox",className:"h-4 w-4 accent-primary",checked:u,onChange:V=>h(V.target.checked)}),"Include an address on this card"]}),u&&e.jsx(xe,{value:c,onChange:V=>d(V.target.value),placeholder:"123 Main St, Austin, TX"})]}),M&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:I}),e.jsx(xe,{type:"date",value:m,onChange:V=>p(V.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Personal Message (optional)"}),e.jsx(Ms,{value:f,onChange:V=>y(V.target.value),placeholder:(P==null?void 0:P.defaultMessage)||"Add a personal message...",rows:3})]}),e.jsx(fas,{photoUrl:b,videoUrl:S,onPhotoChange:j,onVideoChange:C,contactId:s.contact_id}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Template Style"}),e.jsx("div",{className:"grid grid-cols-5 gap-2",children:$or.map(({key:V,label:G,gradient:$})=>e.jsxs("button",{onClick:()=>g(V),className:`p-2 rounded-lg border-2 transition-all text-center ${v===V?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("div",{className:`h-10 rounded-md mb-1.5 ${$}`}),e.jsx("span",{className:"text-[10px] font-medium",children:G})]},V))})]}),e.jsx(B,{onClick:O,disabled:!l.trim()||a,className:"w-full gap-2",children:a?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"h-4 w-4 animate-spin"})," Saving..."]}):"Save Changes"})]})]})]})}function Hor(){const{user:s}=hs(),t=Bt(),{data:n}=Ror(s==null?void 0:s.id),r=Oor(),[a,i]=_.useState(""),[l,o]=Yl(),c=l.get("cardType"),d=l.get("contactId"),u=l.get("name"),h=l.get("address"),m=l.get("date"),p=!!c,{data:f,isLoading:y}=at({queryKey:["sendable-cards",s==null?void 0:s.id],queryFn:async()=>{const{data:C,error:E}=await q.from("sendable_cards").select("*").eq("owner_user_id",s.id).order("created_at",{ascending:!1});if(E)throw E;return C},enabled:!!(s!=null&&s.id)}),v=mt({mutationFn:async C=>{const{error:E}=await q.from("sendable_cards").delete().eq("id",C);if(E)throw E},onSuccess:()=>{t.invalidateQueries({queryKey:["sendable-cards"]}),se.success("Card deleted")}}),g=C=>{const E=`https://cardstudio.relevelup.com/c/${C}`;navigator.clipboard.writeText(E),se.success("Share link copied!")},b=f==null?void 0:f.filter(C=>{var E;return!a||C.recipient_name.toLowerCase().includes(a.toLowerCase())||((E=C.property_address)==null?void 0:E.toLowerCase().includes(a.toLowerCase()))}),j={elegant:"Elegant",bold:"Bold",warm:"Warm"},S={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(zs,{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(pCt,{initialOpen:p,initialCardType:c,initialContactId:d||void 0,initialRecipientName:u||void 0,initialAddress:h||void 0,initialDate:m||void 0,onOpenChange:()=>o({})})]}),e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search cards...",value:a,onChange:C=>i(C.target.value),className:"pl-9"})]}),y?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[1,2,3].map(C=>e.jsx(ve,{className:"animate-pulse",children:e.jsxs(Me,{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"})]})},C))}):b!=null&&b.length?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:b.map(C=>{var E;return e.jsxs(ve,{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 ${C.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":C.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:[C.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"})]}),C.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%)]"})]}),C.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:C.card_type==="home_anniversary"?"🏡":C.card_type==="wedding_anniversary"?"💍":C.card_type==="birthday"?"🎂":C.card_type==="just_sold"?"🎉":C.card_type==="just_listed"?"🏠":C.card_type==="thank_you"?"💐":C.card_type==="congratulations"?"🏆":C.card_type==="holiday"?"🎄":C.card_type==="thinking_of_you"?"💭":"✉️"}),e.jsx("p",{className:`text-[10px] uppercase tracking-[0.2em] mb-1 ${C.template==="bold"?"text-white/70":"text-muted-foreground"}`,children:S[C.card_type]||C.card_type}),e.jsx("p",{className:`font-semibold text-base ${C.template==="bold"?"text-white":"text-foreground"}`,children:C.recipient_name}),C.property_address&&e.jsx("p",{className:`text-xs mt-1 ${C.template==="bold"?"text-white/60":"text-muted-foreground"}`,children:C.property_address})]}),e.jsx("div",{className:"absolute top-2 right-2 z-10",children:e.jsx(Oe,{variant:C.template==="bold"?"outline":"secondary",className:`text-[10px] ${C.template==="bold"?"border-white/30 text-white/80":""}`,children:j[C.template]||C.template})})]}),e.jsxs(Me,{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(ya,{className:"h-3 w-3"}),C.view_count," views"]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Ed(new Date(C.created_at),{addSuffix:!0})})]}),C.sent_at&&e.jsxs("p",{className:"text-[10px] text-emerald-600 mb-2",children:["Sent ",Hs(new Date(C.sent_at),"MMM d, yyyy")," via ",C.sent_via]}),!C.sent_at&&(n==null?void 0:n[C.id])&&e.jsxs("div",{className:"mb-2 flex items-center gap-2 text-[10px] text-primary",children:[e.jsx(Qd,{className:"h-3 w-3"}),e.jsxs("span",{children:["Scheduled for ",JYe(n[C.id].scheduled_at,n[C.id].timezone)]}),e.jsx("button",{className:"underline text-muted-foreground hover:text-foreground",onClick:()=>r.mutate(n[C.id].id),children:"Cancel"})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsxs(B,{variant:"outline",size:"sm",className:"flex-1 gap-1 text-xs",onClick:()=>g(C.share_token),children:[e.jsx(Ia,{className:"h-3 w-3"}),"Copy Link"]}),e.jsx(Vor,{card:C}),e.jsx(qor,{card:C,existingSchedule:(n==null?void 0:n[C.id])||null},((E=n==null?void 0:n[C.id])==null?void 0:E.id)||"none"),e.jsx(B,{variant:"outline",size:"sm",className:"gap-1 text-xs",onClick:()=>window.open(`https://cardstudio.relevelup.com/c/${C.share_token}`,"_blank"),children:e.jsx(wr,{className:"h-3 w-3"})}),e.jsx(B,{variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive gap-1 text-xs",onClick:()=>v.mutate(C.id),children:e.jsx(Sn,{className:"h-3 w-3"})})]})]})]},C.id)})}):e.jsx(ve,{className:"border-dashed",children:e.jsxs(Me,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx("div",{className:"h-16 w-16 rounded-full bg-primary/10 flex items-center justify-center mb-4",children:e.jsx(ln,{className:"h-8 w-8 text-primary"})}),e.jsx("h3",{className:"font-semibold text-lg mb-1",children:"No cards yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Create your first digital card to send to a client"}),e.jsx(pCt,{initialOpen:p,initialCardType:c,initialContactId:d||void 0,initialRecipientName:u||void 0,initialAddress:h||void 0,initialDate:m||void 0,onOpenChange:()=>o({})})]})})]})})}const Wde=[{id:"mls",label:"MLS Description",tag:"Standard",icon:Jr,accent:"from-sky-500 to-cyan-500",desc:"Polished MLS-ready listing",category:"listing"},{id:"luxury",label:"Luxury MLS",tag:"Premium",icon:$f,accent:"from-amber-500 to-orange-500",desc:"Evocative, high-end voice",category:"listing"},{id:"short",label:"Short MLS",tag:"Concise",icon:nf,accent:"from-violet-500 to-fuchsia-500",desc:"Punchy 60–90 words",category:"listing"},{id:"openHouse",label:"Open House",tag:"Promo",icon:dN,accent:"from-emerald-500 to-teal-500",desc:"Friendly invite copy",category:"listing",extras:["openHouse"]},{id:"newConstruction",label:"New Construction",tag:"Build",icon:PQ,accent:"from-rose-500 to-pink-500",desc:"Builder-focused angle",category:"listing",extras:["newConstruction"]},{id:"investment",label:"Investment",tag:"ROI",icon:Nl,accent:"from-indigo-500 to-blue-500",desc:"Cap rate & income hooks",category:"listing",extras:["investment"]},{id:"facebookPost",label:"Facebook Post",tag:"Social",icon:tf,accent:"from-blue-600 to-blue-400",desc:"Engaging FB caption",category:"social"},{id:"instagramPost",label:"Instagram Post",tag:"Social",icon:Im,accent:"from-pink-500 via-fuchsia-500 to-orange-400",desc:"IG caption + hashtags",category:"social"},{id:"linkedinPost",label:"LinkedIn Post",tag:"Social",icon:dg,accent:"from-sky-700 to-sky-500",desc:"Professional tone",category:"social"},{id:"justListed",label:"Just Listed",tag:"Announce",icon:wh,accent:"from-emerald-500 to-green-500",desc:"Hit the market announcement",category:"social"},{id:"comingSoon",label:"Coming Soon",tag:"Tease",icon:Gr,accent:"from-amber-500 to-yellow-500",desc:"Build pre-market buzz",category:"social",extras:["comingSoon"]},{id:"priceImprovement",label:"Price Improvement",tag:"Update",icon:gS,accent:"from-orange-500 to-red-500",desc:"New price announcement",category:"social",extras:["priceImprovement"]},{id:"openHousePost",label:"Open House Post",tag:"Event",icon:pc,accent:"from-teal-500 to-emerald-500",desc:"Social invite to OH",category:"social",extras:["openHouse"]},{id:"underContract",label:"Under Contract",tag:"Status",icon:kQ,accent:"from-indigo-500 to-purple-500",desc:"Pending celebration",category:"social",extras:["underContract"]},{id:"justSold",label:"Just Sold",tag:"Celebrate",icon:Ex,accent:"from-fuchsia-500 to-pink-500",desc:"Sold success post",category:"social",extras:["sold"]},{id:"propertyTourScript",label:"Property Tour",tag:"Script",icon:Kr,accent:"from-red-500 to-rose-500",desc:"Full walkthrough script",category:"video",extras:["signoff"]},{id:"reelScript",label:"Reel Script",tag:"Short",icon:dm,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:n7,accent:"from-violet-500 to-purple-500",desc:"5 scroll-stopping hooks",category:"video",extras:["vibe"]},{id:"luxuryWalkthrough",label:"Luxury Walkthrough",tag:"Premium",icon:$f,accent:"from-amber-500 to-yellow-500",desc:"Cinematic, refined tone",category:"video",extras:["signoff"]},{id:"droneScript",label:"Drone Script",tag:"Aerial",icon:eJ,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:Xa,accent:"from-emerald-500 to-teal-500",desc:"Area lifestyle script",category:"video",extras:["neighborhood","signoff"]},{id:"justListedEmail",label:"Just Listed Email",tag:"Announce",icon:ln,accent:"from-emerald-500 to-green-500",desc:"Email blast for new listing",category:"email",extras:["signoff"]},{id:"openHouseEmail",label:"Open House Invite",tag:"Invite",icon:Vq,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:In,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:gS,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:$4,accent:"from-fuchsia-500 to-pink-500",desc:"Sold announcement email",category:"email",extras:["sold","signoff"]},{id:"neighborhoodEmail",label:"Neighborhood Email",tag:"Nurture",icon:Xa,accent:"from-sky-500 to-indigo-500",desc:"Area update / market touch",category:"email",extras:["neighborhood","signoff"]}];function Gor(){var Si,Gi,rl,Ii,Ta,eo,So,Ra,Eo,Ro,di;const{user:s}=hs(),[t,n]=_.useState(""),[r,a]=_.useState(""),[i,l]=_.useState([]),[o,c]=_.useState(""),[d,u]=_.useState([]),[h,m]=_.useState(""),[p,f]=_.useState(""),[y,v]=_.useState(""),[g,b]=_.useState(""),[j,S]=_.useState(""),[C,E]=_.useState(""),[P,M]=_.useState(""),[I,D]=_.useState(null),[O,V]=_.useState(""),[G,$]=_.useState(""),[H,Y]=_.useState(""),[Z,ne]=_.useState(""),[ce,ie]=_.useState(""),[te,ae]=_.useState(""),[le,be]=_.useState(""),[me,he]=_.useState(""),[pe,Ce]=_.useState(""),[Ae,Pe]=_.useState(""),[ze,ke]=_.useState(""),[Ze,Se]=_.useState(""),[Fe,Ne]=_.useState(""),[Ye,Ve]=_.useState(""),[qe,Qe]=_.useState(""),[Ue,Xe]=_.useState(""),[nt,$e]=_.useState(""),[Ge,ct]=_.useState(""),[xt,qt]=_.useState(""),[Vt,Xt]=_.useState(""),[fs,Ft]=_.useState(""),[wt,Ts]=_.useState(""),[vt,$s]=_.useState(""),[As,jn]=_.useState(""),[ar,Dn]=_.useState(""),[Ur,Vs]=_.useState("listing"),[hn,dr]=_.useState("mls"),[Cn,Yn]=_.useState({}),[on,Ir]=_.useState({}),[Wn,Js]=_.useState(!1),[Fa,ks]=_.useState(!1),Gs=rr=>{Vs(rr);const oi=Wde.find(Oo=>Oo.category===rr);oi&&dr(oi.id)},{data:Ws}=at({queryKey:["listing-studio-listings",s==null?void 0:s.id],enabled:!!(s!=null&&s.id)&&Wn,queryFn:async()=>{const{data:rr,error:oi}=await q.from("listings").select("id, property_address, city, state, price, bedrooms, bathrooms, square_footage, property_type, description").eq("agent_id",s.id).order("created_at",{ascending:!1}).limit(50);if(oi)throw oi;return rr||[]}}),Ys=()=>{const rr=o.trim();rr&&(l(oi=>[...oi,rr]),c(""))},Bn=rr=>l(oi=>oi.filter((Oo,kl)=>kl!==rr)),or=rr=>{var oi,Oo,kl,Jo;D(rr.id),n(rr.property_address||""),E(rr.city||""),M(rr.state||""),b(((oi=rr.price)==null?void 0:oi.toString())||""),m(((Oo=rr.bedrooms)==null?void 0:Oo.toString())||""),f(((kl=rr.bathrooms)==null?void 0:kl.toString())||""),v(((Jo=rr.square_footage)==null?void 0:Jo.toString())||""),S(rr.property_type||""),a(rr.description||""),Js(!1),se.success("Listing imported")},Wt=async rr=>{if(!(!rr.target.files||!(s!=null&&s.id))){ks(!0);try{const oi=[];for(const Oo of Array.from(rr.target.files).slice(0,10)){const kl=`${s.id}/${Date.now()}-${Oo.name.replace(/[^\w.-]/g,"_")}`,{error:Jo}=await q.storage.from("listing-photos").upload(kl,Oo,{upsert:!1});if(Jo){console.error(Jo);continue}const{data:Sl}=q.storage.from("listing-photos").getPublicUrl(kl);oi.push(Sl.publicUrl)}u(Oo=>[...Oo,...oi]),oi.length&&se.success(`${oi.length} photo(s) uploaded`)}catch(oi){se.error(oi.message||"Photo upload failed")}finally{ks(!1)}}},rt=Wde.find(rr=>rr.id===hn),pt=async rr=>{var Oo,kl,Jo;const oi=Wde.find(Sl=>Sl.id===rr);if(!t.trim()&&!r.trim()&&i.length===0){se.error("Add a property address, MLS remarks, or features first");return}if((Oo=oi.extras)!=null&&Oo.includes("openHouse")&&(!O||!G||!H)){se.error("Add the open house date, start and end time");return}if((kl=oi.extras)!=null&&kl.includes("priceImprovement")&&(!Z||!ce)){se.error("Add previous and new price");return}if((Jo=oi.extras)!=null&&Jo.includes("sold")&&!te){se.error("Add the sold price");return}dr(rr),Ir(Sl=>({...Sl,[rr]:!0}));try{const{data:Sl,error:vu}=await q.functions.invoke("listing-studio-generate",{body:{copyType:rr,propertyAddress:t,mlsRemarks:r,features:i,photoUrls:d,listingId:I,bedrooms:h?Number(h):null,bathrooms:p?Number(p):null,squareFootage:y?Number(y):null,price:g?Number(g):null,propertyType:j||null,city:C||null,state:P||null,openHouseDate:O||null,openHouseStart:G||null,openHouseEnd:H||null,previousPrice:Z?Number(Z):null,newPrice:ce?Number(ce):null,soldPrice:te?Number(te):null,soldDate:le||null,comingSoonDate:me||null,builderName:pe||null,yearBuilt:Ae?Number(Ae):null,warrantyInfo:ze||null,monthlyRent:Ze?Number(Ze):null,capRate:Fe||null,occupancy:Ye||null,daysOnMarket:qe?Number(qe):null,offerCount:Ue?Number(Ue):null,originalListPrice:nt?Number(nt):null,soldDaysOnMarket:Ge?Number(Ge):null,commissionOffered:xt||null,refreshments:Vt||null,vibe:fs||null,neighborhoodHighlights:wt||null,agentName:vt||null,agentBrokerage:As||null,agentContact:ar||null}});if(vu)throw vu;if(Sl!=null&&Sl.error)throw new Error(Sl.error);Yn(Ku=>({...Ku,[rr]:Sl.content}))}catch(Sl){se.error(Sl.message||"Generation failed")}finally{Ir(Sl=>({...Sl,[rr]:!1}))}},jt=rr=>{navigator.clipboard.writeText(rr),se.success("Copied to clipboard")},Mt=rt.icon,es=Cn[hn]?Cn[hn].trim().split(/\s+/).length:0,ps=rr=>e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3",children:Wde.filter(oi=>oi.category===rr).map(oi=>{const Oo=oi.icon,kl=hn===oi.id,Jo=!!Cn[oi.id];return e.jsxs("button",{onClick:()=>dr(oi.id),className:At("relative text-left p-4 rounded-2xl border transition-all overflow-hidden group",kl?"border-primary shadow-lg shadow-primary/10 bg-card":"border-border/60 hover:border-border bg-card/50 hover:bg-card"),children:[kl&&e.jsx("div",{className:At("absolute inset-0 opacity-[0.07] bg-gradient-to-br",oi.accent)}),e.jsxs("div",{className:"relative space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:At("h-9 w-9 rounded-xl grid place-items-center text-white bg-gradient-to-br shadow-sm",oi.accent),children:e.jsx(Oo,{className:"h-4 w-4"})}),Jo&&e.jsx("div",{className:"h-5 w-5 rounded-full bg-emerald-500/15 text-emerald-600 grid place-items-center",children:e.jsx(ea,{className:"h-3 w-3"})})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold text-sm",children:oi.label}),e.jsx("div",{className:"text-xs text-muted-foreground line-clamp-1",children:oi.desc})]})]})]},oi.id)})}),Is=(Si=rt.extras)==null?void 0:Si.includes("openHouse"),js=(Gi=rt.extras)==null?void 0:Gi.includes("priceImprovement"),Kt=(rl=rt.extras)==null?void 0:rl.includes("sold"),Qs=(Ii=rt.extras)==null?void 0:Ii.includes("comingSoon"),an=(Ta=rt.extras)==null?void 0:Ta.includes("newConstruction"),er=(eo=rt.extras)==null?void 0:eo.includes("investment"),Xr=(So=rt.extras)==null?void 0:So.includes("underContract"),ma=(Ra=rt.extras)==null?void 0:Ra.includes("brokerOpen"),Br=(Eo=rt.extras)==null?void 0:Eo.includes("vibe"),sa=(Ro=rt.extras)==null?void 0:Ro.includes("neighborhood"),Rr=(di=rt.extras)==null?void 0:di.includes("signoff"),ra=Is||js||Kt||Qs||an||er||Xr||ma||Br||sa||Rr;return e.jsx(zs,{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(un,{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(Ls,{open:Wn,onOpenChange:Js,children:[e.jsx(nl,{asChild:!0,children:e.jsxs(B,{size:"lg",variant:"secondary",className:"shadow-lg shadow-fuchsia-500/10",children:[e.jsx(Fr,{className:"h-4 w-4 mr-2"}),"Import from Listings"]})}),e.jsxs(Ps,{className:"max-w-2xl max-h-[80vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Ds,{children:"Import from Listing Exchange"})}),e.jsxs("div",{className:"space-y-2 mt-2",children:[!(Ws!=null&&Ws.length)&&e.jsx("p",{className:"text-sm text-muted-foreground py-8 text-center",children:"No listings found yet."}),Ws==null?void 0:Ws.map(rr=>e.jsxs("button",{onClick:()=>or(rr),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:rr.property_address||"Untitled listing"}),e.jsxs("div",{className:"text-sm text-muted-foreground mt-0.5",children:[[rr.city,rr.state].filter(Boolean).join(", "),rr.price?` · $${Number(rr.price).toLocaleString()}`:"",rr.bedrooms?` · ${rr.bedrooms}bd`:"",rr.bathrooms?` · ${rr.bathrooms}ba`:""]})]},rr.id))]})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-5 gap-6",children:[e.jsx(ve,{className:"lg:col-span-2 border-border/60 shadow-sm",children:e.jsxs(Me,{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(Jr,{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(J,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Address"}),e.jsx(xe,{value:t,onChange:rr=>n(rr.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(J,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"City"}),e.jsx(xe,{value:C,onChange:rr=>E(rr.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"State"}),e.jsx(xe,{value:P,onChange:rr=>M(rr.target.value)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Price"}),e.jsx(xe,{type:"number",value:g,onChange:rr=>b(rr.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Type"}),e.jsx(xe,{value:j,onChange:rr=>S(rr.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(J,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Beds"}),e.jsx(xe,{type:"number",value:h,onChange:rr=>m(rr.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Baths"}),e.jsx(xe,{type:"number",step:"0.5",value:p,onChange:rr=>f(rr.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Sqft"}),e.jsx(xe,{type:"number",value:y,onChange:rr=>v(rr.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"MLS Remarks / Notes"}),e.jsx(Ms,{value:r,onChange:rr=>a(rr.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(J,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Features"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{value:o,onChange:rr=>c(rr.target.value),onKeyDown:rr=>rr.key==="Enter"&&(rr.preventDefault(),Ys()),placeholder:"e.g. Quartz countertops"}),e.jsx(B,{type:"button",size:"icon",variant:"secondary",onClick:Ys,children:e.jsx(rn,{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((rr,oi)=>e.jsxs(Oe,{variant:"secondary",className:"pl-3 pr-1 py-1 gap-1",children:[rr,e.jsx("button",{onClick:()=>Bn(oi),className:"ml-0.5 p-0.5 hover:bg-background/60 rounded-full",children:e.jsx(Qn,{className:"h-3 w-3"})})]},oi))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{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(jy,{className:"h-4 w-4"}),Fa?"Uploading…":"Click to upload photos",e.jsx("input",{type:"file",accept:"image/*",multiple:!0,onChange:Wt,disabled:Fa,className:"hidden"})]}),d.length>0&&e.jsx("div",{className:"grid grid-cols-4 gap-2 mt-2",children:d.map((rr,oi)=>e.jsxs("div",{className:"relative aspect-square rounded-lg overflow-hidden group",children:[e.jsx("img",{src:rr,alt:"",className:"w-full h-full object-cover"}),e.jsx("button",{onClick:()=>u(Oo=>Oo.filter((kl,Jo)=>Jo!==oi)),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(Qn,{className:"h-3 w-3"})})]},oi))})]}),ra&&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(un,{className:"h-4 w-4 text-primary"}),e.jsxs("div",{className:"text-sm font-semibold",children:["Extra info for ",rt.label]})]}),Is&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Date"}),e.jsx(xe,{type:"date",value:O,onChange:rr=>V(rr.target.value)})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Start"}),e.jsx(xe,{type:"time",value:G,onChange:rr=>$(rr.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"End"}),e.jsx(xe,{type:"time",value:H,onChange:rr=>Y(rr.target.value)})]})]})]}),js&&e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Previous Price"}),e.jsx(xe,{type:"number",value:Z,onChange:rr=>ne(rr.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"New Price"}),e.jsx(xe,{type:"number",value:ce,onChange:rr=>ie(rr.target.value),placeholder:"$"})]})]}),Kt&&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(J,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Sold Price"}),e.jsx(xe,{type:"number",value:te,onChange:rr=>ae(rr.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Sold Date"}),e.jsx(xe,{type:"date",value:le,onChange:rr=>be(rr.target.value)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Original List Price (optional)"}),e.jsx(xe,{type:"number",value:nt,onChange:rr=>$e(rr.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Days on Market (optional)"}),e.jsx(xe,{type:"number",value:Ge,onChange:rr=>ct(rr.target.value)})]})]})]}),Qs&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Expected Live Date (optional)"}),e.jsx(xe,{type:"date",value:me,onChange:rr=>he(rr.target.value)})]}),an&&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(J,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Builder Name"}),e.jsx(xe,{value:pe,onChange:rr=>Ce(rr.target.value),placeholder:"ABC Homes"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Year Built"}),e.jsx(xe,{type:"number",value:Ae,onChange:rr=>Pe(rr.target.value),placeholder:"2026"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Warranty / Energy / Smart-home (optional)"}),e.jsx(xe,{value:ze,onChange:rr=>ke(rr.target.value),placeholder:"10-yr structural, ENERGY STAR, smart-home pkg"})]})]}),er&&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(J,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Monthly Rent (optional)"}),e.jsx(xe,{type:"number",value:Ze,onChange:rr=>Se(rr.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Cap Rate (optional)"}),e.jsx(xe,{value:Fe,onChange:rr=>Ne(rr.target.value),placeholder:"6.5%"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Occupancy"}),e.jsxs("select",{value:Ye,onChange:rr=>Ve(rr.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"})]})]})]}),Xr&&e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Days on Market (optional)"}),e.jsx(xe,{type:"number",value:qe,onChange:rr=>Qe(rr.target.value),placeholder:"e.g. 3"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"# of Offers (optional)"}),e.jsx(xe,{type:"number",value:Ue,onChange:rr=>Xe(rr.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(J,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Commission / Co-op Offered (optional)"}),e.jsx(xe,{value:xt,onChange:rr=>qt(rr.target.value),placeholder:"2.5% buyer agent commission"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Refreshments / Perks (optional)"}),e.jsx(xe,{value:Vt,onChange:rr=>Xt(rr.target.value),placeholder:"Lunch + raffle for $100 gift card"})]})]}),Br&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Vibe / Tone"}),e.jsxs("select",{value:fs,onChange:rr=>Ft(rr.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"})]})]}),sa&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Nearby Highlights (optional)"}),e.jsx(Ms,{value:wt,onChange:rr=>Ts(rr.target.value),rows:3,placeholder:"Top schools, parks, coffee shops, restaurants, commute, walkability…"})]}),Rr&&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(J,{className:"text-xs font-medium text-muted-foreground",children:"Agent Name"}),e.jsx(xe,{value:vt,onChange:rr=>$s(rr.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{className:"text-xs font-medium text-muted-foreground",children:"Brokerage"}),e.jsx(xe,{value:As,onChange:rr=>jn(rr.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{className:"text-xs font-medium text-muted-foreground",children:"Phone / Email"}),e.jsx(xe,{value:ar,onChange:rr=>Dn(rr.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:Fr},{key:"social",label:"Social Media",icon:Im},{key:"video",label:"Video Scripts",icon:Kr},{key:"email",label:"Email Marketing",icon:ln}].map(rr=>{const oi=rr.icon,Oo=Ur===rr.key;return e.jsxs("button",{onClick:()=>Gs(rr.key),className:At("flex-1 flex items-center justify-center gap-2 px-4 py-2.5 rounded-lg text-sm font-medium transition-all",Oo?"bg-card shadow-sm text-foreground border border-border/60":"text-muted-foreground hover:text-foreground hover:bg-background/50"),children:[e.jsx(oi,{className:"h-4 w-4"}),rr.label]},rr.key)})}),ps(Ur),e.jsxs(ve,{className:"border-border/60 shadow-sm overflow-hidden",children:[e.jsx("div",{className:At("h-1 bg-gradient-to-r",rt.accent)}),e.jsxs(Me,{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:At("h-10 w-10 rounded-xl grid place-items-center text-white bg-gradient-to-br",rt.accent),children:e.jsx(Mt,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"font-semibold flex items-center gap-2",children:[rt.label,e.jsx(Oe,{variant:"outline",className:"text-[10px] font-normal",children:rt.tag})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Cn[hn]?`${es} words`:"Ready to generate"})]})]}),e.jsxs("div",{className:"flex gap-2",children:[Cn[hn]&&e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>jt(Cn[hn]),children:[e.jsx(Ia,{className:"h-4 w-4 mr-2"})," Copy"]}),e.jsx(B,{onClick:()=>pt(hn),disabled:on[hn],className:At("shadow-lg shadow-primary/10 bg-gradient-to-r text-white border-0 hover:opacity-90",rt.accent),size:"sm",children:on[hn]?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"})," Generating"]}):Cn[hn]?e.jsxs(e.Fragment,{children:[e.jsx(uo,{className:"h-4 w-4 mr-2"})," Regenerate"]}):e.jsxs(e.Fragment,{children:[e.jsx(Qx,{className:"h-4 w-4 mr-2"})," Generate"]})})]})]}),Cn[hn]?e.jsx(Ms,{value:Cn[hn],onChange:rr=>Yn(oi=>({...oi,[hn]:rr.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:At("mx-auto h-14 w-14 rounded-2xl grid place-items-center text-white bg-gradient-to-br mb-4",rt.accent),children:e.jsx(Qx,{className:"h-6 w-6"})}),e.jsxs("div",{className:"font-medium mb-1",children:["Generate a ",rt.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 OZ({delay:s,x:t,y:n,size:r}){return e.jsx(Sr.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 Wor(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=Sz[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(Sr.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(Sr.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(OZ,{delay:0,x:"15%",y:"20%",size:8}),e.jsx(OZ,{delay:1,x:"80%",y:"30%",size:6}),e.jsx(OZ,{delay:2,x:"60%",y:"70%",size:10}),e.jsx(OZ,{delay:.5,x:"25%",y:"80%",size:7}),e.jsx(OZ,{delay:1.5,x:"70%",y:"15%",size:5})]}),e.jsxs(Sr.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(Sr.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(Sr.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(Sr.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(Sr.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(Sr.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(Sr.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(Sr.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(Sr.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(Sr.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(Sr.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(Sr.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(Sr.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(Sr.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(Sr.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(Sr.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(_a,{className:"h-3.5 w-3.5"})," Call"]}),d&&e.jsxs(Sr.a,{href:`mailto:${d}`,className:"flex items-center gap-1.5 px-4 py-2 rounded-full bg-slate-100 dark:bg-slate-800 text-xs font-medium text-slate-600 dark:text-slate-300 hover:bg-slate-200 dark:hover:bg-slate-700 transition-colors shadow-sm",whileHover:{scale:1.05},whileTap:{scale:.95},children:[e.jsx(ln,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),e.jsx(Sr.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 zBe({delay:s,x:t,y:n,color:r,size:a}){return e.jsx(Sr.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 zZ({delay:s,x:t,y:n}){return e.jsx(Sr.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 fCt={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 Kor(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=Sz[t],f=fCt[t]||fCt.home_anniversary;return e.jsxs("div",{className:`min-h-screen bg-gradient-to-br ${f.bg} flex items-center justify-center p-4 overflow-hidden relative`,children:[e.jsx(zBe,{delay:0,x:"10%",y:"10%",color:f.orbs[0],size:200}),e.jsx(zBe,{delay:1,x:"70%",y:"60%",color:f.orbs[1],size:180}),e.jsx(zBe,{delay:2,x:"50%",y:"20%",color:f.orbs[2],size:150}),e.jsx(zZ,{delay:0,x:"20%",y:"25%"}),e.jsx(zZ,{delay:.8,x:"75%",y:"15%"}),e.jsx(zZ,{delay:1.6,x:"85%",y:"65%"}),e.jsx(zZ,{delay:2.4,x:"10%",y:"75%"}),e.jsx(zZ,{delay:.4,x:"45%",y:"85%"}),e.jsxs(Sr.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(Sr.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(Sr.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(Sr.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(Sr.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(Sr.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(Sr.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(Sr.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(Sr.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(Sr.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(Sr.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(Jr,{className:"h-3.5 w-3.5"}),r]})]}),h&&e.jsx(Sr.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(Sr.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(Sr.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(Sr.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(Sr.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(Sr.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(_a,{className:"h-3.5 w-3.5"})," Call Me"]}),d&&e.jsxs(Sr.a,{href:`mailto:${d}`,className:"flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-gradient-to-r from-violet-500/30 to-fuchsia-500/30 text-xs font-semibold text-white hover:from-violet-500/50 hover:to-fuchsia-500/50 transition-all border border-white/15 shadow-lg",whileHover:{scale:1.05},whileTap:{scale:.95},children:[e.jsx(ln,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),e.jsx(Sr.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 Yor({emoji:s,delay:t,x:n,duration:r}){return e.jsx(Sr.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 xCt={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 Zor(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=Sz[t],f=xCt[t]||xCt.home_anniversary;return e.jsxs("div",{className:`min-h-screen bg-gradient-to-b ${f.bg} flex items-center justify-center p-4 overflow-hidden relative`,children:[p.emojis.map((y,v)=>e.jsx(Yor,{emoji:y,delay:v*1.2,x:`${15+v*14}%`,duration:5+v%3},v)),e.jsx(Sr.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(Sr.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(Sr.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(Sr.div,{className:`h-28 bg-gradient-to-r ${f.header} relative overflow-hidden`,children:[e.jsx(Sr.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(Sr.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(Sr.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(Sr.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(Sr.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(Sr.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(Sr.div,{className:"mb-3",initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1},transition:{delay:.6},children:e.jsxs("span",{className:`inline-flex items-baseline gap-1.5 ${f.accent}`,children:[e.jsx(Sr.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(Sr.h1,{className:`text-3xl font-bold ${f.accent} mb-1`,initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:.9},children:[p.title.join(" ")," ",p.emojis[4]]}),e.jsxs(Sr.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:1.1},children:[e.jsx("p",{className:`text-lg font-semibold ${f.text} mb-1`,children:n}),r&&e.jsxs("p",{className:`text-sm ${f.text} opacity-70 flex items-center justify-center gap-1 mb-5`,children:[e.jsx(Xa,{className:"h-3 w-3"}),r]})]}),h&&e.jsx(Sr.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(Sr.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(Sr.div,{className:"bg-gradient-to-br from-amber-50 to-orange-50 rounded-2xl p-5 mb-6 border border-amber-100 shadow-inner",initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:1.3},children:e.jsxs("p",{className:`text-sm ${f.text} leading-relaxed italic`,children:['"',i||p.defaultMessage,'"']})}),e.jsxs(Sr.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(Sr.img,{src:o,alt:l,className:"h-12 w-12 rounded-full object-cover ring-2 ring-amber-200 shadow-md",whileHover:{scale:1.1}}):e.jsx("div",{className:`h-12 w-12 rounded-full bg-gradient-to-br ${f.header} flex items-center justify-center shadow-md`,children:e.jsx("span",{className:"text-sm font-bold text-white",children:l.charAt(0)})}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:`text-sm font-bold ${f.accent}`,children:l}),u&&e.jsx("p",{className:`text-xs ${f.text} opacity-60`,children:u})]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-2 mt-4",children:[c&&e.jsxs(Sr.a,{href:`tel:${c}`,className:`flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-gradient-to-r ${f.header} text-xs font-semibold text-white shadow-md`,whileHover:{scale:1.05},whileTap:{scale:.95},children:[e.jsx(_a,{className:"h-3.5 w-3.5"})," Call"]}),d&&e.jsxs(Sr.a,{href:`mailto:${d}`,className:`flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-gradient-to-r ${f.header} text-xs font-semibold text-white shadow-md`,whileHover:{scale:1.05},whileTap:{scale:.95},children:[e.jsx(ln,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),e.jsx(Sr.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 Kde({delay:s,x:t,y:n,size:r,color:a}){return e.jsx(Sr.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 BBe({delay:s,x:t,y:n,size:r}){return e.jsx(Sr.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 gCt={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 Xor(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=Sz[t],f=gCt[t]||gCt.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(Kde,{delay:0,x:"5%",y:"10%",size:300,color:f.mesh[0]}),e.jsx(Kde,{delay:2,x:"60%",y:"50%",size:250,color:f.mesh[1]}),e.jsx(Kde,{delay:4,x:"30%",y:"70%",size:200,color:f.mesh[2]}),e.jsx(Kde,{delay:1,x:"80%",y:"15%",size:180,color:f.mesh[0]}),e.jsx(BBe,{delay:0,x:"15%",y:"20%",size:100}),e.jsx(BBe,{delay:3,x:"70%",y:"60%",size:140}),e.jsx(BBe,{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(Sr.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(Sr.div,{className:`relative rounded-[28px] overflow-hidden backdrop-blur-2xl bg-white/[0.06] border border-white/[0.12] shadow-2xl ${f.glow}`,initial:{scale:.92},animate:{scale:1},transition:{duration:.6,delay:.2,type:"spring",stiffness:120},children:[e.jsx("div",{className:"relative h-[2px] bg-gradient-to-r from-transparent via-white/20 to-transparent overflow-hidden",children:e.jsx(Sr.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(Sr.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(Sr.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(Sr.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(Sr.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(Sr.span,{className:"text-3xl font-black text-white",initial:{opacity:0},animate:{opacity:1},transition:{delay:.8},children:a}),e.jsx("span",{className:`text-[10px] font-bold uppercase tracking-[0.2em] ${f.accent}`,children:a===1?"Year":"Years"})]}),e.jsx(Sr.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(Sr.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(Sr.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(Xa,{className:"h-3 w-3"})," ",r]})]}),e.jsx(Sr.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(Sr.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(Sr.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(Sr.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(Sr.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(Sr.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(Sr.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(_a,{className:"h-3.5 w-3.5"})," Call"]}),d&&e.jsxs(Sr.a,{href:`mailto:${d}`,className:"flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-white/[0.06] border border-white/[0.1] text-xs font-medium text-white/70 hover:bg-white/[0.12] transition-colors backdrop-blur-sm",whileHover:{scale:1.05},whileTap:{scale:.95},children:[e.jsx(ln,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),e.jsx(Sr.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 UBe({delay:s,x:t,angle:n,color:r}){return e.jsx(Sr.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 Yde({delay:s,x:t}){return e.jsx(Sr.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 yCt={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 Qor(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=Sz[t],f=yCt[t]||yCt.home_anniversary;return e.jsxs("div",{className:`min-h-screen bg-gradient-to-b ${f.gradient} flex items-center justify-center p-4 overflow-hidden relative`,children:[e.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(ellipse_at_top,rgba(255,255,255,0.04)_0%,transparent_60%)]"}),e.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(ellipse_at_bottom,rgba(0,0,0,0.6)_0%,transparent_60%)]"}),e.jsx(UBe,{delay:0,x:"20%",angle:15,color:f.stripe}),e.jsx(UBe,{delay:2,x:"75%",angle:-12,color:f.stripe}),e.jsx(UBe,{delay:4,x:"50%",angle:5,color:f.stripe}),e.jsx(Yde,{delay:0,x:"30%"}),e.jsx(Yde,{delay:1.5,x:"60%"}),e.jsx(Yde,{delay:3,x:"45%"}),e.jsx(Yde,{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(Sr.div,{className:"w-full max-w-md relative z-10",initial:{opacity:0},animate:{opacity:1},transition:{duration:1.2},children:[e.jsx(Sr.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(Sr.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(Sr.div,{className:`h-20 w-20 mx-auto rounded-2xl bg-gradient-to-br ${f.accent} flex items-center justify-center shadow-2xl`,animate:{boxShadow:["0 0 40px rgba(255,255,255,0.05)","0 0 80px rgba(255,255,255,0.1)","0 0 40px rgba(255,255,255,0.05)"]},transition:{duration:3,repeat:1/0,ease:"easeInOut"},children:e.jsx("span",{className:"text-4xl",children:p.icon})})}),t==="home_anniversary"&&a!==null&&a>0&&e.jsxs(Sr.div,{className:"mb-6",initial:{opacity:0},animate:{opacity:1},transition:{delay:.7},children:[e.jsx(Sr.span,{className:`text-6xl font-black bg-gradient-to-r ${f.accent} bg-clip-text text-transparent`,initial:{scale:.5,opacity:0},animate:{scale:1,opacity:1},transition:{delay:.9,type:"spring"},children:a}),e.jsx("p",{className:"text-[10px] font-bold uppercase tracking-[0.4em] text-white/30 mt-1",children:a===1?"Year":"Years"})]}),e.jsx("div",{className:"overflow-hidden mb-2",children:e.jsx(Sr.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(Sr.h2,{className:`text-5xl font-black bg-gradient-to-r ${f.accent} bg-clip-text text-transparent`,initial:{y:"100%"},animate:{y:0},transition:{duration:.7,delay:.95,ease:[.16,1,.3,1]},children:p.title[1]})}),e.jsxs(Sr.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(Xa,{className:"h-3 w-3"})," ",r]})]}),e.jsxs(Sr.div,{className:"flex items-center justify-center gap-3 my-8",initial:{opacity:0},animate:{opacity:1},transition:{delay:1.2},children:[e.jsx(Sr.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(Sr.span,{className:"text-white/10 text-xs",animate:{rotate:[0,360]},transition:{duration:20,repeat:1/0,ease:"linear"},children:"✦"}),e.jsx(Sr.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(Sr.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(Sr.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(Sr.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(Sr.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(Sr.img,{src:o,alt:l,className:"h-12 w-12 rounded-full object-cover ring-2 ring-white/10 shadow-xl",whileHover:{scale:1.1}}):e.jsx("div",{className:`h-12 w-12 rounded-full bg-gradient-to-br ${f.accent} flex items-center justify-center shadow-xl`,children:e.jsx("span",{className:"text-sm font-bold text-slate-900",children:l.charAt(0)})}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"text-sm font-medium text-white/70",children:l}),u&&e.jsx("p",{className:"text-[11px] text-white/25",children:u})]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-2",children:[c&&e.jsxs(Sr.a,{href:`tel:${c}`,className:`flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-gradient-to-r ${f.accent} text-xs font-semibold text-slate-900 shadow-lg`,whileHover:{scale:1.05,boxShadow:"0 10px 40px rgba(255,255,255,0.15)"},whileTap:{scale:.95},children:[e.jsx(_a,{className:"h-3.5 w-3.5"})," Call"]}),d&&e.jsxs(Sr.a,{href:`mailto:${d}`,className:"flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-white/[0.06] border border-white/[0.1] text-xs font-medium text-white/60 hover:bg-white/[0.12] transition-colors",whileHover:{scale:1.05},whileTap:{scale:.95},children:[e.jsx(ln,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})}),e.jsx(Sr.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 xas(){const{shareToken:s}=Li(),{data:t,isLoading:n,error:r}=at({queryKey:["public-sendable-card",s],queryFn:async()=>{const{data:l,error:o}=await q.from("sendable_cards").select("*").eq("share_token",s).single();if(o)throw o;return l},enabled:!!s});if(_.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]),_.useEffect(()=>{s&&q.rpc("log_sendable_card_view",{p_share_token:s}).then(({error:l})=>{l&&console.error("Error tracking view:",l)})},[s]),n)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsxs("div",{className:"animate-pulse space-y-4 text-center",children:[e.jsx("div",{className:"h-8 w-48 bg-muted rounded mx-auto"}),e.jsx("div",{className:"h-4 w-32 bg-muted rounded mx-auto"})]})});if(r||!t)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Card not found"}),e.jsx("p",{className:"text-muted-foreground",children:"This card may have been removed or the link is invalid."})]})});const a=t.home_anniversary_date?Math.floor((Date.now()-Ru(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(Kor,{...i});case"warm":return e.jsx(Zor,{...i});case"glass":return e.jsx(Xor,{...i});case"cinematic":return e.jsx(Qor,{...i});case"elegant":default:return e.jsx(Wor,{...i})}}function Jor(){const s=ha();return at({queryKey:["drip-settings",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("drip_settings").select("*").eq("user_id",s).maybeSingle();if(n)throw n;return t},enabled:!!s})}function elr(){const s=ha(),t=Bt();return mt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r}=await q.from("drip_settings").select("id").eq("user_id",s).maybeSingle();if(r){const{data:a,error:i}=await q.from("drip_settings").update(n).eq("user_id",s).select().single();if(i)throw i;return a}else{const{data:a,error:i}=await q.from("drip_settings").insert({user_id:s,is_globally_enabled:n.is_globally_enabled??!1,append_signature:n.append_signature??!0}).select().single();if(i)throw i;return a}},onSuccess:()=>{t.invalidateQueries({queryKey:["drip-settings"]})}})}function tlr(){const s=Fn(),{isGmailConnected:t,gmailEmail:n}=Vg(),{data:r,isLoading:a}=Jor(),i=elr(),[l,o]=_.useState(!1),[c,d]=_.useState(!0),[u,h]=_.useState(!1);_.useEffect(()=>{r&&(o(r.is_globally_enabled),d(r.append_signature))},[r]);const m=async f=>{if(f&&!t){se.error("Connect your Gmail account first before enabling Smart Drips");return}o(f);try{await i.mutateAsync({is_globally_enabled:f}),se.success(f?"Smart Drips enabled globally":"Smart Drips paused globally")}catch{o(!f),se.error("Failed to update settings")}},p=async f=>{d(f);try{await i.mutateAsync({append_signature:f}),se.success(f?"Signature will be appended to drip emails":"Signature disabled for drip emails")}catch{d(!f),se.error("Failed to update settings")}};return e.jsxs(Ls,{open:u,onOpenChange:h,children:[e.jsx(nl,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"gap-1.5",children:[e.jsx(qc,{className:"h-3.5 w-3.5"}),"Settings"]})}),e.jsxs(Ps,{className:"sm:max-w-md",children:[e.jsxs(Os,{children:[e.jsxs(Ds,{className:"flex items-center gap-2",children:[e.jsx(qc,{className:"h-5 w-5 text-primary"}),"Smart Drip Settings"]}),e.jsx(_r,{children:"Configure how your automated drip emails are sent."})]}),e.jsxs("div",{className:"space-y-5 pt-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Email Connection"}),e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border bg-muted/30",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`p-2 rounded-full ${t?"bg-emerald-500/10":"bg-destructive/10"}`,children:e.jsx(ln,{className:`h-4 w-4 ${t?"text-emerald-600":"text-destructive"}`})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:t?"Gmail Connected":"Gmail Not Connected"}),n&&e.jsx("p",{className:"text-xs text-muted-foreground",children:n})]})]}),t?e.jsxs(Oe,{variant:"outline",className:"gap-1 text-emerald-600 border-emerald-200 bg-emerald-500/10 text-[10px]",children:[e.jsx(Er,{className:"h-3 w-3"}),"Active"]}):e.jsxs(B,{variant:"outline",size:"sm",className:"text-xs gap-1",onClick:()=>{h(!1),s("/mission-control/integrations")},children:[e.jsx(wr,{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(wc,{}),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(tJ,{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(fn,{checked:l,onCheckedChange:m,disabled:a||i.isPending})]}),e.jsx(wc,{}),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(V2,{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(fn,{checked:c,onCheckedChange:p,disabled:a||i.isPending})]}),c&&e.jsxs(B,{variant:"ghost",size:"sm",className:"w-full text-xs text-muted-foreground",onClick:()=>{h(!1),s("/profile")},children:[e.jsx(V2,{className:"h-3 w-3 mr-1"}),"Edit your email signature in Profile settings"]})]})]})]})}function slr(){const s=ha();return at({queryKey:["drip-templates",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("drip_templates").select("*").or(`owner_user_id.eq.${s},is_starter.eq.true`).order("sort_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function nlr(){const s=ha();return at({queryKey:["drip-pipeline-stages",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("deal_pipeline_stages").select("*").eq("owner_user_id",s).order("sort_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function rlr(){const s=ha(),t=Bt();return mt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("drip_templates").insert({owner_user_id:s,stage_id:n.stage_id,title:n.title||"",subject:n.subject||"",body:n.body||"",video_url:n.video_url||null,channel:n.channel||"email",delay_type:n.delay_type||"instant",delay_minutes:n.delay_minutes||0,is_enabled:!1,deal_type:n.deal_type||null,sort_order:n.sort_order||0}).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["drip-templates"]})}})}function alr(){const s=Bt();return mt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("drip_templates").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["drip-templates"]})}})}function ilr(){const s=Bt();return mt({mutationFn:async t=>{const{error:n}=await q.from("drip_templates").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["drip-templates"]})}})}function olr(){const s=ha(),t=Bt();return mt({mutationFn:async({templateId:n,stageId:r})=>{if(!s)throw new Error("Not authenticated");const{data:a,error:i}=await q.from("drip_templates").select("*").eq("id",n).single();if(i)throw i;const{data:l,error:o}=await q.from("drip_templates").insert({owner_user_id:s,stage_id:r,title:a.title,subject:a.subject,body:a.body,video_url:a.video_url,channel:a.channel,delay_type:a.delay_type,delay_minutes:a.delay_minutes,is_enabled:!1,is_starter:!1,deal_type:a.deal_type}).select().single();if(o)throw o;return l},onSuccess:()=>{t.invalidateQueries({queryKey:["drip-templates"]})}})}const llr=[{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"}],qBe=1e3;function gas({open:s,onOpenChange:t,campaignId:n,campaignName:r,birthdayFocused:a,onSuccess:i}){const l=ha(),o=jnt(),[c,d]=_.useState(""),[u,h]=_.useState(!!a),[m,p]=_.useState(new Set),{data:f,isLoading:y}=at({queryKey:["campaign-contact-picker",l],queryFn:async()=>{const M=[];for(let I=0;;I+=qBe){const{data:D,error:O}=await q.from("innercircle_contacts").select("id, first_name, last_name, email, birthday").eq("owner_user_id",l).order("first_name").range(I,I+qBe-1);if(O)throw O;if(M.push(...D||[]),!D||D.length{const{data:M,error:I}=await q.from("drip_campaign_enrollments").select("contact_id, status").eq("campaign_id",n);if(I)throw I;return new Set((M||[]).filter(D=>D.status==="active"||D.status==="paused").map(D=>D.contact_id))},enabled:s&&!!n}),g=_.useMemo(()=>{const M=c.trim().toLowerCase();return(f||[]).filter(I=>u&&!I.birthday?!1:M?`${I.first_name||""} ${I.last_name||""}`.toLowerCase().includes(M)||(I.email||"").toLowerCase().includes(M):!0)},[f,c,u]),b=g.filter(M=>!(v!=null&&v.has(M.id))).map(M=>M.id),j=b.length>0&&b.every(M=>m.has(M)),S=M=>{p(I=>{const D=new Set(I);return D.has(M)?D.delete(M):D.add(M),D})},C=()=>{p(M=>{if(j){const I=new Set(M);return b.forEach(D=>I.delete(D)),I}return new Set([...M,...b])})},E=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`),se.success(I.join(" · ")),p(new Set),t(!1),i==null||i()}catch(M){se.error(M.message||"Failed to add contacts")}},P=(f||[]).filter(M=>M.birthday).length;return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"max-w-lg max-h-[85vh] flex flex-col p-0 overflow-hidden",children:[e.jsxs(Os,{className:"p-5 pb-3 border-b shrink-0 text-left",children:[e.jsxs(Ds,{className:"flex items-center gap-2",children:[e.jsx(In,{className:"h-4 w-4 text-primary"}),"Add contacts — ",r||"Campaign"]}),e.jsxs(_r,{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(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search contacts by name or email...",value:c,onChange:M=>d(M.target.value),className:"pl-9 h-9"})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[e.jsxs("label",{className:"flex items-center gap-2 text-xs text-muted-foreground cursor-pointer",children:[e.jsx($a,{checked:u,onCheckedChange:M=>h(!!M)}),e.jsx(Bf,{className:"h-3.5 w-3.5 text-primary"}),"Only contacts with a birthday on file (",P,")"]}),e.jsx(B,{variant:"ghost",size:"sm",className:"text-xs h-7",onClick:C,disabled:b.length===0,children:j?"Clear all":`Select all ${b.length}`})]})]}),e.jsx("div",{className:"flex-1 min-h-0 px-5 py-3",children:e.jsx(Ji,{className:"h-[320px] -mx-1 px-1",children:y?e.jsx("div",{className:"text-center py-10 text-sm text-muted-foreground",children:"Loading contacts..."}):g.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:g.map(M=>{const I=v==null?void 0:v.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($a,{checked:I?!0:m.has(M.id),disabled:I,onCheckedChange:()=>S(M.id)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:[M.first_name,M.last_name].filter(Boolean).join(" ")||"Unnamed contact"}),e.jsxs("div",{className:"flex items-center gap-3 text-[11px] text-muted-foreground",children:[M.email&&e.jsxs("span",{className:"flex items-center gap-1 truncate",children:[e.jsx(ln,{className:"h-2.5 w-2.5"}),M.email]}),M.birthday&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Bf,{className:"h-2.5 w-2.5"}),M.birthday]})]})]}),I&&e.jsx(Oe,{variant:"outline",className:"text-[9px]",children:"In campaign"})]},M.id)})})})}),e.jsxs(yr,{className:"p-4 border-t shrink-0 gap-2 sm:gap-2",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{onClick:E,disabled:m.size===0||o.isPending,children:[o.isPending&&e.jsx(Ct,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),"Add ",m.size||""," contact",m.size===1?"":"s"]})]})]})})}function clr({open:s,onOpenChange:t,campaignId:n,campaignName:r}){const{data:a,isLoading:i}=JDn(n||void 0),l=tRn(),o=jnt(),[c,d]=_.useState(!1),u=async(p,f)=>{try{await l.mutateAsync({id:p,status:f}),se.success(`Enrollment ${f}`)}catch{se.error("Failed to update")}},h=async p=>{if(n)try{const f=await o.mutateAsync({campaignId:n,contactIds:[p]});f.enrolled>0?se.success("Contact re-enrolled — first email queued"):f.skipped>0?se.message("Already active in this campaign"):se.error("Could not re-enroll")}catch{se.error("Failed to re-enroll")}},m=p=>{const f={active:"bg-emerald-500/10 text-emerald-600 border-emerald-200",paused:"bg-amber-500/10 text-amber-600 border-amber-200",completed:"bg-blue-500/10 text-blue-600 border-blue-200",exited:"bg-muted text-muted-foreground"};return e.jsx(Oe,{variant:"outline",className:`text-[10px] capitalize ${f[p]||""}`,children:p})};return e.jsxs(Ls,{open:s,onOpenChange:t,children:[e.jsxs(Ps,{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(Ds,{className:"flex items-center gap-2",children:[e.jsx(In,{className:"h-4 w-4 text-primary"}),"Enrollments — ",r||"Campaign"]}),e.jsx(_r,{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(B,{size:"sm",variant:"outline",onClick:()=>d(!0),children:[e.jsx(Pl,{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(cn,{className:"h-14"},p))}):!a||a.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(In,{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(B,{size:"sm",onClick:()=>d(!0),children:[e.jsx(Pl,{className:"h-3.5 w-3.5 mr-1.5"})," Add contacts"]})]}):e.jsx("div",{className:"space-y-2",children:a.map(p=>{var f,y,v,g;return e.jsxs("div",{className:"flex items-center gap-3 p-3 border rounded-lg bg-card",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("p",{className:"font-medium text-sm truncate",children:[(f=p.contact)==null?void 0:f.first_name," ",(y=p.contact)==null?void 0:y.last_name]}),m(p.status)]}),e.jsxs("div",{className:"flex items-center gap-3 text-[11px] text-muted-foreground mt-0.5",children:[((v=p.contact)==null?void 0:v.email)&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ln,{className:"h-2.5 w-2.5"})," ",p.contact.email]}),e.jsxs("span",{children:["Step ",p.current_step]}),p.next_send_at&&p.status==="active"&&e.jsxs("span",{children:["Next: ",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(B,{size:"sm",variant:"ghost",onClick:()=>u(p.id,"paused"),title:"Pause",children:e.jsx(ky,{className:"h-3.5 w-3.5"})}),p.status==="paused"&&e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>u(p.id,"active"),title:"Resume",children:e.jsx(Jd,{className:"h-3.5 w-3.5"})}),(p.status==="active"||p.status==="paused")&&e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>u(p.id,"exited"),title:"Exit",children:e.jsx(Qn,{className:"h-3.5 w-3.5 text-destructive"})}),(p.status==="exited"||p.status==="completed")&&((g=p.contact)==null?void 0:g.id)&&e.jsxs(B,{size:"sm",variant:"outline",className:"h-7 text-[11px] gap-1",onClick:()=>h(p.contact.id),disabled:o.isPending,children:[e.jsx(Tx,{className:"h-3 w-3"}),"Re-enroll"]})]},p.id)})})})})]}),e.jsx(gas,{open:c,onOpenChange:d,campaignId:n,campaignName:r,birthdayFocused:/birthday/i.test(r||"")})]})}function dlr(){var C,E,P;const{data:s,isLoading:t}=Dae(),{hasLeadSite:n}=lf(),r=wnt(),a=YDn(),i=kYt(),[l,o]=_.useState(null),[c,d]=_.useState(!1),[u,h]=_.useState(null),[m,p]=_.useState(null),[f,y]=_.useState(null),v=(s||[]).filter(M=>!M.is_starter),g=(s||[]).filter(M=>M.is_starter).filter(M=>!M.requires_lead_site||n),b=async M=>{try{await r.mutateAsync(M),se.success("Campaign added to your library — customize and activate it!"),o(null)}catch(I){se.error(I.message||"Failed to copy campaign")}},j=async M=>{try{await i.mutateAsync({id:M.id,is_active:!M.is_active}),se.success(M.is_active?"Campaign paused":"Campaign activated")}catch{se.error("Failed to update")}},S=async M=>{if(await Xi("Delete this campaign? Active enrollments will be removed."))try{await a.mutateAsync(M),se.success("Campaign deleted")}catch{se.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(cn,{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(hS,{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(ku,{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(Or,{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(In,{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(B,{size:"sm",onClick:()=>{h(null),d(!0)},children:[e.jsx(rn,{className:"h-3.5 w-3.5 mr-1.5"})," New Campaign"]})]}),v.length===0?e.jsxs("div",{className:"text-center py-10 border border-dashed rounded-xl bg-muted/20",children:[e.jsx(un,{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(B,{size:"sm",onClick:()=>{h(null),d(!0)},children:[e.jsx(rn,{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:v.map(M=>e.jsx(ulr,{campaign:M,onPreview:()=>o(M.id),onToggleActive:()=>j(M),onDelete:()=>S(M.id),onEdit:()=>{h(M.id),d(!0)},onViewEnrollments:()=>p(M.id),onAddContacts:()=>y(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(un,{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(Oe,{variant:"outline",className:"text-[10px]",children:[g.length," templates"]})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:g.map(M=>e.jsx(hlr,{campaign:M,onPreview:()=>o(M.id)},M.id))})]}),e.jsx(gas,{open:!!f,onOpenChange:M=>!M&&y(null),campaignId:f,campaignName:(C=v.find(M=>M.id===f))==null?void 0:C.name,birthdayFocused:/birthday/i.test(((E=v.find(M=>M.id===f))==null?void 0:E.name)||"")}),e.jsx(mlr,{campaignId:l,open:!!l,onOpenChange:M=>!M&&o(null),onClone:b,isCloning:r.isPending,onEdit:M=>{o(null),h(M),d(!0)}}),e.jsx(EYt,{open:c,onOpenChange:d,campaignId:u}),e.jsx(clr,{open:!!m,onOpenChange:M=>!M&&p(null),campaignId:m,campaignName:(P=v.find(M=>M.id===m))==null?void 0:P.name})]})}function ulr({campaign:s,onPreview:t,onToggleActive:n,onDelete:r,onEdit:a,onViewEnrollments:i,onAddContacts:l}){const c=eRn(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(Oe,{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(Oe,{variant:"outline",className:"text-[9px] mt-2",children:ZIe[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(xl,{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(B,{size:"sm",className:"w-full h-8 text-xs mt-3",onClick:l,children:[e.jsx(Pl,{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(B,{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(B,{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 hlr({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(Oe,{className:"absolute top-2 right-2 bg-white/90 text-foreground hover:bg-white text-[10px]",children:[e.jsx(un,{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(Oe,{variant:"outline",className:"text-[9px] mt-2",children:ZIe[s.category]})]})]})}function mlr({campaignId:s,open:t,onOpenChange:n,onClone:r,isCloning:a,onEdit:i}){const{data:l}=Dae(),{data:o}=SYt(s||void 0),[c,d]=_.useState(new Set),u=l==null?void 0:l.find(p=>p.id===s);if(!u)return null;const h=p=>{d(f=>{const y=new Set(f);return y.has(p)?y.delete(p):y.add(p),y})},m=(p,f)=>{if(p.delay_type==="calendar_anchor"){const v=p.anchor_field==="birthday"?"birthday":"home anniversary",g=p.anchor_offset_days||0;return g===0?`On their ${v}`:g<0?`${Math.abs(g)} days before ${v}`:`${g} days after ${v}`}if(f===0&&p.delay_days===0&&p.delay_hours===0)return"Sends immediately";const y=[];return p.delay_days&&y.push(`${p.delay_days}d`),p.delay_hours&&y.push(`${p.delay_hours}h`),f===0?`After ${y.join(" ")}`:`+${y.join(" ")}`};return e.jsx(Ls,{open:t,onOpenChange:n,children:e.jsxs(Ps,{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(Ds,{className:"text-xl font-bold text-white",children:u.name}),e.jsx(_r,{className:"text-white/90 mt-1",children:u.description}),e.jsxs("div",{className:"flex gap-2 mt-3",children:[e.jsx(Oe,{className:"bg-white/20 text-white border-white/20 hover:bg-white/20",children:ZIe[u.category]}),e.jsxs(Oe,{className:"bg-white/20 text-white border-white/20 hover:bg-white/20",children:[(o==null?void 0:o.length)||0," step",(o==null?void 0:o.length)!==1?"s":""]})]})]})]})}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:e.jsxs("div",{className:"p-6 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"The sequence"}),u.is_starter?e.jsx("span",{className:"text-[10px] text-muted-foreground italic",children:"Copy to your library to edit"}):e.jsx("span",{className:"text-[10px] text-muted-foreground italic",children:"Tap a step to expand · Edit to customize"})]}),o==null?void 0:o.map((p,f)=>{const y=c.has(p.id);return e.jsxs("div",{className:"flex gap-3",children:[e.jsxs("div",{className:"shrink-0 flex flex-col items-center",children:[e.jsx("div",{className:"h-8 w-8 rounded-full bg-primary/10 text-primary flex items-center justify-center text-xs font-semibold",children:f+1}),fh(p.id),className:"flex-1 pb-4 text-left",children:e.jsxs("div",{className:"border rounded-lg p-3 bg-muted/20 hover:bg-muted/30 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1.5 text-xs text-muted-foreground",children:[p.delay_type==="calendar_anchor"?e.jsx(ga,{className:"h-3 w-3"}):e.jsx(Gr,{className:"h-3 w-3"}),e.jsx("span",{children:m(p,f)}),e.jsx("span",{children:"·"}),e.jsx(ln,{className:"h-3 w-3"}),e.jsx("span",{className:"capitalize",children:p.channel})]}),e.jsx("p",{className:"font-medium text-sm",children:p.subject}),(()=>{const v=p.body||"",g=/<\/?[a-z][\s\S]*>/i.test(v),b=g?v.replace(//gi,"").replace(/<[^>]+>/g," ").replace(/ /g," ").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/\s+/g," ").trim():v;return y?g?e.jsx("div",{className:"text-xs text-foreground mt-2 prose prose-sm max-w-none [&_a]:text-primary",dangerouslySetInnerHTML:{__html:v}}):e.jsx("p",{className:"text-xs text-muted-foreground mt-2 whitespace-pre-line",children:v}):e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-1",children:b})})(),p.body&&p.body.length>160&&e.jsx("span",{className:"text-[10px] text-primary mt-1.5 inline-block",children:y?"Show less":"Show full email"})]})})]},p.id)})]})}),e.jsxs(yr,{className:"border-t p-4 shrink-0",children:[e.jsx(B,{variant:"outline",onClick:()=>n(!1),children:"Close"}),!u.is_starter&&i&&e.jsxs(B,{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(B,{onClick:()=>r(u.id),disabled:a,children:[a?e.jsx(Ct,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(Ia,{className:"h-3.5 w-3.5 mr-1.5"}),"Copy to my campaigns"]})]})]})})}const JCe=[{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 plr(){const s=ha();return at({queryKey:["drip-auto-rules",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("drip_auto_enroll_rules").select("*, campaign:drip_campaigns(id, name, category, cover_color)").eq("owner_user_id",s).order("created_at",{ascending:!0});if(n)throw n;return t||[]},enabled:!!s})}function flr(){const s=ha(),t=Bt();return mt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const r={owner_user_id:s,campaign_id:n.campaign_id,trigger_type:n.trigger_type,lead_days:n.lead_days??14,filter_tags:n.filter_tags??[],filter_relationship_types:n.filter_relationship_types??[],require_email:n.require_email??!0,is_active:n.is_active??!0};n.id&&(r.id=n.id);const{data:a,error:i}=await q.from("drip_auto_enroll_rules").upsert(r).select().single();if(i)throw i;return a},onSuccess:()=>{t.invalidateQueries({queryKey:["drip-auto-rules"]})}})}function xlr(){const s=Bt();return mt({mutationFn:async({id:t,is_active:n})=>{const{error:r}=await q.from("drip_auto_enroll_rules").update({is_active:n}).eq("id",t);if(r)throw r},onSuccess:()=>s.invalidateQueries({queryKey:["drip-auto-rules"]})})}function glr(){const s=Bt();return mt({mutationFn:async t=>{const{error:n}=await q.from("drip_auto_enroll_rules").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["drip-auto-rules"]})})}function ylr(s=25){const t=ha();return at({queryKey:["drip-auto-log",t,s],queryFn:async()=>{if(!t)return[];const{data:n,error:r}=await q.from("drip_auto_enroll_log").select("*, contact:innercircle_contacts(id, first_name, last_name, email)").eq("owner_user_id",t).order("created_at",{ascending:!1}).limit(s);if(r)throw r;return n||[]},enabled:!!t})}function vlr(){const s=ha();return at({queryKey:["life-event-coverage",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("innercircle_contacts").select("birthday, home_anniversary, spouse_birthday, wedding_anniversary, email").eq("owner_user_id",s).limit(1e4);if(n)throw n;const r=t||[],a=(l,o)=>{if(!l)return!1;const[,c,d]=String(l).split("-").map(Number),u=new Date;let h=new Date(u.getFullYear(),c-1,d);return h{const o=r.filter(c=>!!c[l.column]);i[l.value]={total:o.length,upcoming30:o.filter(c=>a(c[l.column],30)).length}}),{totalContacts:r.length,counts:i}},enabled:!!s})}function blr(){const s=Bt();return mt({mutationFn:async t=>{const{data:n,error:r}=await q.functions.invoke("process-life-event-drips",{body:t?{rule_id:t}:{}});if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["drip-auto-rules"]}),s.invalidateQueries({queryKey:["drip-auto-log"]}),s.invalidateQueries({queryKey:["drip-campaign-enrollments"]})}})}const _lr={birthday:Bf,home_anniversary:dS,spouse_birthday:Vo,wedding_anniversary:Do};function wlr(){var S;const{data:s,isLoading:t}=plr(),{data:n}=Dae(),{data:r}=vlr(),{data:a}=ylr(10),i=flr(),l=xlr(),o=glr(),c=blr(),d=wnt(),[u,h]=_.useState(null),m=_.useMemo(()=>(n||[]).filter(C=>!C.is_starter),[n]),p={birthday:"Birthday",home_anniversary:"Home Anniversary",spouse_birthday:"Spouse Birthday",wedding_anniversary:"Wedding Anniversary"},f=_.useMemo(()=>{if(!(u!=null&&u.trigger_type))return null;const C=p[u.trigger_type];return!C||m.some(P=>String(P.name||"").toLowerCase().includes(C.toLowerCase()))?null:(n||[]).find(P=>P.is_starter&&String(P.name||"").toLowerCase()===C.toLowerCase())??null},[n,m,u==null?void 0:u.trigger_type]),y=async()=>{if(f)try{const C=await d.mutateAsync(f.id);h(E=>({...E,campaign_id:C.id})),se.success(`“${f.name}” template added to your campaigns`)}catch(C){se.error((C==null?void 0:C.message)||"Could not copy the template")}},v=C=>(s||[]).find(E=>E.trigger_type===C),g=async()=>{if(!(u!=null&&u.campaign_id)||!(u!=null&&u.trigger_type)){se.error("Pick a campaign first");return}try{await i.mutateAsync(u),se.success("Autopilot rule saved"),h(null)}catch(C){se.error((C==null?void 0:C.message)||"Could not save rule")}},b=async()=>{try{const C=await c.mutateAsync(void 0);se.success(C!=null&&C.enrolled?`Enrolled ${C.enrolled} contact${C.enrolled===1?"":"s"} with upcoming life events`:"All caught up — nobody new to enroll right now")}catch(C){se.error((C==null?void 0:C.message)||"Autopilot run failed")}},j=(s||[]).filter(C=>C.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(un,{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(B,{variant:"outline",onClick:b,disabled:c.isPending||j===0,className:"gap-2 shrink-0",children:[c.isPending?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(uo,{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:JCe.map(C=>{const E=r.counts[C.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:[C.emoji," ",C.label]}),e.jsx("p",{className:"text-lg font-bold leading-tight",children:(E==null?void 0:E.total)??0}),e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:[(E==null?void 0:E.upcoming30)??0," in next 30 days"]})]},C.value)})})]}),t?e.jsx("div",{className:"flex justify-center py-10",children:e.jsx(Ct,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):e.jsx("div",{className:"grid sm:grid-cols-2 gap-3",children:JCe.map(C=>{var I;const E=v(C.value),P=_lr[C.value]||Bf,M=r==null?void 0:r.counts[C.value];return e.jsxs("div",{className:At("rounded-xl border bg-card p-4 transition-colors",(E==null?void 0:E.is_active)&&"border-primary/40 bg-primary/[0.03]"),children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:At("h-10 w-10 rounded-lg flex items-center justify-center shrink-0",E!=null&&E.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:C.label}),(E==null?void 0:E.is_active)&&e.jsx(Oe,{className:"text-[10px] bg-primary/10 text-primary hover:bg-primary/10",children:"On"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:E?`${((I=E.campaign)==null?void 0:I.name)??"Campaign"} · starts ${E.lead_days} days before`:C.description}),E&&E.total_enrolled>0&&e.jsxs("p",{className:"text-[11px] text-muted-foreground mt-1",children:[E.total_enrolled," contact",E.total_enrolled===1?"":"s"," enrolled so far"]}),!E&&((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."})]}),E?e.jsx(fn,{checked:E.is_active,onCheckedChange:D=>l.mutate({id:E.id,is_active:D})}):null]}),e.jsxs("div",{className:"flex gap-2 mt-3",children:[e.jsxs(B,{size:"sm",variant:E?"outline":"default",className:"flex-1 gap-1.5",onClick:()=>h(E??{trigger_type:C.value,lead_days:C.value==="birthday"?7:14,require_email:!0,is_active:!0,filter_tags:[],filter_relationship_types:[]}),children:[E?e.jsx(nf,{className:"h-3.5 w-3.5"}):e.jsx(rn,{className:"h-3.5 w-3.5"}),E?"Edit rule":"Turn on autopilot"]}),E&&e.jsx(B,{size:"sm",variant:"ghost",className:"text-muted-foreground hover:text-destructive",onClick:()=>o.mutate(E.id),children:e.jsx(Sn,{className:"h-3.5 w-3.5"})})]})]},C.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(C=>{var E,P;return e.jsxs("div",{className:"flex items-center gap-3 px-4 py-2.5",children:[e.jsx(ea,{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:[(E=C.contact)==null?void 0:E.first_name," ",(P=C.contact)==null?void 0:P.last_name]}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[String(C.trigger_type).replace(/_/g," ")," · ",C.note]})]}),e.jsx("span",{className:"text-[11px] text-muted-foreground shrink-0",children:new Date(C.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric"})})]},C.id)})})]}),e.jsx(Ls,{open:!!u,onOpenChange:C=>!C&&h(null),children:e.jsxs(Ps,{className:"sm:max-w-md",children:[e.jsxs(Os,{children:[e.jsxs(Ds,{children:[(S=JCe.find(C=>C.value===(u==null?void 0:u.trigger_type)))==null?void 0:S.label," autopilot"]}),e.jsx(_r,{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(J,{children:"Campaign to enroll into"}),e.jsxs(is,{value:(u==null?void 0:u.campaign_id)??"",onValueChange:C=>h(E=>({...E,campaign_id:C})),children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Select one of your campaigns"})}),e.jsx(as,{children:m.map(C=>e.jsx(He,{value:C.id,children:C.name},C.id))})]}),f&&e.jsx("div",{className:"rounded-lg border border-primary/25 bg-primary/5 p-3",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(un,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"text-sm font-medium leading-tight",children:["Use the LevelUp “",f.name,"” template"]}),e.jsx("p",{className:"mt-0.5 text-xs text-muted-foreground",children:"Beautifully designed, personalized emails written for this moment. We'll copy it into your campaigns so you can edit anything you like."}),e.jsxs(B,{size:"sm",variant:"outline",className:"mt-2 gap-1.5",disabled:d.isPending,onClick:y,children:[d.isPending?e.jsx(Ct,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(rn,{className:"h-3.5 w-3.5"}),"Use this template"]})]})]})}),m.length===0&&!f&&e.jsx("p",{className:"text-xs text-amber-600 dark:text-amber-400",children:"You need one of your own campaigns first — clone a starter from the Campaigns tab."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(J,{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(kx,{min:0,max:45,step:1,value:[(u==null?void 0:u.lead_days)??14],onValueChange:([C])=>h(E=>({...E,lead_days:C}))}),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(J,{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(fn,{checked:(u==null?void 0:u.require_email)??!0,onCheckedChange:C=>h(E=>({...E,require_email:C}))})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(J,{className:"text-sm",children:"Autopilot active"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Runs every morning automatically."})]}),e.jsx(fn,{checked:(u==null?void 0:u.is_active)??!0,onCheckedChange:C=>h(E=>({...E,is_active:C}))})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"ghost",onClick:()=>h(null),children:"Cancel"}),e.jsxs(B,{onClick:g,disabled:i.isPending||!(u!=null&&u.campaign_id),children:[i.isPending&&e.jsx(Ct,{className:"h-4 w-4 mr-1.5 animate-spin"}),"Save rule"]})]})]})})]})}function jlr(){const s=ha(),t=Fn(),{isGmailConnected:n,gmailEmail:r,isLoading:a}=Vg(),{data:i,isLoading:l}=slr(),{data:o,isLoading:c}=nlr(),d=rlr(),u=alr(),h=ilr(),m=olr(),[p,f]=_.useState(null),[y,v]=_.useState(null),g=(i==null?void 0:i.filter(I=>!I.is_starter&&I.owner_user_id===s))||[],b=(i==null?void 0:i.filter(I=>I.is_starter))||[],j=I=>g.filter(D=>D.stage_id===I),S=async I=>{try{await u.mutateAsync({id:I.id,is_enabled:!I.is_enabled}),se.success(I.is_enabled?"Drip disabled":"Drip enabled")}catch{se.error("Failed to update")}},C=async I=>{try{const D=o==null?void 0:o.find(O=>O.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}),f(I),se.success("Drip template created")}catch{se.error("Failed to create template")}},E=async I=>{try{await h.mutateAsync(I),se.success("Template deleted")}catch{se.error("Failed to delete")}},P=async I=>{if(!o||o.length===0){se.error("No pipeline stages found");return}const D=o[0].id;try{await m.mutateAsync({templateId:I,stageId:D}),se.success("Template copied to your drips!")}catch{se.error("Failed to copy template")}},M=l||c;return e.jsx(zs,{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(nf,{className:"h-5 w-5 text-primary"}),e.jsx("h1",{className:"text-2xl font-bold",children:"Smart Drips"}),e.jsx(Oe,{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(tlr,{})]}),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(hS,{className:"h-4 w-4 text-primary mt-0.5 shrink-0"}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[e.jsx("p",{className:"font-medium text-foreground mb-1",children:"How it works"}),e.jsxs("p",{children:["When a deal moves to a new stage in your pipeline, Smart Drips automatically sends your pre-written email to the client. Nothing sends until you create a template ",e.jsx("strong",{children:"and"})," toggle it on."]})]})]}),!a&&(n?e.jsxs("div",{className:"bg-emerald-500/5 border border-emerald-500/20 rounded-xl p-4 mb-6 flex items-start gap-3",children:[e.jsx(ln,{className:"h-4 w-4 text-emerald-600 mt-0.5 shrink-0"}),e.jsxs("div",{className:"text-sm flex-1",children:[e.jsxs("p",{className:"font-medium text-foreground mb-0.5",children:["Sending from your Gmail",r?` (${r})`:""]}),e.jsx("p",{className:"text-muted-foreground",children:"Drips will send directly from your connected Gmail for the most personal feel and best deliverability."})]})]}):e.jsxs("div",{className:"bg-amber-500/5 border border-amber-500/20 rounded-xl p-4 mb-6 flex items-start gap-3",children:[e.jsx(hS,{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(B,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>t("/mission-control/integrations"),children:[e.jsx(ln,{className:"h-3 w-3 mr-1.5"}),"Connect Gmail"]})]})]})),e.jsxs(Yr,{defaultValue:"my-drips",children:[e.jsxs(Zr,{className:"grid grid-cols-4 w-full max-w-2xl mb-6",children:[e.jsx(Ht,{value:"my-drips",children:"Stage Drips"}),e.jsxs(Ht,{value:"campaigns",children:["Campaigns",e.jsx(Oe,{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(Ht,{value:"autopilot",children:["Life Events",e.jsx(Oe,{variant:"outline",className:"ml-1.5 text-[9px] bg-primary/10 text-primary border-primary/20 px-1 py-0",children:"Auto"})]}),e.jsxs(Ht,{value:"starters",children:["Stage Starters",b.length>0&&e.jsx(Oe,{variant:"secondary",className:"ml-1.5 text-[10px] px-1.5 py-0",children:b.length})]})]}),e.jsx(Gt,{value:"campaigns",children:e.jsx(dlr,{})}),e.jsx(Gt,{value:"autopilot",children:e.jsx(wlr,{})}),e.jsx(Gt,{value:"my-drips",children:M?e.jsx("div",{className:"space-y-3",children:[1,2,3,4].map(I=>e.jsx(cn,{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(nf,{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=j(I.id),O=p===I.id,V=D.some(G=>G.is_enabled);return e.jsxs("div",{className:"border rounded-xl overflow-hidden",children:[e.jsxs("button",{onClick:()=>f(O?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(Oe,{variant:"outline",className:`text-[10px] ${V?"bg-emerald-500/10 text-emerald-600 border-emerald-200":"text-muted-foreground"}`,children:[D.length," drip",D.length!==1?"s":"",V&&" · Active"]}),O?e.jsx(tl,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(xi,{className:"h-4 w-4 text-muted-foreground"})]}),O&&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(B,{variant:"outline",size:"sm",onClick:()=>C(I.id),disabled:d.isPending,children:[e.jsx(rn,{className:"h-3.5 w-3.5 mr-1.5"}),"Create Drip"]})]}):e.jsxs(e.Fragment,{children:[D.map(G=>e.jsx(vCt,{template:G,isEditing:y===G.id,onToggleEdit:()=>v(y===G.id?null:G.id),onToggleEnabled:()=>S(G),onUpdate:$=>u.mutateAsync({id:G.id,...$}),onDelete:()=>E(G.id),userId:s||""},G.id)),e.jsxs(B,{variant:"ghost",size:"sm",className:"w-full text-xs text-muted-foreground",onClick:()=>C(I.id),children:[e.jsx(rn,{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=j(I.id),O=p===I.id,V=D.some(G=>G.is_enabled);return e.jsxs("div",{className:"border rounded-xl overflow-hidden mb-2",children:[e.jsxs("button",{onClick:()=>f(O?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(Oe,{variant:"outline",className:`text-[10px] ${V?"bg-emerald-500/10 text-emerald-600 border-emerald-200":"text-muted-foreground"}`,children:[D.length," drip",D.length!==1?"s":"",V&&" · Active"]}),O?e.jsx(tl,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(xi,{className:"h-4 w-4 text-muted-foreground"})]}),O&&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(B,{variant:"outline",size:"sm",onClick:()=>C(I.id),disabled:d.isPending,children:[e.jsx(rn,{className:"h-3.5 w-3.5 mr-1.5"})," Create Drip"]})]}):e.jsxs(e.Fragment,{children:[D.map(G=>e.jsx(vCt,{template:G,isEditing:y===G.id,onToggleEdit:()=>v(y===G.id?null:G.id),onToggleEnabled:()=>S(G),onUpdate:$=>u.mutateAsync({id:G.id,...$}),onDelete:()=>E(G.id),userId:s||""},G.id)),e.jsxs(B,{variant:"ghost",size:"sm",className:"w-full text-xs text-muted-foreground",onClick:()=>C(I.id),children:[e.jsx(rn,{className:"h-3 w-3 mr-1"})," Add another drip"]})]})})]},I.id)})]})]})}),e.jsx(Gt,{value:"starters",children:b.length===0?e.jsxs("div",{className:"text-center py-12 border border-dashed rounded-xl",children:[e.jsx(un,{className:"h-10 w-10 text-muted-foreground/40 mx-auto mb-3"}),e.jsx("h3",{className:"font-semibold text-lg mb-1",children:"No Starter Templates Yet"}),e.jsx("p",{className:"text-sm text-muted-foreground max-w-md mx-auto",children:"Admin-created starter templates will appear here. You'll be able to copy them into your own drips."})]}):e.jsx("div",{className:"space-y-3",children:b.map(I=>e.jsx(Nlr,{template:I,onCopy:()=>P(I.id),isCopying:m.isPending},I.id))})})]})]})})}function vCt({template:s,isEditing:t,onToggleEdit:n,onToggleEnabled:r,onUpdate:a,onDelete:i,userId:l}){const[o,c]=_.useState(s.title),[d,u]=_.useState(s.subject),[h,m]=_.useState(s.body),[p,f]=_.useState(s.video_url||""),[y,v]=_.useState(s.channel),[g,b]=_.useState(s.delay_type),[j,S]=_.useState(s.delay_minutes),[C,E]=_.useState(!1),P=async()=>{E(!0);try{await a({title:o,subject:d,body:h,video_url:p||null,channel:y,delay_type:g,delay_minutes:j}),se.success("Drip saved"),n()}catch{se.error("Failed to save")}finally{E(!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(Hi,{className:"h-3 w-3 text-muted-foreground"}):e.jsx(ln,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:s.delay_type==="instant"?"Sends instantly":`Sends after ${s.delay_minutes>=60?`${Math.round(s.delay_minutes/60)}h`:`${s.delay_minutes}m`}`}),s.video_url&&e.jsx(Kr,{className:"h-3 w-3 text-primary"})]})]}),e.jsx(fn,{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(J,{className:"text-xs font-medium",children:"Title (internal)"}),e.jsx(xe,{value:o,onChange:I=>c(I.target.value),className:"mt-1 h-8 text-sm",placeholder:"e.g. Buyer intro video"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(J,{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:()=>v(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 ${y===I?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:[I==="sms"?e.jsx(Hi,{className:"h-3 w-3"}):e.jsx(ln,{className:"h-3 w-3"}),I==="sms"?"SMS":"Email"]},I))})]}),e.jsxs("div",{className:"flex-1",children:[e.jsx(J,{className:"text-xs font-medium",children:"Timing"}),e.jsxs("div",{className:"flex gap-1 mt-1",children:[e.jsx("button",{onClick:()=>b("instant"),className:`flex-1 px-3 py-1.5 rounded-md text-xs font-medium border transition-colors ${g==="instant"?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:"Instant"}),e.jsxs("button",{onClick:()=>b("scheduled"),className:`flex-1 px-3 py-1.5 rounded-md text-xs font-medium border transition-colors ${g==="scheduled"?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:[e.jsx(Gr,{className:"h-3 w-3 mr-1 inline"}),"Delay"]})]})]})]}),g==="scheduled"&&e.jsxs("div",{children:[e.jsx(J,{className:"text-xs font-medium",children:"Delay"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(xe,{type:"number",min:1,value:j>=60?Math.round(j/60):j,onChange:I=>{const D=parseInt(I.target.value)||0;S(j>=60?D*60:D)},className:"h-8 w-20 text-sm"}),e.jsx("div",{className:"flex gap-1",children:[{label:"Minutes",mins:j<60?j:30},{label:"Hours",mins:j>=60?j:60},{label:"Days",mins:j>=1440?j:1440}].map(I=>e.jsx("button",{className:`px-2 py-1 rounded text-xs border transition-colors ${I.label==="Minutes"&&j<60||I.label==="Hours"&&j>=60&&j<1440||I.label==="Days"&&j>=1440?"bg-primary/10 text-primary border-primary/30":"text-muted-foreground border-input"}`,onClick:()=>{I.label==="Minutes"?S(30):I.label==="Hours"?S(60):S(1440)},children:I.label},I.label))})]})]}),y==="email"&&e.jsxs("div",{children:[e.jsx(J,{className:"text-xs font-medium",children:"Subject Line"}),e.jsx(xe,{value:d,onChange:I=>u(I.target.value),className:"mt-1 h-8 text-sm",placeholder:"e.g. Next steps for your home purchase"})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx(J,{className:"text-xs font-medium",children:y==="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..."}),llr.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:y==="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(J,{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(Kr,{className:"h-3 w-3 inline mr-1 text-primary"}),p.length>50?p.slice(0,50)+"...":p]}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 text-xs text-destructive",onClick:()=>f(""),children:"Remove"})]}):e.jsxs("div",{className:"mt-1 flex items-center gap-1.5",children:[e.jsx(qat,{onVideoReady:I=>f(I)}),e.jsx(iz,{userId:l,onSelect:I=>f(I),triggerSize:"sm",triggerClassName:"gap-1.5 flex-1"}),e.jsxs(B,{variant:"ghost",size:"sm",className:"gap-1 text-xs text-muted-foreground flex-1",onClick:()=>{const I=prompt("Paste a YouTube or Loom URL:");I&&f(I)},children:[e.jsx(Vc,{className:"h-3 w-3"})," Paste URL"]})]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsxs(B,{variant:"ghost",size:"sm",className:"text-xs text-destructive hover:text-destructive",onClick:i,children:[e.jsx(Sn,{className:"h-3 w-3 mr-1"})," Delete"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",size:"sm",className:"text-xs",onClick:n,children:"Cancel"}),e.jsx(B,{size:"sm",className:"text-xs",onClick:P,disabled:C,children:C?"Saving...":"Save Drip"})]})]})]})]})}function Nlr({template:s,onCopy:t,isCopying:n}){const[r,a]=_.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(Oe,{variant:"secondary",className:"text-[10px] px-1.5 py-0",children:l}),e.jsxs(Oe,{variant:"outline",className:"text-[10px] gap-1",children:[s.channel==="sms"?e.jsx(Hi,{className:"h-3 w-3"}):e.jsx(ln,{className:"h-3 w-3"}),s.channel==="sms"?"SMS":"Email"]}),e.jsxs(Oe,{variant:"outline",className:"text-[10px] gap-1",children:[e.jsx(Gr,{className:"h-3 w-3"}),s.delay_type==="instant"?"Instant":o.replace("Sends ","")]}),r?e.jsx(tl,{className:"h-4 w-4 text-muted-foreground ml-1"}):e.jsx(xi,{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(Gr,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:o})]}),e.jsxs(B,{onClick:c=>{c.stopPropagation(),t()},size:"sm",className:"w-full gap-1.5",disabled:n,children:[e.jsx(Ia,{className:"h-3.5 w-3.5"}),"Use This Template"]})]})]})}const yas=()=>{const s=ru();return _.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 klr(){return _.useEffect(()=>(document.body.classList.add("cardstudio-page"),()=>{document.body.classList.remove("cardstudio-page")}),[]),e.jsxs(jH,{children:[e.jsx(Qt,{path:"/c/:shareToken",element:e.jsx(xas,{})}),e.jsx(Qt,{path:"*",element:e.jsx(yas,{})})]})}const $Be={Home:"🏠",Search:"🔍",DollarSign:"💰",Coffee:"☕",Calendar:"📅",Users:"👥",Phone:"📞",Video:"🎥"},Slr=["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 Clr(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 VBe(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 vas({slugOverride:s}){const t=Li(),n=s||t.slug,[r,a]=_.useState("types"),[i,l]=_.useState(null),[o,c]=_.useState(null),[d,u]=_.useState(null),[h,m]=_.useState(new Date),[p,f]=_.useState({name:"",email:"",phone:"",message:""}),[y,v]=_.useState(!1),[g,b]=_.useState(null),[j,S]=_.useState(()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"America/New_York"}catch{return"America/New_York"}}),{data:C,isLoading:E}=at({queryKey:["public-booking-settings",n],queryFn:async()=>{const{data:ie,error:te}=await q.from("agent_booking_settings").select("*").eq("slug",n).eq("is_active",!0).single();if(te)throw te;return ie},enabled:!!n}),{data:P}=at({queryKey:["public-booking-profile",C==null?void 0:C.user_id],queryFn:async()=>{const{data:ie,error:te}=await q.from("profiles").select("name, avatar_url, email, phone, title, bio").eq("id",C.user_id).single();if(te)throw te;return ie},enabled:!!(C!=null&&C.user_id)}),{data:M=[]}=at({queryKey:["public-booking-types",C==null?void 0:C.user_id],queryFn:async()=>{const{data:ie,error:te}=await q.from("agent_booking_types").select("id, name, description, duration_minutes, color, icon, qualification_enabled").eq("user_id",C.user_id).eq("is_active",!0).eq("is_coaching_only",!1).order("sort_order");if(te)throw te;return ie},enabled:!!(C!=null&&C.user_id)}),I=Hs(h,"yyyy-MM"),{data:D={},isFetching:O}=at({queryKey:["public-availability-map",n,i==null?void 0:i.id,I],enabled:!!n&&!!i,staleTime:6e4,queryFn:async()=>{const ie=new Date(h.getFullYear(),h.getMonth(),1),te=If(new Date),ae=Z4(te,ie)?te:ie,le=new Date(h.getFullYear(),h.getMonth()+1,0),be=Math.max(1,Math.round((le.getTime()-ae.getTime())/864e5)+1),{data:me,error:he}=await q.functions.invoke("agent-booking",{body:{action:"availability",slug:n,booking_type_id:i.id,start:Hs(ae,"yyyy-MM-dd"),days:Math.min(be,90)}});if(he)throw he;if(me!=null&&me.error)throw new Error(me.error);return(me==null?void 0:me.availability)||{}}}),V=ie=>{const te=If(new Date),ae=zh(te,(C==null?void 0:C.max_advance_days)||30);return yS(ie,te)||Z4(ie,ae)?!1:(D[Hs(ie,"yyyy-MM-dd")]||[]).length>0},G=_.useMemo(()=>o?D[Hs(o,"yyyy-MM-dd")]||[]:[],[o,D]),$=_.useMemo(()=>{const ie=h.getFullYear(),te=h.getMonth(),ae=new Date(ie,te,1),le=new Date(ie,te+1,0),be=ae.getDay(),me=[];for(let he=0;he{var ie,te;if(!(!i||!o||!d||!p.name||!C)){v(!0);try{const ae=Hs(o,"yyyy-MM-dd"),{data:le,error:be}=await q.functions.invoke("agent-booking",{body:{action:"create",slug:n,booking_type_id:i.id,date:ae,time:d,guest_name:p.name,guest_email:p.email||null,guest_phone:p.phone||null,guest_message:p.message||null,guest_timezone:j}});if(be){let pe=be.message;try{const Ce=await((te=(ie=be.context)==null?void 0:ie.json)==null?void 0:te.call(ie));Ce!=null&&Ce.error&&(pe=Ce.error)}catch{}throw new Error(pe)}if(le!=null&&le.error)throw new Error(le.error);const me=(le==null?void 0:le.end_time)||d,he=le!=null&&le.manage_token?`${window.location.origin}/booking/manage/${le.manage_token}`:null;b(he),q.functions.invoke("booking-notify",{body:{agentUserId:C.user_id,guestName:p.name,guestEmail:p.email||null,guestPhone:p.phone||null,guestMessage:p.message||null,bookingTypeName:i.name,bookingDate:ae,startTime:d,endTime:me,durationMinutes:i.duration_minutes,meetingLink:C.meeting_link||null,manageUrl:he}}).catch(pe=>console.error("Booking notify error:",pe)),a("confirmed")}catch(ae){se.error("Failed to book: "+ae.message)}finally{v(!1)}}},Y=ie=>{const[te,ae]=ie.split(":").map(Number),le=te>=12?"PM":"AM";return`${te%12||12}:${ae.toString().padStart(2,"0")} ${le}`},Z=(C==null?void 0:C.timezone)||"America/New_York",ne=j!==Z,ce=(ie,te)=>{if(!ne)return Y(te);try{return new Intl.DateTimeFormat("en-US",{timeZone:j,hour:"numeric",minute:"2-digit"}).format(new Date(Clr(ie,te,Z)))}catch{return Y(te)}};return E?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..."})]})}):C?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(Fo,{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(_a,{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(ln,{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(ie=>e.jsx("button",{onClick:()=>{l(ie),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:ie.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:$Be[ie.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:ie.name}),ie.description&&e.jsx("p",{className:"text-xs text-slate-500 mt-0.5 line-clamp-2",children:ie.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(Gr,{className:"h-3 w-3"}),ie.duration_minutes,"m"]})]})})},ie.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:$Be[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(Gr,{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($c,{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(xi,{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(ie=>e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-slate-400 font-semibold py-2",children:ie},ie)),$.map((ie,te)=>{if(!ie)return e.jsx("div",{},`pad-${te}`);const ae=V(ie),le=o&&cm(ie,o),be=cm(ie,new Date);return e.jsx("button",{disabled:!ae,onClick:()=>{c(ie),u(null)},className:`h-10 w-10 mx-auto rounded-xl text-sm font-medium transition-all duration-150 ${le?"bg-[#406E71] text-white shadow-md shadow-[#406E71]/30 scale-105":ae?"hover:bg-[#406E71]/10 text-slate-700 hover:text-[#406E71]":"text-slate-200 cursor-not-allowed"} ${be&&!le?"ring-1 ring-[#406E71]/40":""}`,children:ie.getDate()},ie.toISOString())})]})]}),o&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pc,{className:"h-4 w-4 text-[#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:j,onChange:ie=>S(ie.target.value),className:"text-[11px] font-medium text-slate-700 bg-transparent focus:outline-none cursor-pointer",children:Array.from(new Set([j,Z,...Slr])).map(ie=>e.jsxs("option",{value:ie,children:[ie.replace(/_/g," ")," (",VBe(ie),")"]},ie))})]}),O&&G.length===0?e.jsxs("div",{className:"text-center py-8 space-y-2",children:[e.jsx(Ct,{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…"})]}):G.length===0?e.jsxs("div",{className:"text-center py-8 space-y-2",children:[e.jsx(Gr,{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:G.map(ie=>{const te=d===ie;return e.jsx("button",{onClick:()=>u(ie),className:`px-3 py-2.5 rounded-xl text-sm font-medium transition-all duration-150 ${te?"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:ce(Hs(o,"yyyy-MM-dd"),ie)},ie)})}),d&&e.jsx(B,{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:$Be[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(pc,{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(Gr,{className:"h-3.5 w-3.5 text-[#406E71]"}),ce(Hs(o,"yyyy-MM-dd"),d)," (",VBe(j),") · ",i.duration_minutes," min"]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs font-semibold text-slate-700",children:"Full Name *"}),e.jsx(xe,{value:p.name,onChange:ie=>f({...p,name:ie.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(J,{className:"text-xs font-semibold text-slate-700",children:"Email"}),e.jsxs("div",{className:"relative",children:[e.jsx(ln,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(xe,{type:"email",value:p.email,onChange:ie=>f({...p,email:ie.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(J,{className:"text-xs font-semibold text-slate-700",children:"Phone"}),e.jsxs("div",{className:"relative",children:[e.jsx(_a,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(xe,{type:"tel",value:p.phone,onChange:ie=>f({...p,phone:ie.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(J,{className:"text-xs font-semibold text-slate-700",children:"Message (optional)"}),e.jsx(Ms,{value:p.message,onChange:ie=>f({...p,message:ie.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(B,{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:H,disabled:!p.name||y,children:y?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(Er,{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?`${ce(Hs(o,"yyyy-MM-dd"),d)} (${VBe(j)})`:""," · ",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."}),g&&e.jsx("div",{className:"pt-1",children:e.jsx("a",{href:g,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(_a,{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(ln,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]})}),e.jsx("p",{className:"text-center text-[10px] text-slate-300 mt-6 font-medium tracking-wide uppercase",children:"Powered by LevelUp"})]})]}):e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-[#f0f4f8] via-white to-[#e8f0f8] flex items-center justify-center p-4",children:e.jsxs("div",{className:"max-w-sm w-full text-center space-y-4",children:[e.jsx("div",{className:"mx-auto w-16 h-16 rounded-2xl bg-slate-100 flex items-center justify-center",children:e.jsx(pc,{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 Alr(){const t=ru().pathname.slice(1).split("/")[0];return _.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(vas,{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 Elr(){const t=ru().pathname.slice(1);return _.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(Azt,{slugOverride:t})}function Tlr(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 Mlr={playfair:"'Playfair Display', Georgia, serif",baskerville:"'Libre Baskerville', Georgia, serif",instrument:"'Instrument Serif', Georgia, serif",sans:"'Inter', system-ui, sans-serif"};function Plr({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=Mlr[s.heading_font||"playfair"],u=s.eyebrow||null,h=s.headline_accent||null,m=Array.isArray(s.trust_pills)?s.trust_pills:[],p=t,f=p.length>5;return e.jsxs("section",{className:"relative w-full min-h-screen md:min-h-[760px] overflow-hidden",style:{backgroundColor:c},children:[s.hero_image_url?e.jsx("img",{src:s.hero_image_url,alt:"",className:"absolute inset-0 w-full h-full object-cover",loading:"eager"}):e.jsx("div",{className:"absolute inset-0",style:{background:`linear-gradient(135deg, ${c}, #000)`}}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-r from-black/85 via-black/55 to-black/25"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/70 via-transparent to-black/20"}),e.jsx("div",{className:"relative z-10 mx-auto w-full max-w-7xl px-6 md:px-10 py-16 md:py-24 min-h-screen md:min-h-[760px] flex items-center",children:e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-5 gap-10 lg:gap-12 w-full items-center",children:[e.jsxs("div",{className:"lg:col-span-3 text-white",children:[s.logo_url&&e.jsx(Llr,{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(_a,{className:"h-3 w-3"})," ",s.agent_phone]}),s.agent_email&&e.jsxs("a",{href:`mailto:${s.agent_email}`,className:"flex items-center gap-1 hover:text-white",children:[e.jsx(ln,{className:"h-3 w-3"})," ",s.agent_email]})]})]})]})]}),e.jsx("div",{className:"lg:col-span-2",children:e.jsxs("div",{className:"rounded-2xl border border-white/15 bg-white/10 backdrop-blur-xl shadow-2xl p-5 md:p-6",children:[e.jsxs("form",{className:"space-y-3",onSubmit:a,children:[e.jsx("div",{className:f?"space-y-3 max-h-[52vh] overflow-y-auto pr-1 -mr-1":"space-y-3",children:p.map(y=>e.jsxs("div",{children:[e.jsxs(J,{className:"block text-[11px] font-semibold tracking-wider uppercase text-white/85 mb-1.5",children:[y.label,y.is_required&&e.jsx("span",{className:"ml-1",style:{color:o},children:"*"})]}),e.jsx("div",{className:"[&_input]:bg-white/95 [&_input]:border-0 [&_input]:text-neutral-900 [&_input]:placeholder:text-neutral-400 [&_textarea]:bg-white/95 [&_textarea]:border-0 [&_textarea]:text-neutral-900 [&_textarea]:placeholder:text-neutral-400 [&_button[role=combobox]]:bg-white/95 [&_button[role=combobox]]:border-0 [&_button[role=combobox]]:text-neutral-900 [&_span]:text-white/90 [&_button[role=checkbox]]:border-white/60 [&_button[role=checkbox]]:bg-white/20 [&_button[role=checkbox][data-state=checked]]:bg-white [&_button[role=checkbox][data-state=checked]]:text-neutral-900",children:l(y,n,r,c)})]},y.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((y,v)=>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}}),y]},v))})]})})]})})]})}function Llr({src:s}){const[t,n]=_.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(Tlr(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})}const bCt={playfair:"'Playfair Display', Georgia, serif",baskerville:"'Libre Baskerville', Georgia, serif",instrument:"'Instrument Serif', Georgia, serif",sans:"'Inter', system-ui, sans-serif"};function Ilr({page:s,fields:t,answers:n,setAnswers:r,onSubmit:a,isSubmitting:i,renderField:l,activePath:o,setActivePath:c}){const d=_.useRef(null),[u,h]=_.useState(!1),m=s.primary_color||"#406E71",p=s.accent_color||"#2a4c64",f=s.settings||{},y=bCt[s.heading_font]||bCt.playfair,v=Array.isArray(s.trust_pills)?s.trust_pills:[],g={buyerLabel:f.buyer_button_label||"I'm a Buyer",buyerSub:f.buyer_button_subtext||"Find the right home, at the right price",sellerLabel:f.seller_button_label||"I'm a Seller",sellerSub:f.seller_button_subtext||"Get a free, no-obligation home evaluation",buyerTitle:f.buyer_form_title||"Tell me what you’re looking for",buyerSubtitle:f.buyer_form_subtext||"A few quick questions and I’ll send you matching homes.",sellerTitle:f.seller_form_title||"Get your free home evaluation",sellerSubtitle:f.seller_form_subtext||"Tell me about your home and I’ll prepare your value report.",buyerCta:f.buyer_submit_label||"Send me homes",sellerCta:f.seller_submit_label||"Get my home value"},b=_.useMemo(()=>{const E=t.filter(I=>(I.field_group||"default")==="buyer"),P=t.filter(I=>(I.field_group||"default")==="seller"),M=t.filter(I=>(I.field_group||"default")==="default");return{buyer:E.length?[...M,...E]:[...M],seller:P.length?[...M,...P]:[...M]}},[t]),j=o?b[o]:[];_.useEffect(()=>{o&&d.current&&d.current.scrollIntoView({behavior:"smooth",block:"start"})},[o]);const S=j.filter(E=>E.is_required&&!n[E.label]),C=E=>{E.preventDefault(),h(!0),!(S.length>0)&&a(E)};return e.jsxs("div",{className:"min-h-screen bg-neutral-950",children:[e.jsxs("section",{className:"relative min-h-[78vh] flex items-center overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0",style:{background:s.hero_image_url?`url(${s.hero_image_url}) center/cover no-repeat`:`linear-gradient(135deg, ${m}, ${p})`}}),e.jsx("div",{className:"absolute inset-0",style:{background:"linear-gradient(180deg, rgba(0,0,0,.72) 0%, rgba(0,0,0,.42) 38%, rgba(0,0,0,.82) 100%)"}}),e.jsx("div",{className:"absolute inset-x-0 bottom-0 h-40",style:{background:"linear-gradient(180deg, transparent, #0a0a0a)"}}),e.jsxs("div",{className:"relative w-full max-w-6xl mx-auto px-5 py-20 text-center",children:[s.logo_url&&e.jsx("img",{src:s.logo_url,alt:"",className:"h-11 w-auto mx-auto mb-8 drop-shadow-lg"}),s.eyebrow&&e.jsx("p",{className:"text-[11px] md:text-xs uppercase tracking-[0.32em] text-white/70 mb-5",children:s.eyebrow}),e.jsxs("h1",{className:"text-white text-4xl md:text-6xl lg:text-7xl leading-[1.05] tracking-tight",style:{fontFamily:y},children:[s.hero_headline,s.headline_accent&&e.jsxs(e.Fragment,{children:[" ",e.jsx("em",{className:"italic",style:{color:"#fff",opacity:.85},children:s.headline_accent})]})]}),s.hero_subtext&&e.jsx("p",{className:"mt-5 text-base md:text-lg text-white/80 max-w-2xl mx-auto leading-relaxed",children:s.hero_subtext}),e.jsxs("div",{className:"mt-12 grid gap-4 sm:grid-cols-2 max-w-3xl mx-auto",children:[e.jsx(_Ct,{active:o==="buyer",icon:e.jsx(_b,{className:"h-5 w-5"}),label:g.buyerLabel,sub:g.buyerSub,color:m,onClick:()=>{h(!1),c("buyer")}}),e.jsx(_Ct,{active:o==="seller",icon:e.jsx(Jr,{className:"h-5 w-5"}),label:g.sellerLabel,sub:g.sellerSub,color:p,onClick:()=>{h(!1),c("seller")}})]}),v.length>0&&e.jsx("div",{className:"mt-9 flex flex-wrap items-center justify-center gap-2",children:v.map(E=>e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full border border-white/20 bg-white/10 px-3.5 py-1.5 text-[11px] font-medium text-white/85 backdrop-blur",children:[e.jsx(Dm,{className:"h-3 w-3"})," ",E]},E))})]})]}),e.jsx("section",{ref:d,className:"relative bg-neutral-950 px-5 pb-20 pt-2 scroll-mt-4",children:e.jsxs("div",{className:"max-w-3xl mx-auto",children:[o?e.jsxs("div",{className:"-mt-14 rounded-3xl border border-white/10 bg-white shadow-[0_40px_80px_-30px_rgba(0,0,0,.8)] overflow-hidden",children:[e.jsxs("div",{className:"px-6 md:px-9 py-6",style:{background:`linear-gradient(120deg, ${o==="buyer"?m:p}, ${o==="buyer"?p:m})`},children:[e.jsxs("button",{type:"button",onClick:()=>c(null),className:"inline-flex items-center gap-1.5 text-[11px] uppercase tracking-widest text-white/75 hover:text-white transition-colors",children:[e.jsx(ka,{className:"h-3 w-3"})," Change"]}),e.jsx("h2",{className:"mt-3 text-2xl md:text-3xl text-white leading-tight",style:{fontFamily:y},children:o==="buyer"?g.buyerTitle:g.sellerTitle}),e.jsx("p",{className:"mt-1.5 text-sm text-white/80",children:o==="buyer"?g.buyerSubtitle:g.sellerSubtitle})]}),e.jsxs("form",{onSubmit:C,className:"px-6 md:px-9 py-7 space-y-4",children:[j.length===0&&e.jsx("p",{className:"text-sm text-neutral-500",children:"This form has no questions yet."}),j.map(E=>e.jsxs("div",{children:[e.jsxs(J,{className:"text-[13px] font-medium text-neutral-700",children:[E.label,E.is_required&&e.jsx("span",{className:"ml-1",style:{color:m},children:"*"})]}),l(E,n,r,m)]},E.id)),u&&S.length>0&&e.jsxs("p",{className:"text-sm text-red-600",children:["Please fill in: ",S.map(E=>E.label).join(", ")]}),e.jsxs(B,{type:"submit",disabled:i,className:"w-full h-12 text-white text-base rounded-xl shadow-lg hover:opacity-95",style:{backgroundColor:o==="buyer"?m:p},children:[i?"Sending…":o==="buyer"?g.buyerCta:g.sellerCta,!i&&e.jsx(La,{className:"h-4 w-4 ml-2"})]})]})]}):e.jsx("p",{className:"text-center text-white/45 text-sm py-10",children:"Choose an option above to get started."}),s.agent_name&&e.jsxs("div",{className:"mt-10 flex items-center justify-center gap-4 rounded-2xl border border-white/10 bg-white/[0.04] px-6 py-5 backdrop-blur",children:[s.agent_photo_url&&e.jsx("img",{src:s.agent_photo_url,alt:s.agent_name,className:"h-14 w-14 rounded-full object-cover ring-2 ring-white/20"}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"text-white font-medium",children:s.agent_name}),e.jsxs("div",{className:"mt-1 flex flex-wrap gap-x-4 gap-y-1 text-xs text-white/65",children:[s.agent_phone&&e.jsxs("a",{href:`tel:${s.agent_phone}`,className:"inline-flex items-center gap-1 hover:text-white",children:[e.jsx(_a,{className:"h-3 w-3"})," ",s.agent_phone]}),s.agent_email&&e.jsxs("a",{href:`mailto:${s.agent_email}`,className:"inline-flex items-center gap-1 hover:text-white",children:[e.jsx(ln,{className:"h-3 w-3"})," ",s.agent_email]})]})]})]})]})})]})}function _Ct({active:s,icon:t,label:n,sub:r,color:a,onClick:i}){return e.jsxs("button",{type:"button",onClick:i,className:`group relative overflow-hidden rounded-2xl border px-6 py-7 text-left transition-all duration-300 backdrop-blur-xl ${s?"border-white/60 bg-white/95 shadow-2xl -translate-y-0.5":"border-white/20 bg-white/10 hover:bg-white/20 hover:-translate-y-0.5"}`,children:[e.jsx("span",{className:"inline-flex h-11 w-11 items-center justify-center rounded-full",style:{backgroundColor:s?a:"rgba(255,255,255,.18)",color:"#fff"},children:t}),e.jsx("span",{className:`mt-4 block text-xl font-semibold ${s?"":"text-white"}`,style:s?{color:a}:void 0,children:n}),e.jsx("span",{className:`mt-1 block text-sm ${s?"text-neutral-600":"text-white/70"}`,children:r}),e.jsx(La,{className:`absolute right-5 top-7 h-4 w-4 transition-transform group-hover:translate-x-1 ${s?"":"text-white/60"}`,style:s?{color:a}:void 0})]})}function Dlr(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 Rlr(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 Flr(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 Olr({startsAt:s,locationName:t,address:n,title:r,accent:a}){const[i,l]=_.useState(Date.now());_.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=Dlr(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(Gr,{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(Xa,{className:"h-3.5 w-3.5"})," ",h]})]})]}),!d&&e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs("a",{href:Rlr(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(ga,{className:"h-4 w-4"})," Add to Google"]}),e.jsxs("a",{href:Flr(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(ga,{className:"h-4 w-4"})," Apple / Outlook"]})]})]})})})}function zlr(){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 bas({slugOverride:s}){var G;const{slug:t}=Li(),n=s||t,[r,a]=_.useState(!1),[i,l]=_.useState({}),[o,c]=_.useState(null),[d,u]=_.useState(0),[h,m]=_.useState(!1),[p,f]=_.useState(""),[y]=_.useState(()=>Date.now()),v=_.useState(()=>zlr())[0],{data:g,isLoading:b}=at({queryKey:["public-landing-page",n],queryFn:async()=>{const{data:$,error:H}=await q.from("landing_pages").select("*").eq("slug",n).eq("is_published",!0).single();if(H)throw H;return $},enabled:!!n}),{data:j=[]}=at({queryKey:["public-landing-page-fields",g==null?void 0:g.id],queryFn:async()=>{const{data:$,error:H}=await q.from("landing_page_fields").select("*").eq("page_id",g.id).order("sort_order");if(H)throw H;return $},enabled:!!(g!=null&&g.id)});_.useEffect(()=>{g!=null&&g.id&&q.from("landing_pages").update({view_count:(g.view_count||0)+1}).eq("id",g.id).then(()=>{})},[g==null?void 0:g.id]),_.useEffect(()=>{if(!(g!=null&&g.id))return;const $=new URLSearchParams(window.location.search);q.functions.invoke("landing-page-track",{body:{page_id:g.id,event_type:"view",session_id:v,utm_source:$.get("utm_source"),utm_medium:$.get("utm_medium"),utm_campaign:$.get("utm_campaign"),referrer:document.referrer||null,device:window.matchMedia("(max-width: 768px)").matches?"mobile":"desktop"}}).catch(()=>{})},[g==null?void 0:g.id,v]);const S=mt({mutationFn:async()=>{const $=j.find(le=>le.field_type==="text"&&le.label.toLowerCase().includes("name")),H=j.find(le=>le.field_type==="email"),Y=j.find(le=>le.field_type==="phone"),Z=$?String(i[$.label]||""):null,ne=H?String(i[H.label]||""):null,ce=Y?String(i[Y.label]||""):null,ie=new URLSearchParams(window.location.search),{data:te,error:ae}=await q.functions.invoke("landing-page-submit",{body:{page_id:g.id,answers:JSON.parse(JSON.stringify(o?{"I am a":o==="buyer"?"Buyer":"Seller",...i}:i)),contact_name:Z,contact_email:ne,contact_phone:ce,session_id:v,honeypot:p,rendered_at:y,utm_source:ie.get("utm_source"),utm_medium:ie.get("utm_medium"),utm_campaign:ie.get("utm_campaign"),referrer:document.referrer||null}});if(ae)throw ae;return te},onSuccess:$=>{a(!0),$!=null&&$.redirect_url&&setTimeout(()=>{window.location.href=$.redirect_url},1500)}}),C=$=>{$.preventDefault(),!((g==null?void 0:g.page_type)!=="buyer_seller"&&j.filter(Y=>Y.is_required&&!i[Y.label]).length>0)&&S.mutate()};if(b)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 E=g.primary_color||"#406E71",P=g.accent_color||"#2a4c64",M=g,I=g.page_type==="lead_magnet",D=g.page_type==="just_listed"||g.page_type==="just_sold",O=Array.isArray(M.property_photos)?M.property_photos:[],V=M.lead_magnet_file_url||M.lead_magnet_external_url;if(r)return e.jsx("div",{className:"min-h-screen flex items-center justify-center",style:{background:`linear-gradient(135deg, ${E}, ${P})`},children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-2xl p-8 max-w-md mx-4 text-center",children:[e.jsx(Er,{className:"h-16 w-16 mx-auto mb-4",style:{color:E}}),e.jsx("h2",{className:"text-2xl font-bold mb-2",children:I?"Your download is ready!":"Submitted!"}),e.jsx("p",{className:"text-gray-600",children:g.success_message}),I&&V&&e.jsxs("a",{href:V,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:E},children:[e.jsx(li,{className:"h-5 w-5"}),"Download ",M.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:E},children:[e.jsx(_a,{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:E},children:[e.jsx(ln,{className:"h-3 w-3"})," ",g.agent_email]})]})]})});if(D){const $=H=>{const Y=parseFloat(H.replace(/[^0-9.]/g,""));return isNaN(Y)?H:new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(Y)};return e.jsxs("div",{className:"min-h-screen bg-gray-50",children:[h&&O.length>0&&e.jsxs("div",{className:"fixed inset-0 z-50 bg-black/95 flex items-center justify-center",onClick:()=>m(!1),children:[e.jsx("button",{onClick:()=>m(!1),className:"absolute top-4 right-4 text-white/80 hover:text-white z-10",children:e.jsx(Qn,{className:"h-8 w-8"})}),e.jsx("button",{onClick:H=>{H.stopPropagation(),u(Y=>Y===0?O.length-1:Y-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($c,{className:"h-6 w-6"})}),e.jsx("img",{src:O[d],alt:`Property photo ${d+1}`,className:"max-h-[90vh] max-w-[90vw] object-contain rounded-lg",onClick:H=>H.stopPropagation()}),e.jsx("button",{onClick:H=>{H.stopPropagation(),u(Y=>Y===O.length-1?0:Y+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(xi,{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:[d+1," / ",O.length]})]}),O.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:M.property_status==="just_sold"?"#e74c3c":E},children:M.property_status==="just_sold"?"🎉 Just Sold":"🏡 Just Listed"}),O.length===1?e.jsxs("div",{className:"rounded-2xl overflow-hidden cursor-pointer group",onClick:()=>{u(0),m(!0)},children:[e.jsx("img",{src:O[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(aP,{className:"h-4 w-4"})," View"]})]}):O.length===2?e.jsx("div",{className:"grid grid-cols-2 gap-2 rounded-2xl overflow-hidden",children:O.slice(0,2).map((H,Y)=>e.jsx("div",{className:"cursor-pointer group relative",onClick:()=>{u(Y),m(!0)},children:e.jsx("img",{src:H,alt:`Property ${Y+1}`,className:"w-full h-[45vh] object-cover group-hover:scale-105 transition-transform duration-500"})},Y))}):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:()=>{u(0),m(!0)},children:e.jsx("img",{src:O[0],alt:"Property main",className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"})}),O.slice(1,5).map((H,Y)=>e.jsxs("div",{className:"cursor-pointer group relative",onClick:()=>{u(Y+1),m(!0)},children:[e.jsx("img",{src:H,alt:`Property ${Y+2}`,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"}),Y===3&&O.length>5&&e.jsxs("div",{className:"absolute inset-0 bg-black/50 flex items-center justify-center text-white font-bold text-lg",children:["+",O.length-5," more"]})]},Y))]}),O.length>2&&e.jsxs("button",{onClick:()=>{u(0),m(!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(aP,{className:"h-4 w-4"})," View all ",O.length," photos"]})]}),O.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, ${E}, ${P})`},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:[M.property_price&&e.jsx("p",{className:"text-3xl md:text-4xl font-bold mb-2",style:{color:E},children:$(M.property_price)}),M.property_address&&e.jsxs("p",{className:"text-gray-600 flex items-center gap-1.5 mb-5 text-lg",children:[e.jsx(Xa,{className:"h-5 w-5 shrink-0"})," ",M.property_address]}),e.jsxs("div",{className:"flex gap-6 mb-5 py-4 border-y border-gray-100",children:[M.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(dj,{className:"h-5 w-5",style:{color:E}})," ",M.property_beds]}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:"Bedrooms"})]}),M.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(S0,{className:"h-5 w-5",style:{color:E}})," ",M.property_baths]}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:"Bathrooms"})]}),M.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(W4,{className:"h-5 w-5",style:{color:E}})," ",Number(M.property_sqft).toLocaleString()]}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:"Sq Ft"})]})]}),M.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:M.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:E},children:M.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(_a,{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(ln,{className:"h-3 w-3"})," ",g.agent_email]})]})]})]}),e.jsxs("form",{onSubmit:C,className:"space-y-3",children:[j.map(H=>e.jsxs("div",{children:[e.jsxs(J,{className:"text-xs font-medium",children:[H.label,H.is_required&&e.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),Zde(H,i,l)]},H.id)),e.jsx(B,{type:"submit",className:"w-full text-white",style:{backgroundColor:E},disabled:S.isPending,children:S.isPending?"Submitting...":"Submit"}),S.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.page_type==="buyer_seller"?e.jsxs(e.Fragment,{children:[e.jsx("input",{type:"text",name:"company_website",tabIndex:-1,autoComplete:"off","aria-hidden":"true",value:p,onChange:$=>f($.target.value),style:{position:"absolute",left:"-10000px",top:"auto",width:"1px",height:"1px",overflow:"hidden"}}),e.jsx(Ilr,{page:g,fields:j,answers:i,setAnswers:l,onSubmit:C,isSubmitting:S.isPending,renderField:Zde,activePath:o,setActivePath:c}),S.isError&&e.jsx("p",{className:"text-center text-sm text-red-500 pb-8 bg-neutral-950",children:"Something went wrong. Please try again."}),e.jsx("div",{className:"text-center py-6 text-xs text-white/30 bg-neutral-950",children:"Powered by LevelUp"})]}):g.theme_style!=="classic"&&!I?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:p,onChange:$=>f($.target.value),style:{position:"absolute",left:"-10000px",top:"auto",width:"1px",height:"1px",overflow:"hidden"}}),e.jsx(Plr,{page:g,fields:j,answers:i,setAnswers:l,onSubmit:C,isSubmitting:S.isPending,renderField:Zde}),g.page_type==="event_registration"&&((G=g.settings)==null?void 0:G.event_starts_at)&&e.jsx(Olr,{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"}),S.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, ${E}, ${P})`},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}),I&&M.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(li,{className:"h-4 w-4"}),"Free Download: ",M.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:[I&&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(_a,{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(ln,{className:"h-3 w-3"})," ",g.agent_email]})]})]})]}),e.jsxs("form",{onSubmit:C,className:"space-y-4",children:[j.map($=>e.jsxs("div",{children:[e.jsxs(J,{className:"text-sm font-medium",children:[$.label,$.is_required&&e.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),Zde($,i,l)]},$.id)),e.jsx(B,{type:"submit",className:"w-full text-white",style:{backgroundColor:E},disabled:S.isPending,children:S.isPending?"Submitting...":I?"Get My Free Download":"Submit"}),S.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 Zde(s,t,n,r){const a=t[s.label]||"",i=Array.isArray(s.options)?s.options:[];switch(s.field_type){case"text":case"email":case"phone":return e.jsx(xe,{type:s.field_type==="email"?"email":s.field_type==="phone"?"tel":"text",value:String(a),onChange:l=>n(o=>({...o,[s.label]:l.target.value})),placeholder:s.placeholder||"",className:"mt-1"});case"textarea":return e.jsx(Ms,{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(is,{value:String(a),onValueChange:l=>n(o=>({...o,[s.label]:l})),children:[e.jsx(rs,{className:"mt-1",children:e.jsx(ls,{placeholder:"Select..."})}),e.jsx(as,{children:i.map(l=>e.jsx(He,{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($a,{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(fn,{checked:!!a,onCheckedChange:l=>n(o=>({...o,[s.label]:l?"Yes":"No"}))}),e.jsx("span",{className:"text-sm text-gray-600",children:a?"Yes":"No"})]});default:return e.jsx(xe,{value:String(a),onChange:l=>n(o=>({...o,[s.label]:l.target.value})),className:"mt-1"})}}function Blr(){const t=ru().pathname.slice(1).split("/")[0];return _.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(bas,{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 Ulr=[{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}],lwr={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"},cwr={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"},wCt={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 dwr(s){return wCt[s]||wCt.basic}function qlr(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}):Ulr,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 $lr=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 Vlr(s){const t=s.toLowerCase().replace(/:\d+$/,"");return!!($lr.has(t)||t.endsWith(".lovable.app")||t.endsWith(".lovableproject.com")||t.endsWith(".lovable.dev"))}function _as(){return new URLSearchParams(window.location.search).get("previewSlug")}function Hlr(){const s=_as();if(s)return s;const n=window.location.hostname.match(/^([^.]+)\.thelocalmove\.com$/i);return n?n[1]:null}function Glr(){const s=Hlr(),t=!!_as(),n=window.location.hostname,r=s?null:M6t(n),a=!s&&!Vlr(n)&&n.includes(".")&&!T6t(n),i=s||r||(a?n:null),{data:l,isLoading:o,error:c}=at({queryKey:["lead-site",i,a,t],queryFn:async()=>{var j;if(!i)return null;const u=q.from("lead_sites").select("*"),h=t?u:u.eq("is_active",!0);let m;if(s)m=await h.eq("subdomain_slug",s).maybeSingle();else if(r)m=await h.ilike("custom_domain",r).maybeSingle();else if(a)m=await h.ilike("custom_domain",n).maybeSingle();else return null;const{data:p,error:f}=m;if(f)throw f;if(!p)return null;const{data:y}=await q.from("profiles").select("id, name, avatar_url, email, phone, title, bio, areas_served, years_experience, instagram_url, facebook_url, linkedin_url, google_business_url, zillow_profile_url, realtor_profile_url, specialties").eq("id",p.agent_id).single();let v=null;if(p.show_team_logo)if(p.team_logo_url)v=p.team_logo_url;else{const{data:S}=await q.from("team_members").select("team_id, teams(avatar_url, name)").eq("user_id",p.agent_id).limit(1).maybeSingle();S&&((j=S.teams)!=null&&j.avatar_url)&&(v=S.teams.avatar_url)}const g={id:p.id,agentId:p.agent_id,subdomainSlug:p.subdomain_slug,customDomain:p.custom_domain||null,mlsProviderId:p.mls_provider_id,siteTitle:p.site_title,siteTagline:p.site_tagline,leadRegistrationMode:p.lead_registration_mode||"disabled",registrationTriggerCount:p.registration_trigger_count??1,themeConfig:p.theme_config||{},themeTier:p.theme_tier||"basic",planTier:p.plan_tier||"paid",ownerType:p.owner_type||"agent",orgTier:p.org_tier||"essential",brokerageId:p.brokerage_id||null,teamId:p.team_id||null,orgName:p.org_name||null,orgLogoUrl:p.org_logo_url||null,orgLogoDarkUrl:p.org_logo_dark_url||null,orgProfile:p.org_profile||{},brandColor:p.brand_color||void 0,accentColor:p.accent_color||void 0,mlsServiceCities:Array.isArray(p.mls_service_cities)?p.mls_service_cities:[],isActive:p.is_active,brokerageLegalName:p.brokerage_legal_name||null,brokerageLicenseNumber:p.brokerage_license_number||null,agentLicenseNumber:p.agent_license_number||null,licenseState:p.license_state||null,mlsDisclaimerText:p.mls_disclaimer_text||null,mlsLogoUrl:p.mls_logo_url||null,equalHousingEnabled:p.equal_housing_enabled??!0,faviconUrl:p.favicon_url||null,ogImageUrl:p.og_image_url||null,showTeamLogo:p.show_team_logo??!1,teamLogoUrl:v,noMlsMode:p.no_mls_mode===!0,bookingUrl:p.booking_url||null,pageSubtitles:p.page_subtitles||{},agent:y?{id:y.id,full_name:y.name||"",avatar_url:y.avatar_url,email:y.email,phone:y.phone,title:y.title,bio:y.bio,areas_served:y.areas_served||null,years_experience:y.years_experience??null,instagram_url:y.instagram_url||null,facebook_url:y.facebook_url||null,linkedin_url:y.linkedin_url||null,google_business_url:y.google_business_url||null,zillow_profile_url:y.zillow_profile_url||null,realtor_profile_url:y.realtor_profile_url||null,specialties:y.specialties||null}:void 0,testimonials:Array.isArray(p.testimonials)?p.testimonials.filter(S=>S&&typeof S=="object"&&S.text).map(S=>({name:String(S.name||"Client"),text:String(S.text),rating:typeof S.rating=="number"?S.rating:5,location:S.location?String(S.location):void 0})):[],seoMetaTitle:p.seo_meta_title||null,seoMetaDescription:p.seo_meta_description||null},b=qlr(p);return{siteConfig:g,themeConfig:b}},enabled:!!i,staleTime:5*60*1e3,gcTime:30*60*1e3,refetchOnWindowFocus:!1}),d=r||(a?n:null);return{siteConfig:(l==null?void 0:l.siteConfig)??null,themeConfig:(l==null?void 0:l.themeConfig)??null,isLoading:o,error:c,slug:s??(l==null?void 0:l.siteConfig.subdomainSlug)??null,customDomain:d}}async function Wlr(s,t){try{await q.functions.invoke("lead-site-notify",{body:{lead:t,lead_site_id:s}})}catch(n){console.warn("Lead notification failed:",n)}}const was=_.createContext(null);function rDe(){const s=_.useContext(was);if(!s)throw new Error("useLeadSiteAuth must be used within LeadSiteAuthProvider");return s}function jCt({siteConfig:s,children:t}){const[n,r]=_.useState(null),[a,i]=_.useState(null),[l,o]=_.useState(!0);_.useEffect(()=>{let h=!0,m=0;const p=async v=>{const g=++m,{data:b}=await q.from("lead_site_consumer_profiles").select("id, name, phone").eq("user_id",v.id).eq("lead_site_id",s.id).maybeSingle();!h||g!==m||(i(b?{...b,email:v.email||""}:null),o(!1))},{data:{subscription:f}}=q.auth.onAuthStateChange((v,g)=>{const b=(g==null?void 0:g.user)??null;r(b),b?window.setTimeout(()=>void p(b),0):(m+=1,i(null),o(!1))}),y=window.setTimeout(()=>{h&&(console.warn("Lead site auth initialization timed out."),o(!1))},8e3);return()=>{h=!1,window.clearTimeout(y),f.unsubscribe()}},[s.id]);const c=_.useCallback(async h=>{const m=h.email.toLowerCase().trim(),p=h.phone.replace(/\D/g,""),{data:f,error:y}=await q.auth.signUp({email:m,password:p,options:{data:{full_name:h.name,consumer_site_id:s.id},emailRedirectTo:window.location.origin}});if(y){if(y.message.includes("already registered")){await d(m,p);return}throw y}if(f.user){const{error:v}=await q.from("lead_site_consumer_profiles").insert({user_id:f.user.id,lead_site_id:s.id,name:h.name.trim(),phone:h.phone.trim()});v&&console.warn("Consumer profile insert error:",v);const{error:g}=await q.from("lead_site_leads").insert({lead_site_id:s.id,name:h.name.trim(),email:m,phone:h.phone.trim(),message:"Created account on website",source_page:window.location.pathname,lead_type:"website_registration",metadata:{registered:!0,has_account:!0}});g&&console.error("Lead insert error (CRM sync may not trigger):",g),Wlr(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=_.useCallback(async(h,m)=>{const p=m.replace(/\D/g,""),{error:f}=await q.auth.signInWithPassword({email:h.toLowerCase().trim(),password:p});if(f)throw f},[]),u=_.useCallback(async()=>{await q.auth.signOut(),r(null),i(null)},[]);return e.jsx(was.Provider,{value:{user:n,profile:a,isLoading:l,signUp:c,signIn:d,signOut:u},children:t})}const jas=new Set(["7605cc2e-ce21-4f4f-8bb1-4c0f217b1109"]),Nas=new Set(["tomlois"]);function M9(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||jas.has(s.id||"")||Nas.has((s.subdomainSlug||"").toLowerCase())||!s.mlsProviderId:!1}function Klr(s,t){var n;return s?((n=s.themeConfig)==null?void 0:n.referralMode)===!0||jas.has(s.id||"")||Nas.has((s.subdomainSlug||"").toLowerCase()):!1}function uwr(s,t){return Klr(s)?"referral":M9(s,t)?"direct":"idx"}function hwr(s){return`Contact ${s.split(" ")[0]||"Me"}`}const xK="#c9a96e",Ylr="Schedule a Free Consultation",Zlr={sm:"px-5 py-2.5 text-[11px]",md:"px-7 py-3.5 text-xs",lg:"px-9 py-4 text-xs"};function lE({bookingUrl:s,label:t=Ylr,className:n="",variant:r="solid",color:a=xK,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 ${Zlr[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(bv,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{children:t})]})}function mwr({bookingUrl:s,agentName:t,accentColor:n=xK,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:Gr,title:r.point1Title||"30 Minutes",text:r.point1Text||"A focused conversation about your goals, timeline, and options."},{icon:XQ,title:r.point2Title||"A Personal Call",text:r.point2Text||`${t.split(" ")[0]} calls you at the time you choose — no phone tag.`},{icon:Er,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(Sr.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(lE,{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 pwr({bookingUrl:s,accentColor:t=xK,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(lE,{bookingUrl:s,label:"Schedule Now",color:t,size:"sm",className:"flex-shrink-0",source:l})]}):null}function Xlr({bookingUrl:s,accentColor:t=xK}){const[n,r]=_.useState(!1),[a,i]=_.useState(!1);if(_.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(bv,{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(Qn,{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(lE,{bookingUrl:s,label:"Schedule a Free Consultation",size:"sm",color:t,source:"sticky"})})]})}function Qlr({bookingUrl:s,agentName:t}){return _.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(bv,{className:"h-8 w-8 mx-auto mb-6",style:{color:xK}}),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(lE,{bookingUrl:s,label:"Open Booking Calendar",size:"lg",source:"schedule_page"})})]})})}const nit=` 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 aDe(s){return at({queryKey:["lead-site-exchange-listings",s],enabled:!!s,staleTime:5*60*1e3,queryFn:async()=>{const{data:t,error:n}=await q.from("listings").select(nit).eq("agent_id",s).eq("show_on_lead_site",!0).eq("is_approved",!0).neq("status","sold").order("created_at",{ascending:!1});if(n)throw n;return t||[]}})}function rit(s){return at({queryKey:["lead-site-sold-listings",s],enabled:!!s,staleTime:5*60*1e3,queryFn:async()=>{const{data:t,error:n}=await q.from("listings").select(nit).eq("agent_id",s).eq("show_on_lead_site",!0).eq("is_approved",!0).eq("status","sold").order("created_at",{ascending:!1});if(n)throw n;return t||[]}})}function fwr(s,t){return at({queryKey:["lead-site-exchange-listing",s,t],enabled:!!s&&!!t,queryFn:async()=>{const n=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t);let r=q.from("listings").select(nit).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 xwr(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 gwr(s){return s?`$${s.toLocaleString()}`:"Price upon request"}function ait({open:s,mode:t,siteConfig:n,onComplete:r,onSkip:a,theme:i="default",accentColor:l}){var G;const{signUp:o,signIn:c}=rDe(),[d,u]=_.useState(!1),[h,m]=_.useState(""),[p,f]=_.useState(""),[y,v]=_.useState(""),[g,b]=_.useState(!1),[j,S]=_.useState(""),C=t==="required",E=i==="luxury",P=l||(E?"#c9a96e":"#2563eb"),M=((G=n.agent)==null?void 0:G.full_name)||"the agent",I={borderColor:`${P}66`,"--tw-ring-color":`${P}66`},D=async $=>{var Y;if($.preventDefault(),S(""),!p.trim()||!y.trim()){S("Email and phone number are required.");return}if(!d&&!h.trim()){S("Name is required.");return}if(y.replace(/\D/g,"").length<7){S("Please enter a valid phone number.");return}b(!0);try{d?await c(p,y):await o({name:h,email:p,phone:y}),r()}catch(Z){(Y=Z==null?void 0:Z.message)!=null&&Y.includes("Invalid login")?S("Invalid email or phone number. Please try again."):S((Z==null?void 0:Z.message)||"Something went wrong. Please try again.")}finally{b(!1)}},O=E?"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",V=E?I:void 0;return e.jsx(Ls,{open:s,onOpenChange:C?void 0:$=>{$||a()},children:e.jsxs(Ps,{className:`sm:max-w-md ${E?"border-white/10 bg-[#f7f1e7] text-[#201915]":""}`,onPointerDownOutside:C?$=>$.preventDefault():void 0,onEscapeKeyDown:C?$=>$.preventDefault():void 0,children:[e.jsxs(Os,{children:[e.jsx(Ds,{className:"text-xl",style:E?{fontFamily:"'Playfair Display', Georgia, serif"}:void 0,children:d?"Welcome Back":C?"Create a Free Account to Continue":"Save Your Search & Get Updates"}),e.jsx(_r,{className:E?"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:$=>m($.target.value),className:O,style:V}),e.jsx("input",{type:"email",required:!0,placeholder:"Email address",value:p,onChange:$=>f($.target.value),className:O,style:V}),e.jsxs("div",{children:[e.jsx("input",{type:"tel",required:!0,placeholder:"Phone number",value:y,onChange:$=>v($.target.value),className:O,style:V}),e.jsx("p",{className:`text-xs mt-1 ${E?"text-[#8a7869]":"text-gray-400"}`,children:d?"Your phone number is your password":"Your phone number will be used as your password"})]}),j&&e.jsx("p",{className:"text-red-600 text-sm",children:j}),e.jsx("button",{type:"submit",disabled:g,className:`w-full py-2.5 font-medium rounded-lg disabled:opacity-50 transition-colors ${E?"text-black hover:opacity-90 tracking-wider uppercase text-sm":"bg-blue-600 text-white hover:bg-blue-700"}`,style:E?{backgroundColor:P}:void 0,children:g?d?"Signing in...":"Creating account...":d?"Sign In":"Create Account"}),e.jsx("button",{type:"button",onClick:()=>{u(!d),S("")},className:"w-full text-center text-sm hover:opacity-80 transition-opacity",style:{color:P},children:d?"Don't have an account? Sign up":"Already have an account? Sign in"}),!C&&!d&&e.jsx("button",{type:"button",onClick:a,className:`w-full py-2 text-sm transition-colors ${E?"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 ${E?"text-[#8a7869]":"text-gray-400"}`,children:"By registering you agree to receive property updates. You can unsubscribe anytime."})]})})}function iit({siteConfig:s,pagePath:t}){const n=s.agent;if(!n)return null;const r=s.customDomain?`https://${s.customDomain}`:`https://${s.subdomainSlug}.thelocalmove.com`,a=s.id==="7605cc2e-ce21-4f4f-8bb1-4c0f217b1109",i=!M9(s),o=(n.areas_served||"").split(/,|;|\|/).map(E=>E.trim()).filter(Boolean),c=o[0]||"",[d,u]=c.split(/,\s*/),h=(n.bio||"").match(/\b(CRS|GRI|ABR|CNE|SRES|SRS|RENE|MRP|PSA|AHWD|C2EX|CIPS|CRB|e-?PRO)\b/gi)||[],m=[...new Set(h.map(E=>E.toUpperCase()))],p=s.testimonials||[],f=p.length?{"@type":"AggregateRating",ratingValue:(p.reduce((E,P)=>E+(P.rating||5),0)/p.length).toFixed(1),reviewCount:p.length,bestRating:5,worstRating:1}:void 0,y=[n.google_business_url,n.zillow_profile_url,n.realtor_profile_url,n.linkedin_url,n.facebook_url,n.instagram_url].filter(Boolean),v=(n.specialties||"").split(/,|;|\n/).map(E=>E.trim()).filter(Boolean),g={"@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:a?"Personal Real Estate Advisor":n.title||"Real Estate Agent",description:n.bio||`${n.full_name} is a trusted local real estate professional${c?` serving ${c}`:""}.`,priceRange:"$$",...y.length&&{sameAs:y},...s.brokerageLegalName&&{worksFor:{"@type":"RealEstateAgent",name:s.brokerageLegalName,...s.brokerageLicenseNumber&&{identifier:s.brokerageLicenseNumber}}},...s.agentLicenseNumber&&{identifier:s.agentLicenseNumber},...d&&{address:{"@type":"PostalAddress",addressLocality:d,...u&&{addressRegion:u},addressCountry:"US"}},...o.length&&{areaServed:o.map(E=>{const[P,M]=E.split(/,\s*/);return{"@type":"City",name:P,...M&&{containedInPlace:{"@type":"State",name:M}}}})},...f&&{aggregateRating:f},...p.length&&{review:p.slice(0,10).map(E=>({"@type":"Review",author:{"@type":"Person",name:E.name},reviewBody:E.text,reviewRating:{"@type":"Rating",ratingValue:E.rating||5,bestRating:5,worstRating:1},...E.location&&{locationCreated:{"@type":"Place",name:E.location}}}))}},b={"@context":"https://schema.org","@type":"Person","@id":`${r}/#person`,name:n.full_name,jobTitle:a?"Personal Real Estate Advisor":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,...a&&{email:"Tom@TomLois.com",telephone:"520-271-2716",address:{"@type":"PostalAddress",addressLocality:"Columbia",addressRegion:"Missouri",addressCountry:"US"}},...y.length&&{sameAs:y},knowsAbout:[...new Set([...v,"Residential Real Estate","Home Buying","Home Selling",...o.map(E=>`${E} Real Estate`)])].filter(Boolean).slice(0,25),...v.length&&{makesOffer:v.slice(0,12).map(E=>({"@type":"Offer",itemOffered:{"@type":"Service",name:E,serviceType:"Real Estate Service"}}))},...m.length&&{hasCredential:m.map(E=>({"@type":"EducationalOccupationalCredential",credentialCategory:"designation",name:E}))},...s.brokerageLegalName&&{worksFor:{"@type":"Organization",name:s.brokerageLegalName}}},j={"@context":"https://schema.org","@type":"WebSite","@id":`${r}/#website`,name:s.siteTitle||`${n.full_name} Real Estate`,url:r,publisher:{"@id":`${r}/#agent`},...i&&{potentialAction:{"@type":"SearchAction",target:{"@type":"EntryPoint",urlTemplate:`${r}/search?q={search_term_string}`},"query-input":"required name=search_term_string"}}},S=[...i?[{name:"Search Homes",description:`Browse all current MLS listings${c?` in ${c}`:""}.`,path:"/search"}]:[],{name:"Featured Areas",description:"Explore featured neighborhoods, cities, and communities.",path:"/areas"},...i?[{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"}],C={"@context":"https://schema.org","@type":"ItemList","@id":`${r}/#nav`,name:"Main Navigation",itemListElement:S.map((E,P)=>({"@type":"SiteNavigationElement",position:P+1,name:E.name,description:E.description,url:`${r}${E.path}`}))};return e.jsxs(ul,{children:[e.jsx("script",{type:"application/ld+json",children:JSON.stringify(g)}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify(b)}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify(j)}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify(C)})]})}function ywr({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 vwr({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 Jlr({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 bwr({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 _wr({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 oit({siteConfig:s}){var p;const t=s.agent;if(!t)return null;const n=t.full_name,r=s.brokerageLegalName||"their brokerage",a=t.areas_served||"the local market",i=((p=a.split(/,|;|\|/)[0])==null?void 0:p.trim())||"the local area",l=t.years_experience,o=t.phone||"",c=t.email,d=s.agentLicenseNumber,u=(t.bio||"").match(/\b(CRS|GRI|ABR|CNE|SRES|SRS|RENE|MRP|PSA|AHWD|C2EX|CIPS|CRB|e-?PRO)\b/gi)||[],h=[...new Set(u.map(f=>f.toUpperCase()))],m=[{question:`Who is ${n}?`,answer:`${n} is a ${t.title||"REALTOR®"} with ${r}${l?`, with ${l}+ years of local real estate experience`:""} serving ${a}. ${t.bio?t.bio.slice(0,280):""}`.trim()},{question:`What areas does ${n} serve?`,answer:`${n} serves ${a} and surrounding communities. Whether you're buying, selling, relocating, or downsizing, ${n.split(" ")[0]} provides expert local guidance.`},{question:`How can I contact ${n}?`,answer:`You can reach ${n} by ${o?`phone at ${o}, `:""}email at ${c}, or by booking a consultation directly through this website.`},...h.length?[{question:`What real estate designations does ${n} hold?`,answer:`${n} holds the following professional designations: ${h.join(", ")}. These designations represent advanced training in specialized areas of real estate.`}]:[],...d?[{question:`Is ${n} a licensed real estate agent?`,answer:`Yes, ${n} is a fully licensed real estate professional (License #${d}) with ${r}.`}]:[],{question:`How do I search for homes for sale in ${i}?`,answer:`Use the property search on this site to view all current MLS listings in ${i}. You can filter by price, bedrooms, neighborhood, school district, and more. Save searches to receive instant email alerts when new homes match your criteria.`},{question:`What is the home buying process like in ${i}?`,answer:`${n} guides buyers through every step: getting pre-approved, searching MLS listings, touring homes, writing competitive offers, navigating inspections and appraisals, and closing on schedule. Contact ${n.split(" ")[0]} for a free buyer consultation.`},{question:`How do I find out what my home is worth in ${i}?`,answer:`Request a free, no-obligation home valuation from ${n}. ${n.split(" ")[0]} provides a comparative market analysis (CMA) using recent sold comps and current market conditions in ${i}.`}];return e.jsx(Jlr,{faqs:m})}const NCt="ls_visitor_geo",ecr=1e3*60*60,HBe="lu_lc_attrib_v1",tcr=1e3*60*60*24*90;function scr(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 ncr(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 rcr(){try{const s=localStorage.getItem(NCt);if(s){const t=JSON.parse(s);if(Date.now()-t.ts{i.current||(i.current=!0,rcr().then(l=>{a.current=l}))},[]),_.useEffect(()=>{if(!(s!=null&&s.id))return;const l=n.pathname;if(l===r.current)return;r.current=l;const o=scr(l),c=ncr(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(HBe,JSON.stringify({contact_id:p,ts:Date.now()}))}catch{}return p}const f=m.get("lc");if(f&&/^[0-9a-f-]{36}$/i.test(f)){const{data:y}=await q.from("listing_email_recipients").select("contact_id").eq("id",f).maybeSingle(),v=y==null?void 0:y.contact_id;if(v){try{localStorage.setItem(HBe,JSON.stringify({contact_id:v,ts:Date.now()}))}catch{}return v}}try{const y=localStorage.getItem(HBe);if(y){const v=JSON.parse(y);if(v!=null&&v.contact_id&&Date.now()-(v.ts||0){q.from("lead_site_page_views").insert({lead_site_id:s.id,page_type:o,page_path:l,page_title:c,visitor_fingerprint:d,auth_user_id:t||null,contact_id:m,visitor_city:(u==null?void 0:u.city)||null,visitor_region:(u==null?void 0:u.region)||null,visitor_country:(u==null?void 0:u.country)||null,visitor_lat:(u==null?void 0:u.lat)||null,visitor_lng:(u==null?void 0:u.lng)||null}).then(({error:p})=>{p&&console.error("[PageTracking] insert failed:",p.message)})})},[n.pathname,n.search,s==null?void 0:s.id,t])}const acr=3e4;function cit(s,t){const n=ru(),r=_.useRef(null),a=_.useRef(null),i=_.useRef(0),l=n.pathname,o=icr(l),c=ocr(l,o),d=o==="listing"&&l.split("/listing/")[1]||null;_.useEffect(()=>{if(!(s!=null&&s.id)||!t)return;o==="listing"&&(i.current+=1);const u=localStorage.getItem(`ls_visitor_fp_${s.id}`)||null,h=async()=>{const{data:m,error:p}=await q.from("lead_site_active_visitors").upsert({lead_site_id:s.id,auth_user_id:t,visitor_fingerprint:u,current_page_path:l,current_page_title:c,current_mls_number:d,last_seen_at:new Date().toISOString(),listing_views_count:i.current},{onConflict:"lead_site_id,session_key"}).select("id, notified_agent").single();!p&&m&&(r.current=m.id,i.current>=2&&!m.notified_agent&&q.functions.invoke("lead-site-presence-notify",{body:{visitor_id:m.id,lead_site_id:s.id}}).catch(()=>{}))};return h(),a.current&&clearInterval(a.current),a.current=setInterval(h,acr),()=>{a.current&&clearInterval(a.current)}},[s==null?void 0:s.id,t,l]),_.useEffect(()=>{if(!(s!=null&&s.id)||!t)return;const u=()=>{r.current&&q.from("lead_site_active_visitors").delete().eq("id",r.current).then(()=>{})};return window.addEventListener("beforeunload",u),()=>window.removeEventListener("beforeunload",u)},[s==null?void 0:s.id,t])}function icr(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 ocr(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 Wi=Number.isFinite||function(s){return typeof s=="number"&&isFinite(s)},lcr=Number.isSafeInteger||function(s){return typeof s=="number"&&Math.abs(s)<=ccr},ccr=Number.MAX_SAFE_INTEGER||9007199254740991;let Lo=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}({}),vr=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}({}),Rt=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 Ad={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},mo={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class rU{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 dcr{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 rU(t),this.fast_=new rU(n),this.defaultTTFB_=a,this.ttfb_=new rU(t)}update(t,n){const{slow_:r,fast_:a,ttfb_:i}=this;r.halfLife!==t&&(this.slow_=new rU(t,r.getEstimate(),r.getTotalWeight())),a.halfLife!==n&&(this.fast_=new rU(n,a.getEstimate(),a.getTotalWeight())),i.halfLife!==t&&(this.ttfb_=new rU(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 ucr(s,t,n){return(t=mcr(t))in s?Object.defineProperty(s,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):s[t]=n,s}function pm(){return pm=Object.assign?Object.assign.bind():function(s){for(var t=1;t`):v6}function SCt(s,t,n){return t[s]?t[s].bind(t):fcr(s,n)}const tZe=eZe();function xcr(s,t,n){const r=eZe();if(typeof console=="object"&&s===!0||typeof s=="object"){const a=["debug","log","info","warn","error"];a.forEach(i=>{r[i]=SCt(i,s,n)});try{r.log(`Debug logs enabled for "${t}" in hls.js version 1.6.16`)}catch{return eZe()}a.forEach(i=>{tZe[i]=SCt(i,s)})}else pm(tZe,r);return r}const Vh=tZe;function ZP(s=!0){return typeof self>"u"?void 0:(s||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function gcr(s){return typeof self<"u"&&s===self.ManagedMediaSource}function kas(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 kj(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 lv(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(!Wi(t)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=t}get ref(){return ng(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 bcr extends Cas{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 Aas(s,t){const n=Object.getPrototypeOf(s);if(n){const r=Object.getOwnPropertyDescriptor(n,t);return r||Aas(n,t)}}function _cr(s,t){const n=Aas(s,t);n&&(n.enumerable=!0,Object.defineProperty(s,t,n))}const ACt=Math.pow(2,32)-1,wcr=[].push,Eas={video:1,audio:2,id3:3,text:4};function u0(s){return String.fromCharCode.apply(null,s)}function Tas(s,t){const n=s[t]<<8|s[t+1];return n<0?65536+n:n}function oc(s,t){const n=Mas(s,t);return n<0?4294967296+n:n}function ECt(s,t){let n=oc(s,t);return n*=Math.pow(2,32),n+=oc(s,t+4),n}function Mas(s,t){return s[t]<<24|s[t+1]<<16|s[t+2]<<8|s[t+3]}function jcr(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 xd(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=xd(s.subarray(a+8,o),t.slice(1));c.length&&wcr.apply(n,c)}a=o}return n}function Ncr(s){const t=[],n=s[0];let r=8;const a=oc(s,r);r+=4;let i=0,l=0;n===0?(i=oc(s,r),l=oc(s,r+4),r+=8):(i=ECt(s,r),l=ECt(s,r+8),r+=16),r+=2;let o=s.length+l;const c=Tas(s,r);r+=2;for(let d=0;d>>31===1)return Vh.warn("SIDX has hierarchical references (not supported)"),null;const f=oc(s,u);u+=4,t.push({referenceSize:m,subsegmentDuration:f,info:{duration:f/a,start:o,end:o+m-1}}),o+=m,u+=4,r=u}return{earliestPresentationTime:i,timescale:a,version:n,referencesCount:c,references:t}}function Pas(s){const t=[],n=xd(s,["moov","trak"]);for(let a=0;a{const i=oc(a,4),l=t[i];l&&(l.default={duration:oc(a,12),flags:oc(a,20)})}),t}function kcr(s){const t=s.subarray(8),n=t.subarray(86),r=u0(t.subarray(4,8));let a=r,i;const l=r==="enca"||r==="encv";if(l){const d=xd(t,[r])[0].subarray(r==="enca"?28:78);xd(d,["sinf"]).forEach(h=>{const m=xd(h,["schm"])[0];if(m){const p=u0(m.subarray(4,8));if(p==="cbcs"||p==="cenc"){const f=xd(h,["frma"])[0];f&&(a=u0(f))}}})}const o=a;switch(a){case"avc1":case"avc2":case"avc3":case"avc4":{const c=xd(n,["avcC"])[0];c&&c.length>3&&(a+="."+Qde(c[1])+Qde(c[2])+Qde(c[3]),i=Xde(o==="avc1"?"dva1":"dvav",n));break}case"mp4a":{const c=xd(t,[r])[0],d=xd(c.subarray(28),["esds"])[0];if(d&&d.length>7){let u=4;if(d[u++]!==3)break;u=KBe(d,u),u+=2;const h=d[u++];if(h&128&&(u+=2),h&64&&(u+=d[u++]),d[u++]!==4)break;u=KBe(d,u);const m=d[u++];if(m===64)a+="."+Qde(m);else break;if(u+=12,d[u++]!==5)break;u=KBe(d,u);const p=d[u++];let f=(p&248)>>3;f===31&&(f+=1+((p&7)<<3)+((d[u]&224)>>5)),a+="."+f}break}case"hvc1":case"hev1":{const c=xd(n,["hvcC"])[0];if(c&&c.length>12){const d=c[1],u=["","A","B","C"][d>>6],h=d&31,m=oc(c,2),p=(d&32)>>5?"H":"L",f=c[12],y=c.subarray(6,12);a+="."+u+h,a+="."+Scr(m).toString(16).toUpperCase(),a+="."+p+f;let v="";for(let g=y.length;g--;){const b=y[g];(b||v)&&(v="."+b.toString(16).toUpperCase()+v)}a+=v}i=Xde(o=="hev1"?"dvhe":"dvh1",n);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{a=Xde(a,n)||a;break}case"vp09":{const c=xd(n,["vpcC"])[0];if(c&&c.length>6){const d=c[4],u=c[5],h=c[6]>>4&15;a+="."+G5(d)+"."+G5(u)+"."+G5(h)}break}case"av01":{const c=xd(n,["av1C"])[0];if(c&&c.length>2){const d=c[1]>>>5,u=c[1]&31,h=c[2]>>>7?"H":"M",m=(c[2]&64)>>6,p=(c[2]&32)>>5,f=d===2&&m?p?12:10:m?10:8,y=(c[2]&16)>>4,v=(c[2]&8)>>3,g=(c[2]&4)>>2,b=c[2]&3;a+="."+d+"."+G5(u)+h+"."+G5(f)+"."+y+"."+v+g+b+"."+G5(1)+"."+G5(1)+"."+G5(1)+"."+0,i=Xde("dav1",n)}break}}return{codec:a,encrypted:l,supplemental:i}}function Xde(s,t){const n=xd(t,["dvvC"]),r=n.length?n[0]:xd(t,["dvcC"])[0];if(r){const a=r[2]>>1&127,i=r[2]<<5&32|r[3]>>3&31;return s+"."+G5(a)+"."+G5(i)}}function Scr(s){let t=0;for(let n=0;n<32;n++)t|=(s>>n&1)<<31-n;return t>>>0}function KBe(s,t){const n=t+5;for(;s[t++]&128&&t{const i=r.subarray(8,24);i.some(l=>l!==0)||(Vh.log(`[eme] Patching keyId in 'enc${a?"a":"v"}>sinf>>tenc' box: ${lv(i)} -> ${lv(n)}`),r.set(n,8))})}function Acr(s){const t=[];return Las(s,n=>t.push(n.subarray(8,24))),t}function Las(s,t){xd(s,["moov","trak"]).forEach(r=>{const a=xd(r,["mdia","minf","stbl","stsd"])[0];if(!a)return;const i=a.subarray(8);let l=xd(i,["enca"]);const o=l.length>0;o||(l=xd(i,["encv"])),l.forEach(c=>{const d=o?c.subarray(28):c.subarray(78);xd(d,["sinf"]).forEach(h=>{const m=Ias(h);m&&t(m,o)})})})}function Ias(s){const t=xd(s,["schm"])[0];if(t){const n=u0(t.subarray(4,8));if(n==="cbcs"||n==="cenc"){const r=xd(s,["schi","tenc"])[0];if(r)return r}}}function Ecr(s,t,n){const r={},a=xd(s,["moof","traf"]);for(let i=0;ir[i].duration)){let i=1/0,l=0;const o=xd(s,["sidx"]);for(let c=0;ch+m.info.duration||0,0);l=Math.max(l,u+d.earliestPresentationTime/d.timescale)}}l&&Wi(l)&&Object.keys(r).forEach(c=>{r[c].duration||(r[c].duration=l*r[c].timescale-r[c].start)})}return r}function Tcr(s){const t={valid:null,remainder:null},n=xd(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 RN(s,t){const n=new Uint8Array(s.length+t.length);return n.set(s),n.set(t,s.length),n}function TCt(s,t){const n=[],r=t.samples,a=t.timescale,i=t.id;let l=!1;return xd(r,["moof"]).map(c=>{const d=c.byteOffset-8;xd(c,["traf"]).map(h=>{const m=xd(h,["tfdt"]).map(p=>{const f=p[0];let y=oc(p,4);return f===1&&(y*=Math.pow(2,32),y+=oc(p,8)),y/a})[0];return m!==void 0&&(s=m),xd(h,["tfhd"]).map(p=>{const f=oc(p,4),y=oc(p,0)&16777215,v=(y&1)!==0,g=(y&2)!==0,b=(y&8)!==0;let j=0;const S=(y&16)!==0;let C=0;const E=(y&32)!==0;let P=8;f===i&&(v&&(P+=8),g&&(P+=4),b&&(j=oc(p,P),P+=4),S&&(C=oc(p,P),P+=4),E&&(P+=4),t.type==="video"&&(l=iDe(t.codec)),xd(h,["trun"]).map(M=>{const I=M[0],D=oc(M,0)&16777215,O=(D&1)!==0;let V=0;const G=(D&4)!==0,$=(D&256)!==0;let H=0;const Y=(D&512)!==0;let Z=0;const ne=(D&1024)!==0,ce=(D&2048)!==0;let ie=0;const te=oc(M,4);let ae=8;O&&(V=oc(M,ae),ae+=4),G&&(ae+=4);let le=V+d;for(let be=0;be>1&63;return n===39||n===40}else return(t&31)===6}function hit(s,t,n,r){const a=Das(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){Vh.error(`Malformed SEI payload. ${o} is too small, only ${d} bytes left to parse.`);break}if(l===4){if(a[u++]===181){const m=Tas(a,u);if(u+=2,m===49){const p=oc(a,u);if(u+=4,p===1195456820){const f=a[u++];if(f===3){const y=a[u++],v=31&y,g=64&y,b=g?2+v*3:0,j=new Uint8Array(b);if(g){j[0]=y;for(let S=1;S16){const h=[];for(let f=0;f<16;f++){const y=a[u++].toString(16);h.push(y.length==1?"0"+y:y),(f===3||f===5||f===7||f===9)&&h.push("-")}const m=o-16,p=new Uint8Array(m);for(let f=0;f>24&255,i[1]=r>>16&255,i[2]=r>>8&255,i[3]=r&255,i.set(s,4),a=0,r=8;a0?(i=new Uint8Array(4),t.length>0&&new DataView(i.buffer).setUint32(0,t.length,!1)):i=new Uint8Array;const l=new Uint8Array(4);return n.byteLength>0&&new DataView(l.buffer).setUint32(0,n.byteLength,!1),Lcr([112,115,115,104],new Uint8Array([r,0,0,0]),s,i,a,l,n)}function Dcr(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=lv(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),zG={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 mit(s,t){const n=zG[t];return!!n&&!!n[s.slice(0,4)]}function Use(s,t,n=!0){return!s.split(",").some(r=>!pit(r,t,n))}function pit(s,t,n=!0){var r;const a=ZP(n);return(r=a==null?void 0:a.isTypeSupported(qse(s,t)))!=null?r:!1}function qse(s,t){return`${t}/mp4;codecs=${s}`}function MCt(s){if(s){const t=s.substring(0,4);return zG.video[t]}return 2}function S6e(s){const t=Ras();return s.split(",").reduce((n,r)=>{const i=t&&iDe(r)?9:zG.video[r];return i?(i*2+n)/(n?3:2):(zG.audio[r]+n)/(n?2:1)},0)}const YBe={};function Fcr(s,t=!0){if(YBe[s])return YBe[s];const n={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[s];for(let a=0;aFcr(n.toLowerCase(),t))}function zcr(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)&&(PCt(s,"audio")||PCt(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 PCt(s,t){return mit(s,t)&&pit(s,t)}function Bcr(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 Ucr(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 LCt(s){const t=ZP(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 sZe(s){return s.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const qcr={supported:!0,powerEfficient:!0,smooth:!0},$cr={supported:!1,smooth:!1,powerEfficient:!1},Fas={supported:!0,configurations:[],decodingInfoResults:[qcr]};function Oas(s,t){return{supported:!1,configurations:t,decodingInfoResults:[$cr],error:s}}function Vcr(s,t,n,r,a,i){const l=s.videoCodec,o=s.audioCodec?s.audioGroups:null,c=i==null?void 0:i.audioCodec,d=i==null?void 0:i.channels,u=d?parseInt(d):c?1/0:2;let h=null;if(o!=null&&o.length)try{o.length===1&&o[0]?h=t.groups[o[0]].channels:h=o.reduce((m,p)=>{if(p){const f=t.groups[p];if(!f)throw new Error(`Audio track group ${p} not found`);Object.keys(f.channels).forEach(y=>{m[y]=(m[y]||0)+f.channels[y]})}return m},{2:0})}catch{return!0}return l!==void 0&&(l.split(",").some(m=>iDe(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&&Wi(u)&&Object.keys(h).some(m=>parseInt(m)>u)}function zas(s,t,n,r={}){const a=s.videoCodec;if(!a&&!s.audioCodec||!n)return Promise.resolve(Fas);const i=[],l=Hcr(s),o=l.length,c=Gcr(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=>iDe(h))&&Ras())return Promise.resolve(Oas(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${u})`),i))}return Promise.all(i.map(u=>{const h=Kcr(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 Hcr(s){var t;const n=(t=s.videoCodec)==null?void 0:t.split(","),r=Bas(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:qse(Ucr(c),"video"),width:a,height:i,bitrate:r,framerate:l};return o!=="sdr"&&(d.transferFunction=o),d}):[]}function Gcr(s,t,n){var r;const a=(r=s.audioCodec)==null?void 0:r.split(","),i=Bas(s);return a&&s.audioGroups?s.audioGroups.reduce((l,o)=>{var c;const d=o?(c=t.groups[o])==null?void 0:c.tracks:null;return d?d.reduce((u,h)=>{if(h.groupId===o){const m=parseFloat(h.channels||"");a.forEach(p=>{const f={contentType:qse(p,"audio"),bitrate:n?Wcr(p,i):i};m&&(f.channels=""+m),u.push(f)})}return u},l):l},[]):[]}function Wcr(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 Bas(s){return Math.ceil(Math.max(s.bitrate*.9,s.averageBitrate)/1e3)*1e3||1}function Kcr(s){let t="";const{audio:n,video:r}=s;if(r){const a=sZe(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=sZe(n.contentType);t+=`${r?"_":""}${a}_c${n.channels}`}return t}const nZe=["NONE","TYPE-0","TYPE-1",null];function Ycr(s){return nZe.indexOf(s)>-1}const A6e=["SDR","PQ","HLG"];function Zcr(s){return!!s&&A6e.indexOf(s)>-1}var t3e={No:"",Yes:"YES",v2:"v2"};function ICt(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 RCt(this._audioGroups,t)}hasSubtitleGroup(t){return RCt(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 RCt(s,t){return!t||!s?!1:s.indexOf(t)!==-1}function Xcr(){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 Qcr(s,t){let n=!1,r=[];if(s&&(n=s!=="SDR",r=[s]),t){r=t.allowedVideoRanges||A6e.slice(0);const a=r.join("")!=="SDR"&&!t.videoCodec;n=t.preferHDR!==void 0?t.preferHDR:a&&Xcr(),n||(r=["SDR"])}return{preferHDR:n,allowedVideoRanges:r}}const Jcr=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}},Lm=(s,t)=>JSON.stringify(s,Jcr(t));function edr(s,t,n,r,a){const i=Object.keys(s),l=r==null?void 0:r.channels,o=r==null?void 0:r.audioCodec,c=a==null?void 0:a.videoCodec,d=l&&parseInt(l)===2;let u=!1,h=!1,m=1/0,p=1/0,f=1/0,y=1/0,v=0,g=[];const{preferHDR:b,allowedVideoRanges:j}=Qcr(t,a);for(let M=i.length;M--;){const I=s[i[M]];u||(u=I.channels[2]>0),m=Math.min(m,I.minHeight),p=Math.min(p,I.minFramerate),f=Math.min(f,I.minBitrate),j.filter(O=>I.videoRanges[O]>0).length>0&&(h=!0)}m=Wi(m)?m:0,p=Wi(p)?p:0;const S=Math.max(1080,m),C=Math.max(30,p);f=Wi(f)?f:n,n=Math.max(f,n),h||(t=void 0);const E=i.length>1;return{codecSet:i.reduce((M,I)=>{const D=s[I];if(I===M)return M;if(g=h?j.filter(O=>D.videoRanges[O]>0):[],E){if(D.minBitrate>n)return E5(I,`min bitrate of ${D.minBitrate} > current estimate of ${n}`),M;if(!D.hasDefaultAudio)return E5(I,"no renditions with default or auto-select sound found"),M;if(o&&I.indexOf(o.substring(0,4))%5!==0)return E5(I,`audio codec preference "${o}" not found`),M;if(l&&!d){if(!D.channels[l])return E5(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 E5(I,"no renditions with stereo sound found"),M;if(D.minHeight>S)return E5(I,`min resolution of ${D.minHeight} > maximum of ${S}`),M;if(D.minFramerate>C)return E5(I,`min framerate of ${D.minFramerate} > maximum of ${C}`),M;if(!g.some(O=>D.videoRanges[O]>0))return E5(I,`no variants with VIDEO-RANGE of ${Lm(g)} found`),M;if(c&&I.indexOf(c.substring(0,4))%5!==0)return E5(I,`video codec preference "${c}" not found`),M;if(D.maxScore=S6e(M)||D.fragmentError>s[M].fragmentError)?M:(y=D.minIndex,v=D.maxScore,I)},void 0),videoRanges:g,preferHDR:b,minFramerate:p,minBitrate:f,minIndex:y}}function E5(s,t){Vh.log(`[abr] start candidates with "${s}" ignored because ${t}`)}function Uas(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 tdr(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 FCt(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 F4(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 ZR(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 rdr(s,t,n,r,a){const i=t[r],o=t.reduce((m,p,f)=>{const y=p.uri;return(m[y]||(m[y]=[])).push(f),m},{})[i.uri];o.length>1&&(r=Math.max.apply(Math,o));const c=i.videoRange,d=i.frameRate,u=i.codecSet.substring(0,4),h=OCt(t,r,m=>{if(m.videoRange!==c||m.frameRate!==d||m.codecSet.substring(0,4)!==u)return!1;const p=m.audioGroups,f=n.filter(y=>!p||p.indexOf(y.groupId)!==-1);return F4(s,f,a)>-1});return h>-1?h:OCt(t,r,m=>{const p=m.audioGroups,f=n.filter(y=>!p||p.indexOf(y.groupId)!==-1);return F4(s,f,a)>-1})}function OCt(s,t,n){for(let r=t;r>-1;r--)if(n(s[r]))return r;for(let r=t+1;r{var r;const{fragCurrent:a,partCurrent:i,hls:l}=this,{autoLevelEnabled:o,media:c}=l;if(!a||!c)return;const d=performance.now(),u=i?i.stats:a.stats,h=i?i.duration:a.duration,m=d-u.loading.start,p=l.minAutoLevel,f=a.level,y=this._nextAutoLevel;if(u.aborted||u.loaded&&u.loaded===u.total||f<=p){this.clearTimer(),this._nextAutoLevel=-1;return}if(!o)return;const v=y>-1&&y!==f,g=!!n||v;if(!g&&(c.paused||!c.playbackRate||!c.readyState))return;const b=l.mainForwardBufferInfo;if(!g&&b===null)return;const j=this.bwEstimator.getEstimateTTFB(),S=Math.abs(c.playbackRate);if(m<=Math.max(j,1e3*(h/(S*2))))return;const C=b?b.len/S:0,E=u.loading.first?u.loading.first-u.loading.start:-1,P=u.loaded&&E>-1,M=this.getBwEstimate(),I=l.levels,D=I[f],O=Math.max(u.loaded,Math.round(h*(a.bitrate||D.averageBitrate)/8));let V=P?m-E:m;V<1&&P&&(V=Math.min(m,u.loaded*8/M));const G=P?u.loaded*1e3/V:0,$=j/1e3,H=G?(O-u.loaded)/G:O*8/M+$;if(H<=C)return;const Y=G?G*8:M,Z=((r=(n==null?void 0:n.details)||this.hls.latestLevelDetails)==null?void 0:r.live)===!0,ne=this.hls.config.abrBandWidthUpFactor;let ce=Number.POSITIVE_INFINITY,ie;for(ie=f-1;ie>p;ie--){const be=I[ie].maxBitrate,me=!I[ie].details||Z;if(ce=this.getTimeToLoadFrag($,Y,h*be,me),ce=H||ce>h*10)return;P?this.bwEstimator.sample(m-Math.min(j,E),u.loaded):this.bwEstimator.sampleTTFB(m);const te=I[ie].maxBitrate;this.getBwEstimate()*ne>te&&this.resetEstimator(te);const ae=this.findBestLevel(te,p,ie,0,C,1,1);ae>-1&&(ie=ae),this.warn(`Fragment ${a.sn}${i?" part "+i.index:""} of level ${f} is loading too slowly; Fragment duration: ${a.duration.toFixed(3)} Time to underbuffer: ${C.toFixed(3)} s Estimated load time for current fragment: ${H.toFixed(3)} s Estimated load time for down switch fragment: ${ce.toFixed(3)} s TTFB estimate: ${E|0} ms Current BW estimate: ${Wi(M)?M|0:"Unknown"} bps New BW estimate: ${this.getBwEstimate()|0} bps Switching to level ${ie} @ ${te|0} bps`),l.nextLoadLevel=l.nextAutoLevel=ie,this.clearTimer();const le=()=>{if(this.clearTimer(),this.fragCurrent===a&&this.hls.loadLevel===ie&&ie>0){const be=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${ie>0?"and switching down":""} Fragment duration: ${a.duration.toFixed(3)} s Time to underbuffer: ${be.toFixed(3)} s`),a.abortRequests(),this.fragCurrent=this.partCurrent=null,ie>p){let me=this.findBestLevel(this.hls.levels[p].bitrate,p,ie,0,be,1,1);me===-1&&(me=p),this.hls.nextLoadLevel=this.hls.nextAutoLevel=me,this.resetEstimator(this.hls.levels[me].bitrate)}}};v||H>ce*2?le():this.timer=self.setInterval(le,ce*1e3),l.trigger(Rt.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 dcr(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate)}registerListeners(){const{hls:t}=this;t.on(Rt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Rt.FRAG_LOADING,this.onFragLoading,this),t.on(Rt.FRAG_LOADED,this.onFragLoaded,this),t.on(Rt.FRAG_BUFFERED,this.onFragBuffered,this),t.on(Rt.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(Rt.LEVEL_LOADED,this.onLevelLoaded,this),t.on(Rt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(Rt.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.on(Rt.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t&&(t.off(Rt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Rt.FRAG_LOADING,this.onFragLoading,this),t.off(Rt.FRAG_LOADED,this.onFragLoaded,this),t.off(Rt.FRAG_BUFFERED,this.onFragBuffered,this),t.off(Rt.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(Rt.LEVEL_LOADED,this.onLevelLoaded,this),t.off(Rt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(Rt.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.off(Rt.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 vr.BUFFER_ADD_CODEC_ERROR:case vr.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case vr.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;Wi(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===mo.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(Rt.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!==mo.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 v=this.findBestLevel(c,l,a,d,0,u,h);if(v>=0)return this.rebufferNotice=-1,v}let m=o?Math.min(o,i.maxStarvationDelay):i.maxStarvationDelay;if(!d){const v=this.bitrateTestDelay;v&&(m=(o?Math.min(o,i.maxLoadingDelay):i.maxLoadingDelay)-v,this.info(`bitrate test took ${Math.round(1e3*v)}ms, set first fragment max fetchDuration to ${Math.round(1e3*m)} ms`),u=h=1)}const p=this.findBestLevel(c,l,a,d,m,u,h);if(this.rebufferNotice!==p&&(this.rebufferNotice=p,this.info(`${d?"rebuffering expected":"buffer is empty"}, optimal quality level ${p}`)),p>-1)return p;const f=r.levels[l],y=r.loadLevelObj;return y&&(f==null?void 0:f.bitrate)=n;Y--){var H;const Z=f[Y],ne=Y>h;if(!Z)continue;if(g.useMediaCapabilities&&!Z.supportedResult&&!Z.supportedPromise){const me=navigator.mediaCapabilities;typeof(me==null?void 0:me.decodingInfo)=="function"&&Vcr(Z,D,E,P,t,M)?(Z.supportedPromise=zas(Z,D,me,this.supportedCache),Z.supportedPromise.then(he=>{if(!this.hls)return;Z.supportedResult=he;const pe=this.hls.levels,Ce=pe.indexOf(Z);he.error?this.warn(`MediaCapabilities decodingInfo error: "${he.error}" for level ${Ce} ${Lm(he)}`):he.supported?he.decodingInfoResults.some(Ae=>Ae.smooth===!1||Ae.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${Ce} not smooth or powerEfficient: ${Lm(he)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${Ce} ${Lm(he)}`),Ce>-1&&pe.length>1&&(this.log(`Removing unsupported level ${Ce}`),this.hls.removeLevel(Ce),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(he=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${he}`)})):Z.supportedResult=Fas}if((C&&Z.codecSet!==C||E&&Z.videoRange!==E||ne&&P>Z.frameRate||!ne&&P>0&&Pme.smooth===!1))&&(!S||Y!==O)){$.push(Y);continue}const ce=Z.details,ie=(p?ce==null?void 0:ce.partTarget:ce==null?void 0:ce.averagetargetduration)||V;let te;ne?te=o*t:te=l*t;const ae=V&&a>=V*2&&i===0?Z.averageBitrate:Z.maxBitrate,le=this.getTimeToLoadFrag(G,te,ae*ie,ce===void 0);if(te>=ae&&(Y===u||Z.loadError===0&&Z.fragmentError===0)&&(le<=G||!Wi(le)||j&&!this.bitrateTestDelay||le${Y} adjustedbw(${Math.round(te)})-bitrate=${Math.round(te-ae)} ttfb:${G.toFixed(1)} avgDuration:${ie.toFixed(1)} maxFetchDuration:${d.toFixed(1)} fetchDuration:${le.toFixed(1)} firstSelection:${S} codecSet:${Z.codecSet} videoRange:${Z.videoRange} hls.loadLevel:${v}`)),S&&(this.firstSelection=Y),Y}}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 qas={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 idr(s,t,n){if(t===null||!Array.isArray(s)||!s.length||!Wi(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)&&zCt(n,r,i)===0||odr(i,s,Math.min(a,r))))return i;const l=qas.search(t,zCt.bind(null,n,r));return l&&(l!==s||!i)?l:i}function odr(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 zCt(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 ldr(s,t,n){const r=Math.min(t,n.duration+(n.deltaPTS?n.deltaPTS:0))*1e3;return(n.endProgramDateTime||0)-r>s}function $as(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 qas.search(r,l=>l.cct?-1:(i=l,l.end<=n?1:l.start>n?-1:0)),i||null}return null}function T6e(s){switch(s.details){case vr.FRAG_LOAD_TIMEOUT:case vr.KEY_LOAD_TIMEOUT:case vr.LEVEL_LOAD_TIMEOUT:case vr.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function Vas(s){return s.details.startsWith("key")}function Has(s){return Vas(s)&&!!s.frag&&!s.frag.decryptdata}function BCt(s,t){const n=T6e(t);return s.default[`${n?"timeout":"error"}Retry`]}function fit(s,t){const n=s.backoff==="linear"?1:Math.pow(2,t);return Math.min(n*s.retryDelayMs,s.maxRetryDelayMs)}function UCt(s){return Fh(Fh({},s),{errorRetry:null,timeoutRetry:null})}function M6e(s,t,n,r){if(!s)return!1;const a=r==null?void 0:r.code,i=t499)}function rZe(s){return s===0&&navigator.onLine===!1}var ov={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},Pw={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4,SwitchToSDR:8};class ddr extends GN{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(Rt.ERROR,this.onError,this),t.on(Rt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Rt.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const t=this.hls;t&&(t.off(Rt.ERROR,this.onError,this),t.off(Rt.ERROR,this.onErrorOut,this),t.off(Rt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Rt.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)===mo.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 vr.FRAG_LOAD_ERROR:case vr.FRAG_LOAD_TIMEOUT:case vr.KEY_LOAD_ERROR:case vr.KEY_LOAD_TIMEOUT:n.errorAction=this.getFragRetryOrSwitchAction(n);return;case vr.FRAG_PARSING_ERROR:if((r=n.frag)!=null&&r.gap){n.errorAction=X$();return}case vr.FRAG_GAP:case vr.FRAG_DECRYPT_ERROR:{n.errorAction=this.getFragRetryOrSwitchAction(n),n.errorAction.action=ov.SendAlternateToPenaltyBox;return}case vr.LEVEL_EMPTY_ERROR:case vr.LEVEL_PARSING_ERROR:{var l;const c=n.parent===mo.MAIN?n.level:a.loadLevel;n.details===vr.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 vr.LEVEL_LOAD_ERROR:case vr.LEVEL_LOAD_TIMEOUT:typeof(i==null?void 0:i.level)=="number"&&(n.errorAction=this.getPlaylistRetryOrSwitchAction(n,i.level));return;case vr.AUDIO_TRACK_LOAD_ERROR:case vr.AUDIO_TRACK_LOAD_TIMEOUT:case vr.SUBTITLE_LOAD_ERROR:case vr.SUBTITLE_TRACK_LOAD_TIMEOUT:if(i){const c=a.loadLevelObj;if(c&&(i.type===Ad.AUDIO_TRACK&&c.hasAudioGroup(i.groupId)||i.type===Ad.SUBTITLE_TRACK&&c.hasSubtitleGroup(i.groupId))){n.errorAction=this.getPlaylistRetryOrSwitchAction(n,a.loadLevel),n.errorAction.action=ov.SendAlternateToPenaltyBox,n.errorAction.flags=Pw.MoveAllAlternatesMatchingHost;return}}return;case vr.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:n.errorAction={action:ov.SendAlternateToPenaltyBox,flags:Pw.MoveAllAlternatesMatchingHDCP};return;case vr.KEY_SYSTEM_SESSION_UPDATE_FAILED:case vr.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case vr.KEY_SYSTEM_NO_SESSION:n.errorAction={action:ov.SendAlternateToPenaltyBox,flags:Pw.MoveAllAlternatesMatchingKey};return;case vr.BUFFER_ADD_CODEC_ERROR:case vr.REMUX_ALLOC_ERROR:case vr.BUFFER_APPEND_ERROR:if(!n.errorAction){var o;n.errorAction=this.getLevelSwitchAction(n,(o=n.level)!=null?o:a.loadLevel)}return;case vr.INTERNAL_EXCEPTION:case vr.BUFFER_APPENDING_ERROR:case vr.BUFFER_FULL_ERROR:case vr.LEVEL_SWITCH_ERROR:case vr.BUFFER_STALLED_ERROR:case vr.BUFFER_SEEK_OVER_HOLE:case vr.BUFFER_NUDGE_ON_STALL:n.errorAction=X$();return}n.type===Lo.KEY_SYSTEM_ERROR&&(n.levelRetry=!1,n.errorAction=X$())}getPlaylistRetryOrSwitchAction(t,n){const r=this.hls,a=BCt(r.config.playlistLoadPolicy,t),i=this.playlistError++;if(M6e(a,i,T6e(t),t.response))return{action:ov.RetryRequest,flags:Pw.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=BCt(Vas(t)?l:i,t),c=n.levels.reduce((u,h)=>u+h.fragmentError,0);if(a&&(t.details!==vr.FRAG_GAP&&a.fragmentError++,!Has(t)&&M6e(o,c,T6e(t),t.response)))return{action:ov.RetryRequest,flags:Pw.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===vr.BUFFER_APPEND_ERROR&&a.fragmentError++;let u=-1;const{levels:h,loadLevel:m,minAutoLevel:p,maxAutoLevel:f}=r;!r.autoLevelEnabled&&!r.config.preserveManualLevelOnError&&(r.loadLevel=-1);const y=(i=t.frag)==null?void 0:i.type,g=(y===mo.AUDIO&&d===vr.FRAG_PARSING_ERROR||t.sourceBufferName==="audio"&&(d===vr.BUFFER_ADD_CODEC_ERROR||d===vr.BUFFER_APPEND_ERROR))&&h.some(({audioCodec:E})=>a.audioCodec!==E),j=t.sourceBufferName==="video"&&(d===vr.BUFFER_ADD_CODEC_ERROR||d===vr.BUFFER_APPEND_ERROR)&&h.some(({codecSet:E,audioCodec:P})=>a.codecSet!==E&&a.audioCodec===P),{type:S,groupId:C}=(l=t.context)!=null?l:{};for(let E=h.length;E--;){const P=(E+m)%h.length;if(P!==m&&P>=p&&P<=f&&h[P].loadError===0){var o,c;const M=h[P];if(d===vr.FRAG_GAP&&y===mo.MAIN&&t.frag){const I=h[P].details;if(I){const D=P9(t.frag,I.fragments,t.frag.start);if(D!=null&&D.gap)continue}}else{if(S===Ad.AUDIO_TRACK&&M.hasAudioGroup(C)||S===Ad.SUBTITLE_TRACK&&M.hasSubtitleGroup(C))continue;if(y===mo.AUDIO&&(o=a.audioGroups)!=null&&o.some(I=>M.hasAudioGroup(I))||y===mo.SUBTITLE&&(c=a.subtitleGroups)!=null&&c.some(I=>M.hasSubtitleGroup(I))||g&&a.audioCodec===M.audioCodec||j&&a.codecSet===M.codecSet||!g&&a.codecSet!==M.codecSet)continue}u=P;break}}if(u>-1&&r.loadLevel!==u)return t.levelRetry=!0,this.playlistError=0,{action:ov.SendAlternateToPenaltyBox,flags:Pw.None,nextAutoLevel:u}}return{action:ov.SendAlternateToPenaltyBox,flags:Pw.MoveAllAlternatesMatchingHost}}onErrorOut(t,n){var r;switch((r=n.errorAction)==null?void 0:r.action){case ov.DoNothing:break;case ov.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(n),!n.errorAction.resolved&&n.details!==vr.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 Pw.None:this.switchLevel(t,i);break;case Pw.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=nZe[nZe.indexOf(u)-1],r.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${n.maxHdcpLevel}" or lower`);break}}case Pw.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) ${lv(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=aU(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),Jde(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]=qCt(r,a=>a.fragment.sn>=t))}fragBuffered(t,n){const r=aU(t);let a=this.fragments[r];!a&&n&&(a=this.fragments[r]={body:t,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},t.gap&&(this.hasGaps=!0)),a&&(a.loaded=null,this.bufferedEnd(a,t))}getBufferedTimes(t,n,r,a){const i={time:[],partial:r},l=t.start,o=t.end,c=t.minEndPTS||o,d=t.maxStartPTS||l;for(let u=0;u=h&&c<=m){i.time.push({startPTS:Math.max(l,a.start(u)),endPTS:Math.min(o,a.end(u))});break}else if(lh){const p=Math.max(l,a.start(u)),f=Math.min(o,a.end(u));f>p&&(i.partial=!0,i.time.push({startPTS:p,endPTS:f}))}else if(o<=h)break}return i}getPartialFragment(t){let n=null,r,a,i,l=0;const{bufferPadding:o,fragments:c}=this;return Object.keys(c).forEach(d=>{const u=c[d];u&&Jde(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||Jde(n))}getState(t){const n=aU(t),r=this.fragments[n];return r?r.buffered?Jde(r)?f0.PARTIAL:f0.OK:f0.APPENDING:f0.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=aU(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=aU(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=aU(t);t.clearElementaryStreamInfo();const r=this.activePartLists[t.type];if(r){const a=t.sn;this.activePartLists[t.type]=qCt(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 Jde(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 aU(s){return`${s.type}_${s.level}_${s.sn}`}function qCt(s,t){return s.filter(n=>{const r=t(n);return r||n.clearElementaryStreamInfo(),r})}var XP={cbc:0,ctr:1};class hdr{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 XP.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},n,t);case XP.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 mdr(s){const t=s.byteLength,n=t&&new DataView(s.buffer).getUint8(t-1);return n?s.slice(0,t-n):s}class pdr{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(t){const n=new DataView(t),r=new Uint32Array(4);for(let a=0;a<4;a++)r[a]=n.getUint32(a*4);return r}initTable(){const t=this.sBox,n=this.invSBox,r=this.subMix,a=r[0],i=r[1],l=r[2],o=r[3],c=this.invSubMix,d=c[0],u=c[1],h=c[2],m=c[3],p=new Uint32Array(256);let f=0,y=0,v=0;for(v=0;v<256;v++)v<128?p[v]=v<<1:p[v]=v<<1^283;for(v=0;v<256;v++){let g=y^y<<1^y<<2^y<<3^y<<4;g=g>>>8^g&255^99,t[f]=g,n[g]=f;const b=p[f],j=p[b],S=p[j];let C=p[g]*257^g*16843008;a[f]=C<<24|C>>>8,i[f]=C<<16|C>>>16,l[f]=C<<8|C>>>24,o[f]=C,C=S*16843009^j*65537^b*257^f*16843008,d[g]=C<<24|C>>>8,u[g]=C<<16|C>>>16,h[g]=C<<8|C>>>24,m[g]=C,f?(f=b^p[p[p[S^b]]],y^=p[p[y]]):f=y=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!==XP.cbc||n.byteLength!==16)return Vh.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),o&&(t=RN(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 pdr),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 fdr(this.subtle,n,a)}return this.fastAesKey.expandKey().then(i=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new hdr(this.subtle,new Uint8Array(r),a).decrypt(t.buffer,i)):Promise.reject(new Error("web crypto not initialized"))).catch(i=>(Vh.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%gdr;return r!==t.length&&(n=t.slice(0,r),this.remainderData=t.slice(r)),n}logOnce(t){this.logEnabled&&(Vh.log(`[decrypter]: ${t}`),this.logEnabled=!1)}}const $Ct=Math.pow(2,17);class ydr{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 $3({type:Lo.NETWORK_ERROR,details:vr.FRAG_LOAD_ERROR,fatal:!1,frag:t,error:new Error(`Fragment does not have a ${r?"part list":"url"}`),networkDetails:null}));this.abort();const a=this.config,i=a.fLoader,l=a.loader;return new Promise((o,c)=>{if(this.loader&&this.loader.destroy(),t.gap)if(t.tagList.some(f=>f[0]==="GAP")){c(HCt(t));return}else t.gap=!1;const d=this.loader=i?new i(a):new l(a),u=VCt(t);t.loader=d;const h=UCt(a.fragLoadPolicy.default),m={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:t.sn==="initSegment"?1/0:$Ct};t.stats=d.stats;const p={onSuccess:(f,y,v,g)=>{this.resetLoader(t,d);let b=f.data;v.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(b.slice(0,16)),b=b.slice(16)),o({frag:t,part:null,payload:b,networkDetails:g})},onError:(f,y,v,g)=>{this.resetLoader(t,d),c(new $3({type:Lo.NETWORK_ERROR,details:vr.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:Fh({url:r,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:v,stats:g}))},onAbort:(f,y,v)=>{this.resetLoader(t,d),c(new $3({type:Lo.NETWORK_ERROR,details:vr.INTERNAL_ABORTED,fatal:!1,frag:t,error:new Error("Aborted"),networkDetails:v,stats:f}))},onTimeout:(f,y,v)=>{this.resetLoader(t,d),c(new $3({type:Lo.NETWORK_ERROR,details:vr.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:new Error(`Timeout after ${m.timeout}ms`),networkDetails:v,stats:f}))}};n&&(p.onProgress=(f,y,v,g)=>n({frag:t,part:null,payload:v,networkDetails:g})),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(HCt(t,n));return}const d=this.loader=i?new i(a):new l(a),u=VCt(t,n);t.loader=d;const h=UCt(a.fragLoadPolicy.default),m={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:$Ct};n.stats=d.stats,d.load(u,m,{onSuccess:(p,f,y,v)=>{this.resetLoader(t,d),this.updateStatsFromPart(t,n);const g={frag:t,part:n,payload:p.data,networkDetails:v};r(g),o(g)},onError:(p,f,y,v)=>{this.resetLoader(t,d),c(new $3({type:Lo.NETWORK_ERROR,details:vr.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:n,response:Fh({url:u.url,data:void 0},p),error:new Error(`HTTP Error ${p.code} ${p.text}`),networkDetails:y,stats:v}))},onAbort:(p,f,y)=>{t.stats.aborted=n.stats.aborted,this.resetLoader(t,d),c(new $3({type:Lo.NETWORK_ERROR,details:vr.INTERNAL_ABORTED,fatal:!1,frag:t,part:n,error:new Error("Aborted"),networkDetails:y,stats:p}))},onTimeout:(p,f,y)=>{this.resetLoader(t,d),c(new $3({type:Lo.NETWORK_ERROR,details:vr.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:n,error:new Error(`Timeout after ${m.timeout}ms`),networkDetails:y,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 VCt(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(Wi(a)&&Wi(i)){var l;let o=a,c=i;if(s.sn==="initSegment"&&vdr((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 HCt(s,t){const n=new Error(`GAP ${s.gap?"tag":"attribute"} found`),r={type:Lo.MEDIA_ERROR,details:vr.FRAG_GAP,fatal:!1,frag:s,error:n,networkDetails:null};return t&&(r.part=t),(t||s).stats.aborted=!0,new $3(r)}function vdr(s){return s==="AES-128"||s==="AES-256"}class $3 extends Error{constructor(t){super(t.error.message),this.data=void 0,this.data=t}}class Gas extends GN{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 git{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=eue(),this.buffering={audio:eue(),video:eue(),audiovideo:eue()},this.level=t,this.sn=n,this.id=r,this.size=a,this.part=i,this.partial=l}}function eue(){return{start:0,executeStart:0,executeEnd:0,end:0}}const GCt={length:0,start:()=>0,end:()=>0};class _c{static isBuffered(t,n){if(t){const r=_c.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=_c.getBuffered(t);return _c.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 KCt(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 bdr(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 _dr=/^(\d+)x(\d+)$/,YCt=/(.+?)=(".*?"|.*?)(?:,|$)/g;class kf{constructor(t,n){typeof t=="string"&&(t=kf.parseAttrList(t,n)),pm(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=_dr.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(YCt.lastIndex=0;(r=YCt.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=aZe(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":Vh.warn(`${t}: attribute ${l} is missing quotes`)}a[l]=o}return a}}const wdr="com.apple.hls.interstitial";function jdr(s){return s!=="ID"&&s!=="CLASS"&&s!=="CUE"&&s!=="START-DATE"&&s!=="DURATION"&&s!=="END-DATE"&&s!=="END-ON-NEXT"}function Ndr(s){return s==="SCTE35-OUT"||s==="SCTE35-IN"||s==="SCTE35-CMD"}class Kas{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]){Vh.warn(`DATERANGE tag attribute: "${l}" does not match for tags with ID: "${t.ID}"`),this._badValueForSameId=l;break}t=pm(new kf({}),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"]);Wi(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?(Vh.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(Wi(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===wdr}get isValid(){return!!this.id&&!this._badValueForSameId&&Wi(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 kdr=10;class Sdr{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?Wi(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||kdr}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 P6e(s,t){return s.length===t.length?!s.some((n,r)=>n!==t[r]):!1}function ZCt(s,t){return!s&&!t?!0:!s||!t?!1:P6e(s,t)}function Q$(s){return s==="AES-128"||s==="AES-256"||s==="AES-256-CTR"}function yit(s){switch(s){case"AES-128":case"AES-256":return XP.cbc;case"AES-256-CTR":return XP.ctr;default:throw new Error(`invalid full segment method ${s}`)}}function vit(s){return Uint8Array.from(atob(s),t=>t.charCodeAt(0))}function iZe(s){return Uint8Array.from(unescape(encodeURIComponent(s)),t=>t.charCodeAt(0))}function Cdr(s){const t=iZe(s).subarray(0,16),n=new Uint8Array(16);return n.set(t,16-t.length),n}function Yas(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 Zas(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=vit(l)):n=Cdr(l)}}return n}const L6e=typeof self<"u"?self:void 0;var Pf={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},uv={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function s3e(s){switch(s){case uv.FAIRPLAY:return Pf.FAIRPLAY;case uv.PLAYREADY:return Pf.PLAYREADY;case uv.WIDEVINE:return Pf.WIDEVINE;case uv.CLEARKEY:return Pf.CLEARKEY}}function ZBe(s){switch(s){case Pf.FAIRPLAY:return uv.FAIRPLAY;case Pf.PLAYREADY:return uv.PLAYREADY;case Pf.WIDEVINE:return uv.WIDEVINE;case Pf.CLEARKEY:return uv.CLEARKEY}}function sQ(s){const{drmSystems:t,widevineLicenseUrl:n}=s,r=t?[Pf.FAIRPLAY,Pf.WIDEVINE,Pf.PLAYREADY,Pf.CLEARKEY].filter(a=>!!t[a]):[];return!r[Pf.WIDEVINE]&&n&&r.push(Pf.WIDEVINE),r}const Xas=function(s){return L6e!=null&&(s=L6e.navigator)!=null&&s.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function Adr(s,t,n,r){let a;switch(s){case Pf.FAIRPLAY:a=["cenc","sinf"];break;case Pf.WIDEVINE:case Pf.PLAYREADY:a=["cenc"];break;case Pf.CLEARKEY:a=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${s}`)}return Edr(a,t,n,r)}function Edr(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 Tdr(s){var t;return!!s&&(s.sessionType==="persistent-license"||!!((t=s.sessionTypes)!=null&&t.some(n=>n==="persistent-license")))}function Qas(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=vit(o).subarray(0,16);return Yas(c),c}}return null}let iU={};class NP{static clearKeyUriToKeyIdMap(){iU={}}static setKeyIdForUri(t,n){iU[t]=n}static addKeyIdForUri(t){const n=Object.keys(iU).length%Number.MAX_SAFE_INTEGER,r=new Uint8Array(16);return new DataView(r.buffer,12,4).setUint32(0,n),iU[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&&!Q$(t),l!=null&&l.startsWith("0x")&&(this.keyId=new Uint8Array(Sas(l)))}matches(t){return t.uri===this.uri&&t.method===this.method&&t.encrypted===this.encrypted&&t.keyFormat===this.keyFormat&&P6e(t.keyFormatVersions,this.keyFormatVersions)&&ZCt(t.iv,this.iv)&&ZCt(t.keyId,this.keyId)}isSupported(){if(this.method){if(Q$(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case uv.FAIRPLAY:case uv.WIDEVINE:case uv.PLAYREADY:case uv.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(Q$(this.method)){let i=this.iv;return i||(typeof t!="number"&&(Vh.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0),i=Pdr(t)),new NP(this.method,this.uri,"identity",this.keyFormatVersions,i)}if(this.keyId){const i=iU[this.uri];if(i&&!P6e(this.keyId,i)&&NP.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const r=Zas(this.uri);if(r)switch(this.keyFormat){case uv.WIDEVINE:if(this.pssh=r,!this.keyId){const i=Dcr(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=XCt(n));break;case uv.PLAYREADY:{const i=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=Icr(i,null,r),this.keyId=Qas(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=Mdr(n),i||(i=XCt(n),i||(i=iU[this.uri])),i&&(this.keyId=i,NP.setKeyIdForUri(this.uri,i))}return this}}function Mdr(s){const t=s==null?void 0:s[uv.WIDEVINE];return t?t.keyId:null}function XCt(s){const t=s==null?void 0:s[uv.PLAYREADY];if(t){const n=Zas(t.uri);if(n)return Qas(n)}return null}function Pdr(s){const t=new Uint8Array(16);for(let n=12;n<16;n++)t[n]=s>>8*(15-n)&255;return t}const QCt=/#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,JCt=/#EXT-X-MEDIA:(.*)/g,Ldr=/^#EXT(?:INF|-X-TARGETDURATION):/m,XBe=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),Idr=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 O4{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(JCt.lastIndex=0;(a=JCt.exec(t))!==null;){const d=new kf(a[1],r),u=d.TYPE;if(u){const h=o[u],m=i[u]||[];i[u]=m;const p=d.LANGUAGE,f=d["ASSOC-LANGUAGE"],y=d.CHANNELS,v=d.CHARACTERISTICS,g=d["INSTREAM-ID"],b={attrs:d,bitrate:0,id:c++,groupId:d["GROUP-ID"]||"",name:d.NAME||p||"",type:u,default:d.bool("DEFAULT"),autoselect:d.bool("AUTOSELECT"),forced:d.bool("FORCED"),lang:p,url:d.URI?O4.resolve(d.URI,n):""};if(f&&(b.assocLang=f),y&&(b.channels=y),v&&(b.characteristics=v),g&&(b.instreamId=g),h!=null&&h.length){const j=O4.findGroup(h,b.groupId)||h[0];n3t(b,j,"audioCodec"),n3t(b,j,"textCodec")}m.push(b)}}return i}static parseLevelPlaylist(t,n,r,a,i,l){var o;const c={url:n},d=new Sdr(n),u=d.fragments,h=[];let m=null,p=0,f=0,y=0,v=0,g=0,b=null,j=new WBe(a,c),S,C,E,P=-1,M=!1,I=null,D;if(XBe.lastIndex=0,d.m3u8=t,d.hasVariableRefs=WCt(t),((o=XBe.exec(t))==null?void 0:o[0])!=="#EXTM3U")return d.playlistParsingError=new Error("Missing format identifier #EXTM3U"),d;for(;(S=XBe.exec(t))!==null;){M&&(M=!1,j=new WBe(a,c),j.playlistOffset=y,j.setStart(y),j.sn=p,j.cc=v,g&&(j.bitrate=g),j.level=r,m&&(j.initSegment=m,m.rawProgramDateTime&&(j.rawProgramDateTime=m.rawProgramDateTime,m.rawProgramDateTime=null),I&&(j.setByteRange(I),I=null)));const $=S[1];if($){j.duration=parseFloat($);const H=(" "+S[2]).slice(1);j.title=H||null,j.tagList.push(H?["INF",$,H]:["INF",$])}else if(S[3]){if(Wi(j.duration)){j.playlistOffset=y,j.setStart(y),E&&a3t(j,E,d),j.sn=p,j.level=r,j.cc=v,u.push(j);const H=(" "+S[3]).slice(1);j.relurl=aZe(d,H),oZe(j,b,h),b=j,y+=j.duration,p++,f=0,M=!0}}else{if(S=S[0].match(Idr),!S){Vh.warn("No matches on slow regex match for level playlist!");continue}for(C=1;C0&&i3t(d,H,S),p=d.startSN=parseInt(Y);break;case"SKIP":{d.skippedSegments&&S3(d,H,S);const ne=new kf(Y,d),ce=ne.decimalInteger("SKIPPED-SEGMENTS");if(Wi(ce)){d.skippedSegments+=ce;for(let te=ce;te--;)u.push(null);p+=ce}const ie=ne.enumeratedString("RECENTLY-REMOVED-DATERANGES");ie&&(d.recentlyRemovedDateranges=(d.recentlyRemovedDateranges||[]).concat(ie.split(" ")));break}case"TARGETDURATION":d.targetduration!==0&&S3(d,H,S),d.targetduration=Math.max(parseInt(Y),1);break;case"VERSION":d.version!==null&&S3(d,H,S),d.version=parseInt(Y);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":d.live||S3(d,H,S),d.live=!1;break;case"#":(Y||Z)&&j.tagList.push(Z?[Y,Z]:[Y]);break;case"DISCONTINUITY":v++,j.tagList.push(["DIS"]);break;case"GAP":j.gap=!0,j.tagList.push([H]);break;case"BITRATE":j.tagList.push([H,Y]),g=parseInt(Y)*1e3,Wi(g)?j.bitrate=g:g=0;break;case"DATERANGE":{const ne=new kf(Y,d),ce=new Kas(ne,d.dateRanges[ne.ID],d.dateRangeTagCount);d.dateRangeTagCount++,ce.isValid||d.skippedSegments?d.dateRanges[ce.id]=ce:Vh.warn(`Ignoring invalid DATERANGE tag: "${Y}"`),j.tagList.push(["EXT-X-DATERANGE",Y]);break}case"DEFINE":{{const ne=new kf(Y,d);"IMPORT"in ne?bdr(d,ne,l):KCt(d,ne,n)}break}case"DISCONTINUITY-SEQUENCE":d.startCC!==0?S3(d,H,S):u.length>0&&i3t(d,H,S),d.startCC=v=parseInt(Y);break;case"KEY":{const ne=e3t(Y,n,d);if(ne.isSupported()){if(ne.method==="NONE"){E=void 0;break}E||(E={});const ce=E[ne.keyFormat];ce!=null&&ce.matches(ne)||(ce&&(E=pm({},E)),E[ne.keyFormat]=ne)}else Vh.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${Y}"`);break}case"START":d.startTimeOffset=t3t(Y);break;case"MAP":{const ne=new kf(Y,d);if(j.duration){const ce=new WBe(a,c);r3t(ce,ne,r,E),m=ce,j.initSegment=m,m.rawProgramDateTime&&!j.rawProgramDateTime&&(j.rawProgramDateTime=m.rawProgramDateTime)}else{const ce=j.byteRangeEndOffset;if(ce){const ie=j.byteRangeStartOffset;I=`${ce-ie}@${ie}`}else I=null;r3t(j,ne,r,E),m=j,M=!0}m.cc=v;break}case"SERVER-CONTROL":{D&&S3(d,H,S),D=new kf(Y),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&&S3(d,H,S);const ne=new kf(Y);d.partTarget=ne.decimalFloatingPoint("PART-TARGET");break}case"PART":{let ne=d.partList;ne||(ne=d.partList=[]);const ce=f>0?ne[ne.length-1]:void 0,ie=f++,te=new kf(Y,d),ae=new bcr(te,j,c,ie,ce);ne.push(ae),j.duration+=ae.duration;break}case"PRELOAD-HINT":{const ne=new kf(Y,d);d.preloadHint=ne;break}case"RENDITION-REPORT":{const ne=new kf(Y,d);d.renditionReports=d.renditionReports||[],d.renditionReports.push(ne);break}default:Vh.warn(`line parsed but not handled: ${S}`);break}}}b&&!b.relurl?(u.pop(),y-=b.duration,d.partList&&(d.fragmentHint=b)):d.partList&&(oZe(j,b,h),j.cc=v,d.fragmentHint=j,E&&a3t(j,E,d)),d.targetduration||(d.playlistParsingError=new Error("Missing Target Duration"));const O=u.length,V=u[0],G=u[O-1];if(y+=d.skippedSegments*d.targetduration,y>0&&O&&G){d.averagetargetduration=y/O;const $=G.sn;d.endSN=$!=="initSegment"?$:0,d.live||(G.endList=!0),P>0&&(Rdr(u,P),V&&h.unshift(V))}return d.fragmentHint&&(y+=d.fragmentHint.duration),d.totalduration=y,h.length&&d.dateRangeTagCount&&V&&Jas(h,d),d.endCC=v,d}}function Jas(s,t){let n=s.length;if(!n)if(t.hasProgramDateTime){const o=t.fragments[t.fragments.length-1];s.push(o),n++}else return;const r=s[n-1],a=t.live?1/0:t.totalduration,i=Object.keys(t.dateRanges);for(let o=i.length;o--;){const c=t.dateRanges[i[o]],d=c.startDate.getTime();c.tagAnchor=r.ref;for(let u=n;u--;){var l;if(((l=s[u])==null?void 0:l.sn)=o||r===0){var l;const c=(((l=n[r+1])==null?void 0:l.start)||a)-i.start;if(t<=o+c*1e3){const d=n[r].sn-s.startSN;if(d<0)return-1;const u=s.fragments;if(u.length>n.length){const m=(n[r+1]||u[u.length-1]).sn-s.startSN;for(let p=m;p>d;p--){const f=u[p].programDateTime;if(t>=f&&tr);["video","audio","text"].forEach(r=>{const a=n.filter(i=>mit(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 n3t(s,t,n){const r=t[n];r&&(s[n]=r)}function Rdr(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 oZe(s,t,n){s.rawProgramDateTime?n.push(s):t!=null&&t.programDateTime&&(s.programDateTime=t.endProgramDateTime)}function r3t(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 a3t(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 S3(s,t,n){s.playlistParsingError=new Error(`#EXT-X-${t} must not appear more than once (${n[0]})`)}function i3t(s,t,n){s.playlistParsingError=new Error(`#EXT-X-${t} must appear before the first Media Segment (${n[0]})`)}function QBe(s,t){const n=t.startPTS;if(Wi(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 eis(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(Wi(u)){const g=Math.abs(u-n);s&&g>s.totalduration?l.warn(`media timestamps and playlist times differ by ${g}s for level ${t.level} ${s.url}`):Wi(t.deltaPTS)?t.deltaPTS=Math.max(g,t.deltaPTS):t.deltaPTS=g,c=Math.max(n,u),n=Math.min(n,u),a=t.startDTS!==void 0?Math.min(a,t.startDTS):a,d=Math.min(r,h),r=Math.max(r,h),i=t.endDTS!==void 0?Math.max(i,t.endDTS):i}const m=n-t.start;t.start!==0&&t.setStart(n),t.setDuration(r-t.start),t.startPTS=n,t.maxStartPTS=c,t.startDTS=a,t.endPTS=r,t.minEndPTS=d,t.endDTS=i;const p=t.sn;if(!s||ps.endSN)return 0;let f;const y=p-s.startSN,v=s.fragments;for(v[y]=t,f=y;f>0;f--)QBe(v[f],v[f-1]);for(f=y;f=0;u--){const h=a[u].initSegment;if(h){r=h;break}}s.fragmentHint&&delete s.fragmentHint.endPTS;let i;Bdr(s,t,(u,h,m,p)=>{if((!t.startCC||t.skippedSegments)&&h.cc!==u.cc){const f=u.cc-h.cc;for(let y=m;y{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=Odr(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?eis(t,i,i.startPTS,i.endPTS,i.startDTS,i.endDTS,n):tis(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 Odr(s,t,n){const{dateRanges:r,recentlyRemovedDateranges:a}=t,i=pm({},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 Kas(r[c].attr,d);u.isValid?(i[c]=u,d||(u.tagOrder+=o)):n.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${Lm(r[c].attr)}"`)}),i):r}function zdr(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 Bdr(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&&Udr(m,p)){t.playlistParsingError=o3t(`media sequence mismatch ${h.sn}:`,s,t,u,h);return}else if(u.cc!==h.cc){t.playlistParsingError=o3t(`discontinuity sequence mismatch (${u.cc}!=${h.cc})`,s,t,u,h);return}}}}function o3t(s,t,n,r,a){return new Error(`${s} ${a.url} Playlist starting @${t.startSN} ${t.m3u8} Playlist starting @${n.startSN} ${n.m3u8}`)}function tis(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 Udr(s,t){return s!==t&&t?c3t(s)!==c3t(t):!1}function c3t(s){return s.replace(/\?[^?]*$/,"")}function wee(s,t){for(let r=0,a=s.length;rs.startCC)}function d3t(s,t){const n=s.start+t;s.startPTS=n,s.setStart(n),s.endPTS=n+s.duration}function iis(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=_c.bufferInfo(d||c,h,l.maxBufferHole),p=!m.len;if(this.log(`Media seeking to ${Wi(h)?h.toFixed(3):h}, state: ${u}, ${p?"out of":"in"} buffer`),this.state===la.ENDED)this.resetLoadingState();else if(o){const f=l.maxFragLookUpTolerance,y=o.start-f,v=o.start+o.duration+f;if(p||vm.end){const g=h>v;(hf&&(this.lastCurrentTime=h),!this.loadingParts){const y=Math.max(m.end,h),v=this.shouldLoadParts(this.getLevelDetails(),y);v&&(this.log(`LL-Part loading ON after seeking to ${h.toFixed(2)} with buffer @${y.toFixed(2)}`),this.loadingParts=v)}}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===la.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 ydr(t.config),this.keyLoader=r,this.fragmentTracker=n,this.config=t.config,this.decrypter=new xit(t.config)}registerListeners(){const{hls:t}=this;t.on(Rt.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(Rt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(Rt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Rt.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(Rt.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(Rt.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(Rt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(Rt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Rt.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(Rt.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(t){}stopLoad(){if(this.state===la.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=la.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=_c.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===la.FRAG_LOADING||!this.fragCurrent&&l===la.PARSING)&&(this.fragmentTracker.removeFragment(o),this.state=la.IDLE);return}"payload"in i&&(this.log(`Loaded ${o.type} sn: ${o.sn} of ${this.playlistLabel()} ${o.level}`),this.hls.trigger(Rt.FRAG_LOADED,i)),this._handleFragmentLoadComplete(i)}).catch(i=>{this.state===la.STOPPED||this.state===la.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)===f0.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)===f0.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(Rt.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&&Q$(o.method)){const c=self.performance.now();return this.decrypter.decrypt(new Uint8Array(l),o.key.buffer,o.iv.buffer,yit(o.method)).catch(d=>{throw a.trigger(Rt.ERROR,{type:Lo.MEDIA_ERROR,details:vr.FRAG_DECRYPT_ERROR,fatal:!1,error:d,reason:d.message,frag:i}),d}).then(d=>{const u=self.performance.now();return a.trigger(Rt.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===la.STOPPED||this.state===la.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!==la.STOPPED&&(this.state=la.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(Rt.ERROR,{type:Lo.KEY_SYSTEM_ERROR,details:vr.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?Vdr.toString(_c.getBuffered(r)):"(detached)"})`),ng(t)){var a;if(t.type!==mo.SUBTITLE){const l=t.elementaryStreams;if(!Object.keys(l).some(o=>!!l[o])){this.state=la.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=la.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 git(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=la.KEY_LOADING,this.fragCurrent=t,o=this.keyLoader.load(t).then(m=>{if(!this.fragContextChanged(m.frag))return this.hls.trigger(Rt.KEY_LOADED,m),this.state===la.KEY_LOADING&&(this.state=la.IDLE),m}),this.hls.trigger(Rt.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(ng(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&&ng(t)){const m=l.partList;if(m&&a){r>l.fragmentEnd&&l.fragmentHint&&(t=l.fragmentHint);const p=this.getNextPart(m,t,r);if(p>-1){const f=m[p];t=this.fragCurrent=f.fragment,this.log(`Loading ${t.type} sn: ${t.sn} part: ${f.index} (${p}/${m.length-1}) of ${this.fragInfo(t,!1,f)}) cc: ${t.cc} [${l.startSN}-${l.endSN}], target: ${parseFloat(r.toFixed(3))}`),this.nextLoadPosition=f.start+f.duration,this.state=la.FRAG_LOADING;let y;return o?y=o.then(v=>!v||this.fragContextChanged(v.frag)?null:this.doFragPartsLoad(t,f,n,a)).catch(v=>this.handleFragLoadError(v)):y=this.doFragPartsLoad(t,f,n,a).catch(v=>this.handleFragLoadError(v)),this.hls.trigger(Rt.FRAG_LOADING,{frag:t,part:f,targetBufferTime:r}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):y}else if(!t.url||this.loadedEndOfParts(m,r))return Promise.resolve(null)}}if(ng(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))}`),Wi(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=la.FRAG_LOADING;const u=this.config.progressive&&t.type!==mo.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(Rt.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(Rt.FRAG_LOADED,m);const f=l3t(r.details,t.sn,h.index+1)||ris(d,t.sn,h.index+1);if(f)u(f);else return i({frag:t,part:p,partsLoaded:c})}).catch(l)};u(n)})}handleFragLoadError(t){if("data"in t){const n=t.data;n.frag&&n.details===vr.INTERNAL_ABORTED?this.handleFragLoadAborted(n.frag,n.part):n.frag&&n.type===Lo.KEY_SYSTEM_ERROR?(n.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(n.frag)):this.hls.trigger(Rt.ERROR,n)}else this.hls.trigger(Rt.ERROR,{type:Lo.OTHER_ERROR,details:vr.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null}_handleTransmuxerFlush(t){const n=this.getCurrentContext(t);if(!n||this.state!==la.PARSING){!this.fragCurrent&&this.state!==la.STOPPED&&this.state!==la.ERROR&&(this.state=la.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===mo.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?l3t(c,i,l):null,u=d?d.fragment:nis(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!==la.PARSING)return;const{data1:l,data2:o}=t;let c=l;if(o&&(c=RN(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(Rt.BUFFER_APPENDING,h),t.dropped&&t.independent&&!r){if(i)return;this.flushBufferGap(n)}}flushBufferGap(t){const n=this.media;if(!n)return;if(!_c.isBuffered(n,n.currentTime)){this.flushMainBuffer(0,t.start);return}const r=n.currentTime,a=_c.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(!Wi(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=_c.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 _c.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=mo.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?(v=p,g=p===m?"config":"next load start"):f!==null?(v=f,g="live edge"):(v=t,g="buffer pos"),v=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(u3t(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(u3t(this.config)&&t.type!==mo.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=idr(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=$as(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=P9(i,l,t,y)}else m=l[l.length-1];if(m){const f=m.sn-r.startSN,y=this.fragmentTracker.getState(m);if((y===f0.OK||y===f0.PARTIAL&&m.gap)&&(i=m),i&&m.sn===i.sn&&(!h||u[0].fragment.sn>m.sn||!r.live)&&m.level===i.level){const g=l[f+1];m.sn${t.startSN} fragments: ${a}`),c}return i}waitForCdnTuneIn(t){return t.live&&t.canBlockReload&&t.partTarget&&t.tuneInGoal>Math.max(t.partHoldBack,t.partTarget*3)}setStartPosition(t,n){let r=this.startPosition;r=0&&(r=this.nextLoadPosition),r}handleFragLoadAborted(t,n){this.transmuxer&&t.type===this.playlistType&&ng(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!==la.FRAG_LOADING_WAITING_RETRY)&&(this.state=la.IDLE)}onFragmentOrKeyLoadError(t,n){var r;if(n.chunkMeta&&!n.frag){const g=this.getCurrentContext(n.chunkMeta);g&&(n.frag=g.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===vr.FRAG_GAP;l&&this.fragmentTracker.fragBuffered(a,!0);const o=n.errorAction;if(!o){this.state=la.ERROR;return}const{action:c,flags:d,retryCount:u=0,retryConfig:h}=o,m=!!h,p=m&&c===ov.RetryRequest,f=m&&!o.resolved&&d===Pw.MoveAllAlternatesMatchingHost,y=(r=this.hls.latestLevelDetails)==null?void 0:r.live;if(!p&&f&&ng(a)&&!a.endList&&y&&!Has(n))this.resetFragmentErrors(t),this.treatAsGap(a),o.resolved=!0;else if((p||f)&&u=n||r&&!rZe(0))&&(r&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=la.IDLE)}reduceLengthAndFlushBuffer(t){if(this.state===la.PARSING||this.state===la.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===mo.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==la.STOPPED&&(this.state=la.IDLE)}afterBufferFlushed(t,n,r){if(!t)return;const a=_c.getBuffered(t);this.fragmentTracker.detectEvictedFragments(n,a,r),this.state===la.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==la.STOPPED&&(this.state=la.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:eis(i,t,u.startPTS,u.endPTS,u.startDTS,u.endDTS,this);return this.hls.trigger(Rt.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(Rt.ERROR,{type:Lo.MEDIA_ERROR,details:vr.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=la.PARSED,this.log(`Parsed ${t.type} sn: ${t.sn}${n?" part: "+n.index:""} of ${this.fragInfo(t,!1,n)})`),this.hls.trigger(Rt.FRAG_PARSED,{frag:t,part:n})}playlistLabel(){return this.playlistType===mo.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 u3t(s){return!!s.interstitialsController&&s.enableInterstitialPlayback!==!1}class lis{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=Hdr(t,n);else return new Uint8Array(0);return this.reset(),r}reset(){this.chunks.length=0,this.dataLength=0}}function Hdr(s,t){const n=new Uint8Array(t);let r=0;for(let a=0;a0)return s.subarray(n,n+r)}function Qdr(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(Rt.ERROR,Rt.ERROR,{type:Lo.MEDIA_ERROR,details:vr.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 Vh.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 dis(s,t){return s[t]===255&&(s[t+1]&246)===240}function uis(s,t){return s[t+1]&1?7:9}function jit(s,t){return(s[t+3]&3)<<11|s[t+4]<<3|(s[t+5]&224)>>>5}function Jdr(s,t){return t+5=s.length)return!1;const r=jit(s,t);if(r<=n)return!1;const a=t+r;return a===s.length||D6e(s,a)}return!1}function his(s,t,n,r,a){if(!s.samplerate){const i=Qdr(t,n,r,a);if(!i)return;pm(s,i)}}function mis(s){return 1024*9e4/s}function sur(s,t){const n=uis(s,t);if(t+n<=s.length){const r=jit(s,t)-n;if(r>0)return{headerLength:n,frameLength:r}}}function pis(s,t,n,r,a){const i=mis(s.samplerate),l=r+a*i,o=sur(t,n);let c;if(o){const{frameLength:h,headerLength:m}=o,p=m+h,f=Math.max(0,n+p-t.length);f?(c=new Uint8Array(p-m),c.set(t.subarray(n+m,t.length),0)):c=t.subarray(n+m,n+p);const y={unit:c,pts:l};return f||s.samples.push(y),{sample:y,length:p,missing:f}}const d=t.length-n;return c=new Uint8Array(d),c.set(t.subarray(n,t.length),0),{sample:{unit:c,pts:l},length:d,missing:-1}}function nur(s,t){return wit(s,t)&&oDe(s,t+6)+10<=s.length-t}function rur(s){return s instanceof ArrayBuffer?s:s.byteOffset==0&&s.byteLength==s.buffer.byteLength?s.buffer:new Uint8Array(s).buffer}function eUe(s,t=0,n=1/0){return aur(s,t,n,Uint8Array)}function aur(s,t,n,r){const a=iur(s);let i=1;"BYTES_PER_ELEMENT"in r&&(i=r.BYTES_PER_ELEMENT);const l=our(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 iur(s){return s instanceof ArrayBuffer?s:s.buffer}function our(s){return s&&s.buffer instanceof ArrayBuffer&&s.byteLength!==void 0&&s.byteOffset!==void 0}function lur(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=kj(eUe(s.data,1,r)),i=s.data[2+r],l=s.data.subarray(3+r).indexOf(0);if(l===-1)return;const o=kj(eUe(s.data,3+r,l));let c;return a==="-->"?c=kj(eUe(s.data,4+r+l)):c=rur(s.data.subarray(4+r+l)),t.mimeType=a,t.pictureType=i,t.description=o,t.data=c,t}function cur(s){if(s.size<2)return;const t=kj(s.data,!0),n=new Uint8Array(s.data.subarray(t.length+1));return{key:s.type,info:t,data:n.buffer}}function dur(s){if(s.size<2)return;if(s.type==="TXXX"){let n=1;const r=kj(s.data.subarray(n),!0);n+=r.length+1;const a=kj(s.data.subarray(n));return{key:s.type,info:r,data:a}}const t=kj(s.data.subarray(1));return{key:s.type,info:"",data:t}}function uur(s){if(s.type==="WXXX"){if(s.size<2)return;let n=1;const r=kj(s.data.subarray(n),!0);n+=r.length+1;const a=kj(s.data.subarray(n));return{key:s.type,info:r,data:a}}const t=kj(s.data);return{key:s.type,info:"",data:t}}function hur(s){return s.type==="PRIV"?cur(s):s.type[0]==="W"?uur(s):s.type==="APIC"?lur(s):dur(s)}function mur(s){const t=String.fromCharCode(s[0],s[1],s[2],s[3]),n=oDe(s,4),r=10;return{type:t,size:n,data:s.subarray(r,r+n)}}const tue=10,pur=10;function fis(s){let t=0;const n=[];for(;wit(s,t);){const r=oDe(s,t+6);s[t+5]>>6&1&&(t+=tue),t+=tue;const a=t+r;for(;t+pur0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:Yw.audioId3,duration:Number.POSITIVE_INFINITY});a{if(Wi(s))return s*90;const r=n?n.baseTime*9e4/n.timescale:0;return t*9e4+r};let sue=null;const gur=[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],yur=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],vur=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],bur=[0,1,1,4];function gis(s,t,n,r,a){if(n+24>t.length)return;const i=yis(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 yis(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=gur[c*14+a-1]*1e3,h=yur[(n===3?0:n===2?1:2)*3+i],m=o===3?1:2,p=vur[n][r],f=bur[r],y=p*8*f,v=Math.floor(p*d/h+l)*f;if(sue===null){const j=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);sue=j?parseInt(j[1]):0}return!!sue&&sue<=87&&r===2&&d>=224e3&&o===0&&(s[t+3]=s[t+3]|128),{sampleRate:h,channelCount:m,frameLength:v,samplesPerFrame:y}}}function Sit(s,t){return s[t]===255&&(s[t+1]&224)===224&&(s[t+1]&6)!==0}function vis(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,y=[2,1,2,3,3,4,4,5][h]+p,v=t[n+5]>>3,g=t[n+5]&7,b=new Uint8Array([i<<6|v<<1|g>>2,(g&3)<<6|h<<3|p<<2|c>>4,c<<4&224]),j=1536/o*9e4,S=r+a*j,C=t.subarray(n,n+u);return s.config=b,s.channelCount=y,s.samplerate=o,s.samples.push({unit:C,pts:S}),u}class Nur extends kit{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=Hse(t,0);let r=(n==null?void 0:n.length)||0;if(n&&t[r]===11&&t[r+1]===119&&Nit(n)!==void 0&&_is(t,r)<=16)return!1;for(let a=t.length;r{const l=Pcr(i);if(kur.test(l.schemeIdUri)){const o=m3t(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:Yw.emsg,duration:c})}else if(this.config.enableEmsgKLVMetadata&&l.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const o=m3t(l,n);r.samples.push({data:l.payload,len:l.payload.byteLength,dts:o,pts:o,type:Yw.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 m3t(s,t){return Wi(s.presentationTime)?s.presentationTime/s.timeScale:t+s.presentationTimeDelta/s.timeScale}class Cur{constructor(t,n,r){this.keyData=void 0,this.decrypter=void 0,this.keyData=r,this.decrypter=new xit(n,{removePKCS7Padding:!1})}decryptBuffer(t){return this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer,XP.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 jis{constructor(){this.VideoSample=null}createVideoSample(t,n,r){return{key:t,frame:!1,pts:n,dts:r,units:[],length:0}}getLastNalUnit(t){var n;let r=this.VideoSample,a;if((!r||r.units.length===0)&&(r=t[t.length-1]),(n=r)!=null&&n.units){const i=r.units;a=i[i.length-1]}return a}pushAccessUnit(t,n){if(t.units.length&&t.frame){if(t.pts===void 0){const r=n.samples,a=r.length;if(a){const i=r[a-1];t.pts=i.pts,t.dts=i.dts}else{n.dropped++;return}}n.samples.push(t)}}parseNALu(t,n,r){const a=n.byteLength;let i=t.naluState||0;const l=i,o=[];let c=0,d,u,h,m=-1,p=0;for(i===-1&&(m=0,p=this.getNALuType(n,0),i=0,c=1);c=0){const f={data:n.subarray(m,u),type:p};o.push(f)}else{const f=this.getLastNalUnit(t.samples);f&&(l&&c<=4-l&&f.state&&(f.data=f.data.subarray(0,f.data.byteLength-l)),u>0&&(f.data=RN(f.data,n.subarray(0,u)),f.state=0))}c=0&&i>=0){const f={data:n.subarray(m,a),type:p,state:i};o.push(f)}if(o.length===0){const f=this.getLastNalUnit(t.samples);f&&(f.data=RN(f.data,n))}return t.naluState=i,o}}class jee{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&&Vh.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 Aur extends jis{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 y=!1;o=!0;const v=d.data;if(c&&v.length>4){const g=this.readSliceType(v);(g===2||g===4||g===7||g===9)&&(y=!0)}if(y){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=y;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,hit(d.data,1,r.pts,n.samples);break}case 7:{var p,f;o=!0,c=!0;const y=d.data,v=this.readSPS(y);if(!t.sps||t.width!==v.width||t.height!==v.height||((p=t.pixelRatio)==null?void 0:p[0])!==v.pixelRatio[0]||((f=t.pixelRatio)==null?void 0:f[1])!==v.pixelRatio[1]){t.width=v.width,t.height=v.height,t.pixelRatio=v.pixelRatio,t.sps=[y];const g=y.subarray(1,4);let b="avc1.";for(let j=0;j<3;j++){let S=g[j].toString(16);S.length<2&&(S="0"+S),b+=S}t.codec=b}break}case 8:o=!0,t.pps=[d.data];break;case 9:o=!0,t.audFound=!0,(h=l)!=null&&h.frame&&(this.pushAccessUnit(l,t),l=null),l||(l=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts));break;case 12:o=!0;break;default:o=!1;break}l&&o&&l.units.push(d)}),a&&l&&(this.pushAccessUnit(l,t),this.VideoSample=null)}getNALuType(t,n){return t[n]&31}readSliceType(t){const n=new jee(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,hit(d.data,2,r.pts,n.samples);break;case 32:o=!0,t.vps||(typeof t.params!="object"&&(t.params={}),t.params=pm(t.params,this.readVPS(d.data)),this.initVPS=d.data),t.vps=[d.data];break;case 33:if(o=!0,c=!0,t.vps!==void 0&&t.vps[0]!==this.initVPS&&t.sps!==void 0&&!this.matchSPS(t.sps[0],d.data)&&(this.initVPS=t.vps[0],t.sps=t.pps=void 0),!t.sps){const p=this.readSPS(d.data);t.width=p.width,t.height=p.height,t.pixelRatio=p.pixelRatio,t.codec=p.codecString,t.sps=[],typeof t.params!="object"&&(t.params={});for(const f in p.params)t.params[f]=p.params[f]}this.pushParameterSet(t.sps,d.data,t.vps),l||(l=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts)),l.key=!0;break;case 34:if(o=!0,typeof t.params=="object"){if(!t.pps){t.pps=[];const p=this.readPPS(d.data);for(const f in p)t.params[f]=p[f]}this.pushParameterSet(t.pps,d.data,t.vps)}break;case 35:o=!0,t.audFound=!0,(h=l)!=null&&h.frame&&(this.pushAccessUnit(l,t),l=null),l||(l=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts));break;default:o=!1;break}l&&o&&l.units.push(d)}),a&&l&&(this.pushAccessUnit(l,t),this.VideoSample=null)}pushParameterSet(t,n,r){(r&&r[0]===this.initVPS||!r&&!t.length)&&t.push(n)}getNALuType(t,n){return(t[n]&126)>>>1}ebsp2rbsp(t){const n=new Uint8Array(t.byteLength);let r=0;for(let a=0;a=2&&t[a]===3&&t[a-1]===0&&t[a-2]===0||(n[r]=t[a],r++);return new Uint8Array(n.buffer,0,r)}pushAccessUnit(t,n){super.pushAccessUnit(t,n),this.initVPS&&(this.initVPS=null)}readVPS(t){const n=new jee(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 jee(this.ebsp2rbsp(t));n.readUByte(),n.readUByte(),n.readBits(4);const r=n.readBits(3);n.readBoolean();const a=n.readBits(2),i=n.readBoolean(),l=n.readBits(5),o=n.readUByte(),c=n.readUByte(),d=n.readUByte(),u=n.readUByte(),h=n.readUByte(),m=n.readUByte(),p=n.readUByte(),f=n.readUByte(),y=n.readUByte(),v=n.readUByte(),g=n.readUByte(),b=[],j=[];for(let Ne=0;Ne0)for(let Ne=r;Ne<8;Ne++)n.readBits(2);for(let Ne=0;Ne1&&n.readEG();for(let Ue=0;Ue0&&Xe<16?(ae=nt[Xe-1],le=$e[Xe-1]):Xe===255&&(ae=n.readBits(16),le=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(),pe=n.readBoolean(),pe&&(n.skipUEG(),n.skipUEG(),n.skipUEG(),n.skipUEG()),n.readBoolean()&&(me=n.readBits(32),he=n.readBits(32),n.readBoolean()&&n.readUEG(),n.readBoolean())){const $e=n.readBoolean(),Ge=n.readBoolean();let ct=!1;($e||Ge)&&(ct=n.readBoolean(),ct&&(n.readUByte(),n.readBits(5),n.readBoolean(),n.readBits(5)),n.readBits(4),n.readBits(4),ct&&n.readBits(4),n.readBits(5),n.readBits(5),n.readBits(5));for(let xt=0;xt<=r;xt++){be=n.readBoolean();const qt=be||n.readBoolean();let Vt=!1;qt?n.readEG():Vt=n.readBoolean();const Xt=Vt?1:n.readUEG()+1;if($e)for(let fs=0;fs>Ne&1)<<31-Ne)>>>0;let Se=Ze.toString(16);return l===1&&Se==="2"&&(Se="6"),{codecString:`hvc1.${ze}${l}.${Se}.${i?"H":"L"}${g}.B0`,params:{general_tier_flag:i,general_profile_idc:l,general_profile_space:a,general_profile_compatibility_flags:[o,c,d,u],general_constraint_indicator_flags:[h,m,p,f,y,v],general_level_idc:g,bit_depth:V+8,bit_depth_luma_minus8:V,bit_depth_chroma_minus8:G,min_spatial_segmentation_idc:te,chroma_format_idc:S,frame_rate:{fixed:be,fps:he/me}},width:Ae,height:Pe,pixelRatio:[ae,le]}}readPPS(t){const n=new jee(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 Q0=188;class b6{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=b6.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(Q0*5,n-Q0)+1,a=0;for(;a1&&(l===0&&o>2||c+Q0>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:Eas[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=b6.createTrack("video"),this._videoTrack.duration=a,this._audioTrack=b6.createTrack("audio",a),this._id3Track=b6.createTrack("id3"),this._txtTrack=b6.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=n,this.videoCodec=r}resetTimeStamp(){}resetContiguity(){const{_audioTrack:t,_videoTrack:n,_id3Track:r}=this;t&&(t.pesData=null),n&&(n.pesData=null),r&&(r.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(t,n,r=!1,a=!1){r||(this.sampleAes=null);let i;const l=this._videoTrack,o=this._audioTrack,c=this._id3Track,d=this._txtTrack;let u=l.pid,h=l.pesData,m=o.pid,p=c.pid,f=o.pesData,y=c.pesData,v=null,g=this.pmtParsed,b=this._pmtId,j=t.length;if(this.remainderData&&(t=RN(this.remainderData,t),j=t.length,this.remainderData=null),j>4;let O;if(D>1){if(O=P+5+t[P+4],O===P+Q0)continue}else O=P+4;switch(I){case u:M&&(h&&(i=oU(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(O,P+Q0)),h.size+=P+Q0-O);break;case m:if(M){if(f&&(i=oU(f,this.logger)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,i);break;case"mp3":this.parseMPEGPES(o,i);break;case"ac3":this.parseAC3PES(o,i);break}f={data:[],size:0}}f&&(f.data.push(t.subarray(O,P+Q0)),f.size+=P+Q0-O);break;case p:M&&(y&&(i=oU(y,this.logger))&&this.parseID3PES(c,i),y={data:[],size:0}),y&&(y.data.push(t.subarray(O,P+Q0)),y.size+=P+Q0-O);break;case 0:M&&(O+=t[O]+1),b=this._pmtId=Tur(t,O);break;case b:{M&&(O+=t[O]+1);const V=Mur(t,O,this.typeSupported,r,this.observer,this.logger);u=V.videoPid,u>0&&(l.pid=u,l.segmentCodec=V.segmentVideoCodec),m=V.audioPid,m>0&&(o.pid=m,o.segmentCodec=V.segmentAudioCodec),p=V.id3Pid,p>0&&(c.pid=p),v!==null&&!g&&(this.logger.warn(`MPEG-TS PMT found at ${P} after unknown PID '${v}'. Backtracking to sync byte @${S} to parse all TS packets.`),v=null,P=S-188),g=this.pmtParsed=!0;break}case 17:case 8191:break;default:v=I;break}}else C++;C>0&&dZe(this.observer,new Error(`Found ${C} TS packet/s that do not start with 0x47`),void 0,this.logger),l.pesData=h,o.pesData=f,c.pesData=y;const E={audioTrack:o,videoTrack:l,id3Track:c,textTrack:d};return a&&this.extractRemainingSamples(E),E}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=oU(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=oU(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=oU(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 Cur(this.observer,this.config,n);return this.decrypt(a,i)}readyVideoParser(t){this.videoParser===null&&(t==="avc"?this.videoParser=new Aur:t==="hevc"&&(this.videoParser=new Eur))}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=RN(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=pm({},n,{type:this._videoTrack?Yw.emsg:Yw.audioId3,duration:Number.POSITIVE_INFINITY});t.samples.push(r)}}function cZe(s,t){return((s[t+1]&31)<<8)+s[t+2]}function Tur(s,t){return(s[t+10]&31)<<8|s[t+11]}function Mur(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 y=s[m+1]+2;m+=y,p-=y}}break;case 194:case 135:return dZe(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 dZe(s,t,n,r){r.warn(`parsing error: ${t.message}`),s.emit(Rt.ERROR,Rt.ERROR,{type:Lo.MEDIA_ERROR,details:vr.FRAG_PARSING_ERROR,fatal:!1,levelRetry:n,error:t,reason:t.message})}function tUe(s,t){t.log(`${s} with AES-128-CBC encryption found in unencrypted stream`)}function oU(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]=RN(c[0],c[1]),c.splice(1,1);if(r=c[0],(r[0]<<16)+(r[1]<<8)+r[2]===1){if(a=(r[4]<<8)+r[5],a&&a>s.size-6)return null;const u=r[7];u&192&&(l=(r[9]&14)*536870912+(r[10]&255)*4194304+(r[11]&254)*16384+(r[12]&255)*128+(r[13]&254)/2,u&64?(o=(r[14]&14)*536870912+(r[15]&255)*4194304+(r[16]&254)*16384+(r[17]&255)*128+(r[18]&254)/2,l-o>60*9e4&&(t.warn(`${Math.round((l-o)/9e4)}s delta between PTS and DTS, align them`),l=o)):o=l),i=r[8];let h=i+9;if(s.size<=h)return null;s.size-=h;const m=new Uint8Array(s.size);for(let p=0,f=c.length;py){h-=y;continue}else r=r.subarray(h),y-=h,h=0;m.set(r,n),n+=y}return a&&(a-=i+3),{data:m,pts:l,dts:o,len:a}}return null}class Pur{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 IT=Math.pow(2,32)-1;class xr{static init(){xr.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 xr.types)xr.types.hasOwnProperty(t)&&(xr.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]);xr.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]);xr.STTS=xr.STSC=xr.STCO=i,xr.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),xr.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),xr.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),xr.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]);xr.FTYP=xr.box(xr.types.ftyp,l,c,l,o),xr.DINF=xr.box(xr.types.dinf,xr.box(xr.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 xr.box(xr.types.mdia,xr.mdhd(t.timescale||0,t.duration||0),xr.hdlr(t.type),xr.minf(t))}static mfhd(t){return xr.box(xr.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"?xr.box(xr.types.minf,xr.box(xr.types.smhd,xr.SMHD),xr.DINF,xr.stbl(t)):xr.box(xr.types.minf,xr.box(xr.types.vmhd,xr.VMHD),xr.DINF,xr.stbl(t))}static moof(t,n,r){return xr.box(xr.types.moof,xr.mfhd(t),xr.traf(r,n))}static moov(t){let n=t.length;const r=[];for(;n--;)r[n]=xr.trak(t[n]);return xr.box.apply(null,[xr.types.moov,xr.mvhd(t[0].timescale||0,t[0].duration||0)].concat(r).concat(xr.mvex(t)))}static mvex(t){let n=t.length;const r=[];for(;n--;)r[n]=xr.trex(t[n]);return xr.box.apply(null,[xr.types.mvex,...r])}static mvhd(t,n){n*=t;const r=Math.floor(n/(IT+1)),a=Math.floor(n%(IT+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 xr.box(xr.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=xr.box(xr.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 xr.box(xr.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,xr.box(xr.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),xr.box(xr.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 xr.box(xr.types.mp4a,xr.audioStsd(t),xr.box(xr.types.esds,xr.esds(t)))}static mp3(t){return xr.box(xr.types[".mp3"],xr.audioStsd(t))}static ac3(t){return xr.box(xr.types["ac-3"],xr.audioStsd(t),xr.box(xr.types.dac3,t.config))}static stsd(t){const{segmentCodec:n}=t;if(t.type==="audio"){if(n==="aac")return xr.box(xr.types.stsd,xr.STSD,xr.mp4a(t));if(n==="ac3"&&t.config)return xr.box(xr.types.stsd,xr.STSD,xr.ac3(t));if(n==="mp3"&&t.codec==="mp3")return xr.box(xr.types.stsd,xr.STSD,xr.mp3(t))}else if(t.pps&&t.sps){if(n==="avc")return xr.box(xr.types.stsd,xr.STSD,xr.avc1(t));if(n==="hevc"&&t.vps)return xr.box(xr.types.stsd,xr.STSD,xr.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/(IT+1)),o=Math.floor(r%(IT+1));return xr.box(xr.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=xr.sdtp(t),a=t.id,i=Math.floor(n/(IT+1)),l=Math.floor(n%(IT+1));return xr.box(xr.types.traf,xr.box(xr.types.tfhd,new Uint8Array([0,0,0,0,a>>24,a>>16&255,a>>8&255,a&255])),xr.box(xr.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])),xr.trun(t,r.length+16+20+8+16+8+8),r)}static trak(t){return t.duration=t.duration||4294967295,xr.box(xr.types.trak,xr.tkhd(t),xr.mdia(t))}static trex(t){const n=t.id;return xr.box(xr.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 xr.box(xr.types.trun,l)}static initSegment(t){xr.types||xr.init();const n=xr.moov(t);return RN(xr.FTYP,n)}static hvc1(t){const n=t.params,r=[t.vps,t.sps,t.pps],a=4,i=new Uint8Array([1,n.general_profile_space<<6|(n.general_tier_flag?32:0)|n.general_profile_idc,n.general_profile_compatibility_flags[0],n.general_profile_compatibility_flags[1],n.general_profile_compatibility_flags[2],n.general_profile_compatibility_flags[3],n.general_constraint_indicator_flags[0],n.general_constraint_indicator_flags[1],n.general_constraint_indicator_flags[2],n.general_constraint_indicator_flags[3],n.general_constraint_indicator_flags[4],n.general_constraint_indicator_flags[5],n.general_level_idc,240|n.min_spatial_segmentation_idc>>8,255&n.min_spatial_segmentation_idc,252|n.parallelismType,252|n.chroma_format_idc,248|n.bit_depth_luma_minus8,248|n.bit_depth_chroma_minus8,0,parseInt(n.frame_rate.fps),a-1|n.temporal_id_nested<<2|n.num_temporal_layers<<3|(n.frame_rate.fixed?64:0),r.length]);let l=i.length;for(let f=0;f>8,r[f][y].length&255]),l),l+=2,o.set(r[f][y],l),l+=r[f][y].length}const d=xr.box(xr.types.hvcC,o),u=t.width,h=t.height,m=t.pixelRatio[0],p=t.pixelRatio[1];return xr.box(xr.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,xr.box(xr.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),xr.box(xr.types.pasp,new Uint8Array([m>>24,m>>16&255,m>>8&255,m&255,p>>24,p>>16&255,p>>8&255,p&255])))}}xr.types=void 0;xr.HDLR_TYPES=void 0;xr.STTS=void 0;xr.STSC=void 0;xr.STCO=void 0;xr.STSZ=void 0;xr.VMHD=void 0;xr.SMHD=void 0;xr.STSD=void 0;xr.FTYP=void 0;xr.DINF=void 0;const Nis=9e4;function Cit(s,t,n=1,r=!1){const a=s*t*n;return r?Math.round(a):a}function Lur(s,t,n=1,r=!1){return Cit(s,t,1/n,r)}function BZ(s,t=!1){return Cit(s,1e3,1/Nis,t)}function Iur(s,t=1){return Cit(s,Nis,1/t)}function p3t(s){const{baseTime:t,timescale:n,trackId:r}=s;return`${t/n} (${t}/${n}) trackId: ${r}`}const Dur=10*1e3,Rur=1024,Fur=1152,Our=1536;let lU=null,sUe=null;function f3t(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 n3e extends GN{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,lU===null){const l=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);lU=l?parseInt(l[1]):0}if(sUe===null){const i=navigator.userAgent.match(/Safari\/(\d+)/i);sUe=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&&p3t(n)} > ${t&&p3t(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=$w(o,r),c=o-i),c>0?i:o},r);return n&&this.debug("PTS rollover detected"),a}remux(t,n,r,a,i,l,o,c){let d,u,h,m,p,f,y=i,v=i;const g=t.pid>-1,b=n.pid>-1,j=n.samples.length,S=t.samples.length>0,C=o&&j>0||j>1;if((!g||S)&&(!b||C)||this.ISGenerated||o){if(this.ISGenerated){var P,M,I,D;const $=this.videoTrackConfig;($&&(n.width!==$.width||n.height!==$.height||((P=n.pixelRatio)==null?void 0:P[0])!==((M=$.pixelRatio)==null?void 0:M[0])||((I=n.pixelRatio)==null?void 0:I[1])!==((D=$.pixelRatio)==null?void 0:D[1]))||!$&&C||this.nextAudioTs===null&&S)&&this.resetInitSegment()}this.ISGenerated||(h=this.generateIS(t,n,i,l));const O=this.isVideoContiguous;let V=-1,G;if(C&&(V=zur(n.samples),!O&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,V>0){this.warn(`Dropped ${V} out of ${j} video samples due to a missing keyframe`);const $=this.getVideoStartPts(n.samples);n.samples=n.samples.slice(V),n.dropped+=V,v+=(n.samples[0].pts-$)/n.inputTimeScale,G=v}else V===-1&&(this.warn(`No keyframe found out of ${j} video samples`),f=!1);if(this.ISGenerated){if(S&&C){const $=this.getVideoStartPts(n.samples),Y=($w(t.samples[0].pts,$)-$)/n.inputTimeScale;y+=Math.max(0,Y),v+=Math.max(0,-Y)}if(S){if(t.samplerate||(this.warn("regenerate InitSegment as audio detected"),h=this.generateIS(t,n,i,l)),u=this.remuxAudio(t,y,this.isAudioContiguous,l,b||C||c===mo.AUDIO?v:void 0),C){const $=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,v,O,$)}}else C&&(d=this.remuxVideo(n,v,O,0));d&&(d.firstKeyFrame=V,d.independent=V!==-1,d.firstKeyFramePTS=G)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(r.samples.length&&(p=kis(r,i,this._initPTS,this._initDTS)),a.samples.length&&(m=Sis(a,i,this._initPTS))),{audio:u,video:d,initSegment:h,independent:f,text:m,id3:p}}computeInitPts(t,n,r,a){const i=Math.round(r*n);let l=$w(t,i);if(l0?te-1:te].dts&&(b=!0)}b&&l.sort(function(te,ae){const le=te.dts-ae.dts,be=te.pts-ae.pts;return le||be}),f=l[0].dts,y=l[l.length-1].dts;const S=y-f,C=S?Math.round(S/(c-1)):p||t.inputTimeScale/30;if(r){const te=f-j,ae=te>C,le=te<-1;if((ae||le)&&(ae?this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${BZ(te,!0)} ms (${te}dts) hole between fragments detected at ${n.toFixed(3)}`):this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${BZ(-te,!0)} ms (${te}dts) overlapping between fragments detected at ${n.toFixed(3)}`),!le||j>=l[0].pts||lU)){f=j;const be=l[0].pts-te;if(ae)l[0].dts=f,l[0].pts=be;else{let me=!0;for(let he=0;hebe&&me);he++){const pe=l[he].pts;if(l[he].dts-=te,l[he].pts-=te,he0?ae.dts-l[te-1].dts:C;if(me=te>0?ae.pts-l[te-1].pts:C,pe.stretchShortVideoTrack&&this.nextAudioTs!==null){const Ae=Math.floor(pe.maxBufferHole*i),Pe=(a?v+a*i:this.nextAudioTs+u)-ae.pts;Pe>Ae?(p=Pe-Ce,p<0?p=Ce:V=!0,this.log(`It is approximately ${Pe/90} ms to the next segment; using duration ${p/90} ms for the last video frame.`)):p=Ce}else p=Ce}const he=Math.round(ae.pts-ae.dts);G=Math.min(G,p),H=Math.max(H,p),$=Math.min($,me),Y=Math.max(Y,me),o.push(f3t(ae.key,p,be,he))}if(o.length){if(lU){if(lU<70){const te=o[0].flags;te.dependsOn=2,te.isNonSync=0}}else if(sUe&&Y-$0&&(a&&Math.abs(j-(g+b))<9e3||Math.abs($w(y[0].pts,j)-(g+b))<20*u),y.forEach(function(Y){Y.pts=$w(Y.pts,j)}),!r||g<0){const Y=y.length;if(y=y.filter(Z=>Z.pts>=0),Y!==y.length&&this.warn(`Removed ${y.length-Y} of ${Y} samples (initPTS ${b} / ${l})`),!y.length)return;i===0?g=0:a&&!f?g=Math.max(0,j-b):g=y[0].pts-b}if(t.segmentCodec==="aac"){const Y=this.config.maxAudioFramesDrift;for(let Z=0,ne=g+b;Z=Y*u&&ae0){P+=v;try{E=new Uint8Array(P)}catch(ae){this.observer.emit(Rt.ERROR,Rt.ERROR,{type:Lo.MUX_ERROR,details:vr.REMUX_ALLOC_ERROR,fatal:!1,error:ae,bytes:P,reason:`fail allocating audio mdat ${P}`});return}m||(new DataView(E.buffer).setUint32(0,P),E.set(xr.types.mdat,4))}else return;E.set(ce,v);const te=ce.byteLength;v+=te,p.push(f3t(!0,d,te,0)),C=ie}const I=p.length;if(!I)return;const D=p[p.length-1];g=C-b,this.nextAudioTs=g+c*D.duration;const O=m?new Uint8Array(0):xr.moof(t.sequenceNumber++,S/c,pm({},t,{samples:p}));t.samples=[];const V=(S-b)/l,G=this.nextAudioTs/l,H={data1:O,data2:E,startPTS:V,endPTS:G,startDTS:V,endDTS:G,type:"audio",hasAudio:!0,hasVideo:!1,nb:I};return this.isAudioContiguous=!0,H}}function $w(s,t){let n;if(t===null)return s;for(t4294967296;)s+=n;return s}function zur(s){for(let t=0;tl.pts-o.pts);const i=s.samples;return s.samples=[],{samples:i}}class Bur extends GN{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=Pas(t);if(n)Ccr(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=x3t(i,Am.AUDIO,this)),l&&(a=x3t(l,Am.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};Wi(u)||(u=this.lastEndTime=i||0);const m=n.samples;if(!m.length)return h;const p={initPTS:void 0,timescale:void 0,trackId:void 0};let f=this.initData;if((o=f)!=null&&o.length||(this.generateInitSegment(m),f=this.initData),!((c=f)!=null&&c.length))return this.warn("Failed to generate initSegment."),h;this.emitInitSegment&&(p.tracks=this.initTracks,this.emitInitSegment=!1);const y=Ecr(m,f,this),v=f.audio?y[f.audio.id]:null,g=f.video?y[f.video.id]:null,b=nue(g,1/0),j=nue(v,1/0),S=nue(g,0,!0),C=nue(v,0,!0);let E=i,P=0;const M=v&&(!g||!d&&j0?this.lastEndTime=O:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const V=!!f.audio,G=!!f.video;let $="";V&&($+="audio"),G&&($+="video");const H=(f.audio?f.audio.encrypted:!1)||(f.video?f.video.encrypted:!1),Y={data1:m,startPTS:D,startDTS:D,endPTS:O,endDTS:O,type:$,hasAudio:V,hasVideo:G,nb:1,dropped:0,encrypted:H};h.audio=V&&!G?Y:void 0,h.video=G?Y:void 0;const Z=g==null?void 0:g.sampleCount;if(Z){const ne=g.keyFrameIndex,ce=ne!==-1;Y.nb=Z,Y.dropped=ne===0||this.isVideoContiguous?0:ce?ne:Z,Y.independent=ce,Y.firstKeyFrame=ne,ce&&g.keyFrameStart&&(Y.firstKeyFramePTS=(g.keyFrameStart-d.baseTime)/d.timescale),this.isVideoContiguous||(h.independent=ce),this.isVideoContiguous||(this.isVideoContiguous=ce),Y.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${ne}/${Z} dropped: ${Y.dropped} start: ${Y.firstKeyFramePTS||"NA"}`)}return h.initSegment=p,h.id3=kis(r,i,d,d),a.samples.length&&(h.text=Sis(a,i,d)),h}}function nue(s,t,n=!1){return(s==null?void 0:s.start)!==void 0?(s.start+(n?s.duration:0))/s.timescale:t}function Uur(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 x3t(s,t,n){const r=s.codec;return r&&r.length>4?r:t===Am.AUDIO?r==="ec-3"||r==="ac-3"||r==="alac"?r:r==="fLaC"||r==="Opus"?C6e(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 V3;try{V3=self.performance.now.bind(self.performance)}catch{V3=Date.now}const r3e=[{demux:Sur,remux:Bur},{demux:b6,remux:n3e},{demux:wur,remux:n3e},{demux:Nur,remux:n3e}];r3e.splice(2,0,{demux:jur,remux:n3e});class g3t{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=V3();let l=new Uint8Array(t);const{currentTransmuxState:o,transmuxConfig:c}=this;a&&(this.currentTransmuxState=a);const{contiguous:d,discontinuity:u,trackSwitch:h,accurateTimeOffset:m,timeOffset:p,initSegmentChange:f}=a||o,{audioCodec:y,videoCodec:v,defaultInitPts:g,duration:b,initSegmentData:j}=c,S=qur(l,n);if(S&&Q$(S.method)){const M=this.getDecrypter(),I=yit(S.method);if(M.isSync()){let D=M.softwareDecrypt(l,S.key.buffer,S.iv.buffer,I);if(r.part>-1){const V=M.flush();D=V&&V.buffer}if(!D)return i.executeEnd=V3(),nUe(r);l=new Uint8Array(D)}else return this.asyncResult=!0,this.decryptionPromise=M.webCryptoDecrypt(l,S.key.buffer,S.iv.buffer,I).then(D=>{const O=this.push(D,null,r);return this.decryptionPromise=null,O}),this.decryptionPromise}const C=this.needsProbing(u,h);if(C){const M=this.configureTransmuxer(l);if(M)return this.logger.warn(`[transmuxer] ${M.message}`),this.observer.emit(Rt.ERROR,Rt.ERROR,{type:Lo.MEDIA_ERROR,details:vr.FRAG_PARSING_ERROR,fatal:!1,error:M,reason:M.message}),i.executeEnd=V3(),nUe(r)}(u||h||f||C)&&this.resetInitSegment(j,y,v,b,n),(u||f||C)&&this.resetInitialTimestamp(g),d||this.resetContiguity();const E=this.transmux(l,S,p,m,r);this.asyncResult=Gse(E);const P=this.currentTransmuxState;return P.contiguous=!0,P.discontinuity=!1,P.trackSwitch=!1,i.executeEnd=V3(),E}flush(t){const n=t.transmuxing;n.executeStart=V3();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=V3();const h=[nUe(t)];return this.asyncResult?Promise.resolve(h):h}const u=c.flush(o);return Gse(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===mo.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=V3()}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=r3e.length;h0&&(t==null?void 0:t.key)!=null&&t.iv!==null&&t.method!=null&&(n=t),n}const nUe=s=>({remuxResult:{},chunkMeta:s});function Gse(s){return"then"in s&&s.then instanceof Function}class $ur{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 Vur{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 y3t=0;class Cis{constructor(t,n,r,a){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=y3t++,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(Rt.ERROR,{type:Lo.OTHER_ERROR,details:vr.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===Rt.ERROR&&(d=d,d.parent=this.id,d.part=this.part,this.error=d.error),this.hls.trigger(c,d)};this.observer=new _it,this.observer.on(Rt.FRAG_DECRYPTED,l),this.observer.on(Rt.ERROR,l);const o=LCt(i.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const c=this.hls.logger;if(i.workerPath||Kdr()){try{i.workerPath?(c.log(`loading Web Worker ${i.workerPath} for "${n}"`),this.workerContext=Zdr(i.workerPath)):(c.log(`injecting Web Worker for "${n}"`),this.workerContext=Ydr());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:Lm(i)})}catch(u){c.warn(`Error setting up "${n}" Web Worker, fallback to inline`,u),this.terminateWorker(),this.error=null,this.transmuxer=new g3t(this.observer,o,i,"",n,t.logger)}return}}this.transmuxer=new g3t(this.observer,o,i,"",n,t.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const t=this.instanceNo;this.instanceNo=y3t++;const n=this.hls.config,r=LCt(n.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:t,typeSupported:r,id:this.id,config:Lm(n)})}}terminateWorker(){if(this.workerContext){const{worker:t}=this.workerContext;this.workerContext=null,t.removeEventListener("message",this.onWorkerMessage),t.removeEventListener("error",this.onWorkerError),Xdr(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const n=this.transmuxer;n&&(n.destroy(),this.transmuxer=null)}const t=this.observer;t&&t.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(t,n,r,a,i,l,o,c,d,u){var h,m;d.transmuxing.start=self.performance.now();const{instanceNo:p,transmuxer:f}=this,y=l?l.start:i.start,v=i.decryptdata,g=this.frag,b=!(g&&i.cc===g.cc),j=!(g&&d.level===g.level),S=g?d.sn-g.sn:-1,C=this.part?d.part-this.part.index:-1,E=S===0&&d.id>1&&d.id===(g==null?void 0:g.stats.chunkCount),P=!j&&(S===1||S===0&&(C===1||E&&C<=0)),M=self.performance.now();(j||S||i.stats.parsing.start===0)&&(i.stats.parsing.start=M),l&&(C||!P)&&(l.stats.parsing.start=M);const I=!(g&&((h=i.initSegment)==null?void 0:h.url)===((m=g.initSegment)==null?void 0:m.url)),D=new Vur(b,P,c,j,y,I);if(!P||b||I){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${i.type} sn: ${d.sn}${d.part>-1?" part: "+d.part:""} ${this.id===mo.MAIN?"level":"track"}: ${d.level} id: ${d.id} discontinuity: ${b} trackSwitch: ${j} contiguous: ${P} accurateTimeOffset: ${c} timeOffset: ${y} initSegmentChange: ${I}`);const O=new $ur(r,a,n,o,u);this.configureTransmuxer(O)}if(this.frag=i,this.part=l,this.workerContext)this.workerContext.worker.postMessage({instanceNo:p,cmd:"demux",data:t,decryptdata:v,chunkMeta:d,state:D},t instanceof ArrayBuffer?[t]:[]);else if(f){const O=f.push(t,v,d,D);Gse(O)?O.then(V=>{this.handleTransmuxComplete(V)}).catch(V=>{this.transmuxerError(V,d,"transmuxer-interface push error")}):this.handleTransmuxComplete(O)}}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);Gse(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(Rt.ERROR,{type:Lo.MEDIA_ERROR,details:vr.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 v3t=100;class Hur extends bit{constructor(t,n,r){super(t,n,r,"audio-stream-controller",mo.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(Rt.LEVEL_LOADED,this.onLevelLoaded,this),t.on(Rt.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.on(Rt.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(Rt.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(Rt.BUFFER_RESET,this.onBufferReset,this),t.on(Rt.BUFFER_CREATED,this.onBufferCreated,this),t.on(Rt.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(Rt.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(Rt.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(Rt.FRAG_LOADING,this.onFragLoading,this),t.on(Rt.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:t}=this;t&&(super.unregisterListeners(),t.off(Rt.LEVEL_LOADED,this.onLevelLoaded,this),t.off(Rt.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.off(Rt.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(Rt.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(Rt.BUFFER_RESET,this.onBufferReset,this),t.off(Rt.BUFFER_CREATED,this.onBufferCreated,this),t.off(Rt.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(Rt.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(Rt.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(Rt.FRAG_LOADING,this.onFragLoading,this),t.off(Rt.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(t,{frag:n,id:r,initPTS:a,timescale:i,trackId:l}){if(r===mo.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===la.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===la.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=$as(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===la.IDLE&&this.doTickIdle())}startLoad(t,n){if(!this.levels){this.startPosition=t,this.state=la.STOPPED;return}const r=this.lastCurrentTime;this.stopLoad(),this.setInterval(v3t),r>0&&t===-1?(this.log(`Override startPosition with lastCurrentTime @${r.toFixed(3)}`),t=r,this.state=la.IDLE):this.state=la.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=n?-1:t,this.tick()}doTick(){switch(this.state){case la.IDLE:this.doTickIdle();break;case la.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=la.WAITING_INIT_PTS}break}case la.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case la.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=la.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=la.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=la.WAITING_TRACK,this.startFragRequested=!1;return}const d=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&d&&(this.bufferFlushed=!1,this.afterBufferFlushed(d,Am.AUDIO,mo.AUDIO));const u=this.getFwdBufferInfo(d,mo.AUDIO);if(u===null)return;if(!this.switchingTrack&&this._streamEnded(u,c)){n.trigger(Rt.BUFFER_EOS,{type:"audio"}),this.state=la.ENDED;return}const h=u.len,m=n.maxBufferLength,p=c.fragments,f=p[0].start,y=this.getLoadPosition(),v=this.flushing?y:u.end;if(this.switchingTrack&&a){const j=y;c.PTSKnown&&jf||u.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),a.currentTime=f+.05)}if(h>=m&&!this.switchingTrack&&vb.end){const S=this.fragmentTracker.getFragAtPos(v,mo.MAIN);S&&S.end>b.end&&(b=S,this.mainFragLoading={frag:S,targetBufferTime:null})}if(g.start>b.end)return}this.loadFragment(g,o,v)}onMediaDetaching(t,n){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(t,n)}onAudioTracksUpdated(t,{audioTracks:n}){this.resetTransmuxer(),this.levels=n.map(r=>new $se(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!==la.STOPPED&&(this.setInterval(v3t),this.state=la.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(Rt.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!==la.STOPPED&&(this.state=la.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||(ois(i,d),i.alignedSliding||I6e(i,d),h=i.fragmentStart)}u.details=i,this.levelLastLoaded=u,this.startFragRequested||this.setStartPosition(d,h),this.hls.trigger(Rt.AUDIO_TRACK_UPDATED,{details:i,id:l,groupId:n.groupId}),this.state===la.WAITING_TRACK&&!this.waitForCdnTuneIn(i)&&(this.state=la.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 Cis(this.hls,mo.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const p=this.initPTS[r.cc],f=(n=r.initSegment)==null?void 0:n.data;if(p!==void 0){const v=a?a.index:-1,g=v!==-1,b=new git(r.level,r.sn,r.stats.chunkCount,i.byteLength,v,g);m.push(i,f,h,"",r,a,u.totalduration,!1,b,p)}else{this.log(`Unknown video PTS for cc ${r.cc}, waiting for video PTS before demuxing audio frag ${r.sn} of [${u.startSN} ,${u.endSN}],track ${o}`);const{cache:y}=this.waitingData=this.waitingData||{frag:r,part:a,cache:new lis,complete:!1};y.push(new Uint8Array(i)),this.state!==la.STOPPED&&(this.state=la.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===mo.MAIN&&ng(n.frag)&&(this.mainFragLoading=n,this.state===la.IDLE&&this.tick())}onFragBuffered(t,n){const{frag:r,part:a}=n;if(r.type!==mo.AUDIO){!this.audioOnly&&r.type===mo.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(ng(r)){this.fragPrevious=r;const i=this.switchingTrack;i&&(this.bufferedTrack=i,this.switchingTrack=null,this.hls.trigger(Rt.AUDIO_TRACK_SWITCHED,Fh({},i)))}this.fragBufferedComplete(r,a),this.media&&this.tick()}onError(t,n){var r;if(n.fatal){this.state=la.ERROR;return}switch(n.details){case vr.FRAG_GAP:case vr.FRAG_PARSING_ERROR:case vr.FRAG_DECRYPT_ERROR:case vr.FRAG_LOAD_ERROR:case vr.FRAG_LOAD_TIMEOUT:case vr.KEY_LOAD_ERROR:case vr.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(mo.AUDIO,n);break;case vr.AUDIO_TRACK_LOAD_ERROR:case vr.AUDIO_TRACK_LOAD_TIMEOUT:case vr.LEVEL_PARSING_ERROR:!n.levelRetry&&this.state===la.WAITING_TRACK&&((r=n.context)==null?void 0:r.type)===Ad.AUDIO_TRACK&&(this.state=la.IDLE);break;case vr.BUFFER_ADD_CODEC_ERROR:case vr.BUFFER_APPEND_ERROR:if(n.parent!=="audio")return;this.reduceLengthAndFlushBuffer(n)||this.resetLoadingState();break;case vr.BUFFER_FULL_ERROR:if(n.parent!=="audio")return;this.reduceLengthAndFlushBuffer(n)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case vr.INTERNAL_EXCEPTION:this.recoverWorkerError(n);break}}onBufferFlushing(t,{type:n}){n!==Am.VIDEO&&(this.flushing=!0)}onBufferFlushed(t,{type:n}){if(n!==Am.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===la.ENDED&&(this.state=la.IDLE);const r=this.mediaBuffer||this.media;r&&(this.afterBufferFlushed(r,n,mo.AUDIO),this.tick())}}_handleTransmuxComplete(t){var n;const r="audio",{hls:a}=this,{remuxResult:i,chunkMeta:l}=t,o=this.getCurrentContext(l);if(!o){this.resetWhenMissingContext(l);return}const{frag:c,part:d,level:u}=o,{details:h}=u,{audio:m,text:p,id3:f,initSegment:y}=i;if(this.fragContextChanged(c)||!h){this.fragmentTracker.removeFragment(c);return}if(this.state=la.PARSING,this.switchingTrack&&m&&this.completeAudioSwitch(this.switchingTrack),y!=null&&y.tracks){const v=c.initSegment||c;if(this.unhandledEncryptionError(y,c))return;this._bufferInitSegment(u,y.tracks,v,l),a.trigger(Rt.FRAG_PARSING_INIT_SEGMENT,{frag:v,id:r,tracks:y.tracks})}if(m){const{startPTS:v,endPTS:g,startDTS:b,endDTS:j}=m;d&&(d.elementaryStreams[Am.AUDIO]={startPTS:v,endPTS:g,startDTS:b,endDTS:j}),c.setElementaryStreamInfo(Am.AUDIO,v,g,b,j),this.bufferFragmentData(m,c,d,l)}if(f!=null&&(n=f.samples)!=null&&n.length){const v=pm({id:r,frag:c,details:h},f);a.trigger(Rt.FRAG_PARSING_METADATA,v)}if(p){const v=pm({id:r,frag:c,details:h},p);a.trigger(Rt.FRAG_PARSING_USERDATA,v)}}_bufferInitSegment(t,n,r,a){if(this.state!==la.PARSING||(n.video&&delete n.video,n.audiovideo&&delete n.audiovideo,!n.audio))return;const i=n.audio;i.id=mo.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(Rt.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(Rt.BUFFER_APPENDING,c)}this.tickImmediate()}loadFragment(t,n,r){const a=this.fragmentTracker.getState(t);if(this.switchingTrack||a===f0.NOT_LOADED||a===f0.PARTIAL){var i;if(!ng(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=la.WAITING_INIT_PTS;const l=this.mainDetails;l&&l.fragmentStart!==n.details.fragmentStart&&I6e(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;F7({name:n,lang:r,assocLang:a,characteristics:i,audioCodec:l,channels:o},t,ZR)||(E6e(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(Rt.AUDIO_TRACK_SWITCHED,Fh({},t))}}class Ait extends GN{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&&ICt(r);return new DCt(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){Fdr(r,a,this);const b=a.playlistParsingError;if(b){this.warn(b);const j=this.hls;if(!j.config.ignorePlaylistParsingErrors){var d;const{networkDetails:S}=n;j.trigger(Rt.ERROR,{type:Lo.NETWORK_ERROR,details:vr.LEVEL_PARSING_ERROR,fatal:!1,url:a.url,error:b,reason:b.message,level:n.level||void 0,parent:(d=a.fragments[0])==null?void 0:d.type,networkDetails:S,stats:i});return}a.playlistParsingError=null}}a.requestScheduled===-1&&(a.requestScheduled=i.loading.start);const h=this.hls.mainForwardBufferInfo,m=h?h.end-h.len:0,p=(a.edge-m)*1e3,f=sis(a,p);if(a.requestScheduled+f0){if(I>a.targetduration*3)this.log(`Playlist last advanced ${M.toFixed(2)}s ago. Omitting segment and part directives.`),v=void 0,g=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 O=Math.floor(D/a.targetduration);if(v+=O,g!==void 0){const V=Math.round(D%a.targetduration/a.partTarget);g+=V}this.log(`CDN Tune-in age: ${a.ageHeader}s last advanced ${M.toFixed(2)}s goal: ${D} skip sn ${O} to part ${g}`)}a.tuneInGoal=D}if(y=this.getDeliveryDirectives(a,n.deliveryDirectives,v,g),b||!P){a.requestScheduled=l,this.loadingPlaylist(u,y);return}}else(a.canBlockReload||a.canSkipUntil)&&(y=this.getDeliveryDirectives(a,n.deliveryDirectives,v,g));y&&v!==void 0&&a.canBlockReload&&(a.requestScheduled=i.loading.first+Math.max(f-o*2,f/2)),this.scheduleLoading(u,y,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=ICt(t);return n!=null&&n.skip&&t.deltaUpdateFailed&&(r=n.msn,a=n.part,i=t3e.No),new DCt(r,a,i)}checkRetry(t){const n=t.details,r=T6e(t),a=t.errorAction,{action:i,retryCount:l=0,retryConfig:o}=a||{},c=!!a&&!!o&&(i===ov.RetryRequest||!a.resolved&&i===ov.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=fit(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 Ais(s,t){if(s.length!==t.length)return!1;for(let n=0;ns[a]!==t[a])}function uZe(s,t){return t.label.toLowerCase()===s.name.toLowerCase()&&(!t.language||t.language.toLowerCase()===(s.lang||"").toLowerCase())}class Gur extends Ait{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(Rt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Rt.MANIFEST_PARSED,this.onManifestParsed,this),t.on(Rt.LEVEL_LOADING,this.onLevelLoading,this),t.on(Rt.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(Rt.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(Rt.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(Rt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Rt.MANIFEST_PARSED,this.onManifestParsed,this),t.off(Rt.LEVEL_LOADING,this.onLevelLoading,this),t.off(Rt.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(Rt.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(Rt.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=F4(c,o,ZR);if(m>-1)i=o[m];else{const p=F4(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(Rt.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(Rt.ERROR,{type:Lo.MEDIA_ERROR,details:vr.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:m})}}}onError(t,n){n.fatal||!n.context||n.context.type===Ad.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&&F7(t,a,ZR))return a;const i=F4(t,this.tracksInGroup,ZR);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=rdr(t,n.levels,r,l,ZR);if(o===-1)return null;n.nextLoadLevel=o}if(t.channels||t.audioCodec){const l=F4(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(Rt.AUDIO_TRACK_SWITCHING,Fh({},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 b3t=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,Eis="HlsJsTrackRemovedError";class Kur extends Error{constructor(t){super(t),this.name=Eis}}class Yur extends GN{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(Rt.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=gcr(ZP(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(Rt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(Rt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(Rt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Rt.MANIFEST_PARSED,this.onManifestParsed,this),t.on(Rt.BUFFER_RESET,this.onBufferReset,this),t.on(Rt.BUFFER_APPENDING,this.onBufferAppending,this),t.on(Rt.BUFFER_CODECS,this.onBufferCodecs,this),t.on(Rt.BUFFER_EOS,this.onBufferEos,this),t.on(Rt.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(Rt.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(Rt.FRAG_PARSED,this.onFragParsed,this),t.on(Rt.FRAG_CHANGED,this.onFragChanged,this),t.on(Rt.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(Rt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(Rt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(Rt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Rt.MANIFEST_PARSED,this.onManifestParsed,this),t.off(Rt.BUFFER_RESET,this.onBufferReset,this),t.off(Rt.BUFFER_APPENDING,this.onBufferAppending,this),t.off(Rt.BUFFER_CODECS,this.onBufferCodecs,this),t.off(Rt.BUFFER_EOS,this.onBufferEos,this),t.off(Rt.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(Rt.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(Rt.FRAG_PARSED,this.onFragParsed,this),t.off(Rt.FRAG_CHANGED,this.onFragChanged,this),t.off(Rt.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?pm(r,a.tracks):this.sourceBuffers.forEach(i=>{const[l]=i;l&&(r[l]=pm({},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=ZP(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,_3t(r),Zur(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: ${Lm(r,(c,d)=>c==="initSegment"?void 0:d)}; transfer tracks: ${Lm(a,(c,d)=>c==="initSegment"?void 0:d)}}`),!kas(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(Rt.MEDIA_DETACHING,{}),this.onMediaAttaching(Rt.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 v=_c.getBuffered(h);m.detectEvictedFragments(d,v,p,null,!0)}const f=rUe(d),y=[d,h];this.sourceBuffers[f]=y,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&&_3t(a),a.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(Rt.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[rUe(t)]=[null,null];const n=this.tracks[t];n&&(n.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new Wur(this.tracks)}onBufferCodecs(t,n){var r;const a=this.tracks,i=Object.keys(n);this.log(`BUFFER_CODECS: "${i}" (current SB count ${this.sourceBufferCount})`);const l="audiovideo"in n&&(a.audio||a.video)||a.audiovideo&&("audio"in n||"video"in n),o=!l&&this.sourceBufferCount&&this.media&&i.some(c=>!a[c]);if(l||o){this.warn(`Unsupported transition between "${Object.keys(a)}" and "${i}" SourceBuffers`);return}i.forEach(c=>{var d,u;const h=n[c],{id:m,codec:p,levelCodec:f,container:y,metadata:v,supplemental:g}=h;let b=a[c];const j=(d=this.transferData)==null||(d=d.tracks)==null?void 0:d[c],S=j!=null&&j.buffer?j:b,C=(S==null?void 0:S.pendingCodec)||(S==null?void 0:S.codec),E=S==null?void 0:S.levelCodec;b||(b=a[c]={buffer:void 0,listeners:[],codec:p,supplemental:g,container:y,levelCodec:f,metadata:v,id:m});const P=e3e(C,E),M=P==null?void 0:P.replace(b3t,"$1");let I=e3e(p,f);const D=(u=I)==null?void 0:u.replace(b3t,"$1");I&&P&&M!==D&&(c.slice(0,5)==="audio"&&(I=C6e(I,this.appendSource)),this.log(`switching codec ${C} to ${I}`),I!==(b.pendingCodec||b.codec)&&(b.pendingCodec=I),b.container=y,this.appendChangeType(c,y,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,mo.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&&_c.isBuffered(c.buffer,a)||((o=this.fragmentTracker.getAppendedFrag(a,mo.MAIN))==null?void 0:o.gap)===!0)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:o=>{this.warn("Error executing block-audio operation",o)}};this.blockedAudioAppend={op:l,frag:t},this.append(l,"audio",!0)}unblockAudio(){const{blockedAudioAppend:t,operationQueue:n}=this;t&&n&&(this.blockedAudioAppend=null,n.unblockAudio(t.op))}onBufferAppending(t,n){const{tracks:r}=this,{data:a,type:i,parent:l,frag:o,part:c,chunkMeta:d,offset:u}=n,h=d.buffering[i],{sn:m,cc:p}=o,f=self.performance.now();h.start=f;const y=o.stats.buffering,v=c?c.stats.buffering:null;y.start===0&&(y.start=f),v&&v.start===0&&(v.start=f);const g=r.audio;let b=!1;i==="audio"&&(g==null?void 0:g.container)==="audio/mpeg"&&(b=!this.lastMpegAudioChunk||d.id===1||this.lastMpegAudioChunk.sn!==d.sn,this.lastMpegAudioChunk=d);const j=r.video,S=j==null?void 0:j.buffer;if(S&&m!=="initSegment"){const P=c||o,M=this.blockedAudioAppend;if(i==="audio"&&l!=="main"&&!this.blockedAudioAppend&&!(j.ending||j.ended)){const D=P.start+P.duration*.05,O=S.buffered,V=this.currentOp("video");!O.length&&!V?this.blockAudio(P):!V&&!_c.isBuffered(S,D)&&this.lastVideoAppendEndD||I{var P;h.executeStart=self.performance.now();const M=(P=this.tracks[i])==null?void 0:P.buffer;M&&(b?this.updateTimestampOffset(M,C,.1,i,m,p):u!==void 0&&Wi(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,y.first===0&&(y.first=P),v&&v.first===0&&(v.first=P);const M={};this.sourceBuffers.forEach(([I,D])=>{I&&(M[I]=_c.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(Rt.BUFFER_APPENDED,{type:i,frag:o,part:c,chunkMeta:d,parent:o.type,timeRanges:M})},onError:P=>{var M;const I={type:Lo.MEDIA_ERROR,parent:o.type,details:vr.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=vr.BUFFER_FULL_ERROR;else if(P.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!D)I.errorAction=X$(!0);else if(P.name===Eis&&this.sourceBufferCount===0)I.errorAction=X$(!0);else{const O=++this.appendErrors[i];this.warn(`Failed ${O}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${i}" sourceBuffer (${D||"no media error"})`),(O>=this.hls.config.appendErrorMaxRetry||D)&&(I.fatal=!0)}this.hls.trigger(Rt.ERROR,I)}};this.log(`queuing "${i}" append sn: ${m}${c?" p: "+c.index:""} of ${o.type===mo.MAIN?"level":"track"} ${o.level} cc: ${p}`),this.append(E,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(Rt.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[Am.AUDIOVIDEO]?i.push("audiovideo"):(l[Am.AUDIO]&&i.push("audio"),l[Am.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(Rt.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(Rt.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(Rt.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===vr.BUFFER_APPEND_ERROR&&n.frag){var r;const a=(r=n.errorAction)==null?void 0:r.nextAutoLevel;Wi(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(Wi(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(Wi(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=_c.getBuffered(i);if(o.length>0&&r>o.start(0)){var l;this.hls.trigger(Rt.BACK_BUFFER_REACHED,{bufferEnd:r});const c=this.tracks[a];if((l=this.details)!=null&&l.live)this.hls.trigger(Rt.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(Rt.BUFFER_FLUSHING,{startOffset:0,endOffset:r,type:a})}}})}flushFrontBuffer(t,n,r){this.sourceBuffers.forEach(([a,i])=>{if(i){const l=_c.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(Rt.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 Wi(i)?{duration:i}:null;const l=this.media.duration,o=Wi(r.duration)?r.duration:0;return a>o&&a>l||!Wi(l)?{duration:a}:null}updateMediaSource({duration:t,start:n,end:r}){const a=this.mediaSource;!this.media||!a||a.readyState!=="open"||(a.duration!==t&&(Wi(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}) ${Lm(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(Rt.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(Rt.ERROR,{type:Lo.MEDIA_ERROR,details:vr.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":""} ${Lm(o)}`);try{const u=r.addSourceBuffer(d),h=rUe(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(Rt.ERROR,{type:Lo.MEDIA_ERROR,details:vr.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")&&Use(r,"video")&&(a=zcr(a,r));const i=e3e(a,t.levelCodec);return i?n.slice(0,5)==="audio"?C6e(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(Rt.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(Rt.ERROR,{type:Lo.MEDIA_ERROR,details:vr.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=Wi(a.duration)?a.duration:1/0,d=Wi(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 Kur(`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 _3t(s){const t=s.querySelectorAll("source");[].slice.call(t).forEach(n=>{s.removeChild(n)})}function Zur(s,t){const n=self.document.createElement("source");n.type="video/mp4",n.src=t,s.appendChild(n)}function rUe(s){return s==="audio"?1:0}class Eit{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(Rt.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(Rt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(Rt.MANIFEST_PARSED,this.onManifestParsed,this),t.on(Rt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(Rt.BUFFER_CODECS,this.onBufferCodecs,this),t.on(Rt.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:t}=this;t.off(Rt.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(Rt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(Rt.MANIFEST_PARSED,this.onManifestParsed,this),t.off(Rt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(Rt.BUFFER_CODECS,this.onBufferCodecs,this),t.off(Rt.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&&Wi(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,Eit.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 Xur={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},r_=Xur,Qur={HLS:"h"},Jur=Qur;class yC{constructor(t,n){Array.isArray(t)&&(t=t.map(r=>r instanceof yC?r:new yC(r))),this.value=t,this.params=n}}const ehr="Dict";function thr(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 shr(s,t,n,r){return new Error(`failed to ${s} "${thr(t)}" as ${n}`,{cause:r})}function vC(s,t,n){return shr("serialize",s,t,n)}class Tis{constructor(t){this.description=t}}const w3t="Bare Item",nhr="Boolean";function rhr(s){if(typeof s!="boolean")throw vC(s,nhr);return s?"?1":"?0"}function ahr(s){return btoa(String.fromCharCode(...s))}const ihr="Byte Sequence";function ohr(s){if(ArrayBuffer.isView(s)===!1)throw vC(s,ihr);return`:${ahr(s)}:`}const lhr="Integer";function chr(s){return s<-999999999999999||99999999999999912)throw vC(s,uhr);const n=t.toString();return n.includes(".")?n:`${n}.0`}const mhr="String",phr=/[\x00-\x1f\x7f]+/;function fhr(s){if(phr.test(s))throw vC(s,mhr);return`"${s.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function xhr(s){return s.description||s.toString().slice(7,-1)}const ghr="Token";function j3t(s){const t=xhr(s);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(t)===!1)throw vC(t,ghr);return t}function hZe(s){switch(typeof s){case"number":if(!Wi(s))throw vC(s,w3t);return Number.isInteger(s)?Mis(s):hhr(s);case"string":return fhr(s);case"symbol":return j3t(s);case"boolean":return rhr(s);case"object":if(s instanceof Date)return dhr(s);if(s instanceof Uint8Array)return ohr(s);if(s instanceof Tis)return j3t(s);default:throw vC(s,w3t)}}const yhr="Key";function mZe(s){if(/^[a-z*][a-z0-9\-_.*]*$/.test(s)===!1)throw vC(s,yhr);return s}function Tit(s){return s==null?"":Object.entries(s).map(([t,n])=>n===!0?`;${mZe(t)}`:`;${mZe(t)}=${hZe(n)}`).join("")}function Lis(s){return s instanceof yC?`${hZe(s.value)}${Tit(s.params)}`:hZe(s)}function vhr(s){return`(${s.value.map(Lis).join(" ")})${Tit(s.params)}`}function bhr(s,t={whitespace:!0}){if(typeof s!="object"||s==null)throw vC(s,ehr);const n=s instanceof Map?s.entries():Object.entries(s),r=t!=null&&t.whitespace?" ":"";return Array.from(n).map(([a,i])=>{i instanceof yC||(i=new yC(i));let l=mZe(a);return i.value===!0?l+=Tit(i.params):(l+="=",Array.isArray(i.value)?l+=vhr(i):l+=Lis(i)),l}).join(`,${r}`)}function Iis(s,t){return bhr(s,t)}const T5="CMCD-Object",ux="CMCD-Request",EI="CMCD-Session",DT="CMCD-Status",_hr={br:T5,ab:T5,d:T5,ot:T5,tb:T5,tpb:T5,lb:T5,tab:T5,lab:T5,url:T5,pb:ux,bl:ux,tbl:ux,dl:ux,ltc:ux,mtp:ux,nor:ux,nrr:ux,rc:ux,sn:ux,sta:ux,su:ux,ttfb:ux,ttfbb:ux,ttlb:ux,cmsdd:ux,cmsds:ux,smrt:ux,df:ux,cs:ux,ts:ux,cid:EI,pr:EI,sf:EI,sid:EI,st:EI,v:EI,msd:EI,bs:DT,bsd:DT,cdn:DT,rtp:DT,bg:DT,pt:DT,ec:DT,e:DT},whr={REQUEST:ux};function jhr(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 Nhr(s,t){const n={};if(!s)return n;const r=Object.keys(s),a=t?jhr(t):{};return r.reduce((i,l)=>{var o;const c=_hr[l]||a[l]||whr.REQUEST,d=(o=i[c])!==null&&o!==void 0?o:i[c]={};return d[l]=s[l],i},n)}function khr(s){return["ot","sf","st","e","sta"].includes(s)}function Shr(s){return typeof s=="number"?Wi(s):s!=null&&s!==""&&s!==!1}const Dis="event";function Chr(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 a3e=s=>Math.round(s),pZe=(s,t)=>Array.isArray(s)?s.map(n=>pZe(n,t)):s instanceof yC&&typeof s.value=="string"?new yC(pZe(s.value,t),s.params):(t.baseUrl&&(s=Chr(s,t.baseUrl)),t.version===1?encodeURIComponent(s):s),rue=s=>a3e(s/100)*100,Ahr=(s,t)=>{let n=s;return t.version>=2&&(s instanceof yC&&typeof s.value=="string"?n=new yC([s]):typeof s=="string"&&(n=[s])),pZe(n,t)},Ehr={br:a3e,d:a3e,bl:rue,dl:rue,mtp:rue,nor:Ahr,rtp:rue,tb:a3e},Ris="request",Fis="response",Mit=["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"],Thr=["e"],Mhr=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function lDe(s){return Mhr.test(s)}function Phr(s){return Mit.includes(s)||Thr.includes(s)||lDe(s)}const Ois=["d","dl","nor","ot","rtp","su"];function Lhr(s){return Mit.includes(s)||Ois.includes(s)||lDe(s)}const Ihr=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function Dhr(s){return Mit.includes(s)||Ois.includes(s)||Ihr.includes(s)||lDe(s)}const Rhr=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function Fhr(s){return Rhr.includes(s)||lDe(s)}const Ohr={[Fis]:Dhr,[Dis]:Phr,[Ris]:Lhr};function zis(s,t={}){const n={};if(s==null||typeof s!="object")return n;const r=t.version||s.v||1,a=t.reportingMode||Ris,i=r===1?Fhr:Ohr[a];let l=Object.keys(s).filter(i);const o=t.filter;typeof o=="function"&&(l=l.filter(o));const c=a===Fis||a===Dis;c&&!l.includes("ts")&&l.push("ts"),r>1&&!l.includes("v")&&l.push("v");const d=pm({},Ehr,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"&&!Wi(m)&&(m=Date.now()),Shr(m)&&(khr(h)&&typeof m=="string"&&(m=new Tis(m)),n[h]=m))}),n}function zhr(s,t={}){const n={};if(!s)return n;const r=zis(s,t),a=Nhr(r,t==null?void 0:t.customHeaderMap);return Object.entries(a).reduce((i,[l,o])=>{const c=Iis(o,{whitespace:!1});return c&&(i[l]=c),i},n)}function Bhr(s,t,n){return pm(s,zhr(t,n))}const Uhr="CMCD";function qhr(s,t={}){return s?Iis(zis(s,t),{whitespace:!1}):""}function $hr(s,t={}){if(!s)return"";const n=qhr(s,t);return encodeURIComponent(n)}function Vhr(s,t={}){if(!s)return"";const n=$hr(s,t);return`${Uhr}=${n}`}const N3t=/CMCD=[^&#]+/;function Hhr(s,t,n){const r=Vhr(t,n);if(!r)return s;if(N3t.test(s))return s.replace(N3t,r);const a=s.includes("?")?"&":"?";return`${s}${a}${r}`}class Ghr{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:r_.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===r_.VIDEO||c===r_.AUDIO||c==r_.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(Rt.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(Rt.MEDIA_DETACHED,this.onMediaDetached,this),t.on(Rt.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const t=this.hls;t.off(Rt.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(Rt.MEDIA_DETACHED,this.onMediaDetached,this),t.off(Rt.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:Jur.HLS,sid:this.sid,cid:this.cid,pr:(t=this.media)==null?void 0:t.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(t,n={}){pm(n,this.createData());const r=n.ot===r_.INIT||n.ot===r_.VIDEO||n.ot===r_.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={}),Bhr(t.headers,n,i)):t.url=Hhr(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 r_.TIMED_TEXT;if(t.sn==="initSegment")return r_.INIT;if(n==="audio")return r_.AUDIO;if(n==="main")return this.hls.audioTracks.length?r_.VIDEO:r_.MUXED}getTopBandwidth(t){let n=0,r;const a=this.hls;if(t===r_.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===r_.AUDIO?this.audioBuffer:this.videoBuffer;return!r||!n?NaN:_c.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 Whr=3e5;class Khr extends GN{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(Rt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Rt.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(Rt.MANIFEST_PARSED,this.onManifestParsed,this),t.on(Rt.ERROR,this.onError,this)}unregisterListeners(){const t=this.hls;t&&(t.off(Rt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Rt.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(Rt.MANIFEST_PARSED,this.onManifestParsed,this),t.off(Rt.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)===ov.SendAlternateToPenaltyBox&&r.flags===Pw.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===vr.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: ${Lm(i)} penalized: ${Lm(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]>Whr&&delete r[i]});for(let i=0;i0){this.log(`Setting Pathway to "${l}"`),this.pathwayId=l,ais(n),this.hls.trigger(Rt.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 kf(u.attrs);h["PATHWAY-ID"]=l;const m=h.AUDIO&&`${h.AUDIO}_clone_${l}`,p=h.SUBTITLES&&`${h.SUBTITLES}_clone_${l}`;m&&(r[h.AUDIO]=m,h.AUDIO=m),p&&(a[h.SUBTITLES]=p,h.SUBTITLES=p);const f=Bis(u.uri,h["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",c),y=new $se({attrs:h,audioCodec:u.audioCodec,bitrate:u.bitrate,height:u.height,name:u.name,url:f,videoCodec:u.videoCodec,width:u.width});if(u.audioGroups)for(let v=1;v{this.log(`Loaded steering manifest: "${a}"`);const f=u.data;if((f==null?void 0:f.VERSION)!==1){this.log(`Steering VERSION ${f.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=f.TTL;const{"RELOAD-URI":y,"PATHWAY-CLONES":v,"PATHWAY-PRIORITY":g}=f;if(y)try{this.uri=new self.URL(y,a).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${y}`);return}this.scheduleRefresh(this.uri||m.url),v&&this.clonePathways(v);const b={steeringManifest:f,url:a.toString()};this.hls.trigger(Rt.STEERING_MANIFEST_LOADED,b),g&&this.updatePathwayPriority(g)},onError:(u,h,m,p)=>{if(this.log(`Error loading steering manifest: ${u.code} ${u.text} (${h.url})`),this.stopLoad(),u.code===410){this.enabled=!1,this.log(`Steering manifest ${h.url} no longer available`);return}let f=this.timeToLoad*1e3;if(u.code===429){const y=this.loader;if(typeof(y==null?void 0:y.getResponseHeader)=="function"){const v=y.getResponseHeader("Retry-After");v&&(f=parseFloat(v)*1e3)}this.log(`Steering manifest ${h.url} rate limited`);return}this.scheduleRefresh(this.uri||h.url,f)},onTimeout:(u,h,m)=>{this.log(`Timeout loading steering manifest (${h.url})`),this.scheduleRefresh(this.uri||h.url)}};this.log(`Requesting steering manifest: ${a}`),this.loader.load(i,c,d)}scheduleRefresh(t,n=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var r;const a=(r=this.hls)==null?void 0:r.media;if(a&&!a.ended){this.loadSteeringManifest(t);return}this.scheduleRefresh(t,this.timeToLoad*1e3)},n)}}function k3t(s,t,n,r){s&&Object.keys(t).forEach(a=>{const i=s.filter(l=>l.groupId===a).map(l=>{const o=pm({},l);return o.details=void 0,o.attrs=new kf(o.attrs),o.url=o.attrs.URI=Bis(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 Bis(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 J$ extends GN{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=J$.CDMCleanupPromise?[J$.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=sQ(this.config));const o=l.map(ZBe).filter(c=>!!c);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(l=>{const o=s3e(l);if(r!=="sinf"||o!==Pf.FAIRPLAY){this.log(`Ignoring "${n.type}" event with init data type: "${r}" for selected key-system ${o}`);return}let c;try{const p=u0(new Uint8Array(a)),f=vit(JSON.parse(p).sinf),y=Ias(f);if(!y)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");c=new Uint8Array(y.subarray(8,24))}catch(p){this.warn(`${i} Failed to parse sinf: ${p}`);return}const d=lv(c),{keyIdToKeySessionPromise:u,mediaKeySessions:h}=this;let m=u[d];for(let p=0;pthis.generateRequestWithPreferredKeySession(f,r,a,"encrypted-event-key-match")),m.catch(g=>this.handleError(g));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(Rt.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(Rt.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(Rt.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(Rt.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(Rt.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(Rt.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(Rt.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(Rt.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(Rt.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(Rt.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===Pf.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 Cw?o(h):o(new Cw({type:Lo.KEY_SYSTEM_ERROR,details:vr.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 Xas===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=Adr(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: ${Lm(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: ${lv(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=aue(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 ${lv(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})=>ZBe(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=ZBe(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=sQ(this.config),r=t.map(s3e).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 Cw){const c=Fh({},o.data);this.getKeyStatus(n)==="internal-error"&&(c.decryptdata=n);const d=new Cw(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 Cw){n&&(t.data.frag=n);const r=t.data.decryptdata;this.error(`${t.message}${r?` (${lv(r.keyId||[])})`:""}`),this.hls.trigger(Rt.ERROR,t.data)}else this.error(t.message),this.hls.trigger(Rt.ERROR,{type:Lo.KEY_SYSTEM_ERROR,details:vr.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0})}getKeySystemForKeyPromise(t){const n=aue(t),r=this.keyIdToKeySessionPromise[n];if(!r){const a=s3e(t.keyFormat),i=a?[a]:sQ(this.config);return this.attemptKeySystemAccess(i)}return r}getKeySystemSelectionPromise(t){if(t.length||(t=sQ(this.config)),t.length===0)throw new Cw({type:Lo.KEY_SYSTEM_ERROR,details:vr.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${Lm({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(t)}attemptSetMediaKeys(t,n){if(this.mediaResolved=void 0,this.mediaKeys===n)return Promise.resolve();const r=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${t}"`);const a=Promise.all(r).then(()=>this.media?this.media.setMediaKeys(n):new Promise((i,l)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return l(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=n,this.media.setMediaKeys(n).then(i).catch(l)}}));return this.mediaKeys=n,this.setMediaKeysQueue.push(a),a.then(()=>{this.log(`Media-keys set for "${t}"`),r.push(a),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(i=>r.indexOf(i)===-1)})}generateRequestWithPreferredKeySession(t,n,r,a){var i;const l=(i=this.config.drmSystems)==null||(i=i[t.keySystem])==null?void 0:i.generateRequest;if(l)try{const f=l.call(this.hls,n,r,t);if(!f)throw new Error("Invalid response from configured generateRequest filter");n=f.initDataType,r=f.initData?f.initData:null,t.decryptdata.pssh=r?new Uint8Array(r):null}catch(f){if(this.warn(f.message),this.hls&&this.hls.config.debug)throw f}if(r===null)return this.log(`Skipping key-session request for "${a}" (no initData)`),Promise.resolve(t);const o=aue(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 _it,u=t._onmessage=f=>{const y=t.mediaKeysSession;if(!y){d.emit("error",new Error("invalid state"));return}const{messageType:v,message:g}=f;this.log(`"${v}" message event for session "${y.sessionId}" message size: ${g.byteLength}`),v==="license-request"||v==="license-renewal"?this.renewLicense(t,g).catch(b=>{d.eventNames().length?d.emit("error",b):this.handleError(b)}):v==="license-release"?t.keySystem===Pf.FAIRPLAY&&this.updateKeySession(t,iZe("acknowledged")).then(()=>this.removeSession(t)).catch(b=>this.handleError(b)):this.warn(`unhandled media key message type "${v}"`)},h=(f,y)=>{y.keyStatus=f;let v;f.startsWith("usable")?d.emit("resolved"):f==="internal-error"||f==="output-restricted"||f==="output-downscaled"?v=S3t(f,y.decryptdata):f==="expired"?v=new Error(`key expired (keyId: ${o})`):f==="released"?v=new Error("key released"):f==="status-pending"||this.warn(`unhandled key status change "${f}" (keyId: ${o})`),v&&(d.eventNames().length?d.emit("error",v):this.handleError(v))},m=t._onkeystatuseschange=f=>{if(!t.mediaKeysSession){d.emit("error",new Error("invalid state"));return}const v=this.getKeyStatuses(t);if(!Object.keys(v).some(S=>v[S]!=="status-pending"))return;if(v[o]==="expired"){this.log(`Expired key ${Lm(v)} in key-session "${t.mediaKeysSession.sessionId}"`),this.renewKeySession(t);return}let b=v[o];if(b)h(b,t);else{var j;t.keyStatusTimeouts||(t.keyStatusTimeouts={}),(j=t.keyStatusTimeouts)[o]||(j[o]=self.setTimeout(()=>{if(!t.mediaKeysSession||!this.mediaKeys)return;const C=this.getKeyStatus(t.decryptdata);if(C&&C!=="status-pending")return this.log(`No status for keyId ${o} in key-session "${t.mediaKeysSession.sessionId}". Using session key-status ${C} from other session.`),h(C,t);this.log(`key status for ${o} in key-session "${t.mediaKeysSession.sessionId}" timed out after 1000ms`),b="internal-error",h(b,t)},1e3)),this.log(`No status for keyId ${o} (${Lm(v)}).`)}};vb(t.mediaKeysSession,"message",u),vb(t.mediaKeysSession,"keystatuseschange",m);const p=new Promise((f,y)=>{d.on("error",y),d.on("resolved",f)});return t.mediaKeysSession.generateRequest(n,r).then(()=>{this.log(`Request generated for key-session "${t.mediaKeysSession.sessionId}" keyId: ${o} URI: ${c}`)}).catch(f=>{throw new Cw({type:Lo.KEY_SYSTEM_ERROR,details:vr.KEY_SYSTEM_NO_SESSION,error:f,decryptdata:t.decryptdata,fatal:!1},`Error generating key-session request: ${f}`)}).then(()=>p).catch(f=>(d.removeAllListeners(),this.removeSession(t).then(()=>{throw f}))).then(()=>(d.removeAllListeners(),t))}getKeyStatuses(t){const n={};return t.mediaKeysSession.keyStatuses.forEach((r,a)=>{if(typeof a=="string"&&typeof r=="object"){const o=a;a=r,r=o}const i="buffer"in a?new Uint8Array(a.buffer,a.byteOffset,a.byteLength):new Uint8Array(a);if(t.keySystem===Pf.PLAYREADY&&i.length===16){const o=lv(i);n[o]=r,Yas(i)}const l=lv(i);r==="internal-error"&&(this.bannedKeyIds[l]=r),this.log(`key status change "${r}" for keyStatuses keyId: ${l} key-session "${t.mediaKeysSession.sessionId}"`),n[l]=r}),n}fetchServerCertificate(t){const n=this.config,r=n.loader,a=new r(n),i=this.getServerCertificateUrl(t);return i?(this.log(`Fetching server certificate for "${t}"`),new Promise((l,o)=>{const c={responseType:"arraybuffer",url:i},d=n.certLoadPolicy.default,u={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(m,p,f,y)=>{l(m.data)},onError:(m,p,f,y)=>{o(new Cw({type:Lo.KEY_SYSTEM_ERROR,details:vr.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:f,response:Fh({url:c.url,data:void 0},m)},`"${t}" certificate request failed (${i}). Status: ${m.code} (${m.text})`))},onTimeout:(m,p,f)=>{o(new Cw({type:Lo.KEY_SYSTEM_ERROR,details:vr.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:f,response:{url:c.url,data:void 0}},`"${t}" certificate request timed out (${i})`))},onAbort:(m,p,f)=>{o(new Error("aborted"))}};a.load(c,u,h)})):Promise.resolve()}setMediaKeysServerCertificate(t,n,r){return new Promise((a,i)=>{t.setServerCertificate(r).then(l=>{this.log(`setServerCertificate ${l?"success":"not supported by CDM"} (${r.byteLength}) on "${n}"`),a(t)}).catch(l=>{i(new Cw({type:Lo.KEY_SYSTEM_ERROR,details:vr.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 Cw({type:Lo.KEY_SYSTEM_ERROR,details:vr.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 iZe(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 Cw({type:Lo.KEY_SYSTEM_ERROR,details:vr.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==Pf.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,vb(r,"encrypted",this.onMediaEncrypted),vb(r,"waitingforkey",this.onWaitingForKey);const a=this.mediaResolved;a?a():this.mediaKeys=r.mediaKeys}onMediaDetached(){const t=this.media;t&&(E_(t,"encrypted",this.onMediaEncrypted),E_(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,NP.clearKeyUriToKeyIdMap();const i=a.length;J$.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(Rt.ERROR,{type:Lo.OTHER_ERROR,details:vr.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(Rt.ERROR,{type:Lo.OTHER_ERROR,details:vr.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: ${lv((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(Tdr(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(Rt.ERROR,{type:Lo.OTHER_ERROR,details:vr.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(Rt.ERROR,{type:Lo.OTHER_ERROR,details:vr.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${d}`)})})}return Promise.resolve()}}J$.CDMCleanupPromise=void 0;function aue(s){if(!s)throw new Error("Could not read keyId of undefined decryptdata");if(s.keyId===null)throw new Error("keyId is null");return lv(s.keyId)}function Yhr(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 Cw 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 S3t(s,t){const n=s==="output-restricted",r=n?vr.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:vr.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Cw({type:Lo.KEY_SYSTEM_ERROR,details:r,fatal:!1,decryptdata:t},n?"HDCP level output restricted":`key status changed to "${s}"`)}class Zhr{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(Rt.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(Rt.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(Rt.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(Rt.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(Rt.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(Rt.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 Uis(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 qis(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){Vh.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){Vh.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${a}`)}}n==="disabled"&&(s.mode=n)}function gq(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 fZe(s,t,n,r){const a=s.mode;if(a==="disabled"&&(s.mode="hidden"),s.cues&&s.cues.length>0){const i=Qhr(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 i3e(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=i3e(this.media.textTracks);for(let i=0;i-1&&this.toggleTrackModes()}registerListeners(){const{hls:t}=this;t.on(Rt.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(Rt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(Rt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Rt.MANIFEST_PARSED,this.onManifestParsed,this),t.on(Rt.LEVEL_LOADING,this.onLevelLoading,this),t.on(Rt.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(Rt.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(Rt.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(Rt.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(Rt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(Rt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Rt.MANIFEST_PARSED,this.onManifestParsed,this),t.off(Rt.LEVEL_LOADING,this.onLevelLoading,this),t.off(Rt.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(Rt.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(Rt.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;i3e(r.textTracks).forEach(l=>{gq(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=F4(o,l);if(u>-1)i=l[u];else{const h=F4(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(Rt.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=F4(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(Rt.SUBTITLE_TRACK_LOADING,{url:i,id:r,groupId:a,deliveryDirectives:n||null,track:t})}toggleTrackModes(){const{media:t}=this;if(!t)return;const n=i3e(t.textTracks),r=this.currentTrack;let a;if(r&&(a=n.filter(i=>uZe(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||!Wi(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(Rt.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(Rt.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 emr(){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 Nee(s){let t=5381,n=s.length;for(;n;)t=t*33^s.charCodeAt(--n);return(t>>>0).toString()}const eV=.025;let R6e=function(s){return s[s.Point=0]="Point",s[s.Range=1]="Range",s}({});function tmr(s,t,n){return`${s.identifier}-${n+1}-${Nee(t)}`}class smr{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 aUe(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=aUe(n,t);return n-r<.1}return!1}get resumptionOffset(){const t=this.resumeOffset,n=Wi(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 aUe(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 nmr(this)}}function aUe(s,t){return s-t.start":s.cue.post?"":""}${s.timelineStart.toFixed(2)}-${s.resumeTime.toFixed(2)}]`}function LU(s){const t=s.timelineStart,n=s.duration||0;return`["${s.identifier}" ${t.toFixed(2)}-${(t+n).toFixed(2)}]`}class rmr{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(Rt.PLAYOUT_LIMIT_REACHED,{})};const i=this.hls=new t(n);this.interstitial=r,this.assetItem=a;const l=()=>{this.hasDetails=!0};i.once(Rt.LEVEL_LOADED,l),i.once(Rt.AUDIO_TRACK_LOADED,l),i.once(Rt.SUBTITLE_TRACK_LOADED,l),i.on(Rt.MEDIA_ATTACHING,(o,{media:c})=>{this.removeMediaListeners(),this.mediaAttached=c,this.interstitial.playoutLimit&&(c.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&i.on(Rt.BUFFER_APPENDED,()=>{const u=this.bufferedEnd;this.reachedPlayout(u)&&(this._bufferedEosTime=u,i.trigger(Rt.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=$is(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=_c.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=_c.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: ${LU(this.assetItem)} ${(t=this.hls)==null?void 0:t.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const C3t=.033;class amr extends GN{constructor(t,n){super("interstitials-sched",n),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=t}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(t=>t.reset()),this.events=this.items=null}resetErrorsInRange(t,n){return this.events?this.events.reduce((r,a)=>t<=a.startOffset&&n>a.startOffset?(delete a.error,r+1):r,0):0}get duration(){const t=this.items;return t?t[t.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(t){return t&&this.eventMap[t]||null}hasEvent(t){return t in this.eventMap}findItemIndex(t,n){if(t.event)return this.findEventIndex(t.event.identifier);let r=-1;t.nextEvent?r=this.findEventIndex(t.nextEvent.identifier)-1:t.previousEvent&&(r=this.findEventIndex(t.previousEvent.identifier)+1);const a=this.items;if(a)for(a[r]||(n===void 0&&(n=t.start),r=this.findItemIndexAtTime(n));r>=0&&(i=a[r])!=null&&i.event;){var i;r--}return r}findItemIndexAtTime(t,n){const r=this.items;if(r)for(let a=0;ai.start&&t1)for(let i=0;io&&(n!o.includes(d.identifier)):[];l.length&&l.sort((d,u)=>{const h=d.cue.pre,m=d.cue.post,p=u.cue.pre,f=u.cue.post;if(h&&!p)return-1;if(p&&!h||m&&!f)return 1;if(f&&!m)return-1;if(!h&&!p&&!m&&!f){const y=d.startTime,v=u.startTime;if(y!==v)return y-v}return d.dateRange.tagOrder-u.dateRange.tagOrder}),this.events=l,c.forEach(d=>{this.removeEvent(d)}),this.updateSchedule(t,c)}updateSchedule(t,n=[],r=!1){const a=this.events||[];if(a.length||n.length||this.length<2){const i=this.items,l=this.parseSchedule(a,t);(r||n.length||(i==null?void 0:i.length)!==l.length||l.some((c,d)=>Math.abs(c.playout.start-i[d].playout.start)>.005||Math.abs(c.playout.end-i[d].playout.end)>.005))&&(this.items=l,this.onScheduleUpdate(n,i))}}parseDateRanges(t,n,r){const a=[],i=Object.keys(t);for(let l=0;l!c.error&&!(c.cue.once&&c.hasPlayed)),t.length){this.resolveOffsets(t,n);let c=0,d=0;if(t.forEach((u,h)=>{const m=u.cue.pre,p=u.cue.post,f=t[h-1]||null,y=u.appendInPlace,v=p?i:u.startOffset,g=u.duration,b=u.timelineOccupancy===R6e.Range?g:0,j=u.resumptionOffset,S=(f==null?void 0:f.startTime)===v,C=v+u.cumulativeDuration;let E=y?C+g:v+j;if(m||!p&&v<=0){const M=d;d+=b,u.timelineStart=C;const I=l;l+=g,r.push({event:u,start:C,end:E,playout:{start:I,end:l},integrated:{start:M,end:d}})}else if(v<=i){if(!S){const D=v-c;if(D>C3t){const O=c,V=d;d+=D;const G=l;l+=D;const $={previousEvent:t[h-1]||null,nextEvent:u,start:O,end:O+D,playout:{start:G,end:l},integrated:{start:V,end:d}};r.push($)}else D>0&&f&&(f.cumulativeDuration+=D,r[r.length-1].end=v)}p&&(E=C),u.timelineStart=C;const M=d;d+=b;const I=l;l+=g,r.push({event:u,start:C,end:E,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=P9(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+1eV?(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=P9(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 v=m.data,g=v==null?void 0:v.ASSETS;if(!Array.isArray(g)){const b=this.assignAssetListError(t,vr.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),f.url,p,y);this.hls.trigger(Rt.ERROR,b);return}t.assetListResponse=v,this.hls.trigger(Rt.ASSET_LIST_LOADED,{event:t,assetListResponse:v,networkDetails:y})},onError:(m,p,f,y)=>{const v=this.assignAssetListError(t,vr.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${m.code} ${m.text} (${p.url})`),p.url,y,f);this.hls.trigger(Rt.ERROR,v)},onTimeout:(m,p,f)=>{const y=this.assignAssetListError(t,vr.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${p.url})`),p.url,m,f);this.hls.trigger(Rt.ERROR,y)}};return o.load(c,u,h),this.hls.trigger(Rt.ASSET_LIST_LOADING,{event:t}),o}assignAssetListError(t,n,r,a,i,l){return t.error=r,{type:Lo.NETWORK_ERROR,details:n,fatal:!1,interstitial:t,url:a,error:r,networkDetails:l,stats:i}}}function A3t(s){var t;s==null||(t=s.play())==null||t.catch(()=>{})}function cU(s,t){return`[${s}] Advancing timeline position to ${t}`}class omr extends GN{constructor(t,n){super("interstitials",t.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const r=this.currentTime;if(r===void 0||this.playbackDisabled||!this.schedule)return;const a=r-this.timelinePos;if(Math.abs(a)<1/7056e5)return;const l=a<=-.01;this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),this.timelinePos=r,this.bufferedPos=r;const o=this.playingItem;if(!o){this.checkBuffer();return}if(l&&this.schedule.resetErrorsInRange(r,r-a)&&this.updateSchedule(!0),this.checkBuffer(),l&&r=o.end){var c;const p=this.findItemIndex(o);let f=this.schedule.findItemIndexAtTime(r);if(f===-1&&(f=p+(l?-1:1),this.log(`seeked ${l?"back ":""}to position not covered by schedule ${r} (resolving from ${p} to ${f})`)),!this.isInterstitial(o)&&(c=this.media)!=null&&c.paused&&(this.shouldPlay=!1),!l&&f>p){const y=this.schedule.findJumpRestrictedIndex(p+1,f);if(y>p){this.setSchedulePosition(y);return}}this.setSchedulePosition(f);return}const d=this.playingAsset;if(!d){if(this.playingLastItem&&this.isInterstitial(o)){const p=o.event.assetList[0];p&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(r,p))}return}const u=d.timelineStart,h=d.duration||0;if(l&&r=u+h){var m;(m=o.event)!=null&&m.appendInPlace&&(this.clearAssetPlayers(o.event,o),this.flushFrontBuffer(r)),this.setScheduleToAssetAtTime(r,d)}},this.onTimeupdate=()=>{const r=this.currentTime;if(r===void 0||this.playbackDisabled)return;if(this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),r>this.timelinePos)this.timelinePos=r,r>this.bufferedPos&&this.checkBuffer();else return;const a=this.playingItem;if(!a||this.playingLastItem)return;if(r>=a.end){this.timelinePos=a.end;const o=this.findItemIndex(a);this.setSchedulePosition(o+1)}const i=this.playingAsset;if(!i)return;const l=i.timelineStart+(i.duration||0);r>=l&&this.setScheduleToAssetAtTime(r,i)},this.onScheduleUpdate=(r,a)=>{const i=this.schedule;if(!i)return;const l=this.playingItem,o=i.events||[],c=i.items||[],d=i.durations,u=r.map(y=>y.identifier),h=!!(o.length||u.length);(h||a)&&this.log(`INTERSTITIALS_UPDATED (${o.length}): ${o} Schedule: ${c.map(y=>bk(y))} pos: ${this.timelinePos}`),u.length&&this.log(`Removed events ${u}`);let m=null,p=null;l&&(m=this.updateItem(l,this.timelinePos),this.itemsMatch(l,m)?this.playingItem=m:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const f=this.bufferingItem;if(f&&(p=this.updateItem(f,this.bufferedPos),this.itemsMatch(f,p)?this.bufferingItem=p:f.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(f.event,null))),r.forEach(y=>{y.assetList.forEach(v=>{this.clearAssetPlayer(v.identifier,null)})}),this.playerQueue.forEach(y=>{if(y.interstitial.appendInPlace){const v=y.assetItem.timelineStart,g=y.timelineOffset-v;if(g)try{y.timelineOffset=v}catch(b){Math.abs(g)>eV&&this.warn(`${b} ("${y.assetId}" ${y.timelineOffset}->${v})`)}}}),h||a){if(this.hls.trigger(Rt.INTERSTITIALS_UPDATED,{events:o.slice(0),schedule:c.slice(0),durations:d,removedIds:u}),this.isInterstitial(l)&&u.includes(l.event.identifier)){this.warn(`Interstitial "${l.event.identifier}" removed while playing`),this.primaryFallback(l.event);return}l&&this.trimInPlace(m,l),f&&p!==m&&this.trimInPlace(p,f),this.checkBuffer()}},this.hls=t,this.HlsPlayerClass=n,this.assetListLoader=new imr(t),this.schedule=new amr(this.onScheduleUpdate,t.logger),this.registerListeners()}registerListeners(){const t=this.hls;t&&(t.on(Rt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(Rt.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(Rt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(Rt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Rt.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(Rt.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(Rt.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.on(Rt.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(Rt.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.on(Rt.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.on(Rt.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.on(Rt.BUFFER_APPENDED,this.onBufferAppended,this),t.on(Rt.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(Rt.BUFFERED_TO_END,this.onBufferedToEnd,this),t.on(Rt.MEDIA_ENDED,this.onMediaEnded,this),t.on(Rt.ERROR,this.onError,this),t.on(Rt.DESTROYING,this.onDestroying,this))}unregisterListeners(){const t=this.hls;t&&(t.off(Rt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(Rt.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(Rt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(Rt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Rt.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(Rt.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(Rt.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.off(Rt.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(Rt.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.off(Rt.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.off(Rt.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.off(Rt.BUFFER_CODECS,this.onBufferCodecs,this),t.off(Rt.BUFFER_APPENDED,this.onBufferAppended,this),t.off(Rt.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(Rt.BUFFERED_TO_END,this.onBufferedToEnd,this),t.off(Rt.MEDIA_ENDED,this.onMediaEnded,this),t.off(Rt.ERROR,this.onError,this),t.off(Rt.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){E_(t,"play",this.onPlay),E_(t,"pause",this.onPause),E_(t,"seeking",this.onSeeking),E_(t,"timeupdate",this.onTimeupdate)}onMediaAttaching(t,n){const r=this.media=n.media;vb(r,"seeking",this.onSeeking),vb(r,"timeupdate",this.onTimeupdate),vb(r,"play",this.onPlay),vb(r,"pause",this.onPause)}onMediaAttached(t,n){const r=this.effectivePlayingItem,a=this.detachedData;if(this.detachedData=null,r===null)this.checkStart();else if(!a){this.clearScheduleState();const i=this.findItemIndex(r);this.setSchedulePosition(i)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(t,n){const r=!!n.transferMedia,a=this.media;if(this.media=null,!r&&(a&&this.removeMediaListeners(a),this.detachedData)){const i=this.getBufferingPlayer();i&&(this.log(`Removing schedule state for detachedData and ${i}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,i.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const t=this,n=()=>t.bufferingItem||t.waitingItem,r=h=>h&&t.getAssetPlayer(h.identifier),a=(h,m,p,f,y)=>{if(h){let v=h[m].start;const g=h.event;if(g){if(m==="playout"||g.timelineOccupancy!==R6e.Point){const b=r(p);(b==null?void 0:b.interstitial)===g&&(v+=b.assetItem.startOffset+b[y])}}else{const b=f==="bufferedPos"?l():t[f];v+=b-h.start}return v}return 0},i=(h,m)=>{var p;if(h!==0&&m!=="primary"&&(p=t.schedule)!=null&&p.length){var f;const y=t.schedule.findItemIndexAtTime(h),v=(f=t.schedule.items)==null?void 0:f[y];if(v){const g=v[m].start-v.start;return h+g}}return h},l=()=>{const h=t.bufferedPos;return h===Number.MAX_VALUE?o("primary"):Math.max(h,0)},o=h=>{var m,p;return(m=t.primaryDetails)!=null&&m.live?t.primaryDetails.edge:((p=t.schedule)==null?void 0:p.durations[h])||0},c=(h,m)=>{var p,f;const y=t.effectivePlayingItem;if(y!=null&&(p=y.event)!=null&&p.restrictions.skip||!t.schedule)return;t.log(`seek to ${h} "${m}"`);const v=t.effectivePlayingItem,g=t.schedule.findItemIndexAtTime(h,m),b=(f=t.schedule.items)==null?void 0:f[g],j=t.getBufferingPlayer(),S=j==null?void 0:j.interstitial,C=S==null?void 0:S.appendInPlace,E=v&&t.itemsMatch(v,b);if(v&&(C||E)){const P=r(t.playingAsset),M=(P==null?void 0:P.media)||t.primaryMedia;if(M){const I=m==="primary"?M.currentTime:a(v,m,t.playingAsset,"timelinePos","currentTime"),D=h-I,O=(C?I:M.currentTime)+D;if(O>=0&&(!P||C||O<=P.duration)){M.currentTime=O;return}}}if(b){let P=h;if(m!=="primary"){const I=b[m].start,D=h-I;P=b.start+D}const M=!t.isInterstitial(b);if((!t.isInterstitial(v)||v.event.appendInPlace)&&(M||b.event.appendInPlace)){const I=t.media||(C?j==null?void 0:j.media:null);I&&(I.currentTime=P)}else if(v){const I=t.findItemIndex(v);if(g>I){const O=t.schedule.findJumpRestrictedIndex(I+1,g);if(O>I){t.setSchedulePosition(O);return}}let D=0;if(M)t.timelinePos=P,t.checkBuffer();else{const O=b.event.assetList,V=h-(b[m]||b).start;for(let G=O.length;G--;){const $=O[G];if($.duration&&V>=$.startOffset&&V<$.startOffset+$.duration){D=G;break}}}t.setSchedulePosition(g,D)}}},d=()=>{const h=t.effectivePlayingItem;if(t.isInterstitial(h))return h;const m=n();return t.isInterstitial(m)?m:null},u={get bufferedEnd(){const h=n(),m=t.bufferingItem;if(m&&m===h){var p;return a(m,"playout",t.bufferingAsset,"bufferedPos","bufferedEnd")-m.playout.start||((p=t.bufferingAsset)==null?void 0:p.startOffset)||0}return 0},get currentTime(){const h=d(),m=t.effectivePlayingItem;return m&&m===h?a(m,"playout",t.effectivePlayingAsset,"timelinePos","currentTime")-m.playout.start:0},set currentTime(h){const m=d(),p=t.effectivePlayingItem;p&&p===m&&c(h+p.playout.start,"playout")},get duration(){const h=d();return h?h.playout.end-h.playout.start:0},get assetPlayers(){var h;const m=(h=d())==null?void 0:h.event.assetList;return m?m.map(p=>t.getAssetPlayer(p.identifier)):[]},get playingIndex(){var h;const m=(h=d())==null?void 0:h.event;return m&&t.effectivePlayingAsset?m.findAssetIndex(t.effectivePlayingAsset):-1},get scheduleItem(){return d()}};return this.manager={get events(){var h;return((h=t.schedule)==null||(h=h.events)==null?void 0:h.slice(0))||[]},get schedule(){var h;return((h=t.schedule)==null||(h=h.items)==null?void 0:h.slice(0))||[]},get interstitialPlayer(){return d()?u:null},get playerQueue(){return t.playerQueue.slice(0)},get bufferingAsset(){return t.bufferingAsset},get bufferingItem(){return n()},get bufferingIndex(){const h=n();return t.findItemIndex(h)},get playingAsset(){return t.effectivePlayingAsset},get playingItem(){return t.effectivePlayingItem},get playingIndex(){const h=t.effectivePlayingItem;return t.findItemIndex(h)},primary:{get bufferedEnd(){return l()},get currentTime(){const h=t.timelinePos;return h>0?h:0},set currentTime(h){c(h,"primary")},get duration(){return o("primary")},get seekableStart(){var h;return((h=t.primaryDetails)==null?void 0:h.fragmentStart)||0}},integrated:{get bufferedEnd(){return a(n(),"integrated",t.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return a(t.effectivePlayingItem,"integrated",t.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(h){c(h,"integrated")},get duration(){return o("integrated")},get seekableStart(){var h;return i(((h=t.primaryDetails)==null?void 0:h.fragmentStart)||0,"integrated")}},skip:()=>{const h=t.effectivePlayingItem,m=h==null?void 0:h.event;if(m&&!m.restrictions.skip){const p=t.findItemIndex(h);if(m.appendInPlace){const f=h.playout.start+h.event.duration;c(f+.001,"playout")}else t.advanceAfterAssetEnded(m,p,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var t;const n=this.playingItem,r=(t=this.schedule)==null?void 0:t.items;return!this.playbackStarted||!n||!r?!1:this.findItemIndex(n)===r.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var t,n;if(this.mediaSelection===null)return;const r=this.waitingItem||this.playingItem;if(this.isInterstitial(r)&&!r.event.appendInPlace)return;let a=this.media;!a&&(t=this.bufferingItem)!=null&&(t=t.event)!=null&&t.appendInPlace&&(a=this.primaryMedia);const i=(n=a)==null?void 0:n.currentTime;if(!(i===void 0||!Wi(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} ${Lm(i)}`),this.detachedData=i}else n&&a&&(this.shouldPlay||(this.shouldPlay=!a.paused))}transferMediaTo(t,n){var r,a;if(t.media===n)return;let i=null;const l=this.hls,o=t!==l,c=o&&t.interstitial.appendInPlace,d=(r=this.detachedData)==null?void 0:r.mediaSource;let u;if(l.media)c&&(i=l.transferMedia(),this.detachedData=i),u="Primary";else if(d){const f=this.getBufferingPlayer();f?(i=f.transferMedia(),u=`${f}`):u="detached MediaSource"}else u="detached media";if(!i){if(d)i=this.detachedData,this.log(`using detachedData: MediaSource ${Lm(i)}`);else if(!this.detachedData||l.media===n){const f=this.playerQueue;f.length>1&&f.forEach(y=>{if(o&&y.interstitial.appendInPlace!==c){const v=y.interstitial;this.clearInterstitial(y.interstitial,null),v.appendInPlace=!1,v.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${v}`)}}),this.hls.detachMedia(),this.detachedData={media:n}}}const h=i&&"mediaSource"in i&&((a=i.mediaSource)==null?void 0:a.readyState)!=="closed",m=h&&i?i:n;this.log(`${h?"transfering MediaSource":"attaching media"} to ${o?t:"Primary"} from ${u} (media.currentTime: ${n.currentTime})`);const p=this.schedule;if(m===i&&p){const f=o&&t.assetId===p.assetIdAtEnd;m.overrides={duration:p.duration,endOfStream:!o||f,cueRemoval:!o}}t.attachMedia(m)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const t=this.schedule,n=t==null?void 0:t.events;if(!n||this.playbackDisabled||!this.media)return;this.bufferedPos===-1&&(this.bufferedPos=0);const r=this.timelinePos,a=this.effectivePlayingItem;if(r===-1){const i=this.hls.startPosition;if(this.timelinePos=i,n.length===0)this.setSchedulePosition(0);else if(n[0].cue.pre){this.log(cU("checkStart (preroll)",i));const l=t.findEventIndex(n[0].identifier);this.setSchedulePosition(l)}else if(i>=0||!this.primaryLive){this.log(cU("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(cU("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=iUe(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=iUe(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&&bk(i)}) pos: ${this.timelinePos}`);const l=this.waitingItem||this.playingItem,o=this.playingLastItem;if(this.isInterstitial(l)){const u=l.event,h=this.playingAsset,m=h==null?void 0:h.identifier,p=m?this.getAssetPlayer(m):null;if(p&&m&&(!this.eventItemsMatch(l,i)||n!==void 0&&m!==u.assetList[n].identifier)){var c;const f=u.findAssetIndex(h);if(this.log(`INTERSTITIAL_ASSET_ENDED ${f+1}/${u.assetList.length} ${LU(h)}`),this.endedAsset=h,this.playingAsset=null,this.hls.trigger(Rt.INTERSTITIAL_ASSET_ENDED,{asset:h,assetListIndex:f,event:u,schedule:a.slice(0),scheduleIndex:t,player:p}),l!==this.playingItem){this.itemsMatch(l,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(u,this.findItemIndex(this.playingItem),f);return}this.retreiveMediaSource(m,i),p.media&&!((c=this.detachedData)!=null&&c.mediaSource)&&p.detachMedia()}if(!this.eventItemsMatch(l,i)&&(this.endedItem=l,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${u} ${bk(l)}`),u.hasPlayed=!0,this.hls.trigger(Rt.INTERSTITIAL_ENDED,{event:u,schedule:a.slice(0),scheduleIndex:t}),u.cue.once)){var d;this.updateSchedule();const f=(d=this.schedule)==null?void 0:d.items;if(i&&f){const y=this.findItemIndex(i);this.advanceSchedule(y,f,n,l,o)}return}}this.advanceSchedule(t,a,n,l,o)}advanceSchedule(t,n,r,a,i){const l=this.schedule;if(!l)return;const o=n[t]||null,c=this.primaryMedia,d=this.playerQueue;if(d.length&&d.forEach(u=>{const h=u.interstitial,m=l.findEventIndex(h.identifier);(mt+1)&&this.clearInterstitial(h,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);const u=o.event;if(r===void 0){r=l.findAssetIndex(u,this.timelinePos);const f=iUe(u,r-1);if(u.isAssetPastPlayoutLimit(f)||u.appendInPlace&&this.timelinePos===o.end){this.advanceAfterAssetEnded(u,t,r);return}r=f}const h=this.waitingItem;this.assetsBuffered(o,c)||this.setBufferingItem(o);let m=this.preloadAssets(u,r);if(this.eventItemsMatch(o,h||a)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${bk(o)} ${u.appendInPlace?"append in place":""}`),this.hls.trigger(Rt.INTERSTITIAL_STARTED,{event:u,schedule:n.slice(0),scheduleIndex:t})),!u.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${u}`);return}if(u.assetListLoader&&(u.assetListLoader.destroy(),u.assetListLoader=void 0),!c){this.log(`Waiting for attachMedia to start Interstitial ${u}`);return}this.waitingItem=this.endedItem=null,this.playingItem=o;const p=u.assetList[r];if(!p){this.advanceAfterAssetEnded(u,t,r||0);return}if(m||(m=this.getAssetPlayer(p.identifier)),m===null||m.destroyed){const f=u.assetList.length;this.warn(`asset ${r+1}/${f} player destroyed ${u}`),m=this.createAssetPlayer(u,p,r),m.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&u.appendInPlace&&this.isAssetBuffered(p))return;this.startAssetPlayer(m,r,n,t,c),this.shouldPlay&&A3t(m.media)}else o?(this.resumePrimary(o,t,a),this.shouldPlay&&A3t(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 ${bk(t)}`),!((a=this.detachedData)!=null&&a.mediaSource)){let o=this.timelinePos;(o=t.end)&&(o=this.getPrimaryResumption(t,n),this.log(cU("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 ${bk(t)}`),this.hls.trigger(Rt.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:_c.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(cU("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(Rt.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(Rt.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=Fh(Fh({},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=Fh(Fh({},this.altSelection),{},{audio:r});return}const i=Fh(Fh({},a),{},{audio:r});this.mediaSelection=i}onSubtitleTrackUpdated(t,n){const r=this.hls.subtitleTracks[n.id],a=this.mediaSelection;if(!a){this.altSelection=Fh(Fh({},this.altSelection),{},{subtitles:r});return}const i=Fh(Fh({},a),{},{subtitles:r});this.mediaSelection=i}onAudioTrackSwitching(t,n){const r=FCt(n);this.playerQueue.forEach(({hls:a})=>a&&(a.setAudioOption(n)||a.setAudioOption(r)))}onSubtitleTrackSwitch(t,n){const r=FCt(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=_c.bufferInfo(this.primaryMedia,r,0);(a.end>r||(a.nextStart||0)>r)&&(this.log(`trim buffered interstitial ${bk(t)} (was ${bk(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=_c.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 ${bk(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(Rt.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(Rt.BUFFER_FLUSHING,{startOffset:t,endOffset:1/0,type:a})})}getAssetPlayerQueueIndex(t){const n=this.playerQueue;for(let r=0;r1){const C=n.duration;C&&S{if(S.live){var C;const M=new Error(`Interstitials MUST be VOD assets ${t}`),I={fatal:!0,type:Lo.OTHER_ERROR,details:vr.INTERSTITIAL_ASSET_ITEM_ERROR,error:M},D=((C=this.schedule)==null?void 0:C.findEventIndex(t.identifier))||-1;this.handleAssetItemError(I,t,D,r,M.message);return}const E=S.edge-S.fragmentStart,P=n.duration;(y||P===null||E>P)&&(y=!1,this.log(`Interstitial asset "${h}" duration change ${P} > ${E}`),n.duration=E,this.updateSchedule())};f.on(Rt.LEVEL_UPDATED,(S,{details:C})=>v(C)),f.on(Rt.LEVEL_PTS_UPDATED,(S,{details:C})=>v(C)),f.on(Rt.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const g=(S,C)=>{const E=this.getAssetPlayer(h);if(E&&C.tracks){E.off(Rt.BUFFER_CODECS,g),E.tracks=C.tracks;const P=this.primaryMedia;this.bufferingAsset===E.assetItem&&P&&!E.media&&this.bufferAssetPlayer(E,P)}};f.on(Rt.BUFFER_CODECS,g);const b=()=>{var S;const C=this.getAssetPlayer(h);if(this.log(`buffered to end of asset ${C}`),!C||!this.schedule)return;const E=this.schedule.findEventIndex(t.identifier),P=(S=this.schedule.items)==null?void 0:S[E];this.isInterstitial(P)&&this.advanceAssetBuffering(P,n)};f.on(Rt.BUFFERED_TO_END,b);const j=S=>()=>{if(!this.getAssetPlayer(h)||!this.schedule)return;this.shouldPlay=!0;const E=this.schedule.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,E,S)};return f.once(Rt.MEDIA_ENDED,j(r)),f.once(Rt.PLAYOUT_LIMIT_REACHED,j(1/0)),f.on(Rt.ERROR,(S,C)=>{if(!this.schedule)return;const E=this.getAssetPlayer(h);if(C.details===vr.BUFFER_STALLED_ERROR){if(E!=null&&E.appendInPlace){this.handleInPlaceStall(t);return}this.onTimeupdate(),this.checkBuffer(!0);return}this.handleAssetItemError(C,t,this.schedule.findEventIndex(t.identifier),r,`Asset player error ${C.error} ${t}`)}),f.on(Rt.DESTROYING,()=>{if(!this.getAssetPlayer(h)||!this.schedule)return;const C=new Error(`Asset player destroyed unexpectedly ${h}`),E={fatal:!0,type:Lo.OTHER_ERROR,details:vr.INTERSTITIAL_ASSET_ITEM_ERROR,error:C};this.handleAssetItemError(E,t,this.schedule.findEventIndex(t.identifier),r,C.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${LU(n)}`),this.hls.trigger(Rt.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:n,assetListIndex:r,event:t,player:f}),f}clearInterstitial(t,n){this.clearAssetPlayers(t,n),t.reset()}clearAssetPlayers(t,n){t.assetList.forEach(r=>{this.clearAssetPlayer(r.identifier,n)})}resetAssetPlayer(t){const n=this.getAssetPlayerQueueIndex(t);if(n!==-1){this.log(`reset asset player "${t}" after error`);const r=this.playerQueue[n];this.transferMediaFromPlayer(r,null),r.resetDetails()}}clearAssetPlayer(t,n){const r=this.getAssetPlayerQueueIndex(t);if(r!==-1){const a=this.playerQueue[r];this.log(`clear ${a} toSegment: ${n&&bk(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} ${LU(o)}`),this.hls.trigger(Rt.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&&!kas(h,t.tracks)){const m=new Error(`Asset ${LU(l)} SourceBuffer tracks ('${Object.keys(t.tracks)}') are not compatible with primary content tracks ('${Object.keys(h)}')`),p={fatal:!0,type:Lo.OTHER_ERROR,details:vr.INTERSTITIAL_ASSET_ITEM_ERROR,error:m},f=i.findAssetIndex(l);this.handleAssetItemError(p,i,o,f,m.message);return}}this.transferMediaTo(t,n)}handleInPlaceStall(t){const n=this.schedule,r=this.primaryMedia;if(!n||!r)return;const a=r.currentTime,i=n.findAssetIndex(t,a),l=t.assetList[i];if(l){const o=this.getAssetPlayer(l.identifier);if(o){const c=o.currentTime||a-l.timelineStart,d=o.duration-c;if(this.warn(`Stalled at ${c} of ${c+d} in ${o} ${t} (media.currentTime: ${a})`),c&&(d/r.playbackRate<.5||o.bufferedInPlaceToEnd(r))&&o.hls){const u=n.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,u,i)}}}}advanceInPlace(t){const n=this.primaryMedia;n&&n.currentTime!y.error))n.error=f;else for(let y=a;y{const g=parseFloat(y.DURATION);this.createAsset(i,v,u,c+u,g,y.URI),u+=g}),i.duration=u,this.log(`Loaded asset-list with duration: ${u} (was: ${d}) ${i}`);const h=this.waitingItem,m=(h==null?void 0:h.event.identifier)===l;this.updateSchedule();const p=(a=this.bufferingItem)==null?void 0:a.event;if(m){var f;const y=this.schedule.findEventIndex(l),v=(f=this.schedule.items)==null?void 0:f[y];if(v){if(!this.playingItem&&this.timelinePos>v.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==y){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(v)}this.setSchedulePosition(y)}else if((p==null?void 0:p.identifier)===l){const y=i.assetList[0];if(y){const v=this.getAssetPlayer(y.identifier);if(p.appendInPlace){const g=this.primaryMedia;v&&g&&this.bufferAssetPlayer(v,g)}else v&&v.loadSource()}}}onError(t,n){if(this.schedule)switch(n.details){case vr.ASSET_LIST_PARSING_ERROR:case vr.ASSET_LIST_LOAD_ERROR:case vr.ASSET_LIST_LOAD_TIMEOUT:{const r=n.interstitial;r&&(this.updateSchedule(!0),this.primaryFallback(r));break}case vr.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 E3t=500;class lmr extends bit{constructor(t,n,r){super(t,n,r,"subtitle-stream-controller",mo.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(Rt.LEVEL_LOADED,this.onLevelLoaded,this),t.on(Rt.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(Rt.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(Rt.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(Rt.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on(Rt.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(Rt.LEVEL_LOADED,this.onLevelLoaded,this),t.off(Rt.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(Rt.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(Rt.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(Rt.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off(Rt.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(t,n){this.stopLoad(),this.state=la.IDLE,this.setInterval(E3t),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)||(ng(r)&&(this.fragPrevious=r),this.state=la.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 $se(r));return}this.tracksBuffered=[],this.levels=n.map(r=>{const a=new $se(r);return this.tracksBuffered[a.id]=[],a}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,mo.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!==la.STOPPED&&this.setInterval(E3t)}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?(I6e(l,h),d=l.fragmentStart):m&&(d=m.start,lZe(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,lZe(l,d))}h&&!this.startFragRequested&&this.setStartPosition(h,d)}c.details=l,this.levelLastLoaded=c,o===a&&(this.hls.trigger(Rt.SUBTITLE_TRACK_UPDATED,{details:l,id:o,groupId:n.groupId}),this.tick(),l.live&&!this.fragCurrent&&this.media&&this.state===la.IDLE&&(P9(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&&Q$(a.method)){const l=performance.now();this.decrypter.decrypt(new Uint8Array(r),a.key.buffer,a.iv.buffer,yit(a.method)).catch(o=>{throw i.trigger(Rt.ERROR,{type:Lo.MEDIA_ERROR,details:vr.FRAG_DECRYPT_ERROR,fatal:!1,error:o,reason:o.message,frag:n}),o}).then(o=>{const c=performance.now();i.trigger(Rt.FRAG_DECRYPTED,{frag:n,payload:o,stats:{tstart:l,tdecrypt:c}})}).catch(o=>{this.warn(`${o.name}: ${o.message}`),this.state=la.IDLE})}}doTick(){if(!this.media){this.state=la.IDLE;return}if(this.state===la.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=_c.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],i,a.maxBufferHole),{end:o,len:c}=l,d=r.details,u=this.hls.maxBufferLength+d.levelTargetDuration;if(c>u)return;const h=d.fragments,m=h.length,p=d.edge;let f=null;const y=this.fragPrevious;if(op-b?0:b;f=P9(y,h,Math.max(h[0].start,o),j),!f&&y&&y.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 dmr={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},Vis=s=>String.fromCharCode(dmr[s]||s),Sk=15,C3=100,umr={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},hmr={17:2,18:4,21:6,22:8,23:10,19:13,20:15},mmr={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},pmr={25:2,26:4,29:6,30:8,31:10,27:13,28:15},fmr=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class xmr{constructor(){this.time=null,this.verboseLevel=0}log(t,n){if(this.verboseLevel>=t){const r=typeof n=="function"?n():n;Vh.log(`${this.time} [${t}] ${r}`)}}}const TI=function(t){const n=[];for(let r=0;rC3&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=C3)}moveCursor(t){const n=this.pos+t;if(t>1)for(let r=this.pos+1;r=144&&this.backSpace();const n=Vis(t);if(this.pos>=C3){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 = "+Lm(t));let n=t.row-1;if(this.nrRollUpRows&&n"bkgData = "+Lm(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 T3t{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 oUe(r),this.nonDisplayedMemory=new oUe(r),this.lastOutputScreen=new oUe(r),this.currRollUpRow=this.displayedMemory.rows[Sk-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[Sk-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: "+Lm(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 M3t{constructor(t,n,r){this.channels=void 0,this.currentChannel=0,this.cmdHistory=bmr(),this.logger=void 0;const a=this.logger=new xmr;this.channels=[null,new T3t(t,n,a),new T3t(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"["+TI([n[r],n[r+1]])+"] -> ("+TI([a,i])+")");const c=this.cmdHistory;if(a>=16&&a<=31){if(vmr(a,i,c)){iue(null,null,c),this.logger.log(3,()=>"Repeated command ("+TI([a,i])+") is dropped");continue}iue(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 iue(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 "+TI([a,i])+" orig: "+TI([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 ("+TI([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?umr[t]:mmr[t]:r=l===1?hmr[t]:pmr[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 '"+Vis(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 = "+TI(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=fmr[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.");E=D,this.hasBeenReset=!0}})),Object.defineProperty(u,"positionAlign",i({},h,{get:function(){return P},set:function(D){const O=a(D);if(!O)throw new SyntaxError("An invalid or illegal string was specified.");P=O,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 O=a(D);if(!O)throw new SyntaxError("An invalid or illegal string was specified.");I=O,this.hasBeenReset=!0}})),u.displayState=void 0}return l.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},l}();class _mr{decode(t,n){if(!t)return"";if(typeof t!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))}}function Gis(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 wmr{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 Wis(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 xZe=new Pit(0,0,""),oue=xZe.align==="middle"?"middle":"center";function jmr(s,t,n){const r=s;function a(){const o=Gis(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 wmr;Wis(o,function(m,p){let f;switch(m){case"region":for(let y=n.length-1;y>=0;y--)if(n[y].id===p){d.set(m,n[y].region);break}break;case"vertical":d.alt(m,p,["rl","lr"]);break;case"line":f=p.split(","),d.integer(m,f[0]),d.percent(m,f[0])&&d.set("snapToLines",!1),d.alt(m,f[0],["auto"]),f.length===2&&d.alt("lineAlign",f[1],["start",oue,"end"]);break;case"position":f=p.split(","),d.percent(m,f[0]),f.length===2&&d.alt("positionAlign",f[1],["start",oue,"end","line-left","line-right","auto"]);break;case"size":d.percent(m,p);break;case"align":d.alt(m,p,["start",oue,"end","left","right"]);break}},/:/,/\s/),c.region=d.get("region",null),c.vertical=d.get("vertical","");let u=d.get("line","auto");u==="auto"&&xZe.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",oue);let h=d.get("position","auto");h==="auto"&&xZe.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 Kis(s){return s.replace(//gi,` `)}class Nmr{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new _mr,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=Kis(i);l")===-1){n.cue.id=i;continue}case"CUE":if(!n.cue){n.state="BADCUE";continue}try{jmr(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 kmr=/\r\n|\n\r|\n|\r/g,lUe=function(t,n,r=0){return t.slice(r,r+n.length)===n},Smr=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(!Wi(n)||!Wi(r)||!Wi(a)||!Wi(i))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${t}`);return n+=1e3*r,n+=60*1e3*a,n+=60*60*1e3*i,n};function Lit(s,t,n){return Nee(s.toString())+Nee(t.toString())+Nee(n)}const Cmr=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 Amr(s,t,n,r,a,i,l){const o=new Nmr,c=kj(new Uint8Array(s)).trim().replace(kmr,` `).split(` `),d=[],u=t?Iur(t.baseTime,t.timescale):0;let h="00:00.000",m=0,p=0,f,y=!0;o.oncue=function(v){const g=n[r];let b=n.ccOffset;const j=(m-u)/9e4;if(g!=null&&g.new&&(p!==void 0?b=n.ccOffset=g.start:Cmr(n,r,j)),j){if(!t){f=new Error("Missing initPTS for VTT MPEGTS");return}b=j-n.presentationOffset}const S=v.endTime-v.startTime,C=$w((v.startTime+b-p)*9e4,a*9e4)/9e4;v.startTime=Math.max(C,0),v.endTime=Math.max(C+S,0);const E=v.text.trim();v.text=decodeURIComponent(encodeURIComponent(E)),v.id||(v.id=Lit(v.startTime,v.endTime,E)),v.endTime>0&&d.push(v)},o.onparsingerror=function(v){f=v},o.onflush=function(){if(f){l(f);return}i(d)},c.forEach(v=>{if(y)if(lUe(v,"X-TIMESTAMP-MAP=")){y=!1,v.slice(16).split(",").forEach(g=>{lUe(g,"LOCAL:")?h=g.slice(6):lUe(g,"MPEGTS:")&&(m=parseInt(g.slice(7)))});try{p=Smr(h)/1e3}catch(g){f=g}return}else v===""&&(y=!1);o.parse(v+` `)}),o.flush()}const cUe="stpp.ttml.im1t",Yis=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Zis=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,Emr={left:"start",center:"center",right:"end",start:"start",end:"end"};function P3t(s,t,n,r){const a=xd(new Uint8Array(s),["mdat"]);if(a.length===0){r(new Error("Could not parse IMSC1 mdat"));return}const i=a.map(o=>kj(o)),l=Lur(t.baseTime,1,t.timescale);try{i.forEach(o=>n(Tmr(o,l)))}catch(o){r(o)}}function Tmr(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=L3t(dUe(a,"styling","style")),d=L3t(dUe(a,"layout","region")),u=dUe(a,"body","[begin]");return[].map.call(u,h=>{const m=Xis(h,o);if(!m||!h.hasAttribute("begin"))return null;const p=hUe(h.getAttribute("begin"),l),f=hUe(h.getAttribute("dur"),l);let y=hUe(h.getAttribute("end"),l);if(p===null)throw I3t(h);if(y===null){if(f===null)throw I3t(h);y=p+f}const v=new Pit(p-t,y-t,m);v.id=Lit(v.startTime,v.endTime,v.text);const g=d[h.getAttribute("region")],b=c[h.getAttribute("style")],j=Mmr(g,b,c),{textAlign:S}=j;if(S){const C=Emr[S];C&&(v.lineAlign=C),v.align=S}return pm(v,j),v}).filter(h=>h!==null)}function dUe(s,t,n){const r=s.getElementsByTagName(t)[0];return r?[].slice.call(r.querySelectorAll(n)):[]}function L3t(s){return s.reduce((t,n)=>{const r=n.getAttribute("xml:id");return r&&(t[r]=n),t},{})}function Xis(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?Xis(r,t):t?n+r.textContent.trim().replace(/\s+/g," "):n+r.textContent},"")}function Mmr(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=uUe(t,r,c)||uUe(s,r,c)||uUe(a,r,c);return d&&(o[c]=d),o},{})}function uUe(s,t,n){return s&&s.hasAttributeNS(t,n)?s.getAttributeNS(t,n):null}function I3t(s){return new Error(`Could not parse ttml timestamp ${s}`)}function hUe(s,t){if(!s)return null;let n=Gis(s);return n===null&&(Yis.test(s)?n=Pmr(s,t):Zis.test(s)&&(n=Lmr(s,t))),n}function Pmr(s,t){const n=Yis.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 Lmr(s,t){const n=Zis.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 lue{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 Imr{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=R3t(),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(Rt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(Rt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(Rt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Rt.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(Rt.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(Rt.FRAG_LOADING,this.onFragLoading,this),t.on(Rt.FRAG_LOADED,this.onFragLoaded,this),t.on(Rt.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(Rt.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(Rt.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(Rt.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(Rt.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:t}=this;t.off(Rt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(Rt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(Rt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Rt.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(Rt.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(Rt.FRAG_LOADING,this.onFragLoading,this),t.off(Rt.FRAG_LOADED,this.onFragLoaded,this),t.off(Rt.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.off(Rt.FRAG_DECRYPTED,this.onFragDecrypted,this),t.off(Rt.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(Rt.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.off(Rt.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const t=new lue(this,"textTrack1"),n=new lue(this,"textTrack2"),r=new lue(this,"textTrack3"),a=new lue(this,"textTrack4");this.cea608Parser1=new M3t(1,t,n),this.cea608Parser2=new M3t(3,r,a)}addCues(t,n,r,a,i){let l=!1;for(let o=i.length;o--;){const c=i[o],d=Dmr(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(Rt.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===mo.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(Rt.FRAG_LOADED,c):this.hls.trigger(Rt.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{gq(a[i]),delete a[i]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=R3t(),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===cUe);if(this.config.enableWebVTT||a&&this.config.enableIMSC1){if(Ais(this.tracks,r)){this.tracks=r;return}if(this.textTracks=[],this.tracks=r,this.config.renderTextTracksNatively){const l=this.media,o=l?i3e(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(Rt.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===mo.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===mo.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===cUe?this._parseIMSC1(r,a):this._parseVTTs(n)}}else this.hls.trigger(Rt.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:new Error("Empty subtitle payload")})}_parseIMSC1(t,n){const r=this.hls;P3t(n,this.initPTS[t.cc],a=>{this._appendCues(a,t.level),r.trigger(Rt.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t})},a=>{r.logger.log(`Failed to parse IMSC1: ${a}`),r.trigger(Rt.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?RN(r.initSegment.data,new Uint8Array(a)).buffer:a;Amr(d,this.initPTS[r.cc],this.vttCCs,r.cc,r.start,u=>{this._appendCues(u,r.level),c.trigger(Rt.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(Rt.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:u})})}_fallbackToIMSC1(t,n){const r=this.tracks[t.level];r.textCodec||P3t(n,this.initPTS[t.cc],()=>{r.textCodec=cUe,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=>qis(a,i))}else{const a=this.tracks[n];if(!a)return;const i=a.default?"default":"subtitles"+n;r.trigger(Rt.CUES_PARSED,{type:"subtitles",cues:t,track:i})}}onFragDecrypted(t,n){const{frag:r}=n;r.type===mo.SUBTITLE&&this.onFragLoaded(Rt.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===mo.MAIN&&this.closedCaptionsForLevel(r)==="NONE"))for(let i=0;ifZe(o[c],n,r))}if(this.config.renderTextTracksNatively&&n===0&&a!==void 0){const{textTracks:o}=this;Object.keys(o).forEach(c=>fZe(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=Kis(d.trim()),f=Lit(t,n,p);s!=null&&(h=s.cues)!=null&&h.getCueById(f)||(l=new u(t,n,p),l.id=f,l.line=m+1,l.align="left",l.position=10+Math.min(80,Math.floor(c*8/32)*10),a.push(l))}return s&&a.length&&(a.sort((m,p)=>m.line==="auto"||p.line==="auto"?0:m.line>8&&p.line>8?p.line-m.line:m.line-p.line),a.forEach(m=>qis(s,m))),a}};function Omr(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const zmr=/(\d+)-(\d+)\/(\d+)/;class F3t{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||$mr,this.controller=new self.AbortController,this.stats=new uit}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=Bmr(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&&Wi(c)?c:d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(a,t,this.response))},n.timeout),(Gse(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:y,statusText:v}=h;throw new Vmr(v||"fetch, bad network response",y,h)}a.loading.first=p,a.total=qmr(h.headers)||a.total;const f=(m=this.callbacks)==null?void 0:m.onProgress;return f&&Wi(n.highWaterMark)?this.loadProgressively(h,a,t,n.highWaterMark,f):l?h.arrayBuffer():t.responseType==="json"?h.json():h.text()}).then(h=>{var m,p;const f=this.response;if(!f)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),a.loading.end=Math.max(self.performance.now(),a.loading.first);const y=h[o];y&&(a.loaded=a.total=y);const v={url:f.url,data:h,code:f.status},g=(m=this.callbacks)==null?void 0:m.onProgress;g&&!Wi(n.highWaterMark)&&g(a,t,h,f),(p=this.callbacks)==null||p.onSuccess(v,a,t,f)}).catch(h=>{var m;if(self.clearTimeout(this.requestTimeout),a.aborted)return;const p=h&&h.code||0,f=h?h.message:null;(m=this.callbacks)==null||m.onError({code:p,text:f},t,h?h.details:null,a)})}getCacheAge(){let t=null;if(this.response){const n=this.response.headers.get("age");t=n?parseFloat(n):null}return t}getResponseHeader(t){return this.response?this.response.headers.get(t):null}loadProgressively(t,n,r,a=0,i){const l=new lis,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 Bmr(s,t){const n={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(pm({},s.headers))};return s.rangeEnd&&n.headers.set("Range","bytes="+s.rangeStart+"-"+String(s.rangeEnd-1)),n}function Umr(s){const t=zmr.exec(s);if(t)return parseInt(t[2])-parseInt(t[1])+1}function qmr(s){const t=s.get("Content-Range");if(t){const r=Umr(t);if(Wi(r))return r}const n=s.get("Content-Length");if(n)return parseInt(n)}function $mr(s,t){return new self.Request(s.url,t)}class Vmr extends Error{constructor(t,n,r){super(t),this.code=void 0,this.details=void 0,this.code=n,this.details=r}}const Hmr=/^age:\s*[\d.]+\s*$/im;class Jis{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 uit,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&&Wi(i)?i:l,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.timeout),t.send()}readystatechange(){const{context:t,loader:n,stats:r}=this;if(!t||!n)return;const a=n.readyState,i=this.config;if(!r.aborted&&a>=2&&(r.loading.first===0&&(r.loading.first=Math.max(self.performance.now(),r.loading.start),i.timeout!==i.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),i.timeout=i.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.loadPolicy.maxLoadTimeMs-(r.loading.first-r.loading.start)))),a===4)){self.clearTimeout(this.requestTimeout),n.onreadystatechange=null,n.onprogress=null;const d=n.status,u=n.responseType==="text"?n.responseText:null;if(d>=200&&d<300){const f=u??n.response;if(f!=null){var l,o;r.loading.end=Math.max(self.performance.now(),r.loading.first);const y=n.responseType==="arraybuffer"?f.byteLength:f.length;r.loaded=r.total=y,r.bwEstimate=r.total*8e3/(r.loading.end-r.loading.first);const v=(l=this.callbacks)==null?void 0:l.onProgress;v&&v(r,t,f,n);const g={url:n.responseURL,data:f,code:d};(o=this.callbacks)==null||o.onSuccess(g,r,t,n);return}}const h=i.loadPolicy.errorRetry,m=r.retry,p={url:t.url,data:void 0,code:d};if(M6e(h,m,!1,p))this.retry(h);else{var c;Vh.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(M6e(t,n,!0))this.retry(t);else{var r;Vh.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=fit(t,r.retry),r.retry++,Vh.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&&Hmr.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 Gmr={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},Wmr=Fh(Fh({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:Jis,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:adr,bufferController:Yur,capLevelController:Eit,errorController:ddr,fpsController:Zhr,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:Xas,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:Gmr},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},Kmr()),{},{subtitleStreamController:lmr,subtitleTrackController:Jhr,timelineController:Imr,audioStreamController:Hur,audioTrackController:Gur,emeController:J$,cmcdController:Ghr,contentSteeringController:Khr,interstitialsController:omr});function Kmr(){return{cueHandler:Fmr,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 Ymr(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=gZe(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}": ${Lm(t[o])}`)}),Fh(Fh({},r),t)}function gZe(s){return s&&typeof s=="object"?Array.isArray(s)?s.map(gZe):Object.keys(s).reduce((t,n)=>(t[n]=gZe(s[n]),t),{}):s}function Zmr(s,t){const n=s.loader;n!==F3t&&n!==Jis?(t.log("[config]: Custom loader detected, cannot enable progressive streaming"),s.progressive=!1):Omr()&&(s.loader=F3t,s.progressive=!0,s.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}const o3e=2,Xmr=.1,Qmr=.05,Jmr=100;class epr extends Gas{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(Rt.MEDIA_ENDED,{stalled:!1})}},this.hls=t,this.fragmentTracker=n,this.registerListeners()}registerListeners(){const{hls:t}=this;t&&(t.on(Rt.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(Rt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(Rt.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(Rt.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(Rt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(Rt.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(Jmr),this.mediaSource=n.mediaSource;const r=this.media=n.media;vb(r,"playing",this.onMediaPlaying),vb(r,"waiting",this.onMediaWaiting),vb(r,"ended",this.onMediaEnded)}onMediaDetaching(t,n){this.clearInterval();const{media:r}=this;r&&(E_(r,"playing",this.onMediaPlaying),E_(r,"waiting",this.onMediaWaiting),E_(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(Rt.MEDIA_ENDED,{stalled:!1}));return}if(!_c.getBuffered(l).length){this.nudgeRetry=0;return}const h=_c.bufferInfo(l,t,0),m=h.nextStart||0,p=this.fragmentTracker;if(o&&p&&this.hls){const E=O3t(this.hls.inFlightFragments,t),P=h.len>o3e,M=!m||E||m-t>o3e&&!p.getPartialFragment(t);if(P||M)return;this.moved=!1}const f=(a=this.hls)==null?void 0:a.latestLevelDetails;if(!this.moved&&this.stalled!==null&&p){if(!(h.len>0)&&!m)return;const P=Math.max(m,h.start||0)-t,I=!!(f!=null&&f.live)?f.targetduration*2:o3e,D=cue(t,p);if(P>0&&(P<=I||D)){l.paused||this._trySkipBufferHole(D);return}}const y=i.detectStallWithCurrentTimeMs,v=self.performance.now(),g=this.waiting;let b=this.stalled;if(b===null)if(g>0&&v-g=y||g)&&this.hls){var S;if(((S=this.mediaSource)==null?void 0:S.readyState)==="ended"&&!(f!=null&&f.live)&&Math.abs(t-((f==null?void 0:f.edge)||0))<1){if(this.ended)return;this.ended=t||1,this.hls.trigger(Rt.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(h),!this.media||!this.hls)return}const C=_c.bufferInfo(l,t,i.maxBufferHole);this._tryFixBufferStall(C,j,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(Rt.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=_c.bufferedInfo(_c.timeRangesToArray(this.buffered.audio),t,0);if(i.len>1&&n>=i.start){const l=_c.timeRangesToArray(a),o=_c.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=cue(t,this.fragmentTracker);m&&"fragment"in m?m=m.fragment:m||(m=void 0);const p=_c.bufferInfo(this.media,t,0);this.hls.trigger(Rt.ERROR,{type:Lo.MEDIA_ERROR,details:vr.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=cue(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,mo.MAIN),l=r.getFragAtPos(a,mo.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 (${Lm(t)})`);this.warn(l.message),n.trigger(Rt.ERROR,{type:Lo.MEDIA_ERROR,details:vr.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=_c.bufferInfo(a,l,0),c=l0&&o.len<1&&a.readyState<3,m=c-l;if(m>0&&(u||h)){if(m>i.maxBufferHole){let f=!1;if(l===0){const y=r.getAppendedFrag(0,mo.MAIN);y&&c"u"))return self.VTTCue||self.TextTrackCue}function mUe(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,Lm(a?Fh({type:a},r):r))}return i}const due=(()=>{const s=yZe();try{s&&new s(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class spr{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(Rt.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(Rt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(Rt.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(Rt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(Rt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Rt.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on(Rt.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(Rt.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(Rt.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:t}=this;t&&(t.off(Rt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(Rt.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(Rt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(Rt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Rt.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off(Rt.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(Rt.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(Rt.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&&gq(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;ndue&&(h=due),h-u<=0&&(h=u+tpr);for(let p=0;pu.type===Yw.audioId3&&c:a==="video"?d=u=>u.type===Yw.emsg&&o:d=u=>u.type===Yw.audioId3&&c||u.type===Yw.emsg&&o,fZe(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=yZe();if(r&&a&&!l){const{fragmentStart:y,fragmentEnd:v}=t;let g=this.assetCue;g?(g.startTime=y,g.endTime=v):o&&(g=this.assetCue=mUe(o,y,v,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),g&&(g.id=r,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(g),g.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 y=Object.keys(h).filter(v=>!u.includes(v));for(let v=y.length;v--;){var p;const g=y[v],b=(p=h[g])==null?void 0:p.cues;delete h[g],b&&Object.keys(b).forEach(j=>{const S=b[j];if(S){S.removeEventListener("enter",this.onEventCueEnter);try{c.removeCue(S)}catch{}}})}}else h=this.dateRangeCuesAppended={}}const f=t.fragments[t.fragments.length-1];if(!(u.length===0||!Wi(f==null?void 0:f.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let y=0;y{if(V!==g.id){const G=d[V];if(G.class===g.class&&G.startDate>g.startDate&&(!O||g.startDate.01&&(V.startTime=b,V.endTime=E);else if(o){let G=g.attr[O];Ndr(O)&&(G=Sas(G));const H=mUe(o,b,E,{key:O,data:G},Yw.dateRange);H&&(H.id=v,this.id3Track.addCue(H),S[O]=H,l&&(O==="X-ASSET-LIST"||O==="X-ASSET-URL")&&H.addEventListener("enter",this.onEventCueEnter))}}h[v]={cues:S,dateRange:g,durationKnown:C}}}}}class npr{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(Rt.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(Rt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(Rt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Rt.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(Rt.ERROR,this.onError,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(Rt.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(Rt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(Rt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Rt.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(Rt.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===vr.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 rpr extends Ait{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(Rt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Rt.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(Rt.LEVEL_LOADED,this.onLevelLoaded,this),t.on(Rt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(Rt.FRAG_BUFFERED,this.onFragBuffered,this),t.on(Rt.ERROR,this.onError,this)}_unregisterListeners(){const{hls:t}=this;t.off(Rt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Rt.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(Rt.LEVEL_LOADED,this.onLevelLoaded,this),t.off(Rt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(Rt.FRAG_BUFFERED,this.onFragBuffered,this),t.off(Rt.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=C6e(m,r)||void 0),p&&(p=u.videoCodec=Bcr(p));const{width:f,height:y,unknownCodecs:v}=u,g=(v==null?void 0:v.length)||0;if(o||(o=!!(f&&y)),c||(c=!!p),d||(d=!!m),g||m&&!this.isAudioSupported(m)||p&&!this.isVideoSupported(p)){this.log(`Some or all CODECS not supported "${h.CODECS}"`);return}const{CODECS:b,"FRAME-RATE":j,"HDCP-LEVEL":S,"PATHWAY-ID":C,RESOLUTION:E,"VIDEO-RANGE":P}=h,I=`${`${C||"."}-`}${u.bitrate}-${E}-${j}-${b}-${P}-${S}`;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 O=this.createLevel(u);i[I]=O,a.push(O)}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 $se(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=Oas(a,[])}return n}isAudioSupported(t){return Use(t,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(t){return Use(t,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(t,n,r,a,i){var l;let o=[],c=[],d=t;const u=((l=n.stats)==null?void 0:l.parsing)||{};if((r||a)&&i&&(d=d.filter(({videoCodec:b,videoRange:j,width:S,height:C})=>(!!b||!!(S&&C))&&Zcr(j))),d.length===0){Promise.resolve().then(()=>{if(this.hls){let b="no level with compatible codecs found in manifest",j=b;n.levels.length&&(j=`one or more CODECS in variant not supported: ${Lm(n.levels.map(C=>C.attrs.CODECS).filter((C,E,P)=>P.indexOf(C)===E))}`,this.warn(j),b+=` (${j})`);const S=new Error(b);this.hls.trigger(Rt.ERROR,{type:Lo.MEDIA_ERROR,details:vr.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:n.url,error:S,reason:j})}}),u.end=performance.now();return}n.audioTracks&&(o=n.audioTracks.filter(b=>!b.audioCodec||this.isAudioSupported(b.audioCodec)),B3t(o)),n.subtitles&&(c=n.subtitles,B3t(c));const h=d.slice(0);d.sort((b,j)=>{if(b.attrs["HDCP-LEVEL"]!==j.attrs["HDCP-LEVEL"])return(b.attrs["HDCP-LEVEL"]||"")>(j.attrs["HDCP-LEVEL"]||"")?1:-1;if(r&&b.height!==j.height)return b.height-j.height;if(b.frameRate!==j.frameRate)return b.frameRate-j.frameRate;if(b.videoRange!==j.videoRange)return A6e.indexOf(b.videoRange)-A6e.indexOf(j.videoRange);if(b.videoCodec!==j.videoCodec){const S=MCt(b.videoCodec),C=MCt(j.videoCodec);if(S!==C)return C-S}if(b.uri===j.uri&&b.codecSet!==j.codecSet){const S=S6e(b.codecSet),C=S6e(j.codecSet);if(S!==C)return C-S}return b.averageBitrate!==j.averageBitrate?b.averageBitrate-j.averageBitrate:0});let m=h[0];if(this.steering&&(d=this.steering.filterParsedLevels(d),d.length!==h.length)){for(let b=0;bS&&S===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=C)}break}const f=i&&!a,y=this.hls.config,v=!!(y.audioStreamController&&y.audioTrackController),g={levels:d,audioTracks:o,subtitleTracks:c,sessionData:n.sessionData,sessionKeys:n.sessionKeys,firstLevel:this._firstLevel,stats:n.stats,audio:i,video:a,altAudio:v&&!f&&o.some(b=>!!b.url)};u.end=performance.now(),this.hls.trigger(Rt.MANIFEST_PARSED,g)}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(Rt.ERROR,{type:Lo.OTHER_ERROR,details:vr.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(Rt.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===Ad.LEVEL&&n.context.level===this.level&&this.checkRetry(n)}onFragBuffered(t,{frag:n}){if(n!==void 0&&n.type===mo.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(Rt.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));ais(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(Rt.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(Rt.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:n,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:r}))}}function B3t(s){const t={};s.forEach(n=>{const r=n.groupId||"";n.id=t[r]=t[r]||0,t[r]++})}function eos(){return self.SourceBuffer||self.WebKitSourceBuffer}function tos(){if(!ZP())return!1;const t=eos();return!t||t.prototype&&typeof t.prototype.appendBuffer=="function"&&typeof t.prototype.remove=="function"}function apr(){if(!tos())return!1;const s=ZP();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(qse(t,"video")))||["mp4a.40.2","fLaC"].some(t=>s.isTypeSupported(qse(t,"audio"))))}function ipr(){var s;const t=eos();return typeof(t==null||(s=t.prototype)==null?void 0:s.changeType)=="function"}const opr=100;class lpr extends bit{constructor(t,n,r){super(t,n,r,"stream-controller",mo.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||!Wi(i)||(this.log(`Media seeked to ${i.toFixed(3)}`),!this.getBufferedFrag(i)))return;const l=this.getFwdBufferInfoAtPos(a,i,mo.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(Rt.MANIFEST_PARSED,this.onManifestParsed,this),t.on(Rt.LEVEL_LOADING,this.onLevelLoading,this),t.on(Rt.LEVEL_LOADED,this.onLevelLoaded,this),t.on(Rt.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(Rt.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(Rt.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(Rt.BUFFER_CREATED,this.onBufferCreated,this),t.on(Rt.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(Rt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(Rt.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(Rt.MANIFEST_PARSED,this.onManifestParsed,this),t.off(Rt.LEVEL_LOADED,this.onLevelLoaded,this),t.off(Rt.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(Rt.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(Rt.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(Rt.BUFFER_CREATED,this.onBufferCreated,this),t.off(Rt.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(Rt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(Rt.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(opr),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=la.IDLE,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=n?-1:t,this.tick()}else this._forceStartLoad=!0,this.state=la.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case la.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=la.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=la.IDLE;break}break}case la.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===la.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 y={};this.altAudio===2&&(y.type="video"),this.hls.trigger(Rt.BUFFER_EOS,y),this.state=la.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===la.WAITING_LEVEL||this.waitForLive(l)){this.level=i,this.state=la.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&&ng(p)&&this.fragmentTracker.getState(p)!==f0.OK){var f;const v=((f=this.backtrackFragment)!=null?f:p).sn-d.startSN,g=d.fragments[v-1];g&&p.cc===g.cc&&(p=g,this.fragmentTracker.removeFragment(g))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(p&&this.isLoopLoading(p,m)){if(!p.gap){const v=this.audioOnly&&!this.altAudio?Am.AUDIO:Am.VIDEO,g=(v===Am.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;g&&this.afterBufferFlushed(g,v,mo.MAIN)}p=this.getNextFragmentLoopLoading(p,d,o,mo.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===f0.NOT_LOADED||a===f0.PARTIAL?ng(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,mo.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(Rt.AUDIO_TRACK_SWITCHED,n)}),r.trigger(Rt.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}r.trigger(Rt.AUDIO_TRACK_SWITCHED,n)}}onAudioTrackSwitched(t,n){const r=E6e(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===mo.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===la.PARSED&&(this.state=la.IDLE);return}const o=a?a.stats:r.stats;this.fragLastKbps=Math.round(8*o.total/(o.buffering.end-o.loading.first)),ng(r)&&(this.fragPrevious=r),this.fragBufferedComplete(r,a)}const l=this.media;l&&(!this._hasEnoughToStart&&_c.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=la.ERROR;return}switch(n.details){case vr.FRAG_GAP:case vr.FRAG_PARSING_ERROR:case vr.FRAG_DECRYPT_ERROR:case vr.FRAG_LOAD_ERROR:case vr.FRAG_LOAD_TIMEOUT:case vr.KEY_LOAD_ERROR:case vr.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(mo.MAIN,n);break;case vr.LEVEL_LOAD_ERROR:case vr.LEVEL_LOAD_TIMEOUT:case vr.LEVEL_PARSING_ERROR:!n.levelRetry&&this.state===la.WAITING_LEVEL&&((r=n.context)==null?void 0:r.type)===Ad.LEVEL&&(this.state=la.IDLE);break;case vr.BUFFER_ADD_CODEC_ERROR:case vr.BUFFER_APPEND_ERROR:if(n.parent!=="main")return;this.reduceLengthAndFlushBuffer(n)&&this.resetLoadingState();break;case vr.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 vr.INTERNAL_EXCEPTION:this.recoverWorkerError(n);break}}onFragLoadEmergencyAborted(){this.state=la.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(t,{type:n}){if(n!==Am.AUDIO||!this.altAudio){const r=(n===Am.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;r&&(this.afterBufferFlushed(r,n,mo.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=la.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(Rt.FRAG_LOADED,r),i.bitrateTest=!1}).catch(r=>{this.state===la.STOPPED||this.state===la.ERROR||(this.warn(r),this.resetFragmentLoading(t))})}_handleTransmuxComplete(t){const n=this.playlistType,{hls:r}=this,{remuxResult:a,chunkMeta:i}=t,l=this.getCurrentContext(i);if(!l){this.resetWhenMissingContext(i);return}const{frag:o,part:c,level:d}=l,{video:u,text:h,id3:m,initSegment:p}=a,{details:f}=d,y=this.altAudio?void 0:a.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=la.PARSING,p){const v=p.tracks;if(v){const S=o.initSegment||o;if(this.unhandledEncryptionError(p,o))return;this._bufferInitSegment(d,v,S,i),r.trigger(Rt.FRAG_PARSING_INIT_SEGMENT,{frag:S,id:n,tracks:v})}const g=p.initPTS,b=p.timescale,j=this.initPTS[o.cc];if(Wi(g)&&(!j||j.baseTime!==g||j.timescale!==b)){const S=p.trackId;this.initPTS[o.cc]={baseTime:g,timescale:b,trackId:S},r.trigger(Rt.INIT_PTS_FOUND,{frag:o,id:n,initPTS:g,timescale:b,trackId:S})}}if(u&&f){y&&u.type==="audiovideo"&&this.logMuxedErr(o);const v=f.fragments[o.sn-1-f.startSN],g=o.sn===f.startSN,b=!v||o.cc>v.cc;if(a.independent!==!1){const{startPTS:j,endPTS:S,startDTS:C,endDTS:E}=u;if(c)c.elementaryStreams[u.type]={startPTS:j,endPTS:S,startDTS:C,endDTS:E};else if(u.firstKeyFrame&&u.independent&&i.id===1&&!b&&(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:j;if(!g&&Mo3e&&(o.gap=!0);o.setElementaryStreamInfo(u.type,j,S,C,E),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(u,o,c,i,g||b)}else if(g||b)o.gap=!0;else{this.backtrack(o);return}}if(y){const{startPTS:v,endPTS:g,startDTS:b,endDTS:j}=y;c&&(c.elementaryStreams[Am.AUDIO]={startPTS:v,endPTS:g,startDTS:b,endDTS:j}),o.setElementaryStreamInfo(Am.AUDIO,v,g,b,j),this.bufferFragmentData(y,o,c,i)}if(f&&m!=null&&m.samples.length){const v={id:n,frag:o,details:f,samples:m.samples};r.trigger(Rt.FRAG_PARSING_METADATA,v)}if(f&&h){const v={id:n,frag:o,details:f,samples:h.samples};r.trigger(Rt.FRAG_PARSING_USERDATA,v)}}logMuxedErr(t){this.warn(`${ng(t)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${t.url}`)}_bufferInitSegment(t,n,r,a){if(this.state!==la.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=e3e(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=mo.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=mo.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(Rt.BUFFER_CODECS,n),!this.hls)return;c.forEach(d=>{const h=n[d].initSegment;h!=null&&h.byteLength&&this.hls.trigger(Rt.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,mo.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=la.IDLE}checkFragmentChanged(){const t=this.media;let n=null;if(t&&t.readyState>1&&t.seeking===!1){const r=t.currentTime;if(_c.isBuffered(t,r)?n=this.getAppendedFrag(r):_c.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(Rt.FRAG_CHANGED,{frag:n}),(!a||a.level!==i)&&this.hls.trigger(Rt.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 Wi(n)?this.getAppendedFrag(n):null}get currentProgramDateTime(){var t;const n=((t=this.media)==null?void 0:t.currentTime)||this.lastCurrentTime;if(Wi(n)){const r=this.getLevelDetails(),a=this.currentFrag||(r?P9(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 cpr extends GN{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=vr.KEY_LOAD_ERROR,r,a,i){return new $3({type:Lo.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=s3e(o);if(c)return this.emeController.getKeySystemAccess([c])})}if(this.config.requireKeySystemAccessOnStart){const a=sQ(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,vr.KEY_LOAD_ERROR,d))}const l=i.uri;if(!l)return Promise.reject(this.createKeyLoadError(t,vr.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${l}"`)));const o=pUe(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: "+lv(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,vr.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=Acr(n.initSegment.data);if(l.length){let o=l[0];o.some(c=>c!==0)?(this.log(`Using keyId found in init segment ${lv(o)}`),NP.setKeyIdForUri(t.decryptdata.uri,o)):(o=NP.addKeyIdForUri(t.decryptdata.uri),this.log(`Generating keyId to patch media ${lv(o)}`)),t.decryptdata.keyId=o}}if(!t.decryptdata.keyId&&!ng(n))return Promise.resolve(r);const i=this.emeController.loadKey(r);return(t.keyLoadPromise=i.then(l=>(t.mediaKeySessionContext=l,r))).catch(l=>{throw t.keyLoadPromise=null,"data"in l&&(l.data.frag=n),l})}return Promise.resolve(r)}loadKeyHTTP(t,n){const r=this.config,a=r.loader,i=new a(r);return n.keyLoader=t.loader=i,t.keyLoadPromise=new Promise((l,o)=>{const c={keyInfo:t,frag:n,responseType:"arraybuffer",url:t.decryptdata.uri},d=r.keyLoadPolicy.default,u={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(m,p,f,y)=>{const{frag:v,keyInfo:g}=f,b=pUe(g.decryptdata);if(!v.decryptdata||g!==this.keyIdToKeyInfo[b])return o(this.createKeyLoadError(v,vr.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),y));g.decryptdata.key=v.decryptdata.key=new Uint8Array(m.data),v.keyLoader=null,g.loader=null,l({frag:v,keyInfo:g})},onError:(m,p,f,y)=>{this.resetLoader(p),o(this.createKeyLoadError(n,vr.KEY_LOAD_ERROR,new Error(`HTTP Error ${m.code} loading key ${m.text}`),f,Fh({url:c.url,data:void 0},m)))},onTimeout:(m,p,f)=>{this.resetLoader(p),o(this.createKeyLoadError(n,vr.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),f))},onAbort:(m,p,f)=>{this.resetLoader(p),o(this.createKeyLoadError(n,vr.INTERNAL_ABORTED,new Error("key loading aborted"),f))}};i.load(c,u,h)})}resetLoader(t){const{frag:n,keyInfo:r,url:a}=t,i=r.loader;n.keyLoader===i&&(n.keyLoader=null,r.loader=null);const l=pUe(r.decryptdata)||a;delete this.keyIdToKeyInfo[l],i&&i.destroy()}}function pUe(s){if(s.keyFormat!==uv.FAIRPLAY){const t=s.keyId;if(t)return lv(t)}return s.uri}function U3t(s){const{type:t}=s;switch(t){case Ad.AUDIO_TRACK:return mo.AUDIO;case Ad.SUBTITLE_TRACK:return mo.SUBTITLE;default:return mo.MAIN}}function fUe(s,t){let n=s.url;return(n===void 0||n.indexOf("data:")===0)&&(n=t.url),n}class dpr{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(Rt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Rt.LEVEL_LOADING,this.onLevelLoading,this),t.on(Rt.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(Rt.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.on(Rt.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:t}=this;t.off(Rt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Rt.LEVEL_LOADING,this.onLevelLoading,this),t.off(Rt.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(Rt.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.off(Rt.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:Ad.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:Ad.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:Ad.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:Ad.SUBTITLE_TRACK,url:i,deliveryDirectives:l,levelOrTrack:o})}onLevelsUpdated(t,n){const r=this.loaders[Ad.LEVEL];if(r){const a=r.context;a&&!n.levels.some(i=>i===a.levelOrTrack)&&(r.abort(),delete this.loaders[Ad.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===Ad.MANIFEST?i=r.manifestLoadPolicy.default:i=pm({},r.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),a=this.createInternalLoader(t),Wi((n=t.deliveryDirectives)==null?void 0:n.part)){let d;if(t.type===Ad.LEVEL&&t.level!==null?d=this.hls.levels[t.level].details:t.type===Ad.AUDIO_TRACK&&t.id!==null?d=this.hls.audioTracks[t.id].details:t.type===Ad.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=pm({},i,{maxTimeToFirstByteMs:Math.min(m,i.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(m,i.maxTimeToFirstByteMs)})}}}const l=i.errorRetry||i.timeoutRetry||{},o={loadPolicy:i,timeout:i.maxLoadTimeMs,maxRetry:l.maxNumRetry||0,retryDelay:l.retryDelayMs||0,maxRetryDelay:l.maxRetryDelayMs||0},c={onSuccess:(d,u,h,m)=>{const p=this.getInternalLoader(h);this.resetInternalLoader(h.type);const f=d.data;u.parsing.start=performance.now(),O4.isMediaPlaylist(f)||h.type!==Ad.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=fUe(t,r),c=O4.parseMasterPlaylist(l,o);if(c.playlistParsingError){n.parsing.end=performance.now(),this.handleManifestParsingError(t,r,c.playlistParsingError,a,n);return}const{contentSteering:d,levels:u,sessionData:h,sessionKeys:m,startTimeOffset:p,variableList:f}=c;this.variableList=f,u.forEach(b=>{const{unknownCodecs:j}=b;if(j){const{preferManagedMediaSource:S}=this.hls.config;let{audioCodec:C,videoCodec:E}=b;for(let P=j.length;P--;){const M=j[P];Use(M,"audio",S)?(b.audioCodec=C=C?`${C},${M}`:M,zG.audio[C.substring(0,4)]=2,j.splice(P,1)):Use(M,"video",S)&&(b.videoCodec=E=E?`${E},${M}`:M,zG.video[E.substring(0,4)]=2,j.splice(P,1))}}});const{AUDIO:y=[],SUBTITLES:v,"CLOSED-CAPTIONS":g}=O4.parseMasterPlaylistMedia(l,o,c);y.length&&!y.some(j=>!j.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"),y.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new kf({}),bitrate:0,url:""})),i.trigger(Rt.MANIFEST_LOADED,{levels:u,audioTracks:y,subtitles:v,captions:g,contentSteering:d,url:o,stats:n,networkDetails:a,sessionData:h,sessionKeys:m,startTimeOffset:p,variableList:f})}handleTrackOrLevelPlaylist(t,n,r,a,i){const l=this.hls,{id:o,level:c,type:d}=r,u=fUe(t,r),h=Wi(c)?c:Wi(o)?o:0,m=U3t(r),p=O4.parseLevelPlaylist(t.data,u,h,m,0,this.variableList);if(d===Ad.MANIFEST){const f={attrs:new kf({}),bitrate:0,details:p,name:"",url:u};p.requestScheduled=n.loading.start+sis(p,0),l.trigger(Rt.MANIFEST_LOADED,{levels:[f],audioTracks:[],url:u,stats:n,networkDetails:a,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}n.parsing.end=performance.now(),r.levelDetails=p,this.handlePlaylistLoaded(p,t,n,r,a,i)}handleManifestParsingError(t,n,r,a,i){this.hls.trigger(Rt.ERROR,{type:Lo.NETWORK_ERROR,details:vr.MANIFEST_PARSING_ERROR,fatal:n.type===Ad.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===Ad.LEVEL?l+=`: ${t.level} id: ${t.id}`:(t.type===Ad.AUDIO_TRACK||t.type===Ad.SUBTITLE_TRACK)&&(l+=` id: ${t.id} group-id: "${t.groupId}"`);const o=new Error(l);this.hls.logger.warn(`[playlist-loader]: ${l}`);let c=vr.UNKNOWN,d=!1;const u=this.getInternalLoader(t);switch(t.type){case Ad.MANIFEST:c=r?vr.MANIFEST_LOAD_TIMEOUT:vr.MANIFEST_LOAD_ERROR,d=!0;break;case Ad.LEVEL:c=r?vr.LEVEL_LOAD_TIMEOUT:vr.LEVEL_LOAD_ERROR,d=!1;break;case Ad.AUDIO_TRACK:c=r?vr.AUDIO_TRACK_LOAD_TIMEOUT:vr.AUDIO_TRACK_LOAD_ERROR,d=!1;break;case Ad.SUBTITLE_TRACK:c=r?vr.SUBTITLE_TRACK_LOAD_TIMEOUT:vr.SUBTITLE_LOAD_ERROR,d=!1;break}u&&this.resetInternalLoader(t.type);const h={type:Lo.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=Fh({url:m,data:void 0},a)}this.hls.trigger(Rt.ERROR,h)}handlePlaylistLoaded(t,n,r,a,i,l){const o=this.hls,{type:c,level:d,levelOrTrack:u,id:h,groupId:m,deliveryDirectives:p}=a,f=fUe(n,a),y=U3t(a);let v=typeof a.level=="number"&&y===mo.MAIN?d:void 0;const g=t.playlistParsingError;if(g){if(this.hls.logger.warn(`${g} ${t.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(Rt.ERROR,{type:Lo.NETWORK_ERROR,details:vr.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:g,reason:g.message,response:n,context:a,level:v,parent:y,networkDetails:i,stats:r});return}t.playlistParsingError=null}if(!t.fragments.length){const b=t.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(Rt.ERROR,{type:Lo.NETWORK_ERROR,details:vr.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:b,reason:b.message,response:n,context:a,level:v,parent:y,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 Ad.MANIFEST:case Ad.LEVEL:if(v){if(!u)v=0;else if(u!==o.levels[v]){const b=o.levels.indexOf(u);b>-1&&(v=b)}}o.trigger(Rt.LEVEL_LOADED,{details:t,levelInfo:u||o.levels[0],level:v||0,id:h||0,stats:r,networkDetails:i,deliveryDirectives:p,withoutMultiVariant:c===Ad.MANIFEST});break;case Ad.AUDIO_TRACK:o.trigger(Rt.AUDIO_TRACK_LOADED,{details:t,track:u,id:h||0,groupId:m||"",stats:r,networkDetails:i,deliveryDirectives:p});break;case Ad.SUBTITLE_TRACK:o.trigger(Rt.SUBTITLE_TRACK_LOADED,{details:t,track:u,id:h||0,groupId:m||"",stats:r,networkDetails:i,deliveryDirectives:p});break}}}class A4{static get version(){return Vse}static isMSESupported(){return tos()}static isSupported(){return apr()}static getMediaSource(){return ZP()}static get Events(){return Rt}static get MetadataSchema(){return Yw}static get ErrorTypes(){return Lo}static get ErrorDetails(){return vr}static get DefaultConfig(){return A4.defaultConfig?A4.defaultConfig:Wmr}static set DefaultConfig(t){A4.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 _it,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=xcr(t.debug||!1,"Hls instance",t.assetPlayerId),r=this.config=Ymr(A4.DefaultConfig,t,n);this.userConfig=t,r.progressive&&Zmr(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 udr(this),m=r.interstitialsController,p=m?this.interstitialsController=new m(this,A4):null,f=this.bufferController=new i(this,h),y=this.capLevelController=new l(this),v=new c(this),g=new dpr(this),b=r.contentSteeringController,j=b?new b(this):null,S=this.levelController=new rpr(this,j),C=new spr(this),E=new cpr(this.config,this.logger),P=this.streamController=new lpr(this,h,E),M=this.gapController=new epr(this,h);y.setStreamController(P),v.setStreamController(P);const I=[g,S,P];p&&I.splice(1,0,p),j&&I.splice(1,0,j),this.networkControllers=I;const D=[u,f,M,y,v,C,h];this.audioTrackController=this.createController(r.audioTrackController,I);const O=r.audioStreamController;O&&I.push(this.audioStreamController=new O(this,h,E)),this.subtitleTrackController=this.createController(r.subtitleTrackController,I);const V=r.subtitleStreamController;V&&I.push(this.subtititleStreamController=new V(this,h,E)),this.createController(r.timelineController,D),E.emeController=this.emeController=this.createController(r.emeController,D),this.cmcdController=this.createController(r.cmcdController,D),this.latencyController=this.createController(npr,D),this.coreComponents=D,I.push(d);const G=d.onErrorOut;typeof G=="function"&&this.on(Rt.ERROR,G,d),this.on(Rt.MANIFEST_LOADED,g.onManifestLoaded,g)}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===Rt.ERROR;this.trigger(Rt.ERROR,{type:Lo.OTHER_ERROR,details:vr.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(Rt.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(Rt.ERROR,{type:Lo.OTHER_ERROR,details:vr.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(Rt.MEDIA_ATTACHING,a)}detachMedia(){this.logger.log("detachMedia"),this.trigger(Rt.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const t=this.bufferController.transferMedia();return this.trigger(Rt.MEDIA_DETACHING,{transferMedia:t}),t}loadSource(t){this.stopLoad();const n=this.media,r=this._url,a=this._url=dit.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(Rt.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={[mo.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(t[mo.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(t[mo.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=emr()),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){Ycr(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=Uas(n);return zas(t,r,navigator.mediaCapabilities)}}A4.defaultConfig=void 0;const upr=/(?:player\.mediadelivery\.net|iframe\.mediadelivery\.net|iframe\.n\.net|video\.bunnycdn\.com|[a-z0-9-]+\.b-cdn\.net)/i;function yq(s){return!!s&&upr.test(s)&&!/\.mp4($|\?)/i.test(s)}function hpr(s){const t=s.match(/\/(?:play|embed)\/(\d+)\/([a-z0-9-]+)/i);return t?{libraryId:t[1],videoId:t[2]}:null}function mpr(s,t){if(!s)return null;const n=hpr(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 ppr(s){const t=s.match(/https:\/\/[^"']+playlist\.m3u8[^"']*/i);return t?t[0].replace(/&/g,"&").replace(/\u0026/g,"&"):null}const vZe=_.forwardRef(function({sourceUrl:t,thumbnailUrl:n,autoPlay:r,muted:a,loop:i,playsInline:l=!0,...o},c){const d=_.useRef(null),[u,h]=_.useState(null),m=_.useMemo(()=>mpr(t,{autoplay:!!r,muted:!!a,loop:!!i}),[t,r,a,i]);_.useEffect(()=>{let f=!1;if(!t){h(null);return}if(!yq(t)){h(t);return}if(!m){h(null);return}return h(null),fetch(m).then(async y=>{if(!y.ok)throw new Error(`Failed to load Bunny embed (${y.status})`);const v=await y.text();return ppr(v)}).then(y=>{f||h(y)}).catch(()=>{f||h(null)}),()=>{f=!0}},[m,t]),_.useEffect(()=>{const f=d.current;if(!f||!u)return;let y=null;const v=()=>{if(!r)return;const b=f.play();b&&b.catch(()=>{})};if(f.muted=!!a,f.loop=!!i,u.endsWith(".m3u8")){if(f.canPlayType("application/vnd.apple.mpegurl")){f.src=u;const b=()=>v();return f.addEventListener("loadedmetadata",b),()=>{f.removeEventListener("loadedmetadata",b),f.removeAttribute("src"),f.load()}}return A4.isSupported()?(y=new A4({enableWorker:!0,lowLatencyMode:!0}),y.loadSource(u),y.attachMedia(f),y.on(A4.Events.MANIFEST_PARSED,v),()=>{y==null||y.destroy(),f.removeAttribute("src"),f.load()}):void 0}f.src=u;const g=()=>v();return f.addEventListener("loadedmetadata",g),()=>{f.removeEventListener("loadedmetadata",g),f.removeAttribute("src"),f.load()}},[r,i,a,u]),_.useEffect(()=>{const f=d.current;if(f){if(f.muted=!!a,f.loop=!!i,r&&u){const y=f.play();y&&y.catch(()=>{});return}f.pause()}},[r,i,a,u]);const p=f=>{if(d.current=f,typeof c=="function"){c(f);return}c&&(c.current=f)};return e.jsx("video",{ref:p,poster:n||void 0,autoPlay:r,muted:a,loop:i,playsInline:l,preload:"metadata",...o})}),fpr={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 xpr(){try{let s=localStorage.getItem("vg_visitor_token");return s||(s=crypto.randomUUID(),localStorage.setItem("vg_visitor_token",s)),s}catch{return null}}function q3t(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 Iit({config:s,appSlug:t="video_greeter",preview:n=!1,embedded:r=!1}){const[a,i]=_.useState(!1),[l,o]=_.useState(!1),[c,d]=_.useState(!0),[u,h]=_.useState(!1),[m,p]=_.useState("portrait"),[f,y]=_.useState(!1),[v,g]=_.useState(!1),[b,j]=_.useState({name:"",email:"",phone:""}),[S,C]=_.useState(()=>({width:typeof window<"u"?window.innerWidth:1280,height:typeof window<"u"?window.innerHeight:720})),E=_.useRef(null),P=_.useRef(null),M=_.useRef(!1),I=async(Ne,Ye)=>{if(!n)try{await q.from("widget_events").insert({user_id:s.user_id,app_slug:t,event_type:Ne,visitor_token:xpr(),page_url:typeof window<"u"?window.location.href:null,metadata:Ye||{}})}catch{}};_.useEffect(()=>{if(u)return;const Ne=typeof window<"u"?window.location.pathname:"/",Ye=s.targeting||{mode:"all"};if(Ye.mode==="include"&&!q3t(Ye.include,Ne)||Ye.mode==="exclude"&&q3t(Ye.exclude,Ne))return;const Ve=s.trigger||{type:"immediate"};if(Ve.type==="immediate"||n){i(!0);return}if(Ve.type==="delay"){const qe=(Ve.value||3)*1e3,Qe=setTimeout(()=>i(!0),qe);return()=>clearTimeout(Qe)}if(Ve.type==="scroll"){const qe=(Ve.value||25)/100,Qe=()=>{(window.scrollY+window.innerHeight)/document.documentElement.scrollHeight>=qe&&(i(!0),window.removeEventListener("scroll",Qe))};return window.addEventListener("scroll",Qe,{passive:!0}),()=>window.removeEventListener("scroll",Qe)}if(Ve.type==="exit_intent"){const qe=Qe=>{Qe.clientY<=0&&i(!0)};return document.addEventListener("mouseleave",qe),()=>document.removeEventListener("mouseleave",qe)}},[u,s.targeting,s.trigger,n]),_.useEffect(()=>{a&&!M.current&&(M.current=!0,I("impression"))},[a]),_.useEffect(()=>{if(l&&P.current&&!yq(s.video_url)){P.current.currentTime=0,P.current.muted=!1,d(!1);const Ne=P.current.play();Ne&&Ne.catch(()=>{})}else l&&yq(s.video_url)&&d(!1)},[l,s.video_url]),_.useEffect(()=>{if(!s.thumbnail_url)return;let Ne=!1;const Ye=new Image;return Ye.onload=()=>{Ne||p(Ye.naturalWidth>Ye.naturalHeight?"landscape":"portrait")},Ye.src=s.thumbnail_url,()=>{Ne=!0}},[s.thumbnail_url]),_.useEffect(()=>{const Ne=()=>{C({width:window.innerWidth,height:window.innerHeight})};return Ne(),window.addEventListener("resize",Ne),()=>window.removeEventListener("resize",Ne)},[]);const D=()=>{o(!0),I("expand")},O=Ne=>{Ne.stopPropagation(),h(!0),o(!1)},V=Ne=>{I("cta_click",{cta_id:Ne.id,label:Ne.label,url:Ne.url})},G=async Ne=>{if(Ne.preventDefault(),n){y(!0);return}if(!(!b.email||!b.name)){g(!0);try{const{error:Ye}=await q.functions.invoke("submit-widget-lead",{body:{user_id:s.user_id,app_slug:t,name:b.name,email:b.email,phone:b.phone||void 0,page_url:window.location.href}});if(Ye)throw Ye;I("lead_capture",{email:b.email}),y(!0)}catch(Ye){console.error("lead submit failed",Ye)}finally{g(!1)}}};if(!a||u||!s.video_url&&!s.video_embed_url)return null;const $=fpr[m][s.size||"md"],H=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",Y=s.shape==="circle"?"rounded-full":"rounded-2xl",Z=n?m==="landscape"?"w-[280px]":"w-[220px]":m==="landscape"?"w-[360px] sm:w-[420px]":"w-[300px] sm:w-[340px]",ne=m==="landscape"?"aspect-video":"aspect-[9/16]",ce=s.agent||{},ie=s.lead_form_fields||["name","email","phone"],te=!!(s.show_socials&&(ce.instagram_url||ce.facebook_url||ce.linkedin_url)),ae=108+(s.ctas||[]).length*48+(s.lead_form_enabled&&!f?72+ie.length*42:0)+(f?40:0)+(te?34:0),le=Math.max(300,S.height-32),be=Math.max(220,S.width-32),me=Math.max(150,le-ae),he=Math.floor(m==="landscape"?me*(16/9):me*(9/16)),pe=m==="landscape"?Math.max(220,Math.min(420,be,he)):Math.max(180,Math.min(340,be,he)),Ce=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":`${Z} 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`,Ae=r?{width:`${pe}px`,maxHeight:"calc(100dvh - 2rem)"}:void 0,Pe=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",Ze=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",Fe=r?"w-full flex items-center justify-center gap-2 px-3 py-2 bg-gray-900 text-white rounded-xl text-sm font-semibold hover:bg-black transition-colors disabled:opacity-60":"w-full flex items-center justify-center gap-2 px-3 py-2.5 bg-gray-900 text-white rounded-xl text-sm font-semibold hover:bg-black transition-colors disabled:opacity-60";return e.jsx("div",{"data-vg-widget":!0,"data-expanded":l?"true":"false",className:`${H} z-[70]`,style:{paddingBottom:"env(safe-area-inset-bottom)"},children:l?e.jsxs("div",{className:Ce,style:Ae,children:[e.jsxs("div",{className:`relative bg-black ${ne}`,children:[yq(s.video_url)?e.jsx(vZe,{ref:P,sourceUrl:s.video_url,thumbnailUrl:s.thumbnail_url,autoPlay:!0,muted:c,loop:!1,className:"w-full h-full object-cover",onLoadedMetadata:Ne=>{const{videoWidth:Ye,videoHeight:Ve}=Ne.currentTarget;Ye&&Ve&&p(Ye>Ve?"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:Ne=>{const{videoWidth:Ye,videoHeight:Ve}=Ne.currentTarget;Ye&&Ve&&p(Ye>Ve?"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(fJ,{className:"w-4 h-4"}):e.jsx(pJ,{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(Qn,{className:"w-4 h-4"})})]}),e.jsxs("div",{className:Pe,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[ce.avatar_url&&e.jsx("img",{src:ce.avatar_url,alt:ce.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:Ze,children:s.greeting_subtitle})]})]}),(s.ctas||[]).length>0&&e.jsx("div",{className:"space-y-2",children:(s.ctas||[]).map(Ne=>{var Ye;return e.jsxs("a",{href:Ne.url,target:(Ye=Ne.url)!=null&&Ye.startsWith("http")?"_blank":void 0,rel:"noopener noreferrer",onClick:()=>V(Ne),className:`flex items-center justify-between gap-2 ${r?"px-3 py-2":"px-3.5 py-2.5"} rounded-xl text-sm font-semibold transition-colors ${Ne.style==="secondary"?"bg-gray-100 text-gray-900 hover:bg-gray-200":"bg-gray-900 text-white hover:bg-gray-800"}`,children:[e.jsx("span",{children:Ne.label}),e.jsx(wr,{className:"w-3.5 h-3.5 opacity-60"})]},Ne.id)})}),s.lead_form_enabled&&!f&&e.jsxs("form",{onSubmit:G,className:"space-y-2 pt-1",children:[ie.includes("name")&&e.jsx("input",{type:"text",placeholder:"Name",required:!0,value:b.name,onChange:Ne=>j({...b,name:Ne.target.value}),className:Se}),ie.includes("email")&&e.jsx("input",{type:"email",placeholder:"Email",required:!0,value:b.email,onChange:Ne=>j({...b,email:Ne.target.value}),className:Se}),ie.includes("phone")&&e.jsx("input",{type:"tel",placeholder:"Phone (optional)",value:b.phone,onChange:Ne=>j({...b,phone:Ne.target.value}),className:Se}),e.jsxs("button",{type:"submit",disabled:v,className:Fe,children:[e.jsx(Or,{className:"w-3.5 h-3.5"}),v?"Sending...":"Send"]})]}),f&&e.jsx("p",{className:"text-sm text-emerald-600 font-medium text-center py-2",children:"Thanks! I'll be in touch shortly."}),s.show_socials&&(ce.instagram_url||ce.facebook_url||ce.linkedin_url)&&e.jsxs("div",{className:"flex items-center justify-center gap-3 pt-2 border-t border-gray-100",children:[ce.instagram_url&&e.jsx("a",{href:ce.instagram_url,target:"_blank",rel:"noopener noreferrer",className:"text-gray-400 hover:text-gray-900",onClick:()=>I("cta_click",{social:"instagram"}),children:e.jsx(Im,{className:"w-4 h-4"})}),ce.facebook_url&&e.jsx("a",{href:ce.facebook_url,target:"_blank",rel:"noopener noreferrer",className:"text-gray-400 hover:text-gray-900",onClick:()=>I("cta_click",{social:"facebook"}),children:e.jsx(tf,{className:"w-4 h-4"})}),ce.linkedin_url&&e.jsx("a",{href:ce.linkedin_url,target:"_blank",rel:"noopener noreferrer",className:"text-gray-400 hover:text-gray-900",onClick:()=>I("cta_click",{social:"linkedin"}),children:e.jsx(dg,{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 ${Y} overflow-hidden shadow-2xl ring-2 ring-white/40 hover:ring-white/80 hover:scale-105 transition-all bg-black`,style:{width:$.w,height:$.h},"aria-label":"Play video greeting",children:[yq(s.video_url)?e.jsx(vZe,{ref:E,sourceUrl:s.video_url,thumbnailUrl:s.thumbnail_url,autoPlay:!0,muted:!0,loop:!0,className:"w-full h-full object-cover pointer-events-none",onLoadedMetadata:Ne=>{const{videoWidth:Ye,videoHeight:Ve}=Ne.currentTarget;Ye&&Ve&&p(Ye>Ve?"landscape":"portrait")}},`collapsed-${s.video_url}-${s.thumbnail_url||"no-thumb"}`):e.jsx("video",{ref:E,src:s.video_url||void 0,poster:s.thumbnail_url||void 0,autoPlay:!0,muted:!0,loop:!0,playsInline:!0,preload:"metadata",className:"w-full h-full object-cover",onLoadedMetadata:Ne=>{const{videoWidth:Ye,videoHeight:Ve}=Ne.currentTarget;Ye&&Ve&&p(Ye>Ve?"landscape":"portrait")}}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/40 via-transparent to-transparent pointer-events-none"}),e.jsx("div",{className:"absolute bottom-2 left-1/2 -translate-x-1/2 w-12 h-12 rounded-full bg-white/95 flex items-center justify-center shadow-lg pointer-events-none",children:e.jsx("svg",{viewBox:"0 0 24 24",className:"w-6 h-6 text-black ml-0.5",fill:"currentColor",children:e.jsx("path",{d:"M8 5v14l11-7z"})})}),e.jsx("span",{className:"absolute top-2 right-2 px-2 py-0.5 text-[10px] font-bold uppercase tracking-wider bg-red-500 text-white rounded-full animate-pulse",children:"Live"})]}),e.jsx("button",{onClick:O,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(Qn,{className:"w-3.5 h-3.5"})})]})})}function Dit({slug:s}){const[t,n]=_.useState(null);return _.useEffect(()=>{if(!s)return;let r=!1;return(async()=>{const{data:a,error:i}=await q.rpc("get_public_video_greeter_config",{_slug:s});!r&&!i&&a&&n(a)})(),()=>{r=!0}},[s]),t?e.jsx(Iit,{config:t}):null}const sos="eip_last_shown",$3t="eip_visitor_token";function gpr(){try{let s=localStorage.getItem($3t);return s||(s=crypto.randomUUID(),localStorage.setItem($3t,s)),s}catch{return}}function ypr(s){try{const t=Number(localStorage.getItem(sos)||0);return t?Date.now()-t>s*24*60*60*1e3:!0}catch{return!0}}function vpr(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 nos({config:s,preview:t=!1,forceOpen:n=!1}){const[r,a]=_.useState(n),[i,l]=_.useState(!1),[o,c]=_.useState(!1),[d,u]=_.useState({name:"",email:"",phone:""}),h=_.useRef(!1),m=_.useRef(!1),p=async(E,P={})=>{if(!t)try{await q.from("widget_events").insert({user_id:s.user_id,app_slug:"exit_intent",event_type:E,visitor_token:gpr(),page_url:window.location.href,metadata:P})}catch{}};_.useEffect(()=>{if(t||!vpr(s.targeting)||!ypr(s.frequency_days))return;const E=/Mobi|Android/i.test(navigator.userAgent),P={low:5,medium:15,high:30}[s.trigger_sensitivity]||15,M=V=>{if(!h.current){h.current=!0,a(!0);try{localStorage.setItem(sos,String(Date.now()))}catch{}p("impression",{reason:V})}},I=V=>{V.clientY<=P&&M("mouse_leave")},D=()=>{s.enable_mobile_back&&E&&M("back_button")};if(s.enable_mobile_back&&E){try{window.history.pushState({eip:!0},"")}catch{}window.addEventListener("popstate",D)}else document.addEventListener("mouseleave",I);let O;return s.enable_time_fallback&&(O=window.setTimeout(()=>M("time_fallback"),Math.max(5,s.time_fallback_seconds)*1e3)),()=>{document.removeEventListener("mouseleave",I),window.removeEventListener("popstate",D),O&&window.clearTimeout(O)}},[s,t]),_.useEffect(()=>{r&&!m.current&&!t&&!h.current&&(m.current=!0)},[r,t]);const f=()=>{a(!1),t||p("close")},y=async E=>{if(E.preventDefault(),t){l(!0);return}if(!(!d.email||!d.name)){c(!0);try{const{error:P}=await q.functions.invoke("submit-widget-lead",{body:{user_id:s.user_id,app_slug:"exit_intent",name:d.name,email:d.email,phone:d.phone||void 0,page_url:window.location.href}});if(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 v=s.form_fields||["name","email"],g=s.agent||{},b=[g.first_name,g.last_name].filter(Boolean).join(" "),j=s.use_agent_photo&&g.avatar_url||s.image_url,S=s.theme_color||"#f97316",C=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:C,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:E=>E.stopPropagation(),children:[e.jsx("div",{className:"h-2 w-full",style:{background:`linear-gradient(90deg, ${S}, ${xUe(S,-25)})`}}),e.jsx("button",{onClick:f,className:"absolute top-3 right-3 z-10 w-8 h-8 rounded-full bg-background/80 backdrop-blur hover:bg-background flex items-center justify-center text-muted-foreground hover:text-foreground transition","aria-label":"Close",children:e.jsx(Qn,{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:[j&&e.jsx("img",{src:j,alt:b||"Agent",className:"w-14 h-14 rounded-full object-cover ring-2 shadow-md",style:{boxShadow:`0 0 0 2px ${S}33`,"--tw-ring-color":S}}),e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-semibold",style:{background:`${S}1A`,color:S},children:[e.jsx(un,{className:"w-3 h-3"}),s.offer_label]})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold tracking-tight leading-tight",children:s.headline}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:s.subheadline})]}),i?e.jsxs("div",{className:"rounded-xl p-5 text-center space-y-2",style:{background:`${S}10`,color:S},children:[e.jsx("div",{className:"text-3xl",children:"🎉"}),e.jsx("p",{className:"text-sm font-medium",style:{color:S},children:s.success_message})]}):s.form_enabled?e.jsxs("form",{onSubmit:y,className:"space-y-2.5",children:[v.includes("name")&&e.jsx("input",{type:"text",placeholder:"Your name",value:d.name,onChange:E=>u({...d,name:E.target.value}),className:"w-full px-4 py-3 text-sm rounded-lg border border-input bg-background focus:outline-none focus:ring-2 transition",style:{"--tw-ring-color":S},required:!0}),v.includes("email")&&e.jsx("input",{type:"email",placeholder:"you@email.com",value:d.email,onChange:E=>u({...d,email:E.target.value}),className:"w-full px-4 py-3 text-sm rounded-lg border border-input bg-background focus:outline-none focus:ring-2 transition",style:{"--tw-ring-color":S},required:!0}),v.includes("phone")&&e.jsx("input",{type:"tel",placeholder:"Phone (optional)",value:d.phone,onChange:E=>u({...d,phone:E.target.value}),className:"w-full px-4 py-3 text-sm rounded-lg border border-input bg-background focus:outline-none focus:ring-2 transition",style:{"--tw-ring-color":S}}),e.jsx("button",{type:"submit",disabled:o,className:"w-full py-3 rounded-lg font-semibold text-white shadow-lg hover:opacity-95 active:scale-[0.99] transition disabled:opacity-60",style:{background:`linear-gradient(135deg, ${S}, ${xUe(S,-20)})`},children:o?"Sending...":s.cta_label}),e.jsx("p",{className:"text-[10px] text-center text-muted-foreground pt-1",children:"We respect your inbox. Unsubscribe anytime."})]}):e.jsx("a",{href:s.cta_url||"#",onClick:()=>p("cta_click",{url:s.cta_url}),className:"block w-full text-center py-3 rounded-lg font-semibold text-white shadow-lg hover:opacity-95 transition",style:{background:`linear-gradient(135deg, ${S}, ${xUe(S,-20)})`},children:s.cta_label}),b&&e.jsxs("p",{className:"text-[11px] text-center text-muted-foreground pt-1",children:["Sent personally by ",b]})]})]})})}function xUe(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 Rit({slug:s}){const[t,n]=_.useState(null);return _.useEffect(()=>{if(!s)return;let r=!1;return(async()=>{const{data:a,error:i}=await q.rpc("get_public_exit_intent_config",{_slug:s});!r&&!i&&a&&n(a)})(),()=>{r=!0}},[s]),t?e.jsx(nos,{config:t}):null}const V3t="lm_dismissed",H3t="lm_visitor_token";function bpr(){try{let s=localStorage.getItem(H3t);return s||(s=crypto.randomUUID(),localStorage.setItem(H3t,s)),s}catch{return}}function _pr(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 Fit({config:s,preview:t=!1}){const[n,r]=_.useState(!1),[a,i]=_.useState(!1),[l,o]=_.useState(!1),[c,d]=_.useState(!1),[u,h]=_.useState({name:"",email:"",phone:""}),m=_.useRef(!1),p=async(j,S={})=>{if(!t)try{await q.from("widget_events").insert({user_id:s.user_id,app_slug:"lead_magnet",event_type:j,visitor_token:bpr(),page_url:window.location.href,metadata:S})}catch{}};_.useEffect(()=>{if(t){r(!0);return}if(!_pr(s.targeting))return;try{if(sessionStorage.getItem(V3t))return}catch{}const j=()=>{m.current||(m.current=!0,r(!0),p("impression"))};if(s.trigger_type==="immediate")j();else if(s.trigger_type==="delay"){const S=window.setTimeout(j,Math.max(0,s.trigger_value)*1e3);return()=>window.clearTimeout(S)}else if(s.trigger_type==="scroll"){const S=()=>{(window.scrollY+window.innerHeight)/document.documentElement.scrollHeight*100>=(s.trigger_value||30)&&j()};return window.addEventListener("scroll",S,{passive:!0}),()=>window.removeEventListener("scroll",S)}},[s,t]);const f=()=>{r(!1);try{sessionStorage.setItem(V3t,"1")}catch{}t||p("close")},y=async j=>{if(j.preventDefault(),t){o(!0);return}if(!(!u.email||!u.name)){d(!0);try{const{error:S}=await q.functions.invoke("submit-widget-lead",{body:{user_id:s.user_id,app_slug:"lead_magnet",name:u.name,email:u.email,phone:u.phone||void 0,page_url:window.location.href}});if(S)throw S;p("lead_capture",{email:u.email}),o(!0),(s.delivery_method==="instant"||s.delivery_method==="both")&&s.download_url&&setTimeout(()=>{const C=document.createElement("a");C.href=s.download_url,C.target="_blank",C.rel="noopener",C.download="",document.body.appendChild(C),C.click(),C.remove()},600)}catch(S){console.error("lead magnet submit failed",S)}finally{d(!1)}}};if(!n)return null;const v=s.theme_color||"#2563eb",g=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, ${v}, ${UZ(v,-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(Vo,{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:v},children:s.download_label}),e.jsx("button",{onClick:f,className:"text-white/80 hover:text-white","aria-label":"Close",children:e.jsx(Qn,{className:"w-4 h-4"})})]})}),a&&b()]});if(!a)return e.jsxs(e.Fragment,{children:[e.jsxs("button",{onClick:()=>{i(!0),p("expand")},className:`${g} 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, ${v}, ${UZ(v,-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(Sx,{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:j=>{j.stopPropagation(),f()},className:"ml-1 w-6 h-6 rounded-full bg-white/20 hover:bg-white/30 flex items-center justify-center text-white","aria-label":"Close",children:e.jsx(Qn,{className:"w-3 h-3"})})]}),a&&b()]});return b();function b(){const j=s.form_fields||["name","email"],S=s.agent||{},C=[S.first_name,S.last_name].filter(Boolean).join(" ");return e.jsx("div",{className:t?"absolute inset-0 flex items-center justify-center p-4 z-20":"fixed inset-0 z-[85] flex items-center justify-center p-4",style:{background:t?"transparent":"rgba(0,0,0,0.6)"},onClick:()=>i(!1),children:e.jsxs("div",{className:"relative w-full max-w-lg bg-background rounded-2xl shadow-2xl overflow-hidden animate-in fade-in zoom-in-95 duration-300",onClick:E=>E.stopPropagation(),children:[e.jsxs("div",{className:"relative h-44 sm:h-52 overflow-hidden",style:{background:`linear-gradient(135deg, ${v}, ${UZ(v,-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(Fr,{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:v},children:[e.jsx(Vo,{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(Qn,{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:`${v}10`},children:[e.jsx(li,{className:"w-8 h-8 mx-auto",style:{color:v}}),e.jsx("p",{className:"text-sm font-medium",style:{color:v},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:v},children:"Click here if download didn't start"})]}):s.form_enabled?e.jsxs("form",{onSubmit:y,className:"space-y-2.5",children:[j.includes("name")&&e.jsx("input",{type:"text",placeholder:"Your name",value:u.name,onChange:E=>h({...u,name:E.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":v},required:!0}),j.includes("email")&&e.jsx("input",{type:"email",placeholder:"you@email.com",value:u.email,onChange:E=>h({...u,email:E.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":v},required:!0}),j.includes("phone")&&e.jsx("input",{type:"tel",placeholder:"Phone (optional)",value:u.phone,onChange:E=>h({...u,phone:E.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":v}}),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, ${v}, ${UZ(v,-20)})`},children:[e.jsx(li,{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, ${v}, ${UZ(v,-20)})`},children:s.download_label}),C&&e.jsxs("p",{className:"text-[11px] text-center text-muted-foreground",children:["Curated by ",C]})]})]})})}}function UZ(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 Oit({slug:s}){const[t,n]=_.useState(null);return _.useEffect(()=>{if(!s)return;let r=!1;return(async()=>{const{data:a,error:i}=await q.rpc("get_public_lead_magnet_config",{_slug:s});!r&&!i&&a&&n(a)})(),()=>{r=!0}},[s]),t?e.jsx(Fit,{config:t}):null}function zit({siteConfig:s,className:t="",iconClassName:n=""}){var i;const r=((i=s==null?void 0:s.themeConfig)==null?void 0:i.socialLinks)||null;if(!r)return null;const a=[{key:"facebook",url:r.facebook,Icon:tf,label:"Facebook"},{key:"instagram",url:r.instagram,Icon:Im,label:"Instagram"},{key:"linkedin",url:r.linkedin,Icon:dg,label:"LinkedIn"},{key:"youtube",url:r.youtube,Icon:f$,label:"YouTube"}].filter(l=>!!l.url);return a.length?e.jsx("div",{className:`flex items-center gap-3 ${t}`,children:a.map(({key:l,url:o,Icon:c,label:d})=>e.jsx("a",{href:o,target:"_blank",rel:"noopener noreferrer","aria-label":d,className:`inline-flex items-center justify-center h-9 w-9 rounded-full border border-current/20 opacity-70 hover:opacity-100 transition-opacity ${n}`,children:e.jsx(c,{className:"h-4 w-4"})},l))}):null}const wpr="7605cc2e-ce21-4f4f-8bb1-4c0f217b1109";function jpr({children:s,siteConfig:t}){var Ne,Ye,Ve,qe,Qe,Ue,Xe,nt,$e;const n=ru(),r=Fn(),[a,i]=_.useState(!1),[l,o]=_.useState(!1),[c,d]=_.useState(!1),[u,h]=_.useState([]),[m,p]=_.useState([]),[f,y]=_.useState([]),[v,g]=_.useState(null),b=_.useRef(null),j=_.useRef(null),{user:S,profile:C,signOut:E}=rDe();lit(t,S==null?void 0:S.id),cit(t,S==null?void 0:S.id);const P=((Ne=t.agent)==null?void 0:Ne.full_name)||"Agent",M=t.siteTitle||`${P} Real Estate`,I=n.pathname==="/search",D=n.pathname==="/",O=t.leadRegistrationMode!=="disabled",V=t.id===wpr;_.useEffect(()=>{(async()=>{const{data:ct}=await q.from("lead_site_city_pages").select("city_name, city_slug").eq("site_id",t.id).eq("is_published",!0).order("sort_order",{ascending:!0});h(ct||[])})()},[t.id]),_.useEffect(()=>{(async()=>{const{data:ct}=await q.from("lead_site_menu_items").select("*").eq("site_id",t.id).order("sort_order",{ascending:!0});y(ct||[]),p((ct||[]).filter(xt=>xt.is_visible!==!1))})()},[t.id]),_.useEffect(()=>{const Ge=ct=>{b.current&&!b.current.contains(ct.target)&&d(!1),j.current&&!j.current.contains(ct.target)&&g(null)};return document.addEventListener("mousedown",Ge),()=>document.removeEventListener("mousedown",Ge)},[]);const G=M9(t),$=t==null?void 0:t.bookingUrl,{data:H}=aDe(G?t.agentId:null),Y=((H==null?void 0:H.length)??0)>0,{data:Z}=rit(t.agentId),ne=((Z==null?void 0:Z.length)??0)>0,ce=G?m.filter(Ge=>{const ct=String(Ge.target_url||"").toLowerCase(),xt=String(Ge.label||"").toLowerCase();return ct!=="/search"&&!ct.startsWith("/search?")&&!xt.includes("search")}):m,ie=G&&Y&&ce.length>0&&!ce.some(Ge=>String(Ge.target_url||"").toLowerCase().startsWith("/listings"))?[...ce,{id:"__my-listings",label:"My Listings",target_url:"/listings",parent_id:null,is_visible:!0}]:ce,te=ie.length>0,ae=[{to:"/",label:"Home"},...G?[]:[{to:"/search",label:"Search"}],...G&&Y?[{to:"/listings",label:"My Listings"}]:[],...ne?[{to:"/sold",label:"Sold"}]:[],{to:"/sell",label:"Sell"},{to:"/blog",label:"Blog"},{to:"/community",label:"Community"},{to:"/about",label:"About"},{to:"/contact",label:"Contact"}],le=ie.filter(Ge=>!Ge.parent_id),be=Ge=>ie.filter(ct=>ct.parent_id===Ge),me=f.filter(Ge=>!Ge.parent_id),he=new Set([...me,...le].filter(Ge=>String(Ge.target_url||"").trim()!=="").map(Ge=>String(Ge.target_url).toLowerCase().replace(/\/+$/,"")||"/")),pe=new Set([...me,...le].map(Ge=>String(Ge.label||"").trim().toLowerCase())),Pe=["/","/search","/about","/contact","/sell","/blog"].some(Ge=>he.has(Ge))?[]:ae.filter(Ge=>!he.has(Ge.to.toLowerCase())&&!pe.has(Ge.label.toLowerCase())),ze=D?"bg-transparent text-white":"bg-white/95 backdrop-blur text-gray-900 border-b border-gray-100 shadow-sm",ke=t.seoMetaTitle||t.siteTitle||`${P} - Real Estate`,Ze=t.seoMetaDescription||t.siteTagline||`Browse homes and listings with ${P}`,Se=t.ogImageUrl||((Ye=t.agent)==null?void 0:Ye.avatar_url)||"",Fe=t.customDomain?`https://${t.customDomain}`:`https://${t.subdomainSlug||""}.thelocalmove.com`;return e.jsxs("div",{className:`flex flex-col ${I?"h-screen overflow-hidden":"min-h-screen"} bg-white`,children:[e.jsx(iit,{siteConfig:t,pagePath:n.pathname}),(!V||n.pathname==="/p/frequently-asked-questions")&&e.jsx(oit,{siteConfig:t}),e.jsxs(ul,{children:[e.jsx("title",{children:ke}),e.jsx("meta",{name:"description",content:Ze}),e.jsx("meta",{property:"og:title",content:ke}),e.jsx("meta",{property:"og:description",content:Ze}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:url",content:Fe+n.pathname}),Se&&e.jsx("meta",{property:"og:image",content:Se}),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:Ze}),Se&&e.jsx("meta",{name:"twitter:image",content:Se}),t.faviconUrl&&e.jsx("link",{rel:"icon",href:t.faviconUrl,type:"image/png"}),e.jsx("link",{rel:"canonical",href:`${Fe}${n.pathname}`}),t.subdomainSlug==="matthogg"&&e.jsx("script",{src:"https://analytics.ahrefs.com/analytics.js","data-key":"kyFjzruyvE0yTdMokzgCBw",async:!0})]}),e.jsxs("header",{className:`${D?"absolute":"sticky"} top-0 left-0 right-0 z-50 transition-all ${ze}`,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(ir,{to:"/",className:"flex items-center gap-3",children:[t.showTeamLogo&&t.teamLogoUrl?e.jsx("img",{src:t.teamLogoUrl,alt:`${M} logo`,className:"h-10 sm:h-12 w-auto max-w-[180px] object-contain"}):(Ve=t.agent)!=null&&Ve.avatar_url?e.jsx("img",{src:t.agent.avatar_url,alt:P,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:M})})]}),e.jsxs("nav",{className:"hidden md:flex items-center gap-1",children:[t.bookingUrl&&!V&&e.jsx(lE,{bookingUrl:t.bookingUrl,label:"Schedule",size:"sm",className:"order-last ml-3",source:"nav"}),Pe.map(Ge=>e.jsx(ir,{to:Ge.to,className:`px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${n.pathname===Ge.to?D?"bg-white/15 text-white":"bg-gray-100 text-gray-900":D?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,children:Ge.label},Ge.to)),te&&le.map(Ge=>{if(Ge.item_type==="dropdown"){const ct=be(Ge.id);return e.jsxs("div",{ref:j,className:"relative",children:[e.jsxs("button",{onClick:()=>g(v===Ge.id?null:Ge.id),className:`flex items-center gap-1 px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${D?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,children:[Ge.label," ",e.jsx(tl,{className:`h-3.5 w-3.5 transition-transform ${v===Ge.id?"rotate-180":""}`})]}),v===Ge.id&&ct.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:ct.map(xt=>e.jsx(uue,{item:xt,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"},xt.id))})]},Ge.id)}return e.jsx(uue,{item:Ge,className:`px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${D?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`},Ge.id)}),u.length>0&&!V&&e.jsxs("div",{ref:b,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-")?D?"bg-white/15 text-white":"bg-gray-100 text-gray-900":D?"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(tl,{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(Ge=>e.jsx("button",{onClick:()=>{r(`/homes-for-sale-in-${Ge.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:Ge.city_name},Ge.city_slug))})]}),!V&&(S?e.jsxs("div",{className:"flex items-center gap-1 ml-2",children:[e.jsxs(ir,{to:"/account",className:`flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium transition-colors ${D?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,children:[e.jsx(Do,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden lg:inline",children:"Saved"})]}),e.jsxs(ir,{to:"/account",className:`flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium transition-colors ${D?"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:((qe=C==null?void 0:C.name)==null?void 0:qe.split(" ")[0])||"Account"})]})]}):O?e.jsx("button",{onClick:()=>o(!0),className:`ml-2 px-4 py-2 rounded-lg text-sm font-medium transition-colors ${D?"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 ${D?"text-white hover:bg-white/10":"text-gray-600 hover:bg-gray-100"}`,children:a?e.jsx(Qn,{className:"h-5 w-5"}):e.jsx(GA,{className:"h-5 w-5"})})]})}),a&&e.jsx("div",{className:`md:hidden border-t ${D?"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&&!V&&e.jsx(lE,{bookingUrl:t.bookingUrl,label:"Schedule a Free Consultation",size:"sm",className:"w-full mb-3",source:"mobile_nav"}),Pe.map(Ge=>e.jsx(ir,{to:Ge.to,onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${n.pathname===Ge.to?D?"bg-white/15 text-white":"bg-gray-100 text-gray-900":D?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`,children:Ge.label},Ge.to)),te&&le.map(Ge=>{if(Ge.item_type==="dropdown"){const ct=be(Ge.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 ${D?"text-white/40":"text-gray-400"}`,children:Ge.label}),ct.map(xt=>e.jsx(uue,{item:xt,onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${D?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`},xt.id))]},Ge.id)}return e.jsx(uue,{item:Ge,onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${D?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`},Ge.id)}),u.length>0&&!V&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:`px-3 pt-3 pb-1 text-xs font-semibold uppercase tracking-wider ${D?"text-white/40":"text-gray-400"}`,children:"Cities"}),u.map(Ge=>e.jsx(ir,{to:`/homes-for-sale-in-${Ge.city_slug}`,onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${n.pathname===`/homes-for-sale-in-${Ge.city_slug}`?D?"bg-white/15 text-white":"bg-gray-100 text-gray-900":D?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`,children:Ge.city_name},Ge.city_slug))]}),!V&&(S?e.jsxs(e.Fragment,{children:[e.jsx(ir,{to:"/account",onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${D?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`,children:"My Account"}),e.jsx("button",{onClick:async()=>{await E(),i(!1)},className:`block w-full text-left px-3 py-2.5 rounded-lg text-sm font-medium ${D?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`,children:"Sign Out"})]}):O?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 ${D?"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}),!I&&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:[((Qe=t.agent)==null?void 0:Qe.avatar_url)&&e.jsx("img",{src:t.agent.avatar_url,alt:P,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:P}),e.jsx("p",{className:"text-sm text-gray-500",children:V?"Personal Real Estate Advisor":((Ue=t.agent)==null?void 0:Ue.title)||"Real Estate Professional"})]})]}),((Xe=t.agent)==null?void 0:Xe.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(_a,{className:"h-3.5 w-3.5"})," ",t.agent.phone]})}),((nt=t.agent)==null?void 0:nt.email)&&e.jsx("p",{className:"text-sm mt-1",children:e.jsxs("a",{href:`mailto:${t.agent.email}`,className:"hover:text-white transition-colors flex items-center gap-2",children:[e.jsx(ln,{className:"h-3.5 w-3.5"})," ",t.agent.email]})}),e.jsx(zit,{siteConfig:t,className:"mt-4"}),V&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-sm mt-4",children:"Helping you find the right real estate agent, wherever you need one."}),e.jsx("p",{className:"text-sm mt-2",children:"Columbia, Missouri"})]})]}),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:[(V?[{to:"/p/how-it-works",label:"How It Works"},{to:"/p/about-tom",label:"About Tom"},{to:"/p/who-i-help",label:"Who I Help"},{to:"/p/frequently-asked-questions",label:"Frequently Asked Questions"},{to:"/p/call-tom-first",label:"Call Tom First"}]:Pe).map(Ge=>e.jsx("li",{children:e.jsx(ir,{to:Ge.to,className:"hover:text-white transition-colors",children:Ge.label})},Ge.to)),$&&!V&&e.jsx("li",{children:e.jsx("a",{href:$,target:"_blank",rel:"noopener noreferrer",className:"hover:text-white transition-colors",children:"Schedule a Call"})})]}),u.length>0&&!V&&e.jsxs(e.Fragment,{children:[e.jsx("h4",{className:"font-semibold text-white mt-8 mb-4 text-sm tracking-wider uppercase",children:"Local Areas"}),e.jsx("ul",{className:"space-y-3 text-sm",children:u.map(Ge=>e.jsx("li",{children:e.jsx(ir,{to:`/homes-for-sale-in-${Ge.city_slug}`,className:"hover:text-white transition-colors",children:Ge.city_name})},Ge.city_slug))})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold text-white mb-4 text-sm tracking-wider uppercase",children:"Get In Touch"}),e.jsx("p",{className:"text-sm text-gray-500 leading-relaxed mb-4",children:V?"Helping you find the right real estate agent, wherever you need one.":G?"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(ir,{to:V?"/p/call-tom-first":"/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:V?"Call Tom First":"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:[P," · ",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()," ",P,". Powered by LevelUp."]})]})]})]})}),!I&&!V&&(($e=t.agent)==null?void 0:$e.avatar_url)&&e.jsx(Npr,{agent:t.agent,bookingUrl:$}),l&&e.jsx(ait,{open:l,mode:"optional",siteConfig:t,onComplete:()=>o(!1),onSkip:()=>o(!1)}),e.jsx(Dit,{slug:t.subdomainSlug}),e.jsx(Rit,{slug:t.subdomainSlug}),!V&&e.jsx(Oit,{slug:t.subdomainSlug})]})}function Npr({agent:s,bookingUrl:t}){var i;const[n,r]=_.useState(!1),a=Fn();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(_a,{className:"h-4 w-4 text-gray-400"}),s.phone]}),s.email&&e.jsxs("a",{href:`mailto:${s.email}`,className:"flex items-center gap-2 w-full px-3 py-2 bg-gray-50 hover:bg-gray-100 rounded-xl text-sm text-gray-700 transition-colors",children:[e.jsx(ln,{className:"h-4 w-4 text-gray-400"}),"Email Me"]}),e.jsx("button",{onClick:()=>{r(!1),a("/contact")},className:"w-full px-3 py-2.5 bg-blue-600 hover:bg-blue-700 text-white text-sm font-semibold rounded-xl transition-colors",children:"Ask a Question"}),t&&e.jsx("a",{href:t,target:"_blank",rel:"noopener noreferrer",className:"block text-center w-full px-3 py-2.5 bg-gray-900 hover:bg-gray-800 text-white text-sm font-semibold rounded-xl transition-colors",children:"Schedule a Call"})]})]}),e.jsx("button",{onClick:()=>r(!1),className:"absolute top-3 right-3 p-1 text-gray-400 hover:text-gray-600 rounded-full hover:bg-gray-100",children:e.jsx(Qn,{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 uue({item:s,className:t,onClick:n}){const r=s.target_url||"#";return/^(https?:)?\/\//i.test(r)||/^(mailto:|tel:)/i.test(r)?e.jsx("a",{href:r,target:"_blank",rel:"noopener noreferrer",className:t,onClick:n,children:s.label}):e.jsx(ir,{to:r,className:t,onClick:n,children:s.label})}const G3t={california:"California DRE License",ca:"California DRE License"};function bZe(s){const t=(s||"").trim();if(!t)return"Real Estate License";const n=t.toLowerCase();return G3t[n]?G3t[n]:`${t.replace(/\b\w/g,a=>a.toUpperCase())} Real Estate License`}function W3t(s){if(s)return s.replace(/^\s*DRE\s*#?\s*/i,"").replace(/^\s*#/,"").trim()||void 0}function kpr({children:s,siteConfig:t}){var ze,ke,Ze,Se,Fe,Ne,Ye,Ve;const n=ru(),r=Fn(),[a,i]=_.useState(!1),[l,o]=_.useState(!1),[c,d]=_.useState(!1),[u,h]=_.useState(!1),[m,p]=_.useState([]),[f,y]=_.useState(!1),v=_.useRef(null),g=_.useRef(null),{user:b,profile:j,signOut:S}=rDe();lit(t,b==null?void 0:b.id),cit(t,b==null?void 0:b.id);const C=((ze=t.agent)==null?void 0:ze.full_name)||"Agent",E=W3t(t.agentLicenseNumber),P=W3t(t.brokerageLicenseNumber),M=t.siteTitle||`${C} Real Estate`,I=qe=>{if(!qe)return qe;const Qe=C.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Ue=new RegExp(`^\\s*${Qe}\\s*[|\\-–—:]\\s*`,"i");return qe.replace(Ue,"").trim()},D=M&&M!==`${C} Real Estate`?M:null,O=D?I(D):null,V=O&&O.toLowerCase()!==C.toLowerCase()?O:null,G=n.pathname==="/search",$=n.pathname==="/",H=t.leadRegistrationMode!=="disabled",Y="#c9a96e",Z=t.bookingUrl;_.useEffect(()=>{const qe=()=>y(window.scrollY>80);return window.addEventListener("scroll",qe,{passive:!0}),()=>window.removeEventListener("scroll",qe)},[]),_.useEffect(()=>{(async()=>{const{data:Qe}=await q.from("lead_site_city_pages").select("city_name, city_slug").eq("site_id",t.id).eq("is_published",!0).order("sort_order",{ascending:!0});p(Qe||[])})()},[t.id]),_.useEffect(()=>{const qe=Qe=>{v.current&&!v.current.contains(Qe.target)&&d(!1),g.current&&!g.current.contains(Qe.target)&&h(!1)};return document.addEventListener("mousedown",qe),()=>document.removeEventListener("mousedown",qe)},[]);const ne=(((ke=t.themeConfig)==null?void 0:ke.focusPages)??[]).filter(qe=>qe==null?void 0:qe.slug).map(qe=>({to:`/${qe.slug}`,label:qe.navLabel||qe.title})),ce=QYt(t)||M9(t),{data:ie}=aDe(ce?t.agentId:null),te=((ie==null?void 0:ie.length)??0)>0,{data:ae}=rit(t.agentId),le=((ae==null?void 0:ae.length)??0)>0,be=[{to:"/",label:"Home"},...ce?te?[{to:"/listings",label:"My Listings"}]:[]:[{to:"/search",label:"Search"}],...le?[{to:"/sold",label:"Sold"}]:[],{to:"/sell",label:"Sell"},{to:"/blog",label:"Blog"},{to:"/community",label:"Community"},{to:"/about",label:"About"},{to:"/contact",label:"Contact"}],me=[...be,...ne],he=t.siteTitle||`${C} - Real Estate`,pe=t.siteTagline||`Browse homes and listings with ${C}`,Ce=t.ogImageUrl||((Ze=t.agent)==null?void 0:Ze.avatar_url)||"",Ae=t.customDomain?`https://${t.customDomain}`:`https://${t.subdomainSlug||""}.thelocalmove.com`,Pe=$?f?"bg-[#0d0b0a]/95 backdrop-blur-lg border-b border-white/5":"bg-transparent":"bg-[#0d0b0a] border-b border-white/5";return e.jsxs("div",{className:`flex flex-col ${G?"h-screen overflow-hidden":"min-h-screen"} bg-[#0d0b0a]`,children:[e.jsx(iit,{siteConfig:t,pagePath:n.pathname}),e.jsx(oit,{siteConfig:t}),e.jsxs(ul,{children:[e.jsx("title",{children:he}),e.jsx("meta",{name:"description",content:pe}),e.jsx("meta",{property:"og:title",content:he}),e.jsx("meta",{property:"og:description",content:pe}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:url",content:Ae+n.pathname}),Ce&&e.jsx("meta",{property:"og:image",content:Ce}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),e.jsx("meta",{name:"twitter:title",content:he}),e.jsx("meta",{name:"twitter:description",content:pe}),Ce&&e.jsx("meta",{name:"twitter:image",content:Ce}),t.faviconUrl&&e.jsx("link",{rel:"icon",href:t.faviconUrl,type:"image/png"}),e.jsx("link",{rel:"canonical",href:`${Ae}${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:`${$?"fixed":"sticky"} top-0 left-0 right-0 z-50 transition-all duration-500 ${Pe}`,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(ir,{to:"/",className:"flex items-center gap-3 shrink-0",children:[t.showTeamLogo&&t.teamLogoUrl&&e.jsx("img",{src:t.teamLogoUrl,alt:`${C} 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:C}),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}),V&&e.jsx("span",{className:"hidden xl:block whitespace-nowrap text-[10px] tracking-[0.18em] uppercase text-white/40",children:V})]})]}),e.jsxs("nav",{className:"hidden lg:flex items-center justify-end gap-0 flex-1 min-w-0",children:[be.map(qe=>e.jsx(ir,{to:qe.to,className:`whitespace-nowrap px-2.5 xl:px-4 py-2 text-xs tracking-[0.15em] uppercase transition-colors duration-300 ${n.pathname===qe.to?"text-white":"text-white/40 hover:text-white"}`,children:qe.label},qe.to)),ne.length>0&&e.jsxs("div",{ref:g,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 ${ne.some(qe=>n.pathname===qe.to)?"text-white":"text-white/40 hover:text-white"}`,children:["Specialty"," ",e.jsx(tl,{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:ne.map(qe=>e.jsx(ir,{to:qe.to,onClick:()=>h(!1),className:`block px-5 py-2.5 text-xs tracking-wider text-white/50 hover:text-white hover:bg-white/5 uppercase transition-colors ${n.pathname===qe.to?"text-white":""}`,children:qe.label},qe.to))})]}),m.length>0&&e.jsxs("div",{ref:v,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(tl,{className:`h-3 w-3 transition-transform ${c?"rotate-180":""}`})]}),c&&e.jsx("div",{className:"absolute top-full right-0 mt-2 w-56 bg-[#1a1715] border border-white/10 py-2 z-50 animate-in fade-in slide-in-from-top-2 duration-150",children:m.map(qe=>e.jsx("button",{onClick:()=>{r(`/homes-for-sale-in-${qe.city_slug}`),d(!1)},className:"w-full text-left px-5 py-2.5 text-xs tracking-wider text-white/50 hover:text-white hover:bg-white/5 uppercase transition-colors",children:qe.city_name},qe.city_slug))})]}),b?e.jsxs("div",{className:"flex items-center gap-1 ml-3",children:[e.jsxs(ir,{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(Do,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden xl:inline",children:"Saved"})]}),e.jsxs(ir,{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:((Se=j==null?void 0:j.name)==null?void 0:Se.split(" ")[0])||"Account"})]})]}):H?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,Z&&e.jsx(lE,{bookingUrl:Z,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(Qn,{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:[Z&&e.jsx(lE,{bookingUrl:Z,label:"Schedule a Free Consultation",size:"sm",className:"w-full mb-3",source:"mobile_nav"}),be.map(qe=>e.jsx(ir,{to:qe.to,onClick:()=>i(!1),className:`block px-3 py-3 text-xs tracking-[0.2em] uppercase transition-colors ${n.pathname===qe.to?"text-white":"text-white/40 hover:text-white"}`,children:qe.label},qe.to)),ne.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:Y},children:"Specialty"}),ne.map(qe=>e.jsx(ir,{to:qe.to,onClick:()=>i(!1),className:`block px-3 py-2.5 text-xs tracking-wider uppercase transition-colors ${n.pathname===qe.to?"text-white":"text-white/40 hover:text-white"}`,children:qe.label},qe.to))]}),m.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-3 pt-4 pb-2 text-[10px] tracking-[0.3em] uppercase",style:{color:Y},children:"Cities"}),m.map(qe=>e.jsx(ir,{to:`/homes-for-sale-in-${qe.city_slug}`,onClick:()=>i(!1),className:"block px-3 py-2.5 text-xs tracking-wider text-white/40 hover:text-white uppercase transition-colors",children:qe.city_name},qe.city_slug))]}),b?e.jsxs(e.Fragment,{children:[e.jsx(ir,{to:"/account",onClick:()=>i(!1),className:"block px-3 py-3 text-xs tracking-[0.2em] uppercase text-white/40 hover:text-white",children:"My Account"}),e.jsx("button",{onClick:async()=>{await S(),i(!1)},className:"block w-full text-left px-3 py-3 text-xs tracking-[0.2em] uppercase text-white/40 hover:text-white",children:"Sign Out"})]}):H?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}),!G&&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:C}),e.jsx("p",{className:"text-white/70 text-xs tracking-[0.15em] uppercase mb-6",children:((Fe=t.agent)==null?void 0:Fe.title)||"Real Estate Professional"}),(E||P)&&e.jsxs("div",{className:"mb-6 p-4 border border-white/10 bg-white/5",children:[E&&e.jsxs("p",{className:"text-sm text-white font-medium tracking-wide",children:[bZe(t.licenseState)," #",E]}),P&&e.jsxs("p",{className:"text-xs text-white/70 tracking-wider uppercase mt-1",children:["Brokerage License #",P]})]}),((Ne=t.agent)==null?void 0:Ne.phone)&&e.jsxs("a",{href:`tel:${t.agent.phone}`,className:"flex items-center gap-3 text-sm text-white/70 hover:text-white transition-colors mb-3",children:[e.jsx(_a,{className:"h-3.5 w-3.5"})," ",t.agent.phone]}),((Ye=t.agent)==null?void 0:Ye.email)&&e.jsxs("a",{href:`mailto:${t.agent.email}`,className:"flex items-center gap-3 text-sm text-white/70 hover:text-white transition-colors",children:[e.jsx(ln,{className:"h-3.5 w-3.5"})," ",t.agent.email]}),e.jsx(zit,{siteConfig:t,className:"mt-6",iconClassName:"border-white/20"})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-xs tracking-[0.3em] uppercase mb-6 text-white",style:{color:Y},children:"Quick Links"}),e.jsxs("ul",{className:"space-y-3",children:[me.map(qe=>e.jsx("li",{children:e.jsx(ir,{to:qe.to,className:"text-xs tracking-wider uppercase text-white/70 hover:text-white transition-colors",children:qe.label})},qe.to)),Z&&e.jsx("li",{children:e.jsx("a",{href:Z,target:"_blank",rel:"noopener noreferrer",className:"text-xs tracking-wider uppercase transition-colors hover:opacity-80",style:{color:xK},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:Y},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:[Z&&e.jsx(lE,{bookingUrl:Z,label:"Schedule a Free Consultation",size:"sm",source:"footer"}),e.jsx(ir,{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:[C," · ",t.brokerageLegalName]}),E&&e.jsxs("span",{children:[bZe(t.licenseState)," #",E]}),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()," ",C,". Powered by LevelUp."]})]})]})]})}),!G&&((Ve=t.agent)==null?void 0:Ve.avatar_url)&&e.jsx(Spr,{agent:t.agent,agentLicense:E,siteConfig:t,accentColor:Y}),l&&e.jsx(ait,{open:l,mode:"optional",siteConfig:t,onComplete:()=>o(!1),onSkip:()=>o(!1),theme:"luxury",accentColor:Y}),e.jsx(Dit,{slug:t.subdomainSlug}),e.jsx(Rit,{slug:t.subdomainSlug}),e.jsx(Oit,{slug:t.subdomainSlug})]})}function Spr({agent:s,agentLicense:t,siteConfig:n,accentColor:r}){var o;const[a,i]=_.useState(!1),l=Fn();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:bZe(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(_a,{className:"h-3.5 w-3.5"})," ",s.phone]}),s.email&&e.jsxs("a",{href:`mailto:${s.email}`,className:"flex items-center gap-2 w-full px-3 py-2.5 bg-white/5 hover:bg-white/10 text-xs text-white/70 hover:text-white transition-colors tracking-wider",children:[e.jsx(ln,{className:"h-3.5 w-3.5"})," Email Me"]}),e.jsx("button",{onClick:()=>{i(!1),l("/contact")},className:"w-full px-3 py-2.5 text-xs tracking-[0.2em] uppercase text-black hover:opacity-90 transition-colors",style:{backgroundColor:r},children:"Send a Message"})]})]}),e.jsx("button",{onClick:()=>i(!1),className:"absolute top-3 right-3 p-1 text-white/20 hover:text-white/50",children:e.jsx(Qn,{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 qZ="#2c1810",M5="#b8860b";function Cpr({children:s,siteConfig:t}){var $,H,Y;const n=ru();Fn();const[r,a]=_.useState(!1),[i,l]=_.useState(!1),[o,c]=_.useState(!1),[d,u]=_.useState([]),[h,m]=_.useState(!1),p=_.useRef(null),{user:f,profile:y,signOut:v}=rDe();lit(t,f==null?void 0:f.id),cit(t,f==null?void 0:f.id);const g=(($=t.agent)==null?void 0:$.full_name)||"Agent",b=t.siteTitle||`${g} Land & Ranch`,j=n.pathname==="/",S=t.leadRegistrationMode!=="disabled",C=M9(t);_.useEffect(()=>{const Z=()=>m(window.scrollY>80);return window.addEventListener("scroll",Z,{passive:!0}),()=>window.removeEventListener("scroll",Z)},[]),_.useEffect(()=>{(async()=>{const{data:ne}=await q.from("lead_site_city_pages").select("city_name, city_slug").eq("site_id",t.id).eq("is_published",!0).order("sort_order");ne&&u(ne)})()},[t.id]),_.useEffect(()=>{const Z=ne=>{p.current&&!p.current.contains(ne.target)&&c(!1)};return document.addEventListener("mousedown",Z),()=>document.removeEventListener("mousedown",Z)},[]);const{data:E}=rit(t.agentId),{data:P}=aDe(t.agentId),M=((E==null?void 0:E.length)??0)>0,I=((P==null?void 0:P.length)??0)>0,D=[{label:"Home",path:"/"},...C?[]:[{label:"Search Properties",path:"/search"}],...C&&I?[{label:"My Listings",path:"/listings"}]:[],...M?[{label:"Sold",path:"/sold"}]:[],{label:"About",path:"/about"},{label:"Blog",path:"/blog"},{label:"Contact",path:"/contact"}],O=h||!j?"bg-white/95 backdrop-blur-md shadow-sm":"bg-transparent",V=h||!j?qZ:"#ffffff",G=t.customDomain?`https://${t.customDomain}`:`https://${t.subdomainSlug||""}.thelocalmove.com`;return e.jsxs("div",{className:"min-h-screen",style:{fontFamily:"'Lora', Georgia, serif"},children:[e.jsxs(ul,{children:[e.jsx("title",{children:b}),e.jsx("meta",{property:"og:url",content:G+n.pathname}),e.jsx("link",{rel:"canonical",href:`${G}${n.pathname}`}),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(iit,{siteConfig:t}),e.jsx(oit,{siteConfig:t}),e.jsxs("header",{className:`fixed top-0 left-0 right-0 z-50 transition-all duration-300 ${O}`,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(ir,{to:"/",className:"flex items-center gap-2.5",children:[e.jsx(WO,{className:"w-7 h-7",style:{color:M5}}),e.jsx("span",{className:"text-lg font-bold tracking-wide",style:{color:V,fontFamily:"'Playfair Display', Georgia, serif"},children:b})]}),e.jsxs("nav",{className:"hidden md:flex items-center gap-1",children:[D.map(Z=>e.jsx(ir,{to:Z.path,className:"px-4 py-2 text-sm font-medium tracking-wide uppercase transition-colors hover:opacity-80",style:{color:n.pathname===Z.path?M5:V},children:Z.label},Z.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:V},children:["Area Guides ",e.jsx(tl,{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(Z=>e.jsx(ir,{to:`/homes-for-sale-in-${Z.city_slug}`,className:"block px-4 py-2.5 text-sm hover:bg-gray-50 transition-colors",style:{color:qZ},onClick:()=>c(!1),children:Z.city_name},Z.city_slug))})]}),f?e.jsx("div",{className:"flex items-center gap-2 ml-3",children:e.jsxs(ir,{to:"/account",className:"px-4 py-2 text-sm font-medium rounded-full border-2 transition-all hover:scale-105",style:{borderColor:M5,color:V},children:[e.jsx(Fo,{className:"w-4 h-4 inline mr-1.5"}),(y==null?void 0:y.name)||"Account"]})}):S?e.jsx("button",{onClick:()=>l(!0),className:"ml-3 px-5 py-2.5 text-sm font-semibold text-white rounded-full hover:shadow-lg transition-all hover:scale-105",style:{backgroundColor:M5},children:"Sign In"}):null]}),e.jsx("button",{onClick:()=>a(!r),className:"md:hidden p-2",style:{color:V},children:r?e.jsx(Qn,{className:"w-6 h-6"}):e.jsx(GA,{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:[D.map(Z=>e.jsx(ir,{to:Z.path,className:"block px-4 py-3 text-base font-medium rounded-lg hover:bg-gray-50 transition-colors",style:{color:n.pathname===Z.path?M5:qZ},onClick:()=>a(!1),children:Z.label},Z.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:"Area Guides"}),d.map(Z=>e.jsx(ir,{to:`/homes-for-sale-in-${Z.city_slug}`,className:"block px-4 py-2.5 text-sm rounded-lg hover:bg-gray-50",style:{color:qZ},onClick:()=>a(!1),children:Z.city_name},Z.city_slug))]}),!f&&S&&e.jsx("button",{onClick:()=>{l(!0),a(!1)},className:"w-full mt-3 px-5 py-3 text-white font-semibold rounded-full",style:{backgroundColor:M5},children:"Sign In"})]})})]}),e.jsx("main",{children:s}),e.jsx("footer",{className:"py-16 px-4",style:{backgroundColor:qZ},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(WO,{className:"w-6 h-6",style:{color:M5}}),e.jsx("span",{className:"text-lg font-bold text-white",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:b})]}),e.jsx("p",{className:"text-white/60 text-sm leading-relaxed",children:"Personal guidance for buying and selling land, homes, and rural property."}),e.jsx(zit,{siteConfig:t,className:"mt-5",iconClassName:"border-white/20 text-white"})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-white font-semibold mb-4 text-sm tracking-wider uppercase",children:"Quick Links"}),e.jsx("div",{className:"space-y-2",children:D.map(Z=>e.jsx(ir,{to:Z.path,className:"block text-white/60 hover:text-white text-sm transition-colors",children:Z.label},Z.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:[((H=t.agent)==null?void 0:H.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(_a,{className:"w-4 h-4",style:{color:M5}}),t.agent.phone]}),((Y=t.agent)==null?void 0:Y.email)&&e.jsxs("a",{href:`mailto:${t.agent.email}`,className:"flex items-center gap-2 text-white/60 hover:text-white text-sm transition-colors",children:[e.jsx(ln,{className:"w-4 h-4",style:{color:M5}}),t.agent.email]})]})]})]}),e.jsxs("div",{className:"mt-12 pt-8 border-t border-white/10 flex items-center justify-between",children:[e.jsxs("p",{className:"text-white/40 text-xs",children:["© ",new Date().getFullYear()," ",b,". All rights reserved."]}),e.jsx("div",{className:"h-px w-16",style:{backgroundColor:M5}})]})]})}),i&&e.jsx(ait,{open:i,mode:t.leadRegistrationMode==="required"?"required":"optional",siteConfig:t,onSkip:()=>l(!1),onComplete:()=>l(!1)}),e.jsx(Dit,{slug:t.subdomainSlug}),e.jsx(Rit,{slug:t.subdomainSlug}),e.jsx(Oit,{slug:t.subdomainSlug})]})}function K3t(){const{pathname:s}=ru();return _.useEffect(()=>{window.scrollTo({top:0,left:0,behavior:"auto"})},[s]),null}const Apr=_.lazy(()=>za(()=>import("./LeadSiteHome-D1Ps7r6E.js"),__vite__mapDeps([0,1,2,3,4,5]))),Epr=_.lazy(()=>za(()=>import("./LeadSiteLuxuryHome-DiYdO3Un.js"),__vite__mapDeps([6,2,3,4,7,8]))),Tpr=_.lazy(()=>za(()=>import("./LeadSiteLandRanchHome-BF86E2tB.js"),__vite__mapDeps([9,1,2,3,4,5]))),Y3t=_.lazy(()=>za(()=>import("./LeadSiteSearch-CItmwr1a.js"),__vite__mapDeps([10,1,11,4,12]))),Mpr=_.lazy(()=>za(()=>import("./LeadSiteLuxurySearch-GycJcAWg.js"),__vite__mapDeps([13,1,11,4,12]))),Z3t=_.lazy(()=>za(()=>import("./LeadSiteListingDetail-03jUD4Zz.js"),__vite__mapDeps([14,15,4,16]))),Ppr=_.lazy(()=>za(()=>import("./LeadSiteLuxuryListingDetail-CBr1v-j5.js"),__vite__mapDeps([17,15,4,16]))),Lpr=_.lazy(()=>za(()=>import("./LeadSiteAbout-Vbs_9Eoo.js"),[])),Ipr=_.lazy(()=>za(()=>import("./LeadSiteLuxuryAbout-CXFYd56h.js"),[])),Dpr=_.lazy(()=>za(()=>import("./LeadSiteContact-CwRZGQZ2.js"),[])),Rpr=_.lazy(()=>za(()=>import("./LeadSiteLuxuryContact-DBOFItm2.js"),[])),Fpr=_.lazy(()=>za(()=>import("./LeadSiteConsumerDashboard-VsYKOr8l.js"),[])),hue=_.lazy(()=>za(()=>import("./LeadSiteBlog-D-8dRWVu.js"),[])),Opr=_.lazy(()=>za(()=>import("./LeadSiteCommunity-BDPo5pyT.js"),[])),zpr=_.lazy(()=>za(()=>import("./LeadSiteSellers-Bfp61Tnl.js"),[])),Bpr=_.lazy(()=>za(()=>import("./LeadSiteCityPage-C5zFJDh0.js"),__vite__mapDeps([18,19,4,12]))),Upr=_.lazy(()=>za(()=>import("./LeadSiteSubdivisionPage-Ab0LmhJH.js"),__vite__mapDeps([20,4]))),qpr=_.lazy(()=>za(()=>import("./LeadSiteCustomPage-DCmDVsuS.js"),[])),$pr=_.lazy(()=>za(()=>import("./LeadSiteFocusPage-m8m5Ijxc.js"),__vite__mapDeps([21,3,4]))),Vpr=_.lazy(()=>za(()=>import("./LeadSiteExchangeListings-mhjTuEDU.js"),[]).then(s=>({default:s.LeadSiteExchangeListingsIndex}))),Hpr=_.lazy(()=>za(()=>import("./LeadSiteExchangeListings-mhjTuEDU.js"),[]).then(s=>({default:s.LeadSiteSoldListingsIndex}))),Gpr=_.lazy(()=>za(()=>import("./LeadSiteExchangeListings-mhjTuEDU.js"),[]).then(s=>({default:s.LeadSiteExchangeListingDetail}))),Wpr=_.lazy(()=>za(()=>import("./OrgSiteLayout-B5-PonSC.js"),[])),Kpr=_.lazy(()=>za(()=>import("./OrgSiteHome-C73w6xbd.js").then(s=>s.O),[])),Ypr=_.lazy(()=>za(()=>import("./OrgSiteAgents-BIaL63kf.js"),__vite__mapDeps([22,23,24]))),Zpr=_.lazy(()=>za(()=>import("./OrgSiteAgents-BIaL63kf.js"),__vite__mapDeps([22,23,24])).then(s=>({default:s.OrgSiteAgentProfile}))),X3t=_.lazy(()=>za(()=>import("./OrgSiteListings-laCxPlL0.js"),__vite__mapDeps([25,23,24]))),Xpr=_.lazy(()=>za(()=>import("./OrgSiteListings-laCxPlL0.js"),__vite__mapDeps([25,23,24])).then(s=>({default:s.OrgSiteListingDetail}))),Qpr=_.lazy(()=>za(()=>import("./OrgSitePages-Cbr99MEL.js"),__vite__mapDeps([24,23])).then(s=>({default:s.OrgSiteAbout}))),Jpr=_.lazy(()=>za(()=>import("./OrgSitePages-Cbr99MEL.js"),__vite__mapDeps([24,23])).then(s=>({default:s.OrgSiteContact}))),efr=_.lazy(()=>za(()=>import("./OrgSitePages-Cbr99MEL.js"),__vite__mapDeps([24,23])).then(s=>({default:s.OrgSiteJoin})));function _Ze(){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 tfr({siteConfig:s}){const{data:t,isLoading:n}=aDe(s.agentId);return n?e.jsx(_Ze,{}):e.jsx(fd,{to:t!=null&&t.length?"/listings":"/contact?interest=Property%20search",replace:!0})}function sfr(){var m;const{siteConfig:s,themeConfig:t,isLoading:n,error:r}=Glr();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."})]})});if(s.ownerType==="brokerage"||s.ownerType==="team"){const p=s.orgTier==="pro";return e.jsxs(jCt,{siteConfig:s,children:[e.jsx(K3t,{}),e.jsx(_.Suspense,{fallback:e.jsx(_Ze,{}),children:e.jsx(Wpr,{siteConfig:s,themeConfig:t??void 0,children:e.jsxs(jH,{children:[e.jsx(Qt,{path:"/",element:e.jsx(Kpr,{siteConfig:s,themeConfig:t??void 0})}),e.jsx(Qt,{path:"/listings",element:e.jsx(X3t,{siteConfig:s,themeConfig:t??void 0})}),e.jsx(Qt,{path:"/sold",element:e.jsx(X3t,{siteConfig:s,themeConfig:t??void 0,sold:!0})}),e.jsx(Qt,{path:"/listings/:slug",element:e.jsx(Xpr,{siteConfig:s,themeConfig:t??void 0})}),e.jsx(Qt,{path:"/agents",element:e.jsx(Ypr,{siteConfig:s,themeConfig:t??void 0})}),e.jsx(Qt,{path:"/agents/:slug",element:e.jsx(Zpr,{siteConfig:s,themeConfig:t??void 0})}),e.jsx(Qt,{path:"/about",element:e.jsx(Qpr,{siteConfig:s,themeConfig:t??void 0})}),e.jsx(Qt,{path:"/contact",element:e.jsx(Jpr,{siteConfig:s,themeConfig:t??void 0})}),e.jsx(Qt,{path:"/join",element:e.jsx(efr,{siteConfig:s,themeConfig:t??void 0})}),e.jsx(Qt,{path:"/blog",element:e.jsx(hue,{siteConfig:s,isLuxury:!1})}),e.jsx(Qt,{path:"/blog/:slug",element:e.jsx(hue,{siteConfig:s,isLuxury:!1})}),e.jsx(Qt,{path:"/search",element:p?e.jsx(Y3t,{siteConfig:s}):e.jsx(fd,{to:"/listings",replace:!0})}),e.jsx(Qt,{path:"/listing/:mlsNumber",element:p?e.jsx(Z3t,{siteConfig:s}):e.jsx(fd,{to:"/listings",replace:!0})}),e.jsx(Qt,{path:"/*",element:e.jsx(Q3t,{siteConfig:s,referralMode:!p})})]})})})]})}const a=(t==null?void 0:t.themeTier)==="luxury",i=(t==null?void 0:t.themeTier)==="land-ranch",l=i?Cpr:a?kpr:jpr,o=QYt(s),c=o||M9(s,t),d=s.id==="7605cc2e-ce21-4f4f-8bb1-4c0f217b1109",u=!o&&M9(s,t),h=i?e.jsx(Tpr,{siteConfig:s,themeConfig:t??void 0}):a?e.jsx(Epr,{siteConfig:s,themeConfig:t??void 0}):e.jsx(Apr,{siteConfig:s,themeConfig:t??void 0});return e.jsxs(jCt,{siteConfig:s,children:[e.jsx(K3t,{}),e.jsxs(l,{siteConfig:s,children:[e.jsx(_.Suspense,{fallback:e.jsx(_Ze,{}),children:e.jsxs(jH,{children:[e.jsx(Qt,{path:"/",element:h}),e.jsx(Qt,{path:"/listings",element:e.jsx(Vpr,{siteConfig:s})}),e.jsx(Qt,{path:"/sold",element:e.jsx(Hpr,{siteConfig:s})}),e.jsx(Qt,{path:"/listings/:slug",element:e.jsx(Gpr,{siteConfig:s})}),e.jsx(Qt,{path:"/search",element:c?e.jsx(tfr,{siteConfig:s}):a?e.jsx(Mpr,{siteConfig:s}):e.jsx(Y3t,{siteConfig:s})}),e.jsx(Qt,{path:"/listing/:mlsNumber",element:c?e.jsx(fd,{to:"/contact?interest=Property%20details",replace:!0}):a?e.jsx(Ppr,{siteConfig:s}):e.jsx(Z3t,{siteConfig:s})}),e.jsx(Qt,{path:"/about",element:a?e.jsx(Ipr,{siteConfig:s}):e.jsx(Lpr,{siteConfig:s})}),e.jsx(Qt,{path:"/contact",element:a?e.jsx(Rpr,{siteConfig:s}):e.jsx(Dpr,{siteConfig:s})}),e.jsx(Qt,{path:"/account",element:e.jsx(Fpr,{siteConfig:s})}),e.jsx(Qt,{path:"/blog",element:e.jsx(hue,{siteConfig:s,isLuxury:a})}),e.jsx(Qt,{path:"/blog/:slug",element:e.jsx(hue,{siteConfig:s,isLuxury:a})}),e.jsx(Qt,{path:"/sell",element:e.jsx(zpr,{siteConfig:s,themeConfig:t??void 0,isLuxury:a})}),e.jsx(Qt,{path:"/community",element:e.jsx(Opr,{siteConfig:s,isLuxury:a})}),e.jsx(Qt,{path:"/schedule",element:e.jsx(Qlr,{bookingUrl:s.bookingUrl,agentName:((m=s.agent)==null?void 0:m.full_name)||"your agent"})}),((t==null?void 0:t.focusPages)??[]).map(p=>e.jsx(Qt,{path:`/${p.slug}`,element:e.jsx($pr,{siteConfig:s,page:p,accentColor:(t==null?void 0:t.accentColor)||s.accentColor||"#c9a96e"})},p.slug)),e.jsx(Qt,{path:"/p/:pageSlug",element:e.jsx(qpr,{siteConfig:s})}),e.jsx(Qt,{path:"/*",element:e.jsx(Q3t,{siteConfig:s,referralMode:u})})]})}),!d&&e.jsx(Xlr,{bookingUrl:s.bookingUrl})]})]})}function Q3t({siteConfig:s,referralMode:t}){const n=ru(),r=n.pathname.match(/^\/homes-in-(.+)$/);if(r)return e.jsx(Upr,{siteConfig:s,subdivisionSlug:r[1]});const a=n.pathname.match(/^\/homes-for-sale-in-(.+)$/);return a?e.jsx(Bpr,{siteConfig:s,citySlugOverride:a[1],referralMode:t}):null}function nfr(){const{user:s,loading:t}=hs(),{data:n,isLoading:r}=at({queryKey:["feature-entitlement","levelup_attract",s==null?void 0:s.id],enabled:!!s,staleTime:5*60*1e3,queryFn:async()=>{const{data:a,error:i}=await q.from("feature_entitlements").select("enabled, expires_at, tier").eq("user_id",s.id).eq("feature_key","levelup_attract").maybeSingle();if(i)throw i;return a?{hasAccess:a.enabled&&(!a.expires_at||new Date(a.expires_at).getTime()>Date.now()),tier:a.tier??null}:{hasAccess:!1,tier:null}}});return{hasAccess:!!(n!=null&&n.hasAccess),tier:(n==null?void 0:n.tier)??null,isLoading:t||r}}function rfr({children:s}){const{user:t,loading:n}=hs(),{hasAccess:r,isLoading:a}=nfr(),i=ru();return _.useEffect(()=>{!n&&!a&&t&&!r&&se.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(fd,{to:"/dashboard",replace:!0}):(sessionStorage.setItem("redirectAfterLogin",i.pathname),e.jsx(fd,{to:"/auth",replace:!0}))}function J3t({children:s}){const{user:t,loading:n}=hs(),{hasAccess:r,isLoading:a}=JMe(),i=ru();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(fd,{to:"/dashboard",replace:!0}):(sessionStorage.setItem("redirectAfterLogin",i.pathname),e.jsx(fd,{to:"/auth",replace:!0}))}const wZe={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"},afr=["First-time buyers","Move-up buyers","Luxury","New construction","Investors","Relocation","Downsizing / seniors","Military / VA","Land & ranch","Waterfront","Condos","Multi-family"],ifr=["Buyers","Sellers","Both equally","Investors","Renters","Builders / developers"],ofr=["Warm & approachable","Bold & direct","Educational & analytical","Playful & funny","Polished & luxury","Down-to-earth & local","High-energy & motivational"],lfr=[{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"}],cfr=["Under $250k","$250k – $500k","$500k – $750k","$750k – $1M","$1M – $2M","$2M+"],dfr=["Brand new (under 1 year)","1–3 years","3–5 years","5–10 years","10–20 years","20+ years"],ufr=[{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"}],hfr=[{value:"instagram",label:"Instagram"},{value:"tiktok",label:"TikTok"},{value:"facebook",label:"Facebook"},{value:"youtube",label:"YouTube Shorts"},{value:"linkedin",label:"LinkedIn"}],mfr=[{value:"15-30s",label:"15–30 seconds"},{value:"30-45s",label:"30–45 seconds"},{value:"45-60s",label:"45–60 seconds"}],pfr=[{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"}],ffr=[{value:"local",label:"Mostly local market content"},{value:"evergreen",label:"Mostly evergreen content"},{value:"mix",label:"A healthy mix of both"}];function ros({value:s,label:t}){const[n,r]=_.useState(!1);return s?e.jsxs(B,{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),se.success(`${t} copied`),setTimeout(()=>r(!1),1600)},children:[n?e.jsx(ea,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(Ia,{className:"h-3.5 w-3.5 mr-1"}),"Copy"]}):null}function MI({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(ros,{value:n,label:s}):null]}),e.jsx("div",{className:"text-[14.5px] leading-relaxed text-foreground whitespace-pre-wrap",children:t})]})}function l3e({reel:s,index:t,onUpdate:n,readOnly:r}){var c;const[a,i]=_.useState(t===0),l=!!s.recorded_at,o=!!s.posted_at;return e.jsx(ve,{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(Oe,{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(Oe,{variant:"outline",className:"text-[10.5px] font-medium text-muted-foreground",children:wZe[s.category]??s.category}):null,o?e.jsx(Oe,{className:"bg-emerald-100 text-emerald-800 border-0 text-[10.5px]",children:"Posted"}):l?e.jsx(Oe,{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(B,{type:"button",size:"icon",variant:"ghost","aria-label":s.favorited?"Remove from saved":"Save this reel",className:At("h-9 w-9 shrink-0",s.favorited&&"text-amber-500"),onClick:()=>n({favorited:!s.favorited}),children:e.jsx(Da,{className:At("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(ros,{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(MI,{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(B,{type:"button",size:"sm",variant:l?"default":"outline",className:"rounded-full",onClick:()=>n({recorded_at:l?null:new Date().toISOString()}),children:[e.jsx(Kr,{className:"h-3.5 w-3.5 mr-1.5"}),l?"Recorded":"Mark as recorded"]}),e.jsxs(B,{type:"button",size:"sm",variant:o?"default":"outline",className:"rounded-full",onClick:()=>n({posted_at:o?null:new Date().toISOString()}),children:[e.jsx(Or,{className:"h-3.5 w-3.5 mr-1.5"}),o?"Posted":"Mark as posted"]})]}):null,e.jsxs(f1,{open:a,onOpenChange:i,children:[e.jsx(x1,{asChild:!0,children:e.jsxs(B,{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(tl,{className:At("h-4 w-4 transition-transform",a&&"rotate-180")})]})}),e.jsxs(g1,{className:"space-y-5 pt-2",children:[e.jsx(wc,{}),s.filming_directions?e.jsx(MI,{label:"How to film it",children:e.jsxs("span",{className:"flex gap-2",children:[e.jsx(Eq,{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(MI,{label:"Caption",copyValue:s.caption,children:s.caption}):null,(c=s.hashtags)!=null&&c.length?e.jsx(MI,{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(MI,{label:"Pinned comment",copyValue:s.pinned_comment,children:s.pinned_comment}):null,s.reply_strategy?e.jsx(MI,{label:"Reply strategy",children:e.jsxs("span",{className:"flex gap-2",children:[e.jsx(Hi,{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(un,{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(MI,{label:"Bonus content idea",children:e.jsxs("span",{className:"flex gap-2",children:[e.jsx(mS,{className:"h-4 w-4 mt-0.5 shrink-0 text-muted-foreground"}),e.jsx("span",{children:s.bonus_idea})]})}):null]})]})]})})}function aos(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 eAt(){const s=aos(),[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 kee(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 Bit(s){const{user:t}=hs(),n=s??(t==null?void 0:t.id),r=Bt(),a=at({queryKey:["weekly-reels-profile",n],enabled:!!n,queryFn:async()=>{const{data:h,error:m}=await q.from("weekly_reel_profiles").select("*").eq("user_id",n).maybeSingle();if(m)throw m;return h??null}}),i=at({queryKey:["weekly-reels-packs",n],enabled:!!n,queryFn:async()=>{const{data:h,error:m}=await q.from("weekly_reel_packs").select("*").eq("user_id",n).order("week_start_date",{ascending:!1}).limit(52);if(m)throw m;const p=(h??[]).map(y=>y.id);let f=[];if(p.length){const{data:y,error:v}=await q.from("weekly_reels").select("*").in("pack_id",p).order("position",{ascending:!0});if(v)throw v;f=y??[]}return(h??[]).map(y=>({...y,reels:f.filter(v=>v.pack_id===y.id)}))}}),l=mt({mutationFn:async h=>{if(!n)throw new Error("Not signed in");const m={...h,user_id:n,...h.onboarding_completed?{onboarding_completed_at:new Date().toISOString()}:{}},{error:p}=await q.from("weekly_reel_profiles").upsert(m,{onConflict:"user_id"});if(p)throw p},onSuccess:()=>{r.invalidateQueries({queryKey:["weekly-reels-profile",n]})},onError:h=>se.error(h.message)}),o=mt({mutationFn:async({id:h,values:m})=>{const{error:p}=await q.from("weekly_reels").update(m).eq("id",h);if(p)throw p},onSuccess:()=>r.invalidateQueries({queryKey:["weekly-reels-packs",n]}),onError:h=>se.error(h.message)}),c=aos(),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 mue({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 xfr(){var D,O,V,G,$;const s=Fn(),{user:t}=hs(),{profile:n,packs:r,currentPack:a,history:i,saveProfile:l,updateReel:o}=Bit(),[c,d]=_.useState(!1),[u,h]=_.useState(!1),[m,p]=_.useState(""),[f,y]=_.useState("all"),[v,g]=_.useState("all"),b=(((D=n.data)==null?void 0:D.full_name)||((O=t==null?void 0:t.user_metadata)==null?void 0:O.full_name)||"there").split(" ")[0],j=!!((V=n.data)!=null&&V.onboarding_completed),S=_.useMemo(()=>(r.data??[]).flatMap(H=>H.reels.map(Y=>({reel:Y,pack:H}))),[r.data]),C=_.useMemo(()=>{const H=m.trim().toLowerCase();return S.filter(({pack:Y})=>v==="all"?!0:Y.week_start_date===v).filter(({reel:Y})=>f==="all"?!0:Y.category===f).filter(({reel:Y})=>H?`${Y.topic} ${Y.hook} ${Y.script}`.toLowerCase().includes(H):!0)},[S,m,f,v]),E=S.filter(({reel:H})=>H.favorited),P=async()=>{d(!0);try{const{data:H,error:Y}=await q.functions.invoke("weekly-reels-generate",{body:{action:"generate_pack",force:!0}});if(Y)throw new Error(await Ate(Y));if(H!=null&&H.error)throw new Error(H.error);await r.refetch(),se.success(H!=null&&H.skipped?String(H.skipped):"Your pack is ready")}catch(H){se.error(H instanceof Error?H.message:"Generation failed")}finally{d(!1)}},M=async()=>{if(a){h(!0);try{const{data:H,error:Y}=await q.functions.invoke("weekly-reels-generate",{body:{action:"send_pack_email",packId:a.id}});if(Y)throw new Error(await Ate(Y));if(H!=null&&H.error)throw new Error(H.error);await r.refetch(),se.success(`Sent to ${(H==null?void 0:H.recipient)??"your inbox"}`)}catch(H){se.error(H instanceof Error?H.message:"Could not send the email")}finally{h(!1)}}},I=H=>Y=>o.mutate({id:H.id,values:Y});return!n.isLoading&&!j?e.jsx(zs,{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(ve,{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(dm,{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(B,{size:"lg",className:"neon-cta mt-7",onClick:()=>s("/weekly-reels/onboarding"),children:[e.jsx(un,{className:"h-4 w-4 mr-2"})," Start setup — about 5 minutes"]})]})})})}):e.jsx(zs,{title:"Weekly Reels",children:e.jsx("div",{className:"program-theme-neon relative min-h-screen",children:e.jsxs("div",{className:"relative mx-auto w-full max-w-5xl px-4 py-8 sm:px-6",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"neon-eyebrow font-semibold",children:"Weekly Reels"}),e.jsxs("h1",{className:"neon-title mt-2 w-fit text-3xl font-black uppercase tracking-tight sm:text-4xl",children:["Welcome back, ",b]}),e.jsx("p",{className:"mt-2 text-[15px] text-muted-foreground",children:"Your Reels for the week, written around your market and your voice."})]}),e.jsxs(B,{variant:"outline",onClick:()=>s("/weekly-reels/onboarding"),children:[e.jsx(fS,{className:"h-4 w-4 mr-2"})," Edit my profile"]})]}),e.jsxs(ve,{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(mue,{icon:Er,label:"Onboarding",value:j?"Complete":"Incomplete"}),e.jsx(mue,{icon:Eq,label:"Weekly delivery",value:(G=n.data)!=null&&G.delivery_active?"Active":"Paused"}),e.jsx(mue,{icon:Qd,label:"Next pack",value:eAt()}),e.jsx(mue,{icon:ln,label:"Email this week",value:(a==null?void 0:a.delivery_status)==="sent"?"Delivered":(a==null?void 0:a.delivery_status)==="failed"?"Failed":"Scheduled"})]}),e.jsxs("div",{className:"mt-5 flex flex-wrap items-center justify-between gap-3 border-t border-border/60 pt-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(fn,{checked:!!(($=n.data)!=null&&$.delivery_active),onCheckedChange:H=>l.mutate({delivery_active:H}),"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(B,{variant:"outline",size:"sm",onClick:M,disabled:u,children:[u?e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(ln,{className:"h-4 w-4 mr-2"}),"Email me this week's pack"]}):null,e.jsxs(B,{size:"sm",className:"neon-cta",onClick:P,disabled:c,children:[c?e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(un,{className:"h-4 w-4 mr-2"}),a&&a.reels.length?"Regenerate this week":"Generate this week's pack"]})]})]})]}),e.jsxs(Yr,{defaultValue:"current",className:"mt-8",children:[e.jsxs(Zr,{children:[e.jsx(Ht,{value:"current",children:"This week"}),e.jsx(Ht,{value:"history",children:"History"}),e.jsxs(Ht,{value:"saved",children:["Saved",E.length?` (${E.length})`:""]})]}),e.jsx(Gt,{value:"current",className:"mt-6",children:r.isLoading?e.jsx("div",{className:"flex justify-center py-16",children:e.jsx(Ct,{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(Oe,{variant:"outline",className:"text-[11.5px]",children:["Week of ",kee(a.week_start_date)]}),e.jsxs("span",{className:"text-[13px] text-muted-foreground",children:[a.reels.filter(H=>H.posted_at).length," of ",a.reels.length," posted"]})]}),e.jsx("div",{className:"space-y-4",children:a.reels.map((H,Y)=>e.jsx(l3e,{reel:H,index:Y,onUpdate:I(H)},H.id))})]}):e.jsxs(ve,{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(dm,{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: ",eAt(),". Don't want to wait? Write them now."]}),e.jsxs(B,{className:"neon-cta mt-6",onClick:P,disabled:c,children:[c?e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(un,{className:"h-4 w-4 mr-2"}),"Generate it now"]})]})}),e.jsxs(Gt,{value:"history",className:"mt-6",children:[e.jsx(ve,{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(Lr,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(xe,{value:m,onChange:H=>p(H.target.value),placeholder:"Search topics and scripts...",className:"pl-9"})]}),e.jsxs(is,{value:f,onValueChange:y,children:[e.jsx(rs,{className:"sm:w-[190px]",children:e.jsx(ls,{placeholder:"All topics"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All topics"}),Object.entries(wZe).map(([H,Y])=>e.jsx(He,{value:H,children:Y},H))]})]}),e.jsxs(is,{value:v,onValueChange:g,children:[e.jsx(rs,{className:"sm:w-[180px]",children:e.jsx(ls,{placeholder:"All weeks"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All weeks"}),(r.data??[]).map(H=>e.jsx(He,{value:H.week_start_date,children:kee(H.week_start_date)},H.id))]})]})]})}),C.length?e.jsx(G9,{type:"multiple",className:"mt-4 space-y-3",children:C.map(({reel:H,pack:Y})=>e.jsxs(gL,{value:H.id,className:"rounded-2xl border border-border/70 bg-card px-4 sm:px-5",children:[e.jsx(yL,{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(Oe,{variant:"outline",className:"text-[10.5px] shrink-0",children:kee(Y.week_start_date)}),H.category?e.jsx(Oe,{className:"bg-muted text-muted-foreground border-0 text-[10.5px] shrink-0",children:wZe[H.category]??H.category}):null,e.jsx("span",{className:"truncate text-[14.5px] font-medium text-foreground",children:H.topic})]})}),e.jsx(vL,{className:"pb-4",children:e.jsx(l3e,{reel:H,index:H.position-1,onUpdate:I(H)})})]},H.id))}):e.jsxs(ve,{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(Lr,{className:"h-6 w-6 text-muted-foreground"})}),e.jsx("h3",{className:"mt-5 text-lg font-semibold text-foreground",children:"Nothing here yet"}),e.jsx("p",{className:"mx-auto mt-2 max-w-sm text-[14.5px] text-muted-foreground",children:S.length?"No Reels match these filters. Try widening your search.":"Your past packs will collect here once a few weeks have gone by."})]})]}),e.jsx(Gt,{value:"saved",className:"mt-6",children:E.length?e.jsx("div",{className:"space-y-4",children:E.map(({reel:H},Y)=>e.jsx(l3e,{reel:H,index:Y,onUpdate:I(H)},H.id))}):e.jsxs(ve,{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(Da,{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 PI=[{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 gfr(){const s=Fn(),{user:t}=hs(),{profile:n,saveProfile:r}=Bit(),[a,i]=_.useState(0),[l,o]=_.useState({specialties:[],client_types:[],brand_voice:[],preferred_reel_length:"30-45s",main_platform:"instagram",content_mix:"mix"}),[c,d]=_.useState(!1),[u,h]=_.useState(!1);_.useEffect(()=>{u||n.isLoading||(o(b=>{var j,S,C,E,P,M;return{...b,...n.data??{},full_name:((j=n.data)==null?void 0:j.full_name)??((S=t==null?void 0:t.user_metadata)==null?void 0:S.full_name)??"",email:((C=n.data)==null?void 0:C.email)??(t==null?void 0:t.email)??"",specialties:((E=n.data)==null?void 0:E.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=(b,j)=>o(S=>({...S,[b]:j})),p=(b,j)=>o(S=>{const C=S[b]??[];return{...S,[b]:C.includes(j)?C.filter(E=>E!==j):[...C,j]}}),f=_.useMemo(()=>{var b,j,S;return a===0?!!((b=l.full_name)!=null&&b.trim())&&!!((j=l.email)!=null&&j.trim()):a===1?!!((S=l.primary_market)!=null&&S.trim()):a===2?(l.brand_voice??[]).length>0:!0},[a,l]),y=async(b,j)=>{if(t){d(!0);try{const S=b.name.split(".").pop(),C=`${t.id}/weekly-reels-${j}-${Date.now()}.${S}`,{error:E}=await q.storage.from("avatars").upload(C,b,{upsert:!0});if(E)throw E;const{data:P}=q.storage.from("avatars").getPublicUrl(C);m(j,P.publicUrl),se.success("Image uploaded")}catch(S){se.error(S instanceof Error?S.message:"Upload failed")}finally{d(!1)}}},v=async()=>{await r.mutateAsync({...l,onboarding_completed:!0}),se.success("You're all set — your first pack is on the way."),s("/weekly-reels")},g=async()=>{await r.mutateAsync(l),se.success("Progress saved")};return e.jsx(zs,{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 ",PI.length," · ",PI[a].title]}),e.jsxs("span",{className:"neon-stat font-black",children:[Math.round((a+1)/PI.length*100),"%"]})]}),e.jsx(Fi,{value:(a+1)/PI.length*100,className:"mt-2 h-1.5"})]}),e.jsxs(ve,{className:"neon-topline rounded-2xl p-5 sm:p-7",children:[e.jsx("h2",{className:"text-lg font-semibold tracking-tight text-foreground",children:PI[a].title}),e.jsx("p",{className:"mt-1 text-[14px] text-muted-foreground",children:PI[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(J,{children:"Full name *"}),e.jsx(xe,{value:l.full_name??"",onChange:b=>m("full_name",b.target.value),placeholder:"Jane Realtor"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Email *"}),e.jsx(xe,{type:"email",value:l.email??"",onChange:b=>m("email",b.target.value),placeholder:"jane@brokerage.com"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Mobile number"}),e.jsx(xe,{value:l.mobile_number??"",onChange:b=>m("mobile_number",b.target.value),placeholder:"Optional"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Brokerage"}),e.jsx(xe,{value:l.brokerage??"",onChange:b=>m("brokerage",b.target.value)})]})]}),e.jsx("div",{className:"grid gap-4 sm:grid-cols-2",children:["headshot_url","logo_url"].map(b=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(J,{children:[b==="headshot_url"?"Headshot":"Logo"," (optional)"]}),e.jsxs("div",{className:"flex items-center gap-3",children:[l[b]?e.jsx("img",{src:l[b],alt:b==="headshot_url"?"Your headshot":"Your logo",className:"h-12 w-12 rounded-lg object-cover"}):null,e.jsxs("label",{className:"flex-1",children:[e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:j=>{var C;const S=(C=j.target.files)==null?void 0:C[0];S&&y(S,b)}}),e.jsxs("span",{className:"flex h-10 cursor-pointer items-center justify-center gap-2 rounded-md border border-input text-[13.5px] text-muted-foreground hover:bg-accent",children:[c?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Oa,{className:"h-4 w-4"}),"Upload"]})]})]})]},b))})]}),a===1&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Primary market — city & state *"}),e.jsx(xe,{value:l.primary_market??"",onChange:b=>m("primary_market",b.target.value),placeholder:"Tulsa, OK"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Neighborhoods or service areas"}),e.jsx(Ms,{rows:2,value:l.service_areas??"",onChange:b=>m("service_areas",b.target.value),placeholder:"Jenks, Bixby, Broken Arrow, midtown Tulsa"})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Years in real estate"}),e.jsxs(is,{value:l.years_in_real_estate??"",onValueChange:b=>m("years_in_real_estate",b),children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Select"})}),e.jsx(as,{children:dfr.map(b=>e.jsx(He,{value:b,children:b},b))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Typical price point"}),e.jsxs(is,{value:l.typical_price_point??"",onValueChange:b=>m("typical_price_point",b),children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Select"})}),e.jsx(as,{children:cfr.map(b=>e.jsx(He,{value:b,children:b},b))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Primary specialties / niches"}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:afr.map(b=>e.jsxs("label",{className:"flex items-center gap-2.5 text-[14px]",children:[e.jsx($a,{checked:(l.specialties??[]).includes(b),onCheckedChange:()=>p("specialties",b)}),b]},b))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Client types you serve"}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:ifr.map(b=>e.jsxs("label",{className:"flex items-center gap-2.5 text-[14px]",children:[e.jsx($a,{checked:(l.client_types??[]).includes(b),onCheckedChange:()=>p("client_types",b)}),b]},b))})]})]}),a===2&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Brand voice — pick everything that fits *"}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:ofr.map(b=>e.jsxs("label",{className:"flex items-center gap-2.5 text-[14px]",children:[e.jsx($a,{checked:(l.brand_voice??[]).includes(b),onCheckedChange:()=>p("brand_voice",b)}),b]},b))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Anything else about how you talk?"}),e.jsx(Ms,{rows:2,value:l.brand_voice_notes??"",onChange:b=>m("brand_voice_notes",b.target.value),placeholder:"I say 'y'all' a lot and I hate corporate jargon."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Humor level"}),e.jsx(k_,{value:l.humor_level??"",onValueChange:b=>m("humor_level",b),className:"space-y-1.5",children:lfr.map(b=>e.jsxs("label",{className:"flex items-center gap-2.5 text-[14px]",children:[e.jsx(sm,{value:b.value}),b.label]},b.value))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Personal interests & hobbies"}),e.jsx(Ms,{rows:2,value:l.personal_interests??"",onChange:b=>m("personal_interests",b.target.value),placeholder:"Golf, smoking brisket, coaching my son's baseball team"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Family or community details you're happy to reference"}),e.jsx(Ms,{rows:2,value:l.family_community_notes??"",onChange:b=>m("family_community_notes",b.target.value),placeholder:"Married with two kids, active in the Jenks chamber"})]})]}),a===3&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Preferred Reel length"}),e.jsxs(is,{value:l.preferred_reel_length??"30-45s",onValueChange:b=>m("preferred_reel_length",b),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsx(as,{children:mfr.map(b=>e.jsx(He,{value:b.value,children:b.label},b.value))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Preferred CTA style"}),e.jsxs(is,{value:l.preferred_cta_style??"",onValueChange:b=>m("preferred_cta_style",b),children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Select"})}),e.jsx(as,{children:ufr.map(b=>e.jsx(He,{value:b.value,children:b.label},b.value))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Main social platform"}),e.jsxs(is,{value:l.main_platform??"instagram",onValueChange:b=>m("main_platform",b),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsx(as,{children:hfr.map(b=>e.jsx(He,{value:b.value,children:b.label},b.value))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Instagram handle"}),e.jsx(xe,{value:l.instagram_handle??"",onChange:b=>m("instagram_handle",b.target.value),placeholder:"@janerealtor"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Website"}),e.jsx(xe,{value:l.website??"",onChange:b=>m("website",b.target.value),placeholder:"https://janerealtor.com"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"On-camera comfort level"}),e.jsx(k_,{value:l.content_comfort_level??"",onValueChange:b=>m("content_comfort_level",b),className:"space-y-1.5",children:pfr.map(b=>e.jsxs("label",{className:"flex items-center gap-2.5 text-[14px]",children:[e.jsx(sm,{value:b.value}),b.label]},b.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Local vs evergreen content"}),e.jsx(k_,{value:l.content_mix??"mix",onValueChange:b=>m("content_mix",b),className:"space-y-1.5",children:ffr.map(b=>e.jsxs("label",{className:"flex items-center gap-2.5 text-[14px]",children:[e.jsx(sm,{value:b.value}),b.label]},b.value))})]})]}),a===4&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Topics you love talking about"}),e.jsx(Ms,{rows:2,value:l.topics_enjoyed??"",onChange:b=>m("topics_enjoyed",b.target.value),placeholder:"Renovation ROI, negotiating repairs, small-town living"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Topics you never want to cover"}),e.jsx(Ms,{rows:2,value:l.topics_avoided??"",onChange:b=>m("topics_avoided",b.target.value),placeholder:"Politics, interest rate predictions, dancing trends"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Lead magnets or offers to promote"}),e.jsx(Ms,{rows:2,value:l.lead_magnets??"",onChange:b=>m("lead_magnets",b.target.value),placeholder:"Free home value report, first-time buyer guide"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Current business goals"}),e.jsx(Ms,{rows:2,value:l.business_goals??"",onChange:b=>m("business_goals",b.target.value),placeholder:"Two listings a month and more sphere referrals"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Compliance or brokerage disclaimer notes"}),e.jsx(Ms,{rows:2,value:l.compliance_notes??"",onChange:b=>m("compliance_notes",b.target.value),placeholder:"Must include brokerage name on any listing content"})]})]})]}),e.jsxs("div",{className:"mt-8 flex flex-wrap items-center justify-between gap-3",children:[e.jsxs(B,{type:"button",variant:"ghost",disabled:a===0,onClick:()=>i(b=>Math.max(0,b-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(B,{type:"button",variant:"outline",onClick:g,disabled:r.isPending,children:"Save draft"}),ai(b=>b+1),children:["Continue ",e.jsx(La,{className:"h-4 w-4 ml-1.5"})]}):e.jsxs(B,{className:"neon-cta",type:"button",onClick:v,disabled:r.isPending,children:[r.isPending?e.jsx(Ct,{className:"h-4 w-4 mr-1.5 animate-spin"}):e.jsx(ea,{className:"h-4 w-4 mr-1.5"}),"Finish setup"]})]})]})]})]})})})}function ios(s,t=!1){const{user:n}=hs(),r=Bt(),a=at({queryKey:["wr-admin-members",s,t,n==null?void 0:n.id],enabled:!!n,queryFn:async()=>{let y=null;if(t){const{data:D,error:O}=await q.from("feature_entitlements").select("user_id").eq("feature_key",KU).eq("enabled",!0);if(O)throw O;if(y=(D??[]).map(V=>V.user_id),!y.length)return[]}let v=q.from("profiles").select("id, email, name").order("name",{ascending:!0}).limit(t?1e3:100);if(y&&(v=v.in("id",y)),s.trim()){const D=`%${s.trim()}%`;v=v.or(`email.ilike.${D},name.ilike.${D}`)}const{data:g,error:b}=await v;if(b)throw b;const j=(g??[]).map(D=>D.id);if(!j.length)return[];const[{data:S},{data:C},{data:E}]=await Promise.all([q.from("feature_entitlements").select("user_id, enabled, tier, expires_at").eq("feature_key",KU).in("user_id",j),q.from("weekly_reel_profiles").select("user_id, onboarding_completed, delivery_active, primary_market").in("user_id",j),q.from("weekly_reel_packs").select("id, user_id, week_start_date, generation_status, delivery_status").in("user_id",j).order("week_start_date",{ascending:!1})]),P=new Map((S??[]).map(D=>[D.user_id,D])),M=new Map((C??[]).map(D=>[D.user_id,D])),I=new Map;return(E??[]).forEach(D=>{I.has(D.user_id)||I.set(D.user_id,D)}),(g??[]).map(D=>{const O=P.get(D.id),V=M.get(D.id),G=I.get(D.id);return{user_id:D.id,email:D.email,full_name:D.name,enabled:!!(O!=null&&O.enabled),tier:(O==null?void 0:O.tier)??null,expires_at:(O==null?void 0:O.expires_at)??null,onboarded:!!(V!=null&&V.onboarding_completed),delivery_active:(V==null?void 0:V.delivery_active)??!1,primary_market:(V==null?void 0:V.primary_market)??null,latest_week:(G==null?void 0:G.week_start_date)??null,latest_pack_id:(G==null?void 0:G.id)??null,latest_generation_status:(G==null?void 0:G.generation_status)??null,latest_delivery_status:(G==null?void 0:G.delivery_status)??null}})}}),i=at({queryKey:["wr-admin-generation-logs"],enabled:!!n,queryFn:async()=>{const{data:y,error:v}=await q.from("weekly_reel_generation_logs").select("*").order("created_at",{ascending:!1}).limit(100);if(v)throw v;return y??[]}}),l=at({queryKey:["wr-admin-delivery-logs"],enabled:!!n,queryFn:async()=>{const{data:y,error:v}=await q.from("weekly_reel_delivery_logs").select("*").order("created_at",{ascending:!1}).limit(100);if(v)throw v;return y??[]}}),o=()=>{r.invalidateQueries({queryKey:["wr-admin-members"]}),r.invalidateQueries({queryKey:["wr-admin-generation-logs"]}),r.invalidateQueries({queryKey:["wr-admin-delivery-logs"]})},c=mt({mutationFn:async({userId:y,enabled:v})=>{const{error:g}=await q.from("feature_entitlements").upsert({user_id:y,feature_key:KU,enabled:v,tier:"member",enabled_by:n.id,enabled_at:new Date().toISOString()},{onConflict:"user_id,feature_key"});if(g)throw g;await q.from("feature_entitlement_audit").insert({feature_key:KU,target_user_id:y,action:v?"grant":"revoke",performed_by:n.id})},onSuccess:(y,v)=>{o(),se.success(v.enabled?"Access granted":"Access revoked")},onError:y=>se.error(y.message)}),d=async y=>{const{data:v,error:g}=await q.functions.invoke("weekly-reels-generate",{body:y});if(g)throw new Error(await Ate(g));if(v!=null&&v.error)throw new Error(String(v.error));return v},u=mt({mutationFn:y=>d({action:"generate_pack",userId:y.userId,force:y.force??!0}),onSuccess:()=>{o(),se.success("Pack generated")},onError:y=>se.error(y.message)}),h=mt({mutationFn:y=>d({action:"regenerate_reel",reelId:y.reelId,instructions:y.instructions}),onSuccess:()=>{o(),se.success("Reel regenerated")},onError:y=>se.error(y.message)}),m=mt({mutationFn:y=>d({action:"send_pack_email",packId:y.packId}),onSuccess:()=>{o(),se.success("Pack emailed")},onError:y=>se.error(y.message)}),p=mt({mutationFn:y=>d({action:"send_test_email",packId:y.packId,to:y.to}),onSuccess:()=>se.success("Test email sent"),onError:y=>se.error(y.message)}),f=mt({mutationFn:()=>d({action:"run_weekly"}),onSuccess:y=>{o(),se.success(`Weekly run complete${(y==null?void 0:y.processed)!=null?` — ${y.processed} agents`:""}`)},onError:y=>se.error(y.message)});return{members:a,generationLogs:i,deliveryLogs:l,setAccess:c,generatePack:u,regenerateReel:h,sendPack:m,sendTest:p,runWeekly:f}}function vq({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(Oe,{className:`${t} border-0 text-[11px] capitalize`,children:s})}function yfr({member:s,onClose:t}){var m,p,f;const n=ios(""),{packs:r,profile:a}=Bit(s==null?void 0:s.user_id),[i,l]=_.useState(""),[o,c]=_.useState(""),[d,u]=_.useState(null),h=((m=r.data)==null?void 0:m[0])??null;return e.jsx(Ls,{open:!!s,onOpenChange:y=>!y&&t(),children:e.jsxs(Ps,{className:"max-w-3xl max-h-[88vh] overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:(s==null?void 0:s.full_name)||(s==null?void 0:s.email)}),e.jsxs(_r,{children:[((p=a.data)==null?void 0:p.primary_market)??"No market on file"," ·"," ",(f=a.data)!=null&&f.onboarding_completed?"Onboarded":"Onboarding incomplete"]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(B,{size:"sm",onClick:()=>s&&n.generatePack.mutate({userId:s.user_id}),disabled:n.generatePack.isPending,children:[n.generatePack.isPending?e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(un,{className:"h-4 w-4 mr-2"}),"Generate pack"]}),e.jsxs(B,{size:"sm",variant:"outline",disabled:!h||n.sendPack.isPending,onClick:()=>h&&n.sendPack.mutate({packId:h.id}),children:[e.jsx(ln,{className:"h-4 w-4 mr-2"})," Email latest pack"]})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-2 rounded-xl bg-muted/60 p-3",children:[e.jsxs("div",{className:"flex-1 min-w-[200px] space-y-1.5",children:[e.jsx(J,{className:"text-[12px]",children:"Send a test copy to"}),e.jsx(xe,{value:i,onChange:y=>l(y.target.value),placeholder:"you@relevelup.com"})]}),e.jsxs(B,{size:"sm",variant:"outline",disabled:!h||!i||n.sendTest.isPending,onClick:()=>h&&n.sendTest.mutate({packId:h.id,to:i}),children:[e.jsx(Or,{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(Oe,{variant:"outline",children:["Week of ",kee(h.week_start_date)]}),e.jsx(vq,{value:h.generation_status}),e.jsx(vq,{value:h.delivery_status})]}),h.reels.map((y,v)=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(l3e,{reel:y,index:v,readOnly:!0}),d===y.id?e.jsxs("div",{className:"rounded-xl border border-border/70 p-3 space-y-2",children:[e.jsx(Ms,{rows:2,value:o,onChange:g=>c(g.target.value),placeholder:"Optional guidance: make it more local, less salesy, focus on sellers..."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{size:"sm",disabled:n.regenerateReel.isPending,onClick:()=>n.regenerateReel.mutate({reelId:y.id,instructions:o||void 0},{onSuccess:()=>{u(null),c(""),r.refetch()}}),children:[n.regenerateReel.isPending?e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(uo,{className:"h-4 w-4 mr-2"}),"Regenerate"]}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>u(null),children:"Cancel"})]})]}):e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>u(y.id),children:[e.jsx(uo,{className:"h-4 w-4 mr-2"})," Regenerate this reel"]})]},y.id))]}):e.jsx("p",{className:"py-6 text-center text-[14px] text-muted-foreground",children:"No packs generated for this agent yet."}),e.jsx(yr,{children:e.jsx(B,{variant:"outline",onClick:t,children:"Close"})})]})})}function vfr(){const[s,t]=_.useState(""),[n,r]=_.useState(!1),[a,i]=_.useState(null),l=ios(s,n),o=_.useMemo(()=>l.members.data??[],[l.members.data]);return e.jsxs(zs,{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(B,{onClick:()=>l.runWeekly.mutate(),disabled:l.runWeekly.isPending,children:[l.runWeekly.isPending?e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(un,{className:"h-4 w-4 mr-2"}),"Run this week now"]})]}),e.jsxs(Yr,{defaultValue:"members",className:"mt-7",children:[e.jsxs(Zr,{children:[e.jsx(Ht,{value:"members",children:"Members"}),e.jsx(Ht,{value:"generation",children:"Generation log"}),e.jsx(Ht,{value:"delivery",children:"Delivery log"})]}),e.jsxs(Gt,{value:"members",className:"mt-5",children:[e.jsx(ve,{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(Lr,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(xe,{value:s,onChange:c=>t(c.target.value),placeholder:"Search by name or email...",className:"pl-9"})]}),e.jsxs("label",{className:"flex items-center gap-2.5 text-[14px] text-muted-foreground",children:[e.jsx(fn,{checked:n,onCheckedChange:r}),"Only members with access"]})]})}),e.jsx(ve,{className:"mt-4 rounded-2xl overflow-hidden",children:e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"Agent"}),e.jsx(Pt,{children:"Market"}),e.jsx(Pt,{children:"Onboarded"}),e.jsx(Pt,{children:"Latest week"}),e.jsx(Pt,{children:"Generation"}),e.jsx(Pt,{children:"Delivery"}),e.jsx(Pt,{className:"text-right",children:"Access"}),e.jsx(Pt,{})]})}),e.jsx(Ka,{children:l.members.isLoading?e.jsx(pn,{children:e.jsx(gt,{colSpan:8,className:"py-10 text-center",children:e.jsx(Ct,{className:"mx-auto h-5 w-5 animate-spin text-muted-foreground"})})}):o.length?o.map(c=>e.jsxs(pn,{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(Oe,{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?kee(c.latest_week):"—"}),e.jsx(gt,{children:e.jsx(vq,{value:c.latest_generation_status})}),e.jsx(gt,{children:e.jsx(vq,{value:c.latest_delivery_status})}),e.jsx(gt,{className:"text-right",children:e.jsx(fn,{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(B,{size:"sm",variant:"ghost",onClick:()=>i(c),children:"Manage"})})]},c.user_id)):e.jsx(pn,{children:e.jsx(gt,{colSpan:8,className:"py-10 text-center text-muted-foreground",children:"No members match this search."})})})]})})]}),e.jsx(Gt,{value:"generation",className:"mt-5",children:e.jsx(ve,{className:"rounded-2xl overflow-hidden",children:e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"When"}),e.jsx(Pt,{children:"Status"}),e.jsx(Pt,{children:"Model"}),e.jsx(Pt,{children:"Tokens"}),e.jsx(Pt,{children:"Cost"}),e.jsx(Pt,{children:"Error"})]})}),e.jsx(Ka,{children:(l.generationLogs.data??[]).map(c=>e.jsxs(pn,{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(vq,{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(Gt,{value:"delivery",className:"mt-5",children:e.jsx(ve,{className:"rounded-2xl overflow-hidden",children:e.jsxs(Ga,{children:[e.jsx(Wa,{children:e.jsxs(pn,{children:[e.jsx(Pt,{children:"When"}),e.jsx(Pt,{children:"Recipient"}),e.jsx(Pt,{children:"Status"}),e.jsx(Pt,{children:"Error"})]})}),e.jsx(Ka,{children:(l.deliveryLogs.data??[]).map(c=>e.jsxs(pn,{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(vq,{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(yfr,{member:a,onClose:()=>i(null)})]})}function Uit(){const{user:s}=hs(),t=Bt(),n=at({queryKey:["attract-settings",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:i,error:l}=await q.from("attract_settings").select("*").eq("user_id",s.id).maybeSingle();if(l)throw l;return i}}),r=mt({mutationFn:async i=>{const l={...i,user_id:s.id},{data:o,error:c}=await q.from("attract_settings").upsert(l,{onConflict:"user_id"}).select().single();if(c)throw c;return o},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-settings"]}),se.success("Settings saved")},onError:i=>se.error(i.message)}),a=mt({mutationFn:async()=>{const{error:i}=await q.from("attract_settings").update({onboarding_completed_at:null}).eq("user_id",s.id);if(i)throw i},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-settings"]}),se.success("Onboarding reset — run it again anytime")}});return{settings:n.data,isLoading:n.isLoading,save:r,upsert:r,resetOnboarding:a}}const oos="v1",km={recency:22,consistency:16,value_delivered:14,kit_engagement:16,event_participation:12,follow_up_discipline:10,pipeline_momentum:10};Object.values(km).reduce((s,t)=>s+t,0);const los=864e5,d0=(s,t=new Date)=>Math.floor((new Date(t).getTime()-new Date(s).getTime())/los),cos=["touch_logged","call","text","email","dm","meeting","note"];function bfr(s,t,n=new Date){var y,v,g;const a=t.activities.filter(b=>b.agent_id===s.id).filter(b=>cos.includes(b.activity_type)).sort((b,j)=>+new Date(j.created_at)-+new Date(b.created_at)),i=s.last_touch_at||((y=a[0])==null?void 0:y.created_at)||null,l=t.shares.filter(b=>b.agent_id===s.id),o=new Set(l.map(b=>b.id)),c=t.kitEvents.filter(b=>o.has(b.share_id)),d={};for(const b of l)d[b.id]=[];for(const b of c)(d[v=b.share_id]||(d[v]=[])).push(b);const u=t.attendees.filter(b=>b.agent_id===s.id),h=t.followUps.filter(b=>b.agent_id===s.id),m=h.filter(b=>!b.completed_at),p=t.stageChanges.filter(b=>b.agent_id===s.id).sort((b,j)=>+new Date(j.created_at)-+new Date(b.created_at)),f=new Set(a.filter(b=>d0(b.created_at,n)<=180).map(b=>b.created_at.slice(0,7)));return{agent:s,touches:a,lastTouchAt:i,daysSinceTouch:i?d0(i,n):null,touches90:a.filter(b=>d0(b.created_at,n)<=90).length,touches30:a.filter(b=>d0(b.created_at,n)<=30).length,distinctTouchMonths:f.size,shares:l,shareEvents:d,highIntentShares:l.filter(b=>b.engagement_level==="high_intent"||b.engagement_level==="engaged"),lastShareAt:l.map(b=>b.created_at).sort().reverse()[0]||null,totalKitOpens:l.reduce((b,j)=>b+(j.open_count||0),0),downloads:c.filter(b=>b.event_type==="file_download").length,ctaClicks:c.filter(b=>b.event_type==="primary_cta_click"||b.event_type==="external_link_click").length,questions:c.filter(b=>b.event_type==="question_submitted").length,meetingRequests:c.filter(b=>b.event_type==="meeting_requested").length+u.filter(b=>b.meeting_requested).length,attendees:u,attended:u.filter(b=>!!b.checked_in_at||b.status==="attended").length,noShows:u.filter(b=>!!b.no_show_at||b.status==="no_show").length,invitedNotRegistered:u.filter(b=>!!b.invited_at&&!b.registered_at&&!b.checked_in_at).length,openFollowUps:m,overdueFollowUps:m.filter(b=>b.due_at&&new Date(b.due_at)!!b.completed_at),stageChanges:p,lastStageChangeAt:((g=p[0])==null?void 0:g.created_at)||null,daysSinceStageChange:p[0]?d0(p[0].created_at,n):null,scoreEvents:t.scoreEvents.filter(b=>b.agent_id===s.id)}}const c3e=["new_connection","building_relationship","engaging_with_value","active_conversation","exploring_options","brokerage_presentation","decision_pending","joined"],d3e=["not_right_now","not_a_fit","long_term_relationship"];function _fr(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=km.recency,c=`Last meaningful touch ${l} day(s) ago.`,r.push("Recent personal contact")):l<=21?(o=km.recency*.85,c=`Last touch ${l} days ago.`,r.push("Contact is still fresh")):l<=45?(o=km.recency*.6,c=`Last touch ${l} days ago.`,i.push("Reach out within the next week to keep momentum.")):l<=90?(o=km.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=km.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:km.recency,earned:Math.round(o),detail:c,direction:o>=km.recency*.6?"positive":"negative"});const d=Math.min(s.distinctTouchMonths,6),u=km.consistency*(d/6),h=s.touches30>6;n.push({key:"consistency",label:"Consistency of touches",weight:km.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>=km.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=km.value_delivered*Math.min(m/3,1);n.push({key:"value_delivered",label:"Value delivered",weight:km.value_delivered,earned:Math.round(p),detail:m?`${m} resource kit share(s) sent.`:"No resource kit shared yet.",direction:m?"positive":"neutral"}),m?r.push(`${m} resource kit share(s) delivered`):i.push("Share a relevant Resource Kit — value first, no ask.");const f=(s.totalKitOpens>0?4:0)+Math.min(s.downloads,2)*2+Math.min(s.ctaClicks,2)*2+(s.questions>0?2:0)+(s.meetingRequests>0?4:0),y=Math.min(f,km.kit_engagement);n.push({key:"kit_engagement",label:"Kit engagement",weight:km.kit_engagement,earned:y,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:y>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 v=Math.min(s.attended,2)*5+(s.attendees.length?2:0)-Math.min(s.noShows,2)*2,g=Math.max(0,Math.min(v,km.event_participation));n.push({key:"event_participation",label:"Event participation",weight:km.event_participation,earned:g,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:g>0?"positive":"neutral"}),s.attended>0&&r.push(`${s.attended} event(s) attended`),s.attendees.length||i.push("Invite them to your next event or mastermind."),s.noShows>0&&a.push(`${s.noShows} no-show(s)`);const b=s.completedFollowUps.length+s.openFollowUps.length;let j=b===0?km.follow_up_discipline*.4:km.follow_up_discipline*(s.completedFollowUps.length/b);j-=Math.min(s.overdueFollowUps.length,3)*2,j=Math.max(0,Math.min(j,km.follow_up_discipline)),n.push({key:"follow_up_discipline",label:"Follow-up discipline",weight:km.follow_up_discipline,earned:Math.round(j),detail:b?`${s.completedFollowUps.length} of ${b} follow-ups completed, ${s.overdueFollowUps.length} overdue.`:"No follow-ups created yet.",direction:s.overdueFollowUps.length?"negative":"positive"}),s.overdueFollowUps.length&&(a.push(`${s.overdueFollowUps.length} overdue commitment(s)`),i.push("Clear the overdue follow-up you promised."));const S=c3e.indexOf(s.agent.stage);let C=0,E;if(d3e.includes(s.agent.stage))C=km.pipeline_momentum*.3,E="Relationship is intentionally parked — long-term nurture.";else if(S<0)C=km.pipeline_momentum*.3,E=`Stage "${s.agent.stage}" is outside the advancing ladder.`;else{const I=km.pipeline_momentum*(S/(c3e.length-1)),D=s.daysSinceStageChange!==null&&s.daysSinceStageChange>60;C=D?I*.5:I,E=`Stage ${S+1} of ${c3e.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:km.pipeline_momentum,earned:Math.round(C),detail:E,direction:C>km.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:{...km},engine_version:oos,calculated_at:t.toISOString()}}const dos=[{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"}],wfr={urgent:100,high:70,medium:40,low:15},N2=(s,t=new Date)=>new Date(t.getTime()+s*los).toISOString(),O5=s=>s.first_name||"there",jfr=3;function k2(s,t,n={}){var o,c;const r=O5(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 Nfr(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 g;return(g=t.kits.find(b=>b.id===v))==null?void 0:g.title},o=v=>{r.push({...v,message_source:"rules",rank_score:v.rank_score??wfr[v.priority]})},c=s.shares.find(v=>v.engagement_level==="high_intent");if(s.meetingRequests>0||s.questions>0||c){const v=c?l(c.kit_id):void 0,g=[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 ${O5(a)} — they are actively engaging`,reasons:g,priority:"urgent",suggested_due_at:N2(1,n),draft_message:k2("high_intent",s,{kitTitle:v}),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(v=>v.last_opened_at&&v.first_opened_at&&d0(v.last_opened_at,n)<=7&&d0(v.first_opened_at,v.last_opened_at)>=14&&(v.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:`${O5(a)} came back to a kit you shared`,reasons:[`Re-opened "${l(d.kit_id)??"a shared kit"}" ${d0(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:N2(2,n),draft_message:k2("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(v=>v.checked_in_at&&d0(v.checked_in_at,n)<=7&&v.followup_status!=="done").sort((v,g)=>+new Date(g.checked_in_at)-+new Date(v.checked_in_at))[0];if(u){const v=t.events.find(b=>b.id===u.event_id),g=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 ${(v==null?void 0:v.title)??"the event"} — ${g}h since they attended`,reasons:[`Checked in to "${(v==null?void 0:v.title)??"event"}" ${g} hours ago`,`Follow-up status is "${u.followup_status??"pending"}"`,g<=48?"Inside the 48-hour window where follow-up matters most":"Past the ideal 48-hour window — still worth doing today"],priority:g<=48?"urgent":"high",suggested_due_at:N2(g<=48?1:0,n),draft_message:k2("event_follow_up",s,{eventTitle:v==null?void 0:v.title}),suggested_event_id:u.event_id,suggested_kit_id:(v==null?void 0:v.resource_kit_id)??null,source_signals:{attendee_id:u.id,hours_since:g},rank_score:g<=48?96:74})}else{const v=s.attendees.find(g=>g.no_show_at&&d0(g.no_show_at,n)<=10);if(v){const g=t.events.find(b=>b.id===v.event_id);o({agent_id:a.id,rec_key:`event_no_show:${v.event_id}`,signal_group:"event_follow_up",signal_label:"Event follow-up needed",action_type:"no_show_recovery",channel:"text",title:`${O5(a)} missed ${(g==null?void 0:g.title)??"an event"} — recover gracefully`,reasons:[`Registered but did not attend "${(g==null?void 0:g.title)??"event"}"`,"No-show recovery works best within a week, with zero guilt"],priority:"medium",suggested_due_at:N2(2,n),draft_message:k2("event_no_show",s,{eventTitle:g==null?void 0:g.title}),suggested_event_id:v.event_id,source_signals:{attendee_id:v.id},rank_score:52})}}const h=s.shares.find(v=>v.first_opened_at&&d0(v.first_opened_at,n)>=3&&d0(v.first_opened_at,n)<=30&&(s.daysSinceTouch===null||s.lastTouchAt&&new Date(s.lastTouchAt)!v.first_opened_at&&d0(v.created_at,n)>=5&&v.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 ${d0(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:N2(2,n),draft_message:k2("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 ${O5(a)} personally`,reasons:[`Shared ${d0(m.created_at,n)} days ago and never opened`,"A personal message beats a resend"],priority:"medium",suggested_due_at:N2(2,n),draft_message:k2("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((v,g)=>+new Date(v.due_at)-+new Date(g.due_at))[0];if(p){const v=d0(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 ${v} day(s): ${p.title}`,reasons:[`Follow-up "${p.title}" was due ${v} day(s) ago`,`Priority: ${p.priority??"medium"}`],priority:v>7?"urgent":"high",suggested_due_at:N2(0,n),draft_message:k2("overdue_commitment",s,{followUpTitle:p.title}),source_signals:{follow_up_id:p.id,days_late:v},rank_score:92+Math.min(v,8)})}const f=c3e.indexOf(a.stage);if(!d3e.includes(a.stage)&&f>=2&&s.attended>0&&(s.totalKitOpens>0||s.downloads>0)&&(s.daysSinceStageChange===null||s.daysSinceStageChange>21)&&o({agent_id:a.id,rec_key:"ready_deeper",signal_group:"ready_deeper",signal_label:"Ready for a deeper conversation",action_type:"deeper_conversation",channel:"call",title:`Have the honest next-chapter conversation with ${O5(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:N2(4,n),draft_message:k2("ready_deeper",s),source_signals:{stage:a.stage,attended:s.attended},rank_score:72}),s.daysSinceTouch===null&&d0(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 ${O5(a)}`,reasons:[`Added to your pipeline ${d0(a.created_at,n)} days ago`,"No touch, kit, or event activity logged"],priority:"medium",suggested_due_at:N2(3,n),draft_message:k2("no_touch",s),source_signals:{created_at:a.created_at},rank_score:48});else if(s.daysSinceTouch!==null){const v=a.temperature==="hot"?14:a.temperature==="cold"?90:45;if(s.daysSinceTouch>v){const g=s.daysSinceTouch>v*2;o({agent_id:a.id,rec_key:g?"no_touch_long":"going_cold",signal_group:g?"no_touch":"going_cold",signal_label:g?"No meaningful touch recently":"Relationship going cold",action_type:"check_in",channel:"personal_check_in",title:`${O5(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 ${v} days`,s.touches90?`${s.touches90} touch(es) in the last 90 days`:"No touches in the last 90 days"],priority:g?"high":"medium",suggested_due_at:N2(3,n),draft_message:k2(g?"no_touch":"going_cold",s),source_signals:{days_since_touch:s.daysSinceTouch,threshold:v},rank_score:g?62:44})}}if(!s.shares.length&&!d3e.includes(a.stage)&&t.primaryPillar==="provide"){const v=t.kits.find(g=>g.status==="published"&&(!g.audience||!a.production_context||!0));v&&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 "${v.title}" with ${O5(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:N2(5,n),draft_message:k2("share_value",s,{kitTitle:v.title}),suggested_kit_id:v.id,source_signals:{pillar:"provide"},rank_score:38})}if(!s.attendees.length&&!d3e.includes(a.stage)&&t.primaryPillar==="connect"){const v=t.events.filter(g=>g.status==="published"&&g.starts_at&&new Date(g.starts_at)>n).sort((g,b)=>+new Date(g.starts_at)-+new Date(b.starts_at))[0];v&&o({agent_id:a.id,rec_key:`invite_event:${v.id}`,signal_group:"ready_deeper",signal_label:"Ready for a deeper conversation",action_type:"invite_to_event",channel:"event_invitation",title:`Invite ${O5(a)} to ${v.title}`,reasons:["Never invited to an event",`"${v.title}" is published and upcoming`,"Your 90-day plan primary pillar is Connect"],priority:"medium",suggested_due_at:N2(4,n),draft_message:k2("event_invite_nudge",s,{eventTitle:v.title,eventWhen:v.starts_at?new Date(v.starts_at).toLocaleDateString():void 0}),suggested_event_id:v.id,source_signals:{pillar:"connect",event_id:v.id},rank_score:40})}return(i?r.filter(v=>v.priority==="urgent"):r).sort((v,g)=>g.rank_score-v.rank_score).slice(0,3)}const tAt=[{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"]}],kfr={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 Sfr(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:cos.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 Cfr(s,t,n){return s.shares.slice().sort((r,a)=>+new Date(a.created_at)-+new Date(r.created_at)).map(r=>{var m;const a=s.shareEvents[r.id]??[],i=a.filter(p=>p.event_type==="file_download").length,l=a.filter(p=>p.event_type==="primary_cta_click"||p.event_type==="external_link_click").length,o=a.filter(p=>p.event_type==="question_submitted").length,c=a.filter(p=>p.event_type==="meeting_requested").length,d=r.engagement_level==="high_intent"||c>0?"High Intent":r.engagement_level==="engaged"||i>0||l>0||o>0?"Engaged":r.first_opened_at?"Viewed":"Sent",u=t.followUps.filter(p=>p.agent_id===s.agent.id&&new Date(p.created_at)>=new Date(r.created_at)).sort((p,f)=>+new Date(p.created_at)-+new Date(f.created_at))[0]??null,h=s.stageChanges.filter(p=>new Date(p.created_at)>new Date(r.created_at)).sort((p,f)=>+new Date(p.created_at)-+new Date(f.created_at))[0]??null;return{share:r,kitTitle:((m=t.kits.find(p=>p.id===r.kit_id))==null?void 0:m.title)??"Resource kit",shareUrl:`${n}/attract-kit/${r.share_token}`,events:a,firstViewedAt:r.first_opened_at??null,lastViewedAt:r.last_opened_at??null,visits:r.open_count??0,downloads:i,ctaClicks:l,questions:o,meetingRequests:c,classification:d,followUp:u,stageAdvancedAfter:h}})}function Afr(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 tm=q;function Efr(){const{user:s}=hs();return at({queryKey:["attract-intel-data",s==null?void 0:s.id],enabled:!!s,staleTime:3e4,queryFn:async()=>{var f,y;const[t,n,r,a,i,l,o,c,d,u,h,m]=await Promise.all([tm.from("attract_agents").select("*").order("updated_at",{ascending:!1}),tm.from("attract_activities").select("*").order("created_at",{ascending:!1}).limit(2e3),tm.from("attract_follow_ups").select("*").order("created_at",{ascending:!1}).limit(2e3),tm.from("attract_kit_shares").select("*").order("created_at",{ascending:!1}).limit(1e3),tm.from("attract_kit_events").select("*").order("created_at",{ascending:!1}).limit(2e3),tm.from("attract_event_attendees").select("*").order("created_at",{ascending:!1}).limit(2e3),tm.from("attract_events").select("id, title, starts_at, status, resource_kit_id, public_slug").limit(500),tm.from("attract_pipeline_history").select("*").order("created_at",{ascending:!1}).limit(2e3),tm.from("attract_score_events").select("*").order("created_at",{ascending:!1}).limit(2e3),tm.from("attract_resource_kits").select("id, title, audience, pillar, status, is_template").eq("is_template",!1),tm.from("attract_event_notes").select("*").order("created_at",{ascending:!1}).limit(1e3),tm.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(v=>v.error);if(p)throw p.error;return{agents:t.data??[],activities:n.data??[],followUps:r.data??[],shares:a.data??[],kitEvents:i.data??[],attendees:l.data??[],events:o.data??[],stageChanges:c.data??[],scoreEvents:d.data??[],kits:u.data??[],eventNotes:h.data??[],primaryPillar:((f=m==null?void 0:m.data)==null?void 0:f.primary_pillar)??((y=m==null?void 0:m.data)==null?void 0:y.attraction_style)??null}}})}function gK(){const s=Efr(),t=_.useMemo(()=>{if(!s.data)return[];const r=new Date;return s.data.agents.map(a=>{const i=bfr(a,s.data,r),l=_fr(i,r),o=Nfr(i,s.data,r);return{agent:a,signals:i,score:l,recommendations:o,primary:o[0]??null}})},[s.data]),n=_.useMemo(()=>new Map(t.map(r=>[r.agent.id,r])),[t]);return{...s,dataset:s.data,intel:t,byId:n}}function Tfr(s){const{dataset:t,byId:n,isLoading:r,error:a,refetch:i}=gK(),l=s?n.get(s)??null:null,o=_.useMemo(()=>l&&t?Sfr(l.signals,t,t.eventNotes??[]):[],[l,t]),c=_.useMemo(()=>l&&t?Cfr(l.signals,t,typeof window<"u"?window.location.origin:""):[],[l,t]),d=_.useMemo(()=>l&&t?Afr(l.signals,t):null,[l,t]);return{item:l,dataset:t,timeline:o,valueShared:c,nextKit:d,isLoading:r,error:a,refetch:i}}function uos(){const{user:s}=hs(),t=Bt();return mt({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:oos,calculated_at:i.score.calculated_at}));for(let i=0;i{t.invalidateQueries({queryKey:["attract-score-snapshots"]}),n&&!r&&se.success(`Recalculated ${n} relationship score${n===1?"":"s"}`)},onError:n=>se.error(n.message??"Could not save scores")})}function cDe(){const{user:s}=hs();return at({queryKey:["attract-recommendations",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await tm.from("attract_recommendations").select("*").order("rank_score",{ascending:!1});if(n)throw n;return t??[]}})}function dDe(){const{user:s}=hs(),t=Bt();return mt({mutationFn:async n=>{if(!s)return{inserted:0,refreshed:0};const r=n.flatMap(u=>u.recommendations),{data:a,error:i}=await tm.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 tm.from("attract_recommendations").insert(o);if(u)throw u}for(const u of c)await tm.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=>se.error(n.message??"Could not sync recommendations")})}function Mfr(){const{user:s}=hs(),t=Bt(),n=()=>{t.invalidateQueries({queryKey:["attract-recommendations"]}),t.invalidateQueries({queryKey:["attract-followups"]}),t.invalidateQueries({queryKey:["attract-intel-data"]}),t.invalidateQueries({queryKey:["attract-activities"]})},r=mt({mutationFn:async({id:c,patch:d})=>{const{error:u}=await tm.from("attract_recommendations").update(d).eq("id",c);if(u)throw u},onSuccess:n,onError:c=>se.error(c.message)}),a=mt({mutationFn:async c=>{const{error:d}=await tm.from("attract_recommendations").update({status:"dismissed",dismissed_at:new Date().toISOString()}).eq("id",c);if(d)throw d},onSuccess:()=>{n(),se.success("Dismissed")}}),i=mt({mutationFn:async({id:c,days:d})=>{const u=new Date(Date.now()+d*864e5).toISOString(),{error:h}=await tm.from("attract_recommendations").update({status:"snoozed",snoozed_until:u}).eq("id",c);if(h)throw h},onSuccess:()=>{n(),se.success("Snoozed")}}),l=mt({mutationFn:async c=>{if(c.follow_up_id){const{data:h}=await tm.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 tm.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 tm.from("attract_recommendations").update({follow_up_id:d.id}).eq("id",c.id),{id:d.id,existed:!1}},onSuccess:c=>{n(),se.success(c.existed?"Follow-up already exists":"Follow-up created")},onError:c=>se.error(c.message)}),o=mt({mutationFn:async({rec:c,note:d})=>{const u=new Date().toISOString(),{error:h}=await tm.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 tm.from("attract_follow_ups").update({completed_at:u}).eq("id",c.follow_up_id).is("completed_at",null),await tm.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 tm.from("attract_recommendations").update({status:"completed",completed_at:u}).eq("id",c.id);if(m)throw m},onSuccess:()=>{n(),t.invalidateQueries({queryKey:["attract-score"]}),se.success("Logged — timeline and score updated")},onError:c=>se.error(c.message)});return{update:r,dismiss:a,snooze:i,createFollowUp:l,logCompleted:o}}function Pfr(){const{user:s}=hs(),t=Bt();return mt({mutationFn:async n=>{const{error:r}=await tm.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"]}),se.success("Logged")},onError:n=>se.error(n.message)})}const sAt={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 qit({score:s,className:t}){const n=sAt[s.band]??sAt.cooling;return e.jsxs(Oe,{variant:"outline",className:At("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 hos({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(qit,{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:At("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(Nl,{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(gS,{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(uN,{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 nAt({className:s}){const{intel:t}=gK(),[n,r]=_.useState(""),[a,i]=_.useState(!1),l=Fn(),o=_.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:At("relative",s),children:[e.jsx(Lr,{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(qit,{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 gUe=[{to:"/attract",label:"Today",icon:fN,exact:!0,hint:"Your five best moves"},{to:"/attract/agents",label:"Agents",icon:In,hint:"Your recruiting pipeline"},{to:"/attract/toolkit",label:"Toolkit",icon:Cx,hint:"Kits, scripts, objections"},{to:"/attract/calculator",label:"Calculator",icon:uj,hint:"Show them their numbers"},{to:"/attract/attract-page",label:"Attract Page",icon:$2,hint:"Your public join page"},{to:"/attract/results",label:"Results",icon:bl,hint:"Who joined, what worked"}];function Lfr(){const s=ru(),{settings:t,isLoading:n}=Uit(),r=!n&&!!t&&!t.onboarding_completed_at,a=s.pathname==="/attract/onboarding";if(r&&!a&&!s.pathname.startsWith("/attract/settings"))return e.jsx(fd,{to:"/attract/onboarding",replace:!0});const i=(o,c)=>{const d=o.icon;return e.jsx(o6,{to:o.to,end:o.exact,className:({isActive:u})=>At("group relative flex items-center gap-3 rounded-xl px-3 py-2.5 text-[13.5px] font-medium transition-all",u?"bg-white/[0.08] text-white ring-1 ring-inset ring-white/15":"text-slate-400 hover:bg-white/[0.04] hover:text-white"),children:({isActive:u})=>e.jsxs(e.Fragment,{children:[e.jsx("span",{className:At("absolute left-0 top-1/2 -translate-y-1/2 h-6 w-[3px] rounded-r-full bg-gradient-to-b from-violet-400 to-indigo-500 transition-opacity",u?"opacity-100":"opacity-0")}),e.jsx(d,{className:At("h-4 w-4 flex-shrink-0",u?"text-violet-300":"opacity-70 group-hover:opacity-100")}),e.jsxs("span",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:"block truncate",children:o.label}),e.jsx("span",{className:"block text-[10.5px] text-slate-500 font-normal truncate",children:o.hint})]})]})},o.to)},l=[{to:"/attract/follow-up",label:"Follow-Up Center"},{to:"/attract/opportunities",label:"Opportunities"},{to:"/attract/settings",label:"Settings"}];return e.jsxs("div",{className:"attract-root min-h-screen bg-[#F5F6FA] text-slate-900",children:[e.jsx("style",{children:` .attract-root { --a-primary: 139 92 246; --a-primary-strong: 109 40 217; --a-indigo: 79 70 229; --a-teal: 20 184 166; --a-green: 22 163 74; --a-orange: 249 115 22; --a-rose: 244 63 94; } .attract-root .btn-primary { background: linear-gradient(135deg, rgb(var(--a-primary)) 0%, rgb(var(--a-indigo)) 100%); } `}),e.jsxs("div",{className:"flex min-h-screen",children:[e.jsxs("aside",{className:"hidden lg:flex w-[264px] flex-col bg-[#0B0F1E] text-slate-200 border-r border-white/5 relative",children:[e.jsx("div",{className:"pointer-events-none absolute -top-24 -left-16 h-64 w-64 rounded-full bg-violet-700/20 blur-3xl"}),e.jsxs("div",{className:"relative px-5 py-6 border-b border-white/[0.07]",children:[e.jsxs(o6,{to:"/dashboard",className:"inline-flex items-center gap-1.5 text-[10.5px] uppercase tracking-[0.16em] text-slate-500 hover:text-white transition-colors",children:[e.jsx(ka,{className:"h-3 w-3"})," LevelUp Hub"]}),e.jsxs("div",{className:"mt-3.5 flex items-center gap-2.5",children:[e.jsx("div",{className:"h-9 w-9 rounded-xl bg-gradient-to-br from-violet-500 to-indigo-600 grid place-items-center shadow-lg shadow-violet-900/50",children:e.jsx(sP,{className:"h-4 w-4 text-white"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[14.5px] font-semibold tracking-tight text-white leading-none",children:"ATTRACT"}),e.jsx("div",{className:"text-[10.5px] text-slate-500 leading-tight mt-1",children:"Recruit agents to your team"})]})]})]}),e.jsx("div",{className:"relative px-3.5 pt-3.5",children:e.jsx(nAt,{})}),e.jsxs("nav",{className:"relative flex-1 overflow-y-auto py-3 px-2.5 space-y-1",children:[gUe.map(o=>i(o)),e.jsx("div",{className:"pt-5 pb-1 px-3 text-[10px] uppercase tracking-[0.16em] text-slate-600 font-semibold",children:"More"}),l.map(o=>e.jsx(o6,{to:o.to,className:({isActive:c})=>At("block rounded-lg px-3 py-2 text-[12.5px]",c?"bg-white/10 text-white":"text-slate-500 hover:text-white hover:bg-white/5"),children:o.label},o.to))]}),e.jsx("div",{className:"relative px-3.5 py-4 border-t border-white/5",children:e.jsxs("div",{className:"rounded-xl bg-gradient-to-br from-violet-600/20 to-indigo-600/10 ring-1 ring-inset ring-violet-500/20 p-3.5",children:[e.jsx("div",{className:"text-[11px] font-semibold text-violet-200",children:"One job"}),e.jsx("div",{className:"text-[11.5px] text-slate-400 mt-1 leading-snug",children:"Move one agent one step closer today. Verify compensation details before you share them."})]})})]}),e.jsxs("div",{className:"lg:hidden fixed top-0 inset-x-0 z-40 bg-[#0B0F1E]/95 backdrop-blur text-white px-4 py-3 flex items-center gap-3 border-b border-white/10",children:[e.jsx(o6,{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(sP,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[13px] font-semibold tracking-tight",children:"ATTRACT"}),e.jsx("div",{className:"text-[10px] text-slate-400",children:"Recruit agents to your team"})]}),e.jsxs(qg,{children:[e.jsx(zre,{asChild:!0,children:e.jsx("button",{className:"text-slate-300 p-1","aria-label":"Open menu",children:e.jsx(GA,{className:"h-5 w-5"})})}),e.jsx(hg,{side:"right",className:"bg-[#0B0F1E] text-slate-200 border-white/10 w-[280px] overflow-y-auto",children:e.jsxs("div",{className:"pt-6",children:[e.jsx(nAt,{className:"mb-4"}),e.jsx("div",{className:"space-y-1",children:gUe.map(o=>i(o))}),e.jsx("div",{className:"mt-5 mb-1 px-3 text-[10px] uppercase tracking-[0.16em] text-slate-600 font-semibold",children:"More"}),l.map(o=>e.jsx(o6,{to:o.to,className:({isActive:c})=>At("block rounded-lg px-3 py-2.5 text-[13px]",c?"bg-white/10 text-white":"text-slate-400 hover:bg-white/5"),children:o.label},o.to))]})})]})]}),e.jsx("div",{className:"lg:hidden fixed bottom-0 inset-x-0 z-40 bg-[#0B0F1E]/95 backdrop-blur border-t border-white/10 flex pb-[env(safe-area-inset-bottom)]",children:gUe.slice(0,5).map(o=>{const c=o.icon;return e.jsxs(o6,{to:o.to,end:o.exact,className:({isActive:d})=>At("flex-1 min-w-0 flex flex-col items-center gap-1 py-2.5 text-[10px]",d?"text-white":"text-slate-500"),children:[e.jsx(c,{className:"h-4 w-4"}),e.jsx("span",{className:"truncate max-w-[70px]",children:o.label})]},o.to)})}),e.jsx("main",{className:"flex-1 min-w-0 pt-16 lg:pt-0 pb-24 lg:pb-0",children:e.jsx("div",{className:"max-w-[1360px] mx-auto px-4 sm:px-6 lg:px-9 py-6 lg:py-9",children:e.jsx(rQe,{})},s.pathname)})]})]})}function $it(s=!0){const{intel:t,isLoading:n}=gK(),r=uos(),a=dDe(),i=_.useRef(!1);return _.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 Ifr(){const{user:s}=hs(),t=Bt(),n=at({queryKey:["attract-daily-plan",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:a,error:i}=await q.from("attract_daily_plan").select("*").order("sort_order");if(i)throw i;return a??[]}}),r=mt({mutationFn:async a=>{const i=!a.completed,{error:l}=await q.from("attract_daily_plan").update({completed:i,progress:i?a.target:0}).eq("id",a.id);if(l)throw l},onSuccess:()=>t.invalidateQueries({queryKey:["attract-daily-plan"]})});return{items:n.data??[],isLoading:n.isLoading,toggle:r}}const $Z=q;function WE(){const{user:s}=hs(),t=Bt(),n=at({queryKey:["attract-agents",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:d,error:u}=await q.from("attract_agents").select("*").order("updated_at",{ascending:!1});if(u)throw u;return d??[]}}),r=()=>{["attract-agents","attract-intel","attract-intelligence","attract-agent-intel","attract-activities","attract-followups","attract-recommendations","attract-score","attract_milestones","attract-daily-plan"].forEach(d=>t.invalidateQueries({queryKey:[d]}))},a=mt({mutationFn:async d=>{const u={...d,user_id:s.id},{data:h,error:m}=d.id?await q.from("attract_agents").update(u).eq("id",d.id).select().single():await q.from("attract_agents").insert(u).select().single();if(m)throw m;return h},onSuccess:()=>{r(),se.success("Saved")},onError:d=>se.error(d.message)}),i=mt({mutationFn:async({id:d,to_stage:u,from_stage:h})=>{const{error:m}=await q.from("attract_agents").update({stage:u}).eq("id",d);if(m)throw m;await q.from("attract_pipeline_history").insert({user_id:s.id,agent_id:d,from_stage:h??null,to_stage:u})},onSuccess:()=>r(),onError:d=>se.error(d.message)}),l=mt({mutationFn:async({id:d,values:u,changedLabels:h,previousStage:m})=>{const{stage:p,...f}=u;if(Object.keys(f).length){const{error:y}=await $Z.from("attract_agents").update(f).eq("id",d);if(y)throw y}if(p&&p!==m){const{error:y}=await $Z.from("attract_agents").update({stage:p}).eq("id",d);if(y)throw y;await $Z.from("attract_pipeline_history").insert({user_id:s.id,agent_id:d,from_stage:m??null,to_stage:p})}h.length&&await $Z.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(),se.success("Contact updated")},onError:d=>se.error(d.message??"Could not save contact")}),o=mt({mutationFn:async({id:d,archived:u})=>{const{error:h}=await $Z.from("attract_agents").update({is_archived:u}).eq("id",d);if(h)throw h},onSuccess:(d,u)=>{r(),se.success(u.archived?"Removed from active pipeline":"Restored to pipeline")},onError:d=>se.error(d.message)}),c=mt({mutationFn:async d=>{const{error:u}=await q.from("attract_agents").delete().eq("id",d);if(u)throw u},onSuccess:()=>{r(),se.success("Contact permanently deleted")},onError:d=>se.error(d.message)});return{agents:n.data??[],activeAgents:(n.data??[]).filter(d=>!d.is_archived),isLoading:n.isLoading,upsertAgent:a,saveAgentDetails:l,moveStage:i,archiveAgent:o,deleteAgent:c}}function uDe(){const{user:s}=hs(),t=Bt(),n=at({queryKey:["attract-followups",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:a,error:i}=await q.from("attract_follow_ups").select("*").order("due_at",{ascending:!0,nullsFirst:!1});if(i)throw i;return a??[]}}),r=mt({mutationFn:async a=>{const{error:i}=await q.from("attract_follow_ups").update({completed_at:new Date().toISOString()}).eq("id",a);if(i)throw i},onSuccess:()=>t.invalidateQueries({queryKey:["attract-followups"]})});return{followUps:n.data??[],isLoading:n.isLoading,complete:r}}function mos(s=12){const{user:t}=hs(),n=at({queryKey:["attract-activities",t==null?void 0:t.id,s],enabled:!!t,queryFn:async()=>{const{data:r,error:a}=await q.from("attract_activities").select("*").order("created_at",{ascending:!1}).limit(s);if(a)throw a;return r??[]}});return{activities:n.data??[],isLoading:n.isLoading}}const rAt={call:{icon:_a,label:"Call"},text:{icon:Hi,label:"Text"},email:{icon:ln,label:"Email"},dm:{icon:Or,label:"DM"},resource_share:{icon:fj,label:"Share a kit"},event_invitation:{icon:gy,label:"Invite to event"},personal_check_in:{icon:DQ,label:"Personal check-in"}},aAt={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 Dfr(s){var t;return((t=dos.find(n=>n.key===s))==null?void 0:t.blurb)??""}function pos(s){var t;return((t=dos.find(n=>n.key===s))==null?void 0:t.label)??s.replace(/_/g," ")}function F6e({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}=Mfr(),[p,f]=_.useState(!1),[y,v]=_.useState(s.draft_message??""),g=c.isPending||d.isPending||u.isPending||h.isPending||m.isPending,b=rAt[s.channel]??rAt.personal_check_in,j=s.suggested_due_at?new Date(s.suggested_due_at):null,S=j?j{c.mutate({id:s.id,patch:{draft_message:y}},{onSuccess:()=>{f(!1),se.success("Opening message updated")}})},E=async()=>{try{await navigator.clipboard.writeText(s.draft_message??""),se.success("Opening message copied — send it yourself from your phone or inbox")}catch{se.error("Could not copy — select the text manually")}};return e.jsx(ve,{className:At("rounded-2xl border-slate-200/70 bg-white shadow-sm overflow-hidden",o),children:e.jsxs("div",{className:"p-4 sm:p-5",children:[e.jsxs("div",{className:"flex items-start gap-3 flex-wrap",children:[e.jsx("div",{className:"h-10 w-10 rounded-xl bg-gradient-to-br from-violet-500 to-indigo-600 text-white grid place-items-center shadow-sm flex-shrink-0",children:e.jsx(b.icon,{className:"h-4.5 w-4.5","aria-hidden":!0})}),e.jsxs("div",{className:"flex-1 min-w-[180px]",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(Oe,{variant:"outline",className:At("rounded-full text-[10.5px] uppercase tracking-wider font-semibold ring-1 border-transparent",aAt[s.priority]??aAt.medium),children:s.priority}),e.jsx("span",{className:"text-[11px] text-violet-700 font-medium",children:pos(s.signal_group)}),s.is_demo&&e.jsx(Oe,{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(ir,{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(xi,{className:"h-3 w-3"})]}):e.jsx("span",{className:"font-medium text-slate-700",children:t}),n&&e.jsxs("span",{className:"capitalize",children:["· ",n.replace(/_/g," ")]}),e.jsxs("span",{children:["· ",b.label]}),j&&e.jsxs("span",{className:At("inline-flex items-center gap-1",S?"text-rose-600 font-medium":""),children:["· ",e.jsx(Gr,{className:"h-3 w-3"})," ",S?"Due now":`Do by ${j.toLocaleDateString()}`]})]})]}),e.jsxs(tu,{children:[e.jsx(su,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"rounded-full","aria-label":"More recommendation actions",children:e.jsx(Xx,{className:"h-4 w-4"})})}),e.jsxs(Od,{align:"end",className:"w-56",children:[e.jsx(PP,{children:"Recommendation"}),e.jsx(M0,{}),e.jsxs(ca,{onClick:()=>f(P=>!P),children:[e.jsx(Ya,{className:"h-4 w-4 mr-2"})," Edit opening message"]}),e.jsxs(ca,{onClick:E,children:[e.jsx(Ia,{className:"h-4 w-4 mr-2"})," Copy message"]}),e.jsx(M0,{}),e.jsxs(ca,{onClick:()=>u.mutate({id:s.id,days:3}),children:[e.jsx(Gr,{className:"h-4 w-4 mr-2"})," Snooze 3 days"]}),e.jsxs(ca,{onClick:()=>u.mutate({id:s.id,days:7}),children:[e.jsx(Gr,{className:"h-4 w-4 mr-2"})," Snooze 1 week"]}),e.jsxs(ca,{className:"text-rose-600",onClick:()=>d.mutate(s.id),children:[e.jsx(Qn,{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(hS,{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:Dfr(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(Ms,{value:y,onChange:P=>v(P.target.value),rows:4,className:"text-[13.5px]","aria-label":"Opening message"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{size:"sm",className:"rounded-full btn-primary text-white",onClick:C,disabled:g,children:"Save message"}),e.jsx(B,{size:"sm",variant:"ghost",className:"rounded-full",onClick:()=>{v(s.draft_message??""),f(!1)},children:"Cancel"})]})]}):e.jsxs("button",{onClick:()=>f(!0),className:"w-full text-left rounded-xl border border-slate-200 bg-white p-3 text-[13.5px] leading-relaxed text-slate-700 hover:border-violet-300 transition-colors",children:[s.draft_message||"No draft message yet — click to write one.",e.jsx("span",{className:"block text-[11px] text-violet-600 mt-1.5",children:"Click to edit before you send"})]})]}),(r||a)&&e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2 text-[11.5px]",children:[r&&e.jsxs("span",{className:"rounded-full bg-teal-50 text-teal-700 px-2.5 py-1",children:["Suggested kit: ",r]}),a&&e.jsxs("span",{className:"rounded-full bg-indigo-50 text-indigo-700 px-2.5 py-1",children:["Suggested event: ",a]})]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[e.jsxs(B,{size:"sm",className:"rounded-full btn-primary text-white",disabled:g,onClick:()=>m.mutate({rec:s}),children:[e.jsx(ea,{className:"h-3.5 w-3.5 mr-1.5"})," I did this"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",disabled:g,onClick:()=>h.mutate(s),children:[e.jsx(gy,{className:"h-3.5 w-3.5 mr-1.5"})," ",s.follow_up_id?"Follow-up created":"Create follow-up"]}),e.jsxs(B,{size:"sm",variant:"ghost",className:"rounded-full",onClick:E,children:[e.jsx(Ia,{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 Rfr({label:s="Nothing needs attention right now."}){return e.jsxs(ve,{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(ea,{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 cE=[{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"}],hDe={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"},fos=new Map;for(const s of[...cE,hDe])for(const t of s.legacy)fos.set(t,s);function dE(s){return s?fos.get(s)??cE[0]:cE[0]}function xos(s){return dE(s).label}function Vit(s){var n;return((n=[...cE,hDe].find(r=>r.key===s))==null?void 0:n.canonical)??"new_connection"}const yUe={first_name:"",last_name:"",brokerage:"",email:"",phone:"",city:"",source:"",notes:""};function gos({open:s,onOpenChange:t,defaultStageKey:n,onAdded:r}){const{upsertAgent:a,agents:i}=WE(),[l,o]=_.useState({...yUe}),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:Vit(n??"new_relationship"),temperature:"warm"},{onSuccess:h=>{o({...yUe}),t(!1),r==null||r(h==null?void 0:h.id)}})};return e.jsx(Ls,{open:s,onOpenChange:h=>{t(h),h||o({...yUe})},children:e.jsxs(Ps,{className:"max-w-lg",children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Add a relationship"}),e.jsx(_r,{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(J,{children:"First name *"}),e.jsx(xe,{value:l.first_name,onChange:c("first_name"),autoFocus:!0})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Last name"}),e.jsx(xe,{value:l.last_name,onChange:c("last_name")})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx(J,{children:"Brokerage"}),e.jsx(xe,{value:l.brokerage,onChange:c("brokerage"),placeholder:"Where they hang their license"})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Email"}),e.jsx(xe,{type:"email",value:l.email,onChange:c("email")})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Phone"}),e.jsx(xe,{value:l.phone,onChange:c("phone")})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Market"}),e.jsx(xe,{value:l.city,onChange:c("city"),placeholder:"City or area"})]}),e.jsxs("div",{children:[e.jsx(J,{children:"How you know each other"}),e.jsx(xe,{value:l.source,onChange:c("source"),placeholder:"Co-op deal, event, referral…"})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx(J,{children:"Note (optional)"}),e.jsx(Ms,{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(yr,{children:[e.jsx(B,{variant:"ghost",onClick:()=>t(!1),children:"Cancel"}),e.jsx(B,{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 Ffr(){const{user:s}=hs();return at({queryKey:["attract-score",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("attract_score_events").select("category, points, description, created_at");if(n)throw n;const r=t??[],a=r.reduce((l,o)=>l+(o.points??0),0),i={};for(const l of r)i[l.category]=(i[l.category]??0)+l.points;return{total:Math.min(a,100),rows:r,byCategory:i}}})}const Ofr=[{key:"relationships_added",label:"Relationships Added",icon:x0,target:15},{key:"follow_ups_completed",label:"Follow-Ups Completed",icon:Er,target:15},{key:"resources_shared",label:"Resources Shared",icon:bd,target:15},{key:"content_posted",label:"Agent Content Posted",icon:wh,target:15},{key:"events_connections",label:"Events / Connections",icon:dS,target:20},{key:"brokerage_conversations",label:"Brokerage Conversations",icon:WQ,target:20}];function zfr(){const{data:s}=Ffr(),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(ve,{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(Nl,{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:Ofr.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(B,{variant:"outline",size:"sm",className:"rounded-full",children:"View Score Breakdown"})})]})}function yos(s){const{user:t}=hs();return at({queryKey:["attract-events",t==null?void 0:t.id,s],enabled:!!t,queryFn:async()=>{let n=q.from("attract_events").select("*").eq("is_template",!1).order("starts_at",{ascending:!0});const{data:r,error:a}=await n;if(a)throw a;return r??[]}})}function Hit(s){return at({queryKey:["attract-event",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("attract_events").select("*").eq("id",s).single();if(n)throw n;return t}})}function vos(s){return at({queryKey:["attract-event-attendees",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("attract_event_attendees").select("*, attract_agents(id, first_name, last_name, primary_pillar, stage)").eq("event_id",s).order("created_at",{ascending:!1});if(n)throw n;return t??[]}})}function Bfr(s){return at({queryKey:["attract-event-invitations",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("attract_event_invitations").select("*, attract_agents(id, first_name, last_name)").eq("event_id",s).order("created_at",{ascending:!1});if(n)throw n;return t??[]}})}function Ufr(s){return at({queryKey:["attract-event-notes",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("attract_event_notes").select("*").eq("event_id",s).order("created_at",{ascending:!1});if(n)throw n;return t??[]}})}function bos(){return at({queryKey:["attract-event-templates"],queryFn:async()=>{const{data:s,error:t}=await q.from("attract_event_templates").select("*").order("title");if(t)throw t;return s??[]}})}function qfr(){const{user:s}=hs(),t=Bt();return mt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const r={user_id:s.id,title:n.title||"Untitled event",starts_at:n.starts_at||new Date(Date.now()+7*864e5).toISOString(),status:"draft",...n},{data:a,error:i}=await q.from("attract_events").insert(r).select().single();if(i)throw i;return a},onSuccess:()=>t.invalidateQueries({queryKey:["attract-events"]})})}function _os(){const s=Bt();return mt({mutationFn:async({id:t,patch:n})=>{const{data:r,error:a}=await q.from("attract_events").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["attract-events"]}),s.invalidateQueries({queryKey:["attract-event",t.id]})}})}function $fr(){const s=Bt();return mt({mutationFn:async t=>{const{error:n}=await q.from("attract_events").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["attract-events"]})})}function wos(){const{user:s}=hs(),t=Bt();return mt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const r={user_id:s.id,...n},{data:a,error:i}=n.id?await q.from("attract_event_attendees").update(r).eq("id",n.id).select().single():await q.from("attract_event_attendees").insert(r).select().single();if(i)throw i;return a},onSuccess:n=>{t.invalidateQueries({queryKey:["attract-event-attendees",n.event_id]}),t.invalidateQueries({queryKey:["attract-event",n.event_id]})}})}function Vfr(){const{user:s}=hs(),t=Bt();return mt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("attract_event_notes").insert({user_id:s.id,...n}).select().single();if(a)throw a;return r},onSuccess:n=>t.invalidateQueries({queryKey:["attract-event-notes",n.event_id]})})}function Hfr(){const{user:s}=hs(),t=Bt();return mt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("attract_event_invitations").insert({user_id:s.id,...n}).select().single();if(a)throw a;return r},onSuccess:n=>t.invalidateQueries({queryKey:["attract-event-invitations",n.event_id]})})}function Gfr(){const{user:s}=hs(),t=Bt();return mt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("attract_events").select("*").eq("id",n).single();if(a)throw a;const{id:i,public_slug:l,check_in_token:o,published_at:c,registration_count:d,attendance_count:u,created_at:h,updated_at:m,...p}=r,{data:f,error:y}=await q.from("attract_events").insert({...p,title:r.title+" (Copy)",status:"draft"}).select().single();if(y)throw y;return f},onSuccess:()=>t.invalidateQueries({queryKey:["attract-events"]})})}function mDe(s){return`${window.location.origin}/attract-event/${s}`}function Wfr(s,t){return`${window.location.origin}/attract-event-checkin/${s}?a=${encodeURIComponent(t)}`}function jos(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 Kfr(){const{data:s=[]}=yos(),t=s.slice(0,3);return e.jsxs(ve,{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(B,{variant:"outline",size:"sm",className:"rounded-full gap-1",children:[e.jsx(rn,{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(Kr,{className:"h-3 w-3"})," Virtual"]}):e.jsxs("span",{className:"flex items-center gap-1 truncate",children:[e.jsx(Xa,{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(dS,{className:"h-6 w-6 mx-auto text-slate-300 mb-2"}),e.jsx("div",{className:"text-sm",children:"No upcoming events yet."})]})]})]})}function Yfr(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 Zfr(){const s=new Date().getHours();return s<12?"Good morning":s<18?"Good afternoon":"Good evening"}const iAt=20;function Xfr(){const{user:s}=hs(),{intel:t,byId:n,isLoading:r}=gK(),{data:a=[],isLoading:i}=cDe(),l=dDe();$it();const{items:o,toggle:c}=Ifr(),{agents:d,isLoading:u}=WE(),{followUps:h}=uDe(),{activities:m}=mos(200),[p,f]=_.useState(!1),y=r||i||u,v=_.useMemo(()=>{const S=Date.now();return a.filter(C=>C.status==="open"||C.status==="snoozed"&&C.snoozed_until&&+new Date(C.snoozed_until)<=S).sort((C,E)=>E.rank_score-C.rank_score).slice(0,5)},[a]),g=_.useMemo(()=>{const S=new Date;S.setHours(0,0,0,0),S.setDate(S.getDate()-(S.getDay()+6)%7);const C=m.filter(M=>new Date(M.created_at)>=S).length,E=h.filter(M=>M.completed_at&&new Date(M.completed_at)>=S).length,P=C+E;return{moves:P,pct:Math.min(100,Math.round(P/iAt*100))}},[m,h]),b=S=>{var E;const C=(E=n.get(S))==null?void 0:E.agent;return C?[C.first_name,C.last_name].filter(Boolean).join(" "):"this relationship"},j=d.length>0;return e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsx(gos,{open:p,onOpenChange:f}),e.jsxs("div",{className:"relative overflow-hidden rounded-3xl bg-[#0B0F1E] text-white px-6 py-7 md:px-8 md:py-9 mb-7",children:[e.jsx("div",{className:"pointer-events-none absolute -top-24 -right-12 h-64 w-64 rounded-full bg-violet-600/30 blur-3xl"}),e.jsx("div",{className:"pointer-events-none absolute -bottom-28 left-6 h-56 w-56 rounded-full bg-indigo-500/20 blur-3xl"}),e.jsx("div",{className:"pointer-events-none absolute inset-0 opacity-[0.06]",style:{backgroundImage:"radial-gradient(circle at 20% 20%, white 1px, transparent 1px), radial-gradient(circle at 80% 60%, white 1px, transparent 1px)",backgroundSize:"46px 46px"}}),e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 rounded-full bg-white/10 ring-1 ring-inset ring-white/15 px-3 py-1 text-[10.5px] uppercase tracking-[0.18em] font-semibold text-violet-200 mb-3",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-violet-400"})," Today"]}),e.jsxs("h1",{className:"text-[26px] md:text-[34px] font-semibold tracking-tight leading-[1.12]",children:[Zfr(),", ",Yfr(s),". Here are your best moves today."]}),e.jsx("p",{className:"text-slate-300/90 mt-2 text-[14px]",children:"One agent, one step closer. That is the whole job today."}),e.jsxs("div",{className:"mt-6 rounded-2xl bg-white/[0.06] ring-1 ring-inset ring-white/10 px-4 py-3.5 backdrop-blur-sm",children:[e.jsxs("div",{className:"flex items-baseline justify-between gap-3",children:[e.jsxs("div",{className:"text-[13.5px] text-slate-300",children:[e.jsxs("span",{className:"font-semibold text-white tabular-nums",children:[g.moves," of ",iAt]})," meaningful moves completed this week"]}),e.jsx("span",{className:"text-[11px] uppercase tracking-wider text-slate-500",children:"This week"})]}),e.jsx("div",{className:"h-1.5 rounded-full bg-white/10 mt-2.5 overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-gradient-to-r from-violet-400 to-indigo-400 transition-all",style:{width:`${g.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"}),!y&&e.jsxs(B,{variant:"ghost",size:"sm",className:"rounded-full text-slate-500 h-8",onClick:()=>l.mutate(t),disabled:l.isPending,children:[e.jsx(uo,{className:At("h-3.5 w-3.5 mr-1.5",l.isPending&&"animate-spin")})," Refresh"]})]}),y?e.jsxs("div",{className:"space-y-3","aria-busy":"true",children:[e.jsx("div",{className:"text-[13px] text-slate-500",children:"Looking at your relationships…"}),[0,1,2].map(S=>e.jsx(cn,{className:"h-40 w-full rounded-2xl"},S))]}):v.length?e.jsx("div",{className:"space-y-3",children:v.map(S=>{var C;return e.jsx(F6e,{rec:S,agentName:b(S.agent_id),agentStage:xos((C=n.get(S.agent_id))==null?void 0:C.agent.stage)},S.id)})}):j?e.jsxs(ve,{className:"rounded-2xl border-dashed border-slate-300 bg-white/60 p-8 text-center",children:[e.jsx(un,{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(B,{className:"rounded-full btn-primary text-white",asChild:!0,children:e.jsx(ir,{to:"/attract/agents?view=attention",children:"See who’s gone quiet"})}),e.jsx(B,{variant:"outline",className:"rounded-full",asChild:!0,children:e.jsx(ir,{to:"/attract/toolkit/kits",children:"Share something useful"})})]})]}):e.jsxs(ve,{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(Pl,{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(B,{className:"rounded-full btn-primary text-white mt-4",onClick:()=>f(!0),children:[e.jsx(Pl,{className:"h-4 w-4 mr-1.5"})," Add your first relationship"]})]}),!!o.length&&e.jsxs(ve,{className:"mt-6 p-5 rounded-2xl border-slate-200/70 bg-white shadow-sm",children:[e.jsx("div",{className:"text-[13px] font-semibold uppercase tracking-wider text-slate-600 mb-3",children:"Your daily rhythm"}),e.jsx("ul",{className:"space-y-1",children:o.map(S=>e.jsxs("li",{onClick:()=>c.mutate(S),className:"flex items-center gap-3 px-2 py-2 rounded-xl hover:bg-slate-50 cursor-pointer transition-colors",children:[e.jsx($a,{checked:S.completed,className:"border-slate-300 data-[state=checked]:bg-violet-600 data-[state=checked]:border-violet-600"}),e.jsx("span",{className:At("flex-1 text-[13.5px]",S.completed?"line-through text-slate-400":"text-slate-800"),children:S.label}),e.jsxs("span",{className:"text-[11px] tabular-nums text-slate-400",children:[S.progress,"/",S.target]})]},S.id))})]}),e.jsxs("div",{className:"mt-6 grid grid-cols-2 lg:grid-cols-4 gap-3",children:[e.jsx(pue,{icon:Pl,label:"Add an agent",onClick:()=>f(!0)}),e.jsx(pue,{icon:uj,label:"Run their numbers",to:"/attract/calculator"}),e.jsx(pue,{icon:fj,label:"Share a value kit",to:"/attract/toolkit/kits"}),e.jsx(pue,{icon:o7,label:"Handle an objection",to:"/attract/toolkit/objections"})]}),e.jsxs("div",{className:"mt-6 space-y-3",children:[e.jsxs(f1,{children:[e.jsxs(x1,{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(dS,{className:"h-4 w-4 text-violet-500"})," Upcoming conversations & events"]}),e.jsx(tl,{className:"h-4 w-4 text-slate-400"})]}),e.jsx(g1,{className:"pt-3",children:e.jsx(Kfr,{})})]}),e.jsxs(f1,{children:[e.jsxs(x1,{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(un,{className:"h-4 w-4 text-violet-500"})," View coaching insights"]}),e.jsx(tl,{className:"h-4 w-4 text-slate-400"})]}),e.jsx(g1,{className:"pt-3",children:e.jsx(zfr,{})})]})]}),e.jsx("div",{className:"mt-6 flex justify-center",children:e.jsx(B,{variant:"ghost",className:"rounded-full text-violet-700",asChild:!0,children:e.jsxs(ir,{to:"/attract/agents?view=attention",children:["See everyone who needs attention ",e.jsx(La,{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 pue({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(ir,{to:n,children:a}):e.jsx("button",{className:"text-left w-full",onClick:r,children:a})}function KE({eyebrow:s,title:t,description:n,actions:r,stats:a,className:i}){return e.jsxs("div",{className:At("relative overflow-hidden rounded-3xl bg-[#0B0F1E] text-white mb-7 px-6 py-7 md:px-8 md:py-8",i),children:[e.jsx("div",{className:"pointer-events-none absolute -top-24 -right-16 h-64 w-64 rounded-full bg-violet-600/30 blur-3xl"}),e.jsx("div",{className:"pointer-events-none absolute -bottom-28 left-10 h-56 w-56 rounded-full bg-indigo-500/20 blur-3xl"}),e.jsx("div",{className:"pointer-events-none absolute inset-0 opacity-[0.06]",style:{backgroundImage:"radial-gradient(circle at 20% 20%, white 1px, transparent 1px), radial-gradient(circle at 80% 60%, white 1px, transparent 1px)",backgroundSize:"46px 46px"}}),e.jsxs("div",{className:"relative flex flex-col md:flex-row md:items-end md:justify-between gap-5",children:[e.jsxs("div",{className:"min-w-0",children:[s&&e.jsxs("div",{className:"inline-flex items-center gap-2 rounded-full bg-white/10 ring-1 ring-inset ring-white/15 px-3 py-1 text-[10.5px] uppercase tracking-[0.18em] font-semibold text-violet-200 mb-3",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-violet-400"}),s]}),e.jsx("h1",{className:"text-[26px] md:text-[34px] font-semibold tracking-tight leading-[1.12]",children:t}),n&&e.jsx("p",{className:"text-slate-300/90 mt-2 max-w-2xl text-[14px] leading-relaxed",children:n})]}),r&&e.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:r})]}),a&&a.length>0&&e.jsx("div",{className:"relative mt-6 grid grid-cols-2 lg:grid-cols-4 gap-2.5",children:a.map(l=>e.jsxs("div",{className:"rounded-2xl bg-white/[0.06] ring-1 ring-inset ring-white/10 px-4 py-3 backdrop-blur-sm",children:[e.jsx("div",{className:At("text-[22px] font-semibold tabular-nums leading-none",l.tone??"text-white"),children:l.value}),e.jsx("div",{className:"text-[11px] uppercase tracking-wider text-slate-400 mt-1.5",children:l.label})]},l.label))})]})}function Nos(){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 Qfr(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 A3=(s,t)=>{for(const n of t)if(s[n])return s[n];return""};function Jfr({open:s,onOpenChange:t}){const{user:n}=hs(),r=Bt(),[a,i]=_.useState([]),[l,o]=_.useState(""),[c,d]=_.useState(!1),u=()=>{i([]),o("")},h=async f=>{if(!f)return;const y=await f.text(),v=Qfr(y);if(!v.length){se.error("That file looks empty.");return}o(f.name),i(v)},m=a.map(f=>{const y=A3(f,["name","full name","full_name"]),v=A3(f,["first name","first_name","firstname"])||y.split(" ")[0]||"",g=A3(f,["last name","last_name","lastname"])||y.split(" ").slice(1).join(" ")||null;return{first_name:v,last_name:g,email:A3(f,["email","email address","e-mail"])||null,phone:A3(f,["phone","phone number","mobile","cell"])||null,brokerage:A3(f,["brokerage","company","office"])||null,city:A3(f,["city"])||null,state:A3(f,["state","province"])||null,notes:A3(f,["notes","note"])||null,source:"csv_import",stage:"prospect"}}).filter(f=>f.first_name),p=async()=>{if(!(!n||!m.length)){d(!0);try{const f=m.map(v=>({...v,user_id:n.id}));let y=0;for(let v=0;v{f||u(),t(f)},children:e.jsxs(Ps,{className:"sm:max-w-lg",children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Import relationships"}),e.jsx(_r,{children:"Upload a CSV. We'll look for columns like name, email, phone, brokerage, city, state and notes."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(xe,{type:"file",accept:".csv,text/csv",onChange:f=>{var y;return h((y=f.target.files)==null?void 0:y[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(uS,{className:"h-4 w-4"})," ",l]}),e.jsxs("div",{className:"text-muted-foreground",children:[m.length," of ",a.length," rows ready to import."]}),e.jsxs("div",{className:"text-muted-foreground text-xs",children:["Preview: ",m.slice(0,3).map(f=>`${f.first_name} ${f.last_name??""}`.trim()).join(", "),m.length>3?"…":""]})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{onClick:p,disabled:c||!m.length,children:[e.jsx(Oa,{className:"h-4 w-4 mr-1.5"}),c?"Importing…":`Import ${m.length||""}`.trim()]})]})]})})}const exr=["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"],txr={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"},J0=s=>typeof s=="string"&&s.trim()===""?null:s,dU=s=>{const t=s.trim();return t?/^https?:\/\//i.test(t)?t:`https://${t}`:null},sxr=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},VZ=s=>(s??"").replace(/[^\d]/g,""),nxr=s=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s.trim()),fue=s=>s?String(s).slice(0,10):"";function oAt(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:fue(s.birthday_on),work_anniversary_on:fue(s.work_anniversary_on),license_anniversary_on:fue(s.license_anniversary_on),next_follow_up_at:fue(s.next_follow_up_at)}}function uU({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 Gp({label:s,value:t,onChange:n,className:r,...a}){return e.jsxs("div",{className:r,children:[e.jsx(J,{className:"text-[12px] text-slate-600",children:s}),e.jsx(xe,{className:"mt-1",value:t,onChange:i=>n(i.target.value),...a})]})}function kos({agent:s,open:t,onOpenChange:n,onDeleted:r}){const{agents:a,saveAgentDetails:i,archiveAgent:l,deleteAgent:o}=WE(),[c,d]=_.useState({}),[u,h]=_.useState(!1),[m,p]=_.useState(!1),[f,y]=_.useState(!1);_.useEffect(()=>{s&&t&&(d(oAt(s)),y(!1))},[s==null?void 0:s.id,t]);const v=_.useMemo(()=>s?oAt(s):{},[s]),g=_.useMemo(()=>Object.keys(c).filter(M=>String(c[M]??"")!==String(v[M]??"")),[c,v]),b=g.length>0,j=(M,I)=>d(D=>({...D,[M]:I}));if(!s)return null;const S=M=>{if(!M&&b){h(!0);return}n(M)},C=()=>{var O;const M=(O=c.email)==null?void 0:O.trim().toLowerCase(),I=VZ(c.phone),D=`${c.first_name} ${c.last_name}`.trim().toLowerCase();return a.filter(V=>{var G;return V.id===s.id||V.is_archived?!1:!!(M&&((G=V.email)==null?void 0:G.toLowerCase())===M||I.length>=10&&VZ(V.phone)===I||D&&`${V.first_name} ${V.last_name??""}`.trim().toLowerCase()===D)})},E=()=>{var V,G,$;if(!((V=c.first_name)!=null&&V.trim())){se.error("First name is required");return}if((G=c.email)!=null&&G.trim()&&!nxr(c.email)){se.error("That email address looks incomplete");return}const M=C(),I=M.some(H=>{var Y,Z;return((Y=c.email)==null?void 0:Y.trim())&&((Z=H.email)==null?void 0:Z.toLowerCase())===c.email.trim().toLowerCase()||VZ(c.phone).length>=10&&VZ(H.phone)===VZ(c.phone)});if(M.length&&!f){y(!0),se.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:J0(c.last_name),preferred_name:J0(c.preferred_name),email:($=c.email)!=null&&$.trim()?c.email.trim().toLowerCase():null,phone:sxr(c.phone??""),website_url:dU(c.website_url??""),instagram_url:dU(c.instagram_url??""),linkedin_url:dU(c.linkedin_url??""),facebook_url:dU(c.facebook_url??""),other_url:dU(c.other_url??""),photo_url:dU(c.photo_url??""),brokerage:J0(c.brokerage),team_name:J0(c.team_name),city:J0(c.city),state:J0(c.state),postal_code:J0(c.postal_code),market_area:J0(c.market_area),source:J0(c.source),relationship_owner:J0(c.relationship_owner),temperature:c.temperature,primary_pillar:c.primary_pillar==="none"?null:c.primary_pillar,tags:String(c.tags??"").split(",").map(H=>H.trim()).filter(Boolean),goals:J0(c.goals),challenges:J0(c.challenges),interests:J0(c.interests),production_context:J0(c.production_context),notes:J0(c.notes),birthday_on:J0(c.birthday_on),work_anniversary_on:J0(c.work_anniversary_on),license_anniversary_on:J0(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},O={};if(g.forEach(H=>{H in D&&(O[H]=D[H])}),!Object.keys(O).length){n(!1);return}i.mutate({id:s.id,values:O,changedLabels:g.map(H=>txr[H]??H),previousStage:s.stage},{onSuccess:()=>n(!1)})},P=C();return e.jsxs(e.Fragment,{children:[e.jsx(qg,{open:t,onOpenChange:S,children:e.jsxs(hg,{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(P0,{className:"space-y-1 text-left",children:[e.jsxs(L0,{className:"text-white text-lg",children:["Edit ",[s.first_name,s.last_name].filter(Boolean).join(" ")]}),e.jsx(U9,{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(xl,{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(uU,{title:"Basic info",children:[e.jsx(Gp,{label:"First name *",value:c.first_name,onChange:M=>j("first_name",M)}),e.jsx(Gp,{label:"Last name",value:c.last_name,onChange:M=>j("last_name",M)}),e.jsx(Gp,{label:"Preferred name",value:c.preferred_name,onChange:M=>j("preferred_name",M),placeholder:"What they go by"}),e.jsx(Gp,{label:"Photo / headshot URL",value:c.photo_url,onChange:M=>j("photo_url",M),placeholder:"https://…"})]}),e.jsxs(uU,{title:"Contact & social",children:[e.jsx(Gp,{label:"Email",type:"email",value:c.email,onChange:M=>j("email",M)}),e.jsx(Gp,{label:"Phone",value:c.phone,onChange:M=>j("phone",M)}),e.jsx(Gp,{label:"Website",value:c.website_url,onChange:M=>j("website_url",M)}),e.jsx(Gp,{label:"Instagram",value:c.instagram_url,onChange:M=>j("instagram_url",M)}),e.jsx(Gp,{label:"LinkedIn",value:c.linkedin_url,onChange:M=>j("linkedin_url",M)}),e.jsx(Gp,{label:"Facebook",value:c.facebook_url,onChange:M=>j("facebook_url",M)}),e.jsx(Gp,{label:"Other link",value:c.other_url,onChange:M=>j("other_url",M),className:"sm:col-span-2"})]}),e.jsxs(uU,{title:"Brokerage & market",children:[e.jsx(Gp,{label:"Brokerage",value:c.brokerage,onChange:M=>j("brokerage",M)}),e.jsx(Gp,{label:"Team",value:c.team_name,onChange:M=>j("team_name",M)}),e.jsx(Gp,{label:"City",value:c.city,onChange:M=>j("city",M)}),e.jsx(Gp,{label:"State",value:c.state,onChange:M=>j("state",M)}),e.jsx(Gp,{label:"ZIP / postal code",value:c.postal_code,onChange:M=>j("postal_code",M)}),e.jsx(Gp,{label:"Market / service area",value:c.market_area,onChange:M=>j("market_area",M)})]}),e.jsxs(uU,{title:"Relationship intelligence",hint:"These drive scoring, recommendations, filters and reports.",children:[e.jsxs("div",{children:[e.jsx(J,{className:"text-[12px] text-slate-600",children:"Pipeline stage"}),e.jsxs(is,{value:c.stage,onValueChange:M=>j("stage",M),children:[e.jsx(rs,{className:"mt-1",children:e.jsx(ls,{})}),e.jsx(as,{children:exr.map(M=>e.jsx(He,{value:M,className:"capitalize",children:M.replace(/_/g," ")},M))})]})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-[12px] text-slate-600",children:"Temperature"}),e.jsxs(is,{value:c.temperature,onValueChange:M=>j("temperature",M),children:[e.jsx(rs,{className:"mt-1",children:e.jsx(ls,{})}),e.jsx(as,{children:["cold","warm","hot"].map(M=>e.jsx(He,{value:M,className:"capitalize",children:M},M))})]})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-[12px] text-slate-600",children:"Primary pillar"}),e.jsxs(is,{value:c.primary_pillar,onValueChange:M=>j("primary_pillar",M),children:[e.jsx(rs,{className:"mt-1",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"none",children:"Not set"}),["produce","influence","provide","connect"].map(M=>e.jsx(He,{value:M,className:"capitalize",children:M},M))]})]})]}),e.jsx(Gp,{label:"Source",value:c.source,onChange:M=>j("source",M),placeholder:"Event, referral, social…"}),e.jsx(Gp,{label:"Relationship owner",value:c.relationship_owner,onChange:M=>j("relationship_owner",M),placeholder:"You, or a teammate"}),e.jsx(Gp,{label:"Tags (comma separated)",value:c.tags,onChange:M=>j("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(Oe,{variant:"outline",className:"rounded-full text-[11px]",children:M},M))})]}),e.jsxs(uU,{title:"Important dates",hint:"Birthdays and anniversaries feed Milestones & Celebrations automatically — no duplicate entry needed.",children:[e.jsx(Gp,{label:"Birthday",type:"date",value:c.birthday_on,onChange:M=>j("birthday_on",M)}),e.jsx(Gp,{label:"Work anniversary",type:"date",value:c.work_anniversary_on,onChange:M=>j("work_anniversary_on",M)}),e.jsx(Gp,{label:"License anniversary",type:"date",value:c.license_anniversary_on,onChange:M=>j("license_anniversary_on",M)}),e.jsx(Gp,{label:"Next follow-up",type:"date",value:c.next_follow_up_at,onChange:M=>j("next_follow_up_at",M)})]}),e.jsxs(uU,{title:"Notes",children:[e.jsxs("div",{className:"sm:col-span-2",children:[e.jsx(J,{className:"text-[12px] text-slate-600",children:"Goals"}),e.jsx(Ms,{className:"mt-1",rows:2,value:c.goals,onChange:M=>j("goals",M.target.value)})]}),e.jsxs("div",{className:"sm:col-span-2",children:[e.jsx(J,{className:"text-[12px] text-slate-600",children:"Challenges"}),e.jsx(Ms,{className:"mt-1",rows:2,value:c.challenges,onChange:M=>j("challenges",M.target.value)})]}),e.jsxs("div",{className:"sm:col-span-2",children:[e.jsx(J,{className:"text-[12px] text-slate-600",children:"Interests"}),e.jsx(Ms,{className:"mt-1",rows:2,value:c.interests,onChange:M=>j("interests",M.target.value)})]}),e.jsxs("div",{className:"sm:col-span-2",children:[e.jsx(J,{className:"text-[12px] text-slate-600",children:"Production context"}),e.jsx(Ms,{className:"mt-1",rows:2,value:c.production_context,onChange:M=>j("production_context",M.target.value)})]}),e.jsxs("div",{className:"sm:col-span-2",children:[e.jsx(J,{className:"text-[12px] text-slate-600",children:"Personal notes"}),e.jsx(Ms,{className:"mt-1",rows:4,value:c.notes,onChange:M=>j("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(B,{variant:"outline",size:"sm",className:"rounded-full",onClick:()=>l.mutate({id:s.id,archived:!s.is_archived},{onSuccess:()=>n(!1)}),children:[e.jsx(by,{className:"h-3.5 w-3.5 mr-1.5"}),s.is_archived?"Restore to pipeline":"Remove from pipeline (archive)"]}),e.jsxs(B,{variant:"destructive",size:"sm",className:"rounded-full",onClick:()=>p(!0),children:[e.jsx(Sn,{className:"h-3.5 w-3.5 mr-1.5"})," Delete permanently"]})]}),e.jsx("p",{className:"text-[12px] text-rose-700/80",children:"Archiving keeps every note, touch and score. Deleting is permanent."})]})]}),e.jsxs("div",{className:"sticky bottom-0 bg-white/95 backdrop-blur border-t px-5 py-3 flex items-center justify-between gap-3",children:[e.jsx("span",{className:"text-[12px] text-slate-500",children:i.isPending?"Saving…":b?`${g.length} unsaved change${g.length>1?"s":""}`:"All changes saved"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{variant:"ghost",className:"rounded-full",onClick:()=>S(!1),children:[e.jsx(Qn,{className:"h-4 w-4 mr-1"})," Cancel"]}),e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600 text-white",disabled:!b||i.isPending,onClick:E,children:[i.isPending&&e.jsx(Ct,{className:"h-4 w-4 mr-1.5 animate-spin"}),"Save changes"]})]})]})]})}),e.jsx(Kl,{open:u,onOpenChange:h,children:e.jsxs(Ol,{children:[e.jsxs(zl,{children:[e.jsx(Ul,{children:"Discard unsaved changes?"}),e.jsxs(ql,{children:["You have ",g.length," unsaved change(s) on this contact."]})]}),e.jsxs(Bl,{children:[e.jsx($l,{children:"Keep editing"}),e.jsx(Ml,{onClick:()=>{h(!1),n(!1)},children:"Discard"})]})]})}),e.jsx(Kl,{open:m,onOpenChange:p,children:e.jsxs(Ol,{children:[e.jsxs(zl,{children:[e.jsx(Ul,{children:"Delete this contact permanently?"}),e.jsx(ql,{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($l,{children:"Cancel"}),e.jsx(Ml,{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 rxr(){const s=Fn(),[t,n]=Yl(),{agents:r,activeAgents:a,isLoading:i,moveStage:l}=WE(),{followUps:o,complete:c}=uDe(),{data:d=[]}=cDe();$it();const u=t.get("view")||"attention",h=$=>n(H=>(H.set("view",$),H),{replace:!0}),[m,p]=_.useState(""),[f,y]=_.useState("all"),[v,g]=_.useState(!1),[b,j]=_.useState(!1),[S,C]=_.useState(!1),[E,P]=_.useState(null),[M,I]=_.useState(null),D=$=>!!$.is_archived!==v||f!=="all"&&dE($.stage).key!==f?!1:m.trim()?`${$.first_name} ${$.last_name??""} ${$.brokerage??""} ${$.city??""} ${($.tags??[]).join(" ")} ${$.email??""}`.toLowerCase().includes(m.trim().toLowerCase()):!0,O=_.useMemo(()=>r.filter(D),[r,m,f,v]),V=_.useMemo(()=>{const $=If(new Date),H=o.filter(te=>!te.completed_at),Y=d.filter(te=>te.status==="open"),Z=H.filter(te=>te.due_at&&yS(new Date(te.due_at),$)),ne=H.filter(te=>te.due_at&&yy(new Date(te.due_at))),ce=a.filter(te=>{const ae=te.last_touch_at?new Date(te.last_touch_at):null;return ae?Date.now()-+ae>45*864e5:!!te.created_at&&Date.now()-+new Date(te.created_at)>14*864e5}),ie=a.filter(te=>!te.next_follow_up_at&&!H.some(ae=>ae.agent_id===te.id));return{overdue:Z,dueToday:ne,quiet:ce,noNextStep:ie,openRecs:Y}},[o,d,a]),G=$=>{const H=r.find(Y=>Y.id===$);return H?`${H.first_name} ${H.last_name??""}`.trim():"Someone"};return a.length,V.overdue.length,V.dueToday.length,V.quiet.length,e.jsxs("div",{children:[e.jsx(gos,{open:b,onOpenChange:j,onAdded:$=>$&&s(`/attract/agents/${$}`)}),e.jsx(Jfr,{open:S,onOpenChange:C}),e.jsx(kos,{agent:E?r.find($=>$.id===E.id)??E:null,open:!!E,onOpenChange:$=>!$&&P(null)}),e.jsx(KE,{eyebrow:"Agents",title:"Your recruiting pipeline",description:"Every agent you're building with, who needs attention today, and what you promised them.",stats:[{label:"In pipeline",value:a.length},{label:"Overdue",value:V.overdue.length,tone:V.overdue.length?"text-rose-400":void 0},{label:"Due today",value:V.dueToday.length,tone:V.dueToday.length?"text-amber-400":void 0},{label:"Gone quiet",value:V.quiet.length}],actions:e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"outline",className:"rounded-full bg-white/10 text-white border-white/20 hover:bg-white/20 hover:text-white",onClick:()=>C(!0),children:[e.jsx(Oa,{className:"h-3.5 w-3.5 mr-1.5"})," Import"]}),e.jsxs(B,{className:"rounded-full bg-white text-slate-900 hover:bg-slate-100",onClick:()=>j(!0),children:[e.jsx(rn,{className:"h-4 w-4 mr-1"})," Add agent"]})]})}),e.jsxs(ve,{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(Lr,{className:"h-4 w-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400"}),e.jsx(xe,{value:m,onChange:$=>p($.target.value),placeholder:"Search name, brokerage, market, tag…",className:"pl-9 rounded-full h-9","aria-label":"Search relationships"})]}),e.jsxs(is,{value:f,onValueChange:y,children:[e.jsx(rs,{className:"w-[190px] h-9 rounded-full text-[13px]",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All stages"}),[...cE,hDe].map($=>e.jsx(He,{value:$.key,children:$.label},$.key))]})]}),e.jsxs(B,{variant:v?"default":"outline",size:"sm",className:"rounded-full h-9",onClick:()=>g($=>!$),children:[e.jsx(by,{className:"h-3.5 w-3.5 mr-1.5"})," ",v?"Archived":"Active"]}),e.jsx("div",{className:"flex bg-slate-100 rounded-full p-0.5",children:[["attention","Needs attention"],["stages","Stages"],["list","List"]].map(([$,H])=>e.jsxs("button",{onClick:()=>h($),className:At("rounded-full h-8 px-3 text-[12.5px] font-medium transition-colors",u===$?"bg-white text-slate-900 shadow-sm":"text-slate-500 hover:text-slate-800"),children:[$==="stages"?e.jsx(sf,{className:"h-3.5 w-3.5 mr-1 inline"}):$==="list"?e.jsx(A0,{className:"h-3.5 w-3.5 mr-1 inline"}):null,H]},$))})]}),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($=>e.jsx(cn,{className:"h-24 w-full rounded-2xl"},$))]}):r.length?u==="attention"?e.jsxs("div",{className:"space-y-6",children:[e.jsx(xue,{title:"Overdue commitments",tone:"#f43f5e",items:V.overdue,render:$=>e.jsx(lAt,{f:$,name:G($.agent_id),onDone:()=>c.mutate($.id)},$.id)}),e.jsx(xue,{title:"Due today",tone:"#f97316",items:V.dueToday,render:$=>e.jsx(lAt,{f:$,name:G($.agent_id),onDone:()=>c.mutate($.id)},$.id)}),e.jsx(xue,{title:"Haven't talked in a while",tone:"#8b5cf6",items:V.quiet.filter(D),render:$=>e.jsx(vUe,{a:$,note:$.last_touch_at?`Last touch ${Hs(new Date($.last_touch_at),"MMM d")}`:"No meaningful touch yet"},$.id)}),e.jsx(xue,{title:"No next step set",tone:"#94a3b8",items:V.noNextStep.filter(D),render:$=>e.jsx(vUe,{a:$,note:"Decide one small next step"},$.id)}),!V.overdue.length&&!V.dueToday.length&&!V.quiet.length&&!V.noNextStep.length&&e.jsxs(ve,{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(Ji,{className:"w-full",children:[e.jsx("div",{className:"flex gap-4 pb-4",style:{minWidth:cE.length*290},children:cE.map($=>{const H=O.filter(Y=>dE(Y.stage).key===$.key);return e.jsxs("div",{className:"w-[275px] flex-shrink-0",onDragOver:Y=>{Y.preventDefault(),Y.dataTransfer.dropEffect="move"},onDrop:Y=>{Y.preventDefault();const Z=r.find(ne=>ne.id===M);Z&&dE(Z.stage).key!==$.key&&l.mutate({id:Z.id,to_stage:Vit($.key),from_stage:Z.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:$.color}}),e.jsx("h3",{className:"text-[13px] font-semibold text-slate-800",children:$.label}),e.jsx(Oe,{variant:"secondary",className:"text-[10px] h-5 px-1.5",children:H.length})]}),e.jsx("div",{className:"text-[11px] text-slate-400 mt-0.5 pl-4.5",children:$.help})]}),e.jsxs("div",{className:"rounded-2xl bg-slate-100/60 p-2 space-y-2 min-h-[180px]",children:[H.map(Y=>e.jsxs("div",{draggable:!0,onDragStart:()=>I(Y.id),onClick:()=>s(`/attract/agents/${Y.id}`),className:"bg-white rounded-xl p-3 cursor-pointer hover:shadow-md border-l-[3px] transition-all",style:{borderLeftColor:$.color},children:[e.jsxs("div",{className:"text-[13.5px] font-semibold text-slate-900 truncate",children:[Y.first_name," ",Y.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:Y.brokerage??"Brokerage not set"})]}),!Y.email&&!Y.phone&&e.jsx("div",{className:"mt-1.5 text-[10.5px] text-amber-700",children:"No contact info yet"})]},Y.id)),!H.length&&e.jsx("div",{className:"text-[11.5px] text-slate-400 text-center py-4",children:"Drag someone here"})]})]},$.key)})}),e.jsx(Bre,{orientation:"horizontal"})]}):e.jsxs(ve,{className:"rounded-2xl divide-y divide-slate-100 overflow-hidden",children:[O.map($=>e.jsx(vUe,{a:$,onEdit:()=>P($)},$.id)),!O.length&&e.jsx("div",{className:"p-10 text-center text-[13px] text-slate-500",children:"No one matches this view."})]}):e.jsx(axr,{onAdd:()=>j(!0)})]})}function xue({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(Oe,{variant:"secondary",className:"text-[10px]",children:n.length})]}),e.jsx(ve,{className:"rounded-2xl divide-y divide-slate-100 overflow-hidden",children:n.slice(0,12).map(r)})]}):null}function lAt({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($a,{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(ir,{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 vUe({a:s,note:t,onEdit:n}){var i,l;const r=dE(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(ir,{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(Xa,{className:"h-3 w-3"}),s.city]}),t&&e.jsxs("span",{className:"text-slate-400",children:["· ",t]})]})]}),e.jsx(Oe,{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(B,{variant:"ghost",size:"sm",className:"rounded-full",onClick:n,children:"Edit"})]})}function axr({onAdd:s}){return e.jsxs(ve,{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(x0,{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(B,{className:"rounded-full btn-primary text-white mt-4",onClick:s,children:[e.jsx(rn,{className:"h-4 w-4 mr-1.5"})," Add a relationship"]})]})}const ixr={call:_a,email:ln,coffee:H4,gift:Vo,text:ln,event:Qd};function oxr(){const{followUps:s,complete:t}=uDe(),{agents:n}=WE(),r=_.useMemo(()=>{const l=If(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);yS(p,l)?o.push(m):yy(p)?c.push(m):ZAs(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:Gr},{label:"Completed This Week",value:r.done.filter(l=>l.completed_at&&new Date(l.completed_at)>zh(new Date,-7)).length,tone:"text-emerald-600 bg-emerald-50",icon:Er}];return e.jsxs("div",{children:[e.jsx(KE,{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(ve,{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(Nos,{})}),e.jsxs("div",{className:"space-y-6",children:[e.jsx(HZ,{title:"Overdue",items:r.overdue,agentMap:a,onComplete:l=>t.mutate(l),tone:"rose"}),e.jsx(HZ,{title:"Today",items:r.today,agentMap:a,onComplete:l=>t.mutate(l),tone:"orange"}),e.jsx(HZ,{title:"Tomorrow",items:r.tomorrow,agentMap:a,onComplete:l=>t.mutate(l),tone:"violet"}),e.jsx(HZ,{title:"Later This Week",items:r.later,agentMap:a,onComplete:l=>t.mutate(l),tone:"slate"}),r.done.length>0&&e.jsx(HZ,{title:"Recently Completed",items:r.done.slice(0,5),agentMap:a,onComplete:()=>{},tone:"emerald",done:!0})]})]})}function HZ({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(Oe,{variant:"secondary",className:"text-[10px]",children:t.length})]}),e.jsx(ve,{className:"rounded-2xl divide-y divide-slate-100 overflow-hidden",children:t.map(o=>{const c=n.get(o.agent_id),d=ixr[o.touch_type??""]??ln;return e.jsxs("div",{className:`flex items-start gap-3 p-4 hover:bg-slate-50 ${i?"opacity-60":""}`,children:[e.jsx($a,{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(B,{variant:"ghost",size:"sm",children:"Snooze"})]},o.id)})})]})}function lxr(){const{user:s}=hs(),t=at({queryKey:["attract-resources",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:r,error:a}=await q.from("attract_resources").select("*").order("created_at",{ascending:!1});if(a)throw a;return r??[]}}),n=at({queryKey:["attract-resource-shares",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:r,error:a}=await q.from("attract_resource_shares").select("*").order("created_at",{ascending:!1});if(a)throw a;return r??[]}});return{resources:t.data??[],shares:n.data??[],isLoading:t.isLoading}}const cxr={pdf:Fr,link:vd,video:Kr,tool:Y4,guide:Sx},dxr={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 uxr(){const{resources:s,isLoading:t}=lxr(),[n,r]=_.useState(""),[a,i]=_.useState("all"),l=Array.from(new Set(s.map(c=>c.category).filter(Boolean))),o=s.filter(c=>(a==="all"||c.category===a)&&(!n||`${c.title} ${c.description??""}`.toLowerCase().includes(n.toLowerCase())));return e.jsxs("div",{children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-5",children:[e.jsx("div",{className:"text-[13px] text-slate-500",children:"Every resource, script, and tool you use — ready to share in one click."}),e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",children:[e.jsx(rn,{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(Lr,{className:"h-4 w-4 text-slate-400 absolute left-3 top-1/2 -translate-y-1/2"}),e.jsx(xe,{value:n,onChange:c=>r(c.target.value),placeholder:"Search resources…",className:"pl-9 rounded-full bg-white"})]}),e.jsxs("div",{className:"flex gap-1.5 flex-wrap",children:[e.jsx(B,{size:"sm",variant:a==="all"?"default":"outline",className:"rounded-full h-8",onClick:()=>i("all"),children:"All"}),l.map(c=>e.jsx(B,{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(ve,{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=cxr[c.resource_type]??Fr;return e.jsxs(ve,{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(Oe,{className:`${dxr[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(B,{size:"sm",variant:"outline",className:"rounded-full gap-1",children:[e.jsx(bd,{className:"h-3.5 w-3.5"})," Share"]})]})]},c.id)})})]})}const Sos=[{step:"First outreach",icon:Hi,color:"#7c3aed",title:"After you meet at a closing or showing",channel:"Text",body:"Hey {{first_name}} — {{your_name}} from the {{address}} deal. You were easy to work with, which is rarer than it should be. I keep a short list of agents I like doing business with and you made it. Coffee sometime in the next couple weeks?"},{step:"First outreach",icon:Hi,color:"#7c3aed",title:"Congratulate a recent close",channel:"DM",body:"Saw your closing at {{property}} — nice work {{first_name}}. Those aren’t easy in this market. If you ever want to trade notes on what’s actually getting deals across the line right now, I’m always up for a coffee."},{step:"Value first",icon:Or,color:"#4f46e5",title:"Send something useful, no ask",channel:"Email",body:`Hey {{first_name}} — I put this together for my own business and figured you’d get more out of it than my hard drive will: {{resource_link}} No agenda. If it saves you an hour this week, that’s a win.`},{step:"Value first",icon:Or,color:"#4f46e5",title:"Share the kit after a good conversation",channel:"Email",body:`Great talking today {{first_name}}. Here’s the {{kit_name}} I mentioned — everything in there is what I actually run in my business: {{kit_link}} Steal any of it. If a piece of it doesn’t make sense, text me and I’ll walk you through it.`},{step:"The coffee ask",icon:H4,color:"#0d9488",title:"Direct, low-pressure invite",channel:"Text",body:"Hey {{first_name}}, any chance you’re free for a 30-minute coffee in the next two weeks? No agenda — I just want to hear how the year is actually going for you."},{step:"The coffee ask",icon:H4,color:"#0d9488",title:'When they ask "what’s this about?"',channel:"Text",body:"Honestly? I like how you work and I think we’d both get something out of knowing each other better. If at some point it makes sense to talk about what I’m building, we can — but that’s not why I’m asking."},{step:"The numbers talk",icon:wv,color:"#c9a84c",title:"Open the comp conversation",channel:"Text",body:"{{first_name}} — you mentioned fees eating into your year. I have a calculator that runs your actual production against what you’d have kept here. Takes four minutes and I’ll send you the sheet either way. Want me to run it?"},{step:"The numbers talk",icon:wv,color:"#c9a84c",title:"Follow-up with the one-pager",channel:"Email",body:`Here’s the breakdown we ran, {{first_name}}. Same production, two different outcomes. {{summary}} No pressure and no follow-up spam. If you want to walk through the assumptions, I’m around.`},{step:"When they go quiet",icon:QA,color:"#f97316",title:"After they ghost you",channel:"Text",body:"Hey {{first_name}} — no reply needed. Assuming things got busy, which is a good problem. I’ll check back in a few months. If anything changes before then, you know where I am."},{step:"When they go quiet",icon:QA,color:"#f97316",title:"The quarterly re-open",channel:"Text",body:"Hey {{first_name}} — quarter’s wrapping up. How did it land for you? Genuinely curious, no ask attached."},{step:"When they say no",icon:QA,color:"#94a3b8",title:"Keep the relationship, drop the pitch",channel:"Text",body:"Totally respect that {{first_name}}. I’m not going anywhere and neither is the offer. I’d still like to stay in touch — I’ll send you anything useful I come across, and if the situation ever changes, one text is all it takes."},{step:"After they join",icon:wv,color:"#16a34a",title:"Day one welcome",channel:"Text",body:"Welcome aboard {{first_name}}. Here’s what happens this week: 1) onboarding call Tuesday, 2) database imported by Thursday, 3) your first campaign live by Friday. I’ll drive all three. You just keep selling."}],hxr=["All",...Array.from(new Set(Sos.map(s=>s.step)))];function mxr(){const[s,t]=_.useState(""),[n,r]=_.useState("All"),a=_.useMemo(()=>Sos.filter(l=>(n==="All"||l.step===n)&&(!s||`${l.title} ${l.body} ${l.step}`.toLowerCase().includes(s.toLowerCase()))),[s,n]),i=l=>{navigator.clipboard.writeText(l),se.success("Script copied")};return e.jsxs("div",{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-5",children:[e.jsxs("div",{className:"relative flex-1 min-w-[240px] max-w-sm",children:[e.jsx(Lr,{className:"h-4 w-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400"}),e.jsx(xe,{value:s,onChange:l=>t(l.target.value),placeholder:"Search scripts…",className:"pl-9 rounded-full h-9 bg-white","aria-label":"Search scripts"})]}),e.jsx("div",{className:"flex gap-1.5 flex-wrap",children:hxr.map(l=>e.jsx("button",{onClick:()=>r(l),className:At("rounded-full h-9 px-3.5 text-[12.5px] font-medium border transition-colors",n===l?"bg-slate-900 text-white border-slate-900":"bg-white text-slate-600 border-slate-200 hover:border-slate-300"),children:l},l))})]}),e.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:a.map(l=>{const o=l.icon;return e.jsxs(ve,{className:"p-5 rounded-2xl border-slate-200/80 flex flex-col",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex items-start gap-3 min-w-0",children:[e.jsx("div",{className:"h-9 w-9 rounded-xl grid place-items-center flex-shrink-0",style:{background:`${l.color}18`,color:l.color},children:e.jsx(o,{className:"h-4 w-4"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[14.5px] font-semibold text-slate-900 leading-snug",children:l.title}),e.jsx("div",{className:"text-[11.5px] text-slate-500 mt-0.5",children:l.step})]})]}),e.jsx(Oe,{variant:"outline",className:"rounded-full text-[10px] uppercase tracking-wider flex-shrink-0",children:l.channel})]}),e.jsx("p",{className:"mt-4 text-[13.5px] text-slate-700 leading-relaxed whitespace-pre-wrap",children:l.body}),e.jsx("div",{className:"mt-auto pt-4 flex justify-end",children:e.jsxs(B,{variant:"outline",size:"sm",className:"rounded-full gap-1.5",onClick:()=>i(l.body),children:[e.jsx(Ia,{className:"h-3.5 w-3.5"})," Copy"]})})]},l.title)})}),e.jsx("p",{className:"mt-6 text-center text-[11.5px] text-slate-400 max-w-xl mx-auto",children:"Merge fields are placeholders — replace them with real details before sending. A script that sounds like a script gets ignored."})]})}const pxr=s=>s.toLocaleString("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0});function fxr(){const{agents:s}=WE(),{activities:t}=mos(365),n=_.useMemo(()=>s.filter(c=>dE(c.stage).key==="joined"),[s]),r=_.useMemo(()=>{const c=JCs(new Date),d=$Qe(new Date),u=v=>v.joined_at?new Date(v.joined_at):new Date(v.updated_at),h=n.filter(v=>u(v)>=c).length,m=n.filter(v=>u(v)>=d).length,p=n.map(v=>pv(u(v),new Date(v.created_at))).filter(v=>Number.isFinite(v)&&v>=0),f=p.length?Math.round(p.reduce((v,g)=>v+g,0)/p.length):null,y=n.reduce((v,g)=>v+(g.est_revenue_share??0),0);return{thisQuarter:h,thisYear:m,avgDays:f,revShare:y}},[n]),a=_.useMemo(()=>{const c=s.filter(d=>!d.is_archived);return cE.map(d=>({stage:d.label,count:c.filter(u=>dE(u.stage).key===d.key).length,color:d.color}))},[s]),i=_.useMemo(()=>{const c=s.filter(h=>!h.is_archived),d=c.length,u=c.filter(h=>dE(h.stage).key==="joined").length;return d?Math.round(u/d*100):0},[s]),l=_.useMemo(()=>Array.from({length:12},(d,u)=>{const h=new Date;return h.setDate(1),h.setMonth(h.getMonth()-(11-u)),h}).map(d=>{const u=new Date(d);u.setMonth(u.getMonth()+1);const h=t.filter(p=>{const f=new Date(p.created_at);return f>=d&&f{const f=p.joined_at?new Date(p.joined_at):new Date(p.updated_at);return f>=d&&f{var d;const c=new Map;for(const u of n){const h=((d=u.source)==null?void 0:d.trim())||"Unknown";c.set(h,(c.get(h)??0)+1)}return Array.from(c.entries()).map(([u,h])=>({source:u,count:h})).sort((u,h)=>h.count-u.count).slice(0,6)},[n]);return e.jsxs("div",{children:[e.jsx(KE,{eyebrow:"Results",title:"Who joined, and what actually got them there.",description:"No score, no gamification — just the numbers that tell you where to spend next month.",stats:[{label:"Joined this quarter",value:r.thisQuarter,tone:"text-emerald-400"},{label:"Joined this year",value:r.thisYear},{label:"Avg. days to join",value:r.avgDays??"—"},{label:"Est. annual rev share",value:pxr(r.revShare)}]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-5",children:[e.jsxs(ve,{className:"p-6 rounded-2xl",children:[e.jsxs("div",{className:"flex items-baseline justify-between mb-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider text-slate-500",children:"Pipeline"}),e.jsx("div",{className:"text-[16px] font-semibold text-slate-900 mt-0.5",children:"Where everyone stands"})]}),e.jsxs(Oe,{variant:"outline",className:"rounded-full",children:[i,"% joined"]})]}),e.jsx(jb,{width:"100%",height:260,children:e.jsxs(BW,{data:a,layout:"vertical",margin:{left:28},children:[e.jsx(Mv,{type:"number",tick:{fontSize:11},allowDecimals:!1}),e.jsx(Pv,{dataKey:"stage",type:"category",tick:{fontSize:11},width:120}),e.jsx(Mf,{cursor:{fill:"#f8fafc"}}),e.jsx(H_,{dataKey:"count",radius:[0,8,8,0],children:a.map((c,d)=>e.jsx(tz,{fill:c.color},d))})]})})]}),e.jsxs(ve,{className:"p-6 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider text-slate-500",children:"Momentum"}),e.jsx("div",{className:"text-[16px] font-semibold text-slate-900 mt-0.5 mb-4",children:"Touches vs. joins · last 12 months"}),e.jsx(jb,{width:"100%",height:260,children:e.jsxs(Qst,{data:l,children:[e.jsx(Mv,{dataKey:"month",tick:{fontSize:11}}),e.jsx(Pv,{tick:{fontSize:11},allowDecimals:!1}),e.jsx(Mf,{}),e.jsx(BP,{type:"monotone",dataKey:"touches",stroke:"#8b5cf6",strokeWidth:2.5,dot:!1,name:"Touches"}),e.jsx(BP,{type:"monotone",dataKey:"joins",stroke:"#16a34a",strokeWidth:2.5,dot:{r:3},name:"Joins"})]})})]}),e.jsxs(ve,{className:"p-6 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider text-slate-500",children:"Attribution"}),e.jsx("div",{className:"text-[16px] font-semibold text-slate-900 mt-0.5 mb-4",children:"What produced the joins"}),o.length===0?e.jsx("div",{className:"text-[13px] text-slate-500 py-10 text-center",children:"No one has joined yet. Sources appear here the moment they do."}):e.jsx("div",{className:"space-y-2.5",children:o.map(c=>{const d=o[0].count||1;return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between text-[13px] mb-1",children:[e.jsx("span",{className:"text-slate-700 capitalize",children:c.source.replace(/_/g," ")}),e.jsx("span",{className:"font-semibold text-slate-900 tabular-nums",children:c.count})]}),e.jsx("div",{className:"h-2 rounded-full bg-slate-100 overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-gradient-to-r from-violet-500 to-indigo-500",style:{width:`${c.count/d*100}%`}})})]},c.source)})})]}),e.jsxs(ve,{className:"p-6 rounded-2xl",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(wl,{className:"h-4 w-4 text-amber-500"}),e.jsx("div",{className:"text-[16px] font-semibold text-slate-900",children:"Agents who joined"})]}),n.length===0?e.jsx("div",{className:"text-[13px] text-slate-500 py-10 text-center",children:"Your first join shows up here — with how long it took and where it came from."}):e.jsx("div",{className:"divide-y divide-slate-100",children:n.slice(0,8).map(c=>{const d=c.joined_at?new Date(c.joined_at):new Date(c.updated_at),u=pv(d,new Date(c.created_at));return e.jsxs(ir,{to:`/attract/agents/${c.id}`,className:"flex items-center justify-between gap-3 py-3 group",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"text-[13.5px] font-medium text-slate-900 truncate",children:[c.first_name," ",c.last_name]}),e.jsxs("div",{className:"text-[12px] text-slate-500 truncate",children:[Hs(d,"MMM d, yyyy"),u>=0?` · ${u} days from first touch`:""]})]}),e.jsx(La,{className:"h-4 w-4 text-slate-300 group-hover:text-violet-600 transition-colors"})]},c.id)})}),e.jsx(B,{variant:"outline",className:"rounded-full w-full mt-4",asChild:!0,children:e.jsx(ir,{to:"/attract/agents",children:"Open the pipeline"})})]})]})]})}function xxr(){const{settings:s,upsert:t,resetOnboarding:n}=Uit(),[r,a]=_.useState({});_.useEffect(()=>{s&&a(s)},[s]);const i=l=>a({...r,...l});return e.jsxs("div",{className:"max-w-3xl",children:[e.jsx(KE,{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(ve,{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(ku,{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(B,{asChild:!0,variant:"outline",className:"rounded-full",children:e.jsx(ir,{to:"/attract/settings",children:"View plan"})}),e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:()=>n.mutate(),children:[e.jsx(Tx,{className:"h-4 w-4 mr-1.5"})," Rerun onboarding"]})]})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(ve,{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(J,{children:"Elevator introduction"}),e.jsx(Ms,{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(J,{children:"Focus market"}),e.jsx(xe,{value:r.focus_market??"",onChange:l=>i({focus_market:l.target.value}),placeholder:"Orange County, CA"})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Annual attraction goal"}),e.jsx(xe,{type:"number",value:r.annual_attract_goal??"",onChange:l=>i({annual_attract_goal:Number(l.target.value)||null}),placeholder:"12"})]})]}),e.jsxs("div",{children:[e.jsx(J,{children:'Your "why" for attraction'}),e.jsx(Ms,{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(ve,{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(J,{children:"Hot leads follow-up"}),e.jsxs(is,{value:String(r.hot_cadence_days??3),onValueChange:l=>i({hot_cadence_days:Number(l)}),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"1",children:"Every day"}),e.jsx(He,{value:"3",children:"Every 3 days"}),e.jsx(He,{value:"7",children:"Every week"})]})]})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Warm leads follow-up"}),e.jsxs(is,{value:String(r.warm_cadence_days??14),onValueChange:l=>i({warm_cadence_days:Number(l)}),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"7",children:"Weekly"}),e.jsx(He,{value:"14",children:"Every 2 weeks"}),e.jsx(He,{value:"30",children:"Monthly"})]})]})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Long-term nurture"}),e.jsxs(is,{value:String(r.longterm_cadence_days??60),onValueChange:l=>i({longterm_cadence_days:Number(l)}),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"30",children:"Monthly"}),e.jsx(He,{value:"60",children:"Every 2 months"}),e.jsx(He,{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(fn,{checked:r.weekly_digest_enabled??!0,onCheckedChange:l=>i({weekly_digest_enabled:l})})]})})]})]}),e.jsxs(ve,{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(B,{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 cAt=[{to:"/attract/toolkit/kits",label:"Value kits",icon:Nh,blurb:"Bundles worth opening"},{to:"/attract/toolkit/scripts",label:"Scripts",icon:WA,blurb:"What to say, word for word"},{to:"/attract/toolkit/objections",label:"Objections",icon:o7,blurb:"Answers that hold up"},{to:"/attract/toolkit/events",label:"Events",icon:dS,blurb:"Rooms worth being in"},{to:"/attract/toolkit/content",label:"Content",icon:Qx,blurb:"Posts that attract"},{to:"/attract/toolkit/resources",label:"Library",icon:fj,blurb:"Everything else you share"}];function gxr(){const{pathname:s}=ru(),t=cAt.find(n=>s.startsWith(n.to));return e.jsxs("div",{children:[e.jsx(KE,{eyebrow:"Recruiting toolkit",title:"Everything you hand an agent — in one place.",description:(t==null?void 0:t.blurb)??"Kits, scripts, objection answers, events and content. Nothing else to hunt for."}),e.jsx("div",{className:"-mt-2 mb-7 overflow-x-auto",children:e.jsx("div",{className:"inline-flex min-w-full gap-1 rounded-2xl bg-white p-1.5 border border-slate-200/80 shadow-sm",children:cAt.map(n=>{const r=n.icon;return e.jsxs(o6,{to:n.to,className:({isActive:a})=>At("group relative flex items-center gap-2 rounded-xl px-4 py-2.5 text-[13px] font-medium whitespace-nowrap transition-all",a?"bg-gradient-to-r from-violet-600 to-indigo-600 text-white shadow-md shadow-violet-600/20":"text-slate-600 hover:bg-slate-50 hover:text-slate-900"),children:[e.jsx(r,{className:"h-4 w-4 opacity-90"}),n.label]},n.to)})})}),e.jsx(rQe,{})]})}const Cos=[{category:"Model",q:'"Isn’t this just an MLM?"',opener:"Fair question — and the answer is no, and here is the actual difference.",a:"You are paid on real estate commissions you earn. Revenue share is a marketing expense the brokerage pays out of company dollar for agents you personally attract. You never buy inventory, never pay to join a downline, and you never have to recruit anyone to make money here. If you sell zero and attract zero, you still keep more of your commission than you do today."},{category:"Model",q:'"What does it actually cost me?"',opener:"Let me show you your exact numbers instead of a brochure.",a:"A one-time start-up fee, a small monthly technology fee, and a per-transaction broker review fee until you cap. No desk fee, no royalty fee, no franchise fee. Run your last 12 months through the calculator with me and you will see the real difference in take-home, not a hypothetical."},{category:"Brand",q:'"I’d lose my brand and my team."',opener:"Your name stays your name.",a:"You keep your brand, your team, your logo and your database. Branding requirements are minimal, and your marketing stays yours. Most agents who move end up building their brand harder here because nothing is taken off the top to fund someone else’s."},{category:"Loyalty",q:'"I’m loyal to my broker."',opener:"That says a lot about you, and I would never ask you to be disloyal.",a:"Loyalty is the reason I want you on my team — you are exactly the kind of person I would want in the room. But loyalty runs both ways. Look at what you paid in splits and fees last year and ask whether that investment came back to you. If it did, stay. If it did not, you owe it to your family to at least see the math."},{category:"Support",q:'"I need a broker I can actually reach."',opener:"You get two lines of support, not a call center.",a:"State broker support is available and free — real brokers, same day. And you get me directly. Text me at 9pm on a Sunday when a deal is falling apart and I answer. That is the part of this you cannot get from a sign-up link."},{category:"Support",q:'"There’s no office. I’d be on my own."',opener:"You would have more people around you, not fewer.",a:"There are 80+ hours of live training every week and a mastermind you can join from anywhere. Most agents in a physical office talk to two people a week. The agents who move usually tell me they feel less alone, not more — because the room is always open."},{category:"Timing",q:'"What happens to my pending deals?"',opener:"We map every pending file before you sign anything.",a:"Most agents close pendings at their current brokerage, or transfer them depending on their independent contractor agreement. We go through them one by one so there are no surprises and no lost commission."},{category:"Timing",q:'"Now isn’t a good time."',opener:"Then let us pick the time together instead of dropping it.",a:"There is never a clean window in this business. But the transition is typically 24 to 72 hours — application, license transfer, MLS update. If you are mid-listing season, we start the paperwork the week after your next closing. Put a date on the calendar and I will handle the checklist."},{category:"Money",q:'"I’m already capped where I am."',opener:"Then this year is the exact right year to look.",a:"Capping resets on your anniversary. If you move right after your cap year ends, you keep the benefit of the cap you already paid for and start fresh under a lower one. Send me your anniversary date and I will show you the ideal move window."},{category:"Money",q:'"Revenue share sounds too good to be true."',opener:"It is a marketing budget, not magic.",a:"Every brokerage spends money attracting agents — billboards, recruiters, sign-on bonuses. This one pays that budget to the agents who bring people instead. It is paid monthly out of company dollar on production, it is capped per tier, and it is willable. That is the whole mechanism."}],yxr=["All",...Array.from(new Set(Cos.map(s=>s.category)))];function vxr(){const[s,t]=_.useState(""),[n,r]=_.useState("All"),a=_.useMemo(()=>Cos.filter(l=>(n==="All"||l.category===n)&&(!s||`${l.q} ${l.a} ${l.opener}`.toLowerCase().includes(s.toLowerCase()))),[s,n]),i=l=>{navigator.clipboard.writeText(`${l.opener} ${l.a}`),se.success("Answer copied")};return e.jsxs("div",{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-5",children:[e.jsxs("div",{className:"relative flex-1 min-w-[240px] max-w-sm",children:[e.jsx(Lr,{className:"h-4 w-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400"}),e.jsx(xe,{value:s,onChange:l=>t(l.target.value),placeholder:"Search an objection…",className:"pl-9 rounded-full h-9 bg-white","aria-label":"Search objections"})]}),e.jsx("div",{className:"flex gap-1.5 flex-wrap",children:yxr.map(l=>e.jsx("button",{onClick:()=>r(l),className:At("rounded-full h-9 px-3.5 text-[12.5px] font-medium border transition-colors",n===l?"bg-slate-900 text-white border-slate-900":"bg-white text-slate-600 border-slate-200 hover:border-slate-300"),children:l},l))})]}),e.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:a.map(l=>e.jsxs(ve,{className:"p-5 rounded-2xl border-slate-200/80 flex flex-col",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex items-start gap-3 min-w-0",children:[e.jsx("div",{className:"h-9 w-9 rounded-xl bg-violet-50 text-violet-600 grid place-items-center flex-shrink-0",children:e.jsx(o7,{className:"h-4 w-4"})}),e.jsx("div",{className:"text-[15px] font-semibold text-slate-900 leading-snug",children:l.q})]}),e.jsx(Oe,{variant:"outline",className:"rounded-full text-[10px] uppercase tracking-wider flex-shrink-0",children:l.category})]}),e.jsxs("div",{className:"mt-4 rounded-xl bg-amber-50/70 border border-amber-100 px-3.5 py-2.5 flex items-start gap-2",children:[e.jsx(mS,{className:"h-3.5 w-3.5 text-amber-600 mt-0.5 flex-shrink-0"}),e.jsx("div",{className:"text-[12.5px] text-amber-900 font-medium",children:l.opener})]}),e.jsx("p",{className:"mt-3 text-[13.5px] text-slate-700 leading-relaxed",children:l.a}),e.jsx("div",{className:"mt-auto pt-4 flex justify-end",children:e.jsxs(B,{variant:"outline",size:"sm",className:"rounded-full gap-1.5",onClick:()=>i(l),children:[e.jsx(Ia,{className:"h-3.5 w-3.5"})," Copy answer"]})})]},l.q))}),a.length===0&&e.jsx(ve,{className:"p-12 rounded-2xl text-center border-dashed text-slate-500",children:"No objection matches that search."}),e.jsx("p",{className:"mt-6 text-center text-[11.5px] text-slate-400 max-w-xl mx-auto",children:"Verify compensation details against your brokerage’s current published materials before sharing. These are conversation starters, not compliance-approved marketing."})]})}const Aos={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},dAt={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"},bxr=[{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."}],_xr=[{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."}],wxr=[{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."}],jxr="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.",Nxr={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:""},IU={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 kxr(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:bxr,sponsor_cards:wxr,faqs:_xr,lead_magnet:Nxr,calculator:IU,sections:Aos,disclaimer:jxr,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 Eos(s){return s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)}const ey=s=>s.toLocaleString("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0});function Sxr(){const{user:s}=hs(),[t,n]=_.useState(""),[r,a]=_.useState(18),[i,l]=_.useState(45e4),[o,c]=_.useState(2.5),[d,u]=_.useState(IU.current_split),[h,m]=_.useState(IU.current_monthly_fees),[p,f]=_.useState(395),[y,v]=_.useState(IU.split),[g,b]=_.useState(IU.cap),[j,S]=_.useState(IU.transaction_fee),[C,E]=_.useState(85),P=_.useMemo(()=>{const D=r*i*(o/100),O=D*(1-d/100),V=h*12+p*r,G=D-O-V,$=D*(1-y/100),H=Math.min($,g),Y=$>=g,Z=C*12+j*r,ne=D-H-Z,ce=y<100?g/(1-y/100):0,ie=D>0?Math.ceil(ce/(D/r)):0;return{gci:D,currentNet:G,currentSplitCost:O,currentFees:V,newNet:ne,newSplitCost:H,newFees:Z,capped:Y,sidesToCap:ie,difference:ne-G}},[r,i,o,d,h,p,y,g,j,C]),M=_.useMemo(()=>[`${t?`${t} — `:""}What last year would have looked like`,"",`${r} sides · ${ey(i)} average price · ${o}% commission`,`Gross commission income: ${ey(P.gci)}`,"","Where you are now",` Brokerage split: -${ey(P.currentSplitCost)}`,` Fees: -${ey(P.currentFees)}`,` You keep: ${ey(P.currentNet)}`,"","Where you could be",` Brokerage split (capped at ${ey(g)}): -${ey(P.newSplitCost)}`,` Fees: -${ey(P.newFees)}`,` You keep: ${ey(P.newNet)}`,"",`Difference: ${P.difference>=0?"+":""}${ey(P.difference)} per year`,P.capped?`You would cap in roughly ${P.sidesToCap} sides and keep 100% after that.`:"","","Illustrative only — not a guarantee of results. Verify current fees and caps before making a decision."].filter(Boolean).join(` `),[t,r,i,o,P,g]),I=()=>{var V;const D=encodeURIComponent(t?`${t.split(" ")[0]} — the numbers we talked about`:"The numbers we talked about"),O=encodeURIComponent(`${M} — ${((V=s==null?void 0:s.user_metadata)==null?void 0:V.full_name)??""}`);window.location.href=`mailto:?subject=${D}&body=${O}`};return e.jsxs("div",{className:"max-w-6xl mx-auto",children:[e.jsx(KE,{eyebrow:"The value conversation",title:"Show them their own numbers.",description:"Open this live in a coffee meeting. Enter their real production, and let the math do the convincing.",actions:e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"outline",className:"rounded-full bg-white/10 text-white border-white/20 hover:bg-white/20 hover:text-white",onClick:()=>{navigator.clipboard.writeText(M),se.success("Summary copied")},children:[e.jsx(Ia,{className:"h-3.5 w-3.5 mr-1.5"})," Copy"]}),e.jsxs(B,{variant:"outline",className:"rounded-full bg-white/10 text-white border-white/20 hover:bg-white/20 hover:text-white",onClick:()=>window.print(),children:[e.jsx(ZA,{className:"h-3.5 w-3.5 mr-1.5"})," Print"]}),e.jsxs(B,{className:"rounded-full bg-white text-slate-900 hover:bg-slate-100",onClick:I,children:[e.jsx(ln,{className:"h-4 w-4 mr-1.5"})," Email it"]})]})}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-[1fr_420px] gap-6 items-start",children:[e.jsxs("div",{className:"space-y-5",children:[e.jsxs(ve,{className:"p-6 rounded-2xl",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-5",children:[e.jsx("div",{className:"h-8 w-8 rounded-lg bg-violet-50 text-violet-600 grid place-items-center",children:e.jsx(uj,{className:"h-4 w-4"})}),e.jsx("div",{className:"text-[15px] font-semibold text-slate-900",children:"Their production"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsx(E3,{label:"Agent name (optional)",children:e.jsx(xe,{value:t,onChange:D=>n(D.target.value),placeholder:"Jordan Reyes"})}),e.jsx(E3,{label:"Sides closed last year",children:e.jsx(xe,{type:"number",value:r,onChange:D=>a(Number(D.target.value)||0)})}),e.jsx(E3,{label:"Average sale price",children:e.jsx(xe,{type:"number",value:i,onChange:D=>l(Number(D.target.value)||0)})}),e.jsx(E3,{label:"Commission %",children:e.jsx(xe,{type:"number",step:"0.1",value:o,onChange:D=>c(Number(D.target.value)||0)})})]}),e.jsxs("div",{className:"mt-5 rounded-xl bg-slate-50 px-4 py-3 flex items-center justify-between",children:[e.jsx("span",{className:"text-[13px] text-slate-600",children:"Gross commission income"}),e.jsx("span",{className:"text-[18px] font-semibold text-slate-900 tabular-nums",children:ey(P.gci)})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-5",children:[e.jsxs(ve,{className:"p-6 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider text-slate-500 mb-4",children:"Where they are now"}),e.jsx(uAt,{label:"Their split to the agent",suffix:"%",value:d,min:50,max:100,onChange:u}),e.jsx(E3,{label:"Monthly fees (desk, tech, royalty)",className:"mt-4",children:e.jsx(xe,{type:"number",value:h,onChange:D=>m(Number(D.target.value)||0)})}),e.jsx(E3,{label:"Per-transaction fee",className:"mt-4",children:e.jsx(xe,{type:"number",value:p,onChange:D=>f(Number(D.target.value)||0)})})]}),e.jsxs(ve,{className:"p-6 rounded-2xl ring-1 ring-violet-200",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider text-violet-600 mb-4",children:"Where they could be"}),e.jsx(uAt,{label:"Split to the agent",suffix:"%",value:y,min:50,max:100,onChange:v}),e.jsx(E3,{label:"Annual cap",className:"mt-4",children:e.jsx(xe,{type:"number",value:g,onChange:D=>b(Number(D.target.value)||0)})}),e.jsx(E3,{label:"Per-transaction fee",className:"mt-4",children:e.jsx(xe,{type:"number",value:j,onChange:D=>S(Number(D.target.value)||0)})}),e.jsx(E3,{label:"Monthly technology fee",className:"mt-4",children:e.jsx(xe,{type:"number",value:C,onChange:D=>E(Number(D.target.value)||0)})})]})]})]}),e.jsxs("div",{className:"lg:sticky lg:top-6 space-y-4",children:[e.jsxs(ve,{className:"relative overflow-hidden rounded-3xl bg-[#0B0F1E] text-white p-7 border-0",children:[e.jsx("div",{className:"pointer-events-none absolute -top-20 -right-10 h-52 w-52 rounded-full bg-emerald-500/20 blur-3xl"}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-slate-400",children:"Annual difference"}),e.jsxs("div",{className:`mt-2 text-[42px] font-semibold tracking-tight tabular-nums leading-none ${P.difference>=0?"text-emerald-400":"text-rose-400"}`,children:[P.difference>=0?"+":"",ey(P.difference)]}),e.jsx("div",{className:"text-[13px] text-slate-300 mt-2",children:P.difference>=0?"more in their pocket on the exact same production.":"less — be honest about it and focus on the other value."}),e.jsxs("div",{className:"mt-6 space-y-3",children:[e.jsx(hAt,{label:"Keeps today",value:ey(P.currentNet),muted:!0}),e.jsx(hAt,{label:"Would keep here",value:ey(P.newNet),strong:!0})]}),P.capped&&e.jsxs("div",{className:"mt-5 rounded-xl bg-white/[0.07] ring-1 ring-inset ring-white/10 px-4 py-3 flex items-start gap-2.5",children:[e.jsx(Nl,{className:"h-4 w-4 text-emerald-400 mt-0.5 flex-shrink-0"}),e.jsxs("div",{className:"text-[12.5px] text-slate-200",children:["They’d cap in roughly ",e.jsxs("span",{className:"font-semibold text-white",children:[P.sidesToCap," sides"]})," and keep ",e.jsx("span",{className:"font-semibold text-white",children:"100%"})," of every commission after that."]})]})]})]}),e.jsxs(ve,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider text-slate-500 mb-3",children:"Breakdown"}),e.jsx(gue,{label:"Split cost today",value:`-${ey(P.currentSplitCost)}`}),e.jsx(gue,{label:"Fees today",value:`-${ey(P.currentFees)}`}),e.jsx("div",{className:"h-px bg-slate-100 my-2.5"}),e.jsx(gue,{label:"Split cost here",value:`-${ey(P.newSplitCost)}`}),e.jsx(gue,{label:"Fees here",value:`-${ey(P.newFees)}`})]}),e.jsx("p",{className:"text-[11px] text-slate-400 leading-relaxed px-1",children:"Illustrative only and not a guarantee of results. Verify current caps, fees and splits against published brokerage materials before sharing with an agent."})]})]})]})}function E3({label:s,children:t,className:n}){return e.jsxs("div",{className:n,children:[e.jsx(J,{className:"text-[12px] text-slate-600",children:s}),e.jsx("div",{className:"mt-1.5",children:t})]})}function uAt({label:s,value:t,min:n,max:r,suffix:a,onChange:i}){return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(J,{className:"text-[12px] text-slate-600",children:s}),e.jsxs("span",{className:"text-[13px] font-semibold text-slate-900 tabular-nums",children:[t,a]})]}),e.jsx(kx,{className:"mt-3",value:[t],min:n,max:r,step:1,onValueChange:l=>i(l[0])})]})}function hAt({label:s,value:t,strong:n,muted:r}){return e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:`text-[13px] ${r?"text-slate-400":"text-slate-300"}`,children:s}),e.jsx("span",{className:`tabular-nums ${n?"text-[20px] font-semibold text-white":"text-[15px] text-slate-300"}`,children:t})]})}function gue({label:s,value:t}){return e.jsxs("div",{className:"flex items-center justify-between py-1",children:[e.jsx("span",{className:"text-[12.5px] text-slate-600",children:s}),e.jsx("span",{className:"text-[12.5px] font-medium text-slate-900 tabular-nums",children:t})]})}function Cxr(){const s=Fn(),{data:t=[],isLoading:n}=yos(),r=Gfr(),a=$fr(),[i,l]=_.useState("all"),[o,c]=_.useState(""),d=_.useMemo(()=>t.filter(u=>!(i!=="all"&&u.status!==i||o&&!u.title.toLowerCase().includes(o.toLowerCase()))),[t,i,o]);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center md:justify-between gap-3",children:[e.jsx("div",{className:"text-[13px] text-slate-500",children:"Every room you have built — drafted, live, and complete."}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(xe,{placeholder:"Search events",className:"pl-9 rounded-full w-[240px] bg-white",value:o,onChange:u=>c(u.target.value)})]}),e.jsxs(B,{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(rn,{className:"h-4 w-4 mr-2"})," New event"]})]})]}),e.jsxs(Yr,{value:i,onValueChange:u=>l(u),children:[e.jsxs(Zr,{className:"rounded-full bg-white border border-slate-200",children:[e.jsxs(Ht,{value:"all",className:"rounded-full",children:["All (",t.length,")"]}),e.jsxs(Ht,{value:"draft",className:"rounded-full",children:["Drafts (",t.filter(u=>u.status==="draft").length,")"]}),e.jsxs(Ht,{value:"published",className:"rounded-full",children:["Published (",t.filter(u=>u.status==="published").length,")"]}),e.jsxs(Ht,{value:"completed",className:"rounded-full",children:["Completed (",t.filter(u=>u.status==="completed").length,")"]})]}),e.jsx(Gt,{value:i,className:"mt-5",children:n?e.jsx(ve,{className:"p-12 rounded-2xl text-center text-slate-500",children:"Loading events…"}):d.length===0?e.jsxs(ve,{className:"p-12 rounded-2xl text-center border-dashed",children:[e.jsx(ga,{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(B,{className:"mt-4 rounded-full",onClick:()=>s("/attract/events/new"),children:[e.jsx(rn,{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(ve,{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(Oe,{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(Oe,{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(Kr,{className:"h-3.5 w-3.5"})," Virtual"]}):u.format==="hybrid"?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Kr,{className:"h-3.5 w-3.5"})," Hybrid"]}):e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Xa,{className:"h-3.5 w-3.5"})," ",u.location||"In person"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(In,{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(B,{variant:"ghost",size:"sm",className:"h-8 rounded-full text-slate-500",onClick:()=>r.mutate(u.id),children:[e.jsx(Ia,{className:"h-3.5 w-3.5 mr-1"})," Duplicate"]}),u.status==="published"&&u.public_slug&&e.jsxs(B,{variant:"ghost",size:"sm",className:"h-8 rounded-full text-slate-500",onClick:()=>{navigator.clipboard.writeText(mDe(u.public_slug)),se.success("Registration link copied")},children:[e.jsx(wr,{className:"h-3.5 w-3.5 mr-1"})," Link"]})]}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 rounded-full text-rose-600 hover:bg-rose-50",onClick:async()=>{await Xi("Delete this event?")&&a.mutate(u.id)},children:e.jsx(Sn,{className:"h-3.5 w-3.5"})})]})]})]},u.id))})})]})]})}const DU=["attract-kits"],GZ=s=>["attract-kit-items",s],WZ=s=>["attract-kit-shares",s??"all"],Axr=s=>["attract-kit-events",s??"all"],Exr=["attract-kit-templates"];function Git(){const{user:s}=hs(),t=Bt(),n=at({queryKey:[...DU,s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:o,error:c}=await q.from("attract_resource_kits").select("*").order("updated_at",{ascending:!1});if(c)throw c;return o??[]}}),r=mt({mutationFn:async o=>{if(!s)throw new Error("not authenticated");const{data:c,error:d}=await q.from("attract_resource_kits").insert({user_id:s.id,title:o.title||"Untitled Kit",...o}).select("*").single();if(d)throw d;return c},onSuccess:()=>t.invalidateQueries({queryKey:DU})}),a=mt({mutationFn:async({id:o,patch:c})=>{const{data:d,error:u}=await q.from("attract_resource_kits").update(c).eq("id",o).select("*").single();if(u)throw u;return d},onSuccess:()=>t.invalidateQueries({queryKey:DU})}),i=mt({mutationFn:async o=>{const{error:c}=await q.from("attract_resource_kits").delete().eq("id",o);if(c)throw c},onSuccess:()=>t.invalidateQueries({queryKey:DU})}),l=mt({mutationFn:async o=>{const{data:c,error:d}=await q.rpc("duplicate_attract_kit",{_kit_id:o});if(d)throw d;return c},onSuccess:()=>t.invalidateQueries({queryKey:DU})});return{kits:n.data??[],isLoading:n.isLoading,create:r,update:a,remove:i,duplicate:l}}function Tos(s){return at({queryKey:["attract-kit",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("attract_resource_kits").select("*").eq("id",s).single();if(n)throw n;return t}})}function Txr(s){const t=Bt(),n=at({queryKey:GZ(s??""),enabled:!!s,queryFn:async()=>{const{data:o,error:c}=await q.from("attract_resource_kit_items").select("*").eq("kit_id",s).order("sort_order");if(c)throw c;return o??[]}}),r=mt({mutationFn:async o=>{var u;const{data:c,error:d}=await q.from("attract_resource_kit_items").insert({kit_id:s,type:"text",title:"New item",sort_order:((u=n.data)==null?void 0:u.length)??0,...o}).select("*").single();if(d)throw d;return c},onSuccess:()=>t.invalidateQueries({queryKey:GZ(s??"")})}),a=mt({mutationFn:async({id:o,patch:c})=>{const{error:d}=await q.from("attract_resource_kit_items").update(c).eq("id",o);if(d)throw d},onSuccess:()=>t.invalidateQueries({queryKey:GZ(s??"")})}),i=mt({mutationFn:async o=>{const{error:c}=await q.from("attract_resource_kit_items").delete().eq("id",o);if(c)throw c},onSuccess:()=>t.invalidateQueries({queryKey:GZ(s??"")})}),l=mt({mutationFn:async o=>{await Promise.all(o.map((c,d)=>q.from("attract_resource_kit_items").update({sort_order:d}).eq("id",c)))},onSuccess:()=>t.invalidateQueries({queryKey:GZ(s??"")})});return{items:n.data??[],isLoading:n.isLoading,add:r,update:a,remove:i,reorder:l}}function Mos(s){const{user:t}=hs(),n=Bt(),r=at({queryKey:WZ(s),enabled:!!t,queryFn:async()=>{let l=q.from("attract_kit_shares").select("*").order("created_at",{ascending:!1});s&&(l=l.eq("kit_id",s));const{data:o,error:c}=await l;if(c)throw c;return o??[]}}),a=mt({mutationFn:async l=>{if(!t)throw new Error("not authenticated");const{data:o,error:c}=await q.from("attract_kit_shares").insert({owner_user_id:t.id,...l}).select("*").single();if(c)throw c;return o},onSuccess:l=>{var o;n.invalidateQueries({queryKey:WZ(s)}),n.invalidateQueries({queryKey:WZ()});try{(o=navigator.clipboard)==null||o.writeText(Pos(l.share_token)),se.success("Share link created and copied")}catch{se.success("Share link created")}},onError:l=>se.error((l==null?void 0:l.message)||"Could not create share link")}),i=mt({mutationFn:async l=>{const{error:o}=await q.from("attract_kit_shares").update({status:"revoked"}).eq("id",l);if(o)throw o},onSuccess:()=>{n.invalidateQueries({queryKey:WZ(s)}),n.invalidateQueries({queryKey:WZ()}),se.success("Link revoked")},onError:l=>se.error((l==null?void 0:l.message)||"Could not revoke link")});return{shares:r.data??[],isLoading:r.isLoading,create:a,revoke:i}}function Mxr(s){return at({queryKey:Axr(s),queryFn:async()=>{let t=q.from("attract_kit_events").select("*").order("created_at",{ascending:!1}).limit(500);s&&(t=t.eq("kit_id",s));const{data:n,error:r}=await t;if(r)throw r;return n??[]}})}function Pxr(){return at({queryKey:Exr,queryFn:async()=>{const{data:s,error:t}=await q.from("attract_kit_templates").select("*").eq("is_active",!0).order("sort_order");if(t)throw t;return s??[]}})}function Lxr(){const s=Bt();return mt({mutationFn:async t=>{const{data:n,error:r}=await q.rpc("clone_attract_kit_template",{_template_id:t});if(r)throw r;return n},onSuccess:()=>s.invalidateQueries({queryKey:DU})})}function Pos(s){return`${typeof window<"u"?window.location.origin:""}/attract-kit/${s}`}const Ixr=[{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 mAt(){const{eventId:s}=Li(),t=Fn(),[n]=Yl(),r=n.get("type"),a=!!s,{data:i}=Hit(s),{data:l=[]}=bos(),{kits:o}=Git(),c=qfr(),d=_os(),[u,h]=_.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});_.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=g=>h(b=>({...b,...g})),p=_.useMemo(()=>l.slice(0,4),[l]),f=g=>{m({title:g.title,description:g.description,event_type_key:g.event_type_key,related_pillar:g.related_pillar,intended_audience:g.intended_audience,agenda:g.suggested_agenda||[],learning_outcomes:g.suggested_outcomes||[],registration_questions:g.suggested_questions||[],confirmation_message:g.suggested_confirmation}),se.success(`Loaded "${g.title}"`)},y=async(g={})=>{const b={...u,starts_at:u.starts_at?new Date(u.starts_at).toISOString():new Date().toISOString(),ends_at:u.ends_at?new Date(u.ends_at).toISOString():null,capacity:u.capacity===""?null:Number(u.capacity),status:g.publish?"published":u.status||"draft"};if(a)await d.mutateAsync({id:s,patch:b}),se.success(g.publish?"Published":"Saved");else{const j=await c.mutateAsync(b);se.success(g.publish?"Event published":"Draft saved"),t(`/attract/events/${j.id}${g.publish?"":"/edit"}`,{replace:!0})}},v=i!=null&&i.public_slug?mDe(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(B,{variant:"ghost",size:"sm",className:"rounded-full",onClick:()=>t("/attract/toolkit/events"),children:[e.jsx(ka,{className:"h-4 w-4 mr-2"})," All events"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[v&&e.jsxs(B,{variant:"outline",size:"sm",className:"rounded-full",onClick:()=>{navigator.clipboard.writeText(v),se.success("Registration link copied")},children:[e.jsx(Vc,{className:"h-3.5 w-3.5 mr-2"})," Copy link"]}),e.jsxs(B,{variant:"outline",size:"sm",className:"rounded-full",onClick:()=>y(),children:[e.jsx(Ho,{className:"h-4 w-4 mr-2"})," Save draft"]}),e.jsxs(B,{size:"sm",className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>y({publish:!0}),children:[e.jsx(Sy,{className:"h-4 w-4 mr-2"})," ",(i==null?void 0:i.status)==="published"?"Update published":"Publish"]})]})]}),!a&&p.length>0&&e.jsxs(ve,{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(un,{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(g=>e.jsxs("button",{onClick:()=>f(g),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:g.title}),e.jsx("div",{className:"text-[12px] text-slate-600 line-clamp-2 mt-0.5",children:g.description})]},g.id))})]}),e.jsxs(ve,{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(J,{children:"Title"}),e.jsx(xe,{value:u.title,onChange:g=>m({title:g.target.value}),placeholder:"Coffee & Systems Roundtable"})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Event type"}),e.jsxs(is,{value:u.event_type_key,onValueChange:g=>m({event_type_key:g}),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsx(as,{children:Ixr.map(g=>e.jsx(He,{value:g.key,children:g.label},g.key))})]})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Related pillar"}),e.jsxs(is,{value:u.related_pillar||"connect",onValueChange:g=>m({related_pillar:g}),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"produce",children:"Produce"}),e.jsx(He,{value:"influence",children:"Influence"}),e.jsx(He,{value:"provide",children:"Provide"}),e.jsx(He,{value:"connect",children:"Connect"})]})]})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(J,{children:"Intended audience"}),e.jsx(xe,{value:u.intended_audience||"",onChange:g=>m({intended_audience:g.target.value}),placeholder:"Producing agents 1–5 years in"})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(J,{children:"Description"}),e.jsx(Ms,{rows:4,value:u.description||"",onChange:g=>m({description:g.target.value}),placeholder:"What is this event and why does it matter?"})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Starts at"}),e.jsx(xe,{type:"datetime-local",value:u.starts_at||"",onChange:g=>m({starts_at:g.target.value})})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Ends at"}),e.jsx(xe,{type:"datetime-local",value:u.ends_at||"",onChange:g=>m({ends_at:g.target.value})})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Time zone"}),e.jsxs(is,{value:u.timezone||"America/New_York",onValueChange:g=>m({timezone:g}),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsx(as,{children:["America/New_York","America/Chicago","America/Denver","America/Los_Angeles","America/Phoenix"].map(g=>e.jsx(He,{value:g,children:g},g))})]})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Format"}),e.jsxs(is,{value:u.format,onValueChange:g=>m({format:g}),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"in_person",children:"In person"}),e.jsx(He,{value:"virtual",children:"Virtual"}),e.jsx(He,{value:"hybrid",children:"Hybrid"})]})]})]}),u.format!=="virtual"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx(J,{children:"Venue / location name"}),e.jsx(xe,{value:u.location||"",onChange:g=>m({location:g.target.value}),placeholder:"Rise Coffee — Downtown"})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Address"}),e.jsx(xe,{value:u.address||"",onChange:g=>m({address:g.target.value}),placeholder:"123 Main St, City, ST"})]})]}),u.format!=="in_person"&&e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(J,{children:"Virtual meeting URL"}),e.jsx(xe,{value:u.virtual_url||"",onChange:g=>m({virtual_url:g.target.value}),placeholder:"https://zoom.us/…"})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Capacity (optional)"}),e.jsx(xe,{type:"number",value:u.capacity,onChange:g=>m({capacity:g.target.value}),placeholder:"No limit"})]}),e.jsxs("div",{className:"flex items-center gap-3 pt-6",children:[e.jsx(fn,{checked:u.waitlist_enabled,onCheckedChange:g=>m({waitlist_enabled:g}),id:"wl"}),e.jsx(J,{htmlFor:"wl",className:"cursor-pointer",children:"Allow waitlist if full"})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Host name (as shown publicly)"}),e.jsx(xe,{value:u.host_name||"",onChange:g=>m({host_name:g.target.value}),placeholder:"Jeremy from LevelUp"})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Cover image URL"}),e.jsx(xe,{value:u.cover_image_url||"",onChange:g=>m({cover_image_url:g.target.value}),placeholder:"https://…"})]})]})]}),e.jsxs(ve,{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(J,{children:"Agenda"}),e.jsxs(B,{size:"sm",variant:"ghost",className:"rounded-full",onClick:()=>m({agenda:[...u.agenda||[],{time:"",item:""}]}),children:[e.jsx(rn,{className:"h-3.5 w-3.5 mr-1"})," Add item"]})]}),e.jsxs("div",{className:"space-y-2",children:[(u.agenda||[]).map((g,b)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{className:"w-24",value:g.time||"",onChange:j=>{const S=[...u.agenda];S[b]={...S[b],time:j.target.value},m({agenda:S})},placeholder:"0:00"}),e.jsx(xe,{value:g.item||"",onChange:j=>{const S=[...u.agenda];S[b]={...S[b],item:j.target.value},m({agenda:S})},placeholder:"What happens here"}),e.jsx(B,{size:"icon",variant:"ghost",onClick:()=>m({agenda:u.agenda.filter((j,S)=>S!==b)}),children:e.jsx(Qn,{className:"h-4 w-4"})})]},b)),(u.agenda||[]).length===0&&e.jsx("div",{className:"text-[12px] text-slate-400",children:"Add each moment of the event so attendees know what to expect."})]})]}),e.jsx(wc,{}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(J,{children:"What attendees will receive"}),e.jsxs(B,{size:"sm",variant:"ghost",className:"rounded-full",onClick:()=>m({learning_outcomes:[...u.learning_outcomes||[],""]}),children:[e.jsx(rn,{className:"h-3.5 w-3.5 mr-1"})," Add outcome"]})]}),e.jsx("div",{className:"space-y-2",children:(u.learning_outcomes||[]).map((g,b)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{value:g,onChange:j=>{const S=[...u.learning_outcomes];S[b]=j.target.value,m({learning_outcomes:S})},placeholder:"One clear, honest outcome"}),e.jsx(B,{size:"icon",variant:"ghost",onClick:()=>m({learning_outcomes:u.learning_outcomes.filter((j,S)=>S!==b)}),children:e.jsx(Qn,{className:"h-4 w-4"})})]},b))})]})]})]}),e.jsxs(ve,{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(J,{children:"Registration questions"}),e.jsxs(B,{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(rn,{className:"h-3.5 w-3.5 mr-1"})," Add question"]})]}),e.jsx("div",{className:"space-y-2",children:(u.registration_questions||[]).map((g,b)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(xe,{className:"flex-1",value:g.label,onChange:j=>{const S=[...u.registration_questions];S[b]={...S[b],label:j.target.value,key:g.key||`q${b+1}`},m({registration_questions:S})},placeholder:"Question shown to registrants"}),e.jsxs(is,{value:g.type,onValueChange:j=>{const S=[...u.registration_questions];S[b]={...S[b],type:j},m({registration_questions:S})},children:[e.jsx(rs,{className:"w-32",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"text",children:"Short text"}),e.jsx(He,{value:"long",children:"Long text"})]})]}),e.jsx(B,{size:"icon",variant:"ghost",onClick:()=>m({registration_questions:u.registration_questions.filter((j,S)=>S!==b)}),children:e.jsx(Qn,{className:"h-4 w-4"})})]},b))})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Confirmation message (shown after registration)"}),e.jsx(Ms,{rows:3,value:u.confirmation_message||"",onChange:g=>m({confirmation_message:g.target.value}),placeholder:"You are in — come with one honest question."})]})]})]}),e.jsxs(ve,{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(J,{children:"Attach a Resource Kit"}),e.jsxs(is,{value:u.resource_kit_id||"none",onValueChange:g=>m({resource_kit_id:g==="none"?null:g}),children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"None"})}),e.jsxs(as,{children:[e.jsx(He,{value:"none",children:"None"}),(o||[]).map(g=>e.jsx(He,{value:g.id,children:g.title},g.id))]})]})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Deliver kit"}),e.jsxs(is,{value:u.kit_delivery_trigger||"after_attendance",onValueChange:g=>m({kit_delivery_trigger:g}),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"on_registration",children:"On registration"}),e.jsx(He,{value:"on_confirmation",children:"On confirmation"}),e.jsx(He,{value:"on_check_in",children:"At check-in"}),e.jsx(He,{value:"after_attendance",children:"After attendance"}),e.jsx(He,{value:"manual",children:"Only manually"})]})]})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Default follow-up window (hours)"}),e.jsx(xe,{type:"number",value:u.followup_hours??48,onChange:g=>m({followup_hours:Number(g.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(ve,{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(Oe,{variant:"secondary",className:"bg-rose-50 text-rose-700 border-rose-200",children:"Add title and start time"}),(u.agenda||[]).length===0&&e.jsx(Oe,{variant:"secondary",className:"bg-amber-50 text-amber-700 border-amber-200",children:"No agenda yet"}),(u.learning_outcomes||[]).length===0&&e.jsx(Oe,{variant:"secondary",className:"bg-amber-50 text-amber-700 border-amber-200",children:"No stated outcomes"}),!u.resource_kit_id&&e.jsx(Oe,{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(B,{variant:"outline",className:"rounded-full",onClick:()=>y(),children:[e.jsx(Ho,{className:"h-4 w-4 mr-2"})," Save draft"]}),e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>y({publish:!0}),children:[e.jsx(Sy,{className:"h-4 w-4 mr-2"})," Publish"]})]})]})]})}const u3e=s=>s?[s.first_name,s.last_name].filter(Boolean).join(" "):"";function Dxr(){const{eventId:s}=Li(),t=Fn(),{data:n}=Hit(s),{data:r=[]}=vos(s),{data:a=[]}=Bfr(s),{data:i=[]}=Ufr(s),{agents:l}=WE(),{data:o=[]}=bos(),c=wos(),d=Vfr(),u=Hfr(),h=_os(),m=_.useMemo(()=>{const y=r.length,v=r.filter(I=>I.status==="registered"||I.status==="confirmed").length,g=r.filter(I=>I.status==="attended").length,b=r.filter(I=>I.status==="no_show").length,j=r.filter(I=>I.status==="waitlisted").length,S=v+g+b,C=S>0?Math.round(g/S*100):0,E=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=g>0?Math.round(P/g*100):0;return{total:y,registered:v,attended:g,noShow:b,waitlist:j,attendRate:C,invView:E,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?mDe(n.public_slug):null,f=()=>{const y=new Blob([jos(n)],{type:"text/calendar"}),v=URL.createObjectURL(y),g=document.createElement("a");g.href=v,g.download=`${n.public_slug||"event"}.ics`,g.click(),URL.revokeObjectURL(v)};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(B,{variant:"ghost",size:"sm",className:"rounded-full",onClick:()=>t("/attract/toolkit/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(B,{variant:"outline",size:"sm",className:"rounded-full",onClick:f,children:[e.jsx(li,{className:"h-3.5 w-3.5 mr-2"})," ICS"]}),p&&e.jsxs(B,{variant:"outline",size:"sm",className:"rounded-full",onClick:()=>{navigator.clipboard.writeText(p),se.success("Link copied")},children:[e.jsx(Ia,{className:"h-3.5 w-3.5 mr-2"})," Copy link"]}),p&&e.jsx(B,{variant:"outline",size:"sm",className:"rounded-full",asChild:!0,children:e.jsxs("a",{href:p,target:"_blank",rel:"noreferrer",children:[e.jsx(wr,{className:"h-3.5 w-3.5 mr-2"})," Preview page"]})}),e.jsxs(B,{size:"sm",className:"rounded-full",onClick:()=>t(`/attract/events/${n.id}/checkin`),children:[e.jsx(Hf,{className:"h-3.5 w-3.5 mr-2"})," Check-in mode"]}),e.jsx(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>t(`/attract/events/${n.id}/edit`),children:"Edit"})]})]}),e.jsx(ve,{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(Oe,{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(Oe,{variant:"secondary",className:"bg-white/10 border-white/10 text-white capitalize",children:n.related_pillar}),n.event_type_key&&e.jsx(Oe,{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(ga,{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(Kr,{className:"h-4 w-4"})," Virtual"]}):e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Xa,{className:"h-4 w-4"})," ",n.location||"In person"]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(In,{className:"h-4 w-4"})," ",n.registration_count," registered",n.capacity?` / ${n.capacity}`:""]})]})]}),n.status==="draft"&&e.jsx(B,{className:"rounded-full bg-white text-slate-900 hover:bg-white/90",onClick:async()=>{await h.mutateAsync({id:n.id,patch:{status:"published"}}),se.success("Published")},children:"Publish now"}),n.status==="published"&&new Date(n.starts_at){await h.mutateAsync({id:n.id,patch:{status:"completed"}}),se.success("Marked completed")},children:"Mark completed"})]})}),e.jsxs(Yr,{defaultValue:"overview",children:[e.jsxs(Zr,{className:"rounded-full bg-white border border-slate-200 flex-wrap h-auto",children:[e.jsx(Ht,{value:"overview",className:"rounded-full",children:"Overview"}),e.jsxs(Ht,{value:"invitations",className:"rounded-full",children:["Invitations (",a.length,")"]}),e.jsxs(Ht,{value:"registrations",className:"rounded-full",children:["Registrations (",r.length,")"]}),e.jsxs(Ht,{value:"notes",className:"rounded-full",children:["Notes (",i.length,")"]}),e.jsx(Ht,{value:"kit",className:"rounded-full",children:"Resource Kit"}),e.jsx(Ht,{value:"followup",className:"rounded-full",children:"48-hour follow-up"}),e.jsx(Ht,{value:"analytics",className:"rounded-full",children:"Analytics"})]}),e.jsxs(Gt,{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(S2,{icon:In,label:"Registered",value:m.registered+m.attended}),e.jsx(S2,{icon:ea,label:"Attended",value:m.attended}),e.jsx(S2,{icon:bl,label:"Attendance rate",value:`${m.attendRate}%`}),e.jsx(S2,{icon:Ny,label:"Follow-up completion",value:`${m.followedRate}%`})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs(ve,{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((y,v)=>e.jsxs("li",{className:"flex gap-3 text-[14px]",children:[e.jsx("span",{className:"text-slate-500 tabular-nums w-16 shrink-0",children:y.time||""}),e.jsx("span",{className:"text-slate-800",children:y.item})]},v))}),(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((y,v)=>e.jsxs("li",{className:"text-[13.5px] text-slate-700 flex gap-2",children:[e.jsx(ea,{className:"h-4 w-4 text-emerald-600 shrink-0 mt-0.5"})," ",y]},v))})]})]}),e.jsxs(ve,{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(B,{size:"sm",variant:"outline",className:"rounded-full mt-2 w-full",onClick:()=>{navigator.clipboard.writeText(p),se.success("Copied")},children:[e.jsx(Ia,{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(B,{size:"sm",variant:"outline",className:"rounded-full w-full",onClick:()=>t(`/attract/events/${n.id}/checkin`),children:[e.jsx(Hf,{className:"h-3.5 w-3.5 mr-2"})," Open check-in"]})]})]})]})]}),e.jsx(Gt,{value:"invitations",className:"mt-5",children:e.jsx(Rxr,{eventId:n.id,eventSlug:n.public_slug,agents:l,invitations:a,templates:o,onCreate:u.mutate})}),e.jsx(Gt,{value:"registrations",className:"mt-5",children:e.jsx(Fxr,{eventId:n.id,attendees:r,onUpsert:c.mutate,checkInToken:n.check_in_token})}),e.jsx(Gt,{value:"notes",className:"mt-5",children:e.jsx(Oxr,{eventId:n.id,attendees:r,notes:i,onCreate:d.mutate})}),e.jsx(Gt,{value:"kit",className:"mt-5",children:e.jsxs(ve,{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(B,{variant:"outline",className:"rounded-full mt-4",onClick:()=>t(`/attract/toolkit/kits/${n.resource_kit_id}/analytics`),children:"Open kit analytics"})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-[15px] text-slate-700",children:"No kit attached yet. Attach one so attendees leave with something valuable."}),e.jsxs("div",{className:"flex gap-2 mt-4",children:[e.jsx(B,{className:"rounded-full",onClick:()=>t(`/attract/events/${n.id}/edit`),children:"Attach a kit"}),e.jsx(B,{variant:"outline",className:"rounded-full",onClick:()=>t("/attract/toolkit/kits/new"),children:"Create a new kit"})]})]})]})}),e.jsx(Gt,{value:"followup",className:"mt-5",children:e.jsx(zxr,{eventId:n.id,attendees:r,onUpsert:c.mutate})}),e.jsxs(Gt,{value:"analytics",className:"mt-5",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(S2,{icon:Or,label:"Invitations sent",value:a.length}),e.jsx(S2,{icon:wr,label:"Invitation view rate",value:`${m.invView}%`}),e.jsx(S2,{icon:In,label:"Registered",value:m.registered+m.attended}),e.jsx(S2,{icon:ea,label:"Attended",value:m.attended}),e.jsx(S2,{icon:bl,label:"Attendance rate",value:`${m.attendRate}%`}),e.jsx(S2,{icon:Ny,label:"Follow-up complete (48h)",value:`${m.followedRate}%`}),e.jsx(S2,{icon:WA,label:"Notes captured",value:i.length}),e.jsx(S2,{icon:Pl,label:"Meetings requested",value:r.filter(y=>y.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 S2({icon:s,label:t,value:n}){return e.jsxs(ve,{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 Rxr({eventId:s,eventSlug:t,agents:n,invitations:r,templates:a,onCreate:i}){const[l,o]=_.useState(""),[c,d]=_.useState(""),[u,h]=_.useState(""),[m,p]=_.useState("email"),[f,y]=_.useState(""),v=a==null?void 0:a[0],g=()=>{if(!v)return;const j=m==="sms"?v.suggested_invitation_sms:m==="dm"?v.suggested_invitation_dm:v.suggested_invitation_email,S=t?`${window.location.origin}/attract-event/${t}`:"";y((j||"").replaceAll("{{first_name}}",(c||"friend").split(" ")[0]).replaceAll("{{link}}",S).replaceAll("{{date}}",""))},b=()=>{if(!c||m==="email"&&!u){se.error("Add a name and email");return}const j=n.find(S=>S.id===l);i({event_id:s,agent_id:l||null,recipient_name:c||u3e(j),recipient_email:u||(j==null?void 0:j.email),channel:m,message_body:f,status:"sent"}),d(""),h(""),y(""),o(""),se.success("Invitation logged")};return e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs(ve,{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(J,{children:"Attract agent (optional)"}),e.jsxs(is,{value:l||"none",onValueChange:j=>{o(j==="none"?"":j);const S=n.find(C=>C.id===j);S&&(d(u3e(S)),h(S.email||""))},children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Pick an agent"})}),e.jsxs(as,{children:[e.jsx(He,{value:"none",children:"Guest (not in pipeline)"}),n.map(j=>e.jsx(He,{value:j.id,children:u3e(j)},j.id))]})]})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Channel"}),e.jsxs(is,{value:m,onValueChange:p,children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"email",children:"Email"}),e.jsx(He,{value:"sms",children:"Text message"}),e.jsx(He,{value:"dm",children:"DM"}),e.jsx(He,{value:"call",children:"Phone call"}),e.jsx(He,{value:"in_person",children:"In person"})]})]})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Recipient name"}),e.jsx(xe,{value:c,onChange:j=>d(j.target.value)})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Recipient email"}),e.jsx(xe,{value:u,onChange:j=>h(j.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(J,{children:"Message"}),v&&e.jsxs(B,{size:"sm",variant:"ghost",className:"rounded-full text-xs",onClick:g,children:[e.jsx(un,{className:"h-3 w-3 mr-1"})," Draft from template"]})]}),e.jsx(Ms,{rows:5,value:f,onChange:j=>y(j.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(B,{variant:"outline",className:"rounded-full",onClick:()=>{f&&(navigator.clipboard.writeText(f),se.success("Copied"))},children:[e.jsx(Ia,{className:"h-3.5 w-3.5 mr-2"})," Copy message"]}),e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:b,children:[e.jsx(Or,{className:"h-3.5 w-3.5 mr-2"})," Log invitation"]})]})]})]}),e.jsxs(ve,{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(j=>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:j.recipient_name||j.recipient_email}),e.jsx(Oe,{variant:"secondary",className:"capitalize",children:j.status})]}),e.jsxs("div",{className:"text-[11.5px] text-slate-500 mt-0.5",children:["via ",j.channel," · ",Ed(new Date(j.sent_at))," ago",j.view_count>0?` · viewed ${j.view_count}×`:""]})]},j.id))})]})]})}function Fxr({eventId:s,attendees:t,onUpsert:n,checkInToken:r}){const[a,i]=_.useState(""),[l,o]=_.useState(""),c=()=>{if(!a){se.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(""),se.success("Walk-in added")};return e.jsxs("div",{className:"space-y-5",children:[e.jsxs(ve,{className:"p-4 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-2",children:"Add a walk-in guest"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-2",children:[e.jsx(xe,{placeholder:"Name",value:a,onChange:d=>i(d.target.value)}),e.jsx(xe,{placeholder:"Email (optional)",value:l,onChange:d=>o(d.target.value)}),e.jsxs(B,{className:"rounded-full md:col-span-2",onClick:c,children:[e.jsx(Pl,{className:"h-4 w-4 mr-2"})," Add & check in"]})]})]}),e.jsx(ve,{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||u3e(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(Oe,{variant:"secondary",className:"capitalize",children:d.status}),e.jsxs(is,{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(rs,{className:"h-8 w-40 text-xs",children:e.jsx(ls,{})}),e.jsx(as,{children:["invited","registered","confirmed","waitlisted","attended","no_show","cancelled"].map(u=>e.jsx(He,{value:u,className:"text-xs",children:u.replace("_"," ")},u))})]}),r&&d.personalized_token&&e.jsx(B,{variant:"ghost",size:"sm",className:"rounded-full text-xs",onClick:()=>{navigator.clipboard.writeText(Wfr(r,d.personalized_token)),se.success("Check-in link copied")},children:e.jsx(Ia,{className:"h-3.5 w-3.5"})})]})]},d.id))})})]})}function Oxr({eventId:s,attendees:t,notes:n,onCreate:r}){const[a,i]=_.useState(""),[l,o]=_.useState(""),[c,d]=_.useState("warm"),[u,h]=_.useState(!1),[m,p]=_.useState(""),f=()=>{if(!l.trim()){se.error("Add a note");return}const y=t.find(v=>v.id===a);r({event_id:s,attendee_id:a||null,agent_id:(y==null?void 0:y.agent_id)||null,note:l,temperature:c,recommended_next_action:m||null,wants_one_on_one:u}),o(""),i(""),p(""),h(!1),se.success("Note captured")};return e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs(ve,{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(J,{children:"Attendee (optional)"}),e.jsxs(is,{value:a||"none",onValueChange:y=>i(y==="none"?"":y),children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Anyone in the room"})}),e.jsxs(as,{children:[e.jsx(He,{value:"none",children:"General note"}),t.map(y=>e.jsx(He,{value:y.id,children:y.guest_name||y.guest_email},y.id))]})]})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Note"}),e.jsx(Ms,{rows:4,value:l,onChange:y=>o(y.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(J,{children:"Relationship temperature"}),e.jsxs(is,{value:c,onValueChange:d,children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsx(as,{children:["cold","warm","hot"].map(y=>e.jsx(He,{value:y,children:y},y))})]})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(J,{children:"Recommended next action"}),e.jsx(xe,{value:m,onChange:y=>p(y.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:y=>h(y.target.checked)}),"They should get a one-on-one conversation"]})]}),e.jsx("div",{className:"flex justify-end mt-4",children:e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:f,children:[e.jsx(rn,{className:"h-4 w-4 mr-2"})," Save note"]})})]}),e.jsxs(ve,{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(y=>{const v=t.find(g=>g.id===y.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:(v==null?void 0:v.guest_name)||"General"}),e.jsx("div",{className:"text-[13px] text-slate-700 mt-1 whitespace-pre-wrap",children:y.note}),e.jsxs("div",{className:"flex items-center gap-2 mt-2 flex-wrap text-[11px] text-slate-500",children:[y.temperature&&e.jsx(Oe,{variant:"secondary",className:"capitalize",children:y.temperature}),y.wants_one_on_one&&e.jsx(Oe,{className:"bg-emerald-500",children:"Wants 1:1"}),y.recommended_next_action&&e.jsxs("span",{children:["Next: ",y.recommended_next_action]})]})]},y.id)})})]})]})}function zxr({eventId:s,attendees:t,onUpsert:n}){const r=_.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(ve,{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(B,{size:"sm",variant:"ghost",className:"rounded-full h-8",onClick:()=>a(d.id,"in_progress"),children:"In progress"}),e.jsx(B,{size:"sm",className:"rounded-full h-8 bg-emerald-600 hover:bg-emerald-700",onClick:()=>a(d.id,"done"),children:e.jsx(ea,{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 yK={},Bxr=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then},Los={},$j={};let Wit;const Uxr=[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];$j.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};$j.getSymbolTotalCodewords=function(t){return Uxr[t]};$j.getBCHDigit=function(s){let t=0;for(;s!==0;)t++,s>>>=1;return t};$j.setToSJISFunction=function(t){if(typeof t!="function")throw new Error('"toSJISFunc" is not a valid function.');Wit=t};$j.isKanjiModeEnabled=function(){return typeof Wit<"u"};$j.toSJIS=function(t){return Wit(t)};var pDe={};(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}}})(pDe);function Ios(){this.buffer=[],this.length=0}Ios.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 qxr=Ios;function mie(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)}mie.prototype.set=function(s,t,n,r){const a=s*this.size+t;this.data[a]=n,r&&(this.reservedBit[a]=!0)};mie.prototype.get=function(s,t){return this.data[s*this.size+t]};mie.prototype.xor=function(s,t,n){this.data[s*this.size+t]^=n};mie.prototype.isReserved=function(s,t){return this.reservedBit[s*this.size+t]};var $xr=mie,Dos={};(function(s){const t=$j.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 Hxr=Kit,Bos={},zL={},Yit={};Yit.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40};var zC={};const Uos="[0-9]+",Gxr="[A-Z $%*+\\-./:]+";let Kse="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";Kse=Kse.replace(/u/g,"\\u");const Wxr="(?:(?![A-Z0-9 $%*+\\-./:]|"+Kse+`)(?:.|[\r ]))+`;zC.KANJI=new RegExp(Kse,"g");zC.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");zC.BYTE=new RegExp(Wxr,"g");zC.NUMERIC=new RegExp(Uos,"g");zC.ALPHANUMERIC=new RegExp(Gxr,"g");const Kxr=new RegExp("^"+Kse+"$"),Yxr=new RegExp("^"+Uos+"$"),Zxr=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");zC.testKanji=function(t){return Kxr.test(t)};zC.testNumeric=function(t){return Yxr.test(t)};zC.testAlphanumeric=function(t){return Zxr.test(t)};(function(s){const t=Yit,n=zC;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}}})(zL);(function(s){const t=$j,n=fDe,r=pDe,a=zL,i=Yit,l=7973,o=t.getBCHDigit(l);function c(m,p,f){for(let y=1;y<=40;y++)if(p<=s.getCapacity(y,f,m))return y}function d(m,p){return a.getCharCountIndicator(m,p)+4}function u(m,p){let f=0;return m.forEach(function(y){const v=d(y.mode,p);f+=v+y.getBitsLength()}),f}function h(m,p){for(let f=1;f<=40;f++)if(u(m,f)<=s.getCapacity(f,p,a.MIXED))return f}s.from=function(p,f){return i.isValid(p)?parseInt(p,10):f},s.getCapacity=function(p,f,y){if(!i.isValid(p))throw new Error("Invalid QR Code version");typeof y>"u"&&(y=a.BYTE);const v=t.getSymbolTotalCodewords(p),g=n.getTotalCodewordsCount(p,f),b=(v-g)*8;if(y===a.MIXED)return b;const j=b-d(y,p);switch(y){case a.NUMERIC:return Math.floor(j/10*3);case a.ALPHANUMERIC:return Math.floor(j/11*2);case a.KANJI:return Math.floor(j/13);case a.BYTE:default:return Math.floor(j/8)}},s.getBestVersionForData=function(p,f){let y;const v=r.from(f,r.M);if(Array.isArray(p)){if(p.length>1)return h(p,v);if(p.length===0)return 1;y=p[0]}else y=p;return c(y.mode,y.getLength(),v)},s.getEncodedBits=function(p){if(!i.isValid(p)||p<7)throw new Error("Invalid QR Code version");let f=p<<12;for(;t.getBCHDigit(f)-o>=0;)f^=l<=0;)a^=$os<0&&(r=this.data.substr(n),a=parseInt(r,10),t.put(a,i*3+1))};var Jxr=UG;const egr=zL,bUe=["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 qG(s){this.mode=egr.ALPHANUMERIC,this.data=s}qG.getBitsLength=function(t){return 11*Math.floor(t/2)+6*(t%2)};qG.prototype.getLength=function(){return this.data.length};qG.prototype.getBitsLength=function(){return qG.getBitsLength(this.data.length)};qG.prototype.write=function(t){let n;for(n=0;n+2<=this.data.length;n+=2){let r=bUe.indexOf(this.data[n])*45;r+=bUe.indexOf(this.data[n+1]),t.put(r,11)}this.data.length%2&&t.put(bUe.indexOf(this.data[n]),6)};var tgr=qG;const sgr=zL;function $G(s){this.mode=sgr.BYTE,typeof s=="string"?this.data=new TextEncoder().encode(s):this.data=new Uint8Array(s)}$G.getBitsLength=function(t){return t*8};$G.prototype.getLength=function(){return this.data.length};$G.prototype.getBitsLength=function(){return $G.getBitsLength(this.data.length)};$G.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 igr=VG,Hos={exports:{}};(function(s){var t={single_source_shortest_paths:function(n,r,a){var i={},l={};l[r]=0;var o=t.PriorityQueue.make();o.push(r,0);for(var c,d,u,h,m,p,f,y,v;!o.empty();){c=o.pop(),d=c.value,h=c.cost,m=n[d]||{};for(u in m)m.hasOwnProperty(u)&&(p=m[u],f=h+p,y=l[u],v=typeof l[u]>"u",(v||y>f)&&(l[u]=f,o.push(u,f),i[u]=d))}if(typeof a<"u"&&typeof l[a]>"u"){var g=["Could not find a path from ",r," to ",a,"."].join("");throw new Error(g)}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})(Hos);var ogr=Hos.exports;(function(s){const t=zL,n=Jxr,r=tgr,a=ngr,i=igr,l=zC,o=$j,c=ogr;function d(g){return unescape(encodeURIComponent(g)).length}function u(g,b,j){const S=[];let C;for(;(C=g.exec(j))!==null;)S.push({data:C[0],index:C.index,mode:b,length:C[0].length});return S}function h(g){const b=u(l.NUMERIC,t.NUMERIC,g),j=u(l.ALPHANUMERIC,t.ALPHANUMERIC,g);let S,C;return o.isKanjiModeEnabled()?(S=u(l.BYTE,t.BYTE,g),C=u(l.KANJI,t.KANJI,g)):(S=u(l.BYTE_KANJI,t.BYTE,g),C=[]),b.concat(j,S,C).sort(function(P,M){return P.index-M.index}).map(function(P){return{data:P.data,mode:P.mode,length:P.length}})}function m(g,b){switch(b){case t.NUMERIC:return n.getBitsLength(g);case t.ALPHANUMERIC:return r.getBitsLength(g);case t.KANJI:return i.getBitsLength(g);case t.BYTE:return a.getBitsLength(g)}}function p(g){return g.reduce(function(b,j){const S=b.length-1>=0?b[b.length-1]:null;return S&&S.mode===j.mode?(b[b.length-1].data+=j.data,b):(b.push(j),b)},[])}function f(g){const b=[];for(let j=0;j=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 xgr(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 jUe(s,t,n){const r=s.size,a=mgr.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 vgr(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 bgr(s,t,n){const r=new lgr;n.forEach(function(c){r.put(c.mode.bit,4),r.put(c.getLength(),pgr.getCharCountIndicator(c.mode,s)),c.write(r)});const a=gDe.getSymbolTotalCodewords(s),i=kZe.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&&ygr(c,t),vgr(c,l),isNaN(r)&&(r=NZe.getBestMask(c,jUe.bind(null,c,n))),NZe.applyMask(r,c),jUe(c,n,r),{modules:c,version:t,errorCorrectionLevel:n,maskPattern:r,segments:a}}Los.create=function(t,n){if(typeof t>"u"||t==="")throw new Error("No input text");let r=_Ue.M,a,i;return typeof n<"u"&&(r=_Ue.from(n.errorCorrectionLevel,_Ue.M),a=z6e.from(n.version),i=NZe.from(n.maskPattern),n.toSJISFunc&&gDe.setToSJISFunction(n.toSJISFunc)),wgr(t,a,r,i)};var Gos={},Zit={};(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)}})(Gos);var Wos={};const jgr=Zit;function xAt(s,t){const n=s.a/255,r=t+'="'+s.hex+'"';return n<1?r+" "+t+'-opacity="'+n.toFixed(2).slice(1)+'"':r}function NUe(s,t,n){let r=s+t;return typeof n<"u"&&(r+=" "+n),r}function Ngr(s,t,n){let r="",a=0,i=!1,l=0;for(let o=0;o0&&c>0&&s[o-1]||(r+=i?NUe("M",c+n,.5+d+n):NUe("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 kgr=Bxr,SZe=Los,Kos=Gos,Sgr=Wos;function Xit(s,t,n,r,a){const i=[].slice.call(arguments,1),l=i.length,o=typeof i[l-1]=="function";if(!o&&!kgr())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=SZe.create(n,r);c(s(u,t,r))}catch(u){d(u)}})}try{const c=SZe.create(n,r);a(null,s(c,t,r))}catch(c){a(c)}}yK.create=SZe.create;yK.toCanvas=Xit.bind(null,Kos.render);yK.toDataURL=Xit.bind(null,Kos.renderToDataURL);yK.toString=Xit.bind(null,function(s,t,n){return Sgr.render(s,n)});function Cgr(){const{eventId:s}=Li(),t=Fn(),{data:n}=Hit(s),{data:r=[]}=vos(s),a=wos(),[i,l]=_.useState(""),[o,c]=_.useState(""),[d,u]=_.useState(""),[h,m]=_.useState(""),p=n!=null&&n.public_slug?mDe(n.public_slug):"";_.useEffect(()=>{p&&yK.toDataURL(p,{width:320,margin:1}).then(m).catch(()=>{})},[p]);const f=_.useMemo(()=>i?r.filter(g=>(g.guest_name||"").toLowerCase().includes(i.toLowerCase())||(g.guest_email||"").toLowerCase().includes(i.toLowerCase())):r,[r,i]),y=g=>{a.mutate({id:g.id,event_id:s,status:"attended",checked_in_at:new Date().toISOString()}),se.success(`${g.guest_name||"Guest"} checked in`)},v=()=>{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(""),se.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(B,{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(ve,{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(ve,{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(Hf,{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(ve,{className:"p-5 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[13px] font-semibold text-slate-900 mb-3",children:"Add walk-in"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(xe,{placeholder:"Name",value:o,onChange:g=>c(g.target.value)}),e.jsx(xe,{placeholder:"Email (optional)",value:d,onChange:g=>u(g.target.value)}),e.jsxs(B,{className:"w-full rounded-full",onClick:v,children:[e.jsx(Pl,{className:"h-4 w-4 mr-2"})," Add & check in"]})]})]})]}),e.jsxs(ve,{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(Lr,{className:"absolute left-6 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(xe,{placeholder:"Search attendees",value:i,onChange:g=>l(g.target.value),className:"pl-9 rounded-full border-slate-200"})]}),f.length===0?e.jsx("div",{className:"p-8 text-center text-slate-400 text-[13px]",children:"No matches."}):e.jsx("div",{className:"divide-y divide-slate-100 max-h-[60vh] overflow-auto",children:f.map(g=>{const b=g.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:g.guest_name||g.guest_email}),e.jsx("div",{className:"text-[12px] text-slate-500 truncate",children:g.guest_email})]}),b?e.jsxs(Oe,{className:"bg-emerald-500",children:[e.jsx(ea,{className:"h-3 w-3 mr-1"})," Checked in"]}):e.jsxs(B,{size:"lg",className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>y(g),children:[e.jsx(ea,{className:"h-5 w-5 mr-2"})," Check in"]})]},g.id)})})]})]})}):e.jsx("div",{className:"p-8 text-slate-500",children:"Loading…"})}const Agr=["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"],Egr=["Lead generation","Database marketing","Listing marketing","Social media/video","Open houses","Negotiation","Systems and technology","Team building","Leadership","New construction","Luxury","Business planning"],gAt=[{key:"produce",icon:wl,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:un,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:LQ,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:dS,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:sP,title:"Balanced Plan",blurb:"A little of all four. Best for veteran attractors.",example:"Rotate weekly focus between production, teaching, providing, and connecting."}],Tgr=[{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"}],yAt=["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 vAt(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 Mgr(){const s=Fn(),{settings:t,save:n}=Uit(),[r,a]=_.useState(0),[i,l]=_.useState([]),[o,c]=_.useState([]),[d,u]=_.useState(null),[h,m]=_.useState({}),[p,f]=_.useState("");_.useEffect(()=>{var j,S;t&&((j=t.audiences)!=null&&j.length&&l(t.audiences),(S=t.teachables)!=null&&S.length&&c(t.teachables),t.attraction_style&&u(t.attraction_style),t.activity_baseline&&m(t.activity_baseline),t.ninety_day_outcome&&f(t.ninety_day_outcome))},[t==null?void 0:t.user_id]);const y=["Welcome","Audience","Teach","Style","Baseline","Outcome","Plan"],v=_.useMemo(()=>r===1?i.length>0:r===2?o.length>0:r===3?!!d:r===5?!!p:!0,[r,i,o,d,p]),g=(j,S,C)=>{C(j.includes(S)?j.filter(E=>E!==S):[...j,S])},b=async()=>{if(!d)return;const j=vAt({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:j,primary_pillar:d,onboarding_completed_at:new Date().toISOString()}),se.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:y.map((j,S)=>e.jsx("div",{className:At("h-1.5 flex-1 rounded-full transition-colors",S<=r?"bg-violet-600":"bg-slate-200")},j))}),e.jsx(mW,{mode:"wait",children:e.jsxs(Sr.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:gAt.filter(j=>j.key!=="balanced").map(j=>e.jsxs(ve,{className:"p-4 rounded-2xl border-slate-200",children:[e.jsx(j.icon,{className:"h-5 w-5 text-violet-600 mb-2"}),e.jsx("div",{className:"text-[13px] font-semibold text-slate-900",children:j.title}),e.jsx("div",{className:"text-[11.5px] text-slate-500 mt-0.5",children:j.blurb})]},j.key))})]}),r===1&&e.jsx(KZ,{icon:In,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:Agr.map(j=>e.jsx(kUe,{label:j,active:i.includes(j),onClick:()=>g(i,j,l)},j))})}),r===2&&e.jsx(KZ,{icon:mm,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:Egr.map(j=>e.jsx(kUe,{label:j,active:o.includes(j),onClick:()=>g(o,j,c)},j))})}),r===3&&e.jsx(KZ,{icon:sP,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:gAt.map(j=>e.jsx(ve,{onClick:()=>u(j.key),className:At("p-5 rounded-2xl cursor-pointer transition-all border-2",d===j.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(j.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:j.title}),e.jsx("div",{className:"text-[12.5px] text-slate-600 mt-0.5",children:j.blurb}),e.jsxs("div",{className:"text-[11.5px] text-slate-500 italic mt-2",children:["Example: ",j.example]})]}),d===j.key&&e.jsx(ea,{className:"h-5 w-5 text-violet-600"})]})},j.key))})}),r===4&&e.jsx(KZ,{icon:hm,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:Tgr.map(j=>e.jsxs("div",{children:[e.jsx(J,{className:"text-[12.5px] text-slate-700",children:j.label}),e.jsx(xe,{type:"number",min:0,value:h[j.key]??"",onChange:S=>m({...h,[j.key]:Number(S.target.value)||0})})]},j.key))})}),r===5&&e.jsx(KZ,{icon:ku,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:[yAt.map(j=>e.jsx(kUe,{label:j,active:p===j,onClick:()=>f(j),full:!0},j)),e.jsxs("div",{className:"mt-3",children:[e.jsx(J,{className:"text-[12.5px] text-slate-700",children:"Or write your own"}),e.jsx(Ms,{rows:2,placeholder:"A specific outcome you can measure in 90 days...",value:yAt.includes(p)?"":p,onChange:j=>f(j.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(Pgr,{plan:vAt({style:d,baseline:h,outcome:p})})]})]},r)}),e.jsxs("div",{className:"mt-10 flex items-center justify-between",children:[e.jsxs(B,{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(B,{className:"bg-gradient-to-r from-violet-600 to-indigo-600 rounded-full px-6",disabled:!v,onClick:()=>a(r+1),children:["Continue ",e.jsx(La,{className:"h-4 w-4 ml-1"})]}):e.jsxs(B,{className:"bg-gradient-to-r from-violet-600 to-indigo-600 rounded-full px-6",onClick:b,disabled:n.isPending,children:[e.jsx(Sy,{className:"h-4 w-4 mr-1.5"})," Activate my 90-day plan"]})]})]})}function KZ({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 kUe({label:s,active:t,onClick:n,full:r}){return e.jsx("button",{type:"button",onClick:n,className:At("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(ea,{className:"h-4 w-4 text-violet-600"})," ",s]})})}function Pgr({plan:s}){return e.jsxs("div",{className:"mt-6 space-y-6",children:[e.jsxs(ve,{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(ve,{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(ve,{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(ve,{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(ve,{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 Lgr(){const{user:s}=hs(),t=Bt(),n=at({queryKey:["attract-content",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:o,error:c}=await q.from("attract_content_drafts").select("*").order("updated_at",{ascending:!1});if(c)throw c;return o??[]}}),r=mt({mutationFn:async o=>{const{data:c,error:d}=await q.functions.invoke("attract-content-generate",{body:o});if(d)throw d;if(c!=null&&c.error)throw new Error(c.error);return c},onSuccess:o=>{t.invalidateQueries({queryKey:["attract-content"]}),o.demo?se.info("Demo generation used — configure AI provider for live results"):se.success("Content generated")},onError:o=>se.error(o.message)}),a=mt({mutationFn:async o=>{const{data:c,error:d}=await q.from("attract_content_drafts").update(o).eq("id",o.id).select().single();if(d)throw d;return c},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-content"]}),se.success("Saved")}}),i=mt({mutationFn:async o=>{const{error:c}=await q.from("attract_content_drafts").update({status:"posted",posted_at:new Date().toISOString()}).eq("id",o);if(c)throw c;await q.rpc("award_attract_activity",{_user_id:s.id,_activity_type:"content_posted",_title:"Posted authority content",_description:null,_pillar:"influence",_agent_id:null,_metadata:{draft_id:o},_dedupe_minutes:30})},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-content"]}),t.invalidateQueries({queryKey:["attract-activities"]}),se.success("Marked as posted")}}),l=mt({mutationFn:async o=>{const{error:c}=await q.from("attract_content_drafts").delete().eq("id",o);if(c)throw c},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-content"]}),se.success("Draft removed")}});return{drafts:n.data??[],isLoading:n.isLoading,generate:r,save:a,markPosted:i,remove:l}}const CZe=[{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"}]}],Igr=["Direct","Educational","Fun","Contrarian","Encouraging"],Dgr=["short","medium","long"],Rgr=["instagram","linkedin","facebook","youtube","email"],B6e={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 Fgr(){const{drafts:s,isLoading:t,generate:n,save:r,markPosted:a,remove:i}=Lgr(),[l,o]=_.useState(!1),[c,d]=_.useState(null),u=_.useMemo(()=>({ready:s.filter(h=>h.status==="ready"),draft:s.filter(h=>h.status==="draft"),idea:s.filter(h=>h.status==="idea"),posted:s.filter(h=>h.status==="posted")}),[s]);return e.jsxs("div",{children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-5",children:[e.jsx("div",{className:"text-[13px] text-slate-500 max-w-xl",children:"Turn your real experience into agent-focused content that builds authority — without sounding like a brokerage pitch."}),e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>{d(null),o(!0)},children:[e.jsx(Qx,{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(un,{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(Yr,{defaultValue:"all",className:"mb-8",children:[e.jsxs(Zr,{children:[e.jsxs(Ht,{value:"all",children:["All (",s.length,")"]}),e.jsxs(Ht,{value:"ready",children:["Ready (",u.ready.length,")"]}),e.jsxs(Ht,{value:"draft",children:["Draft (",u.draft.length,")"]}),e.jsxs(Ht,{value:"posted",children:["Posted (",u.posted.length,")"]})]}),e.jsx(Gt,{value:"all",children:e.jsx(bue,{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(Gt,{value:"ready",children:e.jsx(bue,{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(Gt,{value:"draft",children:e.jsx(bue,{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(Gt,{value:"posted",children:e.jsx(bue,{drafts:u.posted,isLoading:t,onOpen:h=>{d(h),o(!0)},onPosted:()=>{},onRemove:h=>i.mutate(h),onEmpty:()=>{d(null),o(!0)}})})]}),e.jsx(Nos,{}),e.jsx(Ogr,{open:l,editing:c,onClose:()=>{o(!1),d(null)},generate:n,save:r,markPosted:h=>a.mutate(h)})]})}function bue({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(ve,{className:"p-5 rounded-2xl h-24 animate-pulse bg-slate-100"},l))}):s.length===0?e.jsxs(ve,{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(Qm,{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(B,{className:"mt-6 rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:i,children:[e.jsx(rn,{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=CZe.find(u=>u.key===l.mode))==null?void 0:c.label)??l.mode;return e.jsx(ve,{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(Oe,{className:At("text-[10.5px] border-0",B6e[l.status].color),children:B6e[l.status].label}),e.jsx(Oe,{variant:"outline",className:"text-[10.5px]",children:o}),l.tone&&e.jsx(Oe,{variant:"outline",className:"text-[10.5px]",children:l.tone}),l.ratio_flag&&e.jsxs(Oe,{className:"text-[10.5px] bg-amber-100 text-amber-900 border-0 gap-1",children:[e.jsx(xl,{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(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>n(l),children:"Open"}),l.status!=="posted"&&e.jsxs(B,{size:"sm",variant:"ghost",className:"text-emerald-700",onClick:()=>r(l.id),children:[e.jsx(ea,{className:"h-3.5 w-3.5 mr-1"})," Posted"]}),e.jsx(B,{size:"sm",variant:"ghost",className:"text-rose-600",onClick:()=>a(l.id),children:e.jsx(Sn,{className:"h-3.5 w-3.5"})})]})]})},l.id)})})}function Ogr({open:s,editing:t,onClose:n,generate:r,save:a,markPosted:i}){const[l,o]=_.useState((t==null?void 0:t.mode)??"transaction_lesson"),[c,d]=_.useState((t==null?void 0:t.input_json)??{}),[u,h]=_.useState((t==null?void 0:t.topic)??""),[m,p]=_.useState((t==null?void 0:t.tone)??"Educational"),[f,y]=_.useState((t==null?void 0:t.length)??"medium"),[v,g]=_.useState((t==null?void 0:t.platforms)??["instagram"]),[b,j]=_.useState((t==null?void 0:t.include_brokerage_reference)??!1),[S,C]=_.useState(t??null),[E,P]=_.useState(""),[M,I]=_.useState((t==null?void 0:t.status)??"draft"),D=CZe.find(G=>G.key===l),O=async G=>{const $=await r.mutateAsync({mode:l,topic:u,inputs:c,tone:m,length:f,platforms:v,include_brokerage_reference:b,refinement:G??E,draft_id:S==null?void 0:S.id});$!=null&&$.draft&&C($.draft),P("")},V=async G=>{if(!S)return;const $=await a.mutateAsync({id:S.id,...G});C($)};return e.jsx(Ls,{open:s,onOpenChange:G=>!G&&n(),children:e.jsx(Ps,{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(Os,{children:[e.jsx(Ds,{className:"text-base",children:"Content Studio"}),e.jsx(_r,{className:"text-[12px]",children:D.blurb})]}),e.jsxs("div",{className:"mt-4 space-y-3",children:[e.jsxs("div",{children:[e.jsx(J,{className:"text-[12px]",children:"Content mode"}),e.jsxs(is,{value:l,onValueChange:G=>{o(G),d({})},children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsx(as,{children:CZe.map(G=>e.jsx(He,{value:G.key,children:G.label},G.key))})]})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-[12px]",children:"Topic (optional)"}),e.jsx(xe,{value:u,onChange:G=>h(G.target.value),placeholder:"1-line summary"})]}),D.fields.map(G=>e.jsxs("div",{children:[e.jsx(J,{className:"text-[12px]",children:G.label}),e.jsx(Ms,{rows:2,value:c[G.key]??"",onChange:$=>d({...c,[G.key]:$.target.value}),placeholder:G.placeholder})]},G.key)),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx(J,{className:"text-[12px]",children:"Tone"}),e.jsxs(is,{value:m,onValueChange:p,children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsx(as,{children:Igr.map(G=>e.jsx(He,{value:G,children:G},G))})]})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-[12px]",children:"Length"}),e.jsxs(is,{value:f,onValueChange:y,children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsx(as,{children:Dgr.map(G=>e.jsx(He,{value:G,children:G},G))})]})]})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-[12px]",children:"Platforms"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1",children:Rgr.map(G=>e.jsx("button",{type:"button",onClick:()=>g(v.includes(G)?v.filter($=>$!==G):[...v,G]),className:At("rounded-full px-2.5 py-1 text-[11px] capitalize border",v.includes(G)?"bg-violet-600 text-white border-violet-600":"bg-white border-slate-200 text-slate-700"),children:G},G))})]}),e.jsxs("label",{className:"flex items-center gap-2 text-[12px] text-slate-700",children:[e.jsx("input",{type:"checkbox",checked:b,onChange:G=>j(G.target.checked)}),"Include a light brokerage reference"]}),e.jsxs(B,{className:"w-full bg-gradient-to-r from-violet-600 to-indigo-600 rounded-full",onClick:()=>O(),disabled:r.isPending,children:[e.jsx(Qx,{className:"h-4 w-4 mr-1.5"})," ",r.isPending?"Generating…":S?"Regenerate":"Generate content"]})]})]}),e.jsx("div",{className:"overflow-y-auto p-6",children:S?e.jsxs("div",{className:"space-y-5",children:[S.ratio_flag&&e.jsxs("div",{className:"rounded-xl border border-amber-200 bg-amber-50 p-3 text-[12.5px] text-amber-900 flex items-start gap-2",children:[e.jsx(xl,{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(B,{size:"sm",variant:"outline",onClick:()=>O("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(Oe,{className:At("text-[10.5px] border-0",B6e[M].color),children:B6e[M].label}),e.jsxs(is,{value:M,onValueChange:G=>{I(G),V({status:G})},children:[e.jsx(rs,{className:"h-8 w-32 text-[12px]",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"idea",children:"Idea"}),e.jsx(He,{value:"draft",children:"Draft"}),e.jsx(He,{value:"ready",children:"Ready"}),e.jsx(He,{value:"posted",children:"Posted"})]})]}),e.jsx(xe,{type:"date",className:"h-8 w-40 text-[12px]",value:S.planned_at?S.planned_at.slice(0,10):"",onChange:G=>V({planned_at:G.target.value?new Date(G.target.value).toISOString():null})}),S.status!=="posted"&&e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>i(S.id),children:[e.jsx(Or,{className:"h-3.5 w-3.5 mr-1"})," Mark posted"]}),e.jsx(B,{size:"sm",variant:"outline",className:"rounded-full",asChild:!0,children:e.jsxs(ir,{to:`/attract/toolkit/kits/new?seed=${encodeURIComponent(S.topic||S.mode)}`,children:[e.jsx(rn,{className:"h-3.5 w-3.5 mr-1"})," Turn into a kit"]})})]}),e.jsx(hU,{title:"Hook options",children:e.jsx("div",{className:"space-y-1.5",children:(S.hook_options??[]).map((G,$)=>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:[$+1,"."]}),e.jsx("span",{className:"flex-1",children:G}),e.jsx(AZe,{value:G})]},$))})}),e.jsx(hU,{title:"Teleprompter script",children:e.jsx(SUe,{value:S.script??"",onSave:G=>V({script:G})})}),e.jsx(hU,{title:"Social caption",children:e.jsx(SUe,{value:S.caption??"",onSave:G=>V({caption:G})})}),e.jsx(hU,{title:"Carousel outline",children:e.jsx("div",{className:"space-y-1.5",children:(S.carousel_outline??[]).map((G,$)=>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 ",G.slide??$+1]}),e.jsx("div",{className:"text-slate-800 mt-0.5",children:G.text})]},$))})}),e.jsx(hU,{title:"Email lesson",children:e.jsx(SUe,{value:S.email_lesson??"",onSave:G=>V({email_lesson:G})})}),e.jsx(hU,{title:"CTA options",children:e.jsx("div",{className:"space-y-1.5",children:(S.cta_options??[]).map((G,$)=>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:G}),e.jsx(AZe,{value:G})]},$))})}),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(G=>e.jsx(B,{size:"sm",variant:"outline",className:"text-[11.5px]",onClick:()=>O(G),children:G},G))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{value:E,onChange:G=>P(G.target.value),placeholder:"Custom refinement…"}),e.jsxs(B,{variant:"outline",onClick:()=>O(),disabled:r.isPending,children:[e.jsx(uo,{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(e$,{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 hU({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(ga,{className:"h-3 w-3 opacity-0"})," ",s]}),t]})}function SUe({value:s,onSave:t}){const[n,r]=_.useState(s);return e.jsxs("div",{children:[e.jsx(Ms,{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(B,{size:"sm",variant:"outline",onClick:()=>t(n),children:"Save edit"}),e.jsx(AZe,{value:n})]})]})}function AZe({value:s}){return e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>{navigator.clipboard.writeText(s),se.success("Copied")},children:e.jsx(Ia,{className:"h-3.5 w-3.5"})})}const zgr={draft:"bg-slate-100 text-slate-700",published:"bg-emerald-100 text-emerald-800",archived:"bg-amber-100 text-amber-800"};function Bgr(){const{kits:s,isLoading:t,create:n,duplicate:r,remove:a}=Git(),i=Fn(),l=async()=>{const o=await n.mutateAsync({title:"Untitled Kit",status:"draft"});i(`/attract/toolkit/kits/${o.id}/edit`)};return e.jsxs("div",{children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-5",children:[e.jsx("div",{className:"text-[13px] text-slate-500",children:"Package the value you already share, then track what actually creates conversations."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",asChild:!0,className:"rounded-full",children:e.jsxs(ir,{to:"/attract/toolkit/kits/templates",children:[e.jsx(fj,{className:"h-4 w-4 mr-2"}),"Starter library"]})}),e.jsxs(B,{onClick:l,className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",children:[e.jsx(rn,{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(ve,{className:"p-10 text-center rounded-2xl border-dashed border-slate-300 bg-white",children:[e.jsx(un,{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(B,{variant:"outline",asChild:!0,children:e.jsx(ir,{to:"/attract/toolkit/kits/templates",children:"Browse starter library"})}),e.jsx(B,{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(ve,{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(Oe,{className:zgr[o.status]+" capitalize",children:o.status}),o.pillar&&e.jsx(Oe,{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(Oe,{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(B,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs(ir,{to:`/attract/toolkit/kits/${o.id}/edit`,children:[e.jsx(Yq,{className:"h-3.5 w-3.5 mr-1.5"}),"Edit"]})}),e.jsx(B,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs(ir,{to:`/attract/toolkit/kits/${o.id}/analytics`,children:[e.jsx(bl,{className:"h-3.5 w-3.5 mr-1.5"}),"Analytics"]})}),e.jsx(B,{size:"sm",variant:"ghost",onClick:async()=>{const d=await r.mutateAsync(o.id);se.success("Duplicated"),i(`/attract/toolkit/kits/${d}/edit`)},children:e.jsx(Ia,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"sm",variant:"ghost",onClick:async()=>{await Xi("Delete this kit? Shares and events will also be removed.")&&a.mutate(o.id,{onSuccess:()=>se.success("Deleted")})},children:e.jsx(Sn,{className:"h-3.5 w-3.5 text-rose-600"})})]})]},o.id)})})]})}const Ugr={pdf:Fr,video:Jd,link:Vc,checklist:Ny,template:WA,text:Fr,content_studio:un,resource:Fr};function Yos({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(ve,{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:qgr(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=Ugr[o.type]??Fr;return e.jsx(ve,{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(B,{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(wr,{className:"h-3.5 w-3.5 mr-1.5"}),"Open"]})}),o.allow_download&&o.type!=="link"&&e.jsx(B,{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(li,{className:"h-3.5 w-3.5 mr-1.5"}),"Download"]})}),o.type==="link"&&e.jsx(B,{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(B,{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 qgr(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 $gr=[{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 bAt(){var G,$;const{kitId:s}=Li(),[t]=Yl(),n=Fn(),{user:r}=hs(),a=s===void 0,{create:i,update:l}=Git(),{data:o,isLoading:c}=Tos(s),{items:d,add:u,update:h,remove:m,reorder:p}=Txr(s),{shares:f,create:y,revoke:v}=Mos(s),{agents:g}=WE(),[b,j]=_.useState(null),[S,C]=_.useState("desktop"),[E,P]=_.useState("idle"),M=_.useRef(null);_.useEffect(()=>{a&&!b&&(async()=>{const H=t.get("seed"),Y=await i.mutateAsync({title:H?`From: ${H}`:"Untitled Kit",status:"draft"});n(`/attract/toolkit/kits/${Y.id}/edit`,{replace:!0})})()},[a]),_.useEffect(()=>{o&&j(o)},[o==null?void 0:o.id]);const I=H=>{s&&(j(Y=>({...Y,...H})),P("saving"),clearTimeout(M.current),M.current=setTimeout(async()=>{try{await l.mutateAsync({id:s,patch:H}),P("saved"),setTimeout(()=>P("idle"),1500)}catch(Y){se.error(Y.message??"Save failed"),P("idle")}},800))},D=async H=>{!s||!r||await u.mutateAsync({user_id:r.id,type:H,title:`New ${H.replace("_"," ")}`})},O=(H,Y)=>{const Z=[...d],ne=H+Y;ne<0||ne>=Z.length||([Z[H],Z[ne]]=[Z[ne],Z[H]],p.mutate(Z.map(ce=>ce.id)))},V=f.filter(H=>H.status==="active");return a||!b?e.jsx("div",{className:"text-slate-500 text-sm",children:"Preparing your kit…"}):c?e.jsx("div",{className:"text-slate-500 text-sm",children:"Loading…"}):e.jsxs("div",{children:[e.jsx(KE,{eyebrow:"Provide · Kit builder",title:b.title||"Untitled Kit",description:E==="saving"?"Saving…":E==="saved"?"Saved":`Last edited ${Hs(new Date(b.updated_at),"MMM d, h:mm a")}`,actions:e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsx(B,{variant:"outline",size:"sm",asChild:!0,className:"rounded-full",children:e.jsxs(ir,{to:"/attract/toolkit/kits",children:[e.jsx(ka,{className:"h-4 w-4 mr-1"}),"Kits"]})}),e.jsx(B,{variant:"outline",size:"sm",asChild:!0,className:"rounded-full",children:e.jsx(ir,{to:`/attract/toolkit/kits/${s}/analytics`,children:"Analytics"})}),e.jsxs(is,{value:b.status,onValueChange:H=>I({status:H}),children:[e.jsx(rs,{className:"w-[130px] rounded-full",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"draft",children:"Draft"}),e.jsx(He,{value:"published",children:"Published"}),e.jsx(He,{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(ve,{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(J,{children:"Title"}),e.jsx(xe,{value:b.title??"",onChange:H=>I({title:H.target.value})})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Short description"}),e.jsx(Ms,{rows:3,value:b.description??"",onChange:H=>I({description:H.target.value})})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Cover image URL"}),e.jsx(xe,{placeholder:"https://…",value:b.cover_image_url??"",onChange:H=>I({cover_image_url:H.target.value})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Audience"}),e.jsx(xe,{placeholder:"e.g. New agents",value:b.audience??"",onChange:H=>I({audience:H.target.value})})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Pillar"}),e.jsxs(is,{value:b.pillar??"",onValueChange:H=>I({pillar:H}),children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Choose"})}),e.jsxs(as,{children:[e.jsx(He,{value:"produce",children:"Produce"}),e.jsx(He,{value:"influence",children:"Influence"}),e.jsx(He,{value:"provide",children:"Provide"}),e.jsx(He,{value:"connect",children:"Connect"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Tags (comma separated)"}),e.jsx(xe,{value:(b.tags??[]).join(", "),onChange:H=>I({tags:H.target.value.split(",").map(Y=>Y.trim()).filter(Boolean)})})]})]})]}),e.jsxs(ve,{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(Ms,{rows:4,placeholder:"Write a short personal note that opens the kit.",value:b.intro_text??"",onChange:H=>I({intro_text:H.target.value})}),e.jsxs("div",{children:[e.jsx(J,{children:"Intro video URL (optional)"}),e.jsx(xe,{placeholder:"Loom/YouTube/Vimeo",value:b.intro_video_url??"",onChange:H=>I({intro_video_url:H.target.value})})]})]})]}),e.jsxs(ve,{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(J,{children:"Button label"}),e.jsx(xe,{value:b.cta_label??"",onChange:H=>I({cta_label:H.target.value})})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Button URL"}),e.jsx(xe,{placeholder:"https://…",value:b.cta_url??"",onChange:H=>I({cta_url:H.target.value})})]})]}),e.jsxs("div",{className:"mt-3",children:[e.jsx(J,{children:"Expiration (optional)"}),e.jsx(xe,{type:"datetime-local",value:b.expires_at?b.expires_at.slice(0,16):"",onChange:H=>I({expires_at:H.target.value?new Date(H.target.value).toISOString():null})})]})]}),e.jsxs(ve,{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(Vgr,{kitId:s,agents:g,shares:V,onCreate:H=>y.mutate(H),onRevoke:H=>v.mutate(H),status:b.status})]})]}),e.jsx("div",{className:"xl:col-span-5 space-y-4",children:e.jsxs(ve,{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(is,{onValueChange:H=>D(H),children:[e.jsx(rs,{className:"w-[180px]",children:e.jsx(ls,{placeholder:"+ Add item"})}),e.jsx(as,{children:$gr.map(H=>e.jsx(He,{value:H.value,children:H.label},H.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((H,Y)=>{var Z,ne;return e.jsx(ve,{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:()=>O(Y,-1),children:e.jsx(sp,{className:"h-4 w-4"})}),e.jsx("button",{className:"text-slate-400 hover:text-slate-700",onClick:()=>O(Y,1),children:e.jsx(zf,{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(Oe,{variant:"outline",className:"capitalize",children:H.type.replace("_"," ")}),e.jsx(xe,{className:"flex-1",value:H.title,onChange:ce=>h.mutate({id:H.id,patch:{title:ce.target.value}})})]}),e.jsx(Ms,{rows:2,placeholder:"Short description",value:H.description??"",onChange:ce=>h.mutate({id:H.id,patch:{description:ce.target.value}})}),["video","pdf","link","resource"].includes(H.type)&&e.jsx(xe,{placeholder:"URL",value:H.url??"",onChange:ce=>h.mutate({id:H.id,patch:{url:ce.target.value}})}),["text","template"].includes(H.type)&&e.jsx(Ms,{rows:4,placeholder:"Body text or script",value:((Z=H.content)==null?void 0:Z.body)??"",onChange:ce=>h.mutate({id:H.id,patch:{content:{...H.content??{},body:ce.target.value}}})}),H.type==="checklist"&&e.jsx(Ms,{rows:5,placeholder:"One item per line",value:(((ne=H.content)==null?void 0:ne.items)??[]).join(` `),onChange:ce=>h.mutate({id:H.id,patch:{content:{items:ce.target.value.split(` `).map(ie=>ie.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(fn,{checked:H.allow_download,onCheckedChange:ce=>h.mutate({id:H.id,patch:{allow_download:ce}})}),"Allow download"]}),e.jsxs("label",{className:"flex items-center gap-2 text-[12px] text-slate-600",children:[e.jsx(fn,{checked:!H.is_hidden,onCheckedChange:ce=>h.mutate({id:H.id,patch:{is_hidden:!ce}})}),"Visible"]}),e.jsxs("button",{className:"ml-auto text-rose-600 text-[12px] flex items-center gap-1",onClick:()=>m.mutate(H.id),children:[e.jsx(Sn,{className:"h-3.5 w-3.5"}),"Delete"]})]})]})]})},H.id)})]})]})}),e.jsx("div",{className:"xl:col-span-3",children:e.jsxs(ve,{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(Yr,{value:S,onValueChange:H=>C(H),children:e.jsxs(Zr,{className:"h-8",children:[e.jsx(Ht,{value:"desktop",className:"h-6 px-2",children:e.jsx(hN,{className:"h-3.5 w-3.5"})}),e.jsx(Ht,{value:"mobile",className:"h-6 px-2",children:e.jsx(p1,{className:"h-3.5 w-3.5"})})]})})]}),e.jsx("div",{className:S==="mobile"?"max-w-[320px] mx-auto":"",children:e.jsx(Yos,{kit:b,items:d,owner:{display_name:((G=r==null?void 0:r.user_metadata)==null?void 0:G.full_name)||(r==null?void 0:r.email)||"You",avatar_url:(($=r==null?void 0:r.user_metadata)==null?void 0:$.avatar_url)??null,brokerage:null},mode:"preview"})})]})})]})]})}function Vgr({kitId:s,agents:t,shares:n,onCreate:r,onRevoke:a,status:i}){const[l,o]=_.useState("general"),[c,d]=_.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(is,{value:l,onValueChange:u=>o(u),children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Choose agent"})}),e.jsxs(as,{children:[e.jsx(He,{value:"general",children:"General share link"}),t.map(u=>e.jsxs(He,{value:u.id,children:[u.first_name," ",u.last_name??""]},u.id))]})]}),e.jsx(Ms,{rows:2,placeholder:"Optional personal note shown on the page",value:c,onChange:u=>d(u.target.value)}),e.jsxs(B,{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(bd,{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=Pos(u.share_token),m=u.agent_id?((p=t.find(f=>f.id===u.agent_id))==null?void 0:p.first_name)??"Agent":"General";return e.jsxs("div",{className:"border rounded-lg p-2.5 text-[12.5px]",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"font-medium",children:m}),e.jsx(Oe,{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(B,{size:"sm",variant:"outline",onClick:()=>{navigator.clipboard.writeText(h),se.success("Link copied")},children:[e.jsx(Ia,{className:"h-3.5 w-3.5 mr-1"}),"Copy"]}),e.jsx(B,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:h,target:"_blank",rel:"noreferrer",children:[e.jsx(wr,{className:"h-3.5 w-3.5 mr-1"}),"Open"]})}),e.jsxs(B,{size:"sm",variant:"ghost",className:"text-rose-600",onClick:()=>a(u.id),children:[e.jsx(VO,{className:"h-3.5 w-3.5 mr-1"}),"Revoke"]})]})]},u.id)})]})]})}const Hgr={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 Ggr(){const{kitId:s}=Li(),{data:t}=Tos(s),{shares:n}=Mos(s),{data:r=[]}=Mxr(s),a=_.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=_.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(KE,{eyebrow:"Kit analytics",title:(t==null?void 0:t.title)??"Kit",description:"Which value is actually creating conversations.",actions:e.jsx(B,{variant:"outline",size:"sm",asChild:!0,className:"rounded-full",children:e.jsxs(ir,{to:`/attract/toolkit/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(RT,{label:"Shares",value:a.shares,icon:ya,tone:"violet"}),e.jsx(RT,{label:"Unique agents",value:a.uniqueAgents,icon:ya,tone:"indigo"}),e.jsx(RT,{label:"View rate",value:`${a.viewRate}%`,icon:ya,tone:"teal"}),e.jsx(RT,{label:"Engaged",value:a.engaged,icon:$h,tone:"emerald"}),e.jsx(RT,{label:"Downloads",value:a.downloads,icon:li,tone:"orange"}),e.jsx(RT,{label:"CTA clicks",value:a.ctaClicks,icon:$h,tone:"rose"}),e.jsx(RT,{label:"Questions",value:a.questions,icon:Ou,tone:"violet"}),e.jsx(RT,{label:"Meetings",value:a.meetings,icon:Qd,tone:"indigo"})]}),e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-3 gap-6",children:[e.jsxs(ve,{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(jb,{width:"100%",height:"100%",children:e.jsxs(Qst,{data:i,children:[e.jsx(kE,{strokeDasharray:"3 3",stroke:"#eee"}),e.jsx(Mv,{dataKey:"date",fontSize:11}),e.jsx(Pv,{fontSize:11,allowDecimals:!1}),e.jsx(Mf,{}),e.jsx(BP,{type:"monotone",dataKey:"count",stroke:"#7c3aed",strokeWidth:2})]})})})]}),e.jsxs(ve,{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(Hgr).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(ve,{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(Oe,{variant:"secondary",className:"capitalize",children:l.engagement_level.replace("_"," ")})]},l.id))]})]})]})}function RT({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(ve,{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 Wgr(){const{data:s=[],isLoading:t}=Pxr(),n=Lxr(),r=Fn(),a=async i=>{try{const l=await n.mutateAsync(i);se.success("Added to your drafts"),r(`/attract/toolkit/kits/${l}/edit`)}catch(l){se.error(l.message??"Could not clone template")}};return e.jsxs("div",{children:[e.jsx(KE,{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(B,{variant:"outline",asChild:!0,className:"rounded-full",children:e.jsxs(ir,{to:"/attract/toolkit/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(ve,{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(un,{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(Oe,{variant:"outline",className:"capitalize",children:i.pillar}),(i.tags??[]).slice(0,4).map(o=>e.jsxs(Oe,{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(B,{className:"mt-4 bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>a(i.id),children:[e.jsx(Qx,{className:"h-4 w-4 mr-2"}),"Use this kit"]})]},i.id)})})]})}const Kgr=q,Ygr=[...cE,hDe],Zgr={hot:gu,warm:fN,cold:sj},YZ=({label:s})=>e.jsxs("span",{className:"text-slate-400 italic",children:["Not recorded",s?` — add ${s}`:""]}),FT=s=>[s.first_name,s.last_name].filter(Boolean).join(" "),Xgr=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 mU({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 Qgr={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 Jgr(){const{agentId:s}=Li(),t=Fn(),{item:n,timeline:r,valueShared:a,nextKit:i,isLoading:l,error:o,refetch:c}=Tfr(s),{data:d=[]}=cDe(),{upsertAgent:u,moveStage:h}=WE(),{followUps:m,complete:p}=uDe(),f=Pfr(),{gmailEmail:y}=Vg(),[v,g]=_.useState("all"),[b,j]=_.useState(!1),[S,C]=_.useState(!1),[E,P]=_.useState("call"),[M,I]=_.useState(""),[D,O]=_.useState(""),[V,G]=_.useState(!1),[$,H]=_.useState(""),[Y,Z]=_.useState(!1),[ne,ce]=_.useState(""),[ie,te]=_.useState(new Date(Date.now()+3*864e5).toISOString().slice(0,10)),[ae,le]=_.useState(null),[be,me]=_.useState(!1),he=_.useMemo(()=>d.filter(Ne=>Ne.agent_id===s&&Ne.status==="open").sort((Ne,Ye)=>Ye.rank_score-Ne.rank_score),[d,s]),pe=_.useMemo(()=>m.filter(Ne=>Ne.agent_id===s),[m,s]),Ce=_.useMemo(()=>{const Ne=tAt.find(Ye=>Ye.key===v);return!Ne||!Ne.kinds.length?r:r.filter(Ye=>Ne.kinds.includes(Ye.kind))},[r,v]);if(l)return e.jsxs("div",{className:"space-y-4",children:[e.jsx(cn,{className:"h-8 w-40"}),e.jsx(cn,{className:"h-40 w-full rounded-2xl"}),e.jsx(cn,{className:"h-64 w-full rounded-2xl"})]});if(o)return e.jsxs(ve,{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(B,{className:"rounded-full mt-4",onClick:()=>c(),children:[e.jsx(uo,{className:"h-4 w-4 mr-2"})," Try again"]})]});if(!n)return e.jsxs(ve,{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(B,{className:"rounded-full mt-4",onClick:()=>t("/attract/agents"),children:"Back to relationships"})]});const Ae=n.agent,Pe=n.signals,ze=Zgr[Ae.temperature??""]??fN,ke=()=>{f.mutate({agent_id:Ae.id,activity_type:E,title:M||`${E.replace(/_/g," ")} with ${FT(Ae)}`,description:D||void 0},{onSuccess:()=>{j(!1),I(""),O("")}})},Ze=async()=>{var Ye;if(!$.trim())return;const Ne=[(Ye=Ae.notes)==null?void 0:Ye.trim(),`[${new Date().toLocaleDateString()}] ${$.trim()}`].filter(Boolean).join(` `);u.mutate({id:Ae.id,first_name:Ae.first_name,notes:Ne},{onSuccess:()=>{G(!1),H(""),c()}}),f.mutate({agent_id:Ae.id,activity_type:"note",title:"Note added",description:$.trim()})},Se=async()=>{if(!ne.trim()){se.error("Give the follow-up a title");return}if(pe.find(qe=>!qe.completed_at&&qe.title.trim().toLowerCase()===ne.trim().toLowerCase())){se.error("An open follow-up with that title already exists");return}const{data:Ye}=await q.auth.getUser(),{error:Ve}=await Kgr.from("attract_follow_ups").insert({user_id:Ye.user.id,agent_id:Ae.id,title:ne.trim(),due_at:new Date(`${ie}T12:00:00`).toISOString(),touch_type:"call",priority:"medium"});if(Ve){se.error(Ve.message);return}se.success("Follow-up created"),Z(!1),ce(""),c()},Fe=()=>{ae&&(window.open(ae.href,"_self"),f.mutate({agent_id:Ae.id,activity_type:ae.kind,title:`${ae.kind==="call"?"Called":ae.kind==="text"?"Texted":"Emailed"} ${FT(Ae)}`}),le(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(ir,{to:"/attract",className:"hover:text-violet-700",children:"Attract"}),e.jsx(xi,{className:"h-3 w-3"}),e.jsx(ir,{to:"/attract/agents",className:"hover:text-violet-700",children:"Relationships"}),e.jsx(xi,{className:"h-3 w-3"}),e.jsx("span",{className:"text-slate-800 font-medium truncate",children:FT(Ae)})]}),e.jsxs(ve,{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(B,{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:[Ae.photo_url?e.jsx("img",{src:Ae.photo_url,alt:`${FT(Ae)} 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:Xgr(Ae)}),e.jsxs("div",{className:"flex-1 min-w-[220px]",children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:FT(Ae)}),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:Ae.brokerage||"Brokerage not recorded"}),e.jsx("span",{className:"opacity-40",children:"·"}),e.jsx("span",{children:[Ae.city,Ae.state].filter(Boolean).join(", ")||"Market not recorded"}),Ae.is_demo&&e.jsx(Oe,{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(Oe,{className:"rounded-full bg-white/10 text-white border-transparent",children:xos(Ae.stage)}),e.jsxs(Oe,{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"})," ",Ae.temperature??"temperature unset"]}),e.jsx(qit,{score:n.score,className:"bg-white/10 text-white ring-white/20"}),(Ae.tags??[]).map(Ne=>e.jsx(Oe,{variant:"outline",className:"rounded-full bg-transparent text-slate-200 border-white/20",children:Ne},Ne))]})]}),e.jsxs("div",{className:"text-[12px] text-slate-300 space-y-1 min-w-[190px]",children:[e.jsx("div",{children:Ae.email?e.jsx("a",{className:"hover:text-white underline decoration-white/30",href:`mailto:${Ae.email}`,children:Ae.email}):"No email on file"}),e.jsx("div",{children:Ae.phone?e.jsx("a",{className:"hover:text-white underline decoration-white/30",href:`tel:${Ae.phone}`,children:Ae.phone}):"No phone on file"}),e.jsxs("div",{children:["Last meaningful touch: ",Pe.lastTouchAt?`${new Date(Pe.lastTouchAt).toLocaleDateString()} (${Pe.daysSinceTouch}d ago)`:"never logged"]}),e.jsxs("div",{children:["Next follow-up: ",Ae.next_follow_up_at?new Date(Ae.next_follow_up_at).toLocaleDateString():"none scheduled"]}),e.jsxs("div",{children:["Source: ",Ae.source||"not recorded"," · Owner: ",Ae.relationship_owner||"you"]})]})]})]}),e.jsxs("div",{className:"p-3 sm:p-4 bg-white flex flex-wrap gap-2",children:[e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>C(!0),children:[e.jsx(Ya,{className:"h-3.5 w-3.5 mr-1.5"})," Edit contact"]}),e.jsxs(Ls,{open:b,onOpenChange:j,children:[e.jsx(nl,{asChild:!0,children:e.jsxs(B,{size:"sm",className:"rounded-full btn-primary text-white",children:[e.jsx(Er,{className:"h-3.5 w-3.5 mr-1.5"})," Log touch"]})}),e.jsxs(Ps,{children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Log a conversation"}),e.jsx(_r,{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(J,{children:"Type"}),e.jsxs(is,{value:E,onValueChange:P,children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsx(as,{children:["call","text","email","dm","meeting","note"].map(Ne=>e.jsx(He,{value:Ne,className:"capitalize",children:Ne},Ne))})]})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Title"}),e.jsx(xe,{value:M,onChange:Ne=>I(Ne.target.value),placeholder:`Call with ${Ae.first_name}`})]}),e.jsxs("div",{children:[e.jsx(J,{children:"What happened"}),e.jsx(Ms,{rows:4,value:D,onChange:Ne=>O(Ne.target.value)})]})]}),e.jsx(yr,{children:e.jsx(B,{className:"rounded-full btn-primary text-white",onClick:ke,disabled:f.isPending,children:"Log it"})})]})]}),e.jsxs(Ls,{open:V,onOpenChange:G,children:[e.jsx(nl,{asChild:!0,children:e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",children:[e.jsx(c7,{className:"h-3.5 w-3.5 mr-1.5"})," Add note"]})}),e.jsxs(Ps,{children:[e.jsx(Os,{children:e.jsx(Ds,{children:"Add a relationship note"})}),e.jsx(Ms,{rows:5,value:$,onChange:Ne=>H(Ne.target.value),placeholder:"What did you learn about them?"}),e.jsx(yr,{children:e.jsx(B,{className:"rounded-full btn-primary text-white",onClick:Ze,children:"Save note"})})]})]}),e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",disabled:!Ae.phone,onClick:()=>Ae.phone&&le({kind:"call",href:`tel:${Ae.phone}`}),children:[e.jsx(_a,{className:"h-3.5 w-3.5 mr-1.5"})," Call"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",disabled:!Ae.phone,onClick:()=>Ae.phone&&le({kind:"text",href:`sms:${Ae.phone}`}),children:[e.jsx(Hi,{className:"h-3.5 w-3.5 mr-1.5"})," Text"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",disabled:!Ae.email,onClick:()=>Ae.email&&me(!0),children:[e.jsx(ln,{className:"h-3.5 w-3.5 mr-1.5"})," Email"]}),e.jsx(B,{size:"sm",variant:"outline",className:"rounded-full",asChild:!0,children:e.jsxs(ir,{to:"/attract/toolkit/kits",children:[e.jsx(fj,{className:"h-3.5 w-3.5 mr-1.5"})," Share kit"]})}),e.jsx(B,{size:"sm",variant:"outline",className:"rounded-full",asChild:!0,children:e.jsxs(ir,{to:"/attract/toolkit/events",children:[e.jsx(gy,{className:"h-3.5 w-3.5 mr-1.5"})," Invite to event"]})}),e.jsxs(Ls,{open:Y,onOpenChange:Z,children:[e.jsx(nl,{asChild:!0,children:e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",children:[e.jsx(Gr,{className:"h-3.5 w-3.5 mr-1.5"})," Create follow-up"]})}),e.jsxs(Ps,{children:[e.jsx(Os,{children:e.jsx(Ds,{children:"Create a follow-up"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(J,{children:"What will you do?"}),e.jsx(xe,{value:ne,onChange:Ne=>ce(Ne.target.value),placeholder:"Call about their Q3 goals"})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Due"}),e.jsx(xe,{type:"date",value:ie,onChange:Ne=>te(Ne.target.value)})]})]}),e.jsx(yr,{children:e.jsx(B,{className:"rounded-full btn-primary text-white",onClick:Se,children:"Create"})})]})]}),e.jsxs(is,{value:dE(Ae.stage).key,onValueChange:Ne=>{const Ye=Vit(Ne);Ye!==Ae.stage&&h.mutate({id:Ae.id,to_stage:Ye,from_stage:Ae.stage})},children:[e.jsxs(rs,{className:"w-[230px] h-9 rounded-full text-[13px]","aria-label":"Change relationship stage",children:[e.jsx(U4,{className:"h-3.5 w-3.5 mr-1.5 opacity-60"}),e.jsx(ls,{})]}),e.jsx(as,{children:Ygr.map(Ne=>e.jsx(He,{value:Ne.key,children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"h-2 w-2 rounded-full",style:{background:Ne.color}}),Ne.label]})},Ne.key))})]})]})]}),e.jsx(Ls,{open:!!ae,onOpenChange:Ne=>!Ne&&le(null),children:e.jsxs(Ps,{children:[e.jsxs(Os,{children:[e.jsxs(Ds,{children:["Open your ",(ae==null?void 0:ae.kind)==="email"?"email app":(ae==null?void 0:ae.kind)==="text"?"messaging app":"phone app","?"]}),e.jsx(_r,{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(yr,{children:[e.jsx(B,{variant:"ghost",className:"rounded-full",onClick:()=>le(null),children:"Cancel"}),e.jsx(B,{className:"rounded-full btn-primary text-white",onClick:Fe,children:"Continue"})]})]})}),e.jsxs(Yr,{defaultValue:"overview",children:[e.jsx(Zr,{className:"rounded-full bg-white border border-slate-200 p-1 flex-wrap h-auto",children:["overview","timeline","value","events","followups","notes"].map(Ne=>e.jsx(Ht,{value:Ne,className:"rounded-full text-[13px] capitalize data-[state=active]:bg-violet-600 data-[state=active]:text-white",children:Ne==="value"?"Value shared":Ne==="followups"?"Follow-ups":Ne==="notes"?"Notes & insights":Ne},Ne))}),e.jsxs(Gt,{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(ve,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-violet-600 mb-3",children:"Next best relationship touch"}),he[0]?e.jsx(F6e,{rec:he[0],agentName:FT(Ae),agentStage:Ae.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(ve,{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(mU,{label:"Goals",children:Ae.goals||e.jsx(YZ,{label:"their goals"})}),e.jsx(mU,{label:"Challenges",children:Ae.challenges||e.jsx(YZ,{label:"their challenges"})}),e.jsx(mU,{label:"Interests",children:Ae.interests||e.jsx(YZ,{label:"interests"})}),e.jsx(mU,{label:"Production context",children:Ae.production_context||e.jsx(YZ,{label:"production context"})}),e.jsx(mU,{label:"Primary pillar",children:Ae.primary_pillar?e.jsx("span",{className:"capitalize",children:Ae.primary_pillar}):e.jsx(YZ,{label:"a pillar"})}),e.jsx(mU,{label:"Added to pipeline",children:new Date(Ae.created_at).toLocaleDateString()})]})]}),e.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-4 gap-3",children:[{label:"Touches (90d)",value:Pe.touches90},{label:"Kits shared",value:Pe.shares.length},{label:"Kit opens",value:Pe.totalKitOpens},{label:"Events attended",value:Pe.attended}].map(Ne=>e.jsxs(ve,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-2xl font-semibold tabular-nums text-slate-900",children:Ne.value}),e.jsx("div",{className:"text-[11.5px] text-slate-500 mt-0.5",children:Ne.label})]},Ne.label))})]}),e.jsxs(ve,{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(hos,{score:n.score})]})]}),he.length>1&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-slate-500",children:"Other open recommendations"}),he.slice(1).map(Ne=>e.jsx(F6e,{rec:Ne,agentName:FT(Ae),showAgentLink:!1,compact:!0},Ne.id))]})]}),e.jsx(Gt,{value:"timeline",className:"mt-5",children:e.jsxs(ve,{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:tAt.map(Ne=>e.jsx("button",{onClick:()=>g(Ne.key),className:At("rounded-full px-3 py-1.5 text-[12px] font-medium transition-colors",v===Ne.key?"bg-violet-600 text-white":"bg-slate-100 text-slate-600 hover:bg-slate-200"),children:Ne.label},Ne.key))}),e.jsxs(B,{size:"sm",className:"rounded-full btn-primary text-white",onClick:()=>j(!0),children:[e.jsx(Er,{className:"h-3.5 w-3.5 mr-1.5"})," Log something"]})]}),Ce.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"}),Ce.map(Ne=>e.jsxs("li",{className:"relative pb-5",children:[e.jsx("span",{"aria-hidden":!0,className:At("absolute -left-[15px] sm:-left-[18px] top-1.5 h-2.5 w-2.5 rounded-full ring-2 ring-white",Qgr[Ne.kind]??"bg-slate-300")}),e.jsx("div",{className:"text-[13.5px] font-medium text-slate-900",children:Ne.title}),Ne.detail&&e.jsx("div",{className:"text-[12.5px] text-slate-600 mt-0.5 whitespace-pre-wrap",children:Ne.detail}),e.jsxs("div",{className:"text-[11px] text-slate-400 mt-1",children:[new Date(Ne.at).toLocaleString()," · ",e.jsx("span",{className:"capitalize",children:Ne.kind.replace(/_/g," ")})]})]},Ne.id))]}):e.jsx("div",{className:"py-10 text-center text-[13.5px] text-slate-500",children:"Nothing in this view yet. Log a conversation to start the history."})]})}),e.jsxs(Gt,{value:"value",className:"mt-5 space-y-4",children:[i&&e.jsxs(ve,{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(B,{size:"sm",className:"rounded-full mt-3 btn-primary text-white",asChild:!0,children:e.jsx(ir,{to:"/attract/toolkit/kits",children:"Open Resource Kits"})})]}),a.length?a.map(Ne=>e.jsxs(ve,{className:"p-4 sm:p-5 rounded-2xl",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-900",children:Ne.kitTitle}),e.jsxs("div",{className:"text-[12px] text-slate-500 mt-0.5",children:["Sent ",new Date(Ne.share.created_at).toLocaleDateString()," ·",Ne.firstViewedAt?` first viewed ${new Date(Ne.firstViewedAt).toLocaleDateString()}`:" never viewed",Ne.lastViewedAt?` · last viewed ${new Date(Ne.lastViewedAt).toLocaleDateString()}`:""]})]}),e.jsx(Oe,{variant:"outline",className:At("rounded-full border-transparent ring-1",Ne.classification==="High Intent"?"bg-rose-50 text-rose-700 ring-rose-200":Ne.classification==="Engaged"?"bg-teal-50 text-teal-700 ring-teal-200":Ne.classification==="Viewed"?"bg-amber-50 text-amber-700 ring-amber-200":"bg-slate-50 text-slate-600 ring-slate-200"),children:Ne.classification})]}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-5 gap-3 mt-4",children:[["Visits",Ne.visits],["Downloads",Ne.downloads],["Link clicks",Ne.ctaClicks],["Questions",Ne.questions],["Meeting asks",Ne.meetingRequests]].map(([Ye,Ve])=>e.jsxs("div",{className:"rounded-xl bg-slate-50 p-2.5",children:[e.jsx("div",{className:"text-[17px] font-semibold tabular-nums text-slate-900",children:Ve}),e.jsx("div",{className:"text-[10.5px] text-slate-500",children:Ye})]},Ye))}),e.jsxs("div",{className:"mt-3 text-[12.5px] text-slate-600 space-y-1",children:[e.jsxs("div",{children:["Link status: ",e.jsx("span",{className:"capitalize font-medium",children:Ne.share.status})]}),e.jsxs("div",{children:["Follow-up after sharing: ",Ne.followUp?`${Ne.followUp.title}${Ne.followUp.completed_at?" (completed)":" (open)"}`:"none created"]}),e.jsxs("div",{children:["Stage movement after sharing: ",Ne.stageAdvancedAfter?`moved to ${Ne.stageAdvancedAfter.to_stage.replace(/_/g," ")} on ${new Date(Ne.stageAdvancedAfter.created_at).toLocaleDateString()}`:"no stage movement yet"]})]}),e.jsx(B,{size:"sm",variant:"outline",className:"rounded-full mt-3",asChild:!0,children:e.jsxs("a",{href:Ne.shareUrl,target:"_blank",rel:"noreferrer",children:["Open share link ",e.jsx(wr,{className:"h-3.5 w-3.5 ml-1.5"})]})})]},Ne.share.id)):e.jsxs(ve,{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(Gt,{value:"events",className:"mt-5 space-y-3",children:Pe.attendees.length?Pe.attendees.map(Ne=>e.jsx(ve,{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(ir,{to:`/attract/events/${Ne.event_id}`,className:"text-[14.5px] font-semibold text-slate-900 hover:text-violet-700",children:"View event"}),e.jsxs("div",{className:"text-[12px] text-slate-500 mt-0.5",children:[Ne.invited_at&&`Invited ${new Date(Ne.invited_at).toLocaleDateString()} · `,Ne.registered_at?`Registered ${new Date(Ne.registered_at).toLocaleDateString()}`:"Not registered",Ne.checked_in_at&&` · Attended ${new Date(Ne.checked_in_at).toLocaleDateString()}`,Ne.no_show_at&&" · No-show"]})]}),e.jsx(Oe,{variant:"outline",className:"rounded-full capitalize",children:Ne.followup_status?`follow-up ${Ne.followup_status}`:Ne.status??"invited"})]})},Ne.id)):e.jsxs(ve,{className:"p-8 rounded-2xl text-center",children:[e.jsx(x0,{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(B,{size:"sm",className:"rounded-full mt-4 btn-primary text-white",asChild:!0,children:e.jsx(ir,{to:"/attract/toolkit/events",children:"See your events"})})]})}),e.jsx(Gt,{value:"followups",className:"mt-5 space-y-3",children:pe.length?pe.map(Ne=>{const Ye=!Ne.completed_at&&Ne.due_at&&new Date(Ne.due_at)p.mutate(Ne.id),children:[e.jsx(Er,{className:"h-3.5 w-3.5 mr-1.5"})," Complete"]})]},Ne.id)}):e.jsxs(ve,{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(B,{size:"sm",className:"rounded-full mt-4 btn-primary text-white",onClick:()=>Z(!0),children:"Create one"})]})}),e.jsxs(Gt,{value:"notes",className:"mt-5 space-y-4",children:[e.jsxs(ve,{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(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>G(!0),children:"Add note"})]}),Ae.notes?e.jsx("div",{className:"text-[13.5px] text-slate-700 whitespace-pre-wrap",children:Ae.notes}):e.jsx("div",{className:"text-[13px] text-slate-500",children:"No notes recorded yet."})]}),e.jsxs(ve,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-slate-500 mb-2",children:"What the data says"}),e.jsx("ul",{className:"text-[13px] text-slate-700 space-y-1.5 list-disc pl-4",children:[...n.score.positives.map(Ne=>`Strength: ${Ne}`),...n.score.negatives.map(Ne=>`Risk: ${Ne}`),...n.score.improvements.map(Ne=>`Next: ${Ne}`)].map((Ne,Ye)=>e.jsx("li",{children:Ne},Ye))})]})]})]}),e.jsx(kos,{agent:Ae,open:S,onOpenChange:C,onDeleted:()=>t("/attract/agents")}),Ae.email&&e.jsx(DS,{open:be,onOpenChange:me,contact:{id:Ae.id,first_name:Ae.preferred_name||Ae.first_name,last_name:Ae.last_name||"",email:Ae.email},gmailEmail:y,sendSource:"attract",logTouchpoint:!1,onSendComplete:()=>{f.mutate({agent_id:Ae.id,activity_type:"email",title:`Emailed ${FT(Ae)}`})}})]})}const e0r=[{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 t0r(){const{intel:s,byId:t,isLoading:n,error:r,refetch:a}=gK(),{data:i=[],isLoading:l}=cDe(),o=dDe();$it();const[c,d]=_.useState(""),[u,h]=_.useState("all"),[m,p]=_.useState("open"),f=g=>{var j;const b=(j=t.get(g))==null?void 0:j.agent;return b?[b.first_name,b.last_name].filter(Boolean).join(" "):"Unknown agent"},y=_.useMemo(()=>{const g=Date.now();return i.filter(b=>m==="open"?b.status==="open"||b.status==="snoozed"&&b.snoozed_until&&+new Date(b.snoozed_until)<=g:m==="snoozed"?b.status==="snoozed":m==="done"?b.status==="completed":m==="dismissed"?b.status==="dismissed":!0).filter(b=>u==="all"||b.signal_group===u).filter(b=>{if(!c.trim())return!0;const j=c.toLowerCase();return f(b.agent_id).toLowerCase().includes(j)||b.title.toLowerCase().includes(j)||(b.reasons??[]).join(" ").toLowerCase().includes(j)}).sort((b,j)=>j.rank_score-b.rank_score)},[i,m,u,c,t]),v=_.useMemo(()=>{const g=i.filter(b=>b.status==="open");return{open:g.length,urgent:g.filter(b=>b.priority==="urgent").length,highIntent:g.filter(b=>b.signal_group==="high_intent").length,overdue:g.filter(b=>b.suggested_due_at&&+new Date(b.suggested_due_at)e.jsx(cn,{className:"h-28 w-full rounded-2xl"},g))}):r?e.jsxs(ve,{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(B,{className:"rounded-full mt-4",onClick:()=>a(),children:[e.jsx(uo,{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(B,{variant:"outline",className:"rounded-full",onClick:()=>o.mutate(s),disabled:o.isPending,children:[e.jsx(uo,{className:At("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:v.open},{label:"Urgent",value:v.urgent},{label:"High intent signals",value:v.highIntent},{label:"Past suggested date",value:v.overdue}].map(g=>e.jsxs(ve,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-2xl font-semibold tabular-nums text-slate-900",children:g.value}),e.jsx("div",{className:"text-[11.5px] text-slate-500 mt-0.5",children:g.label})]},g.label))}),e.jsxs(ve,{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(Lr,{className:"h-4 w-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400"}),e.jsx(xe,{value:c,onChange:g=>d(g.target.value),placeholder:"Search agents or reasons",className:"pl-9 rounded-full h-9","aria-label":"Search recommendations"})]}),e.jsxs(is,{value:u,onValueChange:h,children:[e.jsxs(rs,{className:"w-[190px] h-9 rounded-full text-[13px]",children:[e.jsx(D_,{className:"h-3.5 w-3.5 mr-1.5 opacity-60"}),e.jsx(ls,{})]}),e.jsx(as,{children:e0r.map(g=>e.jsx(He,{value:g.key,children:g.label},g.key))})]}),e.jsxs(is,{value:m,onValueChange:p,children:[e.jsx(rs,{className:"w-[150px] h-9 rounded-full text-[13px]",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"open",children:"Needs action"}),e.jsx(He,{value:"snoozed",children:"Snoozed"}),e.jsx(He,{value:"done",children:"Completed"}),e.jsx(He,{value:"dismissed",children:"Dismissed"}),e.jsx(He,{value:"all",children:"All"})]})]})]}),y.length?e.jsx("div",{className:"space-y-3",children:y.map(g=>{var b;return e.jsx(F6e,{rec:g,agentName:f(g.agent_id),agentStage:(b=t.get(g.agent_id))==null?void 0:b.agent.stage},g.id)})}):i.length?e.jsx(Rfr,{label:"Nothing matches this view. Try switching the filter."}):e.jsxs(ve,{className:"p-10 rounded-2xl text-center",children:[e.jsx(un,{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(B,{className:"rounded-full btn-primary text-white",asChild:!0,children:e.jsx(ir,{to:"/attract/agents",children:"Open pipeline"})}),e.jsx(B,{variant:"outline",className:"rounded-full",asChild:!0,children:e.jsx(ir,{to:"/attract/toolkit/kits",children:"Share a kit"})})]})]}),!!y.length&&e.jsxs("div",{className:"text-[11.5px] text-slate-400",children:["Showing ",y.length," of ",i.length," tracked recommendations · grouped signals: ",[...new Set(y.map(g=>pos(g.signal_group)))].join(", ")]})]})}const CUe=s=>[s.first_name,s.last_name].filter(Boolean).join(" ");function s0r(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 n0r(s,t,n=new Date){const r=s0r(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:CUe(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:CUe(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),f=t.shares.filter(M=>new Date(M.created_at)>=i),y={shares:f.length,opened:t.shares.filter(M=>M.first_opened_at&&new Date(M.first_opened_at)>=i).length,engaged:t.shares.filter(M=>M.engagement_level==="engaged").length,high_intent:t.shares.filter(M=>M.engagement_level==="high_intent").length,downloads:t.kitEvents.filter(M=>M.event_type==="file_download"&&new Date(M.created_at)>=i).length,questions:t.kitEvents.filter(M=>M.event_type==="question_submitted"&&new Date(M.created_at)>=i).length},v={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}))},g=[...s.filter(M=>M.agent.next_follow_up_at&&new Date(M.agent.next_follow_up_at)>n&&d0(n,M.agent.next_follow_up_at)<=7).slice(0,5).map(M=>({label:CUe(M.agent),detail:`Follow-up scheduled ${new Date(M.agent.next_follow_up_at).toLocaleDateString()}`})),...v.upcoming.map(M=>({label:M.title,detail:M.starts_at?`Event on ${new Date(M.starts_at).toLocaleDateString()}`:"Event scheduled"}))].slice(0,6),b=t.activities.filter(M=>new Date(M.created_at)>=i),j={produce:0,influence:0,provide:0,connect:0};for(const M of b)M.pillar&&j[M.pillar]!==void 0&&j[M.pillar]++;const S=Object.entries(j).map(([M,I])=>({pillar:M,count:I})),C=S.slice().sort((M,I)=>M.count-I.count)[0],E=t.primaryPillar?`Your 90-day primary pillar is ${t.primaryPillar}. This week your lightest pillar was ${C.pillar} (${C.count} activities) — give it one deliberate rep.`:`Your lightest pillar this week was ${C.pillar} (${C.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:b.filter(M=>["touch_logged","call","text","email","dm","meeting"].includes(M.activity_type)).length,kits_shared:f.length};return{week_start:r.toISOString().slice(0,10),week_end:a.toISOString().slice(0,10),generated_at:n.toISOString(),conversations:c,high_intent:u,renewed:h,overdue:m,stale:p,kit_summary:y,event_summary:v,upcoming_opportunities:g,pillar_balance:S,recommended_focus:E,wins:P}}const LI=q,r0r=[{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 a0r(){const{user:s}=hs(),t=Bt(),{intel:n,dataset:r,isLoading:a,refetch:i}=gK(),l=dDe(),o=uos(),[c,d]=_.useState(""),[u,h]=_.useState(!1),m=_.useMemo(()=>r?n0r(n,r):null,[n,r]),p=_.useMemo(()=>{const v=c.toLowerCase().trim();return n.filter(g=>!v||`${g.agent.first_name} ${g.agent.last_name??""}`.toLowerCase().includes(v))},[n,c]),f=async()=>{if(!s)return;h(!0);const{data:v}=await LI.from("attract_agents").select("id").eq("user_id",s.id).eq("is_demo",!0);if((v??[]).length){se.info("Demo agents already exist"),h(!1);return}const{data:g,error:b}=await LI.from("attract_agents").insert(r0r.map(S=>({...S,user_id:s.id,is_demo:!0,source:"demo_seed"}))).select("id, first_name");if(b){se.error(b.message),h(!1);return}const j=Date.now();await LI.from("attract_activities").insert((g??[]).map((S,C)=>({user_id:s.id,agent_id:S.id,activity_type:"touch_logged",pillar:"connect",title:`Demo conversation with ${S.first_name}`,created_at:new Date(j-(C+1)*14*864e5).toISOString()}))),await LI.from("attract_follow_ups").insert({user_id:s.id,agent_id:g[0].id,title:"Demo overdue commitment",touch_type:"call",priority:"high",due_at:new Date(j-6*864e5).toISOString()}),se.success("Demo relationships seeded"),h(!1),t.invalidateQueries({queryKey:["attract-intel-data"]}),i()},y=async()=>{if(!s)return;h(!0);const{data:v}=await LI.from("attract_agents").select("id").eq("user_id",s.id).eq("is_demo",!0),g=(v??[]).map(b=>b.id);if(!g.length){se.info("No demo data to clear"),h(!1);return}for(const b of["attract_recommendations","attract_agent_scores","attract_follow_ups","attract_activities"])await LI.from(b).delete().in("agent_id",g);await LI.from("attract_agents").delete().in("id",g),se.success("Demo data removed"),h(!1),t.invalidateQueries({queryKey:["attract-intel-data"]}),i()};return a?e.jsx(cn,{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(B,{variant:"ghost",size:"sm",className:"rounded-full -ml-2",asChild:!0,children:e.jsxs(ir,{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(B,{variant:"outline",className:"rounded-full",onClick:()=>{o.mutate({items:n}),l.mutate(n)},disabled:l.isPending||o.isPending,children:[e.jsx(uo,{className:"h-3.5 w-3.5 mr-1.5"})," Recompute & persist"]}),e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:f,disabled:u,children:[e.jsx(vQ,{className:"h-3.5 w-3.5 mr-1.5"})," Seed demo relationships"]}),e.jsxs(B,{variant:"outline",className:"rounded-full text-destructive",onClick:y,disabled:u,children:[e.jsx(Sn,{className:"h-3.5 w-3.5 mr-1.5"})," Clear demo data"]})]}),e.jsxs(Yr,{defaultValue:"agents",children:[e.jsxs(Zr,{className:"rounded-full",children:[e.jsx(Ht,{value:"agents",className:"rounded-full",children:"Scores & signals"}),e.jsx(Ht,{value:"digest",className:"rounded-full",children:"Digest payload"})]}),e.jsxs(Gt,{value:"agents",className:"mt-4 space-y-3",children:[e.jsx(xe,{value:c,onChange:v=>d(v.target.value),placeholder:"Filter by name",className:"max-w-sm rounded-full"}),!p.length&&e.jsx(ve,{className:"p-6 rounded-2xl text-[13.5px] text-muted-foreground",children:"No agents in your Attract pipeline."}),p.map(v=>e.jsxs(ve,{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(ir,{to:`/attract/agents/${v.agent.id}`,className:"text-[15px] font-semibold hover:text-violet-700",children:[v.agent.first_name,v.agent.last_name].filter(Boolean).join(" ")}),e.jsxs("div",{className:"text-[12px] text-muted-foreground mt-0.5 capitalize",children:[v.agent.stage.replace(/_/g," ")," · ",v.agent.temperature??"no temperature"," · ",v.signals.daysSinceTouch??"—"," days since touch"]})]}),v.agent.is_demo&&e.jsx(Oe,{variant:"outline",className:"rounded-full",children:"Demo"})]}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-4 mt-4",children:[e.jsx(hos,{score:v.score}),e.jsxs("div",{children:[e.jsxs("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-muted-foreground mb-1.5",children:["Recommendations (",v.recommendations.length,")"]}),v.recommendations.length?e.jsx("ul",{className:"space-y-2",children:v.recommendations.map(g=>e.jsxs("li",{className:"text-[12.5px]",children:[e.jsx("span",{className:"font-medium",children:g.title}),e.jsxs("span",{className:"text-muted-foreground",children:[" · ",g.signal_group," · rank ",g.rank_score," · ",g.priority]}),e.jsx("div",{className:"text-muted-foreground",children:g.reasons.join(" · ")})]},g.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:v.signals.touches90,kitShares:v.signals.shares.length,kitOpens:v.signals.totalKitOpens,questions:v.signals.questions,meetingRequests:v.signals.meetingRequests,overdueFollowUps:v.signals.overdueFollowUps.length,attended:v.signals.attended},null,2)})]})]},v.agent.id))]}),e.jsx(Gt,{value:"digest",className:"mt-4",children:e.jsx(ve,{className:"p-4 rounded-2xl",children:e.jsx("pre",{className:"text-[11px] bg-muted p-3 rounded-lg overflow-auto max-h-[600px]",children:JSON.stringify(m,null,2)})})})]})]})}const _At=[{key:"today",pillar:"core",title:"Today",route:"/attract",status:"live",tables:["attract_recommendations","attract_follow_ups","attract_daily_plan"],notes:"Prioritized daily queue of recruiting moves."},{key:"agents",pillar:"core",title:"Agents (pipeline)",route:"/attract/agents",status:"live",tables:["attract_agents","attract_pipeline_history"],notes:"Needs-attention, stage board and list in one page."},{key:"agent_detail",pillar:"core",title:"Agent detail",route:"/attract/agents/:agentId",status:"live",tables:["attract_agents","attract_activities","attract_follow_ups"],notes:"Timeline, touches, kits shared, notes."},{key:"calculator",pillar:"core",title:"Comp calculator",route:"/attract/calculator",status:"live",tables:[],notes:"Live split/cap comparison; copy, print or email the one-pager."},{key:"attract_page",pillar:"core",title:"Attraction landing page",route:"/attract/attract-page",status:"live",tables:["attract_landing_pages","attract_landing_events"],notes:"Public join page with lead magnet and calculator."},{key:"results",pillar:"core",title:"Results",route:"/attract/results",status:"live",tables:["attract_agents","attract_activities"],notes:"Joins, pipeline conversion, days-to-join, attribution."},{key:"follow_up",pillar:"core",title:"Follow-Up Center",route:"/attract/follow-up",status:"live",tables:["attract_follow_ups"],notes:"Every commitment on one list."},{key:"opportunities",pillar:"core",title:"Opportunities",route:"/attract/opportunities",status:"live",tables:["attract_recommendations","attract_agent_scores"],notes:"Ranked, explainable recommendations."},{key:"settings",pillar:"core",title:"Settings",route:"/attract/settings",status:"live",tables:["attract_settings"],notes:"Goals, audience, cadence."},{key:"resource_kits",pillar:"toolkit",title:"Value kits",route:"/attract/toolkit/kits",status:"live",tables:["attract_resource_kits","attract_resource_kit_items","attract_kit_shares","attract_kit_events"],notes:"Build, share, track engagement."},{key:"kit_templates",pillar:"toolkit",title:"Starter kit library",route:"/attract/toolkit/kits/templates",status:"live",tables:["attract_kit_templates"],notes:"10 starter kits, clone to own."},{key:"scripts",pillar:"toolkit",title:"Recruiting scripts",route:"/attract/toolkit/scripts",status:"live",tables:[],notes:"Funnel-staged scripts with copy-to-clipboard."},{key:"objections",pillar:"toolkit",title:"Objection answers",route:"/attract/toolkit/objections",status:"live",tables:[],notes:"Opener + full answer per objection, searchable."},{key:"event_engine",pillar:"toolkit",title:"Events",route:"/attract/toolkit/events",status:"live",tables:["attract_events","attract_event_attendees","attract_event_invitations","attract_event_notes"],notes:"Builder, public registration, invitations, QR check-in."},{key:"checkin",pillar:"toolkit",title:"Mobile check-in",route:"/attract/events/:eventId/checkin",status:"live",tables:["attract_event_attendees"],notes:"QR + manual check-in."},{key:"content_studio",pillar:"toolkit",title:"Content Studio",route:"/attract/toolkit/content",status:"live",tables:["attract_content_drafts"],notes:"AI-assisted recruiting content drafts."},{key:"value_library",pillar:"toolkit",title:"Resource library",route:"/attract/toolkit/resources",status:"partial",tables:["attract_resources"],notes:"Read + save works; no categorization/search yet."}],wAt={live:"Live",partial:"Partial",placeholder:"Placeholder",integration_required:"Integration required"},i0r={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 o0r(){const[s,t]=_.useState(""),[n,r]=_.useState("all"),a=_.useMemo(()=>_At.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=_.useMemo(()=>{const l={live:0,partial:0,placeholder:0,integration_required:0};return _At.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(B,{variant:"ghost",size:"sm",className:"rounded-full -ml-2",asChild:!0,children:e.jsxs(ir,{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(ve,{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:wAt[l]})]},l))}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsx(xe,{value:s,onChange:l=>t(l.target.value),placeholder:"Filter tools",className:"max-w-sm rounded-full"}),n!=="all"&&e.jsx(B,{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(ve,{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(Oe,{variant:"outline",className:"rounded-full capitalize",children:l.pillar}),e.jsx(Oe,{variant:"outline",className:`rounded-full ${i0r[l.status]}`,children:wAt[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(B,{variant:"outline",size:"sm",className:"rounded-full",asChild:!0,children:e.jsxs(ir,{to:l.route,children:[l.route," ",e.jsx(wr,{className:"h-3 w-3 ml-1.5"})]})}):e.jsx("span",{className:"text-[12px] text-muted-foreground",children:l.route??"No route"})]})},`${l.pillar}-${l.key}`))})]})}function l0r(){var c;const{shareToken:s}=Li(),[t,n]=_.useState("loading"),[r,a]=_.useState(null),[i,l]=_.useState(!1);_.useEffect(()=>{(async()=>{if(!s){n("not_found");return}const{data:d,error:u}=await q.rpc("public_get_attract_kit",{_token:s});if(u){n("error");return}if(!d||d.status!=="ok"){n((d==null?void 0:d.status)??"not_found");return}a(d),n("ok"),q.rpc("public_log_attract_kit_event",{_token:s,_event_type:"page_view",_item_id:null,_metadata:{}})})()},[s]);const o=(d,u,h)=>{s&&q.rpc("public_log_attract_kit_event",{_token:s,_event_type:d,_item_id:u??null,_metadata:h??{}})};return t==="loading"?e.jsx("div",{className:"min-h-screen bg-[#05070f] grid place-items-center text-slate-300",children:"Loading…"}):t!=="ok"?e.jsx("div",{className:"min-h-screen bg-[#05070f] grid place-items-center px-6",children:e.jsxs(ve,{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(un,{className:"h-3.5 w-3.5"})," A LevelUp Attract kit"]}),e.jsx(Yos,{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(ve,{className:"mt-6 p-6 bg-white/5 border-white/10 text-slate-100 rounded-2xl",children:i?e.jsx(c0r,{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(B,{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 c0r({token:s,onSent:t,onEvent:n}){const[r,a]=_.useState(""),[i,l]=_.useState(""),[o,c]=_.useState(""),[d,u]=_.useState(!1),h=async()=>{if(o.trim().length<2)return se.error("Please add a short message");u(!0);const{data:m,error:p}=await q.rpc("public_submit_attract_kit_question",{_token:s,_name:r,_email:i,_message:o});if(u(!1),p||!(m!=null&&m.ok))return se.error("Could not send — please try again");se.success("Sent — thank you!"),t()};return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-[14px] font-semibold",children:"Send a private message"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-2",children:[e.jsx(xe,{placeholder:"Your name (optional)",value:r,onChange:m=>a(m.target.value),className:"bg-white/5 border-white/10 text-white placeholder:text-slate-500"}),e.jsx(xe,{placeholder:"Your email (optional)",value:i,onChange:m=>l(m.target.value),className:"bg-white/5 border-white/10 text-white placeholder:text-slate-500"})]}),e.jsx(Ms,{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(B,{variant:"outline",onClick:()=>{n("meeting_requested"),se.success("Request sent")},children:"Request a conversation"}),e.jsx(B,{onClick:h,disabled:d,className:"bg-gradient-to-r from-violet-600 to-indigo-600 ml-auto",children:d?"Sending…":"Send question"})]})]})}function d0r(){const{slug:s}=Li(),[t]=Yl(),n=t.get("inv")||null,[r,a]=_.useState("loading"),[i,l]=_.useState(null),[o,c]=_.useState({name:"",email:"",phone:"",answers:{}}),[d,u]=_.useState(!1),[h,m]=_.useState(null);_.useEffect(()=>{s&&(async()=>{const{data:y,error:v}=await q.rpc("public_get_attract_event",{_slug:s});if(v||!y||y.error){a((y==null?void 0:y.error)||"not_found");return}l(y),a("ok"),n&&q.rpc("public_track_attract_invitation_view",{_token:n})})()},[s,n]);const p=async()=>{u(!0);const{data:y,error:v}=await q.rpc("public_register_attract_event",{_slug:s,_name:o.name,_email:o.email,_phone:o.phone||null,_answers:o.answers||{},_invitation_token:n});if(u(!1),v){alert("Something went wrong. Please try again.");return}const g=y;if(g!=null&&g.error){alert(g.error==="invalid_email"?"That email looks off.":g.error==="full"?"This event is full.":"Could not register.");return}m(g)},f=()=>{if(!i)return;const y=new Blob([jos(i)],{type:"text/calendar"}),v=document.createElement("a");v.href=URL.createObjectURL(y),v.download=`${s}.ics`,v.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 y=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:y}),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(ve,{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(ga,{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(Kr,{className:"h-5 w-5 text-violet-600 mt-0.5"}):e.jsx(Xa,{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(In,{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((y,v)=>e.jsxs("li",{className:"flex gap-2 text-[14px] text-slate-800",children:[e.jsx(ea,{className:"h-4 w-4 text-emerald-600 shrink-0 mt-0.5"})," ",y]},v))})]}),(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((y,v)=>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:y.time}),e.jsx("span",{className:"text-slate-800",children:y.item})]},v))})]})]}),h?e.jsxs(ve,{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(ea,{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(B,{variant:"outline",className:"rounded-full mt-5",onClick:f,children:[e.jsx(li,{className:"h-4 w-4 mr-2"})," Add to calendar"]})]}):e.jsxs(ve,{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(un,{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(J,{children:"Full name"}),e.jsx(xe,{value:o.name,onChange:y=>c({...o,name:y.target.value})})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Email"}),e.jsx(xe,{type:"email",value:o.email,onChange:y=>c({...o,email:y.target.value})})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Phone (optional)"}),e.jsx(xe,{value:o.phone,onChange:y=>c({...o,phone:y.target.value})})]})]}),(i.registration_questions||[]).map(y=>e.jsxs("div",{children:[e.jsx(J,{children:y.label}),y.type==="long"?e.jsx(Ms,{rows:3,value:o.answers[y.key]||"",onChange:v=>c({...o,answers:{...o.answers,[y.key]:v.target.value}})}):e.jsx(xe,{value:o.answers[y.key]||"",onChange:v=>c({...o,answers:{...o.answers,[y.key]:v.target.value}})})]},y.key))]}),e.jsx(B,{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 u0r(){const{token:s}=Li(),[t]=Yl(),n=t.get("a"),[r,a]=_.useState("loading"),[i,l]=_.useState("");return _.useEffect(()=>{if(!s||!n){a("error");return}(async()=>{const{data:o}=await q.rpc("public_check_in_attendee",{_check_in_token:s,_attendee_token:n}),c=o;c!=null&&c.ok?(l(c.name||""),a(c.already?"already":"ok")):a("error")})()},[s,n]),e.jsx("div",{className:"min-h-screen grid place-items-center bg-slate-50 px-4",children:e.jsxs(ve,{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(ea,{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 _ue=s=>s.toLocaleString("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0});function h0r(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 Zos({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]=_.useState(!1),[d,u]=_.useState(null),[h,m]=_.useState(!1),[p,f]=_.useState({first_name:"",last_name:"",email:"",phone:"",brokerage:"",message:""}),[y,v]=_.useState({first_name:"",email:""}),g=s.calculator||{},[b,j]=_.useState(15e4),S=_.useMemo(()=>{const D=Number(g.cap??16e3),O=Number(g.split??80)/100,V=Number(g.transaction_fee??250),G=Number(g.current_split??70)/100,$=Number(g.current_monthly_fees??150),H=Math.min(b*(1-O),D),Y=b-H-V*12,Z=b*G-$*12;return{here:Math.max(Y,0),current:Math.max(Z,0),diff:Math.max(Y-Z,0),capped:H>=D}},[b,g]),C=async(D,O,V)=>{if(r||!t){u(D);return}m(!0);try{await t({first_name:O.first_name||"",last_name:O.last_name||"",email:O.email||"",phone:O.phone||"",brokerage:O.brokerage||"",message:O.message||"",source:D,metadata:V}),u(D)}catch(G){ia({title:"We couldn't send that",description:(G==null?void 0:G.message)||"Please try again in a moment.",variant:"destructive"})}finally{m(!1)}},E=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(La,{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:[E(),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(ga,{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,O)=>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})]},O))})}),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:h0r(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(om,{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,O)=>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(ea,{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})]},O))})]})}),l.calculator!==!1&&g.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:g.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(J,{className:"text-white/70",children:"Your annual GCI"}),e.jsx("span",{className:"text-2xl font-bold",style:{color:i},children:_ue(b)})]}),e.jsx("input",{type:"range",min:25e3,max:1e6,step:5e3,value:b,onChange:D=>j(Number(D.target.value)),onMouseUp:()=>n==null?void 0:n("calculator_run","calculator",{gci:b}),onTouchEnd:()=>n==null?void 0:n("calculator_run","calculator",{gci:b}),className:"w-full accent-white"})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"rounded-2xl border border-white/10 p-5",children:[e.jsx("div",{className:"text-xs uppercase tracking-wider text-white/45",children:"Where you are now"}),e.jsx("div",{className:"mt-2 text-2xl font-semibold text-white/80",children:_ue(S.current)})]}),e.jsxs("div",{className:"rounded-2xl border p-5",style:{borderColor:i},children:[e.jsx("div",{className:"text-xs uppercase tracking-wider",style:{color:i},children:"With me"}),e.jsx("div",{className:"mt-2 text-2xl font-bold",children:_ue(S.here)}),S.capped&&e.jsx("div",{className:"mt-1 text-xs text-white/50",children:"You would cap this year."})]}),e.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/[0.04] p-5",children:[e.jsx("div",{className:"text-xs uppercase tracking-wider text-white/45",children:"Difference"}),e.jsxs("div",{className:"mt-2 text-2xl font-bold",style:{color:i},children:["+",_ue(S.diff)]})]})]}),e.jsx("p",{className:"mt-6 text-xs leading-relaxed text-white/35",children:"Estimates only, based on the assumptions above. Your actual numbers depend on your production and agreements."}),e.jsx("div",{className:"mt-8",children:E("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,O)=>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:O+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})]})]},O))})]})}),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,O)=>e.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/[0.03] p-6",children:[e.jsx(pS,{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(Da,{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})]})]})]},O))})]})}),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(G9,{type:"single",collapsible:!0,className:"w-full",children:(s.faqs||[]).map((D,O)=>e.jsxs(gL,{value:`faq-${O}`,className:"border-white/10",children:[e.jsx(yL,{className:"text-left text-base font-medium text-white hover:no-underline",children:D.q}),e.jsx(vL,{className:"text-sm leading-relaxed text-white/65",children:D.a})]},O))})]})}),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(li,{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(),C("lead_magnet",{first_name:y.first_name,email:y.email,message:`Requested: ${s.lead_magnet.title}`})},children:[e.jsx(xe,{required:!0,placeholder:"First name",value:y.first_name,onChange:D=>v(O=>({...O,first_name:D.target.value})),className:"h-12 border-white/15 bg-white/5 text-white placeholder:text-white/35"}),e.jsx(xe,{required:!0,type:"email",placeholder:"Email",value:y.email,onChange:D=>v(O=>({...O,email:D.target.value})),className:"h-12 border-white/15 bg-white/5 text-white placeholder:text-white/35"}),e.jsx(B,{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(ea,{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(ga,{className:"h-4 w-4"})," Pick a time"]})]}):e.jsxs("form",{onSubmit:D=>{D.preventDefault(),C("attraction_page",p,{gci:b})},className:"space-y-4 rounded-3xl border border-white/10 bg-white/[0.05] p-8 backdrop-blur",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-sm text-white/70",children:"First name *"}),e.jsx(xe,{required:!0,value:p.first_name,onChange:D=>f(O=>({...O,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(J,{className:"text-sm text-white/70",children:"Last name"}),e.jsx(xe,{value:p.last_name,onChange:D=>f(O=>({...O,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(J,{className:"text-sm text-white/70",children:"Email *"}),e.jsx(xe,{required:!0,type:"email",value:p.email,onChange:D=>f(O=>({...O,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(J,{className:"text-sm text-white/70",children:"Phone"}),e.jsx(xe,{value:p.phone,onChange:D=>f(O=>({...O,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(J,{className:"text-sm text-white/70",children:"Current brokerage"}),e.jsx(xe,{value:p.brokerage,onChange:D=>f(O=>({...O,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(J,{className:"text-sm text-white/70",children:"What would you want to know?"}),e.jsx(Ms,{rows:3,value:p.message,onChange:D=>f(O=>({...O,message:D.target.value})),className:"resize-none border-white/15 bg-white/5 text-white"})]}),e.jsx(B,{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(Rm,{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(_a,{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(La,{className:"h-4 w-4"})]})})]})}const wue=q;function m0r(){const{slug:s}=Li(),[t,n]=_.useState(null),[r,a]=_.useState("loading");_.useEffect(()=>{if(!s)return;let o=!1;return(async()=>{const{data:c,error:d}=await wue.rpc("public_get_attract_landing_page",{_slug:s});if(!o){if(d||!c||c.error){a("missing");return}n(c),a("ready"),wue.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&&wue.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 wue.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(Zos,{cfg:t,onSubmitLead:l,onTrack:i})]})}const jAt={media_mode:"photo",show_property_snapshot:!0,show_discover:!0,show_testimonial:!0};function Xos(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 tV=[{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."}],Qos=[{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"}],p0r=["New Lead","Attempting Contact","Conversation Started","Nurturing","Appointment Requested","Appointment Scheduled","Listing Presentation","Listing Signed","Long Term Follow Up","Lost"],f0r=[{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"}],x0r=["Not enough showings","No offers","Marketing felt thin","Communication from my agent","Priced too high","Timing / market conditions","Something else"];function g0r(s){return s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)}function y0r(s){const t=g0r(s)||"property",n=Math.random().toString(36).slice(2,7);return`${t}-${n}`}function QP(s){return s==null?"—":`$${Number(s).toLocaleString("en-US",{maximumFractionDigits:0})}`}const NAt="https://dashboard.relevelup.com";function EZe(){if(typeof window>"u")return NAt;const s=window.location.hostname;return s==="localhost"||s==="127.0.0.1"||s==="dashboard.relevelup.com"?window.location.origin:NAt}function Jos(s){return`${EZe()}/revival/${s}`}const kAt=[Lr,bl,cg,ku,WO,un];function SAt(){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 AUe(s){const{data:t,error:n}=await q.functions.invoke("listing-revival-public",{body:s});if(n)throw n;if(t!=null&&t.error)throw new Error(String(t.error));return t}function v0r(){var I,D;const{slug:s=""}=Li(),[t]=Yl(),[n,r]=_.useState(null),[a,i]=_.useState(!0),[l,o]=_.useState(!1),[c,d]=_.useState(!1),u=_.useRef(null),[h,m]=_.useState({first_name:"",last_name:"",email:"",phone:"",still_selling:"",timeline:"",frustration:"",preferred_contact:"email",comments:"",wants_plan:!0,honeypot:""}),p=(O,V)=>m(G=>({...G,[O]:V}));_.useEffect(()=>{let O=!0;return(async()=>{try{const V=await AUe({action:"get",slug:s});if(!O)return;r(V),await AUe({action:"track",slug:s,event_type:t.get("src")==="qr"?"qr_scan":"page_view",session_id:SAt(),metadata:{referrer:document.referrer||null}})}catch{O&&r(null)}finally{O&&i(!1)}})(),()=>{O=!1}},[s,t]);const y=((n==null?void 0:n.campaign.content)??{}).landing,v=(n==null?void 0:n.campaign.landing_config)??{},g=(n==null?void 0:n.property)??((I=n==null?void 0:n.campaign)==null?void 0:I.property),b=n==null?void 0:n.agent,j=v.media_mode??"photo",S=Xos(v.video_url),C=v.media_image_url||(g==null?void 0:g.photo_url)||null;_.useEffect(()=>{g!=null&&g.property_address&&(document.title=`Your Free Property Review — ${g.property_address}`)},[g==null?void 0:g.property_address]);const E=_.useMemo(()=>(y==null?void 0:y.discover)??[],[y]),P=async O=>{if(O.preventDefault(),!(!h.first_name.trim()||!h.email.trim()&&!h.phone.trim())){o(!0);try{await AUe({action:"submit",slug:s,session_id:SAt(),...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(Ct,{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(Jr,{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:[g!=null&&g.photo_url?e.jsx("img",{src:g.photo_url,alt:g.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(Sr.div,{initial:{opacity:0,y:18},animate:{opacity:1,y:0},transition:{duration:.6},children:[e.jsx("div",{className:"revival-eyebrow text-accent",children:(y==null?void 0:y.eyebrow)??"A complimentary review"}),e.jsx("h1",{className:"revival-serif text-4xl sm:text-[54px] leading-[1.08] mt-3",children:(y==null?void 0:y.headline)??"Your Free Real Estate Relaunch Review"}),e.jsx("p",{className:"text-white/75 text-lg mt-4 max-w-2xl mx-auto",children:(y==null?void 0:y.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(Jr,{className:"h-4 w-4 text-accent"})," ",g==null?void 0:g.property_address]}),e.jsx("div",{className:"mt-8",children:e.jsx(B,{size:"lg",className:"bg-accent text-accent-foreground hover:bg-accent/90",onClick:()=>{var O;return(O=u.current)==null?void 0:O.scrollIntoView({behavior:"smooth"})},children:(y==null?void 0:y.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(Sr.div,{initial:{opacity:0,scale:.97},animate:{opacity:1,scale:1},className:"revival-tile p-10 text-center",children:[e.jsx(Er,{className:"h-12 w-12 mx-auto text-accent"}),e.jsx("h2",{className:"revival-serif text-3xl mt-4",children:"Your review is on its way"}),e.jsxs("p",{className:"text-muted-foreground mt-2 max-w-lg mx-auto",children:[(b==null?void 0:b.name)??"Your agent"," has been notified and will personally prepare your Property Revival Plan. Watch your inbox — you’ll hear back shortly."]}),e.jsx(B,{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 ${j==="none"?"":"lg:grid-cols-2"}`,children:[e.jsxs("div",{children:[e.jsxs("div",{className:"revival-eyebrow text-muted-foreground",children:["A word from ",(b==null?void 0:b.name)??"your agent"]}),e.jsx("p",{className:"mt-3 text-lg leading-relaxed",children:y==null?void 0:y.intro}),b?e.jsxs("div",{className:"mt-6 flex items-center gap-4",children:[b.avatar_url?e.jsx("img",{src:b.avatar_url,alt:b.name??"",className:"h-14 w-14 rounded-full object-cover"}):null,e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold",children:b.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[b.title??"Real Estate Specialist",b.brokerage_name?` · ${b.brokerage_name}`:""]})]})]}):null]}),j==="video"&&S?e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"revival-tile aspect-video overflow-hidden",children:S.kind==="file"?e.jsx("video",{src:S.src,controls:!0,playsInline:!0,className:"h-full w-full object-cover"}):e.jsx("iframe",{src:S.src,title:"Agent introduction",className:"h-full w-full",allowFullScreen:!0})}),v.video_caption?e.jsx("p",{className:"text-sm text-muted-foreground text-center",children:v.video_caption}):null]}):j==="photo"&&C?e.jsx("div",{className:"revival-tile aspect-video overflow-hidden",children:e.jsx("img",{src:C,alt:(g==null?void 0:g.property_address)??"Property",className:"h-full w-full object-cover"})}):j!=="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(om,{className:"h-12 w-12 mx-auto text-accent"}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-2",children:["A personal introduction from ",(b==null?void 0:b.name)??"your agent"]})]})}):null]}),g&&v.show_property_snapshot!==!1?e.jsxs("section",{className:"revival-tile overflow-hidden grid md:grid-cols-[1.1fr_1fr]",children:[g.photo_url?e.jsx("img",{src:g.photo_url,alt:g.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:g.property_address}),e.jsx("p",{className:"text-muted-foreground",children:[g.city,g.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:QP(g.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:QP(g.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:g.days_on_market??"—"})]})]})]})]}):null,E.length&&v.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:E.map((O,V)=>{const G=kAt[V%kAt.length];return e.jsxs(Sr.div,{initial:{opacity:0,y:18},whileInView:{opacity:1,y:0},viewport:{once:!0},transition:{delay:V*.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(G,{className:"h-5 w-5 text-accent-foreground"})}),e.jsx("div",{className:"font-semibold mt-3",children:O.title}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 leading-relaxed",children:O.body})]},V)})})]}):null,(D=y==null?void 0:y.testimonial)!=null&&D.quote&&v.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:["“",y.testimonial.quote,"”"]}),e.jsx("p",{className:"text-accent text-sm mt-4 uppercase tracking-[0.2em]",children:y.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:O=>p("honeypot",O.target.value)}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"First name *"}),e.jsx(xe,{required:!0,value:h.first_name,onChange:O=>p("first_name",O.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Last name"}),e.jsx(xe,{value:h.last_name,onChange:O=>p("last_name",O.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Email"}),e.jsx(xe,{type:"email",value:h.email,onChange:O=>p("email",O.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Phone"}),e.jsx(xe,{value:h.phone,onChange:O=>p("phone",O.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Are you still interested in selling?"}),e.jsxs(is,{value:h.still_selling,onValueChange:O=>p("still_selling",O),children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Select one"})}),e.jsxs(as,{children:[e.jsx(He,{value:"yes",children:"Yes"}),e.jsx(He,{value:"maybe",children:"Maybe — depends on the plan"}),e.jsx(He,{value:"no",children:"Not right now"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Your timeline"}),e.jsxs(is,{value:h.timeline,onValueChange:O=>p("timeline",O),children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Select one"})}),e.jsx(as,{children:f0r.map(O=>e.jsx(He,{value:O.value,children:O.label},O.value))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Biggest frustration last time"}),e.jsxs(is,{value:h.frustration,onValueChange:O=>p("frustration",O),children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Select one"})}),e.jsx(as,{children:x0r.map(O=>e.jsx(He,{value:O,children:O},O))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Preferred contact method"}),e.jsxs(is,{value:h.preferred_contact,onValueChange:O=>p("preferred_contact",O),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"email",children:"Email"}),e.jsx(He,{value:"phone",children:"Phone call"}),e.jsx(He,{value:"text",children:"Text message"})]})]})]}),e.jsxs("div",{className:"sm:col-span-2 space-y-1.5",children:[e.jsx(J,{children:"Anything you'd like me to know?"}),e.jsx(Ms,{rows:3,value:h.comments,onChange:O=>p("comments",O.target.value)})]}),e.jsxs("label",{className:"sm:col-span-2 flex items-center gap-3 text-sm",children:[e.jsx($a,{checked:h.wants_plan,onCheckedChange:O=>p("wants_plan",!!O)}),"Send me the full Property Revival Plan for my home"]}),e.jsx("div",{className:"sm:col-span-2",children:e.jsx(B,{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(Ct,{className:"h-4 w-4 mr-2 animate-spin"})," Sending…"]}):(y==null?void 0:y.cta)??"Get my free review"})})]})]})]}),e.jsxs("footer",{className:"revival-dark py-10 text-center",children:[e.jsx("div",{className:"text-lg font-semibold",children:b==null?void 0:b.name}),e.jsx("div",{className:"text-accent text-sm",children:(b==null?void 0:b.title)??"Real Estate Specialist"}),e.jsx("div",{className:"text-white/60 text-sm mt-2",children:[b==null?void 0:b.phone,b==null?void 0:b.email].filter(Boolean).join(" · ")}),b!=null&&b.brokerage_name?e.jsx("div",{className:"text-white/40 text-xs mt-3",children:b.brokerage_name}):null]})]})}const Ew="#0f2540",W5="#c9a227";function ZZ({children:s,className:t,footer:n,page:r}){return e.jsxs("div",{"data-revival-plan-page":"",className:At("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 jue({eyebrow:s,title:t}){return e.jsxs("div",{children:[e.jsx("div",{className:"text-[10.5px] tracking-[0.28em] uppercase font-bold",style:{color:W5},children:s}),e.jsx("h2",{className:"revival-serif text-[30px] leading-tight mt-1",style:{color:Ew},children:t}),e.jsx("div",{className:"mt-3 h-[3px] w-14 rounded-full",style:{background:W5}})]})}function b0r({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:Ew},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?W5:"rgba(15,37,64,.10)"}},r))})]})}function TZe({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:At("space-y-8",a),children:[e.jsxs(ZZ,{children:[e.jsxs("div",{className:"relative h-[52%] overflow-hidden",style:{background:Ew},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), ${Ew})`}}),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:W5},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:QP(t.original_price)},{k:"Final price",v:QP(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:Ew},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:Ew},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(AN,{value:r,size:64,level:"M",fgColor:Ew})}),e.jsx("div",{className:"text-[8.5px] tracking-[0.18em] uppercase text-[#0f2540]/45 mt-1",children:"View online"})]}):null]})]})]}),o.length?e.jsx(ZZ,{footer:d,page:2,children:e.jsxs("div",{className:"px-12 pt-12 flex-1 flex flex-col",children:[e.jsx(jue,{eyebrow:"Section One",title:"Marketing scorecard"}),e.jsx("p",{className:"mt-4 text-[14px] leading-7 text-[#28313f]",children:"A review of how the previous listing performed across the six areas that most influence a sale. Each area is rated on a 1–5 scale, where 5 means the listing was doing everything today’s buyers respond to."}),e.jsx("div",{className:"mt-6 grid grid-cols-2 gap-3",children:o.map(([p,f])=>e.jsx(b0r,{label:p,value:Number(f)},p))}),(u=s==null?void 0:s.buyers_experienced)!=null&&u.length?e.jsxs("div",{className:"mt-8",children:[e.jsx("div",{className:"text-[10.5px] tracking-[0.28em] uppercase font-bold",style:{color:W5},children:"What buyers experienced"}),e.jsx("ul",{className:"mt-3 space-y-2",children:s.buyers_experienced.slice(0,5).map((p,f)=>e.jsxs("li",{className:"flex gap-3 text-[13.5px] leading-6 text-[#28313f]",children:[e.jsx("span",{className:"mt-[7px] h-[6px] w-[6px] shrink-0 rounded-full",style:{background:W5}}),p]},f))})]}):null]})}):null,(h=s==null?void 0:s.differently)!=null&&h.length?e.jsx(ZZ,{footer:d,page:3,children:e.jsxs("div",{className:"px-12 pt-12 flex-1 flex flex-col",children:[e.jsx(jue,{eyebrow:"Section Two",title:"What we would do differently"}),e.jsxs("p",{className:"mt-4 text-[14px] leading-7 text-[#28313f]",children:["Every point below is part of the plan for ",i," — not a general list."]}),e.jsx("div",{className:"mt-6 grid grid-cols-2 gap-3",children:s.differently.slice(0,10).map((p,f)=>e.jsxs("div",{className:"rounded-xl border border-[#0f2540]/12 px-4 py-3 flex gap-3",children:[e.jsx("span",{className:"h-[22px] w-[22px] shrink-0 rounded-full grid place-items-center text-[11px] font-bold text-white",style:{background:Ew},children:f+1}),e.jsx("span",{className:"text-[13px] leading-6 text-[#28313f]",children:p})]},f))})]})}):null,c.length?e.jsx(ZZ,{footer:d,page:4,children:e.jsxs("div",{className:"px-12 pt-12 flex-1 flex flex-col",children:[e.jsx(jue,{eyebrow:"Section Three",title:"Your relaunch strategy"}),e.jsxs("p",{className:"mt-4 text-[14px] leading-7 text-[#28313f]",children:["A week-by-week plan for bringing ",i," back to market with momentum."]}),e.jsx("div",{className:"mt-6 space-y-3",children:c.slice(0,5).map((p,f)=>e.jsxs("div",{className:"rounded-xl border border-[#0f2540]/12 p-5 flex gap-5",children:[e.jsx("div",{className:"h-11 w-11 shrink-0 rounded-xl grid place-items-center text-white font-bold",style:{background:Ew},children:f+1}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] tracking-[0.26em] uppercase font-bold",style:{color:W5},children:p.week}),e.jsx("div",{className:"text-[16px] font-semibold mt-0.5",style:{color:Ew},children:p.title}),e.jsx("p",{className:"text-[13px] leading-6 text-[#28313f] mt-1",children:p.body})]})]},f))})]})}):null,e.jsx(ZZ,{footer:d,page:5,children:e.jsxs("div",{className:"px-12 pt-12 flex-1 flex flex-col",children:[e.jsx(jue,{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:W5},children:"Questions to ask any agent"}),e.jsx("ol",{className:"mt-3 space-y-2",children:s.questions.slice(0,6).map((p,f)=>e.jsxs("li",{className:"flex gap-3 text-[13.5px] leading-6 text-[#28313f]",children:[e.jsxs("span",{className:"text-[12px] font-bold tabular-nums",style:{color:Ew},children:[f+1,"."]}),p]},f))})]}):null,e.jsxs("div",{className:"mt-8 rounded-2xl p-8 text-white",style:{background:Ew},children:[e.jsx("div",{className:"text-[10.5px] tracking-[0.28em] uppercase font-bold",style:{color:W5},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:W5},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(AN,{value:r,size:60,level:"M",fgColor:Ew})}):null]})]})]})})]})}const XZ=[15,37,64],EUe=[201,162,39],CAt=[31,41,55],Nue=[107,114,128];async function _0r(s,t=8){return yK.toDataURL(s,{margin:0,scale:t,color:{dark:"#0f2540",light:"#ffffff"}})}function w0r(s){return[s.title,s.brokerage_name,s.phone,s.email,s.website_url].filter(Boolean).map(String)}function Qit(s){return s.replace(/[^a-z0-9]+/gi,"-").replace(/^-+|-+$/g,"").toLowerCase().slice(0,60)}async function j0r(s){const{campaign:t,agent:n,url:r,photoDataUrl:a}=s,i=t.property,l=new Mo({unit:"pt",format:[648,432],orientation:"landscape"}),o=648,c=432;if(l.setFillColor(...XZ),l.rect(0,0,o,c,"F"),a)try{l.addImage(a,"JPEG",0,0,o,c*.62)}catch{}l.setFillColor(...XZ),l.rect(0,c*.6,o,c*.4,"F"),l.setFillColor(...EUe),l.rect(0,c*.6-4,o,4,"F"),l.setTextColor(...EUe),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(...XZ),l.rect(0,0,10,c,"F");const d=44;l.setTextColor(...XZ),l.setFont("times","normal"),l.setFontSize(19),l.text(n.name??"",d,54),l.setFont("helvetica","normal"),l.setFontSize(9),l.setTextColor(...Nue),l.text(w0r(n).join(" · "),d,72,{maxWidth:o/2+40}),l.setDrawColor(...EUe),l.setLineWidth(1),l.line(d,88,o/2+60,88),l.setTextColor(...CAt),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 _0r(r);l.addImage(h,"PNG",d,c-150,108,108),l.setFont("helvetica","bold"),l.setFontSize(10),l.setTextColor(...XZ),l.text("Scan for your free review",d+122,c-112),l.setFont("helvetica","normal"),l.setFontSize(8.5),l.setTextColor(...Nue),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(...Nue),l.text("MAILING ADDRESS",m+10,126),l.setFontSize(11),l.setTextColor(...CAt),[(i==null?void 0:i.seller_name)??"Current Resident",(i==null?void 0:i.mailing_address)??(i==null?void 0:i.property_address)??"",[(i==null?void 0:i.mailing_city)??(i==null?void 0:i.city),(i==null?void 0:i.mailing_state)??(i==null?void 0:i.state),(i==null?void 0:i.mailing_zip)??(i==null?void 0:i.zip)].filter(Boolean).join(", ")].filter(Boolean).forEach((f,y)=>l.text(String(f),m+14,162+y*18,{maxWidth:o-m-72})),l.setDrawColor(210,214,220),l.rect(o-118,40,74,62),l.setFontSize(7.5),l.setTextColor(...Nue),l.text("POSTAGE",o-96,74),l.save(`revival-postcard-${Qit((i==null?void 0:i.property_address)??t.name)}.pdf`)}async function els(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 N0r(s,t){const{toPng:n}=await za(async()=>{const{toPng:d}=await Promise.resolve().then(()=>X$t);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 els(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 Mo({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-${Qit(t)}.pdf`)}async function tls(s,t){const{toPng:n}=await za(async()=>{const{toPng:d}=await Promise.resolve().then(()=>X$t);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 els(h);m&&d.setAttribute("src",m)}));const l=new Mo({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-${Qit(t)}.pdf`)}function AAt(){var m,p,f;const{slug:s=""}=Li(),[t,n]=_.useState(null),[r,a]=_.useState(!0),[i,l]=_.useState(!1),o=_.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 tls(o.current,(c==null?void 0:c.property_address)??"plan")}finally{l(!1)}}};if(_.useEffect(()=>{let y=!0;return(async()=>{try{const{data:v,error:g}=await q.functions.invoke("listing-revival-public",{body:{action:"get",slug:s}});if(g)throw g;if(!y)return;n(v),await q.functions.invoke("listing-revival-public",{body:{action:"track",slug:s,event_type:"plan_view"}})}catch{y&&n(null)}finally{y&&a(!1)}})(),()=>{y=!1}},[s]),_.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(Ct,{className:"h-6 w-6 animate-spin text-[#0f2540]"})});if(!t||!((f=(p=t.campaign)==null?void 0:p.content)!=null&&f.plan))return e.jsx("div",{className:"min-h-screen grid place-items-center bg-[#f7f5f1] px-6 text-center",children:e.jsxs("div",{children:[e.jsx(Jr,{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(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(li,{className:"h-4 w-4"}),"Download PDF"]})]}),e.jsx("div",{ref:o,children:e.jsx(TZe,{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 k0r(){const{user:s}=hs();return at({queryKey:["revival-campaigns",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("listing_revival_campaigns").select("*, property:listing_revival_properties(*)").order("created_at",{ascending:!1});if(n)throw n;return t??[]}})}function S0r(s){return at({queryKey:["revival-campaign",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("listing_revival_campaigns").select("*, property:listing_revival_properties(*)").eq("id",s).maybeSingle();if(n)throw n;return t??null}})}function C0r(){const{user:s}=hs();return at({queryKey:["revival-properties",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("listing_revival_properties").select("*").order("created_at",{ascending:!1});if(n)throw n;return t??[]}})}function sls(){const{user:s}=hs();return at({queryKey:["revival-leads",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("listing_revival_leads").select("*").order("created_at",{ascending:!1});if(n)throw n;return t??[]}})}function A0r(){const{user:s}=hs();return at({queryKey:["revival-tasks",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("listing_revival_tasks").select("*").order("due_date",{ascending:!0});if(n)throw n;return t??[]}})}function nls(){const{user:s}=hs();return at({queryKey:["revival-events",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("listing_revival_events").select("*").order("created_at",{ascending:!1}).limit(1e3);if(n)throw n;return t??[]}})}function Jit(){const s=Bt(),t=()=>{["revival-campaigns","revival-campaign","revival-properties","revival-leads","revival-tasks","revival-events"].forEach(c=>s.invalidateQueries({queryKey:[c]}))},n=mt({mutationFn:async c=>{const{data:d,error:u}=await q.functions.invoke("listing-revival-generate",{body:c});if(u)throw u;if(d!=null&&d.error)throw new Error(String(d.error));return d},onSuccess:t,onError:c=>se.error(c.message)}),r=mt({mutationFn:async c=>{const{error:d}=await q.from("listing_revival_campaigns").update(c.patch).eq("id",c.id);if(d)throw d},onSuccess:()=>{t(),se.success("Saved")},onError:c=>se.error(c.message)}),a=mt({mutationFn:async c=>{const{error:d}=await q.from("listing_revival_properties").update(c.patch).eq("id",c.id);if(d)throw d},onSuccess:()=>{t(),se.success("Property updated")},onError:c=>se.error(c.message)}),i=mt({mutationFn:async c=>{const{error:d}=await q.from("listing_revival_campaigns").delete().eq("id",c);if(d)throw d},onSuccess:()=>{t(),se.success("Campaign deleted")},onError:c=>se.error(c.message)}),l=mt({mutationFn:async c=>{const{error:d}=await q.from("listing_revival_campaigns").update({status:c.archived?"archived":"active",published:!c.archived}).eq("id",c.id);if(d)throw d;return c},onSuccess:c=>{t(),se.success(c.archived?"Campaign archived":"Campaign restored")},onError:c=>se.error(c.message)}),o=mt({mutationFn:async c=>{const{error:d}=await q.from("listing_revival_tasks").update({completed_at:c.done?new Date().toISOString():null}).eq("id",c.id);if(d)throw d},onSuccess:t,onError:c=>se.error(c.message)});return{generate:n,saveCampaign:r,saveProperty:a,deleteCampaign:i,archiveCampaign:l,toggleTask:o,invalidate:t}}const E0r=[{id:"dashboard",label:"Dashboard",icon:hm},{id:"campaigns",label:"Campaigns",icon:un},{id:"properties",label:"Properties",icon:Jr},{id:"letters",label:"Letters",icon:ln},{id:"landing",label:"Landing Pages",icon:sl},{id:"plans",label:"Revival Plans",icon:Fr},{id:"followup",label:"Follow Up",icon:qf},{id:"analytics",label:"Analytics",icon:bl},{id:"templates",label:"Templates",icon:pj},{id:"settings",label:"Settings",icon:fS}];function a_({label:s,value:t,icon:n,delay:r=0,hint:a}){return e.jsxs(Sr.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 T0r(){const s=Fn(),[t,n]=_.useState("dashboard"),[r,a]=_.useState(""),[i,l]=_.useState(!1),[o,c]=_.useState(null),d=dnr(),u=k0r(),h=C0r(),m=sls(),p=A0r(),f=nls(),{toggleTask:y,archiveCampaign:v,deleteCampaign:g}=Jit(),b=u.data??[],j=m.data??[],S=f.data??[],C=p.data??[],E=_.useMemo(()=>{const $=H=>S.filter(Y=>Y.event_type===H).length;return{properties:(h.data??[]).length,campaigns:b.length,letters:b.filter(H=>{var Y;return(Y=H.content)==null?void 0:Y.letter}).length,qr:$("qr_scan"),visits:$("page_view"),planViews:$("plan_view"),leads:j.length,appointments:$("appointment"),won:j.filter(H=>H.stage==="listing_signed").length,hot:j.filter(H=>H.temperature==="hot").length}},[b,j,S,h.data]),P=_.useMemo(()=>{const $=[];for(let H=13;H>=0;H--){const Y=new Date(Date.now()-H*864e5),Z=Y.toISOString().slice(0,10);$.push({day:Hs(Y,"MMM d"),visits:S.filter(ne=>ne.event_type==="page_view"&&ne.created_at.startsWith(Z)).length,scans:S.filter(ne=>ne.event_type==="qr_scan"&&ne.created_at.startsWith(Z)).length,leads:j.filter(ne=>ne.created_at.startsWith(Z)).length})}return $},[S,j]),M=$=>$.status==="archived",I=b.filter($=>{var Y,Z;if(i?!M($):M($))return!1;const H=r.trim().toLowerCase();return H?`${$.name} ${((Y=$.property)==null?void 0:Y.property_address)??""} ${((Z=$.property)==null?void 0:Z.seller_name)??""}`.toLowerCase().includes(H):!0}),D=b.filter(M).length,O=$=>s(`/apps/listing-revival/campaigns/${$}`),V=$=>{navigator.clipboard.writeText(Jos($)),se.success("Landing page link copied")},G=$=>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(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{value:r,onChange:H=>a(H.target.value),placeholder:"Search campaigns…",className:"pl-9"})]}),e.jsxs(B,{variant:i?"default":"outline",size:"sm",onClick:()=>l(H=>!H),children:[e.jsx(by,{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.":$}):e.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:I.map((H,Y)=>{var te,ae,le,be;const Z=tV.find(me=>me.id===H.style),ne=j.filter(me=>me.campaign_id===H.id).length,ce=S.filter(me=>me.campaign_id===H.id&&me.event_type==="page_view").length,ie=M(H);return e.jsxs(Sr.div,{initial:{opacity:0,y:14},animate:{opacity:1,y:0},transition:{delay:Math.min(Y*.04,.3),duration:.4},className:At("revival-tile overflow-hidden",ie&&"opacity-80"),children:[e.jsxs("div",{className:"h-28 bg-muted relative",children:[(te=H.property)!=null&&te.photo_url?e.jsx("img",{src:H.property.photo_url,alt:H.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(Jr,{className:"h-7 w-7 text-accent"})}),e.jsx(Oe,{className:"absolute top-3 left-3 bg-background/90 text-foreground border-0",children:(Z==null?void 0:Z.name)??H.style}),ie?e.jsx(Oe,{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:((ae=H.property)==null?void 0:ae.property_address)??H.name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:((le=H.property)==null?void 0:le.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(sl,{className:"h-3.5 w-3.5"}),ce]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(In,{className:"h-3.5 w-3.5"}),ne]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Jr,{className:"h-3.5 w-3.5"}),((be=H.property)==null?void 0:be.days_on_market)??"—"," DOM"]})]}),e.jsxs("div",{className:"mt-4 flex gap-2",children:[e.jsxs(B,{size:"sm",className:"flex-1",onClick:()=>O(H.id),children:["Open ",e.jsx(La,{className:"h-3.5 w-3.5 ml-1"})]}),e.jsx(B,{size:"sm",variant:"outline",onClick:()=>V(H.slug),children:e.jsx(Ia,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"sm",variant:"outline",asChild:!0,children:e.jsx("a",{href:`/revival/${H.slug}`,target:"_blank",rel:"noreferrer",children:e.jsx(wr,{className:"h-3.5 w-3.5"})})}),e.jsxs(tu,{children:[e.jsx(su,{asChild:!0,children:e.jsx(B,{size:"sm",variant:"outline",children:e.jsx(Xx,{className:"h-3.5 w-3.5"})})}),e.jsxs(Od,{align:"end",children:[e.jsx(ca,{onClick:()=>v.mutate({id:H.id,archived:!ie}),children:ie?e.jsxs(e.Fragment,{children:[e.jsx(VM,{className:"h-4 w-4 mr-2"})," Restore campaign"]}):e.jsxs(e.Fragment,{children:[e.jsx(by,{className:"h-4 w-4 mr-2"})," Archive campaign"]})}),e.jsx(M0,{}),e.jsxs(ca,{className:"text-destructive focus:text-destructive",onClick:()=>{var me;return c({id:H.id,name:((me=H.property)==null?void 0:me.property_address)??H.name})},children:[e.jsx(Sn,{className:"h-4 w-4 mr-2"})," Delete permanently"]})]})]})]})]})]},H.id)})}),e.jsx(Kl,{open:!!o,onOpenChange:H=>!H&&c(null),children:e.jsxs(Ol,{children:[e.jsxs(zl,{children:[e.jsx(Ul,{children:"Delete this campaign?"}),e.jsxs(ql,{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($l,{children:"Cancel"}),e.jsx(Ml,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",onClick:()=>{o&&g.mutate(o.id),c(null)},children:"Delete permanently"})]})]})})]});return!d.isLoading&&!d.hasAccess?e.jsx(zs,{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(un,{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(zs,{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(Sr.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(B,{size:"lg",className:"bg-accent text-accent-foreground hover:bg-accent/90",onClick:()=>s("/apps/listing-revival/new"),children:[e.jsx(rn,{className:"h-4 w-4 mr-1"})," New Campaign"]}),e.jsx(B,{size:"lg",variant:"outline",className:"bg-transparent text-white border-white/25 hover:bg-white/10",onClick:()=>n("campaigns"),children:"View campaigns"})]})]})]}),e.jsxs(Yr,{value:t,onValueChange:n,className:"mt-6",children:[e.jsx(Zr,{className:"flex w-full overflow-x-auto no-scrollbar justify-start bg-transparent p-0 gap-2 h-auto",children:E0r.map($=>e.jsxs(Ht,{value:$.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($.icon,{className:"h-3.5 w-3.5 mr-1.5"}),$.label]},$.id))}),e.jsxs(Gt,{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(a_,{label:"Properties",value:E.properties,icon:Jr,delay:0}),e.jsx(a_,{label:"Campaigns",value:E.campaigns,icon:un,delay:.04}),e.jsx(a_,{label:"Letters",value:E.letters,icon:ln,delay:.08}),e.jsx(a_,{label:"QR Scans",value:E.qr,icon:Hf,delay:.12}),e.jsx(a_,{label:"Page Visits",value:E.visits,icon:sl,delay:.16}),e.jsx(a_,{label:"Plans Viewed",value:E.planViews,icon:Fr,delay:.2}),e.jsx(a_,{label:"Seller Leads",value:E.leads,icon:In,delay:.24}),e.jsx(a_,{label:"Appointments",value:E.appointments,icon:bv,delay:.28}),e.jsx(a_,{label:"Listings Won",value:E.won,icon:wl,delay:.32}),e.jsx(a_,{label:"Hot Leads",value:E.hot,icon:gu,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(jb,{width:"100%",height:"100%",children:e.jsxs(Jst,{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(kE,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",vertical:!1}),e.jsx(Mv,{dataKey:"day",tick:{fontSize:11},stroke:"hsl(var(--muted-foreground))"}),e.jsx(Pv,{allowDecimals:!1,tick:{fontSize:11},stroke:"hsl(var(--muted-foreground))",width:28}),e.jsx(Mf,{contentStyle:{borderRadius:12,border:"1px solid hsl(var(--border))"}}),e.jsx(U_,{type:"monotone",dataKey:"visits",stroke:"hsl(var(--primary))",fill:"url(#revVisits)",strokeWidth:2}),e.jsx(U_,{type:"monotone",dataKey:"leads",stroke:"hsl(var(--accent))",fill:"url(#revLeads)",strokeWidth:2})]})})})]}),e.jsxs("div",{className:"revival-tile p-5",children:[e.jsx("div",{className:"revival-eyebrow text-muted-foreground",children:"Recent activity"}),e.jsxs("div",{className:"mt-3 space-y-3 max-h-64 overflow-auto pr-1",children:[S.slice(0,20).map($=>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:$.event_type.replace(/_/g," ")}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Hs(new Date($.created_at),"MMM d, h:mm a")})]})]},$.id)),S.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No activity yet. Mail your first letter to start tracking."}):null]})]})]}),e.jsxs("div",{className:"revival-tile p-5",children:[e.jsx("div",{className:"revival-eyebrow text-muted-foreground",children:"Upcoming follow ups"}),e.jsxs("div",{className:"mt-3 space-y-2",children:[C.filter($=>!$.completed_at).slice(0,6).map($=>e.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-border px-4 py-3",children:[e.jsx($a,{checked:!!$.completed_at,onCheckedChange:H=>y.mutate({id:$.id,done:!!H})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium truncate",children:$.title}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:$.detail})]}),e.jsx(Oe,{variant:"outline",children:Hs(new Date(`${$.due_date}T12:00:00`),"MMM d")})]},$.id)),C.filter($=>!$.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(Gt,{value:"campaigns",className:"mt-6",children:G("No campaigns yet — click New Campaign to build your first one.")}),e.jsx(Gt,{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($=>e.jsxs("tr",{className:"border-t border-border",children:[e.jsx("td",{className:"px-4 py-3 font-medium",children:$.property_address}),e.jsx("td",{className:"px-4 py-3",children:$.seller_name??"—"}),e.jsx("td",{className:"px-4 py-3",children:QP($.original_price)}),e.jsx("td",{className:"px-4 py-3",children:QP($.final_price)}),e.jsx("td",{className:"px-4 py-3",children:$.days_on_market??"—"}),e.jsx("td",{className:"px-4 py-3",children:$.expiration_date??"—"})]},$.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(Gt,{value:"letters",className:"mt-6",children:G("Letters appear here once you create a campaign.")}),e.jsx(Gt,{value:"landing",className:"mt-6",children:G("Landing pages appear here once you create a campaign.")}),e.jsx(Gt,{value:"plans",className:"mt-6",children:G("Property Revival Plans appear here once you create a campaign.")}),e.jsxs(Gt,{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:[C.filter($=>!$.completed_at).map($=>e.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-border px-4 py-3",children:[e.jsx($a,{checked:!1,onCheckedChange:()=>y.mutate({id:$.id,done:!0})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium truncate",children:$.title}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:$.detail})]}),e.jsx(Oe,{variant:"outline",className:"capitalize",children:$.channel})]},$.id)),C.filter($=>!$.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:[j.map($=>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:[$.first_name,$.last_name].filter(Boolean).join(" ")||"Homeowner"}),e.jsxs(Oe,{className:At("capitalize border-0",$.temperature==="hot"&&"bg-red-500/15 text-red-600",$.temperature==="warm"&&"bg-amber-500/15 text-amber-700",$.temperature==="nurture"&&"bg-sky-500/15 text-sky-700",$.temperature==="low"&&"bg-muted text-muted-foreground"),children:[$.temperature," · ",$.lead_score]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-1",children:[$.timeline?`Timeline: ${$.timeline} · `:"",$.next_action]})]},$.id)),j.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:p0r.map($=>{const H=$.toLowerCase().replace(/ /g,"_"),Y=j.filter(Z=>Z.stage===H).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:$}),e.jsx("div",{className:"text-2xl font-bold tabular-nums",children:Y})]},$)})})]})]}),e.jsxs(Gt,{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(a_,{label:"Lead capture %",value:`${E.visits?Math.round(E.leads/E.visits*100):0}%`,icon:In}),e.jsx(a_,{label:"Scan → visit",value:`${E.qr?Math.round(E.visits/E.qr*100):0}%`,icon:Hf}),e.jsx(a_,{label:"Appointments",value:E.appointments,icon:bv}),e.jsx(a_,{label:"Conversion %",value:`${E.leads?Math.round(E.won/E.leads*100):0}%`,icon:wl})]}),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(jb,{width:"100%",height:"100%",children:e.jsxs(BW,{data:b.slice(0,10).map($=>{var H;return{name:(((H=$.property)==null?void 0:H.property_address)??$.name).slice(0,18),visits:S.filter(Y=>Y.campaign_id===$.id&&Y.event_type==="page_view").length,leads:j.filter(Y=>Y.campaign_id===$.id).length}}),children:[e.jsx(kE,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",vertical:!1}),e.jsx(Mv,{dataKey:"name",tick:{fontSize:10},stroke:"hsl(var(--muted-foreground))"}),e.jsx(Pv,{allowDecimals:!1,tick:{fontSize:11},stroke:"hsl(var(--muted-foreground))",width:28}),e.jsx(Mf,{contentStyle:{borderRadius:12,border:"1px solid hsl(var(--border))"}}),e.jsx(H_,{dataKey:"visits",fill:"hsl(var(--primary))",radius:[6,6,0,0]}),e.jsx(H_,{dataKey:"leads",fill:"hsl(var(--accent))",radius:[6,6,0,0]})]})})})]})]}),e.jsxs(Gt,{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:tV.map($=>e.jsxs("div",{className:"revival-tile p-5",children:[e.jsx("div",{className:At("h-1.5 w-full rounded-full bg-gradient-to-r mb-4",$.accent)}),e.jsx("div",{className:"font-semibold",children:$.name}),e.jsx("div",{className:"text-xs uppercase tracking-wider text-accent-foreground/70",children:$.tagline}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:$.description}),e.jsxs("p",{className:"revival-serif text-[15px] mt-3 leading-snug",children:["“",$.previewHeadline,"”"]})]},$.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:Qos.map($=>e.jsxs("div",{className:"revival-tile p-4",children:[e.jsx("div",{className:"font-semibold",children:$.name}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:$.note})]},$.id))})]})]}),e.jsx(Gt,{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(B,{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 EAt=["Import the property","Choose the campaign style","Generate everything"];function M0r(){var b;const s=Fn(),{user:t}=hs(),{generate:n,invalidate:r}=Jit(),[a,i]=_.useState(0),[l,o]=_.useState(!1),[c,d]=_.useState(tV[0].id),[u,h]=_.useState("professional"),[m,p]=_.useState({property_address:"",city:"",state:"",zip:"",seller_name:"",seller_email:"",seller_phone:"",mailing_address:"",mailing_city:"",mailing_state:"",mailing_zip:"",original_price:"",final_price:"",days_on_market:"",expiration_date:"",mls_link:"",photo_url:"",agent_notes:""}),f=(j,S)=>p(C=>({...C,[j]:S})),y=a===0?m.property_address.trim().length>3:!0,v=async()=>{if(t){o(!0);try{const{data:j,error:S}=await q.from("listing_revival_properties").insert({owner_user_id:t.id,property_address:m.property_address.trim(),city:m.city||null,state:m.state||null,zip:m.zip||null,seller_name:m.seller_name||null,seller_email:m.seller_email||null,seller_phone:m.seller_phone||null,mailing_address:m.mailing_address||null,mailing_city:m.mailing_city||null,mailing_state:m.mailing_state||null,mailing_zip:m.mailing_zip||null,original_price:m.original_price?Number(m.original_price):null,final_price:m.final_price?Number(m.final_price):null,days_on_market:m.days_on_market?Number(m.days_on_market):null,expiration_date:m.expiration_date||null,mls_link:m.mls_link||null,photo_url:m.photo_url||null,agent_notes:m.agent_notes||null}).select().single();if(S)throw S;const{data:C,error:E}=await q.from("listing_revival_campaigns").insert({owner_user_id:t.id,property_id:j.id,name:m.property_address.trim(),slug:y0r(m.property_address),style:c,letter_template:u,status:"generating",published:!0}).select().single();if(E)throw E;await n.mutateAsync({campaignId:C.id}),r(),se.success("Campaign built — everything is ready."),s(`/apps/listing-revival/campaigns/${C.id}`)}catch(j){se.error(j instanceof Error?j.message:"Could not create the campaign")}finally{o(!1)}}},g=(j,S,C={})=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:S}),e.jsx(xe,{value:m[j],onChange:E=>f(j,E.target.value),...C})]});return e.jsx(zs,{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(B,{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:EAt.map((j,S)=>e.jsxs("div",{className:"flex items-center gap-3 flex-1",children:[e.jsx("div",{className:At("h-9 w-9 rounded-full grid place-items-center text-sm font-bold shrink-0 transition-colors",Sf("photo_url",j??""),label:"Property photo",prefix:"revival-property"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Agent notes"}),e.jsx(Ms,{rows:6,value:m.agent_notes,onChange:j=>f("agent_notes",j.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:tV.map(j=>e.jsxs("button",{type:"button",onClick:()=>d(j.id),className:At("text-left rounded-2xl border p-5 transition-all",c===j.id?"border-accent ring-2 ring-accent/40 bg-accent/[0.04]":"border-border hover:border-accent/50"),children:[e.jsx("div",{className:At("h-1.5 w-full rounded-full bg-gradient-to-r mb-4",j.accent)}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"font-semibold",children:j.name}),c===j.id?e.jsx(ea,{className:"h-4 w-4 text-accent"}):null]}),e.jsx("div",{className:"text-[11px] uppercase tracking-wider text-muted-foreground",children:j.tagline}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:j.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:j.previewHeadline}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:j.previewBody})]})]},j.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:Qos.map(j=>e.jsxs("button",{type:"button",onClick:()=>h(j.id),className:At("rounded-xl border p-4 text-left transition-all",u===j.id?"border-accent ring-2 ring-accent/40":"border-border hover:border-accent/50"),children:[e.jsx("div",{className:"font-medium",children:j.name}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:j.note})]},j.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(Qx,{className:"h-7 w-7 text-accent"})}),e.jsx("h2",{className:"revival-serif text-2xl mt-4",children:"Build the full campaign"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:"One click creates the personalized letter with its QR code, the private landing page, the Property Revival Plan, a 7-email sequence, 5 texts, your call and video scripts, and a 30-day follow-up task plan."}),e.jsxs("div",{className:"mt-6 rounded-2xl border border-border p-5 text-left space-y-2 text-sm",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Property"}),e.jsx("span",{className:"font-medium",children:m.property_address||"—"})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Seller"}),e.jsx("span",{className:"font-medium",children:m.seller_name||"Homeowner"})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Style"}),e.jsx("span",{className:"font-medium",children:(b=tV.find(j=>j.id===c))==null?void 0:b.name})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Letter"}),e.jsx("span",{className:"font-medium capitalize",children:u})]})]}),e.jsx(B,{size:"lg",className:"mt-6 w-full bg-accent text-accent-foreground hover:bg-accent/90",disabled:l,onClick:v,children:l?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"})," Building your campaign…"]}):e.jsxs(e.Fragment,{children:[e.jsx(un,{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(B,{variant:"outline",disabled:a===0,onClick:()=>i(j=>j-1),children:"Back"}),e.jsxs(B,{disabled:!y,onClick:()=>i(j=>j+1),children:["Continue ",e.jsx(La,{className:"h-4 w-4 ml-1"})]})]}):e.jsx("div",{className:"flex justify-start mt-6",children:e.jsx(B,{variant:"outline",disabled:l,onClick:()=>i(1),children:"Back"})})]})})}const TAt={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 P0r(s){return s<=900?1:s<=1150?.94:s<=1400?.88:s<=1700?.82:s<=2100?.76:.7}function MAt({campaign:s,letter:t,agent:n,url:r,className:a}){var h,m;const i=TAt[s.letter_template]??TAt.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=P0r(c),u={fontSize:`${(i.size*d).toFixed(2)}px`,lineHeight:1.6};return e.jsxs("div",{id:"revival-letter-sheet",className:At("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:At("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:At("mt-1 h-[3px] w-16 rounded-full",i.rule)}),e.jsxs("div",{className:At("mt-4 text-[#28313f] flex flex-col",i.body),style:{...u,gap:`${(.7*d).toFixed(2)}em`},children:[o.map((p,f)=>e.jsx("p",{children:p},f)),t.closing?e.jsx("p",{className:"font-semibold text-[#0f2540]",children:t.closing}):null]}),e.jsxs("div",{className:"mt-auto pt-4",children:[e.jsx("div",{style:{fontSize:`${(13*d).toFixed(1)}px`},className:"text-[#28313f]",children:"Sincerely,"}),e.jsx("div",{className:"revival-serif italic text-[#0f2540] leading-tight mt-1",style:{fontSize:`${(26*d).toFixed(1)}px`},children:t.signature||n.name})]})]}),e.jsxs("div",{className:"min-h-0 space-y-4 pt-2",children:[l!=null&&l.photo_url?e.jsxs("div",{className:"overflow-hidden rounded-lg",children:[e.jsx("img",{src:l.photo_url,alt:l.property_address??"Property",className:"h-[190px] w-full object-cover",loading:"lazy"}),e.jsxs("div",{className:"bg-[#0f2540] text-white px-4 py-3 text-[11.5px] grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-white/60",children:"Property"}),e.jsx("div",{className:"font-semibold leading-tight",children:l.property_address})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-white/60",children:"Days on market"}),e.jsx("div",{className:"font-semibold",children:l.days_on_market??"—"})]})]})]}):null,e.jsxs("div",{className:"rounded-xl border border-[#c9a227]/45 p-4 text-center",children:[e.jsx("div",{className:"inline-block bg-[#c9a227] text-[#0f2540] text-[10px] font-extrabold tracking-[0.18em] uppercase px-3 py-1 rounded",children:"Scan to unlock"}),e.jsxs("div",{className:"revival-serif text-[19px] text-[#0f2540] leading-tight mt-2",children:["Your Private",e.jsx("br",{}),"Property Review"]}),e.jsx("div",{className:"flex justify-center my-3",children:e.jsx(AN,{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 rls({letter:s,saving:t,onSave:n,onCancel:r}){const[a,i]=_.useState(s);_.useEffect(()=>{i(s)},[s]);const l=(u,h)=>i(m=>({...m,[u]:h})),o=(u,h)=>i(m=>({...m,paragraphs:m.paragraphs.map((p,f)=>f===u?h:p)})),c=()=>i(u=>({...u,paragraphs:[...u.paragraphs,""]})),d=u=>i(h=>({...h,paragraphs:h.paragraphs.filter((m,p)=>p!==u)}));return e.jsxs("div",{className:"rounded-xl border border-border bg-card p-5 space-y-5 max-w-3xl",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-semibold",children:"Edit letter"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Your edits are saved to this campaign and used in the PDF."})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{size:"sm",variant:"ghost",onClick:r,disabled:t,children:[e.jsx(Qn,{className:"h-3.5 w-3.5 mr-1.5"})," Cancel"]}),e.jsxs(B,{size:"sm",onClick:()=>n({...a,paragraphs:a.paragraphs.map(u=>u.trim()).filter(Boolean)}),disabled:t,children:[t?e.jsx(Ct,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(Ho,{className:"h-3.5 w-3.5 mr-1.5"}),"Save letter"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{className:"text-xs",children:"Greeting"}),e.jsx(xe,{value:a.greeting??"",onChange:u=>l("greeting",u.target.value),placeholder:"Dear Jane,"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(J,{className:"text-xs",children:"Body paragraphs"}),e.jsxs(B,{size:"sm",variant:"outline",onClick:c,children:[e.jsx(rn,{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(Ms,{value:u,onChange:m=>o(h,m.target.value),rows:4,className:"flex-1"}),e.jsx(B,{size:"icon",variant:"ghost",onClick:()=>d(h),"aria-label":"Remove paragraph",children:e.jsx(Sn,{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(J,{className:"text-xs",children:"Closing line"}),e.jsx(xe,{value:a.closing??"",onChange:u=>l("closing",u.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{className:"text-xs",children:"Signature"}),e.jsx(xe,{value:a.signature??"",onChange:u=>l("signature",u.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{className:"text-xs",children:"P.S."}),e.jsx(Ms,{value:a.ps??"",onChange:u=>l("ps",u.target.value),rows:2})]})]})}function PAt(s){if(!s)return null;const t=Math.floor(s/60),n=Math.round(s%60);return`${t}:${String(n).padStart(2,"0")}`}function L0r(s){return s.share_token?`https://video.relevelup.com/thumb/${s.share_token}`:s.thumbnail_url}function I0r({video:s}){const[t,n]=_.useState(!1),r=L0r(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(om,{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 D0r=(()=>{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 R0r({open:s,onOpenChange:t,onSelect:n,propertyAddress:r}){const{user:a}=hs(),[i,l]=_.useState("library"),[o,c]=_.useState([]),[d,u]=_.useState(!1),[h,m]=_.useState(""),[p,f]=_.useState("record"),[y,v]=_.useState(0),[g,b]=_.useState(0),j=TC(),S=_.useCallback(async()=>{if(a){u(!0);try{const{data:I,error:D}=await q.from("agent_videos").select("id, title, recipient_name, playback_url, thumbnail_url, share_token, duration_seconds, created_at").eq("owner_user_id",a.id).eq("is_deleted",!1).eq("status","ready").order("created_at",{ascending:!1}).limit(60);if(D)throw D;c(I??[])}catch{se.error("Could not load your video library")}finally{u(!1)}}},[a]);_.useEffect(()=>{s&&S()},[s,S]);const C=_.useMemo(()=>{const I=h.trim().toLowerCase();return I?o.filter(D=>`${D.title??""} ${D.recipient_name??""}`.toLowerCase().includes(I)):o},[o,h]),E=I=>{if(!I.playback_url){se.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||(f("record"),v(0),b(0)))},M=_.useCallback(async(I,D)=>{f("uploading");const O=r?`Listing Revival — ${r}`:"Listing Revival intro";try{const{videoId:V,libraryId:G}=await PL(O),{uploadUrl:$,apiKey:H}=await LL(V),Y=new XMLHttpRequest;Y.upload.onprogress=ae=>{ae.lengthComputable&&v(ae.loaded/ae.total*100)},await new Promise((ae,le)=>{Y.onload=()=>Y.status>=200&&Y.status<300?ae():le(new Error("Upload failed")),Y.onerror=()=>le(new Error("Upload failed")),Y.open("PUT",$),Y.setRequestHeader("AccessKey",H),Y.send(I)}),f("processing");const Z=`https://iframe.mediadelivery.net/embed/${G}/${V}`,ne=Date.now(),ce=9e4;let ie=0;for(;ie<4;){if(await new Promise(le=>setTimeout(le,3e3)),Date.now()-ne>ce){await j.mutateAsync({bunny_video_id:V,playback_url:`https://iframe.mediadelivery.net/play/${G}/${V}`,file_size_mb:I.size/(1024*1024),title:O,status:"processing",touch_type:"video"}),n(Z),se.success("Video saved — still encoding, it will appear shortly."),f("done"),setTimeout(()=>P(!1),1200);return}const ae=await TN(V);if(ie=ae.status,b(ae.encodeProgress||0),ie===5||ie===6)throw new Error("Video processing failed")}const te=await TN(V);await j.mutateAsync({bunny_video_id:V,playback_url:te.directPlayUrl||Z,thumbnail_url:te.thumbnailUrl,preview_url:te.previewUrl||null,duration_seconds:te.length||D,file_size_mb:(te.storageSize||I.size)/(1024*1024),title:O,status:"ready",touch_type:"video"}),n(te.directPlayUrl||Z),se.success("Video recorded and added to your landing page!"),f("done"),setTimeout(()=>P(!1),1200)}catch(V){console.error("Revival recording upload error:",V),se.error("Failed to process video. Please try again."),f("record")}},[j,n,r]);return e.jsx(Ls,{open:s,onOpenChange:P,children:e.jsxs(Ps,{className:"max-w-4xl max-h-[92vh] overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Add a video to your landing page"}),e.jsx(_r,{children:"Pick one you already recorded, or record a brand new one right here without leaving Listing Revival."})]}),e.jsxs(Yr,{value:i,onValueChange:l,children:[e.jsxs(Zr,{className:"grid w-full grid-cols-2",children:[e.jsxs(Ht,{value:"library",children:[e.jsx(dm,{className:"h-3.5 w-3.5 mr-1.5"})," My library"]}),e.jsxs(Ht,{value:"record",children:[e.jsx(Kr,{className:"h-3.5 w-3.5 mr-1.5"})," Record new"]})]}),e.jsxs(Gt,{value:"library",className:"mt-4 space-y-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{value:h,onChange:I=>m(I.target.value),placeholder:"Search your videos…",className:"pl-9"})]}),d?e.jsx("div",{className:"grid gap-3 sm:grid-cols-3",children:Array.from({length:6}).map((I,D)=>e.jsx(cn,{className:"aspect-video rounded-xl"},D))}):C.length===0?e.jsxs("div",{className:"rounded-xl border border-dashed border-border p-10 text-center",children:[e.jsx(om,{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(B,{size:"sm",variant:"outline",className:"mt-3",onClick:()=>l("record"),children:[e.jsx(Kr,{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:C.map(I=>e.jsxs("button",{type:"button",onClick:()=>E(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(I0r,{video:I}),PAt(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:PAt(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(Gt,{value:"record",className:"mt-4",children:[p==="record"?e.jsxs("div",{className:"space-y-3",children:[D0r?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(B,{size:"sm",variant:"outline",onClick:()=>window.open(window.location.href,"_blank","noopener"),children:[e.jsx(wr,{className:"h-3.5 w-3.5 mr-1.5"})," Open in new tab"]})]}):null,e.jsx($E,{maxDurationSeconds:600,onRecordingComplete:M,onError:I=>se.error(I)})]}):null,p==="uploading"?e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12",children:[e.jsx(Ct,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Uploading your video…"}),e.jsx(Fi,{value:y,className:"w-64"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Math.round(y),"%"]})]}):null,p==="processing"?e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12",children:[e.jsx(Ct,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Processing your video…"}),e.jsx(Fi,{value:g,className:"w-64"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Math.round(g),"%"]})]}):null,p==="done"?e.jsxs("div",{className:"flex flex-col items-center gap-3 py-12",children:[e.jsx(_l,{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 F0r=[{id:"photo",label:"Property photo",hint:"Shows the listing photo. Best if you have no video.",icon:hc},{id:"video",label:"Video",hint:"Record one here, pick from your library, or paste a link.",icon:Kr},{id:"none",label:"Nothing",hint:"Hide the media block entirely for a clean, text-only intro.",icon:Ax}];function O0r({campaignId:s,content:t,landingConfig:n,propertyPhotoUrl:r,saving:a,onSave:i}){var C;const[l,o]=_.useState(t.landing),[c,d]=_.useState({...jAt,...n}),[u,h]=_.useState(!1),[m,p]=_.useState(!1);_.useEffect(()=>{o(t.landing)},[t.landing]),_.useEffect(()=>{d({...jAt,...n})},[n]);const f=(E,P)=>{o(M=>({...M??{},[E]:P})),h(!0)},y=(E,P)=>{d(M=>({...M,[E]:P})),h(!0)},v=(l==null?void 0:l.discover)??[],g=E=>f("discover",E),b=_.useMemo(()=>Xos(c.video_url),[c.video_url]),j=c.media_image_url||r||null,S=()=>{i({content:{...t,landing:l},landing_config:c}),h(!1)};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"revival-eyebrow text-muted-foreground",children:"Landing page editor"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Everything here updates your public page instantly after saving."})]}),e.jsxs(B,{size:"sm",onClick:S,disabled:!u||a,children:[a?e.jsx(Ct,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(Ho,{className:"h-3.5 w-3.5 mr-1.5"}),"Save changes"]})]}),e.jsxs("div",{className:"revival-tile p-6 space-y-4",children:[e.jsx("div",{className:"font-semibold",children:"Headline & intro"}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Eyebrow"}),e.jsx(xe,{value:(l==null?void 0:l.eyebrow)??"",onChange:E=>f("eyebrow",E.target.value),placeholder:"A complimentary review"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Button text"}),e.jsx(xe,{value:(l==null?void 0:l.cta)??"",onChange:E=>f("cta",E.target.value),placeholder:"Get my free review"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Headline"}),e.jsx(xe,{value:(l==null?void 0:l.headline)??"",onChange:E=>f("headline",E.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Subheadline"}),e.jsx(Ms,{rows:2,value:(l==null?void 0:l.subheadline)??"",onChange:E=>f("subheadline",E.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Personal intro paragraph"}),e.jsx(Ms,{rows:5,value:(l==null?void 0:l.intro)??"",onChange:E=>f("intro",E.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:F0r.map(E=>{const P=(c.media_mode??"photo")===E.id;return e.jsxs("button",{type:"button",onClick:()=>y("media_mode",E.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(E.icon,{className:`h-5 w-5 ${P?"text-accent":"text-muted-foreground"}`}),e.jsx("div",{className:"font-medium mt-2",children:E.label}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:E.hint})]},E.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(J,{children:"Video link"}),e.jsx(xe,{value:c.video_url??"",onChange:E=>y("video_url",E.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(B,{type:"button",size:"sm",onClick:()=>p(!0),children:[e.jsx(Kr,{className:"h-3.5 w-3.5 mr-1.5"})," Record or choose a video"]}),c.video_url?e.jsxs(B,{type:"button",size:"sm",variant:"ghost",onClick:()=>y("video_url",""),children:[e.jsx(Sn,{className:"h-3.5 w-3.5 mr-1.5"})," Remove video"]}):null]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Caption under the video"}),e.jsx(xe,{value:c.video_caption??"",onChange:E=>y("video_caption",E.target.value),placeholder:"A personal introduction"})]}),e.jsx("div",{className:"aspect-video rounded-lg overflow-hidden bg-muted grid place-items-center",children:(b==null?void 0:b.kind)==="file"?e.jsx("video",{src:b.src,controls:!0,className:"h-full w-full object-cover"}):b?e.jsx("iframe",{src:b.src,title:"Video preview",className:"h-full w-full",allowFullScreen:!0}):e.jsxs("div",{className:"text-center text-sm text-muted-foreground",children:[e.jsx(om,{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(yz,{label:"Photo shown next to your intro",value:c.media_image_url??"",onChange:E=>y("media_image_url",E),prefix:"revival-landing",hint:"Leave empty to use the property photo from this campaign."}),j?e.jsx("img",{src:j,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(([E,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(fn,{checked:c[E]!==!1,onCheckedChange:I=>y(E,I)})]},E))]}),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(B,{size:"sm",variant:"outline",onClick:()=>g([...v,{title:"",body:""}]),children:[e.jsx(rn,{className:"h-3.5 w-3.5 mr-1.5"})," Add card"]})]}),v.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No highlight cards yet."}):null,v.map((E,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(Oe,{variant:"outline",children:P+1}),e.jsx(xe,{value:E.title,placeholder:"Card title",onChange:M=>g(v.map((I,D)=>D===P?{...I,title:M.target.value}:I))}),e.jsx(B,{size:"icon",variant:"ghost",onClick:()=>g(v.filter((M,I)=>I!==P)),children:e.jsx(Sn,{className:"h-4 w-4"})})]}),e.jsx(Ms,{rows:2,value:E.body,placeholder:"What this card explains",onChange:M=>g(v.map((I,D)=>D===P?{...I,body:M.target.value}:I))})]},P))]}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(B,{onClick:S,disabled:!u||a,children:[a?e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ho,{className:"h-4 w-4 mr-2"}),"Save changes"]})}),e.jsx(R0r,{open:m,onOpenChange:p,propertyAddress:((C=t==null?void 0:t.landing)==null?void 0:C.headline)??null,onSelect:E=>{y("video_url",E),y("media_mode","video")}})]})}const TUe={intro:"",scores:{},buyers_experienced:[],differently:[],strategy_weeks:[],questions:[],resources:[],invitation:""},z0r=s=>Math.min(5,Math.max(1,Math.round(s||1)));function B0r({plan:s,saving:t,onSave:n}){const[r,a]=_.useState({...TUe,...s});_.useEffect(()=>{a({...TUe,...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(J,{children:c}),e.jsxs(B,{type:"button",size:"sm",variant:"ghost",onClick:()=>i(o,[...r[o]??[],""]),children:[e.jsx(rn,{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(Ms,{value:u,rows:2,onChange:m=>{const p=[...r[o]??[]];p[h]=m.target.value,i(o,p)}}),e.jsx(B,{type:"button",size:"icon",variant:"ghost",onClick:()=>i(o,(r[o]??[]).filter((m,p)=>p!==h)),children:e.jsx(Sn,{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(B,{type:"button",size:"sm",variant:"ghost",onClick:()=>a({...TUe,...s}),children:[e.jsx(Tx,{className:"h-3.5 w-3.5 mr-1.5"})," Reset"]}),e.jsxs(B,{type:"button",size:"sm",disabled:t,className:"bg-accent text-accent-foreground hover:bg-accent/90",onClick:()=>n(r),children:[t?e.jsx(Ct,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(Ho,{className:"h-3.5 w-3.5 mr-1.5"}),"Save plan"]})]})]}),e.jsxs("section",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"plan-intro",children:"Introduction"}),e.jsx(Ms,{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(J,{children:"Marketing scorecard (1–5)"}),e.jsxs(B,{type:"button",size:"sm",variant:"ghost",onClick:()=>i("scores",{...r.scores,[`Category ${Object.keys(r.scores??{}).length+1}`]:3}),children:[e.jsx(rn,{className:"h-3.5 w-3.5 mr-1"})," Add category"]})]}),e.jsx("div",{className:"space-y-2",children:Object.entries(r.scores??{}).map(([o,c],d)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xe,{value:o,onChange:u=>{const h=Object.entries(r.scores??{});h[d]=[u.target.value,c],i("scores",Object.fromEntries(h))}}),e.jsx(xe,{type:"number",min:1,max:5,className:"w-20",value:c,onChange:u=>i("scores",{...r.scores,[o]:z0r(Number(u.target.value))})}),e.jsx(B,{type:"button",size:"icon",variant:"ghost",onClick:()=>{const u={...r.scores??{}};delete u[o],i("scores",u)},children:e.jsx(Sn,{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(J,{children:"Relaunch timeline"}),e.jsxs(B,{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(rn,{className:"h-3.5 w-3.5 mr-1"})," Add week"]})]}),e.jsx("div",{className:"space-y-3",children:(r.strategy_weeks??[]).map((o,c)=>e.jsxs("div",{className:"rounded-xl border p-3 space-y-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{className:"w-28",value:o.week,placeholder:"Week 1",onChange:d=>{const u=[...r.strategy_weeks??[]];u[c]={...o,week:d.target.value},i("strategy_weeks",u)}}),e.jsx(xe,{value:o.title,placeholder:"Title",onChange:d=>{const u=[...r.strategy_weeks??[]];u[c]={...o,title:d.target.value},i("strategy_weeks",u)}}),e.jsx(B,{type:"button",size:"icon",variant:"ghost",onClick:()=>i("strategy_weeks",(r.strategy_weeks??[]).filter((d,u)=>u!==c)),children:e.jsx(Sn,{className:"h-4 w-4 text-destructive"})})]}),e.jsx(Ms,{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(J,{children:"Resources"}),e.jsxs(B,{type:"button",size:"sm",variant:"ghost",onClick:()=>i("resources",[...r.resources??[],{title:"",body:""}]),children:[e.jsx(rn,{className:"h-3.5 w-3.5 mr-1"})," Add resource"]})]}),e.jsx("div",{className:"space-y-3",children:(r.resources??[]).map((o,c)=>e.jsxs("div",{className:"rounded-xl border p-3 space-y-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{value:o.title,placeholder:"Title",onChange:d=>{const u=[...r.resources??[]];u[c]={...o,title:d.target.value},i("resources",u)}}),e.jsx(B,{type:"button",size:"icon",variant:"ghost",onClick:()=>i("resources",(r.resources??[]).filter((d,u)=>u!==c)),children:e.jsx(Sn,{className:"h-4 w-4 text-destructive"})})]}),e.jsx(Ms,{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(J,{htmlFor:"plan-invitation",children:"Closing invitation"}),e.jsx(Ms,{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(B,{type:"button",disabled:t,className:"bg-accent text-accent-foreground hover:bg-accent/90",onClick:()=>n(r),children:[t?e.jsx(Ct,{className:"h-4 w-4 mr-1.5 animate-spin"}):e.jsx(Ho,{className:"h-4 w-4 mr-1.5"}),"Save plan"]})})]})}const U0r=[{key:"letter",label:"Letter",icon:ln,blurb:"Personalized print-ready letter mailed to the homeowner."},{key:"qr_scan",label:"QR Scan",icon:Hf,blurb:"Homeowner scans the unique code on the letter."},{key:"page_view",label:"Landing Page",icon:sl,blurb:"Private property review page opens on their phone."},{key:"form_submit",label:"Lead Form",icon:qf,blurb:"They request the plan — Agent OS is updated instantly."},{key:"plan_view",label:"Revival Plan",icon:Fr,blurb:"The full Property Revival Plan is delivered."},{key:"email",label:"Email Sequence",icon:Or,blurb:"Seven branded emails nurture the conversation."},{key:"sms",label:"Text Sequence",icon:Hi,blurb:"Five short texts keep momentum going."},{key:"appointment",label:"Appointment",icon:bv,blurb:"They book a complimentary strategy session."},{key:"listing",label:"Listing Signed",icon:Hh,blurb:"The relaunch begins."}];function q0r({counts:s,onStep:t,activeStep:n}){return e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:U0r.map((r,a)=>{const i=r.icon,l=s[r.key]??0,o=l>0;return e.jsxs(Sr.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:At("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:At("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 $0r({open:s,onOpenChange:t,campaignId:n,email:r,ctaUrl:a,seller:i}){const{user:l}=hs(),[o,c]=_.useState([]),[d,u]=_.useState(""),[h,m]=_.useState([]),[p,f]=_.useState(""),[y,v]=_.useState(""),[g,b]=_.useState("View your property review"),[j,S]=_.useState(""),[C,E]=_.useState(!1),[P,M]=_.useState(!1),I=_.useRef(null);_.useEffect(()=>{!s||!r||(c([]),u(""),m([]),f(r.subject||""),v(r.body||""),S(""))},[s,r==null?void 0:r.key,r==null?void 0:r.subject]),_.useEffect(()=>{if(!s||!r)return;const $=setTimeout(async()=>{E(!0);try{const{data:H,error:Y}=await q.functions.invoke("listing-revival-email",{body:{campaign_id:n,subject:p,body:y,preview_text:r.preview,cta_label:g,cta_url:a,preview_only:!0}});if(Y)throw Y;H!=null&&H.html&&S(H.html)}catch{}finally{E(!1)}},400);return()=>clearTimeout($)},[s,n,p,y,g,a,r==null?void 0:r.key]),_.useEffect(()=>{I.current&&clearTimeout(I.current);const $=d.trim();if(!l||$.length<2||/\S+@\S+\.\S+/.test($)){m([]);return}return I.current=setTimeout(async()=>{const H=`%${$}%`,Y=q,{data:Z}=await Y.from("innercircle_contacts").select("id, first_name, last_name, email").eq("owner_user_id",l.id).not("email","is",null).or(`first_name.ilike.${H},last_name.ilike.${H},email.ilike.${H}`).order("first_name",{ascending:!0}).limit(6);m(Z||[])},200),()=>{I.current&&clearTimeout(I.current)}},[d,l==null?void 0:l.id]);const D=$=>{$.email&&(c(H=>H.some(Y=>Y.email.toLowerCase()===$.email.toLowerCase())?H:[...H,$]),u(""),m([]))},O=()=>{const $=d.trim();if(!/\S+@\S+\.\S+/.test($)){se.error("Enter a valid email address");return}D({email:$})},V=_.useMemo(()=>!!r&&o.length>0&&p.trim().length>0&&!P,[r,o,p,P]),G=async()=>{var $,H;if(r){M(!0);try{const{data:Y,error:Z}=await q.functions.invoke("listing-revival-email",{body:{campaign_id:n,subject:p,body:y,preview_text:r.preview,cta_label:g,cta_url:a,email_key:r.key,recipients:o}});if(Z){let ne="";try{const ce=Z==null?void 0:Z.context;ce&&typeof ce.json=="function"&&(ne=(($=await ce.json())==null?void 0:$.error)||"")}catch{}throw new Error(ne||Z.message||"Could not send the email")}if(!(Y!=null&&Y.success))throw new Error(((H=Y==null?void 0:Y.errors)==null?void 0:H[0])||(Y==null?void 0:Y.error)||"Could not send the email");se.success(Y.failed?`Sent to ${Y.sent} · ${Y.failed} failed`:`Email sent to ${Y.sent} ${Y.sent===1?"contact":"contacts"}`),t(!1)}catch(Y){se.error((Y==null?void 0:Y.message)||"Could not send the email",{duration:1e4})}finally{M(!1)}}};return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"max-w-5xl max-h-[92vh] overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsxs(Ds,{className:"flex items-center gap-2",children:[e.jsx(ln,{className:"h-4 w-4"})," Send this email"]}),e.jsx(_r,{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(J,{children:"Recipients"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{value:d,onChange:$=>u($.target.value),placeholder:"Search contacts or type an email",onKeyDown:$=>{$.key==="Enter"&&($.preventDefault(),O())}}),e.jsx(B,{type:"button",variant:"outline",size:"icon",onClick:O,children:e.jsx(rn,{className:"h-4 w-4"})})]}),h.length>0&&e.jsx("div",{className:"rounded-xl border divide-y overflow-hidden",children:h.map($=>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:$.email,first_name:$.first_name,last_name:$.last_name,contact_id:$.id}),children:[e.jsx(Fo,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-sm",children:[$.first_name,$.last_name].filter(Boolean).join(" ")||$.email}),e.jsx("span",{className:"text-xs text-muted-foreground ml-auto",children:$.email})]},$.id))}),(i==null?void 0:i.email)&&!o.some($=>$.email.toLowerCase()===i.email.toLowerCase())&&e.jsxs(B,{type:"button",size:"sm",variant:"ghost",onClick:()=>D({email:i.email,first_name:(i.name||"").split(" ")[0]}),children:[e.jsx(rn,{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($=>e.jsxs(Oe,{variant:"secondary",className:"gap-1",children:[[$.first_name,$.last_name].filter(Boolean).join(" ")||$.email,e.jsx("button",{type:"button",onClick:()=>c(H=>H.filter(Y=>Y.email!==$.email)),children:e.jsx(Qn,{className:"h-3 w-3"})})]},$.email))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Subject"}),e.jsx(xe,{value:p,onChange:$=>f($.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Message"}),e.jsx(Ms,{rows:10,value:y,onChange:$=>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(J,{children:"Button label"}),e.jsx(xe,{value:g,onChange:$=>b($.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(J,{className:"flex items-center gap-2",children:["Live preview ",C&&e.jsx(Ct,{className:"h-3 w-3 animate-spin"})]}),e.jsx("div",{className:"rounded-xl border overflow-hidden bg-muted/30 h-[520px]",children:j?e.jsx("iframe",{title:"Email preview",srcDoc:j,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(yr,{children:[e.jsx(B,{variant:"ghost",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{onClick:G,disabled:!V,children:[P?e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Or,{className:"h-4 w-4 mr-2"}),"Send to ",o.length||0]})]})]})})}const LAt=s=>({property_address:(s==null?void 0:s.property_address)??"",city:(s==null?void 0:s.city)??"",state:(s==null?void 0:s.state)??"",zip:(s==null?void 0:s.zip)??"",seller_name:(s==null?void 0:s.seller_name)??"",seller_email:(s==null?void 0:s.seller_email)??"",seller_phone:(s==null?void 0:s.seller_phone)??"",mailing_address:(s==null?void 0:s.mailing_address)??"",mailing_city:(s==null?void 0:s.mailing_city)??"",mailing_state:(s==null?void 0:s.mailing_state)??"",mailing_zip:(s==null?void 0:s.mailing_zip)??"",original_price:(s==null?void 0:s.original_price)!=null?String(s.original_price):"",final_price:(s==null?void 0:s.final_price)!=null?String(s.final_price):"",days_on_market:(s==null?void 0:s.days_on_market)!=null?String(s.days_on_market):"",expiration_date:(s==null?void 0:s.expiration_date)??"",mls_link:(s==null?void 0:s.mls_link)??"",photo_url:(s==null?void 0:s.photo_url)??"",agent_notes:(s==null?void 0:s.agent_notes)??""});function V0r({open:s,onOpenChange:t,property:n,saving:r,onSave:a}){const[i,l]=_.useState(()=>LAt(n));_.useEffect(()=>{s&&l(LAt(n))},[s,n]);const o=(h,m)=>l(p=>({...p,[h]:m})),c=(h,m,p="text")=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs",children:m}),e.jsx(xe,{type:p,value:i[h],onChange:f=>o(h,f.target.value)})]}),d=h=>h.trim()===""?null:Number(h),u=()=>{a({property_address:i.property_address.trim()||null,city:i.city.trim()||null,state:i.state.trim()||null,zip:i.zip.trim()||null,seller_name:i.seller_name.trim()||null,seller_email:i.seller_email.trim()||null,seller_phone:i.seller_phone.trim()||null,mailing_address:i.mailing_address.trim()||null,mailing_city:i.mailing_city.trim()||null,mailing_state:i.mailing_state.trim()||null,mailing_zip:i.mailing_zip.trim()||null,original_price:d(i.original_price),final_price:d(i.final_price),days_on_market:d(i.days_on_market),expiration_date:i.expiration_date||null,mls_link:i.mls_link.trim()||null,photo_url:i.photo_url.trim()||null,agent_notes:i.agent_notes.trim()||null})};return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Edit property details"}),e.jsx(_r,{children:"Update the address, pricing, seller info or photo. Letters, landing pages and emails use this information."})]}),e.jsxs("div",{className:"space-y-5",children:[e.jsx(yz,{label:"Property photo",value:i.photo_url,onChange:h=>o("photo_url",h??""),prefix:"revival-property",hint:"Upload a new photo or paste an image URL. This shows on the campaign card and landing page."}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsx("div",{className:"sm:col-span-2",children:c("property_address","Property address")}),c("city","City"),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[c("state","State"),c("zip","Zip")]}),c("seller_name","Seller name"),c("seller_email","Seller email","email"),c("seller_phone","Seller phone"),c("expiration_date","Expiration date","date"),c("original_price","Original list price","number"),c("final_price","Final list price","number"),c("days_on_market","Days on market","number"),c("mls_link","MLS link"),e.jsx("div",{className:"sm:col-span-2",children:c("mailing_address","Mailing address (if different)")}),c("mailing_city","Mailing city"),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[c("mailing_state","Mailing state"),c("mailing_zip","Mailing zip")]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs",children:"Agent notes"}),e.jsx(Ms,{rows:4,value:i.agent_notes,onChange:h=>o("agent_notes",h.target.value),placeholder:"Why it didn't sell, condition, seller motivation…"})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{onClick:u,disabled:r,children:[r?e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):null,"Save changes"]})]})]})})}const H0r=[{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"]}],IAt="c0a11111-0000-4000-8000-000000000030";function G0r(){var te,ae,le,be,me,he,pe,Ce,Ae,Pe,ze,ke,Ze,Se,Fe,Ne,Ye,Ve,qe,Qe,Ue,Xe,nt,$e,Ge,ct,xt,qt,Vt;const{id:s}=Li(),t=Fn(),{user:n}=hs(),r=S0r(s),a=nls(),i=sls(),{generate:l,saveCampaign:o,saveProperty:c,deleteCampaign:d}=Jit(),[u,h]=_.useState(""),[m,p]=_.useState(null),[f,y]=_.useState(!1),[v,g]=_.useState(!1),[b,j]=_.useState(!1),[S,C]=_.useState(null),E=at({queryKey:["revival-drip-campaigns",n==null?void 0:n.id],enabled:!!n,queryFn:async()=>{const{data:Xt}=await q.from("drip_campaigns").select("id, name").eq("owner_user_id",n.id).order("name");return Xt??[]}}),P=mt({mutationFn:async()=>{if(!n)throw new Error("Not signed in");const[{data:Xt},{data:fs}]=await Promise.all([q.from("drip_campaigns").select("*").eq("id",IAt).maybeSingle(),q.from("drip_campaign_steps").select("*").eq("campaign_id",IAt).order("step_order")]);if(!Xt)throw new Error("Starter campaign not found");const{data:Ft,error:wt}=await q.from("drip_campaigns").insert({owner_user_id:n.id,name:Xt.name,description:Xt.description,category:Xt.category,icon:Xt.icon,cover_color:Xt.cover_color,goal:Xt.goal,is_active:!0,is_starter:!1}).select("id, name").single();if(wt)throw wt;if(fs!=null&&fs.length){const{error:Ts}=await q.from("drip_campaign_steps").insert(fs.map(vt=>({campaign_id:Ft.id,step_order:vt.step_order,channel:vt.channel,subject:vt.subject,body:vt.body,delay_type:vt.delay_type,delay_days:vt.delay_days,delay_hours:vt.delay_hours,send_window_start:vt.send_window_start,send_window_end:vt.send_window_end})));if(Ts)throw Ts}return Ft},onSuccess:async Xt=>{await E.refetch(),o.mutate({id:s,patch:{drip_campaign_id:Xt.id}}),se.success("Expired Listing Revival drip installed and assigned")},onError:Xt=>se.error(Xt.message)}),M=(E.data??[]).some(Xt=>{var fs;return(fs=Xt.name)==null?void 0:fs.startsWith("Expired Listing Revival")}),I=at({queryKey:["revival-agent-profile",n==null?void 0:n.id],enabled:!!n,queryFn:async()=>{const{data:Xt}=await q.from("profiles").select("name, email, phone, avatar_url, brokerage_name, website_url, title").eq("id",n.id).maybeSingle();return Xt}}),D=r.data,O=(D==null?void 0:D.content)??{},V=D?Jos(D.slug):"",G={name:(te=I.data)==null?void 0:te.name,title:(ae=I.data)==null?void 0:ae.title,phone:(le=I.data)==null?void 0:le.phone,email:(be=I.data)==null?void 0:be.email,website_url:(me=I.data)==null?void 0:me.website_url,avatar_url:(he=I.data)==null?void 0:he.avatar_url,brokerage_name:(pe=I.data)==null?void 0:pe.brokerage_name},$=_.useRef(null),H=async()=>{var fs,Ft;const Xt=(fs=$.current)==null?void 0:fs.firstElementChild;if(Xt){p("letter");try{await N0r(Xt,((Ft=D==null?void 0:D.property)==null?void 0:Ft.property_address)??(D==null?void 0:D.name)??"letter"),se.success("Letter PDF downloaded")}catch{se.error("Could not build the letter PDF")}finally{p(null)}}},Y=_.useRef(null),Z=async()=>{var fs;const Xt=Y.current;if(Xt){p("plan");try{await tls(Xt,((fs=D==null?void 0:D.property)==null?void 0:fs.property_address)??(D==null?void 0:D.name)??"plan"),se.success("Plan PDF downloaded")}catch{se.error("Could not build the plan PDF")}finally{p(null)}}},ne=_.useMemo(()=>{var Ft,wt;const Xt=(a.data??[]).filter(Ts=>Ts.campaign_id===s),fs={};return Xt.forEach(Ts=>{fs[Ts.event_type]=(fs[Ts.event_type]??0)+1}),fs.letter=O.letter?1:0,fs.email=((Ft=O.emails)==null?void 0:Ft.length)??0,fs.sms=((wt=O.sms)==null?void 0:wt.length)??0,fs.form_submit=(i.data??[]).filter(Ts=>Ts.campaign_id===s).length,fs},[a.data,i.data,s,O]);if(r.isLoading)return e.jsx(zs,{title:"Campaign",children:e.jsx("div",{className:"grid place-items-center py-24",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin"})})});if(!D)return e.jsx(zs,{title:"Campaign",children:e.jsx("div",{className:"py-24 text-center text-muted-foreground",children:"Campaign not found."})});const ce=tV.find(Xt=>Xt.id===D.style),ie=Xt=>l.mutate({campaignId:D.id,section:Xt,instruction:u||void 0});return e.jsxs(zs,{title:D.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(B,{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(Sr.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:(ce==null?void 0:ce.name)??D.style}),e.jsx("h1",{className:"revival-serif text-3xl mt-1",children:(Ce=D.property)==null?void 0:Ce.property_address}),e.jsxs("p",{className:"text-white/70 mt-1",children:[((Ae=D.property)==null?void 0:Ae.seller_name)??"Homeowner",(Pe=D.property)!=null&&Pe.city?` · ${D.property.city}, ${D.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:QP((ze=D.property)==null?void 0:ze.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:QP((ke=D.property)==null?void 0:ke.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:((Ze=D.property)==null?void 0:Ze.days_on_market)??"—"})]})]}),e.jsxs("div",{className:"mt-6 flex flex-wrap gap-2",children:[e.jsx(B,{size:"sm",className:"bg-accent text-accent-foreground hover:bg-accent/90",asChild:!0,children:e.jsxs("a",{href:`/revival/${D.slug}`,target:"_blank",rel:"noreferrer",children:[e.jsx(wr,{className:"h-3.5 w-3.5 mr-1.5"})," View landing page"]})}),e.jsxs(B,{size:"sm",variant:"outline",className:"bg-transparent text-white border-white/25 hover:bg-white/10",onClick:()=>j(!0),children:[e.jsx(Ya,{className:"h-3.5 w-3.5 mr-1.5"})," Edit property & photo"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"bg-transparent text-white border-white/25 hover:bg-white/10",onClick:()=>{navigator.clipboard.writeText(V),se.success("Link copied")},children:[e.jsx(Ia,{className:"h-3.5 w-3.5 mr-1.5"})," Copy link"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"bg-transparent text-white border-white/25 hover:bg-white/10",disabled:l.isPending,onClick:()=>ie(),children:[l.isPending?e.jsx(Ct,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(uo,{className:"h-3.5 w-3.5 mr-1.5"}),"Regenerate all"]})]})]}),e.jsxs("div",{className:"relative min-h-[220px]",children:[(Se=D.property)!=null&&Se.photo_url?e.jsx("img",{src:D.property.photo_url,alt:D.property.property_address??"",className:"absolute inset-0 h-full w-full object-cover"}):e.jsxs("button",{type:"button",onClick:()=>j(!0),className:"absolute inset-0 flex flex-col items-center justify-center gap-2 bg-white/5 text-white/70 text-sm hover:bg-white/10",children:[e.jsx(jy,{className:"h-6 w-6"}),"Add a property photo"]}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-r from-[hsl(var(--revival-navy))] via-transparent to-transparent pointer-events-none"})]})]})}),e.jsxs(Yr,{defaultValue:"journey",className:"mt-6",children:[e.jsx(Zr,{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(Xt=>e.jsx(Ht,{value:Xt,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:Xt},Xt))}),e.jsxs(Gt,{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(Jq,{className:"h-4 w-4"})," The homeowner's journey, tracked end to end."]}),e.jsx(q0r,{counts:ne})]}),e.jsxs(Gt,{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(B,{size:"sm",disabled:!O.letter||m==="letter",onClick:H,children:[m==="letter"?e.jsx(Ct,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(ZA,{className:"h-3.5 w-3.5 mr-1.5"}),"Download print-ready PDF"]}),e.jsxs(B,{size:"sm",variant:"outline",disabled:!O.letter,onClick:()=>g(Xt=>!Xt),children:[e.jsx(Ya,{className:"h-3.5 w-3.5 mr-1.5"})," ",v?"Close editor":"Edit letter"]}),e.jsxs(B,{size:"sm",variant:"outline",disabled:l.isPending,onClick:()=>ie("letter"),children:[e.jsx(un,{className:"h-3.5 w-3.5 mr-1.5"})," Rewrite letter"]}),e.jsx(xe,{value:u,onChange:Xt=>h(Xt.target.value),placeholder:"Optional instruction: e.g. shorter, warmer, mention the pool",className:"max-w-sm"})]}),v&&O.letter?e.jsx(rls,{letter:O.letter,saving:o.isPending,onCancel:()=>g(!1),onSave:Xt=>{o.mutate({id:s,patch:{content:{...O,letter:Xt}}},{onSuccess:()=>g(!1)})}}):null,O.letter?e.jsx(MAt,{campaign:D,letter:O.letter,url:V,agent:G}):e.jsx("p",{className:"text-muted-foreground",children:"No letter generated yet."})]}),e.jsx(Gt,{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(B,{size:"sm",className:"mt-3",disabled:!O.letter||m==="letter",onClick:H,children:[m==="letter"?e.jsx(Ct,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(hj,{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(B,{size:"sm",className:"mt-3",disabled:m==="postcard",onClick:async()=>{var Xt,fs,Ft,wt,Ts,vt,$s,As,jn,ar;p("postcard");try{await j0r({campaign:D,url:V,headline:(Xt=O.landing)==null?void 0:Xt.headline,subhead:(fs=O.landing)==null?void 0:fs.subheadline,message:(Ft=O.landing)==null?void 0:Ft.intro,photoDataUrl:((wt=D.property)==null?void 0:wt.photo_url)??null,agent:{name:(Ts=I.data)==null?void 0:Ts.name,title:(vt=I.data)==null?void 0:vt.title,phone:($s=I.data)==null?void 0:$s.phone,email:(As=I.data)==null?void 0:As.email,website_url:(jn=I.data)==null?void 0:jn.website_url,brokerage_name:(ar=I.data)==null?void 0:ar.brokerage_name}}),se.success("Postcard PDF downloaded")}catch{se.error("Could not build the postcard PDF")}finally{p(null)}},children:[m==="postcard"?e.jsx(Ct,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(hj,{className:"h-3.5 w-3.5 mr-1.5"}),"Download postcard PDF"]})]})]}),e.jsxs("div",{className:"rounded-xl bg-muted/50 p-4 text-sm text-muted-foreground",children:["Mailing address on file:"," ",e.jsxs("span",{className:"text-foreground font-medium",children:[((Fe=D.property)==null?void 0:Fe.mailing_address)??((Ne=D.property)==null?void 0:Ne.property_address)??"—",(Ye=D.property)!=null&&Ye.mailing_city?`, ${D.property.mailing_city} ${D.property.mailing_state??""} ${D.property.mailing_zip??""}`:""]})]})]})}),e.jsxs(Gt,{value:"landing",className:"mt-6 space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[e.jsxs(B,{size:"sm",variant:"outline",disabled:l.isPending,onClick:()=>ie("landing"),children:[e.jsx(un,{className:"h-3.5 w-3.5 mr-1.5"})," Rewrite landing copy"]}),e.jsx(B,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:`/revival/${D.slug}`,target:"_blank",rel:"noreferrer",children:[e.jsx(wr,{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(O0r,{campaignId:D.id,content:O,landingConfig:D.landing_config??{},propertyPhotoUrl:(Ve=D.property)==null?void 0:Ve.photo_url,saving:o.isPending,onSave:Xt=>o.mutate({id:D.id,patch:Xt})}),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(AN,{value:V,size:168,level:"M"})}),e.jsx("p",{className:"text-xs text-muted-foreground mt-3 max-w-[180px] break-all",children:V})]})]})]}),e.jsxs(Gt,{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(B,{size:"sm",variant:"outline",disabled:l.isPending,onClick:()=>ie("plan"),children:[e.jsx(un,{className:"h-3.5 w-3.5 mr-1.5"})," Rewrite plan"]}),e.jsxs(B,{size:"sm",variant:f?"secondary":"outline",onClick:()=>y(Xt=>!Xt),children:[e.jsx(Ya,{className:"h-3.5 w-3.5 mr-1.5"})," ",f?"Done editing":"Edit plan"]}),e.jsx(B,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:`/revival/${D.slug}/plan`,target:"_blank",rel:"noreferrer",children:[e.jsx(wr,{className:"h-3.5 w-3.5 mr-1.5"})," View live plan"]})}),e.jsxs(B,{size:"sm",className:"bg-accent text-accent-foreground hover:bg-accent/90",disabled:!O.plan||m==="plan",onClick:Z,children:[m==="plan"?e.jsx(Ct,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(hj,{className:"h-3.5 w-3.5 mr-1.5"}),"Download plan PDF"]})]})]})}),f&&O.plan?e.jsx(B0r,{plan:O.plan,saving:o.isPending,onSave:Xt=>o.mutate({id:D.id,patch:{content:{...O,plan:Xt}}},{onSuccess:()=>se.success("Plan updated")})}):null,O.plan?e.jsx("div",{className:"rounded-3xl bg-muted/40 p-4 sm:p-8",children:e.jsx(TZe,{plan:O.plan,property:{...D.property??{},seller_name:(qe=D.property)==null?void 0:qe.seller_name},agent:G,url:`${EZe()}/revival/${D.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(Gt,{value:"emails",className:"mt-6 space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(B,{size:"sm",variant:"outline",disabled:l.isPending,onClick:()=>ie("emails"),children:[e.jsx(un,{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."})]}),(O.emails??[]).map((Xt,fs)=>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:Xt.subject}),e.jsx(Oe,{variant:"outline",children:Xt.key})]}),e.jsx("div",{className:"text-xs text-muted-foreground mt-0.5",children:Xt.preview}),e.jsx("p",{className:"mt-3 text-sm whitespace-pre-wrap leading-relaxed",children:Xt.body}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-1",children:[e.jsxs(B,{size:"sm",onClick:()=>C(Xt),children:[e.jsx(ln,{className:"h-3.5 w-3.5 mr-1.5"})," Preview & send"]}),e.jsxs(B,{size:"sm",variant:"ghost",onClick:()=>{navigator.clipboard.writeText(`${Xt.subject} ${Xt.body}`),se.success("Email copied")},children:[e.jsx(Ia,{className:"h-3.5 w-3.5 mr-1.5"})," Copy"]})]})]},fs))]}),e.jsxs(Gt,{value:"texts",className:"mt-6 space-y-3",children:[e.jsxs(B,{size:"sm",variant:"outline",disabled:l.isPending,onClick:()=>ie("sms"),children:[e.jsx(un,{className:"h-3.5 w-3.5 mr-1.5"})," Rewrite texts"]}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:(O.sms??[]).map((Xt,fs)=>e.jsxs("div",{className:"revival-tile p-5",children:[e.jsx(Oe,{variant:"outline",children:Xt.key}),e.jsx("p",{className:"mt-2 text-sm leading-relaxed",children:Xt.body}),e.jsxs(B,{size:"sm",variant:"ghost",className:"mt-2",onClick:()=>{navigator.clipboard.writeText(Xt.body),se.success("Text copied")},children:[e.jsx(Ia,{className:"h-3.5 w-3.5 mr-1.5"})," Copy"]})]},fs))})]}),e.jsxs(Gt,{value:"scripts",className:"mt-6 space-y-3",children:[e.jsxs(B,{size:"sm",variant:"outline",disabled:l.isPending,onClick:()=>ie("scripts"),children:[e.jsx(un,{className:"h-3.5 w-3.5 mr-1.5"})," Rewrite scripts"]}),[["Phone script",(Qe=O.scripts)==null?void 0:Qe.phone],["Voicemail",(Ue=O.scripts)==null?void 0:Ue.voicemail],["Video script",(Xe=O.scripts)==null?void 0:Xe.video],["Door knock",(nt=O.scripts)==null?void 0:nt.door_knock]].map(([Xt,fs])=>fs?e.jsxs("div",{className:"revival-tile p-5",children:[e.jsx("div",{className:"font-semibold",children:Xt}),e.jsx("p",{className:"mt-2 text-sm whitespace-pre-wrap leading-relaxed",children:fs})]},Xt):null),((($e=O.scripts)==null?void 0:$e.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:(((Ge=O.scripts)==null?void 0:Ge.objections)??[]).map((Xt,fs)=>e.jsxs("div",{children:[e.jsxs("div",{className:"text-sm font-medium",children:["“",Xt.objection,"”"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:Xt.response})]},fs))})]}):null]}),e.jsx(Gt,{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(J,{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(fn,{checked:D.published,onCheckedChange:Xt=>o.mutate({id:D.id,patch:{published:Xt}})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"font-semibold",children:"Campaign name"}),e.jsx(xe,{defaultValue:D.name,onBlur:Xt=>Xt.target.value!==D.name&&o.mutate({id:D.id,patch:{name:Xt.target.value}})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{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:H0r.map(Xt=>e.jsxs("button",{type:"button",onClick:()=>o.mutate({id:D.id,patch:{theme:Xt.id}}),className:`text-left rounded-xl border p-3 transition-all ${(D.theme??"estate")===Xt.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:[Xt.swatch.map(fs=>e.jsx("span",{className:"h-4 w-4 rounded-full border border-black/10",style:{background:fs}},fs)),e.jsx("span",{className:"font-medium ml-1",children:Xt.name})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1.5",children:Xt.description})]},Xt.id))})]}),e.jsxs("div",{className:"flex items-center justify-between border-t border-border pt-4",children:[e.jsxs("div",{children:[e.jsxs(J,{className:"font-semibold flex items-center gap-1.5",children:[e.jsx($4,{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(fn,{checked:!!D.alert_on_engagement,onCheckedChange:Xt=>o.mutate({id:D.id,patch:{alert_on_engagement:Xt}})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(J,{className:"font-semibold flex items-center gap-1.5",children:[e.jsx(ln,{className:"h-4 w-4"})," Auto-enroll new leads in a drip"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Sellers who submit the form get added to this campaign automatically."}),e.jsxs(is,{value:D.drip_campaign_id??"none",onValueChange:Xt=>o.mutate({id:D.id,patch:{drip_campaign_id:Xt==="none"?null:Xt}}),children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"No drip campaign"})}),e.jsxs(as,{children:[e.jsx(He,{value:"none",children:"No drip campaign"}),(E.data??[]).map(Xt=>e.jsx(He,{value:Xt.id,children:Xt.name},Xt.id))]})]}),!M&&e.jsxs("div",{className:"mt-3 rounded-xl border border-amber-500/30 bg-amber-500/5 p-4",children:[e.jsx("p",{className:"text-sm font-semibold text-foreground",children:"Recommended: Expired Listing Revival (8 emails, 45 days)"}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"A luxury-styled nurture written for homeowners whose listing expired — confirmation, why homes expire, the 5-part relaunch plan, pricing truth, presentation, a case study, and two graceful closes."}),e.jsx(B,{size:"sm",className:"mt-3",disabled:P.isPending,onClick:()=>P.mutate(),children:P.isPending?"Installing…":"Install & assign to this campaign"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"font-semibold",children:"Internal notes"}),e.jsx(Ms,{rows:4,defaultValue:((ct=D.branding)==null?void 0:ct.notes)??"",onBlur:Xt=>o.mutate({id:D.id,patch:{branding:{...D.branding,notes:Xt.target.value}}})})]}),e.jsx("div",{className:"border-t border-border pt-4",children:e.jsxs(B,{variant:"destructive",size:"sm",onClick:async()=>{await Xi("Delete this campaign? The landing page will stop working.")&&d.mutate(D.id,{onSuccess:()=>t("/apps/listing-revival")})},children:[e.jsx(Sn,{className:"h-3.5 w-3.5 mr-1.5"})," Delete campaign"]})})]})})]}),O.letter?e.jsx("div",{ref:$,"aria-hidden":!0,className:"pointer-events-none fixed left-[-10000px] top-0 w-[816px]",children:e.jsx(MAt,{campaign:D,letter:O.letter,url:V,agent:G,className:"shadow-none"})}):null,O.plan?e.jsx("div",{ref:Y,"aria-hidden":!0,className:"pointer-events-none fixed left-[-10000px] top-0 w-[816px]",children:e.jsx(TZe,{plan:O.plan,property:{...D.property??{},seller_name:(xt=D.property)==null?void 0:xt.seller_name},agent:G,url:`${EZe()}/revival/${D.slug}/plan`})}):null]}),e.jsx($0r,{open:!!S,onOpenChange:Xt=>!Xt&&C(null),campaignId:D.id,email:S,ctaUrl:V,seller:{name:(qt=D.property)==null?void 0:qt.seller_name,email:(Vt=D.property)==null?void 0:Vt.seller_email}}),e.jsx(V0r,{open:b,onOpenChange:j,property:D.property,saving:c.isPending,onSave:Xt=>{var fs;(fs=D.property)!=null&&fs.id&&c.mutate({id:D.property.id,patch:Xt},{onSuccess:()=>j(!1)})}})]})}function als(){const{user:s}=hs();return at({queryKey:["fsbo-campaigns",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("fsbo_campaigns").select("*, property:fsbo_properties(*)").order("created_at",{ascending:!1});if(n)throw n;return t??[]}})}function W0r(s){return at({queryKey:["fsbo-campaign",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("fsbo_campaigns").select("*, property:fsbo_properties(*)").eq("id",s).maybeSingle();if(n)throw n;return t??null}})}function ils(){const{user:s}=hs();return at({queryKey:["fsbo-properties",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("fsbo_properties").select("*").order("created_at",{ascending:!1});if(n)throw n;return t??[]}})}function eot(){const{user:s}=hs();return at({queryKey:["fsbo-leads",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("fsbo_leads").select("*").order("created_at",{ascending:!1});if(n)throw n;return t??[]}})}function K0r(){const{user:s}=hs();return at({queryKey:["fsbo-tasks",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("fsbo_tasks").select("*").order("due_date",{ascending:!0});if(n)throw n;return t??[]}})}function tot(){const{user:s}=hs();return at({queryKey:["fsbo-events",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("fsbo_events").select("*").order("created_at",{ascending:!1}).limit(1e3);if(n)throw n;return t??[]}})}function yDe(){const s=Bt(),t=()=>{["fsbo-campaigns","fsbo-campaign","fsbo-properties","fsbo-leads","fsbo-tasks","fsbo-events"].forEach(c=>s.invalidateQueries({queryKey:[c]}))},n=mt({mutationFn:async c=>{const{data:d,error:u}=await q.functions.invoke("fsbo-generate",{body:c});if(u)throw u;if(d!=null&&d.error)throw new Error(String(d.error));return d},onSuccess:t,onError:c=>se.error(c.message)}),r=mt({mutationFn:async c=>{const{error:d}=await q.from("fsbo_campaigns").update(c.patch).eq("id",c.id);if(d)throw d},onSuccess:()=>{t(),se.success("Saved")},onError:c=>se.error(c.message)}),a=mt({mutationFn:async c=>{const{error:d}=await q.from("fsbo_campaigns").delete().eq("id",c);if(d)throw d},onSuccess:()=>{t(),se.success("Campaign deleted")},onError:c=>se.error(c.message)}),i=mt({mutationFn:async c=>{const{error:d}=await q.from("fsbo_campaigns").update({status:c.archived?"archived":"draft",published:!c.archived}).eq("id",c.id);if(d)throw d;return c},onSuccess:c=>{t(),se.success(c.archived?"Campaign archived":"Campaign restored")},onError:c=>se.error(c.message)}),l=mt({mutationFn:async c=>{const{error:d}=await q.from("fsbo_properties").update(c.patch).eq("id",c.id);if(d)throw d},onSuccess:()=>{t(),se.success("Property details updated")},onError:c=>se.error(c.message)}),o=mt({mutationFn:async c=>{const{error:d}=await q.from("fsbo_tasks").update({completed_at:c.done?new Date().toISOString():null}).eq("id",c.id);if(d)throw d},onSuccess:t,onError:c=>se.error(c.message)});return{generate:n,saveCampaign:r,deleteCampaign:a,archiveCampaign:i,toggleTask:o,updateProperty:l,invalidate:t}}function Y0r(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 U6e=[{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."}],ols=[{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"}],lls=[{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"}],Z0r=[{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"}],X0r=["Need to sell quickly","Want to maximize net proceeds","Testing the market","Already bought another home","Relocating","Downsizing / Upsizing","Estate sale","Other"],Q0r=[{value:"email",label:"Email"},{value:"phone",label:"Phone"},{value:"text",label:"Text"}];function MZe(s){return s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)}function J0r(s){const t=MZe(s)||"property",n=Math.random().toString(36).slice(2,7);return`${t}-${n}`}function PZe(s){return s==null?"—":`$${Number(s).toLocaleString("en-US",{maximumFractionDigits:0})}`}function eyr(){return typeof window>"u"?"":window.location.origin}function cls(s){return`${eyr()}/fsbo/${s}`}const DAt="fsbo_breakthrough";function tyr(){const{user:s,loading:t,isAdmin:n}=hs(),{data:r}=at({queryKey:["feature-entitlement",DAt,s==null?void 0:s.id],enabled:!!s&&!n,staleTime:5*60*1e3,queryFn:async()=>{const{data:a,error:i}=await q.from("feature_entitlements").select("enabled, expires_at, tier").eq("user_id",s.id).eq("feature_key",DAt).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 syr={property_address:"",city:"",state:"",zip:"",property_type:"single_family",estimated_value:"",seller_name:"",seller_email:"",seller_phone:"",notes:"",photo_url:""};function dls({property:s,open:t,onOpenChange:n}){const{updateProperty:r}=yDe(),[a,i]=_.useState(syr);_.useEffect(()=>{!t||!s||i({property_address:s.property_address??"",city:s.city??"",state:s.state??"",zip:s.zip??"",property_type:s.property_type??"single_family",estimated_value:s.estimated_value!=null?String(s.estimated_value):"",seller_name:s.seller_name??"",seller_email:s.seller_email??"",seller_phone:s.seller_phone??"",notes:s.notes??"",photo_url:s.photo_url??""})},[t,s]);const l=(d,u)=>i(h=>({...h,[d]:u})),o=(d,u,h={})=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:u}),e.jsx(xe,{value:a[d],onChange:m=>l(d,m.target.value),...h})]}),c=async()=>{s&&(await r.mutateAsync({id:s.id,patch:{property_address:a.property_address.trim()||s.property_address,city:a.city||null,state:a.state||null,zip:a.zip||null,property_type:a.property_type||"single_family",estimated_value:a.estimated_value?Number(a.estimated_value):null,seller_name:a.seller_name||null,seller_email:a.seller_email||null,seller_phone:a.seller_phone||null,notes:a.notes||null,photo_url:a.photo_url||null}}),n(!1))};return e.jsx(Ls,{open:t,onOpenChange:n,children:e.jsxs(Ps,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"Edit property & seller details"}),e.jsx(_r,{children:"Update the homeowner's name, phone, email, estimated value and notes. Changes show up everywhere this property appears."})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsx("div",{className:"sm:col-span-2",children:o("property_address","Property address")}),o("city","City"),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o("state","State"),o("zip","Zip")]}),o("estimated_value","Estimated value",{type:"number",placeholder:"895000"}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Property type"}),e.jsx("select",{className:"w-full h-10 rounded-md border border-input bg-background px-3 py-2 text-sm",value:a.property_type,onChange:d=>l("property_type",d.target.value),children:lls.map(d=>e.jsx("option",{value:d.value,children:d.label},d.value))})]}),o("seller_name","Seller name"),o("seller_phone","Seller phone"),e.jsx("div",{className:"sm:col-span-2",children:o("seller_email","Seller email",{type:"email"})}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Property photo"}),e.jsx(yz,{value:a.photo_url,onChange:d=>l("photo_url",d??""),label:"Property photo",prefix:"fsbo-property"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Agent notes"}),e.jsx(Ms,{rows:6,value:a.notes,onChange:d=>l("notes",d.target.value)})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsxs(B,{onClick:c,disabled:r.isPending,children:[r.isPending?e.jsx(Ct,{className:"h-4 w-4 mr-1 animate-spin"}):null,"Save details"]})]})]})})}const nyr=[{id:"dashboard",label:"Dashboard",icon:hm},{id:"campaigns",label:"Campaigns",icon:un},{id:"properties",label:"Properties",icon:Jr},{id:"letters",label:"Letters",icon:ln},{id:"landing",label:"Landing Pages",icon:sl},{id:"guides",label:"Seller Guides",icon:Fr},{id:"followup",label:"Follow Up",icon:qf},{id:"analytics",label:"Analytics",icon:bl},{id:"templates",label:"Templates",icon:pj},{id:"settings",label:"Settings",icon:fS}];function P5({label:s,value:t,icon:n,delay:r=0,hint:a}){return e.jsxs(Sr.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 ryr(){const s=Fn(),[t,n]=_.useState("dashboard"),[r,a]=_.useState(""),[i,l]=_.useState(!1),[o,c]=_.useState(null),[d,u]=_.useState(null),h=tyr(),m=als(),p=ils(),f=eot(),y=K0r(),v=tot(),{toggleTask:g,archiveCampaign:b,deleteCampaign:j}=yDe(),S=m.data??[],C=f.data??[],E=v.data??[],P=y.data??[],M=_.useMemo(()=>{const Y=Z=>E.filter(ne=>ne.event_type===Z).length;return{properties:(p.data??[]).length,campaigns:S.length,letters:S.filter(Z=>{var ne;return(ne=Z.content)==null?void 0:ne.letter}).length,qr:Y("qr_scan"),visits:Y("page_view"),guideViews:Y("guide_view"),leads:C.length,appointments:Y("appointment"),listed:C.filter(Z=>Z.temperature==="hot").length,hot:C.filter(Z=>Z.temperature==="hot").length}},[S,C,E,p.data]),I=_.useMemo(()=>{const Y=[];for(let Z=13;Z>=0;Z--){const ne=new Date(Date.now()-Z*864e5),ce=ne.toISOString().slice(0,10);Y.push({day:Hs(ne,"MMM d"),visits:E.filter(ie=>ie.event_type==="page_view"&&ie.created_at.startsWith(ce)).length,scans:E.filter(ie=>ie.event_type==="qr_scan"&&ie.created_at.startsWith(ce)).length,leads:C.filter(ie=>ie.created_at.startsWith(ce)).length})}return Y},[E,C]),D=Y=>Y.status==="archived",O=S.filter(Y=>{var ne,ce;if(i?!D(Y):D(Y))return!1;const Z=r.trim().toLowerCase();return Z?`${Y.name} ${((ne=Y.property)==null?void 0:ne.property_address)??""} ${((ce=Y.property)==null?void 0:ce.seller_name)??""}`.toLowerCase().includes(Z):!0}),V=S.filter(D).length,G=Y=>s(`/apps/fsbo-breakthrough/campaigns/${Y}`),$=Y=>{navigator.clipboard.writeText(cls(Y)),se.success("Landing page link copied")},H=Y=>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(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{value:r,onChange:Z=>a(Z.target.value),placeholder:"Search campaigns…",className:"pl-9"})]}),e.jsxs(B,{variant:i?"default":"outline",size:"sm",onClick:()=>l(Z=>!Z),children:[e.jsx(by,{className:"h-3.5 w-3.5 mr-1.5"}),i?"Viewing archived":`Archived (${V})`]})]}),O.length===0?e.jsx("div",{className:"fsbo-tile p-10 text-center text-muted-foreground",children:i?"No archived campaigns.":Y}):e.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:O.map((Z,ne)=>{var le,be,me,he,pe;const ce=U6e.find(Ce=>Ce.id===Z.style),ie=C.filter(Ce=>Ce.campaign_id===Z.id).length,te=E.filter(Ce=>Ce.campaign_id===Z.id&&Ce.event_type==="page_view").length,ae=D(Z);return e.jsxs(Sr.div,{initial:{opacity:0,y:14},animate:{opacity:1,y:0},transition:{delay:Math.min(ne*.04,.3),duration:.4},className:At("fsbo-tile overflow-hidden",ae&&"opacity-80"),children:[e.jsxs("div",{className:"h-28 bg-muted relative",children:[(le=Z.property)!=null&&le.photo_url?e.jsx("img",{src:Z.property.photo_url,alt:Z.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(Jr,{className:"h-7 w-7 text-accent"})}),e.jsx(Oe,{className:"absolute top-3 left-3 bg-background/90 text-foreground border-0",children:(ce==null?void 0:ce.name)??Z.style}),ae?e.jsx(Oe,{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:((be=Z.property)==null?void 0:be.property_address)??Z.name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:((me=Z.property)==null?void 0:me.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(sl,{className:"h-3.5 w-3.5"}),te]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(In,{className:"h-3.5 w-3.5"}),ie]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Jr,{className:"h-3.5 w-3.5"}),((he=Z.property)==null?void 0:he.property_type)??"—"]}),((pe=Z.property)==null?void 0:pe.estimated_value)!=null?e.jsxs("span",{className:"flex items-center gap-1 font-medium text-foreground",children:[e.jsx(yd,{className:"h-3.5 w-3.5"}),PZe(Z.property.estimated_value)]}):null]}),e.jsxs("div",{className:"mt-4 flex gap-2",children:[e.jsxs(B,{size:"sm",className:"flex-1",onClick:()=>G(Z.id),children:["Open ",e.jsx(La,{className:"h-3.5 w-3.5 ml-1"})]}),e.jsx(B,{size:"sm",variant:"outline",onClick:()=>$(Z.slug),children:e.jsx(Ia,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"sm",variant:"outline",asChild:!0,children:e.jsx("a",{href:`/fsbo/${Z.slug}`,target:"_blank",rel:"noreferrer",children:e.jsx(wr,{className:"h-3.5 w-3.5"})})}),e.jsxs(tu,{children:[e.jsx(su,{asChild:!0,children:e.jsx(B,{size:"sm",variant:"outline",children:e.jsx(Xx,{className:"h-3.5 w-3.5"})})}),e.jsxs(Od,{align:"end",children:[e.jsxs(ca,{disabled:!Z.property,onClick:()=>Z.property&&u(Z.property),children:[e.jsx(Ya,{className:"h-4 w-4 mr-2"})," Edit property & seller details"]}),e.jsx(ca,{onClick:()=>b.mutate({id:Z.id,archived:!ae}),children:ae?e.jsxs(e.Fragment,{children:[e.jsx(VM,{className:"h-4 w-4 mr-2"})," Restore campaign"]}):e.jsxs(e.Fragment,{children:[e.jsx(by,{className:"h-4 w-4 mr-2"})," Archive campaign"]})}),e.jsx(M0,{}),e.jsxs(ca,{className:"text-destructive focus:text-destructive",onClick:()=>{var Ce;return c({id:Z.id,name:((Ce=Z.property)==null?void 0:Ce.property_address)??Z.name})},children:[e.jsx(Sn,{className:"h-4 w-4 mr-2"})," Delete permanently"]})]})]})]})]})]},Z.id)})}),e.jsx(Kl,{open:!!o,onOpenChange:Z=>!Z&&c(null),children:e.jsxs(Ol,{children:[e.jsxs(zl,{children:[e.jsx(Ul,{children:"Delete this campaign?"}),e.jsxs(ql,{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($l,{children:"Cancel"}),e.jsx(Ml,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",onClick:()=>{o&&j.mutate(o.id),c(null)},children:"Delete permanently"})]})]})})]});return!h.isLoading&&!h.hasAccess?e.jsx(zs,{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(un,{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(zs,{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(Sr.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(B,{size:"lg",className:"bg-accent text-accent-foreground hover:bg-accent/90",onClick:()=>s("/apps/fsbo-breakthrough/new"),children:[e.jsx(rn,{className:"h-4 w-4 mr-1"})," New Campaign"]}),e.jsx(B,{size:"lg",variant:"outline",className:"bg-transparent text-white border-white/25 hover:bg-white/10",onClick:()=>n("campaigns"),children:"View campaigns"})]})]})]}),e.jsxs(Yr,{value:t,onValueChange:n,className:"mt-6",children:[e.jsx(Zr,{className:"flex w-full overflow-x-auto no-scrollbar justify-start bg-transparent p-0 gap-2 h-auto",children:nyr.map(Y=>e.jsxs(Ht,{value:Y.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(Y.icon,{className:"h-3.5 w-3.5 mr-1.5"}),Y.label]},Y.id))}),e.jsxs(Gt,{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(P5,{label:"Properties",value:M.properties,icon:Jr,delay:0}),e.jsx(P5,{label:"Campaigns",value:M.campaigns,icon:un,delay:.04}),e.jsx(P5,{label:"Letters",value:M.letters,icon:ln,delay:.08}),e.jsx(P5,{label:"QR Scans",value:M.qr,icon:Hf,delay:.12}),e.jsx(P5,{label:"Page Visits",value:M.visits,icon:sl,delay:.16}),e.jsx(P5,{label:"Guide Views",value:M.guideViews,icon:Fr,delay:.2}),e.jsx(P5,{label:"Seller Leads",value:M.leads,icon:In,delay:.24}),e.jsx(P5,{label:"Appointments",value:M.appointments,icon:bv,delay:.28}),e.jsx(P5,{label:"Hot Leads",value:M.hot,icon:gu,delay:.32,hint:"Score 75+"}),e.jsx(P5,{label:"Listings Won",value:M.listed,icon:wl,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(jb,{width:"100%",height:"100%",children:e.jsxs(Jst,{data:I,children:[e.jsxs("defs",{children:[e.jsxs("linearGradient",{id:"fsboVisits",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"hsl(var(--primary))",stopOpacity:.4}),e.jsx("stop",{offset:"100%",stopColor:"hsl(var(--primary))",stopOpacity:0})]}),e.jsxs("linearGradient",{id:"fsboLeads",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"hsl(var(--accent))",stopOpacity:.5}),e.jsx("stop",{offset:"100%",stopColor:"hsl(var(--accent))",stopOpacity:0})]})]}),e.jsx(kE,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",vertical:!1}),e.jsx(Mv,{dataKey:"day",tick:{fontSize:11},stroke:"hsl(var(--muted-foreground))"}),e.jsx(Pv,{allowDecimals:!1,tick:{fontSize:11},stroke:"hsl(var(--muted-foreground))",width:28}),e.jsx(Mf,{contentStyle:{borderRadius:12,border:"1px solid hsl(var(--border))"}}),e.jsx(U_,{type:"monotone",dataKey:"visits",stroke:"hsl(var(--primary))",fill:"url(#fsboVisits)",strokeWidth:2}),e.jsx(U_,{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:[P.filter(Y=>!Y.completed_at).slice(0,5).map(Y=>e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg bg-muted/40",children:[e.jsx($a,{checked:!!Y.completed_at,onCheckedChange:Z=>g.mutate({id:Y.id,done:!!Z})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-sm font-medium",children:Y.title}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Y.detail}),Y.due_date?e.jsxs("div",{className:"text-xs text-muted-foreground mt-1",children:["Due ",Y.due_date]}):null]})]},Y.id)),!P.filter(Y=>!Y.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(Gt,{value:"campaigns",className:"mt-6",children:H("No campaigns yet. Start with a new FSBO property.")}),e.jsx(Gt,{value:"properties",className:"mt-6",children:e.jsx("div",{className:"space-y-3",children:(p.data??[]).length===0?e.jsx("div",{className:"fsbo-tile p-10 text-center text-muted-foreground",children:"No FSBO properties added yet."}):e.jsx("div",{className:"grid gap-3 md:grid-cols-2 lg:grid-cols-3",children:(p.data??[]).map(Y=>e.jsxs("div",{className:"fsbo-tile p-4",children:[e.jsx("div",{className:"font-semibold",children:Y.property_address}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[Y.city,Y.city&&Y.state?", ":"",Y.state]}),e.jsx("div",{className:"mt-2 text-sm",children:Y.seller_name||"—"}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[Y.seller_phone||"—"," · ",Y.seller_email||"—"]}),e.jsxs("div",{className:"mt-1 text-sm text-muted-foreground",children:["Est. value ",PZe(Y.estimated_value)]}),e.jsxs(B,{size:"sm",variant:"outline",className:"mt-3",onClick:()=>u(Y),children:[e.jsx(Ya,{className:"h-3.5 w-3.5 mr-1.5"})," Edit details"]})]},Y.id))})})}),e.jsx(Gt,{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:P.map(Y=>e.jsxs("div",{className:At("flex items-start gap-3 p-3 rounded-lg",Y.completed_at?"bg-muted/30":"bg-muted/40"),children:[e.jsx($a,{checked:!!Y.completed_at,onCheckedChange:Z=>g.mutate({id:Y.id,done:!!Z})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:At("text-sm font-medium",Y.completed_at&&"line-through text-muted-foreground"),children:Y.title}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Y.detail}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-1 capitalize",children:[Y.channel," · ",Y.due_date??"No due date"]})]})]},Y.id))})]})}),e.jsx(Gt,{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:E.slice(0,50).map(Y=>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:Y.event_type.replace(/_/g," ")}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Hs(new Date(Y.created_at),"MMM d, h:mm a")})]},Y.id))})]})}),e.jsx(Gt,{value:"letters",className:"mt-6",children:H("Generate letter content by creating a campaign first.")}),e.jsx(Gt,{value:"landing",className:"mt-6",children:H("Generate landing pages by creating a campaign first.")}),e.jsx(Gt,{value:"guides",className:"mt-6",children:H("Generate seller guides by creating a campaign first.")}),e.jsx(Gt,{value:"templates",className:"mt-6",children:e.jsx("div",{className:"grid gap-3 md:grid-cols-2 lg:grid-cols-3",children:ols.map(Y=>e.jsxs("div",{className:"fsbo-tile p-4",children:[e.jsx("div",{className:"font-semibold",children:Y.name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:Y.note})]},Y.id))})}),e.jsx(Gt,{value:"settings",className:"mt-6",children:e.jsxs("div",{className:"fsbo-tile p-5 max-w-xl",children:[e.jsx("div",{className:"text-lg font-semibold",children:"Settings"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:"Campaign style, tone, and landing page settings are managed inside each campaign."})]})})]}),e.jsx(dls,{property:d,open:!!d,onOpenChange:Y=>{Y||u(null)}})]})})}const RAt=["Add the property","Choose the campaign voice","Generate everything"];function ayr(){const s=Fn(),{user:t}=hs(),{generate:n,invalidate:r}=yDe(),[a,i]=_.useState(0),[l,o]=_.useState(!1),[c,d]=_.useState(U6e[0].id),[u,h]=_.useState("professional"),[m,p]=_.useState({property_address:"",city:"",state:"",zip:"",property_type:"single_family",estimated_value:"",seller_name:"",seller_email:"",seller_phone:"",notes:"",photo_url:""}),f=(b,j)=>p(S=>({...S,[b]:j})),y=a===0?m.property_address.trim().length>3:!0,v=async()=>{if(t){o(!0);try{const{data:b,error:j}=await q.from("fsbo_properties").insert({owner_user_id:t.id,property_address:m.property_address.trim(),city:m.city||null,state:m.state||null,zip:m.zip||null,property_type:m.property_type||"single_family",estimated_value:m.estimated_value?Number(m.estimated_value):null,seller_name:m.seller_name||null,seller_email:m.seller_email||null,seller_phone:m.seller_phone||null,notes:m.notes||null,photo_url:m.photo_url||null}).select().single();if(j)throw j;const{data:S,error:C}=await q.from("fsbo_campaigns").insert({owner_user_id:t.id,property_id:b.id,name:m.property_address.trim(),slug:J0r(m.property_address),style:c,tone:u,status:"generating",published:!0}).select().single();if(C)throw C;await n.mutateAsync({campaignId:S.id}),r(),se.success("Campaign built — everything is ready."),s(`/apps/fsbo-breakthrough/campaigns/${S.id}`)}catch(b){se.error(b instanceof Error?b.message:"Could not create the campaign")}finally{o(!1)}}},g=(b,j,S={})=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:j}),e.jsx(xe,{value:m[b],onChange:C=>f(b,C.target.value),...S})]});return e.jsx(zs,{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(B,{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:RAt.map((b,j)=>e.jsxs("div",{className:"flex items-center gap-3 flex-1",children:[e.jsx("div",{className:At("h-9 w-9 rounded-full grid place-items-center text-sm font-bold shrink-0 transition-colors",jf("property_type",b.target.value),children:lls.map(b=>e.jsx("option",{value:b.value,children:b.label},b.value))})]}),g("seller_name","Seller name"),g("seller_email","Seller email",{type:"email"}),g("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(J,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Property photo"}),e.jsx(yz,{value:m.photo_url,onChange:b=>f("photo_url",b??""),label:"Property photo",prefix:"fsbo-property"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Agent notes"}),e.jsx(Ms,{rows:6,value:m.notes,onChange:b=>f("notes",b.target.value),placeholder:"Anything you know: asking price, why they're selling solo, motivation, photos, etc."})]})]})]}):null,a===1?e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"fsbo-tile p-6",children:[e.jsx("div",{className:"fsbo-eyebrow text-muted-foreground",children:"Step two"}),e.jsx("h2",{className:"fsbo-serif text-2xl mt-1",children:"Pick the voice of the campaign"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"The style shapes the letter, the landing page and the whole follow-up sequence."}),e.jsx("div",{className:"grid gap-3 mt-5 md:grid-cols-2 xl:grid-cols-3",children:U6e.map(b=>e.jsxs("button",{onClick:()=>d(b.id),className:At("text-left p-5 rounded-xl border transition-all relative overflow-hidden",c===b.id?"border-primary bg-primary/5":"border-border bg-card hover:border-primary/30"),children:[e.jsx("div",{className:At("absolute inset-x-0 top-0 h-1 bg-gradient-to-r",b.accent)}),e.jsx("div",{className:"font-semibold",children:b.name}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:b.tagline}),e.jsx("div",{className:"text-sm text-muted-foreground mt-2",children:b.description}),e.jsx("div",{className:"mt-3 text-xs text-primary font-medium",children:b.previewHeadline}),e.jsx("div",{className:"text-xs text-muted-foreground",children:b.previewBody})]},b.id))})]}),e.jsxs("div",{className:"fsbo-tile p-6",children:[e.jsx("div",{className:"fsbo-eyebrow text-muted-foreground",children:"Letter tone"}),e.jsx("div",{className:"grid gap-3 mt-3 sm:grid-cols-2 lg:grid-cols-5",children:ols.map(b=>e.jsxs("button",{onClick:()=>h(b.id),className:At("p-4 rounded-xl border text-left transition-all",u===b.id?"border-primary bg-primary/5":"border-border bg-card hover:border-primary/30"),children:[e.jsx("div",{className:"font-medium",children:b.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:b.note})]},b.id))})]})]}):null,a===2?e.jsxs("div",{className:"fsbo-tile p-10 text-center",children:[e.jsx("div",{className:"mx-auto h-14 w-14 rounded-full bg-primary/10 grid place-items-center mb-4",children:e.jsx(Qx,{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(B,{size:"lg",onClick:v,disabled:l,children:[l?e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(un,{className:"h-4 w-4 mr-2"}),"Generate campaign"]})})]}):null]},a)}),e.jsxs("div",{className:"flex justify-between mt-6",children:[e.jsxs(B,{variant:"outline",disabled:a===0,onClick:()=>i(b=>b-1),children:[e.jsx(ka,{className:"h-4 w-4 mr-1"})," Back"]}),a<2&&e.jsxs(B,{disabled:!y,onClick:()=>i(b=>b+1),children:["Next ",e.jsx(La,{className:"h-4 w-4 ml-1"})]})]})]})})}function iyr(){var be,me,he,pe,Ce,Ae,Pe,ze,ke,Ze,Se,Fe,Ne,Ye,Ve,qe,Qe,Ue,Xe,nt;const{id:s}=Li(),t=Fn(),{user:n}=hs(),r=W0r(s),a=tot(),i=eot(),{generate:l,saveCampaign:o,deleteCampaign:c}=yDe(),[d,u]=_.useState(""),[h,m]=_.useState(!1),[p,f]=_.useState("letter"),[y,v]=_.useState(!1),[g,b]=_.useState(!1),j=r.data,S=(j==null?void 0:j.content)??{},C=j?cls(j.slug):"",E=at({queryKey:["fsbo-agent-profile",n==null?void 0:n.id],enabled:!!n,queryFn:async()=>{const{data:$e}=await q.from("profiles").select("name, email, phone, avatar_url, brokerage_name, website_url, title").eq("id",n.id).maybeSingle();return $e}}),{data:P}=XUt(),M={name:((be=E.data)==null?void 0:be.name)??(P==null?void 0:P.agent_name)??null,title:((me=E.data)==null?void 0:me.title)??null,phone:((he=E.data)==null?void 0:he.phone)??(P==null?void 0:P.phone)??null,email:((pe=E.data)==null?void 0:pe.email)??(P==null?void 0:P.email)??null,website_url:((Ce=E.data)==null?void 0:Ce.website_url)??(P==null?void 0:P.website_url)??null,avatar_url:((Ae=E.data)==null?void 0:Ae.avatar_url)??(P==null?void 0:P.headshot_url)??null,brokerage_name:((Pe=E.data)==null?void 0:Pe.brokerage_name)??(P==null?void 0:P.brokerage_name)??null,logo_url:(P==null?void 0:P.brokerage_logo_url)??(P==null?void 0:P.logo_url)??null,license_number:(P==null?void 0:P.license_number)??null,license_state:(P==null?void 0:P.license_state)??null,compliance_line:(P==null?void 0:P.compliance_line)??null},I=_.useRef(null),D=_.useRef(null),O=_.useMemo(()=>{var ct,xt;const $e=(a.data??[]).filter(qt=>qt.campaign_id===s),Ge={};return $e.forEach(qt=>{Ge[qt.event_type]=(Ge[qt.event_type]??0)+1}),Ge.letter=S.letter?1:0,Ge.email=((ct=S.emails)==null?void 0:ct.length)??0,Ge.sms=((xt=S.sms)==null?void 0:xt.length)??0,Ge.form_submit=(i.data??[]).filter(qt=>qt.campaign_id===s).length,Ge},[a.data,i.data,s,S]),V=async()=>{var $e;if(I.current){m(!0);try{const Ge=await $H(I.current,{pixelRatio:2}),ct=document.createElement("a");ct.href=Ge;const xt=MZe((($e=j==null?void 0:j.property)==null?void 0:$e.property_address)??"letter");ct.download=`${xt||"letter"}.png`,ct.click(),se.success("Letter image downloaded")}catch{se.error("Could not download letter")}finally{m(!1)}}},G=async()=>{var $e;if(D.current){m(!0);try{const Ge=await $H(D.current,{pixelRatio:2}),ct=document.createElement("a");ct.href=Ge;const xt=MZe((($e=j==null?void 0:j.property)==null?void 0:$e.property_address)??"guide");ct.download=`${xt||"guide"}-guide.png`,ct.click(),se.success("Guide image downloaded")}catch{se.error("Could not download guide")}finally{m(!1)}}},$=$e=>{var Xt;const Ge=document.querySelector("[data-print-root]"),ct=Ge?document.createElement("div"):null;Ge&&ct&&((Xt=Ge.parentNode)==null||Xt.insertBefore(ct,Ge),document.body.appendChild(Ge));const xt=document.title;document.title=$e,document.body.classList.add("printing-doc");let qt=!1;const Vt=()=>{qt||(qt=!0,Ge&&(ct!=null&&ct.parentNode)&&ct.parentNode.replaceChild(Ge,ct),document.body.classList.remove("printing-doc"),document.title=xt,window.removeEventListener("afterprint",Vt))};window.addEventListener("afterprint",Vt);try{window.print()}finally{setTimeout(Vt,1e3)}},H=(((ze=j==null?void 0:j.property)==null?void 0:ze.property_address)??"Campaign").replace(/[\\/:*?"<>|]/g,"-").trim(),Y=$e=>{s&&(l.mutate({campaignId:s,section:$e,instruction:d}),u(""))};if(r.isLoading)return e.jsx(zs,{title:"Campaign",children:e.jsx("div",{className:"grid place-items-center py-24",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin"})})});if(!j)return e.jsx(zs,{title:"Campaign",children:e.jsx("div",{className:"py-12 text-center text-muted-foreground",children:"Campaign not found."})});const Z=U6e.find($e=>$e.id===j.style),ne=S.letter,ce=S.landing,ie=S.guide,te=S.emails??[],ae=S.sms??[],le=S.scripts;return e.jsx(zs,{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(B,{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.jsx(dls,{property:j.property,open:g,onOpenChange:b}),e.jsxs("div",{className:"fsbo-dark rounded-2xl p-6 sm:p-8 relative overflow-hidden",children:[e.jsx("div",{className:"absolute -right-10 -top-16 h-56 w-56 rounded-full bg-accent/20 blur-3xl"}),e.jsxs("div",{className:"relative flex flex-col lg:flex-row lg:items-center justify-between gap-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"fsbo-eyebrow text-accent",children:[(Z==null?void 0:Z.name)??j.style," · ",j.status]}),e.jsx("h1",{className:"fsbo-serif text-2xl sm:text-3xl mt-1",children:((ke=j.property)==null?void 0:ke.property_address)??j.name}),e.jsxs("p",{className:"text-white/70 mt-1",children:[((Ze=j.property)==null?void 0:Ze.seller_name)||"Homeowner"," · ",(Se=j.property)==null?void 0:Se.city,(Fe=j.property)!=null&&Fe.city&&((Ne=j.property)!=null&&Ne.state)?", ":"",(Ye=j.property)==null?void 0:Ye.state,(Ve=j.property)!=null&&Ve.estimated_value?` · Est. ${PZe(j.property.estimated_value)}`:""]}),(qe=j.property)!=null&&qe.seller_phone||(Qe=j.property)!=null&&Qe.seller_email?e.jsx("p",{className:"text-white/50 text-sm mt-1",children:[(Ue=j.property)==null?void 0:Ue.seller_phone,(Xe=j.property)==null?void 0:Xe.seller_email].filter(Boolean).join(" · ")}):null]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(B,{size:"sm",variant:"outline",className:"bg-white/10 border-white/20 text-white hover:bg-white/20",onClick:()=>b(!0),children:[e.jsx(Ya,{className:"h-4 w-4 mr-1"})," Edit details"]}),e.jsx(B,{size:"sm",variant:"outline",className:"bg-white/10 border-white/20 text-white hover:bg-white/20",asChild:!0,children:e.jsxs("a",{href:C,target:"_blank",rel:"noreferrer",children:[e.jsx(sl,{className:"h-4 w-4 mr-1"})," Preview"]})}),e.jsxs(B,{size:"sm",variant:"outline",className:"bg-white/10 border-white/20 text-white hover:bg-white/20",onClick:()=>{navigator.clipboard.writeText(C),se.success("Copied")},children:[e.jsx(Ia,{className:"h-4 w-4 mr-1"})," Copy link"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"bg-white/10 border-white/20 text-white hover:bg-white/20",onClick:()=>Y(),children:[e.jsx(uo,{className:"h-4 w-4 mr-1"})," Regenerate"]}),e.jsx(B,{size:"sm",variant:"outline",className:"bg-white/10 border-white/20 text-white hover:bg-white/20 hover:text-destructive",onClick:()=>c.mutate(j.id),children:e.jsx(Sn,{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:O.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:O.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:O.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:O.guide_view??0})]})]})]}),e.jsxs("div",{className:"mt-4 flex gap-2",children:[e.jsx(xe,{placeholder:"Tell AI what to change (e.g., 'make it shorter', 'focus on luxury buyers')...",value:d,onChange:$e=>u($e.target.value),className:"max-w-xl"}),e.jsx(B,{variant:"outline",onClick:()=>Y(),disabled:l.isPending,children:l.isPending?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(un,{className:"h-4 w-4"})})]}),e.jsxs(Yr,{value:p,onValueChange:f,className:"mt-6",children:[e.jsx(Zr,{className:"flex w-full overflow-x-auto no-scrollbar justify-start bg-transparent p-0 gap-2 h-auto",children:[{id:"letter",label:"Letter",icon:ln},{id:"landing",label:"Landing Page",icon:sl},{id:"guide",label:"Seller Guide",icon:Fr},{id:"scripts",label:"Scripts & Drip",icon:Hi},{id:"leads",label:"Leads",icon:_a}].map($e=>e.jsxs(Ht,{value:$e.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($e.icon,{className:"h-3.5 w-3.5 mr-1.5"})," ",$e.label]},$e.id))}),e.jsxs(Gt,{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(B,{size:"sm",variant:"outline",onClick:()=>v($e=>!$e),disabled:!ne,children:[e.jsx(Ya,{className:"h-4 w-4 mr-1"})," ",y?"Close editor":"Edit letter"]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:V,disabled:h,children:[e.jsx(hj,{className:"h-4 w-4 mr-1"})," Download image"]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>$(H),children:[e.jsx(ZA,{className:"h-4 w-4 mr-1"})," Print"]})]})]}),y&&ne?e.jsx("div",{className:"mb-6 print:hidden","data-print-hide":!0,children:e.jsx(rls,{letter:ne,saving:o.isPending,onCancel:()=>v(!1),onSave:$e=>{o.mutate({id:s,patch:{content:{...S,letter:$e}}},{onSuccess:()=>v(!1)})}})}):null,e.jsx("div",{className:"fsbo-tile p-6 max-w-3xl mx-auto",children:e.jsxs("div",{ref:I,"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-start justify-between gap-6 mb-8 pb-4 border-b","data-print-keep":!0,children:[e.jsxs("div",{className:"min-w-0",children:[M.logo_url?e.jsx("img",{src:M.logo_url,alt:M.brokerage_name??"Brokerage logo",crossOrigin:"anonymous",className:"h-12 max-w-[220px] object-contain mb-2"}):null,M.name?e.jsx("div",{className:"font-bold text-lg",children:M.name}):null,M.title?e.jsx("div",{className:"text-sm text-gray-600",children:M.title}):null,M.brokerage_name?e.jsx("div",{className:"text-sm font-medium text-gray-700",children:M.brokerage_name}):null,e.jsxs("div",{className:"text-sm text-gray-600 mt-1 space-y-0.5",children:[M.phone?e.jsx("div",{children:M.phone}):null,M.email?e.jsx("div",{children:M.email}):null,M.website_url?e.jsx("div",{children:M.website_url.replace(/^https?:\/\//,"")}):null]})]}),M.avatar_url?e.jsx("img",{src:M.avatar_url,alt:M.name??"",crossOrigin:"anonymous",className:"h-16 w-16 rounded-full object-cover shrink-0"}):null]}),ne?e.jsxs("div",{className:"space-y-4 text-[15px] leading-relaxed",children:[e.jsx("div",{children:ne.greeting}),ne.paragraphs.map(($e,Ge)=>e.jsx("p",{children:$e},Ge)),e.jsx("div",{children:ne.closing}),e.jsx("div",{className:"font-semibold","data-print-keep":!0,children:ne.signature}),e.jsx("div",{className:"text-sm text-gray-600 italic mt-4","data-print-keep":!0,children:ne.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(AN,{value:C,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:C})]})]}),M.brokerage_name||M.license_number||M.compliance_line?e.jsxs("div",{className:"mt-6 pt-4 border-t text-[11px] leading-4 text-gray-500","data-print-keep":!0,children:[M.brokerage_name?e.jsx("div",{className:"font-medium text-gray-600",children:M.brokerage_name}):null,M.license_number?e.jsxs("div",{children:[M.license_state?`${M.license_state} `:"","License #",M.license_number]}):null,M.compliance_line?e.jsx("div",{children:M.compliance_line}):null]}):null]})})]}),e.jsxs(Gt,{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(B,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:C,target:"_blank",rel:"noreferrer",children:[e.jsx(wr,{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:ce?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-sm uppercase tracking-wider text-primary",children:ce.eyebrow}),e.jsx("h2",{className:"text-3xl font-bold",children:ce.headline}),e.jsx("p",{className:"text-lg text-muted-foreground",children:ce.subheadline}),e.jsx("p",{className:"text-foreground",children:ce.intro}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 mt-4",children:ce.discover.map(($e,Ge)=>e.jsxs("div",{className:"bg-muted/40 p-4 rounded-lg",children:[e.jsx("div",{className:"font-semibold",children:$e.title}),e.jsx("div",{className:"text-sm text-muted-foreground",children:$e.body})]},Ge))}),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:['"',ce.testimonial.quote,'"']}),e.jsxs("div",{className:"text-sm font-semibold mt-2",children:["— ",ce.testimonial.author]})]}),e.jsx("div",{className:"mt-4",children:e.jsx(B,{size:"lg",children:ce.cta})})]}):e.jsx("div",{className:"text-muted-foreground",children:"Landing page content not generated yet."})})]}),e.jsxs(Gt,{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(B,{size:"sm",variant:"outline",onClick:G,disabled:h,children:[e.jsx(hj,{className:"h-4 w-4 mr-1"})," Download image"]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>$(H),children:[e.jsx(ZA,{className:"h-4 w-4 mr-1"})," Print"]}),e.jsx(B,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:`${C}/guide`,target:"_blank",rel:"noreferrer",children:[e.jsx(wr,{className:"h-4 w-4 mr-1"})," Public view"]})})]})]}),e.jsx("div",{ref:D,"data-print-root":!0,className:"fsbo-tile p-8 max-w-4xl mx-auto space-y-6 bg-white text-foreground",children:ie?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:(nt=j.property)==null?void 0:nt.property_address})]}),e.jsx("p",{className:"text-lg leading-relaxed",children:ie.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:ie.checklist.map(($e,Ge)=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"text-primary",children:"✓"}),e.jsx("span",{children:$e})]},Ge))})]}),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:ie.pitfalls.map(($e,Ge)=>e.jsxs("div",{className:"bg-muted/30 p-4 rounded-lg",children:[e.jsx("div",{className:"font-semibold",children:$e.title}),e.jsx("div",{className:"text-sm text-muted-foreground",children:$e.body})]},Ge))})]}),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:ie.seller_advantages.map(($e,Ge)=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"text-primary",children:"+"}),e.jsx("span",{children:$e})]},Ge))})]}),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:ie.agent_value.map(($e,Ge)=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"text-primary",children:"→"}),e.jsx("span",{children:$e})]},Ge))})]})]}),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:ie.cta}),e.jsx("p",{className:"text-muted-foreground mb-4",children:ie.cta_body}),e.jsx(B,{size:"lg",children:"Request a Free Consultation"})]})]}):e.jsx("div",{className:"text-muted-foreground",children:"Guide content not generated yet."})})]}),e.jsx(Gt,{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"}),le?e.jsxs("div",{className:"space-y-4",children:[e.jsx(kue,{label:"Phone",text:le.phone}),e.jsx(kue,{label:"Voicemail",text:le.voicemail}),e.jsx(kue,{label:"Video",text:le.video}),e.jsx(kue,{label:"Door knock",text:le.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:le.objections.map(($e,Ge)=>e.jsxs("div",{className:"bg-muted/40 p-3 rounded-lg",children:[e.jsxs("div",{className:"text-sm font-medium text-destructive",children:['"',$e.objection,'"']}),e.jsx("div",{className:"text-sm mt-1",children:$e.response})]},Ge))})]})]}):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:[te.map(($e,Ge)=>e.jsxs("div",{className:"bg-muted/40 p-3 rounded-lg",children:[e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Day ",Ge*4+1]}),e.jsx("div",{className:"font-medium",children:$e.subject}),e.jsx("div",{className:"text-sm text-muted-foreground truncate",children:$e.preview})]},$e.key)),!te.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:[ae.map(($e,Ge)=>e.jsxs("div",{className:"bg-muted/40 p-3 rounded-lg",children:[e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Step ",Ge+1]}),e.jsx("div",{className:"text-sm",children:$e.body})]},$e.key)),!ae.length&&e.jsx("div",{className:"text-muted-foreground",children:"No SMS messages generated yet."})]})]})]})]})}),e.jsx(Gt,{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($e=>$e.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($e=>$e.campaign_id===s).map($e=>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:[$e.first_name," ",$e.last_name]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[$e.email," · ",$e.phone]}),e.jsxs("div",{className:"text-sm text-muted-foreground mt-1",children:["Timeline: ",$e.timeline??"—"," · Motivation: ",$e.motivation??"—"]}),e.jsx("div",{className:"text-sm mt-1",children:$e.message})]}),e.jsxs("div",{className:"text-right",children:[e.jsxs(Oe,{className:At($e.temperature==="hot"?"bg-red-500/15 text-red-600":"bg-amber-500/15 text-amber-600"),children:[$e.temperature," · ",$e.lead_score]}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:Hs(new Date($e.created_at),"MMM d")})]})]},$e.id))})]})})]})]})})}function kue({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(B,{size:"sm",variant:"ghost",className:"h-6 px-2",onClick:()=>{navigator.clipboard.writeText(t),se.success("Copied")},children:e.jsx(Ia,{className:"h-3.5 w-3.5"})})]}),e.jsx("div",{className:"text-sm text-muted-foreground",children:t})]})}const oyr="https://relzejiswnotikjgvjhz.supabase.co/functions/v1/fsbo-public",FAt="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM";async function IF(s){try{const t=await fetch(oyr,{method:"POST",headers:{"Content-Type":"application/json",apikey:FAt,Authorization:`Bearer ${FAt}`},body:JSON.stringify(s)});return t.ok?await t.json():null}catch{return null}}function lyr(){const{slug:s}=Li(),[t,n]=_.useState(null),[r,a]=_.useState(!0),[i,l]=_.useState(!1),[o,c]=_.useState(!1),[d,u]=_.useState({first_name:"",last_name:"",email:"",phone:"",timeline:"",motivation:"",preferred_contact:"email",message:""});_.useEffect(()=>{s&&(a(!0),IF({action:"get",slug:s}).then(j=>{j!=null&&j.campaign&&n(j),a(!1)}))},[s]),_.useEffect(()=>{if(!s)return;const j=sessionStorage.getItem(`fsbo-${s}`)||crypto.randomUUID();sessionStorage.setItem(`fsbo-${s}`,j),IF({action:"track",slug:s,event_type:"page_view",session_id:j})},[s]);const h=async j=>{if(j.preventDefault(),!s)return;c(!0);const S=sessionStorage.getItem(`fsbo-${s}`)||void 0,C=await IF({action:"submit",slug:s,...d,session_id:S,wants_guide:!0});c(!1),C?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(Ct,{className:"h-6 w-6 animate-spin text-primary"})});if(!t)return e.jsx("div",{className:"min-h-screen grid place-items-center text-muted-foreground",children:"Landing page not found."});const m=t.campaign,p=m.content??{},f=p.landing,y=t.agent,v=m.property??{},g=p.landing_config??{media_mode:"photo",show_property_snapshot:!0,show_discover:!0,show_testimonial:!0},b=g.video_url?Y0r(g.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:[(f==null?void 0:f.headline)||"Selling On Your Own?"," — ",(y==null?void 0:y.name)||"LevelUp"]}),e.jsx("meta",{name:"description",content:(f==null?void 0:f.subheadline)||"Free FSBO seller guide from a local agent."})]}),e.jsx("div",{className:"bg-gradient-to-br from-[#4a6741] to-[#2d5a3d] text-white",children:e.jsx("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 py-12 lg:py-20",children:e.jsxs("div",{className:"grid lg:grid-cols-2 gap-10 items-center",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm uppercase tracking-wider text-[#f4d06f] font-semibold",children:(f==null?void 0:f.eyebrow)||"Free FSBO Seller Guide"}),e.jsx("h1",{className:"text-3xl sm:text-5xl font-bold mt-4 leading-tight",children:(f==null?void 0:f.headline)||"Selling On Your Own? Here's What You Should Know."}),e.jsx("p",{className:"text-lg text-white/80 mt-4",children:(f==null?void 0:f.subheadline)||`A complimentary guide for ${v.property_address||"your home"} created by a local agent.`}),e.jsxs("div",{className:"mt-6 flex flex-wrap gap-3",children:[e.jsxs("a",{href:"#form",className:"inline-flex items-center gap-2 bg-[#f4d06f] text-[#0f4c5c] px-5 py-3 rounded-lg font-semibold hover:bg-[#f4d06f]/90",children:[(f==null?void 0:f.cta)||"Send Me the Free Guide"," ",e.jsx(La,{className:"h-4 w-4"})]}),e.jsx("a",{href:`/fsbo/${s}/guide`,className:"inline-flex items-center gap-2 bg-white/10 text-white px-5 py-3 rounded-lg font-semibold hover:bg-white/20",children:"Read the guide"})]})]}),e.jsx("div",{className:"rounded-2xl overflow-hidden shadow-2xl bg-white/10 ring-1 ring-white/15",children:(b==null?void 0:b.kind)==="iframe"?e.jsx("iframe",{src:b.src,className:"w-full aspect-video block border-0",scrolling:"no",allowFullScreen:!0,title:"Property media"}):(b==null?void 0:b.kind)==="file"?e.jsx("video",{src:b.src,className:"w-full aspect-video object-cover block",controls:!0}):typeof v.photo_url=="string"&&v.photo_url?e.jsx("img",{src:v.photo_url,alt:String(v.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(Jr,{className:"h-12 w-12"})})})]})})}),g.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(Xa,{className:"h-4 w-4 text-[#4a6741]"})," ",e.jsx("span",{className:"font-semibold",children:v.property_address})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Jr,{className:"h-4 w-4 text-[#4a6741]"})," ",e.jsx("span",{className:"capitalize",children:String(v.property_type||"").replace("_"," ")})]}),v.estimated_value?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("span",{className:"font-semibold",children:["Est. $",Number(v.estimated_value).toLocaleString()]})}):null]})}),e.jsx("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 py-16",children:e.jsxs("div",{className:"grid lg:grid-cols-5 gap-12",children:[e.jsxs("div",{className:"lg:col-span-3 space-y-6",children:[e.jsx("div",{className:"text-lg leading-relaxed text-stone-700",children:f==null?void 0:f.intro}),g.show_discover!==!1&&(f==null?void 0:f.discover)&&e.jsx("div",{className:"grid sm:grid-cols-2 gap-4 mt-6",children:f.discover.map((j,S)=>e.jsxs("div",{className:"bg-white p-5 rounded-xl shadow-sm border border-stone-100",children:[e.jsx("div",{className:"font-semibold text-[#4a6741] mb-1",children:j.title}),e.jsx("div",{className:"text-sm text-stone-600",children:j.body})]},S))}),g.show_testimonial!==!1&&(f==null?void 0:f.testimonial)&&e.jsxs("div",{className:"mt-8 bg-[#4a6741]/10 p-6 rounded-2xl border-l-4 border-[#4a6741]",children:[e.jsx("div",{className:"flex gap-1 text-[#f4d06f] mb-2",children:[...Array(5)].map((j,S)=>e.jsx(Da,{className:"h-4 w-4 fill-current"},S))}),e.jsxs("div",{className:"italic text-lg text-stone-800",children:['"',f.testimonial.quote,'"']}),e.jsxs("div",{className:"font-semibold text-sm mt-3",children:["— ",f.testimonial.author]})]})]}),e.jsx("div",{id:"form",className:"lg:col-span-2",children:e.jsx("div",{className:"bg-white rounded-2xl shadow-lg p-6 sm:p-8 sticky top-6",children:i?e.jsxs("div",{className:"text-center py-8",children:[e.jsx("div",{className:"mx-auto h-14 w-14 rounded-full bg-green-100 grid place-items-center mb-4",children:e.jsx(Er,{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. ",(y==null?void 0:y.name)||"The agent"," will follow up soon."]}),e.jsx("a",{href:`/fsbo/${s}/guide`,className:"inline-block mt-4 text-[#4a6741] font-semibold underline",children:"Read it now"})]}):e.jsxs("form",{onSubmit:h,className:"space-y-4",children:[e.jsx("h3",{className:"text-xl font-bold",children:(f==null?void 0:f.form_subhead)||"Get your free guide"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(J,{className:"text-xs",children:"First"}),e.jsx(xe,{value:d.first_name,onChange:j=>u(S=>({...S,first_name:j.target.value})),required:!0})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(J,{className:"text-xs",children:"Last"}),e.jsx(xe,{value:d.last_name,onChange:j=>u(S=>({...S,last_name:j.target.value})),required:!0})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(J,{className:"text-xs",children:"Email"}),e.jsx(xe,{type:"email",value:d.email,onChange:j=>u(S=>({...S,email:j.target.value})),required:!0})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(J,{className:"text-xs",children:"Phone"}),e.jsx(xe,{type:"tel",value:d.phone,onChange:j=>u(S=>({...S,phone:j.target.value}))})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(J,{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:j=>u(S=>({...S,timeline:j.target.value})),children:[e.jsx("option",{value:"",children:"Select…"}),Z0r.map(j=>e.jsx("option",{value:j.value,children:j.label},j.value))]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(J,{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:j=>u(S=>({...S,preferred_contact:j.target.value})),children:Q0r.map(j=>e.jsx("option",{value:j.value,children:j.label},j.value))})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(J,{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:j=>u(S=>({...S,motivation:j.target.value})),children:[e.jsx("option",{value:"",children:"Select…"}),X0r.map(j=>e.jsx("option",{value:j,children:j},j))]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(J,{className:"text-xs",children:"Message (optional)"}),e.jsx(Ms,{rows:3,value:d.message,onChange:j=>u(S=>({...S,message:j.target.value}))})]}),e.jsxs(B,{type:"submit",className:"w-full",size:"lg",disabled:o,children:[o?e.jsx(Ct,{className:"h-4 w-4 animate-spin mr-2"}):null,(f==null?void 0:f.cta)||"Send Me the Free Guide"]}),e.jsxs("p",{className:"text-xs text-stone-500 text-center",children:["No spam. Unsubscribe anytime. Your info helps ",(y==null?void 0:y.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:[y!=null&&y.avatar_url?e.jsx("img",{src:y.avatar_url,alt:y.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:y==null?void 0:y.name}),e.jsxs("div",{className:"text-stone-600",children:[y==null?void 0:y.title,y!=null&&y.title&&(y!=null&&y.brokerage)?" · ":"",y==null?void 0:y.brokerage]}),e.jsxs("div",{className:"flex flex-wrap justify-center sm:justify-start gap-2 mt-3",children:[y!=null&&y.phone?e.jsx(B,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:`tel:${y.phone}`,children:[e.jsx(_a,{className:"h-4 w-4 mr-1"})," Call"]})}):null,y!=null&&y.email?e.jsx(B,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:`mailto:${y.email}`,children:[e.jsx(ln,{className:"h-4 w-4 mr-1"})," Email"]})}):null,y!=null&&y.website_url?e.jsx(B,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:y.website_url,target:"_blank",rel:"noreferrer",children:[e.jsx(Hi,{className:"h-4 w-4 mr-1"})," Website"]})}):null]})]})]})})})]})}function cyr(){const{slug:s}=Li(),[t,n]=_.useState(null),[r,a]=_.useState(!0),[i,l]=_.useState({first_name:"",last_name:"",email:"",phone:"",message:""}),[o,c]=_.useState(!1),[d,u]=_.useState(!1);_.useEffect(()=>{s&&(a(!0),IF({action:"get",slug:s}).then(g=>{g!=null&&g.campaign&&n(g),a(!1)}))},[s]),_.useEffect(()=>{s&&IF({action:"track",slug:s,event_type:"guide_view"})},[s]);const h=async g=>{if(g.preventDefault(),!s||o)return;c(!0);const b=await IF({action:"submit",slug:s,...i,message:`Requested a free consultation from the guide page.${i.message?` — ${i.message}`:""}`,preferred_contact:"either",wants_guide:!1});c(!1),b?(u(!0),IF({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(Ct,{className:"h-6 w-6 animate-spin text-primary"})});if(!t)return e.jsx("div",{className:"min-h-screen grid place-items-center text-muted-foreground",children:"Guide not found."});const m=t.campaign,f=(m.content??{}).guide,y=t.agent,v=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 — ",(v==null?void 0:v.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(ir,{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:v==null?void 0:v.property_address})]}),f?e.jsxs("div",{className:"space-y-10 mt-8",children:[e.jsx("p",{className:"text-lg leading-relaxed text-stone-700",children:f.intro}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold mb-4",children:"FSBO Reality Checklist"}),e.jsx("ul",{className:"space-y-3",children:f.checklist.map((g,b)=>e.jsxs("li",{className:"flex items-start gap-3 p-3 bg-stone-50 rounded-lg",children:[e.jsx("span",{className:"text-[#4a6741] font-bold text-lg",children:"✓"}),e.jsx("span",{className:"text-stone-700",children:g})]},b))})]}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold mb-4",children:"Common Pitfalls"}),e.jsx("div",{className:"grid gap-4 sm:grid-cols-2",children:f.pitfalls.map((g,b)=>e.jsxs("div",{className:"bg-stone-50 p-5 rounded-xl",children:[e.jsx("div",{className:"font-semibold text-stone-900 mb-1",children:g.title}),e.jsx("div",{className:"text-sm text-stone-600",children:g.body})]},b))})]}),e.jsxs("div",{className:"grid gap-8 sm:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold mb-4",children:"Your Advantages"}),e.jsx("ul",{className:"space-y-3",children:f.seller_advantages.map((g,b)=>e.jsxs("li",{className:"flex items-start gap-3",children:[e.jsx("span",{className:"text-[#4a6741] font-bold",children:"+"}),e.jsx("span",{className:"text-stone-700",children:g})]},b))})]}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold mb-4",children:"What an Agent Brings"}),e.jsx("ul",{className:"space-y-3",children:f.agent_value.map((g,b)=>e.jsxs("li",{className:"flex items-start gap-3",children:[e.jsx("span",{className:"text-[#4a6741] font-bold",children:"→"}),e.jsx("span",{className:"text-stone-700",children:g})]},b))})]})]}),e.jsxs("div",{id:"consult",className:"bg-[#4a6741]/10 p-8 rounded-2xl",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("h3",{className:"text-2xl font-bold mb-3 text-stone-900",children:f.cta}),e.jsx("p",{className:"text-stone-600 mb-6 max-w-lg mx-auto",children:f.cta_body})]}),d?e.jsxs("div",{className:"text-center py-6",children:[e.jsx("div",{className:"mx-auto h-14 w-14 rounded-full bg-green-100 grid place-items-center mb-3",children:e.jsx(Er,{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:[(y==null?void 0:y.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(J,{className:"text-xs",children:"First"}),e.jsx(xe,{value:i.first_name,onChange:g=>l(b=>({...b,first_name:g.target.value})),required:!0})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(J,{className:"text-xs",children:"Last"}),e.jsx(xe,{value:i.last_name,onChange:g=>l(b=>({...b,last_name:g.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(J,{className:"text-xs",children:"Email"}),e.jsx(xe,{type:"email",value:i.email,onChange:g=>l(b=>({...b,email:g.target.value})),required:!0})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(J,{className:"text-xs",children:"Phone"}),e.jsx(xe,{type:"tel",value:i.phone,onChange:g=>l(b=>({...b,phone:g.target.value}))})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(J,{className:"text-xs",children:"Best time / anything I should know (optional)"}),e.jsx(Ms,{rows:3,value:i.message,onChange:g=>l(b=>({...b,message:g.target.value}))})]}),e.jsxs(B,{type:"submit",size:"lg",className:"w-full",disabled:o,children:[o?e.jsx(Ct,{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:[y!=null&&y.avatar_url?e.jsx("img",{src:y.avatar_url,alt:y.name??"",className:"h-16 w-16 rounded-full object-cover"}):null,e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold text-lg",children:y==null?void 0:y.name}),e.jsxs("div",{className:"text-sm text-stone-600",children:[y==null?void 0:y.title,y!=null&&y.title&&(y!=null&&y.brokerage)?" · ":"",y==null?void 0:y.brokerage]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[y!=null&&y.phone?e.jsx(B,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:`tel:${y.phone}`,children:[e.jsx(_a,{className:"h-4 w-4 mr-1"})," Call"]})}):null,y!=null&&y.email?e.jsx(B,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:`mailto:${y.email}`,children:[e.jsx(ln,{className:"h-4 w-4 mr-1"})," Email"]})}):null]})]})]})})]})}function dyr(){const s=als(),t=ils(),n=eot(),r=tot(),a=Bt(),[i,l]=_.useState(""),o=mt({mutationFn:async()=>{const{data:h,error:m}=await q.from("profiles").select("id");if(m)throw m;const p=new Date().toISOString(),f=(h??[]).map(v=>({user_id:v.id,feature_key:"fsbo_breakthrough",enabled:!0,tier:"beta",expires_at:null,created_at:p,updated_at:p})),{error:y}=await q.from("feature_entitlements").upsert(f,{onConflict:"user_id,feature_key"});if(y)throw y},onSuccess:()=>{se.success("Enabled for all members"),a.invalidateQueries({queryKey:["fsbo-breakthrough-access"]})},onError:h=>se.error(h.message)}),c=_.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=_.useMemo(()=>{const h=[];for(let m=13;m>=0;m--){const p=new Date(Date.now()-m*864e5),f=p.toISOString().slice(0,10);h.push({day:Hs(p,"MMM d"),visits:(r.data??[]).filter(y=>y.event_type==="page_view"&&y.created_at.startsWith(f)).length,scans:(r.data??[]).filter(y=>y.event_type==="qr_scan"&&y.created_at.startsWith(f)).length,leads:(n.data??[]).filter(y=>y.created_at.startsWith(f)).length})}return h},[r.data,n.data]),u=(s.data??[]).filter(h=>{var m;return`${h.name} ${((m=h.property)==null?void 0:m.property_address)??""}`.toLowerCase().includes(i.trim().toLowerCase())});return s.isLoading||t.isLoading||n.isLoading||r.isLoading?e.jsx(zs,{title:"By-Owner Breakthrough Admin",children:e.jsx("div",{className:"grid place-items-center py-24",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin"})})}):e.jsx(zs,{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(B,{onClick:()=>o.mutate(),disabled:o.isPending,children:[o.isPending?e.jsx(Ct,{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(OT,{label:"Properties",value:c.properties,icon:Jr}),e.jsx(OT,{label:"Campaigns",value:c.campaigns,icon:ln}),e.jsx(OT,{label:"Page visits",value:c.visits,icon:sl}),e.jsx(OT,{label:"QR scans",value:c.qr,icon:Hf}),e.jsx(OT,{label:"Guide views",value:c.guideViews,icon:Fr}),e.jsx(OT,{label:"Leads",value:c.leads,icon:In}),e.jsx(OT,{label:"Appointments",value:c.appointments,icon:In}),e.jsx(OT,{label:"Letters",value:c.letters,icon:ln})]}),e.jsxs("div",{className:"fsbo-tile p-5 mb-6",children:[e.jsx("div",{className:"fsbo-eyebrow text-muted-foreground",children:"Last 14 days"}),e.jsx("div",{className:"text-lg font-semibold mt-1",children:"Network-wide engagement"}),e.jsx("div",{className:"h-64 mt-4",children:e.jsx(jb,{width:"100%",height:"100%",children:e.jsxs(Jst,{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(kE,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",vertical:!1}),e.jsx(Mv,{dataKey:"day",tick:{fontSize:11},stroke:"hsl(var(--muted-foreground))"}),e.jsx(Pv,{allowDecimals:!1,tick:{fontSize:11},stroke:"hsl(var(--muted-foreground))",width:28}),e.jsx(Mf,{contentStyle:{borderRadius:12,border:"1px solid hsl(var(--border))"}}),e.jsx(U_,{type:"monotone",dataKey:"visits",stroke:"hsl(var(--primary))",fill:"url(#fsboAdminVisits)",strokeWidth:2}),e.jsx(U_,{type:"monotone",dataKey:"scans",stackId:"1",stroke:"hsl(var(--accent))",fill:"url(#fsboAdminLeads)",strokeWidth:2}),e.jsx(U_,{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(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{className:"pl-9",placeholder:"Search campaigns…",value:i,onChange:h=>l(h.target.value)})]})]}),e.jsxs("div",{className:"space-y-3",children:[u.map(h=>{var f,y,v,g,b,j;const m=(n.data??[]).filter(S=>S.campaign_id===h.id).length,p=(r.data??[]).filter(S=>S.campaign_id===h.id&&S.event_type==="page_view").length;return e.jsxs("a",{href:`/apps/fsbo-breakthrough/campaigns/${h.id}`,className:"flex items-center justify-between p-4 rounded-xl bg-muted/40 hover:bg-muted/60 transition-colors",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold",children:((f=h.property)==null?void 0:f.property_address)??h.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[((y=h.property)==null?void 0:y.seller_name)||"Homeowner"," · ",(v=h.property)==null?void 0:v.city,(g=h.property)!=null&&g.city&&((b=h.property)!=null&&b.state)?", ":"",(j=h.property)==null?void 0:j.state]})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs(Oe,{variant:"secondary",children:[e.jsx(sl,{className:"h-3 w-3 mr-1"}),p]}),e.jsxs(Oe,{variant:"secondary",children:[e.jsx(In,{className:"h-3 w-3 mr-1"}),m]}),e.jsx(La,{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 OT({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 QZ=q;function uyr(){const{user:s}=hs(),t=Bt(),n=["attract-landing-page",s==null?void 0:s.id],{data:r,isLoading:a}=at({queryKey:n,enabled:!!s,queryFn:async()=>{const{data:c,error:d}=await QZ.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}=at({queryKey:["attract-landing-analytics",r==null?void 0:r.id],enabled:!!(r!=null&&r.id),queryFn:async()=>{const{data:c,error:d}=await QZ.from("attract_landing_events").select("event_type, section_key, created_at").eq("page_id",r.id).order("created_at",{ascending:!1}).limit(1e3);if(d)throw d;const u=c||[],h=u.filter(f=>f.event_type==="view").length,m=u.filter(f=>f.event_type==="cta_click").length,p=u.filter(f=>f.event_type==="calculator_run").length;return{views:h,ctas:m,calcs:p,conversion:h?Math.round(m/h*100):0}}}),l=mt({mutationFn:async c=>{const d=Eos(c||"my-attraction-page")||"attraction-page";let u=d;for(let f=0;f<5;f++){const{data:y}=await QZ.from("attract_landing_pages").select("id").eq("slug",u).maybeSingle();if(!y)break;u=`${d}-${Math.random().toString(36).slice(2,6)}`}const h=kxr(c||"Your Name"),{data:m,error:p}=await QZ.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}),se.success("Attraction page created")},onError:c=>se.error(c.message||"Could not create the page")}),o=mt({mutationFn:async c=>{const{error:d}=await QZ.from("attract_landing_pages").update(c).eq("id",r.id);if(d)throw d},onSuccess:()=>{t.invalidateQueries({queryKey:n}),se.success("Saved")},onError:c=>{var d;return se.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 hyr(){var v,g,b,j,S,C,E,P,M,I,D,O;const{user:s}=hs(),{page:t,isLoading:n,analytics:r,createPage:a,savePage:i}=uyr(),[l,o]=_.useState(null),[c,d]=_.useState(!1);_.useEffect(()=>{t&&o({...t})},[t]);const u=_.useMemo(()=>l!=null&&l.slug?`${window.location.origin}/join/${l.slug}`:"",[l==null?void 0:l.slug]),h=V=>o(G=>({...G,...V})),m=(V,G)=>h({[V]:G}),p=(V,G,$)=>m(V,l[V].map((H,Y)=>Y===G?{...H,...$}:H)),f=()=>{const{id:V,user_id:G,created_at:$,updated_at:H,...Y}=l;i.mutate({...Y,slug:Eos(Y.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(un,{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(B,{size:"lg",onClick:()=>{var V;return a.mutate(((V=s==null?void 0:s.user_metadata)==null?void 0:V.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(B,{variant:"outline",size:"sm",onClick:()=>d(!1),children:"Back to editor"})]}),e.jsx(Zos,{cfg:l,preview:!0})]});const y={...Aos,...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(B,{variant:"outline",size:"sm",onClick:()=>d(!0),children:[e.jsx(ya,{className:"mr-2 h-4 w-4"})," Preview"]}),l.is_published&&e.jsx(B,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:u,target:"_blank",rel:"noreferrer",children:[e.jsx(wr,{className:"mr-2 h-4 w-4"})," View live"]})}),e.jsxs(B,{size:"sm",onClick:f,disabled:i.isPending,children:[e.jsx(Ho,{className:"mr-2 h-4 w-4"})," ",i.isPending?"Saving…":"Save changes"]})]})]}),e.jsx("div",{className:"mb-6 grid gap-3 sm:grid-cols-4",children:[{label:"Page views",value:(r==null?void 0:r.views)??0},{label:"CTA clicks",value:(r==null?void 0:r.ctas)??0},{label:"Calculator runs",value:(r==null?void 0:r.calcs)??0},{label:"Click rate",value:`${(r==null?void 0:r.conversion)??0}%`}].map(V=>e.jsx(ve,{children:e.jsxs(Me,{className:"p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-wider text-muted-foreground",children:V.label}),e.jsx("div",{className:"mt-1 text-2xl font-bold",children:V.value})]})},V.label))}),e.jsxs(Yr,{defaultValue:"content",children:[e.jsxs(Zr,{className:"mb-6 flex-wrap",children:[e.jsx(Ht,{value:"content",children:"Content"}),e.jsx(Ht,{value:"proof",children:"Proof & FAQ"}),e.jsx(Ht,{value:"calculator",children:"Calculator"}),e.jsx(Ht,{value:"sections",children:"Sections"}),e.jsx(Ht,{value:"publish",children:"Publish"})]}),e.jsxs(Gt,{value:"content",className:"space-y-6",children:[e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"Hero"})}),e.jsxs(Me,{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(Vm,{label:"Your name",value:l.agent_name,onChange:V=>h({agent_name:V})}),e.jsx(Vm,{label:"Title / brokerage",value:l.agent_title,onChange:V=>h({agent_title:V})}),e.jsx(Vm,{label:"Eyebrow line",value:l.eyebrow,onChange:V=>h({eyebrow:V}),className:"md:col-span-2"}),e.jsxs("div",{className:"md:col-span-2 space-y-1.5",children:[e.jsx(J,{children:"Headline"}),e.jsx(Ms,{rows:2,value:l.headline||"",onChange:V=>h({headline:V.target.value})})]}),e.jsxs("div",{className:"md:col-span-2 space-y-1.5",children:[e.jsx(J,{children:"Subheadline"}),e.jsx(Ms,{rows:3,value:l.subheadline||"",onChange:V=>h({subheadline:V.target.value})})]}),e.jsx(Vm,{label:"Button text",value:l.cta_label,onChange:V=>h({cta_label:V})}),e.jsx(Vm,{label:"Scheduling link (Calendly etc.)",value:l.calendar_url,onChange:V=>h({calendar_url:V})}),e.jsx(Vm,{label:"Headshot URL",value:l.headshot_url,onChange:V=>h({headshot_url:V})}),e.jsx(Vm,{label:"Hero background image URL",value:l.hero_image_url,onChange:V=>h({hero_image_url:V})}),e.jsx(Vm,{label:"Logo URL",value:l.logo_url,onChange:V=>h({logo_url:V})}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx(Vm,{label:"Primary color",type:"color",value:l.primary_color,onChange:V=>h({primary_color:V})}),e.jsx(Vm,{label:"Accent color",type:"color",value:l.accent_color,onChange:V=>h({accent_color:V})})]}),e.jsx(Vm,{label:"Phone",value:l.phone,onChange:V=>h({phone:V})}),e.jsx(Vm,{label:"Email",value:l.email,onChange:V=>h({email:V})})]})]}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"Credibility strip"})}),e.jsxs(Me,{className:"space-y-3",children:[(l.credibility||[]).map((V,G)=>e.jsxs(JZ,{onRemove:()=>m("credibility",l.credibility.filter(($,H)=>H!==G)),children:[e.jsx(xe,{placeholder:"Value (e.g. $42M)",value:V.value||"",onChange:$=>p("credibility",G,{value:$.target.value})}),e.jsx(xe,{placeholder:"Label (e.g. Closed volume)",value:V.label||"",onChange:$=>p("credibility",G,{label:$.target.value})})]},G)),e.jsx(eX,{onClick:()=>m("credibility",[...l.credibility||[],{value:"",label:""}]),label:"Add stat"})]})]}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"Your story"})}),e.jsxs(Me,{className:"space-y-4",children:[e.jsx(Vm,{label:"Section title",value:l.story_title,onChange:V=>h({story_title:V})}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Story"}),e.jsx(Ms,{rows:6,value:l.story_body||"",onChange:V=>h({story_body:V.target.value})})]}),e.jsx(Vm,{label:"Story video URL (YouTube, Vimeo, Loom, MP4)",value:l.story_video_url,onChange:V=>h({story_video_url:V})})]})]}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"Value stack"})}),e.jsxs(Me,{className:"space-y-4",children:[(l.value_cards||[]).map((V,G)=>e.jsxs(JZ,{vertical:!0,onRemove:()=>m("value_cards",l.value_cards.filter(($,H)=>H!==G)),children:[e.jsx(xe,{placeholder:"Title",value:V.title||"",onChange:$=>p("value_cards",G,{title:$.target.value})}),e.jsx(Ms,{rows:2,placeholder:"Description",value:V.body||"",onChange:$=>p("value_cards",G,{body:$.target.value})}),e.jsx(xe,{placeholder:"Proof point (optional)",value:V.proof||"",onChange:$=>p("value_cards",G,{proof:$.target.value})})]},G)),e.jsx(eX,{onClick:()=>m("value_cards",[...l.value_cards||[],{title:"",body:""}]),label:"Add value card"})]})]}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"What you get from me"})}),e.jsxs(Me,{className:"space-y-4",children:[(l.sponsor_cards||[]).map((V,G)=>e.jsxs(JZ,{vertical:!0,onRemove:()=>m("sponsor_cards",l.sponsor_cards.filter(($,H)=>H!==G)),children:[e.jsx(xe,{placeholder:"Title",value:V.title||"",onChange:$=>p("sponsor_cards",G,{title:$.target.value})}),e.jsx(Ms,{rows:2,placeholder:"Description",value:V.body||"",onChange:$=>p("sponsor_cards",G,{body:$.target.value})})]},G)),e.jsx(eX,{onClick:()=>m("sponsor_cards",[...l.sponsor_cards||[],{title:"",body:""}]),label:"Add commitment"})]})]}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"Free download & upcoming event"})}),e.jsxs(Me,{className:"space-y-4",children:[e.jsx(Vm,{label:"Download title",value:(v=l.lead_magnet)==null?void 0:v.title,onChange:V=>h({lead_magnet:{...l.lead_magnet,title:V}})}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Download description"}),e.jsx(Ms,{rows:2,value:((g=l.lead_magnet)==null?void 0:g.body)||"",onChange:V=>h({lead_magnet:{...l.lead_magnet,body:V.target.value}})})]}),e.jsx(Vm,{label:"File URL",value:(b=l.lead_magnet)==null?void 0:b.file_url,onChange:V=>h({lead_magnet:{...l.lead_magnet,file_url:V}})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsx(Vm,{label:"Event title",value:(j=l.event_block)==null?void 0:j.title,onChange:V=>h({event_block:{...l.event_block,title:V}})}),e.jsx(Vm,{label:"When",value:(S=l.event_block)==null?void 0:S.when,onChange:V=>h({event_block:{...l.event_block,when:V}})}),e.jsx(Vm,{label:"Registration link",value:(C=l.event_block)==null?void 0:C.url,onChange:V=>h({event_block:{...l.event_block,url:V}})})]})]})]})]}),e.jsxs(Gt,{value:"proof",className:"space-y-6",children:[e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"Testimonials"})}),e.jsxs(Me,{className:"space-y-4",children:[(l.testimonials||[]).map((V,G)=>e.jsxs(JZ,{vertical:!0,onRemove:()=>m("testimonials",l.testimonials.filter(($,H)=>H!==G)),children:[e.jsx(Ms,{rows:3,placeholder:"Quote",value:V.quote||"",onChange:$=>p("testimonials",G,{quote:$.target.value})}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsx(xe,{placeholder:"Name",value:V.name||"",onChange:$=>p("testimonials",G,{name:$.target.value})}),e.jsx(xe,{placeholder:"Role / market",value:V.role||"",onChange:$=>p("testimonials",G,{role:$.target.value})}),e.jsx(xe,{placeholder:"Photo URL",value:V.photo_url||"",onChange:$=>p("testimonials",G,{photo_url:$.target.value})})]})]},G)),e.jsx(eX,{onClick:()=>m("testimonials",[...l.testimonials||[],{quote:"",name:""}]),label:"Add testimonial"})]})]}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"Objection-handling FAQ"})}),e.jsxs(Me,{className:"space-y-4",children:[(l.faqs||[]).map((V,G)=>e.jsxs(JZ,{vertical:!0,onRemove:()=>m("faqs",l.faqs.filter(($,H)=>H!==G)),children:[e.jsx(xe,{placeholder:"Question",value:V.q||"",onChange:$=>p("faqs",G,{q:$.target.value})}),e.jsx(Ms,{rows:3,placeholder:"Answer",value:V.a||"",onChange:$=>p("faqs",G,{a:$.target.value})})]},G)),e.jsx(eX,{onClick:()=>m("faqs",[...l.faqs||[],{q:"",a:""}]),label:"Add question"})]})]}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"Income disclaimer"})}),e.jsx(Me,{children:e.jsx(Ms,{rows:4,value:l.disclaimer||"",onChange:V=>h({disclaimer:V.target.value})})})]})]}),e.jsx(Gt,{value:"calculator",children:e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"Earnings calculator"})}),e.jsxs(Me,{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(Vm,{label:"Section title",value:(E=l.calculator)==null?void 0:E.title,onChange:V=>h({calculator:{...l.calculator,title:V}}),className:"md:col-span-2"}),e.jsx(Vm,{label:"Cap ($)",type:"number",value:(P=l.calculator)==null?void 0:P.cap,onChange:V=>h({calculator:{...l.calculator,cap:Number(V)}})}),e.jsx(Vm,{label:"Your split (%)",type:"number",value:(M=l.calculator)==null?void 0:M.split,onChange:V=>h({calculator:{...l.calculator,split:Number(V)}})}),e.jsx(Vm,{label:"Per-transaction fee ($)",type:"number",value:(I=l.calculator)==null?void 0:I.transaction_fee,onChange:V=>h({calculator:{...l.calculator,transaction_fee:Number(V)}})}),e.jsx(Vm,{label:"Typical competitor split (%)",type:"number",value:(D=l.calculator)==null?void 0:D.current_split,onChange:V=>h({calculator:{...l.calculator,current_split:Number(V)}})}),e.jsx(Vm,{label:"Typical competitor monthly fees ($)",type:"number",value:(O=l.calculator)==null?void 0:O.current_monthly_fees,onChange:V=>h({calculator:{...l.calculator,current_monthly_fees:Number(V)}})}),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(Gt,{value:"sections",children:e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"Show or hide sections"})}),e.jsx(Me,{className:"divide-y",children:Object.keys(dAt).map(V=>e.jsxs("div",{className:"flex items-center justify-between py-3",children:[e.jsx("span",{className:"text-sm",children:dAt[V]}),e.jsx(fn,{checked:y[V]!==!1,onCheckedChange:G=>h({sections:{...y,[V]:G}})})]},V))})]})}),e.jsxs(Gt,{value:"publish",className:"space-y-6",children:[e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"Publishing"})}),e.jsxs(Me,{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(fn,{checked:!!l.is_published,onCheckedChange:V=>h({is_published:V})})]}),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(fn,{checked:!!l.noindex,onCheckedChange:V=>h({noindex:V})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Web address"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{value:l.slug||"",onChange:V=>h({slug:V.target.value})}),e.jsx(B,{variant:"outline",onClick:()=>{navigator.clipboard.writeText(u),se.success("Link copied")},children:e.jsx(Ia,{className:"h-4 w-4"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:u})]}),e.jsx(Vm,{label:"Search title",value:l.seo_title,onChange:V=>h({seo_title:V})}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Search description"}),e.jsx(Ms,{rows:2,value:l.seo_description||"",onChange:V=>h({seo_description:V.target.value})})]})]})]}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsxs(St,{className:"flex items-center gap-2 text-base",children:[e.jsx(bl,{className:"h-4 w-4"})," Where leads go"]})}),e.jsx(Me,{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(B,{onClick:f,disabled:i.isPending,children:[e.jsx(Ho,{className:"mr-2 h-4 w-4"})," ",i.isPending?"Saving…":"Save changes"]})})]})}function Vm({label:s,value:t,onChange:n,type:r="text",className:a}){return e.jsxs("div",{className:`space-y-1.5 ${a||""}`,children:[e.jsx(J,{children:s}),e.jsx(xe,{type:r,value:t??"",onChange:i=>n(i.target.value)})]})}function JZ({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(B,{variant:"ghost",size:"icon",onClick:t,className:"text-muted-foreground hover:text-destructive",children:e.jsx(Sn,{className:"h-4 w-4"})})]})}function eX({onClick:s,label:t}){return e.jsxs(B,{variant:"outline",size:"sm",onClick:s,children:[e.jsx(rn,{className:"mr-2 h-4 w-4"})," ",t]})}function myr(s){const{user:t}=hs(),n=Bt(),r=at({queryKey:["admin-attract-list",s,t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{let o=q.from("profiles").select("id, email, full_name").order("full_name",{ascending:!0}).limit(100);if(s.trim()){const m=`%${s.trim()}%`;o=o.or(`email.ilike.${m},full_name.ilike.${m}`)}const{data:c,error:d}=await o;if(d)throw d;const u=(c??[]).map(m=>m.id);let h={};if(u.length){const{data:m,error:p}=await q.from("feature_entitlements").select("user_id, enabled, tier, enabled_at, expires_at, notes, enabled_by").eq("feature_key","levelup_attract").in("user_id",u);if(p)throw p;(m??[]).forEach(f=>{h[f.user_id]=f})}return(c??[]).map(m=>{var p,f,y,v,g,b;return{user_id:m.id,email:m.email,full_name:m.full_name,enabled:!!((p=h[m.id])!=null&&p.enabled),tier:((f=h[m.id])==null?void 0:f.tier)??null,enabled_at:((y=h[m.id])==null?void 0:y.enabled_at)??null,expires_at:((v=h[m.id])==null?void 0:v.expires_at)??null,notes:((g=h[m.id])==null?void 0:g.notes)??null,enabled_by:((b=h[m.id])==null?void 0:b.enabled_by)??null}})}}),a=at({queryKey:["admin-attract-audit",t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{const{data:o,error:c}=await q.from("feature_entitlement_audit").select("*").eq("feature_key","levelup_attract").order("created_at",{ascending:!1}).limit(50);if(c)throw c;return o??[]}}),i=mt({mutationFn:async({target_user_id:o,tier:c,expires_at:d,notes:u})=>{const h={user_id:o,feature_key:"levelup_attract",enabled:!0,tier:c??"beta",enabled_by:t.id,enabled_at:new Date().toISOString(),expires_at:d??null,notes:u??null},{error:m}=await q.from("feature_entitlements").upsert(h,{onConflict:"user_id,feature_key"});if(m)throw m;await q.from("feature_entitlement_audit").insert({feature_key:"levelup_attract",target_user_id:o,action:"grant",tier:h.tier,expires_at:h.expires_at,notes:h.notes,performed_by:t.id})},onSuccess:()=>{n.invalidateQueries({queryKey:["admin-attract-list"]}),n.invalidateQueries({queryKey:["admin-attract-audit"]}),se.success("Access granted")},onError:o=>se.error(o.message)}),l=mt({mutationFn:async o=>{const{error:c}=await q.from("feature_entitlements").update({enabled:!1}).eq("user_id",o).eq("feature_key","levelup_attract");if(c)throw c;await q.from("feature_entitlement_audit").insert({feature_key:"levelup_attract",target_user_id:o,action:"revoke",performed_by:t.id})},onSuccess:()=>{n.invalidateQueries({queryKey:["admin-attract-list"]}),n.invalidateQueries({queryKey:["admin-attract-audit"]}),se.success("Access revoked")},onError:o=>se.error(o.message)});return{list:r,audit:a,grant:i,revoke:l}}function pyr(){const[s,t]=_.useState(""),{list:n,audit:r,grant:a,revoke:i}=myr(s),[l,o]=_.useState(null),[c,d]=_.useState(null),[u,h]=_.useState("beta"),[m,p]=_.useState(""),[f,y]=_.useState(""),v=b=>{d(b),h(b.tier??"beta"),p(b.expires_at?b.expires_at.slice(0,10):""),y(b.notes??"")},g=async()=>{c&&(await a.mutateAsync({target_user_id:c.user_id,tier:u,expires_at:m?new Date(m).toISOString():null,notes:f||void 0}),d(null))};return e.jsxs("div",{className:"p-6",children:[e.jsx(Wh,{title:"LevelUp Attract — Access Management",description:"Grant or revoke access to LevelUp Attract for individual members. Every change is audited."}),e.jsx(ve,{className:"p-4 rounded-2xl mb-4",children:e.jsxs("div",{className:"relative max-w-md",children:[e.jsx(Lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(xe,{value:s,onChange:b=>t(b.target.value),placeholder:"Search by name or email...",className:"pl-9"})]})}),e.jsxs(ve,{className:"rounded-2xl overflow-hidden mb-8",children:[e.jsxs("div",{className:"grid grid-cols-[1fr_auto_auto_auto] gap-3 px-5 py-3 text-[11px] uppercase tracking-widest text-slate-500 font-semibold border-b",children:[e.jsx("div",{children:"Member"}),e.jsx("div",{children:"Access"}),e.jsx("div",{children:"Enabled"}),e.jsx("div",{children:"Actions"})]}),n.isLoading&&e.jsx("div",{className:"p-6 text-center text-slate-500 text-sm",children:"Loading members…"}),!n.isLoading&&(n.data??[]).length===0&&e.jsx("div",{className:"p-6 text-center text-slate-500 text-sm",children:"No members match."}),(n.data??[]).map(b=>e.jsxs("div",{className:"grid grid-cols-[1fr_auto_auto_auto] gap-3 px-5 py-3 items-center border-b last:border-0 hover:bg-slate-50",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[13.5px] font-medium text-slate-900 truncate",children:b.full_name||b.email||b.user_id}),e.jsx("div",{className:"text-[11.5px] text-slate-500 truncate",children:b.email})]}),e.jsx("div",{children:b.enabled?e.jsxs(Oe,{className:"bg-emerald-100 text-emerald-800 border-0 gap-1",children:[e.jsx(un,{className:"h-3 w-3"})," ",b.tier??"enabled"]}):e.jsx(Oe,{variant:"outline",className:"text-slate-500",children:"Not enabled"})}),e.jsx("div",{className:"text-[11.5px] text-slate-500 whitespace-nowrap",children:b.enabled_at?Hs(new Date(b.enabled_at),"MMM d, yyyy"):"—"}),e.jsx("div",{className:"flex gap-1.5",children:b.enabled?e.jsxs(e.Fragment,{children:[e.jsx(B,{size:"sm",variant:"outline",onClick:()=>v(b),children:"Edit"}),e.jsx(B,{size:"sm",variant:"ghost",className:"text-rose-600",onClick:()=>o({user:b,action:"revoke"}),children:"Revoke"})]}):e.jsxs(B,{size:"sm",className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>v(b),children:[e.jsx(Dm,{className:"h-3.5 w-3.5 mr-1"})," Enable"]})})]},b.user_id))]}),e.jsxs(ve,{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(R_,{className:"h-3.5 w-3.5"})," Recent audit history"]}),r.isLoading&&e.jsx("div",{className:"text-slate-500 text-sm",children:"Loading…"}),(r.data??[]).length===0&&!r.isLoading&&e.jsx("div",{className:"text-slate-500 text-sm",children:"No changes yet."}),e.jsx("div",{className:"space-y-1.5",children:(r.data??[]).map(b=>e.jsxs("div",{className:"text-[12.5px] text-slate-700 flex items-center gap-2",children:[e.jsx(Oe,{variant:"outline",className:"text-[10.5px] capitalize",children:b.action}),e.jsx("span",{className:"font-mono text-[11px] text-slate-500",children:b.target_user_id.slice(0,8)}),b.tier&&e.jsxs("span",{className:"text-slate-500",children:["· ",b.tier]}),b.notes&&e.jsxs("span",{className:"text-slate-500",children:["· ",b.notes]}),e.jsx("span",{className:"text-slate-400 ml-auto",children:Hs(new Date(b.created_at),"MMM d h:mm a")})]},b.id))})]}),e.jsx(Ls,{open:!!c,onOpenChange:b=>!b&&d(null),children:e.jsxs(Ps,{children:[e.jsxs(Os,{children:[e.jsxs(Ds,{children:[c!=null&&c.enabled?"Update":"Enable"," Attract access"]}),e.jsx(_r,{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(J,{children:"Tier"}),e.jsxs(is,{value:u,onValueChange:h,children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"beta",children:"Beta"}),e.jsx(He,{value:"standard",children:"Standard"}),e.jsx(He,{value:"pro",children:"Pro"}),e.jsx(He,{value:"founder",children:"Founder"})]})]})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Expires (optional)"}),e.jsx(xe,{type:"date",value:m,onChange:b=>p(b.target.value)})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Internal notes (optional)"}),e.jsx(Ms,{rows:2,value:f,onChange:b=>y(b.target.value)})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"ghost",onClick:()=>d(null),children:"Cancel"}),e.jsx(B,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:g,disabled:a.isPending,children:c!=null&&c.enabled?"Save changes":"Enable access"})]})]})}),e.jsx(Kl,{open:!!l,onOpenChange:b=>!b&&o(null),children:e.jsxs(Ol,{children:[e.jsxs(zl,{children:[e.jsx(Ul,{children:"Revoke Attract access?"}),e.jsxs(ql,{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($l,{children:"Cancel"}),e.jsxs(Ml,{className:"bg-rose-600 hover:bg-rose-700",onClick:async()=>{l&&await i.mutateAsync(l.user.user_id),o(null)},children:[e.jsx(Rd,{className:"h-4 w-4 mr-1.5"})," Revoke access"]})]})]})})]})}const fyr=({team:s,onSelect:t})=>{const{data:n}=at({queryKey:["team-card-info",s.id],queryFn:async()=>{const{data:r}=await q.from("team_members").select("user_id, role").eq("team_id",s.id),a=(r==null?void 0:r.length)||0,i=r==null?void 0:r.find(o=>o.role==="team_leader");let l=null;if(i){const{data:o}=await q.from("profiles").select("name, avatar_url").eq("id",i.user_id).single();l=o}return{count:a,leaderProfile:l}}});return e.jsxs(ve,{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(St,{className:"text-lg truncate",children:s.name}),s.description&&e.jsx(kn,{className:"mt-1 line-clamp-2",children:s.description})]}),e.jsxs(Oe,{variant:"secondary",className:"ml-2 shrink-0",children:[e.jsx(In,{className:"h-3 w-3 mr-1"}),(n==null?void 0:n.count)??"…"]})]})}),e.jsxs(Me,{className:"space-y-3",children:[(n==null?void 0:n.leaderProfile)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(ja,{className:"h-6 w-6",children:[e.jsx(pi,{src:n.leaderProfile.avatar_url||""}),e.jsx(Na,{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($f,{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(Rm,{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(Oe,{variant:"outline",className:"text-xs py-0",children:"Lead Pond"}),s.shared_assets_enabled&&e.jsx(Oe,{variant:"outline",className:"text-xs py-0",children:"Shared Assets"}),s.shared_videos_enabled&&e.jsx(Oe,{variant:"outline",className:"text-xs py-0",children:"Shared Videos"})]})]})]})},xyr=()=>{const{user:s,isAdmin:t,isBrokerageManager:n,brokerageId:r,managedBrokerages:a,selectedBrokerageId:i}=hs(),l=i||(a.length>0?a[0].id:r),o=t?void 0:l||void 0,{teams:c,isLoading:d,createTeam:u,updateTeam:h,deleteTeam:m,addMember:p,removeMember:f,updateMemberRole:y}=SC(o),[v,g]=_.useState(!1),[b,j]=_.useState(null),{data:S}=at({queryKey:["all-brokerages-for-teams"],queryFn:async()=>{const{data:I,error:D}=await q.from("brokerages").select("id, name").order("name");if(D)throw D;return I||[]},enabled:t}),C=(b==null?void 0:b.brokerage_id)||l||null,{data:E}=at({queryKey:["brokerage-agents-for-teams",t?"all":C],queryFn:async()=>{const I=[];for(let O=0;;O++){let V=q.from("profiles").select("id, name, email, avatar_url, brokerage_id").order("name").range(O*1e3,O*1e3+1e3-1);!t&&C&&(V=V.eq("brokerage_id",C));const{data:G,error:$}=await V;if($)throw $;if(I.push(...G||[]),!G||G.length<1e3)break}return I},enabled:t||!!C}),P=(E||[]).slice().sort((I,D)=>{const O=C&&I.brokerage_id===C?0:1,V=C&&D.brokerage_id===C?0:1;return O!==V?O-V:(I.name||I.email||"").localeCompare(D.name||D.email||"")}),M=async I=>{const D=I.brokerage_id||l||null,O=await u.mutateAsync({name:I.name,brokerage_id:D,description:I.description});if(I.leaderId&&I.leaderId!=="none"&&await p.mutateAsync({team_id:O.id,user_id:I.leaderId,role:"team_leader"}),I.memberIds)for(const V of I.memberIds)await p.mutateAsync({team_id:O.id,user_id:V,role:"team_member"});g(!1)};return!n&&!t?e.jsx(zs,{title:"Teams",description:"Team Management",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(In,{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(zs,{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(B,{onClick:()=>g(!0),children:[e.jsx(rn,{className:"mr-2 h-4 w-4"}),"Create Team"]})]}),e.jsx(AVt,{open:v,onOpenChange:g,onCreateTeam:M,isCreating:u.isPending,brokerageAgents:P,isAdmin:t,allBrokerages:S,activeBrokerageId:l}),d&&e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(I=>e.jsx(ve,{children:e.jsxs(Me,{className:"p-6",children:[e.jsx(cn,{className:"h-5 w-32 mb-3"}),e.jsx(cn,{className:"h-4 w-48 mb-4"}),e.jsx(cn,{className:"h-8 w-full"})]})},I))}),!d&&c.length===0&&!b&&e.jsx(ve,{children:e.jsxs(Me,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(In,{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(B,{onClick:()=>g(!0),children:[e.jsx(rn,{className:"mr-2 h-4 w-4"}),"Create Your First Team"]})]})}),!d&&c.length>0&&!b&&e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:c.map(I=>e.jsx(fyr,{team:I,onSelect:()=>j(I)},I.id))}),b&&e.jsx(CVt,{team:b,brokerageAgents:P,onBack:()=>j(null),onUpdate:I=>h.mutateAsync({id:b.id,...I}).then(D=>j(D)),onAddMember:(I,D)=>p.mutateAsync({team_id:b.id,user_id:I,role:D}),onRemoveMember:I=>f.mutateAsync({team_id:b.id,member_id:I}),onUpdateRole:(I,D)=>y.mutateAsync({team_id:b.id,member_id:I,role:D}),onDeleteTeam:()=>m.mutate(b.id),isUpdating:h.isPending,isAddingMember:p.isPending})]})})},uls=({team:s})=>{const{updateTeam:t}=SC(),n=r=>t.mutate({id:s.id,...r});return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsx(St,{className:"text-lg",children:"Team Settings"}),e.jsx(kn,{children:"Control how your team shares contacts, leads, and assets."})]}),e.jsxs(Me,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Contact Visibility"}),e.jsxs(is,{defaultValue:s.contact_visibility,onValueChange:r=>n({contact_visibility:r}),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"private",children:"Private — Members keep their contacts private"}),e.jsx(He,{value:"leader_only",children:"Leader Only — Only team leaders can see member contacts"}),e.jsx(He,{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(J,{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(fn,{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(J,{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(fn,{checked:s.shared_assets_enabled,onCheckedChange:r=>n({shared_assets_enabled:r})})]})]})]}),s.lead_pond_enabled&&e.jsx(NVt,{teamId:s.id})]})},gyr=()=>{const{data:s,isLoading:t,teams:n,activeTeamId:r,setActiveTeamId:a}=G_(),{useTeamMembers:i}=SC(),{data:l=[],isLoading:o}=i((s==null?void 0:s.teamId)||"");if(t)return e.jsx(zs,{title:"My Team",description:"Your team",children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(cn,{className:"h-8 w-48"}),e.jsx(cn,{className:"h-40 w-full"})]})});if(!s)return e.jsx(zs,{title:"My Team",description:"Your team",children:e.jsx(ve,{children:e.jsxs(Me,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(In,{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(zs,{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($f,{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(Oe,{variant:s.role==="team_leader"?"default":"secondary",className:"capitalize",children:s.role==="team_leader"?e.jsxs(e.Fragment,{children:[e.jsx($f,{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(Yr,{defaultValue:"members",className:"space-y-4",children:[e.jsxs(Zr,{className:"flex-wrap",children:[e.jsx(Ht,{value:"members",children:"Members"}),c.contact_visibility!=="private"&&e.jsxs(Ht,{value:"contacts",children:[e.jsx(WM,{className:"mr-1 h-3.5 w-3.5"}),"Team Contacts"]}),c.lead_pond_enabled&&e.jsxs(Ht,{value:"lead-pond",children:[e.jsx(m1,{className:"mr-1 h-3.5 w-3.5"}),"Lead Pond"]}),c.shared_assets_enabled&&e.jsxs(Ht,{value:"shared-assets",children:[e.jsx(wy,{className:"mr-1 h-3.5 w-3.5"}),"Shared Assets"]}),s.role==="team_leader"&&e.jsxs(Ht,{value:"settings",children:[e.jsx(qc,{className:"mr-1 h-3.5 w-3.5"}),"Settings"]})]}),e.jsx(Gt,{value:"members",className:"space-y-2",children:o?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(d=>e.jsx(cn,{className:"h-16 w-full"},d))}):l.map(d=>{var u,h,m,p;return e.jsx(ve,{children:e.jsxs(Me,{className:"flex items-center gap-3 p-4",children:[e.jsxs(ja,{className:"h-10 w-10",children:[e.jsx(pi,{src:((u=d.profile)==null?void 0:u.avatar_url)||""}),e.jsx(Na,{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(Oe,{className:"ml-auto bg-amber-500/10 text-amber-600 border-amber-500",children:[e.jsx($f,{className:"mr-1 h-3 w-3"})," Leader"]}):e.jsx(Oe,{variant:"secondary",className:"ml-auto",children:"Member"})]})},d.id)})}),c.contact_visibility!=="private"&&e.jsx(Gt,{value:"contacts",className:"space-y-4",children:e.jsx(ZLe,{})}),c.lead_pond_enabled&&e.jsx(Gt,{value:"lead-pond",className:"space-y-4",children:e.jsx(XLe,{teamId:s.teamId})}),c.shared_assets_enabled&&e.jsx(Gt,{value:"shared-assets",className:"space-y-4",children:e.jsx(Vtt,{teamId:s.teamId})}),s.role==="team_leader"&&e.jsx(Gt,{value:"settings",className:"space-y-4",children:e.jsx(uls,{team:c})})]},s.teamId)]})})},yyr=(s,t)=>at({queryKey:["team-production",s,t],queryFn:async()=>{const{data:n,error:r}=await q.rpc("get_team_production",{_team_id:s,_user_id:t});if(r)throw r;return(n||[]).map(a=>({...a,won_units_month:Number(a.won_units_month)||0,won_volume_month:Number(a.won_volume_month)||0,won_units_all:Number(a.won_units_all)||0,won_volume_all:Number(a.won_volume_all)||0,active_units:Number(a.active_units)||0,active_volume:Number(a.active_volume)||0}))},enabled:!!s&&!!t,staleTime:60*1e3}),T3=s=>Number(s)||0,vyr=(s,t,n=!0)=>at({queryKey:["team-financials",s,t],queryFn:async()=>{const{data:r,error:a}=await q.rpc("get_team_financials",{_team_id:s,_user_id:t});if(a)throw a;const i=(r||[]).map(c=>({...c,units:T3(c.units),volume:T3(c.volume),gci:T3(c.gci),net_to_agent:T3(c.net_to_agent),pipeline_units:T3(c.pipeline_units),pipeline_volume:T3(c.pipeline_volume),pipeline_gci:T3(c.pipeline_gci),team_dollar:T3(c.team_dollar),pipeline_team_dollar:T3(c.pipeline_team_dollar)})),l=i.filter(c=>c.scope==="member").sort((c,d)=>d.gci-c.gci||d.volume-c.volume),o=i.filter(c=>c.scope==="month").sort((c,d)=>(c.bucket_month||"").localeCompare(d.bucket_month||""));return{members:l,months:o,totals:{unitsMonth:l.reduce((c,d)=>c+d.units,0),volumeMonth:l.reduce((c,d)=>c+d.volume,0),gciMonth:l.reduce((c,d)=>c+d.gci,0),pipelineUnits:l.reduce((c,d)=>c+d.pipeline_units,0),pipelineVolume:l.reduce((c,d)=>c+d.pipeline_volume,0),pipelineGci:l.reduce((c,d)=>c+d.pipeline_gci,0),gciTrailing12:o.reduce((c,d)=>c+d.gci,0),teamDollarMonth:l.reduce((c,d)=>c+d.team_dollar,0),teamDollarPipeline:l.reduce((c,d)=>c+d.pipeline_team_dollar,0),teamDollarTrailing12:o.reduce((c,d)=>c+d.team_dollar,0)}}},enabled:!!s&&!!t&&n,staleTime:60*1e3}),byr=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],C2=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s||0),_yr=s=>{const t=Number(s)||0;return Math.abs(t)>=1e6?`$${(t/1e6).toFixed(1)}M`:Math.abs(t)>=1e3?`$${Math.round(t/1e3)}K`:`$${Math.round(t)}`},wyr=s=>{if(!s)return"";const[t,n]=s.split(/[-/T]/);return`${byr[Number(n)-1]||""} '${t.slice(2)}`},tX=({icon:s,label:t,value:n,sub:r})=>e.jsxs("div",{className:"team-hub-stat p-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.12em] text-muted-foreground",children:t}),e.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-primary/10 text-primary",children:e.jsx(s,{className:"h-4 w-4"})})]}),e.jsx("p",{className:"mt-3 text-3xl font-bold tracking-tight tabular-nums",children:n}),r&&e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:r})]}),jyr=({teamId:s,userId:t})=>{var u;const{data:n,isLoading:r}=vyr(s,t);if(r)return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-4",children:[1,2,3,4].map(h=>e.jsx(cn,{className:"h-24 w-full"},h))}),e.jsx(cn,{className:"h-64 w-full"})]});if(!n)return e.jsx(ve,{children:e.jsx(Me,{className:"py-10 text-center text-muted-foreground",children:"Financial outlook is available to team leaders."})});const{totals:a,members:i,months:l}=n,o=l.map(h=>({label:wyr(h.bucket_month),gci:Math.round(h.gci),volume:Math.round(h.volume),units:h.units})),c=((u=i[0])==null?void 0:u.gci)||0,d=a.unitsMonth>0?a.volumeMonth/a.unitsMonth:0;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsx(tX,{icon:yd,label:"GCI this month",value:C2(a.gciMonth),sub:`${a.unitsMonth} closing${a.unitsMonth===1?"":"s"} · ${C2(a.volumeMonth)} volume`}),e.jsx(tX,{icon:mj,label:"Pipeline GCI",value:C2(a.pipelineGci),sub:`${a.pipelineUnits} open · ${C2(a.pipelineVolume)} volume`}),e.jsx(tX,{icon:Nl,label:"GCI last 12 months",value:C2(a.gciTrailing12),sub:"Rolling team total"}),e.jsx(tX,{icon:F_,label:"Team dollar",value:C2(a.teamDollarMonth),sub:`From member splits · ${C2(a.teamDollarPipeline)} in pipeline`}),e.jsx(tX,{icon:F_,label:"Avg sale price",value:d?C2(d):"—",sub:"Closings this month"})]}),e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-2",children:e.jsx(St,{className:"text-base",children:"Team GCI trend"})}),e.jsx(Me,{children:o.length===0?e.jsx("p",{className:"py-8 text-center text-sm text-muted-foreground",children:"No closed deals in the last 12 months yet."}):e.jsx("div",{className:"h-64",children:e.jsx(jb,{width:"100%",height:"100%",children:e.jsxs(BW,{data:o,margin:{top:8,right:8,left:0,bottom:0},children:[e.jsx(kE,{strokeDasharray:"3 3",className:"stroke-border",vertical:!1}),e.jsx(Mv,{dataKey:"label",tickLine:!1,axisLine:!1,fontSize:11}),e.jsx(Pv,{tickFormatter:_yr,tickLine:!1,axisLine:!1,fontSize:11,width:56}),e.jsx(Mf,{formatter:(h,m)=>m==="units"?[h,"Units"]:[C2(h),m==="gci"?"GCI":"Volume"],contentStyle:{background:"hsl(var(--popover))",border:"1px solid hsl(var(--border))",borderRadius:8,color:"hsl(var(--popover-foreground))",fontSize:12}}),e.jsx(H_,{dataKey:"gci",fill:"hsl(var(--primary))",radius:[4,4,0,0]})]})})})})]}),e.jsxs(ve,{children:[e.jsx(bt,{className:"pb-2",children:e.jsx(St,{className:"text-base",children:"Contribution by agent"})}),e.jsx(Me,{className:"space-y-4",children:i.length===0?e.jsx("p",{className:"py-4 text-center text-sm text-muted-foreground",children:"No team members yet."}):i.map(h=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(ja,{className:"h-8 w-8",children:[e.jsx(pi,{src:h.member_avatar_url||""}),e.jsx(Na,{children:(h.member_name||"?").charAt(0).toUpperCase()})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:h.member_name||"Unknown"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[h.units," closed this month · ",h.pipeline_units," in pipeline (",C2(h.pipeline_gci),")",h.team_dollar>0?` · ${C2(h.team_dollar)} to team`:""]})]}),e.jsx("p",{className:"text-sm font-semibold",children:C2(h.gci)})]}),e.jsx(Fi,{value:c>0?h.gci/c*100:0,className:"h-1.5"})]},h.member_user_id))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"GCI uses each deal's net commission when set, otherwise its expected commission. Closings are dated by their actual close date. Team dollar is each deal's team split applied to its commission."})]})},bq=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s||0),zT=({icon:s,label:t,value:n,sub:r})=>e.jsxs("div",{className:"team-hub-stat p-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.12em] text-muted-foreground",children:t}),e.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-primary/10 text-primary",children:e.jsx(s,{className:"h-4 w-4"})})]}),e.jsx("p",{className:"mt-3 text-3xl font-bold tracking-tight tabular-nums",children:n}),r&&e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:r})]}),Nyr=({rows:s,myUserId:t})=>e.jsx(ve,{className:"overflow-hidden",children:e.jsx(Me,{className:"p-0",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/40 text-left text-[11px] uppercase tracking-[0.12em] text-muted-foreground",children:[e.jsx("th",{className:"px-4 py-3 font-semibold",children:"#"}),e.jsx("th",{className:"px-4 py-3 font-semibold",children:"Agent"}),e.jsx("th",{className:"px-4 py-3 font-semibold text-right",children:"This month"}),e.jsx("th",{className:"px-4 py-3 font-semibold text-right",children:"Volume MTD"}),e.jsx("th",{className:"px-4 py-3 font-semibold text-right",children:"Active"}),e.jsx("th",{className:"px-4 py-3 font-semibold text-right",children:"All-time"})]})}),e.jsx("tbody",{children:s.map((n,r)=>e.jsxs("tr",{className:"team-hub-row border-b last:border-0 "+(n.user_id===t?"bg-primary/5 ring-1 ring-inset ring-primary/15":""),children:[e.jsx("td",{className:"px-4 py-3",children:e.jsx("span",{className:"team-hub-rank","data-rank":r+1,children:r===0?e.jsx(wl,{className:"h-3.5 w-3.5"}):r+1})}),e.jsx("td",{className:"px-4 py-3",children:e.jsxs("div",{className:"flex items-center gap-2.5 min-w-0",children:[e.jsxs(ja,{className:"h-9 w-9 ring-2 ring-background shadow-sm",children:[e.jsx(pi,{src:n.avatar_url||""}),e.jsx(Na,{children:(n.name||"?").charAt(0).toUpperCase()})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"font-medium truncate",children:[n.name||"Unknown",n.user_id===t&&e.jsx("span",{className:"ml-1.5 text-[11px] font-normal text-primary",children:"You"})]}),n.role==="team_leader"&&e.jsxs("span",{className:"inline-flex items-center text-[11px] text-amber-600",children:[e.jsx($f,{className:"mr-0.5 h-3 w-3"})," Leader"]})]})]})}),e.jsxs("td",{className:"px-4 py-3 text-right font-semibold tabular-nums",children:[n.won_units_month," unit",n.won_units_month===1?"":"s"]}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums",children:bq(n.won_volume_month)}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums",children:n.active_units}),e.jsxs("td",{className:"px-4 py-3 text-right text-muted-foreground tabular-nums",children:[n.won_units_all," / ",bq(n.won_volume_all)]})]},n.user_id))})]})})})}),kyr=()=>{const{user:s}=hs(),{data:t,isLoading:n,teams:r,activeTeamId:a,setActiveTeamId:i}=G_(),{useTeamMembers:l}=SC(),{data:o=[],isLoading:c}=l((t==null?void 0:t.teamId)||""),{data:d=[],isLoading:u}=yyr(t==null?void 0:t.teamId,s==null?void 0:s.id),h=(t==null?void 0:t.role)==="team_leader",m=t==null?void 0:t.team,[p]=Yl(),f=p.get("tab"),y=f==="website"&&h?"website":f||"members",v=_.useMemo(()=>d.reduce((j,S)=>({monthUnits:j.monthUnits+S.won_units_month,monthVolume:j.monthVolume+S.won_volume_month,activeUnits:j.activeUnits+S.active_units,activeVolume:j.activeVolume+S.active_volume}),{monthUnits:0,monthVolume:0,activeUnits:0,activeVolume:0}),[d]),g=_.useMemo(()=>d.find(j=>j.user_id===(s==null?void 0:s.id))||null,[d,s==null?void 0:s.id]),b=_.useMemo(()=>{if(!g)return null;const j=d.findIndex(S=>S.user_id===g.user_id);return j>=0?j+1:null},[d,g]);return n?e.jsx(zs,{title:"Team",description:"Your team hub",children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(cn,{className:"h-8 w-48"}),e.jsx(cn,{className:"h-40 w-full"})]})}):!t||!m?e.jsx(zs,{title:"Team",description:"Your team hub",children:e.jsx(ve,{children:e.jsxs(Me,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(In,{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."})]})})}):e.jsx(zs,{title:"Team",description:m.name,children:e.jsxs("div",{className:"team-hub space-y-6",children:[e.jsxs("div",{children:[r.length>1&&e.jsx("div",{className:"flex flex-wrap gap-2 mb-3",children:r.map(j=>{var S;return e.jsxs("button",{onClick:()=>i(j.teamId),className:"rounded-full border px-3.5 py-1.5 text-sm transition-colors "+(j.teamId===a?"bg-primary text-primary-foreground border-primary shadow-sm":"bg-background text-muted-foreground hover:bg-muted"),children:[(S=j.team)==null?void 0:S.name,j.role==="team_leader"&&e.jsx($f,{className:"ml-1 inline h-3 w-3"})]},j.teamId)})}),e.jsx("div",{className:"team-hub-hero p-6 sm:p-7",children:e.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[e.jsx("span",{className:"flex h-12 w-12 items-center justify-center rounded-xl bg-primary/12 text-primary",children:e.jsx(In,{className:"h-6 w-6"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2.5",children:[e.jsx("h2",{className:"text-2xl font-bold tracking-tight sm:text-3xl",children:m.name}),e.jsx(Oe,{variant:h?"default":"secondary",className:"capitalize",children:h?e.jsxs(e.Fragment,{children:[e.jsx($f,{className:"mr-1 h-3 w-3"})," Leader"]}):"Member"})]}),m.description?e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-muted-foreground",children:m.description}):e.jsxs("p",{className:"mt-1 text-sm text-muted-foreground",children:[d.length," member",d.length===1?"":"s"," · shared contacts, leads and resources"]})]})]})})]}),h?e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsx(zT,{icon:yd,label:"Volume MTD",value:bq(v.monthVolume),sub:"Closed this month"}),e.jsx(zT,{icon:Nl,label:"Units MTD",value:String(v.monthUnits),sub:"Closed this month"}),e.jsx(zT,{icon:mj,label:"Active deals",value:String(v.activeUnits),sub:bq(v.activeVolume)+" in pipeline"}),e.jsx(zT,{icon:In,label:"Team size",value:String(d.length),sub:"Members on the team"})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsx("h3",{className:"text-[11px] font-semibold uppercase tracking-[0.12em] text-muted-foreground",children:"My standing"}),g?e.jsxs("div",{className:"grid gap-4 grid-cols-2 lg:grid-cols-4",children:[e.jsx(zT,{icon:Nl,label:"Units MTD",value:String(g.won_units_month),sub:"Closed this month"}),e.jsx(zT,{icon:yd,label:"Volume MTD",value:bq(g.won_volume_month),sub:"Closed this month"}),e.jsx(zT,{icon:mj,label:"My active deals",value:String(g.active_units),sub:bq(g.active_volume)+" in pipeline"}),e.jsx(zT,{icon:wl,label:"Team ranking",value:b?`#${b}`:"—",sub:`of ${d.length} member${d.length===1?"":"s"}`})]}):u?e.jsx("div",{className:"grid gap-4 grid-cols-2 lg:grid-cols-4",children:[1,2,3,4].map(j=>e.jsx(cn,{className:"h-28 w-full"},j))}):e.jsx(ve,{children:e.jsx(Me,{className:"py-8 text-center text-sm text-muted-foreground",children:"No production data yet — close your first deal!"})})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("h3",{className:"text-[11px] font-semibold uppercase tracking-[0.12em] text-muted-foreground",children:h?"Team production":"Leaderboard"}),u?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(j=>e.jsx(cn,{className:"h-14 w-full"},j))}):d.length===0?e.jsx(ve,{children:e.jsx(Me,{className:"py-8 text-center text-muted-foreground",children:"No production data yet."})}):e.jsx(Nyr,{rows:d,myUserId:(s==null?void 0:s.id)||""})]}),e.jsxs(Yr,{defaultValue:y,className:"space-y-4",children:[e.jsxs(Zr,{className:"team-hub-tabs h-auto flex-wrap justify-start gap-1",children:[e.jsx(Ht,{value:"members",children:"Members"}),m.contact_visibility!=="private"&&e.jsxs(Ht,{value:"contacts",children:[e.jsx(WM,{className:"mr-1 h-3.5 w-3.5"}),"Team Contacts"]}),m.lead_pond_enabled&&e.jsxs(Ht,{value:"lead-pond",children:[e.jsx(m1,{className:"mr-1 h-3.5 w-3.5"}),"Lead Pond"]}),m.shared_assets_enabled&&e.jsxs(Ht,{value:"shared-assets",children:[e.jsx(wy,{className:"mr-1 h-3.5 w-3.5"}),"Shared Assets"]}),h&&e.jsxs(Ht,{value:"financials",children:[e.jsx(yd,{className:"mr-1 h-3.5 w-3.5"}),"Financials"]}),h&&e.jsxs(Ht,{value:"website",children:[e.jsx(sl,{className:"mr-1 h-3.5 w-3.5"}),"Team Website"]}),h&&e.jsxs(Ht,{value:"settings",children:[e.jsx(qc,{className:"mr-1 h-3.5 w-3.5"}),"Settings"]})]}),e.jsx(Gt,{value:"members",className:"space-y-2",children:c?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(j=>e.jsx(cn,{className:"h-16 w-full"},j))}):o.map(j=>{var S,C,E,P;return e.jsx(ve,{children:e.jsxs(Me,{className:"flex items-center gap-3 p-4",children:[e.jsxs(ja,{className:"h-10 w-10",children:[e.jsx(pi,{src:((S=j.profile)==null?void 0:S.avatar_url)||""}),e.jsx(Na,{children:(((C=j.profile)==null?void 0:C.name)||"?").charAt(0).toUpperCase()})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium",children:((E=j.profile)==null?void 0:E.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(P=j.profile)==null?void 0:P.email})]}),j.role==="team_leader"?e.jsxs(Oe,{className:"ml-auto bg-amber-500/10 text-amber-600 border-amber-500",children:[e.jsx($f,{className:"mr-1 h-3 w-3"})," Leader"]}):e.jsx(Oe,{variant:"secondary",className:"ml-auto",children:"Member"})]})},j.id)})}),m.contact_visibility!=="private"&&e.jsx(Gt,{value:"contacts",className:"space-y-4",children:e.jsx(ZLe,{})}),m.lead_pond_enabled&&e.jsx(Gt,{value:"lead-pond",className:"space-y-4",children:e.jsx(XLe,{teamId:t.teamId})}),m.shared_assets_enabled&&e.jsx(Gt,{value:"shared-assets",className:"space-y-4",children:e.jsx(Vtt,{teamId:t.teamId})}),h&&e.jsx(Gt,{value:"financials",className:"space-y-4",children:e.jsx(jyr,{teamId:t.teamId,userId:(s==null?void 0:s.id)||""})}),h&&e.jsx(Gt,{value:"website",className:"space-y-4",children:e.jsx(sit,{teamId:t.teamId,orgLabel:"team"})}),h&&e.jsx(Gt,{value:"settings",className:"space-y-4",children:e.jsx(uls,{team:m})})]},`${t.teamId}-${y}`)]})})},OAt={Home:"🏠",Search:"🔍",DollarSign:"💰",Coffee:"☕",Calendar:"📅",Users:"👥",Phone:"📞",Video:"🎥"};function Syr({types:s,onSave:t,onDelete:n}){const[r,a]=_.useState(null),[i,l]=_.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(ve,{children:[e.jsxs(bt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(St,{children:"Booking Types"}),e.jsx(kn,{children:"The meeting types prospects can book with you"})]}),e.jsxs(B,{onClick:o,size:"sm",children:[e.jsx(rn,{className:"h-4 w-4 mr-1"})," Add Type"]})]}),e.jsx(Me,{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:OAt[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(Oe,{variant:"secondary",className:"text-xs",children:"Inactive"}),u.is_coaching_only&&e.jsx(Oe,{variant:"outline",className:"text-xs",children:"Coaching only"}),u.qualification_enabled&&e.jsxs(Oe,{variant:"outline",className:"text-xs gap-1",children:[e.jsx(VQ,{className:"h-3 w-3"})," Qualifying"]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Gr,{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(B,{variant:"ghost",size:"sm",onClick:()=>c(u),children:e.jsx(Ya,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>n(u.id),className:"text-destructive hover:text-destructive",children:e.jsx(Sn,{className:"h-4 w-4"})})]})]},u.id))})})]}),e.jsx(Ls,{open:i,onOpenChange:l,children:e.jsxs(Ps,{children:[e.jsx(Os,{children:e.jsxs(Ds,{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(J,{children:"Name"}),e.jsx(xe,{value:r.name||"",onChange:u=>a({...r,name:u.target.value}),placeholder:"e.g. Listing Consultation"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Description"}),e.jsx(Ms,{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(J,{children:"Duration (minutes)"}),e.jsx(xe,{type:"number",min:15,max:180,step:15,value:r.duration_minutes||30,onChange:u=>a({...r,duration_minutes:parseInt(u.target.value)||30})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:r.color||"#3B82F6",onChange:u=>a({...r,color:u.target.value}),className:"h-10 w-10 rounded border cursor-pointer"}),e.jsx(xe,{value:r.color||"#3B82F6",onChange:u=>a({...r,color:u.target.value}),className:"flex-1"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Max bookings per day"}),e.jsx(xe,{type:"number",min:0,max:50,value:r.max_per_day??"",onChange:u=>a({...r,max_per_day:u.target.value===""?null:parseInt(u.target.value)||0}),placeholder:"Unlimited"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Leave blank for unlimited. Once this many are booked on a day, the day closes."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Icon"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(OAt).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(J,{children:"Meeting Link Override (optional)"}),e.jsx(xe,{value:r.meeting_link_override||"",onChange:u=>a({...r,meeting_link_override:u.target.value||null}),placeholder:"Use a different link for this type"})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(J,{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(fn,{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(J,{children:"Pre-Qualification Questions"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Ask qualifying questions before booking"})]}),e.jsx(fn,{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(J,{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(fn,{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(J,{children:"Active"}),e.jsx(fn,{checked:r.is_active??!0,onCheckedChange:u=>a({...r,is_active:u})})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(B,{onClick:d,children:"Save"})]})]})})]})}const Cyr={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 Ayr({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(Fo,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"font-medium",children:i.guest_name}),e.jsx(Oe,{className:`text-xs ${Cyr[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(pc,{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(Gr,{className:"h-3.5 w-3.5"}),(o=i.start_time)==null?void 0:o.slice(0,5)," - ",(c=i.end_time)==null?void 0:c.slice(0,5)]})]}),e.jsxs("div",{className:"flex items-center gap-3 text-sm text-muted-foreground",children:[i.guest_email&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ln,{className:"h-3 w-3"}),i.guest_email]}),i.guest_phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(_a,{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(Oe,{variant:"outline",className:"text-xs",children:i.booking_type.name}),i.google_sync_status==="synced"&&e.jsxs(Oe,{variant:"outline",className:"text-xs gap-1 text-emerald-700 border-emerald-300 dark:text-emerald-400",children:[e.jsx(bv,{className:"h-3 w-3"})," On Google Calendar"]}),i.google_sync_status==="failed"&&e.jsxs(Oe,{variant:"outline",className:"text-xs gap-1 text-amber-700 border-amber-300 dark:text-amber-400",children:[e.jsx(Aq,{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(B,{variant:"ghost",size:"sm",onClick:()=>t(i.id),className:"text-destructive hover:text-destructive",children:[e.jsx(Rd,{className:"h-4 w-4 mr-1"})," Cancel"]})]},i.id)};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsx(St,{children:"Upcoming Bookings"}),e.jsxs(kn,{children:[n.length," upcoming appointment",n.length!==1?"s":""]})]}),e.jsx(Me,{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(ve,{children:[e.jsx(bt,{children:e.jsx(St,{children:"Past & Cancelled"})}),e.jsx(Me,{children:e.jsx("div",{className:"space-y-3",children:r.slice(0,20).map(i=>a(i))})})]})]})}function Eyr(){const{settings:s,bookingTypes:t,availability:n,blockedDates:r,bookings:a,isLoading:i,initializeSettings:l,updateSettings:o,upsertBookingType:c,deleteBookingType:d,upsertAvailability:u,deleteAvailability:h,addBlockedDate:m,removeBlockedDate:p,cancelBooking:f}=d9t(),[y,v]=_.useState("");_.useState(15),y||s!=null&&s.meeting_link;const g=s!=null&&s.slug?`https://booking.relevelup.com/${s.slug}`:null;return i?e.jsx(zs,{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(zs,{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(pc,{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:[g&&e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>{navigator.clipboard.writeText(g),se.success("Booking link copied!")},children:[e.jsx(Ia,{className:"h-4 w-4 mr-1"})," Copy Link"]}),e.jsx(B,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:g,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(wr,{className:"h-4 w-4 mr-1"})," Preview"]})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(J,{htmlFor:"scheduler-active",className:"text-sm",children:"Active"}),e.jsx(fn,{id:"scheduler-active",checked:s.is_active,onCheckedChange:b=>o.mutate({is_active:b})})]})]})]}),e.jsxs(Yr,{defaultValue:"types",className:"space-y-4",children:[e.jsxs(Zr,{children:[e.jsx(Ht,{value:"types",children:"Booking Types"}),e.jsx(Ht,{value:"availability",children:"Availability"}),e.jsx(Ht,{value:"settings",children:"Settings"}),e.jsxs(Ht,{value:"bookings",children:["Bookings",a.filter(b=>b.status==="confirmed").length>0&&e.jsx(Oe,{variant:"secondary",className:"ml-1.5 text-xs",children:a.filter(b=>b.status==="confirmed").length})]})]}),e.jsx(Gt,{value:"types",children:e.jsx(Syr,{types:t,onSave:b=>c.mutate(b),onDelete:b=>d.mutate(b)})}),e.jsx(Gt,{value:"availability",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(u9t,{slots:n,onSave:b=>u.mutate(b),onDelete:b=>h.mutate(b)}),e.jsx(h9t,{blockedDates:r,onAdd:b=>m.mutate(b),onRemove:b=>p.mutate(b)})]})}),e.jsxs(Gt,{value:"settings",className:"space-y-6",children:[e.jsx(p9t,{scope:"agent"}),e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsxs(St,{className:"flex items-center gap-2",children:[e.jsx(fS,{className:"h-5 w-5"}),"General Settings"]}),e.jsx(kn,{children:"Configure your booking page defaults"})]}),e.jsxs(Me,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Booking Page URL"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xe,{value:s.slug,readOnly:!0,className:"bg-muted"}),e.jsx(B,{variant:"outline",size:"sm",onClick:()=>{g&&(navigator.clipboard.writeText(g),se.success("Copied!"))},children:e.jsx(Ia,{className:"h-4 w-4"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:g})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(J,{htmlFor:"meeting-link",children:[e.jsx(vd,{className:"h-4 w-4 inline mr-1"}),"Default Meeting Link"]}),e.jsx(xe,{id:"meeting-link",placeholder:"https://zoom.us/j/your-personal-link",defaultValue:s.meeting_link||"",onBlur:b=>o.mutate({meeting_link:b.target.value||null})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Your Zoom personal link, Google Meet, or phone number"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Buffer Between Meetings"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xe,{type:"number",min:0,max:60,defaultValue:s.buffer_minutes,onBlur:b=>o.mutate({buffer_minutes:parseInt(b.target.value)||15})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"min"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Minimum Notice"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xe,{type:"number",min:0,max:72,defaultValue:s.min_notice_hours,onBlur:b=>o.mutate({min_notice_hours:parseInt(b.target.value)||2})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"hours"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Max Advance Booking"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xe,{type:"number",min:1,max:90,defaultValue:s.max_advance_days,onBlur:b=>o.mutate({max_advance_days:parseInt(b.target.value)||30})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"days"})]})]})]}),e.jsxs("div",{className:"space-y-3 pt-2 border-t",children:[e.jsx(J,{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(fn,{checked:s.reminders_enabled!==!1,onCheckedChange:b=>o.mutate({reminders_enabled:b})})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Text message reminders"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Texts guests who left a phone number. Standard opt-out language is included."})]}),e.jsx(fn,{checked:!!s.sms_reminders_enabled,onCheckedChange:b=>o.mutate({sms_reminders_enabled:b})})]})]}),e.jsxs("div",{className:"space-y-2 pt-2 border-t",children:[e.jsx(J,{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(B,{variant:"outline",size:"sm",onClick:()=>{navigator.clipboard.writeText(``),se.success("Embed code copied")},children:[e.jsx(Ia,{className:"h-4 w-4 mr-1.5"})," Copy embed code"]})]})]})]})]}),e.jsx(Gt,{value:"bookings",children:e.jsx(Ayr,{bookings:a,onCancel:b=>f.mutate({id:b})})})]})]})}):e.jsx(zs,{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(pc,{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(ve,{children:e.jsxs(Me,{className:"pt-6 space-y-4",children:[e.jsx("div",{className:"grid grid-cols-2 gap-4",children:[{icon:"🏠",title:"Listing Consultation",desc:"60 min"},{icon:"🔍",title:"Buyer Consultation",desc:"45 min"},{icon:"💰",title:"Home Valuation",desc:"30 min"},{icon:"☕",title:"General Meeting",desc:"30 min"}].map(b=>e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border bg-muted/30",children:[e.jsx("span",{className:"text-2xl",children:b.icon}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:b.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:b.desc})]})]},b.title))}),e.jsx(wc,{}),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(B,{onClick:()=>l.mutate(),disabled:l.isPending,className:"w-full",size:"lg",children:[e.jsx(un,{className:"h-4 w-4 mr-2"}),l.isPending?"Setting up...":"Activate Scheduler"]})]})})]})})}function Tyr(s,t,n=!0){return at({queryKey:["my-calendar",s,t],enabled:n&&!!s&&!!t,staleTime:6e4,queryFn:async()=>{const{data:r,error:a}=await q.functions.invoke("my-calendar",{body:{start:s,end:t}});if(a){let i=a.message;try{const l=a.context;if(l!=null&&l.json){const o=await l.json();o!=null&&o.error&&(i=o.error)}}catch{}throw new Error(i)}if(r!=null&&r.error)throw new Error(r.error);return r}})}async function MUe(s){const{data:t,error:n}=await q.functions.invoke("agent-appointments",{body:s});if(n){let r=n.message;try{const a=n.context;if(a!=null&&a.json){const i=await a.json();i!=null&&i.error&&(r=i.error)}}catch{}throw new Error(r)}if(t!=null&&t.error)throw new Error(t.error);return t}function Myr(){const s=Bt(),t=()=>{s.invalidateQueries({queryKey:["my-calendar"]}),s.invalidateQueries({queryKey:["agent-appointments"]})},n=mt({mutationFn:async i=>MUe({action:i.id?"update":"create",...i}),onSuccess:t}),r=mt({mutationFn:async i=>MUe({action:"cancel",id:i}),onSuccess:t});return{save:n,remove:r,checkConflicts:async(i,l,o)=>MUe({action:"check_conflicts",start_at:i,end_at:l,id:o})}}function zAt(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:RE(),year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1}).formatToParts(new Date(c)),h=p=>{var f;return Number((f=u.find(y=>y.type===p))==null?void 0:f.value)},m=Date.UTC(h("year"),h("month")-1,h("day"),h("hour")%24,h("minute"),h("second"));c+=o-m}return new Date(c).toISOString()}function PUe(s){const t=new Intl.DateTimeFormat("en-CA",{timeZone:RE(),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 Pyr=[{id:"google_meet",label:"Google Meet",icon:Kr},{id:"in_person",label:"In person",icon:Xa},{id:"phone",label:"Phone",icon:_a}];function Lyr({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}=Myr(),m=!!(l!=null&&l.id),[p,f]=_.useState(""),[y,v]=_.useState(""),[g,b]=_.useState("09:00"),[j,S]=_.useState("09:30"),[C,E]=_.useState("in_person"),[P,M]=_.useState(""),[I,D]=_.useState(""),[O,V]=_.useState([]),[G,$]=_.useState(""),[H,Y]=_.useState(!1);_.useEffect(()=>{if(s){if(l){const be=PUe(l.start_at),me=PUe(l.end_at);f(l.title),v(be.date),b(be.time),S(me.time),E(l.meeting_mode),M(l.location||""),D(l.notes||""),V((l.agent_appointment_contacts||[]).map(he=>he.contact_id))}else{f(""),v(n||PUe(new Date().toISOString()).date);const be=r||"09:00",[me,he]=be.split(":").map(Number),pe=me*60+he+30;b(be),S(`${`${Math.floor(pe/60)%24}`.padStart(2,"0")}:${`${pe%60}`.padStart(2,"0")}`),E(o?"google_meet":"in_person"),M(""),D(""),V(a?[a]:[])}$(""),Y(!1)}},[s,l,n,r,a,o]),_.useEffect(()=>{if(j<=g){const[be,me]=g.split(":").map(Number),he=new Date(0,0,0,be,me+30);S(`${String(he.getHours()).padStart(2,"0")}:${String(he.getMinutes()).padStart(2,"0")}`)}},[g]);const Z=_.useMemo(()=>y?zAt(y,g):"",[y,g]),ne=_.useMemo(()=>y?zAt(y,j):"",[y,j]);_.useEffect(()=>{if(!s||!o||!Z||!ne)return;let be=!1;const me=setTimeout(async()=>{try{const he=await h(Z,ne,l==null?void 0:l.id);be||Y(!!he.conflicts.length)}catch{}},500);return()=>{be=!0,clearTimeout(me)}},[s,o,Z,ne]);const{data:ce=[]}=at({queryKey:["appointment-contact-search",G],enabled:s,queryFn:async()=>{let be=q.from("innercircle_contacts").select("id, first_name, last_name, email").not("email","is",null).neq("email","").like("email","%@%").order("first_name").limit(20);if(G.trim()){const pe=`%${G.trim()}%`;be=be.or(`first_name.ilike.${pe},last_name.ilike.${pe},email.ilike.${pe}`)}const{data:me,error:he}=await be;if(he)throw he;return(me||[]).filter(pe=>!!pe.email&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(pe.email.trim()))}}),{data:ie=[]}=at({queryKey:["appointment-selected-contacts",O],enabled:s&&O.length>0,queryFn:async()=>{const{data:be}=await q.from("innercircle_contacts").select("id, first_name, last_name, email").in("id",O);return be||[]}}),te=be=>[be.first_name,be.last_name].filter(Boolean).join(" ")||be.email||"Contact",ae=async()=>{if(!p.trim())return se.error("Give the appointment a title");if(!y)return se.error("Pick a date");try{await d.mutateAsync({id:l==null?void 0:l.id,title:p.trim(),start_at:Z,end_at:ne,meeting_mode:C,location:C==="google_meet"?null:P||null,notes:I||null,deal_id:i??(l==null?void 0:l.deal_id)??null,contact_ids:O}),se.success(m?"Appointment updated":"Appointment created"),c==null||c(),t(!1)}catch(be){se.error(be instanceof Error?be.message:"Could not save the appointment")}},le=async()=>{if(l!=null&&l.id)try{await u.mutateAsync(l.id),se.success("Appointment deleted"),c==null||c(),t(!1)}catch(be){se.error(be instanceof Error?be.message:"Could not delete the appointment")}};return e.jsx(Ls,{open:s,onOpenChange:t,children:e.jsxs(Ps,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:m?"Edit appointment":"New appointment"}),e.jsx(_r,{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(J,{children:"Title"}),e.jsx(xe,{value:p,onChange:be=>f(be.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(J,{children:"Date"}),e.jsx(xe,{type:"date",value:y,onChange:be=>v(be.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Start"}),e.jsx(xe,{type:"time",value:g,onChange:be=>b(be.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"End"}),e.jsx(xe,{type:"time",value:j,onChange:be=>S(be.target.value)})]})]}),H&&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(xl,{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(J,{children:"Meeting type"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Pyr.map(be=>{const me=be.icon,he=C===be.id;return e.jsxs("button",{type:"button",onClick:()=>E(be.id),className:At("inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-xs font-medium transition-colors",he?"bg-primary text-primary-foreground border-primary":"hover:bg-accent"),children:[e.jsx(me,{className:"h-3.5 w-3.5"}),be.label]},be.id)})}),C==="google_meet"&&!o&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connect Google Calendar to auto-create the Meet link."})]}),C!=="google_meet"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:C==="phone"?"Phone number":"Location"}),e.jsx(xe,{value:P,onChange:be=>M(be.target.value),placeholder:C==="phone"?"(555) 123-4567":"123 Main St, Suite 200"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(J,{className:"flex items-center gap-1.5",children:[e.jsx(In,{className:"h-3.5 w-3.5"})," Contacts"]}),ie.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:ie.map(be=>e.jsxs(Oe,{variant:"secondary",className:"max-w-[220px] gap-1",title:te(be),children:[e.jsx("span",{className:"truncate",children:te(be)}),e.jsx("button",{type:"button",onClick:()=>V(me=>me.filter(he=>he!==be.id)),children:e.jsx(Qn,{className:"h-3 w-3"})})]},be.id))}),e.jsx(xe,{value:G,onChange:be=>$(be.target.value),placeholder:"Search contacts with an email…"}),G.trim()&&e.jsxs("div",{className:"max-h-40 overflow-y-auto rounded-lg border divide-y",children:[ce.filter(be=>!O.includes(be.id)).map(be=>e.jsxs("button",{type:"button",onClick:()=>{V(me=>[...me,be.id]),$("")},className:"flex w-full items-baseline gap-2 overflow-hidden px-3 py-2 text-left text-sm hover:bg-accent/50",title:[te(be),be.email].filter(Boolean).join(" · "),children:[e.jsx("span",{className:"min-w-0 flex-1 truncate font-medium",children:te(be)}),be.email&&e.jsx("span",{className:"max-w-[45%] shrink-0 truncate text-xs text-muted-foreground",children:be.email})]},be.id)),ce.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:O.length===0?"Tap a search result to add a guest — they get the Google invite.":`${O.length} guest${O.length>1?"s":""} will be invited to the calendar event.`})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Notes"}),e.jsx(Ms,{value:I,onChange:be=>D(be.target.value),rows:3,placeholder:"Anything you want on the invite…"})]})]}),e.jsxs(yr,{className:"gap-2 sm:justify-between",children:[m?e.jsxs(B,{variant:"ghost",onClick:le,disabled:u.isPending,className:"text-destructive hover:text-destructive",children:[e.jsx(Sn,{className:"h-4 w-4 mr-1.5"})," Delete"]}):e.jsx("span",{}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(B,{onClick:ae,disabled:d.isPending,children:d.isPending?"Saving…":m?"Save changes":"Create appointment"})]})]})]})})}function Iyr(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:RE(),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 nQ(s){const[t,n,r]=s.split(/[-/T]/).map(Number);return new Date(t,(n||1)-1,r||1)}function Aw(s){const t=`${s.getMonth()+1}`.padStart(2,"0"),n=`${s.getDate()}`.padStart(2,"0");return`${s.getFullYear()}-${t}-${n}`}function F3(s,t){const n=new Date(s);return n.setDate(n.getDate()+t),n}function LUe(s){return F3(s,-s.getDay())}function BT(){return new Intl.DateTimeFormat("en-CA",{timeZone:RE(),year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date)}function sot(s){return s?new Intl.DateTimeFormat("en-US",{timeZone:RE(),hour:"numeric",minute:"2-digit"}).format(new Date(s)).toLowerCase().replace(" ",""):""}function Yse(s){return new Intl.DateTimeFormat("en-US",{weekday:"long",month:"long",day:"numeric"}).format(nQ(s))}const LZe=[{id:"google",label:"Google Calendar",color:"#4285F4",soft:"#4285F41A",icon:pc},{id:"appointments",label:"My appointments",color:"#0F766E",soft:"#0F766E1A",icon:gy},{id:"bookings",label:"Guest bookings",color:"#406E71",soft:"#406E711A",icon:Gr},{id:"deals",label:"Deal dates",color:"#2a4c64",soft:"#2a4c641A",icon:wv},{id:"tasks",label:"Tasks",color:"#B45309",soft:"#B453091A",icon:Ny},{id:"open_houses",label:"Open houses",color:"#7C3AED",soft:"#7C3AED1A",icon:Jr},{id:"events",label:"LevelUp events",color:"#0EA5E9",soft:"#0EA5E91A",icon:un},{id:"coaching",label:"Coaching",color:"#DB2777",soft:"#DB27771A",icon:Kr}],vDe=Object.fromEntries(LZe.map(s=>[s.id,s])),hls="levelup.myCalendar.layers",BAt="levelup.myCalendar.view";function Dyr(){try{return JSON.parse(localStorage.getItem(hls)||"{}")}catch{return{}}}function Ryr(){var Ce,Ae;const s=Fn(),[t,n]=Yl(),[r,a]=_.useState(()=>nQ(BT())),[i,l]=_.useState(()=>localStorage.getItem(BAt)||"month"),[o,c]=_.useState(Dyr),[d,u]=_.useState(BT()),[h,m]=_.useState(!1),[p,f]=_.useState(BT()),[y,v]=_.useState(void 0),[g,b]=_.useState(null),[j,S]=_.useState(!1),{timezone:C}=yae(),E=(Pe,ze)=>{b(null);const ke=BT(),Ze=Pe||ke;f(Ze{u(Pe),a(nQ(Pe)),l("day")},M=Pe=>{Pe.layer==="appointments"&&(b(Iyr(Pe)),m(!0))};_.useEffect(()=>localStorage.setItem(BAt,i),[i]),_.useEffect(()=>localStorage.setItem(hls,JSON.stringify(o)),[o]);const I=m9t(!0,"agent");_.useEffect(()=>{const Pe=t.get("google_calendar");if(!Pe)return;Pe==="connected"?se.success("Google Calendar connected"):se.error(t.get("google_calendar_error")||"Google Calendar connection failed");const ze=new URLSearchParams(t);ze.delete("google_calendar"),ze.delete("google_calendar_error"),n(ze,{replace:!0})},[t,n]);const{rangeStart:D,rangeEnd:O,gridDays:V}=_.useMemo(()=>{if(i==="week"){const Ze=LUe(r);return{rangeStart:Aw(Ze),rangeEnd:Aw(F3(Ze,6)),gridDays:Array.from({length:7},(Se,Fe)=>F3(Ze,Fe))}}if(i==="day")return{rangeStart:Aw(r),rangeEnd:Aw(r),gridDays:[r]};if(i==="agenda")return{rangeStart:Aw(r),rangeEnd:Aw(F3(r,44)),gridDays:[]};const Pe=new Date(r.getFullYear(),r.getMonth(),1),ze=LUe(Pe),ke=Array.from({length:42},(Ze,Se)=>F3(ze,Se));return{rangeStart:Aw(ze),rangeEnd:Aw(ke[41]),gridDays:ke}},[r,i]),{data:G,isLoading:$,isFetching:H,refetch:Y,error:Z}=Tyr(D,O),ne=!!((Ce=I.status.data)!=null&&Ce.connected)||!!(G!=null&&G.google.connected),ce=_.useMemo(()=>((G==null?void 0:G.items)||[]).filter(Pe=>!o[Pe.layer]),[G,o]),ie=_.useMemo(()=>{const Pe=new Map;return ce.forEach(ze=>{const ke=Pe.get(ze.date)||[];ke.push(ze),Pe.set(ze.date,ke)}),Pe},[ce]),te=_.useMemo(()=>ie.get(d)||[],[ie,d]),ae=BT(),le=_.useMemo(()=>ce.filter(Pe=>Pe.date>=ae).slice(0,6),[ce,ae]),be=_.useMemo(()=>ce.filter(Pe=>{var ze,ke;return Pe.date{if(i==="week"){const Pe=LUe(r),ze=F3(Pe,6),ke=Pe.getMonth()===ze.getMonth(),Ze=(Se,Fe)=>new Intl.DateTimeFormat("en-US",{month:Fe?"short":void 0,day:"numeric"}).format(Se);return`${Ze(Pe,!0)} – ${Ze(ze,!ke)}, ${ze.getFullYear()}`}return i==="day"?Yse(Aw(r)):i==="agenda"?"Next 45 days":new Intl.DateTimeFormat("en-US",{month:"long",year:"numeric"}).format(r)},[r,i]),he=Pe=>{if(i==="day"){a(ze=>{const ke=F3(ze,Pe);return u(Aw(ke)),ke});return}a(i==="week"?ze=>F3(ze,Pe*7):i==="agenda"?ze=>F3(ze,Pe*45):ze=>new Date(ze.getFullYear(),ze.getMonth()+Pe,1))},pe=Pe=>{if(Pe==="google"&&!ne){I.connect.mutate();return}c(ze=>({...ze,[Pe]:!ze[Pe]}))};return e.jsxs(zs,{children:[e.jsxs("div",{className:"p-4 md:p-6 space-y-5 max-w-[1600px] mx-auto",children:[e.jsxs("div",{className:"rounded-2xl border bg-card shadow-sm overflow-hidden",children:[e.jsxs("div",{className:"px-5 py-5 md:px-7 md:py-6",style:{background:"linear-gradient(135deg, #2a4c6412, #406E7112)"},children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h1",{className:"text-2xl md:text-3xl font-semibold tracking-tight text-foreground",children:"My Calendar"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Appointments, deal deadlines, tasks and open houses — all in one place."}),e.jsxs("button",{type:"button",onClick:()=>S(!0),className:"mt-2 inline-flex items-center gap-1.5 text-xs text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx($2,{className:"h-3.5 w-3.5"}),"Times shown in ",C.replace(/_/g," "),pP(C)?` (${pP(C)})`:""," · change"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>S(!0),className:"rounded-full","aria-label":"Calendar settings",children:[e.jsx(qc,{className:"h-4 w-4 mr-2"}),"Settings"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>Y(),disabled:H,className:"rounded-full",children:[e.jsx(uo,{className:At("h-4 w-4 mr-2",H&&"animate-spin")}),"Refresh"]}),e.jsxs(B,{size:"sm",className:"rounded-full",onClick:()=>E(),children:[e.jsx(rn,{className:"h-4 w-4 mr-1.5"}),"New appointment"]}),e.jsxs(B,{variant:"outline",size:"sm",className:"rounded-full",onClick:()=>s("/mission-control/scheduler"),children:["Scheduler settings",e.jsx(La,{className:"h-4 w-4 ml-2"})]})]})]}),e.jsxs("div",{className:"mt-4 flex flex-wrap items-center gap-2",children:[ne?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(Er,{className:"h-3.5 w-3.5"}),"Google Calendar connected",((Ae=I.status.data)==null?void 0:Ae.account_email)&&e.jsxs("span",{className:"opacity-70",children:["· ",I.status.data.account_email]})]}):e.jsxs("button",{onClick:()=>I.connect.mutate(),disabled:I.connect.isPending,className:"inline-flex items-center gap-2 rounded-full px-3 py-1.5 text-xs font-medium border border-dashed hover:bg-accent transition-colors",children:[e.jsx(pc,{className:"h-3.5 w-3.5"}),I.connect.isPending?"Opening Google…":"Connect Google Calendar"]}),(G==null?void 0:G.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"}),G.google.error]})]})]}),!ne&&!I.status.isLoading&&e.jsxs("div",{className:"border-t px-5 py-4 md:px-7 flex flex-wrap items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-start gap-3 min-w-0",children:[e.jsx("div",{className:"h-10 w-10 rounded-xl flex items-center justify-center shrink-0",style:{background:"#4285F41A"},children:e.jsx(pc,{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(B,{onClick:()=>I.connect.mutate(),disabled:I.connect.isPending,className:"rounded-full",children:"Connect Google Calendar"})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(B,{variant:"outline",size:"icon",className:"rounded-full h-9 w-9",onClick:()=>he(-1),children:e.jsx($c,{className:"h-4 w-4"})}),e.jsx(B,{variant:"outline",size:"icon",className:"rounded-full h-9 w-9",onClick:()=>he(1),children:e.jsx(xi,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"sm",className:"rounded-full",onClick:()=>{a(nQ(BT())),u(BT())},children:"Today"}),e.jsx("h2",{className:"text-lg font-semibold ml-1 text-foreground",children:me})]}),e.jsx("div",{className:"inline-flex rounded-full border p-1 bg-card",children:["month","week","day","agenda"].map(Pe=>e.jsx("button",{onClick:()=>{Pe==="day"&&a(nQ(d||BT())),l(Pe)},className:At("px-3.5 py-1.5 text-xs font-medium rounded-full capitalize transition-all",i===Pe?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:Pe},Pe))})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:LZe.map(Pe=>{const ze=Pe.id==="google"?!ne:o[Pe.id],ke=Pe.icon;return e.jsxs("button",{onClick:()=>pe(Pe.id),className:At("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",ze&&"border-dashed opacity-70"),style:ze?void 0:{background:Pe.soft,borderColor:`${Pe.color}55`,color:Pe.color},children:[e.jsx(ke,{className:"h-3.5 w-3.5"}),Pe.label,Pe.id==="google"&&!ne&&e.jsx("span",{className:"opacity-70",children:"· connect"})]},Pe.id)})}),Z&&e.jsx(ve,{className:"p-4 border-destructive/40",children:e.jsx("p",{className:"text-sm text-destructive",children:Z.message})}),e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-[minmax(0,1fr)_320px] gap-5",children:[e.jsx(ve,{className:"rounded-2xl overflow-hidden shadow-sm",children:$?e.jsx("div",{className:"p-6 space-y-3",children:Array.from({length:6}).map((Pe,ze)=>e.jsx(cn,{className:"h-16 w-full"},ze))}):i==="agenda"?e.jsx(Oyr,{items:ce,today:ae,onOpenItem:M}):i==="day"?e.jsx(zyr,{dayKey:Aw(r),items:ie.get(Aw(r))||[],today:ae,onCreate:E,onOpenItem:M}):e.jsx(Fyr,{days:V,byDay:ie,anchorMonth:r.getMonth(),today:ae,week:i==="week",selectedDay:d,onSelectDay:u,onOpenDay:P,onCreate:E,onOpenItem:M})}),e.jsxs("div",{className:"space-y-4",children:[i!=="day"&&te.length>0&&e.jsxs(ve,{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(pc,{className:"h-4 w-4 text-primary"})," ",Yse(d)]}),e.jsxs(B,{size:"sm",variant:"ghost",className:"rounded-full h-7 px-2 text-xs",onClick:()=>P(d),children:["Day view ",e.jsx(La,{className:"h-3 w-3 ml-1"})]})]}),e.jsx("div",{className:"space-y-2",children:te.map(Pe=>e.jsx(IUe,{item:Pe,onOpen:s},Pe.id))})]}),e.jsxs(ve,{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(Gr,{className:"h-4 w-4 text-primary"})," Up next"]}),le.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:le.map(Pe=>e.jsx(IUe,{item:Pe,onOpen:s},Pe.id))})]}),be.length>0&&e.jsxs(ve,{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:be.map(Pe=>e.jsx(IUe,{item:Pe,onOpen:s,overdue:!0},Pe.id))})]}),e.jsxs(ve,{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:LZe.filter(Pe=>!o[Pe.id]).map(Pe=>{const ze=ce.filter(ke=>ke.layer===Pe.id).length;return ze?e.jsxs("div",{className:"rounded-xl px-3 py-2",style:{background:Pe.soft},children:[e.jsx("p",{className:"text-lg font-semibold",style:{color:Pe.color},children:ze}),e.jsx("p",{className:"text-[11px] text-muted-foreground leading-tight",children:Pe.label})]},Pe.id):null})})]})]})]})]}),e.jsx(Lyr,{open:h,onOpenChange:m,defaultDate:p,defaultTime:y,appointment:g,googleConnected:ne,onSaved:()=>Y()}),e.jsx(Yqt,{open:j,onOpenChange:S})]})}function IUe({item:s,onOpen:t,overdue:n}){const r=vDe[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:[Yse(s.date),s.start&&!s.allDay?` · ${sot(s.start)}`:"",s.subtitle?` · ${s.subtitle}`:""]})]}),n&&e.jsx(Oe,{variant:"destructive",className:"text-[10px]",children:"Overdue"})]})}function IZe({item:s,onOpen:t}){var c,d;const n=vDe[s.layer],r=s.layer==="tasks"?!!((c=s.meta)!=null&&c.done):!!((d=s.meta)!=null&&d.completed),a=At("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:sot(s.start)}),e.jsx("span",{className:"truncate",children:s.title}),s.externalLink&&!s.link&&e.jsx(wr,{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 Fyr({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:At("grid grid-cols-7",a?"min-h-[520px]":""),children:s.map(h=>{const m=Aw(h),p=t.get(m)||[],f=m===r,y=!a&&h.getMonth()!==n;return e.jsxs("div",{role:"button",tabIndex:0,onClick:()=>l(m),onKeyDown:v=>{v.key==="Enter"&&l(m)},onDoubleClick:()=>o==null?void 0:o(m),className:At("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]",y&&"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:v=>{v.stopPropagation(),o?o(m):l(m)},className:At("inline-flex h-6 min-w-6 px-1.5 items-center justify-center rounded-full text-xs font-semibold transition-colors hover:bg-primary/15",f?"bg-primary text-primary-foreground hover:bg-primary":y?"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:v=>{v.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(rn,{className:"h-3.5 w-3.5"})})]})]}),e.jsxs("div",{className:"space-y-1",children:[p.slice(0,u).map(v=>e.jsx(IZe,{item:v,onOpen:d},v.id)),p.length>u&&e.jsxs("button",{type:"button",onClick:v=>{v.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 Oyr({items:s,today:t,onOpenItem:n}){const r=_.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:At("text-sm font-semibold",a===t?"text-primary":"text-foreground"),children:Yse(a)}),a===t&&e.jsx(Oe,{className:"text-[10px]",children:"Today"})]}),e.jsx("div",{className:"space-y-2",children:i.map(l=>{const o=vDe[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":sot(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(Oe,{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(pc,{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 UAt=6,qAt=22,sX=60;function Sue(s){var a,i;const t=new Intl.DateTimeFormat("en-US",{timeZone:RE(),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 zyr({dayKey:s,items:t,today:n,onCreate:r,onOpenItem:a}){const[i,l]=_.useState(()=>Sue(new Date().toISOString()));_.useEffect(()=>{const S=setInterval(()=>l(Sue(new Date().toISOString())),6e4);return()=>clearInterval(S)},[]);const o=t.filter(S=>S.allDay||!S.start),c=t.filter(S=>!S.allDay&&S.start).map(S=>{const C=Sue(S.start),E=S.end?Math.max(Sue(S.end),C+15):C+30;return{item:S,start:C,end:E}}).sort((S,C)=>S.start-C.start||S.end-C.end),d=[];let u=[];const h=()=>{if(!u.length)return;const S=[];u.map(E=>{let P=S.findIndex(M=>M<=E.start);return P===-1?(P=S.length,S.push(E.end)):S[P]=E.end,{...E,col:P}}).forEach(E=>d.push({...E,cols:S.length})),u=[]};let m=-1;for(const S of c)u.length&&S.start>=m&&h(),u.push(S),m=Math.max(m,S.end);h();const p=c.length?Math.min(...c.map(S=>S.start)):UAt*60,f=c.length?Math.max(...c.map(S=>S.end)):qAt*60,y=Math.min(UAt,Math.floor(p/60)),v=Math.max(qAt,Math.ceil(f/60)),g=Array.from({length:v-y+1},(S,C)=>y+C),b=S=>(S-y*60)/60*sX,j=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:Yse(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(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>r(s),children:[e.jsx(rn,{className:"h-4 w-4 mr-1.5"})," Add"]})]}),o.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-1.5 border-b px-4 py-2.5 bg-background",children:[e.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-wide text-muted-foreground mr-1 self-center",children:"All day"}),o.map(S=>e.jsx("span",{className:"max-w-[240px]",children:e.jsx(IZe,{item:S,onOpen:a})},S.id))]}),e.jsx("div",{className:"relative overflow-y-auto max-h-[640px] pt-3 pb-4",children:e.jsxs("div",{className:"relative",style:{height:g.length*sX},children:[g.map((S,C)=>e.jsxs("div",{className:"absolute left-0 right-0 border-t border-border/60",style:{top:C*sX,height:sX},children:[e.jsx("span",{className:"absolute -top-2 left-2 text-[10px] font-medium text-muted-foreground w-14",children:new Intl.DateTimeFormat("en-US",{hour:"numeric"}).format(new Date(2e3,0,1,S)).toLowerCase()}),e.jsx("button",{type:"button","aria-label":`Create at ${S}:00`,onClick:()=>r==null?void 0:r(s,`${`${S}`.padStart(2,"0")}:00`),className:"absolute left-16 right-2 top-0 h-full rounded-md hover:bg-accent/50 transition-colors"})]},S)),j&&i>=y*60&&i<=v*60&&e.jsxs("div",{className:"absolute left-14 right-2 z-20 pointer-events-none",style:{top:b(i)},children:[e.jsx("div",{className:"h-px bg-destructive"}),e.jsx("div",{className:"absolute -left-1.5 -top-1 h-2.5 w-2.5 rounded-full bg-destructive"})]}),d.map(({item:S,start:C,end:E,col:P,cols:M})=>{const I=vDe[S.layer],D=Math.max(22,(E-C)/60*sX-4),O=100/M;return e.jsx("div",{className:"absolute z-10",style:{top:b(C)+2,height:D,left:`calc(4rem + ${P*O}% * 0.92)`,width:`calc(${O}% * 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(IZe,{item:S,onOpen:a}),D>44&&S.subtitle&&e.jsx("p",{className:"text-[10px] text-muted-foreground truncate pl-1.5 mt-0.5",children:S.subtitle})]})},S.id)})]})})]})}function Cue(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 Byr(s){const[t,n,r]=s.split(/[-/T]/).map(Number);return Hs(new Date(t,n-1,r),"EEEE, MMMM d, yyyy")}function Uyr(){var ce;const{token:s}=Li(),[t]=Yl(),[n,r]=_.useState(null),[a,i]=_.useState(!0),[l,o]=_.useState(null),[c,d]=_.useState("details"),[u,h]=_.useState(!1),[m,p]=_.useState(""),[f,y]=_.useState(null),[v,g]=_.useState(new Date),[b,j]=_.useState({}),[S,C]=_.useState(!1),[E,P]=_.useState(null),[M,I]=_.useState(null),D=async ie=>{var le,be;const{data:te,error:ae}=await q.functions.invoke("agent-booking",{body:ie});if(ae){let me=ae.message;try{const he=await((be=(le=ae.context)==null?void 0:le.json)==null?void 0:be.call(le));he!=null&&he.error&&(me=he.error)}catch{}throw new Error(me)}if(te!=null&&te.error)throw new Error(te.error);return te};_.useEffect(()=>{s&&(async()=>{try{const ie=await D({action:"manage_get",manage_token:s});r(ie),t.get("cancel")==="1"&&d("cancel")}catch(ie){o(ie.message)}finally{i(!1)}})()},[s]),_.useEffect(()=>{if(c!=="reschedule"||!(n!=null&&n.booking_type))return;let ie=!1;return(async()=>{C(!0);try{const te=new Date(v.getFullYear(),v.getMonth(),1),ae=If(new Date),le=Z4(ae,te)?ae:te,be=new Date(v.getFullYear(),v.getMonth()+1,0),me=Math.max(1,Math.round((be.getTime()-le.getTime())/864e5)+1),he=await D({action:"availability",slug:n.slug,booking_type_id:n.booking_type.id,start:Hs(le,"yyyy-MM-dd"),days:Math.min(me,90),ignore_booking_id:n.booking.id});ie||j((he==null?void 0:he.availability)||{})}catch(te){ie||se.error(te.message)}finally{ie||C(!1)}})(),()=>{ie=!0}},[c,v,(ce=n==null?void 0:n.booking_type)==null?void 0:ce.id]);const O=_.useMemo(()=>{const ie=v.getFullYear(),te=v.getMonth(),ae=new Date(ie,te,1),le=new Date(ie,te+1,0),be=[];for(let me=0;me{h(!0);try{await D({action:"manage_cancel",manage_token:s,reason:m}),y("cancelled"),d("done")}catch(ie){se.error(ie.message)}finally{h(!1)}},$=async()=>{if(!(!E||!M)){h(!0);try{await D({action:"manage_reschedule",manage_token:s,date:Hs(E,"yyyy-MM-dd"),time:M}),y("rescheduled"),d("done")}catch(ie){se.error(ie.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(Ct,{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(Rd,{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:H,booking_type:Y,agent:Z}=n,ne=H.status==="cancelled";return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-[#f0f4f8] via-white to-[#e8f0f8] py-10 px-4",children:e.jsxs("div",{className:"max-w-lg mx-auto",children:[e.jsxs("div",{className:"bg-white rounded-2xl shadow-xl overflow-hidden",children:[e.jsxs("div",{className:"bg-gradient-to-br from-[#406E71] to-[#2a4c64] px-8 py-7 text-center",children:[e.jsx("h1",{className:"text-xl font-bold text-white",children:c==="done"?f==="cancelled"?"Booking cancelled":"Booking rescheduled":"Manage your booking"}),e.jsxs("p",{className:"text-white/80 text-sm mt-1",children:[(Y==null?void 0:Y.name)||"Meeting",Z!=null&&Z.name?` with ${Z.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(pc,{className:"h-4 w-4 text-[#406E71]"}),Byr(H.booking_date)]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-slate-600",children:[e.jsx(Gr,{className:"h-4 w-4 text-[#406E71]"}),Cue(String(H.start_time).slice(0,5))," –"," ",Cue(String(H.end_time).slice(0,5)),e.jsxs("span",{className:"text-xs text-slate-400",children:["(",n.timezone.replace(/_/g," "),")"]})]}),ne&&e.jsx("p",{className:"text-xs font-semibold text-red-600 pt-1",children:"This booking is cancelled."})]}),c==="details"&&!ne&&e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[n.allow_reschedule&&e.jsx(B,{className:"h-12 rounded-xl bg-[#406E71] hover:bg-[#365c5e] text-white font-semibold",onClick:()=>d("reschedule"),children:"Reschedule"}),n.allow_cancel&&e.jsx(B,{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"&&!ne&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-sm text-slate-600",children:["Let ",(Z==null?void 0:Z.name)||"your host"," know why you can't make it (optional)."]}),e.jsx(Ms,{value:m,onChange:ie=>p(ie.target.value),placeholder:"Something came up…",className:"rounded-xl",rows:3}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx(B,{variant:"ghost",className:"flex-1 h-11 rounded-xl",onClick:()=>d("details"),disabled:u,children:"Keep booking"}),e.jsx(B,{className:"flex-1 h-11 rounded-xl bg-red-600 hover:bg-red-700 text-white font-semibold",onClick:G,disabled:u,children:u?e.jsx(Ct,{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:()=>g(new Date(v.getFullYear(),v.getMonth()-1,1)),children:e.jsx($c,{className:"h-4 w-4 text-slate-500"})}),e.jsx("span",{className:"text-sm font-semibold text-slate-800",children:Hs(v,"MMMM yyyy")}),e.jsx("button",{className:"p-2 rounded-lg hover:bg-slate-100",onClick:()=>g(new Date(v.getFullYear(),v.getMonth()+1,1)),children:e.jsx(xi,{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((ie,te)=>e.jsx("div",{className:"text-[11px] font-semibold text-slate-400 py-1",children:ie},te)),O.map((ie,te)=>{if(!ie)return e.jsx("div",{},`p${te}`);const ae=Hs(ie,"yyyy-MM-dd"),le=(b[ae]||[]).length>0&&!yS(ie,If(new Date)),be=E&&cm(ie,E);return e.jsx("button",{disabled:!le,onClick:()=>{P(ie),I(null)},className:`aspect-square rounded-lg text-sm font-medium transition-colors ${be?"bg-[#406E71] text-white":le?"bg-[#406E71]/10 text-[#406E71] hover:bg-[#406E71]/20":"text-slate-300"}`,children:ie.getDate()},ae)})]}),S&&e.jsxs("p",{className:"text-center text-xs text-slate-400 flex items-center justify-center gap-2",children:[e.jsx(Ct,{className:"h-3.5 w-3.5 animate-spin"})," Checking availability…"]}),E&&e.jsx("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-2 max-h-48 overflow-y-auto",children:V.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"}):V.map(ie=>e.jsx("button",{onClick:()=>I(ie),className:`px-3 py-2.5 rounded-xl text-sm font-medium ${M===ie?"bg-[#406E71] text-white":"bg-slate-50 text-slate-700 hover:bg-[#406E71]/10"}`,children:Cue(ie)},ie))}),e.jsx(B,{className:"w-full h-12 rounded-xl bg-[#406E71] hover:bg-[#365c5e] text-white font-semibold",disabled:!E||!M||u,onClick:$,children:u?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):"Confirm new time"}),e.jsxs("p",{className:"text-center text-[11px] text-slate-400",children:["Times shown in ",n.timezone.replace(/_/g," ")]})]}),c==="done"&&e.jsxs("div",{className:"text-center space-y-4 py-4",children:[f==="cancelled"?e.jsx(Rd,{className:"h-12 w-12 text-red-500 mx-auto"}):e.jsx(Er,{className:"h-12 w-12 text-emerald-500 mx-auto"}),e.jsx("p",{className:"text-sm text-slate-600",children:f==="cancelled"?`Your meeting has been cancelled and ${(Z==null?void 0:Z.name)||"your host"} has been notified.`:`Your meeting is now on ${E?Hs(E,"EEEE, MMMM d"):""} at ${M?Cue(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 $At=[{id:"buyer_seller",label:"Buyer / Seller Choice",description:`Visitors pick "I'm a Buyer" or "I'm a Seller" and get the matching form`},{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 qyr(){const{user:s}=hs(),t=ha(),{toast:n}=vi(),r=Fn(),a=Bt(),[i,l]=_.useState(!1),[o,c]=_.useState(null),[d,u]=_.useState(null),[h,m]=_.useState({title:"",description:"",page_type:"lead_capture"}),{data:p=[],isLoading:f}=at({queryKey:["landing-pages",t],queryFn:async()=>{const{data:b,error:j}=await q.from("landing_pages").select("*").eq("user_id",t).is("deleted_at",null).order("created_at",{ascending:!1});if(j)throw j;return b},enabled:!!t}),y=mt({mutationFn:async()=>{const b=h.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,"")+"-"+Date.now().toString(36),{data:j}=await q.from("profiles").select("name, phone, avatar_url, email").eq("id",t).single(),S=h.page_type==="just_listed"||h.page_type==="just_sold",{data:C,error:E}=await q.from("landing_pages").insert({user_id:t,title:h.title,description:h.description||null,page_type:h.page_type,slug:b,hero_headline:S?h.page_type==="just_listed"?"🏡 Just Listed":"🎉 Just Sold":h.page_type==="lead_magnet"?"📥 Free Download":h.page_type==="buyer_seller"?"Buying or selling?":h.title,hero_subtext:h.page_type==="buyer_seller"?"Tell me which one you are and I’ll take it from there.":null,agent_name:(j==null?void 0:j.name)||null,agent_phone:(j==null?void 0:j.phone)||null,agent_email:(j==null?void 0:j.email)||s.email||null,agent_photo_url:(j==null?void 0:j.avatar_url)||null,property_status:S?h.page_type.replace("just_",""):null}).select().single();if(E)throw E;const P=$yr(h.page_type);if(P.length>0){const{error:M}=await q.from("landing_page_fields").insert(P.map((I,D)=>({...I,page_id:C.id,sort_order:D})));if(M)throw M}return C},onSuccess:b=>{a.invalidateQueries({queryKey:["landing-pages"]}),l(!1),m({title:"",description:"",page_type:"lead_capture"}),n({title:"Landing page created!"}),r(`/mission-control/landing-pages/${b.id}`)},onError:b=>n({title:"Error",description:b.message,variant:"destructive"})}),v=mt({mutationFn:async b=>{const{error:j}=await q.from("landing_pages").update({deleted_at:new Date().toISOString(),is_published:!1}).eq("id",b);if(j)throw j},onSuccess:()=>{a.invalidateQueries({queryKey:["landing-pages"]}),c(null),n({title:"Landing page deleted"})}}),g=b=>`https://pages.relevelup.com/${b}`;return e.jsxs(zs,{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(B,{variant:"outline",onClick:()=>r("/mission-control/landing-pages/defaults"),children:[e.jsx(qc,{className:"h-4 w-4 mr-2"})," Defaults"]}),e.jsxs(B,{onClick:()=>l(!0),children:[e.jsx(rn,{className:"h-4 w-4 mr-2"})," New Page"]})]})]}),f?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):p.length===0?e.jsx(ve,{children:e.jsxs(Me,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx(Fr,{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(B,{onClick:()=>l(!0),children:[e.jsx(rn,{className:"h-4 w-4 mr-2"})," Create Landing Page"]})]})}):e.jsx("div",{className:"grid gap-4",children:p.map(b=>{var j;return e.jsx(ve,{className:"hover:shadow-md transition-shadow",children:e.jsx(Me,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0 cursor-pointer",onClick:()=>r(`/mission-control/landing-pages/${b.id}`),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold truncate",children:b.title}),e.jsx(Oe,{variant:b.is_published?"default":"secondary",className:"text-[10px]",children:b.is_published?"Published":"Draft"}),e.jsx(Oe,{variant:"outline",className:"text-[10px]",children:((j=$At.find(S=>S.id===b.page_type))==null?void 0:j.label)||b.page_type})]}),b.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1 truncate",children:b.description}),e.jsxs("div",{className:"flex items-center gap-4 mt-2 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ya,{className:"h-3 w-3"})," ",b.view_count," views"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Fr,{className:"h-3 w-3"})," ",b.submission_count," submissions"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 ml-4",children:[b.is_published&&e.jsxs(e.Fragment,{children:[e.jsx(B,{size:"sm",variant:"outline",onClick:()=>u(g(b.slug)),children:e.jsx(Hf,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"sm",variant:"outline",onClick:()=>{navigator.clipboard.writeText(g(b.slug)),n({title:"Link copied!"})},children:e.jsx(Ia,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"sm",variant:"outline",asChild:!0,children:e.jsx("a",{href:g(b.slug),target:"_blank",rel:"noopener noreferrer",children:e.jsx(wr,{className:"h-3.5 w-3.5"})})})]}),e.jsxs(tu,{children:[e.jsx(su,{asChild:!0,children:e.jsx(B,{size:"sm",variant:"ghost",children:e.jsx(Xx,{className:"h-4 w-4"})})}),e.jsxs(Od,{align:"end",children:[e.jsxs(ca,{onClick:()=>r(`/mission-control/landing-pages/${b.id}`),children:[e.jsx(Ya,{className:"h-3.5 w-3.5 mr-2"})," Edit"]}),e.jsxs(ca,{onClick:()=>c(b.id),className:"text-destructive",children:[e.jsx(Sn,{className:"h-3.5 w-3.5 mr-2"})," Delete"]})]})]})]})]})})},b.id)})})]}),e.jsx(Ls,{open:i,onOpenChange:l,children:e.jsxs(Ps,{children:[e.jsx(Os,{children:e.jsx(Ds,{children:"Create Landing Page"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Page Title"}),e.jsx(xe,{value:h.title,onChange:b=>m(j=>({...j,title:b.target.value})),placeholder:"e.g. Veterans Home & Land Expo"})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Description (optional)"}),e.jsx(Ms,{value:h.description,onChange:b=>m(j=>({...j,description:b.target.value})),placeholder:"Brief internal description...",rows:2})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Page Template"}),e.jsxs(is,{value:h.page_type,onValueChange:b=>m(j=>({...j,page_type:b})),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsx(as,{children:$At.map(b=>e.jsx(He,{value:b.id,children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:b.label}),e.jsx("div",{className:"text-xs text-muted-foreground",children:b.description})]})},b.id))})]})]})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(B,{onClick:()=>y.mutate(),disabled:!h.title.trim()||y.isPending,children:y.isPending?"Creating...":"Create Page"})]})]})}),e.jsx(Kl,{open:!!o,onOpenChange:()=>c(null),children:e.jsxs(Ol,{children:[e.jsxs(zl,{children:[e.jsx(Ul,{children:"Delete Landing Page?"}),e.jsx(ql,{children:"This will permanently delete this page and all its submissions."})]}),e.jsxs(Bl,{children:[e.jsx($l,{children:"Cancel"}),e.jsx(Ml,{onClick:()=>o&&v.mutate(o),children:"Delete"})]})]})}),e.jsx(Ls,{open:!!d,onOpenChange:()=>u(null),children:e.jsxs(Ps,{className:"max-w-sm",children:[e.jsx(Os,{children:e.jsx(Ds,{children:"QR Code"})}),e.jsxs("div",{className:"flex flex-col items-center gap-4 py-4",children:[d&&e.jsx(AN,{value:d,size:240}),e.jsx("p",{className:"text-xs text-muted-foreground text-center break-all",children:d}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>{d&&(navigator.clipboard.writeText(d),n({title:"URL copied!"}))},children:[e.jsx(Ia,{className:"h-3.5 w-3.5 mr-1"})," Copy URL"]})]})]})})]})}function $yr(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"buyer_seller":return[...t.map(n=>({...n,field_group:"default"})),{field_type:"text",label:"Areas or neighborhoods you love",placeholder:"Downtown, Eastside...",is_required:!1,field_group:"buyer"},{field_type:"select",label:"Price range",options:JSON.stringify(["Under $200k","$200k - $350k","$350k - $500k","$500k - $750k","$750k+"]),is_required:!1,field_group:"buyer"},{field_type:"select",label:"When would you like to move?",options:JSON.stringify(["ASAP","1-3 months","3-6 months","6+ months","Just exploring"]),is_required:!1,field_group:"buyer"},{field_type:"toggle",label:"Do you need help with financing?",is_required:!1,field_group:"buyer"},{field_type:"text",label:"Property address",placeholder:"123 Main St, City, State",is_required:!0,field_group:"seller"},{field_type:"select",label:"Property type",options:JSON.stringify(["Single family","Condo / Townhome","Multi-family","Land","Other"]),is_required:!1,field_group:"seller"},{field_type:"select",label:"When are you hoping to sell?",options:JSON.stringify(["ASAP","1-3 months","3-6 months","6+ months","Just curious"]),is_required:!1,field_group:"seller"},{field_type:"textarea",label:"Recent updates or anything I should know?",placeholder:"New roof, remodeled kitchen...",is_required:!1,field_group:"seller"}];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}]}}const L5=s=>s.replace(/&/g,"&").replace(//g,">").replace(/"/g,"""),Aue=s=>"$"+Math.round(s).toLocaleString("en-US"),VAt=s=>s.replace(/_/g," ").replace(/\b\w/g,t=>t.toUpperCase());function Vyr(s){var a;const t=[],n=[...s.cities??[],...s.zip_codes??[]].filter(Boolean);if(n.length&&t.push(`Area: ${n.join(", ")}`),(a=s.property_types)!=null&&a.length&&t.push(`Home type: ${s.property_types.map(VAt).join(", ")}`),s.min_beds&&t.push(`${s.min_beds}+ bedrooms`),s.min_baths&&t.push(`${s.min_baths}+ bathrooms`),s.min_sqft||s.max_sqft){const i=s.min_sqft&&s.max_sqft?`${s.min_sqft.toLocaleString()}–${s.max_sqft.toLocaleString()} sq ft`:s.min_sqft?`${s.min_sqft.toLocaleString()}+ sq ft`:`Up to ${s.max_sqft.toLocaleString()} sq ft`;t.push(i)}if(s.show_max_budget&&(s.min_budget||s.max_budget)){const i=s.min_budget&&s.max_budget?`${Aue(s.min_budget)}–${Aue(s.max_budget)}`:s.min_budget?`${Aue(s.min_budget)}+`:`Up to ${Aue(s.max_budget)}`;t.push(`Budget: ${i}`)}s.timeline&&t.push(`Timing: ${s.timeline}`);const r=s.features;if(r&&typeof r=="object"){const i=[];for(const[l,o]of Object.entries(r))(o==="required"||o===!0)&&i.push(VAt(l));i.length&&t.push(`Must have: ${i.join(", ")}`)}return t}function Hyr(s,t,n){var d,u,h;const r=((d=s.headline)==null?void 0:d.trim())||"I have a buyer looking for a home in your area",a=((u=s.description)==null?void 0:u.trim())||"One of my buyers is actively searching and hasn't found the right home yet. If your home is even close to what they're after, it's worth a look.",i=Vyr(s),l=((h=t==null?void 0:t.name)==null?void 0:h.trim())||"",o=[t==null?void 0:t.title,t==null?void 0:t.brokerage_name].filter(Boolean).join(" · "),c=i.map(m=>` ${L5(m)} `).join("");return`
${i.length?``:""}
Buyer looking in your neighborhood
${L5(r)}

Hi {{first_name}},

${L5(a)}

${c}
What they're looking for
See if your home fits
Takes about a minute. No account, no obligation, and no listing agreement.

If it isn't a fit, no problem at all — just reply and let me know, or pass this along to a neighbor who might be thinking about selling.

${t!=null&&t.avatar_url?``:""}
${L5(l)}
${L5(l)}
${o?`
${L5(o)}
`:""} ${t!=null&&t.phone?`
${L5(t.phone)}
`:""} ${t!=null&&t.email?``:""}
`.trim()}function mls({open:s,onOpenChange:t,campaign:n}){const{user:r}=hs(),a=ha(),{isReady:i,settings:l}=$9(),{data:o=[]}=rz(),{data:c=[]}=Pae(),{neighborhoods:d,unmappedCount:u}=Nnt(),[h,m]=_.useState(1),[p,f]=_.useState("all"),[y,v]=_.useState([]),[g,b]=_.useState([]),[j,S]=_.useState([]),[C,E]=_.useState(""),[P,M]=_.useState(""),[I,D]=_.useState(!1),[O,V]=_.useState(!1),[G,$]=_.useState(!1),H=n?`${window.location.origin}/buyer-match/${n.slug}?src=email`:"",{data:Y}=at({queryKey:["buyer-match-email-agent",a],enabled:!!a&&s,queryFn:async()=>{const{data:Se}=await q.from("profiles").select("name, title, email, phone, avatar_url, brokerage_name, email_signature").eq("id",a).maybeSingle();return Se}}),{data:Z=[],isLoading:ne}=at({queryKey:["buyer-match-email-contacts",a],enabled:!!a&&s,queryFn:async()=>{const Se=[];for(let Ne=0;;Ne+=1e3){const{data:Ye,error:Ve}=await q.from("innercircle_contacts").select("id, first_name, last_name, email, lead_source, lead_source_ref:lead_sources(name)").eq("owner_user_id",a).eq("email_opt_out",!1).not("email","is",null).neq("email","").order("first_name").range(Ne,Ne+1e3-1);if(Ve)throw Ve;const qe=Ye??[];if(Se.push(...qe),qe.length<1e3)break}return Se}}),{data:ce=[]}=at({queryKey:["ses-suppressed-emails-buyer-match"],enabled:s,queryFn:async()=>{const{data:Se}=await q.from("ses_suppressed_emails").select("email");return(Se||[]).map(Fe=>Fe.email.toLowerCase())}}),ie=_.useMemo(()=>{const Se=new Set;return Z.forEach(Fe=>{var Ye;const Ne=(((Ye=Fe.lead_source_ref)==null?void 0:Ye.name)||Fe.lead_source||"").trim();Ne&&Se.add(Ne)}),Array.from(Se).sort((Fe,Ne)=>Fe.localeCompare(Ne))},[Z]),te=_.useMemo(()=>{const Se=new Set(ce);return Z.filter(Fe=>{var Ne;return((Ne=Fe.email)==null?void 0:Ne.includes("@"))&&!Se.has(Fe.email.toLowerCase())})},[Z,ce]),ae=Z.length-te.length,le=_.useMemo(()=>{if(p==="all")return te;if(p==="neighborhoods"){const Fe=LYt(d,y);return Fe?te.filter(Ne=>Fe.has(Ne.id)):[]}if(p==="tags"){if(g.length===0)return[];const Fe=new Set;for(const Ne of c)g.includes(Ne.tag_id)&&Fe.add(Ne.contact_id);return te.filter(Ne=>Fe.has(Ne.id))}if(j.length===0)return[];const Se=new Set(j.map(Fe=>Fe.toLowerCase()));return te.filter(Fe=>{var Ne;return Se.has((((Ne=Fe.lead_source_ref)==null?void 0:Ne.name)||Fe.lead_source||"").trim().toLowerCase())})},[p,te,d,y,g,c,j]);_.useEffect(()=>{var Se;!s||!n||(m(1),f("all"),v([]),b([]),S([]),E((Se=n.headline)!=null&&Se.trim()?n.headline.trim().slice(0,120):"I have a buyer looking in your neighborhood"),M(Hyr(n,Y??null,H)))},[s,n==null?void 0:n.id,Y==null?void 0:Y.name]);const be=Y!=null&&Y.email_signature?`
${Y.email_signature}
`:"",me=`${P}${be}`,he=_.useMemo(()=>me.replace(/\{\{\s*first_name\s*\}\}/g,"Friend").replace(/\{\{\s*name\s*\}\}/g,"Friend"),[me]),Ce=`${((l==null?void 0:l.display_name)||"ReLevelUp").toLowerCase().replace(/[^a-z]/g,".")}@send.relevelup.com`,Ae=!!n&&n.status==="active"&&i&&!!C.trim()&&le.length>0&&!I,Pe=async()=>{const Se=(Y==null?void 0:Y.email)||(r==null?void 0:r.email);if(!Se){se.error("No email address on your profile to send a test to.");return}V(!0);try{const{data:Fe,error:Ne}=await q.functions.invoke("ses-send-campaign",{body:{action:"test_send",to:Se,from_email:Ce,subject:`[TEST] ${C}`,body_html:he,reply_to:(l==null?void 0:l.reply_to_email)||void 0}});if(Ne)throw Ne;if(Fe!=null&&Fe.error)throw new Error(Fe.error);se.success(`Test email sent to ${Se}`)}catch(Fe){se.error((Fe==null?void 0:Fe.message)||"Could not send the test email.")}finally{V(!1)}},ze=async()=>{if(!(!Ae||!n||!r)){$(!1),D(!0);try{const{data:Se,error:Fe}=await q.from("email_campaigns").insert({user_id:a||r.id,name:`Buyer Match: ${n.name}`,subject:C.trim(),body_html:me,from_email:Ce,reply_to_email:(l==null?void 0:l.reply_to_email)||null,total_recipients:le.length,status:"draft"}).select("id").single();if(Fe)throw Fe;const Ne=le.map(Ve=>({campaign_id:Se.id,contact_id:Ve.id,email:Ve.email,name:[Ve.first_name,Ve.last_name].filter(Boolean).join(" ")||null,status:"pending"}));for(let Ve=0;VeSe.includes(Fe)?Se.filter(Ne=>Ne!==Fe):[...Se,Fe];return e.jsxs(e.Fragment,{children:[e.jsx(Ls,{open:s,onOpenChange:Se=>!I&&t(Se),children:e.jsxs(Ps,{className:"max-w-4xl max-h-[92vh] overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsxs(Ds,{className:"flex items-center gap-2",children:[e.jsx(ln,{className:"h-5 w-5"})," Email this Buyer Match to your contacts"]}),e.jsxs(_r,{children:["Step ",h," of 3 — ",h===1?"choose who gets it":h===2?"write the email":"review and send"]})]}),!i&&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:"Verify your sender email before you can email your contacts."}),e.jsx(B,{size:"sm",className:"mt-3",onClick:()=>window.open("/mission-control/integrations#mass-email","_blank"),children:"Set up Mass Email →"})]})]}),n&&n.status!=="active"&&e.jsx("div",{className:"rounded-lg border border-amber-300 bg-amber-50 p-3 text-sm text-amber-900",children:"This campaign isn't live yet. Publish it first so the link in your email works."}),h===1&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs(Yr,{value:p,onValueChange:Se=>f(Se),children:[e.jsxs(Zr,{className:"grid grid-cols-4 w-full",children:[e.jsxs(Ht,{value:"all",children:[e.jsx(In,{className:"h-3.5 w-3.5 mr-1"})," Everyone"]}),e.jsxs(Ht,{value:"neighborhoods",children:[e.jsx(Xa,{className:"h-3.5 w-3.5 mr-1"})," Neighborhoods"]}),e.jsxs(Ht,{value:"tags",children:[e.jsx(Ep,{className:"h-3.5 w-3.5 mr-1"})," Tags"]}),e.jsx(Ht,{value:"lead_source",children:"Lead source"})]}),e.jsx(Gt,{value:"all",className:"pt-4 text-sm text-muted-foreground",children:"Everyone in your contacts with an email address who hasn't opted out."}),e.jsxs(Gt,{value:"neighborhoods",className:"pt-4",children:[d.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"You haven't drawn any neighborhoods yet. Draw one on the contacts map, then come back here."}):e.jsx("div",{className:"max-h-56 overflow-y-auto space-y-1 border rounded-md p-2",children:d.map(Se=>e.jsxs("button",{type:"button",onClick:()=>v(Fe=>Ze(Fe,Se.id)),className:"w-full flex items-center gap-2 px-2 py-1.5 rounded hover:bg-muted text-sm text-left",children:[e.jsx($a,{checked:y.includes(Se.id),className:"pointer-events-none"}),e.jsx("span",{className:"h-2.5 w-2.5 rounded-full",style:{backgroundColor:Se.color}}),e.jsx("span",{className:"flex-1 truncate",children:Se.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Se.count})]},Se.id))}),u>0&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:[u.toLocaleString()," contacts aren't mapped yet, so they can't be in a neighborhood."]})]}),e.jsx(Gt,{value:"tags",className:"pt-4",children:e.jsx("div",{className:"max-h-56 overflow-y-auto space-y-1 border rounded-md p-2",children:o.length===0?e.jsx("p",{className:"text-sm text-muted-foreground p-2",children:"No tags yet."}):o.map(Se=>e.jsxs("button",{type:"button",onClick:()=>b(Fe=>Ze(Fe,Se.id)),className:"w-full flex items-center gap-2 px-2 py-1.5 rounded hover:bg-muted text-sm text-left",children:[e.jsx($a,{checked:g.includes(Se.id),className:"pointer-events-none"}),e.jsx("span",{className:"flex-1 truncate",children:Se.name})]},Se.id))})}),e.jsx(Gt,{value:"lead_source",className:"pt-4",children:e.jsx("div",{className:"max-h-56 overflow-y-auto space-y-1 border rounded-md p-2",children:ie.length===0?e.jsx("p",{className:"text-sm text-muted-foreground p-2",children:"No lead sources on your contacts yet."}):ie.map(Se=>e.jsxs("button",{type:"button",onClick:()=>S(Fe=>Ze(Fe,Se)),className:"w-full flex items-center gap-2 px-2 py-1.5 rounded hover:bg-muted text-sm text-left",children:[e.jsx($a,{checked:j.includes(Se),className:"pointer-events-none"}),e.jsx("span",{className:"flex-1 truncate",children:Se})]},Se))})})]}),e.jsx(ve,{children:e.jsxs(Me,{className:"p-4 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-semibold",children:ne?"…":le.length.toLocaleString()}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"people will get this email"})]}),ae>0&&e.jsxs("div",{className:"text-xs text-muted-foreground text-right max-w-[240px]",children:[ae.toLocaleString()," contacts are excluded because they unsubscribed or their address bounced."]})]})})]}),h===2&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Subject"}),e.jsx(xe,{value:C,onChange:Se=>E(Se.target.value),maxLength:150})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Email"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Edit any of the wording. ",e.jsx("code",{children:"{{first_name}}"})," fills in each person's first name."]}),e.jsx(ent,{html:P,onChange:M})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Preview"}),e.jsx("div",{className:"border rounded-lg overflow-hidden bg-white max-h-[420px] overflow-y-auto",children:e.jsx("div",{dangerouslySetInnerHTML:{__html:he}})})]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:Pe,disabled:O||!C.trim(),children:[O?e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Or,{className:"h-4 w-4 mr-2"}),"Send myself a test"]})]}),h===3&&e.jsxs("div",{className:"space-y-3 text-sm",children:[e.jsx(ve,{children:e.jsxs(Me,{className:"p-4 space-y-2",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Sending to"}),e.jsxs("span",{className:"font-medium",children:[le.length.toLocaleString()," contacts"]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Audience"}),e.jsx("span",{className:"font-medium",children:ke})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Subject"}),e.jsx("span",{className:"font-medium truncate max-w-[60%]",children:C})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"From"}),e.jsx("span",{className:"font-medium",children:Ce})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Replies go to"}),e.jsx("span",{className:"font-medium",children:(l==null?void 0:l.reply_to_email)||"—"})]}),e.jsxs("div",{className:"flex justify-between gap-4",children:[e.jsx("span",{className:"text-muted-foreground",children:"Link"}),e.jsx("span",{className:"font-medium truncate",children:H})]})]})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Clicks from this email are tracked as email traffic on your campaign, separate from QR codes and social shares. Nothing sends until you press Send."}),e.jsx(Oe,{variant:"secondary",children:"Opens and clicks appear in Sent Emails"})]}),e.jsxs(yr,{className:"gap-2 sm:justify-between",children:[e.jsx(B,{variant:"outline",onClick:()=>h===1?t(!1):m(Se=>Se-1),disabled:I,children:h===1?"Cancel":e.jsxs(e.Fragment,{children:[e.jsx(ka,{className:"h-4 w-4 mr-1"})," Back"]})}),h<3?e.jsxs(B,{onClick:()=>m(Se=>Se+1),disabled:h===1&&le.length===0,children:["Next ",e.jsx(La,{className:"h-4 w-4 ml-1"})]}):e.jsxs(B,{onClick:()=>$(!0),disabled:!Ae,children:[I?e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Or,{className:"h-4 w-4 mr-2"}),"Send to ",le.length.toLocaleString()]})]})]})}),e.jsx(Kl,{open:G,onOpenChange:$,children:e.jsxs(Ol,{children:[e.jsxs(zl,{children:[e.jsx(Ul,{children:"Send this email now?"}),e.jsxs(ql,{children:["It goes to ",le.length.toLocaleString()," contacts right away and can't be recalled."]})]}),e.jsxs(Bl,{children:[e.jsx($l,{children:"Cancel"}),e.jsx(Ml,{onClick:ze,children:"Send it"})]})]})})]})}const Gyr={draft:"Draft",active:"Live",paused:"Paused",expired:"Expired",matched:"Buyer matched",archived:"Archived"};function Wyr(){const s=ha(),{toast:t}=vi(),n=Fn(),r=Bt(),[a,i]=_.useState(!1),[l,o]=_.useState(""),[c,d]=_.useState(null),[u,h]=_.useState(null),{data:m=[],isLoading:p}=at({queryKey:["buyer-match-campaigns",s],queryFn:async()=>{const{data:j,error:S}=await q.from("buyer_match_campaigns").select("*").eq("owner_user_id",s).order("created_at",{ascending:!1});if(S)throw S;return j??[]},enabled:!!s}),{data:f=[]}=at({queryKey:["buyer-match-inquiries-all",s],queryFn:async()=>{const{data:j,error:S}=await q.from("buyer_match_inquiries").select("id, campaign_id, stage, created_at").eq("owner_user_id",s);if(S)throw S;return j??[]},enabled:!!s}),y=_.useMemo(()=>{const j=m.filter(I=>I.status==="active").length,S=m.reduce((I,D)=>I+(D.view_count??0),0),C=m.reduce((I,D)=>I+(D.check_count??0),0),E=f.length,P=f.filter(I=>["conversation_started","appointment_scheduled","listing_opportunity","listing_signed"].includes(I.stage)).length,M=f.filter(I=>I.stage==="listing_signed").length;return{active:j,views:S,checks:C,leads:E,conversations:P,listings:M}},[m,f]),v=mt({mutationFn:async j=>{const{data:S,error:C}=await q.from("buyer_match_campaigns").insert({owner_user_id:s,name:j,slug:""}).select("id").single();if(C)throw C;return S.id},onSuccess:j=>{i(!1),o(""),n(`/mission-control/buyer-match/${j}`)},onError:j=>t({title:"Could not create it",description:j.message,variant:"destructive"})}),g=mt({mutationFn:async({id:j,patch:S})=>{const{error:C}=await q.from("buyer_match_campaigns").update(S).eq("id",j);if(C)throw C},onSuccess:()=>r.invalidateQueries({queryKey:["buyer-match-campaigns",s]}),onError:j=>t({title:"Could not update it",description:j.message,variant:"destructive"})}),b=j=>f.filter(S=>S.campaign_id===j).length;return e.jsxs(zs,{children:[e.jsxs("div",{className:"p-4 md:p-8 space-y-6 max-w-7xl mx-auto",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("h1",{className:"text-2xl md:text-3xl font-bold",children:"Buyer Match"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Have a buyer who can't find the right home? Turn their wish list into your next seller conversation."})]}),e.jsxs(B,{onClick:()=>i(!0),children:[e.jsx(rn,{className:"h-4 w-4 mr-2"})," Create Buyer Match Campaign"]})]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-6 gap-3",children:[{label:"Live campaigns",value:y.active,icon:In},{label:"Page visits",value:y.views,icon:ya},{label:"Home checks (anonymous)",value:y.checks,icon:Jr},{label:"Leads with contact details",value:y.leads,icon:Hi},{label:"Conversations started",value:y.conversations,icon:Hi},{label:"Listings signed",value:y.listings,icon:Jr}].map(j=>e.jsx(ve,{children:e.jsxs(Me,{className:"p-4",children:[e.jsx(j.icon,{className:"h-4 w-4 text-muted-foreground mb-2"}),e.jsx("div",{className:"text-2xl font-semibold",children:j.value}),e.jsx("div",{className:"text-xs text-muted-foreground leading-tight",children:j.label})]})},j.label))}),p?e.jsx("p",{className:"text-muted-foreground",children:"Loading…"}):m.length===0?e.jsx(ve,{children:e.jsxs(Me,{className:"p-10 text-center space-y-3",children:[e.jsx(In,{className:"h-10 w-10 mx-auto text-muted-foreground"}),e.jsx("h2",{className:"text-lg font-semibold",children:"No campaigns yet"}),e.jsx("p",{className:"text-muted-foreground max-w-md mx-auto",children:"Pick one real, active buyer, list what they're looking for, and share a page where homeowners can check whether their home fits."}),e.jsxs(B,{onClick:()=>i(!0),children:[e.jsx(rn,{className:"h-4 w-4 mr-2"})," Create your first campaign"]})]})}):e.jsx("div",{className:"grid gap-4 md:grid-cols-2",children:m.map(j=>{const C=j.status==="active"&&j.expires_at&&new Date(j.expires_at)n(`/mission-control/buyer-match/${j.id}`),children:[e.jsx(Ya,{className:"h-4 w-4 mr-2"})," Edit"]}),j.status!=="draft"&&e.jsxs(ca,{onClick:()=>window.open(`/buyer-match/${j.slug}`,"_blank"),children:[e.jsx(wr,{className:"h-4 w-4 mr-2"})," View public page"]}),e.jsxs(ca,{onClick:()=>n(`/mission-control/buyer-match/${j.id}?tab=share`),children:[e.jsx(bd,{className:"h-4 w-4 mr-2"})," Share kit"]}),j.status==="active"&&e.jsxs(ca,{onClick:()=>h(j.id),children:[e.jsx(ln,{className:"h-4 w-4 mr-2"})," Email my contacts"]}),j.status==="active"&&e.jsxs(ca,{onClick:()=>g.mutate({id:j.id,patch:{status:"paused"}}),children:[e.jsx(ky,{className:"h-4 w-4 mr-2"})," Pause"]}),(j.status==="paused"||C==="expired")&&e.jsxs(ca,{onClick:()=>d(j.id),children:[e.jsx(Jd,{className:"h-4 w-4 mr-2"})," Reactivate"]}),j.status!=="archived"&&e.jsxs(ca,{onClick:()=>g.mutate({id:j.id,patch:{status:"archived",archived_at:new Date().toISOString()}}),children:[e.jsx(by,{className:"h-4 w-4 mr-2"})," Archive"]})]})]})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 text-xs text-muted-foreground",children:[j.min_beds?e.jsxs("span",{children:[j.min_beds,"+ beds"]}):null,j.min_baths?e.jsxs("span",{children:[j.min_baths,"+ baths"]}):null,j.max_budget?e.jsxs("span",{children:["Up to $",Number(j.max_budget).toLocaleString()]}):null,j.timeline?e.jsx("span",{children:j.timeline}):null]}),e.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[e.jsxs("span",{children:[j.view_count??0," visits"]}),e.jsxs("span",{children:[j.check_count??0," home checks"]}),e.jsxs("span",{className:"font-medium",children:[b(j.id)," leads"]})]}),C==="expired"&&e.jsxs("p",{className:"text-xs text-amber-600 flex items-center gap-1",children:[e.jsx(uo,{className:"h-3 w-3"})," This campaign has ended. Reactivate it once you confirm the buyer is still looking."]}),j.expires_at&&C==="active"&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Runs through ",new Date(j.expires_at).toLocaleDateString("en-US",{timeZone:"America/New_York"})]})]})},j.id)})})]}),e.jsx(Ls,{open:a,onOpenChange:i,children:e.jsxs(Ps,{children:[e.jsxs(Os,{children:[e.jsx(Ds,{children:"New Buyer Match campaign"}),e.jsx(_r,{children:'Give it a name only you will see, like "Johnson family — ranch in Prospect".'})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Campaign name"}),e.jsx(xe,{value:l,onChange:j=>o(j.target.value),placeholder:"Buyer name or nickname"})]}),e.jsxs(yr,{children:[e.jsx(B,{variant:"outline",onClick:()=>i(!1),children:"Cancel"}),e.jsx(B,{disabled:!l.trim()||v.isPending,onClick:()=>v.mutate(l.trim()),children:"Continue"})]})]})}),e.jsx(Kl,{open:!!c,onOpenChange:j=>!j&&d(null),children:e.jsxs(Ol,{children:[e.jsxs(zl,{children:[e.jsx(Ul,{children:"Is this buyer still actively looking?"}),e.jsx(ql,{children:"Reactivating puts the page back online for another 30 days. Only do this if the buyer is still searching and still fine with you sharing their housing needs."})]}),e.jsxs(Bl,{children:[e.jsx($l,{children:"Cancel"}),e.jsx(Ml,{onClick:()=>{c&&(g.mutate({id:c,patch:{status:"active",verified_at:new Date().toISOString(),expires_at:new Date(Date.now()+30*864e5).toISOString(),expiry_notified_at:null}}),d(null))},children:"Yes, reactivate"})]})]})}),e.jsx(mls,{open:!!u,onOpenChange:j=>!j&&h(null),campaign:m.find(j=>j.id===u)??null})]})}const Kyr=[{key:"garage",label:"Garage"},{key:"fenced_yard",label:"Fenced yard"},{key:"single_story",label:"Single story"},{key:"home_office",label:"Home office"},{key:"pool",label:"Pool"},{key:"acreage",label:"Acreage"},{key:"basement",label:"Basement"},{key:"updated_kitchen",label:"Updated kitchen"}],not=[{key:"single_family",label:"Single family"},{key:"condo",label:"Condo"},{key:"townhouse",label:"Townhouse"},{key:"multi_family",label:"Multi-family"},{key:"land",label:"Land"},{key:"other",label:"Other"}],Eue=s=>String(s??"").trim().toLowerCase(),A2=s=>{if(s==null||s==="")return null;const t=Number(s);return Number.isFinite(t)?t:null};function DZe(s){var t;return((t=not.find(n=>n.key===s))==null?void 0:t.label)??(s||"Not provided")}function Yyr(s,t){const n=[],r=(s.cities||[]).filter(Boolean),a=(s.zip_codes||[]).filter(Boolean);if(r.length||a.length){const C=r.some(M=>Eue(M)===Eue(t.city)),E=a.some(M=>Eue(M)===Eue(t.zip)),P=!!(t.city||t.zip);n.push({label:"Location",required:!0,status:P?C||E?"pass":"fail":"unknown",detail:P?C||E?`${t.city||t.zip} is in this buyer's search area.`:`This buyer is searching ${[...r,...a].join(", ")}.`:"We need the city or ZIP code to compare."})}const i=(s.property_types||[]).filter(Boolean);if(i.length){const C=!!t.property_type;n.push({label:"Property type",required:!0,status:C?i.includes(t.property_type)?"pass":"fail":"unknown",detail:C?i.includes(t.property_type)?`${DZe(t.property_type)} is a fit.`:`This buyer is looking for ${i.map(DZe).join(", ")}.`:"Property type not provided."})}const l=A2(s.min_beds);if(l!==null){const C=A2(t.beds);n.push({label:"Bedrooms",required:!0,status:C===null?"unknown":C>=l?"pass":"fail",detail:C===null?`Buyer needs at least ${l} bedrooms.`:C>=l?`${C} bedrooms meets the minimum of ${l}.`:`Buyer needs at least ${l} bedrooms.`})}const o=A2(s.min_baths);if(o!==null){const C=A2(t.baths);n.push({label:"Bathrooms",required:!0,status:C===null?"unknown":C>=o?"pass":"fail",detail:C===null?`Buyer needs at least ${o} bathrooms.`:C>=o?`${C} bathrooms meets the minimum of ${o}.`:`Buyer needs at least ${o} bathrooms.`})}const c=A2(s.min_sqft),d=A2(s.max_sqft);if(c!==null||d!==null){const C=A2(t.sqft);let E="unknown";if(C!==null){const M=c===null||C>=c,I=d===null||C<=d;E=M&&I?"pass":"fail"}const P=c!==null&&d!==null?`${c.toLocaleString()}–${d.toLocaleString()} sq ft`:c!==null?`at least ${c.toLocaleString()} sq ft`:`up to ${d.toLocaleString()} sq ft`;n.push({label:"Square footage",required:!0,status:E,detail:C===null?`Buyer is looking for ${P}.`:E==="pass"?`${C.toLocaleString()} sq ft fits ${P}.`:`Buyer is looking for ${P}.`})}const u=A2(s.min_lot_size);if(u!==null){const C=A2(t.lot_size),E=s.lot_size_unit||"acres";n.push({label:"Lot size",required:!0,status:C===null?"unknown":C>=u?"pass":"fail",detail:C===null?`Buyer needs at least ${u} ${E}.`:C>=u?`${C} ${E} meets the minimum of ${u} ${E}.`:`Buyer needs at least ${u} ${E}.`})}const h=A2(s.max_budget),m=A2(s.min_budget);if(h!==null){const C=t.price_unknown?null:A2(t.expected_price);let E="unknown";if(C!==null){const P=C<=h,M=m===null||C>=m;E=P&&M?"pass":"fail"}n.push({label:"Price",required:!0,status:E,detail:C===null?"No expected price provided, so price has not been compared.":E==="pass"?"Your expected price is inside this buyer's range.":"Your expected price is outside this buyer's range."})}const p=t.features||{};for(const C of s.features||[]){const E=p[C.key];let P;!E||E==="unsure"?P="unknown":E==="yes"?P=C.required?"pass":"bonus":P=C.required?"fail":"missed",n.push({label:C.label,required:C.required,status:P,detail:C.required?P==="pass"?"Required by this buyer — your home has it.":P==="fail"?"Required by this buyer.":"Required by this buyer — not confirmed yet.":P==="bonus"?"Nice to have — your home has it.":P==="missed"?"Nice to have, not required.":"Nice to have — not confirmed yet."})}const f=n.filter(C=>C.required),y=f.filter(C=>C.status==="fail").length,v=f.filter(C=>C.status==="unknown").length,g=f.filter(C=>C.status==="pass").length;let b;return y===0&&v===0&&g>0?b="strong":y===0?b=v>0?"more_info":"strong":g>=y?b="partial":b="outside",f.length===0&&(b="more_info"),{level:b,headline:b==="strong"?"Potential strong fit":b==="partial"?"Some requirements line up":b==="more_info"?"More details needed":"Outside this buyer's current criteria",summary:b==="strong"?"Everything you shared lines up with what this buyer is looking for.":b==="partial"?"Parts of your home match what this buyer needs, and parts do not.":b==="more_info"?"A few details are still missing, so the comparison is incomplete.":"Based on what you shared, your home does not line up with this buyer's needs right now.",lines:n}}const Zyr=["Ready to buy now","Buying in the next 3 months","Buying in the next 6 months","Flexible timing"],Xyr=["facebook","instagram","email","postcard","door","qr"],Qyr=[["new_inquiry","New inquiry"],["contact_attempted","Contact attempted"],["conversation_started","Conversation started"],["appointment_scheduled","Appointment scheduled"],["listing_opportunity","Listing opportunity"],["listing_signed","Listing signed"],["closed","Closed"],["not_moving_forward","Not moving forward"]];function Jyr(){const{campaignId:s}=Li(),t=Fn(),{toast:n}=vi(),r=ha(),a=Bt(),[i]=Yl(),[l,o]=_.useState(null),[c,d]=_.useState(!1),[u,h]=_.useState(i.get("tab")||"needs"),[m,p]=_.useState(!1),{data:f}=at({queryKey:["buyer-match-campaign",s],queryFn:async()=>{const{data:$,error:H}=await q.from("buyer_match_campaigns").select("*").eq("id",s).maybeSingle();if(H)throw H;return $},enabled:!!s}),{data:y=[]}=at({queryKey:["buyer-match-contacts",r],queryFn:async()=>{const{data:$,error:H}=await q.from("innercircle_contacts").select("id, first_name, last_name").eq("owner_user_id",r).order("first_name").limit(1e3);if(H)throw H;return $??[]},enabled:!!r}),{data:v=[]}=at({queryKey:["buyer-match-inquiries",s],queryFn:async()=>{const{data:$,error:H}=await q.from("buyer_match_inquiries").select("*").eq("campaign_id",s).order("created_at",{ascending:!1});if(H)throw H;return $??[]},enabled:!!s});_.useEffect(()=>{f&&!l&&(o({...f}),d(!!f.verified_at))},[f,l]);const g=$=>o(H=>({...H??{},...$})),b=_.useMemo(()=>Array.isArray(l==null?void 0:l.features)?l.features:[],[l]),j=($,H)=>{const Y=b.find(Z=>Z.key===$);g(Y?{features:b.filter(Z=>Z.key!==$)}:{features:[...b,{key:$,label:H,required:!1}]})},S=($,H)=>g({features:b.map(Y=>Y.key===$?{...Y,required:H}:Y)}),C=f?`${window.location.origin}/buyer-match/${f.slug}`:"",E=_.useMemo(()=>{if(!l)return{headline:"",description:""};const $=[...l.cities??[],...l.zip_codes??[]].join(", "),H=`My buyer is looking for a home${$?` in ${$}`:""}`,Y=[l.min_beds?`${l.min_beds}+ bedrooms`:null,l.min_baths?`${l.min_baths}+ bathrooms`:null,l.min_sqft?`${Number(l.min_sqft).toLocaleString()}+ sq ft`:null,l.show_max_budget&&l.max_budget?`a budget up to $${Number(l.max_budget).toLocaleString()}`:null,...b.filter(ne=>ne.required).map(ne=>ne.label.toLowerCase())].filter(Boolean),Z=`I'm working with a buyer who is actively searching${$?` in ${$}`:""}${Y.length?` for ${Y.join(", ")}`:""}${l.timeline?`. Their timing: ${String(l.timeline).toLowerCase()}`:""}. If your home lines up, check below and I'll reach out personally — no obligation, no listing agreement needed to have a conversation.`;return{headline:H,description:Z}},[l,b]),P=mt({mutationFn:async $=>{const{error:H}=await q.from("buyer_match_campaigns").update($).eq("id",s);if(H)throw H},onSuccess:()=>{a.invalidateQueries({queryKey:["buyer-match-campaign",s]}),a.invalidateQueries({queryKey:["buyer-match-campaigns",r]}),n({title:"Saved"})},onError:$=>n({title:"Could not save",description:$.message,variant:"destructive"})}),M=()=>{if(!l)return{};const $=H=>H===""||H===null||H===void 0?null:Number(H);return{name:l.name,buyer_contact_id:l.buyer_contact_id||null,cities:l.cities??[],zip_codes:l.zip_codes??[],property_types:l.property_types??[],min_beds:$(l.min_beds),min_baths:$(l.min_baths),min_sqft:$(l.min_sqft),max_sqft:$(l.max_sqft),min_lot_size:$(l.min_lot_size),lot_size_unit:l.lot_size_unit||"acres",min_budget:$(l.min_budget),max_budget:$(l.max_budget),timeline:l.timeline||null,features:b,private_notes:l.private_notes||null,headline:l.headline||E.headline,description:l.description||E.description,show_max_budget:!!l.show_max_budget,create_task_on_inquiry:l.create_task_on_inquiry!==!1}},I=()=>{if(!c){n({title:"Please confirm the buyer is real and active",variant:"destructive"});return}P.mutate({...M(),status:"active",published_at:(f==null?void 0:f.published_at)??new Date().toISOString(),verified_at:new Date().toISOString(),verification_text:"This campaign represents a real, active buyer, and I have permission to market their housing needs without revealing their identity.",expires_at:new Date(Date.now()+30*864e5).toISOString()})},D=mt({mutationFn:async({id:$,stage:H})=>{const{error:Y}=await q.from("buyer_match_inquiries").update({stage:H,stage_updated_at:new Date().toISOString()}).eq("id",$);if(Y)throw Y},onSuccess:()=>a.invalidateQueries({queryKey:["buyer-match-inquiries",s]})}),O=$=>{navigator.clipboard.writeText($),n({title:"Copied"})},V=($,H,Y)=>e.jsx(xe,{value:($??[]).join(", "),placeholder:Y,onChange:Z=>H(Z.target.value.split(",").map(ne=>ne.trim()).filter(Boolean))});if(!l)return e.jsx(zs,{children:e.jsx("div",{className:"p-8 text-muted-foreground",children:"Loading…"})});const G={facebook:`${l.headline||E.headline}. ${l.description||E.description} See if your home fits: ${C}?src=facebook`,instagram:`${l.headline||E.headline} If your home lines up, tap the link in my bio or visit ${C}?src=instagram`,email:`Subject: I have a buyer looking in your neighborhood Hi there, ${l.description||E.description} You can see the details and check whether your home fits here: ${C}?src=email No obligation at all — I'm happy just to answer questions.`,postcard:`${l.headline||E.headline} See whether your home fits: ${C}?src=postcard`};return e.jsxs(zs,{children:[e.jsxs("div",{className:"p-4 md:p-8 space-y-6 max-w-5xl mx-auto",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs(B,{variant:"ghost",onClick:()=>t("/mission-control/buyer-match"),children:[e.jsx(ka,{className:"h-4 w-4 mr-2"})," Buyer Match"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[(f==null?void 0:f.status)!=="draft"&&e.jsxs(B,{variant:"outline",onClick:()=>window.open(`/buyer-match/${f==null?void 0:f.slug}`,"_blank"),children:[e.jsx(wr,{className:"h-4 w-4 mr-2"})," View page"]}),e.jsxs(B,{variant:"outline",onClick:()=>P.mutate(M()),disabled:P.isPending,children:[e.jsx(Ho,{className:"h-4 w-4 mr-2"})," Save"]}),e.jsxs(B,{onClick:I,disabled:P.isPending,children:[e.jsx(Sy,{className:"h-4 w-4 mr-2"})," ",(f==null?void 0:f.status)==="active"?"Save & republish":"Publish"]})]})]}),e.jsxs(Yr,{value:u,onValueChange:h,children:[e.jsxs(Zr,{className:"flex-wrap h-auto",children:[e.jsx(Ht,{value:"needs",children:"Buyer needs"}),e.jsx(Ht,{value:"copy",children:"Public wording"}),e.jsx(Ht,{value:"share",children:"Share kit"}),e.jsxs(Ht,{value:"leads",children:["Leads (",v.length,")"]})]}),e.jsx(Gt,{value:"needs",className:"space-y-4 mt-4",children:e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{children:"What this buyer is looking for"})}),e.jsxs(Me,{className:"space-y-4",children:[e.jsxs("div",{className:"grid md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Campaign name (private)"}),e.jsx(xe,{value:l.name??"",onChange:$=>g({name:$.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Link to a buyer in your contacts (optional)"}),e.jsxs(is,{value:l.buyer_contact_id??"none",onValueChange:$=>g({buyer_contact_id:$==="none"?null:$}),children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Not linked"})}),e.jsxs(as,{className:"max-h-72 overflow-y-auto",children:[e.jsx(He,{value:"none",children:"Not linked"}),y.map($=>e.jsx(He,{value:$.id,children:[$.first_name,$.last_name].filter(Boolean).join(" ")},$.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Cities / neighborhoods"}),V(l.cities,$=>g({cities:$}),"Prospect, Middletown")]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"ZIP codes"}),V(l.zip_codes,$=>g({zip_codes:$}),"40059, 40245")]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Property types"}),e.jsx("div",{className:"flex flex-wrap gap-3",children:not.map($=>e.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[e.jsx($a,{checked:(l.property_types??[]).includes($.key),onCheckedChange:H=>g({property_types:H?[...l.property_types??[],$.key]:(l.property_types??[]).filter(Y=>Y!==$.key)})}),$.label]},$.key))})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Min beds"}),e.jsx(xe,{type:"number",value:l.min_beds??"",onChange:$=>g({min_beds:$.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Min baths"}),e.jsx(xe,{type:"number",step:"0.5",value:l.min_baths??"",onChange:$=>g({min_baths:$.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Min sq ft"}),e.jsx(xe,{type:"number",value:l.min_sqft??"",onChange:$=>g({min_sqft:$.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Max sq ft"}),e.jsx(xe,{type:"number",value:l.max_sqft??"",onChange:$=>g({max_sqft:$.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Min lot size"}),e.jsx(xe,{type:"number",step:"0.1",value:l.min_lot_size??"",onChange:$=>g({min_lot_size:$.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Lot unit"}),e.jsxs(is,{value:l.lot_size_unit??"acres",onValueChange:$=>g({lot_size_unit:$}),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"acres",children:"acres"}),e.jsx(He,{value:"sq ft",children:"sq ft"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Min budget"}),e.jsx(xe,{type:"number",value:l.min_budget??"",onChange:$=>g({min_budget:$.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Max budget"}),e.jsx(xe,{type:"number",value:l.max_budget??"",onChange:$=>g({max_budget:$.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Timeline"}),e.jsxs(is,{value:l.timeline??"",onValueChange:$=>g({timeline:$}),children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Choose a timeline"})}),e.jsx(as,{children:Zyr.map($=>e.jsx(He,{value:$,children:$},$))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Features"}),e.jsx("div",{className:"grid sm:grid-cols-2 gap-2",children:Kyr.map($=>{const H=b.find(Y=>Y.key===$.key);return e.jsxs("div",{className:"flex items-center justify-between rounded-md border p-2",children:[e.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[e.jsx($a,{checked:!!H,onCheckedChange:()=>j($.key,$.label)}),$.label]}),H&&e.jsxs("label",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:["Must have",e.jsx(fn,{checked:H.required,onCheckedChange:Y=>S($.key,Y)})]})]},$.key)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Private notes (never shown publicly)"}),e.jsx(Ms,{value:l.private_notes??"",onChange:$=>g({private_notes:$.target.value}),rows:3})]}),e.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[e.jsx(fn,{checked:l.create_task_on_inquiry!==!1,onCheckedChange:$=>g({create_task_on_inquiry:$})}),"Create a follow-up task for me on every inquiry"]})]})]})}),e.jsx(Gt,{value:"copy",className:"space-y-4 mt-4",children:e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{children:"What homeowners will read"})}),e.jsxs(Me,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Headline"}),e.jsx(xe,{value:l.headline??"",placeholder:E.headline,onChange:$=>g({headline:$.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Description"}),e.jsx(Ms,{rows:6,value:l.description??"",placeholder:E.description,onChange:$=>g({description:$.target.value})}),e.jsx(B,{variant:"outline",size:"sm",onClick:()=>g(E),children:"Use suggested wording"})]}),e.jsxs("div",{className:"flex items-start gap-3 rounded-md border p-3",children:[e.jsx(fn,{checked:!!l.show_max_budget,onCheckedChange:$=>g({show_max_budget:$})}),e.jsxs("div",{className:"text-sm",children:[e.jsx("p",{className:"font-medium",children:"Show this buyer's budget publicly"}),e.jsx("p",{className:"text-muted-foreground",children:"Turning this on publishes the exact budget range on the page. Leave it off to keep it private."})]})]}),e.jsxs("label",{className:"flex items-start gap-2 text-sm",children:[e.jsx($a,{checked:c,onCheckedChange:$=>d(!!$),className:"mt-1"}),e.jsx("span",{children:"This campaign represents a real, active buyer, and I have permission to market their housing needs without revealing their identity."})]})]})]})}),e.jsx(Gt,{value:"share",className:"space-y-4 mt-4",children:(f==null?void 0:f.status)==="draft"?e.jsx(ve,{children:e.jsx(Me,{className:"p-6 text-muted-foreground",children:"Publish the campaign to get your link and QR codes."})}):e.jsxs(e.Fragment,{children:[e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{children:"Email your contacts"})}),e.jsxs(Me,{className:"flex flex-col sm:flex-row sm:items-center gap-3",children:[e.jsx("p",{className:"text-sm text-muted-foreground flex-1",children:"Send a branded email about this buyer to everyone, a neighborhood you've drawn on your contacts map, a tag, or a lead source."}),e.jsxs(B,{onClick:()=>p(!0),disabled:(f==null?void 0:f.status)!=="active",children:[e.jsx(ln,{className:"h-4 w-4 mr-2"})," Email my contacts"]})]})]}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{children:"Your link"})}),e.jsxs(Me,{className:"space-y-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{readOnly:!0,value:C}),e.jsx(B,{variant:"outline",onClick:()=>O(C),children:e.jsx(Ia,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-6 gap-4",children:Xyr.map($=>e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx("div",{className:"bg-background p-2 rounded border inline-block",children:e.jsx(AN,{value:`${C}?src=${$}`,size:96})}),e.jsx("p",{className:"text-xs capitalize text-muted-foreground",children:$})]},$))}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Each code tracks where the visit came from. Nothing posts, sends, prints, or orders anything automatically."})]})]}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{children:"Copy you can paste"})}),e.jsx(Me,{className:"space-y-4",children:Object.entries(G).map(([$,H])=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(J,{className:"capitalize",children:$}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>O(H),children:[e.jsx(Ia,{className:"h-4 w-4 mr-1"})," Copy"]})]}),e.jsx(Ms,{readOnly:!0,rows:$==="email"?7:4,value:H})]},$))})]})]})}),e.jsx(Gt,{value:"leads",className:"space-y-4 mt-4",children:v.length===0?e.jsx(ve,{children:e.jsx(Me,{className:"p-6 text-muted-foreground",children:"No inquiries yet."})}):v.map($=>{const H=$.comparison??{},Y=$.property??{},Z=`Hi ${$.first_name}, thanks for checking whether your home fits my buyer's search. Based on what you shared, ${String(H.summary??"").toLowerCase()} I'd love to talk through it — no obligation. When is a good time to connect?`;return e.jsx(ve,{children:e.jsxs(Me,{className:"p-5 space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold",children:[$.first_name,$.last_name].filter(Boolean).join(" ")}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[[$.email,$.phone].filter(Boolean).join(" · ")," · prefers ",$.preferred_contact]}),Y.address&&e.jsx("p",{className:"text-sm mt-1",children:[Y.address,Y.city,Y.state,Y.zip].filter(Boolean).join(", ")})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Oe,{children:H.headline??$.fit_level}),e.jsxs(is,{value:$.stage,onValueChange:ne=>D.mutate({id:$.id,stage:ne}),children:[e.jsx(rs,{className:"w-52",children:e.jsx(ls,{})}),e.jsx(as,{children:Qyr.map(([ne,ce])=>e.jsx(He,{value:ne,children:ce},ne))})]})]})]}),$.selling_intent&&e.jsxs("p",{className:"text-sm",children:["Selling interest: ",$.selling_intent.replace(/_/g," ")]}),$.message&&e.jsxs("p",{className:"text-sm italic",children:['"',$.message,'"']}),Array.isArray(H.lines)&&e.jsx("div",{className:"text-sm space-y-1",children:H.lines.map((ne,ce)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx("span",{className:"w-36 text-muted-foreground",children:ne.label}),e.jsx("span",{children:ne.detail})]},ce))}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{className:"text-xs",children:"Follow-up draft (you send it)"}),e.jsx(Ms,{rows:3,defaultValue:Z})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[$.contact_id&&e.jsx(B,{variant:"outline",size:"sm",onClick:()=>t(`/inner-circle/contacts/${$.contact_id}`),children:"Open contact"}),$.email&&e.jsx(B,{variant:"outline",size:"sm",asChild:!0,children:e.jsx("a",{href:`mailto:${$.email}`,children:"Email"})}),$.phone&&e.jsx(B,{variant:"outline",size:"sm",asChild:!0,children:e.jsx("a",{href:`tel:${$.phone}`,children:"Call"})})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Consent recorded ",$.consent_at?new Date($.consent_at).toLocaleString("en-US",{timeZone:"America/New_York"}):"—",$.marketing_opt_in?" · also opted into ongoing marketing":" · no marketing opt-in",$.source?` · from ${$.source}`:""]})]})},$.id)})})]})]}),e.jsx(mls,{open:m,onOpenChange:p,campaign:f??null})]})}const evr="buyer-match-inquiry-v1",HAt="I am asking this agent to contact me about this specific inquiry using the contact details I provided. Message and data rates may apply.",tvr="You may also send me occasional market updates and marketing messages. This is optional and separate from my question above.";function DUe(){const s="buyer-match-session";let t=sessionStorage.getItem(s);return t||(t=crypto.randomUUID(),sessionStorage.setItem(s,t)),t}function svr(){var be;const{slug:s}=Li(),[t]=Yl(),n=t.get("src"),r=_.useRef(Date.now()),a=_.useRef(crypto.randomUUID()),[i,l]=_.useState(null),[o,c]=_.useState(null),[d,u]=_.useState({features:{}}),[h,m]=_.useState(null),[p,f]=_.useState({preferred_contact:"email"}),[y,v]=_.useState(!1),[g,b]=_.useState(!1),[j,S]=_.useState(""),[C,E]=_.useState(!1),[P,M]=_.useState(!1),[I,D]=_.useState(null);_.useEffect(()=>{s&&(async()=>{const{data:me,error:he}=await q.functions.invoke("buyer-match-public",{body:{slug:s}});if(he||me!=null&&me.error){c("This page is not available.");return}l(me),q.functions.invoke("buyer-match-track",{body:{slug:s,event_type:"page_view",session_id:DUe(),source:n,referrer:document.referrer}})})()},[s,n]);const O=i==null?void 0:i.campaign,V=i==null?void 0:i.agent,G=(O==null?void 0:O.status)==="active",$=_.useMemo(()=>Array.isArray(O==null?void 0:O.features)?O.features:[],[O]),H=_.useMemo(()=>{var Ae;if(!O)return[];const me=[],he=[...O.cities??[],...O.zip_codes??[]].join(", ");he&&me.push({label:"Where",value:he}),(Ae=O.property_types)!=null&&Ae.length&&me.push({label:"Home type",value:O.property_types.map(DZe).join(", ")}),O.min_beds&&me.push({label:"Bedrooms",value:`${O.min_beds}+`}),O.min_baths&&me.push({label:"Bathrooms",value:`${O.min_baths}+`}),(O.min_sqft||O.max_sqft)&&me.push({label:"Size",value:O.min_sqft&&O.max_sqft?`${Number(O.min_sqft).toLocaleString()}–${Number(O.max_sqft).toLocaleString()} sq ft`:O.min_sqft?`${Number(O.min_sqft).toLocaleString()}+ sq ft`:`up to ${Number(O.max_sqft).toLocaleString()} sq ft`}),O.min_lot_size&&me.push({label:"Lot",value:`${O.min_lot_size}+ ${O.lot_size_unit}`}),O.show_max_budget&&O.max_budget&&me.push({label:"Budget",value:O.min_budget?`$${Number(O.min_budget).toLocaleString()}–$${Number(O.max_budget).toLocaleString()}`:`up to $${Number(O.max_budget).toLocaleString()}`}),O.timeline&&me.push({label:"Timing",value:O.timeline});const pe=$.filter(Pe=>Pe.required).map(Pe=>Pe.label),Ce=$.filter(Pe=>!Pe.required).map(Pe=>Pe.label);return pe.length&&me.push({label:"Must have",value:pe.join(", ")}),Ce.length&&me.push({label:"Nice to have",value:Ce.join(", ")}),me},[O,$]),Y=()=>{if(!O)return;const me=Yyr(O,d);m(me),q.functions.invoke("buyer-match-track",{body:{slug:s,event_type:"check_completed",session_id:DUe(),source:n,metadata:{fit_level:me.level}}}),setTimeout(()=>{var he;return(he=document.getElementById("buyer-match-result"))==null?void 0:he.scrollIntoView({behavior:"smooth"})},50)},Z=async()=>{var pe;if(D(null),!((pe=p.first_name)!=null&&pe.trim()))return D("Please add your name.");if(!p.email&&!p.phone)return D("Please add an email address or phone number.");if(!y)return D("Please confirm you would like to be contacted about this inquiry.");E(!0);const{data:me,error:he}=await q.functions.invoke("buyer-match-submit",{body:{slug:s,...p,property:d,selling_intent:p.selling_intent,marketing_opt_in:g,consent_version:evr,consent_text:HAt,source:n,session_id:DUe(),idempotency_key:a.current,website_field:j,render_ms:Date.now()-r.current}});if(E(!1),he||me!=null&&me.error){D((me==null?void 0:me.error)??"We couldn't send that just now. Please try again.");return}M(!0)};if(o)return e.jsx("div",{className:"min-h-screen flex items-center justify-center p-8 text-muted-foreground",children:o});if(!O)return e.jsx("div",{className:"min-h-screen flex items-center justify-center p-8 text-muted-foreground",children:"Loading…"});const ne=O.status==="paused"?"This buyer search is paused right now, so it isn't accepting home checks.":O.status==="expired"?"This buyer search has ended.":O.status==="matched"?"This buyer has found a home, so this search is closed.":null,ce=`${O.headline} | Buyer Match`,ie=String(O.description??"").replace(/\s+/g," ").slice(0,190),te=`https://dashboard.relevelup.com/buyer-match/${encodeURIComponent(O.slug)}`,ae=`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/buyer-match-og?slug=${encodeURIComponent(O.slug)}&mode=image`,le=[...O.cities??[],...O.zip_codes??[]].join(" · ");return e.jsxs("div",{className:"buyer-match-public min-h-screen bg-background text-foreground",children:[e.jsxs(ul,{children:[e.jsx("title",{children:ce}),e.jsx("meta",{name:"description",content:ie}),e.jsx("link",{rel:"canonical",href:te}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:title",content:ce}),e.jsx("meta",{property:"og:description",content:ie}),e.jsx("meta",{property:"og:url",content:te}),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",{name:"twitter:card",content:"summary_large_image"}),e.jsx("meta",{name:"twitter:image",content:ae})]}),e.jsx("header",{className:"border-b border-border bg-card/80 px-5 py-4 backdrop-blur",children:e.jsxs("div",{className:"mx-auto flex max-w-5xl items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[V!=null&&V.avatar_url?e.jsx("img",{src:V.avatar_url,alt:(V==null?void 0:V.name)??"Agent",className:"h-11 w-11 shrink-0 rounded-full border border-border object-cover"}):e.jsx("div",{className:"flex h-11 w-11 shrink-0 items-center justify-center rounded-full bg-primary text-sm font-semibold text-primary-foreground",children:((be=V==null?void 0:V.name)==null?void 0:be.slice(0,2))||"BM"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate font-semibold",children:V==null?void 0:V.name}),(V==null?void 0:V.brokerage_name)&&e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:V.brokerage_name})]})]}),(V==null?void 0:V.logo_url)&&e.jsx("img",{src:V.logo_url,alt:(V==null?void 0:V.brokerage_name)??"Brokerage",className:"h-9 max-w-36 object-contain"})]})}),e.jsxs("main",{children:[e.jsxs("section",{className:"mx-auto max-w-4xl px-5 pb-12 pt-14 text-center md:pb-16 md:pt-20",children:[e.jsxs("div",{className:"mb-6 inline-flex items-center gap-2 rounded-full border border-border bg-card px-4 py-2 text-xs font-semibold uppercase text-primary",children:[e.jsx("span",{className:`h-2 w-2 rounded-full ${G?"bg-accent":"bg-muted-foreground"}`}),G?"Active buyer search":"Campaign update",le?` · ${le}`:""]}),e.jsx("h1",{className:"buyer-match-serif mx-auto max-w-3xl text-4xl leading-tight md:text-6xl",children:O.headline}),e.jsx("p",{className:"mx-auto mt-6 max-w-2xl whitespace-pre-line text-base leading-7 text-muted-foreground md:text-lg",children:O.description}),ne&&e.jsx("div",{className:"mx-auto mt-7 max-w-xl rounded-md border border-border bg-secondary p-4 text-sm text-secondary-foreground",children:ne})]}),e.jsx("section",{className:"border-y border-border bg-card/45",children:e.jsxs("div",{className:"mx-auto grid max-w-5xl gap-10 px-5 py-12 md:grid-cols-5 md:py-16",children:[e.jsxs("aside",{className:"md:col-span-2",children:[e.jsx("p",{className:"text-xs font-semibold uppercase text-muted-foreground",children:"The buyer brief"}),e.jsx("h2",{className:"buyer-match-serif mt-3 text-3xl",children:"What they’re hoping to find"}),e.jsx("div",{className:"mt-8 divide-y divide-border border-y border-border",children:H.map(me=>e.jsxs("div",{className:"grid grid-cols-[7rem_1fr] gap-4 py-4",children:[e.jsx("p",{className:"text-xs font-semibold uppercase text-muted-foreground",children:me.label}),e.jsx("p",{className:"font-medium leading-6",children:me.value})]},me.label))}),e.jsxs("div",{className:"mt-7 flex gap-3 text-sm leading-6 text-muted-foreground",children:[e.jsx(BQ,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),e.jsx("p",{children:"Buyer details stay private. Your property information is only used for this comparison."})]})]}),G&&e.jsx("section",{className:"md:col-span-3",children:e.jsxs("div",{className:"border border-border bg-card p-5 shadow-lg sm:p-8 md:p-10",children:[e.jsxs("div",{className:"mb-8 flex items-start gap-4",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-primary text-primary-foreground",children:e.jsx(Jr,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"buyer-match-serif text-3xl",children:"Check for a match"}),e.jsx("p",{className:"mt-1 text-sm leading-6 text-muted-foreground",children:"No account needed. Answer what you know; skipped details remain unknown."})]})]}),e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Street address"}),e.jsxs("div",{className:"relative",children:[e.jsx(Xa,{className:"absolute left-3 top-3 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{className:"pl-10",value:d.address??"",onChange:me=>u({...d,address:me.target.value})})]})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"City"}),e.jsx(xe,{value:d.city??"",onChange:me=>u({...d,city:me.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"State"}),e.jsx(xe,{value:d.state??"",onChange:me=>u({...d,state:me.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"ZIP"}),e.jsx(xe,{value:d.zip??"",onChange:me=>u({...d,zip:me.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Home type"}),e.jsxs(is,{value:d.property_type??"",onValueChange:me=>u({...d,property_type:me}),children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Choose"})}),e.jsx(as,{children:not.map(me=>e.jsx(He,{value:me.key,children:me.label},me.key))})]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Beds"}),e.jsx(xe,{type:"number",value:d.beds??"",onChange:me=>u({...d,beds:me.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Baths"}),e.jsx(xe,{type:"number",step:"0.5",value:d.baths??"",onChange:me=>u({...d,baths:me.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Sq ft"}),e.jsx(xe,{type:"number",value:d.sqft??"",onChange:me=>u({...d,sqft:me.target.value})})]})]}),O.min_lot_size?e.jsxs("div",{className:"space-y-2",children:[e.jsxs(J,{children:["Lot size (",O.lot_size_unit,")"]}),e.jsx(xe,{type:"number",step:"0.1",value:d.lot_size??"",onChange:me=>u({...d,lot_size:me.target.value})})]}):null,$.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Does your home have…"}),$.map(me=>e.jsxs("div",{className:"flex flex-col justify-between gap-3 border border-border p-3 sm:flex-row sm:items-center",children:[e.jsxs("span",{className:"text-sm",children:[me.label,me.required?" *":""]}),e.jsx("div",{className:"flex gap-1",children:["yes","no","unsure"].map(he=>{var pe;return e.jsx(B,{type:"button",size:"sm",variant:((pe=d.features)==null?void 0:pe[me.key])===he?"default":"outline",onClick:()=>u({...d,features:{...d.features??{},[me.key]:he}}),children:he==="unsure"?"Not sure":he==="yes"?"Yes":"No"},he)})})]},me.key))]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"What price would you expect? (optional)"}),e.jsx(xe,{type:"number",disabled:d.price_unknown,value:d.expected_price??"",onChange:me=>u({...d,expected_price:me.target.value})}),e.jsxs("label",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx($a,{checked:!!d.price_unknown,onCheckedChange:me=>u({...d,price_unknown:!!me})}),"I'm not sure"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This is not a home valuation or an offer."})]}),e.jsxs(B,{size:"lg",className:"w-full",onClick:Y,children:["See how my home compares ",e.jsx(La,{className:"ml-2 h-4 w-4"})]})]})]})})]})}),h&&e.jsxs("section",{id:"buyer-match-result",className:"mx-auto max-w-3xl space-y-6 px-5 py-14 md:py-20",children:[e.jsxs("div",{className:"border border-border bg-card p-6 sm:p-9",children:[e.jsx("div",{className:"mb-5 flex h-11 w-11 items-center justify-center rounded-full bg-accent text-accent-foreground",children:e.jsx(un,{className:"h-5 w-5"})}),e.jsx("h2",{className:"buyer-match-serif text-3xl",children:h.headline}),e.jsx("p",{className:"text-muted-foreground",children:h.summary}),e.jsx("div",{className:"mt-6 divide-y divide-border border-y border-border",children:h.lines.map((me,he)=>{const pe=me.status==="pass"||me.status==="bonus"?Er:me.status==="fail"?Rd:me.status==="unknown"?f4:Da;return e.jsxs("div",{className:"flex gap-3 py-3 text-sm",children:[e.jsx(pe,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),e.jsxs("span",{children:[e.jsxs("strong",{children:[me.label,":"]})," ",me.detail]})]},he)})}),e.jsxs("p",{className:"mt-5 text-xs leading-5 text-muted-foreground",children:["This comparison uses the information you provided and the buyer's stated preferences.",V!=null&&V.name?` ${V.name}`:" The agent"," will need to confirm whether there is a potential fit."]})]}),P?e.jsxs("div",{className:"border border-border bg-card p-8 text-center",children:[e.jsx(Er,{className:"mx-auto h-9 w-9 text-primary"}),e.jsxs("h3",{className:"buyer-match-serif mt-4 text-2xl",children:["Thanks — your message is on its way to ",V==null?void 0:V.name]}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"They'll reach out using the contact method you chose."}),(i==null?void 0:i.booking_slug)&&e.jsx(B,{asChild:!0,children:e.jsx("a",{href:`/book/${i.booking_slug}`,children:"Schedule a conversation"})})]}):e.jsxs("div",{className:"border border-border bg-card p-6 sm:p-9",children:[e.jsx("p",{className:"text-xs font-semibold uppercase text-muted-foreground",children:"Start a private conversation"}),e.jsxs("h3",{className:"buyer-match-serif mt-2 text-3xl",children:["Ask ",(V==null?void 0:V.name)??"the agent"," about a possible match"]}),e.jsxs("div",{className:"mt-7 space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"How are you thinking about selling?"}),e.jsxs(is,{value:p.selling_intent??"",onValueChange:me=>f({...p,selling_intent:me}),children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Choose one"})}),e.jsxs(as,{children:[e.jsx(He,{value:"just_curious",children:"Just curious"}),e.jsx(He,{value:"thinking_about_it",children:"Thinking about it"}),e.jsx(He,{value:"open_to_offers",children:"Open to the right offer"}),e.jsx(He,{value:"ready_now",children:"Ready to talk now"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"First name"}),e.jsx(xe,{value:p.first_name??"",onChange:me=>f({...p,first_name:me.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Last name"}),e.jsx(xe,{value:p.last_name??"",onChange:me=>f({...p,last_name:me.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Email"}),e.jsx(xe,{type:"email",value:p.email??"",onChange:me=>f({...p,email:me.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Phone (optional)"}),e.jsx(xe,{type:"tel",value:p.phone??"",onChange:me=>f({...p,phone:me.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Preferred contact method"}),e.jsxs(is,{value:p.preferred_contact,onValueChange:me=>f({...p,preferred_contact:me}),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"email",children:"Email"}),e.jsx(He,{value:"phone",disabled:!p.phone,children:"Phone call"}),e.jsx(He,{value:"text",disabled:!p.phone,children:"Text message"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Message (optional)"}),e.jsx(Ms,{rows:3,value:p.message??"",onChange:me=>f({...p,message:me.target.value})})]}),e.jsx("input",{type:"text",value:j,onChange:me=>S(me.target.value),tabIndex:-1,autoComplete:"off",className:"hidden","aria-hidden":"true"}),e.jsxs("label",{className:"flex items-start gap-2 text-sm",children:[e.jsx($a,{checked:y,onCheckedChange:me=>v(!!me),className:"mt-1"}),e.jsx("span",{children:HAt})]}),e.jsxs("label",{className:"flex items-start gap-2 text-sm",children:[e.jsx($a,{checked:g,onCheckedChange:me=>b(!!me),className:"mt-1"}),e.jsx("span",{children:tvr})]}),I&&e.jsx("p",{className:"text-sm text-destructive",children:I}),e.jsx(B,{size:"lg",className:"w-full",onClick:Z,disabled:C,children:C?"Sending…":"Send my question"})]})]})]}),!G&&e.jsx("section",{className:"mx-auto max-w-2xl px-5 pb-14",children:e.jsxs("div",{className:"border border-border bg-card p-6",children:[e.jsx("h3",{className:"buyer-match-serif text-2xl",children:"Still want to talk?"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["You can reach ",(V==null?void 0:V.name)??"the agent"," directly using the details below."]}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[(V==null?void 0:V.email)&&e.jsx(B,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:`mailto:${V.email}`,children:[e.jsx(ln,{className:"h-4 w-4 mr-2"}),"Email"]})}),(V==null?void 0:V.phone)&&e.jsx(B,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:`tel:${V.phone}`,children:[e.jsx(_a,{className:"h-4 w-4 mr-2"}),"Call"]})}),(i==null?void 0:i.booking_slug)&&e.jsx(B,{asChild:!0,children:e.jsx("a",{href:`/book/${i.booking_slug}`,children:"Schedule a conversation"})})]})]})}),e.jsxs("footer",{className:"mx-auto max-w-5xl space-y-2 border-t border-border px-5 py-8 text-xs leading-5 text-muted-foreground",children:[e.jsxs("p",{children:[V==null?void 0:V.name,V!=null&&V.brokerage_name?` · ${V.brokerage_name}`:"",V!=null&&V.license_number?` · License ${V.license_number}`:""]}),e.jsx("p",{children:"Buyer details are kept private. Checking your home does not create an agency relationship, an offer, or a listing agreement, and it is not a home valuation."})]})]})]})}function nvr(s,t){return t?`${(s/t*100).toFixed(1)}%`:"0%"}function rvr({pageId:s}){const{data:t=[],isLoading:n}=at({queryKey:["landing-page-events",s],queryFn:async()=>{const l=new Date(Date.now()-2592e6).toISOString(),{data:o,error:c}=await q.from("landing_page_events").select("event_type, session_id, utm_source, utm_medium, utm_campaign, referrer, device, created_at").eq("page_id",s).gte("created_at",l).order("created_at",{ascending:!1}).limit(1e3);if(c)throw c;return o||[]}}),{data:r=[]}=at({queryKey:["landing-page-submissions-analytics",s],queryFn:async()=>{const{data:l}=await q.from("landing_page_submissions").select("id, created_at").eq("page_id",s);return l||[]}}),a=_.useMemo(()=>{const l=t.filter(f=>f.event_type==="view"),o=t.filter(f=>f.event_type==="click"),c=new Set(l.map(f=>f.session_id).filter(Boolean)),d=new Map,u=new Map,h=new Map;for(const f of l){const y=f.utm_source||"Direct / unknown";if(d.set(y,(d.get(y)||0)+1),f.referrer)try{const g=new URL(f.referrer).hostname.replace(/^www\./,"");u.set(g,(u.get(g)||0)+1)}catch{}const v=f.device||"unknown";h.set(v,(h.get(v)||0)+1)}const m=[];for(let f=13;f>=0;f--){const y=new Date;y.setHours(0,0,0,0),y.setDate(y.getDate()-f);const v=new Date(y);v.setDate(y.getDate()+1);const g=y.toLocaleDateString("en-US",{month:"numeric",day:"numeric"}),b=l.filter(S=>{const C=new Date(S.created_at);return C>=y&&C{const C=new Date(S.created_at);return C>=y&&Cf.views));return{views:l.length,sessions:c.size,clicks:o.length,submissions:r.length,conversion:nvr(r.length,c.size||l.length),sourceCounts:[...d.entries()].sort((f,y)=>y[1]-f[1]).slice(0,6),referrerCounts:[...u.entries()].sort((f,y)=>y[1]-f[1]).slice(0,6),deviceCounts:[...h.entries()].sort((f,y)=>y[1]-f[1]),days:m,maxBar:p}},[t,r]);if(n)return e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:Array.from({length:4}).map((l,o)=>e.jsx(cn,{className:"h-24"},o))});const i=[{label:"Views (30d)",value:a.views,icon:ya},{label:"Unique visitors",value:a.sessions,icon:In},{label:"Submissions",value:a.submissions,icon:Or},{label:"Conversion rate",value:a.conversion,icon:Nl}];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(ve,{children:e.jsxs(Me,{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(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"Last 14 days"})}),e.jsxs(Me,{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(ve,{children:[e.jsx(bt,{children:e.jsxs(St,{className:"text-base flex items-center gap-2",children:[e.jsx($h,{className:"h-4 w-4"})," Top sources"]})}),e.jsx(Me,{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(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"Top referrers"})}),e.jsx(Me,{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(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"Devices"})}),e.jsx(Me,{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 avr=[{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 ivr=0;const GAt=()=>`f_${Date.now()}_${++ivr}`;function ovr({field:s,index:t,updateField:n,removeField:r,showGroup:a}){const{attributes:i,listeners:l,setNodeRef:o,transform:c,transition:d,isDragging:u}=rLe({id:s.clientId}),h={transform:OP.Transform.toString(c),transition:d,zIndex:u?50:void 0,opacity:u?.85:1};return e.jsx(ve,{ref:o,style:h,children:e.jsx(Me,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("button",{type:"button",...i,...l,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(Vf,{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(J,{className:"text-xs",children:"Field Type"}),e.jsxs(is,{value:s.field_type,onValueChange:m=>n(t,{field_type:m}),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsx(as,{children:avr.map(m=>e.jsx(He,{value:m.value,children:m.label},m.value))})]})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Label"}),e.jsx(xe,{value:s.label,onChange:m=>n(t,{label:m.target.value}),placeholder:"e.g. Full Name"})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Placeholder"}),e.jsx(xe,{value:s.placeholder||"",onChange:m=>n(t,{placeholder:m.target.value}),placeholder:"Optional hint text"})]})]}),(s.field_type==="select"||s.field_type==="multiselect")&&e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Options (comma-separated)"}),e.jsx(xe,{value:s.options?(typeof s.options=="string"?JSON.parse(s.options):s.options).join(", "):"",onChange:m=>n(t,{options:JSON.stringify(m.target.value.split(",").map(p=>p.trim()).filter(Boolean))}),placeholder:"Option 1, Option 2, Option 3"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fn,{checked:s.is_required,onCheckedChange:m=>n(t,{is_required:m})}),e.jsx(J,{className:"text-xs",children:"Required"})]}),a&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(J,{className:"text-xs",children:"Show on"}),e.jsxs(is,{value:s.field_group||"default",onValueChange:m=>n(t,{field_group:m}),children:[e.jsx(rs,{className:"h-8 w-[170px]",children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"default",children:"Both forms"}),e.jsx(He,{value:"buyer",children:"Buyer form only"}),e.jsx(He,{value:"seller",children:"Seller form only"})]})]})]})]})]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>r(t),children:e.jsx(Sn,{className:"h-3.5 w-3.5 text-destructive"})})]})})})}function lvr(){const{pageId:s}=Li(),t=Fn(),{user:n}=hs(),r=ha(),{toast:a}=vi(),i=Bt(),[l,o]=_.useState(null),[c,d]=_.useState(!1),{data:u,isLoading:h}=at({queryKey:["landing-page",s],queryFn:async()=>{const{data:te,error:ae}=await q.from("landing_pages").select("*").eq("id",s).single();if(ae)throw ae;return te},enabled:!!s}),{data:m=[],isLoading:p}=at({queryKey:["landing-page-fields",s],queryFn:async()=>{const{data:te,error:ae}=await q.from("landing_page_fields").select("*").eq("page_id",s).order("sort_order");if(ae)throw ae;return te},enabled:!!s}),{data:f=[]}=at({queryKey:["landing-page-submissions",s],queryFn:async()=>{const{data:te,error:ae}=await q.from("landing_page_submissions").select("*").eq("page_id",s).order("created_at",{ascending:!1});if(ae)throw ae;return te},enabled:!!s}),{data:y=[]}=at({queryKey:["my-listings-for-pages",r],queryFn:async()=>{const{data:te,error:ae}=await q.from("listings").select("id, property_address, city, state, price, bedrooms, bathrooms, square_footage, description, status").eq("agent_id",r).order("created_at",{ascending:!1});if(ae)throw ae;return te},enabled:!!n&&((u==null?void 0:u.page_type)==="just_listed"||(u==null?void 0:u.page_type)==="just_sold")}),{data:v=[]}=at({queryKey:["drips-for-landing",r],queryFn:async()=>{const{data:te}=await q.from("drip_campaigns").select("id, name").eq("owner_user_id",r).eq("is_active",!0).order("name");return te||[]},enabled:!!r}),{data:g}=at({queryKey:["agent-landing-defaults",r],queryFn:async()=>{const{data:te}=await q.from("agent_landing_page_defaults").select("*").eq("user_id",r).maybeSingle();return te},enabled:!!r}),[b,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:"",settings_buyer_button_label:"",settings_buyer_button_subtext:"",settings_seller_button_label:"",settings_seller_button_subtext:"",settings_buyer_form_title:"",settings_buyer_form_subtext:"",settings_seller_form_title:"",settings_seller_form_subtext:"",settings_buyer_submit_label:"",settings_seller_submit_label:""}),[S,C]=_.useState([]);_.useEffect(()=>{var te,ae,le,be,me,he,pe,Ce,Ae,Pe,ze,ke,Ze,Se,Fe,Ne,Ye,Ve,qe;u&&j({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:((te=u.settings)==null?void 0:te.redirect_url)||"",settings_auto_responder_subject:((ae=u.settings)==null?void 0:ae.auto_responder_subject)||"",settings_auto_responder_body:((le=u.settings)==null?void 0:le.auto_responder_body)||"",settings_drip_campaign_id:((be=u.settings)==null?void 0:be.drip_campaign_id)||null,settings_disable_auto_responder:!!((me=u.settings)!=null&&me.disable_auto_responder),settings_disable_drip:!!((he=u.settings)!=null&&he.disable_drip),settings_event_starts_at:((pe=u.settings)==null?void 0:pe.event_starts_at)||"",settings_event_location_name:((Ce=u.settings)==null?void 0:Ce.event_location_name)||"",settings_event_address:((Ae=u.settings)==null?void 0:Ae.event_address)||"",settings_buyer_button_label:((Pe=u.settings)==null?void 0:Pe.buyer_button_label)||"",settings_buyer_button_subtext:((ze=u.settings)==null?void 0:ze.buyer_button_subtext)||"",settings_seller_button_label:((ke=u.settings)==null?void 0:ke.seller_button_label)||"",settings_seller_button_subtext:((Ze=u.settings)==null?void 0:Ze.seller_button_subtext)||"",settings_buyer_form_title:((Se=u.settings)==null?void 0:Se.buyer_form_title)||"",settings_buyer_form_subtext:((Fe=u.settings)==null?void 0:Fe.buyer_form_subtext)||"",settings_seller_form_title:((Ne=u.settings)==null?void 0:Ne.seller_form_title)||"",settings_seller_form_subtext:((Ye=u.settings)==null?void 0:Ye.seller_form_subtext)||"",settings_buyer_submit_label:((Ve=u.settings)==null?void 0:Ve.buyer_submit_label)||"",settings_seller_submit_label:((qe=u.settings)==null?void 0:qe.seller_submit_label)||""})},[u]),_.useEffect(()=>{m.length>0&&C(m.map(te=>({id:te.id,clientId:te.id||GAt(),field_type:te.field_type,label:te.label,placeholder:te.placeholder,is_required:te.is_required,options:typeof te.options=="string"?te.options:te.options?JSON.stringify(te.options):null,sort_order:te.sort_order,field_group:te.field_group||"default"})))},[m]);const E=mt({mutationFn:async()=>{const{error:te}=await q.from("landing_pages").update({title:b.title,hero_headline:b.hero_headline,hero_subtext:b.hero_subtext||null,hero_image_url:b.hero_image_url,logo_url:b.logo_url,primary_color:b.primary_color,accent_color:b.accent_color,agent_name:b.agent_name||null,agent_phone:b.agent_phone||null,agent_email:b.agent_email||null,agent_photo_url:b.agent_photo_url,success_message:b.success_message,is_published:b.is_published,description:b.description||null,lead_magnet_file_url:b.lead_magnet_file_url,lead_magnet_file_name:b.lead_magnet_file_name,lead_magnet_external_url:b.lead_magnet_external_url,listing_id:b.listing_id,property_address:b.property_address||null,property_price:b.property_price||null,property_beds:b.property_beds||null,property_baths:b.property_baths||null,property_sqft:b.property_sqft||null,property_description:b.property_description||null,property_photos:b.property_photos,property_status:b.property_status,theme_style:b.theme_style,eyebrow:b.eyebrow||null,headline_accent:b.headline_accent||null,heading_font:b.heading_font,trust_pills:b.trust_pills,redirect_url:b.settings_redirect_url||null,auto_responder_enabled:!b.settings_disable_auto_responder,auto_responder_subject:b.settings_auto_responder_subject||null,auto_responder_body:b.settings_auto_responder_body||null,drip_campaign_id:b.settings_disable_drip?null:b.settings_drip_campaign_id||null,settings:{...(u==null?void 0:u.settings)||{},redirect_url:b.settings_redirect_url||null,auto_responder_subject:b.settings_auto_responder_subject||null,auto_responder_body:b.settings_auto_responder_body||null,drip_campaign_id:b.settings_drip_campaign_id||null,disable_auto_responder:!!b.settings_disable_auto_responder,disable_drip:!!b.settings_disable_drip,event_starts_at:b.settings_event_starts_at||null,event_location_name:b.settings_event_location_name||null,event_address:b.settings_event_address||null,buyer_button_label:b.settings_buyer_button_label||null,buyer_button_subtext:b.settings_buyer_button_subtext||null,seller_button_label:b.settings_seller_button_label||null,seller_button_subtext:b.settings_seller_button_subtext||null,buyer_form_title:b.settings_buyer_form_title||null,buyer_form_subtext:b.settings_buyer_form_subtext||null,seller_form_title:b.settings_seller_form_title||null,seller_form_subtext:b.settings_seller_form_subtext||null,buyer_submit_label:b.settings_buyer_submit_label||null,seller_submit_label:b.settings_seller_submit_label||null},updated_at:new Date().toISOString()}).eq("id",s);if(te)throw te;if(await q.from("landing_page_fields").delete().eq("page_id",s),S.length>0){const{error:ae}=await q.from("landing_page_fields").insert(S.map((le,be)=>({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:be,field_group:le.field_group||"default"})));if(ae)throw ae}},onSuccess:()=>{i.invalidateQueries({queryKey:["landing-page",s]}),i.invalidateQueries({queryKey:["landing-page-fields",s]}),a({title:"Page saved!"})},onError:te=>a({title:"Error",description:te.message,variant:"destructive"})}),P=async(te,ae)=>{const le=te.name.split(".").pop(),be=`landing-pages/${n.id}/${ae}-${Date.now()}.${le}`,{error:me}=await q.storage.from("recruit-landing").upload(be,te);if(me)throw me;const{data:{publicUrl:he}}=q.storage.from("recruit-landing").getPublicUrl(be);return he},M=async(te,ae)=>{var be;const le=(be=te.target.files)==null?void 0:be[0];if(le){o(ae);try{const me=await P(le,ae);j(he=>({...he,[ae]:me})),a({title:"Image uploaded!"})}catch(me){a({title:"Upload failed",description:me.message,variant:"destructive"})}finally{o(null)}}},I=async te=>{var le;const ae=(le=te.target.files)==null?void 0:le[0];if(ae){o("lead_magnet");try{const be=await P(ae,"lead-magnet");j(me=>({...me,lead_magnet_file_url:be,lead_magnet_file_name:ae.name})),a({title:"File uploaded!"})}catch(be){a({title:"Upload failed",description:be.message,variant:"destructive"})}finally{o(null)}}},D=async te=>{const ae=te.target.files;if(!(!ae||ae.length===0)){o("property_photos");try{const le=[];for(const be of Array.from(ae)){const me=await P(be,"property-photo");le.push(me)}j(be=>({...be,property_photos:[...be.property_photos,...le]})),a({title:`${le.length} photo(s) uploaded!`})}catch(le){a({title:"Upload failed",description:le.message,variant:"destructive"})}finally{o(null)}}},O=async te=>{const ae=y.find(be=>be.id===te);if(!ae)return;const{data:le}=await q.from("listing_photos").select("photo_url").eq("listing_id",te).order("sort_order");j(be=>({...be,listing_id:te,property_address:ae.property_address||`${ae.city}, ${ae.state}`,property_price:ae.price?`$${ae.price.toLocaleString()}`:"",property_beds:ae.bedrooms?String(ae.bedrooms):"",property_baths:ae.bathrooms?String(ae.bathrooms):"",property_sqft:ae.square_footage?ae.square_footage.toLocaleString():"",property_description:ae.description||"",property_photos:(le==null?void 0:le.map(me=>me.photo_url))||be.property_photos})),a({title:"Listing data imported!"})},V=()=>{C(te=>[...te,{clientId:GAt(),field_type:"text",label:"",placeholder:"",is_required:!1,options:null,sort_order:te.length,field_group:"default"}])},G=(te,ae)=>{C(le=>le.map((be,me)=>me===te?{...be,...ae}:be))},$=te=>{C(ae=>ae.filter((le,be)=>be!==te))},H=YPe(IH(yW,{activationConstraint:{distance:6}}),IH(QPe,{coordinateGetter:tzt})),Y=te=>{const{active:ae,over:le}=te;!le||ae.id===le.id||C(be=>{const me=be.findIndex(pe=>pe.clientId===ae.id),he=be.findIndex(pe=>pe.clientId===le.id);return me<0||he<0?be:sLe(be,me,he).map((pe,Ce)=>({...pe,sort_order:Ce}))})},Z=u?`https://pages.relevelup.com/${u.slug}`:"",ne=(u==null?void 0:u.page_type)==="lead_magnet",ce=(u==null?void 0:u.page_type)==="buyer_seller",ie=(u==null?void 0:u.page_type)==="just_listed"||(u==null?void 0:u.page_type)==="just_sold";return h||p?e.jsx(zs,{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(zs,{title:b.title||"Edit Page",children:[e.jsxs("div",{className:"space-y-6 max-w-4xl mx-auto",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(B,{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:b.title||"Untitled Page"}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[e.jsx(Oe,{variant:b.is_published?"default":"secondary",className:"text-[10px]",children:b.is_published?"Published":"Draft"}),e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(ya,{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(In,{className:"h-3 w-3"})," ",f.length," submissions"]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[b.is_published&&e.jsxs(e.Fragment,{children:[e.jsx(B,{size:"sm",variant:"outline",onClick:()=>d(!0),children:e.jsx(Hf,{className:"h-3.5 w-3.5"})}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>{navigator.clipboard.writeText(Z),a({title:"Link copied!"})},children:[e.jsx(Ia,{className:"h-3.5 w-3.5 mr-1"})," Copy Link"]}),e.jsx(B,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:Z,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(wr,{className:"h-3.5 w-3.5 mr-1"})," Preview"]})})]}),e.jsxs(B,{onClick:()=>E.mutate(),disabled:E.isPending,children:[e.jsx(Ho,{className:"h-4 w-4 mr-2"}),E.isPending?"Saving...":"Save"]})]})]}),e.jsxs(Yr,{defaultValue:"design",children:[e.jsxs(Zr,{children:[e.jsx(Ht,{value:"design",children:"Design"}),ne&&e.jsx(Ht,{value:"lead_magnet",children:"Lead Magnet"}),ie&&e.jsx(Ht,{value:"property",children:"Property Details"}),e.jsxs(Ht,{value:"fields",children:["Form Fields (",S.length,")"]}),e.jsxs(Ht,{value:"submissions",children:["Submissions (",f.length,")"]}),e.jsx(Ht,{value:"automation",children:"Automation"}),e.jsx(Ht,{value:"analytics",children:"Analytics"}),e.jsx(Ht,{value:"settings",children:"Settings"})]}),e.jsxs(Gt,{value:"design",className:"space-y-4 mt-4",children:[e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"Page Details"})}),e.jsxs(Me,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Page Title (internal)"}),e.jsx(xe,{value:b.title,onChange:te=>j(ae=>({...ae,title:te.target.value}))})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Description (internal)"}),e.jsx(xe,{value:b.description,onChange:te=>j(ae=>({...ae,description:te.target.value}))})]})]})]}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsxs(St,{className:"text-base flex items-center gap-2",children:["Theme & Style",e.jsx(Oe,{variant:"secondary",className:"text-[10px]",children:"New"})]})}),e.jsxs(Me,{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(J,{children:"Theme Style"}),e.jsxs(is,{value:b.theme_style,onValueChange:te=>j(ae=>({...ae,theme_style:te})),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"premium",children:"Premium — cinematic + glass form"}),e.jsx(He,{value:"classic",children:"Classic — centered card"})]})]})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Headline Font"}),e.jsxs(is,{value:b.heading_font,onValueChange:te=>j(ae=>({...ae,heading_font:te})),children:[e.jsx(rs,{children:e.jsx(ls,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"playfair",children:"Playfair Display (editorial serif)"}),e.jsx(He,{value:"baskerville",children:"Libre Baskerville (classic serif)"}),e.jsx(He,{value:"instrument",children:"Instrument Serif (modern serif)"}),e.jsx(He,{value:"sans",children:"Inter (clean sans-serif)"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Trust Pills (comma separated, shown under CTA)"}),e.jsx(xe,{value:b.trust_pills.join(", "),onChange:te=>j(ae=>({...ae,trust_pills:te.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(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"Hero Section"})}),e.jsxs(Me,{className:"space-y-4",children:[b.theme_style==="premium"&&e.jsxs("div",{children:[e.jsx(J,{children:"Eyebrow (small label above headline)"}),e.jsx(xe,{value:b.eyebrow,onChange:te=>j(ae=>({...ae,eyebrow:te.target.value})),placeholder:"HOME VALUE"})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Headline"}),e.jsx(xe,{value:b.hero_headline,onChange:te=>j(ae=>({...ae,hero_headline:te.target.value})),placeholder:"What Is Your Home"})]}),b.theme_style==="premium"&&e.jsxs("div",{children:[e.jsx(J,{children:"Accent Word(s) — italic & colored (optional)"}),e.jsx(xe,{value:b.headline_accent,onChange:te=>j(ae=>({...ae,headline_accent:te.target.value})),placeholder:"Actually Worth?"})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Subtext"}),e.jsx(Ms,{value:b.hero_subtext,onChange:te=>j(ae=>({...ae,hero_subtext:te.target.value})),rows:3,placeholder:"A brief description..."})]}),e.jsxs("div",{children:[e.jsxs(J,{children:["Background Image ",b.theme_style==="premium"&&e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"(dusk/cinematic recommended)"})]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[b.hero_image_url&&e.jsx("img",{src:b.hero_image_url,alt:"Hero",className:"h-16 w-28 object-cover rounded"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(B,{variant:"outline",size:"sm",asChild:!0,disabled:l==="hero_image_url",children:e.jsxs("span",{children:[e.jsx(Oa,{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:te=>M(te,"hero_image_url")})]}),b.hero_image_url&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>j(te=>({...te,hero_image_url:null})),children:e.jsx(Sn,{className:"h-3.5 w-3.5"})})]})]})]})]}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"Branding"})}),e.jsxs(Me,{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(J,{children:"Logo"}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[b.logo_url&&e.jsx("img",{src:b.logo_url,alt:"Logo",className:"h-10 w-auto rounded"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(B,{variant:"outline",size:"sm",asChild:!0,disabled:l==="logo_url",children:e.jsxs("span",{children:[e.jsx(Oa,{className:"h-3.5 w-3.5 mr-1"}),l==="logo_url"?"...":"Upload"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:te=>M(te,"logo_url")})]})]})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Agent Photo"}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[b.agent_photo_url&&e.jsx("img",{src:b.agent_photo_url,alt:"Agent",className:"h-10 w-10 rounded-full object-cover"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(B,{variant:"outline",size:"sm",asChild:!0,disabled:l==="agent_photo_url",children:e.jsxs("span",{children:[e.jsx(Oa,{className:"h-3.5 w-3.5 mr-1"}),l==="agent_photo_url"?"...":"Upload"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:te=>M(te,"agent_photo_url")})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Primary Color"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("input",{type:"color",value:b.primary_color,onChange:te=>j(ae=>({...ae,primary_color:te.target.value})),className:"h-9 w-12 rounded border cursor-pointer"}),e.jsx(xe,{value:b.primary_color,onChange:te=>j(ae=>({...ae,primary_color:te.target.value})),className:"font-mono text-xs"})]})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Accent Color"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("input",{type:"color",value:b.accent_color,onChange:te=>j(ae=>({...ae,accent_color:te.target.value})),className:"h-9 w-12 rounded border cursor-pointer"}),e.jsx(xe,{value:b.accent_color,onChange:te=>j(ae=>({...ae,accent_color:te.target.value})),className:"font-mono text-xs"})]})]})]})]})]}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"Agent Info (shown on page)"})}),e.jsx(Me,{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(J,{children:"Name"}),e.jsx(xe,{value:b.agent_name,onChange:te=>j(ae=>({...ae,agent_name:te.target.value}))})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Phone"}),e.jsx(xe,{value:b.agent_phone,onChange:te=>j(ae=>({...ae,agent_phone:te.target.value}))})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Email"}),e.jsx(xe,{value:b.agent_email,onChange:te=>j(ae=>({...ae,agent_email:te.target.value}))})]})]})})]})]}),ne&&e.jsx(Gt,{value:"lead_magnet",className:"space-y-4 mt-4",children:e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsxs(St,{className:"text-base flex items-center gap-2",children:[e.jsx(li,{className:"h-4 w-4"})," Giveaway File"]})}),e.jsxs(Me,{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(J,{children:"Upload File (PDF, guide, checklist, etc.)"}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[b.lead_magnet_file_name&&e.jsxs(Oe,{variant:"outline",className:"gap-1",children:[e.jsx(li,{className:"h-3 w-3"})," ",b.lead_magnet_file_name]}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(B,{variant:"outline",size:"sm",asChild:!0,disabled:l==="lead_magnet",children:e.jsxs("span",{children:[e.jsx(Oa,{className:"h-3.5 w-3.5 mr-1"}),l==="lead_magnet"?"Uploading...":"Upload File"]})}),e.jsx("input",{type:"file",className:"hidden",onChange:I})]}),b.lead_magnet_file_url&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>j(te=>({...te,lead_magnet_file_url:null,lead_magnet_file_name:null})),children:e.jsx(Sn,{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(J,{className:"flex items-center gap-1",children:[e.jsx(vd,{className:"h-3.5 w-3.5"})," External URL"]}),e.jsx(xe,{value:b.lead_magnet_external_url||"",onChange:te=>j(ae=>({...ae,lead_magnet_external_url:te.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"})]})]})]})}),ie&&e.jsxs(Gt,{value:"property",className:"space-y-4 mt-4",children:[e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsxs(St,{className:"text-base flex items-center gap-2",children:[e.jsx(Jr,{className:"h-4 w-4"})," Import from Listing Exchange"]})}),e.jsxs(Me,{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(is,{value:b.listing_id||"",onValueChange:te=>O(te),children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Select a listing to import..."})}),e.jsx(as,{children:y.map(te=>{var ae;return e.jsxs(He,{value:te.id,children:[te.property_address||`${te.city}, ${te.state}`," — $",(ae=te.price)==null?void 0:ae.toLocaleString()]},te.id)})})]})]})]}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"Property Information"})}),e.jsxs(Me,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Property Address"}),e.jsx(xe,{value:b.property_address,onChange:te=>j(ae=>({...ae,property_address:te.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(J,{children:"Price"}),e.jsx(xe,{value:b.property_price,onChange:te=>j(ae=>({...ae,property_price:te.target.value})),placeholder:"$450,000"})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Beds"}),e.jsx(xe,{value:b.property_beds,onChange:te=>j(ae=>({...ae,property_beds:te.target.value})),placeholder:"4"})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Baths"}),e.jsx(xe,{value:b.property_baths,onChange:te=>j(ae=>({...ae,property_baths:te.target.value})),placeholder:"3"})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Sq Ft"}),e.jsx(xe,{value:b.property_sqft,onChange:te=>j(ae=>({...ae,property_sqft:te.target.value})),placeholder:"2,400"})]})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Description"}),e.jsx(Ms,{value:b.property_description,onChange:te=>j(ae=>({...ae,property_description:te.target.value})),rows:3,placeholder:"Beautiful home in a great neighborhood..."})]})]})]}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"Property Photos"})}),e.jsxs(Me,{className:"space-y-4",children:[b.property_photos.length>0&&e.jsx("div",{className:"grid grid-cols-3 md:grid-cols-4 gap-2",children:b.property_photos.map((te,ae)=>e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:te,alt:`Property ${ae+1}`,className:"h-24 w-full object-cover rounded"}),e.jsx(B,{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:()=>j(le=>({...le,property_photos:le.property_photos.filter((be,me)=>me!==ae)})),children:e.jsx(Sn,{className:"h-3 w-3"})})]},ae))}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(B,{variant:"outline",size:"sm",asChild:!0,disabled:l==="property_photos",children:e.jsxs("span",{children:[e.jsx(Oa,{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(Gt,{value:"fields",className:"space-y-4 mt-4",children:[ce&&e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"Buyer / Seller choice"})}),e.jsxs(Me,{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Buyer button text"}),e.jsx(xe,{value:b.settings_buyer_button_label,onChange:te=>j(ae=>({...ae,settings_buyer_button_label:te.target.value})),placeholder:"I'm a Buyer"})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Buyer button description"}),e.jsx(xe,{value:b.settings_buyer_button_subtext,onChange:te=>j(ae=>({...ae,settings_buyer_button_subtext:te.target.value})),placeholder:"Find the right home, at the right price"})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Buyer form heading"}),e.jsx(xe,{value:b.settings_buyer_form_title,onChange:te=>j(ae=>({...ae,settings_buyer_form_title:te.target.value})),placeholder:"Tell me what you're looking for"})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Buyer form subheading"}),e.jsx(xe,{value:b.settings_buyer_form_subtext,onChange:te=>j(ae=>({...ae,settings_buyer_form_subtext:te.target.value})),placeholder:"A few quick questions and I'll send matching homes."})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Buyer submit button"}),e.jsx(xe,{value:b.settings_buyer_submit_label,onChange:te=>j(ae=>({...ae,settings_buyer_submit_label:te.target.value})),placeholder:"Send me homes"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Seller button text"}),e.jsx(xe,{value:b.settings_seller_button_label,onChange:te=>j(ae=>({...ae,settings_seller_button_label:te.target.value})),placeholder:"I'm a Seller"})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Seller button description"}),e.jsx(xe,{value:b.settings_seller_button_subtext,onChange:te=>j(ae=>({...ae,settings_seller_button_subtext:te.target.value})),placeholder:"Get a free, no-obligation home evaluation"})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Seller form heading"}),e.jsx(xe,{value:b.settings_seller_form_title,onChange:te=>j(ae=>({...ae,settings_seller_form_title:te.target.value})),placeholder:"Get your free home evaluation"})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Seller form subheading"}),e.jsx(xe,{value:b.settings_seller_form_subtext,onChange:te=>j(ae=>({...ae,settings_seller_form_subtext:te.target.value})),placeholder:"Tell me about your home and I'll prepare your value report."})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xs",children:"Seller submit button"}),e.jsx(xe,{value:b.settings_seller_submit_label,onChange:te=>j(ae=>({...ae,settings_seller_submit_label:te.target.value})),placeholder:"Get my home value"})]})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:ce?"Choose which form each question appears on: both, buyer only, or seller only.":"Configure the form fields visitors will fill out"}),e.jsxs(B,{size:"sm",onClick:V,children:[e.jsx(rn,{className:"h-3.5 w-3.5 mr-1"})," Add Field"]})]}),S.length===0?e.jsx(ve,{children:e.jsx(Me,{className:"py-8 text-center text-muted-foreground",children:"No fields yet. Add fields to build your form."})}):e.jsx(tLe,{sensors:H,collisionDetection:ZPe,onDragEnd:Y,children:e.jsx(nLe,{items:S.map(te=>te.clientId),strategy:_zs,children:e.jsx("div",{className:"space-y-3",children:S.map((te,ae)=>e.jsx(ovr,{field:te,index:ae,updateField:G,removeField:$,showGroup:ce},te.clientId))})})})]}),e.jsx(Gt,{value:"submissions",className:"mt-4",children:f.length===0?e.jsx(ve,{children:e.jsx(Me,{className:"py-12 text-center text-muted-foreground",children:"No submissions yet. Share your page to start collecting leads!"})}):e.jsx("div",{className:"space-y-3",children:f.map(te=>e.jsx(ve,{children:e.jsx(Me,{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:te.contact_name||"Anonymous"}),te.synced_to_crm&&e.jsx(Oe,{variant:"outline",className:"text-[10px]",children:"Synced"})]}),e.jsxs("div",{className:"text-sm text-muted-foreground mt-0.5",children:[te.contact_email&&e.jsx("span",{className:"mr-3",children:te.contact_email}),te.contact_phone&&e.jsx("span",{children:te.contact_phone})]}),te.answers&&typeof te.answers=="object"&&e.jsx("div",{className:"mt-2 text-sm space-y-1",children:Object.entries(te.answers).map(([ae,le])=>e.jsxs("div",{children:[e.jsxs("span",{className:"font-medium text-muted-foreground",children:[ae,":"]})," ",e.jsx("span",{children:String(le)})]},ae))})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(te.created_at).toLocaleDateString()})]})})},te.id))})}),e.jsxs(Gt,{value:"automation",className:"space-y-4 mt-4",children:[(u==null?void 0:u.page_type)==="event_registration"&&e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsx(St,{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(Me,{className:"grid gap-3 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5 md:col-span-2",children:[e.jsx(J,{children:"Starts at"}),e.jsx(xe,{type:"datetime-local",value:b.settings_event_starts_at,onChange:te=>j(ae=>({...ae,settings_event_starts_at:te.target.value}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Venue / location name"}),e.jsx(xe,{placeholder:"e.g. The Grand Hotel",value:b.settings_event_location_name,onChange:te=>j(ae=>({...ae,settings_event_location_name:te.target.value}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(J,{children:"Address (for map link)"}),e.jsx(xe,{placeholder:"123 Main St, City, ST",value:b.settings_event_address,onChange:te=>j(ae=>({...ae,settings_event_address:te.target.value}))})]})]})]}),e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsx(St,{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",g!=null&&g.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(Me,{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(J,{children:"Send auto-reply for this page"}),e.jsx(fn,{checked:!b.settings_disable_auto_responder,onCheckedChange:te=>j(ae=>({...ae,settings_disable_auto_responder:!te}))})]}),!b.settings_disable_auto_responder&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx(J,{children:"Subject (override)"}),e.jsx(xe,{value:b.settings_auto_responder_subject,onChange:te=>j(ae=>({...ae,settings_auto_responder_subject:te.target.value})),placeholder:(g==null?void 0:g.default_auto_responder_subject)||"Thanks for reaching out, {{client_first_name}}!"})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Body (override)"}),e.jsx(Ms,{rows:8,value:b.settings_auto_responder_body,onChange:te=>j(ae=>({...ae,settings_auto_responder_body:te.target.value})),placeholder:(g==null?void 0:g.default_auto_responder_body)||`Hi {{client_first_name}}, Thanks for reaching out…`})]})]})]})]}),e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsx(St,{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.",(g==null?void 0:g.default_drip_campaign_id)&&" Account default applies if no override is selected."]})]}),e.jsxs(Me,{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(J,{children:"Enroll new leads in a drip"}),e.jsx(fn,{checked:!b.settings_disable_drip,onCheckedChange:te=>j(ae=>({...ae,settings_disable_drip:!te}))})]}),!b.settings_disable_drip&&e.jsxs("div",{children:[e.jsx(J,{children:"Drip override for this page"}),e.jsxs("select",{className:"mt-1 w-full rounded-md border bg-background px-3 py-2 text-sm",value:b.settings_drip_campaign_id||"",onChange:te=>j(ae=>({...ae,settings_drip_campaign_id:te.target.value||null})),children:[e.jsx("option",{value:"",children:"— Use account default —"}),v.map(te=>e.jsx("option",{value:te.id,children:te.name},te.id))]})]})]})]}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"Redirect after submit"})}),e.jsxs(Me,{children:[e.jsx(xe,{value:b.settings_redirect_url,onChange:te=>j(ae=>({...ae,settings_redirect_url:te.target.value})),placeholder:(g==null?void 0:g.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(Gt,{value:"analytics",className:"space-y-4 mt-4",children:e.jsx(rvr,{pageId:s})}),e.jsxs(Gt,{value:"settings",className:"space-y-4 mt-4",children:[e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"Publishing"})}),e.jsxs(Me,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Published"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Make this page publicly accessible"})]}),e.jsx(fn,{checked:b.is_published,onCheckedChange:te=>j(ae=>({...ae,is_published:te}))})]}),b.is_published&&e.jsxs("div",{className:"p-3 bg-muted/50 rounded-lg border",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Public URL:"}),e.jsx("code",{className:"text-xs ml-2 break-all",children:Z})]})]})]}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{className:"text-base",children:"Thank You Message"})}),e.jsx(Me,{children:e.jsx(Ms,{value:b.success_message,onChange:te=>j(ae=>({...ae,success_message:te.target.value})),rows:2,placeholder:"Message shown after form submission"})})]})]})]})]}),e.jsx(Ls,{open:c,onOpenChange:d,children:e.jsxs(Ps,{className:"max-w-sm",children:[e.jsx(Os,{children:e.jsx(Ds,{children:"QR Code"})}),e.jsxs("div",{className:"flex flex-col items-center gap-4 py-4",children:[e.jsx(AN,{value:Z,size:240}),e.jsx("p",{className:"text-xs text-muted-foreground text-center break-all",children:Z})]})]})})]}):e.jsx(zs,{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(B,{variant:"link",onClick:()=>t("/mission-control/landing-pages"),children:"Go back"})]})})}const cvr={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},dvr=`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 uvr(){const s=ha(),{toast:t}=vi(),n=Fn(),r=Bt(),[a,i]=_.useState(cvr),{data:l}=at({queryKey:["landing-page-defaults",s],queryFn:async()=>{const{data:d}=await q.from("agent_landing_page_defaults").select("*").eq("user_id",s).maybeSingle();return d||null},enabled:!!s}),{data:o=[]}=at({queryKey:["drip-campaigns-mine",s],queryFn:async()=>{const{data:d}=await q.from("drip_campaigns").select("id, name").eq("owner_user_id",s).eq("is_active",!0).order("name");return d||[]},enabled:!!s});_.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=mt({mutationFn:async()=>{const{error:d}=await q.from("agent_landing_page_defaults").upsert({user_id:s,...a},{onConflict:"user_id"});if(d)throw d},onSuccess:()=>{r.invalidateQueries({queryKey:["landing-page-defaults"]}),t({title:"Defaults saved"})},onError:d=>t({title:"Save failed",description:d.message,variant:"destructive"})});return e.jsx(zs,{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(B,{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(B,{onClick:()=>c.mutate(),disabled:c.isPending,children:[e.jsx(Ho,{className:"h-4 w-4 mr-2"})," ",c.isPending?"Saving…":"Save Defaults"]})]}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Landing Page Defaults"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"These run on every landing page automatically. Any page can override them in its own settings."})]}),e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsx(St,{children:"Instant auto-reply to the lead"}),e.jsxs(kn,{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(Me,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Subject"}),e.jsx(xe,{value:a.default_auto_responder_subject||"",onChange:d=>i(u=>({...u,default_auto_responder_subject:d.target.value})),placeholder:"Thanks for reaching out, {{client_first_name}}!"})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Message body"}),e.jsx(Ms,{rows:10,value:a.default_auto_responder_body||"",onChange:d=>i(u=>({...u,default_auto_responder_body:d.target.value})),placeholder:dvr}),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(ve,{children:[e.jsxs(bt,{children:[e.jsx(St,{children:"Default Smart Drip"}),e.jsx(kn,{children:"Every new lead drops into this drip unless a page overrides it."})]}),e.jsx(Me,{children:e.jsxs(is,{value:a.default_drip_campaign_id||"none",onValueChange:d=>i(u=>({...u,default_drip_campaign_id:d==="none"?null:d})),children:[e.jsx(rs,{children:e.jsx(ls,{placeholder:"Pick a drip…"})}),e.jsxs(as,{children:[e.jsx(He,{value:"none",children:"— No default drip —"}),o.map(d=>e.jsx(He,{value:d.id,children:d.name},d.id))]})]})})]}),e.jsxs(ve,{children:[e.jsx(bt,{children:e.jsx(St,{children:"Defaults for every page"})}),e.jsxs(Me,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(J,{children:"Default booking / calendar link"}),e.jsx(xe,{value:a.default_calendar_link||"",onChange:d=>i(u=>({...u,default_calendar_link:d.target.value})),placeholder:"https://calendly.com/your-name/intro"})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Default redirect after submit (optional)"}),e.jsx(xe,{value:a.default_redirect_url||"",onChange:d=>i(u=>({...u,default_redirect_url:d.target.value})),placeholder:"https://your-site.com/thanks"})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(J,{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(fn,{checked:a.use_brand_kit,onCheckedChange:d=>i(u=>({...u,use_brand_kit:d}))})]})]})]}),e.jsxs(ve,{children:[e.jsxs(bt,{children:[e.jsx(St,{children:"Text me when a lead submits"}),e.jsx(kn,{children:"Get an SMS the second a lead hits your inbox. Coming soon — requires SMS sender setup."})]}),e.jsxs(Me,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsx(J,{className:"text-base",children:"SMS me new leads"}),e.jsx(fn,{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(J,{children:"Phone number for alerts"}),e.jsx(xe,{type:"tel",value:a.agent_sms_phone||"",onChange:d=>i(u=>({...u,agent_sms_phone:d.target.value})),placeholder:"(555) 123-4567"})]})]})]})]})})}function pls({hasLeadSite:s}){const t=Fn(),n=Bt(),[r,a]=_.useState(!1),{offer:i}=vPe(!s);if(s||!i)return null;const l=async()=>{a(!0);try{const{data:o,error:c}=await q.functions.invoke("claim-free-lead-site",{body:{}});if(c)throw c;if(o!=null&&o.error)throw new Error(o.error);await n.invalidateQueries({queryKey:["agent-lead-site"]}),se.success("Your website is live! Let’s make it yours."),t(`/admin/lead-sites/${o.siteId}/edit`)}catch(o){se.error((o==null?void 0:o.message)||"Could not create your website")}finally{a(!1)}};return e.jsx(ve,{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($f,{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(un,{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(B,{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(wr,{className:"w-3 h-3"})]})]})]})]})})}function hvr(){return at({queryKey:["website-apps"],queryFn:async()=>{const{data:s,error:t}=await q.from("website_apps").select("*").order("sort_order",{ascending:!0});if(t)throw t;return s||[]}})}function bDe(){const{user:s}=hs();return at({queryKey:["agent-website-app-installs",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return[];const{data:t,error:n}=await q.from("agent_website_app_installs").select("*").eq("user_id",s.id);if(n)throw n;return t||[]},enabled:!!(s!=null&&s.id)})}function _De(){const{user:s}=hs(),t=Bt();return mt({mutationFn:async({app_slug:n,enabled:r})=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{error:a}=await q.from("agent_website_app_installs").upsert({user_id:s.id,app_slug:n,enabled:r},{onConflict:"user_id,app_slug"});if(a)throw a},onSuccess:(n,r)=>{t.invalidateQueries({queryKey:["agent-website-app-installs"]}),se.success(r.enabled?"App installed":"App turned off")},onError:n=>se.error(n.message||"Failed to update app")})}const mvr={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"}},pvr={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 fvr(){const s=Fn(),{data:t=[],isLoading:n}=hvr(),{data:r=[]}=bDe(),{hasLeadSite:a,siteUrl:i,isLoading:l}=lf(),o=_De(),[c,d]=_.useState(!1),u=m=>{var p;return((p=r.find(f=>f.app_slug===m))==null?void 0:p.enabled)??!1},h=m=>r.some(p=>p.app_slug===m);return e.jsxs(zs,{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(nf,{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(un,{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(B,{onClick:()=>d(!0),className:"mt-5 bg-white text-indigo-700 hover:bg-white/90 shadow-lg font-semibold gap-2",children:[e.jsx(om,{className:"w-5 h-5"}),"Watch: How to use Website Apps"]})]})]}),e.jsx(pls,{hasLeadSite:a}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(ve,{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(sl,{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(Oe,{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(wr,{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(wr,{className:"w-3 h-3"})]})," ","to learn more — apps install automatically once you have one."]})]})]})}),e.jsx(ve,{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(Y3,{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=jMe[m.icon||"Sparkles"]||un,f=u(m.slug),y=h(m.slug),v=m.status==="coming_soon",g=mvr[m.slug]||pvr;return e.jsxs(ve,{className:`group relative overflow-hidden border-0 ring-1 ring-border ${g.ring} hover:ring-2 transition-all hover:shadow-xl ${v?"opacity-70":""}`,children:[e.jsx("div",{className:`h-1.5 w-full bg-gradient-to-r ${g.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 ${g.iconBg} ${g.iconText} flex items-center justify-center shadow-md group-hover:scale-105 transition-transform`,children:e.jsx(p,{className:"w-7 h-7"})}),v?e.jsx(Oe,{variant:"secondary",children:"Coming soon"}):f?e.jsxs(Oe,{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"]}):y?e.jsx(Oe,{variant:"outline",children:"Paused"}):e.jsx(Oe,{className:g.chip+" hover:"+g.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})]}),!v&&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(fn,{checked:f,onCheckedChange:b=>o.mutate({app_slug:m.slug,enabled:b})}),e.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:f?"On":"Off"})]}),e.jsxs(B,{size:"sm",className:`bg-gradient-to-r ${g.gradient} text-white hover:opacity-90 shadow-md border-0`,onClick:()=>s(`/website-apps/${m.slug}`),children:[e.jsx(qc,{className:"w-3.5 h-3.5 mr-1.5"}),"Configure",e.jsx(La,{className:"w-3.5 h-3.5 ml-1"})]})]})]})]},m.id)})})]}),e.jsx(Ls,{open:c,onOpenChange:d,children:e.jsxs(Ps,{className:"max-w-4xl p-0 overflow-hidden bg-black border-0",children:[e.jsx(Os,{className:"px-5 pt-4 pb-2 bg-background",children:e.jsx(Ds,{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 xvr(){const{leadSite:s,hasLeadSite:t,isLoading:n}=lf(),{hasOffer:r,isLoading:a}=vPe(!t);return t&&s?e.jsx(fd,{to:`/my-website/${s.id}/edit`,replace:!0}):e.jsx(zs,{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(pls,{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 RUe={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 gvr(){const{user:s}=hs();return at({queryKey:["video-greeter-config",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return RUe;const{data:t,error:n}=await q.from("video_greeter_configs").select("*").eq("user_id",s.id).maybeSingle();if(n)throw n;return t?{...RUe,...t}:RUe},enabled:!!(s!=null&&s.id)})}function yvr(){const{user:s}=hs(),t=Bt();return mt({mutationFn:async n=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{error:r}=await q.from("video_greeter_configs").upsert({user_id:s.id,...n},{onConflict:"user_id"});if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["video-greeter-config"]}),se.success("Saved")},onError:n=>se.error(n.message||"Failed to save")})}function vvr({label:s,value:t,onChange:n,thumbnailUrl:r,placeholder:a="https://...",hint:i}){const l=_.useRef(null),[o,c]=_.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/")){se.error("Please select a video file");return}if(h.size>50*1024*1024){se.error("Video must be under 50MB");return}c(!0);try{const p=h.name.split(".").pop()||"mp4",f=`lead-site/videos/${Date.now()}-${Math.random().toString(36).slice(2,6)}.${p}`,{error:y}=await q.storage.from("agent-uploads").upload(f,h,{upsert:!0});if(y)throw y;const{data:{publicUrl:v}}=q.storage.from("agent-uploads").getPublicUrl(f);n(v),se.success("Video uploaded!")}catch(p){se.error(p.message||"Upload failed")}finally{c(!1),l.current&&(l.current.value="")}}};return e.jsxs("div",{children:[e.jsx(J,{children:s}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{value:t,onChange:u=>n(u.target.value),placeholder:a,className:"flex-1"}),e.jsxs(B,{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(Ct,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Oa,{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}):yq(t)?e.jsx(vZe,{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(B,{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(Qn,{className:"h-3 w-3"})})]})})()]})}const bvr=[{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 _vr({onVideoReady:s}){const[t,n]=_.useState(!1),[r,a]=_.useState("script"),[i,l]=_.useState(""),[o,c]=_.useState(!0),[d,u]=_.useState(!1),[h,m]=_.useState(0),[p,f]=_.useState(0),y=TC(),v=()=>{a("script"),l(""),m(0),f(0),c(!0)},g=j=>{!j&&(r==="uploading"||r==="processing")||(n(j),j||v())},b=_.useCallback(async(j,S)=>{a("uploading");try{const C="Video Greeter",{videoId:E,libraryId:P}=await PL(C),{uploadUrl:M,apiKey:I}=await LL(E),D=new XMLHttpRequest;D.upload.onprogress=ce=>{ce.lengthComputable&&m(ce.loaded/ce.total*100)},await new Promise((ce,ie)=>{D.onload=()=>D.status>=200&&D.status<300?ce():ie(new Error("Upload failed")),D.onerror=()=>ie(new Error("Upload failed")),D.open("PUT",M),D.setRequestHeader("AccessKey",I),D.send(j)}),a("processing");let O=0;const V=Date.now(),G=9e4,$=`https://iframe.mediadelivery.net/embed/${P}/${E}`,H=`https://iframe.mediadelivery.net/play/${P}/${E}`;for(;O<4;){if(await new Promise(ie=>setTimeout(ie,3e3)),Date.now()-V>G){const ie=j.size/1048576,te=await y.mutateAsync({bunny_video_id:E,playback_url:H,file_size_mb:ie,title:C,status:"processing",touch_type:"video"});s({videoId:(te==null?void 0:te.id)||E,playbackUrl:$,thumbnailUrl:null}),se.success("Video saved — still encoding. Will be ready shortly."),a("done"),setTimeout(()=>{n(!1),v()},1500);return}const ce=await TN(E);if(O=ce.status,f(ce.encodeProgress||0),O===5||O===6)throw new Error("Video processing failed")}const Y=await TN(E),Z=(Y.storageSize||j.size)/(1024*1024),ne=await y.mutateAsync({bunny_video_id:E,playback_url:Y.directPlayUrl||$,thumbnail_url:Y.thumbnailUrl,preview_url:Y.previewUrl||null,duration_seconds:Y.length||S,file_size_mb:Z,title:C,status:"ready",touch_type:"video"});s({videoId:(ne==null?void 0:ne.id)||E,playbackUrl:Y.directPlayUrl||$,thumbnailUrl:Y.thumbnailUrl||null}),se.success("Video recorded & added to your library!"),a("done"),setTimeout(()=>{n(!1),v()},1500)}catch(C){console.error(C),se.error("Failed to process video. Please try again."),a("record")}},[y,s]);return e.jsxs(Ls,{open:t,onOpenChange:g,children:[e.jsx(nl,{asChild:!0,children:e.jsxs(B,{variant:"default",size:"sm",className:"gap-1.5",children:[e.jsx(Kr,{className:"h-4 w-4"}),"Record now"]})}),e.jsxs(Ps,{className:"sm:max-w-3xl max-h-[92vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsxs(Ds,{className:"flex items-center gap-2",children:[e.jsx(un,{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(Ji,{className:"h-[280px] pr-3",children:e.jsx("div",{className:"grid sm:grid-cols-2 gap-3",children:bvr.map(j=>e.jsxs(ve,{className:"p-3 cursor-pointer hover:border-primary transition-colors",onClick:()=>l(j.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:j.title}),e.jsx(Oe,{variant:"outline",className:"text-[10px] shrink-0",children:j.duration})]}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2",children:j.description})]},j.id))})})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-sm mb-1",children:"2. Edit your script"}),e.jsx(Ms,{rows:5,value:i,onChange:j=>l(j.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(B,{variant:"ghost",onClick:()=>{l(""),a("record")},children:"Skip — freestyle"}),e.jsxs(B,{onClick:()=>a("record"),children:[e.jsx(Fr,{className:"h-4 w-4 mr-1.5"})," Continue to recorder"]})]})]}),r==="record"&&e.jsxs("div",{className:"space-y-3",children:[e.jsx($E,{maxDurationSeconds:60,onRecordingComplete:b,onRecordingStateChange:u,onError:j=>se.error(j),teleprompterContent:o&&i?e.jsx(aat,{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(B,{variant:"ghost",size:"sm",onClick:()=>a("script"),children:"← Back to script"}),i&&!o&&e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>c(!0),children:[e.jsx(Fr,{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(Ct,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Uploading video..."}),e.jsx(Fi,{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(Ct,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Processing video..."}),e.jsx(Fi,{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(_l,{className:"h-12 w-12 text-emerald-500"}),e.jsx("p",{className:"text-sm font-medium",children:"Video attached to your greeter!"})]})]})]})}function wvr(){var S;const s=Fn(),{user:t}=hs(),{leadSite:n}=lf(),{data:r}=gvr(),a=yvr(),{data:i=[]}=bDe(),l=_De(),[o,c]=_.useState(null),[d,u]=_.useState({impressions:0,expands:0,ctaClicks:0,leads:0});if(_.useEffect(()=>{r&&!o&&c(r)},[r,o]),_.useEffect(()=>{t!=null&&t.id&&q.from("widget_events").select("event_type",{count:"exact"}).eq("user_id",t.id).eq("app_slug","video_greeter").then(({data:C})=>{const E=C||[];u({impressions:E.filter(P=>P.event_type==="impression").length,expands:E.filter(P=>P.event_type==="expand").length,ctaClicks:E.filter(P=>P.event_type==="cta_click").length,leads:E.filter(P=>P.event_type==="lead_capture").length})})},[t==null?void 0:t.id]),!o)return e.jsx(zs,{title:"Video Greeter",children:e.jsx("div",{className:"p-8 text-sm text-muted-foreground",children:"Loading..."})});const h=((S=i.find(C=>C.app_slug==="video_greeter"))==null?void 0:S.enabled)??!1,m=C=>c({...o,...C}),p=C=>m({ctas:C}),f=()=>p([...o.ctas||[],{id:crypto.randomUUID(),label:"New Button",url:"https://",style:"primary"}]),y=C=>p((o.ctas||[]).filter(E=>E.id!==C)),v=(C,E)=>p((o.ctas||[]).map(P=>P.id===C?{...P,...E}:P)),g=()=>a.mutate(o),b=(n==null?void 0:n.subdomain_slug)||(t==null?void 0:t.id)||"",j=`